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 // Reconstructs command line arguments so that so that you can re-run
102 // the same command with the same inputs. This is for --reproduce.
103 std::string elf::createResponseFile(const opt::InputArgList &Args) {
104   SmallString<0> Data;
105   raw_svector_ostream OS(Data);
106 
107   // Copy the command line to the output while rewriting paths.
108   for (auto *Arg : Args) {
109     switch (Arg->getOption().getID()) {
110     case OPT_reproduce:
111       break;
112     case OPT_INPUT:
113       OS << quote(rewritePath(Arg->getValue())) << "\n";
114       break;
115     case OPT_L:
116     case OPT_dynamic_list:
117     case OPT_rpath:
118     case OPT_alias_script_T:
119     case OPT_script:
120     case OPT_version_script:
121       OS << Arg->getSpelling() << " " << quote(rewritePath(Arg->getValue()))
122          << "\n";
123       break;
124     default:
125       OS << stringize(Arg) << "\n";
126     }
127   }
128   return Data.str();
129 }
130 
131 std::string elf::findFromSearchPaths(StringRef Path) {
132   for (StringRef Dir : Config->SearchPaths) {
133     std::string FullPath = buildSysrootedPath(Dir, Path);
134     if (fs::exists(FullPath))
135       return FullPath;
136   }
137   return "";
138 }
139 
140 // Searches a given library from input search paths, which are filled
141 // from -L command line switches. Returns a path to an existent library file.
142 std::string elf::searchLibrary(StringRef Path) {
143   if (Path.startswith(":"))
144     return findFromSearchPaths(Path.substr(1));
145   for (StringRef Dir : Config->SearchPaths) {
146     if (!Config->Static) {
147       std::string S = buildSysrootedPath(Dir, ("lib" + Path + ".so").str());
148       if (fs::exists(S))
149         return S;
150     }
151     std::string S = buildSysrootedPath(Dir, ("lib" + Path + ".a").str());
152     if (fs::exists(S))
153       return S;
154   }
155   return "";
156 }
157 
158 // Makes a path by concatenating Dir and File.
159 // If Dir starts with '=' the result will be preceded by Sysroot,
160 // which can be set with --sysroot command line switch.
161 std::string elf::buildSysrootedPath(StringRef Dir, StringRef File) {
162   SmallString<128> Path;
163   if (Dir.startswith("="))
164     path::append(Path, Config->Sysroot, Dir.substr(1), File);
165   else
166     path::append(Path, Dir, File);
167   return Path.str();
168 }
169