6 #include <libelfu/libelfu.h>
9 void elfu_mExpandNobits(ElfuElf *me, GElf_Off off)
13 GElf_Xword expansionSize;
19 /* Find the maximum amount we need to expand by. Check PHDRs first */
20 CIRCLEQ_FOREACH(mp, &me->phdrList, elem) {
21 GElf_Off off2 = mp->phdr.p_offset;
22 GElf_Off end2 = mp->phdr.p_offset + mp->phdr.p_filesz;
24 GElf_Xword size2 = mp->phdr.p_memsz - mp->phdr.p_filesz;
25 if (size2 > expansionSize) {
26 expansionSize = size2;
28 } else if (end2 > off) {
31 * Found a PHDR whose file contents overlaps with the section
32 * to be filled. This means that it relies on the NOBITS area
33 * being actually 0 bytes, and the expansion would ruin it.
35 fprintf(stderr, "mExpandNobits: Found PHDR spanning expansion offset. Aborting.\n");
39 // end2 < off, and the PHDR is unaffected.
45 CIRCLEQ_FOREACH(ms, &me->scnList, elem) {
46 if (ms->shdr.sh_offset == off) {
47 if (ms->shdr.sh_type == SHT_NOBITS) {
48 if (ms->shdr.sh_size > expansionSize) {
49 expansionSize = ms->shdr.sh_size;
60 /* Move all following PHDR offsets further down the file. */
61 CIRCLEQ_FOREACH(mp, &me->phdrList, elem) {
62 GElf_Off off2 = mp->phdr.p_offset;
63 GElf_Off end2 = mp->phdr.p_offset + mp->phdr.p_filesz;
66 mp->phdr.p_offset += expansionSize;
69 /* This PHDR now has corresponding bytes in the file for every
71 mp->phdr.p_filesz = mp->phdr.p_memsz;
76 /* Move the following sections */
77 CIRCLEQ_FOREACH(ms, &me->scnList, elem) {
78 if (ms->shdr.sh_offset >= off) {
79 if (ms->shdr.sh_offset > off
80 || ms->shdr.sh_type != SHT_NOBITS) {
81 ms->shdr.sh_offset += expansionSize;
86 /* Move SHDR/PHDR tables */
87 if (me->ehdr.e_shoff >= off) {
88 me->ehdr.e_shoff += expansionSize;
91 if (me->ehdr.e_phoff >= off) {
92 me->ehdr.e_phoff += expansionSize;
96 /* Convert any NOBITS at off to PROGBITS */
97 CIRCLEQ_FOREACH(ms, &me->scnList, elem) {
98 if (ms->shdr.sh_offset == off) {
99 if (ms->shdr.sh_type == SHT_NOBITS) {
100 ms->data.d_buf = malloc(ms->shdr.sh_size);
101 memset(ms->data.d_buf, '\0', ms->shdr.sh_size);
102 if (!ms->data.d_buf) {
103 fprintf(stderr, "mExpandNobits: Could not allocate %jd bytes for NOBITS expansion.\n", ms->shdr.sh_size);
106 ms->data.d_align = 1;
108 ms->data.d_type = ELF_T_BYTE;
109 ms->data.d_size = ms->shdr.sh_size;
110 ms->data.d_version = elf_version(EV_NONE);
112 ms->shdr.sh_type = SHT_PROGBITS;