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