blob: 1903206141e4715ffd61e71b26ba464f7dafae73 [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 Clegg93102972018-02-23 05:08:53 +0000217static Symbol *addUndefinedFunction(StringRef Name, const WasmSignature *Type) {
218 return Symtab->addUndefined(Name, WASM_SYMBOL_TYPE_FUNCTION, 0, nullptr,
Sam Clegga1892302018-02-13 20:14:26 +0000219 Type);
220}
221
Sam Cleggc94d3932017-11-17 18:14:09 +0000222void LinkerDriver::link(ArrayRef<const char *> ArgsArr) {
223 WasmOptTable Parser;
224 opt::InputArgList Args = Parser.parse(ArgsArr.slice(1));
225
226 // Handle --help
227 if (Args.hasArg(OPT_help)) {
Rui Ueyama97f66af2018-02-23 20:24:40 +0000228 Parser.PrintHelp(outs(), ArgsArr[0], "LLVM Linker", false);
Sam Cleggc94d3932017-11-17 18:14:09 +0000229 return;
230 }
231
Rui Ueyamaeecdaaa2018-02-23 20:24:28 +0000232 // Handle --version
233 if (Args.hasArg(OPT_version) || Args.hasArg(OPT_v)) {
234 outs() << getLLDVersion() << "\n";
235 return;
236 }
237
Sam Cleggc94d3932017-11-17 18:14:09 +0000238 // Parse and evaluate -mllvm options.
239 std::vector<const char *> V;
Rui Ueyamaceb15e82017-11-28 22:17:39 +0000240 V.push_back("wasm-ld (LLVM option parsing)");
Sam Cleggc94d3932017-11-17 18:14:09 +0000241 for (auto *Arg : Args.filtered(OPT_mllvm))
242 V.push_back(Arg->getValue());
243 cl::ParseCommandLineOptions(V.size(), V.data());
244
Rui Ueyama3e039442017-11-28 19:58:45 +0000245 errorHandler().ErrorLimit = args::getInteger(Args, OPT_error_limit, 20);
Sam Cleggc94d3932017-11-17 18:14:09 +0000246
Sam Cleggc94d3932017-11-17 18:14:09 +0000247 Config->AllowUndefined = Args.hasArg(OPT_allow_undefined);
Sam Cleggb8621592017-11-30 01:40:08 +0000248 Config->CheckSignatures =
249 Args.hasFlag(OPT_check_signatures, OPT_no_check_signatures, false);
Rui Ueyama8cbb3b52017-12-11 17:52:43 +0000250 Config->Entry = getEntry(Args, Args.hasArg(OPT_relocatable) ? "" : "_start");
Sam Cleggc94d3932017-11-17 18:14:09 +0000251 Config->ImportMemory = Args.hasArg(OPT_import_memory);
252 Config->OutputFile = Args.getLastArgValue(OPT_o);
Rui Ueyama8cbb3b52017-12-11 17:52:43 +0000253 Config->Relocatable = Args.hasArg(OPT_relocatable);
Sam Clegg03626332018-01-31 01:45:47 +0000254 Config->GcSections =
255 Args.hasFlag(OPT_gc_sections, OPT_no_gc_sections, !Config->Relocatable);
256 Config->PrintGcSections =
257 Args.hasFlag(OPT_print_gc_sections, OPT_no_print_gc_sections, false);
Rui Ueyama3e039442017-11-28 19:58:45 +0000258 Config->SearchPaths = args::getStrings(Args, OPT_L);
Sam Cleggc94d3932017-11-17 18:14:09 +0000259 Config->StripAll = Args.hasArg(OPT_strip_all);
260 Config->StripDebug = Args.hasArg(OPT_strip_debug);
Sam Cleggc94d3932017-11-17 18:14:09 +0000261 errorHandler().Verbose = Args.hasArg(OPT_verbose);
262 ThreadsEnabled = Args.hasFlag(OPT_threads, OPT_no_threads, true);
263
Rui Ueyama3e039442017-11-28 19:58:45 +0000264 Config->InitialMemory = args::getInteger(Args, OPT_initial_memory, 0);
265 Config->GlobalBase = args::getInteger(Args, OPT_global_base, 1024);
266 Config->MaxMemory = args::getInteger(Args, OPT_max_memory, 0);
267 Config->ZStackSize =
268 args::getZOptionValue(Args, OPT_z, "stack-size", WasmPageSize);
Sam Cleggc94d3932017-11-17 18:14:09 +0000269
270 if (auto *Arg = Args.getLastArg(OPT_allow_undefined_file))
Sam Clegg31efdcd2018-01-11 22:31:35 +0000271 readImportFile(Arg->getValue());
Sam Cleggc94d3932017-11-17 18:14:09 +0000272
Rui Ueyama4aab7b12018-02-16 22:58:19 +0000273 if (!Args.hasArg(OPT_INPUT)) {
274 error("no input files");
275 return;
276 }
277
Sam Cleggc94d3932017-11-17 18:14:09 +0000278 if (Config->OutputFile.empty())
279 error("no output file specified");
280
Sam Clegg03626332018-01-31 01:45:47 +0000281 if (Config->Relocatable) {
282 if (!Config->Entry.empty())
283 error("entry point specified for relocatable output file");
284 if (Config->GcSections)
285 error("-r and --gc-sections may not be used together");
286 if (Args.hasArg(OPT_undefined))
287 error("-r -and --undefined may not be used together");
288 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000289
Sam Clegg0f0a4282018-01-20 01:44:45 +0000290 Symbol *EntrySym = nullptr;
Sam Cleggc94d3932017-11-17 18:14:09 +0000291 if (!Config->Relocatable) {
Sam Clegg93102972018-02-23 05:08:53 +0000292 // Can't export the SP right now because it's mutable, and mutable
293 // globals aren't yet supported in the official binary format.
294 // TODO(sbc): Remove WASM_SYMBOL_VISIBILITY_HIDDEN if/when the
295 // "mutable global" proposal is accepted.
296 StackPointerGlobal.Type = {WASM_TYPE_I32, true};
297 StackPointerGlobal.InitExpr.Value.Int32 = 0;
298 StackPointerGlobal.InitExpr.Opcode = WASM_OPCODE_I32_CONST;
299 InputGlobal *StackPointer = make<InputGlobal>(StackPointerGlobal);
300 StackPointer->Live = true;
Sam Clegga1892302018-02-13 20:14:26 +0000301
Sam Clegg93102972018-02-23 05:08:53 +0000302 static WasmSignature NullSignature = {{}, WASM_TYPE_NORESULT};
Sam Clegga1892302018-02-13 20:14:26 +0000303 // Add synthetic symbols before any others
304 WasmSym::CallCtors = Symtab->addSyntheticFunction(
305 "__wasm_call_ctors", &NullSignature, WASM_SYMBOL_VISIBILITY_HIDDEN);
Sam Clegg93102972018-02-23 05:08:53 +0000306 WasmSym::StackPointer = Symtab->addSyntheticGlobal(
307 "__stack_pointer", WASM_SYMBOL_VISIBILITY_HIDDEN, StackPointer);
Sam Clegg00245532018-02-20 23:38:27 +0000308 WasmSym::HeapBase = Symtab->addSyntheticDataSymbol("__heap_base");
Sam Clegg93102972018-02-23 05:08:53 +0000309 WasmSym::DsoHandle = Symtab->addSyntheticDataSymbol(
310 "__dso_handle", WASM_SYMBOL_VISIBILITY_HIDDEN);
Sam Clegg00245532018-02-20 23:38:27 +0000311 WasmSym::DataEnd = Symtab->addSyntheticDataSymbol("__data_end");
Sam Clegga1892302018-02-13 20:14:26 +0000312
Sam Clegg50686852018-01-12 18:35:13 +0000313 if (!Config->Entry.empty())
Sam Clegga1892302018-02-13 20:14:26 +0000314 EntrySym = addUndefinedFunction(Config->Entry, &NullSignature);
Sam Cleggc94d3932017-11-17 18:14:09 +0000315
Sam Clegg31de2f02017-12-07 03:19:53 +0000316 // Handle the `--undefined <sym>` options.
Sam Clegg2a06afa2018-01-12 22:10:35 +0000317 for (auto* Arg : Args.filtered(OPT_undefined))
Sam Clegga1892302018-02-13 20:14:26 +0000318 addUndefinedFunction(Arg->getValue(), nullptr);
Sam Cleggc94d3932017-11-17 18:14:09 +0000319 }
320
321 createFiles(Args);
322 if (errorCount())
323 return;
324
325 // Add all files to the symbol table. This will add almost all
326 // symbols that we need to the symbol table.
327 for (InputFile *F : Files)
328 Symtab->addFile(F);
329
330 // Make sure we have resolved all symbols.
331 if (!Config->Relocatable && !Config->AllowUndefined) {
332 Symtab->reportRemainingUndefines();
Sam Clegg31de2f02017-12-07 03:19:53 +0000333 } else {
334 // When we allow undefined symbols we cannot include those defined in
335 // -u/--undefined since these undefined symbols have only names and no
336 // function signature, which means they cannot be written to the final
337 // output.
Sam Clegg2a06afa2018-01-12 22:10:35 +0000338 for (auto* Arg : Args.filtered(OPT_undefined)) {
339 Symbol *Sym = Symtab->find(Arg->getValue());
Sam Clegg31de2f02017-12-07 03:19:53 +0000340 if (!Sym->isDefined())
341 error("function forced with --undefined not found: " + Sym->getName());
342 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000343 }
Rui Ueyama9d8ce232017-12-11 23:09:03 +0000344 if (errorCount())
345 return;
Sam Cleggc94d3932017-11-17 18:14:09 +0000346
Sam Clegg2a06afa2018-01-12 22:10:35 +0000347 for (auto *Arg : Args.filtered(OPT_export)) {
348 Symbol *Sym = Symtab->find(Arg->getValue());
349 if (!Sym || !Sym->isDefined())
350 error("symbol exported via --export not found: " +
351 Twine(Arg->getValue()));
352 else
353 Sym->setHidden(false);
354 }
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}