/*
** ctors.c for libelfsh
** 
** Started on  Tue Feb 26 22:11:12 2002 mayhem
** Last update Mon Mar 25 10:30:12 2002 mayhem
*/
#include "libelfsh.h"



/* Read the constructor array in .ctors */
void		*elfsh_get_ctors(Elfsh32_Obj *file, int *num)
{
  Elfsh32_Sect	*new;

  new = elfsh_get_section_by_name(file, ELFSH_SECTION_NAME_CTORS, NULL, NULL, NULL);
  if (!new)
    ELFSH_SETERROR("libelfsh: Cant retreive .ctors . \n", NULL);

  new->nbr = new->shdr->sh_size / 4;

  new->data = elfsh_load_section(file, new->shdr);
  if (!new->data)
    return (NULL);

  file->ctors = new;
  if (num)
    *num = new->nbr;

  return (new->data);
}



/* Modify a CTORS entry using its index */
int		elfsh_set_ctors_entry_by_index(Elfsh32_Obj *file, int index, int new_addr)
{
  int		nbr;
  int		*ctors;
  
  ctors = elfsh_get_ctors(file, &nbr);
  if (!ctors)
    return (-1);
  if (index >= file->ctors->nbr)
    ELFSH_SETERROR("libelfsh: index too big . \n", -1);
  ctors[index] = new_addr;
  return (0);
}



/* Modify a CTORS entry using its name */
int		elfsh_set_ctors_entry_by_name(Elfsh32_Obj *file, char *name, int new_addr)
{
  int		nbr;
  int		*ctors;
  Elf32_Sym	*sym;
  int		index;

  ctors = elfsh_get_ctors(file, &nbr);
  if (!ctors)
    return (-1);

  sym = elfsh_get_symbol_by_name(file, name);
  if (!sym)
    return (-1);

  for (index = 0; index < nbr; index++)
    if (ctors[index] == sym->st_value)
      {
	ctors[index] = new_addr;
	return (0);
      }
  
  ELFSH_SETERROR("libelfsh: Cant find ctors entry for this symbol . \n", -1);
}





