Print ELF header/segments/sections
[centaur.git] / src / printing / segments.c
1 #include <stdio.h>
2
3 #include <libelf.h>
4 #include <gelf.h>
5
6 #include <libelfu/libelfu.h>
7
8
9 static char *ptstr[] = {"NULL", "LOAD", "DYNAMIC", "INTERP", "NOTE", "SHLIB", "PHDR", "TLS", "NUM"};
10
11
12 char* segmentTypeStr(size_t pt)
13 {
14   if (pt >= 0 && pt <= PT_NUM) {
15     return ptstr[pt];
16   }
17
18   return "-?-";
19 }
20
21
22 void printSectionsInSegment(Elf *e, GElf_Phdr *phdr)
23 {
24   Elf_Scn *scn;
25
26   scn = elf_getscn(e, 0);
27
28   while (scn) {
29     ELFU_BOOL isInSeg;
30
31     isInSeg = elfu_segmentContainsSection(phdr, scn);
32     if (isInSeg == ELFU_TRUE) {
33       printf("       %10u %s\n", elf_ndxscn(scn), elfu_sectionName(e, scn));
34     }
35
36     scn = elf_nextscn(e, scn);
37   }
38 }
39
40
41 void printSegments(Elf *e)
42 {
43   size_t i, n;
44
45   if (elf_getphdrnum(e, &n)) {
46     fprintf(stderr, "elf_getphdrnum() failed: %s.", elf_errmsg(-1));
47   }
48
49   printf("Segments:\n");
50   printf("      #   typeStr     type   offset    vaddr    paddr   filesz    memsz    flags    align\n");
51
52   for (i = 0; i < n; i++) {
53     GElf_Phdr phdr;
54
55     if (gelf_getphdr(e, i, &phdr) != &phdr) {
56       fprintf(stderr, "getphdr() failed for #%d: %s.", i, elf_errmsg(-1));
57       continue;
58     }
59
60     printf(" * %4d: %8s ", i, segmentTypeStr(phdr.p_type));
61
62     printf("%8jx %8jx %8jx %8jx %8jx %8jx %8jx %8jx\n",
63             (uintmax_t) phdr.p_type,
64             (uintmax_t) phdr.p_offset,
65             (uintmax_t) phdr.p_vaddr,
66             (uintmax_t) phdr.p_paddr,
67             (uintmax_t) phdr.p_filesz,
68             (uintmax_t) phdr.p_memsz,
69             (uintmax_t) phdr.p_flags,
70             (uintmax_t) phdr.p_align);
71
72     printSectionsInSegment(e, &phdr);
73   }
74
75   printf("\n");
76 }