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"
16 #include "SymbolTable.h"
19 #include "lld/Common/Args.h"
20 #include "lld/Common/Driver.h"
21 #include "lld/Common/ErrorHandler.h"
22 #include "lld/Common/Memory.h"
23 #include "lld/Common/Timer.h"
24 #include "lld/Common/Version.h"
25 #include "llvm/ADT/Optional.h"
26 #include "llvm/ADT/StringSwitch.h"
27 #include "llvm/BinaryFormat/Magic.h"
28 #include "llvm/Object/ArchiveWriter.h"
29 #include "llvm/Object/COFFImportFile.h"
30 #include "llvm/Object/COFFModuleDefinition.h"
31 #include "llvm/Option/Arg.h"
32 #include "llvm/Option/ArgList.h"
33 #include "llvm/Option/Option.h"
34 #include "llvm/Support/Debug.h"
35 #include "llvm/Support/Path.h"
36 #include "llvm/Support/Process.h"
37 #include "llvm/Support/TarWriter.h"
38 #include "llvm/Support/TargetSelect.h"
39 #include "llvm/Support/raw_ostream.h"
40 #include "llvm/ToolDrivers/llvm-lib/LibDriver.h"
46 using namespace llvm::object;
47 using namespace llvm::COFF;
48 using llvm::sys::Process;
53 static Timer InputFileTimer("Input File Reading", Timer::root());
55 Configuration *Config;
58 bool link(ArrayRef<const char *> Args, bool CanExitEarly, raw_ostream &Diag) {
59 errorHandler().LogName = sys::path::filename(Args[0]);
60 errorHandler().ErrorOS = &Diag;
61 errorHandler().ColorDiagnostics = Diag.has_colors();
62 errorHandler().ErrorLimitExceededMsg =
63 "too many errors emitted, stopping now"
64 " (use /errorlimit:0 to see all errors)";
65 errorHandler().ExitEarly = CanExitEarly;
66 Config = make<Configuration>();
68 Symtab = make<SymbolTable>();
70 Driver = make<LinkerDriver>();
73 // Call exit() if we can to avoid calling destructors.
75 exitLld(errorCount() ? 1 : 0);
78 ObjFile::Instances.clear();
79 ImportFile::Instances.clear();
80 BitcodeFile::Instances.clear();
84 // Drop directory components and replace extension with ".exe" or ".dll".
85 static std::string getOutputPath(StringRef Path) {
86 auto P = Path.find_last_of("\\/");
87 StringRef S = (P == StringRef::npos) ? Path : Path.substr(P + 1);
88 const char* E = Config->DLL ? ".dll" : ".exe";
89 return (S.substr(0, S.rfind('.')) + E).str();
92 // ErrorOr is not default constructible, so it cannot be used as the type
93 // parameter of a future.
94 // FIXME: We could open the file in createFutureForFile and avoid needing to
95 // return an error here, but for the moment that would cost us a file descriptor
96 // (a limited resource on Windows) for the duration that the future is pending.
97 typedef std::pair<std::unique_ptr<MemoryBuffer>, std::error_code> MBErrPair;
99 // Create a std::future that opens and maps a file using the best strategy for
100 // the host platform.
101 static std::future<MBErrPair> createFutureForFile(std::string Path) {
103 // On Windows, file I/O is relatively slow so it is best to do this
105 auto Strategy = std::launch::async;
107 auto Strategy = std::launch::deferred;
109 return std::async(Strategy, [=]() {
110 auto MBOrErr = MemoryBuffer::getFile(Path,
112 /*RequiresNullTerminator*/ false);
114 return MBErrPair{nullptr, MBOrErr.getError()};
115 return MBErrPair{std::move(*MBOrErr), std::error_code()};
119 // Symbol names are mangled by prepending "_" on x86.
120 static StringRef mangle(StringRef Sym) {
121 assert(Config->Machine != IMAGE_FILE_MACHINE_UNKNOWN);
122 if (Config->Machine == I386)
123 return Saver.save("_" + Sym);
127 static bool findUnderscoreMangle(StringRef Sym) {
128 StringRef Entry = Symtab->findMangle(mangle(Sym));
129 return !Entry.empty() && !isa<Undefined>(Symtab->find(Entry));
132 MemoryBufferRef LinkerDriver::takeBuffer(std::unique_ptr<MemoryBuffer> MB) {
133 MemoryBufferRef MBRef = *MB;
134 make<std::unique_ptr<MemoryBuffer>>(std::move(MB)); // take ownership
137 Driver->Tar->append(relativeToRoot(MBRef.getBufferIdentifier()),
142 void LinkerDriver::addBuffer(std::unique_ptr<MemoryBuffer> MB,
144 StringRef Filename = MB->getBufferIdentifier();
146 MemoryBufferRef MBRef = takeBuffer(std::move(MB));
147 FilePaths.push_back(Filename);
149 // File type is detected by contents, not by file extension.
150 switch (identify_magic(MBRef.getBuffer())) {
151 case file_magic::windows_resource:
152 Resources.push_back(MBRef);
154 case file_magic::archive:
156 std::unique_ptr<Archive> File =
157 CHECK(Archive::create(MBRef), Filename + ": failed to parse archive");
159 for (MemoryBufferRef M : getArchiveMembers(File.get()))
160 addArchiveBuffer(M, "<whole-archive>", Filename);
163 Symtab->addFile(make<ArchiveFile>(MBRef));
165 case file_magic::bitcode:
166 Symtab->addFile(make<BitcodeFile>(MBRef));
168 case file_magic::coff_object:
169 case file_magic::coff_import_library:
170 Symtab->addFile(make<ObjFile>(MBRef));
172 case file_magic::coff_cl_gl_object:
173 error(Filename + ": is not a native COFF file. Recompile without /GL");
175 case file_magic::pecoff_executable:
176 if (Filename.endswith_lower(".dll")) {
177 error(Filename + ": bad file type. Did you specify a DLL instead of an "
183 error(MBRef.getBufferIdentifier() + ": unknown file type");
188 void LinkerDriver::enqueuePath(StringRef Path, bool WholeArchive) {
190 std::make_shared<std::future<MBErrPair>>(createFutureForFile(Path));
191 std::string PathStr = Path;
193 auto MBOrErr = Future->get();
195 error("could not open " + PathStr + ": " + MBOrErr.second.message());
197 Driver->addBuffer(std::move(MBOrErr.first), WholeArchive);
201 void LinkerDriver::addArchiveBuffer(MemoryBufferRef MB, StringRef SymName,
202 StringRef ParentName) {
203 file_magic Magic = identify_magic(MB.getBuffer());
204 if (Magic == file_magic::coff_import_library) {
205 Symtab->addFile(make<ImportFile>(MB));
210 if (Magic == file_magic::coff_object) {
211 Obj = make<ObjFile>(MB);
212 } else if (Magic == file_magic::bitcode) {
213 Obj = make<BitcodeFile>(MB);
215 error("unknown file type: " + MB.getBufferIdentifier());
219 Obj->ParentName = ParentName;
220 Symtab->addFile(Obj);
221 log("Loaded " + toString(Obj) + " for " + SymName);
224 void LinkerDriver::enqueueArchiveMember(const Archive::Child &C,
226 StringRef ParentName) {
227 if (!C.getParent()->isThin()) {
228 MemoryBufferRef MB = CHECK(
229 C.getMemoryBufferRef(),
230 "could not get the buffer for the member defining symbol " + SymName);
231 enqueueTask([=]() { Driver->addArchiveBuffer(MB, SymName, ParentName); });
235 auto Future = std::make_shared<std::future<MBErrPair>>(createFutureForFile(
236 CHECK(C.getFullName(),
237 "could not get the filename for the member defining symbol " +
240 auto MBOrErr = Future->get();
242 fatal("could not get the buffer for the member defining " + SymName +
243 ": " + MBOrErr.second.message());
244 Driver->addArchiveBuffer(takeBuffer(std::move(MBOrErr.first)), SymName,
249 static bool isDecorated(StringRef Sym) {
250 return Sym.startswith("@") || Sym.contains("@@") || Sym.startswith("?") ||
251 (!Config->MinGW && Sym.contains('@'));
254 // Parses .drectve section contents and returns a list of files
255 // specified by /defaultlib.
256 void LinkerDriver::parseDirectives(StringRef S) {
258 // .drectve is always tokenized using Windows shell rules.
259 // /EXPORT: option can appear too many times, processing in fastpath.
260 opt::InputArgList Args;
261 std::vector<StringRef> Exports;
262 std::tie(Args, Exports) = Parser.parseDirectives(S);
264 for (StringRef E : Exports) {
265 // If a common header file contains dllexported function
266 // declarations, many object files may end up with having the
267 // same /EXPORT options. In order to save cost of parsing them,
268 // we dedup them first.
269 if (!DirectivesExports.insert(E).second)
272 Export Exp = parseExport(E);
273 if (Config->Machine == I386 && Config->MinGW) {
274 if (!isDecorated(Exp.Name))
275 Exp.Name = Saver.save("_" + Exp.Name);
276 if (!Exp.ExtName.empty() && !isDecorated(Exp.ExtName))
277 Exp.ExtName = Saver.save("_" + Exp.ExtName);
279 Exp.Directives = true;
280 Config->Exports.push_back(Exp);
283 for (auto *Arg : Args) {
284 switch (Arg->getOption().getUnaliasedOption().getID()) {
286 parseAligncomm(Arg->getValue());
288 case OPT_alternatename:
289 parseAlternateName(Arg->getValue());
292 if (Optional<StringRef> Path = findLib(Arg->getValue()))
293 enqueuePath(*Path, false);
296 Config->Entry = addUndefined(mangle(Arg->getValue()));
298 case OPT_failifmismatch:
299 checkFailIfMismatch(Arg->getValue());
302 addUndefined(Arg->getValue());
305 parseMerge(Arg->getValue());
307 case OPT_nodefaultlib:
308 Config->NoDefaultLibs.insert(doFindLib(Arg->getValue()));
311 parseSection(Arg->getValue());
314 parseSubsystem(Arg->getValue(), &Config->Subsystem,
315 &Config->MajorOSVersion, &Config->MinorOSVersion);
317 case OPT_editandcontinue:
321 case OPT_throwingnew:
324 error(Arg->getSpelling() + " is not allowed in .drectve");
329 // Find file from search paths. You can omit ".obj", this function takes
330 // care of that. Note that the returned path is not guaranteed to exist.
331 StringRef LinkerDriver::doFindFile(StringRef Filename) {
332 bool HasPathSep = (Filename.find_first_of("/\\") != StringRef::npos);
335 bool HasExt = Filename.contains('.');
336 for (StringRef Dir : SearchPaths) {
337 SmallString<128> Path = Dir;
338 sys::path::append(Path, Filename);
339 if (sys::fs::exists(Path.str()))
340 return Saver.save(Path.str());
343 if (sys::fs::exists(Path.str()))
344 return Saver.save(Path.str());
350 static Optional<sys::fs::UniqueID> getUniqueID(StringRef Path) {
351 sys::fs::UniqueID Ret;
352 if (sys::fs::getUniqueID(Path, Ret))
357 // Resolves a file path. This never returns the same path
358 // (in that case, it returns None).
359 Optional<StringRef> LinkerDriver::findFile(StringRef Filename) {
360 StringRef Path = doFindFile(Filename);
362 if (Optional<sys::fs::UniqueID> ID = getUniqueID(Path)) {
363 bool Seen = !VisitedFiles.insert(*ID).second;
368 if (Path.endswith_lower(".lib"))
369 VisitedLibs.insert(sys::path::filename(Path));
373 // Find library file from search path.
374 StringRef LinkerDriver::doFindLib(StringRef Filename) {
375 // Add ".lib" to Filename if that has no file extension.
376 bool HasExt = Filename.contains('.');
378 Filename = Saver.save(Filename + ".lib");
379 return doFindFile(Filename);
382 // Resolves a library path. /nodefaultlib options are taken into
383 // consideration. This never returns the same path (in that case,
385 Optional<StringRef> LinkerDriver::findLib(StringRef Filename) {
386 if (Config->NoDefaultLibAll)
388 if (!VisitedLibs.insert(Filename.lower()).second)
391 StringRef Path = doFindLib(Filename);
392 if (Config->NoDefaultLibs.count(Path))
395 if (Optional<sys::fs::UniqueID> ID = getUniqueID(Path))
396 if (!VisitedFiles.insert(*ID).second)
401 // Parses LIB environment which contains a list of search paths.
402 void LinkerDriver::addLibSearchPaths() {
403 Optional<std::string> EnvOpt = Process::GetEnv("LIB");
404 if (!EnvOpt.hasValue())
406 StringRef Env = Saver.save(*EnvOpt);
407 while (!Env.empty()) {
409 std::tie(Path, Env) = Env.split(';');
410 SearchPaths.push_back(Path);
414 Symbol *LinkerDriver::addUndefined(StringRef Name) {
415 Symbol *B = Symtab->addUndefined(Name);
418 Config->GCRoot.push_back(B);
423 // Windows specific -- find default entry point name.
425 // There are four different entry point functions for Windows executables,
426 // each of which corresponds to a user-defined "main" function. This function
427 // infers an entry point from a user-defined "main" function.
428 StringRef LinkerDriver::findDefaultEntry() {
429 assert(Config->Subsystem != IMAGE_SUBSYSTEM_UNKNOWN &&
430 "must handle /subsystem before calling this");
432 // As a special case, if /nodefaultlib is given, we directly look for an
433 // entry point. This is because, if no default library is linked, users
434 // need to define an entry point instead of a "main".
435 bool FindMain = !Config->NoDefaultLibAll;
436 if (Config->Subsystem == IMAGE_SUBSYSTEM_WINDOWS_GUI) {
437 if (findUnderscoreMangle(FindMain ? "WinMain" : "WinMainCRTStartup"))
438 return mangle("WinMainCRTStartup");
439 if (findUnderscoreMangle(FindMain ? "wWinMain" : "wWinMainCRTStartup"))
440 return mangle("wWinMainCRTStartup");
442 if (findUnderscoreMangle(FindMain ? "main" : "mainCRTStartup"))
443 return mangle("mainCRTStartup");
444 if (findUnderscoreMangle(FindMain ? "wmain" : "wmainCRTStartup"))
445 return mangle("wmainCRTStartup");
449 WindowsSubsystem LinkerDriver::inferSubsystem() {
451 return IMAGE_SUBSYSTEM_WINDOWS_GUI;
452 if (findUnderscoreMangle("main") || findUnderscoreMangle("wmain"))
453 return IMAGE_SUBSYSTEM_WINDOWS_CUI;
454 if (findUnderscoreMangle("WinMain") || findUnderscoreMangle("wWinMain"))
455 return IMAGE_SUBSYSTEM_WINDOWS_GUI;
456 return IMAGE_SUBSYSTEM_UNKNOWN;
459 static uint64_t getDefaultImageBase() {
461 return Config->DLL ? 0x180000000 : 0x140000000;
462 return Config->DLL ? 0x10000000 : 0x400000;
465 static std::string createResponseFile(const opt::InputArgList &Args,
466 ArrayRef<StringRef> FilePaths,
467 ArrayRef<StringRef> SearchPaths) {
469 raw_svector_ostream OS(Data);
471 for (auto *Arg : Args) {
472 switch (Arg->getOption().getID()) {
478 case OPT_manifest_colon:
479 case OPT_manifestdependency:
480 case OPT_manifestfile:
481 case OPT_manifestinput:
482 case OPT_manifestuac:
485 OS << toString(*Arg) << "\n";
489 for (StringRef Path : SearchPaths) {
490 std::string RelPath = relativeToRoot(Path);
491 OS << "/libpath:" << quote(RelPath) << "\n";
494 for (StringRef Path : FilePaths)
495 OS << quote(relativeToRoot(Path)) << "\n";
500 static unsigned getDefaultDebugType(const opt::InputArgList &Args) {
501 unsigned DebugTypes = static_cast<unsigned>(DebugType::CV);
502 if (Args.hasArg(OPT_driver))
503 DebugTypes |= static_cast<unsigned>(DebugType::PData);
504 if (Args.hasArg(OPT_profile))
505 DebugTypes |= static_cast<unsigned>(DebugType::Fixup);
509 static unsigned parseDebugType(StringRef Arg) {
510 SmallVector<StringRef, 3> Types;
511 Arg.split(Types, ',', /*KeepEmpty=*/false);
513 unsigned DebugTypes = static_cast<unsigned>(DebugType::None);
514 for (StringRef Type : Types)
515 DebugTypes |= StringSwitch<unsigned>(Type.lower())
516 .Case("cv", static_cast<unsigned>(DebugType::CV))
517 .Case("pdata", static_cast<unsigned>(DebugType::PData))
518 .Case("fixup", static_cast<unsigned>(DebugType::Fixup))
523 static std::string getMapFile(const opt::InputArgList &Args) {
524 auto *Arg = Args.getLastArg(OPT_lldmap, OPT_lldmap_file);
527 if (Arg->getOption().getID() == OPT_lldmap_file)
528 return Arg->getValue();
530 assert(Arg->getOption().getID() == OPT_lldmap);
531 StringRef OutFile = Config->OutputFile;
532 return (OutFile.substr(0, OutFile.rfind('.')) + ".map").str();
535 static std::string getImplibPath() {
536 if (!Config->Implib.empty())
537 return Config->Implib;
538 SmallString<128> Out = StringRef(Config->OutputFile);
539 sys::path::replace_extension(Out, ".lib");
544 // The import name is caculated as the following:
546 // | LIBRARY w/ ext | LIBRARY w/o ext | no LIBRARY
547 // -----+----------------+---------------------+------------------
548 // LINK | {value} | {value}.{.dll/.exe} | {output name}
549 // LIB | {value} | {value}.dll | {output name}.dll
551 static std::string getImportName(bool AsLib) {
552 SmallString<128> Out;
554 if (Config->ImportName.empty()) {
555 Out.assign(sys::path::filename(Config->OutputFile));
557 sys::path::replace_extension(Out, ".dll");
559 Out.assign(Config->ImportName);
560 if (!sys::path::has_extension(Out))
561 sys::path::replace_extension(Out,
562 (Config->DLL || AsLib) ? ".dll" : ".exe");
568 static void createImportLibrary(bool AsLib) {
569 std::vector<COFFShortExport> Exports;
570 for (Export &E1 : Config->Exports) {
573 E2.SymbolName = E1.SymbolName;
574 E2.ExtName = E1.ExtName;
575 E2.Ordinal = E1.Ordinal;
576 E2.Noname = E1.Noname;
578 E2.Private = E1.Private;
579 E2.Constant = E1.Constant;
580 Exports.push_back(E2);
583 auto HandleError = [](Error &&E) {
584 handleAllErrors(std::move(E),
585 [](ErrorInfoBase &EIB) { error(EIB.message()); });
587 std::string LibName = getImportName(AsLib);
588 std::string Path = getImplibPath();
590 if (!Config->Incremental) {
591 HandleError(writeImportLibrary(LibName, Path, Exports, Config->Machine,
596 // If the import library already exists, replace it only if the contents
598 ErrorOr<std::unique_ptr<MemoryBuffer>> OldBuf = MemoryBuffer::getFile(
599 Path, /*FileSize*/ -1, /*RequiresNullTerminator*/ false);
601 HandleError(writeImportLibrary(LibName, Path, Exports, Config->Machine,
606 SmallString<128> TmpName;
607 if (std::error_code EC =
608 sys::fs::createUniqueFile(Path + ".tmp-%%%%%%%%.lib", TmpName))
609 fatal("cannot create temporary file for import library " + Path + ": " +
612 if (Error E = writeImportLibrary(LibName, TmpName, Exports, Config->Machine,
614 HandleError(std::move(E));
618 std::unique_ptr<MemoryBuffer> NewBuf = check(MemoryBuffer::getFile(
619 TmpName, /*FileSize*/ -1, /*RequiresNullTerminator*/ false));
620 if ((*OldBuf)->getBuffer() != NewBuf->getBuffer()) {
622 HandleError(errorCodeToError(sys::fs::rename(TmpName, Path)));
624 sys::fs::remove(TmpName);
628 static void parseModuleDefs(StringRef Path) {
629 std::unique_ptr<MemoryBuffer> MB = CHECK(
630 MemoryBuffer::getFile(Path, -1, false, true), "could not open " + Path);
631 COFFModuleDefinition M = check(parseCOFFModuleDefinition(
632 MB->getMemBufferRef(), Config->Machine, Config->MinGW));
634 if (Config->OutputFile.empty())
635 Config->OutputFile = Saver.save(M.OutputFile);
636 Config->ImportName = Saver.save(M.ImportName);
638 Config->ImageBase = M.ImageBase;
640 Config->StackReserve = M.StackReserve;
642 Config->StackCommit = M.StackCommit;
644 Config->HeapReserve = M.HeapReserve;
646 Config->HeapCommit = M.HeapCommit;
647 if (M.MajorImageVersion)
648 Config->MajorImageVersion = M.MajorImageVersion;
649 if (M.MinorImageVersion)
650 Config->MinorImageVersion = M.MinorImageVersion;
651 if (M.MajorOSVersion)
652 Config->MajorOSVersion = M.MajorOSVersion;
653 if (M.MinorOSVersion)
654 Config->MinorOSVersion = M.MinorOSVersion;
656 for (COFFShortExport E1 : M.Exports) {
658 // In simple cases, only Name is set. Renamed exports are parsed
659 // and set as "ExtName = Name". If Name has the form "OtherDll.Func",
660 // it shouldn't be a normal exported function but a forward to another
661 // DLL instead. This is supported by both MS and GNU linkers.
662 if (E1.ExtName != E1.Name && StringRef(E1.Name).contains('.')) {
663 E2.Name = Saver.save(E1.ExtName);
664 E2.ForwardTo = Saver.save(E1.Name);
665 Config->Exports.push_back(E2);
668 E2.Name = Saver.save(E1.Name);
669 E2.ExtName = Saver.save(E1.ExtName);
670 E2.Ordinal = E1.Ordinal;
671 E2.Noname = E1.Noname;
673 E2.Private = E1.Private;
674 E2.Constant = E1.Constant;
675 Config->Exports.push_back(E2);
679 // A helper function for filterBitcodeFiles.
680 static bool needsRebuilding(MemoryBufferRef MB) {
681 // The MSVC linker doesn't support thin archives, so if it's a thin
682 // archive, we always need to rebuild it.
683 std::unique_ptr<Archive> File =
684 CHECK(Archive::create(MB), "Failed to read " + MB.getBufferIdentifier());
688 // Returns true if the archive contains at least one bitcode file.
689 for (MemoryBufferRef Member : getArchiveMembers(File.get()))
690 if (identify_magic(Member.getBuffer()) == file_magic::bitcode)
695 // Opens a given path as an archive file and removes bitcode files
696 // from them if exists. This function is to appease the MSVC linker as
697 // their linker doesn't like archive files containing non-native
700 // If a given archive doesn't contain bitcode files, the archive path
701 // is returned as-is. Otherwise, a new temporary file is created and
702 // its path is returned.
703 static Optional<std::string>
704 filterBitcodeFiles(StringRef Path, std::vector<std::string> &TemporaryFiles) {
705 std::unique_ptr<MemoryBuffer> MB = CHECK(
706 MemoryBuffer::getFile(Path, -1, false, true), "could not open " + Path);
707 MemoryBufferRef MBRef = MB->getMemBufferRef();
708 file_magic Magic = identify_magic(MBRef.getBuffer());
710 if (Magic == file_magic::bitcode)
712 if (Magic != file_magic::archive)
714 if (!needsRebuilding(MBRef))
717 std::unique_ptr<Archive> File =
718 CHECK(Archive::create(MBRef),
719 MBRef.getBufferIdentifier() + ": failed to parse archive");
721 std::vector<NewArchiveMember> New;
722 for (MemoryBufferRef Member : getArchiveMembers(File.get()))
723 if (identify_magic(Member.getBuffer()) != file_magic::bitcode)
724 New.emplace_back(Member);
729 log("Creating a temporary archive for " + Path + " to remove bitcode files");
732 if (std::error_code EC = sys::fs::createTemporaryFile(
733 "lld-" + sys::path::stem(Path), ".lib", S))
734 fatal("cannot create a temporary file: " + EC.message());
735 std::string Temp = S.str();
736 TemporaryFiles.push_back(Temp);
739 llvm::writeArchive(Temp, New, /*WriteSymtab=*/true, Archive::Kind::K_GNU,
740 /*Deterministics=*/true,
742 handleAllErrors(std::move(E), [&](const ErrorInfoBase &EI) {
743 error("failed to create a new archive " + S.str() + ": " + EI.message());
748 // Create response file contents and invoke the MSVC linker.
749 void LinkerDriver::invokeMSVC(opt::InputArgList &Args) {
750 std::string Rsp = "/nologo\n";
751 std::vector<std::string> Temps;
753 // Write out archive members that we used in symbol resolution and pass these
754 // to MSVC before any archives, so that MSVC uses the same objects to satisfy
756 for (ObjFile *Obj : ObjFile::Instances) {
757 if (Obj->ParentName.empty())
761 if (auto EC = sys::fs::createTemporaryFile(
762 "lld-" + sys::path::filename(Obj->ParentName), ".obj", Fd, S))
763 fatal("cannot create a temporary file: " + EC.message());
764 raw_fd_ostream OS(Fd, /*shouldClose*/ true);
765 OS << Obj->MB.getBuffer();
766 Temps.push_back(S.str());
767 Rsp += quote(S) + "\n";
770 for (auto *Arg : Args) {
771 switch (Arg->getOption().getID()) {
774 case OPT_lldmap_file:
775 case OPT_lldsavetemps:
777 // LLD-specific options are stripped.
780 if (!StringRef(Arg->getValue()).startswith("lld"))
781 Rsp += toString(*Arg) + " ";
784 if (Optional<StringRef> Path = doFindFile(Arg->getValue())) {
785 if (Optional<std::string> S = filterBitcodeFiles(*Path, Temps))
786 Rsp += quote(*S) + "\n";
789 Rsp += quote(Arg->getValue()) + "\n";
793 Rsp += toString(*Arg) + "\n";
797 std::vector<StringRef> ObjFiles = Symtab->compileBitcodeFiles();
798 runMSVCLinker(Rsp, ObjFiles);
800 for (StringRef Path : Temps)
801 sys::fs::remove(Path);
804 void LinkerDriver::enqueueTask(std::function<void()> Task) {
805 TaskQueue.push_back(std::move(Task));
808 bool LinkerDriver::run() {
809 ScopedTimer T(InputFileTimer);
811 bool DidWork = !TaskQueue.empty();
812 while (!TaskQueue.empty()) {
814 TaskQueue.pop_front();
819 // Parse an /order file. If an option is given, the linker places
820 // COMDAT sections in the same order as their names appear in the
822 static void parseOrderFile(StringRef Arg) {
823 // For some reason, the MSVC linker requires a filename to be
825 if (!Arg.startswith("@")) {
826 error("malformed /order option: '@' missing");
830 // Get a list of all comdat sections for error checking.
831 DenseSet<StringRef> Set;
832 for (Chunk *C : Symtab->getChunks())
833 if (auto *Sec = dyn_cast<SectionChunk>(C))
835 Set.insert(Sec->Sym->getName());
838 StringRef Path = Arg.substr(1);
839 std::unique_ptr<MemoryBuffer> MB = CHECK(
840 MemoryBuffer::getFile(Path, -1, false, true), "could not open " + Path);
842 // Parse a file. An order file contains one symbol per line.
843 // All symbols that were not present in a given order file are
844 // considered to have the lowest priority 0 and are placed at
845 // end of an output section.
846 for (std::string S : args::getLines(MB->getMemBufferRef())) {
847 if (Config->Machine == I386 && !isDecorated(S))
850 if (Set.count(S) == 0) {
851 if (Config->WarnMissingOrderSymbol)
852 warn("/order:" + Arg + ": missing symbol: " + S + " [LNK4037]");
855 Config->Order[S] = INT_MIN + Config->Order.size();
859 void LinkerDriver::link(ArrayRef<const char *> ArgsArr) {
860 // If the first command line argument is "/lib", link.exe acts like lib.exe.
861 // We call our own implementation of lib.exe that understands bitcode files.
862 if (ArgsArr.size() > 1 && StringRef(ArgsArr[1]).equals_lower("/lib")) {
863 if (llvm::libDriverMain(ArgsArr.slice(1)) != 0)
869 InitializeAllTargetInfos();
870 InitializeAllTargets();
871 InitializeAllTargetMCs();
872 InitializeAllAsmParsers();
873 InitializeAllAsmPrinters();
875 // Parse command line options.
877 opt::InputArgList Args = Parser.parseLINK(ArgsArr);
879 // Parse and evaluate -mllvm options.
880 std::vector<const char *> V;
881 V.push_back("lld-link (LLVM option parsing)");
882 for (auto *Arg : Args.filtered(OPT_mllvm))
883 V.push_back(Arg->getValue());
884 cl::ParseCommandLineOptions(V.size(), V.data());
886 // Handle /errorlimit early, because error() depends on it.
887 if (auto *Arg = Args.getLastArg(OPT_errorlimit)) {
889 StringRef S = Arg->getValue();
890 if (S.getAsInteger(10, N))
891 error(Arg->getSpelling() + " number expected, but got " + S);
892 errorHandler().ErrorLimit = N;
896 if (Args.hasArg(OPT_help)) {
897 printHelp(ArgsArr[0]);
901 if (Args.hasArg(OPT_show_timing))
902 Config->ShowTiming = true;
904 ScopedTimer T(Timer::root());
905 // Handle --version, which is an lld extension. This option is a bit odd
906 // because it doesn't start with "/", but we deliberately chose "--" to
907 // avoid conflict with /version and for compatibility with clang-cl.
908 if (Args.hasArg(OPT_dash_dash_version)) {
909 outs() << getLLDVersion() << "\n";
913 // Handle /lldmingw early, since it can potentially affect how other
914 // options are handled.
915 Config->MinGW = Args.hasArg(OPT_lldmingw);
917 if (auto *Arg = Args.getLastArg(OPT_linkrepro)) {
918 SmallString<64> Path = StringRef(Arg->getValue());
919 sys::path::append(Path, "repro.tar");
921 Expected<std::unique_ptr<TarWriter>> ErrOrWriter =
922 TarWriter::create(Path, "repro");
925 Tar = std::move(*ErrOrWriter);
927 error("/linkrepro: failed to open " + Path + ": " +
928 toString(ErrOrWriter.takeError()));
932 if (!Args.hasArg(OPT_INPUT)) {
933 if (Args.hasArg(OPT_deffile))
934 Config->NoEntry = true;
936 fatal("no input files");
939 // Construct search path list.
940 SearchPaths.push_back("");
941 for (auto *Arg : Args.filtered(OPT_libpath))
942 SearchPaths.push_back(Arg->getValue());
946 for (auto *Arg : Args.filtered(OPT_ignore)) {
947 if (StringRef(Arg->getValue()) == "4037")
948 Config->WarnMissingOrderSymbol = false;
949 else if (StringRef(Arg->getValue()) == "4217")
950 Config->WarnLocallyDefinedImported = false;
951 // Other warning numbers are ignored.
955 if (auto *Arg = Args.getLastArg(OPT_out))
956 Config->OutputFile = Arg->getValue();
959 if (Args.hasArg(OPT_verbose))
960 Config->Verbose = true;
961 errorHandler().Verbose = Config->Verbose;
963 // Handle /force or /force:unresolved
964 if (Args.hasArg(OPT_force, OPT_force_unresolved))
965 Config->Force = true;
968 if (Args.hasArg(OPT_debug, OPT_debug_dwarf, OPT_debug_ghash)) {
969 Config->Debug = true;
970 Config->Incremental = true;
971 if (auto *Arg = Args.getLastArg(OPT_debugtype))
972 Config->DebugTypes = parseDebugType(Arg->getValue());
974 Config->DebugTypes = getDefaultDebugType(Args);
978 bool ShouldCreatePDB = Args.hasArg(OPT_debug, OPT_debug_ghash);
979 if (ShouldCreatePDB) {
980 if (auto *Arg = Args.getLastArg(OPT_pdb))
981 Config->PDBPath = Arg->getValue();
982 if (auto *Arg = Args.getLastArg(OPT_pdbaltpath))
983 Config->PDBAltPath = Arg->getValue();
984 if (Args.hasArg(OPT_natvis))
985 Config->NatvisFiles = Args.getAllArgValues(OPT_natvis);
987 if (auto *Arg = Args.getLastArg(OPT_pdb_source_path))
988 Config->PDBSourcePath = Arg->getValue();
992 if (Args.hasArg(OPT_noentry)) {
993 if (Args.hasArg(OPT_dll))
994 Config->NoEntry = true;
996 error("/noentry must be specified with /dll");
1000 if (Args.hasArg(OPT_dll)) {
1002 Config->ManifestID = 2;
1005 // Handle /dynamicbase and /fixed. We can't use hasFlag for /dynamicbase
1006 // because we need to explicitly check whether that option or its inverse was
1007 // present in the argument list in order to handle /fixed.
1008 auto *DynamicBaseArg = Args.getLastArg(OPT_dynamicbase, OPT_dynamicbase_no);
1009 if (DynamicBaseArg &&
1010 DynamicBaseArg->getOption().getID() == OPT_dynamicbase_no)
1011 Config->DynamicBase = false;
1013 // MSDN claims "/FIXED:NO is the default setting for a DLL, and /FIXED is the
1014 // default setting for any other project type.", but link.exe defaults to
1015 // /FIXED:NO for exe outputs as well. Match behavior, not docs.
1016 bool Fixed = Args.hasFlag(OPT_fixed, OPT_fixed_no, false);
1018 if (DynamicBaseArg &&
1019 DynamicBaseArg->getOption().getID() == OPT_dynamicbase) {
1020 error("/fixed must not be specified with /dynamicbase");
1022 Config->Relocatable = false;
1023 Config->DynamicBase = false;
1027 // Handle /appcontainer
1028 Config->AppContainer =
1029 Args.hasFlag(OPT_appcontainer, OPT_appcontainer_no, false);
1032 if (auto *Arg = Args.getLastArg(OPT_machine))
1033 Config->Machine = getMachineType(Arg->getValue());
1035 // Handle /nodefaultlib:<filename>
1036 for (auto *Arg : Args.filtered(OPT_nodefaultlib))
1037 Config->NoDefaultLibs.insert(doFindLib(Arg->getValue()));
1039 // Handle /nodefaultlib
1040 if (Args.hasArg(OPT_nodefaultlib_all))
1041 Config->NoDefaultLibAll = true;
1044 if (auto *Arg = Args.getLastArg(OPT_base))
1045 parseNumbers(Arg->getValue(), &Config->ImageBase);
1048 if (auto *Arg = Args.getLastArg(OPT_stack))
1049 parseNumbers(Arg->getValue(), &Config->StackReserve, &Config->StackCommit);
1052 if (auto *Arg = Args.getLastArg(OPT_guard))
1053 parseGuard(Arg->getValue());
1056 if (auto *Arg = Args.getLastArg(OPT_heap))
1057 parseNumbers(Arg->getValue(), &Config->HeapReserve, &Config->HeapCommit);
1060 if (auto *Arg = Args.getLastArg(OPT_version))
1061 parseVersion(Arg->getValue(), &Config->MajorImageVersion,
1062 &Config->MinorImageVersion);
1064 // Handle /subsystem
1065 if (auto *Arg = Args.getLastArg(OPT_subsystem))
1066 parseSubsystem(Arg->getValue(), &Config->Subsystem, &Config->MajorOSVersion,
1067 &Config->MinorOSVersion);
1069 // Handle /timestamp
1070 if (llvm::opt::Arg *Arg = Args.getLastArg(OPT_timestamp, OPT_repro)) {
1071 if (Arg->getOption().getID() == OPT_repro) {
1072 Config->Timestamp = 0;
1073 Config->Repro = true;
1075 Config->Repro = false;
1076 StringRef Value(Arg->getValue());
1077 if (Value.getAsInteger(0, Config->Timestamp))
1078 fatal(Twine("invalid timestamp: ") + Value +
1079 ". Expected 32-bit integer");
1082 Config->Repro = false;
1083 Config->Timestamp = time(nullptr);
1086 // Handle /alternatename
1087 for (auto *Arg : Args.filtered(OPT_alternatename))
1088 parseAlternateName(Arg->getValue());
1091 for (auto *Arg : Args.filtered(OPT_incl))
1092 addUndefined(Arg->getValue());
1095 if (auto *Arg = Args.getLastArg(OPT_implib))
1096 Config->Implib = Arg->getValue();
1099 bool DoGC = !Args.hasArg(OPT_debug) || Args.hasArg(OPT_profile);
1101 Args.hasArg(OPT_profile) ? 0 : 1; // 0: off, 1: limited, 2: on
1102 unsigned TailMerge = 1;
1103 for (auto *Arg : Args.filtered(OPT_opt)) {
1104 std::string Str = StringRef(Arg->getValue()).lower();
1105 SmallVector<StringRef, 1> Vec;
1106 StringRef(Str).split(Vec, ',');
1107 for (StringRef S : Vec) {
1110 } else if (S == "noref") {
1112 } else if (S == "icf" || S.startswith("icf=")) {
1114 } else if (S == "noicf") {
1116 } else if (S == "lldtailmerge") {
1118 } else if (S == "nolldtailmerge") {
1120 } else if (S.startswith("lldlto=")) {
1121 StringRef OptLevel = S.substr(7);
1122 if (OptLevel.getAsInteger(10, Config->LTOO) || Config->LTOO > 3)
1123 error("/opt:lldlto: invalid optimization level: " + OptLevel);
1124 } else if (S.startswith("lldltojobs=")) {
1125 StringRef Jobs = S.substr(11);
1126 if (Jobs.getAsInteger(10, Config->ThinLTOJobs) ||
1127 Config->ThinLTOJobs == 0)
1128 error("/opt:lldltojobs: invalid job count: " + Jobs);
1129 } else if (S.startswith("lldltopartitions=")) {
1130 StringRef N = S.substr(17);
1131 if (N.getAsInteger(10, Config->LTOPartitions) ||
1132 Config->LTOPartitions == 0)
1133 error("/opt:lldltopartitions: invalid partition count: " + N);
1134 } else if (S != "lbr" && S != "nolbr")
1135 error("/opt: unknown option: " + S);
1139 // Limited ICF is enabled if GC is enabled and ICF was never mentioned
1141 // FIXME: LLD only implements "limited" ICF, i.e. it only merges identical
1142 // code. If the user passes /OPT:ICF explicitly, LLD should merge identical
1143 // comdat readonly data.
1144 if (ICFLevel == 1 && !DoGC)
1146 Config->DoGC = DoGC;
1147 Config->DoICF = ICFLevel > 0;
1148 Config->TailMerge = (TailMerge == 1 && Config->DoICF) || TailMerge == 2;
1150 // Handle /lldsavetemps
1151 if (Args.hasArg(OPT_lldsavetemps))
1152 Config->SaveTemps = true;
1155 if (Args.hasArg(OPT_kill_at))
1156 Config->KillAt = true;
1158 // Handle /lldltocache
1159 if (auto *Arg = Args.getLastArg(OPT_lldltocache))
1160 Config->LTOCache = Arg->getValue();
1162 // Handle /lldsavecachepolicy
1163 if (auto *Arg = Args.getLastArg(OPT_lldltocachepolicy))
1164 Config->LTOCachePolicy = CHECK(
1165 parseCachePruningPolicy(Arg->getValue()),
1166 Twine("/lldltocachepolicy: invalid cache policy: ") + Arg->getValue());
1168 // Handle /failifmismatch
1169 for (auto *Arg : Args.filtered(OPT_failifmismatch))
1170 checkFailIfMismatch(Arg->getValue());
1173 for (auto *Arg : Args.filtered(OPT_merge))
1174 parseMerge(Arg->getValue());
1176 // Add default section merging rules after user rules. User rules take
1177 // precedence, but we will emit a warning if there is a conflict.
1178 parseMerge(".idata=.rdata");
1179 parseMerge(".didat=.rdata");
1180 parseMerge(".edata=.rdata");
1181 parseMerge(".xdata=.rdata");
1182 parseMerge(".bss=.data");
1185 for (auto *Arg : Args.filtered(OPT_section))
1186 parseSection(Arg->getValue());
1188 // Handle /aligncomm
1189 for (auto *Arg : Args.filtered(OPT_aligncomm))
1190 parseAligncomm(Arg->getValue());
1192 // Handle /manifestdependency. This enables /manifest unless /manifest:no is
1194 if (auto *Arg = Args.getLastArg(OPT_manifestdependency)) {
1195 Config->ManifestDependency = Arg->getValue();
1196 Config->Manifest = Configuration::SideBySide;
1199 // Handle /manifest and /manifest:
1200 if (auto *Arg = Args.getLastArg(OPT_manifest, OPT_manifest_colon)) {
1201 if (Arg->getOption().getID() == OPT_manifest)
1202 Config->Manifest = Configuration::SideBySide;
1204 parseManifest(Arg->getValue());
1207 // Handle /manifestuac
1208 if (auto *Arg = Args.getLastArg(OPT_manifestuac))
1209 parseManifestUAC(Arg->getValue());
1211 // Handle /manifestfile
1212 if (auto *Arg = Args.getLastArg(OPT_manifestfile))
1213 Config->ManifestFile = Arg->getValue();
1215 // Handle /manifestinput
1216 for (auto *Arg : Args.filtered(OPT_manifestinput))
1217 Config->ManifestInput.push_back(Arg->getValue());
1219 if (!Config->ManifestInput.empty() &&
1220 Config->Manifest != Configuration::Embed) {
1221 fatal("/manifestinput: requires /manifest:embed");
1224 // Handle miscellaneous boolean flags.
1225 Config->AllowBind = Args.hasFlag(OPT_allowbind, OPT_allowbind_no, true);
1226 Config->AllowIsolation =
1227 Args.hasFlag(OPT_allowisolation, OPT_allowisolation_no, true);
1228 Config->Incremental =
1229 Args.hasFlag(OPT_incremental, OPT_incremental_no,
1230 !Config->DoGC && !Config->DoICF && !Args.hasArg(OPT_order) &&
1231 !Args.hasArg(OPT_profile));
1232 Config->IntegrityCheck =
1233 Args.hasFlag(OPT_integritycheck, OPT_integritycheck_no, false);
1234 Config->NxCompat = Args.hasFlag(OPT_nxcompat, OPT_nxcompat_no, true);
1235 Config->TerminalServerAware =
1236 !Config->DLL && Args.hasFlag(OPT_tsaware, OPT_tsaware_no, true);
1237 Config->DebugDwarf = Args.hasArg(OPT_debug_dwarf);
1238 Config->DebugGHashes = Args.hasArg(OPT_debug_ghash);
1239 Config->DebugSymtab = Args.hasArg(OPT_debug_symtab);
1241 Config->MapFile = getMapFile(Args);
1243 if (Config->Incremental && Args.hasArg(OPT_profile)) {
1244 warn("ignoring '/incremental' due to '/profile' specification");
1245 Config->Incremental = false;
1248 if (Config->Incremental && Args.hasArg(OPT_order)) {
1249 warn("ignoring '/incremental' due to '/order' specification");
1250 Config->Incremental = false;
1253 if (Config->Incremental && Config->DoGC) {
1254 warn("ignoring '/incremental' because REF is enabled; use '/opt:noref' to "
1256 Config->Incremental = false;
1259 if (Config->Incremental && Config->DoICF) {
1260 warn("ignoring '/incremental' because ICF is enabled; use '/opt:noicf' to "
1262 Config->Incremental = false;
1268 std::set<sys::fs::UniqueID> WholeArchives;
1269 for (auto *Arg : Args.filtered(OPT_wholearchive_file))
1270 if (Optional<StringRef> Path = doFindFile(Arg->getValue()))
1271 if (Optional<sys::fs::UniqueID> ID = getUniqueID(*Path))
1272 WholeArchives.insert(*ID);
1274 // A predicate returning true if a given path is an argument for
1275 // /wholearchive:, or /wholearchive is enabled globally.
1276 // This function is a bit tricky because "foo.obj /wholearchive:././foo.obj"
1277 // needs to be handled as "/wholearchive:foo.obj foo.obj".
1278 auto IsWholeArchive = [&](StringRef Path) -> bool {
1279 if (Args.hasArg(OPT_wholearchive_flag))
1281 if (Optional<sys::fs::UniqueID> ID = getUniqueID(Path))
1282 return WholeArchives.count(*ID);
1286 // Create a list of input files. Files can be given as arguments
1287 // for /defaultlib option.
1288 for (auto *Arg : Args.filtered(OPT_INPUT, OPT_wholearchive_file))
1289 if (Optional<StringRef> Path = findFile(Arg->getValue()))
1290 enqueuePath(*Path, IsWholeArchive(*Path));
1292 for (auto *Arg : Args.filtered(OPT_defaultlib))
1293 if (Optional<StringRef> Path = findLib(Arg->getValue()))
1294 enqueuePath(*Path, false);
1296 // Windows specific -- Create a resource file containing a manifest file.
1297 if (Config->Manifest == Configuration::Embed)
1298 addBuffer(createManifestRes(), false);
1300 // Read all input files given via the command line.
1303 // We should have inferred a machine type by now from the input files, but if
1304 // not we assume x64.
1305 if (Config->Machine == IMAGE_FILE_MACHINE_UNKNOWN) {
1306 warn("/machine is not specified. x64 is assumed");
1307 Config->Machine = AMD64;
1310 // Input files can be Windows resource files (.res files). We use
1311 // WindowsResource to convert resource files to a regular COFF file,
1312 // then link the resulting file normally.
1313 if (!Resources.empty())
1314 Symtab->addFile(make<ObjFile>(convertResToCOFF(Resources)));
1317 Tar->append("response.txt",
1318 createResponseFile(Args, FilePaths,
1319 ArrayRef<StringRef>(SearchPaths).slice(1)));
1321 // Handle /largeaddressaware
1322 Config->LargeAddressAware = Args.hasFlag(
1323 OPT_largeaddressaware, OPT_largeaddressaware_no, Config->is64());
1325 // Handle /highentropyva
1326 Config->HighEntropyVA =
1328 Args.hasFlag(OPT_highentropyva, OPT_highentropyva_no, true);
1330 if (!Config->DynamicBase &&
1331 (Config->Machine == ARMNT || Config->Machine == ARM64))
1332 error("/dynamicbase:no is not compatible with " +
1333 machineToStr(Config->Machine));
1336 for (auto *Arg : Args.filtered(OPT_export)) {
1337 Export E = parseExport(Arg->getValue());
1338 if (Config->Machine == I386) {
1339 if (!isDecorated(E.Name))
1340 E.Name = Saver.save("_" + E.Name);
1341 if (!E.ExtName.empty() && !isDecorated(E.ExtName))
1342 E.ExtName = Saver.save("_" + E.ExtName);
1344 Config->Exports.push_back(E);
1348 if (auto *Arg = Args.getLastArg(OPT_deffile)) {
1349 // parseModuleDefs mutates Config object.
1350 parseModuleDefs(Arg->getValue());
1353 // Handle generation of import library from a def file.
1354 if (!Args.hasArg(OPT_INPUT)) {
1356 createImportLibrary(/*AsLib=*/true);
1360 // Windows specific -- if no /subsystem is given, we need to infer
1361 // that from entry point name. Must happen before /entry handling,
1362 // and after the early return when just writing an import library.
1363 if (Config->Subsystem == IMAGE_SUBSYSTEM_UNKNOWN) {
1364 Config->Subsystem = inferSubsystem();
1365 if (Config->Subsystem == IMAGE_SUBSYSTEM_UNKNOWN)
1366 fatal("subsystem must be defined");
1369 // Handle /entry and /dll
1370 if (auto *Arg = Args.getLastArg(OPT_entry)) {
1371 Config->Entry = addUndefined(mangle(Arg->getValue()));
1372 } else if (!Config->Entry && !Config->NoEntry) {
1373 if (Args.hasArg(OPT_dll)) {
1374 StringRef S = (Config->Machine == I386) ? "__DllMainCRTStartup@12"
1375 : "_DllMainCRTStartup";
1376 Config->Entry = addUndefined(S);
1378 // Windows specific -- If entry point name is not given, we need to
1379 // infer that from user-defined entry name.
1380 StringRef S = findDefaultEntry();
1382 fatal("entry point must be defined");
1383 Config->Entry = addUndefined(S);
1384 log("Entry name inferred: " + S);
1388 // Handle /delayload
1389 for (auto *Arg : Args.filtered(OPT_delayload)) {
1390 Config->DelayLoads.insert(StringRef(Arg->getValue()).lower());
1391 if (Config->Machine == I386) {
1392 Config->DelayLoadHelper = addUndefined("___delayLoadHelper2@8");
1394 Config->DelayLoadHelper = addUndefined("__delayLoadHelper2");
1398 // Set default image name if neither /out or /def set it.
1399 if (Config->OutputFile.empty()) {
1400 Config->OutputFile =
1401 getOutputPath((*Args.filtered(OPT_INPUT).begin())->getValue());
1404 if (ShouldCreatePDB) {
1405 // Put the PDB next to the image if no /pdb flag was passed.
1406 if (Config->PDBPath.empty()) {
1407 Config->PDBPath = Config->OutputFile;
1408 sys::path::replace_extension(Config->PDBPath, ".pdb");
1411 // The embedded PDB path should be the absolute path to the PDB if no
1412 // /pdbaltpath flag was passed.
1413 if (Config->PDBAltPath.empty()) {
1414 Config->PDBAltPath = Config->PDBPath;
1416 // It's important to make the path absolute and remove dots. This path
1417 // will eventually be written into the PE header, and certain Microsoft
1418 // tools won't work correctly if these assumptions are not held.
1419 sys::fs::make_absolute(Config->PDBAltPath);
1420 sys::path::remove_dots(Config->PDBAltPath);
1424 // Set default image base if /base is not given.
1425 if (Config->ImageBase == uint64_t(-1))
1426 Config->ImageBase = getDefaultImageBase();
1428 Symtab->addSynthetic(mangle("__ImageBase"), nullptr);
1429 if (Config->Machine == I386) {
1430 Symtab->addAbsolute("___safe_se_handler_table", 0);
1431 Symtab->addAbsolute("___safe_se_handler_count", 0);
1434 Symtab->addAbsolute(mangle("__guard_fids_count"), 0);
1435 Symtab->addAbsolute(mangle("__guard_fids_table"), 0);
1436 Symtab->addAbsolute(mangle("__guard_flags"), 0);
1437 Symtab->addAbsolute(mangle("__guard_iat_count"), 0);
1438 Symtab->addAbsolute(mangle("__guard_iat_table"), 0);
1439 Symtab->addAbsolute(mangle("__guard_longjmp_count"), 0);
1440 Symtab->addAbsolute(mangle("__guard_longjmp_table"), 0);
1441 // Needed for MSVC 2017 15.5 CRT.
1442 Symtab->addAbsolute(mangle("__enclave_config"), 0);
1444 // This code may add new undefined symbols to the link, which may enqueue more
1445 // symbol resolution tasks, so we need to continue executing tasks until we
1448 // Windows specific -- if entry point is not found,
1449 // search for its mangled names.
1451 Symtab->mangleMaybe(Config->Entry);
1453 // Windows specific -- Make sure we resolve all dllexported symbols.
1454 for (Export &E : Config->Exports) {
1455 if (!E.ForwardTo.empty())
1457 E.Sym = addUndefined(E.Name);
1459 Symtab->mangleMaybe(E.Sym);
1462 // Add weak aliases. Weak aliases is a mechanism to give remaining
1463 // undefined symbols final chance to be resolved successfully.
1464 for (auto Pair : Config->AlternateNames) {
1465 StringRef From = Pair.first;
1466 StringRef To = Pair.second;
1467 Symbol *Sym = Symtab->find(From);
1470 if (auto *U = dyn_cast<Undefined>(Sym))
1472 U->WeakAlias = Symtab->addUndefined(To);
1475 // Windows specific -- if __load_config_used can be resolved, resolve it.
1476 if (Symtab->findUnderscore("_load_config_used"))
1477 addUndefined(mangle("_load_config_used"));
1483 // If /msvclto is given, we use the MSVC linker to link LTO output files.
1484 // This is useful because MSVC link.exe can generate complete PDBs.
1485 if (Args.hasArg(OPT_msvclto)) {
1490 // Do LTO by compiling bitcode input files to a set of native COFF files then
1491 // link those files.
1492 Symtab->addCombinedLTOObjects();
1495 // Make sure we have resolved all symbols.
1496 Symtab->reportRemainingUndefines();
1501 if (Args.hasFlag(OPT_safeseh, OPT_safeseh_no, false)) {
1502 for (ObjFile *File : ObjFile::Instances)
1503 if (!File->hasSafeSEH())
1504 error("/safeseh: " + File->getName() + " is not compatible with SEH");
1509 // In MinGW, all symbols are automatically exported if no symbols
1510 // are chosen to be exported.
1511 if (Config->DLL && ((Config->MinGW && Config->Exports.empty()) ||
1512 Args.hasArg(OPT_export_all_symbols))) {
1513 AutoExporter Exporter;
1515 Symtab->forEachSymbol([=](Symbol *S) {
1516 auto *Def = dyn_cast<Defined>(S);
1517 if (!Exporter.shouldExport(Def))
1520 E.Name = Def->getName();
1522 if (Def->getChunk() &&
1523 !(Def->getChunk()->getOutputCharacteristics() & IMAGE_SCN_MEM_EXECUTE))
1525 Config->Exports.push_back(E);
1529 // Windows specific -- when we are creating a .dll file, we also
1530 // need to create a .lib file.
1531 if (!Config->Exports.empty() || Config->DLL) {
1533 createImportLibrary(/*AsLib=*/false);
1534 assignExportOrdinals();
1537 // Handle /output-def (MinGW specific).
1538 if (auto *Arg = Args.getLastArg(OPT_output_def))
1539 writeDefFile(Arg->getValue());
1541 // Set extra alignment for .comm symbols
1542 for (auto Pair : Config->AlignComm) {
1543 StringRef Name = Pair.first;
1544 uint32_t Alignment = Pair.second;
1546 Symbol *Sym = Symtab->find(Name);
1548 warn("/aligncomm symbol " + Name + " not found");
1552 // If the symbol isn't common, it must have been replaced with a regular
1553 // symbol, which will carry its own alignment.
1554 auto *DC = dyn_cast<DefinedCommon>(Sym);
1558 CommonChunk *C = DC->getChunk();
1559 C->Alignment = std::max(C->Alignment, Alignment);
1562 // Windows specific -- Create a side-by-side manifest file.
1563 if (Config->Manifest == Configuration::SideBySide)
1564 createSideBySideManifest();
1566 // Handle /order. We want to do this at this moment because we
1567 // need a complete list of comdat sections to warn on nonexistent
1569 if (auto *Arg = Args.getLastArg(OPT_order))
1570 parseOrderFile(Arg->getValue());
1572 // Identify unreferenced COMDAT sections.
1574 markLive(Symtab->getChunks());
1576 // Identify identical COMDAT sections to merge them.
1578 doICF(Symtab->getChunks());
1580 // Write the result.
1583 // Stop early so we can print the results.
1584 Timer::root().stop();
1585 if (Config->ShowTiming)
1586 Timer::root().print();