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