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