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