PageRenderTime 43ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 0ms

/contrib/llvm/tools/lld/ELF/DriverUtils.cpp

https://bitbucket.org/freebsd/freebsd-base
C++ | 253 lines | 173 code | 26 blank | 54 comment | 49 complexity | a49d221b4bc91f9b126b494d5a8d838d 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/ErrorHandler.h"
  16. #include "lld/Common/Memory.h"
  17. #include "lld/Common/Reproduce.h"
  18. #include "lld/Common/Version.h"
  19. #include "llvm/ADT/Optional.h"
  20. #include "llvm/ADT/STLExtras.h"
  21. #include "llvm/ADT/Triple.h"
  22. #include "llvm/Option/Option.h"
  23. #include "llvm/Support/CommandLine.h"
  24. #include "llvm/Support/FileSystem.h"
  25. #include "llvm/Support/Path.h"
  26. #include "llvm/Support/Process.h"
  27. using namespace llvm;
  28. using namespace llvm::sys;
  29. using namespace llvm::opt;
  30. using namespace lld;
  31. using namespace lld::elf;
  32. // Create OptTable
  33. // Create prefix string literals used in Options.td
  34. #define PREFIX(NAME, VALUE) const char *const NAME[] = VALUE;
  35. #include "Options.inc"
  36. #undef PREFIX
  37. // Create table mapping all options defined in Options.td
  38. static const opt::OptTable::Info optInfo[] = {
  39. #define OPTION(X1, X2, ID, KIND, GROUP, ALIAS, X7, X8, X9, X10, X11, X12) \
  40. {X1, X2, X10, X11, OPT_##ID, opt::Option::KIND##Class, \
  41. X9, X8, OPT_##GROUP, OPT_##ALIAS, X7, X12},
  42. #include "Options.inc"
  43. #undef OPTION
  44. };
  45. ELFOptTable::ELFOptTable() : OptTable(optInfo) {}
  46. // Set color diagnostics according to -color-diagnostics={auto,always,never}
  47. // or -no-color-diagnostics flags.
  48. static void handleColorDiagnostics(opt::InputArgList &args) {
  49. auto *arg = args.getLastArg(OPT_color_diagnostics, OPT_color_diagnostics_eq,
  50. OPT_no_color_diagnostics);
  51. if (!arg)
  52. return;
  53. if (arg->getOption().getID() == OPT_color_diagnostics) {
  54. errorHandler().colorDiagnostics = true;
  55. } else if (arg->getOption().getID() == OPT_no_color_diagnostics) {
  56. errorHandler().colorDiagnostics = false;
  57. } else {
  58. StringRef s = arg->getValue();
  59. if (s == "always")
  60. errorHandler().colorDiagnostics = true;
  61. else if (s == "never")
  62. errorHandler().colorDiagnostics = false;
  63. else if (s != "auto")
  64. error("unknown option: --color-diagnostics=" + s);
  65. }
  66. }
  67. static cl::TokenizerCallback getQuotingStyle(opt::InputArgList &args) {
  68. if (auto *arg = args.getLastArg(OPT_rsp_quoting)) {
  69. StringRef s = arg->getValue();
  70. if (s != "windows" && s != "posix")
  71. error("invalid response file quoting: " + s);
  72. if (s == "windows")
  73. return cl::TokenizeWindowsCommandLine;
  74. return cl::TokenizeGNUCommandLine;
  75. }
  76. if (Triple(sys::getProcessTriple()).getOS() == Triple::Win32)
  77. return cl::TokenizeWindowsCommandLine;
  78. return cl::TokenizeGNUCommandLine;
  79. }
  80. // Gold LTO plugin takes a `--plugin-opt foo=bar` option as an alias for
  81. // `--plugin-opt=foo=bar`. We want to handle `--plugin-opt=foo=` as an
  82. // option name and `bar` as a value. Unfortunately, OptParser cannot
  83. // handle an option with a space in it.
  84. //
  85. // In this function, we concatenate command line arguments so that
  86. // `--plugin-opt <foo>` is converted to `--plugin-opt=<foo>`. This is a
  87. // bit hacky, but looks like it is still better than handling --plugin-opt
  88. // options by hand.
  89. static void concatLTOPluginOptions(SmallVectorImpl<const char *> &args) {
  90. SmallVector<const char *, 256> v;
  91. for (size_t i = 0, e = args.size(); i != e; ++i) {
  92. StringRef s = args[i];
  93. if ((s == "-plugin-opt" || s == "--plugin-opt") && i + 1 != e) {
  94. v.push_back(saver.save(s + "=" + args[i + 1]).data());
  95. ++i;
  96. } else {
  97. v.push_back(args[i]);
  98. }
  99. }
  100. args = std::move(v);
  101. }
  102. // Parses a given list of options.
  103. opt::InputArgList ELFOptTable::parse(ArrayRef<const char *> argv) {
  104. // Make InputArgList from string vectors.
  105. unsigned missingIndex;
  106. unsigned missingCount;
  107. SmallVector<const char *, 256> vec(argv.data(), argv.data() + argv.size());
  108. // We need to get the quoting style for response files before parsing all
  109. // options so we parse here before and ignore all the options but
  110. // --rsp-quoting.
  111. opt::InputArgList args = this->ParseArgs(vec, missingIndex, missingCount);
  112. // Expand response files (arguments in the form of @<filename>)
  113. // and then parse the argument again.
  114. cl::ExpandResponseFiles(saver, getQuotingStyle(args), vec);
  115. concatLTOPluginOptions(vec);
  116. args = this->ParseArgs(vec, missingIndex, missingCount);
  117. handleColorDiagnostics(args);
  118. if (missingCount)
  119. error(Twine(args.getArgString(missingIndex)) + ": missing argument");
  120. for (auto *arg : args.filtered(OPT_UNKNOWN)) {
  121. std::string nearest;
  122. if (findNearest(arg->getAsString(args), nearest) > 1)
  123. error("unknown argument '" + arg->getAsString(args) + "'");
  124. else
  125. error("unknown argument '" + arg->getAsString(args) +
  126. "', did you mean '" + nearest + "'");
  127. }
  128. return args;
  129. }
  130. void elf::printHelp() {
  131. ELFOptTable().PrintHelp(
  132. outs(), (config->progName + " [options] file...").str().c_str(), "lld",
  133. false /*ShowHidden*/, true /*ShowAllAliases*/);
  134. outs() << "\n";
  135. // Scripts generated by Libtool versions up to at least 2.4.6 (the most
  136. // recent version as of March 2017) expect /: supported targets:.* elf/
  137. // in a message for the -help option. If it doesn't match, the scripts
  138. // assume that the linker doesn't support very basic features such as
  139. // shared libraries. Therefore, we need to print out at least "elf".
  140. 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 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(sys::path::filename(arg->getValue())) << "\n";
  167. break;
  168. case OPT_dynamic_list:
  169. case OPT_library_path:
  170. case OPT_rpath:
  171. case OPT_script:
  172. case OPT_symbol_ordering_file:
  173. case OPT_sysroot:
  174. case OPT_version_script:
  175. os << arg->getSpelling() << " " << quote(rewritePath(arg->getValue()))
  176. << "\n";
  177. break;
  178. default:
  179. os << toString(*arg) << "\n";
  180. }
  181. }
  182. return data.str();
  183. }
  184. // Find a file by concatenating given paths. If a resulting path
  185. // starts with "=", the character is replaced with a --sysroot value.
  186. static Optional<std::string> findFile(StringRef path1, const Twine &path2) {
  187. SmallString<128> s;
  188. if (path1.startswith("="))
  189. path::append(s, config->sysroot, path1.substr(1), path2);
  190. else
  191. path::append(s, path1, path2);
  192. if (fs::exists(s))
  193. return s.str().str();
  194. return None;
  195. }
  196. Optional<std::string> elf::findFromSearchPaths(StringRef path) {
  197. for (StringRef dir : config->searchPaths)
  198. if (Optional<std::string> s = findFile(dir, path))
  199. return s;
  200. return None;
  201. }
  202. // This is for -l<basename>. We'll look for lib<basename>.so or lib<basename>.a from
  203. // search paths.
  204. Optional<std::string> elf::searchLibraryBaseName(StringRef name) {
  205. for (StringRef dir : config->searchPaths) {
  206. if (!config->isStatic)
  207. if (Optional<std::string> s = findFile(dir, "lib" + name + ".so"))
  208. return s;
  209. if (Optional<std::string> s = findFile(dir, "lib" + name + ".a"))
  210. return s;
  211. }
  212. return None;
  213. }
  214. // This is for -l<namespec>.
  215. Optional<std::string> elf::searchLibrary(StringRef name) {
  216. if (name.startswith(":"))
  217. return findFromSearchPaths(name.substr(1));
  218. return searchLibraryBaseName (name);
  219. }
  220. // If a linker/version script doesn't exist in the current directory, we also
  221. // look for the script in the '-L' search paths. This matches the behaviour of
  222. // '-T', --version-script=, and linker script INPUT() command in ld.bfd.
  223. Optional<std::string> elf::searchScript(StringRef name) {
  224. if (fs::exists(name))
  225. return name.str();
  226. return findFromSearchPaths(name);
  227. }