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