xref: /freebsd/contrib/llvm-project/lld/ELF/DriverUtils.cpp (revision 0fca6ea1d4eea4c934cfff25ac9ee8ad6fe95583)
10b57cec5SDimitry Andric //===- DriverUtils.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 //
9bdd1243dSDimitry Andric // This file contains utility functions for the ctx.driver. Because there
100b57cec5SDimitry Andric // are so many small functions, we created this separate file to make
110b57cec5SDimitry Andric // Driver.cpp less cluttered.
120b57cec5SDimitry Andric //
130b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
140b57cec5SDimitry Andric 
1581ad6265SDimitry Andric #include "Config.h"
160b57cec5SDimitry Andric #include "Driver.h"
1704eeddc0SDimitry Andric #include "lld/Common/CommonLinkerContext.h"
180b57cec5SDimitry Andric #include "lld/Common/Reproduce.h"
190b57cec5SDimitry Andric #include "llvm/Option/Option.h"
200b57cec5SDimitry Andric #include "llvm/Support/CommandLine.h"
210b57cec5SDimitry Andric #include "llvm/Support/FileSystem.h"
220b57cec5SDimitry Andric #include "llvm/Support/Path.h"
23e8d8bef9SDimitry Andric #include "llvm/Support/TimeProfiler.h"
2406c3fb27SDimitry Andric #include "llvm/TargetParser/Host.h"
2506c3fb27SDimitry Andric #include "llvm/TargetParser/Triple.h"
26bdd1243dSDimitry Andric #include <optional>
270b57cec5SDimitry Andric 
280b57cec5SDimitry Andric using namespace llvm;
290b57cec5SDimitry Andric using namespace llvm::sys;
300b57cec5SDimitry Andric using namespace llvm::opt;
315ffd83dbSDimitry Andric using namespace lld;
325ffd83dbSDimitry Andric using namespace lld::elf;
330b57cec5SDimitry Andric 
340b57cec5SDimitry Andric // Create OptTable
350b57cec5SDimitry Andric 
360b57cec5SDimitry Andric // Create prefix string literals used in Options.td
37bdd1243dSDimitry Andric #define PREFIX(NAME, VALUE)                                                    \
38bdd1243dSDimitry Andric   static constexpr StringLiteral NAME##_init[] = VALUE;                        \
39bdd1243dSDimitry Andric   static constexpr ArrayRef<StringLiteral> NAME(NAME##_init,                   \
40bdd1243dSDimitry Andric                                                 std::size(NAME##_init) - 1);
410b57cec5SDimitry Andric #include "Options.inc"
420b57cec5SDimitry Andric #undef PREFIX
430b57cec5SDimitry Andric 
440b57cec5SDimitry Andric // Create table mapping all options defined in Options.td
45bdd1243dSDimitry Andric static constexpr opt::OptTable::Info optInfo[] = {
465f757f3fSDimitry Andric #define OPTION(...) LLVM_CONSTRUCT_OPT_INFO(__VA_ARGS__),
470b57cec5SDimitry Andric #include "Options.inc"
480b57cec5SDimitry Andric #undef OPTION
490b57cec5SDimitry Andric };
500b57cec5SDimitry Andric 
ELFOptTable()51bdd1243dSDimitry Andric ELFOptTable::ELFOptTable() : GenericOptTable(optInfo) {}
520b57cec5SDimitry Andric 
53349cc55cSDimitry Andric // Set color diagnostics according to --color-diagnostics={auto,always,never}
54349cc55cSDimitry Andric // or --no-color-diagnostics flags.
handleColorDiagnostics(opt::InputArgList & args)550b57cec5SDimitry Andric static void handleColorDiagnostics(opt::InputArgList &args) {
56972a253aSDimitry Andric   auto *arg = args.getLastArg(OPT_color_diagnostics);
570b57cec5SDimitry Andric   if (!arg)
580b57cec5SDimitry Andric     return;
590b57cec5SDimitry Andric   StringRef s = arg->getValue();
600b57cec5SDimitry Andric   if (s == "always")
61480093f4SDimitry Andric     lld::errs().enable_colors(true);
620b57cec5SDimitry Andric   else if (s == "never")
63480093f4SDimitry Andric     lld::errs().enable_colors(false);
640b57cec5SDimitry Andric   else if (s != "auto")
650b57cec5SDimitry Andric     error("unknown option: --color-diagnostics=" + s);
660b57cec5SDimitry Andric }
670b57cec5SDimitry Andric 
getQuotingStyle(opt::InputArgList & args)680b57cec5SDimitry Andric static cl::TokenizerCallback getQuotingStyle(opt::InputArgList &args) {
690b57cec5SDimitry Andric   if (auto *arg = args.getLastArg(OPT_rsp_quoting)) {
700b57cec5SDimitry Andric     StringRef s = arg->getValue();
710b57cec5SDimitry Andric     if (s != "windows" && s != "posix")
720b57cec5SDimitry Andric       error("invalid response file quoting: " + s);
730b57cec5SDimitry Andric     if (s == "windows")
740b57cec5SDimitry Andric       return cl::TokenizeWindowsCommandLine;
750b57cec5SDimitry Andric     return cl::TokenizeGNUCommandLine;
760b57cec5SDimitry Andric   }
775ffd83dbSDimitry Andric   if (Triple(sys::getProcessTriple()).isOSWindows())
780b57cec5SDimitry Andric     return cl::TokenizeWindowsCommandLine;
790b57cec5SDimitry Andric   return cl::TokenizeGNUCommandLine;
800b57cec5SDimitry Andric }
810b57cec5SDimitry Andric 
820b57cec5SDimitry Andric // Gold LTO plugin takes a `--plugin-opt foo=bar` option as an alias for
830b57cec5SDimitry Andric // `--plugin-opt=foo=bar`. We want to handle `--plugin-opt=foo=` as an
840b57cec5SDimitry Andric // option name and `bar` as a value. Unfortunately, OptParser cannot
850b57cec5SDimitry Andric // handle an option with a space in it.
860b57cec5SDimitry Andric //
870b57cec5SDimitry Andric // In this function, we concatenate command line arguments so that
880b57cec5SDimitry Andric // `--plugin-opt <foo>` is converted to `--plugin-opt=<foo>`. This is a
890b57cec5SDimitry Andric // bit hacky, but looks like it is still better than handling --plugin-opt
900b57cec5SDimitry Andric // options by hand.
concatLTOPluginOptions(SmallVectorImpl<const char * > & args)910b57cec5SDimitry Andric static void concatLTOPluginOptions(SmallVectorImpl<const char *> &args) {
920b57cec5SDimitry Andric   SmallVector<const char *, 256> v;
930b57cec5SDimitry Andric   for (size_t i = 0, e = args.size(); i != e; ++i) {
940b57cec5SDimitry Andric     StringRef s = args[i];
950b57cec5SDimitry Andric     if ((s == "-plugin-opt" || s == "--plugin-opt") && i + 1 != e) {
9604eeddc0SDimitry Andric       v.push_back(saver().save(s + "=" + args[i + 1]).data());
970b57cec5SDimitry Andric       ++i;
980b57cec5SDimitry Andric     } else {
990b57cec5SDimitry Andric       v.push_back(args[i]);
1000b57cec5SDimitry Andric     }
1010b57cec5SDimitry Andric   }
1020b57cec5SDimitry Andric   args = std::move(v);
1030b57cec5SDimitry Andric }
1040b57cec5SDimitry Andric 
1050b57cec5SDimitry Andric // Parses a given list of options.
parse(ArrayRef<const char * > argv)1060b57cec5SDimitry Andric opt::InputArgList ELFOptTable::parse(ArrayRef<const char *> argv) {
1070b57cec5SDimitry Andric   // Make InputArgList from string vectors.
1080b57cec5SDimitry Andric   unsigned missingIndex;
1090b57cec5SDimitry Andric   unsigned missingCount;
1100b57cec5SDimitry Andric   SmallVector<const char *, 256> vec(argv.data(), argv.data() + argv.size());
1110b57cec5SDimitry Andric 
1120b57cec5SDimitry Andric   // We need to get the quoting style for response files before parsing all
1130b57cec5SDimitry Andric   // options so we parse here before and ignore all the options but
1140b57cec5SDimitry Andric   // --rsp-quoting.
1150b57cec5SDimitry Andric   opt::InputArgList args = this->ParseArgs(vec, missingIndex, missingCount);
1160b57cec5SDimitry Andric 
1170b57cec5SDimitry Andric   // Expand response files (arguments in the form of @<filename>)
1180b57cec5SDimitry Andric   // and then parse the argument again.
11904eeddc0SDimitry Andric   cl::ExpandResponseFiles(saver(), getQuotingStyle(args), vec);
1200b57cec5SDimitry Andric   concatLTOPluginOptions(vec);
1210b57cec5SDimitry Andric   args = this->ParseArgs(vec, missingIndex, missingCount);
1220b57cec5SDimitry Andric 
1230b57cec5SDimitry Andric   handleColorDiagnostics(args);
1240b57cec5SDimitry Andric   if (missingCount)
1250b57cec5SDimitry Andric     error(Twine(args.getArgString(missingIndex)) + ": missing argument");
1260b57cec5SDimitry Andric 
127e8d8bef9SDimitry Andric   for (opt::Arg *arg : args.filtered(OPT_UNKNOWN)) {
1280b57cec5SDimitry Andric     std::string nearest;
1290b57cec5SDimitry Andric     if (findNearest(arg->getAsString(args), nearest) > 1)
1300b57cec5SDimitry Andric       error("unknown argument '" + arg->getAsString(args) + "'");
1310b57cec5SDimitry Andric     else
1320b57cec5SDimitry Andric       error("unknown argument '" + arg->getAsString(args) +
1330b57cec5SDimitry Andric             "', did you mean '" + nearest + "'");
1340b57cec5SDimitry Andric   }
1350b57cec5SDimitry Andric   return args;
1360b57cec5SDimitry Andric }
1370b57cec5SDimitry Andric 
printHelp()1385ffd83dbSDimitry Andric void elf::printHelp() {
139fe6060f1SDimitry Andric   ELFOptTable().printHelp(
140480093f4SDimitry Andric       lld::outs(), (config->progName + " [options] file...").str().c_str(),
141480093f4SDimitry Andric       "lld", false /*ShowHidden*/, true /*ShowAllAliases*/);
142480093f4SDimitry Andric   lld::outs() << "\n";
1430b57cec5SDimitry Andric 
144349cc55cSDimitry Andric   // Scripts generated by Libtool versions up to 2021-10 expect /: supported
145349cc55cSDimitry Andric   // targets:.* elf/ in a message for the --help option. If it doesn't match,
146349cc55cSDimitry Andric   // the scripts assume that the linker doesn't support very basic features
147349cc55cSDimitry Andric   // such as shared libraries. Therefore, we need to print out at least "elf".
148480093f4SDimitry Andric   lld::outs() << config->progName << ": supported targets: elf\n";
1490b57cec5SDimitry Andric }
1500b57cec5SDimitry Andric 
rewritePath(StringRef s)1510b57cec5SDimitry Andric static std::string rewritePath(StringRef s) {
1520b57cec5SDimitry Andric   if (fs::exists(s))
1530b57cec5SDimitry Andric     return relativeToRoot(s);
1545ffd83dbSDimitry Andric   return std::string(s);
1550b57cec5SDimitry Andric }
1560b57cec5SDimitry Andric 
1570b57cec5SDimitry Andric // Reconstructs command line arguments so that so that you can re-run
1580b57cec5SDimitry Andric // the same command with the same inputs. This is for --reproduce.
createResponseFile(const opt::InputArgList & args)1595ffd83dbSDimitry Andric std::string elf::createResponseFile(const opt::InputArgList &args) {
1600b57cec5SDimitry Andric   SmallString<0> data;
1610b57cec5SDimitry Andric   raw_svector_ostream os(data);
1620b57cec5SDimitry Andric   os << "--chroot .\n";
1630b57cec5SDimitry Andric 
1640b57cec5SDimitry Andric   // Copy the command line to the output while rewriting paths.
1650b57cec5SDimitry Andric   for (auto *arg : args) {
1660b57cec5SDimitry Andric     switch (arg->getOption().getID()) {
1670b57cec5SDimitry Andric     case OPT_reproduce:
1680b57cec5SDimitry Andric       break;
1690b57cec5SDimitry Andric     case OPT_INPUT:
1700b57cec5SDimitry Andric       os << quote(rewritePath(arg->getValue())) << "\n";
1710b57cec5SDimitry Andric       break;
1720b57cec5SDimitry Andric     case OPT_o:
173bdd1243dSDimitry Andric     case OPT_Map:
174bdd1243dSDimitry Andric     case OPT_print_archive_stats:
175bdd1243dSDimitry Andric     case OPT_why_extract:
176bdd1243dSDimitry Andric       // If an output path contains directories, "lld @response.txt" will
177bdd1243dSDimitry Andric       // likely fail because the archive we are creating doesn't contain empty
1780b57cec5SDimitry Andric       // directories for the output path (-o doesn't create directories).
1790b57cec5SDimitry Andric       // Strip directories to prevent the issue.
180bdd1243dSDimitry Andric       os << arg->getSpelling();
181bdd1243dSDimitry Andric       if (arg->getOption().getRenderStyle() == opt::Option::RenderSeparateStyle)
182bdd1243dSDimitry Andric         os << ' ';
183bdd1243dSDimitry Andric       os << quote(path::filename(arg->getValue())) << '\n';
1840b57cec5SDimitry Andric       break;
185fe6060f1SDimitry Andric     case OPT_lto_sample_profile:
186fe6060f1SDimitry Andric       os << arg->getSpelling() << quote(rewritePath(arg->getValue())) << "\n";
187fe6060f1SDimitry Andric       break;
188e8d8bef9SDimitry Andric     case OPT_call_graph_ordering_file:
189*0fca6ea1SDimitry Andric     case OPT_default_script:
1900b57cec5SDimitry Andric     case OPT_dynamic_list:
191972a253aSDimitry Andric     case OPT_export_dynamic_symbol_list:
192e8d8bef9SDimitry Andric     case OPT_just_symbols:
1930b57cec5SDimitry Andric     case OPT_library_path:
19406c3fb27SDimitry Andric     case OPT_remap_inputs_file:
195e8d8bef9SDimitry Andric     case OPT_retain_symbols_file:
1960b57cec5SDimitry Andric     case OPT_rpath:
1970b57cec5SDimitry Andric     case OPT_script:
1980b57cec5SDimitry Andric     case OPT_symbol_ordering_file:
1990b57cec5SDimitry Andric     case OPT_sysroot:
2000b57cec5SDimitry Andric     case OPT_version_script:
2010b57cec5SDimitry Andric       os << arg->getSpelling() << " " << quote(rewritePath(arg->getValue()))
2020b57cec5SDimitry Andric          << "\n";
2030b57cec5SDimitry Andric       break;
2040b57cec5SDimitry Andric     default:
2050b57cec5SDimitry Andric       os << toString(*arg) << "\n";
2060b57cec5SDimitry Andric     }
2070b57cec5SDimitry Andric   }
2087a6dacacSDimitry Andric   return std::string(data);
2090b57cec5SDimitry Andric }
2100b57cec5SDimitry Andric 
2110b57cec5SDimitry Andric // Find a file by concatenating given paths. If a resulting path
2120b57cec5SDimitry Andric // starts with "=", the character is replaced with a --sysroot value.
findFile(StringRef path1,const Twine & path2)213bdd1243dSDimitry Andric static std::optional<std::string> findFile(StringRef path1,
214bdd1243dSDimitry Andric                                            const Twine &path2) {
2150b57cec5SDimitry Andric   SmallString<128> s;
21606c3fb27SDimitry Andric   if (path1.starts_with("="))
2170b57cec5SDimitry Andric     path::append(s, config->sysroot, path1.substr(1), path2);
2180b57cec5SDimitry Andric   else
2190b57cec5SDimitry Andric     path::append(s, path1, path2);
2200b57cec5SDimitry Andric 
2210b57cec5SDimitry Andric   if (fs::exists(s))
2225ffd83dbSDimitry Andric     return std::string(s);
223bdd1243dSDimitry Andric   return std::nullopt;
2240b57cec5SDimitry Andric }
2250b57cec5SDimitry Andric 
findFromSearchPaths(StringRef path)226bdd1243dSDimitry Andric std::optional<std::string> elf::findFromSearchPaths(StringRef path) {
2270b57cec5SDimitry Andric   for (StringRef dir : config->searchPaths)
228bdd1243dSDimitry Andric     if (std::optional<std::string> s = findFile(dir, path))
2290b57cec5SDimitry Andric       return s;
230bdd1243dSDimitry Andric   return std::nullopt;
2310b57cec5SDimitry Andric }
2320b57cec5SDimitry Andric 
2330b57cec5SDimitry Andric // This is for -l<basename>. We'll look for lib<basename>.so or lib<basename>.a from
2340b57cec5SDimitry Andric // search paths.
searchLibraryBaseName(StringRef name)235bdd1243dSDimitry Andric std::optional<std::string> elf::searchLibraryBaseName(StringRef name) {
2360b57cec5SDimitry Andric   for (StringRef dir : config->searchPaths) {
2370b57cec5SDimitry Andric     if (!config->isStatic)
238bdd1243dSDimitry Andric       if (std::optional<std::string> s = findFile(dir, "lib" + name + ".so"))
2390b57cec5SDimitry Andric         return s;
240bdd1243dSDimitry Andric     if (std::optional<std::string> s = findFile(dir, "lib" + name + ".a"))
2410b57cec5SDimitry Andric       return s;
2420b57cec5SDimitry Andric   }
243bdd1243dSDimitry Andric   return std::nullopt;
2440b57cec5SDimitry Andric }
2450b57cec5SDimitry Andric 
2460b57cec5SDimitry Andric // This is for -l<namespec>.
searchLibrary(StringRef name)247bdd1243dSDimitry Andric std::optional<std::string> elf::searchLibrary(StringRef name) {
248e8d8bef9SDimitry Andric   llvm::TimeTraceScope timeScope("Locate library", name);
24906c3fb27SDimitry Andric   if (name.starts_with(":"))
2500b57cec5SDimitry Andric     return findFromSearchPaths(name.substr(1));
2510b57cec5SDimitry Andric   return searchLibraryBaseName(name);
2520b57cec5SDimitry Andric }
2530b57cec5SDimitry Andric 
2540b57cec5SDimitry Andric // If a linker/version script doesn't exist in the current directory, we also
2550b57cec5SDimitry Andric // look for the script in the '-L' search paths. This matches the behaviour of
2560b57cec5SDimitry Andric // '-T', --version-script=, and linker script INPUT() command in ld.bfd.
searchScript(StringRef name)257bdd1243dSDimitry Andric std::optional<std::string> elf::searchScript(StringRef name) {
2580b57cec5SDimitry Andric   if (fs::exists(name))
2590b57cec5SDimitry Andric     return name.str();
2600b57cec5SDimitry Andric   return findFromSearchPaths(name);
2610b57cec5SDimitry Andric }
262