3 #include <libelfu/libelfu.h>
8 int 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 int rv = f(me, ms, aux1, aux2);
29 CIRCLEQ_FOREACH(ms, &me->orphanScnList, elemChildScn) {
30 int rv = f(me, ms, aux1, aux2);
45 static int subCounter(ElfuElf *me, ElfuScn *ms, void *aux1, void *aux2)
47 size_t *i = (size_t*)aux1;
48 ElfuScn *otherScn = (ElfuScn*)aux2;
60 size_t elfu_mScnCount(ElfuElf *me)
62 /* NULL section *is not* counted */
67 elfu_mScnForall(me, subCounter, &i, NULL);
73 /* Returns the section index equivalent to the model flattened to ELF */
74 size_t elfu_mScnIndex(ElfuElf *me, ElfuScn *ms)
76 /* NULL section *is* counted */
82 elfu_mScnForall(me, subCounter, &i, ms);
84 /* If this assertion is broken then ms is not a section in me. */
85 assert(i <= elfu_mScnCount(me));
94 char* elfu_mScnName(ElfuElf *me, ElfuScn *ms)
103 if (!me->shstrtab->data.d_buf) {
107 return &((char*)me->shstrtab->data.d_buf)[ms->shdr.sh_name];
111 static int subScnsToArray(ElfuElf *me, ElfuScn *ms, void *aux1, void *aux2)
113 ElfuScn **arr = (ElfuScn**)aux1;
114 size_t *i = (size_t*)aux2;
122 static int cmpScnOffs(const void *ms1, const void *ms2)
127 ElfuScn *s1 = *(ElfuScn**)ms1;
128 ElfuScn *s2 = *(ElfuScn**)ms2;
134 if (s1->shdr.sh_offset < s2->shdr.sh_offset) {
136 } else if (s1->shdr.sh_offset == s2->shdr.sh_offset) {
138 } else /* if (s1->shdr.sh_offset > s2->shdr.sh_offset) */ {
143 ElfuScn** elfu_mScnSortedByOffset(ElfuElf *me, size_t *count)
148 ElfuScn **sortedSecs;
151 /* Sort sections by offset in file */
152 numSecs = elfu_mScnCount(me);
153 sortedSecs = malloc(numSecs * sizeof(*sortedSecs));
155 ELFU_WARN("elfu_mScnSortedByOffset: Failed to allocate memory.\n");
160 elfu_mScnForall(me, subScnsToArray, sortedSecs, &i);
161 assert(i == numSecs);
163 qsort(sortedSecs, numSecs, sizeof(*sortedSecs), cmpScnOffs);