/*
** pht.c for elfsh
** 
** Started on  Fri Nov  2 15:18:35 2001 mayhem
** Last update Sun May 12 14:21:55 2002 mayhem
*/
#include "elfsh.h"




/* Display the program header table (pht) */
int		display_pht(Elfsh32_Obj *file, argv_t *av)
{
  Elf32_Phdr	*phdr;
  Elf32_Shdr	*shdr;
  int		num;
  int		shtnum;
  int		index;
  int		index2;
  char		*type;
  u_int		typenum;
  Elfsh32_Sect	*list;

  if ((phdr = elfsh_get_pht(file, &num)) == 0)
    RET(-1);
  
  printf("\n\n [Program header table (PHT) for object %s] \n\n", file->name);

  /* Primary view */
  for (index = 0; index < num; index++)
    {
      
      typenum = elfsh_get_segment_type(phdr + index);
      type = (typenum >= SEGTYPE_MAX ? "Unknown" : elfsh_seg_type[typenum]);
      
      printf(" [%02u] %-10p -> %-10p %c%c%c memsz(%07u) fileoff(%08u) filesz(%07u) align(%04u) => %s\n",
	     index, (void *) phdr[index].p_vaddr,
	     (void *) phdr[index].p_vaddr + phdr[index].p_memsz,
	     (elfsh_segment_is_readable(&phdr[index])   ? 'r' : '-'),
	     (elfsh_segment_is_writable(&phdr[index])   ? 'w' : '-'),
	     (elfsh_segment_is_executable(&phdr[index]) ? 'x' : '-'),
	     phdr[index].p_memsz,
	     phdr[index].p_offset,
	     phdr[index].p_filesz,
	     phdr[index].p_align,
	     type);
    }


  printf("\n\n [Program header table (PHT) for object %s : Linking perspective] \n", file->name);

  /* Retreive the sht */
  if ((shdr = elfsh_get_sht(file, &shtnum)) == 0)
    RET(-1);

  puts("");

  /* ALternate View */
  for (index = 0; index < num; index++, index2 = 0)
    {
      typenum = elfsh_get_segment_type(phdr + index);
      type = (typenum >= SEGTYPE_MAX ? "Unknown" : elfsh_seg_type_short[typenum]);
      printf(" [%02u] {%s} \t", index, type);
      fflush(stdout);
      
      for (index2 = 0, list = file->sections; list; list = list->next)
	if (elfsh_segment_is_parent(list, phdr + index))
	  {
	    index2++;
	    printf("%s%s ", 
		   (list->shdr->sh_offset + list->shdr->sh_size > phdr[index].p_offset + phdr[index].p_filesz ? 
		    "|" : ""),
		   elfsh_get_section_name(file, list->shdr));
	    fflush(stdout);
	  }
      puts("");
    }


  puts("");
  return (0);
}
