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" 21bdd1243dSDimitry Andric #include "lld/Common/CommonLinkerContext.h" 220b57cec5SDimitry Andric #include "lld/Common/Driver.h" 230b57cec5SDimitry Andric #include "lld/Common/Filesystem.h" 240b57cec5SDimitry Andric #include "lld/Common/Timer.h" 250b57cec5SDimitry Andric #include "lld/Common/Version.h" 2681ad6265SDimitry Andric #include "llvm/ADT/IntrusiveRefCntPtr.h" 270b57cec5SDimitry Andric #include "llvm/ADT/StringSwitch.h" 2881ad6265SDimitry Andric #include "llvm/ADT/Triple.h" 290b57cec5SDimitry Andric #include "llvm/BinaryFormat/Magic.h" 30e8d8bef9SDimitry Andric #include "llvm/Config/llvm-config.h" 3185868e8aSDimitry Andric #include "llvm/LTO/LTO.h" 320b57cec5SDimitry Andric #include "llvm/Object/ArchiveWriter.h" 330b57cec5SDimitry Andric #include "llvm/Object/COFFImportFile.h" 340b57cec5SDimitry Andric #include "llvm/Object/COFFModuleDefinition.h" 350b57cec5SDimitry Andric #include "llvm/Object/WindowsMachineFlag.h" 360b57cec5SDimitry Andric #include "llvm/Option/Arg.h" 370b57cec5SDimitry Andric #include "llvm/Option/ArgList.h" 380b57cec5SDimitry Andric #include "llvm/Option/Option.h" 39e8d8bef9SDimitry Andric #include "llvm/Support/BinaryStreamReader.h" 40480093f4SDimitry Andric #include "llvm/Support/CommandLine.h" 410b57cec5SDimitry Andric #include "llvm/Support/Debug.h" 420b57cec5SDimitry Andric #include "llvm/Support/LEB128.h" 430b57cec5SDimitry Andric #include "llvm/Support/MathExtras.h" 445ffd83dbSDimitry Andric #include "llvm/Support/Parallel.h" 450b57cec5SDimitry Andric #include "llvm/Support/Path.h" 460b57cec5SDimitry Andric #include "llvm/Support/Process.h" 470b57cec5SDimitry Andric #include "llvm/Support/TarWriter.h" 480b57cec5SDimitry Andric #include "llvm/Support/TargetSelect.h" 4981ad6265SDimitry Andric #include "llvm/Support/VirtualFileSystem.h" 500b57cec5SDimitry Andric #include "llvm/Support/raw_ostream.h" 510b57cec5SDimitry Andric #include "llvm/ToolDrivers/llvm-lib/LibDriver.h" 520b57cec5SDimitry Andric #include <algorithm> 530b57cec5SDimitry Andric #include <future> 540b57cec5SDimitry Andric #include <memory> 55bdd1243dSDimitry Andric #include <optional> 560b57cec5SDimitry Andric 570b57cec5SDimitry Andric using namespace llvm; 580b57cec5SDimitry Andric using namespace llvm::object; 590b57cec5SDimitry Andric using namespace llvm::COFF; 60fe6060f1SDimitry Andric using namespace llvm::sys; 610b57cec5SDimitry Andric 62bdd1243dSDimitry Andric namespace lld::coff { 630b57cec5SDimitry Andric 6404eeddc0SDimitry Andric bool link(ArrayRef<const char *> args, llvm::raw_ostream &stdoutOS, 6504eeddc0SDimitry Andric llvm::raw_ostream &stderrOS, bool exitEarly, bool disableOutput) { 6604eeddc0SDimitry Andric // This driver-specific context will be freed later by lldMain(). 6704eeddc0SDimitry Andric auto *ctx = new COFFLinkerContext; 68480093f4SDimitry Andric 6904eeddc0SDimitry Andric ctx->e.initialize(stdoutOS, stderrOS, exitEarly, disableOutput); 7004eeddc0SDimitry Andric ctx->e.logName = args::getFilenameWithoutExe(args[0]); 7104eeddc0SDimitry Andric ctx->e.errorLimitExceededMsg = "too many errors emitted, stopping now" 720b57cec5SDimitry Andric " (use /errorlimit:0 to see all errors)"; 7385868e8aSDimitry Andric 74bdd1243dSDimitry Andric ctx->driver.linkerMain(args); 750b57cec5SDimitry Andric 7604eeddc0SDimitry Andric return errorCount() == 0; 770b57cec5SDimitry Andric } 780b57cec5SDimitry Andric 790b57cec5SDimitry Andric // Parse options of the form "old;new". 800b57cec5SDimitry Andric static std::pair<StringRef, StringRef> getOldNewOptions(opt::InputArgList &args, 810b57cec5SDimitry Andric unsigned id) { 820b57cec5SDimitry Andric auto *arg = args.getLastArg(id); 830b57cec5SDimitry Andric if (!arg) 840b57cec5SDimitry Andric return {"", ""}; 850b57cec5SDimitry Andric 860b57cec5SDimitry Andric StringRef s = arg->getValue(); 870b57cec5SDimitry Andric std::pair<StringRef, StringRef> ret = s.split(';'); 880b57cec5SDimitry Andric if (ret.second.empty()) 890b57cec5SDimitry Andric error(arg->getSpelling() + " expects 'old;new' format, but got " + s); 900b57cec5SDimitry Andric return ret; 910b57cec5SDimitry Andric } 920b57cec5SDimitry Andric 93480093f4SDimitry Andric // Drop directory components and replace extension with 94480093f4SDimitry Andric // ".exe", ".dll" or ".sys". 95bdd1243dSDimitry Andric static std::string getOutputPath(StringRef path, bool isDll, bool isDriver) { 96480093f4SDimitry Andric StringRef ext = ".exe"; 97bdd1243dSDimitry Andric if (isDll) 98480093f4SDimitry Andric ext = ".dll"; 99bdd1243dSDimitry Andric else if (isDriver) 100480093f4SDimitry Andric ext = ".sys"; 101480093f4SDimitry Andric 102480093f4SDimitry Andric return (sys::path::stem(path) + ext).str(); 1030b57cec5SDimitry Andric } 1040b57cec5SDimitry Andric 1050b57cec5SDimitry Andric // Returns true if S matches /crtend.?\.o$/. 1060b57cec5SDimitry Andric static bool isCrtend(StringRef s) { 1070b57cec5SDimitry Andric if (!s.endswith(".o")) 1080b57cec5SDimitry Andric return false; 1090b57cec5SDimitry Andric s = s.drop_back(2); 1100b57cec5SDimitry Andric if (s.endswith("crtend")) 1110b57cec5SDimitry Andric return true; 1120b57cec5SDimitry Andric return !s.empty() && s.drop_back().endswith("crtend"); 1130b57cec5SDimitry Andric } 1140b57cec5SDimitry Andric 1150b57cec5SDimitry Andric // ErrorOr is not default constructible, so it cannot be used as the type 1160b57cec5SDimitry Andric // parameter of a future. 1170b57cec5SDimitry Andric // FIXME: We could open the file in createFutureForFile and avoid needing to 1180b57cec5SDimitry Andric // return an error here, but for the moment that would cost us a file descriptor 1190b57cec5SDimitry Andric // (a limited resource on Windows) for the duration that the future is pending. 1200b57cec5SDimitry Andric using MBErrPair = std::pair<std::unique_ptr<MemoryBuffer>, std::error_code>; 1210b57cec5SDimitry Andric 1220b57cec5SDimitry Andric // Create a std::future that opens and maps a file using the best strategy for 1230b57cec5SDimitry Andric // the host platform. 1240b57cec5SDimitry Andric static std::future<MBErrPair> createFutureForFile(std::string path) { 125fe6060f1SDimitry Andric #if _WIN64 1260b57cec5SDimitry Andric // On Windows, file I/O is relatively slow so it is best to do this 127fe6060f1SDimitry Andric // asynchronously. But 32-bit has issues with potentially launching tons 128fe6060f1SDimitry Andric // of threads 1290b57cec5SDimitry Andric auto strategy = std::launch::async; 1300b57cec5SDimitry Andric #else 1310b57cec5SDimitry Andric auto strategy = std::launch::deferred; 1320b57cec5SDimitry Andric #endif 1330b57cec5SDimitry Andric return std::async(strategy, [=]() { 134fe6060f1SDimitry Andric auto mbOrErr = MemoryBuffer::getFile(path, /*IsText=*/false, 135fe6060f1SDimitry Andric /*RequiresNullTerminator=*/false); 1360b57cec5SDimitry Andric if (!mbOrErr) 1370b57cec5SDimitry Andric return MBErrPair{nullptr, mbOrErr.getError()}; 1380b57cec5SDimitry Andric return MBErrPair{std::move(*mbOrErr), std::error_code()}; 1390b57cec5SDimitry Andric }); 1400b57cec5SDimitry Andric } 1410b57cec5SDimitry Andric 1420b57cec5SDimitry Andric // Symbol names are mangled by prepending "_" on x86. 143bdd1243dSDimitry Andric StringRef LinkerDriver::mangle(StringRef sym) { 144bdd1243dSDimitry Andric assert(ctx.config.machine != IMAGE_FILE_MACHINE_UNKNOWN); 145bdd1243dSDimitry Andric if (ctx.config.machine == I386) 14604eeddc0SDimitry Andric return saver().save("_" + sym); 1470b57cec5SDimitry Andric return sym; 1480b57cec5SDimitry Andric } 1490b57cec5SDimitry Andric 150bdd1243dSDimitry Andric llvm::Triple::ArchType LinkerDriver::getArch() { 151bdd1243dSDimitry Andric switch (ctx.config.machine) { 15281ad6265SDimitry Andric case I386: 15381ad6265SDimitry Andric return llvm::Triple::ArchType::x86; 15481ad6265SDimitry Andric case AMD64: 15581ad6265SDimitry Andric return llvm::Triple::ArchType::x86_64; 15681ad6265SDimitry Andric case ARMNT: 15781ad6265SDimitry Andric return llvm::Triple::ArchType::arm; 15881ad6265SDimitry Andric case ARM64: 15981ad6265SDimitry Andric return llvm::Triple::ArchType::aarch64; 16081ad6265SDimitry Andric default: 16181ad6265SDimitry Andric return llvm::Triple::ArchType::UnknownArch; 16281ad6265SDimitry Andric } 16381ad6265SDimitry Andric } 16481ad6265SDimitry Andric 165349cc55cSDimitry Andric bool LinkerDriver::findUnderscoreMangle(StringRef sym) { 166349cc55cSDimitry Andric Symbol *s = ctx.symtab.findMangle(mangle(sym)); 1670b57cec5SDimitry Andric return s && !isa<Undefined>(s); 1680b57cec5SDimitry Andric } 1690b57cec5SDimitry Andric 1700b57cec5SDimitry Andric MemoryBufferRef LinkerDriver::takeBuffer(std::unique_ptr<MemoryBuffer> mb) { 1710b57cec5SDimitry Andric MemoryBufferRef mbref = *mb; 1720b57cec5SDimitry Andric make<std::unique_ptr<MemoryBuffer>>(std::move(mb)); // take ownership 1730b57cec5SDimitry Andric 174bdd1243dSDimitry Andric if (ctx.driver.tar) 175bdd1243dSDimitry Andric ctx.driver.tar->append(relativeToRoot(mbref.getBufferIdentifier()), 1760b57cec5SDimitry Andric mbref.getBuffer()); 1770b57cec5SDimitry Andric return mbref; 1780b57cec5SDimitry Andric } 1790b57cec5SDimitry Andric 1800b57cec5SDimitry Andric void LinkerDriver::addBuffer(std::unique_ptr<MemoryBuffer> mb, 18185868e8aSDimitry Andric bool wholeArchive, bool lazy) { 1820b57cec5SDimitry Andric StringRef filename = mb->getBufferIdentifier(); 1830b57cec5SDimitry Andric 1840b57cec5SDimitry Andric MemoryBufferRef mbref = takeBuffer(std::move(mb)); 1850b57cec5SDimitry Andric filePaths.push_back(filename); 1860b57cec5SDimitry Andric 1870b57cec5SDimitry Andric // File type is detected by contents, not by file extension. 1880b57cec5SDimitry Andric switch (identify_magic(mbref.getBuffer())) { 1890b57cec5SDimitry Andric case file_magic::windows_resource: 1900b57cec5SDimitry Andric resources.push_back(mbref); 1910b57cec5SDimitry Andric break; 1920b57cec5SDimitry Andric case file_magic::archive: 1930b57cec5SDimitry Andric if (wholeArchive) { 1940b57cec5SDimitry Andric std::unique_ptr<Archive> file = 1950b57cec5SDimitry Andric CHECK(Archive::create(mbref), filename + ": failed to parse archive"); 1960b57cec5SDimitry Andric Archive *archive = file.get(); 1970b57cec5SDimitry Andric make<std::unique_ptr<Archive>>(std::move(file)); // take ownership 1980b57cec5SDimitry Andric 19985868e8aSDimitry Andric int memberIndex = 0; 2000b57cec5SDimitry Andric for (MemoryBufferRef m : getArchiveMembers(archive)) 20185868e8aSDimitry Andric addArchiveBuffer(m, "<whole-archive>", filename, memberIndex++); 2020b57cec5SDimitry Andric return; 2030b57cec5SDimitry Andric } 204349cc55cSDimitry Andric ctx.symtab.addFile(make<ArchiveFile>(ctx, mbref)); 2050b57cec5SDimitry Andric break; 2060b57cec5SDimitry Andric case file_magic::bitcode: 20704eeddc0SDimitry Andric ctx.symtab.addFile(make<BitcodeFile>(ctx, mbref, "", 0, lazy)); 2080b57cec5SDimitry Andric break; 2090b57cec5SDimitry Andric case file_magic::coff_object: 2100b57cec5SDimitry Andric case file_magic::coff_import_library: 21104eeddc0SDimitry Andric ctx.symtab.addFile(make<ObjFile>(ctx, mbref, lazy)); 2120b57cec5SDimitry Andric break; 2130b57cec5SDimitry Andric case file_magic::pdb: 214349cc55cSDimitry Andric ctx.symtab.addFile(make<PDBInputFile>(ctx, mbref)); 2150b57cec5SDimitry Andric break; 2160b57cec5SDimitry Andric case file_magic::coff_cl_gl_object: 2170b57cec5SDimitry Andric error(filename + ": is not a native COFF file. Recompile without /GL"); 2180b57cec5SDimitry Andric break; 2190b57cec5SDimitry Andric case file_magic::pecoff_executable: 220bdd1243dSDimitry Andric if (ctx.config.mingw) { 221349cc55cSDimitry Andric ctx.symtab.addFile(make<DLLFile>(ctx, mbref)); 222fe6060f1SDimitry Andric break; 223fe6060f1SDimitry Andric } 224fe6060f1SDimitry Andric if (filename.endswith_insensitive(".dll")) { 2250b57cec5SDimitry Andric error(filename + ": bad file type. Did you specify a DLL instead of an " 2260b57cec5SDimitry Andric "import library?"); 2270b57cec5SDimitry Andric break; 2280b57cec5SDimitry Andric } 229bdd1243dSDimitry Andric [[fallthrough]]; 2300b57cec5SDimitry Andric default: 2310b57cec5SDimitry Andric error(mbref.getBufferIdentifier() + ": unknown file type"); 2320b57cec5SDimitry Andric break; 2330b57cec5SDimitry Andric } 2340b57cec5SDimitry Andric } 2350b57cec5SDimitry Andric 23685868e8aSDimitry Andric void LinkerDriver::enqueuePath(StringRef path, bool wholeArchive, bool lazy) { 2375ffd83dbSDimitry Andric auto future = std::make_shared<std::future<MBErrPair>>( 2385ffd83dbSDimitry Andric createFutureForFile(std::string(path))); 2395ffd83dbSDimitry Andric std::string pathStr = std::string(path); 2400b57cec5SDimitry Andric enqueueTask([=]() { 2410b57cec5SDimitry Andric auto mbOrErr = future->get(); 2420b57cec5SDimitry Andric if (mbOrErr.second) { 2430b57cec5SDimitry Andric std::string msg = 2440b57cec5SDimitry Andric "could not open '" + pathStr + "': " + mbOrErr.second.message(); 2450b57cec5SDimitry Andric // Check if the filename is a typo for an option flag. OptTable thinks 2460b57cec5SDimitry Andric // that all args that are not known options and that start with / are 2470b57cec5SDimitry Andric // filenames, but e.g. `/nodefaultlibs` is more likely a typo for 2480b57cec5SDimitry Andric // the option `/nodefaultlib` than a reference to a file in the root 2490b57cec5SDimitry Andric // directory. 2500b57cec5SDimitry Andric std::string nearest; 251bdd1243dSDimitry Andric if (ctx.optTable.findNearest(pathStr, nearest) > 1) 2520b57cec5SDimitry Andric error(msg); 2530b57cec5SDimitry Andric else 2540b57cec5SDimitry Andric error(msg + "; did you mean '" + nearest + "'"); 2550b57cec5SDimitry Andric } else 256bdd1243dSDimitry Andric ctx.driver.addBuffer(std::move(mbOrErr.first), wholeArchive, lazy); 2570b57cec5SDimitry Andric }); 2580b57cec5SDimitry Andric } 2590b57cec5SDimitry Andric 2600b57cec5SDimitry Andric void LinkerDriver::addArchiveBuffer(MemoryBufferRef mb, StringRef symName, 2610b57cec5SDimitry Andric StringRef parentName, 2620b57cec5SDimitry Andric uint64_t offsetInArchive) { 2630b57cec5SDimitry Andric file_magic magic = identify_magic(mb.getBuffer()); 2640b57cec5SDimitry Andric if (magic == file_magic::coff_import_library) { 265349cc55cSDimitry Andric InputFile *imp = make<ImportFile>(ctx, mb); 2660b57cec5SDimitry Andric imp->parentName = parentName; 267349cc55cSDimitry Andric ctx.symtab.addFile(imp); 2680b57cec5SDimitry Andric return; 2690b57cec5SDimitry Andric } 2700b57cec5SDimitry Andric 2710b57cec5SDimitry Andric InputFile *obj; 2720b57cec5SDimitry Andric if (magic == file_magic::coff_object) { 273349cc55cSDimitry Andric obj = make<ObjFile>(ctx, mb); 2740b57cec5SDimitry Andric } else if (magic == file_magic::bitcode) { 27504eeddc0SDimitry Andric obj = 27604eeddc0SDimitry Andric make<BitcodeFile>(ctx, mb, parentName, offsetInArchive, /*lazy=*/false); 277bdd1243dSDimitry Andric } else if (magic == file_magic::coff_cl_gl_object) { 278bdd1243dSDimitry Andric error(mb.getBufferIdentifier() + 279bdd1243dSDimitry Andric ": is not a native COFF file. Recompile without /GL?"); 280bdd1243dSDimitry Andric return; 2810b57cec5SDimitry Andric } else { 2820b57cec5SDimitry Andric error("unknown file type: " + mb.getBufferIdentifier()); 2830b57cec5SDimitry Andric return; 2840b57cec5SDimitry Andric } 2850b57cec5SDimitry Andric 2860b57cec5SDimitry Andric obj->parentName = parentName; 287349cc55cSDimitry Andric ctx.symtab.addFile(obj); 2880b57cec5SDimitry Andric log("Loaded " + toString(obj) + " for " + symName); 2890b57cec5SDimitry Andric } 2900b57cec5SDimitry Andric 2910b57cec5SDimitry Andric void LinkerDriver::enqueueArchiveMember(const Archive::Child &c, 2920b57cec5SDimitry Andric const Archive::Symbol &sym, 2930b57cec5SDimitry Andric StringRef parentName) { 2940b57cec5SDimitry Andric 2950b57cec5SDimitry Andric auto reportBufferError = [=](Error &&e, StringRef childName) { 2960b57cec5SDimitry Andric fatal("could not get the buffer for the member defining symbol " + 297bdd1243dSDimitry Andric toCOFFString(ctx, sym) + ": " + parentName + "(" + childName + 298bdd1243dSDimitry Andric "): " + toString(std::move(e))); 2990b57cec5SDimitry Andric }; 3000b57cec5SDimitry Andric 3010b57cec5SDimitry Andric if (!c.getParent()->isThin()) { 3020b57cec5SDimitry Andric uint64_t offsetInArchive = c.getChildOffset(); 3030b57cec5SDimitry Andric Expected<MemoryBufferRef> mbOrErr = c.getMemoryBufferRef(); 3040b57cec5SDimitry Andric if (!mbOrErr) 3050b57cec5SDimitry Andric reportBufferError(mbOrErr.takeError(), check(c.getFullName())); 3060b57cec5SDimitry Andric MemoryBufferRef mb = mbOrErr.get(); 3070b57cec5SDimitry Andric enqueueTask([=]() { 308bdd1243dSDimitry Andric ctx.driver.addArchiveBuffer(mb, toCOFFString(ctx, sym), parentName, 3090b57cec5SDimitry Andric offsetInArchive); 3100b57cec5SDimitry Andric }); 3110b57cec5SDimitry Andric return; 3120b57cec5SDimitry Andric } 3130b57cec5SDimitry Andric 314bdd1243dSDimitry Andric std::string childName = 315bdd1243dSDimitry Andric CHECK(c.getFullName(), 3160b57cec5SDimitry Andric "could not get the filename for the member defining symbol " + 317bdd1243dSDimitry Andric toCOFFString(ctx, sym)); 3180b57cec5SDimitry Andric auto future = std::make_shared<std::future<MBErrPair>>( 3190b57cec5SDimitry Andric createFutureForFile(childName)); 3200b57cec5SDimitry Andric enqueueTask([=]() { 3210b57cec5SDimitry Andric auto mbOrErr = future->get(); 3220b57cec5SDimitry Andric if (mbOrErr.second) 3230b57cec5SDimitry Andric reportBufferError(errorCodeToError(mbOrErr.second), childName); 32485868e8aSDimitry Andric // Pass empty string as archive name so that the original filename is 32585868e8aSDimitry Andric // used as the buffer identifier. 326bdd1243dSDimitry Andric ctx.driver.addArchiveBuffer(takeBuffer(std::move(mbOrErr.first)), 327bdd1243dSDimitry Andric toCOFFString(ctx, sym), "", 328bdd1243dSDimitry Andric /*OffsetInArchive=*/0); 3290b57cec5SDimitry Andric }); 3300b57cec5SDimitry Andric } 3310b57cec5SDimitry Andric 332bdd1243dSDimitry Andric bool LinkerDriver::isDecorated(StringRef sym) { 3330b57cec5SDimitry Andric return sym.startswith("@") || sym.contains("@@") || sym.startswith("?") || 334bdd1243dSDimitry Andric (!ctx.config.mingw && sym.contains('@')); 3350b57cec5SDimitry Andric } 3360b57cec5SDimitry Andric 3370b57cec5SDimitry Andric // Parses .drectve section contents and returns a list of files 3380b57cec5SDimitry Andric // specified by /defaultlib. 3390b57cec5SDimitry Andric void LinkerDriver::parseDirectives(InputFile *file) { 3400b57cec5SDimitry Andric StringRef s = file->getDirectives(); 3410b57cec5SDimitry Andric if (s.empty()) 3420b57cec5SDimitry Andric return; 3430b57cec5SDimitry Andric 3440b57cec5SDimitry Andric log("Directives: " + toString(file) + ": " + s); 3450b57cec5SDimitry Andric 346bdd1243dSDimitry Andric ArgParser parser(ctx); 3470b57cec5SDimitry Andric // .drectve is always tokenized using Windows shell rules. 3480b57cec5SDimitry Andric // /EXPORT: option can appear too many times, processing in fastpath. 3495ffd83dbSDimitry Andric ParsedDirectives directives = parser.parseDirectives(s); 3500b57cec5SDimitry Andric 3515ffd83dbSDimitry Andric for (StringRef e : directives.exports) { 3520b57cec5SDimitry Andric // If a common header file contains dllexported function 3530b57cec5SDimitry Andric // declarations, many object files may end up with having the 3540b57cec5SDimitry Andric // same /EXPORT options. In order to save cost of parsing them, 3550b57cec5SDimitry Andric // we dedup them first. 3560b57cec5SDimitry Andric if (!directivesExports.insert(e).second) 3570b57cec5SDimitry Andric continue; 3580b57cec5SDimitry Andric 3590b57cec5SDimitry Andric Export exp = parseExport(e); 360bdd1243dSDimitry Andric if (ctx.config.machine == I386 && ctx.config.mingw) { 3610b57cec5SDimitry Andric if (!isDecorated(exp.name)) 36204eeddc0SDimitry Andric exp.name = saver().save("_" + exp.name); 3630b57cec5SDimitry Andric if (!exp.extName.empty() && !isDecorated(exp.extName)) 36404eeddc0SDimitry Andric exp.extName = saver().save("_" + exp.extName); 3650b57cec5SDimitry Andric } 3660b57cec5SDimitry Andric exp.directives = true; 367bdd1243dSDimitry Andric ctx.config.exports.push_back(exp); 3680b57cec5SDimitry Andric } 3690b57cec5SDimitry Andric 3705ffd83dbSDimitry Andric // Handle /include: in bulk. 3715ffd83dbSDimitry Andric for (StringRef inc : directives.includes) 3725ffd83dbSDimitry Andric addUndefined(inc); 3735ffd83dbSDimitry Andric 37461cfbce3SDimitry Andric // Handle /exclude-symbols: in bulk. 37561cfbce3SDimitry Andric for (StringRef e : directives.excludes) { 37661cfbce3SDimitry Andric SmallVector<StringRef, 2> vec; 37761cfbce3SDimitry Andric e.split(vec, ','); 37861cfbce3SDimitry Andric for (StringRef sym : vec) 37961cfbce3SDimitry Andric excludedSymbols.insert(mangle(sym)); 38061cfbce3SDimitry Andric } 38161cfbce3SDimitry Andric 382349cc55cSDimitry Andric // https://docs.microsoft.com/en-us/cpp/preprocessor/comment-c-cpp?view=msvc-160 3835ffd83dbSDimitry Andric for (auto *arg : directives.args) { 3840b57cec5SDimitry Andric switch (arg->getOption().getID()) { 3850b57cec5SDimitry Andric case OPT_aligncomm: 3860b57cec5SDimitry Andric parseAligncomm(arg->getValue()); 3870b57cec5SDimitry Andric break; 3880b57cec5SDimitry Andric case OPT_alternatename: 3890b57cec5SDimitry Andric parseAlternateName(arg->getValue()); 3900b57cec5SDimitry Andric break; 3910b57cec5SDimitry Andric case OPT_defaultlib: 392bdd1243dSDimitry Andric if (std::optional<StringRef> path = findLib(arg->getValue())) 39385868e8aSDimitry Andric enqueuePath(*path, false, false); 3940b57cec5SDimitry Andric break; 3950b57cec5SDimitry Andric case OPT_entry: 396bdd1243dSDimitry Andric ctx.config.entry = addUndefined(mangle(arg->getValue())); 3970b57cec5SDimitry Andric break; 3980b57cec5SDimitry Andric case OPT_failifmismatch: 3990b57cec5SDimitry Andric checkFailIfMismatch(arg->getValue(), file); 4000b57cec5SDimitry Andric break; 4010b57cec5SDimitry Andric case OPT_incl: 4020b57cec5SDimitry Andric addUndefined(arg->getValue()); 4030b57cec5SDimitry Andric break; 404349cc55cSDimitry Andric case OPT_manifestdependency: 405bdd1243dSDimitry Andric ctx.config.manifestDependencies.insert(arg->getValue()); 406349cc55cSDimitry Andric break; 4070b57cec5SDimitry Andric case OPT_merge: 4080b57cec5SDimitry Andric parseMerge(arg->getValue()); 4090b57cec5SDimitry Andric break; 4100b57cec5SDimitry Andric case OPT_nodefaultlib: 411bdd1243dSDimitry Andric ctx.config.noDefaultLibs.insert(doFindLib(arg->getValue()).lower()); 412bdd1243dSDimitry Andric break; 413bdd1243dSDimitry Andric case OPT_release: 414bdd1243dSDimitry Andric ctx.config.writeCheckSum = true; 4150b57cec5SDimitry Andric break; 4160b57cec5SDimitry Andric case OPT_section: 4170b57cec5SDimitry Andric parseSection(arg->getValue()); 4180b57cec5SDimitry Andric break; 419fe6060f1SDimitry Andric case OPT_stack: 420bdd1243dSDimitry Andric parseNumbers(arg->getValue(), &ctx.config.stackReserve, 421bdd1243dSDimitry Andric &ctx.config.stackCommit); 422fe6060f1SDimitry Andric break; 423e8d8bef9SDimitry Andric case OPT_subsystem: { 424e8d8bef9SDimitry Andric bool gotVersion = false; 425bdd1243dSDimitry Andric parseSubsystem(arg->getValue(), &ctx.config.subsystem, 426bdd1243dSDimitry Andric &ctx.config.majorSubsystemVersion, 427bdd1243dSDimitry Andric &ctx.config.minorSubsystemVersion, &gotVersion); 428e8d8bef9SDimitry Andric if (gotVersion) { 429bdd1243dSDimitry Andric ctx.config.majorOSVersion = ctx.config.majorSubsystemVersion; 430bdd1243dSDimitry Andric ctx.config.minorOSVersion = ctx.config.minorSubsystemVersion; 431e8d8bef9SDimitry Andric } 4320b57cec5SDimitry Andric break; 433e8d8bef9SDimitry Andric } 4340b57cec5SDimitry Andric // Only add flags here that link.exe accepts in 4350b57cec5SDimitry Andric // `#pragma comment(linker, "/flag")`-generated sections. 4360b57cec5SDimitry Andric case OPT_editandcontinue: 4370b57cec5SDimitry Andric case OPT_guardsym: 4380b57cec5SDimitry Andric case OPT_throwingnew: 439*cbe9438cSDimitry Andric case OPT_inferasanlibs: 440*cbe9438cSDimitry Andric case OPT_inferasanlibs_no: 4410b57cec5SDimitry Andric break; 4420b57cec5SDimitry Andric default: 443*cbe9438cSDimitry Andric error(arg->getSpelling() + " is not allowed in .drectve (" + 444*cbe9438cSDimitry Andric toString(file) + ")"); 4450b57cec5SDimitry Andric } 4460b57cec5SDimitry Andric } 4470b57cec5SDimitry Andric } 4480b57cec5SDimitry Andric 4490b57cec5SDimitry Andric // Find file from search paths. You can omit ".obj", this function takes 4500b57cec5SDimitry Andric // care of that. Note that the returned path is not guaranteed to exist. 4510b57cec5SDimitry Andric StringRef LinkerDriver::doFindFile(StringRef filename) { 452bdd1243dSDimitry Andric auto getFilename = [this](StringRef filename) -> StringRef { 453bdd1243dSDimitry Andric if (ctx.config.vfs) 454bdd1243dSDimitry Andric if (auto statOrErr = ctx.config.vfs->status(filename)) 455753f127fSDimitry Andric return saver().save(statOrErr->getName()); 456753f127fSDimitry Andric return filename; 457753f127fSDimitry Andric }; 458753f127fSDimitry Andric 4590b57cec5SDimitry Andric bool hasPathSep = (filename.find_first_of("/\\") != StringRef::npos); 4600b57cec5SDimitry Andric if (hasPathSep) 461753f127fSDimitry Andric return getFilename(filename); 4620b57cec5SDimitry Andric bool hasExt = filename.contains('.'); 4630b57cec5SDimitry Andric for (StringRef dir : searchPaths) { 4640b57cec5SDimitry Andric SmallString<128> path = dir; 4650b57cec5SDimitry Andric sys::path::append(path, filename); 466753f127fSDimitry Andric path = SmallString<128>{getFilename(path.str())}; 4670b57cec5SDimitry Andric if (sys::fs::exists(path.str())) 46804eeddc0SDimitry Andric return saver().save(path.str()); 4690b57cec5SDimitry Andric if (!hasExt) { 4700b57cec5SDimitry Andric path.append(".obj"); 471753f127fSDimitry Andric path = SmallString<128>{getFilename(path.str())}; 4720b57cec5SDimitry Andric if (sys::fs::exists(path.str())) 47304eeddc0SDimitry Andric return saver().save(path.str()); 4740b57cec5SDimitry Andric } 4750b57cec5SDimitry Andric } 4760b57cec5SDimitry Andric return filename; 4770b57cec5SDimitry Andric } 4780b57cec5SDimitry Andric 479bdd1243dSDimitry Andric static std::optional<sys::fs::UniqueID> getUniqueID(StringRef path) { 4800b57cec5SDimitry Andric sys::fs::UniqueID ret; 4810b57cec5SDimitry Andric if (sys::fs::getUniqueID(path, ret)) 482bdd1243dSDimitry Andric return std::nullopt; 4830b57cec5SDimitry Andric return ret; 4840b57cec5SDimitry Andric } 4850b57cec5SDimitry Andric 4860b57cec5SDimitry Andric // Resolves a file path. This never returns the same path 487bdd1243dSDimitry Andric // (in that case, it returns std::nullopt). 488bdd1243dSDimitry Andric std::optional<StringRef> LinkerDriver::findFile(StringRef filename) { 4890b57cec5SDimitry Andric StringRef path = doFindFile(filename); 4900b57cec5SDimitry Andric 491bdd1243dSDimitry Andric if (std::optional<sys::fs::UniqueID> id = getUniqueID(path)) { 4920b57cec5SDimitry Andric bool seen = !visitedFiles.insert(*id).second; 4930b57cec5SDimitry Andric if (seen) 494bdd1243dSDimitry Andric return std::nullopt; 4950b57cec5SDimitry Andric } 4960b57cec5SDimitry Andric 497fe6060f1SDimitry Andric if (path.endswith_insensitive(".lib")) 49881ad6265SDimitry Andric visitedLibs.insert(std::string(sys::path::filename(path).lower())); 4990b57cec5SDimitry Andric return path; 5000b57cec5SDimitry Andric } 5010b57cec5SDimitry Andric 5020b57cec5SDimitry Andric // MinGW specific. If an embedded directive specified to link to 5030b57cec5SDimitry Andric // foo.lib, but it isn't found, try libfoo.a instead. 5040b57cec5SDimitry Andric StringRef LinkerDriver::doFindLibMinGW(StringRef filename) { 5050b57cec5SDimitry Andric if (filename.contains('/') || filename.contains('\\')) 5060b57cec5SDimitry Andric return filename; 5070b57cec5SDimitry Andric 5080b57cec5SDimitry Andric SmallString<128> s = filename; 5090b57cec5SDimitry Andric sys::path::replace_extension(s, ".a"); 51004eeddc0SDimitry Andric StringRef libName = saver().save("lib" + s.str()); 5110b57cec5SDimitry Andric return doFindFile(libName); 5120b57cec5SDimitry Andric } 5130b57cec5SDimitry Andric 5140b57cec5SDimitry Andric // Find library file from search path. 5150b57cec5SDimitry Andric StringRef LinkerDriver::doFindLib(StringRef filename) { 5160b57cec5SDimitry Andric // Add ".lib" to Filename if that has no file extension. 5170b57cec5SDimitry Andric bool hasExt = filename.contains('.'); 5180b57cec5SDimitry Andric if (!hasExt) 51904eeddc0SDimitry Andric filename = saver().save(filename + ".lib"); 5200b57cec5SDimitry Andric StringRef ret = doFindFile(filename); 5210b57cec5SDimitry Andric // For MinGW, if the find above didn't turn up anything, try 5220b57cec5SDimitry Andric // looking for a MinGW formatted library name. 523bdd1243dSDimitry Andric if (ctx.config.mingw && ret == filename) 5240b57cec5SDimitry Andric return doFindLibMinGW(filename); 5250b57cec5SDimitry Andric return ret; 5260b57cec5SDimitry Andric } 5270b57cec5SDimitry Andric 5280b57cec5SDimitry Andric // Resolves a library path. /nodefaultlib options are taken into 5290b57cec5SDimitry Andric // consideration. This never returns the same path (in that case, 530bdd1243dSDimitry Andric // it returns std::nullopt). 531bdd1243dSDimitry Andric std::optional<StringRef> LinkerDriver::findLib(StringRef filename) { 532bdd1243dSDimitry Andric if (ctx.config.noDefaultLibAll) 533bdd1243dSDimitry Andric return std::nullopt; 5340b57cec5SDimitry Andric if (!visitedLibs.insert(filename.lower()).second) 535bdd1243dSDimitry Andric return std::nullopt; 5360b57cec5SDimitry Andric 5370b57cec5SDimitry Andric StringRef path = doFindLib(filename); 538bdd1243dSDimitry Andric if (ctx.config.noDefaultLibs.count(path.lower())) 539bdd1243dSDimitry Andric return std::nullopt; 5400b57cec5SDimitry Andric 541bdd1243dSDimitry Andric if (std::optional<sys::fs::UniqueID> id = getUniqueID(path)) 5420b57cec5SDimitry Andric if (!visitedFiles.insert(*id).second) 543bdd1243dSDimitry Andric return std::nullopt; 5440b57cec5SDimitry Andric return path; 5450b57cec5SDimitry Andric } 5460b57cec5SDimitry Andric 54781ad6265SDimitry Andric void LinkerDriver::detectWinSysRoot(const opt::InputArgList &Args) { 54881ad6265SDimitry Andric IntrusiveRefCntPtr<vfs::FileSystem> VFS = vfs::getRealFileSystem(); 54981ad6265SDimitry Andric 55081ad6265SDimitry Andric // Check the command line first, that's the user explicitly telling us what to 55181ad6265SDimitry Andric // use. Check the environment next, in case we're being invoked from a VS 55281ad6265SDimitry Andric // command prompt. Failing that, just try to find the newest Visual Studio 55381ad6265SDimitry Andric // version we can and use its default VC toolchain. 554bdd1243dSDimitry Andric std::optional<StringRef> VCToolsDir, VCToolsVersion, WinSysRoot; 55581ad6265SDimitry Andric if (auto *A = Args.getLastArg(OPT_vctoolsdir)) 55681ad6265SDimitry Andric VCToolsDir = A->getValue(); 55781ad6265SDimitry Andric if (auto *A = Args.getLastArg(OPT_vctoolsversion)) 55881ad6265SDimitry Andric VCToolsVersion = A->getValue(); 55981ad6265SDimitry Andric if (auto *A = Args.getLastArg(OPT_winsysroot)) 56081ad6265SDimitry Andric WinSysRoot = A->getValue(); 56181ad6265SDimitry Andric if (!findVCToolChainViaCommandLine(*VFS, VCToolsDir, VCToolsVersion, 56281ad6265SDimitry Andric WinSysRoot, vcToolChainPath, vsLayout) && 56381ad6265SDimitry Andric (Args.hasArg(OPT_lldignoreenv) || 56481ad6265SDimitry Andric !findVCToolChainViaEnvironment(*VFS, vcToolChainPath, vsLayout)) && 56581ad6265SDimitry Andric !findVCToolChainViaSetupConfig(*VFS, vcToolChainPath, vsLayout) && 56681ad6265SDimitry Andric !findVCToolChainViaRegistry(vcToolChainPath, vsLayout)) 56781ad6265SDimitry Andric return; 56881ad6265SDimitry Andric 56981ad6265SDimitry Andric // If the VC environment hasn't been configured (perhaps because the user did 57081ad6265SDimitry Andric // not run vcvarsall), try to build a consistent link environment. If the 57181ad6265SDimitry Andric // environment variable is set however, assume the user knows what they're 57281ad6265SDimitry Andric // doing. If the user passes /vctoolsdir or /winsdkdir, trust that over env 57381ad6265SDimitry Andric // vars. 57481ad6265SDimitry Andric if (const auto *A = Args.getLastArg(OPT_diasdkdir, OPT_winsysroot)) { 57581ad6265SDimitry Andric diaPath = A->getValue(); 57681ad6265SDimitry Andric if (A->getOption().getID() == OPT_winsysroot) 57781ad6265SDimitry Andric path::append(diaPath, "DIA SDK"); 57881ad6265SDimitry Andric } 57981ad6265SDimitry Andric useWinSysRootLibPath = Args.hasArg(OPT_lldignoreenv) || 58081ad6265SDimitry Andric !Process::GetEnv("LIB") || 58181ad6265SDimitry Andric Args.getLastArg(OPT_vctoolsdir, OPT_winsysroot); 58281ad6265SDimitry Andric if (Args.hasArg(OPT_lldignoreenv) || !Process::GetEnv("LIB") || 58381ad6265SDimitry Andric Args.getLastArg(OPT_winsdkdir, OPT_winsysroot)) { 584bdd1243dSDimitry Andric std::optional<StringRef> WinSdkDir, WinSdkVersion; 58581ad6265SDimitry Andric if (auto *A = Args.getLastArg(OPT_winsdkdir)) 58681ad6265SDimitry Andric WinSdkDir = A->getValue(); 58781ad6265SDimitry Andric if (auto *A = Args.getLastArg(OPT_winsdkversion)) 58881ad6265SDimitry Andric WinSdkVersion = A->getValue(); 58981ad6265SDimitry Andric 59081ad6265SDimitry Andric if (useUniversalCRT(vsLayout, vcToolChainPath, getArch(), *VFS)) { 59181ad6265SDimitry Andric std::string UniversalCRTSdkPath; 59281ad6265SDimitry Andric std::string UCRTVersion; 59381ad6265SDimitry Andric if (getUniversalCRTSdkDir(*VFS, WinSdkDir, WinSdkVersion, WinSysRoot, 59481ad6265SDimitry Andric UniversalCRTSdkPath, UCRTVersion)) { 59581ad6265SDimitry Andric universalCRTLibPath = UniversalCRTSdkPath; 59681ad6265SDimitry Andric path::append(universalCRTLibPath, "Lib", UCRTVersion, "ucrt"); 59781ad6265SDimitry Andric } 59881ad6265SDimitry Andric } 59981ad6265SDimitry Andric 60081ad6265SDimitry Andric std::string sdkPath; 60181ad6265SDimitry Andric std::string windowsSDKIncludeVersion; 60281ad6265SDimitry Andric std::string windowsSDKLibVersion; 60381ad6265SDimitry Andric if (getWindowsSDKDir(*VFS, WinSdkDir, WinSdkVersion, WinSysRoot, sdkPath, 60481ad6265SDimitry Andric sdkMajor, windowsSDKIncludeVersion, 60581ad6265SDimitry Andric windowsSDKLibVersion)) { 60681ad6265SDimitry Andric windowsSdkLibPath = sdkPath; 60781ad6265SDimitry Andric path::append(windowsSdkLibPath, "Lib"); 60881ad6265SDimitry Andric if (sdkMajor >= 8) 60981ad6265SDimitry Andric path::append(windowsSdkLibPath, windowsSDKLibVersion, "um"); 61081ad6265SDimitry Andric } 61181ad6265SDimitry Andric } 61281ad6265SDimitry Andric } 61381ad6265SDimitry Andric 61481ad6265SDimitry Andric void LinkerDriver::addWinSysRootLibSearchPaths() { 61581ad6265SDimitry Andric if (!diaPath.empty()) { 61681ad6265SDimitry Andric // The DIA SDK always uses the legacy vc arch, even in new MSVC versions. 61781ad6265SDimitry Andric path::append(diaPath, "lib", archToLegacyVCArch(getArch())); 61881ad6265SDimitry Andric searchPaths.push_back(saver().save(diaPath.str())); 61981ad6265SDimitry Andric } 62081ad6265SDimitry Andric if (useWinSysRootLibPath) { 62181ad6265SDimitry Andric searchPaths.push_back(saver().save(getSubDirectoryPath( 62281ad6265SDimitry Andric SubDirectoryType::Lib, vsLayout, vcToolChainPath, getArch()))); 62381ad6265SDimitry Andric searchPaths.push_back(saver().save( 62481ad6265SDimitry Andric getSubDirectoryPath(SubDirectoryType::Lib, vsLayout, vcToolChainPath, 62581ad6265SDimitry Andric getArch(), "atlmfc"))); 62681ad6265SDimitry Andric } 62781ad6265SDimitry Andric if (!universalCRTLibPath.empty()) { 62881ad6265SDimitry Andric StringRef ArchName = archToWindowsSDKArch(getArch()); 62981ad6265SDimitry Andric if (!ArchName.empty()) { 63081ad6265SDimitry Andric path::append(universalCRTLibPath, ArchName); 63181ad6265SDimitry Andric searchPaths.push_back(saver().save(universalCRTLibPath.str())); 63281ad6265SDimitry Andric } 63381ad6265SDimitry Andric } 63481ad6265SDimitry Andric if (!windowsSdkLibPath.empty()) { 63581ad6265SDimitry Andric std::string path; 63681ad6265SDimitry Andric if (appendArchToWindowsSDKLibPath(sdkMajor, windowsSdkLibPath, getArch(), 63781ad6265SDimitry Andric path)) 63881ad6265SDimitry Andric searchPaths.push_back(saver().save(path)); 63981ad6265SDimitry Andric } 64081ad6265SDimitry Andric } 64181ad6265SDimitry Andric 6420b57cec5SDimitry Andric // Parses LIB environment which contains a list of search paths. 6430b57cec5SDimitry Andric void LinkerDriver::addLibSearchPaths() { 644bdd1243dSDimitry Andric std::optional<std::string> envOpt = Process::GetEnv("LIB"); 64581ad6265SDimitry Andric if (!envOpt) 6460b57cec5SDimitry Andric return; 64704eeddc0SDimitry Andric StringRef env = saver().save(*envOpt); 6480b57cec5SDimitry Andric while (!env.empty()) { 6490b57cec5SDimitry Andric StringRef path; 6500b57cec5SDimitry Andric std::tie(path, env) = env.split(';'); 6510b57cec5SDimitry Andric searchPaths.push_back(path); 6520b57cec5SDimitry Andric } 6530b57cec5SDimitry Andric } 6540b57cec5SDimitry Andric 6550b57cec5SDimitry Andric Symbol *LinkerDriver::addUndefined(StringRef name) { 656349cc55cSDimitry Andric Symbol *b = ctx.symtab.addUndefined(name); 6570b57cec5SDimitry Andric if (!b->isGCRoot) { 6580b57cec5SDimitry Andric b->isGCRoot = true; 659bdd1243dSDimitry Andric ctx.config.gcroot.push_back(b); 6600b57cec5SDimitry Andric } 6610b57cec5SDimitry Andric return b; 6620b57cec5SDimitry Andric } 6630b57cec5SDimitry Andric 6640b57cec5SDimitry Andric StringRef LinkerDriver::mangleMaybe(Symbol *s) { 6650b57cec5SDimitry Andric // If the plain symbol name has already been resolved, do nothing. 6660b57cec5SDimitry Andric Undefined *unmangled = dyn_cast<Undefined>(s); 6670b57cec5SDimitry Andric if (!unmangled) 6680b57cec5SDimitry Andric return ""; 6690b57cec5SDimitry Andric 6700b57cec5SDimitry Andric // Otherwise, see if a similar, mangled symbol exists in the symbol table. 671349cc55cSDimitry Andric Symbol *mangled = ctx.symtab.findMangle(unmangled->getName()); 6720b57cec5SDimitry Andric if (!mangled) 6730b57cec5SDimitry Andric return ""; 6740b57cec5SDimitry Andric 6750b57cec5SDimitry Andric // If we find a similar mangled symbol, make this an alias to it and return 6760b57cec5SDimitry Andric // its name. 6770b57cec5SDimitry Andric log(unmangled->getName() + " aliased to " + mangled->getName()); 678349cc55cSDimitry Andric unmangled->weakAlias = ctx.symtab.addUndefined(mangled->getName()); 6790b57cec5SDimitry Andric return mangled->getName(); 6800b57cec5SDimitry Andric } 6810b57cec5SDimitry Andric 6820b57cec5SDimitry Andric // Windows specific -- find default entry point name. 6830b57cec5SDimitry Andric // 6840b57cec5SDimitry Andric // There are four different entry point functions for Windows executables, 6850b57cec5SDimitry Andric // each of which corresponds to a user-defined "main" function. This function 6860b57cec5SDimitry Andric // infers an entry point from a user-defined "main" function. 6870b57cec5SDimitry Andric StringRef LinkerDriver::findDefaultEntry() { 688bdd1243dSDimitry Andric assert(ctx.config.subsystem != IMAGE_SUBSYSTEM_UNKNOWN && 6890b57cec5SDimitry Andric "must handle /subsystem before calling this"); 6900b57cec5SDimitry Andric 691bdd1243dSDimitry Andric if (ctx.config.mingw) 692bdd1243dSDimitry Andric return mangle(ctx.config.subsystem == IMAGE_SUBSYSTEM_WINDOWS_GUI 6930b57cec5SDimitry Andric ? "WinMainCRTStartup" 6940b57cec5SDimitry Andric : "mainCRTStartup"); 6950b57cec5SDimitry Andric 696bdd1243dSDimitry Andric if (ctx.config.subsystem == IMAGE_SUBSYSTEM_WINDOWS_GUI) { 6970b57cec5SDimitry Andric if (findUnderscoreMangle("wWinMain")) { 6980b57cec5SDimitry Andric if (!findUnderscoreMangle("WinMain")) 6990b57cec5SDimitry Andric return mangle("wWinMainCRTStartup"); 7000b57cec5SDimitry Andric warn("found both wWinMain and WinMain; using latter"); 7010b57cec5SDimitry Andric } 7020b57cec5SDimitry Andric return mangle("WinMainCRTStartup"); 7030b57cec5SDimitry Andric } 7040b57cec5SDimitry Andric if (findUnderscoreMangle("wmain")) { 7050b57cec5SDimitry Andric if (!findUnderscoreMangle("main")) 7060b57cec5SDimitry Andric return mangle("wmainCRTStartup"); 7070b57cec5SDimitry Andric warn("found both wmain and main; using latter"); 7080b57cec5SDimitry Andric } 7090b57cec5SDimitry Andric return mangle("mainCRTStartup"); 7100b57cec5SDimitry Andric } 7110b57cec5SDimitry Andric 7120b57cec5SDimitry Andric WindowsSubsystem LinkerDriver::inferSubsystem() { 713bdd1243dSDimitry Andric if (ctx.config.dll) 7140b57cec5SDimitry Andric return IMAGE_SUBSYSTEM_WINDOWS_GUI; 715bdd1243dSDimitry Andric if (ctx.config.mingw) 7160b57cec5SDimitry Andric return IMAGE_SUBSYSTEM_WINDOWS_CUI; 7170b57cec5SDimitry Andric // Note that link.exe infers the subsystem from the presence of these 7180b57cec5SDimitry Andric // functions even if /entry: or /nodefaultlib are passed which causes them 7190b57cec5SDimitry Andric // to not be called. 7200b57cec5SDimitry Andric bool haveMain = findUnderscoreMangle("main"); 7210b57cec5SDimitry Andric bool haveWMain = findUnderscoreMangle("wmain"); 7220b57cec5SDimitry Andric bool haveWinMain = findUnderscoreMangle("WinMain"); 7230b57cec5SDimitry Andric bool haveWWinMain = findUnderscoreMangle("wWinMain"); 7240b57cec5SDimitry Andric if (haveMain || haveWMain) { 7250b57cec5SDimitry Andric if (haveWinMain || haveWWinMain) { 7260b57cec5SDimitry Andric warn(std::string("found ") + (haveMain ? "main" : "wmain") + " and " + 7270b57cec5SDimitry Andric (haveWinMain ? "WinMain" : "wWinMain") + 7280b57cec5SDimitry Andric "; defaulting to /subsystem:console"); 7290b57cec5SDimitry Andric } 7300b57cec5SDimitry Andric return IMAGE_SUBSYSTEM_WINDOWS_CUI; 7310b57cec5SDimitry Andric } 7320b57cec5SDimitry Andric if (haveWinMain || haveWWinMain) 7330b57cec5SDimitry Andric return IMAGE_SUBSYSTEM_WINDOWS_GUI; 7340b57cec5SDimitry Andric return IMAGE_SUBSYSTEM_UNKNOWN; 7350b57cec5SDimitry Andric } 7360b57cec5SDimitry Andric 737bdd1243dSDimitry Andric uint64_t LinkerDriver::getDefaultImageBase() { 738bdd1243dSDimitry Andric if (ctx.config.is64()) 739bdd1243dSDimitry Andric return ctx.config.dll ? 0x180000000 : 0x140000000; 740bdd1243dSDimitry Andric return ctx.config.dll ? 0x10000000 : 0x400000; 7410b57cec5SDimitry Andric } 7420b57cec5SDimitry Andric 743fe6060f1SDimitry Andric static std::string rewritePath(StringRef s) { 744fe6060f1SDimitry Andric if (fs::exists(s)) 745fe6060f1SDimitry Andric return relativeToRoot(s); 746fe6060f1SDimitry Andric return std::string(s); 747fe6060f1SDimitry Andric } 748fe6060f1SDimitry Andric 749fe6060f1SDimitry Andric // Reconstructs command line arguments so that so that you can re-run 750fe6060f1SDimitry Andric // the same command with the same inputs. This is for --reproduce. 7510b57cec5SDimitry Andric static std::string createResponseFile(const opt::InputArgList &args, 7520b57cec5SDimitry Andric ArrayRef<StringRef> filePaths, 7530b57cec5SDimitry Andric ArrayRef<StringRef> searchPaths) { 7540b57cec5SDimitry Andric SmallString<0> data; 7550b57cec5SDimitry Andric raw_svector_ostream os(data); 7560b57cec5SDimitry Andric 7570b57cec5SDimitry Andric for (auto *arg : args) { 7580b57cec5SDimitry Andric switch (arg->getOption().getID()) { 7590b57cec5SDimitry Andric case OPT_linkrepro: 76085868e8aSDimitry Andric case OPT_reproduce: 7610b57cec5SDimitry Andric case OPT_INPUT: 7620b57cec5SDimitry Andric case OPT_defaultlib: 7630b57cec5SDimitry Andric case OPT_libpath: 76481ad6265SDimitry Andric case OPT_winsysroot: 7650b57cec5SDimitry Andric break; 766fe6060f1SDimitry Andric case OPT_call_graph_ordering_file: 767fe6060f1SDimitry Andric case OPT_deffile: 768349cc55cSDimitry Andric case OPT_manifestinput: 769fe6060f1SDimitry Andric case OPT_natvis: 770fe6060f1SDimitry Andric os << arg->getSpelling() << quote(rewritePath(arg->getValue())) << '\n'; 771fe6060f1SDimitry Andric break; 772fe6060f1SDimitry Andric case OPT_order: { 773fe6060f1SDimitry Andric StringRef orderFile = arg->getValue(); 774fe6060f1SDimitry Andric orderFile.consume_front("@"); 775fe6060f1SDimitry Andric os << arg->getSpelling() << '@' << quote(rewritePath(orderFile)) << '\n'; 776fe6060f1SDimitry Andric break; 777fe6060f1SDimitry Andric } 778fe6060f1SDimitry Andric case OPT_pdbstream: { 779fe6060f1SDimitry Andric const std::pair<StringRef, StringRef> nameFile = 780fe6060f1SDimitry Andric StringRef(arg->getValue()).split("="); 781fe6060f1SDimitry Andric os << arg->getSpelling() << nameFile.first << '=' 782fe6060f1SDimitry Andric << quote(rewritePath(nameFile.second)) << '\n'; 783fe6060f1SDimitry Andric break; 784fe6060f1SDimitry Andric } 7850b57cec5SDimitry Andric case OPT_implib: 786349cc55cSDimitry Andric case OPT_manifestfile: 7870b57cec5SDimitry Andric case OPT_pdb: 7885ffd83dbSDimitry Andric case OPT_pdbstripped: 7890b57cec5SDimitry Andric case OPT_out: 7900b57cec5SDimitry Andric os << arg->getSpelling() << sys::path::filename(arg->getValue()) << "\n"; 7910b57cec5SDimitry Andric break; 7920b57cec5SDimitry Andric default: 7930b57cec5SDimitry Andric os << toString(*arg) << "\n"; 7940b57cec5SDimitry Andric } 7950b57cec5SDimitry Andric } 7960b57cec5SDimitry Andric 7970b57cec5SDimitry Andric for (StringRef path : searchPaths) { 7980b57cec5SDimitry Andric std::string relPath = relativeToRoot(path); 7990b57cec5SDimitry Andric os << "/libpath:" << quote(relPath) << "\n"; 8000b57cec5SDimitry Andric } 8010b57cec5SDimitry Andric 8020b57cec5SDimitry Andric for (StringRef path : filePaths) 8030b57cec5SDimitry Andric os << quote(relativeToRoot(path)) << "\n"; 8040b57cec5SDimitry Andric 8055ffd83dbSDimitry Andric return std::string(data.str()); 8060b57cec5SDimitry Andric } 8070b57cec5SDimitry Andric 808fe6060f1SDimitry Andric enum class DebugKind { 809fe6060f1SDimitry Andric Unknown, 810fe6060f1SDimitry Andric None, 811fe6060f1SDimitry Andric Full, 812fe6060f1SDimitry Andric FastLink, 813fe6060f1SDimitry Andric GHash, 814fe6060f1SDimitry Andric NoGHash, 815fe6060f1SDimitry Andric Dwarf, 816fe6060f1SDimitry Andric Symtab 817fe6060f1SDimitry Andric }; 8180b57cec5SDimitry Andric 8190b57cec5SDimitry Andric static DebugKind parseDebugKind(const opt::InputArgList &args) { 8200b57cec5SDimitry Andric auto *a = args.getLastArg(OPT_debug, OPT_debug_opt); 8210b57cec5SDimitry Andric if (!a) 8220b57cec5SDimitry Andric return DebugKind::None; 8230b57cec5SDimitry Andric if (a->getNumValues() == 0) 8240b57cec5SDimitry Andric return DebugKind::Full; 8250b57cec5SDimitry Andric 8260b57cec5SDimitry Andric DebugKind debug = StringSwitch<DebugKind>(a->getValue()) 8270b57cec5SDimitry Andric .CaseLower("none", DebugKind::None) 8280b57cec5SDimitry Andric .CaseLower("full", DebugKind::Full) 8290b57cec5SDimitry Andric .CaseLower("fastlink", DebugKind::FastLink) 8300b57cec5SDimitry Andric // LLD extensions 8310b57cec5SDimitry Andric .CaseLower("ghash", DebugKind::GHash) 832fe6060f1SDimitry Andric .CaseLower("noghash", DebugKind::NoGHash) 8330b57cec5SDimitry Andric .CaseLower("dwarf", DebugKind::Dwarf) 8340b57cec5SDimitry Andric .CaseLower("symtab", DebugKind::Symtab) 8350b57cec5SDimitry Andric .Default(DebugKind::Unknown); 8360b57cec5SDimitry Andric 8370b57cec5SDimitry Andric if (debug == DebugKind::FastLink) { 8380b57cec5SDimitry Andric warn("/debug:fastlink unsupported; using /debug:full"); 8390b57cec5SDimitry Andric return DebugKind::Full; 8400b57cec5SDimitry Andric } 8410b57cec5SDimitry Andric if (debug == DebugKind::Unknown) { 8420b57cec5SDimitry Andric error("/debug: unknown option: " + Twine(a->getValue())); 8430b57cec5SDimitry Andric return DebugKind::None; 8440b57cec5SDimitry Andric } 8450b57cec5SDimitry Andric return debug; 8460b57cec5SDimitry Andric } 8470b57cec5SDimitry Andric 8480b57cec5SDimitry Andric static unsigned parseDebugTypes(const opt::InputArgList &args) { 8490b57cec5SDimitry Andric unsigned debugTypes = static_cast<unsigned>(DebugType::None); 8500b57cec5SDimitry Andric 8510b57cec5SDimitry Andric if (auto *a = args.getLastArg(OPT_debugtype)) { 8520b57cec5SDimitry Andric SmallVector<StringRef, 3> types; 8530b57cec5SDimitry Andric StringRef(a->getValue()) 8540b57cec5SDimitry Andric .split(types, ',', /*MaxSplit=*/-1, /*KeepEmpty=*/false); 8550b57cec5SDimitry Andric 8560b57cec5SDimitry Andric for (StringRef type : types) { 8570b57cec5SDimitry Andric unsigned v = StringSwitch<unsigned>(type.lower()) 8580b57cec5SDimitry Andric .Case("cv", static_cast<unsigned>(DebugType::CV)) 8590b57cec5SDimitry Andric .Case("pdata", static_cast<unsigned>(DebugType::PData)) 8600b57cec5SDimitry Andric .Case("fixup", static_cast<unsigned>(DebugType::Fixup)) 8610b57cec5SDimitry Andric .Default(0); 8620b57cec5SDimitry Andric if (v == 0) { 8630b57cec5SDimitry Andric warn("/debugtype: unknown option '" + type + "'"); 8640b57cec5SDimitry Andric continue; 8650b57cec5SDimitry Andric } 8660b57cec5SDimitry Andric debugTypes |= v; 8670b57cec5SDimitry Andric } 8680b57cec5SDimitry Andric return debugTypes; 8690b57cec5SDimitry Andric } 8700b57cec5SDimitry Andric 8710b57cec5SDimitry Andric // Default debug types 8720b57cec5SDimitry Andric debugTypes = static_cast<unsigned>(DebugType::CV); 8730b57cec5SDimitry Andric if (args.hasArg(OPT_driver)) 8740b57cec5SDimitry Andric debugTypes |= static_cast<unsigned>(DebugType::PData); 8750b57cec5SDimitry Andric if (args.hasArg(OPT_profile)) 8760b57cec5SDimitry Andric debugTypes |= static_cast<unsigned>(DebugType::Fixup); 8770b57cec5SDimitry Andric 8780b57cec5SDimitry Andric return debugTypes; 8790b57cec5SDimitry Andric } 8800b57cec5SDimitry Andric 881bdd1243dSDimitry Andric std::string LinkerDriver::getMapFile(const opt::InputArgList &args, 882bdd1243dSDimitry Andric opt::OptSpecifier os, 883bdd1243dSDimitry Andric opt::OptSpecifier osFile) { 8845ffd83dbSDimitry Andric auto *arg = args.getLastArg(os, osFile); 8850b57cec5SDimitry Andric if (!arg) 8860b57cec5SDimitry Andric return ""; 8875ffd83dbSDimitry Andric if (arg->getOption().getID() == osFile.getID()) 8880b57cec5SDimitry Andric return arg->getValue(); 8890b57cec5SDimitry Andric 8905ffd83dbSDimitry Andric assert(arg->getOption().getID() == os.getID()); 891bdd1243dSDimitry Andric StringRef outFile = ctx.config.outputFile; 8920b57cec5SDimitry Andric return (outFile.substr(0, outFile.rfind('.')) + ".map").str(); 8930b57cec5SDimitry Andric } 8940b57cec5SDimitry Andric 895bdd1243dSDimitry Andric std::string LinkerDriver::getImplibPath() { 896bdd1243dSDimitry Andric if (!ctx.config.implib.empty()) 897bdd1243dSDimitry Andric return std::string(ctx.config.implib); 898bdd1243dSDimitry Andric SmallString<128> out = StringRef(ctx.config.outputFile); 8990b57cec5SDimitry Andric sys::path::replace_extension(out, ".lib"); 9005ffd83dbSDimitry Andric return std::string(out.str()); 9010b57cec5SDimitry Andric } 9020b57cec5SDimitry Andric 90385868e8aSDimitry Andric // The import name is calculated as follows: 9040b57cec5SDimitry Andric // 9050b57cec5SDimitry Andric // | LIBRARY w/ ext | LIBRARY w/o ext | no LIBRARY 9060b57cec5SDimitry Andric // -----+----------------+---------------------+------------------ 9070b57cec5SDimitry Andric // LINK | {value} | {value}.{.dll/.exe} | {output name} 9080b57cec5SDimitry Andric // LIB | {value} | {value}.dll | {output name}.dll 9090b57cec5SDimitry Andric // 910bdd1243dSDimitry Andric std::string LinkerDriver::getImportName(bool asLib) { 9110b57cec5SDimitry Andric SmallString<128> out; 9120b57cec5SDimitry Andric 913bdd1243dSDimitry Andric if (ctx.config.importName.empty()) { 914bdd1243dSDimitry Andric out.assign(sys::path::filename(ctx.config.outputFile)); 9150b57cec5SDimitry Andric if (asLib) 9160b57cec5SDimitry Andric sys::path::replace_extension(out, ".dll"); 9170b57cec5SDimitry Andric } else { 918bdd1243dSDimitry Andric out.assign(ctx.config.importName); 9190b57cec5SDimitry Andric if (!sys::path::has_extension(out)) 9200b57cec5SDimitry Andric sys::path::replace_extension(out, 921bdd1243dSDimitry Andric (ctx.config.dll || asLib) ? ".dll" : ".exe"); 9220b57cec5SDimitry Andric } 9230b57cec5SDimitry Andric 9245ffd83dbSDimitry Andric return std::string(out.str()); 9250b57cec5SDimitry Andric } 9260b57cec5SDimitry Andric 927bdd1243dSDimitry Andric void LinkerDriver::createImportLibrary(bool asLib) { 9280b57cec5SDimitry Andric std::vector<COFFShortExport> exports; 929bdd1243dSDimitry Andric for (Export &e1 : ctx.config.exports) { 9300b57cec5SDimitry Andric COFFShortExport e2; 9315ffd83dbSDimitry Andric e2.Name = std::string(e1.name); 9325ffd83dbSDimitry Andric e2.SymbolName = std::string(e1.symbolName); 9335ffd83dbSDimitry Andric e2.ExtName = std::string(e1.extName); 93404eeddc0SDimitry Andric e2.AliasTarget = std::string(e1.aliasTarget); 9350b57cec5SDimitry Andric e2.Ordinal = e1.ordinal; 9360b57cec5SDimitry Andric e2.Noname = e1.noname; 9370b57cec5SDimitry Andric e2.Data = e1.data; 9380b57cec5SDimitry Andric e2.Private = e1.isPrivate; 9390b57cec5SDimitry Andric e2.Constant = e1.constant; 9400b57cec5SDimitry Andric exports.push_back(e2); 9410b57cec5SDimitry Andric } 9420b57cec5SDimitry Andric 9430b57cec5SDimitry Andric std::string libName = getImportName(asLib); 9440b57cec5SDimitry Andric std::string path = getImplibPath(); 9450b57cec5SDimitry Andric 946bdd1243dSDimitry Andric if (!ctx.config.incremental) { 947bdd1243dSDimitry Andric checkError(writeImportLibrary(libName, path, exports, ctx.config.machine, 948bdd1243dSDimitry Andric ctx.config.mingw)); 9490b57cec5SDimitry Andric return; 9500b57cec5SDimitry Andric } 9510b57cec5SDimitry Andric 9520b57cec5SDimitry Andric // If the import library already exists, replace it only if the contents 9530b57cec5SDimitry Andric // have changed. 9540b57cec5SDimitry Andric ErrorOr<std::unique_ptr<MemoryBuffer>> oldBuf = MemoryBuffer::getFile( 955fe6060f1SDimitry Andric path, /*IsText=*/false, /*RequiresNullTerminator=*/false); 9560b57cec5SDimitry Andric if (!oldBuf) { 957bdd1243dSDimitry Andric checkError(writeImportLibrary(libName, path, exports, ctx.config.machine, 958bdd1243dSDimitry Andric ctx.config.mingw)); 9590b57cec5SDimitry Andric return; 9600b57cec5SDimitry Andric } 9610b57cec5SDimitry Andric 9620b57cec5SDimitry Andric SmallString<128> tmpName; 9630b57cec5SDimitry Andric if (std::error_code ec = 9640b57cec5SDimitry Andric sys::fs::createUniqueFile(path + ".tmp-%%%%%%%%.lib", tmpName)) 9650b57cec5SDimitry Andric fatal("cannot create temporary file for import library " + path + ": " + 9660b57cec5SDimitry Andric ec.message()); 9670b57cec5SDimitry Andric 968bdd1243dSDimitry Andric if (Error e = writeImportLibrary(libName, tmpName, exports, 969bdd1243dSDimitry Andric ctx.config.machine, ctx.config.mingw)) { 970349cc55cSDimitry Andric checkError(std::move(e)); 9710b57cec5SDimitry Andric return; 9720b57cec5SDimitry Andric } 9730b57cec5SDimitry Andric 9740b57cec5SDimitry Andric std::unique_ptr<MemoryBuffer> newBuf = check(MemoryBuffer::getFile( 975fe6060f1SDimitry Andric tmpName, /*IsText=*/false, /*RequiresNullTerminator=*/false)); 9760b57cec5SDimitry Andric if ((*oldBuf)->getBuffer() != newBuf->getBuffer()) { 9770b57cec5SDimitry Andric oldBuf->reset(); 978349cc55cSDimitry Andric checkError(errorCodeToError(sys::fs::rename(tmpName, path))); 9790b57cec5SDimitry Andric } else { 9800b57cec5SDimitry Andric sys::fs::remove(tmpName); 9810b57cec5SDimitry Andric } 9820b57cec5SDimitry Andric } 9830b57cec5SDimitry Andric 984bdd1243dSDimitry Andric void LinkerDriver::parseModuleDefs(StringRef path) { 985fe6060f1SDimitry Andric std::unique_ptr<MemoryBuffer> mb = 986fe6060f1SDimitry Andric CHECK(MemoryBuffer::getFile(path, /*IsText=*/false, 987fe6060f1SDimitry Andric /*RequiresNullTerminator=*/false, 988fe6060f1SDimitry Andric /*IsVolatile=*/true), 989fe6060f1SDimitry Andric "could not open " + path); 9900b57cec5SDimitry Andric COFFModuleDefinition m = check(parseCOFFModuleDefinition( 991bdd1243dSDimitry Andric mb->getMemBufferRef(), ctx.config.machine, ctx.config.mingw)); 9920b57cec5SDimitry Andric 993fe6060f1SDimitry Andric // Include in /reproduce: output if applicable. 994bdd1243dSDimitry Andric ctx.driver.takeBuffer(std::move(mb)); 995fe6060f1SDimitry Andric 996bdd1243dSDimitry Andric if (ctx.config.outputFile.empty()) 997bdd1243dSDimitry Andric ctx.config.outputFile = std::string(saver().save(m.OutputFile)); 998bdd1243dSDimitry Andric ctx.config.importName = std::string(saver().save(m.ImportName)); 9990b57cec5SDimitry Andric if (m.ImageBase) 1000bdd1243dSDimitry Andric ctx.config.imageBase = m.ImageBase; 10010b57cec5SDimitry Andric if (m.StackReserve) 1002bdd1243dSDimitry Andric ctx.config.stackReserve = m.StackReserve; 10030b57cec5SDimitry Andric if (m.StackCommit) 1004bdd1243dSDimitry Andric ctx.config.stackCommit = m.StackCommit; 10050b57cec5SDimitry Andric if (m.HeapReserve) 1006bdd1243dSDimitry Andric ctx.config.heapReserve = m.HeapReserve; 10070b57cec5SDimitry Andric if (m.HeapCommit) 1008bdd1243dSDimitry Andric ctx.config.heapCommit = m.HeapCommit; 10090b57cec5SDimitry Andric if (m.MajorImageVersion) 1010bdd1243dSDimitry Andric ctx.config.majorImageVersion = m.MajorImageVersion; 10110b57cec5SDimitry Andric if (m.MinorImageVersion) 1012bdd1243dSDimitry Andric ctx.config.minorImageVersion = m.MinorImageVersion; 10130b57cec5SDimitry Andric if (m.MajorOSVersion) 1014bdd1243dSDimitry Andric ctx.config.majorOSVersion = m.MajorOSVersion; 10150b57cec5SDimitry Andric if (m.MinorOSVersion) 1016bdd1243dSDimitry Andric ctx.config.minorOSVersion = m.MinorOSVersion; 10170b57cec5SDimitry Andric 10180b57cec5SDimitry Andric for (COFFShortExport e1 : m.Exports) { 10190b57cec5SDimitry Andric Export e2; 10200b57cec5SDimitry Andric // In simple cases, only Name is set. Renamed exports are parsed 10210b57cec5SDimitry Andric // and set as "ExtName = Name". If Name has the form "OtherDll.Func", 10220b57cec5SDimitry Andric // it shouldn't be a normal exported function but a forward to another 10230b57cec5SDimitry Andric // DLL instead. This is supported by both MS and GNU linkers. 10245ffd83dbSDimitry Andric if (!e1.ExtName.empty() && e1.ExtName != e1.Name && 10255ffd83dbSDimitry Andric StringRef(e1.Name).contains('.')) { 102604eeddc0SDimitry Andric e2.name = saver().save(e1.ExtName); 102704eeddc0SDimitry Andric e2.forwardTo = saver().save(e1.Name); 1028bdd1243dSDimitry Andric ctx.config.exports.push_back(e2); 10290b57cec5SDimitry Andric continue; 10300b57cec5SDimitry Andric } 103104eeddc0SDimitry Andric e2.name = saver().save(e1.Name); 103204eeddc0SDimitry Andric e2.extName = saver().save(e1.ExtName); 103304eeddc0SDimitry Andric e2.aliasTarget = saver().save(e1.AliasTarget); 10340b57cec5SDimitry Andric e2.ordinal = e1.Ordinal; 10350b57cec5SDimitry Andric e2.noname = e1.Noname; 10360b57cec5SDimitry Andric e2.data = e1.Data; 10370b57cec5SDimitry Andric e2.isPrivate = e1.Private; 10380b57cec5SDimitry Andric e2.constant = e1.Constant; 1039bdd1243dSDimitry Andric ctx.config.exports.push_back(e2); 10400b57cec5SDimitry Andric } 10410b57cec5SDimitry Andric } 10420b57cec5SDimitry Andric 10430b57cec5SDimitry Andric void LinkerDriver::enqueueTask(std::function<void()> task) { 10440b57cec5SDimitry Andric taskQueue.push_back(std::move(task)); 10450b57cec5SDimitry Andric } 10460b57cec5SDimitry Andric 10470b57cec5SDimitry Andric bool LinkerDriver::run() { 1048349cc55cSDimitry Andric ScopedTimer t(ctx.inputFileTimer); 10490b57cec5SDimitry Andric 10500b57cec5SDimitry Andric bool didWork = !taskQueue.empty(); 10510b57cec5SDimitry Andric while (!taskQueue.empty()) { 10520b57cec5SDimitry Andric taskQueue.front()(); 10530b57cec5SDimitry Andric taskQueue.pop_front(); 10540b57cec5SDimitry Andric } 10550b57cec5SDimitry Andric return didWork; 10560b57cec5SDimitry Andric } 10570b57cec5SDimitry Andric 10580b57cec5SDimitry Andric // Parse an /order file. If an option is given, the linker places 10590b57cec5SDimitry Andric // COMDAT sections in the same order as their names appear in the 10600b57cec5SDimitry Andric // given file. 1061bdd1243dSDimitry Andric void LinkerDriver::parseOrderFile(StringRef arg) { 10620b57cec5SDimitry Andric // For some reason, the MSVC linker requires a filename to be 10630b57cec5SDimitry Andric // preceded by "@". 10640b57cec5SDimitry Andric if (!arg.startswith("@")) { 10650b57cec5SDimitry Andric error("malformed /order option: '@' missing"); 10660b57cec5SDimitry Andric return; 10670b57cec5SDimitry Andric } 10680b57cec5SDimitry Andric 10690b57cec5SDimitry Andric // Get a list of all comdat sections for error checking. 10700b57cec5SDimitry Andric DenseSet<StringRef> set; 1071349cc55cSDimitry Andric for (Chunk *c : ctx.symtab.getChunks()) 10720b57cec5SDimitry Andric if (auto *sec = dyn_cast<SectionChunk>(c)) 10730b57cec5SDimitry Andric if (sec->sym) 10740b57cec5SDimitry Andric set.insert(sec->sym->getName()); 10750b57cec5SDimitry Andric 10760b57cec5SDimitry Andric // Open a file. 10770b57cec5SDimitry Andric StringRef path = arg.substr(1); 1078fe6060f1SDimitry Andric std::unique_ptr<MemoryBuffer> mb = 1079fe6060f1SDimitry Andric CHECK(MemoryBuffer::getFile(path, /*IsText=*/false, 1080fe6060f1SDimitry Andric /*RequiresNullTerminator=*/false, 1081fe6060f1SDimitry Andric /*IsVolatile=*/true), 1082fe6060f1SDimitry Andric "could not open " + path); 10830b57cec5SDimitry Andric 10840b57cec5SDimitry Andric // Parse a file. An order file contains one symbol per line. 10850b57cec5SDimitry Andric // All symbols that were not present in a given order file are 10860b57cec5SDimitry Andric // considered to have the lowest priority 0 and are placed at 10870b57cec5SDimitry Andric // end of an output section. 10885ffd83dbSDimitry Andric for (StringRef arg : args::getLines(mb->getMemBufferRef())) { 10895ffd83dbSDimitry Andric std::string s(arg); 1090bdd1243dSDimitry Andric if (ctx.config.machine == I386 && !isDecorated(s)) 10910b57cec5SDimitry Andric s = "_" + s; 10920b57cec5SDimitry Andric 10930b57cec5SDimitry Andric if (set.count(s) == 0) { 1094bdd1243dSDimitry Andric if (ctx.config.warnMissingOrderSymbol) 10950b57cec5SDimitry Andric warn("/order:" + arg + ": missing symbol: " + s + " [LNK4037]"); 10960b57cec5SDimitry Andric } 10970b57cec5SDimitry Andric else 1098bdd1243dSDimitry Andric ctx.config.order[s] = INT_MIN + ctx.config.order.size(); 10990b57cec5SDimitry Andric } 1100fe6060f1SDimitry Andric 1101fe6060f1SDimitry Andric // Include in /reproduce: output if applicable. 1102bdd1243dSDimitry Andric ctx.driver.takeBuffer(std::move(mb)); 11030b57cec5SDimitry Andric } 11040b57cec5SDimitry Andric 1105bdd1243dSDimitry Andric void LinkerDriver::parseCallGraphFile(StringRef path) { 1106fe6060f1SDimitry Andric std::unique_ptr<MemoryBuffer> mb = 1107fe6060f1SDimitry Andric CHECK(MemoryBuffer::getFile(path, /*IsText=*/false, 1108fe6060f1SDimitry Andric /*RequiresNullTerminator=*/false, 1109fe6060f1SDimitry Andric /*IsVolatile=*/true), 1110fe6060f1SDimitry Andric "could not open " + path); 1111e8d8bef9SDimitry Andric 1112e8d8bef9SDimitry Andric // Build a map from symbol name to section. 1113e8d8bef9SDimitry Andric DenseMap<StringRef, Symbol *> map; 1114349cc55cSDimitry Andric for (ObjFile *file : ctx.objFileInstances) 1115e8d8bef9SDimitry Andric for (Symbol *sym : file->getSymbols()) 1116e8d8bef9SDimitry Andric if (sym) 1117e8d8bef9SDimitry Andric map[sym->getName()] = sym; 1118e8d8bef9SDimitry Andric 1119e8d8bef9SDimitry Andric auto findSection = [&](StringRef name) -> SectionChunk * { 1120e8d8bef9SDimitry Andric Symbol *sym = map.lookup(name); 1121e8d8bef9SDimitry Andric if (!sym) { 1122bdd1243dSDimitry Andric if (ctx.config.warnMissingOrderSymbol) 1123e8d8bef9SDimitry Andric warn(path + ": no such symbol: " + name); 1124e8d8bef9SDimitry Andric return nullptr; 1125e8d8bef9SDimitry Andric } 1126e8d8bef9SDimitry Andric 1127e8d8bef9SDimitry Andric if (DefinedCOFF *dr = dyn_cast_or_null<DefinedCOFF>(sym)) 1128e8d8bef9SDimitry Andric return dyn_cast_or_null<SectionChunk>(dr->getChunk()); 1129e8d8bef9SDimitry Andric return nullptr; 1130e8d8bef9SDimitry Andric }; 1131e8d8bef9SDimitry Andric 1132e8d8bef9SDimitry Andric for (StringRef line : args::getLines(*mb)) { 1133e8d8bef9SDimitry Andric SmallVector<StringRef, 3> fields; 1134e8d8bef9SDimitry Andric line.split(fields, ' '); 1135e8d8bef9SDimitry Andric uint64_t count; 1136e8d8bef9SDimitry Andric 1137e8d8bef9SDimitry Andric if (fields.size() != 3 || !to_integer(fields[2], count)) { 1138e8d8bef9SDimitry Andric error(path + ": parse error"); 1139e8d8bef9SDimitry Andric return; 1140e8d8bef9SDimitry Andric } 1141e8d8bef9SDimitry Andric 1142e8d8bef9SDimitry Andric if (SectionChunk *from = findSection(fields[0])) 1143e8d8bef9SDimitry Andric if (SectionChunk *to = findSection(fields[1])) 1144bdd1243dSDimitry Andric ctx.config.callGraphProfile[{from, to}] += count; 1145e8d8bef9SDimitry Andric } 1146fe6060f1SDimitry Andric 1147fe6060f1SDimitry Andric // Include in /reproduce: output if applicable. 1148bdd1243dSDimitry Andric ctx.driver.takeBuffer(std::move(mb)); 1149e8d8bef9SDimitry Andric } 1150e8d8bef9SDimitry Andric 1151349cc55cSDimitry Andric static void readCallGraphsFromObjectFiles(COFFLinkerContext &ctx) { 1152349cc55cSDimitry Andric for (ObjFile *obj : ctx.objFileInstances) { 1153e8d8bef9SDimitry Andric if (obj->callgraphSec) { 1154e8d8bef9SDimitry Andric ArrayRef<uint8_t> contents; 1155e8d8bef9SDimitry Andric cantFail( 1156e8d8bef9SDimitry Andric obj->getCOFFObj()->getSectionContents(obj->callgraphSec, contents)); 1157e8d8bef9SDimitry Andric BinaryStreamReader reader(contents, support::little); 1158e8d8bef9SDimitry Andric while (!reader.empty()) { 1159e8d8bef9SDimitry Andric uint32_t fromIndex, toIndex; 1160e8d8bef9SDimitry Andric uint64_t count; 1161e8d8bef9SDimitry Andric if (Error err = reader.readInteger(fromIndex)) 1162e8d8bef9SDimitry Andric fatal(toString(obj) + ": Expected 32-bit integer"); 1163e8d8bef9SDimitry Andric if (Error err = reader.readInteger(toIndex)) 1164e8d8bef9SDimitry Andric fatal(toString(obj) + ": Expected 32-bit integer"); 1165e8d8bef9SDimitry Andric if (Error err = reader.readInteger(count)) 1166e8d8bef9SDimitry Andric fatal(toString(obj) + ": Expected 64-bit integer"); 1167e8d8bef9SDimitry Andric auto *fromSym = dyn_cast_or_null<Defined>(obj->getSymbol(fromIndex)); 1168e8d8bef9SDimitry Andric auto *toSym = dyn_cast_or_null<Defined>(obj->getSymbol(toIndex)); 1169e8d8bef9SDimitry Andric if (!fromSym || !toSym) 1170e8d8bef9SDimitry Andric continue; 1171e8d8bef9SDimitry Andric auto *from = dyn_cast_or_null<SectionChunk>(fromSym->getChunk()); 1172e8d8bef9SDimitry Andric auto *to = dyn_cast_or_null<SectionChunk>(toSym->getChunk()); 1173e8d8bef9SDimitry Andric if (from && to) 1174bdd1243dSDimitry Andric ctx.config.callGraphProfile[{from, to}] += count; 1175e8d8bef9SDimitry Andric } 1176e8d8bef9SDimitry Andric } 1177e8d8bef9SDimitry Andric } 1178e8d8bef9SDimitry Andric } 1179e8d8bef9SDimitry Andric 11800b57cec5SDimitry Andric static void markAddrsig(Symbol *s) { 11810b57cec5SDimitry Andric if (auto *d = dyn_cast_or_null<Defined>(s)) 11820b57cec5SDimitry Andric if (SectionChunk *c = dyn_cast_or_null<SectionChunk>(d->getChunk())) 11830b57cec5SDimitry Andric c->keepUnique = true; 11840b57cec5SDimitry Andric } 11850b57cec5SDimitry Andric 1186349cc55cSDimitry Andric static void findKeepUniqueSections(COFFLinkerContext &ctx) { 11870b57cec5SDimitry Andric // Exported symbols could be address-significant in other executables or DSOs, 11880b57cec5SDimitry Andric // so we conservatively mark them as address-significant. 1189bdd1243dSDimitry Andric for (Export &r : ctx.config.exports) 11900b57cec5SDimitry Andric markAddrsig(r.sym); 11910b57cec5SDimitry Andric 11920b57cec5SDimitry Andric // Visit the address-significance table in each object file and mark each 11930b57cec5SDimitry Andric // referenced symbol as address-significant. 1194349cc55cSDimitry Andric for (ObjFile *obj : ctx.objFileInstances) { 11950b57cec5SDimitry Andric ArrayRef<Symbol *> syms = obj->getSymbols(); 11960b57cec5SDimitry Andric if (obj->addrsigSec) { 11970b57cec5SDimitry Andric ArrayRef<uint8_t> contents; 11980b57cec5SDimitry Andric cantFail( 11990b57cec5SDimitry Andric obj->getCOFFObj()->getSectionContents(obj->addrsigSec, contents)); 12000b57cec5SDimitry Andric const uint8_t *cur = contents.begin(); 12010b57cec5SDimitry Andric while (cur != contents.end()) { 12020b57cec5SDimitry Andric unsigned size; 12030b57cec5SDimitry Andric const char *err; 12040b57cec5SDimitry Andric uint64_t symIndex = decodeULEB128(cur, &size, contents.end(), &err); 12050b57cec5SDimitry Andric if (err) 12060b57cec5SDimitry Andric fatal(toString(obj) + ": could not decode addrsig section: " + err); 12070b57cec5SDimitry Andric if (symIndex >= syms.size()) 12080b57cec5SDimitry Andric fatal(toString(obj) + ": invalid symbol index in addrsig section"); 12090b57cec5SDimitry Andric markAddrsig(syms[symIndex]); 12100b57cec5SDimitry Andric cur += size; 12110b57cec5SDimitry Andric } 12120b57cec5SDimitry Andric } else { 12130b57cec5SDimitry Andric // If an object file does not have an address-significance table, 12140b57cec5SDimitry Andric // conservatively mark all of its symbols as address-significant. 12150b57cec5SDimitry Andric for (Symbol *s : syms) 12160b57cec5SDimitry Andric markAddrsig(s); 12170b57cec5SDimitry Andric } 12180b57cec5SDimitry Andric } 12190b57cec5SDimitry Andric } 12200b57cec5SDimitry Andric 12210b57cec5SDimitry Andric // link.exe replaces each %foo% in altPath with the contents of environment 12220b57cec5SDimitry Andric // variable foo, and adds the two magic env vars _PDB (expands to the basename 12230b57cec5SDimitry Andric // of pdb's output path) and _EXT (expands to the extension of the output 12240b57cec5SDimitry Andric // binary). 12250b57cec5SDimitry Andric // lld only supports %_PDB% and %_EXT% and warns on references to all other env 12260b57cec5SDimitry Andric // vars. 1227bdd1243dSDimitry Andric void LinkerDriver::parsePDBAltPath() { 12280b57cec5SDimitry Andric SmallString<128> buf; 12290b57cec5SDimitry Andric StringRef pdbBasename = 1230bdd1243dSDimitry Andric sys::path::filename(ctx.config.pdbPath, sys::path::Style::windows); 12310b57cec5SDimitry Andric StringRef binaryExtension = 1232bdd1243dSDimitry Andric sys::path::extension(ctx.config.outputFile, sys::path::Style::windows); 12330b57cec5SDimitry Andric if (!binaryExtension.empty()) 12340b57cec5SDimitry Andric binaryExtension = binaryExtension.substr(1); // %_EXT% does not include '.'. 12350b57cec5SDimitry Andric 12360b57cec5SDimitry Andric // Invariant: 12370b57cec5SDimitry Andric // +--------- cursor ('a...' might be the empty string). 12380b57cec5SDimitry Andric // | +----- firstMark 12390b57cec5SDimitry Andric // | | +- secondMark 12400b57cec5SDimitry Andric // v v v 12410b57cec5SDimitry Andric // a...%...%... 12420b57cec5SDimitry Andric size_t cursor = 0; 1243bdd1243dSDimitry Andric while (cursor < ctx.config.pdbAltPath.size()) { 12440b57cec5SDimitry Andric size_t firstMark, secondMark; 1245bdd1243dSDimitry Andric if ((firstMark = ctx.config.pdbAltPath.find('%', cursor)) == 1246bdd1243dSDimitry Andric StringRef::npos || 1247bdd1243dSDimitry Andric (secondMark = ctx.config.pdbAltPath.find('%', firstMark + 1)) == 1248bdd1243dSDimitry Andric StringRef::npos) { 12490b57cec5SDimitry Andric // Didn't find another full fragment, treat rest of string as literal. 1250bdd1243dSDimitry Andric buf.append(ctx.config.pdbAltPath.substr(cursor)); 12510b57cec5SDimitry Andric break; 12520b57cec5SDimitry Andric } 12530b57cec5SDimitry Andric 12540b57cec5SDimitry Andric // Found a full fragment. Append text in front of first %, and interpret 12550b57cec5SDimitry Andric // text between first and second % as variable name. 1256bdd1243dSDimitry Andric buf.append(ctx.config.pdbAltPath.substr(cursor, firstMark - cursor)); 1257bdd1243dSDimitry Andric StringRef var = 1258bdd1243dSDimitry Andric ctx.config.pdbAltPath.substr(firstMark, secondMark - firstMark + 1); 1259fe6060f1SDimitry Andric if (var.equals_insensitive("%_pdb%")) 12600b57cec5SDimitry Andric buf.append(pdbBasename); 1261fe6060f1SDimitry Andric else if (var.equals_insensitive("%_ext%")) 12620b57cec5SDimitry Andric buf.append(binaryExtension); 12630b57cec5SDimitry Andric else { 12640b57cec5SDimitry Andric warn("only %_PDB% and %_EXT% supported in /pdbaltpath:, keeping " + 12650b57cec5SDimitry Andric var + " as literal"); 12660b57cec5SDimitry Andric buf.append(var); 12670b57cec5SDimitry Andric } 12680b57cec5SDimitry Andric 12690b57cec5SDimitry Andric cursor = secondMark + 1; 12700b57cec5SDimitry Andric } 12710b57cec5SDimitry Andric 1272bdd1243dSDimitry Andric ctx.config.pdbAltPath = buf; 12730b57cec5SDimitry Andric } 12740b57cec5SDimitry Andric 127585868e8aSDimitry Andric /// Convert resource files and potentially merge input resource object 127685868e8aSDimitry Andric /// trees into one resource tree. 12770b57cec5SDimitry Andric /// Call after ObjFile::Instances is complete. 127885868e8aSDimitry Andric void LinkerDriver::convertResources() { 127985868e8aSDimitry Andric std::vector<ObjFile *> resourceObjFiles; 128085868e8aSDimitry Andric 1281349cc55cSDimitry Andric for (ObjFile *f : ctx.objFileInstances) { 128285868e8aSDimitry Andric if (f->isResourceObjFile()) 128385868e8aSDimitry Andric resourceObjFiles.push_back(f); 12840b57cec5SDimitry Andric } 12850b57cec5SDimitry Andric 1286bdd1243dSDimitry Andric if (!ctx.config.mingw && 128785868e8aSDimitry Andric (resourceObjFiles.size() > 1 || 128885868e8aSDimitry Andric (resourceObjFiles.size() == 1 && !resources.empty()))) { 128985868e8aSDimitry Andric error((!resources.empty() ? "internal .obj file created from .res files" 129085868e8aSDimitry Andric : toString(resourceObjFiles[1])) + 12910b57cec5SDimitry Andric ": more than one resource obj file not allowed, already got " + 129285868e8aSDimitry Andric toString(resourceObjFiles.front())); 129385868e8aSDimitry Andric return; 12940b57cec5SDimitry Andric } 129585868e8aSDimitry Andric 129685868e8aSDimitry Andric if (resources.empty() && resourceObjFiles.size() <= 1) { 129785868e8aSDimitry Andric // No resources to convert, and max one resource object file in 129885868e8aSDimitry Andric // the input. Keep that preconverted resource section as is. 129985868e8aSDimitry Andric for (ObjFile *f : resourceObjFiles) 130085868e8aSDimitry Andric f->includeResourceChunks(); 130185868e8aSDimitry Andric return; 130285868e8aSDimitry Andric } 1303349cc55cSDimitry Andric ObjFile *f = 1304349cc55cSDimitry Andric make<ObjFile>(ctx, convertResToCOFF(resources, resourceObjFiles)); 1305349cc55cSDimitry Andric ctx.symtab.addFile(f); 130685868e8aSDimitry Andric f->includeResourceChunks(); 13070b57cec5SDimitry Andric } 13080b57cec5SDimitry Andric 13090b57cec5SDimitry Andric // In MinGW, if no symbols are chosen to be exported, then all symbols are 13100b57cec5SDimitry Andric // automatically exported by default. This behavior can be forced by the 13110b57cec5SDimitry Andric // -export-all-symbols option, so that it happens even when exports are 13120b57cec5SDimitry Andric // explicitly specified. The automatic behavior can be disabled using the 13130b57cec5SDimitry Andric // -exclude-all-symbols option, so that lld-link behaves like link.exe rather 13140b57cec5SDimitry Andric // than MinGW in the case that nothing is explicitly exported. 13150b57cec5SDimitry Andric void LinkerDriver::maybeExportMinGWSymbols(const opt::InputArgList &args) { 1316fe6060f1SDimitry Andric if (!args.hasArg(OPT_export_all_symbols)) { 1317bdd1243dSDimitry Andric if (!ctx.config.dll) 13180b57cec5SDimitry Andric return; 13190b57cec5SDimitry Andric 1320bdd1243dSDimitry Andric if (!ctx.config.exports.empty()) 13210b57cec5SDimitry Andric return; 13220b57cec5SDimitry Andric if (args.hasArg(OPT_exclude_all_symbols)) 13230b57cec5SDimitry Andric return; 13240b57cec5SDimitry Andric } 13250b57cec5SDimitry Andric 1326bdd1243dSDimitry Andric AutoExporter exporter(ctx, excludedSymbols); 13270b57cec5SDimitry Andric 13280b57cec5SDimitry Andric for (auto *arg : args.filtered(OPT_wholearchive_file)) 1329bdd1243dSDimitry Andric if (std::optional<StringRef> path = doFindFile(arg->getValue())) 13300b57cec5SDimitry Andric exporter.addWholeArchive(*path); 13310b57cec5SDimitry Andric 133261cfbce3SDimitry Andric for (auto *arg : args.filtered(OPT_exclude_symbols)) { 133361cfbce3SDimitry Andric SmallVector<StringRef, 2> vec; 133461cfbce3SDimitry Andric StringRef(arg->getValue()).split(vec, ','); 133561cfbce3SDimitry Andric for (StringRef sym : vec) 133661cfbce3SDimitry Andric exporter.addExcludedSymbol(mangle(sym)); 133761cfbce3SDimitry Andric } 133861cfbce3SDimitry Andric 1339349cc55cSDimitry Andric ctx.symtab.forEachSymbol([&](Symbol *s) { 13400b57cec5SDimitry Andric auto *def = dyn_cast<Defined>(s); 1341bdd1243dSDimitry Andric if (!exporter.shouldExport(def)) 13420b57cec5SDimitry Andric return; 13430b57cec5SDimitry Andric 1344fe6060f1SDimitry Andric if (!def->isGCRoot) { 1345fe6060f1SDimitry Andric def->isGCRoot = true; 1346bdd1243dSDimitry Andric ctx.config.gcroot.push_back(def); 1347fe6060f1SDimitry Andric } 1348fe6060f1SDimitry Andric 13490b57cec5SDimitry Andric Export e; 13500b57cec5SDimitry Andric e.name = def->getName(); 13510b57cec5SDimitry Andric e.sym = def; 13520b57cec5SDimitry Andric if (Chunk *c = def->getChunk()) 13530b57cec5SDimitry Andric if (!(c->getOutputCharacteristics() & IMAGE_SCN_MEM_EXECUTE)) 13540b57cec5SDimitry Andric e.data = true; 1355fe6060f1SDimitry Andric s->isUsedInRegularObj = true; 1356bdd1243dSDimitry Andric ctx.config.exports.push_back(e); 13570b57cec5SDimitry Andric }); 13580b57cec5SDimitry Andric } 13590b57cec5SDimitry Andric 136085868e8aSDimitry Andric // lld has a feature to create a tar file containing all input files as well as 136185868e8aSDimitry Andric // all command line options, so that other people can run lld again with exactly 136285868e8aSDimitry Andric // the same inputs. This feature is accessible via /linkrepro and /reproduce. 136385868e8aSDimitry Andric // 136485868e8aSDimitry Andric // /linkrepro and /reproduce are very similar, but /linkrepro takes a directory 136585868e8aSDimitry Andric // name while /reproduce takes a full path. We have /linkrepro for compatibility 136685868e8aSDimitry Andric // with Microsoft link.exe. 1367bdd1243dSDimitry Andric std::optional<std::string> getReproduceFile(const opt::InputArgList &args) { 136885868e8aSDimitry Andric if (auto *arg = args.getLastArg(OPT_reproduce)) 136985868e8aSDimitry Andric return std::string(arg->getValue()); 137085868e8aSDimitry Andric 137185868e8aSDimitry Andric if (auto *arg = args.getLastArg(OPT_linkrepro)) { 137285868e8aSDimitry Andric SmallString<64> path = StringRef(arg->getValue()); 137385868e8aSDimitry Andric sys::path::append(path, "repro.tar"); 13745ffd83dbSDimitry Andric return std::string(path); 137585868e8aSDimitry Andric } 137685868e8aSDimitry Andric 1377e8d8bef9SDimitry Andric // This is intentionally not guarded by OPT_lldignoreenv since writing 1378e8d8bef9SDimitry Andric // a repro tar file doesn't affect the main output. 1379e8d8bef9SDimitry Andric if (auto *path = getenv("LLD_REPRODUCE")) 1380e8d8bef9SDimitry Andric return std::string(path); 1381e8d8bef9SDimitry Andric 1382bdd1243dSDimitry Andric return std::nullopt; 138385868e8aSDimitry Andric } 13840b57cec5SDimitry Andric 1385753f127fSDimitry Andric static std::unique_ptr<llvm::vfs::FileSystem> 1386753f127fSDimitry Andric getVFS(const opt::InputArgList &args) { 1387753f127fSDimitry Andric using namespace llvm::vfs; 1388753f127fSDimitry Andric 1389753f127fSDimitry Andric const opt::Arg *arg = args.getLastArg(OPT_vfsoverlay); 1390753f127fSDimitry Andric if (!arg) 1391753f127fSDimitry Andric return nullptr; 1392753f127fSDimitry Andric 1393753f127fSDimitry Andric auto bufOrErr = llvm::MemoryBuffer::getFile(arg->getValue()); 1394753f127fSDimitry Andric if (!bufOrErr) { 1395753f127fSDimitry Andric checkError(errorCodeToError(bufOrErr.getError())); 1396753f127fSDimitry Andric return nullptr; 1397753f127fSDimitry Andric } 1398753f127fSDimitry Andric 1399753f127fSDimitry Andric if (auto ret = vfs::getVFSFromYAML(std::move(*bufOrErr), /*DiagHandler*/ nullptr, 1400753f127fSDimitry Andric arg->getValue())) 1401753f127fSDimitry Andric return ret; 1402753f127fSDimitry Andric 1403753f127fSDimitry Andric error("Invalid vfs overlay"); 1404753f127fSDimitry Andric return nullptr; 1405753f127fSDimitry Andric } 1406753f127fSDimitry Andric 1407e8d8bef9SDimitry Andric void LinkerDriver::linkerMain(ArrayRef<const char *> argsArr) { 1408349cc55cSDimitry Andric ScopedTimer rootTimer(ctx.rootTimer); 1409bdd1243dSDimitry Andric Configuration *config = &ctx.config; 14105ffd83dbSDimitry Andric 14110b57cec5SDimitry Andric // Needed for LTO. 14120b57cec5SDimitry Andric InitializeAllTargetInfos(); 14130b57cec5SDimitry Andric InitializeAllTargets(); 14140b57cec5SDimitry Andric InitializeAllTargetMCs(); 14150b57cec5SDimitry Andric InitializeAllAsmParsers(); 14160b57cec5SDimitry Andric InitializeAllAsmPrinters(); 14170b57cec5SDimitry Andric 14180b57cec5SDimitry Andric // If the first command line argument is "/lib", link.exe acts like lib.exe. 14190b57cec5SDimitry Andric // We call our own implementation of lib.exe that understands bitcode files. 1420fe6060f1SDimitry Andric if (argsArr.size() > 1 && 1421fe6060f1SDimitry Andric (StringRef(argsArr[1]).equals_insensitive("/lib") || 1422fe6060f1SDimitry Andric StringRef(argsArr[1]).equals_insensitive("-lib"))) { 14230b57cec5SDimitry Andric if (llvm::libDriverMain(argsArr.slice(1)) != 0) 14240b57cec5SDimitry Andric fatal("lib failed"); 14250b57cec5SDimitry Andric return; 14260b57cec5SDimitry Andric } 14270b57cec5SDimitry Andric 14280b57cec5SDimitry Andric // Parse command line options. 1429bdd1243dSDimitry Andric ArgParser parser(ctx); 143085868e8aSDimitry Andric opt::InputArgList args = parser.parse(argsArr); 14310b57cec5SDimitry Andric 14320b57cec5SDimitry Andric // Parse and evaluate -mllvm options. 14330b57cec5SDimitry Andric std::vector<const char *> v; 14340b57cec5SDimitry Andric v.push_back("lld-link (LLVM option parsing)"); 1435bdd1243dSDimitry Andric for (const auto *arg : args.filtered(OPT_mllvm)) { 14360b57cec5SDimitry Andric v.push_back(arg->getValue()); 1437bdd1243dSDimitry Andric config->mllvmOpts.emplace_back(arg->getValue()); 1438bdd1243dSDimitry Andric } 1439e8d8bef9SDimitry Andric cl::ResetAllOptionOccurrences(); 14400b57cec5SDimitry Andric cl::ParseCommandLineOptions(v.size(), v.data()); 14410b57cec5SDimitry Andric 14420b57cec5SDimitry Andric // Handle /errorlimit early, because error() depends on it. 14430b57cec5SDimitry Andric if (auto *arg = args.getLastArg(OPT_errorlimit)) { 14440b57cec5SDimitry Andric int n = 20; 14450b57cec5SDimitry Andric StringRef s = arg->getValue(); 14460b57cec5SDimitry Andric if (s.getAsInteger(10, n)) 14470b57cec5SDimitry Andric error(arg->getSpelling() + " number expected, but got " + s); 14480b57cec5SDimitry Andric errorHandler().errorLimit = n; 14490b57cec5SDimitry Andric } 14500b57cec5SDimitry Andric 1451753f127fSDimitry Andric config->vfs = getVFS(args); 1452753f127fSDimitry Andric 14530b57cec5SDimitry Andric // Handle /help 14540b57cec5SDimitry Andric if (args.hasArg(OPT_help)) { 14550b57cec5SDimitry Andric printHelp(argsArr[0]); 14560b57cec5SDimitry Andric return; 14570b57cec5SDimitry Andric } 14580b57cec5SDimitry Andric 14595ffd83dbSDimitry Andric // /threads: takes a positive integer and provides the default value for 14605ffd83dbSDimitry Andric // /opt:lldltojobs=. 14615ffd83dbSDimitry Andric if (auto *arg = args.getLastArg(OPT_threads)) { 14625ffd83dbSDimitry Andric StringRef v(arg->getValue()); 14635ffd83dbSDimitry Andric unsigned threads = 0; 14645ffd83dbSDimitry Andric if (!llvm::to_integer(v, threads, 0) || threads == 0) 14655ffd83dbSDimitry Andric error(arg->getSpelling() + ": expected a positive integer, but got '" + 14665ffd83dbSDimitry Andric arg->getValue() + "'"); 14675ffd83dbSDimitry Andric parallel::strategy = hardware_concurrency(threads); 14685ffd83dbSDimitry Andric config->thinLTOJobs = v.str(); 14695ffd83dbSDimitry Andric } 14700b57cec5SDimitry Andric 14710b57cec5SDimitry Andric if (args.hasArg(OPT_show_timing)) 14720b57cec5SDimitry Andric config->showTiming = true; 14730b57cec5SDimitry Andric 14740b57cec5SDimitry Andric config->showSummary = args.hasArg(OPT_summary); 14750b57cec5SDimitry Andric 14760b57cec5SDimitry Andric // Handle --version, which is an lld extension. This option is a bit odd 14770b57cec5SDimitry Andric // because it doesn't start with "/", but we deliberately chose "--" to 14780b57cec5SDimitry Andric // avoid conflict with /version and for compatibility with clang-cl. 14790b57cec5SDimitry Andric if (args.hasArg(OPT_dash_dash_version)) { 1480e8d8bef9SDimitry Andric message(getLLDVersion()); 14810b57cec5SDimitry Andric return; 14820b57cec5SDimitry Andric } 14830b57cec5SDimitry Andric 14840b57cec5SDimitry Andric // Handle /lldmingw early, since it can potentially affect how other 14850b57cec5SDimitry Andric // options are handled. 14860b57cec5SDimitry Andric config->mingw = args.hasArg(OPT_lldmingw); 1487bdd1243dSDimitry Andric if (config->mingw) 1488bdd1243dSDimitry Andric ctx.e.errorLimitExceededMsg = "too many errors emitted, stopping now" 1489bdd1243dSDimitry Andric " (use --error-limit=0 to see all errors)"; 14900b57cec5SDimitry Andric 149185868e8aSDimitry Andric // Handle /linkrepro and /reproduce. 1492bdd1243dSDimitry Andric if (std::optional<std::string> path = getReproduceFile(args)) { 14930b57cec5SDimitry Andric Expected<std::unique_ptr<TarWriter>> errOrWriter = 149485868e8aSDimitry Andric TarWriter::create(*path, sys::path::stem(*path)); 14950b57cec5SDimitry Andric 14960b57cec5SDimitry Andric if (errOrWriter) { 14970b57cec5SDimitry Andric tar = std::move(*errOrWriter); 14980b57cec5SDimitry Andric } else { 149985868e8aSDimitry Andric error("/linkrepro: failed to open " + *path + ": " + 15000b57cec5SDimitry Andric toString(errOrWriter.takeError())); 15010b57cec5SDimitry Andric } 15020b57cec5SDimitry Andric } 15030b57cec5SDimitry Andric 1504480093f4SDimitry Andric if (!args.hasArg(OPT_INPUT, OPT_wholearchive_file)) { 15050b57cec5SDimitry Andric if (args.hasArg(OPT_deffile)) 15060b57cec5SDimitry Andric config->noEntry = true; 15070b57cec5SDimitry Andric else 15080b57cec5SDimitry Andric fatal("no input files"); 15090b57cec5SDimitry Andric } 15100b57cec5SDimitry Andric 15110b57cec5SDimitry Andric // Construct search path list. 15120b57cec5SDimitry Andric searchPaths.push_back(""); 15130b57cec5SDimitry Andric for (auto *arg : args.filtered(OPT_libpath)) 15140b57cec5SDimitry Andric searchPaths.push_back(arg->getValue()); 151581ad6265SDimitry Andric detectWinSysRoot(args); 151681ad6265SDimitry Andric if (!args.hasArg(OPT_lldignoreenv) && !args.hasArg(OPT_winsysroot)) 15170b57cec5SDimitry Andric addLibSearchPaths(); 15180b57cec5SDimitry Andric 15190b57cec5SDimitry Andric // Handle /ignore 15200b57cec5SDimitry Andric for (auto *arg : args.filtered(OPT_ignore)) { 15210b57cec5SDimitry Andric SmallVector<StringRef, 8> vec; 15220b57cec5SDimitry Andric StringRef(arg->getValue()).split(vec, ','); 15230b57cec5SDimitry Andric for (StringRef s : vec) { 15240b57cec5SDimitry Andric if (s == "4037") 15250b57cec5SDimitry Andric config->warnMissingOrderSymbol = false; 15260b57cec5SDimitry Andric else if (s == "4099") 15270b57cec5SDimitry Andric config->warnDebugInfoUnusable = false; 15280b57cec5SDimitry Andric else if (s == "4217") 15290b57cec5SDimitry Andric config->warnLocallyDefinedImported = false; 1530480093f4SDimitry Andric else if (s == "longsections") 1531480093f4SDimitry Andric config->warnLongSectionNames = false; 15320b57cec5SDimitry Andric // Other warning numbers are ignored. 15330b57cec5SDimitry Andric } 15340b57cec5SDimitry Andric } 15350b57cec5SDimitry Andric 15360b57cec5SDimitry Andric // Handle /out 15370b57cec5SDimitry Andric if (auto *arg = args.getLastArg(OPT_out)) 15380b57cec5SDimitry Andric config->outputFile = arg->getValue(); 15390b57cec5SDimitry Andric 15400b57cec5SDimitry Andric // Handle /verbose 15410b57cec5SDimitry Andric if (args.hasArg(OPT_verbose)) 15420b57cec5SDimitry Andric config->verbose = true; 15430b57cec5SDimitry Andric errorHandler().verbose = config->verbose; 15440b57cec5SDimitry Andric 15450b57cec5SDimitry Andric // Handle /force or /force:unresolved 15460b57cec5SDimitry Andric if (args.hasArg(OPT_force, OPT_force_unresolved)) 15470b57cec5SDimitry Andric config->forceUnresolved = true; 15480b57cec5SDimitry Andric 15490b57cec5SDimitry Andric // Handle /force or /force:multiple 15500b57cec5SDimitry Andric if (args.hasArg(OPT_force, OPT_force_multiple)) 15510b57cec5SDimitry Andric config->forceMultiple = true; 15520b57cec5SDimitry Andric 15530b57cec5SDimitry Andric // Handle /force or /force:multipleres 15540b57cec5SDimitry Andric if (args.hasArg(OPT_force, OPT_force_multipleres)) 15550b57cec5SDimitry Andric config->forceMultipleRes = true; 15560b57cec5SDimitry Andric 15570b57cec5SDimitry Andric // Handle /debug 15580b57cec5SDimitry Andric DebugKind debug = parseDebugKind(args); 15590b57cec5SDimitry Andric if (debug == DebugKind::Full || debug == DebugKind::Dwarf || 1560fe6060f1SDimitry Andric debug == DebugKind::GHash || debug == DebugKind::NoGHash) { 15610b57cec5SDimitry Andric config->debug = true; 15620b57cec5SDimitry Andric config->incremental = true; 15630b57cec5SDimitry Andric } 15640b57cec5SDimitry Andric 15650b57cec5SDimitry Andric // Handle /demangle 156681ad6265SDimitry Andric config->demangle = args.hasFlag(OPT_demangle, OPT_demangle_no, true); 15670b57cec5SDimitry Andric 15680b57cec5SDimitry Andric // Handle /debugtype 15690b57cec5SDimitry Andric config->debugTypes = parseDebugTypes(args); 15700b57cec5SDimitry Andric 1571480093f4SDimitry Andric // Handle /driver[:uponly|:wdm]. 1572480093f4SDimitry Andric config->driverUponly = args.hasArg(OPT_driver_uponly) || 1573480093f4SDimitry Andric args.hasArg(OPT_driver_uponly_wdm) || 1574480093f4SDimitry Andric args.hasArg(OPT_driver_wdm_uponly); 1575480093f4SDimitry Andric config->driverWdm = args.hasArg(OPT_driver_wdm) || 1576480093f4SDimitry Andric args.hasArg(OPT_driver_uponly_wdm) || 1577480093f4SDimitry Andric args.hasArg(OPT_driver_wdm_uponly); 1578480093f4SDimitry Andric config->driver = 1579480093f4SDimitry Andric config->driverUponly || config->driverWdm || args.hasArg(OPT_driver); 1580480093f4SDimitry Andric 15810b57cec5SDimitry Andric // Handle /pdb 15820b57cec5SDimitry Andric bool shouldCreatePDB = 1583fe6060f1SDimitry Andric (debug == DebugKind::Full || debug == DebugKind::GHash || 1584fe6060f1SDimitry Andric debug == DebugKind::NoGHash); 15850b57cec5SDimitry Andric if (shouldCreatePDB) { 15860b57cec5SDimitry Andric if (auto *arg = args.getLastArg(OPT_pdb)) 15870b57cec5SDimitry Andric config->pdbPath = arg->getValue(); 15880b57cec5SDimitry Andric if (auto *arg = args.getLastArg(OPT_pdbaltpath)) 15890b57cec5SDimitry Andric config->pdbAltPath = arg->getValue(); 1590349cc55cSDimitry Andric if (auto *arg = args.getLastArg(OPT_pdbpagesize)) 1591349cc55cSDimitry Andric parsePDBPageSize(arg->getValue()); 15920b57cec5SDimitry Andric if (args.hasArg(OPT_natvis)) 15930b57cec5SDimitry Andric config->natvisFiles = args.getAllArgValues(OPT_natvis); 15945ffd83dbSDimitry Andric if (args.hasArg(OPT_pdbstream)) { 15955ffd83dbSDimitry Andric for (const StringRef value : args.getAllArgValues(OPT_pdbstream)) { 15965ffd83dbSDimitry Andric const std::pair<StringRef, StringRef> nameFile = value.split("="); 15975ffd83dbSDimitry Andric const StringRef name = nameFile.first; 15985ffd83dbSDimitry Andric const std::string file = nameFile.second.str(); 15995ffd83dbSDimitry Andric config->namedStreams[name] = file; 16005ffd83dbSDimitry Andric } 16015ffd83dbSDimitry Andric } 16020b57cec5SDimitry Andric 16030b57cec5SDimitry Andric if (auto *arg = args.getLastArg(OPT_pdb_source_path)) 16040b57cec5SDimitry Andric config->pdbSourcePath = arg->getValue(); 16050b57cec5SDimitry Andric } 16060b57cec5SDimitry Andric 16075ffd83dbSDimitry Andric // Handle /pdbstripped 16085ffd83dbSDimitry Andric if (args.hasArg(OPT_pdbstripped)) 16095ffd83dbSDimitry Andric warn("ignoring /pdbstripped flag, it is not yet supported"); 16105ffd83dbSDimitry Andric 16110b57cec5SDimitry Andric // Handle /noentry 16120b57cec5SDimitry Andric if (args.hasArg(OPT_noentry)) { 16130b57cec5SDimitry Andric if (args.hasArg(OPT_dll)) 16140b57cec5SDimitry Andric config->noEntry = true; 16150b57cec5SDimitry Andric else 16160b57cec5SDimitry Andric error("/noentry must be specified with /dll"); 16170b57cec5SDimitry Andric } 16180b57cec5SDimitry Andric 16190b57cec5SDimitry Andric // Handle /dll 16200b57cec5SDimitry Andric if (args.hasArg(OPT_dll)) { 16210b57cec5SDimitry Andric config->dll = true; 16220b57cec5SDimitry Andric config->manifestID = 2; 16230b57cec5SDimitry Andric } 16240b57cec5SDimitry Andric 16250b57cec5SDimitry Andric // Handle /dynamicbase and /fixed. We can't use hasFlag for /dynamicbase 16260b57cec5SDimitry Andric // because we need to explicitly check whether that option or its inverse was 16270b57cec5SDimitry Andric // present in the argument list in order to handle /fixed. 16280b57cec5SDimitry Andric auto *dynamicBaseArg = args.getLastArg(OPT_dynamicbase, OPT_dynamicbase_no); 16290b57cec5SDimitry Andric if (dynamicBaseArg && 16300b57cec5SDimitry Andric dynamicBaseArg->getOption().getID() == OPT_dynamicbase_no) 16310b57cec5SDimitry Andric config->dynamicBase = false; 16320b57cec5SDimitry Andric 16330b57cec5SDimitry Andric // MSDN claims "/FIXED:NO is the default setting for a DLL, and /FIXED is the 16340b57cec5SDimitry Andric // default setting for any other project type.", but link.exe defaults to 16350b57cec5SDimitry Andric // /FIXED:NO for exe outputs as well. Match behavior, not docs. 16360b57cec5SDimitry Andric bool fixed = args.hasFlag(OPT_fixed, OPT_fixed_no, false); 16370b57cec5SDimitry Andric if (fixed) { 16380b57cec5SDimitry Andric if (dynamicBaseArg && 16390b57cec5SDimitry Andric dynamicBaseArg->getOption().getID() == OPT_dynamicbase) { 16400b57cec5SDimitry Andric error("/fixed must not be specified with /dynamicbase"); 16410b57cec5SDimitry Andric } else { 16420b57cec5SDimitry Andric config->relocatable = false; 16430b57cec5SDimitry Andric config->dynamicBase = false; 16440b57cec5SDimitry Andric } 16450b57cec5SDimitry Andric } 16460b57cec5SDimitry Andric 16470b57cec5SDimitry Andric // Handle /appcontainer 16480b57cec5SDimitry Andric config->appContainer = 16490b57cec5SDimitry Andric args.hasFlag(OPT_appcontainer, OPT_appcontainer_no, false); 16500b57cec5SDimitry Andric 16510b57cec5SDimitry Andric // Handle /machine 16520b57cec5SDimitry Andric if (auto *arg = args.getLastArg(OPT_machine)) { 16530b57cec5SDimitry Andric config->machine = getMachineType(arg->getValue()); 16540b57cec5SDimitry Andric if (config->machine == IMAGE_FILE_MACHINE_UNKNOWN) 16550b57cec5SDimitry Andric fatal(Twine("unknown /machine argument: ") + arg->getValue()); 165681ad6265SDimitry Andric addWinSysRootLibSearchPaths(); 16570b57cec5SDimitry Andric } 16580b57cec5SDimitry Andric 16590b57cec5SDimitry Andric // Handle /nodefaultlib:<filename> 16600b57cec5SDimitry Andric for (auto *arg : args.filtered(OPT_nodefaultlib)) 16610b57cec5SDimitry Andric config->noDefaultLibs.insert(doFindLib(arg->getValue()).lower()); 16620b57cec5SDimitry Andric 16630b57cec5SDimitry Andric // Handle /nodefaultlib 16640b57cec5SDimitry Andric if (args.hasArg(OPT_nodefaultlib_all)) 16650b57cec5SDimitry Andric config->noDefaultLibAll = true; 16660b57cec5SDimitry Andric 16670b57cec5SDimitry Andric // Handle /base 16680b57cec5SDimitry Andric if (auto *arg = args.getLastArg(OPT_base)) 16690b57cec5SDimitry Andric parseNumbers(arg->getValue(), &config->imageBase); 16700b57cec5SDimitry Andric 16710b57cec5SDimitry Andric // Handle /filealign 16720b57cec5SDimitry Andric if (auto *arg = args.getLastArg(OPT_filealign)) { 16730b57cec5SDimitry Andric parseNumbers(arg->getValue(), &config->fileAlign); 16740b57cec5SDimitry Andric if (!isPowerOf2_64(config->fileAlign)) 16750b57cec5SDimitry Andric error("/filealign: not a power of two: " + Twine(config->fileAlign)); 16760b57cec5SDimitry Andric } 16770b57cec5SDimitry Andric 16780b57cec5SDimitry Andric // Handle /stack 16790b57cec5SDimitry Andric if (auto *arg = args.getLastArg(OPT_stack)) 16800b57cec5SDimitry Andric parseNumbers(arg->getValue(), &config->stackReserve, &config->stackCommit); 16810b57cec5SDimitry Andric 16820b57cec5SDimitry Andric // Handle /guard:cf 16830b57cec5SDimitry Andric if (auto *arg = args.getLastArg(OPT_guard)) 16840b57cec5SDimitry Andric parseGuard(arg->getValue()); 16850b57cec5SDimitry Andric 16860b57cec5SDimitry Andric // Handle /heap 16870b57cec5SDimitry Andric if (auto *arg = args.getLastArg(OPT_heap)) 16880b57cec5SDimitry Andric parseNumbers(arg->getValue(), &config->heapReserve, &config->heapCommit); 16890b57cec5SDimitry Andric 16900b57cec5SDimitry Andric // Handle /version 16910b57cec5SDimitry Andric if (auto *arg = args.getLastArg(OPT_version)) 16920b57cec5SDimitry Andric parseVersion(arg->getValue(), &config->majorImageVersion, 16930b57cec5SDimitry Andric &config->minorImageVersion); 16940b57cec5SDimitry Andric 16950b57cec5SDimitry Andric // Handle /subsystem 16960b57cec5SDimitry Andric if (auto *arg = args.getLastArg(OPT_subsystem)) 1697e8d8bef9SDimitry Andric parseSubsystem(arg->getValue(), &config->subsystem, 1698e8d8bef9SDimitry Andric &config->majorSubsystemVersion, 1699e8d8bef9SDimitry Andric &config->minorSubsystemVersion); 1700e8d8bef9SDimitry Andric 1701e8d8bef9SDimitry Andric // Handle /osversion 1702e8d8bef9SDimitry Andric if (auto *arg = args.getLastArg(OPT_osversion)) { 1703e8d8bef9SDimitry Andric parseVersion(arg->getValue(), &config->majorOSVersion, 17040b57cec5SDimitry Andric &config->minorOSVersion); 1705e8d8bef9SDimitry Andric } else { 1706e8d8bef9SDimitry Andric config->majorOSVersion = config->majorSubsystemVersion; 1707e8d8bef9SDimitry Andric config->minorOSVersion = config->minorSubsystemVersion; 1708e8d8bef9SDimitry Andric } 17090b57cec5SDimitry Andric 17100b57cec5SDimitry Andric // Handle /timestamp 17110b57cec5SDimitry Andric if (llvm::opt::Arg *arg = args.getLastArg(OPT_timestamp, OPT_repro)) { 17120b57cec5SDimitry Andric if (arg->getOption().getID() == OPT_repro) { 17130b57cec5SDimitry Andric config->timestamp = 0; 17140b57cec5SDimitry Andric config->repro = true; 17150b57cec5SDimitry Andric } else { 17160b57cec5SDimitry Andric config->repro = false; 17170b57cec5SDimitry Andric StringRef value(arg->getValue()); 17180b57cec5SDimitry Andric if (value.getAsInteger(0, config->timestamp)) 17190b57cec5SDimitry Andric fatal(Twine("invalid timestamp: ") + value + 17200b57cec5SDimitry Andric ". Expected 32-bit integer"); 17210b57cec5SDimitry Andric } 17220b57cec5SDimitry Andric } else { 17230b57cec5SDimitry Andric config->repro = false; 17240b57cec5SDimitry Andric config->timestamp = time(nullptr); 17250b57cec5SDimitry Andric } 17260b57cec5SDimitry Andric 17270b57cec5SDimitry Andric // Handle /alternatename 17280b57cec5SDimitry Andric for (auto *arg : args.filtered(OPT_alternatename)) 17290b57cec5SDimitry Andric parseAlternateName(arg->getValue()); 17300b57cec5SDimitry Andric 17310b57cec5SDimitry Andric // Handle /include 17320b57cec5SDimitry Andric for (auto *arg : args.filtered(OPT_incl)) 17330b57cec5SDimitry Andric addUndefined(arg->getValue()); 17340b57cec5SDimitry Andric 17350b57cec5SDimitry Andric // Handle /implib 17360b57cec5SDimitry Andric if (auto *arg = args.getLastArg(OPT_implib)) 17370b57cec5SDimitry Andric config->implib = arg->getValue(); 17380b57cec5SDimitry Andric 173981ad6265SDimitry Andric config->noimplib = args.hasArg(OPT_noimplib); 174081ad6265SDimitry Andric 17410b57cec5SDimitry Andric // Handle /opt. 17420b57cec5SDimitry Andric bool doGC = debug == DebugKind::None || args.hasArg(OPT_profile); 1743bdd1243dSDimitry Andric std::optional<ICFLevel> icfLevel; 1744fe6060f1SDimitry Andric if (args.hasArg(OPT_profile)) 1745fe6060f1SDimitry Andric icfLevel = ICFLevel::None; 17460b57cec5SDimitry Andric unsigned tailMerge = 1; 1747e8d8bef9SDimitry Andric bool ltoDebugPM = false; 17480b57cec5SDimitry Andric for (auto *arg : args.filtered(OPT_opt)) { 17490b57cec5SDimitry Andric std::string str = StringRef(arg->getValue()).lower(); 17500b57cec5SDimitry Andric SmallVector<StringRef, 1> vec; 17510b57cec5SDimitry Andric StringRef(str).split(vec, ','); 17520b57cec5SDimitry Andric for (StringRef s : vec) { 17530b57cec5SDimitry Andric if (s == "ref") { 17540b57cec5SDimitry Andric doGC = true; 17550b57cec5SDimitry Andric } else if (s == "noref") { 17560b57cec5SDimitry Andric doGC = false; 17570b57cec5SDimitry Andric } else if (s == "icf" || s.startswith("icf=")) { 1758fe6060f1SDimitry Andric icfLevel = ICFLevel::All; 1759fe6060f1SDimitry Andric } else if (s == "safeicf") { 1760fe6060f1SDimitry Andric icfLevel = ICFLevel::Safe; 17610b57cec5SDimitry Andric } else if (s == "noicf") { 1762fe6060f1SDimitry Andric icfLevel = ICFLevel::None; 17630b57cec5SDimitry Andric } else if (s == "lldtailmerge") { 17640b57cec5SDimitry Andric tailMerge = 2; 17650b57cec5SDimitry Andric } else if (s == "nolldtailmerge") { 17660b57cec5SDimitry Andric tailMerge = 0; 1767e8d8bef9SDimitry Andric } else if (s == "ltonewpassmanager") { 176881ad6265SDimitry Andric /* We always use the new PM. */ 1769e8d8bef9SDimitry Andric } else if (s == "ltodebugpassmanager") { 1770e8d8bef9SDimitry Andric ltoDebugPM = true; 1771e8d8bef9SDimitry Andric } else if (s == "noltodebugpassmanager") { 1772e8d8bef9SDimitry Andric ltoDebugPM = false; 17730b57cec5SDimitry Andric } else if (s.startswith("lldlto=")) { 17740b57cec5SDimitry Andric StringRef optLevel = s.substr(7); 17750b57cec5SDimitry Andric if (optLevel.getAsInteger(10, config->ltoo) || config->ltoo > 3) 17760b57cec5SDimitry Andric error("/opt:lldlto: invalid optimization level: " + optLevel); 17770b57cec5SDimitry Andric } else if (s.startswith("lldltojobs=")) { 17780b57cec5SDimitry Andric StringRef jobs = s.substr(11); 17795ffd83dbSDimitry Andric if (!get_threadpool_strategy(jobs)) 17800b57cec5SDimitry Andric error("/opt:lldltojobs: invalid job count: " + jobs); 17815ffd83dbSDimitry Andric config->thinLTOJobs = jobs.str(); 17820b57cec5SDimitry Andric } else if (s.startswith("lldltopartitions=")) { 17830b57cec5SDimitry Andric StringRef n = s.substr(17); 17840b57cec5SDimitry Andric if (n.getAsInteger(10, config->ltoPartitions) || 17850b57cec5SDimitry Andric config->ltoPartitions == 0) 17860b57cec5SDimitry Andric error("/opt:lldltopartitions: invalid partition count: " + n); 17870b57cec5SDimitry Andric } else if (s != "lbr" && s != "nolbr") 17880b57cec5SDimitry Andric error("/opt: unknown option: " + s); 17890b57cec5SDimitry Andric } 17900b57cec5SDimitry Andric } 17910b57cec5SDimitry Andric 1792fe6060f1SDimitry Andric if (!icfLevel) 1793fe6060f1SDimitry Andric icfLevel = doGC ? ICFLevel::All : ICFLevel::None; 17940b57cec5SDimitry Andric config->doGC = doGC; 179581ad6265SDimitry Andric config->doICF = *icfLevel; 1796fe6060f1SDimitry Andric config->tailMerge = 1797fe6060f1SDimitry Andric (tailMerge == 1 && config->doICF != ICFLevel::None) || tailMerge == 2; 1798e8d8bef9SDimitry Andric config->ltoDebugPassManager = ltoDebugPM; 17990b57cec5SDimitry Andric 18000b57cec5SDimitry Andric // Handle /lldsavetemps 18010b57cec5SDimitry Andric if (args.hasArg(OPT_lldsavetemps)) 18020b57cec5SDimitry Andric config->saveTemps = true; 18030b57cec5SDimitry Andric 18040b57cec5SDimitry Andric // Handle /kill-at 18050b57cec5SDimitry Andric if (args.hasArg(OPT_kill_at)) 18060b57cec5SDimitry Andric config->killAt = true; 18070b57cec5SDimitry Andric 18080b57cec5SDimitry Andric // Handle /lldltocache 18090b57cec5SDimitry Andric if (auto *arg = args.getLastArg(OPT_lldltocache)) 18100b57cec5SDimitry Andric config->ltoCache = arg->getValue(); 18110b57cec5SDimitry Andric 18120b57cec5SDimitry Andric // Handle /lldsavecachepolicy 18130b57cec5SDimitry Andric if (auto *arg = args.getLastArg(OPT_lldltocachepolicy)) 18140b57cec5SDimitry Andric config->ltoCachePolicy = CHECK( 18150b57cec5SDimitry Andric parseCachePruningPolicy(arg->getValue()), 18160b57cec5SDimitry Andric Twine("/lldltocachepolicy: invalid cache policy: ") + arg->getValue()); 18170b57cec5SDimitry Andric 18180b57cec5SDimitry Andric // Handle /failifmismatch 18190b57cec5SDimitry Andric for (auto *arg : args.filtered(OPT_failifmismatch)) 18200b57cec5SDimitry Andric checkFailIfMismatch(arg->getValue(), nullptr); 18210b57cec5SDimitry Andric 18220b57cec5SDimitry Andric // Handle /merge 18230b57cec5SDimitry Andric for (auto *arg : args.filtered(OPT_merge)) 18240b57cec5SDimitry Andric parseMerge(arg->getValue()); 18250b57cec5SDimitry Andric 18260b57cec5SDimitry Andric // Add default section merging rules after user rules. User rules take 18270b57cec5SDimitry Andric // precedence, but we will emit a warning if there is a conflict. 18280b57cec5SDimitry Andric parseMerge(".idata=.rdata"); 18290b57cec5SDimitry Andric parseMerge(".didat=.rdata"); 18300b57cec5SDimitry Andric parseMerge(".edata=.rdata"); 18310b57cec5SDimitry Andric parseMerge(".xdata=.rdata"); 18320b57cec5SDimitry Andric parseMerge(".bss=.data"); 18330b57cec5SDimitry Andric 18340b57cec5SDimitry Andric if (config->mingw) { 18350b57cec5SDimitry Andric parseMerge(".ctors=.rdata"); 18360b57cec5SDimitry Andric parseMerge(".dtors=.rdata"); 18370b57cec5SDimitry Andric parseMerge(".CRT=.rdata"); 18380b57cec5SDimitry Andric } 18390b57cec5SDimitry Andric 18400b57cec5SDimitry Andric // Handle /section 18410b57cec5SDimitry Andric for (auto *arg : args.filtered(OPT_section)) 18420b57cec5SDimitry Andric parseSection(arg->getValue()); 18430b57cec5SDimitry Andric 18440b57cec5SDimitry Andric // Handle /align 18450b57cec5SDimitry Andric if (auto *arg = args.getLastArg(OPT_align)) { 18460b57cec5SDimitry Andric parseNumbers(arg->getValue(), &config->align); 18470b57cec5SDimitry Andric if (!isPowerOf2_64(config->align)) 18480b57cec5SDimitry Andric error("/align: not a power of two: " + StringRef(arg->getValue())); 1849480093f4SDimitry Andric if (!args.hasArg(OPT_driver)) 1850480093f4SDimitry Andric warn("/align specified without /driver; image may not run"); 18510b57cec5SDimitry Andric } 18520b57cec5SDimitry Andric 18530b57cec5SDimitry Andric // Handle /aligncomm 18540b57cec5SDimitry Andric for (auto *arg : args.filtered(OPT_aligncomm)) 18550b57cec5SDimitry Andric parseAligncomm(arg->getValue()); 18560b57cec5SDimitry Andric 1857349cc55cSDimitry Andric // Handle /manifestdependency. 1858349cc55cSDimitry Andric for (auto *arg : args.filtered(OPT_manifestdependency)) 1859349cc55cSDimitry Andric config->manifestDependencies.insert(arg->getValue()); 18600b57cec5SDimitry Andric 18610b57cec5SDimitry Andric // Handle /manifest and /manifest: 18620b57cec5SDimitry Andric if (auto *arg = args.getLastArg(OPT_manifest, OPT_manifest_colon)) { 18630b57cec5SDimitry Andric if (arg->getOption().getID() == OPT_manifest) 18640b57cec5SDimitry Andric config->manifest = Configuration::SideBySide; 18650b57cec5SDimitry Andric else 18660b57cec5SDimitry Andric parseManifest(arg->getValue()); 18670b57cec5SDimitry Andric } 18680b57cec5SDimitry Andric 18690b57cec5SDimitry Andric // Handle /manifestuac 18700b57cec5SDimitry Andric if (auto *arg = args.getLastArg(OPT_manifestuac)) 18710b57cec5SDimitry Andric parseManifestUAC(arg->getValue()); 18720b57cec5SDimitry Andric 18730b57cec5SDimitry Andric // Handle /manifestfile 18740b57cec5SDimitry Andric if (auto *arg = args.getLastArg(OPT_manifestfile)) 18750b57cec5SDimitry Andric config->manifestFile = arg->getValue(); 18760b57cec5SDimitry Andric 18770b57cec5SDimitry Andric // Handle /manifestinput 18780b57cec5SDimitry Andric for (auto *arg : args.filtered(OPT_manifestinput)) 18790b57cec5SDimitry Andric config->manifestInput.push_back(arg->getValue()); 18800b57cec5SDimitry Andric 18810b57cec5SDimitry Andric if (!config->manifestInput.empty() && 18820b57cec5SDimitry Andric config->manifest != Configuration::Embed) { 18830b57cec5SDimitry Andric fatal("/manifestinput: requires /manifest:embed"); 18840b57cec5SDimitry Andric } 18850b57cec5SDimitry Andric 18860b57cec5SDimitry Andric config->thinLTOEmitImportsFiles = args.hasArg(OPT_thinlto_emit_imports_files); 18870b57cec5SDimitry Andric config->thinLTOIndexOnly = args.hasArg(OPT_thinlto_index_only) || 18880b57cec5SDimitry Andric args.hasArg(OPT_thinlto_index_only_arg); 18890b57cec5SDimitry Andric config->thinLTOIndexOnlyArg = 18900b57cec5SDimitry Andric args.getLastArgValue(OPT_thinlto_index_only_arg); 18910b57cec5SDimitry Andric config->thinLTOPrefixReplace = 18920b57cec5SDimitry Andric getOldNewOptions(args, OPT_thinlto_prefix_replace); 18930b57cec5SDimitry Andric config->thinLTOObjectSuffixReplace = 18940b57cec5SDimitry Andric getOldNewOptions(args, OPT_thinlto_object_suffix_replace); 189585868e8aSDimitry Andric config->ltoObjPath = args.getLastArgValue(OPT_lto_obj_path); 1896fe6060f1SDimitry Andric config->ltoCSProfileGenerate = args.hasArg(OPT_lto_cs_profile_generate); 1897fe6060f1SDimitry Andric config->ltoCSProfileFile = args.getLastArgValue(OPT_lto_cs_profile_file); 18980b57cec5SDimitry Andric // Handle miscellaneous boolean flags. 1899349cc55cSDimitry Andric config->ltoPGOWarnMismatch = args.hasFlag(OPT_lto_pgo_warn_mismatch, 1900349cc55cSDimitry Andric OPT_lto_pgo_warn_mismatch_no, true); 19010b57cec5SDimitry Andric config->allowBind = args.hasFlag(OPT_allowbind, OPT_allowbind_no, true); 19020b57cec5SDimitry Andric config->allowIsolation = 19030b57cec5SDimitry Andric args.hasFlag(OPT_allowisolation, OPT_allowisolation_no, true); 19040b57cec5SDimitry Andric config->incremental = 19050b57cec5SDimitry Andric args.hasFlag(OPT_incremental, OPT_incremental_no, 1906fe6060f1SDimitry Andric !config->doGC && config->doICF == ICFLevel::None && 1907fe6060f1SDimitry Andric !args.hasArg(OPT_order) && !args.hasArg(OPT_profile)); 19080b57cec5SDimitry Andric config->integrityCheck = 19090b57cec5SDimitry Andric args.hasFlag(OPT_integritycheck, OPT_integritycheck_no, false); 19105ffd83dbSDimitry Andric config->cetCompat = args.hasFlag(OPT_cetcompat, OPT_cetcompat_no, false); 19110b57cec5SDimitry Andric config->nxCompat = args.hasFlag(OPT_nxcompat, OPT_nxcompat_no, true); 19120b57cec5SDimitry Andric for (auto *arg : args.filtered(OPT_swaprun)) 19130b57cec5SDimitry Andric parseSwaprun(arg->getValue()); 19140b57cec5SDimitry Andric config->terminalServerAware = 19150b57cec5SDimitry Andric !config->dll && args.hasFlag(OPT_tsaware, OPT_tsaware_no, true); 19160b57cec5SDimitry Andric config->debugDwarf = debug == DebugKind::Dwarf; 1917fe6060f1SDimitry Andric config->debugGHashes = debug == DebugKind::GHash || debug == DebugKind::Full; 19180b57cec5SDimitry Andric config->debugSymtab = debug == DebugKind::Symtab; 19195ffd83dbSDimitry Andric config->autoImport = 19205ffd83dbSDimitry Andric args.hasFlag(OPT_auto_import, OPT_auto_import_no, config->mingw); 19215ffd83dbSDimitry Andric config->pseudoRelocs = args.hasFlag( 19225ffd83dbSDimitry Andric OPT_runtime_pseudo_reloc, OPT_runtime_pseudo_reloc_no, config->mingw); 1923e8d8bef9SDimitry Andric config->callGraphProfileSort = args.hasFlag( 1924e8d8bef9SDimitry Andric OPT_call_graph_profile_sort, OPT_call_graph_profile_sort_no, true); 1925fe6060f1SDimitry Andric config->stdcallFixup = 1926fe6060f1SDimitry Andric args.hasFlag(OPT_stdcall_fixup, OPT_stdcall_fixup_no, config->mingw); 1927fe6060f1SDimitry Andric config->warnStdcallFixup = !args.hasArg(OPT_stdcall_fixup); 19280b57cec5SDimitry Andric 1929*cbe9438cSDimitry Andric if (args.hasFlag(OPT_inferasanlibs, OPT_inferasanlibs_no, false)) 1930*cbe9438cSDimitry Andric warn("ignoring '/inferasanlibs', this flag is not supported"); 1931*cbe9438cSDimitry Andric 1932e8d8bef9SDimitry Andric // Don't warn about long section names, such as .debug_info, for mingw or 1933e8d8bef9SDimitry Andric // when -debug:dwarf is requested. 1934480093f4SDimitry Andric if (config->mingw || config->debugDwarf) 1935480093f4SDimitry Andric config->warnLongSectionNames = false; 1936480093f4SDimitry Andric 19370b57cec5SDimitry Andric if (config->incremental && args.hasArg(OPT_profile)) { 19380b57cec5SDimitry Andric warn("ignoring '/incremental' due to '/profile' specification"); 19390b57cec5SDimitry Andric config->incremental = false; 19400b57cec5SDimitry Andric } 19410b57cec5SDimitry Andric 19420b57cec5SDimitry Andric if (config->incremental && args.hasArg(OPT_order)) { 19430b57cec5SDimitry Andric warn("ignoring '/incremental' due to '/order' specification"); 19440b57cec5SDimitry Andric config->incremental = false; 19450b57cec5SDimitry Andric } 19460b57cec5SDimitry Andric 19470b57cec5SDimitry Andric if (config->incremental && config->doGC) { 19480b57cec5SDimitry Andric warn("ignoring '/incremental' because REF is enabled; use '/opt:noref' to " 19490b57cec5SDimitry Andric "disable"); 19500b57cec5SDimitry Andric config->incremental = false; 19510b57cec5SDimitry Andric } 19520b57cec5SDimitry Andric 1953fe6060f1SDimitry Andric if (config->incremental && config->doICF != ICFLevel::None) { 19540b57cec5SDimitry Andric warn("ignoring '/incremental' because ICF is enabled; use '/opt:noicf' to " 19550b57cec5SDimitry Andric "disable"); 19560b57cec5SDimitry Andric config->incremental = false; 19570b57cec5SDimitry Andric } 19580b57cec5SDimitry Andric 19590b57cec5SDimitry Andric if (errorCount()) 19600b57cec5SDimitry Andric return; 19610b57cec5SDimitry Andric 19620b57cec5SDimitry Andric std::set<sys::fs::UniqueID> wholeArchives; 19630b57cec5SDimitry Andric for (auto *arg : args.filtered(OPT_wholearchive_file)) 1964bdd1243dSDimitry Andric if (std::optional<StringRef> path = doFindFile(arg->getValue())) 1965bdd1243dSDimitry Andric if (std::optional<sys::fs::UniqueID> id = getUniqueID(*path)) 19660b57cec5SDimitry Andric wholeArchives.insert(*id); 19670b57cec5SDimitry Andric 19680b57cec5SDimitry Andric // A predicate returning true if a given path is an argument for 19690b57cec5SDimitry Andric // /wholearchive:, or /wholearchive is enabled globally. 19700b57cec5SDimitry Andric // This function is a bit tricky because "foo.obj /wholearchive:././foo.obj" 19710b57cec5SDimitry Andric // needs to be handled as "/wholearchive:foo.obj foo.obj". 19720b57cec5SDimitry Andric auto isWholeArchive = [&](StringRef path) -> bool { 19730b57cec5SDimitry Andric if (args.hasArg(OPT_wholearchive_flag)) 19740b57cec5SDimitry Andric return true; 1975bdd1243dSDimitry Andric if (std::optional<sys::fs::UniqueID> id = getUniqueID(path)) 19760b57cec5SDimitry Andric return wholeArchives.count(*id); 19770b57cec5SDimitry Andric return false; 19780b57cec5SDimitry Andric }; 19790b57cec5SDimitry Andric 198085868e8aSDimitry Andric // Create a list of input files. These can be given as OPT_INPUT options 198185868e8aSDimitry Andric // and OPT_wholearchive_file options, and we also need to track OPT_start_lib 198285868e8aSDimitry Andric // and OPT_end_lib. 198385868e8aSDimitry Andric bool inLib = false; 198485868e8aSDimitry Andric for (auto *arg : args) { 198585868e8aSDimitry Andric switch (arg->getOption().getID()) { 198685868e8aSDimitry Andric case OPT_end_lib: 198785868e8aSDimitry Andric if (!inLib) 198885868e8aSDimitry Andric error("stray " + arg->getSpelling()); 198985868e8aSDimitry Andric inLib = false; 199085868e8aSDimitry Andric break; 199185868e8aSDimitry Andric case OPT_start_lib: 199285868e8aSDimitry Andric if (inLib) 199385868e8aSDimitry Andric error("nested " + arg->getSpelling()); 199485868e8aSDimitry Andric inLib = true; 199585868e8aSDimitry Andric break; 199685868e8aSDimitry Andric case OPT_wholearchive_file: 1997bdd1243dSDimitry Andric if (std::optional<StringRef> path = findFile(arg->getValue())) 199885868e8aSDimitry Andric enqueuePath(*path, true, inLib); 199985868e8aSDimitry Andric break; 200085868e8aSDimitry Andric case OPT_INPUT: 2001bdd1243dSDimitry Andric if (std::optional<StringRef> path = findFile(arg->getValue())) 200285868e8aSDimitry Andric enqueuePath(*path, isWholeArchive(*path), inLib); 200385868e8aSDimitry Andric break; 200485868e8aSDimitry Andric default: 200585868e8aSDimitry Andric // Ignore other options. 200685868e8aSDimitry Andric break; 200785868e8aSDimitry Andric } 200885868e8aSDimitry Andric } 20090b57cec5SDimitry Andric 20100b57cec5SDimitry Andric // Read all input files given via the command line. 20110b57cec5SDimitry Andric run(); 20120b57cec5SDimitry Andric if (errorCount()) 20130b57cec5SDimitry Andric return; 20140b57cec5SDimitry Andric 20150b57cec5SDimitry Andric // We should have inferred a machine type by now from the input files, but if 20160b57cec5SDimitry Andric // not we assume x64. 20170b57cec5SDimitry Andric if (config->machine == IMAGE_FILE_MACHINE_UNKNOWN) { 20180b57cec5SDimitry Andric warn("/machine is not specified. x64 is assumed"); 20190b57cec5SDimitry Andric config->machine = AMD64; 202081ad6265SDimitry Andric addWinSysRootLibSearchPaths(); 20210b57cec5SDimitry Andric } 20220b57cec5SDimitry Andric config->wordsize = config->is64() ? 8 : 4; 20230b57cec5SDimitry Andric 202481ad6265SDimitry Andric // Process files specified as /defaultlib. These must be processed after 202581ad6265SDimitry Andric // addWinSysRootLibSearchPaths(), which is why they are in a separate loop. 202681ad6265SDimitry Andric for (auto *arg : args.filtered(OPT_defaultlib)) 2027bdd1243dSDimitry Andric if (std::optional<StringRef> path = findLib(arg->getValue())) 202881ad6265SDimitry Andric enqueuePath(*path, false, false); 202981ad6265SDimitry Andric run(); 203081ad6265SDimitry Andric if (errorCount()) 203181ad6265SDimitry Andric return; 203281ad6265SDimitry Andric 2033bdd1243dSDimitry Andric // Handle /RELEASE 2034bdd1243dSDimitry Andric if (args.hasArg(OPT_release)) 2035bdd1243dSDimitry Andric config->writeCheckSum = true; 2036bdd1243dSDimitry Andric 20370b57cec5SDimitry Andric // Handle /safeseh, x86 only, on by default, except for mingw. 2038979e22ffSDimitry Andric if (config->machine == I386) { 2039979e22ffSDimitry Andric config->safeSEH = args.hasFlag(OPT_safeseh, OPT_safeseh_no, !config->mingw); 2040979e22ffSDimitry Andric config->noSEH = args.hasArg(OPT_noseh); 2041979e22ffSDimitry Andric } 20420b57cec5SDimitry Andric 20430b57cec5SDimitry Andric // Handle /functionpadmin 20440b57cec5SDimitry Andric for (auto *arg : args.filtered(OPT_functionpadmin, OPT_functionpadmin_opt)) 2045bdd1243dSDimitry Andric parseFunctionPadMin(arg); 20460b57cec5SDimitry Andric 204781ad6265SDimitry Andric if (tar) { 20480b57cec5SDimitry Andric tar->append("response.txt", 20490b57cec5SDimitry Andric createResponseFile(args, filePaths, 20500b57cec5SDimitry Andric ArrayRef<StringRef>(searchPaths).slice(1))); 205181ad6265SDimitry Andric } 20520b57cec5SDimitry Andric 20530b57cec5SDimitry Andric // Handle /largeaddressaware 20540b57cec5SDimitry Andric config->largeAddressAware = args.hasFlag( 20550b57cec5SDimitry Andric OPT_largeaddressaware, OPT_largeaddressaware_no, config->is64()); 20560b57cec5SDimitry Andric 20570b57cec5SDimitry Andric // Handle /highentropyva 20580b57cec5SDimitry Andric config->highEntropyVA = 20590b57cec5SDimitry Andric config->is64() && 20600b57cec5SDimitry Andric args.hasFlag(OPT_highentropyva, OPT_highentropyva_no, true); 20610b57cec5SDimitry Andric 20620b57cec5SDimitry Andric if (!config->dynamicBase && 20630b57cec5SDimitry Andric (config->machine == ARMNT || config->machine == ARM64)) 20640b57cec5SDimitry Andric error("/dynamicbase:no is not compatible with " + 20650b57cec5SDimitry Andric machineToStr(config->machine)); 20660b57cec5SDimitry Andric 20670b57cec5SDimitry Andric // Handle /export 20680b57cec5SDimitry Andric for (auto *arg : args.filtered(OPT_export)) { 20690b57cec5SDimitry Andric Export e = parseExport(arg->getValue()); 20700b57cec5SDimitry Andric if (config->machine == I386) { 20710b57cec5SDimitry Andric if (!isDecorated(e.name)) 207204eeddc0SDimitry Andric e.name = saver().save("_" + e.name); 20730b57cec5SDimitry Andric if (!e.extName.empty() && !isDecorated(e.extName)) 207404eeddc0SDimitry Andric e.extName = saver().save("_" + e.extName); 20750b57cec5SDimitry Andric } 20760b57cec5SDimitry Andric config->exports.push_back(e); 20770b57cec5SDimitry Andric } 20780b57cec5SDimitry Andric 20790b57cec5SDimitry Andric // Handle /def 20800b57cec5SDimitry Andric if (auto *arg = args.getLastArg(OPT_deffile)) { 20810b57cec5SDimitry Andric // parseModuleDefs mutates Config object. 20820b57cec5SDimitry Andric parseModuleDefs(arg->getValue()); 20830b57cec5SDimitry Andric } 20840b57cec5SDimitry Andric 20850b57cec5SDimitry Andric // Handle generation of import library from a def file. 2086480093f4SDimitry Andric if (!args.hasArg(OPT_INPUT, OPT_wholearchive_file)) { 20870b57cec5SDimitry Andric fixupExports(); 208881ad6265SDimitry Andric if (!config->noimplib) 20890b57cec5SDimitry Andric createImportLibrary(/*asLib=*/true); 20900b57cec5SDimitry Andric return; 20910b57cec5SDimitry Andric } 20920b57cec5SDimitry Andric 20930b57cec5SDimitry Andric // Windows specific -- if no /subsystem is given, we need to infer 20940b57cec5SDimitry Andric // that from entry point name. Must happen before /entry handling, 20950b57cec5SDimitry Andric // and after the early return when just writing an import library. 20960b57cec5SDimitry Andric if (config->subsystem == IMAGE_SUBSYSTEM_UNKNOWN) { 20970b57cec5SDimitry Andric config->subsystem = inferSubsystem(); 20980b57cec5SDimitry Andric if (config->subsystem == IMAGE_SUBSYSTEM_UNKNOWN) 20990b57cec5SDimitry Andric fatal("subsystem must be defined"); 21000b57cec5SDimitry Andric } 21010b57cec5SDimitry Andric 21020b57cec5SDimitry Andric // Handle /entry and /dll 21030b57cec5SDimitry Andric if (auto *arg = args.getLastArg(OPT_entry)) { 21040b57cec5SDimitry Andric config->entry = addUndefined(mangle(arg->getValue())); 21050b57cec5SDimitry Andric } else if (!config->entry && !config->noEntry) { 21060b57cec5SDimitry Andric if (args.hasArg(OPT_dll)) { 21070b57cec5SDimitry Andric StringRef s = (config->machine == I386) ? "__DllMainCRTStartup@12" 21080b57cec5SDimitry Andric : "_DllMainCRTStartup"; 21090b57cec5SDimitry Andric config->entry = addUndefined(s); 2110480093f4SDimitry Andric } else if (config->driverWdm) { 2111480093f4SDimitry Andric // /driver:wdm implies /entry:_NtProcessStartup 2112480093f4SDimitry Andric config->entry = addUndefined(mangle("_NtProcessStartup")); 21130b57cec5SDimitry Andric } else { 21140b57cec5SDimitry Andric // Windows specific -- If entry point name is not given, we need to 21150b57cec5SDimitry Andric // infer that from user-defined entry name. 21160b57cec5SDimitry Andric StringRef s = findDefaultEntry(); 21170b57cec5SDimitry Andric if (s.empty()) 21180b57cec5SDimitry Andric fatal("entry point must be defined"); 21190b57cec5SDimitry Andric config->entry = addUndefined(s); 21200b57cec5SDimitry Andric log("Entry name inferred: " + s); 21210b57cec5SDimitry Andric } 21220b57cec5SDimitry Andric } 21230b57cec5SDimitry Andric 21240b57cec5SDimitry Andric // Handle /delayload 21250b57cec5SDimitry Andric for (auto *arg : args.filtered(OPT_delayload)) { 21260b57cec5SDimitry Andric config->delayLoads.insert(StringRef(arg->getValue()).lower()); 21270b57cec5SDimitry Andric if (config->machine == I386) { 21280b57cec5SDimitry Andric config->delayLoadHelper = addUndefined("___delayLoadHelper2@8"); 21290b57cec5SDimitry Andric } else { 21300b57cec5SDimitry Andric config->delayLoadHelper = addUndefined("__delayLoadHelper2"); 21310b57cec5SDimitry Andric } 21320b57cec5SDimitry Andric } 21330b57cec5SDimitry Andric 21340b57cec5SDimitry Andric // Set default image name if neither /out or /def set it. 21350b57cec5SDimitry Andric if (config->outputFile.empty()) { 2136480093f4SDimitry Andric config->outputFile = getOutputPath( 2137bdd1243dSDimitry Andric (*args.filtered(OPT_INPUT, OPT_wholearchive_file).begin())->getValue(), 2138bdd1243dSDimitry Andric config->dll, config->driver); 21390b57cec5SDimitry Andric } 21400b57cec5SDimitry Andric 21410b57cec5SDimitry Andric // Fail early if an output file is not writable. 21420b57cec5SDimitry Andric if (auto e = tryCreateFile(config->outputFile)) { 21430b57cec5SDimitry Andric error("cannot open output file " + config->outputFile + ": " + e.message()); 21440b57cec5SDimitry Andric return; 21450b57cec5SDimitry Andric } 21460b57cec5SDimitry Andric 2147bdd1243dSDimitry Andric config->lldmapFile = getMapFile(args, OPT_lldmap, OPT_lldmap_file); 2148bdd1243dSDimitry Andric config->mapFile = getMapFile(args, OPT_map, OPT_map_file); 2149bdd1243dSDimitry Andric 2150bdd1243dSDimitry Andric if (config->mapFile != "" && args.hasArg(OPT_map_info)) { 2151bdd1243dSDimitry Andric for (auto *arg : args.filtered(OPT_map_info)) { 2152bdd1243dSDimitry Andric std::string s = StringRef(arg->getValue()).lower(); 2153bdd1243dSDimitry Andric if (s == "exports") 2154bdd1243dSDimitry Andric config->mapInfo = true; 2155bdd1243dSDimitry Andric else 2156bdd1243dSDimitry Andric error("unknown option: /mapinfo:" + s); 2157bdd1243dSDimitry Andric } 2158bdd1243dSDimitry Andric } 2159bdd1243dSDimitry Andric 2160bdd1243dSDimitry Andric if (config->lldmapFile != "" && config->lldmapFile == config->mapFile) { 2161bdd1243dSDimitry Andric warn("/lldmap and /map have the same output file '" + config->mapFile + 2162bdd1243dSDimitry Andric "'.\n>>> ignoring /lldmap"); 2163bdd1243dSDimitry Andric config->lldmapFile.clear(); 2164bdd1243dSDimitry Andric } 2165bdd1243dSDimitry Andric 21660b57cec5SDimitry Andric if (shouldCreatePDB) { 21670b57cec5SDimitry Andric // Put the PDB next to the image if no /pdb flag was passed. 21680b57cec5SDimitry Andric if (config->pdbPath.empty()) { 21690b57cec5SDimitry Andric config->pdbPath = config->outputFile; 21700b57cec5SDimitry Andric sys::path::replace_extension(config->pdbPath, ".pdb"); 21710b57cec5SDimitry Andric } 21720b57cec5SDimitry Andric 21730b57cec5SDimitry Andric // The embedded PDB path should be the absolute path to the PDB if no 21740b57cec5SDimitry Andric // /pdbaltpath flag was passed. 21750b57cec5SDimitry Andric if (config->pdbAltPath.empty()) { 21760b57cec5SDimitry Andric config->pdbAltPath = config->pdbPath; 21770b57cec5SDimitry Andric 21780b57cec5SDimitry Andric // It's important to make the path absolute and remove dots. This path 21790b57cec5SDimitry Andric // will eventually be written into the PE header, and certain Microsoft 21800b57cec5SDimitry Andric // tools won't work correctly if these assumptions are not held. 21810b57cec5SDimitry Andric sys::fs::make_absolute(config->pdbAltPath); 21820b57cec5SDimitry Andric sys::path::remove_dots(config->pdbAltPath); 21830b57cec5SDimitry Andric } else { 2184bdd1243dSDimitry Andric // Don't do this earlier, so that ctx.OutputFile is ready. 2185bdd1243dSDimitry Andric parsePDBAltPath(); 21860b57cec5SDimitry Andric } 21870b57cec5SDimitry Andric } 21880b57cec5SDimitry Andric 21890b57cec5SDimitry Andric // Set default image base if /base is not given. 21900b57cec5SDimitry Andric if (config->imageBase == uint64_t(-1)) 21910b57cec5SDimitry Andric config->imageBase = getDefaultImageBase(); 21920b57cec5SDimitry Andric 2193349cc55cSDimitry Andric ctx.symtab.addSynthetic(mangle("__ImageBase"), nullptr); 21940b57cec5SDimitry Andric if (config->machine == I386) { 2195349cc55cSDimitry Andric ctx.symtab.addAbsolute("___safe_se_handler_table", 0); 2196349cc55cSDimitry Andric ctx.symtab.addAbsolute("___safe_se_handler_count", 0); 21970b57cec5SDimitry Andric } 21980b57cec5SDimitry Andric 2199349cc55cSDimitry Andric ctx.symtab.addAbsolute(mangle("__guard_fids_count"), 0); 2200349cc55cSDimitry Andric ctx.symtab.addAbsolute(mangle("__guard_fids_table"), 0); 2201349cc55cSDimitry Andric ctx.symtab.addAbsolute(mangle("__guard_flags"), 0); 2202349cc55cSDimitry Andric ctx.symtab.addAbsolute(mangle("__guard_iat_count"), 0); 2203349cc55cSDimitry Andric ctx.symtab.addAbsolute(mangle("__guard_iat_table"), 0); 2204349cc55cSDimitry Andric ctx.symtab.addAbsolute(mangle("__guard_longjmp_count"), 0); 2205349cc55cSDimitry Andric ctx.symtab.addAbsolute(mangle("__guard_longjmp_table"), 0); 22060b57cec5SDimitry Andric // Needed for MSVC 2017 15.5 CRT. 2207349cc55cSDimitry Andric ctx.symtab.addAbsolute(mangle("__enclave_config"), 0); 2208fe6060f1SDimitry Andric // Needed for MSVC 2019 16.8 CRT. 2209349cc55cSDimitry Andric ctx.symtab.addAbsolute(mangle("__guard_eh_cont_count"), 0); 2210349cc55cSDimitry Andric ctx.symtab.addAbsolute(mangle("__guard_eh_cont_table"), 0); 22110b57cec5SDimitry Andric 22125ffd83dbSDimitry Andric if (config->pseudoRelocs) { 2213349cc55cSDimitry Andric ctx.symtab.addAbsolute(mangle("__RUNTIME_PSEUDO_RELOC_LIST__"), 0); 2214349cc55cSDimitry Andric ctx.symtab.addAbsolute(mangle("__RUNTIME_PSEUDO_RELOC_LIST_END__"), 0); 22155ffd83dbSDimitry Andric } 22165ffd83dbSDimitry Andric if (config->mingw) { 2217349cc55cSDimitry Andric ctx.symtab.addAbsolute(mangle("__CTOR_LIST__"), 0); 2218349cc55cSDimitry Andric ctx.symtab.addAbsolute(mangle("__DTOR_LIST__"), 0); 22190b57cec5SDimitry Andric } 22200b57cec5SDimitry Andric 22210b57cec5SDimitry Andric // This code may add new undefined symbols to the link, which may enqueue more 22220b57cec5SDimitry Andric // symbol resolution tasks, so we need to continue executing tasks until we 22230b57cec5SDimitry Andric // converge. 22240b57cec5SDimitry Andric do { 22250b57cec5SDimitry Andric // Windows specific -- if entry point is not found, 22260b57cec5SDimitry Andric // search for its mangled names. 22270b57cec5SDimitry Andric if (config->entry) 22280b57cec5SDimitry Andric mangleMaybe(config->entry); 22290b57cec5SDimitry Andric 22300b57cec5SDimitry Andric // Windows specific -- Make sure we resolve all dllexported symbols. 22310b57cec5SDimitry Andric for (Export &e : config->exports) { 22320b57cec5SDimitry Andric if (!e.forwardTo.empty()) 22330b57cec5SDimitry Andric continue; 22340b57cec5SDimitry Andric e.sym = addUndefined(e.name); 22350b57cec5SDimitry Andric if (!e.directives) 22360b57cec5SDimitry Andric e.symbolName = mangleMaybe(e.sym); 22370b57cec5SDimitry Andric } 22380b57cec5SDimitry Andric 22390b57cec5SDimitry Andric // Add weak aliases. Weak aliases is a mechanism to give remaining 22400b57cec5SDimitry Andric // undefined symbols final chance to be resolved successfully. 22410b57cec5SDimitry Andric for (auto pair : config->alternateNames) { 22420b57cec5SDimitry Andric StringRef from = pair.first; 22430b57cec5SDimitry Andric StringRef to = pair.second; 2244349cc55cSDimitry Andric Symbol *sym = ctx.symtab.find(from); 22450b57cec5SDimitry Andric if (!sym) 22460b57cec5SDimitry Andric continue; 22470b57cec5SDimitry Andric if (auto *u = dyn_cast<Undefined>(sym)) 22480b57cec5SDimitry Andric if (!u->weakAlias) 2249349cc55cSDimitry Andric u->weakAlias = ctx.symtab.addUndefined(to); 22500b57cec5SDimitry Andric } 22510b57cec5SDimitry Andric 22520b57cec5SDimitry Andric // If any inputs are bitcode files, the LTO code generator may create 22530b57cec5SDimitry Andric // references to library functions that are not explicit in the bitcode 22540b57cec5SDimitry Andric // file's symbol table. If any of those library functions are defined in a 22550b57cec5SDimitry Andric // bitcode file in an archive member, we need to arrange to use LTO to 22560b57cec5SDimitry Andric // compile those archive members by adding them to the link beforehand. 2257349cc55cSDimitry Andric if (!ctx.bitcodeFileInstances.empty()) 225885868e8aSDimitry Andric for (auto *s : lto::LTO::getRuntimeLibcallSymbols()) 2259349cc55cSDimitry Andric ctx.symtab.addLibcall(s); 22600b57cec5SDimitry Andric 22610b57cec5SDimitry Andric // Windows specific -- if __load_config_used can be resolved, resolve it. 2262349cc55cSDimitry Andric if (ctx.symtab.findUnderscore("_load_config_used")) 22630b57cec5SDimitry Andric addUndefined(mangle("_load_config_used")); 22640b57cec5SDimitry Andric 22650b57cec5SDimitry Andric if (args.hasArg(OPT_include_optional)) { 22660b57cec5SDimitry Andric // Handle /includeoptional 22670b57cec5SDimitry Andric for (auto *arg : args.filtered(OPT_include_optional)) 22680eae32dcSDimitry Andric if (isa_and_nonnull<LazyArchive>(ctx.symtab.find(arg->getValue()))) 22690b57cec5SDimitry Andric addUndefined(arg->getValue()); 22700b57cec5SDimitry Andric } 2271a4a491e2SDimitry Andric } while (run()); 22720b57cec5SDimitry Andric 2273e8d8bef9SDimitry Andric // Create wrapped symbols for -wrap option. 2274349cc55cSDimitry Andric std::vector<WrappedSymbol> wrapped = addWrappedSymbols(ctx, args); 2275e8d8bef9SDimitry Andric // Load more object files that might be needed for wrapped symbols. 2276e8d8bef9SDimitry Andric if (!wrapped.empty()) 2277e8d8bef9SDimitry Andric while (run()); 2278e8d8bef9SDimitry Andric 2279fe6060f1SDimitry Andric if (config->autoImport || config->stdcallFixup) { 22805ffd83dbSDimitry Andric // MinGW specific. 22810b57cec5SDimitry Andric // Load any further object files that might be needed for doing automatic 2282fe6060f1SDimitry Andric // imports, and do stdcall fixups. 22830b57cec5SDimitry Andric // 22840b57cec5SDimitry Andric // For cases with no automatically imported symbols, this iterates once 22850b57cec5SDimitry Andric // over the symbol table and doesn't do anything. 22860b57cec5SDimitry Andric // 22870b57cec5SDimitry Andric // For the normal case with a few automatically imported symbols, this 22880b57cec5SDimitry Andric // should only need to be run once, since each new object file imported 22890b57cec5SDimitry Andric // is an import library and wouldn't add any new undefined references, 22900b57cec5SDimitry Andric // but there's nothing stopping the __imp_ symbols from coming from a 22910b57cec5SDimitry Andric // normal object file as well (although that won't be used for the 22920b57cec5SDimitry Andric // actual autoimport later on). If this pass adds new undefined references, 22930b57cec5SDimitry Andric // we won't iterate further to resolve them. 2294fe6060f1SDimitry Andric // 2295fe6060f1SDimitry Andric // If stdcall fixups only are needed for loading import entries from 2296fe6060f1SDimitry Andric // a DLL without import library, this also just needs running once. 2297fe6060f1SDimitry Andric // If it ends up pulling in more object files from static libraries, 2298fe6060f1SDimitry Andric // (and maybe doing more stdcall fixups along the way), this would need 2299fe6060f1SDimitry Andric // to loop these two calls. 2300349cc55cSDimitry Andric ctx.symtab.loadMinGWSymbols(); 23010b57cec5SDimitry Andric run(); 23020b57cec5SDimitry Andric } 23030b57cec5SDimitry Andric 230485868e8aSDimitry Andric // At this point, we should not have any symbols that cannot be resolved. 230585868e8aSDimitry Andric // If we are going to do codegen for link-time optimization, check for 230685868e8aSDimitry Andric // unresolvable symbols first, so we don't spend time generating code that 230785868e8aSDimitry Andric // will fail to link anyway. 2308349cc55cSDimitry Andric if (!ctx.bitcodeFileInstances.empty() && !config->forceUnresolved) 2309349cc55cSDimitry Andric ctx.symtab.reportUnresolvable(); 23100b57cec5SDimitry Andric if (errorCount()) 23110b57cec5SDimitry Andric return; 23120b57cec5SDimitry Andric 2313fe6060f1SDimitry Andric config->hadExplicitExports = !config->exports.empty(); 2314fe6060f1SDimitry Andric if (config->mingw) { 2315fe6060f1SDimitry Andric // In MinGW, all symbols are automatically exported if no symbols 2316fe6060f1SDimitry Andric // are chosen to be exported. 2317fe6060f1SDimitry Andric maybeExportMinGWSymbols(args); 2318fe6060f1SDimitry Andric } 2319fe6060f1SDimitry Andric 232085868e8aSDimitry Andric // Do LTO by compiling bitcode input files to a set of native COFF files then 232185868e8aSDimitry Andric // link those files (unless -thinlto-index-only was given, in which case we 232285868e8aSDimitry Andric // resolve symbols and write indices, but don't generate native code or link). 2323349cc55cSDimitry Andric ctx.symtab.compileBitcodeFiles(); 232485868e8aSDimitry Andric 232585868e8aSDimitry Andric // If -thinlto-index-only is given, we should create only "index 232685868e8aSDimitry Andric // files" and not object files. Index file creation is already done 2327bdd1243dSDimitry Andric // in addCombinedLTOObject, so we are done if that's the case. 232885868e8aSDimitry Andric if (config->thinLTOIndexOnly) 232985868e8aSDimitry Andric return; 233085868e8aSDimitry Andric 233185868e8aSDimitry Andric // If we generated native object files from bitcode files, this resolves 233285868e8aSDimitry Andric // references to the symbols we use from them. 233385868e8aSDimitry Andric run(); 233485868e8aSDimitry Andric 2335e8d8bef9SDimitry Andric // Apply symbol renames for -wrap. 2336e8d8bef9SDimitry Andric if (!wrapped.empty()) 2337349cc55cSDimitry Andric wrapSymbols(ctx, wrapped); 2338e8d8bef9SDimitry Andric 233985868e8aSDimitry Andric // Resolve remaining undefined symbols and warn about imported locals. 2340349cc55cSDimitry Andric ctx.symtab.resolveRemainingUndefines(); 234185868e8aSDimitry Andric if (errorCount()) 234285868e8aSDimitry Andric return; 234385868e8aSDimitry Andric 23440b57cec5SDimitry Andric if (config->mingw) { 23450b57cec5SDimitry Andric // Make sure the crtend.o object is the last object file. This object 23460b57cec5SDimitry Andric // file can contain terminating section chunks that need to be placed 23470b57cec5SDimitry Andric // last. GNU ld processes files and static libraries explicitly in the 23480b57cec5SDimitry Andric // order provided on the command line, while lld will pull in needed 23490b57cec5SDimitry Andric // files from static libraries only after the last object file on the 23500b57cec5SDimitry Andric // command line. 2351349cc55cSDimitry Andric for (auto i = ctx.objFileInstances.begin(), e = ctx.objFileInstances.end(); 23520b57cec5SDimitry Andric i != e; i++) { 23530b57cec5SDimitry Andric ObjFile *file = *i; 23540b57cec5SDimitry Andric if (isCrtend(file->getName())) { 2355349cc55cSDimitry Andric ctx.objFileInstances.erase(i); 2356349cc55cSDimitry Andric ctx.objFileInstances.push_back(file); 23570b57cec5SDimitry Andric break; 23580b57cec5SDimitry Andric } 23590b57cec5SDimitry Andric } 23600b57cec5SDimitry Andric } 23610b57cec5SDimitry Andric 23620b57cec5SDimitry Andric // Windows specific -- when we are creating a .dll file, we also 236385868e8aSDimitry Andric // need to create a .lib file. In MinGW mode, we only do that when the 236485868e8aSDimitry Andric // -implib option is given explicitly, for compatibility with GNU ld. 23650b57cec5SDimitry Andric if (!config->exports.empty() || config->dll) { 23660b57cec5SDimitry Andric fixupExports(); 236781ad6265SDimitry Andric if (!config->noimplib && (!config->mingw || !config->implib.empty())) 23680b57cec5SDimitry Andric createImportLibrary(/*asLib=*/false); 23690b57cec5SDimitry Andric assignExportOrdinals(); 23700b57cec5SDimitry Andric } 23710b57cec5SDimitry Andric 23720b57cec5SDimitry Andric // Handle /output-def (MinGW specific). 23730b57cec5SDimitry Andric if (auto *arg = args.getLastArg(OPT_output_def)) 2374bdd1243dSDimitry Andric writeDefFile(arg->getValue(), config->exports); 23750b57cec5SDimitry Andric 23760b57cec5SDimitry Andric // Set extra alignment for .comm symbols 23770b57cec5SDimitry Andric for (auto pair : config->alignComm) { 23780b57cec5SDimitry Andric StringRef name = pair.first; 23790b57cec5SDimitry Andric uint32_t alignment = pair.second; 23800b57cec5SDimitry Andric 2381349cc55cSDimitry Andric Symbol *sym = ctx.symtab.find(name); 23820b57cec5SDimitry Andric if (!sym) { 23830b57cec5SDimitry Andric warn("/aligncomm symbol " + name + " not found"); 23840b57cec5SDimitry Andric continue; 23850b57cec5SDimitry Andric } 23860b57cec5SDimitry Andric 23870b57cec5SDimitry Andric // If the symbol isn't common, it must have been replaced with a regular 23880b57cec5SDimitry Andric // symbol, which will carry its own alignment. 23890b57cec5SDimitry Andric auto *dc = dyn_cast<DefinedCommon>(sym); 23900b57cec5SDimitry Andric if (!dc) 23910b57cec5SDimitry Andric continue; 23920b57cec5SDimitry Andric 23930b57cec5SDimitry Andric CommonChunk *c = dc->getChunk(); 23940b57cec5SDimitry Andric c->setAlignment(std::max(c->getAlignment(), alignment)); 23950b57cec5SDimitry Andric } 23960b57cec5SDimitry Andric 2397349cc55cSDimitry Andric // Windows specific -- Create an embedded or side-by-side manifest. 2398349cc55cSDimitry Andric // /manifestdependency: enables /manifest unless an explicit /manifest:no is 2399349cc55cSDimitry Andric // also passed. 2400349cc55cSDimitry Andric if (config->manifest == Configuration::Embed) 2401349cc55cSDimitry Andric addBuffer(createManifestRes(), false, false); 2402349cc55cSDimitry Andric else if (config->manifest == Configuration::SideBySide || 2403349cc55cSDimitry Andric (config->manifest == Configuration::Default && 2404349cc55cSDimitry Andric !config->manifestDependencies.empty())) 24050b57cec5SDimitry Andric createSideBySideManifest(); 24060b57cec5SDimitry Andric 24070b57cec5SDimitry Andric // Handle /order. We want to do this at this moment because we 24080b57cec5SDimitry Andric // need a complete list of comdat sections to warn on nonexistent 24090b57cec5SDimitry Andric // functions. 2410e8d8bef9SDimitry Andric if (auto *arg = args.getLastArg(OPT_order)) { 2411e8d8bef9SDimitry Andric if (args.hasArg(OPT_call_graph_ordering_file)) 2412e8d8bef9SDimitry Andric error("/order and /call-graph-order-file may not be used together"); 2413bdd1243dSDimitry Andric parseOrderFile(arg->getValue()); 2414e8d8bef9SDimitry Andric config->callGraphProfileSort = false; 2415e8d8bef9SDimitry Andric } 2416e8d8bef9SDimitry Andric 2417e8d8bef9SDimitry Andric // Handle /call-graph-ordering-file and /call-graph-profile-sort (default on). 2418e8d8bef9SDimitry Andric if (config->callGraphProfileSort) { 2419e8d8bef9SDimitry Andric if (auto *arg = args.getLastArg(OPT_call_graph_ordering_file)) { 2420bdd1243dSDimitry Andric parseCallGraphFile(arg->getValue()); 2421e8d8bef9SDimitry Andric } 2422349cc55cSDimitry Andric readCallGraphsFromObjectFiles(ctx); 2423e8d8bef9SDimitry Andric } 2424e8d8bef9SDimitry Andric 2425e8d8bef9SDimitry Andric // Handle /print-symbol-order. 2426e8d8bef9SDimitry Andric if (auto *arg = args.getLastArg(OPT_print_symbol_order)) 2427e8d8bef9SDimitry Andric config->printSymbolOrder = arg->getValue(); 24280b57cec5SDimitry Andric 24290b57cec5SDimitry Andric // Identify unreferenced COMDAT sections. 2430fe6060f1SDimitry Andric if (config->doGC) { 2431fe6060f1SDimitry Andric if (config->mingw) { 2432fe6060f1SDimitry Andric // markLive doesn't traverse .eh_frame, but the personality function is 2433fe6060f1SDimitry Andric // only reached that way. The proper solution would be to parse and 2434fe6060f1SDimitry Andric // traverse the .eh_frame section, like the ELF linker does. 2435fe6060f1SDimitry Andric // For now, just manually try to retain the known possible personality 2436fe6060f1SDimitry Andric // functions. This doesn't bring in more object files, but only marks 2437fe6060f1SDimitry Andric // functions that already have been included to be retained. 2438bdd1243dSDimitry Andric for (const char *n : {"__gxx_personality_v0", "__gcc_personality_v0", 2439bdd1243dSDimitry Andric "rust_eh_personality"}) { 2440349cc55cSDimitry Andric Defined *d = dyn_cast_or_null<Defined>(ctx.symtab.findUnderscore(n)); 2441fe6060f1SDimitry Andric if (d && !d->isGCRoot) { 2442fe6060f1SDimitry Andric d->isGCRoot = true; 2443fe6060f1SDimitry Andric config->gcroot.push_back(d); 2444fe6060f1SDimitry Andric } 2445fe6060f1SDimitry Andric } 2446fe6060f1SDimitry Andric } 2447fe6060f1SDimitry Andric 2448349cc55cSDimitry Andric markLive(ctx); 2449fe6060f1SDimitry Andric } 24500b57cec5SDimitry Andric 24510b57cec5SDimitry Andric // Needs to happen after the last call to addFile(). 245285868e8aSDimitry Andric convertResources(); 24530b57cec5SDimitry Andric 24540b57cec5SDimitry Andric // Identify identical COMDAT sections to merge them. 2455fe6060f1SDimitry Andric if (config->doICF != ICFLevel::None) { 2456349cc55cSDimitry Andric findKeepUniqueSections(ctx); 2457bdd1243dSDimitry Andric doICF(ctx); 24580b57cec5SDimitry Andric } 24590b57cec5SDimitry Andric 24600b57cec5SDimitry Andric // Write the result. 2461349cc55cSDimitry Andric writeResult(ctx); 24620b57cec5SDimitry Andric 24630b57cec5SDimitry Andric // Stop early so we can print the results. 24645ffd83dbSDimitry Andric rootTimer.stop(); 24650b57cec5SDimitry Andric if (config->showTiming) 2466349cc55cSDimitry Andric ctx.rootTimer.print(); 24670b57cec5SDimitry Andric } 24680b57cec5SDimitry Andric 2469bdd1243dSDimitry Andric } // namespace lld::coff 2470