xref: /llvm-project-15.0.7/lld/wasm/Driver.cpp (revision bf02bcff)
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/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/Parallel.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     if (config->sharedMemory)
457       error("-r and --shared-memory may not be used together");
458   }
459 }
460 
461 // Force Sym to be entered in the output. Used for -u or equivalent.
462 static Symbol *handleUndefined(StringRef name) {
463   Symbol *sym = symtab->find(name);
464   if (!sym)
465     return nullptr;
466 
467   // Since symbol S may not be used inside the program, LTO may
468   // eliminate it. Mark the symbol as "used" to prevent it.
469   sym->isUsedInRegularObj = true;
470 
471   if (auto *lazySym = dyn_cast<LazySymbol>(sym))
472     lazySym->fetch();
473 
474   return sym;
475 }
476 
477 static void handleLibcall(StringRef name) {
478   Symbol *sym = symtab->find(name);
479   if (!sym)
480     return;
481 
482   if (auto *lazySym = dyn_cast<LazySymbol>(sym)) {
483     MemoryBufferRef mb = lazySym->getMemberBuffer();
484     if (isBitcode(mb))
485       lazySym->fetch();
486   }
487 }
488 
489 static UndefinedGlobal *
490 createUndefinedGlobal(StringRef name, llvm::wasm::WasmGlobalType *type) {
491   auto *sym = cast<UndefinedGlobal>(symtab->addUndefinedGlobal(
492       name, None, None, WASM_SYMBOL_UNDEFINED, nullptr, type));
493   config->allowUndefinedSymbols.insert(sym->getName());
494   sym->isUsedInRegularObj = true;
495   return sym;
496 }
497 
498 static GlobalSymbol *createGlobalVariable(StringRef name, bool isMutable,
499                                           int value) {
500   llvm::wasm::WasmGlobal wasmGlobal;
501   wasmGlobal.Type = {WASM_TYPE_I32, isMutable};
502   wasmGlobal.InitExpr.Value.Int32 = value;
503   wasmGlobal.InitExpr.Opcode = WASM_OPCODE_I32_CONST;
504   wasmGlobal.SymbolName = name;
505   return symtab->addSyntheticGlobal(name, WASM_SYMBOL_VISIBILITY_HIDDEN,
506                                     make<InputGlobal>(wasmGlobal, nullptr));
507 }
508 
509 // Create ABI-defined synthetic symbols
510 static void createSyntheticSymbols() {
511   if (config->relocatable)
512     return;
513 
514   static WasmSignature nullSignature = {{}, {}};
515   static WasmSignature i32ArgSignature = {{}, {ValType::I32}};
516   static llvm::wasm::WasmGlobalType globalTypeI32 = {WASM_TYPE_I32, false};
517   static llvm::wasm::WasmGlobalType mutableGlobalTypeI32 = {WASM_TYPE_I32,
518                                                             true};
519   WasmSym::callCtors = symtab->addSyntheticFunction(
520       "__wasm_call_ctors", WASM_SYMBOL_VISIBILITY_HIDDEN,
521       make<SyntheticFunction>(nullSignature, "__wasm_call_ctors"));
522 
523   if (config->isPic) {
524     // For PIC code we create a synthetic function __wasm_apply_relocs which
525     // is called from __wasm_call_ctors before the user-level constructors.
526     WasmSym::applyRelocs = symtab->addSyntheticFunction(
527         "__wasm_apply_relocs", WASM_SYMBOL_VISIBILITY_HIDDEN,
528         make<SyntheticFunction>(nullSignature, "__wasm_apply_relocs"));
529   }
530 
531 
532   if (config->isPic) {
533     WasmSym::stackPointer =
534         createUndefinedGlobal("__stack_pointer", &mutableGlobalTypeI32);
535     // For PIC code, we import two global variables (__memory_base and
536     // __table_base) from the environment and use these as the offset at
537     // which to load our static data and function table.
538     // See:
539     // https://github.com/WebAssembly/tool-conventions/blob/master/DynamicLinking.md
540     WasmSym::memoryBase =
541         createUndefinedGlobal("__memory_base", &globalTypeI32);
542     WasmSym::tableBase = createUndefinedGlobal("__table_base", &globalTypeI32);
543     WasmSym::memoryBase->markLive();
544     WasmSym::tableBase->markLive();
545   } else {
546     // For non-PIC code
547     WasmSym::stackPointer = createGlobalVariable("__stack_pointer", true, 0);
548     WasmSym::stackPointer->markLive();
549   }
550 
551   if (config->sharedMemory && !config->shared) {
552     // Passive segments are used to avoid memory being reinitialized on each
553     // thread's instantiation. These passive segments are initialized and
554     // dropped in __wasm_init_memory, which is registered as the start function
555     WasmSym::initMemory = symtab->addSyntheticFunction(
556         "__wasm_init_memory", WASM_SYMBOL_VISIBILITY_HIDDEN,
557         make<SyntheticFunction>(nullSignature, "__wasm_init_memory"));
558     WasmSym::initMemoryFlag = symtab->addSyntheticDataSymbol(
559         "__wasm_init_memory_flag", WASM_SYMBOL_VISIBILITY_HIDDEN);
560     assert(WasmSym::initMemoryFlag);
561     WasmSym::tlsBase = createGlobalVariable("__tls_base", true, 0);
562     WasmSym::tlsSize = createGlobalVariable("__tls_size", false, 0);
563     WasmSym::tlsAlign = createGlobalVariable("__tls_align", false, 1);
564     WasmSym::initTLS = symtab->addSyntheticFunction(
565         "__wasm_init_tls", WASM_SYMBOL_VISIBILITY_HIDDEN,
566         make<SyntheticFunction>(i32ArgSignature, "__wasm_init_tls"));
567   }
568 }
569 
570 static void createOptionalSymbols() {
571   if (config->relocatable)
572     return;
573 
574   WasmSym::dsoHandle = symtab->addOptionalDataSymbol("__dso_handle");
575 
576   if (!config->shared)
577     WasmSym::dataEnd = symtab->addOptionalDataSymbol("__data_end");
578 
579   if (!config->isPic) {
580     WasmSym::globalBase = symtab->addOptionalDataSymbol("__global_base");
581     WasmSym::heapBase = symtab->addOptionalDataSymbol("__heap_base");
582     WasmSym::definedMemoryBase = symtab->addOptionalDataSymbol("__memory_base");
583     WasmSym::definedTableBase = symtab->addOptionalDataSymbol("__table_base");
584   }
585 }
586 
587 // Reconstructs command line arguments so that so that you can re-run
588 // the same command with the same inputs. This is for --reproduce.
589 static std::string createResponseFile(const opt::InputArgList &args) {
590   SmallString<0> data;
591   raw_svector_ostream os(data);
592 
593   // Copy the command line to the output while rewriting paths.
594   for (auto *arg : args) {
595     switch (arg->getOption().getID()) {
596     case OPT_reproduce:
597       break;
598     case OPT_INPUT:
599       os << quote(relativeToRoot(arg->getValue())) << "\n";
600       break;
601     case OPT_o:
602       // If -o path contains directories, "lld @response.txt" will likely
603       // fail because the archive we are creating doesn't contain empty
604       // directories for the output path (-o doesn't create directories).
605       // Strip directories to prevent the issue.
606       os << "-o " << quote(sys::path::filename(arg->getValue())) << "\n";
607       break;
608     default:
609       os << toString(*arg) << "\n";
610     }
611   }
612   return std::string(data.str());
613 }
614 
615 // The --wrap option is a feature to rename symbols so that you can write
616 // wrappers for existing functions. If you pass `-wrap=foo`, all
617 // occurrences of symbol `foo` are resolved to `wrap_foo` (so, you are
618 // expected to write `wrap_foo` function as a wrapper). The original
619 // symbol becomes accessible as `real_foo`, so you can call that from your
620 // wrapper.
621 //
622 // This data structure is instantiated for each -wrap option.
623 struct WrappedSymbol {
624   Symbol *sym;
625   Symbol *real;
626   Symbol *wrap;
627 };
628 
629 static Symbol *addUndefined(StringRef name) {
630   return symtab->addUndefinedFunction(name, None, None, WASM_SYMBOL_UNDEFINED,
631                                       nullptr, nullptr, false);
632 }
633 
634 // Handles -wrap option.
635 //
636 // This function instantiates wrapper symbols. At this point, they seem
637 // like they are not being used at all, so we explicitly set some flags so
638 // that LTO won't eliminate them.
639 static std::vector<WrappedSymbol> addWrappedSymbols(opt::InputArgList &args) {
640   std::vector<WrappedSymbol> v;
641   DenseSet<StringRef> seen;
642 
643   for (auto *arg : args.filtered(OPT_wrap)) {
644     StringRef name = arg->getValue();
645     if (!seen.insert(name).second)
646       continue;
647 
648     Symbol *sym = symtab->find(name);
649     if (!sym)
650       continue;
651 
652     Symbol *real = addUndefined(saver.save("__real_" + name));
653     Symbol *wrap = addUndefined(saver.save("__wrap_" + name));
654     v.push_back({sym, real, wrap});
655 
656     // We want to tell LTO not to inline symbols to be overwritten
657     // because LTO doesn't know the final symbol contents after renaming.
658     real->canInline = false;
659     sym->canInline = false;
660 
661     // Tell LTO not to eliminate these symbols.
662     sym->isUsedInRegularObj = true;
663     wrap->isUsedInRegularObj = true;
664     real->isUsedInRegularObj = false;
665   }
666   return v;
667 }
668 
669 // Do renaming for -wrap by updating pointers to symbols.
670 //
671 // When this function is executed, only InputFiles and symbol table
672 // contain pointers to symbol objects. We visit them to replace pointers,
673 // so that wrapped symbols are swapped as instructed by the command line.
674 static void wrapSymbols(ArrayRef<WrappedSymbol> wrapped) {
675   DenseMap<Symbol *, Symbol *> map;
676   for (const WrappedSymbol &w : wrapped) {
677     map[w.sym] = w.wrap;
678     map[w.real] = w.sym;
679   }
680 
681   // Update pointers in input files.
682   parallelForEach(symtab->objectFiles, [&](InputFile *file) {
683     MutableArrayRef<Symbol *> syms = file->getMutableSymbols();
684     for (size_t i = 0, e = syms.size(); i != e; ++i)
685       if (Symbol *s = map.lookup(syms[i]))
686         syms[i] = s;
687   });
688 
689   // Update pointers in the symbol table.
690   for (const WrappedSymbol &w : wrapped)
691     symtab->wrap(w.sym, w.real, w.wrap);
692 }
693 
694 void LinkerDriver::link(ArrayRef<const char *> argsArr) {
695   WasmOptTable parser;
696   opt::InputArgList args = parser.parse(argsArr.slice(1));
697 
698   // Handle --help
699   if (args.hasArg(OPT_help)) {
700     parser.PrintHelp(lld::outs(),
701                      (std::string(argsArr[0]) + " [options] file...").c_str(),
702                      "LLVM Linker", false);
703     return;
704   }
705 
706   // Handle --version
707   if (args.hasArg(OPT_version) || args.hasArg(OPT_v)) {
708     lld::outs() << getLLDVersion() << "\n";
709     return;
710   }
711 
712   // Handle --reproduce
713   if (auto *arg = args.getLastArg(OPT_reproduce)) {
714     StringRef path = arg->getValue();
715     Expected<std::unique_ptr<TarWriter>> errOrWriter =
716         TarWriter::create(path, path::stem(path));
717     if (errOrWriter) {
718       tar = std::move(*errOrWriter);
719       tar->append("response.txt", createResponseFile(args));
720       tar->append("version.txt", getLLDVersion() + "\n");
721     } else {
722       error("--reproduce: " + toString(errOrWriter.takeError()));
723     }
724   }
725 
726   // Parse and evaluate -mllvm options.
727   std::vector<const char *> v;
728   v.push_back("wasm-ld (LLVM option parsing)");
729   for (auto *arg : args.filtered(OPT_mllvm))
730     v.push_back(arg->getValue());
731   cl::ParseCommandLineOptions(v.size(), v.data());
732 
733   errorHandler().errorLimit = args::getInteger(args, OPT_error_limit, 20);
734 
735   readConfigs(args);
736 
737   createFiles(args);
738   if (errorCount())
739     return;
740 
741   setConfigs();
742   checkOptions(args);
743   if (errorCount())
744     return;
745 
746   if (auto *arg = args.getLastArg(OPT_allow_undefined_file))
747     readImportFile(arg->getValue());
748 
749   // Fail early if the output file or map file is not writable. If a user has a
750   // long link, e.g. due to a large LTO link, they do not wish to run it and
751   // find that it failed because there was a mistake in their command-line.
752   if (auto e = tryCreateFile(config->outputFile))
753     error("cannot open output file " + config->outputFile + ": " + e.message());
754   // TODO(sbc): add check for map file too once we add support for that.
755   if (errorCount())
756     return;
757 
758   // Handle --trace-symbol.
759   for (auto *arg : args.filtered(OPT_trace_symbol))
760     symtab->trace(arg->getValue());
761 
762   for (auto *arg : args.filtered(OPT_export))
763     config->exportedSymbols.insert(arg->getValue());
764 
765   createSyntheticSymbols();
766 
767   // Add all files to the symbol table. This will add almost all
768   // symbols that we need to the symbol table.
769   for (InputFile *f : files)
770     symtab->addFile(f);
771   if (errorCount())
772     return;
773 
774   // Handle the `--undefined <sym>` options.
775   for (auto *arg : args.filtered(OPT_undefined))
776     handleUndefined(arg->getValue());
777 
778   // Handle the `--export <sym>` options
779   // This works like --undefined but also exports the symbol if its found
780   for (auto *arg : args.filtered(OPT_export))
781     handleUndefined(arg->getValue());
782 
783   Symbol *entrySym = nullptr;
784   if (!config->relocatable && !config->entry.empty()) {
785     entrySym = handleUndefined(config->entry);
786     if (entrySym && entrySym->isDefined())
787       entrySym->forceExport = true;
788     else
789       error("entry symbol not defined (pass --no-entry to suppress): " +
790             config->entry);
791   }
792 
793   createOptionalSymbols();
794 
795   if (errorCount())
796     return;
797 
798   // Create wrapped symbols for -wrap option.
799   std::vector<WrappedSymbol> wrapped = addWrappedSymbols(args);
800 
801   // If any of our inputs are bitcode files, the LTO code generator may create
802   // references to certain library functions that might not be explicit in the
803   // bitcode file's symbol table. If any of those library functions are defined
804   // in a bitcode file in an archive member, we need to arrange to use LTO to
805   // compile those archive members by adding them to the link beforehand.
806   //
807   // We only need to add libcall symbols to the link before LTO if the symbol's
808   // definition is in bitcode. Any other required libcall symbols will be added
809   // to the link after LTO when we add the LTO object file to the link.
810   if (!symtab->bitcodeFiles.empty())
811     for (auto *s : lto::LTO::getRuntimeLibcallSymbols())
812       handleLibcall(s);
813   if (errorCount())
814     return;
815 
816   // Do link-time optimization if given files are LLVM bitcode files.
817   // This compiles bitcode files into real object files.
818   symtab->addCombinedLTOObject();
819   if (errorCount())
820     return;
821 
822   // Resolve any variant symbols that were created due to signature
823   // mismatchs.
824   symtab->handleSymbolVariants();
825   if (errorCount())
826     return;
827 
828   // Apply symbol renames for -wrap.
829   if (!wrapped.empty())
830     wrapSymbols(wrapped);
831 
832   for (auto *arg : args.filtered(OPT_export)) {
833     Symbol *sym = symtab->find(arg->getValue());
834     if (sym && sym->isDefined())
835       sym->forceExport = true;
836     else if (!config->allowUndefined)
837       error(Twine("symbol exported via --export not found: ") +
838             arg->getValue());
839   }
840 
841   if (!config->relocatable) {
842     // Add synthetic dummies for weak undefined functions.  Must happen
843     // after LTO otherwise functions may not yet have signatures.
844     symtab->handleWeakUndefines();
845   }
846 
847   if (entrySym)
848     entrySym->setHidden(false);
849 
850   if (errorCount())
851     return;
852 
853   // Do size optimizations: garbage collection
854   markLive();
855 
856   // Write the result to the file.
857   writeResult();
858 }
859 
860 } // namespace wasm
861 } // namespace lld
862