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/Timer.h"
25 #include "lld/Common/Version.h"
26 #include "llvm/ADT/Optional.h"
27 #include "llvm/ADT/StringSwitch.h"
28 #include "llvm/BinaryFormat/Magic.h"
29 #include "llvm/LTO/LTO.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/CommandLine.h"
38 #include "llvm/Support/Debug.h"
39 #include "llvm/Support/LEB128.h"
40 #include "llvm/Support/MathExtras.h"
41 #include "llvm/Support/Parallel.h"
42 #include "llvm/Support/Path.h"
43 #include "llvm/Support/Process.h"
44 #include "llvm/Support/TarWriter.h"
45 #include "llvm/Support/TargetSelect.h"
46 #include "llvm/Support/raw_ostream.h"
47 #include "llvm/ToolDrivers/llvm-lib/LibDriver.h"
53 using namespace llvm::object;
54 using namespace llvm::COFF;
55 using llvm::sys::Process;
60 static Timer inputFileTimer("Input File Reading", Timer::root());
62 Configuration *config;
65 bool link(ArrayRef<const char *> args, bool canExitEarly, raw_ostream &stdoutOS,
66 raw_ostream &stderrOS) {
67 lld::stdoutOS = &stdoutOS;
68 lld::stderrOS = &stderrOS;
70 errorHandler().logName = args::getFilenameWithoutExe(args[0]);
71 errorHandler().errorLimitExceededMsg =
72 "too many errors emitted, stopping now"
73 " (use /errorlimit:0 to see all errors)";
74 errorHandler().exitEarly = canExitEarly;
75 stderrOS.enable_colors(stderrOS.has_colors());
77 config = make<Configuration>();
78 symtab = make<SymbolTable>();
79 driver = make<LinkerDriver>();
83 // Call exit() if we can to avoid calling destructors.
85 exitLld(errorCount() ? 1 : 0);
88 ObjFile::instances.clear();
89 ImportFile::instances.clear();
90 BitcodeFile::instances.clear();
91 memset(MergeChunk::instances, 0, sizeof(MergeChunk::instances));
97 // Parse options of the form "old;new".
98 static std::pair<StringRef, StringRef> getOldNewOptions(opt::InputArgList &args,
100 auto *arg = args.getLastArg(id);
104 StringRef s = arg->getValue();
105 std::pair<StringRef, StringRef> ret = s.split(';');
106 if (ret.second.empty())
107 error(arg->getSpelling() + " expects 'old;new' format, but got " + s);
111 // Drop directory components and replace extension with
112 // ".exe", ".dll" or ".sys".
113 static std::string getOutputPath(StringRef path) {
114 StringRef ext = ".exe";
117 else if (config->driver)
120 return (sys::path::stem(path) + ext).str();
123 // Returns true if S matches /crtend.?\.o$/.
124 static bool isCrtend(StringRef s) {
125 if (!s.endswith(".o"))
128 if (s.endswith("crtend"))
130 return !s.empty() && s.drop_back().endswith("crtend");
133 // ErrorOr is not default constructible, so it cannot be used as the type
134 // parameter of a future.
135 // FIXME: We could open the file in createFutureForFile and avoid needing to
136 // return an error here, but for the moment that would cost us a file descriptor
137 // (a limited resource on Windows) for the duration that the future is pending.
138 using MBErrPair = std::pair<std::unique_ptr<MemoryBuffer>, std::error_code>;
140 // Create a std::future that opens and maps a file using the best strategy for
141 // the host platform.
142 static std::future<MBErrPair> createFutureForFile(std::string path) {
144 // On Windows, file I/O is relatively slow so it is best to do this
146 auto strategy = std::launch::async;
148 auto strategy = std::launch::deferred;
150 return std::async(strategy, [=]() {
151 auto mbOrErr = MemoryBuffer::getFile(path,
153 /*RequiresNullTerminator*/ false);
155 return MBErrPair{nullptr, mbOrErr.getError()};
156 return MBErrPair{std::move(*mbOrErr), std::error_code()};
160 // Symbol names are mangled by prepending "_" on x86.
161 static StringRef mangle(StringRef sym) {
162 assert(config->machine != IMAGE_FILE_MACHINE_UNKNOWN);
163 if (config->machine == I386)
164 return saver.save("_" + sym);
168 static bool findUnderscoreMangle(StringRef sym) {
169 Symbol *s = symtab->findMangle(mangle(sym));
170 return s && !isa<Undefined>(s);
173 MemoryBufferRef LinkerDriver::takeBuffer(std::unique_ptr<MemoryBuffer> mb) {
174 MemoryBufferRef mbref = *mb;
175 make<std::unique_ptr<MemoryBuffer>>(std::move(mb)); // take ownership
178 driver->tar->append(relativeToRoot(mbref.getBufferIdentifier()),
183 void LinkerDriver::addBuffer(std::unique_ptr<MemoryBuffer> mb,
184 bool wholeArchive, bool lazy) {
185 StringRef filename = mb->getBufferIdentifier();
187 MemoryBufferRef mbref = takeBuffer(std::move(mb));
188 filePaths.push_back(filename);
190 // File type is detected by contents, not by file extension.
191 switch (identify_magic(mbref.getBuffer())) {
192 case file_magic::windows_resource:
193 resources.push_back(mbref);
195 case file_magic::archive:
197 std::unique_ptr<Archive> file =
198 CHECK(Archive::create(mbref), filename + ": failed to parse archive");
199 Archive *archive = file.get();
200 make<std::unique_ptr<Archive>>(std::move(file)); // take ownership
203 for (MemoryBufferRef m : getArchiveMembers(archive))
204 addArchiveBuffer(m, "<whole-archive>", filename, memberIndex++);
207 symtab->addFile(make<ArchiveFile>(mbref));
209 case file_magic::bitcode:
211 symtab->addFile(make<LazyObjFile>(mbref));
213 symtab->addFile(make<BitcodeFile>(mbref, "", 0));
215 case file_magic::coff_object:
216 case file_magic::coff_import_library:
218 symtab->addFile(make<LazyObjFile>(mbref));
220 symtab->addFile(make<ObjFile>(mbref));
222 case file_magic::pdb:
223 symtab->addFile(make<PDBInputFile>(mbref));
225 case file_magic::coff_cl_gl_object:
226 error(filename + ": is not a native COFF file. Recompile without /GL");
228 case file_magic::pecoff_executable:
229 if (filename.endswith_lower(".dll")) {
230 error(filename + ": bad file type. Did you specify a DLL instead of an "
236 error(mbref.getBufferIdentifier() + ": unknown file type");
241 void LinkerDriver::enqueuePath(StringRef path, bool wholeArchive, bool lazy) {
242 auto future = std::make_shared<std::future<MBErrPair>>(
243 createFutureForFile(std::string(path)));
244 std::string pathStr = std::string(path);
246 auto mbOrErr = future->get();
247 if (mbOrErr.second) {
249 "could not open '" + pathStr + "': " + mbOrErr.second.message();
250 // Check if the filename is a typo for an option flag. OptTable thinks
251 // that all args that are not known options and that start with / are
252 // filenames, but e.g. `/nodefaultlibs` is more likely a typo for
253 // the option `/nodefaultlib` than a reference to a file in the root
256 if (optTable.findNearest(pathStr, nearest) > 1)
259 error(msg + "; did you mean '" + nearest + "'");
261 driver->addBuffer(std::move(mbOrErr.first), wholeArchive, lazy);
265 void LinkerDriver::addArchiveBuffer(MemoryBufferRef mb, StringRef symName,
266 StringRef parentName,
267 uint64_t offsetInArchive) {
268 file_magic magic = identify_magic(mb.getBuffer());
269 if (magic == file_magic::coff_import_library) {
270 InputFile *imp = make<ImportFile>(mb);
271 imp->parentName = parentName;
272 symtab->addFile(imp);
277 if (magic == file_magic::coff_object) {
278 obj = make<ObjFile>(mb);
279 } else if (magic == file_magic::bitcode) {
280 obj = make<BitcodeFile>(mb, parentName, offsetInArchive);
282 error("unknown file type: " + mb.getBufferIdentifier());
286 obj->parentName = parentName;
287 symtab->addFile(obj);
288 log("Loaded " + toString(obj) + " for " + symName);
291 void LinkerDriver::enqueueArchiveMember(const Archive::Child &c,
292 const Archive::Symbol &sym,
293 StringRef parentName) {
295 auto reportBufferError = [=](Error &&e, StringRef childName) {
296 fatal("could not get the buffer for the member defining symbol " +
297 toCOFFString(sym) + ": " + parentName + "(" + childName + "): " +
298 toString(std::move(e)));
301 if (!c.getParent()->isThin()) {
302 uint64_t offsetInArchive = c.getChildOffset();
303 Expected<MemoryBufferRef> mbOrErr = c.getMemoryBufferRef();
305 reportBufferError(mbOrErr.takeError(), check(c.getFullName()));
306 MemoryBufferRef mb = mbOrErr.get();
308 driver->addArchiveBuffer(mb, toCOFFString(sym), parentName,
314 std::string childName = CHECK(
316 "could not get the filename for the member defining symbol " +
318 auto future = std::make_shared<std::future<MBErrPair>>(
319 createFutureForFile(childName));
321 auto mbOrErr = future->get();
323 reportBufferError(errorCodeToError(mbOrErr.second), childName);
324 // Pass empty string as archive name so that the original filename is
325 // used as the buffer identifier.
326 driver->addArchiveBuffer(takeBuffer(std::move(mbOrErr.first)),
327 toCOFFString(sym), "", /*OffsetInArchive=*/0);
331 static bool isDecorated(StringRef sym) {
332 return sym.startswith("@") || sym.contains("@@") || sym.startswith("?") ||
333 (!config->mingw && sym.contains('@'));
336 // Parses .drectve section contents and returns a list of files
337 // specified by /defaultlib.
338 void LinkerDriver::parseDirectives(InputFile *file) {
339 StringRef s = file->getDirectives();
343 log("Directives: " + toString(file) + ": " + s);
346 // .drectve is always tokenized using Windows shell rules.
347 // /EXPORT: option can appear too many times, processing in fastpath.
348 ParsedDirectives directives = parser.parseDirectives(s);
350 for (StringRef e : directives.exports) {
351 // If a common header file contains dllexported function
352 // declarations, many object files may end up with having the
353 // same /EXPORT options. In order to save cost of parsing them,
354 // we dedup them first.
355 if (!directivesExports.insert(e).second)
358 Export exp = parseExport(e);
359 if (config->machine == I386 && config->mingw) {
360 if (!isDecorated(exp.name))
361 exp.name = saver.save("_" + exp.name);
362 if (!exp.extName.empty() && !isDecorated(exp.extName))
363 exp.extName = saver.save("_" + exp.extName);
365 exp.directives = true;
366 config->exports.push_back(exp);
369 // Handle /include: in bulk.
370 for (StringRef inc : directives.includes)
373 for (auto *arg : directives.args) {
374 switch (arg->getOption().getID()) {
376 parseAligncomm(arg->getValue());
378 case OPT_alternatename:
379 parseAlternateName(arg->getValue());
382 if (Optional<StringRef> path = findLib(arg->getValue()))
383 enqueuePath(*path, false, false);
386 config->entry = addUndefined(mangle(arg->getValue()));
388 case OPT_failifmismatch:
389 checkFailIfMismatch(arg->getValue(), file);
392 addUndefined(arg->getValue());
395 parseMerge(arg->getValue());
397 case OPT_nodefaultlib:
398 config->noDefaultLibs.insert(doFindLib(arg->getValue()).lower());
401 parseSection(arg->getValue());
404 parseSubsystem(arg->getValue(), &config->subsystem,
405 &config->majorOSVersion, &config->minorOSVersion);
407 // Only add flags here that link.exe accepts in
408 // `#pragma comment(linker, "/flag")`-generated sections.
409 case OPT_editandcontinue:
411 case OPT_throwingnew:
414 error(arg->getSpelling() + " is not allowed in .drectve");
419 // Find file from search paths. You can omit ".obj", this function takes
420 // care of that. Note that the returned path is not guaranteed to exist.
421 StringRef LinkerDriver::doFindFile(StringRef filename) {
422 bool hasPathSep = (filename.find_first_of("/\\") != StringRef::npos);
425 bool hasExt = filename.contains('.');
426 for (StringRef dir : searchPaths) {
427 SmallString<128> path = dir;
428 sys::path::append(path, filename);
429 if (sys::fs::exists(path.str()))
430 return saver.save(path.str());
433 if (sys::fs::exists(path.str()))
434 return saver.save(path.str());
440 static Optional<sys::fs::UniqueID> getUniqueID(StringRef path) {
441 sys::fs::UniqueID ret;
442 if (sys::fs::getUniqueID(path, ret))
447 // Resolves a file path. This never returns the same path
448 // (in that case, it returns None).
449 Optional<StringRef> LinkerDriver::findFile(StringRef filename) {
450 StringRef path = doFindFile(filename);
452 if (Optional<sys::fs::UniqueID> id = getUniqueID(path)) {
453 bool seen = !visitedFiles.insert(*id).second;
458 if (path.endswith_lower(".lib"))
459 visitedLibs.insert(std::string(sys::path::filename(path)));
463 // MinGW specific. If an embedded directive specified to link to
464 // foo.lib, but it isn't found, try libfoo.a instead.
465 StringRef LinkerDriver::doFindLibMinGW(StringRef filename) {
466 if (filename.contains('/') || filename.contains('\\'))
469 SmallString<128> s = filename;
470 sys::path::replace_extension(s, ".a");
471 StringRef libName = saver.save("lib" + s.str());
472 return doFindFile(libName);
475 // Find library file from search path.
476 StringRef LinkerDriver::doFindLib(StringRef filename) {
477 // Add ".lib" to Filename if that has no file extension.
478 bool hasExt = filename.contains('.');
480 filename = saver.save(filename + ".lib");
481 StringRef ret = doFindFile(filename);
482 // For MinGW, if the find above didn't turn up anything, try
483 // looking for a MinGW formatted library name.
484 if (config->mingw && ret == filename)
485 return doFindLibMinGW(filename);
489 // Resolves a library path. /nodefaultlib options are taken into
490 // consideration. This never returns the same path (in that case,
492 Optional<StringRef> LinkerDriver::findLib(StringRef filename) {
493 if (config->noDefaultLibAll)
495 if (!visitedLibs.insert(filename.lower()).second)
498 StringRef path = doFindLib(filename);
499 if (config->noDefaultLibs.count(path.lower()))
502 if (Optional<sys::fs::UniqueID> id = getUniqueID(path))
503 if (!visitedFiles.insert(*id).second)
508 // Parses LIB environment which contains a list of search paths.
509 void LinkerDriver::addLibSearchPaths() {
510 Optional<std::string> envOpt = Process::GetEnv("LIB");
511 if (!envOpt.hasValue())
513 StringRef env = saver.save(*envOpt);
514 while (!env.empty()) {
516 std::tie(path, env) = env.split(';');
517 searchPaths.push_back(path);
521 Symbol *LinkerDriver::addUndefined(StringRef name) {
522 Symbol *b = symtab->addUndefined(name);
525 config->gcroot.push_back(b);
530 StringRef LinkerDriver::mangleMaybe(Symbol *s) {
531 // If the plain symbol name has already been resolved, do nothing.
532 Undefined *unmangled = dyn_cast<Undefined>(s);
536 // Otherwise, see if a similar, mangled symbol exists in the symbol table.
537 Symbol *mangled = symtab->findMangle(unmangled->getName());
541 // If we find a similar mangled symbol, make this an alias to it and return
543 log(unmangled->getName() + " aliased to " + mangled->getName());
544 unmangled->weakAlias = symtab->addUndefined(mangled->getName());
545 return mangled->getName();
548 // Windows specific -- find default entry point name.
550 // There are four different entry point functions for Windows executables,
551 // each of which corresponds to a user-defined "main" function. This function
552 // infers an entry point from a user-defined "main" function.
553 StringRef LinkerDriver::findDefaultEntry() {
554 assert(config->subsystem != IMAGE_SUBSYSTEM_UNKNOWN &&
555 "must handle /subsystem before calling this");
558 return mangle(config->subsystem == IMAGE_SUBSYSTEM_WINDOWS_GUI
559 ? "WinMainCRTStartup"
562 if (config->subsystem == IMAGE_SUBSYSTEM_WINDOWS_GUI) {
563 if (findUnderscoreMangle("wWinMain")) {
564 if (!findUnderscoreMangle("WinMain"))
565 return mangle("wWinMainCRTStartup");
566 warn("found both wWinMain and WinMain; using latter");
568 return mangle("WinMainCRTStartup");
570 if (findUnderscoreMangle("wmain")) {
571 if (!findUnderscoreMangle("main"))
572 return mangle("wmainCRTStartup");
573 warn("found both wmain and main; using latter");
575 return mangle("mainCRTStartup");
578 WindowsSubsystem LinkerDriver::inferSubsystem() {
580 return IMAGE_SUBSYSTEM_WINDOWS_GUI;
582 return IMAGE_SUBSYSTEM_WINDOWS_CUI;
583 // Note that link.exe infers the subsystem from the presence of these
584 // functions even if /entry: or /nodefaultlib are passed which causes them
586 bool haveMain = findUnderscoreMangle("main");
587 bool haveWMain = findUnderscoreMangle("wmain");
588 bool haveWinMain = findUnderscoreMangle("WinMain");
589 bool haveWWinMain = findUnderscoreMangle("wWinMain");
590 if (haveMain || haveWMain) {
591 if (haveWinMain || haveWWinMain) {
592 warn(std::string("found ") + (haveMain ? "main" : "wmain") + " and " +
593 (haveWinMain ? "WinMain" : "wWinMain") +
594 "; defaulting to /subsystem:console");
596 return IMAGE_SUBSYSTEM_WINDOWS_CUI;
598 if (haveWinMain || haveWWinMain)
599 return IMAGE_SUBSYSTEM_WINDOWS_GUI;
600 return IMAGE_SUBSYSTEM_UNKNOWN;
603 static uint64_t getDefaultImageBase() {
605 return config->dll ? 0x180000000 : 0x140000000;
606 return config->dll ? 0x10000000 : 0x400000;
609 static std::string createResponseFile(const opt::InputArgList &args,
610 ArrayRef<StringRef> filePaths,
611 ArrayRef<StringRef> searchPaths) {
613 raw_svector_ostream os(data);
615 for (auto *arg : args) {
616 switch (arg->getOption().getID()) {
623 case OPT_manifest_colon:
624 case OPT_manifestdependency:
625 case OPT_manifestfile:
626 case OPT_manifestinput:
627 case OPT_manifestuac:
631 case OPT_pdbstripped:
633 os << arg->getSpelling() << sys::path::filename(arg->getValue()) << "\n";
636 os << toString(*arg) << "\n";
640 for (StringRef path : searchPaths) {
641 std::string relPath = relativeToRoot(path);
642 os << "/libpath:" << quote(relPath) << "\n";
645 for (StringRef path : filePaths)
646 os << quote(relativeToRoot(path)) << "\n";
648 return std::string(data.str());
651 enum class DebugKind { Unknown, None, Full, FastLink, GHash, Dwarf, Symtab };
653 static DebugKind parseDebugKind(const opt::InputArgList &args) {
654 auto *a = args.getLastArg(OPT_debug, OPT_debug_opt);
656 return DebugKind::None;
657 if (a->getNumValues() == 0)
658 return DebugKind::Full;
660 DebugKind debug = StringSwitch<DebugKind>(a->getValue())
661 .CaseLower("none", DebugKind::None)
662 .CaseLower("full", DebugKind::Full)
663 .CaseLower("fastlink", DebugKind::FastLink)
665 .CaseLower("ghash", DebugKind::GHash)
666 .CaseLower("dwarf", DebugKind::Dwarf)
667 .CaseLower("symtab", DebugKind::Symtab)
668 .Default(DebugKind::Unknown);
670 if (debug == DebugKind::FastLink) {
671 warn("/debug:fastlink unsupported; using /debug:full");
672 return DebugKind::Full;
674 if (debug == DebugKind::Unknown) {
675 error("/debug: unknown option: " + Twine(a->getValue()));
676 return DebugKind::None;
681 static unsigned parseDebugTypes(const opt::InputArgList &args) {
682 unsigned debugTypes = static_cast<unsigned>(DebugType::None);
684 if (auto *a = args.getLastArg(OPT_debugtype)) {
685 SmallVector<StringRef, 3> types;
686 StringRef(a->getValue())
687 .split(types, ',', /*MaxSplit=*/-1, /*KeepEmpty=*/false);
689 for (StringRef type : types) {
690 unsigned v = StringSwitch<unsigned>(type.lower())
691 .Case("cv", static_cast<unsigned>(DebugType::CV))
692 .Case("pdata", static_cast<unsigned>(DebugType::PData))
693 .Case("fixup", static_cast<unsigned>(DebugType::Fixup))
696 warn("/debugtype: unknown option '" + type + "'");
704 // Default debug types
705 debugTypes = static_cast<unsigned>(DebugType::CV);
706 if (args.hasArg(OPT_driver))
707 debugTypes |= static_cast<unsigned>(DebugType::PData);
708 if (args.hasArg(OPT_profile))
709 debugTypes |= static_cast<unsigned>(DebugType::Fixup);
714 static std::string getMapFile(const opt::InputArgList &args,
715 opt::OptSpecifier os, opt::OptSpecifier osFile) {
716 auto *arg = args.getLastArg(os, osFile);
719 if (arg->getOption().getID() == osFile.getID())
720 return arg->getValue();
722 assert(arg->getOption().getID() == os.getID());
723 StringRef outFile = config->outputFile;
724 return (outFile.substr(0, outFile.rfind('.')) + ".map").str();
727 static std::string getImplibPath() {
728 if (!config->implib.empty())
729 return std::string(config->implib);
730 SmallString<128> out = StringRef(config->outputFile);
731 sys::path::replace_extension(out, ".lib");
732 return std::string(out.str());
735 // The import name is calculated as follows:
737 // | LIBRARY w/ ext | LIBRARY w/o ext | no LIBRARY
738 // -----+----------------+---------------------+------------------
739 // LINK | {value} | {value}.{.dll/.exe} | {output name}
740 // LIB | {value} | {value}.dll | {output name}.dll
742 static std::string getImportName(bool asLib) {
743 SmallString<128> out;
745 if (config->importName.empty()) {
746 out.assign(sys::path::filename(config->outputFile));
748 sys::path::replace_extension(out, ".dll");
750 out.assign(config->importName);
751 if (!sys::path::has_extension(out))
752 sys::path::replace_extension(out,
753 (config->dll || asLib) ? ".dll" : ".exe");
756 return std::string(out.str());
759 static void createImportLibrary(bool asLib) {
760 std::vector<COFFShortExport> exports;
761 for (Export &e1 : config->exports) {
763 e2.Name = std::string(e1.name);
764 e2.SymbolName = std::string(e1.symbolName);
765 e2.ExtName = std::string(e1.extName);
766 e2.Ordinal = e1.ordinal;
767 e2.Noname = e1.noname;
769 e2.Private = e1.isPrivate;
770 e2.Constant = e1.constant;
771 exports.push_back(e2);
774 auto handleError = [](Error &&e) {
775 handleAllErrors(std::move(e),
776 [](ErrorInfoBase &eib) { error(eib.message()); });
778 std::string libName = getImportName(asLib);
779 std::string path = getImplibPath();
781 if (!config->incremental) {
782 handleError(writeImportLibrary(libName, path, exports, config->machine,
787 // If the import library already exists, replace it only if the contents
789 ErrorOr<std::unique_ptr<MemoryBuffer>> oldBuf = MemoryBuffer::getFile(
790 path, /*FileSize*/ -1, /*RequiresNullTerminator*/ false);
792 handleError(writeImportLibrary(libName, path, exports, config->machine,
797 SmallString<128> tmpName;
798 if (std::error_code ec =
799 sys::fs::createUniqueFile(path + ".tmp-%%%%%%%%.lib", tmpName))
800 fatal("cannot create temporary file for import library " + path + ": " +
803 if (Error e = writeImportLibrary(libName, tmpName, exports, config->machine,
805 handleError(std::move(e));
809 std::unique_ptr<MemoryBuffer> newBuf = check(MemoryBuffer::getFile(
810 tmpName, /*FileSize*/ -1, /*RequiresNullTerminator*/ false));
811 if ((*oldBuf)->getBuffer() != newBuf->getBuffer()) {
813 handleError(errorCodeToError(sys::fs::rename(tmpName, path)));
815 sys::fs::remove(tmpName);
819 static void parseModuleDefs(StringRef path) {
820 std::unique_ptr<MemoryBuffer> mb = CHECK(
821 MemoryBuffer::getFile(path, -1, false, true), "could not open " + path);
822 COFFModuleDefinition m = check(parseCOFFModuleDefinition(
823 mb->getMemBufferRef(), config->machine, config->mingw));
825 if (config->outputFile.empty())
826 config->outputFile = std::string(saver.save(m.OutputFile));
827 config->importName = std::string(saver.save(m.ImportName));
829 config->imageBase = m.ImageBase;
831 config->stackReserve = m.StackReserve;
833 config->stackCommit = m.StackCommit;
835 config->heapReserve = m.HeapReserve;
837 config->heapCommit = m.HeapCommit;
838 if (m.MajorImageVersion)
839 config->majorImageVersion = m.MajorImageVersion;
840 if (m.MinorImageVersion)
841 config->minorImageVersion = m.MinorImageVersion;
842 if (m.MajorOSVersion)
843 config->majorOSVersion = m.MajorOSVersion;
844 if (m.MinorOSVersion)
845 config->minorOSVersion = m.MinorOSVersion;
847 for (COFFShortExport e1 : m.Exports) {
849 // In simple cases, only Name is set. Renamed exports are parsed
850 // and set as "ExtName = Name". If Name has the form "OtherDll.Func",
851 // it shouldn't be a normal exported function but a forward to another
852 // DLL instead. This is supported by both MS and GNU linkers.
853 if (!e1.ExtName.empty() && e1.ExtName != e1.Name &&
854 StringRef(e1.Name).contains('.')) {
855 e2.name = saver.save(e1.ExtName);
856 e2.forwardTo = saver.save(e1.Name);
857 config->exports.push_back(e2);
860 e2.name = saver.save(e1.Name);
861 e2.extName = saver.save(e1.ExtName);
862 e2.ordinal = e1.Ordinal;
863 e2.noname = e1.Noname;
865 e2.isPrivate = e1.Private;
866 e2.constant = e1.Constant;
867 config->exports.push_back(e2);
871 void LinkerDriver::enqueueTask(std::function<void()> task) {
872 taskQueue.push_back(std::move(task));
875 bool LinkerDriver::run() {
876 ScopedTimer t(inputFileTimer);
878 bool didWork = !taskQueue.empty();
879 while (!taskQueue.empty()) {
881 taskQueue.pop_front();
886 // Parse an /order file. If an option is given, the linker places
887 // COMDAT sections in the same order as their names appear in the
889 static void parseOrderFile(StringRef arg) {
890 // For some reason, the MSVC linker requires a filename to be
892 if (!arg.startswith("@")) {
893 error("malformed /order option: '@' missing");
897 // Get a list of all comdat sections for error checking.
898 DenseSet<StringRef> set;
899 for (Chunk *c : symtab->getChunks())
900 if (auto *sec = dyn_cast<SectionChunk>(c))
902 set.insert(sec->sym->getName());
905 StringRef path = arg.substr(1);
906 std::unique_ptr<MemoryBuffer> mb = CHECK(
907 MemoryBuffer::getFile(path, -1, false, true), "could not open " + path);
909 // Parse a file. An order file contains one symbol per line.
910 // All symbols that were not present in a given order file are
911 // considered to have the lowest priority 0 and are placed at
912 // end of an output section.
913 for (StringRef arg : args::getLines(mb->getMemBufferRef())) {
915 if (config->machine == I386 && !isDecorated(s))
918 if (set.count(s) == 0) {
919 if (config->warnMissingOrderSymbol)
920 warn("/order:" + arg + ": missing symbol: " + s + " [LNK4037]");
923 config->order[s] = INT_MIN + config->order.size();
927 static void markAddrsig(Symbol *s) {
928 if (auto *d = dyn_cast_or_null<Defined>(s))
929 if (SectionChunk *c = dyn_cast_or_null<SectionChunk>(d->getChunk()))
930 c->keepUnique = true;
933 static void findKeepUniqueSections() {
934 // Exported symbols could be address-significant in other executables or DSOs,
935 // so we conservatively mark them as address-significant.
936 for (Export &r : config->exports)
939 // Visit the address-significance table in each object file and mark each
940 // referenced symbol as address-significant.
941 for (ObjFile *obj : ObjFile::instances) {
942 ArrayRef<Symbol *> syms = obj->getSymbols();
943 if (obj->addrsigSec) {
944 ArrayRef<uint8_t> contents;
946 obj->getCOFFObj()->getSectionContents(obj->addrsigSec, contents));
947 const uint8_t *cur = contents.begin();
948 while (cur != contents.end()) {
951 uint64_t symIndex = decodeULEB128(cur, &size, contents.end(), &err);
953 fatal(toString(obj) + ": could not decode addrsig section: " + err);
954 if (symIndex >= syms.size())
955 fatal(toString(obj) + ": invalid symbol index in addrsig section");
956 markAddrsig(syms[symIndex]);
960 // If an object file does not have an address-significance table,
961 // conservatively mark all of its symbols as address-significant.
962 for (Symbol *s : syms)
968 // link.exe replaces each %foo% in altPath with the contents of environment
969 // variable foo, and adds the two magic env vars _PDB (expands to the basename
970 // of pdb's output path) and _EXT (expands to the extension of the output
972 // lld only supports %_PDB% and %_EXT% and warns on references to all other env
974 static void parsePDBAltPath(StringRef altPath) {
975 SmallString<128> buf;
976 StringRef pdbBasename =
977 sys::path::filename(config->pdbPath, sys::path::Style::windows);
978 StringRef binaryExtension =
979 sys::path::extension(config->outputFile, sys::path::Style::windows);
980 if (!binaryExtension.empty())
981 binaryExtension = binaryExtension.substr(1); // %_EXT% does not include '.'.
984 // +--------- cursor ('a...' might be the empty string).
985 // | +----- firstMark
990 while (cursor < altPath.size()) {
991 size_t firstMark, secondMark;
992 if ((firstMark = altPath.find('%', cursor)) == StringRef::npos ||
993 (secondMark = altPath.find('%', firstMark + 1)) == StringRef::npos) {
994 // Didn't find another full fragment, treat rest of string as literal.
995 buf.append(altPath.substr(cursor));
999 // Found a full fragment. Append text in front of first %, and interpret
1000 // text between first and second % as variable name.
1001 buf.append(altPath.substr(cursor, firstMark - cursor));
1002 StringRef var = altPath.substr(firstMark, secondMark - firstMark + 1);
1003 if (var.equals_lower("%_pdb%"))
1004 buf.append(pdbBasename);
1005 else if (var.equals_lower("%_ext%"))
1006 buf.append(binaryExtension);
1008 warn("only %_PDB% and %_EXT% supported in /pdbaltpath:, keeping " +
1009 var + " as literal");
1013 cursor = secondMark + 1;
1016 config->pdbAltPath = buf;
1019 /// Convert resource files and potentially merge input resource object
1020 /// trees into one resource tree.
1021 /// Call after ObjFile::Instances is complete.
1022 void LinkerDriver::convertResources() {
1023 std::vector<ObjFile *> resourceObjFiles;
1025 for (ObjFile *f : ObjFile::instances) {
1026 if (f->isResourceObjFile())
1027 resourceObjFiles.push_back(f);
1030 if (!config->mingw &&
1031 (resourceObjFiles.size() > 1 ||
1032 (resourceObjFiles.size() == 1 && !resources.empty()))) {
1033 error((!resources.empty() ? "internal .obj file created from .res files"
1034 : toString(resourceObjFiles[1])) +
1035 ": more than one resource obj file not allowed, already got " +
1036 toString(resourceObjFiles.front()));
1040 if (resources.empty() && resourceObjFiles.size() <= 1) {
1041 // No resources to convert, and max one resource object file in
1042 // the input. Keep that preconverted resource section as is.
1043 for (ObjFile *f : resourceObjFiles)
1044 f->includeResourceChunks();
1047 ObjFile *f = make<ObjFile>(convertResToCOFF(resources, resourceObjFiles));
1049 f->includeResourceChunks();
1052 // In MinGW, if no symbols are chosen to be exported, then all symbols are
1053 // automatically exported by default. This behavior can be forced by the
1054 // -export-all-symbols option, so that it happens even when exports are
1055 // explicitly specified. The automatic behavior can be disabled using the
1056 // -exclude-all-symbols option, so that lld-link behaves like link.exe rather
1057 // than MinGW in the case that nothing is explicitly exported.
1058 void LinkerDriver::maybeExportMinGWSymbols(const opt::InputArgList &args) {
1062 if (!args.hasArg(OPT_export_all_symbols)) {
1063 if (!config->exports.empty())
1065 if (args.hasArg(OPT_exclude_all_symbols))
1069 AutoExporter exporter;
1071 for (auto *arg : args.filtered(OPT_wholearchive_file))
1072 if (Optional<StringRef> path = doFindFile(arg->getValue()))
1073 exporter.addWholeArchive(*path);
1075 symtab->forEachSymbol([&](Symbol *s) {
1076 auto *def = dyn_cast<Defined>(s);
1077 if (!exporter.shouldExport(def))
1081 e.name = def->getName();
1083 if (Chunk *c = def->getChunk())
1084 if (!(c->getOutputCharacteristics() & IMAGE_SCN_MEM_EXECUTE))
1086 config->exports.push_back(e);
1090 // lld has a feature to create a tar file containing all input files as well as
1091 // all command line options, so that other people can run lld again with exactly
1092 // the same inputs. This feature is accessible via /linkrepro and /reproduce.
1094 // /linkrepro and /reproduce are very similar, but /linkrepro takes a directory
1095 // name while /reproduce takes a full path. We have /linkrepro for compatibility
1096 // with Microsoft link.exe.
1097 Optional<std::string> getReproduceFile(const opt::InputArgList &args) {
1098 if (auto *arg = args.getLastArg(OPT_reproduce))
1099 return std::string(arg->getValue());
1101 if (auto *arg = args.getLastArg(OPT_linkrepro)) {
1102 SmallString<64> path = StringRef(arg->getValue());
1103 sys::path::append(path, "repro.tar");
1104 return std::string(path);
1110 void LinkerDriver::link(ArrayRef<const char *> argsArr) {
1111 ScopedTimer rootTimer(Timer::root());
1114 InitializeAllTargetInfos();
1115 InitializeAllTargets();
1116 InitializeAllTargetMCs();
1117 InitializeAllAsmParsers();
1118 InitializeAllAsmPrinters();
1120 // If the first command line argument is "/lib", link.exe acts like lib.exe.
1121 // We call our own implementation of lib.exe that understands bitcode files.
1122 if (argsArr.size() > 1 && StringRef(argsArr[1]).equals_lower("/lib")) {
1123 if (llvm::libDriverMain(argsArr.slice(1)) != 0)
1124 fatal("lib failed");
1128 // Parse command line options.
1130 opt::InputArgList args = parser.parse(argsArr);
1132 // Parse and evaluate -mllvm options.
1133 std::vector<const char *> v;
1134 v.push_back("lld-link (LLVM option parsing)");
1135 for (auto *arg : args.filtered(OPT_mllvm))
1136 v.push_back(arg->getValue());
1137 cl::ParseCommandLineOptions(v.size(), v.data());
1139 // Handle /errorlimit early, because error() depends on it.
1140 if (auto *arg = args.getLastArg(OPT_errorlimit)) {
1142 StringRef s = arg->getValue();
1143 if (s.getAsInteger(10, n))
1144 error(arg->getSpelling() + " number expected, but got " + s);
1145 errorHandler().errorLimit = n;
1149 if (args.hasArg(OPT_help)) {
1150 printHelp(argsArr[0]);
1154 // /threads: takes a positive integer and provides the default value for
1155 // /opt:lldltojobs=.
1156 if (auto *arg = args.getLastArg(OPT_threads)) {
1157 StringRef v(arg->getValue());
1158 unsigned threads = 0;
1159 if (!llvm::to_integer(v, threads, 0) || threads == 0)
1160 error(arg->getSpelling() + ": expected a positive integer, but got '" +
1161 arg->getValue() + "'");
1162 parallel::strategy = hardware_concurrency(threads);
1163 config->thinLTOJobs = v.str();
1166 if (args.hasArg(OPT_show_timing))
1167 config->showTiming = true;
1169 config->showSummary = args.hasArg(OPT_summary);
1171 // Handle --version, which is an lld extension. This option is a bit odd
1172 // because it doesn't start with "/", but we deliberately chose "--" to
1173 // avoid conflict with /version and for compatibility with clang-cl.
1174 if (args.hasArg(OPT_dash_dash_version)) {
1175 lld::outs() << getLLDVersion() << "\n";
1179 // Handle /lldmingw early, since it can potentially affect how other
1180 // options are handled.
1181 config->mingw = args.hasArg(OPT_lldmingw);
1183 // Handle /linkrepro and /reproduce.
1184 if (Optional<std::string> path = getReproduceFile(args)) {
1185 Expected<std::unique_ptr<TarWriter>> errOrWriter =
1186 TarWriter::create(*path, sys::path::stem(*path));
1189 tar = std::move(*errOrWriter);
1191 error("/linkrepro: failed to open " + *path + ": " +
1192 toString(errOrWriter.takeError()));
1196 if (!args.hasArg(OPT_INPUT, OPT_wholearchive_file)) {
1197 if (args.hasArg(OPT_deffile))
1198 config->noEntry = true;
1200 fatal("no input files");
1203 // Construct search path list.
1204 searchPaths.push_back("");
1205 for (auto *arg : args.filtered(OPT_libpath))
1206 searchPaths.push_back(arg->getValue());
1207 if (!args.hasArg(OPT_lldignoreenv))
1208 addLibSearchPaths();
1211 for (auto *arg : args.filtered(OPT_ignore)) {
1212 SmallVector<StringRef, 8> vec;
1213 StringRef(arg->getValue()).split(vec, ',');
1214 for (StringRef s : vec) {
1216 config->warnMissingOrderSymbol = false;
1217 else if (s == "4099")
1218 config->warnDebugInfoUnusable = false;
1219 else if (s == "4217")
1220 config->warnLocallyDefinedImported = false;
1221 else if (s == "longsections")
1222 config->warnLongSectionNames = false;
1223 // Other warning numbers are ignored.
1228 if (auto *arg = args.getLastArg(OPT_out))
1229 config->outputFile = arg->getValue();
1232 if (args.hasArg(OPT_verbose))
1233 config->verbose = true;
1234 errorHandler().verbose = config->verbose;
1236 // Handle /force or /force:unresolved
1237 if (args.hasArg(OPT_force, OPT_force_unresolved))
1238 config->forceUnresolved = true;
1240 // Handle /force or /force:multiple
1241 if (args.hasArg(OPT_force, OPT_force_multiple))
1242 config->forceMultiple = true;
1244 // Handle /force or /force:multipleres
1245 if (args.hasArg(OPT_force, OPT_force_multipleres))
1246 config->forceMultipleRes = true;
1249 DebugKind debug = parseDebugKind(args);
1250 if (debug == DebugKind::Full || debug == DebugKind::Dwarf ||
1251 debug == DebugKind::GHash) {
1252 config->debug = true;
1253 config->incremental = true;
1257 config->demangle = args.hasFlag(OPT_demangle, OPT_demangle_no);
1259 // Handle /debugtype
1260 config->debugTypes = parseDebugTypes(args);
1262 // Handle /driver[:uponly|:wdm].
1263 config->driverUponly = args.hasArg(OPT_driver_uponly) ||
1264 args.hasArg(OPT_driver_uponly_wdm) ||
1265 args.hasArg(OPT_driver_wdm_uponly);
1266 config->driverWdm = args.hasArg(OPT_driver_wdm) ||
1267 args.hasArg(OPT_driver_uponly_wdm) ||
1268 args.hasArg(OPT_driver_wdm_uponly);
1270 config->driverUponly || config->driverWdm || args.hasArg(OPT_driver);
1273 bool shouldCreatePDB =
1274 (debug == DebugKind::Full || debug == DebugKind::GHash);
1275 if (shouldCreatePDB) {
1276 if (auto *arg = args.getLastArg(OPT_pdb))
1277 config->pdbPath = arg->getValue();
1278 if (auto *arg = args.getLastArg(OPT_pdbaltpath))
1279 config->pdbAltPath = arg->getValue();
1280 if (args.hasArg(OPT_natvis))
1281 config->natvisFiles = args.getAllArgValues(OPT_natvis);
1282 if (args.hasArg(OPT_pdbstream)) {
1283 for (const StringRef value : args.getAllArgValues(OPT_pdbstream)) {
1284 const std::pair<StringRef, StringRef> nameFile = value.split("=");
1285 const StringRef name = nameFile.first;
1286 const std::string file = nameFile.second.str();
1287 config->namedStreams[name] = file;
1291 if (auto *arg = args.getLastArg(OPT_pdb_source_path))
1292 config->pdbSourcePath = arg->getValue();
1295 // Handle /pdbstripped
1296 if (args.hasArg(OPT_pdbstripped))
1297 warn("ignoring /pdbstripped flag, it is not yet supported");
1300 if (args.hasArg(OPT_noentry)) {
1301 if (args.hasArg(OPT_dll))
1302 config->noEntry = true;
1304 error("/noentry must be specified with /dll");
1308 if (args.hasArg(OPT_dll)) {
1310 config->manifestID = 2;
1313 // Handle /dynamicbase and /fixed. We can't use hasFlag for /dynamicbase
1314 // because we need to explicitly check whether that option or its inverse was
1315 // present in the argument list in order to handle /fixed.
1316 auto *dynamicBaseArg = args.getLastArg(OPT_dynamicbase, OPT_dynamicbase_no);
1317 if (dynamicBaseArg &&
1318 dynamicBaseArg->getOption().getID() == OPT_dynamicbase_no)
1319 config->dynamicBase = false;
1321 // MSDN claims "/FIXED:NO is the default setting for a DLL, and /FIXED is the
1322 // default setting for any other project type.", but link.exe defaults to
1323 // /FIXED:NO for exe outputs as well. Match behavior, not docs.
1324 bool fixed = args.hasFlag(OPT_fixed, OPT_fixed_no, false);
1326 if (dynamicBaseArg &&
1327 dynamicBaseArg->getOption().getID() == OPT_dynamicbase) {
1328 error("/fixed must not be specified with /dynamicbase");
1330 config->relocatable = false;
1331 config->dynamicBase = false;
1335 // Handle /appcontainer
1336 config->appContainer =
1337 args.hasFlag(OPT_appcontainer, OPT_appcontainer_no, false);
1340 if (auto *arg = args.getLastArg(OPT_machine)) {
1341 config->machine = getMachineType(arg->getValue());
1342 if (config->machine == IMAGE_FILE_MACHINE_UNKNOWN)
1343 fatal(Twine("unknown /machine argument: ") + arg->getValue());
1346 // Handle /nodefaultlib:<filename>
1347 for (auto *arg : args.filtered(OPT_nodefaultlib))
1348 config->noDefaultLibs.insert(doFindLib(arg->getValue()).lower());
1350 // Handle /nodefaultlib
1351 if (args.hasArg(OPT_nodefaultlib_all))
1352 config->noDefaultLibAll = true;
1355 if (auto *arg = args.getLastArg(OPT_base))
1356 parseNumbers(arg->getValue(), &config->imageBase);
1358 // Handle /filealign
1359 if (auto *arg = args.getLastArg(OPT_filealign)) {
1360 parseNumbers(arg->getValue(), &config->fileAlign);
1361 if (!isPowerOf2_64(config->fileAlign))
1362 error("/filealign: not a power of two: " + Twine(config->fileAlign));
1366 if (auto *arg = args.getLastArg(OPT_stack))
1367 parseNumbers(arg->getValue(), &config->stackReserve, &config->stackCommit);
1370 if (auto *arg = args.getLastArg(OPT_guard))
1371 parseGuard(arg->getValue());
1374 if (auto *arg = args.getLastArg(OPT_heap))
1375 parseNumbers(arg->getValue(), &config->heapReserve, &config->heapCommit);
1378 if (auto *arg = args.getLastArg(OPT_version))
1379 parseVersion(arg->getValue(), &config->majorImageVersion,
1380 &config->minorImageVersion);
1382 // Handle /subsystem
1383 if (auto *arg = args.getLastArg(OPT_subsystem))
1384 parseSubsystem(arg->getValue(), &config->subsystem, &config->majorOSVersion,
1385 &config->minorOSVersion);
1387 // Handle /timestamp
1388 if (llvm::opt::Arg *arg = args.getLastArg(OPT_timestamp, OPT_repro)) {
1389 if (arg->getOption().getID() == OPT_repro) {
1390 config->timestamp = 0;
1391 config->repro = true;
1393 config->repro = false;
1394 StringRef value(arg->getValue());
1395 if (value.getAsInteger(0, config->timestamp))
1396 fatal(Twine("invalid timestamp: ") + value +
1397 ". Expected 32-bit integer");
1400 config->repro = false;
1401 config->timestamp = time(nullptr);
1404 // Handle /alternatename
1405 for (auto *arg : args.filtered(OPT_alternatename))
1406 parseAlternateName(arg->getValue());
1409 for (auto *arg : args.filtered(OPT_incl))
1410 addUndefined(arg->getValue());
1413 if (auto *arg = args.getLastArg(OPT_implib))
1414 config->implib = arg->getValue();
1417 bool doGC = debug == DebugKind::None || args.hasArg(OPT_profile);
1419 args.hasArg(OPT_profile) ? 0 : 1; // 0: off, 1: limited, 2: on
1420 unsigned tailMerge = 1;
1421 for (auto *arg : args.filtered(OPT_opt)) {
1422 std::string str = StringRef(arg->getValue()).lower();
1423 SmallVector<StringRef, 1> vec;
1424 StringRef(str).split(vec, ',');
1425 for (StringRef s : vec) {
1428 } else if (s == "noref") {
1430 } else if (s == "icf" || s.startswith("icf=")) {
1432 } else if (s == "noicf") {
1434 } else if (s == "lldtailmerge") {
1436 } else if (s == "nolldtailmerge") {
1438 } else if (s.startswith("lldlto=")) {
1439 StringRef optLevel = s.substr(7);
1440 if (optLevel.getAsInteger(10, config->ltoo) || config->ltoo > 3)
1441 error("/opt:lldlto: invalid optimization level: " + optLevel);
1442 } else if (s.startswith("lldltojobs=")) {
1443 StringRef jobs = s.substr(11);
1444 if (!get_threadpool_strategy(jobs))
1445 error("/opt:lldltojobs: invalid job count: " + jobs);
1446 config->thinLTOJobs = jobs.str();
1447 } else if (s.startswith("lldltopartitions=")) {
1448 StringRef n = s.substr(17);
1449 if (n.getAsInteger(10, config->ltoPartitions) ||
1450 config->ltoPartitions == 0)
1451 error("/opt:lldltopartitions: invalid partition count: " + n);
1452 } else if (s != "lbr" && s != "nolbr")
1453 error("/opt: unknown option: " + s);
1457 // Limited ICF is enabled if GC is enabled and ICF was never mentioned
1459 // FIXME: LLD only implements "limited" ICF, i.e. it only merges identical
1460 // code. If the user passes /OPT:ICF explicitly, LLD should merge identical
1461 // comdat readonly data.
1462 if (icfLevel == 1 && !doGC)
1464 config->doGC = doGC;
1465 config->doICF = icfLevel > 0;
1466 config->tailMerge = (tailMerge == 1 && config->doICF) || tailMerge == 2;
1468 // Handle /lldsavetemps
1469 if (args.hasArg(OPT_lldsavetemps))
1470 config->saveTemps = true;
1473 if (args.hasArg(OPT_kill_at))
1474 config->killAt = true;
1476 // Handle /lldltocache
1477 if (auto *arg = args.getLastArg(OPT_lldltocache))
1478 config->ltoCache = arg->getValue();
1480 // Handle /lldsavecachepolicy
1481 if (auto *arg = args.getLastArg(OPT_lldltocachepolicy))
1482 config->ltoCachePolicy = CHECK(
1483 parseCachePruningPolicy(arg->getValue()),
1484 Twine("/lldltocachepolicy: invalid cache policy: ") + arg->getValue());
1486 // Handle /failifmismatch
1487 for (auto *arg : args.filtered(OPT_failifmismatch))
1488 checkFailIfMismatch(arg->getValue(), nullptr);
1491 for (auto *arg : args.filtered(OPT_merge))
1492 parseMerge(arg->getValue());
1494 // Add default section merging rules after user rules. User rules take
1495 // precedence, but we will emit a warning if there is a conflict.
1496 parseMerge(".idata=.rdata");
1497 parseMerge(".didat=.rdata");
1498 parseMerge(".edata=.rdata");
1499 parseMerge(".xdata=.rdata");
1500 parseMerge(".bss=.data");
1502 if (config->mingw) {
1503 parseMerge(".ctors=.rdata");
1504 parseMerge(".dtors=.rdata");
1505 parseMerge(".CRT=.rdata");
1509 for (auto *arg : args.filtered(OPT_section))
1510 parseSection(arg->getValue());
1513 if (auto *arg = args.getLastArg(OPT_align)) {
1514 parseNumbers(arg->getValue(), &config->align);
1515 if (!isPowerOf2_64(config->align))
1516 error("/align: not a power of two: " + StringRef(arg->getValue()));
1517 if (!args.hasArg(OPT_driver))
1518 warn("/align specified without /driver; image may not run");
1521 // Handle /aligncomm
1522 for (auto *arg : args.filtered(OPT_aligncomm))
1523 parseAligncomm(arg->getValue());
1525 // Handle /manifestdependency. This enables /manifest unless /manifest:no is
1527 if (auto *arg = args.getLastArg(OPT_manifestdependency)) {
1528 config->manifestDependency = arg->getValue();
1529 config->manifest = Configuration::SideBySide;
1532 // Handle /manifest and /manifest:
1533 if (auto *arg = args.getLastArg(OPT_manifest, OPT_manifest_colon)) {
1534 if (arg->getOption().getID() == OPT_manifest)
1535 config->manifest = Configuration::SideBySide;
1537 parseManifest(arg->getValue());
1540 // Handle /manifestuac
1541 if (auto *arg = args.getLastArg(OPT_manifestuac))
1542 parseManifestUAC(arg->getValue());
1544 // Handle /manifestfile
1545 if (auto *arg = args.getLastArg(OPT_manifestfile))
1546 config->manifestFile = arg->getValue();
1548 // Handle /manifestinput
1549 for (auto *arg : args.filtered(OPT_manifestinput))
1550 config->manifestInput.push_back(arg->getValue());
1552 if (!config->manifestInput.empty() &&
1553 config->manifest != Configuration::Embed) {
1554 fatal("/manifestinput: requires /manifest:embed");
1557 config->thinLTOEmitImportsFiles = args.hasArg(OPT_thinlto_emit_imports_files);
1558 config->thinLTOIndexOnly = args.hasArg(OPT_thinlto_index_only) ||
1559 args.hasArg(OPT_thinlto_index_only_arg);
1560 config->thinLTOIndexOnlyArg =
1561 args.getLastArgValue(OPT_thinlto_index_only_arg);
1562 config->thinLTOPrefixReplace =
1563 getOldNewOptions(args, OPT_thinlto_prefix_replace);
1564 config->thinLTOObjectSuffixReplace =
1565 getOldNewOptions(args, OPT_thinlto_object_suffix_replace);
1566 config->ltoObjPath = args.getLastArgValue(OPT_lto_obj_path);
1567 // Handle miscellaneous boolean flags.
1568 config->allowBind = args.hasFlag(OPT_allowbind, OPT_allowbind_no, true);
1569 config->allowIsolation =
1570 args.hasFlag(OPT_allowisolation, OPT_allowisolation_no, true);
1571 config->incremental =
1572 args.hasFlag(OPT_incremental, OPT_incremental_no,
1573 !config->doGC && !config->doICF && !args.hasArg(OPT_order) &&
1574 !args.hasArg(OPT_profile));
1575 config->integrityCheck =
1576 args.hasFlag(OPT_integritycheck, OPT_integritycheck_no, false);
1577 config->cetCompat = args.hasFlag(OPT_cetcompat, OPT_cetcompat_no, false);
1578 config->nxCompat = args.hasFlag(OPT_nxcompat, OPT_nxcompat_no, true);
1579 for (auto *arg : args.filtered(OPT_swaprun))
1580 parseSwaprun(arg->getValue());
1581 config->terminalServerAware =
1582 !config->dll && args.hasFlag(OPT_tsaware, OPT_tsaware_no, true);
1583 config->debugDwarf = debug == DebugKind::Dwarf;
1584 config->debugGHashes = debug == DebugKind::GHash;
1585 config->debugSymtab = debug == DebugKind::Symtab;
1586 config->autoImport =
1587 args.hasFlag(OPT_auto_import, OPT_auto_import_no, config->mingw);
1588 config->pseudoRelocs = args.hasFlag(
1589 OPT_runtime_pseudo_reloc, OPT_runtime_pseudo_reloc_no, config->mingw);
1591 // Don't warn about long section names, such as .debug_info, for mingw or when
1592 // -debug:dwarf is requested.
1593 if (config->mingw || config->debugDwarf)
1594 config->warnLongSectionNames = false;
1596 config->lldmapFile = getMapFile(args, OPT_lldmap, OPT_lldmap_file);
1597 config->mapFile = getMapFile(args, OPT_map, OPT_map_file);
1599 if (config->lldmapFile != "" && config->lldmapFile == config->mapFile) {
1600 warn("/lldmap and /map have the same output file '" + config->mapFile +
1601 "'.\n>>> ignoring /lldmap");
1602 config->lldmapFile.clear();
1605 if (config->incremental && args.hasArg(OPT_profile)) {
1606 warn("ignoring '/incremental' due to '/profile' specification");
1607 config->incremental = false;
1610 if (config->incremental && args.hasArg(OPT_order)) {
1611 warn("ignoring '/incremental' due to '/order' specification");
1612 config->incremental = false;
1615 if (config->incremental && config->doGC) {
1616 warn("ignoring '/incremental' because REF is enabled; use '/opt:noref' to "
1618 config->incremental = false;
1621 if (config->incremental && config->doICF) {
1622 warn("ignoring '/incremental' because ICF is enabled; use '/opt:noicf' to "
1624 config->incremental = false;
1630 std::set<sys::fs::UniqueID> wholeArchives;
1631 for (auto *arg : args.filtered(OPT_wholearchive_file))
1632 if (Optional<StringRef> path = doFindFile(arg->getValue()))
1633 if (Optional<sys::fs::UniqueID> id = getUniqueID(*path))
1634 wholeArchives.insert(*id);
1636 // A predicate returning true if a given path is an argument for
1637 // /wholearchive:, or /wholearchive is enabled globally.
1638 // This function is a bit tricky because "foo.obj /wholearchive:././foo.obj"
1639 // needs to be handled as "/wholearchive:foo.obj foo.obj".
1640 auto isWholeArchive = [&](StringRef path) -> bool {
1641 if (args.hasArg(OPT_wholearchive_flag))
1643 if (Optional<sys::fs::UniqueID> id = getUniqueID(path))
1644 return wholeArchives.count(*id);
1648 // Create a list of input files. These can be given as OPT_INPUT options
1649 // and OPT_wholearchive_file options, and we also need to track OPT_start_lib
1652 for (auto *arg : args) {
1653 switch (arg->getOption().getID()) {
1656 error("stray " + arg->getSpelling());
1661 error("nested " + arg->getSpelling());
1664 case OPT_wholearchive_file:
1665 if (Optional<StringRef> path = findFile(arg->getValue()))
1666 enqueuePath(*path, true, inLib);
1669 if (Optional<StringRef> path = findFile(arg->getValue()))
1670 enqueuePath(*path, isWholeArchive(*path), inLib);
1673 // Ignore other options.
1678 // Process files specified as /defaultlib. These should be enequeued after
1679 // other files, which is why they are in a separate loop.
1680 for (auto *arg : args.filtered(OPT_defaultlib))
1681 if (Optional<StringRef> path = findLib(arg->getValue()))
1682 enqueuePath(*path, false, false);
1684 // Windows specific -- Create a resource file containing a manifest file.
1685 if (config->manifest == Configuration::Embed)
1686 addBuffer(createManifestRes(), false, false);
1688 // Read all input files given via the command line.
1694 // We should have inferred a machine type by now from the input files, but if
1695 // not we assume x64.
1696 if (config->machine == IMAGE_FILE_MACHINE_UNKNOWN) {
1697 warn("/machine is not specified. x64 is assumed");
1698 config->machine = AMD64;
1700 config->wordsize = config->is64() ? 8 : 4;
1702 // Handle /safeseh, x86 only, on by default, except for mingw.
1703 if (config->machine == I386 &&
1704 args.hasFlag(OPT_safeseh, OPT_safeseh_no, !config->mingw))
1705 config->safeSEH = true;
1707 // Handle /functionpadmin
1708 for (auto *arg : args.filtered(OPT_functionpadmin, OPT_functionpadmin_opt))
1709 parseFunctionPadMin(arg, config->machine);
1712 tar->append("response.txt",
1713 createResponseFile(args, filePaths,
1714 ArrayRef<StringRef>(searchPaths).slice(1)));
1716 // Handle /largeaddressaware
1717 config->largeAddressAware = args.hasFlag(
1718 OPT_largeaddressaware, OPT_largeaddressaware_no, config->is64());
1720 // Handle /highentropyva
1721 config->highEntropyVA =
1723 args.hasFlag(OPT_highentropyva, OPT_highentropyva_no, true);
1725 if (!config->dynamicBase &&
1726 (config->machine == ARMNT || config->machine == ARM64))
1727 error("/dynamicbase:no is not compatible with " +
1728 machineToStr(config->machine));
1731 for (auto *arg : args.filtered(OPT_export)) {
1732 Export e = parseExport(arg->getValue());
1733 if (config->machine == I386) {
1734 if (!isDecorated(e.name))
1735 e.name = saver.save("_" + e.name);
1736 if (!e.extName.empty() && !isDecorated(e.extName))
1737 e.extName = saver.save("_" + e.extName);
1739 config->exports.push_back(e);
1743 if (auto *arg = args.getLastArg(OPT_deffile)) {
1744 // parseModuleDefs mutates Config object.
1745 parseModuleDefs(arg->getValue());
1748 // Handle generation of import library from a def file.
1749 if (!args.hasArg(OPT_INPUT, OPT_wholearchive_file)) {
1751 createImportLibrary(/*asLib=*/true);
1755 // Windows specific -- if no /subsystem is given, we need to infer
1756 // that from entry point name. Must happen before /entry handling,
1757 // and after the early return when just writing an import library.
1758 if (config->subsystem == IMAGE_SUBSYSTEM_UNKNOWN) {
1759 config->subsystem = inferSubsystem();
1760 if (config->subsystem == IMAGE_SUBSYSTEM_UNKNOWN)
1761 fatal("subsystem must be defined");
1764 // Handle /entry and /dll
1765 if (auto *arg = args.getLastArg(OPT_entry)) {
1766 config->entry = addUndefined(mangle(arg->getValue()));
1767 } else if (!config->entry && !config->noEntry) {
1768 if (args.hasArg(OPT_dll)) {
1769 StringRef s = (config->machine == I386) ? "__DllMainCRTStartup@12"
1770 : "_DllMainCRTStartup";
1771 config->entry = addUndefined(s);
1772 } else if (config->driverWdm) {
1773 // /driver:wdm implies /entry:_NtProcessStartup
1774 config->entry = addUndefined(mangle("_NtProcessStartup"));
1776 // Windows specific -- If entry point name is not given, we need to
1777 // infer that from user-defined entry name.
1778 StringRef s = findDefaultEntry();
1780 fatal("entry point must be defined");
1781 config->entry = addUndefined(s);
1782 log("Entry name inferred: " + s);
1786 // Handle /delayload
1787 for (auto *arg : args.filtered(OPT_delayload)) {
1788 config->delayLoads.insert(StringRef(arg->getValue()).lower());
1789 if (config->machine == I386) {
1790 config->delayLoadHelper = addUndefined("___delayLoadHelper2@8");
1792 config->delayLoadHelper = addUndefined("__delayLoadHelper2");
1796 // Set default image name if neither /out or /def set it.
1797 if (config->outputFile.empty()) {
1798 config->outputFile = getOutputPath(
1799 (*args.filtered(OPT_INPUT, OPT_wholearchive_file).begin())->getValue());
1802 // Fail early if an output file is not writable.
1803 if (auto e = tryCreateFile(config->outputFile)) {
1804 error("cannot open output file " + config->outputFile + ": " + e.message());
1808 if (shouldCreatePDB) {
1809 // Put the PDB next to the image if no /pdb flag was passed.
1810 if (config->pdbPath.empty()) {
1811 config->pdbPath = config->outputFile;
1812 sys::path::replace_extension(config->pdbPath, ".pdb");
1815 // The embedded PDB path should be the absolute path to the PDB if no
1816 // /pdbaltpath flag was passed.
1817 if (config->pdbAltPath.empty()) {
1818 config->pdbAltPath = config->pdbPath;
1820 // It's important to make the path absolute and remove dots. This path
1821 // will eventually be written into the PE header, and certain Microsoft
1822 // tools won't work correctly if these assumptions are not held.
1823 sys::fs::make_absolute(config->pdbAltPath);
1824 sys::path::remove_dots(config->pdbAltPath);
1826 // Don't do this earlier, so that Config->OutputFile is ready.
1827 parsePDBAltPath(config->pdbAltPath);
1831 // Set default image base if /base is not given.
1832 if (config->imageBase == uint64_t(-1))
1833 config->imageBase = getDefaultImageBase();
1835 symtab->addSynthetic(mangle("__ImageBase"), nullptr);
1836 if (config->machine == I386) {
1837 symtab->addAbsolute("___safe_se_handler_table", 0);
1838 symtab->addAbsolute("___safe_se_handler_count", 0);
1841 symtab->addAbsolute(mangle("__guard_fids_count"), 0);
1842 symtab->addAbsolute(mangle("__guard_fids_table"), 0);
1843 symtab->addAbsolute(mangle("__guard_flags"), 0);
1844 symtab->addAbsolute(mangle("__guard_iat_count"), 0);
1845 symtab->addAbsolute(mangle("__guard_iat_table"), 0);
1846 symtab->addAbsolute(mangle("__guard_longjmp_count"), 0);
1847 symtab->addAbsolute(mangle("__guard_longjmp_table"), 0);
1848 // Needed for MSVC 2017 15.5 CRT.
1849 symtab->addAbsolute(mangle("__enclave_config"), 0);
1851 if (config->pseudoRelocs) {
1852 symtab->addAbsolute(mangle("__RUNTIME_PSEUDO_RELOC_LIST__"), 0);
1853 symtab->addAbsolute(mangle("__RUNTIME_PSEUDO_RELOC_LIST_END__"), 0);
1855 if (config->mingw) {
1856 symtab->addAbsolute(mangle("__CTOR_LIST__"), 0);
1857 symtab->addAbsolute(mangle("__DTOR_LIST__"), 0);
1860 // This code may add new undefined symbols to the link, which may enqueue more
1861 // symbol resolution tasks, so we need to continue executing tasks until we
1864 // Windows specific -- if entry point is not found,
1865 // search for its mangled names.
1867 mangleMaybe(config->entry);
1869 // Windows specific -- Make sure we resolve all dllexported symbols.
1870 for (Export &e : config->exports) {
1871 if (!e.forwardTo.empty())
1873 e.sym = addUndefined(e.name);
1875 e.symbolName = mangleMaybe(e.sym);
1878 // Add weak aliases. Weak aliases is a mechanism to give remaining
1879 // undefined symbols final chance to be resolved successfully.
1880 for (auto pair : config->alternateNames) {
1881 StringRef from = pair.first;
1882 StringRef to = pair.second;
1883 Symbol *sym = symtab->find(from);
1886 if (auto *u = dyn_cast<Undefined>(sym))
1888 u->weakAlias = symtab->addUndefined(to);
1891 // If any inputs are bitcode files, the LTO code generator may create
1892 // references to library functions that are not explicit in the bitcode
1893 // file's symbol table. If any of those library functions are defined in a
1894 // bitcode file in an archive member, we need to arrange to use LTO to
1895 // compile those archive members by adding them to the link beforehand.
1896 if (!BitcodeFile::instances.empty())
1897 for (auto *s : lto::LTO::getRuntimeLibcallSymbols())
1898 symtab->addLibcall(s);
1900 // Windows specific -- if __load_config_used can be resolved, resolve it.
1901 if (symtab->findUnderscore("_load_config_used"))
1902 addUndefined(mangle("_load_config_used"));
1905 if (args.hasArg(OPT_include_optional)) {
1906 // Handle /includeoptional
1907 for (auto *arg : args.filtered(OPT_include_optional))
1908 if (dyn_cast_or_null<LazyArchive>(symtab->find(arg->getValue())))
1909 addUndefined(arg->getValue());
1913 if (config->autoImport) {
1915 // Load any further object files that might be needed for doing automatic
1918 // For cases with no automatically imported symbols, this iterates once
1919 // over the symbol table and doesn't do anything.
1921 // For the normal case with a few automatically imported symbols, this
1922 // should only need to be run once, since each new object file imported
1923 // is an import library and wouldn't add any new undefined references,
1924 // but there's nothing stopping the __imp_ symbols from coming from a
1925 // normal object file as well (although that won't be used for the
1926 // actual autoimport later on). If this pass adds new undefined references,
1927 // we won't iterate further to resolve them.
1928 symtab->loadMinGWAutomaticImports();
1932 // At this point, we should not have any symbols that cannot be resolved.
1933 // If we are going to do codegen for link-time optimization, check for
1934 // unresolvable symbols first, so we don't spend time generating code that
1935 // will fail to link anyway.
1936 if (!BitcodeFile::instances.empty() && !config->forceUnresolved)
1937 symtab->reportUnresolvable();
1941 // Do LTO by compiling bitcode input files to a set of native COFF files then
1942 // link those files (unless -thinlto-index-only was given, in which case we
1943 // resolve symbols and write indices, but don't generate native code or link).
1944 symtab->addCombinedLTOObjects();
1946 // If -thinlto-index-only is given, we should create only "index
1947 // files" and not object files. Index file creation is already done
1948 // in addCombinedLTOObject, so we are done if that's the case.
1949 if (config->thinLTOIndexOnly)
1952 // If we generated native object files from bitcode files, this resolves
1953 // references to the symbols we use from them.
1956 // Resolve remaining undefined symbols and warn about imported locals.
1957 symtab->resolveRemainingUndefines();
1961 config->hadExplicitExports = !config->exports.empty();
1962 if (config->mingw) {
1963 // In MinGW, all symbols are automatically exported if no symbols
1964 // are chosen to be exported.
1965 maybeExportMinGWSymbols(args);
1967 // Make sure the crtend.o object is the last object file. This object
1968 // file can contain terminating section chunks that need to be placed
1969 // last. GNU ld processes files and static libraries explicitly in the
1970 // order provided on the command line, while lld will pull in needed
1971 // files from static libraries only after the last object file on the
1973 for (auto i = ObjFile::instances.begin(), e = ObjFile::instances.end();
1976 if (isCrtend(file->getName())) {
1977 ObjFile::instances.erase(i);
1978 ObjFile::instances.push_back(file);
1984 // Windows specific -- when we are creating a .dll file, we also
1985 // need to create a .lib file. In MinGW mode, we only do that when the
1986 // -implib option is given explicitly, for compatibility with GNU ld.
1987 if (!config->exports.empty() || config->dll) {
1989 if (!config->mingw || !config->implib.empty())
1990 createImportLibrary(/*asLib=*/false);
1991 assignExportOrdinals();
1994 // Handle /output-def (MinGW specific).
1995 if (auto *arg = args.getLastArg(OPT_output_def))
1996 writeDefFile(arg->getValue());
1998 // Set extra alignment for .comm symbols
1999 for (auto pair : config->alignComm) {
2000 StringRef name = pair.first;
2001 uint32_t alignment = pair.second;
2003 Symbol *sym = symtab->find(name);
2005 warn("/aligncomm symbol " + name + " not found");
2009 // If the symbol isn't common, it must have been replaced with a regular
2010 // symbol, which will carry its own alignment.
2011 auto *dc = dyn_cast<DefinedCommon>(sym);
2015 CommonChunk *c = dc->getChunk();
2016 c->setAlignment(std::max(c->getAlignment(), alignment));
2019 // Windows specific -- Create a side-by-side manifest file.
2020 if (config->manifest == Configuration::SideBySide)
2021 createSideBySideManifest();
2023 // Handle /order. We want to do this at this moment because we
2024 // need a complete list of comdat sections to warn on nonexistent
2026 if (auto *arg = args.getLastArg(OPT_order))
2027 parseOrderFile(arg->getValue());
2029 // Identify unreferenced COMDAT sections.
2031 markLive(symtab->getChunks());
2033 // Needs to happen after the last call to addFile().
2036 // Identify identical COMDAT sections to merge them.
2037 if (config->doICF) {
2038 findKeepUniqueSections();
2039 doICF(symtab->getChunks());
2042 // Write the result.
2045 // Stop early so we can print the results.
2047 if (config->showTiming)
2048 Timer::root().print();