1 //===- Driver.cpp ---------------------------------------------------------===//
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
13 #include "InputFiles.h"
15 #include "SymbolTable.h"
18 #include "lld/Driver/Driver.h"
19 #include "llvm/ADT/Optional.h"
20 #include "llvm/ADT/StringSwitch.h"
21 #include "llvm/Object/ArchiveWriter.h"
22 #include "llvm/Object/COFFImportFile.h"
23 #include "llvm/Object/COFFModuleDefinition.h"
24 #include "llvm/Option/Arg.h"
25 #include "llvm/Option/ArgList.h"
26 #include "llvm/Option/Option.h"
27 #include "llvm/Support/Debug.h"
28 #include "llvm/Support/Path.h"
29 #include "llvm/Support/Process.h"
30 #include "llvm/Support/TarWriter.h"
31 #include "llvm/Support/TargetSelect.h"
32 #include "llvm/Support/raw_ostream.h"
33 #include "llvm/ToolDrivers/llvm-lib/LibDriver.h"
40 using namespace llvm::object;
41 using namespace llvm::COFF;
42 using llvm::sys::Process;
43 using llvm::sys::fs::file_magic;
44 using llvm::sys::fs::identify_magic;
49 Configuration *Config;
52 BumpPtrAllocator BAlloc;
53 StringSaver Saver{BAlloc};
54 std::vector<SpecificAllocBase *> SpecificAllocBase::Instances;
56 bool link(ArrayRef<const char *> Args, raw_ostream &Diag) {
60 Config = make<Configuration>();
61 Config->ColorDiagnostics =
62 (ErrorOS == &llvm::errs() && Process::StandardErrHasColors());
63 Driver = make<LinkerDriver>();
68 // Drop directory components and replace extension with ".exe" or ".dll".
69 static std::string getOutputPath(StringRef Path) {
70 auto P = Path.find_last_of("\\/");
71 StringRef S = (P == StringRef::npos) ? Path : Path.substr(P + 1);
72 const char* E = Config->DLL ? ".dll" : ".exe";
73 return (S.substr(0, S.rfind('.')) + E).str();
76 // ErrorOr is not default constructible, so it cannot be used as the type
77 // parameter of a future.
78 // FIXME: We could open the file in createFutureForFile and avoid needing to
79 // return an error here, but for the moment that would cost us a file descriptor
80 // (a limited resource on Windows) for the duration that the future is pending.
81 typedef std::pair<std::unique_ptr<MemoryBuffer>, std::error_code> MBErrPair;
83 // Create a std::future that opens and maps a file using the best strategy for
85 static std::future<MBErrPair> createFutureForFile(std::string Path) {
87 // On Windows, file I/O is relatively slow so it is best to do this
89 auto Strategy = std::launch::async;
91 auto Strategy = std::launch::deferred;
93 return std::async(Strategy, [=]() {
94 auto MBOrErr = MemoryBuffer::getFile(Path);
96 return MBErrPair{nullptr, MBOrErr.getError()};
97 return MBErrPair{std::move(*MBOrErr), std::error_code()};
101 MemoryBufferRef LinkerDriver::takeBuffer(std::unique_ptr<MemoryBuffer> MB) {
102 MemoryBufferRef MBRef = *MB;
103 make<std::unique_ptr<MemoryBuffer>>(std::move(MB)); // take ownership
106 Driver->Tar->append(relativeToRoot(MBRef.getBufferIdentifier()),
111 void LinkerDriver::addBuffer(std::unique_ptr<MemoryBuffer> MB) {
112 MemoryBufferRef MBRef = takeBuffer(std::move(MB));
114 // File type is detected by contents, not by file extension.
115 file_magic Magic = identify_magic(MBRef.getBuffer());
116 if (Magic == file_magic::windows_resource) {
117 Resources.push_back(MBRef);
121 FilePaths.push_back(MBRef.getBufferIdentifier());
122 if (Magic == file_magic::archive)
123 return Symtab.addFile(make<ArchiveFile>(MBRef));
124 if (Magic == file_magic::bitcode)
125 return Symtab.addFile(make<BitcodeFile>(MBRef));
127 if (Magic == file_magic::coff_cl_gl_object)
128 error(MBRef.getBufferIdentifier() + ": is not a native COFF file. "
129 "Recompile without /GL");
131 Symtab.addFile(make<ObjectFile>(MBRef));
134 void LinkerDriver::enqueuePath(StringRef Path) {
136 std::make_shared<std::future<MBErrPair>>(createFutureForFile(Path));
137 std::string PathStr = Path;
139 auto MBOrErr = Future->get();
141 error("could not open " + PathStr + ": " + MBOrErr.second.message());
143 Driver->addBuffer(std::move(MBOrErr.first));
147 void LinkerDriver::addArchiveBuffer(MemoryBufferRef MB, StringRef SymName,
148 StringRef ParentName) {
149 file_magic Magic = identify_magic(MB.getBuffer());
150 if (Magic == file_magic::coff_import_library) {
151 Symtab.addFile(make<ImportFile>(MB));
156 if (Magic == file_magic::coff_object) {
157 Obj = make<ObjectFile>(MB);
158 } else if (Magic == file_magic::bitcode) {
159 Obj = make<BitcodeFile>(MB);
161 error("unknown file type: " + MB.getBufferIdentifier());
165 Obj->ParentName = ParentName;
167 log("Loaded " + toString(Obj) + " for " + SymName);
170 void LinkerDriver::enqueueArchiveMember(const Archive::Child &C,
172 StringRef ParentName) {
173 if (!C.getParent()->isThin()) {
174 MemoryBufferRef MB = check(
175 C.getMemoryBufferRef(),
176 "could not get the buffer for the member defining symbol " + SymName);
177 enqueueTask([=]() { Driver->addArchiveBuffer(MB, SymName, ParentName); });
181 auto Future = std::make_shared<std::future<MBErrPair>>(createFutureForFile(
182 check(C.getFullName(),
183 "could not get the filename for the member defining symbol " +
186 auto MBOrErr = Future->get();
188 fatal(MBOrErr.second,
189 "could not get the buffer for the member defining " + SymName);
190 Driver->addArchiveBuffer(takeBuffer(std::move(MBOrErr.first)), SymName,
195 static bool isDecorated(StringRef Sym) {
196 return Sym.startswith("_") || Sym.startswith("@") || Sym.startswith("?");
199 // Parses .drectve section contents and returns a list of files
200 // specified by /defaultlib.
201 void LinkerDriver::parseDirectives(StringRef S) {
202 opt::InputArgList Args = Parser.parse(S);
204 for (auto *Arg : Args) {
205 switch (Arg->getOption().getID()) {
206 case OPT_alternatename:
207 parseAlternateName(Arg->getValue());
210 if (Optional<StringRef> Path = findLib(Arg->getValue()))
214 Export E = parseExport(Arg->getValue());
216 Config->Exports.push_back(E);
219 case OPT_failifmismatch:
220 checkFailIfMismatch(Arg->getValue());
223 addUndefined(Arg->getValue());
226 parseMerge(Arg->getValue());
228 case OPT_nodefaultlib:
229 Config->NoDefaultLibs.insert(doFindLib(Arg->getValue()));
232 parseSection(Arg->getValue());
234 case OPT_editandcontinue:
237 case OPT_throwingnew:
240 error(Arg->getSpelling() + " is not allowed in .drectve");
245 // Find file from search paths. You can omit ".obj", this function takes
246 // care of that. Note that the returned path is not guaranteed to exist.
247 StringRef LinkerDriver::doFindFile(StringRef Filename) {
248 bool HasPathSep = (Filename.find_first_of("/\\") != StringRef::npos);
251 bool HasExt = (Filename.find('.') != StringRef::npos);
252 for (StringRef Dir : SearchPaths) {
253 SmallString<128> Path = Dir;
254 sys::path::append(Path, Filename);
255 if (sys::fs::exists(Path.str()))
256 return Saver.save(Path.str());
259 if (sys::fs::exists(Path.str()))
260 return Saver.save(Path.str());
266 // Resolves a file path. This never returns the same path
267 // (in that case, it returns None).
268 Optional<StringRef> LinkerDriver::findFile(StringRef Filename) {
269 StringRef Path = doFindFile(Filename);
270 bool Seen = !VisitedFiles.insert(Path.lower()).second;
276 // Find library file from search path.
277 StringRef LinkerDriver::doFindLib(StringRef Filename) {
278 // Add ".lib" to Filename if that has no file extension.
279 bool HasExt = (Filename.find('.') != StringRef::npos);
281 Filename = Saver.save(Filename + ".lib");
282 return doFindFile(Filename);
285 // Resolves a library path. /nodefaultlib options are taken into
286 // consideration. This never returns the same path (in that case,
288 Optional<StringRef> LinkerDriver::findLib(StringRef Filename) {
289 if (Config->NoDefaultLibAll)
291 if (!VisitedLibs.insert(Filename.lower()).second)
293 StringRef Path = doFindLib(Filename);
294 if (Config->NoDefaultLibs.count(Path))
296 if (!VisitedFiles.insert(Path.lower()).second)
301 // Parses LIB environment which contains a list of search paths.
302 void LinkerDriver::addLibSearchPaths() {
303 Optional<std::string> EnvOpt = Process::GetEnv("LIB");
304 if (!EnvOpt.hasValue())
306 StringRef Env = Saver.save(*EnvOpt);
307 while (!Env.empty()) {
309 std::tie(Path, Env) = Env.split(';');
310 SearchPaths.push_back(Path);
314 SymbolBody *LinkerDriver::addUndefined(StringRef Name) {
315 SymbolBody *B = Symtab.addUndefined(Name);
316 Config->GCRoot.insert(B);
320 // Symbol names are mangled by appending "_" prefix on x86.
321 StringRef LinkerDriver::mangle(StringRef Sym) {
322 assert(Config->Machine != IMAGE_FILE_MACHINE_UNKNOWN);
323 if (Config->Machine == I386)
324 return Saver.save("_" + Sym);
328 // Windows specific -- find default entry point name.
329 StringRef LinkerDriver::findDefaultEntry() {
330 // User-defined main functions and their corresponding entry points.
331 static const char *Entries[][2] = {
332 {"main", "mainCRTStartup"},
333 {"wmain", "wmainCRTStartup"},
334 {"WinMain", "WinMainCRTStartup"},
335 {"wWinMain", "wWinMainCRTStartup"},
337 for (auto E : Entries) {
338 StringRef Entry = Symtab.findMangle(mangle(E[0]));
339 if (!Entry.empty() && !isa<Undefined>(Symtab.find(Entry)->body()))
345 WindowsSubsystem LinkerDriver::inferSubsystem() {
347 return IMAGE_SUBSYSTEM_WINDOWS_GUI;
348 if (Symtab.findUnderscore("main") || Symtab.findUnderscore("wmain"))
349 return IMAGE_SUBSYSTEM_WINDOWS_CUI;
350 if (Symtab.findUnderscore("WinMain") || Symtab.findUnderscore("wWinMain"))
351 return IMAGE_SUBSYSTEM_WINDOWS_GUI;
352 return IMAGE_SUBSYSTEM_UNKNOWN;
355 static uint64_t getDefaultImageBase() {
357 return Config->DLL ? 0x180000000 : 0x140000000;
358 return Config->DLL ? 0x10000000 : 0x400000;
361 static std::string createResponseFile(const opt::InputArgList &Args,
362 ArrayRef<StringRef> FilePaths,
363 ArrayRef<StringRef> SearchPaths) {
365 raw_svector_ostream OS(Data);
367 for (auto *Arg : Args) {
368 switch (Arg->getOption().getID()) {
375 OS << toString(Arg) << "\n";
379 for (StringRef Path : SearchPaths) {
380 std::string RelPath = relativeToRoot(Path);
381 OS << "/libpath:" << quote(RelPath) << "\n";
384 for (StringRef Path : FilePaths)
385 OS << quote(relativeToRoot(Path)) << "\n";
390 static unsigned getDefaultDebugType(const opt::InputArgList &Args) {
391 unsigned DebugTypes = static_cast<unsigned>(DebugType::CV);
392 if (Args.hasArg(OPT_driver))
393 DebugTypes |= static_cast<unsigned>(DebugType::PData);
394 if (Args.hasArg(OPT_profile))
395 DebugTypes |= static_cast<unsigned>(DebugType::Fixup);
399 static unsigned parseDebugType(StringRef Arg) {
400 SmallVector<StringRef, 3> Types;
401 Arg.split(Types, ',', /*KeepEmpty=*/false);
403 unsigned DebugTypes = static_cast<unsigned>(DebugType::None);
404 for (StringRef Type : Types)
405 DebugTypes |= StringSwitch<unsigned>(Type.lower())
406 .Case("cv", static_cast<unsigned>(DebugType::CV))
407 .Case("pdata", static_cast<unsigned>(DebugType::PData))
408 .Case("fixup", static_cast<unsigned>(DebugType::Fixup))
413 static std::string getMapFile(const opt::InputArgList &Args) {
414 auto *Arg = Args.getLastArg(OPT_lldmap, OPT_lldmap_file);
417 if (Arg->getOption().getID() == OPT_lldmap_file)
418 return Arg->getValue();
420 assert(Arg->getOption().getID() == OPT_lldmap);
421 StringRef OutFile = Config->OutputFile;
422 return (OutFile.substr(0, OutFile.rfind('.')) + ".map").str();
425 static std::string getImplibPath() {
426 if (!Config->Implib.empty())
427 return Config->Implib;
428 SmallString<128> Out = StringRef(Config->OutputFile);
429 sys::path::replace_extension(Out, ".lib");
433 std::vector<COFFShortExport> createCOFFShortExportFromConfig() {
434 std::vector<COFFShortExport> Exports;
435 for (Export &E1 : Config->Exports) {
437 // Use SymbolName, which will have any stdcall or fastcall qualifiers.
438 E2.Name = E1.SymbolName;
439 E2.ExtName = E1.ExtName;
440 E2.Ordinal = E1.Ordinal;
441 E2.Noname = E1.Noname;
443 E2.Private = E1.Private;
444 E2.Constant = E1.Constant;
445 Exports.push_back(E2);
450 static void createImportLibrary() {
451 std::vector<COFFShortExport> Exports = createCOFFShortExportFromConfig();
452 std::string DLLName = sys::path::filename(Config->OutputFile);
453 std::string Path = getImplibPath();
454 writeImportLibrary(DLLName, Path, Exports, Config->Machine);
457 static void parseModuleDefs(StringRef Path) {
458 std::unique_ptr<MemoryBuffer> MB = check(
459 MemoryBuffer::getFile(Path, -1, false, true), "could not open " + Path);
460 MemoryBufferRef MBRef = MB->getMemBufferRef();
462 Expected<COFFModuleDefinition> Def =
463 parseCOFFModuleDefinition(MBRef, Config->Machine);
465 fatal(errorToErrorCode(Def.takeError()).message());
467 COFFModuleDefinition &M = *Def;
468 if (Config->OutputFile.empty())
469 Config->OutputFile = Saver.save(M.OutputFile);
472 Config->ImageBase = M.ImageBase;
474 Config->StackReserve = M.StackReserve;
476 Config->StackCommit = M.StackCommit;
478 Config->HeapReserve = M.HeapReserve;
480 Config->HeapCommit = M.HeapCommit;
481 if (M.MajorImageVersion)
482 Config->MajorImageVersion = M.MajorImageVersion;
483 if (M.MinorImageVersion)
484 Config->MinorImageVersion = M.MinorImageVersion;
485 if (M.MajorOSVersion)
486 Config->MajorOSVersion = M.MajorOSVersion;
487 if (M.MinorOSVersion)
488 Config->MinorOSVersion = M.MinorOSVersion;
490 for (COFFShortExport E1 : M.Exports) {
492 E2.Name = Saver.save(E1.Name);
494 E2.ExtName = Saver.save(E1.ExtName);
495 E2.Ordinal = E1.Ordinal;
496 E2.Noname = E1.Noname;
498 E2.Private = E1.Private;
499 E2.Constant = E1.Constant;
500 Config->Exports.push_back(E2);
504 std::vector<MemoryBufferRef> getArchiveMembers(Archive *File) {
505 std::vector<MemoryBufferRef> V;
506 Error Err = Error::success();
507 for (const ErrorOr<Archive::Child> &COrErr : File->children(Err)) {
510 File->getFileName() + ": could not get the child of the archive");
511 MemoryBufferRef MBRef =
512 check(C.getMemoryBufferRef(),
513 File->getFileName() +
514 ": could not get the buffer for a child of the archive");
518 fatal(File->getFileName() +
519 ": Archive::children failed: " + toString(std::move(Err)));
523 // A helper function for filterBitcodeFiles.
524 static bool needsRebuilding(MemoryBufferRef MB) {
525 // The MSVC linker doesn't support thin archives, so if it's a thin
526 // archive, we always need to rebuild it.
527 std::unique_ptr<Archive> File =
528 check(Archive::create(MB), "Failed to read " + MB.getBufferIdentifier());
532 // Returns true if the archive contains at least one bitcode file.
533 for (MemoryBufferRef Member : getArchiveMembers(File.get()))
534 if (identify_magic(Member.getBuffer()) == file_magic::bitcode)
539 // Opens a given path as an archive file and removes bitcode files
540 // from them if exists. This function is to appease the MSVC linker as
541 // their linker doesn't like archive files containing non-native
544 // If a given archive doesn't contain bitcode files, the archive path
545 // is returned as-is. Otherwise, a new temporary file is created and
546 // its path is returned.
547 static Optional<std::string>
548 filterBitcodeFiles(StringRef Path, std::vector<std::string> &TemporaryFiles) {
549 std::unique_ptr<MemoryBuffer> MB = check(
550 MemoryBuffer::getFile(Path, -1, false, true), "could not open " + Path);
551 MemoryBufferRef MBRef = MB->getMemBufferRef();
552 file_magic Magic = identify_magic(MBRef.getBuffer());
554 if (Magic == file_magic::bitcode)
556 if (Magic != file_magic::archive)
558 if (!needsRebuilding(MBRef))
561 std::unique_ptr<Archive> File =
562 check(Archive::create(MBRef),
563 MBRef.getBufferIdentifier() + ": failed to parse archive");
565 std::vector<NewArchiveMember> New;
566 for (MemoryBufferRef Member : getArchiveMembers(File.get()))
567 if (identify_magic(Member.getBuffer()) != file_magic::bitcode)
568 New.emplace_back(Member);
573 log("Creating a temporary archive for " + Path + " to remove bitcode files");
576 if (auto EC = sys::fs::createTemporaryFile("lld-" + sys::path::stem(Path),
578 fatal(EC, "cannot create a temporary file");
579 std::string Temp = S.str();
580 TemporaryFiles.push_back(Temp);
582 std::pair<StringRef, std::error_code> Ret =
583 llvm::writeArchive(Temp, New, /*WriteSymtab=*/true, Archive::Kind::K_GNU,
584 /*Deterministics=*/true,
587 error("failed to create a new archive " + S.str() + ": " + Ret.first);
591 // Create response file contents and invoke the MSVC linker.
592 void LinkerDriver::invokeMSVC(opt::InputArgList &Args) {
593 std::string Rsp = "/nologo\n";
594 std::vector<std::string> Temps;
596 // Write out archive members that we used in symbol resolution and pass these
597 // to MSVC before any archives, so that MSVC uses the same objects to satisfy
599 for (const auto *O : Symtab.ObjectFiles) {
600 if (O->ParentName.empty())
604 if (auto EC = sys::fs::createTemporaryFile(
605 "lld-" + sys::path::filename(O->ParentName), ".obj", Fd, S))
606 fatal(EC, "cannot create a temporary file");
607 raw_fd_ostream OS(Fd, /*shouldClose*/ true);
608 OS << O->MB.getBuffer();
609 Temps.push_back(S.str());
610 Rsp += quote(S) + "\n";
613 for (auto *Arg : Args) {
614 switch (Arg->getOption().getID()) {
617 case OPT_lldmap_file:
618 case OPT_lldsavetemps:
620 // LLD-specific options are stripped.
623 if (!StringRef(Arg->getValue()).startswith("lld"))
624 Rsp += toString(Arg) + " ";
627 if (Optional<StringRef> Path = doFindFile(Arg->getValue())) {
628 if (Optional<std::string> S = filterBitcodeFiles(*Path, Temps))
629 Rsp += quote(*S) + "\n";
632 Rsp += quote(Arg->getValue()) + "\n";
636 Rsp += toString(Arg) + "\n";
640 std::vector<StringRef> ObjectFiles = Symtab.compileBitcodeFiles();
641 runMSVCLinker(Rsp, ObjectFiles);
643 for (StringRef Path : Temps)
644 sys::fs::remove(Path);
647 void LinkerDriver::enqueueTask(std::function<void()> Task) {
648 TaskQueue.push_back(std::move(Task));
651 bool LinkerDriver::run() {
652 bool DidWork = !TaskQueue.empty();
653 while (!TaskQueue.empty()) {
655 TaskQueue.pop_front();
660 void LinkerDriver::link(ArrayRef<const char *> ArgsArr) {
661 // If the first command line argument is "/lib", link.exe acts like lib.exe.
662 // We call our own implementation of lib.exe that understands bitcode files.
663 if (ArgsArr.size() > 1 && StringRef(ArgsArr[1]).equals_lower("/lib")) {
664 if (llvm::libDriverMain(ArgsArr.slice(1)) != 0)
670 InitializeAllTargetInfos();
671 InitializeAllTargets();
672 InitializeAllTargetMCs();
673 InitializeAllAsmParsers();
674 InitializeAllAsmPrinters();
675 InitializeAllDisassemblers();
677 // Parse command line options.
678 opt::InputArgList Args = Parser.parseLINK(ArgsArr.slice(1));
680 // Parse and evaluate -mllvm options.
681 std::vector<const char *> V;
682 V.push_back("lld-link (LLVM option parsing)");
683 for (auto *Arg : Args.filtered(OPT_mllvm))
684 V.push_back(Arg->getValue());
685 cl::ParseCommandLineOptions(V.size(), V.data());
687 // Handle /errorlimit early, because error() depends on it.
688 if (auto *Arg = Args.getLastArg(OPT_errorlimit)) {
690 StringRef S = Arg->getValue();
691 if (S.getAsInteger(10, N))
692 error(Arg->getSpelling() + " number expected, but got " + S);
693 Config->ErrorLimit = N;
697 if (Args.hasArg(OPT_help)) {
698 printHelp(ArgsArr[0]);
702 if (auto *Arg = Args.getLastArg(OPT_linkrepro)) {
703 SmallString<64> Path = StringRef(Arg->getValue());
704 sys::path::append(Path, "repro.tar");
706 Expected<std::unique_ptr<TarWriter>> ErrOrWriter =
707 TarWriter::create(Path, "repro");
710 Tar = std::move(*ErrOrWriter);
712 error("/linkrepro: failed to open " + Path + ": " +
713 toString(ErrOrWriter.takeError()));
717 if (!Args.hasArgNoClaim(OPT_INPUT))
718 fatal("no input files");
720 // Construct search path list.
721 SearchPaths.push_back("");
722 for (auto *Arg : Args.filtered(OPT_libpath))
723 SearchPaths.push_back(Arg->getValue());
727 if (auto *Arg = Args.getLastArg(OPT_out))
728 Config->OutputFile = Arg->getValue();
731 if (Args.hasArg(OPT_verbose))
732 Config->Verbose = true;
734 // Handle /force or /force:unresolved
735 if (Args.hasArg(OPT_force) || Args.hasArg(OPT_force_unresolved))
736 Config->Force = true;
739 if (Args.hasArg(OPT_debug)) {
740 Config->Debug = true;
742 Args.hasArg(OPT_debugtype)
743 ? parseDebugType(Args.getLastArg(OPT_debugtype)->getValue())
744 : getDefaultDebugType(Args);
747 // Create a dummy PDB file to satisfy build sytem rules.
748 if (auto *Arg = Args.getLastArg(OPT_pdb))
749 Config->PDBPath = Arg->getValue();
752 if (Args.hasArg(OPT_noentry)) {
753 if (Args.hasArg(OPT_dll))
754 Config->NoEntry = true;
756 error("/noentry must be specified with /dll");
760 if (Args.hasArg(OPT_dll)) {
762 Config->ManifestID = 2;
766 if (Args.hasArg(OPT_fixed)) {
767 if (Args.hasArg(OPT_dynamicbase)) {
768 error("/fixed must not be specified with /dynamicbase");
770 Config->Relocatable = false;
771 Config->DynamicBase = false;
775 if (Args.hasArg(OPT_appcontainer))
776 Config->AppContainer = true;
779 if (auto *Arg = Args.getLastArg(OPT_machine))
780 Config->Machine = getMachineType(Arg->getValue());
782 // Handle /nodefaultlib:<filename>
783 for (auto *Arg : Args.filtered(OPT_nodefaultlib))
784 Config->NoDefaultLibs.insert(doFindLib(Arg->getValue()));
786 // Handle /nodefaultlib
787 if (Args.hasArg(OPT_nodefaultlib_all))
788 Config->NoDefaultLibAll = true;
791 if (auto *Arg = Args.getLastArg(OPT_base))
792 parseNumbers(Arg->getValue(), &Config->ImageBase);
795 if (auto *Arg = Args.getLastArg(OPT_stack))
796 parseNumbers(Arg->getValue(), &Config->StackReserve, &Config->StackCommit);
799 if (auto *Arg = Args.getLastArg(OPT_heap))
800 parseNumbers(Arg->getValue(), &Config->HeapReserve, &Config->HeapCommit);
803 if (auto *Arg = Args.getLastArg(OPT_version))
804 parseVersion(Arg->getValue(), &Config->MajorImageVersion,
805 &Config->MinorImageVersion);
808 if (auto *Arg = Args.getLastArg(OPT_subsystem))
809 parseSubsystem(Arg->getValue(), &Config->Subsystem, &Config->MajorOSVersion,
810 &Config->MinorOSVersion);
812 // Handle /alternatename
813 for (auto *Arg : Args.filtered(OPT_alternatename))
814 parseAlternateName(Arg->getValue());
817 for (auto *Arg : Args.filtered(OPT_incl))
818 addUndefined(Arg->getValue());
821 if (auto *Arg = Args.getLastArg(OPT_implib))
822 Config->Implib = Arg->getValue();
825 for (auto *Arg : Args.filtered(OPT_opt)) {
826 std::string Str = StringRef(Arg->getValue()).lower();
827 SmallVector<StringRef, 1> Vec;
828 StringRef(Str).split(Vec, ',');
829 for (StringRef S : Vec) {
831 Config->DoGC = false;
832 Config->DoICF = false;
835 if (S == "icf" || StringRef(S).startswith("icf=")) {
836 Config->DoICF = true;
840 Config->DoICF = false;
843 if (StringRef(S).startswith("lldlto=")) {
844 StringRef OptLevel = StringRef(S).substr(7);
845 if (OptLevel.getAsInteger(10, Config->LTOOptLevel) ||
846 Config->LTOOptLevel > 3)
847 error("/opt:lldlto: invalid optimization level: " + OptLevel);
850 if (StringRef(S).startswith("lldltojobs=")) {
851 StringRef Jobs = StringRef(S).substr(11);
852 if (Jobs.getAsInteger(10, Config->LTOJobs) || Config->LTOJobs == 0)
853 error("/opt:lldltojobs: invalid job count: " + Jobs);
856 if (StringRef(S).startswith("lldltopartitions=")) {
857 StringRef N = StringRef(S).substr(17);
858 if (N.getAsInteger(10, Config->LTOPartitions) ||
859 Config->LTOPartitions == 0)
860 error("/opt:lldltopartitions: invalid partition count: " + N);
863 if (S != "ref" && S != "lbr" && S != "nolbr")
864 error("/opt: unknown option: " + S);
868 // Handle /lldsavetemps
869 if (Args.hasArg(OPT_lldsavetemps))
870 Config->SaveTemps = true;
872 // Handle /failifmismatch
873 for (auto *Arg : Args.filtered(OPT_failifmismatch))
874 checkFailIfMismatch(Arg->getValue());
877 for (auto *Arg : Args.filtered(OPT_merge))
878 parseMerge(Arg->getValue());
881 for (auto *Arg : Args.filtered(OPT_section))
882 parseSection(Arg->getValue());
885 if (auto *Arg = Args.getLastArg(OPT_manifest_colon))
886 parseManifest(Arg->getValue());
888 // Handle /manifestuac
889 if (auto *Arg = Args.getLastArg(OPT_manifestuac))
890 parseManifestUAC(Arg->getValue());
892 // Handle /manifestdependency
893 if (auto *Arg = Args.getLastArg(OPT_manifestdependency))
894 Config->ManifestDependency = Arg->getValue();
896 // Handle /manifestfile
897 if (auto *Arg = Args.getLastArg(OPT_manifestfile))
898 Config->ManifestFile = Arg->getValue();
900 // Handle /manifestinput
901 for (auto *Arg : Args.filtered(OPT_manifestinput))
902 Config->ManifestInput.push_back(Arg->getValue());
904 // Handle miscellaneous boolean flags.
905 if (Args.hasArg(OPT_allowisolation_no))
906 Config->AllowIsolation = false;
907 if (Args.hasArg(OPT_dynamicbase_no))
908 Config->DynamicBase = false;
909 if (Args.hasArg(OPT_nxcompat_no))
910 Config->NxCompat = false;
911 if (Args.hasArg(OPT_tsaware_no))
912 Config->TerminalServerAware = false;
913 if (Args.hasArg(OPT_nosymtab))
914 Config->WriteSymtab = false;
915 Config->DumpPdb = Args.hasArg(OPT_dumppdb);
917 Config->MapFile = getMapFile(Args);
922 // Create a list of input files. Files can be given as arguments
923 // for /defaultlib option.
924 std::vector<MemoryBufferRef> MBs;
925 for (auto *Arg : Args.filtered(OPT_INPUT))
926 if (Optional<StringRef> Path = findFile(Arg->getValue()))
928 for (auto *Arg : Args.filtered(OPT_defaultlib))
929 if (Optional<StringRef> Path = findLib(Arg->getValue()))
932 // Windows specific -- Create a resource file containing a manifest file.
933 if (Config->Manifest == Configuration::Embed)
934 addBuffer(createManifestRes());
936 // Read all input files given via the command line.
939 // We should have inferred a machine type by now from the input files, but if
940 // not we assume x64.
941 if (Config->Machine == IMAGE_FILE_MACHINE_UNKNOWN) {
942 warn("/machine is not specified. x64 is assumed");
943 Config->Machine = AMD64;
946 // Windows specific -- Input files can be Windows resource files (.res files).
947 // We invoke cvtres.exe to convert resource files to a regular COFF file
948 // then link the result file normally.
949 if (!Resources.empty())
950 addBuffer(convertResToCOFF(Resources));
953 Tar->append("response.txt",
954 createResponseFile(Args, FilePaths,
955 ArrayRef<StringRef>(SearchPaths).slice(1)));
957 // Handle /largeaddressaware
958 if (Config->is64() || Args.hasArg(OPT_largeaddressaware))
959 Config->LargeAddressAware = true;
961 // Handle /highentropyva
962 if (Config->is64() && !Args.hasArg(OPT_highentropyva_no))
963 Config->HighEntropyVA = true;
965 // Handle /entry and /dll
966 if (auto *Arg = Args.getLastArg(OPT_entry)) {
967 Config->Entry = addUndefined(mangle(Arg->getValue()));
968 } else if (Args.hasArg(OPT_dll) && !Config->NoEntry) {
969 StringRef S = (Config->Machine == I386) ? "__DllMainCRTStartup@12"
970 : "_DllMainCRTStartup";
971 Config->Entry = addUndefined(S);
972 } else if (!Config->NoEntry) {
973 // Windows specific -- If entry point name is not given, we need to
974 // infer that from user-defined entry name.
975 StringRef S = findDefaultEntry();
977 fatal("entry point must be defined");
978 Config->Entry = addUndefined(S);
979 log("Entry name inferred: " + S);
983 for (auto *Arg : Args.filtered(OPT_export)) {
984 Export E = parseExport(Arg->getValue());
985 if (Config->Machine == I386) {
986 if (!isDecorated(E.Name))
987 E.Name = Saver.save("_" + E.Name);
988 if (!E.ExtName.empty() && !isDecorated(E.ExtName))
989 E.ExtName = Saver.save("_" + E.ExtName);
991 Config->Exports.push_back(E);
995 if (auto *Arg = Args.getLastArg(OPT_deffile)) {
996 // parseModuleDefs mutates Config object.
997 parseModuleDefs(Arg->getValue());
1000 // Handle /delayload
1001 for (auto *Arg : Args.filtered(OPT_delayload)) {
1002 Config->DelayLoads.insert(StringRef(Arg->getValue()).lower());
1003 if (Config->Machine == I386) {
1004 Config->DelayLoadHelper = addUndefined("___delayLoadHelper2@8");
1006 Config->DelayLoadHelper = addUndefined("__delayLoadHelper2");
1010 // Set default image name if neither /out or /def set it.
1011 if (Config->OutputFile.empty()) {
1012 Config->OutputFile =
1013 getOutputPath((*Args.filtered(OPT_INPUT).begin())->getValue());
1016 // Put the PDB next to the image if no /pdb flag was passed.
1017 if (Config->Debug && Config->PDBPath.empty()) {
1018 Config->PDBPath = Config->OutputFile;
1019 sys::path::replace_extension(Config->PDBPath, ".pdb");
1022 // Disable PDB generation if the user requested it.
1023 if (Args.hasArg(OPT_nopdb))
1024 Config->PDBPath = "";
1026 // Set default image base if /base is not given.
1027 if (Config->ImageBase == uint64_t(-1))
1028 Config->ImageBase = getDefaultImageBase();
1030 Symtab.addRelative(mangle("__ImageBase"), 0);
1031 if (Config->Machine == I386) {
1032 Config->SEHTable = Symtab.addRelative("___safe_se_handler_table", 0);
1033 Config->SEHCount = Symtab.addAbsolute("___safe_se_handler_count", 0);
1036 // We do not support /guard:cf (control flow protection) yet.
1037 // Define CFG symbols anyway so that we can link MSVC 2015 CRT.
1038 Symtab.addAbsolute(mangle("__guard_fids_table"), 0);
1039 Symtab.addAbsolute(mangle("__guard_fids_count"), 0);
1040 Symtab.addAbsolute(mangle("__guard_flags"), 0x100);
1042 // This code may add new undefined symbols to the link, which may enqueue more
1043 // symbol resolution tasks, so we need to continue executing tasks until we
1046 // Windows specific -- if entry point is not found,
1047 // search for its mangled names.
1049 Symtab.mangleMaybe(Config->Entry);
1051 // Windows specific -- Make sure we resolve all dllexported symbols.
1052 for (Export &E : Config->Exports) {
1053 if (!E.ForwardTo.empty())
1055 E.Sym = addUndefined(E.Name);
1057 Symtab.mangleMaybe(E.Sym);
1060 // Add weak aliases. Weak aliases is a mechanism to give remaining
1061 // undefined symbols final chance to be resolved successfully.
1062 for (auto Pair : Config->AlternateNames) {
1063 StringRef From = Pair.first;
1064 StringRef To = Pair.second;
1065 Symbol *Sym = Symtab.find(From);
1068 if (auto *U = dyn_cast<Undefined>(Sym->body()))
1070 U->WeakAlias = Symtab.addUndefined(To);
1073 // Windows specific -- if __load_config_used can be resolved, resolve it.
1074 if (Symtab.findUnderscore("_load_config_used"))
1075 addUndefined(mangle("_load_config_used"));
1081 // If /msvclto is given, we use the MSVC linker to link LTO output files.
1082 // This is useful because MSVC link.exe can generate complete PDBs.
1083 if (Args.hasArg(OPT_msvclto)) {
1088 // Do LTO by compiling bitcode input files to a set of native COFF files then
1089 // link those files.
1090 Symtab.addCombinedLTOObjects();
1093 // Make sure we have resolved all symbols.
1094 Symtab.reportRemainingUndefines();
1096 // Windows specific -- if no /subsystem is given, we need to infer
1097 // that from entry point name.
1098 if (Config->Subsystem == IMAGE_SUBSYSTEM_UNKNOWN) {
1099 Config->Subsystem = inferSubsystem();
1100 if (Config->Subsystem == IMAGE_SUBSYSTEM_UNKNOWN)
1101 fatal("subsystem must be defined");
1105 if (Args.hasArg(OPT_safeseh)) {
1106 for (ObjectFile *File : Symtab.ObjectFiles)
1107 if (!File->SEHCompat)
1108 error("/safeseh: " + File->getName() + " is not compatible with SEH");
1113 // Windows specific -- when we are creating a .dll file, we also
1114 // need to create a .lib file.
1115 if (!Config->Exports.empty() || Config->DLL) {
1117 createImportLibrary();
1118 assignExportOrdinals();
1121 // Windows specific -- Create a side-by-side manifest file.
1122 if (Config->Manifest == Configuration::SideBySide)
1123 createSideBySideManifest();
1125 // Identify unreferenced COMDAT sections.
1127 markLive(Symtab.getChunks());
1129 // Identify identical COMDAT sections to merge them.
1131 doICF(Symtab.getChunks());
1133 // Write the result.
1134 writeResult(&Symtab);
1136 // Call exit to avoid calling destructors.