blob: 8d909ecd69bde01830eb3c240ad66a168d0bdb1e [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 Clegg03626332018-01-31 01:45:47 +000011#include "InputChunks.h"
12#include "MarkLive.h"
Sam Cleggc94d3932017-11-17 18:14:09 +000013#include "SymbolTable.h"
14#include "Writer.h"
Rui Ueyama3e039442017-11-28 19:58:45 +000015#include "lld/Common/Args.h"
Sam Cleggc94d3932017-11-17 18:14:09 +000016#include "lld/Common/ErrorHandler.h"
Rui Ueyama2017d522017-11-28 20:39:17 +000017#include "lld/Common/Memory.h"
Sam Cleggc94d3932017-11-17 18:14:09 +000018#include "lld/Common/Threads.h"
19#include "lld/Common/Version.h"
20#include "llvm/ADT/Twine.h"
21#include "llvm/Object/Wasm.h"
22#include "llvm/Option/ArgList.h"
23#include "llvm/Support/CommandLine.h"
24#include "llvm/Support/Path.h"
25#include "llvm/Support/Process.h"
26
Sam Clegg03626332018-01-31 01:45:47 +000027#define DEBUG_TYPE "lld"
28
Sam Cleggc94d3932017-11-17 18:14:09 +000029using namespace llvm;
30using namespace llvm::sys;
31using namespace llvm::wasm;
Sam Cleggc94d3932017-11-17 18:14:09 +000032
33using namespace lld;
34using namespace lld::wasm;
35
36namespace {
37
38// Parses command line options.
39class WasmOptTable : public llvm::opt::OptTable {
40public:
41 WasmOptTable();
42 llvm::opt::InputArgList parse(ArrayRef<const char *> Argv);
43};
44
45// Create enum with OPT_xxx values for each option in Options.td
46enum {
47 OPT_INVALID = 0,
48#define OPTION(_1, _2, ID, _4, _5, _6, _7, _8, _9, _10, _11, _12) OPT_##ID,
49#include "Options.inc"
50#undef OPTION
51};
52
53class LinkerDriver {
54public:
55 void link(ArrayRef<const char *> ArgsArr);
56
57private:
58 void createFiles(llvm::opt::InputArgList &Args);
59 void addFile(StringRef Path);
60 void addLibrary(StringRef Name);
61 std::vector<InputFile *> Files;
62};
63
64} // anonymous namespace
65
Sam Cleggc94d3932017-11-17 18:14:09 +000066Configuration *lld::wasm::Config;
Sam Cleggc94d3932017-11-17 18:14:09 +000067
68bool lld::wasm::link(ArrayRef<const char *> Args, bool CanExitEarly,
69 raw_ostream &Error) {
70 errorHandler().LogName = Args[0];
71 errorHandler().ErrorOS = &Error;
72 errorHandler().ColorDiagnostics = Error.has_colors();
73 errorHandler().ErrorLimitExceededMsg =
74 "too many errors emitted, stopping now (use "
75 "-error-limit=0 to see all errors)";
76
77 Config = make<Configuration>();
78 Symtab = make<SymbolTable>();
79
80 LinkerDriver().link(Args);
81
82 // Exit immediately if we don't need to return to the caller.
83 // This saves time because the overhead of calling destructors
84 // for all globally-allocated objects is not negligible.
85 if (CanExitEarly)
86 exitLld(errorCount() ? 1 : 0);
87
88 freeArena();
89 return !errorCount();
90}
91
92// Create OptTable
93
94// Create prefix string literals used in Options.td
95#define PREFIX(NAME, VALUE) const char *const NAME[] = VALUE;
96#include "Options.inc"
97#undef PREFIX
98
99// Create table mapping all options defined in Options.td
100static const opt::OptTable::Info OptInfo[] = {
101#define OPTION(X1, X2, ID, KIND, GROUP, ALIAS, X7, X8, X9, X10, X11, X12) \
102 {X1, X2, X10, X11, OPT_##ID, opt::Option::KIND##Class, \
103 X9, X8, OPT_##GROUP, OPT_##ALIAS, X7, X12},
104#include "Options.inc"
105#undef OPTION
106};
107
Sam Cleggc94d3932017-11-17 18:14:09 +0000108// Set color diagnostics according to -color-diagnostics={auto,always,never}
109// or -no-color-diagnostics flags.
110static void handleColorDiagnostics(opt::InputArgList &Args) {
111 auto *Arg = Args.getLastArg(OPT_color_diagnostics, OPT_color_diagnostics_eq,
112 OPT_no_color_diagnostics);
113 if (!Arg)
114 return;
115
116 if (Arg->getOption().getID() == OPT_color_diagnostics)
117 errorHandler().ColorDiagnostics = true;
118 else if (Arg->getOption().getID() == OPT_no_color_diagnostics)
119 errorHandler().ColorDiagnostics = false;
120 else {
121 StringRef S = Arg->getValue();
122 if (S == "always")
123 errorHandler().ColorDiagnostics = true;
124 if (S == "never")
125 errorHandler().ColorDiagnostics = false;
126 if (S != "auto")
127 error("unknown option: -color-diagnostics=" + S);
128 }
129}
130
131// Find a file by concatenating given paths.
132static Optional<std::string> findFile(StringRef Path1, const Twine &Path2) {
133 SmallString<128> S;
134 path::append(S, Path1, Path2);
135 if (fs::exists(S))
136 return S.str().str();
137 return None;
138}
139
Sam Cleggc94d3932017-11-17 18:14:09 +0000140static void printHelp(const char *Argv0) {
Rui Ueyama6074e6b2017-12-11 23:19:11 +0000141 WasmOptTable().PrintHelp(outs(), Argv0, "LLVM Linker", false);
Sam Cleggc94d3932017-11-17 18:14:09 +0000142}
143
144WasmOptTable::WasmOptTable() : OptTable(OptInfo) {}
145
146opt::InputArgList WasmOptTable::parse(ArrayRef<const char *> Argv) {
147 SmallVector<const char *, 256> Vec(Argv.data(), Argv.data() + Argv.size());
148
149 unsigned MissingIndex;
150 unsigned MissingCount;
151 opt::InputArgList Args = this->ParseArgs(Vec, MissingIndex, MissingCount);
152
153 handleColorDiagnostics(Args);
154 for (auto *Arg : Args.filtered(OPT_UNKNOWN))
155 error("unknown argument: " + Arg->getSpelling());
156 return Args;
157}
158
Sam Clegg31efdcd2018-01-11 22:31:35 +0000159// Currently we allow a ".imports" to live alongside a library. This can
160// be used to specify a list of symbols which can be undefined at link
161// time (imported from the environment. For example libc.a include an
162// import file that lists the syscall functions it relies on at runtime.
163// In the long run this information would be better stored as a symbol
164// attribute/flag in the object file itself.
165// See: https://github.com/WebAssembly/tool-conventions/issues/35
166static void readImportFile(StringRef Filename) {
167 if (Optional<MemoryBufferRef> Buf = readFile(Filename))
168 for (StringRef Sym : args::getLines(*Buf))
169 Config->AllowUndefinedSymbols.insert(Sym);
170}
171
Sam Cleggc94d3932017-11-17 18:14:09 +0000172void LinkerDriver::addFile(StringRef Path) {
173 Optional<MemoryBufferRef> Buffer = readFile(Path);
174 if (!Buffer.hasValue())
175 return;
176 MemoryBufferRef MBRef = *Buffer;
177
Sam Clegg31efdcd2018-01-11 22:31:35 +0000178 if (identify_magic(MBRef.getBuffer()) == file_magic::archive) {
179 SmallString<128> ImportFile = Path;
180 path::replace_extension(ImportFile, ".imports");
181 if (fs::exists(ImportFile))
182 readImportFile(ImportFile.str());
183
Sam Cleggc94d3932017-11-17 18:14:09 +0000184 Files.push_back(make<ArchiveFile>(MBRef));
Sam Clegg31efdcd2018-01-11 22:31:35 +0000185 return;
186 }
187
188 Files.push_back(make<ObjFile>(MBRef));
Sam Cleggc94d3932017-11-17 18:14:09 +0000189}
190
191// Add a given library by searching it from input search paths.
192void LinkerDriver::addLibrary(StringRef Name) {
193 for (StringRef Dir : Config->SearchPaths) {
194 if (Optional<std::string> S = findFile(Dir, "lib" + Name + ".a")) {
195 addFile(*S);
196 return;
197 }
198 }
199
200 error("unable to find library -l" + Name);
201}
202
203void LinkerDriver::createFiles(opt::InputArgList &Args) {
204 for (auto *Arg : Args) {
205 switch (Arg->getOption().getUnaliasedOption().getID()) {
206 case OPT_l:
207 addLibrary(Arg->getValue());
208 break;
209 case OPT_INPUT:
210 addFile(Arg->getValue());
211 break;
212 }
213 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000214}
215
Rui Ueyama909d1232017-12-11 17:52:28 +0000216static StringRef getEntry(opt::InputArgList &Args, StringRef Default) {
Sam Clegg2c096ba2017-12-08 17:58:25 +0000217 auto *Arg = Args.getLastArg(OPT_entry, OPT_no_entry);
218 if (!Arg)
Rui Ueyama909d1232017-12-11 17:52:28 +0000219 return Default;
Sam Clegg2c096ba2017-12-08 17:58:25 +0000220 if (Arg->getOption().getID() == OPT_no_entry)
221 return "";
222 return Arg->getValue();
223}
224
Sam Clegga1892302018-02-13 20:14:26 +0000225static Symbol* addUndefinedFunction(StringRef Name, const WasmSignature *Type) {
226 return Symtab->addUndefined(Name, Symbol::UndefinedFunctionKind, 0, nullptr,
227 Type);
228}
229
Sam Cleggc94d3932017-11-17 18:14:09 +0000230void LinkerDriver::link(ArrayRef<const char *> ArgsArr) {
231 WasmOptTable Parser;
232 opt::InputArgList Args = Parser.parse(ArgsArr.slice(1));
233
234 // Handle --help
235 if (Args.hasArg(OPT_help)) {
236 printHelp(ArgsArr[0]);
237 return;
238 }
239
240 // Parse and evaluate -mllvm options.
241 std::vector<const char *> V;
Rui Ueyamaceb15e82017-11-28 22:17:39 +0000242 V.push_back("wasm-ld (LLVM option parsing)");
Sam Cleggc94d3932017-11-17 18:14:09 +0000243 for (auto *Arg : Args.filtered(OPT_mllvm))
244 V.push_back(Arg->getValue());
245 cl::ParseCommandLineOptions(V.size(), V.data());
246
Rui Ueyama3e039442017-11-28 19:58:45 +0000247 errorHandler().ErrorLimit = args::getInteger(Args, OPT_error_limit, 20);
Sam Cleggc94d3932017-11-17 18:14:09 +0000248
249 if (Args.hasArg(OPT_version) || Args.hasArg(OPT_v)) {
250 outs() << getLLDVersion() << "\n";
251 return;
252 }
253
254 Config->AllowUndefined = Args.hasArg(OPT_allow_undefined);
Sam Cleggb8621592017-11-30 01:40:08 +0000255 Config->CheckSignatures =
256 Args.hasFlag(OPT_check_signatures, OPT_no_check_signatures, false);
Rui Ueyama8cbb3b52017-12-11 17:52:43 +0000257 Config->Entry = getEntry(Args, Args.hasArg(OPT_relocatable) ? "" : "_start");
Sam Cleggc94d3932017-11-17 18:14:09 +0000258 Config->ImportMemory = Args.hasArg(OPT_import_memory);
259 Config->OutputFile = Args.getLastArgValue(OPT_o);
Rui Ueyama8cbb3b52017-12-11 17:52:43 +0000260 Config->Relocatable = Args.hasArg(OPT_relocatable);
Sam Clegg03626332018-01-31 01:45:47 +0000261 Config->GcSections =
262 Args.hasFlag(OPT_gc_sections, OPT_no_gc_sections, !Config->Relocatable);
263 Config->PrintGcSections =
264 Args.hasFlag(OPT_print_gc_sections, OPT_no_print_gc_sections, false);
Rui Ueyama3e039442017-11-28 19:58:45 +0000265 Config->SearchPaths = args::getStrings(Args, OPT_L);
Sam Cleggc94d3932017-11-17 18:14:09 +0000266 Config->StripAll = Args.hasArg(OPT_strip_all);
267 Config->StripDebug = Args.hasArg(OPT_strip_debug);
Sam Cleggc94d3932017-11-17 18:14:09 +0000268 errorHandler().Verbose = Args.hasArg(OPT_verbose);
269 ThreadsEnabled = Args.hasFlag(OPT_threads, OPT_no_threads, true);
270
Rui Ueyama3e039442017-11-28 19:58:45 +0000271 Config->InitialMemory = args::getInteger(Args, OPT_initial_memory, 0);
272 Config->GlobalBase = args::getInteger(Args, OPT_global_base, 1024);
273 Config->MaxMemory = args::getInteger(Args, OPT_max_memory, 0);
274 Config->ZStackSize =
275 args::getZOptionValue(Args, OPT_z, "stack-size", WasmPageSize);
Sam Cleggc94d3932017-11-17 18:14:09 +0000276
277 if (auto *Arg = Args.getLastArg(OPT_allow_undefined_file))
Sam Clegg31efdcd2018-01-11 22:31:35 +0000278 readImportFile(Arg->getValue());
Sam Cleggc94d3932017-11-17 18:14:09 +0000279
Rui Ueyama4aab7b12018-02-16 22:58:19 +0000280 if (!Args.hasArg(OPT_INPUT)) {
281 error("no input files");
282 return;
283 }
284
Sam Cleggc94d3932017-11-17 18:14:09 +0000285 if (Config->OutputFile.empty())
286 error("no output file specified");
287
Sam Clegg03626332018-01-31 01:45:47 +0000288 if (Config->Relocatable) {
289 if (!Config->Entry.empty())
290 error("entry point specified for relocatable output file");
291 if (Config->GcSections)
292 error("-r and --gc-sections may not be used together");
293 if (Args.hasArg(OPT_undefined))
294 error("-r -and --undefined may not be used together");
295 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000296
Sam Clegg0f0a4282018-01-20 01:44:45 +0000297 Symbol *EntrySym = nullptr;
Sam Cleggc94d3932017-11-17 18:14:09 +0000298 if (!Config->Relocatable) {
Sam Clegga1892302018-02-13 20:14:26 +0000299 static WasmSignature NullSignature = {{}, WASM_TYPE_NORESULT};
300
301 // Add synthetic symbols before any others
302 WasmSym::CallCtors = Symtab->addSyntheticFunction(
303 "__wasm_call_ctors", &NullSignature, WASM_SYMBOL_VISIBILITY_HIDDEN);
304 WasmSym::StackPointer = Symtab->addSyntheticGlobal("__stack_pointer");
305 WasmSym::HeapBase = Symtab->addSyntheticGlobal("__heap_base");
306 WasmSym::DsoHandle = Symtab->addSyntheticGlobal("__dso_handle");
307 WasmSym::DataEnd = Symtab->addSyntheticGlobal("__data_end");
308
Sam Clegg50686852018-01-12 18:35:13 +0000309 if (!Config->Entry.empty())
Sam Clegga1892302018-02-13 20:14:26 +0000310 EntrySym = addUndefinedFunction(Config->Entry, &NullSignature);
Sam Cleggc94d3932017-11-17 18:14:09 +0000311
Sam Clegg31de2f02017-12-07 03:19:53 +0000312 // Handle the `--undefined <sym>` options.
Sam Clegg2a06afa2018-01-12 22:10:35 +0000313 for (auto* Arg : Args.filtered(OPT_undefined))
Sam Clegga1892302018-02-13 20:14:26 +0000314 addUndefinedFunction(Arg->getValue(), 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.
Sam Clegg2a06afa2018-01-12 22:10:35 +0000334 for (auto* Arg : Args.filtered(OPT_undefined)) {
335 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
Sam Clegg2a06afa2018-01-12 22:10:35 +0000343 for (auto *Arg : Args.filtered(OPT_export)) {
344 Symbol *Sym = Symtab->find(Arg->getValue());
345 if (!Sym || !Sym->isDefined())
346 error("symbol exported via --export not found: " +
347 Twine(Arg->getValue()));
348 else
349 Sym->setHidden(false);
350 }
351
Sam Clegg0f0a4282018-01-20 01:44:45 +0000352 if (EntrySym)
353 EntrySym->setHidden(false);
354
Sam Clegg2c096ba2017-12-08 17:58:25 +0000355 if (errorCount())
356 return;
Sam Cleggc94d3932017-11-17 18:14:09 +0000357
Sam Clegg03626332018-01-31 01:45:47 +0000358 // Do size optimizations: garbage collection
359 markLive();
360
Sam Cleggc94d3932017-11-17 18:14:09 +0000361 // Write the result to the file.
362 writeResult();
363}