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