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) {
438 E2.ExtName = E1.ExtName;
439 E2.Ordinal = E1.Ordinal;
440 E2.Noname = E1.Noname;
442 E2.Private = E1.Private;
443 E2.Constant = E1.Constant;
444 Exports.push_back(E2);
449 static void createImportLibrary() {
450 std::vector<COFFShortExport> Exports = createCOFFShortExportFromConfig();
451 std::string DLLName = sys::path::filename(Config->OutputFile);
452 std::string Path = getImplibPath();
453 writeImportLibrary(DLLName, Path, Exports, Config->Machine);
456 static void parseModuleDefs(StringRef Path) {
457 std::unique_ptr<MemoryBuffer> MB = check(
458 MemoryBuffer::getFile(Path, -1, false, true), "could not open " + Path);
459 MemoryBufferRef MBRef = MB->getMemBufferRef();
461 Expected<COFFModuleDefinition> Def =
462 parseCOFFModuleDefinition(MBRef, Config->Machine);
464 fatal(errorToErrorCode(Def.takeError()).message());
466 COFFModuleDefinition &M = *Def;
467 if (Config->OutputFile.empty())
468 Config->OutputFile = Saver.save(M.OutputFile);
471 Config->ImageBase = M.ImageBase;
473 Config->StackReserve = M.StackReserve;
475 Config->StackCommit = M.StackCommit;
477 Config->HeapReserve = M.HeapReserve;
479 Config->HeapCommit = M.HeapCommit;
480 if (M.MajorImageVersion)
481 Config->MajorImageVersion = M.MajorImageVersion;
482 if (M.MinorImageVersion)
483 Config->MinorImageVersion = M.MinorImageVersion;
484 if (M.MajorOSVersion)
485 Config->MajorOSVersion = M.MajorOSVersion;
486 if (M.MinorOSVersion)
487 Config->MinorOSVersion = M.MinorOSVersion;
489 for (COFFShortExport E1 : M.Exports) {
491 E2.Name = Saver.save(E1.Name);
493 E2.ExtName = Saver.save(E1.ExtName);
494 E2.Ordinal = E1.Ordinal;
495 E2.Noname = E1.Noname;
497 E2.Private = E1.Private;
498 E2.Constant = E1.Constant;
499 Config->Exports.push_back(E2);
503 std::vector<MemoryBufferRef> getArchiveMembers(Archive *File) {
504 std::vector<MemoryBufferRef> V;
505 Error Err = Error::success();
506 for (const ErrorOr<Archive::Child> &COrErr : File->children(Err)) {
509 File->getFileName() + ": could not get the child of the archive");
510 MemoryBufferRef MBRef =
511 check(C.getMemoryBufferRef(),
512 File->getFileName() +
513 ": could not get the buffer for a child of the archive");
517 fatal(File->getFileName() +
518 ": Archive::children failed: " + toString(std::move(Err)));
522 // A helper function for filterBitcodeFiles.
523 static bool needsRebuilding(MemoryBufferRef MB) {
524 // The MSVC linker doesn't support thin archives, so if it's a thin
525 // archive, we always need to rebuild it.
526 std::unique_ptr<Archive> File =
527 check(Archive::create(MB), "Failed to read " + MB.getBufferIdentifier());
531 // Returns true if the archive contains at least one bitcode file.
532 for (MemoryBufferRef Member : getArchiveMembers(File.get()))
533 if (identify_magic(Member.getBuffer()) == file_magic::bitcode)
538 // Opens a given path as an archive file and removes bitcode files
539 // from them if exists. This function is to appease the MSVC linker as
540 // their linker doesn't like archive files containing non-native
543 // If a given archive doesn't contain bitcode files, the archive path
544 // is returned as-is. Otherwise, a new temporary file is created and
545 // its path is returned.
546 static Optional<std::string>
547 filterBitcodeFiles(StringRef Path, std::vector<std::string> &TemporaryFiles) {
548 std::unique_ptr<MemoryBuffer> MB = check(
549 MemoryBuffer::getFile(Path, -1, false, true), "could not open " + Path);
550 MemoryBufferRef MBRef = MB->getMemBufferRef();
551 file_magic Magic = identify_magic(MBRef.getBuffer());
553 if (Magic == file_magic::bitcode)
555 if (Magic != file_magic::archive)
557 if (!needsRebuilding(MBRef))
560 std::unique_ptr<Archive> File =
561 check(Archive::create(MBRef),
562 MBRef.getBufferIdentifier() + ": failed to parse archive");
564 std::vector<NewArchiveMember> New;
565 for (MemoryBufferRef Member : getArchiveMembers(File.get()))
566 if (identify_magic(Member.getBuffer()) != file_magic::bitcode)
567 New.emplace_back(Member);
572 log("Creating a temporary archive for " + Path + " to remove bitcode files");
575 if (auto EC = sys::fs::createTemporaryFile("lld-" + sys::path::stem(Path),
577 fatal(EC, "cannot create a temporary file");
578 std::string Temp = S.str();
579 TemporaryFiles.push_back(Temp);
581 std::pair<StringRef, std::error_code> Ret =
582 llvm::writeArchive(Temp, New, /*WriteSymtab=*/true, Archive::Kind::K_GNU,
583 /*Deterministics=*/true,
586 error("failed to create a new archive " + S.str() + ": " + Ret.first);
590 // Create response file contents and invoke the MSVC linker.
591 void LinkerDriver::invokeMSVC(opt::InputArgList &Args) {
592 std::string Rsp = "/nologo\n";
593 std::vector<std::string> Temps;
595 // Write out archive members that we used in symbol resolution and pass these
596 // to MSVC before any archives, so that MSVC uses the same objects to satisfy
598 for (const auto *O : Symtab.ObjectFiles) {
599 if (O->ParentName.empty())
603 if (auto EC = sys::fs::createTemporaryFile(
604 "lld-" + sys::path::filename(O->ParentName), ".obj", Fd, S))
605 fatal(EC, "cannot create a temporary file");
606 raw_fd_ostream OS(Fd, /*shouldClose*/ true);
607 OS << O->MB.getBuffer();
608 Temps.push_back(S.str());
609 Rsp += quote(S) + "\n";
612 for (auto *Arg : Args) {
613 switch (Arg->getOption().getID()) {
616 case OPT_lldmap_file:
617 case OPT_lldsavetemps:
619 // LLD-specific options are stripped.
622 if (!StringRef(Arg->getValue()).startswith("lld"))
623 Rsp += toString(Arg) + " ";
626 if (Optional<StringRef> Path = doFindFile(Arg->getValue())) {
627 if (Optional<std::string> S = filterBitcodeFiles(*Path, Temps))
628 Rsp += quote(*S) + "\n";
631 Rsp += quote(Arg->getValue()) + "\n";
635 Rsp += toString(Arg) + "\n";
639 std::vector<StringRef> ObjectFiles = Symtab.compileBitcodeFiles();
640 runMSVCLinker(Rsp, ObjectFiles);
642 for (StringRef Path : Temps)
643 sys::fs::remove(Path);
646 void LinkerDriver::enqueueTask(std::function<void()> Task) {
647 TaskQueue.push_back(std::move(Task));
650 bool LinkerDriver::run() {
651 bool DidWork = !TaskQueue.empty();
652 while (!TaskQueue.empty()) {
654 TaskQueue.pop_front();
659 void LinkerDriver::link(ArrayRef<const char *> ArgsArr) {
660 // If the first command line argument is "/lib", link.exe acts like lib.exe.
661 // We call our own implementation of lib.exe that understands bitcode files.
662 if (ArgsArr.size() > 1 && StringRef(ArgsArr[1]).equals_lower("/lib")) {
663 if (llvm::libDriverMain(ArgsArr.slice(1)) != 0)
669 InitializeAllTargetInfos();
670 InitializeAllTargets();
671 InitializeAllTargetMCs();
672 InitializeAllAsmParsers();
673 InitializeAllAsmPrinters();
674 InitializeAllDisassemblers();
676 // Parse command line options.
677 opt::InputArgList Args = Parser.parseLINK(ArgsArr.slice(1));
679 // Parse and evaluate -mllvm options.
680 std::vector<const char *> V;
681 V.push_back("lld-link (LLVM option parsing)");
682 for (auto *Arg : Args.filtered(OPT_mllvm))
683 V.push_back(Arg->getValue());
684 cl::ParseCommandLineOptions(V.size(), V.data());
686 // Handle /errorlimit early, because error() depends on it.
687 if (auto *Arg = Args.getLastArg(OPT_errorlimit)) {
689 StringRef S = Arg->getValue();
690 if (S.getAsInteger(10, N))
691 error(Arg->getSpelling() + " number expected, but got " + S);
692 Config->ErrorLimit = N;
696 if (Args.hasArg(OPT_help)) {
697 printHelp(ArgsArr[0]);
701 if (auto *Arg = Args.getLastArg(OPT_linkrepro)) {
702 SmallString<64> Path = StringRef(Arg->getValue());
703 sys::path::append(Path, "repro.tar");
705 Expected<std::unique_ptr<TarWriter>> ErrOrWriter =
706 TarWriter::create(Path, "repro");
709 Tar = std::move(*ErrOrWriter);
711 error("/linkrepro: failed to open " + Path + ": " +
712 toString(ErrOrWriter.takeError()));
716 if (!Args.hasArgNoClaim(OPT_INPUT))
717 fatal("no input files");
719 // Construct search path list.
720 SearchPaths.push_back("");
721 for (auto *Arg : Args.filtered(OPT_libpath))
722 SearchPaths.push_back(Arg->getValue());
726 if (auto *Arg = Args.getLastArg(OPT_out))
727 Config->OutputFile = Arg->getValue();
730 if (Args.hasArg(OPT_verbose))
731 Config->Verbose = true;
733 // Handle /force or /force:unresolved
734 if (Args.hasArg(OPT_force) || Args.hasArg(OPT_force_unresolved))
735 Config->Force = true;
738 if (Args.hasArg(OPT_debug)) {
739 Config->Debug = true;
741 Args.hasArg(OPT_debugtype)
742 ? parseDebugType(Args.getLastArg(OPT_debugtype)->getValue())
743 : getDefaultDebugType(Args);
746 // Create a dummy PDB file to satisfy build sytem rules.
747 if (auto *Arg = Args.getLastArg(OPT_pdb))
748 Config->PDBPath = Arg->getValue();
751 if (Args.hasArg(OPT_noentry)) {
752 if (Args.hasArg(OPT_dll))
753 Config->NoEntry = true;
755 error("/noentry must be specified with /dll");
759 if (Args.hasArg(OPT_dll)) {
761 Config->ManifestID = 2;
765 if (Args.hasArg(OPT_fixed)) {
766 if (Args.hasArg(OPT_dynamicbase)) {
767 error("/fixed must not be specified with /dynamicbase");
769 Config->Relocatable = false;
770 Config->DynamicBase = false;
774 if (Args.hasArg(OPT_appcontainer))
775 Config->AppContainer = true;
778 if (auto *Arg = Args.getLastArg(OPT_machine))
779 Config->Machine = getMachineType(Arg->getValue());
781 // Handle /nodefaultlib:<filename>
782 for (auto *Arg : Args.filtered(OPT_nodefaultlib))
783 Config->NoDefaultLibs.insert(doFindLib(Arg->getValue()));
785 // Handle /nodefaultlib
786 if (Args.hasArg(OPT_nodefaultlib_all))
787 Config->NoDefaultLibAll = true;
790 if (auto *Arg = Args.getLastArg(OPT_base))
791 parseNumbers(Arg->getValue(), &Config->ImageBase);
794 if (auto *Arg = Args.getLastArg(OPT_stack))
795 parseNumbers(Arg->getValue(), &Config->StackReserve, &Config->StackCommit);
798 if (auto *Arg = Args.getLastArg(OPT_heap))
799 parseNumbers(Arg->getValue(), &Config->HeapReserve, &Config->HeapCommit);
802 if (auto *Arg = Args.getLastArg(OPT_version))
803 parseVersion(Arg->getValue(), &Config->MajorImageVersion,
804 &Config->MinorImageVersion);
807 if (auto *Arg = Args.getLastArg(OPT_subsystem))
808 parseSubsystem(Arg->getValue(), &Config->Subsystem, &Config->MajorOSVersion,
809 &Config->MinorOSVersion);
811 // Handle /alternatename
812 for (auto *Arg : Args.filtered(OPT_alternatename))
813 parseAlternateName(Arg->getValue());
816 for (auto *Arg : Args.filtered(OPT_incl))
817 addUndefined(Arg->getValue());
820 if (auto *Arg = Args.getLastArg(OPT_implib))
821 Config->Implib = Arg->getValue();
824 for (auto *Arg : Args.filtered(OPT_opt)) {
825 std::string Str = StringRef(Arg->getValue()).lower();
826 SmallVector<StringRef, 1> Vec;
827 StringRef(Str).split(Vec, ',');
828 for (StringRef S : Vec) {
830 Config->DoGC = false;
831 Config->DoICF = false;
834 if (S == "icf" || StringRef(S).startswith("icf=")) {
835 Config->DoICF = true;
839 Config->DoICF = false;
842 if (StringRef(S).startswith("lldlto=")) {
843 StringRef OptLevel = StringRef(S).substr(7);
844 if (OptLevel.getAsInteger(10, Config->LTOOptLevel) ||
845 Config->LTOOptLevel > 3)
846 error("/opt:lldlto: invalid optimization level: " + OptLevel);
849 if (StringRef(S).startswith("lldltojobs=")) {
850 StringRef Jobs = StringRef(S).substr(11);
851 if (Jobs.getAsInteger(10, Config->LTOJobs) || Config->LTOJobs == 0)
852 error("/opt:lldltojobs: invalid job count: " + Jobs);
855 if (StringRef(S).startswith("lldltopartitions=")) {
856 StringRef N = StringRef(S).substr(17);
857 if (N.getAsInteger(10, Config->LTOPartitions) ||
858 Config->LTOPartitions == 0)
859 error("/opt:lldltopartitions: invalid partition count: " + N);
862 if (S != "ref" && S != "lbr" && S != "nolbr")
863 error("/opt: unknown option: " + S);
867 // Handle /lldsavetemps
868 if (Args.hasArg(OPT_lldsavetemps))
869 Config->SaveTemps = true;
871 // Handle /failifmismatch
872 for (auto *Arg : Args.filtered(OPT_failifmismatch))
873 checkFailIfMismatch(Arg->getValue());
876 for (auto *Arg : Args.filtered(OPT_merge))
877 parseMerge(Arg->getValue());
880 for (auto *Arg : Args.filtered(OPT_section))
881 parseSection(Arg->getValue());
884 if (auto *Arg = Args.getLastArg(OPT_manifest_colon))
885 parseManifest(Arg->getValue());
887 // Handle /manifestuac
888 if (auto *Arg = Args.getLastArg(OPT_manifestuac))
889 parseManifestUAC(Arg->getValue());
891 // Handle /manifestdependency
892 if (auto *Arg = Args.getLastArg(OPT_manifestdependency))
893 Config->ManifestDependency = Arg->getValue();
895 // Handle /manifestfile
896 if (auto *Arg = Args.getLastArg(OPT_manifestfile))
897 Config->ManifestFile = Arg->getValue();
899 // Handle /manifestinput
900 for (auto *Arg : Args.filtered(OPT_manifestinput))
901 Config->ManifestInput.push_back(Arg->getValue());
903 // Handle miscellaneous boolean flags.
904 if (Args.hasArg(OPT_allowisolation_no))
905 Config->AllowIsolation = false;
906 if (Args.hasArg(OPT_dynamicbase_no))
907 Config->DynamicBase = false;
908 if (Args.hasArg(OPT_nxcompat_no))
909 Config->NxCompat = false;
910 if (Args.hasArg(OPT_tsaware_no))
911 Config->TerminalServerAware = false;
912 if (Args.hasArg(OPT_nosymtab))
913 Config->WriteSymtab = false;
914 Config->DumpPdb = Args.hasArg(OPT_dumppdb);
916 Config->MapFile = getMapFile(Args);
921 // Create a list of input files. Files can be given as arguments
922 // for /defaultlib option.
923 std::vector<MemoryBufferRef> MBs;
924 for (auto *Arg : Args.filtered(OPT_INPUT))
925 if (Optional<StringRef> Path = findFile(Arg->getValue()))
927 for (auto *Arg : Args.filtered(OPT_defaultlib))
928 if (Optional<StringRef> Path = findLib(Arg->getValue()))
931 // Windows specific -- Create a resource file containing a manifest file.
932 if (Config->Manifest == Configuration::Embed)
933 addBuffer(createManifestRes());
935 // Read all input files given via the command line.
938 // We should have inferred a machine type by now from the input files, but if
939 // not we assume x64.
940 if (Config->Machine == IMAGE_FILE_MACHINE_UNKNOWN) {
941 warn("/machine is not specified. x64 is assumed");
942 Config->Machine = AMD64;
945 // Windows specific -- Input files can be Windows resource files (.res files).
946 // We invoke cvtres.exe to convert resource files to a regular COFF file
947 // then link the result file normally.
948 if (!Resources.empty())
949 addBuffer(convertResToCOFF(Resources));
952 Tar->append("response.txt",
953 createResponseFile(Args, FilePaths,
954 ArrayRef<StringRef>(SearchPaths).slice(1)));
956 // Handle /largeaddressaware
957 if (Config->is64() || Args.hasArg(OPT_largeaddressaware))
958 Config->LargeAddressAware = true;
960 // Handle /highentropyva
961 if (Config->is64() && !Args.hasArg(OPT_highentropyva_no))
962 Config->HighEntropyVA = true;
964 // Handle /entry and /dll
965 if (auto *Arg = Args.getLastArg(OPT_entry)) {
966 Config->Entry = addUndefined(mangle(Arg->getValue()));
967 } else if (Args.hasArg(OPT_dll) && !Config->NoEntry) {
968 StringRef S = (Config->Machine == I386) ? "__DllMainCRTStartup@12"
969 : "_DllMainCRTStartup";
970 Config->Entry = addUndefined(S);
971 } else if (!Config->NoEntry) {
972 // Windows specific -- If entry point name is not given, we need to
973 // infer that from user-defined entry name.
974 StringRef S = findDefaultEntry();
976 fatal("entry point must be defined");
977 Config->Entry = addUndefined(S);
978 log("Entry name inferred: " + S);
982 for (auto *Arg : Args.filtered(OPT_export)) {
983 Export E = parseExport(Arg->getValue());
984 if (Config->Machine == I386) {
985 if (!isDecorated(E.Name))
986 E.Name = Saver.save("_" + E.Name);
987 if (!E.ExtName.empty() && !isDecorated(E.ExtName))
988 E.ExtName = Saver.save("_" + E.ExtName);
990 Config->Exports.push_back(E);
994 if (auto *Arg = Args.getLastArg(OPT_deffile)) {
995 // parseModuleDefs mutates Config object.
996 parseModuleDefs(Arg->getValue());
1000 for (auto *Arg : Args.filtered(OPT_delayload)) {
1001 Config->DelayLoads.insert(StringRef(Arg->getValue()).lower());
1002 if (Config->Machine == I386) {
1003 Config->DelayLoadHelper = addUndefined("___delayLoadHelper2@8");
1005 Config->DelayLoadHelper = addUndefined("__delayLoadHelper2");
1009 // Set default image name if neither /out or /def set it.
1010 if (Config->OutputFile.empty()) {
1011 Config->OutputFile =
1012 getOutputPath((*Args.filtered(OPT_INPUT).begin())->getValue());
1015 // Put the PDB next to the image if no /pdb flag was passed.
1016 if (Config->Debug && Config->PDBPath.empty()) {
1017 Config->PDBPath = Config->OutputFile;
1018 sys::path::replace_extension(Config->PDBPath, ".pdb");
1021 // Disable PDB generation if the user requested it.
1022 if (Args.hasArg(OPT_nopdb))
1023 Config->PDBPath = "";
1025 // Set default image base if /base is not given.
1026 if (Config->ImageBase == uint64_t(-1))
1027 Config->ImageBase = getDefaultImageBase();
1029 Symtab.addRelative(mangle("__ImageBase"), 0);
1030 if (Config->Machine == I386) {
1031 Config->SEHTable = Symtab.addRelative("___safe_se_handler_table", 0);
1032 Config->SEHCount = Symtab.addAbsolute("___safe_se_handler_count", 0);
1035 // We do not support /guard:cf (control flow protection) yet.
1036 // Define CFG symbols anyway so that we can link MSVC 2015 CRT.
1037 Symtab.addAbsolute(mangle("__guard_fids_table"), 0);
1038 Symtab.addAbsolute(mangle("__guard_fids_count"), 0);
1039 Symtab.addAbsolute(mangle("__guard_flags"), 0x100);
1041 // This code may add new undefined symbols to the link, which may enqueue more
1042 // symbol resolution tasks, so we need to continue executing tasks until we
1045 // Windows specific -- if entry point is not found,
1046 // search for its mangled names.
1048 Symtab.mangleMaybe(Config->Entry);
1050 // Windows specific -- Make sure we resolve all dllexported symbols.
1051 for (Export &E : Config->Exports) {
1052 if (!E.ForwardTo.empty())
1054 E.Sym = addUndefined(E.Name);
1056 Symtab.mangleMaybe(E.Sym);
1059 // Add weak aliases. Weak aliases is a mechanism to give remaining
1060 // undefined symbols final chance to be resolved successfully.
1061 for (auto Pair : Config->AlternateNames) {
1062 StringRef From = Pair.first;
1063 StringRef To = Pair.second;
1064 Symbol *Sym = Symtab.find(From);
1067 if (auto *U = dyn_cast<Undefined>(Sym->body()))
1069 U->WeakAlias = Symtab.addUndefined(To);
1072 // Windows specific -- if __load_config_used can be resolved, resolve it.
1073 if (Symtab.findUnderscore("_load_config_used"))
1074 addUndefined(mangle("_load_config_used"));
1080 // If /msvclto is given, we use the MSVC linker to link LTO output files.
1081 // This is useful because MSVC link.exe can generate complete PDBs.
1082 if (Args.hasArg(OPT_msvclto)) {
1087 // Do LTO by compiling bitcode input files to a set of native COFF files then
1088 // link those files.
1089 Symtab.addCombinedLTOObjects();
1092 // Make sure we have resolved all symbols.
1093 Symtab.reportRemainingUndefines();
1095 // Windows specific -- if no /subsystem is given, we need to infer
1096 // that from entry point name.
1097 if (Config->Subsystem == IMAGE_SUBSYSTEM_UNKNOWN) {
1098 Config->Subsystem = inferSubsystem();
1099 if (Config->Subsystem == IMAGE_SUBSYSTEM_UNKNOWN)
1100 fatal("subsystem must be defined");
1104 if (Args.hasArg(OPT_safeseh)) {
1105 for (ObjectFile *File : Symtab.ObjectFiles)
1106 if (!File->SEHCompat)
1107 error("/safeseh: " + File->getName() + " is not compatible with SEH");
1112 // Windows specific -- when we are creating a .dll file, we also
1113 // need to create a .lib file.
1114 if (!Config->Exports.empty() || Config->DLL) {
1116 createImportLibrary();
1117 assignExportOrdinals();
1120 // Windows specific -- Create a side-by-side manifest file.
1121 if (Config->Manifest == Configuration::SideBySide)
1122 createSideBySideManifest();
1124 // Identify unreferenced COMDAT sections.
1126 markLive(Symtab.getChunks());
1128 // Identify identical COMDAT sections to merge them.
1130 doICF(Symtab.getChunks());
1132 // Write the result.
1133 writeResult(&Symtab);
1135 // Call exit to avoid calling destructors.