]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/lld/COFF/Driver.cpp
Merge llvm, clang, compiler-rt, libc++, libunwind, lld, lldb and openmp
[FreeBSD/FreeBSD.git] / contrib / llvm / tools / lld / COFF / Driver.cpp
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     SmallVector<StringRef, 8> Vec;
990     StringRef(Arg->getValue()).split(Vec, ',');
991     for (StringRef S : Vec) {
992       if (S == "4037")
993         Config->WarnMissingOrderSymbol = false;
994       else if (S == "4099")
995         Config->WarnDebugInfoUnusable = false;
996       else if (S == "4217")
997         Config->WarnLocallyDefinedImported = false;
998       // Other warning numbers are ignored.
999     }
1000   }
1001
1002   // Handle /out
1003   if (auto *Arg = Args.getLastArg(OPT_out))
1004     Config->OutputFile = Arg->getValue();
1005
1006   // Handle /verbose
1007   if (Args.hasArg(OPT_verbose))
1008     Config->Verbose = true;
1009   errorHandler().Verbose = Config->Verbose;
1010
1011   // Handle /force or /force:unresolved
1012   if (Args.hasArg(OPT_force, OPT_force_unresolved))
1013     Config->ForceUnresolved = true;
1014
1015   // Handle /force or /force:multiple
1016   if (Args.hasArg(OPT_force, OPT_force_multiple))
1017     Config->ForceMultiple = true;
1018
1019   // Handle /debug
1020   DebugKind Debug = parseDebugKind(Args);
1021   if (Debug == DebugKind::Full || Debug == DebugKind::Dwarf ||
1022       Debug == DebugKind::GHash) {
1023     Config->Debug = true;
1024     Config->Incremental = true;
1025   }
1026
1027   // Handle /debugtype
1028   Config->DebugTypes = parseDebugTypes(Args);
1029
1030   // Handle /pdb
1031   bool ShouldCreatePDB =
1032       (Debug == DebugKind::Full || Debug == DebugKind::GHash);
1033   if (ShouldCreatePDB) {
1034     if (auto *Arg = Args.getLastArg(OPT_pdb))
1035       Config->PDBPath = Arg->getValue();
1036     if (auto *Arg = Args.getLastArg(OPT_pdbaltpath))
1037       Config->PDBAltPath = Arg->getValue();
1038     if (Args.hasArg(OPT_natvis))
1039       Config->NatvisFiles = Args.getAllArgValues(OPT_natvis);
1040
1041     if (auto *Arg = Args.getLastArg(OPT_pdb_source_path))
1042       Config->PDBSourcePath = Arg->getValue();
1043   }
1044
1045   // Handle /noentry
1046   if (Args.hasArg(OPT_noentry)) {
1047     if (Args.hasArg(OPT_dll))
1048       Config->NoEntry = true;
1049     else
1050       error("/noentry must be specified with /dll");
1051   }
1052
1053   // Handle /dll
1054   if (Args.hasArg(OPT_dll)) {
1055     Config->DLL = true;
1056     Config->ManifestID = 2;
1057   }
1058
1059   // Handle /dynamicbase and /fixed. We can't use hasFlag for /dynamicbase
1060   // because we need to explicitly check whether that option or its inverse was
1061   // present in the argument list in order to handle /fixed.
1062   auto *DynamicBaseArg = Args.getLastArg(OPT_dynamicbase, OPT_dynamicbase_no);
1063   if (DynamicBaseArg &&
1064       DynamicBaseArg->getOption().getID() == OPT_dynamicbase_no)
1065     Config->DynamicBase = false;
1066
1067   // MSDN claims "/FIXED:NO is the default setting for a DLL, and /FIXED is the
1068   // default setting for any other project type.", but link.exe defaults to
1069   // /FIXED:NO for exe outputs as well. Match behavior, not docs.
1070   bool Fixed = Args.hasFlag(OPT_fixed, OPT_fixed_no, false);
1071   if (Fixed) {
1072     if (DynamicBaseArg &&
1073         DynamicBaseArg->getOption().getID() == OPT_dynamicbase) {
1074       error("/fixed must not be specified with /dynamicbase");
1075     } else {
1076       Config->Relocatable = false;
1077       Config->DynamicBase = false;
1078     }
1079   }
1080
1081   // Handle /appcontainer
1082   Config->AppContainer =
1083       Args.hasFlag(OPT_appcontainer, OPT_appcontainer_no, false);
1084
1085   // Handle /machine
1086   if (auto *Arg = Args.getLastArg(OPT_machine))
1087     Config->Machine = getMachineType(Arg->getValue());
1088
1089   // Handle /nodefaultlib:<filename>
1090   for (auto *Arg : Args.filtered(OPT_nodefaultlib))
1091     Config->NoDefaultLibs.insert(doFindLib(Arg->getValue()));
1092
1093   // Handle /nodefaultlib
1094   if (Args.hasArg(OPT_nodefaultlib_all))
1095     Config->NoDefaultLibAll = true;
1096
1097   // Handle /base
1098   if (auto *Arg = Args.getLastArg(OPT_base))
1099     parseNumbers(Arg->getValue(), &Config->ImageBase);
1100
1101   // Handle /stack
1102   if (auto *Arg = Args.getLastArg(OPT_stack))
1103     parseNumbers(Arg->getValue(), &Config->StackReserve, &Config->StackCommit);
1104
1105   // Handle /guard:cf
1106   if (auto *Arg = Args.getLastArg(OPT_guard))
1107     parseGuard(Arg->getValue());
1108
1109   // Handle /heap
1110   if (auto *Arg = Args.getLastArg(OPT_heap))
1111     parseNumbers(Arg->getValue(), &Config->HeapReserve, &Config->HeapCommit);
1112
1113   // Handle /version
1114   if (auto *Arg = Args.getLastArg(OPT_version))
1115     parseVersion(Arg->getValue(), &Config->MajorImageVersion,
1116                  &Config->MinorImageVersion);
1117
1118   // Handle /subsystem
1119   if (auto *Arg = Args.getLastArg(OPT_subsystem))
1120     parseSubsystem(Arg->getValue(), &Config->Subsystem, &Config->MajorOSVersion,
1121                    &Config->MinorOSVersion);
1122
1123   // Handle /timestamp
1124   if (llvm::opt::Arg *Arg = Args.getLastArg(OPT_timestamp, OPT_repro)) {
1125     if (Arg->getOption().getID() == OPT_repro) {
1126       Config->Timestamp = 0;
1127       Config->Repro = true;
1128     } else {
1129       Config->Repro = false;
1130       StringRef Value(Arg->getValue());
1131       if (Value.getAsInteger(0, Config->Timestamp))
1132         fatal(Twine("invalid timestamp: ") + Value +
1133               ".  Expected 32-bit integer");
1134     }
1135   } else {
1136     Config->Repro = false;
1137     Config->Timestamp = time(nullptr);
1138   }
1139
1140   // Handle /alternatename
1141   for (auto *Arg : Args.filtered(OPT_alternatename))
1142     parseAlternateName(Arg->getValue());
1143
1144   // Handle /include
1145   for (auto *Arg : Args.filtered(OPT_incl))
1146     addUndefined(Arg->getValue());
1147
1148   // Handle /implib
1149   if (auto *Arg = Args.getLastArg(OPT_implib))
1150     Config->Implib = Arg->getValue();
1151
1152   // Handle /opt.
1153   bool DoGC = Debug == DebugKind::None || Args.hasArg(OPT_profile);
1154   unsigned ICFLevel =
1155       Args.hasArg(OPT_profile) ? 0 : 1; // 0: off, 1: limited, 2: on
1156   unsigned TailMerge = 1;
1157   for (auto *Arg : Args.filtered(OPT_opt)) {
1158     std::string Str = StringRef(Arg->getValue()).lower();
1159     SmallVector<StringRef, 1> Vec;
1160     StringRef(Str).split(Vec, ',');
1161     for (StringRef S : Vec) {
1162       if (S == "ref") {
1163         DoGC = true;
1164       } else if (S == "noref") {
1165         DoGC = false;
1166       } else if (S == "icf" || S.startswith("icf=")) {
1167         ICFLevel = 2;
1168       } else if (S == "noicf") {
1169         ICFLevel = 0;
1170       } else if (S == "lldtailmerge") {
1171         TailMerge = 2;
1172       } else if (S == "nolldtailmerge") {
1173         TailMerge = 0;
1174       } else if (S.startswith("lldlto=")) {
1175         StringRef OptLevel = S.substr(7);
1176         if (OptLevel.getAsInteger(10, Config->LTOO) || Config->LTOO > 3)
1177           error("/opt:lldlto: invalid optimization level: " + OptLevel);
1178       } else if (S.startswith("lldltojobs=")) {
1179         StringRef Jobs = S.substr(11);
1180         if (Jobs.getAsInteger(10, Config->ThinLTOJobs) ||
1181             Config->ThinLTOJobs == 0)
1182           error("/opt:lldltojobs: invalid job count: " + Jobs);
1183       } else if (S.startswith("lldltopartitions=")) {
1184         StringRef N = S.substr(17);
1185         if (N.getAsInteger(10, Config->LTOPartitions) ||
1186             Config->LTOPartitions == 0)
1187           error("/opt:lldltopartitions: invalid partition count: " + N);
1188       } else if (S != "lbr" && S != "nolbr")
1189         error("/opt: unknown option: " + S);
1190     }
1191   }
1192
1193   // Limited ICF is enabled if GC is enabled and ICF was never mentioned
1194   // explicitly.
1195   // FIXME: LLD only implements "limited" ICF, i.e. it only merges identical
1196   // code. If the user passes /OPT:ICF explicitly, LLD should merge identical
1197   // comdat readonly data.
1198   if (ICFLevel == 1 && !DoGC)
1199     ICFLevel = 0;
1200   Config->DoGC = DoGC;
1201   Config->DoICF = ICFLevel > 0;
1202   Config->TailMerge = (TailMerge == 1 && Config->DoICF) || TailMerge == 2;
1203
1204   // Handle /lldsavetemps
1205   if (Args.hasArg(OPT_lldsavetemps))
1206     Config->SaveTemps = true;
1207
1208   // Handle /kill-at
1209   if (Args.hasArg(OPT_kill_at))
1210     Config->KillAt = true;
1211
1212   // Handle /lldltocache
1213   if (auto *Arg = Args.getLastArg(OPT_lldltocache))
1214     Config->LTOCache = Arg->getValue();
1215
1216   // Handle /lldsavecachepolicy
1217   if (auto *Arg = Args.getLastArg(OPT_lldltocachepolicy))
1218     Config->LTOCachePolicy = CHECK(
1219         parseCachePruningPolicy(Arg->getValue()),
1220         Twine("/lldltocachepolicy: invalid cache policy: ") + Arg->getValue());
1221
1222   // Handle /failifmismatch
1223   for (auto *Arg : Args.filtered(OPT_failifmismatch))
1224     checkFailIfMismatch(Arg->getValue());
1225
1226   // Handle /merge
1227   for (auto *Arg : Args.filtered(OPT_merge))
1228     parseMerge(Arg->getValue());
1229
1230   // Add default section merging rules after user rules. User rules take
1231   // precedence, but we will emit a warning if there is a conflict.
1232   parseMerge(".idata=.rdata");
1233   parseMerge(".didat=.rdata");
1234   parseMerge(".edata=.rdata");
1235   parseMerge(".xdata=.rdata");
1236   parseMerge(".bss=.data");
1237
1238   if (Config->MinGW) {
1239     parseMerge(".ctors=.rdata");
1240     parseMerge(".dtors=.rdata");
1241     parseMerge(".CRT=.rdata");
1242   }
1243
1244   // Handle /section
1245   for (auto *Arg : Args.filtered(OPT_section))
1246     parseSection(Arg->getValue());
1247
1248   // Handle /aligncomm
1249   for (auto *Arg : Args.filtered(OPT_aligncomm))
1250     parseAligncomm(Arg->getValue());
1251
1252   // Handle /manifestdependency. This enables /manifest unless /manifest:no is
1253   // also passed.
1254   if (auto *Arg = Args.getLastArg(OPT_manifestdependency)) {
1255     Config->ManifestDependency = Arg->getValue();
1256     Config->Manifest = Configuration::SideBySide;
1257   }
1258
1259   // Handle /manifest and /manifest:
1260   if (auto *Arg = Args.getLastArg(OPT_manifest, OPT_manifest_colon)) {
1261     if (Arg->getOption().getID() == OPT_manifest)
1262       Config->Manifest = Configuration::SideBySide;
1263     else
1264       parseManifest(Arg->getValue());
1265   }
1266
1267   // Handle /manifestuac
1268   if (auto *Arg = Args.getLastArg(OPT_manifestuac))
1269     parseManifestUAC(Arg->getValue());
1270
1271   // Handle /manifestfile
1272   if (auto *Arg = Args.getLastArg(OPT_manifestfile))
1273     Config->ManifestFile = Arg->getValue();
1274
1275   // Handle /manifestinput
1276   for (auto *Arg : Args.filtered(OPT_manifestinput))
1277     Config->ManifestInput.push_back(Arg->getValue());
1278
1279   if (!Config->ManifestInput.empty() &&
1280       Config->Manifest != Configuration::Embed) {
1281     fatal("/manifestinput: requires /manifest:embed");
1282   }
1283
1284   // Handle miscellaneous boolean flags.
1285   Config->AllowBind = Args.hasFlag(OPT_allowbind, OPT_allowbind_no, true);
1286   Config->AllowIsolation =
1287       Args.hasFlag(OPT_allowisolation, OPT_allowisolation_no, true);
1288   Config->Incremental =
1289       Args.hasFlag(OPT_incremental, OPT_incremental_no,
1290                    !Config->DoGC && !Config->DoICF && !Args.hasArg(OPT_order) &&
1291                        !Args.hasArg(OPT_profile));
1292   Config->IntegrityCheck =
1293       Args.hasFlag(OPT_integritycheck, OPT_integritycheck_no, false);
1294   Config->NxCompat = Args.hasFlag(OPT_nxcompat, OPT_nxcompat_no, true);
1295   Config->TerminalServerAware =
1296       !Config->DLL && Args.hasFlag(OPT_tsaware, OPT_tsaware_no, true);
1297   Config->DebugDwarf = Debug == DebugKind::Dwarf;
1298   Config->DebugGHashes = Debug == DebugKind::GHash;
1299   Config->DebugSymtab = Debug == DebugKind::Symtab;
1300
1301   Config->MapFile = getMapFile(Args);
1302
1303   if (Config->Incremental && Args.hasArg(OPT_profile)) {
1304     warn("ignoring '/incremental' due to '/profile' specification");
1305     Config->Incremental = false;
1306   }
1307
1308   if (Config->Incremental && Args.hasArg(OPT_order)) {
1309     warn("ignoring '/incremental' due to '/order' specification");
1310     Config->Incremental = false;
1311   }
1312
1313   if (Config->Incremental && Config->DoGC) {
1314     warn("ignoring '/incremental' because REF is enabled; use '/opt:noref' to "
1315          "disable");
1316     Config->Incremental = false;
1317   }
1318
1319   if (Config->Incremental && Config->DoICF) {
1320     warn("ignoring '/incremental' because ICF is enabled; use '/opt:noicf' to "
1321          "disable");
1322     Config->Incremental = false;
1323   }
1324
1325   if (errorCount())
1326     return;
1327
1328   std::set<sys::fs::UniqueID> WholeArchives;
1329   AutoExporter Exporter;
1330   for (auto *Arg : Args.filtered(OPT_wholearchive_file)) {
1331     if (Optional<StringRef> Path = doFindFile(Arg->getValue())) {
1332       if (Optional<sys::fs::UniqueID> ID = getUniqueID(*Path))
1333         WholeArchives.insert(*ID);
1334       Exporter.addWholeArchive(*Path);
1335     }
1336   }
1337
1338   // A predicate returning true if a given path is an argument for
1339   // /wholearchive:, or /wholearchive is enabled globally.
1340   // This function is a bit tricky because "foo.obj /wholearchive:././foo.obj"
1341   // needs to be handled as "/wholearchive:foo.obj foo.obj".
1342   auto IsWholeArchive = [&](StringRef Path) -> bool {
1343     if (Args.hasArg(OPT_wholearchive_flag))
1344       return true;
1345     if (Optional<sys::fs::UniqueID> ID = getUniqueID(Path))
1346       return WholeArchives.count(*ID);
1347     return false;
1348   };
1349
1350   // Create a list of input files. Files can be given as arguments
1351   // for /defaultlib option.
1352   for (auto *Arg : Args.filtered(OPT_INPUT, OPT_wholearchive_file))
1353     if (Optional<StringRef> Path = findFile(Arg->getValue()))
1354       enqueuePath(*Path, IsWholeArchive(*Path));
1355
1356   for (auto *Arg : Args.filtered(OPT_defaultlib))
1357     if (Optional<StringRef> Path = findLib(Arg->getValue()))
1358       enqueuePath(*Path, false);
1359
1360   // Windows specific -- Create a resource file containing a manifest file.
1361   if (Config->Manifest == Configuration::Embed)
1362     addBuffer(createManifestRes(), false);
1363
1364   // Read all input files given via the command line.
1365   run();
1366
1367   if (errorCount())
1368     return;
1369
1370   // We should have inferred a machine type by now from the input files, but if
1371   // not we assume x64.
1372   if (Config->Machine == IMAGE_FILE_MACHINE_UNKNOWN) {
1373     warn("/machine is not specified. x64 is assumed");
1374     Config->Machine = AMD64;
1375   }
1376   Config->Wordsize = Config->is64() ? 8 : 4;
1377
1378   // Input files can be Windows resource files (.res files). We use
1379   // WindowsResource to convert resource files to a regular COFF file,
1380   // then link the resulting file normally.
1381   if (!Resources.empty())
1382     Symtab->addFile(make<ObjFile>(convertResToCOFF(Resources)));
1383
1384   if (Tar)
1385     Tar->append("response.txt",
1386                 createResponseFile(Args, FilePaths,
1387                                    ArrayRef<StringRef>(SearchPaths).slice(1)));
1388
1389   // Handle /largeaddressaware
1390   Config->LargeAddressAware = Args.hasFlag(
1391       OPT_largeaddressaware, OPT_largeaddressaware_no, Config->is64());
1392
1393   // Handle /highentropyva
1394   Config->HighEntropyVA =
1395       Config->is64() &&
1396       Args.hasFlag(OPT_highentropyva, OPT_highentropyva_no, true);
1397
1398   if (!Config->DynamicBase &&
1399       (Config->Machine == ARMNT || Config->Machine == ARM64))
1400     error("/dynamicbase:no is not compatible with " +
1401           machineToStr(Config->Machine));
1402
1403   // Handle /export
1404   for (auto *Arg : Args.filtered(OPT_export)) {
1405     Export E = parseExport(Arg->getValue());
1406     if (Config->Machine == I386) {
1407       if (!isDecorated(E.Name))
1408         E.Name = Saver.save("_" + E.Name);
1409       if (!E.ExtName.empty() && !isDecorated(E.ExtName))
1410         E.ExtName = Saver.save("_" + E.ExtName);
1411     }
1412     Config->Exports.push_back(E);
1413   }
1414
1415   // Handle /def
1416   if (auto *Arg = Args.getLastArg(OPT_deffile)) {
1417     // parseModuleDefs mutates Config object.
1418     parseModuleDefs(Arg->getValue());
1419   }
1420
1421   // Handle generation of import library from a def file.
1422   if (!Args.hasArg(OPT_INPUT)) {
1423     fixupExports();
1424     createImportLibrary(/*AsLib=*/true);
1425     return;
1426   }
1427
1428   // Windows specific -- if no /subsystem is given, we need to infer
1429   // that from entry point name.  Must happen before /entry handling,
1430   // and after the early return when just writing an import library.
1431   if (Config->Subsystem == IMAGE_SUBSYSTEM_UNKNOWN) {
1432     Config->Subsystem = inferSubsystem();
1433     if (Config->Subsystem == IMAGE_SUBSYSTEM_UNKNOWN)
1434       fatal("subsystem must be defined");
1435   }
1436
1437   // Handle /entry and /dll
1438   if (auto *Arg = Args.getLastArg(OPT_entry)) {
1439     Config->Entry = addUndefined(mangle(Arg->getValue()));
1440   } else if (!Config->Entry && !Config->NoEntry) {
1441     if (Args.hasArg(OPT_dll)) {
1442       StringRef S = (Config->Machine == I386) ? "__DllMainCRTStartup@12"
1443                                               : "_DllMainCRTStartup";
1444       Config->Entry = addUndefined(S);
1445     } else {
1446       // Windows specific -- If entry point name is not given, we need to
1447       // infer that from user-defined entry name.
1448       StringRef S = findDefaultEntry();
1449       if (S.empty())
1450         fatal("entry point must be defined");
1451       Config->Entry = addUndefined(S);
1452       log("Entry name inferred: " + S);
1453     }
1454   }
1455
1456   // Handle /delayload
1457   for (auto *Arg : Args.filtered(OPT_delayload)) {
1458     Config->DelayLoads.insert(StringRef(Arg->getValue()).lower());
1459     if (Config->Machine == I386) {
1460       Config->DelayLoadHelper = addUndefined("___delayLoadHelper2@8");
1461     } else {
1462       Config->DelayLoadHelper = addUndefined("__delayLoadHelper2");
1463     }
1464   }
1465
1466   // Set default image name if neither /out or /def set it.
1467   if (Config->OutputFile.empty()) {
1468     Config->OutputFile =
1469         getOutputPath((*Args.filtered(OPT_INPUT).begin())->getValue());
1470   }
1471
1472   if (ShouldCreatePDB) {
1473     // Put the PDB next to the image if no /pdb flag was passed.
1474     if (Config->PDBPath.empty()) {
1475       Config->PDBPath = Config->OutputFile;
1476       sys::path::replace_extension(Config->PDBPath, ".pdb");
1477     }
1478
1479     // The embedded PDB path should be the absolute path to the PDB if no
1480     // /pdbaltpath flag was passed.
1481     if (Config->PDBAltPath.empty()) {
1482       Config->PDBAltPath = Config->PDBPath;
1483
1484       // It's important to make the path absolute and remove dots.  This path
1485       // will eventually be written into the PE header, and certain Microsoft
1486       // tools won't work correctly if these assumptions are not held.
1487       sys::fs::make_absolute(Config->PDBAltPath);
1488       sys::path::remove_dots(Config->PDBAltPath);
1489     } else {
1490       // Don't do this earlier, so that Config->OutputFile is ready.
1491       parsePDBAltPath(Config->PDBAltPath);
1492     }
1493   }
1494
1495   // Set default image base if /base is not given.
1496   if (Config->ImageBase == uint64_t(-1))
1497     Config->ImageBase = getDefaultImageBase();
1498
1499   Symtab->addSynthetic(mangle("__ImageBase"), nullptr);
1500   if (Config->Machine == I386) {
1501     Symtab->addAbsolute("___safe_se_handler_table", 0);
1502     Symtab->addAbsolute("___safe_se_handler_count", 0);
1503   }
1504
1505   Symtab->addAbsolute(mangle("__guard_fids_count"), 0);
1506   Symtab->addAbsolute(mangle("__guard_fids_table"), 0);
1507   Symtab->addAbsolute(mangle("__guard_flags"), 0);
1508   Symtab->addAbsolute(mangle("__guard_iat_count"), 0);
1509   Symtab->addAbsolute(mangle("__guard_iat_table"), 0);
1510   Symtab->addAbsolute(mangle("__guard_longjmp_count"), 0);
1511   Symtab->addAbsolute(mangle("__guard_longjmp_table"), 0);
1512   // Needed for MSVC 2017 15.5 CRT.
1513   Symtab->addAbsolute(mangle("__enclave_config"), 0);
1514
1515   if (Config->MinGW) {
1516     Symtab->addAbsolute(mangle("__RUNTIME_PSEUDO_RELOC_LIST__"), 0);
1517     Symtab->addAbsolute(mangle("__RUNTIME_PSEUDO_RELOC_LIST_END__"), 0);
1518     Symtab->addAbsolute(mangle("__CTOR_LIST__"), 0);
1519     Symtab->addAbsolute(mangle("__DTOR_LIST__"), 0);
1520   }
1521
1522   // This code may add new undefined symbols to the link, which may enqueue more
1523   // symbol resolution tasks, so we need to continue executing tasks until we
1524   // converge.
1525   do {
1526     // Windows specific -- if entry point is not found,
1527     // search for its mangled names.
1528     if (Config->Entry)
1529       Symtab->mangleMaybe(Config->Entry);
1530
1531     // Windows specific -- Make sure we resolve all dllexported symbols.
1532     for (Export &E : Config->Exports) {
1533       if (!E.ForwardTo.empty())
1534         continue;
1535       E.Sym = addUndefined(E.Name);
1536       if (!E.Directives)
1537         Symtab->mangleMaybe(E.Sym);
1538     }
1539
1540     // Add weak aliases. Weak aliases is a mechanism to give remaining
1541     // undefined symbols final chance to be resolved successfully.
1542     for (auto Pair : Config->AlternateNames) {
1543       StringRef From = Pair.first;
1544       StringRef To = Pair.second;
1545       Symbol *Sym = Symtab->find(From);
1546       if (!Sym)
1547         continue;
1548       if (auto *U = dyn_cast<Undefined>(Sym))
1549         if (!U->WeakAlias)
1550           U->WeakAlias = Symtab->addUndefined(To);
1551     }
1552
1553     // Windows specific -- if __load_config_used can be resolved, resolve it.
1554     if (Symtab->findUnderscore("_load_config_used"))
1555       addUndefined(mangle("_load_config_used"));
1556   } while (run());
1557
1558   if (errorCount())
1559     return;
1560
1561   // Do LTO by compiling bitcode input files to a set of native COFF files then
1562   // link those files.
1563   Symtab->addCombinedLTOObjects();
1564   run();
1565
1566   if (Config->MinGW) {
1567     // Load any further object files that might be needed for doing automatic
1568     // imports.
1569     //
1570     // For cases with no automatically imported symbols, this iterates once
1571     // over the symbol table and doesn't do anything.
1572     //
1573     // For the normal case with a few automatically imported symbols, this
1574     // should only need to be run once, since each new object file imported
1575     // is an import library and wouldn't add any new undefined references,
1576     // but there's nothing stopping the __imp_ symbols from coming from a
1577     // normal object file as well (although that won't be used for the
1578     // actual autoimport later on). If this pass adds new undefined references,
1579     // we won't iterate further to resolve them.
1580     Symtab->loadMinGWAutomaticImports();
1581     run();
1582   }
1583
1584   // Make sure we have resolved all symbols.
1585   Symtab->reportRemainingUndefines();
1586   if (errorCount())
1587     return;
1588
1589   // Handle /safeseh.
1590   if (Args.hasFlag(OPT_safeseh, OPT_safeseh_no, false)) {
1591     for (ObjFile *File : ObjFile::Instances)
1592       if (!File->hasSafeSEH())
1593         error("/safeseh: " + File->getName() + " is not compatible with SEH");
1594     if (errorCount())
1595       return;
1596   }
1597
1598   // In MinGW, all symbols are automatically exported if no symbols
1599   // are chosen to be exported.
1600   if (Config->DLL && ((Config->MinGW && Config->Exports.empty()) ||
1601                       Args.hasArg(OPT_export_all_symbols))) {
1602     Exporter.initSymbolExcludes();
1603
1604     Symtab->forEachSymbol([=](Symbol *S) {
1605       auto *Def = dyn_cast<Defined>(S);
1606       if (!Exporter.shouldExport(Def))
1607         return;
1608       Export E;
1609       E.Name = Def->getName();
1610       E.Sym = Def;
1611       if (Def->getChunk() &&
1612           !(Def->getChunk()->getOutputCharacteristics() & IMAGE_SCN_MEM_EXECUTE))
1613         E.Data = true;
1614       Config->Exports.push_back(E);
1615     });
1616   }
1617
1618   // Windows specific -- when we are creating a .dll file, we also
1619   // need to create a .lib file.
1620   if (!Config->Exports.empty() || Config->DLL) {
1621     fixupExports();
1622     createImportLibrary(/*AsLib=*/false);
1623     assignExportOrdinals();
1624   }
1625
1626   // Handle /output-def (MinGW specific).
1627   if (auto *Arg = Args.getLastArg(OPT_output_def))
1628     writeDefFile(Arg->getValue());
1629
1630   // Set extra alignment for .comm symbols
1631   for (auto Pair : Config->AlignComm) {
1632     StringRef Name = Pair.first;
1633     uint32_t Alignment = Pair.second;
1634
1635     Symbol *Sym = Symtab->find(Name);
1636     if (!Sym) {
1637       warn("/aligncomm symbol " + Name + " not found");
1638       continue;
1639     }
1640
1641     // If the symbol isn't common, it must have been replaced with a regular
1642     // symbol, which will carry its own alignment.
1643     auto *DC = dyn_cast<DefinedCommon>(Sym);
1644     if (!DC)
1645       continue;
1646
1647     CommonChunk *C = DC->getChunk();
1648     C->Alignment = std::max(C->Alignment, Alignment);
1649   }
1650
1651   // Windows specific -- Create a side-by-side manifest file.
1652   if (Config->Manifest == Configuration::SideBySide)
1653     createSideBySideManifest();
1654
1655   // Handle /order. We want to do this at this moment because we
1656   // need a complete list of comdat sections to warn on nonexistent
1657   // functions.
1658   if (auto *Arg = Args.getLastArg(OPT_order))
1659     parseOrderFile(Arg->getValue());
1660
1661   // Identify unreferenced COMDAT sections.
1662   if (Config->DoGC)
1663     markLive(Symtab->getChunks());
1664
1665   // Identify identical COMDAT sections to merge them.
1666   if (Config->DoICF) {
1667     findKeepUniqueSections();
1668     doICF(Symtab->getChunks());
1669   }
1670
1671   // Write the result.
1672   writeResult();
1673
1674   // Stop early so we can print the results.
1675   Timer::root().stop();
1676   if (Config->ShowTiming)
1677     Timer::root().print();
1678 }
1679
1680 } // namespace coff
1681 } // namespace lld