1 //===- InputFiles.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 "InputFiles.h" 10 #include "Chunks.h" 11 #include "Config.h" 12 #include "DebugTypes.h" 13 #include "Driver.h" 14 #include "SymbolTable.h" 15 #include "Symbols.h" 16 #include "lld/Common/DWARF.h" 17 #include "lld/Common/ErrorHandler.h" 18 #include "lld/Common/Memory.h" 19 #include "llvm-c/lto.h" 20 #include "llvm/ADT/SmallVector.h" 21 #include "llvm/ADT/Triple.h" 22 #include "llvm/ADT/Twine.h" 23 #include "llvm/BinaryFormat/COFF.h" 24 #include "llvm/DebugInfo/CodeView/DebugSubsectionRecord.h" 25 #include "llvm/DebugInfo/CodeView/SymbolDeserializer.h" 26 #include "llvm/DebugInfo/CodeView/SymbolRecord.h" 27 #include "llvm/DebugInfo/CodeView/TypeDeserializer.h" 28 #include "llvm/DebugInfo/PDB/Native/NativeSession.h" 29 #include "llvm/DebugInfo/PDB/Native/PDBFile.h" 30 #include "llvm/LTO/LTO.h" 31 #include "llvm/Object/Binary.h" 32 #include "llvm/Object/COFF.h" 33 #include "llvm/Support/Casting.h" 34 #include "llvm/Support/Endian.h" 35 #include "llvm/Support/Error.h" 36 #include "llvm/Support/ErrorOr.h" 37 #include "llvm/Support/FileSystem.h" 38 #include "llvm/Support/Path.h" 39 #include "llvm/Target/TargetOptions.h" 40 #include <cstring> 41 #include <system_error> 42 #include <utility> 43 44 using namespace llvm; 45 using namespace llvm::COFF; 46 using namespace llvm::codeview; 47 using namespace llvm::object; 48 using namespace llvm::support::endian; 49 using namespace lld; 50 using namespace lld::coff; 51 52 using llvm::Triple; 53 using llvm::support::ulittle32_t; 54 55 // Returns the last element of a path, which is supposed to be a filename. 56 static StringRef getBasename(StringRef path) { 57 return sys::path::filename(path, sys::path::Style::windows); 58 } 59 60 // Returns a string in the format of "foo.obj" or "foo.obj(bar.lib)". 61 std::string lld::toString(const coff::InputFile *file) { 62 if (!file) 63 return "<internal>"; 64 if (file->parentName.empty() || file->kind() == coff::InputFile::ImportKind) 65 return std::string(file->getName()); 66 67 return (getBasename(file->parentName) + "(" + getBasename(file->getName()) + 68 ")") 69 .str(); 70 } 71 72 std::vector<ObjFile *> ObjFile::instances; 73 std::map<std::string, PDBInputFile *> PDBInputFile::instances; 74 std::vector<ImportFile *> ImportFile::instances; 75 std::vector<BitcodeFile *> BitcodeFile::instances; 76 77 /// Checks that Source is compatible with being a weak alias to Target. 78 /// If Source is Undefined and has no weak alias set, makes it a weak 79 /// alias to Target. 80 static void checkAndSetWeakAlias(SymbolTable *symtab, InputFile *f, 81 Symbol *source, Symbol *target) { 82 if (auto *u = dyn_cast<Undefined>(source)) { 83 if (u->weakAlias && u->weakAlias != target) { 84 // Weak aliases as produced by GCC are named in the form 85 // .weak.<weaksymbol>.<othersymbol>, where <othersymbol> is the name 86 // of another symbol emitted near the weak symbol. 87 // Just use the definition from the first object file that defined 88 // this weak symbol. 89 if (config->mingw) 90 return; 91 symtab->reportDuplicate(source, f); 92 } 93 u->weakAlias = target; 94 } 95 } 96 97 static bool ignoredSymbolName(StringRef name) { 98 return name == "@feat.00" || name == "@comp.id"; 99 } 100 101 ArchiveFile::ArchiveFile(MemoryBufferRef m) : InputFile(ArchiveKind, m) {} 102 103 void ArchiveFile::parse() { 104 // Parse a MemoryBufferRef as an archive file. 105 file = CHECK(Archive::create(mb), this); 106 107 // Read the symbol table to construct Lazy objects. 108 for (const Archive::Symbol &sym : file->symbols()) 109 symtab->addLazyArchive(this, sym); 110 } 111 112 // Returns a buffer pointing to a member file containing a given symbol. 113 void ArchiveFile::addMember(const Archive::Symbol &sym) { 114 const Archive::Child &c = 115 CHECK(sym.getMember(), 116 "could not get the member for symbol " + toCOFFString(sym)); 117 118 // Return an empty buffer if we have already returned the same buffer. 119 if (!seen.insert(c.getChildOffset()).second) 120 return; 121 122 driver->enqueueArchiveMember(c, sym, getName()); 123 } 124 125 std::vector<MemoryBufferRef> lld::coff::getArchiveMembers(Archive *file) { 126 std::vector<MemoryBufferRef> v; 127 Error err = Error::success(); 128 for (const Archive::Child &c : file->children(err)) { 129 MemoryBufferRef mbref = 130 CHECK(c.getMemoryBufferRef(), 131 file->getFileName() + 132 ": could not get the buffer for a child of the archive"); 133 v.push_back(mbref); 134 } 135 if (err) 136 fatal(file->getFileName() + 137 ": Archive::children failed: " + toString(std::move(err))); 138 return v; 139 } 140 141 void LazyObjFile::fetch() { 142 if (mb.getBuffer().empty()) 143 return; 144 145 InputFile *file; 146 if (isBitcode(mb)) 147 file = make<BitcodeFile>(mb, "", 0, std::move(symbols)); 148 else 149 file = make<ObjFile>(mb, std::move(symbols)); 150 mb = {}; 151 symtab->addFile(file); 152 } 153 154 void LazyObjFile::parse() { 155 if (isBitcode(this->mb)) { 156 // Bitcode file. 157 std::unique_ptr<lto::InputFile> obj = 158 CHECK(lto::InputFile::create(this->mb), this); 159 for (const lto::InputFile::Symbol &sym : obj->symbols()) { 160 if (!sym.isUndefined()) 161 symtab->addLazyObject(this, sym.getName()); 162 } 163 return; 164 } 165 166 // Native object file. 167 std::unique_ptr<Binary> coffObjPtr = CHECK(createBinary(mb), this); 168 COFFObjectFile *coffObj = cast<COFFObjectFile>(coffObjPtr.get()); 169 uint32_t numSymbols = coffObj->getNumberOfSymbols(); 170 for (uint32_t i = 0; i < numSymbols; ++i) { 171 COFFSymbolRef coffSym = check(coffObj->getSymbol(i)); 172 if (coffSym.isUndefined() || !coffSym.isExternal() || 173 coffSym.isWeakExternal()) 174 continue; 175 StringRef name = check(coffObj->getSymbolName(coffSym)); 176 if (coffSym.isAbsolute() && ignoredSymbolName(name)) 177 continue; 178 symtab->addLazyObject(this, name); 179 i += coffSym.getNumberOfAuxSymbols(); 180 } 181 } 182 183 void ObjFile::parse() { 184 // Parse a memory buffer as a COFF file. 185 std::unique_ptr<Binary> bin = CHECK(createBinary(mb), this); 186 187 if (auto *obj = dyn_cast<COFFObjectFile>(bin.get())) { 188 bin.release(); 189 coffObj.reset(obj); 190 } else { 191 fatal(toString(this) + " is not a COFF file"); 192 } 193 194 // Read section and symbol tables. 195 initializeChunks(); 196 initializeSymbols(); 197 initializeFlags(); 198 initializeDependencies(); 199 } 200 201 const coff_section *ObjFile::getSection(uint32_t i) { 202 auto sec = coffObj->getSection(i); 203 if (!sec) 204 fatal("getSection failed: #" + Twine(i) + ": " + toString(sec.takeError())); 205 return *sec; 206 } 207 208 // We set SectionChunk pointers in the SparseChunks vector to this value 209 // temporarily to mark comdat sections as having an unknown resolution. As we 210 // walk the object file's symbol table, once we visit either a leader symbol or 211 // an associative section definition together with the parent comdat's leader, 212 // we set the pointer to either nullptr (to mark the section as discarded) or a 213 // valid SectionChunk for that section. 214 static SectionChunk *const pendingComdat = reinterpret_cast<SectionChunk *>(1); 215 216 void ObjFile::initializeChunks() { 217 uint32_t numSections = coffObj->getNumberOfSections(); 218 sparseChunks.resize(numSections + 1); 219 for (uint32_t i = 1; i < numSections + 1; ++i) { 220 const coff_section *sec = getSection(i); 221 if (sec->Characteristics & IMAGE_SCN_LNK_COMDAT) 222 sparseChunks[i] = pendingComdat; 223 else 224 sparseChunks[i] = readSection(i, nullptr, ""); 225 } 226 } 227 228 SectionChunk *ObjFile::readSection(uint32_t sectionNumber, 229 const coff_aux_section_definition *def, 230 StringRef leaderName) { 231 const coff_section *sec = getSection(sectionNumber); 232 233 StringRef name; 234 if (Expected<StringRef> e = coffObj->getSectionName(sec)) 235 name = *e; 236 else 237 fatal("getSectionName failed: #" + Twine(sectionNumber) + ": " + 238 toString(e.takeError())); 239 240 if (name == ".drectve") { 241 ArrayRef<uint8_t> data; 242 cantFail(coffObj->getSectionContents(sec, data)); 243 directives = StringRef((const char *)data.data(), data.size()); 244 return nullptr; 245 } 246 247 if (name == ".llvm_addrsig") { 248 addrsigSec = sec; 249 return nullptr; 250 } 251 252 if (name == ".llvm.call-graph-profile") { 253 callgraphSec = sec; 254 return nullptr; 255 } 256 257 // Object files may have DWARF debug info or MS CodeView debug info 258 // (or both). 259 // 260 // DWARF sections don't need any special handling from the perspective 261 // of the linker; they are just a data section containing relocations. 262 // We can just link them to complete debug info. 263 // 264 // CodeView needs linker support. We need to interpret debug info, 265 // and then write it to a separate .pdb file. 266 267 // Ignore DWARF debug info unless /debug is given. 268 if (!config->debug && name.startswith(".debug_")) 269 return nullptr; 270 271 if (sec->Characteristics & llvm::COFF::IMAGE_SCN_LNK_REMOVE) 272 return nullptr; 273 auto *c = make<SectionChunk>(this, sec); 274 if (def) 275 c->checksum = def->CheckSum; 276 277 // CodeView sections are stored to a different vector because they are not 278 // linked in the regular manner. 279 if (c->isCodeView()) 280 debugChunks.push_back(c); 281 else if (name == ".gfids$y") 282 guardFidChunks.push_back(c); 283 else if (name == ".gljmp$y") 284 guardLJmpChunks.push_back(c); 285 else if (name == ".sxdata") 286 sxDataChunks.push_back(c); 287 else if (config->tailMerge && sec->NumberOfRelocations == 0 && 288 name == ".rdata" && leaderName.startswith("??_C@")) 289 // COFF sections that look like string literal sections (i.e. no 290 // relocations, in .rdata, leader symbol name matches the MSVC name mangling 291 // for string literals) are subject to string tail merging. 292 MergeChunk::addSection(c); 293 else if (name == ".rsrc" || name.startswith(".rsrc$")) 294 resourceChunks.push_back(c); 295 else 296 chunks.push_back(c); 297 298 return c; 299 } 300 301 void ObjFile::includeResourceChunks() { 302 chunks.insert(chunks.end(), resourceChunks.begin(), resourceChunks.end()); 303 } 304 305 void ObjFile::readAssociativeDefinition( 306 COFFSymbolRef sym, const coff_aux_section_definition *def) { 307 readAssociativeDefinition(sym, def, def->getNumber(sym.isBigObj())); 308 } 309 310 void ObjFile::readAssociativeDefinition(COFFSymbolRef sym, 311 const coff_aux_section_definition *def, 312 uint32_t parentIndex) { 313 SectionChunk *parent = sparseChunks[parentIndex]; 314 int32_t sectionNumber = sym.getSectionNumber(); 315 316 auto diag = [&]() { 317 StringRef name = check(coffObj->getSymbolName(sym)); 318 319 StringRef parentName; 320 const coff_section *parentSec = getSection(parentIndex); 321 if (Expected<StringRef> e = coffObj->getSectionName(parentSec)) 322 parentName = *e; 323 error(toString(this) + ": associative comdat " + name + " (sec " + 324 Twine(sectionNumber) + ") has invalid reference to section " + 325 parentName + " (sec " + Twine(parentIndex) + ")"); 326 }; 327 328 if (parent == pendingComdat) { 329 // This can happen if an associative comdat refers to another associative 330 // comdat that appears after it (invalid per COFF spec) or to a section 331 // without any symbols. 332 diag(); 333 return; 334 } 335 336 // Check whether the parent is prevailing. If it is, so are we, and we read 337 // the section; otherwise mark it as discarded. 338 if (parent) { 339 SectionChunk *c = readSection(sectionNumber, def, ""); 340 sparseChunks[sectionNumber] = c; 341 if (c) { 342 c->selection = IMAGE_COMDAT_SELECT_ASSOCIATIVE; 343 parent->addAssociative(c); 344 } 345 } else { 346 sparseChunks[sectionNumber] = nullptr; 347 } 348 } 349 350 void ObjFile::recordPrevailingSymbolForMingw( 351 COFFSymbolRef sym, DenseMap<StringRef, uint32_t> &prevailingSectionMap) { 352 // For comdat symbols in executable sections, where this is the copy 353 // of the section chunk we actually include instead of discarding it, 354 // add the symbol to a map to allow using it for implicitly 355 // associating .[px]data$<func> sections to it. 356 // Use the suffix from the .text$<func> instead of the leader symbol 357 // name, for cases where the names differ (i386 mangling/decorations, 358 // cases where the leader is a weak symbol named .weak.func.default*). 359 int32_t sectionNumber = sym.getSectionNumber(); 360 SectionChunk *sc = sparseChunks[sectionNumber]; 361 if (sc && sc->getOutputCharacteristics() & IMAGE_SCN_MEM_EXECUTE) { 362 StringRef name = sc->getSectionName().split('$').second; 363 prevailingSectionMap[name] = sectionNumber; 364 } 365 } 366 367 void ObjFile::maybeAssociateSEHForMingw( 368 COFFSymbolRef sym, const coff_aux_section_definition *def, 369 const DenseMap<StringRef, uint32_t> &prevailingSectionMap) { 370 StringRef name = check(coffObj->getSymbolName(sym)); 371 if (name.consume_front(".pdata$") || name.consume_front(".xdata$") || 372 name.consume_front(".eh_frame$")) { 373 // For MinGW, treat .[px]data$<func> and .eh_frame$<func> as implicitly 374 // associative to the symbol <func>. 375 auto parentSym = prevailingSectionMap.find(name); 376 if (parentSym != prevailingSectionMap.end()) 377 readAssociativeDefinition(sym, def, parentSym->second); 378 } 379 } 380 381 Symbol *ObjFile::createRegular(COFFSymbolRef sym) { 382 SectionChunk *sc = sparseChunks[sym.getSectionNumber()]; 383 if (sym.isExternal()) { 384 StringRef name = check(coffObj->getSymbolName(sym)); 385 if (sc) 386 return symtab->addRegular(this, name, sym.getGeneric(), sc, 387 sym.getValue()); 388 // For MinGW symbols named .weak.* that point to a discarded section, 389 // don't create an Undefined symbol. If nothing ever refers to the symbol, 390 // everything should be fine. If something actually refers to the symbol 391 // (e.g. the undefined weak alias), linking will fail due to undefined 392 // references at the end. 393 if (config->mingw && name.startswith(".weak.")) 394 return nullptr; 395 return symtab->addUndefined(name, this, false); 396 } 397 if (sc) 398 return make<DefinedRegular>(this, /*Name*/ "", /*IsCOMDAT*/ false, 399 /*IsExternal*/ false, sym.getGeneric(), sc); 400 return nullptr; 401 } 402 403 void ObjFile::initializeSymbols() { 404 uint32_t numSymbols = coffObj->getNumberOfSymbols(); 405 symbols.resize(numSymbols); 406 407 SmallVector<std::pair<Symbol *, uint32_t>, 8> weakAliases; 408 std::vector<uint32_t> pendingIndexes; 409 pendingIndexes.reserve(numSymbols); 410 411 DenseMap<StringRef, uint32_t> prevailingSectionMap; 412 std::vector<const coff_aux_section_definition *> comdatDefs( 413 coffObj->getNumberOfSections() + 1); 414 415 for (uint32_t i = 0; i < numSymbols; ++i) { 416 COFFSymbolRef coffSym = check(coffObj->getSymbol(i)); 417 bool prevailingComdat; 418 if (coffSym.isUndefined()) { 419 symbols[i] = createUndefined(coffSym); 420 } else if (coffSym.isWeakExternal()) { 421 symbols[i] = createUndefined(coffSym); 422 uint32_t tagIndex = coffSym.getAux<coff_aux_weak_external>()->TagIndex; 423 weakAliases.emplace_back(symbols[i], tagIndex); 424 } else if (Optional<Symbol *> optSym = 425 createDefined(coffSym, comdatDefs, prevailingComdat)) { 426 symbols[i] = *optSym; 427 if (config->mingw && prevailingComdat) 428 recordPrevailingSymbolForMingw(coffSym, prevailingSectionMap); 429 } else { 430 // createDefined() returns None if a symbol belongs to a section that 431 // was pending at the point when the symbol was read. This can happen in 432 // two cases: 433 // 1) section definition symbol for a comdat leader; 434 // 2) symbol belongs to a comdat section associated with another section. 435 // In both of these cases, we can expect the section to be resolved by 436 // the time we finish visiting the remaining symbols in the symbol 437 // table. So we postpone the handling of this symbol until that time. 438 pendingIndexes.push_back(i); 439 } 440 i += coffSym.getNumberOfAuxSymbols(); 441 } 442 443 for (uint32_t i : pendingIndexes) { 444 COFFSymbolRef sym = check(coffObj->getSymbol(i)); 445 if (const coff_aux_section_definition *def = sym.getSectionDefinition()) { 446 if (def->Selection == IMAGE_COMDAT_SELECT_ASSOCIATIVE) 447 readAssociativeDefinition(sym, def); 448 else if (config->mingw) 449 maybeAssociateSEHForMingw(sym, def, prevailingSectionMap); 450 } 451 if (sparseChunks[sym.getSectionNumber()] == pendingComdat) { 452 StringRef name = check(coffObj->getSymbolName(sym)); 453 log("comdat section " + name + 454 " without leader and unassociated, discarding"); 455 continue; 456 } 457 symbols[i] = createRegular(sym); 458 } 459 460 for (auto &kv : weakAliases) { 461 Symbol *sym = kv.first; 462 uint32_t idx = kv.second; 463 checkAndSetWeakAlias(symtab, this, sym, symbols[idx]); 464 } 465 466 // Free the memory used by sparseChunks now that symbol loading is finished. 467 decltype(sparseChunks)().swap(sparseChunks); 468 } 469 470 Symbol *ObjFile::createUndefined(COFFSymbolRef sym) { 471 StringRef name = check(coffObj->getSymbolName(sym)); 472 return symtab->addUndefined(name, this, sym.isWeakExternal()); 473 } 474 475 static const coff_aux_section_definition *findSectionDef(COFFObjectFile *obj, 476 int32_t section) { 477 uint32_t numSymbols = obj->getNumberOfSymbols(); 478 for (uint32_t i = 0; i < numSymbols; ++i) { 479 COFFSymbolRef sym = check(obj->getSymbol(i)); 480 if (sym.getSectionNumber() != section) 481 continue; 482 if (const coff_aux_section_definition *def = sym.getSectionDefinition()) 483 return def; 484 } 485 return nullptr; 486 } 487 488 void ObjFile::handleComdatSelection( 489 COFFSymbolRef sym, COMDATType &selection, bool &prevailing, 490 DefinedRegular *leader, 491 const llvm::object::coff_aux_section_definition *def) { 492 if (prevailing) 493 return; 494 // There's already an existing comdat for this symbol: `Leader`. 495 // Use the comdats's selection field to determine if the new 496 // symbol in `Sym` should be discarded, produce a duplicate symbol 497 // error, etc. 498 499 SectionChunk *leaderChunk = nullptr; 500 COMDATType leaderSelection = IMAGE_COMDAT_SELECT_ANY; 501 502 if (leader->data) { 503 leaderChunk = leader->getChunk(); 504 leaderSelection = leaderChunk->selection; 505 } else { 506 // FIXME: comdats from LTO files don't know their selection; treat them 507 // as "any". 508 selection = leaderSelection; 509 } 510 511 if ((selection == IMAGE_COMDAT_SELECT_ANY && 512 leaderSelection == IMAGE_COMDAT_SELECT_LARGEST) || 513 (selection == IMAGE_COMDAT_SELECT_LARGEST && 514 leaderSelection == IMAGE_COMDAT_SELECT_ANY)) { 515 // cl.exe picks "any" for vftables when building with /GR- and 516 // "largest" when building with /GR. To be able to link object files 517 // compiled with each flag, "any" and "largest" are merged as "largest". 518 leaderSelection = selection = IMAGE_COMDAT_SELECT_LARGEST; 519 } 520 521 // GCCs __declspec(selectany) doesn't actually pick "any" but "same size as". 522 // Clang on the other hand picks "any". To be able to link two object files 523 // with a __declspec(selectany) declaration, one compiled with gcc and the 524 // other with clang, we merge them as proper "same size as" 525 if (config->mingw && ((selection == IMAGE_COMDAT_SELECT_ANY && 526 leaderSelection == IMAGE_COMDAT_SELECT_SAME_SIZE) || 527 (selection == IMAGE_COMDAT_SELECT_SAME_SIZE && 528 leaderSelection == IMAGE_COMDAT_SELECT_ANY))) { 529 leaderSelection = selection = IMAGE_COMDAT_SELECT_SAME_SIZE; 530 } 531 532 // Other than that, comdat selections must match. This is a bit more 533 // strict than link.exe which allows merging "any" and "largest" if "any" 534 // is the first symbol the linker sees, and it allows merging "largest" 535 // with everything (!) if "largest" is the first symbol the linker sees. 536 // Making this symmetric independent of which selection is seen first 537 // seems better though. 538 // (This behavior matches ModuleLinker::getComdatResult().) 539 if (selection != leaderSelection) { 540 log(("conflicting comdat type for " + toString(*leader) + ": " + 541 Twine((int)leaderSelection) + " in " + toString(leader->getFile()) + 542 " and " + Twine((int)selection) + " in " + toString(this)) 543 .str()); 544 symtab->reportDuplicate(leader, this); 545 return; 546 } 547 548 switch (selection) { 549 case IMAGE_COMDAT_SELECT_NODUPLICATES: 550 symtab->reportDuplicate(leader, this); 551 break; 552 553 case IMAGE_COMDAT_SELECT_ANY: 554 // Nothing to do. 555 break; 556 557 case IMAGE_COMDAT_SELECT_SAME_SIZE: 558 if (leaderChunk->getSize() != getSection(sym)->SizeOfRawData) { 559 if (!config->mingw) { 560 symtab->reportDuplicate(leader, this); 561 } else { 562 const coff_aux_section_definition *leaderDef = findSectionDef( 563 leaderChunk->file->getCOFFObj(), leaderChunk->getSectionNumber()); 564 if (!leaderDef || leaderDef->Length != def->Length) 565 symtab->reportDuplicate(leader, this); 566 } 567 } 568 break; 569 570 case IMAGE_COMDAT_SELECT_EXACT_MATCH: { 571 SectionChunk newChunk(this, getSection(sym)); 572 // link.exe only compares section contents here and doesn't complain 573 // if the two comdat sections have e.g. different alignment. 574 // Match that. 575 if (leaderChunk->getContents() != newChunk.getContents()) 576 symtab->reportDuplicate(leader, this, &newChunk, sym.getValue()); 577 break; 578 } 579 580 case IMAGE_COMDAT_SELECT_ASSOCIATIVE: 581 // createDefined() is never called for IMAGE_COMDAT_SELECT_ASSOCIATIVE. 582 // (This means lld-link doesn't produce duplicate symbol errors for 583 // associative comdats while link.exe does, but associate comdats 584 // are never extern in practice.) 585 llvm_unreachable("createDefined not called for associative comdats"); 586 587 case IMAGE_COMDAT_SELECT_LARGEST: 588 if (leaderChunk->getSize() < getSection(sym)->SizeOfRawData) { 589 // Replace the existing comdat symbol with the new one. 590 StringRef name = check(coffObj->getSymbolName(sym)); 591 // FIXME: This is incorrect: With /opt:noref, the previous sections 592 // make it into the final executable as well. Correct handling would 593 // be to undo reading of the whole old section that's being replaced, 594 // or doing one pass that determines what the final largest comdat 595 // is for all IMAGE_COMDAT_SELECT_LARGEST comdats and then reading 596 // only the largest one. 597 replaceSymbol<DefinedRegular>(leader, this, name, /*IsCOMDAT*/ true, 598 /*IsExternal*/ true, sym.getGeneric(), 599 nullptr); 600 prevailing = true; 601 } 602 break; 603 604 case IMAGE_COMDAT_SELECT_NEWEST: 605 llvm_unreachable("should have been rejected earlier"); 606 } 607 } 608 609 Optional<Symbol *> ObjFile::createDefined( 610 COFFSymbolRef sym, 611 std::vector<const coff_aux_section_definition *> &comdatDefs, 612 bool &prevailing) { 613 prevailing = false; 614 auto getName = [&]() { return check(coffObj->getSymbolName(sym)); }; 615 616 if (sym.isCommon()) { 617 auto *c = make<CommonChunk>(sym); 618 chunks.push_back(c); 619 return symtab->addCommon(this, getName(), sym.getValue(), sym.getGeneric(), 620 c); 621 } 622 623 if (sym.isAbsolute()) { 624 StringRef name = getName(); 625 626 if (name == "@feat.00") 627 feat00Flags = sym.getValue(); 628 // Skip special symbols. 629 if (ignoredSymbolName(name)) 630 return nullptr; 631 632 if (sym.isExternal()) 633 return symtab->addAbsolute(name, sym); 634 return make<DefinedAbsolute>(name, sym); 635 } 636 637 int32_t sectionNumber = sym.getSectionNumber(); 638 if (sectionNumber == llvm::COFF::IMAGE_SYM_DEBUG) 639 return nullptr; 640 641 if (llvm::COFF::isReservedSectionNumber(sectionNumber)) 642 fatal(toString(this) + ": " + getName() + 643 " should not refer to special section " + Twine(sectionNumber)); 644 645 if ((uint32_t)sectionNumber >= sparseChunks.size()) 646 fatal(toString(this) + ": " + getName() + 647 " should not refer to non-existent section " + Twine(sectionNumber)); 648 649 // Comdat handling. 650 // A comdat symbol consists of two symbol table entries. 651 // The first symbol entry has the name of the section (e.g. .text), fixed 652 // values for the other fields, and one auxiliary record. 653 // The second symbol entry has the name of the comdat symbol, called the 654 // "comdat leader". 655 // When this function is called for the first symbol entry of a comdat, 656 // it sets comdatDefs and returns None, and when it's called for the second 657 // symbol entry it reads comdatDefs and then sets it back to nullptr. 658 659 // Handle comdat leader. 660 if (const coff_aux_section_definition *def = comdatDefs[sectionNumber]) { 661 comdatDefs[sectionNumber] = nullptr; 662 DefinedRegular *leader; 663 664 if (sym.isExternal()) { 665 std::tie(leader, prevailing) = 666 symtab->addComdat(this, getName(), sym.getGeneric()); 667 } else { 668 leader = make<DefinedRegular>(this, /*Name*/ "", /*IsCOMDAT*/ false, 669 /*IsExternal*/ false, sym.getGeneric()); 670 prevailing = true; 671 } 672 673 if (def->Selection < (int)IMAGE_COMDAT_SELECT_NODUPLICATES || 674 // Intentionally ends at IMAGE_COMDAT_SELECT_LARGEST: link.exe 675 // doesn't understand IMAGE_COMDAT_SELECT_NEWEST either. 676 def->Selection > (int)IMAGE_COMDAT_SELECT_LARGEST) { 677 fatal("unknown comdat type " + std::to_string((int)def->Selection) + 678 " for " + getName() + " in " + toString(this)); 679 } 680 COMDATType selection = (COMDATType)def->Selection; 681 682 if (leader->isCOMDAT) 683 handleComdatSelection(sym, selection, prevailing, leader, def); 684 685 if (prevailing) { 686 SectionChunk *c = readSection(sectionNumber, def, getName()); 687 sparseChunks[sectionNumber] = c; 688 c->sym = cast<DefinedRegular>(leader); 689 c->selection = selection; 690 cast<DefinedRegular>(leader)->data = &c->repl; 691 } else { 692 sparseChunks[sectionNumber] = nullptr; 693 } 694 return leader; 695 } 696 697 // Prepare to handle the comdat leader symbol by setting the section's 698 // ComdatDefs pointer if we encounter a non-associative comdat. 699 if (sparseChunks[sectionNumber] == pendingComdat) { 700 if (const coff_aux_section_definition *def = sym.getSectionDefinition()) { 701 if (def->Selection != IMAGE_COMDAT_SELECT_ASSOCIATIVE) 702 comdatDefs[sectionNumber] = def; 703 } 704 return None; 705 } 706 707 return createRegular(sym); 708 } 709 710 MachineTypes ObjFile::getMachineType() { 711 if (coffObj) 712 return static_cast<MachineTypes>(coffObj->getMachine()); 713 return IMAGE_FILE_MACHINE_UNKNOWN; 714 } 715 716 ArrayRef<uint8_t> ObjFile::getDebugSection(StringRef secName) { 717 if (SectionChunk *sec = SectionChunk::findByName(debugChunks, secName)) 718 return sec->consumeDebugMagic(); 719 return {}; 720 } 721 722 // OBJ files systematically store critical information in a .debug$S stream, 723 // even if the TU was compiled with no debug info. At least two records are 724 // always there. S_OBJNAME stores a 32-bit signature, which is loaded into the 725 // PCHSignature member. S_COMPILE3 stores compile-time cmd-line flags. This is 726 // currently used to initialize the hotPatchable member. 727 void ObjFile::initializeFlags() { 728 ArrayRef<uint8_t> data = getDebugSection(".debug$S"); 729 if (data.empty()) 730 return; 731 732 DebugSubsectionArray subsections; 733 734 BinaryStreamReader reader(data, support::little); 735 ExitOnError exitOnErr; 736 exitOnErr(reader.readArray(subsections, data.size())); 737 738 for (const DebugSubsectionRecord &ss : subsections) { 739 if (ss.kind() != DebugSubsectionKind::Symbols) 740 continue; 741 742 unsigned offset = 0; 743 744 // Only parse the first two records. We are only looking for S_OBJNAME 745 // and S_COMPILE3, and they usually appear at the beginning of the 746 // stream. 747 for (unsigned i = 0; i < 2; ++i) { 748 Expected<CVSymbol> sym = readSymbolFromStream(ss.getRecordData(), offset); 749 if (!sym) { 750 consumeError(sym.takeError()); 751 return; 752 } 753 if (sym->kind() == SymbolKind::S_COMPILE3) { 754 auto cs = 755 cantFail(SymbolDeserializer::deserializeAs<Compile3Sym>(sym.get())); 756 hotPatchable = 757 (cs.Flags & CompileSym3Flags::HotPatch) != CompileSym3Flags::None; 758 } 759 if (sym->kind() == SymbolKind::S_OBJNAME) { 760 auto objName = cantFail(SymbolDeserializer::deserializeAs<ObjNameSym>( 761 sym.get())); 762 pchSignature = objName.Signature; 763 } 764 offset += sym->length(); 765 } 766 } 767 } 768 769 // Depending on the compilation flags, OBJs can refer to external files, 770 // necessary to merge this OBJ into the final PDB. We currently support two 771 // types of external files: Precomp/PCH OBJs, when compiling with /Yc and /Yu. 772 // And PDB type servers, when compiling with /Zi. This function extracts these 773 // dependencies and makes them available as a TpiSource interface (see 774 // DebugTypes.h). Both cases only happen with cl.exe: clang-cl produces regular 775 // output even with /Yc and /Yu and with /Zi. 776 void ObjFile::initializeDependencies() { 777 if (!config->debug) 778 return; 779 780 bool isPCH = false; 781 782 ArrayRef<uint8_t> data = getDebugSection(".debug$P"); 783 if (!data.empty()) 784 isPCH = true; 785 else 786 data = getDebugSection(".debug$T"); 787 788 // Don't make a TpiSource for objects with no debug info. If the object has 789 // symbols but no types, make a plain, empty TpiSource anyway, because it 790 // simplifies adding the symbols later. 791 if (data.empty()) { 792 if (!debugChunks.empty()) 793 debugTypesObj = makeTpiSource(this); 794 return; 795 } 796 797 // Get the first type record. It will indicate if this object uses a type 798 // server (/Zi) or a PCH file (/Yu). 799 CVTypeArray types; 800 BinaryStreamReader reader(data, support::little); 801 cantFail(reader.readArray(types, reader.getLength())); 802 CVTypeArray::Iterator firstType = types.begin(); 803 if (firstType == types.end()) 804 return; 805 806 // Remember the .debug$T or .debug$P section. 807 debugTypes = data; 808 809 // This object file is a PCH file that others will depend on. 810 if (isPCH) { 811 debugTypesObj = makePrecompSource(this); 812 return; 813 } 814 815 // This object file was compiled with /Zi. Enqueue the PDB dependency. 816 if (firstType->kind() == LF_TYPESERVER2) { 817 TypeServer2Record ts = cantFail( 818 TypeDeserializer::deserializeAs<TypeServer2Record>(firstType->data())); 819 debugTypesObj = makeUseTypeServerSource(this, ts); 820 PDBInputFile::enqueue(ts.getName(), this); 821 return; 822 } 823 824 // This object was compiled with /Yu. It uses types from another object file 825 // with a matching signature. 826 if (firstType->kind() == LF_PRECOMP) { 827 PrecompRecord precomp = cantFail( 828 TypeDeserializer::deserializeAs<PrecompRecord>(firstType->data())); 829 debugTypesObj = makeUsePrecompSource(this, precomp); 830 // Drop the LF_PRECOMP record from the input stream. 831 debugTypes = debugTypes.drop_front(firstType->RecordData.size()); 832 return; 833 } 834 835 // This is a plain old object file. 836 debugTypesObj = makeTpiSource(this); 837 } 838 839 // Make a PDB path assuming the PDB is in the same folder as the OBJ 840 static std::string getPdbBaseName(ObjFile *file, StringRef tSPath) { 841 StringRef localPath = 842 !file->parentName.empty() ? file->parentName : file->getName(); 843 SmallString<128> path = sys::path::parent_path(localPath); 844 845 // Currently, type server PDBs are only created by MSVC cl, which only runs 846 // on Windows, so we can assume type server paths are Windows style. 847 sys::path::append(path, 848 sys::path::filename(tSPath, sys::path::Style::windows)); 849 return std::string(path.str()); 850 } 851 852 // The casing of the PDB path stamped in the OBJ can differ from the actual path 853 // on disk. With this, we ensure to always use lowercase as a key for the 854 // PDBInputFile::instances map, at least on Windows. 855 static std::string normalizePdbPath(StringRef path) { 856 #if defined(_WIN32) 857 return path.lower(); 858 #else // LINUX 859 return std::string(path); 860 #endif 861 } 862 863 // If existing, return the actual PDB path on disk. 864 static Optional<std::string> findPdbPath(StringRef pdbPath, 865 ObjFile *dependentFile) { 866 // Ensure the file exists before anything else. In some cases, if the path 867 // points to a removable device, Driver::enqueuePath() would fail with an 868 // error (EAGAIN, "resource unavailable try again") which we want to skip 869 // silently. 870 if (llvm::sys::fs::exists(pdbPath)) 871 return normalizePdbPath(pdbPath); 872 std::string ret = getPdbBaseName(dependentFile, pdbPath); 873 if (llvm::sys::fs::exists(ret)) 874 return normalizePdbPath(ret); 875 return None; 876 } 877 878 PDBInputFile::PDBInputFile(MemoryBufferRef m) : InputFile(PDBKind, m) {} 879 880 PDBInputFile::~PDBInputFile() = default; 881 882 PDBInputFile *PDBInputFile::findFromRecordPath(StringRef path, 883 ObjFile *fromFile) { 884 auto p = findPdbPath(path.str(), fromFile); 885 if (!p) 886 return nullptr; 887 auto it = PDBInputFile::instances.find(*p); 888 if (it != PDBInputFile::instances.end()) 889 return it->second; 890 return nullptr; 891 } 892 893 void PDBInputFile::enqueue(StringRef path, ObjFile *fromFile) { 894 auto p = findPdbPath(path.str(), fromFile); 895 if (!p) 896 return; 897 auto it = PDBInputFile::instances.emplace(*p, nullptr); 898 if (!it.second) 899 return; // already scheduled for load 900 driver->enqueuePDB(*p); 901 } 902 903 void PDBInputFile::parse() { 904 PDBInputFile::instances[mb.getBufferIdentifier().str()] = this; 905 906 std::unique_ptr<pdb::IPDBSession> thisSession; 907 loadErr.emplace(pdb::NativeSession::createFromPdb( 908 MemoryBuffer::getMemBuffer(mb, false), thisSession)); 909 if (*loadErr) 910 return; // fail silently at this point - the error will be handled later, 911 // when merging the debug type stream 912 913 session.reset(static_cast<pdb::NativeSession *>(thisSession.release())); 914 915 pdb::PDBFile &pdbFile = session->getPDBFile(); 916 auto expectedInfo = pdbFile.getPDBInfoStream(); 917 // All PDB Files should have an Info stream. 918 if (!expectedInfo) { 919 loadErr.emplace(expectedInfo.takeError()); 920 return; 921 } 922 debugTypesObj = makeTypeServerSource(this); 923 } 924 925 // Used only for DWARF debug info, which is not common (except in MinGW 926 // environments). This returns an optional pair of file name and line 927 // number for where the variable was defined. 928 Optional<std::pair<StringRef, uint32_t>> 929 ObjFile::getVariableLocation(StringRef var) { 930 if (!dwarf) { 931 dwarf = make<DWARFCache>(DWARFContext::create(*getCOFFObj())); 932 if (!dwarf) 933 return None; 934 } 935 if (config->machine == I386) 936 var.consume_front("_"); 937 Optional<std::pair<std::string, unsigned>> ret = dwarf->getVariableLoc(var); 938 if (!ret) 939 return None; 940 return std::make_pair(saver.save(ret->first), ret->second); 941 } 942 943 // Used only for DWARF debug info, which is not common (except in MinGW 944 // environments). 945 Optional<DILineInfo> ObjFile::getDILineInfo(uint32_t offset, 946 uint32_t sectionIndex) { 947 if (!dwarf) { 948 dwarf = make<DWARFCache>(DWARFContext::create(*getCOFFObj())); 949 if (!dwarf) 950 return None; 951 } 952 953 return dwarf->getDILineInfo(offset, sectionIndex); 954 } 955 956 static StringRef ltrim1(StringRef s, const char *chars) { 957 if (!s.empty() && strchr(chars, s[0])) 958 return s.substr(1); 959 return s; 960 } 961 962 void ImportFile::parse() { 963 const char *buf = mb.getBufferStart(); 964 const auto *hdr = reinterpret_cast<const coff_import_header *>(buf); 965 966 // Check if the total size is valid. 967 if (mb.getBufferSize() != sizeof(*hdr) + hdr->SizeOfData) 968 fatal("broken import library"); 969 970 // Read names and create an __imp_ symbol. 971 StringRef name = saver.save(StringRef(buf + sizeof(*hdr))); 972 StringRef impName = saver.save("__imp_" + name); 973 const char *nameStart = buf + sizeof(coff_import_header) + name.size() + 1; 974 dllName = std::string(StringRef(nameStart)); 975 StringRef extName; 976 switch (hdr->getNameType()) { 977 case IMPORT_ORDINAL: 978 extName = ""; 979 break; 980 case IMPORT_NAME: 981 extName = name; 982 break; 983 case IMPORT_NAME_NOPREFIX: 984 extName = ltrim1(name, "?@_"); 985 break; 986 case IMPORT_NAME_UNDECORATE: 987 extName = ltrim1(name, "?@_"); 988 extName = extName.substr(0, extName.find('@')); 989 break; 990 } 991 992 this->hdr = hdr; 993 externalName = extName; 994 995 impSym = symtab->addImportData(impName, this); 996 // If this was a duplicate, we logged an error but may continue; 997 // in this case, impSym is nullptr. 998 if (!impSym) 999 return; 1000 1001 if (hdr->getType() == llvm::COFF::IMPORT_CONST) 1002 static_cast<void>(symtab->addImportData(name, this)); 1003 1004 // If type is function, we need to create a thunk which jump to an 1005 // address pointed by the __imp_ symbol. (This allows you to call 1006 // DLL functions just like regular non-DLL functions.) 1007 if (hdr->getType() == llvm::COFF::IMPORT_CODE) 1008 thunkSym = symtab->addImportThunk( 1009 name, cast_or_null<DefinedImportData>(impSym), hdr->Machine); 1010 } 1011 1012 BitcodeFile::BitcodeFile(MemoryBufferRef mb, StringRef archiveName, 1013 uint64_t offsetInArchive) 1014 : BitcodeFile(mb, archiveName, offsetInArchive, {}) {} 1015 1016 BitcodeFile::BitcodeFile(MemoryBufferRef mb, StringRef archiveName, 1017 uint64_t offsetInArchive, 1018 std::vector<Symbol *> &&symbols) 1019 : InputFile(BitcodeKind, mb), symbols(std::move(symbols)) { 1020 std::string path = mb.getBufferIdentifier().str(); 1021 if (config->thinLTOIndexOnly) 1022 path = replaceThinLTOSuffix(mb.getBufferIdentifier()); 1023 1024 // ThinLTO assumes that all MemoryBufferRefs given to it have a unique 1025 // name. If two archives define two members with the same name, this 1026 // causes a collision which result in only one of the objects being taken 1027 // into consideration at LTO time (which very likely causes undefined 1028 // symbols later in the link stage). So we append file offset to make 1029 // filename unique. 1030 MemoryBufferRef mbref( 1031 mb.getBuffer(), 1032 saver.save(archiveName.empty() ? path 1033 : archiveName + sys::path::filename(path) + 1034 utostr(offsetInArchive))); 1035 1036 obj = check(lto::InputFile::create(mbref)); 1037 } 1038 1039 BitcodeFile::~BitcodeFile() = default; 1040 1041 void BitcodeFile::parse() { 1042 std::vector<std::pair<Symbol *, bool>> comdat(obj->getComdatTable().size()); 1043 for (size_t i = 0; i != obj->getComdatTable().size(); ++i) 1044 // FIXME: lto::InputFile doesn't keep enough data to do correct comdat 1045 // selection handling. 1046 comdat[i] = symtab->addComdat(this, saver.save(obj->getComdatTable()[i])); 1047 for (const lto::InputFile::Symbol &objSym : obj->symbols()) { 1048 StringRef symName = saver.save(objSym.getName()); 1049 int comdatIndex = objSym.getComdatIndex(); 1050 Symbol *sym; 1051 if (objSym.isUndefined()) { 1052 sym = symtab->addUndefined(symName, this, false); 1053 } else if (objSym.isCommon()) { 1054 sym = symtab->addCommon(this, symName, objSym.getCommonSize()); 1055 } else if (objSym.isWeak() && objSym.isIndirect()) { 1056 // Weak external. 1057 sym = symtab->addUndefined(symName, this, true); 1058 std::string fallback = std::string(objSym.getCOFFWeakExternalFallback()); 1059 Symbol *alias = symtab->addUndefined(saver.save(fallback)); 1060 checkAndSetWeakAlias(symtab, this, sym, alias); 1061 } else if (comdatIndex != -1) { 1062 if (symName == obj->getComdatTable()[comdatIndex]) 1063 sym = comdat[comdatIndex].first; 1064 else if (comdat[comdatIndex].second) 1065 sym = symtab->addRegular(this, symName); 1066 else 1067 sym = symtab->addUndefined(symName, this, false); 1068 } else { 1069 sym = symtab->addRegular(this, symName); 1070 } 1071 symbols.push_back(sym); 1072 if (objSym.isUsed()) 1073 config->gcroot.push_back(sym); 1074 } 1075 directives = obj->getCOFFLinkerOpts(); 1076 } 1077 1078 MachineTypes BitcodeFile::getMachineType() { 1079 switch (Triple(obj->getTargetTriple()).getArch()) { 1080 case Triple::x86_64: 1081 return AMD64; 1082 case Triple::x86: 1083 return I386; 1084 case Triple::arm: 1085 return ARMNT; 1086 case Triple::aarch64: 1087 return ARM64; 1088 default: 1089 return IMAGE_FILE_MACHINE_UNKNOWN; 1090 } 1091 } 1092 1093 std::string lld::coff::replaceThinLTOSuffix(StringRef path) { 1094 StringRef suffix = config->thinLTOObjectSuffixReplace.first; 1095 StringRef repl = config->thinLTOObjectSuffixReplace.second; 1096 1097 if (path.consume_back(suffix)) 1098 return (path + repl).str(); 1099 return std::string(path); 1100 } 1101