xref: /llvm-project-15.0.7/lld/docs/NewLLD.rst (revision 052d95a6)
1The ELF and COFF Linkers
2========================
3
4We started rewriting the ELF (Unix) and COFF (Windows) linkers in May 2015.
5Since then, we have been making a steady progress towards providing
6drop-in replacements for the system linkers.
7
8Currently, the Windows support is mostly complete and is about 2x faster
9than the linker that comes as a part of Micrsoft Visual Studio toolchain.
10
11The ELF support is in progress and is able to link large programs
12such as Clang or LLD itself. Unless your program depends on linker scripts,
13you can expect it to be linkable with LLD.
14It is currently about 1.2x to 2x faster than GNU gold linker.
15We aim to make it a drop-in replacement for the GNU linker.
16
17We expect that FreeBSD is going to be the first large system
18to adopt LLD as the system linker.
19We are working on it in collaboration with the FreeBSD project.
20
21The linkers are notably small; as of October 2016,
22the COFF linker is about 7k lines and the ELF linker is about 18k lines,
23while gold is 165K lines.
24
25The linkers are designed to be as fast and simple as possible.
26Because it is simple, it is easy to extend to support new features.
27It already supports several advanced features such section garbage
28collection and identical code folding.
29
30The COFF linker supports i386, x86-64 and ARM. The ELF linker supports
31i386, x86-64, x32, MIPS32, MIPS64, PowerPC, AMDGPU, ARM and Aarch64,
32although the quality varies depending on platform. By default, LLD
33provides support for all targets because the amount of code we have for
34each target is so small. We do not even provide a way to disable
35targets at compile time.
36
37There are a few key design choices that we made to achieve these goals.
38We will describe them in this document.
39
40The ELF Linker as a Library
41---------------------------
42
43You can embed LLD to your program by linking against it and calling the linker's
44entry point function lld::elf::link.
45
46The current policy is that it is your reponsibility to give trustworthy object
47files. The function is guaranteed to return as long as you do not pass corrupted
48or malicious object files. A corrupted file could cause a fatal error or SEGV.
49That being said, you don't need to worry too much about it if you create object
50files in the usual way and give them to the linker. It is naturally expected to
51work, or otherwise it's a linker's bug.
52
53Design
54======
55
56We will describe the design of the linkers in the rest of the document.
57
58Key Concepts
59------------
60
61Linkers are fairly large pieces of software.
62There are many design choices you have to make to create a complete linker.
63
64This is a list of design choices we've made for ELF and COFF LLD.
65We believe that these high-level design choices achieved a right balance
66between speed, simplicity and extensibility.
67
68* Implement as native linkers
69
70  We implemented the linkers as native linkers for each file format.
71
72  The two linkers share the same design but do not share code.
73  Sharing code makes sense if the benefit is worth its cost.
74  In our case, ELF and COFF are different enough that we thought the layer to
75  abstract the differences wouldn't worth its complexity and run-time cost.
76  Elimination of the abstract layer has greatly simplified the implementation.
77
78* Speed by design
79
80  One of the most important things in archiving high performance is to
81  do less rather than do it efficiently.
82  Therefore, the high-level design matters more than local optimizations.
83  Since we are trying to create a high-performance linker,
84  it is very important to keep the design as efficient as possible.
85
86  Broadly speaking, we do not do anything until we have to do it.
87  For example, we do not read section contents or relocations
88  until we need them to continue linking.
89  When we need to do some costly operation (such as looking up
90  a hash table for each symbol), we do it only once.
91  We obtain a handler (which is typically just a pointer to actual data)
92  on the first operation and use it throughout the process.
93
94* Efficient archive file handling
95
96  LLD's handling of archive files (the files with ".a" file extension) is different
97  from the traditional Unix linkers and similar to Windows linkers.
98  We'll describe how the traditional Unix linker handles archive files,
99  what the problem is, and how LLD approached the problem.
100
101  The traditional Unix linker maintains a set of undefined symbols during linking.
102  The linker visits each file in the order as they appeared in the command line
103  until the set becomes empty. What the linker would do depends on file type.
104
105  - If the linker visits an object file, the linker links object files to the result,
106    and undefined symbols in the object file are added to the set.
107
108  - If the linker visits an archive file, it checks for the archive file's symbol table
109    and extracts all object files that have definitions for any symbols in the set.
110
111  This algorithm sometimes leads to a counter-intuitive behavior.
112  If you give archive files before object files, nothing will happen
113  because when the linker visits archives, there is no undefined symbols in the set.
114  As a result, no files are extracted from the first archive file,
115  and the link is done at that point because the set is empty after it visits one file.
116
117  You can fix the problem by reordering the files,
118  but that cannot fix the issue of mutually-dependent archive files.
119
120  Linking mutually-dependent archive files is tricky.
121  You may specify the same archive file multiple times to
122  let the linker visit it more than once.
123  Or, you may use the special command line options, `--start-group` and `--end-group`,
124  to let the linker loop over the files between the options until
125  no new symbols are added to the set.
126
127  Visiting the same archive files multiple makes the linker slower.
128
129  Here is how LLD approached the problem. Instead of memorizing only undefined symbols,
130  we program LLD so that it memorizes all symbols.
131  When it sees an undefined symbol that can be resolved by extracting an object file
132  from an archive file it previously visited, it immediately extracts the file and link it.
133  It is doable because LLD does not forget symbols it have seen in archive files.
134
135  We believe that the LLD's way is efficient and easy to justify.
136
137  The semantics of LLD's archive handling is different from the traditional Unix's.
138  You can observe it if you carefully craft archive files to exploit it.
139  However, in reality, we don't know any program that cannot link
140  with our algorithm so far, so it's not going to cause trouble.
141
142Numbers You Want to Know
143------------------------
144
145To give you intuition about what kinds of data the linker is mainly working on,
146I'll give you the list of objects and their numbers LLD has to read and process
147in order to link a very large executable. In order to link Chrome with debug info,
148which is roughly 2 GB in output size, LLD reads
149
150- 17,000 files,
151- 1,800,000 sections,
152- 6,300,000 symbols, and
153- 13,000,000 relocations.
154
155LLD produces the 2 GB executable in 15 seconds.
156
157These numbers vary depending on your program, but in general,
158you have a lot of relocations and symbols for each file.
159If your program is written in C++, symbol names are likely to be
160pretty long because of name mangling.
161
162It is important to not waste time on relocations and symbols.
163
164In the above case, the total amount of symbol strings is 450 MB,
165and inserting all of them to a hash table takes 1.5 seconds.
166Therefore, if you causally add a hash table lookup for each symbol,
167it would slow down the linker by 10%. So, don't do that.
168
169On the other hand, you don't have to pursue efficiency
170when handling files.
171
172Important Data Strcutures
173-------------------------
174
175We will describe the key data structures in LLD in this section.
176The linker can be understood as the interactions between them.
177Once you understand their functions, the code of the linker should look obvious to you.
178
179* SymbolBody
180
181  SymbolBody is a class to represent symbols.
182  They are created for symbols in object files or archive files.
183  The linker creates linker-defined symbols as well.
184
185  There are basically three types of SymbolBodies: Defined, Undefined, or Lazy.
186
187  - Defined symbols are for all symbols that are considered as "resolved",
188    including real defined symbols, COMDAT symbols, common symbols,
189    absolute symbols, linker-created symbols, etc.
190  - Undefined symbols represent undefined symbols, which need to be replaced by
191    Defined symbols by the resolver until the link is complete.
192  - Lazy symbols represent symbols we found in archive file headers
193    which can turn into Defined if we read archieve members.
194
195* Symbol
196
197  A Symbol is a container for a SymbolBody. There's only one Symbol for each
198  unique symbol name (this uniqueness is guaranteed by the symbol table).
199  Each global symbol has only one SymbolBody at any one time, which is
200  the SymbolBody stored within a memory region of the Symbol large enough
201  to store any SymbolBody.
202
203  As the resolver reads symbols from input files, it replaces the Symbol's
204  SymbolBody with the "best" SymbolBody for its symbol name by constructing
205  the new SymbolBody in place on top of the existing SymbolBody. For example,
206  if the resolver is given a defined symbol, and the SymbolBody with its name
207  is undefined, it will construct a Defined SymbolBody over the Undefined
208  SymbolBody.
209
210  This means that each SymbolBody pointer always points to the best SymbolBody,
211  and it is possible to get from a SymbolBody to a Symbol, or vice versa,
212  by adding or subtracting a fixed offset. This memory layout helps reduce
213  the cache miss rate through high locality and a small number of required
214  pointer indirections.
215
216* SymbolTable
217
218  SymbolTable is basically a hash table from strings to Symbols
219  with a logic to resolve symbol conflicts. It resolves conflicts by symbol type.
220
221  - If we add Defined and Undefined symbols, the symbol table will keep the former.
222  - If we add Defined and Lazy symbols, it will keep the former.
223  - If we add Lazy and Undefined, it will keep the former,
224    but it will also trigger the Lazy symbol to load the archive member
225    to actually resolve the symbol.
226
227* Chunk (COFF specific)
228
229  Chunk represents a chunk of data that will occupy space in an output.
230  Each regular section becomes a chunk.
231  Chunks created for common or BSS symbols are not backed by sections.
232  The linker may create chunks to append additional data to an output as well.
233
234  Chunks know about their size, how to copy their data to mmap'ed outputs,
235  and how to apply relocations to them.
236  Specifically, section-based chunks know how to read relocation tables
237  and how to apply them.
238
239* InputSection (ELF specific)
240
241  Since we have less synthesized data for ELF, we don't abstract slices of
242  input files as Chunks for ELF. Instead, we directly use the input section
243  as an internal data type.
244
245  InputSection knows about their size and how to copy themselves to
246  mmap'ed outputs, just like COFF Chunks.
247
248* OutputSection
249
250  OutputSection is a container of InputSections (ELF) or Chunks (COFF).
251  An InputSection or Chunk belongs to at most one OutputSection.
252
253There are mainly three actors in this linker.
254
255* InputFile
256
257  InputFile is a superclass of file readers.
258  We have a different subclass for each input file type,
259  such as regular object file, archive file, etc.
260  They are responsible for creating and owning SymbolBodies and
261  InputSections/Chunks.
262
263* Writer
264
265  The writer is responsible for writing file headers and InputSections/Chunks to a file.
266  It creates OutputSections, put all InputSections/Chunks into them,
267  assign unique, non-overlapping addresses and file offsets to them,
268  and then write them down to a file.
269
270* Driver
271
272  The linking process is driven by the driver. The driver
273
274  - processes command line options,
275  - creates a symbol table,
276  - creates an InputFile for each input file and put all symbols in it into the symbol table,
277  - checks if there's no remaining undefined symbols,
278  - creates a writer,
279  - and passes the symbol table to the writer to write the result to a file.
280
281Link-Time Optimization
282----------------------
283
284LTO is implemented by handling LLVM bitcode files as object files.
285The linker resolves symbols in bitcode files normally. If all symbols
286are successfully resolved, it then runs LLVM passes
287with all bitcode files to convert them to one big regular ELF/COFF file.
288Finally, the linker replaces bitcode symbols with ELF/COFF symbols,
289so that they are linked as if they were in the native format from the beginning.
290
291The details are described in this document.
292http://llvm.org/docs/LinkTimeOptimization.html
293
294Glossary
295--------
296
297* RVA (COFF)
298
299  Short for Relative Virtual Address.
300
301  Windows executables or DLLs are not position-independent; they are
302  linked against a fixed address called an image base. RVAs are
303  offsets from an image base.
304
305  Default image bases are 0x140000000 for executables and 0x18000000
306  for DLLs. For example, when we are creating an executable, we assume
307  that the executable will be loaded at address 0x140000000 by the
308  loader, so we apply relocations accordingly. Result texts and data
309  will contain raw absolute addresses.
310
311* VA
312
313  Short for Virtual Address. For COFF, it is equivalent to RVA + image base.
314
315* Base relocations (COFF)
316
317  Relocation information for the loader. If the loader decides to map
318  an executable or a DLL to a different address than their image
319  bases, it fixes up binaries using information contained in the base
320  relocation table. A base relocation table consists of a list of
321  locations containing addresses. The loader adds a difference between
322  RVA and actual load address to all locations listed there.
323
324  Note that this run-time relocation mechanism is much simpler than ELF.
325  There's no PLT or GOT. Images are relocated as a whole just
326  by shifting entire images in memory by some offsets. Although doing
327  this breaks text sharing, I think this mechanism is not actually bad
328  on today's computers.
329
330* ICF
331
332  Short for Identical COMDAT Folding (COFF) or Identical Code Folding (ELF).
333
334  ICF is an optimization to reduce output size by merging read-only sections
335  by not only their names but by their contents. If two read-only sections
336  happen to have the same metadata, actual contents and relocations,
337  they are merged by ICF. It is known as an effective technique,
338  and it usually reduces C++ program's size by a few percent or more.
339
340  Note that this is not entirely sound optimization. C/C++ require
341  different functions have different addresses. If a program depends on
342  that property, it would fail at runtime.
343
344  On Windows, that's not really an issue because MSVC link.exe enabled
345  the optimization by default. As long as your program works
346  with the linker's default settings, your program should be safe with ICF.
347
348  On Unix, your program is generally not guaranteed to be safe with ICF,
349  although large programs happen to work correctly.
350  LLD works fine with ICF for example.
351