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