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