• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 "InputFiles.h"
17 #include "InputSection.h"
18 #include "lld/Common/LLVM.h"
19 #include "lld/Common/Strings.h"
20 #include "llvm/ADT/DenseMap.h"
21 #include "llvm/Object/Archive.h"
22 #include "llvm/Object/ELF.h"
23 
24 namespace lld {
25 // Returns a string representation for a symbol for diagnostics.
26 std::string toString(const elf::Symbol &);
27 
28 // There are two different ways to convert an Archive::Symbol to a string:
29 // One for Microsoft name mangling and one for Itanium name mangling.
30 // Call the functions toCOFFString and toELFString, not just toString.
31 std::string toELFString(const llvm::object::Archive::Symbol &);
32 
33 namespace elf {
34 class CommonSymbol;
35 class Defined;
36 class InputFile;
37 class LazyArchive;
38 class LazyObject;
39 class SharedSymbol;
40 class Symbol;
41 class Undefined;
42 
43 // This is a StringRef-like container that doesn't run strlen().
44 //
45 // ELF string tables contain a lot of null-terminated strings. Most of them
46 // are not necessary for the linker because they are names of local symbols,
47 // and the linker doesn't use local symbol names for name resolution. So, we
48 // use this class to represents strings read from string tables.
49 struct StringRefZ {
StringRefZStringRefZ50   StringRefZ(const char *s) : data(s), size(-1) {}
StringRefZStringRefZ51   StringRefZ(StringRef s) : data(s.data()), size(s.size()) {}
52 
53   const char *data;
54   const uint32_t size;
55 };
56 
57 // The base class for real symbol classes.
58 class Symbol {
59 public:
60   enum Kind {
61     PlaceholderKind,
62     DefinedKind,
63     CommonKind,
64     SharedKind,
65     UndefinedKind,
66     LazyArchiveKind,
67     LazyObjectKind,
68   };
69 
kind()70   Kind kind() const { return static_cast<Kind>(symbolKind); }
71 
72   // The file from which this symbol was created.
73   InputFile *file;
74 
75 protected:
76   const char *nameData;
77   mutable uint32_t nameSize;
78 
79 public:
80   uint32_t dynsymIndex = 0;
81   uint32_t gotIndex = -1;
82   uint32_t pltIndex = -1;
83 
84   uint32_t globalDynIndex = -1;
85 
86   // This field is a index to the symbol's version definition.
87   uint32_t verdefIndex = -1;
88 
89   // Version definition index.
90   uint16_t versionId;
91 
92   // Symbol binding. This is not overwritten by replace() to track
93   // changes during resolution. In particular:
94   //  - An undefined weak is still weak when it resolves to a shared library.
95   //  - An undefined weak will not fetch archive members, but we have to
96   //    remember it is weak.
97   uint8_t binding;
98 
99   // The following fields have the same meaning as the ELF symbol attributes.
100   uint8_t type;    // symbol type
101   uint8_t stOther; // st_other field value
102 
103   uint8_t symbolKind;
104 
105   // Symbol visibility. This is the computed minimum visibility of all
106   // observed non-DSO symbols.
107   uint8_t visibility : 2;
108 
109   // True if the symbol was used for linking and thus need to be added to the
110   // output file's symbol table. This is true for all symbols except for
111   // unreferenced DSO symbols, lazy (archive) symbols, and bitcode symbols that
112   // are unreferenced except by other bitcode objects.
113   uint8_t isUsedInRegularObj : 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.
120   // - If -shared or --export-dynamic is specified, any symbol in an object
121   //   file/bitcode sets this property, unless suppressed by LTO
122   //   canBeOmittedFromSymbolTable().
123   uint8_t exportDynamic : 1;
124 
125   // True if the symbol is in the --dynamic-list file. A Defined symbol with
126   // protected or default visibility with this property is required to be
127   // exported into .dynsym.
128   uint8_t inDynamicList : 1;
129 
130   // False if LTO shouldn't inline whatever this symbol points to. If a symbol
131   // is overwritten after LTO, LTO shouldn't inline the symbol because it
132   // doesn't know the final contents of the symbol.
133   uint8_t canInline : 1;
134 
135   // Used by Undefined and SharedSymbol to track if there has been at least one
136   // undefined reference to the symbol. The binding may change to STB_WEAK if
137   // the first undefined reference from a non-shared object is weak.
138   uint8_t referenced : 1;
139 
140   // True if this symbol is specified by --trace-symbol option.
141   uint8_t traced : 1;
142 
143   inline void replace(const Symbol &newSym);
144 
145   bool includeInDynsym() const;
146   uint8_t computeBinding() const;
isWeak()147   bool isWeak() const { return binding == llvm::ELF::STB_WEAK; }
148 
isUndefined()149   bool isUndefined() const { return symbolKind == UndefinedKind; }
isCommon()150   bool isCommon() const { return symbolKind == CommonKind; }
isDefined()151   bool isDefined() const { return symbolKind == DefinedKind; }
isShared()152   bool isShared() const { return symbolKind == SharedKind; }
isPlaceholder()153   bool isPlaceholder() const { return symbolKind == PlaceholderKind; }
154 
isLocal()155   bool isLocal() const { return binding == llvm::ELF::STB_LOCAL; }
156 
isLazy()157   bool isLazy() const {
158     return symbolKind == LazyArchiveKind || symbolKind == LazyObjectKind;
159   }
160 
161   // True if this is an undefined weak symbol. This only works once
162   // all input files have been added.
isUndefWeak()163   bool isUndefWeak() const {
164     // See comment on lazy symbols for details.
165     return isWeak() && (isUndefined() || isLazy());
166   }
167 
getName()168   StringRef getName() const {
169     if (nameSize == (uint32_t)-1)
170       nameSize = strlen(nameData);
171     return {nameData, nameSize};
172   }
173 
setName(StringRef s)174   void setName(StringRef s) {
175     nameData = s.data();
176     nameSize = s.size();
177   }
178 
179   void parseSymbolVersion();
180 
181   // Get the NUL-terminated version suffix ("", "@...", or "@@...").
182   //
183   // For @@, the name has been truncated by insert(). For @, the name has been
184   // truncated by Symbol::parseSymbolVersion().
getVersionSuffix()185   const char *getVersionSuffix() const {
186     (void)getName();
187     return nameData + nameSize;
188   }
189 
isInGot()190   bool isInGot() const { return gotIndex != -1U; }
isInPlt()191   bool isInPlt() const { return pltIndex != -1U; }
192 
193   uint64_t getVA(int64_t addend = 0) const;
194 
195   uint64_t getGotOffset() const;
196   uint64_t getGotVA() const;
197   uint64_t getGotPltOffset() const;
198   uint64_t getGotPltVA() const;
199   uint64_t getPltVA() const;
200   uint64_t getSize() const;
201   OutputSection *getOutputSection() const;
202 
203   // The following two functions are used for symbol resolution.
204   //
205   // You are expected to call mergeProperties for all symbols in input
206   // files so that attributes that are attached to names rather than
207   // indivisual symbol (such as visibility) are merged together.
208   //
209   // Every time you read a new symbol from an input, you are supposed
210   // to call resolve() with the new symbol. That function replaces
211   // "this" object as a result of name resolution if the new symbol is
212   // more appropriate to be included in the output.
213   //
214   // For example, if "this" is an undefined symbol and a new symbol is
215   // a defined symbol, "this" is replaced with the new symbol.
216   void mergeProperties(const Symbol &other);
217   void resolve(const Symbol &other);
218 
219   // If this is a lazy symbol, fetch an input file and add the symbol
220   // in the file to the symbol table. Calling this function on
221   // non-lazy object causes a runtime error.
222   void fetch() const;
223 
224 private:
isExportDynamic(Kind k,uint8_t visibility)225   static bool isExportDynamic(Kind k, uint8_t visibility) {
226     if (k == SharedKind)
227       return visibility == llvm::ELF::STV_DEFAULT;
228     return config->shared || config->exportDynamic;
229   }
230 
231   void resolveUndefined(const Undefined &other);
232   void resolveCommon(const CommonSymbol &other);
233   void resolveDefined(const Defined &other);
234   template <class LazyT> void resolveLazy(const LazyT &other);
235   void resolveShared(const SharedSymbol &other);
236 
237   int compare(const Symbol *other) const;
238 
239   inline size_t getSymbolSize() const;
240 
241 protected:
Symbol(Kind k,InputFile * file,StringRefZ name,uint8_t binding,uint8_t stOther,uint8_t type)242   Symbol(Kind k, InputFile *file, StringRefZ name, uint8_t binding,
243          uint8_t stOther, uint8_t type)
244       : file(file), nameData(name.data), nameSize(name.size), binding(binding),
245         type(type), stOther(stOther), symbolKind(k), visibility(stOther & 3),
246         isUsedInRegularObj(!file || file->kind() == InputFile::ObjKind),
247         exportDynamic(isExportDynamic(k, visibility)), inDynamicList(false),
248         canInline(false), referenced(false), traced(false), needsPltAddr(false),
249         isInIplt(false), gotInIgot(false), isPreemptible(false),
250         used(!config->gcSections), needsTocRestore(false),
251         scriptDefined(false) {}
252 
253 public:
254   // True the symbol should point to its PLT entry.
255   // For SharedSymbol only.
256   uint8_t needsPltAddr : 1;
257 
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   uint8_t isInIplt : 1;
261 
262   // True if this symbol needs a GOT entry and its GOT entry is actually in
263   // Igot. This will be true only for certain non-preemptible ifuncs.
264   uint8_t gotInIgot : 1;
265 
266   // True if this symbol is preemptible at load time.
267   uint8_t isPreemptible : 1;
268 
269   // True if an undefined or shared symbol is used from a live section.
270   //
271   // NOTE: In Writer.cpp the field is used to mark local defined symbols
272   // which are referenced by relocations when -r or --emit-relocs is given.
273   uint8_t used : 1;
274 
275   // True if a call to this symbol needs to be followed by a restore of the
276   // PPC64 toc pointer.
277   uint8_t needsTocRestore : 1;
278 
279   // True if this symbol is defined by a linker script.
280   uint8_t scriptDefined : 1;
281 
282   // The partition whose dynamic symbol table contains this symbol's definition.
283   uint8_t partition = 1;
284 
isSection()285   bool isSection() const { return type == llvm::ELF::STT_SECTION; }
isTls()286   bool isTls() const { return type == llvm::ELF::STT_TLS; }
isFunc()287   bool isFunc() const { return type == llvm::ELF::STT_FUNC; }
isGnuIFunc()288   bool isGnuIFunc() const { return type == llvm::ELF::STT_GNU_IFUNC; }
isObject()289   bool isObject() const { return type == llvm::ELF::STT_OBJECT; }
isFile()290   bool isFile() const { return type == llvm::ELF::STT_FILE; }
291 };
292 
293 // Represents a symbol that is defined in the current output file.
294 class Defined : public Symbol {
295 public:
Defined(InputFile * file,StringRefZ name,uint8_t binding,uint8_t stOther,uint8_t type,uint64_t value,uint64_t size,SectionBase * section)296   Defined(InputFile *file, StringRefZ name, uint8_t binding, uint8_t stOther,
297           uint8_t type, uint64_t value, uint64_t size, SectionBase *section)
298       : Symbol(DefinedKind, file, name, binding, stOther, type), value(value),
299         size(size), section(section) {}
300 
classof(const Symbol * s)301   static bool classof(const Symbol *s) { return s->isDefined(); }
302 
303   uint64_t value;
304   uint64_t size;
305   SectionBase *section;
306 };
307 
308 // Represents a common symbol.
309 //
310 // On Unix, it is traditionally allowed to write variable definitions
311 // without initialization expressions (such as "int foo;") to header
312 // files. Such definition is called "tentative definition".
313 //
314 // Using tentative definition is usually considered a bad practice
315 // because you should write only declarations (such as "extern int
316 // foo;") to header files. Nevertheless, the linker and the compiler
317 // have to do something to support bad code by allowing duplicate
318 // definitions for this particular case.
319 //
320 // Common symbols represent variable definitions without initializations.
321 // The compiler creates common symbols when it sees variable definitions
322 // without initialization (you can suppress this behavior and let the
323 // compiler create a regular defined symbol by -fno-common).
324 //
325 // The linker allows common symbols to be replaced by regular defined
326 // symbols. If there are remaining common symbols after name resolution is
327 // complete, they are converted to regular defined symbols in a .bss
328 // section. (Therefore, the later passes don't see any CommonSymbols.)
329 class CommonSymbol : public Symbol {
330 public:
CommonSymbol(InputFile * file,StringRefZ name,uint8_t binding,uint8_t stOther,uint8_t type,uint64_t alignment,uint64_t size)331   CommonSymbol(InputFile *file, StringRefZ name, uint8_t binding,
332                uint8_t stOther, uint8_t type, uint64_t alignment, uint64_t size)
333       : Symbol(CommonKind, file, name, binding, stOther, type),
334         alignment(alignment), size(size) {}
335 
classof(const Symbol * s)336   static bool classof(const Symbol *s) { return s->isCommon(); }
337 
338   uint32_t alignment;
339   uint64_t size;
340 };
341 
342 class Undefined : public Symbol {
343 public:
344   Undefined(InputFile *file, StringRefZ name, uint8_t binding, uint8_t stOther,
345             uint8_t type, uint32_t discardedSecIdx = 0)
Symbol(UndefinedKind,file,name,binding,stOther,type)346       : Symbol(UndefinedKind, file, name, binding, stOther, type),
347         discardedSecIdx(discardedSecIdx) {}
348 
classof(const Symbol * s)349   static bool classof(const Symbol *s) { return s->kind() == UndefinedKind; }
350 
351   // The section index if in a discarded section, 0 otherwise.
352   uint32_t discardedSecIdx;
353 };
354 
355 class SharedSymbol : public Symbol {
356 public:
classof(const Symbol * s)357   static bool classof(const Symbol *s) { return s->kind() == SharedKind; }
358 
SharedSymbol(InputFile & file,StringRef name,uint8_t binding,uint8_t stOther,uint8_t type,uint64_t value,uint64_t size,uint32_t alignment,uint32_t verdefIndex)359   SharedSymbol(InputFile &file, StringRef name, uint8_t binding,
360                uint8_t stOther, uint8_t type, uint64_t value, uint64_t size,
361                uint32_t alignment, uint32_t verdefIndex)
362       : Symbol(SharedKind, &file, name, binding, stOther, type), value(value),
363         size(size), alignment(alignment) {
364     this->verdefIndex = verdefIndex;
365     // GNU ifunc is a mechanism to allow user-supplied functions to
366     // resolve PLT slot values at load-time. This is contrary to the
367     // regular symbol resolution scheme in which symbols are resolved just
368     // by name. Using this hook, you can program how symbols are solved
369     // for you program. For example, you can make "memcpy" to be resolved
370     // to a SSE-enabled version of memcpy only when a machine running the
371     // program supports the SSE instruction set.
372     //
373     // Naturally, such symbols should always be called through their PLT
374     // slots. What GNU ifunc symbols point to are resolver functions, and
375     // calling them directly doesn't make sense (unless you are writing a
376     // loader).
377     //
378     // For DSO symbols, we always call them through PLT slots anyway.
379     // So there's no difference between GNU ifunc and regular function
380     // symbols if they are in DSOs. So we can handle GNU_IFUNC as FUNC.
381     if (this->type == llvm::ELF::STT_GNU_IFUNC)
382       this->type = llvm::ELF::STT_FUNC;
383   }
384 
getFile()385   SharedFile &getFile() const { return *cast<SharedFile>(file); }
386 
387   uint64_t value; // st_value
388   uint64_t size;  // st_size
389   uint32_t alignment;
390 };
391 
392 // LazyArchive and LazyObject represent a symbols that is not yet in the link,
393 // but we know where to find it if needed. If the resolver finds both Undefined
394 // and Lazy for the same name, it will ask the Lazy to load a file.
395 //
396 // A special complication is the handling of weak undefined symbols. They should
397 // not load a file, but we have to remember we have seen both the weak undefined
398 // and the lazy. We represent that with a lazy symbol with a weak binding. This
399 // means that code looking for undefined symbols normally also has to take lazy
400 // symbols into consideration.
401 
402 // This class represents a symbol defined in an archive file. It is
403 // created from an archive file header, and it knows how to load an
404 // object file from an archive to replace itself with a defined
405 // symbol.
406 class LazyArchive : public Symbol {
407 public:
LazyArchive(InputFile & file,const llvm::object::Archive::Symbol s)408   LazyArchive(InputFile &file, const llvm::object::Archive::Symbol s)
409       : Symbol(LazyArchiveKind, &file, s.getName(), llvm::ELF::STB_GLOBAL,
410                llvm::ELF::STV_DEFAULT, llvm::ELF::STT_NOTYPE),
411         sym(s) {}
412 
classof(const Symbol * s)413   static bool classof(const Symbol *s) { return s->kind() == LazyArchiveKind; }
414 
415   MemoryBufferRef getMemberBuffer();
416 
417   const llvm::object::Archive::Symbol sym;
418 };
419 
420 // LazyObject symbols represents symbols in object files between
421 // --start-lib and --end-lib options.
422 class LazyObject : public Symbol {
423 public:
LazyObject(InputFile & file,StringRef name)424   LazyObject(InputFile &file, StringRef name)
425       : Symbol(LazyObjectKind, &file, name, llvm::ELF::STB_GLOBAL,
426                llvm::ELF::STV_DEFAULT, llvm::ELF::STT_NOTYPE) {}
427 
classof(const Symbol * s)428   static bool classof(const Symbol *s) { return s->kind() == LazyObjectKind; }
429 };
430 
431 // Some linker-generated symbols need to be created as
432 // Defined symbols.
433 struct ElfSym {
434   // __bss_start
435   static Defined *bss;
436 
437   // etext and _etext
438   static Defined *etext1;
439   static Defined *etext2;
440 
441   // edata and _edata
442   static Defined *edata1;
443   static Defined *edata2;
444 
445   // end and _end
446   static Defined *end1;
447   static Defined *end2;
448 
449   // The _GLOBAL_OFFSET_TABLE_ symbol is defined by target convention to
450   // be at some offset from the base of the .got section, usually 0 or
451   // the end of the .got.
452   static Defined *globalOffsetTable;
453 
454   // _gp, _gp_disp and __gnu_local_gp symbols. Only for MIPS.
455   static Defined *mipsGp;
456   static Defined *mipsGpDisp;
457   static Defined *mipsLocalGp;
458 
459   // __rel{,a}_iplt_{start,end} symbols.
460   static Defined *relaIpltStart;
461   static Defined *relaIpltEnd;
462 
463   // __global_pointer$ for RISC-V.
464   static Defined *riscvGlobalPointer;
465 
466   // _TLS_MODULE_BASE_ on targets that support TLSDESC.
467   static Defined *tlsModuleBase;
468 };
469 
470 // A buffer class that is large enough to hold any Symbol-derived
471 // object. We allocate memory using this class and instantiate a symbol
472 // using the placement new.
473 union SymbolUnion {
474   alignas(Defined) char a[sizeof(Defined)];
475   alignas(CommonSymbol) char b[sizeof(CommonSymbol)];
476   alignas(Undefined) char c[sizeof(Undefined)];
477   alignas(SharedSymbol) char d[sizeof(SharedSymbol)];
478   alignas(LazyArchive) char e[sizeof(LazyArchive)];
479   alignas(LazyObject) char f[sizeof(LazyObject)];
480 };
481 
482 // It is important to keep the size of SymbolUnion small for performance and
483 // memory usage reasons. 80 bytes is a soft limit based on the size of Defined
484 // on a 64-bit system.
485 static_assert(sizeof(SymbolUnion) <= 80, "SymbolUnion too large");
486 
487 template <typename T> struct AssertSymbol {
488   static_assert(std::is_trivially_destructible<T>(),
489                 "Symbol types must be trivially destructible");
490   static_assert(sizeof(T) <= sizeof(SymbolUnion), "SymbolUnion too small");
491   static_assert(alignof(T) <= alignof(SymbolUnion),
492                 "SymbolUnion not aligned enough");
493 };
494 
assertSymbols()495 static inline void assertSymbols() {
496   AssertSymbol<Defined>();
497   AssertSymbol<CommonSymbol>();
498   AssertSymbol<Undefined>();
499   AssertSymbol<SharedSymbol>();
500   AssertSymbol<LazyArchive>();
501   AssertSymbol<LazyObject>();
502 }
503 
504 void printTraceSymbol(const Symbol *sym);
505 
getSymbolSize()506 size_t Symbol::getSymbolSize() const {
507   switch (kind()) {
508   case CommonKind:
509     return sizeof(CommonSymbol);
510   case DefinedKind:
511     return sizeof(Defined);
512   case LazyArchiveKind:
513     return sizeof(LazyArchive);
514   case LazyObjectKind:
515     return sizeof(LazyObject);
516   case SharedKind:
517     return sizeof(SharedSymbol);
518   case UndefinedKind:
519     return sizeof(Undefined);
520   case PlaceholderKind:
521     return sizeof(Symbol);
522   }
523   llvm_unreachable("unknown symbol kind");
524 }
525 
526 // replace() replaces "this" object with a given symbol by memcpy'ing
527 // it over to "this". This function is called as a result of name
528 // resolution, e.g. to replace an undefind symbol with a defined symbol.
replace(const Symbol & newSym)529 void Symbol::replace(const Symbol &newSym) {
530   using llvm::ELF::STT_TLS;
531 
532   // st_value of STT_TLS represents the assigned offset, not the actual address
533   // which is used by STT_FUNC and STT_OBJECT. STT_TLS symbols can only be
534   // referenced by special TLS relocations. It is usually an error if a STT_TLS
535   // symbol is replaced by a non-STT_TLS symbol, vice versa. There are two
536   // exceptions: (a) a STT_NOTYPE lazy/undefined symbol can be replaced by a
537   // STT_TLS symbol, (b) a STT_TLS undefined symbol can be replaced by a
538   // STT_NOTYPE lazy symbol.
539   if (symbolKind != PlaceholderKind && !newSym.isLazy() &&
540       (type == STT_TLS) != (newSym.type == STT_TLS) &&
541       type != llvm::ELF::STT_NOTYPE)
542     error("TLS attribute mismatch: " + toString(*this) + "\n>>> defined in " +
543           toString(newSym.file) + "\n>>> defined in " + toString(file));
544 
545   Symbol old = *this;
546   memcpy(this, &newSym, newSym.getSymbolSize());
547 
548   // old may be a placeholder. The referenced fields must be initialized in
549   // SymbolTable::insert.
550   versionId = old.versionId;
551   visibility = old.visibility;
552   isUsedInRegularObj = old.isUsedInRegularObj;
553   exportDynamic = old.exportDynamic;
554   inDynamicList = old.inDynamicList;
555   canInline = old.canInline;
556   referenced = old.referenced;
557   traced = old.traced;
558   isPreemptible = old.isPreemptible;
559   scriptDefined = old.scriptDefined;
560   partition = old.partition;
561 
562   // Symbol length is computed lazily. If we already know a symbol length,
563   // propagate it.
564   if (nameData == old.nameData && nameSize == 0 && old.nameSize != 0)
565     nameSize = old.nameSize;
566 
567   // Print out a log message if --trace-symbol was specified.
568   // This is for debugging.
569   if (traced)
570     printTraceSymbol(this);
571 }
572 
573 void maybeWarnUnorderableSymbol(const Symbol *sym);
574 bool computeIsPreemptible(const Symbol &sym);
575 void reportBackrefs();
576 
577 // A mapping from a symbol to an InputFile referencing it backward. Used by
578 // --warn-backrefs.
579 extern llvm::DenseMap<const Symbol *,
580                       std::pair<const InputFile *, const InputFile *>>
581     backwardReferences;
582 
583 } // namespace elf
584 } // namespace lld
585 
586 #endif
587