3 #include <libelf/libelf.h>
4 #include <libelf/gelf.h>
5 #include <libelfu/libelfu.h>
10 int elfu_mScnForall(ElfuElf *me, SectionHandlerFunc f, void *aux1, void *aux2)
15 // TODO: Sort PHDRs by offset before interating
17 CIRCLEQ_FOREACH(mp, &me->phdrList, elem) {
18 if (mp->phdr.p_type != PT_LOAD) {
22 CIRCLEQ_FOREACH(ms, &mp->childScnList, elemChildScn) {
23 int rv = f(me, ms, aux1, aux2);
31 CIRCLEQ_FOREACH(ms, &me->orphanScnList, elemChildScn) {
32 int rv = f(me, ms, aux1, aux2);
47 static int subCounter(ElfuElf *me, ElfuScn *ms, void *aux1, void *aux2)
49 size_t *i = (size_t*)aux1;
50 ElfuScn *otherScn = (ElfuScn*)aux2;
62 size_t elfu_mScnCount(ElfuElf *me)
64 /* NULL section *is not* counted */
69 elfu_mScnForall(me, subCounter, &i, NULL);
75 /* Returns the section index equivalent to the model flattened to ELF */
76 size_t elfu_mScnIndex(ElfuElf *me, ElfuScn *ms)
78 /* NULL section *is* counted */
84 elfu_mScnForall(me, subCounter, &i, ms);
86 /* If this assertion is broken then ms is not a section in me. */
87 assert(i <= elfu_mScnCount(me));
96 char* elfu_mScnName(ElfuElf *me, ElfuScn *ms)
105 if (!me->shstrtab->data.d_buf) {
109 return &((char*)me->shstrtab->data.d_buf)[ms->shdr.sh_name];
113 static int subScnsToArray(ElfuElf *me, ElfuScn *ms, void *aux1, void *aux2)
115 ElfuScn **arr = (ElfuScn**)aux1;
116 size_t *i = (size_t*)aux2;
124 static int cmpScnOffs(const void *ms1, const void *ms2)
129 ElfuScn *s1 = *(ElfuScn**)ms1;
130 ElfuScn *s2 = *(ElfuScn**)ms2;
136 if (s1->shdr.sh_offset < s2->shdr.sh_offset) {
138 } else if (s1->shdr.sh_offset == s2->shdr.sh_offset) {
140 } else /* if (s1->shdr.sh_offset > s2->shdr.sh_offset) */ {
145 ElfuScn** elfu_mScnSortedByOffset(ElfuElf *me, size_t *count)
150 ElfuScn **sortedSecs;
153 /* Sort sections by offset in file */
154 numSecs = elfu_mScnCount(me);
155 sortedSecs = malloc(numSecs * sizeof(*sortedSecs));
157 ELFU_WARN("elfu_mScnSortedByOffset: Failed to allocate memory.\n");
162 elfu_mScnForall(me, subScnsToArray, sortedSecs, &i);
163 assert(i == numSecs);
165 qsort(sortedSecs, numSecs, sizeof(*sortedSecs), cmpScnOffs);