Low level software usually has lots of
.rs files. Even lower-level software, like your cryptography library, probably has
.S containing assembly, my least favorite language for code review.
The lowest level software out there, firmware, kernels, and drivers, have one third file type to feed into the toolchain: an
.ld file, a “linker script”. The linker script, provided to Clang as
-Wl,-T,foo.ld1, is like a template for the final executable. It tells the linker how to organize code from the input objects. This permits extremely precise control over the toolchain’s output.
Very few people know how to write linker script; it’s a bit of an obscure skill. Unfortunately, I’m one of them, so I get called to do it on occasion. Hopefully, this post is a good enough summary of the linker script language that you, too, can build your own binary!
Everything in this post can be found in excruciating detail in GNU
lld accepts basically the same syntax. There’s no spec, just what your linker happens to accept. I will, however, do my best to provide a more friendly introduction.
No prior knowledge of how toolchains work is necessary! Where possible, I’ve tried to provide historical context on the names of everything. Toolchains are, unfortunately, bound by half a century of tradition. Better to at least know why they’re called that.
On Windows, assembly files use the sensible
.asmextension. POSIX we use the
.Swhen we’d like Clang to run the C preprocessor on them (virtually all hand-written assembly is of the second kind).
I don’t actually have a historical citation for
.s, other than that it came from the Unix tradition of obnoxiously terse names. If we are to believe that
.ostands for “object”, and
.astands for “archive”, then
.smust stand for “source”, up until the B compiler replaced them with
.bfiles! See http://man.cat-v.org/unix-1st/1/b.
A final bit of trivia:
.Cfiles are obviously different from
.cfiles… they’re C++ files! (Seriously, try it.)
Note: This post is specifically about POSIX. I know basically nothing about MSVC and
link.exeother than that they exist. The most I’ve done is helped people debug trivial
I will also only be covering things specific to linking an executable; linking other outputs, like shared libraries, is beyond this post.
A linker is but a small part of a toolchain, the low-level programmer’s toolbox: everything you need to go from source code to execution.
The crown jewel of any toolchain is the compiler. The LLVM toolchain, for example, includes Clang, a C/C++2 compiler. The compiler takes source code, such as
.cc, and lowers it down to a
.s file, an assembly file which textually describes machine code for a specific architecture (you can also write them yourself).
Another toolchain program, the assembler, assembles each
.s into a
.o file, an object file3. An assembly file is merely a textual representation of an object file; assemblers are not particularly interesting programs.
A third program, the linker, links all of your object files into a final executable or binary, traditionally given the name
This three (or two, if you do compile/assemble in one step) phase process is sometimes called the C compilation model. All modern software build infrastructure is built around this model5.
Clang, being based on LLVM, actually exposes one stage in between the
.ccfile and the
.sfile. You can ask it to skip doing codegen and emit a
.llfile filled with LLVM IR, an intermediate between human-writable source code and assembly. The magic words to get this file are
clang -S -emit-llvm. (The Rust equivalent is
The LLVM toolchain provides
llc, the LLVM compiler, which performs the
.sstep (optionally assembling it, too).
lliis an interpreter for the IR. Studying IR is mostly useful for understanding optimization behavior; topic for another day.
The compiler, assembler, and linker are the central components of a toolchain. Other languages, like Rust, usually provide their own toolchain, or just a compiler, reusing the existing C/C++ toolchain. The assembler and linker are language agnostic.
The toolchain also provides various debugging tools, including an interactive debugger, and tools for manipulating object files, such as
These days, most of this stuff is bundled into a single program, the compiler frontend, which knows how to compiler, assemble, and link, in one invocation. You can ask Clang to spit out
.o files with
clang -c, and
.s files with
The UNIX crowd at Bell Labs was very excited about short, terse names. This tradition survives in Go’s somewhat questionable practice of single-letter variables.
Most toolchain program names are cute contractions.
ccis “C compiler”; compilers for almost all other languages follow this convention, like
scalac; Clang is just
clang, but is perfectly ok being called as
ldis “loader” (you’ll learn why sooner).
nmis “names”. Other names tend to be a bit more sensible.
Some fifty years ago at Bell Labs, someone really wanted to write a program with more than one
.s file. To solve this, a program that could “link” symbol references across object files was written: the first linker.
You can take several
.o files and use
ar (an archaic
tar, basically) to create a library, which always have names like
lib is mandatory). A static library is just a collection of objects, which can be provided on an as-needed basis to the linker.
The “final link” incorporates several
.o files and
.a files to produce an executable. It does roughly the following:
- Parse all the objects and static libraries and put their symbols into a database. Symbols are named addresses of functions and global variables.
- Search for all unresolved symbol references in the
.ofiles and match it up with a symbol from the database, recursively doing this for any code in a
.areferenced during this process. This forms a sort of dependency graph between sections. This step is called symbol resolution.
- Throw out any code that isn’t referenced by the input files by tracing the dependency graph from the entry-point symbol (e.g.,
_starton Linux). This step is called garbage collection.
- Execute the linker script to figure out how to stitch the final binary together. This includes discovering the offsets at which everything will go.
- Resolve relocations, “holes” in the binary that require knowing the final runtime address of the section. Relocations are instructions placed in the object file for the linker to execute.
- Write out the completed binary.
This process is extremely memory-intensive; it is possible for colossal binaries, especially ones with tons of debug information, to “fail to link” because the linker exhausts the system’s memory.
We only care about step 4; whole books can be written about the previous steps. Thankfully, Ian Lance Taylor, mad linker scientist and author of
gold, has written several excellent words on this topic: https://lwn.net/Articles/276782/.
Linkers, fundamentally, consume object files and produce object files; the output is executable, meaning that all relocations have been resolved and an entry-point address (where the OS/bootloader will jump to to start the binary).
It’s useful to be able to peek into object files. The
objdump utility is best for this.
objdump -x my_object.o will show all headers, telling you what exactly is in it.
At a high level, an object file describes how a program should be loaded into memory. The object is divided into sections, which are named blocks of data. Sections may have file-like permissions, such as allocatable, loadable, readonly, and executable.
objdump -h can be used to show the list of sections. Some selected lines of output from
objdump on my machine (I’m on a 64-bit machine, but I’ve trimmed leading zeros to make it all fit):
ALLOC) sections must be allocated space by the operating system; if the section is loadable (
LOAD), then the operating system must further fill that space with the contents of the section. This process is called loading and is performed by a loader program6. The loader is sometimes called the “dynamic linker”, and is often the same program as the “program linker”; this is why the linker is called
Loading can also be done beforehand using the
binary output format. This is useful for tiny microcontrollers that are too primitive to perform any loading.
objcopy is useful for this and many other tasks that involve transforming object files.
Some common (POSIX) sections include:
.text, where your code lives7. It’s usually a loadable, readonly, executable section.
.datacontains the initial values of global variables. It’s loadable.
.rodatacontains constants. It’s loadable and readonly.
.bssis an empty allocatable section8. C specifies that uninitialized globals default to zero; this is a convenient way for avoiding storing a huge block of zeros in the executable!
- Debug sections that are not loaded or allocated; these are usually removed for release builds.
After the linker decides which sections from the
.a inputs to keep (based on which symbols it decided it needed), it looks to the linker script how to arrange them in the output.
Let’s write our first linker script!
This tells the linker to create a
.text section in the output, which contains all sections named
.text from all inputs, plus all sections with names like
.text.foo. The content of the section is laid out in order: the contents of all
.text sections will come before any
.text.* sections; I don’t think the linker makes any promises about the ordering between different objects9.
As I mentioned before, parsers for linker script are fussy10: the space in
.text : is significant.
Note that the two
.text sections are different, and can have different names! The linker generally doesn’t care what a section is named; just its attributes. We could name it
code if we wanted to; even the leading period is mere convention. Some object file formats don’t support arbitrary sections; all the sane ones (ELF, COFF, Mach-O) don’t care, but they don’t all spell it the same way; in Mach-O, you call it
Before continuing, I recommend looking at the appendix so that you have a clear path towards being able to run and test your linker scripts!
None of this syntax is used in practice but it’s useful to contextualize the syntax for pulling in a section. The full form of the syntax is
archive:object(section1 section2 ...)
Naturally, all of this is optional, so you can write
:baz.o(.text .data), where the last one means “not part of a library”. There’s even an
EXCLUDE_FILEsyntax for filtering by source object, and a
INPUT_SECTION_FLAGSsyntax for filtering by the presence of format-specific flags.
Do not use any of this. Just write
*(.text)and don’t think about it too hard. The
*is just a glob for all objects.
Each section has an alignment, which is just the maximum of the alignments of all input sections pulled into it. This is important for ensuring that code and globals are aligned the way the architecture expects them to be. The alignment of a section can be set explicitly with
You can also instruct the linker to toss out sections using the special
/DISCARD/ output section, which overrides any decisions made at garbage-collection time. I’ve only ever used this to discard debug information that GCC was really excited about keeping around.
On the other hand, you can use
KEEP(*(.text.*)) to ensure no
.text sections are discarded by garbage-collection. Unfortunately, this doesn’t let you pull in sections from static libraries that weren’t referenced in the input objects.
Every section has three addresses associated with it. The simplest is the file offset: how far from the start of the file to find the section.
The virtual memory address, or VMA, is where the program expects to find the section at runtime. This is the address that is used by pointers and the program counter.
The load memory address, or LMA, is where the loader (be it a runtime loader or
objcpy) must place the code. This is almost always the same as the VMA. Later on, in Using Symbols and LMAs, I’ll explain a place where this is actually useful.
When declaring a new section, the VMA and LMA are both set to the value11 of the location counter, which has the extremely descriptive name
.12. This counter is automatically incremented as data is copied from the input
We can explicitly specify the VMA of a section by putting an expression before the colon, and the LMA by putting an expression in the
AT(lma) specifier after the colon:
This will modify the location counter; you could also write it as
SECTIONS, the location counter can be set at any point, even while in the middle of declaring a section (though the linker will probably complain if you do something rude like move it backwards).
The location counter is incremented automatically as sections are added, so it’s rarely necessary to fuss with it directly.
By default, the linker will simply allocate sections starting at address
MEMORY statement can be used to define memory regions for more finely controlling how VMAs and LMAs are allocated without writing them down explicitly.
A classic example of a
MEMORY block separates the address space into ROM and RAM:
A region is a block of memory with a name and some attributes. The name is irrelevant beyond the scope of the linker script. The attributes in parens are used to specify what sections could conceivably go in that region. A section is compatible if it has any of the attributes before the
!, and none which come after the
!. (This filter mini-language isn’t very expressive.)
The attributes are the ones we mentioned earlier:
rwxal are readonly, read/write, executable, allocated, and loadable13.
When allocating a section a VMA, the linker will try to pick the best memory region that matches the filter using a heuristic. I don’t really trust the heuristic, but you can instead write
> region to put something into a specific region. Thus,
AT> is the “obvious” of
>, and sets which region to allocate the LMA from.
The origin and length of a region can be obtained with the
Output sections can hold more than just input sections. Arbitrary data can be placed into sections using the
QUAD for placing literal 8, 16, 32, and 64-bit unsigned integers into the section:
Numeric literals in linker script may, conveniently, be given the suffixes
M to specify a kilobyte or megabyte quantity. E.g.,
4K is sugar for
You can fill the unused portions of a section by using the
FILL command, which sets the “fill pattern” from that point onward. For example, we can create four kilobytes of
FILL and the location counter:
The “fill pattern” is used to fill any unspecified space, such as alignment padding or jumping around with the location counter. We can use multiple FILLs to vary the fill pattern, such as if we wanted half the page to be
0x0a and half
When using one fill pattern for the whole section, you can just write
= fill; at the end of the section. For example,
Although the linker needs to resolve all symbols using the input
.a files, you can also declare symbols directly in linker script; this is the absolute latest that symbols can be provided. For example:
This will define a new symbol with value
5. If we then wrote
extern char my_cool_symbol;, we can access the value placed by the linker. However, note that the value of a symbol is an address! If you did
the processor would be very confused about why you just dereferenced a pointer with address
5. The correct way to extract a linker symbol’s value is to write
It seems a bit silly to take the address of the global and use that as some kind of magic value, but that’s just how it works. The exact same mechanism works in Rust, too:
The most common use of this mechanism is percolating information not known until link time. For example, a common idiom is
This allows initialization code to find the section’s address and length; in this case, the pointer values are actually meaningful!
It’s common practice to lead linker symbols with two underscores, because C declares a surprisingly large class of symbols reserved for the implementation, so normal user code won’t call them. These include names like
__text_start, which start with two underscores, and names starting with an underscore and an uppercase letter, like
However, libc and STL headers will totally use the double underscore symbols to make them resistant to tampering by users (which they are entitled to), so beware!
Symbol assignments can even go inside of a section, to capture the location counter’s value between input sections:
Symbol names are not limited to C identifiers, and may contain dashes, periods, dollar signs, and other symbols. They may even be quoted, like
"this symbol has spaces", which C will never be able to access as an
There is a mini-language of expressions that symbols can be assigned to. This includes:
- Numeric literals like
- The location counter,
- Other symbols.
- The usual set of C operators, such as arithmetic and bit operations. Xor is curiously missing.
- A handful of builtin functions, described below.
There are some fairly complicated rules around how symbols may be given relative addresses to the start of a section, which are only relevant when dealing with position-independent code: https://sourceware.org/binutils/docs/ld/Expression-Section.html
Functions belong to one of two board categories: getters for properties of sections, memory regions, and other linker structures; and arithmetic. Useful functions include:
ALIGNOF, which produce the VMA, LMA, size, and alignment of a previously defined section.
LENGTH, which produce the start address and length of a memory region.
LOG2CEILcomputes the base-2 log, rounded up.
exprto the next multiple of
ALIGN(align)is roughly equivalent to
ALIGN(., align)with some subtleties around PIC.
. = ALIGN(align);will align the location counter to
Some other builtins can be found at https://sourceware.org/binutils/docs/ld/Builtin-Functions.html.
A symbol definition can be wrapped in the
PROVIDEO() function to make it “weak”, analogous to the “weak symbol” feature found in Clang. This means that the linker will not use the definition if any input object defines it.
As mentioned before, it is extremely rare for the LMA and VMA to be different. The most common situation where this occurs is when you’re running on a system, like a microcontroller, where memory is partitioned into two pieces: ROM and RAM. The ROM has the executable burned into it, and RAM starts out full of random garbage.
Most of the contents of the linked executable are read-only, so their VMA can be in ROM. However, the
.bss sections need to lie in RAM, because they’re writable. For
.bss this is easy, because it doesn’t have loadable content. For
.data, though, we need to separate the VMA and LMA: the VMA must go in RAM, and the LMA in ROM.
This distinction is important for the code that initializes the RAM: while for
.bss all it has to do is zero it, for
.data, it has to copy from ROM to RAM! The LMA lets us distinguish the copy source and the copy destination.
This has the important property that it tells the loader (usually
objcopy in this case) to use the ROM addresses for actually loading the section to, but to link the code as if it were at a RAM address (which is needed for things like PC-relative loads to work correctly).
Here’s how we’d do it in linker script:
Although we would normally write the initialization code in assembly (since it’s undefined behavior to execute C before initializing the
.data sections), I’ve written it in C for illustrative purposes:
Linker script includes a bunch of other commands that don’t fit into a specific category:
ENTRY()sets the program entry-point, either as a symbol or a raw address. The
-eflag can be used to override it. The
lddocs assert that there are fallbacks if an entry-point can’t be found, but in my experience you can sometimes get errors here.
ENTRY(_start)would use the
_startsymbol, for example14.
#includebut for linker script.
foo.oas a linker input, as if it was passed at the commandline.
GROUPis similar, but with the semantics of
OUTPUT()overrides the usual
a.outdefault output name.
ASSERT()provides static assertions.
EXTERN(sym)causes the linker to behave as if an undefined reference to
symexisted in an input object.
(Other commands are documented, but I’ve never needed them in practice.)
It may be useful to look at some real-life linker scripts.
If you wanna see what Clang, Rust, and the like all ultimately use, run
ld --verbose. This will print the default linker script for your machine; this is a really intense script that uses basically every feature available in linker script (and, since it’s GNU, is very poorly formatted).
The Linux kernel also has linker scripts, which are differently intense, because they use the C preprocessor. For example, the one for amd64: https://github.com/torvalds/linux/blob/master/arch/x86/kernel/vmlinux.lds.S.
Tock OS, a secure operating system written in Rust, has some pretty solid linker scripts, with lots of comments: https://github.com/tock/tock/blob/master/boards/kernel_layout.ld. I recommend taking a look to see what a “real” but not too wild linker script looks like. There’s a fair bit of toolchain-specific stuff in there, too, that should give you an idea of what to expect.
Happy linking! ◼
tl;dr: If you don’t wanna try out any examples, skip this section.
I want you to be able to try out the examples above, but there’s no Godbolt for linker scripts (yet!). Unlike normal code, you can’t just run linker script through a compiler, you’re gonna need some objects to link, too! Let’s set up a very small C project for testing your linker scripts.
Note: I’m assuming you’re on Linux, with x86_64, and using Clang. If you’re on a Mac (even M1), you can probably make
ld64do the right thing, but this is outside of what I’m an expert on.
If you’re on Windows, use WSL. I have no idea how MSCV does linker scripts at all.
First, we want a very simple static library:
extern.c into a static library like so:
We can check out that we got something reasonable by using
nm program shows you all the symbols a library or object defines.
This shows us the address, section type, and name of each symbol;
man nm tells us that
.bss. Capital letters mean that the symbol is exported, so the linker can use it to resolve a symbol reference or a relocation. In C/C++, symbols declared
static or in an unnamed namespace are “hidden”, and can’t be referenced outside of the object. This is sometimes called internal vs external linkage.
Next, we need a C program that uses the library:
Compile it with
clang -c run.c. We can inspect the symbol table with
nm as before:
As you might guess,
d is just
U is interesting: it’s an undefined symbol, meaning the linker will need to perform a symbol resolution! In fact, if we ask Clang to link this for us (it just shells out to a linker like
The linker also complains that there’s no
main() function, and that some object we didn’t provide called
crt1.o wants it. This is the startup code for the C runtime; we can skip linking it with
-nostartfiles. This will result in the linker picking an entry point for us.
We can resolve the missing symbol by linking against our library.
-lfoo says to search for the library
-L. says to include the current directory for searching for libraries.
This gives us our binary,
a.out, which we can now
Let’s write up the simplest possible linker script for all this:
Let’s link! We’ll also want to make sure that the system libc doesn’t get in the way, using
At this point, you can use
objdump to inspect
a.out at your leisure! You’ll notice there are a few other sections, like
.eh_frame. Clang adds these by default, but you can throw them out using
It’s worth it to run the examples in the post through the linker using this “playground”. You can actually control the sections Clang puts symbols into using the
__attribute__((section("blah"))) compiler extension. The Rust equivalent is
#[link_section = "blah"].
And many other things, like Objective-C. ↩
Completely and utterly unrelated to the objects of object-oriented programming. Best I can tell, the etymology is lost to time. ↩
a.outis also an object file format, like ELF, but toolchains live and die by tradition, so that’s the name given to the linker’s output by default. ↩
Rust does not compile each
.rsfile into an object, and its “crates” are much larger than the average C++ translation unit. However, the Rust compiler will nonetheless produce many object files for a single crate, precisely for the benefit of this compilation model. ↩
Operating systems are loaded by a bootloader. Bootloaders are themselves loaded by other bootloaders, such as the BIOS. At the bottom of the turtles is the mask ROM, which is a tiny bootloader permanently burned into the device. ↩
No idea on the etymology. This isn’t ASCII text! ↩
Back in the 50s, this stood for “block started by symbol”. ↩
Yes, yes, you can write
SORT_BY_NAME(*)(.text)but that’s not really something you ever wind up needing.
See https://sourceware.org/binutils/docs/ld/Input-Section-Wildcards.html for more information on this. ↩
You only get
/* */comment syntax because that’s the lowest common denominator. ↩
.actually gets increased to the alignment of the section first. If you insist on an unaligned section, the syntax is, obviously,
(That was sarcasm. It must be stressed that this is not a friendly language.) ↩
This symbol is also available in assembly files.
jmp .is an overly-cute idiom for an infinity busy loop. It is even more terse in ARM and RISC-V, where it’s written
j ., respectively.
Personally, I prefer the obtuse clarity of
loop_forever: j loop_forever. ↩
These are the same characters used to declare a section in assembly. If I wanted to place my code in a section named
.crt0but wanted it to be placed into a readonly, executable memory block, use the the assembler directive
.section .crt0, rxal↩
Note that the entry point is almost never a function called
main(). In the default configuration of most toolchains, an object called
crt0.ois provided as part of the libc, which provides a
_start()function that itself calls
main(). CRT stands for “C runtime”; thus,
crt0.oinitializes the C runtime.
This file contains the moral equivalent of the following C code, which varies according to target:
This behavior can be disabled with
-nostartfilesin Clang. The OSDev wiki has some on this topic: https://wiki.osdev.org/Creating_a_C_Library#Program_Initialization. ↩
If you include libc, you will get bizarre errors involving something called “
libgcc_s) is GCC’s compiler runtime library. Where
libcexposes high-level operations on the C runtime and utilities for manipulating common objects,
libgccprovides even lower-level support, including:
- Polyfills for arithmetic operations not available on the target. For example, dividing two 64-bit integers on most 32-bit targets will emit a reference to the a symbol like
__udivmoddi4(they all have utterly incomprehensible names like this one).
- Soft-float implementations, i.e., IEEE floats implemented in software for targets without an FPU.
- Bits of unwinding (e.g. exceptions and panics) support (the rest is in
- Miscellaneous runtime support code, such as the code that calls C++ static initializers.
libcompiler-rt, is ABI-compatible with
libgccand provides various support for profiling, sanitizers, and many, many other things the compiler needs available for compiling code. ↩
- Polyfills for arithmetic operations not available on the target. For example, dividing two 64-bit integers on most 32-bit targets will emit a reference to the a symbol like