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