xref: /llvm-project-15.0.7/lld/wasm/Driver.cpp (revision d092c912)
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 
576   if (config->isPic) {
577     WasmSym::stackPointer =
578         createUndefinedGlobal("__stack_pointer", config->is64.getValueOr(false)
579                                                      ? &mutableGlobalTypeI64
580                                                      : &mutableGlobalTypeI32);
581     // For PIC code, we import two global variables (__memory_base and
582     // __table_base) from the environment and use these as the offset at
583     // which to load our static data and function table.
584     // See:
585     // https://github.com/WebAssembly/tool-conventions/blob/master/DynamicLinking.md
586     WasmSym::memoryBase = createUndefinedGlobal(
587         "__memory_base",
588         config->is64.getValueOr(false) ? &globalTypeI64 : &globalTypeI32);
589     WasmSym::tableBase = createUndefinedGlobal("__table_base", &globalTypeI32);
590     WasmSym::memoryBase->markLive();
591     WasmSym::tableBase->markLive();
592   } else {
593     // For non-PIC code
594     WasmSym::stackPointer = createGlobalVariable("__stack_pointer", true, 0);
595     WasmSym::stackPointer->markLive();
596   }
597 
598   if (config->sharedMemory && !config->shared) {
599     // Passive segments are used to avoid memory being reinitialized on each
600     // thread's instantiation. These passive segments are initialized and
601     // dropped in __wasm_init_memory, which is registered as the start function
602     WasmSym::initMemory = symtab->addSyntheticFunction(
603         "__wasm_init_memory", WASM_SYMBOL_VISIBILITY_HIDDEN,
604         make<SyntheticFunction>(nullSignature, "__wasm_init_memory"));
605     WasmSym::initMemoryFlag = symtab->addSyntheticDataSymbol(
606         "__wasm_init_memory_flag", WASM_SYMBOL_VISIBILITY_HIDDEN);
607     assert(WasmSym::initMemoryFlag);
608     WasmSym::tlsBase = createGlobalVariable("__tls_base", true, 0);
609     WasmSym::tlsSize = createGlobalVariable("__tls_size", false, 0);
610     WasmSym::tlsAlign = createGlobalVariable("__tls_align", false, 1);
611     WasmSym::initTLS = symtab->addSyntheticFunction(
612         "__wasm_init_tls", WASM_SYMBOL_VISIBILITY_HIDDEN,
613         make<SyntheticFunction>(
614             config->is64.getValueOr(false) ? i64ArgSignature : i32ArgSignature,
615             "__wasm_init_tls"));
616   }
617 }
618 
619 static void createOptionalSymbols() {
620   if (config->relocatable)
621     return;
622 
623   WasmSym::dsoHandle = symtab->addOptionalDataSymbol("__dso_handle");
624 
625   if (!config->shared)
626     WasmSym::dataEnd = symtab->addOptionalDataSymbol("__data_end");
627 
628   if (!config->isPic) {
629     WasmSym::globalBase = symtab->addOptionalDataSymbol("__global_base");
630     WasmSym::heapBase = symtab->addOptionalDataSymbol("__heap_base");
631     WasmSym::definedMemoryBase = symtab->addOptionalDataSymbol("__memory_base");
632     WasmSym::definedTableBase = symtab->addOptionalDataSymbol("__table_base");
633   }
634 }
635 
636 // Reconstructs command line arguments so that so that you can re-run
637 // the same command with the same inputs. This is for --reproduce.
638 static std::string createResponseFile(const opt::InputArgList &args) {
639   SmallString<0> data;
640   raw_svector_ostream os(data);
641 
642   // Copy the command line to the output while rewriting paths.
643   for (auto *arg : args) {
644     switch (arg->getOption().getID()) {
645     case OPT_reproduce:
646       break;
647     case OPT_INPUT:
648       os << quote(relativeToRoot(arg->getValue())) << "\n";
649       break;
650     case OPT_o:
651       // If -o path contains directories, "lld @response.txt" will likely
652       // fail because the archive we are creating doesn't contain empty
653       // directories for the output path (-o doesn't create directories).
654       // Strip directories to prevent the issue.
655       os << "-o " << quote(sys::path::filename(arg->getValue())) << "\n";
656       break;
657     default:
658       os << toString(*arg) << "\n";
659     }
660   }
661   return std::string(data.str());
662 }
663 
664 // The --wrap option is a feature to rename symbols so that you can write
665 // wrappers for existing functions. If you pass `-wrap=foo`, all
666 // occurrences of symbol `foo` are resolved to `wrap_foo` (so, you are
667 // expected to write `wrap_foo` function as a wrapper). The original
668 // symbol becomes accessible as `real_foo`, so you can call that from your
669 // wrapper.
670 //
671 // This data structure is instantiated for each -wrap option.
672 struct WrappedSymbol {
673   Symbol *sym;
674   Symbol *real;
675   Symbol *wrap;
676 };
677 
678 static Symbol *addUndefined(StringRef name) {
679   return symtab->addUndefinedFunction(name, None, None, WASM_SYMBOL_UNDEFINED,
680                                       nullptr, nullptr, false);
681 }
682 
683 // Handles -wrap option.
684 //
685 // This function instantiates wrapper symbols. At this point, they seem
686 // like they are not being used at all, so we explicitly set some flags so
687 // that LTO won't eliminate them.
688 static std::vector<WrappedSymbol> addWrappedSymbols(opt::InputArgList &args) {
689   std::vector<WrappedSymbol> v;
690   DenseSet<StringRef> seen;
691 
692   for (auto *arg : args.filtered(OPT_wrap)) {
693     StringRef name = arg->getValue();
694     if (!seen.insert(name).second)
695       continue;
696 
697     Symbol *sym = symtab->find(name);
698     if (!sym)
699       continue;
700 
701     Symbol *real = addUndefined(saver.save("__real_" + name));
702     Symbol *wrap = addUndefined(saver.save("__wrap_" + name));
703     v.push_back({sym, real, wrap});
704 
705     // We want to tell LTO not to inline symbols to be overwritten
706     // because LTO doesn't know the final symbol contents after renaming.
707     real->canInline = false;
708     sym->canInline = false;
709 
710     // Tell LTO not to eliminate these symbols.
711     sym->isUsedInRegularObj = true;
712     wrap->isUsedInRegularObj = true;
713     real->isUsedInRegularObj = false;
714   }
715   return v;
716 }
717 
718 // Do renaming for -wrap by updating pointers to symbols.
719 //
720 // When this function is executed, only InputFiles and symbol table
721 // contain pointers to symbol objects. We visit them to replace pointers,
722 // so that wrapped symbols are swapped as instructed by the command line.
723 static void wrapSymbols(ArrayRef<WrappedSymbol> wrapped) {
724   DenseMap<Symbol *, Symbol *> map;
725   for (const WrappedSymbol &w : wrapped) {
726     map[w.sym] = w.wrap;
727     map[w.real] = w.sym;
728   }
729 
730   // Update pointers in input files.
731   parallelForEach(symtab->objectFiles, [&](InputFile *file) {
732     MutableArrayRef<Symbol *> syms = file->getMutableSymbols();
733     for (size_t i = 0, e = syms.size(); i != e; ++i)
734       if (Symbol *s = map.lookup(syms[i]))
735         syms[i] = s;
736   });
737 
738   // Update pointers in the symbol table.
739   for (const WrappedSymbol &w : wrapped)
740     symtab->wrap(w.sym, w.real, w.wrap);
741 }
742 
743 void LinkerDriver::link(ArrayRef<const char *> argsArr) {
744   WasmOptTable parser;
745   opt::InputArgList args = parser.parse(argsArr.slice(1));
746 
747   // Handle --help
748   if (args.hasArg(OPT_help)) {
749     parser.PrintHelp(lld::outs(),
750                      (std::string(argsArr[0]) + " [options] file...").c_str(),
751                      "LLVM Linker", false);
752     return;
753   }
754 
755   // Handle --version
756   if (args.hasArg(OPT_version) || args.hasArg(OPT_v)) {
757     lld::outs() << getLLDVersion() << "\n";
758     return;
759   }
760 
761   // Handle --reproduce
762   if (auto *arg = args.getLastArg(OPT_reproduce)) {
763     StringRef path = arg->getValue();
764     Expected<std::unique_ptr<TarWriter>> errOrWriter =
765         TarWriter::create(path, path::stem(path));
766     if (errOrWriter) {
767       tar = std::move(*errOrWriter);
768       tar->append("response.txt", createResponseFile(args));
769       tar->append("version.txt", getLLDVersion() + "\n");
770     } else {
771       error("--reproduce: " + toString(errOrWriter.takeError()));
772     }
773   }
774 
775   // Parse and evaluate -mllvm options.
776   std::vector<const char *> v;
777   v.push_back("wasm-ld (LLVM option parsing)");
778   for (auto *arg : args.filtered(OPT_mllvm))
779     v.push_back(arg->getValue());
780   cl::ResetAllOptionOccurrences();
781   cl::ParseCommandLineOptions(v.size(), v.data());
782 
783   errorHandler().errorLimit = args::getInteger(args, OPT_error_limit, 20);
784 
785   readConfigs(args);
786 
787   createFiles(args);
788   if (errorCount())
789     return;
790 
791   setConfigs();
792   checkOptions(args);
793   if (errorCount())
794     return;
795 
796   if (auto *arg = args.getLastArg(OPT_allow_undefined_file))
797     readImportFile(arg->getValue());
798 
799   // Fail early if the output file or map file is not writable. If a user has a
800   // long link, e.g. due to a large LTO link, they do not wish to run it and
801   // find that it failed because there was a mistake in their command-line.
802   if (auto e = tryCreateFile(config->outputFile))
803     error("cannot open output file " + config->outputFile + ": " + e.message());
804   if (auto e = tryCreateFile(config->mapFile))
805     error("cannot open map file " + config->mapFile + ": " + e.message());
806   if (errorCount())
807     return;
808 
809   // Handle --trace-symbol.
810   for (auto *arg : args.filtered(OPT_trace_symbol))
811     symtab->trace(arg->getValue());
812 
813   for (auto *arg : args.filtered(OPT_export))
814     config->exportedSymbols.insert(arg->getValue());
815 
816   createSyntheticSymbols();
817 
818   // Add all files to the symbol table. This will add almost all
819   // symbols that we need to the symbol table.
820   for (InputFile *f : files)
821     symtab->addFile(f);
822   if (errorCount())
823     return;
824 
825   // Handle the `--undefined <sym>` options.
826   for (auto *arg : args.filtered(OPT_undefined))
827     handleUndefined(arg->getValue());
828 
829   // Handle the `--export <sym>` options
830   // This works like --undefined but also exports the symbol if its found
831   for (auto *arg : args.filtered(OPT_export))
832     handleUndefined(arg->getValue());
833 
834   Symbol *entrySym = nullptr;
835   if (!config->relocatable && !config->entry.empty()) {
836     entrySym = handleUndefined(config->entry);
837     if (entrySym && entrySym->isDefined())
838       entrySym->forceExport = true;
839     else
840       error("entry symbol not defined (pass --no-entry to suppress): " +
841             config->entry);
842   }
843 
844   createOptionalSymbols();
845 
846   if (errorCount())
847     return;
848 
849   // Create wrapped symbols for -wrap option.
850   std::vector<WrappedSymbol> wrapped = addWrappedSymbols(args);
851 
852   // If any of our inputs are bitcode files, the LTO code generator may create
853   // references to certain library functions that might not be explicit in the
854   // bitcode file's symbol table. If any of those library functions are defined
855   // in a bitcode file in an archive member, we need to arrange to use LTO to
856   // compile those archive members by adding them to the link beforehand.
857   //
858   // We only need to add libcall symbols to the link before LTO if the symbol's
859   // definition is in bitcode. Any other required libcall symbols will be added
860   // to the link after LTO when we add the LTO object file to the link.
861   if (!symtab->bitcodeFiles.empty())
862     for (auto *s : lto::LTO::getRuntimeLibcallSymbols())
863       handleLibcall(s);
864   if (errorCount())
865     return;
866 
867   // Do link-time optimization if given files are LLVM bitcode files.
868   // This compiles bitcode files into real object files.
869   symtab->addCombinedLTOObject();
870   if (errorCount())
871     return;
872 
873   // Resolve any variant symbols that were created due to signature
874   // mismatchs.
875   symtab->handleSymbolVariants();
876   if (errorCount())
877     return;
878 
879   // Apply symbol renames for -wrap.
880   if (!wrapped.empty())
881     wrapSymbols(wrapped);
882 
883   for (auto *arg : args.filtered(OPT_export)) {
884     Symbol *sym = symtab->find(arg->getValue());
885     if (sym && sym->isDefined())
886       sym->forceExport = true;
887     else if (!config->allowUndefined)
888       error(Twine("symbol exported via --export not found: ") +
889             arg->getValue());
890   }
891 
892   if (!config->relocatable) {
893     // Add synthetic dummies for weak undefined functions.  Must happen
894     // after LTO otherwise functions may not yet have signatures.
895     symtab->handleWeakUndefines();
896   }
897 
898   if (entrySym)
899     entrySym->setHidden(false);
900 
901   if (errorCount())
902     return;
903 
904   // Do size optimizations: garbage collection
905   markLive();
906 
907   // Write the result to the file.
908   writeResult();
909 }
910 
911 } // namespace wasm
912 } // namespace lld
913