xref: /freebsd/contrib/llvm-project/lld/COFF/Driver.cpp (revision 753f127f3ace09432b2baeffd71a308760641a62)
10b57cec5SDimitry Andric //===- Driver.cpp ---------------------------------------------------------===//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric 
90b57cec5SDimitry Andric #include "Driver.h"
10349cc55cSDimitry Andric #include "COFFLinkerContext.h"
110b57cec5SDimitry Andric #include "Config.h"
120b57cec5SDimitry Andric #include "DebugTypes.h"
130b57cec5SDimitry Andric #include "ICF.h"
140b57cec5SDimitry Andric #include "InputFiles.h"
150b57cec5SDimitry Andric #include "MarkLive.h"
160b57cec5SDimitry Andric #include "MinGW.h"
170b57cec5SDimitry Andric #include "SymbolTable.h"
180b57cec5SDimitry Andric #include "Symbols.h"
190b57cec5SDimitry Andric #include "Writer.h"
200b57cec5SDimitry Andric #include "lld/Common/Args.h"
210b57cec5SDimitry Andric #include "lld/Common/Driver.h"
220b57cec5SDimitry Andric #include "lld/Common/Filesystem.h"
230b57cec5SDimitry Andric #include "lld/Common/Timer.h"
240b57cec5SDimitry Andric #include "lld/Common/Version.h"
2581ad6265SDimitry Andric #include "llvm/ADT/IntrusiveRefCntPtr.h"
260b57cec5SDimitry Andric #include "llvm/ADT/Optional.h"
270b57cec5SDimitry Andric #include "llvm/ADT/StringSwitch.h"
2881ad6265SDimitry Andric #include "llvm/ADT/Triple.h"
290b57cec5SDimitry Andric #include "llvm/BinaryFormat/Magic.h"
30e8d8bef9SDimitry Andric #include "llvm/Config/llvm-config.h"
3185868e8aSDimitry Andric #include "llvm/LTO/LTO.h"
320b57cec5SDimitry Andric #include "llvm/Object/ArchiveWriter.h"
330b57cec5SDimitry Andric #include "llvm/Object/COFFImportFile.h"
340b57cec5SDimitry Andric #include "llvm/Object/COFFModuleDefinition.h"
350b57cec5SDimitry Andric #include "llvm/Object/WindowsMachineFlag.h"
360b57cec5SDimitry Andric #include "llvm/Option/Arg.h"
370b57cec5SDimitry Andric #include "llvm/Option/ArgList.h"
380b57cec5SDimitry Andric #include "llvm/Option/Option.h"
39e8d8bef9SDimitry Andric #include "llvm/Support/BinaryStreamReader.h"
40480093f4SDimitry Andric #include "llvm/Support/CommandLine.h"
410b57cec5SDimitry Andric #include "llvm/Support/Debug.h"
420b57cec5SDimitry Andric #include "llvm/Support/LEB128.h"
430b57cec5SDimitry Andric #include "llvm/Support/MathExtras.h"
445ffd83dbSDimitry Andric #include "llvm/Support/Parallel.h"
450b57cec5SDimitry Andric #include "llvm/Support/Path.h"
460b57cec5SDimitry Andric #include "llvm/Support/Process.h"
470b57cec5SDimitry Andric #include "llvm/Support/TarWriter.h"
480b57cec5SDimitry Andric #include "llvm/Support/TargetSelect.h"
4981ad6265SDimitry Andric #include "llvm/Support/VirtualFileSystem.h"
500b57cec5SDimitry Andric #include "llvm/Support/raw_ostream.h"
510b57cec5SDimitry Andric #include "llvm/ToolDrivers/llvm-lib/LibDriver.h"
520b57cec5SDimitry Andric #include <algorithm>
530b57cec5SDimitry Andric #include <future>
540b57cec5SDimitry Andric #include <memory>
550b57cec5SDimitry Andric 
560b57cec5SDimitry Andric using namespace llvm;
570b57cec5SDimitry Andric using namespace llvm::object;
580b57cec5SDimitry Andric using namespace llvm::COFF;
59fe6060f1SDimitry Andric using namespace llvm::sys;
600b57cec5SDimitry Andric 
610b57cec5SDimitry Andric namespace lld {
620b57cec5SDimitry Andric namespace coff {
630b57cec5SDimitry Andric 
6404eeddc0SDimitry Andric std::unique_ptr<Configuration> config;
6504eeddc0SDimitry Andric std::unique_ptr<LinkerDriver> driver;
660b57cec5SDimitry Andric 
6704eeddc0SDimitry Andric bool link(ArrayRef<const char *> args, llvm::raw_ostream &stdoutOS,
6804eeddc0SDimitry Andric           llvm::raw_ostream &stderrOS, bool exitEarly, bool disableOutput) {
6904eeddc0SDimitry Andric   // This driver-specific context will be freed later by lldMain().
7004eeddc0SDimitry Andric   auto *ctx = new COFFLinkerContext;
71480093f4SDimitry Andric 
7204eeddc0SDimitry Andric   ctx->e.initialize(stdoutOS, stderrOS, exitEarly, disableOutput);
7304eeddc0SDimitry Andric   ctx->e.logName = args::getFilenameWithoutExe(args[0]);
7404eeddc0SDimitry Andric   ctx->e.errorLimitExceededMsg = "too many errors emitted, stopping now"
750b57cec5SDimitry Andric                                  " (use /errorlimit:0 to see all errors)";
7685868e8aSDimitry Andric 
7704eeddc0SDimitry Andric   config = std::make_unique<Configuration>();
7804eeddc0SDimitry Andric   driver = std::make_unique<LinkerDriver>(*ctx);
7985868e8aSDimitry Andric 
80e8d8bef9SDimitry Andric   driver->linkerMain(args);
810b57cec5SDimitry Andric 
8204eeddc0SDimitry Andric   return errorCount() == 0;
830b57cec5SDimitry Andric }
840b57cec5SDimitry Andric 
850b57cec5SDimitry Andric // Parse options of the form "old;new".
860b57cec5SDimitry Andric static std::pair<StringRef, StringRef> getOldNewOptions(opt::InputArgList &args,
870b57cec5SDimitry Andric                                                         unsigned id) {
880b57cec5SDimitry Andric   auto *arg = args.getLastArg(id);
890b57cec5SDimitry Andric   if (!arg)
900b57cec5SDimitry Andric     return {"", ""};
910b57cec5SDimitry Andric 
920b57cec5SDimitry Andric   StringRef s = arg->getValue();
930b57cec5SDimitry Andric   std::pair<StringRef, StringRef> ret = s.split(';');
940b57cec5SDimitry Andric   if (ret.second.empty())
950b57cec5SDimitry Andric     error(arg->getSpelling() + " expects 'old;new' format, but got " + s);
960b57cec5SDimitry Andric   return ret;
970b57cec5SDimitry Andric }
980b57cec5SDimitry Andric 
99480093f4SDimitry Andric // Drop directory components and replace extension with
100480093f4SDimitry Andric // ".exe", ".dll" or ".sys".
1010b57cec5SDimitry Andric static std::string getOutputPath(StringRef path) {
102480093f4SDimitry Andric   StringRef ext = ".exe";
103480093f4SDimitry Andric   if (config->dll)
104480093f4SDimitry Andric     ext = ".dll";
105480093f4SDimitry Andric   else if (config->driver)
106480093f4SDimitry Andric     ext = ".sys";
107480093f4SDimitry Andric 
108480093f4SDimitry Andric   return (sys::path::stem(path) + ext).str();
1090b57cec5SDimitry Andric }
1100b57cec5SDimitry Andric 
1110b57cec5SDimitry Andric // Returns true if S matches /crtend.?\.o$/.
1120b57cec5SDimitry Andric static bool isCrtend(StringRef s) {
1130b57cec5SDimitry Andric   if (!s.endswith(".o"))
1140b57cec5SDimitry Andric     return false;
1150b57cec5SDimitry Andric   s = s.drop_back(2);
1160b57cec5SDimitry Andric   if (s.endswith("crtend"))
1170b57cec5SDimitry Andric     return true;
1180b57cec5SDimitry Andric   return !s.empty() && s.drop_back().endswith("crtend");
1190b57cec5SDimitry Andric }
1200b57cec5SDimitry Andric 
1210b57cec5SDimitry Andric // ErrorOr is not default constructible, so it cannot be used as the type
1220b57cec5SDimitry Andric // parameter of a future.
1230b57cec5SDimitry Andric // FIXME: We could open the file in createFutureForFile and avoid needing to
1240b57cec5SDimitry Andric // return an error here, but for the moment that would cost us a file descriptor
1250b57cec5SDimitry Andric // (a limited resource on Windows) for the duration that the future is pending.
1260b57cec5SDimitry Andric using MBErrPair = std::pair<std::unique_ptr<MemoryBuffer>, std::error_code>;
1270b57cec5SDimitry Andric 
1280b57cec5SDimitry Andric // Create a std::future that opens and maps a file using the best strategy for
1290b57cec5SDimitry Andric // the host platform.
1300b57cec5SDimitry Andric static std::future<MBErrPair> createFutureForFile(std::string path) {
131fe6060f1SDimitry Andric #if _WIN64
1320b57cec5SDimitry Andric   // On Windows, file I/O is relatively slow so it is best to do this
133fe6060f1SDimitry Andric   // asynchronously.  But 32-bit has issues with potentially launching tons
134fe6060f1SDimitry Andric   // of threads
1350b57cec5SDimitry Andric   auto strategy = std::launch::async;
1360b57cec5SDimitry Andric #else
1370b57cec5SDimitry Andric   auto strategy = std::launch::deferred;
1380b57cec5SDimitry Andric #endif
1390b57cec5SDimitry Andric   return std::async(strategy, [=]() {
140fe6060f1SDimitry Andric     auto mbOrErr = MemoryBuffer::getFile(path, /*IsText=*/false,
141fe6060f1SDimitry Andric                                          /*RequiresNullTerminator=*/false);
1420b57cec5SDimitry Andric     if (!mbOrErr)
1430b57cec5SDimitry Andric       return MBErrPair{nullptr, mbOrErr.getError()};
1440b57cec5SDimitry Andric     return MBErrPair{std::move(*mbOrErr), std::error_code()};
1450b57cec5SDimitry Andric   });
1460b57cec5SDimitry Andric }
1470b57cec5SDimitry Andric 
1480b57cec5SDimitry Andric // Symbol names are mangled by prepending "_" on x86.
1490b57cec5SDimitry Andric static StringRef mangle(StringRef sym) {
1500b57cec5SDimitry Andric   assert(config->machine != IMAGE_FILE_MACHINE_UNKNOWN);
1510b57cec5SDimitry Andric   if (config->machine == I386)
15204eeddc0SDimitry Andric     return saver().save("_" + sym);
1530b57cec5SDimitry Andric   return sym;
1540b57cec5SDimitry Andric }
1550b57cec5SDimitry Andric 
15681ad6265SDimitry Andric static llvm::Triple::ArchType getArch() {
15781ad6265SDimitry Andric   switch (config->machine) {
15881ad6265SDimitry Andric   case I386:
15981ad6265SDimitry Andric     return llvm::Triple::ArchType::x86;
16081ad6265SDimitry Andric   case AMD64:
16181ad6265SDimitry Andric     return llvm::Triple::ArchType::x86_64;
16281ad6265SDimitry Andric   case ARMNT:
16381ad6265SDimitry Andric     return llvm::Triple::ArchType::arm;
16481ad6265SDimitry Andric   case ARM64:
16581ad6265SDimitry Andric     return llvm::Triple::ArchType::aarch64;
16681ad6265SDimitry Andric   default:
16781ad6265SDimitry Andric     return llvm::Triple::ArchType::UnknownArch;
16881ad6265SDimitry Andric   }
16981ad6265SDimitry Andric }
17081ad6265SDimitry Andric 
171349cc55cSDimitry Andric bool LinkerDriver::findUnderscoreMangle(StringRef sym) {
172349cc55cSDimitry Andric   Symbol *s = ctx.symtab.findMangle(mangle(sym));
1730b57cec5SDimitry Andric   return s && !isa<Undefined>(s);
1740b57cec5SDimitry Andric }
1750b57cec5SDimitry Andric 
1760b57cec5SDimitry Andric MemoryBufferRef LinkerDriver::takeBuffer(std::unique_ptr<MemoryBuffer> mb) {
1770b57cec5SDimitry Andric   MemoryBufferRef mbref = *mb;
1780b57cec5SDimitry Andric   make<std::unique_ptr<MemoryBuffer>>(std::move(mb)); // take ownership
1790b57cec5SDimitry Andric 
1800b57cec5SDimitry Andric   if (driver->tar)
1810b57cec5SDimitry Andric     driver->tar->append(relativeToRoot(mbref.getBufferIdentifier()),
1820b57cec5SDimitry Andric                         mbref.getBuffer());
1830b57cec5SDimitry Andric   return mbref;
1840b57cec5SDimitry Andric }
1850b57cec5SDimitry Andric 
1860b57cec5SDimitry Andric void LinkerDriver::addBuffer(std::unique_ptr<MemoryBuffer> mb,
18785868e8aSDimitry Andric                              bool wholeArchive, bool lazy) {
1880b57cec5SDimitry Andric   StringRef filename = mb->getBufferIdentifier();
1890b57cec5SDimitry Andric 
1900b57cec5SDimitry Andric   MemoryBufferRef mbref = takeBuffer(std::move(mb));
1910b57cec5SDimitry Andric   filePaths.push_back(filename);
1920b57cec5SDimitry Andric 
1930b57cec5SDimitry Andric   // File type is detected by contents, not by file extension.
1940b57cec5SDimitry Andric   switch (identify_magic(mbref.getBuffer())) {
1950b57cec5SDimitry Andric   case file_magic::windows_resource:
1960b57cec5SDimitry Andric     resources.push_back(mbref);
1970b57cec5SDimitry Andric     break;
1980b57cec5SDimitry Andric   case file_magic::archive:
1990b57cec5SDimitry Andric     if (wholeArchive) {
2000b57cec5SDimitry Andric       std::unique_ptr<Archive> file =
2010b57cec5SDimitry Andric           CHECK(Archive::create(mbref), filename + ": failed to parse archive");
2020b57cec5SDimitry Andric       Archive *archive = file.get();
2030b57cec5SDimitry Andric       make<std::unique_ptr<Archive>>(std::move(file)); // take ownership
2040b57cec5SDimitry Andric 
20585868e8aSDimitry Andric       int memberIndex = 0;
2060b57cec5SDimitry Andric       for (MemoryBufferRef m : getArchiveMembers(archive))
20785868e8aSDimitry Andric         addArchiveBuffer(m, "<whole-archive>", filename, memberIndex++);
2080b57cec5SDimitry Andric       return;
2090b57cec5SDimitry Andric     }
210349cc55cSDimitry Andric     ctx.symtab.addFile(make<ArchiveFile>(ctx, mbref));
2110b57cec5SDimitry Andric     break;
2120b57cec5SDimitry Andric   case file_magic::bitcode:
21304eeddc0SDimitry Andric     ctx.symtab.addFile(make<BitcodeFile>(ctx, mbref, "", 0, lazy));
2140b57cec5SDimitry Andric     break;
2150b57cec5SDimitry Andric   case file_magic::coff_object:
2160b57cec5SDimitry Andric   case file_magic::coff_import_library:
21704eeddc0SDimitry Andric     ctx.symtab.addFile(make<ObjFile>(ctx, mbref, lazy));
2180b57cec5SDimitry Andric     break;
2190b57cec5SDimitry Andric   case file_magic::pdb:
220349cc55cSDimitry Andric     ctx.symtab.addFile(make<PDBInputFile>(ctx, mbref));
2210b57cec5SDimitry Andric     break;
2220b57cec5SDimitry Andric   case file_magic::coff_cl_gl_object:
2230b57cec5SDimitry Andric     error(filename + ": is not a native COFF file. Recompile without /GL");
2240b57cec5SDimitry Andric     break;
2250b57cec5SDimitry Andric   case file_magic::pecoff_executable:
226fe6060f1SDimitry Andric     if (config->mingw) {
227349cc55cSDimitry Andric       ctx.symtab.addFile(make<DLLFile>(ctx, mbref));
228fe6060f1SDimitry Andric       break;
229fe6060f1SDimitry Andric     }
230fe6060f1SDimitry Andric     if (filename.endswith_insensitive(".dll")) {
2310b57cec5SDimitry Andric       error(filename + ": bad file type. Did you specify a DLL instead of an "
2320b57cec5SDimitry Andric                        "import library?");
2330b57cec5SDimitry Andric       break;
2340b57cec5SDimitry Andric     }
2350b57cec5SDimitry Andric     LLVM_FALLTHROUGH;
2360b57cec5SDimitry Andric   default:
2370b57cec5SDimitry Andric     error(mbref.getBufferIdentifier() + ": unknown file type");
2380b57cec5SDimitry Andric     break;
2390b57cec5SDimitry Andric   }
2400b57cec5SDimitry Andric }
2410b57cec5SDimitry Andric 
24285868e8aSDimitry Andric void LinkerDriver::enqueuePath(StringRef path, bool wholeArchive, bool lazy) {
2435ffd83dbSDimitry Andric   auto future = std::make_shared<std::future<MBErrPair>>(
2445ffd83dbSDimitry Andric       createFutureForFile(std::string(path)));
2455ffd83dbSDimitry Andric   std::string pathStr = std::string(path);
2460b57cec5SDimitry Andric   enqueueTask([=]() {
2470b57cec5SDimitry Andric     auto mbOrErr = future->get();
2480b57cec5SDimitry Andric     if (mbOrErr.second) {
2490b57cec5SDimitry Andric       std::string msg =
2500b57cec5SDimitry Andric           "could not open '" + pathStr + "': " + mbOrErr.second.message();
2510b57cec5SDimitry Andric       // Check if the filename is a typo for an option flag. OptTable thinks
2520b57cec5SDimitry Andric       // that all args that are not known options and that start with / are
2530b57cec5SDimitry Andric       // filenames, but e.g. `/nodefaultlibs` is more likely a typo for
2540b57cec5SDimitry Andric       // the option `/nodefaultlib` than a reference to a file in the root
2550b57cec5SDimitry Andric       // directory.
2560b57cec5SDimitry Andric       std::string nearest;
2575ffd83dbSDimitry Andric       if (optTable.findNearest(pathStr, nearest) > 1)
2580b57cec5SDimitry Andric         error(msg);
2590b57cec5SDimitry Andric       else
2600b57cec5SDimitry Andric         error(msg + "; did you mean '" + nearest + "'");
2610b57cec5SDimitry Andric     } else
26285868e8aSDimitry Andric       driver->addBuffer(std::move(mbOrErr.first), wholeArchive, lazy);
2630b57cec5SDimitry Andric   });
2640b57cec5SDimitry Andric }
2650b57cec5SDimitry Andric 
2660b57cec5SDimitry Andric void LinkerDriver::addArchiveBuffer(MemoryBufferRef mb, StringRef symName,
2670b57cec5SDimitry Andric                                     StringRef parentName,
2680b57cec5SDimitry Andric                                     uint64_t offsetInArchive) {
2690b57cec5SDimitry Andric   file_magic magic = identify_magic(mb.getBuffer());
2700b57cec5SDimitry Andric   if (magic == file_magic::coff_import_library) {
271349cc55cSDimitry Andric     InputFile *imp = make<ImportFile>(ctx, mb);
2720b57cec5SDimitry Andric     imp->parentName = parentName;
273349cc55cSDimitry Andric     ctx.symtab.addFile(imp);
2740b57cec5SDimitry Andric     return;
2750b57cec5SDimitry Andric   }
2760b57cec5SDimitry Andric 
2770b57cec5SDimitry Andric   InputFile *obj;
2780b57cec5SDimitry Andric   if (magic == file_magic::coff_object) {
279349cc55cSDimitry Andric     obj = make<ObjFile>(ctx, mb);
2800b57cec5SDimitry Andric   } else if (magic == file_magic::bitcode) {
28104eeddc0SDimitry Andric     obj =
28204eeddc0SDimitry Andric         make<BitcodeFile>(ctx, mb, parentName, offsetInArchive, /*lazy=*/false);
2830b57cec5SDimitry Andric   } else {
2840b57cec5SDimitry Andric     error("unknown file type: " + mb.getBufferIdentifier());
2850b57cec5SDimitry Andric     return;
2860b57cec5SDimitry Andric   }
2870b57cec5SDimitry Andric 
2880b57cec5SDimitry Andric   obj->parentName = parentName;
289349cc55cSDimitry Andric   ctx.symtab.addFile(obj);
2900b57cec5SDimitry Andric   log("Loaded " + toString(obj) + " for " + symName);
2910b57cec5SDimitry Andric }
2920b57cec5SDimitry Andric 
2930b57cec5SDimitry Andric void LinkerDriver::enqueueArchiveMember(const Archive::Child &c,
2940b57cec5SDimitry Andric                                         const Archive::Symbol &sym,
2950b57cec5SDimitry Andric                                         StringRef parentName) {
2960b57cec5SDimitry Andric 
2970b57cec5SDimitry Andric   auto reportBufferError = [=](Error &&e, StringRef childName) {
2980b57cec5SDimitry Andric     fatal("could not get the buffer for the member defining symbol " +
2990b57cec5SDimitry Andric           toCOFFString(sym) + ": " + parentName + "(" + childName + "): " +
3000b57cec5SDimitry Andric           toString(std::move(e)));
3010b57cec5SDimitry Andric   };
3020b57cec5SDimitry Andric 
3030b57cec5SDimitry Andric   if (!c.getParent()->isThin()) {
3040b57cec5SDimitry Andric     uint64_t offsetInArchive = c.getChildOffset();
3050b57cec5SDimitry Andric     Expected<MemoryBufferRef> mbOrErr = c.getMemoryBufferRef();
3060b57cec5SDimitry Andric     if (!mbOrErr)
3070b57cec5SDimitry Andric       reportBufferError(mbOrErr.takeError(), check(c.getFullName()));
3080b57cec5SDimitry Andric     MemoryBufferRef mb = mbOrErr.get();
3090b57cec5SDimitry Andric     enqueueTask([=]() {
3100b57cec5SDimitry Andric       driver->addArchiveBuffer(mb, toCOFFString(sym), parentName,
3110b57cec5SDimitry Andric                                offsetInArchive);
3120b57cec5SDimitry Andric     });
3130b57cec5SDimitry Andric     return;
3140b57cec5SDimitry Andric   }
3150b57cec5SDimitry Andric 
3160b57cec5SDimitry Andric   std::string childName = CHECK(
3170b57cec5SDimitry Andric       c.getFullName(),
3180b57cec5SDimitry Andric       "could not get the filename for the member defining symbol " +
3190b57cec5SDimitry Andric       toCOFFString(sym));
3200b57cec5SDimitry Andric   auto future = std::make_shared<std::future<MBErrPair>>(
3210b57cec5SDimitry Andric       createFutureForFile(childName));
3220b57cec5SDimitry Andric   enqueueTask([=]() {
3230b57cec5SDimitry Andric     auto mbOrErr = future->get();
3240b57cec5SDimitry Andric     if (mbOrErr.second)
3250b57cec5SDimitry Andric       reportBufferError(errorCodeToError(mbOrErr.second), childName);
32685868e8aSDimitry Andric     // Pass empty string as archive name so that the original filename is
32785868e8aSDimitry Andric     // used as the buffer identifier.
3280b57cec5SDimitry Andric     driver->addArchiveBuffer(takeBuffer(std::move(mbOrErr.first)),
32985868e8aSDimitry Andric                              toCOFFString(sym), "", /*OffsetInArchive=*/0);
3300b57cec5SDimitry Andric   });
3310b57cec5SDimitry Andric }
3320b57cec5SDimitry Andric 
3330b57cec5SDimitry Andric static bool isDecorated(StringRef sym) {
3340b57cec5SDimitry Andric   return sym.startswith("@") || sym.contains("@@") || sym.startswith("?") ||
3350b57cec5SDimitry Andric          (!config->mingw && sym.contains('@'));
3360b57cec5SDimitry Andric }
3370b57cec5SDimitry Andric 
3380b57cec5SDimitry Andric // Parses .drectve section contents and returns a list of files
3390b57cec5SDimitry Andric // specified by /defaultlib.
3400b57cec5SDimitry Andric void LinkerDriver::parseDirectives(InputFile *file) {
3410b57cec5SDimitry Andric   StringRef s = file->getDirectives();
3420b57cec5SDimitry Andric   if (s.empty())
3430b57cec5SDimitry Andric     return;
3440b57cec5SDimitry Andric 
3450b57cec5SDimitry Andric   log("Directives: " + toString(file) + ": " + s);
3460b57cec5SDimitry Andric 
3470b57cec5SDimitry Andric   ArgParser parser;
3480b57cec5SDimitry Andric   // .drectve is always tokenized using Windows shell rules.
3490b57cec5SDimitry Andric   // /EXPORT: option can appear too many times, processing in fastpath.
3505ffd83dbSDimitry Andric   ParsedDirectives directives = parser.parseDirectives(s);
3510b57cec5SDimitry Andric 
3525ffd83dbSDimitry Andric   for (StringRef e : directives.exports) {
3530b57cec5SDimitry Andric     // If a common header file contains dllexported function
3540b57cec5SDimitry Andric     // declarations, many object files may end up with having the
3550b57cec5SDimitry Andric     // same /EXPORT options. In order to save cost of parsing them,
3560b57cec5SDimitry Andric     // we dedup them first.
3570b57cec5SDimitry Andric     if (!directivesExports.insert(e).second)
3580b57cec5SDimitry Andric       continue;
3590b57cec5SDimitry Andric 
3600b57cec5SDimitry Andric     Export exp = parseExport(e);
3610b57cec5SDimitry Andric     if (config->machine == I386 && config->mingw) {
3620b57cec5SDimitry Andric       if (!isDecorated(exp.name))
36304eeddc0SDimitry Andric         exp.name = saver().save("_" + exp.name);
3640b57cec5SDimitry Andric       if (!exp.extName.empty() && !isDecorated(exp.extName))
36504eeddc0SDimitry Andric         exp.extName = saver().save("_" + exp.extName);
3660b57cec5SDimitry Andric     }
3670b57cec5SDimitry Andric     exp.directives = true;
3680b57cec5SDimitry Andric     config->exports.push_back(exp);
3690b57cec5SDimitry Andric   }
3700b57cec5SDimitry Andric 
3715ffd83dbSDimitry Andric   // Handle /include: in bulk.
3725ffd83dbSDimitry Andric   for (StringRef inc : directives.includes)
3735ffd83dbSDimitry Andric     addUndefined(inc);
3745ffd83dbSDimitry Andric 
375349cc55cSDimitry Andric   // https://docs.microsoft.com/en-us/cpp/preprocessor/comment-c-cpp?view=msvc-160
3765ffd83dbSDimitry Andric   for (auto *arg : directives.args) {
3770b57cec5SDimitry Andric     switch (arg->getOption().getID()) {
3780b57cec5SDimitry Andric     case OPT_aligncomm:
3790b57cec5SDimitry Andric       parseAligncomm(arg->getValue());
3800b57cec5SDimitry Andric       break;
3810b57cec5SDimitry Andric     case OPT_alternatename:
3820b57cec5SDimitry Andric       parseAlternateName(arg->getValue());
3830b57cec5SDimitry Andric       break;
3840b57cec5SDimitry Andric     case OPT_defaultlib:
3850b57cec5SDimitry Andric       if (Optional<StringRef> path = findLib(arg->getValue()))
38685868e8aSDimitry Andric         enqueuePath(*path, false, false);
3870b57cec5SDimitry Andric       break;
3880b57cec5SDimitry Andric     case OPT_entry:
3890b57cec5SDimitry Andric       config->entry = addUndefined(mangle(arg->getValue()));
3900b57cec5SDimitry Andric       break;
3910b57cec5SDimitry Andric     case OPT_failifmismatch:
3920b57cec5SDimitry Andric       checkFailIfMismatch(arg->getValue(), file);
3930b57cec5SDimitry Andric       break;
3940b57cec5SDimitry Andric     case OPT_incl:
3950b57cec5SDimitry Andric       addUndefined(arg->getValue());
3960b57cec5SDimitry Andric       break;
397349cc55cSDimitry Andric     case OPT_manifestdependency:
398349cc55cSDimitry Andric       config->manifestDependencies.insert(arg->getValue());
399349cc55cSDimitry Andric       break;
4000b57cec5SDimitry Andric     case OPT_merge:
4010b57cec5SDimitry Andric       parseMerge(arg->getValue());
4020b57cec5SDimitry Andric       break;
4030b57cec5SDimitry Andric     case OPT_nodefaultlib:
4040b57cec5SDimitry Andric       config->noDefaultLibs.insert(doFindLib(arg->getValue()).lower());
4050b57cec5SDimitry Andric       break;
4060b57cec5SDimitry Andric     case OPT_section:
4070b57cec5SDimitry Andric       parseSection(arg->getValue());
4080b57cec5SDimitry Andric       break;
409fe6060f1SDimitry Andric     case OPT_stack:
410fe6060f1SDimitry Andric       parseNumbers(arg->getValue(), &config->stackReserve,
411fe6060f1SDimitry Andric                    &config->stackCommit);
412fe6060f1SDimitry Andric       break;
413e8d8bef9SDimitry Andric     case OPT_subsystem: {
414e8d8bef9SDimitry Andric       bool gotVersion = false;
4150b57cec5SDimitry Andric       parseSubsystem(arg->getValue(), &config->subsystem,
416e8d8bef9SDimitry Andric                      &config->majorSubsystemVersion,
417e8d8bef9SDimitry Andric                      &config->minorSubsystemVersion, &gotVersion);
418e8d8bef9SDimitry Andric       if (gotVersion) {
419e8d8bef9SDimitry Andric         config->majorOSVersion = config->majorSubsystemVersion;
420e8d8bef9SDimitry Andric         config->minorOSVersion = config->minorSubsystemVersion;
421e8d8bef9SDimitry Andric       }
4220b57cec5SDimitry Andric       break;
423e8d8bef9SDimitry Andric     }
4240b57cec5SDimitry Andric     // Only add flags here that link.exe accepts in
4250b57cec5SDimitry Andric     // `#pragma comment(linker, "/flag")`-generated sections.
4260b57cec5SDimitry Andric     case OPT_editandcontinue:
4270b57cec5SDimitry Andric     case OPT_guardsym:
4280b57cec5SDimitry Andric     case OPT_throwingnew:
4290b57cec5SDimitry Andric       break;
4300b57cec5SDimitry Andric     default:
4310b57cec5SDimitry Andric       error(arg->getSpelling() + " is not allowed in .drectve");
4320b57cec5SDimitry Andric     }
4330b57cec5SDimitry Andric   }
4340b57cec5SDimitry Andric }
4350b57cec5SDimitry Andric 
4360b57cec5SDimitry Andric // Find file from search paths. You can omit ".obj", this function takes
4370b57cec5SDimitry Andric // care of that. Note that the returned path is not guaranteed to exist.
4380b57cec5SDimitry Andric StringRef LinkerDriver::doFindFile(StringRef filename) {
439*753f127fSDimitry Andric   auto getFilename = [](StringRef filename) -> StringRef {
440*753f127fSDimitry Andric     if (config->vfs)
441*753f127fSDimitry Andric       if (auto statOrErr = config->vfs->status(filename))
442*753f127fSDimitry Andric         return saver().save(statOrErr->getName());
443*753f127fSDimitry Andric     return filename;
444*753f127fSDimitry Andric   };
445*753f127fSDimitry Andric 
4460b57cec5SDimitry Andric   bool hasPathSep = (filename.find_first_of("/\\") != StringRef::npos);
4470b57cec5SDimitry Andric   if (hasPathSep)
448*753f127fSDimitry Andric     return getFilename(filename);
4490b57cec5SDimitry Andric   bool hasExt = filename.contains('.');
4500b57cec5SDimitry Andric   for (StringRef dir : searchPaths) {
4510b57cec5SDimitry Andric     SmallString<128> path = dir;
4520b57cec5SDimitry Andric     sys::path::append(path, filename);
453*753f127fSDimitry Andric     path = SmallString<128>{getFilename(path.str())};
4540b57cec5SDimitry Andric     if (sys::fs::exists(path.str()))
45504eeddc0SDimitry Andric       return saver().save(path.str());
4560b57cec5SDimitry Andric     if (!hasExt) {
4570b57cec5SDimitry Andric       path.append(".obj");
458*753f127fSDimitry Andric       path = SmallString<128>{getFilename(path.str())};
4590b57cec5SDimitry Andric       if (sys::fs::exists(path.str()))
46004eeddc0SDimitry Andric         return saver().save(path.str());
4610b57cec5SDimitry Andric     }
4620b57cec5SDimitry Andric   }
4630b57cec5SDimitry Andric   return filename;
4640b57cec5SDimitry Andric }
4650b57cec5SDimitry Andric 
4660b57cec5SDimitry Andric static Optional<sys::fs::UniqueID> getUniqueID(StringRef path) {
4670b57cec5SDimitry Andric   sys::fs::UniqueID ret;
4680b57cec5SDimitry Andric   if (sys::fs::getUniqueID(path, ret))
4690b57cec5SDimitry Andric     return None;
4700b57cec5SDimitry Andric   return ret;
4710b57cec5SDimitry Andric }
4720b57cec5SDimitry Andric 
4730b57cec5SDimitry Andric // Resolves a file path. This never returns the same path
4740b57cec5SDimitry Andric // (in that case, it returns None).
4750b57cec5SDimitry Andric Optional<StringRef> LinkerDriver::findFile(StringRef filename) {
4760b57cec5SDimitry Andric   StringRef path = doFindFile(filename);
4770b57cec5SDimitry Andric 
4780b57cec5SDimitry Andric   if (Optional<sys::fs::UniqueID> id = getUniqueID(path)) {
4790b57cec5SDimitry Andric     bool seen = !visitedFiles.insert(*id).second;
4800b57cec5SDimitry Andric     if (seen)
4810b57cec5SDimitry Andric       return None;
4820b57cec5SDimitry Andric   }
4830b57cec5SDimitry Andric 
484fe6060f1SDimitry Andric   if (path.endswith_insensitive(".lib"))
48581ad6265SDimitry Andric     visitedLibs.insert(std::string(sys::path::filename(path).lower()));
4860b57cec5SDimitry Andric   return path;
4870b57cec5SDimitry Andric }
4880b57cec5SDimitry Andric 
4890b57cec5SDimitry Andric // MinGW specific. If an embedded directive specified to link to
4900b57cec5SDimitry Andric // foo.lib, but it isn't found, try libfoo.a instead.
4910b57cec5SDimitry Andric StringRef LinkerDriver::doFindLibMinGW(StringRef filename) {
4920b57cec5SDimitry Andric   if (filename.contains('/') || filename.contains('\\'))
4930b57cec5SDimitry Andric     return filename;
4940b57cec5SDimitry Andric 
4950b57cec5SDimitry Andric   SmallString<128> s = filename;
4960b57cec5SDimitry Andric   sys::path::replace_extension(s, ".a");
49704eeddc0SDimitry Andric   StringRef libName = saver().save("lib" + s.str());
4980b57cec5SDimitry Andric   return doFindFile(libName);
4990b57cec5SDimitry Andric }
5000b57cec5SDimitry Andric 
5010b57cec5SDimitry Andric // Find library file from search path.
5020b57cec5SDimitry Andric StringRef LinkerDriver::doFindLib(StringRef filename) {
5030b57cec5SDimitry Andric   // Add ".lib" to Filename if that has no file extension.
5040b57cec5SDimitry Andric   bool hasExt = filename.contains('.');
5050b57cec5SDimitry Andric   if (!hasExt)
50604eeddc0SDimitry Andric     filename = saver().save(filename + ".lib");
5070b57cec5SDimitry Andric   StringRef ret = doFindFile(filename);
5080b57cec5SDimitry Andric   // For MinGW, if the find above didn't turn up anything, try
5090b57cec5SDimitry Andric   // looking for a MinGW formatted library name.
5100b57cec5SDimitry Andric   if (config->mingw && ret == filename)
5110b57cec5SDimitry Andric     return doFindLibMinGW(filename);
5120b57cec5SDimitry Andric   return ret;
5130b57cec5SDimitry Andric }
5140b57cec5SDimitry Andric 
5150b57cec5SDimitry Andric // Resolves a library path. /nodefaultlib options are taken into
5160b57cec5SDimitry Andric // consideration. This never returns the same path (in that case,
5170b57cec5SDimitry Andric // it returns None).
5180b57cec5SDimitry Andric Optional<StringRef> LinkerDriver::findLib(StringRef filename) {
5190b57cec5SDimitry Andric   if (config->noDefaultLibAll)
5200b57cec5SDimitry Andric     return None;
5210b57cec5SDimitry Andric   if (!visitedLibs.insert(filename.lower()).second)
5220b57cec5SDimitry Andric     return None;
5230b57cec5SDimitry Andric 
5240b57cec5SDimitry Andric   StringRef path = doFindLib(filename);
5250b57cec5SDimitry Andric   if (config->noDefaultLibs.count(path.lower()))
5260b57cec5SDimitry Andric     return None;
5270b57cec5SDimitry Andric 
5280b57cec5SDimitry Andric   if (Optional<sys::fs::UniqueID> id = getUniqueID(path))
5290b57cec5SDimitry Andric     if (!visitedFiles.insert(*id).second)
5300b57cec5SDimitry Andric       return None;
5310b57cec5SDimitry Andric   return path;
5320b57cec5SDimitry Andric }
5330b57cec5SDimitry Andric 
53481ad6265SDimitry Andric void LinkerDriver::detectWinSysRoot(const opt::InputArgList &Args) {
53581ad6265SDimitry Andric   IntrusiveRefCntPtr<vfs::FileSystem> VFS = vfs::getRealFileSystem();
53681ad6265SDimitry Andric 
53781ad6265SDimitry Andric   // Check the command line first, that's the user explicitly telling us what to
53881ad6265SDimitry Andric   // use. Check the environment next, in case we're being invoked from a VS
53981ad6265SDimitry Andric   // command prompt. Failing that, just try to find the newest Visual Studio
54081ad6265SDimitry Andric   // version we can and use its default VC toolchain.
54181ad6265SDimitry Andric   Optional<StringRef> VCToolsDir, VCToolsVersion, WinSysRoot;
54281ad6265SDimitry Andric   if (auto *A = Args.getLastArg(OPT_vctoolsdir))
54381ad6265SDimitry Andric     VCToolsDir = A->getValue();
54481ad6265SDimitry Andric   if (auto *A = Args.getLastArg(OPT_vctoolsversion))
54581ad6265SDimitry Andric     VCToolsVersion = A->getValue();
54681ad6265SDimitry Andric   if (auto *A = Args.getLastArg(OPT_winsysroot))
54781ad6265SDimitry Andric     WinSysRoot = A->getValue();
54881ad6265SDimitry Andric   if (!findVCToolChainViaCommandLine(*VFS, VCToolsDir, VCToolsVersion,
54981ad6265SDimitry Andric                                      WinSysRoot, vcToolChainPath, vsLayout) &&
55081ad6265SDimitry Andric       (Args.hasArg(OPT_lldignoreenv) ||
55181ad6265SDimitry Andric        !findVCToolChainViaEnvironment(*VFS, vcToolChainPath, vsLayout)) &&
55281ad6265SDimitry Andric       !findVCToolChainViaSetupConfig(*VFS, vcToolChainPath, vsLayout) &&
55381ad6265SDimitry Andric       !findVCToolChainViaRegistry(vcToolChainPath, vsLayout))
55481ad6265SDimitry Andric     return;
55581ad6265SDimitry Andric 
55681ad6265SDimitry Andric   // If the VC environment hasn't been configured (perhaps because the user did
55781ad6265SDimitry Andric   // not run vcvarsall), try to build a consistent link environment.  If the
55881ad6265SDimitry Andric   // environment variable is set however, assume the user knows what they're
55981ad6265SDimitry Andric   // doing. If the user passes /vctoolsdir or /winsdkdir, trust that over env
56081ad6265SDimitry Andric   // vars.
56181ad6265SDimitry Andric   if (const auto *A = Args.getLastArg(OPT_diasdkdir, OPT_winsysroot)) {
56281ad6265SDimitry Andric     diaPath = A->getValue();
56381ad6265SDimitry Andric     if (A->getOption().getID() == OPT_winsysroot)
56481ad6265SDimitry Andric       path::append(diaPath, "DIA SDK");
56581ad6265SDimitry Andric   }
56681ad6265SDimitry Andric   useWinSysRootLibPath = Args.hasArg(OPT_lldignoreenv) ||
56781ad6265SDimitry Andric                          !Process::GetEnv("LIB") ||
56881ad6265SDimitry Andric                          Args.getLastArg(OPT_vctoolsdir, OPT_winsysroot);
56981ad6265SDimitry Andric   if (Args.hasArg(OPT_lldignoreenv) || !Process::GetEnv("LIB") ||
57081ad6265SDimitry Andric       Args.getLastArg(OPT_winsdkdir, OPT_winsysroot)) {
57181ad6265SDimitry Andric     Optional<StringRef> WinSdkDir, WinSdkVersion;
57281ad6265SDimitry Andric     if (auto *A = Args.getLastArg(OPT_winsdkdir))
57381ad6265SDimitry Andric       WinSdkDir = A->getValue();
57481ad6265SDimitry Andric     if (auto *A = Args.getLastArg(OPT_winsdkversion))
57581ad6265SDimitry Andric       WinSdkVersion = A->getValue();
57681ad6265SDimitry Andric 
57781ad6265SDimitry Andric     if (useUniversalCRT(vsLayout, vcToolChainPath, getArch(), *VFS)) {
57881ad6265SDimitry Andric       std::string UniversalCRTSdkPath;
57981ad6265SDimitry Andric       std::string UCRTVersion;
58081ad6265SDimitry Andric       if (getUniversalCRTSdkDir(*VFS, WinSdkDir, WinSdkVersion, WinSysRoot,
58181ad6265SDimitry Andric                                 UniversalCRTSdkPath, UCRTVersion)) {
58281ad6265SDimitry Andric         universalCRTLibPath = UniversalCRTSdkPath;
58381ad6265SDimitry Andric         path::append(universalCRTLibPath, "Lib", UCRTVersion, "ucrt");
58481ad6265SDimitry Andric       }
58581ad6265SDimitry Andric     }
58681ad6265SDimitry Andric 
58781ad6265SDimitry Andric     std::string sdkPath;
58881ad6265SDimitry Andric     std::string windowsSDKIncludeVersion;
58981ad6265SDimitry Andric     std::string windowsSDKLibVersion;
59081ad6265SDimitry Andric     if (getWindowsSDKDir(*VFS, WinSdkDir, WinSdkVersion, WinSysRoot, sdkPath,
59181ad6265SDimitry Andric                          sdkMajor, windowsSDKIncludeVersion,
59281ad6265SDimitry Andric                          windowsSDKLibVersion)) {
59381ad6265SDimitry Andric       windowsSdkLibPath = sdkPath;
59481ad6265SDimitry Andric       path::append(windowsSdkLibPath, "Lib");
59581ad6265SDimitry Andric       if (sdkMajor >= 8)
59681ad6265SDimitry Andric         path::append(windowsSdkLibPath, windowsSDKLibVersion, "um");
59781ad6265SDimitry Andric     }
59881ad6265SDimitry Andric   }
59981ad6265SDimitry Andric }
60081ad6265SDimitry Andric 
60181ad6265SDimitry Andric void LinkerDriver::addWinSysRootLibSearchPaths() {
60281ad6265SDimitry Andric   if (!diaPath.empty()) {
60381ad6265SDimitry Andric     // The DIA SDK always uses the legacy vc arch, even in new MSVC versions.
60481ad6265SDimitry Andric     path::append(diaPath, "lib", archToLegacyVCArch(getArch()));
60581ad6265SDimitry Andric     searchPaths.push_back(saver().save(diaPath.str()));
60681ad6265SDimitry Andric   }
60781ad6265SDimitry Andric   if (useWinSysRootLibPath) {
60881ad6265SDimitry Andric     searchPaths.push_back(saver().save(getSubDirectoryPath(
60981ad6265SDimitry Andric         SubDirectoryType::Lib, vsLayout, vcToolChainPath, getArch())));
61081ad6265SDimitry Andric     searchPaths.push_back(saver().save(
61181ad6265SDimitry Andric         getSubDirectoryPath(SubDirectoryType::Lib, vsLayout, vcToolChainPath,
61281ad6265SDimitry Andric                             getArch(), "atlmfc")));
61381ad6265SDimitry Andric   }
61481ad6265SDimitry Andric   if (!universalCRTLibPath.empty()) {
61581ad6265SDimitry Andric     StringRef ArchName = archToWindowsSDKArch(getArch());
61681ad6265SDimitry Andric     if (!ArchName.empty()) {
61781ad6265SDimitry Andric       path::append(universalCRTLibPath, ArchName);
61881ad6265SDimitry Andric       searchPaths.push_back(saver().save(universalCRTLibPath.str()));
61981ad6265SDimitry Andric     }
62081ad6265SDimitry Andric   }
62181ad6265SDimitry Andric   if (!windowsSdkLibPath.empty()) {
62281ad6265SDimitry Andric     std::string path;
62381ad6265SDimitry Andric     if (appendArchToWindowsSDKLibPath(sdkMajor, windowsSdkLibPath, getArch(),
62481ad6265SDimitry Andric                                       path))
62581ad6265SDimitry Andric       searchPaths.push_back(saver().save(path));
62681ad6265SDimitry Andric   }
62781ad6265SDimitry Andric }
62881ad6265SDimitry Andric 
6290b57cec5SDimitry Andric // Parses LIB environment which contains a list of search paths.
6300b57cec5SDimitry Andric void LinkerDriver::addLibSearchPaths() {
6310b57cec5SDimitry Andric   Optional<std::string> envOpt = Process::GetEnv("LIB");
63281ad6265SDimitry Andric   if (!envOpt)
6330b57cec5SDimitry Andric     return;
63404eeddc0SDimitry Andric   StringRef env = saver().save(*envOpt);
6350b57cec5SDimitry Andric   while (!env.empty()) {
6360b57cec5SDimitry Andric     StringRef path;
6370b57cec5SDimitry Andric     std::tie(path, env) = env.split(';');
6380b57cec5SDimitry Andric     searchPaths.push_back(path);
6390b57cec5SDimitry Andric   }
6400b57cec5SDimitry Andric }
6410b57cec5SDimitry Andric 
6420b57cec5SDimitry Andric Symbol *LinkerDriver::addUndefined(StringRef name) {
643349cc55cSDimitry Andric   Symbol *b = ctx.symtab.addUndefined(name);
6440b57cec5SDimitry Andric   if (!b->isGCRoot) {
6450b57cec5SDimitry Andric     b->isGCRoot = true;
6460b57cec5SDimitry Andric     config->gcroot.push_back(b);
6470b57cec5SDimitry Andric   }
6480b57cec5SDimitry Andric   return b;
6490b57cec5SDimitry Andric }
6500b57cec5SDimitry Andric 
6510b57cec5SDimitry Andric StringRef LinkerDriver::mangleMaybe(Symbol *s) {
6520b57cec5SDimitry Andric   // If the plain symbol name has already been resolved, do nothing.
6530b57cec5SDimitry Andric   Undefined *unmangled = dyn_cast<Undefined>(s);
6540b57cec5SDimitry Andric   if (!unmangled)
6550b57cec5SDimitry Andric     return "";
6560b57cec5SDimitry Andric 
6570b57cec5SDimitry Andric   // Otherwise, see if a similar, mangled symbol exists in the symbol table.
658349cc55cSDimitry Andric   Symbol *mangled = ctx.symtab.findMangle(unmangled->getName());
6590b57cec5SDimitry Andric   if (!mangled)
6600b57cec5SDimitry Andric     return "";
6610b57cec5SDimitry Andric 
6620b57cec5SDimitry Andric   // If we find a similar mangled symbol, make this an alias to it and return
6630b57cec5SDimitry Andric   // its name.
6640b57cec5SDimitry Andric   log(unmangled->getName() + " aliased to " + mangled->getName());
665349cc55cSDimitry Andric   unmangled->weakAlias = ctx.symtab.addUndefined(mangled->getName());
6660b57cec5SDimitry Andric   return mangled->getName();
6670b57cec5SDimitry Andric }
6680b57cec5SDimitry Andric 
6690b57cec5SDimitry Andric // Windows specific -- find default entry point name.
6700b57cec5SDimitry Andric //
6710b57cec5SDimitry Andric // There are four different entry point functions for Windows executables,
6720b57cec5SDimitry Andric // each of which corresponds to a user-defined "main" function. This function
6730b57cec5SDimitry Andric // infers an entry point from a user-defined "main" function.
6740b57cec5SDimitry Andric StringRef LinkerDriver::findDefaultEntry() {
6750b57cec5SDimitry Andric   assert(config->subsystem != IMAGE_SUBSYSTEM_UNKNOWN &&
6760b57cec5SDimitry Andric          "must handle /subsystem before calling this");
6770b57cec5SDimitry Andric 
6780b57cec5SDimitry Andric   if (config->mingw)
6790b57cec5SDimitry Andric     return mangle(config->subsystem == IMAGE_SUBSYSTEM_WINDOWS_GUI
6800b57cec5SDimitry Andric                       ? "WinMainCRTStartup"
6810b57cec5SDimitry Andric                       : "mainCRTStartup");
6820b57cec5SDimitry Andric 
6830b57cec5SDimitry Andric   if (config->subsystem == IMAGE_SUBSYSTEM_WINDOWS_GUI) {
6840b57cec5SDimitry Andric     if (findUnderscoreMangle("wWinMain")) {
6850b57cec5SDimitry Andric       if (!findUnderscoreMangle("WinMain"))
6860b57cec5SDimitry Andric         return mangle("wWinMainCRTStartup");
6870b57cec5SDimitry Andric       warn("found both wWinMain and WinMain; using latter");
6880b57cec5SDimitry Andric     }
6890b57cec5SDimitry Andric     return mangle("WinMainCRTStartup");
6900b57cec5SDimitry Andric   }
6910b57cec5SDimitry Andric   if (findUnderscoreMangle("wmain")) {
6920b57cec5SDimitry Andric     if (!findUnderscoreMangle("main"))
6930b57cec5SDimitry Andric       return mangle("wmainCRTStartup");
6940b57cec5SDimitry Andric     warn("found both wmain and main; using latter");
6950b57cec5SDimitry Andric   }
6960b57cec5SDimitry Andric   return mangle("mainCRTStartup");
6970b57cec5SDimitry Andric }
6980b57cec5SDimitry Andric 
6990b57cec5SDimitry Andric WindowsSubsystem LinkerDriver::inferSubsystem() {
7000b57cec5SDimitry Andric   if (config->dll)
7010b57cec5SDimitry Andric     return IMAGE_SUBSYSTEM_WINDOWS_GUI;
7020b57cec5SDimitry Andric   if (config->mingw)
7030b57cec5SDimitry Andric     return IMAGE_SUBSYSTEM_WINDOWS_CUI;
7040b57cec5SDimitry Andric   // Note that link.exe infers the subsystem from the presence of these
7050b57cec5SDimitry Andric   // functions even if /entry: or /nodefaultlib are passed which causes them
7060b57cec5SDimitry Andric   // to not be called.
7070b57cec5SDimitry Andric   bool haveMain = findUnderscoreMangle("main");
7080b57cec5SDimitry Andric   bool haveWMain = findUnderscoreMangle("wmain");
7090b57cec5SDimitry Andric   bool haveWinMain = findUnderscoreMangle("WinMain");
7100b57cec5SDimitry Andric   bool haveWWinMain = findUnderscoreMangle("wWinMain");
7110b57cec5SDimitry Andric   if (haveMain || haveWMain) {
7120b57cec5SDimitry Andric     if (haveWinMain || haveWWinMain) {
7130b57cec5SDimitry Andric       warn(std::string("found ") + (haveMain ? "main" : "wmain") + " and " +
7140b57cec5SDimitry Andric            (haveWinMain ? "WinMain" : "wWinMain") +
7150b57cec5SDimitry Andric            "; defaulting to /subsystem:console");
7160b57cec5SDimitry Andric     }
7170b57cec5SDimitry Andric     return IMAGE_SUBSYSTEM_WINDOWS_CUI;
7180b57cec5SDimitry Andric   }
7190b57cec5SDimitry Andric   if (haveWinMain || haveWWinMain)
7200b57cec5SDimitry Andric     return IMAGE_SUBSYSTEM_WINDOWS_GUI;
7210b57cec5SDimitry Andric   return IMAGE_SUBSYSTEM_UNKNOWN;
7220b57cec5SDimitry Andric }
7230b57cec5SDimitry Andric 
7240b57cec5SDimitry Andric static uint64_t getDefaultImageBase() {
7250b57cec5SDimitry Andric   if (config->is64())
7260b57cec5SDimitry Andric     return config->dll ? 0x180000000 : 0x140000000;
7270b57cec5SDimitry Andric   return config->dll ? 0x10000000 : 0x400000;
7280b57cec5SDimitry Andric }
7290b57cec5SDimitry Andric 
730fe6060f1SDimitry Andric static std::string rewritePath(StringRef s) {
731fe6060f1SDimitry Andric   if (fs::exists(s))
732fe6060f1SDimitry Andric     return relativeToRoot(s);
733fe6060f1SDimitry Andric   return std::string(s);
734fe6060f1SDimitry Andric }
735fe6060f1SDimitry Andric 
736fe6060f1SDimitry Andric // Reconstructs command line arguments so that so that you can re-run
737fe6060f1SDimitry Andric // the same command with the same inputs. This is for --reproduce.
7380b57cec5SDimitry Andric static std::string createResponseFile(const opt::InputArgList &args,
7390b57cec5SDimitry Andric                                       ArrayRef<StringRef> filePaths,
7400b57cec5SDimitry Andric                                       ArrayRef<StringRef> searchPaths) {
7410b57cec5SDimitry Andric   SmallString<0> data;
7420b57cec5SDimitry Andric   raw_svector_ostream os(data);
7430b57cec5SDimitry Andric 
7440b57cec5SDimitry Andric   for (auto *arg : args) {
7450b57cec5SDimitry Andric     switch (arg->getOption().getID()) {
7460b57cec5SDimitry Andric     case OPT_linkrepro:
74785868e8aSDimitry Andric     case OPT_reproduce:
7480b57cec5SDimitry Andric     case OPT_INPUT:
7490b57cec5SDimitry Andric     case OPT_defaultlib:
7500b57cec5SDimitry Andric     case OPT_libpath:
75181ad6265SDimitry Andric     case OPT_winsysroot:
7520b57cec5SDimitry Andric       break;
753fe6060f1SDimitry Andric     case OPT_call_graph_ordering_file:
754fe6060f1SDimitry Andric     case OPT_deffile:
755349cc55cSDimitry Andric     case OPT_manifestinput:
756fe6060f1SDimitry Andric     case OPT_natvis:
757fe6060f1SDimitry Andric       os << arg->getSpelling() << quote(rewritePath(arg->getValue())) << '\n';
758fe6060f1SDimitry Andric       break;
759fe6060f1SDimitry Andric     case OPT_order: {
760fe6060f1SDimitry Andric       StringRef orderFile = arg->getValue();
761fe6060f1SDimitry Andric       orderFile.consume_front("@");
762fe6060f1SDimitry Andric       os << arg->getSpelling() << '@' << quote(rewritePath(orderFile)) << '\n';
763fe6060f1SDimitry Andric       break;
764fe6060f1SDimitry Andric     }
765fe6060f1SDimitry Andric     case OPT_pdbstream: {
766fe6060f1SDimitry Andric       const std::pair<StringRef, StringRef> nameFile =
767fe6060f1SDimitry Andric           StringRef(arg->getValue()).split("=");
768fe6060f1SDimitry Andric       os << arg->getSpelling() << nameFile.first << '='
769fe6060f1SDimitry Andric          << quote(rewritePath(nameFile.second)) << '\n';
770fe6060f1SDimitry Andric       break;
771fe6060f1SDimitry Andric     }
7720b57cec5SDimitry Andric     case OPT_implib:
773349cc55cSDimitry Andric     case OPT_manifestfile:
7740b57cec5SDimitry Andric     case OPT_pdb:
7755ffd83dbSDimitry Andric     case OPT_pdbstripped:
7760b57cec5SDimitry Andric     case OPT_out:
7770b57cec5SDimitry Andric       os << arg->getSpelling() << sys::path::filename(arg->getValue()) << "\n";
7780b57cec5SDimitry Andric       break;
7790b57cec5SDimitry Andric     default:
7800b57cec5SDimitry Andric       os << toString(*arg) << "\n";
7810b57cec5SDimitry Andric     }
7820b57cec5SDimitry Andric   }
7830b57cec5SDimitry Andric 
7840b57cec5SDimitry Andric   for (StringRef path : searchPaths) {
7850b57cec5SDimitry Andric     std::string relPath = relativeToRoot(path);
7860b57cec5SDimitry Andric     os << "/libpath:" << quote(relPath) << "\n";
7870b57cec5SDimitry Andric   }
7880b57cec5SDimitry Andric 
7890b57cec5SDimitry Andric   for (StringRef path : filePaths)
7900b57cec5SDimitry Andric     os << quote(relativeToRoot(path)) << "\n";
7910b57cec5SDimitry Andric 
7925ffd83dbSDimitry Andric   return std::string(data.str());
7930b57cec5SDimitry Andric }
7940b57cec5SDimitry Andric 
795fe6060f1SDimitry Andric enum class DebugKind {
796fe6060f1SDimitry Andric   Unknown,
797fe6060f1SDimitry Andric   None,
798fe6060f1SDimitry Andric   Full,
799fe6060f1SDimitry Andric   FastLink,
800fe6060f1SDimitry Andric   GHash,
801fe6060f1SDimitry Andric   NoGHash,
802fe6060f1SDimitry Andric   Dwarf,
803fe6060f1SDimitry Andric   Symtab
804fe6060f1SDimitry Andric };
8050b57cec5SDimitry Andric 
8060b57cec5SDimitry Andric static DebugKind parseDebugKind(const opt::InputArgList &args) {
8070b57cec5SDimitry Andric   auto *a = args.getLastArg(OPT_debug, OPT_debug_opt);
8080b57cec5SDimitry Andric   if (!a)
8090b57cec5SDimitry Andric     return DebugKind::None;
8100b57cec5SDimitry Andric   if (a->getNumValues() == 0)
8110b57cec5SDimitry Andric     return DebugKind::Full;
8120b57cec5SDimitry Andric 
8130b57cec5SDimitry Andric   DebugKind debug = StringSwitch<DebugKind>(a->getValue())
8140b57cec5SDimitry Andric                         .CaseLower("none", DebugKind::None)
8150b57cec5SDimitry Andric                         .CaseLower("full", DebugKind::Full)
8160b57cec5SDimitry Andric                         .CaseLower("fastlink", DebugKind::FastLink)
8170b57cec5SDimitry Andric                         // LLD extensions
8180b57cec5SDimitry Andric                         .CaseLower("ghash", DebugKind::GHash)
819fe6060f1SDimitry Andric                         .CaseLower("noghash", DebugKind::NoGHash)
8200b57cec5SDimitry Andric                         .CaseLower("dwarf", DebugKind::Dwarf)
8210b57cec5SDimitry Andric                         .CaseLower("symtab", DebugKind::Symtab)
8220b57cec5SDimitry Andric                         .Default(DebugKind::Unknown);
8230b57cec5SDimitry Andric 
8240b57cec5SDimitry Andric   if (debug == DebugKind::FastLink) {
8250b57cec5SDimitry Andric     warn("/debug:fastlink unsupported; using /debug:full");
8260b57cec5SDimitry Andric     return DebugKind::Full;
8270b57cec5SDimitry Andric   }
8280b57cec5SDimitry Andric   if (debug == DebugKind::Unknown) {
8290b57cec5SDimitry Andric     error("/debug: unknown option: " + Twine(a->getValue()));
8300b57cec5SDimitry Andric     return DebugKind::None;
8310b57cec5SDimitry Andric   }
8320b57cec5SDimitry Andric   return debug;
8330b57cec5SDimitry Andric }
8340b57cec5SDimitry Andric 
8350b57cec5SDimitry Andric static unsigned parseDebugTypes(const opt::InputArgList &args) {
8360b57cec5SDimitry Andric   unsigned debugTypes = static_cast<unsigned>(DebugType::None);
8370b57cec5SDimitry Andric 
8380b57cec5SDimitry Andric   if (auto *a = args.getLastArg(OPT_debugtype)) {
8390b57cec5SDimitry Andric     SmallVector<StringRef, 3> types;
8400b57cec5SDimitry Andric     StringRef(a->getValue())
8410b57cec5SDimitry Andric         .split(types, ',', /*MaxSplit=*/-1, /*KeepEmpty=*/false);
8420b57cec5SDimitry Andric 
8430b57cec5SDimitry Andric     for (StringRef type : types) {
8440b57cec5SDimitry Andric       unsigned v = StringSwitch<unsigned>(type.lower())
8450b57cec5SDimitry Andric                        .Case("cv", static_cast<unsigned>(DebugType::CV))
8460b57cec5SDimitry Andric                        .Case("pdata", static_cast<unsigned>(DebugType::PData))
8470b57cec5SDimitry Andric                        .Case("fixup", static_cast<unsigned>(DebugType::Fixup))
8480b57cec5SDimitry Andric                        .Default(0);
8490b57cec5SDimitry Andric       if (v == 0) {
8500b57cec5SDimitry Andric         warn("/debugtype: unknown option '" + type + "'");
8510b57cec5SDimitry Andric         continue;
8520b57cec5SDimitry Andric       }
8530b57cec5SDimitry Andric       debugTypes |= v;
8540b57cec5SDimitry Andric     }
8550b57cec5SDimitry Andric     return debugTypes;
8560b57cec5SDimitry Andric   }
8570b57cec5SDimitry Andric 
8580b57cec5SDimitry Andric   // Default debug types
8590b57cec5SDimitry Andric   debugTypes = static_cast<unsigned>(DebugType::CV);
8600b57cec5SDimitry Andric   if (args.hasArg(OPT_driver))
8610b57cec5SDimitry Andric     debugTypes |= static_cast<unsigned>(DebugType::PData);
8620b57cec5SDimitry Andric   if (args.hasArg(OPT_profile))
8630b57cec5SDimitry Andric     debugTypes |= static_cast<unsigned>(DebugType::Fixup);
8640b57cec5SDimitry Andric 
8650b57cec5SDimitry Andric   return debugTypes;
8660b57cec5SDimitry Andric }
8670b57cec5SDimitry Andric 
8685ffd83dbSDimitry Andric static std::string getMapFile(const opt::InputArgList &args,
8695ffd83dbSDimitry Andric                               opt::OptSpecifier os, opt::OptSpecifier osFile) {
8705ffd83dbSDimitry Andric   auto *arg = args.getLastArg(os, osFile);
8710b57cec5SDimitry Andric   if (!arg)
8720b57cec5SDimitry Andric     return "";
8735ffd83dbSDimitry Andric   if (arg->getOption().getID() == osFile.getID())
8740b57cec5SDimitry Andric     return arg->getValue();
8750b57cec5SDimitry Andric 
8765ffd83dbSDimitry Andric   assert(arg->getOption().getID() == os.getID());
8770b57cec5SDimitry Andric   StringRef outFile = config->outputFile;
8780b57cec5SDimitry Andric   return (outFile.substr(0, outFile.rfind('.')) + ".map").str();
8790b57cec5SDimitry Andric }
8800b57cec5SDimitry Andric 
8810b57cec5SDimitry Andric static std::string getImplibPath() {
8820b57cec5SDimitry Andric   if (!config->implib.empty())
8835ffd83dbSDimitry Andric     return std::string(config->implib);
8840b57cec5SDimitry Andric   SmallString<128> out = StringRef(config->outputFile);
8850b57cec5SDimitry Andric   sys::path::replace_extension(out, ".lib");
8865ffd83dbSDimitry Andric   return std::string(out.str());
8870b57cec5SDimitry Andric }
8880b57cec5SDimitry Andric 
88985868e8aSDimitry Andric // The import name is calculated as follows:
8900b57cec5SDimitry Andric //
8910b57cec5SDimitry Andric //        | LIBRARY w/ ext |   LIBRARY w/o ext   | no LIBRARY
8920b57cec5SDimitry Andric //   -----+----------------+---------------------+------------------
8930b57cec5SDimitry Andric //   LINK | {value}        | {value}.{.dll/.exe} | {output name}
8940b57cec5SDimitry Andric //    LIB | {value}        | {value}.dll         | {output name}.dll
8950b57cec5SDimitry Andric //
8960b57cec5SDimitry Andric static std::string getImportName(bool asLib) {
8970b57cec5SDimitry Andric   SmallString<128> out;
8980b57cec5SDimitry Andric 
8990b57cec5SDimitry Andric   if (config->importName.empty()) {
9000b57cec5SDimitry Andric     out.assign(sys::path::filename(config->outputFile));
9010b57cec5SDimitry Andric     if (asLib)
9020b57cec5SDimitry Andric       sys::path::replace_extension(out, ".dll");
9030b57cec5SDimitry Andric   } else {
9040b57cec5SDimitry Andric     out.assign(config->importName);
9050b57cec5SDimitry Andric     if (!sys::path::has_extension(out))
9060b57cec5SDimitry Andric       sys::path::replace_extension(out,
9070b57cec5SDimitry Andric                                    (config->dll || asLib) ? ".dll" : ".exe");
9080b57cec5SDimitry Andric   }
9090b57cec5SDimitry Andric 
9105ffd83dbSDimitry Andric   return std::string(out.str());
9110b57cec5SDimitry Andric }
9120b57cec5SDimitry Andric 
9130b57cec5SDimitry Andric static void createImportLibrary(bool asLib) {
9140b57cec5SDimitry Andric   std::vector<COFFShortExport> exports;
9150b57cec5SDimitry Andric   for (Export &e1 : config->exports) {
9160b57cec5SDimitry Andric     COFFShortExport e2;
9175ffd83dbSDimitry Andric     e2.Name = std::string(e1.name);
9185ffd83dbSDimitry Andric     e2.SymbolName = std::string(e1.symbolName);
9195ffd83dbSDimitry Andric     e2.ExtName = std::string(e1.extName);
92004eeddc0SDimitry Andric     e2.AliasTarget = std::string(e1.aliasTarget);
9210b57cec5SDimitry Andric     e2.Ordinal = e1.ordinal;
9220b57cec5SDimitry Andric     e2.Noname = e1.noname;
9230b57cec5SDimitry Andric     e2.Data = e1.data;
9240b57cec5SDimitry Andric     e2.Private = e1.isPrivate;
9250b57cec5SDimitry Andric     e2.Constant = e1.constant;
9260b57cec5SDimitry Andric     exports.push_back(e2);
9270b57cec5SDimitry Andric   }
9280b57cec5SDimitry Andric 
9290b57cec5SDimitry Andric   std::string libName = getImportName(asLib);
9300b57cec5SDimitry Andric   std::string path = getImplibPath();
9310b57cec5SDimitry Andric 
9320b57cec5SDimitry Andric   if (!config->incremental) {
933349cc55cSDimitry Andric     checkError(writeImportLibrary(libName, path, exports, config->machine,
9340b57cec5SDimitry Andric                                   config->mingw));
9350b57cec5SDimitry Andric     return;
9360b57cec5SDimitry Andric   }
9370b57cec5SDimitry Andric 
9380b57cec5SDimitry Andric   // If the import library already exists, replace it only if the contents
9390b57cec5SDimitry Andric   // have changed.
9400b57cec5SDimitry Andric   ErrorOr<std::unique_ptr<MemoryBuffer>> oldBuf = MemoryBuffer::getFile(
941fe6060f1SDimitry Andric       path, /*IsText=*/false, /*RequiresNullTerminator=*/false);
9420b57cec5SDimitry Andric   if (!oldBuf) {
943349cc55cSDimitry Andric     checkError(writeImportLibrary(libName, path, exports, config->machine,
9440b57cec5SDimitry Andric                                   config->mingw));
9450b57cec5SDimitry Andric     return;
9460b57cec5SDimitry Andric   }
9470b57cec5SDimitry Andric 
9480b57cec5SDimitry Andric   SmallString<128> tmpName;
9490b57cec5SDimitry Andric   if (std::error_code ec =
9500b57cec5SDimitry Andric           sys::fs::createUniqueFile(path + ".tmp-%%%%%%%%.lib", tmpName))
9510b57cec5SDimitry Andric     fatal("cannot create temporary file for import library " + path + ": " +
9520b57cec5SDimitry Andric           ec.message());
9530b57cec5SDimitry Andric 
9540b57cec5SDimitry Andric   if (Error e = writeImportLibrary(libName, tmpName, exports, config->machine,
9550b57cec5SDimitry Andric                                    config->mingw)) {
956349cc55cSDimitry Andric     checkError(std::move(e));
9570b57cec5SDimitry Andric     return;
9580b57cec5SDimitry Andric   }
9590b57cec5SDimitry Andric 
9600b57cec5SDimitry Andric   std::unique_ptr<MemoryBuffer> newBuf = check(MemoryBuffer::getFile(
961fe6060f1SDimitry Andric       tmpName, /*IsText=*/false, /*RequiresNullTerminator=*/false));
9620b57cec5SDimitry Andric   if ((*oldBuf)->getBuffer() != newBuf->getBuffer()) {
9630b57cec5SDimitry Andric     oldBuf->reset();
964349cc55cSDimitry Andric     checkError(errorCodeToError(sys::fs::rename(tmpName, path)));
9650b57cec5SDimitry Andric   } else {
9660b57cec5SDimitry Andric     sys::fs::remove(tmpName);
9670b57cec5SDimitry Andric   }
9680b57cec5SDimitry Andric }
9690b57cec5SDimitry Andric 
9700b57cec5SDimitry Andric static void parseModuleDefs(StringRef path) {
971fe6060f1SDimitry Andric   std::unique_ptr<MemoryBuffer> mb =
972fe6060f1SDimitry Andric       CHECK(MemoryBuffer::getFile(path, /*IsText=*/false,
973fe6060f1SDimitry Andric                                   /*RequiresNullTerminator=*/false,
974fe6060f1SDimitry Andric                                   /*IsVolatile=*/true),
975fe6060f1SDimitry Andric             "could not open " + path);
9760b57cec5SDimitry Andric   COFFModuleDefinition m = check(parseCOFFModuleDefinition(
9770b57cec5SDimitry Andric       mb->getMemBufferRef(), config->machine, config->mingw));
9780b57cec5SDimitry Andric 
979fe6060f1SDimitry Andric   // Include in /reproduce: output if applicable.
980fe6060f1SDimitry Andric   driver->takeBuffer(std::move(mb));
981fe6060f1SDimitry Andric 
9820b57cec5SDimitry Andric   if (config->outputFile.empty())
98304eeddc0SDimitry Andric     config->outputFile = std::string(saver().save(m.OutputFile));
98404eeddc0SDimitry Andric   config->importName = std::string(saver().save(m.ImportName));
9850b57cec5SDimitry Andric   if (m.ImageBase)
9860b57cec5SDimitry Andric     config->imageBase = m.ImageBase;
9870b57cec5SDimitry Andric   if (m.StackReserve)
9880b57cec5SDimitry Andric     config->stackReserve = m.StackReserve;
9890b57cec5SDimitry Andric   if (m.StackCommit)
9900b57cec5SDimitry Andric     config->stackCommit = m.StackCommit;
9910b57cec5SDimitry Andric   if (m.HeapReserve)
9920b57cec5SDimitry Andric     config->heapReserve = m.HeapReserve;
9930b57cec5SDimitry Andric   if (m.HeapCommit)
9940b57cec5SDimitry Andric     config->heapCommit = m.HeapCommit;
9950b57cec5SDimitry Andric   if (m.MajorImageVersion)
9960b57cec5SDimitry Andric     config->majorImageVersion = m.MajorImageVersion;
9970b57cec5SDimitry Andric   if (m.MinorImageVersion)
9980b57cec5SDimitry Andric     config->minorImageVersion = m.MinorImageVersion;
9990b57cec5SDimitry Andric   if (m.MajorOSVersion)
10000b57cec5SDimitry Andric     config->majorOSVersion = m.MajorOSVersion;
10010b57cec5SDimitry Andric   if (m.MinorOSVersion)
10020b57cec5SDimitry Andric     config->minorOSVersion = m.MinorOSVersion;
10030b57cec5SDimitry Andric 
10040b57cec5SDimitry Andric   for (COFFShortExport e1 : m.Exports) {
10050b57cec5SDimitry Andric     Export e2;
10060b57cec5SDimitry Andric     // In simple cases, only Name is set. Renamed exports are parsed
10070b57cec5SDimitry Andric     // and set as "ExtName = Name". If Name has the form "OtherDll.Func",
10080b57cec5SDimitry Andric     // it shouldn't be a normal exported function but a forward to another
10090b57cec5SDimitry Andric     // DLL instead. This is supported by both MS and GNU linkers.
10105ffd83dbSDimitry Andric     if (!e1.ExtName.empty() && e1.ExtName != e1.Name &&
10115ffd83dbSDimitry Andric         StringRef(e1.Name).contains('.')) {
101204eeddc0SDimitry Andric       e2.name = saver().save(e1.ExtName);
101304eeddc0SDimitry Andric       e2.forwardTo = saver().save(e1.Name);
10140b57cec5SDimitry Andric       config->exports.push_back(e2);
10150b57cec5SDimitry Andric       continue;
10160b57cec5SDimitry Andric     }
101704eeddc0SDimitry Andric     e2.name = saver().save(e1.Name);
101804eeddc0SDimitry Andric     e2.extName = saver().save(e1.ExtName);
101904eeddc0SDimitry Andric     e2.aliasTarget = saver().save(e1.AliasTarget);
10200b57cec5SDimitry Andric     e2.ordinal = e1.Ordinal;
10210b57cec5SDimitry Andric     e2.noname = e1.Noname;
10220b57cec5SDimitry Andric     e2.data = e1.Data;
10230b57cec5SDimitry Andric     e2.isPrivate = e1.Private;
10240b57cec5SDimitry Andric     e2.constant = e1.Constant;
10250b57cec5SDimitry Andric     config->exports.push_back(e2);
10260b57cec5SDimitry Andric   }
10270b57cec5SDimitry Andric }
10280b57cec5SDimitry Andric 
10290b57cec5SDimitry Andric void LinkerDriver::enqueueTask(std::function<void()> task) {
10300b57cec5SDimitry Andric   taskQueue.push_back(std::move(task));
10310b57cec5SDimitry Andric }
10320b57cec5SDimitry Andric 
10330b57cec5SDimitry Andric bool LinkerDriver::run() {
1034349cc55cSDimitry Andric   ScopedTimer t(ctx.inputFileTimer);
10350b57cec5SDimitry Andric 
10360b57cec5SDimitry Andric   bool didWork = !taskQueue.empty();
10370b57cec5SDimitry Andric   while (!taskQueue.empty()) {
10380b57cec5SDimitry Andric     taskQueue.front()();
10390b57cec5SDimitry Andric     taskQueue.pop_front();
10400b57cec5SDimitry Andric   }
10410b57cec5SDimitry Andric   return didWork;
10420b57cec5SDimitry Andric }
10430b57cec5SDimitry Andric 
10440b57cec5SDimitry Andric // Parse an /order file. If an option is given, the linker places
10450b57cec5SDimitry Andric // COMDAT sections in the same order as their names appear in the
10460b57cec5SDimitry Andric // given file.
1047349cc55cSDimitry Andric static void parseOrderFile(COFFLinkerContext &ctx, StringRef arg) {
10480b57cec5SDimitry Andric   // For some reason, the MSVC linker requires a filename to be
10490b57cec5SDimitry Andric   // preceded by "@".
10500b57cec5SDimitry Andric   if (!arg.startswith("@")) {
10510b57cec5SDimitry Andric     error("malformed /order option: '@' missing");
10520b57cec5SDimitry Andric     return;
10530b57cec5SDimitry Andric   }
10540b57cec5SDimitry Andric 
10550b57cec5SDimitry Andric   // Get a list of all comdat sections for error checking.
10560b57cec5SDimitry Andric   DenseSet<StringRef> set;
1057349cc55cSDimitry Andric   for (Chunk *c : ctx.symtab.getChunks())
10580b57cec5SDimitry Andric     if (auto *sec = dyn_cast<SectionChunk>(c))
10590b57cec5SDimitry Andric       if (sec->sym)
10600b57cec5SDimitry Andric         set.insert(sec->sym->getName());
10610b57cec5SDimitry Andric 
10620b57cec5SDimitry Andric   // Open a file.
10630b57cec5SDimitry Andric   StringRef path = arg.substr(1);
1064fe6060f1SDimitry Andric   std::unique_ptr<MemoryBuffer> mb =
1065fe6060f1SDimitry Andric       CHECK(MemoryBuffer::getFile(path, /*IsText=*/false,
1066fe6060f1SDimitry Andric                                   /*RequiresNullTerminator=*/false,
1067fe6060f1SDimitry Andric                                   /*IsVolatile=*/true),
1068fe6060f1SDimitry Andric             "could not open " + path);
10690b57cec5SDimitry Andric 
10700b57cec5SDimitry Andric   // Parse a file. An order file contains one symbol per line.
10710b57cec5SDimitry Andric   // All symbols that were not present in a given order file are
10720b57cec5SDimitry Andric   // considered to have the lowest priority 0 and are placed at
10730b57cec5SDimitry Andric   // end of an output section.
10745ffd83dbSDimitry Andric   for (StringRef arg : args::getLines(mb->getMemBufferRef())) {
10755ffd83dbSDimitry Andric     std::string s(arg);
10760b57cec5SDimitry Andric     if (config->machine == I386 && !isDecorated(s))
10770b57cec5SDimitry Andric       s = "_" + s;
10780b57cec5SDimitry Andric 
10790b57cec5SDimitry Andric     if (set.count(s) == 0) {
10800b57cec5SDimitry Andric       if (config->warnMissingOrderSymbol)
10810b57cec5SDimitry Andric         warn("/order:" + arg + ": missing symbol: " + s + " [LNK4037]");
10820b57cec5SDimitry Andric     }
10830b57cec5SDimitry Andric     else
10840b57cec5SDimitry Andric       config->order[s] = INT_MIN + config->order.size();
10850b57cec5SDimitry Andric   }
1086fe6060f1SDimitry Andric 
1087fe6060f1SDimitry Andric   // Include in /reproduce: output if applicable.
1088fe6060f1SDimitry Andric   driver->takeBuffer(std::move(mb));
10890b57cec5SDimitry Andric }
10900b57cec5SDimitry Andric 
1091349cc55cSDimitry Andric static void parseCallGraphFile(COFFLinkerContext &ctx, StringRef path) {
1092fe6060f1SDimitry Andric   std::unique_ptr<MemoryBuffer> mb =
1093fe6060f1SDimitry Andric       CHECK(MemoryBuffer::getFile(path, /*IsText=*/false,
1094fe6060f1SDimitry Andric                                   /*RequiresNullTerminator=*/false,
1095fe6060f1SDimitry Andric                                   /*IsVolatile=*/true),
1096fe6060f1SDimitry Andric             "could not open " + path);
1097e8d8bef9SDimitry Andric 
1098e8d8bef9SDimitry Andric   // Build a map from symbol name to section.
1099e8d8bef9SDimitry Andric   DenseMap<StringRef, Symbol *> map;
1100349cc55cSDimitry Andric   for (ObjFile *file : ctx.objFileInstances)
1101e8d8bef9SDimitry Andric     for (Symbol *sym : file->getSymbols())
1102e8d8bef9SDimitry Andric       if (sym)
1103e8d8bef9SDimitry Andric         map[sym->getName()] = sym;
1104e8d8bef9SDimitry Andric 
1105e8d8bef9SDimitry Andric   auto findSection = [&](StringRef name) -> SectionChunk * {
1106e8d8bef9SDimitry Andric     Symbol *sym = map.lookup(name);
1107e8d8bef9SDimitry Andric     if (!sym) {
1108e8d8bef9SDimitry Andric       if (config->warnMissingOrderSymbol)
1109e8d8bef9SDimitry Andric         warn(path + ": no such symbol: " + name);
1110e8d8bef9SDimitry Andric       return nullptr;
1111e8d8bef9SDimitry Andric     }
1112e8d8bef9SDimitry Andric 
1113e8d8bef9SDimitry Andric     if (DefinedCOFF *dr = dyn_cast_or_null<DefinedCOFF>(sym))
1114e8d8bef9SDimitry Andric       return dyn_cast_or_null<SectionChunk>(dr->getChunk());
1115e8d8bef9SDimitry Andric     return nullptr;
1116e8d8bef9SDimitry Andric   };
1117e8d8bef9SDimitry Andric 
1118e8d8bef9SDimitry Andric   for (StringRef line : args::getLines(*mb)) {
1119e8d8bef9SDimitry Andric     SmallVector<StringRef, 3> fields;
1120e8d8bef9SDimitry Andric     line.split(fields, ' ');
1121e8d8bef9SDimitry Andric     uint64_t count;
1122e8d8bef9SDimitry Andric 
1123e8d8bef9SDimitry Andric     if (fields.size() != 3 || !to_integer(fields[2], count)) {
1124e8d8bef9SDimitry Andric       error(path + ": parse error");
1125e8d8bef9SDimitry Andric       return;
1126e8d8bef9SDimitry Andric     }
1127e8d8bef9SDimitry Andric 
1128e8d8bef9SDimitry Andric     if (SectionChunk *from = findSection(fields[0]))
1129e8d8bef9SDimitry Andric       if (SectionChunk *to = findSection(fields[1]))
1130e8d8bef9SDimitry Andric         config->callGraphProfile[{from, to}] += count;
1131e8d8bef9SDimitry Andric   }
1132fe6060f1SDimitry Andric 
1133fe6060f1SDimitry Andric   // Include in /reproduce: output if applicable.
1134fe6060f1SDimitry Andric   driver->takeBuffer(std::move(mb));
1135e8d8bef9SDimitry Andric }
1136e8d8bef9SDimitry Andric 
1137349cc55cSDimitry Andric static void readCallGraphsFromObjectFiles(COFFLinkerContext &ctx) {
1138349cc55cSDimitry Andric   for (ObjFile *obj : ctx.objFileInstances) {
1139e8d8bef9SDimitry Andric     if (obj->callgraphSec) {
1140e8d8bef9SDimitry Andric       ArrayRef<uint8_t> contents;
1141e8d8bef9SDimitry Andric       cantFail(
1142e8d8bef9SDimitry Andric           obj->getCOFFObj()->getSectionContents(obj->callgraphSec, contents));
1143e8d8bef9SDimitry Andric       BinaryStreamReader reader(contents, support::little);
1144e8d8bef9SDimitry Andric       while (!reader.empty()) {
1145e8d8bef9SDimitry Andric         uint32_t fromIndex, toIndex;
1146e8d8bef9SDimitry Andric         uint64_t count;
1147e8d8bef9SDimitry Andric         if (Error err = reader.readInteger(fromIndex))
1148e8d8bef9SDimitry Andric           fatal(toString(obj) + ": Expected 32-bit integer");
1149e8d8bef9SDimitry Andric         if (Error err = reader.readInteger(toIndex))
1150e8d8bef9SDimitry Andric           fatal(toString(obj) + ": Expected 32-bit integer");
1151e8d8bef9SDimitry Andric         if (Error err = reader.readInteger(count))
1152e8d8bef9SDimitry Andric           fatal(toString(obj) + ": Expected 64-bit integer");
1153e8d8bef9SDimitry Andric         auto *fromSym = dyn_cast_or_null<Defined>(obj->getSymbol(fromIndex));
1154e8d8bef9SDimitry Andric         auto *toSym = dyn_cast_or_null<Defined>(obj->getSymbol(toIndex));
1155e8d8bef9SDimitry Andric         if (!fromSym || !toSym)
1156e8d8bef9SDimitry Andric           continue;
1157e8d8bef9SDimitry Andric         auto *from = dyn_cast_or_null<SectionChunk>(fromSym->getChunk());
1158e8d8bef9SDimitry Andric         auto *to = dyn_cast_or_null<SectionChunk>(toSym->getChunk());
1159e8d8bef9SDimitry Andric         if (from && to)
1160e8d8bef9SDimitry Andric           config->callGraphProfile[{from, to}] += count;
1161e8d8bef9SDimitry Andric       }
1162e8d8bef9SDimitry Andric     }
1163e8d8bef9SDimitry Andric   }
1164e8d8bef9SDimitry Andric }
1165e8d8bef9SDimitry Andric 
11660b57cec5SDimitry Andric static void markAddrsig(Symbol *s) {
11670b57cec5SDimitry Andric   if (auto *d = dyn_cast_or_null<Defined>(s))
11680b57cec5SDimitry Andric     if (SectionChunk *c = dyn_cast_or_null<SectionChunk>(d->getChunk()))
11690b57cec5SDimitry Andric       c->keepUnique = true;
11700b57cec5SDimitry Andric }
11710b57cec5SDimitry Andric 
1172349cc55cSDimitry Andric static void findKeepUniqueSections(COFFLinkerContext &ctx) {
11730b57cec5SDimitry Andric   // Exported symbols could be address-significant in other executables or DSOs,
11740b57cec5SDimitry Andric   // so we conservatively mark them as address-significant.
11750b57cec5SDimitry Andric   for (Export &r : config->exports)
11760b57cec5SDimitry Andric     markAddrsig(r.sym);
11770b57cec5SDimitry Andric 
11780b57cec5SDimitry Andric   // Visit the address-significance table in each object file and mark each
11790b57cec5SDimitry Andric   // referenced symbol as address-significant.
1180349cc55cSDimitry Andric   for (ObjFile *obj : ctx.objFileInstances) {
11810b57cec5SDimitry Andric     ArrayRef<Symbol *> syms = obj->getSymbols();
11820b57cec5SDimitry Andric     if (obj->addrsigSec) {
11830b57cec5SDimitry Andric       ArrayRef<uint8_t> contents;
11840b57cec5SDimitry Andric       cantFail(
11850b57cec5SDimitry Andric           obj->getCOFFObj()->getSectionContents(obj->addrsigSec, contents));
11860b57cec5SDimitry Andric       const uint8_t *cur = contents.begin();
11870b57cec5SDimitry Andric       while (cur != contents.end()) {
11880b57cec5SDimitry Andric         unsigned size;
11890b57cec5SDimitry Andric         const char *err;
11900b57cec5SDimitry Andric         uint64_t symIndex = decodeULEB128(cur, &size, contents.end(), &err);
11910b57cec5SDimitry Andric         if (err)
11920b57cec5SDimitry Andric           fatal(toString(obj) + ": could not decode addrsig section: " + err);
11930b57cec5SDimitry Andric         if (symIndex >= syms.size())
11940b57cec5SDimitry Andric           fatal(toString(obj) + ": invalid symbol index in addrsig section");
11950b57cec5SDimitry Andric         markAddrsig(syms[symIndex]);
11960b57cec5SDimitry Andric         cur += size;
11970b57cec5SDimitry Andric       }
11980b57cec5SDimitry Andric     } else {
11990b57cec5SDimitry Andric       // If an object file does not have an address-significance table,
12000b57cec5SDimitry Andric       // conservatively mark all of its symbols as address-significant.
12010b57cec5SDimitry Andric       for (Symbol *s : syms)
12020b57cec5SDimitry Andric         markAddrsig(s);
12030b57cec5SDimitry Andric     }
12040b57cec5SDimitry Andric   }
12050b57cec5SDimitry Andric }
12060b57cec5SDimitry Andric 
12070b57cec5SDimitry Andric // link.exe replaces each %foo% in altPath with the contents of environment
12080b57cec5SDimitry Andric // variable foo, and adds the two magic env vars _PDB (expands to the basename
12090b57cec5SDimitry Andric // of pdb's output path) and _EXT (expands to the extension of the output
12100b57cec5SDimitry Andric // binary).
12110b57cec5SDimitry Andric // lld only supports %_PDB% and %_EXT% and warns on references to all other env
12120b57cec5SDimitry Andric // vars.
12130b57cec5SDimitry Andric static void parsePDBAltPath(StringRef altPath) {
12140b57cec5SDimitry Andric   SmallString<128> buf;
12150b57cec5SDimitry Andric   StringRef pdbBasename =
12160b57cec5SDimitry Andric       sys::path::filename(config->pdbPath, sys::path::Style::windows);
12170b57cec5SDimitry Andric   StringRef binaryExtension =
12180b57cec5SDimitry Andric       sys::path::extension(config->outputFile, sys::path::Style::windows);
12190b57cec5SDimitry Andric   if (!binaryExtension.empty())
12200b57cec5SDimitry Andric     binaryExtension = binaryExtension.substr(1); // %_EXT% does not include '.'.
12210b57cec5SDimitry Andric 
12220b57cec5SDimitry Andric   // Invariant:
12230b57cec5SDimitry Andric   //   +--------- cursor ('a...' might be the empty string).
12240b57cec5SDimitry Andric   //   |   +----- firstMark
12250b57cec5SDimitry Andric   //   |   |   +- secondMark
12260b57cec5SDimitry Andric   //   v   v   v
12270b57cec5SDimitry Andric   //   a...%...%...
12280b57cec5SDimitry Andric   size_t cursor = 0;
12290b57cec5SDimitry Andric   while (cursor < altPath.size()) {
12300b57cec5SDimitry Andric     size_t firstMark, secondMark;
12310b57cec5SDimitry Andric     if ((firstMark = altPath.find('%', cursor)) == StringRef::npos ||
12320b57cec5SDimitry Andric         (secondMark = altPath.find('%', firstMark + 1)) == StringRef::npos) {
12330b57cec5SDimitry Andric       // Didn't find another full fragment, treat rest of string as literal.
12340b57cec5SDimitry Andric       buf.append(altPath.substr(cursor));
12350b57cec5SDimitry Andric       break;
12360b57cec5SDimitry Andric     }
12370b57cec5SDimitry Andric 
12380b57cec5SDimitry Andric     // Found a full fragment. Append text in front of first %, and interpret
12390b57cec5SDimitry Andric     // text between first and second % as variable name.
12400b57cec5SDimitry Andric     buf.append(altPath.substr(cursor, firstMark - cursor));
12410b57cec5SDimitry Andric     StringRef var = altPath.substr(firstMark, secondMark - firstMark + 1);
1242fe6060f1SDimitry Andric     if (var.equals_insensitive("%_pdb%"))
12430b57cec5SDimitry Andric       buf.append(pdbBasename);
1244fe6060f1SDimitry Andric     else if (var.equals_insensitive("%_ext%"))
12450b57cec5SDimitry Andric       buf.append(binaryExtension);
12460b57cec5SDimitry Andric     else {
12470b57cec5SDimitry Andric       warn("only %_PDB% and %_EXT% supported in /pdbaltpath:, keeping " +
12480b57cec5SDimitry Andric            var + " as literal");
12490b57cec5SDimitry Andric       buf.append(var);
12500b57cec5SDimitry Andric     }
12510b57cec5SDimitry Andric 
12520b57cec5SDimitry Andric     cursor = secondMark + 1;
12530b57cec5SDimitry Andric   }
12540b57cec5SDimitry Andric 
12550b57cec5SDimitry Andric   config->pdbAltPath = buf;
12560b57cec5SDimitry Andric }
12570b57cec5SDimitry Andric 
125885868e8aSDimitry Andric /// Convert resource files and potentially merge input resource object
125985868e8aSDimitry Andric /// trees into one resource tree.
12600b57cec5SDimitry Andric /// Call after ObjFile::Instances is complete.
126185868e8aSDimitry Andric void LinkerDriver::convertResources() {
126285868e8aSDimitry Andric   std::vector<ObjFile *> resourceObjFiles;
126385868e8aSDimitry Andric 
1264349cc55cSDimitry Andric   for (ObjFile *f : ctx.objFileInstances) {
126585868e8aSDimitry Andric     if (f->isResourceObjFile())
126685868e8aSDimitry Andric       resourceObjFiles.push_back(f);
12670b57cec5SDimitry Andric   }
12680b57cec5SDimitry Andric 
126985868e8aSDimitry Andric   if (!config->mingw &&
127085868e8aSDimitry Andric       (resourceObjFiles.size() > 1 ||
127185868e8aSDimitry Andric        (resourceObjFiles.size() == 1 && !resources.empty()))) {
127285868e8aSDimitry Andric     error((!resources.empty() ? "internal .obj file created from .res files"
127385868e8aSDimitry Andric                               : toString(resourceObjFiles[1])) +
12740b57cec5SDimitry Andric           ": more than one resource obj file not allowed, already got " +
127585868e8aSDimitry Andric           toString(resourceObjFiles.front()));
127685868e8aSDimitry Andric     return;
12770b57cec5SDimitry Andric   }
127885868e8aSDimitry Andric 
127985868e8aSDimitry Andric   if (resources.empty() && resourceObjFiles.size() <= 1) {
128085868e8aSDimitry Andric     // No resources to convert, and max one resource object file in
128185868e8aSDimitry Andric     // the input. Keep that preconverted resource section as is.
128285868e8aSDimitry Andric     for (ObjFile *f : resourceObjFiles)
128385868e8aSDimitry Andric       f->includeResourceChunks();
128485868e8aSDimitry Andric     return;
128585868e8aSDimitry Andric   }
1286349cc55cSDimitry Andric   ObjFile *f =
1287349cc55cSDimitry Andric       make<ObjFile>(ctx, convertResToCOFF(resources, resourceObjFiles));
1288349cc55cSDimitry Andric   ctx.symtab.addFile(f);
128985868e8aSDimitry Andric   f->includeResourceChunks();
12900b57cec5SDimitry Andric }
12910b57cec5SDimitry Andric 
12920b57cec5SDimitry Andric // In MinGW, if no symbols are chosen to be exported, then all symbols are
12930b57cec5SDimitry Andric // automatically exported by default. This behavior can be forced by the
12940b57cec5SDimitry Andric // -export-all-symbols option, so that it happens even when exports are
12950b57cec5SDimitry Andric // explicitly specified. The automatic behavior can be disabled using the
12960b57cec5SDimitry Andric // -exclude-all-symbols option, so that lld-link behaves like link.exe rather
12970b57cec5SDimitry Andric // than MinGW in the case that nothing is explicitly exported.
12980b57cec5SDimitry Andric void LinkerDriver::maybeExportMinGWSymbols(const opt::InputArgList &args) {
1299fe6060f1SDimitry Andric   if (!args.hasArg(OPT_export_all_symbols)) {
13000b57cec5SDimitry Andric     if (!config->dll)
13010b57cec5SDimitry Andric       return;
13020b57cec5SDimitry Andric 
13030b57cec5SDimitry Andric     if (!config->exports.empty())
13040b57cec5SDimitry Andric       return;
13050b57cec5SDimitry Andric     if (args.hasArg(OPT_exclude_all_symbols))
13060b57cec5SDimitry Andric       return;
13070b57cec5SDimitry Andric   }
13080b57cec5SDimitry Andric 
13090b57cec5SDimitry Andric   AutoExporter exporter;
13100b57cec5SDimitry Andric 
13110b57cec5SDimitry Andric   for (auto *arg : args.filtered(OPT_wholearchive_file))
13120b57cec5SDimitry Andric     if (Optional<StringRef> path = doFindFile(arg->getValue()))
13130b57cec5SDimitry Andric       exporter.addWholeArchive(*path);
13140b57cec5SDimitry Andric 
1315349cc55cSDimitry Andric   ctx.symtab.forEachSymbol([&](Symbol *s) {
13160b57cec5SDimitry Andric     auto *def = dyn_cast<Defined>(s);
1317349cc55cSDimitry Andric     if (!exporter.shouldExport(ctx, def))
13180b57cec5SDimitry Andric       return;
13190b57cec5SDimitry Andric 
1320fe6060f1SDimitry Andric     if (!def->isGCRoot) {
1321fe6060f1SDimitry Andric       def->isGCRoot = true;
1322fe6060f1SDimitry Andric       config->gcroot.push_back(def);
1323fe6060f1SDimitry Andric     }
1324fe6060f1SDimitry Andric 
13250b57cec5SDimitry Andric     Export e;
13260b57cec5SDimitry Andric     e.name = def->getName();
13270b57cec5SDimitry Andric     e.sym = def;
13280b57cec5SDimitry Andric     if (Chunk *c = def->getChunk())
13290b57cec5SDimitry Andric       if (!(c->getOutputCharacteristics() & IMAGE_SCN_MEM_EXECUTE))
13300b57cec5SDimitry Andric         e.data = true;
1331fe6060f1SDimitry Andric     s->isUsedInRegularObj = true;
13320b57cec5SDimitry Andric     config->exports.push_back(e);
13330b57cec5SDimitry Andric   });
13340b57cec5SDimitry Andric }
13350b57cec5SDimitry Andric 
133685868e8aSDimitry Andric // lld has a feature to create a tar file containing all input files as well as
133785868e8aSDimitry Andric // all command line options, so that other people can run lld again with exactly
133885868e8aSDimitry Andric // the same inputs. This feature is accessible via /linkrepro and /reproduce.
133985868e8aSDimitry Andric //
134085868e8aSDimitry Andric // /linkrepro and /reproduce are very similar, but /linkrepro takes a directory
134185868e8aSDimitry Andric // name while /reproduce takes a full path. We have /linkrepro for compatibility
134285868e8aSDimitry Andric // with Microsoft link.exe.
134385868e8aSDimitry Andric Optional<std::string> getReproduceFile(const opt::InputArgList &args) {
134485868e8aSDimitry Andric   if (auto *arg = args.getLastArg(OPT_reproduce))
134585868e8aSDimitry Andric     return std::string(arg->getValue());
134685868e8aSDimitry Andric 
134785868e8aSDimitry Andric   if (auto *arg = args.getLastArg(OPT_linkrepro)) {
134885868e8aSDimitry Andric     SmallString<64> path = StringRef(arg->getValue());
134985868e8aSDimitry Andric     sys::path::append(path, "repro.tar");
13505ffd83dbSDimitry Andric     return std::string(path);
135185868e8aSDimitry Andric   }
135285868e8aSDimitry Andric 
1353e8d8bef9SDimitry Andric   // This is intentionally not guarded by OPT_lldignoreenv since writing
1354e8d8bef9SDimitry Andric   // a repro tar file doesn't affect the main output.
1355e8d8bef9SDimitry Andric   if (auto *path = getenv("LLD_REPRODUCE"))
1356e8d8bef9SDimitry Andric     return std::string(path);
1357e8d8bef9SDimitry Andric 
135885868e8aSDimitry Andric   return None;
135985868e8aSDimitry Andric }
13600b57cec5SDimitry Andric 
1361*753f127fSDimitry Andric static std::unique_ptr<llvm::vfs::FileSystem>
1362*753f127fSDimitry Andric getVFS(const opt::InputArgList &args) {
1363*753f127fSDimitry Andric   using namespace llvm::vfs;
1364*753f127fSDimitry Andric 
1365*753f127fSDimitry Andric   const opt::Arg *arg = args.getLastArg(OPT_vfsoverlay);
1366*753f127fSDimitry Andric   if (!arg)
1367*753f127fSDimitry Andric     return nullptr;
1368*753f127fSDimitry Andric 
1369*753f127fSDimitry Andric   auto bufOrErr = llvm::MemoryBuffer::getFile(arg->getValue());
1370*753f127fSDimitry Andric   if (!bufOrErr) {
1371*753f127fSDimitry Andric     checkError(errorCodeToError(bufOrErr.getError()));
1372*753f127fSDimitry Andric     return nullptr;
1373*753f127fSDimitry Andric   }
1374*753f127fSDimitry Andric 
1375*753f127fSDimitry Andric   if (auto ret = vfs::getVFSFromYAML(std::move(*bufOrErr), /*DiagHandler*/ nullptr,
1376*753f127fSDimitry Andric                              arg->getValue()))
1377*753f127fSDimitry Andric     return ret;
1378*753f127fSDimitry Andric 
1379*753f127fSDimitry Andric   error("Invalid vfs overlay");
1380*753f127fSDimitry Andric   return nullptr;
1381*753f127fSDimitry Andric }
1382*753f127fSDimitry Andric 
1383e8d8bef9SDimitry Andric void LinkerDriver::linkerMain(ArrayRef<const char *> argsArr) {
1384349cc55cSDimitry Andric   ScopedTimer rootTimer(ctx.rootTimer);
13855ffd83dbSDimitry Andric 
13860b57cec5SDimitry Andric   // Needed for LTO.
13870b57cec5SDimitry Andric   InitializeAllTargetInfos();
13880b57cec5SDimitry Andric   InitializeAllTargets();
13890b57cec5SDimitry Andric   InitializeAllTargetMCs();
13900b57cec5SDimitry Andric   InitializeAllAsmParsers();
13910b57cec5SDimitry Andric   InitializeAllAsmPrinters();
13920b57cec5SDimitry Andric 
13930b57cec5SDimitry Andric   // If the first command line argument is "/lib", link.exe acts like lib.exe.
13940b57cec5SDimitry Andric   // We call our own implementation of lib.exe that understands bitcode files.
1395fe6060f1SDimitry Andric   if (argsArr.size() > 1 &&
1396fe6060f1SDimitry Andric       (StringRef(argsArr[1]).equals_insensitive("/lib") ||
1397fe6060f1SDimitry Andric        StringRef(argsArr[1]).equals_insensitive("-lib"))) {
13980b57cec5SDimitry Andric     if (llvm::libDriverMain(argsArr.slice(1)) != 0)
13990b57cec5SDimitry Andric       fatal("lib failed");
14000b57cec5SDimitry Andric     return;
14010b57cec5SDimitry Andric   }
14020b57cec5SDimitry Andric 
14030b57cec5SDimitry Andric   // Parse command line options.
14040b57cec5SDimitry Andric   ArgParser parser;
140585868e8aSDimitry Andric   opt::InputArgList args = parser.parse(argsArr);
14060b57cec5SDimitry Andric 
14070b57cec5SDimitry Andric   // Parse and evaluate -mllvm options.
14080b57cec5SDimitry Andric   std::vector<const char *> v;
14090b57cec5SDimitry Andric   v.push_back("lld-link (LLVM option parsing)");
14100b57cec5SDimitry Andric   for (auto *arg : args.filtered(OPT_mllvm))
14110b57cec5SDimitry Andric     v.push_back(arg->getValue());
1412e8d8bef9SDimitry Andric   cl::ResetAllOptionOccurrences();
14130b57cec5SDimitry Andric   cl::ParseCommandLineOptions(v.size(), v.data());
14140b57cec5SDimitry Andric 
14150b57cec5SDimitry Andric   // Handle /errorlimit early, because error() depends on it.
14160b57cec5SDimitry Andric   if (auto *arg = args.getLastArg(OPT_errorlimit)) {
14170b57cec5SDimitry Andric     int n = 20;
14180b57cec5SDimitry Andric     StringRef s = arg->getValue();
14190b57cec5SDimitry Andric     if (s.getAsInteger(10, n))
14200b57cec5SDimitry Andric       error(arg->getSpelling() + " number expected, but got " + s);
14210b57cec5SDimitry Andric     errorHandler().errorLimit = n;
14220b57cec5SDimitry Andric   }
14230b57cec5SDimitry Andric 
1424*753f127fSDimitry Andric   config->vfs = getVFS(args);
1425*753f127fSDimitry Andric 
14260b57cec5SDimitry Andric   // Handle /help
14270b57cec5SDimitry Andric   if (args.hasArg(OPT_help)) {
14280b57cec5SDimitry Andric     printHelp(argsArr[0]);
14290b57cec5SDimitry Andric     return;
14300b57cec5SDimitry Andric   }
14310b57cec5SDimitry Andric 
14325ffd83dbSDimitry Andric   // /threads: takes a positive integer and provides the default value for
14335ffd83dbSDimitry Andric   // /opt:lldltojobs=.
14345ffd83dbSDimitry Andric   if (auto *arg = args.getLastArg(OPT_threads)) {
14355ffd83dbSDimitry Andric     StringRef v(arg->getValue());
14365ffd83dbSDimitry Andric     unsigned threads = 0;
14375ffd83dbSDimitry Andric     if (!llvm::to_integer(v, threads, 0) || threads == 0)
14385ffd83dbSDimitry Andric       error(arg->getSpelling() + ": expected a positive integer, but got '" +
14395ffd83dbSDimitry Andric             arg->getValue() + "'");
14405ffd83dbSDimitry Andric     parallel::strategy = hardware_concurrency(threads);
14415ffd83dbSDimitry Andric     config->thinLTOJobs = v.str();
14425ffd83dbSDimitry Andric   }
14430b57cec5SDimitry Andric 
14440b57cec5SDimitry Andric   if (args.hasArg(OPT_show_timing))
14450b57cec5SDimitry Andric     config->showTiming = true;
14460b57cec5SDimitry Andric 
14470b57cec5SDimitry Andric   config->showSummary = args.hasArg(OPT_summary);
14480b57cec5SDimitry Andric 
14490b57cec5SDimitry Andric   // Handle --version, which is an lld extension. This option is a bit odd
14500b57cec5SDimitry Andric   // because it doesn't start with "/", but we deliberately chose "--" to
14510b57cec5SDimitry Andric   // avoid conflict with /version and for compatibility with clang-cl.
14520b57cec5SDimitry Andric   if (args.hasArg(OPT_dash_dash_version)) {
1453e8d8bef9SDimitry Andric     message(getLLDVersion());
14540b57cec5SDimitry Andric     return;
14550b57cec5SDimitry Andric   }
14560b57cec5SDimitry Andric 
14570b57cec5SDimitry Andric   // Handle /lldmingw early, since it can potentially affect how other
14580b57cec5SDimitry Andric   // options are handled.
14590b57cec5SDimitry Andric   config->mingw = args.hasArg(OPT_lldmingw);
14600b57cec5SDimitry Andric 
146185868e8aSDimitry Andric   // Handle /linkrepro and /reproduce.
146285868e8aSDimitry Andric   if (Optional<std::string> path = getReproduceFile(args)) {
14630b57cec5SDimitry Andric     Expected<std::unique_ptr<TarWriter>> errOrWriter =
146485868e8aSDimitry Andric         TarWriter::create(*path, sys::path::stem(*path));
14650b57cec5SDimitry Andric 
14660b57cec5SDimitry Andric     if (errOrWriter) {
14670b57cec5SDimitry Andric       tar = std::move(*errOrWriter);
14680b57cec5SDimitry Andric     } else {
146985868e8aSDimitry Andric       error("/linkrepro: failed to open " + *path + ": " +
14700b57cec5SDimitry Andric             toString(errOrWriter.takeError()));
14710b57cec5SDimitry Andric     }
14720b57cec5SDimitry Andric   }
14730b57cec5SDimitry Andric 
1474480093f4SDimitry Andric   if (!args.hasArg(OPT_INPUT, OPT_wholearchive_file)) {
14750b57cec5SDimitry Andric     if (args.hasArg(OPT_deffile))
14760b57cec5SDimitry Andric       config->noEntry = true;
14770b57cec5SDimitry Andric     else
14780b57cec5SDimitry Andric       fatal("no input files");
14790b57cec5SDimitry Andric   }
14800b57cec5SDimitry Andric 
14810b57cec5SDimitry Andric   // Construct search path list.
14820b57cec5SDimitry Andric   searchPaths.push_back("");
14830b57cec5SDimitry Andric   for (auto *arg : args.filtered(OPT_libpath))
14840b57cec5SDimitry Andric     searchPaths.push_back(arg->getValue());
148581ad6265SDimitry Andric   detectWinSysRoot(args);
148681ad6265SDimitry Andric   if (!args.hasArg(OPT_lldignoreenv) && !args.hasArg(OPT_winsysroot))
14870b57cec5SDimitry Andric     addLibSearchPaths();
14880b57cec5SDimitry Andric 
14890b57cec5SDimitry Andric   // Handle /ignore
14900b57cec5SDimitry Andric   for (auto *arg : args.filtered(OPT_ignore)) {
14910b57cec5SDimitry Andric     SmallVector<StringRef, 8> vec;
14920b57cec5SDimitry Andric     StringRef(arg->getValue()).split(vec, ',');
14930b57cec5SDimitry Andric     for (StringRef s : vec) {
14940b57cec5SDimitry Andric       if (s == "4037")
14950b57cec5SDimitry Andric         config->warnMissingOrderSymbol = false;
14960b57cec5SDimitry Andric       else if (s == "4099")
14970b57cec5SDimitry Andric         config->warnDebugInfoUnusable = false;
14980b57cec5SDimitry Andric       else if (s == "4217")
14990b57cec5SDimitry Andric         config->warnLocallyDefinedImported = false;
1500480093f4SDimitry Andric       else if (s == "longsections")
1501480093f4SDimitry Andric         config->warnLongSectionNames = false;
15020b57cec5SDimitry Andric       // Other warning numbers are ignored.
15030b57cec5SDimitry Andric     }
15040b57cec5SDimitry Andric   }
15050b57cec5SDimitry Andric 
15060b57cec5SDimitry Andric   // Handle /out
15070b57cec5SDimitry Andric   if (auto *arg = args.getLastArg(OPT_out))
15080b57cec5SDimitry Andric     config->outputFile = arg->getValue();
15090b57cec5SDimitry Andric 
15100b57cec5SDimitry Andric   // Handle /verbose
15110b57cec5SDimitry Andric   if (args.hasArg(OPT_verbose))
15120b57cec5SDimitry Andric     config->verbose = true;
15130b57cec5SDimitry Andric   errorHandler().verbose = config->verbose;
15140b57cec5SDimitry Andric 
15150b57cec5SDimitry Andric   // Handle /force or /force:unresolved
15160b57cec5SDimitry Andric   if (args.hasArg(OPT_force, OPT_force_unresolved))
15170b57cec5SDimitry Andric     config->forceUnresolved = true;
15180b57cec5SDimitry Andric 
15190b57cec5SDimitry Andric   // Handle /force or /force:multiple
15200b57cec5SDimitry Andric   if (args.hasArg(OPT_force, OPT_force_multiple))
15210b57cec5SDimitry Andric     config->forceMultiple = true;
15220b57cec5SDimitry Andric 
15230b57cec5SDimitry Andric   // Handle /force or /force:multipleres
15240b57cec5SDimitry Andric   if (args.hasArg(OPT_force, OPT_force_multipleres))
15250b57cec5SDimitry Andric     config->forceMultipleRes = true;
15260b57cec5SDimitry Andric 
15270b57cec5SDimitry Andric   // Handle /debug
15280b57cec5SDimitry Andric   DebugKind debug = parseDebugKind(args);
15290b57cec5SDimitry Andric   if (debug == DebugKind::Full || debug == DebugKind::Dwarf ||
1530fe6060f1SDimitry Andric       debug == DebugKind::GHash || debug == DebugKind::NoGHash) {
15310b57cec5SDimitry Andric     config->debug = true;
15320b57cec5SDimitry Andric     config->incremental = true;
15330b57cec5SDimitry Andric   }
15340b57cec5SDimitry Andric 
15350b57cec5SDimitry Andric   // Handle /demangle
153681ad6265SDimitry Andric   config->demangle = args.hasFlag(OPT_demangle, OPT_demangle_no, true);
15370b57cec5SDimitry Andric 
15380b57cec5SDimitry Andric   // Handle /debugtype
15390b57cec5SDimitry Andric   config->debugTypes = parseDebugTypes(args);
15400b57cec5SDimitry Andric 
1541480093f4SDimitry Andric   // Handle /driver[:uponly|:wdm].
1542480093f4SDimitry Andric   config->driverUponly = args.hasArg(OPT_driver_uponly) ||
1543480093f4SDimitry Andric                          args.hasArg(OPT_driver_uponly_wdm) ||
1544480093f4SDimitry Andric                          args.hasArg(OPT_driver_wdm_uponly);
1545480093f4SDimitry Andric   config->driverWdm = args.hasArg(OPT_driver_wdm) ||
1546480093f4SDimitry Andric                       args.hasArg(OPT_driver_uponly_wdm) ||
1547480093f4SDimitry Andric                       args.hasArg(OPT_driver_wdm_uponly);
1548480093f4SDimitry Andric   config->driver =
1549480093f4SDimitry Andric       config->driverUponly || config->driverWdm || args.hasArg(OPT_driver);
1550480093f4SDimitry Andric 
15510b57cec5SDimitry Andric   // Handle /pdb
15520b57cec5SDimitry Andric   bool shouldCreatePDB =
1553fe6060f1SDimitry Andric       (debug == DebugKind::Full || debug == DebugKind::GHash ||
1554fe6060f1SDimitry Andric        debug == DebugKind::NoGHash);
15550b57cec5SDimitry Andric   if (shouldCreatePDB) {
15560b57cec5SDimitry Andric     if (auto *arg = args.getLastArg(OPT_pdb))
15570b57cec5SDimitry Andric       config->pdbPath = arg->getValue();
15580b57cec5SDimitry Andric     if (auto *arg = args.getLastArg(OPT_pdbaltpath))
15590b57cec5SDimitry Andric       config->pdbAltPath = arg->getValue();
1560349cc55cSDimitry Andric     if (auto *arg = args.getLastArg(OPT_pdbpagesize))
1561349cc55cSDimitry Andric       parsePDBPageSize(arg->getValue());
15620b57cec5SDimitry Andric     if (args.hasArg(OPT_natvis))
15630b57cec5SDimitry Andric       config->natvisFiles = args.getAllArgValues(OPT_natvis);
15645ffd83dbSDimitry Andric     if (args.hasArg(OPT_pdbstream)) {
15655ffd83dbSDimitry Andric       for (const StringRef value : args.getAllArgValues(OPT_pdbstream)) {
15665ffd83dbSDimitry Andric         const std::pair<StringRef, StringRef> nameFile = value.split("=");
15675ffd83dbSDimitry Andric         const StringRef name = nameFile.first;
15685ffd83dbSDimitry Andric         const std::string file = nameFile.second.str();
15695ffd83dbSDimitry Andric         config->namedStreams[name] = file;
15705ffd83dbSDimitry Andric       }
15715ffd83dbSDimitry Andric     }
15720b57cec5SDimitry Andric 
15730b57cec5SDimitry Andric     if (auto *arg = args.getLastArg(OPT_pdb_source_path))
15740b57cec5SDimitry Andric       config->pdbSourcePath = arg->getValue();
15750b57cec5SDimitry Andric   }
15760b57cec5SDimitry Andric 
15775ffd83dbSDimitry Andric   // Handle /pdbstripped
15785ffd83dbSDimitry Andric   if (args.hasArg(OPT_pdbstripped))
15795ffd83dbSDimitry Andric     warn("ignoring /pdbstripped flag, it is not yet supported");
15805ffd83dbSDimitry Andric 
15810b57cec5SDimitry Andric   // Handle /noentry
15820b57cec5SDimitry Andric   if (args.hasArg(OPT_noentry)) {
15830b57cec5SDimitry Andric     if (args.hasArg(OPT_dll))
15840b57cec5SDimitry Andric       config->noEntry = true;
15850b57cec5SDimitry Andric     else
15860b57cec5SDimitry Andric       error("/noentry must be specified with /dll");
15870b57cec5SDimitry Andric   }
15880b57cec5SDimitry Andric 
15890b57cec5SDimitry Andric   // Handle /dll
15900b57cec5SDimitry Andric   if (args.hasArg(OPT_dll)) {
15910b57cec5SDimitry Andric     config->dll = true;
15920b57cec5SDimitry Andric     config->manifestID = 2;
15930b57cec5SDimitry Andric   }
15940b57cec5SDimitry Andric 
15950b57cec5SDimitry Andric   // Handle /dynamicbase and /fixed. We can't use hasFlag for /dynamicbase
15960b57cec5SDimitry Andric   // because we need to explicitly check whether that option or its inverse was
15970b57cec5SDimitry Andric   // present in the argument list in order to handle /fixed.
15980b57cec5SDimitry Andric   auto *dynamicBaseArg = args.getLastArg(OPT_dynamicbase, OPT_dynamicbase_no);
15990b57cec5SDimitry Andric   if (dynamicBaseArg &&
16000b57cec5SDimitry Andric       dynamicBaseArg->getOption().getID() == OPT_dynamicbase_no)
16010b57cec5SDimitry Andric     config->dynamicBase = false;
16020b57cec5SDimitry Andric 
16030b57cec5SDimitry Andric   // MSDN claims "/FIXED:NO is the default setting for a DLL, and /FIXED is the
16040b57cec5SDimitry Andric   // default setting for any other project type.", but link.exe defaults to
16050b57cec5SDimitry Andric   // /FIXED:NO for exe outputs as well. Match behavior, not docs.
16060b57cec5SDimitry Andric   bool fixed = args.hasFlag(OPT_fixed, OPT_fixed_no, false);
16070b57cec5SDimitry Andric   if (fixed) {
16080b57cec5SDimitry Andric     if (dynamicBaseArg &&
16090b57cec5SDimitry Andric         dynamicBaseArg->getOption().getID() == OPT_dynamicbase) {
16100b57cec5SDimitry Andric       error("/fixed must not be specified with /dynamicbase");
16110b57cec5SDimitry Andric     } else {
16120b57cec5SDimitry Andric       config->relocatable = false;
16130b57cec5SDimitry Andric       config->dynamicBase = false;
16140b57cec5SDimitry Andric     }
16150b57cec5SDimitry Andric   }
16160b57cec5SDimitry Andric 
16170b57cec5SDimitry Andric   // Handle /appcontainer
16180b57cec5SDimitry Andric   config->appContainer =
16190b57cec5SDimitry Andric       args.hasFlag(OPT_appcontainer, OPT_appcontainer_no, false);
16200b57cec5SDimitry Andric 
16210b57cec5SDimitry Andric   // Handle /machine
16220b57cec5SDimitry Andric   if (auto *arg = args.getLastArg(OPT_machine)) {
16230b57cec5SDimitry Andric     config->machine = getMachineType(arg->getValue());
16240b57cec5SDimitry Andric     if (config->machine == IMAGE_FILE_MACHINE_UNKNOWN)
16250b57cec5SDimitry Andric       fatal(Twine("unknown /machine argument: ") + arg->getValue());
162681ad6265SDimitry Andric     addWinSysRootLibSearchPaths();
16270b57cec5SDimitry Andric   }
16280b57cec5SDimitry Andric 
16290b57cec5SDimitry Andric   // Handle /nodefaultlib:<filename>
16300b57cec5SDimitry Andric   for (auto *arg : args.filtered(OPT_nodefaultlib))
16310b57cec5SDimitry Andric     config->noDefaultLibs.insert(doFindLib(arg->getValue()).lower());
16320b57cec5SDimitry Andric 
16330b57cec5SDimitry Andric   // Handle /nodefaultlib
16340b57cec5SDimitry Andric   if (args.hasArg(OPT_nodefaultlib_all))
16350b57cec5SDimitry Andric     config->noDefaultLibAll = true;
16360b57cec5SDimitry Andric 
16370b57cec5SDimitry Andric   // Handle /base
16380b57cec5SDimitry Andric   if (auto *arg = args.getLastArg(OPT_base))
16390b57cec5SDimitry Andric     parseNumbers(arg->getValue(), &config->imageBase);
16400b57cec5SDimitry Andric 
16410b57cec5SDimitry Andric   // Handle /filealign
16420b57cec5SDimitry Andric   if (auto *arg = args.getLastArg(OPT_filealign)) {
16430b57cec5SDimitry Andric     parseNumbers(arg->getValue(), &config->fileAlign);
16440b57cec5SDimitry Andric     if (!isPowerOf2_64(config->fileAlign))
16450b57cec5SDimitry Andric       error("/filealign: not a power of two: " + Twine(config->fileAlign));
16460b57cec5SDimitry Andric   }
16470b57cec5SDimitry Andric 
16480b57cec5SDimitry Andric   // Handle /stack
16490b57cec5SDimitry Andric   if (auto *arg = args.getLastArg(OPT_stack))
16500b57cec5SDimitry Andric     parseNumbers(arg->getValue(), &config->stackReserve, &config->stackCommit);
16510b57cec5SDimitry Andric 
16520b57cec5SDimitry Andric   // Handle /guard:cf
16530b57cec5SDimitry Andric   if (auto *arg = args.getLastArg(OPT_guard))
16540b57cec5SDimitry Andric     parseGuard(arg->getValue());
16550b57cec5SDimitry Andric 
16560b57cec5SDimitry Andric   // Handle /heap
16570b57cec5SDimitry Andric   if (auto *arg = args.getLastArg(OPT_heap))
16580b57cec5SDimitry Andric     parseNumbers(arg->getValue(), &config->heapReserve, &config->heapCommit);
16590b57cec5SDimitry Andric 
16600b57cec5SDimitry Andric   // Handle /version
16610b57cec5SDimitry Andric   if (auto *arg = args.getLastArg(OPT_version))
16620b57cec5SDimitry Andric     parseVersion(arg->getValue(), &config->majorImageVersion,
16630b57cec5SDimitry Andric                  &config->minorImageVersion);
16640b57cec5SDimitry Andric 
16650b57cec5SDimitry Andric   // Handle /subsystem
16660b57cec5SDimitry Andric   if (auto *arg = args.getLastArg(OPT_subsystem))
1667e8d8bef9SDimitry Andric     parseSubsystem(arg->getValue(), &config->subsystem,
1668e8d8bef9SDimitry Andric                    &config->majorSubsystemVersion,
1669e8d8bef9SDimitry Andric                    &config->minorSubsystemVersion);
1670e8d8bef9SDimitry Andric 
1671e8d8bef9SDimitry Andric   // Handle /osversion
1672e8d8bef9SDimitry Andric   if (auto *arg = args.getLastArg(OPT_osversion)) {
1673e8d8bef9SDimitry Andric     parseVersion(arg->getValue(), &config->majorOSVersion,
16740b57cec5SDimitry Andric                  &config->minorOSVersion);
1675e8d8bef9SDimitry Andric   } else {
1676e8d8bef9SDimitry Andric     config->majorOSVersion = config->majorSubsystemVersion;
1677e8d8bef9SDimitry Andric     config->minorOSVersion = config->minorSubsystemVersion;
1678e8d8bef9SDimitry Andric   }
16790b57cec5SDimitry Andric 
16800b57cec5SDimitry Andric   // Handle /timestamp
16810b57cec5SDimitry Andric   if (llvm::opt::Arg *arg = args.getLastArg(OPT_timestamp, OPT_repro)) {
16820b57cec5SDimitry Andric     if (arg->getOption().getID() == OPT_repro) {
16830b57cec5SDimitry Andric       config->timestamp = 0;
16840b57cec5SDimitry Andric       config->repro = true;
16850b57cec5SDimitry Andric     } else {
16860b57cec5SDimitry Andric       config->repro = false;
16870b57cec5SDimitry Andric       StringRef value(arg->getValue());
16880b57cec5SDimitry Andric       if (value.getAsInteger(0, config->timestamp))
16890b57cec5SDimitry Andric         fatal(Twine("invalid timestamp: ") + value +
16900b57cec5SDimitry Andric               ".  Expected 32-bit integer");
16910b57cec5SDimitry Andric     }
16920b57cec5SDimitry Andric   } else {
16930b57cec5SDimitry Andric     config->repro = false;
16940b57cec5SDimitry Andric     config->timestamp = time(nullptr);
16950b57cec5SDimitry Andric   }
16960b57cec5SDimitry Andric 
16970b57cec5SDimitry Andric   // Handle /alternatename
16980b57cec5SDimitry Andric   for (auto *arg : args.filtered(OPT_alternatename))
16990b57cec5SDimitry Andric     parseAlternateName(arg->getValue());
17000b57cec5SDimitry Andric 
17010b57cec5SDimitry Andric   // Handle /include
17020b57cec5SDimitry Andric   for (auto *arg : args.filtered(OPT_incl))
17030b57cec5SDimitry Andric     addUndefined(arg->getValue());
17040b57cec5SDimitry Andric 
17050b57cec5SDimitry Andric   // Handle /implib
17060b57cec5SDimitry Andric   if (auto *arg = args.getLastArg(OPT_implib))
17070b57cec5SDimitry Andric     config->implib = arg->getValue();
17080b57cec5SDimitry Andric 
170981ad6265SDimitry Andric   config->noimplib = args.hasArg(OPT_noimplib);
171081ad6265SDimitry Andric 
17110b57cec5SDimitry Andric   // Handle /opt.
17120b57cec5SDimitry Andric   bool doGC = debug == DebugKind::None || args.hasArg(OPT_profile);
1713fe6060f1SDimitry Andric   Optional<ICFLevel> icfLevel = None;
1714fe6060f1SDimitry Andric   if (args.hasArg(OPT_profile))
1715fe6060f1SDimitry Andric     icfLevel = ICFLevel::None;
17160b57cec5SDimitry Andric   unsigned tailMerge = 1;
1717e8d8bef9SDimitry Andric   bool ltoDebugPM = false;
17180b57cec5SDimitry Andric   for (auto *arg : args.filtered(OPT_opt)) {
17190b57cec5SDimitry Andric     std::string str = StringRef(arg->getValue()).lower();
17200b57cec5SDimitry Andric     SmallVector<StringRef, 1> vec;
17210b57cec5SDimitry Andric     StringRef(str).split(vec, ',');
17220b57cec5SDimitry Andric     for (StringRef s : vec) {
17230b57cec5SDimitry Andric       if (s == "ref") {
17240b57cec5SDimitry Andric         doGC = true;
17250b57cec5SDimitry Andric       } else if (s == "noref") {
17260b57cec5SDimitry Andric         doGC = false;
17270b57cec5SDimitry Andric       } else if (s == "icf" || s.startswith("icf=")) {
1728fe6060f1SDimitry Andric         icfLevel = ICFLevel::All;
1729fe6060f1SDimitry Andric       } else if (s == "safeicf") {
1730fe6060f1SDimitry Andric         icfLevel = ICFLevel::Safe;
17310b57cec5SDimitry Andric       } else if (s == "noicf") {
1732fe6060f1SDimitry Andric         icfLevel = ICFLevel::None;
17330b57cec5SDimitry Andric       } else if (s == "lldtailmerge") {
17340b57cec5SDimitry Andric         tailMerge = 2;
17350b57cec5SDimitry Andric       } else if (s == "nolldtailmerge") {
17360b57cec5SDimitry Andric         tailMerge = 0;
1737e8d8bef9SDimitry Andric       } else if (s == "ltonewpassmanager") {
173881ad6265SDimitry Andric         /* We always use the new PM. */
1739e8d8bef9SDimitry Andric       } else if (s == "ltodebugpassmanager") {
1740e8d8bef9SDimitry Andric         ltoDebugPM = true;
1741e8d8bef9SDimitry Andric       } else if (s == "noltodebugpassmanager") {
1742e8d8bef9SDimitry Andric         ltoDebugPM = false;
17430b57cec5SDimitry Andric       } else if (s.startswith("lldlto=")) {
17440b57cec5SDimitry Andric         StringRef optLevel = s.substr(7);
17450b57cec5SDimitry Andric         if (optLevel.getAsInteger(10, config->ltoo) || config->ltoo > 3)
17460b57cec5SDimitry Andric           error("/opt:lldlto: invalid optimization level: " + optLevel);
17470b57cec5SDimitry Andric       } else if (s.startswith("lldltojobs=")) {
17480b57cec5SDimitry Andric         StringRef jobs = s.substr(11);
17495ffd83dbSDimitry Andric         if (!get_threadpool_strategy(jobs))
17500b57cec5SDimitry Andric           error("/opt:lldltojobs: invalid job count: " + jobs);
17515ffd83dbSDimitry Andric         config->thinLTOJobs = jobs.str();
17520b57cec5SDimitry Andric       } else if (s.startswith("lldltopartitions=")) {
17530b57cec5SDimitry Andric         StringRef n = s.substr(17);
17540b57cec5SDimitry Andric         if (n.getAsInteger(10, config->ltoPartitions) ||
17550b57cec5SDimitry Andric             config->ltoPartitions == 0)
17560b57cec5SDimitry Andric           error("/opt:lldltopartitions: invalid partition count: " + n);
17570b57cec5SDimitry Andric       } else if (s != "lbr" && s != "nolbr")
17580b57cec5SDimitry Andric         error("/opt: unknown option: " + s);
17590b57cec5SDimitry Andric     }
17600b57cec5SDimitry Andric   }
17610b57cec5SDimitry Andric 
1762fe6060f1SDimitry Andric   if (!icfLevel)
1763fe6060f1SDimitry Andric     icfLevel = doGC ? ICFLevel::All : ICFLevel::None;
17640b57cec5SDimitry Andric   config->doGC = doGC;
176581ad6265SDimitry Andric   config->doICF = *icfLevel;
1766fe6060f1SDimitry Andric   config->tailMerge =
1767fe6060f1SDimitry Andric       (tailMerge == 1 && config->doICF != ICFLevel::None) || tailMerge == 2;
1768e8d8bef9SDimitry Andric   config->ltoDebugPassManager = ltoDebugPM;
17690b57cec5SDimitry Andric 
17700b57cec5SDimitry Andric   // Handle /lldsavetemps
17710b57cec5SDimitry Andric   if (args.hasArg(OPT_lldsavetemps))
17720b57cec5SDimitry Andric     config->saveTemps = true;
17730b57cec5SDimitry Andric 
17740b57cec5SDimitry Andric   // Handle /kill-at
17750b57cec5SDimitry Andric   if (args.hasArg(OPT_kill_at))
17760b57cec5SDimitry Andric     config->killAt = true;
17770b57cec5SDimitry Andric 
17780b57cec5SDimitry Andric   // Handle /lldltocache
17790b57cec5SDimitry Andric   if (auto *arg = args.getLastArg(OPT_lldltocache))
17800b57cec5SDimitry Andric     config->ltoCache = arg->getValue();
17810b57cec5SDimitry Andric 
17820b57cec5SDimitry Andric   // Handle /lldsavecachepolicy
17830b57cec5SDimitry Andric   if (auto *arg = args.getLastArg(OPT_lldltocachepolicy))
17840b57cec5SDimitry Andric     config->ltoCachePolicy = CHECK(
17850b57cec5SDimitry Andric         parseCachePruningPolicy(arg->getValue()),
17860b57cec5SDimitry Andric         Twine("/lldltocachepolicy: invalid cache policy: ") + arg->getValue());
17870b57cec5SDimitry Andric 
17880b57cec5SDimitry Andric   // Handle /failifmismatch
17890b57cec5SDimitry Andric   for (auto *arg : args.filtered(OPT_failifmismatch))
17900b57cec5SDimitry Andric     checkFailIfMismatch(arg->getValue(), nullptr);
17910b57cec5SDimitry Andric 
17920b57cec5SDimitry Andric   // Handle /merge
17930b57cec5SDimitry Andric   for (auto *arg : args.filtered(OPT_merge))
17940b57cec5SDimitry Andric     parseMerge(arg->getValue());
17950b57cec5SDimitry Andric 
17960b57cec5SDimitry Andric   // Add default section merging rules after user rules. User rules take
17970b57cec5SDimitry Andric   // precedence, but we will emit a warning if there is a conflict.
17980b57cec5SDimitry Andric   parseMerge(".idata=.rdata");
17990b57cec5SDimitry Andric   parseMerge(".didat=.rdata");
18000b57cec5SDimitry Andric   parseMerge(".edata=.rdata");
18010b57cec5SDimitry Andric   parseMerge(".xdata=.rdata");
18020b57cec5SDimitry Andric   parseMerge(".bss=.data");
18030b57cec5SDimitry Andric 
18040b57cec5SDimitry Andric   if (config->mingw) {
18050b57cec5SDimitry Andric     parseMerge(".ctors=.rdata");
18060b57cec5SDimitry Andric     parseMerge(".dtors=.rdata");
18070b57cec5SDimitry Andric     parseMerge(".CRT=.rdata");
18080b57cec5SDimitry Andric   }
18090b57cec5SDimitry Andric 
18100b57cec5SDimitry Andric   // Handle /section
18110b57cec5SDimitry Andric   for (auto *arg : args.filtered(OPT_section))
18120b57cec5SDimitry Andric     parseSection(arg->getValue());
18130b57cec5SDimitry Andric 
18140b57cec5SDimitry Andric   // Handle /align
18150b57cec5SDimitry Andric   if (auto *arg = args.getLastArg(OPT_align)) {
18160b57cec5SDimitry Andric     parseNumbers(arg->getValue(), &config->align);
18170b57cec5SDimitry Andric     if (!isPowerOf2_64(config->align))
18180b57cec5SDimitry Andric       error("/align: not a power of two: " + StringRef(arg->getValue()));
1819480093f4SDimitry Andric     if (!args.hasArg(OPT_driver))
1820480093f4SDimitry Andric       warn("/align specified without /driver; image may not run");
18210b57cec5SDimitry Andric   }
18220b57cec5SDimitry Andric 
18230b57cec5SDimitry Andric   // Handle /aligncomm
18240b57cec5SDimitry Andric   for (auto *arg : args.filtered(OPT_aligncomm))
18250b57cec5SDimitry Andric     parseAligncomm(arg->getValue());
18260b57cec5SDimitry Andric 
1827349cc55cSDimitry Andric   // Handle /manifestdependency.
1828349cc55cSDimitry Andric   for (auto *arg : args.filtered(OPT_manifestdependency))
1829349cc55cSDimitry Andric     config->manifestDependencies.insert(arg->getValue());
18300b57cec5SDimitry Andric 
18310b57cec5SDimitry Andric   // Handle /manifest and /manifest:
18320b57cec5SDimitry Andric   if (auto *arg = args.getLastArg(OPT_manifest, OPT_manifest_colon)) {
18330b57cec5SDimitry Andric     if (arg->getOption().getID() == OPT_manifest)
18340b57cec5SDimitry Andric       config->manifest = Configuration::SideBySide;
18350b57cec5SDimitry Andric     else
18360b57cec5SDimitry Andric       parseManifest(arg->getValue());
18370b57cec5SDimitry Andric   }
18380b57cec5SDimitry Andric 
18390b57cec5SDimitry Andric   // Handle /manifestuac
18400b57cec5SDimitry Andric   if (auto *arg = args.getLastArg(OPT_manifestuac))
18410b57cec5SDimitry Andric     parseManifestUAC(arg->getValue());
18420b57cec5SDimitry Andric 
18430b57cec5SDimitry Andric   // Handle /manifestfile
18440b57cec5SDimitry Andric   if (auto *arg = args.getLastArg(OPT_manifestfile))
18450b57cec5SDimitry Andric     config->manifestFile = arg->getValue();
18460b57cec5SDimitry Andric 
18470b57cec5SDimitry Andric   // Handle /manifestinput
18480b57cec5SDimitry Andric   for (auto *arg : args.filtered(OPT_manifestinput))
18490b57cec5SDimitry Andric     config->manifestInput.push_back(arg->getValue());
18500b57cec5SDimitry Andric 
18510b57cec5SDimitry Andric   if (!config->manifestInput.empty() &&
18520b57cec5SDimitry Andric       config->manifest != Configuration::Embed) {
18530b57cec5SDimitry Andric     fatal("/manifestinput: requires /manifest:embed");
18540b57cec5SDimitry Andric   }
18550b57cec5SDimitry Andric 
18560b57cec5SDimitry Andric   config->thinLTOEmitImportsFiles = args.hasArg(OPT_thinlto_emit_imports_files);
18570b57cec5SDimitry Andric   config->thinLTOIndexOnly = args.hasArg(OPT_thinlto_index_only) ||
18580b57cec5SDimitry Andric                              args.hasArg(OPT_thinlto_index_only_arg);
18590b57cec5SDimitry Andric   config->thinLTOIndexOnlyArg =
18600b57cec5SDimitry Andric       args.getLastArgValue(OPT_thinlto_index_only_arg);
18610b57cec5SDimitry Andric   config->thinLTOPrefixReplace =
18620b57cec5SDimitry Andric       getOldNewOptions(args, OPT_thinlto_prefix_replace);
18630b57cec5SDimitry Andric   config->thinLTOObjectSuffixReplace =
18640b57cec5SDimitry Andric       getOldNewOptions(args, OPT_thinlto_object_suffix_replace);
186585868e8aSDimitry Andric   config->ltoObjPath = args.getLastArgValue(OPT_lto_obj_path);
1866fe6060f1SDimitry Andric   config->ltoCSProfileGenerate = args.hasArg(OPT_lto_cs_profile_generate);
1867fe6060f1SDimitry Andric   config->ltoCSProfileFile = args.getLastArgValue(OPT_lto_cs_profile_file);
18680b57cec5SDimitry Andric   // Handle miscellaneous boolean flags.
1869349cc55cSDimitry Andric   config->ltoPGOWarnMismatch = args.hasFlag(OPT_lto_pgo_warn_mismatch,
1870349cc55cSDimitry Andric                                             OPT_lto_pgo_warn_mismatch_no, true);
18710b57cec5SDimitry Andric   config->allowBind = args.hasFlag(OPT_allowbind, OPT_allowbind_no, true);
18720b57cec5SDimitry Andric   config->allowIsolation =
18730b57cec5SDimitry Andric       args.hasFlag(OPT_allowisolation, OPT_allowisolation_no, true);
18740b57cec5SDimitry Andric   config->incremental =
18750b57cec5SDimitry Andric       args.hasFlag(OPT_incremental, OPT_incremental_no,
1876fe6060f1SDimitry Andric                    !config->doGC && config->doICF == ICFLevel::None &&
1877fe6060f1SDimitry Andric                        !args.hasArg(OPT_order) && !args.hasArg(OPT_profile));
18780b57cec5SDimitry Andric   config->integrityCheck =
18790b57cec5SDimitry Andric       args.hasFlag(OPT_integritycheck, OPT_integritycheck_no, false);
18805ffd83dbSDimitry Andric   config->cetCompat = args.hasFlag(OPT_cetcompat, OPT_cetcompat_no, false);
18810b57cec5SDimitry Andric   config->nxCompat = args.hasFlag(OPT_nxcompat, OPT_nxcompat_no, true);
18820b57cec5SDimitry Andric   for (auto *arg : args.filtered(OPT_swaprun))
18830b57cec5SDimitry Andric     parseSwaprun(arg->getValue());
18840b57cec5SDimitry Andric   config->terminalServerAware =
18850b57cec5SDimitry Andric       !config->dll && args.hasFlag(OPT_tsaware, OPT_tsaware_no, true);
18860b57cec5SDimitry Andric   config->debugDwarf = debug == DebugKind::Dwarf;
1887fe6060f1SDimitry Andric   config->debugGHashes = debug == DebugKind::GHash || debug == DebugKind::Full;
18880b57cec5SDimitry Andric   config->debugSymtab = debug == DebugKind::Symtab;
18895ffd83dbSDimitry Andric   config->autoImport =
18905ffd83dbSDimitry Andric       args.hasFlag(OPT_auto_import, OPT_auto_import_no, config->mingw);
18915ffd83dbSDimitry Andric   config->pseudoRelocs = args.hasFlag(
18925ffd83dbSDimitry Andric       OPT_runtime_pseudo_reloc, OPT_runtime_pseudo_reloc_no, config->mingw);
1893e8d8bef9SDimitry Andric   config->callGraphProfileSort = args.hasFlag(
1894e8d8bef9SDimitry Andric       OPT_call_graph_profile_sort, OPT_call_graph_profile_sort_no, true);
1895fe6060f1SDimitry Andric   config->stdcallFixup =
1896fe6060f1SDimitry Andric       args.hasFlag(OPT_stdcall_fixup, OPT_stdcall_fixup_no, config->mingw);
1897fe6060f1SDimitry Andric   config->warnStdcallFixup = !args.hasArg(OPT_stdcall_fixup);
18980b57cec5SDimitry Andric 
1899e8d8bef9SDimitry Andric   // Don't warn about long section names, such as .debug_info, for mingw or
1900e8d8bef9SDimitry Andric   // when -debug:dwarf is requested.
1901480093f4SDimitry Andric   if (config->mingw || config->debugDwarf)
1902480093f4SDimitry Andric     config->warnLongSectionNames = false;
1903480093f4SDimitry Andric 
19045ffd83dbSDimitry Andric   config->lldmapFile = getMapFile(args, OPT_lldmap, OPT_lldmap_file);
19055ffd83dbSDimitry Andric   config->mapFile = getMapFile(args, OPT_map, OPT_map_file);
19065ffd83dbSDimitry Andric 
19075ffd83dbSDimitry Andric   if (config->lldmapFile != "" && config->lldmapFile == config->mapFile) {
19085ffd83dbSDimitry Andric     warn("/lldmap and /map have the same output file '" + config->mapFile +
19095ffd83dbSDimitry Andric          "'.\n>>> ignoring /lldmap");
19105ffd83dbSDimitry Andric     config->lldmapFile.clear();
19115ffd83dbSDimitry Andric   }
19120b57cec5SDimitry Andric 
19130b57cec5SDimitry Andric   if (config->incremental && args.hasArg(OPT_profile)) {
19140b57cec5SDimitry Andric     warn("ignoring '/incremental' due to '/profile' specification");
19150b57cec5SDimitry Andric     config->incremental = false;
19160b57cec5SDimitry Andric   }
19170b57cec5SDimitry Andric 
19180b57cec5SDimitry Andric   if (config->incremental && args.hasArg(OPT_order)) {
19190b57cec5SDimitry Andric     warn("ignoring '/incremental' due to '/order' specification");
19200b57cec5SDimitry Andric     config->incremental = false;
19210b57cec5SDimitry Andric   }
19220b57cec5SDimitry Andric 
19230b57cec5SDimitry Andric   if (config->incremental && config->doGC) {
19240b57cec5SDimitry Andric     warn("ignoring '/incremental' because REF is enabled; use '/opt:noref' to "
19250b57cec5SDimitry Andric          "disable");
19260b57cec5SDimitry Andric     config->incremental = false;
19270b57cec5SDimitry Andric   }
19280b57cec5SDimitry Andric 
1929fe6060f1SDimitry Andric   if (config->incremental && config->doICF != ICFLevel::None) {
19300b57cec5SDimitry Andric     warn("ignoring '/incremental' because ICF is enabled; use '/opt:noicf' to "
19310b57cec5SDimitry Andric          "disable");
19320b57cec5SDimitry Andric     config->incremental = false;
19330b57cec5SDimitry Andric   }
19340b57cec5SDimitry Andric 
19350b57cec5SDimitry Andric   if (errorCount())
19360b57cec5SDimitry Andric     return;
19370b57cec5SDimitry Andric 
19380b57cec5SDimitry Andric   std::set<sys::fs::UniqueID> wholeArchives;
19390b57cec5SDimitry Andric   for (auto *arg : args.filtered(OPT_wholearchive_file))
19400b57cec5SDimitry Andric     if (Optional<StringRef> path = doFindFile(arg->getValue()))
19410b57cec5SDimitry Andric       if (Optional<sys::fs::UniqueID> id = getUniqueID(*path))
19420b57cec5SDimitry Andric         wholeArchives.insert(*id);
19430b57cec5SDimitry Andric 
19440b57cec5SDimitry Andric   // A predicate returning true if a given path is an argument for
19450b57cec5SDimitry Andric   // /wholearchive:, or /wholearchive is enabled globally.
19460b57cec5SDimitry Andric   // This function is a bit tricky because "foo.obj /wholearchive:././foo.obj"
19470b57cec5SDimitry Andric   // needs to be handled as "/wholearchive:foo.obj foo.obj".
19480b57cec5SDimitry Andric   auto isWholeArchive = [&](StringRef path) -> bool {
19490b57cec5SDimitry Andric     if (args.hasArg(OPT_wholearchive_flag))
19500b57cec5SDimitry Andric       return true;
19510b57cec5SDimitry Andric     if (Optional<sys::fs::UniqueID> id = getUniqueID(path))
19520b57cec5SDimitry Andric       return wholeArchives.count(*id);
19530b57cec5SDimitry Andric     return false;
19540b57cec5SDimitry Andric   };
19550b57cec5SDimitry Andric 
195685868e8aSDimitry Andric   // Create a list of input files. These can be given as OPT_INPUT options
195785868e8aSDimitry Andric   // and OPT_wholearchive_file options, and we also need to track OPT_start_lib
195885868e8aSDimitry Andric   // and OPT_end_lib.
195985868e8aSDimitry Andric   bool inLib = false;
196085868e8aSDimitry Andric   for (auto *arg : args) {
196185868e8aSDimitry Andric     switch (arg->getOption().getID()) {
196285868e8aSDimitry Andric     case OPT_end_lib:
196385868e8aSDimitry Andric       if (!inLib)
196485868e8aSDimitry Andric         error("stray " + arg->getSpelling());
196585868e8aSDimitry Andric       inLib = false;
196685868e8aSDimitry Andric       break;
196785868e8aSDimitry Andric     case OPT_start_lib:
196885868e8aSDimitry Andric       if (inLib)
196985868e8aSDimitry Andric         error("nested " + arg->getSpelling());
197085868e8aSDimitry Andric       inLib = true;
197185868e8aSDimitry Andric       break;
197285868e8aSDimitry Andric     case OPT_wholearchive_file:
19730b57cec5SDimitry Andric       if (Optional<StringRef> path = findFile(arg->getValue()))
197485868e8aSDimitry Andric         enqueuePath(*path, true, inLib);
197585868e8aSDimitry Andric       break;
197685868e8aSDimitry Andric     case OPT_INPUT:
197785868e8aSDimitry Andric       if (Optional<StringRef> path = findFile(arg->getValue()))
197885868e8aSDimitry Andric         enqueuePath(*path, isWholeArchive(*path), inLib);
197985868e8aSDimitry Andric       break;
198085868e8aSDimitry Andric     default:
198185868e8aSDimitry Andric       // Ignore other options.
198285868e8aSDimitry Andric       break;
198385868e8aSDimitry Andric     }
198485868e8aSDimitry Andric   }
19850b57cec5SDimitry Andric 
19860b57cec5SDimitry Andric   // Read all input files given via the command line.
19870b57cec5SDimitry Andric   run();
19880b57cec5SDimitry Andric   if (errorCount())
19890b57cec5SDimitry Andric     return;
19900b57cec5SDimitry Andric 
19910b57cec5SDimitry Andric   // We should have inferred a machine type by now from the input files, but if
19920b57cec5SDimitry Andric   // not we assume x64.
19930b57cec5SDimitry Andric   if (config->machine == IMAGE_FILE_MACHINE_UNKNOWN) {
19940b57cec5SDimitry Andric     warn("/machine is not specified. x64 is assumed");
19950b57cec5SDimitry Andric     config->machine = AMD64;
199681ad6265SDimitry Andric     addWinSysRootLibSearchPaths();
19970b57cec5SDimitry Andric   }
19980b57cec5SDimitry Andric   config->wordsize = config->is64() ? 8 : 4;
19990b57cec5SDimitry Andric 
200081ad6265SDimitry Andric   // Process files specified as /defaultlib. These must be processed after
200181ad6265SDimitry Andric   // addWinSysRootLibSearchPaths(), which is why they are in a separate loop.
200281ad6265SDimitry Andric   for (auto *arg : args.filtered(OPT_defaultlib))
200381ad6265SDimitry Andric     if (Optional<StringRef> path = findLib(arg->getValue()))
200481ad6265SDimitry Andric       enqueuePath(*path, false, false);
200581ad6265SDimitry Andric   run();
200681ad6265SDimitry Andric   if (errorCount())
200781ad6265SDimitry Andric     return;
200881ad6265SDimitry Andric 
20090b57cec5SDimitry Andric   // Handle /safeseh, x86 only, on by default, except for mingw.
2010979e22ffSDimitry Andric   if (config->machine == I386) {
2011979e22ffSDimitry Andric     config->safeSEH = args.hasFlag(OPT_safeseh, OPT_safeseh_no, !config->mingw);
2012979e22ffSDimitry Andric     config->noSEH = args.hasArg(OPT_noseh);
2013979e22ffSDimitry Andric   }
20140b57cec5SDimitry Andric 
20150b57cec5SDimitry Andric   // Handle /functionpadmin
20160b57cec5SDimitry Andric   for (auto *arg : args.filtered(OPT_functionpadmin, OPT_functionpadmin_opt))
20170b57cec5SDimitry Andric     parseFunctionPadMin(arg, config->machine);
20180b57cec5SDimitry Andric 
201981ad6265SDimitry Andric   if (tar) {
20200b57cec5SDimitry Andric     tar->append("response.txt",
20210b57cec5SDimitry Andric                 createResponseFile(args, filePaths,
20220b57cec5SDimitry Andric                                    ArrayRef<StringRef>(searchPaths).slice(1)));
202381ad6265SDimitry Andric   }
20240b57cec5SDimitry Andric 
20250b57cec5SDimitry Andric   // Handle /largeaddressaware
20260b57cec5SDimitry Andric   config->largeAddressAware = args.hasFlag(
20270b57cec5SDimitry Andric       OPT_largeaddressaware, OPT_largeaddressaware_no, config->is64());
20280b57cec5SDimitry Andric 
20290b57cec5SDimitry Andric   // Handle /highentropyva
20300b57cec5SDimitry Andric   config->highEntropyVA =
20310b57cec5SDimitry Andric       config->is64() &&
20320b57cec5SDimitry Andric       args.hasFlag(OPT_highentropyva, OPT_highentropyva_no, true);
20330b57cec5SDimitry Andric 
20340b57cec5SDimitry Andric   if (!config->dynamicBase &&
20350b57cec5SDimitry Andric       (config->machine == ARMNT || config->machine == ARM64))
20360b57cec5SDimitry Andric     error("/dynamicbase:no is not compatible with " +
20370b57cec5SDimitry Andric           machineToStr(config->machine));
20380b57cec5SDimitry Andric 
20390b57cec5SDimitry Andric   // Handle /export
20400b57cec5SDimitry Andric   for (auto *arg : args.filtered(OPT_export)) {
20410b57cec5SDimitry Andric     Export e = parseExport(arg->getValue());
20420b57cec5SDimitry Andric     if (config->machine == I386) {
20430b57cec5SDimitry Andric       if (!isDecorated(e.name))
204404eeddc0SDimitry Andric         e.name = saver().save("_" + e.name);
20450b57cec5SDimitry Andric       if (!e.extName.empty() && !isDecorated(e.extName))
204604eeddc0SDimitry Andric         e.extName = saver().save("_" + e.extName);
20470b57cec5SDimitry Andric     }
20480b57cec5SDimitry Andric     config->exports.push_back(e);
20490b57cec5SDimitry Andric   }
20500b57cec5SDimitry Andric 
20510b57cec5SDimitry Andric   // Handle /def
20520b57cec5SDimitry Andric   if (auto *arg = args.getLastArg(OPT_deffile)) {
20530b57cec5SDimitry Andric     // parseModuleDefs mutates Config object.
20540b57cec5SDimitry Andric     parseModuleDefs(arg->getValue());
20550b57cec5SDimitry Andric   }
20560b57cec5SDimitry Andric 
20570b57cec5SDimitry Andric   // Handle generation of import library from a def file.
2058480093f4SDimitry Andric   if (!args.hasArg(OPT_INPUT, OPT_wholearchive_file)) {
20590b57cec5SDimitry Andric     fixupExports();
206081ad6265SDimitry Andric     if (!config->noimplib)
20610b57cec5SDimitry Andric       createImportLibrary(/*asLib=*/true);
20620b57cec5SDimitry Andric     return;
20630b57cec5SDimitry Andric   }
20640b57cec5SDimitry Andric 
20650b57cec5SDimitry Andric   // Windows specific -- if no /subsystem is given, we need to infer
20660b57cec5SDimitry Andric   // that from entry point name.  Must happen before /entry handling,
20670b57cec5SDimitry Andric   // and after the early return when just writing an import library.
20680b57cec5SDimitry Andric   if (config->subsystem == IMAGE_SUBSYSTEM_UNKNOWN) {
20690b57cec5SDimitry Andric     config->subsystem = inferSubsystem();
20700b57cec5SDimitry Andric     if (config->subsystem == IMAGE_SUBSYSTEM_UNKNOWN)
20710b57cec5SDimitry Andric       fatal("subsystem must be defined");
20720b57cec5SDimitry Andric   }
20730b57cec5SDimitry Andric 
20740b57cec5SDimitry Andric   // Handle /entry and /dll
20750b57cec5SDimitry Andric   if (auto *arg = args.getLastArg(OPT_entry)) {
20760b57cec5SDimitry Andric     config->entry = addUndefined(mangle(arg->getValue()));
20770b57cec5SDimitry Andric   } else if (!config->entry && !config->noEntry) {
20780b57cec5SDimitry Andric     if (args.hasArg(OPT_dll)) {
20790b57cec5SDimitry Andric       StringRef s = (config->machine == I386) ? "__DllMainCRTStartup@12"
20800b57cec5SDimitry Andric                                               : "_DllMainCRTStartup";
20810b57cec5SDimitry Andric       config->entry = addUndefined(s);
2082480093f4SDimitry Andric     } else if (config->driverWdm) {
2083480093f4SDimitry Andric       // /driver:wdm implies /entry:_NtProcessStartup
2084480093f4SDimitry Andric       config->entry = addUndefined(mangle("_NtProcessStartup"));
20850b57cec5SDimitry Andric     } else {
20860b57cec5SDimitry Andric       // Windows specific -- If entry point name is not given, we need to
20870b57cec5SDimitry Andric       // infer that from user-defined entry name.
20880b57cec5SDimitry Andric       StringRef s = findDefaultEntry();
20890b57cec5SDimitry Andric       if (s.empty())
20900b57cec5SDimitry Andric         fatal("entry point must be defined");
20910b57cec5SDimitry Andric       config->entry = addUndefined(s);
20920b57cec5SDimitry Andric       log("Entry name inferred: " + s);
20930b57cec5SDimitry Andric     }
20940b57cec5SDimitry Andric   }
20950b57cec5SDimitry Andric 
20960b57cec5SDimitry Andric   // Handle /delayload
20970b57cec5SDimitry Andric   for (auto *arg : args.filtered(OPT_delayload)) {
20980b57cec5SDimitry Andric     config->delayLoads.insert(StringRef(arg->getValue()).lower());
20990b57cec5SDimitry Andric     if (config->machine == I386) {
21000b57cec5SDimitry Andric       config->delayLoadHelper = addUndefined("___delayLoadHelper2@8");
21010b57cec5SDimitry Andric     } else {
21020b57cec5SDimitry Andric       config->delayLoadHelper = addUndefined("__delayLoadHelper2");
21030b57cec5SDimitry Andric     }
21040b57cec5SDimitry Andric   }
21050b57cec5SDimitry Andric 
21060b57cec5SDimitry Andric   // Set default image name if neither /out or /def set it.
21070b57cec5SDimitry Andric   if (config->outputFile.empty()) {
2108480093f4SDimitry Andric     config->outputFile = getOutputPath(
2109480093f4SDimitry Andric         (*args.filtered(OPT_INPUT, OPT_wholearchive_file).begin())->getValue());
21100b57cec5SDimitry Andric   }
21110b57cec5SDimitry Andric 
21120b57cec5SDimitry Andric   // Fail early if an output file is not writable.
21130b57cec5SDimitry Andric   if (auto e = tryCreateFile(config->outputFile)) {
21140b57cec5SDimitry Andric     error("cannot open output file " + config->outputFile + ": " + e.message());
21150b57cec5SDimitry Andric     return;
21160b57cec5SDimitry Andric   }
21170b57cec5SDimitry Andric 
21180b57cec5SDimitry Andric   if (shouldCreatePDB) {
21190b57cec5SDimitry Andric     // Put the PDB next to the image if no /pdb flag was passed.
21200b57cec5SDimitry Andric     if (config->pdbPath.empty()) {
21210b57cec5SDimitry Andric       config->pdbPath = config->outputFile;
21220b57cec5SDimitry Andric       sys::path::replace_extension(config->pdbPath, ".pdb");
21230b57cec5SDimitry Andric     }
21240b57cec5SDimitry Andric 
21250b57cec5SDimitry Andric     // The embedded PDB path should be the absolute path to the PDB if no
21260b57cec5SDimitry Andric     // /pdbaltpath flag was passed.
21270b57cec5SDimitry Andric     if (config->pdbAltPath.empty()) {
21280b57cec5SDimitry Andric       config->pdbAltPath = config->pdbPath;
21290b57cec5SDimitry Andric 
21300b57cec5SDimitry Andric       // It's important to make the path absolute and remove dots.  This path
21310b57cec5SDimitry Andric       // will eventually be written into the PE header, and certain Microsoft
21320b57cec5SDimitry Andric       // tools won't work correctly if these assumptions are not held.
21330b57cec5SDimitry Andric       sys::fs::make_absolute(config->pdbAltPath);
21340b57cec5SDimitry Andric       sys::path::remove_dots(config->pdbAltPath);
21350b57cec5SDimitry Andric     } else {
21360b57cec5SDimitry Andric       // Don't do this earlier, so that Config->OutputFile is ready.
21370b57cec5SDimitry Andric       parsePDBAltPath(config->pdbAltPath);
21380b57cec5SDimitry Andric     }
21390b57cec5SDimitry Andric   }
21400b57cec5SDimitry Andric 
21410b57cec5SDimitry Andric   // Set default image base if /base is not given.
21420b57cec5SDimitry Andric   if (config->imageBase == uint64_t(-1))
21430b57cec5SDimitry Andric     config->imageBase = getDefaultImageBase();
21440b57cec5SDimitry Andric 
2145349cc55cSDimitry Andric   ctx.symtab.addSynthetic(mangle("__ImageBase"), nullptr);
21460b57cec5SDimitry Andric   if (config->machine == I386) {
2147349cc55cSDimitry Andric     ctx.symtab.addAbsolute("___safe_se_handler_table", 0);
2148349cc55cSDimitry Andric     ctx.symtab.addAbsolute("___safe_se_handler_count", 0);
21490b57cec5SDimitry Andric   }
21500b57cec5SDimitry Andric 
2151349cc55cSDimitry Andric   ctx.symtab.addAbsolute(mangle("__guard_fids_count"), 0);
2152349cc55cSDimitry Andric   ctx.symtab.addAbsolute(mangle("__guard_fids_table"), 0);
2153349cc55cSDimitry Andric   ctx.symtab.addAbsolute(mangle("__guard_flags"), 0);
2154349cc55cSDimitry Andric   ctx.symtab.addAbsolute(mangle("__guard_iat_count"), 0);
2155349cc55cSDimitry Andric   ctx.symtab.addAbsolute(mangle("__guard_iat_table"), 0);
2156349cc55cSDimitry Andric   ctx.symtab.addAbsolute(mangle("__guard_longjmp_count"), 0);
2157349cc55cSDimitry Andric   ctx.symtab.addAbsolute(mangle("__guard_longjmp_table"), 0);
21580b57cec5SDimitry Andric   // Needed for MSVC 2017 15.5 CRT.
2159349cc55cSDimitry Andric   ctx.symtab.addAbsolute(mangle("__enclave_config"), 0);
2160fe6060f1SDimitry Andric   // Needed for MSVC 2019 16.8 CRT.
2161349cc55cSDimitry Andric   ctx.symtab.addAbsolute(mangle("__guard_eh_cont_count"), 0);
2162349cc55cSDimitry Andric   ctx.symtab.addAbsolute(mangle("__guard_eh_cont_table"), 0);
21630b57cec5SDimitry Andric 
21645ffd83dbSDimitry Andric   if (config->pseudoRelocs) {
2165349cc55cSDimitry Andric     ctx.symtab.addAbsolute(mangle("__RUNTIME_PSEUDO_RELOC_LIST__"), 0);
2166349cc55cSDimitry Andric     ctx.symtab.addAbsolute(mangle("__RUNTIME_PSEUDO_RELOC_LIST_END__"), 0);
21675ffd83dbSDimitry Andric   }
21685ffd83dbSDimitry Andric   if (config->mingw) {
2169349cc55cSDimitry Andric     ctx.symtab.addAbsolute(mangle("__CTOR_LIST__"), 0);
2170349cc55cSDimitry Andric     ctx.symtab.addAbsolute(mangle("__DTOR_LIST__"), 0);
21710b57cec5SDimitry Andric   }
21720b57cec5SDimitry Andric 
21730b57cec5SDimitry Andric   // This code may add new undefined symbols to the link, which may enqueue more
21740b57cec5SDimitry Andric   // symbol resolution tasks, so we need to continue executing tasks until we
21750b57cec5SDimitry Andric   // converge.
21760b57cec5SDimitry Andric   do {
21770b57cec5SDimitry Andric     // Windows specific -- if entry point is not found,
21780b57cec5SDimitry Andric     // search for its mangled names.
21790b57cec5SDimitry Andric     if (config->entry)
21800b57cec5SDimitry Andric       mangleMaybe(config->entry);
21810b57cec5SDimitry Andric 
21820b57cec5SDimitry Andric     // Windows specific -- Make sure we resolve all dllexported symbols.
21830b57cec5SDimitry Andric     for (Export &e : config->exports) {
21840b57cec5SDimitry Andric       if (!e.forwardTo.empty())
21850b57cec5SDimitry Andric         continue;
21860b57cec5SDimitry Andric       e.sym = addUndefined(e.name);
21870b57cec5SDimitry Andric       if (!e.directives)
21880b57cec5SDimitry Andric         e.symbolName = mangleMaybe(e.sym);
21890b57cec5SDimitry Andric     }
21900b57cec5SDimitry Andric 
21910b57cec5SDimitry Andric     // Add weak aliases. Weak aliases is a mechanism to give remaining
21920b57cec5SDimitry Andric     // undefined symbols final chance to be resolved successfully.
21930b57cec5SDimitry Andric     for (auto pair : config->alternateNames) {
21940b57cec5SDimitry Andric       StringRef from = pair.first;
21950b57cec5SDimitry Andric       StringRef to = pair.second;
2196349cc55cSDimitry Andric       Symbol *sym = ctx.symtab.find(from);
21970b57cec5SDimitry Andric       if (!sym)
21980b57cec5SDimitry Andric         continue;
21990b57cec5SDimitry Andric       if (auto *u = dyn_cast<Undefined>(sym))
22000b57cec5SDimitry Andric         if (!u->weakAlias)
2201349cc55cSDimitry Andric           u->weakAlias = ctx.symtab.addUndefined(to);
22020b57cec5SDimitry Andric     }
22030b57cec5SDimitry Andric 
22040b57cec5SDimitry Andric     // If any inputs are bitcode files, the LTO code generator may create
22050b57cec5SDimitry Andric     // references to library functions that are not explicit in the bitcode
22060b57cec5SDimitry Andric     // file's symbol table. If any of those library functions are defined in a
22070b57cec5SDimitry Andric     // bitcode file in an archive member, we need to arrange to use LTO to
22080b57cec5SDimitry Andric     // compile those archive members by adding them to the link beforehand.
2209349cc55cSDimitry Andric     if (!ctx.bitcodeFileInstances.empty())
221085868e8aSDimitry Andric       for (auto *s : lto::LTO::getRuntimeLibcallSymbols())
2211349cc55cSDimitry Andric         ctx.symtab.addLibcall(s);
22120b57cec5SDimitry Andric 
22130b57cec5SDimitry Andric     // Windows specific -- if __load_config_used can be resolved, resolve it.
2214349cc55cSDimitry Andric     if (ctx.symtab.findUnderscore("_load_config_used"))
22150b57cec5SDimitry Andric       addUndefined(mangle("_load_config_used"));
22160b57cec5SDimitry Andric   } while (run());
22170b57cec5SDimitry Andric 
22180b57cec5SDimitry Andric   if (args.hasArg(OPT_include_optional)) {
22190b57cec5SDimitry Andric     // Handle /includeoptional
22200b57cec5SDimitry Andric     for (auto *arg : args.filtered(OPT_include_optional))
22210eae32dcSDimitry Andric       if (isa_and_nonnull<LazyArchive>(ctx.symtab.find(arg->getValue())))
22220b57cec5SDimitry Andric         addUndefined(arg->getValue());
22230b57cec5SDimitry Andric     while (run());
22240b57cec5SDimitry Andric   }
22250b57cec5SDimitry Andric 
2226e8d8bef9SDimitry Andric   // Create wrapped symbols for -wrap option.
2227349cc55cSDimitry Andric   std::vector<WrappedSymbol> wrapped = addWrappedSymbols(ctx, args);
2228e8d8bef9SDimitry Andric   // Load more object files that might be needed for wrapped symbols.
2229e8d8bef9SDimitry Andric   if (!wrapped.empty())
2230e8d8bef9SDimitry Andric     while (run());
2231e8d8bef9SDimitry Andric 
2232fe6060f1SDimitry Andric   if (config->autoImport || config->stdcallFixup) {
22335ffd83dbSDimitry Andric     // MinGW specific.
22340b57cec5SDimitry Andric     // Load any further object files that might be needed for doing automatic
2235fe6060f1SDimitry Andric     // imports, and do stdcall fixups.
22360b57cec5SDimitry Andric     //
22370b57cec5SDimitry Andric     // For cases with no automatically imported symbols, this iterates once
22380b57cec5SDimitry Andric     // over the symbol table and doesn't do anything.
22390b57cec5SDimitry Andric     //
22400b57cec5SDimitry Andric     // For the normal case with a few automatically imported symbols, this
22410b57cec5SDimitry Andric     // should only need to be run once, since each new object file imported
22420b57cec5SDimitry Andric     // is an import library and wouldn't add any new undefined references,
22430b57cec5SDimitry Andric     // but there's nothing stopping the __imp_ symbols from coming from a
22440b57cec5SDimitry Andric     // normal object file as well (although that won't be used for the
22450b57cec5SDimitry Andric     // actual autoimport later on). If this pass adds new undefined references,
22460b57cec5SDimitry Andric     // we won't iterate further to resolve them.
2247fe6060f1SDimitry Andric     //
2248fe6060f1SDimitry Andric     // If stdcall fixups only are needed for loading import entries from
2249fe6060f1SDimitry Andric     // a DLL without import library, this also just needs running once.
2250fe6060f1SDimitry Andric     // If it ends up pulling in more object files from static libraries,
2251fe6060f1SDimitry Andric     // (and maybe doing more stdcall fixups along the way), this would need
2252fe6060f1SDimitry Andric     // to loop these two calls.
2253349cc55cSDimitry Andric     ctx.symtab.loadMinGWSymbols();
22540b57cec5SDimitry Andric     run();
22550b57cec5SDimitry Andric   }
22560b57cec5SDimitry Andric 
225785868e8aSDimitry Andric   // At this point, we should not have any symbols that cannot be resolved.
225885868e8aSDimitry Andric   // If we are going to do codegen for link-time optimization, check for
225985868e8aSDimitry Andric   // unresolvable symbols first, so we don't spend time generating code that
226085868e8aSDimitry Andric   // will fail to link anyway.
2261349cc55cSDimitry Andric   if (!ctx.bitcodeFileInstances.empty() && !config->forceUnresolved)
2262349cc55cSDimitry Andric     ctx.symtab.reportUnresolvable();
22630b57cec5SDimitry Andric   if (errorCount())
22640b57cec5SDimitry Andric     return;
22650b57cec5SDimitry Andric 
2266fe6060f1SDimitry Andric   config->hadExplicitExports = !config->exports.empty();
2267fe6060f1SDimitry Andric   if (config->mingw) {
2268fe6060f1SDimitry Andric     // In MinGW, all symbols are automatically exported if no symbols
2269fe6060f1SDimitry Andric     // are chosen to be exported.
2270fe6060f1SDimitry Andric     maybeExportMinGWSymbols(args);
2271fe6060f1SDimitry Andric   }
2272fe6060f1SDimitry Andric 
227385868e8aSDimitry Andric   // Do LTO by compiling bitcode input files to a set of native COFF files then
227485868e8aSDimitry Andric   // link those files (unless -thinlto-index-only was given, in which case we
227585868e8aSDimitry Andric   // resolve symbols and write indices, but don't generate native code or link).
2276349cc55cSDimitry Andric   ctx.symtab.compileBitcodeFiles();
227785868e8aSDimitry Andric 
227885868e8aSDimitry Andric   // If -thinlto-index-only is given, we should create only "index
227985868e8aSDimitry Andric   // files" and not object files. Index file creation is already done
2280349cc55cSDimitry Andric   // in compileBitcodeFiles, so we are done if that's the case.
228185868e8aSDimitry Andric   if (config->thinLTOIndexOnly)
228285868e8aSDimitry Andric     return;
228385868e8aSDimitry Andric 
228485868e8aSDimitry Andric   // If we generated native object files from bitcode files, this resolves
228585868e8aSDimitry Andric   // references to the symbols we use from them.
228685868e8aSDimitry Andric   run();
228785868e8aSDimitry Andric 
2288e8d8bef9SDimitry Andric   // Apply symbol renames for -wrap.
2289e8d8bef9SDimitry Andric   if (!wrapped.empty())
2290349cc55cSDimitry Andric     wrapSymbols(ctx, wrapped);
2291e8d8bef9SDimitry Andric 
229285868e8aSDimitry Andric   // Resolve remaining undefined symbols and warn about imported locals.
2293349cc55cSDimitry Andric   ctx.symtab.resolveRemainingUndefines();
229485868e8aSDimitry Andric   if (errorCount())
229585868e8aSDimitry Andric     return;
229685868e8aSDimitry Andric 
22970b57cec5SDimitry Andric   if (config->mingw) {
22980b57cec5SDimitry Andric     // Make sure the crtend.o object is the last object file. This object
22990b57cec5SDimitry Andric     // file can contain terminating section chunks that need to be placed
23000b57cec5SDimitry Andric     // last. GNU ld processes files and static libraries explicitly in the
23010b57cec5SDimitry Andric     // order provided on the command line, while lld will pull in needed
23020b57cec5SDimitry Andric     // files from static libraries only after the last object file on the
23030b57cec5SDimitry Andric     // command line.
2304349cc55cSDimitry Andric     for (auto i = ctx.objFileInstances.begin(), e = ctx.objFileInstances.end();
23050b57cec5SDimitry Andric          i != e; i++) {
23060b57cec5SDimitry Andric       ObjFile *file = *i;
23070b57cec5SDimitry Andric       if (isCrtend(file->getName())) {
2308349cc55cSDimitry Andric         ctx.objFileInstances.erase(i);
2309349cc55cSDimitry Andric         ctx.objFileInstances.push_back(file);
23100b57cec5SDimitry Andric         break;
23110b57cec5SDimitry Andric       }
23120b57cec5SDimitry Andric     }
23130b57cec5SDimitry Andric   }
23140b57cec5SDimitry Andric 
23150b57cec5SDimitry Andric   // Windows specific -- when we are creating a .dll file, we also
231685868e8aSDimitry Andric   // need to create a .lib file. In MinGW mode, we only do that when the
231785868e8aSDimitry Andric   // -implib option is given explicitly, for compatibility with GNU ld.
23180b57cec5SDimitry Andric   if (!config->exports.empty() || config->dll) {
23190b57cec5SDimitry Andric     fixupExports();
232081ad6265SDimitry Andric     if (!config->noimplib && (!config->mingw || !config->implib.empty()))
23210b57cec5SDimitry Andric       createImportLibrary(/*asLib=*/false);
23220b57cec5SDimitry Andric     assignExportOrdinals();
23230b57cec5SDimitry Andric   }
23240b57cec5SDimitry Andric 
23250b57cec5SDimitry Andric   // Handle /output-def (MinGW specific).
23260b57cec5SDimitry Andric   if (auto *arg = args.getLastArg(OPT_output_def))
23270b57cec5SDimitry Andric     writeDefFile(arg->getValue());
23280b57cec5SDimitry Andric 
23290b57cec5SDimitry Andric   // Set extra alignment for .comm symbols
23300b57cec5SDimitry Andric   for (auto pair : config->alignComm) {
23310b57cec5SDimitry Andric     StringRef name = pair.first;
23320b57cec5SDimitry Andric     uint32_t alignment = pair.second;
23330b57cec5SDimitry Andric 
2334349cc55cSDimitry Andric     Symbol *sym = ctx.symtab.find(name);
23350b57cec5SDimitry Andric     if (!sym) {
23360b57cec5SDimitry Andric       warn("/aligncomm symbol " + name + " not found");
23370b57cec5SDimitry Andric       continue;
23380b57cec5SDimitry Andric     }
23390b57cec5SDimitry Andric 
23400b57cec5SDimitry Andric     // If the symbol isn't common, it must have been replaced with a regular
23410b57cec5SDimitry Andric     // symbol, which will carry its own alignment.
23420b57cec5SDimitry Andric     auto *dc = dyn_cast<DefinedCommon>(sym);
23430b57cec5SDimitry Andric     if (!dc)
23440b57cec5SDimitry Andric       continue;
23450b57cec5SDimitry Andric 
23460b57cec5SDimitry Andric     CommonChunk *c = dc->getChunk();
23470b57cec5SDimitry Andric     c->setAlignment(std::max(c->getAlignment(), alignment));
23480b57cec5SDimitry Andric   }
23490b57cec5SDimitry Andric 
2350349cc55cSDimitry Andric   // Windows specific -- Create an embedded or side-by-side manifest.
2351349cc55cSDimitry Andric   // /manifestdependency: enables /manifest unless an explicit /manifest:no is
2352349cc55cSDimitry Andric   // also passed.
2353349cc55cSDimitry Andric   if (config->manifest == Configuration::Embed)
2354349cc55cSDimitry Andric     addBuffer(createManifestRes(), false, false);
2355349cc55cSDimitry Andric   else if (config->manifest == Configuration::SideBySide ||
2356349cc55cSDimitry Andric            (config->manifest == Configuration::Default &&
2357349cc55cSDimitry Andric             !config->manifestDependencies.empty()))
23580b57cec5SDimitry Andric     createSideBySideManifest();
23590b57cec5SDimitry Andric 
23600b57cec5SDimitry Andric   // Handle /order. We want to do this at this moment because we
23610b57cec5SDimitry Andric   // need a complete list of comdat sections to warn on nonexistent
23620b57cec5SDimitry Andric   // functions.
2363e8d8bef9SDimitry Andric   if (auto *arg = args.getLastArg(OPT_order)) {
2364e8d8bef9SDimitry Andric     if (args.hasArg(OPT_call_graph_ordering_file))
2365e8d8bef9SDimitry Andric       error("/order and /call-graph-order-file may not be used together");
2366349cc55cSDimitry Andric     parseOrderFile(ctx, arg->getValue());
2367e8d8bef9SDimitry Andric     config->callGraphProfileSort = false;
2368e8d8bef9SDimitry Andric   }
2369e8d8bef9SDimitry Andric 
2370e8d8bef9SDimitry Andric   // Handle /call-graph-ordering-file and /call-graph-profile-sort (default on).
2371e8d8bef9SDimitry Andric   if (config->callGraphProfileSort) {
2372e8d8bef9SDimitry Andric     if (auto *arg = args.getLastArg(OPT_call_graph_ordering_file)) {
2373349cc55cSDimitry Andric       parseCallGraphFile(ctx, arg->getValue());
2374e8d8bef9SDimitry Andric     }
2375349cc55cSDimitry Andric     readCallGraphsFromObjectFiles(ctx);
2376e8d8bef9SDimitry Andric   }
2377e8d8bef9SDimitry Andric 
2378e8d8bef9SDimitry Andric   // Handle /print-symbol-order.
2379e8d8bef9SDimitry Andric   if (auto *arg = args.getLastArg(OPT_print_symbol_order))
2380e8d8bef9SDimitry Andric     config->printSymbolOrder = arg->getValue();
23810b57cec5SDimitry Andric 
23820b57cec5SDimitry Andric   // Identify unreferenced COMDAT sections.
2383fe6060f1SDimitry Andric   if (config->doGC) {
2384fe6060f1SDimitry Andric     if (config->mingw) {
2385fe6060f1SDimitry Andric       // markLive doesn't traverse .eh_frame, but the personality function is
2386fe6060f1SDimitry Andric       // only reached that way. The proper solution would be to parse and
2387fe6060f1SDimitry Andric       // traverse the .eh_frame section, like the ELF linker does.
2388fe6060f1SDimitry Andric       // For now, just manually try to retain the known possible personality
2389fe6060f1SDimitry Andric       // functions. This doesn't bring in more object files, but only marks
2390fe6060f1SDimitry Andric       // functions that already have been included to be retained.
2391fe6060f1SDimitry Andric       for (const char *n : {"__gxx_personality_v0", "__gcc_personality_v0"}) {
2392349cc55cSDimitry Andric         Defined *d = dyn_cast_or_null<Defined>(ctx.symtab.findUnderscore(n));
2393fe6060f1SDimitry Andric         if (d && !d->isGCRoot) {
2394fe6060f1SDimitry Andric           d->isGCRoot = true;
2395fe6060f1SDimitry Andric           config->gcroot.push_back(d);
2396fe6060f1SDimitry Andric         }
2397fe6060f1SDimitry Andric       }
2398fe6060f1SDimitry Andric     }
2399fe6060f1SDimitry Andric 
2400349cc55cSDimitry Andric     markLive(ctx);
2401fe6060f1SDimitry Andric   }
24020b57cec5SDimitry Andric 
24030b57cec5SDimitry Andric   // Needs to happen after the last call to addFile().
240485868e8aSDimitry Andric   convertResources();
24050b57cec5SDimitry Andric 
24060b57cec5SDimitry Andric   // Identify identical COMDAT sections to merge them.
2407fe6060f1SDimitry Andric   if (config->doICF != ICFLevel::None) {
2408349cc55cSDimitry Andric     findKeepUniqueSections(ctx);
2409349cc55cSDimitry Andric     doICF(ctx, config->doICF);
24100b57cec5SDimitry Andric   }
24110b57cec5SDimitry Andric 
24120b57cec5SDimitry Andric   // Write the result.
2413349cc55cSDimitry Andric   writeResult(ctx);
24140b57cec5SDimitry Andric 
24150b57cec5SDimitry Andric   // Stop early so we can print the results.
24165ffd83dbSDimitry Andric   rootTimer.stop();
24170b57cec5SDimitry Andric   if (config->showTiming)
2418349cc55cSDimitry Andric     ctx.rootTimer.print();
24190b57cec5SDimitry Andric }
24200b57cec5SDimitry Andric 
24210b57cec5SDimitry Andric } // namespace coff
24220b57cec5SDimitry Andric } // namespace lld
2423