1 //===- Driver.cpp ---------------------------------------------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 9 #include "Driver.h" 10 #include "Config.h" 11 #include "ICF.h" 12 #include "InputFiles.h" 13 #include "MarkLive.h" 14 #include "MinGW.h" 15 #include "SymbolTable.h" 16 #include "Symbols.h" 17 #include "Writer.h" 18 #include "lld/Common/Args.h" 19 #include "lld/Common/Driver.h" 20 #include "lld/Common/ErrorHandler.h" 21 #include "lld/Common/Filesystem.h" 22 #include "lld/Common/Memory.h" 23 #include "lld/Common/Threads.h" 24 #include "lld/Common/Timer.h" 25 #include "lld/Common/Version.h" 26 #include "llvm/ADT/Optional.h" 27 #include "llvm/ADT/StringSwitch.h" 28 #include "llvm/BinaryFormat/Magic.h" 29 #include "llvm/Object/ArchiveWriter.h" 30 #include "llvm/Object/COFFImportFile.h" 31 #include "llvm/Object/COFFModuleDefinition.h" 32 #include "llvm/Option/Arg.h" 33 #include "llvm/Option/ArgList.h" 34 #include "llvm/Option/Option.h" 35 #include "llvm/Support/Debug.h" 36 #include "llvm/Support/LEB128.h" 37 #include "llvm/Support/Path.h" 38 #include "llvm/Support/Process.h" 39 #include "llvm/Support/TarWriter.h" 40 #include "llvm/Support/TargetSelect.h" 41 #include "llvm/Support/raw_ostream.h" 42 #include "llvm/ToolDrivers/llvm-lib/LibDriver.h" 43 #include <algorithm> 44 #include <future> 45 #include <memory> 46 47 using namespace llvm; 48 using namespace llvm::object; 49 using namespace llvm::COFF; 50 using llvm::sys::Process; 51 52 namespace lld { 53 namespace coff { 54 55 static Timer InputFileTimer("Input File Reading", Timer::root()); 56 57 Configuration *Config; 58 LinkerDriver *Driver; 59 60 bool link(ArrayRef<const char *> Args, bool CanExitEarly, raw_ostream &Diag) { 61 errorHandler().LogName = args::getFilenameWithoutExe(Args[0]); 62 errorHandler().ErrorOS = &Diag; 63 errorHandler().ColorDiagnostics = Diag.has_colors(); 64 errorHandler().ErrorLimitExceededMsg = 65 "too many errors emitted, stopping now" 66 " (use /errorlimit:0 to see all errors)"; 67 errorHandler().ExitEarly = CanExitEarly; 68 Config = make<Configuration>(); 69 70 Symtab = make<SymbolTable>(); 71 72 Driver = make<LinkerDriver>(); 73 Driver->link(Args); 74 75 // Call exit() if we can to avoid calling destructors. 76 if (CanExitEarly) 77 exitLld(errorCount() ? 1 : 0); 78 79 freeArena(); 80 ObjFile::Instances.clear(); 81 ImportFile::Instances.clear(); 82 BitcodeFile::Instances.clear(); 83 return !errorCount(); 84 } 85 86 // Drop directory components and replace extension with ".exe" or ".dll". 87 static std::string getOutputPath(StringRef Path) { 88 auto P = Path.find_last_of("\\/"); 89 StringRef S = (P == StringRef::npos) ? Path : Path.substr(P + 1); 90 const char* E = Config->DLL ? ".dll" : ".exe"; 91 return (S.substr(0, S.rfind('.')) + E).str(); 92 } 93 94 // Returns true if S matches /crtend.?\.o$/. 95 static bool isCrtend(StringRef S) { 96 if (!S.endswith(".o")) 97 return false; 98 S = S.drop_back(2); 99 if (S.endswith("crtend")) 100 return true; 101 return !S.empty() && S.drop_back().endswith("crtend"); 102 } 103 104 // ErrorOr is not default constructible, so it cannot be used as the type 105 // parameter of a future. 106 // FIXME: We could open the file in createFutureForFile and avoid needing to 107 // return an error here, but for the moment that would cost us a file descriptor 108 // (a limited resource on Windows) for the duration that the future is pending. 109 using MBErrPair = std::pair<std::unique_ptr<MemoryBuffer>, std::error_code>; 110 111 // Create a std::future that opens and maps a file using the best strategy for 112 // the host platform. 113 static std::future<MBErrPair> createFutureForFile(std::string Path) { 114 #if _WIN32 115 // On Windows, file I/O is relatively slow so it is best to do this 116 // asynchronously. 117 auto Strategy = std::launch::async; 118 #else 119 auto Strategy = std::launch::deferred; 120 #endif 121 return std::async(Strategy, [=]() { 122 auto MBOrErr = MemoryBuffer::getFile(Path, 123 /*FileSize*/ -1, 124 /*RequiresNullTerminator*/ false); 125 if (!MBOrErr) 126 return MBErrPair{nullptr, MBOrErr.getError()}; 127 return MBErrPair{std::move(*MBOrErr), std::error_code()}; 128 }); 129 } 130 131 // Symbol names are mangled by prepending "_" on x86. 132 static StringRef mangle(StringRef Sym) { 133 assert(Config->Machine != IMAGE_FILE_MACHINE_UNKNOWN); 134 if (Config->Machine == I386) 135 return Saver.save("_" + Sym); 136 return Sym; 137 } 138 139 static bool findUnderscoreMangle(StringRef Sym) { 140 StringRef Entry = Symtab->findMangle(mangle(Sym)); 141 return !Entry.empty() && !isa<Undefined>(Symtab->find(Entry)); 142 } 143 144 MemoryBufferRef LinkerDriver::takeBuffer(std::unique_ptr<MemoryBuffer> MB) { 145 MemoryBufferRef MBRef = *MB; 146 make<std::unique_ptr<MemoryBuffer>>(std::move(MB)); // take ownership 147 148 if (Driver->Tar) 149 Driver->Tar->append(relativeToRoot(MBRef.getBufferIdentifier()), 150 MBRef.getBuffer()); 151 return MBRef; 152 } 153 154 void LinkerDriver::addBuffer(std::unique_ptr<MemoryBuffer> MB, 155 bool WholeArchive) { 156 StringRef Filename = MB->getBufferIdentifier(); 157 158 MemoryBufferRef MBRef = takeBuffer(std::move(MB)); 159 FilePaths.push_back(Filename); 160 161 // File type is detected by contents, not by file extension. 162 switch (identify_magic(MBRef.getBuffer())) { 163 case file_magic::windows_resource: 164 Resources.push_back(MBRef); 165 break; 166 case file_magic::archive: 167 if (WholeArchive) { 168 std::unique_ptr<Archive> File = 169 CHECK(Archive::create(MBRef), Filename + ": failed to parse archive"); 170 171 for (MemoryBufferRef M : getArchiveMembers(File.get())) 172 addArchiveBuffer(M, "<whole-archive>", Filename, 0); 173 return; 174 } 175 Symtab->addFile(make<ArchiveFile>(MBRef)); 176 break; 177 case file_magic::bitcode: 178 Symtab->addFile(make<BitcodeFile>(MBRef, "", 0)); 179 break; 180 case file_magic::coff_object: 181 case file_magic::coff_import_library: 182 Symtab->addFile(make<ObjFile>(MBRef)); 183 break; 184 case file_magic::coff_cl_gl_object: 185 error(Filename + ": is not a native COFF file. Recompile without /GL"); 186 break; 187 case file_magic::pecoff_executable: 188 if (Filename.endswith_lower(".dll")) { 189 error(Filename + ": bad file type. Did you specify a DLL instead of an " 190 "import library?"); 191 break; 192 } 193 LLVM_FALLTHROUGH; 194 default: 195 error(MBRef.getBufferIdentifier() + ": unknown file type"); 196 break; 197 } 198 } 199 200 void LinkerDriver::enqueuePath(StringRef Path, bool WholeArchive) { 201 auto Future = 202 std::make_shared<std::future<MBErrPair>>(createFutureForFile(Path)); 203 std::string PathStr = Path; 204 enqueueTask([=]() { 205 auto MBOrErr = Future->get(); 206 if (MBOrErr.second) 207 error("could not open " + PathStr + ": " + MBOrErr.second.message()); 208 else 209 Driver->addBuffer(std::move(MBOrErr.first), WholeArchive); 210 }); 211 } 212 213 void LinkerDriver::addArchiveBuffer(MemoryBufferRef MB, StringRef SymName, 214 StringRef ParentName, 215 uint64_t OffsetInArchive) { 216 file_magic Magic = identify_magic(MB.getBuffer()); 217 if (Magic == file_magic::coff_import_library) { 218 InputFile *Imp = make<ImportFile>(MB); 219 Imp->ParentName = ParentName; 220 Symtab->addFile(Imp); 221 return; 222 } 223 224 InputFile *Obj; 225 if (Magic == file_magic::coff_object) { 226 Obj = make<ObjFile>(MB); 227 } else if (Magic == file_magic::bitcode) { 228 Obj = make<BitcodeFile>(MB, ParentName, OffsetInArchive); 229 } else { 230 error("unknown file type: " + MB.getBufferIdentifier()); 231 return; 232 } 233 234 Obj->ParentName = ParentName; 235 Symtab->addFile(Obj); 236 log("Loaded " + toString(Obj) + " for " + SymName); 237 } 238 239 void LinkerDriver::enqueueArchiveMember(const Archive::Child &C, 240 StringRef SymName, 241 StringRef ParentName) { 242 243 auto ReportBufferError = [=](Error &&E, 244 StringRef ChildName) { 245 fatal("could not get the buffer for the member defining symbol " + 246 SymName + ": " + ParentName + "(" + ChildName + "): " + 247 toString(std::move(E))); 248 }; 249 250 if (!C.getParent()->isThin()) { 251 uint64_t OffsetInArchive = C.getChildOffset(); 252 Expected<MemoryBufferRef> MBOrErr = C.getMemoryBufferRef(); 253 if (!MBOrErr) 254 ReportBufferError(MBOrErr.takeError(), check(C.getFullName())); 255 MemoryBufferRef MB = MBOrErr.get(); 256 enqueueTask([=]() { 257 Driver->addArchiveBuffer(MB, SymName, ParentName, OffsetInArchive); 258 }); 259 return; 260 } 261 262 std::string ChildName = CHECK( 263 C.getFullName(), 264 "could not get the filename for the member defining symbol " + 265 SymName); 266 auto Future = std::make_shared<std::future<MBErrPair>>( 267 createFutureForFile(ChildName)); 268 enqueueTask([=]() { 269 auto MBOrErr = Future->get(); 270 if (MBOrErr.second) 271 ReportBufferError(errorCodeToError(MBOrErr.second), ChildName); 272 Driver->addArchiveBuffer(takeBuffer(std::move(MBOrErr.first)), SymName, 273 ParentName, /* OffsetInArchive */ 0); 274 }); 275 } 276 277 static bool isDecorated(StringRef Sym) { 278 return Sym.startswith("@") || Sym.contains("@@") || Sym.startswith("?") || 279 (!Config->MinGW && Sym.contains('@')); 280 } 281 282 // Parses .drectve section contents and returns a list of files 283 // specified by /defaultlib. 284 void LinkerDriver::parseDirectives(InputFile *File) { 285 StringRef S = File->getDirectives(); 286 if (S.empty()) 287 return; 288 289 log("Directives: " + toString(File) + ": " + S); 290 291 ArgParser Parser; 292 // .drectve is always tokenized using Windows shell rules. 293 // /EXPORT: option can appear too many times, processing in fastpath. 294 opt::InputArgList Args; 295 std::vector<StringRef> Exports; 296 std::tie(Args, Exports) = Parser.parseDirectives(S); 297 298 for (StringRef E : Exports) { 299 // If a common header file contains dllexported function 300 // declarations, many object files may end up with having the 301 // same /EXPORT options. In order to save cost of parsing them, 302 // we dedup them first. 303 if (!DirectivesExports.insert(E).second) 304 continue; 305 306 Export Exp = parseExport(E); 307 if (Config->Machine == I386 && Config->MinGW) { 308 if (!isDecorated(Exp.Name)) 309 Exp.Name = Saver.save("_" + Exp.Name); 310 if (!Exp.ExtName.empty() && !isDecorated(Exp.ExtName)) 311 Exp.ExtName = Saver.save("_" + Exp.ExtName); 312 } 313 Exp.Directives = true; 314 Config->Exports.push_back(Exp); 315 } 316 317 for (auto *Arg : Args) { 318 switch (Arg->getOption().getUnaliasedOption().getID()) { 319 case OPT_aligncomm: 320 parseAligncomm(Arg->getValue()); 321 break; 322 case OPT_alternatename: 323 parseAlternateName(Arg->getValue()); 324 break; 325 case OPT_defaultlib: 326 if (Optional<StringRef> Path = findLib(Arg->getValue())) 327 enqueuePath(*Path, false); 328 break; 329 case OPT_entry: 330 Config->Entry = addUndefined(mangle(Arg->getValue())); 331 break; 332 case OPT_failifmismatch: 333 checkFailIfMismatch(Arg->getValue(), File); 334 break; 335 case OPT_incl: 336 addUndefined(Arg->getValue()); 337 break; 338 case OPT_merge: 339 parseMerge(Arg->getValue()); 340 break; 341 case OPT_nodefaultlib: 342 Config->NoDefaultLibs.insert(doFindLib(Arg->getValue())); 343 break; 344 case OPT_section: 345 parseSection(Arg->getValue()); 346 break; 347 case OPT_subsystem: 348 parseSubsystem(Arg->getValue(), &Config->Subsystem, 349 &Config->MajorOSVersion, &Config->MinorOSVersion); 350 break; 351 case OPT_editandcontinue: 352 case OPT_fastfail: 353 case OPT_guardsym: 354 case OPT_natvis: 355 case OPT_throwingnew: 356 break; 357 default: 358 error(Arg->getSpelling() + " is not allowed in .drectve"); 359 } 360 } 361 } 362 363 // Find file from search paths. You can omit ".obj", this function takes 364 // care of that. Note that the returned path is not guaranteed to exist. 365 StringRef LinkerDriver::doFindFile(StringRef Filename) { 366 bool HasPathSep = (Filename.find_first_of("/\\") != StringRef::npos); 367 if (HasPathSep) 368 return Filename; 369 bool HasExt = Filename.contains('.'); 370 for (StringRef Dir : SearchPaths) { 371 SmallString<128> Path = Dir; 372 sys::path::append(Path, Filename); 373 if (sys::fs::exists(Path.str())) 374 return Saver.save(Path.str()); 375 if (!HasExt) { 376 Path.append(".obj"); 377 if (sys::fs::exists(Path.str())) 378 return Saver.save(Path.str()); 379 } 380 } 381 return Filename; 382 } 383 384 static Optional<sys::fs::UniqueID> getUniqueID(StringRef Path) { 385 sys::fs::UniqueID Ret; 386 if (sys::fs::getUniqueID(Path, Ret)) 387 return None; 388 return Ret; 389 } 390 391 // Resolves a file path. This never returns the same path 392 // (in that case, it returns None). 393 Optional<StringRef> LinkerDriver::findFile(StringRef Filename) { 394 StringRef Path = doFindFile(Filename); 395 396 if (Optional<sys::fs::UniqueID> ID = getUniqueID(Path)) { 397 bool Seen = !VisitedFiles.insert(*ID).second; 398 if (Seen) 399 return None; 400 } 401 402 if (Path.endswith_lower(".lib")) 403 VisitedLibs.insert(sys::path::filename(Path)); 404 return Path; 405 } 406 407 // MinGW specific. If an embedded directive specified to link to 408 // foo.lib, but it isn't found, try libfoo.a instead. 409 StringRef LinkerDriver::doFindLibMinGW(StringRef Filename) { 410 if (Filename.contains('/') || Filename.contains('\\')) 411 return Filename; 412 413 SmallString<128> S = Filename; 414 sys::path::replace_extension(S, ".a"); 415 StringRef LibName = Saver.save("lib" + S.str()); 416 return doFindFile(LibName); 417 } 418 419 // Find library file from search path. 420 StringRef LinkerDriver::doFindLib(StringRef Filename) { 421 // Add ".lib" to Filename if that has no file extension. 422 bool HasExt = Filename.contains('.'); 423 if (!HasExt) 424 Filename = Saver.save(Filename + ".lib"); 425 StringRef Ret = doFindFile(Filename); 426 // For MinGW, if the find above didn't turn up anything, try 427 // looking for a MinGW formatted library name. 428 if (Config->MinGW && Ret == Filename) 429 return doFindLibMinGW(Filename); 430 return Ret; 431 } 432 433 // Resolves a library path. /nodefaultlib options are taken into 434 // consideration. This never returns the same path (in that case, 435 // it returns None). 436 Optional<StringRef> LinkerDriver::findLib(StringRef Filename) { 437 if (Config->NoDefaultLibAll) 438 return None; 439 if (!VisitedLibs.insert(Filename.lower()).second) 440 return None; 441 442 StringRef Path = doFindLib(Filename); 443 if (Config->NoDefaultLibs.count(Path)) 444 return None; 445 446 if (Optional<sys::fs::UniqueID> ID = getUniqueID(Path)) 447 if (!VisitedFiles.insert(*ID).second) 448 return None; 449 return Path; 450 } 451 452 // Parses LIB environment which contains a list of search paths. 453 void LinkerDriver::addLibSearchPaths() { 454 Optional<std::string> EnvOpt = Process::GetEnv("LIB"); 455 if (!EnvOpt.hasValue()) 456 return; 457 StringRef Env = Saver.save(*EnvOpt); 458 while (!Env.empty()) { 459 StringRef Path; 460 std::tie(Path, Env) = Env.split(';'); 461 SearchPaths.push_back(Path); 462 } 463 } 464 465 Symbol *LinkerDriver::addUndefined(StringRef Name) { 466 Symbol *B = Symtab->addUndefined(Name); 467 if (!B->IsGCRoot) { 468 B->IsGCRoot = true; 469 Config->GCRoot.push_back(B); 470 } 471 return B; 472 } 473 474 // Windows specific -- find default entry point name. 475 // 476 // There are four different entry point functions for Windows executables, 477 // each of which corresponds to a user-defined "main" function. This function 478 // infers an entry point from a user-defined "main" function. 479 StringRef LinkerDriver::findDefaultEntry() { 480 assert(Config->Subsystem != IMAGE_SUBSYSTEM_UNKNOWN && 481 "must handle /subsystem before calling this"); 482 483 if (Config->MinGW) 484 return mangle(Config->Subsystem == IMAGE_SUBSYSTEM_WINDOWS_GUI 485 ? "WinMainCRTStartup" 486 : "mainCRTStartup"); 487 488 if (Config->Subsystem == IMAGE_SUBSYSTEM_WINDOWS_GUI) { 489 if (findUnderscoreMangle("wWinMain")) { 490 if (!findUnderscoreMangle("WinMain")) 491 return mangle("wWinMainCRTStartup"); 492 warn("found both wWinMain and WinMain; using latter"); 493 } 494 return mangle("WinMainCRTStartup"); 495 } 496 if (findUnderscoreMangle("wmain")) { 497 if (!findUnderscoreMangle("main")) 498 return mangle("wmainCRTStartup"); 499 warn("found both wmain and main; using latter"); 500 } 501 return mangle("mainCRTStartup"); 502 } 503 504 WindowsSubsystem LinkerDriver::inferSubsystem() { 505 if (Config->DLL) 506 return IMAGE_SUBSYSTEM_WINDOWS_GUI; 507 if (Config->MinGW) 508 return IMAGE_SUBSYSTEM_WINDOWS_CUI; 509 // Note that link.exe infers the subsystem from the presence of these 510 // functions even if /entry: or /nodefaultlib are passed which causes them 511 // to not be called. 512 bool HaveMain = findUnderscoreMangle("main"); 513 bool HaveWMain = findUnderscoreMangle("wmain"); 514 bool HaveWinMain = findUnderscoreMangle("WinMain"); 515 bool HaveWWinMain = findUnderscoreMangle("wWinMain"); 516 if (HaveMain || HaveWMain) { 517 if (HaveWinMain || HaveWWinMain) { 518 warn(std::string("found ") + (HaveMain ? "main" : "wmain") + " and " + 519 (HaveWinMain ? "WinMain" : "wWinMain") + 520 "; defaulting to /subsystem:console"); 521 } 522 return IMAGE_SUBSYSTEM_WINDOWS_CUI; 523 } 524 if (HaveWinMain || HaveWWinMain) 525 return IMAGE_SUBSYSTEM_WINDOWS_GUI; 526 return IMAGE_SUBSYSTEM_UNKNOWN; 527 } 528 529 static uint64_t getDefaultImageBase() { 530 if (Config->is64()) 531 return Config->DLL ? 0x180000000 : 0x140000000; 532 return Config->DLL ? 0x10000000 : 0x400000; 533 } 534 535 static std::string createResponseFile(const opt::InputArgList &Args, 536 ArrayRef<StringRef> FilePaths, 537 ArrayRef<StringRef> SearchPaths) { 538 SmallString<0> Data; 539 raw_svector_ostream OS(Data); 540 541 for (auto *Arg : Args) { 542 switch (Arg->getOption().getID()) { 543 case OPT_linkrepro: 544 case OPT_INPUT: 545 case OPT_defaultlib: 546 case OPT_libpath: 547 case OPT_manifest: 548 case OPT_manifest_colon: 549 case OPT_manifestdependency: 550 case OPT_manifestfile: 551 case OPT_manifestinput: 552 case OPT_manifestuac: 553 break; 554 case OPT_implib: 555 case OPT_pdb: 556 case OPT_out: 557 OS << Arg->getSpelling() << sys::path::filename(Arg->getValue()) << "\n"; 558 break; 559 default: 560 OS << toString(*Arg) << "\n"; 561 } 562 } 563 564 for (StringRef Path : SearchPaths) { 565 std::string RelPath = relativeToRoot(Path); 566 OS << "/libpath:" << quote(RelPath) << "\n"; 567 } 568 569 for (StringRef Path : FilePaths) 570 OS << quote(relativeToRoot(Path)) << "\n"; 571 572 return Data.str(); 573 } 574 575 enum class DebugKind { Unknown, None, Full, FastLink, GHash, Dwarf, Symtab }; 576 577 static DebugKind parseDebugKind(const opt::InputArgList &Args) { 578 auto *A = Args.getLastArg(OPT_debug, OPT_debug_opt); 579 if (!A) 580 return DebugKind::None; 581 if (A->getNumValues() == 0) 582 return DebugKind::Full; 583 584 DebugKind Debug = StringSwitch<DebugKind>(A->getValue()) 585 .CaseLower("none", DebugKind::None) 586 .CaseLower("full", DebugKind::Full) 587 .CaseLower("fastlink", DebugKind::FastLink) 588 // LLD extensions 589 .CaseLower("ghash", DebugKind::GHash) 590 .CaseLower("dwarf", DebugKind::Dwarf) 591 .CaseLower("symtab", DebugKind::Symtab) 592 .Default(DebugKind::Unknown); 593 594 if (Debug == DebugKind::FastLink) { 595 warn("/debug:fastlink unsupported; using /debug:full"); 596 return DebugKind::Full; 597 } 598 if (Debug == DebugKind::Unknown) { 599 error("/debug: unknown option: " + Twine(A->getValue())); 600 return DebugKind::None; 601 } 602 return Debug; 603 } 604 605 static unsigned parseDebugTypes(const opt::InputArgList &Args) { 606 unsigned DebugTypes = static_cast<unsigned>(DebugType::None); 607 608 if (auto *A = Args.getLastArg(OPT_debugtype)) { 609 SmallVector<StringRef, 3> Types; 610 A->getSpelling().split(Types, ',', /*KeepEmpty=*/false); 611 612 for (StringRef Type : Types) { 613 unsigned V = StringSwitch<unsigned>(Type.lower()) 614 .Case("cv", static_cast<unsigned>(DebugType::CV)) 615 .Case("pdata", static_cast<unsigned>(DebugType::PData)) 616 .Case("fixup", static_cast<unsigned>(DebugType::Fixup)) 617 .Default(0); 618 if (V == 0) { 619 warn("/debugtype: unknown option: " + Twine(A->getValue())); 620 continue; 621 } 622 DebugTypes |= V; 623 } 624 return DebugTypes; 625 } 626 627 // Default debug types 628 DebugTypes = static_cast<unsigned>(DebugType::CV); 629 if (Args.hasArg(OPT_driver)) 630 DebugTypes |= static_cast<unsigned>(DebugType::PData); 631 if (Args.hasArg(OPT_profile)) 632 DebugTypes |= static_cast<unsigned>(DebugType::Fixup); 633 634 return DebugTypes; 635 } 636 637 static std::string getMapFile(const opt::InputArgList &Args) { 638 auto *Arg = Args.getLastArg(OPT_lldmap, OPT_lldmap_file); 639 if (!Arg) 640 return ""; 641 if (Arg->getOption().getID() == OPT_lldmap_file) 642 return Arg->getValue(); 643 644 assert(Arg->getOption().getID() == OPT_lldmap); 645 StringRef OutFile = Config->OutputFile; 646 return (OutFile.substr(0, OutFile.rfind('.')) + ".map").str(); 647 } 648 649 static std::string getImplibPath() { 650 if (!Config->Implib.empty()) 651 return Config->Implib; 652 SmallString<128> Out = StringRef(Config->OutputFile); 653 sys::path::replace_extension(Out, ".lib"); 654 return Out.str(); 655 } 656 657 // 658 // The import name is caculated as the following: 659 // 660 // | LIBRARY w/ ext | LIBRARY w/o ext | no LIBRARY 661 // -----+----------------+---------------------+------------------ 662 // LINK | {value} | {value}.{.dll/.exe} | {output name} 663 // LIB | {value} | {value}.dll | {output name}.dll 664 // 665 static std::string getImportName(bool AsLib) { 666 SmallString<128> Out; 667 668 if (Config->ImportName.empty()) { 669 Out.assign(sys::path::filename(Config->OutputFile)); 670 if (AsLib) 671 sys::path::replace_extension(Out, ".dll"); 672 } else { 673 Out.assign(Config->ImportName); 674 if (!sys::path::has_extension(Out)) 675 sys::path::replace_extension(Out, 676 (Config->DLL || AsLib) ? ".dll" : ".exe"); 677 } 678 679 return Out.str(); 680 } 681 682 static void createImportLibrary(bool AsLib) { 683 std::vector<COFFShortExport> Exports; 684 for (Export &E1 : Config->Exports) { 685 COFFShortExport E2; 686 E2.Name = E1.Name; 687 E2.SymbolName = E1.SymbolName; 688 E2.ExtName = E1.ExtName; 689 E2.Ordinal = E1.Ordinal; 690 E2.Noname = E1.Noname; 691 E2.Data = E1.Data; 692 E2.Private = E1.Private; 693 E2.Constant = E1.Constant; 694 Exports.push_back(E2); 695 } 696 697 auto HandleError = [](Error &&E) { 698 handleAllErrors(std::move(E), 699 [](ErrorInfoBase &EIB) { error(EIB.message()); }); 700 }; 701 std::string LibName = getImportName(AsLib); 702 std::string Path = getImplibPath(); 703 704 if (!Config->Incremental) { 705 HandleError(writeImportLibrary(LibName, Path, Exports, Config->Machine, 706 Config->MinGW)); 707 return; 708 } 709 710 // If the import library already exists, replace it only if the contents 711 // have changed. 712 ErrorOr<std::unique_ptr<MemoryBuffer>> OldBuf = MemoryBuffer::getFile( 713 Path, /*FileSize*/ -1, /*RequiresNullTerminator*/ false); 714 if (!OldBuf) { 715 HandleError(writeImportLibrary(LibName, Path, Exports, Config->Machine, 716 Config->MinGW)); 717 return; 718 } 719 720 SmallString<128> TmpName; 721 if (std::error_code EC = 722 sys::fs::createUniqueFile(Path + ".tmp-%%%%%%%%.lib", TmpName)) 723 fatal("cannot create temporary file for import library " + Path + ": " + 724 EC.message()); 725 726 if (Error E = writeImportLibrary(LibName, TmpName, Exports, Config->Machine, 727 Config->MinGW)) { 728 HandleError(std::move(E)); 729 return; 730 } 731 732 std::unique_ptr<MemoryBuffer> NewBuf = check(MemoryBuffer::getFile( 733 TmpName, /*FileSize*/ -1, /*RequiresNullTerminator*/ false)); 734 if ((*OldBuf)->getBuffer() != NewBuf->getBuffer()) { 735 OldBuf->reset(); 736 HandleError(errorCodeToError(sys::fs::rename(TmpName, Path))); 737 } else { 738 sys::fs::remove(TmpName); 739 } 740 } 741 742 static void parseModuleDefs(StringRef Path) { 743 std::unique_ptr<MemoryBuffer> MB = CHECK( 744 MemoryBuffer::getFile(Path, -1, false, true), "could not open " + Path); 745 COFFModuleDefinition M = check(parseCOFFModuleDefinition( 746 MB->getMemBufferRef(), Config->Machine, Config->MinGW)); 747 748 if (Config->OutputFile.empty()) 749 Config->OutputFile = Saver.save(M.OutputFile); 750 Config->ImportName = Saver.save(M.ImportName); 751 if (M.ImageBase) 752 Config->ImageBase = M.ImageBase; 753 if (M.StackReserve) 754 Config->StackReserve = M.StackReserve; 755 if (M.StackCommit) 756 Config->StackCommit = M.StackCommit; 757 if (M.HeapReserve) 758 Config->HeapReserve = M.HeapReserve; 759 if (M.HeapCommit) 760 Config->HeapCommit = M.HeapCommit; 761 if (M.MajorImageVersion) 762 Config->MajorImageVersion = M.MajorImageVersion; 763 if (M.MinorImageVersion) 764 Config->MinorImageVersion = M.MinorImageVersion; 765 if (M.MajorOSVersion) 766 Config->MajorOSVersion = M.MajorOSVersion; 767 if (M.MinorOSVersion) 768 Config->MinorOSVersion = M.MinorOSVersion; 769 770 for (COFFShortExport E1 : M.Exports) { 771 Export E2; 772 // In simple cases, only Name is set. Renamed exports are parsed 773 // and set as "ExtName = Name". If Name has the form "OtherDll.Func", 774 // it shouldn't be a normal exported function but a forward to another 775 // DLL instead. This is supported by both MS and GNU linkers. 776 if (E1.ExtName != E1.Name && StringRef(E1.Name).contains('.')) { 777 E2.Name = Saver.save(E1.ExtName); 778 E2.ForwardTo = Saver.save(E1.Name); 779 Config->Exports.push_back(E2); 780 continue; 781 } 782 E2.Name = Saver.save(E1.Name); 783 E2.ExtName = Saver.save(E1.ExtName); 784 E2.Ordinal = E1.Ordinal; 785 E2.Noname = E1.Noname; 786 E2.Data = E1.Data; 787 E2.Private = E1.Private; 788 E2.Constant = E1.Constant; 789 Config->Exports.push_back(E2); 790 } 791 } 792 793 void LinkerDriver::enqueueTask(std::function<void()> Task) { 794 TaskQueue.push_back(std::move(Task)); 795 } 796 797 bool LinkerDriver::run() { 798 ScopedTimer T(InputFileTimer); 799 800 bool DidWork = !TaskQueue.empty(); 801 while (!TaskQueue.empty()) { 802 TaskQueue.front()(); 803 TaskQueue.pop_front(); 804 } 805 return DidWork; 806 } 807 808 // Parse an /order file. If an option is given, the linker places 809 // COMDAT sections in the same order as their names appear in the 810 // given file. 811 static void parseOrderFile(StringRef Arg) { 812 // For some reason, the MSVC linker requires a filename to be 813 // preceded by "@". 814 if (!Arg.startswith("@")) { 815 error("malformed /order option: '@' missing"); 816 return; 817 } 818 819 // Get a list of all comdat sections for error checking. 820 DenseSet<StringRef> Set; 821 for (Chunk *C : Symtab->getChunks()) 822 if (auto *Sec = dyn_cast<SectionChunk>(C)) 823 if (Sec->Sym) 824 Set.insert(Sec->Sym->getName()); 825 826 // Open a file. 827 StringRef Path = Arg.substr(1); 828 std::unique_ptr<MemoryBuffer> MB = CHECK( 829 MemoryBuffer::getFile(Path, -1, false, true), "could not open " + Path); 830 831 // Parse a file. An order file contains one symbol per line. 832 // All symbols that were not present in a given order file are 833 // considered to have the lowest priority 0 and are placed at 834 // end of an output section. 835 for (std::string S : args::getLines(MB->getMemBufferRef())) { 836 if (Config->Machine == I386 && !isDecorated(S)) 837 S = "_" + S; 838 839 if (Set.count(S) == 0) { 840 if (Config->WarnMissingOrderSymbol) 841 warn("/order:" + Arg + ": missing symbol: " + S + " [LNK4037]"); 842 } 843 else 844 Config->Order[S] = INT_MIN + Config->Order.size(); 845 } 846 } 847 848 static void markAddrsig(Symbol *S) { 849 if (auto *D = dyn_cast_or_null<Defined>(S)) 850 if (Chunk *C = D->getChunk()) 851 C->KeepUnique = true; 852 } 853 854 static void findKeepUniqueSections() { 855 // Exported symbols could be address-significant in other executables or DSOs, 856 // so we conservatively mark them as address-significant. 857 for (Export &R : Config->Exports) 858 markAddrsig(R.Sym); 859 860 // Visit the address-significance table in each object file and mark each 861 // referenced symbol as address-significant. 862 for (ObjFile *Obj : ObjFile::Instances) { 863 ArrayRef<Symbol *> Syms = Obj->getSymbols(); 864 if (Obj->AddrsigSec) { 865 ArrayRef<uint8_t> Contents; 866 Obj->getCOFFObj()->getSectionContents(Obj->AddrsigSec, Contents); 867 const uint8_t *Cur = Contents.begin(); 868 while (Cur != Contents.end()) { 869 unsigned Size; 870 const char *Err; 871 uint64_t SymIndex = decodeULEB128(Cur, &Size, Contents.end(), &Err); 872 if (Err) 873 fatal(toString(Obj) + ": could not decode addrsig section: " + Err); 874 if (SymIndex >= Syms.size()) 875 fatal(toString(Obj) + ": invalid symbol index in addrsig section"); 876 markAddrsig(Syms[SymIndex]); 877 Cur += Size; 878 } 879 } else { 880 // If an object file does not have an address-significance table, 881 // conservatively mark all of its symbols as address-significant. 882 for (Symbol *S : Syms) 883 markAddrsig(S); 884 } 885 } 886 } 887 888 // link.exe replaces each %foo% in AltPath with the contents of environment 889 // variable foo, and adds the two magic env vars _PDB (expands to the basename 890 // of pdb's output path) and _EXT (expands to the extension of the output 891 // binary). 892 // lld only supports %_PDB% and %_EXT% and warns on references to all other env 893 // vars. 894 static void parsePDBAltPath(StringRef AltPath) { 895 SmallString<128> Buf; 896 StringRef PDBBasename = 897 sys::path::filename(Config->PDBPath, sys::path::Style::windows); 898 StringRef BinaryExtension = 899 sys::path::extension(Config->OutputFile, sys::path::Style::windows); 900 if (!BinaryExtension.empty()) 901 BinaryExtension = BinaryExtension.substr(1); // %_EXT% does not include '.'. 902 903 // Invariant: 904 // +--------- Cursor ('a...' might be the empty string). 905 // | +----- FirstMark 906 // | | +- SecondMark 907 // v v v 908 // a...%...%... 909 size_t Cursor = 0; 910 while (Cursor < AltPath.size()) { 911 size_t FirstMark, SecondMark; 912 if ((FirstMark = AltPath.find('%', Cursor)) == StringRef::npos || 913 (SecondMark = AltPath.find('%', FirstMark + 1)) == StringRef::npos) { 914 // Didn't find another full fragment, treat rest of string as literal. 915 Buf.append(AltPath.substr(Cursor)); 916 break; 917 } 918 919 // Found a full fragment. Append text in front of first %, and interpret 920 // text between first and second % as variable name. 921 Buf.append(AltPath.substr(Cursor, FirstMark - Cursor)); 922 StringRef Var = AltPath.substr(FirstMark, SecondMark - FirstMark + 1); 923 if (Var.equals_lower("%_pdb%")) 924 Buf.append(PDBBasename); 925 else if (Var.equals_lower("%_ext%")) 926 Buf.append(BinaryExtension); 927 else { 928 warn("only %_PDB% and %_EXT% supported in /pdbaltpath:, keeping " + 929 Var + " as literal"); 930 Buf.append(Var); 931 } 932 933 Cursor = SecondMark + 1; 934 } 935 936 Config->PDBAltPath = Buf; 937 } 938 939 // In MinGW, if no symbols are chosen to be exported, then all symbols are 940 // automatically exported by default. This behavior can be forced by the 941 // -export-all-symbols option, so that it happens even when exports are 942 // explicitly specified. The automatic behavior can be disabled using the 943 // -exclude-all-symbols option, so that lld-link behaves like link.exe rather 944 // than MinGW in the case that nothing is explicitly exported. 945 void LinkerDriver::maybeExportMinGWSymbols(const opt::InputArgList &Args) { 946 if (!Config->DLL) 947 return; 948 949 if (!Args.hasArg(OPT_export_all_symbols)) { 950 if (!Config->Exports.empty()) 951 return; 952 if (Args.hasArg(OPT_exclude_all_symbols)) 953 return; 954 } 955 956 AutoExporter Exporter; 957 958 for (auto *Arg : Args.filtered(OPT_wholearchive_file)) 959 if (Optional<StringRef> Path = doFindFile(Arg->getValue())) 960 Exporter.addWholeArchive(*Path); 961 962 Symtab->forEachSymbol([&](Symbol *S) { 963 auto *Def = dyn_cast<Defined>(S); 964 if (!Exporter.shouldExport(Def)) 965 return; 966 967 Export E; 968 E.Name = Def->getName(); 969 E.Sym = Def; 970 if (Chunk *C = Def->getChunk()) 971 if (!(C->getOutputCharacteristics() & IMAGE_SCN_MEM_EXECUTE)) 972 E.Data = true; 973 Config->Exports.push_back(E); 974 }); 975 } 976 977 void LinkerDriver::link(ArrayRef<const char *> ArgsArr) { 978 // If the first command line argument is "/lib", link.exe acts like lib.exe. 979 // We call our own implementation of lib.exe that understands bitcode files. 980 if (ArgsArr.size() > 1 && StringRef(ArgsArr[1]).equals_lower("/lib")) { 981 if (llvm::libDriverMain(ArgsArr.slice(1)) != 0) 982 fatal("lib failed"); 983 return; 984 } 985 986 // Needed for LTO. 987 InitializeAllTargetInfos(); 988 InitializeAllTargets(); 989 InitializeAllTargetMCs(); 990 InitializeAllAsmParsers(); 991 InitializeAllAsmPrinters(); 992 993 // Parse command line options. 994 ArgParser Parser; 995 opt::InputArgList Args = Parser.parseLINK(ArgsArr); 996 997 // Parse and evaluate -mllvm options. 998 std::vector<const char *> V; 999 V.push_back("lld-link (LLVM option parsing)"); 1000 for (auto *Arg : Args.filtered(OPT_mllvm)) 1001 V.push_back(Arg->getValue()); 1002 cl::ParseCommandLineOptions(V.size(), V.data()); 1003 1004 // Handle /errorlimit early, because error() depends on it. 1005 if (auto *Arg = Args.getLastArg(OPT_errorlimit)) { 1006 int N = 20; 1007 StringRef S = Arg->getValue(); 1008 if (S.getAsInteger(10, N)) 1009 error(Arg->getSpelling() + " number expected, but got " + S); 1010 errorHandler().ErrorLimit = N; 1011 } 1012 1013 // Handle /help 1014 if (Args.hasArg(OPT_help)) { 1015 printHelp(ArgsArr[0]); 1016 return; 1017 } 1018 1019 lld::ThreadsEnabled = Args.hasFlag(OPT_threads, OPT_threads_no, true); 1020 1021 if (Args.hasArg(OPT_show_timing)) 1022 Config->ShowTiming = true; 1023 1024 Config->ShowSummary = Args.hasArg(OPT_summary); 1025 1026 ScopedTimer T(Timer::root()); 1027 // Handle --version, which is an lld extension. This option is a bit odd 1028 // because it doesn't start with "/", but we deliberately chose "--" to 1029 // avoid conflict with /version and for compatibility with clang-cl. 1030 if (Args.hasArg(OPT_dash_dash_version)) { 1031 outs() << getLLDVersion() << "\n"; 1032 return; 1033 } 1034 1035 // Handle /lldmingw early, since it can potentially affect how other 1036 // options are handled. 1037 Config->MinGW = Args.hasArg(OPT_lldmingw); 1038 1039 if (auto *Arg = Args.getLastArg(OPT_linkrepro)) { 1040 SmallString<64> Path = StringRef(Arg->getValue()); 1041 sys::path::append(Path, "repro.tar"); 1042 1043 Expected<std::unique_ptr<TarWriter>> ErrOrWriter = 1044 TarWriter::create(Path, "repro"); 1045 1046 if (ErrOrWriter) { 1047 Tar = std::move(*ErrOrWriter); 1048 } else { 1049 error("/linkrepro: failed to open " + Path + ": " + 1050 toString(ErrOrWriter.takeError())); 1051 } 1052 } 1053 1054 if (!Args.hasArg(OPT_INPUT)) { 1055 if (Args.hasArg(OPT_deffile)) 1056 Config->NoEntry = true; 1057 else 1058 fatal("no input files"); 1059 } 1060 1061 // Construct search path list. 1062 SearchPaths.push_back(""); 1063 for (auto *Arg : Args.filtered(OPT_libpath)) 1064 SearchPaths.push_back(Arg->getValue()); 1065 addLibSearchPaths(); 1066 1067 // Handle /ignore 1068 for (auto *Arg : Args.filtered(OPT_ignore)) { 1069 SmallVector<StringRef, 8> Vec; 1070 StringRef(Arg->getValue()).split(Vec, ','); 1071 for (StringRef S : Vec) { 1072 if (S == "4037") 1073 Config->WarnMissingOrderSymbol = false; 1074 else if (S == "4099") 1075 Config->WarnDebugInfoUnusable = false; 1076 else if (S == "4217") 1077 Config->WarnLocallyDefinedImported = false; 1078 // Other warning numbers are ignored. 1079 } 1080 } 1081 1082 // Handle /out 1083 if (auto *Arg = Args.getLastArg(OPT_out)) 1084 Config->OutputFile = Arg->getValue(); 1085 1086 // Handle /verbose 1087 if (Args.hasArg(OPT_verbose)) 1088 Config->Verbose = true; 1089 errorHandler().Verbose = Config->Verbose; 1090 1091 // Handle /force or /force:unresolved 1092 if (Args.hasArg(OPT_force, OPT_force_unresolved)) 1093 Config->ForceUnresolved = true; 1094 1095 // Handle /force or /force:multiple 1096 if (Args.hasArg(OPT_force, OPT_force_multiple)) 1097 Config->ForceMultiple = true; 1098 1099 // Handle /debug 1100 DebugKind Debug = parseDebugKind(Args); 1101 if (Debug == DebugKind::Full || Debug == DebugKind::Dwarf || 1102 Debug == DebugKind::GHash) { 1103 Config->Debug = true; 1104 Config->Incremental = true; 1105 } 1106 1107 // Handle /demangle 1108 Config->Demangle = Args.hasFlag(OPT_demangle, OPT_demangle_no); 1109 1110 // Handle /debugtype 1111 Config->DebugTypes = parseDebugTypes(Args); 1112 1113 // Handle /pdb 1114 bool ShouldCreatePDB = 1115 (Debug == DebugKind::Full || Debug == DebugKind::GHash); 1116 if (ShouldCreatePDB) { 1117 if (auto *Arg = Args.getLastArg(OPT_pdb)) 1118 Config->PDBPath = Arg->getValue(); 1119 if (auto *Arg = Args.getLastArg(OPT_pdbaltpath)) 1120 Config->PDBAltPath = Arg->getValue(); 1121 if (Args.hasArg(OPT_natvis)) 1122 Config->NatvisFiles = Args.getAllArgValues(OPT_natvis); 1123 1124 if (auto *Arg = Args.getLastArg(OPT_pdb_source_path)) 1125 Config->PDBSourcePath = Arg->getValue(); 1126 } 1127 1128 // Handle /noentry 1129 if (Args.hasArg(OPT_noentry)) { 1130 if (Args.hasArg(OPT_dll)) 1131 Config->NoEntry = true; 1132 else 1133 error("/noentry must be specified with /dll"); 1134 } 1135 1136 // Handle /dll 1137 if (Args.hasArg(OPT_dll)) { 1138 Config->DLL = true; 1139 Config->ManifestID = 2; 1140 } 1141 1142 // Handle /dynamicbase and /fixed. We can't use hasFlag for /dynamicbase 1143 // because we need to explicitly check whether that option or its inverse was 1144 // present in the argument list in order to handle /fixed. 1145 auto *DynamicBaseArg = Args.getLastArg(OPT_dynamicbase, OPT_dynamicbase_no); 1146 if (DynamicBaseArg && 1147 DynamicBaseArg->getOption().getID() == OPT_dynamicbase_no) 1148 Config->DynamicBase = false; 1149 1150 // MSDN claims "/FIXED:NO is the default setting for a DLL, and /FIXED is the 1151 // default setting for any other project type.", but link.exe defaults to 1152 // /FIXED:NO for exe outputs as well. Match behavior, not docs. 1153 bool Fixed = Args.hasFlag(OPT_fixed, OPT_fixed_no, false); 1154 if (Fixed) { 1155 if (DynamicBaseArg && 1156 DynamicBaseArg->getOption().getID() == OPT_dynamicbase) { 1157 error("/fixed must not be specified with /dynamicbase"); 1158 } else { 1159 Config->Relocatable = false; 1160 Config->DynamicBase = false; 1161 } 1162 } 1163 1164 // Handle /appcontainer 1165 Config->AppContainer = 1166 Args.hasFlag(OPT_appcontainer, OPT_appcontainer_no, false); 1167 1168 // Handle /machine 1169 if (auto *Arg = Args.getLastArg(OPT_machine)) 1170 Config->Machine = getMachineType(Arg->getValue()); 1171 1172 // Handle /nodefaultlib:<filename> 1173 for (auto *Arg : Args.filtered(OPT_nodefaultlib)) 1174 Config->NoDefaultLibs.insert(doFindLib(Arg->getValue())); 1175 1176 // Handle /nodefaultlib 1177 if (Args.hasArg(OPT_nodefaultlib_all)) 1178 Config->NoDefaultLibAll = true; 1179 1180 // Handle /base 1181 if (auto *Arg = Args.getLastArg(OPT_base)) 1182 parseNumbers(Arg->getValue(), &Config->ImageBase); 1183 1184 // Handle /stack 1185 if (auto *Arg = Args.getLastArg(OPT_stack)) 1186 parseNumbers(Arg->getValue(), &Config->StackReserve, &Config->StackCommit); 1187 1188 // Handle /guard:cf 1189 if (auto *Arg = Args.getLastArg(OPT_guard)) 1190 parseGuard(Arg->getValue()); 1191 1192 // Handle /heap 1193 if (auto *Arg = Args.getLastArg(OPT_heap)) 1194 parseNumbers(Arg->getValue(), &Config->HeapReserve, &Config->HeapCommit); 1195 1196 // Handle /version 1197 if (auto *Arg = Args.getLastArg(OPT_version)) 1198 parseVersion(Arg->getValue(), &Config->MajorImageVersion, 1199 &Config->MinorImageVersion); 1200 1201 // Handle /subsystem 1202 if (auto *Arg = Args.getLastArg(OPT_subsystem)) 1203 parseSubsystem(Arg->getValue(), &Config->Subsystem, &Config->MajorOSVersion, 1204 &Config->MinorOSVersion); 1205 1206 // Handle /timestamp 1207 if (llvm::opt::Arg *Arg = Args.getLastArg(OPT_timestamp, OPT_repro)) { 1208 if (Arg->getOption().getID() == OPT_repro) { 1209 Config->Timestamp = 0; 1210 Config->Repro = true; 1211 } else { 1212 Config->Repro = false; 1213 StringRef Value(Arg->getValue()); 1214 if (Value.getAsInteger(0, Config->Timestamp)) 1215 fatal(Twine("invalid timestamp: ") + Value + 1216 ". Expected 32-bit integer"); 1217 } 1218 } else { 1219 Config->Repro = false; 1220 Config->Timestamp = time(nullptr); 1221 } 1222 1223 // Handle /alternatename 1224 for (auto *Arg : Args.filtered(OPT_alternatename)) 1225 parseAlternateName(Arg->getValue()); 1226 1227 // Handle /include 1228 for (auto *Arg : Args.filtered(OPT_incl)) 1229 addUndefined(Arg->getValue()); 1230 1231 // Handle /implib 1232 if (auto *Arg = Args.getLastArg(OPT_implib)) 1233 Config->Implib = Arg->getValue(); 1234 1235 // Handle /opt. 1236 bool DoGC = Debug == DebugKind::None || Args.hasArg(OPT_profile); 1237 unsigned ICFLevel = 1238 Args.hasArg(OPT_profile) ? 0 : 1; // 0: off, 1: limited, 2: on 1239 unsigned TailMerge = 1; 1240 for (auto *Arg : Args.filtered(OPT_opt)) { 1241 std::string Str = StringRef(Arg->getValue()).lower(); 1242 SmallVector<StringRef, 1> Vec; 1243 StringRef(Str).split(Vec, ','); 1244 for (StringRef S : Vec) { 1245 if (S == "ref") { 1246 DoGC = true; 1247 } else if (S == "noref") { 1248 DoGC = false; 1249 } else if (S == "icf" || S.startswith("icf=")) { 1250 ICFLevel = 2; 1251 } else if (S == "noicf") { 1252 ICFLevel = 0; 1253 } else if (S == "lldtailmerge") { 1254 TailMerge = 2; 1255 } else if (S == "nolldtailmerge") { 1256 TailMerge = 0; 1257 } else if (S.startswith("lldlto=")) { 1258 StringRef OptLevel = S.substr(7); 1259 if (OptLevel.getAsInteger(10, Config->LTOO) || Config->LTOO > 3) 1260 error("/opt:lldlto: invalid optimization level: " + OptLevel); 1261 } else if (S.startswith("lldltojobs=")) { 1262 StringRef Jobs = S.substr(11); 1263 if (Jobs.getAsInteger(10, Config->ThinLTOJobs) || 1264 Config->ThinLTOJobs == 0) 1265 error("/opt:lldltojobs: invalid job count: " + Jobs); 1266 } else if (S.startswith("lldltopartitions=")) { 1267 StringRef N = S.substr(17); 1268 if (N.getAsInteger(10, Config->LTOPartitions) || 1269 Config->LTOPartitions == 0) 1270 error("/opt:lldltopartitions: invalid partition count: " + N); 1271 } else if (S != "lbr" && S != "nolbr") 1272 error("/opt: unknown option: " + S); 1273 } 1274 } 1275 1276 // Limited ICF is enabled if GC is enabled and ICF was never mentioned 1277 // explicitly. 1278 // FIXME: LLD only implements "limited" ICF, i.e. it only merges identical 1279 // code. If the user passes /OPT:ICF explicitly, LLD should merge identical 1280 // comdat readonly data. 1281 if (ICFLevel == 1 && !DoGC) 1282 ICFLevel = 0; 1283 Config->DoGC = DoGC; 1284 Config->DoICF = ICFLevel > 0; 1285 Config->TailMerge = (TailMerge == 1 && Config->DoICF) || TailMerge == 2; 1286 1287 // Handle /lldsavetemps 1288 if (Args.hasArg(OPT_lldsavetemps)) 1289 Config->SaveTemps = true; 1290 1291 // Handle /kill-at 1292 if (Args.hasArg(OPT_kill_at)) 1293 Config->KillAt = true; 1294 1295 // Handle /lldltocache 1296 if (auto *Arg = Args.getLastArg(OPT_lldltocache)) 1297 Config->LTOCache = Arg->getValue(); 1298 1299 // Handle /lldsavecachepolicy 1300 if (auto *Arg = Args.getLastArg(OPT_lldltocachepolicy)) 1301 Config->LTOCachePolicy = CHECK( 1302 parseCachePruningPolicy(Arg->getValue()), 1303 Twine("/lldltocachepolicy: invalid cache policy: ") + Arg->getValue()); 1304 1305 // Handle /failifmismatch 1306 for (auto *Arg : Args.filtered(OPT_failifmismatch)) 1307 checkFailIfMismatch(Arg->getValue(), nullptr); 1308 1309 // Handle /merge 1310 for (auto *Arg : Args.filtered(OPT_merge)) 1311 parseMerge(Arg->getValue()); 1312 1313 // Add default section merging rules after user rules. User rules take 1314 // precedence, but we will emit a warning if there is a conflict. 1315 parseMerge(".idata=.rdata"); 1316 parseMerge(".didat=.rdata"); 1317 parseMerge(".edata=.rdata"); 1318 parseMerge(".xdata=.rdata"); 1319 parseMerge(".bss=.data"); 1320 1321 if (Config->MinGW) { 1322 parseMerge(".ctors=.rdata"); 1323 parseMerge(".dtors=.rdata"); 1324 parseMerge(".CRT=.rdata"); 1325 } 1326 1327 // Handle /section 1328 for (auto *Arg : Args.filtered(OPT_section)) 1329 parseSection(Arg->getValue()); 1330 1331 // Handle /aligncomm 1332 for (auto *Arg : Args.filtered(OPT_aligncomm)) 1333 parseAligncomm(Arg->getValue()); 1334 1335 // Handle /manifestdependency. This enables /manifest unless /manifest:no is 1336 // also passed. 1337 if (auto *Arg = Args.getLastArg(OPT_manifestdependency)) { 1338 Config->ManifestDependency = Arg->getValue(); 1339 Config->Manifest = Configuration::SideBySide; 1340 } 1341 1342 // Handle /manifest and /manifest: 1343 if (auto *Arg = Args.getLastArg(OPT_manifest, OPT_manifest_colon)) { 1344 if (Arg->getOption().getID() == OPT_manifest) 1345 Config->Manifest = Configuration::SideBySide; 1346 else 1347 parseManifest(Arg->getValue()); 1348 } 1349 1350 // Handle /manifestuac 1351 if (auto *Arg = Args.getLastArg(OPT_manifestuac)) 1352 parseManifestUAC(Arg->getValue()); 1353 1354 // Handle /manifestfile 1355 if (auto *Arg = Args.getLastArg(OPT_manifestfile)) 1356 Config->ManifestFile = Arg->getValue(); 1357 1358 // Handle /manifestinput 1359 for (auto *Arg : Args.filtered(OPT_manifestinput)) 1360 Config->ManifestInput.push_back(Arg->getValue()); 1361 1362 if (!Config->ManifestInput.empty() && 1363 Config->Manifest != Configuration::Embed) { 1364 fatal("/manifestinput: requires /manifest:embed"); 1365 } 1366 1367 // Handle miscellaneous boolean flags. 1368 Config->AllowBind = Args.hasFlag(OPT_allowbind, OPT_allowbind_no, true); 1369 Config->AllowIsolation = 1370 Args.hasFlag(OPT_allowisolation, OPT_allowisolation_no, true); 1371 Config->Incremental = 1372 Args.hasFlag(OPT_incremental, OPT_incremental_no, 1373 !Config->DoGC && !Config->DoICF && !Args.hasArg(OPT_order) && 1374 !Args.hasArg(OPT_profile)); 1375 Config->IntegrityCheck = 1376 Args.hasFlag(OPT_integritycheck, OPT_integritycheck_no, false); 1377 Config->NxCompat = Args.hasFlag(OPT_nxcompat, OPT_nxcompat_no, true); 1378 for (auto *Arg : Args.filtered(OPT_swaprun)) 1379 parseSwaprun(Arg->getValue()); 1380 Config->TerminalServerAware = 1381 !Config->DLL && Args.hasFlag(OPT_tsaware, OPT_tsaware_no, true); 1382 Config->DebugDwarf = Debug == DebugKind::Dwarf; 1383 Config->DebugGHashes = Debug == DebugKind::GHash; 1384 Config->DebugSymtab = Debug == DebugKind::Symtab; 1385 1386 Config->MapFile = getMapFile(Args); 1387 1388 if (Config->Incremental && Args.hasArg(OPT_profile)) { 1389 warn("ignoring '/incremental' due to '/profile' specification"); 1390 Config->Incremental = false; 1391 } 1392 1393 if (Config->Incremental && Args.hasArg(OPT_order)) { 1394 warn("ignoring '/incremental' due to '/order' specification"); 1395 Config->Incremental = false; 1396 } 1397 1398 if (Config->Incremental && Config->DoGC) { 1399 warn("ignoring '/incremental' because REF is enabled; use '/opt:noref' to " 1400 "disable"); 1401 Config->Incremental = false; 1402 } 1403 1404 if (Config->Incremental && Config->DoICF) { 1405 warn("ignoring '/incremental' because ICF is enabled; use '/opt:noicf' to " 1406 "disable"); 1407 Config->Incremental = false; 1408 } 1409 1410 if (errorCount()) 1411 return; 1412 1413 std::set<sys::fs::UniqueID> WholeArchives; 1414 for (auto *Arg : Args.filtered(OPT_wholearchive_file)) 1415 if (Optional<StringRef> Path = doFindFile(Arg->getValue())) 1416 if (Optional<sys::fs::UniqueID> ID = getUniqueID(*Path)) 1417 WholeArchives.insert(*ID); 1418 1419 // A predicate returning true if a given path is an argument for 1420 // /wholearchive:, or /wholearchive is enabled globally. 1421 // This function is a bit tricky because "foo.obj /wholearchive:././foo.obj" 1422 // needs to be handled as "/wholearchive:foo.obj foo.obj". 1423 auto IsWholeArchive = [&](StringRef Path) -> bool { 1424 if (Args.hasArg(OPT_wholearchive_flag)) 1425 return true; 1426 if (Optional<sys::fs::UniqueID> ID = getUniqueID(Path)) 1427 return WholeArchives.count(*ID); 1428 return false; 1429 }; 1430 1431 // Create a list of input files. Files can be given as arguments 1432 // for /defaultlib option. 1433 for (auto *Arg : Args.filtered(OPT_INPUT, OPT_wholearchive_file)) 1434 if (Optional<StringRef> Path = findFile(Arg->getValue())) 1435 enqueuePath(*Path, IsWholeArchive(*Path)); 1436 1437 for (auto *Arg : Args.filtered(OPT_defaultlib)) 1438 if (Optional<StringRef> Path = findLib(Arg->getValue())) 1439 enqueuePath(*Path, false); 1440 1441 // Windows specific -- Create a resource file containing a manifest file. 1442 if (Config->Manifest == Configuration::Embed) 1443 addBuffer(createManifestRes(), false); 1444 1445 // Read all input files given via the command line. 1446 run(); 1447 1448 if (errorCount()) 1449 return; 1450 1451 // We should have inferred a machine type by now from the input files, but if 1452 // not we assume x64. 1453 if (Config->Machine == IMAGE_FILE_MACHINE_UNKNOWN) { 1454 warn("/machine is not specified. x64 is assumed"); 1455 Config->Machine = AMD64; 1456 } 1457 Config->Wordsize = Config->is64() ? 8 : 4; 1458 1459 // Handle /functionpadmin 1460 for (auto *Arg : Args.filtered(OPT_functionpadmin, OPT_functionpadmin_opt)) 1461 parseFunctionPadMin(Arg, Config->Machine); 1462 1463 // Input files can be Windows resource files (.res files). We use 1464 // WindowsResource to convert resource files to a regular COFF file, 1465 // then link the resulting file normally. 1466 if (!Resources.empty()) 1467 Symtab->addFile(make<ObjFile>(convertResToCOFF(Resources))); 1468 1469 if (Tar) 1470 Tar->append("response.txt", 1471 createResponseFile(Args, FilePaths, 1472 ArrayRef<StringRef>(SearchPaths).slice(1))); 1473 1474 // Handle /largeaddressaware 1475 Config->LargeAddressAware = Args.hasFlag( 1476 OPT_largeaddressaware, OPT_largeaddressaware_no, Config->is64()); 1477 1478 // Handle /highentropyva 1479 Config->HighEntropyVA = 1480 Config->is64() && 1481 Args.hasFlag(OPT_highentropyva, OPT_highentropyva_no, true); 1482 1483 if (!Config->DynamicBase && 1484 (Config->Machine == ARMNT || Config->Machine == ARM64)) 1485 error("/dynamicbase:no is not compatible with " + 1486 machineToStr(Config->Machine)); 1487 1488 // Handle /export 1489 for (auto *Arg : Args.filtered(OPT_export)) { 1490 Export E = parseExport(Arg->getValue()); 1491 if (Config->Machine == I386) { 1492 if (!isDecorated(E.Name)) 1493 E.Name = Saver.save("_" + E.Name); 1494 if (!E.ExtName.empty() && !isDecorated(E.ExtName)) 1495 E.ExtName = Saver.save("_" + E.ExtName); 1496 } 1497 Config->Exports.push_back(E); 1498 } 1499 1500 // Handle /def 1501 if (auto *Arg = Args.getLastArg(OPT_deffile)) { 1502 // parseModuleDefs mutates Config object. 1503 parseModuleDefs(Arg->getValue()); 1504 } 1505 1506 // Handle generation of import library from a def file. 1507 if (!Args.hasArg(OPT_INPUT)) { 1508 fixupExports(); 1509 createImportLibrary(/*AsLib=*/true); 1510 return; 1511 } 1512 1513 // Windows specific -- if no /subsystem is given, we need to infer 1514 // that from entry point name. Must happen before /entry handling, 1515 // and after the early return when just writing an import library. 1516 if (Config->Subsystem == IMAGE_SUBSYSTEM_UNKNOWN) { 1517 Config->Subsystem = inferSubsystem(); 1518 if (Config->Subsystem == IMAGE_SUBSYSTEM_UNKNOWN) 1519 fatal("subsystem must be defined"); 1520 } 1521 1522 // Handle /entry and /dll 1523 if (auto *Arg = Args.getLastArg(OPT_entry)) { 1524 Config->Entry = addUndefined(mangle(Arg->getValue())); 1525 } else if (!Config->Entry && !Config->NoEntry) { 1526 if (Args.hasArg(OPT_dll)) { 1527 StringRef S = (Config->Machine == I386) ? "__DllMainCRTStartup@12" 1528 : "_DllMainCRTStartup"; 1529 Config->Entry = addUndefined(S); 1530 } else { 1531 // Windows specific -- If entry point name is not given, we need to 1532 // infer that from user-defined entry name. 1533 StringRef S = findDefaultEntry(); 1534 if (S.empty()) 1535 fatal("entry point must be defined"); 1536 Config->Entry = addUndefined(S); 1537 log("Entry name inferred: " + S); 1538 } 1539 } 1540 1541 // Handle /delayload 1542 for (auto *Arg : Args.filtered(OPT_delayload)) { 1543 Config->DelayLoads.insert(StringRef(Arg->getValue()).lower()); 1544 if (Config->Machine == I386) { 1545 Config->DelayLoadHelper = addUndefined("___delayLoadHelper2@8"); 1546 } else { 1547 Config->DelayLoadHelper = addUndefined("__delayLoadHelper2"); 1548 } 1549 } 1550 1551 // Set default image name if neither /out or /def set it. 1552 if (Config->OutputFile.empty()) { 1553 Config->OutputFile = 1554 getOutputPath((*Args.filtered(OPT_INPUT).begin())->getValue()); 1555 } 1556 1557 // Fail early if an output file is not writable. 1558 if (auto E = tryCreateFile(Config->OutputFile)) { 1559 error("cannot open output file " + Config->OutputFile + ": " + E.message()); 1560 return; 1561 } 1562 1563 if (ShouldCreatePDB) { 1564 // Put the PDB next to the image if no /pdb flag was passed. 1565 if (Config->PDBPath.empty()) { 1566 Config->PDBPath = Config->OutputFile; 1567 sys::path::replace_extension(Config->PDBPath, ".pdb"); 1568 } 1569 1570 // The embedded PDB path should be the absolute path to the PDB if no 1571 // /pdbaltpath flag was passed. 1572 if (Config->PDBAltPath.empty()) { 1573 Config->PDBAltPath = Config->PDBPath; 1574 1575 // It's important to make the path absolute and remove dots. This path 1576 // will eventually be written into the PE header, and certain Microsoft 1577 // tools won't work correctly if these assumptions are not held. 1578 sys::fs::make_absolute(Config->PDBAltPath); 1579 sys::path::remove_dots(Config->PDBAltPath); 1580 } else { 1581 // Don't do this earlier, so that Config->OutputFile is ready. 1582 parsePDBAltPath(Config->PDBAltPath); 1583 } 1584 } 1585 1586 // Set default image base if /base is not given. 1587 if (Config->ImageBase == uint64_t(-1)) 1588 Config->ImageBase = getDefaultImageBase(); 1589 1590 Symtab->addSynthetic(mangle("__ImageBase"), nullptr); 1591 if (Config->Machine == I386) { 1592 Symtab->addAbsolute("___safe_se_handler_table", 0); 1593 Symtab->addAbsolute("___safe_se_handler_count", 0); 1594 } 1595 1596 Symtab->addAbsolute(mangle("__guard_fids_count"), 0); 1597 Symtab->addAbsolute(mangle("__guard_fids_table"), 0); 1598 Symtab->addAbsolute(mangle("__guard_flags"), 0); 1599 Symtab->addAbsolute(mangle("__guard_iat_count"), 0); 1600 Symtab->addAbsolute(mangle("__guard_iat_table"), 0); 1601 Symtab->addAbsolute(mangle("__guard_longjmp_count"), 0); 1602 Symtab->addAbsolute(mangle("__guard_longjmp_table"), 0); 1603 // Needed for MSVC 2017 15.5 CRT. 1604 Symtab->addAbsolute(mangle("__enclave_config"), 0); 1605 1606 if (Config->MinGW) { 1607 Symtab->addAbsolute(mangle("__RUNTIME_PSEUDO_RELOC_LIST__"), 0); 1608 Symtab->addAbsolute(mangle("__RUNTIME_PSEUDO_RELOC_LIST_END__"), 0); 1609 Symtab->addAbsolute(mangle("__CTOR_LIST__"), 0); 1610 Symtab->addAbsolute(mangle("__DTOR_LIST__"), 0); 1611 } 1612 1613 // This code may add new undefined symbols to the link, which may enqueue more 1614 // symbol resolution tasks, so we need to continue executing tasks until we 1615 // converge. 1616 do { 1617 // Windows specific -- if entry point is not found, 1618 // search for its mangled names. 1619 if (Config->Entry) 1620 Symtab->mangleMaybe(Config->Entry); 1621 1622 // Windows specific -- Make sure we resolve all dllexported symbols. 1623 for (Export &E : Config->Exports) { 1624 if (!E.ForwardTo.empty()) 1625 continue; 1626 E.Sym = addUndefined(E.Name); 1627 if (!E.Directives) 1628 Symtab->mangleMaybe(E.Sym); 1629 } 1630 1631 // Add weak aliases. Weak aliases is a mechanism to give remaining 1632 // undefined symbols final chance to be resolved successfully. 1633 for (auto Pair : Config->AlternateNames) { 1634 StringRef From = Pair.first; 1635 StringRef To = Pair.second; 1636 Symbol *Sym = Symtab->find(From); 1637 if (!Sym) 1638 continue; 1639 if (auto *U = dyn_cast<Undefined>(Sym)) 1640 if (!U->WeakAlias) 1641 U->WeakAlias = Symtab->addUndefined(To); 1642 } 1643 1644 // Windows specific -- if __load_config_used can be resolved, resolve it. 1645 if (Symtab->findUnderscore("_load_config_used")) 1646 addUndefined(mangle("_load_config_used")); 1647 } while (run()); 1648 1649 if (errorCount()) 1650 return; 1651 1652 // Do LTO by compiling bitcode input files to a set of native COFF files then 1653 // link those files. 1654 Symtab->addCombinedLTOObjects(); 1655 run(); 1656 1657 if (Config->MinGW) { 1658 // Load any further object files that might be needed for doing automatic 1659 // imports. 1660 // 1661 // For cases with no automatically imported symbols, this iterates once 1662 // over the symbol table and doesn't do anything. 1663 // 1664 // For the normal case with a few automatically imported symbols, this 1665 // should only need to be run once, since each new object file imported 1666 // is an import library and wouldn't add any new undefined references, 1667 // but there's nothing stopping the __imp_ symbols from coming from a 1668 // normal object file as well (although that won't be used for the 1669 // actual autoimport later on). If this pass adds new undefined references, 1670 // we won't iterate further to resolve them. 1671 Symtab->loadMinGWAutomaticImports(); 1672 run(); 1673 } 1674 1675 // Make sure we have resolved all symbols. 1676 Symtab->reportRemainingUndefines(); 1677 if (errorCount()) 1678 return; 1679 1680 // Handle /safeseh. 1681 if (Args.hasFlag(OPT_safeseh, OPT_safeseh_no, false)) { 1682 for (ObjFile *File : ObjFile::Instances) 1683 if (!File->hasSafeSEH()) 1684 error("/safeseh: " + File->getName() + " is not compatible with SEH"); 1685 if (errorCount()) 1686 return; 1687 } 1688 1689 if (Config->MinGW) { 1690 // In MinGW, all symbols are automatically exported if no symbols 1691 // are chosen to be exported. 1692 maybeExportMinGWSymbols(Args); 1693 1694 // Make sure the crtend.o object is the last object file. This object 1695 // file can contain terminating section chunks that need to be placed 1696 // last. GNU ld processes files and static libraries explicitly in the 1697 // order provided on the command line, while lld will pull in needed 1698 // files from static libraries only after the last object file on the 1699 // command line. 1700 for (auto I = ObjFile::Instances.begin(), E = ObjFile::Instances.end(); 1701 I != E; I++) { 1702 ObjFile *File = *I; 1703 if (isCrtend(File->getName())) { 1704 ObjFile::Instances.erase(I); 1705 ObjFile::Instances.push_back(File); 1706 break; 1707 } 1708 } 1709 } 1710 1711 // Windows specific -- when we are creating a .dll file, we also 1712 // need to create a .lib file. 1713 if (!Config->Exports.empty() || Config->DLL) { 1714 fixupExports(); 1715 createImportLibrary(/*AsLib=*/false); 1716 assignExportOrdinals(); 1717 } 1718 1719 // Handle /output-def (MinGW specific). 1720 if (auto *Arg = Args.getLastArg(OPT_output_def)) 1721 writeDefFile(Arg->getValue()); 1722 1723 // Set extra alignment for .comm symbols 1724 for (auto Pair : Config->AlignComm) { 1725 StringRef Name = Pair.first; 1726 uint32_t Alignment = Pair.second; 1727 1728 Symbol *Sym = Symtab->find(Name); 1729 if (!Sym) { 1730 warn("/aligncomm symbol " + Name + " not found"); 1731 continue; 1732 } 1733 1734 // If the symbol isn't common, it must have been replaced with a regular 1735 // symbol, which will carry its own alignment. 1736 auto *DC = dyn_cast<DefinedCommon>(Sym); 1737 if (!DC) 1738 continue; 1739 1740 CommonChunk *C = DC->getChunk(); 1741 C->Alignment = std::max(C->Alignment, Alignment); 1742 } 1743 1744 // Windows specific -- Create a side-by-side manifest file. 1745 if (Config->Manifest == Configuration::SideBySide) 1746 createSideBySideManifest(); 1747 1748 // Handle /order. We want to do this at this moment because we 1749 // need a complete list of comdat sections to warn on nonexistent 1750 // functions. 1751 if (auto *Arg = Args.getLastArg(OPT_order)) 1752 parseOrderFile(Arg->getValue()); 1753 1754 // Identify unreferenced COMDAT sections. 1755 if (Config->DoGC) 1756 markLive(Symtab->getChunks()); 1757 1758 // Identify identical COMDAT sections to merge them. 1759 if (Config->DoICF) { 1760 findKeepUniqueSections(); 1761 doICF(Symtab->getChunks()); 1762 } 1763 1764 // Write the result. 1765 writeResult(); 1766 1767 // Stop early so we can print the results. 1768 Timer::root().stop(); 1769 if (Config->ShowTiming) 1770 Timer::root().print(); 1771 } 1772 1773 } // namespace coff 1774 } // namespace lld 1775