-
Notifications
You must be signed in to change notification settings - Fork 256
/
Copy pathlib.rs
2328 lines (2147 loc) · 77.3 KB
/
lib.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
//! A WebAssembly test case generator.
//!
//! ## Usage
//!
//! First, use [`cargo fuzz`](https://github.com/rust-fuzz/cargo-fuzz) to define
//! a new fuzz target:
//!
//! ```shell
//! $ cargo fuzz add my_wasm_smith_fuzz_target
//! ```
//!
//! Next, add `wasm-smith` to your dependencies:
//!
//! ```toml
//! # fuzz/Cargo.toml
//!
//! [dependencies]
//! wasm-smith = "0.4.0"
//! ```
//!
//! Then, define your fuzz target so that it takes arbitrary
//! `wasm_smith::Module`s as an argument, convert the module into serialized
//! Wasm bytes via the `to_bytes` method, and then feed it into your system:
//!
//! ```no_run
//! // fuzz/fuzz_targets/my_wasm_smith_fuzz_target.rs
//!
//! #![no_main]
//!
//! use libfuzzer_sys::fuzz_target;
//! use wasm_smith::Module;
//!
//! fuzz_target!(|module: Module| {
//! let wasm_bytes = module.to_bytes();
//!
//! // Your code here...
//! });
//! ```
//!
//! Finally, start fuzzing:
//!
//! ```shell
//! $ cargo fuzz run my_wasm_smith_fuzz_target
//! ```
//!
//! > **Note:** For a real world example, also check out [the `validate` fuzz
//! > target](https://github.com/fitzgen/wasm-smith/blob/main/fuzz/fuzz_targets/validate.rs)
//! > defined in this repository. Using the `wasmparser` crate, it checks that
//! > every module generated by `wasm-smith` validates successfully.
#![deny(missing_docs, missing_debug_implementations)]
// Needed for the `instructions!` macro in `src/code_builder.rs`.
#![recursion_limit = "256"]
mod code_builder;
mod config;
mod encode;
mod terminate;
use crate::code_builder::CodeBuilderAllocations;
use arbitrary::{Arbitrary, Result, Unstructured};
use std::collections::{HashMap, HashSet};
use std::rc::Rc;
use std::str;
pub use config::{Config, DefaultConfig, SwarmConfig};
/// A pseudo-random WebAssembly module.
///
/// Construct instances of this type with [the `Arbitrary`
/// trait](https://docs.rs/arbitrary/*/arbitrary/trait.Arbitrary.html).
///
/// ## Configuring Generated Modules
///
/// This uses the [`DefaultConfig`][crate::DefaultConfig] configuration. If you
/// want to customize the shape of generated modules, define your own
/// configuration type, implement the [`Config`][crate::Config] trait for it,
/// and use [`ConfiguredModule<YourConfigType>`][crate::ConfiguredModule]
/// instead of plain `Module`.
#[derive(Debug, Default, Arbitrary)]
pub struct Module {
inner: ConfiguredModule<DefaultConfig>,
}
/// A pseudo-random generated WebAssembly file with custom configuration.
///
/// If you don't care about custom configuration, use [`Module`][crate::Module]
/// instead.
///
/// For details on configuring, see the [`Config`][crate::Config] trait.
#[derive(Debug, Default)]
pub struct ConfiguredModule<C>
where
C: Config,
{
config: C,
valtypes: Vec<ValType>,
/// Outer modules, if any (used for module linking)
outers: Vec<Outer>,
/// The initial sections of this wasm module, including types and imports.
/// This is stored as a list-of-lists where each `InitialSection` represents
/// a whole section, so this `initial_sections` list represents a list of
/// sections.
///
/// With the module linking proposal, types, imports, module, instance,
/// and alias sections can come in any order and occur repeatedly at the
/// start of a Wasm module. We want to generate interesting entities --
/// entities that require multiple, interspersed occurrences of these
/// sections -- and we don't want to always generate the "same shape" of
/// these initial sections. Each entry in this initializers list is one of
/// these initial sections, and we will directly encode each entry as a
/// section when we serialize this module to bytes, which allows us to
/// easily model the flexibility of the module linking proposal.
initial_sections: Vec<InitialSection<C>>,
/// A map of what import names have been generated. The key here is the
/// name of the import and the value is `None` if it's a single-level
/// import or `Some` if it's a two-level import with the set of
/// second-level import names that have been generated so far.
import_names: HashMap<String, Option<HashSet<String>>>,
/// Where within the `instances` array each implicit instance's type is
/// defined.
implicit_instance_types: HashMap<String, usize>,
/// All types locally defined in this module (available in the type index
/// space).
types: Vec<LocalType>,
/// Indices within `types` that are function types.
func_types: Vec<u32>,
/// Indices within `types` that are module types.
module_types: Vec<u32>,
/// Indices within `types` that are instance types.
instance_types: Vec<u32>,
/// Number of imported items into this module.
num_imports: usize,
/// Number of items aliased into this module.
num_aliases: usize,
/// The number of functions defined in this module (not imported or
/// aliased).
num_defined_funcs: usize,
/// The number of tables defined in this module (not imported or
/// aliased).
num_defined_tables: usize,
/// 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, Instruction)>,
/// 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.
///
/// Note that aliased functions may have types not defined in this module,
/// hence the optional index type. All defined functions in this module,
/// however, will have an index type specified.
funcs: Vec<(Option<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>,
/// All instances available to this module, sorted by their index. The list
/// entry is the type of the instance.
instances: Vec<Rc<InstanceType>>,
/// All modules available to this module, sorted by their index. The list
/// entry is the type of the module.
modules: Vec<Rc<ModuleType>>,
exports: Vec<(String, Export)>,
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,
}
impl<C: Config> ConfiguredModule<C> {
/// Returns a reference to the internal configuration.
pub fn config(&self) -> &C {
&self.config
}
}
impl<'a, C: Config> Arbitrary<'a> for ConfiguredModule<C> {
fn arbitrary(u: &mut Unstructured<'a>) -> Result<Self> {
let mut module = ConfiguredModule::<C>::default();
module.build(u, false)?;
Ok(module)
}
}
/// Same as [`Module`], but may be invalid.
///
/// This module generates function bodies differnetly than `Module` to try to
/// better explore wasm decoders and such.
#[derive(Debug, Default)]
pub struct MaybeInvalidModule {
module: Module,
}
impl MaybeInvalidModule {
/// Encode this Wasm module into bytes.
pub fn to_bytes(&self) -> Vec<u8> {
self.module.to_bytes()
}
}
impl<'a> Arbitrary<'a> for MaybeInvalidModule {
fn arbitrary(u: &mut Unstructured<'a>) -> Result<Self> {
let mut module = Module::default();
module.inner.build(u, true)?;
Ok(MaybeInvalidModule { module })
}
}
#[derive(Debug)]
enum InitialSection<C: Config> {
Type(Vec<Type>),
Import(Vec<(String, Option<String>, EntityType)>),
Alias(Vec<Alias>),
Instance(Vec<Instance>),
Module(Vec<ConfiguredModule<C>>),
}
#[derive(Clone, Debug)]
enum Type {
Func(Rc<FuncType>),
Module(Rc<ModuleType>),
Instance(Rc<InstanceType>),
}
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
struct FuncType {
params: Vec<ValType>,
results: Vec<ValType>,
}
#[derive(Clone, Debug, Default)]
struct InstanceType {
type_size: u32,
exports: indexmap::IndexMap<String, EntityType>,
}
#[derive(Clone, Debug)]
struct ModuleType {
type_size: u32,
imports: Vec<(String, Option<String>, EntityType)>,
import_types: indexmap::IndexMap<String, EntityType>,
/// The list of exports can be found in the `InstanceType` indirection here,
/// and this struct layout is used to ease the instantiation process where
/// we record an instance's signature.
exports: Rc<InstanceType>,
}
#[derive(Clone, Debug)]
enum EntityType {
Global(GlobalType),
Table(TableType),
Memory(MemoryType),
Func(u32, Rc<FuncType>),
Instance(u32, Rc<InstanceType>),
Module(u32, Rc<ModuleType>),
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
enum ValType {
I32,
I64,
F32,
F64,
FuncRef,
ExternRef,
}
#[derive(Clone, Debug)]
struct TableType {
limits: Limits,
elem_ty: ValType,
}
#[derive(Clone, Debug)]
struct MemoryType {
limits: Limits,
}
#[derive(Clone, Debug)]
struct Limits {
min: u32,
max: Option<u32>,
}
impl Limits {
fn limited(u: &mut Unstructured, max_minimum: u32, max_required: bool) -> Result<Self> {
let min = u.int_in_range(0..=max_minimum)?;
let max = if max_required || u.arbitrary().unwrap_or(false) {
Some(if min == max_minimum {
max_minimum
} else {
u.int_in_range(min..=max_minimum)?
})
} else {
None
};
Ok(Limits { min, max })
}
}
#[derive(Clone, Debug, PartialEq)]
struct GlobalType {
val_type: ValType,
mutable: bool,
}
#[derive(Clone, Debug)]
enum Alias {
InstanceExport {
instance: u32,
kind: ItemKind,
name: String,
},
OuterType {
depth: u32,
index: u32,
},
OuterModule {
depth: u32,
index: u32,
},
}
#[derive(Clone, Debug)]
struct Instance {
module: u32,
args: Vec<(String, Export)>,
}
#[derive(Copy, Clone, Debug)]
enum ItemKind {
Func,
Table,
Memory,
Global,
Instance,
Module,
}
#[derive(Copy, Clone, Debug)]
enum Export {
Func(u32),
Table(u32),
Memory(u32),
Global(u32),
Instance(u32),
Module(u32),
}
#[derive(Debug)]
struct ElementSegment {
kind: ElementKind,
ty: ValType,
items: Elements,
}
#[derive(Debug)]
enum ElementKind {
Passive,
Declared,
Active {
table: Option<u32>, // None == table 0 implicitly
offset: Instruction,
},
}
#[derive(Debug)]
enum Elements {
Functions(Vec<u32>),
Expressions(Vec<Option<u32>>),
}
#[derive(Debug)]
struct Code {
locals: Vec<ValType>,
instructions: Instructions,
}
#[derive(Debug)]
enum Instructions {
Generated(Vec<Instruction>),
Arbitrary(Vec<u8>),
}
#[derive(Clone, Copy, Debug)]
enum BlockType {
Empty,
Result(ValType),
FuncType(u32),
}
impl BlockType {
fn params_results<C>(&self, module: &ConfiguredModule<C>) -> (Vec<ValType>, Vec<ValType>)
where
C: Config,
{
match self {
BlockType::Empty => (vec![], vec![]),
BlockType::Result(t) => (vec![], vec![*t]),
BlockType::FuncType(ty) => {
let ty = module.func_type(*ty);
(ty.params.clone(), ty.results.clone())
}
}
}
}
#[derive(Clone, Copy, Debug)]
struct MemArg {
offset: u32,
align: u32,
memory_index: u32,
}
#[derive(Clone, Debug)]
#[allow(non_camel_case_types)]
enum Instruction {
// Control instructions.
Unreachable,
Nop,
Block(BlockType),
Loop(BlockType),
If(BlockType),
Else,
End,
Br(u32),
BrIf(u32),
BrTable(Vec<u32>, u32),
Return,
Call(u32),
CallIndirect { ty: u32, table: u32 },
// Parametric instructions.
Drop,
Select,
// Variable instructions.
LocalGet(u32),
LocalSet(u32),
LocalTee(u32),
GlobalGet(u32),
GlobalSet(u32),
// Memory instructions.
I32Load(MemArg),
I64Load(MemArg),
F32Load(MemArg),
F64Load(MemArg),
I32Load8_S(MemArg),
I32Load8_U(MemArg),
I32Load16_S(MemArg),
I32Load16_U(MemArg),
I64Load8_S(MemArg),
I64Load8_U(MemArg),
I64Load16_S(MemArg),
I64Load16_U(MemArg),
I64Load32_S(MemArg),
I64Load32_U(MemArg),
I32Store(MemArg),
I64Store(MemArg),
F32Store(MemArg),
F64Store(MemArg),
I32Store8(MemArg),
I32Store16(MemArg),
I64Store8(MemArg),
I64Store16(MemArg),
I64Store32(MemArg),
MemorySize(u32),
MemoryGrow(u32),
MemoryInit { mem: u32, data: u32 },
DataDrop(u32),
MemoryCopy { src: u32, dst: u32 },
MemoryFill(u32),
// Numeric instructions.
I32Const(i32),
I64Const(i64),
F32Const(f32),
F64Const(f64),
I32Eqz,
I32Eq,
I32Neq,
I32LtS,
I32LtU,
I32GtS,
I32GtU,
I32LeS,
I32LeU,
I32GeS,
I32GeU,
I64Eqz,
I64Eq,
I64Neq,
I64LtS,
I64LtU,
I64GtS,
I64GtU,
I64LeS,
I64LeU,
I64GeS,
I64GeU,
F32Eq,
F32Neq,
F32Lt,
F32Gt,
F32Le,
F32Ge,
F64Eq,
F64Neq,
F64Lt,
F64Gt,
F64Le,
F64Ge,
I32Clz,
I32Ctz,
I32Popcnt,
I32Add,
I32Sub,
I32Mul,
I32DivS,
I32DivU,
I32RemS,
I32RemU,
I32And,
I32Or,
I32Xor,
I32Shl,
I32ShrS,
I32ShrU,
I32Rotl,
I32Rotr,
I64Clz,
I64Ctz,
I64Popcnt,
I64Add,
I64Sub,
I64Mul,
I64DivS,
I64DivU,
I64RemS,
I64RemU,
I64And,
I64Or,
I64Xor,
I64Shl,
I64ShrS,
I64ShrU,
I64Rotl,
I64Rotr,
F32Abs,
F32Neg,
F32Ceil,
F32Floor,
F32Trunc,
F32Nearest,
F32Sqrt,
F32Add,
F32Sub,
F32Mul,
F32Div,
F32Min,
F32Max,
F32Copysign,
F64Abs,
F64Neg,
F64Ceil,
F64Floor,
F64Trunc,
F64Nearest,
F64Sqrt,
F64Add,
F64Sub,
F64Mul,
F64Div,
F64Min,
F64Max,
F64Copysign,
I32WrapI64,
I32TruncF32S,
I32TruncF32U,
I32TruncF64S,
I32TruncF64U,
I64ExtendI32S,
I64ExtendI32U,
I64TruncF32S,
I64TruncF32U,
I64TruncF64S,
I64TruncF64U,
F32ConvertI32S,
F32ConvertI32U,
F32ConvertI64S,
F32ConvertI64U,
F32DemoteF64,
F64ConvertI32S,
F64ConvertI32U,
F64ConvertI64S,
F64ConvertI64U,
F64PromoteF32,
I32ReinterpretF32,
I64ReinterpretF64,
F32ReinterpretI32,
F64ReinterpretI64,
I32Extend8S,
I32Extend16S,
I64Extend8S,
I64Extend16S,
I64Extend32S,
I32TruncSatF32S,
I32TruncSatF32U,
I32TruncSatF64S,
I32TruncSatF64U,
I64TruncSatF32S,
I64TruncSatF32U,
I64TruncSatF64S,
I64TruncSatF64U,
TypedSelect(ValType),
RefNull(ValType),
RefIsNull,
RefFunc(u32),
TableInit { segment: u32, table: u32 },
ElemDrop { segment: u32 },
TableFill { table: u32 },
TableSet { table: u32 },
TableGet { table: u32 },
TableGrow { table: u32 },
TableSize { table: u32 },
TableCopy { src: u32, dst: u32 },
}
#[derive(Debug)]
struct DataSegment {
kind: DataSegmentKind,
init: Vec<u8>,
}
#[derive(Debug)]
enum DataSegmentKind {
Passive,
Active {
memory_index: u32,
offset: Instruction,
},
}
impl<C> ConfiguredModule<C>
where
C: Config,
{
fn build(&mut self, u: &mut Unstructured, allow_invalid: bool) -> Result<()> {
self.config = C::arbitrary(u)?;
self.valtypes.push(ValType::I32);
self.valtypes.push(ValType::I64);
self.valtypes.push(ValType::F32);
self.valtypes.push(ValType::F64);
if self.config.reference_types_enabled() {
self.valtypes.push(ValType::ExternRef);
self.valtypes.push(ValType::FuncRef);
}
self.arbitrary_initial_sections(u)?;
self.arbitrary_funcs(u)?;
self.arbitrary_tables(u)?;
self.arbitrary_memories(u)?;
self.arbitrary_globals(u)?;
self.arbitrary_exports(u)?;
self.arbitrary_start(u)?;
self.arbitrary_elems(u)?;
self.arbitrary_data(u)?;
self.arbitrary_code(u, allow_invalid)?;
Ok(())
}
fn arbitrary_initial_sections(&mut self, u: &mut Unstructured) -> Result<()> {
let mut aliases = AvailableAliases::default();
let mut instantiations = AvailableInstantiations::default();
if !self.config.module_linking_enabled() {
self.arbitrary_types(self.config.min_types(), u)?;
self.arbitrary_imports(self.config.min_imports(), u)?;
return Ok(());
}
let mut choices: Vec<
fn(
&mut Unstructured,
&mut ConfiguredModule<C>,
&mut AvailableAliases,
&mut AvailableInstantiations,
) -> Result<()>,
> = Vec::new();
loop {
choices.clear();
if self.types.len() < self.config.max_types() {
choices.push(|u, m, _, _| m.arbitrary_types(0, u));
}
if self.num_imports < self.config.max_imports() {
choices.push(|u, m, _, _| m.arbitrary_imports(0, u));
}
if self.modules.len() < self.config.max_modules()
&& self.outers.len() < self.config.max_nesting_depth()
{
choices.push(|u, m, _, _| m.arbitrary_modules(u));
}
aliases.update(self);
if self.num_aliases < self.config.max_aliases() && aliases.aliases.len() > 0 {
choices.push(|u, m, a, _| m.arbitrary_aliases(a, u));
}
instantiations.update(self);
if self.instances.len() < self.config.max_instances() {
choices.push(|u, m, _, i| m.arbitrary_instances(i, u));
}
if choices.is_empty() || !u.arbitrary()? {
break;
}
u.choose(&choices)?(u, self, &mut aliases, &mut instantiations)?;
}
// If after generating a list of sections we haven't met our
// minimum quotas then meet them now.
if self.types.len() < self.config.min_types() {
self.arbitrary_types(self.config.min_types() - self.types.len(), u)?;
}
if self.num_imports < self.config.min_imports() {
self.arbitrary_imports(self.config.min_imports() - self.num_imports, u)?;
}
Ok(())
}
fn arbitrary_types(&mut self, min: usize, u: &mut Unstructured) -> Result<()> {
// Note that we push to `self.initializers` immediately because types
// can mention any previous types, so we need to ensure that after each
// type is generated it's listed in the module's types so indexing will
// succeed.
let section_idx = self.initial_sections.len();
self.initial_sections.push(InitialSection::Type(Vec::new()));
arbitrary_loop(u, min, self.config.max_types() - self.types.len(), |u| {
let ty = self.arbitrary_type(u)?;
self.record_type(&ty);
let types = match self.initial_sections.last_mut().unwrap() {
InitialSection::Type(list) => list,
_ => unreachable!(),
};
self.types.push(LocalType::Defined {
section: section_idx,
nth: types.len(),
});
types.push(ty);
Ok(true)
})?;
let types = match self.initial_sections.last_mut().unwrap() {
InitialSection::Type(list) => list,
_ => unreachable!(),
};
if types.is_empty() && !u.arbitrary()? {
self.initial_sections.pop();
}
Ok(())
}
fn record_type(&mut self, ty: &Type) {
let list = match &ty {
Type::Func(_) => &mut self.func_types,
Type::Module(_) => &mut self.module_types,
Type::Instance(_) => &mut self.instance_types,
};
list.push(self.types.len() as u32);
}
fn arbitrary_type(&mut self, u: &mut Unstructured) -> Result<Type> {
if !self.config.module_linking_enabled() {
return Ok(Type::Func(self.arbitrary_func_type(u)?));
}
Ok(match u.int_in_range(0..=2)? {
0 => Type::Func(self.arbitrary_func_type(u)?),
1 => Type::Module(self.arbitrary_module_type(u, &mut Entities::default())?),
_ => Type::Instance(self.arbitrary_instance_type(u, &mut Entities::default())?),
})
}
fn arbitrary_func_type(&mut self, u: &mut Unstructured) -> Result<Rc<FuncType>> {
let mut params = vec![];
let mut results = vec![];
arbitrary_loop(u, 0, 20, |u| {
params.push(self.arbitrary_valtype(u)?);
Ok(true)
})?;
arbitrary_loop(u, 0, 20, |u| {
results.push(self.arbitrary_valtype(u)?);
Ok(true)
})?;
Ok(Rc::new(FuncType { params, results }))
}
fn arbitrary_module_type(
&mut self,
u: &mut Unstructured,
entities: &mut Entities,
) -> Result<Rc<ModuleType>> {
let exports = self.arbitrary_instance_type(u, entities)?;
let mut imports = Vec::new();
let mut import_types = indexmap::IndexMap::new();
let mut names = HashMap::new();
let mut type_size = exports.type_size;
if !entities.max_reached(&self.config) {
arbitrary_loop(u, 0, self.config.max_imports(), |u| {
let (module, name) = unique_import_strings(1_000, &mut names, true, u)?;
let ty = self.arbitrary_entity_type(u, entities)?;
match type_size.checked_add(ty.size() + 1) {
Some(s) if s < self.config.max_type_size() => type_size = s,
_ => return Ok(false),
}
if let Some(name) = &name {
let ity = import_types.entry(module.clone()).or_insert_with(|| {
EntityType::Instance(u32::max_value(), Default::default())
});
let ity = match ity {
EntityType::Instance(_, ty) => Rc::get_mut(ty).unwrap(),
_ => unreachable!(),
};
ity.exports.insert(name.clone(), ty.clone());
} else {
import_types.insert(module.clone(), ty.clone());
}
imports.push((module, name, ty));
Ok(!entities.max_reached(&self.config))
})?;
}
Ok(Rc::new(ModuleType {
type_size,
imports,
import_types,
exports,
}))
}
fn arbitrary_instance_type(
&mut self,
u: &mut Unstructured,
entities: &mut Entities,
) -> Result<Rc<InstanceType>> {
let mut export_names = HashSet::new();
let mut exports = indexmap::IndexMap::new();
let mut type_size = 0u32;
if !entities.max_reached(&self.config) {
arbitrary_loop(u, 0, self.config.max_exports(), |u| {
let name = unique_string(1_000, &mut export_names, u)?;
let ty = self.arbitrary_entity_type(u, entities)?;
match type_size.checked_add(ty.size() + 1) {
Some(s) if s < self.config.max_type_size() => type_size = s,
_ => return Ok(false),
}
exports.insert(name, ty);
Ok(!entities.max_reached(&self.config))
})?;
}
Ok(Rc::new(InstanceType { type_size, exports }))
}
fn arbitrary_entity_type(
&mut self,
u: &mut Unstructured,
entities: &mut Entities,
) -> Result<EntityType> {
let mut choices: Vec<
fn(&mut Unstructured, &mut ConfiguredModule<C>, &mut Entities) -> Result<EntityType>,
> = Vec::with_capacity(6);
if entities.globals < self.config.max_globals() {
choices.push(|u, m, e| {
e.globals += 1;
Ok(EntityType::Global(m.arbitrary_global_type(u)?))
});
}
if entities.memories < self.config.max_memories() {
choices.push(|u, m, e| {
e.memories += 1;
Ok(EntityType::Memory(m.arbitrary_memtype(u)?))
});
}
if entities.tables < self.config.max_tables() {
choices.push(|u, m, e| {
e.tables += 1;
Ok(EntityType::Table(m.arbitrary_table_type(u)?))
});
}
if entities.funcs < self.config.max_funcs() && self.func_types.len() > 0 {
choices.push(|u, m, e| {
e.funcs += 1;
let idx = *u.choose(&m.func_types)?;
let ty = m.func_type(idx);
Ok(EntityType::Func(idx, ty.clone()))
});
}
if entities.instances < self.config.max_instances() && self.instance_types.len() > 0 {
choices.push(|u, m, e| {
e.instances += 1;
let idx = *u.choose(&m.instance_types)?;
let ty = m.instance_type(idx);
Ok(EntityType::Instance(idx, ty.clone()))
});
}
if entities.modules < self.config.max_modules() && self.module_types.len() > 0 {
choices.push(|u, m, e| {
e.modules += 1;
let idx = *u.choose(&m.module_types)?;
let ty = m.module_type(idx);
Ok(EntityType::Module(idx, ty.clone()))
});
}
u.choose(&choices)?(u, self, entities)
}
fn can_add_local_or_import_func(&self) -> bool {
self.func_types.len() > 0 && self.funcs.len() < self.config.max_funcs()
}
fn can_add_local_or_import_instance(&self) -> bool {
self.instance_types.len() > 0 && self.instances.len() < self.config.max_instances()
}
fn can_add_local_or_import_module(&self) -> bool {
self.module_types.len() > 0 && self.modules.len() < self.config.max_modules()
}
fn can_add_local_or_import_table(&self) -> bool {
self.tables.len() < self.config.max_tables()
}
fn can_add_local_or_import_global(&self) -> bool {
self.globals.len() < self.config.max_globals()
}
fn can_add_local_or_import_memory(&self) -> bool {
self.memories.len() < self.config.max_memories()
}
fn arbitrary_imports(&mut self, min: usize, u: &mut Unstructured) -> Result<()> {
if self.config.max_type_size() < self.type_size {
return Ok(());
}
let mut choices: Vec<
fn(&mut Unstructured, &mut ConfiguredModule<C>) -> Result<EntityType>,
> = Vec::with_capacity(4);
let mut imports = Vec::new();
arbitrary_loop(u, min, self.config.max_imports() - self.num_imports, |u| {
choices.clear();
if self.can_add_local_or_import_func() {
choices.push(|u, m| {
let idx = *u.choose(&m.func_types)?;
let ty = m.func_type(idx).clone();
Ok(EntityType::Func(idx, ty))
});
}
if self.can_add_local_or_import_module() {
choices.push(|u, m| {
let idx = *u.choose(&m.module_types)?;
let ty = m.module_type(idx).clone();
Ok(EntityType::Module(idx, ty.clone()))
});
}
if self.can_add_local_or_import_instance() {
choices.push(|u, m| {
let idx = *u.choose(&m.instance_types)?;
let ty = m.instance_type(idx).clone();
Ok(EntityType::Instance(idx, ty))
});
}
if self.can_add_local_or_import_global() {
choices.push(|u, m| {
let ty = m.arbitrary_global_type(u)?;