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