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 "lld/Config/Version.h"
19 #include "lld/Core/Reproduce.h"
20 #include "llvm/ADT/STLExtras.h"
21 #include "llvm/ADT/Triple.h"
22 #include "llvm/Option/Option.h"
23 #include "llvm/Support/CommandLine.h"
24 #include "llvm/Support/FileSystem.h"
25 #include "llvm/Support/Path.h"
26 #include "llvm/Support/StringSaver.h"
27 
28 using namespace llvm;
29 using namespace llvm::sys;
30 
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, X6, X7, X8, X9, X10)            \
44   {                                                                            \
45     X1, X2, X9, X10, OPT_##ID, opt::Option::KIND##Class, X8, X7, OPT_##GROUP,  \
46         OPT_##ALIAS, X6                                                        \
47   },
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   StringSaver Saver(Alloc);
82   cl::ExpandResponseFiles(Saver, getQuotingStyle(Args), Vec);
83 
84   // Parse options and then do error checking.
85   Args = this->ParseArgs(Vec, MissingIndex, MissingCount);
86   if (MissingCount)
87     error(Twine("missing arg value for \"") + Args.getArgString(MissingIndex) +
88           "\", expected " + Twine(MissingCount) +
89           (MissingCount == 1 ? " argument.\n" : " arguments"));
90 
91   for (auto *Arg : Args.filtered(OPT_UNKNOWN))
92     error("unknown argument: " + Arg->getSpelling());
93   return Args;
94 }
95 
96 void elf::printHelp(const char *Argv0) {
97   ELFOptTable Table;
98   Table.PrintHelp(outs(), Argv0, "lld", false);
99 }
100 
101 std::string elf::getVersionString() {
102   std::string Version = getLLDVersion();
103   std::string Repo = getLLDRepositoryVersion();
104   if (Repo.empty())
105     return "LLD " + Version + "\n";
106   return "LLD " + Version + " " + Repo + "\n";
107 }
108 
109 // Reconstructs command line arguments so that so that you can re-run
110 // the same command with the same inputs. This is for --reproduce.
111 std::string elf::createResponseFile(const opt::InputArgList &Args) {
112   SmallString<0> Data;
113   raw_svector_ostream OS(Data);
114 
115   // Copy the command line to the output while rewriting paths.
116   for (auto *Arg : Args) {
117     switch (Arg->getOption().getID()) {
118     case OPT_reproduce:
119       break;
120     case OPT_INPUT:
121       OS << quote(rewritePath(Arg->getValue())) << "\n";
122       break;
123     case OPT_L:
124     case OPT_dynamic_list:
125     case OPT_rpath:
126     case OPT_alias_script_T:
127     case OPT_script:
128     case OPT_version_script:
129       OS << Arg->getSpelling() << " " << quote(rewritePath(Arg->getValue()))
130          << "\n";
131       break;
132     default:
133       OS << stringize(Arg) << "\n";
134     }
135   }
136   return Data.str();
137 }
138 
139 std::string elf::findFromSearchPaths(StringRef Path) {
140   for (StringRef Dir : Config->SearchPaths) {
141     std::string FullPath = buildSysrootedPath(Dir, Path);
142     if (fs::exists(FullPath))
143       return FullPath;
144   }
145   return "";
146 }
147 
148 // Searches a given library from input search paths, which are filled
149 // from -L command line switches. Returns a path to an existent library file.
150 std::string elf::searchLibrary(StringRef Path) {
151   if (Path.startswith(":"))
152     return findFromSearchPaths(Path.substr(1));
153   for (StringRef Dir : Config->SearchPaths) {
154     if (!Config->Static) {
155       std::string S = buildSysrootedPath(Dir, ("lib" + Path + ".so").str());
156       if (fs::exists(S))
157         return S;
158     }
159     std::string S = buildSysrootedPath(Dir, ("lib" + Path + ".a").str());
160     if (fs::exists(S))
161       return S;
162   }
163   return "";
164 }
165 
166 // Makes a path by concatenating Dir and File.
167 // If Dir starts with '=' the result will be preceded by Sysroot,
168 // which can be set with --sysroot command line switch.
169 std::string elf::buildSysrootedPath(StringRef Dir, StringRef File) {
170   SmallString<128> Path;
171   if (Dir.startswith("="))
172     path::append(Path, Config->Sysroot, Dir.substr(1), File);
173   else
174     path::append(Path, Dir, File);
175   return Path.str();
176 }
177