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