Coverage Report

Created: 2018-01-17 21:32

/Users/buildslave/jenkins/workspace/clang-stage2-coverage-R/llvm/tools/lld/wasm/Driver.cpp
Line
Count
Source (jump to first uncovered line)
1
//===- Driver.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
#include "lld/Common/Driver.h"
11
#include "Config.h"
12
#include "SymbolTable.h"
13
#include "Writer.h"
14
#include "lld/Common/Args.h"
15
#include "lld/Common/ErrorHandler.h"
16
#include "lld/Common/Memory.h"
17
#include "lld/Common/Threads.h"
18
#include "lld/Common/Version.h"
19
#include "llvm/ADT/Twine.h"
20
#include "llvm/Object/Wasm.h"
21
#include "llvm/Option/ArgList.h"
22
#include "llvm/Support/CommandLine.h"
23
#include "llvm/Support/Path.h"
24
#include "llvm/Support/Process.h"
25
26
using namespace llvm;
27
using namespace llvm::sys;
28
using namespace llvm::wasm;
29
30
using namespace lld;
31
using namespace lld::wasm;
32
33
namespace {
34
35
// Parses command line options.
36
class WasmOptTable : public llvm::opt::OptTable {
37
public:
38
  WasmOptTable();
39
  llvm::opt::InputArgList parse(ArrayRef<const char *> Argv);
40
};
41
42
// Create enum with OPT_xxx values for each option in Options.td
43
enum {
44
  OPT_INVALID = 0,
45
#define OPTION(_1, _2, ID, _4, _5, _6, _7, _8, _9, _10, _11, _12) OPT_##ID,
46
#include "Options.inc"
47
#undef OPTION
48
};
49
50
class LinkerDriver {
51
public:
52
  void link(ArrayRef<const char *> ArgsArr);
53
54
private:
55
  void createFiles(llvm::opt::InputArgList &Args);
56
  void addFile(StringRef Path);
57
  void addLibrary(StringRef Name);
58
  std::vector<InputFile *> Files;
59
};
60
61
} // anonymous namespace
62
63
Configuration *lld::wasm::Config;
64
65
bool lld::wasm::link(ArrayRef<const char *> Args, bool CanExitEarly,
66
0
                     raw_ostream &Error) {
67
0
  errorHandler().LogName = Args[0];
68
0
  errorHandler().ErrorOS = &Error;
69
0
  errorHandler().ColorDiagnostics = Error.has_colors();
70
0
  errorHandler().ErrorLimitExceededMsg =
71
0
      "too many errors emitted, stopping now (use "
72
0
      "-error-limit=0 to see all errors)";
73
0
74
0
  Config = make<Configuration>();
75
0
  Symtab = make<SymbolTable>();
76
0
77
0
  LinkerDriver().link(Args);
78
0
79
0
  // Exit immediately if we don't need to return to the caller.
80
0
  // This saves time because the overhead of calling destructors
81
0
  // for all globally-allocated objects is not negligible.
82
0
  if (CanExitEarly)
83
0
    exitLld(errorCount() ? 1 : 0);
84
0
85
0
  freeArena();
86
0
  return !errorCount();
87
0
}
88
89
// Create OptTable
90
91
// Create prefix string literals used in Options.td
92
#define PREFIX(NAME, VALUE) const char *const NAME[] = VALUE;
93
#include "Options.inc"
94
#undef PREFIX
95
96
// Create table mapping all options defined in Options.td
97
static const opt::OptTable::Info OptInfo[] = {
98
#define OPTION(X1, X2, ID, KIND, GROUP, ALIAS, X7, X8, X9, X10, X11, X12)      \
99
  {X1, X2, X10,         X11,         OPT_##ID, opt::Option::KIND##Class,       \
100
   X9, X8, OPT_##GROUP, OPT_##ALIAS, X7,       X12},
101
#include "Options.inc"
102
#undef OPTION
103
};
104
105
// Set color diagnostics according to -color-diagnostics={auto,always,never}
106
// or -no-color-diagnostics flags.
107
0
static void handleColorDiagnostics(opt::InputArgList &Args) {
108
0
  auto *Arg = Args.getLastArg(OPT_color_diagnostics, OPT_color_diagnostics_eq,
109
0
                              OPT_no_color_diagnostics);
110
0
  if (!Arg)
111
0
    return;
112
0
113
0
  if (Arg->getOption().getID() == OPT_color_diagnostics)
114
0
    errorHandler().ColorDiagnostics = true;
115
0
  else if (Arg->getOption().getID() == OPT_no_color_diagnostics)
116
0
    errorHandler().ColorDiagnostics = false;
117
0
  else {
118
0
    StringRef S = Arg->getValue();
119
0
    if (S == "always")
120
0
      errorHandler().ColorDiagnostics = true;
121
0
    if (S == "never")
122
0
      errorHandler().ColorDiagnostics = false;
123
0
    if (S != "auto")
124
0
      error("unknown option: -color-diagnostics=" + S);
125
0
  }
126
0
}
127
128
// Find a file by concatenating given paths.
129
static Optional<std::string> findFile(StringRef Path1, const Twine &Path2) {
130
  SmallString<128> S;
131
  path::append(S, Path1, Path2);
132
  if (fs::exists(S))
133
    return S.str().str();
134
  return None;
135
}
136
137
// Inject a new undefined symbol into the link.  This will cause the link to
138
// fail unless this symbol can be found.
139
static void addSyntheticUndefinedFunction(StringRef Name,
140
0
                                          const WasmSignature *Type) {
141
0
  log("injecting undefined func: " + Name);
142
0
  Symtab->addUndefinedFunction(Name, Type);
143
0
}
144
145
0
static void printHelp(const char *Argv0) {
146
0
  WasmOptTable().PrintHelp(outs(), Argv0, "LLVM Linker", false);
147
0
}
148
149
0
WasmOptTable::WasmOptTable() : OptTable(OptInfo) {}
150
151
0
opt::InputArgList WasmOptTable::parse(ArrayRef<const char *> Argv) {
152
0
  SmallVector<const char *, 256> Vec(Argv.data(), Argv.data() + Argv.size());
153
0
154
0
  unsigned MissingIndex;
155
0
  unsigned MissingCount;
156
0
  opt::InputArgList Args = this->ParseArgs(Vec, MissingIndex, MissingCount);
157
0
158
0
  handleColorDiagnostics(Args);
159
0
  for (auto *Arg : Args.filtered(OPT_UNKNOWN))
160
0
    error("unknown argument: " + Arg->getSpelling());
161
0
  return Args;
162
0
}
163
164
// Currently we allow a ".imports" to live alongside a library. This can
165
// be used to specify a list of symbols which can be undefined at link
166
// time (imported from the environment.  For example libc.a include an
167
// import file that lists the syscall functions it relies on at runtime.
168
// In the long run this information would be better stored as a symbol
169
// attribute/flag in the object file itself.
170
// See: https://github.com/WebAssembly/tool-conventions/issues/35
171
0
static void readImportFile(StringRef Filename) {
172
0
  if (Optional<MemoryBufferRef> Buf = readFile(Filename))
173
0
    for (StringRef Sym : args::getLines(*Buf))
174
0
      Config->AllowUndefinedSymbols.insert(Sym);
175
0
}
176
177
0
void LinkerDriver::addFile(StringRef Path) {
178
0
  Optional<MemoryBufferRef> Buffer = readFile(Path);
179
0
  if (!Buffer.hasValue())
180
0
    return;
181
0
  MemoryBufferRef MBRef = *Buffer;
182
0
183
0
  if (identify_magic(MBRef.getBuffer()) == file_magic::archive) {
184
0
    SmallString<128> ImportFile = Path;
185
0
    path::replace_extension(ImportFile, ".imports");
186
0
    if (fs::exists(ImportFile))
187
0
      readImportFile(ImportFile.str());
188
0
189
0
    Files.push_back(make<ArchiveFile>(MBRef));
190
0
    return;
191
0
  }
192
0
193
0
  Files.push_back(make<ObjFile>(MBRef));
194
0
}
195
196
// Add a given library by searching it from input search paths.
197
0
void LinkerDriver::addLibrary(StringRef Name) {
198
0
  for (StringRef Dir : Config->SearchPaths) {
199
0
    if (Optional<std::string> S = findFile(Dir, "lib" + Name + ".a")) {
200
0
      addFile(*S);
201
0
      return;
202
0
    }
203
0
  }
204
0
205
0
  error("unable to find library -l" + Name);
206
0
}
207
208
0
void LinkerDriver::createFiles(opt::InputArgList &Args) {
209
0
  for (auto *Arg : Args) {
210
0
    switch (Arg->getOption().getUnaliasedOption().getID()) {
211
0
    case OPT_l:
212
0
      addLibrary(Arg->getValue());
213
0
      break;
214
0
    case OPT_INPUT:
215
0
      addFile(Arg->getValue());
216
0
      break;
217
0
    }
218
0
  }
219
0
220
0
  if (Files.empty())
221
0
    error("no input files");
222
0
}
223
224
0
static StringRef getEntry(opt::InputArgList &Args, StringRef Default) {
225
0
  auto *Arg = Args.getLastArg(OPT_entry, OPT_no_entry);
226
0
  if (!Arg)
227
0
    return Default;
228
0
  if (Arg->getOption().getID() == OPT_no_entry)
229
0
    return "";
230
0
  return Arg->getValue();
231
0
}
232
233
0
void LinkerDriver::link(ArrayRef<const char *> ArgsArr) {
234
0
  WasmOptTable Parser;
235
0
  opt::InputArgList Args = Parser.parse(ArgsArr.slice(1));
236
0
237
0
  // Handle --help
238
0
  if (Args.hasArg(OPT_help)) {
239
0
    printHelp(ArgsArr[0]);
240
0
    return;
241
0
  }
242
0
243
0
  // Parse and evaluate -mllvm options.
244
0
  std::vector<const char *> V;
245
0
  V.push_back("wasm-ld (LLVM option parsing)");
246
0
  for (auto *Arg : Args.filtered(OPT_mllvm))
247
0
    V.push_back(Arg->getValue());
248
0
  cl::ParseCommandLineOptions(V.size(), V.data());
249
0
250
0
  errorHandler().ErrorLimit = args::getInteger(Args, OPT_error_limit, 20);
251
0
252
0
  if (Args.hasArg(OPT_version) || Args.hasArg(OPT_v)) {
253
0
    outs() << getLLDVersion() << "\n";
254
0
    return;
255
0
  }
256
0
257
0
  Config->AllowUndefined = Args.hasArg(OPT_allow_undefined);
258
0
  Config->CheckSignatures =
259
0
      Args.hasFlag(OPT_check_signatures, OPT_no_check_signatures, false);
260
0
  Config->EmitRelocs = Args.hasArg(OPT_emit_relocs);
261
0
  Config->Entry = getEntry(Args, Args.hasArg(OPT_relocatable) ? "" : "_start");
262
0
  Config->ImportMemory = Args.hasArg(OPT_import_memory);
263
0
  Config->OutputFile = Args.getLastArgValue(OPT_o);
264
0
  Config->Relocatable = Args.hasArg(OPT_relocatable);
265
0
  Config->SearchPaths = args::getStrings(Args, OPT_L);
266
0
  Config->StripAll = Args.hasArg(OPT_strip_all);
267
0
  Config->StripDebug = Args.hasArg(OPT_strip_debug);
268
0
  errorHandler().Verbose = Args.hasArg(OPT_verbose);
269
0
  ThreadsEnabled = Args.hasFlag(OPT_threads, OPT_no_threads, true);
270
0
  if (Config->Relocatable)
271
0
    Config->EmitRelocs = true;
272
0
273
0
  Config->InitialMemory = args::getInteger(Args, OPT_initial_memory, 0);
274
0
  Config->GlobalBase = args::getInteger(Args, OPT_global_base, 1024);
275
0
  Config->MaxMemory = args::getInteger(Args, OPT_max_memory, 0);
276
0
  Config->ZStackSize =
277
0
      args::getZOptionValue(Args, OPT_z, "stack-size", WasmPageSize);
278
0
279
0
  if (auto *Arg = Args.getLastArg(OPT_allow_undefined_file))
280
0
    readImportFile(Arg->getValue());
281
0
282
0
  if (Config->OutputFile.empty())
283
0
    error("no output file specified");
284
0
285
0
  if (!Args.hasArg(OPT_INPUT))
286
0
    error("no input files");
287
0
288
0
  if (Config->Relocatable && !Config->Entry.empty())
289
0
    error("entry point specified for relocatable output file");
290
0
  if (Config->Relocatable && Args.hasArg(OPT_undefined))
291
0
    error("undefined symbols specified for relocatable output file");
292
0
293
0
  if (!Config->Relocatable) {
294
0
    static WasmSignature Signature = {{}, WASM_TYPE_NORESULT};
295
0
    if (!Config->Entry.empty())
296
0
      addSyntheticUndefinedFunction(Config->Entry, &Signature);
297
0
298
0
    // Handle the `--undefined <sym>` options.
299
0
    for (auto* Arg : Args.filtered(OPT_undefined))
300
0
      addSyntheticUndefinedFunction(Arg->getValue(), nullptr);
301
0
302
0
    // Create linker-synthetic symbols
303
0
    // __wasm_call_ctors:
304
0
    //    Function that directly calls all ctors in priority order.
305
0
    // __stack_pointer:
306
0
    //    Wasm global that holds the address of the top of the explict
307
0
    //    value stack in linear memory.
308
0
    // __dso_handle;
309
0
    //    Global in calls to __cxa_atexit to determine current DLL
310
0
    Config->CtorSymbol = Symtab->addDefinedFunction(
311
0
        "__wasm_call_ctors", &Signature, WASM_SYMBOL_VISIBILITY_HIDDEN);
312
0
    Config->StackPointerSymbol = Symtab->addDefinedGlobal("__stack_pointer");
313
0
    Config->HeapBaseSymbol = Symtab->addDefinedGlobal("__heap_base");
314
0
    Symtab->addDefinedGlobal("__dso_handle")->setVirtualAddress(0);
315
0
  }
316
0
317
0
  createFiles(Args);
318
0
  if (errorCount())
319
0
    return;
320
0
321
0
  // Add all files to the symbol table. This will add almost all
322
0
  // symbols that we need to the symbol table.
323
0
  for (InputFile *F : Files)
324
0
    Symtab->addFile(F);
325
0
326
0
  // Make sure we have resolved all symbols.
327
0
  if (!Config->Relocatable && !Config->AllowUndefined) {
328
0
    Symtab->reportRemainingUndefines();
329
0
  } else {
330
0
    // When we allow undefined symbols we cannot include those defined in
331
0
    // -u/--undefined since these undefined symbols have only names and no
332
0
    // function signature, which means they cannot be written to the final
333
0
    // output.
334
0
    for (auto* Arg : Args.filtered(OPT_undefined)) {
335
0
      Symbol *Sym = Symtab->find(Arg->getValue());
336
0
      if (!Sym->isDefined())
337
0
        error("function forced with --undefined not found: " + Sym->getName());
338
0
    }
339
0
  }
340
0
  if (errorCount())
341
0
    return;
342
0
343
0
  for (auto *Arg : Args.filtered(OPT_export)) {
344
0
    Symbol *Sym = Symtab->find(Arg->getValue());
345
0
    if (!Sym || !Sym->isDefined())
346
0
      error("symbol exported via --export not found: " +
347
0
            Twine(Arg->getValue()));
348
0
    else
349
0
      Sym->setHidden(false);
350
0
  }
351
0
352
0
  if (!Config->Entry.empty() && !Symtab->find(Config->Entry)->isDefined())
353
0
    error("entry point not found: " + Config->Entry);
354
0
  if (errorCount())
355
0
    return;
356
0
357
0
  // Write the result to the file.
358
0
  writeResult();
359
0
}