blob: 2858f68397b72954e00071b3edf0f9ab4b9f8160 [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"
11#include "Config.h"
Sam Cleggc94d3932017-11-17 18:14:09 +000012#include "SymbolTable.h"
13#include "Writer.h"
Rui Ueyama3e039442017-11-28 19:58:45 +000014#include "lld/Common/Args.h"
Sam Cleggc94d3932017-11-17 18:14:09 +000015#include "lld/Common/ErrorHandler.h"
Rui Ueyama2017d522017-11-28 20:39:17 +000016#include "lld/Common/Memory.h"
Sam Cleggc94d3932017-11-17 18:14:09 +000017#include "lld/Common/Threads.h"
18#include "lld/Common/Version.h"
19#include "llvm/ADT/Twine.h"
20#include "llvm/Object/Wasm.h"
21#include "llvm/Option/ArgList.h"
22#include "llvm/Support/CommandLine.h"
23#include "llvm/Support/Path.h"
24#include "llvm/Support/Process.h"
25
26using namespace llvm;
27using namespace llvm::sys;
28using namespace llvm::wasm;
Sam Cleggc94d3932017-11-17 18:14:09 +000029
30using namespace lld;
31using namespace lld::wasm;
32
33namespace {
34
35// Parses command line options.
36class WasmOptTable : public llvm::opt::OptTable {
37public:
38 WasmOptTable();
39 llvm::opt::InputArgList parse(ArrayRef<const char *> Argv);
40};
41
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:
55 void createFiles(llvm::opt::InputArgList &Args);
56 void addFile(StringRef Path);
57 void addLibrary(StringRef Name);
58 std::vector<InputFile *> Files;
59};
60
61} // anonymous namespace
62
Sam Cleggc94d3932017-11-17 18:14:09 +000063Configuration *lld::wasm::Config;
Sam Cleggc94d3932017-11-17 18:14:09 +000064
65bool lld::wasm::link(ArrayRef<const char *> Args, bool CanExitEarly,
66 raw_ostream &Error) {
67 errorHandler().LogName = Args[0];
68 errorHandler().ErrorOS = &Error;
69 errorHandler().ColorDiagnostics = Error.has_colors();
70 errorHandler().ErrorLimitExceededMsg =
71 "too many errors emitted, stopping now (use "
72 "-error-limit=0 to see all errors)";
73
74 Config = make<Configuration>();
75 Symtab = make<SymbolTable>();
76
77 LinkerDriver().link(Args);
78
79 // Exit immediately if we don't need to return to the caller.
80 // This saves time because the overhead of calling destructors
81 // for all globally-allocated objects is not negligible.
82 if (CanExitEarly)
83 exitLld(errorCount() ? 1 : 0);
84
85 freeArena();
86 return !errorCount();
87}
88
89// Create OptTable
90
91// Create prefix string literals used in Options.td
92#define PREFIX(NAME, VALUE) const char *const NAME[] = VALUE;
93#include "Options.inc"
94#undef PREFIX
95
96// Create table mapping all options defined in Options.td
97static const opt::OptTable::Info OptInfo[] = {
98#define OPTION(X1, X2, ID, KIND, GROUP, ALIAS, X7, X8, X9, X10, X11, X12) \
99 {X1, X2, X10, X11, OPT_##ID, opt::Option::KIND##Class, \
100 X9, X8, OPT_##GROUP, OPT_##ALIAS, X7, X12},
101#include "Options.inc"
102#undef OPTION
103};
104
Sam Cleggc94d3932017-11-17 18:14:09 +0000105// Set color diagnostics according to -color-diagnostics={auto,always,never}
106// or -no-color-diagnostics flags.
107static void handleColorDiagnostics(opt::InputArgList &Args) {
108 auto *Arg = Args.getLastArg(OPT_color_diagnostics, OPT_color_diagnostics_eq,
109 OPT_no_color_diagnostics);
110 if (!Arg)
111 return;
112
113 if (Arg->getOption().getID() == OPT_color_diagnostics)
114 errorHandler().ColorDiagnostics = true;
115 else if (Arg->getOption().getID() == OPT_no_color_diagnostics)
116 errorHandler().ColorDiagnostics = false;
117 else {
118 StringRef S = Arg->getValue();
119 if (S == "always")
120 errorHandler().ColorDiagnostics = true;
121 if (S == "never")
122 errorHandler().ColorDiagnostics = false;
123 if (S != "auto")
124 error("unknown option: -color-diagnostics=" + S);
125 }
126}
127
128// Find a file by concatenating given paths.
129static Optional<std::string> findFile(StringRef Path1, const Twine &Path2) {
130 SmallString<128> S;
131 path::append(S, Path1, Path2);
132 if (fs::exists(S))
133 return S.str().str();
134 return None;
135}
136
137// Inject a new wasm global into the output binary with the given value.
138// Wasm global are used in relocatable object files to model symbol imports
Sam Clegg49ed9262017-12-01 00:53:21 +0000139// and exports. In the final executable the only use of wasm globals is
Sam Cleggc94d3932017-11-17 18:14:09 +0000140// for the exlicit stack pointer (__stack_pointer).
Sam Clegg4eedcfc2017-12-05 19:05:45 +0000141static Symbol* addSyntheticGlobal(StringRef Name, int32_t Value) {
Sam Cleggc94d3932017-11-17 18:14:09 +0000142 log("injecting global: " + Name);
143 Symbol *S = Symtab->addDefinedGlobal(Name);
Sam Clegg4eedcfc2017-12-05 19:05:45 +0000144 S->setVirtualAddress(Value);
Sam Clegg4eedcfc2017-12-05 19:05:45 +0000145 return S;
Sam Cleggc94d3932017-11-17 18:14:09 +0000146}
147
148// Inject a new undefined symbol into the link. This will cause the link to
149// fail unless this symbol can be found.
Sam Cleggb8621592017-11-30 01:40:08 +0000150static void addSyntheticUndefinedFunction(StringRef Name,
151 const WasmSignature *Type) {
Sam Cleggc94d3932017-11-17 18:14:09 +0000152 log("injecting undefined func: " + Name);
Sam Cleggb8621592017-11-30 01:40:08 +0000153 Symtab->addUndefinedFunction(Name, Type);
Sam Cleggc94d3932017-11-17 18:14:09 +0000154}
155
156static void printHelp(const char *Argv0) {
157 WasmOptTable Table;
158 Table.PrintHelp(outs(), Argv0, "LLVM Linker", false);
159}
160
161WasmOptTable::WasmOptTable() : OptTable(OptInfo) {}
162
163opt::InputArgList WasmOptTable::parse(ArrayRef<const char *> Argv) {
164 SmallVector<const char *, 256> Vec(Argv.data(), Argv.data() + Argv.size());
165
166 unsigned MissingIndex;
167 unsigned MissingCount;
168 opt::InputArgList Args = this->ParseArgs(Vec, MissingIndex, MissingCount);
169
170 handleColorDiagnostics(Args);
171 for (auto *Arg : Args.filtered(OPT_UNKNOWN))
172 error("unknown argument: " + Arg->getSpelling());
173 return Args;
174}
175
176void LinkerDriver::addFile(StringRef Path) {
177 Optional<MemoryBufferRef> Buffer = readFile(Path);
178 if (!Buffer.hasValue())
179 return;
180 MemoryBufferRef MBRef = *Buffer;
181
182 if (identify_magic(MBRef.getBuffer()) == file_magic::archive)
183 Files.push_back(make<ArchiveFile>(MBRef));
184 else
185 Files.push_back(make<ObjFile>(MBRef));
186}
187
188// Add a given library by searching it from input search paths.
189void LinkerDriver::addLibrary(StringRef Name) {
190 for (StringRef Dir : Config->SearchPaths) {
191 if (Optional<std::string> S = findFile(Dir, "lib" + Name + ".a")) {
192 addFile(*S);
193 return;
194 }
195 }
196
197 error("unable to find library -l" + Name);
198}
199
200void LinkerDriver::createFiles(opt::InputArgList &Args) {
201 for (auto *Arg : Args) {
202 switch (Arg->getOption().getUnaliasedOption().getID()) {
203 case OPT_l:
204 addLibrary(Arg->getValue());
205 break;
206 case OPT_INPUT:
207 addFile(Arg->getValue());
208 break;
209 }
210 }
211
212 if (Files.empty())
213 error("no input files");
214}
215
216void LinkerDriver::link(ArrayRef<const char *> ArgsArr) {
217 WasmOptTable Parser;
218 opt::InputArgList Args = Parser.parse(ArgsArr.slice(1));
219
220 // Handle --help
221 if (Args.hasArg(OPT_help)) {
222 printHelp(ArgsArr[0]);
223 return;
224 }
225
226 // Parse and evaluate -mllvm options.
227 std::vector<const char *> V;
Rui Ueyamaceb15e82017-11-28 22:17:39 +0000228 V.push_back("wasm-ld (LLVM option parsing)");
Sam Cleggc94d3932017-11-17 18:14:09 +0000229 for (auto *Arg : Args.filtered(OPT_mllvm))
230 V.push_back(Arg->getValue());
231 cl::ParseCommandLineOptions(V.size(), V.data());
232
Rui Ueyama3e039442017-11-28 19:58:45 +0000233 errorHandler().ErrorLimit = args::getInteger(Args, OPT_error_limit, 20);
Sam Cleggc94d3932017-11-17 18:14:09 +0000234
235 if (Args.hasArg(OPT_version) || Args.hasArg(OPT_v)) {
236 outs() << getLLDVersion() << "\n";
237 return;
238 }
239
240 Config->AllowUndefined = Args.hasArg(OPT_allow_undefined);
Sam Cleggb8621592017-11-30 01:40:08 +0000241 Config->CheckSignatures =
242 Args.hasFlag(OPT_check_signatures, OPT_no_check_signatures, false);
Sam Cleggc94d3932017-11-17 18:14:09 +0000243 Config->EmitRelocs = Args.hasArg(OPT_emit_relocs);
244 Config->Entry = Args.getLastArgValue(OPT_entry);
245 Config->ImportMemory = Args.hasArg(OPT_import_memory);
246 Config->OutputFile = Args.getLastArgValue(OPT_o);
247 Config->Relocatable = Args.hasArg(OPT_relocatable);
Rui Ueyama3e039442017-11-28 19:58:45 +0000248 Config->SearchPaths = args::getStrings(Args, OPT_L);
Sam Cleggc94d3932017-11-17 18:14:09 +0000249 Config->StripAll = Args.hasArg(OPT_strip_all);
250 Config->StripDebug = Args.hasArg(OPT_strip_debug);
Sam Cleggc94d3932017-11-17 18:14:09 +0000251 errorHandler().Verbose = Args.hasArg(OPT_verbose);
252 ThreadsEnabled = Args.hasFlag(OPT_threads, OPT_no_threads, true);
Sam Clegg22cfe522017-12-05 16:53:25 +0000253 if (Config->Relocatable)
254 Config->EmitRelocs = true;
Sam Cleggc94d3932017-11-17 18:14:09 +0000255
Rui Ueyama3e039442017-11-28 19:58:45 +0000256 Config->InitialMemory = args::getInteger(Args, OPT_initial_memory, 0);
257 Config->GlobalBase = args::getInteger(Args, OPT_global_base, 1024);
258 Config->MaxMemory = args::getInteger(Args, OPT_max_memory, 0);
259 Config->ZStackSize =
260 args::getZOptionValue(Args, OPT_z, "stack-size", WasmPageSize);
Sam Cleggc94d3932017-11-17 18:14:09 +0000261
262 if (auto *Arg = Args.getLastArg(OPT_allow_undefined_file))
263 if (Optional<MemoryBufferRef> Buf = readFile(Arg->getValue()))
Rui Ueyama3e039442017-11-28 19:58:45 +0000264 for (StringRef Sym : args::getLines(*Buf))
Sam Cleggc94d3932017-11-17 18:14:09 +0000265 Config->AllowUndefinedSymbols.insert(Sym);
266
267 if (Config->OutputFile.empty())
268 error("no output file specified");
269
270 if (!Args.hasArg(OPT_INPUT))
271 error("no input files");
272
273 if (Config->Relocatable && !Config->Entry.empty())
274 error("entry point specified for relocatable output file");
Sam Clegg31de2f02017-12-07 03:19:53 +0000275 if (Config->Relocatable && Args.hasArg(OPT_undefined))
276 error("undefined symbols specified for relocatable output file");
Sam Cleggc94d3932017-11-17 18:14:09 +0000277
278 if (!Config->Relocatable) {
279 if (Config->Entry.empty())
280 Config->Entry = "_start";
Rui Ueyama69989bd2017-12-01 02:11:29 +0000281 static WasmSignature Signature = {{}, WASM_TYPE_NORESULT};
Sam Cleggb8621592017-11-30 01:40:08 +0000282 addSyntheticUndefinedFunction(Config->Entry, &Signature);
Sam Cleggc94d3932017-11-17 18:14:09 +0000283
Sam Clegg31de2f02017-12-07 03:19:53 +0000284 // Handle the `--undefined <sym>` options.
285 for (StringRef S : args::getStrings(Args, OPT_undefined))
286 addSyntheticUndefinedFunction(S, nullptr);
287
Sam Clegg4eedcfc2017-12-05 19:05:45 +0000288 Config->StackPointerSymbol = addSyntheticGlobal("__stack_pointer", 0);
Sam Cleggc94d3932017-11-17 18:14:09 +0000289 }
290
291 createFiles(Args);
292 if (errorCount())
293 return;
294
295 // Add all files to the symbol table. This will add almost all
296 // symbols that we need to the symbol table.
297 for (InputFile *F : Files)
298 Symtab->addFile(F);
299
300 // Make sure we have resolved all symbols.
301 if (!Config->Relocatable && !Config->AllowUndefined) {
302 Symtab->reportRemainingUndefines();
303 if (errorCount())
304 return;
Sam Clegg31de2f02017-12-07 03:19:53 +0000305 } else {
306 // When we allow undefined symbols we cannot include those defined in
307 // -u/--undefined since these undefined symbols have only names and no
308 // function signature, which means they cannot be written to the final
309 // output.
310 for (StringRef S : args::getStrings(Args, OPT_undefined)) {
311 Symbol *Sym = Symtab->find(S);
312 if (!Sym->isDefined())
313 error("function forced with --undefined not found: " + Sym->getName());
314 }
315 if (errorCount())
316 return;
Sam Cleggc94d3932017-11-17 18:14:09 +0000317 }
318
319 if (!Config->Entry.empty()) {
320 Symbol *Sym = Symtab->find(Config->Entry);
321 if (!Sym->isFunction())
322 fatal("entry point is not a function: " + Sym->getName());
323 }
324
325 // Write the result to the file.
326 writeResult();
327}