1 //! Generate a Wasm module and the configuration for generating it.
2 
3 use arbitrary::{Arbitrary, Unstructured};
4 use std::sync::atomic::{AtomicUsize, Ordering::Relaxed};
5 
6 /// Default module-level configuration for fuzzing Wasmtime.
7 ///
8 /// Internally this uses `wasm-smith`'s own `Config` but we further refine
9 /// the defaults here as well.
10 #[derive(Debug, Clone)]
11 #[expect(missing_docs, reason = "self-describing fields")]
12 pub struct ModuleConfig {
13     pub config: wasm_smith::Config,
14 
15     // These knobs aren't exposed in `wasm-smith` at this time but are exposed
16     // in our `*.wast` testing so keep knobs here so they can be read during
17     // config-to-`wasmtime::Config` translation.
18     pub function_references_enabled: bool,
19     pub component_model_async: bool,
20     pub component_model_async_builtins: bool,
21     pub component_model_async_stackful: bool,
22     pub legacy_exceptions: bool,
23 }
24 
25 impl<'a> Arbitrary<'a> for ModuleConfig {
26     fn arbitrary(u: &mut Unstructured<'a>) -> arbitrary::Result<ModuleConfig> {
27         let mut config = wasm_smith::Config::arbitrary(u)?;
28 
29         // This list is intended to be the definitive source of truth for
30         // what's at least possible to fuzz within Wasmtime. This is a
31         // combination of features in `wasm-smith` where some proposals are
32         // on-by-default (as determined by fuzz input) and others are
33         // off-by-default (as they aren't stage4+). Wasmtime will default-fuzz
34         // proposals that a pre-stage-4 to test our own implementation. Wasmtime
35         // might also unconditionally disable proposals that it doesn't
36         // implement yet which are stage4+. This is intended to be an exhaustive
37         // list of all the wasm proposals that `wasm-smith` supports and the
38         // fuzzing status within Wasmtime too.
39         let _ = config.multi_value_enabled;
40         let _ = config.saturating_float_to_int_enabled;
41         let _ = config.sign_extension_ops_enabled;
42         let _ = config.bulk_memory_enabled;
43         let _ = config.reference_types_enabled;
44         let _ = config.simd_enabled;
45         let _ = config.relaxed_simd_enabled;
46         let _ = config.tail_call_enabled;
47         let _ = config.extended_const_enabled;
48         let _ = config.gc_enabled;
49         config.exceptions_enabled = false;
50         config.custom_page_sizes_enabled = u.arbitrary()?;
51         config.wide_arithmetic_enabled = u.arbitrary()?;
52         config.memory64_enabled = u.ratio(1, 20)?;
53         config.threads_enabled = u.ratio(1, 20)?;
54         // Allow multi-memory but make it unlikely
55         if u.ratio(1, 20)? {
56             config.max_memories = config.max_memories.max(2);
57         } else {
58             config.max_memories = 1;
59         }
60         // ... NB: if you add something above this line please be sure to update
61         // `docs/stability-wasm-proposals.md`
62 
63         // We get better differential execution when we disallow traps, so we'll
64         // do that most of the time.
65         config.disallow_traps = u.ratio(9, 10)?;
66 
67         Ok(ModuleConfig {
68             component_model_async: false,
69             component_model_async_builtins: false,
70             component_model_async_stackful: false,
71             legacy_exceptions: false,
72             function_references_enabled: config.gc_enabled,
73             config,
74         })
75     }
76 }
77 
78 impl ModuleConfig {
79     /// Uses this configuration and the supplied source of data to generate a
80     /// Wasm module.
81     ///
82     /// If a `default_fuel` is provided, the resulting module will be configured
83     /// to ensure termination; as doing so will add an additional global to the
84     /// module, the pooling allocator, if configured, must also have its globals
85     /// limit updated.
86     pub fn generate(
87         &self,
88         input: &mut Unstructured<'_>,
89         default_fuel: Option<u32>,
90     ) -> arbitrary::Result<wasm_smith::Module> {
91         crate::init_fuzzing();
92 
93         // If requested, save `*.{dna,json}` files for recreating this module
94         // in wasm-tools alone.
95         let input_before = if log::log_enabled!(log::Level::Debug) {
96             let len = input.len();
97             Some(input.peek_bytes(len).unwrap().to_vec())
98         } else {
99             None
100         };
101 
102         let mut module = wasm_smith::Module::new(self.config.clone(), input)?;
103 
104         if let Some(before) = input_before {
105             static GEN_CNT: AtomicUsize = AtomicUsize::new(0);
106             let used = before.len() - input.len();
107             let i = GEN_CNT.fetch_add(1, Relaxed);
108             let dna = format!("testcase{i}.dna");
109             let config = format!("testcase{i}.json");
110             log::debug!("writing `{dna}` and `{config}`");
111             std::fs::write(&dna, &before[..used]).unwrap();
112             std::fs::write(&config, serde_json::to_string_pretty(&self.config).unwrap()).unwrap();
113         }
114 
115         if let Some(default_fuel) = default_fuel {
116             module.ensure_termination(default_fuel).unwrap();
117         }
118 
119         Ok(module)
120     }
121 }
122