Path: blob/main/contrib/llvm-project/lld/COFF/DriverUtils.cpp
34870 views
//===- DriverUtils.cpp ----------------------------------------------------===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//7//8// This file contains utility functions for the driver. Because there9// are so many small functions, we created this separate file to make10// Driver.cpp less cluttered.11//12//===----------------------------------------------------------------------===//1314#include "COFFLinkerContext.h"15#include "Driver.h"16#include "Symbols.h"17#include "lld/Common/ErrorHandler.h"18#include "lld/Common/Memory.h"19#include "llvm/ADT/STLExtras.h"20#include "llvm/ADT/StringExtras.h"21#include "llvm/ADT/StringSwitch.h"22#include "llvm/BinaryFormat/COFF.h"23#include "llvm/IR/Mangler.h"24#include "llvm/Object/COFF.h"25#include "llvm/Object/WindowsResource.h"26#include "llvm/Option/Arg.h"27#include "llvm/Option/ArgList.h"28#include "llvm/Option/Option.h"29#include "llvm/Support/CommandLine.h"30#include "llvm/Support/FileUtilities.h"31#include "llvm/Support/MathExtras.h"32#include "llvm/Support/Process.h"33#include "llvm/Support/Program.h"34#include "llvm/Support/TimeProfiler.h"35#include "llvm/Support/raw_ostream.h"36#include "llvm/WindowsManifest/WindowsManifestMerger.h"37#include <limits>38#include <memory>39#include <optional>4041using namespace llvm::COFF;42using namespace llvm::object;43using namespace llvm::opt;44using namespace llvm;45using llvm::sys::Process;4647namespace lld {48namespace coff {49namespace {5051const uint16_t SUBLANG_ENGLISH_US = 0x0409;52const uint16_t RT_MANIFEST = 24;5354class Executor {55public:56explicit Executor(StringRef s) : prog(saver().save(s)) {}57void add(StringRef s) { args.push_back(saver().save(s)); }58void add(std::string &s) { args.push_back(saver().save(s)); }59void add(Twine s) { args.push_back(saver().save(s)); }60void add(const char *s) { args.push_back(saver().save(s)); }6162void run() {63ErrorOr<std::string> exeOrErr = sys::findProgramByName(prog);64if (auto ec = exeOrErr.getError())65fatal("unable to find " + prog + " in PATH: " + ec.message());66StringRef exe = saver().save(*exeOrErr);67args.insert(args.begin(), exe);6869if (sys::ExecuteAndWait(args[0], args) != 0)70fatal("ExecuteAndWait failed: " +71llvm::join(args.begin(), args.end(), " "));72}7374private:75StringRef prog;76std::vector<StringRef> args;77};7879} // anonymous namespace8081// Parses a string in the form of "<integer>[,<integer>]".82void LinkerDriver::parseNumbers(StringRef arg, uint64_t *addr, uint64_t *size) {83auto [s1, s2] = arg.split(',');84if (s1.getAsInteger(0, *addr))85fatal("invalid number: " + s1);86if (size && !s2.empty() && s2.getAsInteger(0, *size))87fatal("invalid number: " + s2);88}8990// Parses a string in the form of "<integer>[.<integer>]".91// If second number is not present, Minor is set to 0.92void LinkerDriver::parseVersion(StringRef arg, uint32_t *major,93uint32_t *minor) {94auto [s1, s2] = arg.split('.');95if (s1.getAsInteger(10, *major))96fatal("invalid number: " + s1);97*minor = 0;98if (!s2.empty() && s2.getAsInteger(10, *minor))99fatal("invalid number: " + s2);100}101102void LinkerDriver::parseGuard(StringRef fullArg) {103SmallVector<StringRef, 1> splitArgs;104fullArg.split(splitArgs, ",");105for (StringRef arg : splitArgs) {106if (arg.equals_insensitive("no"))107ctx.config.guardCF = GuardCFLevel::Off;108else if (arg.equals_insensitive("nolongjmp"))109ctx.config.guardCF &= ~GuardCFLevel::LongJmp;110else if (arg.equals_insensitive("noehcont"))111ctx.config.guardCF &= ~GuardCFLevel::EHCont;112else if (arg.equals_insensitive("cf") || arg.equals_insensitive("longjmp"))113ctx.config.guardCF |= GuardCFLevel::CF | GuardCFLevel::LongJmp;114else if (arg.equals_insensitive("ehcont"))115ctx.config.guardCF |= GuardCFLevel::CF | GuardCFLevel::EHCont;116else117fatal("invalid argument to /guard: " + arg);118}119}120121// Parses a string in the form of "<subsystem>[,<integer>[.<integer>]]".122void LinkerDriver::parseSubsystem(StringRef arg, WindowsSubsystem *sys,123uint32_t *major, uint32_t *minor,124bool *gotVersion) {125auto [sysStr, ver] = arg.split(',');126std::string sysStrLower = sysStr.lower();127*sys = StringSwitch<WindowsSubsystem>(sysStrLower)128.Case("boot_application", IMAGE_SUBSYSTEM_WINDOWS_BOOT_APPLICATION)129.Case("console", IMAGE_SUBSYSTEM_WINDOWS_CUI)130.Case("default", IMAGE_SUBSYSTEM_UNKNOWN)131.Case("efi_application", IMAGE_SUBSYSTEM_EFI_APPLICATION)132.Case("efi_boot_service_driver", IMAGE_SUBSYSTEM_EFI_BOOT_SERVICE_DRIVER)133.Case("efi_rom", IMAGE_SUBSYSTEM_EFI_ROM)134.Case("efi_runtime_driver", IMAGE_SUBSYSTEM_EFI_RUNTIME_DRIVER)135.Case("native", IMAGE_SUBSYSTEM_NATIVE)136.Case("posix", IMAGE_SUBSYSTEM_POSIX_CUI)137.Case("windows", IMAGE_SUBSYSTEM_WINDOWS_GUI)138.Default(IMAGE_SUBSYSTEM_UNKNOWN);139if (*sys == IMAGE_SUBSYSTEM_UNKNOWN && sysStrLower != "default")140fatal("unknown subsystem: " + sysStr);141if (!ver.empty())142parseVersion(ver, major, minor);143if (gotVersion)144*gotVersion = !ver.empty();145}146147// Parse a string of the form of "<from>=<to>".148// Results are directly written to Config.149void LinkerDriver::parseAlternateName(StringRef s) {150auto [from, to] = s.split('=');151if (from.empty() || to.empty())152fatal("/alternatename: invalid argument: " + s);153auto it = ctx.config.alternateNames.find(from);154if (it != ctx.config.alternateNames.end() && it->second != to)155fatal("/alternatename: conflicts: " + s);156ctx.config.alternateNames.insert(it, std::make_pair(from, to));157}158159// Parse a string of the form of "<from>=<to>".160// Results are directly written to Config.161void LinkerDriver::parseMerge(StringRef s) {162auto [from, to] = s.split('=');163if (from.empty() || to.empty())164fatal("/merge: invalid argument: " + s);165if (from == ".rsrc" || to == ".rsrc")166fatal("/merge: cannot merge '.rsrc' with any section");167if (from == ".reloc" || to == ".reloc")168fatal("/merge: cannot merge '.reloc' with any section");169auto pair = ctx.config.merge.insert(std::make_pair(from, to));170bool inserted = pair.second;171if (!inserted) {172StringRef existing = pair.first->second;173if (existing != to)174warn(s + ": already merged into " + existing);175}176}177178void LinkerDriver::parsePDBPageSize(StringRef s) {179int v;180if (s.getAsInteger(0, v)) {181error("/pdbpagesize: invalid argument: " + s);182return;183}184if (v != 4096 && v != 8192 && v != 16384 && v != 32768) {185error("/pdbpagesize: invalid argument: " + s);186return;187}188189ctx.config.pdbPageSize = v;190}191192static uint32_t parseSectionAttributes(StringRef s) {193uint32_t ret = 0;194for (char c : s.lower()) {195switch (c) {196case 'd':197ret |= IMAGE_SCN_MEM_DISCARDABLE;198break;199case 'e':200ret |= IMAGE_SCN_MEM_EXECUTE;201break;202case 'k':203ret |= IMAGE_SCN_MEM_NOT_CACHED;204break;205case 'p':206ret |= IMAGE_SCN_MEM_NOT_PAGED;207break;208case 'r':209ret |= IMAGE_SCN_MEM_READ;210break;211case 's':212ret |= IMAGE_SCN_MEM_SHARED;213break;214case 'w':215ret |= IMAGE_SCN_MEM_WRITE;216break;217default:218fatal("/section: invalid argument: " + s);219}220}221return ret;222}223224// Parses /section option argument.225void LinkerDriver::parseSection(StringRef s) {226auto [name, attrs] = s.split(',');227if (name.empty() || attrs.empty())228fatal("/section: invalid argument: " + s);229ctx.config.section[name] = parseSectionAttributes(attrs);230}231232// Parses /aligncomm option argument.233void LinkerDriver::parseAligncomm(StringRef s) {234auto [name, align] = s.split(',');235if (name.empty() || align.empty()) {236error("/aligncomm: invalid argument: " + s);237return;238}239int v;240if (align.getAsInteger(0, v)) {241error("/aligncomm: invalid argument: " + s);242return;243}244ctx.config.alignComm[std::string(name)] =245std::max(ctx.config.alignComm[std::string(name)], 1 << v);246}247248// Parses /functionpadmin option argument.249void LinkerDriver::parseFunctionPadMin(llvm::opt::Arg *a) {250StringRef arg = a->getNumValues() ? a->getValue() : "";251if (!arg.empty()) {252// Optional padding in bytes is given.253if (arg.getAsInteger(0, ctx.config.functionPadMin))254error("/functionpadmin: invalid argument: " + arg);255return;256}257// No optional argument given.258// Set default padding based on machine, similar to link.exe.259// There is no default padding for ARM platforms.260if (ctx.config.machine == I386) {261ctx.config.functionPadMin = 5;262} else if (ctx.config.machine == AMD64) {263ctx.config.functionPadMin = 6;264} else {265error("/functionpadmin: invalid argument for this machine: " + arg);266}267}268269// Parses /dependentloadflag option argument.270void LinkerDriver::parseDependentLoadFlags(llvm::opt::Arg *a) {271StringRef arg = a->getNumValues() ? a->getValue() : "";272if (!arg.empty()) {273if (arg.getAsInteger(0, ctx.config.dependentLoadFlags))274error("/dependentloadflag: invalid argument: " + arg);275return;276}277// MSVC linker reports error "no argument specified", although MSDN describes278// argument as optional.279error("/dependentloadflag: no argument specified");280}281282// Parses a string in the form of "EMBED[,=<integer>]|NO".283// Results are directly written to284// Config.285void LinkerDriver::parseManifest(StringRef arg) {286if (arg.equals_insensitive("no")) {287ctx.config.manifest = Configuration::No;288return;289}290if (!arg.starts_with_insensitive("embed"))291fatal("invalid option " + arg);292ctx.config.manifest = Configuration::Embed;293arg = arg.substr(strlen("embed"));294if (arg.empty())295return;296if (!arg.starts_with_insensitive(",id="))297fatal("invalid option " + arg);298arg = arg.substr(strlen(",id="));299if (arg.getAsInteger(0, ctx.config.manifestID))300fatal("invalid option " + arg);301}302303// Parses a string in the form of "level=<string>|uiAccess=<string>|NO".304// Results are directly written to Config.305void LinkerDriver::parseManifestUAC(StringRef arg) {306if (arg.equals_insensitive("no")) {307ctx.config.manifestUAC = false;308return;309}310for (;;) {311arg = arg.ltrim();312if (arg.empty())313return;314if (arg.consume_front_insensitive("level=")) {315std::tie(ctx.config.manifestLevel, arg) = arg.split(" ");316continue;317}318if (arg.consume_front_insensitive("uiaccess=")) {319std::tie(ctx.config.manifestUIAccess, arg) = arg.split(" ");320continue;321}322fatal("invalid option " + arg);323}324}325326// Parses a string in the form of "cd|net[,(cd|net)]*"327// Results are directly written to Config.328void LinkerDriver::parseSwaprun(StringRef arg) {329do {330auto [swaprun, newArg] = arg.split(',');331if (swaprun.equals_insensitive("cd"))332ctx.config.swaprunCD = true;333else if (swaprun.equals_insensitive("net"))334ctx.config.swaprunNet = true;335else if (swaprun.empty())336error("/swaprun: missing argument");337else338error("/swaprun: invalid argument: " + swaprun);339// To catch trailing commas, e.g. `/spawrun:cd,`340if (newArg.empty() && arg.ends_with(","))341error("/swaprun: missing argument");342arg = newArg;343} while (!arg.empty());344}345346// An RAII temporary file class that automatically removes a temporary file.347namespace {348class TemporaryFile {349public:350TemporaryFile(StringRef prefix, StringRef extn, StringRef contents = "") {351SmallString<128> s;352if (auto ec = sys::fs::createTemporaryFile("lld-" + prefix, extn, s))353fatal("cannot create a temporary file: " + ec.message());354path = std::string(s);355356if (!contents.empty()) {357std::error_code ec;358raw_fd_ostream os(path, ec, sys::fs::OF_None);359if (ec)360fatal("failed to open " + path + ": " + ec.message());361os << contents;362}363}364365TemporaryFile(TemporaryFile &&obj) noexcept { std::swap(path, obj.path); }366367~TemporaryFile() {368if (path.empty())369return;370if (sys::fs::remove(path))371fatal("failed to remove " + path);372}373374// Returns a memory buffer of this temporary file.375// Note that this function does not leave the file open,376// so it is safe to remove the file immediately after this function377// is called (you cannot remove an opened file on Windows.)378std::unique_ptr<MemoryBuffer> getMemoryBuffer() {379// IsVolatile=true forces MemoryBuffer to not use mmap().380return CHECK(MemoryBuffer::getFile(path, /*IsText=*/false,381/*RequiresNullTerminator=*/false,382/*IsVolatile=*/true),383"could not open " + path);384}385386std::string path;387};388}389390std::string LinkerDriver::createDefaultXml() {391std::string ret;392raw_string_ostream os(ret);393394// Emit the XML. Note that we do *not* verify that the XML attributes are395// syntactically correct. This is intentional for link.exe compatibility.396os << "<?xml version=\"1.0\" standalone=\"yes\"?>\n"397<< "<assembly xmlns=\"urn:schemas-microsoft-com:asm.v1\"\n"398<< " manifestVersion=\"1.0\">\n";399if (ctx.config.manifestUAC) {400os << " <trustInfo>\n"401<< " <security>\n"402<< " <requestedPrivileges>\n"403<< " <requestedExecutionLevel level=" << ctx.config.manifestLevel404<< " uiAccess=" << ctx.config.manifestUIAccess << "/>\n"405<< " </requestedPrivileges>\n"406<< " </security>\n"407<< " </trustInfo>\n";408}409for (auto manifestDependency : ctx.config.manifestDependencies) {410os << " <dependency>\n"411<< " <dependentAssembly>\n"412<< " <assemblyIdentity " << manifestDependency << " />\n"413<< " </dependentAssembly>\n"414<< " </dependency>\n";415}416os << "</assembly>\n";417return os.str();418}419420std::string421LinkerDriver::createManifestXmlWithInternalMt(StringRef defaultXml) {422std::unique_ptr<MemoryBuffer> defaultXmlCopy =423MemoryBuffer::getMemBufferCopy(defaultXml);424425windows_manifest::WindowsManifestMerger merger;426if (auto e = merger.merge(*defaultXmlCopy.get()))427fatal("internal manifest tool failed on default xml: " +428toString(std::move(e)));429430for (StringRef filename : ctx.config.manifestInput) {431std::unique_ptr<MemoryBuffer> manifest =432check(MemoryBuffer::getFile(filename));433// Call takeBuffer to include in /reproduce: output if applicable.434if (auto e = merger.merge(takeBuffer(std::move(manifest))))435fatal("internal manifest tool failed on file " + filename + ": " +436toString(std::move(e)));437}438439return std::string(merger.getMergedManifest().get()->getBuffer());440}441442std::string443LinkerDriver::createManifestXmlWithExternalMt(StringRef defaultXml) {444// Create the default manifest file as a temporary file.445TemporaryFile Default("defaultxml", "manifest");446std::error_code ec;447raw_fd_ostream os(Default.path, ec, sys::fs::OF_TextWithCRLF);448if (ec)449fatal("failed to open " + Default.path + ": " + ec.message());450os << defaultXml;451os.close();452453// Merge user-supplied manifests if they are given. Since libxml2 is not454// enabled, we must shell out to Microsoft's mt.exe tool.455TemporaryFile user("user", "manifest");456457Executor e("mt.exe");458e.add("/manifest");459e.add(Default.path);460for (StringRef filename : ctx.config.manifestInput) {461e.add("/manifest");462e.add(filename);463464// Manually add the file to the /reproduce: tar if needed.465if (tar)466if (auto mbOrErr = MemoryBuffer::getFile(filename))467takeBuffer(std::move(*mbOrErr));468}469e.add("/nologo");470e.add("/out:" + StringRef(user.path));471e.run();472473return std::string(474CHECK(MemoryBuffer::getFile(user.path), "could not open " + user.path)475.get()476->getBuffer());477}478479std::string LinkerDriver::createManifestXml() {480std::string defaultXml = createDefaultXml();481if (ctx.config.manifestInput.empty())482return defaultXml;483484if (windows_manifest::isAvailable())485return createManifestXmlWithInternalMt(defaultXml);486487return createManifestXmlWithExternalMt(defaultXml);488}489490std::unique_ptr<WritableMemoryBuffer>491LinkerDriver::createMemoryBufferForManifestRes(size_t manifestSize) {492size_t resSize = alignTo(493object::WIN_RES_MAGIC_SIZE + object::WIN_RES_NULL_ENTRY_SIZE +494sizeof(object::WinResHeaderPrefix) + sizeof(object::WinResIDs) +495sizeof(object::WinResHeaderSuffix) + manifestSize,496object::WIN_RES_DATA_ALIGNMENT);497return WritableMemoryBuffer::getNewMemBuffer(resSize, ctx.config.outputFile +498".manifest.res");499}500501static void writeResFileHeader(char *&buf) {502memcpy(buf, COFF::WinResMagic, sizeof(COFF::WinResMagic));503buf += sizeof(COFF::WinResMagic);504memset(buf, 0, object::WIN_RES_NULL_ENTRY_SIZE);505buf += object::WIN_RES_NULL_ENTRY_SIZE;506}507508static void writeResEntryHeader(char *&buf, size_t manifestSize,509int manifestID) {510// Write the prefix.511auto *prefix = reinterpret_cast<object::WinResHeaderPrefix *>(buf);512prefix->DataSize = manifestSize;513prefix->HeaderSize = sizeof(object::WinResHeaderPrefix) +514sizeof(object::WinResIDs) +515sizeof(object::WinResHeaderSuffix);516buf += sizeof(object::WinResHeaderPrefix);517518// Write the Type/Name IDs.519auto *iDs = reinterpret_cast<object::WinResIDs *>(buf);520iDs->setType(RT_MANIFEST);521iDs->setName(manifestID);522buf += sizeof(object::WinResIDs);523524// Write the suffix.525auto *suffix = reinterpret_cast<object::WinResHeaderSuffix *>(buf);526suffix->DataVersion = 0;527suffix->MemoryFlags = object::WIN_RES_PURE_MOVEABLE;528suffix->Language = SUBLANG_ENGLISH_US;529suffix->Version = 0;530suffix->Characteristics = 0;531buf += sizeof(object::WinResHeaderSuffix);532}533534// Create a resource file containing a manifest XML.535std::unique_ptr<MemoryBuffer> LinkerDriver::createManifestRes() {536std::string manifest = createManifestXml();537538std::unique_ptr<WritableMemoryBuffer> res =539createMemoryBufferForManifestRes(manifest.size());540541char *buf = res->getBufferStart();542writeResFileHeader(buf);543writeResEntryHeader(buf, manifest.size(), ctx.config.manifestID);544545// Copy the manifest data into the .res file.546std::copy(manifest.begin(), manifest.end(), buf);547return std::move(res);548}549550void LinkerDriver::createSideBySideManifest() {551std::string path = std::string(ctx.config.manifestFile);552if (path == "")553path = ctx.config.outputFile + ".manifest";554std::error_code ec;555raw_fd_ostream out(path, ec, sys::fs::OF_TextWithCRLF);556if (ec)557fatal("failed to create manifest: " + ec.message());558out << createManifestXml();559}560561// Parse a string in the form of562// "<name>[=<internalname>][,@ordinal[,NONAME]][,DATA][,PRIVATE]"563// or "<name>=<dllname>.<name>".564// Used for parsing /export arguments.565Export LinkerDriver::parseExport(StringRef arg) {566Export e;567e.source = ExportSource::Export;568569StringRef rest;570std::tie(e.name, rest) = arg.split(",");571if (e.name.empty())572goto err;573574if (e.name.contains('=')) {575auto [x, y] = e.name.split("=");576577// If "<name>=<dllname>.<name>".578if (y.contains(".")) {579e.name = x;580e.forwardTo = y;581} else {582e.extName = x;583e.name = y;584if (e.name.empty())585goto err;586}587}588589// Optional parameters590// "[,@ordinal[,NONAME]][,DATA][,PRIVATE][,EXPORTAS,exportname]"591while (!rest.empty()) {592StringRef tok;593std::tie(tok, rest) = rest.split(",");594if (tok.equals_insensitive("noname")) {595if (e.ordinal == 0)596goto err;597e.noname = true;598continue;599}600if (tok.equals_insensitive("data")) {601e.data = true;602continue;603}604if (tok.equals_insensitive("constant")) {605e.constant = true;606continue;607}608if (tok.equals_insensitive("private")) {609e.isPrivate = true;610continue;611}612if (tok.equals_insensitive("exportas")) {613if (!rest.empty() && !rest.contains(','))614e.exportAs = rest;615else616error("invalid EXPORTAS value: " + rest);617break;618}619if (tok.starts_with("@")) {620int32_t ord;621if (tok.substr(1).getAsInteger(0, ord))622goto err;623if (ord <= 0 || 65535 < ord)624goto err;625e.ordinal = ord;626continue;627}628goto err;629}630return e;631632err:633fatal("invalid /export: " + arg);634}635636// Convert stdcall/fastcall style symbols into unsuffixed symbols,637// with or without a leading underscore. (MinGW specific.)638static StringRef killAt(StringRef sym, bool prefix) {639if (sym.empty())640return sym;641// Strip any trailing stdcall suffix642sym = sym.substr(0, sym.find('@', 1));643if (!sym.starts_with("@")) {644if (prefix && !sym.starts_with("_"))645return saver().save("_" + sym);646return sym;647}648// For fastcall, remove the leading @ and replace it with an649// underscore, if prefixes are used.650sym = sym.substr(1);651if (prefix)652sym = saver().save("_" + sym);653return sym;654}655656static StringRef exportSourceName(ExportSource s) {657switch (s) {658case ExportSource::Directives:659return "source file (directives)";660case ExportSource::Export:661return "/export";662case ExportSource::ModuleDefinition:663return "/def";664default:665llvm_unreachable("unknown ExportSource");666}667}668669// Performs error checking on all /export arguments.670// It also sets ordinals.671void LinkerDriver::fixupExports() {672llvm::TimeTraceScope timeScope("Fixup exports");673// Symbol ordinals must be unique.674std::set<uint16_t> ords;675for (Export &e : ctx.config.exports) {676if (e.ordinal == 0)677continue;678if (!ords.insert(e.ordinal).second)679fatal("duplicate export ordinal: " + e.name);680}681682for (Export &e : ctx.config.exports) {683if (!e.exportAs.empty()) {684e.exportName = e.exportAs;685continue;686}687688StringRef sym =689!e.forwardTo.empty() || e.extName.empty() ? e.name : e.extName;690if (ctx.config.machine == I386 && sym.starts_with("_")) {691// In MSVC mode, a fully decorated stdcall function is exported692// as-is with the leading underscore (with type IMPORT_NAME).693// In MinGW mode, a decorated stdcall function gets the underscore694// removed, just like normal cdecl functions.695if (ctx.config.mingw || !sym.contains('@')) {696e.exportName = sym.substr(1);697continue;698}699}700if (isArm64EC(ctx.config.machine) && !e.data && !e.constant) {701if (std::optional<std::string> demangledName =702getArm64ECDemangledFunctionName(sym)) {703e.exportName = saver().save(*demangledName);704continue;705}706}707e.exportName = sym;708}709710if (ctx.config.killAt && ctx.config.machine == I386) {711for (Export &e : ctx.config.exports) {712e.name = killAt(e.name, true);713e.exportName = killAt(e.exportName, false);714e.extName = killAt(e.extName, true);715e.symbolName = killAt(e.symbolName, true);716}717}718719// Uniquefy by name.720DenseMap<StringRef, std::pair<Export *, unsigned>> map(721ctx.config.exports.size());722std::vector<Export> v;723for (Export &e : ctx.config.exports) {724auto pair = map.insert(std::make_pair(e.exportName, std::make_pair(&e, 0)));725bool inserted = pair.second;726if (inserted) {727pair.first->second.second = v.size();728v.push_back(e);729continue;730}731Export *existing = pair.first->second.first;732if (e == *existing || e.name != existing->name)733continue;734// If the existing export comes from .OBJ directives, we are allowed to735// overwrite it with /DEF: or /EXPORT without any warning, as MSVC link.exe736// does.737if (existing->source == ExportSource::Directives) {738*existing = e;739v[pair.first->second.second] = e;740continue;741}742if (existing->source == e.source) {743warn(Twine("duplicate ") + exportSourceName(existing->source) +744" option: " + e.name);745} else {746warn("duplicate export: " + e.name +747Twine(" first seen in " + exportSourceName(existing->source) +748Twine(", now in " + exportSourceName(e.source))));749}750}751ctx.config.exports = std::move(v);752753// Sort by name.754llvm::sort(ctx.config.exports, [](const Export &a, const Export &b) {755return a.exportName < b.exportName;756});757}758759void LinkerDriver::assignExportOrdinals() {760// Assign unique ordinals if default (= 0).761uint32_t max = 0;762for (Export &e : ctx.config.exports)763max = std::max(max, (uint32_t)e.ordinal);764for (Export &e : ctx.config.exports)765if (e.ordinal == 0)766e.ordinal = ++max;767if (max > std::numeric_limits<uint16_t>::max())768fatal("too many exported symbols (got " + Twine(max) + ", max " +769Twine(std::numeric_limits<uint16_t>::max()) + ")");770}771772// Parses a string in the form of "key=value" and check773// if value matches previous values for the same key.774void LinkerDriver::checkFailIfMismatch(StringRef arg, InputFile *source) {775auto [k, v] = arg.split('=');776if (k.empty() || v.empty())777fatal("/failifmismatch: invalid argument: " + arg);778std::pair<StringRef, InputFile *> existing = ctx.config.mustMatch[k];779if (!existing.first.empty() && v != existing.first) {780std::string sourceStr = source ? toString(source) : "cmd-line";781std::string existingStr =782existing.second ? toString(existing.second) : "cmd-line";783fatal("/failifmismatch: mismatch detected for '" + k + "':\n>>> " +784existingStr + " has value " + existing.first + "\n>>> " + sourceStr +785" has value " + v);786}787ctx.config.mustMatch[k] = {v, source};788}789790// Convert Windows resource files (.res files) to a .obj file.791// Does what cvtres.exe does, but in-process and cross-platform.792MemoryBufferRef LinkerDriver::convertResToCOFF(ArrayRef<MemoryBufferRef> mbs,793ArrayRef<ObjFile *> objs) {794object::WindowsResourceParser parser(/* MinGW */ ctx.config.mingw);795796std::vector<std::string> duplicates;797for (MemoryBufferRef mb : mbs) {798std::unique_ptr<object::Binary> bin = check(object::createBinary(mb));799object::WindowsResource *rf = dyn_cast<object::WindowsResource>(bin.get());800if (!rf)801fatal("cannot compile non-resource file as resource");802803if (auto ec = parser.parse(rf, duplicates))804fatal(toString(std::move(ec)));805}806807// Note: This processes all .res files before all objs. Ideally they'd be808// handled in the same order they were linked (to keep the right one, if809// there are duplicates that are tolerated due to forceMultipleRes).810for (ObjFile *f : objs) {811object::ResourceSectionRef rsf;812if (auto ec = rsf.load(f->getCOFFObj()))813fatal(toString(f) + ": " + toString(std::move(ec)));814815if (auto ec = parser.parse(rsf, f->getName(), duplicates))816fatal(toString(std::move(ec)));817}818819if (ctx.config.mingw)820parser.cleanUpManifests(duplicates);821822for (const auto &dupeDiag : duplicates)823if (ctx.config.forceMultipleRes)824warn(dupeDiag);825else826error(dupeDiag);827828Expected<std::unique_ptr<MemoryBuffer>> e =829llvm::object::writeWindowsResourceCOFF(ctx.config.machine, parser,830ctx.config.timestamp);831if (!e)832fatal("failed to write .res to COFF: " + toString(e.takeError()));833834MemoryBufferRef mbref = **e;835make<std::unique_ptr<MemoryBuffer>>(std::move(*e)); // take ownership836return mbref;837}838839// Create OptTable840841// Create prefix string literals used in Options.td842#define PREFIX(NAME, VALUE) \843static constexpr llvm::StringLiteral NAME##_init[] = VALUE; \844static constexpr llvm::ArrayRef<llvm::StringLiteral> NAME( \845NAME##_init, std::size(NAME##_init) - 1);846#include "Options.inc"847#undef PREFIX848849// Create table mapping all options defined in Options.td850static constexpr llvm::opt::OptTable::Info infoTable[] = {851#define OPTION(...) LLVM_CONSTRUCT_OPT_INFO(__VA_ARGS__),852#include "Options.inc"853#undef OPTION854};855856COFFOptTable::COFFOptTable() : GenericOptTable(infoTable, true) {}857858// Set color diagnostics according to --color-diagnostics={auto,always,never}859// or --no-color-diagnostics flags.860static void handleColorDiagnostics(opt::InputArgList &args) {861auto *arg = args.getLastArg(OPT_color_diagnostics, OPT_color_diagnostics_eq,862OPT_no_color_diagnostics);863if (!arg)864return;865if (arg->getOption().getID() == OPT_color_diagnostics) {866lld::errs().enable_colors(true);867} else if (arg->getOption().getID() == OPT_no_color_diagnostics) {868lld::errs().enable_colors(false);869} else {870StringRef s = arg->getValue();871if (s == "always")872lld::errs().enable_colors(true);873else if (s == "never")874lld::errs().enable_colors(false);875else if (s != "auto")876error("unknown option: --color-diagnostics=" + s);877}878}879880static cl::TokenizerCallback getQuotingStyle(opt::InputArgList &args) {881if (auto *arg = args.getLastArg(OPT_rsp_quoting)) {882StringRef s = arg->getValue();883if (s != "windows" && s != "posix")884error("invalid response file quoting: " + s);885if (s == "windows")886return cl::TokenizeWindowsCommandLine;887return cl::TokenizeGNUCommandLine;888}889// The COFF linker always defaults to Windows quoting.890return cl::TokenizeWindowsCommandLine;891}892893ArgParser::ArgParser(COFFLinkerContext &c) : ctx(c) {}894895// Parses a given list of options.896opt::InputArgList ArgParser::parse(ArrayRef<const char *> argv) {897// Make InputArgList from string vectors.898unsigned missingIndex;899unsigned missingCount;900901// We need to get the quoting style for response files before parsing all902// options so we parse here before and ignore all the options but903// --rsp-quoting and /lldignoreenv.904// (This means --rsp-quoting can't be added through %LINK%.)905opt::InputArgList args =906ctx.optTable.ParseArgs(argv, missingIndex, missingCount);907908// Expand response files (arguments in the form of @<filename>) and insert909// flags from %LINK% and %_LINK_%, and then parse the argument again.910SmallVector<const char *, 256> expandedArgv(argv.data(),911argv.data() + argv.size());912if (!args.hasArg(OPT_lldignoreenv))913addLINK(expandedArgv);914cl::ExpandResponseFiles(saver(), getQuotingStyle(args), expandedArgv);915args = ctx.optTable.ParseArgs(ArrayRef(expandedArgv).drop_front(),916missingIndex, missingCount);917918// Print the real command line if response files are expanded.919if (args.hasArg(OPT_verbose) && argv.size() != expandedArgv.size()) {920std::string msg = "Command line:";921for (const char *s : expandedArgv)922msg += " " + std::string(s);923message(msg);924}925926// Save the command line after response file expansion so we can write it to927// the PDB if necessary. Mimic MSVC, which skips input files.928ctx.config.argv = {argv[0]};929for (opt::Arg *arg : args) {930if (arg->getOption().getKind() != opt::Option::InputClass) {931ctx.config.argv.emplace_back(args.getArgString(arg->getIndex()));932}933}934935// Handle /WX early since it converts missing argument warnings to errors.936errorHandler().fatalWarnings = args.hasFlag(OPT_WX, OPT_WX_no, false);937938if (missingCount)939fatal(Twine(args.getArgString(missingIndex)) + ": missing argument");940941handleColorDiagnostics(args);942943for (opt::Arg *arg : args.filtered(OPT_UNKNOWN)) {944std::string nearest;945if (ctx.optTable.findNearest(arg->getAsString(args), nearest) > 1)946warn("ignoring unknown argument '" + arg->getAsString(args) + "'");947else948warn("ignoring unknown argument '" + arg->getAsString(args) +949"', did you mean '" + nearest + "'");950}951952if (args.hasArg(OPT_lib))953warn("ignoring /lib since it's not the first argument");954955return args;956}957958// Tokenizes and parses a given string as command line in .drective section.959ParsedDirectives ArgParser::parseDirectives(StringRef s) {960ParsedDirectives result;961SmallVector<const char *, 16> rest;962963// Handle /EXPORT and /INCLUDE in a fast path. These directives can appear for964// potentially every symbol in the object, so they must be handled quickly.965SmallVector<StringRef, 16> tokens;966cl::TokenizeWindowsCommandLineNoCopy(s, saver(), tokens);967for (StringRef tok : tokens) {968if (tok.starts_with_insensitive("/export:") ||969tok.starts_with_insensitive("-export:"))970result.exports.push_back(tok.substr(strlen("/export:")));971else if (tok.starts_with_insensitive("/include:") ||972tok.starts_with_insensitive("-include:"))973result.includes.push_back(tok.substr(strlen("/include:")));974else if (tok.starts_with_insensitive("/exclude-symbols:") ||975tok.starts_with_insensitive("-exclude-symbols:"))976result.excludes.push_back(tok.substr(strlen("/exclude-symbols:")));977else {978// Copy substrings that are not valid C strings. The tokenizer may have979// already copied quoted arguments for us, so those do not need to be980// copied again.981bool HasNul = tok.end() != s.end() && tok.data()[tok.size()] == '\0';982rest.push_back(HasNul ? tok.data() : saver().save(tok).data());983}984}985986// Make InputArgList from unparsed string vectors.987unsigned missingIndex;988unsigned missingCount;989990result.args = ctx.optTable.ParseArgs(rest, missingIndex, missingCount);991992if (missingCount)993fatal(Twine(result.args.getArgString(missingIndex)) + ": missing argument");994for (auto *arg : result.args.filtered(OPT_UNKNOWN))995warn("ignoring unknown argument: " + arg->getAsString(result.args));996return result;997}998999// link.exe has an interesting feature. If LINK or _LINK_ environment1000// variables exist, their contents are handled as command line strings.1001// So you can pass extra arguments using them.1002void ArgParser::addLINK(SmallVector<const char *, 256> &argv) {1003// Concatenate LINK env and command line arguments, and then parse them.1004if (std::optional<std::string> s = Process::GetEnv("LINK")) {1005std::vector<const char *> v = tokenize(*s);1006argv.insert(std::next(argv.begin()), v.begin(), v.end());1007}1008if (std::optional<std::string> s = Process::GetEnv("_LINK_")) {1009std::vector<const char *> v = tokenize(*s);1010argv.insert(std::next(argv.begin()), v.begin(), v.end());1011}1012}10131014std::vector<const char *> ArgParser::tokenize(StringRef s) {1015SmallVector<const char *, 16> tokens;1016cl::TokenizeWindowsCommandLine(s, saver(), tokens);1017return std::vector<const char *>(tokens.begin(), tokens.end());1018}10191020void LinkerDriver::printHelp(const char *argv0) {1021ctx.optTable.printHelp(lld::outs(),1022(std::string(argv0) + " [options] file...").c_str(),1023"LLVM Linker", false);1024}10251026} // namespace coff1027} // namespace lld102810291030