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