-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmy-interp.cc
352 lines (307 loc) · 11.8 KB
/
my-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
/*
* 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 <cinttypes>
#include <cstdio>
#include <cstdlib>
#include <memory>
#include <string>
#include <vector>
#include <iostream>
#include "src/binary-reader-interp.h"
#include "src/binary-reader.h"
#include "src/cast.h"
#include "src/error-handler.h"
#include "src/interp.h"
#include "src/option-parser.h"
using namespace wabt;
using namespace wabt::interp;
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_run_export;
static bool s_host_print;
static Features s_features;
std::string callExport;
static std::unique_ptr<FileStream> s_log_stream;
static std::unique_ptr<FileStream> s_stdout_stream;
enum class RunVerbosity {
Quiet = 0,
Verbose = 1,
};
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
)";
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::CreateStdout();
});
parser.AddHelpOption();
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('E', "run-my-export", "SIZE",
"Run export",
[](const std::string& argument) {
s_run_export = true;
callExport = argument;
});
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(
"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.AddArgument("filename", OptionParser::ArgumentCount::One,
[](const char* argument) { s_infile = argument; });
parser.Parse(argc, argv);
}
static void RunAllExports(interp::Module* module,
Executor* executor,
RunVerbosity verbose) {
TypedValues args;
TypedValues results;
for (const interp::Export& export_ : module->exports) {
ExecResult exec_result = executor->RunExport(&export_, args);
if (verbose == RunVerbosity::Verbose) {
WriteCall(s_stdout_stream.get(), string_view(), export_.name, args,
exec_result.values, exec_result.result);
}
}
}
static void RunExport(std::string exportName,
interp::Module* module,
Executor* executor,
RunVerbosity verbose) {
for (const interp::Export& export_ : module->exports) {
if(export_.name == exportName){
TypedValues args;
TypedValues results;
Value myValue;
myValue.i32 = 41;
TypedValue myArg = TypedValue(Type::I32,myValue);
args.emplace_back(myArg);
ExecResult exec_result = executor->RunExport(&export_, args);
for (TypedValue& value : exec_result.values) {
switch(value.type){
case Type::I32:
std::cout << "export result i32 " << value.value.i32 << "\r\n";
break;
default:
break;
}
}
if (verbose == RunVerbosity::Verbose) {
WriteCall(s_stdout_stream.get(), string_view(), export_.name, args,
exec_result.values, exec_result.result);
}
}
}
}
static wabt::Result ReadModule(const char* module_filename,
Environment* env,
ErrorHandler* error_handler,
DefinedModule** out_module) {
wabt::Result result;
std::vector<uint8_t> file_data;
*out_module = nullptr;
result = ReadFile(module_filename, &file_data);
if (Succeeded(result)) {
const bool kReadDebugNames = true;
const bool kStopOnFirstError = true;
ReadBinaryOptions options(s_features, s_log_stream.get(), kReadDebugNames,
kStopOnFirstError);
result = ReadBinaryInterp(env, DataOrNull(file_data), file_data.size(),
&options, error_handler, out_module);
if (Succeeded(result)) {
if (s_verbose)
env->DisassembleModule(s_stdout_stream.get(), *out_module);
}
}
return result;
}
#define PRIimport "\"" PRIstringview "." PRIstringview "\""
#define PRINTF_IMPORT_ARG(x) \
WABT_PRINTF_STRING_VIEW_ARG((x).module_name) \
, WABT_PRINTF_STRING_VIEW_ARG((x).field_name)
class WasmInterpHostImportDelegate : public HostImportDelegate {
public:
wabt::Result ImportFunc(interp::FuncImport* import,
interp::Func* func,
interp::FuncSignature* func_sig,
const ErrorCallback& callback) override {
if (import->field_name == "print") {
cast<HostFunc>(func)->callback = PrintCallback;
return wabt::Result::Ok;
}
else if (import->field_name == "import_function") {
cast<HostFunc>(func)->callback = MyImportCallback;
return wabt::Result::Ok;
}
else if (import->field_name == "rust_begin_unwind") {
cast<HostFunc>(func)->callback = RustUnwindCallback;
return wabt::Result::Ok;
}
else {
PrintError(callback, "unknown host function import " PRIimport,
PRINTF_IMPORT_ARG(*import));
return wabt::Result::Error;
}
}
wabt::Result ImportTable(interp::TableImport* import,
interp::Table* table,
const ErrorCallback& callback) override {
return wabt::Result::Error;
}
wabt::Result ImportMemory(interp::MemoryImport* import,
interp::Memory* memory,
const ErrorCallback& callback) override {
return wabt::Result::Error;
}
wabt::Result ImportGlobal(interp::GlobalImport* import,
interp::Global* global,
const ErrorCallback& callback) override {
return wabt::Result::Error;
}
private:
static interp::Result PrintCallback(const HostFunc* func,
const interp::FuncSignature* sig,
Index num_args,
TypedValue* args,
Index num_results,
TypedValue* out_results,
void* user_data) {
memset(out_results, 0, sizeof(TypedValue) * num_results);
for (Index i = 0; i < num_results; ++i)
out_results[i].type = sig->result_types[i];
TypedValues vec_args(args, args + num_args);
TypedValues vec_results(out_results, out_results + num_results);
printf("called host ");
WriteCall(s_stdout_stream.get(), func->module_name, func->field_name,
vec_args, vec_results, interp::Result::Ok);
return interp::Result::Ok;
}
static interp::Result MyImportCallback(const HostFunc* func,
const interp::FuncSignature* sig,
Index num_args,
TypedValue* args,
Index num_results,
TypedValue* out_results,
void* user_data) {
memset(out_results, 0, sizeof(TypedValue) * num_results);
for (Index i = 0; i < num_results; ++i)
out_results[i].type = sig->result_types[i];
TypedValues vec_args(args, args + num_args);
TypedValues vec_results(out_results, out_results + num_results);
std::cout << "Called my import function with args: \r\n";
for(auto &res : vec_args){
switch(res.type){
case Type::I32:
std::cout << "import argument i32 " << res.value.i32 << "\r\n";
break;
default:
break;
}
}
WriteCall(s_stdout_stream.get(), func->module_name, func->field_name,
vec_args, vec_results, interp::Result::Ok);
return interp::Result::Ok;
}
static interp::Result RustUnwindCallback(const HostFunc* func,
const interp::FuncSignature* sig,
Index num_args,
TypedValue* args,
Index num_results,
TypedValue* out_results,
void* user_data) {
return interp::Result::Ok;
}
void PrintError(const ErrorCallback& callback, const char* format, ...) {
WABT_SNPRINTF_ALLOCA(buffer, length, format);
callback(buffer);
}
};
static void InitEnvironment(Environment* env) {
HostModule* host_module = env->AppendHostModule("env");
host_module->import_delegate.reset(new WasmInterpHostImportDelegate());
}
static wabt::Result ReadAndRunModule(const char* module_filename) {
wabt::Result result;
Environment env;
InitEnvironment(&env);
ErrorHandlerFile error_handler(Location::Type::Binary);
DefinedModule* module = nullptr;
result = ReadModule(module_filename, &env, &error_handler, &module);
if (Succeeded(result)) {
Executor executor(&env, s_trace_stream, s_thread_options);
ExecResult exec_result = executor.RunStartFunction(module);
if (exec_result.result == interp::Result::Ok) {
if (s_run_all_exports){
RunAllExports(module, &executor, RunVerbosity::Verbose);
}
else if(s_run_export){
RunExport(callExport,module, &executor, RunVerbosity::Verbose);
}
}
else {
WriteResult(s_stdout_stream.get(), "error running start function",
exec_result.result);
}
}
return result;
}
int ProgramMain(int argc, char** argv) {
InitStdio();
s_stdout_stream = FileStream::CreateStdout();
ParseOptions(argc, argv);
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
}