1 //===- DriverUtils.cpp ----------------------------------------------------===//
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file contains utility functions for the driver. Because there
11 // are so many small functions, we created this separate file to make
12 // Driver.cpp less cluttered.
14 //===----------------------------------------------------------------------===//
17 #include "lld/Common/ErrorHandler.h"
18 #include "lld/Common/Memory.h"
19 #include "lld/Common/Reproduce.h"
20 #include "lld/Common/Version.h"
21 #include "llvm/ADT/Optional.h"
22 #include "llvm/ADT/STLExtras.h"
23 #include "llvm/ADT/Triple.h"
24 #include "llvm/Option/Option.h"
25 #include "llvm/Support/CommandLine.h"
26 #include "llvm/Support/FileSystem.h"
27 #include "llvm/Support/Path.h"
28 #include "llvm/Support/Process.h"
31 using namespace llvm::sys;
32 using namespace llvm::opt;
35 using namespace lld::elf;
39 // Create prefix string literals used in Options.td
40 #define PREFIX(NAME, VALUE) const char *const NAME[] = VALUE;
41 #include "ELF/Options.inc"
44 // Create table mapping all options defined in Options.td
45 static const 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 "ELF/Options.inc"
53 ELFOptTable::ELFOptTable() : OptTable(OptInfo) {}
55 // Set color diagnostics according to -color-diagnostics={auto,always,never}
56 // or -no-color-diagnostics flags.
57 static void handleColorDiagnostics(opt::InputArgList &Args) {
58 auto *Arg = Args.getLastArg(OPT_color_diagnostics, OPT_color_diagnostics_eq,
59 OPT_no_color_diagnostics);
62 if (Arg->getOption().getID() == OPT_color_diagnostics) {
63 errorHandler().ColorDiagnostics = true;
64 } else if (Arg->getOption().getID() == OPT_no_color_diagnostics) {
65 errorHandler().ColorDiagnostics = false;
67 StringRef S = Arg->getValue();
69 errorHandler().ColorDiagnostics = true;
70 else if (S == "never")
71 errorHandler().ColorDiagnostics = false;
73 error("unknown option: --color-diagnostics=" + S);
77 static cl::TokenizerCallback getQuotingStyle(opt::InputArgList &Args) {
78 if (auto *Arg = Args.getLastArg(OPT_rsp_quoting)) {
79 StringRef S = Arg->getValue();
80 if (S != "windows" && S != "posix")
81 error("invalid response file quoting: " + S);
83 return cl::TokenizeWindowsCommandLine;
84 return cl::TokenizeGNUCommandLine;
86 if (Triple(sys::getProcessTriple()).getOS() == Triple::Win32)
87 return cl::TokenizeWindowsCommandLine;
88 return cl::TokenizeGNUCommandLine;
91 // Gold LTO plugin takes a `--plugin-opt foo=bar` option as an alias for
92 // `--plugin-opt=foo=bar`. We want to handle `--plugin-opt=foo=` as an
93 // option name and `bar` as a value. Unfortunately, OptParser cannot
94 // handle an option with a space in it.
96 // In this function, we concatenate command line arguments so that
97 // `--plugin-opt <foo>` is converted to `--plugin-opt=<foo>`. This is a
98 // bit hacky, but looks like it is still better than handling --plugin-opt
100 static void concatLTOPluginOptions(SmallVectorImpl<const char *> &Args) {
101 SmallVector<const char *, 256> V;
102 for (size_t I = 0, E = Args.size(); I != E; ++I) {
103 StringRef S = Args[I];
104 if ((S == "-plugin-opt" || S == "--plugin-opt") && I + 1 != E) {
105 V.push_back(Saver.save(S + "=" + Args[I + 1]).data());
108 V.push_back(Args[I]);
114 // Parses a given list of options.
115 opt::InputArgList ELFOptTable::parse(ArrayRef<const char *> Argv) {
116 // Make InputArgList from string vectors.
117 unsigned MissingIndex;
118 unsigned MissingCount;
119 SmallVector<const char *, 256> Vec(Argv.data(), Argv.data() + Argv.size());
121 // We need to get the quoting style for response files before parsing all
122 // options so we parse here before and ignore all the options but
124 opt::InputArgList Args = this->ParseArgs(Vec, MissingIndex, MissingCount);
126 // Expand response files (arguments in the form of @<filename>)
127 // and then parse the argument again.
128 cl::ExpandResponseFiles(Saver, getQuotingStyle(Args), Vec);
129 concatLTOPluginOptions(Vec);
130 Args = this->ParseArgs(Vec, MissingIndex, MissingCount);
132 handleColorDiagnostics(Args);
134 error(Twine(Args.getArgString(MissingIndex)) + ": missing argument");
136 for (auto *Arg : Args.filtered(OPT_UNKNOWN))
137 error("unknown argument: " + Arg->getSpelling());
141 void elf::printHelp() {
142 ELFOptTable().PrintHelp(outs(), Config->ProgName.data(), "lld",
143 false /*ShowHidden*/, true /*ShowAllAliases*/);
146 // Scripts generated by Libtool versions up to at least 2.4.6 (the most
147 // recent version as of March 2017) expect /: supported targets:.* elf/
148 // in a message for the -help option. If it doesn't match, the scripts
149 // assume that the linker doesn't support very basic features such as
150 // shared libraries. Therefore, we need to print out at least "elf".
151 outs() << Config->ProgName << ": supported targets: elf\n";
154 // Reconstructs command line arguments so that so that you can re-run
155 // the same command with the same inputs. This is for --reproduce.
156 std::string elf::createResponseFile(const opt::InputArgList &Args) {
158 raw_svector_ostream OS(Data);
159 OS << "--chroot .\n";
161 // Copy the command line to the output while rewriting paths.
162 for (auto *Arg : Args) {
163 switch (Arg->getOption().getUnaliasedOption().getID()) {
167 OS << quote(rewritePath(Arg->getValue())) << "\n";
170 // If -o path contains directories, "lld @response.txt" will likely
171 // fail because the archive we are creating doesn't contain empty
172 // directories for the output path (-o doesn't create directories).
173 // Strip directories to prevent the issue.
174 OS << "-o " << quote(sys::path::filename(Arg->getValue())) << "\n";
176 case OPT_dynamic_list:
177 case OPT_library_path:
180 case OPT_symbol_ordering_file:
182 case OPT_version_script:
183 OS << Arg->getSpelling() << " " << quote(rewritePath(Arg->getValue()))
187 OS << toString(*Arg) << "\n";
193 // Find a file by concatenating given paths. If a resulting path
194 // starts with "=", the character is replaced with a --sysroot value.
195 static Optional<std::string> findFile(StringRef Path1, const Twine &Path2) {
197 if (Path1.startswith("="))
198 path::append(S, Config->Sysroot, Path1.substr(1), Path2);
200 path::append(S, Path1, Path2);
203 return S.str().str();
207 Optional<std::string> elf::findFromSearchPaths(StringRef Path) {
208 for (StringRef Dir : Config->SearchPaths)
209 if (Optional<std::string> S = findFile(Dir, Path))
214 // This is for -lfoo. We'll look for libfoo.so or libfoo.a from
216 Optional<std::string> elf::searchLibrary(StringRef Name) {
217 if (Name.startswith(":"))
218 return findFromSearchPaths(Name.substr(1));
220 for (StringRef Dir : Config->SearchPaths) {
222 if (Optional<std::string> S = findFile(Dir, "lib" + Name + ".so"))
224 if (Optional<std::string> S = findFile(Dir, "lib" + Name + ".a"))
230 // If a linker/version script doesn't exist in the current directory, we also
231 // look for the script in the '-L' search paths. This matches the behaviour of
232 // '-T', --version-script=, and linker script INPUT() command in ld.bfd.
233 Optional<std::string> elf::searchScript(StringRef Name) {
234 if (fs::exists(Name))
236 return findFromSearchPaths(Name);