]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/lld/COFF/Driver.cpp
Merge llvm, clang, lld and lldb trunk r300890, and update build glue.
[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   for (auto *Arg : Args) {
516     switch (Arg->getOption().getID()) {
517     case OPT_linkrepro:
518     case OPT_lldmap:
519     case OPT_lldmap_file:
520     case OPT_lldsavetemps:
521     case OPT_msvclto:
522       // LLD-specific options are stripped.
523       break;
524     case OPT_opt:
525       if (!StringRef(Arg->getValue()).startswith("lld"))
526         Rsp += toString(Arg) + " ";
527       break;
528     case OPT_INPUT: {
529       if (Optional<StringRef> Path = doFindFile(Arg->getValue())) {
530         if (Optional<std::string> S = filterBitcodeFiles(*Path, Temps))
531           Rsp += quote(*S) + "\n";
532         continue;
533       }
534       Rsp += quote(Arg->getValue()) + "\n";
535       break;
536     }
537     default:
538       Rsp += toString(Arg) + "\n";
539     }
540   }
541
542   std::vector<StringRef> ObjectFiles = Symtab.compileBitcodeFiles();
543   runMSVCLinker(Rsp, ObjectFiles);
544
545   for (StringRef Path : Temps)
546     sys::fs::remove(Path);
547 }
548
549 void LinkerDriver::enqueueTask(std::function<void()> Task) {
550   TaskQueue.push_back(std::move(Task));
551 }
552
553 bool LinkerDriver::run() {
554   bool DidWork = !TaskQueue.empty();
555   while (!TaskQueue.empty()) {
556     TaskQueue.front()();
557     TaskQueue.pop_front();
558   }
559   return DidWork;
560 }
561
562 void LinkerDriver::link(ArrayRef<const char *> ArgsArr) {
563   // If the first command line argument is "/lib", link.exe acts like lib.exe.
564   // We call our own implementation of lib.exe that understands bitcode files.
565   if (ArgsArr.size() > 1 && StringRef(ArgsArr[1]).equals_lower("/lib")) {
566     if (llvm::libDriverMain(ArgsArr.slice(1)) != 0)
567       fatal("lib failed");
568     return;
569   }
570
571   // Needed for LTO.
572   InitializeAllTargetInfos();
573   InitializeAllTargets();
574   InitializeAllTargetMCs();
575   InitializeAllAsmParsers();
576   InitializeAllAsmPrinters();
577   InitializeAllDisassemblers();
578
579   // Parse command line options.
580   opt::InputArgList Args = Parser.parseLINK(ArgsArr.slice(1));
581
582   // Parse and evaluate -mllvm options.
583   std::vector<const char *> V;
584   V.push_back("lld-link (LLVM option parsing)");
585   for (auto *Arg : Args.filtered(OPT_mllvm))
586     V.push_back(Arg->getValue());
587   cl::ParseCommandLineOptions(V.size(), V.data());
588
589   // Handle /errorlimit early, because error() depends on it.
590   if (auto *Arg = Args.getLastArg(OPT_errorlimit)) {
591     int N = 20;
592     StringRef S = Arg->getValue();
593     if (S.getAsInteger(10, N))
594       error(Arg->getSpelling() + " number expected, but got " + S);
595     Config->ErrorLimit = N;
596   }
597
598   // Handle /help
599   if (Args.hasArg(OPT_help)) {
600     printHelp(ArgsArr[0]);
601     return;
602   }
603
604   if (auto *Arg = Args.getLastArg(OPT_linkrepro)) {
605     SmallString<64> Path = StringRef(Arg->getValue());
606     sys::path::append(Path, "repro.tar");
607
608     Expected<std::unique_ptr<TarWriter>> ErrOrWriter =
609         TarWriter::create(Path, "repro");
610
611     if (ErrOrWriter) {
612       Tar = std::move(*ErrOrWriter);
613     } else {
614       error("/linkrepro: failed to open " + Path + ": " +
615             toString(ErrOrWriter.takeError()));
616     }
617   }
618
619   if (!Args.hasArgNoClaim(OPT_INPUT))
620     fatal("no input files");
621
622   // Construct search path list.
623   SearchPaths.push_back("");
624   for (auto *Arg : Args.filtered(OPT_libpath))
625     SearchPaths.push_back(Arg->getValue());
626   addLibSearchPaths();
627
628   // Handle /out
629   if (auto *Arg = Args.getLastArg(OPT_out))
630     Config->OutputFile = Arg->getValue();
631
632   // Handle /verbose
633   if (Args.hasArg(OPT_verbose))
634     Config->Verbose = true;
635
636   // Handle /force or /force:unresolved
637   if (Args.hasArg(OPT_force) || Args.hasArg(OPT_force_unresolved))
638     Config->Force = true;
639
640   // Handle /debug
641   if (Args.hasArg(OPT_debug)) {
642     Config->Debug = true;
643     Config->DebugTypes =
644         Args.hasArg(OPT_debugtype)
645             ? parseDebugType(Args.getLastArg(OPT_debugtype)->getValue())
646             : getDefaultDebugType(Args);
647   }
648
649   // Create a dummy PDB file to satisfy build sytem rules.
650   if (auto *Arg = Args.getLastArg(OPT_pdb))
651     Config->PDBPath = Arg->getValue();
652
653   // Handle /noentry
654   if (Args.hasArg(OPT_noentry)) {
655     if (Args.hasArg(OPT_dll))
656       Config->NoEntry = true;
657     else
658       error("/noentry must be specified with /dll");
659   }
660
661   // Handle /dll
662   if (Args.hasArg(OPT_dll)) {
663     Config->DLL = true;
664     Config->ManifestID = 2;
665   }
666
667   // Handle /fixed
668   if (Args.hasArg(OPT_fixed)) {
669     if (Args.hasArg(OPT_dynamicbase)) {
670       error("/fixed must not be specified with /dynamicbase");
671     } else {
672       Config->Relocatable = false;
673       Config->DynamicBase = false;
674     }
675   }
676
677   if (Args.hasArg(OPT_appcontainer))
678     Config->AppContainer = true;
679
680   // Handle /machine
681   if (auto *Arg = Args.getLastArg(OPT_machine))
682     Config->Machine = getMachineType(Arg->getValue());
683
684   // Handle /nodefaultlib:<filename>
685   for (auto *Arg : Args.filtered(OPT_nodefaultlib))
686     Config->NoDefaultLibs.insert(doFindLib(Arg->getValue()));
687
688   // Handle /nodefaultlib
689   if (Args.hasArg(OPT_nodefaultlib_all))
690     Config->NoDefaultLibAll = true;
691
692   // Handle /base
693   if (auto *Arg = Args.getLastArg(OPT_base))
694     parseNumbers(Arg->getValue(), &Config->ImageBase);
695
696   // Handle /stack
697   if (auto *Arg = Args.getLastArg(OPT_stack))
698     parseNumbers(Arg->getValue(), &Config->StackReserve, &Config->StackCommit);
699
700   // Handle /heap
701   if (auto *Arg = Args.getLastArg(OPT_heap))
702     parseNumbers(Arg->getValue(), &Config->HeapReserve, &Config->HeapCommit);
703
704   // Handle /version
705   if (auto *Arg = Args.getLastArg(OPT_version))
706     parseVersion(Arg->getValue(), &Config->MajorImageVersion,
707                  &Config->MinorImageVersion);
708
709   // Handle /subsystem
710   if (auto *Arg = Args.getLastArg(OPT_subsystem))
711     parseSubsystem(Arg->getValue(), &Config->Subsystem, &Config->MajorOSVersion,
712                    &Config->MinorOSVersion);
713
714   // Handle /alternatename
715   for (auto *Arg : Args.filtered(OPT_alternatename))
716     parseAlternateName(Arg->getValue());
717
718   // Handle /include
719   for (auto *Arg : Args.filtered(OPT_incl))
720     addUndefined(Arg->getValue());
721
722   // Handle /implib
723   if (auto *Arg = Args.getLastArg(OPT_implib))
724     Config->Implib = Arg->getValue();
725
726   // Handle /opt
727   for (auto *Arg : Args.filtered(OPT_opt)) {
728     std::string Str = StringRef(Arg->getValue()).lower();
729     SmallVector<StringRef, 1> Vec;
730     StringRef(Str).split(Vec, ',');
731     for (StringRef S : Vec) {
732       if (S == "noref") {
733         Config->DoGC = false;
734         Config->DoICF = false;
735         continue;
736       }
737       if (S == "icf" || StringRef(S).startswith("icf=")) {
738         Config->DoICF = true;
739         continue;
740       }
741       if (S == "noicf") {
742         Config->DoICF = false;
743         continue;
744       }
745       if (StringRef(S).startswith("lldlto=")) {
746         StringRef OptLevel = StringRef(S).substr(7);
747         if (OptLevel.getAsInteger(10, Config->LTOOptLevel) ||
748             Config->LTOOptLevel > 3)
749           error("/opt:lldlto: invalid optimization level: " + OptLevel);
750         continue;
751       }
752       if (StringRef(S).startswith("lldltojobs=")) {
753         StringRef Jobs = StringRef(S).substr(11);
754         if (Jobs.getAsInteger(10, Config->LTOJobs) || Config->LTOJobs == 0)
755           error("/opt:lldltojobs: invalid job count: " + Jobs);
756         continue;
757       }
758       if (StringRef(S).startswith("lldltopartitions=")) {
759         StringRef N = StringRef(S).substr(17);
760         if (N.getAsInteger(10, Config->LTOPartitions) ||
761             Config->LTOPartitions == 0)
762           error("/opt:lldltopartitions: invalid partition count: " + N);
763         continue;
764       }
765       if (S != "ref" && S != "lbr" && S != "nolbr")
766         error("/opt: unknown option: " + S);
767     }
768   }
769
770   // Handle /lldsavetemps
771   if (Args.hasArg(OPT_lldsavetemps))
772     Config->SaveTemps = true;
773
774   // Handle /failifmismatch
775   for (auto *Arg : Args.filtered(OPT_failifmismatch))
776     checkFailIfMismatch(Arg->getValue());
777
778   // Handle /merge
779   for (auto *Arg : Args.filtered(OPT_merge))
780     parseMerge(Arg->getValue());
781
782   // Handle /section
783   for (auto *Arg : Args.filtered(OPT_section))
784     parseSection(Arg->getValue());
785
786   // Handle /manifest
787   if (auto *Arg = Args.getLastArg(OPT_manifest_colon))
788     parseManifest(Arg->getValue());
789
790   // Handle /manifestuac
791   if (auto *Arg = Args.getLastArg(OPT_manifestuac))
792     parseManifestUAC(Arg->getValue());
793
794   // Handle /manifestdependency
795   if (auto *Arg = Args.getLastArg(OPT_manifestdependency))
796     Config->ManifestDependency = Arg->getValue();
797
798   // Handle /manifestfile
799   if (auto *Arg = Args.getLastArg(OPT_manifestfile))
800     Config->ManifestFile = Arg->getValue();
801
802   // Handle /manifestinput
803   for (auto *Arg : Args.filtered(OPT_manifestinput))
804     Config->ManifestInput.push_back(Arg->getValue());
805
806   // Handle miscellaneous boolean flags.
807   if (Args.hasArg(OPT_allowbind_no))
808     Config->AllowBind = false;
809   if (Args.hasArg(OPT_allowisolation_no))
810     Config->AllowIsolation = false;
811   if (Args.hasArg(OPT_dynamicbase_no))
812     Config->DynamicBase = false;
813   if (Args.hasArg(OPT_nxcompat_no))
814     Config->NxCompat = false;
815   if (Args.hasArg(OPT_tsaware_no))
816     Config->TerminalServerAware = false;
817   if (Args.hasArg(OPT_nosymtab))
818     Config->WriteSymtab = false;
819   Config->DumpPdb = Args.hasArg(OPT_dumppdb);
820   Config->DebugPdb = Args.hasArg(OPT_debugpdb);
821
822   Config->MapFile = getMapFile(Args);
823
824   if (ErrorCount)
825     return;
826
827   // Create a list of input files. Files can be given as arguments
828   // for /defaultlib option.
829   std::vector<MemoryBufferRef> MBs;
830   for (auto *Arg : Args.filtered(OPT_INPUT))
831     if (Optional<StringRef> Path = findFile(Arg->getValue()))
832       enqueuePath(*Path);
833   for (auto *Arg : Args.filtered(OPT_defaultlib))
834     if (Optional<StringRef> Path = findLib(Arg->getValue()))
835       enqueuePath(*Path);
836
837   // Windows specific -- Create a resource file containing a manifest file.
838   if (Config->Manifest == Configuration::Embed)
839     addBuffer(createManifestRes());
840
841   // Read all input files given via the command line.
842   run();
843
844   // We should have inferred a machine type by now from the input files, but if
845   // not we assume x64.
846   if (Config->Machine == IMAGE_FILE_MACHINE_UNKNOWN) {
847     warn("/machine is not specified. x64 is assumed");
848     Config->Machine = AMD64;
849   }
850
851   // Windows specific -- Input files can be Windows resource files (.res files).
852   // We invoke cvtres.exe to convert resource files to a regular COFF file
853   // then link the result file normally.
854   if (!Resources.empty())
855     addBuffer(convertResToCOFF(Resources));
856
857   if (Tar)
858     Tar->append("response.txt",
859                 createResponseFile(Args, FilePaths,
860                                    ArrayRef<StringRef>(SearchPaths).slice(1)));
861
862   // Handle /largeaddressaware
863   if (Config->is64() || Args.hasArg(OPT_largeaddressaware))
864     Config->LargeAddressAware = true;
865
866   // Handle /highentropyva
867   if (Config->is64() && !Args.hasArg(OPT_highentropyva_no))
868     Config->HighEntropyVA = true;
869
870   // Handle /entry and /dll
871   if (auto *Arg = Args.getLastArg(OPT_entry)) {
872     Config->Entry = addUndefined(mangle(Arg->getValue()));
873   } else if (Args.hasArg(OPT_dll) && !Config->NoEntry) {
874     StringRef S = (Config->Machine == I386) ? "__DllMainCRTStartup@12"
875                                             : "_DllMainCRTStartup";
876     Config->Entry = addUndefined(S);
877   } else if (!Config->NoEntry) {
878     // Windows specific -- If entry point name is not given, we need to
879     // infer that from user-defined entry name.
880     StringRef S = findDefaultEntry();
881     if (S.empty())
882       fatal("entry point must be defined");
883     Config->Entry = addUndefined(S);
884     log("Entry name inferred: " + S);
885   }
886
887   // Handle /export
888   for (auto *Arg : Args.filtered(OPT_export)) {
889     Export E = parseExport(Arg->getValue());
890     if (Config->Machine == I386) {
891       if (!isDecorated(E.Name))
892         E.Name = Saver.save("_" + E.Name);
893       if (!E.ExtName.empty() && !isDecorated(E.ExtName))
894         E.ExtName = Saver.save("_" + E.ExtName);
895     }
896     Config->Exports.push_back(E);
897   }
898
899   // Handle /def
900   if (auto *Arg = Args.getLastArg(OPT_deffile)) {
901     // parseModuleDefs mutates Config object.
902     parseModuleDefs(
903         takeBuffer(check(MemoryBuffer::getFile(Arg->getValue()),
904                          Twine("could not open ") + Arg->getValue())));
905   }
906
907   // Handle /delayload
908   for (auto *Arg : Args.filtered(OPT_delayload)) {
909     Config->DelayLoads.insert(StringRef(Arg->getValue()).lower());
910     if (Config->Machine == I386) {
911       Config->DelayLoadHelper = addUndefined("___delayLoadHelper2@8");
912     } else {
913       Config->DelayLoadHelper = addUndefined("__delayLoadHelper2");
914     }
915   }
916
917   // Set default image name if neither /out or /def set it.
918   if (Config->OutputFile.empty()) {
919     Config->OutputFile =
920         getOutputPath((*Args.filtered(OPT_INPUT).begin())->getValue());
921   }
922
923   // Put the PDB next to the image if no /pdb flag was passed.
924   if (Config->Debug && Config->PDBPath.empty()) {
925     Config->PDBPath = Config->OutputFile;
926     sys::path::replace_extension(Config->PDBPath, ".pdb");
927   }
928
929   // Disable PDB generation if the user requested it.
930   if (Args.hasArg(OPT_nopdb))
931     Config->PDBPath = "";
932
933   // Set default image base if /base is not given.
934   if (Config->ImageBase == uint64_t(-1))
935     Config->ImageBase = getDefaultImageBase();
936
937   Symtab.addRelative(mangle("__ImageBase"), 0);
938   if (Config->Machine == I386) {
939     Config->SEHTable = Symtab.addRelative("___safe_se_handler_table", 0);
940     Config->SEHCount = Symtab.addAbsolute("___safe_se_handler_count", 0);
941   }
942
943   // We do not support /guard:cf (control flow protection) yet.
944   // Define CFG symbols anyway so that we can link MSVC 2015 CRT.
945   Symtab.addAbsolute(mangle("__guard_fids_table"), 0);
946   Symtab.addAbsolute(mangle("__guard_fids_count"), 0);
947   Symtab.addAbsolute(mangle("__guard_flags"), 0x100);
948
949   // This code may add new undefined symbols to the link, which may enqueue more
950   // symbol resolution tasks, so we need to continue executing tasks until we
951   // converge.
952   do {
953     // Windows specific -- if entry point is not found,
954     // search for its mangled names.
955     if (Config->Entry)
956       Symtab.mangleMaybe(Config->Entry);
957
958     // Windows specific -- Make sure we resolve all dllexported symbols.
959     for (Export &E : Config->Exports) {
960       if (!E.ForwardTo.empty())
961         continue;
962       E.Sym = addUndefined(E.Name);
963       if (!E.Directives)
964         Symtab.mangleMaybe(E.Sym);
965     }
966
967     // Add weak aliases. Weak aliases is a mechanism to give remaining
968     // undefined symbols final chance to be resolved successfully.
969     for (auto Pair : Config->AlternateNames) {
970       StringRef From = Pair.first;
971       StringRef To = Pair.second;
972       Symbol *Sym = Symtab.find(From);
973       if (!Sym)
974         continue;
975       if (auto *U = dyn_cast<Undefined>(Sym->body()))
976         if (!U->WeakAlias)
977           U->WeakAlias = Symtab.addUndefined(To);
978     }
979
980     // Windows specific -- if __load_config_used can be resolved, resolve it.
981     if (Symtab.findUnderscore("_load_config_used"))
982       addUndefined(mangle("_load_config_used"));
983   } while (run());
984
985   if (ErrorCount)
986     return;
987
988   // If /msvclto is given, we use the MSVC linker to link LTO output files.
989   // This is useful because MSVC link.exe can generate complete PDBs.
990   if (Args.hasArg(OPT_msvclto)) {
991     invokeMSVC(Args);
992     exit(0);
993   }
994
995   // Do LTO by compiling bitcode input files to a set of native COFF files then
996   // link those files.
997   Symtab.addCombinedLTOObjects();
998   run();
999
1000   // Make sure we have resolved all symbols.
1001   Symtab.reportRemainingUndefines();
1002
1003   // Windows specific -- if no /subsystem is given, we need to infer
1004   // that from entry point name.
1005   if (Config->Subsystem == IMAGE_SUBSYSTEM_UNKNOWN) {
1006     Config->Subsystem = inferSubsystem();
1007     if (Config->Subsystem == IMAGE_SUBSYSTEM_UNKNOWN)
1008       fatal("subsystem must be defined");
1009   }
1010
1011   // Handle /safeseh.
1012   if (Args.hasArg(OPT_safeseh)) {
1013     for (ObjectFile *File : Symtab.ObjectFiles)
1014       if (!File->SEHCompat)
1015         error("/safeseh: " + File->getName() + " is not compatible with SEH");
1016     if (ErrorCount)
1017       return;
1018   }
1019
1020   // Windows specific -- when we are creating a .dll file, we also
1021   // need to create a .lib file.
1022   if (!Config->Exports.empty() || Config->DLL) {
1023     fixupExports();
1024     writeImportLibrary();
1025     assignExportOrdinals();
1026   }
1027
1028   // Windows specific -- Create a side-by-side manifest file.
1029   if (Config->Manifest == Configuration::SideBySide)
1030     createSideBySideManifest();
1031
1032   // Identify unreferenced COMDAT sections.
1033   if (Config->DoGC)
1034     markLive(Symtab.getChunks());
1035
1036   // Identify identical COMDAT sections to merge them.
1037   if (Config->DoICF)
1038     doICF(Symtab.getChunks());
1039
1040   // Write the result.
1041   writeResult(&Symtab);
1042
1043   // Call exit to avoid calling destructors.
1044   exit(0);
1045 }
1046
1047 } // namespace coff
1048 } // namespace lld