-
Notifications
You must be signed in to change notification settings - Fork 851
Expand file tree
/
Copy pathexecution-results.h
More file actions
770 lines (710 loc) · 26.5 KB
/
execution-results.h
File metadata and controls
770 lines (710 loc) · 26.5 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
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
/*
* Copyright 2017 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.
*/
//
// Shared execution result checking code
//
#include <deque>
#include <memory>
#include <unordered_set>
#include "ir/import-names.h"
#include "ir/import-utils.h"
#include "ir/module-utils.h"
#include "shell-interface.h"
#include "support/utilities.h"
#include "wasm-type.h"
#include "wasm.h"
namespace wasm {
namespace {
using Loggings = std::vector<Literal>;
Tag& getWasmTag() {
static Tag tag = []() {
Tag tag;
tag.module = "fuzzing-support";
tag.base = "wasmtag";
tag.name = "imported-wasm-tag";
tag.type = Signature(Type::i32, Type::none);
return tag;
}();
return tag;
}
Tag& getJsTag() {
static Tag tag = []() {
Tag tag;
tag.module = "fuzzing-support";
tag.base = "jstag";
tag.name = "imported-js-tag";
tag.type = Signature(Type(HeapType::ext, Nullable), Type::none);
return tag;
}();
return tag;
}
constexpr Index jsErrorPayload = 0xbad;
void printValue(Literal value) {
// Don't print most reference values, as e.g. funcref(N) contains an index,
// which is not guaranteed to remain identical after optimizations. Do not
// print the type in detail (as even that may change due to closed-world
// optimizations); just print a simple type like JS does, 'object' or
// 'function', but also print null for a null (so a null function does not
// get printed as object, as in JS we have typeof null == 'object').
//
// The only references we print in full are strings and i31s, which have
// simple and stable internal structures that optimizations will not alter.
//
// Non-references can be printed in full.
if (!value.type.isRef()) {
std::cout << value;
return;
}
value = value.unwrap();
auto heapType = value.type.getHeapType();
if (heapType.isMaybeShared(HeapType::ext) &&
value.getExternPayload() == jsErrorPayload) {
std::cout << "jserror";
return;
}
if (heapType.isString() || heapType.isMaybeShared(HeapType::ext) ||
heapType.isMaybeShared(HeapType::i31)) {
std::cout << value;
} else if (value.isNull()) {
std::cout << "null";
} else if (heapType.isFunction()) {
std::cout << "function";
} else {
// Print 'object' and its JS-visible prototype, which may be null.
std::cout << "object(";
printValue(value.getJSPrototype());
std::cout << ')';
}
}
} // namespace
// Logs every relevant import call parameter.
struct LoggingExternalInterface : public ShellExternalInterface {
private:
Loggings& loggings;
struct State {
// Legalization for JS emits get/setTempRet0 calls ("temp ret 0" means a
// temporary return value of 32 bits; "0" is the only important value for
// 64-bit legalization, which needs one such 32-bit chunk in addition to
// the normal return value which can handle 32 bits).
uint32_t tempRet0 = 0;
} state;
// The name of the table exported by the name 'table.' Imports access it.
Name exportedTable;
Module& wasm;
// The imported fuzzing tag for wasm.
const Tag& wasmTag;
// The imported tag for js exceptions.
const Tag& jsTag;
// The ModuleRunner and this ExternalInterface end up needing links both ways,
// so we cannot init this in the constructor.
ModuleRunner* instance = nullptr;
public:
LoggingExternalInterface(
Loggings& loggings,
Module& wasm,
std::map<Name, std::shared_ptr<ModuleRunner>> linkedInstances_ = {})
: ShellExternalInterface(linkedInstances_), loggings(loggings), wasm(wasm),
wasmTag(getWasmTag()), jsTag(getJsTag()) {
for (auto& exp : wasm.exports) {
if (exp->kind == ExternalKind::Table && exp->name == "table") {
exportedTable = *exp->getInternalName();
break;
}
}
}
Literal getImportedFunction(Function* import) override {
if (linkedInstances.count(import->module)) {
return getImportInstance(import)->getExportedFunction(import->base);
}
auto f = [import, this](const Literals& arguments) -> Flow {
if (import->module == "fuzzing-support") {
if (import->base.startsWith("log")) {
// This is a logging function like log-i32 or log-f64.
std::cout << "[LoggingExternalInterface ";
if (import->base == "log-branch") {
// Report this as a special logging, so we can differentiate it
// from the others in the fuzzer.
std::cout << "log-branch";
} else {
// All others are just reported as loggings.
std::cout << "logging";
}
loggings.push_back(Literal()); // buffer with a None between calls
for (auto argument : arguments) {
if (argument.type == Type::i64) {
// To avoid JS legalization changing logging results, treat a
// logging of an i64 as two i32s (which is what legalization
// would turn us into).
auto low = Literal(int32_t(argument.getInteger()));
auto high =
Literal(int32_t(argument.getInteger() >> int32_t(32)));
std::cout << ' ' << low;
loggings.push_back(low);
std::cout << ' ' << high;
loggings.push_back(high);
} else {
std::cout << ' ';
printValue(argument);
loggings.push_back(argument);
}
}
std::cout << "]\n";
return {};
} else if (import->base == "throw") {
// Throw something, depending on the value of the argument. 0 means
// we should throw a JS exception, and any other value means we
// should throw a wasm exception (with that value as the payload).
if (arguments[0].geti32() == 0) {
throwJSException();
} else {
auto payload = std::make_shared<ExnData>(&wasmTag, arguments);
throwException(WasmException{Literal(payload)});
}
} else if (import->base == "table-get") {
// Check for errors here, duplicating tableLoad(), because that will
// trap, and we just want to throw an exception (the same as JS
// would).
if (!exportedTable) {
throwJSException();
}
auto index = arguments[0].getUnsigned();
auto* table = instance->allTables[exportedTable];
if (index >= table->size()) {
throwJSException();
}
return table->get(index);
} else if (import->base == "table-set") {
if (!exportedTable) {
throwJSException();
}
auto index = arguments[0].getUnsigned();
auto* table = instance->allTables[exportedTable];
if (index >= table->size()) {
throwJSException();
}
table->set(index, arguments[1]);
return {};
} else if (import->base == "call-export") {
callExportAsJS(arguments[0].geti32());
// The second argument determines if we should catch and rethrow
// exceptions. There is no observable difference in those two modes
// in the binaryen interpreter, so we don't need to do anything.
// Return nothing. If we wanted to return a value we'd need to have
// multiple such functions, one for each signature.
return {};
} else if (import->base == "call-export-catch") {
try {
callExportAsJS(arguments[0].geti32());
return {Literal(int32_t(0))};
} catch (const WasmException& e) {
return {Literal(int32_t(1))};
}
} else if (import->base == "call-ref") {
// Similar to call-export*, but with a ref.
callRefAsJS(arguments[0]);
return {};
} else if (import->base == "call-ref-catch") {
try {
callRefAsJS(arguments[0]);
return {Literal(int32_t(0))};
} catch (const WasmException& e) {
return {Literal(int32_t(1))};
}
} else if (import->base == "sleep") {
// Do not actually sleep, just return the id.
return {arguments[1]};
} else {
WASM_UNREACHABLE("unknown fuzzer import");
}
} else if (import->module == ENV) {
if (import->base == "log_execution") {
std::cout << "[LoggingExternalInterface log-execution";
for (auto argument : arguments) {
std::cout << ' ' << argument;
}
std::cout << "]\n";
return {};
} else if (import->base == "setTempRet0") {
state.tempRet0 = arguments[0].geti32();
return {};
} else if (import->base == "getTempRet0") {
return {Literal(state.tempRet0)};
}
}
// Anything else, we ignore.
std::cerr << "[LoggingExternalInterface ignoring an unknown import "
<< import->module << " . " << import->base << '\n';
return {};
};
// Use a null instance because this is a host function.
return Literal(std::make_shared<FuncData>(import->name, nullptr, f),
import->type);
}
void throwJSException() {
// JS exceptions contain an externref.
Literals arguments = {Literal::makeExtern(jsErrorPayload, Unshared)};
auto payload = std::make_shared<ExnData>(&jsTag, arguments);
throwException(WasmException{Literal(payload)});
}
Literals callExportAsJS(Index index) {
if (index >= wasm.exports.size()) {
// No export.
throwJSException();
}
auto& exp = wasm.exports[index];
if (exp->kind != ExternalKind::Function) {
// No callable export.
throwJSException();
}
auto funcName = *exp->getInternalName();
return callFunctionAsJS(
[&](Literals arguments) {
return instance->callFunction(funcName, arguments);
},
wasm.getFunction(funcName)->type.getHeapType());
}
Literals callRefAsJS(Literal ref) {
if (!ref.isFunction()) {
// Not a callable ref.
throwJSException();
}
return callFunctionAsJS(
[&](Literals arguments) { return ref.getFuncData()->doCall(arguments); },
ref.type.getHeapType());
}
// Call a function in a "JS-ey" manner, adding arguments as needed, and
// throwing if necessary, the same way JS does. We are given a method that
// does the actual call, and the type we are calling.
Literals callFunctionAsJS(std::function<Flow(Literals)> doCall,
HeapType type) {
auto sig = type.getSignature();
// Send default values as arguments, or error if we need anything else.
Literals arguments;
for (const auto& param : sig.params) {
// An i64 param can work from JS, but fuzz_shell provides 0, which errors
// on attempts to convert it to BigInt. Also trap on v128 etc.
if (param == Type::i64 || trapsOnJSBoundary(param)) {
throwJSException();
}
if (!param.isDefaultable()) {
throwJSException();
}
arguments.push_back(Literal::makeZero(param));
}
// Error on illegal results. Note that this happens, as per JS semantics,
// *before* the call.
for (const auto& result : sig.results) {
// An i64 result is fine: a BigInt will be provided. But v128 and
// [null]exnref still error.
if (trapsOnJSBoundary(result)) {
throwJSException();
}
}
// Call the function.
auto flow = doCall(arguments);
// Suspending through JS is not valid. This traps - it does not throw a
// catchable JS exception.
if (flow.suspendTag) {
trap("suspend through JS");
}
return flow.values;
}
bool trapsOnJSBoundary(Type type) {
if (type == Type::v128) {
return true;
}
if (type.isRef()) {
// Exnref and [null][exn|cont]ref trap.
HeapType top = type.getHeapType().getTop();
if (top.isMaybeShared(HeapType::exn) ||
top.isMaybeShared(HeapType::cont)) {
return true;
}
}
return false;
}
void setModuleRunner(ModuleRunner* instance_) { instance = instance_; }
};
class FuzzerImportResolver
: public LinkedInstancesImportResolver<ModuleRunner> {
using LinkedInstancesImportResolver::LinkedInstancesImportResolver;
// We can synthesize imported externref globals. Use a deque for stable
// addresses.
mutable std::deque<Literals> synthesizedGlobals;
Tag* getTagOrNull(ImportNames name, const Signature& type) const override {
if (name.module == "fuzzing-support") {
if (name.name == "wasmtag") {
return &wasmTag;
}
if (name.name == "jstag") {
return &jsTag;
}
}
return LinkedInstancesImportResolver::getTagOrNull(name, type);
}
virtual Literals*
getGlobalOrNull(ImportNames name, Type type, bool mut) const override {
// First look for globals available from linked instances.
if (auto* global =
LinkedInstancesImportResolver<ModuleRunner>::getGlobalOrNull(
name, type, mut)) {
return global;
}
// This is not a known global, but the fuzzer supports synthesizing
// immutable externref global imports.
// TODO: Figure out how to share this logic with TranslateToFuzzReader.
// TODO: Support other types.
if (mut || !type.isRef() || type.getHeapType() != HeapType::ext) {
return nullptr;
}
// Optimizations may reorder or remove imports, so we need a distinct
// payload that is independent of the import order. Just compute a simple
// payload integer from the import names. This must be kept in sync with
// fuzz_shell.js.
Index payload = 0;
for (auto name : {name.module, name.name}) {
for (auto c : name.str) {
payload = (payload + static_cast<Index>(c)) % 251;
}
}
synthesizedGlobals.emplace_back(
Literals{Literal::makeExtern(payload, Unshared)});
return &synthesizedGlobals.back();
}
private:
Tag& wasmTag = getWasmTag();
Tag& jsTag = getJsTag();
};
// gets execution results from a wasm module. this is useful for fuzzing
//
// we can only get results when there are no imports. we then call each method
// that has a result, with some values
struct ExecutionResults {
struct Trap {};
struct Exception {};
using FunctionResult = std::variant<Literals, Trap, Exception>;
std::map<Name, FunctionResult> results;
Loggings loggings;
// If set, we should ignore this and not compare it to anything.
bool ignore = false;
std::unordered_set<HeapType> publicTypes;
// Execute a module and collect the results. Optionally, provide a second
// module to link with it (like fuzz_shell's second module).
void collect(Module& wasm, Module* second = nullptr) {
auto publicVec = ModuleUtils::getPublicHeapTypes(wasm);
publicTypes.insert(publicVec.begin(), publicVec.end());
if (second) {
auto secondPublicVec = ModuleUtils::getPublicHeapTypes(*second);
publicTypes.insert(secondPublicVec.begin(), secondPublicVec.end());
}
try {
// Instantiate the first module.
LoggingExternalInterface interface(loggings, wasm);
// `linkedInstances` is empty at this point and the below constructors
// make copies.
std::map<Name, std::shared_ptr<ModuleRunner>> linkedInstances;
auto instance = std::make_shared<ModuleRunner>(
wasm,
&interface,
linkedInstances,
std::make_shared<FuzzerImportResolver>(linkedInstances));
instantiate(*instance, interface);
// Instantiate the second, if there is one (we instantiate both before
// running anything, so that we match the behavior of fuzz_shell.js).
std::unique_ptr<LoggingExternalInterface> secondInterface;
std::shared_ptr<ModuleRunner> secondInstance;
if (second) {
// Link and instantiate the second module.
linkedInstances["primary"] = instance;
secondInterface = std::make_unique<LoggingExternalInterface>(
loggings, *second, linkedInstances);
secondInstance = std::make_shared<ModuleRunner>(
*second, secondInterface.get(), linkedInstances);
instantiate(*secondInstance, *secondInterface);
}
// Run.
callExports(wasm, *instance);
if (second) {
std::cout << "[fuzz-exec] running second module\n";
callExports(*second, *secondInstance);
}
} catch (const TrapException&) {
// May throw in instance creation (init of offsets).
} catch (const HostLimitException&) {
// May throw in instance creation (e.g. array.new of huge size).
// This should be ignored and not compared with, as optimizations can
// change whether a host limit is reached.
ignore = true;
}
}
void instantiate(ModuleRunner& instance,
LoggingExternalInterface& interface) {
// This is not an optimization: we want to execute anything, even relaxed
// SIMD instructions.
instance.setRelaxedBehavior(ModuleRunner::RelaxedBehavior::Execute);
instance.instantiate();
interface.setModuleRunner(&instance);
}
void callExports(Module& wasm, ModuleRunner& instance) {
// execute all exported methods (that are therefore preserved through
// opts)
for (auto& exp : wasm.exports) {
if (exp->kind == ExternalKind::Function) {
std::cout << "[fuzz-exec] export " << exp->name << "\n";
auto* func = wasm.getFunction(*exp->getInternalName());
FunctionResult ret = run(func, wasm, instance);
results[exp->name] = ret;
if (auto* values = std::get_if<Literals>(&ret)) {
// ignore the result if we hit an unreachable and returned no value
if (values->size() > 0) {
std::cout << "[fuzz-exec] note result: " << exp->name << " => ";
for (auto value : *values) {
printValue(value);
std::cout << '\n';
}
}
}
} else if (exp->kind == ExternalKind::Global) {
// Log the global's value.
std::cout << "[fuzz-exec] export " << exp->name << "\n";
Literals* value = instance.getExportedGlobalOrNull(exp->name);
assert(value);
assert(value->size() == 1);
std::cout << "[LoggingExternalInterface logging ";
printValue((*value)[0]);
std::cout << "]\n";
}
// Ignore other exports for now. TODO
}
}
// get current results and check them against previous ones
void check(Module& wasm) {
ExecutionResults optimizedResults;
optimizedResults.collect(wasm);
if (optimizedResults != *this) {
std::cout << "[fuzz-exec] optimization passes changed results\n";
exit(1);
}
}
bool areEqual(Literal a, Literal b) {
// Values may be recursive, so naively comparing their structures might
// recurse forever. Instead we need to check coinductive equality, which
// means we assume two values are equivalent until proven otherwise and do
// not recursively compare pairs of values we have already seen.
std::unordered_set<std::pair<GCData*, GCData*>> compared;
return areEqualImpl(a, b, compared);
}
bool areEqualImpl(Literal a,
Literal b,
std::unordered_set<std::pair<GCData*, GCData*>>& compared) {
// Only compare some references. In general the optimizer may change
// identities and structures of functions, types, and GC values in ways that
// are not externally observable. We must therefore limit ourselves to
// comparing information that _is_ externally observable. This includes
// fields that are part of public types as well as configured JS prototypes.
if (!a.type.isRef() || !b.type.isRef()) {
return a == b;
}
// The environment always sees externalized references and is able to
// observe the difference between external references and externalized
// internal references. Make sure this is accounted for below by unwrapping
// the references.
a = a.unwrap();
b = b.unwrap();
auto htA = a.type.getHeapType();
auto htB = b.type.getHeapType();
// What type hierarchy a heap type is in is generally observable.
if (htA.getTop() != htB.getTop()) {
return false;
}
// Null values are observable.
if (htA.isBottom() || htB.isBottom()) {
return a == b;
}
// String values are observable.
if (htA.isString() || htB.isString()) {
return a == b;
}
// i31 values are observable.
if (htA.isMaybeShared(HeapType::i31) || htB.isMaybeShared(HeapType::i31)) {
return a == b;
}
// External references are observable. (These cannot be externalized
// internal references because they've already been unwrapped.)
if (htA.isMaybeShared(HeapType::ext) || htB.isMaybeShared(HeapType::ext)) {
return a == b;
}
// Configured prototypes are observable. Even if they are also opaque Wasm
// references, their having different pointer identities is observable.
// However, we have no way of comparing pointer identities across
// executions, so just recursively look for externally observable
// differences in the prototypes.
if (!areEqualImpl(a.getJSPrototype(), b.getJSPrototype(), compared)) {
return false;
}
// Check for public struct or array content.
auto publicType = getClosestPublicAncestor(htA);
if (publicType != getClosestPublicAncestor(htB)) {
// Since public types are externally observable, having different public
// types is an observable difference.
return false;
}
if (publicType && publicType->isData()) {
auto* dataA = a.getGCData().get();
auto* dataB = b.getGCData().get();
if (dataA == dataB) {
return true;
}
if (!compared.insert({dataA, dataB}).second) {
// We are already comparing these values. Assume they are equivalent
// (until possibly proven otherwise later) and do not recurse further.
return true;
}
compared.insert({dataA, dataB});
if (publicType->isStruct()) {
auto& fields = publicType->getStruct().fields;
auto& valuesA = dataA->values;
auto& valuesB = dataB->values;
for (Index i = 0; i < fields.size(); i++) {
if (!areEqualImpl(valuesA[i], valuesB[i], compared)) {
return false;
}
}
} else if (publicType->isArray()) {
auto& valuesA = dataA->values;
auto& valuesB = dataB->values;
if (valuesA.size() != valuesB.size()) {
return false;
}
for (Index i = 0; i < valuesA.size(); i++) {
if (!areEqualImpl(valuesA[i], valuesB[i], compared)) {
return false;
}
}
}
}
// Other differences are not observable, so conservatively consider the
// values equal.
return true;
}
std::optional<HeapType> getClosestPublicAncestor(HeapType ht) {
while (true) {
if (publicTypes.count(ht)) {
return ht;
}
if (auto super = ht.getDeclaredSuperType()) {
ht = *super;
} else {
return std::nullopt;
}
}
}
bool areEqual(Literals a, Literals b) {
std::unordered_set<std::pair<GCData*, GCData*>> compared;
return areEqualImpl(a, b, compared);
}
bool areEqualImpl(Literals a,
Literals b,
std::unordered_set<std::pair<GCData*, GCData*>>& compared) {
if (a.size() != b.size()) {
std::cout << "literal counts not identical! " << a << " != " << b << '\n';
return false;
}
for (Index i = 0; i < a.size(); i++) {
if (!areEqualImpl(a[i], b[i], compared)) {
std::cout << "values not identical! " << a[i] << " != " << b[i] << '\n';
return false;
}
}
return true;
}
bool operator==(ExecutionResults& other) {
if (ignore || other.ignore) {
std::cout << "ignoring comparison of ExecutionResults!\n";
return true;
}
for (auto& [name, _] : other.results) {
if (results.find(name) == results.end()) {
std::cout << "[fuzz-exec] missing " << name << '\n';
return false;
}
std::cout << "[fuzz-exec] comparing " << name << '\n';
if (results[name].index() != other.results[name].index()) {
return false;
}
auto* values = std::get_if<Literals>(&results[name]);
auto* otherValues = std::get_if<Literals>(&other.results[name]);
if (values && otherValues && !areEqual(*values, *otherValues)) {
return false;
}
}
if (loggings.size() != other.loggings.size()) {
std::cout << "logging counts not identical!\n";
return false;
}
for (Index i = 0; i < loggings.size(); i++) {
if (!areEqual(loggings[i], other.loggings[i])) {
return false;
}
}
return true;
}
bool operator!=(ExecutionResults& other) { return !((*this) == other); }
FunctionResult run(Function* func, Module& wasm, ModuleRunner& instance) {
// Clear the continuation state after each run of an export.
struct CleanUp {
ModuleRunner& instance;
CleanUp(ModuleRunner& instance) : instance(instance) {}
~CleanUp() { instance.clearContinuationStore(); }
} cleanUp(instance);
try {
// call the method
Literals arguments;
for (const auto& param : func->getParams()) {
// zeros in arguments TODO: more?
if (!param.isDefaultable()) {
std::cout << "[trap fuzzer can only send defaultable parameters to "
"exports]\n";
return Trap{};
}
arguments.push_back(Literal::makeZero(param));
}
auto flow = instance.callFunction(func->name, arguments);
if (flow.suspendTag) {
std::cout << "[exception thrown: unhandled suspend]" << std::endl;
return Exception{};
}
return flow.values;
} catch (const TrapException&) {
return Trap{};
} catch (const WasmException& e) {
auto& exn = *e.exn.getExnData();
std::cout << "[exception thrown: " << exn.tag->name;
for (auto val : exn.payload) {
std::cout << ' ';
printValue(val);
}
std::cout << "]" << std::endl;
return Exception{};
} catch (const HostLimitException&) {
// This should be ignored and not compared with, as optimizations can
// change whether a host limit is reached.
ignore = true;
return {};
}
}
};
} // namespace wasm