blob: c3f53e5b1369e2d113fe1a149d89fecab85b7993 [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"
Nicholas Wilsonebda41f2018-03-09 16:43:05 +000012#include "InputChunks.h"
Sam Clegg93102972018-02-23 05:08:53 +000013#include "InputGlobal.h"
Sam Clegg03626332018-01-31 01:45:47 +000014#include "MarkLive.h"
Sam Cleggc94d3932017-11-17 18:14:09 +000015#include "SymbolTable.h"
16#include "Writer.h"
Rui Ueyama3e039442017-11-28 19:58:45 +000017#include "lld/Common/Args.h"
Sam Cleggc94d3932017-11-17 18:14:09 +000018#include "lld/Common/ErrorHandler.h"
Rui Ueyama2017d522017-11-28 20:39:17 +000019#include "lld/Common/Memory.h"
Sam Cleggc94d3932017-11-17 18:14:09 +000020#include "lld/Common/Threads.h"
21#include "lld/Common/Version.h"
22#include "llvm/ADT/Twine.h"
23#include "llvm/Object/Wasm.h"
24#include "llvm/Option/ArgList.h"
25#include "llvm/Support/CommandLine.h"
26#include "llvm/Support/Path.h"
27#include "llvm/Support/Process.h"
28
Sam Clegg03626332018-01-31 01:45:47 +000029#define DEBUG_TYPE "lld"
30
Sam Cleggc94d3932017-11-17 18:14:09 +000031using namespace llvm;
32using namespace llvm::sys;
33using namespace llvm::wasm;
Sam Cleggc94d3932017-11-17 18:14:09 +000034
35using namespace lld;
36using namespace lld::wasm;
37
Rui Ueyama39049c02018-02-23 20:13:38 +000038Configuration *lld::wasm::Config;
Sam Cleggc94d3932017-11-17 18:14:09 +000039
Rui Ueyama39049c02018-02-23 20:13:38 +000040namespace {
Sam Cleggc94d3932017-11-17 18:14:09 +000041
42// Create enum with OPT_xxx values for each option in Options.td
43enum {
44 OPT_INVALID = 0,
45#define OPTION(_1, _2, ID, _4, _5, _6, _7, _8, _9, _10, _11, _12) OPT_##ID,
46#include "Options.inc"
47#undef OPTION
48};
49
50class LinkerDriver {
51public:
52 void link(ArrayRef<const char *> ArgsArr);
53
54private:
Rui Ueyama39049c02018-02-23 20:13:38 +000055 void createFiles(opt::InputArgList &Args);
Sam Cleggc94d3932017-11-17 18:14:09 +000056 void addFile(StringRef Path);
57 void addLibrary(StringRef Name);
58 std::vector<InputFile *> Files;
Sam Clegg93102972018-02-23 05:08:53 +000059 llvm::wasm::WasmGlobal StackPointerGlobal;
Sam Cleggc94d3932017-11-17 18:14:09 +000060};
Sam Cleggc94d3932017-11-17 18:14:09 +000061} // anonymous namespace
62
Sam Cleggc94d3932017-11-17 18:14:09 +000063bool 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
Sam Cleggc94d3932017-11-17 18:14:09 +000087// 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
93static 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
Rui Ueyama39049c02018-02-23 20:13:38 +0000101class WasmOptTable : public llvm::opt::OptTable {
102public:
103 WasmOptTable() : OptTable(OptInfo) {}
104 opt::InputArgList parse(ArrayRef<const char *> Argv);
105};
106
Sam Cleggc94d3932017-11-17 18:14:09 +0000107// Set color diagnostics according to -color-diagnostics={auto,always,never}
108// or -no-color-diagnostics flags.
109static void handleColorDiagnostics(opt::InputArgList &Args) {
110 auto *Arg = Args.getLastArg(OPT_color_diagnostics, OPT_color_diagnostics_eq,
111 OPT_no_color_diagnostics);
112 if (!Arg)
113 return;
114
115 if (Arg->getOption().getID() == OPT_color_diagnostics)
116 errorHandler().ColorDiagnostics = true;
117 else if (Arg->getOption().getID() == OPT_no_color_diagnostics)
118 errorHandler().ColorDiagnostics = false;
119 else {
120 StringRef S = Arg->getValue();
121 if (S == "always")
122 errorHandler().ColorDiagnostics = true;
123 if (S == "never")
124 errorHandler().ColorDiagnostics = false;
125 if (S != "auto")
126 error("unknown option: -color-diagnostics=" + S);
127 }
128}
129
130// Find a file by concatenating given paths.
131static Optional<std::string> findFile(StringRef Path1, const Twine &Path2) {
132 SmallString<128> S;
133 path::append(S, Path1, Path2);
134 if (fs::exists(S))
135 return S.str().str();
136 return None;
137}
138
Sam Cleggc94d3932017-11-17 18:14:09 +0000139opt::InputArgList WasmOptTable::parse(ArrayRef<const char *> Argv) {
140 SmallVector<const char *, 256> Vec(Argv.data(), Argv.data() + Argv.size());
141
142 unsigned MissingIndex;
143 unsigned MissingCount;
144 opt::InputArgList Args = this->ParseArgs(Vec, MissingIndex, MissingCount);
145
146 handleColorDiagnostics(Args);
147 for (auto *Arg : Args.filtered(OPT_UNKNOWN))
148 error("unknown argument: " + Arg->getSpelling());
149 return Args;
150}
151
Sam Clegg31efdcd2018-01-11 22:31:35 +0000152// Currently we allow a ".imports" to live alongside a library. This can
153// be used to specify a list of symbols which can be undefined at link
154// time (imported from the environment. For example libc.a include an
155// import file that lists the syscall functions it relies on at runtime.
156// In the long run this information would be better stored as a symbol
157// attribute/flag in the object file itself.
158// See: https://github.com/WebAssembly/tool-conventions/issues/35
159static void readImportFile(StringRef Filename) {
160 if (Optional<MemoryBufferRef> Buf = readFile(Filename))
161 for (StringRef Sym : args::getLines(*Buf))
162 Config->AllowUndefinedSymbols.insert(Sym);
163}
164
Sam Cleggc94d3932017-11-17 18:14:09 +0000165void LinkerDriver::addFile(StringRef Path) {
166 Optional<MemoryBufferRef> Buffer = readFile(Path);
167 if (!Buffer.hasValue())
168 return;
169 MemoryBufferRef MBRef = *Buffer;
170
Sam Clegg31efdcd2018-01-11 22:31:35 +0000171 if (identify_magic(MBRef.getBuffer()) == file_magic::archive) {
172 SmallString<128> ImportFile = Path;
173 path::replace_extension(ImportFile, ".imports");
174 if (fs::exists(ImportFile))
175 readImportFile(ImportFile.str());
176
Sam Cleggc94d3932017-11-17 18:14:09 +0000177 Files.push_back(make<ArchiveFile>(MBRef));
Sam Clegg31efdcd2018-01-11 22:31:35 +0000178 return;
179 }
180
181 Files.push_back(make<ObjFile>(MBRef));
Sam Cleggc94d3932017-11-17 18:14:09 +0000182}
183
184// Add a given library by searching it from input search paths.
185void LinkerDriver::addLibrary(StringRef Name) {
186 for (StringRef Dir : Config->SearchPaths) {
187 if (Optional<std::string> S = findFile(Dir, "lib" + Name + ".a")) {
188 addFile(*S);
189 return;
190 }
191 }
192
193 error("unable to find library -l" + Name);
194}
195
196void LinkerDriver::createFiles(opt::InputArgList &Args) {
197 for (auto *Arg : Args) {
198 switch (Arg->getOption().getUnaliasedOption().getID()) {
199 case OPT_l:
200 addLibrary(Arg->getValue());
201 break;
202 case OPT_INPUT:
203 addFile(Arg->getValue());
204 break;
205 }
206 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000207}
208
Rui Ueyama909d1232017-12-11 17:52:28 +0000209static StringRef getEntry(opt::InputArgList &Args, StringRef Default) {
Sam Clegg2c096ba2017-12-08 17:58:25 +0000210 auto *Arg = Args.getLastArg(OPT_entry, OPT_no_entry);
211 if (!Arg)
Rui Ueyama909d1232017-12-11 17:52:28 +0000212 return Default;
Sam Clegg2c096ba2017-12-08 17:58:25 +0000213 if (Arg->getOption().getID() == OPT_no_entry)
214 return "";
215 return Arg->getValue();
216}
217
Sam Cleggc94d3932017-11-17 18:14:09 +0000218void LinkerDriver::link(ArrayRef<const char *> ArgsArr) {
219 WasmOptTable Parser;
220 opt::InputArgList Args = Parser.parse(ArgsArr.slice(1));
221
222 // Handle --help
223 if (Args.hasArg(OPT_help)) {
Rui Ueyama97f66af2018-02-23 20:24:40 +0000224 Parser.PrintHelp(outs(), ArgsArr[0], "LLVM Linker", false);
Sam Cleggc94d3932017-11-17 18:14:09 +0000225 return;
226 }
227
Rui Ueyamaeecdaaa2018-02-23 20:24:28 +0000228 // Handle --version
229 if (Args.hasArg(OPT_version) || Args.hasArg(OPT_v)) {
230 outs() << getLLDVersion() << "\n";
231 return;
232 }
233
Sam Cleggc94d3932017-11-17 18:14:09 +0000234 // Parse and evaluate -mllvm options.
235 std::vector<const char *> V;
Rui Ueyamaceb15e82017-11-28 22:17:39 +0000236 V.push_back("wasm-ld (LLVM option parsing)");
Sam Cleggc94d3932017-11-17 18:14:09 +0000237 for (auto *Arg : Args.filtered(OPT_mllvm))
238 V.push_back(Arg->getValue());
239 cl::ParseCommandLineOptions(V.size(), V.data());
240
Rui Ueyama3e039442017-11-28 19:58:45 +0000241 errorHandler().ErrorLimit = args::getInteger(Args, OPT_error_limit, 20);
Sam Cleggc94d3932017-11-17 18:14:09 +0000242
Sam Cleggc94d3932017-11-17 18:14:09 +0000243 Config->AllowUndefined = Args.hasArg(OPT_allow_undefined);
Sam Cleggb8621592017-11-30 01:40:08 +0000244 Config->CheckSignatures =
245 Args.hasFlag(OPT_check_signatures, OPT_no_check_signatures, false);
Rui Ueyama8cbb3b52017-12-11 17:52:43 +0000246 Config->Entry = getEntry(Args, Args.hasArg(OPT_relocatable) ? "" : "_start");
Sam Cleggc94d3932017-11-17 18:14:09 +0000247 Config->ImportMemory = Args.hasArg(OPT_import_memory);
248 Config->OutputFile = Args.getLastArgValue(OPT_o);
Rui Ueyama8cbb3b52017-12-11 17:52:43 +0000249 Config->Relocatable = Args.hasArg(OPT_relocatable);
Sam Clegg03626332018-01-31 01:45:47 +0000250 Config->GcSections =
251 Args.hasFlag(OPT_gc_sections, OPT_no_gc_sections, !Config->Relocatable);
252 Config->PrintGcSections =
253 Args.hasFlag(OPT_print_gc_sections, OPT_no_print_gc_sections, false);
Rui Ueyama3e039442017-11-28 19:58:45 +0000254 Config->SearchPaths = args::getStrings(Args, OPT_L);
Sam Cleggc94d3932017-11-17 18:14:09 +0000255 Config->StripAll = Args.hasArg(OPT_strip_all);
256 Config->StripDebug = Args.hasArg(OPT_strip_debug);
Sam Cleggc94d3932017-11-17 18:14:09 +0000257 errorHandler().Verbose = Args.hasArg(OPT_verbose);
258 ThreadsEnabled = Args.hasFlag(OPT_threads, OPT_no_threads, true);
259
Rui Ueyama3e039442017-11-28 19:58:45 +0000260 Config->InitialMemory = args::getInteger(Args, OPT_initial_memory, 0);
261 Config->GlobalBase = args::getInteger(Args, OPT_global_base, 1024);
262 Config->MaxMemory = args::getInteger(Args, OPT_max_memory, 0);
263 Config->ZStackSize =
264 args::getZOptionValue(Args, OPT_z, "stack-size", WasmPageSize);
Sam Cleggc94d3932017-11-17 18:14:09 +0000265
266 if (auto *Arg = Args.getLastArg(OPT_allow_undefined_file))
Sam Clegg31efdcd2018-01-11 22:31:35 +0000267 readImportFile(Arg->getValue());
Sam Cleggc94d3932017-11-17 18:14:09 +0000268
Rui Ueyama4aab7b12018-02-16 22:58:19 +0000269 if (!Args.hasArg(OPT_INPUT)) {
270 error("no input files");
271 return;
272 }
273
Sam Cleggc94d3932017-11-17 18:14:09 +0000274 if (Config->OutputFile.empty())
275 error("no output file specified");
276
Sam Clegg03626332018-01-31 01:45:47 +0000277 if (Config->Relocatable) {
278 if (!Config->Entry.empty())
279 error("entry point specified for relocatable output file");
280 if (Config->GcSections)
281 error("-r and --gc-sections may not be used together");
282 if (Args.hasArg(OPT_undefined))
283 error("-r -and --undefined may not be used together");
284 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000285
Sam Clegg0f0a4282018-01-20 01:44:45 +0000286 Symbol *EntrySym = nullptr;
Sam Cleggc94d3932017-11-17 18:14:09 +0000287 if (!Config->Relocatable) {
Sam Clegg93102972018-02-23 05:08:53 +0000288 // Can't export the SP right now because it's mutable, and mutable
289 // globals aren't yet supported in the official binary format.
290 // TODO(sbc): Remove WASM_SYMBOL_VISIBILITY_HIDDEN if/when the
291 // "mutable global" proposal is accepted.
292 StackPointerGlobal.Type = {WASM_TYPE_I32, true};
293 StackPointerGlobal.InitExpr.Value.Int32 = 0;
294 StackPointerGlobal.InitExpr.Opcode = WASM_OPCODE_I32_CONST;
295 InputGlobal *StackPointer = make<InputGlobal>(StackPointerGlobal);
296 StackPointer->Live = true;
Sam Clegga1892302018-02-13 20:14:26 +0000297
Sam Clegg93102972018-02-23 05:08:53 +0000298 static WasmSignature NullSignature = {{}, WASM_TYPE_NORESULT};
Nicholas Wilsonebda41f2018-03-09 16:43:05 +0000299
Sam Clegga1892302018-02-13 20:14:26 +0000300 // Add synthetic symbols before any others
301 WasmSym::CallCtors = Symtab->addSyntheticFunction(
Nicholas Wilsonebda41f2018-03-09 16:43:05 +0000302 "__wasm_call_ctors", WASM_SYMBOL_VISIBILITY_HIDDEN,
303 make<SyntheticFunction>(NullSignature, "__wasm_call_ctors"));
Sam Clegg93102972018-02-23 05:08:53 +0000304 WasmSym::StackPointer = Symtab->addSyntheticGlobal(
305 "__stack_pointer", WASM_SYMBOL_VISIBILITY_HIDDEN, StackPointer);
Rui Ueyamac61b8342018-02-28 00:37:03 +0000306 WasmSym::HeapBase = Symtab->addSyntheticDataSymbol("__heap_base", 0);
Sam Clegg93102972018-02-23 05:08:53 +0000307 WasmSym::DsoHandle = Symtab->addSyntheticDataSymbol(
308 "__dso_handle", WASM_SYMBOL_VISIBILITY_HIDDEN);
Rui Ueyamac61b8342018-02-28 00:37:03 +0000309 WasmSym::DataEnd = Symtab->addSyntheticDataSymbol("__data_end", 0);
Sam Clegga1892302018-02-13 20:14:26 +0000310
Sam Clegg50686852018-01-12 18:35:13 +0000311 if (!Config->Entry.empty())
Rui Ueyamae3498ec2018-02-28 00:09:22 +0000312 EntrySym = Symtab->addUndefinedFunction(Config->Entry, 0, nullptr,
313 &NullSignature);
Sam Cleggc94d3932017-11-17 18:14:09 +0000314
Sam Clegg31de2f02017-12-07 03:19:53 +0000315 // Handle the `--undefined <sym>` options.
Nicholas Wilsondbd90bf2018-03-07 13:28:16 +0000316 for (auto *Arg : Args.filtered(OPT_undefined))
Rui Ueyamae3498ec2018-02-28 00:09:22 +0000317 Symtab->addUndefinedFunction(Arg->getValue(), 0, nullptr, nullptr);
Sam Cleggc94d3932017-11-17 18:14:09 +0000318 }
319
320 createFiles(Args);
321 if (errorCount())
322 return;
323
324 // Add all files to the symbol table. This will add almost all
325 // symbols that we need to the symbol table.
326 for (InputFile *F : Files)
327 Symtab->addFile(F);
328
329 // Make sure we have resolved all symbols.
330 if (!Config->Relocatable && !Config->AllowUndefined) {
331 Symtab->reportRemainingUndefines();
Sam Clegg31de2f02017-12-07 03:19:53 +0000332 } else {
333 // When we allow undefined symbols we cannot include those defined in
334 // -u/--undefined since these undefined symbols have only names and no
335 // function signature, which means they cannot be written to the final
336 // output.
Nicholas Wilsondbd90bf2018-03-07 13:28:16 +0000337 for (auto *Arg : Args.filtered(OPT_undefined)) {
Sam Clegg2a06afa2018-01-12 22:10:35 +0000338 Symbol *Sym = Symtab->find(Arg->getValue());
Sam Clegg31de2f02017-12-07 03:19:53 +0000339 if (!Sym->isDefined())
340 error("function forced with --undefined not found: " + Sym->getName());
341 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000342 }
Rui Ueyama9d8ce232017-12-11 23:09:03 +0000343 if (errorCount())
344 return;
Sam Cleggc94d3932017-11-17 18:14:09 +0000345
Rui Ueyamac9f0b652018-02-24 01:58:38 +0000346 // Handle --export.
Sam Clegg2a06afa2018-01-12 22:10:35 +0000347 for (auto *Arg : Args.filtered(OPT_export)) {
Rui Ueyamac9f0b652018-02-24 01:58:38 +0000348 StringRef Name = Arg->getValue();
349 Symbol *Sym = Symtab->find(Name);
350 if (Sym && Sym->isDefined())
Sam Clegg2a06afa2018-01-12 22:10:35 +0000351 Sym->setHidden(false);
Sam Clegg7f814182018-03-08 01:16:05 +0000352 else if (!Config->AllowUndefined)
Rui Ueyamac9f0b652018-02-24 01:58:38 +0000353 error("symbol exported via --export not found: " + Name);
Sam Clegg2a06afa2018-01-12 22:10:35 +0000354 }
355
Sam Clegg0f0a4282018-01-20 01:44:45 +0000356 if (EntrySym)
357 EntrySym->setHidden(false);
358
Sam Clegg2c096ba2017-12-08 17:58:25 +0000359 if (errorCount())
360 return;
Sam Cleggc94d3932017-11-17 18:14:09 +0000361
Sam Clegg03626332018-01-31 01:45:47 +0000362 // Do size optimizations: garbage collection
363 markLive();
364
Sam Cleggc94d3932017-11-17 18:14:09 +0000365 // Write the result to the file.
366 writeResult();
367}