blob: ac0ec9d48f8eb46a6b3c11db9a21f75f38e417ac [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 +0000138static void printHelp(const char *Argv0) {
Rui Ueyama6074e6b2017-12-11 23:19:11 +0000139 WasmOptTable().PrintHelp(outs(), Argv0, "LLVM Linker", false);
Sam Cleggc94d3932017-11-17 18:14:09 +0000140}
141
Sam Cleggc94d3932017-11-17 18:14:09 +0000142opt::InputArgList WasmOptTable::parse(ArrayRef<const char *> Argv) {
143 SmallVector<const char *, 256> Vec(Argv.data(), Argv.data() + Argv.size());
144
145 unsigned MissingIndex;
146 unsigned MissingCount;
147 opt::InputArgList Args = this->ParseArgs(Vec, MissingIndex, MissingCount);
148
149 handleColorDiagnostics(Args);
150 for (auto *Arg : Args.filtered(OPT_UNKNOWN))
151 error("unknown argument: " + Arg->getSpelling());
152 return Args;
153}
154
Sam Clegg31efdcd2018-01-11 22:31:35 +0000155// Currently we allow a ".imports" to live alongside a library. This can
156// be used to specify a list of symbols which can be undefined at link
157// time (imported from the environment. For example libc.a include an
158// import file that lists the syscall functions it relies on at runtime.
159// In the long run this information would be better stored as a symbol
160// attribute/flag in the object file itself.
161// See: https://github.com/WebAssembly/tool-conventions/issues/35
162static void readImportFile(StringRef Filename) {
163 if (Optional<MemoryBufferRef> Buf = readFile(Filename))
164 for (StringRef Sym : args::getLines(*Buf))
165 Config->AllowUndefinedSymbols.insert(Sym);
166}
167
Sam Cleggc94d3932017-11-17 18:14:09 +0000168void LinkerDriver::addFile(StringRef Path) {
169 Optional<MemoryBufferRef> Buffer = readFile(Path);
170 if (!Buffer.hasValue())
171 return;
172 MemoryBufferRef MBRef = *Buffer;
173
Sam Clegg31efdcd2018-01-11 22:31:35 +0000174 if (identify_magic(MBRef.getBuffer()) == file_magic::archive) {
175 SmallString<128> ImportFile = Path;
176 path::replace_extension(ImportFile, ".imports");
177 if (fs::exists(ImportFile))
178 readImportFile(ImportFile.str());
179
Sam Cleggc94d3932017-11-17 18:14:09 +0000180 Files.push_back(make<ArchiveFile>(MBRef));
Sam Clegg31efdcd2018-01-11 22:31:35 +0000181 return;
182 }
183
184 Files.push_back(make<ObjFile>(MBRef));
Sam Cleggc94d3932017-11-17 18:14:09 +0000185}
186
187// Add a given library by searching it from input search paths.
188void LinkerDriver::addLibrary(StringRef Name) {
189 for (StringRef Dir : Config->SearchPaths) {
190 if (Optional<std::string> S = findFile(Dir, "lib" + Name + ".a")) {
191 addFile(*S);
192 return;
193 }
194 }
195
196 error("unable to find library -l" + Name);
197}
198
199void LinkerDriver::createFiles(opt::InputArgList &Args) {
200 for (auto *Arg : Args) {
201 switch (Arg->getOption().getUnaliasedOption().getID()) {
202 case OPT_l:
203 addLibrary(Arg->getValue());
204 break;
205 case OPT_INPUT:
206 addFile(Arg->getValue());
207 break;
208 }
209 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000210}
211
Rui Ueyama909d1232017-12-11 17:52:28 +0000212static StringRef getEntry(opt::InputArgList &Args, StringRef Default) {
Sam Clegg2c096ba2017-12-08 17:58:25 +0000213 auto *Arg = Args.getLastArg(OPT_entry, OPT_no_entry);
214 if (!Arg)
Rui Ueyama909d1232017-12-11 17:52:28 +0000215 return Default;
Sam Clegg2c096ba2017-12-08 17:58:25 +0000216 if (Arg->getOption().getID() == OPT_no_entry)
217 return "";
218 return Arg->getValue();
219}
220
Sam Clegg93102972018-02-23 05:08:53 +0000221static Symbol *addUndefinedFunction(StringRef Name, const WasmSignature *Type) {
222 return Symtab->addUndefined(Name, WASM_SYMBOL_TYPE_FUNCTION, 0, nullptr,
Sam Clegga1892302018-02-13 20:14:26 +0000223 Type);
224}
225
Sam Cleggc94d3932017-11-17 18:14:09 +0000226void LinkerDriver::link(ArrayRef<const char *> ArgsArr) {
227 WasmOptTable Parser;
228 opt::InputArgList Args = Parser.parse(ArgsArr.slice(1));
229
230 // Handle --help
231 if (Args.hasArg(OPT_help)) {
232 printHelp(ArgsArr[0]);
233 return;
234 }
235
Rui Ueyamaeecdaaa2018-02-23 20:24:28 +0000236 // Handle --version
237 if (Args.hasArg(OPT_version) || Args.hasArg(OPT_v)) {
238 outs() << getLLDVersion() << "\n";
239 return;
240 }
241
Sam Cleggc94d3932017-11-17 18:14:09 +0000242 // 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
Sam Cleggc94d3932017-11-17 18:14:09 +0000251 Config->AllowUndefined = Args.hasArg(OPT_allow_undefined);
Sam Cleggb8621592017-11-30 01:40:08 +0000252 Config->CheckSignatures =
253 Args.hasFlag(OPT_check_signatures, OPT_no_check_signatures, false);
Rui Ueyama8cbb3b52017-12-11 17:52:43 +0000254 Config->Entry = getEntry(Args, Args.hasArg(OPT_relocatable) ? "" : "_start");
Sam Cleggc94d3932017-11-17 18:14:09 +0000255 Config->ImportMemory = Args.hasArg(OPT_import_memory);
256 Config->OutputFile = Args.getLastArgValue(OPT_o);
Rui Ueyama8cbb3b52017-12-11 17:52:43 +0000257 Config->Relocatable = Args.hasArg(OPT_relocatable);
Sam Clegg03626332018-01-31 01:45:47 +0000258 Config->GcSections =
259 Args.hasFlag(OPT_gc_sections, OPT_no_gc_sections, !Config->Relocatable);
260 Config->PrintGcSections =
261 Args.hasFlag(OPT_print_gc_sections, OPT_no_print_gc_sections, false);
Rui Ueyama3e039442017-11-28 19:58:45 +0000262 Config->SearchPaths = args::getStrings(Args, OPT_L);
Sam Cleggc94d3932017-11-17 18:14:09 +0000263 Config->StripAll = Args.hasArg(OPT_strip_all);
264 Config->StripDebug = Args.hasArg(OPT_strip_debug);
Sam Cleggc94d3932017-11-17 18:14:09 +0000265 errorHandler().Verbose = Args.hasArg(OPT_verbose);
266 ThreadsEnabled = Args.hasFlag(OPT_threads, OPT_no_threads, true);
267
Rui Ueyama3e039442017-11-28 19:58:45 +0000268 Config->InitialMemory = args::getInteger(Args, OPT_initial_memory, 0);
269 Config->GlobalBase = args::getInteger(Args, OPT_global_base, 1024);
270 Config->MaxMemory = args::getInteger(Args, OPT_max_memory, 0);
271 Config->ZStackSize =
272 args::getZOptionValue(Args, OPT_z, "stack-size", WasmPageSize);
Sam Cleggc94d3932017-11-17 18:14:09 +0000273
274 if (auto *Arg = Args.getLastArg(OPT_allow_undefined_file))
Sam Clegg31efdcd2018-01-11 22:31:35 +0000275 readImportFile(Arg->getValue());
Sam Cleggc94d3932017-11-17 18:14:09 +0000276
Rui Ueyama4aab7b12018-02-16 22:58:19 +0000277 if (!Args.hasArg(OPT_INPUT)) {
278 error("no input files");
279 return;
280 }
281
Sam Cleggc94d3932017-11-17 18:14:09 +0000282 if (Config->OutputFile.empty())
283 error("no output file specified");
284
Sam Clegg03626332018-01-31 01:45:47 +0000285 if (Config->Relocatable) {
286 if (!Config->Entry.empty())
287 error("entry point specified for relocatable output file");
288 if (Config->GcSections)
289 error("-r and --gc-sections may not be used together");
290 if (Args.hasArg(OPT_undefined))
291 error("-r -and --undefined may not be used together");
292 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000293
Sam Clegg0f0a4282018-01-20 01:44:45 +0000294 Symbol *EntrySym = nullptr;
Sam Cleggc94d3932017-11-17 18:14:09 +0000295 if (!Config->Relocatable) {
Sam Clegg93102972018-02-23 05:08:53 +0000296 // Can't export the SP right now because it's mutable, and mutable
297 // globals aren't yet supported in the official binary format.
298 // TODO(sbc): Remove WASM_SYMBOL_VISIBILITY_HIDDEN if/when the
299 // "mutable global" proposal is accepted.
300 StackPointerGlobal.Type = {WASM_TYPE_I32, true};
301 StackPointerGlobal.InitExpr.Value.Int32 = 0;
302 StackPointerGlobal.InitExpr.Opcode = WASM_OPCODE_I32_CONST;
303 InputGlobal *StackPointer = make<InputGlobal>(StackPointerGlobal);
304 StackPointer->Live = true;
Sam Clegga1892302018-02-13 20:14:26 +0000305
Sam Clegg93102972018-02-23 05:08:53 +0000306 static WasmSignature NullSignature = {{}, WASM_TYPE_NORESULT};
Sam Clegga1892302018-02-13 20:14:26 +0000307 // Add synthetic symbols before any others
308 WasmSym::CallCtors = Symtab->addSyntheticFunction(
309 "__wasm_call_ctors", &NullSignature, WASM_SYMBOL_VISIBILITY_HIDDEN);
Sam Clegg93102972018-02-23 05:08:53 +0000310 WasmSym::StackPointer = Symtab->addSyntheticGlobal(
311 "__stack_pointer", WASM_SYMBOL_VISIBILITY_HIDDEN, StackPointer);
Sam Clegg00245532018-02-20 23:38:27 +0000312 WasmSym::HeapBase = Symtab->addSyntheticDataSymbol("__heap_base");
Sam Clegg93102972018-02-23 05:08:53 +0000313 WasmSym::DsoHandle = Symtab->addSyntheticDataSymbol(
314 "__dso_handle", WASM_SYMBOL_VISIBILITY_HIDDEN);
Sam Clegg00245532018-02-20 23:38:27 +0000315 WasmSym::DataEnd = Symtab->addSyntheticDataSymbol("__data_end");
Sam Clegga1892302018-02-13 20:14:26 +0000316
Sam Clegg50686852018-01-12 18:35:13 +0000317 if (!Config->Entry.empty())
Sam Clegga1892302018-02-13 20:14:26 +0000318 EntrySym = addUndefinedFunction(Config->Entry, &NullSignature);
Sam Cleggc94d3932017-11-17 18:14:09 +0000319
Sam Clegg31de2f02017-12-07 03:19:53 +0000320 // Handle the `--undefined <sym>` options.
Sam Clegg2a06afa2018-01-12 22:10:35 +0000321 for (auto* Arg : Args.filtered(OPT_undefined))
Sam Clegga1892302018-02-13 20:14:26 +0000322 addUndefinedFunction(Arg->getValue(), nullptr);
Sam Cleggc94d3932017-11-17 18:14:09 +0000323 }
324
325 createFiles(Args);
326 if (errorCount())
327 return;
328
329 // Add all files to the symbol table. This will add almost all
330 // symbols that we need to the symbol table.
331 for (InputFile *F : Files)
332 Symtab->addFile(F);
333
334 // Make sure we have resolved all symbols.
335 if (!Config->Relocatable && !Config->AllowUndefined) {
336 Symtab->reportRemainingUndefines();
Sam Clegg31de2f02017-12-07 03:19:53 +0000337 } else {
338 // When we allow undefined symbols we cannot include those defined in
339 // -u/--undefined since these undefined symbols have only names and no
340 // function signature, which means they cannot be written to the final
341 // output.
Sam Clegg2a06afa2018-01-12 22:10:35 +0000342 for (auto* Arg : Args.filtered(OPT_undefined)) {
343 Symbol *Sym = Symtab->find(Arg->getValue());
Sam Clegg31de2f02017-12-07 03:19:53 +0000344 if (!Sym->isDefined())
345 error("function forced with --undefined not found: " + Sym->getName());
346 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000347 }
Rui Ueyama9d8ce232017-12-11 23:09:03 +0000348 if (errorCount())
349 return;
Sam Cleggc94d3932017-11-17 18:14:09 +0000350
Sam Clegg2a06afa2018-01-12 22:10:35 +0000351 for (auto *Arg : Args.filtered(OPT_export)) {
352 Symbol *Sym = Symtab->find(Arg->getValue());
353 if (!Sym || !Sym->isDefined())
354 error("symbol exported via --export not found: " +
355 Twine(Arg->getValue()));
356 else
357 Sym->setHidden(false);
358 }
359
Sam Clegg0f0a4282018-01-20 01:44:45 +0000360 if (EntrySym)
361 EntrySym->setHidden(false);
362
Sam Clegg2c096ba2017-12-08 17:58:25 +0000363 if (errorCount())
364 return;
Sam Cleggc94d3932017-11-17 18:14:09 +0000365
Sam Clegg03626332018-01-31 01:45:47 +0000366 // Do size optimizations: garbage collection
367 markLive();
368
Sam Cleggc94d3932017-11-17 18:14:09 +0000369 // Write the result to the file.
370 writeResult();
371}