-
Notifications
You must be signed in to change notification settings - Fork 851
Expand file tree
/
Copy pathfuzzing.cpp
More file actions
6031 lines (5695 loc) · 217 KB
/
fuzzing.cpp
File metadata and controls
6031 lines (5695 loc) · 217 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/glbs.h"
#include "ir/iteration.h"
#include "ir/local-structural-dominance.h"
#include "ir/module-utils.h"
#include "ir/subtype-exprs.h"
#include "ir/subtypes.h"
#include "ir/type-updating.h"
#include "support/string.h"
#include "tools/fuzzing/heap-types.h"
#include "wasm-io.h"
namespace wasm {
namespace {
std::vector<Type> getLoggableTypes(const FeatureSet& features) {
std::vector<Type> loggableTypes = {
Type::i32, Type::i64, Type::f32, Type::f64};
if (features.hasSIMD()) {
loggableTypes.push_back(Type::v128);
}
if (features.hasReferenceTypes()) {
if (features.hasGC()) {
loggableTypes.push_back(Type(HeapType::any, Nullable));
loggableTypes.push_back(Type(HeapType::func, Nullable));
loggableTypes.push_back(Type(HeapType::ext, Nullable));
}
if (features.hasStackSwitching()) {
loggableTypes.push_back(Type(HeapType::cont, Nullable));
}
// Note: exnref traps on the JS boundary, so we cannot try to log it.
}
return loggableTypes;
}
std::vector<MemoryOrder> getMemoryOrders(const FeatureSet& features) {
return features.hasRelaxedAtomics()
? std::vector{MemoryOrder::AcqRel, MemoryOrder::SeqCst}
: std::vector{MemoryOrder::SeqCst};
}
} // namespace
TranslateToFuzzReader::TranslateToFuzzReader(Module& wasm,
std::vector<char>&& input,
bool closedWorld)
: wasm(wasm), closedWorld(closedWorld), builder(wasm),
random(std::move(input), wasm.features),
loggableTypes(getLoggableTypes(wasm.features)),
atomicMemoryOrders(getMemoryOrders(wasm.features)),
publicTypeValidator(wasm.features) {
haveInitialFunctions = !wasm.functions.empty();
// Setup params. Start with the defaults.
globalParams = std::make_unique<FuzzParamsContext>(*this);
// Some of the time, adjust parameters based on the size, e.g. allowing more
// heap types in larger inputs, etc.
if (random.oneIn(2)) {
// A typical random wasm input from fuzz_opt.py is fairly large (to minimize
// the process creation overhead of all the things we run from python), and
// the defaults are tuned to that. This corresponds to INPUT_SIZE_MEAN in
// scripts/fuzz_opt.py
const double MEAN_SIZE = 40 * 1024;
// As we have not read anything from the input, the remaining size is its
// size.
double size = random.remaining();
auto ratio = size / MEAN_SIZE;
auto bits = random.get();
if (bits & 1) {
fuzzParams->MAX_NEW_GC_TYPES *= ratio;
}
if (bits & 2) {
fuzzParams->MAX_GLOBALS *= ratio;
}
if (bits & 4) {
// Only adjust the limit if there is one.
if (fuzzParams->HANG_LIMIT) {
fuzzParams->HANG_LIMIT *= ratio;
// There is a limit, so keep it non-zero to actually prevent hangs.
fuzzParams->HANG_LIMIT = std::max(fuzzParams->HANG_LIMIT, 1);
}
}
if (bits & 8) {
// Only increase the number of tries. Trying fewer times does not help
// find more interesting patterns.
if (ratio > 1) {
fuzzParams->TRIES *= ratio;
}
}
if (bits & 16) {
fuzzParams->MAX_ARRAY_SIZE *= ratio;
}
}
// Half the time add no unreachable code so that we'll execute the most code
// as possible with no early exits.
allowAddingUnreachableCode = oneIn(2);
}
TranslateToFuzzReader::TranslateToFuzzReader(Module& wasm,
std::string& filename,
bool closedWorld)
: TranslateToFuzzReader(wasm,
read_file<std::vector<char>>(filename, Flags::Binary),
closedWorld) {}
void TranslateToFuzzReader::pickPasses(OptimizationOptions& options) {
// Pick random passes to further shape the wasm. This is similar to how we
// pick random passes in fuzz_opt.py, but the goal there is to find problems
// in the passes, while the goal here is more to shape the wasm, so that
// translate-to-fuzz emits interesting outputs (the latter is important for
// things like ClusterFuzz, where we are using Binaryen to fuzz other things
// than itself). As a result, the list of passes here is different from
// fuzz_opt.py.
// Enclose the world, some of the time. We do this before picking any other
// passes so that we make the initial fuzz contents more optimizable by
// closed-world passes later. Note that we do this regardless of whether we
// are in closed-world mode or not, as it is good to get this variety
// regardless.
if (oneIn(2)) {
options.passes.push_back("enclose-world");
}
// Main selection of passes.
while (options.passes.size() < 20 && !random.finished() && !oneIn(3)) {
switch (upTo(42)) {
case 0:
case 1:
case 2:
case 3:
case 4: {
options.passOptions.optimizeLevel = upTo(4);
options.passOptions.shrinkLevel = upTo(3);
options.addDefaultOptPasses();
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:
// Some features do not support flatten yet.
if (!wasm.features.hasReferenceTypes() &&
!wasm.features.hasExceptionHandling() && !wasm.features.hasGC()) {
options.passes.push_back("flatten");
if (oneIn(2)) {
options.passes.push_back("rereloop");
}
}
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("directize");
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;
case 32:
options.passes.push_back("merge-locals");
break;
case 33:
options.passes.push_back("licm");
break;
case 34:
options.passes.push_back("tuple-optimization");
break;
case 35:
options.passes.push_back("rse");
break;
case 36:
options.passes.push_back("monomorphize");
break;
case 37:
options.passes.push_back("monomorphize-always");
break;
case 38:
case 39:
case 40:
case 41:
// GC specific passes.
if (wasm.features.hasGC()) {
// Most of these depend on closed world, so just set that. Set it both
// on the global pass options, and in the internal state of this
// TranslateToFuzzReader instance.
options.passOptions.closedWorld = true;
closedWorld = true;
switch (upTo(16)) {
case 0:
options.passes.push_back("abstract-type-refining");
break;
case 1:
options.passes.push_back("cfp");
break;
case 2:
options.passes.push_back("gsi");
break;
case 3:
options.passes.push_back("gto");
break;
case 4:
options.passes.push_back("heap2local");
break;
case 5:
options.passes.push_back("heap-store-optimization");
break;
case 6:
options.passes.push_back("minimize-rec-groups");
break;
case 7:
options.passes.push_back("remove-unused-types");
break;
case 8:
options.passes.push_back("signature-pruning");
break;
case 9:
options.passes.push_back("signature-refining");
break;
case 10:
options.passes.push_back("type-finalizing");
break;
case 11:
options.passes.push_back("type-refining");
break;
case 12:
options.passes.push_back("type-merging");
break;
case 13:
options.passes.push_back("type-ssa");
break;
case 14:
options.passes.push_back("type-unfinalizing");
break;
case 15:
options.passes.push_back("unsubtyping");
break;
default:
WASM_UNREACHABLE("unexpected value");
}
}
break;
default:
WASM_UNREACHABLE("unexpected value");
}
}
if (oneIn(2)) {
// We randomize these when we pick -O?, but sometimes do so even without, as
// they affect some passes.
options.passOptions.optimizeLevel = upTo(4);
options.passOptions.shrinkLevel = upTo(3);
}
if (!options.passOptions.closedWorld && oneIn(2)) {
options.passOptions.closedWorld = true;
}
// Prune things that error in JS if we call them (like SIMD), some of the
// time. This alters the wasm/JS boundary quite a lot, so testing both forms
// is useful. Note that we do not do this if there is an imported module,
// because in that case legalization could alter the contract between the two
// (that is, if the first module has an i64 param, we must call it like that,
// and not as two i32s which we'd get after legalization).
if (!importedModule && oneIn(2)) {
options.passes.push_back("legalize-and-prune-js-interface");
}
// Usually DCE at the very end, to ensure that our binaries validate in other
// VMs, due to how non-nullable local validation and unreachable code
// interact. See fuzz_opt.py and
// https://github.com/WebAssembly/binaryen/pull/5665
// https://github.com/WebAssembly/binaryen/issues/5599
if (wasm.features.hasGC() && !oneIn(10)) {
options.passes.push_back("dce");
}
// TODO: We could in theory run some function-level passes on particular
// functions, but then we'd need to do this after generation, not
// before (and random data no longer remains then).
}
void TranslateToFuzzReader::build() {
if (fuzzParams->HANG_LIMIT > 0) {
prepareHangLimitSupport();
}
if (allowMemory) {
setupMemory();
}
setupHeapTypes();
setupTables();
setupGlobals();
useImportedGlobals();
if (wasm.features.hasExceptionHandling()) {
setupTags();
addImportThrowingSupport();
}
if (wasm.features.hasReferenceTypes()) {
addImportTableSupport();
}
addImportLoggingSupport();
addImportCallingSupport();
addImportSleepSupport();
// First, modify initial functions. That includes removing imports. Then,
// use the imported module, which are function imports that we allow.
modifyInitialFunctions();
useImportedFunctions();
processFunctions();
if (fuzzParams->HANG_LIMIT > 0) {
addHangLimitSupport();
}
if (allowMemory) {
finalizeMemory();
addHashMemorySupport();
}
finalizeTable();
shuffleExports();
// We may turn various function imports into defined functions. Refinalize at
// the end to update all references to them, which may become exact.
PassRunner runner(&wasm);
ReFinalize().run(&runner, &wasm);
ReFinalize().walkModuleCode(&wasm);
}
void TranslateToFuzzReader::setupMemory() {
// Add a memory, if one does not already exist.
if (wasm.memories.empty()) {
auto memory = Builder::makeMemory("0");
// Add at least one page of memory.
memory->initial = 1 + upTo(10);
// Make the max potentially higher, or unlimited.
if (oneIn(2)) {
memory->max = memory->initial + upTo(4);
} else {
memory->max = Memory::kUnlimitedSize;
}
// Fuzz wasm64 when possible, sometimes.
if (wasm.features.hasMemory64() && oneIn(2)) {
memory->addressType = Type::i64;
}
wasm.addMemory(std::move(memory));
}
auto& memory = wasm.memories[0];
if (wasm.features.hasBulkMemory()) {
size_t numSegments = upTo(8);
// need at least one segment for memory.inits
if (wasm.dataSegments.empty() && !numSegments) {
numSegments = 1;
}
size_t memCovered = 0;
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(fuzzParams->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(
Literal::makeFromInt32(memCovered, memory->addressType));
memCovered += segSize;
segment->memory = memory->name;
}
wasm.addDataSegment(std::move(segment));
}
} else {
// init some data, especially if none exists before
if (!oneIn(wasm.dataSegments.empty() ? 10 : 2)) {
auto segment = builder.makeDataSegment();
segment->memory = memory->name;
segment->offset =
builder.makeConst(Literal::makeFromInt32(0, memory->addressType));
segment->setName(Names::getValidDataSegmentName(wasm, Name::fromInt(0)),
false);
auto num = upTo(fuzzParams->USABLE_MEMORY * 2);
for (size_t i = 0; i < num; i++) {
auto value = upTo(512);
segment->data.push_back(value >= 256 ? 0 : (value & 0xff));
}
wasm.addDataSegment(std::move(segment));
}
}
}
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);
// Use heap types from an imported module, if present.
if (importedModule) {
auto importedHeapTypes = ModuleUtils::collectHeapTypes(*importedModule);
auto rate = upTo(11);
for (auto type : importedHeapTypes) {
if (upTo(10) < rate) {
possibleHeapTypes.push_back(type);
}
}
}
// 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(fuzzParams->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.
auto share = type.getShared();
auto struct_ = HeapTypes::struct_.getBasic(share);
auto array = HeapTypes::array.getBasic(share);
auto eq = HeapTypes::eq.getBasic(share);
auto any = HeapTypes::any.getBasic(share);
auto func = HeapTypes::func.getBasic(share);
auto cont = HeapTypes::cont.getBasic(share);
switch (type.getKind()) {
case HeapTypeKind::Func:
interestingHeapSubTypes[func].push_back(type);
break;
case HeapTypeKind::Struct: {
interestingHeapSubTypes[struct_].push_back(type);
interestingHeapSubTypes[eq].push_back(type);
interestingHeapSubTypes[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});
}
}
break;
}
case HeapTypeKind::Array:
interestingHeapSubTypes[array].push_back(type);
interestingHeapSubTypes[eq].push_back(type);
interestingHeapSubTypes[any].push_back(type);
if (type.getArray().element.mutable_) {
mutableArrays.push_back(type);
}
break;
case HeapTypeKind::Cont:
interestingHeapSubTypes[cont].push_back(type);
break;
case HeapTypeKind::Basic:
WASM_UNREACHABLE("unexpected kind");
}
}
// 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 {
// Start from a potentially empty table.
Address initial = upTo(10);
// Make the max potentially higher, or unlimited.
Address max;
if (oneIn(2)) {
max = initial + upTo(4);
} else {
max = Memory::kUnlimitedSize;
}
// Fuzz wasm64 when possible, sometimes.
auto addressType = Type::i32;
if (wasm.features.hasMemory64() && oneIn(2)) {
addressType = Type::i64;
}
auto tablePtr =
builder.makeTable(Names::getValidTableName(wasm, "fuzzing_table"),
funcref,
initial,
max,
addressType);
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;
});
auto addressType = wasm.getTable(funcrefTableName)->addressType;
if (!hasFuncrefElemSegment) {
// TODO: use a random table
auto segment = std::make_unique<ElementSegment>(
table->name, builder.makeConst(Literal::makeFromInt32(0, addressType)));
segment->setName(Names::getValidElementSegmentName(wasm, "elem$"), false);
wasm.addElementSegment(std::move(segment));
}
// When EH is enabled, set up an exnref table.
if (wasm.features.hasExceptionHandling()) {
Type exnref = Type(HeapType::exn, Nullable);
auto iter =
std::find_if(wasm.tables.begin(), wasm.tables.end(), [&](auto& table) {
return table->type == exnref;
});
if (iter != wasm.tables.end()) {
// Use the existing one.
exnrefTableName = iter->get()->name;
} else {
// Create a new exnref table.
Address initial = upTo(10);
Address max = oneIn(2) ? initial + upTo(4) : Memory::kUnlimitedSize;
auto tablePtr =
builder.makeTable(Names::getValidTableName(wasm, "exnref_table"),
exnref,
initial,
max,
Type::i32); // TODO: wasm64
tablePtr->hasExplicitName = true;
table = wasm.addTable(std::move(tablePtr));
exnrefTableName = table->name;
}
}
}
void TranslateToFuzzReader::useGlobalLater(Global* global) {
auto type = global->type;
auto name = global->name;
globalsByType[type].push_back(name);
if (global->mutable_) {
mutableGlobalsByType[type].push_back(name);
} else {
immutableGlobalsByType[type].push_back(name);
if (global->imported()) {
importedImmutableGlobalsByType[type].push_back(name);
}
}
}
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()) {
if (!preserveImportsAndExports) {
// 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.)
if (!wasm.globals.empty()) {
unsigned percentUsedInitialGlobals = upTo(100);
for (auto& global : wasm.globals) {
if (upTo(100) < percentUsedInitialGlobals) {
useGlobalLater(global.get());
}
}
}
// Create new random globals.
for (size_t index = upTo(fuzzParams->MAX_GLOBALS); index > 0; --index) {
auto type = getConcreteType();
// Prefer immutable ones as they can be used in global.gets in other
// globals, for more interesting patterns.
auto mutability = oneIn(3) ? Builder::Mutable : Builder::Immutable;
// We can only make something trivial (like a constant) in a global
// initializer.
auto* init = makeTrivial(type);
if (type.isTuple() && !init->is<TupleMake>()) {
// For now we disallow anything but tuple.make at the top level of tuple
// globals (see details in wasm-binary.cpp). In the future we may allow
// global.get or other things here.
init = makeConst(type);
assert(init->is<TupleMake>());
}
if (!FindAll<RefAs>(init).list.empty() ||
!FindAll<ContNew>(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.
//
// Likewise, if we see cont.new, we must switch as well. That can happen
// if a nested struct we create has a continuation field, for example.
type = getMVPType();
init = makeConst(type);
}
auto name = Names::getValidGlobalName(wasm, "global$");
auto global = builder.makeGlobal(name, type, init, mutability);
useGlobalLater(wasm.addGlobal(std::move(global)));
// Export some globals, where we can.
if (preserveImportsAndExports || type.isTuple() ||
!isValidPublicType(type)) {
continue;
}
if (mutability == Builder::Mutable && !wasm.features.hasMutableGlobals()) {
continue;
}
if (oneIn(2)) {
auto exportName = Names::getValidExportName(wasm, name);
wasm.addExport(
Builder::makeExport(exportName, name, ExternalKind::Global));
}
}
}
void TranslateToFuzzReader::setupTags() {
// As in modifyInitialFunctions(), we can't allow arbitrary tag imports, which
// would trap when the fuzzing infrastructure doesn't know what to provide.
for (auto& tag : wasm.tags) {
if (tag->imported() && !preserveImportsAndExports) {
tag->module = tag->base = Name();
}
if (tag->results() == Type::none) {
exceptionTags.push_back(tag.get());
}
}
// Add some random tags.
Index num = upTo(3);
for (size_t i = 0; i < num; i++) {
addTag();
}
// Add the fuzzing support tags manually sometimes.
if (!preserveImportsAndExports && oneIn(2) && !random.finished()) {
auto wasmTag = builder.makeTag(Names::getValidTagName(wasm, "wasmtag"),
Signature(Type::i32, Type::none));
wasmTag->module = "fuzzing-support";
wasmTag->base = "wasmtag";
wasm.addTag(std::move(wasmTag));
auto externref = Type(HeapType::ext, Nullable);
auto jsTag = builder.makeTag(Names::getValidTagName(wasm, "jstag"),
Signature(externref, Type::none));
jsTag->module = "fuzzing-support";
jsTag->base = "jstag";
wasm.addTag(std::move(jsTag));
}
}
void TranslateToFuzzReader::addTag() {
auto tag = builder.makeTag(Names::getValidTagName(wasm, "tag$"),
Signature(getControlFlowType(), Type::none));
auto* tagg = wasm.addTag(std::move(tag));
exceptionTags.push_back(tagg);
}
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, memory->addressType));
}
}
if (auto* offset = segment->offset->dynCast<Const>()) {
maxOffset = maxOffset + offset->value.getInteger();
}
}
// Ensure the initial memory can fit the segment (so we don't just trap),
// but only do so when the segment is at a reasonable offset (to avoid
// validation errors on the initial size >= 4GB in wasm32, but also to
// avoid OOM errors on trying to allocate too much initial memory, which is
// annoying in the fuzzer).
Address ONE_GB = 1024 * 1024 * 1024;
if (maxOffset <= ONE_GB) {
memory->initial = std::max(
memory->initial,
Address((maxOffset + Memory::kPageSize - 1) / Memory::kPageSize));
}
}
memory->initial = std::max(memory->initial, fuzzParams->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));
}
if (!preserveImportsAndExports) {
// 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, table->addressType));
}
}
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::kMaxSize32 being an Index (32 bits), as a
// result of which we need to clamp to Table::kMaxSize32 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::kMaxSize32);
table->max = oneIn(2) ? Address(Table::kUnlimitedSize) : table->initial;
if (!preserveImportsAndExports) {
// Avoid an imported table (which the fuzz harness would need to handle).
table->module = table->base = Name();
}
}
}
void TranslateToFuzzReader::shuffleExports() {
// Randomly ordering the exports is useful for a few reasons. First, initial
// content may have a natural order in which to execute things (an "init"
// export first, for example), and changing that order may lead to very
// different execution. Second, even in the fuzzer's own random content there
// is a "direction", since we generate as we go (e.g. no function calls a
// later function that does not exist yet / will be created later), and also
// we emit invokes for a function right after it (so we end up calling the
// same code several times in succession, but interleaving it with others may
// find more things). But we also keep a good chance for the natural order
// here, as it may help some initial content. Note we cannot do this if we are
// preserving the exports, as their order is something we must maintain.
if (wasm.exports.empty() || preserveImportsAndExports || oneIn(2) ||
random.finished()) {
return;
}
// Sort the exports in the simple Fisher-Yates manner.
// https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle#The_modern_algorithm
for (Index i = 0; i < wasm.exports.size() - 1; i++) {
// Pick the index of the item to place at index |i|. The number of items to
// pick from begins at the full length, then decreases with i.
auto j = i + upTo(wasm.exports.size() - i);
// Swap the item over here.
if (j != i) {
std::swap(wasm.exports[i], wasm.exports[j]);
}
}
wasm.updateMaps();
}
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(fuzzParams->HANG_LIMIT)),
Builder::Mutable);
wasm.addGlobal(std::move(glob));
}
void TranslateToFuzzReader::addImportLoggingSupport() {
for (auto type : loggableTypes) {
auto func = std::make_unique<Function>();
Name baseName = std::string("log-") + type.toString();
func->name = Names::getValidFunctionName(wasm, baseName);
logImportNames[type] = func->name;
if (!preserveImportsAndExports) {
func->module = "fuzzing-support";
func->base = baseName;
func->type = Type(Signature(type, Type::none), NonNullable, Inexact);
} else {
// We cannot add an import, so just make it a trivial function (this is
// simpler than avoiding calls to logging in all the rest of the logic).
func->body = builder.makeNop();
func->type = Type(Signature(type, Type::none), NonNullable, Exact);
}
wasm.addFunction(std::move(func));
}
}
void TranslateToFuzzReader::addImportCallingSupport() {
if (preserveImportsAndExports) {
return;