-
Notifications
You must be signed in to change notification settings - Fork 840
Expand file tree
/
Copy pathwasm-shell.cpp
More file actions
606 lines (548 loc) · 19.8 KB
/
wasm-shell.cpp
File metadata and controls
606 lines (548 loc) · 19.8 KB
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
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
/*
* Copyright 2015 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.
*/
//
// A WebAssembly shell, loads a .wast file (WebAssembly in S-Expression format)
// and executes it. This provides similar functionality as the reference
// interpreter, like assert_* calls, so it can run the spec test suite.
//
#include <memory>
#include "execution-results.h"
#include "ir/element-utils.h"
#include "parser/lexer.h"
#include "parser/wat-parser.h"
#include "pass.h"
#include "shell-interface.h"
#include "support/command-line.h"
#include "support/file.h"
#include "support/result.h"
#include "wasm-binary.h"
#include "wasm-interpreter.h"
#include "wasm-validator.h"
using namespace wasm;
using namespace wasm::WATParser;
struct Shell {
// Keyed by module name.
std::map<Name, std::shared_ptr<Module>> modules;
// Keyed by instance name.
std::map<Name, std::shared_ptr<ShellExternalInterface>> interfaces;
std::map<Name, std::shared_ptr<ModuleRunner>> instances;
// Used for imports, keyed by instance name.
std::map<Name, std::shared_ptr<ModuleRunner>> linkedInstances;
Name lastInstance;
std::optional<Name> lastModuleDefinition;
Options& options;
Shell(Options& options) : options(options) { buildSpectestModule(); }
Result<> run(WASTScript& script) {
size_t i = 0;
for (auto& entry : script) {
Colors::red(std::cerr);
std::cerr << i++ << ' ';
Colors::normal(std::cerr);
if (std::get_if<WASTModule>(&entry.cmd)) {
Colors::green(std::cerr);
std::cerr << "BUILDING MODULE [line: " << entry.line << "]\n";
Colors::normal(std::cerr);
} else if (auto* reg = std::get_if<Register>(&entry.cmd)) {
Colors::green(std::cerr);
std::cerr << "REGISTER MODULE INSTANCE AS \"" << reg->name
<< "\" [line: " << entry.line << "]\n";
Colors::normal(std::cerr);
} else {
Colors::green(std::cerr);
std::cerr << "CHECKING [line: " << entry.line << "]\n";
Colors::normal(std::cerr);
}
CHECK_ERR(runCommand(entry.cmd));
}
return Ok{};
}
Result<> runCommand(WASTCommand& cmd) {
if (auto* mod = std::get_if<WASTModule>(&cmd)) {
return addModule(*mod);
} else if (auto* reg = std::get_if<Register>(&cmd)) {
return addRegistration(*reg);
} else if (auto* act = std::get_if<Action>(&cmd)) {
doAction(*act);
return Ok{};
} else if (auto* assn = std::get_if<Assertion>(&cmd)) {
return doAssertion(*assn);
} else if (auto* instantiateModule =
std::get_if<ModuleInstantiation>(&cmd)) {
return doInstantiate(*instantiateModule);
} else {
WASM_UNREACHABLE("unexpected command");
}
}
Result<std::shared_ptr<Module>> makeModule(WASTModule& mod) {
std::shared_ptr<Module> wasm;
if (auto* quoted = std::get_if<QuotedModule>(&mod.module)) {
wasm = std::make_shared<Module>();
switch (quoted->type) {
case QuotedModuleType::Text: {
CHECK_ERR(parseModule(*wasm, quoted->module));
break;
}
case QuotedModuleType::Binary: {
std::vector<char> buffer(quoted->module.begin(),
quoted->module.end());
WasmBinaryReader reader(*wasm, FeatureSet::All, buffer);
try {
reader.read();
} catch (ParseException& p) {
std::stringstream ss;
p.dump(ss);
return Err{ss.str()};
}
break;
}
}
} else if (auto* ptr = std::get_if<std::shared_ptr<Module>>(&mod.module)) {
wasm = *ptr;
} else {
WASM_UNREACHABLE("unexpected module kind");
}
wasm->features = FeatureSet::All;
return wasm;
}
Result<> validateModule(Module& wasm) {
if (!WasmValidator().validate(wasm)) {
return Err{"failed validation"};
}
return Ok{};
}
Result<> doInstantiate(ModuleInstantiation& instantiateModule) {
auto moduleDefinitionName = instantiateModule.moduleName
? instantiateModule.moduleName
: lastModuleDefinition;
if (!moduleDefinitionName) {
return Err{"No module definition found in module instantiation, and no "
"previous module definition was found."};
}
auto instanceName = instantiateModule.instanceName
? instantiateModule.instanceName
: lastModuleDefinition;
if (!instanceName) {
return Err{"No instance name found in module instantiation, and no "
"previous module definition was found."};
}
return instantiate(*modules[*moduleDefinitionName], *instanceName);
}
Result<> instantiate(Module& wasm, Name instanceName) {
auto interface = std::make_shared<ShellExternalInterface>(linkedInstances);
auto instance =
std::make_shared<ModuleRunner>(wasm, interface.get(), linkedInstances);
lastInstance = instanceName;
// Even if instantiation fails, the module may have partially instantiated
// and mutated an imported memory or table. Keep the references alive to
// ensure that function references stay alive.
interfaces[instanceName] = interface;
instances[instanceName] = instance;
try {
// This is not an optimization: we want to execute anything, even relaxed
// SIMD instructions.
instance->setRelaxedBehavior(ModuleRunner::RelaxedBehavior::Execute);
instance->instantiate(/* validateImports_=*/true);
} catch (const std::exception& e) {
return Err{std::string("failed to instantiate module: ") + e.what()};
} catch (...) {
return Err{"failed to instantiate module"};
}
return Ok{};
}
Result<> addModule(WASTModule& mod) {
auto module = makeModule(mod);
CHECK_ERR(module);
auto wasm = *module;
CHECK_ERR(validateModule(*wasm));
modules[wasm->name] = wasm;
if (!mod.isDefinition) {
CHECK_ERR(instantiate(*wasm, wasm->name));
} else {
lastModuleDefinition = wasm->name;
}
return Ok{};
}
Result<> addRegistration(Register& reg) {
Name instanceName = reg.instanceName ? *reg.instanceName : lastInstance;
auto instance = instances[instanceName];
if (!instance) {
return Err{"register called without a module"};
}
linkedInstances[reg.name] = instance;
// We copy pointers as a registered module's name might still be used
// in an assertion or invoke command.
interfaces[reg.name] = interfaces[instanceName];
instances[reg.name] = instances[instanceName];
return Ok{};
}
struct TrapResult {};
struct HostLimitResult {};
struct ExceptionResult {};
struct SuspensionResult {};
using ActionResult = std::variant<Literals,
TrapResult,
HostLimitResult,
ExceptionResult,
SuspensionResult>;
std::string resultToString(ActionResult& result) {
if (std::get_if<TrapResult>(&result)) {
return "trap";
} else if (std::get_if<HostLimitResult>(&result)) {
return "exceeded host limit";
} else if (std::get_if<ExceptionResult>(&result)) {
return "exception";
} else if (std::get_if<SuspensionResult>(&result)) {
return "suspension";
} else if (auto* vals = std::get_if<Literals>(&result)) {
std::stringstream ss;
ss << *vals;
return ss.str();
} else {
WASM_UNREACHABLE("unexpected result");
}
}
ActionResult doAction(Action& act) {
assert(instances[lastInstance].get());
if (auto* invoke = std::get_if<InvokeAction>(&act)) {
auto it = instances.find(invoke->base ? *invoke->base : lastInstance);
if (it == instances.end()) {
return TrapResult{};
}
auto& instance = it->second;
Flow flow;
try {
flow = instance->callExport(invoke->name, invoke->args);
} catch (TrapException&) {
return TrapResult{};
} catch (HostLimitException&) {
return HostLimitResult{};
} catch (WasmException&) {
return ExceptionResult{};
} catch (...) {
WASM_UNREACHABLE("unexpected error");
}
if (flow.suspendTag) {
// This is an unhandled suspension. Handle it here - clear the
// suspension state - so nothing else is affected.
instance->clearContinuationStore();
return SuspensionResult{};
}
return flow.values;
} else if (auto* get = std::get_if<GetAction>(&act)) {
auto it = instances.find(get->base ? *get->base : lastInstance);
if (it == instances.end()) {
return TrapResult{};
}
auto& instance = it->second;
try {
return instance->getExportedGlobalOrTrap(get->name);
} catch (TrapException&) {
return TrapResult{};
} catch (...) {
WASM_UNREACHABLE("unexpected error");
}
} else {
WASM_UNREACHABLE("unexpected action");
}
}
Result<> doAssertion(Assertion& assn) {
if (auto* ret = std::get_if<AssertReturn>(&assn)) {
return assertReturn(*ret);
} else if (auto* act = std::get_if<AssertAction>(&assn)) {
return assertAction(*act);
} else if (auto* mod = std::get_if<AssertModule>(&assn)) {
return assertModule(*mod);
} else {
WASM_UNREACHABLE("unexpected assertion");
}
}
Result<> checkNaN(Literal val, NaNResult nan) {
std::stringstream err;
switch (nan.kind) {
case NaNKind::Canonical:
if (val.type != nan.type || !val.isCanonicalNaN()) {
err << "expected canonical " << nan.type << " NaN, got " << val;
return Err{err.str()};
}
break;
case NaNKind::Arithmetic:
if (val.type != nan.type || !val.isArithmeticNaN()) {
err << "expected arithmetic " << nan.type << " NaN, got " << val;
return Err{err.str()};
}
break;
}
return Ok{};
}
Result<> checkLane(Literal val, LaneResult expected, Index index) {
std::stringstream err;
if (auto* e = std::get_if<Literal>(&expected)) {
if (*e != val) {
err << "expected " << *e << ", got " << val << " at lane " << index;
return Err{err.str()};
}
} else if (auto* nan = std::get_if<NaNResult>(&expected)) {
auto check = checkNaN(val, *nan);
if (auto* e = check.getErr()) {
err << e->msg << " at lane " << index;
return Err{err.str()};
}
} else {
WASM_UNREACHABLE("unexpected lane expectation");
}
return Ok{};
}
Result<> assertReturn(AssertReturn& assn) {
std::stringstream err;
auto result = doAction(assn.action);
auto* values = std::get_if<Literals>(&result);
if (!values) {
return Err{std::string("expected return, got ") + resultToString(result)};
}
if (values->size() != assn.expected.size()) {
err << "expected " << assn.expected.size() << " values, got "
<< resultToString(result);
return Err{err.str()};
}
for (Index i = 0; i < values->size(); ++i) {
auto atIndex = [&]() {
if (values->size() <= 1) {
return std::string{};
}
std::stringstream ss;
ss << " at index " << i;
return ss.str();
};
Literal val = (*values)[i];
auto& expected = assn.expected[i];
if (auto* v = std::get_if<Literal>(&expected)) {
if (val != *v) {
err << "expected " << *v << ", got " << val << atIndex();
return Err{err.str()};
}
} else if (auto* ref = std::get_if<RefResult>(&expected)) {
if (!val.type.isRef() ||
!HeapType::isSubType(val.type.getHeapType(), ref->type)) {
err << "expected " << ref->type << " reference, got " << val
<< atIndex();
return Err{err.str()};
}
} else if ([[maybe_unused]] auto* nullRef =
std::get_if<NullRefResult>(&expected)) {
if (!val.isNull()) {
err << "expected ref.null, got " << val << atIndex();
return Err{err.str()};
}
} else if (auto* nan = std::get_if<NaNResult>(&expected)) {
auto check = checkNaN(val, *nan);
if (auto* e = check.getErr()) {
err << e->msg << atIndex();
return Err{err.str()};
}
} else if (auto* lanes = std::get_if<LaneResults>(&expected)) {
switch (lanes->size()) {
case 4: {
auto vals = val.getLanesF32x4();
for (Index i = 0; i < 4; ++i) {
auto check = checkLane(vals[i], (*lanes)[i], i);
if (auto* e = check.getErr()) {
err << e->msg << atIndex();
return Err{err.str()};
}
}
break;
}
case 2: {
auto vals = val.getLanesF64x2();
for (Index i = 0; i < 2; ++i) {
auto check = checkLane(vals[i], (*lanes)[i], i);
if (auto* e = check.getErr()) {
err << e->msg << atIndex();
return Err{err.str()};
}
}
break;
}
default:
WASM_UNREACHABLE("unexpected number of lanes");
}
} else {
WASM_UNREACHABLE("unexpected expectation");
}
}
return Ok{};
}
Result<> assertAction(AssertAction& assn) {
std::stringstream err;
auto result = doAction(assn.action);
switch (assn.type) {
case ActionAssertionType::Trap:
if (std::get_if<TrapResult>(&result)) {
return Ok{};
}
err << "expected trap";
break;
case ActionAssertionType::Exhaustion:
if (std::get_if<HostLimitResult>(&result)) {
return Ok{};
}
err << "expected exhaustion";
break;
case ActionAssertionType::Exception:
if (std::get_if<ExceptionResult>(&result)) {
return Ok{};
}
err << "expected exception";
break;
case ActionAssertionType::Suspension:
if (std::get_if<SuspensionResult>(&result)) {
return Ok{};
}
err << "expected suspension";
break;
}
err << ", got " << resultToString(result);
return Err{err.str()};
}
Result<> assertModule(AssertModule& assn) {
auto wasm = makeModule(assn.wasm);
if (const auto* err = wasm.getErr()) {
if (assn.type == ModuleAssertionType::Malformed ||
assn.type == ModuleAssertionType::Invalid) {
return Ok{};
}
return Err{err->msg};
}
if (assn.type == ModuleAssertionType::Malformed) {
return Err{"expected malformed module"};
}
auto valid = validateModule(**wasm);
if (auto* err = valid.getErr()) {
if (assn.type == ModuleAssertionType::Invalid) {
return Ok{};
}
return Err{err->msg};
}
if (assn.type == ModuleAssertionType::Invalid) {
return Err{"expected invalid module"};
}
auto instance = instantiate(**wasm, (*wasm)->name);
if (auto* err = instance.getErr()) {
if (assn.type == ModuleAssertionType::Unlinkable ||
assn.type == ModuleAssertionType::Trap) {
return Ok{};
}
return Err{err->msg};
}
if (assn.type == ModuleAssertionType::Unlinkable) {
return Err{"expected unlinkable module"};
}
if (assn.type == ModuleAssertionType::Trap) {
return Err{"expected instantiation to trap"};
}
WASM_UNREACHABLE("unexpected module assertion");
}
// spectest module is a default host-provided module defined by the spec's
// reference interpreter. It's been replaced by the `(register ...)`
// mechanism in the recent spec tests, and is kept for legacy tests only.
//
// TODO: spectest module is considered deprecated by the spec. Remove when
// is actually removed from the spec test.
void buildSpectestModule() {
auto spectest = std::make_shared<Module>();
spectest->features = FeatureSet::All;
Builder builder(*spectest);
spectest->addGlobal(builder.makeGlobal(Name::fromInt(0),
Type::i32,
builder.makeConst<uint32_t>(666),
Builder::Immutable));
spectest->addGlobal(builder.makeGlobal(Name::fromInt(1),
Type::i64,
builder.makeConst<uint64_t>(666),
Builder::Immutable));
spectest->addGlobal(builder.makeGlobal(Name::fromInt(2),
Type::f32,
builder.makeConst<float>(666.6f),
Builder::Immutable));
spectest->addGlobal(builder.makeGlobal(Name::fromInt(3),
Type::f64,
builder.makeConst<double>(666.6),
Builder::Immutable));
spectest->addExport(
builder.makeExport("global_i32", Name::fromInt(0), ExternalKind::Global));
spectest->addExport(
builder.makeExport("global_i64", Name::fromInt(1), ExternalKind::Global));
spectest->addExport(
builder.makeExport("global_f32", Name::fromInt(2), ExternalKind::Global));
spectest->addExport(
builder.makeExport("global_f64", Name::fromInt(3), ExternalKind::Global));
spectest->addTable(builder.makeTable(
Name::fromInt(0), Type(HeapType::func, Nullable), 10, 20));
spectest->addExport(
builder.makeExport("table", Name::fromInt(0), ExternalKind::Table));
spectest->addTable(builder.makeTable(
Name::fromInt(1), Type(HeapType::func, Nullable), 10, 20, Type::i64));
spectest->addExport(
builder.makeExport("table64", Name::fromInt(1), ExternalKind::Table));
Memory* memory =
spectest->addMemory(builder.makeMemory(Name::fromInt(0), 1, 2));
spectest->addExport(
builder.makeExport("memory", memory->name, ExternalKind::Memory));
// print_* functions are handled separately, no need to define here.
WASTModule mod = {/*isDefinition=*/false, spectest};
auto added = addModule(mod);
if (added.getErr()) {
WASM_UNREACHABLE("error building spectest module");
}
Register registration{/*name=*/"spectest"};
modules["spectest"] = spectest;
auto registered = addRegistration(registration);
if (registered.getErr()) {
WASM_UNREACHABLE((std::string("error registering spectest module: ") +
registered.getErr()->msg)
.c_str());
}
}
};
int main(int argc, const char* argv[]) {
Name entry;
std::set<size_t> skipped;
// Read stdin by default.
std::string infile = "-";
Options options("wasm-shell", "Execute .wast files");
options.add_positional(
"INFILE",
Options::Arguments::One,
[&](Options* o, const std::string& argument) { infile = argument; });
options.parse(argc, argv);
auto input = read_file<std::string>(infile, Flags::Text);
// Check that we can parse the script correctly with the new parser.
auto script = WATParser::parseScript(input);
if (auto* err = script.getErr()) {
std::cerr << err->msg << '\n';
exit(1);
}
Lexer lexer(input);
auto result = Shell(options).run(*script);
if (auto* err = result.getErr()) {
std::cerr << err->msg << '\n';
exit(1);
}
Colors::green(std::cerr);
Colors::bold(std::cerr);
std::cerr << "all checks passed.\n";
Colors::normal(std::cerr);
}