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