zelf: My Toy Linker vs. the Sections the Compiler Adds

I wrote a small static linker in Zig called zelf. It worked on every object file I built by hand, then failed on the first real compiler output I gave it. The failure was BadTargetSection, with no section name. It turned out the compiler adds a lot of sections nobody asks for (debug info, CET notes, stack-protector and sanitizer references), and my linker had no policy for any of them.

What zelf is

zelf (Zig + ELF; I found out late that it’s also Dutch for self) links one executable as directly as possible: Linux x86-64, ELF64 relocatable objects in, one statically linked binary out. No dynamic loader, no shared libraries. The point wasn’t to compete with real linkers but to see every step between a couple of .o files and a running program.

It has four modules of about a thousand lines each:

  • Reader: parses ELF64 object files into sections, symbols and relocation entries.
  • Relocations: the few x86-64 fixups a static link needs: R_X86_64_64, R_X86_64_PC32, R_X86_64_PLT32 and R_X86_64_GOTPCREL. Without a real global offset table, GOTPCREL reduces to the same arithmetic as PC32, but only once the linker synthesizes a GOT slot for the target or relaxes the mov that loads through it into a lea. That’s not much extra work.
  • Writer: computes the segment layout, emits a program header and a single R+X PT_LOAD, and writes the bytes.
  • CLI: ties them together.

Each module had its own tests, 86 in total, and for a while the loop was pleasant: write a test, watch it fail for the expected reason, make it pass. The final check was a fixture I’d assembled byte by byte to look like what I believed gcc -c produces. The linker accepted it, wrote a valid executable, and it ran in my VM and exited with status 0. I decided I had a linker.

Real compiler output: two unresolved symbols

Next I tried something I hadn’t written myself: the smallest C program I could think of, a _start that calls the Linux exit syscall with a bit of inline assembly.

void _exit(long code) {
    asm volatile ("syscall" : : "a"(60), "D"(code));
    __builtin_unreachable();
}
void _start(void) { _exit(0); }

No globals, no library calls, no data section. I compiled it with the cross-compiler bundled with Zig:

zig cc -target x86_64-linux-gnu -c -fno-PIC -ffreestanding -nostdlib hello.c -o hello.o

My linker said UnresolvedSymbol. Not which symbol, just the error name. That’s a diagnostics bug, not a logic bug. nm told me:

U __ubsan_handle_builtin_unreachable

The clang inside Zig is configured by default to emit a call into the undefined-behavior sanitizer runtime wherever you write __builtin_unreachable(). My “smallest possible program” needed a sanitizer library I wasn’t going to link.

I removed the __builtin_unreachable (I’d only added it out of habit, to tell the compiler the function doesn’t return). The new object had no UBSan reference. The linker now failed to resolve __stack_chk_fail.

Clang was adding a stack-protector guard around _start, with a reference to __stack_chk_fail in case a buffer overrun tripped it. _start has no buffers, so no overrun is possible, but the compiler doesn’t know that.

I added -fno-stack-protector.

BadTargetSection, with no section named

The next error was different: BadTargetSection, again without saying which section.

I tried fixing it with compiler flags:

  • -fno-asynchronous-unwind-tables and -fno-unwind-tables, guessing that clang was emitting .eh_frame sections with relocations my linker didn’t handle.
  • -fcf-protection=none, because recent clang adds .note.gnu.property metadata for Intel CET compatibility.
  • -fno-sanitize=all, in case another sanitizer was involved.
  • -fno-builtin, in case clang replaced my two-instruction _start with an intrinsic.

None of it helped. Every flag was really an apology to my linker for the compiler doing its normal job.

So I skipped C and wrote the program in assembly, expecting an object with nothing but instructions and bookkeeping:

.global _start
.text
_start:
    movq $60, %rax
    xorq %rdi, %rdi
    syscall
zig cc -target x86_64-linux-gnu -c -nostdlib hello.s -o hello.o

A twelve-byte function from six lines of assembly, no C runtime at all. The linker said BadTargetSection again and produced nothing. I was briefly annoyed at Zig.

What readelf showed

When guessing stops working, look at the evidence. I installed GNU binutils and ran readelf -S on the object:

[ 1] .text              PROGBITS  AX
[ 2] .debug_info        PROGBITS
[ 3] .rela.debug_info   RELA
[ 4] .debug_abbrev      PROGBITS
[ 5] .debug_aranges     PROGBITS
[ 6] .rela.debug_aranges RELA
[ 7] .debug_line        PROGBITS
[ 8] .rela.debug_line   RELA
[ 9] .note.GNU-stack    PROGBITS
[10] .symtab            SYMTAB
[11] .shstrtab          STRTAB
[12] .strtab            STRTAB

For a three-instruction function, zig cc had emitted four DWARF debug sections, three relocation sections for them, a note section and the usual metadata. Only .text had the A (allocatable) flag, meaning it gets a place in the executable’s address space.

The relocations were the answer. The object had eight, and every one targeted a .debug_* section, not .text. My linker walked the whole relocation set, looked up each target section, and correctly found that sections like .debug_info existed in the input but had no address and no bytes in the output layout. It treated that as malformed input and stopped.

Real linkers don’t do that. When a linker drops debug information from a static output, it also drops the relocations that point into it. Those relocations have nowhere to go once their targets are gone, so carrying them forward and then complaining about them misunderstands what stripping means.

The fix

Once the problem was clear, the fix was small. A linker has to distinguish three cases for every section index in an input object:

  1. The section is allocatable and laid out in the output. Apply its relocations in place.
  2. The section doesn’t exist, or is a bookkeeping slot with no real content. A relocation against it really is malformed; error out.
  3. The section exists but is non-allocatable (debug info, a comment, a GNU note) and was intentionally dropped. Skip its relocations quietly.

My code treated (2) and (3) as the same error. I added an ignored field to the per-section dispatch table. The CLI marks every non-allocatable section as ignored, and the relocation driver skips relocations that target them instead of failing. About a dozen lines, mostly comments:

// Section exists in the input but was intentionally dropped from the
// output layout because it isn't allocatable (.debug_*, .comment,
// .note.*, etc.). Mark the slot as ignored so any .rela.* relocations
// targeting it are silently skipped rather than erroring out. Real
// linkers behave the same way when stripping debug info.
if ((sec.sh_flags & reader.SHF_ALLOC) == 0) {
    targets[li] = .{ .ignored = true };
}

The next run accepted the unmodified zig cc output of the C program (not the assembly version). It processed 11 symbols and 10 relocations, of which 9 targeted debug sections and were skipped, and produced a valid x86-64 ELF executable that file reported as statically linked. The 86 existing tests still passed, and an 87th now checks that relocations against an ignored section are skipped without emitting anything.

I also added the symbol name to the unresolved-symbol error, so the next person to hit it is told the missing symbol is __stack_chk_fail instead of just that some symbol is missing. The new message is about forty characters longer and would have replaced most of this debugging session.

What I learned

  1. Hand-built test fixtures only test what you already believe. Every object I built by hand contained exactly the sections I thought a linker should handle, because I chose them. A compiler emits a superset: everything it normally produces, whether you asked or not. A linker that only works on its author’s fixtures isn’t quite a linker yet.
  2. A lot of a static linker’s job is deciding what to drop. I pictured a linker as something that collects bytes, places them, patches them and writes them out. For debug sections, notes, comment strings and the other metadata compilers emit, the right action is to not lay them out and to ignore relocations against them. Layout is the chapter every linker tutorial covers; knowing what to discard is what makes a linker work on real input.
  3. Error messages need their subject. BadTargetSection without a section name is a riddle. I had to install binutils, read a section table, cross-check it against the relocations, and work out by elimination that .debug_info and friends were the problem. Putting the section name in the error would have made that one line of output. A tool with worse diagnostics isn’t simpler; it just makes its user do part of its job.

zelf isn’t meant to replace anything. It was a way to understand linking, and the main thing it taught me is that a lot of what a compiler emits is, from the linker’s side, something to set aside.