]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/lld/ELF/DriverUtils.cpp
Merge lld trunk r300422 and resolve conflicts.
[FreeBSD/FreeBSD.git] / contrib / llvm / tools / lld / ELF / DriverUtils.cpp
1 //===- DriverUtils.cpp ----------------------------------------------------===//
2 //
3 //                             The LLVM Linker
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
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.
13 //
14 //===----------------------------------------------------------------------===//
15
16 #include "Driver.h"
17 #include "Error.h"
18 #include "Memory.h"
19 #include "lld/Config/Version.h"
20 #include "lld/Core/Reproduce.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"
29
30 using namespace llvm;
31 using namespace llvm::sys;
32
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 "ELF/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, X6, X7, X8, X9, X10)            \
46   {X1, X2, X9,          X10,         OPT_##ID, opt::Option::KIND##Class,       \
47    X8, X7, OPT_##GROUP, OPT_##ALIAS, X6},
48 #include "ELF/Options.inc"
49 #undef OPTION
50 };
51
52 ELFOptTable::ELFOptTable() : OptTable(OptInfo) {}
53
54 // Parse -color-diagnostics={auto,always,never} or -no-color-diagnostics.
55 static bool getColorDiagnostics(opt::InputArgList &Args) {
56   auto *Arg = Args.getLastArg(OPT_color_diagnostics, OPT_color_diagnostics_eq,
57                               OPT_no_color_diagnostics);
58   if (!Arg)
59     return ErrorOS->has_colors();
60   if (Arg->getOption().getID() == OPT_color_diagnostics)
61     return true;
62   if (Arg->getOption().getID() == OPT_no_color_diagnostics)
63     return false;
64
65   StringRef S = Arg->getValue();
66   if (S == "auto")
67     return ErrorOS->has_colors();
68   if (S == "always")
69     return true;
70   if (S != "never")
71     error("unknown option: -color-diagnostics=" + S);
72   return false;
73 }
74
75 static cl::TokenizerCallback getQuotingStyle(opt::InputArgList &Args) {
76   if (auto *Arg = Args.getLastArg(OPT_rsp_quoting)) {
77     StringRef S = Arg->getValue();
78     if (S != "windows" && S != "posix")
79       error("invalid response file quoting: " + S);
80     if (S == "windows")
81       return cl::TokenizeWindowsCommandLine;
82     return cl::TokenizeGNUCommandLine;
83   }
84   if (Triple(sys::getProcessTriple()).getOS() == Triple::Win32)
85     return cl::TokenizeWindowsCommandLine;
86   return cl::TokenizeGNUCommandLine;
87 }
88
89 // Parses a given list of options.
90 opt::InputArgList ELFOptTable::parse(ArrayRef<const char *> Argv) {
91   // Make InputArgList from string vectors.
92   unsigned MissingIndex;
93   unsigned MissingCount;
94   SmallVector<const char *, 256> Vec(Argv.data(), Argv.data() + Argv.size());
95
96   // We need to get the quoting style for response files before parsing all
97   // options so we parse here before and ignore all the options but
98   // --rsp-quoting.
99   opt::InputArgList Args = this->ParseArgs(Vec, MissingIndex, MissingCount);
100
101   // Expand response files (arguments in the form of @<filename>)
102   // and then parse the argument again.
103   cl::ExpandResponseFiles(Saver, getQuotingStyle(Args), Vec);
104   Args = this->ParseArgs(Vec, MissingIndex, MissingCount);
105
106   // Interpret -color-diagnostics early so that error messages
107   // for unknown flags are colored.
108   Config->ColorDiagnostics = getColorDiagnostics(Args);
109   if (MissingCount)
110     error(Twine(Args.getArgString(MissingIndex)) + ": missing argument");
111
112   for (auto *Arg : Args.filtered(OPT_UNKNOWN))
113     error("unknown argument: " + Arg->getSpelling());
114   return Args;
115 }
116
117 void elf::printHelp(const char *Argv0) {
118   ELFOptTable Table;
119   Table.PrintHelp(outs(), Argv0, "lld", false);
120   outs() << "\n";
121
122   // Scripts generated by Libtool versions up to at least 2.4.6 (the most
123   // recent version as of March 2017) expect /: supported targets:.* elf/
124   // in a message for the -help option. If it doesn't match, the scripts
125   // assume that the linker doesn't support very basic features such as
126   // shared libraries. Therefore, we need to print out at least "elf".
127   // Here, we print out all the targets that we support.
128   outs() << Argv0 << ": supported targets: "
129          << "elf32-i386 elf32-iamcu elf32-littlearm elf32-ntradbigmips "
130          << "elf32-ntradlittlemips elf32-powerpc elf32-tradbigmips "
131          << "elf32-tradlittlemips elf32-x86-64 "
132          << "elf64-amdgpu elf64-littleaarch64 elf64-powerpc elf64-tradbigmips "
133          << "elf64-tradlittlemips elf64-x86-64\n";
134 }
135
136 // Reconstructs command line arguments so that so that you can re-run
137 // the same command with the same inputs. This is for --reproduce.
138 std::string elf::createResponseFile(const opt::InputArgList &Args) {
139   SmallString<0> Data;
140   raw_svector_ostream OS(Data);
141
142   // Copy the command line to the output while rewriting paths.
143   for (auto *Arg : Args) {
144     switch (Arg->getOption().getID()) {
145     case OPT_reproduce:
146       break;
147     case OPT_INPUT:
148       OS << quote(rewritePath(Arg->getValue())) << "\n";
149       break;
150     case OPT_o:
151       // If -o path contains directories, "lld @response.txt" will likely
152       // fail because the archive we are creating doesn't contain empty
153       // directories for the output path (-o doesn't create directories).
154       // Strip directories to prevent the issue.
155       OS << "-o " << quote(sys::path::filename(Arg->getValue())) << "\n";
156       break;
157     case OPT_L:
158     case OPT_dynamic_list:
159     case OPT_rpath:
160     case OPT_alias_script_T:
161     case OPT_script:
162     case OPT_version_script:
163       OS << Arg->getSpelling() << " " << quote(rewritePath(Arg->getValue()))
164          << "\n";
165       break;
166     default:
167       OS << toString(Arg) << "\n";
168     }
169   }
170   return Data.str();
171 }
172
173 // Find a file by concatenating given paths. If a resulting path
174 // starts with "=", the character is replaced with a --sysroot value.
175 static Optional<std::string> findFile(StringRef Path1, const Twine &Path2) {
176   SmallString<128> S;
177   if (Path1.startswith("="))
178     path::append(S, Config->Sysroot, Path1.substr(1), Path2);
179   else
180     path::append(S, Path1, Path2);
181
182   if (fs::exists(S))
183     return S.str().str();
184   return None;
185 }
186
187 Optional<std::string> elf::findFromSearchPaths(StringRef Path) {
188   for (StringRef Dir : Config->SearchPaths)
189     if (Optional<std::string> S = findFile(Dir, Path))
190       return S;
191   return None;
192 }
193
194 // This is for -lfoo. We'll look for libfoo.so or libfoo.a from
195 // search paths.
196 Optional<std::string> elf::searchLibrary(StringRef Name) {
197   if (Name.startswith(":"))
198     return findFromSearchPaths(Name.substr(1));
199
200   for (StringRef Dir : Config->SearchPaths) {
201     if (!Config->Static)
202       if (Optional<std::string> S = findFile(Dir, "lib" + Name + ".so"))
203         return S;
204     if (Optional<std::string> S = findFile(Dir, "lib" + Name + ".a"))
205       return S;
206   }
207   return None;
208 }