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