xref: /freebsd/contrib/llvm-project/lld/ELF/Symbols.h (revision 06c3fb2749bda94cb5201f81ffdb8fa6c3161b2e)
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 
24 namespace lld {
25 namespace elf {
26 class Symbol;
27 }
28 // Returns a string representation for a symbol for diagnostics.
29 std::string toString(const elf::Symbol &);
30 
31 namespace elf {
32 class CommonSymbol;
33 class Defined;
34 class OutputSection;
35 class SectionBase;
36 class InputSectionBase;
37 class SharedSymbol;
38 class Symbol;
39 class Undefined;
40 class LazyObject;
41 class InputFile;
42 
43 void printTraceSymbol(const Symbol &sym, StringRef name);
44 
45 enum {
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.
61 struct SymbolAux {
62   uint32_t gotIdx = -1;
63   uint32_t pltIdx = -1;
64   uint32_t tlsDescIdx = -1;
65   uint32_t tlsGdIdx = -1;
66 };
67 
68 LLVM_LIBRARY_VISIBILITY extern SmallVector<SymbolAux, 0> symAux;
69 
70 // The base class for real symbol classes.
71 class Symbol {
72 public:
73   enum Kind {
74     PlaceholderKind,
75     DefinedKind,
76     CommonKind,
77     SharedKind,
78     UndefinedKind,
79     LazyObjectKind,
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(this, &o, sizeof(o)); }
90 
91 protected:
92   const char *nameData;
93   // 32-bit size saves space.
94   uint32_t nameSize;
95 
96 public:
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 == LazyObjectKind; }
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 LazyObject &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 
250 private:
251   bool shouldReplace(const Defined &other) const;
252 
253 protected:
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),
258         exportDynamic(false) {}
259 
260   void overwrite(Symbol &sym, Kind k) const {
261     if (sym.traced)
262       printTraceSymbol(*this, 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 
270 public:
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   // True if a call to this symbol needs to be followed by a restore of the
283   // PPC64 toc pointer.
284   uint8_t needsTocRestore : 1;
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   uint8_t scriptDefined : 1;
291 
292   // True if defined in a DSO as protected visibility.
293   uint8_t dsoProtected : 1;
294 
295   // True if targeted by a range extension thunk.
296   uint8_t thunkAccessed : 1;
297 
298   // Temporary flags used to communicate which symbol entries need PLT and GOT
299   // entries during postScanRelocations();
300   std::atomic<uint16_t> flags;
301 
302   // A symAux index used to access GOT/PLT entry indexes. This is allocated in
303   // postScanRelocations().
304   uint32_t auxIdx;
305   uint32_t dynsymIndex;
306 
307   // This field is a index to the symbol's version definition.
308   uint16_t verdefIndex;
309 
310   // Version definition index.
311   uint16_t versionId;
312 
313   void setFlags(uint16_t bits) {
314     flags.fetch_or(bits, std::memory_order_relaxed);
315   }
316   bool hasFlag(uint16_t bit) const {
317     assert(bit && (bit & (bit - 1)) == 0 && "bit must be a power of 2");
318     return flags.load(std::memory_order_relaxed) & bit;
319   }
320 
321   bool needsDynReloc() const {
322     return flags.load(std::memory_order_relaxed) &
323            (NEEDS_COPY | NEEDS_GOT | NEEDS_PLT | NEEDS_TLSDESC | NEEDS_TLSGD |
324             NEEDS_TLSGD_TO_IE | NEEDS_GOT_DTPREL | NEEDS_TLSIE);
325   }
326   void allocateAux() {
327     assert(auxIdx == 0);
328     auxIdx = symAux.size();
329     symAux.emplace_back();
330   }
331 
332   bool isSection() const { return type == llvm::ELF::STT_SECTION; }
333   bool isTls() const { return type == llvm::ELF::STT_TLS; }
334   bool isFunc() const { return type == llvm::ELF::STT_FUNC; }
335   bool isGnuIFunc() const { return type == llvm::ELF::STT_GNU_IFUNC; }
336   bool isObject() const { return type == llvm::ELF::STT_OBJECT; }
337   bool isFile() const { return type == llvm::ELF::STT_FILE; }
338 };
339 
340 // Represents a symbol that is defined in the current output file.
341 class Defined : public Symbol {
342 public:
343   Defined(InputFile *file, StringRef name, uint8_t binding, uint8_t stOther,
344           uint8_t type, uint64_t value, uint64_t size, SectionBase *section)
345       : Symbol(DefinedKind, file, name, binding, stOther, type), value(value),
346         size(size), section(section) {
347     exportDynamic = config->exportDynamic;
348   }
349   void overwrite(Symbol &sym) const {
350     Symbol::overwrite(sym, DefinedKind);
351     sym.verdefIndex = -1;
352     auto &s = static_cast<Defined &>(sym);
353     s.value = value;
354     s.size = size;
355     s.section = section;
356   }
357 
358   static bool classof(const Symbol *s) { return s->isDefined(); }
359 
360   uint64_t value;
361   uint64_t size;
362   SectionBase *section;
363 };
364 
365 // Represents a common symbol.
366 //
367 // On Unix, it is traditionally allowed to write variable definitions
368 // without initialization expressions (such as "int foo;") to header
369 // files. Such definition is called "tentative definition".
370 //
371 // Using tentative definition is usually considered a bad practice
372 // because you should write only declarations (such as "extern int
373 // foo;") to header files. Nevertheless, the linker and the compiler
374 // have to do something to support bad code by allowing duplicate
375 // definitions for this particular case.
376 //
377 // Common symbols represent variable definitions without initializations.
378 // The compiler creates common symbols when it sees variable definitions
379 // without initialization (you can suppress this behavior and let the
380 // compiler create a regular defined symbol by -fno-common).
381 //
382 // The linker allows common symbols to be replaced by regular defined
383 // symbols. If there are remaining common symbols after name resolution is
384 // complete, they are converted to regular defined symbols in a .bss
385 // section. (Therefore, the later passes don't see any CommonSymbols.)
386 class CommonSymbol : public Symbol {
387 public:
388   CommonSymbol(InputFile *file, StringRef name, uint8_t binding,
389                uint8_t stOther, uint8_t type, uint64_t alignment, uint64_t size)
390       : Symbol(CommonKind, file, name, binding, stOther, type),
391         alignment(alignment), size(size) {
392     exportDynamic = config->exportDynamic;
393   }
394   void overwrite(Symbol &sym) const {
395     Symbol::overwrite(sym, CommonKind);
396     auto &s = static_cast<CommonSymbol &>(sym);
397     s.alignment = alignment;
398     s.size = size;
399   }
400 
401   static bool classof(const Symbol *s) { return s->isCommon(); }
402 
403   uint32_t alignment;
404   uint64_t size;
405 };
406 
407 class Undefined : public Symbol {
408 public:
409   Undefined(InputFile *file, StringRef name, uint8_t binding, uint8_t stOther,
410             uint8_t type, uint32_t discardedSecIdx = 0)
411       : Symbol(UndefinedKind, file, name, binding, stOther, type),
412         discardedSecIdx(discardedSecIdx) {}
413   void overwrite(Symbol &sym) const {
414     Symbol::overwrite(sym, UndefinedKind);
415     auto &s = static_cast<Undefined &>(sym);
416     s.discardedSecIdx = discardedSecIdx;
417     s.nonPrevailing = nonPrevailing;
418   }
419 
420   static bool classof(const Symbol *s) { return s->kind() == UndefinedKind; }
421 
422   // The section index if in a discarded section, 0 otherwise.
423   uint32_t discardedSecIdx;
424   bool nonPrevailing = false;
425 };
426 
427 class SharedSymbol : public Symbol {
428 public:
429   static bool classof(const Symbol *s) { return s->kind() == SharedKind; }
430 
431   SharedSymbol(InputFile &file, StringRef name, uint8_t binding,
432                uint8_t stOther, uint8_t type, uint64_t value, uint64_t size,
433                uint32_t alignment)
434       : Symbol(SharedKind, &file, name, binding, stOther, type), value(value),
435         size(size), alignment(alignment) {
436     exportDynamic = true;
437     dsoProtected = visibility() == llvm::ELF::STV_PROTECTED;
438     // GNU ifunc is a mechanism to allow user-supplied functions to
439     // resolve PLT slot values at load-time. This is contrary to the
440     // regular symbol resolution scheme in which symbols are resolved just
441     // by name. Using this hook, you can program how symbols are solved
442     // for you program. For example, you can make "memcpy" to be resolved
443     // to a SSE-enabled version of memcpy only when a machine running the
444     // program supports the SSE instruction set.
445     //
446     // Naturally, such symbols should always be called through their PLT
447     // slots. What GNU ifunc symbols point to are resolver functions, and
448     // calling them directly doesn't make sense (unless you are writing a
449     // loader).
450     //
451     // For DSO symbols, we always call them through PLT slots anyway.
452     // So there's no difference between GNU ifunc and regular function
453     // symbols if they are in DSOs. So we can handle GNU_IFUNC as FUNC.
454     if (this->type == llvm::ELF::STT_GNU_IFUNC)
455       this->type = llvm::ELF::STT_FUNC;
456   }
457   void overwrite(Symbol &sym) const {
458     Symbol::overwrite(sym, SharedKind);
459     auto &s = static_cast<SharedSymbol &>(sym);
460     s.dsoProtected = dsoProtected;
461     s.value = value;
462     s.size = size;
463     s.alignment = alignment;
464   }
465 
466   uint64_t value; // st_value
467   uint64_t size;  // st_size
468   uint32_t alignment;
469 };
470 
471 // LazyObject symbols represent symbols in object files between --start-lib and
472 // --end-lib options. LLD also handles traditional archives as if all the files
473 // in the archive are surrounded by --start-lib and --end-lib.
474 //
475 // A special complication is the handling of weak undefined symbols. They should
476 // not load a file, but we have to remember we have seen both the weak undefined
477 // and the lazy. We represent that with a lazy symbol with a weak binding. This
478 // means that code looking for undefined symbols normally also has to take lazy
479 // symbols into consideration.
480 class LazyObject : public Symbol {
481 public:
482   LazyObject(InputFile &file)
483       : Symbol(LazyObjectKind, &file, {}, llvm::ELF::STB_GLOBAL,
484                llvm::ELF::STV_DEFAULT, llvm::ELF::STT_NOTYPE) {}
485   void overwrite(Symbol &sym) const { Symbol::overwrite(sym, LazyObjectKind); }
486 
487   static bool classof(const Symbol *s) { return s->kind() == LazyObjectKind; }
488 };
489 
490 // Some linker-generated symbols need to be created as
491 // Defined symbols.
492 struct ElfSym {
493   // __bss_start
494   static Defined *bss;
495 
496   // etext and _etext
497   static Defined *etext1;
498   static Defined *etext2;
499 
500   // edata and _edata
501   static Defined *edata1;
502   static Defined *edata2;
503 
504   // end and _end
505   static Defined *end1;
506   static Defined *end2;
507 
508   // The _GLOBAL_OFFSET_TABLE_ symbol is defined by target convention to
509   // be at some offset from the base of the .got section, usually 0 or
510   // the end of the .got.
511   static Defined *globalOffsetTable;
512 
513   // _gp, _gp_disp and __gnu_local_gp symbols. Only for MIPS.
514   static Defined *mipsGp;
515   static Defined *mipsGpDisp;
516   static Defined *mipsLocalGp;
517 
518   // __global_pointer$ for RISC-V.
519   static Defined *riscvGlobalPointer;
520 
521   // __rel{,a}_iplt_{start,end} symbols.
522   static Defined *relaIpltStart;
523   static Defined *relaIpltEnd;
524 
525   // _TLS_MODULE_BASE_ on targets that support TLSDESC.
526   static Defined *tlsModuleBase;
527 };
528 
529 // A buffer class that is large enough to hold any Symbol-derived
530 // object. We allocate memory using this class and instantiate a symbol
531 // using the placement new.
532 
533 // It is important to keep the size of SymbolUnion small for performance and
534 // memory usage reasons. 64 bytes is a soft limit based on the size of Defined
535 // on a 64-bit system. This is enforced by a static_assert in Symbols.cpp.
536 union SymbolUnion {
537   alignas(Defined) char a[sizeof(Defined)];
538   alignas(CommonSymbol) char b[sizeof(CommonSymbol)];
539   alignas(Undefined) char c[sizeof(Undefined)];
540   alignas(SharedSymbol) char d[sizeof(SharedSymbol)];
541   alignas(LazyObject) char e[sizeof(LazyObject)];
542 };
543 
544 template <typename... T> Defined *makeDefined(T &&...args) {
545   auto *sym = getSpecificAllocSingleton<SymbolUnion>().Allocate();
546   memset(sym, 0, sizeof(Symbol));
547   auto &s = *new (reinterpret_cast<Defined *>(sym)) Defined(std::forward<T>(args)...);
548   return &s;
549 }
550 
551 void reportDuplicate(const Symbol &sym, const InputFile *newFile,
552                      InputSectionBase *errSec, uint64_t errOffset);
553 void maybeWarnUnorderableSymbol(const Symbol *sym);
554 bool computeIsPreemptible(const Symbol &sym);
555 
556 } // namespace elf
557 } // namespace lld
558 
559 #endif
560