xref: /llvm-project-15.0.7/lld/COFF/Driver.cpp (revision cfa1376a)
1 //===- Driver.cpp ---------------------------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "Driver.h"
10 #include "Config.h"
11 #include "DebugTypes.h"
12 #include "ICF.h"
13 #include "InputFiles.h"
14 #include "MarkLive.h"
15 #include "MinGW.h"
16 #include "SymbolTable.h"
17 #include "Symbols.h"
18 #include "Writer.h"
19 #include "lld/Common/Args.h"
20 #include "lld/Common/Driver.h"
21 #include "lld/Common/ErrorHandler.h"
22 #include "lld/Common/Filesystem.h"
23 #include "lld/Common/Memory.h"
24 #include "lld/Common/Timer.h"
25 #include "lld/Common/Version.h"
26 #include "llvm/ADT/Optional.h"
27 #include "llvm/ADT/StringSwitch.h"
28 #include "llvm/BinaryFormat/Magic.h"
29 #include "llvm/LTO/LTO.h"
30 #include "llvm/Object/ArchiveWriter.h"
31 #include "llvm/Object/COFFImportFile.h"
32 #include "llvm/Object/COFFModuleDefinition.h"
33 #include "llvm/Object/WindowsMachineFlag.h"
34 #include "llvm/Option/Arg.h"
35 #include "llvm/Option/ArgList.h"
36 #include "llvm/Option/Option.h"
37 #include "llvm/Support/BinaryStreamReader.h"
38 #include "llvm/Support/CommandLine.h"
39 #include "llvm/Support/Debug.h"
40 #include "llvm/Support/LEB128.h"
41 #include "llvm/Support/MathExtras.h"
42 #include "llvm/Support/Parallel.h"
43 #include "llvm/Support/Path.h"
44 #include "llvm/Support/Process.h"
45 #include "llvm/Support/TarWriter.h"
46 #include "llvm/Support/TargetSelect.h"
47 #include "llvm/Support/raw_ostream.h"
48 #include "llvm/ToolDrivers/llvm-lib/LibDriver.h"
49 #include <algorithm>
50 #include <future>
51 #include <memory>
52 
53 using namespace llvm;
54 using namespace llvm::object;
55 using namespace llvm::COFF;
56 using llvm::sys::Process;
57 
58 namespace lld {
59 namespace coff {
60 
61 static Timer inputFileTimer("Input File Reading", Timer::root());
62 
63 Configuration *config;
64 LinkerDriver *driver;
65 
66 bool link(ArrayRef<const char *> args, bool canExitEarly, raw_ostream &stdoutOS,
67           raw_ostream &stderrOS) {
68   lld::stdoutOS = &stdoutOS;
69   lld::stderrOS = &stderrOS;
70 
71   errorHandler().cleanupCallback = []() {
72     TpiSource::clear();
73     freeArena();
74     ObjFile::instances.clear();
75     PDBInputFile::instances.clear();
76     ImportFile::instances.clear();
77     BitcodeFile::instances.clear();
78     memset(MergeChunk::instances, 0, sizeof(MergeChunk::instances));
79     OutputSection::clear();
80   };
81 
82   errorHandler().logName = args::getFilenameWithoutExe(args[0]);
83   errorHandler().errorLimitExceededMsg =
84       "too many errors emitted, stopping now"
85       " (use /errorlimit:0 to see all errors)";
86   errorHandler().exitEarly = canExitEarly;
87   stderrOS.enable_colors(stderrOS.has_colors());
88 
89   config = make<Configuration>();
90   symtab = make<SymbolTable>();
91   driver = make<LinkerDriver>();
92 
93   driver->link(args);
94 
95   // Call exit() if we can to avoid calling destructors.
96   if (canExitEarly)
97     exitLld(errorCount() ? 1 : 0);
98 
99   bool ret = errorCount() == 0;
100   if (!canExitEarly)
101     errorHandler().reset();
102   return ret;
103 }
104 
105 // Parse options of the form "old;new".
106 static std::pair<StringRef, StringRef> getOldNewOptions(opt::InputArgList &args,
107                                                         unsigned id) {
108   auto *arg = args.getLastArg(id);
109   if (!arg)
110     return {"", ""};
111 
112   StringRef s = arg->getValue();
113   std::pair<StringRef, StringRef> ret = s.split(';');
114   if (ret.second.empty())
115     error(arg->getSpelling() + " expects 'old;new' format, but got " + s);
116   return ret;
117 }
118 
119 // Drop directory components and replace extension with
120 // ".exe", ".dll" or ".sys".
121 static std::string getOutputPath(StringRef path) {
122   StringRef ext = ".exe";
123   if (config->dll)
124     ext = ".dll";
125   else if (config->driver)
126     ext = ".sys";
127 
128   return (sys::path::stem(path) + ext).str();
129 }
130 
131 // Returns true if S matches /crtend.?\.o$/.
132 static bool isCrtend(StringRef s) {
133   if (!s.endswith(".o"))
134     return false;
135   s = s.drop_back(2);
136   if (s.endswith("crtend"))
137     return true;
138   return !s.empty() && s.drop_back().endswith("crtend");
139 }
140 
141 // ErrorOr is not default constructible, so it cannot be used as the type
142 // parameter of a future.
143 // FIXME: We could open the file in createFutureForFile and avoid needing to
144 // return an error here, but for the moment that would cost us a file descriptor
145 // (a limited resource on Windows) for the duration that the future is pending.
146 using MBErrPair = std::pair<std::unique_ptr<MemoryBuffer>, std::error_code>;
147 
148 // Create a std::future that opens and maps a file using the best strategy for
149 // the host platform.
150 static std::future<MBErrPair> createFutureForFile(std::string path) {
151 #if _WIN32
152   // On Windows, file I/O is relatively slow so it is best to do this
153   // asynchronously.
154   auto strategy = std::launch::async;
155 #else
156   auto strategy = std::launch::deferred;
157 #endif
158   return std::async(strategy, [=]() {
159     auto mbOrErr = MemoryBuffer::getFile(path,
160                                          /*FileSize*/ -1,
161                                          /*RequiresNullTerminator*/ false);
162     if (!mbOrErr)
163       return MBErrPair{nullptr, mbOrErr.getError()};
164     return MBErrPair{std::move(*mbOrErr), std::error_code()};
165   });
166 }
167 
168 // Symbol names are mangled by prepending "_" on x86.
169 static StringRef mangle(StringRef sym) {
170   assert(config->machine != IMAGE_FILE_MACHINE_UNKNOWN);
171   if (config->machine == I386)
172     return saver.save("_" + sym);
173   return sym;
174 }
175 
176 static bool findUnderscoreMangle(StringRef sym) {
177   Symbol *s = symtab->findMangle(mangle(sym));
178   return s && !isa<Undefined>(s);
179 }
180 
181 MemoryBufferRef LinkerDriver::takeBuffer(std::unique_ptr<MemoryBuffer> mb) {
182   MemoryBufferRef mbref = *mb;
183   make<std::unique_ptr<MemoryBuffer>>(std::move(mb)); // take ownership
184 
185   if (driver->tar)
186     driver->tar->append(relativeToRoot(mbref.getBufferIdentifier()),
187                         mbref.getBuffer());
188   return mbref;
189 }
190 
191 void LinkerDriver::addBuffer(std::unique_ptr<MemoryBuffer> mb,
192                              bool wholeArchive, bool lazy) {
193   StringRef filename = mb->getBufferIdentifier();
194 
195   MemoryBufferRef mbref = takeBuffer(std::move(mb));
196   filePaths.push_back(filename);
197 
198   // File type is detected by contents, not by file extension.
199   switch (identify_magic(mbref.getBuffer())) {
200   case file_magic::windows_resource:
201     resources.push_back(mbref);
202     break;
203   case file_magic::archive:
204     if (wholeArchive) {
205       std::unique_ptr<Archive> file =
206           CHECK(Archive::create(mbref), filename + ": failed to parse archive");
207       Archive *archive = file.get();
208       make<std::unique_ptr<Archive>>(std::move(file)); // take ownership
209 
210       int memberIndex = 0;
211       for (MemoryBufferRef m : getArchiveMembers(archive))
212         addArchiveBuffer(m, "<whole-archive>", filename, memberIndex++);
213       return;
214     }
215     symtab->addFile(make<ArchiveFile>(mbref));
216     break;
217   case file_magic::bitcode:
218     if (lazy)
219       symtab->addFile(make<LazyObjFile>(mbref));
220     else
221       symtab->addFile(make<BitcodeFile>(mbref, "", 0));
222     break;
223   case file_magic::coff_object:
224   case file_magic::coff_import_library:
225     if (lazy)
226       symtab->addFile(make<LazyObjFile>(mbref));
227     else
228       symtab->addFile(make<ObjFile>(mbref));
229     break;
230   case file_magic::pdb:
231     symtab->addFile(make<PDBInputFile>(mbref));
232     break;
233   case file_magic::coff_cl_gl_object:
234     error(filename + ": is not a native COFF file. Recompile without /GL");
235     break;
236   case file_magic::pecoff_executable:
237     if (filename.endswith_lower(".dll")) {
238       error(filename + ": bad file type. Did you specify a DLL instead of an "
239                        "import library?");
240       break;
241     }
242     LLVM_FALLTHROUGH;
243   default:
244     error(mbref.getBufferIdentifier() + ": unknown file type");
245     break;
246   }
247 }
248 
249 void LinkerDriver::enqueuePath(StringRef path, bool wholeArchive, bool lazy) {
250   auto future = std::make_shared<std::future<MBErrPair>>(
251       createFutureForFile(std::string(path)));
252   std::string pathStr = std::string(path);
253   enqueueTask([=]() {
254     auto mbOrErr = future->get();
255     if (mbOrErr.second) {
256       std::string msg =
257           "could not open '" + pathStr + "': " + mbOrErr.second.message();
258       // Check if the filename is a typo for an option flag. OptTable thinks
259       // that all args that are not known options and that start with / are
260       // filenames, but e.g. `/nodefaultlibs` is more likely a typo for
261       // the option `/nodefaultlib` than a reference to a file in the root
262       // directory.
263       std::string nearest;
264       if (optTable.findNearest(pathStr, nearest) > 1)
265         error(msg);
266       else
267         error(msg + "; did you mean '" + nearest + "'");
268     } else
269       driver->addBuffer(std::move(mbOrErr.first), wholeArchive, lazy);
270   });
271 }
272 
273 void LinkerDriver::addArchiveBuffer(MemoryBufferRef mb, StringRef symName,
274                                     StringRef parentName,
275                                     uint64_t offsetInArchive) {
276   file_magic magic = identify_magic(mb.getBuffer());
277   if (magic == file_magic::coff_import_library) {
278     InputFile *imp = make<ImportFile>(mb);
279     imp->parentName = parentName;
280     symtab->addFile(imp);
281     return;
282   }
283 
284   InputFile *obj;
285   if (magic == file_magic::coff_object) {
286     obj = make<ObjFile>(mb);
287   } else if (magic == file_magic::bitcode) {
288     obj = make<BitcodeFile>(mb, parentName, offsetInArchive);
289   } else {
290     error("unknown file type: " + mb.getBufferIdentifier());
291     return;
292   }
293 
294   obj->parentName = parentName;
295   symtab->addFile(obj);
296   log("Loaded " + toString(obj) + " for " + symName);
297 }
298 
299 void LinkerDriver::enqueueArchiveMember(const Archive::Child &c,
300                                         const Archive::Symbol &sym,
301                                         StringRef parentName) {
302 
303   auto reportBufferError = [=](Error &&e, StringRef childName) {
304     fatal("could not get the buffer for the member defining symbol " +
305           toCOFFString(sym) + ": " + parentName + "(" + childName + "): " +
306           toString(std::move(e)));
307   };
308 
309   if (!c.getParent()->isThin()) {
310     uint64_t offsetInArchive = c.getChildOffset();
311     Expected<MemoryBufferRef> mbOrErr = c.getMemoryBufferRef();
312     if (!mbOrErr)
313       reportBufferError(mbOrErr.takeError(), check(c.getFullName()));
314     MemoryBufferRef mb = mbOrErr.get();
315     enqueueTask([=]() {
316       driver->addArchiveBuffer(mb, toCOFFString(sym), parentName,
317                                offsetInArchive);
318     });
319     return;
320   }
321 
322   std::string childName = CHECK(
323       c.getFullName(),
324       "could not get the filename for the member defining symbol " +
325       toCOFFString(sym));
326   auto future = std::make_shared<std::future<MBErrPair>>(
327       createFutureForFile(childName));
328   enqueueTask([=]() {
329     auto mbOrErr = future->get();
330     if (mbOrErr.second)
331       reportBufferError(errorCodeToError(mbOrErr.second), childName);
332     // Pass empty string as archive name so that the original filename is
333     // used as the buffer identifier.
334     driver->addArchiveBuffer(takeBuffer(std::move(mbOrErr.first)),
335                              toCOFFString(sym), "", /*OffsetInArchive=*/0);
336   });
337 }
338 
339 static bool isDecorated(StringRef sym) {
340   return sym.startswith("@") || sym.contains("@@") || sym.startswith("?") ||
341          (!config->mingw && sym.contains('@'));
342 }
343 
344 // Parses .drectve section contents and returns a list of files
345 // specified by /defaultlib.
346 void LinkerDriver::parseDirectives(InputFile *file) {
347   StringRef s = file->getDirectives();
348   if (s.empty())
349     return;
350 
351   log("Directives: " + toString(file) + ": " + s);
352 
353   ArgParser parser;
354   // .drectve is always tokenized using Windows shell rules.
355   // /EXPORT: option can appear too many times, processing in fastpath.
356   ParsedDirectives directives = parser.parseDirectives(s);
357 
358   for (StringRef e : directives.exports) {
359     // If a common header file contains dllexported function
360     // declarations, many object files may end up with having the
361     // same /EXPORT options. In order to save cost of parsing them,
362     // we dedup them first.
363     if (!directivesExports.insert(e).second)
364       continue;
365 
366     Export exp = parseExport(e);
367     if (config->machine == I386 && config->mingw) {
368       if (!isDecorated(exp.name))
369         exp.name = saver.save("_" + exp.name);
370       if (!exp.extName.empty() && !isDecorated(exp.extName))
371         exp.extName = saver.save("_" + exp.extName);
372     }
373     exp.directives = true;
374     config->exports.push_back(exp);
375   }
376 
377   // Handle /include: in bulk.
378   for (StringRef inc : directives.includes)
379     addUndefined(inc);
380 
381   for (auto *arg : directives.args) {
382     switch (arg->getOption().getID()) {
383     case OPT_aligncomm:
384       parseAligncomm(arg->getValue());
385       break;
386     case OPT_alternatename:
387       parseAlternateName(arg->getValue());
388       break;
389     case OPT_defaultlib:
390       if (Optional<StringRef> path = findLib(arg->getValue()))
391         enqueuePath(*path, false, false);
392       break;
393     case OPT_entry:
394       config->entry = addUndefined(mangle(arg->getValue()));
395       break;
396     case OPT_failifmismatch:
397       checkFailIfMismatch(arg->getValue(), file);
398       break;
399     case OPT_incl:
400       addUndefined(arg->getValue());
401       break;
402     case OPT_merge:
403       parseMerge(arg->getValue());
404       break;
405     case OPT_nodefaultlib:
406       config->noDefaultLibs.insert(doFindLib(arg->getValue()).lower());
407       break;
408     case OPT_section:
409       parseSection(arg->getValue());
410       break;
411     case OPT_subsystem: {
412       bool gotVersion = false;
413       parseSubsystem(arg->getValue(), &config->subsystem,
414                      &config->majorSubsystemVersion,
415                      &config->minorSubsystemVersion, &gotVersion);
416       if (gotVersion) {
417         config->majorOSVersion = config->majorSubsystemVersion;
418         config->minorOSVersion = config->minorSubsystemVersion;
419       }
420       break;
421     }
422     // Only add flags here that link.exe accepts in
423     // `#pragma comment(linker, "/flag")`-generated sections.
424     case OPT_editandcontinue:
425     case OPT_guardsym:
426     case OPT_throwingnew:
427       break;
428     default:
429       error(arg->getSpelling() + " is not allowed in .drectve");
430     }
431   }
432 }
433 
434 // Find file from search paths. You can omit ".obj", this function takes
435 // care of that. Note that the returned path is not guaranteed to exist.
436 StringRef LinkerDriver::doFindFile(StringRef filename) {
437   bool hasPathSep = (filename.find_first_of("/\\") != StringRef::npos);
438   if (hasPathSep)
439     return filename;
440   bool hasExt = filename.contains('.');
441   for (StringRef dir : searchPaths) {
442     SmallString<128> path = dir;
443     sys::path::append(path, filename);
444     if (sys::fs::exists(path.str()))
445       return saver.save(path.str());
446     if (!hasExt) {
447       path.append(".obj");
448       if (sys::fs::exists(path.str()))
449         return saver.save(path.str());
450     }
451   }
452   return filename;
453 }
454 
455 static Optional<sys::fs::UniqueID> getUniqueID(StringRef path) {
456   sys::fs::UniqueID ret;
457   if (sys::fs::getUniqueID(path, ret))
458     return None;
459   return ret;
460 }
461 
462 // Resolves a file path. This never returns the same path
463 // (in that case, it returns None).
464 Optional<StringRef> LinkerDriver::findFile(StringRef filename) {
465   StringRef path = doFindFile(filename);
466 
467   if (Optional<sys::fs::UniqueID> id = getUniqueID(path)) {
468     bool seen = !visitedFiles.insert(*id).second;
469     if (seen)
470       return None;
471   }
472 
473   if (path.endswith_lower(".lib"))
474     visitedLibs.insert(std::string(sys::path::filename(path)));
475   return path;
476 }
477 
478 // MinGW specific. If an embedded directive specified to link to
479 // foo.lib, but it isn't found, try libfoo.a instead.
480 StringRef LinkerDriver::doFindLibMinGW(StringRef filename) {
481   if (filename.contains('/') || filename.contains('\\'))
482     return filename;
483 
484   SmallString<128> s = filename;
485   sys::path::replace_extension(s, ".a");
486   StringRef libName = saver.save("lib" + s.str());
487   return doFindFile(libName);
488 }
489 
490 // Find library file from search path.
491 StringRef LinkerDriver::doFindLib(StringRef filename) {
492   // Add ".lib" to Filename if that has no file extension.
493   bool hasExt = filename.contains('.');
494   if (!hasExt)
495     filename = saver.save(filename + ".lib");
496   StringRef ret = doFindFile(filename);
497   // For MinGW, if the find above didn't turn up anything, try
498   // looking for a MinGW formatted library name.
499   if (config->mingw && ret == filename)
500     return doFindLibMinGW(filename);
501   return ret;
502 }
503 
504 // Resolves a library path. /nodefaultlib options are taken into
505 // consideration. This never returns the same path (in that case,
506 // it returns None).
507 Optional<StringRef> LinkerDriver::findLib(StringRef filename) {
508   if (config->noDefaultLibAll)
509     return None;
510   if (!visitedLibs.insert(filename.lower()).second)
511     return None;
512 
513   StringRef path = doFindLib(filename);
514   if (config->noDefaultLibs.count(path.lower()))
515     return None;
516 
517   if (Optional<sys::fs::UniqueID> id = getUniqueID(path))
518     if (!visitedFiles.insert(*id).second)
519       return None;
520   return path;
521 }
522 
523 // Parses LIB environment which contains a list of search paths.
524 void LinkerDriver::addLibSearchPaths() {
525   Optional<std::string> envOpt = Process::GetEnv("LIB");
526   if (!envOpt.hasValue())
527     return;
528   StringRef env = saver.save(*envOpt);
529   while (!env.empty()) {
530     StringRef path;
531     std::tie(path, env) = env.split(';');
532     searchPaths.push_back(path);
533   }
534 }
535 
536 Symbol *LinkerDriver::addUndefined(StringRef name) {
537   Symbol *b = symtab->addUndefined(name);
538   if (!b->isGCRoot) {
539     b->isGCRoot = true;
540     config->gcroot.push_back(b);
541   }
542   return b;
543 }
544 
545 StringRef LinkerDriver::mangleMaybe(Symbol *s) {
546   // If the plain symbol name has already been resolved, do nothing.
547   Undefined *unmangled = dyn_cast<Undefined>(s);
548   if (!unmangled)
549     return "";
550 
551   // Otherwise, see if a similar, mangled symbol exists in the symbol table.
552   Symbol *mangled = symtab->findMangle(unmangled->getName());
553   if (!mangled)
554     return "";
555 
556   // If we find a similar mangled symbol, make this an alias to it and return
557   // its name.
558   log(unmangled->getName() + " aliased to " + mangled->getName());
559   unmangled->weakAlias = symtab->addUndefined(mangled->getName());
560   return mangled->getName();
561 }
562 
563 // Windows specific -- find default entry point name.
564 //
565 // There are four different entry point functions for Windows executables,
566 // each of which corresponds to a user-defined "main" function. This function
567 // infers an entry point from a user-defined "main" function.
568 StringRef LinkerDriver::findDefaultEntry() {
569   assert(config->subsystem != IMAGE_SUBSYSTEM_UNKNOWN &&
570          "must handle /subsystem before calling this");
571 
572   if (config->mingw)
573     return mangle(config->subsystem == IMAGE_SUBSYSTEM_WINDOWS_GUI
574                       ? "WinMainCRTStartup"
575                       : "mainCRTStartup");
576 
577   if (config->subsystem == IMAGE_SUBSYSTEM_WINDOWS_GUI) {
578     if (findUnderscoreMangle("wWinMain")) {
579       if (!findUnderscoreMangle("WinMain"))
580         return mangle("wWinMainCRTStartup");
581       warn("found both wWinMain and WinMain; using latter");
582     }
583     return mangle("WinMainCRTStartup");
584   }
585   if (findUnderscoreMangle("wmain")) {
586     if (!findUnderscoreMangle("main"))
587       return mangle("wmainCRTStartup");
588     warn("found both wmain and main; using latter");
589   }
590   return mangle("mainCRTStartup");
591 }
592 
593 WindowsSubsystem LinkerDriver::inferSubsystem() {
594   if (config->dll)
595     return IMAGE_SUBSYSTEM_WINDOWS_GUI;
596   if (config->mingw)
597     return IMAGE_SUBSYSTEM_WINDOWS_CUI;
598   // Note that link.exe infers the subsystem from the presence of these
599   // functions even if /entry: or /nodefaultlib are passed which causes them
600   // to not be called.
601   bool haveMain = findUnderscoreMangle("main");
602   bool haveWMain = findUnderscoreMangle("wmain");
603   bool haveWinMain = findUnderscoreMangle("WinMain");
604   bool haveWWinMain = findUnderscoreMangle("wWinMain");
605   if (haveMain || haveWMain) {
606     if (haveWinMain || haveWWinMain) {
607       warn(std::string("found ") + (haveMain ? "main" : "wmain") + " and " +
608            (haveWinMain ? "WinMain" : "wWinMain") +
609            "; defaulting to /subsystem:console");
610     }
611     return IMAGE_SUBSYSTEM_WINDOWS_CUI;
612   }
613   if (haveWinMain || haveWWinMain)
614     return IMAGE_SUBSYSTEM_WINDOWS_GUI;
615   return IMAGE_SUBSYSTEM_UNKNOWN;
616 }
617 
618 static uint64_t getDefaultImageBase() {
619   if (config->is64())
620     return config->dll ? 0x180000000 : 0x140000000;
621   return config->dll ? 0x10000000 : 0x400000;
622 }
623 
624 static std::string createResponseFile(const opt::InputArgList &args,
625                                       ArrayRef<StringRef> filePaths,
626                                       ArrayRef<StringRef> searchPaths) {
627   SmallString<0> data;
628   raw_svector_ostream os(data);
629 
630   for (auto *arg : args) {
631     switch (arg->getOption().getID()) {
632     case OPT_linkrepro:
633     case OPT_reproduce:
634     case OPT_INPUT:
635     case OPT_defaultlib:
636     case OPT_libpath:
637     case OPT_manifest:
638     case OPT_manifest_colon:
639     case OPT_manifestdependency:
640     case OPT_manifestfile:
641     case OPT_manifestinput:
642     case OPT_manifestuac:
643       break;
644     case OPT_implib:
645     case OPT_pdb:
646     case OPT_pdbstripped:
647     case OPT_out:
648       os << arg->getSpelling() << sys::path::filename(arg->getValue()) << "\n";
649       break;
650     default:
651       os << toString(*arg) << "\n";
652     }
653   }
654 
655   for (StringRef path : searchPaths) {
656     std::string relPath = relativeToRoot(path);
657     os << "/libpath:" << quote(relPath) << "\n";
658   }
659 
660   for (StringRef path : filePaths)
661     os << quote(relativeToRoot(path)) << "\n";
662 
663   return std::string(data.str());
664 }
665 
666 enum class DebugKind { Unknown, None, Full, FastLink, GHash, Dwarf, Symtab };
667 
668 static DebugKind parseDebugKind(const opt::InputArgList &args) {
669   auto *a = args.getLastArg(OPT_debug, OPT_debug_opt);
670   if (!a)
671     return DebugKind::None;
672   if (a->getNumValues() == 0)
673     return DebugKind::Full;
674 
675   DebugKind debug = StringSwitch<DebugKind>(a->getValue())
676                      .CaseLower("none", DebugKind::None)
677                      .CaseLower("full", DebugKind::Full)
678                      .CaseLower("fastlink", DebugKind::FastLink)
679                      // LLD extensions
680                      .CaseLower("ghash", DebugKind::GHash)
681                      .CaseLower("dwarf", DebugKind::Dwarf)
682                      .CaseLower("symtab", DebugKind::Symtab)
683                      .Default(DebugKind::Unknown);
684 
685   if (debug == DebugKind::FastLink) {
686     warn("/debug:fastlink unsupported; using /debug:full");
687     return DebugKind::Full;
688   }
689   if (debug == DebugKind::Unknown) {
690     error("/debug: unknown option: " + Twine(a->getValue()));
691     return DebugKind::None;
692   }
693   return debug;
694 }
695 
696 static unsigned parseDebugTypes(const opt::InputArgList &args) {
697   unsigned debugTypes = static_cast<unsigned>(DebugType::None);
698 
699   if (auto *a = args.getLastArg(OPT_debugtype)) {
700     SmallVector<StringRef, 3> types;
701     StringRef(a->getValue())
702         .split(types, ',', /*MaxSplit=*/-1, /*KeepEmpty=*/false);
703 
704     for (StringRef type : types) {
705       unsigned v = StringSwitch<unsigned>(type.lower())
706                        .Case("cv", static_cast<unsigned>(DebugType::CV))
707                        .Case("pdata", static_cast<unsigned>(DebugType::PData))
708                        .Case("fixup", static_cast<unsigned>(DebugType::Fixup))
709                        .Default(0);
710       if (v == 0) {
711         warn("/debugtype: unknown option '" + type + "'");
712         continue;
713       }
714       debugTypes |= v;
715     }
716     return debugTypes;
717   }
718 
719   // Default debug types
720   debugTypes = static_cast<unsigned>(DebugType::CV);
721   if (args.hasArg(OPT_driver))
722     debugTypes |= static_cast<unsigned>(DebugType::PData);
723   if (args.hasArg(OPT_profile))
724     debugTypes |= static_cast<unsigned>(DebugType::Fixup);
725 
726   return debugTypes;
727 }
728 
729 static std::string getMapFile(const opt::InputArgList &args,
730                               opt::OptSpecifier os, opt::OptSpecifier osFile) {
731   auto *arg = args.getLastArg(os, osFile);
732   if (!arg)
733     return "";
734   if (arg->getOption().getID() == osFile.getID())
735     return arg->getValue();
736 
737   assert(arg->getOption().getID() == os.getID());
738   StringRef outFile = config->outputFile;
739   return (outFile.substr(0, outFile.rfind('.')) + ".map").str();
740 }
741 
742 static std::string getImplibPath() {
743   if (!config->implib.empty())
744     return std::string(config->implib);
745   SmallString<128> out = StringRef(config->outputFile);
746   sys::path::replace_extension(out, ".lib");
747   return std::string(out.str());
748 }
749 
750 // The import name is calculated as follows:
751 //
752 //        | LIBRARY w/ ext |   LIBRARY w/o ext   | no LIBRARY
753 //   -----+----------------+---------------------+------------------
754 //   LINK | {value}        | {value}.{.dll/.exe} | {output name}
755 //    LIB | {value}        | {value}.dll         | {output name}.dll
756 //
757 static std::string getImportName(bool asLib) {
758   SmallString<128> out;
759 
760   if (config->importName.empty()) {
761     out.assign(sys::path::filename(config->outputFile));
762     if (asLib)
763       sys::path::replace_extension(out, ".dll");
764   } else {
765     out.assign(config->importName);
766     if (!sys::path::has_extension(out))
767       sys::path::replace_extension(out,
768                                    (config->dll || asLib) ? ".dll" : ".exe");
769   }
770 
771   return std::string(out.str());
772 }
773 
774 static void createImportLibrary(bool asLib) {
775   std::vector<COFFShortExport> exports;
776   for (Export &e1 : config->exports) {
777     COFFShortExport e2;
778     e2.Name = std::string(e1.name);
779     e2.SymbolName = std::string(e1.symbolName);
780     e2.ExtName = std::string(e1.extName);
781     e2.Ordinal = e1.ordinal;
782     e2.Noname = e1.noname;
783     e2.Data = e1.data;
784     e2.Private = e1.isPrivate;
785     e2.Constant = e1.constant;
786     exports.push_back(e2);
787   }
788 
789   auto handleError = [](Error &&e) {
790     handleAllErrors(std::move(e),
791                     [](ErrorInfoBase &eib) { error(eib.message()); });
792   };
793   std::string libName = getImportName(asLib);
794   std::string path = getImplibPath();
795 
796   if (!config->incremental) {
797     handleError(writeImportLibrary(libName, path, exports, config->machine,
798                                    config->mingw));
799     return;
800   }
801 
802   // If the import library already exists, replace it only if the contents
803   // have changed.
804   ErrorOr<std::unique_ptr<MemoryBuffer>> oldBuf = MemoryBuffer::getFile(
805       path, /*FileSize*/ -1, /*RequiresNullTerminator*/ false);
806   if (!oldBuf) {
807     handleError(writeImportLibrary(libName, path, exports, config->machine,
808                                    config->mingw));
809     return;
810   }
811 
812   SmallString<128> tmpName;
813   if (std::error_code ec =
814           sys::fs::createUniqueFile(path + ".tmp-%%%%%%%%.lib", tmpName))
815     fatal("cannot create temporary file for import library " + path + ": " +
816           ec.message());
817 
818   if (Error e = writeImportLibrary(libName, tmpName, exports, config->machine,
819                                    config->mingw)) {
820     handleError(std::move(e));
821     return;
822   }
823 
824   std::unique_ptr<MemoryBuffer> newBuf = check(MemoryBuffer::getFile(
825       tmpName, /*FileSize*/ -1, /*RequiresNullTerminator*/ false));
826   if ((*oldBuf)->getBuffer() != newBuf->getBuffer()) {
827     oldBuf->reset();
828     handleError(errorCodeToError(sys::fs::rename(tmpName, path)));
829   } else {
830     sys::fs::remove(tmpName);
831   }
832 }
833 
834 static void parseModuleDefs(StringRef path) {
835   std::unique_ptr<MemoryBuffer> mb = CHECK(
836       MemoryBuffer::getFile(path, -1, false, true), "could not open " + path);
837   COFFModuleDefinition m = check(parseCOFFModuleDefinition(
838       mb->getMemBufferRef(), config->machine, config->mingw));
839 
840   if (config->outputFile.empty())
841     config->outputFile = std::string(saver.save(m.OutputFile));
842   config->importName = std::string(saver.save(m.ImportName));
843   if (m.ImageBase)
844     config->imageBase = m.ImageBase;
845   if (m.StackReserve)
846     config->stackReserve = m.StackReserve;
847   if (m.StackCommit)
848     config->stackCommit = m.StackCommit;
849   if (m.HeapReserve)
850     config->heapReserve = m.HeapReserve;
851   if (m.HeapCommit)
852     config->heapCommit = m.HeapCommit;
853   if (m.MajorImageVersion)
854     config->majorImageVersion = m.MajorImageVersion;
855   if (m.MinorImageVersion)
856     config->minorImageVersion = m.MinorImageVersion;
857   if (m.MajorOSVersion)
858     config->majorOSVersion = m.MajorOSVersion;
859   if (m.MinorOSVersion)
860     config->minorOSVersion = m.MinorOSVersion;
861 
862   for (COFFShortExport e1 : m.Exports) {
863     Export e2;
864     // In simple cases, only Name is set. Renamed exports are parsed
865     // and set as "ExtName = Name". If Name has the form "OtherDll.Func",
866     // it shouldn't be a normal exported function but a forward to another
867     // DLL instead. This is supported by both MS and GNU linkers.
868     if (!e1.ExtName.empty() && e1.ExtName != e1.Name &&
869         StringRef(e1.Name).contains('.')) {
870       e2.name = saver.save(e1.ExtName);
871       e2.forwardTo = saver.save(e1.Name);
872       config->exports.push_back(e2);
873       continue;
874     }
875     e2.name = saver.save(e1.Name);
876     e2.extName = saver.save(e1.ExtName);
877     e2.ordinal = e1.Ordinal;
878     e2.noname = e1.Noname;
879     e2.data = e1.Data;
880     e2.isPrivate = e1.Private;
881     e2.constant = e1.Constant;
882     config->exports.push_back(e2);
883   }
884 }
885 
886 void LinkerDriver::enqueueTask(std::function<void()> task) {
887   taskQueue.push_back(std::move(task));
888 }
889 
890 bool LinkerDriver::run() {
891   ScopedTimer t(inputFileTimer);
892 
893   bool didWork = !taskQueue.empty();
894   while (!taskQueue.empty()) {
895     taskQueue.front()();
896     taskQueue.pop_front();
897   }
898   return didWork;
899 }
900 
901 // Parse an /order file. If an option is given, the linker places
902 // COMDAT sections in the same order as their names appear in the
903 // given file.
904 static void parseOrderFile(StringRef arg) {
905   // For some reason, the MSVC linker requires a filename to be
906   // preceded by "@".
907   if (!arg.startswith("@")) {
908     error("malformed /order option: '@' missing");
909     return;
910   }
911 
912   // Get a list of all comdat sections for error checking.
913   DenseSet<StringRef> set;
914   for (Chunk *c : symtab->getChunks())
915     if (auto *sec = dyn_cast<SectionChunk>(c))
916       if (sec->sym)
917         set.insert(sec->sym->getName());
918 
919   // Open a file.
920   StringRef path = arg.substr(1);
921   std::unique_ptr<MemoryBuffer> mb = CHECK(
922       MemoryBuffer::getFile(path, -1, false, true), "could not open " + path);
923 
924   // Parse a file. An order file contains one symbol per line.
925   // All symbols that were not present in a given order file are
926   // considered to have the lowest priority 0 and are placed at
927   // end of an output section.
928   for (StringRef arg : args::getLines(mb->getMemBufferRef())) {
929     std::string s(arg);
930     if (config->machine == I386 && !isDecorated(s))
931       s = "_" + s;
932 
933     if (set.count(s) == 0) {
934       if (config->warnMissingOrderSymbol)
935         warn("/order:" + arg + ": missing symbol: " + s + " [LNK4037]");
936     }
937     else
938       config->order[s] = INT_MIN + config->order.size();
939   }
940 }
941 
942 static void parseCallGraphFile(StringRef path) {
943   std::unique_ptr<MemoryBuffer> mb = CHECK(
944       MemoryBuffer::getFile(path, -1, false, true), "could not open " + path);
945 
946   // Build a map from symbol name to section.
947   DenseMap<StringRef, Symbol *> map;
948   for (ObjFile *file : ObjFile::instances)
949     for (Symbol *sym : file->getSymbols())
950       if (sym)
951         map[sym->getName()] = sym;
952 
953   auto findSection = [&](StringRef name) -> SectionChunk * {
954     Symbol *sym = map.lookup(name);
955     if (!sym) {
956       if (config->warnMissingOrderSymbol)
957         warn(path + ": no such symbol: " + name);
958       return nullptr;
959     }
960 
961     if (DefinedCOFF *dr = dyn_cast_or_null<DefinedCOFF>(sym))
962       return dyn_cast_or_null<SectionChunk>(dr->getChunk());
963     return nullptr;
964   };
965 
966   for (StringRef line : args::getLines(*mb)) {
967     SmallVector<StringRef, 3> fields;
968     line.split(fields, ' ');
969     uint64_t count;
970 
971     if (fields.size() != 3 || !to_integer(fields[2], count)) {
972       error(path + ": parse error");
973       return;
974     }
975 
976     if (SectionChunk *from = findSection(fields[0]))
977       if (SectionChunk *to = findSection(fields[1]))
978         config->callGraphProfile[{from, to}] += count;
979   }
980 }
981 
982 static void readCallGraphsFromObjectFiles() {
983   for (ObjFile *obj : ObjFile::instances) {
984     if (obj->callgraphSec) {
985       ArrayRef<uint8_t> contents;
986       cantFail(
987           obj->getCOFFObj()->getSectionContents(obj->callgraphSec, contents));
988       BinaryStreamReader reader(contents, support::little);
989       while (!reader.empty()) {
990         uint32_t fromIndex, toIndex;
991         uint64_t count;
992         if (Error err = reader.readInteger(fromIndex))
993           fatal(toString(obj) + ": Expected 32-bit integer");
994         if (Error err = reader.readInteger(toIndex))
995           fatal(toString(obj) + ": Expected 32-bit integer");
996         if (Error err = reader.readInteger(count))
997           fatal(toString(obj) + ": Expected 64-bit integer");
998         auto *fromSym = dyn_cast_or_null<Defined>(obj->getSymbol(fromIndex));
999         auto *toSym = dyn_cast_or_null<Defined>(obj->getSymbol(toIndex));
1000         if (!fromSym || !toSym)
1001           continue;
1002         auto *from = dyn_cast_or_null<SectionChunk>(fromSym->getChunk());
1003         auto *to = dyn_cast_or_null<SectionChunk>(toSym->getChunk());
1004         if (from && to)
1005           config->callGraphProfile[{from, to}] += count;
1006       }
1007     }
1008   }
1009 }
1010 
1011 static void markAddrsig(Symbol *s) {
1012   if (auto *d = dyn_cast_or_null<Defined>(s))
1013     if (SectionChunk *c = dyn_cast_or_null<SectionChunk>(d->getChunk()))
1014       c->keepUnique = true;
1015 }
1016 
1017 static void findKeepUniqueSections() {
1018   // Exported symbols could be address-significant in other executables or DSOs,
1019   // so we conservatively mark them as address-significant.
1020   for (Export &r : config->exports)
1021     markAddrsig(r.sym);
1022 
1023   // Visit the address-significance table in each object file and mark each
1024   // referenced symbol as address-significant.
1025   for (ObjFile *obj : ObjFile::instances) {
1026     ArrayRef<Symbol *> syms = obj->getSymbols();
1027     if (obj->addrsigSec) {
1028       ArrayRef<uint8_t> contents;
1029       cantFail(
1030           obj->getCOFFObj()->getSectionContents(obj->addrsigSec, contents));
1031       const uint8_t *cur = contents.begin();
1032       while (cur != contents.end()) {
1033         unsigned size;
1034         const char *err;
1035         uint64_t symIndex = decodeULEB128(cur, &size, contents.end(), &err);
1036         if (err)
1037           fatal(toString(obj) + ": could not decode addrsig section: " + err);
1038         if (symIndex >= syms.size())
1039           fatal(toString(obj) + ": invalid symbol index in addrsig section");
1040         markAddrsig(syms[symIndex]);
1041         cur += size;
1042       }
1043     } else {
1044       // If an object file does not have an address-significance table,
1045       // conservatively mark all of its symbols as address-significant.
1046       for (Symbol *s : syms)
1047         markAddrsig(s);
1048     }
1049   }
1050 }
1051 
1052 // link.exe replaces each %foo% in altPath with the contents of environment
1053 // variable foo, and adds the two magic env vars _PDB (expands to the basename
1054 // of pdb's output path) and _EXT (expands to the extension of the output
1055 // binary).
1056 // lld only supports %_PDB% and %_EXT% and warns on references to all other env
1057 // vars.
1058 static void parsePDBAltPath(StringRef altPath) {
1059   SmallString<128> buf;
1060   StringRef pdbBasename =
1061       sys::path::filename(config->pdbPath, sys::path::Style::windows);
1062   StringRef binaryExtension =
1063       sys::path::extension(config->outputFile, sys::path::Style::windows);
1064   if (!binaryExtension.empty())
1065     binaryExtension = binaryExtension.substr(1); // %_EXT% does not include '.'.
1066 
1067   // Invariant:
1068   //   +--------- cursor ('a...' might be the empty string).
1069   //   |   +----- firstMark
1070   //   |   |   +- secondMark
1071   //   v   v   v
1072   //   a...%...%...
1073   size_t cursor = 0;
1074   while (cursor < altPath.size()) {
1075     size_t firstMark, secondMark;
1076     if ((firstMark = altPath.find('%', cursor)) == StringRef::npos ||
1077         (secondMark = altPath.find('%', firstMark + 1)) == StringRef::npos) {
1078       // Didn't find another full fragment, treat rest of string as literal.
1079       buf.append(altPath.substr(cursor));
1080       break;
1081     }
1082 
1083     // Found a full fragment. Append text in front of first %, and interpret
1084     // text between first and second % as variable name.
1085     buf.append(altPath.substr(cursor, firstMark - cursor));
1086     StringRef var = altPath.substr(firstMark, secondMark - firstMark + 1);
1087     if (var.equals_lower("%_pdb%"))
1088       buf.append(pdbBasename);
1089     else if (var.equals_lower("%_ext%"))
1090       buf.append(binaryExtension);
1091     else {
1092       warn("only %_PDB% and %_EXT% supported in /pdbaltpath:, keeping " +
1093            var + " as literal");
1094       buf.append(var);
1095     }
1096 
1097     cursor = secondMark + 1;
1098   }
1099 
1100   config->pdbAltPath = buf;
1101 }
1102 
1103 /// Convert resource files and potentially merge input resource object
1104 /// trees into one resource tree.
1105 /// Call after ObjFile::Instances is complete.
1106 void LinkerDriver::convertResources() {
1107   std::vector<ObjFile *> resourceObjFiles;
1108 
1109   for (ObjFile *f : ObjFile::instances) {
1110     if (f->isResourceObjFile())
1111       resourceObjFiles.push_back(f);
1112   }
1113 
1114   if (!config->mingw &&
1115       (resourceObjFiles.size() > 1 ||
1116        (resourceObjFiles.size() == 1 && !resources.empty()))) {
1117     error((!resources.empty() ? "internal .obj file created from .res files"
1118                               : toString(resourceObjFiles[1])) +
1119           ": more than one resource obj file not allowed, already got " +
1120           toString(resourceObjFiles.front()));
1121     return;
1122   }
1123 
1124   if (resources.empty() && resourceObjFiles.size() <= 1) {
1125     // No resources to convert, and max one resource object file in
1126     // the input. Keep that preconverted resource section as is.
1127     for (ObjFile *f : resourceObjFiles)
1128       f->includeResourceChunks();
1129     return;
1130   }
1131   ObjFile *f = make<ObjFile>(convertResToCOFF(resources, resourceObjFiles));
1132   symtab->addFile(f);
1133   f->includeResourceChunks();
1134 }
1135 
1136 // In MinGW, if no symbols are chosen to be exported, then all symbols are
1137 // automatically exported by default. This behavior can be forced by the
1138 // -export-all-symbols option, so that it happens even when exports are
1139 // explicitly specified. The automatic behavior can be disabled using the
1140 // -exclude-all-symbols option, so that lld-link behaves like link.exe rather
1141 // than MinGW in the case that nothing is explicitly exported.
1142 void LinkerDriver::maybeExportMinGWSymbols(const opt::InputArgList &args) {
1143   if (!config->dll)
1144     return;
1145 
1146   if (!args.hasArg(OPT_export_all_symbols)) {
1147     if (!config->exports.empty())
1148       return;
1149     if (args.hasArg(OPT_exclude_all_symbols))
1150       return;
1151   }
1152 
1153   AutoExporter exporter;
1154 
1155   for (auto *arg : args.filtered(OPT_wholearchive_file))
1156     if (Optional<StringRef> path = doFindFile(arg->getValue()))
1157       exporter.addWholeArchive(*path);
1158 
1159   symtab->forEachSymbol([&](Symbol *s) {
1160     auto *def = dyn_cast<Defined>(s);
1161     if (!exporter.shouldExport(def))
1162       return;
1163 
1164     Export e;
1165     e.name = def->getName();
1166     e.sym = def;
1167     if (Chunk *c = def->getChunk())
1168       if (!(c->getOutputCharacteristics() & IMAGE_SCN_MEM_EXECUTE))
1169         e.data = true;
1170     config->exports.push_back(e);
1171   });
1172 }
1173 
1174 // lld has a feature to create a tar file containing all input files as well as
1175 // all command line options, so that other people can run lld again with exactly
1176 // the same inputs. This feature is accessible via /linkrepro and /reproduce.
1177 //
1178 // /linkrepro and /reproduce are very similar, but /linkrepro takes a directory
1179 // name while /reproduce takes a full path. We have /linkrepro for compatibility
1180 // with Microsoft link.exe.
1181 Optional<std::string> getReproduceFile(const opt::InputArgList &args) {
1182   if (auto *arg = args.getLastArg(OPT_reproduce))
1183     return std::string(arg->getValue());
1184 
1185   if (auto *arg = args.getLastArg(OPT_linkrepro)) {
1186     SmallString<64> path = StringRef(arg->getValue());
1187     sys::path::append(path, "repro.tar");
1188     return std::string(path);
1189   }
1190 
1191   return None;
1192 }
1193 
1194 void LinkerDriver::link(ArrayRef<const char *> argsArr) {
1195   ScopedTimer rootTimer(Timer::root());
1196 
1197   // Needed for LTO.
1198   InitializeAllTargetInfos();
1199   InitializeAllTargets();
1200   InitializeAllTargetMCs();
1201   InitializeAllAsmParsers();
1202   InitializeAllAsmPrinters();
1203 
1204   // If the first command line argument is "/lib", link.exe acts like lib.exe.
1205   // We call our own implementation of lib.exe that understands bitcode files.
1206   if (argsArr.size() > 1 && StringRef(argsArr[1]).equals_lower("/lib")) {
1207     if (llvm::libDriverMain(argsArr.slice(1)) != 0)
1208       fatal("lib failed");
1209     return;
1210   }
1211 
1212   // Parse command line options.
1213   ArgParser parser;
1214   opt::InputArgList args = parser.parse(argsArr);
1215 
1216   // Parse and evaluate -mllvm options.
1217   std::vector<const char *> v;
1218   v.push_back("lld-link (LLVM option parsing)");
1219   for (auto *arg : args.filtered(OPT_mllvm))
1220     v.push_back(arg->getValue());
1221   cl::ResetAllOptionOccurrences();
1222   cl::ParseCommandLineOptions(v.size(), v.data());
1223 
1224   // Handle /errorlimit early, because error() depends on it.
1225   if (auto *arg = args.getLastArg(OPT_errorlimit)) {
1226     int n = 20;
1227     StringRef s = arg->getValue();
1228     if (s.getAsInteger(10, n))
1229       error(arg->getSpelling() + " number expected, but got " + s);
1230     errorHandler().errorLimit = n;
1231   }
1232 
1233   // Handle /help
1234   if (args.hasArg(OPT_help)) {
1235     printHelp(argsArr[0]);
1236     return;
1237   }
1238 
1239   // /threads: takes a positive integer and provides the default value for
1240   // /opt:lldltojobs=.
1241   if (auto *arg = args.getLastArg(OPT_threads)) {
1242     StringRef v(arg->getValue());
1243     unsigned threads = 0;
1244     if (!llvm::to_integer(v, threads, 0) || threads == 0)
1245       error(arg->getSpelling() + ": expected a positive integer, but got '" +
1246             arg->getValue() + "'");
1247     parallel::strategy = hardware_concurrency(threads);
1248     config->thinLTOJobs = v.str();
1249   }
1250 
1251   if (args.hasArg(OPT_show_timing))
1252     config->showTiming = true;
1253 
1254   config->showSummary = args.hasArg(OPT_summary);
1255 
1256   // Handle --version, which is an lld extension. This option is a bit odd
1257   // because it doesn't start with "/", but we deliberately chose "--" to
1258   // avoid conflict with /version and for compatibility with clang-cl.
1259   if (args.hasArg(OPT_dash_dash_version)) {
1260     lld::outs() << getLLDVersion() << "\n";
1261     return;
1262   }
1263 
1264   // Handle /lldmingw early, since it can potentially affect how other
1265   // options are handled.
1266   config->mingw = args.hasArg(OPT_lldmingw);
1267 
1268   // Handle /linkrepro and /reproduce.
1269   if (Optional<std::string> path = getReproduceFile(args)) {
1270     Expected<std::unique_ptr<TarWriter>> errOrWriter =
1271         TarWriter::create(*path, sys::path::stem(*path));
1272 
1273     if (errOrWriter) {
1274       tar = std::move(*errOrWriter);
1275     } else {
1276       error("/linkrepro: failed to open " + *path + ": " +
1277             toString(errOrWriter.takeError()));
1278     }
1279   }
1280 
1281   if (!args.hasArg(OPT_INPUT, OPT_wholearchive_file)) {
1282     if (args.hasArg(OPT_deffile))
1283       config->noEntry = true;
1284     else
1285       fatal("no input files");
1286   }
1287 
1288   // Construct search path list.
1289   searchPaths.push_back("");
1290   for (auto *arg : args.filtered(OPT_libpath))
1291     searchPaths.push_back(arg->getValue());
1292   if (!args.hasArg(OPT_lldignoreenv))
1293     addLibSearchPaths();
1294 
1295   // Handle /ignore
1296   for (auto *arg : args.filtered(OPT_ignore)) {
1297     SmallVector<StringRef, 8> vec;
1298     StringRef(arg->getValue()).split(vec, ',');
1299     for (StringRef s : vec) {
1300       if (s == "4037")
1301         config->warnMissingOrderSymbol = false;
1302       else if (s == "4099")
1303         config->warnDebugInfoUnusable = false;
1304       else if (s == "4217")
1305         config->warnLocallyDefinedImported = false;
1306       else if (s == "longsections")
1307         config->warnLongSectionNames = false;
1308       // Other warning numbers are ignored.
1309     }
1310   }
1311 
1312   // Handle /out
1313   if (auto *arg = args.getLastArg(OPT_out))
1314     config->outputFile = arg->getValue();
1315 
1316   // Handle /verbose
1317   if (args.hasArg(OPT_verbose))
1318     config->verbose = true;
1319   errorHandler().verbose = config->verbose;
1320 
1321   // Handle /force or /force:unresolved
1322   if (args.hasArg(OPT_force, OPT_force_unresolved))
1323     config->forceUnresolved = true;
1324 
1325   // Handle /force or /force:multiple
1326   if (args.hasArg(OPT_force, OPT_force_multiple))
1327     config->forceMultiple = true;
1328 
1329   // Handle /force or /force:multipleres
1330   if (args.hasArg(OPT_force, OPT_force_multipleres))
1331     config->forceMultipleRes = true;
1332 
1333   // Handle /debug
1334   DebugKind debug = parseDebugKind(args);
1335   if (debug == DebugKind::Full || debug == DebugKind::Dwarf ||
1336       debug == DebugKind::GHash) {
1337     config->debug = true;
1338     config->incremental = true;
1339   }
1340 
1341   // Handle /demangle
1342   config->demangle = args.hasFlag(OPT_demangle, OPT_demangle_no);
1343 
1344   // Handle /debugtype
1345   config->debugTypes = parseDebugTypes(args);
1346 
1347   // Handle /driver[:uponly|:wdm].
1348   config->driverUponly = args.hasArg(OPT_driver_uponly) ||
1349                          args.hasArg(OPT_driver_uponly_wdm) ||
1350                          args.hasArg(OPT_driver_wdm_uponly);
1351   config->driverWdm = args.hasArg(OPT_driver_wdm) ||
1352                       args.hasArg(OPT_driver_uponly_wdm) ||
1353                       args.hasArg(OPT_driver_wdm_uponly);
1354   config->driver =
1355       config->driverUponly || config->driverWdm || args.hasArg(OPT_driver);
1356 
1357   // Handle /pdb
1358   bool shouldCreatePDB =
1359       (debug == DebugKind::Full || debug == DebugKind::GHash);
1360   if (shouldCreatePDB) {
1361     if (auto *arg = args.getLastArg(OPT_pdb))
1362       config->pdbPath = arg->getValue();
1363     if (auto *arg = args.getLastArg(OPT_pdbaltpath))
1364       config->pdbAltPath = arg->getValue();
1365     if (args.hasArg(OPT_natvis))
1366       config->natvisFiles = args.getAllArgValues(OPT_natvis);
1367     if (args.hasArg(OPT_pdbstream)) {
1368       for (const StringRef value : args.getAllArgValues(OPT_pdbstream)) {
1369         const std::pair<StringRef, StringRef> nameFile = value.split("=");
1370         const StringRef name = nameFile.first;
1371         const std::string file = nameFile.second.str();
1372         config->namedStreams[name] = file;
1373       }
1374     }
1375 
1376     if (auto *arg = args.getLastArg(OPT_pdb_source_path))
1377       config->pdbSourcePath = arg->getValue();
1378   }
1379 
1380   // Handle /pdbstripped
1381   if (args.hasArg(OPT_pdbstripped))
1382     warn("ignoring /pdbstripped flag, it is not yet supported");
1383 
1384   // Handle /noentry
1385   if (args.hasArg(OPT_noentry)) {
1386     if (args.hasArg(OPT_dll))
1387       config->noEntry = true;
1388     else
1389       error("/noentry must be specified with /dll");
1390   }
1391 
1392   // Handle /dll
1393   if (args.hasArg(OPT_dll)) {
1394     config->dll = true;
1395     config->manifestID = 2;
1396   }
1397 
1398   // Handle /dynamicbase and /fixed. We can't use hasFlag for /dynamicbase
1399   // because we need to explicitly check whether that option or its inverse was
1400   // present in the argument list in order to handle /fixed.
1401   auto *dynamicBaseArg = args.getLastArg(OPT_dynamicbase, OPT_dynamicbase_no);
1402   if (dynamicBaseArg &&
1403       dynamicBaseArg->getOption().getID() == OPT_dynamicbase_no)
1404     config->dynamicBase = false;
1405 
1406   // MSDN claims "/FIXED:NO is the default setting for a DLL, and /FIXED is the
1407   // default setting for any other project type.", but link.exe defaults to
1408   // /FIXED:NO for exe outputs as well. Match behavior, not docs.
1409   bool fixed = args.hasFlag(OPT_fixed, OPT_fixed_no, false);
1410   if (fixed) {
1411     if (dynamicBaseArg &&
1412         dynamicBaseArg->getOption().getID() == OPT_dynamicbase) {
1413       error("/fixed must not be specified with /dynamicbase");
1414     } else {
1415       config->relocatable = false;
1416       config->dynamicBase = false;
1417     }
1418   }
1419 
1420   // Handle /appcontainer
1421   config->appContainer =
1422       args.hasFlag(OPT_appcontainer, OPT_appcontainer_no, false);
1423 
1424   // Handle /machine
1425   if (auto *arg = args.getLastArg(OPT_machine)) {
1426     config->machine = getMachineType(arg->getValue());
1427     if (config->machine == IMAGE_FILE_MACHINE_UNKNOWN)
1428       fatal(Twine("unknown /machine argument: ") + arg->getValue());
1429   }
1430 
1431   // Handle /nodefaultlib:<filename>
1432   for (auto *arg : args.filtered(OPT_nodefaultlib))
1433     config->noDefaultLibs.insert(doFindLib(arg->getValue()).lower());
1434 
1435   // Handle /nodefaultlib
1436   if (args.hasArg(OPT_nodefaultlib_all))
1437     config->noDefaultLibAll = true;
1438 
1439   // Handle /base
1440   if (auto *arg = args.getLastArg(OPT_base))
1441     parseNumbers(arg->getValue(), &config->imageBase);
1442 
1443   // Handle /filealign
1444   if (auto *arg = args.getLastArg(OPT_filealign)) {
1445     parseNumbers(arg->getValue(), &config->fileAlign);
1446     if (!isPowerOf2_64(config->fileAlign))
1447       error("/filealign: not a power of two: " + Twine(config->fileAlign));
1448   }
1449 
1450   // Handle /stack
1451   if (auto *arg = args.getLastArg(OPT_stack))
1452     parseNumbers(arg->getValue(), &config->stackReserve, &config->stackCommit);
1453 
1454   // Handle /guard:cf
1455   if (auto *arg = args.getLastArg(OPT_guard))
1456     parseGuard(arg->getValue());
1457 
1458   // Handle /heap
1459   if (auto *arg = args.getLastArg(OPT_heap))
1460     parseNumbers(arg->getValue(), &config->heapReserve, &config->heapCommit);
1461 
1462   // Handle /version
1463   if (auto *arg = args.getLastArg(OPT_version))
1464     parseVersion(arg->getValue(), &config->majorImageVersion,
1465                  &config->minorImageVersion);
1466 
1467   // Handle /subsystem
1468   if (auto *arg = args.getLastArg(OPT_subsystem))
1469     parseSubsystem(arg->getValue(), &config->subsystem,
1470                    &config->majorSubsystemVersion,
1471                    &config->minorSubsystemVersion);
1472 
1473   // Handle /osversion
1474   if (auto *arg = args.getLastArg(OPT_osversion)) {
1475     parseVersion(arg->getValue(), &config->majorOSVersion,
1476                  &config->minorOSVersion);
1477   } else {
1478     config->majorOSVersion = config->majorSubsystemVersion;
1479     config->minorOSVersion = config->minorSubsystemVersion;
1480   }
1481 
1482   // Handle /timestamp
1483   if (llvm::opt::Arg *arg = args.getLastArg(OPT_timestamp, OPT_repro)) {
1484     if (arg->getOption().getID() == OPT_repro) {
1485       config->timestamp = 0;
1486       config->repro = true;
1487     } else {
1488       config->repro = false;
1489       StringRef value(arg->getValue());
1490       if (value.getAsInteger(0, config->timestamp))
1491         fatal(Twine("invalid timestamp: ") + value +
1492               ".  Expected 32-bit integer");
1493     }
1494   } else {
1495     config->repro = false;
1496     config->timestamp = time(nullptr);
1497   }
1498 
1499   // Handle /alternatename
1500   for (auto *arg : args.filtered(OPT_alternatename))
1501     parseAlternateName(arg->getValue());
1502 
1503   // Handle /include
1504   for (auto *arg : args.filtered(OPT_incl))
1505     addUndefined(arg->getValue());
1506 
1507   // Handle /implib
1508   if (auto *arg = args.getLastArg(OPT_implib))
1509     config->implib = arg->getValue();
1510 
1511   // Handle /opt.
1512   bool doGC = debug == DebugKind::None || args.hasArg(OPT_profile);
1513   unsigned icfLevel =
1514       args.hasArg(OPT_profile) ? 0 : 1; // 0: off, 1: limited, 2: on
1515   unsigned tailMerge = 1;
1516   for (auto *arg : args.filtered(OPT_opt)) {
1517     std::string str = StringRef(arg->getValue()).lower();
1518     SmallVector<StringRef, 1> vec;
1519     StringRef(str).split(vec, ',');
1520     for (StringRef s : vec) {
1521       if (s == "ref") {
1522         doGC = true;
1523       } else if (s == "noref") {
1524         doGC = false;
1525       } else if (s == "icf" || s.startswith("icf=")) {
1526         icfLevel = 2;
1527       } else if (s == "noicf") {
1528         icfLevel = 0;
1529       } else if (s == "lldtailmerge") {
1530         tailMerge = 2;
1531       } else if (s == "nolldtailmerge") {
1532         tailMerge = 0;
1533       } else if (s.startswith("lldlto=")) {
1534         StringRef optLevel = s.substr(7);
1535         if (optLevel.getAsInteger(10, config->ltoo) || config->ltoo > 3)
1536           error("/opt:lldlto: invalid optimization level: " + optLevel);
1537       } else if (s.startswith("lldltojobs=")) {
1538         StringRef jobs = s.substr(11);
1539         if (!get_threadpool_strategy(jobs))
1540           error("/opt:lldltojobs: invalid job count: " + jobs);
1541         config->thinLTOJobs = jobs.str();
1542       } else if (s.startswith("lldltopartitions=")) {
1543         StringRef n = s.substr(17);
1544         if (n.getAsInteger(10, config->ltoPartitions) ||
1545             config->ltoPartitions == 0)
1546           error("/opt:lldltopartitions: invalid partition count: " + n);
1547       } else if (s != "lbr" && s != "nolbr")
1548         error("/opt: unknown option: " + s);
1549     }
1550   }
1551 
1552   // Limited ICF is enabled if GC is enabled and ICF was never mentioned
1553   // explicitly.
1554   // FIXME: LLD only implements "limited" ICF, i.e. it only merges identical
1555   // code. If the user passes /OPT:ICF explicitly, LLD should merge identical
1556   // comdat readonly data.
1557   if (icfLevel == 1 && !doGC)
1558     icfLevel = 0;
1559   config->doGC = doGC;
1560   config->doICF = icfLevel > 0;
1561   config->tailMerge = (tailMerge == 1 && config->doICF) || tailMerge == 2;
1562 
1563   // Handle /lldsavetemps
1564   if (args.hasArg(OPT_lldsavetemps))
1565     config->saveTemps = true;
1566 
1567   // Handle /kill-at
1568   if (args.hasArg(OPT_kill_at))
1569     config->killAt = true;
1570 
1571   // Handle /lldltocache
1572   if (auto *arg = args.getLastArg(OPT_lldltocache))
1573     config->ltoCache = arg->getValue();
1574 
1575   // Handle /lldsavecachepolicy
1576   if (auto *arg = args.getLastArg(OPT_lldltocachepolicy))
1577     config->ltoCachePolicy = CHECK(
1578         parseCachePruningPolicy(arg->getValue()),
1579         Twine("/lldltocachepolicy: invalid cache policy: ") + arg->getValue());
1580 
1581   // Handle /failifmismatch
1582   for (auto *arg : args.filtered(OPT_failifmismatch))
1583     checkFailIfMismatch(arg->getValue(), nullptr);
1584 
1585   // Handle /merge
1586   for (auto *arg : args.filtered(OPT_merge))
1587     parseMerge(arg->getValue());
1588 
1589   // Add default section merging rules after user rules. User rules take
1590   // precedence, but we will emit a warning if there is a conflict.
1591   parseMerge(".idata=.rdata");
1592   parseMerge(".didat=.rdata");
1593   parseMerge(".edata=.rdata");
1594   parseMerge(".xdata=.rdata");
1595   parseMerge(".bss=.data");
1596 
1597   if (config->mingw) {
1598     parseMerge(".ctors=.rdata");
1599     parseMerge(".dtors=.rdata");
1600     parseMerge(".CRT=.rdata");
1601   }
1602 
1603   // Handle /section
1604   for (auto *arg : args.filtered(OPT_section))
1605     parseSection(arg->getValue());
1606 
1607   // Handle /align
1608   if (auto *arg = args.getLastArg(OPT_align)) {
1609     parseNumbers(arg->getValue(), &config->align);
1610     if (!isPowerOf2_64(config->align))
1611       error("/align: not a power of two: " + StringRef(arg->getValue()));
1612     if (!args.hasArg(OPT_driver))
1613       warn("/align specified without /driver; image may not run");
1614   }
1615 
1616   // Handle /aligncomm
1617   for (auto *arg : args.filtered(OPT_aligncomm))
1618     parseAligncomm(arg->getValue());
1619 
1620   // Handle /manifestdependency. This enables /manifest unless /manifest:no is
1621   // also passed.
1622   if (auto *arg = args.getLastArg(OPT_manifestdependency)) {
1623     config->manifestDependency = arg->getValue();
1624     config->manifest = Configuration::SideBySide;
1625   }
1626 
1627   // Handle /manifest and /manifest:
1628   if (auto *arg = args.getLastArg(OPT_manifest, OPT_manifest_colon)) {
1629     if (arg->getOption().getID() == OPT_manifest)
1630       config->manifest = Configuration::SideBySide;
1631     else
1632       parseManifest(arg->getValue());
1633   }
1634 
1635   // Handle /manifestuac
1636   if (auto *arg = args.getLastArg(OPT_manifestuac))
1637     parseManifestUAC(arg->getValue());
1638 
1639   // Handle /manifestfile
1640   if (auto *arg = args.getLastArg(OPT_manifestfile))
1641     config->manifestFile = arg->getValue();
1642 
1643   // Handle /manifestinput
1644   for (auto *arg : args.filtered(OPT_manifestinput))
1645     config->manifestInput.push_back(arg->getValue());
1646 
1647   if (!config->manifestInput.empty() &&
1648       config->manifest != Configuration::Embed) {
1649     fatal("/manifestinput: requires /manifest:embed");
1650   }
1651 
1652   config->thinLTOEmitImportsFiles = args.hasArg(OPT_thinlto_emit_imports_files);
1653   config->thinLTOIndexOnly = args.hasArg(OPT_thinlto_index_only) ||
1654                              args.hasArg(OPT_thinlto_index_only_arg);
1655   config->thinLTOIndexOnlyArg =
1656       args.getLastArgValue(OPT_thinlto_index_only_arg);
1657   config->thinLTOPrefixReplace =
1658       getOldNewOptions(args, OPT_thinlto_prefix_replace);
1659   config->thinLTOObjectSuffixReplace =
1660       getOldNewOptions(args, OPT_thinlto_object_suffix_replace);
1661   config->ltoObjPath = args.getLastArgValue(OPT_lto_obj_path);
1662   // Handle miscellaneous boolean flags.
1663   config->allowBind = args.hasFlag(OPT_allowbind, OPT_allowbind_no, true);
1664   config->allowIsolation =
1665       args.hasFlag(OPT_allowisolation, OPT_allowisolation_no, true);
1666   config->incremental =
1667       args.hasFlag(OPT_incremental, OPT_incremental_no,
1668                    !config->doGC && !config->doICF && !args.hasArg(OPT_order) &&
1669                        !args.hasArg(OPT_profile));
1670   config->integrityCheck =
1671       args.hasFlag(OPT_integritycheck, OPT_integritycheck_no, false);
1672   config->cetCompat = args.hasFlag(OPT_cetcompat, OPT_cetcompat_no, false);
1673   config->nxCompat = args.hasFlag(OPT_nxcompat, OPT_nxcompat_no, true);
1674   for (auto *arg : args.filtered(OPT_swaprun))
1675     parseSwaprun(arg->getValue());
1676   config->terminalServerAware =
1677       !config->dll && args.hasFlag(OPT_tsaware, OPT_tsaware_no, true);
1678   config->debugDwarf = debug == DebugKind::Dwarf;
1679   config->debugGHashes = debug == DebugKind::GHash;
1680   config->debugSymtab = debug == DebugKind::Symtab;
1681   config->autoImport =
1682       args.hasFlag(OPT_auto_import, OPT_auto_import_no, config->mingw);
1683   config->pseudoRelocs = args.hasFlag(
1684       OPT_runtime_pseudo_reloc, OPT_runtime_pseudo_reloc_no, config->mingw);
1685   config->callGraphProfileSort = args.hasFlag(
1686       OPT_call_graph_profile_sort, OPT_call_graph_profile_sort_no, true);
1687 
1688   // Don't warn about long section names, such as .debug_info, for mingw or
1689   // when -debug:dwarf is requested.
1690   if (config->mingw || config->debugDwarf)
1691     config->warnLongSectionNames = false;
1692 
1693   config->lldmapFile = getMapFile(args, OPT_lldmap, OPT_lldmap_file);
1694   config->mapFile = getMapFile(args, OPT_map, OPT_map_file);
1695 
1696   if (config->lldmapFile != "" && config->lldmapFile == config->mapFile) {
1697     warn("/lldmap and /map have the same output file '" + config->mapFile +
1698          "'.\n>>> ignoring /lldmap");
1699     config->lldmapFile.clear();
1700   }
1701 
1702   if (config->incremental && args.hasArg(OPT_profile)) {
1703     warn("ignoring '/incremental' due to '/profile' specification");
1704     config->incremental = false;
1705   }
1706 
1707   if (config->incremental && args.hasArg(OPT_order)) {
1708     warn("ignoring '/incremental' due to '/order' specification");
1709     config->incremental = false;
1710   }
1711 
1712   if (config->incremental && config->doGC) {
1713     warn("ignoring '/incremental' because REF is enabled; use '/opt:noref' to "
1714          "disable");
1715     config->incremental = false;
1716   }
1717 
1718   if (config->incremental && config->doICF) {
1719     warn("ignoring '/incremental' because ICF is enabled; use '/opt:noicf' to "
1720          "disable");
1721     config->incremental = false;
1722   }
1723 
1724   if (errorCount())
1725     return;
1726 
1727   std::set<sys::fs::UniqueID> wholeArchives;
1728   for (auto *arg : args.filtered(OPT_wholearchive_file))
1729     if (Optional<StringRef> path = doFindFile(arg->getValue()))
1730       if (Optional<sys::fs::UniqueID> id = getUniqueID(*path))
1731         wholeArchives.insert(*id);
1732 
1733   // A predicate returning true if a given path is an argument for
1734   // /wholearchive:, or /wholearchive is enabled globally.
1735   // This function is a bit tricky because "foo.obj /wholearchive:././foo.obj"
1736   // needs to be handled as "/wholearchive:foo.obj foo.obj".
1737   auto isWholeArchive = [&](StringRef path) -> bool {
1738     if (args.hasArg(OPT_wholearchive_flag))
1739       return true;
1740     if (Optional<sys::fs::UniqueID> id = getUniqueID(path))
1741       return wholeArchives.count(*id);
1742     return false;
1743   };
1744 
1745   // Create a list of input files. These can be given as OPT_INPUT options
1746   // and OPT_wholearchive_file options, and we also need to track OPT_start_lib
1747   // and OPT_end_lib.
1748   bool inLib = false;
1749   for (auto *arg : args) {
1750     switch (arg->getOption().getID()) {
1751     case OPT_end_lib:
1752       if (!inLib)
1753         error("stray " + arg->getSpelling());
1754       inLib = false;
1755       break;
1756     case OPT_start_lib:
1757       if (inLib)
1758         error("nested " + arg->getSpelling());
1759       inLib = true;
1760       break;
1761     case OPT_wholearchive_file:
1762       if (Optional<StringRef> path = findFile(arg->getValue()))
1763         enqueuePath(*path, true, inLib);
1764       break;
1765     case OPT_INPUT:
1766       if (Optional<StringRef> path = findFile(arg->getValue()))
1767         enqueuePath(*path, isWholeArchive(*path), inLib);
1768       break;
1769     default:
1770       // Ignore other options.
1771       break;
1772     }
1773   }
1774 
1775   // Process files specified as /defaultlib. These should be enequeued after
1776   // other files, which is why they are in a separate loop.
1777   for (auto *arg : args.filtered(OPT_defaultlib))
1778     if (Optional<StringRef> path = findLib(arg->getValue()))
1779       enqueuePath(*path, false, false);
1780 
1781   // Windows specific -- Create a resource file containing a manifest file.
1782   if (config->manifest == Configuration::Embed)
1783     addBuffer(createManifestRes(), false, false);
1784 
1785   // Read all input files given via the command line.
1786   run();
1787 
1788   if (errorCount())
1789     return;
1790 
1791   // We should have inferred a machine type by now from the input files, but if
1792   // not we assume x64.
1793   if (config->machine == IMAGE_FILE_MACHINE_UNKNOWN) {
1794     warn("/machine is not specified. x64 is assumed");
1795     config->machine = AMD64;
1796   }
1797   config->wordsize = config->is64() ? 8 : 4;
1798 
1799   // Handle /safeseh, x86 only, on by default, except for mingw.
1800   if (config->machine == I386) {
1801     config->safeSEH = args.hasFlag(OPT_safeseh, OPT_safeseh_no, !config->mingw);
1802     config->noSEH = args.hasArg(OPT_noseh);
1803   }
1804 
1805   // Handle /functionpadmin
1806   for (auto *arg : args.filtered(OPT_functionpadmin, OPT_functionpadmin_opt))
1807     parseFunctionPadMin(arg, config->machine);
1808 
1809   if (tar)
1810     tar->append("response.txt",
1811                 createResponseFile(args, filePaths,
1812                                    ArrayRef<StringRef>(searchPaths).slice(1)));
1813 
1814   // Handle /largeaddressaware
1815   config->largeAddressAware = args.hasFlag(
1816       OPT_largeaddressaware, OPT_largeaddressaware_no, config->is64());
1817 
1818   // Handle /highentropyva
1819   config->highEntropyVA =
1820       config->is64() &&
1821       args.hasFlag(OPT_highentropyva, OPT_highentropyva_no, true);
1822 
1823   if (!config->dynamicBase &&
1824       (config->machine == ARMNT || config->machine == ARM64))
1825     error("/dynamicbase:no is not compatible with " +
1826           machineToStr(config->machine));
1827 
1828   // Handle /export
1829   for (auto *arg : args.filtered(OPT_export)) {
1830     Export e = parseExport(arg->getValue());
1831     if (config->machine == I386) {
1832       if (!isDecorated(e.name))
1833         e.name = saver.save("_" + e.name);
1834       if (!e.extName.empty() && !isDecorated(e.extName))
1835         e.extName = saver.save("_" + e.extName);
1836     }
1837     config->exports.push_back(e);
1838   }
1839 
1840   // Handle /def
1841   if (auto *arg = args.getLastArg(OPT_deffile)) {
1842     // parseModuleDefs mutates Config object.
1843     parseModuleDefs(arg->getValue());
1844   }
1845 
1846   // Handle generation of import library from a def file.
1847   if (!args.hasArg(OPT_INPUT, OPT_wholearchive_file)) {
1848     fixupExports();
1849     createImportLibrary(/*asLib=*/true);
1850     return;
1851   }
1852 
1853   // Windows specific -- if no /subsystem is given, we need to infer
1854   // that from entry point name.  Must happen before /entry handling,
1855   // and after the early return when just writing an import library.
1856   if (config->subsystem == IMAGE_SUBSYSTEM_UNKNOWN) {
1857     config->subsystem = inferSubsystem();
1858     if (config->subsystem == IMAGE_SUBSYSTEM_UNKNOWN)
1859       fatal("subsystem must be defined");
1860   }
1861 
1862   // Handle /entry and /dll
1863   if (auto *arg = args.getLastArg(OPT_entry)) {
1864     config->entry = addUndefined(mangle(arg->getValue()));
1865   } else if (!config->entry && !config->noEntry) {
1866     if (args.hasArg(OPT_dll)) {
1867       StringRef s = (config->machine == I386) ? "__DllMainCRTStartup@12"
1868                                               : "_DllMainCRTStartup";
1869       config->entry = addUndefined(s);
1870     } else if (config->driverWdm) {
1871       // /driver:wdm implies /entry:_NtProcessStartup
1872       config->entry = addUndefined(mangle("_NtProcessStartup"));
1873     } else {
1874       // Windows specific -- If entry point name is not given, we need to
1875       // infer that from user-defined entry name.
1876       StringRef s = findDefaultEntry();
1877       if (s.empty())
1878         fatal("entry point must be defined");
1879       config->entry = addUndefined(s);
1880       log("Entry name inferred: " + s);
1881     }
1882   }
1883 
1884   // Handle /delayload
1885   for (auto *arg : args.filtered(OPT_delayload)) {
1886     config->delayLoads.insert(StringRef(arg->getValue()).lower());
1887     if (config->machine == I386) {
1888       config->delayLoadHelper = addUndefined("___delayLoadHelper2@8");
1889     } else {
1890       config->delayLoadHelper = addUndefined("__delayLoadHelper2");
1891     }
1892   }
1893 
1894   // Set default image name if neither /out or /def set it.
1895   if (config->outputFile.empty()) {
1896     config->outputFile = getOutputPath(
1897         (*args.filtered(OPT_INPUT, OPT_wholearchive_file).begin())->getValue());
1898   }
1899 
1900   // Fail early if an output file is not writable.
1901   if (auto e = tryCreateFile(config->outputFile)) {
1902     error("cannot open output file " + config->outputFile + ": " + e.message());
1903     return;
1904   }
1905 
1906   if (shouldCreatePDB) {
1907     // Put the PDB next to the image if no /pdb flag was passed.
1908     if (config->pdbPath.empty()) {
1909       config->pdbPath = config->outputFile;
1910       sys::path::replace_extension(config->pdbPath, ".pdb");
1911     }
1912 
1913     // The embedded PDB path should be the absolute path to the PDB if no
1914     // /pdbaltpath flag was passed.
1915     if (config->pdbAltPath.empty()) {
1916       config->pdbAltPath = config->pdbPath;
1917 
1918       // It's important to make the path absolute and remove dots.  This path
1919       // will eventually be written into the PE header, and certain Microsoft
1920       // tools won't work correctly if these assumptions are not held.
1921       sys::fs::make_absolute(config->pdbAltPath);
1922       sys::path::remove_dots(config->pdbAltPath);
1923     } else {
1924       // Don't do this earlier, so that Config->OutputFile is ready.
1925       parsePDBAltPath(config->pdbAltPath);
1926     }
1927   }
1928 
1929   // Set default image base if /base is not given.
1930   if (config->imageBase == uint64_t(-1))
1931     config->imageBase = getDefaultImageBase();
1932 
1933   symtab->addSynthetic(mangle("__ImageBase"), nullptr);
1934   if (config->machine == I386) {
1935     symtab->addAbsolute("___safe_se_handler_table", 0);
1936     symtab->addAbsolute("___safe_se_handler_count", 0);
1937   }
1938 
1939   symtab->addAbsolute(mangle("__guard_fids_count"), 0);
1940   symtab->addAbsolute(mangle("__guard_fids_table"), 0);
1941   symtab->addAbsolute(mangle("__guard_flags"), 0);
1942   symtab->addAbsolute(mangle("__guard_iat_count"), 0);
1943   symtab->addAbsolute(mangle("__guard_iat_table"), 0);
1944   symtab->addAbsolute(mangle("__guard_longjmp_count"), 0);
1945   symtab->addAbsolute(mangle("__guard_longjmp_table"), 0);
1946   // Needed for MSVC 2017 15.5 CRT.
1947   symtab->addAbsolute(mangle("__enclave_config"), 0);
1948 
1949   if (config->pseudoRelocs) {
1950     symtab->addAbsolute(mangle("__RUNTIME_PSEUDO_RELOC_LIST__"), 0);
1951     symtab->addAbsolute(mangle("__RUNTIME_PSEUDO_RELOC_LIST_END__"), 0);
1952   }
1953   if (config->mingw) {
1954     symtab->addAbsolute(mangle("__CTOR_LIST__"), 0);
1955     symtab->addAbsolute(mangle("__DTOR_LIST__"), 0);
1956   }
1957 
1958   // This code may add new undefined symbols to the link, which may enqueue more
1959   // symbol resolution tasks, so we need to continue executing tasks until we
1960   // converge.
1961   do {
1962     // Windows specific -- if entry point is not found,
1963     // search for its mangled names.
1964     if (config->entry)
1965       mangleMaybe(config->entry);
1966 
1967     // Windows specific -- Make sure we resolve all dllexported symbols.
1968     for (Export &e : config->exports) {
1969       if (!e.forwardTo.empty())
1970         continue;
1971       e.sym = addUndefined(e.name);
1972       if (!e.directives)
1973         e.symbolName = mangleMaybe(e.sym);
1974     }
1975 
1976     // Add weak aliases. Weak aliases is a mechanism to give remaining
1977     // undefined symbols final chance to be resolved successfully.
1978     for (auto pair : config->alternateNames) {
1979       StringRef from = pair.first;
1980       StringRef to = pair.second;
1981       Symbol *sym = symtab->find(from);
1982       if (!sym)
1983         continue;
1984       if (auto *u = dyn_cast<Undefined>(sym))
1985         if (!u->weakAlias)
1986           u->weakAlias = symtab->addUndefined(to);
1987     }
1988 
1989     // If any inputs are bitcode files, the LTO code generator may create
1990     // references to library functions that are not explicit in the bitcode
1991     // file's symbol table. If any of those library functions are defined in a
1992     // bitcode file in an archive member, we need to arrange to use LTO to
1993     // compile those archive members by adding them to the link beforehand.
1994     if (!BitcodeFile::instances.empty())
1995       for (auto *s : lto::LTO::getRuntimeLibcallSymbols())
1996         symtab->addLibcall(s);
1997 
1998     // Windows specific -- if __load_config_used can be resolved, resolve it.
1999     if (symtab->findUnderscore("_load_config_used"))
2000       addUndefined(mangle("_load_config_used"));
2001   } while (run());
2002 
2003   if (args.hasArg(OPT_include_optional)) {
2004     // Handle /includeoptional
2005     for (auto *arg : args.filtered(OPT_include_optional))
2006       if (dyn_cast_or_null<LazyArchive>(symtab->find(arg->getValue())))
2007         addUndefined(arg->getValue());
2008     while (run());
2009   }
2010 
2011   // Create wrapped symbols for -wrap option.
2012   std::vector<WrappedSymbol> wrapped = addWrappedSymbols(args);
2013   // Load more object files that might be needed for wrapped symbols.
2014   if (!wrapped.empty())
2015     while (run());
2016 
2017   if (config->autoImport) {
2018     // MinGW specific.
2019     // Load any further object files that might be needed for doing automatic
2020     // imports.
2021     //
2022     // For cases with no automatically imported symbols, this iterates once
2023     // over the symbol table and doesn't do anything.
2024     //
2025     // For the normal case with a few automatically imported symbols, this
2026     // should only need to be run once, since each new object file imported
2027     // is an import library and wouldn't add any new undefined references,
2028     // but there's nothing stopping the __imp_ symbols from coming from a
2029     // normal object file as well (although that won't be used for the
2030     // actual autoimport later on). If this pass adds new undefined references,
2031     // we won't iterate further to resolve them.
2032     symtab->loadMinGWAutomaticImports();
2033     run();
2034   }
2035 
2036   // At this point, we should not have any symbols that cannot be resolved.
2037   // If we are going to do codegen for link-time optimization, check for
2038   // unresolvable symbols first, so we don't spend time generating code that
2039   // will fail to link anyway.
2040   if (!BitcodeFile::instances.empty() && !config->forceUnresolved)
2041     symtab->reportUnresolvable();
2042   if (errorCount())
2043     return;
2044 
2045   // Do LTO by compiling bitcode input files to a set of native COFF files then
2046   // link those files (unless -thinlto-index-only was given, in which case we
2047   // resolve symbols and write indices, but don't generate native code or link).
2048   symtab->addCombinedLTOObjects();
2049 
2050   // If -thinlto-index-only is given, we should create only "index
2051   // files" and not object files. Index file creation is already done
2052   // in addCombinedLTOObject, so we are done if that's the case.
2053   if (config->thinLTOIndexOnly)
2054     return;
2055 
2056   // If we generated native object files from bitcode files, this resolves
2057   // references to the symbols we use from them.
2058   run();
2059 
2060   // Apply symbol renames for -wrap.
2061   if (!wrapped.empty())
2062     wrapSymbols(wrapped);
2063 
2064   // Resolve remaining undefined symbols and warn about imported locals.
2065   symtab->resolveRemainingUndefines();
2066   if (errorCount())
2067     return;
2068 
2069   config->hadExplicitExports = !config->exports.empty();
2070   if (config->mingw) {
2071     // In MinGW, all symbols are automatically exported if no symbols
2072     // are chosen to be exported.
2073     maybeExportMinGWSymbols(args);
2074 
2075     // Make sure the crtend.o object is the last object file. This object
2076     // file can contain terminating section chunks that need to be placed
2077     // last. GNU ld processes files and static libraries explicitly in the
2078     // order provided on the command line, while lld will pull in needed
2079     // files from static libraries only after the last object file on the
2080     // command line.
2081     for (auto i = ObjFile::instances.begin(), e = ObjFile::instances.end();
2082          i != e; i++) {
2083       ObjFile *file = *i;
2084       if (isCrtend(file->getName())) {
2085         ObjFile::instances.erase(i);
2086         ObjFile::instances.push_back(file);
2087         break;
2088       }
2089     }
2090   }
2091 
2092   // Windows specific -- when we are creating a .dll file, we also
2093   // need to create a .lib file. In MinGW mode, we only do that when the
2094   // -implib option is given explicitly, for compatibility with GNU ld.
2095   if (!config->exports.empty() || config->dll) {
2096     fixupExports();
2097     if (!config->mingw || !config->implib.empty())
2098       createImportLibrary(/*asLib=*/false);
2099     assignExportOrdinals();
2100   }
2101 
2102   // Handle /output-def (MinGW specific).
2103   if (auto *arg = args.getLastArg(OPT_output_def))
2104     writeDefFile(arg->getValue());
2105 
2106   // Set extra alignment for .comm symbols
2107   for (auto pair : config->alignComm) {
2108     StringRef name = pair.first;
2109     uint32_t alignment = pair.second;
2110 
2111     Symbol *sym = symtab->find(name);
2112     if (!sym) {
2113       warn("/aligncomm symbol " + name + " not found");
2114       continue;
2115     }
2116 
2117     // If the symbol isn't common, it must have been replaced with a regular
2118     // symbol, which will carry its own alignment.
2119     auto *dc = dyn_cast<DefinedCommon>(sym);
2120     if (!dc)
2121       continue;
2122 
2123     CommonChunk *c = dc->getChunk();
2124     c->setAlignment(std::max(c->getAlignment(), alignment));
2125   }
2126 
2127   // Windows specific -- Create a side-by-side manifest file.
2128   if (config->manifest == Configuration::SideBySide)
2129     createSideBySideManifest();
2130 
2131   // Handle /order. We want to do this at this moment because we
2132   // need a complete list of comdat sections to warn on nonexistent
2133   // functions.
2134   if (auto *arg = args.getLastArg(OPT_order)) {
2135     if (args.hasArg(OPT_call_graph_ordering_file))
2136       error("/order and /call-graph-order-file may not be used together");
2137     parseOrderFile(arg->getValue());
2138     config->callGraphProfileSort = false;
2139   }
2140 
2141   // Handle /call-graph-ordering-file and /call-graph-profile-sort (default on).
2142   if (config->callGraphProfileSort) {
2143     if (auto *arg = args.getLastArg(OPT_call_graph_ordering_file)) {
2144       parseCallGraphFile(arg->getValue());
2145     }
2146     readCallGraphsFromObjectFiles();
2147   }
2148 
2149   // Handle /print-symbol-order.
2150   if (auto *arg = args.getLastArg(OPT_print_symbol_order))
2151     config->printSymbolOrder = arg->getValue();
2152 
2153   // Identify unreferenced COMDAT sections.
2154   if (config->doGC)
2155     markLive(symtab->getChunks());
2156 
2157   // Needs to happen after the last call to addFile().
2158   convertResources();
2159 
2160   // Identify identical COMDAT sections to merge them.
2161   if (config->doICF) {
2162     findKeepUniqueSections();
2163     doICF(symtab->getChunks());
2164   }
2165 
2166   // Write the result.
2167   writeResult();
2168 
2169   // Stop early so we can print the results.
2170   rootTimer.stop();
2171   if (config->showTiming)
2172     Timer::root().print();
2173 }
2174 
2175 } // namespace coff
2176 } // namespace lld
2177