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