PageRenderTime 24ms CodeModel.GetById 31ms RepoModel.GetById 0ms app.codeStats 0ms

/contrib/llvm-project/lld/ELF/DriverUtils.cpp

https://github.com/freebsd/freebsd
C++ | 259 lines | 181 code | 25 blank | 53 comment | 48 complexity | 28c7dd6883b9a0f6643d53a0215497d6 MD5 | raw file
  1. //===- DriverUtils.cpp ----------------------------------------------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file contains utility functions for the driver. Because there
  10. // are so many small functions, we created this separate file to make
  11. // Driver.cpp less cluttered.
  12. //
  13. //===----------------------------------------------------------------------===//
  14. #include "Driver.h"
  15. #include "lld/Common/CommonLinkerContext.h"
  16. #include "lld/Common/Reproduce.h"
  17. #include "lld/Common/Version.h"
  18. #include "llvm/ADT/Optional.h"
  19. #include "llvm/ADT/STLExtras.h"
  20. #include "llvm/ADT/Triple.h"
  21. #include "llvm/Option/Option.h"
  22. #include "llvm/Support/CommandLine.h"
  23. #include "llvm/Support/FileSystem.h"
  24. #include "llvm/Support/Host.h"
  25. #include "llvm/Support/Path.h"
  26. #include "llvm/Support/Process.h"
  27. #include "llvm/Support/TimeProfiler.h"
  28. using namespace llvm;
  29. using namespace llvm::sys;
  30. using namespace llvm::opt;
  31. using namespace lld;
  32. using namespace lld::elf;
  33. // Create OptTable
  34. // Create prefix string literals used in Options.td
  35. #define PREFIX(NAME, VALUE) const char *const NAME[] = VALUE;
  36. #include "Options.inc"
  37. #undef PREFIX
  38. // Create table mapping all options defined in Options.td
  39. static const opt::OptTable::Info optInfo[] = {
  40. #define OPTION(X1, X2, ID, KIND, GROUP, ALIAS, X7, X8, X9, X10, X11, X12) \
  41. {X1, X2, X10, X11, OPT_##ID, opt::Option::KIND##Class, \
  42. X9, X8, OPT_##GROUP, OPT_##ALIAS, X7, X12},
  43. #include "Options.inc"
  44. #undef OPTION
  45. };
  46. ELFOptTable::ELFOptTable() : OptTable(optInfo) {}
  47. // Set color diagnostics according to --color-diagnostics={auto,always,never}
  48. // or --no-color-diagnostics flags.
  49. static void handleColorDiagnostics(opt::InputArgList &args) {
  50. auto *arg = args.getLastArg(OPT_color_diagnostics, OPT_color_diagnostics_eq,
  51. OPT_no_color_diagnostics);
  52. if (!arg)
  53. return;
  54. if (arg->getOption().getID() == OPT_color_diagnostics) {
  55. lld::errs().enable_colors(true);
  56. } else if (arg->getOption().getID() == OPT_no_color_diagnostics) {
  57. lld::errs().enable_colors(false);
  58. } else {
  59. StringRef s = arg->getValue();
  60. if (s == "always")
  61. lld::errs().enable_colors(true);
  62. else if (s == "never")
  63. lld::errs().enable_colors(false);
  64. else if (s != "auto")
  65. error("unknown option: --color-diagnostics=" + s);
  66. }
  67. }
  68. static cl::TokenizerCallback getQuotingStyle(opt::InputArgList &args) {
  69. if (auto *arg = args.getLastArg(OPT_rsp_quoting)) {
  70. StringRef s = arg->getValue();
  71. if (s != "windows" && s != "posix")
  72. error("invalid response file quoting: " + s);
  73. if (s == "windows")
  74. return cl::TokenizeWindowsCommandLine;
  75. return cl::TokenizeGNUCommandLine;
  76. }
  77. if (Triple(sys::getProcessTriple()).isOSWindows())
  78. return cl::TokenizeWindowsCommandLine;
  79. return cl::TokenizeGNUCommandLine;
  80. }
  81. // Gold LTO plugin takes a `--plugin-opt foo=bar` option as an alias for
  82. // `--plugin-opt=foo=bar`. We want to handle `--plugin-opt=foo=` as an
  83. // option name and `bar` as a value. Unfortunately, OptParser cannot
  84. // handle an option with a space in it.
  85. //
  86. // In this function, we concatenate command line arguments so that
  87. // `--plugin-opt <foo>` is converted to `--plugin-opt=<foo>`. This is a
  88. // bit hacky, but looks like it is still better than handling --plugin-opt
  89. // options by hand.
  90. static void concatLTOPluginOptions(SmallVectorImpl<const char *> &args) {
  91. SmallVector<const char *, 256> v;
  92. for (size_t i = 0, e = args.size(); i != e; ++i) {
  93. StringRef s = args[i];
  94. if ((s == "-plugin-opt" || s == "--plugin-opt") && i + 1 != e) {
  95. v.push_back(saver().save(s + "=" + args[i + 1]).data());
  96. ++i;
  97. } else {
  98. v.push_back(args[i]);
  99. }
  100. }
  101. args = std::move(v);
  102. }
  103. // Parses a given list of options.
  104. opt::InputArgList ELFOptTable::parse(ArrayRef<const char *> argv) {
  105. // Make InputArgList from string vectors.
  106. unsigned missingIndex;
  107. unsigned missingCount;
  108. SmallVector<const char *, 256> vec(argv.data(), argv.data() + argv.size());
  109. // We need to get the quoting style for response files before parsing all
  110. // options so we parse here before and ignore all the options but
  111. // --rsp-quoting.
  112. opt::InputArgList args = this->ParseArgs(vec, missingIndex, missingCount);
  113. // Expand response files (arguments in the form of @<filename>)
  114. // and then parse the argument again.
  115. cl::ExpandResponseFiles(saver(), getQuotingStyle(args), vec);
  116. concatLTOPluginOptions(vec);
  117. args = this->ParseArgs(vec, missingIndex, missingCount);
  118. handleColorDiagnostics(args);
  119. if (missingCount)
  120. error(Twine(args.getArgString(missingIndex)) + ": missing argument");
  121. for (opt::Arg *arg : args.filtered(OPT_UNKNOWN)) {
  122. std::string nearest;
  123. if (findNearest(arg->getAsString(args), nearest) > 1)
  124. error("unknown argument '" + arg->getAsString(args) + "'");
  125. else
  126. error("unknown argument '" + arg->getAsString(args) +
  127. "', did you mean '" + nearest + "'");
  128. }
  129. return args;
  130. }
  131. void elf::printHelp() {
  132. ELFOptTable().printHelp(
  133. lld::outs(), (config->progName + " [options] file...").str().c_str(),
  134. "lld", false /*ShowHidden*/, true /*ShowAllAliases*/);
  135. lld::outs() << "\n";
  136. // Scripts generated by Libtool versions up to 2021-10 expect /: supported
  137. // targets:.* elf/ in a message for the --help option. If it doesn't match,
  138. // the scripts assume that the linker doesn't support very basic features
  139. // such as shared libraries. Therefore, we need to print out at least "elf".
  140. lld::outs() << config->progName << ": supported targets: elf\n";
  141. }
  142. static std::string rewritePath(StringRef s) {
  143. if (fs::exists(s))
  144. return relativeToRoot(s);
  145. return std::string(s);
  146. }
  147. // Reconstructs command line arguments so that so that you can re-run
  148. // the same command with the same inputs. This is for --reproduce.
  149. std::string elf::createResponseFile(const opt::InputArgList &args) {
  150. SmallString<0> data;
  151. raw_svector_ostream os(data);
  152. os << "--chroot .\n";
  153. // Copy the command line to the output while rewriting paths.
  154. for (auto *arg : args) {
  155. switch (arg->getOption().getID()) {
  156. case OPT_reproduce:
  157. break;
  158. case OPT_INPUT:
  159. os << quote(rewritePath(arg->getValue())) << "\n";
  160. break;
  161. case OPT_o:
  162. // If -o path contains directories, "lld @response.txt" will likely
  163. // fail because the archive we are creating doesn't contain empty
  164. // directories for the output path (-o doesn't create directories).
  165. // Strip directories to prevent the issue.
  166. os << "-o " << quote(path::filename(arg->getValue())) << "\n";
  167. break;
  168. case OPT_lto_sample_profile:
  169. os << arg->getSpelling() << quote(rewritePath(arg->getValue())) << "\n";
  170. break;
  171. case OPT_call_graph_ordering_file:
  172. case OPT_dynamic_list:
  173. case OPT_just_symbols:
  174. case OPT_library_path:
  175. case OPT_retain_symbols_file:
  176. case OPT_rpath:
  177. case OPT_script:
  178. case OPT_symbol_ordering_file:
  179. case OPT_sysroot:
  180. case OPT_version_script:
  181. os << arg->getSpelling() << " " << quote(rewritePath(arg->getValue()))
  182. << "\n";
  183. break;
  184. default:
  185. os << toString(*arg) << "\n";
  186. }
  187. }
  188. return std::string(data.str());
  189. }
  190. // Find a file by concatenating given paths. If a resulting path
  191. // starts with "=", the character is replaced with a --sysroot value.
  192. static Optional<std::string> findFile(StringRef path1, const Twine &path2) {
  193. SmallString<128> s;
  194. if (path1.startswith("="))
  195. path::append(s, config->sysroot, path1.substr(1), path2);
  196. else
  197. path::append(s, path1, path2);
  198. if (fs::exists(s))
  199. return std::string(s);
  200. return None;
  201. }
  202. Optional<std::string> elf::findFromSearchPaths(StringRef path) {
  203. for (StringRef dir : config->searchPaths)
  204. if (Optional<std::string> s = findFile(dir, path))
  205. return s;
  206. return None;
  207. }
  208. // This is for -l<basename>. We'll look for lib<basename>.so or lib<basename>.a from
  209. // search paths.
  210. Optional<std::string> elf::searchLibraryBaseName(StringRef name) {
  211. for (StringRef dir : config->searchPaths) {
  212. if (!config->isStatic)
  213. if (Optional<std::string> s = findFile(dir, "lib" + name + ".so"))
  214. return s;
  215. if (Optional<std::string> s = findFile(dir, "lib" + name + ".a"))
  216. return s;
  217. }
  218. return None;
  219. }
  220. // This is for -l<namespec>.
  221. Optional<std::string> elf::searchLibrary(StringRef name) {
  222. llvm::TimeTraceScope timeScope("Locate library", name);
  223. if (name.startswith(":"))
  224. return findFromSearchPaths(name.substr(1));
  225. return searchLibraryBaseName(name);
  226. }
  227. // If a linker/version script doesn't exist in the current directory, we also
  228. // look for the script in the '-L' search paths. This matches the behaviour of
  229. // '-T', --version-script=, and linker script INPUT() command in ld.bfd.
  230. Optional<std::string> elf::searchScript(StringRef name) {
  231. if (fs::exists(name))
  232. return name.str();
  233. return findFromSearchPaths(name);
  234. }