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