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