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/Option/Arg.h"
23 #include "llvm/Option/ArgList.h"
24 #include "llvm/Option/Option.h"
25 #include "llvm/Support/Debug.h"
26 #include "llvm/Support/Path.h"
27 #include "llvm/Support/Process.h"
28 #include "llvm/Support/TarWriter.h"
29 #include "llvm/Support/TargetSelect.h"
30 #include "llvm/Support/raw_ostream.h"
31 #include "llvm/ToolDrivers/llvm-lib/LibDriver.h"
38 using namespace llvm::COFF;
39 using llvm::sys::Process;
40 using llvm::sys::fs::file_magic;
41 using llvm::sys::fs::identify_magic;
46 Configuration *Config;
49 BumpPtrAllocator BAlloc;
50 StringSaver Saver{BAlloc};
51 std::vector<SpecificAllocBase *> SpecificAllocBase::Instances;
53 bool link(ArrayRef<const char *> Args, raw_ostream &Diag) {
57 Config = make<Configuration>();
58 Config->ColorDiagnostics =
59 (ErrorOS == &llvm::errs() && Process::StandardErrHasColors());
60 Driver = make<LinkerDriver>();
65 // Drop directory components and replace extension with ".exe" or ".dll".
66 static std::string getOutputPath(StringRef Path) {
67 auto P = Path.find_last_of("\\/");
68 StringRef S = (P == StringRef::npos) ? Path : Path.substr(P + 1);
69 const char* E = Config->DLL ? ".dll" : ".exe";
70 return (S.substr(0, S.rfind('.')) + E).str();
73 // ErrorOr is not default constructible, so it cannot be used as the type
74 // parameter of a future.
75 // FIXME: We could open the file in createFutureForFile and avoid needing to
76 // return an error here, but for the moment that would cost us a file descriptor
77 // (a limited resource on Windows) for the duration that the future is pending.
78 typedef std::pair<std::unique_ptr<MemoryBuffer>, std::error_code> MBErrPair;
80 // Create a std::future that opens and maps a file using the best strategy for
82 static std::future<MBErrPair> createFutureForFile(std::string Path) {
84 // On Windows, file I/O is relatively slow so it is best to do this
86 auto Strategy = std::launch::async;
88 auto Strategy = std::launch::deferred;
90 return std::async(Strategy, [=]() {
91 auto MBOrErr = MemoryBuffer::getFile(Path);
93 return MBErrPair{nullptr, MBOrErr.getError()};
94 return MBErrPair{std::move(*MBOrErr), std::error_code()};
98 MemoryBufferRef LinkerDriver::takeBuffer(std::unique_ptr<MemoryBuffer> MB) {
99 MemoryBufferRef MBRef = *MB;
100 OwningMBs.push_back(std::move(MB));
103 Driver->Tar->append(relativeToRoot(MBRef.getBufferIdentifier()),
109 void LinkerDriver::addBuffer(std::unique_ptr<MemoryBuffer> MB) {
110 MemoryBufferRef MBRef = takeBuffer(std::move(MB));
112 // File type is detected by contents, not by file extension.
113 file_magic Magic = identify_magic(MBRef.getBuffer());
114 if (Magic == file_magic::windows_resource) {
115 Resources.push_back(MBRef);
119 FilePaths.push_back(MBRef.getBufferIdentifier());
120 if (Magic == file_magic::archive)
121 return Symtab.addFile(make<ArchiveFile>(MBRef));
122 if (Magic == file_magic::bitcode)
123 return Symtab.addFile(make<BitcodeFile>(MBRef));
125 if (Magic == file_magic::coff_cl_gl_object)
126 error(MBRef.getBufferIdentifier() + ": is not a native COFF file. "
127 "Recompile without /GL");
129 Symtab.addFile(make<ObjectFile>(MBRef));
132 void LinkerDriver::enqueuePath(StringRef Path) {
134 std::make_shared<std::future<MBErrPair>>(createFutureForFile(Path));
135 std::string PathStr = Path;
137 auto MBOrErr = Future->get();
139 error("could not open " + PathStr + ": " + MBOrErr.second.message());
141 Driver->addBuffer(std::move(MBOrErr.first));
145 void LinkerDriver::addArchiveBuffer(MemoryBufferRef MB, StringRef SymName,
146 StringRef ParentName) {
147 file_magic Magic = identify_magic(MB.getBuffer());
148 if (Magic == file_magic::coff_import_library) {
149 Symtab.addFile(make<ImportFile>(MB));
154 if (Magic == file_magic::coff_object) {
155 Obj = make<ObjectFile>(MB);
156 } else if (Magic == file_magic::bitcode) {
157 Obj = make<BitcodeFile>(MB);
159 error("unknown file type: " + MB.getBufferIdentifier());
163 Obj->ParentName = ParentName;
165 log("Loaded " + toString(Obj) + " for " + SymName);
168 void LinkerDriver::enqueueArchiveMember(const Archive::Child &C,
170 StringRef ParentName) {
171 if (!C.getParent()->isThin()) {
172 MemoryBufferRef MB = check(
173 C.getMemoryBufferRef(),
174 "could not get the buffer for the member defining symbol " + SymName);
175 enqueueTask([=]() { Driver->addArchiveBuffer(MB, SymName, ParentName); });
179 auto Future = std::make_shared<std::future<MBErrPair>>(createFutureForFile(
180 check(C.getFullName(),
181 "could not get the filename for the member defining symbol " +
184 auto MBOrErr = Future->get();
186 fatal(MBOrErr.second,
187 "could not get the buffer for the member defining " + SymName);
188 Driver->addArchiveBuffer(takeBuffer(std::move(MBOrErr.first)), SymName,
193 static bool isDecorated(StringRef Sym) {
194 return Sym.startswith("_") || Sym.startswith("@") || Sym.startswith("?");
197 // Parses .drectve section contents and returns a list of files
198 // specified by /defaultlib.
199 void LinkerDriver::parseDirectives(StringRef S) {
200 opt::InputArgList Args = Parser.parse(S);
202 for (auto *Arg : Args) {
203 switch (Arg->getOption().getID()) {
204 case OPT_alternatename:
205 parseAlternateName(Arg->getValue());
208 if (Optional<StringRef> Path = findLib(Arg->getValue()))
212 Export E = parseExport(Arg->getValue());
214 Config->Exports.push_back(E);
217 case OPT_failifmismatch:
218 checkFailIfMismatch(Arg->getValue());
221 addUndefined(Arg->getValue());
224 parseMerge(Arg->getValue());
226 case OPT_nodefaultlib:
227 Config->NoDefaultLibs.insert(doFindLib(Arg->getValue()));
230 parseSection(Arg->getValue());
232 case OPT_editandcontinue:
235 case OPT_throwingnew:
238 error(Arg->getSpelling() + " is not allowed in .drectve");
243 // Find file from search paths. You can omit ".obj", this function takes
244 // care of that. Note that the returned path is not guaranteed to exist.
245 StringRef LinkerDriver::doFindFile(StringRef Filename) {
246 bool HasPathSep = (Filename.find_first_of("/\\") != StringRef::npos);
249 bool HasExt = (Filename.find('.') != StringRef::npos);
250 for (StringRef Dir : SearchPaths) {
251 SmallString<128> Path = Dir;
252 sys::path::append(Path, Filename);
253 if (sys::fs::exists(Path.str()))
254 return Saver.save(Path.str());
257 if (sys::fs::exists(Path.str()))
258 return Saver.save(Path.str());
264 // Resolves a file path. This never returns the same path
265 // (in that case, it returns None).
266 Optional<StringRef> LinkerDriver::findFile(StringRef Filename) {
267 StringRef Path = doFindFile(Filename);
268 bool Seen = !VisitedFiles.insert(Path.lower()).second;
274 // Find library file from search path.
275 StringRef LinkerDriver::doFindLib(StringRef Filename) {
276 // Add ".lib" to Filename if that has no file extension.
277 bool HasExt = (Filename.find('.') != StringRef::npos);
279 Filename = Saver.save(Filename + ".lib");
280 return doFindFile(Filename);
283 // Resolves a library path. /nodefaultlib options are taken into
284 // consideration. This never returns the same path (in that case,
286 Optional<StringRef> LinkerDriver::findLib(StringRef Filename) {
287 if (Config->NoDefaultLibAll)
289 if (!VisitedLibs.insert(Filename.lower()).second)
291 StringRef Path = doFindLib(Filename);
292 if (Config->NoDefaultLibs.count(Path))
294 if (!VisitedFiles.insert(Path.lower()).second)
299 // Parses LIB environment which contains a list of search paths.
300 void LinkerDriver::addLibSearchPaths() {
301 Optional<std::string> EnvOpt = Process::GetEnv("LIB");
302 if (!EnvOpt.hasValue())
304 StringRef Env = Saver.save(*EnvOpt);
305 while (!Env.empty()) {
307 std::tie(Path, Env) = Env.split(';');
308 SearchPaths.push_back(Path);
312 SymbolBody *LinkerDriver::addUndefined(StringRef Name) {
313 SymbolBody *B = Symtab.addUndefined(Name);
314 Config->GCRoot.insert(B);
318 // Symbol names are mangled by appending "_" prefix on x86.
319 StringRef LinkerDriver::mangle(StringRef Sym) {
320 assert(Config->Machine != IMAGE_FILE_MACHINE_UNKNOWN);
321 if (Config->Machine == I386)
322 return Saver.save("_" + Sym);
326 // Windows specific -- find default entry point name.
327 StringRef LinkerDriver::findDefaultEntry() {
328 // User-defined main functions and their corresponding entry points.
329 static const char *Entries[][2] = {
330 {"main", "mainCRTStartup"},
331 {"wmain", "wmainCRTStartup"},
332 {"WinMain", "WinMainCRTStartup"},
333 {"wWinMain", "wWinMainCRTStartup"},
335 for (auto E : Entries) {
336 StringRef Entry = Symtab.findMangle(mangle(E[0]));
337 if (!Entry.empty() && !isa<Undefined>(Symtab.find(Entry)->body()))
343 WindowsSubsystem LinkerDriver::inferSubsystem() {
345 return IMAGE_SUBSYSTEM_WINDOWS_GUI;
346 if (Symtab.findUnderscore("main") || Symtab.findUnderscore("wmain"))
347 return IMAGE_SUBSYSTEM_WINDOWS_CUI;
348 if (Symtab.findUnderscore("WinMain") || Symtab.findUnderscore("wWinMain"))
349 return IMAGE_SUBSYSTEM_WINDOWS_GUI;
350 return IMAGE_SUBSYSTEM_UNKNOWN;
353 static uint64_t getDefaultImageBase() {
355 return Config->DLL ? 0x180000000 : 0x140000000;
356 return Config->DLL ? 0x10000000 : 0x400000;
359 static std::string createResponseFile(const opt::InputArgList &Args,
360 ArrayRef<StringRef> FilePaths,
361 ArrayRef<StringRef> SearchPaths) {
363 raw_svector_ostream OS(Data);
365 for (auto *Arg : Args) {
366 switch (Arg->getOption().getID()) {
373 OS << toString(Arg) << "\n";
377 for (StringRef Path : SearchPaths) {
378 std::string RelPath = relativeToRoot(Path);
379 OS << "/libpath:" << quote(RelPath) << "\n";
382 for (StringRef Path : FilePaths)
383 OS << quote(relativeToRoot(Path)) << "\n";
388 static unsigned getDefaultDebugType(const opt::InputArgList &Args) {
389 unsigned DebugTypes = static_cast<unsigned>(DebugType::CV);
390 if (Args.hasArg(OPT_driver))
391 DebugTypes |= static_cast<unsigned>(DebugType::PData);
392 if (Args.hasArg(OPT_profile))
393 DebugTypes |= static_cast<unsigned>(DebugType::Fixup);
397 static unsigned parseDebugType(StringRef Arg) {
398 SmallVector<StringRef, 3> Types;
399 Arg.split(Types, ',', /*KeepEmpty=*/false);
401 unsigned DebugTypes = static_cast<unsigned>(DebugType::None);
402 for (StringRef Type : Types)
403 DebugTypes |= StringSwitch<unsigned>(Type.lower())
404 .Case("cv", static_cast<unsigned>(DebugType::CV))
405 .Case("pdata", static_cast<unsigned>(DebugType::PData))
406 .Case("fixup", static_cast<unsigned>(DebugType::Fixup))
411 static std::string getMapFile(const opt::InputArgList &Args) {
412 auto *Arg = Args.getLastArg(OPT_lldmap, OPT_lldmap_file);
415 if (Arg->getOption().getID() == OPT_lldmap_file)
416 return Arg->getValue();
418 assert(Arg->getOption().getID() == OPT_lldmap);
419 StringRef OutFile = Config->OutputFile;
420 return (OutFile.substr(0, OutFile.rfind('.')) + ".map").str();
423 std::vector<MemoryBufferRef> getArchiveMembers(Archive *File) {
424 std::vector<MemoryBufferRef> V;
425 Error Err = Error::success();
426 for (const ErrorOr<Archive::Child> &COrErr : File->children(Err)) {
429 File->getFileName() + ": could not get the child of the archive");
430 MemoryBufferRef MBRef =
431 check(C.getMemoryBufferRef(),
432 File->getFileName() +
433 ": could not get the buffer for a child of the archive");
437 fatal(File->getFileName() +
438 ": Archive::children failed: " + toString(std::move(Err)));
442 // A helper function for filterBitcodeFiles.
443 static bool needsRebuilding(MemoryBufferRef MB) {
444 // The MSVC linker doesn't support thin archives, so if it's a thin
445 // archive, we always need to rebuild it.
446 std::unique_ptr<Archive> File =
447 check(Archive::create(MB), "Failed to read " + MB.getBufferIdentifier());
451 // Returns true if the archive contains at least one bitcode file.
452 for (MemoryBufferRef Member : getArchiveMembers(File.get()))
453 if (identify_magic(Member.getBuffer()) == file_magic::bitcode)
458 // Opens a given path as an archive file and removes bitcode files
459 // from them if exists. This function is to appease the MSVC linker as
460 // their linker doesn't like archive files containing non-native
463 // If a given archive doesn't contain bitcode files, the archive path
464 // is returned as-is. Otherwise, a new temporary file is created and
465 // its path is returned.
466 static Optional<std::string>
467 filterBitcodeFiles(StringRef Path, std::vector<std::string> &TemporaryFiles) {
468 std::unique_ptr<MemoryBuffer> MB = check(
469 MemoryBuffer::getFile(Path, -1, false, true), "could not open " + Path);
470 MemoryBufferRef MBRef = MB->getMemBufferRef();
471 file_magic Magic = identify_magic(MBRef.getBuffer());
473 if (Magic == file_magic::bitcode)
475 if (Magic != file_magic::archive)
477 if (!needsRebuilding(MBRef))
480 std::unique_ptr<Archive> File =
481 check(Archive::create(MBRef),
482 MBRef.getBufferIdentifier() + ": failed to parse archive");
484 std::vector<NewArchiveMember> New;
485 for (MemoryBufferRef Member : getArchiveMembers(File.get()))
486 if (identify_magic(Member.getBuffer()) != file_magic::bitcode)
487 New.emplace_back(Member);
492 log("Creating a temporary archive for " + Path + " to remove bitcode files");
495 if (auto EC = sys::fs::createTemporaryFile("lld-" + sys::path::stem(Path),
497 fatal(EC, "cannot create a temporary file");
498 std::string Temp = S.str();
499 TemporaryFiles.push_back(Temp);
501 std::pair<StringRef, std::error_code> Ret =
502 llvm::writeArchive(Temp, New, /*WriteSymtab=*/true, Archive::Kind::K_GNU,
503 /*Deterministics=*/true,
506 error("failed to create a new archive " + S.str() + ": " + Ret.first);
510 // Create response file contents and invoke the MSVC linker.
511 void LinkerDriver::invokeMSVC(opt::InputArgList &Args) {
512 std::string Rsp = "/nologo\n";
513 std::vector<std::string> Temps;
515 // Write out archive members that we used in symbol resolution and pass these
516 // to MSVC before any archives, so that MSVC uses the same objects to satisfy
518 for (const auto *O : Symtab.ObjectFiles) {
519 if (O->ParentName.empty())
523 if (auto EC = sys::fs::createTemporaryFile(
524 "lld-" + sys::path::filename(O->ParentName), ".obj", Fd, S))
525 fatal(EC, "cannot create a temporary file");
526 raw_fd_ostream OS(Fd, /*shouldClose*/ true);
527 OS << O->MB.getBuffer();
528 Temps.push_back(S.str());
529 Rsp += quote(S) + "\n";
532 for (auto *Arg : Args) {
533 switch (Arg->getOption().getID()) {
536 case OPT_lldmap_file:
537 case OPT_lldsavetemps:
539 // LLD-specific options are stripped.
542 if (!StringRef(Arg->getValue()).startswith("lld"))
543 Rsp += toString(Arg) + " ";
546 if (Optional<StringRef> Path = doFindFile(Arg->getValue())) {
547 if (Optional<std::string> S = filterBitcodeFiles(*Path, Temps))
548 Rsp += quote(*S) + "\n";
551 Rsp += quote(Arg->getValue()) + "\n";
555 Rsp += toString(Arg) + "\n";
559 std::vector<StringRef> ObjectFiles = Symtab.compileBitcodeFiles();
560 runMSVCLinker(Rsp, ObjectFiles);
562 for (StringRef Path : Temps)
563 sys::fs::remove(Path);
566 void LinkerDriver::enqueueTask(std::function<void()> Task) {
567 TaskQueue.push_back(std::move(Task));
570 bool LinkerDriver::run() {
571 bool DidWork = !TaskQueue.empty();
572 while (!TaskQueue.empty()) {
574 TaskQueue.pop_front();
579 void LinkerDriver::link(ArrayRef<const char *> ArgsArr) {
580 // If the first command line argument is "/lib", link.exe acts like lib.exe.
581 // We call our own implementation of lib.exe that understands bitcode files.
582 if (ArgsArr.size() > 1 && StringRef(ArgsArr[1]).equals_lower("/lib")) {
583 if (llvm::libDriverMain(ArgsArr.slice(1)) != 0)
589 InitializeAllTargetInfos();
590 InitializeAllTargets();
591 InitializeAllTargetMCs();
592 InitializeAllAsmParsers();
593 InitializeAllAsmPrinters();
594 InitializeAllDisassemblers();
596 // Parse command line options.
597 opt::InputArgList Args = Parser.parseLINK(ArgsArr.slice(1));
599 // Parse and evaluate -mllvm options.
600 std::vector<const char *> V;
601 V.push_back("lld-link (LLVM option parsing)");
602 for (auto *Arg : Args.filtered(OPT_mllvm))
603 V.push_back(Arg->getValue());
604 cl::ParseCommandLineOptions(V.size(), V.data());
606 // Handle /errorlimit early, because error() depends on it.
607 if (auto *Arg = Args.getLastArg(OPT_errorlimit)) {
609 StringRef S = Arg->getValue();
610 if (S.getAsInteger(10, N))
611 error(Arg->getSpelling() + " number expected, but got " + S);
612 Config->ErrorLimit = N;
616 if (Args.hasArg(OPT_help)) {
617 printHelp(ArgsArr[0]);
621 if (auto *Arg = Args.getLastArg(OPT_linkrepro)) {
622 SmallString<64> Path = StringRef(Arg->getValue());
623 sys::path::append(Path, "repro.tar");
625 Expected<std::unique_ptr<TarWriter>> ErrOrWriter =
626 TarWriter::create(Path, "repro");
629 Tar = std::move(*ErrOrWriter);
631 error("/linkrepro: failed to open " + Path + ": " +
632 toString(ErrOrWriter.takeError()));
636 if (!Args.hasArgNoClaim(OPT_INPUT))
637 fatal("no input files");
639 // Construct search path list.
640 SearchPaths.push_back("");
641 for (auto *Arg : Args.filtered(OPT_libpath))
642 SearchPaths.push_back(Arg->getValue());
646 if (auto *Arg = Args.getLastArg(OPT_out))
647 Config->OutputFile = Arg->getValue();
650 if (Args.hasArg(OPT_verbose))
651 Config->Verbose = true;
653 // Handle /force or /force:unresolved
654 if (Args.hasArg(OPT_force) || Args.hasArg(OPT_force_unresolved))
655 Config->Force = true;
658 if (Args.hasArg(OPT_debug)) {
659 Config->Debug = true;
661 Args.hasArg(OPT_debugtype)
662 ? parseDebugType(Args.getLastArg(OPT_debugtype)->getValue())
663 : getDefaultDebugType(Args);
666 // Create a dummy PDB file to satisfy build sytem rules.
667 if (auto *Arg = Args.getLastArg(OPT_pdb))
668 Config->PDBPath = Arg->getValue();
671 if (Args.hasArg(OPT_noentry)) {
672 if (Args.hasArg(OPT_dll))
673 Config->NoEntry = true;
675 error("/noentry must be specified with /dll");
679 if (Args.hasArg(OPT_dll)) {
681 Config->ManifestID = 2;
685 if (Args.hasArg(OPT_fixed)) {
686 if (Args.hasArg(OPT_dynamicbase)) {
687 error("/fixed must not be specified with /dynamicbase");
689 Config->Relocatable = false;
690 Config->DynamicBase = false;
694 if (Args.hasArg(OPT_appcontainer))
695 Config->AppContainer = true;
698 if (auto *Arg = Args.getLastArg(OPT_machine))
699 Config->Machine = getMachineType(Arg->getValue());
701 // Handle /nodefaultlib:<filename>
702 for (auto *Arg : Args.filtered(OPT_nodefaultlib))
703 Config->NoDefaultLibs.insert(doFindLib(Arg->getValue()));
705 // Handle /nodefaultlib
706 if (Args.hasArg(OPT_nodefaultlib_all))
707 Config->NoDefaultLibAll = true;
710 if (auto *Arg = Args.getLastArg(OPT_base))
711 parseNumbers(Arg->getValue(), &Config->ImageBase);
714 if (auto *Arg = Args.getLastArg(OPT_stack))
715 parseNumbers(Arg->getValue(), &Config->StackReserve, &Config->StackCommit);
718 if (auto *Arg = Args.getLastArg(OPT_heap))
719 parseNumbers(Arg->getValue(), &Config->HeapReserve, &Config->HeapCommit);
722 if (auto *Arg = Args.getLastArg(OPT_version))
723 parseVersion(Arg->getValue(), &Config->MajorImageVersion,
724 &Config->MinorImageVersion);
727 if (auto *Arg = Args.getLastArg(OPT_subsystem))
728 parseSubsystem(Arg->getValue(), &Config->Subsystem, &Config->MajorOSVersion,
729 &Config->MinorOSVersion);
731 // Handle /alternatename
732 for (auto *Arg : Args.filtered(OPT_alternatename))
733 parseAlternateName(Arg->getValue());
736 for (auto *Arg : Args.filtered(OPT_incl))
737 addUndefined(Arg->getValue());
740 if (auto *Arg = Args.getLastArg(OPT_implib))
741 Config->Implib = Arg->getValue();
744 for (auto *Arg : Args.filtered(OPT_opt)) {
745 std::string Str = StringRef(Arg->getValue()).lower();
746 SmallVector<StringRef, 1> Vec;
747 StringRef(Str).split(Vec, ',');
748 for (StringRef S : Vec) {
750 Config->DoGC = false;
751 Config->DoICF = false;
754 if (S == "icf" || StringRef(S).startswith("icf=")) {
755 Config->DoICF = true;
759 Config->DoICF = false;
762 if (StringRef(S).startswith("lldlto=")) {
763 StringRef OptLevel = StringRef(S).substr(7);
764 if (OptLevel.getAsInteger(10, Config->LTOOptLevel) ||
765 Config->LTOOptLevel > 3)
766 error("/opt:lldlto: invalid optimization level: " + OptLevel);
769 if (StringRef(S).startswith("lldltojobs=")) {
770 StringRef Jobs = StringRef(S).substr(11);
771 if (Jobs.getAsInteger(10, Config->LTOJobs) || Config->LTOJobs == 0)
772 error("/opt:lldltojobs: invalid job count: " + Jobs);
775 if (StringRef(S).startswith("lldltopartitions=")) {
776 StringRef N = StringRef(S).substr(17);
777 if (N.getAsInteger(10, Config->LTOPartitions) ||
778 Config->LTOPartitions == 0)
779 error("/opt:lldltopartitions: invalid partition count: " + N);
782 if (S != "ref" && S != "lbr" && S != "nolbr")
783 error("/opt: unknown option: " + S);
787 // Handle /lldsavetemps
788 if (Args.hasArg(OPT_lldsavetemps))
789 Config->SaveTemps = true;
791 // Handle /failifmismatch
792 for (auto *Arg : Args.filtered(OPT_failifmismatch))
793 checkFailIfMismatch(Arg->getValue());
796 for (auto *Arg : Args.filtered(OPT_merge))
797 parseMerge(Arg->getValue());
800 for (auto *Arg : Args.filtered(OPT_section))
801 parseSection(Arg->getValue());
804 if (auto *Arg = Args.getLastArg(OPT_manifest_colon))
805 parseManifest(Arg->getValue());
807 // Handle /manifestuac
808 if (auto *Arg = Args.getLastArg(OPT_manifestuac))
809 parseManifestUAC(Arg->getValue());
811 // Handle /manifestdependency
812 if (auto *Arg = Args.getLastArg(OPT_manifestdependency))
813 Config->ManifestDependency = Arg->getValue();
815 // Handle /manifestfile
816 if (auto *Arg = Args.getLastArg(OPT_manifestfile))
817 Config->ManifestFile = Arg->getValue();
819 // Handle /manifestinput
820 for (auto *Arg : Args.filtered(OPT_manifestinput))
821 Config->ManifestInput.push_back(Arg->getValue());
823 // Handle miscellaneous boolean flags.
824 if (Args.hasArg(OPT_allowbind_no))
825 Config->AllowBind = false;
826 if (Args.hasArg(OPT_allowisolation_no))
827 Config->AllowIsolation = false;
828 if (Args.hasArg(OPT_dynamicbase_no))
829 Config->DynamicBase = false;
830 if (Args.hasArg(OPT_nxcompat_no))
831 Config->NxCompat = false;
832 if (Args.hasArg(OPT_tsaware_no))
833 Config->TerminalServerAware = false;
834 if (Args.hasArg(OPT_nosymtab))
835 Config->WriteSymtab = false;
836 Config->DumpPdb = Args.hasArg(OPT_dumppdb);
837 Config->DebugPdb = Args.hasArg(OPT_debugpdb);
839 Config->MapFile = getMapFile(Args);
844 // Create a list of input files. Files can be given as arguments
845 // for /defaultlib option.
846 std::vector<MemoryBufferRef> MBs;
847 for (auto *Arg : Args.filtered(OPT_INPUT))
848 if (Optional<StringRef> Path = findFile(Arg->getValue()))
850 for (auto *Arg : Args.filtered(OPT_defaultlib))
851 if (Optional<StringRef> Path = findLib(Arg->getValue()))
854 // Windows specific -- Create a resource file containing a manifest file.
855 if (Config->Manifest == Configuration::Embed)
856 addBuffer(createManifestRes());
858 // Read all input files given via the command line.
861 // We should have inferred a machine type by now from the input files, but if
862 // not we assume x64.
863 if (Config->Machine == IMAGE_FILE_MACHINE_UNKNOWN) {
864 warn("/machine is not specified. x64 is assumed");
865 Config->Machine = AMD64;
868 // Windows specific -- Input files can be Windows resource files (.res files).
869 // We invoke cvtres.exe to convert resource files to a regular COFF file
870 // then link the result file normally.
871 if (!Resources.empty())
872 addBuffer(convertResToCOFF(Resources));
875 Tar->append("response.txt",
876 createResponseFile(Args, FilePaths,
877 ArrayRef<StringRef>(SearchPaths).slice(1)));
879 // Handle /largeaddressaware
880 if (Config->is64() || Args.hasArg(OPT_largeaddressaware))
881 Config->LargeAddressAware = true;
883 // Handle /highentropyva
884 if (Config->is64() && !Args.hasArg(OPT_highentropyva_no))
885 Config->HighEntropyVA = true;
887 // Handle /entry and /dll
888 if (auto *Arg = Args.getLastArg(OPT_entry)) {
889 Config->Entry = addUndefined(mangle(Arg->getValue()));
890 } else if (Args.hasArg(OPT_dll) && !Config->NoEntry) {
891 StringRef S = (Config->Machine == I386) ? "__DllMainCRTStartup@12"
892 : "_DllMainCRTStartup";
893 Config->Entry = addUndefined(S);
894 } else if (!Config->NoEntry) {
895 // Windows specific -- If entry point name is not given, we need to
896 // infer that from user-defined entry name.
897 StringRef S = findDefaultEntry();
899 fatal("entry point must be defined");
900 Config->Entry = addUndefined(S);
901 log("Entry name inferred: " + S);
905 for (auto *Arg : Args.filtered(OPT_export)) {
906 Export E = parseExport(Arg->getValue());
907 if (Config->Machine == I386) {
908 if (!isDecorated(E.Name))
909 E.Name = Saver.save("_" + E.Name);
910 if (!E.ExtName.empty() && !isDecorated(E.ExtName))
911 E.ExtName = Saver.save("_" + E.ExtName);
913 Config->Exports.push_back(E);
917 if (auto *Arg = Args.getLastArg(OPT_deffile)) {
918 // parseModuleDefs mutates Config object.
920 takeBuffer(check(MemoryBuffer::getFile(Arg->getValue()),
921 Twine("could not open ") + Arg->getValue())));
925 for (auto *Arg : Args.filtered(OPT_delayload)) {
926 Config->DelayLoads.insert(StringRef(Arg->getValue()).lower());
927 if (Config->Machine == I386) {
928 Config->DelayLoadHelper = addUndefined("___delayLoadHelper2@8");
930 Config->DelayLoadHelper = addUndefined("__delayLoadHelper2");
934 // Set default image name if neither /out or /def set it.
935 if (Config->OutputFile.empty()) {
937 getOutputPath((*Args.filtered(OPT_INPUT).begin())->getValue());
940 // Put the PDB next to the image if no /pdb flag was passed.
941 if (Config->Debug && Config->PDBPath.empty()) {
942 Config->PDBPath = Config->OutputFile;
943 sys::path::replace_extension(Config->PDBPath, ".pdb");
946 // Disable PDB generation if the user requested it.
947 if (Args.hasArg(OPT_nopdb))
948 Config->PDBPath = "";
950 // Set default image base if /base is not given.
951 if (Config->ImageBase == uint64_t(-1))
952 Config->ImageBase = getDefaultImageBase();
954 Symtab.addRelative(mangle("__ImageBase"), 0);
955 if (Config->Machine == I386) {
956 Config->SEHTable = Symtab.addRelative("___safe_se_handler_table", 0);
957 Config->SEHCount = Symtab.addAbsolute("___safe_se_handler_count", 0);
960 // We do not support /guard:cf (control flow protection) yet.
961 // Define CFG symbols anyway so that we can link MSVC 2015 CRT.
962 Symtab.addAbsolute(mangle("__guard_fids_table"), 0);
963 Symtab.addAbsolute(mangle("__guard_fids_count"), 0);
964 Symtab.addAbsolute(mangle("__guard_flags"), 0x100);
966 // This code may add new undefined symbols to the link, which may enqueue more
967 // symbol resolution tasks, so we need to continue executing tasks until we
970 // Windows specific -- if entry point is not found,
971 // search for its mangled names.
973 Symtab.mangleMaybe(Config->Entry);
975 // Windows specific -- Make sure we resolve all dllexported symbols.
976 for (Export &E : Config->Exports) {
977 if (!E.ForwardTo.empty())
979 E.Sym = addUndefined(E.Name);
981 Symtab.mangleMaybe(E.Sym);
984 // Add weak aliases. Weak aliases is a mechanism to give remaining
985 // undefined symbols final chance to be resolved successfully.
986 for (auto Pair : Config->AlternateNames) {
987 StringRef From = Pair.first;
988 StringRef To = Pair.second;
989 Symbol *Sym = Symtab.find(From);
992 if (auto *U = dyn_cast<Undefined>(Sym->body()))
994 U->WeakAlias = Symtab.addUndefined(To);
997 // Windows specific -- if __load_config_used can be resolved, resolve it.
998 if (Symtab.findUnderscore("_load_config_used"))
999 addUndefined(mangle("_load_config_used"));
1005 // If /msvclto is given, we use the MSVC linker to link LTO output files.
1006 // This is useful because MSVC link.exe can generate complete PDBs.
1007 if (Args.hasArg(OPT_msvclto)) {
1012 // Do LTO by compiling bitcode input files to a set of native COFF files then
1013 // link those files.
1014 Symtab.addCombinedLTOObjects();
1017 // Make sure we have resolved all symbols.
1018 Symtab.reportRemainingUndefines();
1020 // Windows specific -- if no /subsystem is given, we need to infer
1021 // that from entry point name.
1022 if (Config->Subsystem == IMAGE_SUBSYSTEM_UNKNOWN) {
1023 Config->Subsystem = inferSubsystem();
1024 if (Config->Subsystem == IMAGE_SUBSYSTEM_UNKNOWN)
1025 fatal("subsystem must be defined");
1029 if (Args.hasArg(OPT_safeseh)) {
1030 for (ObjectFile *File : Symtab.ObjectFiles)
1031 if (!File->SEHCompat)
1032 error("/safeseh: " + File->getName() + " is not compatible with SEH");
1037 // Windows specific -- when we are creating a .dll file, we also
1038 // need to create a .lib file.
1039 if (!Config->Exports.empty() || Config->DLL) {
1041 writeImportLibrary();
1042 assignExportOrdinals();
1045 // Windows specific -- Create a side-by-side manifest file.
1046 if (Config->Manifest == Configuration::SideBySide)
1047 createSideBySideManifest();
1049 // Identify unreferenced COMDAT sections.
1051 markLive(Symtab.getChunks());
1053 // Identify identical COMDAT sections to merge them.
1055 doICF(Symtab.getChunks());
1057 // Write the result.
1058 writeResult(&Symtab);
1060 // Call exit to avoid calling destructors.