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