blob: a97026d4df8bc9a2d369ef87780b00e3ebb2b85e [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
Rui Ueyama39049c02018-02-23 20:13:38 +000037Configuration *lld::wasm::Config;
Sam Cleggc94d3932017-11-17 18:14:09 +000038
Rui Ueyama39049c02018-02-23 20:13:38 +000039namespace {
Sam Cleggc94d3932017-11-17 18:14:09 +000040
41// Create enum with OPT_xxx values for each option in Options.td
42enum {
43 OPT_INVALID = 0,
44#define OPTION(_1, _2, ID, _4, _5, _6, _7, _8, _9, _10, _11, _12) OPT_##ID,
45#include "Options.inc"
46#undef OPTION
47};
48
49class LinkerDriver {
50public:
51 void link(ArrayRef<const char *> ArgsArr);
52
53private:
Rui Ueyama39049c02018-02-23 20:13:38 +000054 void createFiles(opt::InputArgList &Args);
Sam Cleggc94d3932017-11-17 18:14:09 +000055 void addFile(StringRef Path);
56 void addLibrary(StringRef Name);
57 std::vector<InputFile *> Files;
Sam Clegg93102972018-02-23 05:08:53 +000058 llvm::wasm::WasmGlobal StackPointerGlobal;
Sam Cleggc94d3932017-11-17 18:14:09 +000059};
Sam Cleggc94d3932017-11-17 18:14:09 +000060} // anonymous namespace
61
Sam Cleggc94d3932017-11-17 18:14:09 +000062bool lld::wasm::link(ArrayRef<const char *> Args, bool CanExitEarly,
63 raw_ostream &Error) {
64 errorHandler().LogName = Args[0];
65 errorHandler().ErrorOS = &Error;
66 errorHandler().ColorDiagnostics = Error.has_colors();
67 errorHandler().ErrorLimitExceededMsg =
68 "too many errors emitted, stopping now (use "
69 "-error-limit=0 to see all errors)";
70
71 Config = make<Configuration>();
72 Symtab = make<SymbolTable>();
73
74 LinkerDriver().link(Args);
75
76 // Exit immediately if we don't need to return to the caller.
77 // This saves time because the overhead of calling destructors
78 // for all globally-allocated objects is not negligible.
79 if (CanExitEarly)
80 exitLld(errorCount() ? 1 : 0);
81
82 freeArena();
83 return !errorCount();
84}
85
Sam Cleggc94d3932017-11-17 18:14:09 +000086// Create prefix string literals used in Options.td
87#define PREFIX(NAME, VALUE) const char *const NAME[] = VALUE;
88#include "Options.inc"
89#undef PREFIX
90
91// Create table mapping all options defined in Options.td
92static const opt::OptTable::Info OptInfo[] = {
93#define OPTION(X1, X2, ID, KIND, GROUP, ALIAS, X7, X8, X9, X10, X11, X12) \
94 {X1, X2, X10, X11, OPT_##ID, opt::Option::KIND##Class, \
95 X9, X8, OPT_##GROUP, OPT_##ALIAS, X7, X12},
96#include "Options.inc"
97#undef OPTION
98};
99
Rui Ueyama39049c02018-02-23 20:13:38 +0000100class WasmOptTable : public llvm::opt::OptTable {
101public:
102 WasmOptTable() : OptTable(OptInfo) {}
103 opt::InputArgList parse(ArrayRef<const char *> Argv);
104};
105
Sam Cleggc94d3932017-11-17 18:14:09 +0000106// Set color diagnostics according to -color-diagnostics={auto,always,never}
107// or -no-color-diagnostics flags.
108static void handleColorDiagnostics(opt::InputArgList &Args) {
109 auto *Arg = Args.getLastArg(OPT_color_diagnostics, OPT_color_diagnostics_eq,
110 OPT_no_color_diagnostics);
111 if (!Arg)
112 return;
113
114 if (Arg->getOption().getID() == OPT_color_diagnostics)
115 errorHandler().ColorDiagnostics = true;
116 else if (Arg->getOption().getID() == OPT_no_color_diagnostics)
117 errorHandler().ColorDiagnostics = false;
118 else {
119 StringRef S = Arg->getValue();
120 if (S == "always")
121 errorHandler().ColorDiagnostics = true;
122 if (S == "never")
123 errorHandler().ColorDiagnostics = false;
124 if (S != "auto")
125 error("unknown option: -color-diagnostics=" + S);
126 }
127}
128
129// Find a file by concatenating given paths.
130static Optional<std::string> findFile(StringRef Path1, const Twine &Path2) {
131 SmallString<128> S;
132 path::append(S, Path1, Path2);
133 if (fs::exists(S))
134 return S.str().str();
135 return None;
136}
137
Sam Cleggc94d3932017-11-17 18:14:09 +0000138opt::InputArgList WasmOptTable::parse(ArrayRef<const char *> Argv) {
139 SmallVector<const char *, 256> Vec(Argv.data(), Argv.data() + Argv.size());
140
141 unsigned MissingIndex;
142 unsigned MissingCount;
143 opt::InputArgList Args = this->ParseArgs(Vec, MissingIndex, MissingCount);
144
145 handleColorDiagnostics(Args);
146 for (auto *Arg : Args.filtered(OPT_UNKNOWN))
147 error("unknown argument: " + Arg->getSpelling());
148 return Args;
149}
150
Sam Clegg31efdcd2018-01-11 22:31:35 +0000151// Currently we allow a ".imports" to live alongside a library. This can
152// be used to specify a list of symbols which can be undefined at link
153// time (imported from the environment. For example libc.a include an
154// import file that lists the syscall functions it relies on at runtime.
155// In the long run this information would be better stored as a symbol
156// attribute/flag in the object file itself.
157// See: https://github.com/WebAssembly/tool-conventions/issues/35
158static void readImportFile(StringRef Filename) {
159 if (Optional<MemoryBufferRef> Buf = readFile(Filename))
160 for (StringRef Sym : args::getLines(*Buf))
161 Config->AllowUndefinedSymbols.insert(Sym);
162}
163
Sam Cleggc94d3932017-11-17 18:14:09 +0000164void LinkerDriver::addFile(StringRef Path) {
165 Optional<MemoryBufferRef> Buffer = readFile(Path);
166 if (!Buffer.hasValue())
167 return;
168 MemoryBufferRef MBRef = *Buffer;
169
Sam Clegg31efdcd2018-01-11 22:31:35 +0000170 if (identify_magic(MBRef.getBuffer()) == file_magic::archive) {
171 SmallString<128> ImportFile = Path;
172 path::replace_extension(ImportFile, ".imports");
173 if (fs::exists(ImportFile))
174 readImportFile(ImportFile.str());
175
Sam Cleggc94d3932017-11-17 18:14:09 +0000176 Files.push_back(make<ArchiveFile>(MBRef));
Sam Clegg31efdcd2018-01-11 22:31:35 +0000177 return;
178 }
179
180 Files.push_back(make<ObjFile>(MBRef));
Sam Cleggc94d3932017-11-17 18:14:09 +0000181}
182
183// Add a given library by searching it from input search paths.
184void LinkerDriver::addLibrary(StringRef Name) {
185 for (StringRef Dir : Config->SearchPaths) {
186 if (Optional<std::string> S = findFile(Dir, "lib" + Name + ".a")) {
187 addFile(*S);
188 return;
189 }
190 }
191
192 error("unable to find library -l" + Name);
193}
194
195void LinkerDriver::createFiles(opt::InputArgList &Args) {
196 for (auto *Arg : Args) {
197 switch (Arg->getOption().getUnaliasedOption().getID()) {
198 case OPT_l:
199 addLibrary(Arg->getValue());
200 break;
201 case OPT_INPUT:
202 addFile(Arg->getValue());
203 break;
204 }
205 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000206}
207
Rui Ueyama909d1232017-12-11 17:52:28 +0000208static StringRef getEntry(opt::InputArgList &Args, StringRef Default) {
Sam Clegg2c096ba2017-12-08 17:58:25 +0000209 auto *Arg = Args.getLastArg(OPT_entry, OPT_no_entry);
210 if (!Arg)
Rui Ueyama909d1232017-12-11 17:52:28 +0000211 return Default;
Sam Clegg2c096ba2017-12-08 17:58:25 +0000212 if (Arg->getOption().getID() == OPT_no_entry)
213 return "";
214 return Arg->getValue();
215}
216
Sam Cleggc94d3932017-11-17 18:14:09 +0000217void LinkerDriver::link(ArrayRef<const char *> ArgsArr) {
218 WasmOptTable Parser;
219 opt::InputArgList Args = Parser.parse(ArgsArr.slice(1));
220
221 // Handle --help
222 if (Args.hasArg(OPT_help)) {
Rui Ueyama97f66af2018-02-23 20:24:40 +0000223 Parser.PrintHelp(outs(), ArgsArr[0], "LLVM Linker", false);
Sam Cleggc94d3932017-11-17 18:14:09 +0000224 return;
225 }
226
Rui Ueyamaeecdaaa2018-02-23 20:24:28 +0000227 // Handle --version
228 if (Args.hasArg(OPT_version) || Args.hasArg(OPT_v)) {
229 outs() << getLLDVersion() << "\n";
230 return;
231 }
232
Sam Cleggc94d3932017-11-17 18:14:09 +0000233 // Parse and evaluate -mllvm options.
234 std::vector<const char *> V;
Rui Ueyamaceb15e82017-11-28 22:17:39 +0000235 V.push_back("wasm-ld (LLVM option parsing)");
Sam Cleggc94d3932017-11-17 18:14:09 +0000236 for (auto *Arg : Args.filtered(OPT_mllvm))
237 V.push_back(Arg->getValue());
238 cl::ParseCommandLineOptions(V.size(), V.data());
239
Rui Ueyama3e039442017-11-28 19:58:45 +0000240 errorHandler().ErrorLimit = args::getInteger(Args, OPT_error_limit, 20);
Sam Cleggc94d3932017-11-17 18:14:09 +0000241
Sam Cleggc94d3932017-11-17 18:14:09 +0000242 Config->AllowUndefined = Args.hasArg(OPT_allow_undefined);
Sam Cleggb8621592017-11-30 01:40:08 +0000243 Config->CheckSignatures =
244 Args.hasFlag(OPT_check_signatures, OPT_no_check_signatures, false);
Rui Ueyama8cbb3b52017-12-11 17:52:43 +0000245 Config->Entry = getEntry(Args, Args.hasArg(OPT_relocatable) ? "" : "_start");
Sam Cleggc94d3932017-11-17 18:14:09 +0000246 Config->ImportMemory = Args.hasArg(OPT_import_memory);
247 Config->OutputFile = Args.getLastArgValue(OPT_o);
Rui Ueyama8cbb3b52017-12-11 17:52:43 +0000248 Config->Relocatable = Args.hasArg(OPT_relocatable);
Sam Clegg03626332018-01-31 01:45:47 +0000249 Config->GcSections =
250 Args.hasFlag(OPT_gc_sections, OPT_no_gc_sections, !Config->Relocatable);
251 Config->PrintGcSections =
252 Args.hasFlag(OPT_print_gc_sections, OPT_no_print_gc_sections, false);
Rui Ueyama3e039442017-11-28 19:58:45 +0000253 Config->SearchPaths = args::getStrings(Args, OPT_L);
Sam Cleggc94d3932017-11-17 18:14:09 +0000254 Config->StripAll = Args.hasArg(OPT_strip_all);
255 Config->StripDebug = Args.hasArg(OPT_strip_debug);
Sam Cleggc94d3932017-11-17 18:14:09 +0000256 errorHandler().Verbose = Args.hasArg(OPT_verbose);
257 ThreadsEnabled = Args.hasFlag(OPT_threads, OPT_no_threads, true);
258
Rui Ueyama3e039442017-11-28 19:58:45 +0000259 Config->InitialMemory = args::getInteger(Args, OPT_initial_memory, 0);
260 Config->GlobalBase = args::getInteger(Args, OPT_global_base, 1024);
261 Config->MaxMemory = args::getInteger(Args, OPT_max_memory, 0);
262 Config->ZStackSize =
263 args::getZOptionValue(Args, OPT_z, "stack-size", WasmPageSize);
Sam Cleggc94d3932017-11-17 18:14:09 +0000264
265 if (auto *Arg = Args.getLastArg(OPT_allow_undefined_file))
Sam Clegg31efdcd2018-01-11 22:31:35 +0000266 readImportFile(Arg->getValue());
Sam Cleggc94d3932017-11-17 18:14:09 +0000267
Rui Ueyama4aab7b12018-02-16 22:58:19 +0000268 if (!Args.hasArg(OPT_INPUT)) {
269 error("no input files");
270 return;
271 }
272
Sam Cleggc94d3932017-11-17 18:14:09 +0000273 if (Config->OutputFile.empty())
274 error("no output file specified");
275
Sam Clegg03626332018-01-31 01:45:47 +0000276 if (Config->Relocatable) {
277 if (!Config->Entry.empty())
278 error("entry point specified for relocatable output file");
279 if (Config->GcSections)
280 error("-r and --gc-sections may not be used together");
281 if (Args.hasArg(OPT_undefined))
282 error("-r -and --undefined may not be used together");
283 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000284
Sam Clegg0f0a4282018-01-20 01:44:45 +0000285 Symbol *EntrySym = nullptr;
Sam Cleggc94d3932017-11-17 18:14:09 +0000286 if (!Config->Relocatable) {
Sam Clegg93102972018-02-23 05:08:53 +0000287 // Can't export the SP right now because it's mutable, and mutable
288 // globals aren't yet supported in the official binary format.
289 // TODO(sbc): Remove WASM_SYMBOL_VISIBILITY_HIDDEN if/when the
290 // "mutable global" proposal is accepted.
291 StackPointerGlobal.Type = {WASM_TYPE_I32, true};
292 StackPointerGlobal.InitExpr.Value.Int32 = 0;
293 StackPointerGlobal.InitExpr.Opcode = WASM_OPCODE_I32_CONST;
294 InputGlobal *StackPointer = make<InputGlobal>(StackPointerGlobal);
295 StackPointer->Live = true;
Sam Clegga1892302018-02-13 20:14:26 +0000296
Sam Clegg93102972018-02-23 05:08:53 +0000297 static WasmSignature NullSignature = {{}, WASM_TYPE_NORESULT};
Sam Clegga1892302018-02-13 20:14:26 +0000298 // Add synthetic symbols before any others
299 WasmSym::CallCtors = Symtab->addSyntheticFunction(
300 "__wasm_call_ctors", &NullSignature, WASM_SYMBOL_VISIBILITY_HIDDEN);
Sam Clegg93102972018-02-23 05:08:53 +0000301 WasmSym::StackPointer = Symtab->addSyntheticGlobal(
302 "__stack_pointer", WASM_SYMBOL_VISIBILITY_HIDDEN, StackPointer);
Rui Ueyamac61b8342018-02-28 00:37:03 +0000303 WasmSym::HeapBase = Symtab->addSyntheticDataSymbol("__heap_base", 0);
Sam Clegg93102972018-02-23 05:08:53 +0000304 WasmSym::DsoHandle = Symtab->addSyntheticDataSymbol(
305 "__dso_handle", WASM_SYMBOL_VISIBILITY_HIDDEN);
Rui Ueyamac61b8342018-02-28 00:37:03 +0000306 WasmSym::DataEnd = Symtab->addSyntheticDataSymbol("__data_end", 0);
Sam Clegga1892302018-02-13 20:14:26 +0000307
Sam Clegg50686852018-01-12 18:35:13 +0000308 if (!Config->Entry.empty())
Rui Ueyamae3498ec2018-02-28 00:09:22 +0000309 EntrySym = Symtab->addUndefinedFunction(Config->Entry, 0, nullptr,
310 &NullSignature);
Sam Cleggc94d3932017-11-17 18:14:09 +0000311
Sam Clegg31de2f02017-12-07 03:19:53 +0000312 // Handle the `--undefined <sym>` options.
Nicholas Wilsondbd90bf2018-03-07 13:28:16 +0000313 for (auto *Arg : Args.filtered(OPT_undefined))
Rui Ueyamae3498ec2018-02-28 00:09:22 +0000314 Symtab->addUndefinedFunction(Arg->getValue(), 0, nullptr, nullptr);
Sam Cleggc94d3932017-11-17 18:14:09 +0000315 }
316
317 createFiles(Args);
318 if (errorCount())
319 return;
320
321 // Add all files to the symbol table. This will add almost all
322 // symbols that we need to the symbol table.
323 for (InputFile *F : Files)
324 Symtab->addFile(F);
325
326 // Make sure we have resolved all symbols.
327 if (!Config->Relocatable && !Config->AllowUndefined) {
328 Symtab->reportRemainingUndefines();
Sam Clegg31de2f02017-12-07 03:19:53 +0000329 } else {
330 // When we allow undefined symbols we cannot include those defined in
331 // -u/--undefined since these undefined symbols have only names and no
332 // function signature, which means they cannot be written to the final
333 // output.
Nicholas Wilsondbd90bf2018-03-07 13:28:16 +0000334 for (auto *Arg : Args.filtered(OPT_undefined)) {
Sam Clegg2a06afa2018-01-12 22:10:35 +0000335 Symbol *Sym = Symtab->find(Arg->getValue());
Sam Clegg31de2f02017-12-07 03:19:53 +0000336 if (!Sym->isDefined())
337 error("function forced with --undefined not found: " + Sym->getName());
338 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000339 }
Rui Ueyama9d8ce232017-12-11 23:09:03 +0000340 if (errorCount())
341 return;
Sam Cleggc94d3932017-11-17 18:14:09 +0000342
Rui Ueyamac9f0b652018-02-24 01:58:38 +0000343 // Handle --export.
Sam Clegg2a06afa2018-01-12 22:10:35 +0000344 for (auto *Arg : Args.filtered(OPT_export)) {
Rui Ueyamac9f0b652018-02-24 01:58:38 +0000345 StringRef Name = Arg->getValue();
346 Symbol *Sym = Symtab->find(Name);
347 if (Sym && Sym->isDefined())
Sam Clegg2a06afa2018-01-12 22:10:35 +0000348 Sym->setHidden(false);
Sam Clegg7f814182018-03-08 01:16:05 +0000349 else if (!Config->AllowUndefined)
Rui Ueyamac9f0b652018-02-24 01:58:38 +0000350 error("symbol exported via --export not found: " + Name);
Sam Clegg2a06afa2018-01-12 22:10:35 +0000351 }
352
Sam Clegg0f0a4282018-01-20 01:44:45 +0000353 if (EntrySym)
354 EntrySym->setHidden(false);
355
Sam Clegg2c096ba2017-12-08 17:58:25 +0000356 if (errorCount())
357 return;
Sam Cleggc94d3932017-11-17 18:14:09 +0000358
Sam Clegg03626332018-01-31 01:45:47 +0000359 // Do size optimizations: garbage collection
360 markLive();
361
Sam Cleggc94d3932017-11-17 18:14:09 +0000362 // Write the result to the file.
363 writeResult();
364}