1 //===- Driver.cpp ---------------------------------------------------------===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
11 #include "DebugTypes.h"
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/Filesystem.h"
23 #include "lld/Common/Memory.h"
24 #include "lld/Common/Threads.h"
25 #include "lld/Common/Timer.h"
26 #include "lld/Common/Version.h"
27 #include "llvm/ADT/Optional.h"
28 #include "llvm/ADT/StringSwitch.h"
29 #include "llvm/BinaryFormat/Magic.h"
30 #include "llvm/Object/ArchiveWriter.h"
31 #include "llvm/Object/COFFImportFile.h"
32 #include "llvm/Object/COFFModuleDefinition.h"
33 #include "llvm/Object/WindowsMachineFlag.h"
34 #include "llvm/Option/Arg.h"
35 #include "llvm/Option/ArgList.h"
36 #include "llvm/Option/Option.h"
37 #include "llvm/Support/Debug.h"
38 #include "llvm/Support/LEB128.h"
39 #include "llvm/Support/MathExtras.h"
40 #include "llvm/Support/Path.h"
41 #include "llvm/Support/Process.h"
42 #include "llvm/Support/TarWriter.h"
43 #include "llvm/Support/TargetSelect.h"
44 #include "llvm/Support/raw_ostream.h"
45 #include "llvm/ToolDrivers/llvm-lib/LibDriver.h"
51 using namespace llvm::object;
52 using namespace llvm::COFF;
53 using llvm::sys::Process;
58 static Timer inputFileTimer("Input File Reading", Timer::root());
60 Configuration *config;
63 bool link(ArrayRef<const char *> args, bool canExitEarly, raw_ostream &diag) {
64 errorHandler().logName = args::getFilenameWithoutExe(args[0]);
65 errorHandler().errorOS = &diag;
66 errorHandler().colorDiagnostics = diag.has_colors();
67 errorHandler().errorLimitExceededMsg =
68 "too many errors emitted, stopping now"
69 " (use /errorlimit:0 to see all errors)";
70 errorHandler().exitEarly = canExitEarly;
71 config = make<Configuration>();
73 symtab = make<SymbolTable>();
75 driver = make<LinkerDriver>();
78 // Call exit() if we can to avoid calling destructors.
80 exitLld(errorCount() ? 1 : 0);
83 ObjFile::instances.clear();
84 ImportFile::instances.clear();
85 BitcodeFile::instances.clear();
86 memset(MergeChunk::instances, 0, sizeof(MergeChunk::instances));
90 // Parse options of the form "old;new".
91 static std::pair<StringRef, StringRef> getOldNewOptions(opt::InputArgList &args,
93 auto *arg = args.getLastArg(id);
97 StringRef s = arg->getValue();
98 std::pair<StringRef, StringRef> ret = s.split(';');
99 if (ret.second.empty())
100 error(arg->getSpelling() + " expects 'old;new' format, but got " + s);
104 // Drop directory components and replace extension with ".exe" or ".dll".
105 static std::string getOutputPath(StringRef path) {
106 auto p = path.find_last_of("\\/");
107 StringRef s = (p == StringRef::npos) ? path : path.substr(p + 1);
108 const char* e = config->dll ? ".dll" : ".exe";
109 return (s.substr(0, s.rfind('.')) + e).str();
112 // Returns true if S matches /crtend.?\.o$/.
113 static bool isCrtend(StringRef s) {
114 if (!s.endswith(".o"))
117 if (s.endswith("crtend"))
119 return !s.empty() && s.drop_back().endswith("crtend");
122 // ErrorOr is not default constructible, so it cannot be used as the type
123 // parameter of a future.
124 // FIXME: We could open the file in createFutureForFile and avoid needing to
125 // return an error here, but for the moment that would cost us a file descriptor
126 // (a limited resource on Windows) for the duration that the future is pending.
127 using MBErrPair = std::pair<std::unique_ptr<MemoryBuffer>, std::error_code>;
129 // Create a std::future that opens and maps a file using the best strategy for
130 // the host platform.
131 static std::future<MBErrPair> createFutureForFile(std::string path) {
133 // On Windows, file I/O is relatively slow so it is best to do this
135 auto strategy = std::launch::async;
137 auto strategy = std::launch::deferred;
139 return std::async(strategy, [=]() {
140 auto mbOrErr = MemoryBuffer::getFile(path,
142 /*RequiresNullTerminator*/ false);
144 return MBErrPair{nullptr, mbOrErr.getError()};
145 return MBErrPair{std::move(*mbOrErr), std::error_code()};
149 // Symbol names are mangled by prepending "_" on x86.
150 static StringRef mangle(StringRef sym) {
151 assert(config->machine != IMAGE_FILE_MACHINE_UNKNOWN);
152 if (config->machine == I386)
153 return saver.save("_" + sym);
157 static bool findUnderscoreMangle(StringRef sym) {
158 Symbol *s = symtab->findMangle(mangle(sym));
159 return s && !isa<Undefined>(s);
162 MemoryBufferRef LinkerDriver::takeBuffer(std::unique_ptr<MemoryBuffer> mb) {
163 MemoryBufferRef mbref = *mb;
164 make<std::unique_ptr<MemoryBuffer>>(std::move(mb)); // take ownership
167 driver->tar->append(relativeToRoot(mbref.getBufferIdentifier()),
172 void LinkerDriver::addBuffer(std::unique_ptr<MemoryBuffer> mb,
174 StringRef filename = mb->getBufferIdentifier();
176 MemoryBufferRef mbref = takeBuffer(std::move(mb));
177 filePaths.push_back(filename);
179 // File type is detected by contents, not by file extension.
180 switch (identify_magic(mbref.getBuffer())) {
181 case file_magic::windows_resource:
182 resources.push_back(mbref);
184 case file_magic::archive:
186 std::unique_ptr<Archive> file =
187 CHECK(Archive::create(mbref), filename + ": failed to parse archive");
188 Archive *archive = file.get();
189 make<std::unique_ptr<Archive>>(std::move(file)); // take ownership
191 for (MemoryBufferRef m : getArchiveMembers(archive))
192 addArchiveBuffer(m, "<whole-archive>", filename, 0);
195 symtab->addFile(make<ArchiveFile>(mbref));
197 case file_magic::bitcode:
198 symtab->addFile(make<BitcodeFile>(mbref, "", 0));
200 case file_magic::coff_object:
201 case file_magic::coff_import_library:
202 symtab->addFile(make<ObjFile>(mbref));
204 case file_magic::pdb:
205 loadTypeServerSource(mbref);
207 case file_magic::coff_cl_gl_object:
208 error(filename + ": is not a native COFF file. Recompile without /GL");
210 case file_magic::pecoff_executable:
211 if (filename.endswith_lower(".dll")) {
212 error(filename + ": bad file type. Did you specify a DLL instead of an "
218 error(mbref.getBufferIdentifier() + ": unknown file type");
223 void LinkerDriver::enqueuePath(StringRef path, bool wholeArchive) {
225 std::make_shared<std::future<MBErrPair>>(createFutureForFile(path));
226 std::string pathStr = path;
228 auto mbOrErr = future->get();
229 if (mbOrErr.second) {
231 "could not open '" + pathStr + "': " + mbOrErr.second.message();
232 // Check if the filename is a typo for an option flag. OptTable thinks
233 // that all args that are not known options and that start with / are
234 // filenames, but e.g. `/nodefaultlibs` is more likely a typo for
235 // the option `/nodefaultlib` than a reference to a file in the root
238 if (COFFOptTable().findNearest(pathStr, nearest) > 1)
241 error(msg + "; did you mean '" + nearest + "'");
243 driver->addBuffer(std::move(mbOrErr.first), wholeArchive);
247 void LinkerDriver::addArchiveBuffer(MemoryBufferRef mb, StringRef symName,
248 StringRef parentName,
249 uint64_t offsetInArchive) {
250 file_magic magic = identify_magic(mb.getBuffer());
251 if (magic == file_magic::coff_import_library) {
252 InputFile *imp = make<ImportFile>(mb);
253 imp->parentName = parentName;
254 symtab->addFile(imp);
259 if (magic == file_magic::coff_object) {
260 obj = make<ObjFile>(mb);
261 } else if (magic == file_magic::bitcode) {
262 obj = make<BitcodeFile>(mb, parentName, offsetInArchive);
264 error("unknown file type: " + mb.getBufferIdentifier());
268 obj->parentName = parentName;
269 symtab->addFile(obj);
270 log("Loaded " + toString(obj) + " for " + symName);
273 void LinkerDriver::enqueueArchiveMember(const Archive::Child &c,
274 const Archive::Symbol &sym,
275 StringRef parentName) {
277 auto reportBufferError = [=](Error &&e, StringRef childName) {
278 fatal("could not get the buffer for the member defining symbol " +
279 toCOFFString(sym) + ": " + parentName + "(" + childName + "): " +
280 toString(std::move(e)));
283 if (!c.getParent()->isThin()) {
284 uint64_t offsetInArchive = c.getChildOffset();
285 Expected<MemoryBufferRef> mbOrErr = c.getMemoryBufferRef();
287 reportBufferError(mbOrErr.takeError(), check(c.getFullName()));
288 MemoryBufferRef mb = mbOrErr.get();
290 driver->addArchiveBuffer(mb, toCOFFString(sym), parentName,
296 std::string childName = CHECK(
298 "could not get the filename for the member defining symbol " +
300 auto future = std::make_shared<std::future<MBErrPair>>(
301 createFutureForFile(childName));
303 auto mbOrErr = future->get();
305 reportBufferError(errorCodeToError(mbOrErr.second), childName);
306 driver->addArchiveBuffer(takeBuffer(std::move(mbOrErr.first)),
307 toCOFFString(sym), parentName,
308 /*OffsetInArchive=*/0);
312 static bool isDecorated(StringRef sym) {
313 return sym.startswith("@") || sym.contains("@@") || sym.startswith("?") ||
314 (!config->mingw && sym.contains('@'));
317 // Parses .drectve section contents and returns a list of files
318 // specified by /defaultlib.
319 void LinkerDriver::parseDirectives(InputFile *file) {
320 StringRef s = file->getDirectives();
324 log("Directives: " + toString(file) + ": " + s);
327 // .drectve is always tokenized using Windows shell rules.
328 // /EXPORT: option can appear too many times, processing in fastpath.
329 opt::InputArgList args;
330 std::vector<StringRef> exports;
331 std::tie(args, exports) = parser.parseDirectives(s);
333 for (StringRef e : exports) {
334 // If a common header file contains dllexported function
335 // declarations, many object files may end up with having the
336 // same /EXPORT options. In order to save cost of parsing them,
337 // we dedup them first.
338 if (!directivesExports.insert(e).second)
341 Export exp = parseExport(e);
342 if (config->machine == I386 && config->mingw) {
343 if (!isDecorated(exp.name))
344 exp.name = saver.save("_" + exp.name);
345 if (!exp.extName.empty() && !isDecorated(exp.extName))
346 exp.extName = saver.save("_" + exp.extName);
348 exp.directives = true;
349 config->exports.push_back(exp);
352 for (auto *arg : args) {
353 switch (arg->getOption().getID()) {
355 parseAligncomm(arg->getValue());
357 case OPT_alternatename:
358 parseAlternateName(arg->getValue());
361 if (Optional<StringRef> path = findLib(arg->getValue()))
362 enqueuePath(*path, false);
365 config->entry = addUndefined(mangle(arg->getValue()));
367 case OPT_failifmismatch:
368 checkFailIfMismatch(arg->getValue(), file);
371 addUndefined(arg->getValue());
374 parseMerge(arg->getValue());
376 case OPT_nodefaultlib:
377 config->noDefaultLibs.insert(doFindLib(arg->getValue()).lower());
380 parseSection(arg->getValue());
383 parseSubsystem(arg->getValue(), &config->subsystem,
384 &config->majorOSVersion, &config->minorOSVersion);
386 // Only add flags here that link.exe accepts in
387 // `#pragma comment(linker, "/flag")`-generated sections.
388 case OPT_editandcontinue:
390 case OPT_throwingnew:
393 error(arg->getSpelling() + " is not allowed in .drectve");
398 // Find file from search paths. You can omit ".obj", this function takes
399 // care of that. Note that the returned path is not guaranteed to exist.
400 StringRef LinkerDriver::doFindFile(StringRef filename) {
401 bool hasPathSep = (filename.find_first_of("/\\") != StringRef::npos);
404 bool hasExt = filename.contains('.');
405 for (StringRef dir : searchPaths) {
406 SmallString<128> path = dir;
407 sys::path::append(path, filename);
408 if (sys::fs::exists(path.str()))
409 return saver.save(path.str());
412 if (sys::fs::exists(path.str()))
413 return saver.save(path.str());
419 static Optional<sys::fs::UniqueID> getUniqueID(StringRef path) {
420 sys::fs::UniqueID ret;
421 if (sys::fs::getUniqueID(path, ret))
426 // Resolves a file path. This never returns the same path
427 // (in that case, it returns None).
428 Optional<StringRef> LinkerDriver::findFile(StringRef filename) {
429 StringRef path = doFindFile(filename);
431 if (Optional<sys::fs::UniqueID> id = getUniqueID(path)) {
432 bool seen = !visitedFiles.insert(*id).second;
437 if (path.endswith_lower(".lib"))
438 visitedLibs.insert(sys::path::filename(path));
442 // MinGW specific. If an embedded directive specified to link to
443 // foo.lib, but it isn't found, try libfoo.a instead.
444 StringRef LinkerDriver::doFindLibMinGW(StringRef filename) {
445 if (filename.contains('/') || filename.contains('\\'))
448 SmallString<128> s = filename;
449 sys::path::replace_extension(s, ".a");
450 StringRef libName = saver.save("lib" + s.str());
451 return doFindFile(libName);
454 // Find library file from search path.
455 StringRef LinkerDriver::doFindLib(StringRef filename) {
456 // Add ".lib" to Filename if that has no file extension.
457 bool hasExt = filename.contains('.');
459 filename = saver.save(filename + ".lib");
460 StringRef ret = doFindFile(filename);
461 // For MinGW, if the find above didn't turn up anything, try
462 // looking for a MinGW formatted library name.
463 if (config->mingw && ret == filename)
464 return doFindLibMinGW(filename);
468 // Resolves a library path. /nodefaultlib options are taken into
469 // consideration. This never returns the same path (in that case,
471 Optional<StringRef> LinkerDriver::findLib(StringRef filename) {
472 if (config->noDefaultLibAll)
474 if (!visitedLibs.insert(filename.lower()).second)
477 StringRef path = doFindLib(filename);
478 if (config->noDefaultLibs.count(path.lower()))
481 if (Optional<sys::fs::UniqueID> id = getUniqueID(path))
482 if (!visitedFiles.insert(*id).second)
487 // Parses LIB environment which contains a list of search paths.
488 void LinkerDriver::addLibSearchPaths() {
489 Optional<std::string> envOpt = Process::GetEnv("LIB");
490 if (!envOpt.hasValue())
492 StringRef env = saver.save(*envOpt);
493 while (!env.empty()) {
495 std::tie(path, env) = env.split(';');
496 searchPaths.push_back(path);
500 Symbol *LinkerDriver::addUndefined(StringRef name) {
501 Symbol *b = symtab->addUndefined(name);
504 config->gcroot.push_back(b);
509 StringRef LinkerDriver::mangleMaybe(Symbol *s) {
510 // If the plain symbol name has already been resolved, do nothing.
511 Undefined *unmangled = dyn_cast<Undefined>(s);
515 // Otherwise, see if a similar, mangled symbol exists in the symbol table.
516 Symbol *mangled = symtab->findMangle(unmangled->getName());
520 // If we find a similar mangled symbol, make this an alias to it and return
522 log(unmangled->getName() + " aliased to " + mangled->getName());
523 unmangled->weakAlias = symtab->addUndefined(mangled->getName());
524 return mangled->getName();
527 // Windows specific -- find default entry point name.
529 // There are four different entry point functions for Windows executables,
530 // each of which corresponds to a user-defined "main" function. This function
531 // infers an entry point from a user-defined "main" function.
532 StringRef LinkerDriver::findDefaultEntry() {
533 assert(config->subsystem != IMAGE_SUBSYSTEM_UNKNOWN &&
534 "must handle /subsystem before calling this");
537 return mangle(config->subsystem == IMAGE_SUBSYSTEM_WINDOWS_GUI
538 ? "WinMainCRTStartup"
541 if (config->subsystem == IMAGE_SUBSYSTEM_WINDOWS_GUI) {
542 if (findUnderscoreMangle("wWinMain")) {
543 if (!findUnderscoreMangle("WinMain"))
544 return mangle("wWinMainCRTStartup");
545 warn("found both wWinMain and WinMain; using latter");
547 return mangle("WinMainCRTStartup");
549 if (findUnderscoreMangle("wmain")) {
550 if (!findUnderscoreMangle("main"))
551 return mangle("wmainCRTStartup");
552 warn("found both wmain and main; using latter");
554 return mangle("mainCRTStartup");
557 WindowsSubsystem LinkerDriver::inferSubsystem() {
559 return IMAGE_SUBSYSTEM_WINDOWS_GUI;
561 return IMAGE_SUBSYSTEM_WINDOWS_CUI;
562 // Note that link.exe infers the subsystem from the presence of these
563 // functions even if /entry: or /nodefaultlib are passed which causes them
565 bool haveMain = findUnderscoreMangle("main");
566 bool haveWMain = findUnderscoreMangle("wmain");
567 bool haveWinMain = findUnderscoreMangle("WinMain");
568 bool haveWWinMain = findUnderscoreMangle("wWinMain");
569 if (haveMain || haveWMain) {
570 if (haveWinMain || haveWWinMain) {
571 warn(std::string("found ") + (haveMain ? "main" : "wmain") + " and " +
572 (haveWinMain ? "WinMain" : "wWinMain") +
573 "; defaulting to /subsystem:console");
575 return IMAGE_SUBSYSTEM_WINDOWS_CUI;
577 if (haveWinMain || haveWWinMain)
578 return IMAGE_SUBSYSTEM_WINDOWS_GUI;
579 return IMAGE_SUBSYSTEM_UNKNOWN;
582 static uint64_t getDefaultImageBase() {
584 return config->dll ? 0x180000000 : 0x140000000;
585 return config->dll ? 0x10000000 : 0x400000;
588 static std::string createResponseFile(const opt::InputArgList &args,
589 ArrayRef<StringRef> filePaths,
590 ArrayRef<StringRef> searchPaths) {
592 raw_svector_ostream os(data);
594 for (auto *arg : args) {
595 switch (arg->getOption().getID()) {
601 case OPT_manifest_colon:
602 case OPT_manifestdependency:
603 case OPT_manifestfile:
604 case OPT_manifestinput:
605 case OPT_manifestuac:
610 os << arg->getSpelling() << sys::path::filename(arg->getValue()) << "\n";
613 os << toString(*arg) << "\n";
617 for (StringRef path : searchPaths) {
618 std::string relPath = relativeToRoot(path);
619 os << "/libpath:" << quote(relPath) << "\n";
622 for (StringRef path : filePaths)
623 os << quote(relativeToRoot(path)) << "\n";
628 enum class DebugKind { Unknown, None, Full, FastLink, GHash, Dwarf, Symtab };
630 static DebugKind parseDebugKind(const opt::InputArgList &args) {
631 auto *a = args.getLastArg(OPT_debug, OPT_debug_opt);
633 return DebugKind::None;
634 if (a->getNumValues() == 0)
635 return DebugKind::Full;
637 DebugKind debug = StringSwitch<DebugKind>(a->getValue())
638 .CaseLower("none", DebugKind::None)
639 .CaseLower("full", DebugKind::Full)
640 .CaseLower("fastlink", DebugKind::FastLink)
642 .CaseLower("ghash", DebugKind::GHash)
643 .CaseLower("dwarf", DebugKind::Dwarf)
644 .CaseLower("symtab", DebugKind::Symtab)
645 .Default(DebugKind::Unknown);
647 if (debug == DebugKind::FastLink) {
648 warn("/debug:fastlink unsupported; using /debug:full");
649 return DebugKind::Full;
651 if (debug == DebugKind::Unknown) {
652 error("/debug: unknown option: " + Twine(a->getValue()));
653 return DebugKind::None;
658 static unsigned parseDebugTypes(const opt::InputArgList &args) {
659 unsigned debugTypes = static_cast<unsigned>(DebugType::None);
661 if (auto *a = args.getLastArg(OPT_debugtype)) {
662 SmallVector<StringRef, 3> types;
663 StringRef(a->getValue())
664 .split(types, ',', /*MaxSplit=*/-1, /*KeepEmpty=*/false);
666 for (StringRef type : types) {
667 unsigned v = StringSwitch<unsigned>(type.lower())
668 .Case("cv", static_cast<unsigned>(DebugType::CV))
669 .Case("pdata", static_cast<unsigned>(DebugType::PData))
670 .Case("fixup", static_cast<unsigned>(DebugType::Fixup))
673 warn("/debugtype: unknown option '" + type + "'");
681 // Default debug types
682 debugTypes = static_cast<unsigned>(DebugType::CV);
683 if (args.hasArg(OPT_driver))
684 debugTypes |= static_cast<unsigned>(DebugType::PData);
685 if (args.hasArg(OPT_profile))
686 debugTypes |= static_cast<unsigned>(DebugType::Fixup);
691 static std::string getMapFile(const opt::InputArgList &args) {
692 auto *arg = args.getLastArg(OPT_lldmap, OPT_lldmap_file);
695 if (arg->getOption().getID() == OPT_lldmap_file)
696 return arg->getValue();
698 assert(arg->getOption().getID() == OPT_lldmap);
699 StringRef outFile = config->outputFile;
700 return (outFile.substr(0, outFile.rfind('.')) + ".map").str();
703 static std::string getImplibPath() {
704 if (!config->implib.empty())
705 return config->implib;
706 SmallString<128> out = StringRef(config->outputFile);
707 sys::path::replace_extension(out, ".lib");
712 // The import name is caculated as the following:
714 // | LIBRARY w/ ext | LIBRARY w/o ext | no LIBRARY
715 // -----+----------------+---------------------+------------------
716 // LINK | {value} | {value}.{.dll/.exe} | {output name}
717 // LIB | {value} | {value}.dll | {output name}.dll
719 static std::string getImportName(bool asLib) {
720 SmallString<128> out;
722 if (config->importName.empty()) {
723 out.assign(sys::path::filename(config->outputFile));
725 sys::path::replace_extension(out, ".dll");
727 out.assign(config->importName);
728 if (!sys::path::has_extension(out))
729 sys::path::replace_extension(out,
730 (config->dll || asLib) ? ".dll" : ".exe");
736 static void createImportLibrary(bool asLib) {
737 std::vector<COFFShortExport> exports;
738 for (Export &e1 : config->exports) {
741 e2.SymbolName = e1.symbolName;
742 e2.ExtName = e1.extName;
743 e2.Ordinal = e1.ordinal;
744 e2.Noname = e1.noname;
746 e2.Private = e1.isPrivate;
747 e2.Constant = e1.constant;
748 exports.push_back(e2);
751 auto handleError = [](Error &&e) {
752 handleAllErrors(std::move(e),
753 [](ErrorInfoBase &eib) { error(eib.message()); });
755 std::string libName = getImportName(asLib);
756 std::string path = getImplibPath();
758 if (!config->incremental) {
759 handleError(writeImportLibrary(libName, path, exports, config->machine,
764 // If the import library already exists, replace it only if the contents
766 ErrorOr<std::unique_ptr<MemoryBuffer>> oldBuf = MemoryBuffer::getFile(
767 path, /*FileSize*/ -1, /*RequiresNullTerminator*/ false);
769 handleError(writeImportLibrary(libName, path, exports, config->machine,
774 SmallString<128> tmpName;
775 if (std::error_code ec =
776 sys::fs::createUniqueFile(path + ".tmp-%%%%%%%%.lib", tmpName))
777 fatal("cannot create temporary file for import library " + path + ": " +
780 if (Error e = writeImportLibrary(libName, tmpName, exports, config->machine,
782 handleError(std::move(e));
786 std::unique_ptr<MemoryBuffer> newBuf = check(MemoryBuffer::getFile(
787 tmpName, /*FileSize*/ -1, /*RequiresNullTerminator*/ false));
788 if ((*oldBuf)->getBuffer() != newBuf->getBuffer()) {
790 handleError(errorCodeToError(sys::fs::rename(tmpName, path)));
792 sys::fs::remove(tmpName);
796 static void parseModuleDefs(StringRef path) {
797 std::unique_ptr<MemoryBuffer> mb = CHECK(
798 MemoryBuffer::getFile(path, -1, false, true), "could not open " + path);
799 COFFModuleDefinition m = check(parseCOFFModuleDefinition(
800 mb->getMemBufferRef(), config->machine, config->mingw));
802 if (config->outputFile.empty())
803 config->outputFile = saver.save(m.OutputFile);
804 config->importName = saver.save(m.ImportName);
806 config->imageBase = m.ImageBase;
808 config->stackReserve = m.StackReserve;
810 config->stackCommit = m.StackCommit;
812 config->heapReserve = m.HeapReserve;
814 config->heapCommit = m.HeapCommit;
815 if (m.MajorImageVersion)
816 config->majorImageVersion = m.MajorImageVersion;
817 if (m.MinorImageVersion)
818 config->minorImageVersion = m.MinorImageVersion;
819 if (m.MajorOSVersion)
820 config->majorOSVersion = m.MajorOSVersion;
821 if (m.MinorOSVersion)
822 config->minorOSVersion = m.MinorOSVersion;
824 for (COFFShortExport e1 : m.Exports) {
826 // In simple cases, only Name is set. Renamed exports are parsed
827 // and set as "ExtName = Name". If Name has the form "OtherDll.Func",
828 // it shouldn't be a normal exported function but a forward to another
829 // DLL instead. This is supported by both MS and GNU linkers.
830 if (e1.ExtName != e1.Name && StringRef(e1.Name).contains('.')) {
831 e2.name = saver.save(e1.ExtName);
832 e2.forwardTo = saver.save(e1.Name);
833 config->exports.push_back(e2);
836 e2.name = saver.save(e1.Name);
837 e2.extName = saver.save(e1.ExtName);
838 e2.ordinal = e1.Ordinal;
839 e2.noname = e1.Noname;
841 e2.isPrivate = e1.Private;
842 e2.constant = e1.Constant;
843 config->exports.push_back(e2);
847 void LinkerDriver::enqueueTask(std::function<void()> task) {
848 taskQueue.push_back(std::move(task));
851 bool LinkerDriver::run() {
852 ScopedTimer t(inputFileTimer);
854 bool didWork = !taskQueue.empty();
855 while (!taskQueue.empty()) {
857 taskQueue.pop_front();
862 // Parse an /order file. If an option is given, the linker places
863 // COMDAT sections in the same order as their names appear in the
865 static void parseOrderFile(StringRef arg) {
866 // For some reason, the MSVC linker requires a filename to be
868 if (!arg.startswith("@")) {
869 error("malformed /order option: '@' missing");
873 // Get a list of all comdat sections for error checking.
874 DenseSet<StringRef> set;
875 for (Chunk *c : symtab->getChunks())
876 if (auto *sec = dyn_cast<SectionChunk>(c))
878 set.insert(sec->sym->getName());
881 StringRef path = arg.substr(1);
882 std::unique_ptr<MemoryBuffer> mb = CHECK(
883 MemoryBuffer::getFile(path, -1, false, true), "could not open " + path);
885 // Parse a file. An order file contains one symbol per line.
886 // All symbols that were not present in a given order file are
887 // considered to have the lowest priority 0 and are placed at
888 // end of an output section.
889 for (std::string s : args::getLines(mb->getMemBufferRef())) {
890 if (config->machine == I386 && !isDecorated(s))
893 if (set.count(s) == 0) {
894 if (config->warnMissingOrderSymbol)
895 warn("/order:" + arg + ": missing symbol: " + s + " [LNK4037]");
898 config->order[s] = INT_MIN + config->order.size();
902 static void markAddrsig(Symbol *s) {
903 if (auto *d = dyn_cast_or_null<Defined>(s))
904 if (SectionChunk *c = dyn_cast_or_null<SectionChunk>(d->getChunk()))
905 c->keepUnique = true;
908 static void findKeepUniqueSections() {
909 // Exported symbols could be address-significant in other executables or DSOs,
910 // so we conservatively mark them as address-significant.
911 for (Export &r : config->exports)
914 // Visit the address-significance table in each object file and mark each
915 // referenced symbol as address-significant.
916 for (ObjFile *obj : ObjFile::instances) {
917 ArrayRef<Symbol *> syms = obj->getSymbols();
918 if (obj->addrsigSec) {
919 ArrayRef<uint8_t> contents;
921 obj->getCOFFObj()->getSectionContents(obj->addrsigSec, contents));
922 const uint8_t *cur = contents.begin();
923 while (cur != contents.end()) {
926 uint64_t symIndex = decodeULEB128(cur, &size, contents.end(), &err);
928 fatal(toString(obj) + ": could not decode addrsig section: " + err);
929 if (symIndex >= syms.size())
930 fatal(toString(obj) + ": invalid symbol index in addrsig section");
931 markAddrsig(syms[symIndex]);
935 // If an object file does not have an address-significance table,
936 // conservatively mark all of its symbols as address-significant.
937 for (Symbol *s : syms)
943 // link.exe replaces each %foo% in altPath with the contents of environment
944 // variable foo, and adds the two magic env vars _PDB (expands to the basename
945 // of pdb's output path) and _EXT (expands to the extension of the output
947 // lld only supports %_PDB% and %_EXT% and warns on references to all other env
949 static void parsePDBAltPath(StringRef altPath) {
950 SmallString<128> buf;
951 StringRef pdbBasename =
952 sys::path::filename(config->pdbPath, sys::path::Style::windows);
953 StringRef binaryExtension =
954 sys::path::extension(config->outputFile, sys::path::Style::windows);
955 if (!binaryExtension.empty())
956 binaryExtension = binaryExtension.substr(1); // %_EXT% does not include '.'.
959 // +--------- cursor ('a...' might be the empty string).
960 // | +----- firstMark
965 while (cursor < altPath.size()) {
966 size_t firstMark, secondMark;
967 if ((firstMark = altPath.find('%', cursor)) == StringRef::npos ||
968 (secondMark = altPath.find('%', firstMark + 1)) == StringRef::npos) {
969 // Didn't find another full fragment, treat rest of string as literal.
970 buf.append(altPath.substr(cursor));
974 // Found a full fragment. Append text in front of first %, and interpret
975 // text between first and second % as variable name.
976 buf.append(altPath.substr(cursor, firstMark - cursor));
977 StringRef var = altPath.substr(firstMark, secondMark - firstMark + 1);
978 if (var.equals_lower("%_pdb%"))
979 buf.append(pdbBasename);
980 else if (var.equals_lower("%_ext%"))
981 buf.append(binaryExtension);
983 warn("only %_PDB% and %_EXT% supported in /pdbaltpath:, keeping " +
984 var + " as literal");
988 cursor = secondMark + 1;
991 config->pdbAltPath = buf;
994 /// Check that at most one resource obj file was used.
995 /// Call after ObjFile::Instances is complete.
996 static void diagnoseMultipleResourceObjFiles() {
997 // The .rsrc$01 section in a resource obj file contains a tree description
998 // of resources. Merging multiple resource obj files would require merging
999 // the trees instead of using usual linker section merging semantics.
1000 // Since link.exe disallows linking more than one resource obj file with
1001 // LNK4078, mirror that. The normal use of resource files is to give the
1002 // linker many .res files, which are then converted to a single resource obj
1003 // file internally, so this is not a big restriction in practice.
1004 ObjFile *resourceObjFile = nullptr;
1005 for (ObjFile *f : ObjFile::instances) {
1006 if (!f->isResourceObjFile)
1009 if (!resourceObjFile) {
1010 resourceObjFile = f;
1015 ": more than one resource obj file not allowed, already got " +
1016 toString(resourceObjFile));
1020 // In MinGW, if no symbols are chosen to be exported, then all symbols are
1021 // automatically exported by default. This behavior can be forced by the
1022 // -export-all-symbols option, so that it happens even when exports are
1023 // explicitly specified. The automatic behavior can be disabled using the
1024 // -exclude-all-symbols option, so that lld-link behaves like link.exe rather
1025 // than MinGW in the case that nothing is explicitly exported.
1026 void LinkerDriver::maybeExportMinGWSymbols(const opt::InputArgList &args) {
1030 if (!args.hasArg(OPT_export_all_symbols)) {
1031 if (!config->exports.empty())
1033 if (args.hasArg(OPT_exclude_all_symbols))
1037 AutoExporter exporter;
1039 for (auto *arg : args.filtered(OPT_wholearchive_file))
1040 if (Optional<StringRef> path = doFindFile(arg->getValue()))
1041 exporter.addWholeArchive(*path);
1043 symtab->forEachSymbol([&](Symbol *s) {
1044 auto *def = dyn_cast<Defined>(s);
1045 if (!exporter.shouldExport(def))
1049 e.name = def->getName();
1051 if (Chunk *c = def->getChunk())
1052 if (!(c->getOutputCharacteristics() & IMAGE_SCN_MEM_EXECUTE))
1054 config->exports.push_back(e);
1058 static const char *libcallRoutineNames[] = {
1059 #define HANDLE_LIBCALL(code, name) name,
1060 #include "llvm/IR/RuntimeLibcalls.def"
1061 #undef HANDLE_LIBCALL
1064 void LinkerDriver::link(ArrayRef<const char *> argsArr) {
1066 InitializeAllTargetInfos();
1067 InitializeAllTargets();
1068 InitializeAllTargetMCs();
1069 InitializeAllAsmParsers();
1070 InitializeAllAsmPrinters();
1072 // If the first command line argument is "/lib", link.exe acts like lib.exe.
1073 // We call our own implementation of lib.exe that understands bitcode files.
1074 if (argsArr.size() > 1 && StringRef(argsArr[1]).equals_lower("/lib")) {
1075 if (llvm::libDriverMain(argsArr.slice(1)) != 0)
1076 fatal("lib failed");
1080 // Parse command line options.
1082 opt::InputArgList args = parser.parseLINK(argsArr);
1084 // Parse and evaluate -mllvm options.
1085 std::vector<const char *> v;
1086 v.push_back("lld-link (LLVM option parsing)");
1087 for (auto *arg : args.filtered(OPT_mllvm))
1088 v.push_back(arg->getValue());
1089 cl::ParseCommandLineOptions(v.size(), v.data());
1091 // Handle /errorlimit early, because error() depends on it.
1092 if (auto *arg = args.getLastArg(OPT_errorlimit)) {
1094 StringRef s = arg->getValue();
1095 if (s.getAsInteger(10, n))
1096 error(arg->getSpelling() + " number expected, but got " + s);
1097 errorHandler().errorLimit = n;
1101 if (args.hasArg(OPT_help)) {
1102 printHelp(argsArr[0]);
1106 lld::threadsEnabled = args.hasFlag(OPT_threads, OPT_threads_no, true);
1108 if (args.hasArg(OPT_show_timing))
1109 config->showTiming = true;
1111 config->showSummary = args.hasArg(OPT_summary);
1113 ScopedTimer t(Timer::root());
1114 // Handle --version, which is an lld extension. This option is a bit odd
1115 // because it doesn't start with "/", but we deliberately chose "--" to
1116 // avoid conflict with /version and for compatibility with clang-cl.
1117 if (args.hasArg(OPT_dash_dash_version)) {
1118 outs() << getLLDVersion() << "\n";
1122 // Handle /lldmingw early, since it can potentially affect how other
1123 // options are handled.
1124 config->mingw = args.hasArg(OPT_lldmingw);
1126 if (auto *arg = args.getLastArg(OPT_linkrepro)) {
1127 SmallString<64> path = StringRef(arg->getValue());
1128 sys::path::append(path, "repro.tar");
1130 Expected<std::unique_ptr<TarWriter>> errOrWriter =
1131 TarWriter::create(path, "repro");
1134 tar = std::move(*errOrWriter);
1136 error("/linkrepro: failed to open " + path + ": " +
1137 toString(errOrWriter.takeError()));
1141 if (!args.hasArg(OPT_INPUT)) {
1142 if (args.hasArg(OPT_deffile))
1143 config->noEntry = true;
1145 fatal("no input files");
1148 // Construct search path list.
1149 searchPaths.push_back("");
1150 for (auto *arg : args.filtered(OPT_libpath))
1151 searchPaths.push_back(arg->getValue());
1152 addLibSearchPaths();
1155 for (auto *arg : args.filtered(OPT_ignore)) {
1156 SmallVector<StringRef, 8> vec;
1157 StringRef(arg->getValue()).split(vec, ',');
1158 for (StringRef s : vec) {
1160 config->warnMissingOrderSymbol = false;
1161 else if (s == "4099")
1162 config->warnDebugInfoUnusable = false;
1163 else if (s == "4217")
1164 config->warnLocallyDefinedImported = false;
1165 // Other warning numbers are ignored.
1170 if (auto *arg = args.getLastArg(OPT_out))
1171 config->outputFile = arg->getValue();
1174 if (args.hasArg(OPT_verbose))
1175 config->verbose = true;
1176 errorHandler().verbose = config->verbose;
1178 // Handle /force or /force:unresolved
1179 if (args.hasArg(OPT_force, OPT_force_unresolved))
1180 config->forceUnresolved = true;
1182 // Handle /force or /force:multiple
1183 if (args.hasArg(OPT_force, OPT_force_multiple))
1184 config->forceMultiple = true;
1186 // Handle /force or /force:multipleres
1187 if (args.hasArg(OPT_force, OPT_force_multipleres))
1188 config->forceMultipleRes = true;
1191 DebugKind debug = parseDebugKind(args);
1192 if (debug == DebugKind::Full || debug == DebugKind::Dwarf ||
1193 debug == DebugKind::GHash) {
1194 config->debug = true;
1195 config->incremental = true;
1199 config->demangle = args.hasFlag(OPT_demangle, OPT_demangle_no);
1201 // Handle /debugtype
1202 config->debugTypes = parseDebugTypes(args);
1205 bool shouldCreatePDB =
1206 (debug == DebugKind::Full || debug == DebugKind::GHash);
1207 if (shouldCreatePDB) {
1208 if (auto *arg = args.getLastArg(OPT_pdb))
1209 config->pdbPath = arg->getValue();
1210 if (auto *arg = args.getLastArg(OPT_pdbaltpath))
1211 config->pdbAltPath = arg->getValue();
1212 if (args.hasArg(OPT_natvis))
1213 config->natvisFiles = args.getAllArgValues(OPT_natvis);
1215 if (auto *arg = args.getLastArg(OPT_pdb_source_path))
1216 config->pdbSourcePath = arg->getValue();
1220 if (args.hasArg(OPT_noentry)) {
1221 if (args.hasArg(OPT_dll))
1222 config->noEntry = true;
1224 error("/noentry must be specified with /dll");
1228 if (args.hasArg(OPT_dll)) {
1230 config->manifestID = 2;
1233 // Handle /dynamicbase and /fixed. We can't use hasFlag for /dynamicbase
1234 // because we need to explicitly check whether that option or its inverse was
1235 // present in the argument list in order to handle /fixed.
1236 auto *dynamicBaseArg = args.getLastArg(OPT_dynamicbase, OPT_dynamicbase_no);
1237 if (dynamicBaseArg &&
1238 dynamicBaseArg->getOption().getID() == OPT_dynamicbase_no)
1239 config->dynamicBase = false;
1241 // MSDN claims "/FIXED:NO is the default setting for a DLL, and /FIXED is the
1242 // default setting for any other project type.", but link.exe defaults to
1243 // /FIXED:NO for exe outputs as well. Match behavior, not docs.
1244 bool fixed = args.hasFlag(OPT_fixed, OPT_fixed_no, false);
1246 if (dynamicBaseArg &&
1247 dynamicBaseArg->getOption().getID() == OPT_dynamicbase) {
1248 error("/fixed must not be specified with /dynamicbase");
1250 config->relocatable = false;
1251 config->dynamicBase = false;
1255 // Handle /appcontainer
1256 config->appContainer =
1257 args.hasFlag(OPT_appcontainer, OPT_appcontainer_no, false);
1260 if (auto *arg = args.getLastArg(OPT_machine)) {
1261 config->machine = getMachineType(arg->getValue());
1262 if (config->machine == IMAGE_FILE_MACHINE_UNKNOWN)
1263 fatal(Twine("unknown /machine argument: ") + arg->getValue());
1266 // Handle /nodefaultlib:<filename>
1267 for (auto *arg : args.filtered(OPT_nodefaultlib))
1268 config->noDefaultLibs.insert(doFindLib(arg->getValue()).lower());
1270 // Handle /nodefaultlib
1271 if (args.hasArg(OPT_nodefaultlib_all))
1272 config->noDefaultLibAll = true;
1275 if (auto *arg = args.getLastArg(OPT_base))
1276 parseNumbers(arg->getValue(), &config->imageBase);
1278 // Handle /filealign
1279 if (auto *arg = args.getLastArg(OPT_filealign)) {
1280 parseNumbers(arg->getValue(), &config->fileAlign);
1281 if (!isPowerOf2_64(config->fileAlign))
1282 error("/filealign: not a power of two: " + Twine(config->fileAlign));
1286 if (auto *arg = args.getLastArg(OPT_stack))
1287 parseNumbers(arg->getValue(), &config->stackReserve, &config->stackCommit);
1290 if (auto *arg = args.getLastArg(OPT_guard))
1291 parseGuard(arg->getValue());
1294 if (auto *arg = args.getLastArg(OPT_heap))
1295 parseNumbers(arg->getValue(), &config->heapReserve, &config->heapCommit);
1298 if (auto *arg = args.getLastArg(OPT_version))
1299 parseVersion(arg->getValue(), &config->majorImageVersion,
1300 &config->minorImageVersion);
1302 // Handle /subsystem
1303 if (auto *arg = args.getLastArg(OPT_subsystem))
1304 parseSubsystem(arg->getValue(), &config->subsystem, &config->majorOSVersion,
1305 &config->minorOSVersion);
1307 // Handle /timestamp
1308 if (llvm::opt::Arg *arg = args.getLastArg(OPT_timestamp, OPT_repro)) {
1309 if (arg->getOption().getID() == OPT_repro) {
1310 config->timestamp = 0;
1311 config->repro = true;
1313 config->repro = false;
1314 StringRef value(arg->getValue());
1315 if (value.getAsInteger(0, config->timestamp))
1316 fatal(Twine("invalid timestamp: ") + value +
1317 ". Expected 32-bit integer");
1320 config->repro = false;
1321 config->timestamp = time(nullptr);
1324 // Handle /alternatename
1325 for (auto *arg : args.filtered(OPT_alternatename))
1326 parseAlternateName(arg->getValue());
1329 for (auto *arg : args.filtered(OPT_incl))
1330 addUndefined(arg->getValue());
1333 if (auto *arg = args.getLastArg(OPT_implib))
1334 config->implib = arg->getValue();
1337 bool doGC = debug == DebugKind::None || args.hasArg(OPT_profile);
1339 args.hasArg(OPT_profile) ? 0 : 1; // 0: off, 1: limited, 2: on
1340 unsigned tailMerge = 1;
1341 for (auto *arg : args.filtered(OPT_opt)) {
1342 std::string str = StringRef(arg->getValue()).lower();
1343 SmallVector<StringRef, 1> vec;
1344 StringRef(str).split(vec, ',');
1345 for (StringRef s : vec) {
1348 } else if (s == "noref") {
1350 } else if (s == "icf" || s.startswith("icf=")) {
1352 } else if (s == "noicf") {
1354 } else if (s == "lldtailmerge") {
1356 } else if (s == "nolldtailmerge") {
1358 } else if (s.startswith("lldlto=")) {
1359 StringRef optLevel = s.substr(7);
1360 if (optLevel.getAsInteger(10, config->ltoo) || config->ltoo > 3)
1361 error("/opt:lldlto: invalid optimization level: " + optLevel);
1362 } else if (s.startswith("lldltojobs=")) {
1363 StringRef jobs = s.substr(11);
1364 if (jobs.getAsInteger(10, config->thinLTOJobs) ||
1365 config->thinLTOJobs == 0)
1366 error("/opt:lldltojobs: invalid job count: " + jobs);
1367 } else if (s.startswith("lldltopartitions=")) {
1368 StringRef n = s.substr(17);
1369 if (n.getAsInteger(10, config->ltoPartitions) ||
1370 config->ltoPartitions == 0)
1371 error("/opt:lldltopartitions: invalid partition count: " + n);
1372 } else if (s != "lbr" && s != "nolbr")
1373 error("/opt: unknown option: " + s);
1377 // Limited ICF is enabled if GC is enabled and ICF was never mentioned
1379 // FIXME: LLD only implements "limited" ICF, i.e. it only merges identical
1380 // code. If the user passes /OPT:ICF explicitly, LLD should merge identical
1381 // comdat readonly data.
1382 if (icfLevel == 1 && !doGC)
1384 config->doGC = doGC;
1385 config->doICF = icfLevel > 0;
1386 config->tailMerge = (tailMerge == 1 && config->doICF) || tailMerge == 2;
1388 // Handle /lldsavetemps
1389 if (args.hasArg(OPT_lldsavetemps))
1390 config->saveTemps = true;
1393 if (args.hasArg(OPT_kill_at))
1394 config->killAt = true;
1396 // Handle /lldltocache
1397 if (auto *arg = args.getLastArg(OPT_lldltocache))
1398 config->ltoCache = arg->getValue();
1400 // Handle /lldsavecachepolicy
1401 if (auto *arg = args.getLastArg(OPT_lldltocachepolicy))
1402 config->ltoCachePolicy = CHECK(
1403 parseCachePruningPolicy(arg->getValue()),
1404 Twine("/lldltocachepolicy: invalid cache policy: ") + arg->getValue());
1406 // Handle /failifmismatch
1407 for (auto *arg : args.filtered(OPT_failifmismatch))
1408 checkFailIfMismatch(arg->getValue(), nullptr);
1411 for (auto *arg : args.filtered(OPT_merge))
1412 parseMerge(arg->getValue());
1414 // Add default section merging rules after user rules. User rules take
1415 // precedence, but we will emit a warning if there is a conflict.
1416 parseMerge(".idata=.rdata");
1417 parseMerge(".didat=.rdata");
1418 parseMerge(".edata=.rdata");
1419 parseMerge(".xdata=.rdata");
1420 parseMerge(".bss=.data");
1422 if (config->mingw) {
1423 parseMerge(".ctors=.rdata");
1424 parseMerge(".dtors=.rdata");
1425 parseMerge(".CRT=.rdata");
1429 for (auto *arg : args.filtered(OPT_section))
1430 parseSection(arg->getValue());
1433 if (auto *arg = args.getLastArg(OPT_align)) {
1434 parseNumbers(arg->getValue(), &config->align);
1435 if (!isPowerOf2_64(config->align))
1436 error("/align: not a power of two: " + StringRef(arg->getValue()));
1439 // Handle /aligncomm
1440 for (auto *arg : args.filtered(OPT_aligncomm))
1441 parseAligncomm(arg->getValue());
1443 // Handle /manifestdependency. This enables /manifest unless /manifest:no is
1445 if (auto *arg = args.getLastArg(OPT_manifestdependency)) {
1446 config->manifestDependency = arg->getValue();
1447 config->manifest = Configuration::SideBySide;
1450 // Handle /manifest and /manifest:
1451 if (auto *arg = args.getLastArg(OPT_manifest, OPT_manifest_colon)) {
1452 if (arg->getOption().getID() == OPT_manifest)
1453 config->manifest = Configuration::SideBySide;
1455 parseManifest(arg->getValue());
1458 // Handle /manifestuac
1459 if (auto *arg = args.getLastArg(OPT_manifestuac))
1460 parseManifestUAC(arg->getValue());
1462 // Handle /manifestfile
1463 if (auto *arg = args.getLastArg(OPT_manifestfile))
1464 config->manifestFile = arg->getValue();
1466 // Handle /manifestinput
1467 for (auto *arg : args.filtered(OPT_manifestinput))
1468 config->manifestInput.push_back(arg->getValue());
1470 if (!config->manifestInput.empty() &&
1471 config->manifest != Configuration::Embed) {
1472 fatal("/manifestinput: requires /manifest:embed");
1475 config->thinLTOEmitImportsFiles = args.hasArg(OPT_thinlto_emit_imports_files);
1476 config->thinLTOIndexOnly = args.hasArg(OPT_thinlto_index_only) ||
1477 args.hasArg(OPT_thinlto_index_only_arg);
1478 config->thinLTOIndexOnlyArg =
1479 args.getLastArgValue(OPT_thinlto_index_only_arg);
1480 config->thinLTOPrefixReplace =
1481 getOldNewOptions(args, OPT_thinlto_prefix_replace);
1482 config->thinLTOObjectSuffixReplace =
1483 getOldNewOptions(args, OPT_thinlto_object_suffix_replace);
1484 // Handle miscellaneous boolean flags.
1485 config->allowBind = args.hasFlag(OPT_allowbind, OPT_allowbind_no, true);
1486 config->allowIsolation =
1487 args.hasFlag(OPT_allowisolation, OPT_allowisolation_no, true);
1488 config->incremental =
1489 args.hasFlag(OPT_incremental, OPT_incremental_no,
1490 !config->doGC && !config->doICF && !args.hasArg(OPT_order) &&
1491 !args.hasArg(OPT_profile));
1492 config->integrityCheck =
1493 args.hasFlag(OPT_integritycheck, OPT_integritycheck_no, false);
1494 config->nxCompat = args.hasFlag(OPT_nxcompat, OPT_nxcompat_no, true);
1495 for (auto *arg : args.filtered(OPT_swaprun))
1496 parseSwaprun(arg->getValue());
1497 config->terminalServerAware =
1498 !config->dll && args.hasFlag(OPT_tsaware, OPT_tsaware_no, true);
1499 config->debugDwarf = debug == DebugKind::Dwarf;
1500 config->debugGHashes = debug == DebugKind::GHash;
1501 config->debugSymtab = debug == DebugKind::Symtab;
1503 config->mapFile = getMapFile(args);
1505 if (config->incremental && args.hasArg(OPT_profile)) {
1506 warn("ignoring '/incremental' due to '/profile' specification");
1507 config->incremental = false;
1510 if (config->incremental && args.hasArg(OPT_order)) {
1511 warn("ignoring '/incremental' due to '/order' specification");
1512 config->incremental = false;
1515 if (config->incremental && config->doGC) {
1516 warn("ignoring '/incremental' because REF is enabled; use '/opt:noref' to "
1518 config->incremental = false;
1521 if (config->incremental && config->doICF) {
1522 warn("ignoring '/incremental' because ICF is enabled; use '/opt:noicf' to "
1524 config->incremental = false;
1530 std::set<sys::fs::UniqueID> wholeArchives;
1531 for (auto *arg : args.filtered(OPT_wholearchive_file))
1532 if (Optional<StringRef> path = doFindFile(arg->getValue()))
1533 if (Optional<sys::fs::UniqueID> id = getUniqueID(*path))
1534 wholeArchives.insert(*id);
1536 // A predicate returning true if a given path is an argument for
1537 // /wholearchive:, or /wholearchive is enabled globally.
1538 // This function is a bit tricky because "foo.obj /wholearchive:././foo.obj"
1539 // needs to be handled as "/wholearchive:foo.obj foo.obj".
1540 auto isWholeArchive = [&](StringRef path) -> bool {
1541 if (args.hasArg(OPT_wholearchive_flag))
1543 if (Optional<sys::fs::UniqueID> id = getUniqueID(path))
1544 return wholeArchives.count(*id);
1548 // Create a list of input files. Files can be given as arguments
1549 // for /defaultlib option.
1550 for (auto *arg : args.filtered(OPT_INPUT, OPT_wholearchive_file))
1551 if (Optional<StringRef> path = findFile(arg->getValue()))
1552 enqueuePath(*path, isWholeArchive(*path));
1554 for (auto *arg : args.filtered(OPT_defaultlib))
1555 if (Optional<StringRef> path = findLib(arg->getValue()))
1556 enqueuePath(*path, false);
1558 // Windows specific -- Create a resource file containing a manifest file.
1559 if (config->manifest == Configuration::Embed)
1560 addBuffer(createManifestRes(), false);
1562 // Read all input files given via the command line.
1568 // We should have inferred a machine type by now from the input files, but if
1569 // not we assume x64.
1570 if (config->machine == IMAGE_FILE_MACHINE_UNKNOWN) {
1571 warn("/machine is not specified. x64 is assumed");
1572 config->machine = AMD64;
1574 config->wordsize = config->is64() ? 8 : 4;
1576 // Handle /safeseh, x86 only, on by default, except for mingw.
1577 if (config->machine == I386 &&
1578 args.hasFlag(OPT_safeseh, OPT_safeseh_no, !config->mingw))
1579 config->safeSEH = true;
1581 // Handle /functionpadmin
1582 for (auto *arg : args.filtered(OPT_functionpadmin, OPT_functionpadmin_opt))
1583 parseFunctionPadMin(arg, config->machine);
1585 // Input files can be Windows resource files (.res files). We use
1586 // WindowsResource to convert resource files to a regular COFF file,
1587 // then link the resulting file normally.
1588 if (!resources.empty())
1589 symtab->addFile(make<ObjFile>(convertResToCOFF(resources)));
1592 tar->append("response.txt",
1593 createResponseFile(args, filePaths,
1594 ArrayRef<StringRef>(searchPaths).slice(1)));
1596 // Handle /largeaddressaware
1597 config->largeAddressAware = args.hasFlag(
1598 OPT_largeaddressaware, OPT_largeaddressaware_no, config->is64());
1600 // Handle /highentropyva
1601 config->highEntropyVA =
1603 args.hasFlag(OPT_highentropyva, OPT_highentropyva_no, true);
1605 if (!config->dynamicBase &&
1606 (config->machine == ARMNT || config->machine == ARM64))
1607 error("/dynamicbase:no is not compatible with " +
1608 machineToStr(config->machine));
1611 for (auto *arg : args.filtered(OPT_export)) {
1612 Export e = parseExport(arg->getValue());
1613 if (config->machine == I386) {
1614 if (!isDecorated(e.name))
1615 e.name = saver.save("_" + e.name);
1616 if (!e.extName.empty() && !isDecorated(e.extName))
1617 e.extName = saver.save("_" + e.extName);
1619 config->exports.push_back(e);
1623 if (auto *arg = args.getLastArg(OPT_deffile)) {
1624 // parseModuleDefs mutates Config object.
1625 parseModuleDefs(arg->getValue());
1628 // Handle generation of import library from a def file.
1629 if (!args.hasArg(OPT_INPUT)) {
1631 createImportLibrary(/*asLib=*/true);
1635 // Windows specific -- if no /subsystem is given, we need to infer
1636 // that from entry point name. Must happen before /entry handling,
1637 // and after the early return when just writing an import library.
1638 if (config->subsystem == IMAGE_SUBSYSTEM_UNKNOWN) {
1639 config->subsystem = inferSubsystem();
1640 if (config->subsystem == IMAGE_SUBSYSTEM_UNKNOWN)
1641 fatal("subsystem must be defined");
1644 // Handle /entry and /dll
1645 if (auto *arg = args.getLastArg(OPT_entry)) {
1646 config->entry = addUndefined(mangle(arg->getValue()));
1647 } else if (!config->entry && !config->noEntry) {
1648 if (args.hasArg(OPT_dll)) {
1649 StringRef s = (config->machine == I386) ? "__DllMainCRTStartup@12"
1650 : "_DllMainCRTStartup";
1651 config->entry = addUndefined(s);
1653 // Windows specific -- If entry point name is not given, we need to
1654 // infer that from user-defined entry name.
1655 StringRef s = findDefaultEntry();
1657 fatal("entry point must be defined");
1658 config->entry = addUndefined(s);
1659 log("Entry name inferred: " + s);
1663 // Handle /delayload
1664 for (auto *arg : args.filtered(OPT_delayload)) {
1665 config->delayLoads.insert(StringRef(arg->getValue()).lower());
1666 if (config->machine == I386) {
1667 config->delayLoadHelper = addUndefined("___delayLoadHelper2@8");
1669 config->delayLoadHelper = addUndefined("__delayLoadHelper2");
1673 // Set default image name if neither /out or /def set it.
1674 if (config->outputFile.empty()) {
1675 config->outputFile =
1676 getOutputPath((*args.filtered(OPT_INPUT).begin())->getValue());
1679 // Fail early if an output file is not writable.
1680 if (auto e = tryCreateFile(config->outputFile)) {
1681 error("cannot open output file " + config->outputFile + ": " + e.message());
1685 if (shouldCreatePDB) {
1686 // Put the PDB next to the image if no /pdb flag was passed.
1687 if (config->pdbPath.empty()) {
1688 config->pdbPath = config->outputFile;
1689 sys::path::replace_extension(config->pdbPath, ".pdb");
1692 // The embedded PDB path should be the absolute path to the PDB if no
1693 // /pdbaltpath flag was passed.
1694 if (config->pdbAltPath.empty()) {
1695 config->pdbAltPath = config->pdbPath;
1697 // It's important to make the path absolute and remove dots. This path
1698 // will eventually be written into the PE header, and certain Microsoft
1699 // tools won't work correctly if these assumptions are not held.
1700 sys::fs::make_absolute(config->pdbAltPath);
1701 sys::path::remove_dots(config->pdbAltPath);
1703 // Don't do this earlier, so that Config->OutputFile is ready.
1704 parsePDBAltPath(config->pdbAltPath);
1708 // Set default image base if /base is not given.
1709 if (config->imageBase == uint64_t(-1))
1710 config->imageBase = getDefaultImageBase();
1712 symtab->addSynthetic(mangle("__ImageBase"), nullptr);
1713 if (config->machine == I386) {
1714 symtab->addAbsolute("___safe_se_handler_table", 0);
1715 symtab->addAbsolute("___safe_se_handler_count", 0);
1718 symtab->addAbsolute(mangle("__guard_fids_count"), 0);
1719 symtab->addAbsolute(mangle("__guard_fids_table"), 0);
1720 symtab->addAbsolute(mangle("__guard_flags"), 0);
1721 symtab->addAbsolute(mangle("__guard_iat_count"), 0);
1722 symtab->addAbsolute(mangle("__guard_iat_table"), 0);
1723 symtab->addAbsolute(mangle("__guard_longjmp_count"), 0);
1724 symtab->addAbsolute(mangle("__guard_longjmp_table"), 0);
1725 // Needed for MSVC 2017 15.5 CRT.
1726 symtab->addAbsolute(mangle("__enclave_config"), 0);
1728 if (config->mingw) {
1729 symtab->addAbsolute(mangle("__RUNTIME_PSEUDO_RELOC_LIST__"), 0);
1730 symtab->addAbsolute(mangle("__RUNTIME_PSEUDO_RELOC_LIST_END__"), 0);
1731 symtab->addAbsolute(mangle("__CTOR_LIST__"), 0);
1732 symtab->addAbsolute(mangle("__DTOR_LIST__"), 0);
1735 // This code may add new undefined symbols to the link, which may enqueue more
1736 // symbol resolution tasks, so we need to continue executing tasks until we
1739 // Windows specific -- if entry point is not found,
1740 // search for its mangled names.
1742 mangleMaybe(config->entry);
1744 // Windows specific -- Make sure we resolve all dllexported symbols.
1745 for (Export &e : config->exports) {
1746 if (!e.forwardTo.empty())
1748 e.sym = addUndefined(e.name);
1750 e.symbolName = mangleMaybe(e.sym);
1753 // Add weak aliases. Weak aliases is a mechanism to give remaining
1754 // undefined symbols final chance to be resolved successfully.
1755 for (auto pair : config->alternateNames) {
1756 StringRef from = pair.first;
1757 StringRef to = pair.second;
1758 Symbol *sym = symtab->find(from);
1761 if (auto *u = dyn_cast<Undefined>(sym))
1763 u->weakAlias = symtab->addUndefined(to);
1766 // If any inputs are bitcode files, the LTO code generator may create
1767 // references to library functions that are not explicit in the bitcode
1768 // file's symbol table. If any of those library functions are defined in a
1769 // bitcode file in an archive member, we need to arrange to use LTO to
1770 // compile those archive members by adding them to the link beforehand.
1771 if (!BitcodeFile::instances.empty())
1772 for (const char *s : libcallRoutineNames)
1773 symtab->addLibcall(s);
1775 // Windows specific -- if __load_config_used can be resolved, resolve it.
1776 if (symtab->findUnderscore("_load_config_used"))
1777 addUndefined(mangle("_load_config_used"));
1783 // Do LTO by compiling bitcode input files to a set of native COFF files then
1784 // link those files (unless -thinlto-index-only was given, in which case we
1785 // resolve symbols and write indices, but don't generate native code or link).
1786 symtab->addCombinedLTOObjects();
1788 // If -thinlto-index-only is given, we should create only "index
1789 // files" and not object files. Index file creation is already done
1790 // in addCombinedLTOObject, so we are done if that's the case.
1791 if (config->thinLTOIndexOnly)
1794 // If we generated native object files from bitcode files, this resolves
1795 // references to the symbols we use from them.
1798 if (args.hasArg(OPT_include_optional)) {
1799 // Handle /includeoptional
1800 for (auto *arg : args.filtered(OPT_include_optional))
1801 if (dyn_cast_or_null<Lazy>(symtab->find(arg->getValue())))
1802 addUndefined(arg->getValue());
1806 if (config->mingw) {
1807 // Load any further object files that might be needed for doing automatic
1810 // For cases with no automatically imported symbols, this iterates once
1811 // over the symbol table and doesn't do anything.
1813 // For the normal case with a few automatically imported symbols, this
1814 // should only need to be run once, since each new object file imported
1815 // is an import library and wouldn't add any new undefined references,
1816 // but there's nothing stopping the __imp_ symbols from coming from a
1817 // normal object file as well (although that won't be used for the
1818 // actual autoimport later on). If this pass adds new undefined references,
1819 // we won't iterate further to resolve them.
1820 symtab->loadMinGWAutomaticImports();
1824 // Make sure we have resolved all symbols.
1825 symtab->reportRemainingUndefines();
1829 if (config->mingw) {
1830 // In MinGW, all symbols are automatically exported if no symbols
1831 // are chosen to be exported.
1832 maybeExportMinGWSymbols(args);
1834 // Make sure the crtend.o object is the last object file. This object
1835 // file can contain terminating section chunks that need to be placed
1836 // last. GNU ld processes files and static libraries explicitly in the
1837 // order provided on the command line, while lld will pull in needed
1838 // files from static libraries only after the last object file on the
1840 for (auto i = ObjFile::instances.begin(), e = ObjFile::instances.end();
1843 if (isCrtend(file->getName())) {
1844 ObjFile::instances.erase(i);
1845 ObjFile::instances.push_back(file);
1851 // Windows specific -- when we are creating a .dll file, we also
1852 // need to create a .lib file.
1853 if (!config->exports.empty() || config->dll) {
1855 createImportLibrary(/*asLib=*/false);
1856 assignExportOrdinals();
1859 // Handle /output-def (MinGW specific).
1860 if (auto *arg = args.getLastArg(OPT_output_def))
1861 writeDefFile(arg->getValue());
1863 // Set extra alignment for .comm symbols
1864 for (auto pair : config->alignComm) {
1865 StringRef name = pair.first;
1866 uint32_t alignment = pair.second;
1868 Symbol *sym = symtab->find(name);
1870 warn("/aligncomm symbol " + name + " not found");
1874 // If the symbol isn't common, it must have been replaced with a regular
1875 // symbol, which will carry its own alignment.
1876 auto *dc = dyn_cast<DefinedCommon>(sym);
1880 CommonChunk *c = dc->getChunk();
1881 c->setAlignment(std::max(c->getAlignment(), alignment));
1884 // Windows specific -- Create a side-by-side manifest file.
1885 if (config->manifest == Configuration::SideBySide)
1886 createSideBySideManifest();
1888 // Handle /order. We want to do this at this moment because we
1889 // need a complete list of comdat sections to warn on nonexistent
1891 if (auto *arg = args.getLastArg(OPT_order))
1892 parseOrderFile(arg->getValue());
1894 // Identify unreferenced COMDAT sections.
1896 markLive(symtab->getChunks());
1898 // Needs to happen after the last call to addFile().
1899 diagnoseMultipleResourceObjFiles();
1901 // Identify identical COMDAT sections to merge them.
1902 if (config->doICF) {
1903 findKeepUniqueSections();
1904 doICF(symtab->getChunks());
1907 // Write the result.
1910 // Stop early so we can print the results.
1911 Timer::root().stop();
1912 if (config->showTiming)
1913 Timer::root().print();