Add printing functions for models to ease debugging
[centaur.git] / src / printing / segments.c
1 #include <stdio.h>
2
3 #include <libelf/libelf.h>
4 #include <libelf/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     GElf_Shdr shdr;
30
31     if (gelf_getshdr(scn, &shdr) != &shdr) {
32       fprintf(stderr, "gelf_getshdr() failed: %s\n", elf_errmsg(-1));
33       continue;
34     }
35
36     if (PHDR_CONTAINS_SCN_IN_MEMORY(phdr, &shdr)) {
37       printf("       %10u %s\n", elf_ndxscn(scn), elfu_eScnName(e, scn));
38     }
39
40     scn = elf_nextscn(e, scn);
41   }
42 }
43
44
45 void printSegments(Elf *e)
46 {
47   size_t i, n;
48
49   if (elf_getphdrnum(e, &n)) {
50     fprintf(stderr, "elf_getphdrnum() failed: %s.", elf_errmsg(-1));
51   }
52
53   printf("Segments:\n");
54   printf("      #   typeStr     type   offset    vaddr    paddr   filesz    memsz    flags    align\n");
55
56   for (i = 0; i < n; i++) {
57     GElf_Phdr phdr;
58
59     if (gelf_getphdr(e, i, &phdr) != &phdr) {
60       fprintf(stderr, "getphdr() failed for #%d: %s.", i, elf_errmsg(-1));
61       continue;
62     }
63
64     printf(" * %4d: %8s ", i, segmentTypeStr(phdr.p_type));
65
66     printf("%8jx %8jx %8jx %8jx %8jx %8jx %8jx %8jx\n",
67             (uintmax_t) phdr.p_type,
68             (uintmax_t) phdr.p_offset,
69             (uintmax_t) phdr.p_vaddr,
70             (uintmax_t) phdr.p_paddr,
71             (uintmax_t) phdr.p_filesz,
72             (uintmax_t) phdr.p_memsz,
73             (uintmax_t) phdr.p_flags,
74             (uintmax_t) phdr.p_align);
75
76     printSectionsInSegment(e, &phdr);
77   }
78
79   printf("\n");
80 }