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