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