1 //===- SymbolTable.cpp ----------------------------------------------------===// 2 // 3 // The LLVM Linker 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // Symbol table is a bag of all known symbols. We put all symbols of 11 // all input files to the symbol table. The symbol table is basically 12 // a hash table with the logic to resolve symbol name conflicts using 13 // the symbol types. 14 // 15 //===----------------------------------------------------------------------===// 16 17 #include "SymbolTable.h" 18 #include "Config.h" 19 #include "LinkerScript.h" 20 #include "Symbols.h" 21 #include "SyntheticSections.h" 22 #include "lld/Common/ErrorHandler.h" 23 #include "lld/Common/Memory.h" 24 #include "lld/Common/Strings.h" 25 #include "llvm/ADT/STLExtras.h" 26 27 using namespace llvm; 28 using namespace llvm::object; 29 using namespace llvm::ELF; 30 31 using namespace lld; 32 using namespace lld::elf; 33 34 SymbolTable *elf::Symtab; 35 36 static InputFile *getFirstElf() { 37 if (!ObjectFiles.empty()) 38 return ObjectFiles[0]; 39 if (!SharedFiles.empty()) 40 return SharedFiles[0]; 41 return nullptr; 42 } 43 44 // All input object files must be for the same architecture 45 // (e.g. it does not make sense to link x86 object files with 46 // MIPS object files.) This function checks for that error. 47 static bool isCompatible(InputFile *F) { 48 if (!F->isElf() && !isa<BitcodeFile>(F)) 49 return true; 50 51 if (F->EKind == Config->EKind && F->EMachine == Config->EMachine) { 52 if (Config->EMachine != EM_MIPS) 53 return true; 54 if (isMipsN32Abi(F) == Config->MipsN32Abi) 55 return true; 56 } 57 58 if (!Config->Emulation.empty()) 59 error(toString(F) + " is incompatible with " + Config->Emulation); 60 else 61 error(toString(F) + " is incompatible with " + toString(getFirstElf())); 62 return false; 63 } 64 65 // Add symbols in File to the symbol table. 66 template <class ELFT> void SymbolTable::addFile(InputFile *File) { 67 if (!isCompatible(File)) 68 return; 69 70 // Binary file 71 if (auto *F = dyn_cast<BinaryFile>(File)) { 72 BinaryFiles.push_back(F); 73 F->parse(); 74 return; 75 } 76 77 // .a file 78 if (auto *F = dyn_cast<ArchiveFile>(File)) { 79 F->parse<ELFT>(); 80 return; 81 } 82 83 // Lazy object file 84 if (auto *F = dyn_cast<LazyObjFile>(File)) { 85 LazyObjFiles.push_back(F); 86 F->parse<ELFT>(); 87 return; 88 } 89 90 if (Config->Trace) 91 message(toString(File)); 92 93 // .so file 94 if (auto *F = dyn_cast<SharedFile<ELFT>>(File)) { 95 // DSOs are uniquified not by filename but by soname. 96 F->parseSoName(); 97 if (errorCount() || !SoNames.insert(F->SoName).second) 98 return; 99 SharedFiles.push_back(F); 100 F->parseRest(); 101 return; 102 } 103 104 // LLVM bitcode file 105 if (auto *F = dyn_cast<BitcodeFile>(File)) { 106 BitcodeFiles.push_back(F); 107 F->parse<ELFT>(ComdatGroups); 108 return; 109 } 110 111 // Regular object file 112 ObjectFiles.push_back(File); 113 cast<ObjFile<ELFT>>(File)->parse(ComdatGroups); 114 } 115 116 // This function is where all the optimizations of link-time 117 // optimization happens. When LTO is in use, some input files are 118 // not in native object file format but in the LLVM bitcode format. 119 // This function compiles bitcode files into a few big native files 120 // using LLVM functions and replaces bitcode symbols with the results. 121 // Because all bitcode files that the program consists of are passed 122 // to the compiler at once, it can do whole-program optimization. 123 template <class ELFT> void SymbolTable::addCombinedLTOObject() { 124 if (BitcodeFiles.empty()) 125 return; 126 127 // Compile bitcode files and replace bitcode symbols. 128 LTO.reset(new BitcodeCompiler); 129 for (BitcodeFile *F : BitcodeFiles) 130 LTO->add(*F); 131 132 for (InputFile *File : LTO->compile()) { 133 DenseSet<CachedHashStringRef> DummyGroups; 134 auto *Obj = cast<ObjFile<ELFT>>(File); 135 Obj->parse(DummyGroups); 136 for (Symbol *Sym : Obj->getGlobalSymbols()) 137 Sym->parseSymbolVersion(); 138 ObjectFiles.push_back(File); 139 } 140 } 141 142 Defined *SymbolTable::addAbsolute(StringRef Name, uint8_t Visibility, 143 uint8_t Binding) { 144 Symbol *Sym = 145 addRegular(Name, Visibility, STT_NOTYPE, 0, 0, Binding, nullptr, nullptr); 146 return cast<Defined>(Sym); 147 } 148 149 // Set a flag for --trace-symbol so that we can print out a log message 150 // if a new symbol with the same name is inserted into the symbol table. 151 void SymbolTable::trace(StringRef Name) { 152 SymMap.insert({CachedHashStringRef(Name), -1}); 153 } 154 155 // Rename SYM as __wrap_SYM. The original symbol is preserved as __real_SYM. 156 // Used to implement --wrap. 157 template <class ELFT> void SymbolTable::addSymbolWrap(StringRef Name) { 158 Symbol *Sym = find(Name); 159 if (!Sym) 160 return; 161 162 // Do not wrap the same symbol twice. 163 if (llvm::find_if(WrappedSymbols, [&](const WrappedSymbol &S) { 164 return S.Sym == Sym; 165 }) != WrappedSymbols.end()) 166 return; 167 168 Symbol *Real = addUndefined<ELFT>(Saver.save("__real_" + Name)); 169 Symbol *Wrap = addUndefined<ELFT>(Saver.save("__wrap_" + Name)); 170 WrappedSymbols.push_back({Sym, Real, Wrap}); 171 172 // We want to tell LTO not to inline symbols to be overwritten 173 // because LTO doesn't know the final symbol contents after renaming. 174 Real->CanInline = false; 175 Sym->CanInline = false; 176 177 // Tell LTO not to eliminate these symbols. 178 Sym->IsUsedInRegularObj = true; 179 Wrap->IsUsedInRegularObj = true; 180 } 181 182 // Apply symbol renames created by -wrap. The renames are created 183 // before LTO in addSymbolWrap() to have a chance to inform LTO (if 184 // LTO is running) not to include these symbols in IPO. Now that the 185 // symbols are finalized, we can perform the replacement. 186 void SymbolTable::applySymbolWrap() { 187 // This function rotates 3 symbols: 188 // 189 // __real_sym becomes sym 190 // sym becomes __wrap_sym 191 // __wrap_sym becomes __real_sym 192 // 193 // The last part is special in that we don't want to change what references to 194 // __wrap_sym point to, we just want have __real_sym in the symbol table. 195 196 for (WrappedSymbol &W : WrappedSymbols) { 197 // First, make a copy of __real_sym. 198 Symbol *Real = nullptr; 199 if (W.Real->isDefined()) { 200 Real = reinterpret_cast<Symbol *>(make<SymbolUnion>()); 201 memcpy(Real, W.Real, sizeof(SymbolUnion)); 202 } 203 204 // Replace __real_sym with sym and sym with __wrap_sym. 205 memcpy(W.Real, W.Sym, sizeof(SymbolUnion)); 206 memcpy(W.Sym, W.Wrap, sizeof(SymbolUnion)); 207 208 // We now have two copies of __wrap_sym. Drop one. 209 W.Wrap->IsUsedInRegularObj = false; 210 211 if (Real) 212 SymVector.push_back(Real); 213 } 214 } 215 216 static uint8_t getMinVisibility(uint8_t VA, uint8_t VB) { 217 if (VA == STV_DEFAULT) 218 return VB; 219 if (VB == STV_DEFAULT) 220 return VA; 221 return std::min(VA, VB); 222 } 223 224 // Find an existing symbol or create and insert a new one. 225 std::pair<Symbol *, bool> SymbolTable::insert(StringRef Name) { 226 // <name>@@<version> means the symbol is the default version. In that 227 // case <name>@@<version> will be used to resolve references to <name>. 228 // 229 // Since this is a hot path, the following string search code is 230 // optimized for speed. StringRef::find(char) is much faster than 231 // StringRef::find(StringRef). 232 size_t Pos = Name.find('@'); 233 if (Pos != StringRef::npos && Pos + 1 < Name.size() && Name[Pos + 1] == '@') 234 Name = Name.take_front(Pos); 235 236 auto P = SymMap.insert({CachedHashStringRef(Name), (int)SymVector.size()}); 237 int &SymIndex = P.first->second; 238 bool IsNew = P.second; 239 bool Traced = false; 240 241 if (SymIndex == -1) { 242 SymIndex = SymVector.size(); 243 IsNew = Traced = true; 244 } 245 246 Symbol *Sym; 247 if (IsNew) { 248 Sym = reinterpret_cast<Symbol *>(make<SymbolUnion>()); 249 Sym->Visibility = STV_DEFAULT; 250 Sym->IsUsedInRegularObj = false; 251 Sym->ExportDynamic = false; 252 Sym->CanInline = true; 253 Sym->Traced = Traced; 254 Sym->VersionId = Config->DefaultSymbolVersion; 255 SymVector.push_back(Sym); 256 } else { 257 Sym = SymVector[SymIndex]; 258 } 259 return {Sym, IsNew}; 260 } 261 262 // Find an existing symbol or create and insert a new one, then apply the given 263 // attributes. 264 std::pair<Symbol *, bool> SymbolTable::insert(StringRef Name, uint8_t Type, 265 uint8_t Visibility, 266 bool CanOmitFromDynSym, 267 InputFile *File) { 268 Symbol *S; 269 bool WasInserted; 270 std::tie(S, WasInserted) = insert(Name); 271 272 // Merge in the new symbol's visibility. 273 S->Visibility = getMinVisibility(S->Visibility, Visibility); 274 275 if (!CanOmitFromDynSym && (Config->Shared || Config->ExportDynamic)) 276 S->ExportDynamic = true; 277 278 if (!File || File->kind() == InputFile::ObjKind) 279 S->IsUsedInRegularObj = true; 280 281 if (!WasInserted && S->Type != Symbol::UnknownType && 282 ((Type == STT_TLS) != S->isTls())) { 283 error("TLS attribute mismatch: " + toString(*S) + "\n>>> defined in " + 284 toString(S->File) + "\n>>> defined in " + toString(File)); 285 } 286 287 return {S, WasInserted}; 288 } 289 290 template <class ELFT> Symbol *SymbolTable::addUndefined(StringRef Name) { 291 return addUndefined<ELFT>(Name, STB_GLOBAL, STV_DEFAULT, 292 /*Type*/ 0, 293 /*CanOmitFromDynSym*/ false, /*File*/ nullptr); 294 } 295 296 static uint8_t getVisibility(uint8_t StOther) { return StOther & 3; } 297 298 template <class ELFT> 299 Symbol *SymbolTable::addUndefined(StringRef Name, uint8_t Binding, 300 uint8_t StOther, uint8_t Type, 301 bool CanOmitFromDynSym, InputFile *File) { 302 Symbol *S; 303 bool WasInserted; 304 uint8_t Visibility = getVisibility(StOther); 305 std::tie(S, WasInserted) = 306 insert(Name, Type, Visibility, CanOmitFromDynSym, File); 307 308 // An undefined symbol with non default visibility must be satisfied 309 // in the same DSO. 310 if (WasInserted || (isa<SharedSymbol>(S) && Visibility != STV_DEFAULT)) { 311 replaceSymbol<Undefined>(S, File, Name, Binding, StOther, Type); 312 return S; 313 } 314 315 if (S->isShared() || S->isLazy() || (S->isUndefined() && Binding != STB_WEAK)) 316 S->Binding = Binding; 317 318 if (!Config->GcSections && Binding != STB_WEAK) 319 if (auto *SS = dyn_cast<SharedSymbol>(S)) 320 SS->getFile<ELFT>().IsNeeded = true; 321 322 if (S->isLazy()) { 323 // An undefined weak will not fetch archive members. See comment on Lazy in 324 // Symbols.h for the details. 325 if (Binding == STB_WEAK) { 326 S->Type = Type; 327 return S; 328 } 329 330 // Do extra check for --warn-backrefs. 331 // 332 // --warn-backrefs is an option to prevent an undefined reference from 333 // fetching an archive member written earlier in the command line. It can be 334 // used to keep compatibility with GNU linkers to some degree. 335 // I'll explain the feature and why you may find it useful in this comment. 336 // 337 // lld's symbol resolution semantics is more relaxed than traditional Unix 338 // linkers. For example, 339 // 340 // ld.lld foo.a bar.o 341 // 342 // succeeds even if bar.o contains an undefined symbol that has to be 343 // resolved by some object file in foo.a. Traditional Unix linkers don't 344 // allow this kind of backward reference, as they visit each file only once 345 // from left to right in the command line while resolving all undefined 346 // symbols at the moment of visiting. 347 // 348 // In the above case, since there's no undefined symbol when a linker visits 349 // foo.a, no files are pulled out from foo.a, and because the linker forgets 350 // about foo.a after visiting, it can't resolve undefined symbols in bar.o 351 // that could have been resolved otherwise. 352 // 353 // That lld accepts more relaxed form means that (besides it'd make more 354 // sense) you can accidentally write a command line or a build file that 355 // works only with lld, even if you have a plan to distribute it to wider 356 // users who may be using GNU linkers. With --warn-backrefs, you can detect 357 // a library order that doesn't work with other Unix linkers. 358 // 359 // The option is also useful to detect cyclic dependencies between static 360 // archives. Again, lld accepts 361 // 362 // ld.lld foo.a bar.a 363 // 364 // even if foo.a and bar.a depend on each other. With --warn-backrefs, it is 365 // handled as an error. 366 // 367 // Here is how the option works. We assign a group ID to each file. A file 368 // with a smaller group ID can pull out object files from an archive file 369 // with an equal or greater group ID. Otherwise, it is a reverse dependency 370 // and an error. 371 // 372 // A file outside --{start,end}-group gets a fresh ID when instantiated. All 373 // files within the same --{start,end}-group get the same group ID. E.g. 374 // 375 // ld.lld A B --start-group C D --end-group E 376 // 377 // A forms group 0. B form group 1. C and D (including their member object 378 // files) form group 2. E forms group 3. I think that you can see how this 379 // group assignment rule simulates the traditional linker's semantics. 380 bool Backref = 381 Config->WarnBackrefs && File && S->File->GroupId < File->GroupId; 382 fetchLazy<ELFT>(S); 383 384 // We don't report backward references to weak symbols as they can be 385 // overridden later. 386 if (Backref && S->Binding != STB_WEAK) 387 warn("backward reference detected: " + Name + " in " + toString(File) + 388 " refers to " + toString(S->File)); 389 } 390 return S; 391 } 392 393 // Using .symver foo,foo@@VER unfortunately creates two symbols: foo and 394 // foo@@VER. We want to effectively ignore foo, so give precedence to 395 // foo@@VER. 396 // FIXME: If users can transition to using 397 // .symver foo,foo@@@VER 398 // we can delete this hack. 399 static int compareVersion(Symbol *S, StringRef Name) { 400 bool A = Name.contains("@@"); 401 bool B = S->getName().contains("@@"); 402 if (A && !B) 403 return 1; 404 if (!A && B) 405 return -1; 406 return 0; 407 } 408 409 // We have a new defined symbol with the specified binding. Return 1 if the new 410 // symbol should win, -1 if the new symbol should lose, or 0 if both symbols are 411 // strong defined symbols. 412 static int compareDefined(Symbol *S, bool WasInserted, uint8_t Binding, 413 StringRef Name) { 414 if (WasInserted) 415 return 1; 416 if (!S->isDefined()) 417 return 1; 418 if (int R = compareVersion(S, Name)) 419 return R; 420 if (Binding == STB_WEAK) 421 return -1; 422 if (S->isWeak()) 423 return 1; 424 return 0; 425 } 426 427 // We have a new non-common defined symbol with the specified binding. Return 1 428 // if the new symbol should win, -1 if the new symbol should lose, or 0 if there 429 // is a conflict. If the new symbol wins, also update the binding. 430 static int compareDefinedNonCommon(Symbol *S, bool WasInserted, uint8_t Binding, 431 bool IsAbsolute, uint64_t Value, 432 StringRef Name) { 433 if (int Cmp = compareDefined(S, WasInserted, Binding, Name)) 434 return Cmp; 435 if (auto *R = dyn_cast<Defined>(S)) { 436 if (R->Section && isa<BssSection>(R->Section)) { 437 // Non-common symbols take precedence over common symbols. 438 if (Config->WarnCommon) 439 warn("common " + S->getName() + " is overridden"); 440 return 1; 441 } 442 if (R->Section == nullptr && Binding == STB_GLOBAL && IsAbsolute && 443 R->Value == Value) 444 return -1; 445 } 446 return 0; 447 } 448 449 Symbol *SymbolTable::addCommon(StringRef N, uint64_t Size, uint32_t Alignment, 450 uint8_t Binding, uint8_t StOther, uint8_t Type, 451 InputFile &File) { 452 Symbol *S; 453 bool WasInserted; 454 std::tie(S, WasInserted) = insert(N, Type, getVisibility(StOther), 455 /*CanOmitFromDynSym*/ false, &File); 456 457 int Cmp = compareDefined(S, WasInserted, Binding, N); 458 if (Cmp < 0) 459 return S; 460 461 if (Cmp > 0) { 462 auto *Bss = make<BssSection>("COMMON", Size, Alignment); 463 Bss->File = &File; 464 Bss->Live = !Config->GcSections; 465 InputSections.push_back(Bss); 466 467 replaceSymbol<Defined>(S, &File, N, Binding, StOther, Type, 0, Size, Bss); 468 return S; 469 } 470 471 auto *D = cast<Defined>(S); 472 auto *Bss = dyn_cast_or_null<BssSection>(D->Section); 473 if (!Bss) { 474 // Non-common symbols take precedence over common symbols. 475 if (Config->WarnCommon) 476 warn("common " + S->getName() + " is overridden"); 477 return S; 478 } 479 480 if (Config->WarnCommon) 481 warn("multiple common of " + D->getName()); 482 483 Bss->Alignment = std::max(Bss->Alignment, Alignment); 484 if (Size > Bss->Size) { 485 D->File = Bss->File = &File; 486 D->Size = Bss->Size = Size; 487 } 488 return S; 489 } 490 491 static void reportDuplicate(Symbol *Sym, InputFile *NewFile) { 492 if (!Config->AllowMultipleDefinition) 493 error("duplicate symbol: " + toString(*Sym) + "\n>>> defined in " + 494 toString(Sym->File) + "\n>>> defined in " + toString(NewFile)); 495 } 496 497 static void reportDuplicate(Symbol *Sym, InputFile *NewFile, 498 InputSectionBase *ErrSec, uint64_t ErrOffset) { 499 if (Config->AllowMultipleDefinition) 500 return; 501 502 Defined *D = cast<Defined>(Sym); 503 if (!D->Section || !ErrSec) { 504 reportDuplicate(Sym, NewFile); 505 return; 506 } 507 508 // Construct and print an error message in the form of: 509 // 510 // ld.lld: error: duplicate symbol: foo 511 // >>> defined at bar.c:30 512 // >>> bar.o (/home/alice/src/bar.o) 513 // >>> defined at baz.c:563 514 // >>> baz.o in archive libbaz.a 515 auto *Sec1 = cast<InputSectionBase>(D->Section); 516 std::string Src1 = Sec1->getSrcMsg(*Sym, D->Value); 517 std::string Obj1 = Sec1->getObjMsg(D->Value); 518 std::string Src2 = ErrSec->getSrcMsg(*Sym, ErrOffset); 519 std::string Obj2 = ErrSec->getObjMsg(ErrOffset); 520 521 std::string Msg = "duplicate symbol: " + toString(*Sym) + "\n>>> defined at "; 522 if (!Src1.empty()) 523 Msg += Src1 + "\n>>> "; 524 Msg += Obj1 + "\n>>> defined at "; 525 if (!Src2.empty()) 526 Msg += Src2 + "\n>>> "; 527 Msg += Obj2; 528 error(Msg); 529 } 530 531 Symbol *SymbolTable::addRegular(StringRef Name, uint8_t StOther, uint8_t Type, 532 uint64_t Value, uint64_t Size, uint8_t Binding, 533 SectionBase *Section, InputFile *File) { 534 Symbol *S; 535 bool WasInserted; 536 std::tie(S, WasInserted) = insert(Name, Type, getVisibility(StOther), 537 /*CanOmitFromDynSym*/ false, File); 538 int Cmp = compareDefinedNonCommon(S, WasInserted, Binding, Section == nullptr, 539 Value, Name); 540 if (Cmp > 0) 541 replaceSymbol<Defined>(S, File, Name, Binding, StOther, Type, Value, Size, 542 Section); 543 else if (Cmp == 0) 544 reportDuplicate(S, File, dyn_cast_or_null<InputSectionBase>(Section), 545 Value); 546 return S; 547 } 548 549 template <typename ELFT> 550 void SymbolTable::addShared(StringRef Name, SharedFile<ELFT> &File, 551 const typename ELFT::Sym &Sym, uint32_t Alignment, 552 uint32_t VerdefIndex) { 553 // DSO symbols do not affect visibility in the output, so we pass STV_DEFAULT 554 // as the visibility, which will leave the visibility in the symbol table 555 // unchanged. 556 Symbol *S; 557 bool WasInserted; 558 std::tie(S, WasInserted) = insert(Name, Sym.getType(), STV_DEFAULT, 559 /*CanOmitFromDynSym*/ true, &File); 560 // Make sure we preempt DSO symbols with default visibility. 561 if (Sym.getVisibility() == STV_DEFAULT) 562 S->ExportDynamic = true; 563 564 // An undefined symbol with non default visibility must be satisfied 565 // in the same DSO. 566 if (WasInserted || 567 ((S->isUndefined() || S->isLazy()) && S->Visibility == STV_DEFAULT)) { 568 uint8_t Binding = S->Binding; 569 bool WasUndefined = S->isUndefined(); 570 replaceSymbol<SharedSymbol>(S, File, Name, Sym.getBinding(), Sym.st_other, 571 Sym.getType(), Sym.st_value, Sym.st_size, 572 Alignment, VerdefIndex); 573 if (!WasInserted) { 574 S->Binding = Binding; 575 if (!S->isWeak() && !Config->GcSections && WasUndefined) 576 File.IsNeeded = true; 577 } 578 } 579 } 580 581 Symbol *SymbolTable::addBitcode(StringRef Name, uint8_t Binding, 582 uint8_t StOther, uint8_t Type, 583 bool CanOmitFromDynSym, BitcodeFile &F) { 584 Symbol *S; 585 bool WasInserted; 586 std::tie(S, WasInserted) = 587 insert(Name, Type, getVisibility(StOther), CanOmitFromDynSym, &F); 588 int Cmp = compareDefinedNonCommon(S, WasInserted, Binding, 589 /*IsAbs*/ false, /*Value*/ 0, Name); 590 if (Cmp > 0) 591 replaceSymbol<Defined>(S, &F, Name, Binding, StOther, Type, 0, 0, nullptr); 592 else if (Cmp == 0) 593 reportDuplicate(S, &F); 594 return S; 595 } 596 597 Symbol *SymbolTable::find(StringRef Name) { 598 auto It = SymMap.find(CachedHashStringRef(Name)); 599 if (It == SymMap.end()) 600 return nullptr; 601 if (It->second == -1) 602 return nullptr; 603 return SymVector[It->second]; 604 } 605 606 // This is used to handle lazy symbols. May replace existent 607 // symbol with lazy version or request to Fetch it. 608 template <class ELFT, typename LazyT, typename... ArgT> 609 static void replaceOrFetchLazy(StringRef Name, InputFile &File, 610 llvm::function_ref<InputFile *()> Fetch, 611 ArgT &&... Arg) { 612 Symbol *S; 613 bool WasInserted; 614 std::tie(S, WasInserted) = Symtab->insert(Name); 615 if (WasInserted) { 616 replaceSymbol<LazyT>(S, File, Symbol::UnknownType, 617 std::forward<ArgT>(Arg)...); 618 return; 619 } 620 if (!S->isUndefined()) 621 return; 622 623 // An undefined weak will not fetch archive members. See comment on Lazy in 624 // Symbols.h for the details. 625 if (S->isWeak()) { 626 replaceSymbol<LazyT>(S, File, S->Type, std::forward<ArgT>(Arg)...); 627 S->Binding = STB_WEAK; 628 return; 629 } 630 631 if (InputFile *F = Fetch()) 632 Symtab->addFile<ELFT>(F); 633 } 634 635 template <class ELFT> 636 void SymbolTable::addLazyArchive(StringRef Name, ArchiveFile &F, 637 const object::Archive::Symbol Sym) { 638 replaceOrFetchLazy<ELFT, LazyArchive>(Name, F, [&]() { return F.fetch(Sym); }, 639 Sym); 640 } 641 642 template <class ELFT> 643 void SymbolTable::addLazyObject(StringRef Name, LazyObjFile &Obj) { 644 replaceOrFetchLazy<ELFT, LazyObject>(Name, Obj, [&]() { return Obj.fetch(); }, 645 Name); 646 } 647 648 template <class ELFT> void SymbolTable::fetchLazy(Symbol *Sym) { 649 if (auto *S = dyn_cast<LazyArchive>(Sym)) { 650 if (InputFile *File = S->fetch()) 651 addFile<ELFT>(File); 652 return; 653 } 654 655 auto *S = cast<LazyObject>(Sym); 656 if (InputFile *File = cast<LazyObjFile>(S->File)->fetch()) 657 addFile<ELFT>(File); 658 } 659 660 // Initialize DemangledSyms with a map from demangled symbols to symbol 661 // objects. Used to handle "extern C++" directive in version scripts. 662 // 663 // The map will contain all demangled symbols. That can be very large, 664 // and in LLD we generally want to avoid do anything for each symbol. 665 // Then, why are we doing this? Here's why. 666 // 667 // Users can use "extern C++ {}" directive to match against demangled 668 // C++ symbols. For example, you can write a pattern such as 669 // "llvm::*::foo(int, ?)". Obviously, there's no way to handle this 670 // other than trying to match a pattern against all demangled symbols. 671 // So, if "extern C++" feature is used, we need to demangle all known 672 // symbols. 673 StringMap<std::vector<Symbol *>> &SymbolTable::getDemangledSyms() { 674 if (!DemangledSyms) { 675 DemangledSyms.emplace(); 676 for (Symbol *Sym : SymVector) { 677 if (!Sym->isDefined()) 678 continue; 679 if (Optional<std::string> S = demangleItanium(Sym->getName())) 680 (*DemangledSyms)[*S].push_back(Sym); 681 else 682 (*DemangledSyms)[Sym->getName()].push_back(Sym); 683 } 684 } 685 return *DemangledSyms; 686 } 687 688 std::vector<Symbol *> SymbolTable::findByVersion(SymbolVersion Ver) { 689 if (Ver.IsExternCpp) 690 return getDemangledSyms().lookup(Ver.Name); 691 if (Symbol *B = find(Ver.Name)) 692 if (B->isDefined()) 693 return {B}; 694 return {}; 695 } 696 697 std::vector<Symbol *> SymbolTable::findAllByVersion(SymbolVersion Ver) { 698 std::vector<Symbol *> Res; 699 StringMatcher M(Ver.Name); 700 701 if (Ver.IsExternCpp) { 702 for (auto &P : getDemangledSyms()) 703 if (M.match(P.first())) 704 Res.insert(Res.end(), P.second.begin(), P.second.end()); 705 return Res; 706 } 707 708 for (Symbol *Sym : SymVector) 709 if (Sym->isDefined() && M.match(Sym->getName())) 710 Res.push_back(Sym); 711 return Res; 712 } 713 714 // If there's only one anonymous version definition in a version 715 // script file, the script does not actually define any symbol version, 716 // but just specifies symbols visibilities. 717 void SymbolTable::handleAnonymousVersion() { 718 for (SymbolVersion &Ver : Config->VersionScriptGlobals) 719 assignExactVersion(Ver, VER_NDX_GLOBAL, "global"); 720 for (SymbolVersion &Ver : Config->VersionScriptGlobals) 721 assignWildcardVersion(Ver, VER_NDX_GLOBAL); 722 for (SymbolVersion &Ver : Config->VersionScriptLocals) 723 assignExactVersion(Ver, VER_NDX_LOCAL, "local"); 724 for (SymbolVersion &Ver : Config->VersionScriptLocals) 725 assignWildcardVersion(Ver, VER_NDX_LOCAL); 726 } 727 728 // Handles -dynamic-list. 729 void SymbolTable::handleDynamicList() { 730 for (SymbolVersion &Ver : Config->DynamicList) { 731 std::vector<Symbol *> Syms; 732 if (Ver.HasWildcard) 733 Syms = findAllByVersion(Ver); 734 else 735 Syms = findByVersion(Ver); 736 737 for (Symbol *B : Syms) { 738 if (!Config->Shared) 739 B->ExportDynamic = true; 740 else if (B->includeInDynsym()) 741 B->IsPreemptible = true; 742 } 743 } 744 } 745 746 // Set symbol versions to symbols. This function handles patterns 747 // containing no wildcard characters. 748 void SymbolTable::assignExactVersion(SymbolVersion Ver, uint16_t VersionId, 749 StringRef VersionName) { 750 if (Ver.HasWildcard) 751 return; 752 753 // Get a list of symbols which we need to assign the version to. 754 std::vector<Symbol *> Syms = findByVersion(Ver); 755 if (Syms.empty()) { 756 if (!Config->UndefinedVersion) 757 error("version script assignment of '" + VersionName + "' to symbol '" + 758 Ver.Name + "' failed: symbol not defined"); 759 return; 760 } 761 762 // Assign the version. 763 for (Symbol *Sym : Syms) { 764 // Skip symbols containing version info because symbol versions 765 // specified by symbol names take precedence over version scripts. 766 // See parseSymbolVersion(). 767 if (Sym->getName().contains('@')) 768 continue; 769 770 if (Sym->VersionId != Config->DefaultSymbolVersion && 771 Sym->VersionId != VersionId) 772 error("duplicate symbol '" + Ver.Name + "' in version script"); 773 Sym->VersionId = VersionId; 774 } 775 } 776 777 void SymbolTable::assignWildcardVersion(SymbolVersion Ver, uint16_t VersionId) { 778 if (!Ver.HasWildcard) 779 return; 780 781 // Exact matching takes precendence over fuzzy matching, 782 // so we set a version to a symbol only if no version has been assigned 783 // to the symbol. This behavior is compatible with GNU. 784 for (Symbol *B : findAllByVersion(Ver)) 785 if (B->VersionId == Config->DefaultSymbolVersion) 786 B->VersionId = VersionId; 787 } 788 789 // This function processes version scripts by updating VersionId 790 // member of symbols. 791 void SymbolTable::scanVersionScript() { 792 // Handle edge cases first. 793 handleAnonymousVersion(); 794 handleDynamicList(); 795 796 // Now we have version definitions, so we need to set version ids to symbols. 797 // Each version definition has a glob pattern, and all symbols that match 798 // with the pattern get that version. 799 800 // First, we assign versions to exact matching symbols, 801 // i.e. version definitions not containing any glob meta-characters. 802 for (VersionDefinition &V : Config->VersionDefinitions) 803 for (SymbolVersion &Ver : V.Globals) 804 assignExactVersion(Ver, V.Id, V.Name); 805 806 // Next, we assign versions to fuzzy matching symbols, 807 // i.e. version definitions containing glob meta-characters. 808 // Note that because the last match takes precedence over previous matches, 809 // we iterate over the definitions in the reverse order. 810 for (VersionDefinition &V : llvm::reverse(Config->VersionDefinitions)) 811 for (SymbolVersion &Ver : V.Globals) 812 assignWildcardVersion(Ver, V.Id); 813 814 // Symbol themselves might know their versions because symbols 815 // can contain versions in the form of <name>@<version>. 816 // Let them parse and update their names to exclude version suffix. 817 for (Symbol *Sym : SymVector) 818 Sym->parseSymbolVersion(); 819 } 820 821 template void SymbolTable::addFile<ELF32LE>(InputFile *); 822 template void SymbolTable::addFile<ELF32BE>(InputFile *); 823 template void SymbolTable::addFile<ELF64LE>(InputFile *); 824 template void SymbolTable::addFile<ELF64BE>(InputFile *); 825 826 template void SymbolTable::addSymbolWrap<ELF32LE>(StringRef); 827 template void SymbolTable::addSymbolWrap<ELF32BE>(StringRef); 828 template void SymbolTable::addSymbolWrap<ELF64LE>(StringRef); 829 template void SymbolTable::addSymbolWrap<ELF64BE>(StringRef); 830 831 template Symbol *SymbolTable::addUndefined<ELF32LE>(StringRef); 832 template Symbol *SymbolTable::addUndefined<ELF32BE>(StringRef); 833 template Symbol *SymbolTable::addUndefined<ELF64LE>(StringRef); 834 template Symbol *SymbolTable::addUndefined<ELF64BE>(StringRef); 835 836 template Symbol *SymbolTable::addUndefined<ELF32LE>(StringRef, uint8_t, uint8_t, 837 uint8_t, bool, InputFile *); 838 template Symbol *SymbolTable::addUndefined<ELF32BE>(StringRef, uint8_t, uint8_t, 839 uint8_t, bool, InputFile *); 840 template Symbol *SymbolTable::addUndefined<ELF64LE>(StringRef, uint8_t, uint8_t, 841 uint8_t, bool, InputFile *); 842 template Symbol *SymbolTable::addUndefined<ELF64BE>(StringRef, uint8_t, uint8_t, 843 uint8_t, bool, InputFile *); 844 845 template void SymbolTable::addCombinedLTOObject<ELF32LE>(); 846 template void SymbolTable::addCombinedLTOObject<ELF32BE>(); 847 template void SymbolTable::addCombinedLTOObject<ELF64LE>(); 848 template void SymbolTable::addCombinedLTOObject<ELF64BE>(); 849 850 template void 851 SymbolTable::addLazyArchive<ELF32LE>(StringRef, ArchiveFile &, 852 const object::Archive::Symbol); 853 template void 854 SymbolTable::addLazyArchive<ELF32BE>(StringRef, ArchiveFile &, 855 const object::Archive::Symbol); 856 template void 857 SymbolTable::addLazyArchive<ELF64LE>(StringRef, ArchiveFile &, 858 const object::Archive::Symbol); 859 template void 860 SymbolTable::addLazyArchive<ELF64BE>(StringRef, ArchiveFile &, 861 const object::Archive::Symbol); 862 863 template void SymbolTable::addLazyObject<ELF32LE>(StringRef, LazyObjFile &); 864 template void SymbolTable::addLazyObject<ELF32BE>(StringRef, LazyObjFile &); 865 template void SymbolTable::addLazyObject<ELF64LE>(StringRef, LazyObjFile &); 866 template void SymbolTable::addLazyObject<ELF64BE>(StringRef, LazyObjFile &); 867 868 template void SymbolTable::fetchLazy<ELF32LE>(Symbol *); 869 template void SymbolTable::fetchLazy<ELF32BE>(Symbol *); 870 template void SymbolTable::fetchLazy<ELF64LE>(Symbol *); 871 template void SymbolTable::fetchLazy<ELF64BE>(Symbol *); 872 873 template void SymbolTable::addShared<ELF32LE>(StringRef, SharedFile<ELF32LE> &, 874 const typename ELF32LE::Sym &, 875 uint32_t Alignment, uint32_t); 876 template void SymbolTable::addShared<ELF32BE>(StringRef, SharedFile<ELF32BE> &, 877 const typename ELF32BE::Sym &, 878 uint32_t Alignment, uint32_t); 879 template void SymbolTable::addShared<ELF64LE>(StringRef, SharedFile<ELF64LE> &, 880 const typename ELF64LE::Sym &, 881 uint32_t Alignment, uint32_t); 882 template void SymbolTable::addShared<ELF64BE>(StringRef, SharedFile<ELF64BE> &, 883 const typename ELF64BE::Sym &, 884 uint32_t Alignment, uint32_t); 885