1 //===- SymbolTable.cpp ----------------------------------------------------===// 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 #include "SymbolTable.h" 10 #include "Config.h" 11 #include "Driver.h" 12 #include "LTO.h" 13 #include "PDB.h" 14 #include "Symbols.h" 15 #include "lld/Common/ErrorHandler.h" 16 #include "lld/Common/Memory.h" 17 #include "lld/Common/Timer.h" 18 #include "llvm/DebugInfo/Symbolize/Symbolize.h" 19 #include "llvm/IR/LLVMContext.h" 20 #include "llvm/Object/WindowsMachineFlag.h" 21 #include "llvm/Support/Debug.h" 22 #include "llvm/Support/raw_ostream.h" 23 #include <utility> 24 25 using namespace llvm; 26 27 namespace lld { 28 namespace coff { 29 30 static Timer ltoTimer("LTO", Timer::root()); 31 32 SymbolTable *symtab; 33 34 void SymbolTable::addFile(InputFile *file) { 35 log("Reading " + toString(file)); 36 file->parse(); 37 38 MachineTypes mt = file->getMachineType(); 39 if (config->machine == IMAGE_FILE_MACHINE_UNKNOWN) { 40 config->machine = mt; 41 } else if (mt != IMAGE_FILE_MACHINE_UNKNOWN && config->machine != mt) { 42 error(toString(file) + ": machine type " + machineToStr(mt) + 43 " conflicts with " + machineToStr(config->machine)); 44 return; 45 } 46 47 if (auto *f = dyn_cast<ObjFile>(file)) { 48 ObjFile::instances.push_back(f); 49 } else if (auto *f = dyn_cast<BitcodeFile>(file)) { 50 BitcodeFile::instances.push_back(f); 51 } else if (auto *f = dyn_cast<ImportFile>(file)) { 52 ImportFile::instances.push_back(f); 53 } 54 55 driver->parseDirectives(file); 56 } 57 58 static void errorOrWarn(const Twine &s) { 59 if (config->forceUnresolved) 60 warn(s); 61 else 62 error(s); 63 } 64 65 // Causes the file associated with a lazy symbol to be linked in. 66 static void forceLazy(Symbol *s) { 67 s->pendingArchiveLoad = true; 68 switch (s->kind()) { 69 case Symbol::Kind::LazyArchiveKind: { 70 auto *l = cast<LazyArchive>(s); 71 l->file->addMember(l->sym); 72 break; 73 } 74 case Symbol::Kind::LazyObjectKind: 75 cast<LazyObject>(s)->file->fetch(); 76 break; 77 default: 78 llvm_unreachable( 79 "symbol passed to forceLazy is not a LazyArchive or LazyObject"); 80 } 81 } 82 83 // Returns the symbol in SC whose value is <= Addr that is closest to Addr. 84 // This is generally the global variable or function whose definition contains 85 // Addr. 86 static Symbol *getSymbol(SectionChunk *sc, uint32_t addr) { 87 DefinedRegular *candidate = nullptr; 88 89 for (Symbol *s : sc->file->getSymbols()) { 90 auto *d = dyn_cast_or_null<DefinedRegular>(s); 91 if (!d || !d->data || d->file != sc->file || d->getChunk() != sc || 92 d->getValue() > addr || 93 (candidate && d->getValue() < candidate->getValue())) 94 continue; 95 96 candidate = d; 97 } 98 99 return candidate; 100 } 101 102 static std::vector<std::string> getSymbolLocations(BitcodeFile *file) { 103 std::string res("\n>>> referenced by "); 104 StringRef source = file->obj->getSourceFileName(); 105 if (!source.empty()) 106 res += source.str() + "\n>>> "; 107 res += toString(file); 108 return {res}; 109 } 110 111 static Optional<std::pair<StringRef, uint32_t>> 112 getFileLineDwarf(const SectionChunk *c, uint32_t addr) { 113 if (!config->symbolizer) 114 config->symbolizer = make<symbolize::LLVMSymbolizer>(); 115 Expected<DILineInfo> expectedLineInfo = config->symbolizer->symbolizeCode( 116 *c->file->getCOFFObj(), {addr, c->getSectionNumber() - 1}); 117 if (!expectedLineInfo) 118 return None; 119 const DILineInfo &lineInfo = *expectedLineInfo; 120 if (lineInfo.FileName == DILineInfo::BadString) 121 return None; 122 return std::make_pair(saver.save(lineInfo.FileName), lineInfo.Line); 123 } 124 125 static Optional<std::pair<StringRef, uint32_t>> 126 getFileLine(const SectionChunk *c, uint32_t addr) { 127 // MinGW can optionally use codeview, even if the default is dwarf. 128 Optional<std::pair<StringRef, uint32_t>> fileLine = 129 getFileLineCodeView(c, addr); 130 // If codeview didn't yield any result, check dwarf in MinGW mode. 131 if (!fileLine && config->mingw) 132 fileLine = getFileLineDwarf(c, addr); 133 return fileLine; 134 } 135 136 // Given a file and the index of a symbol in that file, returns a description 137 // of all references to that symbol from that file. If no debug information is 138 // available, returns just the name of the file, else one string per actual 139 // reference as described in the debug info. 140 std::vector<std::string> getSymbolLocations(ObjFile *file, uint32_t symIndex) { 141 struct Location { 142 Symbol *sym; 143 std::pair<StringRef, uint32_t> fileLine; 144 }; 145 std::vector<Location> locations; 146 147 for (Chunk *c : file->getChunks()) { 148 auto *sc = dyn_cast<SectionChunk>(c); 149 if (!sc) 150 continue; 151 for (const coff_relocation &r : sc->getRelocs()) { 152 if (r.SymbolTableIndex != symIndex) 153 continue; 154 Optional<std::pair<StringRef, uint32_t>> fileLine = 155 getFileLine(sc, r.VirtualAddress); 156 Symbol *sym = getSymbol(sc, r.VirtualAddress); 157 if (fileLine) 158 locations.push_back({sym, *fileLine}); 159 else if (sym) 160 locations.push_back({sym, {"", 0}}); 161 } 162 } 163 164 if (locations.empty()) 165 return std::vector<std::string>({"\n>>> referenced by " + toString(file)}); 166 167 std::vector<std::string> symbolLocations(locations.size()); 168 size_t i = 0; 169 for (Location loc : locations) { 170 llvm::raw_string_ostream os(symbolLocations[i++]); 171 os << "\n>>> referenced by "; 172 if (!loc.fileLine.first.empty()) 173 os << loc.fileLine.first << ":" << loc.fileLine.second 174 << "\n>>> "; 175 os << toString(file); 176 if (loc.sym) 177 os << ":(" << toString(*loc.sym) << ')'; 178 } 179 return symbolLocations; 180 } 181 182 std::vector<std::string> getSymbolLocations(InputFile *file, 183 uint32_t symIndex) { 184 if (auto *o = dyn_cast<ObjFile>(file)) 185 return getSymbolLocations(o, symIndex); 186 if (auto *b = dyn_cast<BitcodeFile>(file)) 187 return getSymbolLocations(b); 188 llvm_unreachable("unsupported file type passed to getSymbolLocations"); 189 return {}; 190 } 191 192 // For an undefined symbol, stores all files referencing it and the index of 193 // the undefined symbol in each file. 194 struct UndefinedDiag { 195 Symbol *sym; 196 struct File { 197 InputFile *file; 198 uint32_t symIndex; 199 }; 200 std::vector<File> files; 201 }; 202 203 static void reportUndefinedSymbol(const UndefinedDiag &undefDiag) { 204 std::string out; 205 llvm::raw_string_ostream os(out); 206 os << "undefined symbol: " << toString(*undefDiag.sym); 207 208 const size_t maxUndefReferences = 10; 209 size_t i = 0, numRefs = 0; 210 for (const UndefinedDiag::File &ref : undefDiag.files) { 211 std::vector<std::string> symbolLocations = 212 getSymbolLocations(ref.file, ref.symIndex); 213 numRefs += symbolLocations.size(); 214 for (const std::string &s : symbolLocations) { 215 if (i >= maxUndefReferences) 216 break; 217 os << s; 218 i++; 219 } 220 } 221 if (i < numRefs) 222 os << "\n>>> referenced " << numRefs - i << " more times"; 223 errorOrWarn(os.str()); 224 } 225 226 void SymbolTable::loadMinGWAutomaticImports() { 227 for (auto &i : symMap) { 228 Symbol *sym = i.second; 229 auto *undef = dyn_cast<Undefined>(sym); 230 if (!undef) 231 continue; 232 if (!sym->isUsedInRegularObj) 233 continue; 234 if (undef->getWeakAlias()) 235 continue; 236 237 StringRef name = undef->getName(); 238 239 if (name.startswith("__imp_")) 240 continue; 241 // If we have an undefined symbol, but we have a lazy symbol we could 242 // load, load it. 243 Symbol *l = find(("__imp_" + name).str()); 244 if (!l || l->pendingArchiveLoad || !l->isLazy()) 245 continue; 246 247 log("Loading lazy " + l->getName() + " from " + l->getFile()->getName() + 248 " for automatic import"); 249 forceLazy(l); 250 } 251 } 252 253 Defined *SymbolTable::impSymbol(StringRef name) { 254 if (name.startswith("__imp_")) 255 return nullptr; 256 return dyn_cast_or_null<Defined>(find(("__imp_" + name).str())); 257 } 258 259 bool SymbolTable::handleMinGWAutomaticImport(Symbol *sym, StringRef name) { 260 Defined *imp = impSymbol(name); 261 if (!imp) 262 return false; 263 264 // Replace the reference directly to a variable with a reference 265 // to the import address table instead. This obviously isn't right, 266 // but we mark the symbol as isRuntimePseudoReloc, and a later pass 267 // will add runtime pseudo relocations for every relocation against 268 // this Symbol. The runtime pseudo relocation framework expects the 269 // reference itself to point at the IAT entry. 270 size_t impSize = 0; 271 if (isa<DefinedImportData>(imp)) { 272 log("Automatically importing " + name + " from " + 273 cast<DefinedImportData>(imp)->getDLLName()); 274 impSize = sizeof(DefinedImportData); 275 } else if (isa<DefinedRegular>(imp)) { 276 log("Automatically importing " + name + " from " + 277 toString(cast<DefinedRegular>(imp)->file)); 278 impSize = sizeof(DefinedRegular); 279 } else { 280 warn("unable to automatically import " + name + " from " + imp->getName() + 281 " from " + toString(cast<DefinedRegular>(imp)->file) + 282 "; unexpected symbol type"); 283 return false; 284 } 285 sym->replaceKeepingName(imp, impSize); 286 sym->isRuntimePseudoReloc = true; 287 288 // There may exist symbols named .refptr.<name> which only consist 289 // of a single pointer to <name>. If it turns out <name> is 290 // automatically imported, we don't need to keep the .refptr.<name> 291 // pointer at all, but redirect all accesses to it to the IAT entry 292 // for __imp_<name> instead, and drop the whole .refptr.<name> chunk. 293 DefinedRegular *refptr = 294 dyn_cast_or_null<DefinedRegular>(find((".refptr." + name).str())); 295 if (refptr && refptr->getChunk()->getSize() == config->wordsize) { 296 SectionChunk *sc = dyn_cast_or_null<SectionChunk>(refptr->getChunk()); 297 if (sc && sc->getRelocs().size() == 1 && *sc->symbols().begin() == sym) { 298 log("Replacing .refptr." + name + " with " + imp->getName()); 299 refptr->getChunk()->live = false; 300 refptr->replaceKeepingName(imp, impSize); 301 } 302 } 303 return true; 304 } 305 306 /// Helper function for reportUnresolvable and resolveRemainingUndefines. 307 /// This function emits an "undefined symbol" diagnostic for each symbol in 308 /// undefs. If localImports is not nullptr, it also emits a "locally 309 /// defined symbol imported" diagnostic for symbols in localImports. 310 /// objFiles and bitcodeFiles (if not nullptr) are used to report where 311 /// undefined symbols are referenced. 312 static void 313 reportProblemSymbols(const SmallPtrSetImpl<Symbol *> &undefs, 314 const DenseMap<Symbol *, Symbol *> *localImports, 315 const std::vector<ObjFile *> objFiles, 316 const std::vector<BitcodeFile *> *bitcodeFiles) { 317 318 // Return early if there is nothing to report (which should be 319 // the common case). 320 if (undefs.empty() && (!localImports || localImports->empty())) 321 return; 322 323 for (Symbol *b : config->gcroot) { 324 if (undefs.count(b)) 325 errorOrWarn("<root>: undefined symbol: " + toString(*b)); 326 if (localImports) 327 if (Symbol *imp = localImports->lookup(b)) 328 warn("<root>: locally defined symbol imported: " + toString(*imp) + 329 " (defined in " + toString(imp->getFile()) + ") [LNK4217]"); 330 } 331 332 std::vector<UndefinedDiag> undefDiags; 333 DenseMap<Symbol *, int> firstDiag; 334 335 auto processFile = [&](InputFile *file, ArrayRef<Symbol *> symbols) { 336 uint32_t symIndex = (uint32_t)-1; 337 for (Symbol *sym : symbols) { 338 ++symIndex; 339 if (!sym) 340 continue; 341 if (undefs.count(sym)) { 342 auto it = firstDiag.find(sym); 343 if (it == firstDiag.end()) { 344 firstDiag[sym] = undefDiags.size(); 345 undefDiags.push_back({sym, {{file, symIndex}}}); 346 } else { 347 undefDiags[it->second].files.push_back({file, symIndex}); 348 } 349 } 350 if (localImports) 351 if (Symbol *imp = localImports->lookup(sym)) 352 warn(toString(file) + 353 ": locally defined symbol imported: " + toString(*imp) + 354 " (defined in " + toString(imp->getFile()) + ") [LNK4217]"); 355 } 356 }; 357 358 for (ObjFile *file : objFiles) 359 processFile(file, file->getSymbols()); 360 361 if (bitcodeFiles) 362 for (BitcodeFile *file : *bitcodeFiles) 363 processFile(file, file->getSymbols()); 364 365 for (const UndefinedDiag &undefDiag : undefDiags) 366 reportUndefinedSymbol(undefDiag); 367 } 368 369 void SymbolTable::reportUnresolvable() { 370 SmallPtrSet<Symbol *, 8> undefs; 371 for (auto &i : symMap) { 372 Symbol *sym = i.second; 373 auto *undef = dyn_cast<Undefined>(sym); 374 if (!undef) 375 continue; 376 if (undef->getWeakAlias()) 377 continue; 378 StringRef name = undef->getName(); 379 if (name.startswith("__imp_")) { 380 Symbol *imp = find(name.substr(strlen("__imp_"))); 381 if (imp && isa<Defined>(imp)) 382 continue; 383 } 384 if (name.contains("_PchSym_")) 385 continue; 386 if (config->mingw && impSymbol(name)) 387 continue; 388 undefs.insert(sym); 389 } 390 391 reportProblemSymbols(undefs, 392 /* localImports */ nullptr, ObjFile::instances, 393 &BitcodeFile::instances); 394 } 395 396 void SymbolTable::resolveRemainingUndefines() { 397 SmallPtrSet<Symbol *, 8> undefs; 398 DenseMap<Symbol *, Symbol *> localImports; 399 400 for (auto &i : symMap) { 401 Symbol *sym = i.second; 402 auto *undef = dyn_cast<Undefined>(sym); 403 if (!undef) 404 continue; 405 if (!sym->isUsedInRegularObj) 406 continue; 407 408 StringRef name = undef->getName(); 409 410 // A weak alias may have been resolved, so check for that. 411 if (Defined *d = undef->getWeakAlias()) { 412 // We want to replace Sym with D. However, we can't just blindly 413 // copy sizeof(SymbolUnion) bytes from D to Sym because D may be an 414 // internal symbol, and internal symbols are stored as "unparented" 415 // Symbols. For that reason we need to check which type of symbol we 416 // are dealing with and copy the correct number of bytes. 417 if (isa<DefinedRegular>(d)) 418 memcpy(sym, d, sizeof(DefinedRegular)); 419 else if (isa<DefinedAbsolute>(d)) 420 memcpy(sym, d, sizeof(DefinedAbsolute)); 421 else 422 memcpy(sym, d, sizeof(SymbolUnion)); 423 continue; 424 } 425 426 // If we can resolve a symbol by removing __imp_ prefix, do that. 427 // This odd rule is for compatibility with MSVC linker. 428 if (name.startswith("__imp_")) { 429 Symbol *imp = find(name.substr(strlen("__imp_"))); 430 if (imp && isa<Defined>(imp)) { 431 auto *d = cast<Defined>(imp); 432 replaceSymbol<DefinedLocalImport>(sym, name, d); 433 localImportChunks.push_back(cast<DefinedLocalImport>(sym)->getChunk()); 434 localImports[sym] = d; 435 continue; 436 } 437 } 438 439 // We don't want to report missing Microsoft precompiled headers symbols. 440 // A proper message will be emitted instead in PDBLinker::aquirePrecompObj 441 if (name.contains("_PchSym_")) 442 continue; 443 444 if (config->mingw && handleMinGWAutomaticImport(sym, name)) 445 continue; 446 447 // Remaining undefined symbols are not fatal if /force is specified. 448 // They are replaced with dummy defined symbols. 449 if (config->forceUnresolved) 450 replaceSymbol<DefinedAbsolute>(sym, name, 0); 451 undefs.insert(sym); 452 } 453 454 reportProblemSymbols( 455 undefs, config->warnLocallyDefinedImported ? &localImports : nullptr, 456 ObjFile::instances, /* bitcode files no longer needed */ nullptr); 457 } 458 459 std::pair<Symbol *, bool> SymbolTable::insert(StringRef name) { 460 bool inserted = false; 461 Symbol *&sym = symMap[CachedHashStringRef(name)]; 462 if (!sym) { 463 sym = reinterpret_cast<Symbol *>(make<SymbolUnion>()); 464 sym->isUsedInRegularObj = false; 465 sym->pendingArchiveLoad = false; 466 inserted = true; 467 } 468 return {sym, inserted}; 469 } 470 471 std::pair<Symbol *, bool> SymbolTable::insert(StringRef name, InputFile *file) { 472 std::pair<Symbol *, bool> result = insert(name); 473 if (!file || !isa<BitcodeFile>(file)) 474 result.first->isUsedInRegularObj = true; 475 return result; 476 } 477 478 Symbol *SymbolTable::addUndefined(StringRef name, InputFile *f, 479 bool isWeakAlias) { 480 Symbol *s; 481 bool wasInserted; 482 std::tie(s, wasInserted) = insert(name, f); 483 if (wasInserted || (s->isLazy() && isWeakAlias)) { 484 replaceSymbol<Undefined>(s, name); 485 return s; 486 } 487 if (s->isLazy()) 488 forceLazy(s); 489 return s; 490 } 491 492 void SymbolTable::addLazyArchive(ArchiveFile *f, const Archive::Symbol &sym) { 493 StringRef name = sym.getName(); 494 Symbol *s; 495 bool wasInserted; 496 std::tie(s, wasInserted) = insert(name); 497 if (wasInserted) { 498 replaceSymbol<LazyArchive>(s, f, sym); 499 return; 500 } 501 auto *u = dyn_cast<Undefined>(s); 502 if (!u || u->weakAlias || s->pendingArchiveLoad) 503 return; 504 s->pendingArchiveLoad = true; 505 f->addMember(sym); 506 } 507 508 void SymbolTable::addLazyObject(LazyObjFile *f, StringRef n) { 509 Symbol *s; 510 bool wasInserted; 511 std::tie(s, wasInserted) = insert(n, f); 512 if (wasInserted) { 513 replaceSymbol<LazyObject>(s, f, n); 514 return; 515 } 516 auto *u = dyn_cast<Undefined>(s); 517 if (!u || u->weakAlias || s->pendingArchiveLoad) 518 return; 519 s->pendingArchiveLoad = true; 520 f->fetch(); 521 } 522 523 void SymbolTable::reportDuplicate(Symbol *existing, InputFile *newFile) { 524 std::string msg = "duplicate symbol: " + toString(*existing) + " in " + 525 toString(existing->getFile()) + " and in " + 526 toString(newFile); 527 528 if (config->forceMultiple) 529 warn(msg); 530 else 531 error(msg); 532 } 533 534 Symbol *SymbolTable::addAbsolute(StringRef n, COFFSymbolRef sym) { 535 Symbol *s; 536 bool wasInserted; 537 std::tie(s, wasInserted) = insert(n, nullptr); 538 s->isUsedInRegularObj = true; 539 if (wasInserted || isa<Undefined>(s) || s->isLazy()) 540 replaceSymbol<DefinedAbsolute>(s, n, sym); 541 else if (!isa<DefinedCOFF>(s)) 542 reportDuplicate(s, nullptr); 543 return s; 544 } 545 546 Symbol *SymbolTable::addAbsolute(StringRef n, uint64_t va) { 547 Symbol *s; 548 bool wasInserted; 549 std::tie(s, wasInserted) = insert(n, nullptr); 550 s->isUsedInRegularObj = true; 551 if (wasInserted || isa<Undefined>(s) || s->isLazy()) 552 replaceSymbol<DefinedAbsolute>(s, n, va); 553 else if (!isa<DefinedCOFF>(s)) 554 reportDuplicate(s, nullptr); 555 return s; 556 } 557 558 Symbol *SymbolTable::addSynthetic(StringRef n, Chunk *c) { 559 Symbol *s; 560 bool wasInserted; 561 std::tie(s, wasInserted) = insert(n, nullptr); 562 s->isUsedInRegularObj = true; 563 if (wasInserted || isa<Undefined>(s) || s->isLazy()) 564 replaceSymbol<DefinedSynthetic>(s, n, c); 565 else if (!isa<DefinedCOFF>(s)) 566 reportDuplicate(s, nullptr); 567 return s; 568 } 569 570 Symbol *SymbolTable::addRegular(InputFile *f, StringRef n, 571 const coff_symbol_generic *sym, 572 SectionChunk *c) { 573 Symbol *s; 574 bool wasInserted; 575 std::tie(s, wasInserted) = insert(n, f); 576 if (wasInserted || !isa<DefinedRegular>(s)) 577 replaceSymbol<DefinedRegular>(s, f, n, /*IsCOMDAT*/ false, 578 /*IsExternal*/ true, sym, c); 579 else 580 reportDuplicate(s, f); 581 return s; 582 } 583 584 std::pair<DefinedRegular *, bool> 585 SymbolTable::addComdat(InputFile *f, StringRef n, 586 const coff_symbol_generic *sym) { 587 Symbol *s; 588 bool wasInserted; 589 std::tie(s, wasInserted) = insert(n, f); 590 if (wasInserted || !isa<DefinedRegular>(s)) { 591 replaceSymbol<DefinedRegular>(s, f, n, /*IsCOMDAT*/ true, 592 /*IsExternal*/ true, sym, nullptr); 593 return {cast<DefinedRegular>(s), true}; 594 } 595 auto *existingSymbol = cast<DefinedRegular>(s); 596 if (!existingSymbol->isCOMDAT) 597 reportDuplicate(s, f); 598 return {existingSymbol, false}; 599 } 600 601 Symbol *SymbolTable::addCommon(InputFile *f, StringRef n, uint64_t size, 602 const coff_symbol_generic *sym, CommonChunk *c) { 603 Symbol *s; 604 bool wasInserted; 605 std::tie(s, wasInserted) = insert(n, f); 606 if (wasInserted || !isa<DefinedCOFF>(s)) 607 replaceSymbol<DefinedCommon>(s, f, n, size, sym, c); 608 else if (auto *dc = dyn_cast<DefinedCommon>(s)) 609 if (size > dc->getSize()) 610 replaceSymbol<DefinedCommon>(s, f, n, size, sym, c); 611 return s; 612 } 613 614 Symbol *SymbolTable::addImportData(StringRef n, ImportFile *f) { 615 Symbol *s; 616 bool wasInserted; 617 std::tie(s, wasInserted) = insert(n, nullptr); 618 s->isUsedInRegularObj = true; 619 if (wasInserted || isa<Undefined>(s) || s->isLazy()) { 620 replaceSymbol<DefinedImportData>(s, n, f); 621 return s; 622 } 623 624 reportDuplicate(s, f); 625 return nullptr; 626 } 627 628 Symbol *SymbolTable::addImportThunk(StringRef name, DefinedImportData *id, 629 uint16_t machine) { 630 Symbol *s; 631 bool wasInserted; 632 std::tie(s, wasInserted) = insert(name, nullptr); 633 s->isUsedInRegularObj = true; 634 if (wasInserted || isa<Undefined>(s) || s->isLazy()) { 635 replaceSymbol<DefinedImportThunk>(s, name, id, machine); 636 return s; 637 } 638 639 reportDuplicate(s, id->file); 640 return nullptr; 641 } 642 643 void SymbolTable::addLibcall(StringRef name) { 644 Symbol *sym = findUnderscore(name); 645 if (!sym) 646 return; 647 648 if (auto *l = dyn_cast<LazyArchive>(sym)) { 649 MemoryBufferRef mb = l->getMemberBuffer(); 650 if (isBitcode(mb)) 651 addUndefined(sym->getName()); 652 } else if (LazyObject *o = dyn_cast<LazyObject>(sym)) { 653 if (isBitcode(o->file->mb)) 654 addUndefined(sym->getName()); 655 } 656 } 657 658 std::vector<Chunk *> SymbolTable::getChunks() { 659 std::vector<Chunk *> res; 660 for (ObjFile *file : ObjFile::instances) { 661 ArrayRef<Chunk *> v = file->getChunks(); 662 res.insert(res.end(), v.begin(), v.end()); 663 } 664 return res; 665 } 666 667 Symbol *SymbolTable::find(StringRef name) { 668 return symMap.lookup(CachedHashStringRef(name)); 669 } 670 671 Symbol *SymbolTable::findUnderscore(StringRef name) { 672 if (config->machine == I386) 673 return find(("_" + name).str()); 674 return find(name); 675 } 676 677 // Return all symbols that start with Prefix, possibly ignoring the first 678 // character of Prefix or the first character symbol. 679 std::vector<Symbol *> SymbolTable::getSymsWithPrefix(StringRef prefix) { 680 std::vector<Symbol *> syms; 681 for (auto pair : symMap) { 682 StringRef name = pair.first.val(); 683 if (name.startswith(prefix) || name.startswith(prefix.drop_front()) || 684 name.drop_front().startswith(prefix) || 685 name.drop_front().startswith(prefix.drop_front())) { 686 syms.push_back(pair.second); 687 } 688 } 689 return syms; 690 } 691 692 Symbol *SymbolTable::findMangle(StringRef name) { 693 if (Symbol *sym = find(name)) 694 if (!isa<Undefined>(sym)) 695 return sym; 696 697 // Efficient fuzzy string lookup is impossible with a hash table, so iterate 698 // the symbol table once and collect all possibly matching symbols into this 699 // vector. Then compare each possibly matching symbol with each possible 700 // mangling. 701 std::vector<Symbol *> syms = getSymsWithPrefix(name); 702 auto findByPrefix = [&syms](const Twine &t) -> Symbol * { 703 std::string prefix = t.str(); 704 for (auto *s : syms) 705 if (s->getName().startswith(prefix)) 706 return s; 707 return nullptr; 708 }; 709 710 // For non-x86, just look for C++ functions. 711 if (config->machine != I386) 712 return findByPrefix("?" + name + "@@Y"); 713 714 if (!name.startswith("_")) 715 return nullptr; 716 // Search for x86 stdcall function. 717 if (Symbol *s = findByPrefix(name + "@")) 718 return s; 719 // Search for x86 fastcall function. 720 if (Symbol *s = findByPrefix("@" + name.substr(1) + "@")) 721 return s; 722 // Search for x86 vectorcall function. 723 if (Symbol *s = findByPrefix(name.substr(1) + "@@")) 724 return s; 725 // Search for x86 C++ non-member function. 726 return findByPrefix("?" + name.substr(1) + "@@Y"); 727 } 728 729 Symbol *SymbolTable::addUndefined(StringRef name) { 730 return addUndefined(name, nullptr, false); 731 } 732 733 std::vector<StringRef> SymbolTable::compileBitcodeFiles() { 734 lto.reset(new BitcodeCompiler); 735 for (BitcodeFile *f : BitcodeFile::instances) 736 lto->add(*f); 737 return lto->compile(); 738 } 739 740 void SymbolTable::addCombinedLTOObjects() { 741 if (BitcodeFile::instances.empty()) 742 return; 743 744 ScopedTimer t(ltoTimer); 745 for (StringRef object : compileBitcodeFiles()) { 746 auto *obj = make<ObjFile>(MemoryBufferRef(object, "lto.tmp")); 747 obj->parse(); 748 ObjFile::instances.push_back(obj); 749 } 750 } 751 752 } // namespace coff 753 } // namespace lld 754