Coverage Report

Created: 2019-07-24 05:18

/Users/buildslave/jenkins/workspace/clang-stage2-coverage-R/llvm/tools/lld/ELF/DriverUtils.cpp
Line
Count
Source (jump to first uncovered line)
1
//===- DriverUtils.cpp ----------------------------------------------------===//
2
//
3
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4
// See https://llvm.org/LICENSE.txt for license information.
5
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6
//
7
//===----------------------------------------------------------------------===//
8
//
9
// This file contains utility functions for the driver. Because there
10
// are so many small functions, we created this separate file to make
11
// Driver.cpp less cluttered.
12
//
13
//===----------------------------------------------------------------------===//
14
15
#include "Driver.h"
16
#include "lld/Common/ErrorHandler.h"
17
#include "lld/Common/Memory.h"
18
#include "lld/Common/Reproduce.h"
19
#include "lld/Common/Version.h"
20
#include "llvm/ADT/Optional.h"
21
#include "llvm/ADT/STLExtras.h"
22
#include "llvm/ADT/Triple.h"
23
#include "llvm/Option/Option.h"
24
#include "llvm/Support/CommandLine.h"
25
#include "llvm/Support/FileSystem.h"
26
#include "llvm/Support/Path.h"
27
#include "llvm/Support/Process.h"
28
29
using namespace llvm;
30
using namespace llvm::sys;
31
using namespace llvm::opt;
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, X7, X8, X9, X10, X11, X12)      \
46
  {X1, X2, X10,         X11,         OPT_##ID, opt::Option::KIND##Class,       \
47
   X9, X8, OPT_##GROUP, OPT_##ALIAS, X7,       X12},
48
#include "Options.inc"
49
#undef OPTION
50
};
51
52
3.03k
ELFOptTable::ELFOptTable() : OptTable(optInfo) {}
53
54
// Set color diagnostics according to -color-diagnostics={auto,always,never}
55
// or -no-color-diagnostics flags.
56
3.03k
static void handleColorDiagnostics(opt::InputArgList &args) {
57
3.03k
  auto *arg = args.getLastArg(OPT_color_diagnostics, OPT_color_diagnostics_eq,
58
3.03k
                              OPT_no_color_diagnostics);
59
3.03k
  if (!arg)
60
3.02k
    return;
61
5
  if (arg->getOption().getID() == OPT_color_diagnostics) {
62
1
    errorHandler().colorDiagnostics = true;
63
4
  } else if (arg->getOption().getID() == OPT_no_color_diagnostics) {
64
1
    errorHandler().colorDiagnostics = false;
65
3
  } else {
66
3
    StringRef s = arg->getValue();
67
3
    if (s == "always")
68
1
      errorHandler().colorDiagnostics = true;
69
2
    else if (s == "never")
70
1
      errorHandler().colorDiagnostics = false;
71
1
    else if (s != "auto")
72
1
      error("unknown option: --color-diagnostics=" + s);
73
3
  }
74
5
}
75
76
3.03k
static cl::TokenizerCallback getQuotingStyle(opt::InputArgList &args) {
77
3.03k
  if (auto *arg = args.getLastArg(OPT_rsp_quoting)) {
78
3
    StringRef s = arg->getValue();
79
3
    if (s != "windows" && 
s != "posix"2
)
80
1
      error("invalid response file quoting: " + s);
81
3
    if (s == "windows")
82
1
      return cl::TokenizeWindowsCommandLine;
83
2
    return cl::TokenizeGNUCommandLine;
84
2
  }
85
3.02k
  if (Triple(sys::getProcessTriple()).getOS() == Triple::Win32)
86
0
    return cl::TokenizeWindowsCommandLine;
87
3.02k
  return cl::TokenizeGNUCommandLine;
88
3.02k
}
89
90
// Gold LTO plugin takes a `--plugin-opt foo=bar` option as an alias for
91
// `--plugin-opt=foo=bar`. We want to handle `--plugin-opt=foo=` as an
92
// option name and `bar` as a value. Unfortunately, OptParser cannot
93
// handle an option with a space in it.
94
//
95
// In this function, we concatenate command line arguments so that
96
// `--plugin-opt <foo>` is converted to `--plugin-opt=<foo>`. This is a
97
// bit hacky, but looks like it is still better than handling --plugin-opt
98
// options by hand.
99
3.03k
static void concatLTOPluginOptions(SmallVectorImpl<const char *> &args) {
100
3.03k
  SmallVector<const char *, 256> v;
101
18.3k
  for (size_t i = 0, e = args.size(); i != e; 
++i15.3k
) {
102
15.3k
    StringRef s = args[i];
103
15.3k
    if ((s == "-plugin-opt" || s == "--plugin-opt") && 
i + 1 != e1
) {
104
1
      v.push_back(saver.save(s + "=" + args[i + 1]).data());
105
1
      ++i;
106
15.3k
    } else {
107
15.3k
      v.push_back(args[i]);
108
15.3k
    }
109
15.3k
  }
110
3.03k
  args = std::move(v);
111
3.03k
}
112
113
// Parses a given list of options.
114
3.03k
opt::InputArgList ELFOptTable::parse(ArrayRef<const char *> argv) {
115
3.03k
  // Make InputArgList from string vectors.
116
3.03k
  unsigned missingIndex;
117
3.03k
  unsigned missingCount;
118
3.03k
  SmallVector<const char *, 256> vec(argv.data(), argv.data() + argv.size());
119
3.03k
120
3.03k
  // We need to get the quoting style for response files before parsing all
121
3.03k
  // options so we parse here before and ignore all the options but
122
3.03k
  // --rsp-quoting.
123
3.03k
  opt::InputArgList args = this->ParseArgs(vec, missingIndex, missingCount);
124
3.03k
125
3.03k
  // Expand response files (arguments in the form of @<filename>)
126
3.03k
  // and then parse the argument again.
127
3.03k
  cl::ExpandResponseFiles(saver, getQuotingStyle(args), vec);
128
3.03k
  concatLTOPluginOptions(vec);
129
3.03k
  args = this->ParseArgs(vec, missingIndex, missingCount);
130
3.03k
131
3.03k
  handleColorDiagnostics(args);
132
3.03k
  if (missingCount)
133
2
    error(Twine(args.getArgString(missingIndex)) + ": missing argument");
134
3.03k
135
3.03k
  for (auto *arg : args.filtered(OPT_UNKNOWN)) {
136
7
    std::string nearest;
137
7
    if (findNearest(arg->getAsString(args), nearest) > 1)
138
6
      error("unknown argument '" + arg->getAsString(args) + "'");
139
1
    else
140
1
      error("unknown argument '" + arg->getAsString(args) +
141
1
            "', did you mean '" + nearest + "'");
142
7
  }
143
3.03k
  return args;
144
3.03k
}
145
146
2
void elf::printHelp() {
147
2
  ELFOptTable().PrintHelp(
148
2
      outs(), (config->progName + " [options] file...").str().c_str(), "lld",
149
2
      false /*ShowHidden*/, true /*ShowAllAliases*/);
150
2
  outs() << "\n";
151
2
152
2
  // Scripts generated by Libtool versions up to at least 2.4.6 (the most
153
2
  // recent version as of March 2017) expect /: supported targets:.* elf/
154
2
  // in a message for the -help option. If it doesn't match, the scripts
155
2
  // assume that the linker doesn't support very basic features such as
156
2
  // shared libraries. Therefore, we need to print out at least "elf".
157
2
  outs() << config->progName << ": supported targets: elf\n";
158
2
}
159
160
20
static std::string rewritePath(StringRef s) {
161
20
  if (fs::exists(s))
162
19
    return relativeToRoot(s);
163
1
  return s;
164
1
}
165
166
// Reconstructs command line arguments so that so that you can re-run
167
// the same command with the same inputs. This is for --reproduce.
168
10
std::string elf::createResponseFile(const opt::InputArgList &args) {
169
10
  SmallString<0> data;
170
10
  raw_svector_ostream os(data);
171
10
  os << "--chroot .\n";
172
10
173
10
  // Copy the command line to the output while rewriting paths.
174
50
  for (auto *arg : args) {
175
50
    switch (arg->getOption().getID()) {
176
50
    case OPT_reproduce:
177
9
      break;
178
50
    case OPT_INPUT:
179
10
      os << quote(rewritePath(arg->getValue())) << "\n";
180
10
      break;
181
50
    case OPT_o:
182
8
      // If -o path contains directories, "lld @response.txt" will likely
183
8
      // fail because the archive we are creating doesn't contain empty
184
8
      // directories for the output path (-o doesn't create directories).
185
8
      // Strip directories to prevent the issue.
186
8
      os << "-o " << quote(sys::path::filename(arg->getValue())) << "\n";
187
8
      break;
188
50
    case OPT_dynamic_list:
189
10
    case OPT_library_path:
190
10
    case OPT_rpath:
191
10
    case OPT_script:
192
10
    case OPT_symbol_ordering_file:
193
10
    case OPT_sysroot:
194
10
    case OPT_version_script:
195
10
      os << arg->getSpelling() << " " << quote(rewritePath(arg->getValue()))
196
10
         << "\n";
197
10
      break;
198
13
    default:
199
13
      os << toString(*arg) << "\n";
200
50
    }
201
50
  }
202
10
  return data.str();
203
10
}
204
205
// Find a file by concatenating given paths. If a resulting path
206
// starts with "=", the character is replaced with a --sysroot value.
207
60
static Optional<std::string> findFile(StringRef path1, const Twine &path2) {
208
60
  SmallString<128> s;
209
60
  if (path1.startswith("="))
210
5
    path::append(s, config->sysroot, path1.substr(1), path2);
211
55
  else
212
55
    path::append(s, path1, path2);
213
60
214
60
  if (fs::exists(s))
215
44
    return s.str().str();
216
16
  return None;
217
16
}
218
219
40
Optional<std::string> elf::findFromSearchPaths(StringRef path) {
220
40
  for (StringRef dir : config->searchPaths)
221
28
    if (Optional<std::string> s = findFile(dir, path))
222
20
      return s;
223
40
  
return None20
;
224
40
}
225
226
// This is for -l<basename>. We'll look for lib<basename>.so or lib<basename>.a from
227
// search paths.
228
37
Optional<std::string> elf::searchLibraryBaseName(StringRef name) {
229
37
  for (StringRef dir : config->searchPaths) {
230
27
    if (!config->isStatic)
231
20
      if (Optional<std::string> s = findFile(dir, "lib" + name + ".so"))
232
15
        return s;
233
12
    if (Optional<std::string> s = findFile(dir, "lib" + name + ".a"))
234
9
      return s;
235
12
  }
236
37
  
return None13
;
237
37
}
238
239
// This is for -l<namespec>.
240
36
Optional<std::string> elf::searchLibrary(StringRef name) {
241
36
    if (name.startswith(":"))
242
10
        return findFromSearchPaths(name.substr(1));
243
26
    return searchLibraryBaseName (name);
244
26
}
245
246
// If a linker/version script doesn't exist in the current directory, we also
247
// look for the script in the '-L' search paths. This matches the behaviour of
248
// '-T', --version-script=, and linker script INPUT() command in ld.bfd.
249
659
Optional<std::string> elf::searchScript(StringRef name) {
250
659
  if (fs::exists(name))
251
647
    return name.str();
252
12
  return findFromSearchPaths(name);
253
12
}