Coverage Report

Created: 2019-07-24 05:18

/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
217
static void initLLVM() {
60
217
  InitializeAllTargets();
61
217
  InitializeAllTargetMCs();
62
217
  InitializeAllAsmPrinters();
63
217
  InitializeAllAsmParsers();
64
217
}
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
217
                     raw_ostream &error) {
84
217
  errorHandler().logName = args::getFilenameWithoutExe(args[0]);
85
217
  errorHandler().errorOS = &error;
86
217
  errorHandler().colorDiagnostics = error.has_colors();
87
217
  errorHandler().errorLimitExceededMsg =
88
217
      "too many errors emitted, stopping now (use "
89
217
      "-error-limit=0 to see all errors)";
90
217
91
217
  config = make<Configuration>();
92
217
  symtab = make<SymbolTable>();
93
217
94
217
  initLLVM();
95
217
  LinkerDriver().link(args);
96
217
97
217
  // Exit immediately if we don't need to return to the caller.
98
217
  // This saves time because the overhead of calling destructors
99
217
  // for all globally-allocated objects is not negligible.
100
217
  if (canExitEarly)
101
0
    exitLld(errorCount() ? 1 : 0);
102
217
103
217
  freeArena();
104
217
  return !errorCount();
105
217
}
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
217
  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
217
static void handleColorDiagnostics(opt::InputArgList &args) {
132
217
  auto *arg = args.getLastArg(OPT_color_diagnostics, OPT_color_diagnostics_eq,
133
217
                              OPT_no_color_diagnostics);
134
217
  if (!arg)
135
217
    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
217
opt::InputArgList WasmOptTable::parse(ArrayRef<const char *> argv) {
161
217
  SmallVector<const char *, 256> vec(argv.data(), argv.data() + argv.size());
162
217
163
217
  unsigned missingIndex;
164
217
  unsigned missingCount;
165
217
166
217
  // Expand response files (arguments in the form of @<filename>)
167
217
  cl::ExpandResponseFiles(saver, cl::TokenizeGNUCommandLine, vec);
168
217
169
217
  opt::InputArgList args = this->ParseArgs(vec, missingIndex, missingCount);
170
217
171
217
  handleColorDiagnostics(args);
172
217
  for (auto *arg : args.filtered(OPT_UNKNOWN))
173
0
    error("unknown argument: " + arg->getAsString(args));
174
217
  return args;
175
217
}
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
6
static void readImportFile(StringRef filename) {
185
6
  if (Optional<MemoryBufferRef> buf = readFile(filename))
186
6
    for (StringRef sym : args::getLines(*buf))
187
6
      config->allowUndefinedSymbols.insert(sym);
188
6
}
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
320
void LinkerDriver::addFile(StringRef path) {
221
320
  Optional<MemoryBufferRef> buffer = readFile(path);
222
320
  if (!buffer.hasValue())
223
2
    return;
224
318
  MemoryBufferRef mbref = *buffer;
225
318
226
318
  switch (identify_magic(mbref.getBuffer())) {
227
318
  case file_magic::archive: {
228
21
    SmallString<128> importFile = path;
229
21
    path::replace_extension(importFile, ".imports");
230
21
    if (fs::exists(importFile))
231
5
      readImportFile(importFile.str());
232
21
233
21
    // Handle -whole-archive.
234
21
    if (inWholeArchive) {
235
4
      for (MemoryBufferRef &m : getArchiveMembers(mbref))
236
7
        files.push_back(createObjectFile(m, path));
237
4
      return;
238
4
    }
239
17
240
17
    std::unique_ptr<Archive> file =
241
17
        CHECK(Archive::create(mbref), path + ": failed to parse archive");
242
17
243
17
    if (!file->isEmpty() && !file->hasSymbolTable()) {
244
1
      error(mbref.getBufferIdentifier() +
245
1
            ": archive has no index; run ranlib to add one");
246
1
    }
247
17
248
17
    files.push_back(make<ArchiveFile>(mbref));
249
17
    return;
250
17
  }
251
297
  case file_magic::bitcode:
252
297
  case file_magic::wasm_object:
253
297
    files.push_back(createObjectFile(mbref));
254
297
    break;
255
297
  default:
256
0
    error("unknown file type: " + mbref.getBufferIdentifier());
257
318
  }
258
318
}
259
260
// Add a given library by searching it from input search paths.
261
0
void LinkerDriver::addLibrary(StringRef name) {
262
0
  for (StringRef dir : config->searchPaths) {
263
0
    if (Optional<std::string> s = findFile(dir, "lib" + name + ".a")) {
264
0
      addFile(*s);
265
0
      return;
266
0
    }
267
0
  }
268
0
269
0
  error("unable to find library -l" + name);
270
0
}
271
272
215
void LinkerDriver::createFiles(opt::InputArgList &args) {
273
891
  for (auto *arg : args) {
274
891
    switch (arg->getOption().getID()) {
275
891
    case OPT_l:
276
0
      addLibrary(arg->getValue());
277
0
      break;
278
891
    case OPT_INPUT:
279
320
      addFile(arg->getValue());
280
320
      break;
281
891
    case OPT_whole_archive:
282
6
      inWholeArchive = true;
283
6
      break;
284
891
    case OPT_no_whole_archive:
285
3
      inWholeArchive = false;
286
3
      break;
287
891
    }
288
891
  }
289
215
}
290
291
217
static StringRef getEntry(opt::InputArgList &args) {
292
217
  auto *arg = args.getLastArg(OPT_entry, OPT_no_entry);
293
217
  if (!arg) {
294
148
    if (args.hasArg(OPT_relocatable))
295
19
      return "";
296
129
    if (args.hasArg(OPT_shared))
297
4
      return "__wasm_call_ctors";
298
125
    return "_start";
299
125
  }
300
69
  if (arg->getOption().getID() == OPT_no_entry)
301
58
    return "";
302
11
  return arg->getValue();
303
11
}
304
305
// Initializes Config members by the command line options.
306
static void readConfigs(opt::InputArgList &args) {
307
  config->allowUndefined = args.hasArg(OPT_allow_undefined);
308
  config->checkFeatures =
309
      args.hasFlag(OPT_check_features, OPT_no_check_features, true);
310
  config->compressRelocations = args.hasArg(OPT_compress_relocations);
311
  config->demangle = args.hasFlag(OPT_demangle, OPT_no_demangle, true);
312
  config->disableVerify = args.hasArg(OPT_disable_verify);
313
  config->emitRelocs = args.hasArg(OPT_emit_relocs);
314
  config->entry = getEntry(args);
315
  config->exportAll = args.hasArg(OPT_export_all);
316
  config->exportDynamic = args.hasFlag(OPT_export_dynamic,
317
      OPT_no_export_dynamic, false);
318
  config->exportTable = args.hasArg(OPT_export_table);
319
  errorHandler().fatalWarnings =
320
      args.hasFlag(OPT_fatal_warnings, OPT_no_fatal_warnings, false);
321
  config->importMemory = args.hasArg(OPT_import_memory);
322
  config->sharedMemory = args.hasArg(OPT_shared_memory);
323
  config->passiveSegments = args.hasFlag(
324
      OPT_passive_segments, OPT_active_segments, config->sharedMemory);
325
  config->importTable = args.hasArg(OPT_import_table);
326
  config->ltoo = args::getInteger(args, OPT_lto_O, 2);
327
  config->ltoPartitions = args::getInteger(args, OPT_lto_partitions, 1);
328
  config->optimize = args::getInteger(args, OPT_O, 0);
329
  config->outputFile = args.getLastArgValue(OPT_o);
330
  config->relocatable = args.hasArg(OPT_relocatable);
331
  config->gcSections =
332
      args.hasFlag(OPT_gc_sections, OPT_no_gc_sections, !config->relocatable);
333
  config->mergeDataSegments =
334
      args.hasFlag(OPT_merge_data_segments, OPT_no_merge_data_segments,
335
                   !config->relocatable);
336
  config->pie = args.hasFlag(OPT_pie, OPT_no_pie, false);
337
  config->printGcSections =
338
      args.hasFlag(OPT_print_gc_sections, OPT_no_print_gc_sections, false);
339
  config->saveTemps = args.hasArg(OPT_save_temps);
340
  config->searchPaths = args::getStrings(args, OPT_L);
341
  config->shared = args.hasArg(OPT_shared);
342
  config->stripAll = args.hasArg(OPT_strip_all);
343
  config->stripDebug = args.hasArg(OPT_strip_debug);
344
  config->stackFirst = args.hasArg(OPT_stack_first);
345
  config->trace = args.hasArg(OPT_trace);
346
  config->thinLTOCacheDir = args.getLastArgValue(OPT_thinlto_cache_dir);
347
  config->thinLTOCachePolicy = CHECK(
348
      parseCachePruningPolicy(args.getLastArgValue(OPT_thinlto_cache_policy)),
349
      "--thinlto-cache-policy: invalid cache policy");
350
  config->thinLTOJobs = args::getInteger(args, OPT_thinlto_jobs, -1u);
351
  errorHandler().verbose = args.hasArg(OPT_verbose);
352
  LLVM_DEBUG(errorHandler().verbose = true);
353
  threadsEnabled = args.hasFlag(OPT_threads, OPT_no_threads, true);
354
355
  config->initialMemory = args::getInteger(args, OPT_initial_memory, 0);
356
  config->globalBase = args::getInteger(args, OPT_global_base, 1024);
357
  config->maxMemory = args::getInteger(args, OPT_max_memory, 0);
358
  config->zStackSize =
359
      args::getZOptionValue(args, OPT_z, "stack-size", WasmPageSize);
360
361
  if (auto *arg = args.getLastArg(OPT_features)) {
362
    config->features =
363
        llvm::Optional<std::vector<std::string>>(std::vector<std::string>());
364
    for (StringRef s : arg->getValues())
365
      config->features->push_back(s);
366
  }
367
}
368
369
// Some Config members do not directly correspond to any particular
370
// command line options, but computed based on other Config values.
371
// This function initialize such members. See Config.h for the details
372
// of these values.
373
217
static void setConfigs() {
374
217
  config->isPic = config->pie || 
config->shared215
;
375
217
376
217
  if (config->isPic) {
377
6
    if (config->exportTable)
378
0
      error("-shared/-pie is incompatible with --export-table");
379
6
    config->importTable = true;
380
6
  }
381
217
382
217
  if (config->shared) {
383
4
    config->importMemory = true;
384
4
    config->exportDynamic = true;
385
4
    config->allowUndefined = true;
386
4
  }
387
217
}
388
389
// Some command line options or some combinations of them are not allowed.
390
// This function checks for such errors.
391
217
static void checkOptions(opt::InputArgList &args) {
392
217
  if (!config->stripDebug && 
!config->stripAll213
&&
config->compressRelocations211
)
393
1
    error("--compress-relocations is incompatible with output debug"
394
1
          " information. Please pass --strip-debug or --strip-all");
395
217
396
217
  if (config->ltoo > 3)
397
2
    error("invalid optimization level for LTO: " + Twine(config->ltoo));
398
217
  if (config->ltoPartitions == 0)
399
0
    error("--lto-partitions: number of threads must be > 0");
400
217
  if (config->thinLTOJobs == 0)
401
0
    error("--thinlto-jobs: number of threads must be > 0");
402
217
403
217
  if (config->pie && 
config->shared2
)
404
0
    error("-shared and -pie may not be used together");
405
217
406
217
  if (config->outputFile.empty())
407
4
    error("no output file specified");
408
217
409
217
  if (config->importTable && 
config->exportTable8
)
410
1
    error("--import-table and --export-table may not be used together");
411
217
412
217
  if (config->relocatable) {
413
21
    if (!config->entry.empty())
414
0
      error("entry point specified for relocatable output file");
415
21
    if (config->gcSections)
416
1
      error("-r and --gc-sections may not be used together");
417
21
    if (config->compressRelocations)
418
0
      error("-r -and --compress-relocations may not be used together");
419
21
    if (args.hasArg(OPT_undefined))
420
0
      error("-r -and --undefined may not be used together");
421
21
    if (config->pie)
422
0
      error("-r and -pie may not be used together");
423
21
  }
424
217
}
425
426
// Force Sym to be entered in the output. Used for -u or equivalent.
427
159
static Symbol *handleUndefined(StringRef name) {
428
159
  Symbol *sym = symtab->find(name);
429
159
  if (!sym)
430
8
    return nullptr;
431
151
432
151
  // Since symbol S may not be used inside the program, LTO may
433
151
  // eliminate it. Mark the symbol as "used" to prevent it.
434
151
  sym->isUsedInRegularObj = true;
435
151
436
151
  if (auto *lazySym = dyn_cast<LazySymbol>(sym))
437
3
    lazySym->fetch();
438
151
439
151
  return sym;
440
151
}
441
442
static UndefinedGlobal *
443
18
createUndefinedGlobal(StringRef name, llvm::wasm::WasmGlobalType *type) {
444
18
  auto *sym =
445
18
      cast<UndefinedGlobal>(symtab->addUndefinedGlobal(name, name,
446
18
                                                       defaultModule, 0,
447
18
                                                       nullptr, type));
448
18
  config->allowUndefinedSymbols.insert(sym->getName());
449
18
  sym->isUsedInRegularObj = true;
450
18
  return sym;
451
18
}
452
453
54
static GlobalSymbol *createGlobalVariable(StringRef name, bool isMutable) {
454
54
  llvm::wasm::WasmGlobal wasmGlobal;
455
54
  wasmGlobal.Type = {WASM_TYPE_I32, isMutable};
456
54
  wasmGlobal.InitExpr.Value.Int32 = 0;
457
54
  wasmGlobal.InitExpr.Opcode = WASM_OPCODE_I32_CONST;
458
54
  wasmGlobal.SymbolName = name;
459
54
  return symtab->addSyntheticGlobal(name, WASM_SYMBOL_VISIBILITY_HIDDEN,
460
54
                                    make<InputGlobal>(wasmGlobal, nullptr));
461
54
}
462
463
// Create ABI-defined synthetic symbols
464
194
static void createSyntheticSymbols() {
465
194
  static WasmSignature nullSignature = {{}, {}};
466
194
  static WasmSignature i32ArgSignature = {{}, {ValType::I32}};
467
194
  static llvm::wasm::WasmGlobalType globalTypeI32 = {WASM_TYPE_I32, false};
468
194
  static llvm::wasm::WasmGlobalType mutableGlobalTypeI32 = {WASM_TYPE_I32,
469
194
                                                            true};
470
194
471
194
  if (!config->relocatable) {
472
194
    WasmSym::callCtors = symtab->addSyntheticFunction(
473
194
        "__wasm_call_ctors", WASM_SYMBOL_VISIBILITY_HIDDEN,
474
194
        make<SyntheticFunction>(nullSignature, "__wasm_call_ctors"));
475
194
476
194
    if (config->passiveSegments) {
477
11
      // Passive segments are used to avoid memory being reinitialized on each
478
11
      // thread's instantiation. These passive segments are initialized and
479
11
      // dropped in __wasm_init_memory, which is the first function called from
480
11
      // __wasm_call_ctors.
481
11
      WasmSym::initMemory = symtab->addSyntheticFunction(
482
11
          "__wasm_init_memory", WASM_SYMBOL_VISIBILITY_HIDDEN,
483
11
          make<SyntheticFunction>(nullSignature, "__wasm_init_memory"));
484
11
    }
485
194
486
194
    if (config->isPic) {
487
6
      // For PIC code we create a synthetic function __wasm_apply_relocs which
488
6
      // is called from __wasm_call_ctors before the user-level constructors.
489
6
      WasmSym::applyRelocs = symtab->addSyntheticFunction(
490
6
          "__wasm_apply_relocs", WASM_SYMBOL_VISIBILITY_HIDDEN,
491
6
          make<SyntheticFunction>(nullSignature, "__wasm_apply_relocs"));
492
6
    }
493
194
  }
494
194
495
194
  if (!config->shared)
496
190
    WasmSym::dataEnd = symtab->addOptionalDataSymbol("__data_end");
497
194
498
194
  if (config->isPic) {
499
6
    WasmSym::stackPointer =
500
6
        createUndefinedGlobal("__stack_pointer", &mutableGlobalTypeI32);
501
6
    // For PIC code, we import two global variables (__memory_base and
502
6
    // __table_base) from the environment and use these as the offset at
503
6
    // which to load our static data and function table.
504
6
    // See:
505
6
    // https://github.com/WebAssembly/tool-conventions/blob/master/DynamicLinking.md
506
6
    WasmSym::memoryBase =
507
6
        createUndefinedGlobal("__memory_base", &globalTypeI32);
508
6
    WasmSym::tableBase = createUndefinedGlobal("__table_base", &globalTypeI32);
509
6
    WasmSym::memoryBase->markLive();
510
6
    WasmSym::tableBase->markLive();
511
188
  } else {
512
188
    llvm::wasm::WasmGlobal global;
513
188
    global.Type = {WASM_TYPE_I32, true};
514
188
    global.InitExpr.Value.Int32 = 0;
515
188
    global.InitExpr.Opcode = WASM_OPCODE_I32_CONST;
516
188
    global.SymbolName = "__stack_pointer";
517
188
    auto *stackPointer = make<InputGlobal>(global, nullptr);
518
188
    stackPointer->live = true;
519
188
    // For non-PIC code
520
188
    // TODO(sbc): Remove WASM_SYMBOL_VISIBILITY_HIDDEN when the mutable global
521
188
    // spec proposal is implemented in all major browsers.
522
188
    // See: https://github.com/WebAssembly/mutable-global
523
188
    WasmSym::stackPointer = symtab->addSyntheticGlobal(
524
188
        "__stack_pointer", WASM_SYMBOL_VISIBILITY_HIDDEN, stackPointer);
525
188
    WasmSym::globalBase = symtab->addOptionalDataSymbol("__global_base");
526
188
    WasmSym::heapBase = symtab->addOptionalDataSymbol("__heap_base");
527
188
  }
528
194
529
194
  if (config->sharedMemory && 
!config->shared18
) {
530
18
    WasmSym::tlsBase = createGlobalVariable("__tls_base", true);
531
18
    WasmSym::tlsSize = createGlobalVariable("__tls_size", false);
532
18
    WasmSym::tlsAlign = createGlobalVariable("__tls_align", false);
533
18
    WasmSym::initTLS = symtab->addSyntheticFunction(
534
18
        "__wasm_init_tls", WASM_SYMBOL_VISIBILITY_HIDDEN,
535
18
        make<SyntheticFunction>(i32ArgSignature, "__wasm_init_tls"));
536
18
  }
537
194
538
194
  WasmSym::dsoHandle = symtab->addSyntheticDataSymbol(
539
194
      "__dso_handle", WASM_SYMBOL_VISIBILITY_HIDDEN);
540
194
}
541
542
// Reconstructs command line arguments so that so that you can re-run
543
// the same command with the same inputs. This is for --reproduce.
544
1
static std::string createResponseFile(const opt::InputArgList &args) {
545
1
  SmallString<0> data;
546
1
  raw_svector_ostream os(data);
547
1
548
1
  // Copy the command line to the output while rewriting paths.
549
3
  for (auto *arg : args) {
550
3
    switch (arg->getOption().getID()) {
551
3
    case OPT_reproduce:
552
1
      break;
553
3
    case OPT_INPUT:
554
1
      os << quote(relativeToRoot(arg->getValue())) << "\n";
555
1
      break;
556
3
    case OPT_o:
557
1
      // If -o path contains directories, "lld @response.txt" will likely
558
1
      // fail because the archive we are creating doesn't contain empty
559
1
      // directories for the output path (-o doesn't create directories).
560
1
      // Strip directories to prevent the issue.
561
1
      os << "-o " << quote(sys::path::filename(arg->getValue())) << "\n";
562
1
      break;
563
3
    default:
564
0
      os << toString(*arg) << "\n";
565
3
    }
566
3
  }
567
1
  return data.str();
568
1
}
569
570
// The --wrap option is a feature to rename symbols so that you can write
571
// wrappers for existing functions. If you pass `-wrap=foo`, all
572
// occurrences of symbol `foo` are resolved to `wrap_foo` (so, you are
573
// expected to write `wrap_foo` function as a wrapper). The original
574
// symbol becomes accessible as `real_foo`, so you can call that from your
575
// wrapper.
576
//
577
// This data structure is instantiated for each -wrap option.
578
struct WrappedSymbol {
579
  Symbol *sym;
580
  Symbol *real;
581
  Symbol *wrap;
582
};
583
584
static Symbol *addUndefined(StringRef name) {
585
  return symtab->addUndefinedFunction(name, "", "", 0, nullptr, nullptr, false);
586
}
587
588
// Handles -wrap option.
589
//
590
// This function instantiates wrapper symbols. At this point, they seem
591
// like they are not being used at all, so we explicitly set some flags so
592
// that LTO won't eliminate them.
593
static std::vector<WrappedSymbol> addWrappedSymbols(opt::InputArgList &args) {
594
  std::vector<WrappedSymbol> v;
595
  DenseSet<StringRef> seen;
596
597
  for (auto *arg : args.filtered(OPT_wrap)) {
598
    StringRef name = arg->getValue();
599
    if (!seen.insert(name).second)
600
      continue;
601
602
    Symbol *sym = symtab->find(name);
603
    if (!sym)
604
      continue;
605
606
    Symbol *real = addUndefined(saver.save("__real_" + name));
607
    Symbol *wrap = addUndefined(saver.save("__wrap_" + name));
608
    v.push_back({sym, real, wrap});
609
610
    // We want to tell LTO not to inline symbols to be overwritten
611
    // because LTO doesn't know the final symbol contents after renaming.
612
    real->canInline = false;
613
    sym->canInline = false;
614
615
    // Tell LTO not to eliminate these symbols.
616
    sym->isUsedInRegularObj = true;
617
    wrap->isUsedInRegularObj = true;
618
    real->isUsedInRegularObj = false;
619
  }
620
  return v;
621
}
622
623
// Do renaming for -wrap by updating pointers to symbols.
624
//
625
// When this function is executed, only InputFiles and symbol table
626
// contain pointers to symbol objects. We visit them to replace pointers,
627
// so that wrapped symbols are swapped as instructed by the command line.
628
static void wrapSymbols(ArrayRef<WrappedSymbol> wrapped) {
629
  DenseMap<Symbol *, Symbol *> map;
630
  for (const WrappedSymbol &w : wrapped) {
631
    map[w.sym] = w.wrap;
632
    map[w.real] = w.sym;
633
  }
634
635
  // Update pointers in input files.
636
2
  parallelForEach(symtab->objectFiles, [&](InputFile *file) {
637
2
    MutableArrayRef<Symbol *> syms = file->getMutableSymbols();
638
10
    for (size_t i = 0, e = syms.size(); i != e; 
++i8
)
639
8
      if (Symbol *s = map.lookup(syms[i]))
640
4
        syms[i] = s;
641
2
  });
642
643
  // Update pointers in the symbol table.
644
  for (const WrappedSymbol &w : wrapped)
645
    symtab->wrap(w.sym, w.real, w.wrap);
646
}
647
648
217
void LinkerDriver::link(ArrayRef<const char *> argsArr) {
649
217
  WasmOptTable parser;
650
217
  opt::InputArgList args = parser.parse(argsArr.slice(1));
651
217
652
217
  // Handle --help
653
217
  if (args.hasArg(OPT_help)) {
654
0
    parser.PrintHelp(outs(),
655
0
                     (std::string(argsArr[0]) + " [options] file...").c_str(),
656
0
                     "LLVM Linker", false);
657
0
    return;
658
0
  }
659
217
660
217
  // Handle --version
661
217
  if (args.hasArg(OPT_version) || args.hasArg(OPT_v)) {
662
0
    outs() << getLLDVersion() << "\n";
663
0
    return;
664
0
  }
665
217
666
217
  // Handle --reproduce
667
217
  if (auto *arg = args.getLastArg(OPT_reproduce)) {
668
1
    StringRef path = arg->getValue();
669
1
    Expected<std::unique_ptr<TarWriter>> errOrWriter =
670
1
        TarWriter::create(path, path::stem(path));
671
1
    if (errOrWriter) {
672
1
      tar = std::move(*errOrWriter);
673
1
      tar->append("response.txt", createResponseFile(args));
674
1
      tar->append("version.txt", getLLDVersion() + "\n");
675
1
    } else {
676
0
      error("--reproduce: " + toString(errOrWriter.takeError()));
677
0
    }
678
1
  }
679
217
680
217
  // Parse and evaluate -mllvm options.
681
217
  std::vector<const char *> v;
682
217
  v.push_back("wasm-ld (LLVM option parsing)");
683
217
  for (auto *arg : args.filtered(OPT_mllvm))
684
2
    v.push_back(arg->getValue());
685
217
  cl::ParseCommandLineOptions(v.size(), v.data());
686
217
687
217
  errorHandler().errorLimit = args::getInteger(args, OPT_error_limit, 20);
688
217
689
217
  readConfigs(args);
690
217
  setConfigs();
691
217
  checkOptions(args);
692
217
693
217
  if (auto *arg = args.getLastArg(OPT_allow_undefined_file))
694
1
    readImportFile(arg->getValue());
695
217
696
217
  if (!args.hasArg(OPT_INPUT)) {
697
2
    error("no input files");
698
2
    return;
699
2
  }
700
215
701
215
  // Handle --trace-symbol.
702
215
  for (auto *arg : args.filtered(OPT_trace_symbol))
703
5
    symtab->trace(arg->getValue());
704
215
705
215
  for (auto *arg : args.filtered(OPT_export))
706
26
    config->exportedSymbols.insert(arg->getValue());
707
215
708
215
  if (!config->relocatable)
709
194
    createSyntheticSymbols();
710
215
711
215
  createFiles(args);
712
215
  if (errorCount())
713
8
    return;
714
207
715
207
  // Add all files to the symbol table. This will add almost all
716
207
  // symbols that we need to the symbol table.
717
207
  for (InputFile *f : files)
718
312
    symtab->addFile(f);
719
207
  if (errorCount())
720
4
    return;
721
203
722
203
  // Handle the `--undefined <sym>` options.
723
203
  for (auto *arg : args.filtered(OPT_undefined))
724
6
    handleUndefined(arg->getValue());
725
203
726
203
  // Handle the `--export <sym>` options
727
203
  // This works like --undefined but also exports the symbol if its found
728
203
  for (auto *arg : args.filtered(OPT_export))
729
26
    handleUndefined(arg->getValue());
730
203
731
203
  Symbol *entrySym = nullptr;
732
203
  if (!config->relocatable && 
!config->entry.empty()183
) {
733
127
    entrySym = handleUndefined(config->entry);
734
127
    if (entrySym && 
entrySym->isDefined()124
)
735
124
      entrySym->forceExport = true;
736
3
    else
737
3
      error("entry symbol not defined (pass --no-entry to supress): " +
738
3
            config->entry);
739
127
  }
740
203
741
203
  if (errorCount())
742
4
    return;
743
199
744
199
  // Create wrapped symbols for -wrap option.
745
199
  std::vector<WrappedSymbol> wrapped = addWrappedSymbols(args);
746
199
747
199
  // Do link-time optimization if given files are LLVM bitcode files.
748
199
  // This compiles bitcode files into real object files.
749
199
  symtab->addCombinedLTOObject();
750
199
  if (errorCount())
751
1
    return;
752
198
753
198
  // Resolve any variant symbols that were created due to signature
754
198
  // mismatchs.
755
198
  symtab->handleSymbolVariants();
756
198
  if (errorCount())
757
3
    return;
758
195
759
195
  // Apply symbol renames for -wrap.
760
195
  if (!wrapped.empty())
761
2
    wrapSymbols(wrapped);
762
195
763
195
  for (auto *arg : args.filtered(OPT_export)) {
764
26
    Symbol *sym = symtab->find(arg->getValue());
765
26
    if (sym && 
sym->isDefined()23
)
766
23
      sym->forceExport = true;
767
3
    else if (!config->allowUndefined)
768
2
      error(Twine("symbol exported via --export not found: ") +
769
2
            arg->getValue());
770
26
  }
771
195
772
195
  if (!config->relocatable) {
773
175
    // Add synthetic dummies for weak undefined functions.  Must happen
774
175
    // after LTO otherwise functions may not yet have signatures.
775
175
    symtab->handleWeakUndefines();
776
175
  }
777
195
778
195
  if (entrySym)
779
119
    entrySym->setHidden(false);
780
195
781
195
  if (errorCount())
782
2
    return;
783
193
784
193
  // Do size optimizations: garbage collection
785
193
  markLive();
786
193
787
193
  // Write the result to the file.
788
193
  writeResult();
789
193
}