llvm-project
2663 строки · 92.5 Кб
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//===----------------------------------------------------------------------===//
8
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/CommonLinkerContext.h"
22#include "lld/Common/Driver.h"
23#include "lld/Common/Filesystem.h"
24#include "lld/Common/Timer.h"
25#include "lld/Common/Version.h"
26#include "llvm/ADT/IntrusiveRefCntPtr.h"
27#include "llvm/ADT/StringSwitch.h"
28#include "llvm/BinaryFormat/Magic.h"
29#include "llvm/Config/llvm-config.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/Option/Arg.h"
35#include "llvm/Option/ArgList.h"
36#include "llvm/Option/Option.h"
37#include "llvm/Support/BinaryStreamReader.h"
38#include "llvm/Support/CommandLine.h"
39#include "llvm/Support/Debug.h"
40#include "llvm/Support/LEB128.h"
41#include "llvm/Support/MathExtras.h"
42#include "llvm/Support/Parallel.h"
43#include "llvm/Support/Path.h"
44#include "llvm/Support/Process.h"
45#include "llvm/Support/TarWriter.h"
46#include "llvm/Support/TargetSelect.h"
47#include "llvm/Support/TimeProfiler.h"
48#include "llvm/Support/VirtualFileSystem.h"
49#include "llvm/Support/raw_ostream.h"
50#include "llvm/TargetParser/Triple.h"
51#include "llvm/ToolDrivers/llvm-lib/LibDriver.h"
52#include <algorithm>
53#include <future>
54#include <memory>
55#include <optional>
56#include <tuple>
57
58using namespace llvm;
59using namespace llvm::object;
60using namespace llvm::COFF;
61using namespace llvm::sys;
62
63namespace lld::coff {
64
65bool link(ArrayRef<const char *> args, llvm::raw_ostream &stdoutOS,
66llvm::raw_ostream &stderrOS, bool exitEarly, bool disableOutput) {
67// This driver-specific context will be freed later by unsafeLldMain().
68auto *ctx = new COFFLinkerContext;
69
70ctx->e.initialize(stdoutOS, stderrOS, exitEarly, disableOutput);
71ctx->e.logName = args::getFilenameWithoutExe(args[0]);
72ctx->e.errorLimitExceededMsg = "too many errors emitted, stopping now"
73" (use /errorlimit:0 to see all errors)";
74
75ctx->driver.linkerMain(args);
76
77return errorCount() == 0;
78}
79
80// Parse options of the form "old;new".
81static std::pair<StringRef, StringRef> getOldNewOptions(opt::InputArgList &args,
82unsigned id) {
83auto *arg = args.getLastArg(id);
84if (!arg)
85return {"", ""};
86
87StringRef s = arg->getValue();
88std::pair<StringRef, StringRef> ret = s.split(';');
89if (ret.second.empty())
90error(arg->getSpelling() + " expects 'old;new' format, but got " + s);
91return ret;
92}
93
94// Parse options of the form "old;new[;extra]".
95static std::tuple<StringRef, StringRef, StringRef>
96getOldNewOptionsExtra(opt::InputArgList &args, unsigned id) {
97auto [oldDir, second] = getOldNewOptions(args, id);
98auto [newDir, extraDir] = second.split(';');
99return {oldDir, newDir, extraDir};
100}
101
102// Drop directory components and replace extension with
103// ".exe", ".dll" or ".sys".
104static std::string getOutputPath(StringRef path, bool isDll, bool isDriver) {
105StringRef ext = ".exe";
106if (isDll)
107ext = ".dll";
108else if (isDriver)
109ext = ".sys";
110
111return (sys::path::stem(path) + ext).str();
112}
113
114// Returns true if S matches /crtend.?\.o$/.
115static bool isCrtend(StringRef s) {
116if (!s.ends_with(".o"))
117return false;
118s = s.drop_back(2);
119if (s.ends_with("crtend"))
120return true;
121return !s.empty() && s.drop_back().ends_with("crtend");
122}
123
124// ErrorOr is not default constructible, so it cannot be used as the type
125// parameter of a future.
126// FIXME: We could open the file in createFutureForFile and avoid needing to
127// return an error here, but for the moment that would cost us a file descriptor
128// (a limited resource on Windows) for the duration that the future is pending.
129using MBErrPair = std::pair<std::unique_ptr<MemoryBuffer>, std::error_code>;
130
131// Create a std::future that opens and maps a file using the best strategy for
132// the host platform.
133static std::future<MBErrPair> createFutureForFile(std::string path) {
134#if _WIN64
135// On Windows, file I/O is relatively slow so it is best to do this
136// asynchronously. But 32-bit has issues with potentially launching tons
137// of threads
138auto strategy = std::launch::async;
139#else
140auto strategy = std::launch::deferred;
141#endif
142return std::async(strategy, [=]() {
143auto mbOrErr = MemoryBuffer::getFile(path, /*IsText=*/false,
144/*RequiresNullTerminator=*/false);
145if (!mbOrErr)
146return MBErrPair{nullptr, mbOrErr.getError()};
147return MBErrPair{std::move(*mbOrErr), std::error_code()};
148});
149}
150
151// Symbol names are mangled by prepending "_" on x86.
152StringRef LinkerDriver::mangle(StringRef sym) {
153assert(ctx.config.machine != IMAGE_FILE_MACHINE_UNKNOWN);
154if (ctx.config.machine == I386)
155return saver().save("_" + sym);
156return sym;
157}
158
159llvm::Triple::ArchType LinkerDriver::getArch() {
160return getMachineArchType(ctx.config.machine);
161}
162
163bool LinkerDriver::findUnderscoreMangle(StringRef sym) {
164Symbol *s = ctx.symtab.findMangle(mangle(sym));
165return s && !isa<Undefined>(s);
166}
167
168MemoryBufferRef LinkerDriver::takeBuffer(std::unique_ptr<MemoryBuffer> mb) {
169MemoryBufferRef mbref = *mb;
170make<std::unique_ptr<MemoryBuffer>>(std::move(mb)); // take ownership
171
172if (ctx.driver.tar)
173ctx.driver.tar->append(relativeToRoot(mbref.getBufferIdentifier()),
174mbref.getBuffer());
175return mbref;
176}
177
178void LinkerDriver::addBuffer(std::unique_ptr<MemoryBuffer> mb,
179bool wholeArchive, bool lazy) {
180StringRef filename = mb->getBufferIdentifier();
181
182MemoryBufferRef mbref = takeBuffer(std::move(mb));
183filePaths.push_back(filename);
184
185// File type is detected by contents, not by file extension.
186switch (identify_magic(mbref.getBuffer())) {
187case file_magic::windows_resource:
188resources.push_back(mbref);
189break;
190case file_magic::archive:
191if (wholeArchive) {
192std::unique_ptr<Archive> file =
193CHECK(Archive::create(mbref), filename + ": failed to parse archive");
194Archive *archive = file.get();
195make<std::unique_ptr<Archive>>(std::move(file)); // take ownership
196
197int memberIndex = 0;
198for (MemoryBufferRef m : getArchiveMembers(archive))
199addArchiveBuffer(m, "<whole-archive>", filename, memberIndex++);
200return;
201}
202ctx.symtab.addFile(make<ArchiveFile>(ctx, mbref));
203break;
204case file_magic::bitcode:
205ctx.symtab.addFile(make<BitcodeFile>(ctx, mbref, "", 0, lazy));
206break;
207case file_magic::coff_object:
208case file_magic::coff_import_library:
209ctx.symtab.addFile(make<ObjFile>(ctx, mbref, lazy));
210break;
211case file_magic::pdb:
212ctx.symtab.addFile(make<PDBInputFile>(ctx, mbref));
213break;
214case file_magic::coff_cl_gl_object:
215error(filename + ": is not a native COFF file. Recompile without /GL");
216break;
217case file_magic::pecoff_executable:
218if (ctx.config.mingw) {
219ctx.symtab.addFile(make<DLLFile>(ctx, mbref));
220break;
221}
222if (filename.ends_with_insensitive(".dll")) {
223error(filename + ": bad file type. Did you specify a DLL instead of an "
224"import library?");
225break;
226}
227[[fallthrough]];
228default:
229error(mbref.getBufferIdentifier() + ": unknown file type");
230break;
231}
232}
233
234void LinkerDriver::enqueuePath(StringRef path, bool wholeArchive, bool lazy) {
235auto future = std::make_shared<std::future<MBErrPair>>(
236createFutureForFile(std::string(path)));
237std::string pathStr = std::string(path);
238enqueueTask([=]() {
239llvm::TimeTraceScope timeScope("File: ", path);
240auto [mb, ec] = future->get();
241if (ec) {
242// Retry reading the file (synchronously) now that we may have added
243// winsysroot search paths from SymbolTable::addFile().
244// Retrying synchronously is important for keeping the order of inputs
245// consistent.
246// This makes it so that if the user passes something in the winsysroot
247// before something we can find with an architecture, we won't find the
248// winsysroot file.
249if (std::optional<StringRef> retryPath = findFileIfNew(pathStr)) {
250auto retryMb = MemoryBuffer::getFile(*retryPath, /*IsText=*/false,
251/*RequiresNullTerminator=*/false);
252ec = retryMb.getError();
253if (!ec)
254mb = std::move(*retryMb);
255} else {
256// We've already handled this file.
257return;
258}
259}
260if (ec) {
261std::string msg = "could not open '" + pathStr + "': " + ec.message();
262// Check if the filename is a typo for an option flag. OptTable thinks
263// that all args that are not known options and that start with / are
264// filenames, but e.g. `/nodefaultlibs` is more likely a typo for
265// the option `/nodefaultlib` than a reference to a file in the root
266// directory.
267std::string nearest;
268if (ctx.optTable.findNearest(pathStr, nearest) > 1)
269error(msg);
270else
271error(msg + "; did you mean '" + nearest + "'");
272} else
273ctx.driver.addBuffer(std::move(mb), wholeArchive, lazy);
274});
275}
276
277void LinkerDriver::addArchiveBuffer(MemoryBufferRef mb, StringRef symName,
278StringRef parentName,
279uint64_t offsetInArchive) {
280file_magic magic = identify_magic(mb.getBuffer());
281if (magic == file_magic::coff_import_library) {
282InputFile *imp = make<ImportFile>(ctx, mb);
283imp->parentName = parentName;
284ctx.symtab.addFile(imp);
285return;
286}
287
288InputFile *obj;
289if (magic == file_magic::coff_object) {
290obj = make<ObjFile>(ctx, mb);
291} else if (magic == file_magic::bitcode) {
292obj =
293make<BitcodeFile>(ctx, mb, parentName, offsetInArchive, /*lazy=*/false);
294} else if (magic == file_magic::coff_cl_gl_object) {
295error(mb.getBufferIdentifier() +
296": is not a native COFF file. Recompile without /GL?");
297return;
298} else {
299error("unknown file type: " + mb.getBufferIdentifier());
300return;
301}
302
303obj->parentName = parentName;
304ctx.symtab.addFile(obj);
305log("Loaded " + toString(obj) + " for " + symName);
306}
307
308void LinkerDriver::enqueueArchiveMember(const Archive::Child &c,
309const Archive::Symbol &sym,
310StringRef parentName) {
311
312auto reportBufferError = [=](Error &&e, StringRef childName) {
313fatal("could not get the buffer for the member defining symbol " +
314toCOFFString(ctx, sym) + ": " + parentName + "(" + childName +
315"): " + toString(std::move(e)));
316};
317
318if (!c.getParent()->isThin()) {
319uint64_t offsetInArchive = c.getChildOffset();
320Expected<MemoryBufferRef> mbOrErr = c.getMemoryBufferRef();
321if (!mbOrErr)
322reportBufferError(mbOrErr.takeError(), check(c.getFullName()));
323MemoryBufferRef mb = mbOrErr.get();
324enqueueTask([=]() {
325llvm::TimeTraceScope timeScope("Archive: ", mb.getBufferIdentifier());
326ctx.driver.addArchiveBuffer(mb, toCOFFString(ctx, sym), parentName,
327offsetInArchive);
328});
329return;
330}
331
332std::string childName =
333CHECK(c.getFullName(),
334"could not get the filename for the member defining symbol " +
335toCOFFString(ctx, sym));
336auto future =
337std::make_shared<std::future<MBErrPair>>(createFutureForFile(childName));
338enqueueTask([=]() {
339auto mbOrErr = future->get();
340if (mbOrErr.second)
341reportBufferError(errorCodeToError(mbOrErr.second), childName);
342llvm::TimeTraceScope timeScope("Archive: ",
343mbOrErr.first->getBufferIdentifier());
344// Pass empty string as archive name so that the original filename is
345// used as the buffer identifier.
346ctx.driver.addArchiveBuffer(takeBuffer(std::move(mbOrErr.first)),
347toCOFFString(ctx, sym), "",
348/*OffsetInArchive=*/0);
349});
350}
351
352bool LinkerDriver::isDecorated(StringRef sym) {
353return sym.starts_with("@") || sym.contains("@@") || sym.starts_with("?") ||
354(!ctx.config.mingw && sym.contains('@'));
355}
356
357// Parses .drectve section contents and returns a list of files
358// specified by /defaultlib.
359void LinkerDriver::parseDirectives(InputFile *file) {
360StringRef s = file->getDirectives();
361if (s.empty())
362return;
363
364log("Directives: " + toString(file) + ": " + s);
365
366ArgParser parser(ctx);
367// .drectve is always tokenized using Windows shell rules.
368// /EXPORT: option can appear too many times, processing in fastpath.
369ParsedDirectives directives = parser.parseDirectives(s);
370
371for (StringRef e : directives.exports) {
372// If a common header file contains dllexported function
373// declarations, many object files may end up with having the
374// same /EXPORT options. In order to save cost of parsing them,
375// we dedup them first.
376if (!directivesExports.insert(e).second)
377continue;
378
379Export exp = parseExport(e);
380if (ctx.config.machine == I386 && ctx.config.mingw) {
381if (!isDecorated(exp.name))
382exp.name = saver().save("_" + exp.name);
383if (!exp.extName.empty() && !isDecorated(exp.extName))
384exp.extName = saver().save("_" + exp.extName);
385}
386exp.source = ExportSource::Directives;
387ctx.config.exports.push_back(exp);
388}
389
390// Handle /include: in bulk.
391for (StringRef inc : directives.includes)
392addUndefined(inc);
393
394// Handle /exclude-symbols: in bulk.
395for (StringRef e : directives.excludes) {
396SmallVector<StringRef, 2> vec;
397e.split(vec, ',');
398for (StringRef sym : vec)
399excludedSymbols.insert(mangle(sym));
400}
401
402// https://docs.microsoft.com/en-us/cpp/preprocessor/comment-c-cpp?view=msvc-160
403for (auto *arg : directives.args) {
404switch (arg->getOption().getID()) {
405case OPT_aligncomm:
406parseAligncomm(arg->getValue());
407break;
408case OPT_alternatename:
409parseAlternateName(arg->getValue());
410break;
411case OPT_defaultlib:
412if (std::optional<StringRef> path = findLibIfNew(arg->getValue()))
413enqueuePath(*path, false, false);
414break;
415case OPT_entry:
416if (!arg->getValue()[0])
417fatal("missing entry point symbol name");
418ctx.config.entry = addUndefined(mangle(arg->getValue()));
419break;
420case OPT_failifmismatch:
421checkFailIfMismatch(arg->getValue(), file);
422break;
423case OPT_incl:
424addUndefined(arg->getValue());
425break;
426case OPT_manifestdependency:
427ctx.config.manifestDependencies.insert(arg->getValue());
428break;
429case OPT_merge:
430parseMerge(arg->getValue());
431break;
432case OPT_nodefaultlib:
433ctx.config.noDefaultLibs.insert(findLib(arg->getValue()).lower());
434break;
435case OPT_release:
436ctx.config.writeCheckSum = true;
437break;
438case OPT_section:
439parseSection(arg->getValue());
440break;
441case OPT_stack:
442parseNumbers(arg->getValue(), &ctx.config.stackReserve,
443&ctx.config.stackCommit);
444break;
445case OPT_subsystem: {
446bool gotVersion = false;
447parseSubsystem(arg->getValue(), &ctx.config.subsystem,
448&ctx.config.majorSubsystemVersion,
449&ctx.config.minorSubsystemVersion, &gotVersion);
450if (gotVersion) {
451ctx.config.majorOSVersion = ctx.config.majorSubsystemVersion;
452ctx.config.minorOSVersion = ctx.config.minorSubsystemVersion;
453}
454break;
455}
456// Only add flags here that link.exe accepts in
457// `#pragma comment(linker, "/flag")`-generated sections.
458case OPT_editandcontinue:
459case OPT_guardsym:
460case OPT_throwingnew:
461case OPT_inferasanlibs:
462case OPT_inferasanlibs_no:
463break;
464default:
465error(arg->getSpelling() + " is not allowed in .drectve (" +
466toString(file) + ")");
467}
468}
469}
470
471// Find file from search paths. You can omit ".obj", this function takes
472// care of that. Note that the returned path is not guaranteed to exist.
473StringRef LinkerDriver::findFile(StringRef filename) {
474auto getFilename = [this](StringRef filename) -> StringRef {
475if (ctx.config.vfs)
476if (auto statOrErr = ctx.config.vfs->status(filename))
477return saver().save(statOrErr->getName());
478return filename;
479};
480
481if (sys::path::is_absolute(filename))
482return getFilename(filename);
483bool hasExt = filename.contains('.');
484for (StringRef dir : searchPaths) {
485SmallString<128> path = dir;
486sys::path::append(path, filename);
487path = SmallString<128>{getFilename(path.str())};
488if (sys::fs::exists(path.str()))
489return saver().save(path.str());
490if (!hasExt) {
491path.append(".obj");
492path = SmallString<128>{getFilename(path.str())};
493if (sys::fs::exists(path.str()))
494return saver().save(path.str());
495}
496}
497return filename;
498}
499
500static std::optional<sys::fs::UniqueID> getUniqueID(StringRef path) {
501sys::fs::UniqueID ret;
502if (sys::fs::getUniqueID(path, ret))
503return std::nullopt;
504return ret;
505}
506
507// Resolves a file path. This never returns the same path
508// (in that case, it returns std::nullopt).
509std::optional<StringRef> LinkerDriver::findFileIfNew(StringRef filename) {
510StringRef path = findFile(filename);
511
512if (std::optional<sys::fs::UniqueID> id = getUniqueID(path)) {
513bool seen = !visitedFiles.insert(*id).second;
514if (seen)
515return std::nullopt;
516}
517
518if (path.ends_with_insensitive(".lib"))
519visitedLibs.insert(std::string(sys::path::filename(path).lower()));
520return path;
521}
522
523// MinGW specific. If an embedded directive specified to link to
524// foo.lib, but it isn't found, try libfoo.a instead.
525StringRef LinkerDriver::findLibMinGW(StringRef filename) {
526if (filename.contains('/') || filename.contains('\\'))
527return filename;
528
529SmallString<128> s = filename;
530sys::path::replace_extension(s, ".a");
531StringRef libName = saver().save("lib" + s.str());
532return findFile(libName);
533}
534
535// Find library file from search path.
536StringRef LinkerDriver::findLib(StringRef filename) {
537// Add ".lib" to Filename if that has no file extension.
538bool hasExt = filename.contains('.');
539if (!hasExt)
540filename = saver().save(filename + ".lib");
541StringRef ret = findFile(filename);
542// For MinGW, if the find above didn't turn up anything, try
543// looking for a MinGW formatted library name.
544if (ctx.config.mingw && ret == filename)
545return findLibMinGW(filename);
546return ret;
547}
548
549// Resolves a library path. /nodefaultlib options are taken into
550// consideration. This never returns the same path (in that case,
551// it returns std::nullopt).
552std::optional<StringRef> LinkerDriver::findLibIfNew(StringRef filename) {
553if (ctx.config.noDefaultLibAll)
554return std::nullopt;
555if (!visitedLibs.insert(filename.lower()).second)
556return std::nullopt;
557
558StringRef path = findLib(filename);
559if (ctx.config.noDefaultLibs.count(path.lower()))
560return std::nullopt;
561
562if (std::optional<sys::fs::UniqueID> id = getUniqueID(path))
563if (!visitedFiles.insert(*id).second)
564return std::nullopt;
565return path;
566}
567
568void LinkerDriver::detectWinSysRoot(const opt::InputArgList &Args) {
569IntrusiveRefCntPtr<vfs::FileSystem> VFS = vfs::getRealFileSystem();
570
571// Check the command line first, that's the user explicitly telling us what to
572// use. Check the environment next, in case we're being invoked from a VS
573// command prompt. Failing that, just try to find the newest Visual Studio
574// version we can and use its default VC toolchain.
575std::optional<StringRef> VCToolsDir, VCToolsVersion, WinSysRoot;
576if (auto *A = Args.getLastArg(OPT_vctoolsdir))
577VCToolsDir = A->getValue();
578if (auto *A = Args.getLastArg(OPT_vctoolsversion))
579VCToolsVersion = A->getValue();
580if (auto *A = Args.getLastArg(OPT_winsysroot))
581WinSysRoot = A->getValue();
582if (!findVCToolChainViaCommandLine(*VFS, VCToolsDir, VCToolsVersion,
583WinSysRoot, vcToolChainPath, vsLayout) &&
584(Args.hasArg(OPT_lldignoreenv) ||
585!findVCToolChainViaEnvironment(*VFS, vcToolChainPath, vsLayout)) &&
586!findVCToolChainViaSetupConfig(*VFS, {}, vcToolChainPath, vsLayout) &&
587!findVCToolChainViaRegistry(vcToolChainPath, vsLayout))
588return;
589
590// If the VC environment hasn't been configured (perhaps because the user did
591// not run vcvarsall), try to build a consistent link environment. If the
592// environment variable is set however, assume the user knows what they're
593// doing. If the user passes /vctoolsdir or /winsdkdir, trust that over env
594// vars.
595if (const auto *A = Args.getLastArg(OPT_diasdkdir, OPT_winsysroot)) {
596diaPath = A->getValue();
597if (A->getOption().getID() == OPT_winsysroot)
598path::append(diaPath, "DIA SDK");
599}
600useWinSysRootLibPath = Args.hasArg(OPT_lldignoreenv) ||
601!Process::GetEnv("LIB") ||
602Args.getLastArg(OPT_vctoolsdir, OPT_winsysroot);
603if (Args.hasArg(OPT_lldignoreenv) || !Process::GetEnv("LIB") ||
604Args.getLastArg(OPT_winsdkdir, OPT_winsysroot)) {
605std::optional<StringRef> WinSdkDir, WinSdkVersion;
606if (auto *A = Args.getLastArg(OPT_winsdkdir))
607WinSdkDir = A->getValue();
608if (auto *A = Args.getLastArg(OPT_winsdkversion))
609WinSdkVersion = A->getValue();
610
611if (useUniversalCRT(vsLayout, vcToolChainPath, getArch(), *VFS)) {
612std::string UniversalCRTSdkPath;
613std::string UCRTVersion;
614if (getUniversalCRTSdkDir(*VFS, WinSdkDir, WinSdkVersion, WinSysRoot,
615UniversalCRTSdkPath, UCRTVersion)) {
616universalCRTLibPath = UniversalCRTSdkPath;
617path::append(universalCRTLibPath, "Lib", UCRTVersion, "ucrt");
618}
619}
620
621std::string sdkPath;
622std::string windowsSDKIncludeVersion;
623std::string windowsSDKLibVersion;
624if (getWindowsSDKDir(*VFS, WinSdkDir, WinSdkVersion, WinSysRoot, sdkPath,
625sdkMajor, windowsSDKIncludeVersion,
626windowsSDKLibVersion)) {
627windowsSdkLibPath = sdkPath;
628path::append(windowsSdkLibPath, "Lib");
629if (sdkMajor >= 8)
630path::append(windowsSdkLibPath, windowsSDKLibVersion, "um");
631}
632}
633}
634
635void LinkerDriver::addClangLibSearchPaths(const std::string &argv0) {
636std::string lldBinary = sys::fs::getMainExecutable(argv0.c_str(), nullptr);
637SmallString<128> binDir(lldBinary);
638sys::path::remove_filename(binDir); // remove lld-link.exe
639StringRef rootDir = sys::path::parent_path(binDir); // remove 'bin'
640
641SmallString<128> libDir(rootDir);
642sys::path::append(libDir, "lib");
643
644// Add the resource dir library path
645SmallString<128> runtimeLibDir(rootDir);
646sys::path::append(runtimeLibDir, "lib", "clang",
647std::to_string(LLVM_VERSION_MAJOR), "lib");
648// Resource dir + osname, which is hardcoded to windows since we are in the
649// COFF driver.
650SmallString<128> runtimeLibDirWithOS(runtimeLibDir);
651sys::path::append(runtimeLibDirWithOS, "windows");
652
653searchPaths.push_back(saver().save(runtimeLibDirWithOS.str()));
654searchPaths.push_back(saver().save(runtimeLibDir.str()));
655searchPaths.push_back(saver().save(libDir.str()));
656}
657
658void LinkerDriver::addWinSysRootLibSearchPaths() {
659if (!diaPath.empty()) {
660// The DIA SDK always uses the legacy vc arch, even in new MSVC versions.
661path::append(diaPath, "lib", archToLegacyVCArch(getArch()));
662searchPaths.push_back(saver().save(diaPath.str()));
663}
664if (useWinSysRootLibPath) {
665searchPaths.push_back(saver().save(getSubDirectoryPath(
666SubDirectoryType::Lib, vsLayout, vcToolChainPath, getArch())));
667searchPaths.push_back(saver().save(
668getSubDirectoryPath(SubDirectoryType::Lib, vsLayout, vcToolChainPath,
669getArch(), "atlmfc")));
670}
671if (!universalCRTLibPath.empty()) {
672StringRef ArchName = archToWindowsSDKArch(getArch());
673if (!ArchName.empty()) {
674path::append(universalCRTLibPath, ArchName);
675searchPaths.push_back(saver().save(universalCRTLibPath.str()));
676}
677}
678if (!windowsSdkLibPath.empty()) {
679std::string path;
680if (appendArchToWindowsSDKLibPath(sdkMajor, windowsSdkLibPath, getArch(),
681path))
682searchPaths.push_back(saver().save(path));
683}
684}
685
686// Parses LIB environment which contains a list of search paths.
687void LinkerDriver::addLibSearchPaths() {
688std::optional<std::string> envOpt = Process::GetEnv("LIB");
689if (!envOpt)
690return;
691StringRef env = saver().save(*envOpt);
692while (!env.empty()) {
693StringRef path;
694std::tie(path, env) = env.split(';');
695searchPaths.push_back(path);
696}
697}
698
699Symbol *LinkerDriver::addUndefined(StringRef name) {
700Symbol *b = ctx.symtab.addUndefined(name);
701if (!b->isGCRoot) {
702b->isGCRoot = true;
703ctx.config.gcroot.push_back(b);
704}
705return b;
706}
707
708StringRef LinkerDriver::mangleMaybe(Symbol *s) {
709// If the plain symbol name has already been resolved, do nothing.
710Undefined *unmangled = dyn_cast<Undefined>(s);
711if (!unmangled)
712return "";
713
714// Otherwise, see if a similar, mangled symbol exists in the symbol table.
715Symbol *mangled = ctx.symtab.findMangle(unmangled->getName());
716if (!mangled)
717return "";
718
719// If we find a similar mangled symbol, make this an alias to it and return
720// its name.
721log(unmangled->getName() + " aliased to " + mangled->getName());
722unmangled->weakAlias = ctx.symtab.addUndefined(mangled->getName());
723return mangled->getName();
724}
725
726// Windows specific -- find default entry point name.
727//
728// There are four different entry point functions for Windows executables,
729// each of which corresponds to a user-defined "main" function. This function
730// infers an entry point from a user-defined "main" function.
731StringRef LinkerDriver::findDefaultEntry() {
732assert(ctx.config.subsystem != IMAGE_SUBSYSTEM_UNKNOWN &&
733"must handle /subsystem before calling this");
734
735if (ctx.config.mingw)
736return mangle(ctx.config.subsystem == IMAGE_SUBSYSTEM_WINDOWS_GUI
737? "WinMainCRTStartup"
738: "mainCRTStartup");
739
740if (ctx.config.subsystem == IMAGE_SUBSYSTEM_WINDOWS_GUI) {
741if (findUnderscoreMangle("wWinMain")) {
742if (!findUnderscoreMangle("WinMain"))
743return mangle("wWinMainCRTStartup");
744warn("found both wWinMain and WinMain; using latter");
745}
746return mangle("WinMainCRTStartup");
747}
748if (findUnderscoreMangle("wmain")) {
749if (!findUnderscoreMangle("main"))
750return mangle("wmainCRTStartup");
751warn("found both wmain and main; using latter");
752}
753return mangle("mainCRTStartup");
754}
755
756WindowsSubsystem LinkerDriver::inferSubsystem() {
757if (ctx.config.dll)
758return IMAGE_SUBSYSTEM_WINDOWS_GUI;
759if (ctx.config.mingw)
760return IMAGE_SUBSYSTEM_WINDOWS_CUI;
761// Note that link.exe infers the subsystem from the presence of these
762// functions even if /entry: or /nodefaultlib are passed which causes them
763// to not be called.
764bool haveMain = findUnderscoreMangle("main");
765bool haveWMain = findUnderscoreMangle("wmain");
766bool haveWinMain = findUnderscoreMangle("WinMain");
767bool haveWWinMain = findUnderscoreMangle("wWinMain");
768if (haveMain || haveWMain) {
769if (haveWinMain || haveWWinMain) {
770warn(std::string("found ") + (haveMain ? "main" : "wmain") + " and " +
771(haveWinMain ? "WinMain" : "wWinMain") +
772"; defaulting to /subsystem:console");
773}
774return IMAGE_SUBSYSTEM_WINDOWS_CUI;
775}
776if (haveWinMain || haveWWinMain)
777return IMAGE_SUBSYSTEM_WINDOWS_GUI;
778return IMAGE_SUBSYSTEM_UNKNOWN;
779}
780
781uint64_t LinkerDriver::getDefaultImageBase() {
782if (ctx.config.is64())
783return ctx.config.dll ? 0x180000000 : 0x140000000;
784return ctx.config.dll ? 0x10000000 : 0x400000;
785}
786
787static std::string rewritePath(StringRef s) {
788if (fs::exists(s))
789return relativeToRoot(s);
790return std::string(s);
791}
792
793// Reconstructs command line arguments so that so that you can re-run
794// the same command with the same inputs. This is for --reproduce.
795static std::string createResponseFile(const opt::InputArgList &args,
796ArrayRef<StringRef> filePaths,
797ArrayRef<StringRef> searchPaths) {
798SmallString<0> data;
799raw_svector_ostream os(data);
800
801for (auto *arg : args) {
802switch (arg->getOption().getID()) {
803case OPT_linkrepro:
804case OPT_reproduce:
805case OPT_INPUT:
806case OPT_defaultlib:
807case OPT_libpath:
808case OPT_winsysroot:
809break;
810case OPT_call_graph_ordering_file:
811case OPT_deffile:
812case OPT_manifestinput:
813case OPT_natvis:
814os << arg->getSpelling() << quote(rewritePath(arg->getValue())) << '\n';
815break;
816case OPT_order: {
817StringRef orderFile = arg->getValue();
818orderFile.consume_front("@");
819os << arg->getSpelling() << '@' << quote(rewritePath(orderFile)) << '\n';
820break;
821}
822case OPT_pdbstream: {
823const std::pair<StringRef, StringRef> nameFile =
824StringRef(arg->getValue()).split("=");
825os << arg->getSpelling() << nameFile.first << '='
826<< quote(rewritePath(nameFile.second)) << '\n';
827break;
828}
829case OPT_implib:
830case OPT_manifestfile:
831case OPT_pdb:
832case OPT_pdbstripped:
833case OPT_out:
834os << arg->getSpelling() << sys::path::filename(arg->getValue()) << "\n";
835break;
836default:
837os << toString(*arg) << "\n";
838}
839}
840
841for (StringRef path : searchPaths) {
842std::string relPath = relativeToRoot(path);
843os << "/libpath:" << quote(relPath) << "\n";
844}
845
846for (StringRef path : filePaths)
847os << quote(relativeToRoot(path)) << "\n";
848
849return std::string(data);
850}
851
852static unsigned parseDebugTypes(const opt::InputArgList &args) {
853unsigned debugTypes = static_cast<unsigned>(DebugType::None);
854
855if (auto *a = args.getLastArg(OPT_debugtype)) {
856SmallVector<StringRef, 3> types;
857StringRef(a->getValue())
858.split(types, ',', /*MaxSplit=*/-1, /*KeepEmpty=*/false);
859
860for (StringRef type : types) {
861unsigned v = StringSwitch<unsigned>(type.lower())
862.Case("cv", static_cast<unsigned>(DebugType::CV))
863.Case("pdata", static_cast<unsigned>(DebugType::PData))
864.Case("fixup", static_cast<unsigned>(DebugType::Fixup))
865.Default(0);
866if (v == 0) {
867warn("/debugtype: unknown option '" + type + "'");
868continue;
869}
870debugTypes |= v;
871}
872return debugTypes;
873}
874
875// Default debug types
876debugTypes = static_cast<unsigned>(DebugType::CV);
877if (args.hasArg(OPT_driver))
878debugTypes |= static_cast<unsigned>(DebugType::PData);
879if (args.hasArg(OPT_profile))
880debugTypes |= static_cast<unsigned>(DebugType::Fixup);
881
882return debugTypes;
883}
884
885std::string LinkerDriver::getMapFile(const opt::InputArgList &args,
886opt::OptSpecifier os,
887opt::OptSpecifier osFile) {
888auto *arg = args.getLastArg(os, osFile);
889if (!arg)
890return "";
891if (arg->getOption().getID() == osFile.getID())
892return arg->getValue();
893
894assert(arg->getOption().getID() == os.getID());
895StringRef outFile = ctx.config.outputFile;
896return (outFile.substr(0, outFile.rfind('.')) + ".map").str();
897}
898
899std::string LinkerDriver::getImplibPath() {
900if (!ctx.config.implib.empty())
901return std::string(ctx.config.implib);
902SmallString<128> out = StringRef(ctx.config.outputFile);
903sys::path::replace_extension(out, ".lib");
904return std::string(out);
905}
906
907// The import name is calculated as follows:
908//
909// | LIBRARY w/ ext | LIBRARY w/o ext | no LIBRARY
910// -----+----------------+---------------------+------------------
911// LINK | {value} | {value}.{.dll/.exe} | {output name}
912// LIB | {value} | {value}.dll | {output name}.dll
913//
914std::string LinkerDriver::getImportName(bool asLib) {
915SmallString<128> out;
916
917if (ctx.config.importName.empty()) {
918out.assign(sys::path::filename(ctx.config.outputFile));
919if (asLib)
920sys::path::replace_extension(out, ".dll");
921} else {
922out.assign(ctx.config.importName);
923if (!sys::path::has_extension(out))
924sys::path::replace_extension(out,
925(ctx.config.dll || asLib) ? ".dll" : ".exe");
926}
927
928return std::string(out);
929}
930
931void LinkerDriver::createImportLibrary(bool asLib) {
932llvm::TimeTraceScope timeScope("Create import library");
933std::vector<COFFShortExport> exports;
934for (Export &e1 : ctx.config.exports) {
935COFFShortExport e2;
936e2.Name = std::string(e1.name);
937e2.SymbolName = std::string(e1.symbolName);
938e2.ExtName = std::string(e1.extName);
939e2.ExportAs = std::string(e1.exportAs);
940e2.ImportName = std::string(e1.importName);
941e2.Ordinal = e1.ordinal;
942e2.Noname = e1.noname;
943e2.Data = e1.data;
944e2.Private = e1.isPrivate;
945e2.Constant = e1.constant;
946exports.push_back(e2);
947}
948
949std::string libName = getImportName(asLib);
950std::string path = getImplibPath();
951
952if (!ctx.config.incremental) {
953checkError(writeImportLibrary(libName, path, exports, ctx.config.machine,
954ctx.config.mingw));
955return;
956}
957
958// If the import library already exists, replace it only if the contents
959// have changed.
960ErrorOr<std::unique_ptr<MemoryBuffer>> oldBuf = MemoryBuffer::getFile(
961path, /*IsText=*/false, /*RequiresNullTerminator=*/false);
962if (!oldBuf) {
963checkError(writeImportLibrary(libName, path, exports, ctx.config.machine,
964ctx.config.mingw));
965return;
966}
967
968SmallString<128> tmpName;
969if (std::error_code ec =
970sys::fs::createUniqueFile(path + ".tmp-%%%%%%%%.lib", tmpName))
971fatal("cannot create temporary file for import library " + path + ": " +
972ec.message());
973
974if (Error e = writeImportLibrary(libName, tmpName, exports,
975ctx.config.machine, ctx.config.mingw)) {
976checkError(std::move(e));
977return;
978}
979
980std::unique_ptr<MemoryBuffer> newBuf = check(MemoryBuffer::getFile(
981tmpName, /*IsText=*/false, /*RequiresNullTerminator=*/false));
982if ((*oldBuf)->getBuffer() != newBuf->getBuffer()) {
983oldBuf->reset();
984checkError(errorCodeToError(sys::fs::rename(tmpName, path)));
985} else {
986sys::fs::remove(tmpName);
987}
988}
989
990void LinkerDriver::parseModuleDefs(StringRef path) {
991llvm::TimeTraceScope timeScope("Parse def file");
992std::unique_ptr<MemoryBuffer> mb =
993CHECK(MemoryBuffer::getFile(path, /*IsText=*/false,
994/*RequiresNullTerminator=*/false,
995/*IsVolatile=*/true),
996"could not open " + path);
997COFFModuleDefinition m = check(parseCOFFModuleDefinition(
998mb->getMemBufferRef(), ctx.config.machine, ctx.config.mingw));
999
1000// Include in /reproduce: output if applicable.
1001ctx.driver.takeBuffer(std::move(mb));
1002
1003if (ctx.config.outputFile.empty())
1004ctx.config.outputFile = std::string(saver().save(m.OutputFile));
1005ctx.config.importName = std::string(saver().save(m.ImportName));
1006if (m.ImageBase)
1007ctx.config.imageBase = m.ImageBase;
1008if (m.StackReserve)
1009ctx.config.stackReserve = m.StackReserve;
1010if (m.StackCommit)
1011ctx.config.stackCommit = m.StackCommit;
1012if (m.HeapReserve)
1013ctx.config.heapReserve = m.HeapReserve;
1014if (m.HeapCommit)
1015ctx.config.heapCommit = m.HeapCommit;
1016if (m.MajorImageVersion)
1017ctx.config.majorImageVersion = m.MajorImageVersion;
1018if (m.MinorImageVersion)
1019ctx.config.minorImageVersion = m.MinorImageVersion;
1020if (m.MajorOSVersion)
1021ctx.config.majorOSVersion = m.MajorOSVersion;
1022if (m.MinorOSVersion)
1023ctx.config.minorOSVersion = m.MinorOSVersion;
1024
1025for (COFFShortExport e1 : m.Exports) {
1026Export e2;
1027// Renamed exports are parsed and set as "ExtName = Name". If Name has
1028// the form "OtherDll.Func", it shouldn't be a normal exported
1029// function but a forward to another DLL instead. This is supported
1030// by both MS and GNU linkers.
1031if (!e1.ExtName.empty() && e1.ExtName != e1.Name &&
1032StringRef(e1.Name).contains('.')) {
1033e2.name = saver().save(e1.ExtName);
1034e2.forwardTo = saver().save(e1.Name);
1035} else {
1036e2.name = saver().save(e1.Name);
1037e2.extName = saver().save(e1.ExtName);
1038}
1039e2.exportAs = saver().save(e1.ExportAs);
1040e2.importName = saver().save(e1.ImportName);
1041e2.ordinal = e1.Ordinal;
1042e2.noname = e1.Noname;
1043e2.data = e1.Data;
1044e2.isPrivate = e1.Private;
1045e2.constant = e1.Constant;
1046e2.source = ExportSource::ModuleDefinition;
1047ctx.config.exports.push_back(e2);
1048}
1049}
1050
1051void LinkerDriver::enqueueTask(std::function<void()> task) {
1052taskQueue.push_back(std::move(task));
1053}
1054
1055bool LinkerDriver::run() {
1056llvm::TimeTraceScope timeScope("Read input files");
1057ScopedTimer t(ctx.inputFileTimer);
1058
1059bool didWork = !taskQueue.empty();
1060while (!taskQueue.empty()) {
1061taskQueue.front()();
1062taskQueue.pop_front();
1063}
1064return didWork;
1065}
1066
1067// Parse an /order file. If an option is given, the linker places
1068// COMDAT sections in the same order as their names appear in the
1069// given file.
1070void LinkerDriver::parseOrderFile(StringRef arg) {
1071// For some reason, the MSVC linker requires a filename to be
1072// preceded by "@".
1073if (!arg.starts_with("@")) {
1074error("malformed /order option: '@' missing");
1075return;
1076}
1077
1078// Get a list of all comdat sections for error checking.
1079DenseSet<StringRef> set;
1080for (Chunk *c : ctx.symtab.getChunks())
1081if (auto *sec = dyn_cast<SectionChunk>(c))
1082if (sec->sym)
1083set.insert(sec->sym->getName());
1084
1085// Open a file.
1086StringRef path = arg.substr(1);
1087std::unique_ptr<MemoryBuffer> mb =
1088CHECK(MemoryBuffer::getFile(path, /*IsText=*/false,
1089/*RequiresNullTerminator=*/false,
1090/*IsVolatile=*/true),
1091"could not open " + path);
1092
1093// Parse a file. An order file contains one symbol per line.
1094// All symbols that were not present in a given order file are
1095// considered to have the lowest priority 0 and are placed at
1096// end of an output section.
1097for (StringRef arg : args::getLines(mb->getMemBufferRef())) {
1098std::string s(arg);
1099if (ctx.config.machine == I386 && !isDecorated(s))
1100s = "_" + s;
1101
1102if (set.count(s) == 0) {
1103if (ctx.config.warnMissingOrderSymbol)
1104warn("/order:" + arg + ": missing symbol: " + s + " [LNK4037]");
1105} else
1106ctx.config.order[s] = INT_MIN + ctx.config.order.size();
1107}
1108
1109// Include in /reproduce: output if applicable.
1110ctx.driver.takeBuffer(std::move(mb));
1111}
1112
1113void LinkerDriver::parseCallGraphFile(StringRef path) {
1114std::unique_ptr<MemoryBuffer> mb =
1115CHECK(MemoryBuffer::getFile(path, /*IsText=*/false,
1116/*RequiresNullTerminator=*/false,
1117/*IsVolatile=*/true),
1118"could not open " + path);
1119
1120// Build a map from symbol name to section.
1121DenseMap<StringRef, Symbol *> map;
1122for (ObjFile *file : ctx.objFileInstances)
1123for (Symbol *sym : file->getSymbols())
1124if (sym)
1125map[sym->getName()] = sym;
1126
1127auto findSection = [&](StringRef name) -> SectionChunk * {
1128Symbol *sym = map.lookup(name);
1129if (!sym) {
1130if (ctx.config.warnMissingOrderSymbol)
1131warn(path + ": no such symbol: " + name);
1132return nullptr;
1133}
1134
1135if (DefinedCOFF *dr = dyn_cast_or_null<DefinedCOFF>(sym))
1136return dyn_cast_or_null<SectionChunk>(dr->getChunk());
1137return nullptr;
1138};
1139
1140for (StringRef line : args::getLines(*mb)) {
1141SmallVector<StringRef, 3> fields;
1142line.split(fields, ' ');
1143uint64_t count;
1144
1145if (fields.size() != 3 || !to_integer(fields[2], count)) {
1146error(path + ": parse error");
1147return;
1148}
1149
1150if (SectionChunk *from = findSection(fields[0]))
1151if (SectionChunk *to = findSection(fields[1]))
1152ctx.config.callGraphProfile[{from, to}] += count;
1153}
1154
1155// Include in /reproduce: output if applicable.
1156ctx.driver.takeBuffer(std::move(mb));
1157}
1158
1159static void readCallGraphsFromObjectFiles(COFFLinkerContext &ctx) {
1160for (ObjFile *obj : ctx.objFileInstances) {
1161if (obj->callgraphSec) {
1162ArrayRef<uint8_t> contents;
1163cantFail(
1164obj->getCOFFObj()->getSectionContents(obj->callgraphSec, contents));
1165BinaryStreamReader reader(contents, llvm::endianness::little);
1166while (!reader.empty()) {
1167uint32_t fromIndex, toIndex;
1168uint64_t count;
1169if (Error err = reader.readInteger(fromIndex))
1170fatal(toString(obj) + ": Expected 32-bit integer");
1171if (Error err = reader.readInteger(toIndex))
1172fatal(toString(obj) + ": Expected 32-bit integer");
1173if (Error err = reader.readInteger(count))
1174fatal(toString(obj) + ": Expected 64-bit integer");
1175auto *fromSym = dyn_cast_or_null<Defined>(obj->getSymbol(fromIndex));
1176auto *toSym = dyn_cast_or_null<Defined>(obj->getSymbol(toIndex));
1177if (!fromSym || !toSym)
1178continue;
1179auto *from = dyn_cast_or_null<SectionChunk>(fromSym->getChunk());
1180auto *to = dyn_cast_or_null<SectionChunk>(toSym->getChunk());
1181if (from && to)
1182ctx.config.callGraphProfile[{from, to}] += count;
1183}
1184}
1185}
1186}
1187
1188static void markAddrsig(Symbol *s) {
1189if (auto *d = dyn_cast_or_null<Defined>(s))
1190if (SectionChunk *c = dyn_cast_or_null<SectionChunk>(d->getChunk()))
1191c->keepUnique = true;
1192}
1193
1194static void findKeepUniqueSections(COFFLinkerContext &ctx) {
1195llvm::TimeTraceScope timeScope("Find keep unique sections");
1196
1197// Exported symbols could be address-significant in other executables or DSOs,
1198// so we conservatively mark them as address-significant.
1199for (Export &r : ctx.config.exports)
1200markAddrsig(r.sym);
1201
1202// Visit the address-significance table in each object file and mark each
1203// referenced symbol as address-significant.
1204for (ObjFile *obj : ctx.objFileInstances) {
1205ArrayRef<Symbol *> syms = obj->getSymbols();
1206if (obj->addrsigSec) {
1207ArrayRef<uint8_t> contents;
1208cantFail(
1209obj->getCOFFObj()->getSectionContents(obj->addrsigSec, contents));
1210const uint8_t *cur = contents.begin();
1211while (cur != contents.end()) {
1212unsigned size;
1213const char *err = nullptr;
1214uint64_t symIndex = decodeULEB128(cur, &size, contents.end(), &err);
1215if (err)
1216fatal(toString(obj) + ": could not decode addrsig section: " + err);
1217if (symIndex >= syms.size())
1218fatal(toString(obj) + ": invalid symbol index in addrsig section");
1219markAddrsig(syms[symIndex]);
1220cur += size;
1221}
1222} else {
1223// If an object file does not have an address-significance table,
1224// conservatively mark all of its symbols as address-significant.
1225for (Symbol *s : syms)
1226markAddrsig(s);
1227}
1228}
1229}
1230
1231// link.exe replaces each %foo% in altPath with the contents of environment
1232// variable foo, and adds the two magic env vars _PDB (expands to the basename
1233// of pdb's output path) and _EXT (expands to the extension of the output
1234// binary).
1235// lld only supports %_PDB% and %_EXT% and warns on references to all other env
1236// vars.
1237void LinkerDriver::parsePDBAltPath() {
1238SmallString<128> buf;
1239StringRef pdbBasename =
1240sys::path::filename(ctx.config.pdbPath, sys::path::Style::windows);
1241StringRef binaryExtension =
1242sys::path::extension(ctx.config.outputFile, sys::path::Style::windows);
1243if (!binaryExtension.empty())
1244binaryExtension = binaryExtension.substr(1); // %_EXT% does not include '.'.
1245
1246// Invariant:
1247// +--------- cursor ('a...' might be the empty string).
1248// | +----- firstMark
1249// | | +- secondMark
1250// v v v
1251// a...%...%...
1252size_t cursor = 0;
1253while (cursor < ctx.config.pdbAltPath.size()) {
1254size_t firstMark, secondMark;
1255if ((firstMark = ctx.config.pdbAltPath.find('%', cursor)) ==
1256StringRef::npos ||
1257(secondMark = ctx.config.pdbAltPath.find('%', firstMark + 1)) ==
1258StringRef::npos) {
1259// Didn't find another full fragment, treat rest of string as literal.
1260buf.append(ctx.config.pdbAltPath.substr(cursor));
1261break;
1262}
1263
1264// Found a full fragment. Append text in front of first %, and interpret
1265// text between first and second % as variable name.
1266buf.append(ctx.config.pdbAltPath.substr(cursor, firstMark - cursor));
1267StringRef var =
1268ctx.config.pdbAltPath.substr(firstMark, secondMark - firstMark + 1);
1269if (var.equals_insensitive("%_pdb%"))
1270buf.append(pdbBasename);
1271else if (var.equals_insensitive("%_ext%"))
1272buf.append(binaryExtension);
1273else {
1274warn("only %_PDB% and %_EXT% supported in /pdbaltpath:, keeping " + var +
1275" as literal");
1276buf.append(var);
1277}
1278
1279cursor = secondMark + 1;
1280}
1281
1282ctx.config.pdbAltPath = buf;
1283}
1284
1285/// Convert resource files and potentially merge input resource object
1286/// trees into one resource tree.
1287/// Call after ObjFile::Instances is complete.
1288void LinkerDriver::convertResources() {
1289llvm::TimeTraceScope timeScope("Convert resources");
1290std::vector<ObjFile *> resourceObjFiles;
1291
1292for (ObjFile *f : ctx.objFileInstances) {
1293if (f->isResourceObjFile())
1294resourceObjFiles.push_back(f);
1295}
1296
1297if (!ctx.config.mingw &&
1298(resourceObjFiles.size() > 1 ||
1299(resourceObjFiles.size() == 1 && !resources.empty()))) {
1300error((!resources.empty() ? "internal .obj file created from .res files"
1301: toString(resourceObjFiles[1])) +
1302": more than one resource obj file not allowed, already got " +
1303toString(resourceObjFiles.front()));
1304return;
1305}
1306
1307if (resources.empty() && resourceObjFiles.size() <= 1) {
1308// No resources to convert, and max one resource object file in
1309// the input. Keep that preconverted resource section as is.
1310for (ObjFile *f : resourceObjFiles)
1311f->includeResourceChunks();
1312return;
1313}
1314ObjFile *f =
1315make<ObjFile>(ctx, convertResToCOFF(resources, resourceObjFiles));
1316ctx.symtab.addFile(f);
1317f->includeResourceChunks();
1318}
1319
1320// In MinGW, if no symbols are chosen to be exported, then all symbols are
1321// automatically exported by default. This behavior can be forced by the
1322// -export-all-symbols option, so that it happens even when exports are
1323// explicitly specified. The automatic behavior can be disabled using the
1324// -exclude-all-symbols option, so that lld-link behaves like link.exe rather
1325// than MinGW in the case that nothing is explicitly exported.
1326void LinkerDriver::maybeExportMinGWSymbols(const opt::InputArgList &args) {
1327if (!args.hasArg(OPT_export_all_symbols)) {
1328if (!ctx.config.dll)
1329return;
1330
1331if (!ctx.config.exports.empty())
1332return;
1333if (args.hasArg(OPT_exclude_all_symbols))
1334return;
1335}
1336
1337AutoExporter exporter(ctx, excludedSymbols);
1338
1339for (auto *arg : args.filtered(OPT_wholearchive_file))
1340if (std::optional<StringRef> path = findFile(arg->getValue()))
1341exporter.addWholeArchive(*path);
1342
1343for (auto *arg : args.filtered(OPT_exclude_symbols)) {
1344SmallVector<StringRef, 2> vec;
1345StringRef(arg->getValue()).split(vec, ',');
1346for (StringRef sym : vec)
1347exporter.addExcludedSymbol(mangle(sym));
1348}
1349
1350ctx.symtab.forEachSymbol([&](Symbol *s) {
1351auto *def = dyn_cast<Defined>(s);
1352if (!exporter.shouldExport(def))
1353return;
1354
1355if (!def->isGCRoot) {
1356def->isGCRoot = true;
1357ctx.config.gcroot.push_back(def);
1358}
1359
1360Export e;
1361e.name = def->getName();
1362e.sym = def;
1363if (Chunk *c = def->getChunk())
1364if (!(c->getOutputCharacteristics() & IMAGE_SCN_MEM_EXECUTE))
1365e.data = true;
1366s->isUsedInRegularObj = true;
1367ctx.config.exports.push_back(e);
1368});
1369}
1370
1371// lld has a feature to create a tar file containing all input files as well as
1372// all command line options, so that other people can run lld again with exactly
1373// the same inputs. This feature is accessible via /linkrepro and /reproduce.
1374//
1375// /linkrepro and /reproduce are very similar, but /linkrepro takes a directory
1376// name while /reproduce takes a full path. We have /linkrepro for compatibility
1377// with Microsoft link.exe.
1378std::optional<std::string> getReproduceFile(const opt::InputArgList &args) {
1379if (auto *arg = args.getLastArg(OPT_reproduce))
1380return std::string(arg->getValue());
1381
1382if (auto *arg = args.getLastArg(OPT_linkrepro)) {
1383SmallString<64> path = StringRef(arg->getValue());
1384sys::path::append(path, "repro.tar");
1385return std::string(path);
1386}
1387
1388// This is intentionally not guarded by OPT_lldignoreenv since writing
1389// a repro tar file doesn't affect the main output.
1390if (auto *path = getenv("LLD_REPRODUCE"))
1391return std::string(path);
1392
1393return std::nullopt;
1394}
1395
1396static std::unique_ptr<llvm::vfs::FileSystem>
1397getVFS(const opt::InputArgList &args) {
1398using namespace llvm::vfs;
1399
1400const opt::Arg *arg = args.getLastArg(OPT_vfsoverlay);
1401if (!arg)
1402return nullptr;
1403
1404auto bufOrErr = llvm::MemoryBuffer::getFile(arg->getValue());
1405if (!bufOrErr) {
1406checkError(errorCodeToError(bufOrErr.getError()));
1407return nullptr;
1408}
1409
1410if (auto ret = vfs::getVFSFromYAML(std::move(*bufOrErr),
1411/*DiagHandler*/ nullptr, arg->getValue()))
1412return ret;
1413
1414error("Invalid vfs overlay");
1415return nullptr;
1416}
1417
1418void LinkerDriver::linkerMain(ArrayRef<const char *> argsArr) {
1419ScopedTimer rootTimer(ctx.rootTimer);
1420Configuration *config = &ctx.config;
1421
1422// Needed for LTO.
1423InitializeAllTargetInfos();
1424InitializeAllTargets();
1425InitializeAllTargetMCs();
1426InitializeAllAsmParsers();
1427InitializeAllAsmPrinters();
1428
1429// If the first command line argument is "/lib", link.exe acts like lib.exe.
1430// We call our own implementation of lib.exe that understands bitcode files.
1431if (argsArr.size() > 1 &&
1432(StringRef(argsArr[1]).equals_insensitive("/lib") ||
1433StringRef(argsArr[1]).equals_insensitive("-lib"))) {
1434if (llvm::libDriverMain(argsArr.slice(1)) != 0)
1435fatal("lib failed");
1436return;
1437}
1438
1439// Parse command line options.
1440ArgParser parser(ctx);
1441opt::InputArgList args = parser.parse(argsArr);
1442
1443// Initialize time trace profiler.
1444config->timeTraceEnabled = args.hasArg(OPT_time_trace_eq);
1445config->timeTraceGranularity =
1446args::getInteger(args, OPT_time_trace_granularity_eq, 500);
1447
1448if (config->timeTraceEnabled)
1449timeTraceProfilerInitialize(config->timeTraceGranularity, argsArr[0]);
1450
1451llvm::TimeTraceScope timeScope("COFF link");
1452
1453// Parse and evaluate -mllvm options.
1454std::vector<const char *> v;
1455v.push_back("lld-link (LLVM option parsing)");
1456for (const auto *arg : args.filtered(OPT_mllvm)) {
1457v.push_back(arg->getValue());
1458config->mllvmOpts.emplace_back(arg->getValue());
1459}
1460{
1461llvm::TimeTraceScope timeScope2("Parse cl::opt");
1462cl::ResetAllOptionOccurrences();
1463cl::ParseCommandLineOptions(v.size(), v.data());
1464}
1465
1466// Handle /errorlimit early, because error() depends on it.
1467if (auto *arg = args.getLastArg(OPT_errorlimit)) {
1468int n = 20;
1469StringRef s = arg->getValue();
1470if (s.getAsInteger(10, n))
1471error(arg->getSpelling() + " number expected, but got " + s);
1472errorHandler().errorLimit = n;
1473}
1474
1475config->vfs = getVFS(args);
1476
1477// Handle /help
1478if (args.hasArg(OPT_help)) {
1479printHelp(argsArr[0]);
1480return;
1481}
1482
1483// /threads: takes a positive integer and provides the default value for
1484// /opt:lldltojobs=.
1485if (auto *arg = args.getLastArg(OPT_threads)) {
1486StringRef v(arg->getValue());
1487unsigned threads = 0;
1488if (!llvm::to_integer(v, threads, 0) || threads == 0)
1489error(arg->getSpelling() + ": expected a positive integer, but got '" +
1490arg->getValue() + "'");
1491parallel::strategy = hardware_concurrency(threads);
1492config->thinLTOJobs = v.str();
1493}
1494
1495if (args.hasArg(OPT_show_timing))
1496config->showTiming = true;
1497
1498config->showSummary = args.hasArg(OPT_summary);
1499config->printSearchPaths = args.hasArg(OPT_print_search_paths);
1500
1501// Handle --version, which is an lld extension. This option is a bit odd
1502// because it doesn't start with "/", but we deliberately chose "--" to
1503// avoid conflict with /version and for compatibility with clang-cl.
1504if (args.hasArg(OPT_dash_dash_version)) {
1505message(getLLDVersion());
1506return;
1507}
1508
1509// Handle /lldmingw early, since it can potentially affect how other
1510// options are handled.
1511config->mingw = args.hasArg(OPT_lldmingw);
1512if (config->mingw)
1513ctx.e.errorLimitExceededMsg = "too many errors emitted, stopping now"
1514" (use --error-limit=0 to see all errors)";
1515
1516// Handle /linkrepro and /reproduce.
1517{
1518llvm::TimeTraceScope timeScope2("Reproducer");
1519if (std::optional<std::string> path = getReproduceFile(args)) {
1520Expected<std::unique_ptr<TarWriter>> errOrWriter =
1521TarWriter::create(*path, sys::path::stem(*path));
1522
1523if (errOrWriter) {
1524tar = std::move(*errOrWriter);
1525} else {
1526error("/linkrepro: failed to open " + *path + ": " +
1527toString(errOrWriter.takeError()));
1528}
1529}
1530}
1531
1532if (!args.hasArg(OPT_INPUT, OPT_wholearchive_file)) {
1533if (args.hasArg(OPT_deffile))
1534config->noEntry = true;
1535else
1536fatal("no input files");
1537}
1538
1539// Construct search path list.
1540{
1541llvm::TimeTraceScope timeScope2("Search paths");
1542searchPaths.emplace_back("");
1543for (auto *arg : args.filtered(OPT_libpath))
1544searchPaths.push_back(arg->getValue());
1545if (!config->mingw) {
1546// Prefer the Clang provided builtins over the ones bundled with MSVC.
1547// In MinGW mode, the compiler driver passes the necessary libpath
1548// options explicitly.
1549addClangLibSearchPaths(argsArr[0]);
1550// Don't automatically deduce the lib path from the environment or MSVC
1551// installations when operating in mingw mode. (This also makes LLD ignore
1552// winsysroot and vctoolsdir arguments.)
1553detectWinSysRoot(args);
1554if (!args.hasArg(OPT_lldignoreenv) && !args.hasArg(OPT_winsysroot))
1555addLibSearchPaths();
1556} else {
1557if (args.hasArg(OPT_vctoolsdir, OPT_winsysroot))
1558warn("ignoring /vctoolsdir or /winsysroot flags in MinGW mode");
1559}
1560}
1561
1562// Handle /ignore
1563for (auto *arg : args.filtered(OPT_ignore)) {
1564SmallVector<StringRef, 8> vec;
1565StringRef(arg->getValue()).split(vec, ',');
1566for (StringRef s : vec) {
1567if (s == "4037")
1568config->warnMissingOrderSymbol = false;
1569else if (s == "4099")
1570config->warnDebugInfoUnusable = false;
1571else if (s == "4217")
1572config->warnLocallyDefinedImported = false;
1573else if (s == "longsections")
1574config->warnLongSectionNames = false;
1575// Other warning numbers are ignored.
1576}
1577}
1578
1579// Handle /out
1580if (auto *arg = args.getLastArg(OPT_out))
1581config->outputFile = arg->getValue();
1582
1583// Handle /verbose
1584if (args.hasArg(OPT_verbose))
1585config->verbose = true;
1586errorHandler().verbose = config->verbose;
1587
1588// Handle /force or /force:unresolved
1589if (args.hasArg(OPT_force, OPT_force_unresolved))
1590config->forceUnresolved = true;
1591
1592// Handle /force or /force:multiple
1593if (args.hasArg(OPT_force, OPT_force_multiple))
1594config->forceMultiple = true;
1595
1596// Handle /force or /force:multipleres
1597if (args.hasArg(OPT_force, OPT_force_multipleres))
1598config->forceMultipleRes = true;
1599
1600// Don't warn about long section names, such as .debug_info, for mingw (or
1601// when -debug:dwarf is requested, handled below).
1602if (config->mingw)
1603config->warnLongSectionNames = false;
1604
1605bool doGC = true;
1606
1607// Handle /debug
1608bool shouldCreatePDB = false;
1609for (auto *arg : args.filtered(OPT_debug, OPT_debug_opt)) {
1610std::string str;
1611if (arg->getOption().getID() == OPT_debug)
1612str = "full";
1613else
1614str = StringRef(arg->getValue()).lower();
1615SmallVector<StringRef, 1> vec;
1616StringRef(str).split(vec, ',');
1617for (StringRef s : vec) {
1618if (s == "fastlink") {
1619warn("/debug:fastlink unsupported; using /debug:full");
1620s = "full";
1621}
1622if (s == "none") {
1623config->debug = false;
1624config->incremental = false;
1625config->includeDwarfChunks = false;
1626config->debugGHashes = false;
1627config->writeSymtab = false;
1628shouldCreatePDB = false;
1629doGC = true;
1630} else if (s == "full" || s == "ghash" || s == "noghash") {
1631config->debug = true;
1632config->incremental = true;
1633config->includeDwarfChunks = true;
1634if (s == "full" || s == "ghash")
1635config->debugGHashes = true;
1636shouldCreatePDB = true;
1637doGC = false;
1638} else if (s == "dwarf") {
1639config->debug = true;
1640config->incremental = true;
1641config->includeDwarfChunks = true;
1642config->writeSymtab = true;
1643config->warnLongSectionNames = false;
1644doGC = false;
1645} else if (s == "nodwarf") {
1646config->includeDwarfChunks = false;
1647} else if (s == "symtab") {
1648config->writeSymtab = true;
1649doGC = false;
1650} else if (s == "nosymtab") {
1651config->writeSymtab = false;
1652} else {
1653error("/debug: unknown option: " + s);
1654}
1655}
1656}
1657
1658// Handle /demangle
1659config->demangle = args.hasFlag(OPT_demangle, OPT_demangle_no, true);
1660
1661// Handle /debugtype
1662config->debugTypes = parseDebugTypes(args);
1663
1664// Handle /driver[:uponly|:wdm].
1665config->driverUponly = args.hasArg(OPT_driver_uponly) ||
1666args.hasArg(OPT_driver_uponly_wdm) ||
1667args.hasArg(OPT_driver_wdm_uponly);
1668config->driverWdm = args.hasArg(OPT_driver_wdm) ||
1669args.hasArg(OPT_driver_uponly_wdm) ||
1670args.hasArg(OPT_driver_wdm_uponly);
1671config->driver =
1672config->driverUponly || config->driverWdm || args.hasArg(OPT_driver);
1673
1674// Handle /pdb
1675if (shouldCreatePDB) {
1676if (auto *arg = args.getLastArg(OPT_pdb))
1677config->pdbPath = arg->getValue();
1678if (auto *arg = args.getLastArg(OPT_pdbaltpath))
1679config->pdbAltPath = arg->getValue();
1680if (auto *arg = args.getLastArg(OPT_pdbpagesize))
1681parsePDBPageSize(arg->getValue());
1682if (args.hasArg(OPT_natvis))
1683config->natvisFiles = args.getAllArgValues(OPT_natvis);
1684if (args.hasArg(OPT_pdbstream)) {
1685for (const StringRef value : args.getAllArgValues(OPT_pdbstream)) {
1686const std::pair<StringRef, StringRef> nameFile = value.split("=");
1687const StringRef name = nameFile.first;
1688const std::string file = nameFile.second.str();
1689config->namedStreams[name] = file;
1690}
1691}
1692
1693if (auto *arg = args.getLastArg(OPT_pdb_source_path))
1694config->pdbSourcePath = arg->getValue();
1695}
1696
1697// Handle /pdbstripped
1698if (args.hasArg(OPT_pdbstripped))
1699warn("ignoring /pdbstripped flag, it is not yet supported");
1700
1701// Handle /noentry
1702if (args.hasArg(OPT_noentry)) {
1703if (args.hasArg(OPT_dll))
1704config->noEntry = true;
1705else
1706error("/noentry must be specified with /dll");
1707}
1708
1709// Handle /dll
1710if (args.hasArg(OPT_dll)) {
1711config->dll = true;
1712config->manifestID = 2;
1713}
1714
1715// Handle /dynamicbase and /fixed. We can't use hasFlag for /dynamicbase
1716// because we need to explicitly check whether that option or its inverse was
1717// present in the argument list in order to handle /fixed.
1718auto *dynamicBaseArg = args.getLastArg(OPT_dynamicbase, OPT_dynamicbase_no);
1719if (dynamicBaseArg &&
1720dynamicBaseArg->getOption().getID() == OPT_dynamicbase_no)
1721config->dynamicBase = false;
1722
1723// MSDN claims "/FIXED:NO is the default setting for a DLL, and /FIXED is the
1724// default setting for any other project type.", but link.exe defaults to
1725// /FIXED:NO for exe outputs as well. Match behavior, not docs.
1726bool fixed = args.hasFlag(OPT_fixed, OPT_fixed_no, false);
1727if (fixed) {
1728if (dynamicBaseArg &&
1729dynamicBaseArg->getOption().getID() == OPT_dynamicbase) {
1730error("/fixed must not be specified with /dynamicbase");
1731} else {
1732config->relocatable = false;
1733config->dynamicBase = false;
1734}
1735}
1736
1737// Handle /appcontainer
1738config->appContainer =
1739args.hasFlag(OPT_appcontainer, OPT_appcontainer_no, false);
1740
1741// Handle /machine
1742{
1743llvm::TimeTraceScope timeScope2("Machine arg");
1744if (auto *arg = args.getLastArg(OPT_machine)) {
1745config->machine = getMachineType(arg->getValue());
1746if (config->machine == IMAGE_FILE_MACHINE_UNKNOWN)
1747fatal(Twine("unknown /machine argument: ") + arg->getValue());
1748addWinSysRootLibSearchPaths();
1749}
1750}
1751
1752// Handle /nodefaultlib:<filename>
1753{
1754llvm::TimeTraceScope timeScope2("Nodefaultlib");
1755for (auto *arg : args.filtered(OPT_nodefaultlib))
1756config->noDefaultLibs.insert(findLib(arg->getValue()).lower());
1757}
1758
1759// Handle /nodefaultlib
1760if (args.hasArg(OPT_nodefaultlib_all))
1761config->noDefaultLibAll = true;
1762
1763// Handle /base
1764if (auto *arg = args.getLastArg(OPT_base))
1765parseNumbers(arg->getValue(), &config->imageBase);
1766
1767// Handle /filealign
1768if (auto *arg = args.getLastArg(OPT_filealign)) {
1769parseNumbers(arg->getValue(), &config->fileAlign);
1770if (!isPowerOf2_64(config->fileAlign))
1771error("/filealign: not a power of two: " + Twine(config->fileAlign));
1772}
1773
1774// Handle /stack
1775if (auto *arg = args.getLastArg(OPT_stack))
1776parseNumbers(arg->getValue(), &config->stackReserve, &config->stackCommit);
1777
1778// Handle /guard:cf
1779if (auto *arg = args.getLastArg(OPT_guard))
1780parseGuard(arg->getValue());
1781
1782// Handle /heap
1783if (auto *arg = args.getLastArg(OPT_heap))
1784parseNumbers(arg->getValue(), &config->heapReserve, &config->heapCommit);
1785
1786// Handle /version
1787if (auto *arg = args.getLastArg(OPT_version))
1788parseVersion(arg->getValue(), &config->majorImageVersion,
1789&config->minorImageVersion);
1790
1791// Handle /subsystem
1792if (auto *arg = args.getLastArg(OPT_subsystem))
1793parseSubsystem(arg->getValue(), &config->subsystem,
1794&config->majorSubsystemVersion,
1795&config->minorSubsystemVersion);
1796
1797// Handle /osversion
1798if (auto *arg = args.getLastArg(OPT_osversion)) {
1799parseVersion(arg->getValue(), &config->majorOSVersion,
1800&config->minorOSVersion);
1801} else {
1802config->majorOSVersion = config->majorSubsystemVersion;
1803config->minorOSVersion = config->minorSubsystemVersion;
1804}
1805
1806// Handle /timestamp
1807if (llvm::opt::Arg *arg = args.getLastArg(OPT_timestamp, OPT_repro)) {
1808if (arg->getOption().getID() == OPT_repro) {
1809config->timestamp = 0;
1810config->repro = true;
1811} else {
1812config->repro = false;
1813StringRef value(arg->getValue());
1814if (value.getAsInteger(0, config->timestamp))
1815fatal(Twine("invalid timestamp: ") + value +
1816". Expected 32-bit integer");
1817}
1818} else {
1819config->repro = false;
1820if (std::optional<std::string> epoch =
1821Process::GetEnv("SOURCE_DATE_EPOCH")) {
1822StringRef value(*epoch);
1823if (value.getAsInteger(0, config->timestamp))
1824fatal(Twine("invalid SOURCE_DATE_EPOCH timestamp: ") + value +
1825". Expected 32-bit integer");
1826} else {
1827config->timestamp = time(nullptr);
1828}
1829}
1830
1831// Handle /alternatename
1832for (auto *arg : args.filtered(OPT_alternatename))
1833parseAlternateName(arg->getValue());
1834
1835// Handle /include
1836for (auto *arg : args.filtered(OPT_incl))
1837addUndefined(arg->getValue());
1838
1839// Handle /implib
1840if (auto *arg = args.getLastArg(OPT_implib))
1841config->implib = arg->getValue();
1842
1843config->noimplib = args.hasArg(OPT_noimplib);
1844
1845if (args.hasArg(OPT_profile))
1846doGC = true;
1847// Handle /opt.
1848std::optional<ICFLevel> icfLevel;
1849if (args.hasArg(OPT_profile))
1850icfLevel = ICFLevel::None;
1851unsigned tailMerge = 1;
1852bool ltoDebugPM = false;
1853for (auto *arg : args.filtered(OPT_opt)) {
1854std::string str = StringRef(arg->getValue()).lower();
1855SmallVector<StringRef, 1> vec;
1856StringRef(str).split(vec, ',');
1857for (StringRef s : vec) {
1858if (s == "ref") {
1859doGC = true;
1860} else if (s == "noref") {
1861doGC = false;
1862} else if (s == "icf" || s.starts_with("icf=")) {
1863icfLevel = ICFLevel::All;
1864} else if (s == "safeicf") {
1865icfLevel = ICFLevel::Safe;
1866} else if (s == "noicf") {
1867icfLevel = ICFLevel::None;
1868} else if (s == "lldtailmerge") {
1869tailMerge = 2;
1870} else if (s == "nolldtailmerge") {
1871tailMerge = 0;
1872} else if (s == "ltodebugpassmanager") {
1873ltoDebugPM = true;
1874} else if (s == "noltodebugpassmanager") {
1875ltoDebugPM = false;
1876} else if (s.consume_front("lldlto=")) {
1877if (s.getAsInteger(10, config->ltoo) || config->ltoo > 3)
1878error("/opt:lldlto: invalid optimization level: " + s);
1879} else if (s.consume_front("lldltocgo=")) {
1880config->ltoCgo.emplace();
1881if (s.getAsInteger(10, *config->ltoCgo) || *config->ltoCgo > 3)
1882error("/opt:lldltocgo: invalid codegen optimization level: " + s);
1883} else if (s.consume_front("lldltojobs=")) {
1884if (!get_threadpool_strategy(s))
1885error("/opt:lldltojobs: invalid job count: " + s);
1886config->thinLTOJobs = s.str();
1887} else if (s.consume_front("lldltopartitions=")) {
1888if (s.getAsInteger(10, config->ltoPartitions) ||
1889config->ltoPartitions == 0)
1890error("/opt:lldltopartitions: invalid partition count: " + s);
1891} else if (s != "lbr" && s != "nolbr")
1892error("/opt: unknown option: " + s);
1893}
1894}
1895
1896if (!icfLevel)
1897icfLevel = doGC ? ICFLevel::All : ICFLevel::None;
1898config->doGC = doGC;
1899config->doICF = *icfLevel;
1900config->tailMerge =
1901(tailMerge == 1 && config->doICF != ICFLevel::None) || tailMerge == 2;
1902config->ltoDebugPassManager = ltoDebugPM;
1903
1904// Handle /lldsavetemps
1905if (args.hasArg(OPT_lldsavetemps))
1906config->saveTemps = true;
1907
1908// Handle /lldemit
1909if (auto *arg = args.getLastArg(OPT_lldemit)) {
1910StringRef s = arg->getValue();
1911if (s == "obj")
1912config->emit = EmitKind::Obj;
1913else if (s == "llvm")
1914config->emit = EmitKind::LLVM;
1915else if (s == "asm")
1916config->emit = EmitKind::ASM;
1917else
1918error("/lldemit: unknown option: " + s);
1919}
1920
1921// Handle /kill-at
1922if (args.hasArg(OPT_kill_at))
1923config->killAt = true;
1924
1925// Handle /lldltocache
1926if (auto *arg = args.getLastArg(OPT_lldltocache))
1927config->ltoCache = arg->getValue();
1928
1929// Handle /lldsavecachepolicy
1930if (auto *arg = args.getLastArg(OPT_lldltocachepolicy))
1931config->ltoCachePolicy = CHECK(
1932parseCachePruningPolicy(arg->getValue()),
1933Twine("/lldltocachepolicy: invalid cache policy: ") + arg->getValue());
1934
1935// Handle /failifmismatch
1936for (auto *arg : args.filtered(OPT_failifmismatch))
1937checkFailIfMismatch(arg->getValue(), nullptr);
1938
1939// Handle /merge
1940for (auto *arg : args.filtered(OPT_merge))
1941parseMerge(arg->getValue());
1942
1943// Add default section merging rules after user rules. User rules take
1944// precedence, but we will emit a warning if there is a conflict.
1945parseMerge(".idata=.rdata");
1946parseMerge(".didat=.rdata");
1947parseMerge(".edata=.rdata");
1948parseMerge(".xdata=.rdata");
1949parseMerge(".00cfg=.rdata");
1950parseMerge(".bss=.data");
1951
1952if (isArm64EC(config->machine))
1953parseMerge(".wowthk=.text");
1954
1955if (config->mingw) {
1956parseMerge(".ctors=.rdata");
1957parseMerge(".dtors=.rdata");
1958parseMerge(".CRT=.rdata");
1959}
1960
1961// Handle /section
1962for (auto *arg : args.filtered(OPT_section))
1963parseSection(arg->getValue());
1964
1965// Handle /align
1966if (auto *arg = args.getLastArg(OPT_align)) {
1967parseNumbers(arg->getValue(), &config->align);
1968if (!isPowerOf2_64(config->align))
1969error("/align: not a power of two: " + StringRef(arg->getValue()));
1970if (!args.hasArg(OPT_driver))
1971warn("/align specified without /driver; image may not run");
1972}
1973
1974// Handle /aligncomm
1975for (auto *arg : args.filtered(OPT_aligncomm))
1976parseAligncomm(arg->getValue());
1977
1978// Handle /manifestdependency.
1979for (auto *arg : args.filtered(OPT_manifestdependency))
1980config->manifestDependencies.insert(arg->getValue());
1981
1982// Handle /manifest and /manifest:
1983if (auto *arg = args.getLastArg(OPT_manifest, OPT_manifest_colon)) {
1984if (arg->getOption().getID() == OPT_manifest)
1985config->manifest = Configuration::SideBySide;
1986else
1987parseManifest(arg->getValue());
1988}
1989
1990// Handle /manifestuac
1991if (auto *arg = args.getLastArg(OPT_manifestuac))
1992parseManifestUAC(arg->getValue());
1993
1994// Handle /manifestfile
1995if (auto *arg = args.getLastArg(OPT_manifestfile))
1996config->manifestFile = arg->getValue();
1997
1998// Handle /manifestinput
1999for (auto *arg : args.filtered(OPT_manifestinput))
2000config->manifestInput.push_back(arg->getValue());
2001
2002if (!config->manifestInput.empty() &&
2003config->manifest != Configuration::Embed) {
2004fatal("/manifestinput: requires /manifest:embed");
2005}
2006
2007// Handle /dwodir
2008config->dwoDir = args.getLastArgValue(OPT_dwodir);
2009
2010config->thinLTOEmitImportsFiles = args.hasArg(OPT_thinlto_emit_imports_files);
2011config->thinLTOIndexOnly = args.hasArg(OPT_thinlto_index_only) ||
2012args.hasArg(OPT_thinlto_index_only_arg);
2013config->thinLTOIndexOnlyArg =
2014args.getLastArgValue(OPT_thinlto_index_only_arg);
2015std::tie(config->thinLTOPrefixReplaceOld, config->thinLTOPrefixReplaceNew,
2016config->thinLTOPrefixReplaceNativeObject) =
2017getOldNewOptionsExtra(args, OPT_thinlto_prefix_replace);
2018config->thinLTOObjectSuffixReplace =
2019getOldNewOptions(args, OPT_thinlto_object_suffix_replace);
2020config->ltoObjPath = args.getLastArgValue(OPT_lto_obj_path);
2021config->ltoCSProfileGenerate = args.hasArg(OPT_lto_cs_profile_generate);
2022config->ltoCSProfileFile = args.getLastArgValue(OPT_lto_cs_profile_file);
2023config->ltoSampleProfileName = args.getLastArgValue(OPT_lto_sample_profile);
2024// Handle miscellaneous boolean flags.
2025config->ltoPGOWarnMismatch = args.hasFlag(OPT_lto_pgo_warn_mismatch,
2026OPT_lto_pgo_warn_mismatch_no, true);
2027config->allowBind = args.hasFlag(OPT_allowbind, OPT_allowbind_no, true);
2028config->allowIsolation =
2029args.hasFlag(OPT_allowisolation, OPT_allowisolation_no, true);
2030config->incremental =
2031args.hasFlag(OPT_incremental, OPT_incremental_no,
2032!config->doGC && config->doICF == ICFLevel::None &&
2033!args.hasArg(OPT_order) && !args.hasArg(OPT_profile));
2034config->integrityCheck =
2035args.hasFlag(OPT_integritycheck, OPT_integritycheck_no, false);
2036config->cetCompat = args.hasFlag(OPT_cetcompat, OPT_cetcompat_no, false);
2037config->nxCompat = args.hasFlag(OPT_nxcompat, OPT_nxcompat_no, true);
2038for (auto *arg : args.filtered(OPT_swaprun))
2039parseSwaprun(arg->getValue());
2040config->terminalServerAware =
2041!config->dll && args.hasFlag(OPT_tsaware, OPT_tsaware_no, true);
2042config->autoImport =
2043args.hasFlag(OPT_auto_import, OPT_auto_import_no, config->mingw);
2044config->pseudoRelocs = args.hasFlag(
2045OPT_runtime_pseudo_reloc, OPT_runtime_pseudo_reloc_no, config->mingw);
2046config->callGraphProfileSort = args.hasFlag(
2047OPT_call_graph_profile_sort, OPT_call_graph_profile_sort_no, true);
2048config->stdcallFixup =
2049args.hasFlag(OPT_stdcall_fixup, OPT_stdcall_fixup_no, config->mingw);
2050config->warnStdcallFixup = !args.hasArg(OPT_stdcall_fixup);
2051config->allowDuplicateWeak =
2052args.hasFlag(OPT_lld_allow_duplicate_weak,
2053OPT_lld_allow_duplicate_weak_no, config->mingw);
2054
2055if (args.hasFlag(OPT_inferasanlibs, OPT_inferasanlibs_no, false))
2056warn("ignoring '/inferasanlibs', this flag is not supported");
2057
2058if (config->incremental && args.hasArg(OPT_profile)) {
2059warn("ignoring '/incremental' due to '/profile' specification");
2060config->incremental = false;
2061}
2062
2063if (config->incremental && args.hasArg(OPT_order)) {
2064warn("ignoring '/incremental' due to '/order' specification");
2065config->incremental = false;
2066}
2067
2068if (config->incremental && config->doGC) {
2069warn("ignoring '/incremental' because REF is enabled; use '/opt:noref' to "
2070"disable");
2071config->incremental = false;
2072}
2073
2074if (config->incremental && config->doICF != ICFLevel::None) {
2075warn("ignoring '/incremental' because ICF is enabled; use '/opt:noicf' to "
2076"disable");
2077config->incremental = false;
2078}
2079
2080if (errorCount())
2081return;
2082
2083std::set<sys::fs::UniqueID> wholeArchives;
2084for (auto *arg : args.filtered(OPT_wholearchive_file))
2085if (std::optional<StringRef> path = findFile(arg->getValue()))
2086if (std::optional<sys::fs::UniqueID> id = getUniqueID(*path))
2087wholeArchives.insert(*id);
2088
2089// A predicate returning true if a given path is an argument for
2090// /wholearchive:, or /wholearchive is enabled globally.
2091// This function is a bit tricky because "foo.obj /wholearchive:././foo.obj"
2092// needs to be handled as "/wholearchive:foo.obj foo.obj".
2093auto isWholeArchive = [&](StringRef path) -> bool {
2094if (args.hasArg(OPT_wholearchive_flag))
2095return true;
2096if (std::optional<sys::fs::UniqueID> id = getUniqueID(path))
2097return wholeArchives.count(*id);
2098return false;
2099};
2100
2101// Create a list of input files. These can be given as OPT_INPUT options
2102// and OPT_wholearchive_file options, and we also need to track OPT_start_lib
2103// and OPT_end_lib.
2104{
2105llvm::TimeTraceScope timeScope2("Parse & queue inputs");
2106bool inLib = false;
2107for (auto *arg : args) {
2108switch (arg->getOption().getID()) {
2109case OPT_end_lib:
2110if (!inLib)
2111error("stray " + arg->getSpelling());
2112inLib = false;
2113break;
2114case OPT_start_lib:
2115if (inLib)
2116error("nested " + arg->getSpelling());
2117inLib = true;
2118break;
2119case OPT_wholearchive_file:
2120if (std::optional<StringRef> path = findFileIfNew(arg->getValue()))
2121enqueuePath(*path, true, inLib);
2122break;
2123case OPT_INPUT:
2124if (std::optional<StringRef> path = findFileIfNew(arg->getValue()))
2125enqueuePath(*path, isWholeArchive(*path), inLib);
2126break;
2127default:
2128// Ignore other options.
2129break;
2130}
2131}
2132}
2133
2134// Read all input files given via the command line.
2135run();
2136if (errorCount())
2137return;
2138
2139// We should have inferred a machine type by now from the input files, but if
2140// not we assume x64.
2141if (config->machine == IMAGE_FILE_MACHINE_UNKNOWN) {
2142warn("/machine is not specified. x64 is assumed");
2143config->machine = AMD64;
2144addWinSysRootLibSearchPaths();
2145}
2146config->wordsize = config->is64() ? 8 : 4;
2147
2148if (config->printSearchPaths) {
2149SmallString<256> buffer;
2150raw_svector_ostream stream(buffer);
2151stream << "Library search paths:\n";
2152
2153for (StringRef path : searchPaths) {
2154if (path == "")
2155path = "(cwd)";
2156stream << " " << path << "\n";
2157}
2158
2159message(buffer);
2160}
2161
2162// Process files specified as /defaultlib. These must be processed after
2163// addWinSysRootLibSearchPaths(), which is why they are in a separate loop.
2164for (auto *arg : args.filtered(OPT_defaultlib))
2165if (std::optional<StringRef> path = findLibIfNew(arg->getValue()))
2166enqueuePath(*path, false, false);
2167run();
2168if (errorCount())
2169return;
2170
2171// Handle /RELEASE
2172if (args.hasArg(OPT_release))
2173config->writeCheckSum = true;
2174
2175// Handle /safeseh, x86 only, on by default, except for mingw.
2176if (config->machine == I386) {
2177config->safeSEH = args.hasFlag(OPT_safeseh, OPT_safeseh_no, !config->mingw);
2178config->noSEH = args.hasArg(OPT_noseh);
2179}
2180
2181// Handle /functionpadmin
2182for (auto *arg : args.filtered(OPT_functionpadmin, OPT_functionpadmin_opt))
2183parseFunctionPadMin(arg);
2184
2185// Handle /dependentloadflag
2186for (auto *arg :
2187args.filtered(OPT_dependentloadflag, OPT_dependentloadflag_opt))
2188parseDependentLoadFlags(arg);
2189
2190if (tar) {
2191llvm::TimeTraceScope timeScope("Reproducer: response file");
2192tar->append("response.txt",
2193createResponseFile(args, filePaths,
2194ArrayRef<StringRef>(searchPaths).slice(1)));
2195}
2196
2197// Handle /largeaddressaware
2198config->largeAddressAware = args.hasFlag(
2199OPT_largeaddressaware, OPT_largeaddressaware_no, config->is64());
2200
2201// Handle /highentropyva
2202config->highEntropyVA =
2203config->is64() &&
2204args.hasFlag(OPT_highentropyva, OPT_highentropyva_no, true);
2205
2206if (!config->dynamicBase &&
2207(config->machine == ARMNT || isAnyArm64(config->machine)))
2208error("/dynamicbase:no is not compatible with " +
2209machineToStr(config->machine));
2210
2211// Handle /export
2212{
2213llvm::TimeTraceScope timeScope("Parse /export");
2214for (auto *arg : args.filtered(OPT_export)) {
2215Export e = parseExport(arg->getValue());
2216if (config->machine == I386) {
2217if (!isDecorated(e.name))
2218e.name = saver().save("_" + e.name);
2219if (!e.extName.empty() && !isDecorated(e.extName))
2220e.extName = saver().save("_" + e.extName);
2221}
2222config->exports.push_back(e);
2223}
2224}
2225
2226// Handle /def
2227if (auto *arg = args.getLastArg(OPT_deffile)) {
2228// parseModuleDefs mutates Config object.
2229parseModuleDefs(arg->getValue());
2230}
2231
2232// Handle generation of import library from a def file.
2233if (!args.hasArg(OPT_INPUT, OPT_wholearchive_file)) {
2234fixupExports();
2235if (!config->noimplib)
2236createImportLibrary(/*asLib=*/true);
2237return;
2238}
2239
2240// Windows specific -- if no /subsystem is given, we need to infer
2241// that from entry point name. Must happen before /entry handling,
2242// and after the early return when just writing an import library.
2243if (config->subsystem == IMAGE_SUBSYSTEM_UNKNOWN) {
2244llvm::TimeTraceScope timeScope("Infer subsystem");
2245config->subsystem = inferSubsystem();
2246if (config->subsystem == IMAGE_SUBSYSTEM_UNKNOWN)
2247fatal("subsystem must be defined");
2248}
2249
2250// Handle /entry and /dll
2251{
2252llvm::TimeTraceScope timeScope("Entry point");
2253if (auto *arg = args.getLastArg(OPT_entry)) {
2254if (!arg->getValue()[0])
2255fatal("missing entry point symbol name");
2256config->entry = addUndefined(mangle(arg->getValue()));
2257} else if (!config->entry && !config->noEntry) {
2258if (args.hasArg(OPT_dll)) {
2259StringRef s = (config->machine == I386) ? "__DllMainCRTStartup@12"
2260: "_DllMainCRTStartup";
2261config->entry = addUndefined(s);
2262} else if (config->driverWdm) {
2263// /driver:wdm implies /entry:_NtProcessStartup
2264config->entry = addUndefined(mangle("_NtProcessStartup"));
2265} else {
2266// Windows specific -- If entry point name is not given, we need to
2267// infer that from user-defined entry name.
2268StringRef s = findDefaultEntry();
2269if (s.empty())
2270fatal("entry point must be defined");
2271config->entry = addUndefined(s);
2272log("Entry name inferred: " + s);
2273}
2274}
2275}
2276
2277// Handle /delayload
2278{
2279llvm::TimeTraceScope timeScope("Delay load");
2280for (auto *arg : args.filtered(OPT_delayload)) {
2281config->delayLoads.insert(StringRef(arg->getValue()).lower());
2282if (config->machine == I386) {
2283config->delayLoadHelper = addUndefined("___delayLoadHelper2@8");
2284} else {
2285config->delayLoadHelper = addUndefined("__delayLoadHelper2");
2286}
2287}
2288}
2289
2290// Set default image name if neither /out or /def set it.
2291if (config->outputFile.empty()) {
2292config->outputFile = getOutputPath(
2293(*args.filtered(OPT_INPUT, OPT_wholearchive_file).begin())->getValue(),
2294config->dll, config->driver);
2295}
2296
2297// Fail early if an output file is not writable.
2298if (auto e = tryCreateFile(config->outputFile)) {
2299error("cannot open output file " + config->outputFile + ": " + e.message());
2300return;
2301}
2302
2303config->lldmapFile = getMapFile(args, OPT_lldmap, OPT_lldmap_file);
2304config->mapFile = getMapFile(args, OPT_map, OPT_map_file);
2305
2306if (config->mapFile != "" && args.hasArg(OPT_map_info)) {
2307for (auto *arg : args.filtered(OPT_map_info)) {
2308std::string s = StringRef(arg->getValue()).lower();
2309if (s == "exports")
2310config->mapInfo = true;
2311else
2312error("unknown option: /mapinfo:" + s);
2313}
2314}
2315
2316if (config->lldmapFile != "" && config->lldmapFile == config->mapFile) {
2317warn("/lldmap and /map have the same output file '" + config->mapFile +
2318"'.\n>>> ignoring /lldmap");
2319config->lldmapFile.clear();
2320}
2321
2322// If should create PDB, use the hash of PDB content for build id. Otherwise,
2323// generate using the hash of executable content.
2324if (args.hasFlag(OPT_build_id, OPT_build_id_no, false))
2325config->buildIDHash = BuildIDHash::Binary;
2326
2327if (shouldCreatePDB) {
2328// Put the PDB next to the image if no /pdb flag was passed.
2329if (config->pdbPath.empty()) {
2330config->pdbPath = config->outputFile;
2331sys::path::replace_extension(config->pdbPath, ".pdb");
2332}
2333
2334// The embedded PDB path should be the absolute path to the PDB if no
2335// /pdbaltpath flag was passed.
2336if (config->pdbAltPath.empty()) {
2337config->pdbAltPath = config->pdbPath;
2338
2339// It's important to make the path absolute and remove dots. This path
2340// will eventually be written into the PE header, and certain Microsoft
2341// tools won't work correctly if these assumptions are not held.
2342sys::fs::make_absolute(config->pdbAltPath);
2343sys::path::remove_dots(config->pdbAltPath);
2344} else {
2345// Don't do this earlier, so that ctx.OutputFile is ready.
2346parsePDBAltPath();
2347}
2348config->buildIDHash = BuildIDHash::PDB;
2349}
2350
2351// Set default image base if /base is not given.
2352if (config->imageBase == uint64_t(-1))
2353config->imageBase = getDefaultImageBase();
2354
2355ctx.symtab.addSynthetic(mangle("__ImageBase"), nullptr);
2356if (config->machine == I386) {
2357ctx.symtab.addAbsolute("___safe_se_handler_table", 0);
2358ctx.symtab.addAbsolute("___safe_se_handler_count", 0);
2359}
2360
2361ctx.symtab.addAbsolute(mangle("__guard_fids_count"), 0);
2362ctx.symtab.addAbsolute(mangle("__guard_fids_table"), 0);
2363ctx.symtab.addAbsolute(mangle("__guard_flags"), 0);
2364ctx.symtab.addAbsolute(mangle("__guard_iat_count"), 0);
2365ctx.symtab.addAbsolute(mangle("__guard_iat_table"), 0);
2366ctx.symtab.addAbsolute(mangle("__guard_longjmp_count"), 0);
2367ctx.symtab.addAbsolute(mangle("__guard_longjmp_table"), 0);
2368// Needed for MSVC 2017 15.5 CRT.
2369ctx.symtab.addAbsolute(mangle("__enclave_config"), 0);
2370// Needed for MSVC 2019 16.8 CRT.
2371ctx.symtab.addAbsolute(mangle("__guard_eh_cont_count"), 0);
2372ctx.symtab.addAbsolute(mangle("__guard_eh_cont_table"), 0);
2373
2374if (isArm64EC(config->machine)) {
2375ctx.symtab.addAbsolute("__arm64x_extra_rfe_table", 0);
2376ctx.symtab.addAbsolute("__arm64x_extra_rfe_table_size", 0);
2377ctx.symtab.addAbsolute("__hybrid_code_map", 0);
2378ctx.symtab.addAbsolute("__hybrid_code_map_count", 0);
2379}
2380
2381if (config->pseudoRelocs) {
2382ctx.symtab.addAbsolute(mangle("__RUNTIME_PSEUDO_RELOC_LIST__"), 0);
2383ctx.symtab.addAbsolute(mangle("__RUNTIME_PSEUDO_RELOC_LIST_END__"), 0);
2384}
2385if (config->mingw) {
2386ctx.symtab.addAbsolute(mangle("__CTOR_LIST__"), 0);
2387ctx.symtab.addAbsolute(mangle("__DTOR_LIST__"), 0);
2388}
2389if (config->debug || config->buildIDHash != BuildIDHash::None)
2390if (ctx.symtab.findUnderscore("__buildid"))
2391ctx.symtab.addUndefined(mangle("__buildid"));
2392
2393// This code may add new undefined symbols to the link, which may enqueue more
2394// symbol resolution tasks, so we need to continue executing tasks until we
2395// converge.
2396{
2397llvm::TimeTraceScope timeScope("Add unresolved symbols");
2398do {
2399// Windows specific -- if entry point is not found,
2400// search for its mangled names.
2401if (config->entry)
2402mangleMaybe(config->entry);
2403
2404// Windows specific -- Make sure we resolve all dllexported symbols.
2405for (Export &e : config->exports) {
2406if (!e.forwardTo.empty())
2407continue;
2408e.sym = addUndefined(e.name);
2409if (e.source != ExportSource::Directives)
2410e.symbolName = mangleMaybe(e.sym);
2411}
2412
2413// Add weak aliases. Weak aliases is a mechanism to give remaining
2414// undefined symbols final chance to be resolved successfully.
2415for (auto pair : config->alternateNames) {
2416StringRef from = pair.first;
2417StringRef to = pair.second;
2418Symbol *sym = ctx.symtab.find(from);
2419if (!sym)
2420continue;
2421if (auto *u = dyn_cast<Undefined>(sym))
2422if (!u->weakAlias)
2423u->weakAlias = ctx.symtab.addUndefined(to);
2424}
2425
2426// If any inputs are bitcode files, the LTO code generator may create
2427// references to library functions that are not explicit in the bitcode
2428// file's symbol table. If any of those library functions are defined in a
2429// bitcode file in an archive member, we need to arrange to use LTO to
2430// compile those archive members by adding them to the link beforehand.
2431if (!ctx.bitcodeFileInstances.empty())
2432for (auto *s : lto::LTO::getRuntimeLibcallSymbols())
2433ctx.symtab.addLibcall(s);
2434
2435// Windows specific -- if __load_config_used can be resolved, resolve it.
2436if (ctx.symtab.findUnderscore("_load_config_used"))
2437addUndefined(mangle("_load_config_used"));
2438
2439if (args.hasArg(OPT_include_optional)) {
2440// Handle /includeoptional
2441for (auto *arg : args.filtered(OPT_include_optional))
2442if (isa_and_nonnull<LazyArchive>(ctx.symtab.find(arg->getValue())))
2443addUndefined(arg->getValue());
2444}
2445} while (run());
2446}
2447
2448// Create wrapped symbols for -wrap option.
2449std::vector<WrappedSymbol> wrapped = addWrappedSymbols(ctx, args);
2450// Load more object files that might be needed for wrapped symbols.
2451if (!wrapped.empty())
2452while (run())
2453;
2454
2455if (config->autoImport || config->stdcallFixup) {
2456// MinGW specific.
2457// Load any further object files that might be needed for doing automatic
2458// imports, and do stdcall fixups.
2459//
2460// For cases with no automatically imported symbols, this iterates once
2461// over the symbol table and doesn't do anything.
2462//
2463// For the normal case with a few automatically imported symbols, this
2464// should only need to be run once, since each new object file imported
2465// is an import library and wouldn't add any new undefined references,
2466// but there's nothing stopping the __imp_ symbols from coming from a
2467// normal object file as well (although that won't be used for the
2468// actual autoimport later on). If this pass adds new undefined references,
2469// we won't iterate further to resolve them.
2470//
2471// If stdcall fixups only are needed for loading import entries from
2472// a DLL without import library, this also just needs running once.
2473// If it ends up pulling in more object files from static libraries,
2474// (and maybe doing more stdcall fixups along the way), this would need
2475// to loop these two calls.
2476ctx.symtab.loadMinGWSymbols();
2477run();
2478}
2479
2480// At this point, we should not have any symbols that cannot be resolved.
2481// If we are going to do codegen for link-time optimization, check for
2482// unresolvable symbols first, so we don't spend time generating code that
2483// will fail to link anyway.
2484if (!ctx.bitcodeFileInstances.empty() && !config->forceUnresolved)
2485ctx.symtab.reportUnresolvable();
2486if (errorCount())
2487return;
2488
2489config->hadExplicitExports = !config->exports.empty();
2490if (config->mingw) {
2491// In MinGW, all symbols are automatically exported if no symbols
2492// are chosen to be exported.
2493maybeExportMinGWSymbols(args);
2494}
2495
2496// Do LTO by compiling bitcode input files to a set of native COFF files then
2497// link those files (unless -thinlto-index-only was given, in which case we
2498// resolve symbols and write indices, but don't generate native code or link).
2499ctx.symtab.compileBitcodeFiles();
2500
2501if (Defined *d =
2502dyn_cast_or_null<Defined>(ctx.symtab.findUnderscore("_tls_used")))
2503config->gcroot.push_back(d);
2504
2505// If -thinlto-index-only is given, we should create only "index
2506// files" and not object files. Index file creation is already done
2507// in addCombinedLTOObject, so we are done if that's the case.
2508// Likewise, don't emit object files for other /lldemit options.
2509if (config->emit != EmitKind::Obj || config->thinLTOIndexOnly)
2510return;
2511
2512// If we generated native object files from bitcode files, this resolves
2513// references to the symbols we use from them.
2514run();
2515
2516// Apply symbol renames for -wrap.
2517if (!wrapped.empty())
2518wrapSymbols(ctx, wrapped);
2519
2520// Resolve remaining undefined symbols and warn about imported locals.
2521ctx.symtab.resolveRemainingUndefines();
2522if (errorCount())
2523return;
2524
2525if (config->mingw) {
2526// Make sure the crtend.o object is the last object file. This object
2527// file can contain terminating section chunks that need to be placed
2528// last. GNU ld processes files and static libraries explicitly in the
2529// order provided on the command line, while lld will pull in needed
2530// files from static libraries only after the last object file on the
2531// command line.
2532for (auto i = ctx.objFileInstances.begin(), e = ctx.objFileInstances.end();
2533i != e; i++) {
2534ObjFile *file = *i;
2535if (isCrtend(file->getName())) {
2536ctx.objFileInstances.erase(i);
2537ctx.objFileInstances.push_back(file);
2538break;
2539}
2540}
2541}
2542
2543// Windows specific -- when we are creating a .dll file, we also
2544// need to create a .lib file. In MinGW mode, we only do that when the
2545// -implib option is given explicitly, for compatibility with GNU ld.
2546if (!config->exports.empty() || config->dll) {
2547llvm::TimeTraceScope timeScope("Create .lib exports");
2548fixupExports();
2549if (!config->noimplib && (!config->mingw || !config->implib.empty()))
2550createImportLibrary(/*asLib=*/false);
2551assignExportOrdinals();
2552}
2553
2554// Handle /output-def (MinGW specific).
2555if (auto *arg = args.getLastArg(OPT_output_def))
2556writeDefFile(arg->getValue(), config->exports);
2557
2558// Set extra alignment for .comm symbols
2559for (auto pair : config->alignComm) {
2560StringRef name = pair.first;
2561uint32_t alignment = pair.second;
2562
2563Symbol *sym = ctx.symtab.find(name);
2564if (!sym) {
2565warn("/aligncomm symbol " + name + " not found");
2566continue;
2567}
2568
2569// If the symbol isn't common, it must have been replaced with a regular
2570// symbol, which will carry its own alignment.
2571auto *dc = dyn_cast<DefinedCommon>(sym);
2572if (!dc)
2573continue;
2574
2575CommonChunk *c = dc->getChunk();
2576c->setAlignment(std::max(c->getAlignment(), alignment));
2577}
2578
2579// Windows specific -- Create an embedded or side-by-side manifest.
2580// /manifestdependency: enables /manifest unless an explicit /manifest:no is
2581// also passed.
2582if (config->manifest == Configuration::Embed)
2583addBuffer(createManifestRes(), false, false);
2584else if (config->manifest == Configuration::SideBySide ||
2585(config->manifest == Configuration::Default &&
2586!config->manifestDependencies.empty()))
2587createSideBySideManifest();
2588
2589// Handle /order. We want to do this at this moment because we
2590// need a complete list of comdat sections to warn on nonexistent
2591// functions.
2592if (auto *arg = args.getLastArg(OPT_order)) {
2593if (args.hasArg(OPT_call_graph_ordering_file))
2594error("/order and /call-graph-order-file may not be used together");
2595parseOrderFile(arg->getValue());
2596config->callGraphProfileSort = false;
2597}
2598
2599// Handle /call-graph-ordering-file and /call-graph-profile-sort (default on).
2600if (config->callGraphProfileSort) {
2601llvm::TimeTraceScope timeScope("Call graph");
2602if (auto *arg = args.getLastArg(OPT_call_graph_ordering_file)) {
2603parseCallGraphFile(arg->getValue());
2604}
2605readCallGraphsFromObjectFiles(ctx);
2606}
2607
2608// Handle /print-symbol-order.
2609if (auto *arg = args.getLastArg(OPT_print_symbol_order))
2610config->printSymbolOrder = arg->getValue();
2611
2612ctx.symtab.initializeEntryThunks();
2613
2614// Identify unreferenced COMDAT sections.
2615if (config->doGC) {
2616if (config->mingw) {
2617// markLive doesn't traverse .eh_frame, but the personality function is
2618// only reached that way. The proper solution would be to parse and
2619// traverse the .eh_frame section, like the ELF linker does.
2620// For now, just manually try to retain the known possible personality
2621// functions. This doesn't bring in more object files, but only marks
2622// functions that already have been included to be retained.
2623for (const char *n : {"__gxx_personality_v0", "__gcc_personality_v0",
2624"rust_eh_personality"}) {
2625Defined *d = dyn_cast_or_null<Defined>(ctx.symtab.findUnderscore(n));
2626if (d && !d->isGCRoot) {
2627d->isGCRoot = true;
2628config->gcroot.push_back(d);
2629}
2630}
2631}
2632
2633markLive(ctx);
2634}
2635
2636// Needs to happen after the last call to addFile().
2637convertResources();
2638
2639// Identify identical COMDAT sections to merge them.
2640if (config->doICF != ICFLevel::None) {
2641findKeepUniqueSections(ctx);
2642doICF(ctx);
2643}
2644
2645// Write the result.
2646writeResult(ctx);
2647
2648// Stop early so we can print the results.
2649rootTimer.stop();
2650if (config->showTiming)
2651ctx.rootTimer.print();
2652
2653if (config->timeTraceEnabled) {
2654// Manually stop the topmost "COFF link" scope, since we're shutting down.
2655timeTraceProfilerEnd();
2656
2657checkError(timeTraceProfilerWrite(
2658args.getLastArgValue(OPT_time_trace_eq).str(), config->outputFile));
2659timeTraceProfilerCleanup();
2660}
2661}
2662
2663} // namespace lld::coff
2664