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 //===----------------------------------------------------------------------===//
18 #include "lld/Config/Version.h"
19 #include "llvm/ADT/STLExtras.h"
20 #include "llvm/ADT/Triple.h"
21 #include "llvm/Option/Option.h"
22 #include "llvm/Support/CommandLine.h"
23 #include "llvm/Support/FileSystem.h"
24 #include "llvm/Support/Path.h"
25 #include "llvm/Support/StringSaver.h"
28 using namespace llvm::sys;
31 using namespace lld::elf;
35 // Create prefix string literals used in Options.td
36 #define PREFIX(NAME, VALUE) const char *const NAME[] = VALUE;
37 #include "ELF/Options.inc"
40 // Create table mapping all options defined in Options.td
41 static const opt::OptTable::Info OptInfo[] = {
42 #define OPTION(X1, X2, ID, KIND, GROUP, ALIAS, X6, X7, X8, X9, X10) \
44 X1, X2, X9, X10, OPT_##ID, opt::Option::KIND##Class, X8, X7, OPT_##GROUP, \
47 #include "ELF/Options.inc"
51 ELFOptTable::ELFOptTable() : OptTable(OptInfo) {}
53 static cl::TokenizerCallback getQuotingStyle(opt::InputArgList &Args) {
54 if (auto *Arg = Args.getLastArg(OPT_rsp_quoting)) {
55 StringRef S = Arg->getValue();
56 if (S != "windows" && S != "posix")
57 error("invalid response file quoting: " + S);
59 return cl::TokenizeWindowsCommandLine;
60 return cl::TokenizeGNUCommandLine;
62 if (Triple(sys::getProcessTriple()).getOS() == Triple::Win32)
63 return cl::TokenizeWindowsCommandLine;
64 return cl::TokenizeGNUCommandLine;
67 // Parses a given list of options.
68 opt::InputArgList ELFOptTable::parse(ArrayRef<const char *> Argv) {
69 // Make InputArgList from string vectors.
70 unsigned MissingIndex;
71 unsigned MissingCount;
72 SmallVector<const char *, 256> Vec(Argv.data(), Argv.data() + Argv.size());
74 // We need to get the quoting style for response files before parsing all
75 // options so we parse here before and ignore all the options but
77 opt::InputArgList Args = this->ParseArgs(Vec, MissingIndex, MissingCount);
79 // Expand response files. '@<filename>' is replaced by the file's contents.
80 StringSaver Saver(Alloc);
81 cl::ExpandResponseFiles(Saver, getQuotingStyle(Args), Vec);
83 // Parse options and then do error checking.
84 Args = this->ParseArgs(Vec, MissingIndex, MissingCount);
86 error(Twine("missing arg value for \"") + Args.getArgString(MissingIndex) +
87 "\", expected " + Twine(MissingCount) +
88 (MissingCount == 1 ? " argument.\n" : " arguments"));
90 for (auto *Arg : Args.filtered(OPT_UNKNOWN))
91 error("unknown argument: " + Arg->getSpelling());
95 void elf::printHelp(const char *Argv0) {
97 Table.PrintHelp(outs(), Argv0, "lld", false);
100 std::string elf::getVersionString() {
101 std::string Version = getLLDVersion();
102 std::string Repo = getLLDRepositoryVersion();
104 return "LLD " + Version + "\n";
105 return "LLD " + Version + " " + Repo + "\n";
108 // Makes a given pathname an absolute path first, and then remove
109 // beginning /. For example, "../foo.o" is converted to "home/john/foo.o",
110 // assuming that the current directory is "/home/john/bar".
111 std::string elf::relativeToRoot(StringRef Path) {
112 SmallString<128> Abs = Path;
113 if (std::error_code EC = fs::make_absolute(Abs))
114 fatal("make_absolute failed: " + EC.message());
115 path::remove_dots(Abs, /*remove_dot_dot=*/true);
117 // This is Windows specific. root_name() returns a drive letter
118 // (e.g. "c:") or a UNC name (//net). We want to keep it as part
120 SmallString<128> Res;
121 StringRef Root = path::root_name(Abs);
122 if (Root.endswith(":"))
123 Res = Root.drop_back();
124 else if (Root.startswith("//"))
125 Res = Root.substr(2);
127 path::append(Res, path::relative_path(Abs));
131 CpioFile::CpioFile(std::unique_ptr<raw_fd_ostream> OS, StringRef S)
132 : OS(std::move(OS)), Basename(S) {}
134 CpioFile *CpioFile::create(StringRef OutputPath) {
135 std::string Path = (OutputPath + ".cpio").str();
137 auto OS = llvm::make_unique<raw_fd_ostream>(Path, EC, fs::F_None);
139 error(EC, "--reproduce: failed to open " + Path);
142 return new CpioFile(std::move(OS), path::filename(OutputPath));
145 static void writeMember(raw_fd_ostream &OS, StringRef Path, StringRef Data) {
146 // The c_dev/c_ino pair should be unique according to the spec,
147 // but no one seems to care.
148 OS << "070707"; // c_magic
149 OS << "000000"; // c_dev
150 OS << "000000"; // c_ino
151 OS << "100664"; // c_mode: C_ISREG | rw-rw-r--
152 OS << "000000"; // c_uid
153 OS << "000000"; // c_gid
154 OS << "000001"; // c_nlink
155 OS << "000000"; // c_rdev
156 OS << "00000000000"; // c_mtime
157 OS << format("%06o", Path.size() + 1); // c_namesize
158 OS << format("%011o", Data.size()); // c_filesize
159 OS << Path << '\0'; // c_name
160 OS << Data; // c_filedata
163 void CpioFile::append(StringRef Path, StringRef Data) {
164 if (!Seen.insert(Path).second)
167 // Construct an in-archive filename so that /home/foo/bar is stored
168 // as baz/home/foo/bar where baz is the basename of the output file.
169 // (i.e. in that case we are creating baz.cpio.)
170 SmallString<128> Fullpath;
171 path::append(Fullpath, Basename, Path);
173 // Use unix path separators so the cpio can be extracted on both unix and
175 std::replace(Fullpath.begin(), Fullpath.end(), '\\', '/');
177 writeMember(*OS, Fullpath, Data);
179 // Print the trailer and seek back.
180 // This way we have a valid archive if we crash.
181 uint64_t Pos = OS->tell();
182 writeMember(*OS, "TRAILER!!!", "");
186 // Quote a given string if it contains a space character.
187 static std::string quote(StringRef S) {
188 if (S.find(' ') == StringRef::npos)
190 return ("\"" + S + "\"").str();
193 static std::string rewritePath(StringRef S) {
195 return relativeToRoot(S);
199 static std::string stringize(opt::Arg *Arg) {
200 std::string K = Arg->getSpelling();
201 if (Arg->getNumValues() == 0)
203 std::string V = quote(Arg->getValue());
204 if (Arg->getOption().getRenderStyle() == opt::Option::RenderJoinedStyle)
209 // Reconstructs command line arguments so that so that you can re-run
210 // the same command with the same inputs. This is for --reproduce.
211 std::string elf::createResponseFile(const opt::InputArgList &Args) {
213 raw_svector_ostream OS(Data);
215 // Copy the command line to the output while rewriting paths.
216 for (auto *Arg : Args) {
217 switch (Arg->getOption().getID()) {
221 OS << quote(rewritePath(Arg->getValue())) << "\n";
224 case OPT_dynamic_list:
226 case OPT_alias_script_T:
228 case OPT_version_script:
229 OS << Arg->getSpelling() << " "
230 << quote(rewritePath(Arg->getValue())) << "\n";
233 OS << stringize(Arg) << "\n";
239 std::string elf::findFromSearchPaths(StringRef Path) {
240 for (StringRef Dir : Config->SearchPaths) {
241 std::string FullPath = buildSysrootedPath(Dir, Path);
242 if (fs::exists(FullPath))
248 // Searches a given library from input search paths, which are filled
249 // from -L command line switches. Returns a path to an existent library file.
250 std::string elf::searchLibrary(StringRef Path) {
251 if (Path.startswith(":"))
252 return findFromSearchPaths(Path.substr(1));
253 for (StringRef Dir : Config->SearchPaths) {
254 if (!Config->Static) {
255 std::string S = buildSysrootedPath(Dir, ("lib" + Path + ".so").str());
259 std::string S = buildSysrootedPath(Dir, ("lib" + Path + ".a").str());
266 // Makes a path by concatenating Dir and File.
267 // If Dir starts with '=' the result will be preceded by Sysroot,
268 // which can be set with --sysroot command line switch.
269 std::string elf::buildSysrootedPath(StringRef Dir, StringRef File) {
270 SmallString<128> Path;
271 if (Dir.startswith("="))
272 path::append(Path, Config->Sysroot, Dir.substr(1), File);
274 path::append(Path, Dir, File);