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