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