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