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