]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/lld/COFF/Driver.cpp
Merge llvm, clang, lld, lldb, compiler-rt and libc++ r308421, and update
[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 "Error.h"
13 #include "InputFiles.h"
14 #include "Memory.h"
15 #include "SymbolTable.h"
16 #include "Symbols.h"
17 #include "Writer.h"
18 #include "lld/Driver/Driver.h"
19 #include "llvm/ADT/Optional.h"
20 #include "llvm/ADT/StringSwitch.h"
21 #include "llvm/BinaryFormat/Magic.h"
22 #include "llvm/Object/ArchiveWriter.h"
23 #include "llvm/Object/COFFImportFile.h"
24 #include "llvm/Object/COFFModuleDefinition.h"
25 #include "llvm/Option/Arg.h"
26 #include "llvm/Option/ArgList.h"
27 #include "llvm/Option/Option.h"
28 #include "llvm/Support/Debug.h"
29 #include "llvm/Support/Path.h"
30 #include "llvm/Support/Process.h"
31 #include "llvm/Support/TarWriter.h"
32 #include "llvm/Support/TargetSelect.h"
33 #include "llvm/Support/raw_ostream.h"
34 #include "llvm/ToolDrivers/llvm-lib/LibDriver.h"
35 #include <algorithm>
36 #include <memory>
37
38 #include <future>
39
40 using namespace llvm;
41 using namespace llvm::object;
42 using namespace llvm::COFF;
43 using llvm::sys::Process;
44
45 namespace lld {
46 namespace coff {
47
48 Configuration *Config;
49 LinkerDriver *Driver;
50
51 BumpPtrAllocator BAlloc;
52 StringSaver Saver{BAlloc};
53 std::vector<SpecificAllocBase *> SpecificAllocBase::Instances;
54
55 bool link(ArrayRef<const char *> Args, raw_ostream &Diag) {
56   ErrorCount = 0;
57   ErrorOS = &Diag;
58   Config = make<Configuration>();
59   Config->Argv = {Args.begin(), Args.end()};
60   Config->ColorDiagnostics =
61       (ErrorOS == &llvm::errs() && Process::StandardErrHasColors());
62   Driver = make<LinkerDriver>();
63   Driver->link(Args);
64   return !ErrorCount;
65 }
66
67 // Drop directory components and replace extension with ".exe" or ".dll".
68 static std::string getOutputPath(StringRef Path) {
69   auto P = Path.find_last_of("\\/");
70   StringRef S = (P == StringRef::npos) ? Path : Path.substr(P + 1);
71   const char* E = Config->DLL ? ".dll" : ".exe";
72   return (S.substr(0, S.rfind('.')) + E).str();
73 }
74
75 // ErrorOr is not default constructible, so it cannot be used as the type
76 // parameter of a future.
77 // FIXME: We could open the file in createFutureForFile and avoid needing to
78 // return an error here, but for the moment that would cost us a file descriptor
79 // (a limited resource on Windows) for the duration that the future is pending.
80 typedef std::pair<std::unique_ptr<MemoryBuffer>, std::error_code> MBErrPair;
81
82 // Create a std::future that opens and maps a file using the best strategy for
83 // the host platform.
84 static std::future<MBErrPair> createFutureForFile(std::string Path) {
85 #if LLVM_ON_WIN32
86   // On Windows, file I/O is relatively slow so it is best to do this
87   // asynchronously.
88   auto Strategy = std::launch::async;
89 #else
90   auto Strategy = std::launch::deferred;
91 #endif
92   return std::async(Strategy, [=]() {
93     auto MBOrErr = MemoryBuffer::getFile(Path);
94     if (!MBOrErr)
95       return MBErrPair{nullptr, MBOrErr.getError()};
96     return MBErrPair{std::move(*MBOrErr), std::error_code()};
97   });
98 }
99
100 MemoryBufferRef LinkerDriver::takeBuffer(std::unique_ptr<MemoryBuffer> MB) {
101   MemoryBufferRef MBRef = *MB;
102   make<std::unique_ptr<MemoryBuffer>>(std::move(MB)); // take ownership
103
104   if (Driver->Tar)
105     Driver->Tar->append(relativeToRoot(MBRef.getBufferIdentifier()),
106                         MBRef.getBuffer());
107   return MBRef;
108 }
109
110 void LinkerDriver::addBuffer(std::unique_ptr<MemoryBuffer> MB) {
111   MemoryBufferRef MBRef = takeBuffer(std::move(MB));
112
113   // File type is detected by contents, not by file extension.
114   file_magic Magic = identify_magic(MBRef.getBuffer());
115   if (Magic == file_magic::windows_resource) {
116     Resources.push_back(MBRef);
117     return;
118   }
119
120   FilePaths.push_back(MBRef.getBufferIdentifier());
121   if (Magic == file_magic::archive)
122     return Symtab.addFile(make<ArchiveFile>(MBRef));
123   if (Magic == file_magic::bitcode)
124     return Symtab.addFile(make<BitcodeFile>(MBRef));
125
126   if (Magic == file_magic::coff_cl_gl_object)
127     error(MBRef.getBufferIdentifier() + ": is not a native COFF file. "
128           "Recompile without /GL");
129   else
130     Symtab.addFile(make<ObjectFile>(MBRef));
131 }
132
133 void LinkerDriver::enqueuePath(StringRef Path) {
134   auto Future =
135       std::make_shared<std::future<MBErrPair>>(createFutureForFile(Path));
136   std::string PathStr = Path;
137   enqueueTask([=]() {
138     auto MBOrErr = Future->get();
139     if (MBOrErr.second)
140       error("could not open " + PathStr + ": " + MBOrErr.second.message());
141     else
142       Driver->addBuffer(std::move(MBOrErr.first));
143   });
144 }
145
146 void LinkerDriver::addArchiveBuffer(MemoryBufferRef MB, StringRef SymName,
147                                     StringRef ParentName) {
148   file_magic Magic = identify_magic(MB.getBuffer());
149   if (Magic == file_magic::coff_import_library) {
150     Symtab.addFile(make<ImportFile>(MB));
151     return;
152   }
153
154   InputFile *Obj;
155   if (Magic == file_magic::coff_object) {
156     Obj = make<ObjectFile>(MB);
157   } else if (Magic == file_magic::bitcode) {
158     Obj = make<BitcodeFile>(MB);
159   } else {
160     error("unknown file type: " + MB.getBufferIdentifier());
161     return;
162   }
163
164   Obj->ParentName = ParentName;
165   Symtab.addFile(Obj);
166   log("Loaded " + toString(Obj) + " for " + SymName);
167 }
168
169 void LinkerDriver::enqueueArchiveMember(const Archive::Child &C,
170                                         StringRef SymName,
171                                         StringRef ParentName) {
172   if (!C.getParent()->isThin()) {
173     MemoryBufferRef MB = check(
174         C.getMemoryBufferRef(),
175         "could not get the buffer for the member defining symbol " + SymName);
176     enqueueTask([=]() { Driver->addArchiveBuffer(MB, SymName, ParentName); });
177     return;
178   }
179
180   auto Future = std::make_shared<std::future<MBErrPair>>(createFutureForFile(
181       check(C.getFullName(),
182             "could not get the filename for the member defining symbol " +
183                 SymName)));
184   enqueueTask([=]() {
185     auto MBOrErr = Future->get();
186     if (MBOrErr.second)
187       fatal(MBOrErr.second,
188             "could not get the buffer for the member defining " + SymName);
189     Driver->addArchiveBuffer(takeBuffer(std::move(MBOrErr.first)), SymName,
190                              ParentName);
191   });
192 }
193
194 static bool isDecorated(StringRef Sym) {
195   return Sym.startswith("_") || Sym.startswith("@") || Sym.startswith("?");
196 }
197
198 // Parses .drectve section contents and returns a list of files
199 // specified by /defaultlib.
200 void LinkerDriver::parseDirectives(StringRef S) {
201   opt::InputArgList Args = Parser.parse(S);
202
203   for (auto *Arg : Args) {
204     switch (Arg->getOption().getID()) {
205     case OPT_alternatename:
206       parseAlternateName(Arg->getValue());
207       break;
208     case OPT_defaultlib:
209       if (Optional<StringRef> Path = findLib(Arg->getValue()))
210         enqueuePath(*Path);
211       break;
212     case OPT_export: {
213       Export E = parseExport(Arg->getValue());
214       E.Directives = true;
215       Config->Exports.push_back(E);
216       break;
217     }
218     case OPT_failifmismatch:
219       checkFailIfMismatch(Arg->getValue());
220       break;
221     case OPT_incl:
222       addUndefined(Arg->getValue());
223       break;
224     case OPT_merge:
225       parseMerge(Arg->getValue());
226       break;
227     case OPT_nodefaultlib:
228       Config->NoDefaultLibs.insert(doFindLib(Arg->getValue()));
229       break;
230     case OPT_section:
231       parseSection(Arg->getValue());
232       break;
233     case OPT_editandcontinue:
234     case OPT_fastfail:
235     case OPT_guardsym:
236     case OPT_throwingnew:
237       break;
238     default:
239       error(Arg->getSpelling() + " is not allowed in .drectve");
240     }
241   }
242 }
243
244 // Find file from search paths. You can omit ".obj", this function takes
245 // care of that. Note that the returned path is not guaranteed to exist.
246 StringRef LinkerDriver::doFindFile(StringRef Filename) {
247   bool HasPathSep = (Filename.find_first_of("/\\") != StringRef::npos);
248   if (HasPathSep)
249     return Filename;
250   bool HasExt = (Filename.find('.') != StringRef::npos);
251   for (StringRef Dir : SearchPaths) {
252     SmallString<128> Path = Dir;
253     sys::path::append(Path, Filename);
254     if (sys::fs::exists(Path.str()))
255       return Saver.save(Path.str());
256     if (!HasExt) {
257       Path.append(".obj");
258       if (sys::fs::exists(Path.str()))
259         return Saver.save(Path.str());
260     }
261   }
262   return Filename;
263 }
264
265 // Resolves a file path. This never returns the same path
266 // (in that case, it returns None).
267 Optional<StringRef> LinkerDriver::findFile(StringRef Filename) {
268   StringRef Path = doFindFile(Filename);
269   bool Seen = !VisitedFiles.insert(Path.lower()).second;
270   if (Seen)
271     return None;
272   return Path;
273 }
274
275 // Find library file from search path.
276 StringRef LinkerDriver::doFindLib(StringRef Filename) {
277   // Add ".lib" to Filename if that has no file extension.
278   bool HasExt = (Filename.find('.') != StringRef::npos);
279   if (!HasExt)
280     Filename = Saver.save(Filename + ".lib");
281   return doFindFile(Filename);
282 }
283
284 // Resolves a library path. /nodefaultlib options are taken into
285 // consideration. This never returns the same path (in that case,
286 // it returns None).
287 Optional<StringRef> LinkerDriver::findLib(StringRef Filename) {
288   if (Config->NoDefaultLibAll)
289     return None;
290   if (!VisitedLibs.insert(Filename.lower()).second)
291     return None;
292   StringRef Path = doFindLib(Filename);
293   if (Config->NoDefaultLibs.count(Path))
294     return None;
295   if (!VisitedFiles.insert(Path.lower()).second)
296     return None;
297   return Path;
298 }
299
300 // Parses LIB environment which contains a list of search paths.
301 void LinkerDriver::addLibSearchPaths() {
302   Optional<std::string> EnvOpt = Process::GetEnv("LIB");
303   if (!EnvOpt.hasValue())
304     return;
305   StringRef Env = Saver.save(*EnvOpt);
306   while (!Env.empty()) {
307     StringRef Path;
308     std::tie(Path, Env) = Env.split(';');
309     SearchPaths.push_back(Path);
310   }
311 }
312
313 SymbolBody *LinkerDriver::addUndefined(StringRef Name) {
314   SymbolBody *B = Symtab.addUndefined(Name);
315   Config->GCRoot.insert(B);
316   return B;
317 }
318
319 // Symbol names are mangled by appending "_" prefix on x86.
320 StringRef LinkerDriver::mangle(StringRef Sym) {
321   assert(Config->Machine != IMAGE_FILE_MACHINE_UNKNOWN);
322   if (Config->Machine == I386)
323     return Saver.save("_" + Sym);
324   return Sym;
325 }
326
327 // Windows specific -- find default entry point name.
328 StringRef LinkerDriver::findDefaultEntry() {
329   // User-defined main functions and their corresponding entry points.
330   static const char *Entries[][2] = {
331       {"main", "mainCRTStartup"},
332       {"wmain", "wmainCRTStartup"},
333       {"WinMain", "WinMainCRTStartup"},
334       {"wWinMain", "wWinMainCRTStartup"},
335   };
336   for (auto E : Entries) {
337     StringRef Entry = Symtab.findMangle(mangle(E[0]));
338     if (!Entry.empty() && !isa<Undefined>(Symtab.find(Entry)->body()))
339       return mangle(E[1]);
340   }
341   return "";
342 }
343
344 WindowsSubsystem LinkerDriver::inferSubsystem() {
345   if (Config->DLL)
346     return IMAGE_SUBSYSTEM_WINDOWS_GUI;
347   if (Symtab.findUnderscore("main") || Symtab.findUnderscore("wmain"))
348     return IMAGE_SUBSYSTEM_WINDOWS_CUI;
349   if (Symtab.findUnderscore("WinMain") || Symtab.findUnderscore("wWinMain"))
350     return IMAGE_SUBSYSTEM_WINDOWS_GUI;
351   return IMAGE_SUBSYSTEM_UNKNOWN;
352 }
353
354 static uint64_t getDefaultImageBase() {
355   if (Config->is64())
356     return Config->DLL ? 0x180000000 : 0x140000000;
357   return Config->DLL ? 0x10000000 : 0x400000;
358 }
359
360 static std::string createResponseFile(const opt::InputArgList &Args,
361                                       ArrayRef<StringRef> FilePaths,
362                                       ArrayRef<StringRef> SearchPaths) {
363   SmallString<0> Data;
364   raw_svector_ostream OS(Data);
365
366   for (auto *Arg : Args) {
367     switch (Arg->getOption().getID()) {
368     case OPT_linkrepro:
369     case OPT_INPUT:
370     case OPT_defaultlib:
371     case OPT_libpath:
372       break;
373     default:
374       OS << toString(Arg) << "\n";
375     }
376   }
377
378   for (StringRef Path : SearchPaths) {
379     std::string RelPath = relativeToRoot(Path);
380     OS << "/libpath:" << quote(RelPath) << "\n";
381   }
382
383   for (StringRef Path : FilePaths)
384     OS << quote(relativeToRoot(Path)) << "\n";
385
386   return Data.str();
387 }
388
389 static unsigned getDefaultDebugType(const opt::InputArgList &Args) {
390   unsigned DebugTypes = static_cast<unsigned>(DebugType::CV);
391   if (Args.hasArg(OPT_driver))
392     DebugTypes |= static_cast<unsigned>(DebugType::PData);
393   if (Args.hasArg(OPT_profile))
394     DebugTypes |= static_cast<unsigned>(DebugType::Fixup);
395   return DebugTypes;
396 }
397
398 static unsigned parseDebugType(StringRef Arg) {
399   SmallVector<StringRef, 3> Types;
400   Arg.split(Types, ',', /*KeepEmpty=*/false);
401
402   unsigned DebugTypes = static_cast<unsigned>(DebugType::None);
403   for (StringRef Type : Types)
404     DebugTypes |= StringSwitch<unsigned>(Type.lower())
405                       .Case("cv", static_cast<unsigned>(DebugType::CV))
406                       .Case("pdata", static_cast<unsigned>(DebugType::PData))
407                       .Case("fixup", static_cast<unsigned>(DebugType::Fixup))
408                       .Default(0);
409   return DebugTypes;
410 }
411
412 static std::string getMapFile(const opt::InputArgList &Args) {
413   auto *Arg = Args.getLastArg(OPT_lldmap, OPT_lldmap_file);
414   if (!Arg)
415     return "";
416   if (Arg->getOption().getID() == OPT_lldmap_file)
417     return Arg->getValue();
418
419   assert(Arg->getOption().getID() == OPT_lldmap);
420   StringRef OutFile = Config->OutputFile;
421   return (OutFile.substr(0, OutFile.rfind('.')) + ".map").str();
422 }
423
424 static std::string getImplibPath() {
425   if (!Config->Implib.empty())
426     return Config->Implib;
427   SmallString<128> Out = StringRef(Config->OutputFile);
428   sys::path::replace_extension(Out, ".lib");
429   return Out.str();
430 }
431
432 //
433 // The import name is caculated as the following:
434 //
435 //        | LIBRARY w/ ext |   LIBRARY w/o ext   | no LIBRARY
436 //   -----+----------------+---------------------+------------------
437 //   LINK | {value}        | {value}.{.dll/.exe} | {output name}
438 //    LIB | {value}        | {value}.dll         | {output name}.dll
439 //
440 static std::string getImportName(bool AsLib) {
441   SmallString<128> Out;
442
443   if (Config->ImportName.empty()) {
444     Out.assign(sys::path::filename(Config->OutputFile));
445     if (AsLib)
446       sys::path::replace_extension(Out, ".dll");
447   } else {
448     Out.assign(Config->ImportName);
449     if (!sys::path::has_extension(Out))
450       sys::path::replace_extension(Out,
451                                    (Config->DLL || AsLib) ? ".dll" : ".exe");
452   }
453
454   return Out.str();
455 }
456
457 static void createImportLibrary(bool AsLib) {
458   std::vector<COFFShortExport> Exports;
459   for (Export &E1 : Config->Exports) {
460     COFFShortExport E2;
461     // Use SymbolName, which will have any stdcall or fastcall qualifiers.
462     E2.Name = E1.SymbolName;
463     E2.ExtName = E1.ExtName;
464     E2.Ordinal = E1.Ordinal;
465     E2.Noname = E1.Noname;
466     E2.Data = E1.Data;
467     E2.Private = E1.Private;
468     E2.Constant = E1.Constant;
469     Exports.push_back(E2);
470   }
471
472   writeImportLibrary(getImportName(AsLib), getImplibPath(), Exports,
473                      Config->Machine);
474 }
475
476 static void parseModuleDefs(StringRef Path) {
477   std::unique_ptr<MemoryBuffer> MB = check(
478     MemoryBuffer::getFile(Path, -1, false, true), "could not open " + Path);
479   COFFModuleDefinition M =
480       check(parseCOFFModuleDefinition(MB->getMemBufferRef(), Config->Machine));
481
482   if (Config->OutputFile.empty())
483     Config->OutputFile = Saver.save(M.OutputFile);
484   Config->ImportName = Saver.save(M.ImportName);
485   if (M.ImageBase)
486     Config->ImageBase = M.ImageBase;
487   if (M.StackReserve)
488     Config->StackReserve = M.StackReserve;
489   if (M.StackCommit)
490     Config->StackCommit = M.StackCommit;
491   if (M.HeapReserve)
492     Config->HeapReserve = M.HeapReserve;
493   if (M.HeapCommit)
494     Config->HeapCommit = M.HeapCommit;
495   if (M.MajorImageVersion)
496     Config->MajorImageVersion = M.MajorImageVersion;
497   if (M.MinorImageVersion)
498     Config->MinorImageVersion = M.MinorImageVersion;
499   if (M.MajorOSVersion)
500     Config->MajorOSVersion = M.MajorOSVersion;
501   if (M.MinorOSVersion)
502     Config->MinorOSVersion = M.MinorOSVersion;
503
504   for (COFFShortExport E1 : M.Exports) {
505     Export E2;
506     E2.Name = Saver.save(E1.Name);
507     if (E1.isWeak())
508       E2.ExtName = Saver.save(E1.ExtName);
509     E2.Ordinal = E1.Ordinal;
510     E2.Noname = E1.Noname;
511     E2.Data = E1.Data;
512     E2.Private = E1.Private;
513     E2.Constant = E1.Constant;
514     Config->Exports.push_back(E2);
515   }
516 }
517
518 std::vector<MemoryBufferRef> getArchiveMembers(Archive *File) {
519   std::vector<MemoryBufferRef> V;
520   Error Err = Error::success();
521   for (const ErrorOr<Archive::Child> &COrErr : File->children(Err)) {
522     Archive::Child C =
523         check(COrErr,
524               File->getFileName() + ": could not get the child of the archive");
525     MemoryBufferRef MBRef =
526         check(C.getMemoryBufferRef(),
527               File->getFileName() +
528                   ": could not get the buffer for a child of the archive");
529     V.push_back(MBRef);
530   }
531   if (Err)
532     fatal(File->getFileName() +
533           ": Archive::children failed: " + toString(std::move(Err)));
534   return V;
535 }
536
537 // A helper function for filterBitcodeFiles.
538 static bool needsRebuilding(MemoryBufferRef MB) {
539   // The MSVC linker doesn't support thin archives, so if it's a thin
540   // archive, we always need to rebuild it.
541   std::unique_ptr<Archive> File =
542       check(Archive::create(MB), "Failed to read " + MB.getBufferIdentifier());
543   if (File->isThin())
544     return true;
545
546   // Returns true if the archive contains at least one bitcode file.
547   for (MemoryBufferRef Member : getArchiveMembers(File.get()))
548     if (identify_magic(Member.getBuffer()) == file_magic::bitcode)
549       return true;
550   return false;
551 }
552
553 // Opens a given path as an archive file and removes bitcode files
554 // from them if exists. This function is to appease the MSVC linker as
555 // their linker doesn't like archive files containing non-native
556 // object files.
557 //
558 // If a given archive doesn't contain bitcode files, the archive path
559 // is returned as-is. Otherwise, a new temporary file is created and
560 // its path is returned.
561 static Optional<std::string>
562 filterBitcodeFiles(StringRef Path, std::vector<std::string> &TemporaryFiles) {
563   std::unique_ptr<MemoryBuffer> MB = check(
564       MemoryBuffer::getFile(Path, -1, false, true), "could not open " + Path);
565   MemoryBufferRef MBRef = MB->getMemBufferRef();
566   file_magic Magic = identify_magic(MBRef.getBuffer());
567
568   if (Magic == file_magic::bitcode)
569     return None;
570   if (Magic != file_magic::archive)
571     return Path.str();
572   if (!needsRebuilding(MBRef))
573     return Path.str();
574
575   std::unique_ptr<Archive> File =
576       check(Archive::create(MBRef),
577             MBRef.getBufferIdentifier() + ": failed to parse archive");
578
579   std::vector<NewArchiveMember> New;
580   for (MemoryBufferRef Member : getArchiveMembers(File.get()))
581     if (identify_magic(Member.getBuffer()) != file_magic::bitcode)
582       New.emplace_back(Member);
583
584   if (New.empty())
585     return None;
586
587   log("Creating a temporary archive for " + Path + " to remove bitcode files");
588
589   SmallString<128> S;
590   if (auto EC = sys::fs::createTemporaryFile("lld-" + sys::path::stem(Path),
591                                              ".lib", S))
592     fatal(EC, "cannot create a temporary file");
593   std::string Temp = S.str();
594   TemporaryFiles.push_back(Temp);
595
596   std::pair<StringRef, std::error_code> Ret =
597       llvm::writeArchive(Temp, New, /*WriteSymtab=*/true, Archive::Kind::K_GNU,
598                          /*Deterministics=*/true,
599                          /*Thin=*/false);
600   if (Ret.second)
601     error("failed to create a new archive " + S.str() + ": " + Ret.first);
602   return Temp;
603 }
604
605 // Create response file contents and invoke the MSVC linker.
606 void LinkerDriver::invokeMSVC(opt::InputArgList &Args) {
607   std::string Rsp = "/nologo\n";
608   std::vector<std::string> Temps;
609
610   // Write out archive members that we used in symbol resolution and pass these
611   // to MSVC before any archives, so that MSVC uses the same objects to satisfy
612   // references.
613   for (const auto *O : Symtab.ObjectFiles) {
614     if (O->ParentName.empty())
615       continue;
616     SmallString<128> S;
617     int Fd;
618     if (auto EC = sys::fs::createTemporaryFile(
619             "lld-" + sys::path::filename(O->ParentName), ".obj", Fd, S))
620       fatal(EC, "cannot create a temporary file");
621     raw_fd_ostream OS(Fd, /*shouldClose*/ true);
622     OS << O->MB.getBuffer();
623     Temps.push_back(S.str());
624     Rsp += quote(S) + "\n";
625   }
626
627   for (auto *Arg : Args) {
628     switch (Arg->getOption().getID()) {
629     case OPT_linkrepro:
630     case OPT_lldmap:
631     case OPT_lldmap_file:
632     case OPT_lldsavetemps:
633     case OPT_msvclto:
634       // LLD-specific options are stripped.
635       break;
636     case OPT_opt:
637       if (!StringRef(Arg->getValue()).startswith("lld"))
638         Rsp += toString(Arg) + " ";
639       break;
640     case OPT_INPUT: {
641       if (Optional<StringRef> Path = doFindFile(Arg->getValue())) {
642         if (Optional<std::string> S = filterBitcodeFiles(*Path, Temps))
643           Rsp += quote(*S) + "\n";
644         continue;
645       }
646       Rsp += quote(Arg->getValue()) + "\n";
647       break;
648     }
649     default:
650       Rsp += toString(Arg) + "\n";
651     }
652   }
653
654   std::vector<StringRef> ObjectFiles = Symtab.compileBitcodeFiles();
655   runMSVCLinker(Rsp, ObjectFiles);
656
657   for (StringRef Path : Temps)
658     sys::fs::remove(Path);
659 }
660
661 void LinkerDriver::enqueueTask(std::function<void()> Task) {
662   TaskQueue.push_back(std::move(Task));
663 }
664
665 bool LinkerDriver::run() {
666   bool DidWork = !TaskQueue.empty();
667   while (!TaskQueue.empty()) {
668     TaskQueue.front()();
669     TaskQueue.pop_front();
670   }
671   return DidWork;
672 }
673
674 void LinkerDriver::link(ArrayRef<const char *> ArgsArr) {
675   // If the first command line argument is "/lib", link.exe acts like lib.exe.
676   // We call our own implementation of lib.exe that understands bitcode files.
677   if (ArgsArr.size() > 1 && StringRef(ArgsArr[1]).equals_lower("/lib")) {
678     if (llvm::libDriverMain(ArgsArr.slice(1)) != 0)
679       fatal("lib failed");
680     return;
681   }
682
683   // Needed for LTO.
684   InitializeAllTargetInfos();
685   InitializeAllTargets();
686   InitializeAllTargetMCs();
687   InitializeAllAsmParsers();
688   InitializeAllAsmPrinters();
689   InitializeAllDisassemblers();
690
691   // Parse command line options.
692   opt::InputArgList Args = Parser.parseLINK(ArgsArr.slice(1));
693
694   // Parse and evaluate -mllvm options.
695   std::vector<const char *> V;
696   V.push_back("lld-link (LLVM option parsing)");
697   for (auto *Arg : Args.filtered(OPT_mllvm))
698     V.push_back(Arg->getValue());
699   cl::ParseCommandLineOptions(V.size(), V.data());
700
701   // Handle /errorlimit early, because error() depends on it.
702   if (auto *Arg = Args.getLastArg(OPT_errorlimit)) {
703     int N = 20;
704     StringRef S = Arg->getValue();
705     if (S.getAsInteger(10, N))
706       error(Arg->getSpelling() + " number expected, but got " + S);
707     Config->ErrorLimit = N;
708   }
709
710   // Handle /help
711   if (Args.hasArg(OPT_help)) {
712     printHelp(ArgsArr[0]);
713     return;
714   }
715
716   if (auto *Arg = Args.getLastArg(OPT_linkrepro)) {
717     SmallString<64> Path = StringRef(Arg->getValue());
718     sys::path::append(Path, "repro.tar");
719
720     Expected<std::unique_ptr<TarWriter>> ErrOrWriter =
721         TarWriter::create(Path, "repro");
722
723     if (ErrOrWriter) {
724       Tar = std::move(*ErrOrWriter);
725     } else {
726       error("/linkrepro: failed to open " + Path + ": " +
727             toString(ErrOrWriter.takeError()));
728     }
729   }
730
731   if (!Args.hasArgNoClaim(OPT_INPUT)) {
732     if (Args.hasArgNoClaim(OPT_deffile))
733       Config->NoEntry = true;
734     else
735       fatal("no input files");
736   }
737
738   // Construct search path list.
739   SearchPaths.push_back("");
740   for (auto *Arg : Args.filtered(OPT_libpath))
741     SearchPaths.push_back(Arg->getValue());
742   addLibSearchPaths();
743
744   // Handle /out
745   if (auto *Arg = Args.getLastArg(OPT_out))
746     Config->OutputFile = Arg->getValue();
747
748   // Handle /verbose
749   if (Args.hasArg(OPT_verbose))
750     Config->Verbose = true;
751
752   // Handle /force or /force:unresolved
753   if (Args.hasArg(OPT_force) || Args.hasArg(OPT_force_unresolved))
754     Config->Force = true;
755
756   // Handle /debug
757   if (Args.hasArg(OPT_debug)) {
758     Config->Debug = true;
759     Config->DebugTypes =
760         Args.hasArg(OPT_debugtype)
761             ? parseDebugType(Args.getLastArg(OPT_debugtype)->getValue())
762             : getDefaultDebugType(Args);
763   }
764
765   // Create a dummy PDB file to satisfy build sytem rules.
766   if (auto *Arg = Args.getLastArg(OPT_pdb))
767     Config->PDBPath = Arg->getValue();
768
769   // Handle /noentry
770   if (Args.hasArg(OPT_noentry)) {
771     if (Args.hasArg(OPT_dll))
772       Config->NoEntry = true;
773     else
774       error("/noentry must be specified with /dll");
775   }
776
777   // Handle /dll
778   if (Args.hasArg(OPT_dll)) {
779     Config->DLL = true;
780     Config->ManifestID = 2;
781   }
782
783   // Handle /fixed
784   if (Args.hasArg(OPT_fixed)) {
785     if (Args.hasArg(OPT_dynamicbase)) {
786       error("/fixed must not be specified with /dynamicbase");
787     } else {
788       Config->Relocatable = false;
789       Config->DynamicBase = false;
790     }
791   }
792
793   if (Args.hasArg(OPT_appcontainer))
794     Config->AppContainer = true;
795
796   // Handle /machine
797   if (auto *Arg = Args.getLastArg(OPT_machine))
798     Config->Machine = getMachineType(Arg->getValue());
799
800   // Handle /nodefaultlib:<filename>
801   for (auto *Arg : Args.filtered(OPT_nodefaultlib))
802     Config->NoDefaultLibs.insert(doFindLib(Arg->getValue()));
803
804   // Handle /nodefaultlib
805   if (Args.hasArg(OPT_nodefaultlib_all))
806     Config->NoDefaultLibAll = true;
807
808   // Handle /base
809   if (auto *Arg = Args.getLastArg(OPT_base))
810     parseNumbers(Arg->getValue(), &Config->ImageBase);
811
812   // Handle /stack
813   if (auto *Arg = Args.getLastArg(OPT_stack))
814     parseNumbers(Arg->getValue(), &Config->StackReserve, &Config->StackCommit);
815
816   // Handle /heap
817   if (auto *Arg = Args.getLastArg(OPT_heap))
818     parseNumbers(Arg->getValue(), &Config->HeapReserve, &Config->HeapCommit);
819
820   // Handle /version
821   if (auto *Arg = Args.getLastArg(OPT_version))
822     parseVersion(Arg->getValue(), &Config->MajorImageVersion,
823                  &Config->MinorImageVersion);
824
825   // Handle /subsystem
826   if (auto *Arg = Args.getLastArg(OPT_subsystem))
827     parseSubsystem(Arg->getValue(), &Config->Subsystem, &Config->MajorOSVersion,
828                    &Config->MinorOSVersion);
829
830   // Handle /alternatename
831   for (auto *Arg : Args.filtered(OPT_alternatename))
832     parseAlternateName(Arg->getValue());
833
834   // Handle /include
835   for (auto *Arg : Args.filtered(OPT_incl))
836     addUndefined(Arg->getValue());
837
838   // Handle /implib
839   if (auto *Arg = Args.getLastArg(OPT_implib))
840     Config->Implib = Arg->getValue();
841
842   // Handle /opt
843   for (auto *Arg : Args.filtered(OPT_opt)) {
844     std::string Str = StringRef(Arg->getValue()).lower();
845     SmallVector<StringRef, 1> Vec;
846     StringRef(Str).split(Vec, ',');
847     for (StringRef S : Vec) {
848       if (S == "noref") {
849         Config->DoGC = false;
850         Config->DoICF = false;
851         continue;
852       }
853       if (S == "icf" || StringRef(S).startswith("icf=")) {
854         Config->DoICF = true;
855         continue;
856       }
857       if (S == "noicf") {
858         Config->DoICF = false;
859         continue;
860       }
861       if (StringRef(S).startswith("lldlto=")) {
862         StringRef OptLevel = StringRef(S).substr(7);
863         if (OptLevel.getAsInteger(10, Config->LTOOptLevel) ||
864             Config->LTOOptLevel > 3)
865           error("/opt:lldlto: invalid optimization level: " + OptLevel);
866         continue;
867       }
868       if (StringRef(S).startswith("lldltojobs=")) {
869         StringRef Jobs = StringRef(S).substr(11);
870         if (Jobs.getAsInteger(10, Config->LTOJobs) || Config->LTOJobs == 0)
871           error("/opt:lldltojobs: invalid job count: " + Jobs);
872         continue;
873       }
874       if (StringRef(S).startswith("lldltopartitions=")) {
875         StringRef N = StringRef(S).substr(17);
876         if (N.getAsInteger(10, Config->LTOPartitions) ||
877             Config->LTOPartitions == 0)
878           error("/opt:lldltopartitions: invalid partition count: " + N);
879         continue;
880       }
881       if (S != "ref" && S != "lbr" && S != "nolbr")
882         error("/opt: unknown option: " + S);
883     }
884   }
885
886   // Handle /lldsavetemps
887   if (Args.hasArg(OPT_lldsavetemps))
888     Config->SaveTemps = true;
889
890   // Handle /failifmismatch
891   for (auto *Arg : Args.filtered(OPT_failifmismatch))
892     checkFailIfMismatch(Arg->getValue());
893
894   // Handle /merge
895   for (auto *Arg : Args.filtered(OPT_merge))
896     parseMerge(Arg->getValue());
897
898   // Handle /section
899   for (auto *Arg : Args.filtered(OPT_section))
900     parseSection(Arg->getValue());
901
902   // Handle /manifest
903   if (auto *Arg = Args.getLastArg(OPT_manifest_colon))
904     parseManifest(Arg->getValue());
905
906   // Handle /manifestuac
907   if (auto *Arg = Args.getLastArg(OPT_manifestuac))
908     parseManifestUAC(Arg->getValue());
909
910   // Handle /manifestdependency
911   if (auto *Arg = Args.getLastArg(OPT_manifestdependency))
912     Config->ManifestDependency = Arg->getValue();
913
914   // Handle /manifestfile
915   if (auto *Arg = Args.getLastArg(OPT_manifestfile))
916     Config->ManifestFile = Arg->getValue();
917
918   // Handle /manifestinput
919   for (auto *Arg : Args.filtered(OPT_manifestinput))
920     Config->ManifestInput.push_back(Arg->getValue());
921
922   // Handle miscellaneous boolean flags.
923   if (Args.hasArg(OPT_allowisolation_no))
924     Config->AllowIsolation = false;
925   if (Args.hasArg(OPT_dynamicbase_no))
926     Config->DynamicBase = false;
927   if (Args.hasArg(OPT_nxcompat_no))
928     Config->NxCompat = false;
929   if (Args.hasArg(OPT_tsaware_no))
930     Config->TerminalServerAware = false;
931   if (Args.hasArg(OPT_nosymtab))
932     Config->WriteSymtab = false;
933
934   Config->MapFile = getMapFile(Args);
935
936   if (ErrorCount)
937     return;
938
939   // Create a list of input files. Files can be given as arguments
940   // for /defaultlib option.
941   std::vector<MemoryBufferRef> MBs;
942   for (auto *Arg : Args.filtered(OPT_INPUT))
943     if (Optional<StringRef> Path = findFile(Arg->getValue()))
944       enqueuePath(*Path);
945   for (auto *Arg : Args.filtered(OPT_defaultlib))
946     if (Optional<StringRef> Path = findLib(Arg->getValue()))
947       enqueuePath(*Path);
948
949   // Windows specific -- Create a resource file containing a manifest file.
950   if (Config->Manifest == Configuration::Embed)
951     addBuffer(createManifestRes());
952
953   // Read all input files given via the command line.
954   run();
955
956   // We should have inferred a machine type by now from the input files, but if
957   // not we assume x64.
958   if (Config->Machine == IMAGE_FILE_MACHINE_UNKNOWN) {
959     warn("/machine is not specified. x64 is assumed");
960     Config->Machine = AMD64;
961   }
962
963   // Input files can be Windows resource files (.res files). We use
964   // WindowsResource to convert resource files to a regular COFF file,
965   // then link the resulting file normally.
966   if (!Resources.empty())
967     addBuffer(convertResToCOFF(Resources));
968
969   if (Tar)
970     Tar->append("response.txt",
971                 createResponseFile(Args, FilePaths,
972                                    ArrayRef<StringRef>(SearchPaths).slice(1)));
973
974   // Handle /largeaddressaware
975   if (Config->is64() || Args.hasArg(OPT_largeaddressaware))
976     Config->LargeAddressAware = true;
977
978   // Handle /highentropyva
979   if (Config->is64() && !Args.hasArg(OPT_highentropyva_no))
980     Config->HighEntropyVA = true;
981
982   // Handle /entry and /dll
983   if (auto *Arg = Args.getLastArg(OPT_entry)) {
984     Config->Entry = addUndefined(mangle(Arg->getValue()));
985   } else if (Args.hasArg(OPT_dll) && !Config->NoEntry) {
986     StringRef S = (Config->Machine == I386) ? "__DllMainCRTStartup@12"
987                                             : "_DllMainCRTStartup";
988     Config->Entry = addUndefined(S);
989   } else if (!Config->NoEntry) {
990     // Windows specific -- If entry point name is not given, we need to
991     // infer that from user-defined entry name.
992     StringRef S = findDefaultEntry();
993     if (S.empty())
994       fatal("entry point must be defined");
995     Config->Entry = addUndefined(S);
996     log("Entry name inferred: " + S);
997   }
998
999   // Handle /export
1000   for (auto *Arg : Args.filtered(OPT_export)) {
1001     Export E = parseExport(Arg->getValue());
1002     if (Config->Machine == I386) {
1003       if (!isDecorated(E.Name))
1004         E.Name = Saver.save("_" + E.Name);
1005       if (!E.ExtName.empty() && !isDecorated(E.ExtName))
1006         E.ExtName = Saver.save("_" + E.ExtName);
1007     }
1008     Config->Exports.push_back(E);
1009   }
1010
1011   // Handle /def
1012   if (auto *Arg = Args.getLastArg(OPT_deffile)) {
1013     // parseModuleDefs mutates Config object.
1014     parseModuleDefs(Arg->getValue());
1015   }
1016
1017   // Handle generation of import library from a def file.
1018   if (!Args.hasArgNoClaim(OPT_INPUT)) {
1019     fixupExports();
1020     createImportLibrary(/*AsLib=*/true);
1021     exit(0);
1022   }
1023
1024   // Handle /delayload
1025   for (auto *Arg : Args.filtered(OPT_delayload)) {
1026     Config->DelayLoads.insert(StringRef(Arg->getValue()).lower());
1027     if (Config->Machine == I386) {
1028       Config->DelayLoadHelper = addUndefined("___delayLoadHelper2@8");
1029     } else {
1030       Config->DelayLoadHelper = addUndefined("__delayLoadHelper2");
1031     }
1032   }
1033
1034   // Set default image name if neither /out or /def set it.
1035   if (Config->OutputFile.empty()) {
1036     Config->OutputFile =
1037         getOutputPath((*Args.filtered(OPT_INPUT).begin())->getValue());
1038   }
1039
1040   // Put the PDB next to the image if no /pdb flag was passed.
1041   if (Config->Debug && Config->PDBPath.empty()) {
1042     Config->PDBPath = Config->OutputFile;
1043     sys::path::replace_extension(Config->PDBPath, ".pdb");
1044   }
1045
1046   // Disable PDB generation if the user requested it.
1047   if (Args.hasArg(OPT_nopdb))
1048     Config->PDBPath = "";
1049
1050   // Set default image base if /base is not given.
1051   if (Config->ImageBase == uint64_t(-1))
1052     Config->ImageBase = getDefaultImageBase();
1053
1054   Symtab.addSynthetic(mangle("__ImageBase"), nullptr);
1055   if (Config->Machine == I386) {
1056     Symtab.addAbsolute("___safe_se_handler_table", 0);
1057     Symtab.addAbsolute("___safe_se_handler_count", 0);
1058   }
1059
1060   // We do not support /guard:cf (control flow protection) yet.
1061   // Define CFG symbols anyway so that we can link MSVC 2015 CRT.
1062   Symtab.addAbsolute(mangle("__guard_fids_count"), 0);
1063   Symtab.addAbsolute(mangle("__guard_fids_table"), 0);
1064   Symtab.addAbsolute(mangle("__guard_flags"), 0x100);
1065   Symtab.addAbsolute(mangle("__guard_iat_count"), 0);
1066   Symtab.addAbsolute(mangle("__guard_iat_table"), 0);
1067   Symtab.addAbsolute(mangle("__guard_longjmp_count"), 0);
1068   Symtab.addAbsolute(mangle("__guard_longjmp_table"), 0);
1069
1070   // This code may add new undefined symbols to the link, which may enqueue more
1071   // symbol resolution tasks, so we need to continue executing tasks until we
1072   // converge.
1073   do {
1074     // Windows specific -- if entry point is not found,
1075     // search for its mangled names.
1076     if (Config->Entry)
1077       Symtab.mangleMaybe(Config->Entry);
1078
1079     // Windows specific -- Make sure we resolve all dllexported symbols.
1080     for (Export &E : Config->Exports) {
1081       if (!E.ForwardTo.empty())
1082         continue;
1083       E.Sym = addUndefined(E.Name);
1084       if (!E.Directives)
1085         Symtab.mangleMaybe(E.Sym);
1086     }
1087
1088     // Add weak aliases. Weak aliases is a mechanism to give remaining
1089     // undefined symbols final chance to be resolved successfully.
1090     for (auto Pair : Config->AlternateNames) {
1091       StringRef From = Pair.first;
1092       StringRef To = Pair.second;
1093       Symbol *Sym = Symtab.find(From);
1094       if (!Sym)
1095         continue;
1096       if (auto *U = dyn_cast<Undefined>(Sym->body()))
1097         if (!U->WeakAlias)
1098           U->WeakAlias = Symtab.addUndefined(To);
1099     }
1100
1101     // Windows specific -- if __load_config_used can be resolved, resolve it.
1102     if (Symtab.findUnderscore("_load_config_used"))
1103       addUndefined(mangle("_load_config_used"));
1104   } while (run());
1105
1106   if (ErrorCount)
1107     return;
1108
1109   // If /msvclto is given, we use the MSVC linker to link LTO output files.
1110   // This is useful because MSVC link.exe can generate complete PDBs.
1111   if (Args.hasArg(OPT_msvclto)) {
1112     invokeMSVC(Args);
1113     exit(0);
1114   }
1115
1116   // Do LTO by compiling bitcode input files to a set of native COFF files then
1117   // link those files.
1118   Symtab.addCombinedLTOObjects();
1119   run();
1120
1121   // Make sure we have resolved all symbols.
1122   Symtab.reportRemainingUndefines();
1123
1124   // Windows specific -- if no /subsystem is given, we need to infer
1125   // that from entry point name.
1126   if (Config->Subsystem == IMAGE_SUBSYSTEM_UNKNOWN) {
1127     Config->Subsystem = inferSubsystem();
1128     if (Config->Subsystem == IMAGE_SUBSYSTEM_UNKNOWN)
1129       fatal("subsystem must be defined");
1130   }
1131
1132   // Handle /safeseh.
1133   if (Args.hasArg(OPT_safeseh)) {
1134     for (ObjectFile *File : Symtab.ObjectFiles)
1135       if (!File->SEHCompat)
1136         error("/safeseh: " + File->getName() + " is not compatible with SEH");
1137     if (ErrorCount)
1138       return;
1139   }
1140
1141   // Windows specific -- when we are creating a .dll file, we also
1142   // need to create a .lib file.
1143   if (!Config->Exports.empty() || Config->DLL) {
1144     fixupExports();
1145     createImportLibrary(/*AsLib=*/false);
1146     assignExportOrdinals();
1147   }
1148
1149   // Windows specific -- Create a side-by-side manifest file.
1150   if (Config->Manifest == Configuration::SideBySide)
1151     createSideBySideManifest();
1152
1153   // Identify unreferenced COMDAT sections.
1154   if (Config->DoGC)
1155     markLive(Symtab.getChunks());
1156
1157   // Identify identical COMDAT sections to merge them.
1158   if (Config->DoICF)
1159     doICF(Symtab.getChunks());
1160
1161   // Write the result.
1162   writeResult(&Symtab);
1163
1164   // Call exit to avoid calling destructors.
1165   exit(0);
1166 }
1167
1168 } // namespace coff
1169 } // namespace lld