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

source code of lld/ELF/Symbols.h