Coverage Report

Created: 2026-11-23 07:59

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/wasm-tools/crates/wasm-smith/src/config.rs
Line
Count
Source
1
//! Configuring the shape of generated Wasm modules.
2
3
use crate::InstructionKinds;
4
use anyhow::bail;
5
use arbitrary::{Arbitrary, Result, Unstructured};
6
7
macro_rules! define_config {
8
    (
9
        $(#[$attr:meta])*
10
        pub struct Config {
11
            $(
12
                $(#[$field_attr:meta])*
13
                pub $field:ident : $field_ty:ty = $default:expr,
14
            )*
15
        }
16
    ) => {
17
        $(#[$attr])*
18
        pub struct Config {
19
            /// The imports that may be used when generating the module.
20
            ///
21
            /// Defaults to `None` which means that any arbitrary import can be
22
            /// generated.
23
            ///
24
            /// To only allow specific imports, set this field to a WebAssembly
25
            /// module which describes the imports allowed.
26
            ///
27
            /// Note that [`Self::min_imports`] is ignored when
28
            /// `available_imports` are enabled.
29
            ///
30
            /// The provided value must be a valid binary encoding of a
31
            /// WebAssembly module. `wasm-smith` will panic if the module cannot
32
            /// be parsed.
33
            ///
34
            /// # Example
35
            ///
36
            /// An implementation of this method could use the `wat` crate to
37
            /// provide a human-readable and maintainable description:
38
            ///
39
            /// ```rust
40
            /// Some(wat::parse_str(r#"
41
            ///     (module
42
            ///         (import "env" "ping" (func (param i32)))
43
            ///         (import "env" "pong" (func (result i32)))
44
            ///         (import "env" "memory" (memory 1))
45
            ///         (import "env" "table" (table 1))
46
            ///         (import "env" "tag" (tag (param i32)))
47
            ///     )
48
            /// "#))
49
            /// # ;
50
            /// ```
51
            pub available_imports: Option<Vec<u8>>,
52
53
            /// If provided, the generated module will have exports with exactly
54
            /// the same names and types as those in the provided WebAssembly
55
            /// module. The implementation (e.g. function bodies, global
56
            /// initializers) of each export in the generated module will be
57
            /// random and unrelated to the implementation in the provided
58
            /// module.
59
            ///
60
            ///
61
            /// Defaults to `None` which means arbitrary exports will be
62
            /// generated.
63
            ///
64
            /// To specify which exports the generated modules should have, set
65
            /// this field to a WebAssembly module which describes the desired
66
            /// exports. To generate modules with varying exports that meet some
67
            /// constraints, consider randomly generating the value for this
68
            /// field.
69
            ///
70
            /// The provided value must be a valid binary encoding of a
71
            /// WebAssembly module. `wasm-smith` will panic if the module cannot
72
            /// be parsed.
73
            ///
74
            /// # Module Limits
75
            ///
76
            /// All types, functions, globals, memories, tables, tags, and exports
77
            /// that are needed to provide the required exports will be generated,
78
            /// even if it causes the resulting module to exceed the limits defined
79
            /// in [`Self::max_type_size`], [`Self::max_types`],
80
            /// [`Self::max_funcs`], [`Self::max_globals`],
81
            /// [`Self::max_memories`], [`Self::max_tables`],
82
            /// [`Self::max_tags`], or [`Self::max_exports`].
83
            ///
84
            /// # Example
85
            ///
86
            /// As for [`Self::available_imports`], the `wat` crate can be used
87
            /// to provide an human-readable description of the desired exports:
88
            ///
89
            /// ```rust
90
            /// Some(wat::parse_str(r#"
91
            ///     (module
92
            ///         (func (export "foo") (param i32) (result i64) unreachable)
93
            ///         (global (export "bar") f32 f32.const 0)
94
            ///         (memory (export "baz") 1 10)
95
            ///         (table (export "qux") 5 10 (ref null extern))
96
            ///         (tag (export "quux") (param f32))
97
            ///     )
98
            /// "#));
99
            /// ```
100
            pub exports: Option<Vec<u8>>,
101
102
            /// If provided, the generated module will have imports and exports
103
            /// with exactly the same names and types as those in the provided
104
            /// WebAssembly module.
105
            ///
106
            /// When `compact_imports_enabled` is enabled, the import section preserves
107
            /// the source entries' order and their `Single`, `Compact1`, and `Compact2`
108
            /// grouping. Empty compact groups are omitted.
109
            /// When `compact_imports_enabled` is disabled,
110
            /// compact groups are emitted as ordinary imports.
111
            ///
112
            /// Defaults to `None` which means arbitrary imports and exports will be
113
            /// generated.
114
            ///
115
            /// Note that [`Self::available_imports`] and [`Self::exports`] are
116
            /// ignored when `module_shape` is enabled.
117
            ///
118
            /// The provided value must be a valid binary encoding of a
119
            /// WebAssembly module. `wasm-smith` will panic if the module cannot
120
            /// be parsed.
121
            ///
122
            /// # Module Limits
123
            ///
124
            /// All types, functions, globals, memories, tables, tags, imports, and exports
125
            /// that are needed to provide the required imports and exports will be generated,
126
            /// even if it causes the resulting module to exceed the limits defined in
127
            /// [`Self::max_type_size`], [`Self::max_types`], [`Self::max_funcs`],
128
            /// [`Self::max_globals`], [`Self::max_memories`], [`Self::max_tables`],
129
            /// [`Self::max_tags`], [`Self::max_imports`], or [`Self::max_exports`].
130
            ///
131
            /// # Example
132
            ///
133
            /// As for [`Self::available_imports`] and [`Self::exports`], the
134
            /// `wat` crate can be used to provide a human-readable description of the
135
            /// module shape:
136
            ///
137
            /// ```rust
138
            /// Some(wat::parse_str(r#"
139
            ///     (module
140
            ///         (import "env" "ping" (func (param i32)))
141
            ///         (import "env" "memory" (memory 1))
142
            ///         (func (export "foo") (param anyref) (result structref) unreachable)
143
            ///         (global (export "bar") arrayref (ref.null array))
144
            ///     )
145
            /// "#));
146
            /// ```
147
            pub module_shape: Option<Vec<u8>>,
148
149
            $(
150
                $(#[$field_attr])*
151
                pub $field: $field_ty,
152
            )*
153
        }
154
155
        impl Default for Config {
156
0
            fn default() -> Config {
157
0
                Config {
158
0
                    available_imports: None,
159
0
                    exports: None,
160
0
                    module_shape: None,
161
0
162
0
                    $(
163
0
                        $field: $default,
164
0
                    )*
165
0
                }
166
0
            }
167
        }
168
169
        #[doc(hidden)]
170
        #[derive(Clone, Debug, Default)]
171
        #[cfg_attr(feature = "clap", derive(clap::Parser))]
172
        #[cfg_attr(feature = "serde", derive(serde_derive::Deserialize, serde_derive::Serialize))]
173
        #[cfg_attr(feature = "serde", serde(rename_all = "kebab-case", deny_unknown_fields))]
174
        pub struct InternalOptionalConfig {
175
            /// The imports that may be used when generating the module.
176
            ///
177
            /// When unspecified, any arbitrary import can be generated.
178
            ///
179
            /// To only allow specific imports, provide a file path of a
180
            /// WebAssembly module which describes the imports allowed.
181
            ///
182
            /// Note that [`Self::min_imports`] is ignored when
183
            /// `available_imports` are enabled.
184
            ///
185
            /// The provided value must be a valid binary encoding of a
186
            /// WebAssembly module. `wasm-smith` will panic if the module cannot
187
            /// be parsed.
188
            #[cfg_attr(feature = "clap", clap(long))]
189
            available_imports: Option<std::path::PathBuf>,
190
191
            /// If provided, the generated module will have exports with exactly
192
            /// the same names and types as those in the provided WebAssembly
193
            /// module. The implementation (e.g. function bodies, global
194
            /// initializers) of each export in the generated module will be
195
            /// random and unrelated to the implementation in the provided
196
            /// module.
197
            ///
198
            /// Defaults to `None` which means arbitrary exports will be
199
            /// generated.
200
            ///
201
            /// To specify which exports the generated modules should have, set
202
            /// this field to a WebAssembly module which describes the desired
203
            /// exports. To generate modules with varying exports that meet some
204
            /// constraints, consider randomly generating the value for this
205
            /// field.
206
            ///
207
            /// The provided value must be a valid binary encoding of a
208
            /// WebAssembly module. `wasm-smith` will panic if the module cannot
209
            /// be parsed.
210
            ///
211
            /// # Module Limits
212
            ///
213
            /// All types, functions, globals, memories, tables, tags, and exports
214
            /// that are needed to provide the required exports will be generated,
215
            /// even if it causes the resulting module to exceed the limits defined
216
            /// in [`Self::max_type_size`], [`Self::max_types`],
217
            /// [`Self::max_funcs`], [`Self::max_globals`],
218
            /// [`Self::max_memories`], [`Self::max_tables`],
219
            /// [`Self::max_tags`], or [`Self::max_exports`].
220
            ///
221
            #[cfg_attr(feature = "clap", clap(long))]
222
            exports: Option<std::path::PathBuf>,
223
224
            /// If provided, the generated module will have imports and exports
225
            /// with exactly the same names and types as those in the provided
226
            /// WebAssembly module.
227
            ///
228
            /// When `compact_imports_enabled` is enabled, the import section preserves
229
            /// the source entries' order and their `Single`, `Compact1`, and `Compact2`
230
            /// grouping. Empty compact groups are omitted.
231
            /// When `compact_imports_enabled` is disabled,
232
            /// compact groups are emitted as ordinary imports.
233
            ///
234
            /// Defaults to `None` which means arbitrary imports and exports will be
235
            /// generated.
236
            ///
237
            /// Note that [`Self::available_imports`] and [`Self::exports`] are
238
            /// ignored when `module_shape` is enabled.
239
            ///
240
            /// The provided value must be a valid binary encoding of a
241
            /// WebAssembly module. `wasm-smith` will panic if the module cannot
242
            /// be parsed.
243
            ///
244
            /// # Module Limits
245
            ///
246
            /// All types, functions, globals, memories, tables, tags, imports, and exports
247
            /// that are needed to provide the required imports and exports will be generated,
248
            /// even if it causes the resulting module to exceed the limits defined in
249
            /// [`Self::max_type_size`], [`Self::max_types`], [`Self::max_funcs`],
250
            /// [`Self::max_globals`], [`Self::max_memories`], [`Self::max_tables`],
251
            /// [`Self::max_tags`], [`Self::max_imports`], or [`Self::max_exports`].
252
            #[cfg_attr(feature = "clap", clap(long))]
253
            module_shape: Option<std::path::PathBuf>,
254
255
            $(
256
                $(#[$field_attr])*
257
                #[cfg_attr(feature = "clap", clap(long))]
258
                pub $field: Option<$field_ty>,
259
            )*
260
        }
261
262
        impl InternalOptionalConfig {
263
0
            pub fn or(self, other: Self) -> Self {
264
0
                Self {
265
0
                    available_imports: self.available_imports.or(other.available_imports),
266
0
                    exports: self.exports.or(other.exports),
267
0
                    module_shape: self.module_shape.or(other.module_shape),
268
0
269
0
                    $(
270
0
                        $field: self.$field.or(other.$field),
271
0
                    )*
272
0
                }
273
0
            }
274
        }
275
276
        #[cfg(feature = "serde")]
277
        impl TryFrom<InternalOptionalConfig> for Config {
278
            type Error = anyhow::Error;
279
            fn try_from(config: InternalOptionalConfig) -> anyhow::Result<Config> {
280
                let default = Config::default();
281
                Ok(Config {
282
                    available_imports: if let Some(file) = config
283
                        .available_imports
284
                        .as_ref() {
285
                            Some(wat::parse_file(file)?)
286
                        } else {
287
                            None
288
                        },
289
                    exports: if let Some(file) = config
290
                        .exports
291
                        .as_ref() {
292
                            Some(wat::parse_file(file)?)
293
                        } else {
294
                            None
295
                        },
296
                    module_shape: if let Some(file) = config
297
                        .module_shape
298
                        .as_ref() {
299
                            Some(wat::parse_file(file)?)
300
                        } else {
301
                            None
302
                        },
303
304
                    $(
305
                        $field: config.$field.unwrap_or(default.$field),
306
                    )*
307
                })
308
            }
309
        }
310
311
        impl TryFrom<&Config> for InternalOptionalConfig {
312
            type Error = anyhow::Error;
313
0
            fn try_from(config: &Config) -> anyhow::Result<InternalOptionalConfig> {
314
0
                if config.available_imports.is_some() {
315
0
                    bail!("cannot serialize configuration with `available_imports`");
316
0
                }
317
0
                if config.exports.is_some() {
318
0
                    bail!("cannot serialize configuration with `exports`");
319
0
                }
320
0
                if config.module_shape.is_some() {
321
0
                    bail!("cannot serialize configuration with `module_shape`");
322
0
                }
323
0
                Ok(InternalOptionalConfig {
324
0
                    available_imports: None,
325
0
                    exports: None,
326
0
                    module_shape: None,
327
0
                    $( $field: Some(config.$field.clone()), )*
328
0
                })
329
0
            }
330
        }
331
    }
332
}
333
334
define_config! {
335
    /// Configuration for a generated module.
336
    ///
337
    /// Don't care to configure your generated modules? Just use
338
    /// [`Module::arbitrary`][crate::Module], which internally uses the default
339
    /// configuration.
340
    ///
341
    /// Want control over the shape of the module that gets generated? Create a
342
    /// `Config` and then pass it to [`Module::new`][crate::Module::new].
343
    ///
344
    /// # Swarm Testing
345
    ///
346
    /// You can use the `Arbitrary for Config` implementation for [swarm
347
    /// testing]. This will dynamically -- but still deterministically -- choose
348
    /// configuration options for you.
349
    ///
350
    /// [swarm testing]: https://www.cs.utah.edu/~regehr/papers/swarm12.pdf
351
    ///
352
    /// Note that we pick only *maximums*, not minimums, here because it is more
353
    /// complex to describe the domain of valid configs when minima are involved
354
    /// (`min <= max` for each variable) and minima are mostly used to ensure
355
    /// certain elements are present, but do not widen the range of generated
356
    /// Wasm modules.
357
    #[derive(Clone, Debug)]
358
    pub struct Config {
359
        /// Determines whether a `start` export may be included. Defaults to `true`.
360
        pub allow_start_export: bool = true,
361
362
        /// The kinds of instructions allowed in the generated wasm
363
        /// programs. Defaults to all.
364
        ///
365
        /// The categories of instructions match the categories used by the
366
        /// [WebAssembly
367
        /// specification](https://webassembly.github.io/spec/core/syntax/instructions.html);
368
        /// e.g., numeric, vector, control, memory, etc.
369
        ///
370
        /// Additionally, we include finer-grained categories which exclude floating point
371
        /// instructions, e.g. [`InstructionKind::NumericInt`] is a subset of
372
        /// [`InstructionKind::Numeric`] consisting of all numeric instructions which
373
        /// don't involve floats.
374
        ///
375
        /// Note that modifying this setting is separate from the proposal
376
        /// flags; that is, if `simd_enabled() == true` but
377
        /// `allowed_instruction()` does not include vector instructions, the
378
        /// generated programs will not include these instructions but could
379
        /// contain vector types.
380
        ///
381
        /// [`InstructionKind::Numeric`]: crate::InstructionKind::Numeric
382
        /// [`InstructionKind::NumericInt`]: crate::InstructionKind::NumericInt
383
        pub allowed_instructions: InstructionKinds = InstructionKinds::all(),
384
385
        /// Determines whether we generate floating point instructions and types.
386
        ///
387
        /// Defaults to `true`.
388
        pub allow_floats: bool = true,
389
390
        /// Determines whether the bulk memory proposal is enabled for
391
        /// generating instructions.
392
        ///
393
        /// Defaults to `true`.
394
        pub bulk_memory_enabled: bool = true,
395
396
        /// Returns whether NaN values are canonicalized after all f32/f64
397
        /// operation. Defaults to false.
398
        ///
399
        /// This can be useful when a generated wasm module is executed in
400
        /// multiple runtimes which may produce different NaN values. This
401
        /// ensures that the generated module will always use the same NaN
402
        /// representation for all instructions which have visible side effects,
403
        /// for example writing floats to memory or float-to-int bitcast
404
        /// instructions.
405
        pub canonicalize_nans: bool = false,
406
407
        /// Returns whether we should avoid generating code that will possibly
408
        /// trap.
409
        ///
410
        /// For some trapping instructions, this will emit extra instructions to
411
        /// ensure they don't trap, while some instructions will simply be
412
        /// excluded.  In cases where we would run into a trap, we instead
413
        /// choose some arbitrary non-trapping behavior. For example, if we
414
        /// detect that a Load instruction would attempt to access out-of-bounds
415
        /// memory, we instead pretend the load succeeded and push 0 onto the
416
        /// stack.
417
        ///
418
        /// One type of trap that we can't currently avoid is
419
        /// StackOverflow. Even when `disallow_traps` is set to true, wasm-smith
420
        /// will eventually generate a program that infinitely recurses, causing
421
        /// the call stack to be exhausted.
422
        ///
423
        /// Defaults to `false`.
424
        pub disallow_traps: bool = false,
425
426
        /// Determines whether the exception-handling proposal is enabled for
427
        /// generating instructions.
428
        ///
429
        /// Defaults to `true`.
430
        pub exceptions_enabled: bool = true,
431
432
        /// Export all WebAssembly objects in the module. Defaults to false.
433
        ///
434
        /// This overrides [`Config::min_exports`] and [`Config::max_exports`].
435
        pub export_everything: bool = false,
436
437
        /// Determines whether the GC proposal is enabled when generating a Wasm
438
        /// module.
439
        ///
440
        /// Defaults to `true`.
441
        pub gc_enabled: bool = true,
442
443
        /// Determines whether compact import section proposal is enabled.
444
        ///
445
        /// Defaults to `true`.
446
        pub compact_imports_enabled: bool = true,
447
448
        /// Determines whether the custom descriptors proposal is enabled when
449
        /// generating a Wasm module.
450
        ///
451
        /// Defaults to `true`.
452
        pub custom_descriptors_enabled: bool = false,
453
454
        /// Determines whether the custom-page-sizes proposal is enabled when
455
        /// generating a Wasm module.
456
        ///
457
        /// Defaults to `false`.
458
        pub custom_page_sizes_enabled: bool = false,
459
460
        /// Determines whether the [branch-hinting proposal] is enabled.
461
        ///
462
        /// When enabled, a `metadata.code.branch_hint` custom section is
463
        /// generated with random hints for `if` and `br_if` instructions.
464
        ///
465
        /// [branch-hinting proposal]: https://github.com/WebAssembly/branch-hinting
466
        ///
467
        /// Defaults to `false`.
468
        pub branch_hinting_enabled: bool = false,
469
470
        /// Returns whether we should generate custom sections or not. Defaults
471
        /// to false.
472
        pub generate_custom_sections: bool = false,
473
474
        /// Returns the maximal size of the `alias` section. Defaults to 1000.
475
        pub max_aliases: usize = 1000,
476
477
        /// The maximum number of components to use. Defaults to 10.
478
        ///
479
        /// This includes imported components.
480
        ///
481
        /// Note that this is only relevant for components.
482
        pub max_components: usize = 10,
483
484
        /// The maximum number of data segments to generate. Defaults to 100.
485
        pub max_data_segments: usize = 100,
486
487
        /// The maximum number of element segments to generate. Defaults to 100.
488
        pub max_element_segments: usize = 100,
489
490
        /// The maximum number of elements within a segment to
491
        /// generate. Defaults to 100.
492
        pub max_elements: usize = 100,
493
494
        /// The maximum number of exports to generate. Defaults to 100.
495
        pub max_exports: usize = 100,
496
497
        /// The maximum number of functions to generate. Defaults to 100.  This
498
        /// includes imported functions.
499
        pub max_funcs: usize = 100,
500
501
        /// The maximum number of globals to generate. Defaults to 100.  This
502
        /// includes imported globals.
503
        pub max_globals: usize = 100,
504
505
        /// The maximum number of imports to generate. Defaults to 100.
506
        pub max_imports: usize = 100,
507
508
        /// The maximum number of instances to use. Defaults to 10.
509
        ///
510
        /// This includes imported instances.
511
        ///
512
        /// Note that this is only relevant for components.
513
        pub max_instances: usize = 10,
514
515
        /// The maximum number of instructions to generate in a function
516
        /// body. Defaults to 100.
517
        ///
518
        /// Note that some additional `end`s, `else`s, and `unreachable`s may be
519
        /// appended to the function body to finish block scopes.
520
        pub max_instructions: usize = 100,
521
522
        /// The maximum number of memories to use. Defaults to 1.
523
        ///
524
        /// This includes imported memories.
525
        ///
526
        /// Note that more than one memory is in the realm of the multi-memory
527
        /// wasm proposal.
528
        pub max_memories: usize = 1,
529
530
        /// The maximum, in bytes, of any 32-bit memory's initial or maximum
531
        /// size.
532
        ///
533
        /// May not be larger than `2**32`.
534
        ///
535
        /// Defaults to `2**32`.
536
        pub max_memory32_bytes: u64 = u32::MAX as u64 + 1,
537
538
        /// The maximum, in bytes, of any 64-bit memory's initial or maximum
539
        /// size.
540
        ///
541
        /// May not be larger than `2**64`.
542
        ///
543
        /// Defaults to `2**64`.
544
        pub max_memory64_bytes: u128 = u64::MAX as u128 + 1,
545
546
        /// The maximum number of modules to use. Defaults to 10.
547
        ///
548
        /// This includes imported modules.
549
        ///
550
        /// Note that this is only relevant for components.
551
        pub max_modules: usize = 10,
552
553
        /// Returns the maximal nesting depth of modules with the component
554
        /// model proposal. Defaults to 10.
555
        pub max_nesting_depth: usize = 10,
556
557
        /// The maximum, elements, of any table's initial or maximum
558
        /// size. Defaults to 1 million.
559
        pub max_table_elements: u64 = 1_000_000,
560
561
        /// The maximum number of tables to use. Defaults to 1.
562
        ///
563
        /// This includes imported tables.
564
        ///
565
        /// Note that more than one table is in the realm of the reference types
566
        /// proposal.
567
        pub max_tables: usize = 1,
568
569
        /// The maximum number of tags to generate. Defaults to 100.
570
        pub max_tags: usize = 100,
571
572
        /// Returns the maximal effective size of any type generated by
573
        /// wasm-smith.
574
        ///
575
        /// Note that this number is roughly in units of "how many types would
576
        /// be needed to represent the recursive type". A function with 8
577
        /// parameters and 2 results would take 11 types (one for the type, 10
578
        /// for params/results). A module type with 2 imports and 3 exports
579
        /// would take 6 (module + imports + exports) plus the size of each
580
        /// import/export type. This is a somewhat rough measurement that is not
581
        /// intended to be very precise.
582
        ///
583
        /// Defaults to 1000.
584
        pub max_type_size: u32 = 1000,
585
586
        /// The maximum number of types to generate. Defaults to 100.
587
        pub max_types: usize = 100,
588
589
        /// The maximum number of values to use. Defaults to 10.
590
        ///
591
        /// This includes imported values.
592
        ///
593
        /// Note that this is irrelevant unless value model support is enabled.
594
        pub max_values: usize = 10,
595
596
        /// Returns whether 64-bit memories are allowed. Defaults to true.
597
        ///
598
        /// Note that this is the gate for the memory64 proposal to WebAssembly.
599
        pub memory64_enabled: bool = true,
600
601
        /// Whether every Wasm memory must have a maximum size
602
        /// specified. Defaults to `false`.
603
        pub memory_max_size_required: bool = false,
604
605
        /// Control the probability of generating memory offsets that are in
606
        /// bounds vs. potentially out of bounds.
607
        ///
608
        /// See the `MemoryOffsetChoices` struct for details.
609
        pub memory_offset_choices: MemoryOffsetChoices = MemoryOffsetChoices::default(),
610
611
        /// The minimum number of data segments to generate. Defaults to 0.
612
        pub min_data_segments: usize = 0,
613
614
        /// The minimum number of element segments to generate. Defaults to 0.
615
        pub min_element_segments: usize = 0,
616
617
        /// The minimum number of elements within a segment to
618
        /// generate. Defaults to 0.
619
        pub min_elements: usize = 0,
620
621
        /// The minimum number of exports to generate. Defaults to 0.
622
        pub min_exports: usize = 0,
623
624
        /// The minimum number of functions to generate. Defaults to 0.
625
        ///
626
        /// This includes imported functions.
627
        pub min_funcs: usize = 0,
628
629
        /// The minimum number of globals to generate. Defaults to 0.
630
        ///
631
        /// This includes imported globals.
632
        pub min_globals: usize = 0,
633
634
        /// The minimum number of imports to generate. Defaults to 0.
635
        ///
636
        /// Note that if the sum of the maximum function[^1], table, global and
637
        /// memory counts is less than the minimum number of imports, then it
638
        /// will not be possible to satisfy all constraints (because imports
639
        /// count against the limits for those element kinds). In that case, we
640
        /// strictly follow the max-constraints, and can fail to satisfy this
641
        /// minimum number.
642
        ///
643
        /// [^1]: the maximum number of functions is also limited by the number
644
        /// of function types arbitrarily chosen; strictly speaking, then, the
645
        /// maximum number of imports that can be created due to max-constraints
646
        /// is `sum(min(num_func_types, max_funcs), max_tables, max_globals,
647
        /// max_memories)`.
648
        pub min_imports: usize = 0,
649
650
        /// The minimum number of memories to use. Defaults to 0.
651
        ///
652
        /// This includes imported memories.
653
        pub min_memories: u32 = 0,
654
655
        /// The minimum number of tables to use. Defaults to 0.
656
        ///
657
        /// This includes imported tables.
658
        pub min_tables: u32 = 0,
659
660
        /// The minimum number of tags to generate. Defaults to 0.
661
        pub min_tags: usize = 0,
662
663
        /// The minimum number of types to generate. Defaults to 0.
664
        pub min_types: usize = 0,
665
666
        /// The minimum size, in bytes, of all leb-encoded integers. Defaults to
667
        /// 1.
668
        ///
669
        /// This is useful for ensuring that all leb-encoded integers are
670
        /// decoded as such rather than as simply one byte. This will forcibly
671
        /// extend leb integers with an over-long encoding in some locations if
672
        /// the size would otherwise be smaller than number returned here.
673
        pub min_uleb_size: u8 = 1,
674
675
        /// Determines whether the multi-value results are enabled.
676
        ///
677
        /// Defaults to `true`.
678
        pub multi_value_enabled: bool = true,
679
680
        /// Determines whether the reference types proposal is enabled for
681
        /// generating instructions.
682
        ///
683
        /// Defaults to `true`.
684
        pub reference_types_enabled: bool = true,
685
686
        /// Determines whether the Relaxed SIMD proposal is enabled for
687
        /// generating instructions.
688
        ///
689
        /// Defaults to `true`.
690
        pub relaxed_simd_enabled: bool = true,
691
692
        /// Determines whether the non-trapping float-to-int conversions
693
        /// proposal is enabled.
694
        ///
695
        /// Defaults to `true`.
696
        pub saturating_float_to_int_enabled: bool = true,
697
698
        /// Determines whether the sign-extension-ops proposal is enabled.
699
        ///
700
        /// Defaults to `true`.
701
        pub sign_extension_ops_enabled: bool = true,
702
703
        /// Determines whether the shared-everything-threads proposal is
704
        /// enabled.
705
        ///
706
        /// The [shared-everything-threads] proposal, among other things,
707
        /// extends `shared` attributes to all WebAssembly objects; it builds on
708
        /// the [threads] proposal.
709
        ///
710
        /// [shared-everything-threads]: https://github.com/WebAssembly/shared-everything-threads
711
        /// [threads]: https://github.com/WebAssembly/threads
712
        ///
713
        /// Defaults to `false`.
714
        pub shared_everything_threads_enabled: bool = false,
715
716
        /// Determines whether the SIMD proposal is enabled for generating
717
        /// instructions.
718
        ///
719
        /// Defaults to `true`.
720
        pub simd_enabled: bool = true,
721
722
        /// Determines whether the tail calls proposal is enabled for generating
723
        /// instructions.
724
        ///
725
        /// Defaults to `true`.
726
        pub tail_call_enabled: bool = true,
727
728
        /// Whether every Wasm table must have a maximum size
729
        /// specified. Defaults to `false`.
730
        pub table_max_size_required: bool = false,
731
732
        /// Determines whether the threads proposal is enabled.
733
        ///
734
        /// The [threads proposal] involves shared linear memory, new atomic
735
        /// instructions, and new `wait` and `notify` instructions.
736
        ///
737
        /// [threads proposal]: https://github.com/WebAssembly/threads/blob/master/proposals/threads/Overview.md
738
        ///
739
        /// Defaults to `true`.
740
        pub threads_enabled: bool = true,
741
742
        /// Indicates whether wasm-smith is allowed to generate invalid function
743
        /// bodies.
744
        ///
745
        /// When enabled this option will enable taking raw bytes from the input
746
        /// byte stream and using them as a wasm function body. This means that
747
        /// the output module is not guaranteed to be valid but can help tickle
748
        /// various parts of validation/compilation in some circumstances as
749
        /// well.
750
        ///
751
        /// Defaults to `false`.
752
        pub allow_invalid_funcs: bool = false,
753
754
        /// Determines whether the [wide-arithmetic proposal] is enabled.
755
        ///
756
        /// [wide-arithmetic proposal]: https://github.com/WebAssembly/wide-arithmetic
757
        ///
758
        /// Defaults to `false`.
759
        pub wide_arithmetic_enabled: bool = true,
760
761
        /// Determines whether the [acquire-release-atomics proposal] is
762
        /// enabled.
763
        ///
764
        /// [acquire-release-atomics proposal]: https://github.com/WebAssembly/acquire-release-atomics
765
        ///
766
        /// Defaults to `false`.
767
        pub acquire_release_atomics_enabled: bool = false,
768
769
        /// Determines whether the [multibyte-array-access proposal] is
770
        /// enabled.
771
        ///
772
        /// [multibyte-array-access proposal]: https://github.com/WebAssembly/multibyte-array-access
773
        ///
774
        /// Defaults to `false`.
775
        pub multibyte_array_access_enabled: bool = false,
776
777
        /// Determines whether the [extended-const proposal] is enabled.
778
        ///
779
        /// [extended-const proposal]: https://github.com/WebAssembly/extended-const
780
        ///
781
        /// Defaults to `true`.
782
        pub extended_const_enabled: bool = true,
783
784
        /// Fuel limiting factor used when generating constant expressions.
785
        ///
786
        /// Defaults to `50`.
787
        pub const_expr_fuel: u32 = 50,
788
789
        /// Whether or not to limit the size of arrays generated in constant
790
        /// expressions.
791
        ///
792
        /// Defaults to `false`.
793
        pub limit_arrays_in_const_exprs: bool = false,
794
    }
795
}
796
797
/// This is a tuple `(a, b, c)` where
798
///
799
/// * `a / (a+b+c)` is the probability of generating a memory offset within
800
///   `0..memory.min_size`, i.e. an offset that is definitely in bounds of a
801
///   non-empty memory. (Note that if a memory is zero-sized, however, no offset
802
///   will ever be in bounds.)
803
///
804
/// * `b / (a+b+c)` is the probability of generating a memory offset within
805
///   `memory.min_size..memory.max_size`, i.e. an offset that is possibly in
806
///   bounds if the memory has been grown.
807
///
808
/// * `c / (a+b+c)` is the probability of generating a memory offset within the
809
///   range `memory.max_size..`, i.e. an offset that is definitely out of
810
///   bounds.
811
///
812
/// At least one of `a`, `b`, and `c` must be non-zero.
813
///
814
/// If you want to always generate memory offsets that are definitely in bounds
815
/// of a non-zero-sized memory, for example, you could return `(1, 0, 0)`.
816
///
817
/// The default is `(90, 9, 1)`.
818
#[derive(Clone, Debug)]
819
#[cfg_attr(
820
    feature = "serde",
821
    derive(serde_derive::Deserialize, serde_derive::Serialize)
822
)]
823
pub struct MemoryOffsetChoices(pub u32, pub u32, pub u32);
824
825
impl Default for MemoryOffsetChoices {
826
9.11k
    fn default() -> Self {
827
9.11k
        MemoryOffsetChoices(90, 9, 1)
828
9.11k
    }
829
}
830
831
impl std::str::FromStr for MemoryOffsetChoices {
832
    type Err = String;
833
0
    fn from_str(s: &str) -> Result<Self, Self::Err> {
834
        use std::str::FromStr;
835
0
        let mut parts = s.split(",");
836
0
        let a = parts
837
0
            .next()
838
0
            .ok_or_else(|| "need 3 comma separated values".to_string())?;
839
0
        let a = <u32 as FromStr>::from_str(a).map_err(|e| e.to_string())?;
840
0
        let b = parts
841
0
            .next()
842
0
            .ok_or_else(|| "need 3 comma separated values".to_string())?;
843
0
        let b = <u32 as FromStr>::from_str(b).map_err(|e| e.to_string())?;
844
0
        let c = parts
845
0
            .next()
846
0
            .ok_or_else(|| "need 3 comma separated values".to_string())?;
847
0
        let c = <u32 as FromStr>::from_str(c).map_err(|e| e.to_string())?;
848
0
        if parts.next().is_some() {
849
0
            return Err("found more than 3 comma separated values".to_string());
850
0
        }
851
0
        Ok(MemoryOffsetChoices(a, b, c))
852
0
    }
853
}
854
855
impl<'a> Arbitrary<'a> for Config {
856
9.11k
    fn arbitrary(u: &mut Unstructured<'a>) -> Result<Self> {
857
        const MAX_MAXIMUM: usize = 1000;
858
859
9.11k
        let mut config = Config {
860
9.11k
            max_types: u.int_in_range(0..=MAX_MAXIMUM)?,
861
9.11k
            max_imports: u.int_in_range(0..=MAX_MAXIMUM)?,
862
9.11k
            max_tags: u.int_in_range(0..=MAX_MAXIMUM)?,
863
9.11k
            max_funcs: u.int_in_range(0..=MAX_MAXIMUM)?,
864
9.11k
            max_globals: u.int_in_range(0..=MAX_MAXIMUM)?,
865
9.11k
            max_exports: u.int_in_range(0..=MAX_MAXIMUM)?,
866
9.11k
            max_element_segments: u.int_in_range(0..=MAX_MAXIMUM)?,
867
9.11k
            max_elements: u.int_in_range(0..=MAX_MAXIMUM)?,
868
9.11k
            max_data_segments: u.int_in_range(0..=MAX_MAXIMUM)?,
869
9.11k
            max_instructions: u.int_in_range(0..=MAX_MAXIMUM)?,
870
9.11k
            max_memories: u.int_in_range(0..=100)?,
871
9.11k
            max_tables: u.int_in_range(0..=100)?,
872
9.11k
            max_memory32_bytes: u.int_in_range(0..=u32::MAX as u64 + 1)?,
873
9.11k
            max_memory64_bytes: u.int_in_range(0..=u64::MAX as u128 + 1)?,
874
9.11k
            min_uleb_size: u.int_in_range(0..=5)?,
875
9.11k
            bulk_memory_enabled: u.arbitrary()?,
876
9.11k
            reference_types_enabled: u.arbitrary()?,
877
9.11k
            simd_enabled: u.arbitrary()?,
878
9.11k
            multi_value_enabled: u.arbitrary()?,
879
9.11k
            max_aliases: u.int_in_range(0..=MAX_MAXIMUM)?,
880
9.11k
            max_nesting_depth: u.int_in_range(0..=10)?,
881
9.11k
            saturating_float_to_int_enabled: u.arbitrary()?,
882
9.11k
            sign_extension_ops_enabled: u.arbitrary()?,
883
9.11k
            relaxed_simd_enabled: u.arbitrary()?,
884
9.11k
            exceptions_enabled: u.arbitrary()?,
885
9.11k
            threads_enabled: u.arbitrary()?,
886
9.11k
            tail_call_enabled: u.arbitrary()?,
887
9.11k
            gc_enabled: u.arbitrary()?,
888
9.11k
            compact_imports_enabled: u.arbitrary()?,
889
9.11k
            memory64_enabled: u.arbitrary()?,
890
9.11k
            branch_hinting_enabled: u.arbitrary()?,
891
            allowed_instructions: {
892
                use flagset::Flags;
893
9.11k
                let mut allowed = Vec::new();
894
109k
                for kind in crate::core::InstructionKind::LIST {
895
109k
                    if u.arbitrary()? {
896
72.6k
                        allowed.push(*kind);
897
72.6k
                    }
898
                }
899
9.11k
                InstructionKinds::new(&allowed)
900
            },
901
9.11k
            table_max_size_required: u.arbitrary()?,
902
9.11k
            max_table_elements: u.int_in_range(0..=1_000_000)?,
903
9.11k
            disallow_traps: u.arbitrary()?,
904
9.11k
            allow_floats: u.arbitrary()?,
905
9.11k
            extended_const_enabled: u.arbitrary()?,
906
9.11k
            const_expr_fuel: u.int_in_range(0..=100)?,
907
9.11k
            limit_arrays_in_const_exprs: u.arbitrary()?,
908
909
            // These fields, unlike the ones above, are less useful to set.
910
            // They either make weird inputs or are for features not widely
911
            // implemented yet so they're turned off by default.
912
            min_types: 0,
913
            min_imports: 0,
914
            min_tags: 0,
915
            min_funcs: 0,
916
            min_globals: 0,
917
            min_exports: 0,
918
            min_element_segments: 0,
919
            min_elements: 0,
920
            min_data_segments: 0,
921
            min_memories: 0,
922
            min_tables: 0,
923
            memory_max_size_required: false,
924
            max_instances: 0,
925
            max_modules: 0,
926
            max_components: 0,
927
            max_values: 0,
928
9.11k
            memory_offset_choices: MemoryOffsetChoices::default(),
929
            allow_start_export: true,
930
            max_type_size: 1000,
931
            canonicalize_nans: false,
932
9.11k
            available_imports: None,
933
9.11k
            exports: None,
934
9.11k
            module_shape: None,
935
            export_everything: false,
936
            generate_custom_sections: false,
937
            allow_invalid_funcs: false,
938
939
            // Proposals that are not stage4+ are disabled by default.
940
            custom_page_sizes_enabled: false,
941
            wide_arithmetic_enabled: false,
942
            acquire_release_atomics_enabled: false,
943
            multibyte_array_access_enabled: false,
944
            shared_everything_threads_enabled: false,
945
            custom_descriptors_enabled: false,
946
        };
947
9.11k
        config.sanitize();
948
9.11k
        Ok(config)
949
9.11k
    }
950
}
951
952
impl Config {
953
    /// "Shrink" this `Config` where appropriate to ensure its configuration is
954
    /// valid for wasm-smith.
955
    ///
956
    /// This method will take the arbitrary state that this `Config` is in and
957
    /// will possibly mutate dependent options as needed by `wasm-smith`. For
958
    /// example if the `reference_types_enabled` field is turned off then
959
    /// `wasm-smith`, as of the time of this writing, additionally requires that
960
    /// the `gc_enabled` is not turned on.
961
    ///
962
    /// This method will not enable anything that isn't already enabled or
963
    /// increase any limit of an item, but it may turn features off or shrink
964
    /// limits from what they're previously specified as.
965
18.2k
    pub(crate) fn sanitize(&mut self) {
966
        // If reference types are disabled then automatically flag tables as
967
        // capped at 1 and disable gc as well.
968
18.2k
        if !self.reference_types_enabled {
969
6.94k
            self.max_tables = self.max_tables.min(1);
970
6.94k
            self.gc_enabled = false;
971
6.94k
            self.shared_everything_threads_enabled = false;
972
11.2k
        }
973
974
        // shared-everything-threads depends on GC, so if gc is disabled then
975
        // also disable shared-everything-threads.
976
18.2k
        if !self.gc_enabled {
977
11.8k
            self.shared_everything_threads_enabled = false;
978
11.8k
            self.custom_descriptors_enabled = false;
979
11.8k
            self.multibyte_array_access_enabled = false;
980
11.8k
        }
981
982
        // If simd is disabled then disable all relaxed simd instructions as
983
        // well.
984
18.2k
        if !self.simd_enabled {
985
5.10k
            self.relaxed_simd_enabled = false;
986
13.1k
        }
987
988
        // It is impossible to use the shared-everything-threads proposal
989
        // without threads, which it is built on.
990
18.2k
        if !self.threads_enabled {
991
8.02k
            self.shared_everything_threads_enabled = false;
992
8.02k
            self.acquire_release_atomics_enabled = false;
993
10.2k
        }
994
995
        // If module_shape is present then disable available_imports and exports.
996
18.2k
        if self.module_shape.is_some() {
997
0
            self.available_imports = None;
998
0
            self.exports = None;
999
18.2k
        }
1000
18.2k
    }
1001
1002
    /// Returns the set of features that are necessary for validating against
1003
    /// this `Config`.
1004
    #[cfg(feature = "wasmparser")]
1005
3.02k
    pub fn features(&self) -> wasmparser::WasmFeatures {
1006
        use wasmparser::WasmFeatures;
1007
1008
        // Currently wasm-smith doesn't have knobs for the MVP (floats) or
1009
        // `mutable-global`. These are unconditionally enabled.
1010
3.02k
        let mut features = WasmFeatures::MUTABLE_GLOBAL | WasmFeatures::WASM1;
1011
1012
        // All other features that can be generated by wasm-smith are gated by
1013
        // configuration fields. Conditionally set each feature based on the
1014
        // status of the fields in `self`.
1015
3.02k
        features.set(
1016
            WasmFeatures::SATURATING_FLOAT_TO_INT,
1017
3.02k
            self.saturating_float_to_int_enabled,
1018
        );
1019
3.02k
        features.set(
1020
            WasmFeatures::SIGN_EXTENSION,
1021
3.02k
            self.sign_extension_ops_enabled,
1022
        );
1023
3.02k
        features.set(WasmFeatures::REFERENCE_TYPES, self.reference_types_enabled);
1024
3.02k
        features.set(WasmFeatures::MULTI_VALUE, self.multi_value_enabled);
1025
3.02k
        features.set(WasmFeatures::BULK_MEMORY, self.bulk_memory_enabled);
1026
3.02k
        features.set(WasmFeatures::SIMD, self.simd_enabled);
1027
3.02k
        features.set(WasmFeatures::RELAXED_SIMD, self.relaxed_simd_enabled);
1028
3.02k
        features.set(WasmFeatures::MULTI_MEMORY, self.max_memories > 1);
1029
3.02k
        features.set(WasmFeatures::EXCEPTIONS, self.exceptions_enabled);
1030
3.02k
        features.set(WasmFeatures::MEMORY64, self.memory64_enabled);
1031
3.02k
        features.set(WasmFeatures::TAIL_CALL, self.tail_call_enabled);
1032
3.02k
        features.set(WasmFeatures::FUNCTION_REFERENCES, self.gc_enabled);
1033
3.02k
        features.set(WasmFeatures::GC, self.gc_enabled);
1034
3.02k
        features.set(WasmFeatures::COMPACT_IMPORTS, self.compact_imports_enabled);
1035
3.02k
        features.set(WasmFeatures::THREADS, self.threads_enabled);
1036
3.02k
        features.set(
1037
            WasmFeatures::SHARED_EVERYTHING_THREADS,
1038
3.02k
            self.shared_everything_threads_enabled,
1039
        );
1040
3.02k
        features.set(
1041
            WasmFeatures::CUSTOM_PAGE_SIZES,
1042
3.02k
            self.custom_page_sizes_enabled,
1043
        );
1044
3.02k
        features.set(WasmFeatures::EXTENDED_CONST, self.extended_const_enabled);
1045
3.02k
        features.set(WasmFeatures::WIDE_ARITHMETIC, self.wide_arithmetic_enabled);
1046
3.02k
        features.set(
1047
            WasmFeatures::ACQUIRE_RELEASE_ATOMICS,
1048
3.02k
            self.acquire_release_atomics_enabled,
1049
        );
1050
3.02k
        features.set(
1051
            WasmFeatures::MULTIBYTE_ARRAY_ACCESS,
1052
3.02k
            self.multibyte_array_access_enabled,
1053
        );
1054
3.02k
        features.set(
1055
            WasmFeatures::CUSTOM_DESCRIPTORS,
1056
3.02k
            self.custom_descriptors_enabled,
1057
        );
1058
1059
3.02k
        features
1060
3.02k
    }
1061
}
1062
1063
#[cfg(feature = "serde")]
1064
impl<'de> serde::Deserialize<'de> for Config {
1065
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1066
    where
1067
        D: serde::de::Deserializer<'de>,
1068
    {
1069
        use serde::de::Error;
1070
1071
        match Config::try_from(InternalOptionalConfig::deserialize(deserializer)?) {
1072
            Ok(config) => Ok(config),
1073
            Err(e) => Err(D::Error::custom(e)),
1074
        }
1075
    }
1076
}
1077
1078
#[cfg(feature = "serde")]
1079
impl serde::Serialize for Config {
1080
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1081
    where
1082
        S: serde::Serializer,
1083
    {
1084
        use serde::ser::Error;
1085
1086
        match InternalOptionalConfig::try_from(self) {
1087
            Ok(result) => result.serialize(serializer),
1088
            Err(e) => Err(S::Error::custom(e)),
1089
        }
1090
    }
1091
}