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/LEB128.h"
36 #include "llvm/Support/Path.h"
37 #include "llvm/Support/Process.h"
38 #include "llvm/Support/TarWriter.h"
39 #include "llvm/Support/TargetSelect.h"
40 #include "llvm/Support/raw_ostream.h"
41 #include "llvm/ToolDrivers/llvm-lib/LibDriver.h"
47 using namespace llvm::object;
48 using namespace llvm::COFF;
49 using llvm::sys::Process;
54 static Timer InputFileTimer("Input File Reading", Timer::root());
56 Configuration *Config;
59 bool link(ArrayRef<const char *> Args, bool CanExitEarly, raw_ostream &Diag) {
60 errorHandler().LogName = args::getFilenameWithoutExe(Args[0]);
61 errorHandler().ErrorOS = &Diag;
62 errorHandler().ColorDiagnostics = Diag.has_colors();
63 errorHandler().ErrorLimitExceededMsg =
64 "too many errors emitted, stopping now"
65 " (use /errorlimit:0 to see all errors)";
66 errorHandler().ExitEarly = CanExitEarly;
67 Config = make<Configuration>();
69 Symtab = make<SymbolTable>();
71 Driver = make<LinkerDriver>();
74 // Call exit() if we can to avoid calling destructors.
76 exitLld(errorCount() ? 1 : 0);
79 ObjFile::Instances.clear();
80 ImportFile::Instances.clear();
81 BitcodeFile::Instances.clear();
85 // Drop directory components and replace extension with ".exe" or ".dll".
86 static std::string getOutputPath(StringRef Path) {
87 auto P = Path.find_last_of("\\/");
88 StringRef S = (P == StringRef::npos) ? Path : Path.substr(P + 1);
89 const char* E = Config->DLL ? ".dll" : ".exe";
90 return (S.substr(0, S.rfind('.')) + E).str();
93 // ErrorOr is not default constructible, so it cannot be used as the type
94 // parameter of a future.
95 // FIXME: We could open the file in createFutureForFile and avoid needing to
96 // return an error here, but for the moment that would cost us a file descriptor
97 // (a limited resource on Windows) for the duration that the future is pending.
98 typedef std::pair<std::unique_ptr<MemoryBuffer>, std::error_code> MBErrPair;
100 // Create a std::future that opens and maps a file using the best strategy for
101 // the host platform.
102 static std::future<MBErrPair> createFutureForFile(std::string Path) {
104 // On Windows, file I/O is relatively slow so it is best to do this
106 auto Strategy = std::launch::async;
108 auto Strategy = std::launch::deferred;
110 return std::async(Strategy, [=]() {
111 auto MBOrErr = MemoryBuffer::getFile(Path,
113 /*RequiresNullTerminator*/ false);
115 return MBErrPair{nullptr, MBOrErr.getError()};
116 return MBErrPair{std::move(*MBOrErr), std::error_code()};
120 // Symbol names are mangled by prepending "_" on x86.
121 static StringRef mangle(StringRef Sym) {
122 assert(Config->Machine != IMAGE_FILE_MACHINE_UNKNOWN);
123 if (Config->Machine == I386)
124 return Saver.save("_" + Sym);
128 static bool findUnderscoreMangle(StringRef Sym) {
129 StringRef Entry = Symtab->findMangle(mangle(Sym));
130 return !Entry.empty() && !isa<Undefined>(Symtab->find(Entry));
133 MemoryBufferRef LinkerDriver::takeBuffer(std::unique_ptr<MemoryBuffer> MB) {
134 MemoryBufferRef MBRef = *MB;
135 make<std::unique_ptr<MemoryBuffer>>(std::move(MB)); // take ownership
138 Driver->Tar->append(relativeToRoot(MBRef.getBufferIdentifier()),
143 void LinkerDriver::addBuffer(std::unique_ptr<MemoryBuffer> MB,
145 StringRef Filename = MB->getBufferIdentifier();
147 MemoryBufferRef MBRef = takeBuffer(std::move(MB));
148 FilePaths.push_back(Filename);
150 // File type is detected by contents, not by file extension.
151 switch (identify_magic(MBRef.getBuffer())) {
152 case file_magic::windows_resource:
153 Resources.push_back(MBRef);
155 case file_magic::archive:
157 std::unique_ptr<Archive> File =
158 CHECK(Archive::create(MBRef), Filename + ": failed to parse archive");
160 for (MemoryBufferRef M : getArchiveMembers(File.get()))
161 addArchiveBuffer(M, "<whole-archive>", Filename);
164 Symtab->addFile(make<ArchiveFile>(MBRef));
166 case file_magic::bitcode:
167 Symtab->addFile(make<BitcodeFile>(MBRef));
169 case file_magic::coff_object:
170 case file_magic::coff_import_library:
171 Symtab->addFile(make<ObjFile>(MBRef));
173 case file_magic::coff_cl_gl_object:
174 error(Filename + ": is not a native COFF file. Recompile without /GL");
176 case file_magic::pecoff_executable:
177 if (Filename.endswith_lower(".dll")) {
178 error(Filename + ": bad file type. Did you specify a DLL instead of an "
184 error(MBRef.getBufferIdentifier() + ": unknown file type");
189 void LinkerDriver::enqueuePath(StringRef Path, bool WholeArchive) {
191 std::make_shared<std::future<MBErrPair>>(createFutureForFile(Path));
192 std::string PathStr = Path;
194 auto MBOrErr = Future->get();
196 error("could not open " + PathStr + ": " + MBOrErr.second.message());
198 Driver->addBuffer(std::move(MBOrErr.first), WholeArchive);
202 void LinkerDriver::addArchiveBuffer(MemoryBufferRef MB, StringRef SymName,
203 StringRef ParentName) {
204 file_magic Magic = identify_magic(MB.getBuffer());
205 if (Magic == file_magic::coff_import_library) {
206 Symtab->addFile(make<ImportFile>(MB));
211 if (Magic == file_magic::coff_object) {
212 Obj = make<ObjFile>(MB);
213 } else if (Magic == file_magic::bitcode) {
214 Obj = make<BitcodeFile>(MB);
216 error("unknown file type: " + MB.getBufferIdentifier());
220 Obj->ParentName = ParentName;
221 Symtab->addFile(Obj);
222 log("Loaded " + toString(Obj) + " for " + SymName);
225 void LinkerDriver::enqueueArchiveMember(const Archive::Child &C,
227 StringRef ParentName) {
228 if (!C.getParent()->isThin()) {
229 MemoryBufferRef MB = CHECK(
230 C.getMemoryBufferRef(),
231 "could not get the buffer for the member defining symbol " + SymName);
232 enqueueTask([=]() { Driver->addArchiveBuffer(MB, SymName, ParentName); });
236 auto Future = std::make_shared<std::future<MBErrPair>>(createFutureForFile(
237 CHECK(C.getFullName(),
238 "could not get the filename for the member defining symbol " +
241 auto MBOrErr = Future->get();
243 fatal("could not get the buffer for the member defining " + SymName +
244 ": " + MBOrErr.second.message());
245 Driver->addArchiveBuffer(takeBuffer(std::move(MBOrErr.first)), SymName,
250 static bool isDecorated(StringRef Sym) {
251 return Sym.startswith("@") || Sym.contains("@@") || Sym.startswith("?") ||
252 (!Config->MinGW && Sym.contains('@'));
255 // Parses .drectve section contents and returns a list of files
256 // specified by /defaultlib.
257 void LinkerDriver::parseDirectives(StringRef S) {
259 // .drectve is always tokenized using Windows shell rules.
260 // /EXPORT: option can appear too many times, processing in fastpath.
261 opt::InputArgList Args;
262 std::vector<StringRef> Exports;
263 std::tie(Args, Exports) = Parser.parseDirectives(S);
265 for (StringRef E : Exports) {
266 // If a common header file contains dllexported function
267 // declarations, many object files may end up with having the
268 // same /EXPORT options. In order to save cost of parsing them,
269 // we dedup them first.
270 if (!DirectivesExports.insert(E).second)
273 Export Exp = parseExport(E);
274 if (Config->Machine == I386 && Config->MinGW) {
275 if (!isDecorated(Exp.Name))
276 Exp.Name = Saver.save("_" + Exp.Name);
277 if (!Exp.ExtName.empty() && !isDecorated(Exp.ExtName))
278 Exp.ExtName = Saver.save("_" + Exp.ExtName);
280 Exp.Directives = true;
281 Config->Exports.push_back(Exp);
284 for (auto *Arg : Args) {
285 switch (Arg->getOption().getUnaliasedOption().getID()) {
287 parseAligncomm(Arg->getValue());
289 case OPT_alternatename:
290 parseAlternateName(Arg->getValue());
293 if (Optional<StringRef> Path = findLib(Arg->getValue()))
294 enqueuePath(*Path, false);
297 Config->Entry = addUndefined(mangle(Arg->getValue()));
299 case OPT_failifmismatch:
300 checkFailIfMismatch(Arg->getValue());
303 addUndefined(Arg->getValue());
306 parseMerge(Arg->getValue());
308 case OPT_nodefaultlib:
309 Config->NoDefaultLibs.insert(doFindLib(Arg->getValue()));
312 parseSection(Arg->getValue());
315 parseSubsystem(Arg->getValue(), &Config->Subsystem,
316 &Config->MajorOSVersion, &Config->MinorOSVersion);
318 case OPT_editandcontinue:
322 case OPT_throwingnew:
325 error(Arg->getSpelling() + " is not allowed in .drectve");
330 // Find file from search paths. You can omit ".obj", this function takes
331 // care of that. Note that the returned path is not guaranteed to exist.
332 StringRef LinkerDriver::doFindFile(StringRef Filename) {
333 bool HasPathSep = (Filename.find_first_of("/\\") != StringRef::npos);
336 bool HasExt = Filename.contains('.');
337 for (StringRef Dir : SearchPaths) {
338 SmallString<128> Path = Dir;
339 sys::path::append(Path, Filename);
340 if (sys::fs::exists(Path.str()))
341 return Saver.save(Path.str());
344 if (sys::fs::exists(Path.str()))
345 return Saver.save(Path.str());
351 static Optional<sys::fs::UniqueID> getUniqueID(StringRef Path) {
352 sys::fs::UniqueID Ret;
353 if (sys::fs::getUniqueID(Path, Ret))
358 // Resolves a file path. This never returns the same path
359 // (in that case, it returns None).
360 Optional<StringRef> LinkerDriver::findFile(StringRef Filename) {
361 StringRef Path = doFindFile(Filename);
363 if (Optional<sys::fs::UniqueID> ID = getUniqueID(Path)) {
364 bool Seen = !VisitedFiles.insert(*ID).second;
369 if (Path.endswith_lower(".lib"))
370 VisitedLibs.insert(sys::path::filename(Path));
374 // MinGW specific. If an embedded directive specified to link to
375 // foo.lib, but it isn't found, try libfoo.a instead.
376 StringRef LinkerDriver::doFindLibMinGW(StringRef Filename) {
377 if (Filename.contains('/') || Filename.contains('\\'))
380 SmallString<128> S = Filename;
381 sys::path::replace_extension(S, ".a");
382 StringRef LibName = Saver.save("lib" + S.str());
383 return doFindFile(LibName);
386 // Find library file from search path.
387 StringRef LinkerDriver::doFindLib(StringRef Filename) {
388 // Add ".lib" to Filename if that has no file extension.
389 bool HasExt = Filename.contains('.');
391 Filename = Saver.save(Filename + ".lib");
392 StringRef Ret = doFindFile(Filename);
393 // For MinGW, if the find above didn't turn up anything, try
394 // looking for a MinGW formatted library name.
395 if (Config->MinGW && Ret == Filename)
396 return doFindLibMinGW(Filename);
400 // Resolves a library path. /nodefaultlib options are taken into
401 // consideration. This never returns the same path (in that case,
403 Optional<StringRef> LinkerDriver::findLib(StringRef Filename) {
404 if (Config->NoDefaultLibAll)
406 if (!VisitedLibs.insert(Filename.lower()).second)
409 StringRef Path = doFindLib(Filename);
410 if (Config->NoDefaultLibs.count(Path))
413 if (Optional<sys::fs::UniqueID> ID = getUniqueID(Path))
414 if (!VisitedFiles.insert(*ID).second)
419 // Parses LIB environment which contains a list of search paths.
420 void LinkerDriver::addLibSearchPaths() {
421 Optional<std::string> EnvOpt = Process::GetEnv("LIB");
422 if (!EnvOpt.hasValue())
424 StringRef Env = Saver.save(*EnvOpt);
425 while (!Env.empty()) {
427 std::tie(Path, Env) = Env.split(';');
428 SearchPaths.push_back(Path);
432 Symbol *LinkerDriver::addUndefined(StringRef Name) {
433 Symbol *B = Symtab->addUndefined(Name);
436 Config->GCRoot.push_back(B);
441 // Windows specific -- find default entry point name.
443 // There are four different entry point functions for Windows executables,
444 // each of which corresponds to a user-defined "main" function. This function
445 // infers an entry point from a user-defined "main" function.
446 StringRef LinkerDriver::findDefaultEntry() {
447 assert(Config->Subsystem != IMAGE_SUBSYSTEM_UNKNOWN &&
448 "must handle /subsystem before calling this");
451 return mangle(Config->Subsystem == IMAGE_SUBSYSTEM_WINDOWS_GUI
452 ? "WinMainCRTStartup"
455 if (Config->Subsystem == IMAGE_SUBSYSTEM_WINDOWS_GUI) {
456 if (findUnderscoreMangle("wWinMain")) {
457 if (!findUnderscoreMangle("WinMain"))
458 return mangle("wWinMainCRTStartup");
459 warn("found both wWinMain and WinMain; using latter");
461 return mangle("WinMainCRTStartup");
463 if (findUnderscoreMangle("wmain")) {
464 if (!findUnderscoreMangle("main"))
465 return mangle("wmainCRTStartup");
466 warn("found both wmain and main; using latter");
468 return mangle("mainCRTStartup");
471 WindowsSubsystem LinkerDriver::inferSubsystem() {
473 return IMAGE_SUBSYSTEM_WINDOWS_GUI;
475 return IMAGE_SUBSYSTEM_WINDOWS_CUI;
476 // Note that link.exe infers the subsystem from the presence of these
477 // functions even if /entry: or /nodefaultlib are passed which causes them
479 bool HaveMain = findUnderscoreMangle("main");
480 bool HaveWMain = findUnderscoreMangle("wmain");
481 bool HaveWinMain = findUnderscoreMangle("WinMain");
482 bool HaveWWinMain = findUnderscoreMangle("wWinMain");
483 if (HaveMain || HaveWMain) {
484 if (HaveWinMain || HaveWWinMain) {
485 warn(std::string("found ") + (HaveMain ? "main" : "wmain") + " and " +
486 (HaveWinMain ? "WinMain" : "wWinMain") +
487 "; defaulting to /subsystem:console");
489 return IMAGE_SUBSYSTEM_WINDOWS_CUI;
491 if (HaveWinMain || HaveWWinMain)
492 return IMAGE_SUBSYSTEM_WINDOWS_GUI;
493 return IMAGE_SUBSYSTEM_UNKNOWN;
496 static uint64_t getDefaultImageBase() {
498 return Config->DLL ? 0x180000000 : 0x140000000;
499 return Config->DLL ? 0x10000000 : 0x400000;
502 static std::string createResponseFile(const opt::InputArgList &Args,
503 ArrayRef<StringRef> FilePaths,
504 ArrayRef<StringRef> SearchPaths) {
506 raw_svector_ostream OS(Data);
508 for (auto *Arg : Args) {
509 switch (Arg->getOption().getID()) {
515 case OPT_manifest_colon:
516 case OPT_manifestdependency:
517 case OPT_manifestfile:
518 case OPT_manifestinput:
519 case OPT_manifestuac:
522 OS << toString(*Arg) << "\n";
526 for (StringRef Path : SearchPaths) {
527 std::string RelPath = relativeToRoot(Path);
528 OS << "/libpath:" << quote(RelPath) << "\n";
531 for (StringRef Path : FilePaths)
532 OS << quote(relativeToRoot(Path)) << "\n";
537 enum class DebugKind { Unknown, None, Full, FastLink, GHash, Dwarf, Symtab };
539 static DebugKind parseDebugKind(const opt::InputArgList &Args) {
540 auto *A = Args.getLastArg(OPT_debug, OPT_debug_opt);
542 return DebugKind::None;
543 if (A->getNumValues() == 0)
544 return DebugKind::Full;
546 DebugKind Debug = StringSwitch<DebugKind>(A->getValue())
547 .CaseLower("none", DebugKind::None)
548 .CaseLower("full", DebugKind::Full)
549 .CaseLower("fastlink", DebugKind::FastLink)
551 .CaseLower("ghash", DebugKind::GHash)
552 .CaseLower("dwarf", DebugKind::Dwarf)
553 .CaseLower("symtab", DebugKind::Symtab)
554 .Default(DebugKind::Unknown);
556 if (Debug == DebugKind::FastLink) {
557 warn("/debug:fastlink unsupported; using /debug:full");
558 return DebugKind::Full;
560 if (Debug == DebugKind::Unknown) {
561 error("/debug: unknown option: " + Twine(A->getValue()));
562 return DebugKind::None;
567 static unsigned parseDebugTypes(const opt::InputArgList &Args) {
568 unsigned DebugTypes = static_cast<unsigned>(DebugType::None);
570 if (auto *A = Args.getLastArg(OPT_debugtype)) {
571 SmallVector<StringRef, 3> Types;
572 A->getSpelling().split(Types, ',', /*KeepEmpty=*/false);
574 for (StringRef Type : Types) {
575 unsigned V = StringSwitch<unsigned>(Type.lower())
576 .Case("cv", static_cast<unsigned>(DebugType::CV))
577 .Case("pdata", static_cast<unsigned>(DebugType::PData))
578 .Case("fixup", static_cast<unsigned>(DebugType::Fixup))
581 warn("/debugtype: unknown option: " + Twine(A->getValue()));
589 // Default debug types
590 DebugTypes = static_cast<unsigned>(DebugType::CV);
591 if (Args.hasArg(OPT_driver))
592 DebugTypes |= static_cast<unsigned>(DebugType::PData);
593 if (Args.hasArg(OPT_profile))
594 DebugTypes |= static_cast<unsigned>(DebugType::Fixup);
599 static std::string getMapFile(const opt::InputArgList &Args) {
600 auto *Arg = Args.getLastArg(OPT_lldmap, OPT_lldmap_file);
603 if (Arg->getOption().getID() == OPT_lldmap_file)
604 return Arg->getValue();
606 assert(Arg->getOption().getID() == OPT_lldmap);
607 StringRef OutFile = Config->OutputFile;
608 return (OutFile.substr(0, OutFile.rfind('.')) + ".map").str();
611 static std::string getImplibPath() {
612 if (!Config->Implib.empty())
613 return Config->Implib;
614 SmallString<128> Out = StringRef(Config->OutputFile);
615 sys::path::replace_extension(Out, ".lib");
620 // The import name is caculated as the following:
622 // | LIBRARY w/ ext | LIBRARY w/o ext | no LIBRARY
623 // -----+----------------+---------------------+------------------
624 // LINK | {value} | {value}.{.dll/.exe} | {output name}
625 // LIB | {value} | {value}.dll | {output name}.dll
627 static std::string getImportName(bool AsLib) {
628 SmallString<128> Out;
630 if (Config->ImportName.empty()) {
631 Out.assign(sys::path::filename(Config->OutputFile));
633 sys::path::replace_extension(Out, ".dll");
635 Out.assign(Config->ImportName);
636 if (!sys::path::has_extension(Out))
637 sys::path::replace_extension(Out,
638 (Config->DLL || AsLib) ? ".dll" : ".exe");
644 static void createImportLibrary(bool AsLib) {
645 std::vector<COFFShortExport> Exports;
646 for (Export &E1 : Config->Exports) {
649 E2.SymbolName = E1.SymbolName;
650 E2.ExtName = E1.ExtName;
651 E2.Ordinal = E1.Ordinal;
652 E2.Noname = E1.Noname;
654 E2.Private = E1.Private;
655 E2.Constant = E1.Constant;
656 Exports.push_back(E2);
659 auto HandleError = [](Error &&E) {
660 handleAllErrors(std::move(E),
661 [](ErrorInfoBase &EIB) { error(EIB.message()); });
663 std::string LibName = getImportName(AsLib);
664 std::string Path = getImplibPath();
666 if (!Config->Incremental) {
667 HandleError(writeImportLibrary(LibName, Path, Exports, Config->Machine,
672 // If the import library already exists, replace it only if the contents
674 ErrorOr<std::unique_ptr<MemoryBuffer>> OldBuf = MemoryBuffer::getFile(
675 Path, /*FileSize*/ -1, /*RequiresNullTerminator*/ false);
677 HandleError(writeImportLibrary(LibName, Path, Exports, Config->Machine,
682 SmallString<128> TmpName;
683 if (std::error_code EC =
684 sys::fs::createUniqueFile(Path + ".tmp-%%%%%%%%.lib", TmpName))
685 fatal("cannot create temporary file for import library " + Path + ": " +
688 if (Error E = writeImportLibrary(LibName, TmpName, Exports, Config->Machine,
690 HandleError(std::move(E));
694 std::unique_ptr<MemoryBuffer> NewBuf = check(MemoryBuffer::getFile(
695 TmpName, /*FileSize*/ -1, /*RequiresNullTerminator*/ false));
696 if ((*OldBuf)->getBuffer() != NewBuf->getBuffer()) {
698 HandleError(errorCodeToError(sys::fs::rename(TmpName, Path)));
700 sys::fs::remove(TmpName);
704 static void parseModuleDefs(StringRef Path) {
705 std::unique_ptr<MemoryBuffer> MB = CHECK(
706 MemoryBuffer::getFile(Path, -1, false, true), "could not open " + Path);
707 COFFModuleDefinition M = check(parseCOFFModuleDefinition(
708 MB->getMemBufferRef(), Config->Machine, Config->MinGW));
710 if (Config->OutputFile.empty())
711 Config->OutputFile = Saver.save(M.OutputFile);
712 Config->ImportName = Saver.save(M.ImportName);
714 Config->ImageBase = M.ImageBase;
716 Config->StackReserve = M.StackReserve;
718 Config->StackCommit = M.StackCommit;
720 Config->HeapReserve = M.HeapReserve;
722 Config->HeapCommit = M.HeapCommit;
723 if (M.MajorImageVersion)
724 Config->MajorImageVersion = M.MajorImageVersion;
725 if (M.MinorImageVersion)
726 Config->MinorImageVersion = M.MinorImageVersion;
727 if (M.MajorOSVersion)
728 Config->MajorOSVersion = M.MajorOSVersion;
729 if (M.MinorOSVersion)
730 Config->MinorOSVersion = M.MinorOSVersion;
732 for (COFFShortExport E1 : M.Exports) {
734 // In simple cases, only Name is set. Renamed exports are parsed
735 // and set as "ExtName = Name". If Name has the form "OtherDll.Func",
736 // it shouldn't be a normal exported function but a forward to another
737 // DLL instead. This is supported by both MS and GNU linkers.
738 if (E1.ExtName != E1.Name && StringRef(E1.Name).contains('.')) {
739 E2.Name = Saver.save(E1.ExtName);
740 E2.ForwardTo = Saver.save(E1.Name);
741 Config->Exports.push_back(E2);
744 E2.Name = Saver.save(E1.Name);
745 E2.ExtName = Saver.save(E1.ExtName);
746 E2.Ordinal = E1.Ordinal;
747 E2.Noname = E1.Noname;
749 E2.Private = E1.Private;
750 E2.Constant = E1.Constant;
751 Config->Exports.push_back(E2);
755 void LinkerDriver::enqueueTask(std::function<void()> Task) {
756 TaskQueue.push_back(std::move(Task));
759 bool LinkerDriver::run() {
760 ScopedTimer T(InputFileTimer);
762 bool DidWork = !TaskQueue.empty();
763 while (!TaskQueue.empty()) {
765 TaskQueue.pop_front();
770 // Parse an /order file. If an option is given, the linker places
771 // COMDAT sections in the same order as their names appear in the
773 static void parseOrderFile(StringRef Arg) {
774 // For some reason, the MSVC linker requires a filename to be
776 if (!Arg.startswith("@")) {
777 error("malformed /order option: '@' missing");
781 // Get a list of all comdat sections for error checking.
782 DenseSet<StringRef> Set;
783 for (Chunk *C : Symtab->getChunks())
784 if (auto *Sec = dyn_cast<SectionChunk>(C))
786 Set.insert(Sec->Sym->getName());
789 StringRef Path = Arg.substr(1);
790 std::unique_ptr<MemoryBuffer> MB = CHECK(
791 MemoryBuffer::getFile(Path, -1, false, true), "could not open " + Path);
793 // Parse a file. An order file contains one symbol per line.
794 // All symbols that were not present in a given order file are
795 // considered to have the lowest priority 0 and are placed at
796 // end of an output section.
797 for (std::string S : args::getLines(MB->getMemBufferRef())) {
798 if (Config->Machine == I386 && !isDecorated(S))
801 if (Set.count(S) == 0) {
802 if (Config->WarnMissingOrderSymbol)
803 warn("/order:" + Arg + ": missing symbol: " + S + " [LNK4037]");
806 Config->Order[S] = INT_MIN + Config->Order.size();
810 static void markAddrsig(Symbol *S) {
811 if (auto *D = dyn_cast_or_null<Defined>(S))
812 if (Chunk *C = D->getChunk())
813 C->KeepUnique = true;
816 static void findKeepUniqueSections() {
817 // Exported symbols could be address-significant in other executables or DSOs,
818 // so we conservatively mark them as address-significant.
819 for (Export &R : Config->Exports)
822 // Visit the address-significance table in each object file and mark each
823 // referenced symbol as address-significant.
824 for (ObjFile *Obj : ObjFile::Instances) {
825 ArrayRef<Symbol *> Syms = Obj->getSymbols();
826 if (Obj->AddrsigSec) {
827 ArrayRef<uint8_t> Contents;
828 Obj->getCOFFObj()->getSectionContents(Obj->AddrsigSec, Contents);
829 const uint8_t *Cur = Contents.begin();
830 while (Cur != Contents.end()) {
833 uint64_t SymIndex = decodeULEB128(Cur, &Size, Contents.end(), &Err);
835 fatal(toString(Obj) + ": could not decode addrsig section: " + Err);
836 if (SymIndex >= Syms.size())
837 fatal(toString(Obj) + ": invalid symbol index in addrsig section");
838 markAddrsig(Syms[SymIndex]);
842 // If an object file does not have an address-significance table,
843 // conservatively mark all of its symbols as address-significant.
844 for (Symbol *S : Syms)
850 // link.exe replaces each %foo% in AltPath with the contents of environment
851 // variable foo, and adds the two magic env vars _PDB (expands to the basename
852 // of pdb's output path) and _EXT (expands to the extension of the output
854 // lld only supports %_PDB% and %_EXT% and warns on references to all other env
856 static void parsePDBAltPath(StringRef AltPath) {
857 SmallString<128> Buf;
858 StringRef PDBBasename =
859 sys::path::filename(Config->PDBPath, sys::path::Style::windows);
860 StringRef BinaryExtension =
861 sys::path::extension(Config->OutputFile, sys::path::Style::windows);
862 if (!BinaryExtension.empty())
863 BinaryExtension = BinaryExtension.substr(1); // %_EXT% does not include '.'.
866 // +--------- Cursor ('a...' might be the empty string).
867 // | +----- FirstMark
872 while (Cursor < AltPath.size()) {
873 size_t FirstMark, SecondMark;
874 if ((FirstMark = AltPath.find('%', Cursor)) == StringRef::npos ||
875 (SecondMark = AltPath.find('%', FirstMark + 1)) == StringRef::npos) {
876 // Didn't find another full fragment, treat rest of string as literal.
877 Buf.append(AltPath.substr(Cursor));
881 // Found a full fragment. Append text in front of first %, and interpret
882 // text between first and second % as variable name.
883 Buf.append(AltPath.substr(Cursor, FirstMark - Cursor));
884 StringRef Var = AltPath.substr(FirstMark, SecondMark - FirstMark + 1);
885 if (Var.equals_lower("%_pdb%"))
886 Buf.append(PDBBasename);
887 else if (Var.equals_lower("%_ext%"))
888 Buf.append(BinaryExtension);
890 warn("only %_PDB% and %_EXT% supported in /pdbaltpath:, keeping " +
891 Var + " as literal");
895 Cursor = SecondMark + 1;
898 Config->PDBAltPath = Buf;
901 void LinkerDriver::link(ArrayRef<const char *> ArgsArr) {
902 // If the first command line argument is "/lib", link.exe acts like lib.exe.
903 // We call our own implementation of lib.exe that understands bitcode files.
904 if (ArgsArr.size() > 1 && StringRef(ArgsArr[1]).equals_lower("/lib")) {
905 if (llvm::libDriverMain(ArgsArr.slice(1)) != 0)
911 InitializeAllTargetInfos();
912 InitializeAllTargets();
913 InitializeAllTargetMCs();
914 InitializeAllAsmParsers();
915 InitializeAllAsmPrinters();
917 // Parse command line options.
919 opt::InputArgList Args = Parser.parseLINK(ArgsArr);
921 // Parse and evaluate -mllvm options.
922 std::vector<const char *> V;
923 V.push_back("lld-link (LLVM option parsing)");
924 for (auto *Arg : Args.filtered(OPT_mllvm))
925 V.push_back(Arg->getValue());
926 cl::ParseCommandLineOptions(V.size(), V.data());
928 // Handle /errorlimit early, because error() depends on it.
929 if (auto *Arg = Args.getLastArg(OPT_errorlimit)) {
931 StringRef S = Arg->getValue();
932 if (S.getAsInteger(10, N))
933 error(Arg->getSpelling() + " number expected, but got " + S);
934 errorHandler().ErrorLimit = N;
938 if (Args.hasArg(OPT_help)) {
939 printHelp(ArgsArr[0]);
943 if (Args.hasArg(OPT_show_timing))
944 Config->ShowTiming = true;
946 ScopedTimer T(Timer::root());
947 // Handle --version, which is an lld extension. This option is a bit odd
948 // because it doesn't start with "/", but we deliberately chose "--" to
949 // avoid conflict with /version and for compatibility with clang-cl.
950 if (Args.hasArg(OPT_dash_dash_version)) {
951 outs() << getLLDVersion() << "\n";
955 // Handle /lldmingw early, since it can potentially affect how other
956 // options are handled.
957 Config->MinGW = Args.hasArg(OPT_lldmingw);
959 if (auto *Arg = Args.getLastArg(OPT_linkrepro)) {
960 SmallString<64> Path = StringRef(Arg->getValue());
961 sys::path::append(Path, "repro.tar");
963 Expected<std::unique_ptr<TarWriter>> ErrOrWriter =
964 TarWriter::create(Path, "repro");
967 Tar = std::move(*ErrOrWriter);
969 error("/linkrepro: failed to open " + Path + ": " +
970 toString(ErrOrWriter.takeError()));
974 if (!Args.hasArg(OPT_INPUT)) {
975 if (Args.hasArg(OPT_deffile))
976 Config->NoEntry = true;
978 fatal("no input files");
981 // Construct search path list.
982 SearchPaths.push_back("");
983 for (auto *Arg : Args.filtered(OPT_libpath))
984 SearchPaths.push_back(Arg->getValue());
988 for (auto *Arg : Args.filtered(OPT_ignore)) {
989 SmallVector<StringRef, 8> Vec;
990 StringRef(Arg->getValue()).split(Vec, ',');
991 for (StringRef S : Vec) {
993 Config->WarnMissingOrderSymbol = false;
994 else if (S == "4099")
995 Config->WarnDebugInfoUnusable = false;
996 else if (S == "4217")
997 Config->WarnLocallyDefinedImported = false;
998 // Other warning numbers are ignored.
1003 if (auto *Arg = Args.getLastArg(OPT_out))
1004 Config->OutputFile = Arg->getValue();
1007 if (Args.hasArg(OPT_verbose))
1008 Config->Verbose = true;
1009 errorHandler().Verbose = Config->Verbose;
1011 // Handle /force or /force:unresolved
1012 if (Args.hasArg(OPT_force, OPT_force_unresolved))
1013 Config->ForceUnresolved = true;
1015 // Handle /force or /force:multiple
1016 if (Args.hasArg(OPT_force, OPT_force_multiple))
1017 Config->ForceMultiple = true;
1020 DebugKind Debug = parseDebugKind(Args);
1021 if (Debug == DebugKind::Full || Debug == DebugKind::Dwarf ||
1022 Debug == DebugKind::GHash) {
1023 Config->Debug = true;
1024 Config->Incremental = true;
1027 // Handle /debugtype
1028 Config->DebugTypes = parseDebugTypes(Args);
1031 bool ShouldCreatePDB =
1032 (Debug == DebugKind::Full || Debug == DebugKind::GHash);
1033 if (ShouldCreatePDB) {
1034 if (auto *Arg = Args.getLastArg(OPT_pdb))
1035 Config->PDBPath = Arg->getValue();
1036 if (auto *Arg = Args.getLastArg(OPT_pdbaltpath))
1037 Config->PDBAltPath = Arg->getValue();
1038 if (Args.hasArg(OPT_natvis))
1039 Config->NatvisFiles = Args.getAllArgValues(OPT_natvis);
1041 if (auto *Arg = Args.getLastArg(OPT_pdb_source_path))
1042 Config->PDBSourcePath = Arg->getValue();
1046 if (Args.hasArg(OPT_noentry)) {
1047 if (Args.hasArg(OPT_dll))
1048 Config->NoEntry = true;
1050 error("/noentry must be specified with /dll");
1054 if (Args.hasArg(OPT_dll)) {
1056 Config->ManifestID = 2;
1059 // Handle /dynamicbase and /fixed. We can't use hasFlag for /dynamicbase
1060 // because we need to explicitly check whether that option or its inverse was
1061 // present in the argument list in order to handle /fixed.
1062 auto *DynamicBaseArg = Args.getLastArg(OPT_dynamicbase, OPT_dynamicbase_no);
1063 if (DynamicBaseArg &&
1064 DynamicBaseArg->getOption().getID() == OPT_dynamicbase_no)
1065 Config->DynamicBase = false;
1067 // MSDN claims "/FIXED:NO is the default setting for a DLL, and /FIXED is the
1068 // default setting for any other project type.", but link.exe defaults to
1069 // /FIXED:NO for exe outputs as well. Match behavior, not docs.
1070 bool Fixed = Args.hasFlag(OPT_fixed, OPT_fixed_no, false);
1072 if (DynamicBaseArg &&
1073 DynamicBaseArg->getOption().getID() == OPT_dynamicbase) {
1074 error("/fixed must not be specified with /dynamicbase");
1076 Config->Relocatable = false;
1077 Config->DynamicBase = false;
1081 // Handle /appcontainer
1082 Config->AppContainer =
1083 Args.hasFlag(OPT_appcontainer, OPT_appcontainer_no, false);
1086 if (auto *Arg = Args.getLastArg(OPT_machine))
1087 Config->Machine = getMachineType(Arg->getValue());
1089 // Handle /nodefaultlib:<filename>
1090 for (auto *Arg : Args.filtered(OPT_nodefaultlib))
1091 Config->NoDefaultLibs.insert(doFindLib(Arg->getValue()));
1093 // Handle /nodefaultlib
1094 if (Args.hasArg(OPT_nodefaultlib_all))
1095 Config->NoDefaultLibAll = true;
1098 if (auto *Arg = Args.getLastArg(OPT_base))
1099 parseNumbers(Arg->getValue(), &Config->ImageBase);
1102 if (auto *Arg = Args.getLastArg(OPT_stack))
1103 parseNumbers(Arg->getValue(), &Config->StackReserve, &Config->StackCommit);
1106 if (auto *Arg = Args.getLastArg(OPT_guard))
1107 parseGuard(Arg->getValue());
1110 if (auto *Arg = Args.getLastArg(OPT_heap))
1111 parseNumbers(Arg->getValue(), &Config->HeapReserve, &Config->HeapCommit);
1114 if (auto *Arg = Args.getLastArg(OPT_version))
1115 parseVersion(Arg->getValue(), &Config->MajorImageVersion,
1116 &Config->MinorImageVersion);
1118 // Handle /subsystem
1119 if (auto *Arg = Args.getLastArg(OPT_subsystem))
1120 parseSubsystem(Arg->getValue(), &Config->Subsystem, &Config->MajorOSVersion,
1121 &Config->MinorOSVersion);
1123 // Handle /timestamp
1124 if (llvm::opt::Arg *Arg = Args.getLastArg(OPT_timestamp, OPT_repro)) {
1125 if (Arg->getOption().getID() == OPT_repro) {
1126 Config->Timestamp = 0;
1127 Config->Repro = true;
1129 Config->Repro = false;
1130 StringRef Value(Arg->getValue());
1131 if (Value.getAsInteger(0, Config->Timestamp))
1132 fatal(Twine("invalid timestamp: ") + Value +
1133 ". Expected 32-bit integer");
1136 Config->Repro = false;
1137 Config->Timestamp = time(nullptr);
1140 // Handle /alternatename
1141 for (auto *Arg : Args.filtered(OPT_alternatename))
1142 parseAlternateName(Arg->getValue());
1145 for (auto *Arg : Args.filtered(OPT_incl))
1146 addUndefined(Arg->getValue());
1149 if (auto *Arg = Args.getLastArg(OPT_implib))
1150 Config->Implib = Arg->getValue();
1153 bool DoGC = Debug == DebugKind::None || Args.hasArg(OPT_profile);
1155 Args.hasArg(OPT_profile) ? 0 : 1; // 0: off, 1: limited, 2: on
1156 unsigned TailMerge = 1;
1157 for (auto *Arg : Args.filtered(OPT_opt)) {
1158 std::string Str = StringRef(Arg->getValue()).lower();
1159 SmallVector<StringRef, 1> Vec;
1160 StringRef(Str).split(Vec, ',');
1161 for (StringRef S : Vec) {
1164 } else if (S == "noref") {
1166 } else if (S == "icf" || S.startswith("icf=")) {
1168 } else if (S == "noicf") {
1170 } else if (S == "lldtailmerge") {
1172 } else if (S == "nolldtailmerge") {
1174 } else if (S.startswith("lldlto=")) {
1175 StringRef OptLevel = S.substr(7);
1176 if (OptLevel.getAsInteger(10, Config->LTOO) || Config->LTOO > 3)
1177 error("/opt:lldlto: invalid optimization level: " + OptLevel);
1178 } else if (S.startswith("lldltojobs=")) {
1179 StringRef Jobs = S.substr(11);
1180 if (Jobs.getAsInteger(10, Config->ThinLTOJobs) ||
1181 Config->ThinLTOJobs == 0)
1182 error("/opt:lldltojobs: invalid job count: " + Jobs);
1183 } else if (S.startswith("lldltopartitions=")) {
1184 StringRef N = S.substr(17);
1185 if (N.getAsInteger(10, Config->LTOPartitions) ||
1186 Config->LTOPartitions == 0)
1187 error("/opt:lldltopartitions: invalid partition count: " + N);
1188 } else if (S != "lbr" && S != "nolbr")
1189 error("/opt: unknown option: " + S);
1193 // Limited ICF is enabled if GC is enabled and ICF was never mentioned
1195 // FIXME: LLD only implements "limited" ICF, i.e. it only merges identical
1196 // code. If the user passes /OPT:ICF explicitly, LLD should merge identical
1197 // comdat readonly data.
1198 if (ICFLevel == 1 && !DoGC)
1200 Config->DoGC = DoGC;
1201 Config->DoICF = ICFLevel > 0;
1202 Config->TailMerge = (TailMerge == 1 && Config->DoICF) || TailMerge == 2;
1204 // Handle /lldsavetemps
1205 if (Args.hasArg(OPT_lldsavetemps))
1206 Config->SaveTemps = true;
1209 if (Args.hasArg(OPT_kill_at))
1210 Config->KillAt = true;
1212 // Handle /lldltocache
1213 if (auto *Arg = Args.getLastArg(OPT_lldltocache))
1214 Config->LTOCache = Arg->getValue();
1216 // Handle /lldsavecachepolicy
1217 if (auto *Arg = Args.getLastArg(OPT_lldltocachepolicy))
1218 Config->LTOCachePolicy = CHECK(
1219 parseCachePruningPolicy(Arg->getValue()),
1220 Twine("/lldltocachepolicy: invalid cache policy: ") + Arg->getValue());
1222 // Handle /failifmismatch
1223 for (auto *Arg : Args.filtered(OPT_failifmismatch))
1224 checkFailIfMismatch(Arg->getValue());
1227 for (auto *Arg : Args.filtered(OPT_merge))
1228 parseMerge(Arg->getValue());
1230 // Add default section merging rules after user rules. User rules take
1231 // precedence, but we will emit a warning if there is a conflict.
1232 parseMerge(".idata=.rdata");
1233 parseMerge(".didat=.rdata");
1234 parseMerge(".edata=.rdata");
1235 parseMerge(".xdata=.rdata");
1236 parseMerge(".bss=.data");
1238 if (Config->MinGW) {
1239 parseMerge(".ctors=.rdata");
1240 parseMerge(".dtors=.rdata");
1241 parseMerge(".CRT=.rdata");
1245 for (auto *Arg : Args.filtered(OPT_section))
1246 parseSection(Arg->getValue());
1248 // Handle /aligncomm
1249 for (auto *Arg : Args.filtered(OPT_aligncomm))
1250 parseAligncomm(Arg->getValue());
1252 // Handle /manifestdependency. This enables /manifest unless /manifest:no is
1254 if (auto *Arg = Args.getLastArg(OPT_manifestdependency)) {
1255 Config->ManifestDependency = Arg->getValue();
1256 Config->Manifest = Configuration::SideBySide;
1259 // Handle /manifest and /manifest:
1260 if (auto *Arg = Args.getLastArg(OPT_manifest, OPT_manifest_colon)) {
1261 if (Arg->getOption().getID() == OPT_manifest)
1262 Config->Manifest = Configuration::SideBySide;
1264 parseManifest(Arg->getValue());
1267 // Handle /manifestuac
1268 if (auto *Arg = Args.getLastArg(OPT_manifestuac))
1269 parseManifestUAC(Arg->getValue());
1271 // Handle /manifestfile
1272 if (auto *Arg = Args.getLastArg(OPT_manifestfile))
1273 Config->ManifestFile = Arg->getValue();
1275 // Handle /manifestinput
1276 for (auto *Arg : Args.filtered(OPT_manifestinput))
1277 Config->ManifestInput.push_back(Arg->getValue());
1279 if (!Config->ManifestInput.empty() &&
1280 Config->Manifest != Configuration::Embed) {
1281 fatal("/manifestinput: requires /manifest:embed");
1284 // Handle miscellaneous boolean flags.
1285 Config->AllowBind = Args.hasFlag(OPT_allowbind, OPT_allowbind_no, true);
1286 Config->AllowIsolation =
1287 Args.hasFlag(OPT_allowisolation, OPT_allowisolation_no, true);
1288 Config->Incremental =
1289 Args.hasFlag(OPT_incremental, OPT_incremental_no,
1290 !Config->DoGC && !Config->DoICF && !Args.hasArg(OPT_order) &&
1291 !Args.hasArg(OPT_profile));
1292 Config->IntegrityCheck =
1293 Args.hasFlag(OPT_integritycheck, OPT_integritycheck_no, false);
1294 Config->NxCompat = Args.hasFlag(OPT_nxcompat, OPT_nxcompat_no, true);
1295 Config->TerminalServerAware =
1296 !Config->DLL && Args.hasFlag(OPT_tsaware, OPT_tsaware_no, true);
1297 Config->DebugDwarf = Debug == DebugKind::Dwarf;
1298 Config->DebugGHashes = Debug == DebugKind::GHash;
1299 Config->DebugSymtab = Debug == DebugKind::Symtab;
1301 Config->MapFile = getMapFile(Args);
1303 if (Config->Incremental && Args.hasArg(OPT_profile)) {
1304 warn("ignoring '/incremental' due to '/profile' specification");
1305 Config->Incremental = false;
1308 if (Config->Incremental && Args.hasArg(OPT_order)) {
1309 warn("ignoring '/incremental' due to '/order' specification");
1310 Config->Incremental = false;
1313 if (Config->Incremental && Config->DoGC) {
1314 warn("ignoring '/incremental' because REF is enabled; use '/opt:noref' to "
1316 Config->Incremental = false;
1319 if (Config->Incremental && Config->DoICF) {
1320 warn("ignoring '/incremental' because ICF is enabled; use '/opt:noicf' to "
1322 Config->Incremental = false;
1328 std::set<sys::fs::UniqueID> WholeArchives;
1329 AutoExporter Exporter;
1330 for (auto *Arg : Args.filtered(OPT_wholearchive_file)) {
1331 if (Optional<StringRef> Path = doFindFile(Arg->getValue())) {
1332 if (Optional<sys::fs::UniqueID> ID = getUniqueID(*Path))
1333 WholeArchives.insert(*ID);
1334 Exporter.addWholeArchive(*Path);
1338 // A predicate returning true if a given path is an argument for
1339 // /wholearchive:, or /wholearchive is enabled globally.
1340 // This function is a bit tricky because "foo.obj /wholearchive:././foo.obj"
1341 // needs to be handled as "/wholearchive:foo.obj foo.obj".
1342 auto IsWholeArchive = [&](StringRef Path) -> bool {
1343 if (Args.hasArg(OPT_wholearchive_flag))
1345 if (Optional<sys::fs::UniqueID> ID = getUniqueID(Path))
1346 return WholeArchives.count(*ID);
1350 // Create a list of input files. Files can be given as arguments
1351 // for /defaultlib option.
1352 for (auto *Arg : Args.filtered(OPT_INPUT, OPT_wholearchive_file))
1353 if (Optional<StringRef> Path = findFile(Arg->getValue()))
1354 enqueuePath(*Path, IsWholeArchive(*Path));
1356 for (auto *Arg : Args.filtered(OPT_defaultlib))
1357 if (Optional<StringRef> Path = findLib(Arg->getValue()))
1358 enqueuePath(*Path, false);
1360 // Windows specific -- Create a resource file containing a manifest file.
1361 if (Config->Manifest == Configuration::Embed)
1362 addBuffer(createManifestRes(), false);
1364 // Read all input files given via the command line.
1370 // We should have inferred a machine type by now from the input files, but if
1371 // not we assume x64.
1372 if (Config->Machine == IMAGE_FILE_MACHINE_UNKNOWN) {
1373 warn("/machine is not specified. x64 is assumed");
1374 Config->Machine = AMD64;
1376 Config->Wordsize = Config->is64() ? 8 : 4;
1378 // Input files can be Windows resource files (.res files). We use
1379 // WindowsResource to convert resource files to a regular COFF file,
1380 // then link the resulting file normally.
1381 if (!Resources.empty())
1382 Symtab->addFile(make<ObjFile>(convertResToCOFF(Resources)));
1385 Tar->append("response.txt",
1386 createResponseFile(Args, FilePaths,
1387 ArrayRef<StringRef>(SearchPaths).slice(1)));
1389 // Handle /largeaddressaware
1390 Config->LargeAddressAware = Args.hasFlag(
1391 OPT_largeaddressaware, OPT_largeaddressaware_no, Config->is64());
1393 // Handle /highentropyva
1394 Config->HighEntropyVA =
1396 Args.hasFlag(OPT_highentropyva, OPT_highentropyva_no, true);
1398 if (!Config->DynamicBase &&
1399 (Config->Machine == ARMNT || Config->Machine == ARM64))
1400 error("/dynamicbase:no is not compatible with " +
1401 machineToStr(Config->Machine));
1404 for (auto *Arg : Args.filtered(OPT_export)) {
1405 Export E = parseExport(Arg->getValue());
1406 if (Config->Machine == I386) {
1407 if (!isDecorated(E.Name))
1408 E.Name = Saver.save("_" + E.Name);
1409 if (!E.ExtName.empty() && !isDecorated(E.ExtName))
1410 E.ExtName = Saver.save("_" + E.ExtName);
1412 Config->Exports.push_back(E);
1416 if (auto *Arg = Args.getLastArg(OPT_deffile)) {
1417 // parseModuleDefs mutates Config object.
1418 parseModuleDefs(Arg->getValue());
1421 // Handle generation of import library from a def file.
1422 if (!Args.hasArg(OPT_INPUT)) {
1424 createImportLibrary(/*AsLib=*/true);
1428 // Windows specific -- if no /subsystem is given, we need to infer
1429 // that from entry point name. Must happen before /entry handling,
1430 // and after the early return when just writing an import library.
1431 if (Config->Subsystem == IMAGE_SUBSYSTEM_UNKNOWN) {
1432 Config->Subsystem = inferSubsystem();
1433 if (Config->Subsystem == IMAGE_SUBSYSTEM_UNKNOWN)
1434 fatal("subsystem must be defined");
1437 // Handle /entry and /dll
1438 if (auto *Arg = Args.getLastArg(OPT_entry)) {
1439 Config->Entry = addUndefined(mangle(Arg->getValue()));
1440 } else if (!Config->Entry && !Config->NoEntry) {
1441 if (Args.hasArg(OPT_dll)) {
1442 StringRef S = (Config->Machine == I386) ? "__DllMainCRTStartup@12"
1443 : "_DllMainCRTStartup";
1444 Config->Entry = addUndefined(S);
1446 // Windows specific -- If entry point name is not given, we need to
1447 // infer that from user-defined entry name.
1448 StringRef S = findDefaultEntry();
1450 fatal("entry point must be defined");
1451 Config->Entry = addUndefined(S);
1452 log("Entry name inferred: " + S);
1456 // Handle /delayload
1457 for (auto *Arg : Args.filtered(OPT_delayload)) {
1458 Config->DelayLoads.insert(StringRef(Arg->getValue()).lower());
1459 if (Config->Machine == I386) {
1460 Config->DelayLoadHelper = addUndefined("___delayLoadHelper2@8");
1462 Config->DelayLoadHelper = addUndefined("__delayLoadHelper2");
1466 // Set default image name if neither /out or /def set it.
1467 if (Config->OutputFile.empty()) {
1468 Config->OutputFile =
1469 getOutputPath((*Args.filtered(OPT_INPUT).begin())->getValue());
1472 if (ShouldCreatePDB) {
1473 // Put the PDB next to the image if no /pdb flag was passed.
1474 if (Config->PDBPath.empty()) {
1475 Config->PDBPath = Config->OutputFile;
1476 sys::path::replace_extension(Config->PDBPath, ".pdb");
1479 // The embedded PDB path should be the absolute path to the PDB if no
1480 // /pdbaltpath flag was passed.
1481 if (Config->PDBAltPath.empty()) {
1482 Config->PDBAltPath = Config->PDBPath;
1484 // It's important to make the path absolute and remove dots. This path
1485 // will eventually be written into the PE header, and certain Microsoft
1486 // tools won't work correctly if these assumptions are not held.
1487 sys::fs::make_absolute(Config->PDBAltPath);
1488 sys::path::remove_dots(Config->PDBAltPath);
1490 // Don't do this earlier, so that Config->OutputFile is ready.
1491 parsePDBAltPath(Config->PDBAltPath);
1495 // Set default image base if /base is not given.
1496 if (Config->ImageBase == uint64_t(-1))
1497 Config->ImageBase = getDefaultImageBase();
1499 Symtab->addSynthetic(mangle("__ImageBase"), nullptr);
1500 if (Config->Machine == I386) {
1501 Symtab->addAbsolute("___safe_se_handler_table", 0);
1502 Symtab->addAbsolute("___safe_se_handler_count", 0);
1505 Symtab->addAbsolute(mangle("__guard_fids_count"), 0);
1506 Symtab->addAbsolute(mangle("__guard_fids_table"), 0);
1507 Symtab->addAbsolute(mangle("__guard_flags"), 0);
1508 Symtab->addAbsolute(mangle("__guard_iat_count"), 0);
1509 Symtab->addAbsolute(mangle("__guard_iat_table"), 0);
1510 Symtab->addAbsolute(mangle("__guard_longjmp_count"), 0);
1511 Symtab->addAbsolute(mangle("__guard_longjmp_table"), 0);
1512 // Needed for MSVC 2017 15.5 CRT.
1513 Symtab->addAbsolute(mangle("__enclave_config"), 0);
1515 if (Config->MinGW) {
1516 Symtab->addAbsolute(mangle("__RUNTIME_PSEUDO_RELOC_LIST__"), 0);
1517 Symtab->addAbsolute(mangle("__RUNTIME_PSEUDO_RELOC_LIST_END__"), 0);
1518 Symtab->addAbsolute(mangle("__CTOR_LIST__"), 0);
1519 Symtab->addAbsolute(mangle("__DTOR_LIST__"), 0);
1522 // This code may add new undefined symbols to the link, which may enqueue more
1523 // symbol resolution tasks, so we need to continue executing tasks until we
1526 // Windows specific -- if entry point is not found,
1527 // search for its mangled names.
1529 Symtab->mangleMaybe(Config->Entry);
1531 // Windows specific -- Make sure we resolve all dllexported symbols.
1532 for (Export &E : Config->Exports) {
1533 if (!E.ForwardTo.empty())
1535 E.Sym = addUndefined(E.Name);
1537 Symtab->mangleMaybe(E.Sym);
1540 // Add weak aliases. Weak aliases is a mechanism to give remaining
1541 // undefined symbols final chance to be resolved successfully.
1542 for (auto Pair : Config->AlternateNames) {
1543 StringRef From = Pair.first;
1544 StringRef To = Pair.second;
1545 Symbol *Sym = Symtab->find(From);
1548 if (auto *U = dyn_cast<Undefined>(Sym))
1550 U->WeakAlias = Symtab->addUndefined(To);
1553 // Windows specific -- if __load_config_used can be resolved, resolve it.
1554 if (Symtab->findUnderscore("_load_config_used"))
1555 addUndefined(mangle("_load_config_used"));
1561 // Do LTO by compiling bitcode input files to a set of native COFF files then
1562 // link those files.
1563 Symtab->addCombinedLTOObjects();
1566 if (Config->MinGW) {
1567 // Load any further object files that might be needed for doing automatic
1570 // For cases with no automatically imported symbols, this iterates once
1571 // over the symbol table and doesn't do anything.
1573 // For the normal case with a few automatically imported symbols, this
1574 // should only need to be run once, since each new object file imported
1575 // is an import library and wouldn't add any new undefined references,
1576 // but there's nothing stopping the __imp_ symbols from coming from a
1577 // normal object file as well (although that won't be used for the
1578 // actual autoimport later on). If this pass adds new undefined references,
1579 // we won't iterate further to resolve them.
1580 Symtab->loadMinGWAutomaticImports();
1584 // Make sure we have resolved all symbols.
1585 Symtab->reportRemainingUndefines();
1590 if (Args.hasFlag(OPT_safeseh, OPT_safeseh_no, false)) {
1591 for (ObjFile *File : ObjFile::Instances)
1592 if (!File->hasSafeSEH())
1593 error("/safeseh: " + File->getName() + " is not compatible with SEH");
1598 // In MinGW, all symbols are automatically exported if no symbols
1599 // are chosen to be exported.
1600 if (Config->DLL && ((Config->MinGW && Config->Exports.empty()) ||
1601 Args.hasArg(OPT_export_all_symbols))) {
1602 Exporter.initSymbolExcludes();
1604 Symtab->forEachSymbol([=](Symbol *S) {
1605 auto *Def = dyn_cast<Defined>(S);
1606 if (!Exporter.shouldExport(Def))
1609 E.Name = Def->getName();
1611 if (Def->getChunk() &&
1612 !(Def->getChunk()->getOutputCharacteristics() & IMAGE_SCN_MEM_EXECUTE))
1614 Config->Exports.push_back(E);
1618 // Windows specific -- when we are creating a .dll file, we also
1619 // need to create a .lib file.
1620 if (!Config->Exports.empty() || Config->DLL) {
1622 createImportLibrary(/*AsLib=*/false);
1623 assignExportOrdinals();
1626 // Handle /output-def (MinGW specific).
1627 if (auto *Arg = Args.getLastArg(OPT_output_def))
1628 writeDefFile(Arg->getValue());
1630 // Set extra alignment for .comm symbols
1631 for (auto Pair : Config->AlignComm) {
1632 StringRef Name = Pair.first;
1633 uint32_t Alignment = Pair.second;
1635 Symbol *Sym = Symtab->find(Name);
1637 warn("/aligncomm symbol " + Name + " not found");
1641 // If the symbol isn't common, it must have been replaced with a regular
1642 // symbol, which will carry its own alignment.
1643 auto *DC = dyn_cast<DefinedCommon>(Sym);
1647 CommonChunk *C = DC->getChunk();
1648 C->Alignment = std::max(C->Alignment, Alignment);
1651 // Windows specific -- Create a side-by-side manifest file.
1652 if (Config->Manifest == Configuration::SideBySide)
1653 createSideBySideManifest();
1655 // Handle /order. We want to do this at this moment because we
1656 // need a complete list of comdat sections to warn on nonexistent
1658 if (auto *Arg = Args.getLastArg(OPT_order))
1659 parseOrderFile(Arg->getValue());
1661 // Identify unreferenced COMDAT sections.
1663 markLive(Symtab->getChunks());
1665 // Identify identical COMDAT sections to merge them.
1666 if (Config->DoICF) {
1667 findKeepUniqueSections();
1668 doICF(Symtab->getChunks());
1671 // Write the result.
1674 // Stop early so we can print the results.
1675 Timer::root().stop();
1676 if (Config->ShowTiming)
1677 Timer::root().print();