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