1 //===- Driver.cpp ---------------------------------------------------------===//
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
12 #include "InputFiles.h"
14 #include "SymbolTable.h"
17 #include "lld/Common/Driver.h"
18 #include "lld/Common/ErrorHandler.h"
19 #include "lld/Common/Memory.h"
20 #include "lld/Common/Version.h"
21 #include "llvm/ADT/Optional.h"
22 #include "llvm/ADT/StringSwitch.h"
23 #include "llvm/BinaryFormat/Magic.h"
24 #include "llvm/Object/ArchiveWriter.h"
25 #include "llvm/Object/COFFImportFile.h"
26 #include "llvm/Object/COFFModuleDefinition.h"
27 #include "llvm/Option/Arg.h"
28 #include "llvm/Option/ArgList.h"
29 #include "llvm/Option/Option.h"
30 #include "llvm/Support/Debug.h"
31 #include "llvm/Support/Path.h"
32 #include "llvm/Support/Process.h"
33 #include "llvm/Support/TarWriter.h"
34 #include "llvm/Support/TargetSelect.h"
35 #include "llvm/Support/raw_ostream.h"
36 #include "llvm/ToolDrivers/llvm-lib/LibDriver.h"
43 using namespace llvm::object;
44 using namespace llvm::COFF;
45 using llvm::sys::Process;
50 Configuration *Config;
53 bool link(ArrayRef<const char *> Args, bool CanExitEarly, raw_ostream &Diag) {
54 errorHandler().LogName = Args[0];
55 errorHandler().ErrorOS = &Diag;
56 errorHandler().ColorDiagnostics = Diag.has_colors();
57 errorHandler().ErrorLimitExceededMsg =
58 "too many errors emitted, stopping now"
59 " (use /ERRORLIMIT:0 to see all errors)";
60 errorHandler().ExitEarly = CanExitEarly;
61 Config = make<Configuration>();
62 Config->Argv = {Args.begin(), Args.end()};
63 Config->CanExitEarly = CanExitEarly;
65 Symtab = make<SymbolTable>();
67 Driver = make<LinkerDriver>();
70 // Call exit() if we can to avoid calling destructors.
72 exitLld(errorCount() ? 1 : 0);
78 // Drop directory components and replace extension with ".exe" or ".dll".
79 static std::string getOutputPath(StringRef Path) {
80 auto P = Path.find_last_of("\\/");
81 StringRef S = (P == StringRef::npos) ? Path : Path.substr(P + 1);
82 const char* E = Config->DLL ? ".dll" : ".exe";
83 return (S.substr(0, S.rfind('.')) + E).str();
86 // ErrorOr is not default constructible, so it cannot be used as the type
87 // parameter of a future.
88 // FIXME: We could open the file in createFutureForFile and avoid needing to
89 // return an error here, but for the moment that would cost us a file descriptor
90 // (a limited resource on Windows) for the duration that the future is pending.
91 typedef std::pair<std::unique_ptr<MemoryBuffer>, std::error_code> MBErrPair;
93 // Create a std::future that opens and maps a file using the best strategy for
95 static std::future<MBErrPair> createFutureForFile(std::string Path) {
97 // On Windows, file I/O is relatively slow so it is best to do this
99 auto Strategy = std::launch::async;
101 auto Strategy = std::launch::deferred;
103 return std::async(Strategy, [=]() {
104 auto MBOrErr = MemoryBuffer::getFile(Path);
106 return MBErrPair{nullptr, MBOrErr.getError()};
107 return MBErrPair{std::move(*MBOrErr), std::error_code()};
111 MemoryBufferRef LinkerDriver::takeBuffer(std::unique_ptr<MemoryBuffer> MB) {
112 MemoryBufferRef MBRef = *MB;
113 make<std::unique_ptr<MemoryBuffer>>(std::move(MB)); // take ownership
116 Driver->Tar->append(relativeToRoot(MBRef.getBufferIdentifier()),
121 void LinkerDriver::addBuffer(std::unique_ptr<MemoryBuffer> MB,
123 MemoryBufferRef MBRef = takeBuffer(std::move(MB));
124 FilePaths.push_back(MBRef.getBufferIdentifier());
126 // File type is detected by contents, not by file extension.
127 switch (identify_magic(MBRef.getBuffer())) {
128 case file_magic::windows_resource:
129 Resources.push_back(MBRef);
132 case file_magic::archive:
134 std::unique_ptr<Archive> File =
135 CHECK(Archive::create(MBRef),
136 MBRef.getBufferIdentifier() + ": failed to parse archive");
138 for (MemoryBufferRef M : getArchiveMembers(File.get()))
139 addArchiveBuffer(M, "<whole-archive>", MBRef.getBufferIdentifier());
142 Symtab->addFile(make<ArchiveFile>(MBRef));
145 case file_magic::bitcode:
146 Symtab->addFile(make<BitcodeFile>(MBRef));
149 case file_magic::coff_cl_gl_object:
150 error(MBRef.getBufferIdentifier() + ": is not a native COFF file. "
151 "Recompile without /GL");
155 Symtab->addFile(make<ObjFile>(MBRef));
160 void LinkerDriver::enqueuePath(StringRef Path, bool WholeArchive) {
162 std::make_shared<std::future<MBErrPair>>(createFutureForFile(Path));
163 std::string PathStr = Path;
165 auto MBOrErr = Future->get();
167 error("could not open " + PathStr + ": " + MBOrErr.second.message());
169 Driver->addBuffer(std::move(MBOrErr.first), WholeArchive);
173 void LinkerDriver::addArchiveBuffer(MemoryBufferRef MB, StringRef SymName,
174 StringRef ParentName) {
175 file_magic Magic = identify_magic(MB.getBuffer());
176 if (Magic == file_magic::coff_import_library) {
177 Symtab->addFile(make<ImportFile>(MB));
182 if (Magic == file_magic::coff_object) {
183 Obj = make<ObjFile>(MB);
184 } else if (Magic == file_magic::bitcode) {
185 Obj = make<BitcodeFile>(MB);
187 error("unknown file type: " + MB.getBufferIdentifier());
191 Obj->ParentName = ParentName;
192 Symtab->addFile(Obj);
193 log("Loaded " + toString(Obj) + " for " + SymName);
196 void LinkerDriver::enqueueArchiveMember(const Archive::Child &C,
198 StringRef ParentName) {
199 if (!C.getParent()->isThin()) {
200 MemoryBufferRef MB = CHECK(
201 C.getMemoryBufferRef(),
202 "could not get the buffer for the member defining symbol " + SymName);
203 enqueueTask([=]() { Driver->addArchiveBuffer(MB, SymName, ParentName); });
207 auto Future = std::make_shared<std::future<MBErrPair>>(createFutureForFile(
208 CHECK(C.getFullName(),
209 "could not get the filename for the member defining symbol " +
212 auto MBOrErr = Future->get();
214 fatal("could not get the buffer for the member defining " + SymName +
215 ": " + MBOrErr.second.message());
216 Driver->addArchiveBuffer(takeBuffer(std::move(MBOrErr.first)), SymName,
221 static bool isDecorated(StringRef Sym) {
222 return Sym.startswith("@") || Sym.contains("@@") || Sym.startswith("?") ||
223 (!Config->MinGW && Sym.contains('@'));
226 // Parses .drectve section contents and returns a list of files
227 // specified by /defaultlib.
228 void LinkerDriver::parseDirectives(StringRef S) {
230 // .drectve is always tokenized using Windows shell rules.
231 opt::InputArgList Args = Parser.parseDirectives(S);
233 for (auto *Arg : Args) {
234 switch (Arg->getOption().getUnaliasedOption().getID()) {
236 parseAligncomm(Arg->getValue());
238 case OPT_alternatename:
239 parseAlternateName(Arg->getValue());
242 if (Optional<StringRef> Path = findLib(Arg->getValue()))
243 enqueuePath(*Path, false);
246 Config->Entry = addUndefined(mangle(Arg->getValue()));
249 // If a common header file contains dllexported function
250 // declarations, many object files may end up with having the
251 // same /EXPORT options. In order to save cost of parsing them,
252 // we dedup them first.
253 if (!DirectivesExports.insert(Arg->getValue()).second)
256 Export E = parseExport(Arg->getValue());
257 if (Config->Machine == I386 && Config->MinGW) {
258 if (!isDecorated(E.Name))
259 E.Name = Saver.save("_" + E.Name);
260 if (!E.ExtName.empty() && !isDecorated(E.ExtName))
261 E.ExtName = Saver.save("_" + E.ExtName);
264 Config->Exports.push_back(E);
267 case OPT_failifmismatch:
268 checkFailIfMismatch(Arg->getValue());
271 addUndefined(Arg->getValue());
274 parseMerge(Arg->getValue());
276 case OPT_nodefaultlib:
277 Config->NoDefaultLibs.insert(doFindLib(Arg->getValue()));
280 parseSection(Arg->getValue());
283 parseSubsystem(Arg->getValue(), &Config->Subsystem,
284 &Config->MajorOSVersion, &Config->MinorOSVersion);
286 case OPT_editandcontinue:
290 case OPT_throwingnew:
293 error(Arg->getSpelling() + " is not allowed in .drectve");
298 // Find file from search paths. You can omit ".obj", this function takes
299 // care of that. Note that the returned path is not guaranteed to exist.
300 StringRef LinkerDriver::doFindFile(StringRef Filename) {
301 bool HasPathSep = (Filename.find_first_of("/\\") != StringRef::npos);
304 bool HasExt = Filename.contains('.');
305 for (StringRef Dir : SearchPaths) {
306 SmallString<128> Path = Dir;
307 sys::path::append(Path, Filename);
308 if (sys::fs::exists(Path.str()))
309 return Saver.save(Path.str());
312 if (sys::fs::exists(Path.str()))
313 return Saver.save(Path.str());
319 // Resolves a file path. This never returns the same path
320 // (in that case, it returns None).
321 Optional<StringRef> LinkerDriver::findFile(StringRef Filename) {
322 StringRef Path = doFindFile(Filename);
323 bool Seen = !VisitedFiles.insert(Path.lower()).second;
326 if (Path.endswith_lower(".lib"))
327 VisitedLibs.insert(sys::path::filename(Path));
331 // Find library file from search path.
332 StringRef LinkerDriver::doFindLib(StringRef Filename) {
333 // Add ".lib" to Filename if that has no file extension.
334 bool HasExt = Filename.contains('.');
336 Filename = Saver.save(Filename + ".lib");
337 return doFindFile(Filename);
340 // Resolves a library path. /nodefaultlib options are taken into
341 // consideration. This never returns the same path (in that case,
343 Optional<StringRef> LinkerDriver::findLib(StringRef Filename) {
344 if (Config->NoDefaultLibAll)
346 if (!VisitedLibs.insert(Filename.lower()).second)
348 StringRef Path = doFindLib(Filename);
349 if (Config->NoDefaultLibs.count(Path))
351 if (!VisitedFiles.insert(Path.lower()).second)
356 // Parses LIB environment which contains a list of search paths.
357 void LinkerDriver::addLibSearchPaths() {
358 Optional<std::string> EnvOpt = Process::GetEnv("LIB");
359 if (!EnvOpt.hasValue())
361 StringRef Env = Saver.save(*EnvOpt);
362 while (!Env.empty()) {
364 std::tie(Path, Env) = Env.split(';');
365 SearchPaths.push_back(Path);
369 Symbol *LinkerDriver::addUndefined(StringRef Name) {
370 Symbol *B = Symtab->addUndefined(Name);
373 Config->GCRoot.push_back(B);
378 // Symbol names are mangled by appending "_" prefix on x86.
379 StringRef LinkerDriver::mangle(StringRef Sym) {
380 assert(Config->Machine != IMAGE_FILE_MACHINE_UNKNOWN);
381 if (Config->Machine == I386)
382 return Saver.save("_" + Sym);
386 // Windows specific -- find default entry point name.
387 StringRef LinkerDriver::findDefaultEntry() {
388 // User-defined main functions and their corresponding entry points.
389 static const char *Entries[][2] = {
390 {"main", "mainCRTStartup"},
391 {"wmain", "wmainCRTStartup"},
392 {"WinMain", "WinMainCRTStartup"},
393 {"wWinMain", "wWinMainCRTStartup"},
395 for (auto E : Entries) {
396 StringRef Entry = Symtab->findMangle(mangle(E[0]));
397 if (!Entry.empty() && !isa<Undefined>(Symtab->find(Entry)))
403 WindowsSubsystem LinkerDriver::inferSubsystem() {
405 return IMAGE_SUBSYSTEM_WINDOWS_GUI;
406 if (Symtab->findUnderscore("main") || Symtab->findUnderscore("wmain"))
407 return IMAGE_SUBSYSTEM_WINDOWS_CUI;
408 if (Symtab->findUnderscore("WinMain") || Symtab->findUnderscore("wWinMain"))
409 return IMAGE_SUBSYSTEM_WINDOWS_GUI;
410 return IMAGE_SUBSYSTEM_UNKNOWN;
413 static uint64_t getDefaultImageBase() {
415 return Config->DLL ? 0x180000000 : 0x140000000;
416 return Config->DLL ? 0x10000000 : 0x400000;
419 static std::string createResponseFile(const opt::InputArgList &Args,
420 ArrayRef<StringRef> FilePaths,
421 ArrayRef<StringRef> SearchPaths) {
423 raw_svector_ostream OS(Data);
425 for (auto *Arg : Args) {
426 switch (Arg->getOption().getID()) {
432 case OPT_manifest_colon:
433 case OPT_manifestdependency:
434 case OPT_manifestfile:
435 case OPT_manifestinput:
436 case OPT_manifestuac:
439 OS << toString(*Arg) << "\n";
443 for (StringRef Path : SearchPaths) {
444 std::string RelPath = relativeToRoot(Path);
445 OS << "/libpath:" << quote(RelPath) << "\n";
448 for (StringRef Path : FilePaths)
449 OS << quote(relativeToRoot(Path)) << "\n";
454 static unsigned getDefaultDebugType(const opt::InputArgList &Args) {
455 unsigned DebugTypes = static_cast<unsigned>(DebugType::CV);
456 if (Args.hasArg(OPT_driver))
457 DebugTypes |= static_cast<unsigned>(DebugType::PData);
458 if (Args.hasArg(OPT_profile))
459 DebugTypes |= static_cast<unsigned>(DebugType::Fixup);
463 static unsigned parseDebugType(StringRef Arg) {
464 SmallVector<StringRef, 3> Types;
465 Arg.split(Types, ',', /*KeepEmpty=*/false);
467 unsigned DebugTypes = static_cast<unsigned>(DebugType::None);
468 for (StringRef Type : Types)
469 DebugTypes |= StringSwitch<unsigned>(Type.lower())
470 .Case("cv", static_cast<unsigned>(DebugType::CV))
471 .Case("pdata", static_cast<unsigned>(DebugType::PData))
472 .Case("fixup", static_cast<unsigned>(DebugType::Fixup))
477 static std::string getMapFile(const opt::InputArgList &Args) {
478 auto *Arg = Args.getLastArg(OPT_lldmap, OPT_lldmap_file);
481 if (Arg->getOption().getID() == OPT_lldmap_file)
482 return Arg->getValue();
484 assert(Arg->getOption().getID() == OPT_lldmap);
485 StringRef OutFile = Config->OutputFile;
486 return (OutFile.substr(0, OutFile.rfind('.')) + ".map").str();
489 static std::string getImplibPath() {
490 if (!Config->Implib.empty())
491 return Config->Implib;
492 SmallString<128> Out = StringRef(Config->OutputFile);
493 sys::path::replace_extension(Out, ".lib");
498 // The import name is caculated as the following:
500 // | LIBRARY w/ ext | LIBRARY w/o ext | no LIBRARY
501 // -----+----------------+---------------------+------------------
502 // LINK | {value} | {value}.{.dll/.exe} | {output name}
503 // LIB | {value} | {value}.dll | {output name}.dll
505 static std::string getImportName(bool AsLib) {
506 SmallString<128> Out;
508 if (Config->ImportName.empty()) {
509 Out.assign(sys::path::filename(Config->OutputFile));
511 sys::path::replace_extension(Out, ".dll");
513 Out.assign(Config->ImportName);
514 if (!sys::path::has_extension(Out))
515 sys::path::replace_extension(Out,
516 (Config->DLL || AsLib) ? ".dll" : ".exe");
522 static void createImportLibrary(bool AsLib) {
523 std::vector<COFFShortExport> Exports;
524 for (Export &E1 : Config->Exports) {
527 E2.SymbolName = E1.SymbolName;
528 E2.ExtName = E1.ExtName;
529 E2.Ordinal = E1.Ordinal;
530 E2.Noname = E1.Noname;
532 E2.Private = E1.Private;
533 E2.Constant = E1.Constant;
534 Exports.push_back(E2);
537 auto E = writeImportLibrary(getImportName(AsLib), getImplibPath(), Exports,
538 Config->Machine, false);
539 handleAllErrors(std::move(E),
540 [&](ErrorInfoBase &EIB) { error(EIB.message()); });
543 static void parseModuleDefs(StringRef Path) {
544 std::unique_ptr<MemoryBuffer> MB = CHECK(
545 MemoryBuffer::getFile(Path, -1, false, true), "could not open " + Path);
546 COFFModuleDefinition M = check(parseCOFFModuleDefinition(
547 MB->getMemBufferRef(), Config->Machine, Config->MinGW));
549 if (Config->OutputFile.empty())
550 Config->OutputFile = Saver.save(M.OutputFile);
551 Config->ImportName = Saver.save(M.ImportName);
553 Config->ImageBase = M.ImageBase;
555 Config->StackReserve = M.StackReserve;
557 Config->StackCommit = M.StackCommit;
559 Config->HeapReserve = M.HeapReserve;
561 Config->HeapCommit = M.HeapCommit;
562 if (M.MajorImageVersion)
563 Config->MajorImageVersion = M.MajorImageVersion;
564 if (M.MinorImageVersion)
565 Config->MinorImageVersion = M.MinorImageVersion;
566 if (M.MajorOSVersion)
567 Config->MajorOSVersion = M.MajorOSVersion;
568 if (M.MinorOSVersion)
569 Config->MinorOSVersion = M.MinorOSVersion;
571 for (COFFShortExport E1 : M.Exports) {
573 E2.Name = Saver.save(E1.Name);
575 E2.ExtName = Saver.save(E1.ExtName);
576 E2.Ordinal = E1.Ordinal;
577 E2.Noname = E1.Noname;
579 E2.Private = E1.Private;
580 E2.Constant = E1.Constant;
581 Config->Exports.push_back(E2);
585 // A helper function for filterBitcodeFiles.
586 static bool needsRebuilding(MemoryBufferRef MB) {
587 // The MSVC linker doesn't support thin archives, so if it's a thin
588 // archive, we always need to rebuild it.
589 std::unique_ptr<Archive> File =
590 CHECK(Archive::create(MB), "Failed to read " + MB.getBufferIdentifier());
594 // Returns true if the archive contains at least one bitcode file.
595 for (MemoryBufferRef Member : getArchiveMembers(File.get()))
596 if (identify_magic(Member.getBuffer()) == file_magic::bitcode)
601 // Opens a given path as an archive file and removes bitcode files
602 // from them if exists. This function is to appease the MSVC linker as
603 // their linker doesn't like archive files containing non-native
606 // If a given archive doesn't contain bitcode files, the archive path
607 // is returned as-is. Otherwise, a new temporary file is created and
608 // its path is returned.
609 static Optional<std::string>
610 filterBitcodeFiles(StringRef Path, std::vector<std::string> &TemporaryFiles) {
611 std::unique_ptr<MemoryBuffer> MB = CHECK(
612 MemoryBuffer::getFile(Path, -1, false, true), "could not open " + Path);
613 MemoryBufferRef MBRef = MB->getMemBufferRef();
614 file_magic Magic = identify_magic(MBRef.getBuffer());
616 if (Magic == file_magic::bitcode)
618 if (Magic != file_magic::archive)
620 if (!needsRebuilding(MBRef))
623 std::unique_ptr<Archive> File =
624 CHECK(Archive::create(MBRef),
625 MBRef.getBufferIdentifier() + ": failed to parse archive");
627 std::vector<NewArchiveMember> New;
628 for (MemoryBufferRef Member : getArchiveMembers(File.get()))
629 if (identify_magic(Member.getBuffer()) != file_magic::bitcode)
630 New.emplace_back(Member);
635 log("Creating a temporary archive for " + Path + " to remove bitcode files");
638 if (auto EC = sys::fs::createTemporaryFile("lld-" + sys::path::stem(Path),
640 fatal("cannot create a temporary file: " + EC.message());
641 std::string Temp = S.str();
642 TemporaryFiles.push_back(Temp);
645 llvm::writeArchive(Temp, New, /*WriteSymtab=*/true, Archive::Kind::K_GNU,
646 /*Deterministics=*/true,
648 handleAllErrors(std::move(E), [&](const ErrorInfoBase &EI) {
649 error("failed to create a new archive " + S.str() + ": " + EI.message());
654 // Create response file contents and invoke the MSVC linker.
655 void LinkerDriver::invokeMSVC(opt::InputArgList &Args) {
656 std::string Rsp = "/nologo\n";
657 std::vector<std::string> Temps;
659 // Write out archive members that we used in symbol resolution and pass these
660 // to MSVC before any archives, so that MSVC uses the same objects to satisfy
662 for (ObjFile *Obj : ObjFile::Instances) {
663 if (Obj->ParentName.empty())
667 if (auto EC = sys::fs::createTemporaryFile(
668 "lld-" + sys::path::filename(Obj->ParentName), ".obj", Fd, S))
669 fatal("cannot create a temporary file: " + EC.message());
670 raw_fd_ostream OS(Fd, /*shouldClose*/ true);
671 OS << Obj->MB.getBuffer();
672 Temps.push_back(S.str());
673 Rsp += quote(S) + "\n";
676 for (auto *Arg : Args) {
677 switch (Arg->getOption().getID()) {
680 case OPT_lldmap_file:
681 case OPT_lldsavetemps:
683 // LLD-specific options are stripped.
686 if (!StringRef(Arg->getValue()).startswith("lld"))
687 Rsp += toString(*Arg) + " ";
690 if (Optional<StringRef> Path = doFindFile(Arg->getValue())) {
691 if (Optional<std::string> S = filterBitcodeFiles(*Path, Temps))
692 Rsp += quote(*S) + "\n";
695 Rsp += quote(Arg->getValue()) + "\n";
699 Rsp += toString(*Arg) + "\n";
703 std::vector<StringRef> ObjFiles = Symtab->compileBitcodeFiles();
704 runMSVCLinker(Rsp, ObjFiles);
706 for (StringRef Path : Temps)
707 sys::fs::remove(Path);
710 void LinkerDriver::enqueueTask(std::function<void()> Task) {
711 TaskQueue.push_back(std::move(Task));
714 bool LinkerDriver::run() {
715 bool DidWork = !TaskQueue.empty();
716 while (!TaskQueue.empty()) {
718 TaskQueue.pop_front();
723 void LinkerDriver::link(ArrayRef<const char *> ArgsArr) {
724 // If the first command line argument is "/lib", link.exe acts like lib.exe.
725 // We call our own implementation of lib.exe that understands bitcode files.
726 if (ArgsArr.size() > 1 && StringRef(ArgsArr[1]).equals_lower("/lib")) {
727 if (llvm::libDriverMain(ArgsArr.slice(1)) != 0)
733 InitializeAllTargetInfos();
734 InitializeAllTargets();
735 InitializeAllTargetMCs();
736 InitializeAllAsmParsers();
737 InitializeAllAsmPrinters();
738 InitializeAllDisassemblers();
740 // Parse command line options.
742 opt::InputArgList Args = Parser.parseLINK(ArgsArr.slice(1));
744 // Parse and evaluate -mllvm options.
745 std::vector<const char *> V;
746 V.push_back("lld-link (LLVM option parsing)");
747 for (auto *Arg : Args.filtered(OPT_mllvm))
748 V.push_back(Arg->getValue());
749 cl::ParseCommandLineOptions(V.size(), V.data());
751 // Handle /errorlimit early, because error() depends on it.
752 if (auto *Arg = Args.getLastArg(OPT_errorlimit)) {
754 StringRef S = Arg->getValue();
755 if (S.getAsInteger(10, N))
756 error(Arg->getSpelling() + " number expected, but got " + S);
757 errorHandler().ErrorLimit = N;
761 if (Args.hasArg(OPT_help)) {
762 printHelp(ArgsArr[0]);
766 // Handle --version, which is an lld extension. This option is a bit odd
767 // because it doesn't start with "/", but we deliberately chose "--" to
768 // avoid conflict with /version and for compatibility with clang-cl.
769 if (Args.hasArg(OPT_dash_dash_version)) {
770 outs() << getLLDVersion() << "\n";
774 // Handle /lldmingw early, since it can potentially affect how other
775 // options are handled.
776 Config->MinGW = Args.hasArg(OPT_lldmingw);
778 if (auto *Arg = Args.getLastArg(OPT_linkrepro)) {
779 SmallString<64> Path = StringRef(Arg->getValue());
780 sys::path::append(Path, "repro.tar");
782 Expected<std::unique_ptr<TarWriter>> ErrOrWriter =
783 TarWriter::create(Path, "repro");
786 Tar = std::move(*ErrOrWriter);
788 error("/linkrepro: failed to open " + Path + ": " +
789 toString(ErrOrWriter.takeError()));
793 if (!Args.hasArg(OPT_INPUT)) {
794 if (Args.hasArg(OPT_deffile))
795 Config->NoEntry = true;
797 fatal("no input files");
800 // Construct search path list.
801 SearchPaths.push_back("");
802 for (auto *Arg : Args.filtered(OPT_libpath))
803 SearchPaths.push_back(Arg->getValue());
807 for (auto *Arg : Args.filtered(OPT_ignore)) {
808 if (StringRef(Arg->getValue()) == "4217")
809 Config->WarnLocallyDefinedImported = false;
810 // Other warning numbers are ignored.
814 if (auto *Arg = Args.getLastArg(OPT_out))
815 Config->OutputFile = Arg->getValue();
818 if (Args.hasArg(OPT_verbose))
819 Config->Verbose = true;
820 errorHandler().Verbose = Config->Verbose;
822 // Handle /force or /force:unresolved
823 if (Args.hasArg(OPT_force, OPT_force_unresolved))
824 Config->Force = true;
827 if (Args.hasArg(OPT_debug, OPT_debug_dwarf, OPT_debug_ghash)) {
828 Config->Debug = true;
829 if (auto *Arg = Args.getLastArg(OPT_debugtype))
830 Config->DebugTypes = parseDebugType(Arg->getValue());
832 Config->DebugTypes = getDefaultDebugType(Args);
836 bool ShouldCreatePDB = Args.hasArg(OPT_debug, OPT_debug_ghash);
838 if (auto *Arg = Args.getLastArg(OPT_pdb))
839 Config->PDBPath = Arg->getValue();
842 if (Args.hasArg(OPT_noentry)) {
843 if (Args.hasArg(OPT_dll))
844 Config->NoEntry = true;
846 error("/noentry must be specified with /dll");
850 if (Args.hasArg(OPT_dll)) {
852 Config->ManifestID = 2;
855 // Handle /dynamicbase and /fixed. We can't use hasFlag for /dynamicbase
856 // because we need to explicitly check whether that option or its inverse was
857 // present in the argument list in order to handle /fixed.
858 auto *DynamicBaseArg = Args.getLastArg(OPT_dynamicbase, OPT_dynamicbase_no);
859 if (DynamicBaseArg &&
860 DynamicBaseArg->getOption().getID() == OPT_dynamicbase_no)
861 Config->DynamicBase = false;
863 bool Fixed = Args.hasFlag(OPT_fixed, OPT_fixed_no, false);
865 if (DynamicBaseArg &&
866 DynamicBaseArg->getOption().getID() == OPT_dynamicbase) {
867 error("/fixed must not be specified with /dynamicbase");
869 Config->Relocatable = false;
870 Config->DynamicBase = false;
874 // Handle /appcontainer
875 Config->AppContainer =
876 Args.hasFlag(OPT_appcontainer, OPT_appcontainer_no, false);
879 if (auto *Arg = Args.getLastArg(OPT_machine))
880 Config->Machine = getMachineType(Arg->getValue());
882 // Handle /nodefaultlib:<filename>
883 for (auto *Arg : Args.filtered(OPT_nodefaultlib))
884 Config->NoDefaultLibs.insert(doFindLib(Arg->getValue()));
886 // Handle /nodefaultlib
887 if (Args.hasArg(OPT_nodefaultlib_all))
888 Config->NoDefaultLibAll = true;
891 if (auto *Arg = Args.getLastArg(OPT_base))
892 parseNumbers(Arg->getValue(), &Config->ImageBase);
895 if (auto *Arg = Args.getLastArg(OPT_stack))
896 parseNumbers(Arg->getValue(), &Config->StackReserve, &Config->StackCommit);
899 if (auto *Arg = Args.getLastArg(OPT_heap))
900 parseNumbers(Arg->getValue(), &Config->HeapReserve, &Config->HeapCommit);
903 if (auto *Arg = Args.getLastArg(OPT_version))
904 parseVersion(Arg->getValue(), &Config->MajorImageVersion,
905 &Config->MinorImageVersion);
908 if (auto *Arg = Args.getLastArg(OPT_subsystem))
909 parseSubsystem(Arg->getValue(), &Config->Subsystem, &Config->MajorOSVersion,
910 &Config->MinorOSVersion);
912 // Handle /alternatename
913 for (auto *Arg : Args.filtered(OPT_alternatename))
914 parseAlternateName(Arg->getValue());
917 for (auto *Arg : Args.filtered(OPT_incl))
918 addUndefined(Arg->getValue());
921 if (auto *Arg = Args.getLastArg(OPT_implib))
922 Config->Implib = Arg->getValue();
925 bool DoGC = !Args.hasArg(OPT_debug);
926 unsigned ICFLevel = 1; // 0: off, 1: limited, 2: on
927 for (auto *Arg : Args.filtered(OPT_opt)) {
928 std::string Str = StringRef(Arg->getValue()).lower();
929 SmallVector<StringRef, 1> Vec;
930 StringRef(Str).split(Vec, ',');
931 for (StringRef S : Vec) {
934 } else if (S == "noref") {
936 } else if (S == "icf" || S.startswith("icf=")) {
938 } else if (S == "noicf") {
940 } else if (S.startswith("lldlto=")) {
941 StringRef OptLevel = S.substr(7);
942 if (OptLevel.getAsInteger(10, Config->LTOOptLevel) ||
943 Config->LTOOptLevel > 3)
944 error("/opt:lldlto: invalid optimization level: " + OptLevel);
945 } else if (S.startswith("lldltojobs=")) {
946 StringRef Jobs = S.substr(11);
947 if (Jobs.getAsInteger(10, Config->LTOJobs) || Config->LTOJobs == 0)
948 error("/opt:lldltojobs: invalid job count: " + Jobs);
949 } else if (S.startswith("lldltopartitions=")) {
950 StringRef N = S.substr(17);
951 if (N.getAsInteger(10, Config->LTOPartitions) ||
952 Config->LTOPartitions == 0)
953 error("/opt:lldltopartitions: invalid partition count: " + N);
954 } else if (S != "lbr" && S != "nolbr")
955 error("/opt: unknown option: " + S);
959 // Limited ICF is enabled if GC is enabled and ICF was never mentioned
961 // FIXME: LLD only implements "limited" ICF, i.e. it only merges identical
962 // code. If the user passes /OPT:ICF explicitly, LLD should merge identical
963 // comdat readonly data.
964 if (ICFLevel == 1 && !DoGC)
967 Config->DoICF = ICFLevel > 0;
969 // Handle /lldsavetemps
970 if (Args.hasArg(OPT_lldsavetemps))
971 Config->SaveTemps = true;
974 if (Args.hasArg(OPT_kill_at))
975 Config->KillAt = true;
977 // Handle /lldltocache
978 if (auto *Arg = Args.getLastArg(OPT_lldltocache))
979 Config->LTOCache = Arg->getValue();
981 // Handle /lldsavecachepolicy
982 if (auto *Arg = Args.getLastArg(OPT_lldltocachepolicy))
983 Config->LTOCachePolicy = CHECK(
984 parseCachePruningPolicy(Arg->getValue()),
985 Twine("/lldltocachepolicy: invalid cache policy: ") + Arg->getValue());
987 // Handle /failifmismatch
988 for (auto *Arg : Args.filtered(OPT_failifmismatch))
989 checkFailIfMismatch(Arg->getValue());
992 for (auto *Arg : Args.filtered(OPT_merge))
993 parseMerge(Arg->getValue());
996 for (auto *Arg : Args.filtered(OPT_section))
997 parseSection(Arg->getValue());
1000 for (auto *Arg : Args.filtered(OPT_aligncomm))
1001 parseAligncomm(Arg->getValue());
1003 // Handle /manifestdependency. This enables /manifest unless /manifest:no is
1005 if (auto *Arg = Args.getLastArg(OPT_manifestdependency)) {
1006 Config->ManifestDependency = Arg->getValue();
1007 Config->Manifest = Configuration::SideBySide;
1010 // Handle /manifest and /manifest:
1011 if (auto *Arg = Args.getLastArg(OPT_manifest, OPT_manifest_colon)) {
1012 if (Arg->getOption().getID() == OPT_manifest)
1013 Config->Manifest = Configuration::SideBySide;
1015 parseManifest(Arg->getValue());
1018 // Handle /manifestuac
1019 if (auto *Arg = Args.getLastArg(OPT_manifestuac))
1020 parseManifestUAC(Arg->getValue());
1022 // Handle /manifestfile
1023 if (auto *Arg = Args.getLastArg(OPT_manifestfile))
1024 Config->ManifestFile = Arg->getValue();
1026 // Handle /manifestinput
1027 for (auto *Arg : Args.filtered(OPT_manifestinput))
1028 Config->ManifestInput.push_back(Arg->getValue());
1030 if (!Config->ManifestInput.empty() &&
1031 Config->Manifest != Configuration::Embed) {
1032 fatal("/MANIFESTINPUT: requires /MANIFEST:EMBED");
1035 // Handle miscellaneous boolean flags.
1036 Config->AllowBind = Args.hasFlag(OPT_allowbind, OPT_allowbind_no, true);
1037 Config->AllowIsolation =
1038 Args.hasFlag(OPT_allowisolation, OPT_allowisolation_no, true);
1039 Config->NxCompat = Args.hasFlag(OPT_nxcompat, OPT_nxcompat_no, true);
1040 Config->TerminalServerAware = Args.hasFlag(OPT_tsaware, OPT_tsaware_no, true);
1041 Config->DebugDwarf = Args.hasArg(OPT_debug_dwarf);
1042 Config->DebugGHashes = Args.hasArg(OPT_debug_ghash);
1044 Config->MapFile = getMapFile(Args);
1049 bool WholeArchiveFlag = Args.hasArg(OPT_wholearchive_flag);
1050 // Create a list of input files. Files can be given as arguments
1051 // for /defaultlib option.
1052 std::vector<MemoryBufferRef> MBs;
1053 for (auto *Arg : Args.filtered(OPT_INPUT, OPT_wholearchive_file)) {
1054 switch (Arg->getOption().getID()) {
1056 if (Optional<StringRef> Path = findFile(Arg->getValue()))
1057 enqueuePath(*Path, WholeArchiveFlag);
1059 case OPT_wholearchive_file:
1060 if (Optional<StringRef> Path = findFile(Arg->getValue()))
1061 enqueuePath(*Path, true);
1065 for (auto *Arg : Args.filtered(OPT_defaultlib))
1066 if (Optional<StringRef> Path = findLib(Arg->getValue()))
1067 enqueuePath(*Path, false);
1069 // Windows specific -- Create a resource file containing a manifest file.
1070 if (Config->Manifest == Configuration::Embed)
1071 addBuffer(createManifestRes(), false);
1073 // Read all input files given via the command line.
1076 // We should have inferred a machine type by now from the input files, but if
1077 // not we assume x64.
1078 if (Config->Machine == IMAGE_FILE_MACHINE_UNKNOWN) {
1079 warn("/machine is not specified. x64 is assumed");
1080 Config->Machine = AMD64;
1083 // Input files can be Windows resource files (.res files). We use
1084 // WindowsResource to convert resource files to a regular COFF file,
1085 // then link the resulting file normally.
1086 if (!Resources.empty())
1087 Symtab->addFile(make<ObjFile>(convertResToCOFF(Resources)));
1090 Tar->append("response.txt",
1091 createResponseFile(Args, FilePaths,
1092 ArrayRef<StringRef>(SearchPaths).slice(1)));
1094 // Handle /largeaddressaware
1095 Config->LargeAddressAware = Args.hasFlag(
1096 OPT_largeaddressaware, OPT_largeaddressaware_no, Config->is64());
1098 // Handle /highentropyva
1099 Config->HighEntropyVA =
1101 Args.hasFlag(OPT_highentropyva, OPT_highentropyva_no, true);
1103 if (!Config->DynamicBase &&
1104 (Config->Machine == ARMNT || Config->Machine == ARM64))
1105 error("/dynamicbase:no is not compatible with " +
1106 machineToStr(Config->Machine));
1108 // Handle /entry and /dll
1109 if (auto *Arg = Args.getLastArg(OPT_entry)) {
1110 Config->Entry = addUndefined(mangle(Arg->getValue()));
1111 } else if (!Config->Entry && !Config->NoEntry) {
1112 if (Args.hasArg(OPT_dll)) {
1113 StringRef S = (Config->Machine == I386) ? "__DllMainCRTStartup@12"
1114 : "_DllMainCRTStartup";
1115 Config->Entry = addUndefined(S);
1117 // Windows specific -- If entry point name is not given, we need to
1118 // infer that from user-defined entry name.
1119 StringRef S = findDefaultEntry();
1121 fatal("entry point must be defined");
1122 Config->Entry = addUndefined(S);
1123 log("Entry name inferred: " + S);
1128 for (auto *Arg : Args.filtered(OPT_export)) {
1129 Export E = parseExport(Arg->getValue());
1130 if (Config->Machine == I386) {
1131 if (!isDecorated(E.Name))
1132 E.Name = Saver.save("_" + E.Name);
1133 if (!E.ExtName.empty() && !isDecorated(E.ExtName))
1134 E.ExtName = Saver.save("_" + E.ExtName);
1136 Config->Exports.push_back(E);
1140 if (auto *Arg = Args.getLastArg(OPT_deffile)) {
1141 // parseModuleDefs mutates Config object.
1142 parseModuleDefs(Arg->getValue());
1145 // Handle generation of import library from a def file.
1146 if (!Args.hasArg(OPT_INPUT)) {
1148 createImportLibrary(/*AsLib=*/true);
1152 // Handle /delayload
1153 for (auto *Arg : Args.filtered(OPT_delayload)) {
1154 Config->DelayLoads.insert(StringRef(Arg->getValue()).lower());
1155 if (Config->Machine == I386) {
1156 Config->DelayLoadHelper = addUndefined("___delayLoadHelper2@8");
1158 Config->DelayLoadHelper = addUndefined("__delayLoadHelper2");
1162 // Set default image name if neither /out or /def set it.
1163 if (Config->OutputFile.empty()) {
1164 Config->OutputFile =
1165 getOutputPath((*Args.filtered(OPT_INPUT).begin())->getValue());
1168 // Put the PDB next to the image if no /pdb flag was passed.
1169 if (ShouldCreatePDB && Config->PDBPath.empty()) {
1170 Config->PDBPath = Config->OutputFile;
1171 sys::path::replace_extension(Config->PDBPath, ".pdb");
1174 // Set default image base if /base is not given.
1175 if (Config->ImageBase == uint64_t(-1))
1176 Config->ImageBase = getDefaultImageBase();
1178 Symtab->addSynthetic(mangle("__ImageBase"), nullptr);
1179 if (Config->Machine == I386) {
1180 Symtab->addAbsolute("___safe_se_handler_table", 0);
1181 Symtab->addAbsolute("___safe_se_handler_count", 0);
1184 // We do not support /guard:cf (control flow protection) yet.
1185 // Define CFG symbols anyway so that we can link MSVC 2015 CRT.
1186 Symtab->addAbsolute(mangle("__guard_fids_count"), 0);
1187 Symtab->addAbsolute(mangle("__guard_fids_table"), 0);
1188 Symtab->addAbsolute(mangle("__guard_flags"), 0x100);
1189 Symtab->addAbsolute(mangle("__guard_iat_count"), 0);
1190 Symtab->addAbsolute(mangle("__guard_iat_table"), 0);
1191 Symtab->addAbsolute(mangle("__guard_longjmp_count"), 0);
1192 Symtab->addAbsolute(mangle("__guard_longjmp_table"), 0);
1193 // Needed for MSVC 2017 15.5 CRT.
1194 Symtab->addAbsolute(mangle("__enclave_config"), 0);
1196 // This code may add new undefined symbols to the link, which may enqueue more
1197 // symbol resolution tasks, so we need to continue executing tasks until we
1200 // Windows specific -- if entry point is not found,
1201 // search for its mangled names.
1203 Symtab->mangleMaybe(Config->Entry);
1205 // Windows specific -- Make sure we resolve all dllexported symbols.
1206 for (Export &E : Config->Exports) {
1207 if (!E.ForwardTo.empty())
1209 E.Sym = addUndefined(E.Name);
1211 Symtab->mangleMaybe(E.Sym);
1214 // Add weak aliases. Weak aliases is a mechanism to give remaining
1215 // undefined symbols final chance to be resolved successfully.
1216 for (auto Pair : Config->AlternateNames) {
1217 StringRef From = Pair.first;
1218 StringRef To = Pair.second;
1219 Symbol *Sym = Symtab->find(From);
1222 if (auto *U = dyn_cast<Undefined>(Sym))
1224 U->WeakAlias = Symtab->addUndefined(To);
1227 // Windows specific -- if __load_config_used can be resolved, resolve it.
1228 if (Symtab->findUnderscore("_load_config_used"))
1229 addUndefined(mangle("_load_config_used"));
1235 // If /msvclto is given, we use the MSVC linker to link LTO output files.
1236 // This is useful because MSVC link.exe can generate complete PDBs.
1237 if (Args.hasArg(OPT_msvclto)) {
1242 // Do LTO by compiling bitcode input files to a set of native COFF files then
1243 // link those files.
1244 Symtab->addCombinedLTOObjects();
1247 // Make sure we have resolved all symbols.
1248 Symtab->reportRemainingUndefines();
1252 // Windows specific -- if no /subsystem is given, we need to infer
1253 // that from entry point name.
1254 if (Config->Subsystem == IMAGE_SUBSYSTEM_UNKNOWN) {
1255 Config->Subsystem = inferSubsystem();
1256 if (Config->Subsystem == IMAGE_SUBSYSTEM_UNKNOWN)
1257 fatal("subsystem must be defined");
1261 if (Args.hasFlag(OPT_safeseh, OPT_safeseh_no, false)) {
1262 for (ObjFile *File : ObjFile::Instances)
1263 if (!File->SEHCompat)
1264 error("/safeseh: " + File->getName() + " is not compatible with SEH");
1269 // In MinGW, all symbols are automatically exported if no symbols
1270 // are chosen to be exported.
1271 if (Config->DLL && ((Config->MinGW && Config->Exports.empty()) ||
1272 Args.hasArg(OPT_export_all_symbols))) {
1273 AutoExporter Exporter;
1275 Symtab->forEachSymbol([=](Symbol *S) {
1276 auto *Def = dyn_cast<Defined>(S);
1277 if (!Exporter.shouldExport(Def))
1280 E.Name = Def->getName();
1282 if (Def->getChunk() &&
1283 !(Def->getChunk()->getPermissions() & IMAGE_SCN_MEM_EXECUTE))
1285 Config->Exports.push_back(E);
1289 // Windows specific -- when we are creating a .dll file, we also
1290 // need to create a .lib file.
1291 if (!Config->Exports.empty() || Config->DLL) {
1293 createImportLibrary(/*AsLib=*/false);
1294 assignExportOrdinals();
1297 // Handle /output-def (MinGW specific).
1298 if (auto *Arg = Args.getLastArg(OPT_output_def))
1299 writeDefFile(Arg->getValue());
1301 // Set extra alignment for .comm symbols
1302 for (auto Pair : Config->AlignComm) {
1303 StringRef Name = Pair.first;
1304 uint32_t Alignment = Pair.second;
1306 Symbol *Sym = Symtab->find(Name);
1308 warn("/aligncomm symbol " + Name + " not found");
1312 auto *DC = dyn_cast<DefinedCommon>(Sym);
1314 warn("/aligncomm symbol " + Name + " of wrong kind");
1318 CommonChunk *C = DC->getChunk();
1319 C->Alignment = std::max(C->Alignment, Alignment);
1322 // Windows specific -- Create a side-by-side manifest file.
1323 if (Config->Manifest == Configuration::SideBySide)
1324 createSideBySideManifest();
1326 // Identify unreferenced COMDAT sections.
1328 markLive(Symtab->getChunks());
1330 // Identify identical COMDAT sections to merge them.
1332 doICF(Symtab->getChunks());
1334 // Write the result.