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" 25*81ad6265SDimitry Andric #include "llvm/ADT/IntrusiveRefCntPtr.h" 260b57cec5SDimitry Andric #include "llvm/ADT/Optional.h" 270b57cec5SDimitry Andric #include "llvm/ADT/StringSwitch.h" 28*81ad6265SDimitry 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" 49*81ad6265SDimitry 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 156*81ad6265SDimitry Andric static llvm::Triple::ArchType getArch() { 157*81ad6265SDimitry Andric switch (config->machine) { 158*81ad6265SDimitry Andric case I386: 159*81ad6265SDimitry Andric return llvm::Triple::ArchType::x86; 160*81ad6265SDimitry Andric case AMD64: 161*81ad6265SDimitry Andric return llvm::Triple::ArchType::x86_64; 162*81ad6265SDimitry Andric case ARMNT: 163*81ad6265SDimitry Andric return llvm::Triple::ArchType::arm; 164*81ad6265SDimitry Andric case ARM64: 165*81ad6265SDimitry Andric return llvm::Triple::ArchType::aarch64; 166*81ad6265SDimitry Andric default: 167*81ad6265SDimitry Andric return llvm::Triple::ArchType::UnknownArch; 168*81ad6265SDimitry Andric } 169*81ad6265SDimitry Andric } 170*81ad6265SDimitry 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) { 4390b57cec5SDimitry Andric bool hasPathSep = (filename.find_first_of("/\\") != StringRef::npos); 4400b57cec5SDimitry Andric if (hasPathSep) 4410b57cec5SDimitry Andric return filename; 4420b57cec5SDimitry Andric bool hasExt = filename.contains('.'); 4430b57cec5SDimitry Andric for (StringRef dir : searchPaths) { 4440b57cec5SDimitry Andric SmallString<128> path = dir; 4450b57cec5SDimitry Andric sys::path::append(path, filename); 4460b57cec5SDimitry Andric if (sys::fs::exists(path.str())) 44704eeddc0SDimitry Andric return saver().save(path.str()); 4480b57cec5SDimitry Andric if (!hasExt) { 4490b57cec5SDimitry Andric path.append(".obj"); 4500b57cec5SDimitry Andric if (sys::fs::exists(path.str())) 45104eeddc0SDimitry Andric return saver().save(path.str()); 4520b57cec5SDimitry Andric } 4530b57cec5SDimitry Andric } 4540b57cec5SDimitry Andric return filename; 4550b57cec5SDimitry Andric } 4560b57cec5SDimitry Andric 4570b57cec5SDimitry Andric static Optional<sys::fs::UniqueID> getUniqueID(StringRef path) { 4580b57cec5SDimitry Andric sys::fs::UniqueID ret; 4590b57cec5SDimitry Andric if (sys::fs::getUniqueID(path, ret)) 4600b57cec5SDimitry Andric return None; 4610b57cec5SDimitry Andric return ret; 4620b57cec5SDimitry Andric } 4630b57cec5SDimitry Andric 4640b57cec5SDimitry Andric // Resolves a file path. This never returns the same path 4650b57cec5SDimitry Andric // (in that case, it returns None). 4660b57cec5SDimitry Andric Optional<StringRef> LinkerDriver::findFile(StringRef filename) { 4670b57cec5SDimitry Andric StringRef path = doFindFile(filename); 4680b57cec5SDimitry Andric 4690b57cec5SDimitry Andric if (Optional<sys::fs::UniqueID> id = getUniqueID(path)) { 4700b57cec5SDimitry Andric bool seen = !visitedFiles.insert(*id).second; 4710b57cec5SDimitry Andric if (seen) 4720b57cec5SDimitry Andric return None; 4730b57cec5SDimitry Andric } 4740b57cec5SDimitry Andric 475fe6060f1SDimitry Andric if (path.endswith_insensitive(".lib")) 476*81ad6265SDimitry Andric visitedLibs.insert(std::string(sys::path::filename(path).lower())); 4770b57cec5SDimitry Andric return path; 4780b57cec5SDimitry Andric } 4790b57cec5SDimitry Andric 4800b57cec5SDimitry Andric // MinGW specific. If an embedded directive specified to link to 4810b57cec5SDimitry Andric // foo.lib, but it isn't found, try libfoo.a instead. 4820b57cec5SDimitry Andric StringRef LinkerDriver::doFindLibMinGW(StringRef filename) { 4830b57cec5SDimitry Andric if (filename.contains('/') || filename.contains('\\')) 4840b57cec5SDimitry Andric return filename; 4850b57cec5SDimitry Andric 4860b57cec5SDimitry Andric SmallString<128> s = filename; 4870b57cec5SDimitry Andric sys::path::replace_extension(s, ".a"); 48804eeddc0SDimitry Andric StringRef libName = saver().save("lib" + s.str()); 4890b57cec5SDimitry Andric return doFindFile(libName); 4900b57cec5SDimitry Andric } 4910b57cec5SDimitry Andric 4920b57cec5SDimitry Andric // Find library file from search path. 4930b57cec5SDimitry Andric StringRef LinkerDriver::doFindLib(StringRef filename) { 4940b57cec5SDimitry Andric // Add ".lib" to Filename if that has no file extension. 4950b57cec5SDimitry Andric bool hasExt = filename.contains('.'); 4960b57cec5SDimitry Andric if (!hasExt) 49704eeddc0SDimitry Andric filename = saver().save(filename + ".lib"); 4980b57cec5SDimitry Andric StringRef ret = doFindFile(filename); 4990b57cec5SDimitry Andric // For MinGW, if the find above didn't turn up anything, try 5000b57cec5SDimitry Andric // looking for a MinGW formatted library name. 5010b57cec5SDimitry Andric if (config->mingw && ret == filename) 5020b57cec5SDimitry Andric return doFindLibMinGW(filename); 5030b57cec5SDimitry Andric return ret; 5040b57cec5SDimitry Andric } 5050b57cec5SDimitry Andric 5060b57cec5SDimitry Andric // Resolves a library path. /nodefaultlib options are taken into 5070b57cec5SDimitry Andric // consideration. This never returns the same path (in that case, 5080b57cec5SDimitry Andric // it returns None). 5090b57cec5SDimitry Andric Optional<StringRef> LinkerDriver::findLib(StringRef filename) { 5100b57cec5SDimitry Andric if (config->noDefaultLibAll) 5110b57cec5SDimitry Andric return None; 5120b57cec5SDimitry Andric if (!visitedLibs.insert(filename.lower()).second) 5130b57cec5SDimitry Andric return None; 5140b57cec5SDimitry Andric 5150b57cec5SDimitry Andric StringRef path = doFindLib(filename); 5160b57cec5SDimitry Andric if (config->noDefaultLibs.count(path.lower())) 5170b57cec5SDimitry Andric return None; 5180b57cec5SDimitry Andric 5190b57cec5SDimitry Andric if (Optional<sys::fs::UniqueID> id = getUniqueID(path)) 5200b57cec5SDimitry Andric if (!visitedFiles.insert(*id).second) 5210b57cec5SDimitry Andric return None; 5220b57cec5SDimitry Andric return path; 5230b57cec5SDimitry Andric } 5240b57cec5SDimitry Andric 525*81ad6265SDimitry Andric void LinkerDriver::detectWinSysRoot(const opt::InputArgList &Args) { 526*81ad6265SDimitry Andric IntrusiveRefCntPtr<vfs::FileSystem> VFS = vfs::getRealFileSystem(); 527*81ad6265SDimitry Andric 528*81ad6265SDimitry Andric // Check the command line first, that's the user explicitly telling us what to 529*81ad6265SDimitry Andric // use. Check the environment next, in case we're being invoked from a VS 530*81ad6265SDimitry Andric // command prompt. Failing that, just try to find the newest Visual Studio 531*81ad6265SDimitry Andric // version we can and use its default VC toolchain. 532*81ad6265SDimitry Andric Optional<StringRef> VCToolsDir, VCToolsVersion, WinSysRoot; 533*81ad6265SDimitry Andric if (auto *A = Args.getLastArg(OPT_vctoolsdir)) 534*81ad6265SDimitry Andric VCToolsDir = A->getValue(); 535*81ad6265SDimitry Andric if (auto *A = Args.getLastArg(OPT_vctoolsversion)) 536*81ad6265SDimitry Andric VCToolsVersion = A->getValue(); 537*81ad6265SDimitry Andric if (auto *A = Args.getLastArg(OPT_winsysroot)) 538*81ad6265SDimitry Andric WinSysRoot = A->getValue(); 539*81ad6265SDimitry Andric if (!findVCToolChainViaCommandLine(*VFS, VCToolsDir, VCToolsVersion, 540*81ad6265SDimitry Andric WinSysRoot, vcToolChainPath, vsLayout) && 541*81ad6265SDimitry Andric (Args.hasArg(OPT_lldignoreenv) || 542*81ad6265SDimitry Andric !findVCToolChainViaEnvironment(*VFS, vcToolChainPath, vsLayout)) && 543*81ad6265SDimitry Andric !findVCToolChainViaSetupConfig(*VFS, vcToolChainPath, vsLayout) && 544*81ad6265SDimitry Andric !findVCToolChainViaRegistry(vcToolChainPath, vsLayout)) 545*81ad6265SDimitry Andric return; 546*81ad6265SDimitry Andric 547*81ad6265SDimitry Andric // If the VC environment hasn't been configured (perhaps because the user did 548*81ad6265SDimitry Andric // not run vcvarsall), try to build a consistent link environment. If the 549*81ad6265SDimitry Andric // environment variable is set however, assume the user knows what they're 550*81ad6265SDimitry Andric // doing. If the user passes /vctoolsdir or /winsdkdir, trust that over env 551*81ad6265SDimitry Andric // vars. 552*81ad6265SDimitry Andric if (const auto *A = Args.getLastArg(OPT_diasdkdir, OPT_winsysroot)) { 553*81ad6265SDimitry Andric diaPath = A->getValue(); 554*81ad6265SDimitry Andric if (A->getOption().getID() == OPT_winsysroot) 555*81ad6265SDimitry Andric path::append(diaPath, "DIA SDK"); 556*81ad6265SDimitry Andric } 557*81ad6265SDimitry Andric useWinSysRootLibPath = Args.hasArg(OPT_lldignoreenv) || 558*81ad6265SDimitry Andric !Process::GetEnv("LIB") || 559*81ad6265SDimitry Andric Args.getLastArg(OPT_vctoolsdir, OPT_winsysroot); 560*81ad6265SDimitry Andric if (Args.hasArg(OPT_lldignoreenv) || !Process::GetEnv("LIB") || 561*81ad6265SDimitry Andric Args.getLastArg(OPT_winsdkdir, OPT_winsysroot)) { 562*81ad6265SDimitry Andric Optional<StringRef> WinSdkDir, WinSdkVersion; 563*81ad6265SDimitry Andric if (auto *A = Args.getLastArg(OPT_winsdkdir)) 564*81ad6265SDimitry Andric WinSdkDir = A->getValue(); 565*81ad6265SDimitry Andric if (auto *A = Args.getLastArg(OPT_winsdkversion)) 566*81ad6265SDimitry Andric WinSdkVersion = A->getValue(); 567*81ad6265SDimitry Andric 568*81ad6265SDimitry Andric if (useUniversalCRT(vsLayout, vcToolChainPath, getArch(), *VFS)) { 569*81ad6265SDimitry Andric std::string UniversalCRTSdkPath; 570*81ad6265SDimitry Andric std::string UCRTVersion; 571*81ad6265SDimitry Andric if (getUniversalCRTSdkDir(*VFS, WinSdkDir, WinSdkVersion, WinSysRoot, 572*81ad6265SDimitry Andric UniversalCRTSdkPath, UCRTVersion)) { 573*81ad6265SDimitry Andric universalCRTLibPath = UniversalCRTSdkPath; 574*81ad6265SDimitry Andric path::append(universalCRTLibPath, "Lib", UCRTVersion, "ucrt"); 575*81ad6265SDimitry Andric } 576*81ad6265SDimitry Andric } 577*81ad6265SDimitry Andric 578*81ad6265SDimitry Andric std::string sdkPath; 579*81ad6265SDimitry Andric std::string windowsSDKIncludeVersion; 580*81ad6265SDimitry Andric std::string windowsSDKLibVersion; 581*81ad6265SDimitry Andric if (getWindowsSDKDir(*VFS, WinSdkDir, WinSdkVersion, WinSysRoot, sdkPath, 582*81ad6265SDimitry Andric sdkMajor, windowsSDKIncludeVersion, 583*81ad6265SDimitry Andric windowsSDKLibVersion)) { 584*81ad6265SDimitry Andric windowsSdkLibPath = sdkPath; 585*81ad6265SDimitry Andric path::append(windowsSdkLibPath, "Lib"); 586*81ad6265SDimitry Andric if (sdkMajor >= 8) 587*81ad6265SDimitry Andric path::append(windowsSdkLibPath, windowsSDKLibVersion, "um"); 588*81ad6265SDimitry Andric } 589*81ad6265SDimitry Andric } 590*81ad6265SDimitry Andric } 591*81ad6265SDimitry Andric 592*81ad6265SDimitry Andric void LinkerDriver::addWinSysRootLibSearchPaths() { 593*81ad6265SDimitry Andric if (!diaPath.empty()) { 594*81ad6265SDimitry Andric // The DIA SDK always uses the legacy vc arch, even in new MSVC versions. 595*81ad6265SDimitry Andric path::append(diaPath, "lib", archToLegacyVCArch(getArch())); 596*81ad6265SDimitry Andric searchPaths.push_back(saver().save(diaPath.str())); 597*81ad6265SDimitry Andric } 598*81ad6265SDimitry Andric if (useWinSysRootLibPath) { 599*81ad6265SDimitry Andric searchPaths.push_back(saver().save(getSubDirectoryPath( 600*81ad6265SDimitry Andric SubDirectoryType::Lib, vsLayout, vcToolChainPath, getArch()))); 601*81ad6265SDimitry Andric searchPaths.push_back(saver().save( 602*81ad6265SDimitry Andric getSubDirectoryPath(SubDirectoryType::Lib, vsLayout, vcToolChainPath, 603*81ad6265SDimitry Andric getArch(), "atlmfc"))); 604*81ad6265SDimitry Andric } 605*81ad6265SDimitry Andric if (!universalCRTLibPath.empty()) { 606*81ad6265SDimitry Andric StringRef ArchName = archToWindowsSDKArch(getArch()); 607*81ad6265SDimitry Andric if (!ArchName.empty()) { 608*81ad6265SDimitry Andric path::append(universalCRTLibPath, ArchName); 609*81ad6265SDimitry Andric searchPaths.push_back(saver().save(universalCRTLibPath.str())); 610*81ad6265SDimitry Andric } 611*81ad6265SDimitry Andric } 612*81ad6265SDimitry Andric if (!windowsSdkLibPath.empty()) { 613*81ad6265SDimitry Andric std::string path; 614*81ad6265SDimitry Andric if (appendArchToWindowsSDKLibPath(sdkMajor, windowsSdkLibPath, getArch(), 615*81ad6265SDimitry Andric path)) 616*81ad6265SDimitry Andric searchPaths.push_back(saver().save(path)); 617*81ad6265SDimitry Andric } 618*81ad6265SDimitry Andric } 619*81ad6265SDimitry Andric 6200b57cec5SDimitry Andric // Parses LIB environment which contains a list of search paths. 6210b57cec5SDimitry Andric void LinkerDriver::addLibSearchPaths() { 6220b57cec5SDimitry Andric Optional<std::string> envOpt = Process::GetEnv("LIB"); 623*81ad6265SDimitry Andric if (!envOpt) 6240b57cec5SDimitry Andric return; 62504eeddc0SDimitry Andric StringRef env = saver().save(*envOpt); 6260b57cec5SDimitry Andric while (!env.empty()) { 6270b57cec5SDimitry Andric StringRef path; 6280b57cec5SDimitry Andric std::tie(path, env) = env.split(';'); 6290b57cec5SDimitry Andric searchPaths.push_back(path); 6300b57cec5SDimitry Andric } 6310b57cec5SDimitry Andric } 6320b57cec5SDimitry Andric 6330b57cec5SDimitry Andric Symbol *LinkerDriver::addUndefined(StringRef name) { 634349cc55cSDimitry Andric Symbol *b = ctx.symtab.addUndefined(name); 6350b57cec5SDimitry Andric if (!b->isGCRoot) { 6360b57cec5SDimitry Andric b->isGCRoot = true; 6370b57cec5SDimitry Andric config->gcroot.push_back(b); 6380b57cec5SDimitry Andric } 6390b57cec5SDimitry Andric return b; 6400b57cec5SDimitry Andric } 6410b57cec5SDimitry Andric 6420b57cec5SDimitry Andric StringRef LinkerDriver::mangleMaybe(Symbol *s) { 6430b57cec5SDimitry Andric // If the plain symbol name has already been resolved, do nothing. 6440b57cec5SDimitry Andric Undefined *unmangled = dyn_cast<Undefined>(s); 6450b57cec5SDimitry Andric if (!unmangled) 6460b57cec5SDimitry Andric return ""; 6470b57cec5SDimitry Andric 6480b57cec5SDimitry Andric // Otherwise, see if a similar, mangled symbol exists in the symbol table. 649349cc55cSDimitry Andric Symbol *mangled = ctx.symtab.findMangle(unmangled->getName()); 6500b57cec5SDimitry Andric if (!mangled) 6510b57cec5SDimitry Andric return ""; 6520b57cec5SDimitry Andric 6530b57cec5SDimitry Andric // If we find a similar mangled symbol, make this an alias to it and return 6540b57cec5SDimitry Andric // its name. 6550b57cec5SDimitry Andric log(unmangled->getName() + " aliased to " + mangled->getName()); 656349cc55cSDimitry Andric unmangled->weakAlias = ctx.symtab.addUndefined(mangled->getName()); 6570b57cec5SDimitry Andric return mangled->getName(); 6580b57cec5SDimitry Andric } 6590b57cec5SDimitry Andric 6600b57cec5SDimitry Andric // Windows specific -- find default entry point name. 6610b57cec5SDimitry Andric // 6620b57cec5SDimitry Andric // There are four different entry point functions for Windows executables, 6630b57cec5SDimitry Andric // each of which corresponds to a user-defined "main" function. This function 6640b57cec5SDimitry Andric // infers an entry point from a user-defined "main" function. 6650b57cec5SDimitry Andric StringRef LinkerDriver::findDefaultEntry() { 6660b57cec5SDimitry Andric assert(config->subsystem != IMAGE_SUBSYSTEM_UNKNOWN && 6670b57cec5SDimitry Andric "must handle /subsystem before calling this"); 6680b57cec5SDimitry Andric 6690b57cec5SDimitry Andric if (config->mingw) 6700b57cec5SDimitry Andric return mangle(config->subsystem == IMAGE_SUBSYSTEM_WINDOWS_GUI 6710b57cec5SDimitry Andric ? "WinMainCRTStartup" 6720b57cec5SDimitry Andric : "mainCRTStartup"); 6730b57cec5SDimitry Andric 6740b57cec5SDimitry Andric if (config->subsystem == IMAGE_SUBSYSTEM_WINDOWS_GUI) { 6750b57cec5SDimitry Andric if (findUnderscoreMangle("wWinMain")) { 6760b57cec5SDimitry Andric if (!findUnderscoreMangle("WinMain")) 6770b57cec5SDimitry Andric return mangle("wWinMainCRTStartup"); 6780b57cec5SDimitry Andric warn("found both wWinMain and WinMain; using latter"); 6790b57cec5SDimitry Andric } 6800b57cec5SDimitry Andric return mangle("WinMainCRTStartup"); 6810b57cec5SDimitry Andric } 6820b57cec5SDimitry Andric if (findUnderscoreMangle("wmain")) { 6830b57cec5SDimitry Andric if (!findUnderscoreMangle("main")) 6840b57cec5SDimitry Andric return mangle("wmainCRTStartup"); 6850b57cec5SDimitry Andric warn("found both wmain and main; using latter"); 6860b57cec5SDimitry Andric } 6870b57cec5SDimitry Andric return mangle("mainCRTStartup"); 6880b57cec5SDimitry Andric } 6890b57cec5SDimitry Andric 6900b57cec5SDimitry Andric WindowsSubsystem LinkerDriver::inferSubsystem() { 6910b57cec5SDimitry Andric if (config->dll) 6920b57cec5SDimitry Andric return IMAGE_SUBSYSTEM_WINDOWS_GUI; 6930b57cec5SDimitry Andric if (config->mingw) 6940b57cec5SDimitry Andric return IMAGE_SUBSYSTEM_WINDOWS_CUI; 6950b57cec5SDimitry Andric // Note that link.exe infers the subsystem from the presence of these 6960b57cec5SDimitry Andric // functions even if /entry: or /nodefaultlib are passed which causes them 6970b57cec5SDimitry Andric // to not be called. 6980b57cec5SDimitry Andric bool haveMain = findUnderscoreMangle("main"); 6990b57cec5SDimitry Andric bool haveWMain = findUnderscoreMangle("wmain"); 7000b57cec5SDimitry Andric bool haveWinMain = findUnderscoreMangle("WinMain"); 7010b57cec5SDimitry Andric bool haveWWinMain = findUnderscoreMangle("wWinMain"); 7020b57cec5SDimitry Andric if (haveMain || haveWMain) { 7030b57cec5SDimitry Andric if (haveWinMain || haveWWinMain) { 7040b57cec5SDimitry Andric warn(std::string("found ") + (haveMain ? "main" : "wmain") + " and " + 7050b57cec5SDimitry Andric (haveWinMain ? "WinMain" : "wWinMain") + 7060b57cec5SDimitry Andric "; defaulting to /subsystem:console"); 7070b57cec5SDimitry Andric } 7080b57cec5SDimitry Andric return IMAGE_SUBSYSTEM_WINDOWS_CUI; 7090b57cec5SDimitry Andric } 7100b57cec5SDimitry Andric if (haveWinMain || haveWWinMain) 7110b57cec5SDimitry Andric return IMAGE_SUBSYSTEM_WINDOWS_GUI; 7120b57cec5SDimitry Andric return IMAGE_SUBSYSTEM_UNKNOWN; 7130b57cec5SDimitry Andric } 7140b57cec5SDimitry Andric 7150b57cec5SDimitry Andric static uint64_t getDefaultImageBase() { 7160b57cec5SDimitry Andric if (config->is64()) 7170b57cec5SDimitry Andric return config->dll ? 0x180000000 : 0x140000000; 7180b57cec5SDimitry Andric return config->dll ? 0x10000000 : 0x400000; 7190b57cec5SDimitry Andric } 7200b57cec5SDimitry Andric 721fe6060f1SDimitry Andric static std::string rewritePath(StringRef s) { 722fe6060f1SDimitry Andric if (fs::exists(s)) 723fe6060f1SDimitry Andric return relativeToRoot(s); 724fe6060f1SDimitry Andric return std::string(s); 725fe6060f1SDimitry Andric } 726fe6060f1SDimitry Andric 727fe6060f1SDimitry Andric // Reconstructs command line arguments so that so that you can re-run 728fe6060f1SDimitry Andric // the same command with the same inputs. This is for --reproduce. 7290b57cec5SDimitry Andric static std::string createResponseFile(const opt::InputArgList &args, 7300b57cec5SDimitry Andric ArrayRef<StringRef> filePaths, 7310b57cec5SDimitry Andric ArrayRef<StringRef> searchPaths) { 7320b57cec5SDimitry Andric SmallString<0> data; 7330b57cec5SDimitry Andric raw_svector_ostream os(data); 7340b57cec5SDimitry Andric 7350b57cec5SDimitry Andric for (auto *arg : args) { 7360b57cec5SDimitry Andric switch (arg->getOption().getID()) { 7370b57cec5SDimitry Andric case OPT_linkrepro: 73885868e8aSDimitry Andric case OPT_reproduce: 7390b57cec5SDimitry Andric case OPT_INPUT: 7400b57cec5SDimitry Andric case OPT_defaultlib: 7410b57cec5SDimitry Andric case OPT_libpath: 742*81ad6265SDimitry Andric case OPT_winsysroot: 7430b57cec5SDimitry Andric break; 744fe6060f1SDimitry Andric case OPT_call_graph_ordering_file: 745fe6060f1SDimitry Andric case OPT_deffile: 746349cc55cSDimitry Andric case OPT_manifestinput: 747fe6060f1SDimitry Andric case OPT_natvis: 748fe6060f1SDimitry Andric os << arg->getSpelling() << quote(rewritePath(arg->getValue())) << '\n'; 749fe6060f1SDimitry Andric break; 750fe6060f1SDimitry Andric case OPT_order: { 751fe6060f1SDimitry Andric StringRef orderFile = arg->getValue(); 752fe6060f1SDimitry Andric orderFile.consume_front("@"); 753fe6060f1SDimitry Andric os << arg->getSpelling() << '@' << quote(rewritePath(orderFile)) << '\n'; 754fe6060f1SDimitry Andric break; 755fe6060f1SDimitry Andric } 756fe6060f1SDimitry Andric case OPT_pdbstream: { 757fe6060f1SDimitry Andric const std::pair<StringRef, StringRef> nameFile = 758fe6060f1SDimitry Andric StringRef(arg->getValue()).split("="); 759fe6060f1SDimitry Andric os << arg->getSpelling() << nameFile.first << '=' 760fe6060f1SDimitry Andric << quote(rewritePath(nameFile.second)) << '\n'; 761fe6060f1SDimitry Andric break; 762fe6060f1SDimitry Andric } 7630b57cec5SDimitry Andric case OPT_implib: 764349cc55cSDimitry Andric case OPT_manifestfile: 7650b57cec5SDimitry Andric case OPT_pdb: 7665ffd83dbSDimitry Andric case OPT_pdbstripped: 7670b57cec5SDimitry Andric case OPT_out: 7680b57cec5SDimitry Andric os << arg->getSpelling() << sys::path::filename(arg->getValue()) << "\n"; 7690b57cec5SDimitry Andric break; 7700b57cec5SDimitry Andric default: 7710b57cec5SDimitry Andric os << toString(*arg) << "\n"; 7720b57cec5SDimitry Andric } 7730b57cec5SDimitry Andric } 7740b57cec5SDimitry Andric 7750b57cec5SDimitry Andric for (StringRef path : searchPaths) { 7760b57cec5SDimitry Andric std::string relPath = relativeToRoot(path); 7770b57cec5SDimitry Andric os << "/libpath:" << quote(relPath) << "\n"; 7780b57cec5SDimitry Andric } 7790b57cec5SDimitry Andric 7800b57cec5SDimitry Andric for (StringRef path : filePaths) 7810b57cec5SDimitry Andric os << quote(relativeToRoot(path)) << "\n"; 7820b57cec5SDimitry Andric 7835ffd83dbSDimitry Andric return std::string(data.str()); 7840b57cec5SDimitry Andric } 7850b57cec5SDimitry Andric 786fe6060f1SDimitry Andric enum class DebugKind { 787fe6060f1SDimitry Andric Unknown, 788fe6060f1SDimitry Andric None, 789fe6060f1SDimitry Andric Full, 790fe6060f1SDimitry Andric FastLink, 791fe6060f1SDimitry Andric GHash, 792fe6060f1SDimitry Andric NoGHash, 793fe6060f1SDimitry Andric Dwarf, 794fe6060f1SDimitry Andric Symtab 795fe6060f1SDimitry Andric }; 7960b57cec5SDimitry Andric 7970b57cec5SDimitry Andric static DebugKind parseDebugKind(const opt::InputArgList &args) { 7980b57cec5SDimitry Andric auto *a = args.getLastArg(OPT_debug, OPT_debug_opt); 7990b57cec5SDimitry Andric if (!a) 8000b57cec5SDimitry Andric return DebugKind::None; 8010b57cec5SDimitry Andric if (a->getNumValues() == 0) 8020b57cec5SDimitry Andric return DebugKind::Full; 8030b57cec5SDimitry Andric 8040b57cec5SDimitry Andric DebugKind debug = StringSwitch<DebugKind>(a->getValue()) 8050b57cec5SDimitry Andric .CaseLower("none", DebugKind::None) 8060b57cec5SDimitry Andric .CaseLower("full", DebugKind::Full) 8070b57cec5SDimitry Andric .CaseLower("fastlink", DebugKind::FastLink) 8080b57cec5SDimitry Andric // LLD extensions 8090b57cec5SDimitry Andric .CaseLower("ghash", DebugKind::GHash) 810fe6060f1SDimitry Andric .CaseLower("noghash", DebugKind::NoGHash) 8110b57cec5SDimitry Andric .CaseLower("dwarf", DebugKind::Dwarf) 8120b57cec5SDimitry Andric .CaseLower("symtab", DebugKind::Symtab) 8130b57cec5SDimitry Andric .Default(DebugKind::Unknown); 8140b57cec5SDimitry Andric 8150b57cec5SDimitry Andric if (debug == DebugKind::FastLink) { 8160b57cec5SDimitry Andric warn("/debug:fastlink unsupported; using /debug:full"); 8170b57cec5SDimitry Andric return DebugKind::Full; 8180b57cec5SDimitry Andric } 8190b57cec5SDimitry Andric if (debug == DebugKind::Unknown) { 8200b57cec5SDimitry Andric error("/debug: unknown option: " + Twine(a->getValue())); 8210b57cec5SDimitry Andric return DebugKind::None; 8220b57cec5SDimitry Andric } 8230b57cec5SDimitry Andric return debug; 8240b57cec5SDimitry Andric } 8250b57cec5SDimitry Andric 8260b57cec5SDimitry Andric static unsigned parseDebugTypes(const opt::InputArgList &args) { 8270b57cec5SDimitry Andric unsigned debugTypes = static_cast<unsigned>(DebugType::None); 8280b57cec5SDimitry Andric 8290b57cec5SDimitry Andric if (auto *a = args.getLastArg(OPT_debugtype)) { 8300b57cec5SDimitry Andric SmallVector<StringRef, 3> types; 8310b57cec5SDimitry Andric StringRef(a->getValue()) 8320b57cec5SDimitry Andric .split(types, ',', /*MaxSplit=*/-1, /*KeepEmpty=*/false); 8330b57cec5SDimitry Andric 8340b57cec5SDimitry Andric for (StringRef type : types) { 8350b57cec5SDimitry Andric unsigned v = StringSwitch<unsigned>(type.lower()) 8360b57cec5SDimitry Andric .Case("cv", static_cast<unsigned>(DebugType::CV)) 8370b57cec5SDimitry Andric .Case("pdata", static_cast<unsigned>(DebugType::PData)) 8380b57cec5SDimitry Andric .Case("fixup", static_cast<unsigned>(DebugType::Fixup)) 8390b57cec5SDimitry Andric .Default(0); 8400b57cec5SDimitry Andric if (v == 0) { 8410b57cec5SDimitry Andric warn("/debugtype: unknown option '" + type + "'"); 8420b57cec5SDimitry Andric continue; 8430b57cec5SDimitry Andric } 8440b57cec5SDimitry Andric debugTypes |= v; 8450b57cec5SDimitry Andric } 8460b57cec5SDimitry Andric return debugTypes; 8470b57cec5SDimitry Andric } 8480b57cec5SDimitry Andric 8490b57cec5SDimitry Andric // Default debug types 8500b57cec5SDimitry Andric debugTypes = static_cast<unsigned>(DebugType::CV); 8510b57cec5SDimitry Andric if (args.hasArg(OPT_driver)) 8520b57cec5SDimitry Andric debugTypes |= static_cast<unsigned>(DebugType::PData); 8530b57cec5SDimitry Andric if (args.hasArg(OPT_profile)) 8540b57cec5SDimitry Andric debugTypes |= static_cast<unsigned>(DebugType::Fixup); 8550b57cec5SDimitry Andric 8560b57cec5SDimitry Andric return debugTypes; 8570b57cec5SDimitry Andric } 8580b57cec5SDimitry Andric 8595ffd83dbSDimitry Andric static std::string getMapFile(const opt::InputArgList &args, 8605ffd83dbSDimitry Andric opt::OptSpecifier os, opt::OptSpecifier osFile) { 8615ffd83dbSDimitry Andric auto *arg = args.getLastArg(os, osFile); 8620b57cec5SDimitry Andric if (!arg) 8630b57cec5SDimitry Andric return ""; 8645ffd83dbSDimitry Andric if (arg->getOption().getID() == osFile.getID()) 8650b57cec5SDimitry Andric return arg->getValue(); 8660b57cec5SDimitry Andric 8675ffd83dbSDimitry Andric assert(arg->getOption().getID() == os.getID()); 8680b57cec5SDimitry Andric StringRef outFile = config->outputFile; 8690b57cec5SDimitry Andric return (outFile.substr(0, outFile.rfind('.')) + ".map").str(); 8700b57cec5SDimitry Andric } 8710b57cec5SDimitry Andric 8720b57cec5SDimitry Andric static std::string getImplibPath() { 8730b57cec5SDimitry Andric if (!config->implib.empty()) 8745ffd83dbSDimitry Andric return std::string(config->implib); 8750b57cec5SDimitry Andric SmallString<128> out = StringRef(config->outputFile); 8760b57cec5SDimitry Andric sys::path::replace_extension(out, ".lib"); 8775ffd83dbSDimitry Andric return std::string(out.str()); 8780b57cec5SDimitry Andric } 8790b57cec5SDimitry Andric 88085868e8aSDimitry Andric // The import name is calculated as follows: 8810b57cec5SDimitry Andric // 8820b57cec5SDimitry Andric // | LIBRARY w/ ext | LIBRARY w/o ext | no LIBRARY 8830b57cec5SDimitry Andric // -----+----------------+---------------------+------------------ 8840b57cec5SDimitry Andric // LINK | {value} | {value}.{.dll/.exe} | {output name} 8850b57cec5SDimitry Andric // LIB | {value} | {value}.dll | {output name}.dll 8860b57cec5SDimitry Andric // 8870b57cec5SDimitry Andric static std::string getImportName(bool asLib) { 8880b57cec5SDimitry Andric SmallString<128> out; 8890b57cec5SDimitry Andric 8900b57cec5SDimitry Andric if (config->importName.empty()) { 8910b57cec5SDimitry Andric out.assign(sys::path::filename(config->outputFile)); 8920b57cec5SDimitry Andric if (asLib) 8930b57cec5SDimitry Andric sys::path::replace_extension(out, ".dll"); 8940b57cec5SDimitry Andric } else { 8950b57cec5SDimitry Andric out.assign(config->importName); 8960b57cec5SDimitry Andric if (!sys::path::has_extension(out)) 8970b57cec5SDimitry Andric sys::path::replace_extension(out, 8980b57cec5SDimitry Andric (config->dll || asLib) ? ".dll" : ".exe"); 8990b57cec5SDimitry Andric } 9000b57cec5SDimitry Andric 9015ffd83dbSDimitry Andric return std::string(out.str()); 9020b57cec5SDimitry Andric } 9030b57cec5SDimitry Andric 9040b57cec5SDimitry Andric static void createImportLibrary(bool asLib) { 9050b57cec5SDimitry Andric std::vector<COFFShortExport> exports; 9060b57cec5SDimitry Andric for (Export &e1 : config->exports) { 9070b57cec5SDimitry Andric COFFShortExport e2; 9085ffd83dbSDimitry Andric e2.Name = std::string(e1.name); 9095ffd83dbSDimitry Andric e2.SymbolName = std::string(e1.symbolName); 9105ffd83dbSDimitry Andric e2.ExtName = std::string(e1.extName); 91104eeddc0SDimitry Andric e2.AliasTarget = std::string(e1.aliasTarget); 9120b57cec5SDimitry Andric e2.Ordinal = e1.ordinal; 9130b57cec5SDimitry Andric e2.Noname = e1.noname; 9140b57cec5SDimitry Andric e2.Data = e1.data; 9150b57cec5SDimitry Andric e2.Private = e1.isPrivate; 9160b57cec5SDimitry Andric e2.Constant = e1.constant; 9170b57cec5SDimitry Andric exports.push_back(e2); 9180b57cec5SDimitry Andric } 9190b57cec5SDimitry Andric 9200b57cec5SDimitry Andric std::string libName = getImportName(asLib); 9210b57cec5SDimitry Andric std::string path = getImplibPath(); 9220b57cec5SDimitry Andric 9230b57cec5SDimitry Andric if (!config->incremental) { 924349cc55cSDimitry Andric checkError(writeImportLibrary(libName, path, exports, config->machine, 9250b57cec5SDimitry Andric config->mingw)); 9260b57cec5SDimitry Andric return; 9270b57cec5SDimitry Andric } 9280b57cec5SDimitry Andric 9290b57cec5SDimitry Andric // If the import library already exists, replace it only if the contents 9300b57cec5SDimitry Andric // have changed. 9310b57cec5SDimitry Andric ErrorOr<std::unique_ptr<MemoryBuffer>> oldBuf = MemoryBuffer::getFile( 932fe6060f1SDimitry Andric path, /*IsText=*/false, /*RequiresNullTerminator=*/false); 9330b57cec5SDimitry Andric if (!oldBuf) { 934349cc55cSDimitry Andric checkError(writeImportLibrary(libName, path, exports, config->machine, 9350b57cec5SDimitry Andric config->mingw)); 9360b57cec5SDimitry Andric return; 9370b57cec5SDimitry Andric } 9380b57cec5SDimitry Andric 9390b57cec5SDimitry Andric SmallString<128> tmpName; 9400b57cec5SDimitry Andric if (std::error_code ec = 9410b57cec5SDimitry Andric sys::fs::createUniqueFile(path + ".tmp-%%%%%%%%.lib", tmpName)) 9420b57cec5SDimitry Andric fatal("cannot create temporary file for import library " + path + ": " + 9430b57cec5SDimitry Andric ec.message()); 9440b57cec5SDimitry Andric 9450b57cec5SDimitry Andric if (Error e = writeImportLibrary(libName, tmpName, exports, config->machine, 9460b57cec5SDimitry Andric config->mingw)) { 947349cc55cSDimitry Andric checkError(std::move(e)); 9480b57cec5SDimitry Andric return; 9490b57cec5SDimitry Andric } 9500b57cec5SDimitry Andric 9510b57cec5SDimitry Andric std::unique_ptr<MemoryBuffer> newBuf = check(MemoryBuffer::getFile( 952fe6060f1SDimitry Andric tmpName, /*IsText=*/false, /*RequiresNullTerminator=*/false)); 9530b57cec5SDimitry Andric if ((*oldBuf)->getBuffer() != newBuf->getBuffer()) { 9540b57cec5SDimitry Andric oldBuf->reset(); 955349cc55cSDimitry Andric checkError(errorCodeToError(sys::fs::rename(tmpName, path))); 9560b57cec5SDimitry Andric } else { 9570b57cec5SDimitry Andric sys::fs::remove(tmpName); 9580b57cec5SDimitry Andric } 9590b57cec5SDimitry Andric } 9600b57cec5SDimitry Andric 9610b57cec5SDimitry Andric static void parseModuleDefs(StringRef path) { 962fe6060f1SDimitry Andric std::unique_ptr<MemoryBuffer> mb = 963fe6060f1SDimitry Andric CHECK(MemoryBuffer::getFile(path, /*IsText=*/false, 964fe6060f1SDimitry Andric /*RequiresNullTerminator=*/false, 965fe6060f1SDimitry Andric /*IsVolatile=*/true), 966fe6060f1SDimitry Andric "could not open " + path); 9670b57cec5SDimitry Andric COFFModuleDefinition m = check(parseCOFFModuleDefinition( 9680b57cec5SDimitry Andric mb->getMemBufferRef(), config->machine, config->mingw)); 9690b57cec5SDimitry Andric 970fe6060f1SDimitry Andric // Include in /reproduce: output if applicable. 971fe6060f1SDimitry Andric driver->takeBuffer(std::move(mb)); 972fe6060f1SDimitry Andric 9730b57cec5SDimitry Andric if (config->outputFile.empty()) 97404eeddc0SDimitry Andric config->outputFile = std::string(saver().save(m.OutputFile)); 97504eeddc0SDimitry Andric config->importName = std::string(saver().save(m.ImportName)); 9760b57cec5SDimitry Andric if (m.ImageBase) 9770b57cec5SDimitry Andric config->imageBase = m.ImageBase; 9780b57cec5SDimitry Andric if (m.StackReserve) 9790b57cec5SDimitry Andric config->stackReserve = m.StackReserve; 9800b57cec5SDimitry Andric if (m.StackCommit) 9810b57cec5SDimitry Andric config->stackCommit = m.StackCommit; 9820b57cec5SDimitry Andric if (m.HeapReserve) 9830b57cec5SDimitry Andric config->heapReserve = m.HeapReserve; 9840b57cec5SDimitry Andric if (m.HeapCommit) 9850b57cec5SDimitry Andric config->heapCommit = m.HeapCommit; 9860b57cec5SDimitry Andric if (m.MajorImageVersion) 9870b57cec5SDimitry Andric config->majorImageVersion = m.MajorImageVersion; 9880b57cec5SDimitry Andric if (m.MinorImageVersion) 9890b57cec5SDimitry Andric config->minorImageVersion = m.MinorImageVersion; 9900b57cec5SDimitry Andric if (m.MajorOSVersion) 9910b57cec5SDimitry Andric config->majorOSVersion = m.MajorOSVersion; 9920b57cec5SDimitry Andric if (m.MinorOSVersion) 9930b57cec5SDimitry Andric config->minorOSVersion = m.MinorOSVersion; 9940b57cec5SDimitry Andric 9950b57cec5SDimitry Andric for (COFFShortExport e1 : m.Exports) { 9960b57cec5SDimitry Andric Export e2; 9970b57cec5SDimitry Andric // In simple cases, only Name is set. Renamed exports are parsed 9980b57cec5SDimitry Andric // and set as "ExtName = Name". If Name has the form "OtherDll.Func", 9990b57cec5SDimitry Andric // it shouldn't be a normal exported function but a forward to another 10000b57cec5SDimitry Andric // DLL instead. This is supported by both MS and GNU linkers. 10015ffd83dbSDimitry Andric if (!e1.ExtName.empty() && e1.ExtName != e1.Name && 10025ffd83dbSDimitry Andric StringRef(e1.Name).contains('.')) { 100304eeddc0SDimitry Andric e2.name = saver().save(e1.ExtName); 100404eeddc0SDimitry Andric e2.forwardTo = saver().save(e1.Name); 10050b57cec5SDimitry Andric config->exports.push_back(e2); 10060b57cec5SDimitry Andric continue; 10070b57cec5SDimitry Andric } 100804eeddc0SDimitry Andric e2.name = saver().save(e1.Name); 100904eeddc0SDimitry Andric e2.extName = saver().save(e1.ExtName); 101004eeddc0SDimitry Andric e2.aliasTarget = saver().save(e1.AliasTarget); 10110b57cec5SDimitry Andric e2.ordinal = e1.Ordinal; 10120b57cec5SDimitry Andric e2.noname = e1.Noname; 10130b57cec5SDimitry Andric e2.data = e1.Data; 10140b57cec5SDimitry Andric e2.isPrivate = e1.Private; 10150b57cec5SDimitry Andric e2.constant = e1.Constant; 10160b57cec5SDimitry Andric config->exports.push_back(e2); 10170b57cec5SDimitry Andric } 10180b57cec5SDimitry Andric } 10190b57cec5SDimitry Andric 10200b57cec5SDimitry Andric void LinkerDriver::enqueueTask(std::function<void()> task) { 10210b57cec5SDimitry Andric taskQueue.push_back(std::move(task)); 10220b57cec5SDimitry Andric } 10230b57cec5SDimitry Andric 10240b57cec5SDimitry Andric bool LinkerDriver::run() { 1025349cc55cSDimitry Andric ScopedTimer t(ctx.inputFileTimer); 10260b57cec5SDimitry Andric 10270b57cec5SDimitry Andric bool didWork = !taskQueue.empty(); 10280b57cec5SDimitry Andric while (!taskQueue.empty()) { 10290b57cec5SDimitry Andric taskQueue.front()(); 10300b57cec5SDimitry Andric taskQueue.pop_front(); 10310b57cec5SDimitry Andric } 10320b57cec5SDimitry Andric return didWork; 10330b57cec5SDimitry Andric } 10340b57cec5SDimitry Andric 10350b57cec5SDimitry Andric // Parse an /order file. If an option is given, the linker places 10360b57cec5SDimitry Andric // COMDAT sections in the same order as their names appear in the 10370b57cec5SDimitry Andric // given file. 1038349cc55cSDimitry Andric static void parseOrderFile(COFFLinkerContext &ctx, StringRef arg) { 10390b57cec5SDimitry Andric // For some reason, the MSVC linker requires a filename to be 10400b57cec5SDimitry Andric // preceded by "@". 10410b57cec5SDimitry Andric if (!arg.startswith("@")) { 10420b57cec5SDimitry Andric error("malformed /order option: '@' missing"); 10430b57cec5SDimitry Andric return; 10440b57cec5SDimitry Andric } 10450b57cec5SDimitry Andric 10460b57cec5SDimitry Andric // Get a list of all comdat sections for error checking. 10470b57cec5SDimitry Andric DenseSet<StringRef> set; 1048349cc55cSDimitry Andric for (Chunk *c : ctx.symtab.getChunks()) 10490b57cec5SDimitry Andric if (auto *sec = dyn_cast<SectionChunk>(c)) 10500b57cec5SDimitry Andric if (sec->sym) 10510b57cec5SDimitry Andric set.insert(sec->sym->getName()); 10520b57cec5SDimitry Andric 10530b57cec5SDimitry Andric // Open a file. 10540b57cec5SDimitry Andric StringRef path = arg.substr(1); 1055fe6060f1SDimitry Andric std::unique_ptr<MemoryBuffer> mb = 1056fe6060f1SDimitry Andric CHECK(MemoryBuffer::getFile(path, /*IsText=*/false, 1057fe6060f1SDimitry Andric /*RequiresNullTerminator=*/false, 1058fe6060f1SDimitry Andric /*IsVolatile=*/true), 1059fe6060f1SDimitry Andric "could not open " + path); 10600b57cec5SDimitry Andric 10610b57cec5SDimitry Andric // Parse a file. An order file contains one symbol per line. 10620b57cec5SDimitry Andric // All symbols that were not present in a given order file are 10630b57cec5SDimitry Andric // considered to have the lowest priority 0 and are placed at 10640b57cec5SDimitry Andric // end of an output section. 10655ffd83dbSDimitry Andric for (StringRef arg : args::getLines(mb->getMemBufferRef())) { 10665ffd83dbSDimitry Andric std::string s(arg); 10670b57cec5SDimitry Andric if (config->machine == I386 && !isDecorated(s)) 10680b57cec5SDimitry Andric s = "_" + s; 10690b57cec5SDimitry Andric 10700b57cec5SDimitry Andric if (set.count(s) == 0) { 10710b57cec5SDimitry Andric if (config->warnMissingOrderSymbol) 10720b57cec5SDimitry Andric warn("/order:" + arg + ": missing symbol: " + s + " [LNK4037]"); 10730b57cec5SDimitry Andric } 10740b57cec5SDimitry Andric else 10750b57cec5SDimitry Andric config->order[s] = INT_MIN + config->order.size(); 10760b57cec5SDimitry Andric } 1077fe6060f1SDimitry Andric 1078fe6060f1SDimitry Andric // Include in /reproduce: output if applicable. 1079fe6060f1SDimitry Andric driver->takeBuffer(std::move(mb)); 10800b57cec5SDimitry Andric } 10810b57cec5SDimitry Andric 1082349cc55cSDimitry Andric static void parseCallGraphFile(COFFLinkerContext &ctx, StringRef path) { 1083fe6060f1SDimitry Andric std::unique_ptr<MemoryBuffer> mb = 1084fe6060f1SDimitry Andric CHECK(MemoryBuffer::getFile(path, /*IsText=*/false, 1085fe6060f1SDimitry Andric /*RequiresNullTerminator=*/false, 1086fe6060f1SDimitry Andric /*IsVolatile=*/true), 1087fe6060f1SDimitry Andric "could not open " + path); 1088e8d8bef9SDimitry Andric 1089e8d8bef9SDimitry Andric // Build a map from symbol name to section. 1090e8d8bef9SDimitry Andric DenseMap<StringRef, Symbol *> map; 1091349cc55cSDimitry Andric for (ObjFile *file : ctx.objFileInstances) 1092e8d8bef9SDimitry Andric for (Symbol *sym : file->getSymbols()) 1093e8d8bef9SDimitry Andric if (sym) 1094e8d8bef9SDimitry Andric map[sym->getName()] = sym; 1095e8d8bef9SDimitry Andric 1096e8d8bef9SDimitry Andric auto findSection = [&](StringRef name) -> SectionChunk * { 1097e8d8bef9SDimitry Andric Symbol *sym = map.lookup(name); 1098e8d8bef9SDimitry Andric if (!sym) { 1099e8d8bef9SDimitry Andric if (config->warnMissingOrderSymbol) 1100e8d8bef9SDimitry Andric warn(path + ": no such symbol: " + name); 1101e8d8bef9SDimitry Andric return nullptr; 1102e8d8bef9SDimitry Andric } 1103e8d8bef9SDimitry Andric 1104e8d8bef9SDimitry Andric if (DefinedCOFF *dr = dyn_cast_or_null<DefinedCOFF>(sym)) 1105e8d8bef9SDimitry Andric return dyn_cast_or_null<SectionChunk>(dr->getChunk()); 1106e8d8bef9SDimitry Andric return nullptr; 1107e8d8bef9SDimitry Andric }; 1108e8d8bef9SDimitry Andric 1109e8d8bef9SDimitry Andric for (StringRef line : args::getLines(*mb)) { 1110e8d8bef9SDimitry Andric SmallVector<StringRef, 3> fields; 1111e8d8bef9SDimitry Andric line.split(fields, ' '); 1112e8d8bef9SDimitry Andric uint64_t count; 1113e8d8bef9SDimitry Andric 1114e8d8bef9SDimitry Andric if (fields.size() != 3 || !to_integer(fields[2], count)) { 1115e8d8bef9SDimitry Andric error(path + ": parse error"); 1116e8d8bef9SDimitry Andric return; 1117e8d8bef9SDimitry Andric } 1118e8d8bef9SDimitry Andric 1119e8d8bef9SDimitry Andric if (SectionChunk *from = findSection(fields[0])) 1120e8d8bef9SDimitry Andric if (SectionChunk *to = findSection(fields[1])) 1121e8d8bef9SDimitry Andric config->callGraphProfile[{from, to}] += count; 1122e8d8bef9SDimitry Andric } 1123fe6060f1SDimitry Andric 1124fe6060f1SDimitry Andric // Include in /reproduce: output if applicable. 1125fe6060f1SDimitry Andric driver->takeBuffer(std::move(mb)); 1126e8d8bef9SDimitry Andric } 1127e8d8bef9SDimitry Andric 1128349cc55cSDimitry Andric static void readCallGraphsFromObjectFiles(COFFLinkerContext &ctx) { 1129349cc55cSDimitry Andric for (ObjFile *obj : ctx.objFileInstances) { 1130e8d8bef9SDimitry Andric if (obj->callgraphSec) { 1131e8d8bef9SDimitry Andric ArrayRef<uint8_t> contents; 1132e8d8bef9SDimitry Andric cantFail( 1133e8d8bef9SDimitry Andric obj->getCOFFObj()->getSectionContents(obj->callgraphSec, contents)); 1134e8d8bef9SDimitry Andric BinaryStreamReader reader(contents, support::little); 1135e8d8bef9SDimitry Andric while (!reader.empty()) { 1136e8d8bef9SDimitry Andric uint32_t fromIndex, toIndex; 1137e8d8bef9SDimitry Andric uint64_t count; 1138e8d8bef9SDimitry Andric if (Error err = reader.readInteger(fromIndex)) 1139e8d8bef9SDimitry Andric fatal(toString(obj) + ": Expected 32-bit integer"); 1140e8d8bef9SDimitry Andric if (Error err = reader.readInteger(toIndex)) 1141e8d8bef9SDimitry Andric fatal(toString(obj) + ": Expected 32-bit integer"); 1142e8d8bef9SDimitry Andric if (Error err = reader.readInteger(count)) 1143e8d8bef9SDimitry Andric fatal(toString(obj) + ": Expected 64-bit integer"); 1144e8d8bef9SDimitry Andric auto *fromSym = dyn_cast_or_null<Defined>(obj->getSymbol(fromIndex)); 1145e8d8bef9SDimitry Andric auto *toSym = dyn_cast_or_null<Defined>(obj->getSymbol(toIndex)); 1146e8d8bef9SDimitry Andric if (!fromSym || !toSym) 1147e8d8bef9SDimitry Andric continue; 1148e8d8bef9SDimitry Andric auto *from = dyn_cast_or_null<SectionChunk>(fromSym->getChunk()); 1149e8d8bef9SDimitry Andric auto *to = dyn_cast_or_null<SectionChunk>(toSym->getChunk()); 1150e8d8bef9SDimitry Andric if (from && to) 1151e8d8bef9SDimitry Andric config->callGraphProfile[{from, to}] += count; 1152e8d8bef9SDimitry Andric } 1153e8d8bef9SDimitry Andric } 1154e8d8bef9SDimitry Andric } 1155e8d8bef9SDimitry Andric } 1156e8d8bef9SDimitry Andric 11570b57cec5SDimitry Andric static void markAddrsig(Symbol *s) { 11580b57cec5SDimitry Andric if (auto *d = dyn_cast_or_null<Defined>(s)) 11590b57cec5SDimitry Andric if (SectionChunk *c = dyn_cast_or_null<SectionChunk>(d->getChunk())) 11600b57cec5SDimitry Andric c->keepUnique = true; 11610b57cec5SDimitry Andric } 11620b57cec5SDimitry Andric 1163349cc55cSDimitry Andric static void findKeepUniqueSections(COFFLinkerContext &ctx) { 11640b57cec5SDimitry Andric // Exported symbols could be address-significant in other executables or DSOs, 11650b57cec5SDimitry Andric // so we conservatively mark them as address-significant. 11660b57cec5SDimitry Andric for (Export &r : config->exports) 11670b57cec5SDimitry Andric markAddrsig(r.sym); 11680b57cec5SDimitry Andric 11690b57cec5SDimitry Andric // Visit the address-significance table in each object file and mark each 11700b57cec5SDimitry Andric // referenced symbol as address-significant. 1171349cc55cSDimitry Andric for (ObjFile *obj : ctx.objFileInstances) { 11720b57cec5SDimitry Andric ArrayRef<Symbol *> syms = obj->getSymbols(); 11730b57cec5SDimitry Andric if (obj->addrsigSec) { 11740b57cec5SDimitry Andric ArrayRef<uint8_t> contents; 11750b57cec5SDimitry Andric cantFail( 11760b57cec5SDimitry Andric obj->getCOFFObj()->getSectionContents(obj->addrsigSec, contents)); 11770b57cec5SDimitry Andric const uint8_t *cur = contents.begin(); 11780b57cec5SDimitry Andric while (cur != contents.end()) { 11790b57cec5SDimitry Andric unsigned size; 11800b57cec5SDimitry Andric const char *err; 11810b57cec5SDimitry Andric uint64_t symIndex = decodeULEB128(cur, &size, contents.end(), &err); 11820b57cec5SDimitry Andric if (err) 11830b57cec5SDimitry Andric fatal(toString(obj) + ": could not decode addrsig section: " + err); 11840b57cec5SDimitry Andric if (symIndex >= syms.size()) 11850b57cec5SDimitry Andric fatal(toString(obj) + ": invalid symbol index in addrsig section"); 11860b57cec5SDimitry Andric markAddrsig(syms[symIndex]); 11870b57cec5SDimitry Andric cur += size; 11880b57cec5SDimitry Andric } 11890b57cec5SDimitry Andric } else { 11900b57cec5SDimitry Andric // If an object file does not have an address-significance table, 11910b57cec5SDimitry Andric // conservatively mark all of its symbols as address-significant. 11920b57cec5SDimitry Andric for (Symbol *s : syms) 11930b57cec5SDimitry Andric markAddrsig(s); 11940b57cec5SDimitry Andric } 11950b57cec5SDimitry Andric } 11960b57cec5SDimitry Andric } 11970b57cec5SDimitry Andric 11980b57cec5SDimitry Andric // link.exe replaces each %foo% in altPath with the contents of environment 11990b57cec5SDimitry Andric // variable foo, and adds the two magic env vars _PDB (expands to the basename 12000b57cec5SDimitry Andric // of pdb's output path) and _EXT (expands to the extension of the output 12010b57cec5SDimitry Andric // binary). 12020b57cec5SDimitry Andric // lld only supports %_PDB% and %_EXT% and warns on references to all other env 12030b57cec5SDimitry Andric // vars. 12040b57cec5SDimitry Andric static void parsePDBAltPath(StringRef altPath) { 12050b57cec5SDimitry Andric SmallString<128> buf; 12060b57cec5SDimitry Andric StringRef pdbBasename = 12070b57cec5SDimitry Andric sys::path::filename(config->pdbPath, sys::path::Style::windows); 12080b57cec5SDimitry Andric StringRef binaryExtension = 12090b57cec5SDimitry Andric sys::path::extension(config->outputFile, sys::path::Style::windows); 12100b57cec5SDimitry Andric if (!binaryExtension.empty()) 12110b57cec5SDimitry Andric binaryExtension = binaryExtension.substr(1); // %_EXT% does not include '.'. 12120b57cec5SDimitry Andric 12130b57cec5SDimitry Andric // Invariant: 12140b57cec5SDimitry Andric // +--------- cursor ('a...' might be the empty string). 12150b57cec5SDimitry Andric // | +----- firstMark 12160b57cec5SDimitry Andric // | | +- secondMark 12170b57cec5SDimitry Andric // v v v 12180b57cec5SDimitry Andric // a...%...%... 12190b57cec5SDimitry Andric size_t cursor = 0; 12200b57cec5SDimitry Andric while (cursor < altPath.size()) { 12210b57cec5SDimitry Andric size_t firstMark, secondMark; 12220b57cec5SDimitry Andric if ((firstMark = altPath.find('%', cursor)) == StringRef::npos || 12230b57cec5SDimitry Andric (secondMark = altPath.find('%', firstMark + 1)) == StringRef::npos) { 12240b57cec5SDimitry Andric // Didn't find another full fragment, treat rest of string as literal. 12250b57cec5SDimitry Andric buf.append(altPath.substr(cursor)); 12260b57cec5SDimitry Andric break; 12270b57cec5SDimitry Andric } 12280b57cec5SDimitry Andric 12290b57cec5SDimitry Andric // Found a full fragment. Append text in front of first %, and interpret 12300b57cec5SDimitry Andric // text between first and second % as variable name. 12310b57cec5SDimitry Andric buf.append(altPath.substr(cursor, firstMark - cursor)); 12320b57cec5SDimitry Andric StringRef var = altPath.substr(firstMark, secondMark - firstMark + 1); 1233fe6060f1SDimitry Andric if (var.equals_insensitive("%_pdb%")) 12340b57cec5SDimitry Andric buf.append(pdbBasename); 1235fe6060f1SDimitry Andric else if (var.equals_insensitive("%_ext%")) 12360b57cec5SDimitry Andric buf.append(binaryExtension); 12370b57cec5SDimitry Andric else { 12380b57cec5SDimitry Andric warn("only %_PDB% and %_EXT% supported in /pdbaltpath:, keeping " + 12390b57cec5SDimitry Andric var + " as literal"); 12400b57cec5SDimitry Andric buf.append(var); 12410b57cec5SDimitry Andric } 12420b57cec5SDimitry Andric 12430b57cec5SDimitry Andric cursor = secondMark + 1; 12440b57cec5SDimitry Andric } 12450b57cec5SDimitry Andric 12460b57cec5SDimitry Andric config->pdbAltPath = buf; 12470b57cec5SDimitry Andric } 12480b57cec5SDimitry Andric 124985868e8aSDimitry Andric /// Convert resource files and potentially merge input resource object 125085868e8aSDimitry Andric /// trees into one resource tree. 12510b57cec5SDimitry Andric /// Call after ObjFile::Instances is complete. 125285868e8aSDimitry Andric void LinkerDriver::convertResources() { 125385868e8aSDimitry Andric std::vector<ObjFile *> resourceObjFiles; 125485868e8aSDimitry Andric 1255349cc55cSDimitry Andric for (ObjFile *f : ctx.objFileInstances) { 125685868e8aSDimitry Andric if (f->isResourceObjFile()) 125785868e8aSDimitry Andric resourceObjFiles.push_back(f); 12580b57cec5SDimitry Andric } 12590b57cec5SDimitry Andric 126085868e8aSDimitry Andric if (!config->mingw && 126185868e8aSDimitry Andric (resourceObjFiles.size() > 1 || 126285868e8aSDimitry Andric (resourceObjFiles.size() == 1 && !resources.empty()))) { 126385868e8aSDimitry Andric error((!resources.empty() ? "internal .obj file created from .res files" 126485868e8aSDimitry Andric : toString(resourceObjFiles[1])) + 12650b57cec5SDimitry Andric ": more than one resource obj file not allowed, already got " + 126685868e8aSDimitry Andric toString(resourceObjFiles.front())); 126785868e8aSDimitry Andric return; 12680b57cec5SDimitry Andric } 126985868e8aSDimitry Andric 127085868e8aSDimitry Andric if (resources.empty() && resourceObjFiles.size() <= 1) { 127185868e8aSDimitry Andric // No resources to convert, and max one resource object file in 127285868e8aSDimitry Andric // the input. Keep that preconverted resource section as is. 127385868e8aSDimitry Andric for (ObjFile *f : resourceObjFiles) 127485868e8aSDimitry Andric f->includeResourceChunks(); 127585868e8aSDimitry Andric return; 127685868e8aSDimitry Andric } 1277349cc55cSDimitry Andric ObjFile *f = 1278349cc55cSDimitry Andric make<ObjFile>(ctx, convertResToCOFF(resources, resourceObjFiles)); 1279349cc55cSDimitry Andric ctx.symtab.addFile(f); 128085868e8aSDimitry Andric f->includeResourceChunks(); 12810b57cec5SDimitry Andric } 12820b57cec5SDimitry Andric 12830b57cec5SDimitry Andric // In MinGW, if no symbols are chosen to be exported, then all symbols are 12840b57cec5SDimitry Andric // automatically exported by default. This behavior can be forced by the 12850b57cec5SDimitry Andric // -export-all-symbols option, so that it happens even when exports are 12860b57cec5SDimitry Andric // explicitly specified. The automatic behavior can be disabled using the 12870b57cec5SDimitry Andric // -exclude-all-symbols option, so that lld-link behaves like link.exe rather 12880b57cec5SDimitry Andric // than MinGW in the case that nothing is explicitly exported. 12890b57cec5SDimitry Andric void LinkerDriver::maybeExportMinGWSymbols(const opt::InputArgList &args) { 1290fe6060f1SDimitry Andric if (!args.hasArg(OPT_export_all_symbols)) { 12910b57cec5SDimitry Andric if (!config->dll) 12920b57cec5SDimitry Andric return; 12930b57cec5SDimitry Andric 12940b57cec5SDimitry Andric if (!config->exports.empty()) 12950b57cec5SDimitry Andric return; 12960b57cec5SDimitry Andric if (args.hasArg(OPT_exclude_all_symbols)) 12970b57cec5SDimitry Andric return; 12980b57cec5SDimitry Andric } 12990b57cec5SDimitry Andric 13000b57cec5SDimitry Andric AutoExporter exporter; 13010b57cec5SDimitry Andric 13020b57cec5SDimitry Andric for (auto *arg : args.filtered(OPT_wholearchive_file)) 13030b57cec5SDimitry Andric if (Optional<StringRef> path = doFindFile(arg->getValue())) 13040b57cec5SDimitry Andric exporter.addWholeArchive(*path); 13050b57cec5SDimitry Andric 1306349cc55cSDimitry Andric ctx.symtab.forEachSymbol([&](Symbol *s) { 13070b57cec5SDimitry Andric auto *def = dyn_cast<Defined>(s); 1308349cc55cSDimitry Andric if (!exporter.shouldExport(ctx, def)) 13090b57cec5SDimitry Andric return; 13100b57cec5SDimitry Andric 1311fe6060f1SDimitry Andric if (!def->isGCRoot) { 1312fe6060f1SDimitry Andric def->isGCRoot = true; 1313fe6060f1SDimitry Andric config->gcroot.push_back(def); 1314fe6060f1SDimitry Andric } 1315fe6060f1SDimitry Andric 13160b57cec5SDimitry Andric Export e; 13170b57cec5SDimitry Andric e.name = def->getName(); 13180b57cec5SDimitry Andric e.sym = def; 13190b57cec5SDimitry Andric if (Chunk *c = def->getChunk()) 13200b57cec5SDimitry Andric if (!(c->getOutputCharacteristics() & IMAGE_SCN_MEM_EXECUTE)) 13210b57cec5SDimitry Andric e.data = true; 1322fe6060f1SDimitry Andric s->isUsedInRegularObj = true; 13230b57cec5SDimitry Andric config->exports.push_back(e); 13240b57cec5SDimitry Andric }); 13250b57cec5SDimitry Andric } 13260b57cec5SDimitry Andric 132785868e8aSDimitry Andric // lld has a feature to create a tar file containing all input files as well as 132885868e8aSDimitry Andric // all command line options, so that other people can run lld again with exactly 132985868e8aSDimitry Andric // the same inputs. This feature is accessible via /linkrepro and /reproduce. 133085868e8aSDimitry Andric // 133185868e8aSDimitry Andric // /linkrepro and /reproduce are very similar, but /linkrepro takes a directory 133285868e8aSDimitry Andric // name while /reproduce takes a full path. We have /linkrepro for compatibility 133385868e8aSDimitry Andric // with Microsoft link.exe. 133485868e8aSDimitry Andric Optional<std::string> getReproduceFile(const opt::InputArgList &args) { 133585868e8aSDimitry Andric if (auto *arg = args.getLastArg(OPT_reproduce)) 133685868e8aSDimitry Andric return std::string(arg->getValue()); 133785868e8aSDimitry Andric 133885868e8aSDimitry Andric if (auto *arg = args.getLastArg(OPT_linkrepro)) { 133985868e8aSDimitry Andric SmallString<64> path = StringRef(arg->getValue()); 134085868e8aSDimitry Andric sys::path::append(path, "repro.tar"); 13415ffd83dbSDimitry Andric return std::string(path); 134285868e8aSDimitry Andric } 134385868e8aSDimitry Andric 1344e8d8bef9SDimitry Andric // This is intentionally not guarded by OPT_lldignoreenv since writing 1345e8d8bef9SDimitry Andric // a repro tar file doesn't affect the main output. 1346e8d8bef9SDimitry Andric if (auto *path = getenv("LLD_REPRODUCE")) 1347e8d8bef9SDimitry Andric return std::string(path); 1348e8d8bef9SDimitry Andric 134985868e8aSDimitry Andric return None; 135085868e8aSDimitry Andric } 13510b57cec5SDimitry Andric 1352e8d8bef9SDimitry Andric void LinkerDriver::linkerMain(ArrayRef<const char *> argsArr) { 1353349cc55cSDimitry Andric ScopedTimer rootTimer(ctx.rootTimer); 13545ffd83dbSDimitry Andric 13550b57cec5SDimitry Andric // Needed for LTO. 13560b57cec5SDimitry Andric InitializeAllTargetInfos(); 13570b57cec5SDimitry Andric InitializeAllTargets(); 13580b57cec5SDimitry Andric InitializeAllTargetMCs(); 13590b57cec5SDimitry Andric InitializeAllAsmParsers(); 13600b57cec5SDimitry Andric InitializeAllAsmPrinters(); 13610b57cec5SDimitry Andric 13620b57cec5SDimitry Andric // If the first command line argument is "/lib", link.exe acts like lib.exe. 13630b57cec5SDimitry Andric // We call our own implementation of lib.exe that understands bitcode files. 1364fe6060f1SDimitry Andric if (argsArr.size() > 1 && 1365fe6060f1SDimitry Andric (StringRef(argsArr[1]).equals_insensitive("/lib") || 1366fe6060f1SDimitry Andric StringRef(argsArr[1]).equals_insensitive("-lib"))) { 13670b57cec5SDimitry Andric if (llvm::libDriverMain(argsArr.slice(1)) != 0) 13680b57cec5SDimitry Andric fatal("lib failed"); 13690b57cec5SDimitry Andric return; 13700b57cec5SDimitry Andric } 13710b57cec5SDimitry Andric 13720b57cec5SDimitry Andric // Parse command line options. 13730b57cec5SDimitry Andric ArgParser parser; 137485868e8aSDimitry Andric opt::InputArgList args = parser.parse(argsArr); 13750b57cec5SDimitry Andric 13760b57cec5SDimitry Andric // Parse and evaluate -mllvm options. 13770b57cec5SDimitry Andric std::vector<const char *> v; 13780b57cec5SDimitry Andric v.push_back("lld-link (LLVM option parsing)"); 13790b57cec5SDimitry Andric for (auto *arg : args.filtered(OPT_mllvm)) 13800b57cec5SDimitry Andric v.push_back(arg->getValue()); 1381e8d8bef9SDimitry Andric cl::ResetAllOptionOccurrences(); 13820b57cec5SDimitry Andric cl::ParseCommandLineOptions(v.size(), v.data()); 13830b57cec5SDimitry Andric 13840b57cec5SDimitry Andric // Handle /errorlimit early, because error() depends on it. 13850b57cec5SDimitry Andric if (auto *arg = args.getLastArg(OPT_errorlimit)) { 13860b57cec5SDimitry Andric int n = 20; 13870b57cec5SDimitry Andric StringRef s = arg->getValue(); 13880b57cec5SDimitry Andric if (s.getAsInteger(10, n)) 13890b57cec5SDimitry Andric error(arg->getSpelling() + " number expected, but got " + s); 13900b57cec5SDimitry Andric errorHandler().errorLimit = n; 13910b57cec5SDimitry Andric } 13920b57cec5SDimitry Andric 13930b57cec5SDimitry Andric // Handle /help 13940b57cec5SDimitry Andric if (args.hasArg(OPT_help)) { 13950b57cec5SDimitry Andric printHelp(argsArr[0]); 13960b57cec5SDimitry Andric return; 13970b57cec5SDimitry Andric } 13980b57cec5SDimitry Andric 13995ffd83dbSDimitry Andric // /threads: takes a positive integer and provides the default value for 14005ffd83dbSDimitry Andric // /opt:lldltojobs=. 14015ffd83dbSDimitry Andric if (auto *arg = args.getLastArg(OPT_threads)) { 14025ffd83dbSDimitry Andric StringRef v(arg->getValue()); 14035ffd83dbSDimitry Andric unsigned threads = 0; 14045ffd83dbSDimitry Andric if (!llvm::to_integer(v, threads, 0) || threads == 0) 14055ffd83dbSDimitry Andric error(arg->getSpelling() + ": expected a positive integer, but got '" + 14065ffd83dbSDimitry Andric arg->getValue() + "'"); 14075ffd83dbSDimitry Andric parallel::strategy = hardware_concurrency(threads); 14085ffd83dbSDimitry Andric config->thinLTOJobs = v.str(); 14095ffd83dbSDimitry Andric } 14100b57cec5SDimitry Andric 14110b57cec5SDimitry Andric if (args.hasArg(OPT_show_timing)) 14120b57cec5SDimitry Andric config->showTiming = true; 14130b57cec5SDimitry Andric 14140b57cec5SDimitry Andric config->showSummary = args.hasArg(OPT_summary); 14150b57cec5SDimitry Andric 14160b57cec5SDimitry Andric // Handle --version, which is an lld extension. This option is a bit odd 14170b57cec5SDimitry Andric // because it doesn't start with "/", but we deliberately chose "--" to 14180b57cec5SDimitry Andric // avoid conflict with /version and for compatibility with clang-cl. 14190b57cec5SDimitry Andric if (args.hasArg(OPT_dash_dash_version)) { 1420e8d8bef9SDimitry Andric message(getLLDVersion()); 14210b57cec5SDimitry Andric return; 14220b57cec5SDimitry Andric } 14230b57cec5SDimitry Andric 14240b57cec5SDimitry Andric // Handle /lldmingw early, since it can potentially affect how other 14250b57cec5SDimitry Andric // options are handled. 14260b57cec5SDimitry Andric config->mingw = args.hasArg(OPT_lldmingw); 14270b57cec5SDimitry Andric 142885868e8aSDimitry Andric // Handle /linkrepro and /reproduce. 142985868e8aSDimitry Andric if (Optional<std::string> path = getReproduceFile(args)) { 14300b57cec5SDimitry Andric Expected<std::unique_ptr<TarWriter>> errOrWriter = 143185868e8aSDimitry Andric TarWriter::create(*path, sys::path::stem(*path)); 14320b57cec5SDimitry Andric 14330b57cec5SDimitry Andric if (errOrWriter) { 14340b57cec5SDimitry Andric tar = std::move(*errOrWriter); 14350b57cec5SDimitry Andric } else { 143685868e8aSDimitry Andric error("/linkrepro: failed to open " + *path + ": " + 14370b57cec5SDimitry Andric toString(errOrWriter.takeError())); 14380b57cec5SDimitry Andric } 14390b57cec5SDimitry Andric } 14400b57cec5SDimitry Andric 1441480093f4SDimitry Andric if (!args.hasArg(OPT_INPUT, OPT_wholearchive_file)) { 14420b57cec5SDimitry Andric if (args.hasArg(OPT_deffile)) 14430b57cec5SDimitry Andric config->noEntry = true; 14440b57cec5SDimitry Andric else 14450b57cec5SDimitry Andric fatal("no input files"); 14460b57cec5SDimitry Andric } 14470b57cec5SDimitry Andric 14480b57cec5SDimitry Andric // Construct search path list. 14490b57cec5SDimitry Andric searchPaths.push_back(""); 14500b57cec5SDimitry Andric for (auto *arg : args.filtered(OPT_libpath)) 14510b57cec5SDimitry Andric searchPaths.push_back(arg->getValue()); 1452*81ad6265SDimitry Andric detectWinSysRoot(args); 1453*81ad6265SDimitry Andric if (!args.hasArg(OPT_lldignoreenv) && !args.hasArg(OPT_winsysroot)) 14540b57cec5SDimitry Andric addLibSearchPaths(); 14550b57cec5SDimitry Andric 14560b57cec5SDimitry Andric // Handle /ignore 14570b57cec5SDimitry Andric for (auto *arg : args.filtered(OPT_ignore)) { 14580b57cec5SDimitry Andric SmallVector<StringRef, 8> vec; 14590b57cec5SDimitry Andric StringRef(arg->getValue()).split(vec, ','); 14600b57cec5SDimitry Andric for (StringRef s : vec) { 14610b57cec5SDimitry Andric if (s == "4037") 14620b57cec5SDimitry Andric config->warnMissingOrderSymbol = false; 14630b57cec5SDimitry Andric else if (s == "4099") 14640b57cec5SDimitry Andric config->warnDebugInfoUnusable = false; 14650b57cec5SDimitry Andric else if (s == "4217") 14660b57cec5SDimitry Andric config->warnLocallyDefinedImported = false; 1467480093f4SDimitry Andric else if (s == "longsections") 1468480093f4SDimitry Andric config->warnLongSectionNames = false; 14690b57cec5SDimitry Andric // Other warning numbers are ignored. 14700b57cec5SDimitry Andric } 14710b57cec5SDimitry Andric } 14720b57cec5SDimitry Andric 14730b57cec5SDimitry Andric // Handle /out 14740b57cec5SDimitry Andric if (auto *arg = args.getLastArg(OPT_out)) 14750b57cec5SDimitry Andric config->outputFile = arg->getValue(); 14760b57cec5SDimitry Andric 14770b57cec5SDimitry Andric // Handle /verbose 14780b57cec5SDimitry Andric if (args.hasArg(OPT_verbose)) 14790b57cec5SDimitry Andric config->verbose = true; 14800b57cec5SDimitry Andric errorHandler().verbose = config->verbose; 14810b57cec5SDimitry Andric 14820b57cec5SDimitry Andric // Handle /force or /force:unresolved 14830b57cec5SDimitry Andric if (args.hasArg(OPT_force, OPT_force_unresolved)) 14840b57cec5SDimitry Andric config->forceUnresolved = true; 14850b57cec5SDimitry Andric 14860b57cec5SDimitry Andric // Handle /force or /force:multiple 14870b57cec5SDimitry Andric if (args.hasArg(OPT_force, OPT_force_multiple)) 14880b57cec5SDimitry Andric config->forceMultiple = true; 14890b57cec5SDimitry Andric 14900b57cec5SDimitry Andric // Handle /force or /force:multipleres 14910b57cec5SDimitry Andric if (args.hasArg(OPT_force, OPT_force_multipleres)) 14920b57cec5SDimitry Andric config->forceMultipleRes = true; 14930b57cec5SDimitry Andric 14940b57cec5SDimitry Andric // Handle /debug 14950b57cec5SDimitry Andric DebugKind debug = parseDebugKind(args); 14960b57cec5SDimitry Andric if (debug == DebugKind::Full || debug == DebugKind::Dwarf || 1497fe6060f1SDimitry Andric debug == DebugKind::GHash || debug == DebugKind::NoGHash) { 14980b57cec5SDimitry Andric config->debug = true; 14990b57cec5SDimitry Andric config->incremental = true; 15000b57cec5SDimitry Andric } 15010b57cec5SDimitry Andric 15020b57cec5SDimitry Andric // Handle /demangle 1503*81ad6265SDimitry Andric config->demangle = args.hasFlag(OPT_demangle, OPT_demangle_no, true); 15040b57cec5SDimitry Andric 15050b57cec5SDimitry Andric // Handle /debugtype 15060b57cec5SDimitry Andric config->debugTypes = parseDebugTypes(args); 15070b57cec5SDimitry Andric 1508480093f4SDimitry Andric // Handle /driver[:uponly|:wdm]. 1509480093f4SDimitry Andric config->driverUponly = args.hasArg(OPT_driver_uponly) || 1510480093f4SDimitry Andric args.hasArg(OPT_driver_uponly_wdm) || 1511480093f4SDimitry Andric args.hasArg(OPT_driver_wdm_uponly); 1512480093f4SDimitry Andric config->driverWdm = args.hasArg(OPT_driver_wdm) || 1513480093f4SDimitry Andric args.hasArg(OPT_driver_uponly_wdm) || 1514480093f4SDimitry Andric args.hasArg(OPT_driver_wdm_uponly); 1515480093f4SDimitry Andric config->driver = 1516480093f4SDimitry Andric config->driverUponly || config->driverWdm || args.hasArg(OPT_driver); 1517480093f4SDimitry Andric 15180b57cec5SDimitry Andric // Handle /pdb 15190b57cec5SDimitry Andric bool shouldCreatePDB = 1520fe6060f1SDimitry Andric (debug == DebugKind::Full || debug == DebugKind::GHash || 1521fe6060f1SDimitry Andric debug == DebugKind::NoGHash); 15220b57cec5SDimitry Andric if (shouldCreatePDB) { 15230b57cec5SDimitry Andric if (auto *arg = args.getLastArg(OPT_pdb)) 15240b57cec5SDimitry Andric config->pdbPath = arg->getValue(); 15250b57cec5SDimitry Andric if (auto *arg = args.getLastArg(OPT_pdbaltpath)) 15260b57cec5SDimitry Andric config->pdbAltPath = arg->getValue(); 1527349cc55cSDimitry Andric if (auto *arg = args.getLastArg(OPT_pdbpagesize)) 1528349cc55cSDimitry Andric parsePDBPageSize(arg->getValue()); 15290b57cec5SDimitry Andric if (args.hasArg(OPT_natvis)) 15300b57cec5SDimitry Andric config->natvisFiles = args.getAllArgValues(OPT_natvis); 15315ffd83dbSDimitry Andric if (args.hasArg(OPT_pdbstream)) { 15325ffd83dbSDimitry Andric for (const StringRef value : args.getAllArgValues(OPT_pdbstream)) { 15335ffd83dbSDimitry Andric const std::pair<StringRef, StringRef> nameFile = value.split("="); 15345ffd83dbSDimitry Andric const StringRef name = nameFile.first; 15355ffd83dbSDimitry Andric const std::string file = nameFile.second.str(); 15365ffd83dbSDimitry Andric config->namedStreams[name] = file; 15375ffd83dbSDimitry Andric } 15385ffd83dbSDimitry Andric } 15390b57cec5SDimitry Andric 15400b57cec5SDimitry Andric if (auto *arg = args.getLastArg(OPT_pdb_source_path)) 15410b57cec5SDimitry Andric config->pdbSourcePath = arg->getValue(); 15420b57cec5SDimitry Andric } 15430b57cec5SDimitry Andric 15445ffd83dbSDimitry Andric // Handle /pdbstripped 15455ffd83dbSDimitry Andric if (args.hasArg(OPT_pdbstripped)) 15465ffd83dbSDimitry Andric warn("ignoring /pdbstripped flag, it is not yet supported"); 15475ffd83dbSDimitry Andric 15480b57cec5SDimitry Andric // Handle /noentry 15490b57cec5SDimitry Andric if (args.hasArg(OPT_noentry)) { 15500b57cec5SDimitry Andric if (args.hasArg(OPT_dll)) 15510b57cec5SDimitry Andric config->noEntry = true; 15520b57cec5SDimitry Andric else 15530b57cec5SDimitry Andric error("/noentry must be specified with /dll"); 15540b57cec5SDimitry Andric } 15550b57cec5SDimitry Andric 15560b57cec5SDimitry Andric // Handle /dll 15570b57cec5SDimitry Andric if (args.hasArg(OPT_dll)) { 15580b57cec5SDimitry Andric config->dll = true; 15590b57cec5SDimitry Andric config->manifestID = 2; 15600b57cec5SDimitry Andric } 15610b57cec5SDimitry Andric 15620b57cec5SDimitry Andric // Handle /dynamicbase and /fixed. We can't use hasFlag for /dynamicbase 15630b57cec5SDimitry Andric // because we need to explicitly check whether that option or its inverse was 15640b57cec5SDimitry Andric // present in the argument list in order to handle /fixed. 15650b57cec5SDimitry Andric auto *dynamicBaseArg = args.getLastArg(OPT_dynamicbase, OPT_dynamicbase_no); 15660b57cec5SDimitry Andric if (dynamicBaseArg && 15670b57cec5SDimitry Andric dynamicBaseArg->getOption().getID() == OPT_dynamicbase_no) 15680b57cec5SDimitry Andric config->dynamicBase = false; 15690b57cec5SDimitry Andric 15700b57cec5SDimitry Andric // MSDN claims "/FIXED:NO is the default setting for a DLL, and /FIXED is the 15710b57cec5SDimitry Andric // default setting for any other project type.", but link.exe defaults to 15720b57cec5SDimitry Andric // /FIXED:NO for exe outputs as well. Match behavior, not docs. 15730b57cec5SDimitry Andric bool fixed = args.hasFlag(OPT_fixed, OPT_fixed_no, false); 15740b57cec5SDimitry Andric if (fixed) { 15750b57cec5SDimitry Andric if (dynamicBaseArg && 15760b57cec5SDimitry Andric dynamicBaseArg->getOption().getID() == OPT_dynamicbase) { 15770b57cec5SDimitry Andric error("/fixed must not be specified with /dynamicbase"); 15780b57cec5SDimitry Andric } else { 15790b57cec5SDimitry Andric config->relocatable = false; 15800b57cec5SDimitry Andric config->dynamicBase = false; 15810b57cec5SDimitry Andric } 15820b57cec5SDimitry Andric } 15830b57cec5SDimitry Andric 15840b57cec5SDimitry Andric // Handle /appcontainer 15850b57cec5SDimitry Andric config->appContainer = 15860b57cec5SDimitry Andric args.hasFlag(OPT_appcontainer, OPT_appcontainer_no, false); 15870b57cec5SDimitry Andric 15880b57cec5SDimitry Andric // Handle /machine 15890b57cec5SDimitry Andric if (auto *arg = args.getLastArg(OPT_machine)) { 15900b57cec5SDimitry Andric config->machine = getMachineType(arg->getValue()); 15910b57cec5SDimitry Andric if (config->machine == IMAGE_FILE_MACHINE_UNKNOWN) 15920b57cec5SDimitry Andric fatal(Twine("unknown /machine argument: ") + arg->getValue()); 1593*81ad6265SDimitry Andric addWinSysRootLibSearchPaths(); 15940b57cec5SDimitry Andric } 15950b57cec5SDimitry Andric 15960b57cec5SDimitry Andric // Handle /nodefaultlib:<filename> 15970b57cec5SDimitry Andric for (auto *arg : args.filtered(OPT_nodefaultlib)) 15980b57cec5SDimitry Andric config->noDefaultLibs.insert(doFindLib(arg->getValue()).lower()); 15990b57cec5SDimitry Andric 16000b57cec5SDimitry Andric // Handle /nodefaultlib 16010b57cec5SDimitry Andric if (args.hasArg(OPT_nodefaultlib_all)) 16020b57cec5SDimitry Andric config->noDefaultLibAll = true; 16030b57cec5SDimitry Andric 16040b57cec5SDimitry Andric // Handle /base 16050b57cec5SDimitry Andric if (auto *arg = args.getLastArg(OPT_base)) 16060b57cec5SDimitry Andric parseNumbers(arg->getValue(), &config->imageBase); 16070b57cec5SDimitry Andric 16080b57cec5SDimitry Andric // Handle /filealign 16090b57cec5SDimitry Andric if (auto *arg = args.getLastArg(OPT_filealign)) { 16100b57cec5SDimitry Andric parseNumbers(arg->getValue(), &config->fileAlign); 16110b57cec5SDimitry Andric if (!isPowerOf2_64(config->fileAlign)) 16120b57cec5SDimitry Andric error("/filealign: not a power of two: " + Twine(config->fileAlign)); 16130b57cec5SDimitry Andric } 16140b57cec5SDimitry Andric 16150b57cec5SDimitry Andric // Handle /stack 16160b57cec5SDimitry Andric if (auto *arg = args.getLastArg(OPT_stack)) 16170b57cec5SDimitry Andric parseNumbers(arg->getValue(), &config->stackReserve, &config->stackCommit); 16180b57cec5SDimitry Andric 16190b57cec5SDimitry Andric // Handle /guard:cf 16200b57cec5SDimitry Andric if (auto *arg = args.getLastArg(OPT_guard)) 16210b57cec5SDimitry Andric parseGuard(arg->getValue()); 16220b57cec5SDimitry Andric 16230b57cec5SDimitry Andric // Handle /heap 16240b57cec5SDimitry Andric if (auto *arg = args.getLastArg(OPT_heap)) 16250b57cec5SDimitry Andric parseNumbers(arg->getValue(), &config->heapReserve, &config->heapCommit); 16260b57cec5SDimitry Andric 16270b57cec5SDimitry Andric // Handle /version 16280b57cec5SDimitry Andric if (auto *arg = args.getLastArg(OPT_version)) 16290b57cec5SDimitry Andric parseVersion(arg->getValue(), &config->majorImageVersion, 16300b57cec5SDimitry Andric &config->minorImageVersion); 16310b57cec5SDimitry Andric 16320b57cec5SDimitry Andric // Handle /subsystem 16330b57cec5SDimitry Andric if (auto *arg = args.getLastArg(OPT_subsystem)) 1634e8d8bef9SDimitry Andric parseSubsystem(arg->getValue(), &config->subsystem, 1635e8d8bef9SDimitry Andric &config->majorSubsystemVersion, 1636e8d8bef9SDimitry Andric &config->minorSubsystemVersion); 1637e8d8bef9SDimitry Andric 1638e8d8bef9SDimitry Andric // Handle /osversion 1639e8d8bef9SDimitry Andric if (auto *arg = args.getLastArg(OPT_osversion)) { 1640e8d8bef9SDimitry Andric parseVersion(arg->getValue(), &config->majorOSVersion, 16410b57cec5SDimitry Andric &config->minorOSVersion); 1642e8d8bef9SDimitry Andric } else { 1643e8d8bef9SDimitry Andric config->majorOSVersion = config->majorSubsystemVersion; 1644e8d8bef9SDimitry Andric config->minorOSVersion = config->minorSubsystemVersion; 1645e8d8bef9SDimitry Andric } 16460b57cec5SDimitry Andric 16470b57cec5SDimitry Andric // Handle /timestamp 16480b57cec5SDimitry Andric if (llvm::opt::Arg *arg = args.getLastArg(OPT_timestamp, OPT_repro)) { 16490b57cec5SDimitry Andric if (arg->getOption().getID() == OPT_repro) { 16500b57cec5SDimitry Andric config->timestamp = 0; 16510b57cec5SDimitry Andric config->repro = true; 16520b57cec5SDimitry Andric } else { 16530b57cec5SDimitry Andric config->repro = false; 16540b57cec5SDimitry Andric StringRef value(arg->getValue()); 16550b57cec5SDimitry Andric if (value.getAsInteger(0, config->timestamp)) 16560b57cec5SDimitry Andric fatal(Twine("invalid timestamp: ") + value + 16570b57cec5SDimitry Andric ". Expected 32-bit integer"); 16580b57cec5SDimitry Andric } 16590b57cec5SDimitry Andric } else { 16600b57cec5SDimitry Andric config->repro = false; 16610b57cec5SDimitry Andric config->timestamp = time(nullptr); 16620b57cec5SDimitry Andric } 16630b57cec5SDimitry Andric 16640b57cec5SDimitry Andric // Handle /alternatename 16650b57cec5SDimitry Andric for (auto *arg : args.filtered(OPT_alternatename)) 16660b57cec5SDimitry Andric parseAlternateName(arg->getValue()); 16670b57cec5SDimitry Andric 16680b57cec5SDimitry Andric // Handle /include 16690b57cec5SDimitry Andric for (auto *arg : args.filtered(OPT_incl)) 16700b57cec5SDimitry Andric addUndefined(arg->getValue()); 16710b57cec5SDimitry Andric 16720b57cec5SDimitry Andric // Handle /implib 16730b57cec5SDimitry Andric if (auto *arg = args.getLastArg(OPT_implib)) 16740b57cec5SDimitry Andric config->implib = arg->getValue(); 16750b57cec5SDimitry Andric 1676*81ad6265SDimitry Andric config->noimplib = args.hasArg(OPT_noimplib); 1677*81ad6265SDimitry Andric 16780b57cec5SDimitry Andric // Handle /opt. 16790b57cec5SDimitry Andric bool doGC = debug == DebugKind::None || args.hasArg(OPT_profile); 1680fe6060f1SDimitry Andric Optional<ICFLevel> icfLevel = None; 1681fe6060f1SDimitry Andric if (args.hasArg(OPT_profile)) 1682fe6060f1SDimitry Andric icfLevel = ICFLevel::None; 16830b57cec5SDimitry Andric unsigned tailMerge = 1; 1684e8d8bef9SDimitry Andric bool ltoDebugPM = false; 16850b57cec5SDimitry Andric for (auto *arg : args.filtered(OPT_opt)) { 16860b57cec5SDimitry Andric std::string str = StringRef(arg->getValue()).lower(); 16870b57cec5SDimitry Andric SmallVector<StringRef, 1> vec; 16880b57cec5SDimitry Andric StringRef(str).split(vec, ','); 16890b57cec5SDimitry Andric for (StringRef s : vec) { 16900b57cec5SDimitry Andric if (s == "ref") { 16910b57cec5SDimitry Andric doGC = true; 16920b57cec5SDimitry Andric } else if (s == "noref") { 16930b57cec5SDimitry Andric doGC = false; 16940b57cec5SDimitry Andric } else if (s == "icf" || s.startswith("icf=")) { 1695fe6060f1SDimitry Andric icfLevel = ICFLevel::All; 1696fe6060f1SDimitry Andric } else if (s == "safeicf") { 1697fe6060f1SDimitry Andric icfLevel = ICFLevel::Safe; 16980b57cec5SDimitry Andric } else if (s == "noicf") { 1699fe6060f1SDimitry Andric icfLevel = ICFLevel::None; 17000b57cec5SDimitry Andric } else if (s == "lldtailmerge") { 17010b57cec5SDimitry Andric tailMerge = 2; 17020b57cec5SDimitry Andric } else if (s == "nolldtailmerge") { 17030b57cec5SDimitry Andric tailMerge = 0; 1704e8d8bef9SDimitry Andric } else if (s == "ltonewpassmanager") { 1705*81ad6265SDimitry Andric /* We always use the new PM. */ 1706e8d8bef9SDimitry Andric } else if (s == "ltodebugpassmanager") { 1707e8d8bef9SDimitry Andric ltoDebugPM = true; 1708e8d8bef9SDimitry Andric } else if (s == "noltodebugpassmanager") { 1709e8d8bef9SDimitry Andric ltoDebugPM = false; 17100b57cec5SDimitry Andric } else if (s.startswith("lldlto=")) { 17110b57cec5SDimitry Andric StringRef optLevel = s.substr(7); 17120b57cec5SDimitry Andric if (optLevel.getAsInteger(10, config->ltoo) || config->ltoo > 3) 17130b57cec5SDimitry Andric error("/opt:lldlto: invalid optimization level: " + optLevel); 17140b57cec5SDimitry Andric } else if (s.startswith("lldltojobs=")) { 17150b57cec5SDimitry Andric StringRef jobs = s.substr(11); 17165ffd83dbSDimitry Andric if (!get_threadpool_strategy(jobs)) 17170b57cec5SDimitry Andric error("/opt:lldltojobs: invalid job count: " + jobs); 17185ffd83dbSDimitry Andric config->thinLTOJobs = jobs.str(); 17190b57cec5SDimitry Andric } else if (s.startswith("lldltopartitions=")) { 17200b57cec5SDimitry Andric StringRef n = s.substr(17); 17210b57cec5SDimitry Andric if (n.getAsInteger(10, config->ltoPartitions) || 17220b57cec5SDimitry Andric config->ltoPartitions == 0) 17230b57cec5SDimitry Andric error("/opt:lldltopartitions: invalid partition count: " + n); 17240b57cec5SDimitry Andric } else if (s != "lbr" && s != "nolbr") 17250b57cec5SDimitry Andric error("/opt: unknown option: " + s); 17260b57cec5SDimitry Andric } 17270b57cec5SDimitry Andric } 17280b57cec5SDimitry Andric 1729fe6060f1SDimitry Andric if (!icfLevel) 1730fe6060f1SDimitry Andric icfLevel = doGC ? ICFLevel::All : ICFLevel::None; 17310b57cec5SDimitry Andric config->doGC = doGC; 1732*81ad6265SDimitry Andric config->doICF = *icfLevel; 1733fe6060f1SDimitry Andric config->tailMerge = 1734fe6060f1SDimitry Andric (tailMerge == 1 && config->doICF != ICFLevel::None) || tailMerge == 2; 1735e8d8bef9SDimitry Andric config->ltoDebugPassManager = ltoDebugPM; 17360b57cec5SDimitry Andric 17370b57cec5SDimitry Andric // Handle /lldsavetemps 17380b57cec5SDimitry Andric if (args.hasArg(OPT_lldsavetemps)) 17390b57cec5SDimitry Andric config->saveTemps = true; 17400b57cec5SDimitry Andric 17410b57cec5SDimitry Andric // Handle /kill-at 17420b57cec5SDimitry Andric if (args.hasArg(OPT_kill_at)) 17430b57cec5SDimitry Andric config->killAt = true; 17440b57cec5SDimitry Andric 17450b57cec5SDimitry Andric // Handle /lldltocache 17460b57cec5SDimitry Andric if (auto *arg = args.getLastArg(OPT_lldltocache)) 17470b57cec5SDimitry Andric config->ltoCache = arg->getValue(); 17480b57cec5SDimitry Andric 17490b57cec5SDimitry Andric // Handle /lldsavecachepolicy 17500b57cec5SDimitry Andric if (auto *arg = args.getLastArg(OPT_lldltocachepolicy)) 17510b57cec5SDimitry Andric config->ltoCachePolicy = CHECK( 17520b57cec5SDimitry Andric parseCachePruningPolicy(arg->getValue()), 17530b57cec5SDimitry Andric Twine("/lldltocachepolicy: invalid cache policy: ") + arg->getValue()); 17540b57cec5SDimitry Andric 17550b57cec5SDimitry Andric // Handle /failifmismatch 17560b57cec5SDimitry Andric for (auto *arg : args.filtered(OPT_failifmismatch)) 17570b57cec5SDimitry Andric checkFailIfMismatch(arg->getValue(), nullptr); 17580b57cec5SDimitry Andric 17590b57cec5SDimitry Andric // Handle /merge 17600b57cec5SDimitry Andric for (auto *arg : args.filtered(OPT_merge)) 17610b57cec5SDimitry Andric parseMerge(arg->getValue()); 17620b57cec5SDimitry Andric 17630b57cec5SDimitry Andric // Add default section merging rules after user rules. User rules take 17640b57cec5SDimitry Andric // precedence, but we will emit a warning if there is a conflict. 17650b57cec5SDimitry Andric parseMerge(".idata=.rdata"); 17660b57cec5SDimitry Andric parseMerge(".didat=.rdata"); 17670b57cec5SDimitry Andric parseMerge(".edata=.rdata"); 17680b57cec5SDimitry Andric parseMerge(".xdata=.rdata"); 17690b57cec5SDimitry Andric parseMerge(".bss=.data"); 17700b57cec5SDimitry Andric 17710b57cec5SDimitry Andric if (config->mingw) { 17720b57cec5SDimitry Andric parseMerge(".ctors=.rdata"); 17730b57cec5SDimitry Andric parseMerge(".dtors=.rdata"); 17740b57cec5SDimitry Andric parseMerge(".CRT=.rdata"); 17750b57cec5SDimitry Andric } 17760b57cec5SDimitry Andric 17770b57cec5SDimitry Andric // Handle /section 17780b57cec5SDimitry Andric for (auto *arg : args.filtered(OPT_section)) 17790b57cec5SDimitry Andric parseSection(arg->getValue()); 17800b57cec5SDimitry Andric 17810b57cec5SDimitry Andric // Handle /align 17820b57cec5SDimitry Andric if (auto *arg = args.getLastArg(OPT_align)) { 17830b57cec5SDimitry Andric parseNumbers(arg->getValue(), &config->align); 17840b57cec5SDimitry Andric if (!isPowerOf2_64(config->align)) 17850b57cec5SDimitry Andric error("/align: not a power of two: " + StringRef(arg->getValue())); 1786480093f4SDimitry Andric if (!args.hasArg(OPT_driver)) 1787480093f4SDimitry Andric warn("/align specified without /driver; image may not run"); 17880b57cec5SDimitry Andric } 17890b57cec5SDimitry Andric 17900b57cec5SDimitry Andric // Handle /aligncomm 17910b57cec5SDimitry Andric for (auto *arg : args.filtered(OPT_aligncomm)) 17920b57cec5SDimitry Andric parseAligncomm(arg->getValue()); 17930b57cec5SDimitry Andric 1794349cc55cSDimitry Andric // Handle /manifestdependency. 1795349cc55cSDimitry Andric for (auto *arg : args.filtered(OPT_manifestdependency)) 1796349cc55cSDimitry Andric config->manifestDependencies.insert(arg->getValue()); 17970b57cec5SDimitry Andric 17980b57cec5SDimitry Andric // Handle /manifest and /manifest: 17990b57cec5SDimitry Andric if (auto *arg = args.getLastArg(OPT_manifest, OPT_manifest_colon)) { 18000b57cec5SDimitry Andric if (arg->getOption().getID() == OPT_manifest) 18010b57cec5SDimitry Andric config->manifest = Configuration::SideBySide; 18020b57cec5SDimitry Andric else 18030b57cec5SDimitry Andric parseManifest(arg->getValue()); 18040b57cec5SDimitry Andric } 18050b57cec5SDimitry Andric 18060b57cec5SDimitry Andric // Handle /manifestuac 18070b57cec5SDimitry Andric if (auto *arg = args.getLastArg(OPT_manifestuac)) 18080b57cec5SDimitry Andric parseManifestUAC(arg->getValue()); 18090b57cec5SDimitry Andric 18100b57cec5SDimitry Andric // Handle /manifestfile 18110b57cec5SDimitry Andric if (auto *arg = args.getLastArg(OPT_manifestfile)) 18120b57cec5SDimitry Andric config->manifestFile = arg->getValue(); 18130b57cec5SDimitry Andric 18140b57cec5SDimitry Andric // Handle /manifestinput 18150b57cec5SDimitry Andric for (auto *arg : args.filtered(OPT_manifestinput)) 18160b57cec5SDimitry Andric config->manifestInput.push_back(arg->getValue()); 18170b57cec5SDimitry Andric 18180b57cec5SDimitry Andric if (!config->manifestInput.empty() && 18190b57cec5SDimitry Andric config->manifest != Configuration::Embed) { 18200b57cec5SDimitry Andric fatal("/manifestinput: requires /manifest:embed"); 18210b57cec5SDimitry Andric } 18220b57cec5SDimitry Andric 18230b57cec5SDimitry Andric config->thinLTOEmitImportsFiles = args.hasArg(OPT_thinlto_emit_imports_files); 18240b57cec5SDimitry Andric config->thinLTOIndexOnly = args.hasArg(OPT_thinlto_index_only) || 18250b57cec5SDimitry Andric args.hasArg(OPT_thinlto_index_only_arg); 18260b57cec5SDimitry Andric config->thinLTOIndexOnlyArg = 18270b57cec5SDimitry Andric args.getLastArgValue(OPT_thinlto_index_only_arg); 18280b57cec5SDimitry Andric config->thinLTOPrefixReplace = 18290b57cec5SDimitry Andric getOldNewOptions(args, OPT_thinlto_prefix_replace); 18300b57cec5SDimitry Andric config->thinLTOObjectSuffixReplace = 18310b57cec5SDimitry Andric getOldNewOptions(args, OPT_thinlto_object_suffix_replace); 183285868e8aSDimitry Andric config->ltoObjPath = args.getLastArgValue(OPT_lto_obj_path); 1833fe6060f1SDimitry Andric config->ltoCSProfileGenerate = args.hasArg(OPT_lto_cs_profile_generate); 1834fe6060f1SDimitry Andric config->ltoCSProfileFile = args.getLastArgValue(OPT_lto_cs_profile_file); 18350b57cec5SDimitry Andric // Handle miscellaneous boolean flags. 1836349cc55cSDimitry Andric config->ltoPGOWarnMismatch = args.hasFlag(OPT_lto_pgo_warn_mismatch, 1837349cc55cSDimitry Andric OPT_lto_pgo_warn_mismatch_no, true); 18380b57cec5SDimitry Andric config->allowBind = args.hasFlag(OPT_allowbind, OPT_allowbind_no, true); 18390b57cec5SDimitry Andric config->allowIsolation = 18400b57cec5SDimitry Andric args.hasFlag(OPT_allowisolation, OPT_allowisolation_no, true); 18410b57cec5SDimitry Andric config->incremental = 18420b57cec5SDimitry Andric args.hasFlag(OPT_incremental, OPT_incremental_no, 1843fe6060f1SDimitry Andric !config->doGC && config->doICF == ICFLevel::None && 1844fe6060f1SDimitry Andric !args.hasArg(OPT_order) && !args.hasArg(OPT_profile)); 18450b57cec5SDimitry Andric config->integrityCheck = 18460b57cec5SDimitry Andric args.hasFlag(OPT_integritycheck, OPT_integritycheck_no, false); 18475ffd83dbSDimitry Andric config->cetCompat = args.hasFlag(OPT_cetcompat, OPT_cetcompat_no, false); 18480b57cec5SDimitry Andric config->nxCompat = args.hasFlag(OPT_nxcompat, OPT_nxcompat_no, true); 18490b57cec5SDimitry Andric for (auto *arg : args.filtered(OPT_swaprun)) 18500b57cec5SDimitry Andric parseSwaprun(arg->getValue()); 18510b57cec5SDimitry Andric config->terminalServerAware = 18520b57cec5SDimitry Andric !config->dll && args.hasFlag(OPT_tsaware, OPT_tsaware_no, true); 18530b57cec5SDimitry Andric config->debugDwarf = debug == DebugKind::Dwarf; 1854fe6060f1SDimitry Andric config->debugGHashes = debug == DebugKind::GHash || debug == DebugKind::Full; 18550b57cec5SDimitry Andric config->debugSymtab = debug == DebugKind::Symtab; 18565ffd83dbSDimitry Andric config->autoImport = 18575ffd83dbSDimitry Andric args.hasFlag(OPT_auto_import, OPT_auto_import_no, config->mingw); 18585ffd83dbSDimitry Andric config->pseudoRelocs = args.hasFlag( 18595ffd83dbSDimitry Andric OPT_runtime_pseudo_reloc, OPT_runtime_pseudo_reloc_no, config->mingw); 1860e8d8bef9SDimitry Andric config->callGraphProfileSort = args.hasFlag( 1861e8d8bef9SDimitry Andric OPT_call_graph_profile_sort, OPT_call_graph_profile_sort_no, true); 1862fe6060f1SDimitry Andric config->stdcallFixup = 1863fe6060f1SDimitry Andric args.hasFlag(OPT_stdcall_fixup, OPT_stdcall_fixup_no, config->mingw); 1864fe6060f1SDimitry Andric config->warnStdcallFixup = !args.hasArg(OPT_stdcall_fixup); 18650b57cec5SDimitry Andric 1866e8d8bef9SDimitry Andric // Don't warn about long section names, such as .debug_info, for mingw or 1867e8d8bef9SDimitry Andric // when -debug:dwarf is requested. 1868480093f4SDimitry Andric if (config->mingw || config->debugDwarf) 1869480093f4SDimitry Andric config->warnLongSectionNames = false; 1870480093f4SDimitry Andric 18715ffd83dbSDimitry Andric config->lldmapFile = getMapFile(args, OPT_lldmap, OPT_lldmap_file); 18725ffd83dbSDimitry Andric config->mapFile = getMapFile(args, OPT_map, OPT_map_file); 18735ffd83dbSDimitry Andric 18745ffd83dbSDimitry Andric if (config->lldmapFile != "" && config->lldmapFile == config->mapFile) { 18755ffd83dbSDimitry Andric warn("/lldmap and /map have the same output file '" + config->mapFile + 18765ffd83dbSDimitry Andric "'.\n>>> ignoring /lldmap"); 18775ffd83dbSDimitry Andric config->lldmapFile.clear(); 18785ffd83dbSDimitry Andric } 18790b57cec5SDimitry Andric 18800b57cec5SDimitry Andric if (config->incremental && args.hasArg(OPT_profile)) { 18810b57cec5SDimitry Andric warn("ignoring '/incremental' due to '/profile' specification"); 18820b57cec5SDimitry Andric config->incremental = false; 18830b57cec5SDimitry Andric } 18840b57cec5SDimitry Andric 18850b57cec5SDimitry Andric if (config->incremental && args.hasArg(OPT_order)) { 18860b57cec5SDimitry Andric warn("ignoring '/incremental' due to '/order' specification"); 18870b57cec5SDimitry Andric config->incremental = false; 18880b57cec5SDimitry Andric } 18890b57cec5SDimitry Andric 18900b57cec5SDimitry Andric if (config->incremental && config->doGC) { 18910b57cec5SDimitry Andric warn("ignoring '/incremental' because REF is enabled; use '/opt:noref' to " 18920b57cec5SDimitry Andric "disable"); 18930b57cec5SDimitry Andric config->incremental = false; 18940b57cec5SDimitry Andric } 18950b57cec5SDimitry Andric 1896fe6060f1SDimitry Andric if (config->incremental && config->doICF != ICFLevel::None) { 18970b57cec5SDimitry Andric warn("ignoring '/incremental' because ICF is enabled; use '/opt:noicf' to " 18980b57cec5SDimitry Andric "disable"); 18990b57cec5SDimitry Andric config->incremental = false; 19000b57cec5SDimitry Andric } 19010b57cec5SDimitry Andric 19020b57cec5SDimitry Andric if (errorCount()) 19030b57cec5SDimitry Andric return; 19040b57cec5SDimitry Andric 19050b57cec5SDimitry Andric std::set<sys::fs::UniqueID> wholeArchives; 19060b57cec5SDimitry Andric for (auto *arg : args.filtered(OPT_wholearchive_file)) 19070b57cec5SDimitry Andric if (Optional<StringRef> path = doFindFile(arg->getValue())) 19080b57cec5SDimitry Andric if (Optional<sys::fs::UniqueID> id = getUniqueID(*path)) 19090b57cec5SDimitry Andric wholeArchives.insert(*id); 19100b57cec5SDimitry Andric 19110b57cec5SDimitry Andric // A predicate returning true if a given path is an argument for 19120b57cec5SDimitry Andric // /wholearchive:, or /wholearchive is enabled globally. 19130b57cec5SDimitry Andric // This function is a bit tricky because "foo.obj /wholearchive:././foo.obj" 19140b57cec5SDimitry Andric // needs to be handled as "/wholearchive:foo.obj foo.obj". 19150b57cec5SDimitry Andric auto isWholeArchive = [&](StringRef path) -> bool { 19160b57cec5SDimitry Andric if (args.hasArg(OPT_wholearchive_flag)) 19170b57cec5SDimitry Andric return true; 19180b57cec5SDimitry Andric if (Optional<sys::fs::UniqueID> id = getUniqueID(path)) 19190b57cec5SDimitry Andric return wholeArchives.count(*id); 19200b57cec5SDimitry Andric return false; 19210b57cec5SDimitry Andric }; 19220b57cec5SDimitry Andric 192385868e8aSDimitry Andric // Create a list of input files. These can be given as OPT_INPUT options 192485868e8aSDimitry Andric // and OPT_wholearchive_file options, and we also need to track OPT_start_lib 192585868e8aSDimitry Andric // and OPT_end_lib. 192685868e8aSDimitry Andric bool inLib = false; 192785868e8aSDimitry Andric for (auto *arg : args) { 192885868e8aSDimitry Andric switch (arg->getOption().getID()) { 192985868e8aSDimitry Andric case OPT_end_lib: 193085868e8aSDimitry Andric if (!inLib) 193185868e8aSDimitry Andric error("stray " + arg->getSpelling()); 193285868e8aSDimitry Andric inLib = false; 193385868e8aSDimitry Andric break; 193485868e8aSDimitry Andric case OPT_start_lib: 193585868e8aSDimitry Andric if (inLib) 193685868e8aSDimitry Andric error("nested " + arg->getSpelling()); 193785868e8aSDimitry Andric inLib = true; 193885868e8aSDimitry Andric break; 193985868e8aSDimitry Andric case OPT_wholearchive_file: 19400b57cec5SDimitry Andric if (Optional<StringRef> path = findFile(arg->getValue())) 194185868e8aSDimitry Andric enqueuePath(*path, true, inLib); 194285868e8aSDimitry Andric break; 194385868e8aSDimitry Andric case OPT_INPUT: 194485868e8aSDimitry Andric if (Optional<StringRef> path = findFile(arg->getValue())) 194585868e8aSDimitry Andric enqueuePath(*path, isWholeArchive(*path), inLib); 194685868e8aSDimitry Andric break; 194785868e8aSDimitry Andric default: 194885868e8aSDimitry Andric // Ignore other options. 194985868e8aSDimitry Andric break; 195085868e8aSDimitry Andric } 195185868e8aSDimitry Andric } 19520b57cec5SDimitry Andric 19530b57cec5SDimitry Andric // Read all input files given via the command line. 19540b57cec5SDimitry Andric run(); 19550b57cec5SDimitry Andric if (errorCount()) 19560b57cec5SDimitry Andric return; 19570b57cec5SDimitry Andric 19580b57cec5SDimitry Andric // We should have inferred a machine type by now from the input files, but if 19590b57cec5SDimitry Andric // not we assume x64. 19600b57cec5SDimitry Andric if (config->machine == IMAGE_FILE_MACHINE_UNKNOWN) { 19610b57cec5SDimitry Andric warn("/machine is not specified. x64 is assumed"); 19620b57cec5SDimitry Andric config->machine = AMD64; 1963*81ad6265SDimitry Andric addWinSysRootLibSearchPaths(); 19640b57cec5SDimitry Andric } 19650b57cec5SDimitry Andric config->wordsize = config->is64() ? 8 : 4; 19660b57cec5SDimitry Andric 1967*81ad6265SDimitry Andric // Process files specified as /defaultlib. These must be processed after 1968*81ad6265SDimitry Andric // addWinSysRootLibSearchPaths(), which is why they are in a separate loop. 1969*81ad6265SDimitry Andric for (auto *arg : args.filtered(OPT_defaultlib)) 1970*81ad6265SDimitry Andric if (Optional<StringRef> path = findLib(arg->getValue())) 1971*81ad6265SDimitry Andric enqueuePath(*path, false, false); 1972*81ad6265SDimitry Andric run(); 1973*81ad6265SDimitry Andric if (errorCount()) 1974*81ad6265SDimitry Andric return; 1975*81ad6265SDimitry Andric 19760b57cec5SDimitry Andric // Handle /safeseh, x86 only, on by default, except for mingw. 1977979e22ffSDimitry Andric if (config->machine == I386) { 1978979e22ffSDimitry Andric config->safeSEH = args.hasFlag(OPT_safeseh, OPT_safeseh_no, !config->mingw); 1979979e22ffSDimitry Andric config->noSEH = args.hasArg(OPT_noseh); 1980979e22ffSDimitry Andric } 19810b57cec5SDimitry Andric 19820b57cec5SDimitry Andric // Handle /functionpadmin 19830b57cec5SDimitry Andric for (auto *arg : args.filtered(OPT_functionpadmin, OPT_functionpadmin_opt)) 19840b57cec5SDimitry Andric parseFunctionPadMin(arg, config->machine); 19850b57cec5SDimitry Andric 1986*81ad6265SDimitry Andric if (tar) { 19870b57cec5SDimitry Andric tar->append("response.txt", 19880b57cec5SDimitry Andric createResponseFile(args, filePaths, 19890b57cec5SDimitry Andric ArrayRef<StringRef>(searchPaths).slice(1))); 1990*81ad6265SDimitry Andric } 19910b57cec5SDimitry Andric 19920b57cec5SDimitry Andric // Handle /largeaddressaware 19930b57cec5SDimitry Andric config->largeAddressAware = args.hasFlag( 19940b57cec5SDimitry Andric OPT_largeaddressaware, OPT_largeaddressaware_no, config->is64()); 19950b57cec5SDimitry Andric 19960b57cec5SDimitry Andric // Handle /highentropyva 19970b57cec5SDimitry Andric config->highEntropyVA = 19980b57cec5SDimitry Andric config->is64() && 19990b57cec5SDimitry Andric args.hasFlag(OPT_highentropyva, OPT_highentropyva_no, true); 20000b57cec5SDimitry Andric 20010b57cec5SDimitry Andric if (!config->dynamicBase && 20020b57cec5SDimitry Andric (config->machine == ARMNT || config->machine == ARM64)) 20030b57cec5SDimitry Andric error("/dynamicbase:no is not compatible with " + 20040b57cec5SDimitry Andric machineToStr(config->machine)); 20050b57cec5SDimitry Andric 20060b57cec5SDimitry Andric // Handle /export 20070b57cec5SDimitry Andric for (auto *arg : args.filtered(OPT_export)) { 20080b57cec5SDimitry Andric Export e = parseExport(arg->getValue()); 20090b57cec5SDimitry Andric if (config->machine == I386) { 20100b57cec5SDimitry Andric if (!isDecorated(e.name)) 201104eeddc0SDimitry Andric e.name = saver().save("_" + e.name); 20120b57cec5SDimitry Andric if (!e.extName.empty() && !isDecorated(e.extName)) 201304eeddc0SDimitry Andric e.extName = saver().save("_" + e.extName); 20140b57cec5SDimitry Andric } 20150b57cec5SDimitry Andric config->exports.push_back(e); 20160b57cec5SDimitry Andric } 20170b57cec5SDimitry Andric 20180b57cec5SDimitry Andric // Handle /def 20190b57cec5SDimitry Andric if (auto *arg = args.getLastArg(OPT_deffile)) { 20200b57cec5SDimitry Andric // parseModuleDefs mutates Config object. 20210b57cec5SDimitry Andric parseModuleDefs(arg->getValue()); 20220b57cec5SDimitry Andric } 20230b57cec5SDimitry Andric 20240b57cec5SDimitry Andric // Handle generation of import library from a def file. 2025480093f4SDimitry Andric if (!args.hasArg(OPT_INPUT, OPT_wholearchive_file)) { 20260b57cec5SDimitry Andric fixupExports(); 2027*81ad6265SDimitry Andric if (!config->noimplib) 20280b57cec5SDimitry Andric createImportLibrary(/*asLib=*/true); 20290b57cec5SDimitry Andric return; 20300b57cec5SDimitry Andric } 20310b57cec5SDimitry Andric 20320b57cec5SDimitry Andric // Windows specific -- if no /subsystem is given, we need to infer 20330b57cec5SDimitry Andric // that from entry point name. Must happen before /entry handling, 20340b57cec5SDimitry Andric // and after the early return when just writing an import library. 20350b57cec5SDimitry Andric if (config->subsystem == IMAGE_SUBSYSTEM_UNKNOWN) { 20360b57cec5SDimitry Andric config->subsystem = inferSubsystem(); 20370b57cec5SDimitry Andric if (config->subsystem == IMAGE_SUBSYSTEM_UNKNOWN) 20380b57cec5SDimitry Andric fatal("subsystem must be defined"); 20390b57cec5SDimitry Andric } 20400b57cec5SDimitry Andric 20410b57cec5SDimitry Andric // Handle /entry and /dll 20420b57cec5SDimitry Andric if (auto *arg = args.getLastArg(OPT_entry)) { 20430b57cec5SDimitry Andric config->entry = addUndefined(mangle(arg->getValue())); 20440b57cec5SDimitry Andric } else if (!config->entry && !config->noEntry) { 20450b57cec5SDimitry Andric if (args.hasArg(OPT_dll)) { 20460b57cec5SDimitry Andric StringRef s = (config->machine == I386) ? "__DllMainCRTStartup@12" 20470b57cec5SDimitry Andric : "_DllMainCRTStartup"; 20480b57cec5SDimitry Andric config->entry = addUndefined(s); 2049480093f4SDimitry Andric } else if (config->driverWdm) { 2050480093f4SDimitry Andric // /driver:wdm implies /entry:_NtProcessStartup 2051480093f4SDimitry Andric config->entry = addUndefined(mangle("_NtProcessStartup")); 20520b57cec5SDimitry Andric } else { 20530b57cec5SDimitry Andric // Windows specific -- If entry point name is not given, we need to 20540b57cec5SDimitry Andric // infer that from user-defined entry name. 20550b57cec5SDimitry Andric StringRef s = findDefaultEntry(); 20560b57cec5SDimitry Andric if (s.empty()) 20570b57cec5SDimitry Andric fatal("entry point must be defined"); 20580b57cec5SDimitry Andric config->entry = addUndefined(s); 20590b57cec5SDimitry Andric log("Entry name inferred: " + s); 20600b57cec5SDimitry Andric } 20610b57cec5SDimitry Andric } 20620b57cec5SDimitry Andric 20630b57cec5SDimitry Andric // Handle /delayload 20640b57cec5SDimitry Andric for (auto *arg : args.filtered(OPT_delayload)) { 20650b57cec5SDimitry Andric config->delayLoads.insert(StringRef(arg->getValue()).lower()); 20660b57cec5SDimitry Andric if (config->machine == I386) { 20670b57cec5SDimitry Andric config->delayLoadHelper = addUndefined("___delayLoadHelper2@8"); 20680b57cec5SDimitry Andric } else { 20690b57cec5SDimitry Andric config->delayLoadHelper = addUndefined("__delayLoadHelper2"); 20700b57cec5SDimitry Andric } 20710b57cec5SDimitry Andric } 20720b57cec5SDimitry Andric 20730b57cec5SDimitry Andric // Set default image name if neither /out or /def set it. 20740b57cec5SDimitry Andric if (config->outputFile.empty()) { 2075480093f4SDimitry Andric config->outputFile = getOutputPath( 2076480093f4SDimitry Andric (*args.filtered(OPT_INPUT, OPT_wholearchive_file).begin())->getValue()); 20770b57cec5SDimitry Andric } 20780b57cec5SDimitry Andric 20790b57cec5SDimitry Andric // Fail early if an output file is not writable. 20800b57cec5SDimitry Andric if (auto e = tryCreateFile(config->outputFile)) { 20810b57cec5SDimitry Andric error("cannot open output file " + config->outputFile + ": " + e.message()); 20820b57cec5SDimitry Andric return; 20830b57cec5SDimitry Andric } 20840b57cec5SDimitry Andric 20850b57cec5SDimitry Andric if (shouldCreatePDB) { 20860b57cec5SDimitry Andric // Put the PDB next to the image if no /pdb flag was passed. 20870b57cec5SDimitry Andric if (config->pdbPath.empty()) { 20880b57cec5SDimitry Andric config->pdbPath = config->outputFile; 20890b57cec5SDimitry Andric sys::path::replace_extension(config->pdbPath, ".pdb"); 20900b57cec5SDimitry Andric } 20910b57cec5SDimitry Andric 20920b57cec5SDimitry Andric // The embedded PDB path should be the absolute path to the PDB if no 20930b57cec5SDimitry Andric // /pdbaltpath flag was passed. 20940b57cec5SDimitry Andric if (config->pdbAltPath.empty()) { 20950b57cec5SDimitry Andric config->pdbAltPath = config->pdbPath; 20960b57cec5SDimitry Andric 20970b57cec5SDimitry Andric // It's important to make the path absolute and remove dots. This path 20980b57cec5SDimitry Andric // will eventually be written into the PE header, and certain Microsoft 20990b57cec5SDimitry Andric // tools won't work correctly if these assumptions are not held. 21000b57cec5SDimitry Andric sys::fs::make_absolute(config->pdbAltPath); 21010b57cec5SDimitry Andric sys::path::remove_dots(config->pdbAltPath); 21020b57cec5SDimitry Andric } else { 21030b57cec5SDimitry Andric // Don't do this earlier, so that Config->OutputFile is ready. 21040b57cec5SDimitry Andric parsePDBAltPath(config->pdbAltPath); 21050b57cec5SDimitry Andric } 21060b57cec5SDimitry Andric } 21070b57cec5SDimitry Andric 21080b57cec5SDimitry Andric // Set default image base if /base is not given. 21090b57cec5SDimitry Andric if (config->imageBase == uint64_t(-1)) 21100b57cec5SDimitry Andric config->imageBase = getDefaultImageBase(); 21110b57cec5SDimitry Andric 2112349cc55cSDimitry Andric ctx.symtab.addSynthetic(mangle("__ImageBase"), nullptr); 21130b57cec5SDimitry Andric if (config->machine == I386) { 2114349cc55cSDimitry Andric ctx.symtab.addAbsolute("___safe_se_handler_table", 0); 2115349cc55cSDimitry Andric ctx.symtab.addAbsolute("___safe_se_handler_count", 0); 21160b57cec5SDimitry Andric } 21170b57cec5SDimitry Andric 2118349cc55cSDimitry Andric ctx.symtab.addAbsolute(mangle("__guard_fids_count"), 0); 2119349cc55cSDimitry Andric ctx.symtab.addAbsolute(mangle("__guard_fids_table"), 0); 2120349cc55cSDimitry Andric ctx.symtab.addAbsolute(mangle("__guard_flags"), 0); 2121349cc55cSDimitry Andric ctx.symtab.addAbsolute(mangle("__guard_iat_count"), 0); 2122349cc55cSDimitry Andric ctx.symtab.addAbsolute(mangle("__guard_iat_table"), 0); 2123349cc55cSDimitry Andric ctx.symtab.addAbsolute(mangle("__guard_longjmp_count"), 0); 2124349cc55cSDimitry Andric ctx.symtab.addAbsolute(mangle("__guard_longjmp_table"), 0); 21250b57cec5SDimitry Andric // Needed for MSVC 2017 15.5 CRT. 2126349cc55cSDimitry Andric ctx.symtab.addAbsolute(mangle("__enclave_config"), 0); 2127fe6060f1SDimitry Andric // Needed for MSVC 2019 16.8 CRT. 2128349cc55cSDimitry Andric ctx.symtab.addAbsolute(mangle("__guard_eh_cont_count"), 0); 2129349cc55cSDimitry Andric ctx.symtab.addAbsolute(mangle("__guard_eh_cont_table"), 0); 21300b57cec5SDimitry Andric 21315ffd83dbSDimitry Andric if (config->pseudoRelocs) { 2132349cc55cSDimitry Andric ctx.symtab.addAbsolute(mangle("__RUNTIME_PSEUDO_RELOC_LIST__"), 0); 2133349cc55cSDimitry Andric ctx.symtab.addAbsolute(mangle("__RUNTIME_PSEUDO_RELOC_LIST_END__"), 0); 21345ffd83dbSDimitry Andric } 21355ffd83dbSDimitry Andric if (config->mingw) { 2136349cc55cSDimitry Andric ctx.symtab.addAbsolute(mangle("__CTOR_LIST__"), 0); 2137349cc55cSDimitry Andric ctx.symtab.addAbsolute(mangle("__DTOR_LIST__"), 0); 21380b57cec5SDimitry Andric } 21390b57cec5SDimitry Andric 21400b57cec5SDimitry Andric // This code may add new undefined symbols to the link, which may enqueue more 21410b57cec5SDimitry Andric // symbol resolution tasks, so we need to continue executing tasks until we 21420b57cec5SDimitry Andric // converge. 21430b57cec5SDimitry Andric do { 21440b57cec5SDimitry Andric // Windows specific -- if entry point is not found, 21450b57cec5SDimitry Andric // search for its mangled names. 21460b57cec5SDimitry Andric if (config->entry) 21470b57cec5SDimitry Andric mangleMaybe(config->entry); 21480b57cec5SDimitry Andric 21490b57cec5SDimitry Andric // Windows specific -- Make sure we resolve all dllexported symbols. 21500b57cec5SDimitry Andric for (Export &e : config->exports) { 21510b57cec5SDimitry Andric if (!e.forwardTo.empty()) 21520b57cec5SDimitry Andric continue; 21530b57cec5SDimitry Andric e.sym = addUndefined(e.name); 21540b57cec5SDimitry Andric if (!e.directives) 21550b57cec5SDimitry Andric e.symbolName = mangleMaybe(e.sym); 21560b57cec5SDimitry Andric } 21570b57cec5SDimitry Andric 21580b57cec5SDimitry Andric // Add weak aliases. Weak aliases is a mechanism to give remaining 21590b57cec5SDimitry Andric // undefined symbols final chance to be resolved successfully. 21600b57cec5SDimitry Andric for (auto pair : config->alternateNames) { 21610b57cec5SDimitry Andric StringRef from = pair.first; 21620b57cec5SDimitry Andric StringRef to = pair.second; 2163349cc55cSDimitry Andric Symbol *sym = ctx.symtab.find(from); 21640b57cec5SDimitry Andric if (!sym) 21650b57cec5SDimitry Andric continue; 21660b57cec5SDimitry Andric if (auto *u = dyn_cast<Undefined>(sym)) 21670b57cec5SDimitry Andric if (!u->weakAlias) 2168349cc55cSDimitry Andric u->weakAlias = ctx.symtab.addUndefined(to); 21690b57cec5SDimitry Andric } 21700b57cec5SDimitry Andric 21710b57cec5SDimitry Andric // If any inputs are bitcode files, the LTO code generator may create 21720b57cec5SDimitry Andric // references to library functions that are not explicit in the bitcode 21730b57cec5SDimitry Andric // file's symbol table. If any of those library functions are defined in a 21740b57cec5SDimitry Andric // bitcode file in an archive member, we need to arrange to use LTO to 21750b57cec5SDimitry Andric // compile those archive members by adding them to the link beforehand. 2176349cc55cSDimitry Andric if (!ctx.bitcodeFileInstances.empty()) 217785868e8aSDimitry Andric for (auto *s : lto::LTO::getRuntimeLibcallSymbols()) 2178349cc55cSDimitry Andric ctx.symtab.addLibcall(s); 21790b57cec5SDimitry Andric 21800b57cec5SDimitry Andric // Windows specific -- if __load_config_used can be resolved, resolve it. 2181349cc55cSDimitry Andric if (ctx.symtab.findUnderscore("_load_config_used")) 21820b57cec5SDimitry Andric addUndefined(mangle("_load_config_used")); 21830b57cec5SDimitry Andric } while (run()); 21840b57cec5SDimitry Andric 21850b57cec5SDimitry Andric if (args.hasArg(OPT_include_optional)) { 21860b57cec5SDimitry Andric // Handle /includeoptional 21870b57cec5SDimitry Andric for (auto *arg : args.filtered(OPT_include_optional)) 21880eae32dcSDimitry Andric if (isa_and_nonnull<LazyArchive>(ctx.symtab.find(arg->getValue()))) 21890b57cec5SDimitry Andric addUndefined(arg->getValue()); 21900b57cec5SDimitry Andric while (run()); 21910b57cec5SDimitry Andric } 21920b57cec5SDimitry Andric 2193e8d8bef9SDimitry Andric // Create wrapped symbols for -wrap option. 2194349cc55cSDimitry Andric std::vector<WrappedSymbol> wrapped = addWrappedSymbols(ctx, args); 2195e8d8bef9SDimitry Andric // Load more object files that might be needed for wrapped symbols. 2196e8d8bef9SDimitry Andric if (!wrapped.empty()) 2197e8d8bef9SDimitry Andric while (run()); 2198e8d8bef9SDimitry Andric 2199fe6060f1SDimitry Andric if (config->autoImport || config->stdcallFixup) { 22005ffd83dbSDimitry Andric // MinGW specific. 22010b57cec5SDimitry Andric // Load any further object files that might be needed for doing automatic 2202fe6060f1SDimitry Andric // imports, and do stdcall fixups. 22030b57cec5SDimitry Andric // 22040b57cec5SDimitry Andric // For cases with no automatically imported symbols, this iterates once 22050b57cec5SDimitry Andric // over the symbol table and doesn't do anything. 22060b57cec5SDimitry Andric // 22070b57cec5SDimitry Andric // For the normal case with a few automatically imported symbols, this 22080b57cec5SDimitry Andric // should only need to be run once, since each new object file imported 22090b57cec5SDimitry Andric // is an import library and wouldn't add any new undefined references, 22100b57cec5SDimitry Andric // but there's nothing stopping the __imp_ symbols from coming from a 22110b57cec5SDimitry Andric // normal object file as well (although that won't be used for the 22120b57cec5SDimitry Andric // actual autoimport later on). If this pass adds new undefined references, 22130b57cec5SDimitry Andric // we won't iterate further to resolve them. 2214fe6060f1SDimitry Andric // 2215fe6060f1SDimitry Andric // If stdcall fixups only are needed for loading import entries from 2216fe6060f1SDimitry Andric // a DLL without import library, this also just needs running once. 2217fe6060f1SDimitry Andric // If it ends up pulling in more object files from static libraries, 2218fe6060f1SDimitry Andric // (and maybe doing more stdcall fixups along the way), this would need 2219fe6060f1SDimitry Andric // to loop these two calls. 2220349cc55cSDimitry Andric ctx.symtab.loadMinGWSymbols(); 22210b57cec5SDimitry Andric run(); 22220b57cec5SDimitry Andric } 22230b57cec5SDimitry Andric 222485868e8aSDimitry Andric // At this point, we should not have any symbols that cannot be resolved. 222585868e8aSDimitry Andric // If we are going to do codegen for link-time optimization, check for 222685868e8aSDimitry Andric // unresolvable symbols first, so we don't spend time generating code that 222785868e8aSDimitry Andric // will fail to link anyway. 2228349cc55cSDimitry Andric if (!ctx.bitcodeFileInstances.empty() && !config->forceUnresolved) 2229349cc55cSDimitry Andric ctx.symtab.reportUnresolvable(); 22300b57cec5SDimitry Andric if (errorCount()) 22310b57cec5SDimitry Andric return; 22320b57cec5SDimitry Andric 2233fe6060f1SDimitry Andric config->hadExplicitExports = !config->exports.empty(); 2234fe6060f1SDimitry Andric if (config->mingw) { 2235fe6060f1SDimitry Andric // In MinGW, all symbols are automatically exported if no symbols 2236fe6060f1SDimitry Andric // are chosen to be exported. 2237fe6060f1SDimitry Andric maybeExportMinGWSymbols(args); 2238fe6060f1SDimitry Andric } 2239fe6060f1SDimitry Andric 224085868e8aSDimitry Andric // Do LTO by compiling bitcode input files to a set of native COFF files then 224185868e8aSDimitry Andric // link those files (unless -thinlto-index-only was given, in which case we 224285868e8aSDimitry Andric // resolve symbols and write indices, but don't generate native code or link). 2243349cc55cSDimitry Andric ctx.symtab.compileBitcodeFiles(); 224485868e8aSDimitry Andric 224585868e8aSDimitry Andric // If -thinlto-index-only is given, we should create only "index 224685868e8aSDimitry Andric // files" and not object files. Index file creation is already done 2247349cc55cSDimitry Andric // in compileBitcodeFiles, so we are done if that's the case. 224885868e8aSDimitry Andric if (config->thinLTOIndexOnly) 224985868e8aSDimitry Andric return; 225085868e8aSDimitry Andric 225185868e8aSDimitry Andric // If we generated native object files from bitcode files, this resolves 225285868e8aSDimitry Andric // references to the symbols we use from them. 225385868e8aSDimitry Andric run(); 225485868e8aSDimitry Andric 2255e8d8bef9SDimitry Andric // Apply symbol renames for -wrap. 2256e8d8bef9SDimitry Andric if (!wrapped.empty()) 2257349cc55cSDimitry Andric wrapSymbols(ctx, wrapped); 2258e8d8bef9SDimitry Andric 225985868e8aSDimitry Andric // Resolve remaining undefined symbols and warn about imported locals. 2260349cc55cSDimitry Andric ctx.symtab.resolveRemainingUndefines(); 226185868e8aSDimitry Andric if (errorCount()) 226285868e8aSDimitry Andric return; 226385868e8aSDimitry Andric 22640b57cec5SDimitry Andric if (config->mingw) { 22650b57cec5SDimitry Andric // Make sure the crtend.o object is the last object file. This object 22660b57cec5SDimitry Andric // file can contain terminating section chunks that need to be placed 22670b57cec5SDimitry Andric // last. GNU ld processes files and static libraries explicitly in the 22680b57cec5SDimitry Andric // order provided on the command line, while lld will pull in needed 22690b57cec5SDimitry Andric // files from static libraries only after the last object file on the 22700b57cec5SDimitry Andric // command line. 2271349cc55cSDimitry Andric for (auto i = ctx.objFileInstances.begin(), e = ctx.objFileInstances.end(); 22720b57cec5SDimitry Andric i != e; i++) { 22730b57cec5SDimitry Andric ObjFile *file = *i; 22740b57cec5SDimitry Andric if (isCrtend(file->getName())) { 2275349cc55cSDimitry Andric ctx.objFileInstances.erase(i); 2276349cc55cSDimitry Andric ctx.objFileInstances.push_back(file); 22770b57cec5SDimitry Andric break; 22780b57cec5SDimitry Andric } 22790b57cec5SDimitry Andric } 22800b57cec5SDimitry Andric } 22810b57cec5SDimitry Andric 22820b57cec5SDimitry Andric // Windows specific -- when we are creating a .dll file, we also 228385868e8aSDimitry Andric // need to create a .lib file. In MinGW mode, we only do that when the 228485868e8aSDimitry Andric // -implib option is given explicitly, for compatibility with GNU ld. 22850b57cec5SDimitry Andric if (!config->exports.empty() || config->dll) { 22860b57cec5SDimitry Andric fixupExports(); 2287*81ad6265SDimitry Andric if (!config->noimplib && (!config->mingw || !config->implib.empty())) 22880b57cec5SDimitry Andric createImportLibrary(/*asLib=*/false); 22890b57cec5SDimitry Andric assignExportOrdinals(); 22900b57cec5SDimitry Andric } 22910b57cec5SDimitry Andric 22920b57cec5SDimitry Andric // Handle /output-def (MinGW specific). 22930b57cec5SDimitry Andric if (auto *arg = args.getLastArg(OPT_output_def)) 22940b57cec5SDimitry Andric writeDefFile(arg->getValue()); 22950b57cec5SDimitry Andric 22960b57cec5SDimitry Andric // Set extra alignment for .comm symbols 22970b57cec5SDimitry Andric for (auto pair : config->alignComm) { 22980b57cec5SDimitry Andric StringRef name = pair.first; 22990b57cec5SDimitry Andric uint32_t alignment = pair.second; 23000b57cec5SDimitry Andric 2301349cc55cSDimitry Andric Symbol *sym = ctx.symtab.find(name); 23020b57cec5SDimitry Andric if (!sym) { 23030b57cec5SDimitry Andric warn("/aligncomm symbol " + name + " not found"); 23040b57cec5SDimitry Andric continue; 23050b57cec5SDimitry Andric } 23060b57cec5SDimitry Andric 23070b57cec5SDimitry Andric // If the symbol isn't common, it must have been replaced with a regular 23080b57cec5SDimitry Andric // symbol, which will carry its own alignment. 23090b57cec5SDimitry Andric auto *dc = dyn_cast<DefinedCommon>(sym); 23100b57cec5SDimitry Andric if (!dc) 23110b57cec5SDimitry Andric continue; 23120b57cec5SDimitry Andric 23130b57cec5SDimitry Andric CommonChunk *c = dc->getChunk(); 23140b57cec5SDimitry Andric c->setAlignment(std::max(c->getAlignment(), alignment)); 23150b57cec5SDimitry Andric } 23160b57cec5SDimitry Andric 2317349cc55cSDimitry Andric // Windows specific -- Create an embedded or side-by-side manifest. 2318349cc55cSDimitry Andric // /manifestdependency: enables /manifest unless an explicit /manifest:no is 2319349cc55cSDimitry Andric // also passed. 2320349cc55cSDimitry Andric if (config->manifest == Configuration::Embed) 2321349cc55cSDimitry Andric addBuffer(createManifestRes(), false, false); 2322349cc55cSDimitry Andric else if (config->manifest == Configuration::SideBySide || 2323349cc55cSDimitry Andric (config->manifest == Configuration::Default && 2324349cc55cSDimitry Andric !config->manifestDependencies.empty())) 23250b57cec5SDimitry Andric createSideBySideManifest(); 23260b57cec5SDimitry Andric 23270b57cec5SDimitry Andric // Handle /order. We want to do this at this moment because we 23280b57cec5SDimitry Andric // need a complete list of comdat sections to warn on nonexistent 23290b57cec5SDimitry Andric // functions. 2330e8d8bef9SDimitry Andric if (auto *arg = args.getLastArg(OPT_order)) { 2331e8d8bef9SDimitry Andric if (args.hasArg(OPT_call_graph_ordering_file)) 2332e8d8bef9SDimitry Andric error("/order and /call-graph-order-file may not be used together"); 2333349cc55cSDimitry Andric parseOrderFile(ctx, arg->getValue()); 2334e8d8bef9SDimitry Andric config->callGraphProfileSort = false; 2335e8d8bef9SDimitry Andric } 2336e8d8bef9SDimitry Andric 2337e8d8bef9SDimitry Andric // Handle /call-graph-ordering-file and /call-graph-profile-sort (default on). 2338e8d8bef9SDimitry Andric if (config->callGraphProfileSort) { 2339e8d8bef9SDimitry Andric if (auto *arg = args.getLastArg(OPT_call_graph_ordering_file)) { 2340349cc55cSDimitry Andric parseCallGraphFile(ctx, arg->getValue()); 2341e8d8bef9SDimitry Andric } 2342349cc55cSDimitry Andric readCallGraphsFromObjectFiles(ctx); 2343e8d8bef9SDimitry Andric } 2344e8d8bef9SDimitry Andric 2345e8d8bef9SDimitry Andric // Handle /print-symbol-order. 2346e8d8bef9SDimitry Andric if (auto *arg = args.getLastArg(OPT_print_symbol_order)) 2347e8d8bef9SDimitry Andric config->printSymbolOrder = arg->getValue(); 23480b57cec5SDimitry Andric 23490b57cec5SDimitry Andric // Identify unreferenced COMDAT sections. 2350fe6060f1SDimitry Andric if (config->doGC) { 2351fe6060f1SDimitry Andric if (config->mingw) { 2352fe6060f1SDimitry Andric // markLive doesn't traverse .eh_frame, but the personality function is 2353fe6060f1SDimitry Andric // only reached that way. The proper solution would be to parse and 2354fe6060f1SDimitry Andric // traverse the .eh_frame section, like the ELF linker does. 2355fe6060f1SDimitry Andric // For now, just manually try to retain the known possible personality 2356fe6060f1SDimitry Andric // functions. This doesn't bring in more object files, but only marks 2357fe6060f1SDimitry Andric // functions that already have been included to be retained. 2358fe6060f1SDimitry Andric for (const char *n : {"__gxx_personality_v0", "__gcc_personality_v0"}) { 2359349cc55cSDimitry Andric Defined *d = dyn_cast_or_null<Defined>(ctx.symtab.findUnderscore(n)); 2360fe6060f1SDimitry Andric if (d && !d->isGCRoot) { 2361fe6060f1SDimitry Andric d->isGCRoot = true; 2362fe6060f1SDimitry Andric config->gcroot.push_back(d); 2363fe6060f1SDimitry Andric } 2364fe6060f1SDimitry Andric } 2365fe6060f1SDimitry Andric } 2366fe6060f1SDimitry Andric 2367349cc55cSDimitry Andric markLive(ctx); 2368fe6060f1SDimitry Andric } 23690b57cec5SDimitry Andric 23700b57cec5SDimitry Andric // Needs to happen after the last call to addFile(). 237185868e8aSDimitry Andric convertResources(); 23720b57cec5SDimitry Andric 23730b57cec5SDimitry Andric // Identify identical COMDAT sections to merge them. 2374fe6060f1SDimitry Andric if (config->doICF != ICFLevel::None) { 2375349cc55cSDimitry Andric findKeepUniqueSections(ctx); 2376349cc55cSDimitry Andric doICF(ctx, config->doICF); 23770b57cec5SDimitry Andric } 23780b57cec5SDimitry Andric 23790b57cec5SDimitry Andric // Write the result. 2380349cc55cSDimitry Andric writeResult(ctx); 23810b57cec5SDimitry Andric 23820b57cec5SDimitry Andric // Stop early so we can print the results. 23835ffd83dbSDimitry Andric rootTimer.stop(); 23840b57cec5SDimitry Andric if (config->showTiming) 2385349cc55cSDimitry Andric ctx.rootTimer.print(); 23860b57cec5SDimitry Andric } 23870b57cec5SDimitry Andric 23880b57cec5SDimitry Andric } // namespace coff 23890b57cec5SDimitry Andric } // namespace lld 2390