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" 21*bdd1243dSDimitry 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> 55*bdd1243dSDimitry 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 62*bdd1243dSDimitry 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 74*bdd1243dSDimitry 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". 95*bdd1243dSDimitry Andric static std::string getOutputPath(StringRef path, bool isDll, bool isDriver) { 96480093f4SDimitry Andric StringRef ext = ".exe"; 97*bdd1243dSDimitry Andric if (isDll) 98480093f4SDimitry Andric ext = ".dll"; 99*bdd1243dSDimitry 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. 143*bdd1243dSDimitry Andric StringRef LinkerDriver::mangle(StringRef sym) { 144*bdd1243dSDimitry Andric assert(ctx.config.machine != IMAGE_FILE_MACHINE_UNKNOWN); 145*bdd1243dSDimitry Andric if (ctx.config.machine == I386) 14604eeddc0SDimitry Andric return saver().save("_" + sym); 1470b57cec5SDimitry Andric return sym; 1480b57cec5SDimitry Andric } 1490b57cec5SDimitry Andric 150*bdd1243dSDimitry Andric llvm::Triple::ArchType LinkerDriver::getArch() { 151*bdd1243dSDimitry 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 174*bdd1243dSDimitry Andric if (ctx.driver.tar) 175*bdd1243dSDimitry 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: 220*bdd1243dSDimitry 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 } 229*bdd1243dSDimitry 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; 251*bdd1243dSDimitry 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 256*bdd1243dSDimitry 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); 277*bdd1243dSDimitry Andric } else if (magic == file_magic::coff_cl_gl_object) { 278*bdd1243dSDimitry Andric error(mb.getBufferIdentifier() + 279*bdd1243dSDimitry Andric ": is not a native COFF file. Recompile without /GL?"); 280*bdd1243dSDimitry 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 " + 297*bdd1243dSDimitry Andric toCOFFString(ctx, sym) + ": " + parentName + "(" + childName + 298*bdd1243dSDimitry 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([=]() { 308*bdd1243dSDimitry Andric ctx.driver.addArchiveBuffer(mb, toCOFFString(ctx, sym), parentName, 3090b57cec5SDimitry Andric offsetInArchive); 3100b57cec5SDimitry Andric }); 3110b57cec5SDimitry Andric return; 3120b57cec5SDimitry Andric } 3130b57cec5SDimitry Andric 314*bdd1243dSDimitry Andric std::string childName = 315*bdd1243dSDimitry Andric CHECK(c.getFullName(), 3160b57cec5SDimitry Andric "could not get the filename for the member defining symbol " + 317*bdd1243dSDimitry 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. 326*bdd1243dSDimitry Andric ctx.driver.addArchiveBuffer(takeBuffer(std::move(mbOrErr.first)), 327*bdd1243dSDimitry Andric toCOFFString(ctx, sym), "", 328*bdd1243dSDimitry Andric /*OffsetInArchive=*/0); 3290b57cec5SDimitry Andric }); 3300b57cec5SDimitry Andric } 3310b57cec5SDimitry Andric 332*bdd1243dSDimitry Andric bool LinkerDriver::isDecorated(StringRef sym) { 3330b57cec5SDimitry Andric return sym.startswith("@") || sym.contains("@@") || sym.startswith("?") || 334*bdd1243dSDimitry 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 346*bdd1243dSDimitry 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); 360*bdd1243dSDimitry 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; 367*bdd1243dSDimitry 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: 392*bdd1243dSDimitry Andric if (std::optional<StringRef> path = findLib(arg->getValue())) 39385868e8aSDimitry Andric enqueuePath(*path, false, false); 3940b57cec5SDimitry Andric break; 3950b57cec5SDimitry Andric case OPT_entry: 396*bdd1243dSDimitry 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: 405*bdd1243dSDimitry 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: 411*bdd1243dSDimitry Andric ctx.config.noDefaultLibs.insert(doFindLib(arg->getValue()).lower()); 412*bdd1243dSDimitry Andric break; 413*bdd1243dSDimitry Andric case OPT_release: 414*bdd1243dSDimitry 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: 420*bdd1243dSDimitry Andric parseNumbers(arg->getValue(), &ctx.config.stackReserve, 421*bdd1243dSDimitry Andric &ctx.config.stackCommit); 422fe6060f1SDimitry Andric break; 423e8d8bef9SDimitry Andric case OPT_subsystem: { 424e8d8bef9SDimitry Andric bool gotVersion = false; 425*bdd1243dSDimitry Andric parseSubsystem(arg->getValue(), &ctx.config.subsystem, 426*bdd1243dSDimitry Andric &ctx.config.majorSubsystemVersion, 427*bdd1243dSDimitry Andric &ctx.config.minorSubsystemVersion, &gotVersion); 428e8d8bef9SDimitry Andric if (gotVersion) { 429*bdd1243dSDimitry Andric ctx.config.majorOSVersion = ctx.config.majorSubsystemVersion; 430*bdd1243dSDimitry 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: 4390b57cec5SDimitry Andric break; 4400b57cec5SDimitry Andric default: 4410b57cec5SDimitry Andric error(arg->getSpelling() + " is not allowed in .drectve"); 4420b57cec5SDimitry Andric } 4430b57cec5SDimitry Andric } 4440b57cec5SDimitry Andric } 4450b57cec5SDimitry Andric 4460b57cec5SDimitry Andric // Find file from search paths. You can omit ".obj", this function takes 4470b57cec5SDimitry Andric // care of that. Note that the returned path is not guaranteed to exist. 4480b57cec5SDimitry Andric StringRef LinkerDriver::doFindFile(StringRef filename) { 449*bdd1243dSDimitry Andric auto getFilename = [this](StringRef filename) -> StringRef { 450*bdd1243dSDimitry Andric if (ctx.config.vfs) 451*bdd1243dSDimitry Andric if (auto statOrErr = ctx.config.vfs->status(filename)) 452753f127fSDimitry Andric return saver().save(statOrErr->getName()); 453753f127fSDimitry Andric return filename; 454753f127fSDimitry Andric }; 455753f127fSDimitry Andric 4560b57cec5SDimitry Andric bool hasPathSep = (filename.find_first_of("/\\") != StringRef::npos); 4570b57cec5SDimitry Andric if (hasPathSep) 458753f127fSDimitry Andric return getFilename(filename); 4590b57cec5SDimitry Andric bool hasExt = filename.contains('.'); 4600b57cec5SDimitry Andric for (StringRef dir : searchPaths) { 4610b57cec5SDimitry Andric SmallString<128> path = dir; 4620b57cec5SDimitry Andric sys::path::append(path, filename); 463753f127fSDimitry Andric path = SmallString<128>{getFilename(path.str())}; 4640b57cec5SDimitry Andric if (sys::fs::exists(path.str())) 46504eeddc0SDimitry Andric return saver().save(path.str()); 4660b57cec5SDimitry Andric if (!hasExt) { 4670b57cec5SDimitry Andric path.append(".obj"); 468753f127fSDimitry Andric path = SmallString<128>{getFilename(path.str())}; 4690b57cec5SDimitry Andric if (sys::fs::exists(path.str())) 47004eeddc0SDimitry Andric return saver().save(path.str()); 4710b57cec5SDimitry Andric } 4720b57cec5SDimitry Andric } 4730b57cec5SDimitry Andric return filename; 4740b57cec5SDimitry Andric } 4750b57cec5SDimitry Andric 476*bdd1243dSDimitry Andric static std::optional<sys::fs::UniqueID> getUniqueID(StringRef path) { 4770b57cec5SDimitry Andric sys::fs::UniqueID ret; 4780b57cec5SDimitry Andric if (sys::fs::getUniqueID(path, ret)) 479*bdd1243dSDimitry Andric return std::nullopt; 4800b57cec5SDimitry Andric return ret; 4810b57cec5SDimitry Andric } 4820b57cec5SDimitry Andric 4830b57cec5SDimitry Andric // Resolves a file path. This never returns the same path 484*bdd1243dSDimitry Andric // (in that case, it returns std::nullopt). 485*bdd1243dSDimitry Andric std::optional<StringRef> LinkerDriver::findFile(StringRef filename) { 4860b57cec5SDimitry Andric StringRef path = doFindFile(filename); 4870b57cec5SDimitry Andric 488*bdd1243dSDimitry Andric if (std::optional<sys::fs::UniqueID> id = getUniqueID(path)) { 4890b57cec5SDimitry Andric bool seen = !visitedFiles.insert(*id).second; 4900b57cec5SDimitry Andric if (seen) 491*bdd1243dSDimitry Andric return std::nullopt; 4920b57cec5SDimitry Andric } 4930b57cec5SDimitry Andric 494fe6060f1SDimitry Andric if (path.endswith_insensitive(".lib")) 49581ad6265SDimitry Andric visitedLibs.insert(std::string(sys::path::filename(path).lower())); 4960b57cec5SDimitry Andric return path; 4970b57cec5SDimitry Andric } 4980b57cec5SDimitry Andric 4990b57cec5SDimitry Andric // MinGW specific. If an embedded directive specified to link to 5000b57cec5SDimitry Andric // foo.lib, but it isn't found, try libfoo.a instead. 5010b57cec5SDimitry Andric StringRef LinkerDriver::doFindLibMinGW(StringRef filename) { 5020b57cec5SDimitry Andric if (filename.contains('/') || filename.contains('\\')) 5030b57cec5SDimitry Andric return filename; 5040b57cec5SDimitry Andric 5050b57cec5SDimitry Andric SmallString<128> s = filename; 5060b57cec5SDimitry Andric sys::path::replace_extension(s, ".a"); 50704eeddc0SDimitry Andric StringRef libName = saver().save("lib" + s.str()); 5080b57cec5SDimitry Andric return doFindFile(libName); 5090b57cec5SDimitry Andric } 5100b57cec5SDimitry Andric 5110b57cec5SDimitry Andric // Find library file from search path. 5120b57cec5SDimitry Andric StringRef LinkerDriver::doFindLib(StringRef filename) { 5130b57cec5SDimitry Andric // Add ".lib" to Filename if that has no file extension. 5140b57cec5SDimitry Andric bool hasExt = filename.contains('.'); 5150b57cec5SDimitry Andric if (!hasExt) 51604eeddc0SDimitry Andric filename = saver().save(filename + ".lib"); 5170b57cec5SDimitry Andric StringRef ret = doFindFile(filename); 5180b57cec5SDimitry Andric // For MinGW, if the find above didn't turn up anything, try 5190b57cec5SDimitry Andric // looking for a MinGW formatted library name. 520*bdd1243dSDimitry Andric if (ctx.config.mingw && ret == filename) 5210b57cec5SDimitry Andric return doFindLibMinGW(filename); 5220b57cec5SDimitry Andric return ret; 5230b57cec5SDimitry Andric } 5240b57cec5SDimitry Andric 5250b57cec5SDimitry Andric // Resolves a library path. /nodefaultlib options are taken into 5260b57cec5SDimitry Andric // consideration. This never returns the same path (in that case, 527*bdd1243dSDimitry Andric // it returns std::nullopt). 528*bdd1243dSDimitry Andric std::optional<StringRef> LinkerDriver::findLib(StringRef filename) { 529*bdd1243dSDimitry Andric if (ctx.config.noDefaultLibAll) 530*bdd1243dSDimitry Andric return std::nullopt; 5310b57cec5SDimitry Andric if (!visitedLibs.insert(filename.lower()).second) 532*bdd1243dSDimitry Andric return std::nullopt; 5330b57cec5SDimitry Andric 5340b57cec5SDimitry Andric StringRef path = doFindLib(filename); 535*bdd1243dSDimitry Andric if (ctx.config.noDefaultLibs.count(path.lower())) 536*bdd1243dSDimitry Andric return std::nullopt; 5370b57cec5SDimitry Andric 538*bdd1243dSDimitry Andric if (std::optional<sys::fs::UniqueID> id = getUniqueID(path)) 5390b57cec5SDimitry Andric if (!visitedFiles.insert(*id).second) 540*bdd1243dSDimitry Andric return std::nullopt; 5410b57cec5SDimitry Andric return path; 5420b57cec5SDimitry Andric } 5430b57cec5SDimitry Andric 54481ad6265SDimitry Andric void LinkerDriver::detectWinSysRoot(const opt::InputArgList &Args) { 54581ad6265SDimitry Andric IntrusiveRefCntPtr<vfs::FileSystem> VFS = vfs::getRealFileSystem(); 54681ad6265SDimitry Andric 54781ad6265SDimitry Andric // Check the command line first, that's the user explicitly telling us what to 54881ad6265SDimitry Andric // use. Check the environment next, in case we're being invoked from a VS 54981ad6265SDimitry Andric // command prompt. Failing that, just try to find the newest Visual Studio 55081ad6265SDimitry Andric // version we can and use its default VC toolchain. 551*bdd1243dSDimitry Andric std::optional<StringRef> VCToolsDir, VCToolsVersion, WinSysRoot; 55281ad6265SDimitry Andric if (auto *A = Args.getLastArg(OPT_vctoolsdir)) 55381ad6265SDimitry Andric VCToolsDir = A->getValue(); 55481ad6265SDimitry Andric if (auto *A = Args.getLastArg(OPT_vctoolsversion)) 55581ad6265SDimitry Andric VCToolsVersion = A->getValue(); 55681ad6265SDimitry Andric if (auto *A = Args.getLastArg(OPT_winsysroot)) 55781ad6265SDimitry Andric WinSysRoot = A->getValue(); 55881ad6265SDimitry Andric if (!findVCToolChainViaCommandLine(*VFS, VCToolsDir, VCToolsVersion, 55981ad6265SDimitry Andric WinSysRoot, vcToolChainPath, vsLayout) && 56081ad6265SDimitry Andric (Args.hasArg(OPT_lldignoreenv) || 56181ad6265SDimitry Andric !findVCToolChainViaEnvironment(*VFS, vcToolChainPath, vsLayout)) && 56281ad6265SDimitry Andric !findVCToolChainViaSetupConfig(*VFS, vcToolChainPath, vsLayout) && 56381ad6265SDimitry Andric !findVCToolChainViaRegistry(vcToolChainPath, vsLayout)) 56481ad6265SDimitry Andric return; 56581ad6265SDimitry Andric 56681ad6265SDimitry Andric // If the VC environment hasn't been configured (perhaps because the user did 56781ad6265SDimitry Andric // not run vcvarsall), try to build a consistent link environment. If the 56881ad6265SDimitry Andric // environment variable is set however, assume the user knows what they're 56981ad6265SDimitry Andric // doing. If the user passes /vctoolsdir or /winsdkdir, trust that over env 57081ad6265SDimitry Andric // vars. 57181ad6265SDimitry Andric if (const auto *A = Args.getLastArg(OPT_diasdkdir, OPT_winsysroot)) { 57281ad6265SDimitry Andric diaPath = A->getValue(); 57381ad6265SDimitry Andric if (A->getOption().getID() == OPT_winsysroot) 57481ad6265SDimitry Andric path::append(diaPath, "DIA SDK"); 57581ad6265SDimitry Andric } 57681ad6265SDimitry Andric useWinSysRootLibPath = Args.hasArg(OPT_lldignoreenv) || 57781ad6265SDimitry Andric !Process::GetEnv("LIB") || 57881ad6265SDimitry Andric Args.getLastArg(OPT_vctoolsdir, OPT_winsysroot); 57981ad6265SDimitry Andric if (Args.hasArg(OPT_lldignoreenv) || !Process::GetEnv("LIB") || 58081ad6265SDimitry Andric Args.getLastArg(OPT_winsdkdir, OPT_winsysroot)) { 581*bdd1243dSDimitry Andric std::optional<StringRef> WinSdkDir, WinSdkVersion; 58281ad6265SDimitry Andric if (auto *A = Args.getLastArg(OPT_winsdkdir)) 58381ad6265SDimitry Andric WinSdkDir = A->getValue(); 58481ad6265SDimitry Andric if (auto *A = Args.getLastArg(OPT_winsdkversion)) 58581ad6265SDimitry Andric WinSdkVersion = A->getValue(); 58681ad6265SDimitry Andric 58781ad6265SDimitry Andric if (useUniversalCRT(vsLayout, vcToolChainPath, getArch(), *VFS)) { 58881ad6265SDimitry Andric std::string UniversalCRTSdkPath; 58981ad6265SDimitry Andric std::string UCRTVersion; 59081ad6265SDimitry Andric if (getUniversalCRTSdkDir(*VFS, WinSdkDir, WinSdkVersion, WinSysRoot, 59181ad6265SDimitry Andric UniversalCRTSdkPath, UCRTVersion)) { 59281ad6265SDimitry Andric universalCRTLibPath = UniversalCRTSdkPath; 59381ad6265SDimitry Andric path::append(universalCRTLibPath, "Lib", UCRTVersion, "ucrt"); 59481ad6265SDimitry Andric } 59581ad6265SDimitry Andric } 59681ad6265SDimitry Andric 59781ad6265SDimitry Andric std::string sdkPath; 59881ad6265SDimitry Andric std::string windowsSDKIncludeVersion; 59981ad6265SDimitry Andric std::string windowsSDKLibVersion; 60081ad6265SDimitry Andric if (getWindowsSDKDir(*VFS, WinSdkDir, WinSdkVersion, WinSysRoot, sdkPath, 60181ad6265SDimitry Andric sdkMajor, windowsSDKIncludeVersion, 60281ad6265SDimitry Andric windowsSDKLibVersion)) { 60381ad6265SDimitry Andric windowsSdkLibPath = sdkPath; 60481ad6265SDimitry Andric path::append(windowsSdkLibPath, "Lib"); 60581ad6265SDimitry Andric if (sdkMajor >= 8) 60681ad6265SDimitry Andric path::append(windowsSdkLibPath, windowsSDKLibVersion, "um"); 60781ad6265SDimitry Andric } 60881ad6265SDimitry Andric } 60981ad6265SDimitry Andric } 61081ad6265SDimitry Andric 61181ad6265SDimitry Andric void LinkerDriver::addWinSysRootLibSearchPaths() { 61281ad6265SDimitry Andric if (!diaPath.empty()) { 61381ad6265SDimitry Andric // The DIA SDK always uses the legacy vc arch, even in new MSVC versions. 61481ad6265SDimitry Andric path::append(diaPath, "lib", archToLegacyVCArch(getArch())); 61581ad6265SDimitry Andric searchPaths.push_back(saver().save(diaPath.str())); 61681ad6265SDimitry Andric } 61781ad6265SDimitry Andric if (useWinSysRootLibPath) { 61881ad6265SDimitry Andric searchPaths.push_back(saver().save(getSubDirectoryPath( 61981ad6265SDimitry Andric SubDirectoryType::Lib, vsLayout, vcToolChainPath, getArch()))); 62081ad6265SDimitry Andric searchPaths.push_back(saver().save( 62181ad6265SDimitry Andric getSubDirectoryPath(SubDirectoryType::Lib, vsLayout, vcToolChainPath, 62281ad6265SDimitry Andric getArch(), "atlmfc"))); 62381ad6265SDimitry Andric } 62481ad6265SDimitry Andric if (!universalCRTLibPath.empty()) { 62581ad6265SDimitry Andric StringRef ArchName = archToWindowsSDKArch(getArch()); 62681ad6265SDimitry Andric if (!ArchName.empty()) { 62781ad6265SDimitry Andric path::append(universalCRTLibPath, ArchName); 62881ad6265SDimitry Andric searchPaths.push_back(saver().save(universalCRTLibPath.str())); 62981ad6265SDimitry Andric } 63081ad6265SDimitry Andric } 63181ad6265SDimitry Andric if (!windowsSdkLibPath.empty()) { 63281ad6265SDimitry Andric std::string path; 63381ad6265SDimitry Andric if (appendArchToWindowsSDKLibPath(sdkMajor, windowsSdkLibPath, getArch(), 63481ad6265SDimitry Andric path)) 63581ad6265SDimitry Andric searchPaths.push_back(saver().save(path)); 63681ad6265SDimitry Andric } 63781ad6265SDimitry Andric } 63881ad6265SDimitry Andric 6390b57cec5SDimitry Andric // Parses LIB environment which contains a list of search paths. 6400b57cec5SDimitry Andric void LinkerDriver::addLibSearchPaths() { 641*bdd1243dSDimitry Andric std::optional<std::string> envOpt = Process::GetEnv("LIB"); 64281ad6265SDimitry Andric if (!envOpt) 6430b57cec5SDimitry Andric return; 64404eeddc0SDimitry Andric StringRef env = saver().save(*envOpt); 6450b57cec5SDimitry Andric while (!env.empty()) { 6460b57cec5SDimitry Andric StringRef path; 6470b57cec5SDimitry Andric std::tie(path, env) = env.split(';'); 6480b57cec5SDimitry Andric searchPaths.push_back(path); 6490b57cec5SDimitry Andric } 6500b57cec5SDimitry Andric } 6510b57cec5SDimitry Andric 6520b57cec5SDimitry Andric Symbol *LinkerDriver::addUndefined(StringRef name) { 653349cc55cSDimitry Andric Symbol *b = ctx.symtab.addUndefined(name); 6540b57cec5SDimitry Andric if (!b->isGCRoot) { 6550b57cec5SDimitry Andric b->isGCRoot = true; 656*bdd1243dSDimitry Andric ctx.config.gcroot.push_back(b); 6570b57cec5SDimitry Andric } 6580b57cec5SDimitry Andric return b; 6590b57cec5SDimitry Andric } 6600b57cec5SDimitry Andric 6610b57cec5SDimitry Andric StringRef LinkerDriver::mangleMaybe(Symbol *s) { 6620b57cec5SDimitry Andric // If the plain symbol name has already been resolved, do nothing. 6630b57cec5SDimitry Andric Undefined *unmangled = dyn_cast<Undefined>(s); 6640b57cec5SDimitry Andric if (!unmangled) 6650b57cec5SDimitry Andric return ""; 6660b57cec5SDimitry Andric 6670b57cec5SDimitry Andric // Otherwise, see if a similar, mangled symbol exists in the symbol table. 668349cc55cSDimitry Andric Symbol *mangled = ctx.symtab.findMangle(unmangled->getName()); 6690b57cec5SDimitry Andric if (!mangled) 6700b57cec5SDimitry Andric return ""; 6710b57cec5SDimitry Andric 6720b57cec5SDimitry Andric // If we find a similar mangled symbol, make this an alias to it and return 6730b57cec5SDimitry Andric // its name. 6740b57cec5SDimitry Andric log(unmangled->getName() + " aliased to " + mangled->getName()); 675349cc55cSDimitry Andric unmangled->weakAlias = ctx.symtab.addUndefined(mangled->getName()); 6760b57cec5SDimitry Andric return mangled->getName(); 6770b57cec5SDimitry Andric } 6780b57cec5SDimitry Andric 6790b57cec5SDimitry Andric // Windows specific -- find default entry point name. 6800b57cec5SDimitry Andric // 6810b57cec5SDimitry Andric // There are four different entry point functions for Windows executables, 6820b57cec5SDimitry Andric // each of which corresponds to a user-defined "main" function. This function 6830b57cec5SDimitry Andric // infers an entry point from a user-defined "main" function. 6840b57cec5SDimitry Andric StringRef LinkerDriver::findDefaultEntry() { 685*bdd1243dSDimitry Andric assert(ctx.config.subsystem != IMAGE_SUBSYSTEM_UNKNOWN && 6860b57cec5SDimitry Andric "must handle /subsystem before calling this"); 6870b57cec5SDimitry Andric 688*bdd1243dSDimitry Andric if (ctx.config.mingw) 689*bdd1243dSDimitry Andric return mangle(ctx.config.subsystem == IMAGE_SUBSYSTEM_WINDOWS_GUI 6900b57cec5SDimitry Andric ? "WinMainCRTStartup" 6910b57cec5SDimitry Andric : "mainCRTStartup"); 6920b57cec5SDimitry Andric 693*bdd1243dSDimitry Andric if (ctx.config.subsystem == IMAGE_SUBSYSTEM_WINDOWS_GUI) { 6940b57cec5SDimitry Andric if (findUnderscoreMangle("wWinMain")) { 6950b57cec5SDimitry Andric if (!findUnderscoreMangle("WinMain")) 6960b57cec5SDimitry Andric return mangle("wWinMainCRTStartup"); 6970b57cec5SDimitry Andric warn("found both wWinMain and WinMain; using latter"); 6980b57cec5SDimitry Andric } 6990b57cec5SDimitry Andric return mangle("WinMainCRTStartup"); 7000b57cec5SDimitry Andric } 7010b57cec5SDimitry Andric if (findUnderscoreMangle("wmain")) { 7020b57cec5SDimitry Andric if (!findUnderscoreMangle("main")) 7030b57cec5SDimitry Andric return mangle("wmainCRTStartup"); 7040b57cec5SDimitry Andric warn("found both wmain and main; using latter"); 7050b57cec5SDimitry Andric } 7060b57cec5SDimitry Andric return mangle("mainCRTStartup"); 7070b57cec5SDimitry Andric } 7080b57cec5SDimitry Andric 7090b57cec5SDimitry Andric WindowsSubsystem LinkerDriver::inferSubsystem() { 710*bdd1243dSDimitry Andric if (ctx.config.dll) 7110b57cec5SDimitry Andric return IMAGE_SUBSYSTEM_WINDOWS_GUI; 712*bdd1243dSDimitry Andric if (ctx.config.mingw) 7130b57cec5SDimitry Andric return IMAGE_SUBSYSTEM_WINDOWS_CUI; 7140b57cec5SDimitry Andric // Note that link.exe infers the subsystem from the presence of these 7150b57cec5SDimitry Andric // functions even if /entry: or /nodefaultlib are passed which causes them 7160b57cec5SDimitry Andric // to not be called. 7170b57cec5SDimitry Andric bool haveMain = findUnderscoreMangle("main"); 7180b57cec5SDimitry Andric bool haveWMain = findUnderscoreMangle("wmain"); 7190b57cec5SDimitry Andric bool haveWinMain = findUnderscoreMangle("WinMain"); 7200b57cec5SDimitry Andric bool haveWWinMain = findUnderscoreMangle("wWinMain"); 7210b57cec5SDimitry Andric if (haveMain || haveWMain) { 7220b57cec5SDimitry Andric if (haveWinMain || haveWWinMain) { 7230b57cec5SDimitry Andric warn(std::string("found ") + (haveMain ? "main" : "wmain") + " and " + 7240b57cec5SDimitry Andric (haveWinMain ? "WinMain" : "wWinMain") + 7250b57cec5SDimitry Andric "; defaulting to /subsystem:console"); 7260b57cec5SDimitry Andric } 7270b57cec5SDimitry Andric return IMAGE_SUBSYSTEM_WINDOWS_CUI; 7280b57cec5SDimitry Andric } 7290b57cec5SDimitry Andric if (haveWinMain || haveWWinMain) 7300b57cec5SDimitry Andric return IMAGE_SUBSYSTEM_WINDOWS_GUI; 7310b57cec5SDimitry Andric return IMAGE_SUBSYSTEM_UNKNOWN; 7320b57cec5SDimitry Andric } 7330b57cec5SDimitry Andric 734*bdd1243dSDimitry Andric uint64_t LinkerDriver::getDefaultImageBase() { 735*bdd1243dSDimitry Andric if (ctx.config.is64()) 736*bdd1243dSDimitry Andric return ctx.config.dll ? 0x180000000 : 0x140000000; 737*bdd1243dSDimitry Andric return ctx.config.dll ? 0x10000000 : 0x400000; 7380b57cec5SDimitry Andric } 7390b57cec5SDimitry Andric 740fe6060f1SDimitry Andric static std::string rewritePath(StringRef s) { 741fe6060f1SDimitry Andric if (fs::exists(s)) 742fe6060f1SDimitry Andric return relativeToRoot(s); 743fe6060f1SDimitry Andric return std::string(s); 744fe6060f1SDimitry Andric } 745fe6060f1SDimitry Andric 746fe6060f1SDimitry Andric // Reconstructs command line arguments so that so that you can re-run 747fe6060f1SDimitry Andric // the same command with the same inputs. This is for --reproduce. 7480b57cec5SDimitry Andric static std::string createResponseFile(const opt::InputArgList &args, 7490b57cec5SDimitry Andric ArrayRef<StringRef> filePaths, 7500b57cec5SDimitry Andric ArrayRef<StringRef> searchPaths) { 7510b57cec5SDimitry Andric SmallString<0> data; 7520b57cec5SDimitry Andric raw_svector_ostream os(data); 7530b57cec5SDimitry Andric 7540b57cec5SDimitry Andric for (auto *arg : args) { 7550b57cec5SDimitry Andric switch (arg->getOption().getID()) { 7560b57cec5SDimitry Andric case OPT_linkrepro: 75785868e8aSDimitry Andric case OPT_reproduce: 7580b57cec5SDimitry Andric case OPT_INPUT: 7590b57cec5SDimitry Andric case OPT_defaultlib: 7600b57cec5SDimitry Andric case OPT_libpath: 76181ad6265SDimitry Andric case OPT_winsysroot: 7620b57cec5SDimitry Andric break; 763fe6060f1SDimitry Andric case OPT_call_graph_ordering_file: 764fe6060f1SDimitry Andric case OPT_deffile: 765349cc55cSDimitry Andric case OPT_manifestinput: 766fe6060f1SDimitry Andric case OPT_natvis: 767fe6060f1SDimitry Andric os << arg->getSpelling() << quote(rewritePath(arg->getValue())) << '\n'; 768fe6060f1SDimitry Andric break; 769fe6060f1SDimitry Andric case OPT_order: { 770fe6060f1SDimitry Andric StringRef orderFile = arg->getValue(); 771fe6060f1SDimitry Andric orderFile.consume_front("@"); 772fe6060f1SDimitry Andric os << arg->getSpelling() << '@' << quote(rewritePath(orderFile)) << '\n'; 773fe6060f1SDimitry Andric break; 774fe6060f1SDimitry Andric } 775fe6060f1SDimitry Andric case OPT_pdbstream: { 776fe6060f1SDimitry Andric const std::pair<StringRef, StringRef> nameFile = 777fe6060f1SDimitry Andric StringRef(arg->getValue()).split("="); 778fe6060f1SDimitry Andric os << arg->getSpelling() << nameFile.first << '=' 779fe6060f1SDimitry Andric << quote(rewritePath(nameFile.second)) << '\n'; 780fe6060f1SDimitry Andric break; 781fe6060f1SDimitry Andric } 7820b57cec5SDimitry Andric case OPT_implib: 783349cc55cSDimitry Andric case OPT_manifestfile: 7840b57cec5SDimitry Andric case OPT_pdb: 7855ffd83dbSDimitry Andric case OPT_pdbstripped: 7860b57cec5SDimitry Andric case OPT_out: 7870b57cec5SDimitry Andric os << arg->getSpelling() << sys::path::filename(arg->getValue()) << "\n"; 7880b57cec5SDimitry Andric break; 7890b57cec5SDimitry Andric default: 7900b57cec5SDimitry Andric os << toString(*arg) << "\n"; 7910b57cec5SDimitry Andric } 7920b57cec5SDimitry Andric } 7930b57cec5SDimitry Andric 7940b57cec5SDimitry Andric for (StringRef path : searchPaths) { 7950b57cec5SDimitry Andric std::string relPath = relativeToRoot(path); 7960b57cec5SDimitry Andric os << "/libpath:" << quote(relPath) << "\n"; 7970b57cec5SDimitry Andric } 7980b57cec5SDimitry Andric 7990b57cec5SDimitry Andric for (StringRef path : filePaths) 8000b57cec5SDimitry Andric os << quote(relativeToRoot(path)) << "\n"; 8010b57cec5SDimitry Andric 8025ffd83dbSDimitry Andric return std::string(data.str()); 8030b57cec5SDimitry Andric } 8040b57cec5SDimitry Andric 805fe6060f1SDimitry Andric enum class DebugKind { 806fe6060f1SDimitry Andric Unknown, 807fe6060f1SDimitry Andric None, 808fe6060f1SDimitry Andric Full, 809fe6060f1SDimitry Andric FastLink, 810fe6060f1SDimitry Andric GHash, 811fe6060f1SDimitry Andric NoGHash, 812fe6060f1SDimitry Andric Dwarf, 813fe6060f1SDimitry Andric Symtab 814fe6060f1SDimitry Andric }; 8150b57cec5SDimitry Andric 8160b57cec5SDimitry Andric static DebugKind parseDebugKind(const opt::InputArgList &args) { 8170b57cec5SDimitry Andric auto *a = args.getLastArg(OPT_debug, OPT_debug_opt); 8180b57cec5SDimitry Andric if (!a) 8190b57cec5SDimitry Andric return DebugKind::None; 8200b57cec5SDimitry Andric if (a->getNumValues() == 0) 8210b57cec5SDimitry Andric return DebugKind::Full; 8220b57cec5SDimitry Andric 8230b57cec5SDimitry Andric DebugKind debug = StringSwitch<DebugKind>(a->getValue()) 8240b57cec5SDimitry Andric .CaseLower("none", DebugKind::None) 8250b57cec5SDimitry Andric .CaseLower("full", DebugKind::Full) 8260b57cec5SDimitry Andric .CaseLower("fastlink", DebugKind::FastLink) 8270b57cec5SDimitry Andric // LLD extensions 8280b57cec5SDimitry Andric .CaseLower("ghash", DebugKind::GHash) 829fe6060f1SDimitry Andric .CaseLower("noghash", DebugKind::NoGHash) 8300b57cec5SDimitry Andric .CaseLower("dwarf", DebugKind::Dwarf) 8310b57cec5SDimitry Andric .CaseLower("symtab", DebugKind::Symtab) 8320b57cec5SDimitry Andric .Default(DebugKind::Unknown); 8330b57cec5SDimitry Andric 8340b57cec5SDimitry Andric if (debug == DebugKind::FastLink) { 8350b57cec5SDimitry Andric warn("/debug:fastlink unsupported; using /debug:full"); 8360b57cec5SDimitry Andric return DebugKind::Full; 8370b57cec5SDimitry Andric } 8380b57cec5SDimitry Andric if (debug == DebugKind::Unknown) { 8390b57cec5SDimitry Andric error("/debug: unknown option: " + Twine(a->getValue())); 8400b57cec5SDimitry Andric return DebugKind::None; 8410b57cec5SDimitry Andric } 8420b57cec5SDimitry Andric return debug; 8430b57cec5SDimitry Andric } 8440b57cec5SDimitry Andric 8450b57cec5SDimitry Andric static unsigned parseDebugTypes(const opt::InputArgList &args) { 8460b57cec5SDimitry Andric unsigned debugTypes = static_cast<unsigned>(DebugType::None); 8470b57cec5SDimitry Andric 8480b57cec5SDimitry Andric if (auto *a = args.getLastArg(OPT_debugtype)) { 8490b57cec5SDimitry Andric SmallVector<StringRef, 3> types; 8500b57cec5SDimitry Andric StringRef(a->getValue()) 8510b57cec5SDimitry Andric .split(types, ',', /*MaxSplit=*/-1, /*KeepEmpty=*/false); 8520b57cec5SDimitry Andric 8530b57cec5SDimitry Andric for (StringRef type : types) { 8540b57cec5SDimitry Andric unsigned v = StringSwitch<unsigned>(type.lower()) 8550b57cec5SDimitry Andric .Case("cv", static_cast<unsigned>(DebugType::CV)) 8560b57cec5SDimitry Andric .Case("pdata", static_cast<unsigned>(DebugType::PData)) 8570b57cec5SDimitry Andric .Case("fixup", static_cast<unsigned>(DebugType::Fixup)) 8580b57cec5SDimitry Andric .Default(0); 8590b57cec5SDimitry Andric if (v == 0) { 8600b57cec5SDimitry Andric warn("/debugtype: unknown option '" + type + "'"); 8610b57cec5SDimitry Andric continue; 8620b57cec5SDimitry Andric } 8630b57cec5SDimitry Andric debugTypes |= v; 8640b57cec5SDimitry Andric } 8650b57cec5SDimitry Andric return debugTypes; 8660b57cec5SDimitry Andric } 8670b57cec5SDimitry Andric 8680b57cec5SDimitry Andric // Default debug types 8690b57cec5SDimitry Andric debugTypes = static_cast<unsigned>(DebugType::CV); 8700b57cec5SDimitry Andric if (args.hasArg(OPT_driver)) 8710b57cec5SDimitry Andric debugTypes |= static_cast<unsigned>(DebugType::PData); 8720b57cec5SDimitry Andric if (args.hasArg(OPT_profile)) 8730b57cec5SDimitry Andric debugTypes |= static_cast<unsigned>(DebugType::Fixup); 8740b57cec5SDimitry Andric 8750b57cec5SDimitry Andric return debugTypes; 8760b57cec5SDimitry Andric } 8770b57cec5SDimitry Andric 878*bdd1243dSDimitry Andric std::string LinkerDriver::getMapFile(const opt::InputArgList &args, 879*bdd1243dSDimitry Andric opt::OptSpecifier os, 880*bdd1243dSDimitry Andric opt::OptSpecifier osFile) { 8815ffd83dbSDimitry Andric auto *arg = args.getLastArg(os, osFile); 8820b57cec5SDimitry Andric if (!arg) 8830b57cec5SDimitry Andric return ""; 8845ffd83dbSDimitry Andric if (arg->getOption().getID() == osFile.getID()) 8850b57cec5SDimitry Andric return arg->getValue(); 8860b57cec5SDimitry Andric 8875ffd83dbSDimitry Andric assert(arg->getOption().getID() == os.getID()); 888*bdd1243dSDimitry Andric StringRef outFile = ctx.config.outputFile; 8890b57cec5SDimitry Andric return (outFile.substr(0, outFile.rfind('.')) + ".map").str(); 8900b57cec5SDimitry Andric } 8910b57cec5SDimitry Andric 892*bdd1243dSDimitry Andric std::string LinkerDriver::getImplibPath() { 893*bdd1243dSDimitry Andric if (!ctx.config.implib.empty()) 894*bdd1243dSDimitry Andric return std::string(ctx.config.implib); 895*bdd1243dSDimitry Andric SmallString<128> out = StringRef(ctx.config.outputFile); 8960b57cec5SDimitry Andric sys::path::replace_extension(out, ".lib"); 8975ffd83dbSDimitry Andric return std::string(out.str()); 8980b57cec5SDimitry Andric } 8990b57cec5SDimitry Andric 90085868e8aSDimitry Andric // The import name is calculated as follows: 9010b57cec5SDimitry Andric // 9020b57cec5SDimitry Andric // | LIBRARY w/ ext | LIBRARY w/o ext | no LIBRARY 9030b57cec5SDimitry Andric // -----+----------------+---------------------+------------------ 9040b57cec5SDimitry Andric // LINK | {value} | {value}.{.dll/.exe} | {output name} 9050b57cec5SDimitry Andric // LIB | {value} | {value}.dll | {output name}.dll 9060b57cec5SDimitry Andric // 907*bdd1243dSDimitry Andric std::string LinkerDriver::getImportName(bool asLib) { 9080b57cec5SDimitry Andric SmallString<128> out; 9090b57cec5SDimitry Andric 910*bdd1243dSDimitry Andric if (ctx.config.importName.empty()) { 911*bdd1243dSDimitry Andric out.assign(sys::path::filename(ctx.config.outputFile)); 9120b57cec5SDimitry Andric if (asLib) 9130b57cec5SDimitry Andric sys::path::replace_extension(out, ".dll"); 9140b57cec5SDimitry Andric } else { 915*bdd1243dSDimitry Andric out.assign(ctx.config.importName); 9160b57cec5SDimitry Andric if (!sys::path::has_extension(out)) 9170b57cec5SDimitry Andric sys::path::replace_extension(out, 918*bdd1243dSDimitry Andric (ctx.config.dll || asLib) ? ".dll" : ".exe"); 9190b57cec5SDimitry Andric } 9200b57cec5SDimitry Andric 9215ffd83dbSDimitry Andric return std::string(out.str()); 9220b57cec5SDimitry Andric } 9230b57cec5SDimitry Andric 924*bdd1243dSDimitry Andric void LinkerDriver::createImportLibrary(bool asLib) { 9250b57cec5SDimitry Andric std::vector<COFFShortExport> exports; 926*bdd1243dSDimitry Andric for (Export &e1 : ctx.config.exports) { 9270b57cec5SDimitry Andric COFFShortExport e2; 9285ffd83dbSDimitry Andric e2.Name = std::string(e1.name); 9295ffd83dbSDimitry Andric e2.SymbolName = std::string(e1.symbolName); 9305ffd83dbSDimitry Andric e2.ExtName = std::string(e1.extName); 93104eeddc0SDimitry Andric e2.AliasTarget = std::string(e1.aliasTarget); 9320b57cec5SDimitry Andric e2.Ordinal = e1.ordinal; 9330b57cec5SDimitry Andric e2.Noname = e1.noname; 9340b57cec5SDimitry Andric e2.Data = e1.data; 9350b57cec5SDimitry Andric e2.Private = e1.isPrivate; 9360b57cec5SDimitry Andric e2.Constant = e1.constant; 9370b57cec5SDimitry Andric exports.push_back(e2); 9380b57cec5SDimitry Andric } 9390b57cec5SDimitry Andric 9400b57cec5SDimitry Andric std::string libName = getImportName(asLib); 9410b57cec5SDimitry Andric std::string path = getImplibPath(); 9420b57cec5SDimitry Andric 943*bdd1243dSDimitry Andric if (!ctx.config.incremental) { 944*bdd1243dSDimitry Andric checkError(writeImportLibrary(libName, path, exports, ctx.config.machine, 945*bdd1243dSDimitry Andric ctx.config.mingw)); 9460b57cec5SDimitry Andric return; 9470b57cec5SDimitry Andric } 9480b57cec5SDimitry Andric 9490b57cec5SDimitry Andric // If the import library already exists, replace it only if the contents 9500b57cec5SDimitry Andric // have changed. 9510b57cec5SDimitry Andric ErrorOr<std::unique_ptr<MemoryBuffer>> oldBuf = MemoryBuffer::getFile( 952fe6060f1SDimitry Andric path, /*IsText=*/false, /*RequiresNullTerminator=*/false); 9530b57cec5SDimitry Andric if (!oldBuf) { 954*bdd1243dSDimitry Andric checkError(writeImportLibrary(libName, path, exports, ctx.config.machine, 955*bdd1243dSDimitry Andric ctx.config.mingw)); 9560b57cec5SDimitry Andric return; 9570b57cec5SDimitry Andric } 9580b57cec5SDimitry Andric 9590b57cec5SDimitry Andric SmallString<128> tmpName; 9600b57cec5SDimitry Andric if (std::error_code ec = 9610b57cec5SDimitry Andric sys::fs::createUniqueFile(path + ".tmp-%%%%%%%%.lib", tmpName)) 9620b57cec5SDimitry Andric fatal("cannot create temporary file for import library " + path + ": " + 9630b57cec5SDimitry Andric ec.message()); 9640b57cec5SDimitry Andric 965*bdd1243dSDimitry Andric if (Error e = writeImportLibrary(libName, tmpName, exports, 966*bdd1243dSDimitry Andric ctx.config.machine, ctx.config.mingw)) { 967349cc55cSDimitry Andric checkError(std::move(e)); 9680b57cec5SDimitry Andric return; 9690b57cec5SDimitry Andric } 9700b57cec5SDimitry Andric 9710b57cec5SDimitry Andric std::unique_ptr<MemoryBuffer> newBuf = check(MemoryBuffer::getFile( 972fe6060f1SDimitry Andric tmpName, /*IsText=*/false, /*RequiresNullTerminator=*/false)); 9730b57cec5SDimitry Andric if ((*oldBuf)->getBuffer() != newBuf->getBuffer()) { 9740b57cec5SDimitry Andric oldBuf->reset(); 975349cc55cSDimitry Andric checkError(errorCodeToError(sys::fs::rename(tmpName, path))); 9760b57cec5SDimitry Andric } else { 9770b57cec5SDimitry Andric sys::fs::remove(tmpName); 9780b57cec5SDimitry Andric } 9790b57cec5SDimitry Andric } 9800b57cec5SDimitry Andric 981*bdd1243dSDimitry Andric void LinkerDriver::parseModuleDefs(StringRef path) { 982fe6060f1SDimitry Andric std::unique_ptr<MemoryBuffer> mb = 983fe6060f1SDimitry Andric CHECK(MemoryBuffer::getFile(path, /*IsText=*/false, 984fe6060f1SDimitry Andric /*RequiresNullTerminator=*/false, 985fe6060f1SDimitry Andric /*IsVolatile=*/true), 986fe6060f1SDimitry Andric "could not open " + path); 9870b57cec5SDimitry Andric COFFModuleDefinition m = check(parseCOFFModuleDefinition( 988*bdd1243dSDimitry Andric mb->getMemBufferRef(), ctx.config.machine, ctx.config.mingw)); 9890b57cec5SDimitry Andric 990fe6060f1SDimitry Andric // Include in /reproduce: output if applicable. 991*bdd1243dSDimitry Andric ctx.driver.takeBuffer(std::move(mb)); 992fe6060f1SDimitry Andric 993*bdd1243dSDimitry Andric if (ctx.config.outputFile.empty()) 994*bdd1243dSDimitry Andric ctx.config.outputFile = std::string(saver().save(m.OutputFile)); 995*bdd1243dSDimitry Andric ctx.config.importName = std::string(saver().save(m.ImportName)); 9960b57cec5SDimitry Andric if (m.ImageBase) 997*bdd1243dSDimitry Andric ctx.config.imageBase = m.ImageBase; 9980b57cec5SDimitry Andric if (m.StackReserve) 999*bdd1243dSDimitry Andric ctx.config.stackReserve = m.StackReserve; 10000b57cec5SDimitry Andric if (m.StackCommit) 1001*bdd1243dSDimitry Andric ctx.config.stackCommit = m.StackCommit; 10020b57cec5SDimitry Andric if (m.HeapReserve) 1003*bdd1243dSDimitry Andric ctx.config.heapReserve = m.HeapReserve; 10040b57cec5SDimitry Andric if (m.HeapCommit) 1005*bdd1243dSDimitry Andric ctx.config.heapCommit = m.HeapCommit; 10060b57cec5SDimitry Andric if (m.MajorImageVersion) 1007*bdd1243dSDimitry Andric ctx.config.majorImageVersion = m.MajorImageVersion; 10080b57cec5SDimitry Andric if (m.MinorImageVersion) 1009*bdd1243dSDimitry Andric ctx.config.minorImageVersion = m.MinorImageVersion; 10100b57cec5SDimitry Andric if (m.MajorOSVersion) 1011*bdd1243dSDimitry Andric ctx.config.majorOSVersion = m.MajorOSVersion; 10120b57cec5SDimitry Andric if (m.MinorOSVersion) 1013*bdd1243dSDimitry Andric ctx.config.minorOSVersion = m.MinorOSVersion; 10140b57cec5SDimitry Andric 10150b57cec5SDimitry Andric for (COFFShortExport e1 : m.Exports) { 10160b57cec5SDimitry Andric Export e2; 10170b57cec5SDimitry Andric // In simple cases, only Name is set. Renamed exports are parsed 10180b57cec5SDimitry Andric // and set as "ExtName = Name". If Name has the form "OtherDll.Func", 10190b57cec5SDimitry Andric // it shouldn't be a normal exported function but a forward to another 10200b57cec5SDimitry Andric // DLL instead. This is supported by both MS and GNU linkers. 10215ffd83dbSDimitry Andric if (!e1.ExtName.empty() && e1.ExtName != e1.Name && 10225ffd83dbSDimitry Andric StringRef(e1.Name).contains('.')) { 102304eeddc0SDimitry Andric e2.name = saver().save(e1.ExtName); 102404eeddc0SDimitry Andric e2.forwardTo = saver().save(e1.Name); 1025*bdd1243dSDimitry Andric ctx.config.exports.push_back(e2); 10260b57cec5SDimitry Andric continue; 10270b57cec5SDimitry Andric } 102804eeddc0SDimitry Andric e2.name = saver().save(e1.Name); 102904eeddc0SDimitry Andric e2.extName = saver().save(e1.ExtName); 103004eeddc0SDimitry Andric e2.aliasTarget = saver().save(e1.AliasTarget); 10310b57cec5SDimitry Andric e2.ordinal = e1.Ordinal; 10320b57cec5SDimitry Andric e2.noname = e1.Noname; 10330b57cec5SDimitry Andric e2.data = e1.Data; 10340b57cec5SDimitry Andric e2.isPrivate = e1.Private; 10350b57cec5SDimitry Andric e2.constant = e1.Constant; 1036*bdd1243dSDimitry Andric ctx.config.exports.push_back(e2); 10370b57cec5SDimitry Andric } 10380b57cec5SDimitry Andric } 10390b57cec5SDimitry Andric 10400b57cec5SDimitry Andric void LinkerDriver::enqueueTask(std::function<void()> task) { 10410b57cec5SDimitry Andric taskQueue.push_back(std::move(task)); 10420b57cec5SDimitry Andric } 10430b57cec5SDimitry Andric 10440b57cec5SDimitry Andric bool LinkerDriver::run() { 1045349cc55cSDimitry Andric ScopedTimer t(ctx.inputFileTimer); 10460b57cec5SDimitry Andric 10470b57cec5SDimitry Andric bool didWork = !taskQueue.empty(); 10480b57cec5SDimitry Andric while (!taskQueue.empty()) { 10490b57cec5SDimitry Andric taskQueue.front()(); 10500b57cec5SDimitry Andric taskQueue.pop_front(); 10510b57cec5SDimitry Andric } 10520b57cec5SDimitry Andric return didWork; 10530b57cec5SDimitry Andric } 10540b57cec5SDimitry Andric 10550b57cec5SDimitry Andric // Parse an /order file. If an option is given, the linker places 10560b57cec5SDimitry Andric // COMDAT sections in the same order as their names appear in the 10570b57cec5SDimitry Andric // given file. 1058*bdd1243dSDimitry Andric void LinkerDriver::parseOrderFile(StringRef arg) { 10590b57cec5SDimitry Andric // For some reason, the MSVC linker requires a filename to be 10600b57cec5SDimitry Andric // preceded by "@". 10610b57cec5SDimitry Andric if (!arg.startswith("@")) { 10620b57cec5SDimitry Andric error("malformed /order option: '@' missing"); 10630b57cec5SDimitry Andric return; 10640b57cec5SDimitry Andric } 10650b57cec5SDimitry Andric 10660b57cec5SDimitry Andric // Get a list of all comdat sections for error checking. 10670b57cec5SDimitry Andric DenseSet<StringRef> set; 1068349cc55cSDimitry Andric for (Chunk *c : ctx.symtab.getChunks()) 10690b57cec5SDimitry Andric if (auto *sec = dyn_cast<SectionChunk>(c)) 10700b57cec5SDimitry Andric if (sec->sym) 10710b57cec5SDimitry Andric set.insert(sec->sym->getName()); 10720b57cec5SDimitry Andric 10730b57cec5SDimitry Andric // Open a file. 10740b57cec5SDimitry Andric StringRef path = arg.substr(1); 1075fe6060f1SDimitry Andric std::unique_ptr<MemoryBuffer> mb = 1076fe6060f1SDimitry Andric CHECK(MemoryBuffer::getFile(path, /*IsText=*/false, 1077fe6060f1SDimitry Andric /*RequiresNullTerminator=*/false, 1078fe6060f1SDimitry Andric /*IsVolatile=*/true), 1079fe6060f1SDimitry Andric "could not open " + path); 10800b57cec5SDimitry Andric 10810b57cec5SDimitry Andric // Parse a file. An order file contains one symbol per line. 10820b57cec5SDimitry Andric // All symbols that were not present in a given order file are 10830b57cec5SDimitry Andric // considered to have the lowest priority 0 and are placed at 10840b57cec5SDimitry Andric // end of an output section. 10855ffd83dbSDimitry Andric for (StringRef arg : args::getLines(mb->getMemBufferRef())) { 10865ffd83dbSDimitry Andric std::string s(arg); 1087*bdd1243dSDimitry Andric if (ctx.config.machine == I386 && !isDecorated(s)) 10880b57cec5SDimitry Andric s = "_" + s; 10890b57cec5SDimitry Andric 10900b57cec5SDimitry Andric if (set.count(s) == 0) { 1091*bdd1243dSDimitry Andric if (ctx.config.warnMissingOrderSymbol) 10920b57cec5SDimitry Andric warn("/order:" + arg + ": missing symbol: " + s + " [LNK4037]"); 10930b57cec5SDimitry Andric } 10940b57cec5SDimitry Andric else 1095*bdd1243dSDimitry Andric ctx.config.order[s] = INT_MIN + ctx.config.order.size(); 10960b57cec5SDimitry Andric } 1097fe6060f1SDimitry Andric 1098fe6060f1SDimitry Andric // Include in /reproduce: output if applicable. 1099*bdd1243dSDimitry Andric ctx.driver.takeBuffer(std::move(mb)); 11000b57cec5SDimitry Andric } 11010b57cec5SDimitry Andric 1102*bdd1243dSDimitry Andric void LinkerDriver::parseCallGraphFile(StringRef path) { 1103fe6060f1SDimitry Andric std::unique_ptr<MemoryBuffer> mb = 1104fe6060f1SDimitry Andric CHECK(MemoryBuffer::getFile(path, /*IsText=*/false, 1105fe6060f1SDimitry Andric /*RequiresNullTerminator=*/false, 1106fe6060f1SDimitry Andric /*IsVolatile=*/true), 1107fe6060f1SDimitry Andric "could not open " + path); 1108e8d8bef9SDimitry Andric 1109e8d8bef9SDimitry Andric // Build a map from symbol name to section. 1110e8d8bef9SDimitry Andric DenseMap<StringRef, Symbol *> map; 1111349cc55cSDimitry Andric for (ObjFile *file : ctx.objFileInstances) 1112e8d8bef9SDimitry Andric for (Symbol *sym : file->getSymbols()) 1113e8d8bef9SDimitry Andric if (sym) 1114e8d8bef9SDimitry Andric map[sym->getName()] = sym; 1115e8d8bef9SDimitry Andric 1116e8d8bef9SDimitry Andric auto findSection = [&](StringRef name) -> SectionChunk * { 1117e8d8bef9SDimitry Andric Symbol *sym = map.lookup(name); 1118e8d8bef9SDimitry Andric if (!sym) { 1119*bdd1243dSDimitry Andric if (ctx.config.warnMissingOrderSymbol) 1120e8d8bef9SDimitry Andric warn(path + ": no such symbol: " + name); 1121e8d8bef9SDimitry Andric return nullptr; 1122e8d8bef9SDimitry Andric } 1123e8d8bef9SDimitry Andric 1124e8d8bef9SDimitry Andric if (DefinedCOFF *dr = dyn_cast_or_null<DefinedCOFF>(sym)) 1125e8d8bef9SDimitry Andric return dyn_cast_or_null<SectionChunk>(dr->getChunk()); 1126e8d8bef9SDimitry Andric return nullptr; 1127e8d8bef9SDimitry Andric }; 1128e8d8bef9SDimitry Andric 1129e8d8bef9SDimitry Andric for (StringRef line : args::getLines(*mb)) { 1130e8d8bef9SDimitry Andric SmallVector<StringRef, 3> fields; 1131e8d8bef9SDimitry Andric line.split(fields, ' '); 1132e8d8bef9SDimitry Andric uint64_t count; 1133e8d8bef9SDimitry Andric 1134e8d8bef9SDimitry Andric if (fields.size() != 3 || !to_integer(fields[2], count)) { 1135e8d8bef9SDimitry Andric error(path + ": parse error"); 1136e8d8bef9SDimitry Andric return; 1137e8d8bef9SDimitry Andric } 1138e8d8bef9SDimitry Andric 1139e8d8bef9SDimitry Andric if (SectionChunk *from = findSection(fields[0])) 1140e8d8bef9SDimitry Andric if (SectionChunk *to = findSection(fields[1])) 1141*bdd1243dSDimitry Andric ctx.config.callGraphProfile[{from, to}] += count; 1142e8d8bef9SDimitry Andric } 1143fe6060f1SDimitry Andric 1144fe6060f1SDimitry Andric // Include in /reproduce: output if applicable. 1145*bdd1243dSDimitry Andric ctx.driver.takeBuffer(std::move(mb)); 1146e8d8bef9SDimitry Andric } 1147e8d8bef9SDimitry Andric 1148349cc55cSDimitry Andric static void readCallGraphsFromObjectFiles(COFFLinkerContext &ctx) { 1149349cc55cSDimitry Andric for (ObjFile *obj : ctx.objFileInstances) { 1150e8d8bef9SDimitry Andric if (obj->callgraphSec) { 1151e8d8bef9SDimitry Andric ArrayRef<uint8_t> contents; 1152e8d8bef9SDimitry Andric cantFail( 1153e8d8bef9SDimitry Andric obj->getCOFFObj()->getSectionContents(obj->callgraphSec, contents)); 1154e8d8bef9SDimitry Andric BinaryStreamReader reader(contents, support::little); 1155e8d8bef9SDimitry Andric while (!reader.empty()) { 1156e8d8bef9SDimitry Andric uint32_t fromIndex, toIndex; 1157e8d8bef9SDimitry Andric uint64_t count; 1158e8d8bef9SDimitry Andric if (Error err = reader.readInteger(fromIndex)) 1159e8d8bef9SDimitry Andric fatal(toString(obj) + ": Expected 32-bit integer"); 1160e8d8bef9SDimitry Andric if (Error err = reader.readInteger(toIndex)) 1161e8d8bef9SDimitry Andric fatal(toString(obj) + ": Expected 32-bit integer"); 1162e8d8bef9SDimitry Andric if (Error err = reader.readInteger(count)) 1163e8d8bef9SDimitry Andric fatal(toString(obj) + ": Expected 64-bit integer"); 1164e8d8bef9SDimitry Andric auto *fromSym = dyn_cast_or_null<Defined>(obj->getSymbol(fromIndex)); 1165e8d8bef9SDimitry Andric auto *toSym = dyn_cast_or_null<Defined>(obj->getSymbol(toIndex)); 1166e8d8bef9SDimitry Andric if (!fromSym || !toSym) 1167e8d8bef9SDimitry Andric continue; 1168e8d8bef9SDimitry Andric auto *from = dyn_cast_or_null<SectionChunk>(fromSym->getChunk()); 1169e8d8bef9SDimitry Andric auto *to = dyn_cast_or_null<SectionChunk>(toSym->getChunk()); 1170e8d8bef9SDimitry Andric if (from && to) 1171*bdd1243dSDimitry Andric ctx.config.callGraphProfile[{from, to}] += count; 1172e8d8bef9SDimitry Andric } 1173e8d8bef9SDimitry Andric } 1174e8d8bef9SDimitry Andric } 1175e8d8bef9SDimitry Andric } 1176e8d8bef9SDimitry Andric 11770b57cec5SDimitry Andric static void markAddrsig(Symbol *s) { 11780b57cec5SDimitry Andric if (auto *d = dyn_cast_or_null<Defined>(s)) 11790b57cec5SDimitry Andric if (SectionChunk *c = dyn_cast_or_null<SectionChunk>(d->getChunk())) 11800b57cec5SDimitry Andric c->keepUnique = true; 11810b57cec5SDimitry Andric } 11820b57cec5SDimitry Andric 1183349cc55cSDimitry Andric static void findKeepUniqueSections(COFFLinkerContext &ctx) { 11840b57cec5SDimitry Andric // Exported symbols could be address-significant in other executables or DSOs, 11850b57cec5SDimitry Andric // so we conservatively mark them as address-significant. 1186*bdd1243dSDimitry Andric for (Export &r : ctx.config.exports) 11870b57cec5SDimitry Andric markAddrsig(r.sym); 11880b57cec5SDimitry Andric 11890b57cec5SDimitry Andric // Visit the address-significance table in each object file and mark each 11900b57cec5SDimitry Andric // referenced symbol as address-significant. 1191349cc55cSDimitry Andric for (ObjFile *obj : ctx.objFileInstances) { 11920b57cec5SDimitry Andric ArrayRef<Symbol *> syms = obj->getSymbols(); 11930b57cec5SDimitry Andric if (obj->addrsigSec) { 11940b57cec5SDimitry Andric ArrayRef<uint8_t> contents; 11950b57cec5SDimitry Andric cantFail( 11960b57cec5SDimitry Andric obj->getCOFFObj()->getSectionContents(obj->addrsigSec, contents)); 11970b57cec5SDimitry Andric const uint8_t *cur = contents.begin(); 11980b57cec5SDimitry Andric while (cur != contents.end()) { 11990b57cec5SDimitry Andric unsigned size; 12000b57cec5SDimitry Andric const char *err; 12010b57cec5SDimitry Andric uint64_t symIndex = decodeULEB128(cur, &size, contents.end(), &err); 12020b57cec5SDimitry Andric if (err) 12030b57cec5SDimitry Andric fatal(toString(obj) + ": could not decode addrsig section: " + err); 12040b57cec5SDimitry Andric if (symIndex >= syms.size()) 12050b57cec5SDimitry Andric fatal(toString(obj) + ": invalid symbol index in addrsig section"); 12060b57cec5SDimitry Andric markAddrsig(syms[symIndex]); 12070b57cec5SDimitry Andric cur += size; 12080b57cec5SDimitry Andric } 12090b57cec5SDimitry Andric } else { 12100b57cec5SDimitry Andric // If an object file does not have an address-significance table, 12110b57cec5SDimitry Andric // conservatively mark all of its symbols as address-significant. 12120b57cec5SDimitry Andric for (Symbol *s : syms) 12130b57cec5SDimitry Andric markAddrsig(s); 12140b57cec5SDimitry Andric } 12150b57cec5SDimitry Andric } 12160b57cec5SDimitry Andric } 12170b57cec5SDimitry Andric 12180b57cec5SDimitry Andric // link.exe replaces each %foo% in altPath with the contents of environment 12190b57cec5SDimitry Andric // variable foo, and adds the two magic env vars _PDB (expands to the basename 12200b57cec5SDimitry Andric // of pdb's output path) and _EXT (expands to the extension of the output 12210b57cec5SDimitry Andric // binary). 12220b57cec5SDimitry Andric // lld only supports %_PDB% and %_EXT% and warns on references to all other env 12230b57cec5SDimitry Andric // vars. 1224*bdd1243dSDimitry Andric void LinkerDriver::parsePDBAltPath() { 12250b57cec5SDimitry Andric SmallString<128> buf; 12260b57cec5SDimitry Andric StringRef pdbBasename = 1227*bdd1243dSDimitry Andric sys::path::filename(ctx.config.pdbPath, sys::path::Style::windows); 12280b57cec5SDimitry Andric StringRef binaryExtension = 1229*bdd1243dSDimitry Andric sys::path::extension(ctx.config.outputFile, sys::path::Style::windows); 12300b57cec5SDimitry Andric if (!binaryExtension.empty()) 12310b57cec5SDimitry Andric binaryExtension = binaryExtension.substr(1); // %_EXT% does not include '.'. 12320b57cec5SDimitry Andric 12330b57cec5SDimitry Andric // Invariant: 12340b57cec5SDimitry Andric // +--------- cursor ('a...' might be the empty string). 12350b57cec5SDimitry Andric // | +----- firstMark 12360b57cec5SDimitry Andric // | | +- secondMark 12370b57cec5SDimitry Andric // v v v 12380b57cec5SDimitry Andric // a...%...%... 12390b57cec5SDimitry Andric size_t cursor = 0; 1240*bdd1243dSDimitry Andric while (cursor < ctx.config.pdbAltPath.size()) { 12410b57cec5SDimitry Andric size_t firstMark, secondMark; 1242*bdd1243dSDimitry Andric if ((firstMark = ctx.config.pdbAltPath.find('%', cursor)) == 1243*bdd1243dSDimitry Andric StringRef::npos || 1244*bdd1243dSDimitry Andric (secondMark = ctx.config.pdbAltPath.find('%', firstMark + 1)) == 1245*bdd1243dSDimitry Andric StringRef::npos) { 12460b57cec5SDimitry Andric // Didn't find another full fragment, treat rest of string as literal. 1247*bdd1243dSDimitry Andric buf.append(ctx.config.pdbAltPath.substr(cursor)); 12480b57cec5SDimitry Andric break; 12490b57cec5SDimitry Andric } 12500b57cec5SDimitry Andric 12510b57cec5SDimitry Andric // Found a full fragment. Append text in front of first %, and interpret 12520b57cec5SDimitry Andric // text between first and second % as variable name. 1253*bdd1243dSDimitry Andric buf.append(ctx.config.pdbAltPath.substr(cursor, firstMark - cursor)); 1254*bdd1243dSDimitry Andric StringRef var = 1255*bdd1243dSDimitry Andric ctx.config.pdbAltPath.substr(firstMark, secondMark - firstMark + 1); 1256fe6060f1SDimitry Andric if (var.equals_insensitive("%_pdb%")) 12570b57cec5SDimitry Andric buf.append(pdbBasename); 1258fe6060f1SDimitry Andric else if (var.equals_insensitive("%_ext%")) 12590b57cec5SDimitry Andric buf.append(binaryExtension); 12600b57cec5SDimitry Andric else { 12610b57cec5SDimitry Andric warn("only %_PDB% and %_EXT% supported in /pdbaltpath:, keeping " + 12620b57cec5SDimitry Andric var + " as literal"); 12630b57cec5SDimitry Andric buf.append(var); 12640b57cec5SDimitry Andric } 12650b57cec5SDimitry Andric 12660b57cec5SDimitry Andric cursor = secondMark + 1; 12670b57cec5SDimitry Andric } 12680b57cec5SDimitry Andric 1269*bdd1243dSDimitry Andric ctx.config.pdbAltPath = buf; 12700b57cec5SDimitry Andric } 12710b57cec5SDimitry Andric 127285868e8aSDimitry Andric /// Convert resource files and potentially merge input resource object 127385868e8aSDimitry Andric /// trees into one resource tree. 12740b57cec5SDimitry Andric /// Call after ObjFile::Instances is complete. 127585868e8aSDimitry Andric void LinkerDriver::convertResources() { 127685868e8aSDimitry Andric std::vector<ObjFile *> resourceObjFiles; 127785868e8aSDimitry Andric 1278349cc55cSDimitry Andric for (ObjFile *f : ctx.objFileInstances) { 127985868e8aSDimitry Andric if (f->isResourceObjFile()) 128085868e8aSDimitry Andric resourceObjFiles.push_back(f); 12810b57cec5SDimitry Andric } 12820b57cec5SDimitry Andric 1283*bdd1243dSDimitry Andric if (!ctx.config.mingw && 128485868e8aSDimitry Andric (resourceObjFiles.size() > 1 || 128585868e8aSDimitry Andric (resourceObjFiles.size() == 1 && !resources.empty()))) { 128685868e8aSDimitry Andric error((!resources.empty() ? "internal .obj file created from .res files" 128785868e8aSDimitry Andric : toString(resourceObjFiles[1])) + 12880b57cec5SDimitry Andric ": more than one resource obj file not allowed, already got " + 128985868e8aSDimitry Andric toString(resourceObjFiles.front())); 129085868e8aSDimitry Andric return; 12910b57cec5SDimitry Andric } 129285868e8aSDimitry Andric 129385868e8aSDimitry Andric if (resources.empty() && resourceObjFiles.size() <= 1) { 129485868e8aSDimitry Andric // No resources to convert, and max one resource object file in 129585868e8aSDimitry Andric // the input. Keep that preconverted resource section as is. 129685868e8aSDimitry Andric for (ObjFile *f : resourceObjFiles) 129785868e8aSDimitry Andric f->includeResourceChunks(); 129885868e8aSDimitry Andric return; 129985868e8aSDimitry Andric } 1300349cc55cSDimitry Andric ObjFile *f = 1301349cc55cSDimitry Andric make<ObjFile>(ctx, convertResToCOFF(resources, resourceObjFiles)); 1302349cc55cSDimitry Andric ctx.symtab.addFile(f); 130385868e8aSDimitry Andric f->includeResourceChunks(); 13040b57cec5SDimitry Andric } 13050b57cec5SDimitry Andric 13060b57cec5SDimitry Andric // In MinGW, if no symbols are chosen to be exported, then all symbols are 13070b57cec5SDimitry Andric // automatically exported by default. This behavior can be forced by the 13080b57cec5SDimitry Andric // -export-all-symbols option, so that it happens even when exports are 13090b57cec5SDimitry Andric // explicitly specified. The automatic behavior can be disabled using the 13100b57cec5SDimitry Andric // -exclude-all-symbols option, so that lld-link behaves like link.exe rather 13110b57cec5SDimitry Andric // than MinGW in the case that nothing is explicitly exported. 13120b57cec5SDimitry Andric void LinkerDriver::maybeExportMinGWSymbols(const opt::InputArgList &args) { 1313fe6060f1SDimitry Andric if (!args.hasArg(OPT_export_all_symbols)) { 1314*bdd1243dSDimitry Andric if (!ctx.config.dll) 13150b57cec5SDimitry Andric return; 13160b57cec5SDimitry Andric 1317*bdd1243dSDimitry Andric if (!ctx.config.exports.empty()) 13180b57cec5SDimitry Andric return; 13190b57cec5SDimitry Andric if (args.hasArg(OPT_exclude_all_symbols)) 13200b57cec5SDimitry Andric return; 13210b57cec5SDimitry Andric } 13220b57cec5SDimitry Andric 1323*bdd1243dSDimitry Andric AutoExporter exporter(ctx, excludedSymbols); 13240b57cec5SDimitry Andric 13250b57cec5SDimitry Andric for (auto *arg : args.filtered(OPT_wholearchive_file)) 1326*bdd1243dSDimitry Andric if (std::optional<StringRef> path = doFindFile(arg->getValue())) 13270b57cec5SDimitry Andric exporter.addWholeArchive(*path); 13280b57cec5SDimitry Andric 132961cfbce3SDimitry Andric for (auto *arg : args.filtered(OPT_exclude_symbols)) { 133061cfbce3SDimitry Andric SmallVector<StringRef, 2> vec; 133161cfbce3SDimitry Andric StringRef(arg->getValue()).split(vec, ','); 133261cfbce3SDimitry Andric for (StringRef sym : vec) 133361cfbce3SDimitry Andric exporter.addExcludedSymbol(mangle(sym)); 133461cfbce3SDimitry Andric } 133561cfbce3SDimitry Andric 1336349cc55cSDimitry Andric ctx.symtab.forEachSymbol([&](Symbol *s) { 13370b57cec5SDimitry Andric auto *def = dyn_cast<Defined>(s); 1338*bdd1243dSDimitry Andric if (!exporter.shouldExport(def)) 13390b57cec5SDimitry Andric return; 13400b57cec5SDimitry Andric 1341fe6060f1SDimitry Andric if (!def->isGCRoot) { 1342fe6060f1SDimitry Andric def->isGCRoot = true; 1343*bdd1243dSDimitry Andric ctx.config.gcroot.push_back(def); 1344fe6060f1SDimitry Andric } 1345fe6060f1SDimitry Andric 13460b57cec5SDimitry Andric Export e; 13470b57cec5SDimitry Andric e.name = def->getName(); 13480b57cec5SDimitry Andric e.sym = def; 13490b57cec5SDimitry Andric if (Chunk *c = def->getChunk()) 13500b57cec5SDimitry Andric if (!(c->getOutputCharacteristics() & IMAGE_SCN_MEM_EXECUTE)) 13510b57cec5SDimitry Andric e.data = true; 1352fe6060f1SDimitry Andric s->isUsedInRegularObj = true; 1353*bdd1243dSDimitry Andric ctx.config.exports.push_back(e); 13540b57cec5SDimitry Andric }); 13550b57cec5SDimitry Andric } 13560b57cec5SDimitry Andric 135785868e8aSDimitry Andric // lld has a feature to create a tar file containing all input files as well as 135885868e8aSDimitry Andric // all command line options, so that other people can run lld again with exactly 135985868e8aSDimitry Andric // the same inputs. This feature is accessible via /linkrepro and /reproduce. 136085868e8aSDimitry Andric // 136185868e8aSDimitry Andric // /linkrepro and /reproduce are very similar, but /linkrepro takes a directory 136285868e8aSDimitry Andric // name while /reproduce takes a full path. We have /linkrepro for compatibility 136385868e8aSDimitry Andric // with Microsoft link.exe. 1364*bdd1243dSDimitry Andric std::optional<std::string> getReproduceFile(const opt::InputArgList &args) { 136585868e8aSDimitry Andric if (auto *arg = args.getLastArg(OPT_reproduce)) 136685868e8aSDimitry Andric return std::string(arg->getValue()); 136785868e8aSDimitry Andric 136885868e8aSDimitry Andric if (auto *arg = args.getLastArg(OPT_linkrepro)) { 136985868e8aSDimitry Andric SmallString<64> path = StringRef(arg->getValue()); 137085868e8aSDimitry Andric sys::path::append(path, "repro.tar"); 13715ffd83dbSDimitry Andric return std::string(path); 137285868e8aSDimitry Andric } 137385868e8aSDimitry Andric 1374e8d8bef9SDimitry Andric // This is intentionally not guarded by OPT_lldignoreenv since writing 1375e8d8bef9SDimitry Andric // a repro tar file doesn't affect the main output. 1376e8d8bef9SDimitry Andric if (auto *path = getenv("LLD_REPRODUCE")) 1377e8d8bef9SDimitry Andric return std::string(path); 1378e8d8bef9SDimitry Andric 1379*bdd1243dSDimitry Andric return std::nullopt; 138085868e8aSDimitry Andric } 13810b57cec5SDimitry Andric 1382753f127fSDimitry Andric static std::unique_ptr<llvm::vfs::FileSystem> 1383753f127fSDimitry Andric getVFS(const opt::InputArgList &args) { 1384753f127fSDimitry Andric using namespace llvm::vfs; 1385753f127fSDimitry Andric 1386753f127fSDimitry Andric const opt::Arg *arg = args.getLastArg(OPT_vfsoverlay); 1387753f127fSDimitry Andric if (!arg) 1388753f127fSDimitry Andric return nullptr; 1389753f127fSDimitry Andric 1390753f127fSDimitry Andric auto bufOrErr = llvm::MemoryBuffer::getFile(arg->getValue()); 1391753f127fSDimitry Andric if (!bufOrErr) { 1392753f127fSDimitry Andric checkError(errorCodeToError(bufOrErr.getError())); 1393753f127fSDimitry Andric return nullptr; 1394753f127fSDimitry Andric } 1395753f127fSDimitry Andric 1396753f127fSDimitry Andric if (auto ret = vfs::getVFSFromYAML(std::move(*bufOrErr), /*DiagHandler*/ nullptr, 1397753f127fSDimitry Andric arg->getValue())) 1398753f127fSDimitry Andric return ret; 1399753f127fSDimitry Andric 1400753f127fSDimitry Andric error("Invalid vfs overlay"); 1401753f127fSDimitry Andric return nullptr; 1402753f127fSDimitry Andric } 1403753f127fSDimitry Andric 1404e8d8bef9SDimitry Andric void LinkerDriver::linkerMain(ArrayRef<const char *> argsArr) { 1405349cc55cSDimitry Andric ScopedTimer rootTimer(ctx.rootTimer); 1406*bdd1243dSDimitry Andric Configuration *config = &ctx.config; 14075ffd83dbSDimitry Andric 14080b57cec5SDimitry Andric // Needed for LTO. 14090b57cec5SDimitry Andric InitializeAllTargetInfos(); 14100b57cec5SDimitry Andric InitializeAllTargets(); 14110b57cec5SDimitry Andric InitializeAllTargetMCs(); 14120b57cec5SDimitry Andric InitializeAllAsmParsers(); 14130b57cec5SDimitry Andric InitializeAllAsmPrinters(); 14140b57cec5SDimitry Andric 14150b57cec5SDimitry Andric // If the first command line argument is "/lib", link.exe acts like lib.exe. 14160b57cec5SDimitry Andric // We call our own implementation of lib.exe that understands bitcode files. 1417fe6060f1SDimitry Andric if (argsArr.size() > 1 && 1418fe6060f1SDimitry Andric (StringRef(argsArr[1]).equals_insensitive("/lib") || 1419fe6060f1SDimitry Andric StringRef(argsArr[1]).equals_insensitive("-lib"))) { 14200b57cec5SDimitry Andric if (llvm::libDriverMain(argsArr.slice(1)) != 0) 14210b57cec5SDimitry Andric fatal("lib failed"); 14220b57cec5SDimitry Andric return; 14230b57cec5SDimitry Andric } 14240b57cec5SDimitry Andric 14250b57cec5SDimitry Andric // Parse command line options. 1426*bdd1243dSDimitry Andric ArgParser parser(ctx); 142785868e8aSDimitry Andric opt::InputArgList args = parser.parse(argsArr); 14280b57cec5SDimitry Andric 14290b57cec5SDimitry Andric // Parse and evaluate -mllvm options. 14300b57cec5SDimitry Andric std::vector<const char *> v; 14310b57cec5SDimitry Andric v.push_back("lld-link (LLVM option parsing)"); 1432*bdd1243dSDimitry Andric for (const auto *arg : args.filtered(OPT_mllvm)) { 14330b57cec5SDimitry Andric v.push_back(arg->getValue()); 1434*bdd1243dSDimitry Andric config->mllvmOpts.emplace_back(arg->getValue()); 1435*bdd1243dSDimitry Andric } 1436e8d8bef9SDimitry Andric cl::ResetAllOptionOccurrences(); 14370b57cec5SDimitry Andric cl::ParseCommandLineOptions(v.size(), v.data()); 14380b57cec5SDimitry Andric 14390b57cec5SDimitry Andric // Handle /errorlimit early, because error() depends on it. 14400b57cec5SDimitry Andric if (auto *arg = args.getLastArg(OPT_errorlimit)) { 14410b57cec5SDimitry Andric int n = 20; 14420b57cec5SDimitry Andric StringRef s = arg->getValue(); 14430b57cec5SDimitry Andric if (s.getAsInteger(10, n)) 14440b57cec5SDimitry Andric error(arg->getSpelling() + " number expected, but got " + s); 14450b57cec5SDimitry Andric errorHandler().errorLimit = n; 14460b57cec5SDimitry Andric } 14470b57cec5SDimitry Andric 1448753f127fSDimitry Andric config->vfs = getVFS(args); 1449753f127fSDimitry Andric 14500b57cec5SDimitry Andric // Handle /help 14510b57cec5SDimitry Andric if (args.hasArg(OPT_help)) { 14520b57cec5SDimitry Andric printHelp(argsArr[0]); 14530b57cec5SDimitry Andric return; 14540b57cec5SDimitry Andric } 14550b57cec5SDimitry Andric 14565ffd83dbSDimitry Andric // /threads: takes a positive integer and provides the default value for 14575ffd83dbSDimitry Andric // /opt:lldltojobs=. 14585ffd83dbSDimitry Andric if (auto *arg = args.getLastArg(OPT_threads)) { 14595ffd83dbSDimitry Andric StringRef v(arg->getValue()); 14605ffd83dbSDimitry Andric unsigned threads = 0; 14615ffd83dbSDimitry Andric if (!llvm::to_integer(v, threads, 0) || threads == 0) 14625ffd83dbSDimitry Andric error(arg->getSpelling() + ": expected a positive integer, but got '" + 14635ffd83dbSDimitry Andric arg->getValue() + "'"); 14645ffd83dbSDimitry Andric parallel::strategy = hardware_concurrency(threads); 14655ffd83dbSDimitry Andric config->thinLTOJobs = v.str(); 14665ffd83dbSDimitry Andric } 14670b57cec5SDimitry Andric 14680b57cec5SDimitry Andric if (args.hasArg(OPT_show_timing)) 14690b57cec5SDimitry Andric config->showTiming = true; 14700b57cec5SDimitry Andric 14710b57cec5SDimitry Andric config->showSummary = args.hasArg(OPT_summary); 14720b57cec5SDimitry Andric 14730b57cec5SDimitry Andric // Handle --version, which is an lld extension. This option is a bit odd 14740b57cec5SDimitry Andric // because it doesn't start with "/", but we deliberately chose "--" to 14750b57cec5SDimitry Andric // avoid conflict with /version and for compatibility with clang-cl. 14760b57cec5SDimitry Andric if (args.hasArg(OPT_dash_dash_version)) { 1477e8d8bef9SDimitry Andric message(getLLDVersion()); 14780b57cec5SDimitry Andric return; 14790b57cec5SDimitry Andric } 14800b57cec5SDimitry Andric 14810b57cec5SDimitry Andric // Handle /lldmingw early, since it can potentially affect how other 14820b57cec5SDimitry Andric // options are handled. 14830b57cec5SDimitry Andric config->mingw = args.hasArg(OPT_lldmingw); 1484*bdd1243dSDimitry Andric if (config->mingw) 1485*bdd1243dSDimitry Andric ctx.e.errorLimitExceededMsg = "too many errors emitted, stopping now" 1486*bdd1243dSDimitry Andric " (use --error-limit=0 to see all errors)"; 14870b57cec5SDimitry Andric 148885868e8aSDimitry Andric // Handle /linkrepro and /reproduce. 1489*bdd1243dSDimitry Andric if (std::optional<std::string> path = getReproduceFile(args)) { 14900b57cec5SDimitry Andric Expected<std::unique_ptr<TarWriter>> errOrWriter = 149185868e8aSDimitry Andric TarWriter::create(*path, sys::path::stem(*path)); 14920b57cec5SDimitry Andric 14930b57cec5SDimitry Andric if (errOrWriter) { 14940b57cec5SDimitry Andric tar = std::move(*errOrWriter); 14950b57cec5SDimitry Andric } else { 149685868e8aSDimitry Andric error("/linkrepro: failed to open " + *path + ": " + 14970b57cec5SDimitry Andric toString(errOrWriter.takeError())); 14980b57cec5SDimitry Andric } 14990b57cec5SDimitry Andric } 15000b57cec5SDimitry Andric 1501480093f4SDimitry Andric if (!args.hasArg(OPT_INPUT, OPT_wholearchive_file)) { 15020b57cec5SDimitry Andric if (args.hasArg(OPT_deffile)) 15030b57cec5SDimitry Andric config->noEntry = true; 15040b57cec5SDimitry Andric else 15050b57cec5SDimitry Andric fatal("no input files"); 15060b57cec5SDimitry Andric } 15070b57cec5SDimitry Andric 15080b57cec5SDimitry Andric // Construct search path list. 15090b57cec5SDimitry Andric searchPaths.push_back(""); 15100b57cec5SDimitry Andric for (auto *arg : args.filtered(OPT_libpath)) 15110b57cec5SDimitry Andric searchPaths.push_back(arg->getValue()); 151281ad6265SDimitry Andric detectWinSysRoot(args); 151381ad6265SDimitry Andric if (!args.hasArg(OPT_lldignoreenv) && !args.hasArg(OPT_winsysroot)) 15140b57cec5SDimitry Andric addLibSearchPaths(); 15150b57cec5SDimitry Andric 15160b57cec5SDimitry Andric // Handle /ignore 15170b57cec5SDimitry Andric for (auto *arg : args.filtered(OPT_ignore)) { 15180b57cec5SDimitry Andric SmallVector<StringRef, 8> vec; 15190b57cec5SDimitry Andric StringRef(arg->getValue()).split(vec, ','); 15200b57cec5SDimitry Andric for (StringRef s : vec) { 15210b57cec5SDimitry Andric if (s == "4037") 15220b57cec5SDimitry Andric config->warnMissingOrderSymbol = false; 15230b57cec5SDimitry Andric else if (s == "4099") 15240b57cec5SDimitry Andric config->warnDebugInfoUnusable = false; 15250b57cec5SDimitry Andric else if (s == "4217") 15260b57cec5SDimitry Andric config->warnLocallyDefinedImported = false; 1527480093f4SDimitry Andric else if (s == "longsections") 1528480093f4SDimitry Andric config->warnLongSectionNames = false; 15290b57cec5SDimitry Andric // Other warning numbers are ignored. 15300b57cec5SDimitry Andric } 15310b57cec5SDimitry Andric } 15320b57cec5SDimitry Andric 15330b57cec5SDimitry Andric // Handle /out 15340b57cec5SDimitry Andric if (auto *arg = args.getLastArg(OPT_out)) 15350b57cec5SDimitry Andric config->outputFile = arg->getValue(); 15360b57cec5SDimitry Andric 15370b57cec5SDimitry Andric // Handle /verbose 15380b57cec5SDimitry Andric if (args.hasArg(OPT_verbose)) 15390b57cec5SDimitry Andric config->verbose = true; 15400b57cec5SDimitry Andric errorHandler().verbose = config->verbose; 15410b57cec5SDimitry Andric 15420b57cec5SDimitry Andric // Handle /force or /force:unresolved 15430b57cec5SDimitry Andric if (args.hasArg(OPT_force, OPT_force_unresolved)) 15440b57cec5SDimitry Andric config->forceUnresolved = true; 15450b57cec5SDimitry Andric 15460b57cec5SDimitry Andric // Handle /force or /force:multiple 15470b57cec5SDimitry Andric if (args.hasArg(OPT_force, OPT_force_multiple)) 15480b57cec5SDimitry Andric config->forceMultiple = true; 15490b57cec5SDimitry Andric 15500b57cec5SDimitry Andric // Handle /force or /force:multipleres 15510b57cec5SDimitry Andric if (args.hasArg(OPT_force, OPT_force_multipleres)) 15520b57cec5SDimitry Andric config->forceMultipleRes = true; 15530b57cec5SDimitry Andric 15540b57cec5SDimitry Andric // Handle /debug 15550b57cec5SDimitry Andric DebugKind debug = parseDebugKind(args); 15560b57cec5SDimitry Andric if (debug == DebugKind::Full || debug == DebugKind::Dwarf || 1557fe6060f1SDimitry Andric debug == DebugKind::GHash || debug == DebugKind::NoGHash) { 15580b57cec5SDimitry Andric config->debug = true; 15590b57cec5SDimitry Andric config->incremental = true; 15600b57cec5SDimitry Andric } 15610b57cec5SDimitry Andric 15620b57cec5SDimitry Andric // Handle /demangle 156381ad6265SDimitry Andric config->demangle = args.hasFlag(OPT_demangle, OPT_demangle_no, true); 15640b57cec5SDimitry Andric 15650b57cec5SDimitry Andric // Handle /debugtype 15660b57cec5SDimitry Andric config->debugTypes = parseDebugTypes(args); 15670b57cec5SDimitry Andric 1568480093f4SDimitry Andric // Handle /driver[:uponly|:wdm]. 1569480093f4SDimitry Andric config->driverUponly = args.hasArg(OPT_driver_uponly) || 1570480093f4SDimitry Andric args.hasArg(OPT_driver_uponly_wdm) || 1571480093f4SDimitry Andric args.hasArg(OPT_driver_wdm_uponly); 1572480093f4SDimitry Andric config->driverWdm = args.hasArg(OPT_driver_wdm) || 1573480093f4SDimitry Andric args.hasArg(OPT_driver_uponly_wdm) || 1574480093f4SDimitry Andric args.hasArg(OPT_driver_wdm_uponly); 1575480093f4SDimitry Andric config->driver = 1576480093f4SDimitry Andric config->driverUponly || config->driverWdm || args.hasArg(OPT_driver); 1577480093f4SDimitry Andric 15780b57cec5SDimitry Andric // Handle /pdb 15790b57cec5SDimitry Andric bool shouldCreatePDB = 1580fe6060f1SDimitry Andric (debug == DebugKind::Full || debug == DebugKind::GHash || 1581fe6060f1SDimitry Andric debug == DebugKind::NoGHash); 15820b57cec5SDimitry Andric if (shouldCreatePDB) { 15830b57cec5SDimitry Andric if (auto *arg = args.getLastArg(OPT_pdb)) 15840b57cec5SDimitry Andric config->pdbPath = arg->getValue(); 15850b57cec5SDimitry Andric if (auto *arg = args.getLastArg(OPT_pdbaltpath)) 15860b57cec5SDimitry Andric config->pdbAltPath = arg->getValue(); 1587349cc55cSDimitry Andric if (auto *arg = args.getLastArg(OPT_pdbpagesize)) 1588349cc55cSDimitry Andric parsePDBPageSize(arg->getValue()); 15890b57cec5SDimitry Andric if (args.hasArg(OPT_natvis)) 15900b57cec5SDimitry Andric config->natvisFiles = args.getAllArgValues(OPT_natvis); 15915ffd83dbSDimitry Andric if (args.hasArg(OPT_pdbstream)) { 15925ffd83dbSDimitry Andric for (const StringRef value : args.getAllArgValues(OPT_pdbstream)) { 15935ffd83dbSDimitry Andric const std::pair<StringRef, StringRef> nameFile = value.split("="); 15945ffd83dbSDimitry Andric const StringRef name = nameFile.first; 15955ffd83dbSDimitry Andric const std::string file = nameFile.second.str(); 15965ffd83dbSDimitry Andric config->namedStreams[name] = file; 15975ffd83dbSDimitry Andric } 15985ffd83dbSDimitry Andric } 15990b57cec5SDimitry Andric 16000b57cec5SDimitry Andric if (auto *arg = args.getLastArg(OPT_pdb_source_path)) 16010b57cec5SDimitry Andric config->pdbSourcePath = arg->getValue(); 16020b57cec5SDimitry Andric } 16030b57cec5SDimitry Andric 16045ffd83dbSDimitry Andric // Handle /pdbstripped 16055ffd83dbSDimitry Andric if (args.hasArg(OPT_pdbstripped)) 16065ffd83dbSDimitry Andric warn("ignoring /pdbstripped flag, it is not yet supported"); 16075ffd83dbSDimitry Andric 16080b57cec5SDimitry Andric // Handle /noentry 16090b57cec5SDimitry Andric if (args.hasArg(OPT_noentry)) { 16100b57cec5SDimitry Andric if (args.hasArg(OPT_dll)) 16110b57cec5SDimitry Andric config->noEntry = true; 16120b57cec5SDimitry Andric else 16130b57cec5SDimitry Andric error("/noentry must be specified with /dll"); 16140b57cec5SDimitry Andric } 16150b57cec5SDimitry Andric 16160b57cec5SDimitry Andric // Handle /dll 16170b57cec5SDimitry Andric if (args.hasArg(OPT_dll)) { 16180b57cec5SDimitry Andric config->dll = true; 16190b57cec5SDimitry Andric config->manifestID = 2; 16200b57cec5SDimitry Andric } 16210b57cec5SDimitry Andric 16220b57cec5SDimitry Andric // Handle /dynamicbase and /fixed. We can't use hasFlag for /dynamicbase 16230b57cec5SDimitry Andric // because we need to explicitly check whether that option or its inverse was 16240b57cec5SDimitry Andric // present in the argument list in order to handle /fixed. 16250b57cec5SDimitry Andric auto *dynamicBaseArg = args.getLastArg(OPT_dynamicbase, OPT_dynamicbase_no); 16260b57cec5SDimitry Andric if (dynamicBaseArg && 16270b57cec5SDimitry Andric dynamicBaseArg->getOption().getID() == OPT_dynamicbase_no) 16280b57cec5SDimitry Andric config->dynamicBase = false; 16290b57cec5SDimitry Andric 16300b57cec5SDimitry Andric // MSDN claims "/FIXED:NO is the default setting for a DLL, and /FIXED is the 16310b57cec5SDimitry Andric // default setting for any other project type.", but link.exe defaults to 16320b57cec5SDimitry Andric // /FIXED:NO for exe outputs as well. Match behavior, not docs. 16330b57cec5SDimitry Andric bool fixed = args.hasFlag(OPT_fixed, OPT_fixed_no, false); 16340b57cec5SDimitry Andric if (fixed) { 16350b57cec5SDimitry Andric if (dynamicBaseArg && 16360b57cec5SDimitry Andric dynamicBaseArg->getOption().getID() == OPT_dynamicbase) { 16370b57cec5SDimitry Andric error("/fixed must not be specified with /dynamicbase"); 16380b57cec5SDimitry Andric } else { 16390b57cec5SDimitry Andric config->relocatable = false; 16400b57cec5SDimitry Andric config->dynamicBase = false; 16410b57cec5SDimitry Andric } 16420b57cec5SDimitry Andric } 16430b57cec5SDimitry Andric 16440b57cec5SDimitry Andric // Handle /appcontainer 16450b57cec5SDimitry Andric config->appContainer = 16460b57cec5SDimitry Andric args.hasFlag(OPT_appcontainer, OPT_appcontainer_no, false); 16470b57cec5SDimitry Andric 16480b57cec5SDimitry Andric // Handle /machine 16490b57cec5SDimitry Andric if (auto *arg = args.getLastArg(OPT_machine)) { 16500b57cec5SDimitry Andric config->machine = getMachineType(arg->getValue()); 16510b57cec5SDimitry Andric if (config->machine == IMAGE_FILE_MACHINE_UNKNOWN) 16520b57cec5SDimitry Andric fatal(Twine("unknown /machine argument: ") + arg->getValue()); 165381ad6265SDimitry Andric addWinSysRootLibSearchPaths(); 16540b57cec5SDimitry Andric } 16550b57cec5SDimitry Andric 16560b57cec5SDimitry Andric // Handle /nodefaultlib:<filename> 16570b57cec5SDimitry Andric for (auto *arg : args.filtered(OPT_nodefaultlib)) 16580b57cec5SDimitry Andric config->noDefaultLibs.insert(doFindLib(arg->getValue()).lower()); 16590b57cec5SDimitry Andric 16600b57cec5SDimitry Andric // Handle /nodefaultlib 16610b57cec5SDimitry Andric if (args.hasArg(OPT_nodefaultlib_all)) 16620b57cec5SDimitry Andric config->noDefaultLibAll = true; 16630b57cec5SDimitry Andric 16640b57cec5SDimitry Andric // Handle /base 16650b57cec5SDimitry Andric if (auto *arg = args.getLastArg(OPT_base)) 16660b57cec5SDimitry Andric parseNumbers(arg->getValue(), &config->imageBase); 16670b57cec5SDimitry Andric 16680b57cec5SDimitry Andric // Handle /filealign 16690b57cec5SDimitry Andric if (auto *arg = args.getLastArg(OPT_filealign)) { 16700b57cec5SDimitry Andric parseNumbers(arg->getValue(), &config->fileAlign); 16710b57cec5SDimitry Andric if (!isPowerOf2_64(config->fileAlign)) 16720b57cec5SDimitry Andric error("/filealign: not a power of two: " + Twine(config->fileAlign)); 16730b57cec5SDimitry Andric } 16740b57cec5SDimitry Andric 16750b57cec5SDimitry Andric // Handle /stack 16760b57cec5SDimitry Andric if (auto *arg = args.getLastArg(OPT_stack)) 16770b57cec5SDimitry Andric parseNumbers(arg->getValue(), &config->stackReserve, &config->stackCommit); 16780b57cec5SDimitry Andric 16790b57cec5SDimitry Andric // Handle /guard:cf 16800b57cec5SDimitry Andric if (auto *arg = args.getLastArg(OPT_guard)) 16810b57cec5SDimitry Andric parseGuard(arg->getValue()); 16820b57cec5SDimitry Andric 16830b57cec5SDimitry Andric // Handle /heap 16840b57cec5SDimitry Andric if (auto *arg = args.getLastArg(OPT_heap)) 16850b57cec5SDimitry Andric parseNumbers(arg->getValue(), &config->heapReserve, &config->heapCommit); 16860b57cec5SDimitry Andric 16870b57cec5SDimitry Andric // Handle /version 16880b57cec5SDimitry Andric if (auto *arg = args.getLastArg(OPT_version)) 16890b57cec5SDimitry Andric parseVersion(arg->getValue(), &config->majorImageVersion, 16900b57cec5SDimitry Andric &config->minorImageVersion); 16910b57cec5SDimitry Andric 16920b57cec5SDimitry Andric // Handle /subsystem 16930b57cec5SDimitry Andric if (auto *arg = args.getLastArg(OPT_subsystem)) 1694e8d8bef9SDimitry Andric parseSubsystem(arg->getValue(), &config->subsystem, 1695e8d8bef9SDimitry Andric &config->majorSubsystemVersion, 1696e8d8bef9SDimitry Andric &config->minorSubsystemVersion); 1697e8d8bef9SDimitry Andric 1698e8d8bef9SDimitry Andric // Handle /osversion 1699e8d8bef9SDimitry Andric if (auto *arg = args.getLastArg(OPT_osversion)) { 1700e8d8bef9SDimitry Andric parseVersion(arg->getValue(), &config->majorOSVersion, 17010b57cec5SDimitry Andric &config->minorOSVersion); 1702e8d8bef9SDimitry Andric } else { 1703e8d8bef9SDimitry Andric config->majorOSVersion = config->majorSubsystemVersion; 1704e8d8bef9SDimitry Andric config->minorOSVersion = config->minorSubsystemVersion; 1705e8d8bef9SDimitry Andric } 17060b57cec5SDimitry Andric 17070b57cec5SDimitry Andric // Handle /timestamp 17080b57cec5SDimitry Andric if (llvm::opt::Arg *arg = args.getLastArg(OPT_timestamp, OPT_repro)) { 17090b57cec5SDimitry Andric if (arg->getOption().getID() == OPT_repro) { 17100b57cec5SDimitry Andric config->timestamp = 0; 17110b57cec5SDimitry Andric config->repro = true; 17120b57cec5SDimitry Andric } else { 17130b57cec5SDimitry Andric config->repro = false; 17140b57cec5SDimitry Andric StringRef value(arg->getValue()); 17150b57cec5SDimitry Andric if (value.getAsInteger(0, config->timestamp)) 17160b57cec5SDimitry Andric fatal(Twine("invalid timestamp: ") + value + 17170b57cec5SDimitry Andric ". Expected 32-bit integer"); 17180b57cec5SDimitry Andric } 17190b57cec5SDimitry Andric } else { 17200b57cec5SDimitry Andric config->repro = false; 17210b57cec5SDimitry Andric config->timestamp = time(nullptr); 17220b57cec5SDimitry Andric } 17230b57cec5SDimitry Andric 17240b57cec5SDimitry Andric // Handle /alternatename 17250b57cec5SDimitry Andric for (auto *arg : args.filtered(OPT_alternatename)) 17260b57cec5SDimitry Andric parseAlternateName(arg->getValue()); 17270b57cec5SDimitry Andric 17280b57cec5SDimitry Andric // Handle /include 17290b57cec5SDimitry Andric for (auto *arg : args.filtered(OPT_incl)) 17300b57cec5SDimitry Andric addUndefined(arg->getValue()); 17310b57cec5SDimitry Andric 17320b57cec5SDimitry Andric // Handle /implib 17330b57cec5SDimitry Andric if (auto *arg = args.getLastArg(OPT_implib)) 17340b57cec5SDimitry Andric config->implib = arg->getValue(); 17350b57cec5SDimitry Andric 173681ad6265SDimitry Andric config->noimplib = args.hasArg(OPT_noimplib); 173781ad6265SDimitry Andric 17380b57cec5SDimitry Andric // Handle /opt. 17390b57cec5SDimitry Andric bool doGC = debug == DebugKind::None || args.hasArg(OPT_profile); 1740*bdd1243dSDimitry Andric std::optional<ICFLevel> icfLevel; 1741fe6060f1SDimitry Andric if (args.hasArg(OPT_profile)) 1742fe6060f1SDimitry Andric icfLevel = ICFLevel::None; 17430b57cec5SDimitry Andric unsigned tailMerge = 1; 1744e8d8bef9SDimitry Andric bool ltoDebugPM = false; 17450b57cec5SDimitry Andric for (auto *arg : args.filtered(OPT_opt)) { 17460b57cec5SDimitry Andric std::string str = StringRef(arg->getValue()).lower(); 17470b57cec5SDimitry Andric SmallVector<StringRef, 1> vec; 17480b57cec5SDimitry Andric StringRef(str).split(vec, ','); 17490b57cec5SDimitry Andric for (StringRef s : vec) { 17500b57cec5SDimitry Andric if (s == "ref") { 17510b57cec5SDimitry Andric doGC = true; 17520b57cec5SDimitry Andric } else if (s == "noref") { 17530b57cec5SDimitry Andric doGC = false; 17540b57cec5SDimitry Andric } else if (s == "icf" || s.startswith("icf=")) { 1755fe6060f1SDimitry Andric icfLevel = ICFLevel::All; 1756fe6060f1SDimitry Andric } else if (s == "safeicf") { 1757fe6060f1SDimitry Andric icfLevel = ICFLevel::Safe; 17580b57cec5SDimitry Andric } else if (s == "noicf") { 1759fe6060f1SDimitry Andric icfLevel = ICFLevel::None; 17600b57cec5SDimitry Andric } else if (s == "lldtailmerge") { 17610b57cec5SDimitry Andric tailMerge = 2; 17620b57cec5SDimitry Andric } else if (s == "nolldtailmerge") { 17630b57cec5SDimitry Andric tailMerge = 0; 1764e8d8bef9SDimitry Andric } else if (s == "ltonewpassmanager") { 176581ad6265SDimitry Andric /* We always use the new PM. */ 1766e8d8bef9SDimitry Andric } else if (s == "ltodebugpassmanager") { 1767e8d8bef9SDimitry Andric ltoDebugPM = true; 1768e8d8bef9SDimitry Andric } else if (s == "noltodebugpassmanager") { 1769e8d8bef9SDimitry Andric ltoDebugPM = false; 17700b57cec5SDimitry Andric } else if (s.startswith("lldlto=")) { 17710b57cec5SDimitry Andric StringRef optLevel = s.substr(7); 17720b57cec5SDimitry Andric if (optLevel.getAsInteger(10, config->ltoo) || config->ltoo > 3) 17730b57cec5SDimitry Andric error("/opt:lldlto: invalid optimization level: " + optLevel); 17740b57cec5SDimitry Andric } else if (s.startswith("lldltojobs=")) { 17750b57cec5SDimitry Andric StringRef jobs = s.substr(11); 17765ffd83dbSDimitry Andric if (!get_threadpool_strategy(jobs)) 17770b57cec5SDimitry Andric error("/opt:lldltojobs: invalid job count: " + jobs); 17785ffd83dbSDimitry Andric config->thinLTOJobs = jobs.str(); 17790b57cec5SDimitry Andric } else if (s.startswith("lldltopartitions=")) { 17800b57cec5SDimitry Andric StringRef n = s.substr(17); 17810b57cec5SDimitry Andric if (n.getAsInteger(10, config->ltoPartitions) || 17820b57cec5SDimitry Andric config->ltoPartitions == 0) 17830b57cec5SDimitry Andric error("/opt:lldltopartitions: invalid partition count: " + n); 17840b57cec5SDimitry Andric } else if (s != "lbr" && s != "nolbr") 17850b57cec5SDimitry Andric error("/opt: unknown option: " + s); 17860b57cec5SDimitry Andric } 17870b57cec5SDimitry Andric } 17880b57cec5SDimitry Andric 1789fe6060f1SDimitry Andric if (!icfLevel) 1790fe6060f1SDimitry Andric icfLevel = doGC ? ICFLevel::All : ICFLevel::None; 17910b57cec5SDimitry Andric config->doGC = doGC; 179281ad6265SDimitry Andric config->doICF = *icfLevel; 1793fe6060f1SDimitry Andric config->tailMerge = 1794fe6060f1SDimitry Andric (tailMerge == 1 && config->doICF != ICFLevel::None) || tailMerge == 2; 1795e8d8bef9SDimitry Andric config->ltoDebugPassManager = ltoDebugPM; 17960b57cec5SDimitry Andric 17970b57cec5SDimitry Andric // Handle /lldsavetemps 17980b57cec5SDimitry Andric if (args.hasArg(OPT_lldsavetemps)) 17990b57cec5SDimitry Andric config->saveTemps = true; 18000b57cec5SDimitry Andric 18010b57cec5SDimitry Andric // Handle /kill-at 18020b57cec5SDimitry Andric if (args.hasArg(OPT_kill_at)) 18030b57cec5SDimitry Andric config->killAt = true; 18040b57cec5SDimitry Andric 18050b57cec5SDimitry Andric // Handle /lldltocache 18060b57cec5SDimitry Andric if (auto *arg = args.getLastArg(OPT_lldltocache)) 18070b57cec5SDimitry Andric config->ltoCache = arg->getValue(); 18080b57cec5SDimitry Andric 18090b57cec5SDimitry Andric // Handle /lldsavecachepolicy 18100b57cec5SDimitry Andric if (auto *arg = args.getLastArg(OPT_lldltocachepolicy)) 18110b57cec5SDimitry Andric config->ltoCachePolicy = CHECK( 18120b57cec5SDimitry Andric parseCachePruningPolicy(arg->getValue()), 18130b57cec5SDimitry Andric Twine("/lldltocachepolicy: invalid cache policy: ") + arg->getValue()); 18140b57cec5SDimitry Andric 18150b57cec5SDimitry Andric // Handle /failifmismatch 18160b57cec5SDimitry Andric for (auto *arg : args.filtered(OPT_failifmismatch)) 18170b57cec5SDimitry Andric checkFailIfMismatch(arg->getValue(), nullptr); 18180b57cec5SDimitry Andric 18190b57cec5SDimitry Andric // Handle /merge 18200b57cec5SDimitry Andric for (auto *arg : args.filtered(OPT_merge)) 18210b57cec5SDimitry Andric parseMerge(arg->getValue()); 18220b57cec5SDimitry Andric 18230b57cec5SDimitry Andric // Add default section merging rules after user rules. User rules take 18240b57cec5SDimitry Andric // precedence, but we will emit a warning if there is a conflict. 18250b57cec5SDimitry Andric parseMerge(".idata=.rdata"); 18260b57cec5SDimitry Andric parseMerge(".didat=.rdata"); 18270b57cec5SDimitry Andric parseMerge(".edata=.rdata"); 18280b57cec5SDimitry Andric parseMerge(".xdata=.rdata"); 18290b57cec5SDimitry Andric parseMerge(".bss=.data"); 18300b57cec5SDimitry Andric 18310b57cec5SDimitry Andric if (config->mingw) { 18320b57cec5SDimitry Andric parseMerge(".ctors=.rdata"); 18330b57cec5SDimitry Andric parseMerge(".dtors=.rdata"); 18340b57cec5SDimitry Andric parseMerge(".CRT=.rdata"); 18350b57cec5SDimitry Andric } 18360b57cec5SDimitry Andric 18370b57cec5SDimitry Andric // Handle /section 18380b57cec5SDimitry Andric for (auto *arg : args.filtered(OPT_section)) 18390b57cec5SDimitry Andric parseSection(arg->getValue()); 18400b57cec5SDimitry Andric 18410b57cec5SDimitry Andric // Handle /align 18420b57cec5SDimitry Andric if (auto *arg = args.getLastArg(OPT_align)) { 18430b57cec5SDimitry Andric parseNumbers(arg->getValue(), &config->align); 18440b57cec5SDimitry Andric if (!isPowerOf2_64(config->align)) 18450b57cec5SDimitry Andric error("/align: not a power of two: " + StringRef(arg->getValue())); 1846480093f4SDimitry Andric if (!args.hasArg(OPT_driver)) 1847480093f4SDimitry Andric warn("/align specified without /driver; image may not run"); 18480b57cec5SDimitry Andric } 18490b57cec5SDimitry Andric 18500b57cec5SDimitry Andric // Handle /aligncomm 18510b57cec5SDimitry Andric for (auto *arg : args.filtered(OPT_aligncomm)) 18520b57cec5SDimitry Andric parseAligncomm(arg->getValue()); 18530b57cec5SDimitry Andric 1854349cc55cSDimitry Andric // Handle /manifestdependency. 1855349cc55cSDimitry Andric for (auto *arg : args.filtered(OPT_manifestdependency)) 1856349cc55cSDimitry Andric config->manifestDependencies.insert(arg->getValue()); 18570b57cec5SDimitry Andric 18580b57cec5SDimitry Andric // Handle /manifest and /manifest: 18590b57cec5SDimitry Andric if (auto *arg = args.getLastArg(OPT_manifest, OPT_manifest_colon)) { 18600b57cec5SDimitry Andric if (arg->getOption().getID() == OPT_manifest) 18610b57cec5SDimitry Andric config->manifest = Configuration::SideBySide; 18620b57cec5SDimitry Andric else 18630b57cec5SDimitry Andric parseManifest(arg->getValue()); 18640b57cec5SDimitry Andric } 18650b57cec5SDimitry Andric 18660b57cec5SDimitry Andric // Handle /manifestuac 18670b57cec5SDimitry Andric if (auto *arg = args.getLastArg(OPT_manifestuac)) 18680b57cec5SDimitry Andric parseManifestUAC(arg->getValue()); 18690b57cec5SDimitry Andric 18700b57cec5SDimitry Andric // Handle /manifestfile 18710b57cec5SDimitry Andric if (auto *arg = args.getLastArg(OPT_manifestfile)) 18720b57cec5SDimitry Andric config->manifestFile = arg->getValue(); 18730b57cec5SDimitry Andric 18740b57cec5SDimitry Andric // Handle /manifestinput 18750b57cec5SDimitry Andric for (auto *arg : args.filtered(OPT_manifestinput)) 18760b57cec5SDimitry Andric config->manifestInput.push_back(arg->getValue()); 18770b57cec5SDimitry Andric 18780b57cec5SDimitry Andric if (!config->manifestInput.empty() && 18790b57cec5SDimitry Andric config->manifest != Configuration::Embed) { 18800b57cec5SDimitry Andric fatal("/manifestinput: requires /manifest:embed"); 18810b57cec5SDimitry Andric } 18820b57cec5SDimitry Andric 18830b57cec5SDimitry Andric config->thinLTOEmitImportsFiles = args.hasArg(OPT_thinlto_emit_imports_files); 18840b57cec5SDimitry Andric config->thinLTOIndexOnly = args.hasArg(OPT_thinlto_index_only) || 18850b57cec5SDimitry Andric args.hasArg(OPT_thinlto_index_only_arg); 18860b57cec5SDimitry Andric config->thinLTOIndexOnlyArg = 18870b57cec5SDimitry Andric args.getLastArgValue(OPT_thinlto_index_only_arg); 18880b57cec5SDimitry Andric config->thinLTOPrefixReplace = 18890b57cec5SDimitry Andric getOldNewOptions(args, OPT_thinlto_prefix_replace); 18900b57cec5SDimitry Andric config->thinLTOObjectSuffixReplace = 18910b57cec5SDimitry Andric getOldNewOptions(args, OPT_thinlto_object_suffix_replace); 189285868e8aSDimitry Andric config->ltoObjPath = args.getLastArgValue(OPT_lto_obj_path); 1893fe6060f1SDimitry Andric config->ltoCSProfileGenerate = args.hasArg(OPT_lto_cs_profile_generate); 1894fe6060f1SDimitry Andric config->ltoCSProfileFile = args.getLastArgValue(OPT_lto_cs_profile_file); 18950b57cec5SDimitry Andric // Handle miscellaneous boolean flags. 1896349cc55cSDimitry Andric config->ltoPGOWarnMismatch = args.hasFlag(OPT_lto_pgo_warn_mismatch, 1897349cc55cSDimitry Andric OPT_lto_pgo_warn_mismatch_no, true); 18980b57cec5SDimitry Andric config->allowBind = args.hasFlag(OPT_allowbind, OPT_allowbind_no, true); 18990b57cec5SDimitry Andric config->allowIsolation = 19000b57cec5SDimitry Andric args.hasFlag(OPT_allowisolation, OPT_allowisolation_no, true); 19010b57cec5SDimitry Andric config->incremental = 19020b57cec5SDimitry Andric args.hasFlag(OPT_incremental, OPT_incremental_no, 1903fe6060f1SDimitry Andric !config->doGC && config->doICF == ICFLevel::None && 1904fe6060f1SDimitry Andric !args.hasArg(OPT_order) && !args.hasArg(OPT_profile)); 19050b57cec5SDimitry Andric config->integrityCheck = 19060b57cec5SDimitry Andric args.hasFlag(OPT_integritycheck, OPT_integritycheck_no, false); 19075ffd83dbSDimitry Andric config->cetCompat = args.hasFlag(OPT_cetcompat, OPT_cetcompat_no, false); 19080b57cec5SDimitry Andric config->nxCompat = args.hasFlag(OPT_nxcompat, OPT_nxcompat_no, true); 19090b57cec5SDimitry Andric for (auto *arg : args.filtered(OPT_swaprun)) 19100b57cec5SDimitry Andric parseSwaprun(arg->getValue()); 19110b57cec5SDimitry Andric config->terminalServerAware = 19120b57cec5SDimitry Andric !config->dll && args.hasFlag(OPT_tsaware, OPT_tsaware_no, true); 19130b57cec5SDimitry Andric config->debugDwarf = debug == DebugKind::Dwarf; 1914fe6060f1SDimitry Andric config->debugGHashes = debug == DebugKind::GHash || debug == DebugKind::Full; 19150b57cec5SDimitry Andric config->debugSymtab = debug == DebugKind::Symtab; 19165ffd83dbSDimitry Andric config->autoImport = 19175ffd83dbSDimitry Andric args.hasFlag(OPT_auto_import, OPT_auto_import_no, config->mingw); 19185ffd83dbSDimitry Andric config->pseudoRelocs = args.hasFlag( 19195ffd83dbSDimitry Andric OPT_runtime_pseudo_reloc, OPT_runtime_pseudo_reloc_no, config->mingw); 1920e8d8bef9SDimitry Andric config->callGraphProfileSort = args.hasFlag( 1921e8d8bef9SDimitry Andric OPT_call_graph_profile_sort, OPT_call_graph_profile_sort_no, true); 1922fe6060f1SDimitry Andric config->stdcallFixup = 1923fe6060f1SDimitry Andric args.hasFlag(OPT_stdcall_fixup, OPT_stdcall_fixup_no, config->mingw); 1924fe6060f1SDimitry Andric config->warnStdcallFixup = !args.hasArg(OPT_stdcall_fixup); 19250b57cec5SDimitry Andric 1926e8d8bef9SDimitry Andric // Don't warn about long section names, such as .debug_info, for mingw or 1927e8d8bef9SDimitry Andric // when -debug:dwarf is requested. 1928480093f4SDimitry Andric if (config->mingw || config->debugDwarf) 1929480093f4SDimitry Andric config->warnLongSectionNames = false; 1930480093f4SDimitry Andric 19310b57cec5SDimitry Andric if (config->incremental && args.hasArg(OPT_profile)) { 19320b57cec5SDimitry Andric warn("ignoring '/incremental' due to '/profile' specification"); 19330b57cec5SDimitry Andric config->incremental = false; 19340b57cec5SDimitry Andric } 19350b57cec5SDimitry Andric 19360b57cec5SDimitry Andric if (config->incremental && args.hasArg(OPT_order)) { 19370b57cec5SDimitry Andric warn("ignoring '/incremental' due to '/order' specification"); 19380b57cec5SDimitry Andric config->incremental = false; 19390b57cec5SDimitry Andric } 19400b57cec5SDimitry Andric 19410b57cec5SDimitry Andric if (config->incremental && config->doGC) { 19420b57cec5SDimitry Andric warn("ignoring '/incremental' because REF is enabled; use '/opt:noref' to " 19430b57cec5SDimitry Andric "disable"); 19440b57cec5SDimitry Andric config->incremental = false; 19450b57cec5SDimitry Andric } 19460b57cec5SDimitry Andric 1947fe6060f1SDimitry Andric if (config->incremental && config->doICF != ICFLevel::None) { 19480b57cec5SDimitry Andric warn("ignoring '/incremental' because ICF is enabled; use '/opt:noicf' to " 19490b57cec5SDimitry Andric "disable"); 19500b57cec5SDimitry Andric config->incremental = false; 19510b57cec5SDimitry Andric } 19520b57cec5SDimitry Andric 19530b57cec5SDimitry Andric if (errorCount()) 19540b57cec5SDimitry Andric return; 19550b57cec5SDimitry Andric 19560b57cec5SDimitry Andric std::set<sys::fs::UniqueID> wholeArchives; 19570b57cec5SDimitry Andric for (auto *arg : args.filtered(OPT_wholearchive_file)) 1958*bdd1243dSDimitry Andric if (std::optional<StringRef> path = doFindFile(arg->getValue())) 1959*bdd1243dSDimitry Andric if (std::optional<sys::fs::UniqueID> id = getUniqueID(*path)) 19600b57cec5SDimitry Andric wholeArchives.insert(*id); 19610b57cec5SDimitry Andric 19620b57cec5SDimitry Andric // A predicate returning true if a given path is an argument for 19630b57cec5SDimitry Andric // /wholearchive:, or /wholearchive is enabled globally. 19640b57cec5SDimitry Andric // This function is a bit tricky because "foo.obj /wholearchive:././foo.obj" 19650b57cec5SDimitry Andric // needs to be handled as "/wholearchive:foo.obj foo.obj". 19660b57cec5SDimitry Andric auto isWholeArchive = [&](StringRef path) -> bool { 19670b57cec5SDimitry Andric if (args.hasArg(OPT_wholearchive_flag)) 19680b57cec5SDimitry Andric return true; 1969*bdd1243dSDimitry Andric if (std::optional<sys::fs::UniqueID> id = getUniqueID(path)) 19700b57cec5SDimitry Andric return wholeArchives.count(*id); 19710b57cec5SDimitry Andric return false; 19720b57cec5SDimitry Andric }; 19730b57cec5SDimitry Andric 197485868e8aSDimitry Andric // Create a list of input files. These can be given as OPT_INPUT options 197585868e8aSDimitry Andric // and OPT_wholearchive_file options, and we also need to track OPT_start_lib 197685868e8aSDimitry Andric // and OPT_end_lib. 197785868e8aSDimitry Andric bool inLib = false; 197885868e8aSDimitry Andric for (auto *arg : args) { 197985868e8aSDimitry Andric switch (arg->getOption().getID()) { 198085868e8aSDimitry Andric case OPT_end_lib: 198185868e8aSDimitry Andric if (!inLib) 198285868e8aSDimitry Andric error("stray " + arg->getSpelling()); 198385868e8aSDimitry Andric inLib = false; 198485868e8aSDimitry Andric break; 198585868e8aSDimitry Andric case OPT_start_lib: 198685868e8aSDimitry Andric if (inLib) 198785868e8aSDimitry Andric error("nested " + arg->getSpelling()); 198885868e8aSDimitry Andric inLib = true; 198985868e8aSDimitry Andric break; 199085868e8aSDimitry Andric case OPT_wholearchive_file: 1991*bdd1243dSDimitry Andric if (std::optional<StringRef> path = findFile(arg->getValue())) 199285868e8aSDimitry Andric enqueuePath(*path, true, inLib); 199385868e8aSDimitry Andric break; 199485868e8aSDimitry Andric case OPT_INPUT: 1995*bdd1243dSDimitry Andric if (std::optional<StringRef> path = findFile(arg->getValue())) 199685868e8aSDimitry Andric enqueuePath(*path, isWholeArchive(*path), inLib); 199785868e8aSDimitry Andric break; 199885868e8aSDimitry Andric default: 199985868e8aSDimitry Andric // Ignore other options. 200085868e8aSDimitry Andric break; 200185868e8aSDimitry Andric } 200285868e8aSDimitry Andric } 20030b57cec5SDimitry Andric 20040b57cec5SDimitry Andric // Read all input files given via the command line. 20050b57cec5SDimitry Andric run(); 20060b57cec5SDimitry Andric if (errorCount()) 20070b57cec5SDimitry Andric return; 20080b57cec5SDimitry Andric 20090b57cec5SDimitry Andric // We should have inferred a machine type by now from the input files, but if 20100b57cec5SDimitry Andric // not we assume x64. 20110b57cec5SDimitry Andric if (config->machine == IMAGE_FILE_MACHINE_UNKNOWN) { 20120b57cec5SDimitry Andric warn("/machine is not specified. x64 is assumed"); 20130b57cec5SDimitry Andric config->machine = AMD64; 201481ad6265SDimitry Andric addWinSysRootLibSearchPaths(); 20150b57cec5SDimitry Andric } 20160b57cec5SDimitry Andric config->wordsize = config->is64() ? 8 : 4; 20170b57cec5SDimitry Andric 201881ad6265SDimitry Andric // Process files specified as /defaultlib. These must be processed after 201981ad6265SDimitry Andric // addWinSysRootLibSearchPaths(), which is why they are in a separate loop. 202081ad6265SDimitry Andric for (auto *arg : args.filtered(OPT_defaultlib)) 2021*bdd1243dSDimitry Andric if (std::optional<StringRef> path = findLib(arg->getValue())) 202281ad6265SDimitry Andric enqueuePath(*path, false, false); 202381ad6265SDimitry Andric run(); 202481ad6265SDimitry Andric if (errorCount()) 202581ad6265SDimitry Andric return; 202681ad6265SDimitry Andric 2027*bdd1243dSDimitry Andric // Handle /RELEASE 2028*bdd1243dSDimitry Andric if (args.hasArg(OPT_release)) 2029*bdd1243dSDimitry Andric config->writeCheckSum = true; 2030*bdd1243dSDimitry Andric 20310b57cec5SDimitry Andric // Handle /safeseh, x86 only, on by default, except for mingw. 2032979e22ffSDimitry Andric if (config->machine == I386) { 2033979e22ffSDimitry Andric config->safeSEH = args.hasFlag(OPT_safeseh, OPT_safeseh_no, !config->mingw); 2034979e22ffSDimitry Andric config->noSEH = args.hasArg(OPT_noseh); 2035979e22ffSDimitry Andric } 20360b57cec5SDimitry Andric 20370b57cec5SDimitry Andric // Handle /functionpadmin 20380b57cec5SDimitry Andric for (auto *arg : args.filtered(OPT_functionpadmin, OPT_functionpadmin_opt)) 2039*bdd1243dSDimitry Andric parseFunctionPadMin(arg); 20400b57cec5SDimitry Andric 204181ad6265SDimitry Andric if (tar) { 20420b57cec5SDimitry Andric tar->append("response.txt", 20430b57cec5SDimitry Andric createResponseFile(args, filePaths, 20440b57cec5SDimitry Andric ArrayRef<StringRef>(searchPaths).slice(1))); 204581ad6265SDimitry Andric } 20460b57cec5SDimitry Andric 20470b57cec5SDimitry Andric // Handle /largeaddressaware 20480b57cec5SDimitry Andric config->largeAddressAware = args.hasFlag( 20490b57cec5SDimitry Andric OPT_largeaddressaware, OPT_largeaddressaware_no, config->is64()); 20500b57cec5SDimitry Andric 20510b57cec5SDimitry Andric // Handle /highentropyva 20520b57cec5SDimitry Andric config->highEntropyVA = 20530b57cec5SDimitry Andric config->is64() && 20540b57cec5SDimitry Andric args.hasFlag(OPT_highentropyva, OPT_highentropyva_no, true); 20550b57cec5SDimitry Andric 20560b57cec5SDimitry Andric if (!config->dynamicBase && 20570b57cec5SDimitry Andric (config->machine == ARMNT || config->machine == ARM64)) 20580b57cec5SDimitry Andric error("/dynamicbase:no is not compatible with " + 20590b57cec5SDimitry Andric machineToStr(config->machine)); 20600b57cec5SDimitry Andric 20610b57cec5SDimitry Andric // Handle /export 20620b57cec5SDimitry Andric for (auto *arg : args.filtered(OPT_export)) { 20630b57cec5SDimitry Andric Export e = parseExport(arg->getValue()); 20640b57cec5SDimitry Andric if (config->machine == I386) { 20650b57cec5SDimitry Andric if (!isDecorated(e.name)) 206604eeddc0SDimitry Andric e.name = saver().save("_" + e.name); 20670b57cec5SDimitry Andric if (!e.extName.empty() && !isDecorated(e.extName)) 206804eeddc0SDimitry Andric e.extName = saver().save("_" + e.extName); 20690b57cec5SDimitry Andric } 20700b57cec5SDimitry Andric config->exports.push_back(e); 20710b57cec5SDimitry Andric } 20720b57cec5SDimitry Andric 20730b57cec5SDimitry Andric // Handle /def 20740b57cec5SDimitry Andric if (auto *arg = args.getLastArg(OPT_deffile)) { 20750b57cec5SDimitry Andric // parseModuleDefs mutates Config object. 20760b57cec5SDimitry Andric parseModuleDefs(arg->getValue()); 20770b57cec5SDimitry Andric } 20780b57cec5SDimitry Andric 20790b57cec5SDimitry Andric // Handle generation of import library from a def file. 2080480093f4SDimitry Andric if (!args.hasArg(OPT_INPUT, OPT_wholearchive_file)) { 20810b57cec5SDimitry Andric fixupExports(); 208281ad6265SDimitry Andric if (!config->noimplib) 20830b57cec5SDimitry Andric createImportLibrary(/*asLib=*/true); 20840b57cec5SDimitry Andric return; 20850b57cec5SDimitry Andric } 20860b57cec5SDimitry Andric 20870b57cec5SDimitry Andric // Windows specific -- if no /subsystem is given, we need to infer 20880b57cec5SDimitry Andric // that from entry point name. Must happen before /entry handling, 20890b57cec5SDimitry Andric // and after the early return when just writing an import library. 20900b57cec5SDimitry Andric if (config->subsystem == IMAGE_SUBSYSTEM_UNKNOWN) { 20910b57cec5SDimitry Andric config->subsystem = inferSubsystem(); 20920b57cec5SDimitry Andric if (config->subsystem == IMAGE_SUBSYSTEM_UNKNOWN) 20930b57cec5SDimitry Andric fatal("subsystem must be defined"); 20940b57cec5SDimitry Andric } 20950b57cec5SDimitry Andric 20960b57cec5SDimitry Andric // Handle /entry and /dll 20970b57cec5SDimitry Andric if (auto *arg = args.getLastArg(OPT_entry)) { 20980b57cec5SDimitry Andric config->entry = addUndefined(mangle(arg->getValue())); 20990b57cec5SDimitry Andric } else if (!config->entry && !config->noEntry) { 21000b57cec5SDimitry Andric if (args.hasArg(OPT_dll)) { 21010b57cec5SDimitry Andric StringRef s = (config->machine == I386) ? "__DllMainCRTStartup@12" 21020b57cec5SDimitry Andric : "_DllMainCRTStartup"; 21030b57cec5SDimitry Andric config->entry = addUndefined(s); 2104480093f4SDimitry Andric } else if (config->driverWdm) { 2105480093f4SDimitry Andric // /driver:wdm implies /entry:_NtProcessStartup 2106480093f4SDimitry Andric config->entry = addUndefined(mangle("_NtProcessStartup")); 21070b57cec5SDimitry Andric } else { 21080b57cec5SDimitry Andric // Windows specific -- If entry point name is not given, we need to 21090b57cec5SDimitry Andric // infer that from user-defined entry name. 21100b57cec5SDimitry Andric StringRef s = findDefaultEntry(); 21110b57cec5SDimitry Andric if (s.empty()) 21120b57cec5SDimitry Andric fatal("entry point must be defined"); 21130b57cec5SDimitry Andric config->entry = addUndefined(s); 21140b57cec5SDimitry Andric log("Entry name inferred: " + s); 21150b57cec5SDimitry Andric } 21160b57cec5SDimitry Andric } 21170b57cec5SDimitry Andric 21180b57cec5SDimitry Andric // Handle /delayload 21190b57cec5SDimitry Andric for (auto *arg : args.filtered(OPT_delayload)) { 21200b57cec5SDimitry Andric config->delayLoads.insert(StringRef(arg->getValue()).lower()); 21210b57cec5SDimitry Andric if (config->machine == I386) { 21220b57cec5SDimitry Andric config->delayLoadHelper = addUndefined("___delayLoadHelper2@8"); 21230b57cec5SDimitry Andric } else { 21240b57cec5SDimitry Andric config->delayLoadHelper = addUndefined("__delayLoadHelper2"); 21250b57cec5SDimitry Andric } 21260b57cec5SDimitry Andric } 21270b57cec5SDimitry Andric 21280b57cec5SDimitry Andric // Set default image name if neither /out or /def set it. 21290b57cec5SDimitry Andric if (config->outputFile.empty()) { 2130480093f4SDimitry Andric config->outputFile = getOutputPath( 2131*bdd1243dSDimitry Andric (*args.filtered(OPT_INPUT, OPT_wholearchive_file).begin())->getValue(), 2132*bdd1243dSDimitry Andric config->dll, config->driver); 21330b57cec5SDimitry Andric } 21340b57cec5SDimitry Andric 21350b57cec5SDimitry Andric // Fail early if an output file is not writable. 21360b57cec5SDimitry Andric if (auto e = tryCreateFile(config->outputFile)) { 21370b57cec5SDimitry Andric error("cannot open output file " + config->outputFile + ": " + e.message()); 21380b57cec5SDimitry Andric return; 21390b57cec5SDimitry Andric } 21400b57cec5SDimitry Andric 2141*bdd1243dSDimitry Andric config->lldmapFile = getMapFile(args, OPT_lldmap, OPT_lldmap_file); 2142*bdd1243dSDimitry Andric config->mapFile = getMapFile(args, OPT_map, OPT_map_file); 2143*bdd1243dSDimitry Andric 2144*bdd1243dSDimitry Andric if (config->mapFile != "" && args.hasArg(OPT_map_info)) { 2145*bdd1243dSDimitry Andric for (auto *arg : args.filtered(OPT_map_info)) { 2146*bdd1243dSDimitry Andric std::string s = StringRef(arg->getValue()).lower(); 2147*bdd1243dSDimitry Andric if (s == "exports") 2148*bdd1243dSDimitry Andric config->mapInfo = true; 2149*bdd1243dSDimitry Andric else 2150*bdd1243dSDimitry Andric error("unknown option: /mapinfo:" + s); 2151*bdd1243dSDimitry Andric } 2152*bdd1243dSDimitry Andric } 2153*bdd1243dSDimitry Andric 2154*bdd1243dSDimitry Andric if (config->lldmapFile != "" && config->lldmapFile == config->mapFile) { 2155*bdd1243dSDimitry Andric warn("/lldmap and /map have the same output file '" + config->mapFile + 2156*bdd1243dSDimitry Andric "'.\n>>> ignoring /lldmap"); 2157*bdd1243dSDimitry Andric config->lldmapFile.clear(); 2158*bdd1243dSDimitry Andric } 2159*bdd1243dSDimitry Andric 21600b57cec5SDimitry Andric if (shouldCreatePDB) { 21610b57cec5SDimitry Andric // Put the PDB next to the image if no /pdb flag was passed. 21620b57cec5SDimitry Andric if (config->pdbPath.empty()) { 21630b57cec5SDimitry Andric config->pdbPath = config->outputFile; 21640b57cec5SDimitry Andric sys::path::replace_extension(config->pdbPath, ".pdb"); 21650b57cec5SDimitry Andric } 21660b57cec5SDimitry Andric 21670b57cec5SDimitry Andric // The embedded PDB path should be the absolute path to the PDB if no 21680b57cec5SDimitry Andric // /pdbaltpath flag was passed. 21690b57cec5SDimitry Andric if (config->pdbAltPath.empty()) { 21700b57cec5SDimitry Andric config->pdbAltPath = config->pdbPath; 21710b57cec5SDimitry Andric 21720b57cec5SDimitry Andric // It's important to make the path absolute and remove dots. This path 21730b57cec5SDimitry Andric // will eventually be written into the PE header, and certain Microsoft 21740b57cec5SDimitry Andric // tools won't work correctly if these assumptions are not held. 21750b57cec5SDimitry Andric sys::fs::make_absolute(config->pdbAltPath); 21760b57cec5SDimitry Andric sys::path::remove_dots(config->pdbAltPath); 21770b57cec5SDimitry Andric } else { 2178*bdd1243dSDimitry Andric // Don't do this earlier, so that ctx.OutputFile is ready. 2179*bdd1243dSDimitry Andric parsePDBAltPath(); 21800b57cec5SDimitry Andric } 21810b57cec5SDimitry Andric } 21820b57cec5SDimitry Andric 21830b57cec5SDimitry Andric // Set default image base if /base is not given. 21840b57cec5SDimitry Andric if (config->imageBase == uint64_t(-1)) 21850b57cec5SDimitry Andric config->imageBase = getDefaultImageBase(); 21860b57cec5SDimitry Andric 2187349cc55cSDimitry Andric ctx.symtab.addSynthetic(mangle("__ImageBase"), nullptr); 21880b57cec5SDimitry Andric if (config->machine == I386) { 2189349cc55cSDimitry Andric ctx.symtab.addAbsolute("___safe_se_handler_table", 0); 2190349cc55cSDimitry Andric ctx.symtab.addAbsolute("___safe_se_handler_count", 0); 21910b57cec5SDimitry Andric } 21920b57cec5SDimitry Andric 2193349cc55cSDimitry Andric ctx.symtab.addAbsolute(mangle("__guard_fids_count"), 0); 2194349cc55cSDimitry Andric ctx.symtab.addAbsolute(mangle("__guard_fids_table"), 0); 2195349cc55cSDimitry Andric ctx.symtab.addAbsolute(mangle("__guard_flags"), 0); 2196349cc55cSDimitry Andric ctx.symtab.addAbsolute(mangle("__guard_iat_count"), 0); 2197349cc55cSDimitry Andric ctx.symtab.addAbsolute(mangle("__guard_iat_table"), 0); 2198349cc55cSDimitry Andric ctx.symtab.addAbsolute(mangle("__guard_longjmp_count"), 0); 2199349cc55cSDimitry Andric ctx.symtab.addAbsolute(mangle("__guard_longjmp_table"), 0); 22000b57cec5SDimitry Andric // Needed for MSVC 2017 15.5 CRT. 2201349cc55cSDimitry Andric ctx.symtab.addAbsolute(mangle("__enclave_config"), 0); 2202fe6060f1SDimitry Andric // Needed for MSVC 2019 16.8 CRT. 2203349cc55cSDimitry Andric ctx.symtab.addAbsolute(mangle("__guard_eh_cont_count"), 0); 2204349cc55cSDimitry Andric ctx.symtab.addAbsolute(mangle("__guard_eh_cont_table"), 0); 22050b57cec5SDimitry Andric 22065ffd83dbSDimitry Andric if (config->pseudoRelocs) { 2207349cc55cSDimitry Andric ctx.symtab.addAbsolute(mangle("__RUNTIME_PSEUDO_RELOC_LIST__"), 0); 2208349cc55cSDimitry Andric ctx.symtab.addAbsolute(mangle("__RUNTIME_PSEUDO_RELOC_LIST_END__"), 0); 22095ffd83dbSDimitry Andric } 22105ffd83dbSDimitry Andric if (config->mingw) { 2211349cc55cSDimitry Andric ctx.symtab.addAbsolute(mangle("__CTOR_LIST__"), 0); 2212349cc55cSDimitry Andric ctx.symtab.addAbsolute(mangle("__DTOR_LIST__"), 0); 22130b57cec5SDimitry Andric } 22140b57cec5SDimitry Andric 22150b57cec5SDimitry Andric // This code may add new undefined symbols to the link, which may enqueue more 22160b57cec5SDimitry Andric // symbol resolution tasks, so we need to continue executing tasks until we 22170b57cec5SDimitry Andric // converge. 22180b57cec5SDimitry Andric do { 22190b57cec5SDimitry Andric // Windows specific -- if entry point is not found, 22200b57cec5SDimitry Andric // search for its mangled names. 22210b57cec5SDimitry Andric if (config->entry) 22220b57cec5SDimitry Andric mangleMaybe(config->entry); 22230b57cec5SDimitry Andric 22240b57cec5SDimitry Andric // Windows specific -- Make sure we resolve all dllexported symbols. 22250b57cec5SDimitry Andric for (Export &e : config->exports) { 22260b57cec5SDimitry Andric if (!e.forwardTo.empty()) 22270b57cec5SDimitry Andric continue; 22280b57cec5SDimitry Andric e.sym = addUndefined(e.name); 22290b57cec5SDimitry Andric if (!e.directives) 22300b57cec5SDimitry Andric e.symbolName = mangleMaybe(e.sym); 22310b57cec5SDimitry Andric } 22320b57cec5SDimitry Andric 22330b57cec5SDimitry Andric // Add weak aliases. Weak aliases is a mechanism to give remaining 22340b57cec5SDimitry Andric // undefined symbols final chance to be resolved successfully. 22350b57cec5SDimitry Andric for (auto pair : config->alternateNames) { 22360b57cec5SDimitry Andric StringRef from = pair.first; 22370b57cec5SDimitry Andric StringRef to = pair.second; 2238349cc55cSDimitry Andric Symbol *sym = ctx.symtab.find(from); 22390b57cec5SDimitry Andric if (!sym) 22400b57cec5SDimitry Andric continue; 22410b57cec5SDimitry Andric if (auto *u = dyn_cast<Undefined>(sym)) 22420b57cec5SDimitry Andric if (!u->weakAlias) 2243349cc55cSDimitry Andric u->weakAlias = ctx.symtab.addUndefined(to); 22440b57cec5SDimitry Andric } 22450b57cec5SDimitry Andric 22460b57cec5SDimitry Andric // If any inputs are bitcode files, the LTO code generator may create 22470b57cec5SDimitry Andric // references to library functions that are not explicit in the bitcode 22480b57cec5SDimitry Andric // file's symbol table. If any of those library functions are defined in a 22490b57cec5SDimitry Andric // bitcode file in an archive member, we need to arrange to use LTO to 22500b57cec5SDimitry Andric // compile those archive members by adding them to the link beforehand. 2251349cc55cSDimitry Andric if (!ctx.bitcodeFileInstances.empty()) 225285868e8aSDimitry Andric for (auto *s : lto::LTO::getRuntimeLibcallSymbols()) 2253349cc55cSDimitry Andric ctx.symtab.addLibcall(s); 22540b57cec5SDimitry Andric 22550b57cec5SDimitry Andric // Windows specific -- if __load_config_used can be resolved, resolve it. 2256349cc55cSDimitry Andric if (ctx.symtab.findUnderscore("_load_config_used")) 22570b57cec5SDimitry Andric addUndefined(mangle("_load_config_used")); 22580b57cec5SDimitry Andric 22590b57cec5SDimitry Andric if (args.hasArg(OPT_include_optional)) { 22600b57cec5SDimitry Andric // Handle /includeoptional 22610b57cec5SDimitry Andric for (auto *arg : args.filtered(OPT_include_optional)) 22620eae32dcSDimitry Andric if (isa_and_nonnull<LazyArchive>(ctx.symtab.find(arg->getValue()))) 22630b57cec5SDimitry Andric addUndefined(arg->getValue()); 22640b57cec5SDimitry Andric } 2265a4a491e2SDimitry Andric } while (run()); 22660b57cec5SDimitry Andric 2267e8d8bef9SDimitry Andric // Create wrapped symbols for -wrap option. 2268349cc55cSDimitry Andric std::vector<WrappedSymbol> wrapped = addWrappedSymbols(ctx, args); 2269e8d8bef9SDimitry Andric // Load more object files that might be needed for wrapped symbols. 2270e8d8bef9SDimitry Andric if (!wrapped.empty()) 2271e8d8bef9SDimitry Andric while (run()); 2272e8d8bef9SDimitry Andric 2273fe6060f1SDimitry Andric if (config->autoImport || config->stdcallFixup) { 22745ffd83dbSDimitry Andric // MinGW specific. 22750b57cec5SDimitry Andric // Load any further object files that might be needed for doing automatic 2276fe6060f1SDimitry Andric // imports, and do stdcall fixups. 22770b57cec5SDimitry Andric // 22780b57cec5SDimitry Andric // For cases with no automatically imported symbols, this iterates once 22790b57cec5SDimitry Andric // over the symbol table and doesn't do anything. 22800b57cec5SDimitry Andric // 22810b57cec5SDimitry Andric // For the normal case with a few automatically imported symbols, this 22820b57cec5SDimitry Andric // should only need to be run once, since each new object file imported 22830b57cec5SDimitry Andric // is an import library and wouldn't add any new undefined references, 22840b57cec5SDimitry Andric // but there's nothing stopping the __imp_ symbols from coming from a 22850b57cec5SDimitry Andric // normal object file as well (although that won't be used for the 22860b57cec5SDimitry Andric // actual autoimport later on). If this pass adds new undefined references, 22870b57cec5SDimitry Andric // we won't iterate further to resolve them. 2288fe6060f1SDimitry Andric // 2289fe6060f1SDimitry Andric // If stdcall fixups only are needed for loading import entries from 2290fe6060f1SDimitry Andric // a DLL without import library, this also just needs running once. 2291fe6060f1SDimitry Andric // If it ends up pulling in more object files from static libraries, 2292fe6060f1SDimitry Andric // (and maybe doing more stdcall fixups along the way), this would need 2293fe6060f1SDimitry Andric // to loop these two calls. 2294349cc55cSDimitry Andric ctx.symtab.loadMinGWSymbols(); 22950b57cec5SDimitry Andric run(); 22960b57cec5SDimitry Andric } 22970b57cec5SDimitry Andric 229885868e8aSDimitry Andric // At this point, we should not have any symbols that cannot be resolved. 229985868e8aSDimitry Andric // If we are going to do codegen for link-time optimization, check for 230085868e8aSDimitry Andric // unresolvable symbols first, so we don't spend time generating code that 230185868e8aSDimitry Andric // will fail to link anyway. 2302349cc55cSDimitry Andric if (!ctx.bitcodeFileInstances.empty() && !config->forceUnresolved) 2303349cc55cSDimitry Andric ctx.symtab.reportUnresolvable(); 23040b57cec5SDimitry Andric if (errorCount()) 23050b57cec5SDimitry Andric return; 23060b57cec5SDimitry Andric 2307fe6060f1SDimitry Andric config->hadExplicitExports = !config->exports.empty(); 2308fe6060f1SDimitry Andric if (config->mingw) { 2309fe6060f1SDimitry Andric // In MinGW, all symbols are automatically exported if no symbols 2310fe6060f1SDimitry Andric // are chosen to be exported. 2311fe6060f1SDimitry Andric maybeExportMinGWSymbols(args); 2312fe6060f1SDimitry Andric } 2313fe6060f1SDimitry Andric 231485868e8aSDimitry Andric // Do LTO by compiling bitcode input files to a set of native COFF files then 231585868e8aSDimitry Andric // link those files (unless -thinlto-index-only was given, in which case we 231685868e8aSDimitry Andric // resolve symbols and write indices, but don't generate native code or link). 2317349cc55cSDimitry Andric ctx.symtab.compileBitcodeFiles(); 231885868e8aSDimitry Andric 231985868e8aSDimitry Andric // If -thinlto-index-only is given, we should create only "index 232085868e8aSDimitry Andric // files" and not object files. Index file creation is already done 2321*bdd1243dSDimitry Andric // in addCombinedLTOObject, so we are done if that's the case. 232285868e8aSDimitry Andric if (config->thinLTOIndexOnly) 232385868e8aSDimitry Andric return; 232485868e8aSDimitry Andric 232585868e8aSDimitry Andric // If we generated native object files from bitcode files, this resolves 232685868e8aSDimitry Andric // references to the symbols we use from them. 232785868e8aSDimitry Andric run(); 232885868e8aSDimitry Andric 2329e8d8bef9SDimitry Andric // Apply symbol renames for -wrap. 2330e8d8bef9SDimitry Andric if (!wrapped.empty()) 2331349cc55cSDimitry Andric wrapSymbols(ctx, wrapped); 2332e8d8bef9SDimitry Andric 233385868e8aSDimitry Andric // Resolve remaining undefined symbols and warn about imported locals. 2334349cc55cSDimitry Andric ctx.symtab.resolveRemainingUndefines(); 233585868e8aSDimitry Andric if (errorCount()) 233685868e8aSDimitry Andric return; 233785868e8aSDimitry Andric 23380b57cec5SDimitry Andric if (config->mingw) { 23390b57cec5SDimitry Andric // Make sure the crtend.o object is the last object file. This object 23400b57cec5SDimitry Andric // file can contain terminating section chunks that need to be placed 23410b57cec5SDimitry Andric // last. GNU ld processes files and static libraries explicitly in the 23420b57cec5SDimitry Andric // order provided on the command line, while lld will pull in needed 23430b57cec5SDimitry Andric // files from static libraries only after the last object file on the 23440b57cec5SDimitry Andric // command line. 2345349cc55cSDimitry Andric for (auto i = ctx.objFileInstances.begin(), e = ctx.objFileInstances.end(); 23460b57cec5SDimitry Andric i != e; i++) { 23470b57cec5SDimitry Andric ObjFile *file = *i; 23480b57cec5SDimitry Andric if (isCrtend(file->getName())) { 2349349cc55cSDimitry Andric ctx.objFileInstances.erase(i); 2350349cc55cSDimitry Andric ctx.objFileInstances.push_back(file); 23510b57cec5SDimitry Andric break; 23520b57cec5SDimitry Andric } 23530b57cec5SDimitry Andric } 23540b57cec5SDimitry Andric } 23550b57cec5SDimitry Andric 23560b57cec5SDimitry Andric // Windows specific -- when we are creating a .dll file, we also 235785868e8aSDimitry Andric // need to create a .lib file. In MinGW mode, we only do that when the 235885868e8aSDimitry Andric // -implib option is given explicitly, for compatibility with GNU ld. 23590b57cec5SDimitry Andric if (!config->exports.empty() || config->dll) { 23600b57cec5SDimitry Andric fixupExports(); 236181ad6265SDimitry Andric if (!config->noimplib && (!config->mingw || !config->implib.empty())) 23620b57cec5SDimitry Andric createImportLibrary(/*asLib=*/false); 23630b57cec5SDimitry Andric assignExportOrdinals(); 23640b57cec5SDimitry Andric } 23650b57cec5SDimitry Andric 23660b57cec5SDimitry Andric // Handle /output-def (MinGW specific). 23670b57cec5SDimitry Andric if (auto *arg = args.getLastArg(OPT_output_def)) 2368*bdd1243dSDimitry Andric writeDefFile(arg->getValue(), config->exports); 23690b57cec5SDimitry Andric 23700b57cec5SDimitry Andric // Set extra alignment for .comm symbols 23710b57cec5SDimitry Andric for (auto pair : config->alignComm) { 23720b57cec5SDimitry Andric StringRef name = pair.first; 23730b57cec5SDimitry Andric uint32_t alignment = pair.second; 23740b57cec5SDimitry Andric 2375349cc55cSDimitry Andric Symbol *sym = ctx.symtab.find(name); 23760b57cec5SDimitry Andric if (!sym) { 23770b57cec5SDimitry Andric warn("/aligncomm symbol " + name + " not found"); 23780b57cec5SDimitry Andric continue; 23790b57cec5SDimitry Andric } 23800b57cec5SDimitry Andric 23810b57cec5SDimitry Andric // If the symbol isn't common, it must have been replaced with a regular 23820b57cec5SDimitry Andric // symbol, which will carry its own alignment. 23830b57cec5SDimitry Andric auto *dc = dyn_cast<DefinedCommon>(sym); 23840b57cec5SDimitry Andric if (!dc) 23850b57cec5SDimitry Andric continue; 23860b57cec5SDimitry Andric 23870b57cec5SDimitry Andric CommonChunk *c = dc->getChunk(); 23880b57cec5SDimitry Andric c->setAlignment(std::max(c->getAlignment(), alignment)); 23890b57cec5SDimitry Andric } 23900b57cec5SDimitry Andric 2391349cc55cSDimitry Andric // Windows specific -- Create an embedded or side-by-side manifest. 2392349cc55cSDimitry Andric // /manifestdependency: enables /manifest unless an explicit /manifest:no is 2393349cc55cSDimitry Andric // also passed. 2394349cc55cSDimitry Andric if (config->manifest == Configuration::Embed) 2395349cc55cSDimitry Andric addBuffer(createManifestRes(), false, false); 2396349cc55cSDimitry Andric else if (config->manifest == Configuration::SideBySide || 2397349cc55cSDimitry Andric (config->manifest == Configuration::Default && 2398349cc55cSDimitry Andric !config->manifestDependencies.empty())) 23990b57cec5SDimitry Andric createSideBySideManifest(); 24000b57cec5SDimitry Andric 24010b57cec5SDimitry Andric // Handle /order. We want to do this at this moment because we 24020b57cec5SDimitry Andric // need a complete list of comdat sections to warn on nonexistent 24030b57cec5SDimitry Andric // functions. 2404e8d8bef9SDimitry Andric if (auto *arg = args.getLastArg(OPT_order)) { 2405e8d8bef9SDimitry Andric if (args.hasArg(OPT_call_graph_ordering_file)) 2406e8d8bef9SDimitry Andric error("/order and /call-graph-order-file may not be used together"); 2407*bdd1243dSDimitry Andric parseOrderFile(arg->getValue()); 2408e8d8bef9SDimitry Andric config->callGraphProfileSort = false; 2409e8d8bef9SDimitry Andric } 2410e8d8bef9SDimitry Andric 2411e8d8bef9SDimitry Andric // Handle /call-graph-ordering-file and /call-graph-profile-sort (default on). 2412e8d8bef9SDimitry Andric if (config->callGraphProfileSort) { 2413e8d8bef9SDimitry Andric if (auto *arg = args.getLastArg(OPT_call_graph_ordering_file)) { 2414*bdd1243dSDimitry Andric parseCallGraphFile(arg->getValue()); 2415e8d8bef9SDimitry Andric } 2416349cc55cSDimitry Andric readCallGraphsFromObjectFiles(ctx); 2417e8d8bef9SDimitry Andric } 2418e8d8bef9SDimitry Andric 2419e8d8bef9SDimitry Andric // Handle /print-symbol-order. 2420e8d8bef9SDimitry Andric if (auto *arg = args.getLastArg(OPT_print_symbol_order)) 2421e8d8bef9SDimitry Andric config->printSymbolOrder = arg->getValue(); 24220b57cec5SDimitry Andric 24230b57cec5SDimitry Andric // Identify unreferenced COMDAT sections. 2424fe6060f1SDimitry Andric if (config->doGC) { 2425fe6060f1SDimitry Andric if (config->mingw) { 2426fe6060f1SDimitry Andric // markLive doesn't traverse .eh_frame, but the personality function is 2427fe6060f1SDimitry Andric // only reached that way. The proper solution would be to parse and 2428fe6060f1SDimitry Andric // traverse the .eh_frame section, like the ELF linker does. 2429fe6060f1SDimitry Andric // For now, just manually try to retain the known possible personality 2430fe6060f1SDimitry Andric // functions. This doesn't bring in more object files, but only marks 2431fe6060f1SDimitry Andric // functions that already have been included to be retained. 2432*bdd1243dSDimitry Andric for (const char *n : {"__gxx_personality_v0", "__gcc_personality_v0", 2433*bdd1243dSDimitry Andric "rust_eh_personality"}) { 2434349cc55cSDimitry Andric Defined *d = dyn_cast_or_null<Defined>(ctx.symtab.findUnderscore(n)); 2435fe6060f1SDimitry Andric if (d && !d->isGCRoot) { 2436fe6060f1SDimitry Andric d->isGCRoot = true; 2437fe6060f1SDimitry Andric config->gcroot.push_back(d); 2438fe6060f1SDimitry Andric } 2439fe6060f1SDimitry Andric } 2440fe6060f1SDimitry Andric } 2441fe6060f1SDimitry Andric 2442349cc55cSDimitry Andric markLive(ctx); 2443fe6060f1SDimitry Andric } 24440b57cec5SDimitry Andric 24450b57cec5SDimitry Andric // Needs to happen after the last call to addFile(). 244685868e8aSDimitry Andric convertResources(); 24470b57cec5SDimitry Andric 24480b57cec5SDimitry Andric // Identify identical COMDAT sections to merge them. 2449fe6060f1SDimitry Andric if (config->doICF != ICFLevel::None) { 2450349cc55cSDimitry Andric findKeepUniqueSections(ctx); 2451*bdd1243dSDimitry Andric doICF(ctx); 24520b57cec5SDimitry Andric } 24530b57cec5SDimitry Andric 24540b57cec5SDimitry Andric // Write the result. 2455349cc55cSDimitry Andric writeResult(ctx); 24560b57cec5SDimitry Andric 24570b57cec5SDimitry Andric // Stop early so we can print the results. 24585ffd83dbSDimitry Andric rootTimer.stop(); 24590b57cec5SDimitry Andric if (config->showTiming) 2460349cc55cSDimitry Andric ctx.rootTimer.print(); 24610b57cec5SDimitry Andric } 24620b57cec5SDimitry Andric 2463*bdd1243dSDimitry Andric } // namespace lld::coff 2464