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