xref: /llvm-project-15.0.7/lld/COFF/Driver.cpp (revision 121ecfd2)
1 //===- Driver.cpp ---------------------------------------------------------===//
2 //
3 //                             The LLVM Linker
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
10 #include "Driver.h"
11 #include "Config.h"
12 #include "ICF.h"
13 #include "InputFiles.h"
14 #include "MarkLive.h"
15 #include "MinGW.h"
16 #include "SymbolTable.h"
17 #include "Symbols.h"
18 #include "Writer.h"
19 #include "lld/Common/Args.h"
20 #include "lld/Common/Driver.h"
21 #include "lld/Common/ErrorHandler.h"
22 #include "lld/Common/Memory.h"
23 #include "lld/Common/Timer.h"
24 #include "lld/Common/Version.h"
25 #include "llvm/ADT/Optional.h"
26 #include "llvm/ADT/StringSwitch.h"
27 #include "llvm/BinaryFormat/Magic.h"
28 #include "llvm/Object/ArchiveWriter.h"
29 #include "llvm/Object/COFFImportFile.h"
30 #include "llvm/Object/COFFModuleDefinition.h"
31 #include "llvm/Option/Arg.h"
32 #include "llvm/Option/ArgList.h"
33 #include "llvm/Option/Option.h"
34 #include "llvm/Support/Debug.h"
35 #include "llvm/Support/Path.h"
36 #include "llvm/Support/Process.h"
37 #include "llvm/Support/TarWriter.h"
38 #include "llvm/Support/TargetSelect.h"
39 #include "llvm/Support/raw_ostream.h"
40 #include "llvm/ToolDrivers/llvm-lib/LibDriver.h"
41 #include <algorithm>
42 #include <future>
43 #include <memory>
44 
45 using namespace llvm;
46 using namespace llvm::object;
47 using namespace llvm::COFF;
48 using llvm::sys::Process;
49 
50 namespace lld {
51 namespace coff {
52 
53 static Timer InputFileTimer("Input File Reading", Timer::root());
54 
55 Configuration *Config;
56 LinkerDriver *Driver;
57 
58 bool link(ArrayRef<const char *> Args, bool CanExitEarly, raw_ostream &Diag) {
59   errorHandler().LogName = args::FilenameWithoutExe(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   bool HaveMain = findUnderscoreMangle("main");
453   bool HaveWMain = findUnderscoreMangle("wmain");
454   bool HaveWinMain = findUnderscoreMangle("WinMain");
455   bool HaveWWinMain = findUnderscoreMangle("wWinMain");
456   if (HaveMain || HaveWMain) {
457     if (HaveWinMain || HaveWWinMain) {
458       warn(std::string("found ") + (HaveMain ? "main" : "wmain") + " and " +
459            (HaveWinMain ? "WinMain" : "wWinMain") +
460            "; defaulting to /subsystem:console");
461     }
462     return IMAGE_SUBSYSTEM_WINDOWS_CUI;
463   }
464   if (HaveWinMain || HaveWWinMain)
465     return IMAGE_SUBSYSTEM_WINDOWS_GUI;
466   return IMAGE_SUBSYSTEM_UNKNOWN;
467 }
468 
469 static uint64_t getDefaultImageBase() {
470   if (Config->is64())
471     return Config->DLL ? 0x180000000 : 0x140000000;
472   return Config->DLL ? 0x10000000 : 0x400000;
473 }
474 
475 static std::string createResponseFile(const opt::InputArgList &Args,
476                                       ArrayRef<StringRef> FilePaths,
477                                       ArrayRef<StringRef> SearchPaths) {
478   SmallString<0> Data;
479   raw_svector_ostream OS(Data);
480 
481   for (auto *Arg : Args) {
482     switch (Arg->getOption().getID()) {
483     case OPT_linkrepro:
484     case OPT_INPUT:
485     case OPT_defaultlib:
486     case OPT_libpath:
487     case OPT_manifest:
488     case OPT_manifest_colon:
489     case OPT_manifestdependency:
490     case OPT_manifestfile:
491     case OPT_manifestinput:
492     case OPT_manifestuac:
493       break;
494     default:
495       OS << toString(*Arg) << "\n";
496     }
497   }
498 
499   for (StringRef Path : SearchPaths) {
500     std::string RelPath = relativeToRoot(Path);
501     OS << "/libpath:" << quote(RelPath) << "\n";
502   }
503 
504   for (StringRef Path : FilePaths)
505     OS << quote(relativeToRoot(Path)) << "\n";
506 
507   return Data.str();
508 }
509 
510 static unsigned getDefaultDebugType(const opt::InputArgList &Args) {
511   unsigned DebugTypes = static_cast<unsigned>(DebugType::CV);
512   if (Args.hasArg(OPT_driver))
513     DebugTypes |= static_cast<unsigned>(DebugType::PData);
514   if (Args.hasArg(OPT_profile))
515     DebugTypes |= static_cast<unsigned>(DebugType::Fixup);
516   return DebugTypes;
517 }
518 
519 static unsigned parseDebugType(StringRef Arg) {
520   SmallVector<StringRef, 3> Types;
521   Arg.split(Types, ',', /*KeepEmpty=*/false);
522 
523   unsigned DebugTypes = static_cast<unsigned>(DebugType::None);
524   for (StringRef Type : Types)
525     DebugTypes |= StringSwitch<unsigned>(Type.lower())
526                       .Case("cv", static_cast<unsigned>(DebugType::CV))
527                       .Case("pdata", static_cast<unsigned>(DebugType::PData))
528                       .Case("fixup", static_cast<unsigned>(DebugType::Fixup))
529                       .Default(0);
530   return DebugTypes;
531 }
532 
533 static std::string getMapFile(const opt::InputArgList &Args) {
534   auto *Arg = Args.getLastArg(OPT_lldmap, OPT_lldmap_file);
535   if (!Arg)
536     return "";
537   if (Arg->getOption().getID() == OPT_lldmap_file)
538     return Arg->getValue();
539 
540   assert(Arg->getOption().getID() == OPT_lldmap);
541   StringRef OutFile = Config->OutputFile;
542   return (OutFile.substr(0, OutFile.rfind('.')) + ".map").str();
543 }
544 
545 static std::string getImplibPath() {
546   if (!Config->Implib.empty())
547     return Config->Implib;
548   SmallString<128> Out = StringRef(Config->OutputFile);
549   sys::path::replace_extension(Out, ".lib");
550   return Out.str();
551 }
552 
553 //
554 // The import name is caculated as the following:
555 //
556 //        | LIBRARY w/ ext |   LIBRARY w/o ext   | no LIBRARY
557 //   -----+----------------+---------------------+------------------
558 //   LINK | {value}        | {value}.{.dll/.exe} | {output name}
559 //    LIB | {value}        | {value}.dll         | {output name}.dll
560 //
561 static std::string getImportName(bool AsLib) {
562   SmallString<128> Out;
563 
564   if (Config->ImportName.empty()) {
565     Out.assign(sys::path::filename(Config->OutputFile));
566     if (AsLib)
567       sys::path::replace_extension(Out, ".dll");
568   } else {
569     Out.assign(Config->ImportName);
570     if (!sys::path::has_extension(Out))
571       sys::path::replace_extension(Out,
572                                    (Config->DLL || AsLib) ? ".dll" : ".exe");
573   }
574 
575   return Out.str();
576 }
577 
578 static void createImportLibrary(bool AsLib) {
579   std::vector<COFFShortExport> Exports;
580   for (Export &E1 : Config->Exports) {
581     COFFShortExport E2;
582     E2.Name = E1.Name;
583     E2.SymbolName = E1.SymbolName;
584     E2.ExtName = E1.ExtName;
585     E2.Ordinal = E1.Ordinal;
586     E2.Noname = E1.Noname;
587     E2.Data = E1.Data;
588     E2.Private = E1.Private;
589     E2.Constant = E1.Constant;
590     Exports.push_back(E2);
591   }
592 
593   auto HandleError = [](Error &&E) {
594     handleAllErrors(std::move(E),
595                     [](ErrorInfoBase &EIB) { error(EIB.message()); });
596   };
597   std::string LibName = getImportName(AsLib);
598   std::string Path = getImplibPath();
599 
600   if (!Config->Incremental) {
601     HandleError(writeImportLibrary(LibName, Path, Exports, Config->Machine,
602                                    Config->MinGW));
603     return;
604   }
605 
606   // If the import library already exists, replace it only if the contents
607   // have changed.
608   ErrorOr<std::unique_ptr<MemoryBuffer>> OldBuf = MemoryBuffer::getFile(
609       Path, /*FileSize*/ -1, /*RequiresNullTerminator*/ false);
610   if (!OldBuf) {
611     HandleError(writeImportLibrary(LibName, Path, Exports, Config->Machine,
612                                    Config->MinGW));
613     return;
614   }
615 
616   SmallString<128> TmpName;
617   if (std::error_code EC =
618           sys::fs::createUniqueFile(Path + ".tmp-%%%%%%%%.lib", TmpName))
619     fatal("cannot create temporary file for import library " + Path + ": " +
620           EC.message());
621 
622   if (Error E = writeImportLibrary(LibName, TmpName, Exports, Config->Machine,
623                                    Config->MinGW)) {
624     HandleError(std::move(E));
625     return;
626   }
627 
628   std::unique_ptr<MemoryBuffer> NewBuf = check(MemoryBuffer::getFile(
629       TmpName, /*FileSize*/ -1, /*RequiresNullTerminator*/ false));
630   if ((*OldBuf)->getBuffer() != NewBuf->getBuffer()) {
631     OldBuf->reset();
632     HandleError(errorCodeToError(sys::fs::rename(TmpName, Path)));
633   } else {
634     sys::fs::remove(TmpName);
635   }
636 }
637 
638 static void parseModuleDefs(StringRef Path) {
639   std::unique_ptr<MemoryBuffer> MB = CHECK(
640       MemoryBuffer::getFile(Path, -1, false, true), "could not open " + Path);
641   COFFModuleDefinition M = check(parseCOFFModuleDefinition(
642       MB->getMemBufferRef(), Config->Machine, Config->MinGW));
643 
644   if (Config->OutputFile.empty())
645     Config->OutputFile = Saver.save(M.OutputFile);
646   Config->ImportName = Saver.save(M.ImportName);
647   if (M.ImageBase)
648     Config->ImageBase = M.ImageBase;
649   if (M.StackReserve)
650     Config->StackReserve = M.StackReserve;
651   if (M.StackCommit)
652     Config->StackCommit = M.StackCommit;
653   if (M.HeapReserve)
654     Config->HeapReserve = M.HeapReserve;
655   if (M.HeapCommit)
656     Config->HeapCommit = M.HeapCommit;
657   if (M.MajorImageVersion)
658     Config->MajorImageVersion = M.MajorImageVersion;
659   if (M.MinorImageVersion)
660     Config->MinorImageVersion = M.MinorImageVersion;
661   if (M.MajorOSVersion)
662     Config->MajorOSVersion = M.MajorOSVersion;
663   if (M.MinorOSVersion)
664     Config->MinorOSVersion = M.MinorOSVersion;
665 
666   for (COFFShortExport E1 : M.Exports) {
667     Export E2;
668     // In simple cases, only Name is set. Renamed exports are parsed
669     // and set as "ExtName = Name". If Name has the form "OtherDll.Func",
670     // it shouldn't be a normal exported function but a forward to another
671     // DLL instead. This is supported by both MS and GNU linkers.
672     if (E1.ExtName != E1.Name && StringRef(E1.Name).contains('.')) {
673       E2.Name = Saver.save(E1.ExtName);
674       E2.ForwardTo = Saver.save(E1.Name);
675       Config->Exports.push_back(E2);
676       continue;
677     }
678     E2.Name = Saver.save(E1.Name);
679     E2.ExtName = Saver.save(E1.ExtName);
680     E2.Ordinal = E1.Ordinal;
681     E2.Noname = E1.Noname;
682     E2.Data = E1.Data;
683     E2.Private = E1.Private;
684     E2.Constant = E1.Constant;
685     Config->Exports.push_back(E2);
686   }
687 }
688 
689 void LinkerDriver::enqueueTask(std::function<void()> Task) {
690   TaskQueue.push_back(std::move(Task));
691 }
692 
693 bool LinkerDriver::run() {
694   ScopedTimer T(InputFileTimer);
695 
696   bool DidWork = !TaskQueue.empty();
697   while (!TaskQueue.empty()) {
698     TaskQueue.front()();
699     TaskQueue.pop_front();
700   }
701   return DidWork;
702 }
703 
704 // Parse an /order file. If an option is given, the linker places
705 // COMDAT sections in the same order as their names appear in the
706 // given file.
707 static void parseOrderFile(StringRef Arg) {
708   // For some reason, the MSVC linker requires a filename to be
709   // preceded by "@".
710   if (!Arg.startswith("@")) {
711     error("malformed /order option: '@' missing");
712     return;
713   }
714 
715   // Get a list of all comdat sections for error checking.
716   DenseSet<StringRef> Set;
717   for (Chunk *C : Symtab->getChunks())
718     if (auto *Sec = dyn_cast<SectionChunk>(C))
719       if (Sec->Sym)
720         Set.insert(Sec->Sym->getName());
721 
722   // Open a file.
723   StringRef Path = Arg.substr(1);
724   std::unique_ptr<MemoryBuffer> MB = CHECK(
725       MemoryBuffer::getFile(Path, -1, false, true), "could not open " + Path);
726 
727   // Parse a file. An order file contains one symbol per line.
728   // All symbols that were not present in a given order file are
729   // considered to have the lowest priority 0 and are placed at
730   // end of an output section.
731   for (std::string S : args::getLines(MB->getMemBufferRef())) {
732     if (Config->Machine == I386 && !isDecorated(S))
733       S = "_" + S;
734 
735     if (Set.count(S) == 0) {
736       if (Config->WarnMissingOrderSymbol)
737         warn("/order:" + Arg + ": missing symbol: " + S + " [LNK4037]");
738     }
739     else
740       Config->Order[S] = INT_MIN + Config->Order.size();
741   }
742 }
743 
744 void LinkerDriver::link(ArrayRef<const char *> ArgsArr) {
745   // If the first command line argument is "/lib", link.exe acts like lib.exe.
746   // We call our own implementation of lib.exe that understands bitcode files.
747   if (ArgsArr.size() > 1 && StringRef(ArgsArr[1]).equals_lower("/lib")) {
748     if (llvm::libDriverMain(ArgsArr.slice(1)) != 0)
749       fatal("lib failed");
750     return;
751   }
752 
753   // Needed for LTO.
754   InitializeAllTargetInfos();
755   InitializeAllTargets();
756   InitializeAllTargetMCs();
757   InitializeAllAsmParsers();
758   InitializeAllAsmPrinters();
759 
760   // Parse command line options.
761   ArgParser Parser;
762   opt::InputArgList Args = Parser.parseLINK(ArgsArr);
763 
764   // Parse and evaluate -mllvm options.
765   std::vector<const char *> V;
766   V.push_back("lld-link (LLVM option parsing)");
767   for (auto *Arg : Args.filtered(OPT_mllvm))
768     V.push_back(Arg->getValue());
769   cl::ParseCommandLineOptions(V.size(), V.data());
770 
771   // Handle /errorlimit early, because error() depends on it.
772   if (auto *Arg = Args.getLastArg(OPT_errorlimit)) {
773     int N = 20;
774     StringRef S = Arg->getValue();
775     if (S.getAsInteger(10, N))
776       error(Arg->getSpelling() + " number expected, but got " + S);
777     errorHandler().ErrorLimit = N;
778   }
779 
780   // Handle /help
781   if (Args.hasArg(OPT_help)) {
782     printHelp(ArgsArr[0]);
783     return;
784   }
785 
786   if (Args.hasArg(OPT_show_timing))
787     Config->ShowTiming = true;
788 
789   ScopedTimer T(Timer::root());
790   // Handle --version, which is an lld extension. This option is a bit odd
791   // because it doesn't start with "/", but we deliberately chose "--" to
792   // avoid conflict with /version and for compatibility with clang-cl.
793   if (Args.hasArg(OPT_dash_dash_version)) {
794     outs() << getLLDVersion() << "\n";
795     return;
796   }
797 
798   // Handle /lldmingw early, since it can potentially affect how other
799   // options are handled.
800   Config->MinGW = Args.hasArg(OPT_lldmingw);
801 
802   if (auto *Arg = Args.getLastArg(OPT_linkrepro)) {
803     SmallString<64> Path = StringRef(Arg->getValue());
804     sys::path::append(Path, "repro.tar");
805 
806     Expected<std::unique_ptr<TarWriter>> ErrOrWriter =
807         TarWriter::create(Path, "repro");
808 
809     if (ErrOrWriter) {
810       Tar = std::move(*ErrOrWriter);
811     } else {
812       error("/linkrepro: failed to open " + Path + ": " +
813             toString(ErrOrWriter.takeError()));
814     }
815   }
816 
817   if (!Args.hasArg(OPT_INPUT)) {
818     if (Args.hasArg(OPT_deffile))
819       Config->NoEntry = true;
820     else
821       fatal("no input files");
822   }
823 
824   // Construct search path list.
825   SearchPaths.push_back("");
826   for (auto *Arg : Args.filtered(OPT_libpath))
827     SearchPaths.push_back(Arg->getValue());
828   addLibSearchPaths();
829 
830   // Handle /ignore
831   for (auto *Arg : Args.filtered(OPT_ignore)) {
832     if (StringRef(Arg->getValue()) == "4037")
833       Config->WarnMissingOrderSymbol = false;
834     else if (StringRef(Arg->getValue()) == "4217")
835       Config->WarnLocallyDefinedImported = false;
836     // Other warning numbers are ignored.
837   }
838 
839   // Handle /out
840   if (auto *Arg = Args.getLastArg(OPT_out))
841     Config->OutputFile = Arg->getValue();
842 
843   // Handle /verbose
844   if (Args.hasArg(OPT_verbose))
845     Config->Verbose = true;
846   errorHandler().Verbose = Config->Verbose;
847 
848   // Handle /force or /force:unresolved
849   if (Args.hasArg(OPT_force, OPT_force_unresolved))
850     Config->Force = true;
851 
852   // Handle /debug
853   if (Args.hasArg(OPT_debug, OPT_debug_dwarf, OPT_debug_ghash)) {
854     Config->Debug = true;
855     Config->Incremental = true;
856     if (auto *Arg = Args.getLastArg(OPT_debugtype))
857       Config->DebugTypes = parseDebugType(Arg->getValue());
858     else
859       Config->DebugTypes = getDefaultDebugType(Args);
860   }
861 
862   // Handle /pdb
863   bool ShouldCreatePDB = Args.hasArg(OPT_debug, OPT_debug_ghash);
864   if (ShouldCreatePDB) {
865     if (auto *Arg = Args.getLastArg(OPT_pdb))
866       Config->PDBPath = Arg->getValue();
867     if (auto *Arg = Args.getLastArg(OPT_pdbaltpath))
868       Config->PDBAltPath = Arg->getValue();
869     if (Args.hasArg(OPT_natvis))
870       Config->NatvisFiles = Args.getAllArgValues(OPT_natvis);
871 
872     if (auto *Arg = Args.getLastArg(OPT_pdb_source_path))
873       Config->PDBSourcePath = Arg->getValue();
874   }
875 
876   // Handle /noentry
877   if (Args.hasArg(OPT_noentry)) {
878     if (Args.hasArg(OPT_dll))
879       Config->NoEntry = true;
880     else
881       error("/noentry must be specified with /dll");
882   }
883 
884   // Handle /dll
885   if (Args.hasArg(OPT_dll)) {
886     Config->DLL = true;
887     Config->ManifestID = 2;
888   }
889 
890   // Handle /dynamicbase and /fixed. We can't use hasFlag for /dynamicbase
891   // because we need to explicitly check whether that option or its inverse was
892   // present in the argument list in order to handle /fixed.
893   auto *DynamicBaseArg = Args.getLastArg(OPT_dynamicbase, OPT_dynamicbase_no);
894   if (DynamicBaseArg &&
895       DynamicBaseArg->getOption().getID() == OPT_dynamicbase_no)
896     Config->DynamicBase = false;
897 
898   // MSDN claims "/FIXED:NO is the default setting for a DLL, and /FIXED is the
899   // default setting for any other project type.", but link.exe defaults to
900   // /FIXED:NO for exe outputs as well. Match behavior, not docs.
901   bool Fixed = Args.hasFlag(OPT_fixed, OPT_fixed_no, false);
902   if (Fixed) {
903     if (DynamicBaseArg &&
904         DynamicBaseArg->getOption().getID() == OPT_dynamicbase) {
905       error("/fixed must not be specified with /dynamicbase");
906     } else {
907       Config->Relocatable = false;
908       Config->DynamicBase = false;
909     }
910   }
911 
912   // Handle /appcontainer
913   Config->AppContainer =
914       Args.hasFlag(OPT_appcontainer, OPT_appcontainer_no, false);
915 
916   // Handle /machine
917   if (auto *Arg = Args.getLastArg(OPT_machine))
918     Config->Machine = getMachineType(Arg->getValue());
919 
920   // Handle /nodefaultlib:<filename>
921   for (auto *Arg : Args.filtered(OPT_nodefaultlib))
922     Config->NoDefaultLibs.insert(doFindLib(Arg->getValue()));
923 
924   // Handle /nodefaultlib
925   if (Args.hasArg(OPT_nodefaultlib_all))
926     Config->NoDefaultLibAll = true;
927 
928   // Handle /base
929   if (auto *Arg = Args.getLastArg(OPT_base))
930     parseNumbers(Arg->getValue(), &Config->ImageBase);
931 
932   // Handle /stack
933   if (auto *Arg = Args.getLastArg(OPT_stack))
934     parseNumbers(Arg->getValue(), &Config->StackReserve, &Config->StackCommit);
935 
936   // Handle /guard:cf
937   if (auto *Arg = Args.getLastArg(OPT_guard))
938     parseGuard(Arg->getValue());
939 
940   // Handle /heap
941   if (auto *Arg = Args.getLastArg(OPT_heap))
942     parseNumbers(Arg->getValue(), &Config->HeapReserve, &Config->HeapCommit);
943 
944   // Handle /version
945   if (auto *Arg = Args.getLastArg(OPT_version))
946     parseVersion(Arg->getValue(), &Config->MajorImageVersion,
947                  &Config->MinorImageVersion);
948 
949   // Handle /subsystem
950   if (auto *Arg = Args.getLastArg(OPT_subsystem))
951     parseSubsystem(Arg->getValue(), &Config->Subsystem, &Config->MajorOSVersion,
952                    &Config->MinorOSVersion);
953 
954   // Handle /timestamp
955   if (llvm::opt::Arg *Arg = Args.getLastArg(OPT_timestamp, OPT_repro)) {
956     if (Arg->getOption().getID() == OPT_repro) {
957       Config->Timestamp = 0;
958       Config->Repro = true;
959     } else {
960       Config->Repro = false;
961       StringRef Value(Arg->getValue());
962       if (Value.getAsInteger(0, Config->Timestamp))
963         fatal(Twine("invalid timestamp: ") + Value +
964               ".  Expected 32-bit integer");
965     }
966   } else {
967     Config->Repro = false;
968     Config->Timestamp = time(nullptr);
969   }
970 
971   // Handle /alternatename
972   for (auto *Arg : Args.filtered(OPT_alternatename))
973     parseAlternateName(Arg->getValue());
974 
975   // Handle /include
976   for (auto *Arg : Args.filtered(OPT_incl))
977     addUndefined(Arg->getValue());
978 
979   // Handle /implib
980   if (auto *Arg = Args.getLastArg(OPT_implib))
981     Config->Implib = Arg->getValue();
982 
983   // Handle /opt.
984   bool DoGC = !Args.hasArg(OPT_debug) || Args.hasArg(OPT_profile);
985   unsigned ICFLevel =
986       Args.hasArg(OPT_profile) ? 0 : 1; // 0: off, 1: limited, 2: on
987   unsigned TailMerge = 1;
988   for (auto *Arg : Args.filtered(OPT_opt)) {
989     std::string Str = StringRef(Arg->getValue()).lower();
990     SmallVector<StringRef, 1> Vec;
991     StringRef(Str).split(Vec, ',');
992     for (StringRef S : Vec) {
993       if (S == "ref") {
994         DoGC = true;
995       } else if (S == "noref") {
996         DoGC = false;
997       } else if (S == "icf" || S.startswith("icf=")) {
998         ICFLevel = 2;
999       } else if (S == "noicf") {
1000         ICFLevel = 0;
1001       } else if (S == "lldtailmerge") {
1002         TailMerge = 2;
1003       } else if (S == "nolldtailmerge") {
1004         TailMerge = 0;
1005       } else if (S.startswith("lldlto=")) {
1006         StringRef OptLevel = S.substr(7);
1007         if (OptLevel.getAsInteger(10, Config->LTOO) || Config->LTOO > 3)
1008           error("/opt:lldlto: invalid optimization level: " + OptLevel);
1009       } else if (S.startswith("lldltojobs=")) {
1010         StringRef Jobs = S.substr(11);
1011         if (Jobs.getAsInteger(10, Config->ThinLTOJobs) ||
1012             Config->ThinLTOJobs == 0)
1013           error("/opt:lldltojobs: invalid job count: " + Jobs);
1014       } else if (S.startswith("lldltopartitions=")) {
1015         StringRef N = S.substr(17);
1016         if (N.getAsInteger(10, Config->LTOPartitions) ||
1017             Config->LTOPartitions == 0)
1018           error("/opt:lldltopartitions: invalid partition count: " + N);
1019       } else if (S != "lbr" && S != "nolbr")
1020         error("/opt: unknown option: " + S);
1021     }
1022   }
1023 
1024   // Limited ICF is enabled if GC is enabled and ICF was never mentioned
1025   // explicitly.
1026   // FIXME: LLD only implements "limited" ICF, i.e. it only merges identical
1027   // code. If the user passes /OPT:ICF explicitly, LLD should merge identical
1028   // comdat readonly data.
1029   if (ICFLevel == 1 && !DoGC)
1030     ICFLevel = 0;
1031   Config->DoGC = DoGC;
1032   Config->DoICF = ICFLevel > 0;
1033   Config->TailMerge = (TailMerge == 1 && Config->DoICF) || TailMerge == 2;
1034 
1035   // Handle /lldsavetemps
1036   if (Args.hasArg(OPT_lldsavetemps))
1037     Config->SaveTemps = true;
1038 
1039   // Handle /kill-at
1040   if (Args.hasArg(OPT_kill_at))
1041     Config->KillAt = true;
1042 
1043   // Handle /lldltocache
1044   if (auto *Arg = Args.getLastArg(OPT_lldltocache))
1045     Config->LTOCache = Arg->getValue();
1046 
1047   // Handle /lldsavecachepolicy
1048   if (auto *Arg = Args.getLastArg(OPT_lldltocachepolicy))
1049     Config->LTOCachePolicy = CHECK(
1050         parseCachePruningPolicy(Arg->getValue()),
1051         Twine("/lldltocachepolicy: invalid cache policy: ") + Arg->getValue());
1052 
1053   // Handle /failifmismatch
1054   for (auto *Arg : Args.filtered(OPT_failifmismatch))
1055     checkFailIfMismatch(Arg->getValue());
1056 
1057   // Handle /merge
1058   for (auto *Arg : Args.filtered(OPT_merge))
1059     parseMerge(Arg->getValue());
1060 
1061   // Add default section merging rules after user rules. User rules take
1062   // precedence, but we will emit a warning if there is a conflict.
1063   parseMerge(".idata=.rdata");
1064   parseMerge(".didat=.rdata");
1065   parseMerge(".edata=.rdata");
1066   parseMerge(".xdata=.rdata");
1067   parseMerge(".bss=.data");
1068 
1069   // Handle /section
1070   for (auto *Arg : Args.filtered(OPT_section))
1071     parseSection(Arg->getValue());
1072 
1073   // Handle /aligncomm
1074   for (auto *Arg : Args.filtered(OPT_aligncomm))
1075     parseAligncomm(Arg->getValue());
1076 
1077   // Handle /manifestdependency. This enables /manifest unless /manifest:no is
1078   // also passed.
1079   if (auto *Arg = Args.getLastArg(OPT_manifestdependency)) {
1080     Config->ManifestDependency = Arg->getValue();
1081     Config->Manifest = Configuration::SideBySide;
1082   }
1083 
1084   // Handle /manifest and /manifest:
1085   if (auto *Arg = Args.getLastArg(OPT_manifest, OPT_manifest_colon)) {
1086     if (Arg->getOption().getID() == OPT_manifest)
1087       Config->Manifest = Configuration::SideBySide;
1088     else
1089       parseManifest(Arg->getValue());
1090   }
1091 
1092   // Handle /manifestuac
1093   if (auto *Arg = Args.getLastArg(OPT_manifestuac))
1094     parseManifestUAC(Arg->getValue());
1095 
1096   // Handle /manifestfile
1097   if (auto *Arg = Args.getLastArg(OPT_manifestfile))
1098     Config->ManifestFile = Arg->getValue();
1099 
1100   // Handle /manifestinput
1101   for (auto *Arg : Args.filtered(OPT_manifestinput))
1102     Config->ManifestInput.push_back(Arg->getValue());
1103 
1104   if (!Config->ManifestInput.empty() &&
1105       Config->Manifest != Configuration::Embed) {
1106     fatal("/manifestinput: requires /manifest:embed");
1107   }
1108 
1109   // Handle miscellaneous boolean flags.
1110   Config->AllowBind = Args.hasFlag(OPT_allowbind, OPT_allowbind_no, true);
1111   Config->AllowIsolation =
1112       Args.hasFlag(OPT_allowisolation, OPT_allowisolation_no, true);
1113   Config->Incremental =
1114       Args.hasFlag(OPT_incremental, OPT_incremental_no,
1115                    !Config->DoGC && !Config->DoICF && !Args.hasArg(OPT_order) &&
1116                        !Args.hasArg(OPT_profile));
1117   Config->IntegrityCheck =
1118       Args.hasFlag(OPT_integritycheck, OPT_integritycheck_no, false);
1119   Config->NxCompat = Args.hasFlag(OPT_nxcompat, OPT_nxcompat_no, true);
1120   Config->TerminalServerAware =
1121       !Config->DLL && Args.hasFlag(OPT_tsaware, OPT_tsaware_no, true);
1122   Config->DebugDwarf = Args.hasArg(OPT_debug_dwarf);
1123   Config->DebugGHashes = Args.hasArg(OPT_debug_ghash);
1124   Config->DebugSymtab = Args.hasArg(OPT_debug_symtab);
1125 
1126   Config->MapFile = getMapFile(Args);
1127 
1128   if (Config->Incremental && Args.hasArg(OPT_profile)) {
1129     warn("ignoring '/incremental' due to '/profile' specification");
1130     Config->Incremental = false;
1131   }
1132 
1133   if (Config->Incremental && Args.hasArg(OPT_order)) {
1134     warn("ignoring '/incremental' due to '/order' specification");
1135     Config->Incremental = false;
1136   }
1137 
1138   if (Config->Incremental && Config->DoGC) {
1139     warn("ignoring '/incremental' because REF is enabled; use '/opt:noref' to "
1140          "disable");
1141     Config->Incremental = false;
1142   }
1143 
1144   if (Config->Incremental && Config->DoICF) {
1145     warn("ignoring '/incremental' because ICF is enabled; use '/opt:noicf' to "
1146          "disable");
1147     Config->Incremental = false;
1148   }
1149 
1150   if (errorCount())
1151     return;
1152 
1153   std::set<sys::fs::UniqueID> WholeArchives;
1154   for (auto *Arg : Args.filtered(OPT_wholearchive_file))
1155     if (Optional<StringRef> Path = doFindFile(Arg->getValue()))
1156       if (Optional<sys::fs::UniqueID> ID = getUniqueID(*Path))
1157         WholeArchives.insert(*ID);
1158 
1159   // A predicate returning true if a given path is an argument for
1160   // /wholearchive:, or /wholearchive is enabled globally.
1161   // This function is a bit tricky because "foo.obj /wholearchive:././foo.obj"
1162   // needs to be handled as "/wholearchive:foo.obj foo.obj".
1163   auto IsWholeArchive = [&](StringRef Path) -> bool {
1164     if (Args.hasArg(OPT_wholearchive_flag))
1165       return true;
1166     if (Optional<sys::fs::UniqueID> ID = getUniqueID(Path))
1167       return WholeArchives.count(*ID);
1168     return false;
1169   };
1170 
1171   // Create a list of input files. Files can be given as arguments
1172   // for /defaultlib option.
1173   for (auto *Arg : Args.filtered(OPT_INPUT, OPT_wholearchive_file))
1174     if (Optional<StringRef> Path = findFile(Arg->getValue()))
1175       enqueuePath(*Path, IsWholeArchive(*Path));
1176 
1177   for (auto *Arg : Args.filtered(OPT_defaultlib))
1178     if (Optional<StringRef> Path = findLib(Arg->getValue()))
1179       enqueuePath(*Path, false);
1180 
1181   // Windows specific -- Create a resource file containing a manifest file.
1182   if (Config->Manifest == Configuration::Embed)
1183     addBuffer(createManifestRes(), false);
1184 
1185   // Read all input files given via the command line.
1186   run();
1187 
1188   // We should have inferred a machine type by now from the input files, but if
1189   // not we assume x64.
1190   if (Config->Machine == IMAGE_FILE_MACHINE_UNKNOWN) {
1191     warn("/machine is not specified. x64 is assumed");
1192     Config->Machine = AMD64;
1193   }
1194 
1195   // Input files can be Windows resource files (.res files). We use
1196   // WindowsResource to convert resource files to a regular COFF file,
1197   // then link the resulting file normally.
1198   if (!Resources.empty())
1199     Symtab->addFile(make<ObjFile>(convertResToCOFF(Resources)));
1200 
1201   if (Tar)
1202     Tar->append("response.txt",
1203                 createResponseFile(Args, FilePaths,
1204                                    ArrayRef<StringRef>(SearchPaths).slice(1)));
1205 
1206   // Handle /largeaddressaware
1207   Config->LargeAddressAware = Args.hasFlag(
1208       OPT_largeaddressaware, OPT_largeaddressaware_no, Config->is64());
1209 
1210   // Handle /highentropyva
1211   Config->HighEntropyVA =
1212       Config->is64() &&
1213       Args.hasFlag(OPT_highentropyva, OPT_highentropyva_no, true);
1214 
1215   if (!Config->DynamicBase &&
1216       (Config->Machine == ARMNT || Config->Machine == ARM64))
1217     error("/dynamicbase:no is not compatible with " +
1218           machineToStr(Config->Machine));
1219 
1220   // Handle /export
1221   for (auto *Arg : Args.filtered(OPT_export)) {
1222     Export E = parseExport(Arg->getValue());
1223     if (Config->Machine == I386) {
1224       if (!isDecorated(E.Name))
1225         E.Name = Saver.save("_" + E.Name);
1226       if (!E.ExtName.empty() && !isDecorated(E.ExtName))
1227         E.ExtName = Saver.save("_" + E.ExtName);
1228     }
1229     Config->Exports.push_back(E);
1230   }
1231 
1232   // Handle /def
1233   if (auto *Arg = Args.getLastArg(OPT_deffile)) {
1234     // parseModuleDefs mutates Config object.
1235     parseModuleDefs(Arg->getValue());
1236   }
1237 
1238   // Handle generation of import library from a def file.
1239   if (!Args.hasArg(OPT_INPUT)) {
1240     fixupExports();
1241     createImportLibrary(/*AsLib=*/true);
1242     return;
1243   }
1244 
1245   // Windows specific -- if no /subsystem is given, we need to infer
1246   // that from entry point name.  Must happen before /entry handling,
1247   // and after the early return when just writing an import library.
1248   if (Config->Subsystem == IMAGE_SUBSYSTEM_UNKNOWN) {
1249     Config->Subsystem = inferSubsystem();
1250     if (Config->Subsystem == IMAGE_SUBSYSTEM_UNKNOWN)
1251       fatal("subsystem must be defined");
1252   }
1253 
1254   // Handle /entry and /dll
1255   if (auto *Arg = Args.getLastArg(OPT_entry)) {
1256     Config->Entry = addUndefined(mangle(Arg->getValue()));
1257   } else if (!Config->Entry && !Config->NoEntry) {
1258     if (Args.hasArg(OPT_dll)) {
1259       StringRef S = (Config->Machine == I386) ? "__DllMainCRTStartup@12"
1260                                               : "_DllMainCRTStartup";
1261       Config->Entry = addUndefined(S);
1262     } else {
1263       // Windows specific -- If entry point name is not given, we need to
1264       // infer that from user-defined entry name.
1265       StringRef S = findDefaultEntry();
1266       if (S.empty())
1267         fatal("entry point must be defined");
1268       Config->Entry = addUndefined(S);
1269       log("Entry name inferred: " + S);
1270     }
1271   }
1272 
1273   // Handle /delayload
1274   for (auto *Arg : Args.filtered(OPT_delayload)) {
1275     Config->DelayLoads.insert(StringRef(Arg->getValue()).lower());
1276     if (Config->Machine == I386) {
1277       Config->DelayLoadHelper = addUndefined("___delayLoadHelper2@8");
1278     } else {
1279       Config->DelayLoadHelper = addUndefined("__delayLoadHelper2");
1280     }
1281   }
1282 
1283   // Set default image name if neither /out or /def set it.
1284   if (Config->OutputFile.empty()) {
1285     Config->OutputFile =
1286         getOutputPath((*Args.filtered(OPT_INPUT).begin())->getValue());
1287   }
1288 
1289   if (ShouldCreatePDB) {
1290     // Put the PDB next to the image if no /pdb flag was passed.
1291     if (Config->PDBPath.empty()) {
1292       Config->PDBPath = Config->OutputFile;
1293       sys::path::replace_extension(Config->PDBPath, ".pdb");
1294     }
1295 
1296     // The embedded PDB path should be the absolute path to the PDB if no
1297     // /pdbaltpath flag was passed.
1298     if (Config->PDBAltPath.empty()) {
1299       Config->PDBAltPath = Config->PDBPath;
1300 
1301       // It's important to make the path absolute and remove dots.  This path
1302       // will eventually be written into the PE header, and certain Microsoft
1303       // tools won't work correctly if these assumptions are not held.
1304       sys::fs::make_absolute(Config->PDBAltPath);
1305       sys::path::remove_dots(Config->PDBAltPath);
1306     }
1307   }
1308 
1309   // Set default image base if /base is not given.
1310   if (Config->ImageBase == uint64_t(-1))
1311     Config->ImageBase = getDefaultImageBase();
1312 
1313   Symtab->addSynthetic(mangle("__ImageBase"), nullptr);
1314   if (Config->Machine == I386) {
1315     Symtab->addAbsolute("___safe_se_handler_table", 0);
1316     Symtab->addAbsolute("___safe_se_handler_count", 0);
1317   }
1318 
1319   Symtab->addAbsolute(mangle("__guard_fids_count"), 0);
1320   Symtab->addAbsolute(mangle("__guard_fids_table"), 0);
1321   Symtab->addAbsolute(mangle("__guard_flags"), 0);
1322   Symtab->addAbsolute(mangle("__guard_iat_count"), 0);
1323   Symtab->addAbsolute(mangle("__guard_iat_table"), 0);
1324   Symtab->addAbsolute(mangle("__guard_longjmp_count"), 0);
1325   Symtab->addAbsolute(mangle("__guard_longjmp_table"), 0);
1326   // Needed for MSVC 2017 15.5 CRT.
1327   Symtab->addAbsolute(mangle("__enclave_config"), 0);
1328 
1329   // This code may add new undefined symbols to the link, which may enqueue more
1330   // symbol resolution tasks, so we need to continue executing tasks until we
1331   // converge.
1332   do {
1333     // Windows specific -- if entry point is not found,
1334     // search for its mangled names.
1335     if (Config->Entry)
1336       Symtab->mangleMaybe(Config->Entry);
1337 
1338     // Windows specific -- Make sure we resolve all dllexported symbols.
1339     for (Export &E : Config->Exports) {
1340       if (!E.ForwardTo.empty())
1341         continue;
1342       E.Sym = addUndefined(E.Name);
1343       if (!E.Directives)
1344         Symtab->mangleMaybe(E.Sym);
1345     }
1346 
1347     // Add weak aliases. Weak aliases is a mechanism to give remaining
1348     // undefined symbols final chance to be resolved successfully.
1349     for (auto Pair : Config->AlternateNames) {
1350       StringRef From = Pair.first;
1351       StringRef To = Pair.second;
1352       Symbol *Sym = Symtab->find(From);
1353       if (!Sym)
1354         continue;
1355       if (auto *U = dyn_cast<Undefined>(Sym))
1356         if (!U->WeakAlias)
1357           U->WeakAlias = Symtab->addUndefined(To);
1358     }
1359 
1360     // Windows specific -- if __load_config_used can be resolved, resolve it.
1361     if (Symtab->findUnderscore("_load_config_used"))
1362       addUndefined(mangle("_load_config_used"));
1363   } while (run());
1364 
1365   if (errorCount())
1366     return;
1367 
1368   // Do LTO by compiling bitcode input files to a set of native COFF files then
1369   // link those files.
1370   Symtab->addCombinedLTOObjects();
1371   run();
1372 
1373   // Make sure we have resolved all symbols.
1374   Symtab->reportRemainingUndefines();
1375   if (errorCount())
1376     return;
1377 
1378   // Handle /safeseh.
1379   if (Args.hasFlag(OPT_safeseh, OPT_safeseh_no, false)) {
1380     for (ObjFile *File : ObjFile::Instances)
1381       if (!File->hasSafeSEH())
1382         error("/safeseh: " + File->getName() + " is not compatible with SEH");
1383     if (errorCount())
1384       return;
1385   }
1386 
1387   // In MinGW, all symbols are automatically exported if no symbols
1388   // are chosen to be exported.
1389   if (Config->DLL && ((Config->MinGW && Config->Exports.empty()) ||
1390                       Args.hasArg(OPT_export_all_symbols))) {
1391     AutoExporter Exporter;
1392 
1393     Symtab->forEachSymbol([=](Symbol *S) {
1394       auto *Def = dyn_cast<Defined>(S);
1395       if (!Exporter.shouldExport(Def))
1396         return;
1397       Export E;
1398       E.Name = Def->getName();
1399       E.Sym = Def;
1400       if (Def->getChunk() &&
1401           !(Def->getChunk()->getOutputCharacteristics() & IMAGE_SCN_MEM_EXECUTE))
1402         E.Data = true;
1403       Config->Exports.push_back(E);
1404     });
1405   }
1406 
1407   // Windows specific -- when we are creating a .dll file, we also
1408   // need to create a .lib file.
1409   if (!Config->Exports.empty() || Config->DLL) {
1410     fixupExports();
1411     createImportLibrary(/*AsLib=*/false);
1412     assignExportOrdinals();
1413   }
1414 
1415   // Handle /output-def (MinGW specific).
1416   if (auto *Arg = Args.getLastArg(OPT_output_def))
1417     writeDefFile(Arg->getValue());
1418 
1419   // Set extra alignment for .comm symbols
1420   for (auto Pair : Config->AlignComm) {
1421     StringRef Name = Pair.first;
1422     uint32_t Alignment = Pair.second;
1423 
1424     Symbol *Sym = Symtab->find(Name);
1425     if (!Sym) {
1426       warn("/aligncomm symbol " + Name + " not found");
1427       continue;
1428     }
1429 
1430     // If the symbol isn't common, it must have been replaced with a regular
1431     // symbol, which will carry its own alignment.
1432     auto *DC = dyn_cast<DefinedCommon>(Sym);
1433     if (!DC)
1434       continue;
1435 
1436     CommonChunk *C = DC->getChunk();
1437     C->Alignment = std::max(C->Alignment, Alignment);
1438   }
1439 
1440   // Windows specific -- Create a side-by-side manifest file.
1441   if (Config->Manifest == Configuration::SideBySide)
1442     createSideBySideManifest();
1443 
1444   // Handle /order. We want to do this at this moment because we
1445   // need a complete list of comdat sections to warn on nonexistent
1446   // functions.
1447   if (auto *Arg = Args.getLastArg(OPT_order))
1448     parseOrderFile(Arg->getValue());
1449 
1450   // Identify unreferenced COMDAT sections.
1451   if (Config->DoGC)
1452     markLive(Symtab->getChunks());
1453 
1454   // Identify identical COMDAT sections to merge them.
1455   if (Config->DoICF)
1456     doICF(Symtab->getChunks());
1457 
1458   // Write the result.
1459   writeResult();
1460 
1461   // Stop early so we can print the results.
1462   Timer::root().stop();
1463   if (Config->ShowTiming)
1464     Timer::root().print();
1465 }
1466 
1467 } // namespace coff
1468 } // namespace lld
1469