xref: /llvm-project-15.0.7/lld/wasm/Driver.cpp (revision fe2bd543)
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/Filesystem.h"
19 #include "lld/Common/Memory.h"
20 #include "lld/Common/Reproduce.h"
21 #include "lld/Common/Strings.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/Host.h"
29 #include "llvm/Support/Parallel.h"
30 #include "llvm/Support/Path.h"
31 #include "llvm/Support/Process.h"
32 #include "llvm/Support/TarWriter.h"
33 #include "llvm/Support/TargetSelect.h"
34 
35 #define DEBUG_TYPE "lld"
36 
37 using namespace llvm;
38 using namespace llvm::object;
39 using namespace llvm::sys;
40 using namespace llvm::wasm;
41 
42 namespace lld {
43 namespace wasm {
44 Configuration *config;
45 
46 namespace {
47 
48 // Create enum with OPT_xxx values for each option in Options.td
49 enum {
50   OPT_INVALID = 0,
51 #define OPTION(_1, _2, ID, _4, _5, _6, _7, _8, _9, _10, _11, _12) OPT_##ID,
52 #include "Options.inc"
53 #undef OPTION
54 };
55 
56 // This function is called on startup. We need this for LTO since
57 // LTO calls LLVM functions to compile bitcode files to native code.
58 // Technically this can be delayed until we read bitcode files, but
59 // we don't bother to do lazily because the initialization is fast.
60 static void initLLVM() {
61   InitializeAllTargets();
62   InitializeAllTargetMCs();
63   InitializeAllAsmPrinters();
64   InitializeAllAsmParsers();
65 }
66 
67 class LinkerDriver {
68 public:
69   void link(ArrayRef<const char *> argsArr);
70 
71 private:
72   void createFiles(opt::InputArgList &args);
73   void addFile(StringRef path);
74   void addLibrary(StringRef name);
75 
76   // True if we are in --whole-archive and --no-whole-archive.
77   bool inWholeArchive = false;
78 
79   std::vector<InputFile *> files;
80 };
81 } // anonymous namespace
82 
83 bool link(ArrayRef<const char *> args, bool canExitEarly, raw_ostream &stdoutOS,
84           raw_ostream &stderrOS) {
85   lld::stdoutOS = &stdoutOS;
86   lld::stderrOS = &stderrOS;
87 
88   errorHandler().cleanupCallback = []() { freeArena(); };
89 
90   errorHandler().logName = args::getFilenameWithoutExe(args[0]);
91   errorHandler().errorLimitExceededMsg =
92       "too many errors emitted, stopping now (use "
93       "-error-limit=0 to see all errors)";
94   stderrOS.enable_colors(stderrOS.has_colors());
95 
96   config = make<Configuration>();
97   symtab = make<SymbolTable>();
98 
99   initLLVM();
100   LinkerDriver().link(args);
101 
102   // Exit immediately if we don't need to return to the caller.
103   // This saves time because the overhead of calling destructors
104   // for all globally-allocated objects is not negligible.
105   if (canExitEarly)
106     exitLld(errorCount() ? 1 : 0);
107 
108   return !errorCount();
109 }
110 
111 // Create prefix string literals used in Options.td
112 #define PREFIX(NAME, VALUE) const char *const NAME[] = VALUE;
113 #include "Options.inc"
114 #undef PREFIX
115 
116 // Create table mapping all options defined in Options.td
117 static const opt::OptTable::Info optInfo[] = {
118 #define OPTION(X1, X2, ID, KIND, GROUP, ALIAS, X7, X8, X9, X10, X11, X12)      \
119   {X1, X2, X10,         X11,         OPT_##ID, opt::Option::KIND##Class,       \
120    X9, X8, OPT_##GROUP, OPT_##ALIAS, X7,       X12},
121 #include "Options.inc"
122 #undef OPTION
123 };
124 
125 namespace {
126 class WasmOptTable : public llvm::opt::OptTable {
127 public:
128   WasmOptTable() : OptTable(optInfo) {}
129   opt::InputArgList parse(ArrayRef<const char *> argv);
130 };
131 } // namespace
132 
133 // Set color diagnostics according to -color-diagnostics={auto,always,never}
134 // or -no-color-diagnostics flags.
135 static void handleColorDiagnostics(opt::InputArgList &args) {
136   auto *arg = args.getLastArg(OPT_color_diagnostics, OPT_color_diagnostics_eq,
137                               OPT_no_color_diagnostics);
138   if (!arg)
139     return;
140   if (arg->getOption().getID() == OPT_color_diagnostics) {
141     lld::errs().enable_colors(true);
142   } else if (arg->getOption().getID() == OPT_no_color_diagnostics) {
143     lld::errs().enable_colors(false);
144   } else {
145     StringRef s = arg->getValue();
146     if (s == "always")
147       lld::errs().enable_colors(true);
148     else if (s == "never")
149       lld::errs().enable_colors(false);
150     else if (s != "auto")
151       error("unknown option: --color-diagnostics=" + s);
152   }
153 }
154 
155 static cl::TokenizerCallback getQuotingStyle(opt::InputArgList &args) {
156   if (auto *arg = args.getLastArg(OPT_rsp_quoting)) {
157     StringRef s = arg->getValue();
158     if (s != "windows" && s != "posix")
159       error("invalid response file quoting: " + s);
160     if (s == "windows")
161       return cl::TokenizeWindowsCommandLine;
162     return cl::TokenizeGNUCommandLine;
163   }
164   if (Triple(sys::getProcessTriple()).isOSWindows())
165     return cl::TokenizeWindowsCommandLine;
166   return cl::TokenizeGNUCommandLine;
167 }
168 
169 // Find a file by concatenating given paths.
170 static Optional<std::string> findFile(StringRef path1, const Twine &path2) {
171   SmallString<128> s;
172   path::append(s, path1, path2);
173   if (fs::exists(s))
174     return std::string(s);
175   return None;
176 }
177 
178 opt::InputArgList WasmOptTable::parse(ArrayRef<const char *> argv) {
179   SmallVector<const char *, 256> vec(argv.data(), argv.data() + argv.size());
180 
181   unsigned missingIndex;
182   unsigned missingCount;
183 
184   // We need to get the quoting style for response files before parsing all
185   // options so we parse here before and ignore all the options but
186   // --rsp-quoting.
187   opt::InputArgList args = this->ParseArgs(vec, missingIndex, missingCount);
188 
189   // Expand response files (arguments in the form of @<filename>)
190   // and then parse the argument again.
191   cl::ExpandResponseFiles(saver, getQuotingStyle(args), vec);
192   args = this->ParseArgs(vec, missingIndex, missingCount);
193 
194   handleColorDiagnostics(args);
195   for (auto *arg : args.filtered(OPT_UNKNOWN))
196     error("unknown argument: " + arg->getAsString(args));
197   return args;
198 }
199 
200 // Currently we allow a ".imports" to live alongside a library. This can
201 // be used to specify a list of symbols which can be undefined at link
202 // time (imported from the environment.  For example libc.a include an
203 // import file that lists the syscall functions it relies on at runtime.
204 // In the long run this information would be better stored as a symbol
205 // attribute/flag in the object file itself.
206 // See: https://github.com/WebAssembly/tool-conventions/issues/35
207 static void readImportFile(StringRef filename) {
208   if (Optional<MemoryBufferRef> buf = readFile(filename))
209     for (StringRef sym : args::getLines(*buf))
210       config->allowUndefinedSymbols.insert(sym);
211 }
212 
213 // Returns slices of MB by parsing MB as an archive file.
214 // Each slice consists of a member file in the archive.
215 std::vector<MemoryBufferRef> static getArchiveMembers(MemoryBufferRef mb) {
216   std::unique_ptr<Archive> file =
217       CHECK(Archive::create(mb),
218             mb.getBufferIdentifier() + ": failed to parse archive");
219 
220   std::vector<MemoryBufferRef> v;
221   Error err = Error::success();
222   for (const Archive::Child &c : file->children(err)) {
223     MemoryBufferRef mbref =
224         CHECK(c.getMemoryBufferRef(),
225               mb.getBufferIdentifier() +
226                   ": could not get the buffer for a child of the archive");
227     v.push_back(mbref);
228   }
229   if (err)
230     fatal(mb.getBufferIdentifier() +
231           ": Archive::children failed: " + toString(std::move(err)));
232 
233   // Take ownership of memory buffers created for members of thin archives.
234   for (std::unique_ptr<MemoryBuffer> &mb : file->takeThinBuffers())
235     make<std::unique_ptr<MemoryBuffer>>(std::move(mb));
236 
237   return v;
238 }
239 
240 void LinkerDriver::addFile(StringRef path) {
241   Optional<MemoryBufferRef> buffer = readFile(path);
242   if (!buffer.hasValue())
243     return;
244   MemoryBufferRef mbref = *buffer;
245 
246   switch (identify_magic(mbref.getBuffer())) {
247   case file_magic::archive: {
248     SmallString<128> importFile = path;
249     path::replace_extension(importFile, ".imports");
250     if (fs::exists(importFile))
251       readImportFile(importFile.str());
252 
253     // Handle -whole-archive.
254     if (inWholeArchive) {
255       for (MemoryBufferRef &m : getArchiveMembers(mbref))
256         files.push_back(createObjectFile(m, path));
257       return;
258     }
259 
260     std::unique_ptr<Archive> file =
261         CHECK(Archive::create(mbref), path + ": failed to parse archive");
262 
263     if (!file->isEmpty() && !file->hasSymbolTable()) {
264       error(mbref.getBufferIdentifier() +
265             ": archive has no index; run ranlib to add one");
266     }
267 
268     files.push_back(make<ArchiveFile>(mbref));
269     return;
270   }
271   case file_magic::bitcode:
272   case file_magic::wasm_object:
273     files.push_back(createObjectFile(mbref));
274     break;
275   default:
276     error("unknown file type: " + mbref.getBufferIdentifier());
277   }
278 }
279 
280 // Add a given library by searching it from input search paths.
281 void LinkerDriver::addLibrary(StringRef name) {
282   for (StringRef dir : config->searchPaths) {
283     if (Optional<std::string> s = findFile(dir, "lib" + name + ".a")) {
284       addFile(*s);
285       return;
286     }
287   }
288 
289   error("unable to find library -l" + name);
290 }
291 
292 void LinkerDriver::createFiles(opt::InputArgList &args) {
293   for (auto *arg : args) {
294     switch (arg->getOption().getID()) {
295     case OPT_l:
296       addLibrary(arg->getValue());
297       break;
298     case OPT_INPUT:
299       addFile(arg->getValue());
300       break;
301     case OPT_whole_archive:
302       inWholeArchive = true;
303       break;
304     case OPT_no_whole_archive:
305       inWholeArchive = false;
306       break;
307     }
308   }
309   if (files.empty() && errorCount() == 0)
310     error("no input files");
311 }
312 
313 static StringRef getEntry(opt::InputArgList &args) {
314   auto *arg = args.getLastArg(OPT_entry, OPT_no_entry);
315   if (!arg) {
316     if (args.hasArg(OPT_relocatable))
317       return "";
318     if (args.hasArg(OPT_shared))
319       return "__wasm_call_ctors";
320     return "_start";
321   }
322   if (arg->getOption().getID() == OPT_no_entry)
323     return "";
324   return arg->getValue();
325 }
326 
327 // Initializes Config members by the command line options.
328 static void readConfigs(opt::InputArgList &args) {
329   config->allowUndefined = args.hasArg(OPT_allow_undefined);
330   config->checkFeatures =
331       args.hasFlag(OPT_check_features, OPT_no_check_features, true);
332   config->compressRelocations = args.hasArg(OPT_compress_relocations);
333   config->demangle = args.hasFlag(OPT_demangle, OPT_no_demangle, true);
334   config->disableVerify = args.hasArg(OPT_disable_verify);
335   config->emitRelocs = args.hasArg(OPT_emit_relocs);
336   config->experimentalPic = args.hasArg(OPT_experimental_pic);
337   config->entry = getEntry(args);
338   config->exportAll = args.hasArg(OPT_export_all);
339   config->exportTable = args.hasArg(OPT_export_table);
340   config->growableTable = args.hasArg(OPT_growable_table);
341   errorHandler().fatalWarnings =
342       args.hasFlag(OPT_fatal_warnings, OPT_no_fatal_warnings, false);
343   config->importMemory = args.hasArg(OPT_import_memory);
344   config->sharedMemory = args.hasArg(OPT_shared_memory);
345   config->importTable = args.hasArg(OPT_import_table);
346   config->ltoo = args::getInteger(args, OPT_lto_O, 2);
347   config->ltoPartitions = args::getInteger(args, OPT_lto_partitions, 1);
348   config->mapFile = args.getLastArgValue(OPT_Map);
349   config->optimize = args::getInteger(args, OPT_O, 0);
350   config->outputFile = args.getLastArgValue(OPT_o);
351   config->relocatable = args.hasArg(OPT_relocatable);
352   config->gcSections =
353       args.hasFlag(OPT_gc_sections, OPT_no_gc_sections, !config->relocatable);
354   config->mergeDataSegments =
355       args.hasFlag(OPT_merge_data_segments, OPT_no_merge_data_segments,
356                    !config->relocatable);
357   config->pie = args.hasFlag(OPT_pie, OPT_no_pie, false);
358   config->printGcSections =
359       args.hasFlag(OPT_print_gc_sections, OPT_no_print_gc_sections, false);
360   config->saveTemps = args.hasArg(OPT_save_temps);
361   config->searchPaths = args::getStrings(args, OPT_L);
362   config->shared = args.hasArg(OPT_shared);
363   config->stripAll = args.hasArg(OPT_strip_all);
364   config->stripDebug = args.hasArg(OPT_strip_debug);
365   config->stackFirst = args.hasArg(OPT_stack_first);
366   config->trace = args.hasArg(OPT_trace);
367   config->thinLTOCacheDir = args.getLastArgValue(OPT_thinlto_cache_dir);
368   config->thinLTOCachePolicy = CHECK(
369       parseCachePruningPolicy(args.getLastArgValue(OPT_thinlto_cache_policy)),
370       "--thinlto-cache-policy: invalid cache policy");
371   errorHandler().verbose = args.hasArg(OPT_verbose);
372   LLVM_DEBUG(errorHandler().verbose = true);
373 
374   config->initialMemory = args::getInteger(args, OPT_initial_memory, 0);
375   config->globalBase = args::getInteger(args, OPT_global_base, 1024);
376   config->maxMemory = args::getInteger(args, OPT_max_memory, 0);
377   config->zStackSize =
378       args::getZOptionValue(args, OPT_z, "stack-size", WasmPageSize);
379 
380   // Default value of exportDynamic depends on `-shared`
381   config->exportDynamic =
382       args.hasFlag(OPT_export_dynamic, OPT_no_export_dynamic, config->shared);
383 
384   // Parse wasm32/64.
385   if (auto *arg = args.getLastArg(OPT_m)) {
386     StringRef s = arg->getValue();
387     if (s == "wasm32")
388       config->is64 = false;
389     else if (s == "wasm64")
390       config->is64 = true;
391     else
392       error("invalid target architecture: " + s);
393   }
394 
395   // --threads= takes a positive integer and provides the default value for
396   // --thinlto-jobs=.
397   if (auto *arg = args.getLastArg(OPT_threads)) {
398     StringRef v(arg->getValue());
399     unsigned threads = 0;
400     if (!llvm::to_integer(v, threads, 0) || threads == 0)
401       error(arg->getSpelling() + ": expected a positive integer, but got '" +
402             arg->getValue() + "'");
403     parallel::strategy = hardware_concurrency(threads);
404     config->thinLTOJobs = v;
405   }
406   if (auto *arg = args.getLastArg(OPT_thinlto_jobs))
407     config->thinLTOJobs = arg->getValue();
408 
409   if (auto *arg = args.getLastArg(OPT_features)) {
410     config->features =
411         llvm::Optional<std::vector<std::string>>(std::vector<std::string>());
412     for (StringRef s : arg->getValues())
413       config->features->push_back(std::string(s));
414   }
415 
416   if (args.hasArg(OPT_print_map))
417     config->mapFile = "-";
418 }
419 
420 // Some Config members do not directly correspond to any particular
421 // command line options, but computed based on other Config values.
422 // This function initialize such members. See Config.h for the details
423 // of these values.
424 static void setConfigs() {
425   config->isPic = config->pie || config->shared;
426 
427   if (config->isPic) {
428     if (config->exportTable)
429       error("-shared/-pie is incompatible with --export-table");
430     config->importTable = true;
431   }
432 
433   if (config->shared) {
434     config->importMemory = true;
435     config->allowUndefined = true;
436   }
437 }
438 
439 // Some command line options or some combinations of them are not allowed.
440 // This function checks for such errors.
441 static void checkOptions(opt::InputArgList &args) {
442   if (!config->stripDebug && !config->stripAll && config->compressRelocations)
443     error("--compress-relocations is incompatible with output debug"
444           " information. Please pass --strip-debug or --strip-all");
445 
446   if (config->ltoo > 3)
447     error("invalid optimization level for LTO: " + Twine(config->ltoo));
448   if (config->ltoPartitions == 0)
449     error("--lto-partitions: number of threads must be > 0");
450   if (!get_threadpool_strategy(config->thinLTOJobs))
451     error("--thinlto-jobs: invalid job count: " + config->thinLTOJobs);
452 
453   if (config->pie && config->shared)
454     error("-shared and -pie may not be used together");
455 
456   if (config->outputFile.empty())
457     error("no output file specified");
458 
459   if (config->importTable && config->exportTable)
460     error("--import-table and --export-table may not be used together");
461 
462   if (config->relocatable) {
463     if (!config->entry.empty())
464       error("entry point specified for relocatable output file");
465     if (config->gcSections)
466       error("-r and --gc-sections may not be used together");
467     if (config->compressRelocations)
468       error("-r -and --compress-relocations may not be used together");
469     if (args.hasArg(OPT_undefined))
470       error("-r -and --undefined may not be used together");
471     if (config->pie)
472       error("-r and -pie may not be used together");
473     if (config->sharedMemory)
474       error("-r and --shared-memory may not be used together");
475   }
476 
477   // To begin to prepare for Module Linking-style shared libraries, start
478   // warning about uses of `-shared` and related flags outside of Experimental
479   // mode, to give anyone using them a heads-up that they will be changing.
480   //
481   // Also, warn about flags which request explicit exports.
482   if (!config->experimentalPic) {
483     // -shared will change meaning when Module Linking is implemented.
484     if (config->shared) {
485       warn("creating shared libraries, with -shared, is not yet stable");
486     }
487 
488     // -pie will change meaning when Module Linking is implemented.
489     if (config->pie) {
490       warn("creating PIEs, with -pie, is not yet stable");
491     }
492   }
493 }
494 
495 // Force Sym to be entered in the output. Used for -u or equivalent.
496 static Symbol *handleUndefined(StringRef name) {
497   Symbol *sym = symtab->find(name);
498   if (!sym)
499     return nullptr;
500 
501   // Since symbol S may not be used inside the program, LTO may
502   // eliminate it. Mark the symbol as "used" to prevent it.
503   sym->isUsedInRegularObj = true;
504 
505   if (auto *lazySym = dyn_cast<LazySymbol>(sym))
506     lazySym->fetch();
507 
508   return sym;
509 }
510 
511 static void handleLibcall(StringRef name) {
512   Symbol *sym = symtab->find(name);
513   if (!sym)
514     return;
515 
516   if (auto *lazySym = dyn_cast<LazySymbol>(sym)) {
517     MemoryBufferRef mb = lazySym->getMemberBuffer();
518     if (isBitcode(mb))
519       lazySym->fetch();
520   }
521 }
522 
523 static UndefinedGlobal *
524 createUndefinedGlobal(StringRef name, llvm::wasm::WasmGlobalType *type) {
525   auto *sym = cast<UndefinedGlobal>(symtab->addUndefinedGlobal(
526       name, None, None, WASM_SYMBOL_UNDEFINED, nullptr, type));
527   config->allowUndefinedSymbols.insert(sym->getName());
528   sym->isUsedInRegularObj = true;
529   return sym;
530 }
531 
532 static GlobalSymbol *createGlobalVariable(StringRef name, bool isMutable,
533                                           int value) {
534   llvm::wasm::WasmGlobal wasmGlobal;
535   if (config->is64.getValueOr(false)) {
536     wasmGlobal.Type = {WASM_TYPE_I64, isMutable};
537     wasmGlobal.InitExpr.Value.Int64 = value;
538     wasmGlobal.InitExpr.Opcode = WASM_OPCODE_I64_CONST;
539   } else {
540     wasmGlobal.Type = {WASM_TYPE_I32, isMutable};
541     wasmGlobal.InitExpr.Value.Int32 = value;
542     wasmGlobal.InitExpr.Opcode = WASM_OPCODE_I32_CONST;
543   }
544   wasmGlobal.SymbolName = name;
545   return symtab->addSyntheticGlobal(name, WASM_SYMBOL_VISIBILITY_HIDDEN,
546                                     make<InputGlobal>(wasmGlobal, nullptr));
547 }
548 
549 // Create ABI-defined synthetic symbols
550 static void createSyntheticSymbols() {
551   if (config->relocatable)
552     return;
553 
554   static WasmSignature nullSignature = {{}, {}};
555   static WasmSignature i32ArgSignature = {{}, {ValType::I32}};
556   static WasmSignature i64ArgSignature = {{}, {ValType::I64}};
557   static llvm::wasm::WasmGlobalType globalTypeI32 = {WASM_TYPE_I32, false};
558   static llvm::wasm::WasmGlobalType globalTypeI64 = {WASM_TYPE_I64, false};
559   static llvm::wasm::WasmGlobalType mutableGlobalTypeI32 = {WASM_TYPE_I32,
560                                                             true};
561   static llvm::wasm::WasmGlobalType mutableGlobalTypeI64 = {WASM_TYPE_I64,
562                                                             true};
563   WasmSym::callCtors = symtab->addSyntheticFunction(
564       "__wasm_call_ctors", WASM_SYMBOL_VISIBILITY_HIDDEN,
565       make<SyntheticFunction>(nullSignature, "__wasm_call_ctors"));
566 
567   if (config->isPic) {
568     // For PIC code we create a synthetic function __wasm_apply_relocs which
569     // is called from __wasm_call_ctors before the user-level constructors.
570     WasmSym::applyRelocs = symtab->addSyntheticFunction(
571         "__wasm_apply_relocs", WASM_SYMBOL_VISIBILITY_HIDDEN,
572         make<SyntheticFunction>(nullSignature, "__wasm_apply_relocs"));
573   }
574 
575   if (config->isPic) {
576     WasmSym::stackPointer =
577         createUndefinedGlobal("__stack_pointer", config->is64.getValueOr(false)
578                                                      ? &mutableGlobalTypeI64
579                                                      : &mutableGlobalTypeI32);
580     // For PIC code, we import two global variables (__memory_base and
581     // __table_base) from the environment and use these as the offset at
582     // which to load our static data and function table.
583     // See:
584     // https://github.com/WebAssembly/tool-conventions/blob/master/DynamicLinking.md
585     WasmSym::memoryBase = createUndefinedGlobal(
586         "__memory_base",
587         config->is64.getValueOr(false) ? &globalTypeI64 : &globalTypeI32);
588     WasmSym::tableBase = createUndefinedGlobal("__table_base", &globalTypeI32);
589     WasmSym::memoryBase->markLive();
590     WasmSym::tableBase->markLive();
591   } else {
592     // For non-PIC code
593     WasmSym::stackPointer = createGlobalVariable("__stack_pointer", true, 0);
594     WasmSym::stackPointer->markLive();
595   }
596 
597   if (config->sharedMemory && !config->shared) {
598     // Passive segments are used to avoid memory being reinitialized on each
599     // thread's instantiation. These passive segments are initialized and
600     // dropped in __wasm_init_memory, which is registered as the start function
601     WasmSym::initMemory = symtab->addSyntheticFunction(
602         "__wasm_init_memory", WASM_SYMBOL_VISIBILITY_HIDDEN,
603         make<SyntheticFunction>(nullSignature, "__wasm_init_memory"));
604     WasmSym::initMemoryFlag = symtab->addSyntheticDataSymbol(
605         "__wasm_init_memory_flag", WASM_SYMBOL_VISIBILITY_HIDDEN);
606     assert(WasmSym::initMemoryFlag);
607     WasmSym::tlsBase = createGlobalVariable("__tls_base", true, 0);
608     WasmSym::tlsSize = createGlobalVariable("__tls_size", false, 0);
609     WasmSym::tlsAlign = createGlobalVariable("__tls_align", false, 1);
610     WasmSym::initTLS = symtab->addSyntheticFunction(
611         "__wasm_init_tls", WASM_SYMBOL_VISIBILITY_HIDDEN,
612         make<SyntheticFunction>(
613             config->is64.getValueOr(false) ? i64ArgSignature : i32ArgSignature,
614             "__wasm_init_tls"));
615   }
616 }
617 
618 static void createOptionalSymbols() {
619   if (config->relocatable)
620     return;
621 
622   WasmSym::dsoHandle = symtab->addOptionalDataSymbol("__dso_handle");
623 
624   if (!config->shared)
625     WasmSym::dataEnd = symtab->addOptionalDataSymbol("__data_end");
626 
627   if (!config->isPic) {
628     WasmSym::globalBase = symtab->addOptionalDataSymbol("__global_base");
629     WasmSym::heapBase = symtab->addOptionalDataSymbol("__heap_base");
630     WasmSym::definedMemoryBase = symtab->addOptionalDataSymbol("__memory_base");
631     WasmSym::definedTableBase = symtab->addOptionalDataSymbol("__table_base");
632   }
633 }
634 
635 // Reconstructs command line arguments so that so that you can re-run
636 // the same command with the same inputs. This is for --reproduce.
637 static std::string createResponseFile(const opt::InputArgList &args) {
638   SmallString<0> data;
639   raw_svector_ostream os(data);
640 
641   // Copy the command line to the output while rewriting paths.
642   for (auto *arg : args) {
643     switch (arg->getOption().getID()) {
644     case OPT_reproduce:
645       break;
646     case OPT_INPUT:
647       os << quote(relativeToRoot(arg->getValue())) << "\n";
648       break;
649     case OPT_o:
650       // If -o path contains directories, "lld @response.txt" will likely
651       // fail because the archive we are creating doesn't contain empty
652       // directories for the output path (-o doesn't create directories).
653       // Strip directories to prevent the issue.
654       os << "-o " << quote(sys::path::filename(arg->getValue())) << "\n";
655       break;
656     default:
657       os << toString(*arg) << "\n";
658     }
659   }
660   return std::string(data.str());
661 }
662 
663 // The --wrap option is a feature to rename symbols so that you can write
664 // wrappers for existing functions. If you pass `-wrap=foo`, all
665 // occurrences of symbol `foo` are resolved to `wrap_foo` (so, you are
666 // expected to write `wrap_foo` function as a wrapper). The original
667 // symbol becomes accessible as `real_foo`, so you can call that from your
668 // wrapper.
669 //
670 // This data structure is instantiated for each -wrap option.
671 struct WrappedSymbol {
672   Symbol *sym;
673   Symbol *real;
674   Symbol *wrap;
675 };
676 
677 static Symbol *addUndefined(StringRef name) {
678   return symtab->addUndefinedFunction(name, None, None, WASM_SYMBOL_UNDEFINED,
679                                       nullptr, nullptr, false);
680 }
681 
682 // Handles -wrap option.
683 //
684 // This function instantiates wrapper symbols. At this point, they seem
685 // like they are not being used at all, so we explicitly set some flags so
686 // that LTO won't eliminate them.
687 static std::vector<WrappedSymbol> addWrappedSymbols(opt::InputArgList &args) {
688   std::vector<WrappedSymbol> v;
689   DenseSet<StringRef> seen;
690 
691   for (auto *arg : args.filtered(OPT_wrap)) {
692     StringRef name = arg->getValue();
693     if (!seen.insert(name).second)
694       continue;
695 
696     Symbol *sym = symtab->find(name);
697     if (!sym)
698       continue;
699 
700     Symbol *real = addUndefined(saver.save("__real_" + name));
701     Symbol *wrap = addUndefined(saver.save("__wrap_" + name));
702     v.push_back({sym, real, wrap});
703 
704     // We want to tell LTO not to inline symbols to be overwritten
705     // because LTO doesn't know the final symbol contents after renaming.
706     real->canInline = false;
707     sym->canInline = false;
708 
709     // Tell LTO not to eliminate these symbols.
710     sym->isUsedInRegularObj = true;
711     wrap->isUsedInRegularObj = true;
712     real->isUsedInRegularObj = false;
713   }
714   return v;
715 }
716 
717 // Do renaming for -wrap by updating pointers to symbols.
718 //
719 // When this function is executed, only InputFiles and symbol table
720 // contain pointers to symbol objects. We visit them to replace pointers,
721 // so that wrapped symbols are swapped as instructed by the command line.
722 static void wrapSymbols(ArrayRef<WrappedSymbol> wrapped) {
723   DenseMap<Symbol *, Symbol *> map;
724   for (const WrappedSymbol &w : wrapped) {
725     map[w.sym] = w.wrap;
726     map[w.real] = w.sym;
727   }
728 
729   // Update pointers in input files.
730   parallelForEach(symtab->objectFiles, [&](InputFile *file) {
731     MutableArrayRef<Symbol *> syms = file->getMutableSymbols();
732     for (size_t i = 0, e = syms.size(); i != e; ++i)
733       if (Symbol *s = map.lookup(syms[i]))
734         syms[i] = s;
735   });
736 
737   // Update pointers in the symbol table.
738   for (const WrappedSymbol &w : wrapped)
739     symtab->wrap(w.sym, w.real, w.wrap);
740 }
741 
742 void LinkerDriver::link(ArrayRef<const char *> argsArr) {
743   WasmOptTable parser;
744   opt::InputArgList args = parser.parse(argsArr.slice(1));
745 
746   // Handle --help
747   if (args.hasArg(OPT_help)) {
748     parser.PrintHelp(lld::outs(),
749                      (std::string(argsArr[0]) + " [options] file...").c_str(),
750                      "LLVM Linker", false);
751     return;
752   }
753 
754   // Handle --version
755   if (args.hasArg(OPT_version) || args.hasArg(OPT_v)) {
756     lld::outs() << getLLDVersion() << "\n";
757     return;
758   }
759 
760   // Handle --reproduce
761   if (auto *arg = args.getLastArg(OPT_reproduce)) {
762     StringRef path = arg->getValue();
763     Expected<std::unique_ptr<TarWriter>> errOrWriter =
764         TarWriter::create(path, path::stem(path));
765     if (errOrWriter) {
766       tar = std::move(*errOrWriter);
767       tar->append("response.txt", createResponseFile(args));
768       tar->append("version.txt", getLLDVersion() + "\n");
769     } else {
770       error("--reproduce: " + toString(errOrWriter.takeError()));
771     }
772   }
773 
774   // Parse and evaluate -mllvm options.
775   std::vector<const char *> v;
776   v.push_back("wasm-ld (LLVM option parsing)");
777   for (auto *arg : args.filtered(OPT_mllvm))
778     v.push_back(arg->getValue());
779   cl::ResetAllOptionOccurrences();
780   cl::ParseCommandLineOptions(v.size(), v.data());
781 
782   errorHandler().errorLimit = args::getInteger(args, OPT_error_limit, 20);
783 
784   readConfigs(args);
785 
786   createFiles(args);
787   if (errorCount())
788     return;
789 
790   setConfigs();
791   checkOptions(args);
792   if (errorCount())
793     return;
794 
795   if (auto *arg = args.getLastArg(OPT_allow_undefined_file))
796     readImportFile(arg->getValue());
797 
798   // Fail early if the output file or map file is not writable. If a user has a
799   // long link, e.g. due to a large LTO link, they do not wish to run it and
800   // find that it failed because there was a mistake in their command-line.
801   if (auto e = tryCreateFile(config->outputFile))
802     error("cannot open output file " + config->outputFile + ": " + e.message());
803   if (auto e = tryCreateFile(config->mapFile))
804     error("cannot open map file " + config->mapFile + ": " + e.message());
805   if (errorCount())
806     return;
807 
808   // Handle --trace-symbol.
809   for (auto *arg : args.filtered(OPT_trace_symbol))
810     symtab->trace(arg->getValue());
811 
812   for (auto *arg : args.filtered(OPT_export))
813     config->exportedSymbols.insert(arg->getValue());
814 
815   createSyntheticSymbols();
816 
817   // Add all files to the symbol table. This will add almost all
818   // symbols that we need to the symbol table.
819   for (InputFile *f : files)
820     symtab->addFile(f);
821   if (errorCount())
822     return;
823 
824   // Handle the `--undefined <sym>` options.
825   for (auto *arg : args.filtered(OPT_undefined))
826     handleUndefined(arg->getValue());
827 
828   // Handle the `--export <sym>` options
829   // This works like --undefined but also exports the symbol if its found
830   for (auto *arg : args.filtered(OPT_export))
831     handleUndefined(arg->getValue());
832 
833   Symbol *entrySym = nullptr;
834   if (!config->relocatable && !config->entry.empty()) {
835     entrySym = handleUndefined(config->entry);
836     if (entrySym && entrySym->isDefined())
837       entrySym->forceExport = true;
838     else
839       error("entry symbol not defined (pass --no-entry to suppress): " +
840             config->entry);
841   }
842 
843   // If the user code defines a `__wasm_call_dtors` function, remember it so
844   // that we can call it from the command export wrappers. Unlike
845   // `__wasm_call_ctors` which we synthesize, `__wasm_call_dtors` is defined
846   // by libc/etc., because destructors are registered dynamically with
847   // `__cxa_atexit` and friends.
848   if (!config->relocatable && !config->shared &&
849       !WasmSym::callCtors->isUsedInRegularObj &&
850       WasmSym::callCtors->getName() != config->entry &&
851       !config->exportedSymbols.count(WasmSym::callCtors->getName())) {
852     if (Symbol *callDtors = handleUndefined("__wasm_call_dtors")) {
853       if (auto *callDtorsFunc = dyn_cast<DefinedFunction>(callDtors)) {
854         if (callDtorsFunc->signature &&
855             (!callDtorsFunc->signature->Params.empty() ||
856              !callDtorsFunc->signature->Returns.empty())) {
857           error("__wasm_call_dtors must have no argument or return values");
858         }
859         WasmSym::callDtors = callDtorsFunc;
860       } else {
861         error("__wasm_call_dtors must be a function");
862       }
863     }
864   }
865 
866   createOptionalSymbols();
867 
868   if (errorCount())
869     return;
870 
871   // Create wrapped symbols for -wrap option.
872   std::vector<WrappedSymbol> wrapped = addWrappedSymbols(args);
873 
874   // If any of our inputs are bitcode files, the LTO code generator may create
875   // references to certain library functions that might not be explicit in the
876   // bitcode file's symbol table. If any of those library functions are defined
877   // in a bitcode file in an archive member, we need to arrange to use LTO to
878   // compile those archive members by adding them to the link beforehand.
879   //
880   // We only need to add libcall symbols to the link before LTO if the symbol's
881   // definition is in bitcode. Any other required libcall symbols will be added
882   // to the link after LTO when we add the LTO object file to the link.
883   if (!symtab->bitcodeFiles.empty())
884     for (auto *s : lto::LTO::getRuntimeLibcallSymbols())
885       handleLibcall(s);
886   if (errorCount())
887     return;
888 
889   // Do link-time optimization if given files are LLVM bitcode files.
890   // This compiles bitcode files into real object files.
891   symtab->addCombinedLTOObject();
892   if (errorCount())
893     return;
894 
895   // Resolve any variant symbols that were created due to signature
896   // mismatchs.
897   symtab->handleSymbolVariants();
898   if (errorCount())
899     return;
900 
901   // Apply symbol renames for -wrap.
902   if (!wrapped.empty())
903     wrapSymbols(wrapped);
904 
905   for (auto *arg : args.filtered(OPT_export)) {
906     Symbol *sym = symtab->find(arg->getValue());
907     if (sym && sym->isDefined())
908       sym->forceExport = true;
909     else if (!config->allowUndefined)
910       error(Twine("symbol exported via --export not found: ") +
911             arg->getValue());
912   }
913 
914   if (!config->relocatable) {
915     // Add synthetic dummies for weak undefined functions.  Must happen
916     // after LTO otherwise functions may not yet have signatures.
917     symtab->handleWeakUndefines();
918   }
919 
920   if (entrySym)
921     entrySym->setHidden(false);
922 
923   if (errorCount())
924     return;
925 
926   // Do size optimizations: garbage collection
927   markLive();
928 
929   // Write the result to the file.
930   writeResult();
931 }
932 
933 } // namespace wasm
934 } // namespace lld
935