linuxassemblyexecutableelfexecutable-format

Linux executable file format. Where is the specification?


I want to understand how Linux executable file is consisted of. Where can I get the specification?

I compiled a simple assemble file with gcc but the generated file size is much bigger than I expected.

# cat tmp.s
.intel_syntax noprefix
.global main
main:
        mov rax, 42
        ret
# gcc -o tmp tmp.s
# ./tmp
# echo $?
42

# ls -l tmp
-rwxr-xr-x 1 root root 8136 Jul 31 04:03 tmp

# xxd tmp
00000000: 7f45 4c46 0201 0100 0000 0000 0000 0000  .ELF............
00000010: 0300 3e00 0100 0000 f004 0000 0000 0000  ..>.............
...
...
00001fb0: 0000 0000 0000 0000 0100 0000 0000 0000  ................
00001fc0: 0000 0000 0000 0000                      ........

# uname -a
Linux fb8275f9e7a0 4.9.125-linuxkit #1 SMP Fri Sep 7 08:20:28 UTC 2018 x86_64 x86_64 x86_64 GNU/Linux

# gcc --version
gcc (Ubuntu 7.4.0-1ubuntu1~18.04.1) 7.4.0
Copyright (C) 2017 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

Solution

  • file tmp would have told you it's an ELF executable. See https://stackoverflow.com/tags/elf/info, and try readelf -a tmp

    re: file size: https://www.muppetlabs.com/~breadbox/software/tiny/teensy.html.

    Also current toolchains align sections to page boundaries, making them bigger than necessary. Link with ld --nmagic to disable section alignment entirely (possibly breaking compiler-generated code). Also disables linking with shared libraries. Anyway, that's why your executable is just over 2x 4kiB when most of it is padding.