xref: /llvm-project-15.0.7/lld/COFF/Driver.cpp (revision b7760210)
1 //===- Driver.cpp ---------------------------------------------------------===//
2 //
3 //                             The LLVM Linker
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
10 #include "Driver.h"
11 #include "Config.h"
12 #include "Error.h"
13 #include "InputFiles.h"
14 #include "Memory.h"
15 #include "SymbolTable.h"
16 #include "Symbols.h"
17 #include "Writer.h"
18 #include "lld/Driver/Driver.h"
19 #include "llvm/ADT/Optional.h"
20 #include "llvm/ADT/StringSwitch.h"
21 #include "llvm/LibDriver/LibDriver.h"
22 #include "llvm/Option/Arg.h"
23 #include "llvm/Option/ArgList.h"
24 #include "llvm/Option/Option.h"
25 #include "llvm/Support/Debug.h"
26 #include "llvm/Support/Path.h"
27 #include "llvm/Support/Process.h"
28 #include "llvm/Support/TarWriter.h"
29 #include "llvm/Support/TargetSelect.h"
30 #include "llvm/Support/raw_ostream.h"
31 #include <algorithm>
32 #include <memory>
33 
34 #ifdef _MSC_VER
35 // <future> depends on <eh.h> for __uncaught_exception.
36 #include <eh.h>
37 #endif
38 
39 #include <future>
40 
41 using namespace llvm;
42 using namespace llvm::COFF;
43 using llvm::sys::Process;
44 using llvm::sys::fs::file_magic;
45 using llvm::sys::fs::identify_magic;
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, raw_ostream &Diag) {
58   ErrorCount = 0;
59   ErrorOS = &Diag;
60   Argv0 = Args[0];
61   Config = make<Configuration>();
62   Config->ColorDiagnostics =
63       (ErrorOS == &llvm::errs() && Process::StandardErrHasColors());
64   Driver = make<LinkerDriver>();
65   Driver->link(Args);
66   return true;
67 }
68 
69 // Drop directory components and replace extension with ".exe" or ".dll".
70 static std::string getOutputPath(StringRef Path) {
71   auto P = Path.find_last_of("\\/");
72   StringRef S = (P == StringRef::npos) ? Path : Path.substr(P + 1);
73   const char* E = Config->DLL ? ".dll" : ".exe";
74   return (S.substr(0, S.rfind('.')) + E).str();
75 }
76 
77 // ErrorOr is not default constructible, so it cannot be used as the type
78 // parameter of a future.
79 // FIXME: We could open the file in createFutureForFile and avoid needing to
80 // return an error here, but for the moment that would cost us a file descriptor
81 // (a limited resource on Windows) for the duration that the future is pending.
82 typedef std::pair<std::unique_ptr<MemoryBuffer>, std::error_code> MBErrPair;
83 
84 // Create a std::future that opens and maps a file using the best strategy for
85 // the host platform.
86 static std::future<MBErrPair> createFutureForFile(std::string Path) {
87 #if LLVM_ON_WIN32
88   // On Windows, file I/O is relatively slow so it is best to do this
89   // asynchronously.
90   auto Strategy = std::launch::async;
91 #else
92   auto Strategy = std::launch::deferred;
93 #endif
94   return std::async(Strategy, [=]() {
95     auto MBOrErr = MemoryBuffer::getFile(Path);
96     if (!MBOrErr)
97       return MBErrPair{nullptr, MBOrErr.getError()};
98     return MBErrPair{std::move(*MBOrErr), std::error_code()};
99   });
100 }
101 
102 MemoryBufferRef LinkerDriver::takeBuffer(std::unique_ptr<MemoryBuffer> MB) {
103   MemoryBufferRef MBRef = *MB;
104   OwningMBs.push_back(std::move(MB));
105 
106   if (Driver->Tar)
107     Driver->Tar->append(relativeToRoot(MBRef.getBufferIdentifier()),
108                         MBRef.getBuffer());
109 
110   return MBRef;
111 }
112 
113 void LinkerDriver::addBuffer(std::unique_ptr<MemoryBuffer> MB) {
114   MemoryBufferRef MBRef = takeBuffer(std::move(MB));
115 
116   // File type is detected by contents, not by file extension.
117   file_magic Magic = identify_magic(MBRef.getBuffer());
118   if (Magic == file_magic::windows_resource) {
119     Resources.push_back(MBRef);
120     return;
121   }
122 
123   FilePaths.push_back(MBRef.getBufferIdentifier());
124   if (Magic == file_magic::archive)
125     return Symtab.addFile(make<ArchiveFile>(MBRef));
126   if (Magic == file_magic::bitcode)
127     return Symtab.addFile(make<BitcodeFile>(MBRef));
128   if (Magic == file_magic::coff_cl_gl_object)
129     fatal(MBRef.getBufferIdentifier() + ": is not a native COFF file. "
130           "Recompile without /GL");
131   Symtab.addFile(make<ObjectFile>(MBRef));
132 }
133 
134 void LinkerDriver::enqueuePath(StringRef Path) {
135   auto Future =
136       std::make_shared<std::future<MBErrPair>>(createFutureForFile(Path));
137   std::string PathStr = Path;
138   enqueueTask([=]() {
139     auto MBOrErr = Future->get();
140     if (MBOrErr.second)
141       fatal(MBOrErr.second, "could not open " + PathStr);
142     Driver->addBuffer(std::move(MBOrErr.first));
143   });
144 
145   if (Config->OutputFile == "")
146     Config->OutputFile = getOutputPath(Path);
147 }
148 
149 void LinkerDriver::addArchiveBuffer(MemoryBufferRef MB, StringRef SymName,
150                                     StringRef ParentName) {
151   file_magic Magic = identify_magic(MB.getBuffer());
152   if (Magic == file_magic::coff_import_library) {
153     Symtab.addFile(make<ImportFile>(MB));
154     return;
155   }
156 
157   InputFile *Obj;
158   if (Magic == file_magic::coff_object)
159     Obj = make<ObjectFile>(MB);
160   else if (Magic == file_magic::bitcode)
161     Obj = make<BitcodeFile>(MB);
162   else
163     fatal("unknown file type: " + MB.getBufferIdentifier());
164 
165   Obj->ParentName = ParentName;
166   Symtab.addFile(Obj);
167   log("Loaded " + toString(Obj) + " for " + SymName);
168 }
169 
170 void LinkerDriver::enqueueArchiveMember(const Archive::Child &C,
171                                         StringRef SymName,
172                                         StringRef ParentName) {
173   if (!C.getParent()->isThin()) {
174     MemoryBufferRef MB = check(
175         C.getMemoryBufferRef(),
176         "could not get the buffer for the member defining symbol " + SymName);
177     enqueueTask([=]() { Driver->addArchiveBuffer(MB, SymName, ParentName); });
178     return;
179   }
180 
181   auto Future = std::make_shared<std::future<MBErrPair>>(createFutureForFile(
182       check(C.getFullName(),
183             "could not get the filename for the member defining symbol " +
184                 SymName)));
185   enqueueTask([=]() {
186     auto MBOrErr = Future->get();
187     if (MBOrErr.second)
188       fatal(MBOrErr.second,
189             "could not get the buffer for the member defining " + SymName);
190     Driver->addArchiveBuffer(takeBuffer(std::move(MBOrErr.first)), SymName,
191                              ParentName);
192   });
193 }
194 
195 static bool isDecorated(StringRef Sym) {
196   return Sym.startswith("_") || Sym.startswith("@") || Sym.startswith("?");
197 }
198 
199 // Parses .drectve section contents and returns a list of files
200 // specified by /defaultlib.
201 void LinkerDriver::parseDirectives(StringRef S) {
202   opt::InputArgList Args = Parser.parse(S);
203 
204   for (auto *Arg : Args) {
205     switch (Arg->getOption().getID()) {
206     case OPT_alternatename:
207       parseAlternateName(Arg->getValue());
208       break;
209     case OPT_defaultlib:
210       if (Optional<StringRef> Path = findLib(Arg->getValue()))
211         enqueuePath(*Path);
212       break;
213     case OPT_export: {
214       Export E = parseExport(Arg->getValue());
215       E.Directives = true;
216       Config->Exports.push_back(E);
217       break;
218     }
219     case OPT_failifmismatch:
220       checkFailIfMismatch(Arg->getValue());
221       break;
222     case OPT_incl:
223       addUndefined(Arg->getValue());
224       break;
225     case OPT_merge:
226       parseMerge(Arg->getValue());
227       break;
228     case OPT_nodefaultlib:
229       Config->NoDefaultLibs.insert(doFindLib(Arg->getValue()));
230       break;
231     case OPT_section:
232       parseSection(Arg->getValue());
233       break;
234     case OPT_editandcontinue:
235     case OPT_fastfail:
236     case OPT_guardsym:
237     case OPT_throwingnew:
238       break;
239     default:
240       fatal(Arg->getSpelling() + " is not allowed in .drectve");
241     }
242   }
243 }
244 
245 // Find file from search paths. You can omit ".obj", this function takes
246 // care of that. Note that the returned path is not guaranteed to exist.
247 StringRef LinkerDriver::doFindFile(StringRef Filename) {
248   bool HasPathSep = (Filename.find_first_of("/\\") != StringRef::npos);
249   if (HasPathSep)
250     return Filename;
251   bool HasExt = (Filename.find('.') != StringRef::npos);
252   for (StringRef Dir : SearchPaths) {
253     SmallString<128> Path = Dir;
254     sys::path::append(Path, Filename);
255     if (sys::fs::exists(Path.str()))
256       return Saver.save(Path.str());
257     if (!HasExt) {
258       Path.append(".obj");
259       if (sys::fs::exists(Path.str()))
260         return Saver.save(Path.str());
261     }
262   }
263   return Filename;
264 }
265 
266 // Resolves a file path. This never returns the same path
267 // (in that case, it returns None).
268 Optional<StringRef> LinkerDriver::findFile(StringRef Filename) {
269   StringRef Path = doFindFile(Filename);
270   bool Seen = !VisitedFiles.insert(Path.lower()).second;
271   if (Seen)
272     return None;
273   return Path;
274 }
275 
276 // Find library file from search path.
277 StringRef LinkerDriver::doFindLib(StringRef Filename) {
278   // Add ".lib" to Filename if that has no file extension.
279   bool HasExt = (Filename.find('.') != StringRef::npos);
280   if (!HasExt)
281     Filename = Saver.save(Filename + ".lib");
282   return doFindFile(Filename);
283 }
284 
285 // Resolves a library path. /nodefaultlib options are taken into
286 // consideration. This never returns the same path (in that case,
287 // it returns None).
288 Optional<StringRef> LinkerDriver::findLib(StringRef Filename) {
289   if (Config->NoDefaultLibAll)
290     return None;
291   if (!VisitedLibs.insert(Filename.lower()).second)
292     return None;
293   StringRef Path = doFindLib(Filename);
294   if (Config->NoDefaultLibs.count(Path))
295     return None;
296   if (!VisitedFiles.insert(Path.lower()).second)
297     return None;
298   return Path;
299 }
300 
301 // Parses LIB environment which contains a list of search paths.
302 void LinkerDriver::addLibSearchPaths() {
303   Optional<std::string> EnvOpt = Process::GetEnv("LIB");
304   if (!EnvOpt.hasValue())
305     return;
306   StringRef Env = Saver.save(*EnvOpt);
307   while (!Env.empty()) {
308     StringRef Path;
309     std::tie(Path, Env) = Env.split(';');
310     SearchPaths.push_back(Path);
311   }
312 }
313 
314 SymbolBody *LinkerDriver::addUndefined(StringRef Name) {
315   SymbolBody *B = Symtab.addUndefined(Name);
316   Config->GCRoot.insert(B);
317   return B;
318 }
319 
320 // Symbol names are mangled by appending "_" prefix on x86.
321 StringRef LinkerDriver::mangle(StringRef Sym) {
322   assert(Config->Machine != IMAGE_FILE_MACHINE_UNKNOWN);
323   if (Config->Machine == I386)
324     return Saver.save("_" + Sym);
325   return Sym;
326 }
327 
328 // Windows specific -- find default entry point name.
329 StringRef LinkerDriver::findDefaultEntry() {
330   // User-defined main functions and their corresponding entry points.
331   static const char *Entries[][2] = {
332       {"main", "mainCRTStartup"},
333       {"wmain", "wmainCRTStartup"},
334       {"WinMain", "WinMainCRTStartup"},
335       {"wWinMain", "wWinMainCRTStartup"},
336   };
337   for (auto E : Entries) {
338     StringRef Entry = Symtab.findMangle(mangle(E[0]));
339     if (!Entry.empty() && !isa<Undefined>(Symtab.find(Entry)->body()))
340       return mangle(E[1]);
341   }
342   return "";
343 }
344 
345 WindowsSubsystem LinkerDriver::inferSubsystem() {
346   if (Config->DLL)
347     return IMAGE_SUBSYSTEM_WINDOWS_GUI;
348   if (Symtab.findUnderscore("main") || Symtab.findUnderscore("wmain"))
349     return IMAGE_SUBSYSTEM_WINDOWS_CUI;
350   if (Symtab.findUnderscore("WinMain") || Symtab.findUnderscore("wWinMain"))
351     return IMAGE_SUBSYSTEM_WINDOWS_GUI;
352   return IMAGE_SUBSYSTEM_UNKNOWN;
353 }
354 
355 static uint64_t getDefaultImageBase() {
356   if (Config->is64())
357     return Config->DLL ? 0x180000000 : 0x140000000;
358   return Config->DLL ? 0x10000000 : 0x400000;
359 }
360 
361 static std::string createResponseFile(const opt::InputArgList &Args,
362                                       ArrayRef<StringRef> FilePaths,
363                                       ArrayRef<StringRef> SearchPaths) {
364   SmallString<0> Data;
365   raw_svector_ostream OS(Data);
366 
367   for (auto *Arg : Args) {
368     switch (Arg->getOption().getID()) {
369     case OPT_linkrepro:
370     case OPT_INPUT:
371     case OPT_defaultlib:
372     case OPT_libpath:
373       break;
374     default:
375       OS << toString(Arg) << "\n";
376     }
377   }
378 
379   for (StringRef Path : SearchPaths) {
380     std::string RelPath = relativeToRoot(Path);
381     OS << "/libpath:" << quote(RelPath) << "\n";
382   }
383 
384   for (StringRef Path : FilePaths)
385     OS << quote(relativeToRoot(Path)) << "\n";
386 
387   return Data.str();
388 }
389 
390 static unsigned getDefaultDebugType(const opt::InputArgList &Args) {
391   unsigned DebugTypes = static_cast<unsigned>(DebugType::CV);
392   if (Args.hasArg(OPT_driver))
393     DebugTypes |= static_cast<unsigned>(DebugType::PData);
394   if (Args.hasArg(OPT_profile))
395     DebugTypes |= static_cast<unsigned>(DebugType::Fixup);
396   return DebugTypes;
397 }
398 
399 static unsigned parseDebugType(StringRef Arg) {
400   SmallVector<StringRef, 3> Types;
401   Arg.split(Types, ',', /*KeepEmpty=*/false);
402 
403   unsigned DebugTypes = static_cast<unsigned>(DebugType::None);
404   for (StringRef Type : Types)
405     DebugTypes |= StringSwitch<unsigned>(Type.lower())
406                       .Case("cv", static_cast<unsigned>(DebugType::CV))
407                       .Case("pdata", static_cast<unsigned>(DebugType::PData))
408                       .Case("fixup", static_cast<unsigned>(DebugType::Fixup))
409                       .Default(0);
410   return DebugTypes;
411 }
412 
413 static std::string getMapFile(const opt::InputArgList &Args) {
414   auto *Arg = Args.getLastArg(OPT_lldmap, OPT_lldmap_file);
415   if (!Arg)
416     return "";
417   if (Arg->getOption().getID() == OPT_lldmap_file)
418     return Arg->getValue();
419 
420   assert(Arg->getOption().getID() == OPT_lldmap);
421   StringRef OutFile = Config->OutputFile;
422   return (OutFile.substr(0, OutFile.rfind('.')) + ".map").str();
423 }
424 
425 static bool isBitcodeFile(StringRef Path) {
426   std::unique_ptr<MemoryBuffer> MB = check(
427       MemoryBuffer::getFile(Path, -1, false, true), "could not open " + Path);
428   StringRef Buf = MB->getBuffer();
429   return sys::fs::identify_magic(Buf) == sys::fs::file_magic::bitcode;
430 }
431 
432 // Create response file contents and invoke the MSVC linker.
433 void LinkerDriver::invokeMSVC(opt::InputArgList &Args) {
434   std::string Rsp = "/nologo ";
435 
436   for (auto *Arg : Args) {
437     switch (Arg->getOption().getID()) {
438     case OPT_linkrepro:
439     case OPT_lldmap:
440     case OPT_lldmap_file:
441     case OPT_msvclto:
442       // LLD-specific options are stripped.
443       break;
444     case OPT_opt:
445       if (!StringRef(Arg->getValue()).startswith("lld"))
446         Rsp += toString(Arg) + " ";
447       break;
448     case OPT_INPUT:
449       // Bitcode files are stripped as they've been compiled to
450       // native object files.
451       if (Optional<StringRef> Path = doFindFile(Arg->getValue()))
452         if (isBitcodeFile(*Path))
453           break;
454       Rsp += quote(Arg->getValue()) + " ";
455       break;
456     default:
457       Rsp += toString(Arg) + " ";
458     }
459   }
460 
461   std::vector<StringRef> ObjectFiles = Symtab.compileBitcodeFiles();
462   runMSVCLinker(Rsp, ObjectFiles);
463 }
464 
465 void LinkerDriver::enqueueTask(std::function<void()> Task) {
466   TaskQueue.push_back(std::move(Task));
467 }
468 
469 bool LinkerDriver::run() {
470   bool DidWork = !TaskQueue.empty();
471   while (!TaskQueue.empty()) {
472     TaskQueue.front()();
473     TaskQueue.pop_front();
474   }
475   return DidWork;
476 }
477 
478 void LinkerDriver::link(ArrayRef<const char *> ArgsArr) {
479   // If the first command line argument is "/lib", link.exe acts like lib.exe.
480   // We call our own implementation of lib.exe that understands bitcode files.
481   if (ArgsArr.size() > 1 && StringRef(ArgsArr[1]).equals_lower("/lib")) {
482     if (llvm::libDriverMain(ArgsArr.slice(1)) != 0)
483       fatal("lib failed");
484     return;
485   }
486 
487   // Needed for LTO.
488   InitializeAllTargetInfos();
489   InitializeAllTargets();
490   InitializeAllTargetMCs();
491   InitializeAllAsmParsers();
492   InitializeAllAsmPrinters();
493   InitializeAllDisassemblers();
494 
495   // Parse command line options.
496   opt::InputArgList Args = Parser.parseLINK(ArgsArr.slice(1));
497 
498   // Handle /help
499   if (Args.hasArg(OPT_help)) {
500     printHelp(ArgsArr[0]);
501     return;
502   }
503 
504   if (auto *Arg = Args.getLastArg(OPT_linkrepro)) {
505     SmallString<64> Path = StringRef(Arg->getValue());
506     sys::path::append(Path, "repro.tar");
507 
508     Expected<std::unique_ptr<TarWriter>> ErrOrWriter =
509         TarWriter::create(Path, "repro");
510 
511     if (ErrOrWriter) {
512       Tar = std::move(*ErrOrWriter);
513     } else {
514       error("/linkrepro: failed to open " + Path + ": " +
515             toString(ErrOrWriter.takeError()));
516     }
517   }
518 
519   if (Args.filtered_begin(OPT_INPUT) == Args.filtered_end())
520     fatal("no input files");
521 
522   // Construct search path list.
523   SearchPaths.push_back("");
524   for (auto *Arg : Args.filtered(OPT_libpath))
525     SearchPaths.push_back(Arg->getValue());
526   addLibSearchPaths();
527 
528   // Handle /out
529   if (auto *Arg = Args.getLastArg(OPT_out))
530     Config->OutputFile = Arg->getValue();
531 
532   // Handle /verbose
533   if (Args.hasArg(OPT_verbose))
534     Config->Verbose = true;
535 
536   // Handle /force or /force:unresolved
537   if (Args.hasArg(OPT_force) || Args.hasArg(OPT_force_unresolved))
538     Config->Force = true;
539 
540   // Handle /debug
541   if (Args.hasArg(OPT_debug)) {
542     Config->Debug = true;
543     Config->DebugTypes =
544         Args.hasArg(OPT_debugtype)
545             ? parseDebugType(Args.getLastArg(OPT_debugtype)->getValue())
546             : getDefaultDebugType(Args);
547   }
548 
549   // Create a dummy PDB file to satisfy build sytem rules.
550   if (auto *Arg = Args.getLastArg(OPT_pdb))
551     Config->PDBPath = Arg->getValue();
552 
553   // Handle /noentry
554   if (Args.hasArg(OPT_noentry)) {
555     if (!Args.hasArg(OPT_dll))
556       fatal("/noentry must be specified with /dll");
557     Config->NoEntry = true;
558   }
559 
560   // Handle /dll
561   if (Args.hasArg(OPT_dll)) {
562     Config->DLL = true;
563     Config->ManifestID = 2;
564   }
565 
566   // Handle /fixed
567   if (Args.hasArg(OPT_fixed)) {
568     if (Args.hasArg(OPT_dynamicbase))
569       fatal("/fixed must not be specified with /dynamicbase");
570     Config->Relocatable = false;
571     Config->DynamicBase = false;
572   }
573 
574   // Handle /machine
575   if (auto *Arg = Args.getLastArg(OPT_machine))
576     Config->Machine = getMachineType(Arg->getValue());
577 
578   // Handle /nodefaultlib:<filename>
579   for (auto *Arg : Args.filtered(OPT_nodefaultlib))
580     Config->NoDefaultLibs.insert(doFindLib(Arg->getValue()));
581 
582   // Handle /nodefaultlib
583   if (Args.hasArg(OPT_nodefaultlib_all))
584     Config->NoDefaultLibAll = true;
585 
586   // Handle /base
587   if (auto *Arg = Args.getLastArg(OPT_base))
588     parseNumbers(Arg->getValue(), &Config->ImageBase);
589 
590   // Handle /stack
591   if (auto *Arg = Args.getLastArg(OPT_stack))
592     parseNumbers(Arg->getValue(), &Config->StackReserve, &Config->StackCommit);
593 
594   // Handle /heap
595   if (auto *Arg = Args.getLastArg(OPT_heap))
596     parseNumbers(Arg->getValue(), &Config->HeapReserve, &Config->HeapCommit);
597 
598   // Handle /version
599   if (auto *Arg = Args.getLastArg(OPT_version))
600     parseVersion(Arg->getValue(), &Config->MajorImageVersion,
601                  &Config->MinorImageVersion);
602 
603   // Handle /subsystem
604   if (auto *Arg = Args.getLastArg(OPT_subsystem))
605     parseSubsystem(Arg->getValue(), &Config->Subsystem, &Config->MajorOSVersion,
606                    &Config->MinorOSVersion);
607 
608   // Handle /alternatename
609   for (auto *Arg : Args.filtered(OPT_alternatename))
610     parseAlternateName(Arg->getValue());
611 
612   // Handle /include
613   for (auto *Arg : Args.filtered(OPT_incl))
614     addUndefined(Arg->getValue());
615 
616   // Handle /implib
617   if (auto *Arg = Args.getLastArg(OPT_implib))
618     Config->Implib = Arg->getValue();
619 
620   // Handle /opt
621   for (auto *Arg : Args.filtered(OPT_opt)) {
622     std::string Str = StringRef(Arg->getValue()).lower();
623     SmallVector<StringRef, 1> Vec;
624     StringRef(Str).split(Vec, ',');
625     for (StringRef S : Vec) {
626       if (S == "noref") {
627         Config->DoGC = false;
628         Config->DoICF = false;
629         continue;
630       }
631       if (S == "icf" || StringRef(S).startswith("icf=")) {
632         Config->DoICF = true;
633         continue;
634       }
635       if (S == "noicf") {
636         Config->DoICF = false;
637         continue;
638       }
639       if (StringRef(S).startswith("lldlto=")) {
640         StringRef OptLevel = StringRef(S).substr(7);
641         if (OptLevel.getAsInteger(10, Config->LTOOptLevel) ||
642             Config->LTOOptLevel > 3)
643           fatal("/opt:lldlto: invalid optimization level: " + OptLevel);
644         continue;
645       }
646       if (StringRef(S).startswith("lldltojobs=")) {
647         StringRef Jobs = StringRef(S).substr(11);
648         if (Jobs.getAsInteger(10, Config->LTOJobs) || Config->LTOJobs == 0)
649           fatal("/opt:lldltojobs: invalid job count: " + Jobs);
650         continue;
651       }
652       if (StringRef(S).startswith("lldltopartitions=")) {
653         StringRef N = StringRef(S).substr(17);
654         if (N.getAsInteger(10, Config->LTOPartitions) ||
655             Config->LTOPartitions == 0)
656           fatal("/opt:lldltopartitions: invalid partition count: " + N);
657         continue;
658       }
659       if (S != "ref" && S != "lbr" && S != "nolbr")
660         fatal("/opt: unknown option: " + S);
661     }
662   }
663 
664   // Handle /lldsavetemps
665   if (Args.hasArg(OPT_lldsavetemps))
666     Config->SaveTemps = true;
667 
668   // Handle /failifmismatch
669   for (auto *Arg : Args.filtered(OPT_failifmismatch))
670     checkFailIfMismatch(Arg->getValue());
671 
672   // Handle /merge
673   for (auto *Arg : Args.filtered(OPT_merge))
674     parseMerge(Arg->getValue());
675 
676   // Handle /section
677   for (auto *Arg : Args.filtered(OPT_section))
678     parseSection(Arg->getValue());
679 
680   // Handle /manifest
681   if (auto *Arg = Args.getLastArg(OPT_manifest_colon))
682     parseManifest(Arg->getValue());
683 
684   // Handle /manifestuac
685   if (auto *Arg = Args.getLastArg(OPT_manifestuac))
686     parseManifestUAC(Arg->getValue());
687 
688   // Handle /manifestdependency
689   if (auto *Arg = Args.getLastArg(OPT_manifestdependency))
690     Config->ManifestDependency = Arg->getValue();
691 
692   // Handle /manifestfile
693   if (auto *Arg = Args.getLastArg(OPT_manifestfile))
694     Config->ManifestFile = Arg->getValue();
695 
696   // Handle /manifestinput
697   for (auto *Arg : Args.filtered(OPT_manifestinput))
698     Config->ManifestInput.push_back(Arg->getValue());
699 
700   // Handle miscellaneous boolean flags.
701   if (Args.hasArg(OPT_allowbind_no))
702     Config->AllowBind = false;
703   if (Args.hasArg(OPT_allowisolation_no))
704     Config->AllowIsolation = false;
705   if (Args.hasArg(OPT_dynamicbase_no))
706     Config->DynamicBase = false;
707   if (Args.hasArg(OPT_nxcompat_no))
708     Config->NxCompat = false;
709   if (Args.hasArg(OPT_tsaware_no))
710     Config->TerminalServerAware = false;
711   if (Args.hasArg(OPT_nosymtab))
712     Config->WriteSymtab = false;
713   Config->DumpPdb = Args.hasArg(OPT_dumppdb);
714   Config->DebugPdb = Args.hasArg(OPT_debugpdb);
715 
716   Config->MapFile = getMapFile(Args);
717 
718   // Create a list of input files. Files can be given as arguments
719   // for /defaultlib option.
720   std::vector<MemoryBufferRef> MBs;
721   for (auto *Arg : Args.filtered(OPT_INPUT))
722     if (Optional<StringRef> Path = findFile(Arg->getValue()))
723       enqueuePath(*Path);
724   for (auto *Arg : Args.filtered(OPT_defaultlib))
725     if (Optional<StringRef> Path = findLib(Arg->getValue()))
726       enqueuePath(*Path);
727 
728   // Windows specific -- Create a resource file containing a manifest file.
729   if (Config->Manifest == Configuration::Embed)
730     addBuffer(createManifestRes());
731 
732   // Read all input files given via the command line.
733   run();
734 
735   // We should have inferred a machine type by now from the input files, but if
736   // not we assume x64.
737   if (Config->Machine == IMAGE_FILE_MACHINE_UNKNOWN) {
738     warn("/machine is not specified. x64 is assumed");
739     Config->Machine = AMD64;
740   }
741 
742   // Windows specific -- Input files can be Windows resource files (.res files).
743   // We invoke cvtres.exe to convert resource files to a regular COFF file
744   // then link the result file normally.
745   if (!Resources.empty())
746     addBuffer(convertResToCOFF(Resources));
747 
748   if (Tar)
749     Tar->append("response.txt",
750                 createResponseFile(Args, FilePaths,
751                                    ArrayRef<StringRef>(SearchPaths).slice(1)));
752 
753   // Handle /largeaddressaware
754   if (Config->is64() || Args.hasArg(OPT_largeaddressaware))
755     Config->LargeAddressAware = true;
756 
757   // Handle /highentropyva
758   if (Config->is64() && !Args.hasArg(OPT_highentropyva_no))
759     Config->HighEntropyVA = true;
760 
761   // Handle /entry and /dll
762   if (auto *Arg = Args.getLastArg(OPT_entry)) {
763     Config->Entry = addUndefined(mangle(Arg->getValue()));
764   } else if (Args.hasArg(OPT_dll) && !Config->NoEntry) {
765     StringRef S = (Config->Machine == I386) ? "__DllMainCRTStartup@12"
766                                             : "_DllMainCRTStartup";
767     Config->Entry = addUndefined(S);
768   } else if (!Config->NoEntry) {
769     // Windows specific -- If entry point name is not given, we need to
770     // infer that from user-defined entry name.
771     StringRef S = findDefaultEntry();
772     if (S.empty())
773       fatal("entry point must be defined");
774     Config->Entry = addUndefined(S);
775     log("Entry name inferred: " + S);
776   }
777 
778   // Handle /export
779   for (auto *Arg : Args.filtered(OPT_export)) {
780     Export E = parseExport(Arg->getValue());
781     if (Config->Machine == I386) {
782       if (!isDecorated(E.Name))
783         E.Name = Saver.save("_" + E.Name);
784       if (!E.ExtName.empty() && !isDecorated(E.ExtName))
785         E.ExtName = Saver.save("_" + E.ExtName);
786     }
787     Config->Exports.push_back(E);
788   }
789 
790   // Handle /def
791   if (auto *Arg = Args.getLastArg(OPT_deffile)) {
792     // parseModuleDefs mutates Config object.
793     parseModuleDefs(
794         takeBuffer(check(MemoryBuffer::getFile(Arg->getValue()),
795                          Twine("could not open ") + Arg->getValue())));
796   }
797 
798   // Handle /delayload
799   for (auto *Arg : Args.filtered(OPT_delayload)) {
800     Config->DelayLoads.insert(StringRef(Arg->getValue()).lower());
801     if (Config->Machine == I386) {
802       Config->DelayLoadHelper = addUndefined("___delayLoadHelper2@8");
803     } else {
804       Config->DelayLoadHelper = addUndefined("__delayLoadHelper2");
805     }
806   }
807 
808   // Set default image base if /base is not given.
809   if (Config->ImageBase == uint64_t(-1))
810     Config->ImageBase = getDefaultImageBase();
811 
812   Symtab.addRelative(mangle("__ImageBase"), 0);
813   if (Config->Machine == I386) {
814     Config->SEHTable = Symtab.addRelative("___safe_se_handler_table", 0);
815     Config->SEHCount = Symtab.addAbsolute("___safe_se_handler_count", 0);
816   }
817 
818   // We do not support /guard:cf (control flow protection) yet.
819   // Define CFG symbols anyway so that we can link MSVC 2015 CRT.
820   Symtab.addAbsolute(mangle("__guard_fids_table"), 0);
821   Symtab.addAbsolute(mangle("__guard_fids_count"), 0);
822   Symtab.addAbsolute(mangle("__guard_flags"), 0x100);
823 
824   // This code may add new undefined symbols to the link, which may enqueue more
825   // symbol resolution tasks, so we need to continue executing tasks until we
826   // converge.
827   do {
828     // Windows specific -- if entry point is not found,
829     // search for its mangled names.
830     if (Config->Entry)
831       Symtab.mangleMaybe(Config->Entry);
832 
833     // Windows specific -- Make sure we resolve all dllexported symbols.
834     for (Export &E : Config->Exports) {
835       if (!E.ForwardTo.empty())
836         continue;
837       E.Sym = addUndefined(E.Name);
838       if (!E.Directives)
839         Symtab.mangleMaybe(E.Sym);
840     }
841 
842     // Add weak aliases. Weak aliases is a mechanism to give remaining
843     // undefined symbols final chance to be resolved successfully.
844     for (auto Pair : Config->AlternateNames) {
845       StringRef From = Pair.first;
846       StringRef To = Pair.second;
847       Symbol *Sym = Symtab.find(From);
848       if (!Sym)
849         continue;
850       if (auto *U = dyn_cast<Undefined>(Sym->body()))
851         if (!U->WeakAlias)
852           U->WeakAlias = Symtab.addUndefined(To);
853     }
854 
855     // Windows specific -- if __load_config_used can be resolved, resolve it.
856     if (Symtab.findUnderscore("_load_config_used"))
857       addUndefined(mangle("_load_config_used"));
858   } while (run());
859 
860   // If /msvclto is given, we use the MSVC linker to link LTO output files.
861   // This is useful because MSVC link.exe can generate complete PDBs.
862   if (Args.hasArg(OPT_msvclto)) {
863     invokeMSVC(Args);
864     exit(0);
865   }
866 
867   // Do LTO by compiling bitcode input files to a set of native COFF files then
868   // link those files.
869   Symtab.addCombinedLTOObjects();
870   run();
871 
872   // Make sure we have resolved all symbols.
873   Symtab.reportRemainingUndefines();
874 
875   // Windows specific -- if no /subsystem is given, we need to infer
876   // that from entry point name.
877   if (Config->Subsystem == IMAGE_SUBSYSTEM_UNKNOWN) {
878     Config->Subsystem = inferSubsystem();
879     if (Config->Subsystem == IMAGE_SUBSYSTEM_UNKNOWN)
880       fatal("subsystem must be defined");
881   }
882 
883   // Handle /safeseh.
884   if (Args.hasArg(OPT_safeseh))
885     for (ObjectFile *File : Symtab.ObjectFiles)
886       if (!File->SEHCompat)
887         fatal("/safeseh: " + File->getName() + " is not compatible with SEH");
888 
889   // Windows specific -- when we are creating a .dll file, we also
890   // need to create a .lib file.
891   if (!Config->Exports.empty() || Config->DLL) {
892     fixupExports();
893     writeImportLibrary();
894     assignExportOrdinals();
895   }
896 
897   // Windows specific -- Create a side-by-side manifest file.
898   if (Config->Manifest == Configuration::SideBySide)
899     createSideBySideManifest();
900 
901   // Identify unreferenced COMDAT sections.
902   if (Config->DoGC)
903     markLive(Symtab.getChunks());
904 
905   // Identify identical COMDAT sections to merge them.
906   if (Config->DoICF)
907     doICF(Symtab.getChunks());
908 
909   // Write the result.
910   writeResult(&Symtab);
911 
912   // Call exit to avoid calling destructors.
913   exit(0);
914 }
915 
916 } // namespace coff
917 } // namespace lld
918