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/Object/Archive.h" 21 #include "llvm/Object/ELF.h" 22 23 namespace lld { 24 namespace elf { 25 class CommonSymbol; 26 class Defined; 27 class InputFile; 28 class LazyArchive; 29 class LazyObject; 30 class SharedSymbol; 31 class Symbol; 32 class Undefined; 33 } // namespace elf 34 35 std::string toString(const elf::Symbol &); 36 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 &); 41 42 namespace elf { 43 44 // This is a StringRef-like container that doesn't run strlen(). 45 // 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. 50 struct StringRefZ { 51 StringRefZ(const char *s) : data(s), size(-1) {} 52 StringRefZ(StringRef s) : data(s.data()), size(s.size()) {} 53 54 const char *data; 55 const uint32_t size; 56 }; 57 58 // The base class for real symbol classes. 59 class Symbol { 60 public: 61 enum Kind { 62 PlaceholderKind, 63 DefinedKind, 64 CommonKind, 65 SharedKind, 66 UndefinedKind, 67 LazyArchiveKind, 68 LazyObjectKind, 69 }; 70 71 Kind kind() const { return static_cast<Kind>(symbolKind); } 72 73 // The file from which this symbol was created. 74 InputFile *file; 75 76 protected: 77 const char *nameData; 78 mutable uint32_t nameSize; 79 80 public: 81 uint32_t dynsymIndex = 0; 82 uint32_t gotIndex = -1; 83 uint32_t pltIndex = -1; 84 85 uint32_t globalDynIndex = -1; 86 87 // This field is a index to the symbol's version definition. 88 uint32_t verdefIndex = -1; 89 90 // Version definition index. 91 uint16_t versionId; 92 93 // An index into the .branch_lt section on PPC64. 94 uint16_t ppc64BranchltIndex = -1; 95 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. 101 uint8_t binding; 102 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 106 107 uint8_t symbolKind; 108 109 // Symbol visibility. This is the computed minimum visibility of all 110 // observed non-DSO symbols. 111 uint8_t visibility : 2; 112 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 uint8_t isUsedInRegularObj : 1; 118 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 uint8_t exportDynamic : 1; 124 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 uint8_t canInline : 1; 129 130 // True if this symbol is specified by --trace-symbol option. 131 uint8_t traced : 1; 132 133 inline void replace(const Symbol &New); 134 135 bool includeInDynsym() const; 136 uint8_t computeBinding() const; 137 bool isWeak() const { return binding == llvm::ELF::STB_WEAK; } 138 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; } 144 145 bool isLocal() const { return binding == llvm::ELF::STB_LOCAL; } 146 147 bool isLazy() const { 148 return symbolKind == LazyArchiveKind || symbolKind == LazyObjectKind; 149 } 150 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()); 156 } 157 158 StringRef getName() const { 159 if (nameSize == (uint32_t)-1) 160 nameSize = strlen(nameData); 161 return {nameData, nameSize}; 162 } 163 164 void setName(StringRef s) { 165 nameData = s.data(); 166 nameSize = s.size(); 167 } 168 169 void parseSymbolVersion(); 170 171 bool isInGot() const { return gotIndex != -1U; } 172 bool isInPlt() const { return pltIndex != -1U; } 173 bool isInPPC64Branchlt() const { return ppc64BranchltIndex != 0xffff; } 174 175 uint64_t getVA(int64_t addend = 0) const; 176 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; 186 187 // The following two functions are used for symbol resolution. 188 // 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. 192 // 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. 197 // 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); 202 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. 206 void fetch() const; 207 208 private: 209 static bool isExportDynamic(Kind k, uint8_t visibility) { 210 if (k == SharedKind) 211 return visibility == llvm::ELF::STV_DEFAULT; 212 return config->shared || config->exportDynamic; 213 } 214 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); 220 221 int compare(const Symbol *other) const; 222 223 inline size_t getSymbolSize() const; 224 225 protected: 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) {} 235 236 public: 237 // True the symbol should point to its PLT entry. 238 // For SharedSymbol only. 239 uint8_t needsPltAddr : 1; 240 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 uint8_t isInIplt : 1; 244 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 uint8_t gotInIgot : 1; 248 249 // True if this symbol is preemptible at load time. 250 uint8_t isPreemptible : 1; 251 252 // True if an undefined or shared symbol is used from a live section. 253 uint8_t used : 1; 254 255 // True if a call to this symbol needs to be followed by a restore of the 256 // PPC64 toc pointer. 257 uint8_t needsTocRestore : 1; 258 259 // True if this symbol is defined by a linker script. 260 uint8_t scriptDefined : 1; 261 262 // The partition whose dynamic symbol table contains this symbol's definition. 263 uint8_t partition = 1; 264 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; } 271 }; 272 273 // Represents a symbol that is defined in the current output file. 274 class Defined : public Symbol { 275 public: 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) {} 280 281 static bool classof(const Symbol *s) { return s->isDefined(); } 282 283 uint64_t value; 284 uint64_t size; 285 SectionBase *section; 286 }; 287 288 // Represents a common symbol. 289 // 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". 293 // 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. 299 // 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). 304 // 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 { 310 public: 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) {} 315 316 static bool classof(const Symbol *s) { return s->isCommon(); } 317 318 uint32_t alignment; 319 uint64_t size; 320 }; 321 322 class Undefined : public Symbol { 323 public: 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) {} 328 329 static bool classof(const Symbol *s) { return s->kind() == UndefinedKind; } 330 331 // The section index if in a discarded section, 0 otherwise. 332 uint32_t discardedSecIdx; 333 }; 334 335 class SharedSymbol : public Symbol { 336 public: 337 static bool classof(const Symbol *s) { return s->kind() == SharedKind; } 338 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. 352 // 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 356 // loader). 357 // 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; 363 } 364 365 SharedFile &getFile() const { return *cast<SharedFile>(file); } 366 367 uint64_t value; // st_value 368 uint64_t size; // st_size 369 uint32_t alignment; 370 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 373 // is weak. 374 bool referenced = false; 375 }; 376 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. 380 // 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. 386 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 390 // symbol. 391 class LazyArchive : public Symbol { 392 public: 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), 396 sym(s) {} 397 398 static bool classof(const Symbol *s) { return s->kind() == LazyArchiveKind; } 399 400 MemoryBufferRef getMemberBuffer(); 401 402 const llvm::object::Archive::Symbol sym; 403 }; 404 405 // LazyObject symbols represents symbols in object files between 406 // --start-lib and --end-lib options. 407 class LazyObject : public Symbol { 408 public: 409 LazyObject(InputFile &file, StringRef name) 410 : Symbol(LazyObjectKind, &file, name, llvm::ELF::STB_GLOBAL, 411 llvm::ELF::STV_DEFAULT, llvm::ELF::STT_NOTYPE) {} 412 413 static bool classof(const Symbol *s) { return s->kind() == LazyObjectKind; } 414 }; 415 416 // Some linker-generated symbols need to be created as 417 // Defined symbols. 418 struct ElfSym { 419 // __bss_start 420 static Defined *bss; 421 422 // etext and _etext 423 static Defined *etext1; 424 static Defined *etext2; 425 426 // edata and _edata 427 static Defined *edata1; 428 static Defined *edata2; 429 430 // end and _end 431 static Defined *end1; 432 static Defined *end2; 433 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; 438 439 // _gp, _gp_disp and __gnu_local_gp symbols. Only for MIPS. 440 static Defined *mipsGp; 441 static Defined *mipsGpDisp; 442 static Defined *mipsLocalGp; 443 444 // __rel{,a}_iplt_{start,end} symbols. 445 static Defined *relaIpltStart; 446 static Defined *relaIpltEnd; 447 448 // __global_pointer$ for RISC-V. 449 static Defined *riscvGlobalPointer; 450 451 // _TLS_MODULE_BASE_ on targets that support TLSDESC. 452 static Defined *tlsModuleBase; 453 }; 454 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. 458 union SymbolUnion { 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)]; 465 }; 466 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"); 471 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"); 478 }; 479 480 static inline void assertSymbols() { 481 AssertSymbol<Defined>(); 482 AssertSymbol<CommonSymbol>(); 483 AssertSymbol<Undefined>(); 484 AssertSymbol<SharedSymbol>(); 485 AssertSymbol<LazyArchive>(); 486 AssertSymbol<LazyObject>(); 487 } 488 489 void printTraceSymbol(const Symbol *sym); 490 491 size_t Symbol::getSymbolSize() const { 492 switch (kind()) { 493 case CommonKind: 494 return sizeof(CommonSymbol); 495 case DefinedKind: 496 return sizeof(Defined); 497 case LazyArchiveKind: 498 return sizeof(LazyArchive); 499 case LazyObjectKind: 500 return sizeof(LazyObject); 501 case SharedKind: 502 return sizeof(SharedSymbol); 503 case UndefinedKind: 504 return sizeof(Undefined); 505 case PlaceholderKind: 506 return sizeof(Symbol); 507 } 508 llvm_unreachable("unknown symbol kind"); 509 } 510 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; 516 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); 525 if (tlsMismatch) 526 error("TLS attribute mismatch: " + toString(*this) + "\n>>> defined in " + 527 toString(New.file) + "\n>>> defined in " + toString(file)); 528 } 529 530 Symbol old = *this; 531 memcpy(this, &New, New.getSymbolSize()); 532 533 versionId = old.versionId; 534 visibility = old.visibility; 535 isUsedInRegularObj = old.isUsedInRegularObj; 536 exportDynamic = old.exportDynamic; 537 canInline = old.canInline; 538 traced = old.traced; 539 isPreemptible = old.isPreemptible; 540 scriptDefined = old.scriptDefined; 541 partition = old.partition; 542 543 // Symbol length is computed lazily. If we already know a symbol length, 544 // propagate it. 545 if (nameData == old.nameData && nameSize == 0 && old.nameSize != 0) 546 nameSize = old.nameSize; 547 548 // Print out a log message if --trace-symbol was specified. 549 // This is for debugging. 550 if (traced) 551 printTraceSymbol(this); 552 } 553 554 void maybeWarnUnorderableSymbol(const Symbol *sym); 555 } // namespace elf 556 } // namespace lld 557 558 #endif 559