Skip to content

Commit 42394e8

Browse files
committed
write out replace sections in original order
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.
1 parent 7c18779 commit 42394e8

File tree

1 file changed

+14
-8
lines changed

1 file changed

+14
-8
lines changed

src/patchelf.cc

Lines changed: 14 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -601,20 +601,26 @@ void ElfFile<ElfFileParamNames>::writeReplacedSections(Elf_Off & curOff,
601601
}
602602

603603
std::set<unsigned int> noted_phdrs = {};
604-
for (auto & i : replacedSections) {
605-
const std::string & sectionName = i.first;
606-
auto & shdr = findSectionHeader(sectionName);
604+
605+
/* We iterate over the sorted section headers here, so that the relative
606+
position between replaced sections stays the same. */
607+
for (auto & shdr : shdrs) {
608+
std::string sectionName = getSectionName(shdr);
609+
auto i = replacedSections.find(sectionName);
610+
if (i == replacedSections.end())
611+
continue;
612+
607613
Elf_Shdr orig_shdr = shdr;
608614
debug("rewriting section '%s' from offset 0x%x (size %d) to offset 0x%x (size %d)\n",
609-
sectionName.c_str(), rdi(shdr.sh_offset), rdi(shdr.sh_size), curOff, i.second.size());
615+
sectionName.c_str(), rdi(shdr.sh_offset), rdi(shdr.sh_size), curOff, i->second.size());
610616

611-
memcpy(fileContents->data() + curOff, (unsigned char *) i.second.c_str(),
612-
i.second.size());
617+
memcpy(fileContents->data() + curOff, (unsigned char *) i->second.c_str(),
618+
i->second.size());
613619

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

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

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

710716
replacedSections.clear();

0 commit comments

Comments
 (0)