From 99718360e76a34c8ba58b89514a74d211a031891 Mon Sep 17 00:00:00 2001 From: Breno Rodrigues Guimaraes Date: Sat, 18 Feb 2023 20:56:04 -0300 Subject: [PATCH] Avoid overlapping program header table with section header table #457 --- src/patchelf.cc | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/src/patchelf.cc b/src/patchelf.cc index 2bb84eb7..74448dee 100644 --- a/src/patchelf.cc +++ b/src/patchelf.cc @@ -749,8 +749,14 @@ void ElfFile::rewriteSectionsLibrary() few segments to someplace else. */ /* Some sections may already be replaced so account for that */ unsigned int i = 1; - Elf_Addr pht_size = sizeof(Elf_Ehdr) + (phdrs.size() + num_notes + 1)*sizeof(Elf_Phdr); - while( i < rdi(hdr()->e_shnum) && rdi(shdrs.at(i).sh_offset) <= pht_size ) { + Elf_Addr firstFreeOffset = sizeof(Elf_Ehdr) + (phdrs.size() + num_notes + 1)*sizeof(Elf_Phdr); + if (rdi(hdr()->e_shoff) < firstFreeOffset) { + // The new program header table will overlap with the section header table. + // Put the section header table right after it, and account for its size. + wri(hdr()->e_shoff, firstFreeOffset); + firstFreeOffset += rdi(hdr()->e_shnum) * rdi(hdr()->e_shentsize); + } + while( i < rdi(hdr()->e_shnum) && rdi(shdrs.at(i).sh_offset) <= firstFreeOffset ) { if (not haveReplacedSection(getSectionName(shdrs.at(i)))) replaceSection(getSectionName(shdrs.at(i)), rdi(shdrs.at(i).sh_size)); i++;