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