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