Debian Codegraph @

third_party/rust/wasm-smith/src/config.rs

raw
1 //! Configuring the shape of generated Wasm modules.
2
3 use crate::InstructionKinds;
4 use arbitrary::{Arbitrary, Result, Unstructured};
5
6 macro_rules! define_config {
7 (
8 $(#[$attr:meta])*
9 pub struct Config {
10 $(
11 $(#[$field_attr:meta])*
12 pub $field:ident : $field_ty:ty = $default:expr,
13 )*
14 }
15 ) => {
16 $(#[$attr])*
17 pub struct Config {
18 /// The imports that may be used when generating the module.
19 ///
20 /// Defaults to `None` which means that any arbitrary import can be
21 /// generated.
22 ///
23 /// To only allow specific imports, set this field to a WebAssembly
24 /// module which describes the imports allowed.
25 ///
26 /// Note that [`Self::min_imports`] is ignored when
27 /// `available_imports` are enabled.
28 ///
29 /// The provided value must be a valid binary encoding of a
30 /// WebAssembly module. `wasm-smith` will panic if the module cannot
31 /// be parsed.
32 ///
33 /// # Example
34 ///
35 /// An implementation of this method could use the `wat` crate to
36 /// provide a human-readable and maintainable description:
37 ///
38 /// ```rust
39 /// Some(wat::parse_str(r#"
40 /// (module
41 /// (import "env" "ping" (func (param i32)))
42 /// (import "env" "pong" (func (result i32)))
43 /// (import "env" "memory" (memory 1))
44 /// (import "env" "table" (table 1))
45 /// (import "env" "tag" (tag (param i32)))
46 /// )
47 /// "#))
48 /// # ;
49 /// ```
50 pub available_imports: Option<Vec<u8>>,
51
52 /// If provided, the generated module will have exports with exactly
53 /// the same names and types as those in the provided WebAssembly
54 /// module. The implementation (e.g. function bodies, global
55 /// initializers) of each export in the generated module will be
56 /// random and unrelated to the implementation in the provided
57 /// module. Only globals and functions are supported.
58 ///
59 ///
60 /// Defaults to `None` which means arbitrary exports will be
61 /// generated.
62 ///
63 /// To specify which exports the generated modules should have, set
64 /// this field to a WebAssembly module which describes the desired
65 /// exports. To generate modules with varying exports that meet some
66 /// constraints, consider randomly generating the value for this
67 /// field.
68 ///
69 /// The provided value must be a valid binary encoding of a
70 /// WebAssembly module. `wasm-smith` will panic if the module cannot
71 /// be parsed.
72 ///
73 /// # Module Limits
74 ///
75 /// All types, functions, globals, and exports that are needed to
76 /// provide the required exports will be generated, even if it
77 /// causes the resulting module to exceed the limits defined in
78 /// [`Self::max_type_size`], [`Self::max_types`],
79 /// [`Self::max_funcs`], [`Self::max_globals`], or
80 /// [`Self::max_exports`].
81 ///
82 /// # Example
83 ///
84 /// As for [`Self::available_imports`], the `wat` crate can be used
85 /// to provide an human-readable description of the desired exports:
86 ///
87 /// ```rust
88 /// Some(wat::parse_str(r#"
89 /// (module
90 /// (func (export "foo") (param i32) (result i64) unreachable)
91 /// (global (export "bar") f32 f32.const 0)
92 /// )
93 /// "#));
94 /// ```
95 pub exports: Option<Vec<u8>>,
96
97 $(
98 $(#[$field_attr])*
99 pub $field: $field_ty,
100 )*
101 }
102
103 impl Default for Config {
104 fn default() -> Config {
105 Config {
106 available_imports: None,
107 exports: None,
108
109 $(
110 $field: $default,
111 )*
112 }
113 }
114 }
115
116 #[cfg(feature = "_internal_cli")]
117 #[doc(hidden)]
118 #[derive(Clone, Debug, Default, clap::Parser, serde_derive::Deserialize)]
119 #[serde(rename_all = "kebab-case", deny_unknown_fields)]
120 pub struct InternalOptionalConfig {
121 /// The imports that may be used when generating the module.
122 ///
123 /// When unspecified, any arbitrary import can be generated.
124 ///
125 /// To only allow specific imports, provide a file path of a
126 /// WebAssembly module which describes the imports allowed.
127 ///
128 /// Note that [`Self::min_imports`] is ignored when
129 /// `available_imports` are enabled.
130 ///
131 /// The provided value must be a valid binary encoding of a
132 /// WebAssembly module. `wasm-smith` will panic if the module cannot
133 /// be parsed.
134 #[cfg_attr(feature = "clap", clap(long))]
135 available_imports: Option<std::path::PathBuf>,
136
137 /// If provided, the generated module will have exports with exactly
138 /// the same names and types as those in the provided WebAssembly
139 /// module. The implementation (e.g. function bodies, global
140 /// initializers) of each export in the generated module will be
141 /// random and unrelated to the implementation in the provided
142 /// module. Only globals and functions are supported.
143 ///
144 /// Defaults to `None` which means arbitrary exports will be
145 /// generated.
146 ///
147 /// To specify which exports the generated modules should have, set
148 /// this field to a WebAssembly module which describes the desired
149 /// exports. To generate modules with varying exports that meet some
150 /// constraints, consider randomly generating the value for this
151 /// field.
152 ///
153 /// The provided value must be a valid binary encoding of a
154 /// WebAssembly module. `wasm-smith` will panic if the module cannot
155 /// be parsed.
156 ///
157 /// # Module Limits
158 ///
159 /// All types, functions, globals, and exports that are needed to
160 /// provide the required exports will be generated, even if it
161 /// causes the resulting module to exceed the limits defined in
162 /// [`Self::max_type_size`], [`Self::max_types`],
163 /// [`Self::max_funcs`], [`Self::max_globals`], or
164 /// [`Self::max_exports`].
165 ///
166 #[cfg_attr(feature = "clap", clap(long))]
167 exports: Option<std::path::PathBuf>,
168
169 $(
170 $(#[$field_attr])*
171 #[cfg_attr(feature = "clap", clap(long))]
172 pub $field: Option<$field_ty>,
173 )*
174 }
175
176 #[cfg(feature = "_internal_cli")]
177 impl InternalOptionalConfig {
178 pub fn or(self, other: Self) -> Self {
179 Self {
180 available_imports: self.available_imports.or(other.available_imports),
181 exports: self.exports.or(other.exports),
182
183 $(
184 $field: self.$field.or(other.$field),
185 )*
186 }
187 }
188 }
189
190 #[cfg(feature = "_internal_cli")]
191 impl TryFrom<InternalOptionalConfig> for Config {
192 type Error = anyhow::Error;
193 fn try_from(config: InternalOptionalConfig) -> anyhow::Result<Config> {
194 let default = Config::default();
195 Ok(Config {
196 available_imports: if let Some(file) = config
197 .available_imports
198 .as_ref() {
199 Some(wat::parse_file(file)?)
200 } else {
201 None
202 },
203 exports: if let Some(file) = config
204 .exports
205 .as_ref() {
206 Some(wat::parse_file(file)?)
207 } else {
208 None
209 },
210
211 $(
212 $field: config.$field.unwrap_or(default.$field),
213 )*
214 })
215 }
216 }
217 }
218 }
219
220 define_config! {
221 /// Configuration for a generated module.
222 ///
223 /// Don't care to configure your generated modules? Just use
224 /// [`Module::arbitrary`][crate::Module], which internally uses the default
225 /// configuration.
226 ///
227 /// Want control over the shape of the module that gets generated? Create a
228 /// `Config` and then pass it to [`Module::new`][crate::Module::new].
229 ///
230 /// # Swarm Testing
231 ///
232 /// You can use the `Arbitrary for Config` implementation for [swarm
233 /// testing]. This will dynamically -- but still deterministically -- choose
234 /// configuration options for you.
235 ///
236 /// [swarm testing]: https://www.cs.utah.edu/~regehr/papers/swarm12.pdf
237 ///
238 /// Note that we pick only *maximums*, not minimums, here because it is more
239 /// complex to describe the domain of valid configs when minima are involved
240 /// (`min <= max` for each variable) and minima are mostly used to ensure
241 /// certain elements are present, but do not widen the range of generated
242 /// Wasm modules.
243 #[derive(Clone, Debug)]
244 pub struct Config {
245 /// Determines whether a `start` export may be included. Defaults to `true`.
246 pub allow_start_export: bool = true,
247
248 /// The kinds of instructions allowed in the generated wasm
249 /// programs. Defaults to all.
250 ///
251 /// The categories of instructions match the categories used by the
252 /// [WebAssembly
253 /// specification](https://webassembly.github.io/spec/core/syntax/instructions.html);
254 /// e.g., numeric, vector, control, memory, etc.
255 ///
256 /// Additionally, we include finer-grained categories which exclude floating point
257 /// instructions, e.g. [`InstructionKind::NumericInt`] is a subset of
258 /// [`InstructionKind::Numeric`] consisting of all numeric instructions which
259 /// don't involve floats.
260 ///
261 /// Note that modifying this setting is separate from the proposal
262 /// flags; that is, if `simd_enabled() == true` but
263 /// `allowed_instruction()` does not include vector instructions, the
264 /// generated programs will not include these instructions but could
265 /// contain vector types.
266 pub allowed_instructions: InstructionKinds = InstructionKinds::all(),
267
268 /// Determines whether we generate floating point instructions and types.
269 ///
270 /// Defaults to `true`.
271 pub allow_floats: bool = true,
272
273 /// Determines whether the bulk memory proposal is enabled for
274 /// generating instructions.
275 ///
276 /// Defaults to `false`.
277 pub bulk_memory_enabled: bool = false,
278
279 /// Returns whether NaN values are canonicalized after all f32/f64
280 /// operation. Defaults to false.
281 ///
282 /// This can be useful when a generated wasm module is executed in
283 /// multiple runtimes which may produce different NaN values. This
284 /// ensures that the generated module will always use the same NaN
285 /// representation for all instructions which have visible side effects,
286 /// for example writing floats to memory or float-to-int bitcast
287 /// instructions.
288 pub canonicalize_nans: bool = false,
289
290 /// Returns whether we should avoid generating code that will possibly
291 /// trap.
292 ///
293 /// For some trapping instructions, this will emit extra instructions to
294 /// ensure they don't trap, while some instructions will simply be
295 /// excluded. In cases where we would run into a trap, we instead
296 /// choose some arbitrary non-trapping behavior. For example, if we
297 /// detect that a Load instruction would attempt to access out-of-bounds
298 /// memory, we instead pretend the load succeeded and push 0 onto the
299 /// stack.
300 ///
301 /// One type of trap that we can't currently avoid is
302 /// StackOverflow. Even when `disallow_traps` is set to true, wasm-smith
303 /// will eventually generate a program that infinitely recurses, causing
304 /// the call stack to be exhausted.
305 ///
306 /// Defaults to `false`.
307 pub disallow_traps: bool = false,
308
309 /// Determines whether the exception-handling proposal is enabled for
310 /// generating instructions.
311 ///
312 /// Defaults to `true`.
313 pub exceptions_enabled: bool = true,
314
315 /// Export all WebAssembly objects in the module. Defaults to false.
316 ///
317 /// This overrides [`Config::min_exports`] and [`Config::max_exports`].
318 pub export_everything: bool = false,
319
320 /// Determines whether the GC proposal is enabled when generating a Wasm
321 /// module.
322 ///
323 /// Defaults to `true`.
324 pub gc_enabled: bool = true,
325
326 /// Determines whether the custom-page-sizes proposal is enabled when
327 /// generating a Wasm module.
328 ///
329 /// Defaults to `false`.
330 pub custom_page_sizes_enabled: bool = false,
331
332 /// Returns whether we should generate custom sections or not. Defaults
333 /// to false.
334 pub generate_custom_sections: bool = false,
335
336 /// Returns the maximal size of the `alias` section. Defaults to 1000.
337 pub max_aliases: usize = 1000,
338
339 /// The maximum number of components to use. Defaults to 10.
340 ///
341 /// This includes imported components.
342 ///
343 /// Note that this is only relevant for components.
344 pub max_components: usize = 10,
345
346 /// The maximum number of data segments to generate. Defaults to 100.
347 pub max_data_segments: usize = 100,
348
349 /// The maximum number of element segments to generate. Defaults to 100.
350 pub max_element_segments: usize = 100,
351
352 /// The maximum number of elements within a segment to
353 /// generate. Defaults to 100.
354 pub max_elements: usize = 100,
355
356 /// The maximum number of exports to generate. Defaults to 100.
357 pub max_exports: usize = 100,
358
359 /// The maximum number of functions to generate. Defaults to 100. This
360 /// includes imported functions.
361 pub max_funcs: usize = 100,
362
363 /// The maximum number of globals to generate. Defaults to 100. This
364 /// includes imported globals.
365 pub max_globals: usize = 100,
366
367 /// The maximum number of imports to generate. Defaults to 100.
368 pub max_imports: usize = 100,
369
370 /// The maximum number of instances to use. Defaults to 10.
371 ///
372 /// This includes imported instances.
373 ///
374 /// Note that this is only relevant for components.
375 pub max_instances: usize = 10,
376
377 /// The maximum number of instructions to generate in a function
378 /// body. Defaults to 100.
379 ///
380 /// Note that some additional `end`s, `else`s, and `unreachable`s may be
381 /// appended to the function body to finish block scopes.
382 pub max_instructions: usize = 100,
383
384 /// The maximum number of memories to use. Defaults to 1.
385 ///
386 /// This includes imported memories.
387 ///
388 /// Note that more than one memory is in the realm of the multi-memory
389 /// wasm proposal.
390 pub max_memories: usize = 1,
391
392 /// The maximum, in bytes, of any 32-bit memory's initial or maximum
393 /// size.
394 ///
395 /// May not be larger than `2**32`.
396 ///
397 /// Defaults to `2**32`.
398 pub max_memory32_bytes: u64 = u32::MAX as u64 + 1,
399
400 /// The maximum, in bytes, of any 64-bit memory's initial or maximum
401 /// size.
402 ///
403 /// May not be larger than `2**64`.
404 ///
405 /// Defaults to `2**64`.
406 pub max_memory64_bytes: u128 = u64::MAX as u128 + 1,
407
408 /// The maximum number of modules to use. Defaults to 10.
409 ///
410 /// This includes imported modules.
411 ///
412 /// Note that this is only relevant for components.
413 pub max_modules: usize = 10,
414
415 /// Returns the maximal nesting depth of modules with the component
416 /// model proposal. Defaults to 10.
417 pub max_nesting_depth: usize = 10,
418
419 /// The maximum, elements, of any table's initial or maximum
420 /// size. Defaults to 1 million.
421 pub max_table_elements: u64 = 1_000_000,
422
423 /// The maximum number of tables to use. Defaults to 1.
424 ///
425 /// This includes imported tables.
426 ///
427 /// Note that more than one table is in the realm of the reference types
428 /// proposal.
429 pub max_tables: usize = 1,
430
431 /// The maximum number of tags to generate. Defaults to 100.
432 pub max_tags: usize = 100,
433
434 /// Returns the maximal effective size of any type generated by
435 /// wasm-smith.
436 ///
437 /// Note that this number is roughly in units of "how many types would
438 /// be needed to represent the recursive type". A function with 8
439 /// parameters and 2 results would take 11 types (one for the type, 10
440 /// for params/results). A module type with 2 imports and 3 exports
441 /// would take 6 (module + imports + exports) plus the size of each
442 /// import/export type. This is a somewhat rough measurement that is not
443 /// intended to be very precise.
444 ///
445 /// Defaults to 1000.
446 pub max_type_size: u32 = 1000,
447
448 /// The maximum number of types to generate. Defaults to 100.
449 pub max_types: usize = 100,
450
451 /// The maximum number of values to use. Defaults to 10.
452 ///
453 /// This includes imported values.
454 ///
455 /// Note that this is irrelevant unless value model support is enabled.
456 pub max_values: usize = 10,
457
458 /// Returns whether 64-bit memories are allowed. Defaults to false.
459 ///
460 /// Note that this is the gate for the memory64 proposal to WebAssembly.
461 pub memory64_enabled: bool = false,
462
463 /// Whether every Wasm memory must have a maximum size
464 /// specified. Defaults to `false`.
465 pub memory_max_size_required: bool = false,
466
467 /// Control the probability of generating memory offsets that are in
468 /// bounds vs. potentially out of bounds.
469 ///
470 /// See the `MemoryOffsetChoices` struct for details.
471 pub memory_offset_choices: MemoryOffsetChoices = MemoryOffsetChoices::default(),
472
473 /// The minimum number of data segments to generate. Defaults to 0.
474 pub min_data_segments: usize = 0,
475
476 /// The minimum number of element segments to generate. Defaults to 0.
477 pub min_element_segments: usize = 0,
478
479 /// The minimum number of elements within a segment to
480 /// generate. Defaults to 0.
481 pub min_elements: usize = 0,
482
483 /// The minimum number of exports to generate. Defaults to 0.
484 pub min_exports: usize = 0,
485
486 /// The minimum number of functions to generate. Defaults to 0.
487 ///
488 /// This includes imported functions.
489 pub min_funcs: usize = 0,
490
491 /// The minimum number of globals to generate. Defaults to 0.
492 ///
493 /// This includes imported globals.
494 pub min_globals: usize = 0,
495
496 /// The minimum number of imports to generate. Defaults to 0.
497 ///
498 /// Note that if the sum of the maximum function[^1], table, global and
499 /// memory counts is less than the minimum number of imports, then it
500 /// will not be possible to satisfy all constraints (because imports
501 /// count against the limits for those element kinds). In that case, we
502 /// strictly follow the max-constraints, and can fail to satisfy this
503 /// minimum number.
504 ///
505 /// [^1]: the maximum number of functions is also limited by the number
506 /// of function types arbitrarily chosen; strictly speaking, then, the
507 /// maximum number of imports that can be created due to max-constraints
508 /// is `sum(min(num_func_types, max_funcs), max_tables, max_globals,
509 /// max_memories)`.
510 pub min_imports: usize = 0,
511
512 /// The minimum number of memories to use. Defaults to 0.
513 ///
514 /// This includes imported memories.
515 pub min_memories: u32 = 0,
516
517 /// The minimum number of tables to use. Defaults to 0.
518 ///
519 /// This includes imported tables.
520 pub min_tables: u32 = 0,
521
522 /// The minimum number of tags to generate. Defaults to 0.
523 pub min_tags: usize = 0,
524
525 /// The minimum number of types to generate. Defaults to 0.
526 pub min_types: usize = 0,
527
528 /// The minimum size, in bytes, of all leb-encoded integers. Defaults to
529 /// 1.
530 ///
531 /// This is useful for ensuring that all leb-encoded integers are
532 /// decoded as such rather than as simply one byte. This will forcibly
533 /// extend leb integers with an over-long encoding in some locations if
534 /// the size would otherwise be smaller than number returned here.
535 pub min_uleb_size: u8 = 1,
536
537 /// Determines whether the multi-value results are enabled.
538 ///
539 /// Defaults to `true`.
540 pub multi_value_enabled: bool = true,
541
542 /// Determines whether the reference types proposal is enabled for
543 /// generating instructions.
544 ///
545 /// Defaults to `true`.
546 pub reference_types_enabled: bool = true,
547
548 /// Determines whether the Relaxed SIMD proposal is enabled for
549 /// generating instructions.
550 ///
551 /// Defaults to `true`.
552 pub relaxed_simd_enabled: bool = true,
553
554 /// Determines whether the nontrapping-float-to-int-conversions propsal
555 /// is enabled.
556 ///
557 /// Defaults to `true`.
558 pub saturating_float_to_int_enabled: bool = true,
559
560 /// Determines whether the sign-extension-ops propsal is enabled.
561 ///
562 /// Defaults to `true`.
563 pub sign_extension_ops_enabled: bool = true,
564
565 /// Determines whether the SIMD proposal is enabled for generating
566 /// instructions.
567 ///
568 /// Defaults to `true`.
569 pub simd_enabled: bool = true,
570
571 /// Determines whether the tail calls proposal is enabled for generating
572 /// instructions.
573 ///
574 /// Defaults to `true`.
575 pub tail_call_enabled: bool = true,
576
577 /// Whether every Wasm table must have a maximum size
578 /// specified. Defaults to `false`.
579 pub table_max_size_required: bool = false,
580
581 /// Determines whether the threads proposal is enabled.
582 ///
583 /// The [threads proposal] involves shared linear memory, new atomic
584 /// instructions, and new `wait` and `notify` instructions.
585 ///
586 /// [threads proposal]: https://github.com/WebAssembly/threads/blob/master/proposals/threads/Overview.md
587 ///
588 /// Defaults to `true`.
589 pub threads_enabled: bool = true,
590
591 /// Indicates whether wasm-smith is allowed to generate invalid function
592 /// bodies.
593 ///
594 /// When enabled this option will enable taking raw bytes from the input
595 /// byte stream and using them as a wasm function body. This means that
596 /// the output module is not guaranteed to be valid but can help tickle
597 /// various parts of validation/compilation in some circumstances as
598 /// well.
599 ///
600 /// Defaults to `false`.
601 pub allow_invalid_funcs: bool = false,
602
603 /// Determines whether the [wide-arithmetic proposal] is enabled.
604 ///
605 /// [wide-arithmetic proposal]: https://github.com/WebAssembly/wide-arithmetic
606 ///
607 /// Defaults to `false`.
608 pub wide_arithmetic_enabled: bool = false,
609 }
610 }
611
612 /// This is a tuple `(a, b, c)` where
613 ///
614 /// * `a / (a+b+c)` is the probability of generating a memory offset within
615 /// `0..memory.min_size`, i.e. an offset that is definitely in bounds of a
616 /// non-empty memory. (Note that if a memory is zero-sized, however, no offset
617 /// will ever be in bounds.)
618 ///
619 /// * `b / (a+b+c)` is the probability of generating a memory offset within
620 /// `memory.min_size..memory.max_size`, i.e. an offset that is possibly in
621 /// bounds if the memory has been grown.
622 ///
623 /// * `c / (a+b+c)` is the probability of generating a memory offset within the
624 /// range `memory.max_size..`, i.e. an offset that is definitely out of
625 /// bounds.
626 ///
627 /// At least one of `a`, `b`, and `c` must be non-zero.
628 ///
629 /// If you want to always generate memory offsets that are definitely in bounds
630 /// of a non-zero-sized memory, for example, you could return `(1, 0, 0)`.
631 ///
632 /// The default is `(90, 9, 1)`.
633 #[derive(Clone, Debug)]
634 #[cfg_attr(feature = "serde_derive", derive(serde_derive::Deserialize))]
635 pub struct MemoryOffsetChoices(pub u32, pub u32, pub u32);
636
637 impl Default for MemoryOffsetChoices {
638 fn default() -> Self {
639 MemoryOffsetChoices(90, 9, 1)
640 }
641 }
642
643 #[cfg(feature = "_internal_cli")]
644 impl std::str::FromStr for MemoryOffsetChoices {
645 type Err = String;
646 fn from_str(s: &str) -> Result<Self, Self::Err> {
647 use std::str::FromStr;
648 let mut parts = s.split(",");
649 let a = parts
650 .next()
651 .ok_or_else(|| "need 3 comma separated values".to_string())?;
652 let a = <u32 as FromStr>::from_str(a).map_err(|e| e.to_string())?;
653 let b = parts
654 .next()
655 .ok_or_else(|| "need 3 comma separated values".to_string())?;
656 let b = <u32 as FromStr>::from_str(b).map_err(|e| e.to_string())?;
657 let c = parts
658 .next()
659 .ok_or_else(|| "need 3 comma separated values".to_string())?;
660 let c = <u32 as FromStr>::from_str(c).map_err(|e| e.to_string())?;
661 if parts.next().is_some() {
662 return Err("found more than 3 comma separated values".to_string());
663 }
664 Ok(MemoryOffsetChoices(a, b, c))
665 }
666 }
667
668 impl<'a> Arbitrary<'a> for Config {
669 fn arbitrary(u: &mut Unstructured<'a>) -> Result<Self> {
670 const MAX_MAXIMUM: usize = 1000;
671
672 let mut config = Config {
673 max_types: u.int_in_range(0..=MAX_MAXIMUM)?,
674 max_imports: u.int_in_range(0..=MAX_MAXIMUM)?,
675 max_tags: u.int_in_range(0..=MAX_MAXIMUM)?,
676 max_funcs: u.int_in_range(0..=MAX_MAXIMUM)?,
677 max_globals: u.int_in_range(0..=MAX_MAXIMUM)?,
678 max_exports: u.int_in_range(0..=MAX_MAXIMUM)?,
679 max_element_segments: u.int_in_range(0..=MAX_MAXIMUM)?,
680 max_elements: u.int_in_range(0..=MAX_MAXIMUM)?,
681 max_data_segments: u.int_in_range(0..=MAX_MAXIMUM)?,
682 max_instructions: u.int_in_range(0..=MAX_MAXIMUM)?,
683 max_memories: u.int_in_range(0..=100)?,
684 max_tables: u.int_in_range(0..=100)?,
685 max_memory32_bytes: u.int_in_range(0..=u32::MAX as u64 + 1)?,
686 max_memory64_bytes: u.int_in_range(0..=u64::MAX as u128 + 1)?,
687 min_uleb_size: u.int_in_range(0..=5)?,
688 bulk_memory_enabled: u.arbitrary()?,
689 reference_types_enabled: u.arbitrary()?,
690 simd_enabled: u.arbitrary()?,
691 multi_value_enabled: u.arbitrary()?,
692 max_aliases: u.int_in_range(0..=MAX_MAXIMUM)?,
693 max_nesting_depth: u.int_in_range(0..=10)?,
694 saturating_float_to_int_enabled: u.arbitrary()?,
695 sign_extension_ops_enabled: u.arbitrary()?,
696 relaxed_simd_enabled: u.arbitrary()?,
697 exceptions_enabled: u.arbitrary()?,
698 threads_enabled: u.arbitrary()?,
699 tail_call_enabled: u.arbitrary()?,
700 gc_enabled: u.arbitrary()?,
701 allowed_instructions: {
702 use flagset::Flags;
703 let mut allowed = Vec::new();
704 for kind in crate::core::InstructionKind::LIST {
705 if u.arbitrary()? {
706 allowed.push(*kind);
707 }
708 }
709 InstructionKinds::new(&allowed)
710 },
711 table_max_size_required: u.arbitrary()?,
712 max_table_elements: u.int_in_range(0..=1_000_000)?,
713 disallow_traps: u.arbitrary()?,
714 allow_floats: u.arbitrary()?,
715
716 // These fields, unlike the ones above, are less useful to set.
717 // They either make weird inputs or are for features not widely
718 // implemented yet so they're turned off by default.
719 min_types: 0,
720 min_imports: 0,
721 min_tags: 0,
722 min_funcs: 0,
723 min_globals: 0,
724 min_exports: 0,
725 min_element_segments: 0,
726 min_elements: 0,
727 min_data_segments: 0,
728 min_memories: 0,
729 min_tables: 0,
730 memory_max_size_required: false,
731 max_instances: 0,
732 max_modules: 0,
733 max_components: 0,
734 max_values: 0,
735 memory_offset_choices: MemoryOffsetChoices::default(),
736 allow_start_export: true,
737 max_type_size: 1000,
738 canonicalize_nans: false,
739 available_imports: None,
740 exports: None,
741 export_everything: false,
742 generate_custom_sections: false,
743 allow_invalid_funcs: false,
744
745 // Proposals that are not stage4+ are disabled by default.
746 memory64_enabled: false,
747 custom_page_sizes_enabled: false,
748 wide_arithmetic_enabled: false,
749 };
750 config.sanitize();
751 Ok(config)
752 }
753 }
754
755 impl Config {
756 /// "Shrink" this `Config` where appropriate to ensure its configuration is
757 /// valid for wasm-smith.
758 ///
759 /// This method will take the arbitrary state that this `Config` is in and
760 /// will possibly mutate dependent options as needed by `wasm-smith`. For
761 /// example if the `reference_types_enabled` field is turned off then
762 /// `wasm-smith`, as of the time of this writing, additionally requires that
763 /// the `gc_enabled` is not turned on.
764 ///
765 /// This method will not enable anything that isn't already enabled or
766 /// increase any limit of an item, but it may turn features off or shrink
767 /// limits from what they're previously specified as.
768 pub(crate) fn sanitize(&mut self) {
769 // If reference types are disabled then automatically flag tables as
770 // capped at 1 and disable gc as well.
771 if !self.reference_types_enabled {
772 self.max_tables = self.max_tables.min(1);
773 self.gc_enabled = false;
774 }
775
776 // If simd is disabled then disable all relaxed simd instructions as
777 // well.
778 if !self.simd_enabled {
779 self.relaxed_simd_enabled = false;
780 }
781 }
782 }