1 //===- Symbols.h ------------------------------------------------*- C++ -*-===//
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
7 //===----------------------------------------------------------------------===//
9 // This file defines various types of Symbols.
11 //===----------------------------------------------------------------------===//
13 #ifndef LLD_ELF_SYMBOLS_H
14 #define LLD_ELF_SYMBOLS_H
16 #include "InputFiles.h"
17 #include "InputSection.h"
18 #include "lld/Common/LLVM.h"
19 #include "lld/Common/Strings.h"
20 #include "llvm/Object/Archive.h"
21 #include "llvm/Object/ELF.h"
35 std::string toString(const elf::Symbol &);
37 // There are two different ways to convert an Archive::Symbol to a string:
38 // One for Microsoft name mangling and one for Itanium name mangling.
39 // Call the functions toCOFFString and toELFString, not just toString.
40 std::string toELFString(const elf::Archive::Symbol &);
44 // This is a StringRef-like container that doesn't run strlen().
46 // ELF string tables contain a lot of null-terminated strings. Most of them
47 // are not necessary for the linker because they are names of local symbols,
48 // and the linker doesn't use local symbol names for name resolution. So, we
49 // use this class to represents strings read from string tables.
51 StringRefZ(const char *s) : data(s), size(-1) {}
52 StringRefZ(StringRef s) : data(s.data()), size(s.size()) {}
58 // The base class for real symbol classes.
71 Kind kind() const { return static_cast<Kind>(symbolKind); }
73 // The file from which this symbol was created.
78 mutable uint32_t nameSize;
81 uint32_t dynsymIndex = 0;
82 uint32_t gotIndex = -1;
83 uint32_t pltIndex = -1;
85 uint32_t globalDynIndex = -1;
87 // This field is a index to the symbol's version definition.
88 uint32_t verdefIndex = -1;
90 // Version definition index.
93 // An index into the .branch_lt section on PPC64.
94 uint16_t ppc64BranchltIndex = -1;
96 // Symbol binding. This is not overwritten by replace() to track
97 // changes during resolution. In particular:
98 // - An undefined weak is still weak when it resolves to a shared library.
99 // - An undefined weak will not fetch archive members, but we have to
100 // remember it is weak.
103 // The following fields have the same meaning as the ELF symbol attributes.
104 uint8_t type; // symbol type
105 uint8_t stOther; // st_other field value
109 // Symbol visibility. This is the computed minimum visibility of all
110 // observed non-DSO symbols.
111 unsigned visibility : 2;
113 // True if the symbol was used for linking and thus need to be added to the
114 // output file's symbol table. This is true for all symbols except for
115 // unreferenced DSO symbols, lazy (archive) symbols, and bitcode symbols that
116 // are unreferenced except by other bitcode objects.
117 unsigned isUsedInRegularObj : 1;
119 // If this flag is true and the symbol has protected or default visibility, it
120 // will appear in .dynsym. This flag is set by interposable DSO symbols in
121 // executables, by most symbols in DSOs and executables built with
122 // --export-dynamic, and by dynamic lists.
123 unsigned exportDynamic : 1;
125 // False if LTO shouldn't inline whatever this symbol points to. If a symbol
126 // is overwritten after LTO, LTO shouldn't inline the symbol because it
127 // doesn't know the final contents of the symbol.
128 unsigned canInline : 1;
130 // True if this symbol is specified by --trace-symbol option.
133 inline void replace(const Symbol &New);
135 bool includeInDynsym() const;
136 uint8_t computeBinding() const;
137 bool isWeak() const { return binding == llvm::ELF::STB_WEAK; }
139 bool isUndefined() const { return symbolKind == UndefinedKind; }
140 bool isCommon() const { return symbolKind == CommonKind; }
141 bool isDefined() const { return symbolKind == DefinedKind; }
142 bool isShared() const { return symbolKind == SharedKind; }
143 bool isPlaceholder() const { return symbolKind == PlaceholderKind; }
145 bool isLocal() const { return binding == llvm::ELF::STB_LOCAL; }
147 bool isLazy() const {
148 return symbolKind == LazyArchiveKind || symbolKind == LazyObjectKind;
151 // True if this is an undefined weak symbol. This only works once
152 // all input files have been added.
153 bool isUndefWeak() const {
154 // See comment on lazy symbols for details.
155 return isWeak() && (isUndefined() || isLazy());
158 StringRef getName() const {
159 if (nameSize == (uint32_t)-1)
160 nameSize = strlen(nameData);
161 return {nameData, nameSize};
164 void setName(StringRef s) {
169 void parseSymbolVersion();
171 bool isInGot() const { return gotIndex != -1U; }
172 bool isInPlt() const { return pltIndex != -1U; }
173 bool isInPPC64Branchlt() const { return ppc64BranchltIndex != 0xffff; }
175 uint64_t getVA(int64_t addend = 0) const;
177 uint64_t getGotOffset() const;
178 uint64_t getGotVA() const;
179 uint64_t getGotPltOffset() const;
180 uint64_t getGotPltVA() const;
181 uint64_t getPltVA() const;
182 uint64_t getPPC64LongBranchTableVA() const;
183 uint64_t getPPC64LongBranchOffset() const;
184 uint64_t getSize() const;
185 OutputSection *getOutputSection() const;
187 // The following two functions are used for symbol resolution.
189 // You are expected to call mergeProperties for all symbols in input
190 // files so that attributes that are attached to names rather than
191 // indivisual symbol (such as visibility) are merged together.
193 // Every time you read a new symbol from an input, you are supposed
194 // to call resolve() with the new symbol. That function replaces
195 // "this" object as a result of name resolution if the new symbol is
196 // more appropriate to be included in the output.
198 // For example, if "this" is an undefined symbol and a new symbol is
199 // a defined symbol, "this" is replaced with the new symbol.
200 void mergeProperties(const Symbol &other);
201 void resolve(const Symbol &other);
203 // If this is a lazy symbol, fetch an input file and add the symbol
204 // in the file to the symbol table. Calling this function on
205 // non-lazy object causes a runtime error.
209 static bool isExportDynamic(Kind k, uint8_t visibility) {
211 return visibility == llvm::ELF::STV_DEFAULT;
212 return config->shared || config->exportDynamic;
215 void resolveUndefined(const Undefined &other);
216 void resolveCommon(const CommonSymbol &other);
217 void resolveDefined(const Defined &other);
218 template <class LazyT> void resolveLazy(const LazyT &other);
219 void resolveShared(const SharedSymbol &other);
221 int compare(const Symbol *other) const;
223 inline size_t getSymbolSize() const;
226 Symbol(Kind k, InputFile *file, StringRefZ name, uint8_t binding,
227 uint8_t stOther, uint8_t type)
228 : file(file), nameData(name.data), nameSize(name.size), binding(binding),
229 type(type), stOther(stOther), symbolKind(k), visibility(stOther & 3),
230 isUsedInRegularObj(!file || file->kind() == InputFile::ObjKind),
231 exportDynamic(isExportDynamic(k, visibility)), canInline(false),
232 traced(false), needsPltAddr(false), isInIplt(false), gotInIgot(false),
233 isPreemptible(false), used(!config->gcSections), needsTocRestore(false),
234 scriptDefined(false) {}
237 // True the symbol should point to its PLT entry.
238 // For SharedSymbol only.
239 unsigned needsPltAddr : 1;
241 // True if this symbol is in the Iplt sub-section of the Plt and the Igot
242 // sub-section of the .got.plt or .got.
243 unsigned isInIplt : 1;
245 // True if this symbol needs a GOT entry and its GOT entry is actually in
246 // Igot. This will be true only for certain non-preemptible ifuncs.
247 unsigned gotInIgot : 1;
249 // True if this symbol is preemptible at load time.
250 unsigned isPreemptible : 1;
252 // True if an undefined or shared symbol is used from a live section.
255 // True if a call to this symbol needs to be followed by a restore of the
256 // PPC64 toc pointer.
257 unsigned needsTocRestore : 1;
259 // True if this symbol is defined by a linker script.
260 unsigned scriptDefined : 1;
262 // The partition whose dynamic symbol table contains this symbol's definition.
263 uint8_t partition = 1;
265 bool isSection() const { return type == llvm::ELF::STT_SECTION; }
266 bool isTls() const { return type == llvm::ELF::STT_TLS; }
267 bool isFunc() const { return type == llvm::ELF::STT_FUNC; }
268 bool isGnuIFunc() const { return type == llvm::ELF::STT_GNU_IFUNC; }
269 bool isObject() const { return type == llvm::ELF::STT_OBJECT; }
270 bool isFile() const { return type == llvm::ELF::STT_FILE; }
273 // Represents a symbol that is defined in the current output file.
274 class Defined : public Symbol {
276 Defined(InputFile *file, StringRefZ name, uint8_t binding, uint8_t stOther,
277 uint8_t type, uint64_t value, uint64_t size, SectionBase *section)
278 : Symbol(DefinedKind, file, name, binding, stOther, type), value(value),
279 size(size), section(section) {}
281 static bool classof(const Symbol *s) { return s->isDefined(); }
285 SectionBase *section;
288 // Represents a common symbol.
290 // On Unix, it is traditionally allowed to write variable definitions
291 // without initialization expressions (such as "int foo;") to header
292 // files. Such definition is called "tentative definition".
294 // Using tentative definition is usually considered a bad practice
295 // because you should write only declarations (such as "extern int
296 // foo;") to header files. Nevertheless, the linker and the compiler
297 // have to do something to support bad code by allowing duplicate
298 // definitions for this particular case.
300 // Common symbols represent variable definitions without initializations.
301 // The compiler creates common symbols when it sees varaible definitions
302 // without initialization (you can suppress this behavior and let the
303 // compiler create a regular defined symbol by -fno-common).
305 // The linker allows common symbols to be replaced by regular defined
306 // symbols. If there are remaining common symbols after name resolution is
307 // complete, they are converted to regular defined symbols in a .bss
308 // section. (Therefore, the later passes don't see any CommonSymbols.)
309 class CommonSymbol : public Symbol {
311 CommonSymbol(InputFile *file, StringRefZ name, uint8_t binding,
312 uint8_t stOther, uint8_t type, uint64_t alignment, uint64_t size)
313 : Symbol(CommonKind, file, name, binding, stOther, type),
314 alignment(alignment), size(size) {}
316 static bool classof(const Symbol *s) { return s->isCommon(); }
322 class Undefined : public Symbol {
324 Undefined(InputFile *file, StringRefZ name, uint8_t binding, uint8_t stOther,
325 uint8_t type, uint32_t discardedSecIdx = 0)
326 : Symbol(UndefinedKind, file, name, binding, stOther, type),
327 discardedSecIdx(discardedSecIdx) {}
329 static bool classof(const Symbol *s) { return s->kind() == UndefinedKind; }
331 // The section index if in a discarded section, 0 otherwise.
332 uint32_t discardedSecIdx;
335 class SharedSymbol : public Symbol {
337 static bool classof(const Symbol *s) { return s->kind() == SharedKind; }
339 SharedSymbol(InputFile &file, StringRef name, uint8_t binding,
340 uint8_t stOther, uint8_t type, uint64_t value, uint64_t size,
341 uint32_t alignment, uint32_t verdefIndex)
342 : Symbol(SharedKind, &file, name, binding, stOther, type), value(value),
343 size(size), alignment(alignment) {
344 this->verdefIndex = verdefIndex;
345 // GNU ifunc is a mechanism to allow user-supplied functions to
346 // resolve PLT slot values at load-time. This is contrary to the
347 // regular symbol resolution scheme in which symbols are resolved just
348 // by name. Using this hook, you can program how symbols are solved
349 // for you program. For example, you can make "memcpy" to be resolved
350 // to a SSE-enabled version of memcpy only when a machine running the
351 // program supports the SSE instruction set.
353 // Naturally, such symbols should always be called through their PLT
354 // slots. What GNU ifunc symbols point to are resolver functions, and
355 // calling them directly doesn't make sense (unless you are writing a
358 // For DSO symbols, we always call them through PLT slots anyway.
359 // So there's no difference between GNU ifunc and regular function
360 // symbols if they are in DSOs. So we can handle GNU_IFUNC as FUNC.
361 if (this->type == llvm::ELF::STT_GNU_IFUNC)
362 this->type = llvm::ELF::STT_FUNC;
365 SharedFile &getFile() const { return *cast<SharedFile>(file); }
367 uint64_t value; // st_value
368 uint64_t size; // st_size
371 // This is true if there has been at least one undefined reference to the
372 // symbol. The binding may change to STB_WEAK if the first undefined reference
374 bool referenced = false;
377 // LazyArchive and LazyObject represent a symbols that is not yet in the link,
378 // but we know where to find it if needed. If the resolver finds both Undefined
379 // and Lazy for the same name, it will ask the Lazy to load a file.
381 // A special complication is the handling of weak undefined symbols. They should
382 // not load a file, but we have to remember we have seen both the weak undefined
383 // and the lazy. We represent that with a lazy symbol with a weak binding. This
384 // means that code looking for undefined symbols normally also has to take lazy
385 // symbols into consideration.
387 // This class represents a symbol defined in an archive file. It is
388 // created from an archive file header, and it knows how to load an
389 // object file from an archive to replace itself with a defined
391 class LazyArchive : public Symbol {
393 LazyArchive(InputFile &file, const llvm::object::Archive::Symbol s)
394 : Symbol(LazyArchiveKind, &file, s.getName(), llvm::ELF::STB_GLOBAL,
395 llvm::ELF::STV_DEFAULT, llvm::ELF::STT_NOTYPE),
398 static bool classof(const Symbol *s) { return s->kind() == LazyArchiveKind; }
400 MemoryBufferRef getMemberBuffer();
402 const llvm::object::Archive::Symbol sym;
405 // LazyObject symbols represents symbols in object files between
406 // --start-lib and --end-lib options.
407 class LazyObject : public Symbol {
409 LazyObject(InputFile &file, StringRef name)
410 : Symbol(LazyObjectKind, &file, name, llvm::ELF::STB_GLOBAL,
411 llvm::ELF::STV_DEFAULT, llvm::ELF::STT_NOTYPE) {}
413 static bool classof(const Symbol *s) { return s->kind() == LazyObjectKind; }
416 // Some linker-generated symbols need to be created as
423 static Defined *etext1;
424 static Defined *etext2;
427 static Defined *edata1;
428 static Defined *edata2;
431 static Defined *end1;
432 static Defined *end2;
434 // The _GLOBAL_OFFSET_TABLE_ symbol is defined by target convention to
435 // be at some offset from the base of the .got section, usually 0 or
436 // the end of the .got.
437 static Defined *globalOffsetTable;
439 // _gp, _gp_disp and __gnu_local_gp symbols. Only for MIPS.
440 static Defined *mipsGp;
441 static Defined *mipsGpDisp;
442 static Defined *mipsLocalGp;
444 // __rel{,a}_iplt_{start,end} symbols.
445 static Defined *relaIpltStart;
446 static Defined *relaIpltEnd;
448 // __global_pointer$ for RISC-V.
449 static Defined *riscvGlobalPointer;
451 // _TLS_MODULE_BASE_ on targets that support TLSDESC.
452 static Defined *tlsModuleBase;
455 // A buffer class that is large enough to hold any Symbol-derived
456 // object. We allocate memory using this class and instantiate a symbol
457 // using the placement new.
459 alignas(Defined) char a[sizeof(Defined)];
460 alignas(CommonSymbol) char b[sizeof(CommonSymbol)];
461 alignas(Undefined) char c[sizeof(Undefined)];
462 alignas(SharedSymbol) char d[sizeof(SharedSymbol)];
463 alignas(LazyArchive) char e[sizeof(LazyArchive)];
464 alignas(LazyObject) char f[sizeof(LazyObject)];
467 // It is important to keep the size of SymbolUnion small for performance and
468 // memory usage reasons. 80 bytes is a soft limit based on the size of Defined
469 // on a 64-bit system.
470 static_assert(sizeof(SymbolUnion) <= 80, "SymbolUnion too large");
472 template <typename T> struct AssertSymbol {
473 static_assert(std::is_trivially_destructible<T>(),
474 "Symbol types must be trivially destructible");
475 static_assert(sizeof(T) <= sizeof(SymbolUnion), "SymbolUnion too small");
476 static_assert(alignof(T) <= alignof(SymbolUnion),
477 "SymbolUnion not aligned enough");
480 static inline void assertSymbols() {
481 AssertSymbol<Defined>();
482 AssertSymbol<CommonSymbol>();
483 AssertSymbol<Undefined>();
484 AssertSymbol<SharedSymbol>();
485 AssertSymbol<LazyArchive>();
486 AssertSymbol<LazyObject>();
489 void printTraceSymbol(const Symbol *sym);
491 size_t Symbol::getSymbolSize() const {
494 return sizeof(CommonSymbol);
496 return sizeof(Defined);
497 case LazyArchiveKind:
498 return sizeof(LazyArchive);
500 return sizeof(LazyObject);
502 return sizeof(SharedSymbol);
504 return sizeof(Undefined);
505 case PlaceholderKind:
506 return sizeof(Symbol);
508 llvm_unreachable("unknown symbol kind");
511 // replace() replaces "this" object with a given symbol by memcpy'ing
512 // it over to "this". This function is called as a result of name
513 // resolution, e.g. to replace an undefind symbol with a defined symbol.
514 void Symbol::replace(const Symbol &New) {
515 using llvm::ELF::STT_TLS;
517 // Symbols representing thread-local variables must be referenced by
518 // TLS-aware relocations, and non-TLS symbols must be reference by
519 // non-TLS relocations, so there's a clear distinction between TLS
520 // and non-TLS symbols. It is an error if the same symbol is defined
521 // as a TLS symbol in one file and as a non-TLS symbol in other file.
522 if (symbolKind != PlaceholderKind && !isLazy() && !New.isLazy()) {
523 bool tlsMismatch = (type == STT_TLS && New.type != STT_TLS) ||
524 (type != STT_TLS && New.type == STT_TLS);
526 error("TLS attribute mismatch: " + toString(*this) + "\n>>> defined in " +
527 toString(New.file) + "\n>>> defined in " + toString(file));
531 memcpy(this, &New, New.getSymbolSize());
533 versionId = old.versionId;
534 visibility = old.visibility;
535 isUsedInRegularObj = old.isUsedInRegularObj;
536 exportDynamic = old.exportDynamic;
537 canInline = old.canInline;
539 isPreemptible = old.isPreemptible;
540 scriptDefined = old.scriptDefined;
541 partition = old.partition;
543 // Symbol length is computed lazily. If we already know a symbol length,
545 if (nameData == old.nameData && nameSize == 0 && old.nameSize != 0)
546 nameSize = old.nameSize;
548 // Print out a log message if --trace-symbol was specified.
549 // This is for debugging.
551 printTraceSymbol(this);
554 void maybeWarnUnorderableSymbol(const Symbol *sym);