-
Notifications
You must be signed in to change notification settings - Fork 712
/
wasm-interp.cc
451 lines (394 loc) · 14.7 KB
/
wasm-interp.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
/*
* Copyright 2016 WebAssembly Community Group participants
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <algorithm>
#include <cassert>
#include <cstdio>
#include <cstdlib>
#include <memory>
#include <string>
#include <vector>
#include "wabt/binary-reader.h"
#include "wabt/error-formatter.h"
#include "wabt/feature.h"
#include "wabt/interp/binary-reader-interp.h"
#include "wabt/interp/interp-util.h"
#include "wabt/interp/interp-wasi.h"
#include "wabt/interp/interp.h"
#include "wabt/literal.h"
#include "wabt/option-parser.h"
#include "wabt/stream.h"
#ifdef WITH_WASI
#include "uvwasi.h"
#endif
using namespace wabt;
using namespace wabt::interp;
struct FunctionCall {
std::string name;
Values args;
};
#define ERROR_EXIT_UNLESS(cond, ...) \
do { \
if (!(cond)) { \
printf(__VA_ARGS__); \
exit(1); \
} \
} while (0);
static int s_verbose;
static const char* s_infile;
static Thread::Options s_thread_options;
static Stream* s_trace_stream;
static bool s_run_all_exports;
static bool s_host_print;
static bool s_dummy_import_func;
static Features s_features;
static bool s_wasi;
static std::vector<FunctionCall> s_run_exports;
static std::vector<std::string> s_wasi_env;
static std::vector<std::string> s_wasi_argv;
static std::vector<std::string> s_wasi_dirs;
static std::unique_ptr<FileStream> s_log_stream;
static std::unique_ptr<FileStream> s_stdout_stream;
static std::unique_ptr<FileStream> s_stderr_stream;
static Store s_store;
static const char s_description[] =
R"( read a file in the wasm binary format, and run in it a stack-based
interpreter.
examples:
# parse binary file test.wasm, and type-check it
$ wasm-interp test.wasm
# parse test.wasm and run all its exported functions
$ wasm-interp test.wasm --run-all-exports
# parse test.wasm, run the exported functions and trace the output
$ wasm-interp test.wasm --run-all-exports --trace
# parse test.wasm and run all its exported functions, setting the
# value stack size to 100 elements
$ wasm-interp test.wasm -V 100 --run-all-exports
# parse test.wasm, run specific exported function by name with argument
$ wasm-interp test.wasm -r "func_sum" -a "i32:8" -a "i32:5"
)";
Result ParseWasmValue(std::string argument, Value& val) {
Result result = Result::Ok;
size_t cindex;
if (argument.empty() || (cindex = argument.find(':')) == std::string::npos) {
return wabt::Result::Error;
}
argument[cindex] = '\0';
const char* ptype = argument.c_str();
const char* pval = argument.c_str() + cindex + 1;
const char* pval_end = ptype + argument.length();
if (strcmp(ptype, "i32") == 0) {
uint32_t parsed_value;
result |=
ParseInt32(pval, pval_end, &parsed_value, ParseIntType::UnsignedOnly);
val.Set(parsed_value);
}
if (strcmp(ptype, "i64") == 0) {
uint64_t parsed_value;
result |=
ParseInt64(pval, pval_end, &parsed_value, ParseIntType::UnsignedOnly);
val.Set(parsed_value);
}
if (strcmp(ptype, "f32") == 0) {
uint32_t parsed_value;
result |= ParseFloat(LiteralType::Float, pval, pval_end, &parsed_value);
val.Set(parsed_value);
}
if (strcmp(ptype, "f64") == 0) {
uint64_t parsed_value;
result |= ParseDouble(LiteralType::Float, pval, pval_end, &parsed_value);
val.Set(parsed_value);
}
return result;
}
static void ParseOptions(int argc, char** argv) {
OptionParser parser("wasm-interp", s_description);
parser.AddOption('v', "verbose", "Use multiple times for more info", []() {
s_verbose++;
s_log_stream = FileStream::CreateStderr();
});
s_features.AddOptions(&parser);
parser.AddOption('V', "value-stack-size", "SIZE",
"Size in elements of the value stack",
[](const std::string& argument) {
// TODO(binji): validate.
s_thread_options.value_stack_size = atoi(argument.c_str());
});
parser.AddOption('C', "call-stack-size", "SIZE",
"Size in elements of the call stack",
[](const std::string& argument) {
// TODO(binji): validate.
s_thread_options.call_stack_size = atoi(argument.c_str());
});
parser.AddOption('t', "trace", "Trace execution",
[]() { s_trace_stream = s_stdout_stream.get(); });
parser.AddOption('r', "run-export", "FUNCTION",
"Run exported function by name",
[](const std::string& argument) {
FunctionCall func;
func.name = argument;
s_run_exports.push_back(func);
});
parser.AddOption('a', "argument", "ARGUMENT",
"Add argument to an exported function execution",
[](const std::string& argument) {
Value val;
ERROR_EXIT_UNLESS(
!s_run_exports.empty(),
"Cannot find a function execution for argument '%s'\n",
argument.c_str());
ERROR_EXIT_UNLESS(Succeeded(ParseWasmValue(argument, val)),
"Failed to parse argument '%s'\n",
argument.c_str());
s_run_exports.back().args.push_back(val);
});
parser.AddOption("wasi",
"Assume input module is WASI compliant (Export "
" WASI API the the module and invoke _start function)",
[]() { s_wasi = true; });
parser.AddOption(
'e', "env", "ENV",
"Pass the given environment string in the WASI runtime",
[](const std::string& argument) { s_wasi_env.push_back(argument); });
parser.AddOption(
'd', "dir", "DIR", "Pass the given directory the the WASI runtime",
[](const std::string& argument) { s_wasi_dirs.push_back(argument); });
parser.AddOption(
"run-all-exports",
"Run all the exported functions, in order. Useful for testing",
[]() { s_run_all_exports = true; });
parser.AddOption("host-print",
"Include an importable function named \"host.print\" for "
"printing to stdout",
[]() { s_host_print = true; });
parser.AddOption(
"dummy-import-func",
"Provide a dummy implementation of all imported functions. The function "
"will log the call and return an appropriate zero value.",
[]() { s_dummy_import_func = true; });
parser.AddArgument("filename", OptionParser::ArgumentCount::One,
[](const char* argument) { s_infile = argument; });
parser.AddArgument(
"arg", OptionParser::ArgumentCount::ZeroOrMore,
[](const char* argument) { s_wasi_argv.push_back(argument); });
parser.Parse(argc, argv);
}
Result RunSpecificExports(const Instance::Ptr& instance,
Errors* errors,
std::vector<FunctionCall>& calls) {
Result result = Result::Ok;
auto module = s_store.UnsafeGet<Module>(instance->module());
auto&& module_desc = module->desc();
for (auto&& export_ : module_desc.exports) {
for (auto& call_ : calls) {
if (export_.type.name == call_.name) {
ERROR_EXIT_UNLESS(export_.type.type->kind == ExternalKind::Func,
"Export '%s' is not a function\n",
export_.type.name.c_str());
if (s_trace_stream) {
s_trace_stream->Writef(">>> running export \"%s\":\n",
call_.name.c_str());
}
auto* func_type = cast<FuncType>(export_.type.type.get());
auto func = s_store.UnsafeGet<Func>(instance->funcs()[export_.index]);
Values results;
Trap::Ptr trap;
result |=
func->Call(s_store, call_.args, results, &trap, s_trace_stream);
WriteCall(s_stdout_stream.get(), export_.type.name, *func_type,
call_.args, results, trap);
}
}
}
return result;
}
Result RunAllExports(const Instance::Ptr& instance, Errors* errors) {
Result result = Result::Ok;
auto module = s_store.UnsafeGet<Module>(instance->module());
auto&& module_desc = module->desc();
for (auto&& export_ : module_desc.exports) {
if (export_.type.type->kind != ExternalKind::Func) {
continue;
}
auto* func_type = cast<FuncType>(export_.type.type.get());
if (func_type->params.empty()) {
if (s_trace_stream) {
s_trace_stream->Writef(">>> running export \"%s\":\n",
export_.type.name.c_str());
}
auto func = s_store.UnsafeGet<Func>(instance->funcs()[export_.index]);
Values params;
Values results;
Trap::Ptr trap;
result |= func->Call(s_store, params, results, &trap, s_trace_stream);
WriteCall(s_stdout_stream.get(), export_.type.name, *func_type, params,
results, trap);
}
}
return result;
}
static void BindImports(const Module::Ptr& module, RefVec& imports) {
auto* stream = s_stdout_stream.get();
for (auto&& import : module->desc().imports) {
if (import.type.type->kind == ExternKind::Func &&
((s_host_print && import.type.module == "host" &&
import.type.name == "print") ||
s_dummy_import_func)) {
auto func_type = *cast<FuncType>(import.type.type.get());
auto import_name = StringPrintf("%s.%s", import.type.module.c_str(),
import.type.name.c_str());
auto host_func = HostFunc::New(
s_store, func_type,
[=](Thread& thread, const Values& params, Values& results,
Trap::Ptr* trap) -> Result {
printf("called host ");
WriteCall(stream, import_name, func_type, params, results, *trap);
return Result::Ok;
});
imports.push_back(host_func.ref());
continue;
}
// By default, just push an null reference. This won't resolve, and
// instantiation will fail.
imports.push_back(Ref::Null);
}
}
static Result ReadModule(const char* module_filename,
Errors* errors,
Module::Ptr* out_module) {
auto* stream = s_stdout_stream.get();
std::vector<uint8_t> file_data;
CHECK_RESULT(ReadFile(module_filename, &file_data));
ModuleDesc module_desc;
const bool kReadDebugNames = true;
const bool kStopOnFirstError = true;
const bool kFailOnCustomSectionError = true;
ReadBinaryOptions options(s_features, s_log_stream.get(), kReadDebugNames,
kStopOnFirstError, kFailOnCustomSectionError);
CHECK_RESULT(ReadBinaryInterp(module_filename, file_data.data(),
file_data.size(), options, errors,
&module_desc));
if (s_verbose) {
module_desc.istream.Disassemble(stream);
}
*out_module = Module::New(s_store, module_desc);
return Result::Ok;
}
static Result InstantiateModule(RefVec& imports,
const Module::Ptr& module,
Instance::Ptr* out_instance) {
RefPtr<Trap> trap;
*out_instance = Instance::Instantiate(s_store, module.ref(), imports, &trap);
if (!*out_instance) {
WriteTrap(s_stderr_stream.get(), "error initializing module", trap);
return Result::Error;
}
return Result::Ok;
}
static Result ReadAndRunModule(const char* module_filename) {
Errors errors;
Module::Ptr module;
Result result = ReadModule(module_filename, &errors, &module);
if (!Succeeded(result)) {
FormatErrorsToFile(errors, Location::Type::Binary);
return result;
}
RefVec imports;
#if WITH_WASI
uvwasi_t uvwasi;
#endif
if (s_wasi) {
#if WITH_WASI
uvwasi_errno_t err;
uvwasi_options_t init_options;
std::vector<const char*> argv;
argv.push_back(module_filename);
for (auto& s : s_wasi_argv) {
if (s_trace_stream) {
s_trace_stream->Writef("wasi: arg: \"%s\"\n", s.c_str());
}
argv.push_back(s.c_str());
}
argv.push_back(nullptr);
std::vector<const char*> envp;
for (auto& s : s_wasi_env) {
if (s_trace_stream) {
s_trace_stream->Writef("wasi: env: \"%s\"\n", s.c_str());
}
envp.push_back(s.c_str());
}
envp.push_back(nullptr);
std::vector<uvwasi_preopen_t> dirs;
for (auto& dir : s_wasi_dirs) {
if (s_trace_stream) {
s_trace_stream->Writef("wasi: dir: \"%s\"\n", dir.c_str());
}
dirs.push_back({dir.c_str(), dir.c_str()});
}
/* Setup the initialization options. */
init_options.in = 0;
init_options.out = 1;
init_options.err = 2;
init_options.fd_table_size = 3;
init_options.argc = argv.size() - 1;
init_options.argv = argv.data();
init_options.envp = envp.data();
init_options.preopenc = dirs.size();
init_options.preopens = dirs.data();
init_options.allocator = NULL;
err = uvwasi_init(&uvwasi, &init_options);
if (err != UVWASI_ESUCCESS) {
s_stderr_stream.get()->Writef("error initialiazing uvwasi: %d\n", err);
return Result::Error;
}
CHECK_RESULT(WasiBindImports(module, imports, s_stderr_stream.get(),
s_trace_stream));
#else
s_stderr_stream.get()->Writef("wasi support not compiled in\n");
return Result::Error;
#endif
} else {
BindImports(module, imports);
}
Instance::Ptr instance;
CHECK_RESULT(InstantiateModule(imports, module, &instance));
if (s_run_all_exports) {
RunAllExports(instance, &errors);
}
if (!s_run_exports.empty()) {
RunSpecificExports(instance, &errors, s_run_exports);
}
#ifdef WITH_WASI
if (s_wasi) {
CHECK_RESULT(
WasiRunStart(instance, &uvwasi, s_stderr_stream.get(), s_trace_stream));
}
#endif
return Result::Ok;
}
int ProgramMain(int argc, char** argv) {
InitStdio();
s_stdout_stream = FileStream::CreateStdout();
s_stderr_stream = FileStream::CreateStderr();
ParseOptions(argc, argv);
s_store.setFeatures(s_features);
wabt::Result result = ReadAndRunModule(s_infile);
return result != wabt::Result::Ok;
}
int main(int argc, char** argv) {
WABT_TRY
return ProgramMain(argc, argv);
WABT_CATCH_BAD_ALLOC_AND_EXIT
}