Skip to content

Commit

Permalink
write out replace sections in original order
Browse files Browse the repository at this point in the history
Libc and other programs sometimes make assumption in which order
sections.

i.e. glibc expects that the strtab is after the symtab section: https://github.com/bminor/glibc/blob/9cc9d61ee12f2f8620d8e0ea3c42af02bf07fe1e/elf/dl-fptr.c#L179

To decrease the likelyhood of breakages we keep the relative order the
same when replacing section.
  • Loading branch information
Mic92 committed Nov 5, 2022
1 parent 7c18779 commit 42394e8
Showing 1 changed file with 14 additions and 8 deletions.
22 changes: 14 additions & 8 deletions src/patchelf.cc
Original file line number Diff line number Diff line change
Expand Up @@ -601,20 +601,26 @@ void ElfFile<ElfFileParamNames>::writeReplacedSections(Elf_Off & curOff,
}

std::set<unsigned int> noted_phdrs = {};
for (auto & i : replacedSections) {
const std::string & sectionName = i.first;
auto & shdr = findSectionHeader(sectionName);

/* We iterate over the sorted section headers here, so that the relative
position between replaced sections stays the same. */
for (auto & shdr : shdrs) {
std::string sectionName = getSectionName(shdr);
auto i = replacedSections.find(sectionName);
if (i == replacedSections.end())
continue;

Elf_Shdr orig_shdr = shdr;
debug("rewriting section '%s' from offset 0x%x (size %d) to offset 0x%x (size %d)\n",
sectionName.c_str(), rdi(shdr.sh_offset), rdi(shdr.sh_size), curOff, i.second.size());
sectionName.c_str(), rdi(shdr.sh_offset), rdi(shdr.sh_size), curOff, i->second.size());

memcpy(fileContents->data() + curOff, (unsigned char *) i.second.c_str(),
i.second.size());
memcpy(fileContents->data() + curOff, (unsigned char *) i->second.c_str(),
i->second.size());

/* Update the section header for this section. */
wri(shdr.sh_offset, curOff);
wri(shdr.sh_addr, startAddr + (curOff - startOffset));
wri(shdr.sh_size, i.second.size());
wri(shdr.sh_size, i->second.size());
wri(shdr.sh_addralign, sectionAlignment);

/* If this is the .interp section, then the PT_INTERP segment
Expand Down Expand Up @@ -704,7 +710,7 @@ void ElfFile<ElfFileParamNames>::writeReplacedSections(Elf_Off & curOff,
}
}

curOff += roundUp(i.second.size(), sectionAlignment);
curOff += roundUp(i->second.size(), sectionAlignment);
}

replacedSections.clear();
Expand Down

0 comments on commit 42394e8

Please sign in to comment.