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