xref: /llvm-project-15.0.7/lld/COFF/Driver.cpp (revision ad38fbff)
1 //===- Driver.cpp ---------------------------------------------------------===//
2 //
3 //                             The LLVM Linker
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
10 #include "Driver.h"
11 #include "Config.h"
12 #include "Error.h"
13 #include "InputFiles.h"
14 #include "Memory.h"
15 #include "SymbolTable.h"
16 #include "Symbols.h"
17 #include "Writer.h"
18 #include "lld/Common/Driver.h"
19 #include "llvm/ADT/Optional.h"
20 #include "llvm/ADT/StringSwitch.h"
21 #include "llvm/BinaryFormat/Magic.h"
22 #include "llvm/Object/ArchiveWriter.h"
23 #include "llvm/Object/COFFImportFile.h"
24 #include "llvm/Object/COFFModuleDefinition.h"
25 #include "llvm/Option/Arg.h"
26 #include "llvm/Option/ArgList.h"
27 #include "llvm/Option/Option.h"
28 #include "llvm/Support/Debug.h"
29 #include "llvm/Support/Path.h"
30 #include "llvm/Support/Process.h"
31 #include "llvm/Support/TarWriter.h"
32 #include "llvm/Support/TargetSelect.h"
33 #include "llvm/Support/raw_ostream.h"
34 #include "llvm/ToolDrivers/llvm-lib/LibDriver.h"
35 #include <algorithm>
36 #include <memory>
37 
38 #include <future>
39 
40 using namespace llvm;
41 using namespace llvm::object;
42 using namespace llvm::COFF;
43 using llvm::sys::Process;
44 
45 namespace lld {
46 namespace coff {
47 
48 Configuration *Config;
49 LinkerDriver *Driver;
50 
51 BumpPtrAllocator BAlloc;
52 StringSaver Saver{BAlloc};
53 std::vector<SpecificAllocBase *> SpecificAllocBase::Instances;
54 
55 bool link(ArrayRef<const char *> Args, raw_ostream &Diag) {
56   ErrorCount = 0;
57   ErrorOS = &Diag;
58 
59   Config = make<Configuration>();
60   Config->Argv = {Args.begin(), Args.end()};
61   Config->ColorDiagnostics = ErrorOS->has_colors();
62 
63   Symtab = make<SymbolTable>();
64 
65   Driver = make<LinkerDriver>();
66   Driver->link(Args);
67   return !ErrorCount;
68 }
69 
70 // Drop directory components and replace extension with ".exe" or ".dll".
71 static std::string getOutputPath(StringRef Path) {
72   auto P = Path.find_last_of("\\/");
73   StringRef S = (P == StringRef::npos) ? Path : Path.substr(P + 1);
74   const char* E = Config->DLL ? ".dll" : ".exe";
75   return (S.substr(0, S.rfind('.')) + E).str();
76 }
77 
78 // ErrorOr is not default constructible, so it cannot be used as the type
79 // parameter of a future.
80 // FIXME: We could open the file in createFutureForFile and avoid needing to
81 // return an error here, but for the moment that would cost us a file descriptor
82 // (a limited resource on Windows) for the duration that the future is pending.
83 typedef std::pair<std::unique_ptr<MemoryBuffer>, std::error_code> MBErrPair;
84 
85 // Create a std::future that opens and maps a file using the best strategy for
86 // the host platform.
87 static std::future<MBErrPair> createFutureForFile(std::string Path) {
88 #if LLVM_ON_WIN32
89   // On Windows, file I/O is relatively slow so it is best to do this
90   // asynchronously.
91   auto Strategy = std::launch::async;
92 #else
93   auto Strategy = std::launch::deferred;
94 #endif
95   return std::async(Strategy, [=]() {
96     auto MBOrErr = MemoryBuffer::getFile(Path);
97     if (!MBOrErr)
98       return MBErrPair{nullptr, MBOrErr.getError()};
99     return MBErrPair{std::move(*MBOrErr), std::error_code()};
100   });
101 }
102 
103 MemoryBufferRef LinkerDriver::takeBuffer(std::unique_ptr<MemoryBuffer> MB) {
104   MemoryBufferRef MBRef = *MB;
105   make<std::unique_ptr<MemoryBuffer>>(std::move(MB)); // take ownership
106 
107   if (Driver->Tar)
108     Driver->Tar->append(relativeToRoot(MBRef.getBufferIdentifier()),
109                         MBRef.getBuffer());
110   return MBRef;
111 }
112 
113 void LinkerDriver::addBuffer(std::unique_ptr<MemoryBuffer> MB,
114                              bool WholeArchive) {
115   MemoryBufferRef MBRef = takeBuffer(std::move(MB));
116 
117   // File type is detected by contents, not by file extension.
118   file_magic Magic = identify_magic(MBRef.getBuffer());
119   if (Magic == file_magic::windows_resource) {
120     Resources.push_back(MBRef);
121     return;
122   }
123 
124   FilePaths.push_back(MBRef.getBufferIdentifier());
125   if (Magic == file_magic::archive) {
126     if (WholeArchive) {
127       std::unique_ptr<Archive> File =
128           check(Archive::create(MBRef),
129                 MBRef.getBufferIdentifier() + ": failed to parse archive");
130 
131       for (MemoryBufferRef M : getArchiveMembers(File.get()))
132         addArchiveBuffer(M, "<whole-archive>", MBRef.getBufferIdentifier());
133       return;
134     }
135     Symtab->addFile(make<ArchiveFile>(MBRef));
136     return;
137   }
138 
139   if (Magic == file_magic::bitcode) {
140     Symtab->addFile(make<BitcodeFile>(MBRef));
141     return;
142   }
143 
144   if (Magic == file_magic::coff_cl_gl_object)
145     error(MBRef.getBufferIdentifier() + ": is not a native COFF file. "
146           "Recompile without /GL");
147   else
148     Symtab->addFile(make<ObjFile>(MBRef));
149 }
150 
151 void LinkerDriver::enqueuePath(StringRef Path, bool WholeArchive) {
152   auto Future =
153       std::make_shared<std::future<MBErrPair>>(createFutureForFile(Path));
154   std::string PathStr = Path;
155   enqueueTask([=]() {
156     auto MBOrErr = Future->get();
157     if (MBOrErr.second)
158       error("could not open " + PathStr + ": " + MBOrErr.second.message());
159     else
160       Driver->addBuffer(std::move(MBOrErr.first), WholeArchive);
161   });
162 }
163 
164 void LinkerDriver::addArchiveBuffer(MemoryBufferRef MB, StringRef SymName,
165                                     StringRef ParentName) {
166   file_magic Magic = identify_magic(MB.getBuffer());
167   if (Magic == file_magic::coff_import_library) {
168     Symtab->addFile(make<ImportFile>(MB));
169     return;
170   }
171 
172   InputFile *Obj;
173   if (Magic == file_magic::coff_object) {
174     Obj = make<ObjFile>(MB);
175   } else if (Magic == file_magic::bitcode) {
176     Obj = make<BitcodeFile>(MB);
177   } else {
178     error("unknown file type: " + MB.getBufferIdentifier());
179     return;
180   }
181 
182   Obj->ParentName = ParentName;
183   Symtab->addFile(Obj);
184   log("Loaded " + toString(Obj) + " for " + SymName);
185 }
186 
187 void LinkerDriver::enqueueArchiveMember(const Archive::Child &C,
188                                         StringRef SymName,
189                                         StringRef ParentName) {
190   if (!C.getParent()->isThin()) {
191     MemoryBufferRef MB = check(
192         C.getMemoryBufferRef(),
193         "could not get the buffer for the member defining symbol " + SymName);
194     enqueueTask([=]() { Driver->addArchiveBuffer(MB, SymName, ParentName); });
195     return;
196   }
197 
198   auto Future = std::make_shared<std::future<MBErrPair>>(createFutureForFile(
199       check(C.getFullName(),
200             "could not get the filename for the member defining symbol " +
201                 SymName)));
202   enqueueTask([=]() {
203     auto MBOrErr = Future->get();
204     if (MBOrErr.second)
205       fatal(MBOrErr.second,
206             "could not get the buffer for the member defining " + SymName);
207     Driver->addArchiveBuffer(takeBuffer(std::move(MBOrErr.first)), SymName,
208                              ParentName);
209   });
210 }
211 
212 static bool isDecorated(StringRef Sym) {
213   return Sym.startswith("_") || Sym.startswith("@") || Sym.startswith("?");
214 }
215 
216 // Parses .drectve section contents and returns a list of files
217 // specified by /defaultlib.
218 void LinkerDriver::parseDirectives(StringRef S) {
219   ArgParser Parser;
220   // .drectve is always tokenized using Windows shell rules.
221   opt::InputArgList Args = Parser.parse(S);
222 
223   for (auto *Arg : Args) {
224     switch (Arg->getOption().getUnaliasedOption().getID()) {
225     case OPT_aligncomm:
226       parseAligncomm(Arg->getValue());
227       break;
228     case OPT_alternatename:
229       parseAlternateName(Arg->getValue());
230       break;
231     case OPT_defaultlib:
232       if (Optional<StringRef> Path = findLib(Arg->getValue()))
233         enqueuePath(*Path, false);
234       break;
235     case OPT_export: {
236       Export E = parseExport(Arg->getValue());
237       if (Config->Machine == I386 && Config->MinGW) {
238         if (!isDecorated(E.Name))
239           E.Name = Saver.save("_" + E.Name);
240         if (!E.ExtName.empty() && !isDecorated(E.ExtName))
241           E.ExtName = Saver.save("_" + E.ExtName);
242       }
243       E.Directives = true;
244       Config->Exports.push_back(E);
245       break;
246     }
247     case OPT_failifmismatch:
248       checkFailIfMismatch(Arg->getValue());
249       break;
250     case OPT_incl:
251       addUndefined(Arg->getValue());
252       break;
253     case OPT_merge:
254       parseMerge(Arg->getValue());
255       break;
256     case OPT_nodefaultlib:
257       Config->NoDefaultLibs.insert(doFindLib(Arg->getValue()));
258       break;
259     case OPT_section:
260       parseSection(Arg->getValue());
261       break;
262     case OPT_editandcontinue:
263     case OPT_fastfail:
264     case OPT_guardsym:
265     case OPT_natvis:
266     case OPT_throwingnew:
267       break;
268     default:
269       error(Arg->getSpelling() + " is not allowed in .drectve");
270     }
271   }
272 }
273 
274 // Find file from search paths. You can omit ".obj", this function takes
275 // care of that. Note that the returned path is not guaranteed to exist.
276 StringRef LinkerDriver::doFindFile(StringRef Filename) {
277   bool HasPathSep = (Filename.find_first_of("/\\") != StringRef::npos);
278   if (HasPathSep)
279     return Filename;
280   bool HasExt = Filename.contains('.');
281   for (StringRef Dir : SearchPaths) {
282     SmallString<128> Path = Dir;
283     sys::path::append(Path, Filename);
284     if (sys::fs::exists(Path.str()))
285       return Saver.save(Path.str());
286     if (!HasExt) {
287       Path.append(".obj");
288       if (sys::fs::exists(Path.str()))
289         return Saver.save(Path.str());
290     }
291   }
292   return Filename;
293 }
294 
295 // Resolves a file path. This never returns the same path
296 // (in that case, it returns None).
297 Optional<StringRef> LinkerDriver::findFile(StringRef Filename) {
298   StringRef Path = doFindFile(Filename);
299   bool Seen = !VisitedFiles.insert(Path.lower()).second;
300   if (Seen)
301     return None;
302   return Path;
303 }
304 
305 // Find library file from search path.
306 StringRef LinkerDriver::doFindLib(StringRef Filename) {
307   // Add ".lib" to Filename if that has no file extension.
308   bool HasExt = Filename.contains('.');
309   if (!HasExt)
310     Filename = Saver.save(Filename + ".lib");
311   return doFindFile(Filename);
312 }
313 
314 // Resolves a library path. /nodefaultlib options are taken into
315 // consideration. This never returns the same path (in that case,
316 // it returns None).
317 Optional<StringRef> LinkerDriver::findLib(StringRef Filename) {
318   if (Config->NoDefaultLibAll)
319     return None;
320   if (!VisitedLibs.insert(Filename.lower()).second)
321     return None;
322   StringRef Path = doFindLib(Filename);
323   if (Config->NoDefaultLibs.count(Path))
324     return None;
325   if (!VisitedFiles.insert(Path.lower()).second)
326     return None;
327   return Path;
328 }
329 
330 // Parses LIB environment which contains a list of search paths.
331 void LinkerDriver::addLibSearchPaths() {
332   Optional<std::string> EnvOpt = Process::GetEnv("LIB");
333   if (!EnvOpt.hasValue())
334     return;
335   StringRef Env = Saver.save(*EnvOpt);
336   while (!Env.empty()) {
337     StringRef Path;
338     std::tie(Path, Env) = Env.split(';');
339     SearchPaths.push_back(Path);
340   }
341 }
342 
343 SymbolBody *LinkerDriver::addUndefined(StringRef Name) {
344   SymbolBody *B = Symtab->addUndefined(Name);
345   Config->GCRoot.insert(B);
346   return B;
347 }
348 
349 // Symbol names are mangled by appending "_" prefix on x86.
350 StringRef LinkerDriver::mangle(StringRef Sym) {
351   assert(Config->Machine != IMAGE_FILE_MACHINE_UNKNOWN);
352   if (Config->Machine == I386)
353     return Saver.save("_" + Sym);
354   return Sym;
355 }
356 
357 // Windows specific -- find default entry point name.
358 StringRef LinkerDriver::findDefaultEntry() {
359   // User-defined main functions and their corresponding entry points.
360   static const char *Entries[][2] = {
361       {"main", "mainCRTStartup"},
362       {"wmain", "wmainCRTStartup"},
363       {"WinMain", "WinMainCRTStartup"},
364       {"wWinMain", "wWinMainCRTStartup"},
365   };
366   for (auto E : Entries) {
367     StringRef Entry = Symtab->findMangle(mangle(E[0]));
368     if (!Entry.empty() && !isa<Undefined>(Symtab->find(Entry)->body()))
369       return mangle(E[1]);
370   }
371   return "";
372 }
373 
374 WindowsSubsystem LinkerDriver::inferSubsystem() {
375   if (Config->DLL)
376     return IMAGE_SUBSYSTEM_WINDOWS_GUI;
377   if (Symtab->findUnderscore("main") || Symtab->findUnderscore("wmain"))
378     return IMAGE_SUBSYSTEM_WINDOWS_CUI;
379   if (Symtab->findUnderscore("WinMain") || Symtab->findUnderscore("wWinMain"))
380     return IMAGE_SUBSYSTEM_WINDOWS_GUI;
381   return IMAGE_SUBSYSTEM_UNKNOWN;
382 }
383 
384 static uint64_t getDefaultImageBase() {
385   if (Config->is64())
386     return Config->DLL ? 0x180000000 : 0x140000000;
387   return Config->DLL ? 0x10000000 : 0x400000;
388 }
389 
390 static std::string createResponseFile(const opt::InputArgList &Args,
391                                       ArrayRef<StringRef> FilePaths,
392                                       ArrayRef<StringRef> SearchPaths) {
393   SmallString<0> Data;
394   raw_svector_ostream OS(Data);
395 
396   for (auto *Arg : Args) {
397     switch (Arg->getOption().getID()) {
398     case OPT_linkrepro:
399     case OPT_INPUT:
400     case OPT_defaultlib:
401     case OPT_libpath:
402       break;
403     default:
404       OS << toString(Arg) << "\n";
405     }
406   }
407 
408   for (StringRef Path : SearchPaths) {
409     std::string RelPath = relativeToRoot(Path);
410     OS << "/libpath:" << quote(RelPath) << "\n";
411   }
412 
413   for (StringRef Path : FilePaths)
414     OS << quote(relativeToRoot(Path)) << "\n";
415 
416   return Data.str();
417 }
418 
419 static unsigned getDefaultDebugType(const opt::InputArgList &Args) {
420   unsigned DebugTypes = static_cast<unsigned>(DebugType::CV);
421   if (Args.hasArg(OPT_driver))
422     DebugTypes |= static_cast<unsigned>(DebugType::PData);
423   if (Args.hasArg(OPT_profile))
424     DebugTypes |= static_cast<unsigned>(DebugType::Fixup);
425   return DebugTypes;
426 }
427 
428 static unsigned parseDebugType(StringRef Arg) {
429   SmallVector<StringRef, 3> Types;
430   Arg.split(Types, ',', /*KeepEmpty=*/false);
431 
432   unsigned DebugTypes = static_cast<unsigned>(DebugType::None);
433   for (StringRef Type : Types)
434     DebugTypes |= StringSwitch<unsigned>(Type.lower())
435                       .Case("cv", static_cast<unsigned>(DebugType::CV))
436                       .Case("pdata", static_cast<unsigned>(DebugType::PData))
437                       .Case("fixup", static_cast<unsigned>(DebugType::Fixup))
438                       .Default(0);
439   return DebugTypes;
440 }
441 
442 static std::string getMapFile(const opt::InputArgList &Args) {
443   auto *Arg = Args.getLastArg(OPT_lldmap, OPT_lldmap_file);
444   if (!Arg)
445     return "";
446   if (Arg->getOption().getID() == OPT_lldmap_file)
447     return Arg->getValue();
448 
449   assert(Arg->getOption().getID() == OPT_lldmap);
450   StringRef OutFile = Config->OutputFile;
451   return (OutFile.substr(0, OutFile.rfind('.')) + ".map").str();
452 }
453 
454 static std::string getImplibPath() {
455   if (!Config->Implib.empty())
456     return Config->Implib;
457   SmallString<128> Out = StringRef(Config->OutputFile);
458   sys::path::replace_extension(Out, ".lib");
459   return Out.str();
460 }
461 
462 //
463 // The import name is caculated as the following:
464 //
465 //        | LIBRARY w/ ext |   LIBRARY w/o ext   | no LIBRARY
466 //   -----+----------------+---------------------+------------------
467 //   LINK | {value}        | {value}.{.dll/.exe} | {output name}
468 //    LIB | {value}        | {value}.dll         | {output name}.dll
469 //
470 static std::string getImportName(bool AsLib) {
471   SmallString<128> Out;
472 
473   if (Config->ImportName.empty()) {
474     Out.assign(sys::path::filename(Config->OutputFile));
475     if (AsLib)
476       sys::path::replace_extension(Out, ".dll");
477   } else {
478     Out.assign(Config->ImportName);
479     if (!sys::path::has_extension(Out))
480       sys::path::replace_extension(Out,
481                                    (Config->DLL || AsLib) ? ".dll" : ".exe");
482   }
483 
484   return Out.str();
485 }
486 
487 static void createImportLibrary(bool AsLib) {
488   std::vector<COFFShortExport> Exports;
489   for (Export &E1 : Config->Exports) {
490     COFFShortExport E2;
491     E2.Name = E1.Name;
492     E2.SymbolName = E1.SymbolName;
493     E2.ExtName = E1.ExtName;
494     E2.Ordinal = E1.Ordinal;
495     E2.Noname = E1.Noname;
496     E2.Data = E1.Data;
497     E2.Private = E1.Private;
498     E2.Constant = E1.Constant;
499     Exports.push_back(E2);
500   }
501 
502   auto E = writeImportLibrary(getImportName(AsLib), getImplibPath(), Exports,
503                               Config->Machine, false);
504   handleAllErrors(std::move(E),
505                   [&](ErrorInfoBase &EIB) { error(EIB.message()); });
506 }
507 
508 static void parseModuleDefs(StringRef Path) {
509   std::unique_ptr<MemoryBuffer> MB = check(
510     MemoryBuffer::getFile(Path, -1, false, true), "could not open " + Path);
511   COFFModuleDefinition M =
512       check(parseCOFFModuleDefinition(MB->getMemBufferRef(), Config->Machine));
513 
514   if (Config->OutputFile.empty())
515     Config->OutputFile = Saver.save(M.OutputFile);
516   Config->ImportName = Saver.save(M.ImportName);
517   if (M.ImageBase)
518     Config->ImageBase = M.ImageBase;
519   if (M.StackReserve)
520     Config->StackReserve = M.StackReserve;
521   if (M.StackCommit)
522     Config->StackCommit = M.StackCommit;
523   if (M.HeapReserve)
524     Config->HeapReserve = M.HeapReserve;
525   if (M.HeapCommit)
526     Config->HeapCommit = M.HeapCommit;
527   if (M.MajorImageVersion)
528     Config->MajorImageVersion = M.MajorImageVersion;
529   if (M.MinorImageVersion)
530     Config->MinorImageVersion = M.MinorImageVersion;
531   if (M.MajorOSVersion)
532     Config->MajorOSVersion = M.MajorOSVersion;
533   if (M.MinorOSVersion)
534     Config->MinorOSVersion = M.MinorOSVersion;
535 
536   for (COFFShortExport E1 : M.Exports) {
537     Export E2;
538     E2.Name = Saver.save(E1.Name);
539     if (E1.isWeak())
540       E2.ExtName = Saver.save(E1.ExtName);
541     E2.Ordinal = E1.Ordinal;
542     E2.Noname = E1.Noname;
543     E2.Data = E1.Data;
544     E2.Private = E1.Private;
545     E2.Constant = E1.Constant;
546     Config->Exports.push_back(E2);
547   }
548 }
549 
550 // Get a sorted list of symbols not to automatically export
551 // when exporting all global symbols for MinGW.
552 static StringSet<> getExportExcludeSymbols() {
553   if (Config->Machine == I386)
554     return {
555         "__NULL_IMPORT_DESCRIPTOR",
556         "__pei386_runtime_relocator",
557         "_do_pseudo_reloc",
558        "_impure_ptr",
559         "__impure_ptr",
560         "__fmode",
561         "_environ",
562         "___dso_handle",
563         // These are the MinGW names that differ from the standard
564         // ones (lacking an extra underscore).
565         "_DllMain@12",
566         "_DllEntryPoint@12",
567         "_DllMainCRTStartup@12",
568     };
569 
570   return {
571       "_NULL_IMPORT_DESCRIPTOR",
572       "_pei386_runtime_relocator",
573       "do_pseudo_reloc",
574       "impure_ptr",
575       "_impure_ptr",
576       "_fmode",
577       "environ",
578       "__dso_handle",
579       // These are the MinGW names that differ from the standard
580       // ones (lacking an extra underscore).
581       "DllMain",
582       "DllEntryPoint",
583       "DllMainCRTStartup",
584   };
585 }
586 
587 // This is MinGW specific.
588 static void writeDefFile(StringRef Name) {
589   std::error_code EC;
590   raw_fd_ostream OS(Name, EC, sys::fs::F_None);
591   if (EC)
592     fatal("cannot open " + Name + ": " + EC.message());
593 
594   OS << "EXPORTS\n";
595   for (Export &E : Config->Exports) {
596     OS << "    " << E.ExportName << " "
597        << "@" << E.Ordinal;
598     if (auto *Def = dyn_cast_or_null<Defined>(E.Sym)) {
599       if (Def && Def->getChunk() &&
600           !(Def->getChunk()->getPermissions() & IMAGE_SCN_MEM_EXECUTE))
601         OS << " DATA";
602     }
603     OS << "\n";
604   }
605 }
606 
607 // A helper function for filterBitcodeFiles.
608 static bool needsRebuilding(MemoryBufferRef MB) {
609   // The MSVC linker doesn't support thin archives, so if it's a thin
610   // archive, we always need to rebuild it.
611   std::unique_ptr<Archive> File =
612       check(Archive::create(MB), "Failed to read " + MB.getBufferIdentifier());
613   if (File->isThin())
614     return true;
615 
616   // Returns true if the archive contains at least one bitcode file.
617   for (MemoryBufferRef Member : getArchiveMembers(File.get()))
618     if (identify_magic(Member.getBuffer()) == file_magic::bitcode)
619       return true;
620   return false;
621 }
622 
623 // Opens a given path as an archive file and removes bitcode files
624 // from them if exists. This function is to appease the MSVC linker as
625 // their linker doesn't like archive files containing non-native
626 // object files.
627 //
628 // If a given archive doesn't contain bitcode files, the archive path
629 // is returned as-is. Otherwise, a new temporary file is created and
630 // its path is returned.
631 static Optional<std::string>
632 filterBitcodeFiles(StringRef Path, std::vector<std::string> &TemporaryFiles) {
633   std::unique_ptr<MemoryBuffer> MB = check(
634       MemoryBuffer::getFile(Path, -1, false, true), "could not open " + Path);
635   MemoryBufferRef MBRef = MB->getMemBufferRef();
636   file_magic Magic = identify_magic(MBRef.getBuffer());
637 
638   if (Magic == file_magic::bitcode)
639     return None;
640   if (Magic != file_magic::archive)
641     return Path.str();
642   if (!needsRebuilding(MBRef))
643     return Path.str();
644 
645   std::unique_ptr<Archive> File =
646       check(Archive::create(MBRef),
647             MBRef.getBufferIdentifier() + ": failed to parse archive");
648 
649   std::vector<NewArchiveMember> New;
650   for (MemoryBufferRef Member : getArchiveMembers(File.get()))
651     if (identify_magic(Member.getBuffer()) != file_magic::bitcode)
652       New.emplace_back(Member);
653 
654   if (New.empty())
655     return None;
656 
657   log("Creating a temporary archive for " + Path + " to remove bitcode files");
658 
659   SmallString<128> S;
660   if (auto EC = sys::fs::createTemporaryFile("lld-" + sys::path::stem(Path),
661                                              ".lib", S))
662     fatal(EC, "cannot create a temporary file");
663   std::string Temp = S.str();
664   TemporaryFiles.push_back(Temp);
665 
666   Error E =
667       llvm::writeArchive(Temp, New, /*WriteSymtab=*/true, Archive::Kind::K_GNU,
668                          /*Deterministics=*/true,
669                          /*Thin=*/false);
670   handleAllErrors(std::move(E), [&](const ErrorInfoBase &EI) {
671     error("failed to create a new archive " + S.str() + ": " + EI.message());
672   });
673   return Temp;
674 }
675 
676 // Create response file contents and invoke the MSVC linker.
677 void LinkerDriver::invokeMSVC(opt::InputArgList &Args) {
678   std::string Rsp = "/nologo\n";
679   std::vector<std::string> Temps;
680 
681   // Write out archive members that we used in symbol resolution and pass these
682   // to MSVC before any archives, so that MSVC uses the same objects to satisfy
683   // references.
684   for (ObjFile *Obj : ObjFile::Instances) {
685     if (Obj->ParentName.empty())
686       continue;
687     SmallString<128> S;
688     int Fd;
689     if (auto EC = sys::fs::createTemporaryFile(
690             "lld-" + sys::path::filename(Obj->ParentName), ".obj", Fd, S))
691       fatal(EC, "cannot create a temporary file");
692     raw_fd_ostream OS(Fd, /*shouldClose*/ true);
693     OS << Obj->MB.getBuffer();
694     Temps.push_back(S.str());
695     Rsp += quote(S) + "\n";
696   }
697 
698   for (auto *Arg : Args) {
699     switch (Arg->getOption().getID()) {
700     case OPT_linkrepro:
701     case OPT_lldmap:
702     case OPT_lldmap_file:
703     case OPT_lldsavetemps:
704     case OPT_msvclto:
705       // LLD-specific options are stripped.
706       break;
707     case OPT_opt:
708       if (!StringRef(Arg->getValue()).startswith("lld"))
709         Rsp += toString(Arg) + " ";
710       break;
711     case OPT_INPUT: {
712       if (Optional<StringRef> Path = doFindFile(Arg->getValue())) {
713         if (Optional<std::string> S = filterBitcodeFiles(*Path, Temps))
714           Rsp += quote(*S) + "\n";
715         continue;
716       }
717       Rsp += quote(Arg->getValue()) + "\n";
718       break;
719     }
720     default:
721       Rsp += toString(Arg) + "\n";
722     }
723   }
724 
725   std::vector<StringRef> ObjFiles = Symtab->compileBitcodeFiles();
726   runMSVCLinker(Rsp, ObjFiles);
727 
728   for (StringRef Path : Temps)
729     sys::fs::remove(Path);
730 }
731 
732 void LinkerDriver::enqueueTask(std::function<void()> Task) {
733   TaskQueue.push_back(std::move(Task));
734 }
735 
736 bool LinkerDriver::run() {
737   bool DidWork = !TaskQueue.empty();
738   while (!TaskQueue.empty()) {
739     TaskQueue.front()();
740     TaskQueue.pop_front();
741   }
742   return DidWork;
743 }
744 
745 void LinkerDriver::link(ArrayRef<const char *> ArgsArr) {
746   // If the first command line argument is "/lib", link.exe acts like lib.exe.
747   // We call our own implementation of lib.exe that understands bitcode files.
748   if (ArgsArr.size() > 1 && StringRef(ArgsArr[1]).equals_lower("/lib")) {
749     if (llvm::libDriverMain(ArgsArr.slice(1)) != 0)
750       fatal("lib failed");
751     return;
752   }
753 
754   // Needed for LTO.
755   InitializeAllTargetInfos();
756   InitializeAllTargets();
757   InitializeAllTargetMCs();
758   InitializeAllAsmParsers();
759   InitializeAllAsmPrinters();
760   InitializeAllDisassemblers();
761 
762   // Parse command line options.
763   ArgParser Parser;
764   opt::InputArgList Args = Parser.parseLINK(ArgsArr.slice(1));
765 
766   // Parse and evaluate -mllvm options.
767   std::vector<const char *> V;
768   V.push_back("lld-link (LLVM option parsing)");
769   for (auto *Arg : Args.filtered(OPT_mllvm))
770     V.push_back(Arg->getValue());
771   cl::ParseCommandLineOptions(V.size(), V.data());
772 
773   // Handle /errorlimit early, because error() depends on it.
774   if (auto *Arg = Args.getLastArg(OPT_errorlimit)) {
775     int N = 20;
776     StringRef S = Arg->getValue();
777     if (S.getAsInteger(10, N))
778       error(Arg->getSpelling() + " number expected, but got " + S);
779     Config->ErrorLimit = N;
780   }
781 
782   // Handle /help
783   if (Args.hasArg(OPT_help)) {
784     printHelp(ArgsArr[0]);
785     return;
786   }
787 
788   // Handle /lldmingw early, since it can potentially affect how other
789   // options are handled.
790   Config->MinGW = Args.hasArg(OPT_lldmingw);
791 
792   if (auto *Arg = Args.getLastArg(OPT_linkrepro)) {
793     SmallString<64> Path = StringRef(Arg->getValue());
794     sys::path::append(Path, "repro.tar");
795 
796     Expected<std::unique_ptr<TarWriter>> ErrOrWriter =
797         TarWriter::create(Path, "repro");
798 
799     if (ErrOrWriter) {
800       Tar = std::move(*ErrOrWriter);
801     } else {
802       error("/linkrepro: failed to open " + Path + ": " +
803             toString(ErrOrWriter.takeError()));
804     }
805   }
806 
807   if (!Args.hasArg(OPT_INPUT)) {
808     if (Args.hasArg(OPT_deffile))
809       Config->NoEntry = true;
810     else
811       fatal("no input files");
812   }
813 
814   // Construct search path list.
815   SearchPaths.push_back("");
816   for (auto *Arg : Args.filtered(OPT_libpath))
817     SearchPaths.push_back(Arg->getValue());
818   addLibSearchPaths();
819 
820   // Handle /out
821   if (auto *Arg = Args.getLastArg(OPT_out))
822     Config->OutputFile = Arg->getValue();
823 
824   // Handle /verbose
825   if (Args.hasArg(OPT_verbose))
826     Config->Verbose = true;
827 
828   // Handle /force or /force:unresolved
829   if (Args.hasArg(OPT_force) || Args.hasArg(OPT_force_unresolved))
830     Config->Force = true;
831 
832   // Handle /debug
833   if (Args.hasArg(OPT_debug)) {
834     Config->Debug = true;
835     if (auto *Arg = Args.getLastArg(OPT_debugtype))
836       Config->DebugTypes = parseDebugType(Arg->getValue());
837     else
838       Config->DebugTypes = getDefaultDebugType(Args);
839   }
840 
841   // Create a dummy PDB file to satisfy build sytem rules.
842   if (auto *Arg = Args.getLastArg(OPT_pdb))
843     Config->PDBPath = Arg->getValue();
844 
845   // Handle /noentry
846   if (Args.hasArg(OPT_noentry)) {
847     if (Args.hasArg(OPT_dll))
848       Config->NoEntry = true;
849     else
850       error("/noentry must be specified with /dll");
851   }
852 
853   // Handle /dll
854   if (Args.hasArg(OPT_dll)) {
855     Config->DLL = true;
856     Config->ManifestID = 2;
857   }
858 
859   // Handle /fixed
860   if (Args.hasArg(OPT_fixed)) {
861     if (Args.hasArg(OPT_dynamicbase)) {
862       error("/fixed must not be specified with /dynamicbase");
863     } else {
864       Config->Relocatable = false;
865       Config->DynamicBase = false;
866     }
867   }
868 
869   if (Args.hasArg(OPT_appcontainer))
870     Config->AppContainer = true;
871 
872   // Handle /machine
873   if (auto *Arg = Args.getLastArg(OPT_machine))
874     Config->Machine = getMachineType(Arg->getValue());
875 
876   // Handle /nodefaultlib:<filename>
877   for (auto *Arg : Args.filtered(OPT_nodefaultlib))
878     Config->NoDefaultLibs.insert(doFindLib(Arg->getValue()));
879 
880   // Handle /nodefaultlib
881   if (Args.hasArg(OPT_nodefaultlib_all))
882     Config->NoDefaultLibAll = true;
883 
884   // Handle /base
885   if (auto *Arg = Args.getLastArg(OPT_base))
886     parseNumbers(Arg->getValue(), &Config->ImageBase);
887 
888   // Handle /stack
889   if (auto *Arg = Args.getLastArg(OPT_stack))
890     parseNumbers(Arg->getValue(), &Config->StackReserve, &Config->StackCommit);
891 
892   // Handle /heap
893   if (auto *Arg = Args.getLastArg(OPT_heap))
894     parseNumbers(Arg->getValue(), &Config->HeapReserve, &Config->HeapCommit);
895 
896   // Handle /version
897   if (auto *Arg = Args.getLastArg(OPT_version))
898     parseVersion(Arg->getValue(), &Config->MajorImageVersion,
899                  &Config->MinorImageVersion);
900 
901   // Handle /subsystem
902   if (auto *Arg = Args.getLastArg(OPT_subsystem))
903     parseSubsystem(Arg->getValue(), &Config->Subsystem, &Config->MajorOSVersion,
904                    &Config->MinorOSVersion);
905 
906   // Handle /alternatename
907   for (auto *Arg : Args.filtered(OPT_alternatename))
908     parseAlternateName(Arg->getValue());
909 
910   // Handle /include
911   for (auto *Arg : Args.filtered(OPT_incl))
912     addUndefined(Arg->getValue());
913 
914   // Handle /implib
915   if (auto *Arg = Args.getLastArg(OPT_implib))
916     Config->Implib = Arg->getValue();
917 
918   // Handle /opt
919   for (auto *Arg : Args.filtered(OPT_opt)) {
920     std::string Str = StringRef(Arg->getValue()).lower();
921     SmallVector<StringRef, 1> Vec;
922     StringRef(Str).split(Vec, ',');
923     for (StringRef S : Vec) {
924       if (S == "noref") {
925         Config->DoGC = false;
926         Config->DoICF = false;
927         continue;
928       }
929       if (S == "icf" || S.startswith("icf=")) {
930         Config->DoICF = true;
931         continue;
932       }
933       if (S == "noicf") {
934         Config->DoICF = false;
935         continue;
936       }
937       if (S.startswith("lldlto=")) {
938         StringRef OptLevel = S.substr(7);
939         if (OptLevel.getAsInteger(10, Config->LTOOptLevel) ||
940             Config->LTOOptLevel > 3)
941           error("/opt:lldlto: invalid optimization level: " + OptLevel);
942         continue;
943       }
944       if (S.startswith("lldltojobs=")) {
945         StringRef Jobs = S.substr(11);
946         if (Jobs.getAsInteger(10, Config->LTOJobs) || Config->LTOJobs == 0)
947           error("/opt:lldltojobs: invalid job count: " + Jobs);
948         continue;
949       }
950       if (S.startswith("lldltopartitions=")) {
951         StringRef N = S.substr(17);
952         if (N.getAsInteger(10, Config->LTOPartitions) ||
953             Config->LTOPartitions == 0)
954           error("/opt:lldltopartitions: invalid partition count: " + N);
955         continue;
956       }
957       if (S != "ref" && S != "lbr" && S != "nolbr")
958         error("/opt: unknown option: " + S);
959     }
960   }
961 
962   // Handle /lldsavetemps
963   if (Args.hasArg(OPT_lldsavetemps))
964     Config->SaveTemps = true;
965 
966   // Handle /lldltocache
967   if (auto *Arg = Args.getLastArg(OPT_lldltocache))
968     Config->LTOCache = Arg->getValue();
969 
970   // Handle /lldsavecachepolicy
971   if (auto *Arg = Args.getLastArg(OPT_lldltocachepolicy))
972     Config->LTOCachePolicy = check(
973         parseCachePruningPolicy(Arg->getValue()),
974         Twine("/lldltocachepolicy: invalid cache policy: ") + Arg->getValue());
975 
976   // Handle /failifmismatch
977   for (auto *Arg : Args.filtered(OPT_failifmismatch))
978     checkFailIfMismatch(Arg->getValue());
979 
980   // Handle /merge
981   for (auto *Arg : Args.filtered(OPT_merge))
982     parseMerge(Arg->getValue());
983 
984   // Handle /section
985   for (auto *Arg : Args.filtered(OPT_section))
986     parseSection(Arg->getValue());
987 
988   // Handle /aligncomm
989   for (auto *Arg : Args.filtered(OPT_aligncomm))
990     parseAligncomm(Arg->getValue());
991 
992   // Handle /manifestdependency. This enables /manifest unless /manifest:no is
993   // also passed.
994   if (auto *Arg = Args.getLastArg(OPT_manifestdependency)) {
995     Config->ManifestDependency = Arg->getValue();
996     Config->Manifest = Configuration::SideBySide;
997   }
998 
999   // Handle /manifest and /manifest:
1000   if (auto *Arg = Args.getLastArg(OPT_manifest, OPT_manifest_colon)) {
1001     if (Arg->getOption().getID() == OPT_manifest)
1002       Config->Manifest = Configuration::SideBySide;
1003     else
1004       parseManifest(Arg->getValue());
1005   }
1006 
1007   // Handle /manifestuac
1008   if (auto *Arg = Args.getLastArg(OPT_manifestuac))
1009     parseManifestUAC(Arg->getValue());
1010 
1011   // Handle /manifestfile
1012   if (auto *Arg = Args.getLastArg(OPT_manifestfile))
1013     Config->ManifestFile = Arg->getValue();
1014 
1015   // Handle /manifestinput
1016   for (auto *Arg : Args.filtered(OPT_manifestinput))
1017     Config->ManifestInput.push_back(Arg->getValue());
1018 
1019   if (!Config->ManifestInput.empty() &&
1020       Config->Manifest != Configuration::Embed) {
1021     fatal("/MANIFESTINPUT: requires /MANIFEST:EMBED");
1022   }
1023 
1024   // Handle miscellaneous boolean flags.
1025   if (Args.hasArg(OPT_allowbind_no))
1026     Config->AllowBind = false;
1027   if (Args.hasArg(OPT_allowisolation_no))
1028     Config->AllowIsolation = false;
1029   if (Args.hasArg(OPT_dynamicbase_no))
1030     Config->DynamicBase = false;
1031   if (Args.hasArg(OPT_nxcompat_no))
1032     Config->NxCompat = false;
1033   if (Args.hasArg(OPT_tsaware_no))
1034     Config->TerminalServerAware = false;
1035   if (Args.hasArg(OPT_nosymtab))
1036     Config->WriteSymtab = false;
1037 
1038   Config->MapFile = getMapFile(Args);
1039 
1040   if (ErrorCount)
1041     return;
1042 
1043   bool WholeArchiveFlag = Args.hasArg(OPT_wholearchive_flag);
1044   // Create a list of input files. Files can be given as arguments
1045   // for /defaultlib option.
1046   std::vector<MemoryBufferRef> MBs;
1047   for (auto *Arg : Args.filtered(OPT_INPUT, OPT_wholearchive_file)) {
1048     switch (Arg->getOption().getID()) {
1049     case OPT_INPUT:
1050       if (Optional<StringRef> Path = findFile(Arg->getValue()))
1051         enqueuePath(*Path, WholeArchiveFlag);
1052       break;
1053     case OPT_wholearchive_file:
1054       if (Optional<StringRef> Path = findFile(Arg->getValue()))
1055         enqueuePath(*Path, true);
1056       break;
1057     }
1058   }
1059   for (auto *Arg : Args.filtered(OPT_defaultlib))
1060     if (Optional<StringRef> Path = findLib(Arg->getValue()))
1061       enqueuePath(*Path, false);
1062 
1063   // Windows specific -- Create a resource file containing a manifest file.
1064   if (Config->Manifest == Configuration::Embed)
1065     addBuffer(createManifestRes(), false);
1066 
1067   // Read all input files given via the command line.
1068   run();
1069 
1070   // We should have inferred a machine type by now from the input files, but if
1071   // not we assume x64.
1072   if (Config->Machine == IMAGE_FILE_MACHINE_UNKNOWN) {
1073     warn("/machine is not specified. x64 is assumed");
1074     Config->Machine = AMD64;
1075   }
1076 
1077   // Input files can be Windows resource files (.res files). We use
1078   // WindowsResource to convert resource files to a regular COFF file,
1079   // then link the resulting file normally.
1080   if (!Resources.empty())
1081     addBuffer(convertResToCOFF(Resources), false);
1082 
1083   if (Tar)
1084     Tar->append("response.txt",
1085                 createResponseFile(Args, FilePaths,
1086                                    ArrayRef<StringRef>(SearchPaths).slice(1)));
1087 
1088   // Handle /largeaddressaware
1089   if (Config->is64() || Args.hasArg(OPT_largeaddressaware))
1090     Config->LargeAddressAware = true;
1091 
1092   // Handle /highentropyva
1093   if (Config->is64() && !Args.hasArg(OPT_highentropyva_no))
1094     Config->HighEntropyVA = true;
1095 
1096   // Handle /entry and /dll
1097   if (auto *Arg = Args.getLastArg(OPT_entry)) {
1098     Config->Entry = addUndefined(mangle(Arg->getValue()));
1099   } else if (Args.hasArg(OPT_dll) && !Config->NoEntry) {
1100     StringRef S = (Config->Machine == I386) ? "__DllMainCRTStartup@12"
1101                                             : "_DllMainCRTStartup";
1102     Config->Entry = addUndefined(S);
1103   } else if (!Config->NoEntry) {
1104     // Windows specific -- If entry point name is not given, we need to
1105     // infer that from user-defined entry name.
1106     StringRef S = findDefaultEntry();
1107     if (S.empty())
1108       fatal("entry point must be defined");
1109     Config->Entry = addUndefined(S);
1110     log("Entry name inferred: " + S);
1111   }
1112 
1113   // Handle /export
1114   for (auto *Arg : Args.filtered(OPT_export)) {
1115     Export E = parseExport(Arg->getValue());
1116     if (Config->Machine == I386) {
1117       if (!isDecorated(E.Name))
1118         E.Name = Saver.save("_" + E.Name);
1119       if (!E.ExtName.empty() && !isDecorated(E.ExtName))
1120         E.ExtName = Saver.save("_" + E.ExtName);
1121     }
1122     Config->Exports.push_back(E);
1123   }
1124 
1125   // Handle /def
1126   if (auto *Arg = Args.getLastArg(OPT_deffile)) {
1127     // parseModuleDefs mutates Config object.
1128     parseModuleDefs(Arg->getValue());
1129   }
1130 
1131   // Handle generation of import library from a def file.
1132   if (!Args.hasArg(OPT_INPUT)) {
1133     fixupExports();
1134     createImportLibrary(/*AsLib=*/true);
1135     exit(0);
1136   }
1137 
1138   // Handle /delayload
1139   for (auto *Arg : Args.filtered(OPT_delayload)) {
1140     Config->DelayLoads.insert(StringRef(Arg->getValue()).lower());
1141     if (Config->Machine == I386) {
1142       Config->DelayLoadHelper = addUndefined("___delayLoadHelper2@8");
1143     } else {
1144       Config->DelayLoadHelper = addUndefined("__delayLoadHelper2");
1145     }
1146   }
1147 
1148   // Set default image name if neither /out or /def set it.
1149   if (Config->OutputFile.empty()) {
1150     Config->OutputFile =
1151         getOutputPath((*Args.filtered(OPT_INPUT).begin())->getValue());
1152   }
1153 
1154   // Put the PDB next to the image if no /pdb flag was passed.
1155   if (Config->Debug && Config->PDBPath.empty()) {
1156     Config->PDBPath = Config->OutputFile;
1157     sys::path::replace_extension(Config->PDBPath, ".pdb");
1158   }
1159 
1160   // Disable PDB generation if the user requested it.
1161   if (Args.hasArg(OPT_nopdb))
1162     Config->PDBPath = "";
1163 
1164   // Set default image base if /base is not given.
1165   if (Config->ImageBase == uint64_t(-1))
1166     Config->ImageBase = getDefaultImageBase();
1167 
1168   Symtab->addSynthetic(mangle("__ImageBase"), nullptr);
1169   if (Config->Machine == I386) {
1170     Symtab->addAbsolute("___safe_se_handler_table", 0);
1171     Symtab->addAbsolute("___safe_se_handler_count", 0);
1172   }
1173 
1174   // We do not support /guard:cf (control flow protection) yet.
1175   // Define CFG symbols anyway so that we can link MSVC 2015 CRT.
1176   Symtab->addAbsolute(mangle("__guard_fids_count"), 0);
1177   Symtab->addAbsolute(mangle("__guard_fids_table"), 0);
1178   Symtab->addAbsolute(mangle("__guard_flags"), 0x100);
1179   Symtab->addAbsolute(mangle("__guard_iat_count"), 0);
1180   Symtab->addAbsolute(mangle("__guard_iat_table"), 0);
1181   Symtab->addAbsolute(mangle("__guard_longjmp_count"), 0);
1182   Symtab->addAbsolute(mangle("__guard_longjmp_table"), 0);
1183 
1184   // This code may add new undefined symbols to the link, which may enqueue more
1185   // symbol resolution tasks, so we need to continue executing tasks until we
1186   // converge.
1187   do {
1188     // Windows specific -- if entry point is not found,
1189     // search for its mangled names.
1190     if (Config->Entry)
1191       Symtab->mangleMaybe(Config->Entry);
1192 
1193     // Windows specific -- Make sure we resolve all dllexported symbols.
1194     for (Export &E : Config->Exports) {
1195       if (!E.ForwardTo.empty())
1196         continue;
1197       E.Sym = addUndefined(E.Name);
1198       if (!E.Directives)
1199         Symtab->mangleMaybe(E.Sym);
1200     }
1201 
1202     // Add weak aliases. Weak aliases is a mechanism to give remaining
1203     // undefined symbols final chance to be resolved successfully.
1204     for (auto Pair : Config->AlternateNames) {
1205       StringRef From = Pair.first;
1206       StringRef To = Pair.second;
1207       Symbol *Sym = Symtab->find(From);
1208       if (!Sym)
1209         continue;
1210       if (auto *U = dyn_cast<Undefined>(Sym->body()))
1211         if (!U->WeakAlias)
1212           U->WeakAlias = Symtab->addUndefined(To);
1213     }
1214 
1215     // Windows specific -- if __load_config_used can be resolved, resolve it.
1216     if (Symtab->findUnderscore("_load_config_used"))
1217       addUndefined(mangle("_load_config_used"));
1218   } while (run());
1219 
1220   if (ErrorCount)
1221     return;
1222 
1223   // If /msvclto is given, we use the MSVC linker to link LTO output files.
1224   // This is useful because MSVC link.exe can generate complete PDBs.
1225   if (Args.hasArg(OPT_msvclto)) {
1226     invokeMSVC(Args);
1227     exit(0);
1228   }
1229 
1230   // Do LTO by compiling bitcode input files to a set of native COFF files then
1231   // link those files.
1232   Symtab->addCombinedLTOObjects();
1233   run();
1234 
1235   // Make sure we have resolved all symbols.
1236   Symtab->reportRemainingUndefines();
1237   if (ErrorCount)
1238     return;
1239 
1240   // Windows specific -- if no /subsystem is given, we need to infer
1241   // that from entry point name.
1242   if (Config->Subsystem == IMAGE_SUBSYSTEM_UNKNOWN) {
1243     Config->Subsystem = inferSubsystem();
1244     if (Config->Subsystem == IMAGE_SUBSYSTEM_UNKNOWN)
1245       fatal("subsystem must be defined");
1246   }
1247 
1248   // Handle /safeseh.
1249   if (Args.hasArg(OPT_safeseh)) {
1250     for (ObjFile *File : ObjFile::Instances)
1251       if (!File->SEHCompat)
1252         error("/safeseh: " + File->getName() + " is not compatible with SEH");
1253     if (ErrorCount)
1254       return;
1255   }
1256 
1257   // In MinGW, all symbols are automatically exported if no symbols
1258   // are chosen to be exported.
1259   if (Config->DLL && ((Config->MinGW && Config->Exports.empty()) ||
1260                       Args.hasArg(OPT_export_all_symbols))) {
1261     StringSet<> ExcludeSymbols = getExportExcludeSymbols();
1262 
1263     Symtab->forEachSymbol([=](Symbol *S) {
1264       auto *Def = dyn_cast<Defined>(S->body());
1265       if (!Def || !Def->isLive() || !Def->getChunk())
1266         return;
1267       if (ExcludeSymbols.count(Def->getName()))
1268         return;
1269       Export E;
1270       E.Name = Def->getName();
1271       E.Sym = Def;
1272       Config->Exports.push_back(E);
1273     });
1274   }
1275 
1276   // Windows specific -- when we are creating a .dll file, we also
1277   // need to create a .lib file.
1278   if (!Config->Exports.empty() || Config->DLL) {
1279     fixupExports();
1280     createImportLibrary(/*AsLib=*/false);
1281     assignExportOrdinals();
1282   }
1283 
1284   // Handle /output-def (MinGW specific).
1285   if (auto *Arg = Args.getLastArg(OPT_output_def))
1286     writeDefFile(Arg->getValue());
1287 
1288   // Set extra alignment for .comm symbols
1289   for (auto Pair : Config->AlignComm) {
1290     StringRef Name = Pair.first;
1291     uint32_t Alignment = Pair.second;
1292 
1293     Symbol *Sym = Symtab->find(Name);
1294     if (!Sym) {
1295       warn("/aligncomm symbol " + Name + " not found");
1296       continue;
1297     }
1298 
1299     auto *DC = dyn_cast<DefinedCommon>(Sym->body());
1300     if (!DC) {
1301       warn("/aligncomm symbol " + Name + " of wrong kind");
1302       continue;
1303     }
1304 
1305     CommonChunk *C = DC->getChunk();
1306     C->Alignment = std::max(C->Alignment, Alignment);
1307   }
1308 
1309   // Windows specific -- Create a side-by-side manifest file.
1310   if (Config->Manifest == Configuration::SideBySide)
1311     createSideBySideManifest();
1312 
1313   // Identify unreferenced COMDAT sections.
1314   if (Config->DoGC)
1315     markLive(Symtab->getChunks());
1316 
1317   // Identify identical COMDAT sections to merge them.
1318   if (Config->DoICF)
1319     doICF(Symtab->getChunks());
1320 
1321   // Write the result.
1322   writeResult();
1323 
1324   if (ErrorCount)
1325     return;
1326 
1327   // Call exit to avoid calling destructors.
1328   exit(0);
1329 }
1330 
1331 } // namespace coff
1332 } // namespace lld
1333