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/LTO/LTO.h"
31 #include "llvm/Object/ArchiveWriter.h"
32 #include "llvm/Object/COFFImportFile.h"
33 #include "llvm/Object/COFFModuleDefinition.h"
34 #include "llvm/Object/WindowsMachineFlag.h"
35 #include "llvm/Option/Arg.h"
36 #include "llvm/Option/ArgList.h"
37 #include "llvm/Option/Option.h"
38 #include "llvm/Support/Debug.h"
39 #include "llvm/Support/LEB128.h"
40 #include "llvm/Support/MathExtras.h"
41 #include "llvm/Support/Path.h"
42 #include "llvm/Support/Process.h"
43 #include "llvm/Support/TarWriter.h"
44 #include "llvm/Support/TargetSelect.h"
45 #include "llvm/Support/raw_ostream.h"
46 #include "llvm/ToolDrivers/llvm-lib/LibDriver.h"
52 using namespace llvm::object;
53 using namespace llvm::COFF;
54 using llvm::sys::Process;
59 static Timer inputFileTimer("Input File Reading", Timer::root());
61 Configuration *config;
64 bool link(ArrayRef<const char *> args, bool canExitEarly, raw_ostream &diag) {
65 errorHandler().logName = args::getFilenameWithoutExe(args[0]);
66 errorHandler().errorOS = &diag;
67 errorHandler().errorLimitExceededMsg =
68 "too many errors emitted, stopping now"
69 " (use /errorlimit:0 to see all errors)";
70 errorHandler().exitEarly = canExitEarly;
71 enableColors(diag.has_colors());
73 config = make<Configuration>();
74 symtab = make<SymbolTable>();
75 driver = make<LinkerDriver>();
79 // Call exit() if we can to avoid calling destructors.
81 exitLld(errorCount() ? 1 : 0);
84 ObjFile::instances.clear();
85 ImportFile::instances.clear();
86 BitcodeFile::instances.clear();
87 memset(MergeChunk::instances, 0, sizeof(MergeChunk::instances));
91 // Parse options of the form "old;new".
92 static std::pair<StringRef, StringRef> getOldNewOptions(opt::InputArgList &args,
94 auto *arg = args.getLastArg(id);
98 StringRef s = arg->getValue();
99 std::pair<StringRef, StringRef> ret = s.split(';');
100 if (ret.second.empty())
101 error(arg->getSpelling() + " expects 'old;new' format, but got " + s);
105 // Drop directory components and replace extension with ".exe" or ".dll".
106 static std::string getOutputPath(StringRef path) {
107 auto p = path.find_last_of("\\/");
108 StringRef s = (p == StringRef::npos) ? path : path.substr(p + 1);
109 const char* e = config->dll ? ".dll" : ".exe";
110 return (s.substr(0, s.rfind('.')) + e).str();
113 // Returns true if S matches /crtend.?\.o$/.
114 static bool isCrtend(StringRef s) {
115 if (!s.endswith(".o"))
118 if (s.endswith("crtend"))
120 return !s.empty() && s.drop_back().endswith("crtend");
123 // ErrorOr is not default constructible, so it cannot be used as the type
124 // parameter of a future.
125 // FIXME: We could open the file in createFutureForFile and avoid needing to
126 // return an error here, but for the moment that would cost us a file descriptor
127 // (a limited resource on Windows) for the duration that the future is pending.
128 using MBErrPair = std::pair<std::unique_ptr<MemoryBuffer>, std::error_code>;
130 // Create a std::future that opens and maps a file using the best strategy for
131 // the host platform.
132 static std::future<MBErrPair> createFutureForFile(std::string path) {
134 // On Windows, file I/O is relatively slow so it is best to do this
136 auto strategy = std::launch::async;
138 auto strategy = std::launch::deferred;
140 return std::async(strategy, [=]() {
141 auto mbOrErr = MemoryBuffer::getFile(path,
143 /*RequiresNullTerminator*/ false);
145 return MBErrPair{nullptr, mbOrErr.getError()};
146 return MBErrPair{std::move(*mbOrErr), std::error_code()};
150 // Symbol names are mangled by prepending "_" on x86.
151 static StringRef mangle(StringRef sym) {
152 assert(config->machine != IMAGE_FILE_MACHINE_UNKNOWN);
153 if (config->machine == I386)
154 return saver.save("_" + sym);
158 static bool findUnderscoreMangle(StringRef sym) {
159 Symbol *s = symtab->findMangle(mangle(sym));
160 return s && !isa<Undefined>(s);
163 MemoryBufferRef LinkerDriver::takeBuffer(std::unique_ptr<MemoryBuffer> mb) {
164 MemoryBufferRef mbref = *mb;
165 make<std::unique_ptr<MemoryBuffer>>(std::move(mb)); // take ownership
168 driver->tar->append(relativeToRoot(mbref.getBufferIdentifier()),
173 void LinkerDriver::addBuffer(std::unique_ptr<MemoryBuffer> mb,
174 bool wholeArchive, bool lazy) {
175 StringRef filename = mb->getBufferIdentifier();
177 MemoryBufferRef mbref = takeBuffer(std::move(mb));
178 filePaths.push_back(filename);
180 // File type is detected by contents, not by file extension.
181 switch (identify_magic(mbref.getBuffer())) {
182 case file_magic::windows_resource:
183 resources.push_back(mbref);
185 case file_magic::archive:
187 std::unique_ptr<Archive> file =
188 CHECK(Archive::create(mbref), filename + ": failed to parse archive");
189 Archive *archive = file.get();
190 make<std::unique_ptr<Archive>>(std::move(file)); // take ownership
193 for (MemoryBufferRef m : getArchiveMembers(archive))
194 addArchiveBuffer(m, "<whole-archive>", filename, memberIndex++);
197 symtab->addFile(make<ArchiveFile>(mbref));
199 case file_magic::bitcode:
201 symtab->addFile(make<LazyObjFile>(mbref));
203 symtab->addFile(make<BitcodeFile>(mbref, "", 0));
205 case file_magic::coff_object:
206 case file_magic::coff_import_library:
208 symtab->addFile(make<LazyObjFile>(mbref));
210 symtab->addFile(make<ObjFile>(mbref));
212 case file_magic::pdb:
213 loadTypeServerSource(mbref);
215 case file_magic::coff_cl_gl_object:
216 error(filename + ": is not a native COFF file. Recompile without /GL");
218 case file_magic::pecoff_executable:
219 if (filename.endswith_lower(".dll")) {
220 error(filename + ": bad file type. Did you specify a DLL instead of an "
226 error(mbref.getBufferIdentifier() + ": unknown file type");
231 void LinkerDriver::enqueuePath(StringRef path, bool wholeArchive, bool lazy) {
233 std::make_shared<std::future<MBErrPair>>(createFutureForFile(path));
234 std::string pathStr = path;
236 auto mbOrErr = future->get();
237 if (mbOrErr.second) {
239 "could not open '" + pathStr + "': " + mbOrErr.second.message();
240 // Check if the filename is a typo for an option flag. OptTable thinks
241 // that all args that are not known options and that start with / are
242 // filenames, but e.g. `/nodefaultlibs` is more likely a typo for
243 // the option `/nodefaultlib` than a reference to a file in the root
246 if (COFFOptTable().findNearest(pathStr, nearest) > 1)
249 error(msg + "; did you mean '" + nearest + "'");
251 driver->addBuffer(std::move(mbOrErr.first), wholeArchive, lazy);
255 void LinkerDriver::addArchiveBuffer(MemoryBufferRef mb, StringRef symName,
256 StringRef parentName,
257 uint64_t offsetInArchive) {
258 file_magic magic = identify_magic(mb.getBuffer());
259 if (magic == file_magic::coff_import_library) {
260 InputFile *imp = make<ImportFile>(mb);
261 imp->parentName = parentName;
262 symtab->addFile(imp);
267 if (magic == file_magic::coff_object) {
268 obj = make<ObjFile>(mb);
269 } else if (magic == file_magic::bitcode) {
270 obj = make<BitcodeFile>(mb, parentName, offsetInArchive);
272 error("unknown file type: " + mb.getBufferIdentifier());
276 obj->parentName = parentName;
277 symtab->addFile(obj);
278 log("Loaded " + toString(obj) + " for " + symName);
281 void LinkerDriver::enqueueArchiveMember(const Archive::Child &c,
282 const Archive::Symbol &sym,
283 StringRef parentName) {
285 auto reportBufferError = [=](Error &&e, StringRef childName) {
286 fatal("could not get the buffer for the member defining symbol " +
287 toCOFFString(sym) + ": " + parentName + "(" + childName + "): " +
288 toString(std::move(e)));
291 if (!c.getParent()->isThin()) {
292 uint64_t offsetInArchive = c.getChildOffset();
293 Expected<MemoryBufferRef> mbOrErr = c.getMemoryBufferRef();
295 reportBufferError(mbOrErr.takeError(), check(c.getFullName()));
296 MemoryBufferRef mb = mbOrErr.get();
298 driver->addArchiveBuffer(mb, toCOFFString(sym), parentName,
304 std::string childName = CHECK(
306 "could not get the filename for the member defining symbol " +
308 auto future = std::make_shared<std::future<MBErrPair>>(
309 createFutureForFile(childName));
311 auto mbOrErr = future->get();
313 reportBufferError(errorCodeToError(mbOrErr.second), childName);
314 // Pass empty string as archive name so that the original filename is
315 // used as the buffer identifier.
316 driver->addArchiveBuffer(takeBuffer(std::move(mbOrErr.first)),
317 toCOFFString(sym), "", /*OffsetInArchive=*/0);
321 static bool isDecorated(StringRef sym) {
322 return sym.startswith("@") || sym.contains("@@") || sym.startswith("?") ||
323 (!config->mingw && sym.contains('@'));
326 // Parses .drectve section contents and returns a list of files
327 // specified by /defaultlib.
328 void LinkerDriver::parseDirectives(InputFile *file) {
329 StringRef s = file->getDirectives();
333 log("Directives: " + toString(file) + ": " + s);
336 // .drectve is always tokenized using Windows shell rules.
337 // /EXPORT: option can appear too many times, processing in fastpath.
338 opt::InputArgList args;
339 std::vector<StringRef> exports;
340 std::tie(args, exports) = parser.parseDirectives(s);
342 for (StringRef e : exports) {
343 // If a common header file contains dllexported function
344 // declarations, many object files may end up with having the
345 // same /EXPORT options. In order to save cost of parsing them,
346 // we dedup them first.
347 if (!directivesExports.insert(e).second)
350 Export exp = parseExport(e);
351 if (config->machine == I386 && config->mingw) {
352 if (!isDecorated(exp.name))
353 exp.name = saver.save("_" + exp.name);
354 if (!exp.extName.empty() && !isDecorated(exp.extName))
355 exp.extName = saver.save("_" + exp.extName);
357 exp.directives = true;
358 config->exports.push_back(exp);
361 for (auto *arg : args) {
362 switch (arg->getOption().getID()) {
364 parseAligncomm(arg->getValue());
366 case OPT_alternatename:
367 parseAlternateName(arg->getValue());
370 if (Optional<StringRef> path = findLib(arg->getValue()))
371 enqueuePath(*path, false, false);
374 config->entry = addUndefined(mangle(arg->getValue()));
376 case OPT_failifmismatch:
377 checkFailIfMismatch(arg->getValue(), file);
380 addUndefined(arg->getValue());
383 parseMerge(arg->getValue());
385 case OPT_nodefaultlib:
386 config->noDefaultLibs.insert(doFindLib(arg->getValue()).lower());
389 parseSection(arg->getValue());
392 parseSubsystem(arg->getValue(), &config->subsystem,
393 &config->majorOSVersion, &config->minorOSVersion);
395 // Only add flags here that link.exe accepts in
396 // `#pragma comment(linker, "/flag")`-generated sections.
397 case OPT_editandcontinue:
399 case OPT_throwingnew:
402 error(arg->getSpelling() + " is not allowed in .drectve");
407 // Find file from search paths. You can omit ".obj", this function takes
408 // care of that. Note that the returned path is not guaranteed to exist.
409 StringRef LinkerDriver::doFindFile(StringRef filename) {
410 bool hasPathSep = (filename.find_first_of("/\\") != StringRef::npos);
413 bool hasExt = filename.contains('.');
414 for (StringRef dir : searchPaths) {
415 SmallString<128> path = dir;
416 sys::path::append(path, filename);
417 if (sys::fs::exists(path.str()))
418 return saver.save(path.str());
421 if (sys::fs::exists(path.str()))
422 return saver.save(path.str());
428 static Optional<sys::fs::UniqueID> getUniqueID(StringRef path) {
429 sys::fs::UniqueID ret;
430 if (sys::fs::getUniqueID(path, ret))
435 // Resolves a file path. This never returns the same path
436 // (in that case, it returns None).
437 Optional<StringRef> LinkerDriver::findFile(StringRef filename) {
438 StringRef path = doFindFile(filename);
440 if (Optional<sys::fs::UniqueID> id = getUniqueID(path)) {
441 bool seen = !visitedFiles.insert(*id).second;
446 if (path.endswith_lower(".lib"))
447 visitedLibs.insert(sys::path::filename(path));
451 // MinGW specific. If an embedded directive specified to link to
452 // foo.lib, but it isn't found, try libfoo.a instead.
453 StringRef LinkerDriver::doFindLibMinGW(StringRef filename) {
454 if (filename.contains('/') || filename.contains('\\'))
457 SmallString<128> s = filename;
458 sys::path::replace_extension(s, ".a");
459 StringRef libName = saver.save("lib" + s.str());
460 return doFindFile(libName);
463 // Find library file from search path.
464 StringRef LinkerDriver::doFindLib(StringRef filename) {
465 // Add ".lib" to Filename if that has no file extension.
466 bool hasExt = filename.contains('.');
468 filename = saver.save(filename + ".lib");
469 StringRef ret = doFindFile(filename);
470 // For MinGW, if the find above didn't turn up anything, try
471 // looking for a MinGW formatted library name.
472 if (config->mingw && ret == filename)
473 return doFindLibMinGW(filename);
477 // Resolves a library path. /nodefaultlib options are taken into
478 // consideration. This never returns the same path (in that case,
480 Optional<StringRef> LinkerDriver::findLib(StringRef filename) {
481 if (config->noDefaultLibAll)
483 if (!visitedLibs.insert(filename.lower()).second)
486 StringRef path = doFindLib(filename);
487 if (config->noDefaultLibs.count(path.lower()))
490 if (Optional<sys::fs::UniqueID> id = getUniqueID(path))
491 if (!visitedFiles.insert(*id).second)
496 // Parses LIB environment which contains a list of search paths.
497 void LinkerDriver::addLibSearchPaths() {
498 Optional<std::string> envOpt = Process::GetEnv("LIB");
499 if (!envOpt.hasValue())
501 StringRef env = saver.save(*envOpt);
502 while (!env.empty()) {
504 std::tie(path, env) = env.split(';');
505 searchPaths.push_back(path);
509 Symbol *LinkerDriver::addUndefined(StringRef name) {
510 Symbol *b = symtab->addUndefined(name);
513 config->gcroot.push_back(b);
518 StringRef LinkerDriver::mangleMaybe(Symbol *s) {
519 // If the plain symbol name has already been resolved, do nothing.
520 Undefined *unmangled = dyn_cast<Undefined>(s);
524 // Otherwise, see if a similar, mangled symbol exists in the symbol table.
525 Symbol *mangled = symtab->findMangle(unmangled->getName());
529 // If we find a similar mangled symbol, make this an alias to it and return
531 log(unmangled->getName() + " aliased to " + mangled->getName());
532 unmangled->weakAlias = symtab->addUndefined(mangled->getName());
533 return mangled->getName();
536 // Windows specific -- find default entry point name.
538 // There are four different entry point functions for Windows executables,
539 // each of which corresponds to a user-defined "main" function. This function
540 // infers an entry point from a user-defined "main" function.
541 StringRef LinkerDriver::findDefaultEntry() {
542 assert(config->subsystem != IMAGE_SUBSYSTEM_UNKNOWN &&
543 "must handle /subsystem before calling this");
546 return mangle(config->subsystem == IMAGE_SUBSYSTEM_WINDOWS_GUI
547 ? "WinMainCRTStartup"
550 if (config->subsystem == IMAGE_SUBSYSTEM_WINDOWS_GUI) {
551 if (findUnderscoreMangle("wWinMain")) {
552 if (!findUnderscoreMangle("WinMain"))
553 return mangle("wWinMainCRTStartup");
554 warn("found both wWinMain and WinMain; using latter");
556 return mangle("WinMainCRTStartup");
558 if (findUnderscoreMangle("wmain")) {
559 if (!findUnderscoreMangle("main"))
560 return mangle("wmainCRTStartup");
561 warn("found both wmain and main; using latter");
563 return mangle("mainCRTStartup");
566 WindowsSubsystem LinkerDriver::inferSubsystem() {
568 return IMAGE_SUBSYSTEM_WINDOWS_GUI;
570 return IMAGE_SUBSYSTEM_WINDOWS_CUI;
571 // Note that link.exe infers the subsystem from the presence of these
572 // functions even if /entry: or /nodefaultlib are passed which causes them
574 bool haveMain = findUnderscoreMangle("main");
575 bool haveWMain = findUnderscoreMangle("wmain");
576 bool haveWinMain = findUnderscoreMangle("WinMain");
577 bool haveWWinMain = findUnderscoreMangle("wWinMain");
578 if (haveMain || haveWMain) {
579 if (haveWinMain || haveWWinMain) {
580 warn(std::string("found ") + (haveMain ? "main" : "wmain") + " and " +
581 (haveWinMain ? "WinMain" : "wWinMain") +
582 "; defaulting to /subsystem:console");
584 return IMAGE_SUBSYSTEM_WINDOWS_CUI;
586 if (haveWinMain || haveWWinMain)
587 return IMAGE_SUBSYSTEM_WINDOWS_GUI;
588 return IMAGE_SUBSYSTEM_UNKNOWN;
591 static uint64_t getDefaultImageBase() {
593 return config->dll ? 0x180000000 : 0x140000000;
594 return config->dll ? 0x10000000 : 0x400000;
597 static std::string createResponseFile(const opt::InputArgList &args,
598 ArrayRef<StringRef> filePaths,
599 ArrayRef<StringRef> searchPaths) {
601 raw_svector_ostream os(data);
603 for (auto *arg : args) {
604 switch (arg->getOption().getID()) {
611 case OPT_manifest_colon:
612 case OPT_manifestdependency:
613 case OPT_manifestfile:
614 case OPT_manifestinput:
615 case OPT_manifestuac:
620 os << arg->getSpelling() << sys::path::filename(arg->getValue()) << "\n";
623 os << toString(*arg) << "\n";
627 for (StringRef path : searchPaths) {
628 std::string relPath = relativeToRoot(path);
629 os << "/libpath:" << quote(relPath) << "\n";
632 for (StringRef path : filePaths)
633 os << quote(relativeToRoot(path)) << "\n";
638 enum class DebugKind { Unknown, None, Full, FastLink, GHash, Dwarf, Symtab };
640 static DebugKind parseDebugKind(const opt::InputArgList &args) {
641 auto *a = args.getLastArg(OPT_debug, OPT_debug_opt);
643 return DebugKind::None;
644 if (a->getNumValues() == 0)
645 return DebugKind::Full;
647 DebugKind debug = StringSwitch<DebugKind>(a->getValue())
648 .CaseLower("none", DebugKind::None)
649 .CaseLower("full", DebugKind::Full)
650 .CaseLower("fastlink", DebugKind::FastLink)
652 .CaseLower("ghash", DebugKind::GHash)
653 .CaseLower("dwarf", DebugKind::Dwarf)
654 .CaseLower("symtab", DebugKind::Symtab)
655 .Default(DebugKind::Unknown);
657 if (debug == DebugKind::FastLink) {
658 warn("/debug:fastlink unsupported; using /debug:full");
659 return DebugKind::Full;
661 if (debug == DebugKind::Unknown) {
662 error("/debug: unknown option: " + Twine(a->getValue()));
663 return DebugKind::None;
668 static unsigned parseDebugTypes(const opt::InputArgList &args) {
669 unsigned debugTypes = static_cast<unsigned>(DebugType::None);
671 if (auto *a = args.getLastArg(OPT_debugtype)) {
672 SmallVector<StringRef, 3> types;
673 StringRef(a->getValue())
674 .split(types, ',', /*MaxSplit=*/-1, /*KeepEmpty=*/false);
676 for (StringRef type : types) {
677 unsigned v = StringSwitch<unsigned>(type.lower())
678 .Case("cv", static_cast<unsigned>(DebugType::CV))
679 .Case("pdata", static_cast<unsigned>(DebugType::PData))
680 .Case("fixup", static_cast<unsigned>(DebugType::Fixup))
683 warn("/debugtype: unknown option '" + type + "'");
691 // Default debug types
692 debugTypes = static_cast<unsigned>(DebugType::CV);
693 if (args.hasArg(OPT_driver))
694 debugTypes |= static_cast<unsigned>(DebugType::PData);
695 if (args.hasArg(OPT_profile))
696 debugTypes |= static_cast<unsigned>(DebugType::Fixup);
701 static std::string getMapFile(const opt::InputArgList &args) {
702 auto *arg = args.getLastArg(OPT_lldmap, OPT_lldmap_file);
705 if (arg->getOption().getID() == OPT_lldmap_file)
706 return arg->getValue();
708 assert(arg->getOption().getID() == OPT_lldmap);
709 StringRef outFile = config->outputFile;
710 return (outFile.substr(0, outFile.rfind('.')) + ".map").str();
713 static std::string getImplibPath() {
714 if (!config->implib.empty())
715 return config->implib;
716 SmallString<128> out = StringRef(config->outputFile);
717 sys::path::replace_extension(out, ".lib");
721 // The import name is calculated as follows:
723 // | LIBRARY w/ ext | LIBRARY w/o ext | no LIBRARY
724 // -----+----------------+---------------------+------------------
725 // LINK | {value} | {value}.{.dll/.exe} | {output name}
726 // LIB | {value} | {value}.dll | {output name}.dll
728 static std::string getImportName(bool asLib) {
729 SmallString<128> out;
731 if (config->importName.empty()) {
732 out.assign(sys::path::filename(config->outputFile));
734 sys::path::replace_extension(out, ".dll");
736 out.assign(config->importName);
737 if (!sys::path::has_extension(out))
738 sys::path::replace_extension(out,
739 (config->dll || asLib) ? ".dll" : ".exe");
745 static void createImportLibrary(bool asLib) {
746 std::vector<COFFShortExport> exports;
747 for (Export &e1 : config->exports) {
750 e2.SymbolName = e1.symbolName;
751 e2.ExtName = e1.extName;
752 e2.Ordinal = e1.ordinal;
753 e2.Noname = e1.noname;
755 e2.Private = e1.isPrivate;
756 e2.Constant = e1.constant;
757 exports.push_back(e2);
760 auto handleError = [](Error &&e) {
761 handleAllErrors(std::move(e),
762 [](ErrorInfoBase &eib) { error(eib.message()); });
764 std::string libName = getImportName(asLib);
765 std::string path = getImplibPath();
767 if (!config->incremental) {
768 handleError(writeImportLibrary(libName, path, exports, config->machine,
773 // If the import library already exists, replace it only if the contents
775 ErrorOr<std::unique_ptr<MemoryBuffer>> oldBuf = MemoryBuffer::getFile(
776 path, /*FileSize*/ -1, /*RequiresNullTerminator*/ false);
778 handleError(writeImportLibrary(libName, path, exports, config->machine,
783 SmallString<128> tmpName;
784 if (std::error_code ec =
785 sys::fs::createUniqueFile(path + ".tmp-%%%%%%%%.lib", tmpName))
786 fatal("cannot create temporary file for import library " + path + ": " +
789 if (Error e = writeImportLibrary(libName, tmpName, exports, config->machine,
791 handleError(std::move(e));
795 std::unique_ptr<MemoryBuffer> newBuf = check(MemoryBuffer::getFile(
796 tmpName, /*FileSize*/ -1, /*RequiresNullTerminator*/ false));
797 if ((*oldBuf)->getBuffer() != newBuf->getBuffer()) {
799 handleError(errorCodeToError(sys::fs::rename(tmpName, path)));
801 sys::fs::remove(tmpName);
805 static void parseModuleDefs(StringRef path) {
806 std::unique_ptr<MemoryBuffer> mb = CHECK(
807 MemoryBuffer::getFile(path, -1, false, true), "could not open " + path);
808 COFFModuleDefinition m = check(parseCOFFModuleDefinition(
809 mb->getMemBufferRef(), config->machine, config->mingw));
811 if (config->outputFile.empty())
812 config->outputFile = saver.save(m.OutputFile);
813 config->importName = saver.save(m.ImportName);
815 config->imageBase = m.ImageBase;
817 config->stackReserve = m.StackReserve;
819 config->stackCommit = m.StackCommit;
821 config->heapReserve = m.HeapReserve;
823 config->heapCommit = m.HeapCommit;
824 if (m.MajorImageVersion)
825 config->majorImageVersion = m.MajorImageVersion;
826 if (m.MinorImageVersion)
827 config->minorImageVersion = m.MinorImageVersion;
828 if (m.MajorOSVersion)
829 config->majorOSVersion = m.MajorOSVersion;
830 if (m.MinorOSVersion)
831 config->minorOSVersion = m.MinorOSVersion;
833 for (COFFShortExport e1 : m.Exports) {
835 // In simple cases, only Name is set. Renamed exports are parsed
836 // and set as "ExtName = Name". If Name has the form "OtherDll.Func",
837 // it shouldn't be a normal exported function but a forward to another
838 // DLL instead. This is supported by both MS and GNU linkers.
839 if (e1.ExtName != e1.Name && StringRef(e1.Name).contains('.')) {
840 e2.name = saver.save(e1.ExtName);
841 e2.forwardTo = saver.save(e1.Name);
842 config->exports.push_back(e2);
845 e2.name = saver.save(e1.Name);
846 e2.extName = saver.save(e1.ExtName);
847 e2.ordinal = e1.Ordinal;
848 e2.noname = e1.Noname;
850 e2.isPrivate = e1.Private;
851 e2.constant = e1.Constant;
852 config->exports.push_back(e2);
856 void LinkerDriver::enqueueTask(std::function<void()> task) {
857 taskQueue.push_back(std::move(task));
860 bool LinkerDriver::run() {
861 ScopedTimer t(inputFileTimer);
863 bool didWork = !taskQueue.empty();
864 while (!taskQueue.empty()) {
866 taskQueue.pop_front();
871 // Parse an /order file. If an option is given, the linker places
872 // COMDAT sections in the same order as their names appear in the
874 static void parseOrderFile(StringRef arg) {
875 // For some reason, the MSVC linker requires a filename to be
877 if (!arg.startswith("@")) {
878 error("malformed /order option: '@' missing");
882 // Get a list of all comdat sections for error checking.
883 DenseSet<StringRef> set;
884 for (Chunk *c : symtab->getChunks())
885 if (auto *sec = dyn_cast<SectionChunk>(c))
887 set.insert(sec->sym->getName());
890 StringRef path = arg.substr(1);
891 std::unique_ptr<MemoryBuffer> mb = CHECK(
892 MemoryBuffer::getFile(path, -1, false, true), "could not open " + path);
894 // Parse a file. An order file contains one symbol per line.
895 // All symbols that were not present in a given order file are
896 // considered to have the lowest priority 0 and are placed at
897 // end of an output section.
898 for (std::string s : args::getLines(mb->getMemBufferRef())) {
899 if (config->machine == I386 && !isDecorated(s))
902 if (set.count(s) == 0) {
903 if (config->warnMissingOrderSymbol)
904 warn("/order:" + arg + ": missing symbol: " + s + " [LNK4037]");
907 config->order[s] = INT_MIN + config->order.size();
911 static void markAddrsig(Symbol *s) {
912 if (auto *d = dyn_cast_or_null<Defined>(s))
913 if (SectionChunk *c = dyn_cast_or_null<SectionChunk>(d->getChunk()))
914 c->keepUnique = true;
917 static void findKeepUniqueSections() {
918 // Exported symbols could be address-significant in other executables or DSOs,
919 // so we conservatively mark them as address-significant.
920 for (Export &r : config->exports)
923 // Visit the address-significance table in each object file and mark each
924 // referenced symbol as address-significant.
925 for (ObjFile *obj : ObjFile::instances) {
926 ArrayRef<Symbol *> syms = obj->getSymbols();
927 if (obj->addrsigSec) {
928 ArrayRef<uint8_t> contents;
930 obj->getCOFFObj()->getSectionContents(obj->addrsigSec, contents));
931 const uint8_t *cur = contents.begin();
932 while (cur != contents.end()) {
935 uint64_t symIndex = decodeULEB128(cur, &size, contents.end(), &err);
937 fatal(toString(obj) + ": could not decode addrsig section: " + err);
938 if (symIndex >= syms.size())
939 fatal(toString(obj) + ": invalid symbol index in addrsig section");
940 markAddrsig(syms[symIndex]);
944 // If an object file does not have an address-significance table,
945 // conservatively mark all of its symbols as address-significant.
946 for (Symbol *s : syms)
952 // link.exe replaces each %foo% in altPath with the contents of environment
953 // variable foo, and adds the two magic env vars _PDB (expands to the basename
954 // of pdb's output path) and _EXT (expands to the extension of the output
956 // lld only supports %_PDB% and %_EXT% and warns on references to all other env
958 static void parsePDBAltPath(StringRef altPath) {
959 SmallString<128> buf;
960 StringRef pdbBasename =
961 sys::path::filename(config->pdbPath, sys::path::Style::windows);
962 StringRef binaryExtension =
963 sys::path::extension(config->outputFile, sys::path::Style::windows);
964 if (!binaryExtension.empty())
965 binaryExtension = binaryExtension.substr(1); // %_EXT% does not include '.'.
968 // +--------- cursor ('a...' might be the empty string).
969 // | +----- firstMark
974 while (cursor < altPath.size()) {
975 size_t firstMark, secondMark;
976 if ((firstMark = altPath.find('%', cursor)) == StringRef::npos ||
977 (secondMark = altPath.find('%', firstMark + 1)) == StringRef::npos) {
978 // Didn't find another full fragment, treat rest of string as literal.
979 buf.append(altPath.substr(cursor));
983 // Found a full fragment. Append text in front of first %, and interpret
984 // text between first and second % as variable name.
985 buf.append(altPath.substr(cursor, firstMark - cursor));
986 StringRef var = altPath.substr(firstMark, secondMark - firstMark + 1);
987 if (var.equals_lower("%_pdb%"))
988 buf.append(pdbBasename);
989 else if (var.equals_lower("%_ext%"))
990 buf.append(binaryExtension);
992 warn("only %_PDB% and %_EXT% supported in /pdbaltpath:, keeping " +
993 var + " as literal");
997 cursor = secondMark + 1;
1000 config->pdbAltPath = buf;
1003 /// Convert resource files and potentially merge input resource object
1004 /// trees into one resource tree.
1005 /// Call after ObjFile::Instances is complete.
1006 void LinkerDriver::convertResources() {
1007 std::vector<ObjFile *> resourceObjFiles;
1009 for (ObjFile *f : ObjFile::instances) {
1010 if (f->isResourceObjFile())
1011 resourceObjFiles.push_back(f);
1014 if (!config->mingw &&
1015 (resourceObjFiles.size() > 1 ||
1016 (resourceObjFiles.size() == 1 && !resources.empty()))) {
1017 error((!resources.empty() ? "internal .obj file created from .res files"
1018 : toString(resourceObjFiles[1])) +
1019 ": more than one resource obj file not allowed, already got " +
1020 toString(resourceObjFiles.front()));
1024 if (resources.empty() && resourceObjFiles.size() <= 1) {
1025 // No resources to convert, and max one resource object file in
1026 // the input. Keep that preconverted resource section as is.
1027 for (ObjFile *f : resourceObjFiles)
1028 f->includeResourceChunks();
1031 ObjFile *f = make<ObjFile>(convertResToCOFF(resources, resourceObjFiles));
1033 f->includeResourceChunks();
1036 // In MinGW, if no symbols are chosen to be exported, then all symbols are
1037 // automatically exported by default. This behavior can be forced by the
1038 // -export-all-symbols option, so that it happens even when exports are
1039 // explicitly specified. The automatic behavior can be disabled using the
1040 // -exclude-all-symbols option, so that lld-link behaves like link.exe rather
1041 // than MinGW in the case that nothing is explicitly exported.
1042 void LinkerDriver::maybeExportMinGWSymbols(const opt::InputArgList &args) {
1046 if (!args.hasArg(OPT_export_all_symbols)) {
1047 if (!config->exports.empty())
1049 if (args.hasArg(OPT_exclude_all_symbols))
1053 AutoExporter exporter;
1055 for (auto *arg : args.filtered(OPT_wholearchive_file))
1056 if (Optional<StringRef> path = doFindFile(arg->getValue()))
1057 exporter.addWholeArchive(*path);
1059 symtab->forEachSymbol([&](Symbol *s) {
1060 auto *def = dyn_cast<Defined>(s);
1061 if (!exporter.shouldExport(def))
1065 e.name = def->getName();
1067 if (Chunk *c = def->getChunk())
1068 if (!(c->getOutputCharacteristics() & IMAGE_SCN_MEM_EXECUTE))
1070 config->exports.push_back(e);
1074 // lld has a feature to create a tar file containing all input files as well as
1075 // all command line options, so that other people can run lld again with exactly
1076 // the same inputs. This feature is accessible via /linkrepro and /reproduce.
1078 // /linkrepro and /reproduce are very similar, but /linkrepro takes a directory
1079 // name while /reproduce takes a full path. We have /linkrepro for compatibility
1080 // with Microsoft link.exe.
1081 Optional<std::string> getReproduceFile(const opt::InputArgList &args) {
1082 if (auto *arg = args.getLastArg(OPT_reproduce))
1083 return std::string(arg->getValue());
1085 if (auto *arg = args.getLastArg(OPT_linkrepro)) {
1086 SmallString<64> path = StringRef(arg->getValue());
1087 sys::path::append(path, "repro.tar");
1088 return path.str().str();
1094 void LinkerDriver::link(ArrayRef<const char *> argsArr) {
1096 InitializeAllTargetInfos();
1097 InitializeAllTargets();
1098 InitializeAllTargetMCs();
1099 InitializeAllAsmParsers();
1100 InitializeAllAsmPrinters();
1102 // If the first command line argument is "/lib", link.exe acts like lib.exe.
1103 // We call our own implementation of lib.exe that understands bitcode files.
1104 if (argsArr.size() > 1 && StringRef(argsArr[1]).equals_lower("/lib")) {
1105 if (llvm::libDriverMain(argsArr.slice(1)) != 0)
1106 fatal("lib failed");
1110 // Parse command line options.
1112 opt::InputArgList args = parser.parse(argsArr);
1114 // Parse and evaluate -mllvm options.
1115 std::vector<const char *> v;
1116 v.push_back("lld-link (LLVM option parsing)");
1117 for (auto *arg : args.filtered(OPT_mllvm))
1118 v.push_back(arg->getValue());
1119 cl::ParseCommandLineOptions(v.size(), v.data());
1121 // Handle /errorlimit early, because error() depends on it.
1122 if (auto *arg = args.getLastArg(OPT_errorlimit)) {
1124 StringRef s = arg->getValue();
1125 if (s.getAsInteger(10, n))
1126 error(arg->getSpelling() + " number expected, but got " + s);
1127 errorHandler().errorLimit = n;
1131 if (args.hasArg(OPT_help)) {
1132 printHelp(argsArr[0]);
1136 lld::threadsEnabled = args.hasFlag(OPT_threads, OPT_threads_no, true);
1138 if (args.hasArg(OPT_show_timing))
1139 config->showTiming = true;
1141 config->showSummary = args.hasArg(OPT_summary);
1143 ScopedTimer t(Timer::root());
1144 // Handle --version, which is an lld extension. This option is a bit odd
1145 // because it doesn't start with "/", but we deliberately chose "--" to
1146 // avoid conflict with /version and for compatibility with clang-cl.
1147 if (args.hasArg(OPT_dash_dash_version)) {
1148 outs() << getLLDVersion() << "\n";
1152 // Handle /lldmingw early, since it can potentially affect how other
1153 // options are handled.
1154 config->mingw = args.hasArg(OPT_lldmingw);
1156 // Handle /linkrepro and /reproduce.
1157 if (Optional<std::string> path = getReproduceFile(args)) {
1158 Expected<std::unique_ptr<TarWriter>> errOrWriter =
1159 TarWriter::create(*path, sys::path::stem(*path));
1162 tar = std::move(*errOrWriter);
1164 error("/linkrepro: failed to open " + *path + ": " +
1165 toString(errOrWriter.takeError()));
1169 if (!args.hasArg(OPT_INPUT)) {
1170 if (args.hasArg(OPT_deffile))
1171 config->noEntry = true;
1173 fatal("no input files");
1176 // Construct search path list.
1177 searchPaths.push_back("");
1178 for (auto *arg : args.filtered(OPT_libpath))
1179 searchPaths.push_back(arg->getValue());
1180 if (!args.hasArg(OPT_lldignoreenv))
1181 addLibSearchPaths();
1184 for (auto *arg : args.filtered(OPT_ignore)) {
1185 SmallVector<StringRef, 8> vec;
1186 StringRef(arg->getValue()).split(vec, ',');
1187 for (StringRef s : vec) {
1189 config->warnMissingOrderSymbol = false;
1190 else if (s == "4099")
1191 config->warnDebugInfoUnusable = false;
1192 else if (s == "4217")
1193 config->warnLocallyDefinedImported = false;
1194 // Other warning numbers are ignored.
1199 if (auto *arg = args.getLastArg(OPT_out))
1200 config->outputFile = arg->getValue();
1203 if (args.hasArg(OPT_verbose))
1204 config->verbose = true;
1205 errorHandler().verbose = config->verbose;
1207 // Handle /force or /force:unresolved
1208 if (args.hasArg(OPT_force, OPT_force_unresolved))
1209 config->forceUnresolved = true;
1211 // Handle /force or /force:multiple
1212 if (args.hasArg(OPT_force, OPT_force_multiple))
1213 config->forceMultiple = true;
1215 // Handle /force or /force:multipleres
1216 if (args.hasArg(OPT_force, OPT_force_multipleres))
1217 config->forceMultipleRes = true;
1220 DebugKind debug = parseDebugKind(args);
1221 if (debug == DebugKind::Full || debug == DebugKind::Dwarf ||
1222 debug == DebugKind::GHash) {
1223 config->debug = true;
1224 config->incremental = true;
1228 config->demangle = args.hasFlag(OPT_demangle, OPT_demangle_no);
1230 // Handle /debugtype
1231 config->debugTypes = parseDebugTypes(args);
1234 bool shouldCreatePDB =
1235 (debug == DebugKind::Full || debug == DebugKind::GHash);
1236 if (shouldCreatePDB) {
1237 if (auto *arg = args.getLastArg(OPT_pdb))
1238 config->pdbPath = arg->getValue();
1239 if (auto *arg = args.getLastArg(OPT_pdbaltpath))
1240 config->pdbAltPath = arg->getValue();
1241 if (args.hasArg(OPT_natvis))
1242 config->natvisFiles = args.getAllArgValues(OPT_natvis);
1244 if (auto *arg = args.getLastArg(OPT_pdb_source_path))
1245 config->pdbSourcePath = arg->getValue();
1249 if (args.hasArg(OPT_noentry)) {
1250 if (args.hasArg(OPT_dll))
1251 config->noEntry = true;
1253 error("/noentry must be specified with /dll");
1257 if (args.hasArg(OPT_dll)) {
1259 config->manifestID = 2;
1262 // Handle /dynamicbase and /fixed. We can't use hasFlag for /dynamicbase
1263 // because we need to explicitly check whether that option or its inverse was
1264 // present in the argument list in order to handle /fixed.
1265 auto *dynamicBaseArg = args.getLastArg(OPT_dynamicbase, OPT_dynamicbase_no);
1266 if (dynamicBaseArg &&
1267 dynamicBaseArg->getOption().getID() == OPT_dynamicbase_no)
1268 config->dynamicBase = false;
1270 // MSDN claims "/FIXED:NO is the default setting for a DLL, and /FIXED is the
1271 // default setting for any other project type.", but link.exe defaults to
1272 // /FIXED:NO for exe outputs as well. Match behavior, not docs.
1273 bool fixed = args.hasFlag(OPT_fixed, OPT_fixed_no, false);
1275 if (dynamicBaseArg &&
1276 dynamicBaseArg->getOption().getID() == OPT_dynamicbase) {
1277 error("/fixed must not be specified with /dynamicbase");
1279 config->relocatable = false;
1280 config->dynamicBase = false;
1284 // Handle /appcontainer
1285 config->appContainer =
1286 args.hasFlag(OPT_appcontainer, OPT_appcontainer_no, false);
1289 if (auto *arg = args.getLastArg(OPT_machine)) {
1290 config->machine = getMachineType(arg->getValue());
1291 if (config->machine == IMAGE_FILE_MACHINE_UNKNOWN)
1292 fatal(Twine("unknown /machine argument: ") + arg->getValue());
1295 // Handle /nodefaultlib:<filename>
1296 for (auto *arg : args.filtered(OPT_nodefaultlib))
1297 config->noDefaultLibs.insert(doFindLib(arg->getValue()).lower());
1299 // Handle /nodefaultlib
1300 if (args.hasArg(OPT_nodefaultlib_all))
1301 config->noDefaultLibAll = true;
1304 if (auto *arg = args.getLastArg(OPT_base))
1305 parseNumbers(arg->getValue(), &config->imageBase);
1307 // Handle /filealign
1308 if (auto *arg = args.getLastArg(OPT_filealign)) {
1309 parseNumbers(arg->getValue(), &config->fileAlign);
1310 if (!isPowerOf2_64(config->fileAlign))
1311 error("/filealign: not a power of two: " + Twine(config->fileAlign));
1315 if (auto *arg = args.getLastArg(OPT_stack))
1316 parseNumbers(arg->getValue(), &config->stackReserve, &config->stackCommit);
1319 if (auto *arg = args.getLastArg(OPT_guard))
1320 parseGuard(arg->getValue());
1323 if (auto *arg = args.getLastArg(OPT_heap))
1324 parseNumbers(arg->getValue(), &config->heapReserve, &config->heapCommit);
1327 if (auto *arg = args.getLastArg(OPT_version))
1328 parseVersion(arg->getValue(), &config->majorImageVersion,
1329 &config->minorImageVersion);
1331 // Handle /subsystem
1332 if (auto *arg = args.getLastArg(OPT_subsystem))
1333 parseSubsystem(arg->getValue(), &config->subsystem, &config->majorOSVersion,
1334 &config->minorOSVersion);
1336 // Handle /timestamp
1337 if (llvm::opt::Arg *arg = args.getLastArg(OPT_timestamp, OPT_repro)) {
1338 if (arg->getOption().getID() == OPT_repro) {
1339 config->timestamp = 0;
1340 config->repro = true;
1342 config->repro = false;
1343 StringRef value(arg->getValue());
1344 if (value.getAsInteger(0, config->timestamp))
1345 fatal(Twine("invalid timestamp: ") + value +
1346 ". Expected 32-bit integer");
1349 config->repro = false;
1350 config->timestamp = time(nullptr);
1353 // Handle /alternatename
1354 for (auto *arg : args.filtered(OPT_alternatename))
1355 parseAlternateName(arg->getValue());
1358 for (auto *arg : args.filtered(OPT_incl))
1359 addUndefined(arg->getValue());
1362 if (auto *arg = args.getLastArg(OPT_implib))
1363 config->implib = arg->getValue();
1366 bool doGC = debug == DebugKind::None || args.hasArg(OPT_profile);
1368 args.hasArg(OPT_profile) ? 0 : 1; // 0: off, 1: limited, 2: on
1369 unsigned tailMerge = 1;
1370 for (auto *arg : args.filtered(OPT_opt)) {
1371 std::string str = StringRef(arg->getValue()).lower();
1372 SmallVector<StringRef, 1> vec;
1373 StringRef(str).split(vec, ',');
1374 for (StringRef s : vec) {
1377 } else if (s == "noref") {
1379 } else if (s == "icf" || s.startswith("icf=")) {
1381 } else if (s == "noicf") {
1383 } else if (s == "lldtailmerge") {
1385 } else if (s == "nolldtailmerge") {
1387 } else if (s.startswith("lldlto=")) {
1388 StringRef optLevel = s.substr(7);
1389 if (optLevel.getAsInteger(10, config->ltoo) || config->ltoo > 3)
1390 error("/opt:lldlto: invalid optimization level: " + optLevel);
1391 } else if (s.startswith("lldltojobs=")) {
1392 StringRef jobs = s.substr(11);
1393 if (jobs.getAsInteger(10, config->thinLTOJobs) ||
1394 config->thinLTOJobs == 0)
1395 error("/opt:lldltojobs: invalid job count: " + jobs);
1396 } else if (s.startswith("lldltopartitions=")) {
1397 StringRef n = s.substr(17);
1398 if (n.getAsInteger(10, config->ltoPartitions) ||
1399 config->ltoPartitions == 0)
1400 error("/opt:lldltopartitions: invalid partition count: " + n);
1401 } else if (s != "lbr" && s != "nolbr")
1402 error("/opt: unknown option: " + s);
1406 // Limited ICF is enabled if GC is enabled and ICF was never mentioned
1408 // FIXME: LLD only implements "limited" ICF, i.e. it only merges identical
1409 // code. If the user passes /OPT:ICF explicitly, LLD should merge identical
1410 // comdat readonly data.
1411 if (icfLevel == 1 && !doGC)
1413 config->doGC = doGC;
1414 config->doICF = icfLevel > 0;
1415 config->tailMerge = (tailMerge == 1 && config->doICF) || tailMerge == 2;
1417 // Handle /lldsavetemps
1418 if (args.hasArg(OPT_lldsavetemps))
1419 config->saveTemps = true;
1422 if (args.hasArg(OPT_kill_at))
1423 config->killAt = true;
1425 // Handle /lldltocache
1426 if (auto *arg = args.getLastArg(OPT_lldltocache))
1427 config->ltoCache = arg->getValue();
1429 // Handle /lldsavecachepolicy
1430 if (auto *arg = args.getLastArg(OPT_lldltocachepolicy))
1431 config->ltoCachePolicy = CHECK(
1432 parseCachePruningPolicy(arg->getValue()),
1433 Twine("/lldltocachepolicy: invalid cache policy: ") + arg->getValue());
1435 // Handle /failifmismatch
1436 for (auto *arg : args.filtered(OPT_failifmismatch))
1437 checkFailIfMismatch(arg->getValue(), nullptr);
1440 for (auto *arg : args.filtered(OPT_merge))
1441 parseMerge(arg->getValue());
1443 // Add default section merging rules after user rules. User rules take
1444 // precedence, but we will emit a warning if there is a conflict.
1445 parseMerge(".idata=.rdata");
1446 parseMerge(".didat=.rdata");
1447 parseMerge(".edata=.rdata");
1448 parseMerge(".xdata=.rdata");
1449 parseMerge(".bss=.data");
1451 if (config->mingw) {
1452 parseMerge(".ctors=.rdata");
1453 parseMerge(".dtors=.rdata");
1454 parseMerge(".CRT=.rdata");
1458 for (auto *arg : args.filtered(OPT_section))
1459 parseSection(arg->getValue());
1462 if (auto *arg = args.getLastArg(OPT_align)) {
1463 parseNumbers(arg->getValue(), &config->align);
1464 if (!isPowerOf2_64(config->align))
1465 error("/align: not a power of two: " + StringRef(arg->getValue()));
1468 // Handle /aligncomm
1469 for (auto *arg : args.filtered(OPT_aligncomm))
1470 parseAligncomm(arg->getValue());
1472 // Handle /manifestdependency. This enables /manifest unless /manifest:no is
1474 if (auto *arg = args.getLastArg(OPT_manifestdependency)) {
1475 config->manifestDependency = arg->getValue();
1476 config->manifest = Configuration::SideBySide;
1479 // Handle /manifest and /manifest:
1480 if (auto *arg = args.getLastArg(OPT_manifest, OPT_manifest_colon)) {
1481 if (arg->getOption().getID() == OPT_manifest)
1482 config->manifest = Configuration::SideBySide;
1484 parseManifest(arg->getValue());
1487 // Handle /manifestuac
1488 if (auto *arg = args.getLastArg(OPT_manifestuac))
1489 parseManifestUAC(arg->getValue());
1491 // Handle /manifestfile
1492 if (auto *arg = args.getLastArg(OPT_manifestfile))
1493 config->manifestFile = arg->getValue();
1495 // Handle /manifestinput
1496 for (auto *arg : args.filtered(OPT_manifestinput))
1497 config->manifestInput.push_back(arg->getValue());
1499 if (!config->manifestInput.empty() &&
1500 config->manifest != Configuration::Embed) {
1501 fatal("/manifestinput: requires /manifest:embed");
1504 config->thinLTOEmitImportsFiles = args.hasArg(OPT_thinlto_emit_imports_files);
1505 config->thinLTOIndexOnly = args.hasArg(OPT_thinlto_index_only) ||
1506 args.hasArg(OPT_thinlto_index_only_arg);
1507 config->thinLTOIndexOnlyArg =
1508 args.getLastArgValue(OPT_thinlto_index_only_arg);
1509 config->thinLTOPrefixReplace =
1510 getOldNewOptions(args, OPT_thinlto_prefix_replace);
1511 config->thinLTOObjectSuffixReplace =
1512 getOldNewOptions(args, OPT_thinlto_object_suffix_replace);
1513 config->ltoObjPath = args.getLastArgValue(OPT_lto_obj_path);
1514 // Handle miscellaneous boolean flags.
1515 config->allowBind = args.hasFlag(OPT_allowbind, OPT_allowbind_no, true);
1516 config->allowIsolation =
1517 args.hasFlag(OPT_allowisolation, OPT_allowisolation_no, true);
1518 config->incremental =
1519 args.hasFlag(OPT_incremental, OPT_incremental_no,
1520 !config->doGC && !config->doICF && !args.hasArg(OPT_order) &&
1521 !args.hasArg(OPT_profile));
1522 config->integrityCheck =
1523 args.hasFlag(OPT_integritycheck, OPT_integritycheck_no, false);
1524 config->nxCompat = args.hasFlag(OPT_nxcompat, OPT_nxcompat_no, true);
1525 for (auto *arg : args.filtered(OPT_swaprun))
1526 parseSwaprun(arg->getValue());
1527 config->terminalServerAware =
1528 !config->dll && args.hasFlag(OPT_tsaware, OPT_tsaware_no, true);
1529 config->debugDwarf = debug == DebugKind::Dwarf;
1530 config->debugGHashes = debug == DebugKind::GHash;
1531 config->debugSymtab = debug == DebugKind::Symtab;
1533 config->mapFile = getMapFile(args);
1535 if (config->incremental && args.hasArg(OPT_profile)) {
1536 warn("ignoring '/incremental' due to '/profile' specification");
1537 config->incremental = false;
1540 if (config->incremental && args.hasArg(OPT_order)) {
1541 warn("ignoring '/incremental' due to '/order' specification");
1542 config->incremental = false;
1545 if (config->incremental && config->doGC) {
1546 warn("ignoring '/incremental' because REF is enabled; use '/opt:noref' to "
1548 config->incremental = false;
1551 if (config->incremental && config->doICF) {
1552 warn("ignoring '/incremental' because ICF is enabled; use '/opt:noicf' to "
1554 config->incremental = false;
1560 std::set<sys::fs::UniqueID> wholeArchives;
1561 for (auto *arg : args.filtered(OPT_wholearchive_file))
1562 if (Optional<StringRef> path = doFindFile(arg->getValue()))
1563 if (Optional<sys::fs::UniqueID> id = getUniqueID(*path))
1564 wholeArchives.insert(*id);
1566 // A predicate returning true if a given path is an argument for
1567 // /wholearchive:, or /wholearchive is enabled globally.
1568 // This function is a bit tricky because "foo.obj /wholearchive:././foo.obj"
1569 // needs to be handled as "/wholearchive:foo.obj foo.obj".
1570 auto isWholeArchive = [&](StringRef path) -> bool {
1571 if (args.hasArg(OPT_wholearchive_flag))
1573 if (Optional<sys::fs::UniqueID> id = getUniqueID(path))
1574 return wholeArchives.count(*id);
1578 // Create a list of input files. These can be given as OPT_INPUT options
1579 // and OPT_wholearchive_file options, and we also need to track OPT_start_lib
1582 for (auto *arg : args) {
1583 switch (arg->getOption().getID()) {
1586 error("stray " + arg->getSpelling());
1591 error("nested " + arg->getSpelling());
1594 case OPT_wholearchive_file:
1595 if (Optional<StringRef> path = findFile(arg->getValue()))
1596 enqueuePath(*path, true, inLib);
1599 if (Optional<StringRef> path = findFile(arg->getValue()))
1600 enqueuePath(*path, isWholeArchive(*path), inLib);
1603 // Ignore other options.
1608 // Process files specified as /defaultlib. These should be enequeued after
1609 // other files, which is why they are in a separate loop.
1610 for (auto *arg : args.filtered(OPT_defaultlib))
1611 if (Optional<StringRef> path = findLib(arg->getValue()))
1612 enqueuePath(*path, false, false);
1614 // Windows specific -- Create a resource file containing a manifest file.
1615 if (config->manifest == Configuration::Embed)
1616 addBuffer(createManifestRes(), false, false);
1618 // Read all input files given via the command line.
1624 // We should have inferred a machine type by now from the input files, but if
1625 // not we assume x64.
1626 if (config->machine == IMAGE_FILE_MACHINE_UNKNOWN) {
1627 warn("/machine is not specified. x64 is assumed");
1628 config->machine = AMD64;
1630 config->wordsize = config->is64() ? 8 : 4;
1632 // Handle /safeseh, x86 only, on by default, except for mingw.
1633 if (config->machine == I386 &&
1634 args.hasFlag(OPT_safeseh, OPT_safeseh_no, !config->mingw))
1635 config->safeSEH = true;
1637 // Handle /functionpadmin
1638 for (auto *arg : args.filtered(OPT_functionpadmin, OPT_functionpadmin_opt))
1639 parseFunctionPadMin(arg, config->machine);
1642 tar->append("response.txt",
1643 createResponseFile(args, filePaths,
1644 ArrayRef<StringRef>(searchPaths).slice(1)));
1646 // Handle /largeaddressaware
1647 config->largeAddressAware = args.hasFlag(
1648 OPT_largeaddressaware, OPT_largeaddressaware_no, config->is64());
1650 // Handle /highentropyva
1651 config->highEntropyVA =
1653 args.hasFlag(OPT_highentropyva, OPT_highentropyva_no, true);
1655 if (!config->dynamicBase &&
1656 (config->machine == ARMNT || config->machine == ARM64))
1657 error("/dynamicbase:no is not compatible with " +
1658 machineToStr(config->machine));
1661 for (auto *arg : args.filtered(OPT_export)) {
1662 Export e = parseExport(arg->getValue());
1663 if (config->machine == I386) {
1664 if (!isDecorated(e.name))
1665 e.name = saver.save("_" + e.name);
1666 if (!e.extName.empty() && !isDecorated(e.extName))
1667 e.extName = saver.save("_" + e.extName);
1669 config->exports.push_back(e);
1673 if (auto *arg = args.getLastArg(OPT_deffile)) {
1674 // parseModuleDefs mutates Config object.
1675 parseModuleDefs(arg->getValue());
1678 // Handle generation of import library from a def file.
1679 if (!args.hasArg(OPT_INPUT)) {
1681 createImportLibrary(/*asLib=*/true);
1685 // Windows specific -- if no /subsystem is given, we need to infer
1686 // that from entry point name. Must happen before /entry handling,
1687 // and after the early return when just writing an import library.
1688 if (config->subsystem == IMAGE_SUBSYSTEM_UNKNOWN) {
1689 config->subsystem = inferSubsystem();
1690 if (config->subsystem == IMAGE_SUBSYSTEM_UNKNOWN)
1691 fatal("subsystem must be defined");
1694 // Handle /entry and /dll
1695 if (auto *arg = args.getLastArg(OPT_entry)) {
1696 config->entry = addUndefined(mangle(arg->getValue()));
1697 } else if (!config->entry && !config->noEntry) {
1698 if (args.hasArg(OPT_dll)) {
1699 StringRef s = (config->machine == I386) ? "__DllMainCRTStartup@12"
1700 : "_DllMainCRTStartup";
1701 config->entry = addUndefined(s);
1703 // Windows specific -- If entry point name is not given, we need to
1704 // infer that from user-defined entry name.
1705 StringRef s = findDefaultEntry();
1707 fatal("entry point must be defined");
1708 config->entry = addUndefined(s);
1709 log("Entry name inferred: " + s);
1713 // Handle /delayload
1714 for (auto *arg : args.filtered(OPT_delayload)) {
1715 config->delayLoads.insert(StringRef(arg->getValue()).lower());
1716 if (config->machine == I386) {
1717 config->delayLoadHelper = addUndefined("___delayLoadHelper2@8");
1719 config->delayLoadHelper = addUndefined("__delayLoadHelper2");
1723 // Set default image name if neither /out or /def set it.
1724 if (config->outputFile.empty()) {
1725 config->outputFile =
1726 getOutputPath((*args.filtered(OPT_INPUT).begin())->getValue());
1729 // Fail early if an output file is not writable.
1730 if (auto e = tryCreateFile(config->outputFile)) {
1731 error("cannot open output file " + config->outputFile + ": " + e.message());
1735 if (shouldCreatePDB) {
1736 // Put the PDB next to the image if no /pdb flag was passed.
1737 if (config->pdbPath.empty()) {
1738 config->pdbPath = config->outputFile;
1739 sys::path::replace_extension(config->pdbPath, ".pdb");
1742 // The embedded PDB path should be the absolute path to the PDB if no
1743 // /pdbaltpath flag was passed.
1744 if (config->pdbAltPath.empty()) {
1745 config->pdbAltPath = config->pdbPath;
1747 // It's important to make the path absolute and remove dots. This path
1748 // will eventually be written into the PE header, and certain Microsoft
1749 // tools won't work correctly if these assumptions are not held.
1750 sys::fs::make_absolute(config->pdbAltPath);
1751 sys::path::remove_dots(config->pdbAltPath);
1753 // Don't do this earlier, so that Config->OutputFile is ready.
1754 parsePDBAltPath(config->pdbAltPath);
1758 // Set default image base if /base is not given.
1759 if (config->imageBase == uint64_t(-1))
1760 config->imageBase = getDefaultImageBase();
1762 symtab->addSynthetic(mangle("__ImageBase"), nullptr);
1763 if (config->machine == I386) {
1764 symtab->addAbsolute("___safe_se_handler_table", 0);
1765 symtab->addAbsolute("___safe_se_handler_count", 0);
1768 symtab->addAbsolute(mangle("__guard_fids_count"), 0);
1769 symtab->addAbsolute(mangle("__guard_fids_table"), 0);
1770 symtab->addAbsolute(mangle("__guard_flags"), 0);
1771 symtab->addAbsolute(mangle("__guard_iat_count"), 0);
1772 symtab->addAbsolute(mangle("__guard_iat_table"), 0);
1773 symtab->addAbsolute(mangle("__guard_longjmp_count"), 0);
1774 symtab->addAbsolute(mangle("__guard_longjmp_table"), 0);
1775 // Needed for MSVC 2017 15.5 CRT.
1776 symtab->addAbsolute(mangle("__enclave_config"), 0);
1778 if (config->mingw) {
1779 symtab->addAbsolute(mangle("__RUNTIME_PSEUDO_RELOC_LIST__"), 0);
1780 symtab->addAbsolute(mangle("__RUNTIME_PSEUDO_RELOC_LIST_END__"), 0);
1781 symtab->addAbsolute(mangle("__CTOR_LIST__"), 0);
1782 symtab->addAbsolute(mangle("__DTOR_LIST__"), 0);
1785 // This code may add new undefined symbols to the link, which may enqueue more
1786 // symbol resolution tasks, so we need to continue executing tasks until we
1789 // Windows specific -- if entry point is not found,
1790 // search for its mangled names.
1792 mangleMaybe(config->entry);
1794 // Windows specific -- Make sure we resolve all dllexported symbols.
1795 for (Export &e : config->exports) {
1796 if (!e.forwardTo.empty())
1798 e.sym = addUndefined(e.name);
1800 e.symbolName = mangleMaybe(e.sym);
1803 // Add weak aliases. Weak aliases is a mechanism to give remaining
1804 // undefined symbols final chance to be resolved successfully.
1805 for (auto pair : config->alternateNames) {
1806 StringRef from = pair.first;
1807 StringRef to = pair.second;
1808 Symbol *sym = symtab->find(from);
1811 if (auto *u = dyn_cast<Undefined>(sym))
1813 u->weakAlias = symtab->addUndefined(to);
1816 // If any inputs are bitcode files, the LTO code generator may create
1817 // references to library functions that are not explicit in the bitcode
1818 // file's symbol table. If any of those library functions are defined in a
1819 // bitcode file in an archive member, we need to arrange to use LTO to
1820 // compile those archive members by adding them to the link beforehand.
1821 if (!BitcodeFile::instances.empty())
1822 for (auto *s : lto::LTO::getRuntimeLibcallSymbols())
1823 symtab->addLibcall(s);
1825 // Windows specific -- if __load_config_used can be resolved, resolve it.
1826 if (symtab->findUnderscore("_load_config_used"))
1827 addUndefined(mangle("_load_config_used"));
1830 if (args.hasArg(OPT_include_optional)) {
1831 // Handle /includeoptional
1832 for (auto *arg : args.filtered(OPT_include_optional))
1833 if (dyn_cast_or_null<LazyArchive>(symtab->find(arg->getValue())))
1834 addUndefined(arg->getValue());
1838 if (config->mingw) {
1839 // Load any further object files that might be needed for doing automatic
1842 // For cases with no automatically imported symbols, this iterates once
1843 // over the symbol table and doesn't do anything.
1845 // For the normal case with a few automatically imported symbols, this
1846 // should only need to be run once, since each new object file imported
1847 // is an import library and wouldn't add any new undefined references,
1848 // but there's nothing stopping the __imp_ symbols from coming from a
1849 // normal object file as well (although that won't be used for the
1850 // actual autoimport later on). If this pass adds new undefined references,
1851 // we won't iterate further to resolve them.
1852 symtab->loadMinGWAutomaticImports();
1856 // At this point, we should not have any symbols that cannot be resolved.
1857 // If we are going to do codegen for link-time optimization, check for
1858 // unresolvable symbols first, so we don't spend time generating code that
1859 // will fail to link anyway.
1860 if (!BitcodeFile::instances.empty() && !config->forceUnresolved)
1861 symtab->reportUnresolvable();
1865 // Do LTO by compiling bitcode input files to a set of native COFF files then
1866 // link those files (unless -thinlto-index-only was given, in which case we
1867 // resolve symbols and write indices, but don't generate native code or link).
1868 symtab->addCombinedLTOObjects();
1870 // If -thinlto-index-only is given, we should create only "index
1871 // files" and not object files. Index file creation is already done
1872 // in addCombinedLTOObject, so we are done if that's the case.
1873 if (config->thinLTOIndexOnly)
1876 // If we generated native object files from bitcode files, this resolves
1877 // references to the symbols we use from them.
1880 // Resolve remaining undefined symbols and warn about imported locals.
1881 symtab->resolveRemainingUndefines();
1885 config->hadExplicitExports = !config->exports.empty();
1886 if (config->mingw) {
1887 // In MinGW, all symbols are automatically exported if no symbols
1888 // are chosen to be exported.
1889 maybeExportMinGWSymbols(args);
1891 // Make sure the crtend.o object is the last object file. This object
1892 // file can contain terminating section chunks that need to be placed
1893 // last. GNU ld processes files and static libraries explicitly in the
1894 // order provided on the command line, while lld will pull in needed
1895 // files from static libraries only after the last object file on the
1897 for (auto i = ObjFile::instances.begin(), e = ObjFile::instances.end();
1900 if (isCrtend(file->getName())) {
1901 ObjFile::instances.erase(i);
1902 ObjFile::instances.push_back(file);
1908 // Windows specific -- when we are creating a .dll file, we also
1909 // need to create a .lib file. In MinGW mode, we only do that when the
1910 // -implib option is given explicitly, for compatibility with GNU ld.
1911 if (!config->exports.empty() || config->dll) {
1913 if (!config->mingw || !config->implib.empty())
1914 createImportLibrary(/*asLib=*/false);
1915 assignExportOrdinals();
1918 // Handle /output-def (MinGW specific).
1919 if (auto *arg = args.getLastArg(OPT_output_def))
1920 writeDefFile(arg->getValue());
1922 // Set extra alignment for .comm symbols
1923 for (auto pair : config->alignComm) {
1924 StringRef name = pair.first;
1925 uint32_t alignment = pair.second;
1927 Symbol *sym = symtab->find(name);
1929 warn("/aligncomm symbol " + name + " not found");
1933 // If the symbol isn't common, it must have been replaced with a regular
1934 // symbol, which will carry its own alignment.
1935 auto *dc = dyn_cast<DefinedCommon>(sym);
1939 CommonChunk *c = dc->getChunk();
1940 c->setAlignment(std::max(c->getAlignment(), alignment));
1943 // Windows specific -- Create a side-by-side manifest file.
1944 if (config->manifest == Configuration::SideBySide)
1945 createSideBySideManifest();
1947 // Handle /order. We want to do this at this moment because we
1948 // need a complete list of comdat sections to warn on nonexistent
1950 if (auto *arg = args.getLastArg(OPT_order))
1951 parseOrderFile(arg->getValue());
1953 // Identify unreferenced COMDAT sections.
1955 markLive(symtab->getChunks());
1957 // Needs to happen after the last call to addFile().
1960 // Identify identical COMDAT sections to merge them.
1961 if (config->doICF) {
1962 findKeepUniqueSections();
1963 doICF(symtab->getChunks());
1966 // Write the result.
1969 // Stop early so we can print the results.
1970 Timer::root().stop();
1971 if (config->showTiming)
1972 Timer::root().print();