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