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