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