-
Notifications
You must be signed in to change notification settings - Fork 246
/
core.rs
2855 lines (2588 loc) · 103 KB
/
core.rs
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
//! Generating arbitary core Wasm modules.
mod code_builder;
pub(crate) mod encode;
mod terminate;
use crate::{arbitrary_loop, limited_string, unique_string, Config};
use arbitrary::{Arbitrary, Result, Unstructured};
use code_builder::CodeBuilderAllocations;
use flagset::{flags, FlagSet};
use std::collections::{HashMap, HashSet};
use std::fmt;
use std::mem;
use std::ops::Range;
use std::rc::Rc;
use std::str::{self, FromStr};
use wasm_encoder::{
AbstractHeapType, ArrayType, BlockType, ConstExpr, ExportKind, FieldType, HeapType, RefType,
StorageType, StructType, ValType,
};
pub(crate) use wasm_encoder::{GlobalType, MemoryType, TableType};
// NB: these constants are used to control the rate at which various events
// occur. For more information see where these constants are used. Their values
// are somewhat random in the sense that they're not scientifically determined
// or anything like that, I just threw a bunch of random data at wasm-smith and
// measured various rates of ooms/traps/etc and adjusted these so abnormal
// events were ~1% of the time.
const CHANCE_OFFSET_INBOUNDS: usize = 10; // bigger = less traps
const CHANCE_SEGMENT_ON_EMPTY: usize = 10; // bigger = less traps
const PCT_INBOUNDS: f64 = 0.995; // bigger = less traps
type Instruction = wasm_encoder::Instruction<'static>;
/// A pseudo-random WebAssembly module.
///
/// Construct instances of this type (with default configuration) with [the
/// `Arbitrary`
/// trait](https://docs.rs/arbitrary/*/arbitrary/trait.Arbitrary.html).
///
/// ## Configuring Generated Modules
///
/// To configure the shape of generated module, create a
/// [`Config`][crate::Config] and then call [`Module::new`][crate::Module::new]
/// with it.
pub struct Module {
config: Config,
duplicate_imports_behavior: DuplicateImportsBehavior,
valtypes: Vec<ValType>,
/// All types locally defined in this module (available in the type index
/// space).
types: Vec<SubType>,
/// Non-overlapping ranges within `types` that belong to the same rec
/// group. All of `types` is covered by these ranges. When GC is not
/// enabled, these are all single-element ranges.
rec_groups: Vec<Range<usize>>,
/// A map from a super type to all of its sub types.
super_to_sub_types: HashMap<u32, Vec<u32>>,
/// Indices within `types` that are not final types.
can_subtype: Vec<u32>,
/// Whether we should encode a types section, even if `self.types` is empty.
should_encode_types: bool,
/// All of this module's imports. These don't have their own index space,
/// but instead introduce entries to each imported entity's associated index
/// space.
imports: Vec<Import>,
/// Whether we should encode an imports section, even if `self.imports` is
/// empty.
should_encode_imports: bool,
/// Indices within `types` that are array types.
array_types: Vec<u32>,
/// Indices within `types` that are function types.
func_types: Vec<u32>,
/// Indices within `types that are struct types.
struct_types: Vec<u32>,
/// Number of imported items into this module.
num_imports: usize,
/// The number of tags defined in this module (not imported or
/// aliased).
num_defined_tags: usize,
/// The number of functions defined in this module (not imported or
/// aliased).
num_defined_funcs: usize,
/// Initialization expressions for all defined tables in this module.
defined_tables: Vec<Option<ConstExpr>>,
/// The number of memories defined in this module (not imported or
/// aliased).
num_defined_memories: usize,
/// The indexes and initialization expressions of globals defined in this
/// module.
defined_globals: Vec<(u32, ConstExpr)>,
/// All tags available to this module, sorted by their index. The list
/// entry is the type of each tag.
tags: Vec<TagType>,
/// All functions available to this module, sorted by their index. The list
/// entry points to the index in this module where the function type is
/// defined (if available) and provides the type of the function.
funcs: Vec<(u32, Rc<FuncType>)>,
/// All tables available to this module, sorted by their index. The list
/// entry is the type of each table.
tables: Vec<TableType>,
/// All globals available to this module, sorted by their index. The list
/// entry is the type of each global.
globals: Vec<GlobalType>,
/// All memories available to this module, sorted by their index. The list
/// entry is the type of each memory.
memories: Vec<MemoryType>,
exports: Vec<(String, ExportKind, u32)>,
start: Option<u32>,
elems: Vec<ElementSegment>,
code: Vec<Code>,
data: Vec<DataSegment>,
/// The predicted size of the effective type of this module, based on this
/// module's size of the types of imports/exports.
type_size: u32,
/// Names currently exported from this module.
export_names: HashSet<String>,
/// Reusable buffer in `self.arbitrary_const_expr` to amortize the cost of
/// allocation.
const_expr_choices: Vec<Box<dyn Fn(&mut Unstructured, ValType) -> Result<ConstExpr>>>,
/// What the maximum type index that can be referenced is.
max_type_limit: MaxTypeLimit,
/// Some known-interesting values, such as powers of two, values just before
/// or just after a memory size, etc...
interesting_values32: Vec<u32>,
interesting_values64: Vec<u64>,
}
impl<'a> Arbitrary<'a> for Module {
fn arbitrary(u: &mut Unstructured<'a>) -> Result<Self> {
Module::new(Config::default(), u)
}
}
impl fmt::Debug for Module {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Module")
.field("config", &self.config)
.field(&"...", &"...")
.finish()
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum DuplicateImportsBehavior {
Allowed,
Disallowed,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum MaxTypeLimit {
ModuleTypes,
Num(u32),
}
impl Module {
/// Returns a reference to the internal configuration.
pub fn config(&self) -> &Config {
&self.config
}
/// Creates a new `Module` with the specified `config` for
/// configuration and `Unstructured` for the DNA of this module.
pub fn new(config: Config, u: &mut Unstructured<'_>) -> Result<Self> {
Self::new_internal(config, u, DuplicateImportsBehavior::Allowed)
}
pub(crate) fn new_internal(
config: Config,
u: &mut Unstructured<'_>,
duplicate_imports_behavior: DuplicateImportsBehavior,
) -> Result<Self> {
let mut module = Module::empty(config, duplicate_imports_behavior);
module.build(u)?;
Ok(module)
}
fn empty(config: Config, duplicate_imports_behavior: DuplicateImportsBehavior) -> Self {
Module {
config,
duplicate_imports_behavior,
valtypes: Vec::new(),
types: Vec::new(),
rec_groups: Vec::new(),
can_subtype: Vec::new(),
super_to_sub_types: HashMap::new(),
should_encode_types: false,
imports: Vec::new(),
should_encode_imports: false,
array_types: Vec::new(),
func_types: Vec::new(),
struct_types: Vec::new(),
num_imports: 0,
num_defined_tags: 0,
num_defined_funcs: 0,
defined_tables: Vec::new(),
num_defined_memories: 0,
defined_globals: Vec::new(),
tags: Vec::new(),
funcs: Vec::new(),
tables: Vec::new(),
globals: Vec::new(),
memories: Vec::new(),
exports: Vec::new(),
start: None,
elems: Vec::new(),
code: Vec::new(),
data: Vec::new(),
type_size: 0,
export_names: HashSet::new(),
const_expr_choices: Vec::new(),
max_type_limit: MaxTypeLimit::ModuleTypes,
interesting_values32: Vec::new(),
interesting_values64: Vec::new(),
}
}
}
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub(crate) struct SubType {
pub(crate) is_final: bool,
pub(crate) supertype: Option<u32>,
pub(crate) composite_type: CompositeType,
}
impl SubType {
fn unwrap_struct(&self) -> &StructType {
self.composite_type.unwrap_struct()
}
fn unwrap_func(&self) -> &Rc<FuncType> {
self.composite_type.unwrap_func()
}
fn unwrap_array(&self) -> &ArrayType {
self.composite_type.unwrap_array()
}
}
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub(crate) struct CompositeType {
pub inner: CompositeInnerType,
pub shared: bool,
}
impl CompositeType {
pub(crate) fn new_func(func: Rc<FuncType>, shared: bool) -> Self {
Self {
inner: CompositeInnerType::Func(func),
shared,
}
}
fn unwrap_func(&self) -> &Rc<FuncType> {
match &self.inner {
CompositeInnerType::Func(f) => f,
_ => panic!("not a func"),
}
}
fn unwrap_array(&self) -> &ArrayType {
match &self.inner {
CompositeInnerType::Array(a) => a,
_ => panic!("not an array"),
}
}
fn unwrap_struct(&self) -> &StructType {
match &self.inner {
CompositeInnerType::Struct(s) => s,
_ => panic!("not a struct"),
}
}
}
impl From<&CompositeType> for wasm_encoder::CompositeType {
fn from(ty: &CompositeType) -> Self {
let inner = match &ty.inner {
CompositeInnerType::Array(a) => wasm_encoder::CompositeInnerType::Array(*a),
CompositeInnerType::Func(f) => wasm_encoder::CompositeInnerType::Func(
wasm_encoder::FuncType::new(f.params.iter().cloned(), f.results.iter().cloned()),
),
CompositeInnerType::Struct(s) => wasm_encoder::CompositeInnerType::Struct(s.clone()),
};
wasm_encoder::CompositeType {
shared: ty.shared,
inner,
}
}
}
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub(crate) enum CompositeInnerType {
Array(ArrayType),
Func(Rc<FuncType>),
Struct(StructType),
}
/// A function signature.
#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub(crate) struct FuncType {
/// Types of the parameter values.
pub(crate) params: Vec<ValType>,
/// Types of the result values.
pub(crate) results: Vec<ValType>,
}
/// An import of an entity provided externally or by a component.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub(crate) struct Import {
/// The name of the module providing this entity.
pub(crate) module: String,
/// The name of the entity.
pub(crate) field: String,
/// The type of this entity.
pub(crate) entity_type: EntityType,
}
/// Type of an entity.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub(crate) enum EntityType {
/// A global entity.
Global(GlobalType),
/// A table entity.
Table(TableType),
/// A memory entity.
Memory(MemoryType),
/// A tag entity.
Tag(TagType),
/// A function entity.
Func(u32, Rc<FuncType>),
}
/// Type of a tag.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub(crate) struct TagType {
/// Index of the function type.
func_type_idx: u32,
/// Type of the function.
func_type: Rc<FuncType>,
}
#[derive(Debug)]
struct ElementSegment {
kind: ElementKind,
ty: RefType,
items: Elements,
}
#[derive(Debug)]
enum ElementKind {
Passive,
Declared,
Active {
table: Option<u32>, // None == table 0 implicitly
offset: Offset,
},
}
#[derive(Debug)]
enum Elements {
Functions(Vec<u32>),
Expressions(Vec<ConstExpr>),
}
#[derive(Debug)]
struct Code {
locals: Vec<ValType>,
instructions: Instructions,
}
#[derive(Debug)]
enum Instructions {
Generated(Vec<Instruction>),
Arbitrary(Vec<u8>),
}
#[derive(Debug)]
struct DataSegment {
kind: DataSegmentKind,
init: Vec<u8>,
}
#[derive(Debug)]
enum DataSegmentKind {
Passive,
Active { memory_index: u32, offset: Offset },
}
#[derive(Debug)]
pub(crate) enum Offset {
Const32(i32),
Const64(i64),
Global(u32),
}
impl Module {
fn build(&mut self, u: &mut Unstructured) -> Result<()> {
self.valtypes = configured_valtypes(&self.config);
// We attempt to figure out our available imports *before* creating the types section here,
// because the types for the imports are already well-known (specified by the user) and we
// must have those populated for all function/etc. imports, no matter what.
//
// This can affect the available capacity for types and such.
if self.arbitrary_imports_from_available(u)? {
self.arbitrary_types(u)?;
} else {
self.arbitrary_types(u)?;
self.arbitrary_imports(u)?;
}
self.should_encode_imports = !self.imports.is_empty() || u.arbitrary()?;
self.arbitrary_tags(u)?;
self.arbitrary_funcs(u)?;
self.arbitrary_tables(u)?;
self.arbitrary_memories(u)?;
self.arbitrary_globals(u)?;
if !self.required_exports(u)? {
self.arbitrary_exports(u)?;
};
self.should_encode_types = !self.types.is_empty() || u.arbitrary()?;
self.arbitrary_start(u)?;
self.arbitrary_elems(u)?;
self.arbitrary_data(u)?;
self.arbitrary_code(u)?;
Ok(())
}
#[inline]
fn val_type_is_sub_type(&self, a: ValType, b: ValType) -> bool {
match (a, b) {
(a, b) if a == b => true,
(ValType::Ref(a), ValType::Ref(b)) => self.ref_type_is_sub_type(a, b),
_ => false,
}
}
/// Is `a` a subtype of `b`?
fn ref_type_is_sub_type(&self, a: RefType, b: RefType) -> bool {
if a == b {
return true;
}
if a.nullable && !b.nullable {
return false;
}
self.heap_type_is_sub_type(a.heap_type, b.heap_type)
}
fn heap_type_is_sub_type(&self, a: HeapType, b: HeapType) -> bool {
use AbstractHeapType::*;
use CompositeInnerType as CT;
use HeapType as HT;
match (a, b) {
(a, b) if a == b => true,
(
HT::Abstract {
shared: a_shared,
ty: a_ty,
},
HT::Abstract {
shared: b_shared,
ty: b_ty,
},
) => {
a_shared == b_shared
&& match (a_ty, b_ty) {
(Eq | I31 | Struct | Array | None, Any) => true,
(I31 | Struct | Array | None, Eq) => true,
(NoExtern, Extern) => true,
(NoFunc, Func) => true,
(None, I31 | Array | Struct) => true,
(NoExn, Exn) => true,
_ => false,
}
}
(HT::Concrete(a), HT::Abstract { shared, ty }) => {
let a_ty = &self.ty(a).composite_type;
if a_ty.shared == shared {
return false;
}
match ty {
Eq | Any => matches!(a_ty.inner, CT::Array(_) | CT::Struct(_)),
Struct => matches!(a_ty.inner, CT::Struct(_)),
Array => matches!(a_ty.inner, CT::Array(_)),
Func => matches!(a_ty.inner, CT::Func(_)),
_ => false,
}
}
(HT::Abstract { shared, ty }, HT::Concrete(b)) => {
let b_ty = &self.ty(b).composite_type;
if shared == b_ty.shared {
return false;
}
match ty {
None => matches!(b_ty.inner, CT::Array(_) | CT::Struct(_)),
NoFunc => matches!(b_ty.inner, CT::Func(_)),
_ => false,
}
}
(HT::Concrete(mut a), HT::Concrete(b)) => loop {
if a == b {
return true;
}
if let Some(supertype) = self.ty(a).supertype {
a = supertype;
} else {
return false;
}
},
}
}
fn arbitrary_types(&mut self, u: &mut Unstructured) -> Result<()> {
assert!(self.config.min_types <= self.config.max_types);
while self.types.len() < self.config.min_types {
self.arbitrary_rec_group(u)?;
}
while self.types.len() < self.config.max_types {
let keep_going = u.arbitrary().unwrap_or(false);
if !keep_going {
break;
}
self.arbitrary_rec_group(u)?;
}
Ok(())
}
fn add_type(&mut self, ty: SubType) -> u32 {
let index = u32::try_from(self.types.len()).unwrap();
if let Some(supertype) = ty.supertype {
self.super_to_sub_types
.entry(supertype)
.or_default()
.push(index);
}
let list = match &ty.composite_type.inner {
CompositeInnerType::Array(_) => &mut self.array_types,
CompositeInnerType::Func(_) => &mut self.func_types,
CompositeInnerType::Struct(_) => &mut self.struct_types,
};
list.push(index);
if !ty.is_final {
self.can_subtype.push(index);
}
self.types.push(ty);
index
}
fn arbitrary_rec_group(&mut self, u: &mut Unstructured) -> Result<()> {
let rec_group_start = self.types.len();
assert!(matches!(self.max_type_limit, MaxTypeLimit::ModuleTypes));
if self.config.gc_enabled {
// With small probability, clone an existing rec group.
if self.clonable_rec_groups().next().is_some() && u.ratio(1, u8::MAX)? {
return self.clone_rec_group(u);
}
// Otherwise, create a new rec group with multiple types inside.
let max_rec_group_size = self.config.max_types - self.types.len();
let rec_group_size = u.int_in_range(0..=max_rec_group_size)?;
let type_ref_limit = u32::try_from(self.types.len() + rec_group_size).unwrap();
self.max_type_limit = MaxTypeLimit::Num(type_ref_limit);
for _ in 0..rec_group_size {
let ty = self.arbitrary_sub_type(u)?;
self.add_type(ty);
}
} else {
let type_ref_limit = u32::try_from(self.types.len()).unwrap();
self.max_type_limit = MaxTypeLimit::Num(type_ref_limit);
let ty = self.arbitrary_sub_type(u)?;
self.add_type(ty);
}
self.max_type_limit = MaxTypeLimit::ModuleTypes;
self.rec_groups.push(rec_group_start..self.types.len());
Ok(())
}
/// Returns an iterator of rec groups that we could currently clone while
/// still staying within the max types limit.
fn clonable_rec_groups(&self) -> impl Iterator<Item = Range<usize>> + '_ {
self.rec_groups
.iter()
.filter(|r| r.end - r.start <= self.config.max_types.saturating_sub(self.types.len()))
.cloned()
}
fn clone_rec_group(&mut self, u: &mut Unstructured) -> Result<()> {
// NB: this does *not* guarantee that the cloned rec group will
// canonicalize the same as the original rec group and be
// deduplicated. That would reqiure a second pass over the cloned types
// to rewrite references within the original rec group to be references
// into the new rec group. That might make sense to do one day, but for
// now we don't do it. That also means that we can't mark the new types
// as "subtypes" of the old types and vice versa.
let candidates: Vec<_> = self.clonable_rec_groups().collect();
let group = u.choose(&candidates)?.clone();
let new_rec_group_start = self.types.len();
for index in group {
let orig_ty_index = u32::try_from(index).unwrap();
let ty = self.ty(orig_ty_index).clone();
self.add_type(ty);
}
self.rec_groups.push(new_rec_group_start..self.types.len());
Ok(())
}
fn arbitrary_sub_type(&mut self, u: &mut Unstructured) -> Result<SubType> {
if !self.config.gc_enabled {
let composite_type = CompositeType {
inner: CompositeInnerType::Func(self.arbitrary_func_type(u)?),
shared: false,
};
return Ok(SubType {
is_final: true,
supertype: None,
composite_type,
});
}
if !self.can_subtype.is_empty() && u.ratio(1, 32_u8)? {
self.arbitrary_sub_type_of_super_type(u)
} else {
Ok(SubType {
is_final: u.arbitrary()?,
supertype: None,
composite_type: self.arbitrary_composite_type(u)?,
})
}
}
fn arbitrary_sub_type_of_super_type(&mut self, u: &mut Unstructured) -> Result<SubType> {
let supertype = *u.choose(&self.can_subtype)?;
let mut composite_type = self.types[usize::try_from(supertype).unwrap()]
.composite_type
.clone();
match &mut composite_type.inner {
CompositeInnerType::Array(a) => {
a.0 = self.arbitrary_matching_field_type(u, a.0)?;
}
CompositeInnerType::Func(f) => {
*f = self.arbitrary_matching_func_type(u, f)?;
}
CompositeInnerType::Struct(s) => {
*s = self.arbitrary_matching_struct_type(u, s)?;
}
}
Ok(SubType {
is_final: u.arbitrary()?,
supertype: Some(supertype),
composite_type,
})
}
fn arbitrary_matching_struct_type(
&mut self,
u: &mut Unstructured,
ty: &StructType,
) -> Result<StructType> {
let len_extra_fields = u.int_in_range(0..=5)?;
let mut fields = Vec::with_capacity(ty.fields.len() + len_extra_fields);
for field in ty.fields.iter() {
fields.push(self.arbitrary_matching_field_type(u, *field)?);
}
for _ in 0..len_extra_fields {
fields.push(self.arbitrary_field_type(u)?);
}
Ok(StructType {
fields: fields.into_boxed_slice(),
})
}
fn arbitrary_matching_field_type(
&mut self,
u: &mut Unstructured,
ty: FieldType,
) -> Result<FieldType> {
Ok(FieldType {
element_type: self.arbitrary_matching_storage_type(u, ty.element_type)?,
mutable: if ty.mutable { u.arbitrary()? } else { false },
})
}
fn arbitrary_matching_storage_type(
&mut self,
u: &mut Unstructured,
ty: StorageType,
) -> Result<StorageType> {
match ty {
StorageType::I8 => Ok(StorageType::I8),
StorageType::I16 => Ok(StorageType::I16),
StorageType::Val(ty) => Ok(StorageType::Val(self.arbitrary_matching_val_type(u, ty)?)),
}
}
fn arbitrary_matching_val_type(
&mut self,
u: &mut Unstructured,
ty: ValType,
) -> Result<ValType> {
match ty {
ValType::I32 => Ok(ValType::I32),
ValType::I64 => Ok(ValType::I64),
ValType::F32 => Ok(ValType::F32),
ValType::F64 => Ok(ValType::F64),
ValType::V128 => Ok(ValType::V128),
ValType::Ref(ty) => Ok(ValType::Ref(self.arbitrary_matching_ref_type(u, ty)?)),
}
}
fn arbitrary_matching_ref_type(&self, u: &mut Unstructured, ty: RefType) -> Result<RefType> {
Ok(RefType {
nullable: ty.nullable,
heap_type: self.arbitrary_matching_heap_type(u, ty.heap_type)?,
})
}
fn arbitrary_matching_heap_type(&self, u: &mut Unstructured, ty: HeapType) -> Result<HeapType> {
if !self.config.gc_enabled {
return Ok(ty);
}
use CompositeInnerType as CT;
use HeapType as HT;
let mut choices = vec![ty];
match ty {
HT::Abstract { shared, ty } => {
use AbstractHeapType::*;
let ht = |ty| HT::Abstract { shared, ty };
match ty {
Any => {
choices.extend([ht(Eq), ht(Struct), ht(Array), ht(I31), ht(None)]);
choices.extend(self.array_types.iter().copied().map(HT::Concrete));
choices.extend(self.struct_types.iter().copied().map(HT::Concrete));
}
Eq => {
choices.extend([ht(Struct), ht(Array), ht(I31), ht(None)]);
choices.extend(self.array_types.iter().copied().map(HT::Concrete));
choices.extend(self.struct_types.iter().copied().map(HT::Concrete));
}
Struct => {
choices.extend([ht(Struct), ht(None)]);
choices.extend(self.struct_types.iter().copied().map(HT::Concrete));
}
Array => {
choices.extend([ht(Array), ht(None)]);
choices.extend(self.array_types.iter().copied().map(HT::Concrete));
}
I31 => {
choices.push(ht(None));
}
Func => {
choices.extend(self.func_types.iter().copied().map(HT::Concrete));
choices.push(ht(NoFunc));
}
Extern => {
choices.push(ht(NoExtern));
}
Exn | NoExn | None | NoExtern | NoFunc => {}
}
}
HT::Concrete(idx) => {
if let Some(subs) = self.super_to_sub_types.get(&idx) {
choices.extend(subs.iter().copied().map(HT::Concrete));
}
match self
.types
.get(usize::try_from(idx).unwrap())
.map(|ty| (ty.composite_type.shared, &ty.composite_type.inner))
{
Some((shared, CT::Array(_) | CT::Struct(_))) => choices.push(HT::Abstract {
shared,
ty: AbstractHeapType::None,
}),
Some((shared, CT::Func(_))) => choices.push(HT::Abstract {
shared,
ty: AbstractHeapType::NoFunc,
}),
None => {
// The referenced type might be part of this same rec
// group we are currently generating, but not generated
// yet. In this case, leave `choices` as it is, and we
// will just end up choosing the original type again
// down below, which is fine.
}
}
}
}
Ok(*u.choose(&choices)?)
}
fn arbitrary_matching_func_type(
&mut self,
u: &mut Unstructured,
ty: &FuncType,
) -> Result<Rc<FuncType>> {
// Note: parameters are contravariant, results are covariant. See
// https://github.com/bytecodealliance/wasm-tools/blob/0616ef196a183cf137ee06b4a5993b7d590088bf/crates/wasmparser/src/readers/core/types/matches.rs#L137-L174
// for details.
let mut params = Vec::with_capacity(ty.params.len());
for param in &ty.params {
params.push(self.arbitrary_super_type_of_val_type(u, *param)?);
}
let mut results = Vec::with_capacity(ty.results.len());
for result in &ty.results {
results.push(self.arbitrary_matching_val_type(u, *result)?);
}
Ok(Rc::new(FuncType { params, results }))
}
fn arbitrary_super_type_of_val_type(
&mut self,
u: &mut Unstructured,
ty: ValType,
) -> Result<ValType> {
match ty {
ValType::I32 => Ok(ValType::I32),
ValType::I64 => Ok(ValType::I64),
ValType::F32 => Ok(ValType::F32),
ValType::F64 => Ok(ValType::F64),
ValType::V128 => Ok(ValType::V128),
ValType::Ref(ty) => Ok(ValType::Ref(self.arbitrary_super_type_of_ref_type(u, ty)?)),
}
}
fn arbitrary_super_type_of_ref_type(
&self,
u: &mut Unstructured,
ty: RefType,
) -> Result<RefType> {
Ok(RefType {
// TODO: For now, only create allow nullable reference
// types. Eventually we should support non-nullable reference types,
// but this means that we will also need to recognize when it is
// impossible to create an instance of the reference (eg `(ref
// nofunc)` has no instances, and self-referential types that
// contain a non-null self-reference are also impossible to create).
nullable: true,
heap_type: self.arbitrary_super_type_of_heap_type(u, ty.heap_type)?,
})
}
fn arbitrary_super_type_of_heap_type(
&self,
u: &mut Unstructured,
ty: HeapType,
) -> Result<HeapType> {
if !self.config.gc_enabled {
return Ok(ty);
}
use CompositeInnerType as CT;
use HeapType as HT;
let mut choices = vec![ty];
match ty {
HT::Abstract { shared, ty } => {
use AbstractHeapType::*;
let ht = |ty| HT::Abstract { shared, ty };
match ty {
None => {
choices.extend([ht(Any), ht(Eq), ht(Struct), ht(Array), ht(I31)]);
choices.extend(self.array_types.iter().copied().map(HT::Concrete));
choices.extend(self.struct_types.iter().copied().map(HT::Concrete));
}
NoExtern => {
choices.push(ht(Extern));
}
NoFunc => {
choices.extend(self.func_types.iter().copied().map(HT::Concrete));
choices.push(ht(Func));
}
NoExn => {
choices.push(ht(Exn));
}
Struct | Array | I31 => {
choices.extend([ht(Any), ht(Eq)]);
}
Eq => {
choices.push(ht(Any));
}
Exn | Any | Func | Extern => {}
}
}
HT::Concrete(mut idx) => {
if let Some(sub_ty) = &self.types.get(usize::try_from(idx).unwrap()) {
let ht = |ty| HT::Abstract {
shared: sub_ty.composite_type.shared,
ty,
};
match &sub_ty.composite_type.inner {
CT::Array(_) => {
choices.extend([
ht(AbstractHeapType::Any),
ht(AbstractHeapType::Eq),
ht(AbstractHeapType::Array),
]);
}
CT::Func(_) => {
choices.push(ht(AbstractHeapType::Func));
}
CT::Struct(_) => {
choices.extend([
ht(AbstractHeapType::Any),
ht(AbstractHeapType::Eq),
ht(AbstractHeapType::Struct),
]);
}
}
} else {
// Same as in `arbitrary_matching_heap_type`: this was a
// forward reference to a concrete type that is part of
// this same rec group we are generating right now, and
// therefore we haven't generated that type yet. Just
// leave `choices` as it is and we will choose the
// original type again down below.
}
while let Some(supertype) = self
.types
.get(usize::try_from(idx).unwrap())
.and_then(|ty| ty.supertype)
{
choices.push(HT::Concrete(supertype));
idx = supertype;
}
}
}
Ok(*u.choose(&choices)?)
}
fn arbitrary_composite_type(&mut self, u: &mut Unstructured) -> Result<CompositeType> {
use CompositeInnerType as CT;
let shared = false; // TODO: handle shared
if !self.config.gc_enabled {
return Ok(CompositeType {
shared,
inner: CT::Func(self.arbitrary_func_type(u)?),
});
}
match u.int_in_range(0..=2)? {
0 => Ok(CompositeType {
shared,
inner: CT::Array(ArrayType(self.arbitrary_field_type(u)?)),
}),
1 => Ok(CompositeType {
shared,
inner: CT::Func(self.arbitrary_func_type(u)?),
}),
2 => Ok(CompositeType {
shared,
inner: CT::Struct(self.arbitrary_struct_type(u)?),
}),
_ => unreachable!(),
}
}
fn arbitrary_struct_type(&mut self, u: &mut Unstructured) -> Result<StructType> {
let len = u.int_in_range(0..=20)?;
let mut fields = Vec::with_capacity(len);
for _ in 0..len {