除了原始机器指令外,可执行文件中还有什么? [英] What is in an executable besides the raw machine instructions?
问题描述
我正在寻求了解低级计算.我注意到编译后的二进制文件比我认为的要大得多.因此,我尝试构建没有任何stdlib代码的最小的c程序,如下所示:
I am on a quest to understand low-level computing. I have noticed my compiled binaries are a lot bigger then I think they should be. So I tried to build the smallest possible c program without any stdlib code as follows:
void _start()
{
while(1) {};
}
gcc -nostdlib -o minimal minimal.c
当我弄清二进制文件时,它确实向我显示了我的期望,即,此精确的代码以三行汇编的形式出现.
When I disasseble the binary, it shows me exactly what I expect, namely this exact code in three lines of assembly.
$ objdump -d minimal
minimal: file format elf64-x86-64
Disassembly of section .text:
0000000000001000 <_start>:
1000: 55 push %rbp
1001: 48 89 e5 mov %rsp,%rbp
1004: eb fe jmp 1004 <_start+0x4>
但是我实际的可执行文件仍然是13856字节.是什么,这使它如此之大?该文件中还有什么?操作系统是否需要超过这6个字节的机器代码?
But my actual executable is still 13856 Bytes in size. What is it, that makes this so large? What else is in that file? Does the OS need more than these 6 Bytes of machine code?
编辑#1:
size
的输出是:
$ size -A minimal
minimal :
section size addr
.interp 28 680
.note.gnu.build-id 36 708
.gnu.hash 28 744
.dynsym 24 776
.dynstr 1 800
.text 6 4096
.eh_frame_hdr 20 8192
.eh_frame 52 8216
.dynamic 208 16176
.comment 18 0
Total 421
推荐答案
现代编译器和链接器并未真正针对在完整规模的平台上生成超小型代码进行过优化.不是因为工作困难,而是因为通常没有必要.不一定需要编译器或链接器添加其他代码(尽管可能会添加),但是它不会尝试将数据和代码打包到尽可能小的空间.
Modern compilers and linkers aren't really optimized for producing ultra-small code on full-scale platforms. Not because the job is difficult, but because there's usually no need to. It isn't necessarily that the compiler or linker adds additional code (although it might), but rather that it won't try hard to pack your data and code into the smallest possible space.
就您而言,我注意到您正在使用动态链接,即使实际上没有任何链接.使用"-static"将节省约8kB. "-s"表示(带状)将去除更多.
In your case, I note that you're using dynamic linking, even though nothing is actually linked. Using "-static" will shave off about 8kB. "-s" (strip) will get rid of a bit more.
我不知道gcc是否有可能制作真正最小的ELF可执行文件.在您的情况下,大约应为400个字节,几乎所有字节都是各种ELF标头,节表等.
I don't know if it's even possible with gcc to make a truly minimal ELF executable. In your case, that ought to be about 400 bytes, nearly all of which will be the various ELF headers, section table, etc.
我不知道是否允许我链接自己的网站(我敢肯定,如果没有的话,我会让别人说对了),但是我有一篇文章介绍了如何通过从头开始以二进制形式构建小型ELF可执行文件:
I don't know if I'm allowed to link my own website (I'm sure somebody will put me right if not), but I have an article on producing a tiny ELF executable by building it from scratch in binary:
http://kevinboone.me/elfdemo.html
这篇关于除了原始机器指令外,可执行文件中还有什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!