Module 2 · Lesson 6 of 131

ELF, the dynamic linker and relocations

The learner can read an ELF file's sections, segments and symbols, trace where ld.so searches for libraries, and explain PLT and GOT binding.

  • Beginner to advanced
  • 10 min read
  • 12 min lab
What you will need

gcc, binutils and make on Ubuntu 24.04 (WSL2, VM or container); a Raspberry Pi or QEMU aarch64 for the cross-compiling section

Your place in the module
By the end you can 3 objectives
  • Read an ELF file with readelf, nm and objdump, and distinguish sections from segments and defined, undefined and weak symbols.
  • Trace how ld.so finds libraries (RPATH, LD_LIBRARY_PATH, RUNPATH, ld.so.cache) and diagnose a library that cannot be found.
  • Describe how lazy binding resolves a call through the PLT and GOT, and compare it with BIND_NOW and RELRO.
Video coming soonELF, the dynamic linker and relocations
The video for this lesson is being recorded. Read the lesson below in the meantime.
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.
01

ELF files, sections and symbols

5 min read

The 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 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:

bash
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.

Sections versus segmentsSectionsSegmentsUsed bylinker andtoolskernel andld.soListed byreadelf -Sreadelf -lExamples.text .data.bssPT_LOADPT_INTERPNeeded to runnoyes
One ELF file seen as sections by the linker and as segments by the loader

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.

bash
nm stats_mean.o

Typical output (yours may list extra entries):

text
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 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.

c
__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.

02

The dynamic linker and where it looks

4 min read

The 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:

text
    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):

  1. The directories in DT_RPATH, but only if the object has no DT_RUNPATH.
  2. The directories in the environment variable LD_LIBRARY_PATH, skipped in secure-execution mode.
  3. The directories in DT_RUNPATH.
  4. The cache /etc/ld.so.cache.
  5. The default directories, /lib and /usr/lib.
glibc library search orderRPATHonly if noRUNPATHLD_LIBRARY_PATHskipped ifsetuidRUNPATHld.so.cache/lib,/usr/libExit from step 5: not foundcannot open shared objectRPATHonly if noRUNPATHLD_LIBRARY_PATHskipped ifsetuidRUNPATHld.so.cache/lib,/usr/libExit from step 5: not foundcannot open shared object
The glibc search order for a needed shared library

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:

bash
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.

LD_LIBRARY_PATH is for development, not products

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.

03

Relocations, the PLT and the GOT

5 min read

A 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 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 holds them. A call to a shared function does not jump to the library directly but to a stub in the . 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:

Step by stepLazy binding of one function call (x86-64 style)
  1. Call the stub: The program calls the PLT stub for the function, for example the one for stats_sum in a shared library.

  2. 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.

  3. 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.

  4. Look up the symbol: The resolver searches the loaded libraries in load order for the definition of the symbol.

  5. Patch the GOT: The resolver writes the real address into the function's GOT entry.

  6. Jump to the function: The resolver transfers control to the real function, which returns straight to the original caller.

  7. Later calls go direct: On every later call the stub reads the patched GOT entry and jumps to the function immediately.

First call through the PLTCallerPLT stubResolverLibraryfunctioncallstats_sum@pltGOT points toresolverpatch GOT,jumpreturnsecond callGOT jumps direct1. Caller → PLT stubcall stats_sum@plt2. PLT stub → ResolverGOT points to resolver3. Resolver → Libraryfunctionpatch GOT, jump4. Library function → Callerreturn5. Caller → PLT stubsecond call6. PLT stub → LibraryfunctionGOT jumps direct
First call resolves through the PLT and patches the GOT; later calls jump straight to the function

Under lazy binding a GOT entry starts pointing back at the PLT, the first call runs the resolver, which patches the GOT, and every later call jumps straight to the function; BIND_NOW skips the middle step by binding at load time.

  • states: [{"id": "unresolved", "label": "GOT entry points at PLT"}, {"id": "resolver", "label": "Resolver searching"}, {"id": "bound", "label": "GOT holds real address"}]
  • transitions: [{"from": "unresolved", "to": "resolver", "event": "first call"}, {"from": "resolver", "to": "bound", "event": "patch GOT"}, {"from": "bound", "to": "bound", "event": "later call"}, {"from": "unresolved", "to": "bound", "event": "BIND_NOW at load"}]

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
  1. 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.
  2. Which objective are you least sure about? Re-read that section, then do its exercise in the practice pack.
  3. 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

Official documentation first. Links checked when the lesson was published.

Find your next step

↑ ↓ to move · Enter to open · Esc to close