[LLD][COFF] Fix TypeServerSource matcher with more than one collision
[llvm-project.git] / lld / COFF / Driver.cpp
blobd4448e8fcee15e4601e60cbe5a604a58a606ba3d
1 //===- Driver.cpp ---------------------------------------------------------===//
2 //
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
6 //
7 //===----------------------------------------------------------------------===//
9 #include "Driver.h"
10 #include "COFFLinkerContext.h"
11 #include "Config.h"
12 #include "DebugTypes.h"
13 #include "ICF.h"
14 #include "InputFiles.h"
15 #include "MarkLive.h"
16 #include "MinGW.h"
17 #include "SymbolTable.h"
18 #include "Symbols.h"
19 #include "Writer.h"
20 #include "lld/Common/Args.h"
21 #include "lld/Common/Driver.h"
22 #include "lld/Common/Filesystem.h"
23 #include "lld/Common/Timer.h"
24 #include "lld/Common/Version.h"
25 #include "llvm/ADT/IntrusiveRefCntPtr.h"
26 #include "llvm/ADT/Optional.h"
27 #include "llvm/ADT/StringSwitch.h"
28 #include "llvm/ADT/Triple.h"
29 #include "llvm/BinaryFormat/Magic.h"
30 #include "llvm/Config/llvm-config.h"
31 #include "llvm/LTO/LTO.h"
32 #include "llvm/Object/ArchiveWriter.h"
33 #include "llvm/Object/COFFImportFile.h"
34 #include "llvm/Object/COFFModuleDefinition.h"
35 #include "llvm/Object/WindowsMachineFlag.h"
36 #include "llvm/Option/Arg.h"
37 #include "llvm/Option/ArgList.h"
38 #include "llvm/Option/Option.h"
39 #include "llvm/Support/BinaryStreamReader.h"
40 #include "llvm/Support/CommandLine.h"
41 #include "llvm/Support/Debug.h"
42 #include "llvm/Support/LEB128.h"
43 #include "llvm/Support/MathExtras.h"
44 #include "llvm/Support/Parallel.h"
45 #include "llvm/Support/Path.h"
46 #include "llvm/Support/Process.h"
47 #include "llvm/Support/TarWriter.h"
48 #include "llvm/Support/TargetSelect.h"
49 #include "llvm/Support/VirtualFileSystem.h"
50 #include "llvm/Support/raw_ostream.h"
51 #include "llvm/ToolDrivers/llvm-lib/LibDriver.h"
52 #include <algorithm>
53 #include <future>
54 #include <memory>
56 using namespace llvm;
57 using namespace llvm::object;
58 using namespace llvm::COFF;
59 using namespace llvm::sys;
61 namespace lld {
62 namespace coff {
64 std::unique_ptr<Configuration> config;
65 std::unique_ptr<LinkerDriver> driver;
67 bool link(ArrayRef<const char *> args, llvm::raw_ostream &stdoutOS,
68 llvm::raw_ostream &stderrOS, bool exitEarly, bool disableOutput) {
69 // This driver-specific context will be freed later by lldMain().
70 auto *ctx = new COFFLinkerContext;
72 ctx->e.initialize(stdoutOS, stderrOS, exitEarly, disableOutput);
73 ctx->e.logName = args::getFilenameWithoutExe(args[0]);
74 ctx->e.errorLimitExceededMsg = "too many errors emitted, stopping now"
75 " (use /errorlimit:0 to see all errors)";
77 config = std::make_unique<Configuration>();
78 driver = std::make_unique<LinkerDriver>(*ctx);
80 driver->linkerMain(args);
82 return errorCount() == 0;
85 // Parse options of the form "old;new".
86 static std::pair<StringRef, StringRef> getOldNewOptions(opt::InputArgList &args,
87 unsigned id) {
88 auto *arg = args.getLastArg(id);
89 if (!arg)
90 return {"", ""};
92 StringRef s = arg->getValue();
93 std::pair<StringRef, StringRef> ret = s.split(';');
94 if (ret.second.empty())
95 error(arg->getSpelling() + " expects 'old;new' format, but got " + s);
96 return ret;
99 // Drop directory components and replace extension with
100 // ".exe", ".dll" or ".sys".
101 static std::string getOutputPath(StringRef path) {
102 StringRef ext = ".exe";
103 if (config->dll)
104 ext = ".dll";
105 else if (config->driver)
106 ext = ".sys";
108 return (sys::path::stem(path) + ext).str();
111 // Returns true if S matches /crtend.?\.o$/.
112 static bool isCrtend(StringRef s) {
113 if (!s.endswith(".o"))
114 return false;
115 s = s.drop_back(2);
116 if (s.endswith("crtend"))
117 return true;
118 return !s.empty() && s.drop_back().endswith("crtend");
121 // ErrorOr is not default constructible, so it cannot be used as the type
122 // parameter of a future.
123 // FIXME: We could open the file in createFutureForFile and avoid needing to
124 // return an error here, but for the moment that would cost us a file descriptor
125 // (a limited resource on Windows) for the duration that the future is pending.
126 using MBErrPair = std::pair<std::unique_ptr<MemoryBuffer>, std::error_code>;
128 // Create a std::future that opens and maps a file using the best strategy for
129 // the host platform.
130 static std::future<MBErrPair> createFutureForFile(std::string path) {
131 #if _WIN64
132 // On Windows, file I/O is relatively slow so it is best to do this
133 // asynchronously. But 32-bit has issues with potentially launching tons
134 // of threads
135 auto strategy = std::launch::async;
136 #else
137 auto strategy = std::launch::deferred;
138 #endif
139 return std::async(strategy, [=]() {
140 auto mbOrErr = MemoryBuffer::getFile(path, /*IsText=*/false,
141 /*RequiresNullTerminator=*/false);
142 if (!mbOrErr)
143 return MBErrPair{nullptr, mbOrErr.getError()};
144 return MBErrPair{std::move(*mbOrErr), std::error_code()};
148 // Symbol names are mangled by prepending "_" on x86.
149 static StringRef mangle(StringRef sym) {
150 assert(config->machine != IMAGE_FILE_MACHINE_UNKNOWN);
151 if (config->machine == I386)
152 return saver().save("_" + sym);
153 return sym;
156 static llvm::Triple::ArchType getArch() {
157 switch (config->machine) {
158 case I386:
159 return llvm::Triple::ArchType::x86;
160 case AMD64:
161 return llvm::Triple::ArchType::x86_64;
162 case ARMNT:
163 return llvm::Triple::ArchType::arm;
164 case ARM64:
165 return llvm::Triple::ArchType::aarch64;
166 default:
167 return llvm::Triple::ArchType::UnknownArch;
171 bool LinkerDriver::findUnderscoreMangle(StringRef sym) {
172 Symbol *s = ctx.symtab.findMangle(mangle(sym));
173 return s && !isa<Undefined>(s);
176 MemoryBufferRef LinkerDriver::takeBuffer(std::unique_ptr<MemoryBuffer> mb) {
177 MemoryBufferRef mbref = *mb;
178 make<std::unique_ptr<MemoryBuffer>>(std::move(mb)); // take ownership
180 if (driver->tar)
181 driver->tar->append(relativeToRoot(mbref.getBufferIdentifier()),
182 mbref.getBuffer());
183 return mbref;
186 void LinkerDriver::addBuffer(std::unique_ptr<MemoryBuffer> mb,
187 bool wholeArchive, bool lazy) {
188 StringRef filename = mb->getBufferIdentifier();
190 MemoryBufferRef mbref = takeBuffer(std::move(mb));
191 filePaths.push_back(filename);
193 // File type is detected by contents, not by file extension.
194 switch (identify_magic(mbref.getBuffer())) {
195 case file_magic::windows_resource:
196 resources.push_back(mbref);
197 break;
198 case file_magic::archive:
199 if (wholeArchive) {
200 std::unique_ptr<Archive> file =
201 CHECK(Archive::create(mbref), filename + ": failed to parse archive");
202 Archive *archive = file.get();
203 make<std::unique_ptr<Archive>>(std::move(file)); // take ownership
205 int memberIndex = 0;
206 for (MemoryBufferRef m : getArchiveMembers(archive))
207 addArchiveBuffer(m, "<whole-archive>", filename, memberIndex++);
208 return;
210 ctx.symtab.addFile(make<ArchiveFile>(ctx, mbref));
211 break;
212 case file_magic::bitcode:
213 ctx.symtab.addFile(make<BitcodeFile>(ctx, mbref, "", 0, lazy));
214 break;
215 case file_magic::coff_object:
216 case file_magic::coff_import_library:
217 ctx.symtab.addFile(make<ObjFile>(ctx, mbref, lazy));
218 break;
219 case file_magic::pdb:
220 ctx.symtab.addFile(make<PDBInputFile>(ctx, mbref));
221 break;
222 case file_magic::coff_cl_gl_object:
223 error(filename + ": is not a native COFF file. Recompile without /GL");
224 break;
225 case file_magic::pecoff_executable:
226 if (config->mingw) {
227 ctx.symtab.addFile(make<DLLFile>(ctx, mbref));
228 break;
230 if (filename.endswith_insensitive(".dll")) {
231 error(filename + ": bad file type. Did you specify a DLL instead of an "
232 "import library?");
233 break;
235 LLVM_FALLTHROUGH;
236 default:
237 error(mbref.getBufferIdentifier() + ": unknown file type");
238 break;
242 void LinkerDriver::enqueuePath(StringRef path, bool wholeArchive, bool lazy) {
243 auto future = std::make_shared<std::future<MBErrPair>>(
244 createFutureForFile(std::string(path)));
245 std::string pathStr = std::string(path);
246 enqueueTask([=]() {
247 auto mbOrErr = future->get();
248 if (mbOrErr.second) {
249 std::string msg =
250 "could not open '" + pathStr + "': " + mbOrErr.second.message();
251 // Check if the filename is a typo for an option flag. OptTable thinks
252 // that all args that are not known options and that start with / are
253 // filenames, but e.g. `/nodefaultlibs` is more likely a typo for
254 // the option `/nodefaultlib` than a reference to a file in the root
255 // directory.
256 std::string nearest;
257 if (optTable.findNearest(pathStr, nearest) > 1)
258 error(msg);
259 else
260 error(msg + "; did you mean '" + nearest + "'");
261 } else
262 driver->addBuffer(std::move(mbOrErr.first), wholeArchive, lazy);
266 void LinkerDriver::addArchiveBuffer(MemoryBufferRef mb, StringRef symName,
267 StringRef parentName,
268 uint64_t offsetInArchive) {
269 file_magic magic = identify_magic(mb.getBuffer());
270 if (magic == file_magic::coff_import_library) {
271 InputFile *imp = make<ImportFile>(ctx, mb);
272 imp->parentName = parentName;
273 ctx.symtab.addFile(imp);
274 return;
277 InputFile *obj;
278 if (magic == file_magic::coff_object) {
279 obj = make<ObjFile>(ctx, mb);
280 } else if (magic == file_magic::bitcode) {
281 obj =
282 make<BitcodeFile>(ctx, mb, parentName, offsetInArchive, /*lazy=*/false);
283 } else {
284 error("unknown file type: " + mb.getBufferIdentifier());
285 return;
288 obj->parentName = parentName;
289 ctx.symtab.addFile(obj);
290 log("Loaded " + toString(obj) + " for " + symName);
293 void LinkerDriver::enqueueArchiveMember(const Archive::Child &c,
294 const Archive::Symbol &sym,
295 StringRef parentName) {
297 auto reportBufferError = [=](Error &&e, StringRef childName) {
298 fatal("could not get the buffer for the member defining symbol " +
299 toCOFFString(sym) + ": " + parentName + "(" + childName + "): " +
300 toString(std::move(e)));
303 if (!c.getParent()->isThin()) {
304 uint64_t offsetInArchive = c.getChildOffset();
305 Expected<MemoryBufferRef> mbOrErr = c.getMemoryBufferRef();
306 if (!mbOrErr)
307 reportBufferError(mbOrErr.takeError(), check(c.getFullName()));
308 MemoryBufferRef mb = mbOrErr.get();
309 enqueueTask([=]() {
310 driver->addArchiveBuffer(mb, toCOFFString(sym), parentName,
311 offsetInArchive);
313 return;
316 std::string childName = CHECK(
317 c.getFullName(),
318 "could not get the filename for the member defining symbol " +
319 toCOFFString(sym));
320 auto future = std::make_shared<std::future<MBErrPair>>(
321 createFutureForFile(childName));
322 enqueueTask([=]() {
323 auto mbOrErr = future->get();
324 if (mbOrErr.second)
325 reportBufferError(errorCodeToError(mbOrErr.second), childName);
326 // Pass empty string as archive name so that the original filename is
327 // used as the buffer identifier.
328 driver->addArchiveBuffer(takeBuffer(std::move(mbOrErr.first)),
329 toCOFFString(sym), "", /*OffsetInArchive=*/0);
333 static bool isDecorated(StringRef sym) {
334 return sym.startswith("@") || sym.contains("@@") || sym.startswith("?") ||
335 (!config->mingw && sym.contains('@'));
338 // Parses .drectve section contents and returns a list of files
339 // specified by /defaultlib.
340 void LinkerDriver::parseDirectives(InputFile *file) {
341 StringRef s = file->getDirectives();
342 if (s.empty())
343 return;
345 log("Directives: " + toString(file) + ": " + s);
347 ArgParser parser;
348 // .drectve is always tokenized using Windows shell rules.
349 // /EXPORT: option can appear too many times, processing in fastpath.
350 ParsedDirectives directives = parser.parseDirectives(s);
352 for (StringRef e : directives.exports) {
353 // If a common header file contains dllexported function
354 // declarations, many object files may end up with having the
355 // same /EXPORT options. In order to save cost of parsing them,
356 // we dedup them first.
357 if (!directivesExports.insert(e).second)
358 continue;
360 Export exp = parseExport(e);
361 if (config->machine == I386 && config->mingw) {
362 if (!isDecorated(exp.name))
363 exp.name = saver().save("_" + exp.name);
364 if (!exp.extName.empty() && !isDecorated(exp.extName))
365 exp.extName = saver().save("_" + exp.extName);
367 exp.directives = true;
368 config->exports.push_back(exp);
371 // Handle /include: in bulk.
372 for (StringRef inc : directives.includes)
373 addUndefined(inc);
375 // https://docs.microsoft.com/en-us/cpp/preprocessor/comment-c-cpp?view=msvc-160
376 for (auto *arg : directives.args) {
377 switch (arg->getOption().getID()) {
378 case OPT_aligncomm:
379 parseAligncomm(arg->getValue());
380 break;
381 case OPT_alternatename:
382 parseAlternateName(arg->getValue());
383 break;
384 case OPT_defaultlib:
385 if (Optional<StringRef> path = findLib(arg->getValue()))
386 enqueuePath(*path, false, false);
387 break;
388 case OPT_entry:
389 config->entry = addUndefined(mangle(arg->getValue()));
390 break;
391 case OPT_failifmismatch:
392 checkFailIfMismatch(arg->getValue(), file);
393 break;
394 case OPT_incl:
395 addUndefined(arg->getValue());
396 break;
397 case OPT_manifestdependency:
398 config->manifestDependencies.insert(arg->getValue());
399 break;
400 case OPT_merge:
401 parseMerge(arg->getValue());
402 break;
403 case OPT_nodefaultlib:
404 config->noDefaultLibs.insert(doFindLib(arg->getValue()).lower());
405 break;
406 case OPT_section:
407 parseSection(arg->getValue());
408 break;
409 case OPT_stack:
410 parseNumbers(arg->getValue(), &config->stackReserve,
411 &config->stackCommit);
412 break;
413 case OPT_subsystem: {
414 bool gotVersion = false;
415 parseSubsystem(arg->getValue(), &config->subsystem,
416 &config->majorSubsystemVersion,
417 &config->minorSubsystemVersion, &gotVersion);
418 if (gotVersion) {
419 config->majorOSVersion = config->majorSubsystemVersion;
420 config->minorOSVersion = config->minorSubsystemVersion;
422 break;
424 // Only add flags here that link.exe accepts in
425 // `#pragma comment(linker, "/flag")`-generated sections.
426 case OPT_editandcontinue:
427 case OPT_guardsym:
428 case OPT_throwingnew:
429 break;
430 default:
431 error(arg->getSpelling() + " is not allowed in .drectve");
436 // Find file from search paths. You can omit ".obj", this function takes
437 // care of that. Note that the returned path is not guaranteed to exist.
438 StringRef LinkerDriver::doFindFile(StringRef filename) {
439 bool hasPathSep = (filename.find_first_of("/\\") != StringRef::npos);
440 if (hasPathSep)
441 return filename;
442 bool hasExt = filename.contains('.');
443 for (StringRef dir : searchPaths) {
444 SmallString<128> path = dir;
445 sys::path::append(path, filename);
446 if (sys::fs::exists(path.str()))
447 return saver().save(path.str());
448 if (!hasExt) {
449 path.append(".obj");
450 if (sys::fs::exists(path.str()))
451 return saver().save(path.str());
454 return filename;
457 static Optional<sys::fs::UniqueID> getUniqueID(StringRef path) {
458 sys::fs::UniqueID ret;
459 if (sys::fs::getUniqueID(path, ret))
460 return None;
461 return ret;
464 // Resolves a file path. This never returns the same path
465 // (in that case, it returns None).
466 Optional<StringRef> LinkerDriver::findFile(StringRef filename) {
467 StringRef path = doFindFile(filename);
469 if (Optional<sys::fs::UniqueID> id = getUniqueID(path)) {
470 bool seen = !visitedFiles.insert(*id).second;
471 if (seen)
472 return None;
475 if (path.endswith_insensitive(".lib"))
476 visitedLibs.insert(std::string(sys::path::filename(path)));
477 return path;
480 // MinGW specific. If an embedded directive specified to link to
481 // foo.lib, but it isn't found, try libfoo.a instead.
482 StringRef LinkerDriver::doFindLibMinGW(StringRef filename) {
483 if (filename.contains('/') || filename.contains('\\'))
484 return filename;
486 SmallString<128> s = filename;
487 sys::path::replace_extension(s, ".a");
488 StringRef libName = saver().save("lib" + s.str());
489 return doFindFile(libName);
492 // Find library file from search path.
493 StringRef LinkerDriver::doFindLib(StringRef filename) {
494 // Add ".lib" to Filename if that has no file extension.
495 bool hasExt = filename.contains('.');
496 if (!hasExt)
497 filename = saver().save(filename + ".lib");
498 StringRef ret = doFindFile(filename);
499 // For MinGW, if the find above didn't turn up anything, try
500 // looking for a MinGW formatted library name.
501 if (config->mingw && ret == filename)
502 return doFindLibMinGW(filename);
503 return ret;
506 // Resolves a library path. /nodefaultlib options are taken into
507 // consideration. This never returns the same path (in that case,
508 // it returns None).
509 Optional<StringRef> LinkerDriver::findLib(StringRef filename) {
510 if (config->noDefaultLibAll)
511 return None;
512 if (!visitedLibs.insert(filename.lower()).second)
513 return None;
515 StringRef path = doFindLib(filename);
516 if (config->noDefaultLibs.count(path.lower()))
517 return None;
519 if (Optional<sys::fs::UniqueID> id = getUniqueID(path))
520 if (!visitedFiles.insert(*id).second)
521 return None;
522 return path;
525 void LinkerDriver::detectWinSysRoot(const opt::InputArgList &Args) {
526 IntrusiveRefCntPtr<vfs::FileSystem> VFS = vfs::getRealFileSystem();
528 // Check the command line first, that's the user explicitly telling us what to
529 // use. Check the environment next, in case we're being invoked from a VS
530 // command prompt. Failing that, just try to find the newest Visual Studio
531 // version we can and use its default VC toolchain.
532 Optional<StringRef> VCToolsDir, VCToolsVersion, WinSysRoot;
533 if (auto *A = Args.getLastArg(OPT_vctoolsdir))
534 VCToolsDir = A->getValue();
535 if (auto *A = Args.getLastArg(OPT_vctoolsversion))
536 VCToolsVersion = A->getValue();
537 if (auto *A = Args.getLastArg(OPT_winsysroot))
538 WinSysRoot = A->getValue();
539 if (!findVCToolChainViaCommandLine(*VFS, VCToolsDir, VCToolsVersion,
540 WinSysRoot, vcToolChainPath, vsLayout) &&
541 (Args.hasArg(OPT_lldignoreenv) ||
542 !findVCToolChainViaEnvironment(*VFS, vcToolChainPath, vsLayout)) &&
543 !findVCToolChainViaSetupConfig(*VFS, vcToolChainPath, vsLayout) &&
544 !findVCToolChainViaRegistry(vcToolChainPath, vsLayout))
545 return;
547 // If the VC environment hasn't been configured (perhaps because the user did
548 // not run vcvarsall), try to build a consistent link environment. If the
549 // environment variable is set however, assume the user knows what they're
550 // doing. If the user passes /vctoolsdir or /winsdkdir, trust that over env
551 // vars.
552 if (const auto *A = Args.getLastArg(OPT_diasdkdir, OPT_winsysroot)) {
553 diaPath = A->getValue();
554 if (A->getOption().getID() == OPT_winsysroot)
555 path::append(diaPath, "DIA SDK");
557 useWinSysRootLibPath = Args.hasArg(OPT_lldignoreenv) ||
558 !Process::GetEnv("LIB") ||
559 Args.getLastArg(OPT_vctoolsdir, OPT_winsysroot);
560 if (Args.hasArg(OPT_lldignoreenv) || !Process::GetEnv("LIB") ||
561 Args.getLastArg(OPT_winsdkdir, OPT_winsysroot)) {
562 Optional<StringRef> WinSdkDir, WinSdkVersion;
563 if (auto *A = Args.getLastArg(OPT_winsdkdir))
564 WinSdkDir = A->getValue();
565 if (auto *A = Args.getLastArg(OPT_winsdkversion))
566 WinSdkVersion = A->getValue();
568 if (useUniversalCRT(vsLayout, vcToolChainPath, getArch(), *VFS)) {
569 std::string UniversalCRTSdkPath;
570 std::string UCRTVersion;
571 if (getUniversalCRTSdkDir(*VFS, WinSdkDir, WinSdkVersion, WinSysRoot,
572 UniversalCRTSdkPath, UCRTVersion)) {
573 universalCRTLibPath = UniversalCRTSdkPath;
574 path::append(universalCRTLibPath, "Lib", UCRTVersion, "ucrt");
578 std::string sdkPath;
579 std::string windowsSDKIncludeVersion;
580 std::string windowsSDKLibVersion;
581 if (getWindowsSDKDir(*VFS, WinSdkDir, WinSdkVersion, WinSysRoot, sdkPath,
582 sdkMajor, windowsSDKIncludeVersion,
583 windowsSDKLibVersion)) {
584 windowsSdkLibPath = sdkPath;
585 path::append(windowsSdkLibPath, "Lib");
586 if (sdkMajor >= 8)
587 path::append(windowsSdkLibPath, windowsSDKLibVersion, "um");
592 void LinkerDriver::addWinSysRootLibSearchPaths() {
593 if (!diaPath.empty()) {
594 // The DIA SDK always uses the legacy vc arch, even in new MSVC versions.
595 path::append(diaPath, "lib", archToLegacyVCArch(getArch()));
596 searchPaths.push_back(saver().save(diaPath.str()));
598 if (useWinSysRootLibPath) {
599 searchPaths.push_back(saver().save(getSubDirectoryPath(
600 SubDirectoryType::Lib, vsLayout, vcToolChainPath, getArch())));
601 searchPaths.push_back(saver().save(
602 getSubDirectoryPath(SubDirectoryType::Lib, vsLayout, vcToolChainPath,
603 getArch(), "atlmfc")));
605 if (!universalCRTLibPath.empty()) {
606 StringRef ArchName = archToWindowsSDKArch(getArch());
607 if (!ArchName.empty()) {
608 path::append(universalCRTLibPath, ArchName);
609 searchPaths.push_back(saver().save(universalCRTLibPath.str()));
612 if (!windowsSdkLibPath.empty()) {
613 std::string path;
614 if (appendArchToWindowsSDKLibPath(sdkMajor, windowsSdkLibPath, getArch(),
615 path))
616 searchPaths.push_back(saver().save(path));
620 // Parses LIB environment which contains a list of search paths.
621 void LinkerDriver::addLibSearchPaths() {
622 Optional<std::string> envOpt = Process::GetEnv("LIB");
623 if (!envOpt.hasValue())
624 return;
625 StringRef env = saver().save(*envOpt);
626 while (!env.empty()) {
627 StringRef path;
628 std::tie(path, env) = env.split(';');
629 searchPaths.push_back(path);
633 Symbol *LinkerDriver::addUndefined(StringRef name) {
634 Symbol *b = ctx.symtab.addUndefined(name);
635 if (!b->isGCRoot) {
636 b->isGCRoot = true;
637 config->gcroot.push_back(b);
639 return b;
642 StringRef LinkerDriver::mangleMaybe(Symbol *s) {
643 // If the plain symbol name has already been resolved, do nothing.
644 Undefined *unmangled = dyn_cast<Undefined>(s);
645 if (!unmangled)
646 return "";
648 // Otherwise, see if a similar, mangled symbol exists in the symbol table.
649 Symbol *mangled = ctx.symtab.findMangle(unmangled->getName());
650 if (!mangled)
651 return "";
653 // If we find a similar mangled symbol, make this an alias to it and return
654 // its name.
655 log(unmangled->getName() + " aliased to " + mangled->getName());
656 unmangled->weakAlias = ctx.symtab.addUndefined(mangled->getName());
657 return mangled->getName();
660 // Windows specific -- find default entry point name.
662 // There are four different entry point functions for Windows executables,
663 // each of which corresponds to a user-defined "main" function. This function
664 // infers an entry point from a user-defined "main" function.
665 StringRef LinkerDriver::findDefaultEntry() {
666 assert(config->subsystem != IMAGE_SUBSYSTEM_UNKNOWN &&
667 "must handle /subsystem before calling this");
669 if (config->mingw)
670 return mangle(config->subsystem == IMAGE_SUBSYSTEM_WINDOWS_GUI
671 ? "WinMainCRTStartup"
672 : "mainCRTStartup");
674 if (config->subsystem == IMAGE_SUBSYSTEM_WINDOWS_GUI) {
675 if (findUnderscoreMangle("wWinMain")) {
676 if (!findUnderscoreMangle("WinMain"))
677 return mangle("wWinMainCRTStartup");
678 warn("found both wWinMain and WinMain; using latter");
680 return mangle("WinMainCRTStartup");
682 if (findUnderscoreMangle("wmain")) {
683 if (!findUnderscoreMangle("main"))
684 return mangle("wmainCRTStartup");
685 warn("found both wmain and main; using latter");
687 return mangle("mainCRTStartup");
690 WindowsSubsystem LinkerDriver::inferSubsystem() {
691 if (config->dll)
692 return IMAGE_SUBSYSTEM_WINDOWS_GUI;
693 if (config->mingw)
694 return IMAGE_SUBSYSTEM_WINDOWS_CUI;
695 // Note that link.exe infers the subsystem from the presence of these
696 // functions even if /entry: or /nodefaultlib are passed which causes them
697 // to not be called.
698 bool haveMain = findUnderscoreMangle("main");
699 bool haveWMain = findUnderscoreMangle("wmain");
700 bool haveWinMain = findUnderscoreMangle("WinMain");
701 bool haveWWinMain = findUnderscoreMangle("wWinMain");
702 if (haveMain || haveWMain) {
703 if (haveWinMain || haveWWinMain) {
704 warn(std::string("found ") + (haveMain ? "main" : "wmain") + " and " +
705 (haveWinMain ? "WinMain" : "wWinMain") +
706 "; defaulting to /subsystem:console");
708 return IMAGE_SUBSYSTEM_WINDOWS_CUI;
710 if (haveWinMain || haveWWinMain)
711 return IMAGE_SUBSYSTEM_WINDOWS_GUI;
712 return IMAGE_SUBSYSTEM_UNKNOWN;
715 static uint64_t getDefaultImageBase() {
716 if (config->is64())
717 return config->dll ? 0x180000000 : 0x140000000;
718 return config->dll ? 0x10000000 : 0x400000;
721 static std::string rewritePath(StringRef s) {
722 if (fs::exists(s))
723 return relativeToRoot(s);
724 return std::string(s);
727 // Reconstructs command line arguments so that so that you can re-run
728 // the same command with the same inputs. This is for --reproduce.
729 static std::string createResponseFile(const opt::InputArgList &args,
730 ArrayRef<StringRef> filePaths,
731 ArrayRef<StringRef> searchPaths) {
732 SmallString<0> data;
733 raw_svector_ostream os(data);
735 for (auto *arg : args) {
736 switch (arg->getOption().getID()) {
737 case OPT_linkrepro:
738 case OPT_reproduce:
739 case OPT_INPUT:
740 case OPT_defaultlib:
741 case OPT_libpath:
742 case OPT_winsysroot:
743 break;
744 case OPT_call_graph_ordering_file:
745 case OPT_deffile:
746 case OPT_manifestinput:
747 case OPT_natvis:
748 os << arg->getSpelling() << quote(rewritePath(arg->getValue())) << '\n';
749 break;
750 case OPT_order: {
751 StringRef orderFile = arg->getValue();
752 orderFile.consume_front("@");
753 os << arg->getSpelling() << '@' << quote(rewritePath(orderFile)) << '\n';
754 break;
756 case OPT_pdbstream: {
757 const std::pair<StringRef, StringRef> nameFile =
758 StringRef(arg->getValue()).split("=");
759 os << arg->getSpelling() << nameFile.first << '='
760 << quote(rewritePath(nameFile.second)) << '\n';
761 break;
763 case OPT_implib:
764 case OPT_manifestfile:
765 case OPT_pdb:
766 case OPT_pdbstripped:
767 case OPT_out:
768 os << arg->getSpelling() << sys::path::filename(arg->getValue()) << "\n";
769 break;
770 default:
771 os << toString(*arg) << "\n";
775 for (StringRef path : searchPaths) {
776 std::string relPath = relativeToRoot(path);
777 os << "/libpath:" << quote(relPath) << "\n";
780 for (StringRef path : filePaths)
781 os << quote(relativeToRoot(path)) << "\n";
783 return std::string(data.str());
786 enum class DebugKind {
787 Unknown,
788 None,
789 Full,
790 FastLink,
791 GHash,
792 NoGHash,
793 Dwarf,
794 Symtab
797 static DebugKind parseDebugKind(const opt::InputArgList &args) {
798 auto *a = args.getLastArg(OPT_debug, OPT_debug_opt);
799 if (!a)
800 return DebugKind::None;
801 if (a->getNumValues() == 0)
802 return DebugKind::Full;
804 DebugKind debug = StringSwitch<DebugKind>(a->getValue())
805 .CaseLower("none", DebugKind::None)
806 .CaseLower("full", DebugKind::Full)
807 .CaseLower("fastlink", DebugKind::FastLink)
808 // LLD extensions
809 .CaseLower("ghash", DebugKind::GHash)
810 .CaseLower("noghash", DebugKind::NoGHash)
811 .CaseLower("dwarf", DebugKind::Dwarf)
812 .CaseLower("symtab", DebugKind::Symtab)
813 .Default(DebugKind::Unknown);
815 if (debug == DebugKind::FastLink) {
816 warn("/debug:fastlink unsupported; using /debug:full");
817 return DebugKind::Full;
819 if (debug == DebugKind::Unknown) {
820 error("/debug: unknown option: " + Twine(a->getValue()));
821 return DebugKind::None;
823 return debug;
826 static unsigned parseDebugTypes(const opt::InputArgList &args) {
827 unsigned debugTypes = static_cast<unsigned>(DebugType::None);
829 if (auto *a = args.getLastArg(OPT_debugtype)) {
830 SmallVector<StringRef, 3> types;
831 StringRef(a->getValue())
832 .split(types, ',', /*MaxSplit=*/-1, /*KeepEmpty=*/false);
834 for (StringRef type : types) {
835 unsigned v = StringSwitch<unsigned>(type.lower())
836 .Case("cv", static_cast<unsigned>(DebugType::CV))
837 .Case("pdata", static_cast<unsigned>(DebugType::PData))
838 .Case("fixup", static_cast<unsigned>(DebugType::Fixup))
839 .Default(0);
840 if (v == 0) {
841 warn("/debugtype: unknown option '" + type + "'");
842 continue;
844 debugTypes |= v;
846 return debugTypes;
849 // Default debug types
850 debugTypes = static_cast<unsigned>(DebugType::CV);
851 if (args.hasArg(OPT_driver))
852 debugTypes |= static_cast<unsigned>(DebugType::PData);
853 if (args.hasArg(OPT_profile))
854 debugTypes |= static_cast<unsigned>(DebugType::Fixup);
856 return debugTypes;
859 static std::string getMapFile(const opt::InputArgList &args,
860 opt::OptSpecifier os, opt::OptSpecifier osFile) {
861 auto *arg = args.getLastArg(os, osFile);
862 if (!arg)
863 return "";
864 if (arg->getOption().getID() == osFile.getID())
865 return arg->getValue();
867 assert(arg->getOption().getID() == os.getID());
868 StringRef outFile = config->outputFile;
869 return (outFile.substr(0, outFile.rfind('.')) + ".map").str();
872 static std::string getImplibPath() {
873 if (!config->implib.empty())
874 return std::string(config->implib);
875 SmallString<128> out = StringRef(config->outputFile);
876 sys::path::replace_extension(out, ".lib");
877 return std::string(out.str());
880 // The import name is calculated as follows:
882 // | LIBRARY w/ ext | LIBRARY w/o ext | no LIBRARY
883 // -----+----------------+---------------------+------------------
884 // LINK | {value} | {value}.{.dll/.exe} | {output name}
885 // LIB | {value} | {value}.dll | {output name}.dll
887 static std::string getImportName(bool asLib) {
888 SmallString<128> out;
890 if (config->importName.empty()) {
891 out.assign(sys::path::filename(config->outputFile));
892 if (asLib)
893 sys::path::replace_extension(out, ".dll");
894 } else {
895 out.assign(config->importName);
896 if (!sys::path::has_extension(out))
897 sys::path::replace_extension(out,
898 (config->dll || asLib) ? ".dll" : ".exe");
901 return std::string(out.str());
904 static void createImportLibrary(bool asLib) {
905 std::vector<COFFShortExport> exports;
906 for (Export &e1 : config->exports) {
907 COFFShortExport e2;
908 e2.Name = std::string(e1.name);
909 e2.SymbolName = std::string(e1.symbolName);
910 e2.ExtName = std::string(e1.extName);
911 e2.AliasTarget = std::string(e1.aliasTarget);
912 e2.Ordinal = e1.ordinal;
913 e2.Noname = e1.noname;
914 e2.Data = e1.data;
915 e2.Private = e1.isPrivate;
916 e2.Constant = e1.constant;
917 exports.push_back(e2);
920 std::string libName = getImportName(asLib);
921 std::string path = getImplibPath();
923 if (!config->incremental) {
924 checkError(writeImportLibrary(libName, path, exports, config->machine,
925 config->mingw));
926 return;
929 // If the import library already exists, replace it only if the contents
930 // have changed.
931 ErrorOr<std::unique_ptr<MemoryBuffer>> oldBuf = MemoryBuffer::getFile(
932 path, /*IsText=*/false, /*RequiresNullTerminator=*/false);
933 if (!oldBuf) {
934 checkError(writeImportLibrary(libName, path, exports, config->machine,
935 config->mingw));
936 return;
939 SmallString<128> tmpName;
940 if (std::error_code ec =
941 sys::fs::createUniqueFile(path + ".tmp-%%%%%%%%.lib", tmpName))
942 fatal("cannot create temporary file for import library " + path + ": " +
943 ec.message());
945 if (Error e = writeImportLibrary(libName, tmpName, exports, config->machine,
946 config->mingw)) {
947 checkError(std::move(e));
948 return;
951 std::unique_ptr<MemoryBuffer> newBuf = check(MemoryBuffer::getFile(
952 tmpName, /*IsText=*/false, /*RequiresNullTerminator=*/false));
953 if ((*oldBuf)->getBuffer() != newBuf->getBuffer()) {
954 oldBuf->reset();
955 checkError(errorCodeToError(sys::fs::rename(tmpName, path)));
956 } else {
957 sys::fs::remove(tmpName);
961 static void parseModuleDefs(StringRef path) {
962 std::unique_ptr<MemoryBuffer> mb =
963 CHECK(MemoryBuffer::getFile(path, /*IsText=*/false,
964 /*RequiresNullTerminator=*/false,
965 /*IsVolatile=*/true),
966 "could not open " + path);
967 COFFModuleDefinition m = check(parseCOFFModuleDefinition(
968 mb->getMemBufferRef(), config->machine, config->mingw));
970 // Include in /reproduce: output if applicable.
971 driver->takeBuffer(std::move(mb));
973 if (config->outputFile.empty())
974 config->outputFile = std::string(saver().save(m.OutputFile));
975 config->importName = std::string(saver().save(m.ImportName));
976 if (m.ImageBase)
977 config->imageBase = m.ImageBase;
978 if (m.StackReserve)
979 config->stackReserve = m.StackReserve;
980 if (m.StackCommit)
981 config->stackCommit = m.StackCommit;
982 if (m.HeapReserve)
983 config->heapReserve = m.HeapReserve;
984 if (m.HeapCommit)
985 config->heapCommit = m.HeapCommit;
986 if (m.MajorImageVersion)
987 config->majorImageVersion = m.MajorImageVersion;
988 if (m.MinorImageVersion)
989 config->minorImageVersion = m.MinorImageVersion;
990 if (m.MajorOSVersion)
991 config->majorOSVersion = m.MajorOSVersion;
992 if (m.MinorOSVersion)
993 config->minorOSVersion = m.MinorOSVersion;
995 for (COFFShortExport e1 : m.Exports) {
996 Export e2;
997 // In simple cases, only Name is set. Renamed exports are parsed
998 // and set as "ExtName = Name". If Name has the form "OtherDll.Func",
999 // it shouldn't be a normal exported function but a forward to another
1000 // DLL instead. This is supported by both MS and GNU linkers.
1001 if (!e1.ExtName.empty() && e1.ExtName != e1.Name &&
1002 StringRef(e1.Name).contains('.')) {
1003 e2.name = saver().save(e1.ExtName);
1004 e2.forwardTo = saver().save(e1.Name);
1005 config->exports.push_back(e2);
1006 continue;
1008 e2.name = saver().save(e1.Name);
1009 e2.extName = saver().save(e1.ExtName);
1010 e2.aliasTarget = saver().save(e1.AliasTarget);
1011 e2.ordinal = e1.Ordinal;
1012 e2.noname = e1.Noname;
1013 e2.data = e1.Data;
1014 e2.isPrivate = e1.Private;
1015 e2.constant = e1.Constant;
1016 config->exports.push_back(e2);
1020 void LinkerDriver::enqueueTask(std::function<void()> task) {
1021 taskQueue.push_back(std::move(task));
1024 bool LinkerDriver::run() {
1025 ScopedTimer t(ctx.inputFileTimer);
1027 bool didWork = !taskQueue.empty();
1028 while (!taskQueue.empty()) {
1029 taskQueue.front()();
1030 taskQueue.pop_front();
1032 return didWork;
1035 // Parse an /order file. If an option is given, the linker places
1036 // COMDAT sections in the same order as their names appear in the
1037 // given file.
1038 static void parseOrderFile(COFFLinkerContext &ctx, StringRef arg) {
1039 // For some reason, the MSVC linker requires a filename to be
1040 // preceded by "@".
1041 if (!arg.startswith("@")) {
1042 error("malformed /order option: '@' missing");
1043 return;
1046 // Get a list of all comdat sections for error checking.
1047 DenseSet<StringRef> set;
1048 for (Chunk *c : ctx.symtab.getChunks())
1049 if (auto *sec = dyn_cast<SectionChunk>(c))
1050 if (sec->sym)
1051 set.insert(sec->sym->getName());
1053 // Open a file.
1054 StringRef path = arg.substr(1);
1055 std::unique_ptr<MemoryBuffer> mb =
1056 CHECK(MemoryBuffer::getFile(path, /*IsText=*/false,
1057 /*RequiresNullTerminator=*/false,
1058 /*IsVolatile=*/true),
1059 "could not open " + path);
1061 // Parse a file. An order file contains one symbol per line.
1062 // All symbols that were not present in a given order file are
1063 // considered to have the lowest priority 0 and are placed at
1064 // end of an output section.
1065 for (StringRef arg : args::getLines(mb->getMemBufferRef())) {
1066 std::string s(arg);
1067 if (config->machine == I386 && !isDecorated(s))
1068 s = "_" + s;
1070 if (set.count(s) == 0) {
1071 if (config->warnMissingOrderSymbol)
1072 warn("/order:" + arg + ": missing symbol: " + s + " [LNK4037]");
1074 else
1075 config->order[s] = INT_MIN + config->order.size();
1078 // Include in /reproduce: output if applicable.
1079 driver->takeBuffer(std::move(mb));
1082 static void parseCallGraphFile(COFFLinkerContext &ctx, StringRef path) {
1083 std::unique_ptr<MemoryBuffer> mb =
1084 CHECK(MemoryBuffer::getFile(path, /*IsText=*/false,
1085 /*RequiresNullTerminator=*/false,
1086 /*IsVolatile=*/true),
1087 "could not open " + path);
1089 // Build a map from symbol name to section.
1090 DenseMap<StringRef, Symbol *> map;
1091 for (ObjFile *file : ctx.objFileInstances)
1092 for (Symbol *sym : file->getSymbols())
1093 if (sym)
1094 map[sym->getName()] = sym;
1096 auto findSection = [&](StringRef name) -> SectionChunk * {
1097 Symbol *sym = map.lookup(name);
1098 if (!sym) {
1099 if (config->warnMissingOrderSymbol)
1100 warn(path + ": no such symbol: " + name);
1101 return nullptr;
1104 if (DefinedCOFF *dr = dyn_cast_or_null<DefinedCOFF>(sym))
1105 return dyn_cast_or_null<SectionChunk>(dr->getChunk());
1106 return nullptr;
1109 for (StringRef line : args::getLines(*mb)) {
1110 SmallVector<StringRef, 3> fields;
1111 line.split(fields, ' ');
1112 uint64_t count;
1114 if (fields.size() != 3 || !to_integer(fields[2], count)) {
1115 error(path + ": parse error");
1116 return;
1119 if (SectionChunk *from = findSection(fields[0]))
1120 if (SectionChunk *to = findSection(fields[1]))
1121 config->callGraphProfile[{from, to}] += count;
1124 // Include in /reproduce: output if applicable.
1125 driver->takeBuffer(std::move(mb));
1128 static void readCallGraphsFromObjectFiles(COFFLinkerContext &ctx) {
1129 for (ObjFile *obj : ctx.objFileInstances) {
1130 if (obj->callgraphSec) {
1131 ArrayRef<uint8_t> contents;
1132 cantFail(
1133 obj->getCOFFObj()->getSectionContents(obj->callgraphSec, contents));
1134 BinaryStreamReader reader(contents, support::little);
1135 while (!reader.empty()) {
1136 uint32_t fromIndex, toIndex;
1137 uint64_t count;
1138 if (Error err = reader.readInteger(fromIndex))
1139 fatal(toString(obj) + ": Expected 32-bit integer");
1140 if (Error err = reader.readInteger(toIndex))
1141 fatal(toString(obj) + ": Expected 32-bit integer");
1142 if (Error err = reader.readInteger(count))
1143 fatal(toString(obj) + ": Expected 64-bit integer");
1144 auto *fromSym = dyn_cast_or_null<Defined>(obj->getSymbol(fromIndex));
1145 auto *toSym = dyn_cast_or_null<Defined>(obj->getSymbol(toIndex));
1146 if (!fromSym || !toSym)
1147 continue;
1148 auto *from = dyn_cast_or_null<SectionChunk>(fromSym->getChunk());
1149 auto *to = dyn_cast_or_null<SectionChunk>(toSym->getChunk());
1150 if (from && to)
1151 config->callGraphProfile[{from, to}] += count;
1157 static void markAddrsig(Symbol *s) {
1158 if (auto *d = dyn_cast_or_null<Defined>(s))
1159 if (SectionChunk *c = dyn_cast_or_null<SectionChunk>(d->getChunk()))
1160 c->keepUnique = true;
1163 static void findKeepUniqueSections(COFFLinkerContext &ctx) {
1164 // Exported symbols could be address-significant in other executables or DSOs,
1165 // so we conservatively mark them as address-significant.
1166 for (Export &r : config->exports)
1167 markAddrsig(r.sym);
1169 // Visit the address-significance table in each object file and mark each
1170 // referenced symbol as address-significant.
1171 for (ObjFile *obj : ctx.objFileInstances) {
1172 ArrayRef<Symbol *> syms = obj->getSymbols();
1173 if (obj->addrsigSec) {
1174 ArrayRef<uint8_t> contents;
1175 cantFail(
1176 obj->getCOFFObj()->getSectionContents(obj->addrsigSec, contents));
1177 const uint8_t *cur = contents.begin();
1178 while (cur != contents.end()) {
1179 unsigned size;
1180 const char *err;
1181 uint64_t symIndex = decodeULEB128(cur, &size, contents.end(), &err);
1182 if (err)
1183 fatal(toString(obj) + ": could not decode addrsig section: " + err);
1184 if (symIndex >= syms.size())
1185 fatal(toString(obj) + ": invalid symbol index in addrsig section");
1186 markAddrsig(syms[symIndex]);
1187 cur += size;
1189 } else {
1190 // If an object file does not have an address-significance table,
1191 // conservatively mark all of its symbols as address-significant.
1192 for (Symbol *s : syms)
1193 markAddrsig(s);
1198 // link.exe replaces each %foo% in altPath with the contents of environment
1199 // variable foo, and adds the two magic env vars _PDB (expands to the basename
1200 // of pdb's output path) and _EXT (expands to the extension of the output
1201 // binary).
1202 // lld only supports %_PDB% and %_EXT% and warns on references to all other env
1203 // vars.
1204 static void parsePDBAltPath(StringRef altPath) {
1205 SmallString<128> buf;
1206 StringRef pdbBasename =
1207 sys::path::filename(config->pdbPath, sys::path::Style::windows);
1208 StringRef binaryExtension =
1209 sys::path::extension(config->outputFile, sys::path::Style::windows);
1210 if (!binaryExtension.empty())
1211 binaryExtension = binaryExtension.substr(1); // %_EXT% does not include '.'.
1213 // Invariant:
1214 // +--------- cursor ('a...' might be the empty string).
1215 // | +----- firstMark
1216 // | | +- secondMark
1217 // v v v
1218 // a...%...%...
1219 size_t cursor = 0;
1220 while (cursor < altPath.size()) {
1221 size_t firstMark, secondMark;
1222 if ((firstMark = altPath.find('%', cursor)) == StringRef::npos ||
1223 (secondMark = altPath.find('%', firstMark + 1)) == StringRef::npos) {
1224 // Didn't find another full fragment, treat rest of string as literal.
1225 buf.append(altPath.substr(cursor));
1226 break;
1229 // Found a full fragment. Append text in front of first %, and interpret
1230 // text between first and second % as variable name.
1231 buf.append(altPath.substr(cursor, firstMark - cursor));
1232 StringRef var = altPath.substr(firstMark, secondMark - firstMark + 1);
1233 if (var.equals_insensitive("%_pdb%"))
1234 buf.append(pdbBasename);
1235 else if (var.equals_insensitive("%_ext%"))
1236 buf.append(binaryExtension);
1237 else {
1238 warn("only %_PDB% and %_EXT% supported in /pdbaltpath:, keeping " +
1239 var + " as literal");
1240 buf.append(var);
1243 cursor = secondMark + 1;
1246 config->pdbAltPath = buf;
1249 /// Convert resource files and potentially merge input resource object
1250 /// trees into one resource tree.
1251 /// Call after ObjFile::Instances is complete.
1252 void LinkerDriver::convertResources() {
1253 std::vector<ObjFile *> resourceObjFiles;
1255 for (ObjFile *f : ctx.objFileInstances) {
1256 if (f->isResourceObjFile())
1257 resourceObjFiles.push_back(f);
1260 if (!config->mingw &&
1261 (resourceObjFiles.size() > 1 ||
1262 (resourceObjFiles.size() == 1 && !resources.empty()))) {
1263 error((!resources.empty() ? "internal .obj file created from .res files"
1264 : toString(resourceObjFiles[1])) +
1265 ": more than one resource obj file not allowed, already got " +
1266 toString(resourceObjFiles.front()));
1267 return;
1270 if (resources.empty() && resourceObjFiles.size() <= 1) {
1271 // No resources to convert, and max one resource object file in
1272 // the input. Keep that preconverted resource section as is.
1273 for (ObjFile *f : resourceObjFiles)
1274 f->includeResourceChunks();
1275 return;
1277 ObjFile *f =
1278 make<ObjFile>(ctx, convertResToCOFF(resources, resourceObjFiles));
1279 ctx.symtab.addFile(f);
1280 f->includeResourceChunks();
1283 // In MinGW, if no symbols are chosen to be exported, then all symbols are
1284 // automatically exported by default. This behavior can be forced by the
1285 // -export-all-symbols option, so that it happens even when exports are
1286 // explicitly specified. The automatic behavior can be disabled using the
1287 // -exclude-all-symbols option, so that lld-link behaves like link.exe rather
1288 // than MinGW in the case that nothing is explicitly exported.
1289 void LinkerDriver::maybeExportMinGWSymbols(const opt::InputArgList &args) {
1290 if (!args.hasArg(OPT_export_all_symbols)) {
1291 if (!config->dll)
1292 return;
1294 if (!config->exports.empty())
1295 return;
1296 if (args.hasArg(OPT_exclude_all_symbols))
1297 return;
1300 AutoExporter exporter;
1302 for (auto *arg : args.filtered(OPT_wholearchive_file))
1303 if (Optional<StringRef> path = doFindFile(arg->getValue()))
1304 exporter.addWholeArchive(*path);
1306 ctx.symtab.forEachSymbol([&](Symbol *s) {
1307 auto *def = dyn_cast<Defined>(s);
1308 if (!exporter.shouldExport(ctx, def))
1309 return;
1311 if (!def->isGCRoot) {
1312 def->isGCRoot = true;
1313 config->gcroot.push_back(def);
1316 Export e;
1317 e.name = def->getName();
1318 e.sym = def;
1319 if (Chunk *c = def->getChunk())
1320 if (!(c->getOutputCharacteristics() & IMAGE_SCN_MEM_EXECUTE))
1321 e.data = true;
1322 s->isUsedInRegularObj = true;
1323 config->exports.push_back(e);
1327 // lld has a feature to create a tar file containing all input files as well as
1328 // all command line options, so that other people can run lld again with exactly
1329 // the same inputs. This feature is accessible via /linkrepro and /reproduce.
1331 // /linkrepro and /reproduce are very similar, but /linkrepro takes a directory
1332 // name while /reproduce takes a full path. We have /linkrepro for compatibility
1333 // with Microsoft link.exe.
1334 Optional<std::string> getReproduceFile(const opt::InputArgList &args) {
1335 if (auto *arg = args.getLastArg(OPT_reproduce))
1336 return std::string(arg->getValue());
1338 if (auto *arg = args.getLastArg(OPT_linkrepro)) {
1339 SmallString<64> path = StringRef(arg->getValue());
1340 sys::path::append(path, "repro.tar");
1341 return std::string(path);
1344 // This is intentionally not guarded by OPT_lldignoreenv since writing
1345 // a repro tar file doesn't affect the main output.
1346 if (auto *path = getenv("LLD_REPRODUCE"))
1347 return std::string(path);
1349 return None;
1352 void LinkerDriver::linkerMain(ArrayRef<const char *> argsArr) {
1353 ScopedTimer rootTimer(ctx.rootTimer);
1355 // Needed for LTO.
1356 InitializeAllTargetInfos();
1357 InitializeAllTargets();
1358 InitializeAllTargetMCs();
1359 InitializeAllAsmParsers();
1360 InitializeAllAsmPrinters();
1362 // If the first command line argument is "/lib", link.exe acts like lib.exe.
1363 // We call our own implementation of lib.exe that understands bitcode files.
1364 if (argsArr.size() > 1 &&
1365 (StringRef(argsArr[1]).equals_insensitive("/lib") ||
1366 StringRef(argsArr[1]).equals_insensitive("-lib"))) {
1367 if (llvm::libDriverMain(argsArr.slice(1)) != 0)
1368 fatal("lib failed");
1369 return;
1372 // Parse command line options.
1373 ArgParser parser;
1374 opt::InputArgList args = parser.parse(argsArr);
1376 // Parse and evaluate -mllvm options.
1377 std::vector<const char *> v;
1378 v.push_back("lld-link (LLVM option parsing)");
1379 for (auto *arg : args.filtered(OPT_mllvm))
1380 v.push_back(arg->getValue());
1381 cl::ResetAllOptionOccurrences();
1382 cl::ParseCommandLineOptions(v.size(), v.data());
1384 // Handle /errorlimit early, because error() depends on it.
1385 if (auto *arg = args.getLastArg(OPT_errorlimit)) {
1386 int n = 20;
1387 StringRef s = arg->getValue();
1388 if (s.getAsInteger(10, n))
1389 error(arg->getSpelling() + " number expected, but got " + s);
1390 errorHandler().errorLimit = n;
1393 // Handle /help
1394 if (args.hasArg(OPT_help)) {
1395 printHelp(argsArr[0]);
1396 return;
1399 // /threads: takes a positive integer and provides the default value for
1400 // /opt:lldltojobs=.
1401 if (auto *arg = args.getLastArg(OPT_threads)) {
1402 StringRef v(arg->getValue());
1403 unsigned threads = 0;
1404 if (!llvm::to_integer(v, threads, 0) || threads == 0)
1405 error(arg->getSpelling() + ": expected a positive integer, but got '" +
1406 arg->getValue() + "'");
1407 parallel::strategy = hardware_concurrency(threads);
1408 config->thinLTOJobs = v.str();
1411 if (args.hasArg(OPT_show_timing))
1412 config->showTiming = true;
1414 config->showSummary = args.hasArg(OPT_summary);
1416 // Handle --version, which is an lld extension. This option is a bit odd
1417 // because it doesn't start with "/", but we deliberately chose "--" to
1418 // avoid conflict with /version and for compatibility with clang-cl.
1419 if (args.hasArg(OPT_dash_dash_version)) {
1420 message(getLLDVersion());
1421 return;
1424 // Handle /lldmingw early, since it can potentially affect how other
1425 // options are handled.
1426 config->mingw = args.hasArg(OPT_lldmingw);
1428 // Handle /linkrepro and /reproduce.
1429 if (Optional<std::string> path = getReproduceFile(args)) {
1430 Expected<std::unique_ptr<TarWriter>> errOrWriter =
1431 TarWriter::create(*path, sys::path::stem(*path));
1433 if (errOrWriter) {
1434 tar = std::move(*errOrWriter);
1435 } else {
1436 error("/linkrepro: failed to open " + *path + ": " +
1437 toString(errOrWriter.takeError()));
1441 if (!args.hasArg(OPT_INPUT, OPT_wholearchive_file)) {
1442 if (args.hasArg(OPT_deffile))
1443 config->noEntry = true;
1444 else
1445 fatal("no input files");
1448 // Construct search path list.
1449 searchPaths.push_back("");
1450 for (auto *arg : args.filtered(OPT_libpath))
1451 searchPaths.push_back(arg->getValue());
1452 detectWinSysRoot(args);
1453 if (!args.hasArg(OPT_lldignoreenv) && !args.hasArg(OPT_winsysroot))
1454 addLibSearchPaths();
1456 // Handle /ignore
1457 for (auto *arg : args.filtered(OPT_ignore)) {
1458 SmallVector<StringRef, 8> vec;
1459 StringRef(arg->getValue()).split(vec, ',');
1460 for (StringRef s : vec) {
1461 if (s == "4037")
1462 config->warnMissingOrderSymbol = false;
1463 else if (s == "4099")
1464 config->warnDebugInfoUnusable = false;
1465 else if (s == "4217")
1466 config->warnLocallyDefinedImported = false;
1467 else if (s == "longsections")
1468 config->warnLongSectionNames = false;
1469 // Other warning numbers are ignored.
1473 // Handle /out
1474 if (auto *arg = args.getLastArg(OPT_out))
1475 config->outputFile = arg->getValue();
1477 // Handle /verbose
1478 if (args.hasArg(OPT_verbose))
1479 config->verbose = true;
1480 errorHandler().verbose = config->verbose;
1482 // Handle /force or /force:unresolved
1483 if (args.hasArg(OPT_force, OPT_force_unresolved))
1484 config->forceUnresolved = true;
1486 // Handle /force or /force:multiple
1487 if (args.hasArg(OPT_force, OPT_force_multiple))
1488 config->forceMultiple = true;
1490 // Handle /force or /force:multipleres
1491 if (args.hasArg(OPT_force, OPT_force_multipleres))
1492 config->forceMultipleRes = true;
1494 // Handle /debug
1495 DebugKind debug = parseDebugKind(args);
1496 if (debug == DebugKind::Full || debug == DebugKind::Dwarf ||
1497 debug == DebugKind::GHash || debug == DebugKind::NoGHash) {
1498 config->debug = true;
1499 config->incremental = true;
1502 // Handle /demangle
1503 config->demangle = args.hasFlag(OPT_demangle, OPT_demangle_no, true);
1505 // Handle /debugtype
1506 config->debugTypes = parseDebugTypes(args);
1508 // Handle /driver[:uponly|:wdm].
1509 config->driverUponly = args.hasArg(OPT_driver_uponly) ||
1510 args.hasArg(OPT_driver_uponly_wdm) ||
1511 args.hasArg(OPT_driver_wdm_uponly);
1512 config->driverWdm = args.hasArg(OPT_driver_wdm) ||
1513 args.hasArg(OPT_driver_uponly_wdm) ||
1514 args.hasArg(OPT_driver_wdm_uponly);
1515 config->driver =
1516 config->driverUponly || config->driverWdm || args.hasArg(OPT_driver);
1518 // Handle /pdb
1519 bool shouldCreatePDB =
1520 (debug == DebugKind::Full || debug == DebugKind::GHash ||
1521 debug == DebugKind::NoGHash);
1522 if (shouldCreatePDB) {
1523 if (auto *arg = args.getLastArg(OPT_pdb))
1524 config->pdbPath = arg->getValue();
1525 if (auto *arg = args.getLastArg(OPT_pdbaltpath))
1526 config->pdbAltPath = arg->getValue();
1527 if (auto *arg = args.getLastArg(OPT_pdbpagesize))
1528 parsePDBPageSize(arg->getValue());
1529 if (args.hasArg(OPT_natvis))
1530 config->natvisFiles = args.getAllArgValues(OPT_natvis);
1531 if (args.hasArg(OPT_pdbstream)) {
1532 for (const StringRef value : args.getAllArgValues(OPT_pdbstream)) {
1533 const std::pair<StringRef, StringRef> nameFile = value.split("=");
1534 const StringRef name = nameFile.first;
1535 const std::string file = nameFile.second.str();
1536 config->namedStreams[name] = file;
1540 if (auto *arg = args.getLastArg(OPT_pdb_source_path))
1541 config->pdbSourcePath = arg->getValue();
1544 // Handle /pdbstripped
1545 if (args.hasArg(OPT_pdbstripped))
1546 warn("ignoring /pdbstripped flag, it is not yet supported");
1548 // Handle /noentry
1549 if (args.hasArg(OPT_noentry)) {
1550 if (args.hasArg(OPT_dll))
1551 config->noEntry = true;
1552 else
1553 error("/noentry must be specified with /dll");
1556 // Handle /dll
1557 if (args.hasArg(OPT_dll)) {
1558 config->dll = true;
1559 config->manifestID = 2;
1562 // Handle /dynamicbase and /fixed. We can't use hasFlag for /dynamicbase
1563 // because we need to explicitly check whether that option or its inverse was
1564 // present in the argument list in order to handle /fixed.
1565 auto *dynamicBaseArg = args.getLastArg(OPT_dynamicbase, OPT_dynamicbase_no);
1566 if (dynamicBaseArg &&
1567 dynamicBaseArg->getOption().getID() == OPT_dynamicbase_no)
1568 config->dynamicBase = false;
1570 // MSDN claims "/FIXED:NO is the default setting for a DLL, and /FIXED is the
1571 // default setting for any other project type.", but link.exe defaults to
1572 // /FIXED:NO for exe outputs as well. Match behavior, not docs.
1573 bool fixed = args.hasFlag(OPT_fixed, OPT_fixed_no, false);
1574 if (fixed) {
1575 if (dynamicBaseArg &&
1576 dynamicBaseArg->getOption().getID() == OPT_dynamicbase) {
1577 error("/fixed must not be specified with /dynamicbase");
1578 } else {
1579 config->relocatable = false;
1580 config->dynamicBase = false;
1584 // Handle /appcontainer
1585 config->appContainer =
1586 args.hasFlag(OPT_appcontainer, OPT_appcontainer_no, false);
1588 // Handle /machine
1589 if (auto *arg = args.getLastArg(OPT_machine)) {
1590 config->machine = getMachineType(arg->getValue());
1591 if (config->machine == IMAGE_FILE_MACHINE_UNKNOWN)
1592 fatal(Twine("unknown /machine argument: ") + arg->getValue());
1593 addWinSysRootLibSearchPaths();
1596 // Handle /nodefaultlib:<filename>
1597 for (auto *arg : args.filtered(OPT_nodefaultlib))
1598 config->noDefaultLibs.insert(doFindLib(arg->getValue()).lower());
1600 // Handle /nodefaultlib
1601 if (args.hasArg(OPT_nodefaultlib_all))
1602 config->noDefaultLibAll = true;
1604 // Handle /base
1605 if (auto *arg = args.getLastArg(OPT_base))
1606 parseNumbers(arg->getValue(), &config->imageBase);
1608 // Handle /filealign
1609 if (auto *arg = args.getLastArg(OPT_filealign)) {
1610 parseNumbers(arg->getValue(), &config->fileAlign);
1611 if (!isPowerOf2_64(config->fileAlign))
1612 error("/filealign: not a power of two: " + Twine(config->fileAlign));
1615 // Handle /stack
1616 if (auto *arg = args.getLastArg(OPT_stack))
1617 parseNumbers(arg->getValue(), &config->stackReserve, &config->stackCommit);
1619 // Handle /guard:cf
1620 if (auto *arg = args.getLastArg(OPT_guard))
1621 parseGuard(arg->getValue());
1623 // Handle /heap
1624 if (auto *arg = args.getLastArg(OPT_heap))
1625 parseNumbers(arg->getValue(), &config->heapReserve, &config->heapCommit);
1627 // Handle /version
1628 if (auto *arg = args.getLastArg(OPT_version))
1629 parseVersion(arg->getValue(), &config->majorImageVersion,
1630 &config->minorImageVersion);
1632 // Handle /subsystem
1633 if (auto *arg = args.getLastArg(OPT_subsystem))
1634 parseSubsystem(arg->getValue(), &config->subsystem,
1635 &config->majorSubsystemVersion,
1636 &config->minorSubsystemVersion);
1638 // Handle /osversion
1639 if (auto *arg = args.getLastArg(OPT_osversion)) {
1640 parseVersion(arg->getValue(), &config->majorOSVersion,
1641 &config->minorOSVersion);
1642 } else {
1643 config->majorOSVersion = config->majorSubsystemVersion;
1644 config->minorOSVersion = config->minorSubsystemVersion;
1647 // Handle /timestamp
1648 if (llvm::opt::Arg *arg = args.getLastArg(OPT_timestamp, OPT_repro)) {
1649 if (arg->getOption().getID() == OPT_repro) {
1650 config->timestamp = 0;
1651 config->repro = true;
1652 } else {
1653 config->repro = false;
1654 StringRef value(arg->getValue());
1655 if (value.getAsInteger(0, config->timestamp))
1656 fatal(Twine("invalid timestamp: ") + value +
1657 ". Expected 32-bit integer");
1659 } else {
1660 config->repro = false;
1661 config->timestamp = time(nullptr);
1664 // Handle /alternatename
1665 for (auto *arg : args.filtered(OPT_alternatename))
1666 parseAlternateName(arg->getValue());
1668 // Handle /include
1669 for (auto *arg : args.filtered(OPT_incl))
1670 addUndefined(arg->getValue());
1672 // Handle /implib
1673 if (auto *arg = args.getLastArg(OPT_implib))
1674 config->implib = arg->getValue();
1676 // Handle /opt.
1677 bool doGC = debug == DebugKind::None || args.hasArg(OPT_profile);
1678 Optional<ICFLevel> icfLevel = None;
1679 if (args.hasArg(OPT_profile))
1680 icfLevel = ICFLevel::None;
1681 unsigned tailMerge = 1;
1682 bool ltoNewPM = true;
1683 bool ltoDebugPM = false;
1684 for (auto *arg : args.filtered(OPT_opt)) {
1685 std::string str = StringRef(arg->getValue()).lower();
1686 SmallVector<StringRef, 1> vec;
1687 StringRef(str).split(vec, ',');
1688 for (StringRef s : vec) {
1689 if (s == "ref") {
1690 doGC = true;
1691 } else if (s == "noref") {
1692 doGC = false;
1693 } else if (s == "icf" || s.startswith("icf=")) {
1694 icfLevel = ICFLevel::All;
1695 } else if (s == "safeicf") {
1696 icfLevel = ICFLevel::Safe;
1697 } else if (s == "noicf") {
1698 icfLevel = ICFLevel::None;
1699 } else if (s == "lldtailmerge") {
1700 tailMerge = 2;
1701 } else if (s == "nolldtailmerge") {
1702 tailMerge = 0;
1703 } else if (s == "ltonewpassmanager") {
1704 ltoNewPM = true;
1705 } else if (s == "noltonewpassmanager") {
1706 ltoNewPM = false;
1707 } else if (s == "ltodebugpassmanager") {
1708 ltoDebugPM = true;
1709 } else if (s == "noltodebugpassmanager") {
1710 ltoDebugPM = false;
1711 } else if (s.startswith("lldlto=")) {
1712 StringRef optLevel = s.substr(7);
1713 if (optLevel.getAsInteger(10, config->ltoo) || config->ltoo > 3)
1714 error("/opt:lldlto: invalid optimization level: " + optLevel);
1715 } else if (s.startswith("lldltojobs=")) {
1716 StringRef jobs = s.substr(11);
1717 if (!get_threadpool_strategy(jobs))
1718 error("/opt:lldltojobs: invalid job count: " + jobs);
1719 config->thinLTOJobs = jobs.str();
1720 } else if (s.startswith("lldltopartitions=")) {
1721 StringRef n = s.substr(17);
1722 if (n.getAsInteger(10, config->ltoPartitions) ||
1723 config->ltoPartitions == 0)
1724 error("/opt:lldltopartitions: invalid partition count: " + n);
1725 } else if (s != "lbr" && s != "nolbr")
1726 error("/opt: unknown option: " + s);
1730 if (!icfLevel)
1731 icfLevel = doGC ? ICFLevel::All : ICFLevel::None;
1732 config->doGC = doGC;
1733 config->doICF = icfLevel.getValue();
1734 config->tailMerge =
1735 (tailMerge == 1 && config->doICF != ICFLevel::None) || tailMerge == 2;
1736 config->ltoNewPassManager = ltoNewPM;
1737 config->ltoDebugPassManager = ltoDebugPM;
1739 // Handle /lldsavetemps
1740 if (args.hasArg(OPT_lldsavetemps))
1741 config->saveTemps = true;
1743 // Handle /kill-at
1744 if (args.hasArg(OPT_kill_at))
1745 config->killAt = true;
1747 // Handle /lldltocache
1748 if (auto *arg = args.getLastArg(OPT_lldltocache))
1749 config->ltoCache = arg->getValue();
1751 // Handle /lldsavecachepolicy
1752 if (auto *arg = args.getLastArg(OPT_lldltocachepolicy))
1753 config->ltoCachePolicy = CHECK(
1754 parseCachePruningPolicy(arg->getValue()),
1755 Twine("/lldltocachepolicy: invalid cache policy: ") + arg->getValue());
1757 // Handle /failifmismatch
1758 for (auto *arg : args.filtered(OPT_failifmismatch))
1759 checkFailIfMismatch(arg->getValue(), nullptr);
1761 // Handle /merge
1762 for (auto *arg : args.filtered(OPT_merge))
1763 parseMerge(arg->getValue());
1765 // Add default section merging rules after user rules. User rules take
1766 // precedence, but we will emit a warning if there is a conflict.
1767 parseMerge(".idata=.rdata");
1768 parseMerge(".didat=.rdata");
1769 parseMerge(".edata=.rdata");
1770 parseMerge(".xdata=.rdata");
1771 parseMerge(".bss=.data");
1773 if (config->mingw) {
1774 parseMerge(".ctors=.rdata");
1775 parseMerge(".dtors=.rdata");
1776 parseMerge(".CRT=.rdata");
1779 // Handle /section
1780 for (auto *arg : args.filtered(OPT_section))
1781 parseSection(arg->getValue());
1783 // Handle /align
1784 if (auto *arg = args.getLastArg(OPT_align)) {
1785 parseNumbers(arg->getValue(), &config->align);
1786 if (!isPowerOf2_64(config->align))
1787 error("/align: not a power of two: " + StringRef(arg->getValue()));
1788 if (!args.hasArg(OPT_driver))
1789 warn("/align specified without /driver; image may not run");
1792 // Handle /aligncomm
1793 for (auto *arg : args.filtered(OPT_aligncomm))
1794 parseAligncomm(arg->getValue());
1796 // Handle /manifestdependency.
1797 for (auto *arg : args.filtered(OPT_manifestdependency))
1798 config->manifestDependencies.insert(arg->getValue());
1800 // Handle /manifest and /manifest:
1801 if (auto *arg = args.getLastArg(OPT_manifest, OPT_manifest_colon)) {
1802 if (arg->getOption().getID() == OPT_manifest)
1803 config->manifest = Configuration::SideBySide;
1804 else
1805 parseManifest(arg->getValue());
1808 // Handle /manifestuac
1809 if (auto *arg = args.getLastArg(OPT_manifestuac))
1810 parseManifestUAC(arg->getValue());
1812 // Handle /manifestfile
1813 if (auto *arg = args.getLastArg(OPT_manifestfile))
1814 config->manifestFile = arg->getValue();
1816 // Handle /manifestinput
1817 for (auto *arg : args.filtered(OPT_manifestinput))
1818 config->manifestInput.push_back(arg->getValue());
1820 if (!config->manifestInput.empty() &&
1821 config->manifest != Configuration::Embed) {
1822 fatal("/manifestinput: requires /manifest:embed");
1825 config->thinLTOEmitImportsFiles = args.hasArg(OPT_thinlto_emit_imports_files);
1826 config->thinLTOIndexOnly = args.hasArg(OPT_thinlto_index_only) ||
1827 args.hasArg(OPT_thinlto_index_only_arg);
1828 config->thinLTOIndexOnlyArg =
1829 args.getLastArgValue(OPT_thinlto_index_only_arg);
1830 config->thinLTOPrefixReplace =
1831 getOldNewOptions(args, OPT_thinlto_prefix_replace);
1832 config->thinLTOObjectSuffixReplace =
1833 getOldNewOptions(args, OPT_thinlto_object_suffix_replace);
1834 config->ltoObjPath = args.getLastArgValue(OPT_lto_obj_path);
1835 config->ltoCSProfileGenerate = args.hasArg(OPT_lto_cs_profile_generate);
1836 config->ltoCSProfileFile = args.getLastArgValue(OPT_lto_cs_profile_file);
1837 // Handle miscellaneous boolean flags.
1838 config->ltoPGOWarnMismatch = args.hasFlag(OPT_lto_pgo_warn_mismatch,
1839 OPT_lto_pgo_warn_mismatch_no, true);
1840 config->allowBind = args.hasFlag(OPT_allowbind, OPT_allowbind_no, true);
1841 config->allowIsolation =
1842 args.hasFlag(OPT_allowisolation, OPT_allowisolation_no, true);
1843 config->incremental =
1844 args.hasFlag(OPT_incremental, OPT_incremental_no,
1845 !config->doGC && config->doICF == ICFLevel::None &&
1846 !args.hasArg(OPT_order) && !args.hasArg(OPT_profile));
1847 config->integrityCheck =
1848 args.hasFlag(OPT_integritycheck, OPT_integritycheck_no, false);
1849 config->cetCompat = args.hasFlag(OPT_cetcompat, OPT_cetcompat_no, false);
1850 config->nxCompat = args.hasFlag(OPT_nxcompat, OPT_nxcompat_no, true);
1851 for (auto *arg : args.filtered(OPT_swaprun))
1852 parseSwaprun(arg->getValue());
1853 config->terminalServerAware =
1854 !config->dll && args.hasFlag(OPT_tsaware, OPT_tsaware_no, true);
1855 config->debugDwarf = debug == DebugKind::Dwarf;
1856 config->debugGHashes = debug == DebugKind::GHash || debug == DebugKind::Full;
1857 config->debugSymtab = debug == DebugKind::Symtab;
1858 config->autoImport =
1859 args.hasFlag(OPT_auto_import, OPT_auto_import_no, config->mingw);
1860 config->pseudoRelocs = args.hasFlag(
1861 OPT_runtime_pseudo_reloc, OPT_runtime_pseudo_reloc_no, config->mingw);
1862 config->callGraphProfileSort = args.hasFlag(
1863 OPT_call_graph_profile_sort, OPT_call_graph_profile_sort_no, true);
1864 config->stdcallFixup =
1865 args.hasFlag(OPT_stdcall_fixup, OPT_stdcall_fixup_no, config->mingw);
1866 config->warnStdcallFixup = !args.hasArg(OPT_stdcall_fixup);
1868 // Don't warn about long section names, such as .debug_info, for mingw or
1869 // when -debug:dwarf is requested.
1870 if (config->mingw || config->debugDwarf)
1871 config->warnLongSectionNames = false;
1873 config->lldmapFile = getMapFile(args, OPT_lldmap, OPT_lldmap_file);
1874 config->mapFile = getMapFile(args, OPT_map, OPT_map_file);
1876 if (config->lldmapFile != "" && config->lldmapFile == config->mapFile) {
1877 warn("/lldmap and /map have the same output file '" + config->mapFile +
1878 "'.\n>>> ignoring /lldmap");
1879 config->lldmapFile.clear();
1882 if (config->incremental && args.hasArg(OPT_profile)) {
1883 warn("ignoring '/incremental' due to '/profile' specification");
1884 config->incremental = false;
1887 if (config->incremental && args.hasArg(OPT_order)) {
1888 warn("ignoring '/incremental' due to '/order' specification");
1889 config->incremental = false;
1892 if (config->incremental && config->doGC) {
1893 warn("ignoring '/incremental' because REF is enabled; use '/opt:noref' to "
1894 "disable");
1895 config->incremental = false;
1898 if (config->incremental && config->doICF != ICFLevel::None) {
1899 warn("ignoring '/incremental' because ICF is enabled; use '/opt:noicf' to "
1900 "disable");
1901 config->incremental = false;
1904 if (errorCount())
1905 return;
1907 std::set<sys::fs::UniqueID> wholeArchives;
1908 for (auto *arg : args.filtered(OPT_wholearchive_file))
1909 if (Optional<StringRef> path = doFindFile(arg->getValue()))
1910 if (Optional<sys::fs::UniqueID> id = getUniqueID(*path))
1911 wholeArchives.insert(*id);
1913 // A predicate returning true if a given path is an argument for
1914 // /wholearchive:, or /wholearchive is enabled globally.
1915 // This function is a bit tricky because "foo.obj /wholearchive:././foo.obj"
1916 // needs to be handled as "/wholearchive:foo.obj foo.obj".
1917 auto isWholeArchive = [&](StringRef path) -> bool {
1918 if (args.hasArg(OPT_wholearchive_flag))
1919 return true;
1920 if (Optional<sys::fs::UniqueID> id = getUniqueID(path))
1921 return wholeArchives.count(*id);
1922 return false;
1925 // Create a list of input files. These can be given as OPT_INPUT options
1926 // and OPT_wholearchive_file options, and we also need to track OPT_start_lib
1927 // and OPT_end_lib.
1928 bool inLib = false;
1929 for (auto *arg : args) {
1930 switch (arg->getOption().getID()) {
1931 case OPT_end_lib:
1932 if (!inLib)
1933 error("stray " + arg->getSpelling());
1934 inLib = false;
1935 break;
1936 case OPT_start_lib:
1937 if (inLib)
1938 error("nested " + arg->getSpelling());
1939 inLib = true;
1940 break;
1941 case OPT_wholearchive_file:
1942 if (Optional<StringRef> path = findFile(arg->getValue()))
1943 enqueuePath(*path, true, inLib);
1944 break;
1945 case OPT_INPUT:
1946 if (Optional<StringRef> path = findFile(arg->getValue()))
1947 enqueuePath(*path, isWholeArchive(*path), inLib);
1948 break;
1949 default:
1950 // Ignore other options.
1951 break;
1955 // Read all input files given via the command line.
1956 run();
1957 if (errorCount())
1958 return;
1960 // We should have inferred a machine type by now from the input files, but if
1961 // not we assume x64.
1962 if (config->machine == IMAGE_FILE_MACHINE_UNKNOWN) {
1963 warn("/machine is not specified. x64 is assumed");
1964 config->machine = AMD64;
1965 addWinSysRootLibSearchPaths();
1967 config->wordsize = config->is64() ? 8 : 4;
1969 // Process files specified as /defaultlib. These must be processed after
1970 // addWinSysRootLibSearchPaths(), which is why they are in a separate loop.
1971 for (auto *arg : args.filtered(OPT_defaultlib))
1972 if (Optional<StringRef> path = findLib(arg->getValue()))
1973 enqueuePath(*path, false, false);
1974 run();
1975 if (errorCount())
1976 return;
1978 // Handle /safeseh, x86 only, on by default, except for mingw.
1979 if (config->machine == I386) {
1980 config->safeSEH = args.hasFlag(OPT_safeseh, OPT_safeseh_no, !config->mingw);
1981 config->noSEH = args.hasArg(OPT_noseh);
1984 // Handle /functionpadmin
1985 for (auto *arg : args.filtered(OPT_functionpadmin, OPT_functionpadmin_opt))
1986 parseFunctionPadMin(arg, config->machine);
1988 if (tar) {
1989 tar->append("response.txt",
1990 createResponseFile(args, filePaths,
1991 ArrayRef<StringRef>(searchPaths).slice(1)));
1994 // Handle /largeaddressaware
1995 config->largeAddressAware = args.hasFlag(
1996 OPT_largeaddressaware, OPT_largeaddressaware_no, config->is64());
1998 // Handle /highentropyva
1999 config->highEntropyVA =
2000 config->is64() &&
2001 args.hasFlag(OPT_highentropyva, OPT_highentropyva_no, true);
2003 if (!config->dynamicBase &&
2004 (config->machine == ARMNT || config->machine == ARM64))
2005 error("/dynamicbase:no is not compatible with " +
2006 machineToStr(config->machine));
2008 // Handle /export
2009 for (auto *arg : args.filtered(OPT_export)) {
2010 Export e = parseExport(arg->getValue());
2011 if (config->machine == I386) {
2012 if (!isDecorated(e.name))
2013 e.name = saver().save("_" + e.name);
2014 if (!e.extName.empty() && !isDecorated(e.extName))
2015 e.extName = saver().save("_" + e.extName);
2017 config->exports.push_back(e);
2020 // Handle /def
2021 if (auto *arg = args.getLastArg(OPT_deffile)) {
2022 // parseModuleDefs mutates Config object.
2023 parseModuleDefs(arg->getValue());
2026 // Handle generation of import library from a def file.
2027 if (!args.hasArg(OPT_INPUT, OPT_wholearchive_file)) {
2028 fixupExports();
2029 createImportLibrary(/*asLib=*/true);
2030 return;
2033 // Windows specific -- if no /subsystem is given, we need to infer
2034 // that from entry point name. Must happen before /entry handling,
2035 // and after the early return when just writing an import library.
2036 if (config->subsystem == IMAGE_SUBSYSTEM_UNKNOWN) {
2037 config->subsystem = inferSubsystem();
2038 if (config->subsystem == IMAGE_SUBSYSTEM_UNKNOWN)
2039 fatal("subsystem must be defined");
2042 // Handle /entry and /dll
2043 if (auto *arg = args.getLastArg(OPT_entry)) {
2044 config->entry = addUndefined(mangle(arg->getValue()));
2045 } else if (!config->entry && !config->noEntry) {
2046 if (args.hasArg(OPT_dll)) {
2047 StringRef s = (config->machine == I386) ? "__DllMainCRTStartup@12"
2048 : "_DllMainCRTStartup";
2049 config->entry = addUndefined(s);
2050 } else if (config->driverWdm) {
2051 // /driver:wdm implies /entry:_NtProcessStartup
2052 config->entry = addUndefined(mangle("_NtProcessStartup"));
2053 } else {
2054 // Windows specific -- If entry point name is not given, we need to
2055 // infer that from user-defined entry name.
2056 StringRef s = findDefaultEntry();
2057 if (s.empty())
2058 fatal("entry point must be defined");
2059 config->entry = addUndefined(s);
2060 log("Entry name inferred: " + s);
2064 // Handle /delayload
2065 for (auto *arg : args.filtered(OPT_delayload)) {
2066 config->delayLoads.insert(StringRef(arg->getValue()).lower());
2067 if (config->machine == I386) {
2068 config->delayLoadHelper = addUndefined("___delayLoadHelper2@8");
2069 } else {
2070 config->delayLoadHelper = addUndefined("__delayLoadHelper2");
2074 // Set default image name if neither /out or /def set it.
2075 if (config->outputFile.empty()) {
2076 config->outputFile = getOutputPath(
2077 (*args.filtered(OPT_INPUT, OPT_wholearchive_file).begin())->getValue());
2080 // Fail early if an output file is not writable.
2081 if (auto e = tryCreateFile(config->outputFile)) {
2082 error("cannot open output file " + config->outputFile + ": " + e.message());
2083 return;
2086 if (shouldCreatePDB) {
2087 // Put the PDB next to the image if no /pdb flag was passed.
2088 if (config->pdbPath.empty()) {
2089 config->pdbPath = config->outputFile;
2090 sys::path::replace_extension(config->pdbPath, ".pdb");
2093 // The embedded PDB path should be the absolute path to the PDB if no
2094 // /pdbaltpath flag was passed.
2095 if (config->pdbAltPath.empty()) {
2096 config->pdbAltPath = config->pdbPath;
2098 // It's important to make the path absolute and remove dots. This path
2099 // will eventually be written into the PE header, and certain Microsoft
2100 // tools won't work correctly if these assumptions are not held.
2101 sys::fs::make_absolute(config->pdbAltPath);
2102 sys::path::remove_dots(config->pdbAltPath);
2103 } else {
2104 // Don't do this earlier, so that Config->OutputFile is ready.
2105 parsePDBAltPath(config->pdbAltPath);
2109 // Set default image base if /base is not given.
2110 if (config->imageBase == uint64_t(-1))
2111 config->imageBase = getDefaultImageBase();
2113 ctx.symtab.addSynthetic(mangle("__ImageBase"), nullptr);
2114 if (config->machine == I386) {
2115 ctx.symtab.addAbsolute("___safe_se_handler_table", 0);
2116 ctx.symtab.addAbsolute("___safe_se_handler_count", 0);
2119 ctx.symtab.addAbsolute(mangle("__guard_fids_count"), 0);
2120 ctx.symtab.addAbsolute(mangle("__guard_fids_table"), 0);
2121 ctx.symtab.addAbsolute(mangle("__guard_flags"), 0);
2122 ctx.symtab.addAbsolute(mangle("__guard_iat_count"), 0);
2123 ctx.symtab.addAbsolute(mangle("__guard_iat_table"), 0);
2124 ctx.symtab.addAbsolute(mangle("__guard_longjmp_count"), 0);
2125 ctx.symtab.addAbsolute(mangle("__guard_longjmp_table"), 0);
2126 // Needed for MSVC 2017 15.5 CRT.
2127 ctx.symtab.addAbsolute(mangle("__enclave_config"), 0);
2128 // Needed for MSVC 2019 16.8 CRT.
2129 ctx.symtab.addAbsolute(mangle("__guard_eh_cont_count"), 0);
2130 ctx.symtab.addAbsolute(mangle("__guard_eh_cont_table"), 0);
2132 if (config->pseudoRelocs) {
2133 ctx.symtab.addAbsolute(mangle("__RUNTIME_PSEUDO_RELOC_LIST__"), 0);
2134 ctx.symtab.addAbsolute(mangle("__RUNTIME_PSEUDO_RELOC_LIST_END__"), 0);
2136 if (config->mingw) {
2137 ctx.symtab.addAbsolute(mangle("__CTOR_LIST__"), 0);
2138 ctx.symtab.addAbsolute(mangle("__DTOR_LIST__"), 0);
2141 // This code may add new undefined symbols to the link, which may enqueue more
2142 // symbol resolution tasks, so we need to continue executing tasks until we
2143 // converge.
2144 do {
2145 // Windows specific -- if entry point is not found,
2146 // search for its mangled names.
2147 if (config->entry)
2148 mangleMaybe(config->entry);
2150 // Windows specific -- Make sure we resolve all dllexported symbols.
2151 for (Export &e : config->exports) {
2152 if (!e.forwardTo.empty())
2153 continue;
2154 e.sym = addUndefined(e.name);
2155 if (!e.directives)
2156 e.symbolName = mangleMaybe(e.sym);
2159 // Add weak aliases. Weak aliases is a mechanism to give remaining
2160 // undefined symbols final chance to be resolved successfully.
2161 for (auto pair : config->alternateNames) {
2162 StringRef from = pair.first;
2163 StringRef to = pair.second;
2164 Symbol *sym = ctx.symtab.find(from);
2165 if (!sym)
2166 continue;
2167 if (auto *u = dyn_cast<Undefined>(sym))
2168 if (!u->weakAlias)
2169 u->weakAlias = ctx.symtab.addUndefined(to);
2172 // If any inputs are bitcode files, the LTO code generator may create
2173 // references to library functions that are not explicit in the bitcode
2174 // file's symbol table. If any of those library functions are defined in a
2175 // bitcode file in an archive member, we need to arrange to use LTO to
2176 // compile those archive members by adding them to the link beforehand.
2177 if (!ctx.bitcodeFileInstances.empty())
2178 for (auto *s : lto::LTO::getRuntimeLibcallSymbols())
2179 ctx.symtab.addLibcall(s);
2181 // Windows specific -- if __load_config_used can be resolved, resolve it.
2182 if (ctx.symtab.findUnderscore("_load_config_used"))
2183 addUndefined(mangle("_load_config_used"));
2184 } while (run());
2186 if (args.hasArg(OPT_include_optional)) {
2187 // Handle /includeoptional
2188 for (auto *arg : args.filtered(OPT_include_optional))
2189 if (isa_and_nonnull<LazyArchive>(ctx.symtab.find(arg->getValue())))
2190 addUndefined(arg->getValue());
2191 while (run());
2194 // Create wrapped symbols for -wrap option.
2195 std::vector<WrappedSymbol> wrapped = addWrappedSymbols(ctx, args);
2196 // Load more object files that might be needed for wrapped symbols.
2197 if (!wrapped.empty())
2198 while (run());
2200 if (config->autoImport || config->stdcallFixup) {
2201 // MinGW specific.
2202 // Load any further object files that might be needed for doing automatic
2203 // imports, and do stdcall fixups.
2205 // For cases with no automatically imported symbols, this iterates once
2206 // over the symbol table and doesn't do anything.
2208 // For the normal case with a few automatically imported symbols, this
2209 // should only need to be run once, since each new object file imported
2210 // is an import library and wouldn't add any new undefined references,
2211 // but there's nothing stopping the __imp_ symbols from coming from a
2212 // normal object file as well (although that won't be used for the
2213 // actual autoimport later on). If this pass adds new undefined references,
2214 // we won't iterate further to resolve them.
2216 // If stdcall fixups only are needed for loading import entries from
2217 // a DLL without import library, this also just needs running once.
2218 // If it ends up pulling in more object files from static libraries,
2219 // (and maybe doing more stdcall fixups along the way), this would need
2220 // to loop these two calls.
2221 ctx.symtab.loadMinGWSymbols();
2222 run();
2225 // At this point, we should not have any symbols that cannot be resolved.
2226 // If we are going to do codegen for link-time optimization, check for
2227 // unresolvable symbols first, so we don't spend time generating code that
2228 // will fail to link anyway.
2229 if (!ctx.bitcodeFileInstances.empty() && !config->forceUnresolved)
2230 ctx.symtab.reportUnresolvable();
2231 if (errorCount())
2232 return;
2234 config->hadExplicitExports = !config->exports.empty();
2235 if (config->mingw) {
2236 // In MinGW, all symbols are automatically exported if no symbols
2237 // are chosen to be exported.
2238 maybeExportMinGWSymbols(args);
2241 // Do LTO by compiling bitcode input files to a set of native COFF files then
2242 // link those files (unless -thinlto-index-only was given, in which case we
2243 // resolve symbols and write indices, but don't generate native code or link).
2244 ctx.symtab.compileBitcodeFiles();
2246 // If -thinlto-index-only is given, we should create only "index
2247 // files" and not object files. Index file creation is already done
2248 // in compileBitcodeFiles, so we are done if that's the case.
2249 if (config->thinLTOIndexOnly)
2250 return;
2252 // If we generated native object files from bitcode files, this resolves
2253 // references to the symbols we use from them.
2254 run();
2256 // Apply symbol renames for -wrap.
2257 if (!wrapped.empty())
2258 wrapSymbols(ctx, wrapped);
2260 // Resolve remaining undefined symbols and warn about imported locals.
2261 ctx.symtab.resolveRemainingUndefines();
2262 if (errorCount())
2263 return;
2265 if (config->mingw) {
2266 // Make sure the crtend.o object is the last object file. This object
2267 // file can contain terminating section chunks that need to be placed
2268 // last. GNU ld processes files and static libraries explicitly in the
2269 // order provided on the command line, while lld will pull in needed
2270 // files from static libraries only after the last object file on the
2271 // command line.
2272 for (auto i = ctx.objFileInstances.begin(), e = ctx.objFileInstances.end();
2273 i != e; i++) {
2274 ObjFile *file = *i;
2275 if (isCrtend(file->getName())) {
2276 ctx.objFileInstances.erase(i);
2277 ctx.objFileInstances.push_back(file);
2278 break;
2283 // Windows specific -- when we are creating a .dll file, we also
2284 // need to create a .lib file. In MinGW mode, we only do that when the
2285 // -implib option is given explicitly, for compatibility with GNU ld.
2286 if (!config->exports.empty() || config->dll) {
2287 fixupExports();
2288 if (!config->mingw || !config->implib.empty())
2289 createImportLibrary(/*asLib=*/false);
2290 assignExportOrdinals();
2293 // Handle /output-def (MinGW specific).
2294 if (auto *arg = args.getLastArg(OPT_output_def))
2295 writeDefFile(arg->getValue());
2297 // Set extra alignment for .comm symbols
2298 for (auto pair : config->alignComm) {
2299 StringRef name = pair.first;
2300 uint32_t alignment = pair.second;
2302 Symbol *sym = ctx.symtab.find(name);
2303 if (!sym) {
2304 warn("/aligncomm symbol " + name + " not found");
2305 continue;
2308 // If the symbol isn't common, it must have been replaced with a regular
2309 // symbol, which will carry its own alignment.
2310 auto *dc = dyn_cast<DefinedCommon>(sym);
2311 if (!dc)
2312 continue;
2314 CommonChunk *c = dc->getChunk();
2315 c->setAlignment(std::max(c->getAlignment(), alignment));
2318 // Windows specific -- Create an embedded or side-by-side manifest.
2319 // /manifestdependency: enables /manifest unless an explicit /manifest:no is
2320 // also passed.
2321 if (config->manifest == Configuration::Embed)
2322 addBuffer(createManifestRes(), false, false);
2323 else if (config->manifest == Configuration::SideBySide ||
2324 (config->manifest == Configuration::Default &&
2325 !config->manifestDependencies.empty()))
2326 createSideBySideManifest();
2328 // Handle /order. We want to do this at this moment because we
2329 // need a complete list of comdat sections to warn on nonexistent
2330 // functions.
2331 if (auto *arg = args.getLastArg(OPT_order)) {
2332 if (args.hasArg(OPT_call_graph_ordering_file))
2333 error("/order and /call-graph-order-file may not be used together");
2334 parseOrderFile(ctx, arg->getValue());
2335 config->callGraphProfileSort = false;
2338 // Handle /call-graph-ordering-file and /call-graph-profile-sort (default on).
2339 if (config->callGraphProfileSort) {
2340 if (auto *arg = args.getLastArg(OPT_call_graph_ordering_file)) {
2341 parseCallGraphFile(ctx, arg->getValue());
2343 readCallGraphsFromObjectFiles(ctx);
2346 // Handle /print-symbol-order.
2347 if (auto *arg = args.getLastArg(OPT_print_symbol_order))
2348 config->printSymbolOrder = arg->getValue();
2350 // Identify unreferenced COMDAT sections.
2351 if (config->doGC) {
2352 if (config->mingw) {
2353 // markLive doesn't traverse .eh_frame, but the personality function is
2354 // only reached that way. The proper solution would be to parse and
2355 // traverse the .eh_frame section, like the ELF linker does.
2356 // For now, just manually try to retain the known possible personality
2357 // functions. This doesn't bring in more object files, but only marks
2358 // functions that already have been included to be retained.
2359 for (const char *n : {"__gxx_personality_v0", "__gcc_personality_v0"}) {
2360 Defined *d = dyn_cast_or_null<Defined>(ctx.symtab.findUnderscore(n));
2361 if (d && !d->isGCRoot) {
2362 d->isGCRoot = true;
2363 config->gcroot.push_back(d);
2368 markLive(ctx);
2371 // Needs to happen after the last call to addFile().
2372 convertResources();
2374 // Identify identical COMDAT sections to merge them.
2375 if (config->doICF != ICFLevel::None) {
2376 findKeepUniqueSections(ctx);
2377 doICF(ctx, config->doICF);
2380 // Write the result.
2381 writeResult(ctx);
2383 // Stop early so we can print the results.
2384 rootTimer.stop();
2385 if (config->showTiming)
2386 ctx.rootTimer.print();
2389 } // namespace coff
2390 } // namespace lld