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