blob: c8f45a2bedfbed399d94d9a3697a05619dc5d6fd [file] [log] [blame]
Sam Cleggc94d3932017-11-17 18:14:09 +00001//===- 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"
Sam Clegg78f766a2018-02-20 21:08:28 +000011#include "Config.h"
Sam Clegg93102972018-02-23 05:08:53 +000012#include "InputGlobal.h"
Sam Clegg03626332018-01-31 01:45:47 +000013#include "MarkLive.h"
Sam Cleggc94d3932017-11-17 18:14:09 +000014#include "SymbolTable.h"
15#include "Writer.h"
Rui Ueyama3e039442017-11-28 19:58:45 +000016#include "lld/Common/Args.h"
Sam Cleggc94d3932017-11-17 18:14:09 +000017#include "lld/Common/ErrorHandler.h"
Rui Ueyama2017d522017-11-28 20:39:17 +000018#include "lld/Common/Memory.h"
Sam Cleggc94d3932017-11-17 18:14:09 +000019#include "lld/Common/Threads.h"
20#include "lld/Common/Version.h"
21#include "llvm/ADT/Twine.h"
22#include "llvm/Object/Wasm.h"
23#include "llvm/Option/ArgList.h"
24#include "llvm/Support/CommandLine.h"
25#include "llvm/Support/Path.h"
26#include "llvm/Support/Process.h"
27
Sam Clegg03626332018-01-31 01:45:47 +000028#define DEBUG_TYPE "lld"
29
Sam Cleggc94d3932017-11-17 18:14:09 +000030using namespace llvm;
31using namespace llvm::sys;
32using namespace llvm::wasm;
Sam Cleggc94d3932017-11-17 18:14:09 +000033
34using namespace lld;
35using namespace lld::wasm;
36
37namespace {
38
39// Parses command line options.
40class WasmOptTable : public llvm::opt::OptTable {
41public:
42 WasmOptTable();
43 llvm::opt::InputArgList parse(ArrayRef<const char *> Argv);
44};
45
46// Create enum with OPT_xxx values for each option in Options.td
47enum {
48 OPT_INVALID = 0,
49#define OPTION(_1, _2, ID, _4, _5, _6, _7, _8, _9, _10, _11, _12) OPT_##ID,
50#include "Options.inc"
51#undef OPTION
52};
53
54class LinkerDriver {
55public:
56 void link(ArrayRef<const char *> ArgsArr);
57
58private:
59 void createFiles(llvm::opt::InputArgList &Args);
60 void addFile(StringRef Path);
61 void addLibrary(StringRef Name);
62 std::vector<InputFile *> Files;
Sam Clegg93102972018-02-23 05:08:53 +000063 llvm::wasm::WasmGlobal StackPointerGlobal;
Sam Cleggc94d3932017-11-17 18:14:09 +000064};
65
66} // anonymous namespace
67
Sam Cleggc94d3932017-11-17 18:14:09 +000068Configuration *lld::wasm::Config;
Sam Cleggc94d3932017-11-17 18:14:09 +000069
70bool lld::wasm::link(ArrayRef<const char *> Args, bool CanExitEarly,
71 raw_ostream &Error) {
72 errorHandler().LogName = Args[0];
73 errorHandler().ErrorOS = &Error;
74 errorHandler().ColorDiagnostics = Error.has_colors();
75 errorHandler().ErrorLimitExceededMsg =
76 "too many errors emitted, stopping now (use "
77 "-error-limit=0 to see all errors)";
78
79 Config = make<Configuration>();
80 Symtab = make<SymbolTable>();
81
82 LinkerDriver().link(Args);
83
84 // Exit immediately if we don't need to return to the caller.
85 // This saves time because the overhead of calling destructors
86 // for all globally-allocated objects is not negligible.
87 if (CanExitEarly)
88 exitLld(errorCount() ? 1 : 0);
89
90 freeArena();
91 return !errorCount();
92}
93
94// Create OptTable
95
96// Create prefix string literals used in Options.td
97#define PREFIX(NAME, VALUE) const char *const NAME[] = VALUE;
98#include "Options.inc"
99#undef PREFIX
100
101// Create table mapping all options defined in Options.td
102static const opt::OptTable::Info OptInfo[] = {
103#define OPTION(X1, X2, ID, KIND, GROUP, ALIAS, X7, X8, X9, X10, X11, X12) \
104 {X1, X2, X10, X11, OPT_##ID, opt::Option::KIND##Class, \
105 X9, X8, OPT_##GROUP, OPT_##ALIAS, X7, X12},
106#include "Options.inc"
107#undef OPTION
108};
109
Sam Cleggc94d3932017-11-17 18:14:09 +0000110// Set color diagnostics according to -color-diagnostics={auto,always,never}
111// or -no-color-diagnostics flags.
112static void handleColorDiagnostics(opt::InputArgList &Args) {
113 auto *Arg = Args.getLastArg(OPT_color_diagnostics, OPT_color_diagnostics_eq,
114 OPT_no_color_diagnostics);
115 if (!Arg)
116 return;
117
118 if (Arg->getOption().getID() == OPT_color_diagnostics)
119 errorHandler().ColorDiagnostics = true;
120 else if (Arg->getOption().getID() == OPT_no_color_diagnostics)
121 errorHandler().ColorDiagnostics = false;
122 else {
123 StringRef S = Arg->getValue();
124 if (S == "always")
125 errorHandler().ColorDiagnostics = true;
126 if (S == "never")
127 errorHandler().ColorDiagnostics = false;
128 if (S != "auto")
129 error("unknown option: -color-diagnostics=" + S);
130 }
131}
132
133// Find a file by concatenating given paths.
134static Optional<std::string> findFile(StringRef Path1, const Twine &Path2) {
135 SmallString<128> S;
136 path::append(S, Path1, Path2);
137 if (fs::exists(S))
138 return S.str().str();
139 return None;
140}
141
Sam Cleggc94d3932017-11-17 18:14:09 +0000142static void printHelp(const char *Argv0) {
Rui Ueyama6074e6b2017-12-11 23:19:11 +0000143 WasmOptTable().PrintHelp(outs(), Argv0, "LLVM Linker", false);
Sam Cleggc94d3932017-11-17 18:14:09 +0000144}
145
146WasmOptTable::WasmOptTable() : OptTable(OptInfo) {}
147
148opt::InputArgList WasmOptTable::parse(ArrayRef<const char *> Argv) {
149 SmallVector<const char *, 256> Vec(Argv.data(), Argv.data() + Argv.size());
150
151 unsigned MissingIndex;
152 unsigned MissingCount;
153 opt::InputArgList Args = this->ParseArgs(Vec, MissingIndex, MissingCount);
154
155 handleColorDiagnostics(Args);
156 for (auto *Arg : Args.filtered(OPT_UNKNOWN))
157 error("unknown argument: " + Arg->getSpelling());
158 return Args;
159}
160
Sam Clegg31efdcd2018-01-11 22:31:35 +0000161// Currently we allow a ".imports" to live alongside a library. This can
162// be used to specify a list of symbols which can be undefined at link
163// time (imported from the environment. For example libc.a include an
164// import file that lists the syscall functions it relies on at runtime.
165// In the long run this information would be better stored as a symbol
166// attribute/flag in the object file itself.
167// See: https://github.com/WebAssembly/tool-conventions/issues/35
168static void readImportFile(StringRef Filename) {
169 if (Optional<MemoryBufferRef> Buf = readFile(Filename))
170 for (StringRef Sym : args::getLines(*Buf))
171 Config->AllowUndefinedSymbols.insert(Sym);
172}
173
Sam Cleggc94d3932017-11-17 18:14:09 +0000174void LinkerDriver::addFile(StringRef Path) {
175 Optional<MemoryBufferRef> Buffer = readFile(Path);
176 if (!Buffer.hasValue())
177 return;
178 MemoryBufferRef MBRef = *Buffer;
179
Sam Clegg31efdcd2018-01-11 22:31:35 +0000180 if (identify_magic(MBRef.getBuffer()) == file_magic::archive) {
181 SmallString<128> ImportFile = Path;
182 path::replace_extension(ImportFile, ".imports");
183 if (fs::exists(ImportFile))
184 readImportFile(ImportFile.str());
185
Sam Cleggc94d3932017-11-17 18:14:09 +0000186 Files.push_back(make<ArchiveFile>(MBRef));
Sam Clegg31efdcd2018-01-11 22:31:35 +0000187 return;
188 }
189
190 Files.push_back(make<ObjFile>(MBRef));
Sam Cleggc94d3932017-11-17 18:14:09 +0000191}
192
193// Add a given library by searching it from input search paths.
194void LinkerDriver::addLibrary(StringRef Name) {
195 for (StringRef Dir : Config->SearchPaths) {
196 if (Optional<std::string> S = findFile(Dir, "lib" + Name + ".a")) {
197 addFile(*S);
198 return;
199 }
200 }
201
202 error("unable to find library -l" + Name);
203}
204
205void LinkerDriver::createFiles(opt::InputArgList &Args) {
206 for (auto *Arg : Args) {
207 switch (Arg->getOption().getUnaliasedOption().getID()) {
208 case OPT_l:
209 addLibrary(Arg->getValue());
210 break;
211 case OPT_INPUT:
212 addFile(Arg->getValue());
213 break;
214 }
215 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000216}
217
Rui Ueyama909d1232017-12-11 17:52:28 +0000218static StringRef getEntry(opt::InputArgList &Args, StringRef Default) {
Sam Clegg2c096ba2017-12-08 17:58:25 +0000219 auto *Arg = Args.getLastArg(OPT_entry, OPT_no_entry);
220 if (!Arg)
Rui Ueyama909d1232017-12-11 17:52:28 +0000221 return Default;
Sam Clegg2c096ba2017-12-08 17:58:25 +0000222 if (Arg->getOption().getID() == OPT_no_entry)
223 return "";
224 return Arg->getValue();
225}
226
Sam Clegg93102972018-02-23 05:08:53 +0000227static Symbol *addUndefinedFunction(StringRef Name, const WasmSignature *Type) {
228 return Symtab->addUndefined(Name, WASM_SYMBOL_TYPE_FUNCTION, 0, nullptr,
Sam Clegga1892302018-02-13 20:14:26 +0000229 Type);
230}
231
Sam Cleggc94d3932017-11-17 18:14:09 +0000232void LinkerDriver::link(ArrayRef<const char *> ArgsArr) {
233 WasmOptTable Parser;
234 opt::InputArgList Args = Parser.parse(ArgsArr.slice(1));
235
236 // Handle --help
237 if (Args.hasArg(OPT_help)) {
238 printHelp(ArgsArr[0]);
239 return;
240 }
241
242 // Parse and evaluate -mllvm options.
243 std::vector<const char *> V;
Rui Ueyamaceb15e82017-11-28 22:17:39 +0000244 V.push_back("wasm-ld (LLVM option parsing)");
Sam Cleggc94d3932017-11-17 18:14:09 +0000245 for (auto *Arg : Args.filtered(OPT_mllvm))
246 V.push_back(Arg->getValue());
247 cl::ParseCommandLineOptions(V.size(), V.data());
248
Rui Ueyama3e039442017-11-28 19:58:45 +0000249 errorHandler().ErrorLimit = args::getInteger(Args, OPT_error_limit, 20);
Sam Cleggc94d3932017-11-17 18:14:09 +0000250
251 if (Args.hasArg(OPT_version) || Args.hasArg(OPT_v)) {
252 outs() << getLLDVersion() << "\n";
253 return;
254 }
255
256 Config->AllowUndefined = Args.hasArg(OPT_allow_undefined);
Sam Cleggb8621592017-11-30 01:40:08 +0000257 Config->CheckSignatures =
258 Args.hasFlag(OPT_check_signatures, OPT_no_check_signatures, false);
Rui Ueyama8cbb3b52017-12-11 17:52:43 +0000259 Config->Entry = getEntry(Args, Args.hasArg(OPT_relocatable) ? "" : "_start");
Sam Cleggc94d3932017-11-17 18:14:09 +0000260 Config->ImportMemory = Args.hasArg(OPT_import_memory);
261 Config->OutputFile = Args.getLastArgValue(OPT_o);
Rui Ueyama8cbb3b52017-12-11 17:52:43 +0000262 Config->Relocatable = Args.hasArg(OPT_relocatable);
Sam Clegg03626332018-01-31 01:45:47 +0000263 Config->GcSections =
264 Args.hasFlag(OPT_gc_sections, OPT_no_gc_sections, !Config->Relocatable);
265 Config->PrintGcSections =
266 Args.hasFlag(OPT_print_gc_sections, OPT_no_print_gc_sections, false);
Rui Ueyama3e039442017-11-28 19:58:45 +0000267 Config->SearchPaths = args::getStrings(Args, OPT_L);
Sam Cleggc94d3932017-11-17 18:14:09 +0000268 Config->StripAll = Args.hasArg(OPT_strip_all);
269 Config->StripDebug = Args.hasArg(OPT_strip_debug);
Sam Cleggc94d3932017-11-17 18:14:09 +0000270 errorHandler().Verbose = Args.hasArg(OPT_verbose);
271 ThreadsEnabled = Args.hasFlag(OPT_threads, OPT_no_threads, true);
272
Rui Ueyama3e039442017-11-28 19:58:45 +0000273 Config->InitialMemory = args::getInteger(Args, OPT_initial_memory, 0);
274 Config->GlobalBase = args::getInteger(Args, OPT_global_base, 1024);
275 Config->MaxMemory = args::getInteger(Args, OPT_max_memory, 0);
276 Config->ZStackSize =
277 args::getZOptionValue(Args, OPT_z, "stack-size", WasmPageSize);
Sam Cleggc94d3932017-11-17 18:14:09 +0000278
279 if (auto *Arg = Args.getLastArg(OPT_allow_undefined_file))
Sam Clegg31efdcd2018-01-11 22:31:35 +0000280 readImportFile(Arg->getValue());
Sam Cleggc94d3932017-11-17 18:14:09 +0000281
Rui Ueyama4aab7b12018-02-16 22:58:19 +0000282 if (!Args.hasArg(OPT_INPUT)) {
283 error("no input files");
284 return;
285 }
286
Sam Cleggc94d3932017-11-17 18:14:09 +0000287 if (Config->OutputFile.empty())
288 error("no output file specified");
289
Sam Clegg03626332018-01-31 01:45:47 +0000290 if (Config->Relocatable) {
291 if (!Config->Entry.empty())
292 error("entry point specified for relocatable output file");
293 if (Config->GcSections)
294 error("-r and --gc-sections may not be used together");
295 if (Args.hasArg(OPT_undefined))
296 error("-r -and --undefined may not be used together");
297 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000298
Sam Clegg0f0a4282018-01-20 01:44:45 +0000299 Symbol *EntrySym = nullptr;
Sam Cleggc94d3932017-11-17 18:14:09 +0000300 if (!Config->Relocatable) {
Sam Clegg93102972018-02-23 05:08:53 +0000301 // Can't export the SP right now because it's mutable, and mutable
302 // globals aren't yet supported in the official binary format.
303 // TODO(sbc): Remove WASM_SYMBOL_VISIBILITY_HIDDEN if/when the
304 // "mutable global" proposal is accepted.
305 StackPointerGlobal.Type = {WASM_TYPE_I32, true};
306 StackPointerGlobal.InitExpr.Value.Int32 = 0;
307 StackPointerGlobal.InitExpr.Opcode = WASM_OPCODE_I32_CONST;
308 InputGlobal *StackPointer = make<InputGlobal>(StackPointerGlobal);
309 StackPointer->Live = true;
Sam Clegga1892302018-02-13 20:14:26 +0000310
Sam Clegg93102972018-02-23 05:08:53 +0000311 static WasmSignature NullSignature = {{}, WASM_TYPE_NORESULT};
Sam Clegga1892302018-02-13 20:14:26 +0000312 // Add synthetic symbols before any others
313 WasmSym::CallCtors = Symtab->addSyntheticFunction(
314 "__wasm_call_ctors", &NullSignature, WASM_SYMBOL_VISIBILITY_HIDDEN);
Sam Clegg93102972018-02-23 05:08:53 +0000315 WasmSym::StackPointer = Symtab->addSyntheticGlobal(
316 "__stack_pointer", WASM_SYMBOL_VISIBILITY_HIDDEN, StackPointer);
Sam Clegg00245532018-02-20 23:38:27 +0000317 WasmSym::HeapBase = Symtab->addSyntheticDataSymbol("__heap_base");
Sam Clegg93102972018-02-23 05:08:53 +0000318 WasmSym::DsoHandle = Symtab->addSyntheticDataSymbol(
319 "__dso_handle", WASM_SYMBOL_VISIBILITY_HIDDEN);
Sam Clegg00245532018-02-20 23:38:27 +0000320 WasmSym::DataEnd = Symtab->addSyntheticDataSymbol("__data_end");
Sam Clegga1892302018-02-13 20:14:26 +0000321
Sam Clegg50686852018-01-12 18:35:13 +0000322 if (!Config->Entry.empty())
Sam Clegga1892302018-02-13 20:14:26 +0000323 EntrySym = addUndefinedFunction(Config->Entry, &NullSignature);
Sam Cleggc94d3932017-11-17 18:14:09 +0000324
Sam Clegg31de2f02017-12-07 03:19:53 +0000325 // Handle the `--undefined <sym>` options.
Sam Clegg2a06afa2018-01-12 22:10:35 +0000326 for (auto* Arg : Args.filtered(OPT_undefined))
Sam Clegga1892302018-02-13 20:14:26 +0000327 addUndefinedFunction(Arg->getValue(), nullptr);
Sam Cleggc94d3932017-11-17 18:14:09 +0000328 }
329
330 createFiles(Args);
331 if (errorCount())
332 return;
333
334 // Add all files to the symbol table. This will add almost all
335 // symbols that we need to the symbol table.
336 for (InputFile *F : Files)
337 Symtab->addFile(F);
338
339 // Make sure we have resolved all symbols.
340 if (!Config->Relocatable && !Config->AllowUndefined) {
341 Symtab->reportRemainingUndefines();
Sam Clegg31de2f02017-12-07 03:19:53 +0000342 } else {
343 // When we allow undefined symbols we cannot include those defined in
344 // -u/--undefined since these undefined symbols have only names and no
345 // function signature, which means they cannot be written to the final
346 // output.
Sam Clegg2a06afa2018-01-12 22:10:35 +0000347 for (auto* Arg : Args.filtered(OPT_undefined)) {
348 Symbol *Sym = Symtab->find(Arg->getValue());
Sam Clegg31de2f02017-12-07 03:19:53 +0000349 if (!Sym->isDefined())
350 error("function forced with --undefined not found: " + Sym->getName());
351 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000352 }
Rui Ueyama9d8ce232017-12-11 23:09:03 +0000353 if (errorCount())
354 return;
Sam Cleggc94d3932017-11-17 18:14:09 +0000355
Sam Clegg2a06afa2018-01-12 22:10:35 +0000356 for (auto *Arg : Args.filtered(OPT_export)) {
357 Symbol *Sym = Symtab->find(Arg->getValue());
358 if (!Sym || !Sym->isDefined())
359 error("symbol exported via --export not found: " +
360 Twine(Arg->getValue()));
361 else
362 Sym->setHidden(false);
363 }
364
Sam Clegg0f0a4282018-01-20 01:44:45 +0000365 if (EntrySym)
366 EntrySym->setHidden(false);
367
Sam Clegg2c096ba2017-12-08 17:58:25 +0000368 if (errorCount())
369 return;
Sam Cleggc94d3932017-11-17 18:14:09 +0000370
Sam Clegg03626332018-01-31 01:45:47 +0000371 // Do size optimizations: garbage collection
372 markLive();
373
Sam Cleggc94d3932017-11-17 18:14:09 +0000374 // Write the result to the file.
375 writeResult();
376}