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