Coverage Report

Created: 2019-05-22 02:55

/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
// 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
#include "lld/Common/Driver.h"
10
#include "Config.h"
11
#include "InputChunks.h"
12
#include "InputGlobal.h"
13
#include "MarkLive.h"
14
#include "SymbolTable.h"
15
#include "Writer.h"
16
#include "lld/Common/Args.h"
17
#include "lld/Common/ErrorHandler.h"
18
#include "lld/Common/Memory.h"
19
#include "lld/Common/Reproduce.h"
20
#include "lld/Common/Strings.h"
21
#include "lld/Common/Threads.h"
22
#include "lld/Common/Version.h"
23
#include "llvm/ADT/Twine.h"
24
#include "llvm/Object/Wasm.h"
25
#include "llvm/Option/Arg.h"
26
#include "llvm/Option/ArgList.h"
27
#include "llvm/Support/CommandLine.h"
28
#include "llvm/Support/Path.h"
29
#include "llvm/Support/Process.h"
30
#include "llvm/Support/TarWriter.h"
31
#include "llvm/Support/TargetSelect.h"
32
33
#define DEBUG_TYPE "lld"
34
35
using namespace llvm;
36
using namespace llvm::object;
37
using namespace llvm::sys;
38
using namespace llvm::wasm;
39
40
using namespace lld;
41
using namespace lld::wasm;
42
43
Configuration *lld::wasm::Config;
44
45
namespace {
46
47
// Create enum with OPT_xxx values for each option in Options.td
48
enum {
49
  OPT_INVALID = 0,
50
#define OPTION(_1, _2, ID, _4, _5, _6, _7, _8, _9, _10, _11, _12) OPT_##ID,
51
#include "Options.inc"
52
#undef OPTION
53
};
54
55
// This function is called on startup. We need this for LTO since
56
// LTO calls LLVM functions to compile bitcode files to native code.
57
// Technically this can be delayed until we read bitcode files, but
58
// we don't bother to do lazily because the initialization is fast.
59
99
static void initLLVM() {
60
99
  InitializeAllTargets();
61
99
  InitializeAllTargetMCs();
62
99
  InitializeAllAsmPrinters();
63
99
  InitializeAllAsmParsers();
64
99
}
65
66
class LinkerDriver {
67
public:
68
  void link(ArrayRef<const char *> ArgsArr);
69
70
private:
71
  void createFiles(opt::InputArgList &Args);
72
  void addFile(StringRef Path);
73
  void addLibrary(StringRef Name);
74
75
  // True if we are in --whole-archive and --no-whole-archive.
76
  bool InWholeArchive = false;
77
78
  std::vector<InputFile *> Files;
79
};
80
} // anonymous namespace
81
82
bool lld::wasm::link(ArrayRef<const char *> Args, bool CanExitEarly,
83
99
                     raw_ostream &Error) {
84
99
  errorHandler().LogName = args::getFilenameWithoutExe(Args[0]);
85
99
  errorHandler().ErrorOS = &Error;
86
99
  errorHandler().ColorDiagnostics = Error.has_colors();
87
99
  errorHandler().ErrorLimitExceededMsg =
88
99
      "too many errors emitted, stopping now (use "
89
99
      "-error-limit=0 to see all errors)";
90
99
91
99
  Config = make<Configuration>();
92
99
  Symtab = make<SymbolTable>();
93
99
94
99
  initLLVM();
95
99
  LinkerDriver().link(Args);
96
99
97
99
  // Exit immediately if we don't need to return to the caller.
98
99
  // This saves time because the overhead of calling destructors
99
99
  // for all globally-allocated objects is not negligible.
100
99
  if (CanExitEarly)
101
0
    exitLld(errorCount() ? 1 : 0);
102
99
103
99
  freeArena();
104
99
  return !errorCount();
105
99
}
106
107
// Create prefix string literals used in Options.td
108
#define PREFIX(NAME, VALUE) const char *const NAME[] = VALUE;
109
#include "Options.inc"
110
#undef PREFIX
111
112
// Create table mapping all options defined in Options.td
113
static const opt::OptTable::Info OptInfo[] = {
114
#define OPTION(X1, X2, ID, KIND, GROUP, ALIAS, X7, X8, X9, X10, X11, X12)      \
115
  {X1, X2, X10,         X11,         OPT_##ID, opt::Option::KIND##Class,       \
116
   X9, X8, OPT_##GROUP, OPT_##ALIAS, X7,       X12},
117
#include "Options.inc"
118
#undef OPTION
119
};
120
121
namespace {
122
class WasmOptTable : public llvm::opt::OptTable {
123
public:
124
99
  WasmOptTable() : OptTable(OptInfo) {}
125
  opt::InputArgList parse(ArrayRef<const char *> Argv);
126
};
127
} // namespace
128
129
// Set color diagnostics according to -color-diagnostics={auto,always,never}
130
// or -no-color-diagnostics flags.
131
99
static void handleColorDiagnostics(opt::InputArgList &Args) {
132
99
  auto *Arg = Args.getLastArg(OPT_color_diagnostics, OPT_color_diagnostics_eq,
133
99
                              OPT_no_color_diagnostics);
134
99
  if (!Arg)
135
99
    return;
136
0
  if (Arg->getOption().getID() == OPT_color_diagnostics) {
137
0
    errorHandler().ColorDiagnostics = true;
138
0
  } else if (Arg->getOption().getID() == OPT_no_color_diagnostics) {
139
0
    errorHandler().ColorDiagnostics = false;
140
0
  } else {
141
0
    StringRef S = Arg->getValue();
142
0
    if (S == "always")
143
0
      errorHandler().ColorDiagnostics = true;
144
0
    else if (S == "never")
145
0
      errorHandler().ColorDiagnostics = false;
146
0
    else if (S != "auto")
147
0
      error("unknown option: --color-diagnostics=" + S);
148
0
  }
149
0
}
150
151
// Find a file by concatenating given paths.
152
static Optional<std::string> findFile(StringRef Path1, const Twine &Path2) {
153
  SmallString<128> S;
154
  path::append(S, Path1, Path2);
155
  if (fs::exists(S))
156
    return S.str().str();
157
  return None;
158
}
159
160
99
opt::InputArgList WasmOptTable::parse(ArrayRef<const char *> Argv) {
161
99
  SmallVector<const char *, 256> Vec(Argv.data(), Argv.data() + Argv.size());
162
99
163
99
  unsigned MissingIndex;
164
99
  unsigned MissingCount;
165
99
166
99
  // Expand response files (arguments in the form of @<filename>)
167
99
  cl::ExpandResponseFiles(Saver, cl::TokenizeGNUCommandLine, Vec);
168
99
169
99
  opt::InputArgList Args = this->ParseArgs(Vec, MissingIndex, MissingCount);
170
99
171
99
  handleColorDiagnostics(Args);
172
99
  for (auto *Arg : Args.filtered(OPT_UNKNOWN))
173
0
    error("unknown argument: " + Arg->getSpelling());
174
99
  return Args;
175
99
}
176
177
// Currently we allow a ".imports" to live alongside a library. This can
178
// be used to specify a list of symbols which can be undefined at link
179
// time (imported from the environment.  For example libc.a include an
180
// import file that lists the syscall functions it relies on at runtime.
181
// In the long run this information would be better stored as a symbol
182
// attribute/flag in the object file itself.
183
// See: https://github.com/WebAssembly/tool-conventions/issues/35
184
3
static void readImportFile(StringRef Filename) {
185
3
  if (Optional<MemoryBufferRef> Buf = readFile(Filename))
186
3
    for (StringRef Sym : args::getLines(*Buf))
187
3
      Config->AllowUndefinedSymbols.insert(Sym);
188
3
}
189
190
// Returns slices of MB by parsing MB as an archive file.
191
// Each slice consists of a member file in the archive.
192
std::vector<MemoryBufferRef> static getArchiveMembers(MemoryBufferRef MB) {
193
  std::unique_ptr<Archive> File =
194
      CHECK(Archive::create(MB),
195
            MB.getBufferIdentifier() + ": failed to parse archive");
196
197
  std::vector<MemoryBufferRef> V;
198
  Error Err = Error::success();
199
  for (const ErrorOr<Archive::Child> &COrErr : File->children(Err)) {
200
    Archive::Child C =
201
        CHECK(COrErr, MB.getBufferIdentifier() +
202
                          ": could not get the child of the archive");
203
    MemoryBufferRef MBRef =
204
        CHECK(C.getMemoryBufferRef(),
205
              MB.getBufferIdentifier() +
206
                  ": could not get the buffer for a child of the archive");
207
    V.push_back(MBRef);
208
  }
209
  if (Err)
210
    fatal(MB.getBufferIdentifier() +
211
          ": Archive::children failed: " + toString(std::move(Err)));
212
213
  // Take ownership of memory buffers created for members of thin archives.
214
  for (std::unique_ptr<MemoryBuffer> &MB : File->takeThinBuffers())
215
    make<std::unique_ptr<MemoryBuffer>>(std::move(MB));
216
217
  return V;
218
}
219
220
149
void LinkerDriver::addFile(StringRef Path) {
221
149
  Optional<MemoryBufferRef> Buffer = readFile(Path);
222
149
  if (!Buffer.hasValue())
223
2
    return;
224
147
  MemoryBufferRef MBRef = *Buffer;
225
147
226
147
  switch (identify_magic(MBRef.getBuffer())) {
227
147
  case file_magic::archive: {
228
12
    // Handle -whole-archive.
229
12
    if (InWholeArchive) {
230
3
      for (MemoryBufferRef &M : getArchiveMembers(MBRef))
231
6
        Files.push_back(createObjectFile(M, Path));
232
3
      return;
233
3
    }
234
9
235
9
    SmallString<128> ImportFile = Path;
236
9
    path::replace_extension(ImportFile, ".imports");
237
9
    if (fs::exists(ImportFile))
238
3
      readImportFile(ImportFile.str());
239
9
240
9
    Files.push_back(make<ArchiveFile>(MBRef));
241
9
    return;
242
9
  }
243
135
  case file_magic::bitcode:
244
135
  case file_magic::wasm_object:
245
135
    Files.push_back(createObjectFile(MBRef));
246
135
    break;
247
135
  default:
248
0
    error("unknown file type: " + MBRef.getBufferIdentifier());
249
147
  }
250
147
}
251
252
// Add a given library by searching it from input search paths.
253
0
void LinkerDriver::addLibrary(StringRef Name) {
254
0
  for (StringRef Dir : Config->SearchPaths) {
255
0
    if (Optional<std::string> S = findFile(Dir, "lib" + Name + ".a")) {
256
0
      addFile(*S);
257
0
      return;
258
0
    }
259
0
  }
260
0
261
0
  error("unable to find library -l" + Name);
262
0
}
263
264
99
void LinkerDriver::createFiles(opt::InputArgList &Args) {
265
374
  for (auto *Arg : Args) {
266
374
    switch (Arg->getOption().getUnaliasedOption().getID()) {
267
374
    case OPT_l:
268
0
      addLibrary(Arg->getValue());
269
0
      break;
270
374
    case OPT_INPUT:
271
149
      addFile(Arg->getValue());
272
149
      break;
273
374
    case OPT_whole_archive:
274
4
      InWholeArchive = true;
275
4
      break;
276
374
    case OPT_no_whole_archive:
277
2
      InWholeArchive = false;
278
2
      break;
279
374
    }
280
374
  }
281
99
}
282
283
99
static StringRef getEntry(opt::InputArgList &Args) {
284
99
  auto *Arg = Args.getLastArg(OPT_entry, OPT_no_entry);
285
99
  if (!Arg) {
286
72
    if (Args.hasArg(OPT_relocatable))
287
9
      return "";
288
63
    if (Args.hasArg(OPT_shared))
289
1
      return "__wasm_call_ctors";
290
62
    return "_start";
291
62
  }
292
27
  if (Arg->getOption().getID() == OPT_no_entry)
293
21
    return "";
294
6
  return Arg->getValue();
295
6
}
296
297
// Initializes Config members by the command line options.
298
static void readConfigs(opt::InputArgList &Args) {
299
  Config->AllowUndefined = Args.hasArg(OPT_allow_undefined);
300
  Config->CheckFeatures =
301
      Args.hasFlag(OPT_check_features, OPT_no_check_features, true);
302
  Config->CompressRelocations = Args.hasArg(OPT_compress_relocations);
303
  Config->Demangle = Args.hasFlag(OPT_demangle, OPT_no_demangle, true);
304
  Config->DisableVerify = Args.hasArg(OPT_disable_verify);
305
  Config->Entry = getEntry(Args);
306
  Config->ExportAll = Args.hasArg(OPT_export_all);
307
  Config->ExportDynamic = Args.hasFlag(OPT_export_dynamic,
308
      OPT_no_export_dynamic, false);
309
  Config->ExportTable = Args.hasArg(OPT_export_table);
310
  errorHandler().FatalWarnings =
311
      Args.hasFlag(OPT_fatal_warnings, OPT_no_fatal_warnings, false);
312
  Config->ImportMemory = Args.hasArg(OPT_import_memory);
313
  Config->SharedMemory = Args.hasArg(OPT_shared_memory);
314
  Config->ImportTable = Args.hasArg(OPT_import_table);
315
  Config->LTOO = args::getInteger(Args, OPT_lto_O, 2);
316
  Config->LTOPartitions = args::getInteger(Args, OPT_lto_partitions, 1);
317
  Config->Optimize = args::getInteger(Args, OPT_O, 0);
318
  Config->OutputFile = Args.getLastArgValue(OPT_o);
319
  Config->Relocatable = Args.hasArg(OPT_relocatable);
320
  Config->GcSections =
321
      Args.hasFlag(OPT_gc_sections, OPT_no_gc_sections, !Config->Relocatable);
322
  Config->MergeDataSegments =
323
      Args.hasFlag(OPT_merge_data_segments, OPT_no_merge_data_segments,
324
                   !Config->Relocatable);
325
  Config->Pie = Args.hasFlag(OPT_pie, OPT_no_pie, false);
326
  Config->PrintGcSections =
327
      Args.hasFlag(OPT_print_gc_sections, OPT_no_print_gc_sections, false);
328
  Config->SaveTemps = Args.hasArg(OPT_save_temps);
329
  Config->SearchPaths = args::getStrings(Args, OPT_L);
330
  Config->Shared = Args.hasArg(OPT_shared);
331
  Config->StripAll = Args.hasArg(OPT_strip_all);
332
  Config->StripDebug = Args.hasArg(OPT_strip_debug);
333
  Config->StackFirst = Args.hasArg(OPT_stack_first);
334
  Config->Trace = Args.hasArg(OPT_trace);
335
  Config->ThinLTOCacheDir = Args.getLastArgValue(OPT_thinlto_cache_dir);
336
  Config->ThinLTOCachePolicy = CHECK(
337
      parseCachePruningPolicy(Args.getLastArgValue(OPT_thinlto_cache_policy)),
338
      "--thinlto-cache-policy: invalid cache policy");
339
  Config->ThinLTOJobs = args::getInteger(Args, OPT_thinlto_jobs, -1u);
340
  errorHandler().Verbose = Args.hasArg(OPT_verbose);
341
  LLVM_DEBUG(errorHandler().Verbose = true);
342
  ThreadsEnabled = Args.hasFlag(OPT_threads, OPT_no_threads, true);
343
344
  Config->InitialMemory = args::getInteger(Args, OPT_initial_memory, 0);
345
  Config->GlobalBase = args::getInteger(Args, OPT_global_base, 1024);
346
  Config->MaxMemory = args::getInteger(Args, OPT_max_memory, 0);
347
  Config->ZStackSize =
348
      args::getZOptionValue(Args, OPT_z, "stack-size", WasmPageSize);
349
350
  if (auto *Arg = Args.getLastArg(OPT_features)) {
351
    Config->Features =
352
        llvm::Optional<std::vector<std::string>>(std::vector<std::string>());
353
    for (StringRef S : Arg->getValues())
354
      Config->Features->push_back(S);
355
  }
356
}
357
358
// Some Config members do not directly correspond to any particular
359
// command line options, but computed based on other Config values.
360
// This function initialize such members. See Config.h for the details
361
// of these values.
362
99
static void setConfigs() {
363
99
  Config->Pic = Config->Pie || Config->Shared;
364
99
365
99
  if (Config->Pic) {
366
1
    if (Config->ExportTable)
367
0
      error("-shared/-pie is incompatible with --export-table");
368
1
    Config->ImportTable = true;
369
1
  }
370
99
371
99
  if (Config->Shared) {
372
1
    Config->ImportMemory = true;
373
1
    Config->ExportDynamic = true;
374
1
    Config->AllowUndefined = true;
375
1
  }
376
99
}
377
378
// Some command line options or some combinations of them are not allowed.
379
// This function checks for such errors.
380
99
static void checkOptions(opt::InputArgList &Args) {
381
99
  if (!Config->StripDebug && 
!Config->StripAll98
&&
Config->CompressRelocations97
)
382
1
    error("--compress-relocations is incompatible with output debug"
383
1
          " information. Please pass --strip-debug or --strip-all");
384
99
385
99
  if (Config->LTOO > 3)
386
1
    error("invalid optimization level for LTO: " + Twine(Config->LTOO));
387
99
  if (Config->LTOPartitions == 0)
388
0
    error("--lto-partitions: number of threads must be > 0");
389
99
  if (Config->ThinLTOJobs == 0)
390
0
    error("--thinlto-jobs: number of threads must be > 0");
391
99
392
99
  if (Config->Pie && 
Config->Shared0
)
393
0
    error("-shared and -pie may not be used together");
394
99
395
99
  if (Config->OutputFile.empty())
396
3
    error("no output file specified");
397
99
398
99
  if (Config->ImportTable && 
Config->ExportTable2
)
399
1
    error("--import-table and --export-table may not be used together");
400
99
401
99
  if (Config->Relocatable) {
402
10
    if (!Config->Entry.empty())
403
0
      error("entry point specified for relocatable output file");
404
10
    if (Config->GcSections)
405
1
      error("-r and --gc-sections may not be used together");
406
10
    if (Config->CompressRelocations)
407
0
      error("-r -and --compress-relocations may not be used together");
408
10
    if (Args.hasArg(OPT_undefined))
409
0
      error("-r -and --undefined may not be used together");
410
10
    if (Config->Pie)
411
0
      error("-r and -pie may not be used together");
412
10
  }
413
99
}
414
415
// Force Sym to be entered in the output. Used for -u or equivalent.
416
static Symbol *handleUndefined(StringRef Name) {
417
  Symbol *Sym = Symtab->find(Name);
418
  if (!Sym)
419
    return nullptr;
420
421
  // Since symbol S may not be used inside the program, LTO may
422
  // eliminate it. Mark the symbol as "used" to prevent it.
423
  Sym->IsUsedInRegularObj = true;
424
425
  if (auto *LazySym = dyn_cast<LazySymbol>(Sym))
426
    LazySym->fetch();
427
428
  return Sym;
429
}
430
431
static UndefinedGlobal *
432
3
createUndefinedGlobal(StringRef Name, llvm::wasm::WasmGlobalType *Type) {
433
3
  auto *Sym =
434
3
      cast<UndefinedGlobal>(Symtab->addUndefinedGlobal(Name, Name,
435
3
                                                       DefaultModule, 0,
436
3
                                                       nullptr, Type));
437
3
  Config->AllowUndefinedSymbols.insert(Sym->getName());
438
3
  Sym->IsUsedInRegularObj = true;
439
3
  return Sym;
440
3
}
441
442
// Create ABI-defined synthetic symbols
443
89
static void createSyntheticSymbols() {
444
89
  static WasmSignature NullSignature = {{}, {}};
445
89
  static llvm::wasm::WasmGlobalType GlobalTypeI32 = {WASM_TYPE_I32, false};
446
89
  static llvm::wasm::WasmGlobalType MutableGlobalTypeI32 = {WASM_TYPE_I32,
447
89
                                                            true};
448
89
449
89
  if (!Config->Relocatable) {
450
89
    WasmSym::CallCtors = Symtab->addSyntheticFunction(
451
89
        "__wasm_call_ctors", WASM_SYMBOL_VISIBILITY_HIDDEN,
452
89
        make<SyntheticFunction>(NullSignature, "__wasm_call_ctors"));
453
89
454
89
    if (Config->Pic) {
455
1
      // For PIC code we create a synthetic function call __wasm_apply_relocs
456
1
      // and add this as the first call in __wasm_call_ctors.
457
1
      // We also unconditionally export 
458
1
      WasmSym::ApplyRelocs = Symtab->addSyntheticFunction(
459
1
          "__wasm_apply_relocs", WASM_SYMBOL_VISIBILITY_HIDDEN,
460
1
          make<SyntheticFunction>(NullSignature, "__wasm_apply_relocs"));
461
1
    }
462
89
  }
463
89
464
89
  // The __stack_pointer is imported in the shared library case, and exported
465
89
  // in the non-shared (executable) case.
466
89
  if (Config->Shared) {
467
1
    WasmSym::StackPointer =
468
1
        createUndefinedGlobal("__stack_pointer", &MutableGlobalTypeI32);
469
88
  } else {
470
88
    llvm::wasm::WasmGlobal Global;
471
88
    Global.Type = {WASM_TYPE_I32, true};
472
88
    Global.InitExpr.Value.Int32 = 0;
473
88
    Global.InitExpr.Opcode = WASM_OPCODE_I32_CONST;
474
88
    Global.SymbolName = "__stack_pointer";
475
88
    auto *StackPointer = make<InputGlobal>(Global, nullptr);
476
88
    StackPointer->Live = true;
477
88
    // For non-PIC code
478
88
    // TODO(sbc): Remove WASM_SYMBOL_VISIBILITY_HIDDEN when the mutable global
479
88
    // spec proposal is implemented in all major browsers.
480
88
    // See: https://github.com/WebAssembly/mutable-global
481
88
    WasmSym::StackPointer = Symtab->addSyntheticGlobal(
482
88
        "__stack_pointer", WASM_SYMBOL_VISIBILITY_HIDDEN, StackPointer);
483
88
    WasmSym::HeapBase = Symtab->addSyntheticDataSymbol("__heap_base", 0);
484
88
    WasmSym::DataEnd = Symtab->addSyntheticDataSymbol("__data_end", 0);
485
88
486
88
    // These two synthetic symbols exist purely for the embedder so we always
487
88
    // want to export them.
488
88
    WasmSym::HeapBase->ForceExport = true;
489
88
    WasmSym::DataEnd->ForceExport = true;
490
88
  }
491
89
492
89
  if (Config->Pic) {
493
1
    // For PIC code, we import two global variables (__memory_base and
494
1
    // __table_base) from the environment and use these as the offset at
495
1
    // which to load our static data and function table.
496
1
    // See:
497
1
    // https://github.com/WebAssembly/tool-conventions/blob/master/DynamicLinking.md
498
1
    WasmSym::MemoryBase =
499
1
        createUndefinedGlobal("__memory_base", &GlobalTypeI32);
500
1
    WasmSym::TableBase = createUndefinedGlobal("__table_base", &GlobalTypeI32);
501
1
    WasmSym::MemoryBase->markLive();
502
1
    WasmSym::TableBase->markLive();
503
1
  }
504
89
505
89
  WasmSym::DsoHandle = Symtab->addSyntheticDataSymbol(
506
89
      "__dso_handle", WASM_SYMBOL_VISIBILITY_HIDDEN);
507
89
}
508
509
// Reconstructs command line arguments so that so that you can re-run
510
// the same command with the same inputs. This is for --reproduce.
511
1
static std::string createResponseFile(const opt::InputArgList &Args) {
512
1
  SmallString<0> Data;
513
1
  raw_svector_ostream OS(Data);
514
1
515
1
  // Copy the command line to the output while rewriting paths.
516
3
  for (auto *Arg : Args) {
517
3
    switch (Arg->getOption().getUnaliasedOption().getID()) {
518
3
    case OPT_reproduce:
519
1
      break;
520
3
    case OPT_INPUT:
521
1
      OS << quote(relativeToRoot(Arg->getValue())) << "\n";
522
1
      break;
523
3
    case OPT_o:
524
1
      // If -o path contains directories, "lld @response.txt" will likely
525
1
      // fail because the archive we are creating doesn't contain empty
526
1
      // directories for the output path (-o doesn't create directories).
527
1
      // Strip directories to prevent the issue.
528
1
      OS << "-o " << quote(sys::path::filename(Arg->getValue())) << "\n";
529
1
      break;
530
3
    default:
531
0
      OS << toString(*Arg) << "\n";
532
3
    }
533
3
  }
534
1
  return Data.str();
535
1
}
536
537
99
void LinkerDriver::link(ArrayRef<const char *> ArgsArr) {
538
99
  WasmOptTable Parser;
539
99
  opt::InputArgList Args = Parser.parse(ArgsArr.slice(1));
540
99
541
99
  // Handle --help
542
99
  if (Args.hasArg(OPT_help)) {
543
0
    Parser.PrintHelp(outs(),
544
0
                     (std::string(ArgsArr[0]) + " [options] file...").c_str(),
545
0
                     "LLVM Linker", false);
546
0
    return;
547
0
  }
548
99
549
99
  // Handle --version
550
99
  if (Args.hasArg(OPT_version) || Args.hasArg(OPT_v)) {
551
0
    outs() << getLLDVersion() << "\n";
552
0
    return;
553
0
  }
554
99
555
99
  // Handle --reproduce
556
99
  if (auto *Arg = Args.getLastArg(OPT_reproduce)) {
557
1
    StringRef Path = Arg->getValue();
558
1
    Expected<std::unique_ptr<TarWriter>> ErrOrWriter =
559
1
        TarWriter::create(Path, path::stem(Path));
560
1
    if (ErrOrWriter) {
561
1
      Tar = std::move(*ErrOrWriter);
562
1
      Tar->append("response.txt", createResponseFile(Args));
563
1
      Tar->append("version.txt", getLLDVersion() + "\n");
564
1
    } else {
565
0
      error("--reproduce: " + toString(ErrOrWriter.takeError()));
566
0
    }
567
1
  }
568
99
569
99
  // Parse and evaluate -mllvm options.
570
99
  std::vector<const char *> V;
571
99
  V.push_back("wasm-ld (LLVM option parsing)");
572
99
  for (auto *Arg : Args.filtered(OPT_mllvm))
573
0
    V.push_back(Arg->getValue());
574
99
  cl::ParseCommandLineOptions(V.size(), V.data());
575
99
576
99
  errorHandler().ErrorLimit = args::getInteger(Args, OPT_error_limit, 20);
577
99
578
99
  readConfigs(Args);
579
99
  setConfigs();
580
99
  checkOptions(Args);
581
99
582
99
  if (auto *Arg = Args.getLastArg(OPT_allow_undefined_file))
583
0
    readImportFile(Arg->getValue());
584
99
585
99
  if (!Args.hasArg(OPT_INPUT)) {
586
0
    error("no input files");
587
0
    return;
588
0
  }
589
99
590
99
  // Handle --trace-symbol.
591
99
  for (auto *Arg : Args.filtered(OPT_trace_symbol))
592
3
    Symtab->trace(Arg->getValue());
593
99
594
99
  if (!Config->Relocatable)
595
89
    createSyntheticSymbols();
596
99
597
99
  createFiles(Args);
598
99
  if (errorCount())
599
6
    return;
600
93
601
93
  // Add all files to the symbol table. This will add almost all
602
93
  // symbols that we need to the symbol table.
603
93
  for (InputFile *F : Files)
604
144
    Symtab->addFile(F);
605
93
  if (errorCount())
606
3
    return;
607
90
608
90
  // Handle the `--undefined <sym>` options.
609
90
  for (auto *Arg : Args.filtered(OPT_undefined))
610
2
    handleUndefined(Arg->getValue());
611
90
612
90
  Symbol *EntrySym = nullptr;
613
90
  if (!Config->Relocatable && 
!Config->Entry.empty()81
) {
614
61
    EntrySym = handleUndefined(Config->Entry);
615
61
    if (EntrySym && 
EntrySym->isDefined()60
)
616
60
      EntrySym->ForceExport = true;
617
1
    else
618
1
      error("entry symbol not defined (pass --no-entry to supress): " +
619
1
            Config->Entry);
620
61
  }
621
90
622
90
  if (errorCount())
623
2
    return;
624
88
625
88
  // Handle the `--export <sym>` options
626
88
  // This works like --undefined but also exports the symbol if its found
627
88
  for (auto *Arg : Args.filtered(OPT_export))
628
7
    handleUndefined(Arg->getValue());
629
88
630
88
  // Do link-time optimization if given files are LLVM bitcode files.
631
88
  // This compiles bitcode files into real object files.
632
88
  Symtab->addCombinedLTOObject();
633
88
  if (errorCount())
634
1
    return;
635
87
636
87
  // Resolve any variant symbols that were created due to signature
637
87
  // mismatchs.
638
87
  Symtab->handleSymbolVariants();
639
87
  if (errorCount())
640
2
    return;
641
85
642
85
  for (auto *Arg : Args.filtered(OPT_export)) {
643
7
    Symbol *Sym = Symtab->find(Arg->getValue());
644
7
    if (Sym && 
Sym->isDefined()6
)
645
6
      Sym->ForceExport = true;
646
1
    else if (!Config->AllowUndefined)
647
1
      error(Twine("symbol exported via --export not found: ") +
648
1
            Arg->getValue());
649
7
  }
650
85
651
85
  if (!Config->Relocatable) {
652
76
    // Add synthetic dummies for weak undefined functions.  Must happen
653
76
    // after LTO otherwise functions may not yet have signatures.
654
76
    Symtab->handleWeakUndefines();
655
76
656
76
    // Make sure we have resolved all symbols.
657
76
    if (!Config->AllowUndefined)
658
69
      Symtab->reportRemainingUndefines();
659
76
  }
660
85
661
85
  if (EntrySym)
662
56
    EntrySym->setHidden(false);
663
85
664
85
  if (errorCount())
665
2
    return;
666
83
667
83
  // Do size optimizations: garbage collection
668
83
  markLive();
669
83
670
83
  // Write the result to the file.
671
83
  writeResult();
672
83
}