<div dir="auto"><div>Many thanks for the great info. What about removing a section? Is there an implementation for that already in the codebase?<br><br><div class="gmail_quote"><div dir="ltr" class="gmail_attr">On Thu, 13 Aug 2020, 20:14 Fangrui Song, <<a href="mailto:maskray@google.com">maskray@google.com</a>> wrote:<br></div><blockquote class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex">On 2020-08-13, David Blaikie via llvm-dev wrote:<br>
>Sounds like the llvm-objcopy source code (llvm/tools/llvm-objcopy) is<br>
>probably a good place to start.<br>
><br>
>On Thu, Aug 13, 2020 at 8:11 AM Joseph via llvm-dev<br>
><<a href="mailto:llvm-dev@lists.llvm.org" target="_blank" rel="noreferrer">llvm-dev@lists.llvm.org</a>> wrote:<br>
>><br>
>> Hey,<br>
>><br>
>> LLVM has logic to parse ELF and PE binaries using `llvm::object::createBinary`. I tried to search in the codebase to see if there's a possibility to add/remove sections after parsing a binary and re-write the binary to another location. Basically, like what llvm-objcopy does. Can you point me to the right classes to look into, if this is something that LLVM has?<br>
>><br>
>> Many thanks<br>
>><br>
>> Joseph<br>
<br>
For ELF,<br>
<br>
* adding a non-SHF_ALLOC section is simple. A non-SHF_ALLOC section is not part of<br>
the memory image and not used by the program (unless for some rare<br>
introspection use cases)<br>
<br>
* adding a SHF_ALLOC section is difficult. You likely need to fix the<br>
containing PT_LOAD segment. llvm-objcopy only does the base p_offset fix.<br>
You need to take care p_vaddr/p_paddr/p_filesz/p_memsz by your self.<br>
<br>
+ adding a section smaller than the known lowest address (ET_EXEC with a<br>
non-zero image base) or larger than the known largest address:<br>
The PT_LOAD fixes are doable.<br>
+ adding a section within the existing address ranges: this is very difficult<br>
due to many implicit inter-section references. If you have an advanced<br>
binary rewriting tool, this is still doable, but definitely brittle.<br>
<br>
File offsets (p_offset,sh_offset) can be reconstructed from addresses.<br>
llvm-objcopy/ELF/Object.cpp layoutSections has some code.<br>
A more sophisticated implementation is in the linker: lld/ELF/Writer.cpp assignFileOffsets<br>
</blockquote></div></div></div>