Coverage Report

Created: 2018-10-23 15:26

/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
//                             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 "lld/Common/ErrorHandler.h"
18
#include "lld/Common/Memory.h"
19
#include "lld/Common/Reproduce.h"
20
#include "lld/Common/Version.h"
21
#include "llvm/ADT/Optional.h"
22
#include "llvm/ADT/STLExtras.h"
23
#include "llvm/ADT/Triple.h"
24
#include "llvm/Option/Option.h"
25
#include "llvm/Support/CommandLine.h"
26
#include "llvm/Support/FileSystem.h"
27
#include "llvm/Support/Path.h"
28
#include "llvm/Support/Process.h"
29
30
using namespace llvm;
31
using namespace llvm::sys;
32
using namespace llvm::opt;
33
34
using namespace lld;
35
using namespace lld::elf;
36
37
// Create OptTable
38
39
// Create prefix string literals used in Options.td
40
#define PREFIX(NAME, VALUE) const char *const NAME[] = VALUE;
41
#include "Options.inc"
42
#undef PREFIX
43
44
// Create table mapping all options defined in Options.td
45
static const opt::OptTable::Info OptInfo[] = {
46
#define OPTION(X1, X2, ID, KIND, GROUP, ALIAS, X7, X8, X9, X10, X11, X12)      \
47
  {X1, X2, X10,         X11,         OPT_##ID, opt::Option::KIND##Class,       \
48
   X9, X8, OPT_##GROUP, OPT_##ALIAS, X7,       X12},
49
#include "Options.inc"
50
#undef OPTION
51
};
52
53
2.59k
ELFOptTable::ELFOptTable() : OptTable(OptInfo) {}
54
55
// Set color diagnostics according to -color-diagnostics={auto,always,never}
56
// or -no-color-diagnostics flags.
57
2.59k
static void handleColorDiagnostics(opt::InputArgList &Args) {
58
2.59k
  auto *Arg = Args.getLastArg(OPT_color_diagnostics, OPT_color_diagnostics_eq,
59
2.59k
                              OPT_no_color_diagnostics);
60
2.59k
  if (!Arg)
61
2.58k
    return;
62
5
  if (Arg->getOption().getID() == OPT_color_diagnostics) {
63
1
    errorHandler().ColorDiagnostics = true;
64
4
  } else if (Arg->getOption().getID() == OPT_no_color_diagnostics) {
65
1
    errorHandler().ColorDiagnostics = false;
66
3
  } else {
67
3
    StringRef S = Arg->getValue();
68
3
    if (S == "always")
69
1
      errorHandler().ColorDiagnostics = true;
70
2
    else if (S == "never")
71
1
      errorHandler().ColorDiagnostics = false;
72
1
    else if (S != "auto")
73
1
      error("unknown option: --color-diagnostics=" + S);
74
3
  }
75
5
}
76
77
2.59k
static cl::TokenizerCallback getQuotingStyle(opt::InputArgList &Args) {
78
2.59k
  if (auto *Arg = Args.getLastArg(OPT_rsp_quoting)) {
79
3
    StringRef S = Arg->getValue();
80
3
    if (S != "windows" && 
S != "posix"2
)
81
1
      error("invalid response file quoting: " + S);
82
3
    if (S == "windows")
83
1
      return cl::TokenizeWindowsCommandLine;
84
2
    return cl::TokenizeGNUCommandLine;
85
2
  }
86
2.58k
  if (Triple(sys::getProcessTriple()).getOS() == Triple::Win32)
87
0
    return cl::TokenizeWindowsCommandLine;
88
2.58k
  return cl::TokenizeGNUCommandLine;
89
2.58k
}
90
91
// Gold LTO plugin takes a `--plugin-opt foo=bar` option as an alias for
92
// `--plugin-opt=foo=bar`. We want to handle `--plugin-opt=foo=` as an
93
// option name and `bar` as a value. Unfortunately, OptParser cannot
94
// handle an option with a space in it.
95
//
96
// In this function, we concatenate command line arguments so that
97
// `--plugin-opt <foo>` is converted to `--plugin-opt=<foo>`. This is a
98
// bit hacky, but looks like it is still better than handling --plugin-opt
99
// options by hand.
100
2.59k
static void concatLTOPluginOptions(SmallVectorImpl<const char *> &Args) {
101
2.59k
  SmallVector<const char *, 256> V;
102
15.7k
  for (size_t I = 0, E = Args.size(); I != E; 
++I13.1k
) {
103
13.1k
    StringRef S = Args[I];
104
13.1k
    if ((S == "-plugin-opt" || S == "--plugin-opt") && 
I + 1 != E1
) {
105
1
      V.push_back(Saver.save(S + "=" + Args[I + 1]).data());
106
1
      ++I;
107
13.1k
    } else {
108
13.1k
      V.push_back(Args[I]);
109
13.1k
    }
110
13.1k
  }
111
2.59k
  Args = std::move(V);
112
2.59k
}
113
114
// Parses a given list of options.
115
2.59k
opt::InputArgList ELFOptTable::parse(ArrayRef<const char *> Argv) {
116
2.59k
  // Make InputArgList from string vectors.
117
2.59k
  unsigned MissingIndex;
118
2.59k
  unsigned MissingCount;
119
2.59k
  SmallVector<const char *, 256> Vec(Argv.data(), Argv.data() + Argv.size());
120
2.59k
121
2.59k
  // We need to get the quoting style for response files before parsing all
122
2.59k
  // options so we parse here before and ignore all the options but
123
2.59k
  // --rsp-quoting.
124
2.59k
  opt::InputArgList Args = this->ParseArgs(Vec, MissingIndex, MissingCount);
125
2.59k
126
2.59k
  // Expand response files (arguments in the form of @<filename>)
127
2.59k
  // and then parse the argument again.
128
2.59k
  cl::ExpandResponseFiles(Saver, getQuotingStyle(Args), Vec);
129
2.59k
  concatLTOPluginOptions(Vec);
130
2.59k
  Args = this->ParseArgs(Vec, MissingIndex, MissingCount);
131
2.59k
132
2.59k
  handleColorDiagnostics(Args);
133
2.59k
  if (MissingCount)
134
2
    error(Twine(Args.getArgString(MissingIndex)) + ": missing argument");
135
2.59k
136
2.59k
  for (auto *Arg : Args.filtered(OPT_UNKNOWN))
137
6
    error("unknown argument: " + Arg->getSpelling());
138
2.59k
  return Args;
139
2.59k
}
140
141
2
void elf::printHelp() {
142
2
  ELFOptTable().PrintHelp(
143
2
      outs(), (Config->ProgName + " [options] file...").str().c_str(), "lld",
144
2
      false /*ShowHidden*/, true /*ShowAllAliases*/);
145
2
  outs() << "\n";
146
2
147
2
  // Scripts generated by Libtool versions up to at least 2.4.6 (the most
148
2
  // recent version as of March 2017) expect /: supported targets:.* elf/
149
2
  // in a message for the -help option. If it doesn't match, the scripts
150
2
  // assume that the linker doesn't support very basic features such as
151
2
  // shared libraries. Therefore, we need to print out at least "elf".
152
2
  outs() << Config->ProgName << ": supported targets: elf\n";
153
2
}
154
155
// Reconstructs command line arguments so that so that you can re-run
156
// the same command with the same inputs. This is for --reproduce.
157
10
std::string elf::createResponseFile(const opt::InputArgList &Args) {
158
10
  SmallString<0> Data;
159
10
  raw_svector_ostream OS(Data);
160
10
  OS << "--chroot .\n";
161
10
162
10
  // Copy the command line to the output while rewriting paths.
163
50
  for (auto *Arg : Args) {
164
50
    switch (Arg->getOption().getUnaliasedOption().getID()) {
165
50
    case OPT_reproduce:
166
9
      break;
167
50
    case OPT_INPUT:
168
10
      OS << quote(rewritePath(Arg->getValue())) << "\n";
169
10
      break;
170
50
    case OPT_o:
171
8
      // If -o path contains directories, "lld @response.txt" will likely
172
8
      // fail because the archive we are creating doesn't contain empty
173
8
      // directories for the output path (-o doesn't create directories).
174
8
      // Strip directories to prevent the issue.
175
8
      OS << "-o " << quote(sys::path::filename(Arg->getValue())) << "\n";
176
8
      break;
177
50
    case OPT_dynamic_list:
178
10
    case OPT_library_path:
179
10
    case OPT_rpath:
180
10
    case OPT_script:
181
10
    case OPT_symbol_ordering_file:
182
10
    case OPT_sysroot:
183
10
    case OPT_version_script:
184
10
      OS << Arg->getSpelling() << " " << quote(rewritePath(Arg->getValue()))
185
10
         << "\n";
186
10
      break;
187
13
    default:
188
13
      OS << toString(*Arg) << "\n";
189
50
    }
190
50
  }
191
10
  return Data.str();
192
10
}
193
194
// Find a file by concatenating given paths. If a resulting path
195
// starts with "=", the character is replaced with a --sysroot value.
196
45
static Optional<std::string> findFile(StringRef Path1, const Twine &Path2) {
197
45
  SmallString<128> S;
198
45
  if (Path1.startswith("="))
199
5
    path::append(S, Config->Sysroot, Path1.substr(1), Path2);
200
40
  else
201
40
    path::append(S, Path1, Path2);
202
45
203
45
  if (fs::exists(S))
204
37
    return S.str().str();
205
8
  return None;
206
8
}
207
208
26
Optional<std::string> elf::findFromSearchPaths(StringRef Path) {
209
26
  for (StringRef Dir : Config->SearchPaths)
210
20
    if (Optional<std::string> S = findFile(Dir, Path))
211
17
      return S;
212
26
  
return None9
;
213
26
}
214
215
// This is for -lfoo. We'll look for libfoo.so or libfoo.a from
216
// search paths.
217
36
Optional<std::string> elf::searchLibrary(StringRef Name) {
218
36
  if (Name.startswith(":"))
219
10
    return findFromSearchPaths(Name.substr(1));
220
26
221
26
  for (StringRef Dir : Config->SearchPaths) {
222
22
    if (!Config->Static)
223
15
      if (Optional<std::string> S = findFile(Dir, "lib" + Name + ".so"))
224
12
        return S;
225
10
    if (Optional<std::string> S = findFile(Dir, "lib" + Name + ".a"))
226
8
      return S;
227
10
  }
228
26
  
return None6
;
229
26
}
230
231
// If a linker/version script doesn't exist in the current directory, we also
232
// look for the script in the '-L' search paths. This matches the behaviour of
233
// '-T', --version-script=, and linker script INPUT() command in ld.bfd.
234
615
Optional<std::string> elf::searchScript(StringRef Name) {
235
615
  if (fs::exists(Name))
236
603
    return Name.str();
237
12
  return findFromSearchPaths(Name);
238
12
}