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