Warm tip: This article is reproduced from serverfault.com, please click

Converting an ELF binary into an .o file

发布于 2020-12-06 03:23:18

The question is as stated in the title: Is it possible to convert an ELF binary file hello_world into an object file hello_world.o, which can be used to generate a new binary hello_world_2 which is a replica of hello_world?

So from my searching, it seems that this is a bit difficult. I have found one method that is the closest which is:

Using either objcopy or ld to create an object file from the binary. An example command of this would be:

ld -r -b binary ./hello_world -o hello_world.o

This command creates an object file consisting of sections something like

00000000 l    d  .data    00000000 .data
00000000 g       .data    00000000 _binary_hello_world_start
00000010 g       .data    00000000 _binary_hello_world_end
00000010 g       *ABS*    00000000 _binary_hello_world_size

That can be accessed if you link this newly generated object file with a separate C file (https://balau82.wordpress.com/2012/02/19/linking-a-binary-blob-with-gcc/). However, this is a bit different than what I wish to do since I need to create a separate code just to access this new object file.

This: Make Executable Binary File From Elf Using GNU objcopy StackOverflow discussion provides a great explanation of a similar topic. However, I'm still wondering if there was some sort of way to achieve my original question of:

binary --> binary.o --> binary_new

Side note: If anyone is curious why I am trying to do this, is because I am trying to add a .rodata section into the binary that I have no source code for (this is a whole another problem which is extensively discussed below). This procedure is recommended to do with an object file because newly added section into the binary will be readable in the load-time.

  1. How can the --add-section switch of OBJCOPY be used?

  2. How to replace a section of an elf file with another using objcopy or libelf, such that it does get loaded into the Memory?

  3. Define new code section in assembly code to compile ELF binary

Thank you for any suggestions in advance,

Questioner
Jay
Viewed
0
Employed Russian 2020-12-06 13:11:55

it seems that this is a bit difficult

That's a bit of understatement: for all practical purposes this is impossible to do (at least on ELF platforms), because in the process of linking hello_world the linker discards much of the information that was contained on object files which comprise hello_world, and is necessary to reconstruct it again.

I am trying to add a .rodata section into the binary that I have no source code for

That is unlikely to be your real goal -- the original binary will not use your added .rodata, so your goal must be something else. See also http://xyproblem.info/.