Recently I've been interested in ELF File Structure. Searching on web, I found an awesome script named pyelftools. But in fact I didn't know the way to save the modified ELF; ELFFile class doesn't have any method to do.
First of all, I did like below:
header = self.elf.headerself._emitline("%s" % header['e_shnum'])header['e_shnum'] = 30self._emitline("%s" % header['e_shnum'])
Yeah, that's poor way. But sadly I have no idea getting an offset of e_shnum in the ELF file. Is there anybody able to teach me?
Regards,
Rex.
According to the author @eli-bendersky, pyelftools is a module for parsing and analyzing ELF/DWARF files and it has no direct way of modifying them. I had a look at the module source files and could not find any methods to edit/save either.
On the introductory post, within comments author acknowledges that pyelftools has no API-level support to do this but some tinkering around can help achieve what you need.
If pyelftools is not a hard dependency, here's an example on how to do the same using elffile:
import elffileeo = elffile.open(name="/bin/ls")
eo.fileHeader.shnum = 30
with open('./ls.bin', 'wb') as f: f.write(eo.pack())
Using readelf, you can verify that changes were saved correctly:
readelf -h ls.bin
ELF Header:Magic: 7f 45 4c 46 01 01 01 00 00 00 00 00 00 00 00 00 Class: ELF32Data: 2's complement, little endianVersion: 1 (current)OS/ABI: UNIX - System VABI Version: 0Type: EXEC (Executable file)Machine: Intel 80386Version: 0x1Entry point address: 0x804be34Start of program headers: 105068 (bytes into file)Start of section headers: 103948 (bytes into file)Flags: 0x0Size of this header: 52 (bytes)Size of program headers: 32 (bytes)Number of program headers: 9Size of section headers: 40 (bytes)Number of section headers: 30Section header string table index: 27
readelf: Error: Unable to read in 0x708 bytes of section headers
There's not much documentation on elffile but you can have a look at the source and figure out ways to replicate pyelftools-specific functionality. If that doesn't work, you can try using both pyelftools for reading/analyzing tasks and elffile to edit sections and write changes.