1//===- Symbols.h ------------------------------------------------*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file defines various types of Symbols.
10//
11//===----------------------------------------------------------------------===//
12
13#ifndef LLD_ELF_SYMBOLS_H
14#define LLD_ELF_SYMBOLS_H
15
16#include "Config.h"
17#include "lld/Common/LLVM.h"
18#include "lld/Common/Memory.h"
19#include "llvm/ADT/DenseMap.h"
20#include "llvm/Object/ELF.h"
21#include "llvm/Support/Compiler.h"
22#include <tuple>
23
24namespace lld::elf {
25class CommonSymbol;
26class Defined;
27class OutputSection;
28class SectionBase;
29class InputSectionBase;
30class SharedSymbol;
31class Symbol;
32class Undefined;
33class LazySymbol;
34class InputFile;
35
36// Returns a string representation for a symbol for diagnostics.
37std::string toStr(Ctx &, const Symbol &);
38const ELFSyncStream &operator<<(const ELFSyncStream &, const Symbol *);
39
40void printTraceSymbol(const Symbol &sym, StringRef name);
41
42enum {
43 // True if an undefined or shared symbol is used from a live section.
44 //
45 // NOTE: In Writer.cpp the field is used to mark local defined symbols
46 // which are referenced by relocations when -r or --emit-relocs is given.
47 USED = 1 << 0,
48 NEEDS_GOT = 1 << 1,
49 NEEDS_PLT = 1 << 2,
50 HAS_DIRECT_RELOC = 1 << 3,
51 // True if this symbol needs a canonical PLT entry, or (during
52 // postScanRelocations) a copy relocation.
53 NEEDS_COPY = 1 << 4,
54 NEEDS_TLSDESC = 1 << 5,
55 NEEDS_TLSGD = 1 << 6,
56 NEEDS_GOT_DTPREL = 1 << 7,
57 NEEDS_TLSIE = 1 << 8,
58 NEEDS_GOT_AUTH = 1 << 9,
59 // 1 << 10 unused
60 NEEDS_TLSDESC_AUTH = 1 << 11,
61 // 1 << 12 unused
62};
63
64// The base class for real symbol classes.
65class Symbol {
66public:
67 enum Kind {
68 PlaceholderKind,
69 DefinedKind,
70 CommonKind,
71 SharedKind,
72 UndefinedKind,
73 LazyKind,
74 };
75
76 Kind kind() const { return static_cast<Kind>(symbolKind); }
77
78 // The file from which this symbol was created.
79 InputFile *file;
80
81 // Symbols are referenced by pointer throughout the linker, so an implicit
82 // copy would create a dangerous duplicate; copy the needed members
83 // explicitly instead. Deleting the copy operations also suppresses the
84 // implicit move operations.
85 Symbol(const Symbol &o) = delete;
86 Symbol &operator=(const Symbol &) = delete;
87
88protected:
89 const char *nameData;
90 // 32-bit size saves space.
91 uint32_t nameSize;
92
93public:
94 // The next three fields have the same meaning as the ELF symbol attributes.
95 // type and binding are placed in this order to optimize generating st_info,
96 // which is defined as (binding << 4) + (type & 0xf), on a little-endian
97 // system.
98 uint8_t type : 4; // symbol type
99
100 // Symbol binding. This is not overwritten by replace() to track
101 // changes during resolution. In particular:
102 // - An undefined weak is still weak when it resolves to a shared library.
103 // - An undefined weak will not extract archive members, but we have to
104 // remember it is weak.
105 uint8_t binding : 4;
106
107 uint8_t stOther; // st_other field value
108
109 uint8_t symbolKind;
110
111 // True if this symbol is preemptible at load time.
112 //
113 // Primarily set in two locations, (a) parseVersionAndComputeIsPreemptible and
114 // (b) demoteSymbolsAndComputeIsPreemptible.
115 LLVM_PREFERRED_TYPE(bool)
116 uint8_t isPreemptible : 1;
117
118 // True if the symbol was used for linking and thus need to be added to the
119 // output file's symbol table. This is true for all symbols except for
120 // unreferenced DSO symbols, lazy (archive) symbols, and bitcode symbols that
121 // are unreferenced except by other bitcode objects.
122 LLVM_PREFERRED_TYPE(bool)
123 uint8_t isUsedInRegularObj : 1;
124
125 // Used by a Defined symbol with protected or default visibility, to record
126 // whether it is required to be exported into .dynsym. This is set when any of
127 // the following conditions hold:
128 //
129 // - If there is an interposable symbol from a DSO. Note: We also do this for
130 // STV_PROTECTED symbols which can't be interposed (to match BFD behavior).
131 // - If -shared or --export-dynamic is specified, any symbol in an object
132 // file/bitcode sets this property, unless suppressed by LTO
133 // canBeOmittedFromSymbolTable().
134 LLVM_PREFERRED_TYPE(bool)
135 uint8_t isExported : 1;
136
137 LLVM_PREFERRED_TYPE(bool)
138 uint8_t ltoCanOmit : 1;
139
140 // True if this symbol is specified by --trace-symbol option.
141 LLVM_PREFERRED_TYPE(bool)
142 uint8_t traced : 1;
143
144 // True if the name contains '@'.
145 LLVM_PREFERRED_TYPE(bool)
146 uint8_t hasVersionSuffix : 1;
147
148 // True if the symbol is in SymbolTable::getSymbols().
149 LLVM_PREFERRED_TYPE(bool)
150 uint8_t inserted : 1;
151
152 // Symbol visibility. This is the computed minimum visibility of all
153 // observed non-DSO symbols.
154 uint8_t visibility() const { return stOther & 3; }
155 void setVisibility(uint8_t visibility) {
156 stOther = (stOther & ~3) | visibility;
157 }
158
159 uint8_t computeBinding(Ctx &) const;
160 bool isGlobal() const { return binding == llvm::ELF::STB_GLOBAL; }
161 bool isWeak() const { return binding == llvm::ELF::STB_WEAK; }
162
163 bool isUndefined() const { return symbolKind == UndefinedKind; }
164 bool isCommon() const { return symbolKind == CommonKind; }
165 bool isDefined() const { return symbolKind == DefinedKind; }
166 bool isShared() const { return symbolKind == SharedKind; }
167 bool isPlaceholder() const { return symbolKind == PlaceholderKind; }
168
169 bool isLocal() const { return binding == llvm::ELF::STB_LOCAL; }
170
171 bool isLazy() const { return symbolKind == LazyKind; }
172
173 // True if this is an undefined weak symbol. This only works once
174 // all input files have been added.
175 bool isUndefWeak() const { return isWeak() && isUndefined(); }
176
177 StringRef getName() const { return {nameData, nameSize}; }
178
179 void setName(StringRef s) {
180 nameData = s.data();
181 nameSize = s.size();
182 }
183
184 void parseSymbolVersion(Ctx &);
185
186 // Get the NUL-terminated version suffix ("", "@...", or "@@...").
187 //
188 // For @@, the name has been truncated by insert(). For @, the name has been
189 // truncated by Symbol::parseSymbolVersion(ctx).
190 const char *getVersionSuffix() const { return nameData + nameSize; }
191
192 uint32_t getGotIdx(Ctx &ctx) const { return ctx.symAux[auxIdx].gotIdx; }
193 uint32_t getPltIdx(Ctx &ctx) const { return ctx.symAux[auxIdx].pltIdx; }
194 uint32_t getTlsDescIdx(Ctx &ctx) const {
195 return ctx.symAux[auxIdx].tlsDescIdx;
196 }
197 uint32_t getTlsGdIdx(Ctx &ctx) const { return ctx.symAux[auxIdx].tlsGdIdx; }
198
199 bool isInGot(Ctx &ctx) const { return getGotIdx(ctx) != uint32_t(-1); }
200 bool isInPlt(Ctx &ctx) const { return getPltIdx(ctx) != uint32_t(-1); }
201
202 uint64_t getVA(Ctx &, int64_t addend = 0) const;
203
204 uint64_t getGotOffset(Ctx &) const;
205 uint64_t getGotVA(Ctx &) const;
206 uint64_t getGotPltOffset(Ctx &) const;
207 uint64_t getGotPltVA(Ctx &) const;
208 uint64_t getPltOffset(Ctx &) const;
209 uint64_t getPltVA(Ctx &) const;
210 uint64_t getSize() const;
211 OutputSection *getOutputSection() const;
212
213 // The following two functions are used for symbol resolution.
214 //
215 // You are expected to call mergeProperties for all symbols in input
216 // files so that attributes that are attached to names rather than
217 // indivisual symbol (such as visibility) are merged together.
218 //
219 // Every time you read a new symbol from an input, you are supposed
220 // to call resolve() with the new symbol. That function replaces
221 // "this" object as a result of name resolution if the new symbol is
222 // more appropriate to be included in the output.
223 //
224 // For example, if "this" is an undefined symbol and a new symbol is
225 // a defined symbol, "this" is replaced with the new symbol.
226 void mergeProperties(const Symbol &other);
227 void resolve(Ctx &, const Undefined &other);
228 void resolve(Ctx &, const CommonSymbol &other);
229 void resolve(Ctx &, const Defined &other);
230 void resolve(Ctx &, const LazySymbol &other);
231 void resolve(Ctx &, const SharedSymbol &other);
232
233 // If this is a lazy symbol, extract an input file and add the symbol
234 // in the file to the symbol table. Calling this function on
235 // non-lazy object causes a runtime error.
236 void extract(Ctx &) const;
237
238 void checkDuplicate(Ctx &, const Defined &other) const;
239
240private:
241 bool shouldReplace(Ctx &, const Defined &other) const;
242
243protected:
244 Symbol(Kind k, InputFile *file, StringRef name, uint8_t binding,
245 uint8_t stOther, uint8_t type)
246 : file(file), nameData(name.data()), nameSize(name.size()), type(type),
247 binding(binding), stOther(stOther), symbolKind(k), isPreemptible(false),
248 isUsedInRegularObj(false), isExported(false), ltoCanOmit(false),
249 traced(false), hasVersionSuffix(false), inserted(false),
250 isInIplt(false), gotInIgot(false), folded(false),
251 archSpecificBit(false), scriptDefined(false), dsoDefined(false),
252 dsoProtected(false), versionScriptAssigned(false), thunkAccessed(false),
253 inDynamicList(false), referenced(false), referencedAfterWrap(false) {}
254
255 void overwrite(Symbol &sym, Kind k) const {
256 if (sym.traced)
257 printTraceSymbol(sym: *this, name: sym.getName());
258 sym.file = file;
259 sym.type = type;
260 sym.binding = binding;
261 sym.stOther = (stOther & ~3) | sym.visibility();
262 sym.symbolKind = k;
263 }
264
265public:
266 // True if this symbol is in the Iplt sub-section of the Plt and the Igot
267 // sub-section of the .got.plt or .got.
268 LLVM_PREFERRED_TYPE(bool)
269 uint8_t isInIplt : 1;
270
271 // True if this symbol needs a GOT entry and its GOT entry is actually in
272 // Igot. This will be true only for certain non-preemptible ifuncs.
273 LLVM_PREFERRED_TYPE(bool)
274 uint8_t gotInIgot : 1;
275
276 // True if defined relative to a section discarded by ICF.
277 LLVM_PREFERRED_TYPE(bool)
278 uint8_t folded : 1;
279
280 // Allow reuse of a bit between architecture-exclusive symbol flags.
281 // - needsTocRestore(): On PPC64, true if a call to this symbol needs to be
282 // followed by a restore of the toc pointer.
283 // - isTagged(): On AArch64, true if the symbol needs special relocation and
284 // metadata semantics because it's tagged, under the AArch64 MemtagABI.
285 LLVM_PREFERRED_TYPE(bool)
286 uint8_t archSpecificBit : 1;
287 bool needsTocRestore() const { return archSpecificBit; }
288 bool isTagged() const { return archSpecificBit; }
289 void setNeedsTocRestore(bool v) { archSpecificBit = v; }
290 void setIsTagged(bool v) {
291 archSpecificBit = v;
292 }
293
294 // True if this symbol is defined by a symbol assignment or wrapped by --wrap.
295 //
296 // LTO shouldn't inline the symbol because it doesn't know the final content
297 // of the symbol.
298 LLVM_PREFERRED_TYPE(bool)
299 uint8_t scriptDefined : 1;
300
301 // True if defined in a DSO. There may also be a definition in a relocatable
302 // object file.
303 LLVM_PREFERRED_TYPE(bool)
304 uint8_t dsoDefined : 1;
305
306 // True if defined in a DSO as protected visibility.
307 LLVM_PREFERRED_TYPE(bool)
308 uint8_t dsoProtected : 1;
309
310 // Temporary flags used to communicate which symbol entries need PLT and GOT
311 // entries during postScanRelocations();
312 std::atomic<uint16_t> flags = 0;
313
314 // A ctx.symAux index used to access GOT/PLT entry indexes. This is allocated
315 // in postScanRelocations().
316 uint32_t auxIdx = 0;
317 uint32_t dynsymIndex = 0;
318
319 // If `file` is SharedFile (for SharedSymbol or copy-relocated Defined), this
320 // represents the Verdef index within the input DSO, which will be converted
321 // to a Verneed index in the output. Otherwise, this represents the Verdef
322 // index (VER_NDX_LOCAL, VER_NDX_GLOBAL, or a named version).
323 // VER_NDX_LOCAL indicates a defined symbol that has been localized by a
324 // version script's local: directive or --exclude-libs.
325 uint16_t versionId = 0;
326 LLVM_PREFERRED_TYPE(bool)
327 uint8_t versionScriptAssigned : 1;
328
329 // True if targeted by a range extension thunk.
330 LLVM_PREFERRED_TYPE(bool)
331 uint8_t thunkAccessed : 1;
332
333 // True if the symbol is in the --dynamic-list file. A Defined symbol with
334 // protected or default visibility with this property is required to be
335 // exported into .dynsym.
336 LLVM_PREFERRED_TYPE(bool)
337 uint8_t inDynamicList : 1;
338
339 // Used to track if there has been at least one undefined reference to the
340 // symbol. For Undefined and SharedSymbol, the binding may change to STB_WEAK
341 // if the first undefined reference from a non-shared object is weak.
342 LLVM_PREFERRED_TYPE(bool)
343 uint8_t referenced : 1;
344
345 // Used to track if this symbol will be referenced after wrapping is performed
346 // (i.e. this will be true for foo if __real_foo is referenced, and will be
347 // true for __wrap_foo if foo is referenced).
348 LLVM_PREFERRED_TYPE(bool)
349 uint8_t referencedAfterWrap : 1;
350
351 // True if this symbol is referenced by the embedded unoptimized part of
352 // dynamic debugging.
353 LLVM_PREFERRED_TYPE(bool)
354 uint8_t isDynDbgRef : 1;
355
356 void setFlags(uint16_t bits) {
357 flags.fetch_or(i: bits, m: std::memory_order_relaxed);
358 }
359 bool hasFlag(uint16_t bit) const {
360 assert(llvm::has_single_bit(bit) && "bit must be a power of 2");
361 return flags.load(m: std::memory_order_relaxed) & bit;
362 }
363
364 bool needsDynReloc() const {
365 return flags.load(m: std::memory_order_relaxed) &
366 (NEEDS_COPY | NEEDS_GOT | NEEDS_PLT | NEEDS_TLSDESC | NEEDS_TLSGD |
367 NEEDS_GOT_DTPREL | NEEDS_TLSIE | NEEDS_GOT_AUTH |
368 NEEDS_TLSDESC_AUTH);
369 }
370 void allocateAux(Ctx &ctx) {
371 assert(auxIdx == 0);
372 auxIdx = ctx.symAux.size();
373 ctx.symAux.emplace_back();
374 }
375
376 bool isSection() const { return type == llvm::ELF::STT_SECTION; }
377 bool isTls() const { return type == llvm::ELF::STT_TLS; }
378 bool isFunc() const { return type == llvm::ELF::STT_FUNC; }
379 bool isGnuIFunc() const { return type == llvm::ELF::STT_GNU_IFUNC; }
380 bool isObject() const { return type == llvm::ELF::STT_OBJECT; }
381 bool isFile() const { return type == llvm::ELF::STT_FILE; }
382};
383
384// Represents a symbol that is defined in the current output file.
385class Defined : public Symbol {
386public:
387 Defined(InputFile *file, StringRef name, uint8_t binding, uint8_t stOther,
388 uint8_t type, uint64_t value, uint64_t size, SectionBase *section)
389 : Symbol(DefinedKind, file, name, binding, stOther, type), value(value),
390 size(size), section(section) {}
391 void overwrite(Symbol &sym) const;
392
393 static bool classof(const Symbol *s) { return s->isDefined(); }
394
395 uint64_t value;
396 uint64_t size;
397 SectionBase *section;
398};
399
400// Represents a common symbol.
401//
402// On Unix, it is traditionally allowed to write variable definitions
403// without initialization expressions (such as "int foo;") to header
404// files. Such definition is called "tentative definition".
405//
406// Using tentative definition is usually considered a bad practice
407// because you should write only declarations (such as "extern int
408// foo;") to header files. Nevertheless, the linker and the compiler
409// have to do something to support bad code by allowing duplicate
410// definitions for this particular case.
411//
412// Common symbols represent variable definitions without initializations.
413// The compiler creates common symbols when it sees variable definitions
414// without initialization (you can suppress this behavior and let the
415// compiler create a regular defined symbol by -fno-common).
416//
417// The linker allows common symbols to be replaced by regular defined
418// symbols. If there are remaining common symbols after name resolution is
419// complete, they are converted to regular defined symbols in a .bss
420// section. (Therefore, the later passes don't see any CommonSymbols.)
421class CommonSymbol : public Symbol {
422public:
423 CommonSymbol(InputFile *file, StringRef name, uint8_t binding,
424 uint8_t stOther, uint8_t type, uint64_t alignment, uint64_t size)
425 : Symbol(CommonKind, file, name, binding, stOther, type),
426 alignment(alignment), size(size) {}
427 void overwrite(Symbol &sym) const {
428 Symbol::overwrite(sym, k: CommonKind);
429 auto &s = static_cast<CommonSymbol &>(sym);
430 s.alignment = alignment;
431 s.size = size;
432 }
433
434 static bool classof(const Symbol *s) { return s->isCommon(); }
435
436 uint32_t alignment;
437 uint64_t size;
438};
439
440class Undefined : public Symbol {
441public:
442 Undefined(InputFile *file, StringRef name, uint8_t binding, uint8_t stOther,
443 uint8_t type, uint32_t discardedSecIdx = 0)
444 : Symbol(UndefinedKind, file, name, binding, stOther, type),
445 discardedSecIdx(discardedSecIdx) {}
446 void overwrite(Symbol &sym) const {
447 Symbol::overwrite(sym, k: UndefinedKind);
448 auto &s = static_cast<Undefined &>(sym);
449 s.discardedSecIdx = discardedSecIdx;
450 s.nonPrevailing = nonPrevailing;
451 }
452
453 static bool classof(const Symbol *s) { return s->kind() == UndefinedKind; }
454
455 // The section index if in a discarded section, 0 otherwise.
456 uint32_t discardedSecIdx;
457 bool nonPrevailing = false;
458};
459
460class SharedSymbol : public Symbol {
461public:
462 static bool classof(const Symbol *s) { return s->kind() == SharedKind; }
463
464 SharedSymbol(InputFile &file, StringRef name, uint8_t binding,
465 uint8_t stOther, uint8_t type, uint64_t value, uint64_t size,
466 uint32_t alignment)
467 : Symbol(SharedKind, &file, name, binding, stOther, type), value(value),
468 size(size), alignment(alignment) {
469 dsoProtected = visibility() == llvm::ELF::STV_PROTECTED;
470 // GNU ifunc is a mechanism to allow user-supplied functions to
471 // resolve PLT slot values at load-time. This is contrary to the
472 // regular symbol resolution scheme in which symbols are resolved just
473 // by name. Using this hook, you can program how symbols are solved
474 // for you program. For example, you can make "memcpy" to be resolved
475 // to a SSE-enabled version of memcpy only when a machine running the
476 // program supports the SSE instruction set.
477 //
478 // Naturally, such symbols should always be called through their PLT
479 // slots. What GNU ifunc symbols point to are resolver functions, and
480 // calling them directly doesn't make sense (unless you are writing a
481 // loader).
482 //
483 // For DSO symbols, we always call them through PLT slots anyway.
484 // So there's no difference between GNU ifunc and regular function
485 // symbols if they are in DSOs. So we can handle GNU_IFUNC as FUNC.
486 if (this->type == llvm::ELF::STT_GNU_IFUNC)
487 this->type = llvm::ELF::STT_FUNC;
488 }
489 void overwrite(Symbol &sym) const {
490 Symbol::overwrite(sym, k: SharedKind);
491 auto &s = static_cast<SharedSymbol &>(sym);
492 s.dsoProtected = dsoProtected;
493 s.value = value;
494 s.size = size;
495 s.alignment = alignment;
496 }
497
498 uint64_t value; // st_value
499 uint64_t size; // st_size
500 uint32_t alignment;
501};
502
503// LazySymbol symbols represent symbols in object files between --start-lib and
504// --end-lib options. LLD also handles traditional archives as if all the files
505// in the archive are surrounded by --start-lib and --end-lib.
506//
507// A special complication is the handling of weak undefined symbols. They should
508// not load a file, but we have to remember we have seen both the weak undefined
509// and the lazy. We represent that with a lazy symbol with a weak binding. This
510// means that code looking for undefined symbols normally also has to take lazy
511// symbols into consideration.
512class LazySymbol : public Symbol {
513public:
514 LazySymbol(InputFile &file)
515 : Symbol(LazyKind, &file, {}, llvm::ELF::STB_GLOBAL,
516 llvm::ELF::STV_DEFAULT, llvm::ELF::STT_NOTYPE) {}
517 void overwrite(Symbol &sym) const { Symbol::overwrite(sym, k: LazyKind); }
518
519 static bool classof(const Symbol *s) { return s->kind() == LazyKind; }
520};
521
522// A buffer class that is large enough to hold any Symbol-derived
523// object. We allocate memory using this class and instantiate a symbol
524// using the placement new.
525
526// It is important to keep the size of SymbolUnion small for performance and
527// memory usage reasons. 64 bytes is a soft limit based on the size of Defined
528// on a 64-bit system. This is enforced by a static_assert in Symbols.cpp.
529union SymbolUnion {
530 alignas(Defined) char a[sizeof(Defined)];
531 alignas(CommonSymbol) char b[sizeof(CommonSymbol)];
532 alignas(Undefined) char c[sizeof(Undefined)];
533 alignas(SharedSymbol) char d[sizeof(SharedSymbol)];
534 alignas(LazySymbol) char e[sizeof(LazySymbol)];
535};
536
537template <typename... T> Defined *makeDefined(T &&...args) {
538 auto *sym = getSpecificAllocSingleton<SymbolUnion>().Allocate();
539 auto &s = *new (reinterpret_cast<Defined *>(sym)) Defined(std::forward<T>(args)...);
540 return &s;
541}
542
543void reportDuplicate(Ctx &, const Symbol &sym, const InputFile *newFile,
544 InputSectionBase *errSec, uint64_t errOffset);
545void maybeWarnUnorderableSymbol(Ctx &, const Symbol *sym);
546bool computeIsPreemptible(Ctx &, const Symbol &sym);
547void parseVersionAndComputeIsPreemptible(Ctx &);
548
549} // namespace lld::elf
550
551#endif
552