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