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 // Symbol visibility. This is the computed minimum visibility of all
149 // observed non-DSO symbols.
150 uint8_t visibility() const { return stOther & 3; }
151 void setVisibility(uint8_t visibility) {
152 stOther = (stOther & ~3) | visibility;
153 }
154
155 uint8_t computeBinding(Ctx &) const;
156 bool isGlobal() const { return binding == llvm::ELF::STB_GLOBAL; }
157 bool isWeak() const { return binding == llvm::ELF::STB_WEAK; }
158
159 bool isUndefined() const { return symbolKind == UndefinedKind; }
160 bool isCommon() const { return symbolKind == CommonKind; }
161 bool isDefined() const { return symbolKind == DefinedKind; }
162 bool isShared() const { return symbolKind == SharedKind; }
163 bool isPlaceholder() const { return symbolKind == PlaceholderKind; }
164
165 bool isLocal() const { return binding == llvm::ELF::STB_LOCAL; }
166
167 bool isLazy() const { return symbolKind == LazyKind; }
168
169 // True if this is an undefined weak symbol. This only works once
170 // all input files have been added.
171 bool isUndefWeak() const { return isWeak() && isUndefined(); }
172
173 StringRef getName() const { return {nameData, nameSize}; }
174
175 void setName(StringRef s) {
176 nameData = s.data();
177 nameSize = s.size();
178 }
179
180 void parseSymbolVersion(Ctx &);
181
182 // Get the NUL-terminated version suffix ("", "@...", or "@@...").
183 //
184 // For @@, the name has been truncated by insert(). For @, the name has been
185 // truncated by Symbol::parseSymbolVersion(ctx).
186 const char *getVersionSuffix() const { return nameData + nameSize; }
187
188 uint32_t getGotIdx(Ctx &ctx) const { return ctx.symAux[auxIdx].gotIdx; }
189 uint32_t getPltIdx(Ctx &ctx) const { return ctx.symAux[auxIdx].pltIdx; }
190 uint32_t getTlsDescIdx(Ctx &ctx) const {
191 return ctx.symAux[auxIdx].tlsDescIdx;
192 }
193 uint32_t getTlsGdIdx(Ctx &ctx) const { return ctx.symAux[auxIdx].tlsGdIdx; }
194
195 bool isInGot(Ctx &ctx) const { return getGotIdx(ctx) != uint32_t(-1); }
196 bool isInPlt(Ctx &ctx) const { return getPltIdx(ctx) != uint32_t(-1); }
197
198 uint64_t getVA(Ctx &, int64_t addend = 0) const;
199
200 uint64_t getGotOffset(Ctx &) const;
201 uint64_t getGotVA(Ctx &) const;
202 uint64_t getGotPltOffset(Ctx &) const;
203 uint64_t getGotPltVA(Ctx &) const;
204 uint64_t getPltOffset(Ctx &) const;
205 uint64_t getPltVA(Ctx &) const;
206 uint64_t getSize() const;
207 OutputSection *getOutputSection() const;
208
209 // The following two functions are used for symbol resolution.
210 //
211 // You are expected to call mergeProperties for all symbols in input
212 // files so that attributes that are attached to names rather than
213 // indivisual symbol (such as visibility) are merged together.
214 //
215 // Every time you read a new symbol from an input, you are supposed
216 // to call resolve() with the new symbol. That function replaces
217 // "this" object as a result of name resolution if the new symbol is
218 // more appropriate to be included in the output.
219 //
220 // For example, if "this" is an undefined symbol and a new symbol is
221 // a defined symbol, "this" is replaced with the new symbol.
222 void mergeProperties(const Symbol &other);
223 void resolve(Ctx &, const Undefined &other);
224 void resolve(Ctx &, const CommonSymbol &other);
225 void resolve(Ctx &, const Defined &other);
226 void resolve(Ctx &, const LazySymbol &other);
227 void resolve(Ctx &, const SharedSymbol &other);
228
229 // If this is a lazy symbol, extract an input file and add the symbol
230 // in the file to the symbol table. Calling this function on
231 // non-lazy object causes a runtime error.
232 void extract(Ctx &) const;
233
234 void checkDuplicate(Ctx &, const Defined &other) const;
235
236private:
237 bool shouldReplace(Ctx &, const Defined &other) const;
238
239protected:
240 Symbol(Kind k, InputFile *file, StringRef name, uint8_t binding,
241 uint8_t stOther, uint8_t type)
242 : file(file), nameData(name.data()), nameSize(name.size()), type(type),
243 binding(binding), stOther(stOther), symbolKind(k), isPreemptible(false),
244 isUsedInRegularObj(false), isExported(false), ltoCanOmit(false),
245 traced(false), hasVersionSuffix(false), isInIplt(false),
246 gotInIgot(false), folded(false), archSpecificBit(false),
247 scriptDefined(false), dsoDefined(false), dsoProtected(false),
248 versionScriptAssigned(false), thunkAccessed(false),
249 inDynamicList(false), referenced(false), referencedAfterWrap(false) {}
250
251 void overwrite(Symbol &sym, Kind k) const {
252 if (sym.traced)
253 printTraceSymbol(sym: *this, name: sym.getName());
254 sym.file = file;
255 sym.type = type;
256 sym.binding = binding;
257 sym.stOther = (stOther & ~3) | sym.visibility();
258 sym.symbolKind = k;
259 }
260
261public:
262 // True if this symbol is in the Iplt sub-section of the Plt and the Igot
263 // sub-section of the .got.plt or .got.
264 LLVM_PREFERRED_TYPE(bool)
265 uint8_t isInIplt : 1;
266
267 // True if this symbol needs a GOT entry and its GOT entry is actually in
268 // Igot. This will be true only for certain non-preemptible ifuncs.
269 LLVM_PREFERRED_TYPE(bool)
270 uint8_t gotInIgot : 1;
271
272 // True if defined relative to a section discarded by ICF.
273 LLVM_PREFERRED_TYPE(bool)
274 uint8_t folded : 1;
275
276 // Allow reuse of a bit between architecture-exclusive symbol flags.
277 // - needsTocRestore(): On PPC64, true if a call to this symbol needs to be
278 // followed by a restore of the toc pointer.
279 // - isTagged(): On AArch64, true if the symbol needs special relocation and
280 // metadata semantics because it's tagged, under the AArch64 MemtagABI.
281 LLVM_PREFERRED_TYPE(bool)
282 uint8_t archSpecificBit : 1;
283 bool needsTocRestore() const { return archSpecificBit; }
284 bool isTagged() const { return archSpecificBit; }
285 void setNeedsTocRestore(bool v) { archSpecificBit = v; }
286 void setIsTagged(bool v) {
287 archSpecificBit = v;
288 }
289
290 // True if this symbol is defined by a symbol assignment or wrapped by --wrap.
291 //
292 // LTO shouldn't inline the symbol because it doesn't know the final content
293 // of the symbol.
294 LLVM_PREFERRED_TYPE(bool)
295 uint8_t scriptDefined : 1;
296
297 // True if defined in a DSO. There may also be a definition in a relocatable
298 // object file.
299 LLVM_PREFERRED_TYPE(bool)
300 uint8_t dsoDefined : 1;
301
302 // True if defined in a DSO as protected visibility.
303 LLVM_PREFERRED_TYPE(bool)
304 uint8_t dsoProtected : 1;
305
306 // Temporary flags used to communicate which symbol entries need PLT and GOT
307 // entries during postScanRelocations();
308 std::atomic<uint16_t> flags = 0;
309
310 // A ctx.symAux index used to access GOT/PLT entry indexes. This is allocated
311 // in postScanRelocations().
312 uint32_t auxIdx = 0;
313 uint32_t dynsymIndex = 0;
314
315 // If `file` is SharedFile (for SharedSymbol or copy-relocated Defined), this
316 // represents the Verdef index within the input DSO, which will be converted
317 // to a Verneed index in the output. Otherwise, this represents the Verdef
318 // index (VER_NDX_LOCAL, VER_NDX_GLOBAL, or a named version).
319 // VER_NDX_LOCAL indicates a defined symbol that has been localized by a
320 // version script's local: directive or --exclude-libs.
321 uint16_t versionId = 0;
322 LLVM_PREFERRED_TYPE(bool)
323 uint8_t versionScriptAssigned : 1;
324
325 // True if targeted by a range extension thunk.
326 LLVM_PREFERRED_TYPE(bool)
327 uint8_t thunkAccessed : 1;
328
329 // True if the symbol is in the --dynamic-list file. A Defined symbol with
330 // protected or default visibility with this property is required to be
331 // exported into .dynsym.
332 LLVM_PREFERRED_TYPE(bool)
333 uint8_t inDynamicList : 1;
334
335 // Used to track if there has been at least one undefined reference to the
336 // symbol. For Undefined and SharedSymbol, the binding may change to STB_WEAK
337 // if the first undefined reference from a non-shared object is weak.
338 LLVM_PREFERRED_TYPE(bool)
339 uint8_t referenced : 1;
340
341 // Used to track if this symbol will be referenced after wrapping is performed
342 // (i.e. this will be true for foo if __real_foo is referenced, and will be
343 // true for __wrap_foo if foo is referenced).
344 LLVM_PREFERRED_TYPE(bool)
345 uint8_t referencedAfterWrap : 1;
346
347 void setFlags(uint16_t bits) {
348 flags.fetch_or(i: bits, m: std::memory_order_relaxed);
349 }
350 bool hasFlag(uint16_t bit) const {
351 assert(llvm::has_single_bit(bit) && "bit must be a power of 2");
352 return flags.load(m: std::memory_order_relaxed) & bit;
353 }
354
355 bool needsDynReloc() const {
356 return flags.load(m: std::memory_order_relaxed) &
357 (NEEDS_COPY | NEEDS_GOT | NEEDS_PLT | NEEDS_TLSDESC | NEEDS_TLSGD |
358 NEEDS_GOT_DTPREL | NEEDS_TLSIE | NEEDS_GOT_AUTH |
359 NEEDS_TLSDESC_AUTH);
360 }
361 void allocateAux(Ctx &ctx) {
362 assert(auxIdx == 0);
363 auxIdx = ctx.symAux.size();
364 ctx.symAux.emplace_back();
365 }
366
367 bool isSection() const { return type == llvm::ELF::STT_SECTION; }
368 bool isTls() const { return type == llvm::ELF::STT_TLS; }
369 bool isFunc() const { return type == llvm::ELF::STT_FUNC; }
370 bool isGnuIFunc() const { return type == llvm::ELF::STT_GNU_IFUNC; }
371 bool isObject() const { return type == llvm::ELF::STT_OBJECT; }
372 bool isFile() const { return type == llvm::ELF::STT_FILE; }
373};
374
375// Represents a symbol that is defined in the current output file.
376class Defined : public Symbol {
377public:
378 Defined(Ctx &ctx, InputFile *file, StringRef name, uint8_t binding,
379 uint8_t stOther, uint8_t type, uint64_t value, uint64_t size,
380 SectionBase *section)
381 : Symbol(DefinedKind, file, name, binding, stOther, type), value(value),
382 size(size), section(section) {
383 }
384 void overwrite(Symbol &sym) const;
385
386 static bool classof(const Symbol *s) { return s->isDefined(); }
387
388 uint64_t value;
389 uint64_t size;
390 SectionBase *section;
391};
392
393// Represents a common symbol.
394//
395// On Unix, it is traditionally allowed to write variable definitions
396// without initialization expressions (such as "int foo;") to header
397// files. Such definition is called "tentative definition".
398//
399// Using tentative definition is usually considered a bad practice
400// because you should write only declarations (such as "extern int
401// foo;") to header files. Nevertheless, the linker and the compiler
402// have to do something to support bad code by allowing duplicate
403// definitions for this particular case.
404//
405// Common symbols represent variable definitions without initializations.
406// The compiler creates common symbols when it sees variable definitions
407// without initialization (you can suppress this behavior and let the
408// compiler create a regular defined symbol by -fno-common).
409//
410// The linker allows common symbols to be replaced by regular defined
411// symbols. If there are remaining common symbols after name resolution is
412// complete, they are converted to regular defined symbols in a .bss
413// section. (Therefore, the later passes don't see any CommonSymbols.)
414class CommonSymbol : public Symbol {
415public:
416 CommonSymbol(Ctx &ctx, InputFile *file, StringRef name, uint8_t binding,
417 uint8_t stOther, uint8_t type, uint64_t alignment, uint64_t size)
418 : Symbol(CommonKind, file, name, binding, stOther, type),
419 alignment(alignment), size(size) {
420 }
421 void overwrite(Symbol &sym) const {
422 Symbol::overwrite(sym, k: CommonKind);
423 auto &s = static_cast<CommonSymbol &>(sym);
424 s.alignment = alignment;
425 s.size = size;
426 }
427
428 static bool classof(const Symbol *s) { return s->isCommon(); }
429
430 uint32_t alignment;
431 uint64_t size;
432};
433
434class Undefined : public Symbol {
435public:
436 Undefined(InputFile *file, StringRef name, uint8_t binding, uint8_t stOther,
437 uint8_t type, uint32_t discardedSecIdx = 0)
438 : Symbol(UndefinedKind, file, name, binding, stOther, type),
439 discardedSecIdx(discardedSecIdx) {}
440 void overwrite(Symbol &sym) const {
441 Symbol::overwrite(sym, k: UndefinedKind);
442 auto &s = static_cast<Undefined &>(sym);
443 s.discardedSecIdx = discardedSecIdx;
444 s.nonPrevailing = nonPrevailing;
445 }
446
447 static bool classof(const Symbol *s) { return s->kind() == UndefinedKind; }
448
449 // The section index if in a discarded section, 0 otherwise.
450 uint32_t discardedSecIdx;
451 bool nonPrevailing = false;
452};
453
454class SharedSymbol : public Symbol {
455public:
456 static bool classof(const Symbol *s) { return s->kind() == SharedKind; }
457
458 SharedSymbol(InputFile &file, StringRef name, uint8_t binding,
459 uint8_t stOther, uint8_t type, uint64_t value, uint64_t size,
460 uint32_t alignment)
461 : Symbol(SharedKind, &file, name, binding, stOther, type), value(value),
462 size(size), alignment(alignment) {
463 dsoProtected = visibility() == llvm::ELF::STV_PROTECTED;
464 // GNU ifunc is a mechanism to allow user-supplied functions to
465 // resolve PLT slot values at load-time. This is contrary to the
466 // regular symbol resolution scheme in which symbols are resolved just
467 // by name. Using this hook, you can program how symbols are solved
468 // for you program. For example, you can make "memcpy" to be resolved
469 // to a SSE-enabled version of memcpy only when a machine running the
470 // program supports the SSE instruction set.
471 //
472 // Naturally, such symbols should always be called through their PLT
473 // slots. What GNU ifunc symbols point to are resolver functions, and
474 // calling them directly doesn't make sense (unless you are writing a
475 // loader).
476 //
477 // For DSO symbols, we always call them through PLT slots anyway.
478 // So there's no difference between GNU ifunc and regular function
479 // symbols if they are in DSOs. So we can handle GNU_IFUNC as FUNC.
480 if (this->type == llvm::ELF::STT_GNU_IFUNC)
481 this->type = llvm::ELF::STT_FUNC;
482 }
483 void overwrite(Symbol &sym) const {
484 Symbol::overwrite(sym, k: SharedKind);
485 auto &s = static_cast<SharedSymbol &>(sym);
486 s.dsoProtected = dsoProtected;
487 s.value = value;
488 s.size = size;
489 s.alignment = alignment;
490 }
491
492 uint64_t value; // st_value
493 uint64_t size; // st_size
494 uint32_t alignment;
495};
496
497// LazySymbol symbols represent symbols in object files between --start-lib and
498// --end-lib options. LLD also handles traditional archives as if all the files
499// in the archive are surrounded by --start-lib and --end-lib.
500//
501// A special complication is the handling of weak undefined symbols. They should
502// not load a file, but we have to remember we have seen both the weak undefined
503// and the lazy. We represent that with a lazy symbol with a weak binding. This
504// means that code looking for undefined symbols normally also has to take lazy
505// symbols into consideration.
506class LazySymbol : public Symbol {
507public:
508 LazySymbol(InputFile &file)
509 : Symbol(LazyKind, &file, {}, llvm::ELF::STB_GLOBAL,
510 llvm::ELF::STV_DEFAULT, llvm::ELF::STT_NOTYPE) {}
511 void overwrite(Symbol &sym) const { Symbol::overwrite(sym, k: LazyKind); }
512
513 static bool classof(const Symbol *s) { return s->kind() == LazyKind; }
514};
515
516// A buffer class that is large enough to hold any Symbol-derived
517// object. We allocate memory using this class and instantiate a symbol
518// using the placement new.
519
520// It is important to keep the size of SymbolUnion small for performance and
521// memory usage reasons. 64 bytes is a soft limit based on the size of Defined
522// on a 64-bit system. This is enforced by a static_assert in Symbols.cpp.
523union SymbolUnion {
524 alignas(Defined) char a[sizeof(Defined)];
525 alignas(CommonSymbol) char b[sizeof(CommonSymbol)];
526 alignas(Undefined) char c[sizeof(Undefined)];
527 alignas(SharedSymbol) char d[sizeof(SharedSymbol)];
528 alignas(LazySymbol) char e[sizeof(LazySymbol)];
529};
530
531template <typename... T> Defined *makeDefined(T &&...args) {
532 auto *sym = getSpecificAllocSingleton<SymbolUnion>().Allocate();
533 auto &s = *new (reinterpret_cast<Defined *>(sym)) Defined(std::forward<T>(args)...);
534 return &s;
535}
536
537void reportDuplicate(Ctx &, const Symbol &sym, const InputFile *newFile,
538 InputSectionBase *errSec, uint64_t errOffset);
539void maybeWarnUnorderableSymbol(Ctx &, const Symbol *sym);
540bool computeIsPreemptible(Ctx &, const Symbol &sym);
541void parseVersionAndComputeIsPreemptible(Ctx &);
542
543} // namespace lld::elf
544
545#endif
546