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