Print ELF header/segments/sections
[centaur.git] / src / lookup / last-section-in-segment.c
1 #include <libelf.h>
2 #include <gelf.h>
3
4 #include <libelfu/libelfu.h>
5
6
7 /*
8  * Returns the first section that  is contained in the segment and
9  * ends as close to its memory image of as possible (the "last"
10  * section in the segment).
11  *
12  * If no section fits, NULL is returned.
13  */
14 Elf_Scn* elfu_lastSectionInSegment(Elf *e, GElf_Phdr *phdr)
15 {
16   Elf_Scn *last = NULL;
17   Elf_Scn *scn;
18
19
20   scn = elf_getscn(e, 1);
21   while (scn) {
22     if (elfu_segmentContainsSection(phdr, scn) == ELFU_TRUE) {
23       if (!last) {
24         last = scn;
25       } else {
26         GElf_Shdr shdrOld;
27         GElf_Shdr shdrNew;
28
29         if (gelf_getshdr(last, &shdrOld) != &shdrOld) {
30           continue;
31         }
32
33         if (gelf_getshdr(scn, &shdrNew) != &shdrNew) {
34           continue;
35         }
36
37         if (shdrNew.sh_offset + shdrNew.sh_size
38             > shdrOld.sh_offset + shdrOld.sh_size) {
39           // TODO: Check (leftover space in memory image) < (p_align)
40           last = scn;
41         }
42       }
43     }
44
45     scn = elf_nextscn(e, scn);
46   }
47
48   return last;
49 }