问题
I'd like to copy an executable ELF file via:
$ objcopy -O binary myfile.elf myfile.bin
Unfortunately:
$ chmod +x myfile.bin
$ ./myfile.bin
results in: cannot execute binary file
Is there any way to retain the files executability?
回答1:
To be executable by the execve(2) syscall, a file usually has to be some elf(5) file (or some script, or some old a.out
format). But see also binfmt_misc
Your objcopy(1) command is loosing the essential meta-data in the ELF file. Maybe you want strip(1)
Recall that ELF is quite a complex and versatile format, it specifies the starting address, the interpreter (ld-linux(8) dynamic linker), the several segments of the program etc. All this meta-data is needed by the kernel for execve(2)
and is lost with objcopy -O binary
...
When you use objcopy -O binary, you are copying only the binary data:
objcopy can be used to generate a raw binary file by using an output target of `binary' (e.g., use -O binary). When objcopy generates a raw binary file, it will essentially produce a memory dump of the contents of the input object file. All symbols and relocation information will be discarded. The memory dump will start at the load address of the lowest section copied into the output file.
In particular you lose the entry point and the segments list given in the original ELF header. The kernel cannot guess them.
I don't understand why you expect the result of objcopy -O binary
to be executable by Linux using execve(2)
. The main purpose of that objcopy -O binary
command is to make firmware or kernel-like stand-alone (or freestanding) binaries, and then you need to exactly understand how they should look like (e.g. what is their starting point, how they are loaded and started) and you probably also use some very specific linker script, and of course that binary cannot contain any syscall to the linux kernel (in particular cannot do any kind of input or output the way a plain Linux executable does them).
Read also more about ABIs, the x86-64 ABI, the Linux Assembly HowTo, the Advanced Linux Programming book.
You probably should read a good OS textbook like Operating System: Three Easy Pieces.
来源:https://stackoverflow.com/questions/19944441/make-executable-binary-file-from-elf-using-gnu-objcopy