Definition
Dead-code elimination is the removal of code and data that cannot affect the program’s behavior. It removes unreachable code, which no execution can reach, and dead computations, whose results nothing uses and which have no other effect. A compiler does this as it translates source code. A linker §12.4, the tool that joins compiled pieces into one program, does it for whole sections, the blocks of code or data in those pieces, that nothing refers to. Code present in the source can therefore be absent from the program.
The idea
A firmware source tree contains a function verify_signature. That fact alone does not show that the device checks signatures. The function is in the program only if the build compiled it and the linker kept it, and it runs only if some path from the program’s start reaches a call to it. Each build stage can drop it.
Removal is useful: a library offers a hundred functions, the program uses five, and the other ninety-five should not fill the device’s flash memory §6.6. The picture is packing by following references: start from what the program must have, pack everything it uses, then everything those things use, and leave the rest behind. The picture fails where a use is invisible to the packer: code reached through a table that the linker assembles, through the processor’s table of interrupt handlers §6.12, or through a name looked up at run time. Those are the places where removal goes wrong.
How it works
Three mechanisms remove code, at three stages of the build, by different rules.
Configuration, before compilation. The C preprocessor, the stage that handles the lines that start with
#, deletes the text under an#ifwhose condition is false, often set by a configuration system such as Kconfig §6.40. The compiler never sees that text. Strictly this is not dead-code elimination, but the effect is the same: the feature is compiled out.The compiler. It builds a control-flow graph §3.13 of each function, whose nodes are basic blocks §3.14 (runs of instructions that execute straight through) and whose edges are the possible jumps, and deletes blocks that no path from the entry reaches. For dead computations it marks as live every instruction with an effect outside the function, such as a store to memory that may be read later, a call, an access to a volatile object (memory marked as changeable from outside the program), or the computation of the returned value. It then marks every instruction whose result a live instruction uses, repeats until nothing changes, and deletes what is unmarked. Constant propagation, the replacement of values known at compile time by constants, makes many tests always true or always false and so creates unreachable code. A function visible only in its own file (declared
staticin C) that has no remaining caller is deleted whole.The linker. It can keep or discard only whole input sections. By default the compiler places the code of the functions of one source file together in one section,
.text. The compiler options §12.3-ffunction-sectionsand-fdata-sectionsinstead give every function and every variable a section of its own, named after it: functionmain_initgoes into.text.main_init, zero-initialized variablebufinto.bss.buf. The GNU linker (GNU, a name that stands for GNU’s Not Unix, is the free-software project that publishes it) then removes unreferenced sections when given--gc-sections, where gc abbreviates garbage collection, its manual’s term for this removal.
The GNU linker’s removal runs in three steps.
Start from the root sections: the section holding the program’s entry symbol, the sections holding symbols named on the command line with
-u, and the sections that the linker script §12.5 marks withKEEP.Follow every relocation §12.50, the record of a place in one section that refers to a symbol in another, and mark the section that defines that symbol; repeat for each newly marked section.
Discard every unmarked section. The option
--print-gc-sectionslists them.
Per-function sections also let tools select exactly one function: a linker script can place .text.main_init on its own, at a chosen address, and a tool such as objcopy can copy exactly that function’s bytes out of the linked file. Without the option, the function shares .text with the rest of its file and cannot be selected alone. The GCC §12.17 (GNU Compiler Collection) manual warns that the options make files larger and linking slower, and prevent optimizations that rely on the known distance between functions of one file.
Uses that no reference shows need explicit rules. Registration records for drivers or commands, placed in a named section that the linker gathers into a table, are named by no relocation, so the linker script must wrap them in KEEP. So must the vector table §6.14, the table of handler addresses that the processor reads at reset and on every interrupt §6.11; its relocations then keep the handlers. A function called only from assembly text inside C code, or found by name at run time, needs __attribute__((used)) so that the compiler emits it; that attribute acts on the compiler, not on the linker.
Worked example
A source file util.c defines three functions whose machine code is 120 bytes (crc16), 200 bytes (crc32) and 300 bytes (hexdump). The program calls only crc16, and the link uses --gc-sections.
Without -ffunction-sections, util.o has one .text section of bytes. The call to crc16 refers to that section, so the linker keeps all 620 bytes. With the option, util.o has three sections of 120, 200 and 300 bytes, and only .text.crc16 is reached. The linker discards bytes and keeps 120: since , about 81% of the file’s code is removed.
Now suppose hexdump handles a command of a debug console. A record in a section .cmds registers it, and the console walks the records between the linker-script symbols __cmds_start and __cmds_end. No code refers to the record by name. If the linker script lacks KEEP(*(.cmds)), the linker discards the record, then finds no reference to .text.hexdump and discards the handler too. The build succeeds, and the command is silently missing.
Finally, suppose main.c contains if (CONFIG_VERIFY) verify_signature(img); and the configuration defines CONFIG_VERIFY as 0. The compiler sees if (0) and deletes the call as unreachable; if verify_signature has no other caller, the linker discards it. The source contains the check, and the program does not.
Stated precisely
Linker: let be the set of input sections and the root sections, and write when section contains a relocation that refers to a symbol defined in section . With --gc-sections, the GNU linker keeps exactly the sections reachable from by following zero or more times. holds the section of the entry symbol, the sections of symbols named with -u, the sections that match KEEP, and, when the output is a shared library or exports symbols, the sections of the exported symbols.
Compiler: an instruction or block may be deleted if deleting it leaves the observable behavior (accesses to volatile objects, data written to files, interactive input and output) unchanged for every execution without undefined behavior §4.12. That holds when no execution reaches the code, or when its result is never used and it has no effect of its own.
Both preserve behavior only if the roots are complete: every way control can reach code is a visible reference or a declared root. The ways include the entry point, the vector table, tables the linker assembles, names looked up at run time, and calls from outside the program, such as from a bootloader §6.30 or from code in read-only memory.
Limits and common mistakes
Presence in the source proves nothing. Establish three facts separately: the code is in the linked program (its symbol table §12.8, the linker’s map file or --print-gc-sections output); a path from the entry point reaches it; and it guards every route to the operation it is meant to guard. Keeping code is not running it: KEEP and used preserve bytes but create no call.
A compiler may delete a memset that clears a secret key just before the buffer is freed or goes out of scope, because nothing reads those bytes afterwards. The Common Weakness Enumeration (CWE), a public catalog of software weaknesses, lists this as CWE-14, compiler removal of code to clear buffers. Use a clearing function that the compiler must keep, such as explicit_bzero where the C library offers it or the optional C11 function memset_s, or write the zeros through a pointer to volatile memory.
A check that can fail only after undefined behavior has happened may be deleted. If a pointer is used to read memory and only afterwards compared with a null pointer §4.26, the compiler may conclude that the pointer is not null and remove the comparison.
Code excluded by the preprocessor is not compiled, so its errors go unnoticed until a configuration enables it; code under a C if on a constant is compiled and checked, then removed. Counting source lines measures neither program size nor the trusted computing base §1.4 (the code on whose correctness the system’s security depends).
Questions answered
Can a source feature be present but compiled or linked out?
Yes. A feature present in the source can be absent from the finished program, removed at one of three build stages.
Configuration: the C preprocessor deletes code under an
#ifwhose condition is false, before the compiler sees it.Compilation: dead-code elimination in the compiler deletes code that no execution can reach, such as a call under a condition that is the constant 0, and computations whose results are never used.
Linking: when every function has its own section (the compiler option
-ffunction-sections) and the GNU linker (GNU stands for GNU’s Not Unix) runs with--gc-sections, it discards every function and variable that nothing reachable from the program’s entry refers to, including code registered only through a linker-assembled table that the linker script does not protect withKEEP.
The build succeeds in every case, and no error reports the missing feature.
To know whether a feature is present, examine the linked program, not the source: its symbol table or map file shows whether the code is there, the linker’s --print-gc-sections report shows what was discarded, and a call path from the entry point, confirmed by a test that exercises the feature, shows that it runs.
Related entries: Compiler flag (§12.3), Linker (§12.4), Link-time optimization (LTO) (§12.10), Incremental validation (§10.42), Linker script (§12.5), Compiler optimization (§3.39), Vector table (§6.14). Further reading: [109].