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 "ScriptParser.h"
20 #include "lld/Config/Version.h"
21 #include "lld/Core/Reproduce.h"
22 #include "llvm/ADT/Optional.h"
23 #include "llvm/ADT/STLExtras.h"
24 #include "llvm/ADT/Triple.h"
25 #include "llvm/Option/Option.h"
26 #include "llvm/Support/CommandLine.h"
27 #include "llvm/Support/FileSystem.h"
28 #include "llvm/Support/Path.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 "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 "Options.inc"
49 #undef OPTION
50 };
51 
52 ELFOptTable::ELFOptTable() : OptTable(OptInfo) {}
53 
54 static cl::TokenizerCallback getQuotingStyle(opt::InputArgList &Args) {
55   if (auto *Arg = Args.getLastArg(OPT_rsp_quoting)) {
56     StringRef S = Arg->getValue();
57     if (S != "windows" && S != "posix")
58       error("invalid response file quoting: " + S);
59     if (S == "windows")
60       return cl::TokenizeWindowsCommandLine;
61     return cl::TokenizeGNUCommandLine;
62   }
63   if (Triple(sys::getProcessTriple()).getOS() == Triple::Win32)
64     return cl::TokenizeWindowsCommandLine;
65   return cl::TokenizeGNUCommandLine;
66 }
67 
68 // Parses a given list of options.
69 opt::InputArgList ELFOptTable::parse(ArrayRef<const char *> Argv) {
70   // Make InputArgList from string vectors.
71   unsigned MissingIndex;
72   unsigned MissingCount;
73   SmallVector<const char *, 256> Vec(Argv.data(), Argv.data() + Argv.size());
74 
75   // We need to get the quoting style for response files before parsing all
76   // options so we parse here before and ignore all the options but
77   // --rsp-quoting.
78   opt::InputArgList Args = this->ParseArgs(Vec, MissingIndex, MissingCount);
79 
80   // Expand response files. '@<filename>' is replaced by the file's contents.
81   cl::ExpandResponseFiles(Saver, getQuotingStyle(Args), Vec);
82 
83   // Parse options and then do error checking.
84   Args = this->ParseArgs(Vec, MissingIndex, MissingCount);
85   if (MissingCount)
86     error(Twine(Args.getArgString(MissingIndex)) + ": missing argument");
87 
88   for (auto *Arg : Args.filtered(OPT_UNKNOWN))
89     error("unknown argument: " + Arg->getSpelling());
90   return Args;
91 }
92 
93 // Parse the --dynamic-list argument.  A dynamic list is in the form
94 //
95 //  { symbol1; symbol2; [...]; symbolN };
96 //
97 // Multiple groups can be defined in the same file, and they are merged
98 // into a single group.
99 void elf::parseDynamicList(MemoryBufferRef MB) {
100   class Parser : public ScriptParserBase {
101   public:
102     Parser(MemoryBufferRef MB) : ScriptParserBase(MB) {}
103 
104     void run() {
105       while (!atEOF()) {
106         expect("{");
107         while (!Error && !consume("}")) {
108           Config->DynamicList.push_back(unquote(next()));
109           expect(";");
110         }
111         expect(";");
112       }
113     }
114   };
115 
116   Parser(MB).run();
117 }
118 
119 void elf::printHelp(const char *Argv0) {
120   ELFOptTable Table;
121   Table.PrintHelp(outs(), Argv0, "lld", false);
122 }
123 
124 // Reconstructs command line arguments so that so that you can re-run
125 // the same command with the same inputs. This is for --reproduce.
126 std::string elf::createResponseFile(const opt::InputArgList &Args) {
127   SmallString<0> Data;
128   raw_svector_ostream OS(Data);
129 
130   // Copy the command line to the output while rewriting paths.
131   for (auto *Arg : Args) {
132     switch (Arg->getOption().getID()) {
133     case OPT_reproduce:
134       break;
135     case OPT_INPUT:
136       OS << quote(rewritePath(Arg->getValue())) << "\n";
137       break;
138     case OPT_L:
139     case OPT_dynamic_list:
140     case OPT_rpath:
141     case OPT_alias_script_T:
142     case OPT_script:
143     case OPT_version_script:
144       OS << Arg->getSpelling() << " " << quote(rewritePath(Arg->getValue()))
145          << "\n";
146       break;
147     default:
148       OS << stringize(Arg) << "\n";
149     }
150   }
151   return Data.str();
152 }
153 
154 // Find a file by concatenating given paths. If a resulting path
155 // starts with "=", the character is replaced with a --sysroot value.
156 static Optional<std::string> findFile(StringRef Path1, const Twine &Path2) {
157   SmallString<128> S;
158   if (Path1.startswith("="))
159     path::append(S, Config->Sysroot, Path1.substr(1), Path2);
160   else
161     path::append(S, Path1, Path2);
162 
163   if (fs::exists(S))
164     return S.str().str();
165   return None;
166 }
167 
168 Optional<std::string> elf::findFromSearchPaths(StringRef Path) {
169   for (StringRef Dir : Config->SearchPaths)
170     if (Optional<std::string> S = findFile(Dir, Path))
171       return S;
172   return None;
173 }
174 
175 // This is for -lfoo. We'll look for libfoo.so or libfoo.a from
176 // search paths.
177 Optional<std::string> elf::searchLibrary(StringRef Name) {
178   if (Name.startswith(":"))
179     return findFromSearchPaths(Name.substr(1));
180 
181   for (StringRef Dir : Config->SearchPaths) {
182     if (!Config->Static)
183       if (Optional<std::string> S = findFile(Dir, "lib" + Name + ".so"))
184         return S;
185     if (Optional<std::string> S = findFile(Dir, "lib" + Name + ".a"))
186       return S;
187   }
188   return None;
189 }
190