Systems and hardwareDive 03 of 06
From gcc main.c to main()
A call begins as five bytes with a hole. Follow a tiny C program through ELF objects, symbol resolution, relocation, the PLT and GOT, and the loader that makes those bytes runnable.
- Levels
- 7
- Reading
- 42 min
- Depth
- Idea to Machine
- Published
One call · two decisions
The compiler knows the name.
Who knows the address?
You wrote greet(). The compiler leaves four empty bytes. The linker fills them; a shared library adds one more destination to find at runtime.
e8 e8 fe ff ffcall 0x1040 · greet@plt, a local forwarding stubShared build: the call reaches the executable’s PLT. The library’s runtime address lives in the GOT.
Computed from GCC 15.2.0 fixtures; GNU binutils 2.46. Commands and sources appear in level 1; the four-byte calculation is in level 6.
A function you have not built yet
You can compile a call to a function that does not exist yet. Write its declaration, use the right calling convention, and the compiler can generate almost all the instructions. The missing piece is where the call should go. That address might depend on an object file compiled tomorrow, a library somebody else built, or the random address a library receives when your program starts.
Here is the entire application we will follow. main.c asks a library for a greeting and reads an integer from the same library. It then calls printf from libc. greet.c supplies the greeting, counts visits and defines the integer. Every successful build below printshello: 42.
#include <stdio.h>
extern const char *greet(void);
extern int answer;
int main(void) {
printf("%s: %d\n", greet(), answer);
return 0;
}int answer = 42;
int visits;
const char *greet(void) {
++visits;
return "hello";
}The declaration of greet tells the compiler that it takes no arguments and returns a pointer. The declaration of answer tells it the object has type int and is defined elsewhere. Neither declaration allocates the library’s storage or copies the function into this translation unit. Including a header would distribute these same declarations more conveniently; it would not connect the machine code.
This separation is useful long before shared libraries enter the story. A large program has thousands of source files. Changing one function should not force you to recompile all of them. A library author should be able to distribute compiled implementation code and declarations without distributing every implementation detail. Separate compilation provides those boundaries, and a linker connects the pieces.
The linker has two central jobs. Symbol resolution chooses which definition satisfies a name such as greet. Relocation adjusts a reference after the linker knows where the chosen definition, or a forwarding entry for it, will live. Layout connects these jobs: a symbol’s final address depends on where its input section lands in the output file.
main.o · code + undefined symbolsgreet.o · code + data + relocationsMake both versions
These are the commands used for the fixtures on x86-64 Linux. GCC is the driver: it arranges preprocessing, compilation, assembly and linking, and supplies the C runtime’s startup objects and libraries. The -c option stops before linking. The -shared option produces a shared object; ar produces an archive of object files. The driver’s-Wl, prefix forwards comma-separated arguments to the linker.
gcc -O1 -U_FORTIFY_SOURCE -D_FORTIFY_SOURCE=0 -fPIC -fno-asynchronous-unwind-tables -fcf-protection=none -c main.c greet.c
gcc -shared -Wl,-soname,libgreet.so -o libgreet.so greet.o
ar rcs libgreet.a greet.o
gcc -pie -o greet-default main.o -L. -lgreet -Wl,-rpath,'$ORIGIN'
gcc -pie -o greet-lazy main.o -L. -lgreet -Wl,-rpath,'$ORIGIN',-z,lazy,-z,relro
gcc -pie -o greet-now main.o -L. -lgreet -Wl,-rpath,'$ORIGIN',-z,now,-z,relro
gcc -static-pie -o greet-static main.o -L. -lgreet
gcc -pie -o greet-local main.o greet.o
clang-21 -O1 -U_FORTIFY_SOURCE -D_FORTIFY_SOURCE=0 -fPIC -fno-asynchronous-unwind-tables -fcf-protection=none -c main.c -o main-clang.oThere are distinct transformations inside that first compile command. Preprocessing expands includes and macros into a translation unit. Compilation checks declarations, optimizes the program and selects instructions; assembly encodes those instructions into an object. You can stop after preprocessing with -E or request assembly text with -S. The normal driver can run the stages without keeping every intermediate text file. A linker error means the driver reached a later stage than a syntax or type error.
The assembler can encode a call’s opcode before knowing the destination. It emits an instruction template plus a relocation record for the unknown field. The record survives inside the object, so the next tool does not need to rediscover the original C expression. This is also why searching an object file for the string greet does not locate the call instruction: the symbol spelling lives in a string table, and a relocation connects its index to a byte position in the code.
All our own code uses -fPIC, so references can work independently of the final load address. The dynamic executables use -pie; the fully static executable uses -static-pie. We also build greet-local, which includes our function directly but still uses shared libc. That middle case lets us see what happens to exactly the same object instructions when their definitions become local.
Two flags keep the teaching artifacts small: -fno-asynchronous-unwind-tables removes our objects’ asynchronous unwind tables and -fcf-protection=none disables compiler-added control-flow protection in those objects. The system’s startup objects can still contain endbr64. Explicitly disabling _FORTIFY_SOURCE keeps the source call as printf; this Ubuntu compiler otherwise emits __printf_chk. These choices explain the bytes you will see, rather than prescribing production build settings.
There are two different meanings of “static” here. A static library is an archive from which the linker extracts object members. A statically linked executable includes its needed library implementations, including libc in our greet-static build. Linking libgreet.a while leaving libc shared is also possible. “Uses a static library” does not by itself describe the whole executable.
| Build | Where greet lives | Where printf lives | Runtime work |
|---|---|---|---|
| greet-static | Executable | Executable | Static PIE startup relocates itself |
| greet-local | Executable | libc.so.6 | Loader supplies libc |
| greet-lazy / greet-now | libgreet.so | libc.so.6 | Loader supplies both libraries |
Artifact environment: gcc (Ubuntu 15.2.0-16ubuntu1) 15.2.0; Ubuntu clang version 21.1.8 (6ubuntu1); GNU readelf (GNU Binutils for Ubuntu) 2.46; GNU objdump (GNU Binutils for Ubuntu) 2.46; GNU nm (GNU Binutils for Ubuntu) 2.46; GNU ar (GNU Binutils for Ubuntu) 2.46; GNU ld (GNU Binutils for Ubuntu) 2.46; GNU gdb (Ubuntu 17.1-2ubuntu1) 17.1; ldd (Ubuntu GLIBC 2.43-2ubuntu2.7) 2.43; Linux 7.0.0-38-generic. All captures were made in a scratch directory on 15 November 2026.
The compiler can generate a call from a declaration. The linker supplies a destination, and a dynamic loader may finish that decision when the program runs.
An object is bytes plus promises
Open greet.o and you find a structured binary file, not just an instruction stream. Linux commonly uses Executable and Linkable Format: a binary container for relocatable objects, executables, shared libraries and core dumps.. The first bytes identify the format, word size and byte order. Later records describe where code and data live, which names they define, and which references still need adjustment.
An ELF file begins with its header. In this object, EI_CLASS = 2 means ELF64, EI_DATA = 1 means little-endian and e_machine = 62 identifies x86-64. e_type = 1, or ET_REL, says this is a relocatable object. It has no executable entry point and no program-header table. The header’s e_shoff, e_shentsize and e_shnum locate an array of section headers. Those fields are offsets and counts, not pointers into your browser’s memory. The layout follows the ELF header specification.
Use the viewer to decode the real bytes. Start with e_shoff, then choose a section record. Notice how its sh_offset points to a payload while the section record itself sits in the table near the end of the file. Breaking the table offset demonstrates why a parser must validate a range before following it.
File bytes 0x0–0x3f · ELF header
Columns advance by one byte; rows by eight. The outlined field is decoded below.
Decoded record
ELF64 · little-endian · x86-64 Type: ET_REL (1) Header: 64 bytes Section table: 0x1f8 Section count: 11 Program headers: none
e_shoff = f8 01 00 00 00 00 00 00 = 0x1f8
Decoded greet.o: 1208 bytes, 11 sections, 7 symbols, 2 relocations.
Object-only subset: ELF64 LE x86-64 ET_REL, ordinary section numbering, one symbol table, ASCII names ≤128 bytes, 64 KiB input, ≤128 sections and ≤512 symbols/relocations. No groups, compression, TLS symbols, program headers or extended numbering. Sections use types NULL, PROGBITS, SYMTAB, STRTAB, RELA, NOBITS or LLVM_ADDRSIG; Rela types 2, 4, 9, 41, 42.
GCC 15.2.0 / Clang 21.1.8; GNU readelf 2.46: readelf -hW -SW -rW -sW greet.o (or the selected object). Fixture build commands are in level 1.
Sections organize the linker’s inputs
.text holds instructions. .data contains the initialized integer answer = 42, encoded as 2a 00 00 00. .bss reserves four bytes for the zero-initialized visits. The string "hello", including its terminating zero, lands in a read-only string section named .rodata.str1.1. The section name is a convention; its type and flags supply the machine-readable meaning.
.bss is particularly revealing. Its section type is SHT_NOBITS: it has a size but occupies no payload bytes in the file. The eventual program image must provide zero-filled storage. A four-megabyte uninitialized array can therefore increase memory requirements without adding four megabytes of zeroes to the executable. ELF also permits unused padding between sections; neither padding nor a section header is application data. The section specification defines these distinctions.
Compare the decoded header with readelf
GNU readelf (GNU Binutils for Ubuntu) 2.46
$ readelf -hW greet.o
ELF Header:
Magic: 7f 45 4c 46 02 01 01 00 00 00 00 00 00 00 00 00
Class: ELF64
Data: 2's complement, little endian
Version: 1 (current)
OS/ABI: UNIX - System V
ABI Version: 0
Type: REL (Relocatable file)
Machine: Advanced Micro Devices X86-64
Version: 0x1
Entry point address: 0x0
Start of program headers: 0 (bytes into file)
Start of section headers: 504 (bytes into file)
Flags: 0x0
Size of this header: 64 (bytes)
Size of program headers: 0 (bytes)
Number of program headers: 0
Size of section headers: 64 (bytes)
Number of section headers: 11
Section header string table index: 10GNU readelf (GNU Binutils for Ubuntu) 2.46
$ readelf -SW greet.o
There are 11 section headers, starting at offset 0x1f8:
Section Headers:
[Nr] Name Type Address Off Size ES Flg Lk Inf Al
[ 0] NULL 0000000000000000 000000 000000 00 0 0 0
[ 1] .text PROGBITS 0000000000000000 000040 000012 00 AX 0 0 1
[ 2] .rela.text RELA 0000000000000000 000168 000030 18 I 8 1 8
[ 3] .data PROGBITS 0000000000000000 000054 000004 00 WA 0 0 4
[ 4] .bss NOBITS 0000000000000000 000058 000004 00 WA 0 0 4
[ 5] .rodata.str1.1 PROGBITS 0000000000000000 000058 000006 01 AMS 0 0 1
[ 6] .comment PROGBITS 0000000000000000 00005e 000027 01 MS 0 0 1
[ 7] .note.GNU-stack PROGBITS 0000000000000000 000085 000000 00 0 0 1
[ 8] .symtab SYMTAB 0000000000000000 000088 0000a8 18 9 3 8
[ 9] .strtab STRTAB 0000000000000000 000130 000038 00 0 0 1
[10] .shstrtab STRTAB 0000000000000000 000198 000059 00 0 0 1
Key to Flags:
W (write), A (alloc), X (execute), M (merge), S (strings), I (info),
L (link order), O (extra OS processing required), G (group), T (TLS),
C (compressed), x (unknown), o (OS specific), E (exclude),
D (mbind), l (large), p (processor specific)The remaining sections are instructions to the tools. .symtab is an array of symbols. .strtab contains their names, selected by byte offsets. .shstrtab holds section names separately. .rela.text lists adjustments to the text section, each naming a location, a symbol, a relocation type and an explicit signed addend. Debug sections, when requested, describe source lines and types; they are another consumer of the container.
A symbol is more than its spelling
An ELF64 symbol occupies 24 bytes. st_name indexes a string table; st_value and st_size describe its value and extent. st_info packs binding in the high four bits and type in the low four. st_other carries visibility in its low two bits. st_shndx identifies the defining section or a special index such as SHN_UNDEF. These fields follow the ELF symbol-table specification.
In a relocatable file, a defined function’s value is usually an offset within its section. The value zero for greet means the function starts at offset zero of its text section. It does not mean calling it jumps to virtual address zero. An undefined symbol also often has value zero, but its section index is SHN_UNDEF; that index makes the difference.
Binding answers how a name participates in resolution. STB_LOCAL symbols stay within one object. STB_GLOBAL definitions can satisfy other objects. STB_WEAK definitions allow a strong definition to take precedence under the link editor’s rules. Type distinguishes a function from a data object or a section symbol. Visibility controls export and preemption properties: a global symbol can still be hidden from other shared objects.
GCC 15.2.0 · nm -n main.o; nm -n greet.o · binutils 2.46
main.o: U greetneeds a definitiongreet.o: T greetmain.o: U answerneeds an addressgreet.o: D answermain.o: U printfprovided by libcprintf@GLIBC_2.2.5greet.o: B visitszero-initialized storage.bss · 4 bytesT, D and B describe defined symbols in text, initialized data and BSS. U means undefined in this object. These letters summarize the symbol records; the library’s runtime interface uses .dynsym.
GNU readelf (GNU Binutils for Ubuntu) 2.46
$ readelf -sW greet.o
Symbol table '.symtab' contains 7 entries:
Num: Value Size Type Bind Vis Ndx Name
0: 0000000000000000 0 NOTYPE LOCAL DEFAULT UND
1: 0000000000000000 0 FILE LOCAL DEFAULT ABS greet.c
2: 0000000000000000 0 NOTYPE LOCAL DEFAULT 5 .LC0
3: 0000000000000000 18 FUNC GLOBAL DEFAULT 1 greet
4: 0000000000000000 0 NOTYPE GLOBAL DEFAULT UND _GLOBAL_OFFSET_TABLE_
5: 0000000000000000 4 OBJECT GLOBAL DEFAULT 4 visits
6: 0000000000000000 4 OBJECT GLOBAL DEFAULT 3 answerStripping a final executable’s full symbol table does not erase its ability to call libraries. Runtime lookup uses the smaller dynamic symbol table, .dynsym, and dynamic strings. Internal labels useful to a debugger can disappear while exported and imported names needed by the loader remain. Conversely, retaining a name in .symtab does not promise that another shared object can look it up.
This is where languages converge after their earlier checks. The Zig comptime dive follows compile-time evaluation into emitted code and constants. The Rust ownership dive shows what remains after ownership checking. Once those compilers emit native objects, the linker still needs definitions, section layout and relocations. Source-language guarantees do not make addresses known earlier.
Object files preserve the information the compiler could not finish: names, section boundaries and exact places that need adjustment.
Choose definitions, lay out the program
The linker receives main.o and a collection of possible definitions. It builds a symbol table of its own, chooses definitions, extracts needed archive members and assigns output addresses. Only after that layout is known can it finish the numeric references. You can think of an input section as a movable block with labels inside it: moving the block changes every label’s address by the same amount.
An ordinary object named on the command line contributes its contents even if no earlier input asks for them. An archive works differently. libgreet.a contains greet.o and an index of the names that member defines. GNU ld.bfd extracts a member when it satisfies an unresolved reference at the point the archive is processed. Extracting it may introduce further references and cause more members of that archive to be needed.
Why library order matters
Put main.o first and the linker learns that greet and answer are missing. When it encounters the archive, it extracts greet.o to satisfy them. Put the archive first and neither name is needed yet. The linker passes it, later reads main.o and finishes with unresolved references. This is the traditional archive search behavior of the linker used here; other linkers can retain more information or diagnose order differently.
main.o · needs greet, answer↓ archive searchlibgreet.a · extracts greet.oDefinitions foundlibgreet.a · nothing needed yet↓ continuemain.o · needs greet, answerUndefined references remain$ gcc -pie -o bad-order -L. -Wl,-Bstatic -lgreet -Wl,-Bdynamic main.o
/usr/bin/x86_64-linux-gnu-ld.bfd: main.o: in function `main':
main.c:(.text+0x4): undefined reference to `answer'
/usr/bin/x86_64-linux-gnu-ld.bfd: main.c:(.text+0xb): undefined reference to `greet'
collect2: error: ld returned 1 exit status
exit status: 1The practical rule is to place a library after the objects or libraries that need it. For cyclic archive dependencies, --start-group and --end-group tell GNU ld to search a group repeatedly until no more members are extracted. --whole-archive includes all members, which is useful for some registration schemes but can pull in much more code. These options solve distinct problems; wrapping every library in both hides the dependency graph. The GNU ld options manual specifies archive search and grouping.
Archive extraction happens at member granularity. Needing one function from a member can bring in its other functions and data. Compiling with function/data sections and linking with section garbage collection can remove unreferenced sections afterward. An archive does not automatically mean “copy exactly the functions called by main,” and copying a member does not guarantee every section survives final garbage collection.
When two definitions compete
Two ordinary strong definitions of the same externally visible name are normally an error. A weak definition lets a strong one win. An unresolved weak reference may remain zero, so code using an optional weak function must check whether it exists before calling it. None of these rules means the linker checks whether a declaration’s C type agrees with the implementation. Ordinary ELF symbol names are not a complete language-level type system.
This matters when code links successfully but crashes. If one object declares greet with the wrong calling convention or return type, matching the name cannot repair its instructions. C++ name mangling records more signature information in many symbol names, but it is still an ABI contract between producers and consumers. Linking is one boundary of correctness, not the final proof that two pieces agree on all their assumptions.
Sections become a loadable image
After choosing definitions, the linker merges compatible input sections into output sections and places them into A region described by a program header for the execution environment; loadable segments specify file bytes, memory sizes and permissions.. The distinction is essential. Sections are a link-editing view, organized by purpose and name. Program headers describe the execution view: which byte ranges become memory, at which addresses and with which permissions.
Our dynamic executable has four PT_LOAD segments. One is read-only metadata, one is executable code, one is read-only constants and unwind information, and one is writable data. The kernel can map ranges according to those permissions without knowing which bytes are called .text. The .symtab section need not be mapped at all. The ELF program-loading specification describes this execution view.
greet-lazy · readelf -lW · GNU binutils 2.46
Each bar uses the same 0–0x1000 byte scale. Labels give exact segment sizes, before page rounding.
vaddr 0x0 · file offset 0x01680 file bytes / 1680 memory bytes
vaddr 0x1000 · file offset 0x1000389 file bytes / 389 memory bytes
vaddr 0x2000 · file offset 0x2000224 file bytes / 224 memory bytes
vaddr 0x3da8 · file offset 0x2da8632 file bytes / 640 memory bytes
Solid: file-backed contents. Contrasting tail: eight zero-filled bytes in the writable segment. A tiny tail is still drawn at its true size.
GNU readelf (GNU Binutils for Ubuntu) 2.46
$ readelf -lW greet-lazy
Elf file type is DYN (Position-Independent Executable file)
Entry point 0x1060
There are 14 program headers, starting at offset 64
Program Headers:
Type Offset VirtAddr PhysAddr FileSiz MemSiz Flg Align
PHDR 0x000040 0x0000000000000040 0x0000000000000040 0x000310 0x000310 R 0x8
INTERP 0x000374 0x0000000000000374 0x0000000000000374 0x00001c 0x00001c R 0x1
[Requesting program interpreter: /lib64/ld-linux-x86-64.so.2]
LOAD 0x000000 0x0000000000000000 0x0000000000000000 0x000690 0x000690 R 0x1000
LOAD 0x001000 0x0000000000001000 0x0000000000001000 0x000185 0x000185 R E 0x1000
LOAD 0x002000 0x0000000000002000 0x0000000000002000 0x0000e0 0x0000e0 R 0x1000
LOAD 0x002da8 0x0000000000003da8 0x0000000000003da8 0x000278 0x000280 RW 0x1000
DYNAMIC 0x002db8 0x0000000000003db8 0x0000000000003db8 0x000200 0x000200 RW 0x8
NOTE 0x000350 0x0000000000000350 0x0000000000000350 0x000024 0x000024 R 0x4
NOTE 0x0020a0 0x00000000000020a0 0x00000000000020a0 0x000020 0x000020 R 0x8
NOTE 0x0020c0 0x00000000000020c0 0x00000000000020c0 0x000020 0x000020 R 0x4
GNU_PROPERTY 0x0020a0 0x00000000000020a0 0x00000000000020a0 0x000020 0x000020 R 0x8
GNU_EH_FRAME 0x00200c 0x000000000000200c 0x000000000000200c 0x000024 0x000024 R 0x4
GNU_STACK 0x000000 0x0000000000000000 0x0000000000000000 0x000000 0x000000 RW 0x10
GNU_RELRO 0x002da8 0x0000000000003da8 0x0000000000003da8 0x000258 0x000258 R 0x1
Section to Segment mapping:
Segment Sections...
00
01 .interp
02 .note.gnu.build-id .interp .gnu.hash .dynsym .dynstr .gnu.version .gnu.version_r .rela.dyn .rela.plt
03 .init .plt .plt.got .text .fini
04 .rodata .eh_frame_hdr .eh_frame .note.gnu.property .note.ABI-tag
05 .init_array .fini_array .dynamic .got .got.plt .data .bss
06 .dynamic
07 .note.gnu.build-id
08 .note.gnu.property
09 .note.ABI-tag
10 .note.gnu.property
11 .eh_frame_hdr
12
13 .init_array .fini_array .dynamic .gotLook at the writable segment: file offset 0x2da8, virtual address 0x3da8. Their low 12 bits agree, allowing page-aligned mapping at a 4 KiB page size. Its memory size exceeds its file size by eight bytes, which supplies zero-filled storage. The program header’s p_filesz counts file contents, while p_memsz describes the complete memory extent. Bytes in the memory-only tail must start as zero.
Fully static PIE changes the dependency arrangement, not this need for layout. Our greet-static has loadable segments and relocation work but no PT_INTERP requesting a separate loader and no DT_NEEDED entries for libc or libgreet. It still contains a dynamic table used by its startup relocation machinery. Therefore neither ET_DYN nor the presence of .dynamic alone proves an executable depends on shared libraries.
Inspect the static PIE program headers and dynamic table
GNU readelf (GNU Binutils for Ubuntu) 2.46
$ readelf -lW greet-static
Elf file type is DYN (Position-Independent Executable file)
Entry point 0x7760
There are 13 program headers, starting at offset 64
Program Headers:
Type Offset VirtAddr PhysAddr FileSiz MemSiz Flg Align
LOAD 0x000000 0x0000000000000000 0x0000000000000000 0x006d10 0x006d10 R 0x1000
LOAD 0x007000 0x0000000000007000 0x0000000000007000 0x085d4d 0x085d4d R E 0x1000
LOAD 0x08d000 0x000000000008d000 0x000000000008d000 0x0280b8 0x0280b8 R 0x1000
LOAD 0x0b5ec8 0x00000000000b6ec8 0x00000000000b6ec8 0x005ab0 0x00b280 RW 0x1000
DYNAMIC 0x0b9ce8 0x00000000000bace8 0x00000000000bace8 0x0001b0 0x0001b0 RW 0x8
NOTE 0x000318 0x0000000000000318 0x0000000000000318 0x000024 0x000024 R 0x4
NOTE 0x0b5078 0x00000000000b5078 0x00000000000b5078 0x000020 0x000020 R 0x8
NOTE 0x0b5098 0x00000000000b5098 0x00000000000b5098 0x000020 0x000020 R 0x4
TLS 0x0b5ec8 0x00000000000b6ec8 0x00000000000b6ec8 0x000038 0x000050 R 0x8
GNU_PROPERTY 0x0b5078 0x00000000000b5078 0x00000000000b5078 0x000020 0x000020 R 0x8
GNU_EH_FRAME 0x0a9720 0x00000000000a9720 0x00000000000a9720 0x0021b4 0x0021b4 R 0x4
GNU_STACK 0x000000 0x0000000000000000 0x0000000000000000 0x000000 0x000000 RW 0x10
GNU_RELRO 0x0b5ec8 0x00000000000b6ec8 0x00000000000b6ec8 0x004138 0x004138 R 0x1
Section to Segment mapping:
Segment Sections...
00 .note.gnu.build-id .gnu.hash .dynsym .dynstr .rela.dyn .rela.plt
01 .init .plt .plt.got .text .fini
02 .rodata .stapsdt.base rodata.cst32 .eh_frame_hdr .eh_frame .gcc_except_table .note.gnu.property .note.ABI-tag
03 .tdata .init_array .fini_array .data.rel.ro .dynamic .got .data .bss
04 .dynamic
05 .note.gnu.build-id
06 .note.gnu.property
07 .note.ABI-tag
08 .tdata .tbss
09 .note.gnu.property
10 .eh_frame_hdr
11
12 .tdata .init_array .fini_array .data.rel.ro .dynamic .gotGNU readelf (GNU Binutils for Ubuntu) 2.46
$ readelf -dW greet-static
Dynamic section at offset 0xb9ce8 contains 23 entries:
Tag Type Name/Value
0x000000000000000c (INIT) 0x7000
0x000000000000000d (FINI) 0x8cd40
0x0000000000000019 (INIT_ARRAY) 0xb6f00
0x000000000000001b (INIT_ARRAYSZ) 16 (bytes)
0x000000000000001a (FINI_ARRAY) 0xb6f10
0x000000000000001c (FINI_ARRAYSZ) 16 (bytes)
0x000000006ffffef5 (GNU_HASH) 0x340
0x0000000000000005 (STRTAB) 0x378
0x0000000000000006 (SYMTAB) 0x360
0x000000000000000a (STRSZ) 1 (bytes)
0x000000000000000b (SYMENT) 24 (bytes)
0x0000000000000015 (DEBUG) 0x0
0x0000000000000003 (PLTGOT) 0xbae98
0x0000000000000002 (PLTRELSZ) 528 (bytes)
0x0000000000000014 (PLTREL) RELA
0x0000000000000017 (JMPREL) 0x6b00
0x0000000000000007 (RELA) 0x380
0x0000000000000008 (RELASZ) 26496 (bytes)
0x0000000000000009 (RELAENT) 24 (bytes)
0x000000000000001e (FLAGS) BIND_NOW
0x000000006ffffffb (FLAGS_1) Flags: NOW PIE
0x000000006ffffff9 (RELACOUNT) 1104
0x0000000000000000 (NULL) 0x0The link editor chooses definitions and layout. Program headers then describe the memory image, independently of the section names that helped build it.
Leave a door open for a library
A shared library lets the executable carry a dependency instead of a copy of the library’s implementation. Our executable records libgreet.so and libc.so.6 as DT_NEEDED entries. Their final addresses are unknown when the executable is linked. The dynamic loader must find those files, map them and connect references between them.
Position-independent executable: an executable built so it can run at different load addresses, commonly represented as ELF ET_DYN on Linux. makes it practical to randomize the executable’s load address. Shared objects are also built to tolerate different bases. For an object loaded with biasB, an ordinary defined symbol at link-time virtual address v appears at B + v. Each object has its own bias. ASLR changes those biases across runs; it does not randomly rearrange every instruction within an object.
PT_INTERP: /lib64/ld-linux-x86-64.so.2The kernel loads the interpreter.greet · answer · visits$ORIGIN RUNPATH finds our sibling file.printf · __libc_start_mainShared library search finds glibc.Captured with readelf -dW greet-lazy and readelf -lW greet-lazy, binutils 2.46. PT_INTERP selects the loader; DT_NEEDED names the libraries.
The .dynamic table is a sequence of tags and values terminated by DT_NULL. It points to dynamic strings, symbols, relocation tables, initialization arrays and other loader inputs. Some values are addresses; some are sizes, flags or string offsets. DT_NEEDED, for example, is an offset into the dynamic string table, rather than a pointer to the library’s mapping.
Our library is found through the executable’s DT_RUNPATH of$ORIGIN, expanded by the loader to the executable’s directory. The shell quotes in the build command preserve that literal dollar sign. RUNPATH applies to direct dependencies of the object carrying it; it is not automatically inherited down every dependency chain. The loader also has rules for environment paths, its cache, default directories and secure execution. The ld.so manual gives the search order.
GNU readelf (GNU Binutils for Ubuntu) 2.46
$ readelf -dW greet-lazy
Dynamic section at offset 0x2db8 contains 28 entries:
Tag Type Name/Value
0x0000000000000001 (NEEDED) Shared library: [libgreet.so]
0x0000000000000001 (NEEDED) Shared library: [libc.so.6]
0x000000000000001d (RUNPATH) Library runpath: [$ORIGIN]
0x000000000000000c (INIT) 0x1000
0x000000000000000d (FINI) 0x1178
0x0000000000000019 (INIT_ARRAY) 0x3da8
0x000000000000001b (INIT_ARRAYSZ) 8 (bytes)
0x000000000000001a (FINI_ARRAY) 0x3db0
0x000000000000001c (FINI_ARRAYSZ) 8 (bytes)
0x000000006ffffef5 (GNU_HASH) 0x390
0x0000000000000005 (STRTAB) 0x490
0x0000000000000006 (SYMTAB) 0x3b8
0x000000000000000a (STRSZ) 176 (bytes)
0x000000000000000b (SYMENT) 24 (bytes)
0x0000000000000015 (DEBUG) 0x0
0x0000000000000003 (PLTGOT) 0x3fe8
0x0000000000000002 (PLTRELSZ) 48 (bytes)
0x0000000000000014 (PLTREL) RELA
0x0000000000000017 (JMPREL) 0x660
0x0000000000000007 (RELA) 0x588
0x0000000000000008 (RELASZ) 216 (bytes)
0x0000000000000009 (RELAENT) 24 (bytes)
0x000000006ffffffb (FLAGS_1) Flags: PIE
0x000000006ffffffe (VERNEED) 0x558
0x000000006fffffff (VERNEEDNUM) 1
0x000000006ffffff0 (VERSYM) 0x540
0x000000006ffffff9 (RELACOUNT) 3
0x0000000000000000 (NULL) 0x0Put the unknown address in writable data
Rewriting every call instruction at runtime would dirty code pages and make sharing them harder. Instead, the linker can point a call at a nearby forwarding stub in the Procedure linkage table: executable stubs that route external function calls through dynamically initialized address slots.. The stub jumps indirectly through a slot in the Global offset table: address slots used by position-independent code and updated by link-time or runtime relocation.. The call’s relative distance to its own PLT is fixed when linking; the slot can hold the library’s runtime address.
In our explicitly lazy build, greet@plt initially jumps back into the continuation of its own PLT entry. That continuation pushes an index and jumps to the common PLT resolver entry. The runtime resolver uses the associated R_X86_64_JUMP_SLOT relocation to identify the symbol, looks it up and writes the address into the slot. It then transfers to the function with the original call’s arguments intact. Later calls take the same initial indirect jump, which now reaches the function directly.
Real slot 0x5a8965a69008 · PIE base 0x5a8965a65000 · glibc 2.43 / GDB 17.1. This is the explicitly lazy build.
Before the first call
GOT slot still points into the PLTcall greet@plt
jmp *greet@got.plt(%rip)Ask the runtime resolver
push relocation index; jump to PLT0Enter the real function
GOT slot now contains the definitionA later call takes the shortcut
jmp *greet@got.plt(%rip)- GDB stopped at main; ld.so has already rebased the slot’s initial pointer.
- The indirect jump reads the slot and lands on the PLT entry’s push instruction.
- The trampoline preserves the call’s arguments while resolving the JUMP_SLOT entry.
- GDB stopped at greet’s entry. The slot changed from the PLT continuation to this function.
- The same indirect jump now reaches the resolved function without another name lookup.
Capture: gdb -q -nx -batch -x binding.gdb ./greet-lazy. The script and raw output are below. Middle transitions follow the captured PLT instructions; the two slot values were measured.
Reproduce the GOT observation with GDB
set debuginfod enabled off
set pagination off
set disable-randomization off
start
set $base = (long)&main - 4425
set $slot = $base + 16392
printf "PIE base: %#lx; greet GOT slot: %#lx\n", $base, $slot
printf "Before first greet call\n"
x/gx $slot
x/3i *(void **)$slot
python print("PROC_MAPS_BEGIN\n" + open("/proc/%d/maps" % gdb.selected_inferior().pid).read() + "PROC_MAPS_END")
info auxv
break greet
continue
printf "At greet entry, after resolver\n"
x/gx $slot
x/i *(void **)$slot
continueGNU gdb (Ubuntu 17.1-2ubuntu1) 17.1
$ gdb -q -nx -batch -x binding.gdb ./greet-lazy
This GDB supports auto-downloading debuginfo from the following URLs:
<https://debuginfod.ubuntu.com>
Enable debuginfod for this session? (y or [n]) [answered N; input not from terminal]
Debuginfod has been disabled.
To make this setting permanent, add 'set debuginfod enabled off' to .gdbinit.
Temporary breakpoint 1 at 0x1149
[Thread debugging using libthread_db enabled]
Using host libthread_db library "/usr/lib/x86_64-linux-gnu/libthread_db.so.1".
Temporary breakpoint 1, 0x00005a8965a66149 in main ()
PIE base: 0x5a8965a65000; greet GOT slot: 0x5a8965a69008
Before first greet call
0x5a8965a69008 <greet@got.plt>: 0x00005a8965a66046
0x5a8965a66046 <greet@plt+6>: push $0x1
0x5a8965a6604b <greet@plt+11>: jmp 0x5a8965a66020
0x5a8965a66050 <__cxa_finalize@plt>: jmp *0x2f8a(%rip) # 0x5a8965a68fe0
PROC_MAPS_BEGIN
5a8965a65000-5a8965a66000 r--p 00000000 00:33 27671453 /tmp/claude-1000/-home-r-Projects-undefinedstack/ab631be5-67b3-4b6a-a237-985dffd4d9af/scratchpad/linking/greet-lazy
5a8965a66000-5a8965a67000 r-xp 00001000 00:33 27671453 /tmp/claude-1000/-home-r-Projects-undefinedstack/ab631be5-67b3-4b6a-a237-985dffd4d9af/scratchpad/linking/greet-lazy
5a8965a67000-5a8965a68000 r--p 00002000 00:33 27671453 /tmp/claude-1000/-home-r-Projects-undefinedstack/ab631be5-67b3-4b6a-a237-985dffd4d9af/scratchpad/linking/greet-lazy
5a8965a68000-5a8965a69000 r--p 00002000 00:33 27671453 /tmp/claude-1000/-home-r-Projects-undefinedstack/ab631be5-67b3-4b6a-a237-985dffd4d9af/scratchpad/linking/greet-lazy
5a8965a69000-5a8965a6a000 rw-p 00003000 00:33 27671453 /tmp/claude-1000/-home-r-Projects-undefinedstack/ab631be5-67b3-4b6a-a237-985dffd4d9af/scratchpad/linking/greet-lazy
77563a200000-77563a228000 r--p 00000000 fc:01 33557279 /usr/lib/x86_64-linux-gnu/libc.so.6
77563a228000-77563a3c0000 r-xp 00028000 fc:01 33557279 /usr/lib/x86_64-linux-gnu/libc.so.6
77563a3c0000-77563a40e000 r--p 001c0000 fc:01 33557279 /usr/lib/x86_64-linux-gnu/libc.so.6
77563a40e000-77563a412000 r--p 0020e000 fc:01 33557279 /usr/lib/x86_64-linux-gnu/libc.so.6
77563a412000-77563a414000 rw-p 00212000 fc:01 33557279 /usr/lib/x86_64-linux-gnu/libc.so.6
77563a414000-77563a421000 rw-p 00000000 00:00 0
77563a481000-77563a484000 rw-p 00000000 00:00 0
77563a49c000-77563a49d000 r--p 00000000 00:33 27671423 /tmp/claude-1000/-home-r-Projects-undefinedstack/ab631be5-67b3-4b6a-a237-985dffd4d9af/scratchpad/linking/libgreet.so
77563a49d000-77563a49e000 r-xp 00001000 00:33 27671423 /tmp/claude-1000/-home-r-Projects-undefinedstack/ab631be5-67b3-4b6a-a237-985dffd4d9af/scratchpad/linking/libgreet.so
77563a49e000-77563a49f000 r--p 00002000 00:33 27671423 /tmp/claude-1000/-home-r-Projects-undefinedstack/ab631be5-67b3-4b6a-a237-985dffd4d9af/scratchpad/linking/libgreet.so
77563a49f000-77563a4a0000 r--p 00002000 00:33 27671423 /tmp/claude-1000/-home-r-Projects-undefinedstack/ab631be5-67b3-4b6a-a237-985dffd4d9af/scratchpad/linking/libgreet.so
77563a4a0000-77563a4a1000 rw-p 00003000 00:33 27671423 /tmp/claude-1000/-home-r-Projects-undefinedstack/ab631be5-67b3-4b6a-a237-985dffd4d9af/scratchpad/linking/libgreet.so
77563a4a1000-77563a4a3000 rw-p 00000000 00:00 0
77563a4a3000-77563a4a7000 r--p 00000000 00:00 0 [vvar]
77563a4a7000-77563a4a9000 r--p 00000000 00:00 0 [vvar_vclock]
77563a4a9000-77563a4ab000 r-xp 00000000 00:00 0 [vdso]
77563a4ab000-77563a4ac000 r--p 00000000 fc:01 33557272 /usr/lib/x86_64-linux-gnu/ld-linux-x86-64.so.2
77563a4ac000-77563a4db000 r-xp 00001000 fc:01 33557272 /usr/lib/x86_64-linux-gnu/ld-linux-x86-64.so.2
77563a4db000-77563a4e6000 r--p 00030000 fc:01 33557272 /usr/lib/x86_64-linux-gnu/ld-linux-x86-64.so.2
77563a4e6000-77563a4e8000 r--p 0003b000 fc:01 33557272 /usr/lib/x86_64-linux-gnu/ld-linux-x86-64.so.2
77563a4e8000-77563a4e9000 rw-p 0003d000 fc:01 33557272 /usr/lib/x86_64-linux-gnu/ld-linux-x86-64.so.2
77563a4e9000-77563a4ea000 rw-p 00000000 00:00 0
7ffed0a92000-7ffed0ab4000 rw-p 00000000 00:00 0 [stack]
ffffffffff600000-ffffffffff601000 --xp 00000000 00:00 0 [vsyscall]
PROC_MAPS_END
33 AT_SYSINFO_EHDR System-supplied DSO's ELF header 0x77563a4a9000
51 AT_MINSIGSTKSZ Minimum stack size for signal delivery 0xe30
16 AT_HWCAP Machine-dependent CPU capability hints 0xbfebfbff
6 AT_PAGESZ System page size 4096
17 AT_CLKTCK Frequency of times() 100
3 AT_PHDR Program headers for program 0x5a8965a65040
4 AT_PHENT Size of program header entry 56
5 AT_PHNUM Number of program headers 14
7 AT_BASE Base address of interpreter 0x77563a4ab000
8 AT_FLAGS Flags 0x0
9 AT_ENTRY Entry point of program 0x5a8965a66060
11 AT_UID Real user ID 1000
12 AT_EUID Effective user ID 1000
13 AT_GID Real group ID 1000
14 AT_EGID Effective group ID 1000
23 AT_SECURE Boolean, was exec setuid-like? 0
25 AT_RANDOM Address of 16 random bytes 0x7ffed0ab12a9
26 AT_HWCAP2 Extension of AT_HWCAP 0x2
31 AT_EXECFN File name of executable 0x7ffed0ab3f84 "/tmp/claude-1000/-home-r-Projects-undefinedstack/ab631be5-67b3-4b6a-a237-985dffd4d9af/scratchpad/linking/greet-lazy"
15 AT_PLATFORM String identifying platform 0x7ffed0ab12b9 "x86_64"
27 AT_RSEQ_FEATURE_SIZE rseq supported feature size 33
28 AT_RSEQ_ALIGN rseq allocation alignment 64
0 AT_NULL End of vector 0x0
Breakpoint 2 at 0x77563a49d0f9
Breakpoint 2, 0x000077563a49d0f9 in greet () from /tmp/claude-1000/-home-r-Projects-undefinedstack/ab631be5-67b3-4b6a-a237-985dffd4d9af/scratchpad/linking/libgreet.so
At greet entry, after resolver
0x5a8965a69008 <greet@got.plt>: 0x000077563a49d0f9
=> 0x77563a49d0f9 <greet>: mov 0x2ed8(%rip),%rax # 0x77563a49ffd8
hello: 42
[Inferior 1 (process 2710804) exited normally]GNU readelf (GNU Binutils for Ubuntu) 2.46
$ readelf -rW greet-lazy
Relocation section '.rela.dyn' at offset 0x588 contains 9 entries:
Offset Info Type Symbol's Value Symbol's Name + Addend
0000000000003da8 0000000000000008 R_X86_64_RELATIVE 1140
0000000000003db0 0000000000000008 R_X86_64_RELATIVE 1100
0000000000004018 0000000000000008 R_X86_64_RELATIVE 4018
0000000000003fb8 0000000100000006 R_X86_64_GLOB_DAT 0000000000000000 __libc_start_main@GLIBC_2.34 + 0
0000000000003fc0 0000000200000006 R_X86_64_GLOB_DAT 0000000000000000 _ITM_deregisterTMCloneTable + 0
0000000000003fc8 0000000500000006 R_X86_64_GLOB_DAT 0000000000000000 __gmon_start__ + 0
0000000000003fd0 0000000600000006 R_X86_64_GLOB_DAT 0000000000000000 answer + 0
0000000000003fd8 0000000700000006 R_X86_64_GLOB_DAT 0000000000000000 _ITM_registerTMCloneTable + 0
0000000000003fe0 0000000800000006 R_X86_64_GLOB_DAT 0000000000000000 __cxa_finalize@GLIBC_2.2.5 + 0
Relocation section '.rela.plt' at offset 0x660 contains 2 entries:
Offset Info Type Symbol's Value Symbol's Name + Addend
0000000000004000 0000000300000007 R_X86_64_JUMP_SLOT 0000000000000000 printf@GLIBC_2.2.5 + 0
0000000000004008 0000000400000007 R_X86_64_JUMP_SLOT 0000000000000000 greet + 0Not every external reference waits for a function call. The GOT entry for the data symbol answer uses R_X86_64_GLOB_DAT and is filled during loading. Relative pointer relocations can often add the load bias without a symbol-name search. Function pointer use, compiler options such as -fno-plt, linker optimizations and architecture conventions can all change the path. The PLT sequence above is the actual x86-64 sequence emitted for these flags.
Lazy binding is a policy choice
Our unqualified GCC link already sets BIND_NOW. We explicitly pass -z lazy to observe first-call resolution, and-z now to build the eager comparison. With eager binding, required PLT slots are resolved before main, so the first call does not need the lazy resolver. Check the binary’s flags rather than inferring policy from the presence of a PLT section.
GNU readelf (GNU Binutils for Ubuntu) 2.46
$ readelf -dW greet-default
0x000000000000001e (FLAGS) BIND_NOW
0x000000006ffffffb (FLAGS_1) Flags: NOW PIESelected lines from the capture; addresses belong to this build or run.
| Policy | When greet is resolved | GOT protection |
|---|---|---|
| -z lazy -z relro | First call | Lazy slots stay writable outside the protected range |
| -z now -z relro | Startup | Linker can include all required GOT slots in the RELRO range |
PT_GNU_RELRO identifies memory that the loader can make read-only after relocation. It covers data that needs initialization writes but no later mutation. Full GOT protection requires completing the relevant relocations before applying that protection. Lazy binding needs its slots to remain writable. RELRO changes a page’s permissions; it does not eliminate indirection or make a writable C global immutable.
Which definition wins at runtime?
Dynamic lookup uses a scope of objects, not simply the file containing the caller. A default-visible definition in a shared object can be interposed by another definition earlier in the lookup scope, such as one supplied by an LD_PRELOAD library. This supports instrumentation and replacement, but it also limits optimizations: an internal reference may have to honor the replacement instead of assuming its own definition wins.
-fvisibility=hidden changes the default visibility of definitions you compile; public API symbols can then be explicitly marked default-visible.-Bsymbolic, when linking a shared object, binds references within it to its own definitions where applicable. These are different choices with ABI consequences, especially for object identity and shared data. Applying them casually can make two pieces of the program disagree about whether they refer to the same object.
Versions add another dimension to a dynamic symbol. Our imported printf appears as printf@GLIBC_2.2.5. The version name identifies a required ABI version, not the installed glibc release: this run uses glibc 2.43. Our executable also requires a newer version of __libc_start_main. Linking on a new system can therefore create requirements an older target cannot satisfy even though the target contains a function with the same unversioned name.
GNU readelf (GNU Binutils for Ubuntu) 2.46
$ readelf -sW greet-lazy
1: 0000000000000000 0 FUNC GLOBAL DEFAULT UND __libc_start_main@GLIBC_2.34 (2)
3: 0000000000000000 0 FUNC GLOBAL DEFAULT UND printf@GLIBC_2.2.5 (3)
8: 0000000000000000 0 FUNC WEAK DEFAULT UND __cxa_finalize@GLIBC_2.2.5 (3)
18: 0000000000000000 0 FUNC GLOBAL DEFAULT UND __libc_start_main@GLIBC_2.34
23: 0000000000000000 0 FUNC GLOBAL DEFAULT UND printf@GLIBC_2.2.5
36: 0000000000000000 0 FUNC WEAK DEFAULT UND __cxa_finalize@GLIBC_2.2.5Selected lines from the capture; addresses belong to this build or run.
Position-independent code keeps stable relative references in instructions and puts runtime-dependent addresses in relocatable data.
A file becomes a running process
The executable is a file until a process asks the kernel to execute it. On Linux, execve replaces the calling process’s program image. The ELF handler checks the file, establishes the new address space, maps the executable’s loadable segments and prepares the initial user stack. WhenPT_INTERP is present, it also maps the named interpreter and starts execution at that interpreter’s entry.
The kernel does not resolve greet, inspect C declarations or search libc’s dynamic symbol table. Those are user-space loader jobs. The syscall boundary explains the handoff: the kernel builds the initial execution environment, then returns to user mode with the instruction pointer aimed at the interpreter. The system-call dive examines that privilege boundary, and Linux’s ELF execution handler shows the loading path.
The initial stack contains the argument count, pointers to argument strings, environment pointers and an An array of type/value entries supplied at process startup, giving the runtime facts such as program headers, page size and entry address.. Entries such as AT_PHDR, AT_PHNUM, AT_BASE and AT_ENTRY let the interpreter locate the executable’s headers and eventual entry point. AT_RANDOM points to kernel-supplied random bytes used by runtime security mechanisms.
Kernel · execve
Map the executable and interpreter
PT_LOAD establishes the executable mappings. PT_INTERP names ld-linux-x86-64.so.2.
argc · argv · environment · auxiliary vectorld.so · bootstrap
Make the loader’s own references usable
Apply the bootstrap relocations needed to use loader code and data at its chosen load address.
AT_PHDR · AT_PHNUM · AT_BASE · AT_ENTRYld.so · dependencies
Find and map the shared objects
Read DT_NEEDED, search for libgreet.so and libc.so.6, and map their loadable segments.
Per-object link maps · lookup scopesld.so · relocations and TLS
Make pointers and thread storage valid
Apply required relocations; resolve eager calls and IFUNCs when required. Install the initial thread’s TLS.
GOT · relative pointers · TLS module offsetsLoader and C runtime · initialization
Run initialization, enter the startup code
Dependency initializers run before normal program execution. The executable’s startup path arranges its own initialization before main.
preinit_array · DT_INIT · init_arrayC runtime · _start
Call main with a prepared process
_start extracts the startup arguments and calls __libc_start_main. The runtime calls main, then performs exit handling.
main(argc, argv, envp) · ABI-defined registers- execve replaces the process image. With PT_INTERP, the kernel starts the interpreter rather than jumping straight to the program’s entry point.
- The auxiliary vector carries the program headers and entry address. The interpreter uses a restricted bootstrap path before ordinary symbol resolution is available.
- The same library file can back mappings in many processes. Each process has its own addresses and writable relocation state.
- Lazy JUMP_SLOT lookup can remain deferred. Other required relocations and TLS setup must finish before code that depends on them runs.
- On this glibc path the loader runs dependency initializers, then transfers to _start; __libc_start_main handles the executable’s initialization before main.
- Returning from main enters the runtime’s exit path: exit handlers, stream flushing and process termination. _start itself has no C caller to return to.
The loader has a bootstrap problem
The interpreter is itself position-independent code. Before it can use ordinary loader routines and global state, it must make its own early references usable. glibc uses a restricted bootstrap relocation path for this. It then reads the executable’s dynamic metadata, discovers dependencies and creates bookkeeping for the mapped objects and their lookup scopes. The glibc runtime-loader source exposes the bootstrap and main loading phases.
Mapping a segment establishes virtual memory regions backed by parts of files or zero-filled memory. It does not require eagerly reading every instruction page into physical RAM. A later page fault can bring in a page when code or data is touched. That is the connection to the virtual-memory dive: the loader arranges mappings and permissions; the kernel and MMU service actual accesses.
The loader’s diagnostics let us watch the dependency search. In the capture below, the executable’s RUNPATH leads to our sibling libgreet.so. The symbol trace shows lookup through scopes, while the binding trace records the selected definition. A lookup message is an attempt; a binding message is a result. These logs also include runtime-support symbols that our source never mentions.
ldd (Ubuntu GLIBC 2.43-2ubuntu2.7) 2.43
$ LD_DEBUG=libs ./greet-lazy
2710740: find library=libgreet.so [0]; searching
2710740: search path=/tmp/.mount_T3-CodpLLGmF/usr/lib/glibc-hwcaps/x86-64-v3:/tmp/.mount_T3-CodpLLGmF/usr/lib/glibc-hwcaps/x86-64-v2:/tmp/.mount_T3-CodpLLGmF/usr/lib:/tmp/.mount_T3-CodooHLMo/usr/lib/glibc-hwcaps/x86-64-v3:/tmp/.mount_T3-CodooHLMo/usr/lib/glibc-hwcaps/x86-64-v2:/tmp/.mount_T3-CodooHLMo/usr/lib (LD_LIBRARY_PATH)
2710740: trying file=/tmp/.mount_T3-CodpLLGmF/usr/lib/glibc-hwcaps/x86-64-v3/libgreet.so
2710740: (no such file)
2710740: trying file=/tmp/.mount_T3-CodpLLGmF/usr/lib/glibc-hwcaps/x86-64-v2/libgreet.so
2710740: (no such file)
2710740: trying file=/tmp/.mount_T3-CodpLLGmF/usr/lib/libgreet.so
2710740: (no such file)
2710740: trying file=/tmp/.mount_T3-CodooHLMo/usr/lib/glibc-hwcaps/x86-64-v3/libgreet.so
2710740: (no such file)
2710740: trying file=/tmp/.mount_T3-CodooHLMo/usr/lib/glibc-hwcaps/x86-64-v2/libgreet.so
2710740: (no such file)
2710740: trying file=/tmp/.mount_T3-CodooHLMo/usr/lib/libgreet.so
2710740: (no such file)
2710740: search path=/tmp/claude-1000/-home-r-Projects-undefinedstack/ab631be5-67b3-4b6a-a237-985dffd4d9af/scratchpad/linking/glibc-hwcaps/x86-64-v3:/tmp/claude-1000/-home-r-Projects-undefinedstack/ab631be5-67b3-4b6a-a237-985dffd4d9af/scratchpad/linking/glibc-hwcaps/x86-64-v2:/tmp/claude-1000/-home-r-Projects-undefinedstack/ab631be5-67b3-4b6a-a237-985dffd4d9af/scratchpad/linking (RUNPATH from file ./greet-lazy)
2710740: trying file=/tmp/claude-1000/-home-r-Projects-undefinedstack/ab631be5-67b3-4b6a-a237-985dffd4d9af/scratchpad/linking/glibc-hwcaps/x86-64-v3/libgreet.so
2710740: (no such file)
2710740: trying file=/tmp/claude-1000/-home-r-Projects-undefinedstack/ab631be5-67b3-4b6a-a237-985dffd4d9af/scratchpad/linking/glibc-hwcaps/x86-64-v2/libgreet.so
2710740: (no such file)
2710740: trying file=/tmp/claude-1000/-home-r-Projects-undefinedstack/ab631be5-67b3-4b6a-a237-985dffd4d9af/scratchpad/linking/libgreet.so
2710740:
2710740: find library=libc.so.6 [0]; searching
2710740: search path=/tmp/.mount_T3-CodpLLGmF/usr/lib:/tmp/.mount_T3-CodooHLMo/usr/lib (LD_LIBRARY_PATH)
2710740: trying file=/tmp/.mount_T3-CodpLLGmF/usr/lib/libc.so.6
2710740: (no such file)
2710740: trying file=/tmp/.mount_T3-CodooHLMo/usr/lib/libc.so.6
2710740: (no such file)
2710740: search path=/tmp/claude-1000/-home-r-Projects-undefinedstack/ab631be5-67b3-4b6a-a237-985dffd4d9af/scratchpad/linking (RUNPATH from file ./greet-lazy)
2710740: trying file=/tmp/claude-1000/-home-r-Projects-undefinedstack/ab631be5-67b3-4b6a-a237-985dffd4d9af/scratchpad/linking/libc.so.6
2710740: (no such file)
2710740: search cache=/etc/ld.so.cache
2710740: trying file=/usr/lib/x86_64-linux-gnu/libc.so.6Selected lines from the capture; addresses belong to this build or run.
ldd (Ubuntu GLIBC 2.43-2ubuntu2.7) 2.43
$ LD_DEBUG=symbols ./greet-lazy
2710744: symbol=greet; lookup in file=./greet-lazy [0]
2710744: symbol=greet; lookup in file=/tmp/claude-1000/-home-r-Projects-undefinedstack/ab631be5-67b3-4b6a-a237-985dffd4d9af/scratchpad/linking/libgreet.so [0]Selected lines from the capture; addresses belong to this build or run.
ldd (Ubuntu GLIBC 2.43-2ubuntu2.7) 2.43
$ LD_DEBUG=bindings ./greet-lazy
2710747: binding file ./greet-lazy [0] to /tmp/claude-1000/-home-r-Projects-undefinedstack/ab631be5-67b3-4b6a-a237-985dffd4d9af/scratchpad/linking/libgreet.so [0]: normal symbol `greet'Selected lines from the capture; addresses belong to this build or run.
At the first breakpoint in main, the real process maps look like this. The executable has separate read, execute and write mappings. The library and libc have their own groups elsewhere. The loader is mapped too, and so are the stack and kernel-provided virtual DSO. A single library can occupy several mappings because its segments have different permissions and because the loader protects a RELRO subrange after relocation.
GDB 17.1; Linux 7.0.0-38-generic. Command inside binding.gdb: python print(open("/proc/%d/maps" % gdb.selected_inferior().pid).read()). Full paths retained.
5a8965a65000-5a8965a66000 r--p 00000000 00:33 27671453 /tmp/claude-1000/-home-r-Projects-undefinedstack/ab631be5-67b3-4b6a-a237-985dffd4d9af/scratchpad/linking/greet-lazy 5a8965a66000-5a8965a67000 r-xp 00001000 00:33 27671453 /tmp/claude-1000/-home-r-Projects-undefinedstack/ab631be5-67b3-4b6a-a237-985dffd4d9af/scratchpad/linking/greet-lazy 5a8965a67000-5a8965a68000 r--p 00002000 00:33 27671453 /tmp/claude-1000/-home-r-Projects-undefinedstack/ab631be5-67b3-4b6a-a237-985dffd4d9af/scratchpad/linking/greet-lazy 5a8965a68000-5a8965a69000 r--p 00002000 00:33 27671453 /tmp/claude-1000/-home-r-Projects-undefinedstack/ab631be5-67b3-4b6a-a237-985dffd4d9af/scratchpad/linking/greet-lazy 5a8965a69000-5a8965a6a000 rw-p 00003000 00:33 27671453 /tmp/claude-1000/-home-r-Projects-undefinedstack/ab631be5-67b3-4b6a-a237-985dffd4d9af/scratchpad/linking/greet-lazy 77563a200000-77563a228000 r--p 00000000 fc:01 33557279 /usr/lib/x86_64-linux-gnu/libc.so.6 77563a228000-77563a3c0000 r-xp 00028000 fc:01 33557279 /usr/lib/x86_64-linux-gnu/libc.so.6 77563a3c0000-77563a40e000 r--p 001c0000 fc:01 33557279 /usr/lib/x86_64-linux-gnu/libc.so.6 77563a40e000-77563a412000 r--p 0020e000 fc:01 33557279 /usr/lib/x86_64-linux-gnu/libc.so.6 77563a412000-77563a414000 rw-p 00212000 fc:01 33557279 /usr/lib/x86_64-linux-gnu/libc.so.6 77563a414000-77563a421000 rw-p 00000000 00:00 0 77563a481000-77563a484000 rw-p 00000000 00:00 0 77563a49c000-77563a49d000 r--p 00000000 00:33 27671423 /tmp/claude-1000/-home-r-Projects-undefinedstack/ab631be5-67b3-4b6a-a237-985dffd4d9af/scratchpad/linking/libgreet.so 77563a49d000-77563a49e000 r-xp 00001000 00:33 27671423 /tmp/claude-1000/-home-r-Projects-undefinedstack/ab631be5-67b3-4b6a-a237-985dffd4d9af/scratchpad/linking/libgreet.so 77563a49e000-77563a49f000 r--p 00002000 00:33 27671423 /tmp/claude-1000/-home-r-Projects-undefinedstack/ab631be5-67b3-4b6a-a237-985dffd4d9af/scratchpad/linking/libgreet.so 77563a49f000-77563a4a0000 r--p 00002000 00:33 27671423 /tmp/claude-1000/-home-r-Projects-undefinedstack/ab631be5-67b3-4b6a-a237-985dffd4d9af/scratchpad/linking/libgreet.so 77563a4a0000-77563a4a1000 rw-p 00003000 00:33 27671423 /tmp/claude-1000/-home-r-Projects-undefinedstack/ab631be5-67b3-4b6a-a237-985dffd4d9af/scratchpad/linking/libgreet.so 77563a4a1000-77563a4a3000 rw-p 00000000 00:00 0 77563a4a3000-77563a4a7000 r--p 00000000 00:00 0 [vvar] 77563a4a7000-77563a4a9000 r--p 00000000 00:00 0 [vvar_vclock] 77563a4a9000-77563a4ab000 r-xp 00000000 00:00 0 [vdso] 77563a4ab000-77563a4ac000 r--p 00000000 fc:01 33557272 /usr/lib/x86_64-linux-gnu/ld-linux-x86-64.so.2 77563a4ac000-77563a4db000 r-xp 00001000 fc:01 33557272 /usr/lib/x86_64-linux-gnu/ld-linux-x86-64.so.2 77563a4db000-77563a4e6000 r--p 00030000 fc:01 33557272 /usr/lib/x86_64-linux-gnu/ld-linux-x86-64.so.2 77563a4e6000-77563a4e8000 r--p 0003b000 fc:01 33557272 /usr/lib/x86_64-linux-gnu/ld-linux-x86-64.so.2 77563a4e8000-77563a4e9000 rw-p 0003d000 fc:01 33557272 /usr/lib/x86_64-linux-gnu/ld-linux-x86-64.so.2 77563a4e9000-77563a4ea000 rw-p 00000000 00:00 0 7ffed0a92000-7ffed0ab4000 rw-p 00000000 00:00 0 [stack] ffffffffff600000-ffffffffff601000 --xp 00000000 00:00 0 [vsyscall]
Notice the read-only mapping immediately before the executable’s writable page. The loader has already changed the RELRO range’s permissions. The lazy greet slot sits in the following writable page, outside that range. The file offset can appear more than once because a page boundary and segment boundary need not coincide; the maps describe page-level mappings, not a verbatim list of ELF section headers.
Relocations can run code, too
An indirect function, or STT_GNU_IFUNC, chooses an implementation through a resolver. glibc can use CPU features to select a version of routines such as memcpy. The resolver returns a function address. An R_X86_64_IRELATIVE relocation identifies a local resolver using an address derived from load bias and addend; the loader calls it and writes its returned address. It is therefore more involved than adding a constant to a pointer.
IFUNC resolution and lazy function binding interact with initialization order. A resolver runs early enough that it cannot assume the application has completed ordinary startup. Our tiny source never calls memcpy, so the greeting trace is evidence for the PLT path, not proof of a particular memcpy implementation. Static glibc startup can also have IFUNC relocation work; “no shared libc” does not mean “no CPU-dependent dispatch.”
Thread-local storage adds another address space convention. A thread-local variable needs a different instance per thread, while an ordinary global like answer has one instance in this process’s defining object. The loader determines the initial TLS layout and installs the thread pointer used by the target ABI. Code-generation models can use fixed offsets or call runtime helpers depending on what the compiler and linker know. Libraries loaded later may require dynamic TLS allocation.
The entry point still is not main
The ELF entry address identifies startup code, conventionally _start in a C executable. The real instructions below clear the frame pointer, recover arguments from the initial stack, align the stack, take main’s address and call __libc_start_main. These instructions came from system startup objects linked by the GCC driver, not from the source body of main.
1060: f3 0f 1e fa endbr64
1064: 31 ed xor %ebp,%ebp
1066: 49 89 d1 mov %rdx,%r9
1069: 5e pop %rsi
106a: 48 89 e2 mov %rsp,%rdx
106d: 48 83 e4 f0 and $0xfffffffffffffff0,%rsp
1071: 50 push %rax
1072: 54 push %rsp
1073: 45 31 c0 xor %r8d,%r8d
1076: 31 c9 xor %ecx,%ecx
1078: 48 8d 3d ca 00 00 00 lea 0xca(%rip),%rdi # 1149 <main>
107f: ff 15 33 2f 00 00 call *0x2f33(%rip) # 3fb8 <__libc_start_main@GLIBC_2.34>
1085: f4 hlt
1086: 66 2e 0f 1f 84 00 00 00 00 00 cs nopw 0x0(%rax,%rax,1)On this glibc path, the dynamic loader handles dependency initialization before transferring to the executable’s entry. The executable’s own initialization is arranged through __libc_start_main before main. Preinitialization arrays, legacy init functions and initialization arrays have defined roles; flattening them into “the kernel calls constructors” loses the actual handoff. The C startup implementation shows this division.
When main returns zero, the runtime performs normal exit handling, including registered handlers and standard-I/O cleanup. There is no earlier C caller waiting for _start to return. A raw _exit syscall skips normal stdio flushing; returning from main uses the library’s exit path. By the time the first greeting appears, several layers of code have already run without appearing in main.c.
execve establishes the process image. The interpreter makes its references usable. C startup code turns that prepared image into a call to main.
Fill the hole, four bytes at a time
Now zoom into the four empty bytes in the opening visual. In main.o, the call to greet starts at text offset 0xa. Its opcode is e8, followed by a signed 32-bit displacement. The relocation points at offset 0xb, the first byte of that displacement, rather than the opcode. The placeholder bytes happen to be zero; their meaning comes from the relocation record.
An ELF64 Rela entry occupies 24 bytes: an eight-byte r_offset, an eight-byte r_info and an eight-byte signed r_addend. The upper 32 bits of r_info select the symbol; the lower 32 bits select the relocation type. In this relocatable object, r_offset is relative to the target section. In a linked dynamic object, a relocation’s offset instead denotes a virtual address within the object. The generic ELF relocation specification defines the record.
GNU readelf (GNU Binutils for Ubuntu) 2.46
$ readelf -rW main.o
Relocation section '.rela.text' at offset 0x1a0 contains 4 entries:
Offset Info Type Symbol's Value Symbol's Name + Addend
0000000000000004 000000050000002a R_X86_64_REX_GOTPCRELX 0000000000000000 answer - 4
000000000000000b 0000000600000004 R_X86_64_PLT32 0000000000000000 greet - 4
0000000000000017 0000000200000002 R_X86_64_PC32 0000000000000000 .LC0 - 4
0000000000000021 0000000700000004 R_X86_64_PLT32 0000000000000000 printf - 4GNU objdump (GNU Binutils for Ubuntu) 2.46
$ objdump -drwC main.o
main.o: file format elf64-x86-64
Disassembly of section .text:
0000000000000000 <main>:
0: 53 push %rbx
1: 48 8b 05 00 00 00 00 mov 0x0(%rip),%rax # 8 <main+0x8> 4: R_X86_64_REX_GOTPCRELX answer-0x4
8: 8b 18 mov (%rax),%ebx
a: e8 00 00 00 00 call f <main+0xf> b: R_X86_64_PLT32 greet-0x4
f: 48 89 c6 mov %rax,%rsi
12: 89 da mov %ebx,%edx
14: 48 8d 3d 00 00 00 00 lea 0x0(%rip),%rdi # 1b <main+0x1b> 17: R_X86_64_PC32 .LC0-0x4
1b: b8 00 00 00 00 mov $0x0,%eax
20: e8 00 00 00 00 call 25 <main+0x25> 21: R_X86_64_PLT32 printf-0x4
25: b8 00 00 00 00 mov $0x0,%eax
2a: 5b pop %rbx
2b: c3 retThe relocation type supplies the equation
Let S be the resolved symbol value, A the signed addend and P the address of the field being patched. R_X86_64_PC32 writes S + A − P into a 32-bit field, with the signed-range check required by the ABI. R_X86_64_PLT32 uses L + A − P, where L is the symbol’s PLT entry. When a call can bind directly to a local definition, the linker can use that definition instead.
The −4 addend reconciles two reference points. The relocation’sP is the beginning of the four-byte displacement. The CPU adds the displacement to the instruction pointer after that field. Therefore the patch needs target − (P + 4), which is target + (−4) − P. That −4 is not the size of a pointer or the distance between sections.
In greet-local, main begins at 0x1139, its displacement field is at 0x1144 and greet is at 0x1165. The patch is 0x1165 − 4 − 0x1144 = 0x1d. The instruction becomes e8 1d 00 00 00. At execution, the next instruction address is 0x1148; adding 0x1d reaches 0x1165. All these offsets come from the linked disassembly.
d = S + A − P = 0x1165 − 4 − 0x1144 = 29
RIPnext + d = 0x1148 + 29 = 0x1165
- S · resolved target
- 0x1165
- A · addend
- −4
- P · patch address
- 0x1144
0x1165 − 4 − 0x1144 = 29 = 0x1d
e8 00 00 00 00e8 00 00 00 00Patch the four bytes starting at section offset 0xb. The result must match objdump’s linked instruction.
Selected greet: PLT32 is resolved directly to this executable’s definition. Apply the relocation to fill the displacement.
GCC 15.2.0; binutils 2.46: objdump -drwC main.o; objdump -drwC greet-local. Linked with gcc -pie -o greet-local main.o greet.o. GOTPCRELX here uses the linker’s observed direct-address relaxation.
Select printf to see a negative displacement. Its PLT entry lies before the call site, so the signed result is encoded in two’s complement. The highest byte becomes ff, rather than indicating an unsigned address near 4 GiB. x86-64 sign-extends a rel32 displacement when adding it to the next instruction pointer. The range is −231 through 231 − 1 bytes.
ASLR does not disturb this distance within one image. If both endpoints gain bias B, then (B + S) + A − (B + P) = S + A − P. The two copies of B cancel. That is why a relative call can be position-independent without rewriting its displacement every time the executable is mapped somewhere else. Calls between independently placed objects need an arrangement such as the PLT/GOT path.
Relax a GOT load into a direct address
The first instruction after main’s register save asks for the address of answer through the GOT. Its object relocation is R_X86_64_REX_GOTPCRELX. Before relaxation, the displacement would address a GOT slot whose contents are the symbol’s address. The GOT-relative equation targets the slot: GOT + G + A − P, where G is the slot’s offset in the GOT.
The X form tells the linker an eligible instruction may be relaxed. In greet-local, the executable contains answer’s definition and the linker can use its address directly. It changes opcode 8b (mov, read memory) to 8d (lea, compute an address), then patches a direct PC-relative displacement. The instruction stays seven bytes long. The later load through the returned address remains; only the extra GOT read disappears.
This is why applying the same arithmetic to every relocation would be wrong. A nonrelaxed GOT reference needs the slot’s address, a PLT reference needs an entry address and a direct PC-relative reference needs the symbol address. The transformation of an instruction is also more than replacing its four placeholder bytes. The x86-64 psABI, relocation tables and appendix B.2 define these equations and eligible GOTPCRELX transformations.
1139: 53 push %rbx
113a: 48 8d 05 cf 2e 00 00 lea 0x2ecf(%rip),%rax # 4010 <answer>
1141: 8b 18 mov (%rax),%ebx
1143: e8 1d 00 00 00 call 1165 <greet>
1148: 48 89 c6 mov %rax,%rsi
114b: 89 da mov %ebx,%edx
114d: 48 8d 3d b0 0e 00 00 lea 0xeb0(%rip),%rdi # 2004 <_IO_stdin_used+0x4>
1154: b8 00 00 00 00 mov $0x0,%eax
1159: e8 d2 fe ff ff call 1030 <printf@plt>
115e: b8 00 00 00 00 mov $0x0,%eax
1163: 5b pop %rbx
1164: c3 retIn the shared build, answer stays external to the executable, so a GOT entry holds its address. In the locally linked build, both answer and greet can use direct references. The original compiler output is identical; the link context creates the difference. The linker’s extra information can improve code even without running a whole-program optimizer.
Relocation overflows are meaningful errors. A signed 32-bit field cannot describe an arbitrary 64-bit distance. If layout pushes a required target out of range, a linker needs an allowed alternative representation or must report failure. It cannot quietly truncate the integer and hope the CPU finds the symbol. Code models, instruction selection and architecture-specific linker support determine which alternatives are available.
A relocation is a typed calculation at an exact byte location. The equation, range check and any instruction transformation must agree with the machine’s interpretation.
Count what the machinery costs
For a long-running program, startup can be a small fraction of total execution. For a tool launched thousands of times, mapping objects, walking relocation tables and searching names can become visible. Distinguish the time to build the executable, the time to start a process and the cost of each steady-state call. These are different workloads and need different measurements.
Our measurements launch fresh processes with warm filesystem caches. Each process prints once and exits; stdout is redirected to /dev/null. Seven batches of 100 launches reveal the scheduling variation that a single timing would hide. The dynamic and static builds execute the same C program, but their startup paths and file sizes differ. The measured wall time also includes Python’s process launch and wait overhead.
Warm-cache process launch to exit · milliseconds per process
Seven batches × 100 sequential subprocess.run calls, stdout → /dev/null, after 20 warm-ups. Bars show the median batch mean; dots show every batch. The common axis starts at zero.
1.588 ms1.512 ms0.761 msLinux 7.0.0-38-generic; GCC 15.2.0, ld.bfd 2.46, glibc 2.43. Includes Python launch/wait, kernel execution, loading, printf and exit. Loader-only cycle counts appear below.
Reproduce the process-launch measurement
import subprocess, time
for name in ["greet-lazy", "greet-now", "greet-static"]:
for _ in range(20):
subprocess.run(["./" + name], stdout=subprocess.DEVNULL, check=True)
samples = []
for _ in range(7):
start = time.perf_counter_ns()
for _ in range(100):
subprocess.run(["./" + name], stdout=subprocess.DEVNULL, check=True)
samples.append((time.perf_counter_ns() - start) / 100 / 1e6)
print(name, samples)The static executable is 858,176 bytes; the lazy dynamic executable is 16,032 bytes, plus a 15,040byte shared library and the system’s libc. File size alone does not give resident memory use. Mapped pages can be untouched, shared across processes or privately dirtied by relocation. Comparing only the main executable’s size leaves most of the dynamic program’s implementation out of the accounting.
The static build’s lower launch times here are useful evidence about this small workload. They do not isolate a universal price for shared libraries. The binaries have different code footprints and initialization paths, and a warmed page cache changes storage costs. A real service with plugins, many dependencies or heavy constructors can have a very different distribution of startup work.
Measure the loader separately
LD_DEBUG=statistics reports startup counters inside glibc’s loader, including relocation and object-loading work. This capture names its units as cycles. Keep those units: a cycle count is not automatically nanoseconds, and the diagnostic itself changes execution. The final relocation count can exceed the startup count because lazy binding does more work after startup.
ldd (Ubuntu GLIBC 2.43-2ubuntu2.7) 2.43
$ LD_DEBUG=statistics ./greet-lazy
2710749:
2710749: runtime linker statistics:
2710749: total startup time in dynamic loader: 170420 cycles
2710749: time needed for relocation: 4110 cycles (2.4%)
2710749: number of relocations: 102
2710749: number of relocations from cache: 7
2710749: number of relative relocations: 6
2710749: time needed to load objects: 69057 cycles (40.5%)
2710749:
2710749: runtime linker statistics:
2710749: final number of relocations: 104
2710749: final number of relocations from cache: 7
hello: 42To investigate a large startup bill, first count objects and relocations, then locate symbol searches and initialization code. A hidden internal symbol may avoid dynamic lookup and enable relaxation. Removing an unnecessary dependency can avoid mappings and constructors altogether. Eager binding can move work earlier and enable stronger protection; lazy binding can avoid resolving functions that never run. The best choice depends on which costs your application actually pays.
Prelink historically tried to do more relocation work ahead of execution by arranging preferred library addresses and recording prepared results. Keeping those assumptions useful requires handling changed libraries and load layouts. Modern position-independent code, ASLR and faster runtime lookup change that tradeoff. Prelink is an example of shifting work across the build/load boundary, not a prerequisite for understanding or tuning the binaries here.
Link-time optimization changes what the linker sees
With ordinary native objects, the linker sees bytes, symbols and relocation records. Link-time optimization: compiler optimization across translation units using intermediate representation retained until the link step. preserves compiler intermediate representation so a compiler plugin can optimize across translation units during linking. It may inline greet, propagate answer’s value or remove unreachable code if visibility and semantic rules permit those transformations. The result still needs executable layout and any remaining relocations.
Compile and link with compatible LTO settings and toolchains; an object carrying intermediate representation is not just an architecture-independent replacement for an ELF ABI. GCC’s optimization options describe how -flto participates in the final link. The small non-LTO fixtures here preserve the function and address boundaries so you can inspect them.
Choose a linker by measuring your build
ld.bfd, lld and mold implement overlapping ELF link-editor jobs, with different designs, platform coverage and performance characteristics. This host only provides ld.bfd. Our probes for gcc -fuse-ld=gold, -fuse-ld=lld and -fuse-ld=mold fail because those linkers are unavailable; no comparative speed result follows from that absence.
For the tiny main.o + greet.o link, 21 runs of gcc -fuse-ld=bfd -pie -o bench-link main.o greet.o have a median of 21.99 ms on this host. This includes the driver and process overhead. A two-object test says little about a large C++ application with debug data, millions of symbols and many threads available for parallel linking.
Gold’s status is a separate maintenance question: the binutils 2.44 release announcement explicitly deprecated it and moved its sources out of the default release tarball. That dated upstream statement is more useful than calling it a modern default. Check availability and required features in your build environment before swapping linkers.
Inspect the linker timing loop and availability probes
import subprocess, time
samples = []
for _ in range(21):
start = time.perf_counter_ns()
subprocess.run([
"gcc", "-fuse-ld=bfd", "-pie", "-o", "bench-link", "main.o", "greet.o"
], check=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
samples.append((time.perf_counter_ns() - start) / 1e6)
print(samples)bfd: available
gold: unavailable
collect2: fatal error: cannot find ‘ld’
compilation terminated.
lld: unavailable
collect2: fatal error: cannot find ‘ld’
compilation terminated.
mold: unavailable
collect2: fatal error: cannot find ‘ld’
compilation terminated.A tool for each question
When an undefined-reference error appears, inspect symbols and archive order before changing runtime library paths. When a binary cannot find a shared object, inspect DT_NEEDED, RUNPATH and the loader’s search trace. When a call takes an unexpected implementation, inspect bindings and visibility. When a process faults at an address, connect the linked disassembly to the mapping’s load bias before assuming the printed virtual address is a file offset.
| Question | Command | Look for |
|---|---|---|
| What kind of ELF? | readelf -hW file | Class, machine, type, entry |
| What did compilation leave? | readelf -SW -sW -rW file.o | Sections, definitions, relocation records |
| Where are definitions? | nm -n file.o | Defined and undefined names |
| Which bytes change? | objdump -drwC file.o | Instructions alongside relocation sites |
| What gets mapped? | readelf -lW program | PT_LOAD, PT_INTERP, GNU_RELRO |
| What does ld.so need? | readelf -dW program | NEEDED, RUNPATH, relocation tags, NOW |
| Which lookup won? | LD_DEBUG=libs,symbols,bindings ./greet-lazy | Search attempts and selected definitions |
| What actually exists now? | cat /proc/<pid>/maps | Runtime ranges, permissions and backing files |
The path from gcc to main is a sequence of commitments. The compiler commits to instructions and ABI conventions. The link editor commits to definitions, layout and the references it can finish. The kernel commits to a process image. The dynamic loader commits runtime addresses into the remaining slots. Finally the C runtime calls the function you wrote. At each boundary, the bytes and records tell you which decision has already been made and which one is still open.
Measure the boundary you want to improve, then inspect the records that control it. The same tools explain both a broken build and a successful first call.
End of Linking and loading · 7 levels, Idea to Machine
Where to next
Next in Systems and hardware · 04 of 06
Atomics, from a log queue to a store buffer
Two threads write, then read. Both can read the old value. Follow a log record through a lock-free queue to understand the language contract, compiler instructions, store buffers, and the cache lines moving between cores.
Practical notes
Cross-compile C and Zig with Zig 0.17.1
Select the target explicitly with zig cc -target or a build script using standardTargetOptions. Verify the file format separately from whether the artifact runs on the target.
Why ldd is unsafe on untrusted binaries
Inspect ELF dependency metadata with readelf or objdump instead of invoking the loader. Use LD_DEBUG only when you intentionally execute a trusted program.