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