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