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