Coverage Report

Created: 2019-05-22 02:55

/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
1.41k
ELFOptTable::ELFOptTable() : OptTable(OptInfo) {}
53
54
// Set color diagnostics according to -color-diagnostics={auto,always,never}
55
// or -no-color-diagnostics flags.
56
1.41k
static void handleColorDiagnostics(opt::InputArgList &Args) {
57
1.41k
  auto *Arg = Args.getLastArg(OPT_color_diagnostics, OPT_color_diagnostics_eq,
58
1.41k
                              OPT_no_color_diagnostics);
59
1.41k
  if (!Arg)
60
1.41k
    return;
61
0
  if (Arg->getOption().getID() == OPT_color_diagnostics) {
62
0
    errorHandler().ColorDiagnostics = true;
63
0
  } else if (Arg->getOption().getID() == OPT_no_color_diagnostics) {
64
0
    errorHandler().ColorDiagnostics = false;
65
0
  } else {
66
0
    StringRef S = Arg->getValue();
67
0
    if (S == "always")
68
0
      errorHandler().ColorDiagnostics = true;
69
0
    else if (S == "never")
70
0
      errorHandler().ColorDiagnostics = false;
71
0
    else if (S != "auto")
72
0
      error("unknown option: --color-diagnostics=" + S);
73
0
  }
74
0
}
75
76
1.41k
static cl::TokenizerCallback getQuotingStyle(opt::InputArgList &Args) {
77
1.41k
  if (auto *Arg = Args.getLastArg(OPT_rsp_quoting)) {
78
2
    StringRef S = Arg->getValue();
79
2
    if (S != "windows" && S != "posix")
80
1
      error("invalid response file quoting: " + S);
81
2
    if (S == "windows")
82
0
      return cl::TokenizeWindowsCommandLine;
83
2
    return cl::TokenizeGNUCommandLine;
84
2
  }
85
1.41k
  if (Triple(sys::getProcessTriple()).getOS() == Triple::Win32)
86
0
    return cl::TokenizeWindowsCommandLine;
87
1.41k
  return cl::TokenizeGNUCommandLine;
88
1.41k
}
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
1.41k
static void concatLTOPluginOptions(SmallVectorImpl<const char *> &Args) {
100
1.41k
  SmallVector<const char *, 256> V;
101
8.56k
  for (size_t I = 0, E = Args.size(); I != E; 
++I7.15k
) {
102
7.15k
    StringRef S = Args[I];
103
7.15k
    if ((S == "-plugin-opt" || S == "--plugin-opt") && 
I + 1 != E0
) {
104
0
      V.push_back(Saver.save(S + "=" + Args[I + 1]).data());
105
0
      ++I;
106
7.15k
    } else {
107
7.15k
      V.push_back(Args[I]);
108
7.15k
    }
109
7.15k
  }
110
1.41k
  Args = std::move(V);
111
1.41k
}
112
113
// Parses a given list of options.
114
1.41k
opt::InputArgList ELFOptTable::parse(ArrayRef<const char *> Argv) {
115
1.41k
  // Make InputArgList from string vectors.
116
1.41k
  unsigned MissingIndex;
117
1.41k
  unsigned MissingCount;
118
1.41k
  SmallVector<const char *, 256> Vec(Argv.data(), Argv.data() + Argv.size());
119
1.41k
120
1.41k
  // We need to get the quoting style for response files before parsing all
121
1.41k
  // options so we parse here before and ignore all the options but
122
1.41k
  // --rsp-quoting.
123
1.41k
  opt::InputArgList Args = this->ParseArgs(Vec, MissingIndex, MissingCount);
124
1.41k
125
1.41k
  // Expand response files (arguments in the form of @<filename>)
126
1.41k
  // and then parse the argument again.
127
1.41k
  cl::ExpandResponseFiles(Saver, getQuotingStyle(Args), Vec);
128
1.41k
  concatLTOPluginOptions(Vec);
129
1.41k
  Args = this->ParseArgs(Vec, MissingIndex, MissingCount);
130
1.41k
131
1.41k
  handleColorDiagnostics(Args);
132
1.41k
  if (MissingCount)
133
1
    error(Twine(Args.getArgString(MissingIndex)) + ": missing argument");
134
1.41k
135
1.41k
  for (auto *Arg : Args.filtered(OPT_UNKNOWN)) {
136
1
    std::string Nearest;
137
1
    if (findNearest(Arg->getAsString(Args), Nearest) > 1)
138
1
      error("unknown argument '" + Arg->getSpelling() + "'");
139
0
    else
140
0
      error("unknown argument '" + Arg->getSpelling() + "', did you mean '" +
141
0
            Nearest + "'");
142
1
  }
143
1.41k
  return Args;
144
1.41k
}
145
146
0
void elf::printHelp() {
147
0
  ELFOptTable().PrintHelp(
148
0
      outs(), (Config->ProgName + " [options] file...").str().c_str(), "lld",
149
0
      false /*ShowHidden*/, true /*ShowAllAliases*/);
150
0
  outs() << "\n";
151
0
152
0
  // Scripts generated by Libtool versions up to at least 2.4.6 (the most
153
0
  // recent version as of March 2017) expect /: supported targets:.* elf/
154
0
  // in a message for the -help option. If it doesn't match, the scripts
155
0
  // assume that the linker doesn't support very basic features such as
156
0
  // shared libraries. Therefore, we need to print out at least "elf".
157
0
  outs() << Config->ProgName << ": supported targets: elf\n";
158
0
}
159
160
15
static std::string rewritePath(StringRef S) {
161
15
  if (fs::exists(S))
162
15
    return relativeToRoot(S);
163
0
  return S;
164
0
}
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
5
std::string elf::createResponseFile(const opt::InputArgList &Args) {
169
5
  SmallString<0> Data;
170
5
  raw_svector_ostream OS(Data);
171
5
  OS << "--chroot .\n";
172
5
173
5
  // Copy the command line to the output while rewriting paths.
174
32
  for (auto *Arg : Args) {
175
32
    switch (Arg->getOption().getUnaliasedOption().getID()) {
176
32
    case OPT_reproduce:
177
5
      break;
178
32
    case OPT_INPUT:
179
5
      OS << quote(rewritePath(Arg->getValue())) << "\n";
180
5
      break;
181
32
    case OPT_o:
182
4
      // If -o path contains directories, "lld @response.txt" will likely
183
4
      // fail because the archive we are creating doesn't contain empty
184
4
      // directories for the output path (-o doesn't create directories).
185
4
      // Strip directories to prevent the issue.
186
4
      OS << "-o " << quote(sys::path::filename(Arg->getValue())) << "\n";
187
4
      break;
188
32
    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
10
    default:
199
8
      OS << toString(*Arg) << "\n";
200
32
    }
201
32
  }
202
5
  return Data.str();
203
5
}
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
26
static Optional<std::string> findFile(StringRef Path1, const Twine &Path2) {
208
26
  SmallString<128> S;
209
26
  if (Path1.startswith("="))
210
4
    path::append(S, Config->Sysroot, Path1.substr(1), Path2);
211
22
  else
212
22
    path::append(S, Path1, Path2);
213
26
214
26
  if (fs::exists(S))
215
21
    return S.str().str();
216
5
  return None;
217
5
}
218
219
19
Optional<std::string> elf::findFromSearchPaths(StringRef Path) {
220
19
  for (StringRef Dir : Config->SearchPaths)
221
11
    if (Optional<std::string> S = findFile(Dir, Path))
222
8
      return S;
223
19
  
return None11
;
224
19
}
225
226
// This is for -l<basename>. We'll look for lib<basename>.so or lib<basename>.a from
227
// search paths.
228
21
Optional<std::string> elf::searchLibraryBaseName(StringRef Name) {
229
21
  for (StringRef Dir : Config->SearchPaths) {
230
14
    if (!Config->Static)
231
8
      if (Optional<std::string> S = findFile(Dir, "lib" + Name + ".so"))
232
7
        return S;
233
7
    if (Optional<std::string> S = findFile(Dir, "lib" + Name + ".a"))
234
6
      return S;
235
7
  }
236
21
  
return None8
;
237
21
}
238
239
// This is for -l<namespec>.
240
21
Optional<std::string> elf::searchLibrary(StringRef Name) {
241
21
    if (Name.startswith(":"))
242
7
        return findFromSearchPaths(Name.substr(1));
243
14
    return searchLibraryBaseName (Name);
244
14
}
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
317
Optional<std::string> elf::searchScript(StringRef Name) {
250
317
  if (fs::exists(Name))
251
313
    return Name.str();
252
4
  return findFromSearchPaths(Name);
253
4
}