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