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