forked from WebAssembly/binaryen
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfuzzing.cpp
More file actions
4229 lines (4040 loc) · 147 KB
/
fuzzing.cpp
File metadata and controls
4229 lines (4040 loc) · 147 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
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright 2021 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 "tools/fuzzing.h"
#include "ir/gc-type-utils.h"
#include "ir/iteration.h"
#include "ir/local-structural-dominance.h"
#include "ir/module-utils.h"
#include "ir/subtypes.h"
#include "ir/type-updating.h"
#include "support/string.h"
#include "tools/fuzzing/heap-types.h"
#include "tools/fuzzing/parameters.h"
namespace wasm {
namespace {
// Weighting for the core make* methods. Some nodes are important enough that
// we should do them quite often.
} // anonymous namespace
TranslateToFuzzReader::TranslateToFuzzReader(Module& wasm,
std::vector<char>&& input)
: wasm(wasm), builder(wasm), random(std::move(input), wasm.features) {
// Half the time add no unreachable code so that we'll execute the most code
// as possible with no early exits.
allowAddingUnreachableCode = oneIn(2);
// - funcref cannot be logged because referenced functions can be inlined or
// removed during optimization
// - there's no point in logging anyref because it is opaque
// - don't bother logging tuples
loggableTypes = {Type::i32, Type::i64, Type::f32, Type::f64};
if (wasm.features.hasSIMD()) {
loggableTypes.push_back(Type::v128);
}
}
TranslateToFuzzReader::TranslateToFuzzReader(Module& wasm,
std::string& filename)
: TranslateToFuzzReader(
wasm, read_file<std::vector<char>>(filename, Flags::Binary)) {}
void TranslateToFuzzReader::pickPasses(OptimizationOptions& options) {
while (options.passes.size() < 20 && !random.finished() && !oneIn(3)) {
switch (upTo(32)) {
case 0:
case 1:
case 2:
case 3:
case 4: {
options.passes.push_back("O");
options.passOptions.optimizeLevel = upTo(4);
options.passOptions.shrinkLevel = upTo(4);
break;
}
case 5:
options.passes.push_back("coalesce-locals");
break;
case 6:
options.passes.push_back("code-pushing");
break;
case 7:
options.passes.push_back("code-folding");
break;
case 8:
options.passes.push_back("dce");
break;
case 9:
options.passes.push_back("duplicate-function-elimination");
break;
case 10:
options.passes.push_back("flatten");
break;
case 11:
options.passes.push_back("inlining");
break;
case 12:
options.passes.push_back("inlining-optimizing");
break;
case 13:
options.passes.push_back("local-cse");
break;
case 14:
options.passes.push_back("memory-packing");
break;
case 15:
options.passes.push_back("merge-blocks");
break;
case 16:
options.passes.push_back("optimize-instructions");
break;
case 17:
options.passes.push_back("pick-load-signs");
break;
case 18:
options.passes.push_back("precompute");
break;
case 19:
options.passes.push_back("precompute-propagate");
break;
case 20:
options.passes.push_back("remove-unused-brs");
break;
case 21:
options.passes.push_back("remove-unused-module-elements");
break;
case 22:
options.passes.push_back("remove-unused-names");
break;
case 23:
options.passes.push_back("reorder-functions");
break;
case 24:
options.passes.push_back("reorder-locals");
break;
case 25: {
options.passes.push_back("flatten");
options.passes.push_back("rereloop");
break;
}
case 26:
options.passes.push_back("simplify-locals");
break;
case 27:
options.passes.push_back("simplify-locals-notee");
break;
case 28:
options.passes.push_back("simplify-locals-nostructure");
break;
case 29:
options.passes.push_back("simplify-locals-notee-nostructure");
break;
case 30:
options.passes.push_back("ssa");
break;
case 31:
options.passes.push_back("vacuum");
break;
default:
WASM_UNREACHABLE("unexpected value");
}
}
if (oneIn(2)) {
options.passOptions.optimizeLevel = upTo(4);
}
if (oneIn(2)) {
options.passOptions.shrinkLevel = upTo(4);
}
std::cout << "opt level: " << options.passOptions.optimizeLevel << '\n';
std::cout << "shrink level: " << options.passOptions.shrinkLevel << '\n';
}
void TranslateToFuzzReader::build() {
if (HANG_LIMIT > 0) {
prepareHangLimitSupport();
}
if (allowMemory) {
setupMemory();
}
setupHeapTypes();
setupTables();
setupGlobals();
if (wasm.features.hasExceptionHandling()) {
setupTags();
}
modifyInitialFunctions();
addImportLoggingSupport();
// keep adding functions until we run out of input
while (!random.finished()) {
auto* func = addFunction();
addInvocations(func);
}
if (HANG_LIMIT > 0) {
addHangLimitSupport();
}
if (allowMemory) {
finalizeMemory();
addHashMemorySupport();
}
finalizeTable();
}
void TranslateToFuzzReader::setupMemory() {
// Add memory itself
MemoryUtils::ensureExists(&wasm);
auto& memory = wasm.memories[0];
if (wasm.features.hasBulkMemory()) {
size_t memCovered = 0;
// need at least one segment for memory.inits
size_t numSegments = upTo(8) + 1;
for (size_t i = 0; i < numSegments; i++) {
auto segment = builder.makeDataSegment();
segment->setName(Names::getValidDataSegmentName(wasm, Name::fromInt(i)),
false);
segment->isPassive = bool(upTo(2));
size_t segSize = upTo(USABLE_MEMORY * 2);
segment->data.resize(segSize);
for (size_t j = 0; j < segSize; j++) {
segment->data[j] = upTo(512);
}
if (!segment->isPassive) {
segment->offset = builder.makeConst(int32_t(memCovered));
memCovered += segSize;
segment->memory = memory->name;
}
wasm.addDataSegment(std::move(segment));
}
} else {
// init some data
auto segment = builder.makeDataSegment();
segment->memory = memory->name;
segment->offset = builder.makeConst(int32_t(0));
segment->setName(Name::fromInt(0), false);
wasm.dataSegments.push_back(std::move(segment));
auto num = upTo(USABLE_MEMORY * 2);
for (size_t i = 0; i < num; i++) {
auto value = upTo(512);
wasm.dataSegments[0]->data.push_back(value >= 256 ? 0 : (value & 0xff));
}
}
}
void TranslateToFuzzReader::setupHeapTypes() {
// Start with any existing heap types in the module, which may exist in any
// initial content we began with.
auto possibleHeapTypes = ModuleUtils::collectHeapTypes(wasm);
// Filter away uninhabitable heap types, that is, heap types that we cannot
// construct, like a type with a non-nullable reference to itself.
interestingHeapTypes = HeapTypeGenerator::getInhabitable(possibleHeapTypes);
// For GC, also generate random types.
if (wasm.features.hasGC()) {
auto generator =
HeapTypeGenerator::create(random, wasm.features, upTo(MAX_NEW_GC_TYPES));
auto result = generator.builder.build();
if (auto* err = result.getError()) {
Fatal() << "Failed to build heap types: " << err->reason << " at index "
<< err->index;
}
// Make the new types inhabitable. This process modifies existing types, so
// it leaves more available compared to HeapTypeGenerator::getInhabitable.
// We run that before on existing content, which may have instructions that
// use the types, as editing them is not trivial, and for new types here we
// are free to modify them so we keep as many as we can.
auto inhabitable = HeapTypeGenerator::makeInhabitable(*result);
for (auto type : inhabitable) {
// Trivial types are already handled specifically in e.g.
// getSingleConcreteType(), and we avoid adding them here as then we'd
// need to add code to avoid uninhabitable combinations of them (like a
// non-nullable bottom heap type).
if (!type.isBottom() && !type.isBasic()) {
interestingHeapTypes.push_back(type);
if (oneIn(2)) {
// Add a name for this type.
wasm.typeNames[type].name =
"generated_type$" + std::to_string(interestingHeapTypes.size());
}
}
}
}
// Compute subtypes ahead of time. It is more efficient to do this all at once
// now, rather than lazily later.
SubTypes subTypes(interestingHeapTypes);
for (auto type : interestingHeapTypes) {
for (auto subType : subTypes.getImmediateSubTypes(type)) {
interestingHeapSubTypes[type].push_back(subType);
}
// Basic types must be handled directly, since subTypes doesn't look at
// those.
if (type.isStruct()) {
interestingHeapSubTypes[HeapType::struct_].push_back(type);
interestingHeapSubTypes[HeapType::eq].push_back(type);
interestingHeapSubTypes[HeapType::any].push_back(type);
// Note the mutable fields.
auto& fields = type.getStruct().fields;
for (Index i = 0; i < fields.size(); i++) {
if (fields[i].mutable_) {
mutableStructFields.push_back(StructField{type, i});
}
}
} else if (type.isArray()) {
interestingHeapSubTypes[HeapType::array].push_back(type);
interestingHeapSubTypes[HeapType::eq].push_back(type);
interestingHeapSubTypes[HeapType::any].push_back(type);
if (type.getArray().element.mutable_) {
mutableArrays.push_back(type);
}
} else if (type.isSignature()) {
interestingHeapSubTypes[HeapType::func].push_back(type);
}
}
// Compute struct and array fields.
for (auto type : interestingHeapTypes) {
if (type.isStruct()) {
auto& fields = type.getStruct().fields;
for (Index i = 0; i < fields.size(); i++) {
typeStructFields[fields[i].type].push_back(StructField{type, i});
}
} else if (type.isArray()) {
typeArrays[type.getArray().element.type].push_back(type);
}
}
}
// TODO(reference-types): allow the fuzzer to create multiple tables
void TranslateToFuzzReader::setupTables() {
// Ensure a funcref element segment and table exist. Segments with more
// specific function types may have a smaller chance of getting functions.
Table* table = nullptr;
Type funcref = Type(HeapType::func, Nullable);
auto iter = std::find_if(wasm.tables.begin(),
wasm.tables.end(),
[&](auto& table) { return table->type == funcref; });
if (iter != wasm.tables.end()) {
table = iter->get();
} else {
auto tablePtr = builder.makeTable(
Names::getValidTableName(wasm, "fuzzing_table"), funcref, 0, 0);
tablePtr->hasExplicitName = true;
table = wasm.addTable(std::move(tablePtr));
}
funcrefTableName = table->name;
bool hasFuncrefElemSegment =
std::any_of(wasm.elementSegments.begin(),
wasm.elementSegments.end(),
[&](auto& segment) {
return segment->table.is() && segment->type == funcref;
});
if (!hasFuncrefElemSegment) {
// TODO: use a random table
auto segment = std::make_unique<ElementSegment>(
table->name, builder.makeConst(int32_t(0)));
segment->setName(Names::getValidElementSegmentName(wasm, "elem$"), false);
wasm.addElementSegment(std::move(segment));
}
}
void TranslateToFuzzReader::setupGlobals() {
// If there were initial wasm contents, there may be imported globals. That
// would be a problem in the fuzzer harness as we'd error if we do not
// provide them (and provide the proper type, etc.).
// Avoid that, so that all the standard fuzzing infrastructure can always
// run the wasm.
for (auto& global : wasm.globals) {
if (global->imported()) {
// Remove import info from imported globals, and give them a simple
// initializer.
global->module = global->base = Name();
global->init = makeConst(global->type);
} else {
// If the initialization referred to an imported global, it no longer can
// point to the same global after we make it a non-imported global unless
// GC is enabled, since before GC, Wasm only made imported globals
// available in constant expressions.
if (!wasm.features.hasGC() &&
!FindAll<GlobalGet>(global->init).list.empty()) {
global->init = makeConst(global->type);
}
}
}
// Randomly assign some globals from initial content to be ignored for the
// fuzzer to use. Such globals will only be used from initial content. This is
// important to preserve some real-world patterns, like the "once" pattern in
// which a global is used in one function only. (If we randomly emitted gets
// and sets of such globals, we'd with very high probability end up breaking
// that pattern, and not fuzzing it at all.)
//
// Pick a percentage of initial globals to ignore later down when we decide
// which to allow uses from.
auto numInitialGlobals = wasm.globals.size();
unsigned percentIgnoredInitialGlobals = 0;
if (numInitialGlobals) {
// Only generate this random number if it will be used.
percentIgnoredInitialGlobals = upTo(100);
}
// Create new random globals.
for (size_t index = upTo(MAX_GLOBALS); index > 0; --index) {
auto type = getConcreteType();
auto* init = makeConst(type);
if (!FindAll<RefAs>(init).list.empty()) {
// When creating this initial value we ended up emitting a RefAs, which
// means we had to stop in the middle of an overly-nested struct or array,
// which we can break out of using ref.as_non_null of a nullable ref. That
// traps in normal code, which is bad enough, but it does not even
// validate in a global. Switch to something safe instead.
type = getMVPType();
init = makeConst(type);
}
auto mutability = oneIn(2) ? Builder::Mutable : Builder::Immutable;
auto global = builder.makeGlobal(
Names::getValidGlobalName(wasm, "global$"), type, init, mutability);
wasm.addGlobal(std::move(global));
}
// Set up data structures for picking globals later for get/set operations.
for (Index i = 0; i < wasm.globals.size(); i++) {
auto& global = wasm.globals[i];
// Apply the chance for initial globals to be ignored, see above.
if (i < numInitialGlobals && upTo(100) < percentIgnoredInitialGlobals) {
continue;
}
// This is a global we can use later, note it.
globalsByType[global->type].push_back(global->name);
if (global->mutable_) {
mutableGlobalsByType[global->type].push_back(global->name);
}
}
}
void TranslateToFuzzReader::setupTags() {
// As in modifyInitialFunctions(), we can't allow tag imports as it would trap
// when the fuzzing infrastructure doesn't know what to provide.
for (auto& tag : wasm.tags) {
if (tag->imported()) {
tag->module = tag->base = Name();
}
}
// Add some random tags.
Index num = upTo(3);
for (size_t i = 0; i < num; i++) {
addTag();
}
}
void TranslateToFuzzReader::addTag() {
auto tag = builder.makeTag(Names::getValidTagName(wasm, "tag$"),
Signature(getControlFlowType(), Type::none));
wasm.addTag(std::move(tag));
}
void TranslateToFuzzReader::finalizeMemory() {
auto& memory = wasm.memories[0];
for (auto& segment : wasm.dataSegments) {
Address maxOffset = segment->data.size();
if (!segment->isPassive) {
if (!wasm.features.hasGC()) {
// Using a non-imported global in a segment offset is not valid in wasm
// unless GC is enabled. This can occur due to us adding a local
// definition to what used to be an imported global in initial contents.
// To fix that, replace such invalid offsets with a constant.
for ([[maybe_unused]] auto* get :
FindAll<GlobalGet>(segment->offset).list) {
// No imported globals should remain.
assert(!wasm.getGlobal(get->name)->imported());
// TODO: It would be better to avoid segment overlap so that
// MemoryPacking can run.
segment->offset =
builder.makeConst(Literal::makeFromInt32(0, Type::i32));
}
}
if (auto* offset = segment->offset->dynCast<Const>()) {
maxOffset = maxOffset + offset->value.getInteger();
}
}
memory->initial = std::max(
memory->initial,
Address((maxOffset + Memory::kPageSize - 1) / Memory::kPageSize));
}
memory->initial = std::max(memory->initial, USABLE_MEMORY);
// Avoid an unlimited memory size, which would make fuzzing very difficult
// as different VMs will run out of system memory in different ways.
if (memory->max == Memory::kUnlimitedSize) {
memory->max = memory->initial;
}
if (memory->max <= memory->initial) {
// To allow growth to work (which a testcase may assume), try to make the
// maximum larger than the initial.
// TODO: scan the wasm for grow instructions?
memory->max =
std::min(Address(memory->initial + 1), Address(Memory::kMaxSize32));
}
// Avoid an imported memory (which the fuzz harness would need to handle).
for (auto& memory : wasm.memories) {
memory->module = memory->base = Name();
}
}
void TranslateToFuzzReader::finalizeTable() {
for (auto& table : wasm.tables) {
ModuleUtils::iterTableSegments(
wasm, table->name, [&](ElementSegment* segment) {
// If the offset contains a global that was imported (which is ok) but
// no longer is (not ok unless GC is enabled), we may need to change
// that.
if (!wasm.features.hasGC()) {
for ([[maybe_unused]] auto* get :
FindAll<GlobalGet>(segment->offset).list) {
// No imported globals should remain.
assert(!wasm.getGlobal(get->name)->imported());
// TODO: the segments must not overlap...
segment->offset =
builder.makeConst(Literal::makeFromInt32(0, Type::i32));
}
}
Address maxOffset = segment->data.size();
if (auto* offset = segment->offset->dynCast<Const>()) {
maxOffset = maxOffset + offset->value.getInteger();
}
table->initial = std::max(table->initial, maxOffset);
});
// The code above raises table->initial to a size large enough to accomodate
// all of its segments, with the intention of avoiding a trap during
// startup. However a single segment of (say) size 4GB would have a table of
// that size, which will use a lot of memory and execute very slowly, so we
// prefer in the fuzzer to trap on such a thing. To achieve that, set a
// reasonable limit for the maximum table size.
//
// This also avoids an issue that arises from table->initial being an
// Address (64 bits) but Table::kMaxSize being an Index (32 bits), as a
// result of which we need to clamp to Table::kMaxSize as well in order for
// the module to validate (but since we are clamping to a smaller value,
// there is no need).
const Address ReasonableMaxTableSize = 10000;
table->initial = std::min(table->initial, ReasonableMaxTableSize);
assert(ReasonableMaxTableSize <= Table::kMaxSize);
table->max = oneIn(2) ? Address(Table::kUnlimitedSize) : table->initial;
// Avoid an imported table (which the fuzz harness would need to handle).
table->module = table->base = Name();
}
}
void TranslateToFuzzReader::prepareHangLimitSupport() {
HANG_LIMIT_GLOBAL = Names::getValidGlobalName(wasm, "hangLimit");
}
void TranslateToFuzzReader::addHangLimitSupport() {
auto glob = builder.makeGlobal(HANG_LIMIT_GLOBAL,
Type::i32,
builder.makeConst(int32_t(HANG_LIMIT)),
Builder::Mutable);
wasm.addGlobal(std::move(glob));
}
void TranslateToFuzzReader::addImportLoggingSupport() {
for (auto type : loggableTypes) {
auto* func = new Function;
Name name = std::string("log-") + type.toString();
func->name = name;
func->module = "fuzzing-support";
func->base = name;
func->type = Signature(type, Type::none);
wasm.addFunction(func);
}
}
void TranslateToFuzzReader::addHashMemorySupport() {
// Add memory hasher helper (for the hash, see hash.h). The function looks
// like:
// function hashMemory() {
// hash = 5381;
// hash = ((hash << 5) + hash) ^ mem[0];
// hash = ((hash << 5) + hash) ^ mem[1];
// ..
// return hash;
// }
std::vector<Expression*> contents;
contents.push_back(
builder.makeLocalSet(0, builder.makeConst(uint32_t(5381))));
auto zero = Literal::makeFromInt32(0, wasm.memories[0]->indexType);
for (Index i = 0; i < USABLE_MEMORY; i++) {
contents.push_back(builder.makeLocalSet(
0,
builder.makeBinary(
XorInt32,
builder.makeBinary(
AddInt32,
builder.makeBinary(ShlInt32,
builder.makeLocalGet(0, Type::i32),
builder.makeConst(uint32_t(5))),
builder.makeLocalGet(0, Type::i32)),
builder.makeLoad(1,
false,
i,
1,
builder.makeConst(zero),
Type::i32,
wasm.memories[0]->name))));
}
contents.push_back(builder.makeLocalGet(0, Type::i32));
auto* body = builder.makeBlock(contents);
auto* hasher = wasm.addFunction(builder.makeFunction(
"hashMemory", Signature(Type::none, Type::i32), {Type::i32}, body));
wasm.addExport(
builder.makeExport(hasher->name, hasher->name, ExternalKind::Function));
// Export memory so JS fuzzing can use it
if (!wasm.getExportOrNull("memory")) {
wasm.addExport(builder.makeExport(
"memory", wasm.memories[0]->name, ExternalKind::Memory));
}
}
TranslateToFuzzReader::FunctionCreationContext::~FunctionCreationContext() {
// We must ensure non-nullable locals validate. Later down we'll run
// TypeUpdating::handleNonDefaultableLocals which will make them validate by
// turning them nullable + add ref.as_non_null to fix up types. That has the
// downside of making them trap at runtime, however, and also we lose the non-
// nullability in the type, so we prefer to do a manual fixup that avoids a
// trap, which we do by writing a non-nullable value into the local at the
// function entry.
// TODO: We could be more precise and use a LocalGraph here, at the cost of
// doing more work.
LocalStructuralDominance info(
func, parent.wasm, LocalStructuralDominance::NonNullableOnly);
for (auto index : info.nonDominatingIndices) {
// Do not always do this, but with high probability, to reduce the amount of
// traps.
if (!parent.oneIn(5)) {
auto* value = parent.makeTrivial(func->getLocalType(index));
func->body = parent.builder.makeSequence(
parent.builder.makeLocalSet(index, value), func->body);
}
}
// Then, to handle remaining cases we did not just fix up, do the general
// fixup to ensure we validate.
TypeUpdating::handleNonDefaultableLocals(func, parent.wasm);
if (HANG_LIMIT > 0) {
parent.addHangLimitChecks(func);
}
assert(breakableStack.empty());
assert(hangStack.empty());
parent.funcContext = nullptr;
}
Expression* TranslateToFuzzReader::makeHangLimitCheck() {
// If the hang limit global reaches 0 then we trap and reset it. That allows
// calls to other exports to proceed, with hang checking, after the trap halts
// the currently called export.
return builder.makeSequence(
builder.makeIf(
builder.makeUnary(UnaryOp::EqZInt32,
builder.makeGlobalGet(HANG_LIMIT_GLOBAL, Type::i32)),
builder.makeSequence(
builder.makeGlobalSet(HANG_LIMIT_GLOBAL,
builder.makeConst(int32_t(HANG_LIMIT))),
builder.makeUnreachable())),
builder.makeGlobalSet(
HANG_LIMIT_GLOBAL,
builder.makeBinary(BinaryOp::SubInt32,
builder.makeGlobalGet(HANG_LIMIT_GLOBAL, Type::i32),
builder.makeConst(int32_t(1)))));
}
Expression* TranslateToFuzzReader::makeLogging() {
auto type = getLoggableType();
return builder.makeCall(
std::string("log-") + type.toString(), {make(type)}, Type::none);
}
Expression* TranslateToFuzzReader::makeMemoryHashLogging() {
auto* hash = builder.makeCall(std::string("hashMemory"), {}, Type::i32);
return builder.makeCall(std::string("log-i32"), {hash}, Type::none);
}
// TODO: return std::unique_ptr<Function>
Function* TranslateToFuzzReader::addFunction() {
LOGGING_PERCENT = upToSquared(100);
auto* func = new Function;
func->name = Names::getValidFunctionName(wasm, "func");
FunctionCreationContext context(*this, func);
assert(funcContext->typeLocals.empty());
Index numParams = upToSquared(MAX_PARAMS);
std::vector<Type> params;
params.reserve(numParams);
for (Index i = 0; i < numParams; i++) {
auto type = getSingleConcreteType();
funcContext->typeLocals[type].push_back(params.size());
params.push_back(type);
}
auto paramType = Type(params);
auto resultType = getControlFlowType();
func->type = Signature(paramType, resultType);
Index numVars = upToSquared(MAX_VARS);
for (Index i = 0; i < numVars; i++) {
auto type = getConcreteType();
funcContext->typeLocals[type].push_back(params.size() + func->vars.size());
func->vars.push_back(type);
}
// with small chance, make the body unreachable
auto bodyType = func->getResults();
if (oneIn(10)) {
bodyType = Type::unreachable;
}
// with reasonable chance make the body a block
if (oneIn(2)) {
func->body = makeBlock(bodyType);
} else {
func->body = make(bodyType);
}
// Our OOB checks are already in the code, and if we recombine/mutate we
// may end up breaking them. TODO: do them after the fact, like with the
// hang limit checks.
if (allowOOB) {
// Recombinations create duplicate code patterns.
recombine(func);
// Mutations add random small changes, which can subtly break duplicate
// code patterns.
mutate(func);
// TODO: liveness operations on gets, with some prob alter a get to one
// with more possible sets.
// Recombination, mutation, etc. can break validation; fix things up
// after.
fixAfterChanges(func);
}
// Add hang limit checks after all other operations on the function body.
wasm.addFunction(func);
// Export some functions, but not all (to allow inlining etc.). Try to export
// at least one, though, to keep each testcase interesting. Only functions
// with valid params and returns can be exported because the trap fuzzer
// depends on that (TODO: fix this).
auto validExportType = [](Type t) {
if (!t.isRef()) {
return true;
}
auto heapType = t.getHeapType();
return heapType == HeapType::ext || heapType == HeapType::func ||
heapType == HeapType::string;
};
bool validExportParams =
std::all_of(paramType.begin(), paramType.end(), [&](Type t) {
return validExportType(t) && t.isDefaultable();
});
// Note: spec discussions around JS API integration are still ongoing, and it
// is not clear if we should allow nondefaultable types in exports or not
// (in imports, we cannot allow them in the fuzzer anyhow, since it can't
// construct such values in JS to send over to the wasm from the fuzzer
// harness).
bool validExportResults =
std::all_of(resultType.begin(), resultType.end(), validExportType);
if (validExportParams && validExportResults &&
(numAddedFunctions == 0 || oneIn(2)) &&
!wasm.getExportOrNull(func->name)) {
auto* export_ = new Export;
export_->name = func->name;
export_->value = func->name;
export_->kind = ExternalKind::Function;
wasm.addExport(export_);
}
// add some to an elem segment
while (oneIn(3) && !random.finished()) {
auto type = Type(func->type, NonNullable);
std::vector<ElementSegment*> compatibleSegments;
ModuleUtils::iterActiveElementSegments(wasm, [&](ElementSegment* segment) {
if (Type::isSubType(type, segment->type)) {
compatibleSegments.push_back(segment);
}
});
auto& randomElem = compatibleSegments[upTo(compatibleSegments.size())];
randomElem->data.push_back(builder.makeRefFunc(func->name, func->type));
}
numAddedFunctions++;
return func;
}
void TranslateToFuzzReader::addHangLimitChecks(Function* func) {
// loop limit
for (auto* loop : FindAll<Loop>(func->body).list) {
loop->body =
builder.makeSequence(makeHangLimitCheck(), loop->body, loop->type);
}
// recursion limit
func->body =
builder.makeSequence(makeHangLimitCheck(), func->body, func->getResults());
// ArrayNew can hang the fuzzer if the array size is massive. This doesn't
// cause an OOM (which the fuzzer knows how to ignore) but it just works for
// many seconds on building the array. To avoid that, limit the size with high
// probability.
for (auto* arrayNew : FindAll<ArrayNew>(func->body).list) {
if (!oneIn(100)) {
arrayNew->size = builder.makeBinary(
AndInt32, arrayNew->size, builder.makeConst(int32_t(1024 - 1)));
}
}
}
void TranslateToFuzzReader::recombine(Function* func) {
// Don't always do this.
if (oneIn(2)) {
return;
}
// First, scan and group all expressions by type.
struct Scanner
: public PostWalker<Scanner, UnifiedExpressionVisitor<Scanner>> {
TranslateToFuzzReader& parent;
// A map of all expressions, categorized by type.
InsertOrderedMap<Type, std::vector<Expression*>> exprsByType;
Scanner(TranslateToFuzzReader& parent) : parent(parent) {}
void visitExpression(Expression* curr) {
if (parent.canBeArbitrarilyReplaced(curr)) {
for (auto type : getRelevantTypes(curr->type)) {
exprsByType[type].push_back(curr);
}
}
}
std::vector<Type> getRelevantTypes(Type type) {
// Given an expression of a type, we can replace not only other
// expressions with the same type, but also supertypes - since then we'd
// be replacing with a subtype, which is valid.
if (!type.isRef()) {
return {type};
}
std::vector<Type> ret;
auto heapType = type.getHeapType();
auto nullability = type.getNullability();
if (nullability == NonNullable) {
ret = getRelevantTypes(Type(heapType, Nullable));
}
while (1) {
ret.push_back(Type(heapType, nullability));
auto super = heapType.getSuperType();
if (!super) {
break;
}
heapType = *super;
}
return ret;
}
};
Scanner scanner(*this);
scanner.walk(func->body);
// Potentially trim the list of possible picks, so replacements are more
// likely to collide.
for (auto& pair : scanner.exprsByType) {
if (oneIn(2)) {
continue;
}
auto& list = pair.second;
std::vector<Expression*> trimmed;
size_t num = upToSquared(list.size());
for (size_t i = 0; i < num; i++) {
trimmed.push_back(pick(list));
}
if (trimmed.empty()) {
trimmed.push_back(pick(list));
}
list.swap(trimmed);
}
// Replace them with copies, to avoid a copy into one altering another copy
for (auto& pair : scanner.exprsByType) {
for (auto*& item : pair.second) {
item = ExpressionManipulator::copy(item, wasm);
}
}
// Second, with some probability replace an item with another item having
// a proper type. (This is not always valid due to nesting of labels, but
// we'll fix that up later.)
struct Modder : public PostWalker<Modder, UnifiedExpressionVisitor<Modder>> {
Module& wasm;
Scanner& scanner;
TranslateToFuzzReader& parent;
Modder(Module& wasm, Scanner& scanner, TranslateToFuzzReader& parent)
: wasm(wasm), scanner(scanner), parent(parent) {}
void visitExpression(Expression* curr) {
if (parent.oneIn(10) && parent.canBeArbitrarilyReplaced(curr)) {
// Replace it!
auto& candidates = scanner.exprsByType[curr->type];
assert(!candidates.empty()); // this expression itself must be there
auto* rep = parent.pick(candidates);
replaceCurrent(ExpressionManipulator::copy(rep, wasm));
}
}
};
Modder modder(wasm, scanner, *this);
modder.walk(func->body);
// TODO: A specific form of recombination we should perhaps do more often is
// to recombine among an expression's children, and in particular to
// reorder them.
}
// Given two expressions, try to replace one of the children of the first with
// the second. For example, given i32.add and an i32.const, the i32.const could
// be placed as either of the children of the i32.add. This tramples the
// existing content there. Returns true if we found a place.
static bool replaceChildWith(Expression* expr, Expression* with) {
for (auto*& child : ChildIterator(expr)) {
// To replace, we must have an appropriate type, and we cannot replace a
// Pop under any circumstances.
if (Type::isSubType(with->type, child->type) &&
FindAll<Pop>(child).list.empty()) {
child = with;
return true;
}
}
return false;
}
void TranslateToFuzzReader::mutate(Function* func) {
// We want a 50% chance to not do this at all, and otherwise, we want to pick
// a different frequency to do it in each function. That gives us more
// diversity between fuzzings of the same initial content (once we might
// mutate with 5%, and only change one or two places, while another time we
// might mutate with 50% and change quite a lot; without this type of
// mechanism, in a large function the amount of mutations will generally be
// very close to the mean due to the central limit theorem).
auto r = upTo(200);
if (r > 100) {
return;
}
// Prefer lower numbers: We want something like a 10% chance to mutate on
// average. To achieve that, we raise r/100, which is in the range [0, 1], to
// the 9th power, giving us a number also in the range [0, 1] with a mean of
// \integral_0^1 t^9 dx = 0.1 * t^10 |_0^1 = 0.1
// As a result, we get a value in the range of 0-100%. (Note that 100% is ok
// since we can't replace everything anyhow, see below.)
double t = r;
t = t / 100;
t = pow(t, 9);
Index percentChance = t * 100;
// Adjust almost-zero frequencies to at least a few %, just so we have some
// reasonable chance of making some changes.
percentChance = std::max(percentChance, Index(3));
struct Modder : public PostWalker<Modder, UnifiedExpressionVisitor<Modder>> {
TranslateToFuzzReader& parent;
Index percentChance;
// Whether to replace with unreachable. This can lead to less code getting
// executed, so we don't want to do it all the time even in a big function.
bool allowUnreachable;
Modder(TranslateToFuzzReader& parent, Index percentChance)
: parent(parent), percentChance(percentChance) {
// If the parent allows it then sometimes replace with an unreachable, and
// sometimes not. Even if we allow it, only do it in certain functions
// (half the time) and only do it rarely (see below).
allowUnreachable = parent.allowAddingUnreachableCode && parent.oneIn(2);
}
void visitExpression(Expression* curr) {
if (parent.upTo(100) < percentChance &&
parent.canBeArbitrarilyReplaced(curr)) {
// We can replace in various modes, see below. Generate a random number
// up to 100 to help us there.
int mode = parent.upTo(100);
if (allowUnreachable && mode < 5) {
replaceCurrent(parent.make(Type::unreachable));
return;
}
// For constants, perform only a small tweaking in some cases.
// TODO: more minor tweaks to immediates, like making a load atomic or
// not, changing an offset, etc.
if (auto* c = curr->dynCast<Const>()) {
if (mode < 50) {
c->value = parent.tweak(c->value);
} else {
// Just replace the entire thing.
replaceCurrent(parent.make(curr->type));
}
return;
}
// Generate a replacement for the expression, and by default replace all
// of |curr| (including children) with that replacement, but in some
// cases we can do more subtle things.
//
// Note that such a replacement is not always valid due to nesting of
// labels, but we'll fix that up later. Note also that make() picks a
// subtype, so this has a chance to replace us with anything that is