3 #include <libelfu/libelfu.h>
8 void* elfu_mScnForall(ElfuElf *me, SectionHandlerFunc f, void *aux1, void *aux2)
13 // TODO: Sort PHDRs by offset before interating
15 CIRCLEQ_FOREACH(mp, &me->phdrList, elem) {
16 if (mp->phdr.p_type != PT_LOAD) {
20 CIRCLEQ_FOREACH(ms, &mp->childScnList, elemChildScn) {
21 void *rv = f(me, ms, aux1, aux2);
29 CIRCLEQ_FOREACH(ms, &me->orphanScnList, elemChildScn) {
30 void *rv = f(me, ms, aux1, aux2);
45 static void* subCounter(ElfuElf *me, ElfuScn *ms, void *aux1, void *aux2)
47 size_t *i = (size_t*)aux1;
48 ElfuScn *otherScn = (ElfuScn*)aux2;
61 size_t elfu_mScnCount(ElfuElf *me)
63 /* NULL section *is not* counted */
68 elfu_mScnForall(me, subCounter, &i, NULL);
74 /* Returns the index a section would have in the flattened ELF */
75 size_t elfu_mScnIndex(ElfuElf *me, ElfuScn *ms)
77 /* NULL section *is* counted */
83 elfu_mScnForall(me, subCounter, &i, ms);
85 /* If this assertion is broken then ms is not a section in me. */
86 assert(i <= elfu_mScnCount(me));
91 static void* subOldscn(ElfuElf *me, ElfuScn *ms, void *aux1, void *aux2)
93 ElfuScn *otherScn = (ElfuScn*)aux1;
96 if (ms->oldptr == otherScn) {
104 /* Returns the section with oldscn == oldscn */
105 ElfuScn* elfu_mScnByOldscn(ElfuElf *me, ElfuScn *oldscn)
110 return elfu_mScnForall(me, subOldscn, oldscn, NULL);
118 char* elfu_mScnName(ElfuElf *me, ElfuScn *ms)
127 if (!me->shstrtab->data.d_buf) {
131 return &((char*)me->shstrtab->data.d_buf)[ms->shdr.sh_name];
135 static void* subScnsToArray(ElfuElf *me, ElfuScn *ms, void *aux1, void *aux2)
137 ElfuScn **arr = (ElfuScn**)aux1;
138 size_t *i = (size_t*)aux2;
147 static int cmpScnOffs(const void *ms1, const void *ms2)
155 s1 = *(ElfuScn**)ms1;
156 s2 = *(ElfuScn**)ms2;
162 if (s1->shdr.sh_offset < s2->shdr.sh_offset) {
164 } else if (s1->shdr.sh_offset == s2->shdr.sh_offset) {
166 } else /* if (s1->shdr.sh_offset > s2->shdr.sh_offset) */ {
171 ElfuScn** elfu_mScnSortedByOffset(ElfuElf *me, size_t *count)
174 ElfuScn **sortedSecs;
179 /* Sort sections by offset in file */
180 numSecs = elfu_mScnCount(me);
181 sortedSecs = malloc(numSecs * sizeof(*sortedSecs));
183 ELFU_WARN("elfu_mScnSortedByOffset: Failed to allocate memory.\n");
188 elfu_mScnForall(me, subScnsToArray, sortedSecs, &i);
189 assert(i == numSecs);
191 qsort(sortedSecs, numSecs, sizeof(*sortedSecs), cmpScnOffs);