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