xref: /llvm-project-15.0.7/lld/wasm/Driver.cpp (revision ed2f9a60)
1 //===- Driver.cpp ---------------------------------------------------------===//
2 //
3 //                             The LLVM Linker
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
10 #include "lld/Common/Driver.h"
11 #include "Config.h"
12 #include "InputChunks.h"
13 #include "InputGlobal.h"
14 #include "MarkLive.h"
15 #include "SymbolTable.h"
16 #include "Writer.h"
17 #include "lld/Common/Args.h"
18 #include "lld/Common/ErrorHandler.h"
19 #include "lld/Common/Memory.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/ArgList.h"
26 #include "llvm/Support/CommandLine.h"
27 #include "llvm/Support/Path.h"
28 #include "llvm/Support/Process.h"
29 #include "llvm/Support/TargetSelect.h"
30 
31 #define DEBUG_TYPE "lld"
32 
33 using namespace llvm;
34 using namespace llvm::sys;
35 using namespace llvm::wasm;
36 
37 using namespace lld;
38 using namespace lld::wasm;
39 
40 Configuration *lld::wasm::Config;
41 
42 namespace {
43 
44 // Create enum with OPT_xxx values for each option in Options.td
45 enum {
46   OPT_INVALID = 0,
47 #define OPTION(_1, _2, ID, _4, _5, _6, _7, _8, _9, _10, _11, _12) OPT_##ID,
48 #include "Options.inc"
49 #undef OPTION
50 };
51 
52 // This function is called on startup. We need this for LTO since
53 // LTO calls LLVM functions to compile bitcode files to native code.
54 // Technically this can be delayed until we read bitcode files, but
55 // we don't bother to do lazily because the initialization is fast.
56 static void initLLVM() {
57   InitializeAllTargets();
58   InitializeAllTargetMCs();
59   InitializeAllAsmPrinters();
60   InitializeAllAsmParsers();
61 }
62 
63 class LinkerDriver {
64 public:
65   void link(ArrayRef<const char *> ArgsArr);
66 
67 private:
68   void createFiles(opt::InputArgList &Args);
69   void addFile(StringRef Path);
70   void addLibrary(StringRef Name);
71 
72   // True if we are in --whole-archive and --no-whole-archive.
73   bool InWholeArchive = false;
74 
75   std::vector<InputFile *> Files;
76 };
77 } // anonymous namespace
78 
79 bool lld::wasm::link(ArrayRef<const char *> Args, bool CanExitEarly,
80                      raw_ostream &Error) {
81   errorHandler().LogName = sys::path::filename(Args[0]);
82   errorHandler().ErrorOS = &Error;
83   errorHandler().ColorDiagnostics = Error.has_colors();
84   errorHandler().ErrorLimitExceededMsg =
85       "too many errors emitted, stopping now (use "
86       "-error-limit=0 to see all errors)";
87 
88   Config = make<Configuration>();
89   Symtab = make<SymbolTable>();
90 
91   initLLVM();
92   LinkerDriver().link(Args);
93 
94   // Exit immediately if we don't need to return to the caller.
95   // This saves time because the overhead of calling destructors
96   // for all globally-allocated objects is not negligible.
97   if (CanExitEarly)
98     exitLld(errorCount() ? 1 : 0);
99 
100   freeArena();
101   return !errorCount();
102 }
103 
104 // Create prefix string literals used in Options.td
105 #define PREFIX(NAME, VALUE) const char *const NAME[] = VALUE;
106 #include "Options.inc"
107 #undef PREFIX
108 
109 // Create table mapping all options defined in Options.td
110 static const opt::OptTable::Info OptInfo[] = {
111 #define OPTION(X1, X2, ID, KIND, GROUP, ALIAS, X7, X8, X9, X10, X11, X12)      \
112   {X1, X2, X10,         X11,         OPT_##ID, opt::Option::KIND##Class,       \
113    X9, X8, OPT_##GROUP, OPT_##ALIAS, X7,       X12},
114 #include "Options.inc"
115 #undef OPTION
116 };
117 
118 namespace {
119 class WasmOptTable : public llvm::opt::OptTable {
120 public:
121   WasmOptTable() : OptTable(OptInfo) {}
122   opt::InputArgList parse(ArrayRef<const char *> Argv);
123 };
124 } // namespace
125 
126 // Set color diagnostics according to -color-diagnostics={auto,always,never}
127 // or -no-color-diagnostics flags.
128 static void handleColorDiagnostics(opt::InputArgList &Args) {
129   auto *Arg = Args.getLastArg(OPT_color_diagnostics, OPT_color_diagnostics_eq,
130                               OPT_no_color_diagnostics);
131   if (!Arg)
132     return;
133   if (Arg->getOption().getID() == OPT_color_diagnostics) {
134     errorHandler().ColorDiagnostics = true;
135   } else if (Arg->getOption().getID() == OPT_no_color_diagnostics) {
136     errorHandler().ColorDiagnostics = false;
137   } else {
138     StringRef S = Arg->getValue();
139     if (S == "always")
140       errorHandler().ColorDiagnostics = true;
141     else if (S == "never")
142       errorHandler().ColorDiagnostics = false;
143     else if (S != "auto")
144       error("unknown option: --color-diagnostics=" + S);
145   }
146 }
147 
148 // Find a file by concatenating given paths.
149 static Optional<std::string> findFile(StringRef Path1, const Twine &Path2) {
150   SmallString<128> S;
151   path::append(S, Path1, Path2);
152   if (fs::exists(S))
153     return S.str().str();
154   return None;
155 }
156 
157 opt::InputArgList WasmOptTable::parse(ArrayRef<const char *> Argv) {
158   SmallVector<const char *, 256> Vec(Argv.data(), Argv.data() + Argv.size());
159 
160   unsigned MissingIndex;
161   unsigned MissingCount;
162 
163   // Expand response files (arguments in the form of @<filename>)
164   cl::ExpandResponseFiles(Saver, cl::TokenizeGNUCommandLine, Vec);
165 
166   opt::InputArgList Args = this->ParseArgs(Vec, MissingIndex, MissingCount);
167 
168   handleColorDiagnostics(Args);
169   for (auto *Arg : Args.filtered(OPT_UNKNOWN))
170     error("unknown argument: " + Arg->getSpelling());
171   return Args;
172 }
173 
174 // Currently we allow a ".imports" to live alongside a library. This can
175 // be used to specify a list of symbols which can be undefined at link
176 // time (imported from the environment.  For example libc.a include an
177 // import file that lists the syscall functions it relies on at runtime.
178 // In the long run this information would be better stored as a symbol
179 // attribute/flag in the object file itself.
180 // See: https://github.com/WebAssembly/tool-conventions/issues/35
181 static void readImportFile(StringRef Filename) {
182   if (Optional<MemoryBufferRef> Buf = readFile(Filename))
183     for (StringRef Sym : args::getLines(*Buf))
184       Config->AllowUndefinedSymbols.insert(Sym);
185 }
186 
187 // Returns slices of MB by parsing MB as an archive file.
188 // Each slice consists of a member file in the archive.
189 std::vector<MemoryBufferRef> static getArchiveMembers(
190     MemoryBufferRef MB) {
191   std::unique_ptr<Archive> File =
192       CHECK(Archive::create(MB),
193             MB.getBufferIdentifier() + ": failed to parse archive");
194 
195   std::vector<MemoryBufferRef> V;
196   Error Err = Error::success();
197   for (const ErrorOr<Archive::Child> &COrErr : File->children(Err)) {
198     Archive::Child C =
199         CHECK(COrErr, MB.getBufferIdentifier() +
200                           ": could not get the child of the archive");
201     MemoryBufferRef MBRef =
202         CHECK(C.getMemoryBufferRef(),
203               MB.getBufferIdentifier() +
204                   ": could not get the buffer for a child of the archive");
205     V.push_back(MBRef);
206   }
207   if (Err)
208     fatal(MB.getBufferIdentifier() + ": Archive::children failed: " +
209           toString(std::move(Err)));
210 
211   // Take ownership of memory buffers created for members of thin archives.
212   for (std::unique_ptr<MemoryBuffer> &MB : File->takeThinBuffers())
213     make<std::unique_ptr<MemoryBuffer>>(std::move(MB));
214 
215   return V;
216 }
217 
218 void LinkerDriver::addFile(StringRef Path) {
219   Optional<MemoryBufferRef> Buffer = readFile(Path);
220   if (!Buffer.hasValue())
221     return;
222   MemoryBufferRef MBRef = *Buffer;
223 
224   switch (identify_magic(MBRef.getBuffer())) {
225   case file_magic::archive: {
226     // Handle -whole-archive.
227     if (InWholeArchive) {
228       for (MemoryBufferRef &M : getArchiveMembers(MBRef))
229         Files.push_back(createObjectFile(M));
230       return;
231     }
232 
233     SmallString<128> ImportFile = Path;
234     path::replace_extension(ImportFile, ".imports");
235     if (fs::exists(ImportFile))
236       readImportFile(ImportFile.str());
237 
238     Files.push_back(make<ArchiveFile>(MBRef));
239     return;
240   }
241   case file_magic::bitcode:
242   case file_magic::wasm_object:
243     Files.push_back(createObjectFile(MBRef));
244     break;
245   default:
246     error("unknown file type: " + MBRef.getBufferIdentifier());
247   }
248 }
249 
250 // Add a given library by searching it from input search paths.
251 void LinkerDriver::addLibrary(StringRef Name) {
252   for (StringRef Dir : Config->SearchPaths) {
253     if (Optional<std::string> S = findFile(Dir, "lib" + Name + ".a")) {
254       addFile(*S);
255       return;
256     }
257   }
258 
259   error("unable to find library -l" + Name);
260 }
261 
262 void LinkerDriver::createFiles(opt::InputArgList &Args) {
263   for (auto *Arg : Args) {
264     switch (Arg->getOption().getUnaliasedOption().getID()) {
265     case OPT_l:
266       addLibrary(Arg->getValue());
267       break;
268     case OPT_INPUT:
269       addFile(Arg->getValue());
270       break;
271     case OPT_whole_archive:
272       InWholeArchive = true;
273       break;
274     case OPT_no_whole_archive:
275       InWholeArchive = false;
276       break;
277     }
278   }
279 }
280 
281 static StringRef getEntry(opt::InputArgList &Args, StringRef Default) {
282   auto *Arg = Args.getLastArg(OPT_entry, OPT_no_entry);
283   if (!Arg)
284     return Default;
285   if (Arg->getOption().getID() == OPT_no_entry)
286     return "";
287   return Arg->getValue();
288 }
289 
290 static const uint8_t UnreachableFn[] = {
291     0x03 /* ULEB length */, 0x00 /* ULEB num locals */,
292     0x00 /* opcode unreachable */, 0x0b /* opcode end */
293 };
294 
295 // For weak undefined functions, there may be "call" instructions that reference
296 // the symbol. In this case, we need to synthesise a dummy/stub function that
297 // will abort at runtime, so that relocations can still provided an operand to
298 // the call instruction that passes Wasm validation.
299 static void handleWeakUndefines() {
300   for (Symbol *Sym : Symtab->getSymbols()) {
301     if (!Sym->isUndefined() || !Sym->isWeak())
302       continue;
303     auto *FuncSym = dyn_cast<FunctionSymbol>(Sym);
304     if (!FuncSym)
305       continue;
306 
307     // It is possible for undefined functions not to have a signature (eg. if
308     // added via "--undefined"), but weak undefined ones do have a signature.
309     assert(FuncSym->FunctionType);
310     const WasmSignature &Sig = *FuncSym->FunctionType;
311 
312     // Add a synthetic dummy for weak undefined functions.  These dummies will
313     // be GC'd if not used as the target of any "call" instructions.
314     Optional<std::string> SymName = demangleItanium(Sym->getName());
315     StringRef DebugName =
316         Saver.save("undefined function " +
317                    (SymName ? StringRef(*SymName) : Sym->getName()));
318     SyntheticFunction *Func =
319         make<SyntheticFunction>(Sig, Sym->getName(), DebugName);
320     Func->setBody(UnreachableFn);
321     // Ensure it compares equal to the null pointer, and so that table relocs
322     // don't pull in the stub body (only call-operand relocs should do that).
323     Func->setTableIndex(0);
324     Symtab->SyntheticFunctions.emplace_back(Func);
325     // Hide our dummy to prevent export.
326     uint32_t Flags = WASM_SYMBOL_VISIBILITY_HIDDEN;
327     replaceSymbol<DefinedFunction>(Sym, Sym->getName(), Flags, nullptr, Func);
328   }
329 }
330 
331 // Force Sym to be entered in the output. Used for -u or equivalent.
332 static Symbol *handleUndefined(StringRef Name) {
333   Symbol *Sym = Symtab->find(Name);
334   if (!Sym)
335     return nullptr;
336 
337   // Since symbol S may not be used inside the program, LTO may
338   // eliminate it. Mark the symbol as "used" to prevent it.
339   Sym->IsUsedInRegularObj = true;
340 
341   if (auto *LazySym = dyn_cast<LazySymbol>(Sym))
342     LazySym->fetch();
343 
344   return Sym;
345 }
346 
347 void LinkerDriver::link(ArrayRef<const char *> ArgsArr) {
348   WasmOptTable Parser;
349   opt::InputArgList Args = Parser.parse(ArgsArr.slice(1));
350 
351   // Handle --help
352   if (Args.hasArg(OPT_help)) {
353     Parser.PrintHelp(outs(), ArgsArr[0], "LLVM Linker", false);
354     return;
355   }
356 
357   // Handle --version
358   if (Args.hasArg(OPT_version) || Args.hasArg(OPT_v)) {
359     outs() << getLLDVersion() << "\n";
360     return;
361   }
362 
363   // Parse and evaluate -mllvm options.
364   std::vector<const char *> V;
365   V.push_back("wasm-ld (LLVM option parsing)");
366   for (auto *Arg : Args.filtered(OPT_mllvm))
367     V.push_back(Arg->getValue());
368   cl::ParseCommandLineOptions(V.size(), V.data());
369 
370   errorHandler().ErrorLimit = args::getInteger(Args, OPT_error_limit, 20);
371 
372   Config->AllowUndefined = Args.hasArg(OPT_allow_undefined);
373   Config->Demangle = Args.hasFlag(OPT_demangle, OPT_no_demangle, true);
374   Config->DisableVerify = Args.hasArg(OPT_disable_verify);
375   Config->Entry = getEntry(Args, Args.hasArg(OPT_relocatable) ? "" : "_start");
376   Config->ExportAll = Args.hasArg(OPT_export_all);
377   Config->ExportTable = Args.hasArg(OPT_export_table);
378   errorHandler().FatalWarnings =
379       Args.hasFlag(OPT_fatal_warnings, OPT_no_fatal_warnings, false);
380   Config->ImportMemory = Args.hasArg(OPT_import_memory);
381   Config->ImportTable = Args.hasArg(OPT_import_table);
382   Config->LTOO = args::getInteger(Args, OPT_lto_O, 2);
383   Config->LTOPartitions = args::getInteger(Args, OPT_lto_partitions, 1);
384   Config->Optimize = args::getInteger(Args, OPT_O, 0);
385   Config->OutputFile = Args.getLastArgValue(OPT_o);
386   Config->Relocatable = Args.hasArg(OPT_relocatable);
387   Config->GcSections =
388       Args.hasFlag(OPT_gc_sections, OPT_no_gc_sections, !Config->Relocatable);
389   Config->MergeDataSegments =
390       Args.hasFlag(OPT_merge_data_segments, OPT_no_merge_data_segments,
391                    !Config->Relocatable);
392   Config->PrintGcSections =
393       Args.hasFlag(OPT_print_gc_sections, OPT_no_print_gc_sections, false);
394   Config->SaveTemps = Args.hasArg(OPT_save_temps);
395   Config->SearchPaths = args::getStrings(Args, OPT_L);
396   Config->StripAll = Args.hasArg(OPT_strip_all);
397   Config->StripDebug = Args.hasArg(OPT_strip_debug);
398   Config->StackFirst = Args.hasArg(OPT_stack_first);
399   Config->ThinLTOCacheDir = Args.getLastArgValue(OPT_thinlto_cache_dir);
400   Config->ThinLTOCachePolicy = CHECK(
401       parseCachePruningPolicy(Args.getLastArgValue(OPT_thinlto_cache_policy)),
402       "--thinlto-cache-policy: invalid cache policy");
403   Config->ThinLTOJobs = args::getInteger(Args, OPT_thinlto_jobs, -1u);
404   errorHandler().Verbose = Args.hasArg(OPT_verbose);
405   ThreadsEnabled = Args.hasFlag(OPT_threads, OPT_no_threads, true);
406 
407   Config->InitialMemory = args::getInteger(Args, OPT_initial_memory, 0);
408   Config->GlobalBase = args::getInteger(Args, OPT_global_base, 1024);
409   Config->MaxMemory = args::getInteger(Args, OPT_max_memory, 0);
410   Config->ZStackSize =
411       args::getZOptionValue(Args, OPT_z, "stack-size", WasmPageSize);
412 
413   Config->CompressRelocTargets = Config->Optimize > 0 && !Config->Relocatable;
414 
415   if (Config->LTOO > 3)
416     error("invalid optimization level for LTO: " + Twine(Config->LTOO));
417   if (Config->LTOPartitions == 0)
418     error("--lto-partitions: number of threads must be > 0");
419   if (Config->ThinLTOJobs == 0)
420     error("--thinlto-jobs: number of threads must be > 0");
421 
422   if (auto *Arg = Args.getLastArg(OPT_allow_undefined_file))
423     readImportFile(Arg->getValue());
424 
425   if (!Args.hasArg(OPT_INPUT)) {
426     error("no input files");
427     return;
428   }
429 
430   if (Config->OutputFile.empty())
431     error("no output file specified");
432 
433   if (Config->ImportTable && Config->ExportTable)
434     error("--import-table and --export-table may not be used together");
435 
436   if (Config->Relocatable) {
437     if (!Config->Entry.empty())
438       error("entry point specified for relocatable output file");
439     if (Config->GcSections)
440       error("-r and --gc-sections may not be used together");
441     if (Args.hasArg(OPT_undefined))
442       error("-r -and --undefined may not be used together");
443   }
444 
445   Symbol *EntrySym = nullptr;
446   if (!Config->Relocatable) {
447     llvm::wasm::WasmGlobal Global;
448     Global.Type = {WASM_TYPE_I32, true};
449     Global.InitExpr.Value.Int32 = 0;
450     Global.InitExpr.Opcode = WASM_OPCODE_I32_CONST;
451     Global.SymbolName = "__stack_pointer";
452     InputGlobal *StackPointer = make<InputGlobal>(Global, nullptr);
453     StackPointer->Live = true;
454 
455     static WasmSignature NullSignature = {{}, WASM_TYPE_NORESULT};
456 
457     // Add synthetic symbols before any others
458     WasmSym::CallCtors = Symtab->addSyntheticFunction(
459         "__wasm_call_ctors", WASM_SYMBOL_VISIBILITY_HIDDEN,
460         make<SyntheticFunction>(NullSignature, "__wasm_call_ctors"));
461     // TODO(sbc): Remove WASM_SYMBOL_VISIBILITY_HIDDEN when the mutable global
462     // spec proposal is implemented in all major browsers.
463     // See: https://github.com/WebAssembly/mutable-global
464     WasmSym::StackPointer = Symtab->addSyntheticGlobal(
465         "__stack_pointer", WASM_SYMBOL_VISIBILITY_HIDDEN, StackPointer);
466     WasmSym::HeapBase = Symtab->addSyntheticDataSymbol("__heap_base", 0);
467     WasmSym::DsoHandle = Symtab->addSyntheticDataSymbol(
468         "__dso_handle", WASM_SYMBOL_VISIBILITY_HIDDEN);
469     WasmSym::DataEnd = Symtab->addSyntheticDataSymbol("__data_end", 0);
470   }
471 
472   createFiles(Args);
473   if (errorCount())
474     return;
475 
476   // Add all files to the symbol table. This will add almost all
477   // symbols that we need to the symbol table.
478   for (InputFile *F : Files)
479     Symtab->addFile(F);
480   if (errorCount())
481     return;
482 
483   // Handle the `--undefined <sym>` options.
484   for (auto *Arg : Args.filtered(OPT_undefined))
485     handleUndefined(Arg->getValue());
486 
487   // Handle the `--export <sym>` options
488   // This works like --undefined but also exports the symbol if its found
489   for (auto *Arg : Args.filtered(OPT_export)) {
490     Symbol *Sym = handleUndefined(Arg->getValue());
491     if (Sym && Sym->isDefined())
492       Sym->ForceExport = true;
493     else if (!Config->AllowUndefined)
494       error(Twine("symbol exported via --export not found: ") +
495             Arg->getValue());
496   }
497 
498   if (!Config->Relocatable) {
499     // Add synthetic dummies for weak undefined functions.
500     handleWeakUndefines();
501 
502     if (!Config->Entry.empty()) {
503       EntrySym = handleUndefined(Config->Entry);
504       if (!EntrySym)
505         error("entry symbol not defined (pass --no-entry to supress): " +
506               Config->Entry);
507     }
508 
509     // Make sure we have resolved all symbols.
510     if (!Config->AllowUndefined)
511       Symtab->reportRemainingUndefines();
512   }
513 
514   if (errorCount())
515     return;
516 
517   // Do link-time optimization if given files are LLVM bitcode files.
518   // This compiles bitcode files into real object files.
519   Symtab->addCombinedLTOObject();
520   if (errorCount())
521     return;
522 
523   if (EntrySym)
524     EntrySym->setHidden(false);
525 
526   if (errorCount())
527     return;
528 
529   // Do size optimizations: garbage collection
530   markLive();
531 
532   // Write the result to the file.
533   writeResult();
534 }
535