1 //===- Driver.cpp ---------------------------------------------------------===// 2 // 3 // The LLVM Linker 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 10 #include "Driver.h" 11 #include "Config.h" 12 #include "InputFiles.h" 13 #include "MinGW.h" 14 #include "SymbolTable.h" 15 #include "Symbols.h" 16 #include "Writer.h" 17 #include "lld/Common/Driver.h" 18 #include "lld/Common/ErrorHandler.h" 19 #include "lld/Common/Memory.h" 20 #include "lld/Common/Version.h" 21 #include "llvm/ADT/Optional.h" 22 #include "llvm/ADT/StringSwitch.h" 23 #include "llvm/BinaryFormat/Magic.h" 24 #include "llvm/Object/ArchiveWriter.h" 25 #include "llvm/Object/COFFImportFile.h" 26 #include "llvm/Object/COFFModuleDefinition.h" 27 #include "llvm/Option/Arg.h" 28 #include "llvm/Option/ArgList.h" 29 #include "llvm/Option/Option.h" 30 #include "llvm/Support/Debug.h" 31 #include "llvm/Support/Path.h" 32 #include "llvm/Support/Process.h" 33 #include "llvm/Support/TarWriter.h" 34 #include "llvm/Support/TargetSelect.h" 35 #include "llvm/Support/raw_ostream.h" 36 #include "llvm/ToolDrivers/llvm-lib/LibDriver.h" 37 #include <algorithm> 38 #include <memory> 39 40 #include <future> 41 42 using namespace llvm; 43 using namespace llvm::object; 44 using namespace llvm::COFF; 45 using llvm::sys::Process; 46 47 namespace lld { 48 namespace coff { 49 50 Configuration *Config; 51 LinkerDriver *Driver; 52 53 bool link(ArrayRef<const char *> Args, bool CanExitEarly, raw_ostream &Diag) { 54 errorHandler().LogName = Args[0]; 55 errorHandler().ErrorOS = &Diag; 56 errorHandler().ColorDiagnostics = Diag.has_colors(); 57 errorHandler().ErrorLimitExceededMsg = 58 "too many errors emitted, stopping now" 59 " (use /ERRORLIMIT:0 to see all errors)"; 60 errorHandler().ExitEarly = CanExitEarly; 61 Config = make<Configuration>(); 62 Config->Argv = {Args.begin(), Args.end()}; 63 Config->CanExitEarly = CanExitEarly; 64 65 Symtab = make<SymbolTable>(); 66 67 Driver = make<LinkerDriver>(); 68 Driver->link(Args); 69 70 // Call exit() if we can to avoid calling destructors. 71 if (CanExitEarly) 72 exitLld(errorCount() ? 1 : 0); 73 74 freeArena(); 75 return !errorCount(); 76 } 77 78 // Drop directory components and replace extension with ".exe" or ".dll". 79 static std::string getOutputPath(StringRef Path) { 80 auto P = Path.find_last_of("\\/"); 81 StringRef S = (P == StringRef::npos) ? Path : Path.substr(P + 1); 82 const char* E = Config->DLL ? ".dll" : ".exe"; 83 return (S.substr(0, S.rfind('.')) + E).str(); 84 } 85 86 // ErrorOr is not default constructible, so it cannot be used as the type 87 // parameter of a future. 88 // FIXME: We could open the file in createFutureForFile and avoid needing to 89 // return an error here, but for the moment that would cost us a file descriptor 90 // (a limited resource on Windows) for the duration that the future is pending. 91 typedef std::pair<std::unique_ptr<MemoryBuffer>, std::error_code> MBErrPair; 92 93 // Create a std::future that opens and maps a file using the best strategy for 94 // the host platform. 95 static std::future<MBErrPair> createFutureForFile(std::string Path) { 96 #if LLVM_ON_WIN32 97 // On Windows, file I/O is relatively slow so it is best to do this 98 // asynchronously. 99 auto Strategy = std::launch::async; 100 #else 101 auto Strategy = std::launch::deferred; 102 #endif 103 return std::async(Strategy, [=]() { 104 auto MBOrErr = MemoryBuffer::getFile(Path); 105 if (!MBOrErr) 106 return MBErrPair{nullptr, MBOrErr.getError()}; 107 return MBErrPair{std::move(*MBOrErr), std::error_code()}; 108 }); 109 } 110 111 MemoryBufferRef LinkerDriver::takeBuffer(std::unique_ptr<MemoryBuffer> MB) { 112 MemoryBufferRef MBRef = *MB; 113 make<std::unique_ptr<MemoryBuffer>>(std::move(MB)); // take ownership 114 115 if (Driver->Tar) 116 Driver->Tar->append(relativeToRoot(MBRef.getBufferIdentifier()), 117 MBRef.getBuffer()); 118 return MBRef; 119 } 120 121 void LinkerDriver::addBuffer(std::unique_ptr<MemoryBuffer> MB, 122 bool WholeArchive) { 123 MemoryBufferRef MBRef = takeBuffer(std::move(MB)); 124 FilePaths.push_back(MBRef.getBufferIdentifier()); 125 126 // File type is detected by contents, not by file extension. 127 switch (identify_magic(MBRef.getBuffer())) { 128 case file_magic::windows_resource: 129 Resources.push_back(MBRef); 130 break; 131 132 case file_magic::archive: 133 if (WholeArchive) { 134 std::unique_ptr<Archive> File = 135 CHECK(Archive::create(MBRef), 136 MBRef.getBufferIdentifier() + ": failed to parse archive"); 137 138 for (MemoryBufferRef M : getArchiveMembers(File.get())) 139 addArchiveBuffer(M, "<whole-archive>", MBRef.getBufferIdentifier()); 140 return; 141 } 142 Symtab->addFile(make<ArchiveFile>(MBRef)); 143 break; 144 145 case file_magic::bitcode: 146 Symtab->addFile(make<BitcodeFile>(MBRef)); 147 break; 148 149 case file_magic::coff_cl_gl_object: 150 error(MBRef.getBufferIdentifier() + ": is not a native COFF file. " 151 "Recompile without /GL"); 152 break; 153 154 default: 155 Symtab->addFile(make<ObjFile>(MBRef)); 156 break; 157 } 158 } 159 160 void LinkerDriver::enqueuePath(StringRef Path, bool WholeArchive) { 161 auto Future = 162 std::make_shared<std::future<MBErrPair>>(createFutureForFile(Path)); 163 std::string PathStr = Path; 164 enqueueTask([=]() { 165 auto MBOrErr = Future->get(); 166 if (MBOrErr.second) 167 error("could not open " + PathStr + ": " + MBOrErr.second.message()); 168 else 169 Driver->addBuffer(std::move(MBOrErr.first), WholeArchive); 170 }); 171 } 172 173 void LinkerDriver::addArchiveBuffer(MemoryBufferRef MB, StringRef SymName, 174 StringRef ParentName) { 175 file_magic Magic = identify_magic(MB.getBuffer()); 176 if (Magic == file_magic::coff_import_library) { 177 Symtab->addFile(make<ImportFile>(MB)); 178 return; 179 } 180 181 InputFile *Obj; 182 if (Magic == file_magic::coff_object) { 183 Obj = make<ObjFile>(MB); 184 } else if (Magic == file_magic::bitcode) { 185 Obj = make<BitcodeFile>(MB); 186 } else { 187 error("unknown file type: " + MB.getBufferIdentifier()); 188 return; 189 } 190 191 Obj->ParentName = ParentName; 192 Symtab->addFile(Obj); 193 log("Loaded " + toString(Obj) + " for " + SymName); 194 } 195 196 void LinkerDriver::enqueueArchiveMember(const Archive::Child &C, 197 StringRef SymName, 198 StringRef ParentName) { 199 if (!C.getParent()->isThin()) { 200 MemoryBufferRef MB = CHECK( 201 C.getMemoryBufferRef(), 202 "could not get the buffer for the member defining symbol " + SymName); 203 enqueueTask([=]() { Driver->addArchiveBuffer(MB, SymName, ParentName); }); 204 return; 205 } 206 207 auto Future = std::make_shared<std::future<MBErrPair>>(createFutureForFile( 208 CHECK(C.getFullName(), 209 "could not get the filename for the member defining symbol " + 210 SymName))); 211 enqueueTask([=]() { 212 auto MBOrErr = Future->get(); 213 if (MBOrErr.second) 214 fatal("could not get the buffer for the member defining " + SymName + 215 ": " + MBOrErr.second.message()); 216 Driver->addArchiveBuffer(takeBuffer(std::move(MBOrErr.first)), SymName, 217 ParentName); 218 }); 219 } 220 221 static bool isDecorated(StringRef Sym) { 222 return Sym.startswith("@") || Sym.contains("@@") || Sym.startswith("?") || 223 (!Config->MinGW && Sym.contains('@')); 224 } 225 226 // Parses .drectve section contents and returns a list of files 227 // specified by /defaultlib. 228 void LinkerDriver::parseDirectives(StringRef S) { 229 ArgParser Parser; 230 // .drectve is always tokenized using Windows shell rules. 231 opt::InputArgList Args = Parser.parseDirectives(S); 232 233 for (auto *Arg : Args) { 234 switch (Arg->getOption().getUnaliasedOption().getID()) { 235 case OPT_aligncomm: 236 parseAligncomm(Arg->getValue()); 237 break; 238 case OPT_alternatename: 239 parseAlternateName(Arg->getValue()); 240 break; 241 case OPT_defaultlib: 242 if (Optional<StringRef> Path = findLib(Arg->getValue())) 243 enqueuePath(*Path, false); 244 break; 245 case OPT_entry: 246 Config->Entry = addUndefined(mangle(Arg->getValue())); 247 break; 248 case OPT_export: { 249 // If a common header file contains dllexported function 250 // declarations, many object files may end up with having the 251 // same /EXPORT options. In order to save cost of parsing them, 252 // we dedup them first. 253 if (!DirectivesExports.insert(Arg->getValue()).second) 254 break; 255 256 Export E = parseExport(Arg->getValue()); 257 if (Config->Machine == I386 && Config->MinGW) { 258 if (!isDecorated(E.Name)) 259 E.Name = Saver.save("_" + E.Name); 260 if (!E.ExtName.empty() && !isDecorated(E.ExtName)) 261 E.ExtName = Saver.save("_" + E.ExtName); 262 } 263 E.Directives = true; 264 Config->Exports.push_back(E); 265 break; 266 } 267 case OPT_failifmismatch: 268 checkFailIfMismatch(Arg->getValue()); 269 break; 270 case OPT_incl: 271 addUndefined(Arg->getValue()); 272 break; 273 case OPT_merge: 274 parseMerge(Arg->getValue()); 275 break; 276 case OPT_nodefaultlib: 277 Config->NoDefaultLibs.insert(doFindLib(Arg->getValue())); 278 break; 279 case OPT_section: 280 parseSection(Arg->getValue()); 281 break; 282 case OPT_subsystem: 283 parseSubsystem(Arg->getValue(), &Config->Subsystem, 284 &Config->MajorOSVersion, &Config->MinorOSVersion); 285 break; 286 case OPT_editandcontinue: 287 case OPT_fastfail: 288 case OPT_guardsym: 289 case OPT_natvis: 290 case OPT_throwingnew: 291 break; 292 default: 293 error(Arg->getSpelling() + " is not allowed in .drectve"); 294 } 295 } 296 } 297 298 // Find file from search paths. You can omit ".obj", this function takes 299 // care of that. Note that the returned path is not guaranteed to exist. 300 StringRef LinkerDriver::doFindFile(StringRef Filename) { 301 bool HasPathSep = (Filename.find_first_of("/\\") != StringRef::npos); 302 if (HasPathSep) 303 return Filename; 304 bool HasExt = Filename.contains('.'); 305 for (StringRef Dir : SearchPaths) { 306 SmallString<128> Path = Dir; 307 sys::path::append(Path, Filename); 308 if (sys::fs::exists(Path.str())) 309 return Saver.save(Path.str()); 310 if (!HasExt) { 311 Path.append(".obj"); 312 if (sys::fs::exists(Path.str())) 313 return Saver.save(Path.str()); 314 } 315 } 316 return Filename; 317 } 318 319 // Resolves a file path. This never returns the same path 320 // (in that case, it returns None). 321 Optional<StringRef> LinkerDriver::findFile(StringRef Filename) { 322 StringRef Path = doFindFile(Filename); 323 bool Seen = !VisitedFiles.insert(Path.lower()).second; 324 if (Seen) 325 return None; 326 if (Path.endswith_lower(".lib")) 327 VisitedLibs.insert(sys::path::filename(Path)); 328 return Path; 329 } 330 331 // Find library file from search path. 332 StringRef LinkerDriver::doFindLib(StringRef Filename) { 333 // Add ".lib" to Filename if that has no file extension. 334 bool HasExt = Filename.contains('.'); 335 if (!HasExt) 336 Filename = Saver.save(Filename + ".lib"); 337 return doFindFile(Filename); 338 } 339 340 // Resolves a library path. /nodefaultlib options are taken into 341 // consideration. This never returns the same path (in that case, 342 // it returns None). 343 Optional<StringRef> LinkerDriver::findLib(StringRef Filename) { 344 if (Config->NoDefaultLibAll) 345 return None; 346 if (!VisitedLibs.insert(Filename.lower()).second) 347 return None; 348 StringRef Path = doFindLib(Filename); 349 if (Config->NoDefaultLibs.count(Path)) 350 return None; 351 if (!VisitedFiles.insert(Path.lower()).second) 352 return None; 353 return Path; 354 } 355 356 // Parses LIB environment which contains a list of search paths. 357 void LinkerDriver::addLibSearchPaths() { 358 Optional<std::string> EnvOpt = Process::GetEnv("LIB"); 359 if (!EnvOpt.hasValue()) 360 return; 361 StringRef Env = Saver.save(*EnvOpt); 362 while (!Env.empty()) { 363 StringRef Path; 364 std::tie(Path, Env) = Env.split(';'); 365 SearchPaths.push_back(Path); 366 } 367 } 368 369 Symbol *LinkerDriver::addUndefined(StringRef Name) { 370 Symbol *B = Symtab->addUndefined(Name); 371 if (!B->IsGCRoot) { 372 B->IsGCRoot = true; 373 Config->GCRoot.push_back(B); 374 } 375 return B; 376 } 377 378 // Symbol names are mangled by appending "_" prefix on x86. 379 StringRef LinkerDriver::mangle(StringRef Sym) { 380 assert(Config->Machine != IMAGE_FILE_MACHINE_UNKNOWN); 381 if (Config->Machine == I386) 382 return Saver.save("_" + Sym); 383 return Sym; 384 } 385 386 // Windows specific -- find default entry point name. 387 StringRef LinkerDriver::findDefaultEntry() { 388 // User-defined main functions and their corresponding entry points. 389 static const char *Entries[][2] = { 390 {"main", "mainCRTStartup"}, 391 {"wmain", "wmainCRTStartup"}, 392 {"WinMain", "WinMainCRTStartup"}, 393 {"wWinMain", "wWinMainCRTStartup"}, 394 }; 395 for (auto E : Entries) { 396 StringRef Entry = Symtab->findMangle(mangle(E[0])); 397 if (!Entry.empty() && !isa<Undefined>(Symtab->find(Entry))) 398 return mangle(E[1]); 399 } 400 return ""; 401 } 402 403 WindowsSubsystem LinkerDriver::inferSubsystem() { 404 if (Config->DLL) 405 return IMAGE_SUBSYSTEM_WINDOWS_GUI; 406 if (Symtab->findUnderscore("main") || Symtab->findUnderscore("wmain")) 407 return IMAGE_SUBSYSTEM_WINDOWS_CUI; 408 if (Symtab->findUnderscore("WinMain") || Symtab->findUnderscore("wWinMain")) 409 return IMAGE_SUBSYSTEM_WINDOWS_GUI; 410 return IMAGE_SUBSYSTEM_UNKNOWN; 411 } 412 413 static uint64_t getDefaultImageBase() { 414 if (Config->is64()) 415 return Config->DLL ? 0x180000000 : 0x140000000; 416 return Config->DLL ? 0x10000000 : 0x400000; 417 } 418 419 static std::string createResponseFile(const opt::InputArgList &Args, 420 ArrayRef<StringRef> FilePaths, 421 ArrayRef<StringRef> SearchPaths) { 422 SmallString<0> Data; 423 raw_svector_ostream OS(Data); 424 425 for (auto *Arg : Args) { 426 switch (Arg->getOption().getID()) { 427 case OPT_linkrepro: 428 case OPT_INPUT: 429 case OPT_defaultlib: 430 case OPT_libpath: 431 case OPT_manifest: 432 case OPT_manifest_colon: 433 case OPT_manifestdependency: 434 case OPT_manifestfile: 435 case OPT_manifestinput: 436 case OPT_manifestuac: 437 break; 438 default: 439 OS << toString(*Arg) << "\n"; 440 } 441 } 442 443 for (StringRef Path : SearchPaths) { 444 std::string RelPath = relativeToRoot(Path); 445 OS << "/libpath:" << quote(RelPath) << "\n"; 446 } 447 448 for (StringRef Path : FilePaths) 449 OS << quote(relativeToRoot(Path)) << "\n"; 450 451 return Data.str(); 452 } 453 454 static unsigned getDefaultDebugType(const opt::InputArgList &Args) { 455 unsigned DebugTypes = static_cast<unsigned>(DebugType::CV); 456 if (Args.hasArg(OPT_driver)) 457 DebugTypes |= static_cast<unsigned>(DebugType::PData); 458 if (Args.hasArg(OPT_profile)) 459 DebugTypes |= static_cast<unsigned>(DebugType::Fixup); 460 return DebugTypes; 461 } 462 463 static unsigned parseDebugType(StringRef Arg) { 464 SmallVector<StringRef, 3> Types; 465 Arg.split(Types, ',', /*KeepEmpty=*/false); 466 467 unsigned DebugTypes = static_cast<unsigned>(DebugType::None); 468 for (StringRef Type : Types) 469 DebugTypes |= StringSwitch<unsigned>(Type.lower()) 470 .Case("cv", static_cast<unsigned>(DebugType::CV)) 471 .Case("pdata", static_cast<unsigned>(DebugType::PData)) 472 .Case("fixup", static_cast<unsigned>(DebugType::Fixup)) 473 .Default(0); 474 return DebugTypes; 475 } 476 477 static std::string getMapFile(const opt::InputArgList &Args) { 478 auto *Arg = Args.getLastArg(OPT_lldmap, OPT_lldmap_file); 479 if (!Arg) 480 return ""; 481 if (Arg->getOption().getID() == OPT_lldmap_file) 482 return Arg->getValue(); 483 484 assert(Arg->getOption().getID() == OPT_lldmap); 485 StringRef OutFile = Config->OutputFile; 486 return (OutFile.substr(0, OutFile.rfind('.')) + ".map").str(); 487 } 488 489 static std::string getImplibPath() { 490 if (!Config->Implib.empty()) 491 return Config->Implib; 492 SmallString<128> Out = StringRef(Config->OutputFile); 493 sys::path::replace_extension(Out, ".lib"); 494 return Out.str(); 495 } 496 497 // 498 // The import name is caculated as the following: 499 // 500 // | LIBRARY w/ ext | LIBRARY w/o ext | no LIBRARY 501 // -----+----------------+---------------------+------------------ 502 // LINK | {value} | {value}.{.dll/.exe} | {output name} 503 // LIB | {value} | {value}.dll | {output name}.dll 504 // 505 static std::string getImportName(bool AsLib) { 506 SmallString<128> Out; 507 508 if (Config->ImportName.empty()) { 509 Out.assign(sys::path::filename(Config->OutputFile)); 510 if (AsLib) 511 sys::path::replace_extension(Out, ".dll"); 512 } else { 513 Out.assign(Config->ImportName); 514 if (!sys::path::has_extension(Out)) 515 sys::path::replace_extension(Out, 516 (Config->DLL || AsLib) ? ".dll" : ".exe"); 517 } 518 519 return Out.str(); 520 } 521 522 static void createImportLibrary(bool AsLib) { 523 std::vector<COFFShortExport> Exports; 524 for (Export &E1 : Config->Exports) { 525 COFFShortExport E2; 526 E2.Name = E1.Name; 527 E2.SymbolName = E1.SymbolName; 528 E2.ExtName = E1.ExtName; 529 E2.Ordinal = E1.Ordinal; 530 E2.Noname = E1.Noname; 531 E2.Data = E1.Data; 532 E2.Private = E1.Private; 533 E2.Constant = E1.Constant; 534 Exports.push_back(E2); 535 } 536 537 auto E = writeImportLibrary(getImportName(AsLib), getImplibPath(), Exports, 538 Config->Machine, false); 539 handleAllErrors(std::move(E), 540 [&](ErrorInfoBase &EIB) { error(EIB.message()); }); 541 } 542 543 static void parseModuleDefs(StringRef Path) { 544 std::unique_ptr<MemoryBuffer> MB = CHECK( 545 MemoryBuffer::getFile(Path, -1, false, true), "could not open " + Path); 546 COFFModuleDefinition M = check(parseCOFFModuleDefinition( 547 MB->getMemBufferRef(), Config->Machine, Config->MinGW)); 548 549 if (Config->OutputFile.empty()) 550 Config->OutputFile = Saver.save(M.OutputFile); 551 Config->ImportName = Saver.save(M.ImportName); 552 if (M.ImageBase) 553 Config->ImageBase = M.ImageBase; 554 if (M.StackReserve) 555 Config->StackReserve = M.StackReserve; 556 if (M.StackCommit) 557 Config->StackCommit = M.StackCommit; 558 if (M.HeapReserve) 559 Config->HeapReserve = M.HeapReserve; 560 if (M.HeapCommit) 561 Config->HeapCommit = M.HeapCommit; 562 if (M.MajorImageVersion) 563 Config->MajorImageVersion = M.MajorImageVersion; 564 if (M.MinorImageVersion) 565 Config->MinorImageVersion = M.MinorImageVersion; 566 if (M.MajorOSVersion) 567 Config->MajorOSVersion = M.MajorOSVersion; 568 if (M.MinorOSVersion) 569 Config->MinorOSVersion = M.MinorOSVersion; 570 571 for (COFFShortExport E1 : M.Exports) { 572 Export E2; 573 E2.Name = Saver.save(E1.Name); 574 if (E1.isWeak()) 575 E2.ExtName = Saver.save(E1.ExtName); 576 E2.Ordinal = E1.Ordinal; 577 E2.Noname = E1.Noname; 578 E2.Data = E1.Data; 579 E2.Private = E1.Private; 580 E2.Constant = E1.Constant; 581 Config->Exports.push_back(E2); 582 } 583 } 584 585 // A helper function for filterBitcodeFiles. 586 static bool needsRebuilding(MemoryBufferRef MB) { 587 // The MSVC linker doesn't support thin archives, so if it's a thin 588 // archive, we always need to rebuild it. 589 std::unique_ptr<Archive> File = 590 CHECK(Archive::create(MB), "Failed to read " + MB.getBufferIdentifier()); 591 if (File->isThin()) 592 return true; 593 594 // Returns true if the archive contains at least one bitcode file. 595 for (MemoryBufferRef Member : getArchiveMembers(File.get())) 596 if (identify_magic(Member.getBuffer()) == file_magic::bitcode) 597 return true; 598 return false; 599 } 600 601 // Opens a given path as an archive file and removes bitcode files 602 // from them if exists. This function is to appease the MSVC linker as 603 // their linker doesn't like archive files containing non-native 604 // object files. 605 // 606 // If a given archive doesn't contain bitcode files, the archive path 607 // is returned as-is. Otherwise, a new temporary file is created and 608 // its path is returned. 609 static Optional<std::string> 610 filterBitcodeFiles(StringRef Path, std::vector<std::string> &TemporaryFiles) { 611 std::unique_ptr<MemoryBuffer> MB = CHECK( 612 MemoryBuffer::getFile(Path, -1, false, true), "could not open " + Path); 613 MemoryBufferRef MBRef = MB->getMemBufferRef(); 614 file_magic Magic = identify_magic(MBRef.getBuffer()); 615 616 if (Magic == file_magic::bitcode) 617 return None; 618 if (Magic != file_magic::archive) 619 return Path.str(); 620 if (!needsRebuilding(MBRef)) 621 return Path.str(); 622 623 std::unique_ptr<Archive> File = 624 CHECK(Archive::create(MBRef), 625 MBRef.getBufferIdentifier() + ": failed to parse archive"); 626 627 std::vector<NewArchiveMember> New; 628 for (MemoryBufferRef Member : getArchiveMembers(File.get())) 629 if (identify_magic(Member.getBuffer()) != file_magic::bitcode) 630 New.emplace_back(Member); 631 632 if (New.empty()) 633 return None; 634 635 log("Creating a temporary archive for " + Path + " to remove bitcode files"); 636 637 SmallString<128> S; 638 if (auto EC = sys::fs::createTemporaryFile("lld-" + sys::path::stem(Path), 639 ".lib", S)) 640 fatal("cannot create a temporary file: " + EC.message()); 641 std::string Temp = S.str(); 642 TemporaryFiles.push_back(Temp); 643 644 Error E = 645 llvm::writeArchive(Temp, New, /*WriteSymtab=*/true, Archive::Kind::K_GNU, 646 /*Deterministics=*/true, 647 /*Thin=*/false); 648 handleAllErrors(std::move(E), [&](const ErrorInfoBase &EI) { 649 error("failed to create a new archive " + S.str() + ": " + EI.message()); 650 }); 651 return Temp; 652 } 653 654 // Create response file contents and invoke the MSVC linker. 655 void LinkerDriver::invokeMSVC(opt::InputArgList &Args) { 656 std::string Rsp = "/nologo\n"; 657 std::vector<std::string> Temps; 658 659 // Write out archive members that we used in symbol resolution and pass these 660 // to MSVC before any archives, so that MSVC uses the same objects to satisfy 661 // references. 662 for (ObjFile *Obj : ObjFile::Instances) { 663 if (Obj->ParentName.empty()) 664 continue; 665 SmallString<128> S; 666 int Fd; 667 if (auto EC = sys::fs::createTemporaryFile( 668 "lld-" + sys::path::filename(Obj->ParentName), ".obj", Fd, S)) 669 fatal("cannot create a temporary file: " + EC.message()); 670 raw_fd_ostream OS(Fd, /*shouldClose*/ true); 671 OS << Obj->MB.getBuffer(); 672 Temps.push_back(S.str()); 673 Rsp += quote(S) + "\n"; 674 } 675 676 for (auto *Arg : Args) { 677 switch (Arg->getOption().getID()) { 678 case OPT_linkrepro: 679 case OPT_lldmap: 680 case OPT_lldmap_file: 681 case OPT_lldsavetemps: 682 case OPT_msvclto: 683 // LLD-specific options are stripped. 684 break; 685 case OPT_opt: 686 if (!StringRef(Arg->getValue()).startswith("lld")) 687 Rsp += toString(*Arg) + " "; 688 break; 689 case OPT_INPUT: { 690 if (Optional<StringRef> Path = doFindFile(Arg->getValue())) { 691 if (Optional<std::string> S = filterBitcodeFiles(*Path, Temps)) 692 Rsp += quote(*S) + "\n"; 693 continue; 694 } 695 Rsp += quote(Arg->getValue()) + "\n"; 696 break; 697 } 698 default: 699 Rsp += toString(*Arg) + "\n"; 700 } 701 } 702 703 std::vector<StringRef> ObjFiles = Symtab->compileBitcodeFiles(); 704 runMSVCLinker(Rsp, ObjFiles); 705 706 for (StringRef Path : Temps) 707 sys::fs::remove(Path); 708 } 709 710 void LinkerDriver::enqueueTask(std::function<void()> Task) { 711 TaskQueue.push_back(std::move(Task)); 712 } 713 714 bool LinkerDriver::run() { 715 bool DidWork = !TaskQueue.empty(); 716 while (!TaskQueue.empty()) { 717 TaskQueue.front()(); 718 TaskQueue.pop_front(); 719 } 720 return DidWork; 721 } 722 723 void LinkerDriver::link(ArrayRef<const char *> ArgsArr) { 724 // If the first command line argument is "/lib", link.exe acts like lib.exe. 725 // We call our own implementation of lib.exe that understands bitcode files. 726 if (ArgsArr.size() > 1 && StringRef(ArgsArr[1]).equals_lower("/lib")) { 727 if (llvm::libDriverMain(ArgsArr.slice(1)) != 0) 728 fatal("lib failed"); 729 return; 730 } 731 732 // Needed for LTO. 733 InitializeAllTargetInfos(); 734 InitializeAllTargets(); 735 InitializeAllTargetMCs(); 736 InitializeAllAsmParsers(); 737 InitializeAllAsmPrinters(); 738 InitializeAllDisassemblers(); 739 740 // Parse command line options. 741 ArgParser Parser; 742 opt::InputArgList Args = Parser.parseLINK(ArgsArr.slice(1)); 743 744 // Parse and evaluate -mllvm options. 745 std::vector<const char *> V; 746 V.push_back("lld-link (LLVM option parsing)"); 747 for (auto *Arg : Args.filtered(OPT_mllvm)) 748 V.push_back(Arg->getValue()); 749 cl::ParseCommandLineOptions(V.size(), V.data()); 750 751 // Handle /errorlimit early, because error() depends on it. 752 if (auto *Arg = Args.getLastArg(OPT_errorlimit)) { 753 int N = 20; 754 StringRef S = Arg->getValue(); 755 if (S.getAsInteger(10, N)) 756 error(Arg->getSpelling() + " number expected, but got " + S); 757 errorHandler().ErrorLimit = N; 758 } 759 760 // Handle /help 761 if (Args.hasArg(OPT_help)) { 762 printHelp(ArgsArr[0]); 763 return; 764 } 765 766 // Handle --version, which is an lld extension. This option is a bit odd 767 // because it doesn't start with "/", but we deliberately chose "--" to 768 // avoid conflict with /version and for compatibility with clang-cl. 769 if (Args.hasArg(OPT_dash_dash_version)) { 770 outs() << getLLDVersion() << "\n"; 771 return; 772 } 773 774 // Handle /lldmingw early, since it can potentially affect how other 775 // options are handled. 776 Config->MinGW = Args.hasArg(OPT_lldmingw); 777 778 if (auto *Arg = Args.getLastArg(OPT_linkrepro)) { 779 SmallString<64> Path = StringRef(Arg->getValue()); 780 sys::path::append(Path, "repro.tar"); 781 782 Expected<std::unique_ptr<TarWriter>> ErrOrWriter = 783 TarWriter::create(Path, "repro"); 784 785 if (ErrOrWriter) { 786 Tar = std::move(*ErrOrWriter); 787 } else { 788 error("/linkrepro: failed to open " + Path + ": " + 789 toString(ErrOrWriter.takeError())); 790 } 791 } 792 793 if (!Args.hasArg(OPT_INPUT)) { 794 if (Args.hasArg(OPT_deffile)) 795 Config->NoEntry = true; 796 else 797 fatal("no input files"); 798 } 799 800 // Construct search path list. 801 SearchPaths.push_back(""); 802 for (auto *Arg : Args.filtered(OPT_libpath)) 803 SearchPaths.push_back(Arg->getValue()); 804 addLibSearchPaths(); 805 806 // Handle /ignore 807 for (auto *Arg : Args.filtered(OPT_ignore)) { 808 if (StringRef(Arg->getValue()) == "4217") 809 Config->WarnLocallyDefinedImported = false; 810 // Other warning numbers are ignored. 811 } 812 813 // Handle /out 814 if (auto *Arg = Args.getLastArg(OPT_out)) 815 Config->OutputFile = Arg->getValue(); 816 817 // Handle /verbose 818 if (Args.hasArg(OPT_verbose)) 819 Config->Verbose = true; 820 errorHandler().Verbose = Config->Verbose; 821 822 // Handle /force or /force:unresolved 823 if (Args.hasArg(OPT_force, OPT_force_unresolved)) 824 Config->Force = true; 825 826 // Handle /debug 827 if (Args.hasArg(OPT_debug, OPT_debug_dwarf, OPT_debug_ghash)) { 828 Config->Debug = true; 829 if (auto *Arg = Args.getLastArg(OPT_debugtype)) 830 Config->DebugTypes = parseDebugType(Arg->getValue()); 831 else 832 Config->DebugTypes = getDefaultDebugType(Args); 833 } 834 835 // Handle /pdb 836 bool ShouldCreatePDB = Args.hasArg(OPT_debug, OPT_debug_ghash); 837 if (ShouldCreatePDB) 838 if (auto *Arg = Args.getLastArg(OPT_pdb)) 839 Config->PDBPath = Arg->getValue(); 840 841 // Handle /noentry 842 if (Args.hasArg(OPT_noentry)) { 843 if (Args.hasArg(OPT_dll)) 844 Config->NoEntry = true; 845 else 846 error("/noentry must be specified with /dll"); 847 } 848 849 // Handle /dll 850 if (Args.hasArg(OPT_dll)) { 851 Config->DLL = true; 852 Config->ManifestID = 2; 853 } 854 855 // Handle /dynamicbase and /fixed. We can't use hasFlag for /dynamicbase 856 // because we need to explicitly check whether that option or its inverse was 857 // present in the argument list in order to handle /fixed. 858 auto *DynamicBaseArg = Args.getLastArg(OPT_dynamicbase, OPT_dynamicbase_no); 859 if (DynamicBaseArg && 860 DynamicBaseArg->getOption().getID() == OPT_dynamicbase_no) 861 Config->DynamicBase = false; 862 863 bool Fixed = Args.hasFlag(OPT_fixed, OPT_fixed_no, false); 864 if (Fixed) { 865 if (DynamicBaseArg && 866 DynamicBaseArg->getOption().getID() == OPT_dynamicbase) { 867 error("/fixed must not be specified with /dynamicbase"); 868 } else { 869 Config->Relocatable = false; 870 Config->DynamicBase = false; 871 } 872 } 873 874 // Handle /appcontainer 875 Config->AppContainer = 876 Args.hasFlag(OPT_appcontainer, OPT_appcontainer_no, false); 877 878 // Handle /machine 879 if (auto *Arg = Args.getLastArg(OPT_machine)) 880 Config->Machine = getMachineType(Arg->getValue()); 881 882 // Handle /nodefaultlib:<filename> 883 for (auto *Arg : Args.filtered(OPT_nodefaultlib)) 884 Config->NoDefaultLibs.insert(doFindLib(Arg->getValue())); 885 886 // Handle /nodefaultlib 887 if (Args.hasArg(OPT_nodefaultlib_all)) 888 Config->NoDefaultLibAll = true; 889 890 // Handle /base 891 if (auto *Arg = Args.getLastArg(OPT_base)) 892 parseNumbers(Arg->getValue(), &Config->ImageBase); 893 894 // Handle /stack 895 if (auto *Arg = Args.getLastArg(OPT_stack)) 896 parseNumbers(Arg->getValue(), &Config->StackReserve, &Config->StackCommit); 897 898 // Handle /heap 899 if (auto *Arg = Args.getLastArg(OPT_heap)) 900 parseNumbers(Arg->getValue(), &Config->HeapReserve, &Config->HeapCommit); 901 902 // Handle /version 903 if (auto *Arg = Args.getLastArg(OPT_version)) 904 parseVersion(Arg->getValue(), &Config->MajorImageVersion, 905 &Config->MinorImageVersion); 906 907 // Handle /subsystem 908 if (auto *Arg = Args.getLastArg(OPT_subsystem)) 909 parseSubsystem(Arg->getValue(), &Config->Subsystem, &Config->MajorOSVersion, 910 &Config->MinorOSVersion); 911 912 // Handle /alternatename 913 for (auto *Arg : Args.filtered(OPT_alternatename)) 914 parseAlternateName(Arg->getValue()); 915 916 // Handle /include 917 for (auto *Arg : Args.filtered(OPT_incl)) 918 addUndefined(Arg->getValue()); 919 920 // Handle /implib 921 if (auto *Arg = Args.getLastArg(OPT_implib)) 922 Config->Implib = Arg->getValue(); 923 924 // Handle /opt. 925 bool DoGC = !Args.hasArg(OPT_debug); 926 unsigned ICFLevel = 1; // 0: off, 1: limited, 2: on 927 for (auto *Arg : Args.filtered(OPT_opt)) { 928 std::string Str = StringRef(Arg->getValue()).lower(); 929 SmallVector<StringRef, 1> Vec; 930 StringRef(Str).split(Vec, ','); 931 for (StringRef S : Vec) { 932 if (S == "ref") { 933 DoGC = true; 934 } else if (S == "noref") { 935 DoGC = false; 936 } else if (S == "icf" || S.startswith("icf=")) { 937 ICFLevel = 2; 938 } else if (S == "noicf") { 939 ICFLevel = 0; 940 } else if (S.startswith("lldlto=")) { 941 StringRef OptLevel = S.substr(7); 942 if (OptLevel.getAsInteger(10, Config->LTOOptLevel) || 943 Config->LTOOptLevel > 3) 944 error("/opt:lldlto: invalid optimization level: " + OptLevel); 945 } else if (S.startswith("lldltojobs=")) { 946 StringRef Jobs = S.substr(11); 947 if (Jobs.getAsInteger(10, Config->LTOJobs) || Config->LTOJobs == 0) 948 error("/opt:lldltojobs: invalid job count: " + Jobs); 949 } else if (S.startswith("lldltopartitions=")) { 950 StringRef N = S.substr(17); 951 if (N.getAsInteger(10, Config->LTOPartitions) || 952 Config->LTOPartitions == 0) 953 error("/opt:lldltopartitions: invalid partition count: " + N); 954 } else if (S != "lbr" && S != "nolbr") 955 error("/opt: unknown option: " + S); 956 } 957 } 958 959 // Limited ICF is enabled if GC is enabled and ICF was never mentioned 960 // explicitly. 961 // FIXME: LLD only implements "limited" ICF, i.e. it only merges identical 962 // code. If the user passes /OPT:ICF explicitly, LLD should merge identical 963 // comdat readonly data. 964 if (ICFLevel == 1 && !DoGC) 965 ICFLevel = 0; 966 Config->DoGC = DoGC; 967 Config->DoICF = ICFLevel > 0; 968 969 // Handle /lldsavetemps 970 if (Args.hasArg(OPT_lldsavetemps)) 971 Config->SaveTemps = true; 972 973 // Handle /lldltocache 974 if (auto *Arg = Args.getLastArg(OPT_lldltocache)) 975 Config->LTOCache = Arg->getValue(); 976 977 // Handle /lldsavecachepolicy 978 if (auto *Arg = Args.getLastArg(OPT_lldltocachepolicy)) 979 Config->LTOCachePolicy = CHECK( 980 parseCachePruningPolicy(Arg->getValue()), 981 Twine("/lldltocachepolicy: invalid cache policy: ") + Arg->getValue()); 982 983 // Handle /failifmismatch 984 for (auto *Arg : Args.filtered(OPT_failifmismatch)) 985 checkFailIfMismatch(Arg->getValue()); 986 987 // Handle /merge 988 for (auto *Arg : Args.filtered(OPT_merge)) 989 parseMerge(Arg->getValue()); 990 991 // Handle /section 992 for (auto *Arg : Args.filtered(OPT_section)) 993 parseSection(Arg->getValue()); 994 995 // Handle /aligncomm 996 for (auto *Arg : Args.filtered(OPT_aligncomm)) 997 parseAligncomm(Arg->getValue()); 998 999 // Handle /manifestdependency. This enables /manifest unless /manifest:no is 1000 // also passed. 1001 if (auto *Arg = Args.getLastArg(OPT_manifestdependency)) { 1002 Config->ManifestDependency = Arg->getValue(); 1003 Config->Manifest = Configuration::SideBySide; 1004 } 1005 1006 // Handle /manifest and /manifest: 1007 if (auto *Arg = Args.getLastArg(OPT_manifest, OPT_manifest_colon)) { 1008 if (Arg->getOption().getID() == OPT_manifest) 1009 Config->Manifest = Configuration::SideBySide; 1010 else 1011 parseManifest(Arg->getValue()); 1012 } 1013 1014 // Handle /manifestuac 1015 if (auto *Arg = Args.getLastArg(OPT_manifestuac)) 1016 parseManifestUAC(Arg->getValue()); 1017 1018 // Handle /manifestfile 1019 if (auto *Arg = Args.getLastArg(OPT_manifestfile)) 1020 Config->ManifestFile = Arg->getValue(); 1021 1022 // Handle /manifestinput 1023 for (auto *Arg : Args.filtered(OPT_manifestinput)) 1024 Config->ManifestInput.push_back(Arg->getValue()); 1025 1026 if (!Config->ManifestInput.empty() && 1027 Config->Manifest != Configuration::Embed) { 1028 fatal("/MANIFESTINPUT: requires /MANIFEST:EMBED"); 1029 } 1030 1031 // Handle miscellaneous boolean flags. 1032 Config->AllowBind = Args.hasFlag(OPT_allowbind, OPT_allowbind_no, true); 1033 Config->AllowIsolation = 1034 Args.hasFlag(OPT_allowisolation, OPT_allowisolation_no, true); 1035 Config->NxCompat = Args.hasFlag(OPT_nxcompat, OPT_nxcompat_no, true); 1036 Config->TerminalServerAware = Args.hasFlag(OPT_tsaware, OPT_tsaware_no, true); 1037 Config->DebugDwarf = Args.hasArg(OPT_debug_dwarf); 1038 Config->DebugGHashes = Args.hasArg(OPT_debug_ghash); 1039 1040 Config->MapFile = getMapFile(Args); 1041 1042 if (errorCount()) 1043 return; 1044 1045 bool WholeArchiveFlag = Args.hasArg(OPT_wholearchive_flag); 1046 // Create a list of input files. Files can be given as arguments 1047 // for /defaultlib option. 1048 std::vector<MemoryBufferRef> MBs; 1049 for (auto *Arg : Args.filtered(OPT_INPUT, OPT_wholearchive_file)) { 1050 switch (Arg->getOption().getID()) { 1051 case OPT_INPUT: 1052 if (Optional<StringRef> Path = findFile(Arg->getValue())) 1053 enqueuePath(*Path, WholeArchiveFlag); 1054 break; 1055 case OPT_wholearchive_file: 1056 if (Optional<StringRef> Path = findFile(Arg->getValue())) 1057 enqueuePath(*Path, true); 1058 break; 1059 } 1060 } 1061 for (auto *Arg : Args.filtered(OPT_defaultlib)) 1062 if (Optional<StringRef> Path = findLib(Arg->getValue())) 1063 enqueuePath(*Path, false); 1064 1065 // Windows specific -- Create a resource file containing a manifest file. 1066 if (Config->Manifest == Configuration::Embed) 1067 addBuffer(createManifestRes(), false); 1068 1069 // Read all input files given via the command line. 1070 run(); 1071 1072 // We should have inferred a machine type by now from the input files, but if 1073 // not we assume x64. 1074 if (Config->Machine == IMAGE_FILE_MACHINE_UNKNOWN) { 1075 warn("/machine is not specified. x64 is assumed"); 1076 Config->Machine = AMD64; 1077 } 1078 1079 // Input files can be Windows resource files (.res files). We use 1080 // WindowsResource to convert resource files to a regular COFF file, 1081 // then link the resulting file normally. 1082 if (!Resources.empty()) 1083 Symtab->addFile(make<ObjFile>(convertResToCOFF(Resources))); 1084 1085 if (Tar) 1086 Tar->append("response.txt", 1087 createResponseFile(Args, FilePaths, 1088 ArrayRef<StringRef>(SearchPaths).slice(1))); 1089 1090 // Handle /largeaddressaware 1091 Config->LargeAddressAware = Args.hasFlag( 1092 OPT_largeaddressaware, OPT_largeaddressaware_no, Config->is64()); 1093 1094 // Handle /highentropyva 1095 Config->HighEntropyVA = 1096 Config->is64() && 1097 Args.hasFlag(OPT_highentropyva, OPT_highentropyva_no, true); 1098 1099 if (!Config->DynamicBase && 1100 (Config->Machine == ARMNT || Config->Machine == ARM64)) 1101 error("/dynamicbase:no is not compatible with " + 1102 machineToStr(Config->Machine)); 1103 1104 // Handle /entry and /dll 1105 if (auto *Arg = Args.getLastArg(OPT_entry)) { 1106 Config->Entry = addUndefined(mangle(Arg->getValue())); 1107 } else if (!Config->Entry && !Config->NoEntry) { 1108 if (Args.hasArg(OPT_dll)) { 1109 StringRef S = (Config->Machine == I386) ? "__DllMainCRTStartup@12" 1110 : "_DllMainCRTStartup"; 1111 Config->Entry = addUndefined(S); 1112 } else { 1113 // Windows specific -- If entry point name is not given, we need to 1114 // infer that from user-defined entry name. 1115 StringRef S = findDefaultEntry(); 1116 if (S.empty()) 1117 fatal("entry point must be defined"); 1118 Config->Entry = addUndefined(S); 1119 log("Entry name inferred: " + S); 1120 } 1121 } 1122 1123 // Handle /export 1124 for (auto *Arg : Args.filtered(OPT_export)) { 1125 Export E = parseExport(Arg->getValue()); 1126 if (Config->Machine == I386) { 1127 if (!isDecorated(E.Name)) 1128 E.Name = Saver.save("_" + E.Name); 1129 if (!E.ExtName.empty() && !isDecorated(E.ExtName)) 1130 E.ExtName = Saver.save("_" + E.ExtName); 1131 } 1132 Config->Exports.push_back(E); 1133 } 1134 1135 // Handle /def 1136 if (auto *Arg = Args.getLastArg(OPT_deffile)) { 1137 // parseModuleDefs mutates Config object. 1138 parseModuleDefs(Arg->getValue()); 1139 } 1140 1141 // Handle generation of import library from a def file. 1142 if (!Args.hasArg(OPT_INPUT)) { 1143 fixupExports(); 1144 createImportLibrary(/*AsLib=*/true); 1145 return; 1146 } 1147 1148 // Handle /delayload 1149 for (auto *Arg : Args.filtered(OPT_delayload)) { 1150 Config->DelayLoads.insert(StringRef(Arg->getValue()).lower()); 1151 if (Config->Machine == I386) { 1152 Config->DelayLoadHelper = addUndefined("___delayLoadHelper2@8"); 1153 } else { 1154 Config->DelayLoadHelper = addUndefined("__delayLoadHelper2"); 1155 } 1156 } 1157 1158 // Set default image name if neither /out or /def set it. 1159 if (Config->OutputFile.empty()) { 1160 Config->OutputFile = 1161 getOutputPath((*Args.filtered(OPT_INPUT).begin())->getValue()); 1162 } 1163 1164 // Put the PDB next to the image if no /pdb flag was passed. 1165 if (ShouldCreatePDB && Config->PDBPath.empty()) { 1166 Config->PDBPath = Config->OutputFile; 1167 sys::path::replace_extension(Config->PDBPath, ".pdb"); 1168 } 1169 1170 // Set default image base if /base is not given. 1171 if (Config->ImageBase == uint64_t(-1)) 1172 Config->ImageBase = getDefaultImageBase(); 1173 1174 Symtab->addSynthetic(mangle("__ImageBase"), nullptr); 1175 if (Config->Machine == I386) { 1176 Symtab->addAbsolute("___safe_se_handler_table", 0); 1177 Symtab->addAbsolute("___safe_se_handler_count", 0); 1178 } 1179 1180 // We do not support /guard:cf (control flow protection) yet. 1181 // Define CFG symbols anyway so that we can link MSVC 2015 CRT. 1182 Symtab->addAbsolute(mangle("__guard_fids_count"), 0); 1183 Symtab->addAbsolute(mangle("__guard_fids_table"), 0); 1184 Symtab->addAbsolute(mangle("__guard_flags"), 0x100); 1185 Symtab->addAbsolute(mangle("__guard_iat_count"), 0); 1186 Symtab->addAbsolute(mangle("__guard_iat_table"), 0); 1187 Symtab->addAbsolute(mangle("__guard_longjmp_count"), 0); 1188 Symtab->addAbsolute(mangle("__guard_longjmp_table"), 0); 1189 // Needed for MSVC 2017 15.5 CRT. 1190 Symtab->addAbsolute(mangle("__enclave_config"), 0); 1191 1192 // This code may add new undefined symbols to the link, which may enqueue more 1193 // symbol resolution tasks, so we need to continue executing tasks until we 1194 // converge. 1195 do { 1196 // Windows specific -- if entry point is not found, 1197 // search for its mangled names. 1198 if (Config->Entry) 1199 Symtab->mangleMaybe(Config->Entry); 1200 1201 // Windows specific -- Make sure we resolve all dllexported symbols. 1202 for (Export &E : Config->Exports) { 1203 if (!E.ForwardTo.empty()) 1204 continue; 1205 E.Sym = addUndefined(E.Name); 1206 if (!E.Directives) 1207 Symtab->mangleMaybe(E.Sym); 1208 } 1209 1210 // Add weak aliases. Weak aliases is a mechanism to give remaining 1211 // undefined symbols final chance to be resolved successfully. 1212 for (auto Pair : Config->AlternateNames) { 1213 StringRef From = Pair.first; 1214 StringRef To = Pair.second; 1215 Symbol *Sym = Symtab->find(From); 1216 if (!Sym) 1217 continue; 1218 if (auto *U = dyn_cast<Undefined>(Sym)) 1219 if (!U->WeakAlias) 1220 U->WeakAlias = Symtab->addUndefined(To); 1221 } 1222 1223 // Windows specific -- if __load_config_used can be resolved, resolve it. 1224 if (Symtab->findUnderscore("_load_config_used")) 1225 addUndefined(mangle("_load_config_used")); 1226 } while (run()); 1227 1228 if (errorCount()) 1229 return; 1230 1231 // If /msvclto is given, we use the MSVC linker to link LTO output files. 1232 // This is useful because MSVC link.exe can generate complete PDBs. 1233 if (Args.hasArg(OPT_msvclto)) { 1234 invokeMSVC(Args); 1235 return; 1236 } 1237 1238 // Do LTO by compiling bitcode input files to a set of native COFF files then 1239 // link those files. 1240 Symtab->addCombinedLTOObjects(); 1241 run(); 1242 1243 // Make sure we have resolved all symbols. 1244 Symtab->reportRemainingUndefines(); 1245 if (errorCount()) 1246 return; 1247 1248 // Windows specific -- if no /subsystem is given, we need to infer 1249 // that from entry point name. 1250 if (Config->Subsystem == IMAGE_SUBSYSTEM_UNKNOWN) { 1251 Config->Subsystem = inferSubsystem(); 1252 if (Config->Subsystem == IMAGE_SUBSYSTEM_UNKNOWN) 1253 fatal("subsystem must be defined"); 1254 } 1255 1256 // Handle /safeseh. 1257 if (Args.hasFlag(OPT_safeseh, OPT_safeseh_no, false)) { 1258 for (ObjFile *File : ObjFile::Instances) 1259 if (!File->SEHCompat) 1260 error("/safeseh: " + File->getName() + " is not compatible with SEH"); 1261 if (errorCount()) 1262 return; 1263 } 1264 1265 // In MinGW, all symbols are automatically exported if no symbols 1266 // are chosen to be exported. 1267 if (Config->DLL && ((Config->MinGW && Config->Exports.empty()) || 1268 Args.hasArg(OPT_export_all_symbols))) { 1269 AutoExporter Exporter; 1270 1271 Symtab->forEachSymbol([=](Symbol *S) { 1272 auto *Def = dyn_cast<Defined>(S); 1273 if (!Exporter.shouldExport(Def)) 1274 return; 1275 Export E; 1276 E.Name = Def->getName(); 1277 E.Sym = Def; 1278 if (Def->getChunk() && 1279 !(Def->getChunk()->getPermissions() & IMAGE_SCN_MEM_EXECUTE)) 1280 E.Data = true; 1281 Config->Exports.push_back(E); 1282 }); 1283 } 1284 1285 // Windows specific -- when we are creating a .dll file, we also 1286 // need to create a .lib file. 1287 if (!Config->Exports.empty() || Config->DLL) { 1288 fixupExports(); 1289 createImportLibrary(/*AsLib=*/false); 1290 assignExportOrdinals(); 1291 } 1292 1293 // Handle /output-def (MinGW specific). 1294 if (auto *Arg = Args.getLastArg(OPT_output_def)) 1295 writeDefFile(Arg->getValue()); 1296 1297 // Set extra alignment for .comm symbols 1298 for (auto Pair : Config->AlignComm) { 1299 StringRef Name = Pair.first; 1300 uint32_t Alignment = Pair.second; 1301 1302 Symbol *Sym = Symtab->find(Name); 1303 if (!Sym) { 1304 warn("/aligncomm symbol " + Name + " not found"); 1305 continue; 1306 } 1307 1308 auto *DC = dyn_cast<DefinedCommon>(Sym); 1309 if (!DC) { 1310 warn("/aligncomm symbol " + Name + " of wrong kind"); 1311 continue; 1312 } 1313 1314 CommonChunk *C = DC->getChunk(); 1315 C->Alignment = std::max(C->Alignment, Alignment); 1316 } 1317 1318 // Windows specific -- Create a side-by-side manifest file. 1319 if (Config->Manifest == Configuration::SideBySide) 1320 createSideBySideManifest(); 1321 1322 // Identify unreferenced COMDAT sections. 1323 if (Config->DoGC) 1324 markLive(Symtab->getChunks()); 1325 1326 // Identify identical COMDAT sections to merge them. 1327 if (Config->DoICF) 1328 doICF(Symtab->getChunks()); 1329 1330 // Write the result. 1331 writeResult(); 1332 } 1333 1334 } // namespace coff 1335 } // namespace lld 1336