3

Is it possible to replace a non-code section inside an ELF file? If so, then how? Is there something I would have to consider before simply replacing the bytes by some other bytes (of course nothing larger)? Maybe some hash or similar?

Note that I'm not interested in modifying code, so the solutions presented in What are the available libraries to statically modify ELF executables? is not what I'm looking for, also many solutions there aren't architecture-agnostic.

(BTW, I would require this for a replacing the initrd/initramfs file system embedded into a kernel image [vmlinux.64] which is also an ELF file, see https://unix.stackexchange.com/q/342298/117599. This question here is supposed to be more in general.)

1 Answer 1

5
+50

I'm not aware of any ready-made tools for such task, but I suspect in most cases the good old dd will do the task of replacing the actual bytes in the file (or maybe you can make objcopy work too). What can be more difficult is making the code work with the changed data. This depends on the nature of the data in question. For example:

  1. When replacing (patching) code (instructions), you need to be aware of possible relocations pointing into the address range you're replacing (if the file is relocatable). The loader will apply the relocations without checking that they make sense and that will likely make your code work incorrectly or crash. Same issue applies to data which may be relocated (e.g. tables of pointers).

  2. Even if the data you're replacing is not affected by the loader, it might be used in other ways. For your initrd example, the code in the kernel makes references to symbols like __initramfs_start, __initramfs_end, whose values may need to be updated to account for the new initrd size. How to do that depends on how the code is using those symbols: are they taken from the ELF symbol table or just embedded in the code (i.e. were resolved at link time)? In the latter case you'll need to find and patch those values in the binary, keeping in mind that they are probably virtual load-time addresses and not file offsets.

  3. In case the code is using the ELF sections, you will need to update the section headers to properly point to your data or adjust their size e(some hex editors allow you to edit fields of the ELF headers but in the worst case you'll need to do it manually by patching individual bytes).

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.