gcc -static turns a C program that prints 14 bytes into a file of roughly 785 KB. Almost none of that is your code. It is the C library, the startup code that runs before main, symbol tables for humans, and page-alignment padding inside the ELF file. This article takes one hello world from a normal gcc build down to a 167-byte executable, one change at a time, and shows what each change removed and why it was there.
It is for anyone who has written C but never looked inside the file the compiler hands back. You need a shell on an x86-64 Linux machine. By the end you will be able to read readelf output, explain what the kernel needs to start a program, and tell which size tricks belong in a real build and which ones only belong in a lesson.
Last verified: December 2026. Versions used: Ubuntu 24.04.5, GCC 13.3.0, GNU Binutils 2.42 (ld, as, objcopy, readelf), glibc 2.39, NASM 2.16.01, Linux kernel 6.18. Your byte counts will differ on another toolchain; the shape of the ladder will not.
File size at each step, measured on the test machine described above. Log scale: the drop from step 4 to step 5 is a factor of 75.
Where This Came From
I worked through Heavy Wizardry 101 by David Martínez Oliveira (No Starch Press, 2026) to learn low-level systems programming: x86-64 assembly, binary formats and ELF structure. Along the way I compared a compiled C program with hand-written assembly. My test program added two numbers and returned the sum as the exit status. The figures I recorded were about 789 KB for gcc -static, about 360 bytes for hand-written assembly linked with ld, and about 489 bytes for the C version once I had dropped the C library, stripped it, removed the note sections and squeezed out the padding. I did not record the exact flags behind those figures.
Two things stopped me along the way: readelf -d /bin/ls | grep INTERP printing nothing, and not understanding the difference between _start and main. Both come down to the same lesson: the kernel reads very little of an ELF file, and main is not in the part it reads.
For this article the ladder was rebuilt from scratch on a test machine, with the program switched to hello world so that it has to make a real system call. Every size below comes from that machine, not from my original setup. The Verify section compares the results with my original numbers.
How It Works
An ELF file (Executable and Linkable Format, the standard binary format on Linux) has exactly one structure at a fixed position: the ELF header in the first 64 bytes. The System V gABI, the specification ELF comes from, states that “only the ELF header has a fixed position in the file.” Everything else is found through offsets stored in that header:
e_entry: the virtual address where execution starts.man 5 elfcalls it the address “to which the system first transfers control.”e_phoff: where the program header table starts. Each program header describes a segment: a range of the file to map into memory, at what address, with what permissions (PT_LOAD), or a piece of information for the loader (PT_INTERP,PT_GNU_STACK).e_shoff: where the section header table starts. Each section header describes a section: a named piece such as.text(code),.rodata(constants),.symtab(symbols) or.comment.
Sections are the linker’s view of the bytes; segments are the loader’s view of the same bytes. readelf -S lists sections, and readelf -l lists segments and which sections fall inside each one. The gABI makes the split explicit: files that are executed “must have a program header table,” while a section header table is required only for files used during linking.
The Linux kernel’s ELF loader, load_elf_binary() in fs/binfmt_elf.c, follows that rule. It checks the magic bytes, the file type (ET_EXEC or ET_DYN) and the architecture, reads the program headers from e_phoff, maps every PT_LOAD segment, notes PT_GNU_STACK to decide whether the stack is executable, and loads the interpreter named by PT_INTERP if there is one. Then it jumps to e_entry, or to the interpreter’s entry point. It never reads the section headers. That single fact is why most of this article works.
_start versus main
In a normal C program e_entry points at _start (the kernel runs the dynamic loader first if there is one, and the loader then jumps there), supplied by a startup object file (crt1.o on glibc systems) that the compiler links in without asking. _start reads argc, argv and the environment off the stack the kernel built and calls glibc’s __libc_start_main, which initializes the library and calls your main. When main returns, glibc calls exit(), which flushes stdio buffers and ends the process.
So main is a C convention the kernel has never heard of. _start is not a function in the usual sense: nothing called it, so there is no return address on the stack. If _start executes ret, the CPU pops whatever value sits at the top of the stack (argc on entry, or garbage after the compiler has used the stack) and jumps to it, and the process dies with a segmentation fault. A _start you write yourself must end the process with a system call.
System calls on x86-64
A system call is a request from a program to the kernel. On x86-64 Linux you make one by loading registers and executing the syscall instruction. man 2 syscall gives the convention: the call number goes in rax, arguments one to six go in rdi, rsi, rdx, r10, r8 and r9, and the result comes back in rax. The kernel’s entry code (arch/x86/entry/entry_64.S) documents that the CPU itself overwrites rcx with the return address and r11 with the saved flags, so inline assembly must list both as clobbered. The numbers come from arch/x86/entry/syscalls/syscall_64.tbl: write is 1 and exit is 60. (exit_group, 231, ends every thread in the process; with one thread, exit is enough.)
For the source-to-CPU picture this sits inside, see The Elements of Programming.
Prerequisites
- An x86-64 Linux machine or VM. The measurements here come from Ubuntu 24.04; any distribution works, but sizes will differ.
- GCC, GNU Binutils, glibc’s static archive and NASM. On Ubuntu or Debian:
sudo apt update
sudo apt install build-essential nasm file
- An empty working directory:
mkdir -p ~/elf-ladder && cd ~/elf-ladder
Every command below runs from there. stat -c %s <file> prints exact bytes; ls -lh rounds to KiB.
Step 1: Build a Normal Hello World and Find Its Loader
Start with the program everyone writes first. Open the file with vim hello.c (press i to insert, Esc then :wq to save and quit):
#include <stdio.h>
int main(void) {
printf("Hello, World!\n");
return 0;
}
gcc hello.c -o step1-dynamic
stat -c %s step1-dynamic
ldd step1-dynamic
readelf -l step1-dynamic | grep -A2 INTERP
15960
linux-vdso.so.1 (0x00007f0b9bfe8000)
libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007f0b9bc00000)
/lib64/ld-linux-x86-64.so.2 (0x00007f0b9bfea000)
INTERP 0x0000000000000318 0x0000000000000318 0x0000000000000318
0x000000000000001c 0x000000000000001c R 0x1
[Requesting program interpreter: /lib64/ld-linux-x86-64.so.2]
This binary is dynamically linked: printf is not inside it. The PT_INTERP segment names a program, the dynamic loader ld-linux-x86-64.so.2, and the kernel starts that loader first. The loader maps libc.so.6 into the process, fills in the addresses of printf and friends, and only then jumps to the program’s _start. ldd shows the libraries the loader would pull in. The man page for ldd warns that it may run the program to find out, so never point it at an untrusted file; objdump -p <file> | grep NEEDED is the safe alternative.
This is where my first stumble lives. I ran readelf -d /bin/ls | grep INTERP and got nothing. -d dumps the dynamic section, the table of tags the loader reads (NEEDED, RUNPATH and so on). INTERP and DYNAMIC are segment types, so they appear under -l. Segments are -l; the dynamic section’s contents are -d.
The ELF header tells you this is a position-independent executable (PIE), which Ubuntu’s GCC builds by default:
readelf -h step1-dynamic
Type: DYN (Position-Independent Executable file)
Entry point address: 0x1060
Start of program headers: 64 (bytes into file)
Number of program headers: 13
Number of section headers: 31
Of the 15,960 bytes, 13,789 are zero bytes, most of them padding. The linker places code, read-only data and writable data in separate PT_LOAD segments, starts the code and the read-only data each on a 4 KiB boundary in the file, and fills the gaps with zeros. Keep that in mind for Step 7.
Step 2: Link Statically
-static tells GCC to copy the library code into the executable instead of leaving it for the loader.
gcc -static hello.c -o step2-static
stat -c %s step2-static
file step2-static
ldd step2-static
size step2-static
785336
step2-static: ELF 64-bit LSB executable, x86-64, version 1 (GNU/Linux), statically linked, BuildID[sha1]=92cc..., for GNU/Linux 3.2.0, not stripped
not a dynamic executable
text data bss dec hex filename
668193 23376 22472 714041 ae539 step2-static
There is no INTERP segment any more (readelf -l step2-static | grep INTERP prints nothing), and the file grew by a factor of 49. size sums the sections that get loaded into memory: 668 KB of code and constants.
Why so much for one printf? Ask the linker. A link map lists every archive member it pulled in and the symbol that caused it:
printf 'int main(void) { return 0; }\n' > empty.c
gcc -static empty.c -o /dev/null -Wl,-Map=empty.map
sed -n '/^Archive member included/,/^Discarded input sections/p' empty.map \
| grep -oE '^[^ ]+\.a\([^)]+\)' | sort -u | wc -l
423
An empty main that calls nothing pulls in 423 object files from libc.a, libgcc.a and libgcc_eh.a. The map shows the chain. Excerpt, paths shortened:
libc.a(libc-start.o) crt1.o (__libc_start_main)
libc.a(dl-load.o) libc.a(libc-start.o) (_dl_process_pt_gnu_property)
libc.a(malloc.o) libc.a(exit.o) (free)
libc.a(vfprintf-internal.o) libc.a(fprintf_chk.o) (__vfprintf_internal)
libc.a(C-ctype.o) libc.a(xlocale.o) (_nl_C_LC_CTYPE)
libgcc_eh.a(unwind-dw2.o) libc.a(iofputs.o) (_Unwind_Resume)
crt1.o needs __libc_start_main. Static glibc’s startup still processes the binary’s ELF properties, and that code lives with the dynamic loader, so loader code comes along. exit needs free, which brings the whole malloc implementation. Somewhere in the chain a call to fprintf pulls in the full printf engine, and locale tables arrive the same way. The weight is the runtime that surrounds main, and it is there whether or not you call printf. On this machine the stripped empty program is 8 bytes larger than the stripped hello world.
Step 3: Strip the Symbols
The symbol table (.symtab) maps addresses to names like printf and main, and .strtab holds the name strings. Debuggers, nm and objdump use them. The CPU never reads them.
gcc -static -s hello.c -o step3-stripped
stat -c %s step3-stripped
size step3-stripped
706576
text data bss dec hex filename
668193 23376 22472 714041 ae539 step3-stripped
GCC’s -s passes --strip-all to the linker; running strip -s step2-static afterwards gives the same 706,576 bytes. That removed 78,760 bytes, and size did not change at all, which is the proof that none of those bytes were ever loaded into memory. This is the first practical step in the article: strip release binaries and keep the unstripped copy for debugging crash reports.
Step 4: Try -Os and Section Garbage Collection (and Watch Them Do Nothing)
-ffunction-sections and -fdata-sections put every function and variable in its own section. -Wl,--gc-sections then lets the linker discard any section nothing refers to. -Os optimizes for size instead of speed.
gcc -static -s -Os -ffunction-sections -fdata-sections \
-Wl,--gc-sections hello.c -o step4-gc-os
stat -c %s step4-gc-os
706536
Forty bytes. -Os only changes code you compile, and main is a handful of instructions. Garbage collection only discards what nothing references, and the link map shows every one of those 423 members was pulled in by a real reference. These flags pay off in large programs with dead code of their own, not against a runtime that really uses what it links.
ELF-level tricks are just as weak while glibc is inside. Added to the stripped static build from Step 3, -Wl,-z,norelro gave 704,560 bytes and -Wl,-z,noseparate-code gave 702,480. The Step 4 flags plus both of those and -Wl,--build-id=none came to 697,592: about 1 percent. The only big lever left is the library itself.
Step 5: Drop libc and Write _start Yourself
Without glibc there is no printf, no exit() and no startup code, so the program provides its own _start and talks to the kernel directly. Create tiny.c:
/* tiny.c: Hello, World! with no C library at all. */
static long sys_write(int fd, const void *buf, unsigned long len)
{
long ret;
__asm__ volatile ("syscall"
: "=a"(ret) /* return value in rax */
: "a"(1L), /* rax = 1, write */
"D"((long)fd), /* rdi = fd */
"S"(buf), /* rsi = buffer */
"d"(len) /* rdx = length */
: "rcx", "r11", "memory"); /* syscall clobbers */
return ret;
}
static __attribute__((noreturn)) void sys_exit(int code)
{
__asm__ volatile ("syscall"
:
: "a"(60L), /* rax = 60, exit */
"D"((long)code) /* rdi = status */
: "rcx", "r11", "memory");
__builtin_unreachable();
}
/* The kernel jumps here. Nothing called us, so we must never return. */
__attribute__((force_align_arg_pointer, noreturn)) void _start(void)
{
static const char msg[] = "Hello, World!\n";
sys_write(1, msg, sizeof msg - 1);
sys_exit(0);
}
The constraint letters pin each value to a register: a is rax, D is rdi, S is rsi, d is rdx. force_align_arg_pointer makes GCC realign the stack if needed: compiled code assumes the stack pointer sits 8 bytes off a 16-byte boundary at function entry (a call just pushed a return address), but the kernel enters _start exactly 16-byte aligned. When the code does not use the stack, the attribute costs nothing. Troubleshooting shows the crash without it.
gcc -static -nostdlib tiny.c -o step5-nolibc
stat -c %s step5-nolibc
./step5-nolibc; echo "exit=$?"
9384
Hello, World!
exit=0
-nostdlib means no standard startup files and no standard libraries; the GCC manual says it skips both, so it already includes -nostartfiles. Compared with the static build in Step 2, that removed 775,952 bytes. It also removed something you cannot see: on Ubuntu, the default -fstack-protector-strong is switched off whenever -nostdlib is passed (Ubuntu documents this, and gcc -dumpspecs shows the rule). Without libc there is nothing to set up the canary, so it makes sense, but it happens silently.
The sections that are left:
readelf -SW step5-nolibc
[ 1] .note.gnu.property NOTE 00000000004001c8 0001c8 000020 00 A 0 0 8
[ 2] .note.gnu.build-id NOTE 00000000004001e8 0001e8 000024 00 A 0 0 4
[ 3] .text PROGBITS 0000000000401000 001000 000078 00 AX 0 0 1
[ 4] .rodata PROGBITS 0000000000402000 002000 00000f 00 A 0 0 8
[ 5] .eh_frame PROGBITS 0000000000402010 002010 000070 00 A 0 0 8
[ 6] .comment PROGBITS 0000000000000000 002080 00002d 01 MS 0 0 1
[ 7] .symtab SYMTAB 0000000000000000 0020b0 0000d8 18 8 5 8
[ 8] .strtab STRTAB 0000000000000000 002188 000039 00 0 0 1
[ 9] .shstrtab STRTAB 0000000000000000 0021c1 000062 00 0 0 1
The program is 120 bytes of .text and 15 bytes of .rodata. The other 9,000-odd bytes are metadata and padding, which the next three steps remove.
Step 6: Turn Off the Metadata the Compiler Adds
Each flag removes or shrinks one piece of the list above:
gcc -static -nostdlib -s -Os -fno-asynchronous-unwind-tables \
-fcf-protection=none -Wl,--build-id=none tiny.c -o step6-flags
stat -c %s step6-flags
8608
-sdrops.symtaband.strtabas in Step 3.-Osinlines the two helpers, which at the default-O0were real functions with stack frames. Together with the next two flags it shrinks.textfrom 120 bytes to 31.-fno-asynchronous-unwind-tablesstops GCC from emitting.eh_frame, the tables debuggers and C++ exceptions use to walk the stack.-fcf-protection=noneturns off Intel CET instrumentation, which Ubuntu enables by default. In these builds it removed theendbr64instruction at the start of_startand the.note.gnu.propertysection that marks the binary as CET-compatible.-Wl,--build-id=nonestops the linker from writing.note.gnu.build-id, a hash that debuginfo tools use to match a binary with its symbols.
Adding -Wl,-z,norelro makes no difference here, because RELRO (relocation read-only, which makes the global offset table and other data that needs relocating read-only once startup has filled it in) only covers data this program no longer has.
The file is still 8,608 bytes because the content did not cause the size. Look at the segments:
LOAD 0x000000 0x0000000000400000 0x0000000000400000 0x000120 0x000120 R 0x1000
LOAD 0x001000 0x0000000000401000 0x0000000000401000 0x00001f 0x00001f R E 0x1000
LOAD 0x002000 0x0000000000402000 0x0000000000402000 0x00000f 0x00000f R 0x1000
GNU_STACK 0x000000 0x0000000000000000 0x0000000000000000 0x000000 0x000000 RW 0x10
Three loadable segments at file offsets 0x0, 0x1000 and 0x2000. Between them is nearly 8 KB of zeros.
Step 7: Remove the Page Padding
ld 2.42 defaults to -z separate-code on x86-64 Linux (ld --help marks it “default”), and binutils 2.47, the latest release as of December 2026, still does. It keeps the headers and read-only data out of the executable segment, and pads the file so that no 4 KiB page holds both code and non-code. A PT_LOAD segment’s file offset must also agree with its address modulo the page size (a gABI rule), so the padding is real bytes in the file, not just gaps in memory. When separate-code became the default on Linux/x86 in 2018, the patch author gave cache performance and security as the reasons.
gcc -static -nostdlib -s -Os -fno-asynchronous-unwind-tables \
-fcf-protection=none -Wl,--build-id=none \
-Wl,-z,noseparate-code tiny.c -o step7-nopad
stat -c %s step7-nopad
readelf -lW step7-nopad
624
LOAD 0x000000 0x0000000000400000 0x0000000000400000 0x0000df 0x0000df R E 0x1000
GNU_STACK 0x000000 0x0000000000000000 0x0000000000000000 0x000000 0x000000 RW 0x10
Section to Segment mapping:
Segment Sections...
00 .text .rodata
One segment now covers the ELF header, the program headers, the code and the string, and it is mapped readable and executable. That is the cost: the header bytes and the constants are now in executable memory, the exact thing separate-code exists to prevent.
Two older linker switches reach the same 624 bytes here. -Wl,-n (--nmagic) turns off page alignment of sections. -Wl,-N (--omagic) also makes the text writable, and ld warns LOAD segment with RWX permissions. Do not use -N outside an exercise.
Step 8: Remove the .comment Section
.comment holds the compiler’s version string. The loader ignores it.
objcopy --remove-section .comment step7-nopad step8-nocomment
stat -c %s step8-nocomment
readelf -h step8-nocomment
504
Type: EXEC (Executable file)
Entry point address: 0x4000b0
Start of program headers: 64 (bytes into file)
Start of section headers: 248 (bytes into file)
Size of this header: 64 (bytes)
Size of program headers: 56 (bytes)
Number of program headers: 2
Size of section headers: 64 (bytes)
Number of section headers: 4
Removing it saved 120 bytes: 45 bytes of text, the 9 bytes of its name in .shstrtab, a 64-byte section header and 2 bytes of alignment. The binutils manual warns that --remove-section used carelessly “may make the output file unusable”, which is true. Removing a section the program reads at run time would break it, and objcopy will not stop you.
This 504-byte C program is the closest match to the roughly 489 bytes I recorded. The disassembly is the entire program:
objdump -d -M intel step8-nocomment
00000000004000b0 <.text>:
4000b0: b8 01 00 00 00 mov eax,0x1
4000b5: 48 8d 35 14 00 00 00 lea rsi,[rip+0x14] # 0x4000d0
4000bc: ba 0e 00 00 00 mov edx,0xe
4000c1: 48 89 c7 mov rdi,rax
4000c4: 0f 05 syscall
4000c6: b8 3c 00 00 00 mov eax,0x3c
4000cb: 31 ff xor edi,edi
4000cd: 0f 05 syscall
GCC noticed that rax and rdi both need the value 1 and copied one into the other. Eight instructions; everything else in the file is bookkeeping.
Step 9: Write a Linker Script
A linker script tells ld exactly which segments and sections to create. When a script contains a PHDRS command, the linker creates only the program headers you list. Create tiny.ld:
/* tiny.ld: one loadable segment holding the headers, code and constants. */
ENTRY(_start)
PHDRS
{
text PT_LOAD FILEHDR PHDRS FLAGS(5); /* 5 = PF_R | PF_X */
}
SECTIONS
{
. = 0x400000 + SIZEOF_HEADERS;
.text : { *(.text .text.*) *(.rodata .rodata.*) } :text
/DISCARD/ : { *(.comment) *(.note*) *(.eh_frame*) }
}
FILEHDR and PHDRS put the ELF header and program headers inside the loadable segment. The string is merged into .text, and /DISCARD/ throws away notes, comments and unwind tables at link time, so no objcopy pass is needed.
gcc -static -nostdlib -s -Os -fno-asynchronous-unwind-tables \
-fcf-protection=none -Wl,--build-id=none \
-Wl,-T,tiny.ld tiny.c -o step9-script
stat -c %s step9-script
readelf -lW step9-script
376
LOAD 0x000000 0x0000000000400000 0x0000000000400000 0x0000a7 0x0000a7 R E 0x1000
The GNU_STACK header is gone, and with it 56 bytes. Without that header the kernel picks a default. Since Linux 5.8, a 64-bit x86 program with no PT_GNU_STACK gets a non-executable stack; before that change it got an executable one, and so did every other readable mapping. On the test machine’s kernel, the [stack] line in /proc/<pid>/maps for such a binary reads rw-p. If you want the header back explicitly, add stack PT_GNU_STACK FLAGS(6); to PHDRS; the file grows to 432 bytes.
Look at the FileSiz: 0xa7, 167 bytes. That is everything the kernel maps. The other 209 bytes are section names and three section headers, and the kernel never reads them. You can prove it by cutting them off:
head -c 167 step9-script > step9-truncated
chmod +x step9-truncated
./step9-truncated
Hello, World!
readelf -h step9-truncated now complains that the section headers extend past the end of the file. The kernel does not care. This is a learning exercise only: objdump, gdb and anything else that reads sections will misbehave on that file.
Step 10: Compare Hand-Written Assembly
The comparison that started this was how much of the size is the language. Here is the same program in NASM syntax, hello.asm:
; hello.asm: write(1, msg, len) then exit(0), no libc
global _start
section .text
_start:
mov eax, 1 ; syscall number: write
mov edi, 1 ; fd 1 = stdout
lea rsi, [rel msg] ; buffer
mov edx, len ; length
syscall
mov eax, 60 ; syscall number: exit
xor edi, edi ; status 0
syscall
section .rodata
msg: db "Hello, World!", 10
len: equ $ - msg
nasm -f elf64 hello.asm -o hello-asm.o
ld -s -n hello-asm.o -o step10-asm
stat -c %s step10-asm
./step10-asm
464
Hello, World!
With plain ld -s and no -n, the same object is 8,488 bytes. The hand-written code is 33 bytes against GCC’s 31, and the file is bigger than the 376-byte C build only because it went through the linker’s default layout instead of a script. Language was never the variable. Linking is. (NASM emits no .note.GNU-stack section, so this file has no GNU_STACK header either.)
Step 11: Write the ELF Header by Hand
The last step drops the linker. NASM’s -f bin output writes bytes exactly as you list them, so you can write the ELF header and one program header yourself. Create handmade.asm:
; handmade.asm: a complete ELF executable written by hand.
; Build: nasm -f bin handmade.asm -o handmade && chmod +x handmade
BITS 64
org 0x400000 ; virtual address the file is mapped at
ehdr: ; Elf64_Ehdr (64 bytes)
db 0x7f, "ELF" ; e_ident[EI_MAG0..3]
db 2 ; EI_CLASS = ELFCLASS64
db 1 ; EI_DATA = ELFDATA2LSB (little endian)
db 1 ; EI_VERSION = EV_CURRENT
db 0 ; EI_OSABI = ELFOSABI_SYSV
times 8 db 0 ; EI_ABIVERSION + padding
dw 2 ; e_type = ET_EXEC
dw 0x3e ; e_machine = EM_X86_64
dd 1 ; e_version
dq _start ; e_entry
dq phdr - $$ ; e_phoff
dq 0 ; e_shoff (no section headers)
dd 0 ; e_flags
dw ehdrsize ; e_ehsize
dw phdrsize ; e_phentsize
dw 1 ; e_phnum
dw 0 ; e_shentsize
dw 0 ; e_shnum
dw 0 ; e_shstrndx
ehdrsize equ $ - ehdr
phdr: ; Elf64_Phdr (56 bytes)
dd 1 ; p_type = PT_LOAD
dd 5 ; p_flags = PF_R | PF_X
dq 0 ; p_offset
dq $$ ; p_vaddr
dq $$ ; p_paddr
dq filesize ; p_filesz
dq filesize ; p_memsz
dq 0x1000 ; p_align
phdrsize equ $ - phdr
_start:
mov eax, 1 ; write
mov edi, 1 ; stdout
lea rsi, [rel msg]
mov edx, msglen
syscall
mov eax, 60 ; exit
xor edi, edi
syscall
msg: db "Hello, World!", 10
msglen equ $ - msg
filesize equ $ - $$
nasm -f bin handmade.asm -o step11-handmade
chmod +x step11-handmade
stat -c %s step11-handmade
./step11-handmade
file step11-handmade
167
Hello, World!
step11-handmade: ELF 64-bit LSB executable, x86-64, version 1 (SYSV), statically linked, no section header
167 bytes: the same count as the mapped part of the C build in Step 9. Every field the kernel checks is here: the magic, the class, the type, the machine, the entry point and a program header table with one PT_LOAD entry whose offset and address agree modulo the page size. e_shoff is zero, which man 5 elf defines as “no section header table.”
What is in the two smallest files. Everything shaded is mapped by the single PT_LOAD segment; the rest exists for tools, not for the kernel.
Smaller files exist. Brian Raiter’s classic tiny-ELF tutorial (32-bit x86) overlaps the program header with the ELF header and hides code inside header fields the kernel does not check, reaching 45 bytes. Those tricks teach you exactly which fields Linux validates, but they depend on loader details that change between kernel versions (the tutorial itself notes a field older kernels ignored and newer ones check), so they are not something to rely on.
Verify
Put the whole ladder in one script so you can rerun it after changing a flag. Save this as ladder.sh next to hello.c, tiny.c, tiny.ld, hello.asm and handmade.asm:
#!/bin/sh
# Rebuild every step and print the file size of each result.
set -e
sz() { printf '%9s %s\n' "$(stat -c %s "$1")" "$1"; }
gcc hello.c -o step1-dynamic; sz step1-dynamic
gcc -static hello.c -o step2-static; sz step2-static
gcc -static -s hello.c -o step3-stripped; sz step3-stripped
gcc -static -s -Os -ffunction-sections -fdata-sections \
-Wl,--gc-sections hello.c -o step4-gc-os; sz step4-gc-os
gcc -static -nostdlib tiny.c -o step5-nolibc; sz step5-nolibc
gcc -static -nostdlib -s -Os -fno-asynchronous-unwind-tables \
-fcf-protection=none -Wl,--build-id=none tiny.c -o step6-flags; sz step6-flags
gcc -static -nostdlib -s -Os -fno-asynchronous-unwind-tables \
-fcf-protection=none -Wl,--build-id=none \
-Wl,-z,noseparate-code tiny.c -o step7-nopad; sz step7-nopad
objcopy --remove-section .comment step7-nopad step8-nocomment; sz step8-nocomment
gcc -static -nostdlib -s -Os -fno-asynchronous-unwind-tables \
-fcf-protection=none -Wl,--build-id=none \
-Wl,-T,tiny.ld tiny.c -o step9-script; sz step9-script
nasm -f elf64 hello.asm -o hello-asm.o
ld -s -n hello-asm.o -o step10-asm; sz step10-asm
nasm -f bin handmade.asm -o step11-handmade && chmod +x step11-handmade; sz step11-handmade
chmod +x ladder.sh
./ladder.sh
for f in step*[0-9]-*; do printf '%s: ' "$f"; ./"$f"; done
15960 step1-dynamic
785336 step2-static
706576 step3-stripped
706536 step4-gc-os
9384 step5-nolibc
8608 step6-flags
624 step7-nopad
504 step8-nocomment
376 step9-script
464 step10-asm
167 step11-handmade
Every binary should print Hello, World!. Then compare with the figures I recorded. My June program was not hello world, so it is rebuilt here too. add.c:
int main(void) {
int a = 10;
int b = 20;
return a + b;
}
add-tiny.c, the same sum with no C library:
/* add-tiny.c: exit with status 10 + 20, no C library. */
__attribute__((noreturn)) void _start(void)
{
int a = 10;
int b = 20;
__asm__ volatile ("syscall"
:
: "a"(60L), "D"((long)(a + b)) /* exit(a + b) */
: "rcx", "r11", "memory");
__builtin_unreachable();
}
And add.asm:
; add.asm: exit with status 10 + 20
global _start
section .text
_start:
mov ebx, 10
mov ecx, 20
add ebx, ecx
mov eax, 60 ; exit
mov edi, ebx ; status = sum
syscall
nasm -f elf64 add.asm -o add-asm.o
ld -s -n add-asm.o -o add-asm
stat -c %s add-asm
./add-asm; echo "exit=$?"
360
exit=30
The two C versions, first with only some of the levers (no libc, strip, delete the notes, no page padding) and then with every lever from Steps 6 to 8:
gcc -static add.c -o add-static
gcc -static -nostdlib -Wl,-z,noseparate-code add-tiny.c -o add-partial
strip -s add-partial
objcopy -R .note.gnu.build-id -R .note.gnu.property add-partial
gcc -static -nostdlib -s -Os -fno-asynchronous-unwind-tables \
-fcf-protection=none -Wl,--build-id=none \
-Wl,-z,noseparate-code add-tiny.c -o add-tiny
objcopy --remove-section .comment add-tiny
stat -c '%s %n' add-static add-partial add-tiny
for f in add-static add-partial add-tiny; do ./"$f"; echo "$f exit=$?"; done
785208 add-static
912 add-partial
400 add-tiny
add-static exit=30
add-partial exit=30
add-tiny exit=30
| Build | My recorded figures (June 2026) | add program, this machine | hello world, this machine |
|---|---|---|---|
gcc -static |
about 789 KB | 785,208 | 785,336 |
hand-written assembly through ld |
about 360 | 360 (ld -s -n) |
464 (ld -s -n) |
| C without libc, stripped, notes and padding removed | about 489 | 400 (all levers through Step 8) | 504 |
The test machine’s assembly figure lands on 360 too. The static figure is within a few percent. I don’t have the exact flags, units or environment behind my recorded figures, so I would not expect an exact match. The freestanding C figure depends entirely on which levers you pull: 912 bytes with the partial set, because the unwind tables and .comment stay in, and 400 with everything. My 489 sits between those, and I can’t say which flag set produced it.
What Is Practical and What Is a Toy
Use in real builds: strip release binaries, keeping an unstripped copy or separate debug info. Use -ffunction-sections -fdata-sections -Wl,--gc-sections on large programs with code they never call. Use -Os where size matters more than speed, and measure, because it can be slower.
Learning exercises that break things:
- No libc means no
printf,malloc, threads, locale or buffered I/O. GCC may still emit calls tomemcpy,memset,memmoveandmemcmpon its own, and the GCC manual says you must then supply them. If you need a small static binary for real, link against musl instead of glibc. That has its own trade-offs, which I covered in Linux release builds: glibc is too new and musl cannot load Wayland. -z noseparate-code,-n,-Nput constants (and withnoseparate-code, the headers) into executable memory, and-Nmakes code writable. Writable plus executable memory is what turns a memory-corruption bug into running attacker code.- Overlapping headers, truncated section tables and hand-written ELF headers run on today’s kernel and confuse every debugging tool you own.
The hardening you removed along the way, all on by default in Ubuntu’s GCC:
- PIE: a static non-PIE binary loads at the fixed address
0x400000every time, so address space layout randomization cannot move its code. - RELRO and
-z now: in a dynamic program these make the global offset table read-only after startup, which blocks a classic way of hijacking function calls. - Stack protector:
-nostdlibsilently drops-fstack-protector-strongon Ubuntu, so stack buffer overflows are no longer caught. - CET (
-fcf-protection): addsendbr64landing markers for indirect branches and marks the binary as compatible with shadow stacks. Whether either is enforced depends on the CPU, the kernel and the C library, but stripping the markers rules it out.
None of that matters for eight instructions that take no input. All of it matters for a program that parses anything from outside.
Troubleshooting
Segmentation fault right after _start that uses a local array: the stack is misaligned. With -O2, a 16-byte local char array initialized in _start compiled to movaps [rsp-0x18], xmm0, which requires a 16-byte aligned address. The kernel enters _start with rsp 16-byte aligned, but GCC assumed the usual function-entry state where rsp + 8 is aligned. Add __attribute__((force_align_arg_pointer)) to _start, as tiny.c does, or write _start in assembly and call a C function from it.
Segmentation fault when _start returns: _start has no return address. End it with the exit system call and mark it noreturn.
undefined reference to memcpy (or memset) with -nostdlib: GCC turned a struct copy or array initialization into a library call. Write those functions yourself.
readelf -d file | grep INTERP prints nothing: INTERP is a segment type. Use readelf -l file | grep -A2 INTERP. If readelf -d says “There is no dynamic section in this file”, the binary is statically linked.
Empty NOTE program headers after objcopy -R .note.*: removing note sections after linking deletes the sections but the linker already wrote NOTE and GNU_PROPERTY program headers for them, so they stay behind with zero size and the bytes inside the loadable segment are not reclaimed. Stop the notes from being created in the first place with -fcf-protection=none, -Wl,--build-id=none or a linker script /DISCARD/ rule.
Sizes differ from mine: different GCC, binutils and glibc versions produce different layouts, and Fedora, Arch and others ship different default flags than Ubuntu. Run gcc -Q --help=common | grep -E 'stack-protector|cf-protection|PIE' and ld --help | grep -E 'separate-code|relro' to see your defaults.
Sources and further reading
- System V gABI, ELF Object Files: Introduction supports the fixed-position ELF header and which files need program or section header tables.
- System V gABI, Program Header defines
PT_LOAD,PT_INTERPand the offset/address congruence rule. - elf(5), Linux man-pages covers
e_entry,e_phoff,e_shoffandPT_GNU_STACK. - fs/binfmt_elf.c, Linux kernel shows the loader reading program headers only, handling
PT_INTERP,PT_LOADandPT_GNU_STACK, and rounding the initial stack pointer down to 16 bytes (STACK_ROUND). - syscall_64.tbl, Linux kernel lists
write= 1,exit= 60,exit_group= 231. - entry_64.S, Linux kernel documents the
syscallregister convention and thercx/r11clobbers. - syscall(2), Linux man-pages gives the x86-64 argument and return registers.
- x86/elf: Disable automatic READ_IMPLIES_EXEC on 64-bit is the Linux 5.8 change that made a missing
PT_GNU_STACKmean a non-executable stack on x86-64. - tools/nolibc x86-64 startup fix discussion covers
_startstack alignment versus function-entry alignment. - GCC Link Options for
-nostdlib,-nostartfiles,-static,-sand thememcpy/memsetcaveat. - GCC Optimize Options for
-Os,-ffunction-sectionsand-fdata-sections. - GCC Instrumentation Options for
-fstack-protector-strongand-fcf-protection. - GCC x86 Function Attributes for
force_align_arg_pointer. - GNU ld Command-line Options for
--gc-sections,-n,-N,-z separate-code,-z relro,--build-idand the RWX warning. - GNU ld PHDRS command for
FILEHDR,PHDRSandFLAGS. - GNU objcopy for
--remove-sectionand its warning. - H.J. Lu’s 2018 patch enabling -z separate-code on Linux/x86 for the stated reasons behind the default.
- ld/configure.tgt, binutils 2.47 branch still enables
-z separate-codeby default for Linux/x86. - Ubuntu ToolChain/CompilerFlags lists Ubuntu’s default hardening flags and notes that
-nostdlibdisables the stack protector default. - ldd(1), Linux man-pages for the warning about running
lddon untrusted files. - A Whirlwind Tutorial on Creating Really Teensy ELF Executables for Linux by Brian Raiter, the overlapping-header technique taken to 45 bytes.
- Heavy Wizardry 101, No Starch Press listing via Penguin is the book this exercise came from.