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