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