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/BinaryFormat/Magic.h"
22 #include "llvm/Object/ArchiveWriter.h"
23 #include "llvm/Object/COFFImportFile.h"
24 #include "llvm/Object/COFFModuleDefinition.h"
25 #include "llvm/Option/Arg.h"
26 #include "llvm/Option/ArgList.h"
27 #include "llvm/Option/Option.h"
28 #include "llvm/Support/Debug.h"
29 #include "llvm/Support/Path.h"
30 #include "llvm/Support/Process.h"
31 #include "llvm/Support/TarWriter.h"
32 #include "llvm/Support/TargetSelect.h"
33 #include "llvm/Support/raw_ostream.h"
34 #include "llvm/ToolDrivers/llvm-lib/LibDriver.h"
41 using namespace llvm::object;
42 using namespace llvm::COFF;
43 using llvm::sys::Process;
48 Configuration *Config;
51 BumpPtrAllocator BAlloc;
52 StringSaver Saver{BAlloc};
53 std::vector<SpecificAllocBase *> SpecificAllocBase::Instances;
55 bool link(ArrayRef<const char *> Args, raw_ostream &Diag) {
58 Config = make<Configuration>();
59 Config->Argv = {Args.begin(), Args.end()};
60 Config->ColorDiagnostics =
61 (ErrorOS == &llvm::errs() && Process::StandardErrHasColors());
62 Driver = make<LinkerDriver>();
67 // Drop directory components and replace extension with ".exe" or ".dll".
68 static std::string getOutputPath(StringRef Path) {
69 auto P = Path.find_last_of("\\/");
70 StringRef S = (P == StringRef::npos) ? Path : Path.substr(P + 1);
71 const char* E = Config->DLL ? ".dll" : ".exe";
72 return (S.substr(0, S.rfind('.')) + E).str();
75 // ErrorOr is not default constructible, so it cannot be used as the type
76 // parameter of a future.
77 // FIXME: We could open the file in createFutureForFile and avoid needing to
78 // return an error here, but for the moment that would cost us a file descriptor
79 // (a limited resource on Windows) for the duration that the future is pending.
80 typedef std::pair<std::unique_ptr<MemoryBuffer>, std::error_code> MBErrPair;
82 // Create a std::future that opens and maps a file using the best strategy for
84 static std::future<MBErrPair> createFutureForFile(std::string Path) {
86 // On Windows, file I/O is relatively slow so it is best to do this
88 auto Strategy = std::launch::async;
90 auto Strategy = std::launch::deferred;
92 return std::async(Strategy, [=]() {
93 auto MBOrErr = MemoryBuffer::getFile(Path);
95 return MBErrPair{nullptr, MBOrErr.getError()};
96 return MBErrPair{std::move(*MBOrErr), std::error_code()};
100 MemoryBufferRef LinkerDriver::takeBuffer(std::unique_ptr<MemoryBuffer> MB) {
101 MemoryBufferRef MBRef = *MB;
102 make<std::unique_ptr<MemoryBuffer>>(std::move(MB)); // take ownership
105 Driver->Tar->append(relativeToRoot(MBRef.getBufferIdentifier()),
110 void LinkerDriver::addBuffer(std::unique_ptr<MemoryBuffer> MB) {
111 MemoryBufferRef MBRef = takeBuffer(std::move(MB));
113 // File type is detected by contents, not by file extension.
114 file_magic Magic = identify_magic(MBRef.getBuffer());
115 if (Magic == file_magic::windows_resource) {
116 Resources.push_back(MBRef);
120 FilePaths.push_back(MBRef.getBufferIdentifier());
121 if (Magic == file_magic::archive)
122 return Symtab.addFile(make<ArchiveFile>(MBRef));
123 if (Magic == file_magic::bitcode)
124 return Symtab.addFile(make<BitcodeFile>(MBRef));
126 if (Magic == file_magic::coff_cl_gl_object)
127 error(MBRef.getBufferIdentifier() + ": is not a native COFF file. "
128 "Recompile without /GL");
130 Symtab.addFile(make<ObjectFile>(MBRef));
133 void LinkerDriver::enqueuePath(StringRef Path) {
135 std::make_shared<std::future<MBErrPair>>(createFutureForFile(Path));
136 std::string PathStr = Path;
138 auto MBOrErr = Future->get();
140 error("could not open " + PathStr + ": " + MBOrErr.second.message());
142 Driver->addBuffer(std::move(MBOrErr.first));
146 void LinkerDriver::addArchiveBuffer(MemoryBufferRef MB, StringRef SymName,
147 StringRef ParentName) {
148 file_magic Magic = identify_magic(MB.getBuffer());
149 if (Magic == file_magic::coff_import_library) {
150 Symtab.addFile(make<ImportFile>(MB));
155 if (Magic == file_magic::coff_object) {
156 Obj = make<ObjectFile>(MB);
157 } else if (Magic == file_magic::bitcode) {
158 Obj = make<BitcodeFile>(MB);
160 error("unknown file type: " + MB.getBufferIdentifier());
164 Obj->ParentName = ParentName;
166 log("Loaded " + toString(Obj) + " for " + SymName);
169 void LinkerDriver::enqueueArchiveMember(const Archive::Child &C,
171 StringRef ParentName) {
172 if (!C.getParent()->isThin()) {
173 MemoryBufferRef MB = check(
174 C.getMemoryBufferRef(),
175 "could not get the buffer for the member defining symbol " + SymName);
176 enqueueTask([=]() { Driver->addArchiveBuffer(MB, SymName, ParentName); });
180 auto Future = std::make_shared<std::future<MBErrPair>>(createFutureForFile(
181 check(C.getFullName(),
182 "could not get the filename for the member defining symbol " +
185 auto MBOrErr = Future->get();
187 fatal(MBOrErr.second,
188 "could not get the buffer for the member defining " + SymName);
189 Driver->addArchiveBuffer(takeBuffer(std::move(MBOrErr.first)), SymName,
194 static bool isDecorated(StringRef Sym) {
195 return Sym.startswith("_") || Sym.startswith("@") || Sym.startswith("?");
198 // Parses .drectve section contents and returns a list of files
199 // specified by /defaultlib.
200 void LinkerDriver::parseDirectives(StringRef S) {
201 opt::InputArgList Args = Parser.parse(S);
203 for (auto *Arg : Args) {
204 switch (Arg->getOption().getID()) {
205 case OPT_alternatename:
206 parseAlternateName(Arg->getValue());
209 if (Optional<StringRef> Path = findLib(Arg->getValue()))
213 Export E = parseExport(Arg->getValue());
215 Config->Exports.push_back(E);
218 case OPT_failifmismatch:
219 checkFailIfMismatch(Arg->getValue());
222 addUndefined(Arg->getValue());
225 parseMerge(Arg->getValue());
227 case OPT_nodefaultlib:
228 Config->NoDefaultLibs.insert(doFindLib(Arg->getValue()));
231 parseSection(Arg->getValue());
233 case OPT_editandcontinue:
236 case OPT_throwingnew:
239 error(Arg->getSpelling() + " is not allowed in .drectve");
244 // Find file from search paths. You can omit ".obj", this function takes
245 // care of that. Note that the returned path is not guaranteed to exist.
246 StringRef LinkerDriver::doFindFile(StringRef Filename) {
247 bool HasPathSep = (Filename.find_first_of("/\\") != StringRef::npos);
250 bool HasExt = (Filename.find('.') != StringRef::npos);
251 for (StringRef Dir : SearchPaths) {
252 SmallString<128> Path = Dir;
253 sys::path::append(Path, Filename);
254 if (sys::fs::exists(Path.str()))
255 return Saver.save(Path.str());
258 if (sys::fs::exists(Path.str()))
259 return Saver.save(Path.str());
265 // Resolves a file path. This never returns the same path
266 // (in that case, it returns None).
267 Optional<StringRef> LinkerDriver::findFile(StringRef Filename) {
268 StringRef Path = doFindFile(Filename);
269 bool Seen = !VisitedFiles.insert(Path.lower()).second;
275 // Find library file from search path.
276 StringRef LinkerDriver::doFindLib(StringRef Filename) {
277 // Add ".lib" to Filename if that has no file extension.
278 bool HasExt = (Filename.find('.') != StringRef::npos);
280 Filename = Saver.save(Filename + ".lib");
281 return doFindFile(Filename);
284 // Resolves a library path. /nodefaultlib options are taken into
285 // consideration. This never returns the same path (in that case,
287 Optional<StringRef> LinkerDriver::findLib(StringRef Filename) {
288 if (Config->NoDefaultLibAll)
290 if (!VisitedLibs.insert(Filename.lower()).second)
292 StringRef Path = doFindLib(Filename);
293 if (Config->NoDefaultLibs.count(Path))
295 if (!VisitedFiles.insert(Path.lower()).second)
300 // Parses LIB environment which contains a list of search paths.
301 void LinkerDriver::addLibSearchPaths() {
302 Optional<std::string> EnvOpt = Process::GetEnv("LIB");
303 if (!EnvOpt.hasValue())
305 StringRef Env = Saver.save(*EnvOpt);
306 while (!Env.empty()) {
308 std::tie(Path, Env) = Env.split(';');
309 SearchPaths.push_back(Path);
313 SymbolBody *LinkerDriver::addUndefined(StringRef Name) {
314 SymbolBody *B = Symtab.addUndefined(Name);
315 Config->GCRoot.insert(B);
319 // Symbol names are mangled by appending "_" prefix on x86.
320 StringRef LinkerDriver::mangle(StringRef Sym) {
321 assert(Config->Machine != IMAGE_FILE_MACHINE_UNKNOWN);
322 if (Config->Machine == I386)
323 return Saver.save("_" + Sym);
327 // Windows specific -- find default entry point name.
328 StringRef LinkerDriver::findDefaultEntry() {
329 // User-defined main functions and their corresponding entry points.
330 static const char *Entries[][2] = {
331 {"main", "mainCRTStartup"},
332 {"wmain", "wmainCRTStartup"},
333 {"WinMain", "WinMainCRTStartup"},
334 {"wWinMain", "wWinMainCRTStartup"},
336 for (auto E : Entries) {
337 StringRef Entry = Symtab.findMangle(mangle(E[0]));
338 if (!Entry.empty() && !isa<Undefined>(Symtab.find(Entry)->body()))
344 WindowsSubsystem LinkerDriver::inferSubsystem() {
346 return IMAGE_SUBSYSTEM_WINDOWS_GUI;
347 if (Symtab.findUnderscore("main") || Symtab.findUnderscore("wmain"))
348 return IMAGE_SUBSYSTEM_WINDOWS_CUI;
349 if (Symtab.findUnderscore("WinMain") || Symtab.findUnderscore("wWinMain"))
350 return IMAGE_SUBSYSTEM_WINDOWS_GUI;
351 return IMAGE_SUBSYSTEM_UNKNOWN;
354 static uint64_t getDefaultImageBase() {
356 return Config->DLL ? 0x180000000 : 0x140000000;
357 return Config->DLL ? 0x10000000 : 0x400000;
360 static std::string createResponseFile(const opt::InputArgList &Args,
361 ArrayRef<StringRef> FilePaths,
362 ArrayRef<StringRef> SearchPaths) {
364 raw_svector_ostream OS(Data);
366 for (auto *Arg : Args) {
367 switch (Arg->getOption().getID()) {
374 OS << toString(Arg) << "\n";
378 for (StringRef Path : SearchPaths) {
379 std::string RelPath = relativeToRoot(Path);
380 OS << "/libpath:" << quote(RelPath) << "\n";
383 for (StringRef Path : FilePaths)
384 OS << quote(relativeToRoot(Path)) << "\n";
389 static unsigned getDefaultDebugType(const opt::InputArgList &Args) {
390 unsigned DebugTypes = static_cast<unsigned>(DebugType::CV);
391 if (Args.hasArg(OPT_driver))
392 DebugTypes |= static_cast<unsigned>(DebugType::PData);
393 if (Args.hasArg(OPT_profile))
394 DebugTypes |= static_cast<unsigned>(DebugType::Fixup);
398 static unsigned parseDebugType(StringRef Arg) {
399 SmallVector<StringRef, 3> Types;
400 Arg.split(Types, ',', /*KeepEmpty=*/false);
402 unsigned DebugTypes = static_cast<unsigned>(DebugType::None);
403 for (StringRef Type : Types)
404 DebugTypes |= StringSwitch<unsigned>(Type.lower())
405 .Case("cv", static_cast<unsigned>(DebugType::CV))
406 .Case("pdata", static_cast<unsigned>(DebugType::PData))
407 .Case("fixup", static_cast<unsigned>(DebugType::Fixup))
412 static std::string getMapFile(const opt::InputArgList &Args) {
413 auto *Arg = Args.getLastArg(OPT_lldmap, OPT_lldmap_file);
416 if (Arg->getOption().getID() == OPT_lldmap_file)
417 return Arg->getValue();
419 assert(Arg->getOption().getID() == OPT_lldmap);
420 StringRef OutFile = Config->OutputFile;
421 return (OutFile.substr(0, OutFile.rfind('.')) + ".map").str();
424 static std::string getImplibPath() {
425 if (!Config->Implib.empty())
426 return Config->Implib;
427 SmallString<128> Out = StringRef(Config->OutputFile);
428 sys::path::replace_extension(Out, ".lib");
433 // The import name is caculated as the following:
435 // | LIBRARY w/ ext | LIBRARY w/o ext | no LIBRARY
436 // -----+----------------+---------------------+------------------
437 // LINK | {value} | {value}.{.dll/.exe} | {output name}
438 // LIB | {value} | {value}.dll | {output name}.dll
440 static std::string getImportName(bool AsLib) {
441 SmallString<128> Out;
443 if (Config->ImportName.empty()) {
444 Out.assign(sys::path::filename(Config->OutputFile));
446 sys::path::replace_extension(Out, ".dll");
448 Out.assign(Config->ImportName);
449 if (!sys::path::has_extension(Out))
450 sys::path::replace_extension(Out,
451 (Config->DLL || AsLib) ? ".dll" : ".exe");
457 static void createImportLibrary(bool AsLib) {
458 std::vector<COFFShortExport> Exports;
459 for (Export &E1 : Config->Exports) {
461 // Use SymbolName, which will have any stdcall or fastcall qualifiers.
462 E2.Name = E1.SymbolName;
463 E2.ExtName = E1.ExtName;
464 E2.Ordinal = E1.Ordinal;
465 E2.Noname = E1.Noname;
467 E2.Private = E1.Private;
468 E2.Constant = E1.Constant;
469 Exports.push_back(E2);
472 writeImportLibrary(getImportName(AsLib), getImplibPath(), Exports,
476 static void parseModuleDefs(StringRef Path) {
477 std::unique_ptr<MemoryBuffer> MB = check(
478 MemoryBuffer::getFile(Path, -1, false, true), "could not open " + Path);
479 COFFModuleDefinition M =
480 check(parseCOFFModuleDefinition(MB->getMemBufferRef(), Config->Machine));
482 if (Config->OutputFile.empty())
483 Config->OutputFile = Saver.save(M.OutputFile);
484 Config->ImportName = Saver.save(M.ImportName);
486 Config->ImageBase = M.ImageBase;
488 Config->StackReserve = M.StackReserve;
490 Config->StackCommit = M.StackCommit;
492 Config->HeapReserve = M.HeapReserve;
494 Config->HeapCommit = M.HeapCommit;
495 if (M.MajorImageVersion)
496 Config->MajorImageVersion = M.MajorImageVersion;
497 if (M.MinorImageVersion)
498 Config->MinorImageVersion = M.MinorImageVersion;
499 if (M.MajorOSVersion)
500 Config->MajorOSVersion = M.MajorOSVersion;
501 if (M.MinorOSVersion)
502 Config->MinorOSVersion = M.MinorOSVersion;
504 for (COFFShortExport E1 : M.Exports) {
506 E2.Name = Saver.save(E1.Name);
508 E2.ExtName = Saver.save(E1.ExtName);
509 E2.Ordinal = E1.Ordinal;
510 E2.Noname = E1.Noname;
512 E2.Private = E1.Private;
513 E2.Constant = E1.Constant;
514 Config->Exports.push_back(E2);
518 std::vector<MemoryBufferRef> getArchiveMembers(Archive *File) {
519 std::vector<MemoryBufferRef> V;
520 Error Err = Error::success();
521 for (const ErrorOr<Archive::Child> &COrErr : File->children(Err)) {
524 File->getFileName() + ": could not get the child of the archive");
525 MemoryBufferRef MBRef =
526 check(C.getMemoryBufferRef(),
527 File->getFileName() +
528 ": could not get the buffer for a child of the archive");
532 fatal(File->getFileName() +
533 ": Archive::children failed: " + toString(std::move(Err)));
537 // A helper function for filterBitcodeFiles.
538 static bool needsRebuilding(MemoryBufferRef MB) {
539 // The MSVC linker doesn't support thin archives, so if it's a thin
540 // archive, we always need to rebuild it.
541 std::unique_ptr<Archive> File =
542 check(Archive::create(MB), "Failed to read " + MB.getBufferIdentifier());
546 // Returns true if the archive contains at least one bitcode file.
547 for (MemoryBufferRef Member : getArchiveMembers(File.get()))
548 if (identify_magic(Member.getBuffer()) == file_magic::bitcode)
553 // Opens a given path as an archive file and removes bitcode files
554 // from them if exists. This function is to appease the MSVC linker as
555 // their linker doesn't like archive files containing non-native
558 // If a given archive doesn't contain bitcode files, the archive path
559 // is returned as-is. Otherwise, a new temporary file is created and
560 // its path is returned.
561 static Optional<std::string>
562 filterBitcodeFiles(StringRef Path, std::vector<std::string> &TemporaryFiles) {
563 std::unique_ptr<MemoryBuffer> MB = check(
564 MemoryBuffer::getFile(Path, -1, false, true), "could not open " + Path);
565 MemoryBufferRef MBRef = MB->getMemBufferRef();
566 file_magic Magic = identify_magic(MBRef.getBuffer());
568 if (Magic == file_magic::bitcode)
570 if (Magic != file_magic::archive)
572 if (!needsRebuilding(MBRef))
575 std::unique_ptr<Archive> File =
576 check(Archive::create(MBRef),
577 MBRef.getBufferIdentifier() + ": failed to parse archive");
579 std::vector<NewArchiveMember> New;
580 for (MemoryBufferRef Member : getArchiveMembers(File.get()))
581 if (identify_magic(Member.getBuffer()) != file_magic::bitcode)
582 New.emplace_back(Member);
587 log("Creating a temporary archive for " + Path + " to remove bitcode files");
590 if (auto EC = sys::fs::createTemporaryFile("lld-" + sys::path::stem(Path),
592 fatal(EC, "cannot create a temporary file");
593 std::string Temp = S.str();
594 TemporaryFiles.push_back(Temp);
596 std::pair<StringRef, std::error_code> Ret =
597 llvm::writeArchive(Temp, New, /*WriteSymtab=*/true, Archive::Kind::K_GNU,
598 /*Deterministics=*/true,
601 error("failed to create a new archive " + S.str() + ": " + Ret.first);
605 // Create response file contents and invoke the MSVC linker.
606 void LinkerDriver::invokeMSVC(opt::InputArgList &Args) {
607 std::string Rsp = "/nologo\n";
608 std::vector<std::string> Temps;
610 // Write out archive members that we used in symbol resolution and pass these
611 // to MSVC before any archives, so that MSVC uses the same objects to satisfy
613 for (const auto *O : Symtab.ObjectFiles) {
614 if (O->ParentName.empty())
618 if (auto EC = sys::fs::createTemporaryFile(
619 "lld-" + sys::path::filename(O->ParentName), ".obj", Fd, S))
620 fatal(EC, "cannot create a temporary file");
621 raw_fd_ostream OS(Fd, /*shouldClose*/ true);
622 OS << O->MB.getBuffer();
623 Temps.push_back(S.str());
624 Rsp += quote(S) + "\n";
627 for (auto *Arg : Args) {
628 switch (Arg->getOption().getID()) {
631 case OPT_lldmap_file:
632 case OPT_lldsavetemps:
634 // LLD-specific options are stripped.
637 if (!StringRef(Arg->getValue()).startswith("lld"))
638 Rsp += toString(Arg) + " ";
641 if (Optional<StringRef> Path = doFindFile(Arg->getValue())) {
642 if (Optional<std::string> S = filterBitcodeFiles(*Path, Temps))
643 Rsp += quote(*S) + "\n";
646 Rsp += quote(Arg->getValue()) + "\n";
650 Rsp += toString(Arg) + "\n";
654 std::vector<StringRef> ObjectFiles = Symtab.compileBitcodeFiles();
655 runMSVCLinker(Rsp, ObjectFiles);
657 for (StringRef Path : Temps)
658 sys::fs::remove(Path);
661 void LinkerDriver::enqueueTask(std::function<void()> Task) {
662 TaskQueue.push_back(std::move(Task));
665 bool LinkerDriver::run() {
666 bool DidWork = !TaskQueue.empty();
667 while (!TaskQueue.empty()) {
669 TaskQueue.pop_front();
674 void LinkerDriver::link(ArrayRef<const char *> ArgsArr) {
675 // If the first command line argument is "/lib", link.exe acts like lib.exe.
676 // We call our own implementation of lib.exe that understands bitcode files.
677 if (ArgsArr.size() > 1 && StringRef(ArgsArr[1]).equals_lower("/lib")) {
678 if (llvm::libDriverMain(ArgsArr.slice(1)) != 0)
684 InitializeAllTargetInfos();
685 InitializeAllTargets();
686 InitializeAllTargetMCs();
687 InitializeAllAsmParsers();
688 InitializeAllAsmPrinters();
689 InitializeAllDisassemblers();
691 // Parse command line options.
692 opt::InputArgList Args = Parser.parseLINK(ArgsArr.slice(1));
694 // Parse and evaluate -mllvm options.
695 std::vector<const char *> V;
696 V.push_back("lld-link (LLVM option parsing)");
697 for (auto *Arg : Args.filtered(OPT_mllvm))
698 V.push_back(Arg->getValue());
699 cl::ParseCommandLineOptions(V.size(), V.data());
701 // Handle /errorlimit early, because error() depends on it.
702 if (auto *Arg = Args.getLastArg(OPT_errorlimit)) {
704 StringRef S = Arg->getValue();
705 if (S.getAsInteger(10, N))
706 error(Arg->getSpelling() + " number expected, but got " + S);
707 Config->ErrorLimit = N;
711 if (Args.hasArg(OPT_help)) {
712 printHelp(ArgsArr[0]);
716 if (auto *Arg = Args.getLastArg(OPT_linkrepro)) {
717 SmallString<64> Path = StringRef(Arg->getValue());
718 sys::path::append(Path, "repro.tar");
720 Expected<std::unique_ptr<TarWriter>> ErrOrWriter =
721 TarWriter::create(Path, "repro");
724 Tar = std::move(*ErrOrWriter);
726 error("/linkrepro: failed to open " + Path + ": " +
727 toString(ErrOrWriter.takeError()));
731 if (!Args.hasArgNoClaim(OPT_INPUT)) {
732 if (Args.hasArgNoClaim(OPT_deffile))
733 Config->NoEntry = true;
735 fatal("no input files");
738 // Construct search path list.
739 SearchPaths.push_back("");
740 for (auto *Arg : Args.filtered(OPT_libpath))
741 SearchPaths.push_back(Arg->getValue());
745 if (auto *Arg = Args.getLastArg(OPT_out))
746 Config->OutputFile = Arg->getValue();
749 if (Args.hasArg(OPT_verbose))
750 Config->Verbose = true;
752 // Handle /force or /force:unresolved
753 if (Args.hasArg(OPT_force) || Args.hasArg(OPT_force_unresolved))
754 Config->Force = true;
757 if (Args.hasArg(OPT_debug)) {
758 Config->Debug = true;
760 Args.hasArg(OPT_debugtype)
761 ? parseDebugType(Args.getLastArg(OPT_debugtype)->getValue())
762 : getDefaultDebugType(Args);
765 // Create a dummy PDB file to satisfy build sytem rules.
766 if (auto *Arg = Args.getLastArg(OPT_pdb))
767 Config->PDBPath = Arg->getValue();
770 if (Args.hasArg(OPT_noentry)) {
771 if (Args.hasArg(OPT_dll))
772 Config->NoEntry = true;
774 error("/noentry must be specified with /dll");
778 if (Args.hasArg(OPT_dll)) {
780 Config->ManifestID = 2;
784 if (Args.hasArg(OPT_fixed)) {
785 if (Args.hasArg(OPT_dynamicbase)) {
786 error("/fixed must not be specified with /dynamicbase");
788 Config->Relocatable = false;
789 Config->DynamicBase = false;
793 if (Args.hasArg(OPT_appcontainer))
794 Config->AppContainer = true;
797 if (auto *Arg = Args.getLastArg(OPT_machine))
798 Config->Machine = getMachineType(Arg->getValue());
800 // Handle /nodefaultlib:<filename>
801 for (auto *Arg : Args.filtered(OPT_nodefaultlib))
802 Config->NoDefaultLibs.insert(doFindLib(Arg->getValue()));
804 // Handle /nodefaultlib
805 if (Args.hasArg(OPT_nodefaultlib_all))
806 Config->NoDefaultLibAll = true;
809 if (auto *Arg = Args.getLastArg(OPT_base))
810 parseNumbers(Arg->getValue(), &Config->ImageBase);
813 if (auto *Arg = Args.getLastArg(OPT_stack))
814 parseNumbers(Arg->getValue(), &Config->StackReserve, &Config->StackCommit);
817 if (auto *Arg = Args.getLastArg(OPT_heap))
818 parseNumbers(Arg->getValue(), &Config->HeapReserve, &Config->HeapCommit);
821 if (auto *Arg = Args.getLastArg(OPT_version))
822 parseVersion(Arg->getValue(), &Config->MajorImageVersion,
823 &Config->MinorImageVersion);
826 if (auto *Arg = Args.getLastArg(OPT_subsystem))
827 parseSubsystem(Arg->getValue(), &Config->Subsystem, &Config->MajorOSVersion,
828 &Config->MinorOSVersion);
830 // Handle /alternatename
831 for (auto *Arg : Args.filtered(OPT_alternatename))
832 parseAlternateName(Arg->getValue());
835 for (auto *Arg : Args.filtered(OPT_incl))
836 addUndefined(Arg->getValue());
839 if (auto *Arg = Args.getLastArg(OPT_implib))
840 Config->Implib = Arg->getValue();
843 for (auto *Arg : Args.filtered(OPT_opt)) {
844 std::string Str = StringRef(Arg->getValue()).lower();
845 SmallVector<StringRef, 1> Vec;
846 StringRef(Str).split(Vec, ',');
847 for (StringRef S : Vec) {
849 Config->DoGC = false;
850 Config->DoICF = false;
853 if (S == "icf" || StringRef(S).startswith("icf=")) {
854 Config->DoICF = true;
858 Config->DoICF = false;
861 if (StringRef(S).startswith("lldlto=")) {
862 StringRef OptLevel = StringRef(S).substr(7);
863 if (OptLevel.getAsInteger(10, Config->LTOOptLevel) ||
864 Config->LTOOptLevel > 3)
865 error("/opt:lldlto: invalid optimization level: " + OptLevel);
868 if (StringRef(S).startswith("lldltojobs=")) {
869 StringRef Jobs = StringRef(S).substr(11);
870 if (Jobs.getAsInteger(10, Config->LTOJobs) || Config->LTOJobs == 0)
871 error("/opt:lldltojobs: invalid job count: " + Jobs);
874 if (StringRef(S).startswith("lldltopartitions=")) {
875 StringRef N = StringRef(S).substr(17);
876 if (N.getAsInteger(10, Config->LTOPartitions) ||
877 Config->LTOPartitions == 0)
878 error("/opt:lldltopartitions: invalid partition count: " + N);
881 if (S != "ref" && S != "lbr" && S != "nolbr")
882 error("/opt: unknown option: " + S);
886 // Handle /lldsavetemps
887 if (Args.hasArg(OPT_lldsavetemps))
888 Config->SaveTemps = true;
890 // Handle /failifmismatch
891 for (auto *Arg : Args.filtered(OPT_failifmismatch))
892 checkFailIfMismatch(Arg->getValue());
895 for (auto *Arg : Args.filtered(OPT_merge))
896 parseMerge(Arg->getValue());
899 for (auto *Arg : Args.filtered(OPT_section))
900 parseSection(Arg->getValue());
903 if (auto *Arg = Args.getLastArg(OPT_manifest_colon))
904 parseManifest(Arg->getValue());
906 // Handle /manifestuac
907 if (auto *Arg = Args.getLastArg(OPT_manifestuac))
908 parseManifestUAC(Arg->getValue());
910 // Handle /manifestdependency
911 if (auto *Arg = Args.getLastArg(OPT_manifestdependency))
912 Config->ManifestDependency = Arg->getValue();
914 // Handle /manifestfile
915 if (auto *Arg = Args.getLastArg(OPT_manifestfile))
916 Config->ManifestFile = Arg->getValue();
918 // Handle /manifestinput
919 for (auto *Arg : Args.filtered(OPT_manifestinput))
920 Config->ManifestInput.push_back(Arg->getValue());
922 // Handle miscellaneous boolean flags.
923 if (Args.hasArg(OPT_allowisolation_no))
924 Config->AllowIsolation = false;
925 if (Args.hasArg(OPT_dynamicbase_no))
926 Config->DynamicBase = false;
927 if (Args.hasArg(OPT_nxcompat_no))
928 Config->NxCompat = false;
929 if (Args.hasArg(OPT_tsaware_no))
930 Config->TerminalServerAware = false;
931 if (Args.hasArg(OPT_nosymtab))
932 Config->WriteSymtab = false;
934 Config->MapFile = getMapFile(Args);
939 // Create a list of input files. Files can be given as arguments
940 // for /defaultlib option.
941 std::vector<MemoryBufferRef> MBs;
942 for (auto *Arg : Args.filtered(OPT_INPUT))
943 if (Optional<StringRef> Path = findFile(Arg->getValue()))
945 for (auto *Arg : Args.filtered(OPT_defaultlib))
946 if (Optional<StringRef> Path = findLib(Arg->getValue()))
949 // Windows specific -- Create a resource file containing a manifest file.
950 if (Config->Manifest == Configuration::Embed)
951 addBuffer(createManifestRes());
953 // Read all input files given via the command line.
956 // We should have inferred a machine type by now from the input files, but if
957 // not we assume x64.
958 if (Config->Machine == IMAGE_FILE_MACHINE_UNKNOWN) {
959 warn("/machine is not specified. x64 is assumed");
960 Config->Machine = AMD64;
963 // Input files can be Windows resource files (.res files). We use
964 // WindowsResource to convert resource files to a regular COFF file,
965 // then link the resulting file normally.
966 if (!Resources.empty())
967 addBuffer(convertResToCOFF(Resources));
970 Tar->append("response.txt",
971 createResponseFile(Args, FilePaths,
972 ArrayRef<StringRef>(SearchPaths).slice(1)));
974 // Handle /largeaddressaware
975 if (Config->is64() || Args.hasArg(OPT_largeaddressaware))
976 Config->LargeAddressAware = true;
978 // Handle /highentropyva
979 if (Config->is64() && !Args.hasArg(OPT_highentropyva_no))
980 Config->HighEntropyVA = true;
982 // Handle /entry and /dll
983 if (auto *Arg = Args.getLastArg(OPT_entry)) {
984 Config->Entry = addUndefined(mangle(Arg->getValue()));
985 } else if (Args.hasArg(OPT_dll) && !Config->NoEntry) {
986 StringRef S = (Config->Machine == I386) ? "__DllMainCRTStartup@12"
987 : "_DllMainCRTStartup";
988 Config->Entry = addUndefined(S);
989 } else if (!Config->NoEntry) {
990 // Windows specific -- If entry point name is not given, we need to
991 // infer that from user-defined entry name.
992 StringRef S = findDefaultEntry();
994 fatal("entry point must be defined");
995 Config->Entry = addUndefined(S);
996 log("Entry name inferred: " + S);
1000 for (auto *Arg : Args.filtered(OPT_export)) {
1001 Export E = parseExport(Arg->getValue());
1002 if (Config->Machine == I386) {
1003 if (!isDecorated(E.Name))
1004 E.Name = Saver.save("_" + E.Name);
1005 if (!E.ExtName.empty() && !isDecorated(E.ExtName))
1006 E.ExtName = Saver.save("_" + E.ExtName);
1008 Config->Exports.push_back(E);
1012 if (auto *Arg = Args.getLastArg(OPT_deffile)) {
1013 // parseModuleDefs mutates Config object.
1014 parseModuleDefs(Arg->getValue());
1017 // Handle generation of import library from a def file.
1018 if (!Args.hasArgNoClaim(OPT_INPUT)) {
1020 createImportLibrary(/*AsLib=*/true);
1024 // Handle /delayload
1025 for (auto *Arg : Args.filtered(OPT_delayload)) {
1026 Config->DelayLoads.insert(StringRef(Arg->getValue()).lower());
1027 if (Config->Machine == I386) {
1028 Config->DelayLoadHelper = addUndefined("___delayLoadHelper2@8");
1030 Config->DelayLoadHelper = addUndefined("__delayLoadHelper2");
1034 // Set default image name if neither /out or /def set it.
1035 if (Config->OutputFile.empty()) {
1036 Config->OutputFile =
1037 getOutputPath((*Args.filtered(OPT_INPUT).begin())->getValue());
1040 // Put the PDB next to the image if no /pdb flag was passed.
1041 if (Config->Debug && Config->PDBPath.empty()) {
1042 Config->PDBPath = Config->OutputFile;
1043 sys::path::replace_extension(Config->PDBPath, ".pdb");
1046 // Disable PDB generation if the user requested it.
1047 if (Args.hasArg(OPT_nopdb))
1048 Config->PDBPath = "";
1050 // Set default image base if /base is not given.
1051 if (Config->ImageBase == uint64_t(-1))
1052 Config->ImageBase = getDefaultImageBase();
1054 Symtab.addSynthetic(mangle("__ImageBase"), nullptr);
1055 if (Config->Machine == I386) {
1056 Symtab.addAbsolute("___safe_se_handler_table", 0);
1057 Symtab.addAbsolute("___safe_se_handler_count", 0);
1060 // We do not support /guard:cf (control flow protection) yet.
1061 // Define CFG symbols anyway so that we can link MSVC 2015 CRT.
1062 Symtab.addAbsolute(mangle("__guard_fids_count"), 0);
1063 Symtab.addAbsolute(mangle("__guard_fids_table"), 0);
1064 Symtab.addAbsolute(mangle("__guard_flags"), 0x100);
1065 Symtab.addAbsolute(mangle("__guard_iat_count"), 0);
1066 Symtab.addAbsolute(mangle("__guard_iat_table"), 0);
1067 Symtab.addAbsolute(mangle("__guard_longjmp_count"), 0);
1068 Symtab.addAbsolute(mangle("__guard_longjmp_table"), 0);
1070 // This code may add new undefined symbols to the link, which may enqueue more
1071 // symbol resolution tasks, so we need to continue executing tasks until we
1074 // Windows specific -- if entry point is not found,
1075 // search for its mangled names.
1077 Symtab.mangleMaybe(Config->Entry);
1079 // Windows specific -- Make sure we resolve all dllexported symbols.
1080 for (Export &E : Config->Exports) {
1081 if (!E.ForwardTo.empty())
1083 E.Sym = addUndefined(E.Name);
1085 Symtab.mangleMaybe(E.Sym);
1088 // Add weak aliases. Weak aliases is a mechanism to give remaining
1089 // undefined symbols final chance to be resolved successfully.
1090 for (auto Pair : Config->AlternateNames) {
1091 StringRef From = Pair.first;
1092 StringRef To = Pair.second;
1093 Symbol *Sym = Symtab.find(From);
1096 if (auto *U = dyn_cast<Undefined>(Sym->body()))
1098 U->WeakAlias = Symtab.addUndefined(To);
1101 // Windows specific -- if __load_config_used can be resolved, resolve it.
1102 if (Symtab.findUnderscore("_load_config_used"))
1103 addUndefined(mangle("_load_config_used"));
1109 // If /msvclto is given, we use the MSVC linker to link LTO output files.
1110 // This is useful because MSVC link.exe can generate complete PDBs.
1111 if (Args.hasArg(OPT_msvclto)) {
1116 // Do LTO by compiling bitcode input files to a set of native COFF files then
1117 // link those files.
1118 Symtab.addCombinedLTOObjects();
1121 // Make sure we have resolved all symbols.
1122 Symtab.reportRemainingUndefines();
1124 // Windows specific -- if no /subsystem is given, we need to infer
1125 // that from entry point name.
1126 if (Config->Subsystem == IMAGE_SUBSYSTEM_UNKNOWN) {
1127 Config->Subsystem = inferSubsystem();
1128 if (Config->Subsystem == IMAGE_SUBSYSTEM_UNKNOWN)
1129 fatal("subsystem must be defined");
1133 if (Args.hasArg(OPT_safeseh)) {
1134 for (ObjectFile *File : Symtab.ObjectFiles)
1135 if (!File->SEHCompat)
1136 error("/safeseh: " + File->getName() + " is not compatible with SEH");
1141 // Windows specific -- when we are creating a .dll file, we also
1142 // need to create a .lib file.
1143 if (!Config->Exports.empty() || Config->DLL) {
1145 createImportLibrary(/*AsLib=*/false);
1146 assignExportOrdinals();
1149 // Windows specific -- Create a side-by-side manifest file.
1150 if (Config->Manifest == Configuration::SideBySide)
1151 createSideBySideManifest();
1153 // Identify unreferenced COMDAT sections.
1155 markLive(Symtab.getChunks());
1157 // Identify identical COMDAT sections to merge them.
1159 doICF(Symtab.getChunks());
1161 // Write the result.
1162 writeResult(&Symtab);
1164 // Call exit to avoid calling destructors.