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