/*
** notes.c for libelfsh
** 
** Started on  Sun Jun 10 22:57:09 2001 mayhem
** Last update Sun Mar 10 01:07:18 2002 mayhem
*/
#include "libelfsh.h"




/* Return the content of the 'range'th section of type SHT_NOTE */
Elfsh32_Sect		*elfsh_get_notes(Elfsh32_Obj *file, u_int range, char *name)
{
  Elfsh32_Sect		*notes;
  Elfsh32_Note_ent	*e;
  Elfsh32_Note_ent	*tmp;	
  int			offset;
  int			size;

  notes = elfsh_get_section_by_type(file, SHT_NOTE, NULL, NULL, &size, range);
  if (!notes)
    return (NULL);

  notes->nbr = size;
  if ((notes->data = elfsh_load_section(file, notes->shdr)) == NULL)
    return (NULL);
  
  /* Parse all the note entries of the section */
  for (offset = 0; offset < size; offset += (e->namesz + e->descsz + sizeof(int) * 3))
    {
      
      XALLOC(e, sizeof(Elfsh32_Note_ent), NULL);
      
      e->namesz    = * (int *) notes->data;
      e->namesz   += e->namesz % 4;
      e->descsz    = * (int *) notes->data + 1;
      e->descsz   += e->descsz % 4;
      e->note      = strdup((char *) notes->data + offset + sizeof(int) * 3);
      e->desc      = strdup((char *) notes->data + offset + sizeof(int) * 3 + e->namesz);
      
      /* Put the note entry at the end of the list */
      if (!notes->altdata)
	notes->altdata = e;
      else
	{
	  tmp = notes->altdata;
	  while (tmp->next)
	    tmp = tmp->next;
	  tmp->next = e;
	  e->prev = tmp;
	}
      notes->altnbr++;
      
    }
  
  return (notes);
  
}








/* Free the notes section linked list */
void			elfsh_free_notes(Elfsh32_Obj *file)
{
  Elfsh32_Note_ent	*e;
  Elfsh32_Note_ent	*etmp;
  Elfsh32_Sect		*sect;

  for (sect = file->sections; sect; sect = sect->next)
    if (sect->data && sect->shdr->sh_type == SHT_NOTE)
      {
	free(sect->data);
	for (e = sect->altdata; e; e = etmp)
	  {
	    etmp = e->next;
	    free(e->note);
	    free(e->desc);
	    free(e);
	  }
      }

}









