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/LibDriver/LibDriver.h"
22 #include "llvm/Object/ArchiveWriter.h"
23 #include "llvm/Option/Arg.h"
24 #include "llvm/Option/ArgList.h"
25 #include "llvm/Option/Option.h"
26 #include "llvm/Support/Debug.h"
27 #include "llvm/Support/Path.h"
28 #include "llvm/Support/Process.h"
29 #include "llvm/Support/TarWriter.h"
30 #include "llvm/Support/TargetSelect.h"
31 #include "llvm/Support/raw_ostream.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 for (auto *Arg : Args) {
516 switch (Arg->getOption().getID()) {
519 case OPT_lldmap_file:
520 case OPT_lldsavetemps:
522 // LLD-specific options are stripped.
525 if (!StringRef(Arg->getValue()).startswith("lld"))
526 Rsp += toString(Arg) + " ";
529 if (Optional<StringRef> Path = doFindFile(Arg->getValue())) {
530 if (Optional<std::string> S = filterBitcodeFiles(*Path, Temps))
531 Rsp += quote(*S) + "\n";
534 Rsp += quote(Arg->getValue()) + "\n";
538 Rsp += toString(Arg) + "\n";
542 std::vector<StringRef> ObjectFiles = Symtab.compileBitcodeFiles();
543 runMSVCLinker(Rsp, ObjectFiles);
545 for (StringRef Path : Temps)
546 sys::fs::remove(Path);
549 void LinkerDriver::enqueueTask(std::function<void()> Task) {
550 TaskQueue.push_back(std::move(Task));
553 bool LinkerDriver::run() {
554 bool DidWork = !TaskQueue.empty();
555 while (!TaskQueue.empty()) {
557 TaskQueue.pop_front();
562 void LinkerDriver::link(ArrayRef<const char *> ArgsArr) {
563 // If the first command line argument is "/lib", link.exe acts like lib.exe.
564 // We call our own implementation of lib.exe that understands bitcode files.
565 if (ArgsArr.size() > 1 && StringRef(ArgsArr[1]).equals_lower("/lib")) {
566 if (llvm::libDriverMain(ArgsArr.slice(1)) != 0)
572 InitializeAllTargetInfos();
573 InitializeAllTargets();
574 InitializeAllTargetMCs();
575 InitializeAllAsmParsers();
576 InitializeAllAsmPrinters();
577 InitializeAllDisassemblers();
579 // Parse command line options.
580 opt::InputArgList Args = Parser.parseLINK(ArgsArr.slice(1));
582 // Parse and evaluate -mllvm options.
583 std::vector<const char *> V;
584 V.push_back("lld-link (LLVM option parsing)");
585 for (auto *Arg : Args.filtered(OPT_mllvm))
586 V.push_back(Arg->getValue());
587 cl::ParseCommandLineOptions(V.size(), V.data());
589 // Handle /errorlimit early, because error() depends on it.
590 if (auto *Arg = Args.getLastArg(OPT_errorlimit)) {
592 StringRef S = Arg->getValue();
593 if (S.getAsInteger(10, N))
594 error(Arg->getSpelling() + " number expected, but got " + S);
595 Config->ErrorLimit = N;
599 if (Args.hasArg(OPT_help)) {
600 printHelp(ArgsArr[0]);
604 if (auto *Arg = Args.getLastArg(OPT_linkrepro)) {
605 SmallString<64> Path = StringRef(Arg->getValue());
606 sys::path::append(Path, "repro.tar");
608 Expected<std::unique_ptr<TarWriter>> ErrOrWriter =
609 TarWriter::create(Path, "repro");
612 Tar = std::move(*ErrOrWriter);
614 error("/linkrepro: failed to open " + Path + ": " +
615 toString(ErrOrWriter.takeError()));
619 if (!Args.hasArgNoClaim(OPT_INPUT))
620 fatal("no input files");
622 // Construct search path list.
623 SearchPaths.push_back("");
624 for (auto *Arg : Args.filtered(OPT_libpath))
625 SearchPaths.push_back(Arg->getValue());
629 if (auto *Arg = Args.getLastArg(OPT_out))
630 Config->OutputFile = Arg->getValue();
633 if (Args.hasArg(OPT_verbose))
634 Config->Verbose = true;
636 // Handle /force or /force:unresolved
637 if (Args.hasArg(OPT_force) || Args.hasArg(OPT_force_unresolved))
638 Config->Force = true;
641 if (Args.hasArg(OPT_debug)) {
642 Config->Debug = true;
644 Args.hasArg(OPT_debugtype)
645 ? parseDebugType(Args.getLastArg(OPT_debugtype)->getValue())
646 : getDefaultDebugType(Args);
649 // Create a dummy PDB file to satisfy build sytem rules.
650 if (auto *Arg = Args.getLastArg(OPT_pdb))
651 Config->PDBPath = Arg->getValue();
654 if (Args.hasArg(OPT_noentry)) {
655 if (Args.hasArg(OPT_dll))
656 Config->NoEntry = true;
658 error("/noentry must be specified with /dll");
662 if (Args.hasArg(OPT_dll)) {
664 Config->ManifestID = 2;
668 if (Args.hasArg(OPT_fixed)) {
669 if (Args.hasArg(OPT_dynamicbase)) {
670 error("/fixed must not be specified with /dynamicbase");
672 Config->Relocatable = false;
673 Config->DynamicBase = false;
677 if (Args.hasArg(OPT_appcontainer))
678 Config->AppContainer = true;
681 if (auto *Arg = Args.getLastArg(OPT_machine))
682 Config->Machine = getMachineType(Arg->getValue());
684 // Handle /nodefaultlib:<filename>
685 for (auto *Arg : Args.filtered(OPT_nodefaultlib))
686 Config->NoDefaultLibs.insert(doFindLib(Arg->getValue()));
688 // Handle /nodefaultlib
689 if (Args.hasArg(OPT_nodefaultlib_all))
690 Config->NoDefaultLibAll = true;
693 if (auto *Arg = Args.getLastArg(OPT_base))
694 parseNumbers(Arg->getValue(), &Config->ImageBase);
697 if (auto *Arg = Args.getLastArg(OPT_stack))
698 parseNumbers(Arg->getValue(), &Config->StackReserve, &Config->StackCommit);
701 if (auto *Arg = Args.getLastArg(OPT_heap))
702 parseNumbers(Arg->getValue(), &Config->HeapReserve, &Config->HeapCommit);
705 if (auto *Arg = Args.getLastArg(OPT_version))
706 parseVersion(Arg->getValue(), &Config->MajorImageVersion,
707 &Config->MinorImageVersion);
710 if (auto *Arg = Args.getLastArg(OPT_subsystem))
711 parseSubsystem(Arg->getValue(), &Config->Subsystem, &Config->MajorOSVersion,
712 &Config->MinorOSVersion);
714 // Handle /alternatename
715 for (auto *Arg : Args.filtered(OPT_alternatename))
716 parseAlternateName(Arg->getValue());
719 for (auto *Arg : Args.filtered(OPT_incl))
720 addUndefined(Arg->getValue());
723 if (auto *Arg = Args.getLastArg(OPT_implib))
724 Config->Implib = Arg->getValue();
727 for (auto *Arg : Args.filtered(OPT_opt)) {
728 std::string Str = StringRef(Arg->getValue()).lower();
729 SmallVector<StringRef, 1> Vec;
730 StringRef(Str).split(Vec, ',');
731 for (StringRef S : Vec) {
733 Config->DoGC = false;
734 Config->DoICF = false;
737 if (S == "icf" || StringRef(S).startswith("icf=")) {
738 Config->DoICF = true;
742 Config->DoICF = false;
745 if (StringRef(S).startswith("lldlto=")) {
746 StringRef OptLevel = StringRef(S).substr(7);
747 if (OptLevel.getAsInteger(10, Config->LTOOptLevel) ||
748 Config->LTOOptLevel > 3)
749 error("/opt:lldlto: invalid optimization level: " + OptLevel);
752 if (StringRef(S).startswith("lldltojobs=")) {
753 StringRef Jobs = StringRef(S).substr(11);
754 if (Jobs.getAsInteger(10, Config->LTOJobs) || Config->LTOJobs == 0)
755 error("/opt:lldltojobs: invalid job count: " + Jobs);
758 if (StringRef(S).startswith("lldltopartitions=")) {
759 StringRef N = StringRef(S).substr(17);
760 if (N.getAsInteger(10, Config->LTOPartitions) ||
761 Config->LTOPartitions == 0)
762 error("/opt:lldltopartitions: invalid partition count: " + N);
765 if (S != "ref" && S != "lbr" && S != "nolbr")
766 error("/opt: unknown option: " + S);
770 // Handle /lldsavetemps
771 if (Args.hasArg(OPT_lldsavetemps))
772 Config->SaveTemps = true;
774 // Handle /failifmismatch
775 for (auto *Arg : Args.filtered(OPT_failifmismatch))
776 checkFailIfMismatch(Arg->getValue());
779 for (auto *Arg : Args.filtered(OPT_merge))
780 parseMerge(Arg->getValue());
783 for (auto *Arg : Args.filtered(OPT_section))
784 parseSection(Arg->getValue());
787 if (auto *Arg = Args.getLastArg(OPT_manifest_colon))
788 parseManifest(Arg->getValue());
790 // Handle /manifestuac
791 if (auto *Arg = Args.getLastArg(OPT_manifestuac))
792 parseManifestUAC(Arg->getValue());
794 // Handle /manifestdependency
795 if (auto *Arg = Args.getLastArg(OPT_manifestdependency))
796 Config->ManifestDependency = Arg->getValue();
798 // Handle /manifestfile
799 if (auto *Arg = Args.getLastArg(OPT_manifestfile))
800 Config->ManifestFile = Arg->getValue();
802 // Handle /manifestinput
803 for (auto *Arg : Args.filtered(OPT_manifestinput))
804 Config->ManifestInput.push_back(Arg->getValue());
806 // Handle miscellaneous boolean flags.
807 if (Args.hasArg(OPT_allowbind_no))
808 Config->AllowBind = false;
809 if (Args.hasArg(OPT_allowisolation_no))
810 Config->AllowIsolation = false;
811 if (Args.hasArg(OPT_dynamicbase_no))
812 Config->DynamicBase = false;
813 if (Args.hasArg(OPT_nxcompat_no))
814 Config->NxCompat = false;
815 if (Args.hasArg(OPT_tsaware_no))
816 Config->TerminalServerAware = false;
817 if (Args.hasArg(OPT_nosymtab))
818 Config->WriteSymtab = false;
819 Config->DumpPdb = Args.hasArg(OPT_dumppdb);
820 Config->DebugPdb = Args.hasArg(OPT_debugpdb);
822 Config->MapFile = getMapFile(Args);
827 // Create a list of input files. Files can be given as arguments
828 // for /defaultlib option.
829 std::vector<MemoryBufferRef> MBs;
830 for (auto *Arg : Args.filtered(OPT_INPUT))
831 if (Optional<StringRef> Path = findFile(Arg->getValue()))
833 for (auto *Arg : Args.filtered(OPT_defaultlib))
834 if (Optional<StringRef> Path = findLib(Arg->getValue()))
837 // Windows specific -- Create a resource file containing a manifest file.
838 if (Config->Manifest == Configuration::Embed)
839 addBuffer(createManifestRes());
841 // Read all input files given via the command line.
844 // We should have inferred a machine type by now from the input files, but if
845 // not we assume x64.
846 if (Config->Machine == IMAGE_FILE_MACHINE_UNKNOWN) {
847 warn("/machine is not specified. x64 is assumed");
848 Config->Machine = AMD64;
851 // Windows specific -- Input files can be Windows resource files (.res files).
852 // We invoke cvtres.exe to convert resource files to a regular COFF file
853 // then link the result file normally.
854 if (!Resources.empty())
855 addBuffer(convertResToCOFF(Resources));
858 Tar->append("response.txt",
859 createResponseFile(Args, FilePaths,
860 ArrayRef<StringRef>(SearchPaths).slice(1)));
862 // Handle /largeaddressaware
863 if (Config->is64() || Args.hasArg(OPT_largeaddressaware))
864 Config->LargeAddressAware = true;
866 // Handle /highentropyva
867 if (Config->is64() && !Args.hasArg(OPT_highentropyva_no))
868 Config->HighEntropyVA = true;
870 // Handle /entry and /dll
871 if (auto *Arg = Args.getLastArg(OPT_entry)) {
872 Config->Entry = addUndefined(mangle(Arg->getValue()));
873 } else if (Args.hasArg(OPT_dll) && !Config->NoEntry) {
874 StringRef S = (Config->Machine == I386) ? "__DllMainCRTStartup@12"
875 : "_DllMainCRTStartup";
876 Config->Entry = addUndefined(S);
877 } else if (!Config->NoEntry) {
878 // Windows specific -- If entry point name is not given, we need to
879 // infer that from user-defined entry name.
880 StringRef S = findDefaultEntry();
882 fatal("entry point must be defined");
883 Config->Entry = addUndefined(S);
884 log("Entry name inferred: " + S);
888 for (auto *Arg : Args.filtered(OPT_export)) {
889 Export E = parseExport(Arg->getValue());
890 if (Config->Machine == I386) {
891 if (!isDecorated(E.Name))
892 E.Name = Saver.save("_" + E.Name);
893 if (!E.ExtName.empty() && !isDecorated(E.ExtName))
894 E.ExtName = Saver.save("_" + E.ExtName);
896 Config->Exports.push_back(E);
900 if (auto *Arg = Args.getLastArg(OPT_deffile)) {
901 // parseModuleDefs mutates Config object.
903 takeBuffer(check(MemoryBuffer::getFile(Arg->getValue()),
904 Twine("could not open ") + Arg->getValue())));
908 for (auto *Arg : Args.filtered(OPT_delayload)) {
909 Config->DelayLoads.insert(StringRef(Arg->getValue()).lower());
910 if (Config->Machine == I386) {
911 Config->DelayLoadHelper = addUndefined("___delayLoadHelper2@8");
913 Config->DelayLoadHelper = addUndefined("__delayLoadHelper2");
917 // Set default image name if neither /out or /def set it.
918 if (Config->OutputFile.empty()) {
920 getOutputPath((*Args.filtered(OPT_INPUT).begin())->getValue());
923 // Put the PDB next to the image if no /pdb flag was passed.
924 if (Config->Debug && Config->PDBPath.empty()) {
925 Config->PDBPath = Config->OutputFile;
926 sys::path::replace_extension(Config->PDBPath, ".pdb");
929 // Disable PDB generation if the user requested it.
930 if (Args.hasArg(OPT_nopdb))
931 Config->PDBPath = "";
933 // Set default image base if /base is not given.
934 if (Config->ImageBase == uint64_t(-1))
935 Config->ImageBase = getDefaultImageBase();
937 Symtab.addRelative(mangle("__ImageBase"), 0);
938 if (Config->Machine == I386) {
939 Config->SEHTable = Symtab.addRelative("___safe_se_handler_table", 0);
940 Config->SEHCount = Symtab.addAbsolute("___safe_se_handler_count", 0);
943 // We do not support /guard:cf (control flow protection) yet.
944 // Define CFG symbols anyway so that we can link MSVC 2015 CRT.
945 Symtab.addAbsolute(mangle("__guard_fids_table"), 0);
946 Symtab.addAbsolute(mangle("__guard_fids_count"), 0);
947 Symtab.addAbsolute(mangle("__guard_flags"), 0x100);
949 // This code may add new undefined symbols to the link, which may enqueue more
950 // symbol resolution tasks, so we need to continue executing tasks until we
953 // Windows specific -- if entry point is not found,
954 // search for its mangled names.
956 Symtab.mangleMaybe(Config->Entry);
958 // Windows specific -- Make sure we resolve all dllexported symbols.
959 for (Export &E : Config->Exports) {
960 if (!E.ForwardTo.empty())
962 E.Sym = addUndefined(E.Name);
964 Symtab.mangleMaybe(E.Sym);
967 // Add weak aliases. Weak aliases is a mechanism to give remaining
968 // undefined symbols final chance to be resolved successfully.
969 for (auto Pair : Config->AlternateNames) {
970 StringRef From = Pair.first;
971 StringRef To = Pair.second;
972 Symbol *Sym = Symtab.find(From);
975 if (auto *U = dyn_cast<Undefined>(Sym->body()))
977 U->WeakAlias = Symtab.addUndefined(To);
980 // Windows specific -- if __load_config_used can be resolved, resolve it.
981 if (Symtab.findUnderscore("_load_config_used"))
982 addUndefined(mangle("_load_config_used"));
988 // If /msvclto is given, we use the MSVC linker to link LTO output files.
989 // This is useful because MSVC link.exe can generate complete PDBs.
990 if (Args.hasArg(OPT_msvclto)) {
995 // Do LTO by compiling bitcode input files to a set of native COFF files then
997 Symtab.addCombinedLTOObjects();
1000 // Make sure we have resolved all symbols.
1001 Symtab.reportRemainingUndefines();
1003 // Windows specific -- if no /subsystem is given, we need to infer
1004 // that from entry point name.
1005 if (Config->Subsystem == IMAGE_SUBSYSTEM_UNKNOWN) {
1006 Config->Subsystem = inferSubsystem();
1007 if (Config->Subsystem == IMAGE_SUBSYSTEM_UNKNOWN)
1008 fatal("subsystem must be defined");
1012 if (Args.hasArg(OPT_safeseh)) {
1013 for (ObjectFile *File : Symtab.ObjectFiles)
1014 if (!File->SEHCompat)
1015 error("/safeseh: " + File->getName() + " is not compatible with SEH");
1020 // Windows specific -- when we are creating a .dll file, we also
1021 // need to create a .lib file.
1022 if (!Config->Exports.empty() || Config->DLL) {
1024 writeImportLibrary();
1025 assignExportOrdinals();
1028 // Windows specific -- Create a side-by-side manifest file.
1029 if (Config->Manifest == Configuration::SideBySide)
1030 createSideBySideManifest();
1032 // Identify unreferenced COMDAT sections.
1034 markLive(Symtab.getChunks());
1036 // Identify identical COMDAT sections to merge them.
1038 doICF(Symtab.getChunks());
1040 // Write the result.
1041 writeResult(&Symtab);
1043 // Call exit to avoid calling destructors.