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