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