Path: blob/main/contrib/llvm-project/lld/ELF/DriverUtils.cpp
34878 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 ctx.driver. Because there9// are so many small functions, we created this separate file to make10// Driver.cpp less cluttered.11//12//===----------------------------------------------------------------------===//1314#include "Config.h"15#include "Driver.h"16#include "lld/Common/CommonLinkerContext.h"17#include "lld/Common/Reproduce.h"18#include "llvm/Option/Option.h"19#include "llvm/Support/CommandLine.h"20#include "llvm/Support/FileSystem.h"21#include "llvm/Support/Path.h"22#include "llvm/Support/TimeProfiler.h"23#include "llvm/TargetParser/Host.h"24#include "llvm/TargetParser/Triple.h"25#include <optional>2627using namespace llvm;28using namespace llvm::sys;29using namespace llvm::opt;30using namespace lld;31using namespace lld::elf;3233// Create OptTable3435// Create prefix string literals used in Options.td36#define PREFIX(NAME, VALUE) \37static constexpr StringLiteral NAME##_init[] = VALUE; \38static constexpr ArrayRef<StringLiteral> NAME(NAME##_init, \39std::size(NAME##_init) - 1);40#include "Options.inc"41#undef PREFIX4243// Create table mapping all options defined in Options.td44static constexpr opt::OptTable::Info optInfo[] = {45#define OPTION(...) LLVM_CONSTRUCT_OPT_INFO(__VA_ARGS__),46#include "Options.inc"47#undef OPTION48};4950ELFOptTable::ELFOptTable() : GenericOptTable(optInfo) {}5152// Set color diagnostics according to --color-diagnostics={auto,always,never}53// or --no-color-diagnostics flags.54static void handleColorDiagnostics(opt::InputArgList &args) {55auto *arg = args.getLastArg(OPT_color_diagnostics);56if (!arg)57return;58StringRef s = arg->getValue();59if (s == "always")60lld::errs().enable_colors(true);61else if (s == "never")62lld::errs().enable_colors(false);63else if (s != "auto")64error("unknown option: --color-diagnostics=" + s);65}6667static cl::TokenizerCallback getQuotingStyle(opt::InputArgList &args) {68if (auto *arg = args.getLastArg(OPT_rsp_quoting)) {69StringRef s = arg->getValue();70if (s != "windows" && s != "posix")71error("invalid response file quoting: " + s);72if (s == "windows")73return cl::TokenizeWindowsCommandLine;74return cl::TokenizeGNUCommandLine;75}76if (Triple(sys::getProcessTriple()).isOSWindows())77return cl::TokenizeWindowsCommandLine;78return cl::TokenizeGNUCommandLine;79}8081// Gold LTO plugin takes a `--plugin-opt foo=bar` option as an alias for82// `--plugin-opt=foo=bar`. We want to handle `--plugin-opt=foo=` as an83// option name and `bar` as a value. Unfortunately, OptParser cannot84// handle an option with a space in it.85//86// In this function, we concatenate command line arguments so that87// `--plugin-opt <foo>` is converted to `--plugin-opt=<foo>`. This is a88// bit hacky, but looks like it is still better than handling --plugin-opt89// options by hand.90static void concatLTOPluginOptions(SmallVectorImpl<const char *> &args) {91SmallVector<const char *, 256> v;92for (size_t i = 0, e = args.size(); i != e; ++i) {93StringRef s = args[i];94if ((s == "-plugin-opt" || s == "--plugin-opt") && i + 1 != e) {95v.push_back(saver().save(s + "=" + args[i + 1]).data());96++i;97} else {98v.push_back(args[i]);99}100}101args = std::move(v);102}103104// Parses a given list of options.105opt::InputArgList ELFOptTable::parse(ArrayRef<const char *> argv) {106// Make InputArgList from string vectors.107unsigned missingIndex;108unsigned missingCount;109SmallVector<const char *, 256> vec(argv.data(), argv.data() + argv.size());110111// We need to get the quoting style for response files before parsing all112// options so we parse here before and ignore all the options but113// --rsp-quoting.114opt::InputArgList args = this->ParseArgs(vec, missingIndex, missingCount);115116// Expand response files (arguments in the form of @<filename>)117// and then parse the argument again.118cl::ExpandResponseFiles(saver(), getQuotingStyle(args), vec);119concatLTOPluginOptions(vec);120args = this->ParseArgs(vec, missingIndex, missingCount);121122handleColorDiagnostics(args);123if (missingCount)124error(Twine(args.getArgString(missingIndex)) + ": missing argument");125126for (opt::Arg *arg : args.filtered(OPT_UNKNOWN)) {127std::string nearest;128if (findNearest(arg->getAsString(args), nearest) > 1)129error("unknown argument '" + arg->getAsString(args) + "'");130else131error("unknown argument '" + arg->getAsString(args) +132"', did you mean '" + nearest + "'");133}134return args;135}136137void elf::printHelp() {138ELFOptTable().printHelp(139lld::outs(), (config->progName + " [options] file...").str().c_str(),140"lld", false /*ShowHidden*/, true /*ShowAllAliases*/);141lld::outs() << "\n";142143// Scripts generated by Libtool versions up to 2021-10 expect /: supported144// targets:.* elf/ in a message for the --help option. If it doesn't match,145// the scripts assume that the linker doesn't support very basic features146// such as shared libraries. Therefore, we need to print out at least "elf".147lld::outs() << config->progName << ": supported targets: elf\n";148}149150static std::string rewritePath(StringRef s) {151if (fs::exists(s))152return relativeToRoot(s);153return std::string(s);154}155156// Reconstructs command line arguments so that so that you can re-run157// the same command with the same inputs. This is for --reproduce.158std::string elf::createResponseFile(const opt::InputArgList &args) {159SmallString<0> data;160raw_svector_ostream os(data);161os << "--chroot .\n";162163// Copy the command line to the output while rewriting paths.164for (auto *arg : args) {165switch (arg->getOption().getID()) {166case OPT_reproduce:167break;168case OPT_INPUT:169os << quote(rewritePath(arg->getValue())) << "\n";170break;171case OPT_o:172case OPT_Map:173case OPT_print_archive_stats:174case OPT_why_extract:175// If an output path contains directories, "lld @response.txt" will176// likely fail because the archive we are creating doesn't contain empty177// directories for the output path (-o doesn't create directories).178// Strip directories to prevent the issue.179os << arg->getSpelling();180if (arg->getOption().getRenderStyle() == opt::Option::RenderSeparateStyle)181os << ' ';182os << quote(path::filename(arg->getValue())) << '\n';183break;184case OPT_lto_sample_profile:185os << arg->getSpelling() << quote(rewritePath(arg->getValue())) << "\n";186break;187case OPT_call_graph_ordering_file:188case OPT_default_script:189case OPT_dynamic_list:190case OPT_export_dynamic_symbol_list:191case OPT_just_symbols:192case OPT_library_path:193case OPT_remap_inputs_file:194case OPT_retain_symbols_file:195case OPT_rpath:196case OPT_script:197case OPT_symbol_ordering_file:198case OPT_sysroot:199case OPT_version_script:200os << arg->getSpelling() << " " << quote(rewritePath(arg->getValue()))201<< "\n";202break;203default:204os << toString(*arg) << "\n";205}206}207return std::string(data);208}209210// Find a file by concatenating given paths. If a resulting path211// starts with "=", the character is replaced with a --sysroot value.212static std::optional<std::string> findFile(StringRef path1,213const Twine &path2) {214SmallString<128> s;215if (path1.starts_with("="))216path::append(s, config->sysroot, path1.substr(1), path2);217else218path::append(s, path1, path2);219220if (fs::exists(s))221return std::string(s);222return std::nullopt;223}224225std::optional<std::string> elf::findFromSearchPaths(StringRef path) {226for (StringRef dir : config->searchPaths)227if (std::optional<std::string> s = findFile(dir, path))228return s;229return std::nullopt;230}231232// This is for -l<basename>. We'll look for lib<basename>.so or lib<basename>.a from233// search paths.234std::optional<std::string> elf::searchLibraryBaseName(StringRef name) {235for (StringRef dir : config->searchPaths) {236if (!config->isStatic)237if (std::optional<std::string> s = findFile(dir, "lib" + name + ".so"))238return s;239if (std::optional<std::string> s = findFile(dir, "lib" + name + ".a"))240return s;241}242return std::nullopt;243}244245// This is for -l<namespec>.246std::optional<std::string> elf::searchLibrary(StringRef name) {247llvm::TimeTraceScope timeScope("Locate library", name);248if (name.starts_with(":"))249return findFromSearchPaths(name.substr(1));250return searchLibraryBaseName(name);251}252253// If a linker/version script doesn't exist in the current directory, we also254// look for the script in the '-L' search paths. This matches the behaviour of255// '-T', --version-script=, and linker script INPUT() command in ld.bfd.256std::optional<std::string> elf::searchScript(StringRef name) {257if (fs::exists(name))258return name.str();259return findFromSearchPaths(name);260}261262263