543 lines · c
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-exception6//7//===----------------------------------------------------------------------===//8//9// This file defines various types of Symbols.10//11//===----------------------------------------------------------------------===//12 13#ifndef LLD_ELF_SYMBOLS_H14#define LLD_ELF_SYMBOLS_H15 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 24namespace lld::elf {25class CommonSymbol;26class Defined;27class OutputSection;28class SectionBase;29class InputSectionBase;30class SharedSymbol;31class Symbol;32class Undefined;33class LazySymbol;34class InputFile;35 36// Returns a string representation for a symbol for diagnostics.37std::string toStr(Ctx &, const Symbol &);38const ELFSyncStream &operator<<(const ELFSyncStream &, const Symbol *);39 40void printTraceSymbol(const Symbol &sym, StringRef name);41 42enum {43 NEEDS_GOT = 1 << 0,44 NEEDS_PLT = 1 << 1,45 HAS_DIRECT_RELOC = 1 << 2,46 // True if this symbol needs a canonical PLT entry, or (during47 // postScanRelocations) a copy relocation.48 NEEDS_COPY = 1 << 3,49 NEEDS_TLSDESC = 1 << 4,50 NEEDS_TLSGD = 1 << 5,51 NEEDS_TLSGD_TO_IE = 1 << 6,52 NEEDS_GOT_DTPREL = 1 << 7,53 NEEDS_TLSIE = 1 << 8,54 NEEDS_GOT_AUTH = 1 << 9,55 NEEDS_GOT_NONAUTH = 1 << 10,56 NEEDS_TLSDESC_AUTH = 1 << 11,57 NEEDS_TLSDESC_NONAUTH = 1 << 12,58};59 60// The base class for real symbol classes.61class Symbol {62public:63 enum Kind {64 PlaceholderKind,65 DefinedKind,66 CommonKind,67 SharedKind,68 UndefinedKind,69 LazyKind,70 };71 72 Kind kind() const { return static_cast<Kind>(symbolKind); }73 74 // The file from which this symbol was created.75 InputFile *file;76 77 // The default copy constructor is deleted due to atomic flags. Define one for78 // places where no atomic is needed.79 Symbol(const Symbol &o) { memcpy(static_cast<void *>(this), &o, sizeof(o)); }80 81protected:82 const char *nameData;83 // 32-bit size saves space.84 uint32_t nameSize;85 86public:87 // The next three fields have the same meaning as the ELF symbol attributes.88 // type and binding are placed in this order to optimize generating st_info,89 // which is defined as (binding << 4) + (type & 0xf), on a little-endian90 // system.91 uint8_t type : 4; // symbol type92 93 // Symbol binding. This is not overwritten by replace() to track94 // changes during resolution. In particular:95 // - An undefined weak is still weak when it resolves to a shared library.96 // - An undefined weak will not extract archive members, but we have to97 // remember it is weak.98 uint8_t binding : 4;99 100 uint8_t stOther; // st_other field value101 102 uint8_t symbolKind;103 104 // The partition whose dynamic symbol table contains this symbol's definition.105 uint8_t partition;106 107 // True if this symbol is preemptible at load time.108 //109 // Primarily set in two locations, (a) parseVersionAndComputeIsPreemptible and110 // (b) demoteSymbolsAndComputeIsPreemptible.111 LLVM_PREFERRED_TYPE(bool)112 uint8_t isPreemptible : 1;113 114 // True if the symbol was used for linking and thus need to be added to the115 // output file's symbol table. This is true for all symbols except for116 // unreferenced DSO symbols, lazy (archive) symbols, and bitcode symbols that117 // are unreferenced except by other bitcode objects.118 LLVM_PREFERRED_TYPE(bool)119 uint8_t isUsedInRegularObj : 1;120 121 // True if an undefined or shared symbol is used from a live section.122 //123 // NOTE: In Writer.cpp the field is used to mark local defined symbols124 // which are referenced by relocations when -r or --emit-relocs is given.125 LLVM_PREFERRED_TYPE(bool)126 uint8_t used : 1;127 128 // Used by a Defined symbol with protected or default visibility, to record129 // whether it is required to be exported into .dynsym. This is set when any of130 // the following conditions hold:131 //132 // - If there is an interposable symbol from a DSO. Note: We also do this for133 // STV_PROTECTED symbols which can't be interposed (to match BFD behavior).134 // - If -shared or --export-dynamic is specified, any symbol in an object135 // file/bitcode sets this property, unless suppressed by LTO136 // canBeOmittedFromSymbolTable().137 LLVM_PREFERRED_TYPE(bool)138 uint8_t isExported : 1;139 140 LLVM_PREFERRED_TYPE(bool)141 uint8_t ltoCanOmit : 1;142 143 // True if this symbol is specified by --trace-symbol option.144 LLVM_PREFERRED_TYPE(bool)145 uint8_t traced : 1;146 147 // True if the name contains '@'.148 LLVM_PREFERRED_TYPE(bool)149 uint8_t hasVersionSuffix : 1;150 151 // Symbol visibility. This is the computed minimum visibility of all152 // observed non-DSO symbols.153 uint8_t visibility() const { return stOther & 3; }154 void setVisibility(uint8_t visibility) {155 stOther = (stOther & ~3) | visibility;156 }157 158 uint8_t computeBinding(Ctx &) const;159 bool isGlobal() const { return binding == llvm::ELF::STB_GLOBAL; }160 bool isWeak() const { return binding == llvm::ELF::STB_WEAK; }161 162 bool isUndefined() const { return symbolKind == UndefinedKind; }163 bool isCommon() const { return symbolKind == CommonKind; }164 bool isDefined() const { return symbolKind == DefinedKind; }165 bool isShared() const { return symbolKind == SharedKind; }166 bool isPlaceholder() const { return symbolKind == PlaceholderKind; }167 168 bool isLocal() const { return binding == llvm::ELF::STB_LOCAL; }169 170 bool isLazy() const { return symbolKind == LazyKind; }171 172 // True if this is an undefined weak symbol. This only works once173 // all input files have been added.174 bool isUndefWeak() const { return isWeak() && isUndefined(); }175 176 StringRef getName() const { return {nameData, nameSize}; }177 178 void setName(StringRef s) {179 nameData = s.data();180 nameSize = s.size();181 }182 183 void parseSymbolVersion(Ctx &);184 185 // Get the NUL-terminated version suffix ("", "@...", or "@@...").186 //187 // For @@, the name has been truncated by insert(). For @, the name has been188 // truncated by Symbol::parseSymbolVersion(ctx).189 const char *getVersionSuffix() const { return nameData + nameSize; }190 191 uint32_t getGotIdx(Ctx &ctx) const { return ctx.symAux[auxIdx].gotIdx; }192 uint32_t getPltIdx(Ctx &ctx) const { return ctx.symAux[auxIdx].pltIdx; }193 uint32_t getTlsDescIdx(Ctx &ctx) const {194 return ctx.symAux[auxIdx].tlsDescIdx;195 }196 uint32_t getTlsGdIdx(Ctx &ctx) const { return ctx.symAux[auxIdx].tlsGdIdx; }197 198 bool isInGot(Ctx &ctx) const { return getGotIdx(ctx) != uint32_t(-1); }199 bool isInPlt(Ctx &ctx) const { return getPltIdx(ctx) != uint32_t(-1); }200 201 uint64_t getVA(Ctx &, int64_t addend = 0) const;202 203 uint64_t getGotOffset(Ctx &) const;204 uint64_t getGotVA(Ctx &) const;205 uint64_t getGotPltOffset(Ctx &) const;206 uint64_t getGotPltVA(Ctx &) const;207 uint64_t getPltVA(Ctx &) const;208 uint64_t getSize() const;209 OutputSection *getOutputSection() const;210 211 // The following two functions are used for symbol resolution.212 //213 // You are expected to call mergeProperties for all symbols in input214 // files so that attributes that are attached to names rather than215 // indivisual symbol (such as visibility) are merged together.216 //217 // Every time you read a new symbol from an input, you are supposed218 // to call resolve() with the new symbol. That function replaces219 // "this" object as a result of name resolution if the new symbol is220 // more appropriate to be included in the output.221 //222 // For example, if "this" is an undefined symbol and a new symbol is223 // a defined symbol, "this" is replaced with the new symbol.224 void mergeProperties(const Symbol &other);225 void resolve(Ctx &, const Undefined &other);226 void resolve(Ctx &, const CommonSymbol &other);227 void resolve(Ctx &, const Defined &other);228 void resolve(Ctx &, const LazySymbol &other);229 void resolve(Ctx &, const SharedSymbol &other);230 231 // If this is a lazy symbol, extract an input file and add the symbol232 // in the file to the symbol table. Calling this function on233 // non-lazy object causes a runtime error.234 void extract(Ctx &) const;235 236 void checkDuplicate(Ctx &, const Defined &other) const;237 238private:239 bool shouldReplace(Ctx &, const Defined &other) const;240 241protected:242 Symbol(Kind k, InputFile *file, StringRef name, uint8_t binding,243 uint8_t stOther, uint8_t type)244 : file(file), nameData(name.data()), nameSize(name.size()), type(type),245 binding(binding), stOther(stOther), symbolKind(k), ltoCanOmit(false),246 archSpecificBit(false) {}247 248 void overwrite(Symbol &sym, Kind k) const {249 if (sym.traced)250 printTraceSymbol(*this, sym.getName());251 sym.file = file;252 sym.type = type;253 sym.binding = binding;254 sym.stOther = (stOther & ~3) | sym.visibility();255 sym.symbolKind = k;256 }257 258public:259 // True if this symbol is in the Iplt sub-section of the Plt and the Igot260 // sub-section of the .got.plt or .got.261 LLVM_PREFERRED_TYPE(bool)262 uint8_t isInIplt : 1;263 264 // True if this symbol needs a GOT entry and its GOT entry is actually in265 // Igot. This will be true only for certain non-preemptible ifuncs.266 LLVM_PREFERRED_TYPE(bool)267 uint8_t gotInIgot : 1;268 269 // True if defined relative to a section discarded by ICF.270 LLVM_PREFERRED_TYPE(bool)271 uint8_t folded : 1;272 273 // Allow reuse of a bit between architecture-exclusive symbol flags.274 // - needsTocRestore(): On PPC64, true if a call to this symbol needs to be275 // followed by a restore of the toc pointer.276 // - isTagged(): On AArch64, true if the symbol needs special relocation and277 // metadata semantics because it's tagged, under the AArch64 MemtagABI.278 LLVM_PREFERRED_TYPE(bool)279 uint8_t archSpecificBit : 1;280 bool needsTocRestore() const { return archSpecificBit; }281 bool isTagged() const { return archSpecificBit; }282 void setNeedsTocRestore(bool v) { archSpecificBit = v; }283 void setIsTagged(bool v) {284 archSpecificBit = v;285 }286 287 // True if this symbol is defined by a symbol assignment or wrapped by --wrap.288 //289 // LTO shouldn't inline the symbol because it doesn't know the final content290 // of the symbol.291 LLVM_PREFERRED_TYPE(bool)292 uint8_t scriptDefined : 1;293 294 // True if defined in a DSO. There may also be a definition in a relocatable295 // object file.296 LLVM_PREFERRED_TYPE(bool)297 uint8_t dsoDefined : 1;298 299 // True if defined in a DSO as protected visibility.300 LLVM_PREFERRED_TYPE(bool)301 uint8_t dsoProtected : 1;302 303 // Temporary flags used to communicate which symbol entries need PLT and GOT304 // entries during postScanRelocations();305 std::atomic<uint16_t> flags;306 307 // A ctx.symAux index used to access GOT/PLT entry indexes. This is allocated308 // in postScanRelocations().309 uint32_t auxIdx;310 uint32_t dynsymIndex;311 312 // If `file` is SharedFile (for SharedSymbol or copy-relocated Defined), this313 // represents the Verdef index within the input DSO, which will be converted314 // to a Verneed index in the output. Otherwise, this represents the Verdef315 // index (VER_NDX_LOCAL, VER_NDX_GLOBAL, or a named version).316 // VER_NDX_LOCAL indicates a defined symbol that has been localized by a317 // version script's local: directive or --exclude-libs.318 uint16_t versionId;319 LLVM_PREFERRED_TYPE(bool)320 uint8_t versionScriptAssigned : 1;321 322 // True if targeted by a range extension thunk.323 LLVM_PREFERRED_TYPE(bool)324 uint8_t thunkAccessed : 1;325 326 // True if the symbol is in the --dynamic-list file. A Defined symbol with327 // protected or default visibility with this property is required to be328 // exported into .dynsym.329 LLVM_PREFERRED_TYPE(bool)330 uint8_t inDynamicList : 1;331 332 // Used to track if there has been at least one undefined reference to the333 // symbol. For Undefined and SharedSymbol, the binding may change to STB_WEAK334 // if the first undefined reference from a non-shared object is weak.335 LLVM_PREFERRED_TYPE(bool)336 uint8_t referenced : 1;337 338 // Used to track if this symbol will be referenced after wrapping is performed339 // (i.e. this will be true for foo if __real_foo is referenced, and will be340 // true for __wrap_foo if foo is referenced).341 LLVM_PREFERRED_TYPE(bool)342 uint8_t referencedAfterWrap : 1;343 344 void setFlags(uint16_t bits) {345 flags.fetch_or(bits, std::memory_order_relaxed);346 }347 bool hasFlag(uint16_t bit) const {348 assert(llvm::has_single_bit(bit) && "bit must be a power of 2");349 return flags.load(std::memory_order_relaxed) & bit;350 }351 352 bool needsDynReloc() const {353 return flags.load(std::memory_order_relaxed) &354 (NEEDS_COPY | NEEDS_GOT | NEEDS_PLT | NEEDS_TLSDESC | NEEDS_TLSGD |355 NEEDS_TLSGD_TO_IE | NEEDS_GOT_DTPREL | NEEDS_TLSIE);356 }357 void allocateAux(Ctx &ctx) {358 assert(auxIdx == 0);359 auxIdx = ctx.symAux.size();360 ctx.symAux.emplace_back();361 }362 363 bool isSection() const { return type == llvm::ELF::STT_SECTION; }364 bool isTls() const { return type == llvm::ELF::STT_TLS; }365 bool isFunc() const { return type == llvm::ELF::STT_FUNC; }366 bool isGnuIFunc() const { return type == llvm::ELF::STT_GNU_IFUNC; }367 bool isObject() const { return type == llvm::ELF::STT_OBJECT; }368 bool isFile() const { return type == llvm::ELF::STT_FILE; }369};370 371// Represents a symbol that is defined in the current output file.372class Defined : public Symbol {373public:374 Defined(Ctx &ctx, InputFile *file, StringRef name, uint8_t binding,375 uint8_t stOther, uint8_t type, uint64_t value, uint64_t size,376 SectionBase *section)377 : Symbol(DefinedKind, file, name, binding, stOther, type), value(value),378 size(size), section(section) {379 }380 void overwrite(Symbol &sym) const;381 382 static bool classof(const Symbol *s) { return s->isDefined(); }383 384 uint64_t value;385 uint64_t size;386 SectionBase *section;387};388 389// Represents a common symbol.390//391// On Unix, it is traditionally allowed to write variable definitions392// without initialization expressions (such as "int foo;") to header393// files. Such definition is called "tentative definition".394//395// Using tentative definition is usually considered a bad practice396// because you should write only declarations (such as "extern int397// foo;") to header files. Nevertheless, the linker and the compiler398// have to do something to support bad code by allowing duplicate399// definitions for this particular case.400//401// Common symbols represent variable definitions without initializations.402// The compiler creates common symbols when it sees variable definitions403// without initialization (you can suppress this behavior and let the404// compiler create a regular defined symbol by -fno-common).405//406// The linker allows common symbols to be replaced by regular defined407// symbols. If there are remaining common symbols after name resolution is408// complete, they are converted to regular defined symbols in a .bss409// section. (Therefore, the later passes don't see any CommonSymbols.)410class CommonSymbol : public Symbol {411public:412 CommonSymbol(Ctx &ctx, InputFile *file, StringRef name, uint8_t binding,413 uint8_t stOther, uint8_t type, uint64_t alignment, uint64_t size)414 : Symbol(CommonKind, file, name, binding, stOther, type),415 alignment(alignment), size(size) {416 }417 void overwrite(Symbol &sym) const {418 Symbol::overwrite(sym, CommonKind);419 auto &s = static_cast<CommonSymbol &>(sym);420 s.alignment = alignment;421 s.size = size;422 }423 424 static bool classof(const Symbol *s) { return s->isCommon(); }425 426 uint32_t alignment;427 uint64_t size;428};429 430class Undefined : public Symbol {431public:432 Undefined(InputFile *file, StringRef name, uint8_t binding, uint8_t stOther,433 uint8_t type, uint32_t discardedSecIdx = 0)434 : Symbol(UndefinedKind, file, name, binding, stOther, type),435 discardedSecIdx(discardedSecIdx) {}436 void overwrite(Symbol &sym) const {437 Symbol::overwrite(sym, UndefinedKind);438 auto &s = static_cast<Undefined &>(sym);439 s.discardedSecIdx = discardedSecIdx;440 s.nonPrevailing = nonPrevailing;441 }442 443 static bool classof(const Symbol *s) { return s->kind() == UndefinedKind; }444 445 // The section index if in a discarded section, 0 otherwise.446 uint32_t discardedSecIdx;447 bool nonPrevailing = false;448};449 450class SharedSymbol : public Symbol {451public:452 static bool classof(const Symbol *s) { return s->kind() == SharedKind; }453 454 SharedSymbol(InputFile &file, StringRef name, uint8_t binding,455 uint8_t stOther, uint8_t type, uint64_t value, uint64_t size,456 uint32_t alignment)457 : Symbol(SharedKind, &file, name, binding, stOther, type), value(value),458 size(size), alignment(alignment) {459 dsoProtected = visibility() == llvm::ELF::STV_PROTECTED;460 // GNU ifunc is a mechanism to allow user-supplied functions to461 // resolve PLT slot values at load-time. This is contrary to the462 // regular symbol resolution scheme in which symbols are resolved just463 // by name. Using this hook, you can program how symbols are solved464 // for you program. For example, you can make "memcpy" to be resolved465 // to a SSE-enabled version of memcpy only when a machine running the466 // program supports the SSE instruction set.467 //468 // Naturally, such symbols should always be called through their PLT469 // slots. What GNU ifunc symbols point to are resolver functions, and470 // calling them directly doesn't make sense (unless you are writing a471 // loader).472 //473 // For DSO symbols, we always call them through PLT slots anyway.474 // So there's no difference between GNU ifunc and regular function475 // symbols if they are in DSOs. So we can handle GNU_IFUNC as FUNC.476 if (this->type == llvm::ELF::STT_GNU_IFUNC)477 this->type = llvm::ELF::STT_FUNC;478 }479 void overwrite(Symbol &sym) const {480 Symbol::overwrite(sym, SharedKind);481 auto &s = static_cast<SharedSymbol &>(sym);482 s.dsoProtected = dsoProtected;483 s.value = value;484 s.size = size;485 s.alignment = alignment;486 }487 488 uint64_t value; // st_value489 uint64_t size; // st_size490 uint32_t alignment;491};492 493// LazySymbol symbols represent symbols in object files between --start-lib and494// --end-lib options. LLD also handles traditional archives as if all the files495// in the archive are surrounded by --start-lib and --end-lib.496//497// A special complication is the handling of weak undefined symbols. They should498// not load a file, but we have to remember we have seen both the weak undefined499// and the lazy. We represent that with a lazy symbol with a weak binding. This500// means that code looking for undefined symbols normally also has to take lazy501// symbols into consideration.502class LazySymbol : public Symbol {503public:504 LazySymbol(InputFile &file)505 : Symbol(LazyKind, &file, {}, llvm::ELF::STB_GLOBAL,506 llvm::ELF::STV_DEFAULT, llvm::ELF::STT_NOTYPE) {}507 void overwrite(Symbol &sym) const { Symbol::overwrite(sym, LazyKind); }508 509 static bool classof(const Symbol *s) { return s->kind() == LazyKind; }510};511 512// A buffer class that is large enough to hold any Symbol-derived513// object. We allocate memory using this class and instantiate a symbol514// using the placement new.515 516// It is important to keep the size of SymbolUnion small for performance and517// memory usage reasons. 64 bytes is a soft limit based on the size of Defined518// on a 64-bit system. This is enforced by a static_assert in Symbols.cpp.519union SymbolUnion {520 alignas(Defined) char a[sizeof(Defined)];521 alignas(CommonSymbol) char b[sizeof(CommonSymbol)];522 alignas(Undefined) char c[sizeof(Undefined)];523 alignas(SharedSymbol) char d[sizeof(SharedSymbol)];524 alignas(LazySymbol) char e[sizeof(LazySymbol)];525};526 527template <typename... T> Defined *makeDefined(T &&...args) {528 auto *sym = getSpecificAllocSingleton<SymbolUnion>().Allocate();529 memset(sym, 0, sizeof(Symbol));530 auto &s = *new (reinterpret_cast<Defined *>(sym)) Defined(std::forward<T>(args)...);531 return &s;532}533 534void reportDuplicate(Ctx &, const Symbol &sym, const InputFile *newFile,535 InputSectionBase *errSec, uint64_t errOffset);536void maybeWarnUnorderableSymbol(Ctx &, const Symbol *sym);537bool computeIsPreemptible(Ctx &, const Symbol &sym);538void parseVersionAndComputeIsPreemptible(Ctx &);539 540} // namespace lld::elf541 542#endif543