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