
Recall first from Static and shared libraries
- Linking joins object files and libraries by matching undefined symbols to definitions; library order on the command line matters.
- A static archive is a bundle of object files copied into the program; a shared library is mapped at run time and shared by many processes.
- A shared library has three names: the real file, the soname that programs record, and the link name used at build time.
ELF files, sections and symbols
5 min readThe first lesson on this topic built a static archive and a shared library and explained the three-name scheme. This lesson asks: how does the dynamic linker load a shared library and resolve its symbols?
The Executable and Linkable Format, the standard file format for object files, executables, shared libraries and core dumps on Linux and most Unix systems format began in System V Unix and replaced the older a.out format on Linux in the mid-1990s. The same format covers four kinds of file, which you see in the header's Type field: a relocatable object (.o), an executable, a shared object (.so), and a core dump.
Start with file and the header:
file app_dyn libstats.so.1.2.3 stats_sum.o
readelf -h app_dyn
The header begins with the four bytes 0x7f 'E' 'L' 'F' and records the class (32 or 64 bit), the byte order, the machine (such as x86-64 or AArch64), the entry point, and where the program header table and section header table are. A default Ubuntu executable is a position-independent executable, so readelf shows type DYN for it, just as for a shared library. file distinguishes them for you.
Sections: the linker's view
A section is a named range such as .text (code), .rodata (read-only data), .data (initialised writable data) and .bss (zero-filled data that takes no space in the file). Others hold the symbol tables .symtab and .dynsym, the dynamic metadata .dynamic, the relocation tables, the constructor lists .init_array and .fini_array, and the debug data from last lesson. readelf -S lists them.
Segments: the loader's view
The loader does not care about sections. It reads the program header table, readelf -l, which lists segments. The important ones are PT_LOAD (map this range of the file into memory with these permissions), PT_INTERP (the path of the dynamic linker), PT_DYNAMIC (the dynamic metadata), PT_GNU_RELRO (a region to make read-only after relocation) and PT_GNU_STACK (whether the stack may be executable). The output ends with a section-to-segment mapping that shows which sections fall inside which segment.
Section headers are not needed to run a program; stripping tools may remove them. Segments are what the kernel and loader use.
Symbols
Three tools show symbols. nm is the quickest, readelf -s shows every field, and objdump -t is similar. For a shared library, nm -D and readelf --dyn-syms show the dynamic symbol table, the subset the loader uses. strip removes .symtab but must keep .dynsym, because dynamic linking needs it.
nm stats_mean.o
Typical output (yours may list extra entries):
0000000000000000 T stats_mean
U stats_sum
T means defined in the code section, and U means undefined: this object refers to stats_sum but does not define it, so the linker must find it elsewhere. Other letters include D (initialised data), B (bss), R (read-only data), W (weak) and V (weak object). A capital letter means a global symbol; a lowercase letter means local, visible only inside that file. Functions and variables declared static in C become local symbols.
A a global symbol that another definition may override without error, and that resolves to address zero when it is only referenced and has no definition is declared with __attribute__((weak)). Embedded code uses this for default interrupt handlers: the startup code defines every handler as a weak alias of an empty function, and your driver defines a normal function of the same name, which silently wins.
__attribute__((weak)) void board_hook(void) { } /* default: does nothing */
C++ complicates names. To allow overloading, the C++ compiler mangles a function name to encode its parameter types, so void f(int) becomes _Z1fi. A C library that C++ code must call is declared inside extern "C" { ... }, which turns mangling off. That is why stats.h should contain the __cplusplus guard shown earlier. nm -C or c++filt turns mangled names back into readable ones.
Going deeperWhy undefined symbols are allowed in a shared library
By default gcc -shared does not complain about undefined symbols, because a shared library may legitimately depend on symbols supplied by the program or by another library at load time. That also means a missing dependency shows up as a run-time failure, not a build error. Add -Wl,-z,defs (or --no-undefined) when building a library that should be complete on its own, and the linker refuses to finish if anything is unresolved.
The dynamic linker and where it looks
4 min readThe the program, ld.so or ld-linux, named in the executable's PT_INTERP segment, that the kernel runs first to load the needed shared libraries and connect symbols before main is itself a shared object. readelf -l app_dyn | grep interpreter shows its path. On x86-64 it is /lib64/ld-linux-x86-64.so.2; on 64-bit ARM it is /lib/ld-linux-aarch64.so.1; on 32-bit ARM with hardware floating point it is /lib/ld-linux-armhf.so.3. The kernel maps your program and that interpreter and starts the interpreter, which maps the rest.
If that path does not exist on the machine, the shell reports cannot execute: required file not found, a confusing message because the program file itself is present. The cause is usually a glibc-linked binary on a musl system, or an ARM binary built for the wrong ABI.
What the loader reads
readelf -d app_dyn prints the dynamic section. Each NEEDED entry is a soname the loader must find. Run only on trusted files, ldd app_dyn prints each needed library and where it resolved:
linux-vdso.so.1 (0x00007ffd...)
libstats.so.1 => not found
libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007f...)
/lib64/ld-linux-x86-64.so.2 (0x00007f...)
The linux-vdso.so.1 line is a kernel-provided object, not a file. Some versions of ldd run the program's loader on the file, and the manual page warns against using it on untrusted binaries; readelf -d or objdump -p only read the file and are safe.
The search order
For a NEEDED name without a slash, glibc searches in this order, described in ld.so(8):
- The directories in
DT_RPATH, but only if the object has noDT_RUNPATH. - The directories in the environment variable
LD_LIBRARY_PATH, skipped in secure-execution mode. - The directories in
DT_RUNPATH. - The cache
/etc/ld.so.cache. - The default directories,
/liband/usr/lib.
You set an embedded run path at link time with -Wl,-rpath,DIR. The special token $ORIGIN means the directory containing the file itself, which makes a self-contained application folder relocatable:
gcc main.o -L. -lstats -Wl,-rpath,'$ORIGIN' -o app_dyn
readelf -d app_dyn | grep -E 'NEEDED|RUNPATH|RPATH'
Single quotes keep the shell from expanding $ORIGIN; inside a Makefile write $$ORIGIN. On Ubuntu 24.04 the linker emits DT_RUNPATH for -rpath. The older tag DT_RPATH is produced with -Wl,--disable-new-dtags. They differ in two ways: RPATH is searched before LD_LIBRARY_PATH, so the environment cannot override it, and it also applies to the dependencies of dependencies, while RUNPATH is searched after LD_LIBRARY_PATH and covers only the object's own direct needs.
Setting LD_LIBRARY_PATH globally changes which libraries every program loads and can cause a program to pick up the wrong library. For a device, use RUNPATH with $ORIGIN or install into a standard directory. For setuid and setgid programs, and programs with file capabilities, glibc enters secure-execution mode and ignores LD_LIBRARY_PATH and most other LD_ variables, because otherwise a user could inject code into a privileged process. sudo also strips these variables from the environment by default.
The loader loads needed libraries breadth-first, starting from the program's own NEEDED list. This load order also fixes which definition wins when two libraries export the same name, a point that returns with LD_PRELOAD later.
Relocations, the PLT and the GOT
5 min readA shared library can be mapped at a different address in every process, and ASLR randomises the address each run. Code therefore cannot hold the address of a function in another library. A a record in an ELF file telling the linker or loader to compute an address and write it into a specific location describes each place that needs a computed value. readelf -r app_dyn lists them. On x86-64 the common types are R_X86_64_RELATIVE (add the load address of this object), R_X86_64_GLOB_DAT (store the address of a global symbol) and R_X86_64_JUMP_SLOT (store a function address for a call). The AArch64 equivalents are R_AARCH64_RELATIVE, R_AARCH64_GLOB_DAT and R_AARCH64_JUMP_SLOT.
The code sits in read-only, shared pages, so the addresses live elsewhere. The Global Offset Table, a table of addresses in the writable data of a program or library, filled by the dynamic linker holds them. A call to a shared function does not jump to the library directly but to a stub in the Procedure Linkage Table, a table of small code stubs in the program, each of which jumps through one GOT entry. The code is position-independent and the GOT entry is the only thing the loader needs to write.
The classic mechanism, still used with the option -z lazy, is lazy binding. The GOT entry for each function starts out pointing back into the PLT, so the first call takes a detour through the resolver:
Call the stub: The program calls the PLT stub for the function, for example the one for
stats_sumin a shared library.Read the GOT entry: The stub jumps through its GOT entry. On the first call that entry does not hold the real address; it points to the next instruction in the stub.
Push the identity: The stub pushes an index naming which relocation it is, then jumps to the first PLT stub, which pushes a pointer to the library list and jumps into the dynamic linker's resolver.
Look up the symbol: The resolver searches the loaded libraries in load order for the definition of the symbol.
Patch the GOT: The resolver writes the real address into the function's GOT entry.
Jump to the function: The resolver transfers control to the real function, which returns straight to the original caller.
Later calls go direct: On every later call the stub reads the patched GOT entry and jumps to the function immediately.
Lazy binding and BIND_NOW
Lazy binding speeds up startup because functions never called are never looked up. But the first call to each function pays an unpredictable lookup cost, which is a poor fit for a real-time loop, and the GOT must stay writable for the life of the process, which gives an attacker with a memory-write bug a target. Ubuntu's toolchain therefore links binaries with -z now by default, which sets the BIND_NOW flag: the loader resolves every function at start and then makes the relocated area read-only. This combination is called full RELRO, and readelf -l shows the GNU_RELRO segment while readelf -d shows FLAGS: BIND_NOW. You can still ask for lazy binding with -Wl,-z,lazy, and force binding at start on any program with the environment variable LD_BIND_NOW=1.
With -fno-plt, gcc emits calls that load the function address from the GOT directly and call through it, so no PLT stub is used. That saves one jump per call at the price of larger code and combines well with -z now.
Going deeperWhy the first call is hard to see with ltrace and gdb
In gdb, disassemble on a call to a shared function shows call to a symbol such as stats_sum@plt, not the library function. Stepping into it with stepi on a program linked with -z lazy shows the push and the jump into the resolver, and after the first call the same stub jumps directly. With Intel branch-protection enabled (-fcf-protection), stubs live in a second section called .plt.sec. On a -z now binary there are no lazy entries to watch, which is why the demonstration needs the explicit -z lazy flag.
Key takeaways
- ELF sections describe a file for the linker; segments describe the same bytes for the loader, and readelf shows both.
- ld.so searches RPATH, LD_LIBRARY_PATH, RUNPATH, the ld.so.cache and the default directories, and ldd shows the result.
- Calls to shared functions go through the PLT and GOT; lazy binding resolves them on first call, while BIND_NOW and RELRO resolve and lock them at load time.
Reflect
- Explain to a colleague, in two sentences: read an ELF file with readelf, nm and objdump, and distinguish sections from segments and defined, undefined and weak symbols.
- Which objective are you least sure about? Re-read that section, then do its exercise in the practice pack.
- What surprised you when you ran the commands yourself?
On a real board
Repeat the key commands on your Raspberry Pi or lab board over SSH or the serial console. Note anything that behaves differently from your PC, such as missing tools, a BusyBox shell or a read-only filesystem.
References and further reading
- Man pageld.so(8), the dynamic linker/loader
- Man pageelf(5), format of ELF executable binary files
- Man pageldd(1)
Official documentation first. Links checked when the lesson was published.