Skip to main content

wasmtime_fuzzing/generators/
config.rs

1//! Generate a configuration for both Wasmtime and the Wasm module to execute.
2
3use super::{AsyncConfig, CodegenSettings, InstanceAllocationStrategy, MemoryConfig, ModuleConfig};
4use crate::oracles::{StoreLimits, Timeout};
5use arbitrary::{Arbitrary, Unstructured};
6use std::num::NonZeroU32;
7use std::time::Duration;
8use wasmtime::Result;
9use wasmtime::{Enabled, Engine, Module, Store};
10use wasmtime_test_util::wast::{WastConfig, WastTest, limits};
11
12/// Configuration for `wasmtime::Config` and generated modules for a session of
13/// fuzzing.
14///
15/// This configuration guides what modules are generated, how wasmtime
16/// configuration is generated, and is typically itself generated through a call
17/// to `Arbitrary` which allows for a form of "swarm testing".
18#[derive(Debug, Clone)]
19pub struct Config {
20    /// Configuration related to the `wasmtime::Config`.
21    pub wasmtime: WasmtimeConfig,
22    /// Configuration related to generated modules.
23    pub module_config: ModuleConfig,
24}
25
26impl Config {
27    /// Indicates that this configuration is being used for differential
28    /// execution.
29    ///
30    /// The purpose of this function is to update the configuration which was
31    /// generated to be compatible with execution in multiple engines. The goal
32    /// is to produce the exact same result in all engines so we need to paper
33    /// over things like nan differences and memory/table behavior differences.
34    pub fn set_differential_config(&mut self) {
35        let config = &mut self.module_config.config;
36
37        // Make it more likely that there are types available to generate a
38        // function with.
39        config.min_types = config.min_types.max(1);
40        config.max_types = config.max_types.max(1);
41
42        // Generate at least one function
43        config.min_funcs = config.min_funcs.max(1);
44        config.max_funcs = config.max_funcs.max(1);
45
46        // Allow a memory to be generated, but don't let it get too large.
47        // Additionally require the maximum size to guarantee that the growth
48        // behavior is consistent across engines.
49        config.max_memory32_bytes = 10 << 16;
50        config.max_memory64_bytes = 10 << 16;
51        config.memory_max_size_required = true;
52
53        // If tables are generated make sure they don't get too large to avoid
54        // hitting any engine-specific limit. Additionally ensure that the
55        // maximum size is required to guarantee consistent growth across
56        // engines.
57        //
58        // Note that while reference types are disabled below, only allow one
59        // table.
60        config.max_table_elements = 1_000;
61        config.table_max_size_required = true;
62
63        // Don't allow any imports
64        config.max_imports = 0;
65
66        // Try to get the function and the memory exported
67        config.export_everything = true;
68
69        // NaN is canonicalized at the wasm level for differential fuzzing so we
70        // can paper over NaN differences between engines.
71        config.canonicalize_nans = true;
72
73        // If using the pooling allocator, update the instance limits too
74        if let InstanceAllocationStrategy::Pooling(pooling) = &mut self.wasmtime.strategy {
75            // One single-page memory
76            pooling.total_memories = config.max_memories as u32;
77            pooling.max_memory_size = 10 << 16;
78            pooling.max_memories_per_module = config.max_memories as u32;
79            if pooling.memory_protection_keys == Enabled::Auto
80                && pooling.max_memory_protection_keys > 1
81            {
82                pooling.total_memories =
83                    pooling.total_memories * (pooling.max_memory_protection_keys as u32);
84            }
85
86            pooling.total_tables = config.max_tables as u32;
87            pooling.table_elements = 1_000;
88            pooling.max_tables_per_module = config.max_tables as u32;
89
90            pooling.core_instance_size = 1_000_000;
91
92            let cfg = &mut self.wasmtime.memory_config;
93            match &mut cfg.memory_reservation {
94                Some(size) => *size = (*size).max(pooling.max_memory_size as u64),
95                other @ None => *other = Some(pooling.max_memory_size as u64),
96            }
97        }
98
99        // These instructions are explicitly not expected to be exactly the same
100        // across engines. Don't fuzz them.
101        config.relaxed_simd_enabled = false;
102
103        self.wasmtime.make_internally_consistent();
104    }
105
106    /// Uses this configuration and the supplied source of data to generate
107    /// a wasm module.
108    ///
109    /// If a `default_fuel` is provided, the resulting module will be configured
110    /// to ensure termination; as doing so will add an additional global to the module,
111    /// the pooling allocator, if configured, will also have its globals limit updated.
112    pub fn generate(
113        &self,
114        input: &mut Unstructured<'_>,
115        default_fuel: Option<u32>,
116    ) -> arbitrary::Result<wasm_smith::Module> {
117        self.module_config.generate(input, default_fuel)
118    }
119
120    /// Updates this configuration to be able to run the `test` specified.
121    ///
122    /// This primarily updates `self.module_config` to ensure that it enables
123    /// all features and proposals necessary to execute the `test` specified.
124    /// This will additionally update limits in the pooling allocator to be able
125    /// to execute all tests.
126    pub fn make_wast_test_compliant(&mut self, test: &WastTest) -> WastConfig {
127        let wasmtime_test_util::wast::TestConfig {
128            bulk_memory,
129            memory64,
130            custom_page_sizes,
131            multi_memory,
132            threads,
133            shared_everything_threads,
134            gc,
135            function_references,
136            relaxed_simd,
137            reference_types,
138            tail_call,
139            extended_const,
140            wide_arithmetic,
141            branch_hinting,
142            compact_imports,
143            component_model_async,
144            component_model_more_async_builtins,
145            component_model_async_stackful,
146            component_model_threading,
147            component_model_error_context,
148            component_model_gc,
149            component_model_map,
150            component_model_memory64,
151            component_model_fixed_length_lists,
152            component_model_implements,
153            component_model_canonical_names,
154            component_model_accessors,
155            simd,
156            exceptions,
157            legacy_exceptions: _,
158            custom_descriptors: _,
159
160            hogs_memory: _,
161            nan_canonicalization: _,
162            gc_types: _,
163            stack_switching,
164            spec_test: _,
165        } = test.config;
166
167        // Enable/disable some proposals that aren't configurable in wasm-smith
168        // but are configurable in Wasmtime.
169        self.module_config.function_references_enabled =
170            function_references.or(gc).unwrap_or(false);
171        self.module_config.component_model_async = component_model_async.unwrap_or(false);
172        self.module_config.component_model_more_async_builtins =
173            component_model_more_async_builtins.unwrap_or(false);
174        self.module_config.component_model_async_stackful =
175            component_model_async_stackful.unwrap_or(false);
176        self.module_config.component_model_threading = component_model_threading.unwrap_or(false);
177        self.module_config.component_model_error_context =
178            component_model_error_context.unwrap_or(false);
179        self.module_config.component_model_gc = component_model_gc.unwrap_or(false);
180        self.module_config.component_model_map = component_model_map.unwrap_or(false);
181        self.module_config.component_model_memory64 = component_model_memory64.unwrap_or(false);
182        self.module_config.component_model_fixed_length_lists =
183            component_model_fixed_length_lists.unwrap_or(false);
184        self.module_config.component_model_implements = component_model_implements.unwrap_or(false);
185        self.module_config.component_model_canonical_names =
186            component_model_canonical_names.unwrap_or(false);
187        self.module_config.component_model_accessors = component_model_accessors.unwrap_or(false);
188        self.module_config.stack_switching = stack_switching.unwrap_or(false);
189        self.wasmtime.branch_hinting = branch_hinting.unwrap_or(false);
190
191        // Enable/disable proposals that wasm-smith has knobs for which will be
192        // read when creating `wasmtime::Config`.
193        let config = &mut self.module_config.config;
194        config.bulk_memory_enabled = bulk_memory.unwrap_or(false);
195        config.multi_value_enabled = true;
196        config.wide_arithmetic_enabled = wide_arithmetic.unwrap_or(false);
197        config.compact_imports_enabled = compact_imports.unwrap_or(false);
198        config.memory64_enabled = memory64.unwrap_or(false);
199        config.relaxed_simd_enabled = relaxed_simd.unwrap_or(false);
200        config.simd_enabled = config.relaxed_simd_enabled || simd.unwrap_or(false);
201        config.tail_call_enabled = tail_call.unwrap_or(false);
202        config.custom_page_sizes_enabled = custom_page_sizes.unwrap_or(false);
203        config.threads_enabled = threads.unwrap_or(false);
204        config.shared_everything_threads_enabled = shared_everything_threads.unwrap_or(false);
205        config.gc_enabled = gc.unwrap_or(false);
206        config.reference_types_enabled = config.gc_enabled
207            || self.module_config.function_references_enabled
208            || self.module_config.component_model_async
209            || reference_types.unwrap_or(false);
210        config.extended_const_enabled = extended_const.unwrap_or(false);
211        config.exceptions_enabled =
212            self.module_config.stack_switching || exceptions.unwrap_or(false);
213        if multi_memory.unwrap_or(false) {
214            config.max_memories = limits::MEMORIES_PER_MODULE as usize;
215        } else {
216            config.max_memories = 1;
217        }
218
219        if self.module_config.stack_switching {
220            self.wasmtime.inlining = Some(Inlining::No);
221        }
222
223        if let Some(n) = &mut self.wasmtime.memory_config.memory_reservation {
224            *n = (*n).max(limits::MEMORY_SIZE as u64);
225        }
226        if let Some(n) = &mut self.wasmtime.memory_config.gc_heap_reservation {
227            *n = (*n).max(limits::GC_HEAP_SIZE as u64);
228        }
229
230        // FIXME: it might be more ideal to avoid the need for this entirely
231        // and to just let the test fail. If a test fails due to a pooling
232        // allocator resource limit being met we could ideally detect that and
233        // let the fuzz test case pass. That would avoid the need to hardcode
234        // so much here and in theory wouldn't reduce the usefulness of fuzzers
235        // all that much. At this time though we can't easily test this configuration.
236        if let InstanceAllocationStrategy::Pooling(pooling) = &mut self.wasmtime.strategy {
237            // Clamp protection keys between 1 & 2 to reduce the number of
238            // slots and then multiply the total memories by the number of keys
239            // we have since a single store has access to only one key.
240            pooling.max_memory_protection_keys = pooling.max_memory_protection_keys.max(1).min(2);
241            pooling.total_memories = pooling
242                .total_memories
243                .max(limits::MEMORIES * (pooling.max_memory_protection_keys as u32));
244
245            // For other limits make sure they meet the minimum threshold
246            // required for our wast tests.
247            pooling.total_component_instances = pooling
248                .total_component_instances
249                .max(limits::COMPONENT_INSTANCES);
250            pooling.total_tables = pooling.total_tables.max(limits::TABLES);
251            pooling.max_tables_per_module =
252                pooling.max_tables_per_module.max(limits::TABLES_PER_MODULE);
253            pooling.max_tables_per_component = pooling
254                .max_tables_per_component
255                .max(limits::TABLES_PER_MODULE);
256            pooling.max_memories_per_module = pooling
257                .max_memories_per_module
258                .max(limits::MEMORIES_PER_MODULE);
259            pooling.max_memories_per_component = pooling
260                .max_memories_per_component
261                .max(limits::MEMORIES_PER_COMPONENT);
262            pooling.total_core_instances = pooling.total_core_instances.max(limits::CORE_INSTANCES);
263            pooling.max_memory_size = pooling
264                .max_memory_size
265                .max(limits::MEMORY_SIZE)
266                .max(limits::GC_HEAP_SIZE);
267            pooling.table_elements = pooling.table_elements.max(limits::TABLE_ELEMENTS);
268            pooling.core_instance_size = pooling.core_instance_size.max(limits::CORE_INSTANCE_SIZE);
269            pooling.component_instance_size = pooling
270                .component_instance_size
271                .max(limits::CORE_INSTANCE_SIZE);
272            pooling.total_stacks = pooling.total_stacks.max(limits::TOTAL_STACKS);
273        }
274
275        // Re-enforce internal consistency after all the adjustments above
276        // (e.g. memory_reservation may have been bumped without a
277        // corresponding bump to gc_heap_reservation).
278        self.wasmtime.make_internally_consistent();
279
280        // Return the test configuration that this fuzz configuration represents
281        // which is used afterwards to test if the `test` here is expected to
282        // fail or not.
283        WastConfig {
284            collector: match self.wasmtime.collector {
285                Collector::Null => wasmtime_test_util::wast::Collector::Null,
286                Collector::DeferredReferenceCounting => {
287                    wasmtime_test_util::wast::Collector::DeferredReferenceCounting
288                }
289                Collector::Copying => wasmtime_test_util::wast::Collector::Copying,
290            },
291            pooling: matches!(
292                self.wasmtime.strategy,
293                InstanceAllocationStrategy::Pooling(_)
294            ),
295            compiler: match self.wasmtime.compiler_strategy {
296                CompilerStrategy::CraneliftNative => {
297                    wasmtime_test_util::wast::Compiler::CraneliftNative
298                }
299                CompilerStrategy::CraneliftPulley => {
300                    wasmtime_test_util::wast::Compiler::CraneliftPulley
301                }
302                CompilerStrategy::Winch => wasmtime_test_util::wast::Compiler::Winch,
303            },
304        }
305    }
306
307    /// Converts this to a `wasmtime::Config` object
308    pub fn to_wasmtime(&self) -> wasmtime::Config {
309        crate::init_fuzzing();
310
311        let mut cfg = wasmtime_cli_flags::CommonOptions::default();
312        cfg.codegen.native_unwind_info =
313            Some(cfg!(target_os = "windows") || self.wasmtime.native_unwind_info);
314        cfg.codegen.parallel_compilation = Some(false);
315
316        cfg.debug.address_map = Some(self.wasmtime.generate_address_map);
317        cfg.debug.symbols = Some(self.wasmtime.debug_symbols);
318        cfg.opts.opt_level = Some(self.wasmtime.opt_level.to_wasmtime());
319        cfg.opts.regalloc_algorithm = Some(self.wasmtime.regalloc_algorithm.to_wasmtime());
320        cfg.opts.signals_based_traps = Some(self.wasmtime.signals_based_traps);
321        cfg.opts.memory_guaranteed_dense_image_size = Some(std::cmp::min(
322            // Clamp this at 16MiB so we don't get huge in-memory
323            // images during fuzzing.
324            16 << 20,
325            self.wasmtime.memory_guaranteed_dense_image_size,
326        ));
327        cfg.opts.gc_zeal_alloc_counter = self
328            .wasmtime
329            .gc_zeal_alloc_counter
330            .map(|c| c.clamp(NonZeroU32::new(1).unwrap(), NonZeroU32::new(1024).unwrap()));
331        cfg.wasm.async_stack_zeroing = Some(self.wasmtime.async_stack_zeroing);
332        cfg.wasm.bulk_memory = Some(self.module_config.config.bulk_memory_enabled);
333        cfg.wasm.component_model_async = Some(self.module_config.component_model_async);
334        cfg.wasm.component_model_more_async_builtins =
335            Some(self.module_config.component_model_more_async_builtins);
336        cfg.wasm.component_model_async_stackful =
337            Some(self.module_config.component_model_async_stackful);
338        cfg.wasm.component_model_threading = Some(self.module_config.component_model_threading);
339        cfg.wasm.component_model_error_context =
340            Some(self.module_config.component_model_error_context);
341        cfg.wasm.component_model_gc = Some(self.module_config.component_model_gc);
342        cfg.wasm.component_model_map = Some(self.module_config.component_model_map);
343        cfg.wasm.component_model_memory64 = Some(self.module_config.component_model_memory64);
344        cfg.wasm.component_model_fixed_length_lists =
345            Some(self.module_config.component_model_fixed_length_lists);
346        cfg.wasm.component_model_implements = Some(self.module_config.component_model_implements);
347        cfg.wasm.component_model_canonical_names =
348            Some(self.module_config.component_model_canonical_names);
349        cfg.wasm.component_model_accessors = Some(self.module_config.component_model_accessors);
350        cfg.wasm.custom_page_sizes = Some(self.module_config.config.custom_page_sizes_enabled);
351        cfg.wasm.compact_imports = Some(self.module_config.config.compact_imports_enabled);
352        cfg.wasm.epoch_interruption = Some(self.wasmtime.epoch_interruption);
353        cfg.wasm.extended_const = Some(self.module_config.config.extended_const_enabled);
354        cfg.wasm.fuel = self.wasmtime.consume_fuel.then(|| u64::MAX);
355        cfg.wasm.function_references = Some(self.module_config.function_references_enabled);
356        cfg.wasm.gc = Some(self.module_config.config.gc_enabled);
357        cfg.wasm.memory64 = Some(self.module_config.config.memory64_enabled);
358        cfg.wasm.multi_memory = Some(self.module_config.config.max_memories > 1);
359        cfg.wasm.multi_value = Some(self.module_config.config.multi_value_enabled);
360        cfg.wasm.nan_canonicalization = Some(self.wasmtime.canonicalize_nans);
361        cfg.wasm.reference_types = Some(self.module_config.config.reference_types_enabled);
362        cfg.wasm.simd = Some(self.module_config.config.simd_enabled);
363        cfg.wasm.tail_call = Some(self.module_config.config.tail_call_enabled);
364        cfg.wasm.threads = Some(self.module_config.config.threads_enabled);
365        cfg.wasm.shared_everything_threads =
366            Some(self.module_config.config.shared_everything_threads_enabled);
367        cfg.wasm.wide_arithmetic = Some(self.module_config.config.wide_arithmetic_enabled);
368        cfg.wasm.branch_hinting = Some(self.wasmtime.branch_hinting);
369        cfg.wasm.exceptions = Some(self.module_config.config.exceptions_enabled);
370        // Winch disables GC types by default, but we want to fuzz it
371        if self.wasmtime.compiler_strategy == CompilerStrategy::Winch {
372            cfg.wasm.gc_support = Some(true);
373        }
374        cfg.wasm.stack_switching = Some(self.module_config.stack_switching);
375        cfg.wasm.shared_memory = Some(self.module_config.shared_memory);
376        if !self.module_config.config.simd_enabled {
377            cfg.wasm.relaxed_simd = Some(false);
378        }
379        cfg.codegen.collector = Some(self.wasmtime.collector.to_wasmtime());
380        cfg.codegen.metadata_for_internal_asserts =
381            Some(self.wasmtime.metadata_for_internal_asserts);
382        cfg.codegen.metadata_for_gc_heap_corruption =
383            Some(self.wasmtime.metadata_for_gc_heap_corruption);
384
385        let compiler_strategy = &self.wasmtime.compiler_strategy;
386        let cranelift_strategy = match compiler_strategy {
387            CompilerStrategy::CraneliftNative | CompilerStrategy::CraneliftPulley => true,
388            CompilerStrategy::Winch => false,
389        };
390        self.wasmtime.compiler_strategy.configure(&mut cfg);
391
392        // Host-specific codegen settings (target triple and ISA flags) don't
393        // apply to Pulley, so skip this if that's selected.
394        if *compiler_strategy != CompilerStrategy::CraneliftPulley {
395            self.wasmtime.codegen.configure(&mut cfg);
396        }
397
398        cfg.codegen.inlining = self.wasmtime.inlining.map(|i| i.into());
399
400        // If the wasm-smith-generated module use nan canonicalization then we
401        // don't need to enable it, but if it doesn't enable it already then we
402        // enable this codegen option.
403        cfg.wasm.nan_canonicalization = Some(!self.module_config.config.canonicalize_nans);
404
405        // Only set cranelift specific flags when the Cranelift strategy is
406        // chosen.
407        if cranelift_strategy {
408            if let Some(size) = self.wasmtime.inlining_small_callee_size {
409                cfg.codegen.cranelift.push((
410                    "wasmtime_inlining_small_callee_size".to_string(),
411                    // Clamp to avoid extreme code size blow up.
412                    Some(std::cmp::min(1000, size).to_string()),
413                ));
414            }
415            if let Some(size) = self.wasmtime.inlining_sum_size_threshold {
416                cfg.codegen.cranelift.push((
417                    "wasmtime_inlining_sum_size_threshold".to_string(),
418                    // Clamp to avoid extreme code size blow up.
419                    Some(std::cmp::min(1000, size).to_string()),
420                ));
421            }
422
423            // Enabling the verifier will at-least-double compilation time, which
424            // with a 20-30x slowdown in fuzzing can cause issues related to
425            // timeouts. If generated modules can have more than a small handful of
426            // functions then disable the verifier when fuzzing to try to lessen the
427            // impact of timeouts.
428            if self.module_config.config.max_funcs > 10 {
429                cfg.codegen.cranelift_debug_verifier = Some(false);
430            }
431
432            if self.wasmtime.force_jump_veneers {
433                cfg.codegen.cranelift.push((
434                    "wasmtime_linkopt_force_jump_veneer".to_string(),
435                    Some("true".to_string()),
436                ));
437            }
438
439            if let Some(pad) = self.wasmtime.padding_between_functions {
440                cfg.codegen.cranelift.push((
441                    "wasmtime_linkopt_padding_between_functions".to_string(),
442                    Some(pad.to_string()),
443                ));
444            }
445
446            // Eager init is currently only supported on Cranelift, not Winch.
447            cfg.opts.table_lazy_init = Some(self.wasmtime.table_lazy_init);
448        }
449
450        self.wasmtime.strategy.configure(&mut cfg);
451
452        // Vary the memory configuration, but only if threads are not enabled.
453        // When the threads proposal is enabled we might generate shared memory,
454        // which is less amenable to different memory configurations:
455        // - shared memories are required to be "static" so fuzzing the various
456        //   memory configurations will mostly result in uninteresting errors.
457        //   The interesting part about shared memories is the runtime so we
458        //   don't fuzz non-default settings.
459        // - shared memories are required to be aligned which means that the
460        //   `CustomUnaligned` variant isn't actually safe to use with a shared
461        //   memory.
462        if !self.module_config.config.threads_enabled {
463            let memory_config = self.wasmtime.memory_config.clone();
464            memory_config.configure(&mut cfg);
465        }
466
467        log::debug!("creating wasmtime config with CLI options:\n{cfg}");
468        let mut cfg = cfg.config(None).expect("failed to create wasmtime::Config");
469
470        if self.wasmtime.async_config != AsyncConfig::Disabled {
471            log::debug!("async config in use {:?}", self.wasmtime.async_config);
472            self.wasmtime.async_config.configure(&mut cfg);
473        }
474
475        return cfg;
476    }
477
478    /// Convenience function for generating a `Store<T>` using this
479    /// configuration.
480    pub fn to_store(&self) -> Store<StoreLimits> {
481        let engine = Engine::new(&self.to_wasmtime()).unwrap();
482        let mut store = Store::new(&engine, StoreLimits::new());
483        self.configure_store(&mut store);
484        store
485    }
486
487    /// Configures a store based on this configuration.
488    pub fn configure_store(&self, store: &mut Store<StoreLimits>) {
489        store.limiter(|s| s as &mut dyn wasmtime::ResourceLimiter);
490        self.configure_store_epoch_and_fuel(store);
491    }
492
493    /// Configures everything unrelated to `T` in a store, such as epochs and
494    /// fuel.
495    pub fn configure_store_epoch_and_fuel<T>(&self, store: &mut Store<T>) {
496        // Configure the store to never abort by default, that is it'll have
497        // max fuel or otherwise trap on an epoch change but the epoch won't
498        // ever change.
499        //
500        // Afterwards though see what `AsyncConfig` is being used an further
501        // refine the store's configuration based on that.
502        if self.wasmtime.consume_fuel {
503            store.set_fuel(u64::MAX).unwrap();
504        }
505        if self.wasmtime.epoch_interruption {
506            store.epoch_deadline_trap();
507            store.set_epoch_deadline(1);
508        }
509        match self.wasmtime.async_config {
510            AsyncConfig::Disabled => {}
511            AsyncConfig::YieldWithFuel(amt) => {
512                assert!(self.wasmtime.consume_fuel);
513                store.fuel_async_yield_interval(Some(amt)).unwrap();
514            }
515            AsyncConfig::YieldWithEpochs { ticks, .. } => {
516                assert!(self.wasmtime.epoch_interruption);
517                store.set_epoch_deadline(ticks);
518                store.epoch_deadline_async_yield_and_update(ticks);
519            }
520        }
521    }
522
523    /// Generates an arbitrary method of timing out an instance, ensuring that
524    /// this configuration supports the returned timeout.
525    pub fn generate_timeout(&mut self, u: &mut Unstructured<'_>) -> arbitrary::Result<Timeout> {
526        let time_duration = Duration::from_millis(100);
527        let timeout = u
528            .choose(&[Timeout::Fuel(100_000), Timeout::Epoch(time_duration)])?
529            .clone();
530        match &timeout {
531            Timeout::Fuel(..) => {
532                self.wasmtime.consume_fuel = true;
533            }
534            Timeout::Epoch(..) => {
535                self.wasmtime.epoch_interruption = true;
536            }
537            Timeout::None => unreachable!("Not an option given to choose()"),
538        }
539        Ok(timeout)
540    }
541
542    /// Compiles the `wasm` within the `engine` provided.
543    ///
544    /// This notably will use `Module::{serialize,deserialize_file}` to
545    /// round-trip if configured in the fuzzer.
546    pub fn compile(&self, engine: &Engine, wasm: &[u8]) -> Result<Module> {
547        // Propagate this error in case the caller wants to handle
548        // valid-vs-invalid wasm.
549        let module = Module::new(engine, wasm)?;
550        if !self.wasmtime.use_precompiled_cwasm {
551            return Ok(module);
552        }
553
554        // Don't propagate these errors to prevent them from accidentally being
555        // interpreted as invalid wasm, these should never fail on a
556        // well-behaved host system.
557        let dir = tempfile::TempDir::new().unwrap();
558        let file = dir.path().join("module.wasm");
559        std::fs::write(&file, module.serialize().unwrap()).unwrap();
560        unsafe { Ok(Module::deserialize_file(engine, &file).unwrap()) }
561    }
562
563    /// Updates this configuration to forcibly enable async support. Only useful
564    /// in fuzzers which do async calls.
565    pub fn enable_async(&mut self, u: &mut Unstructured<'_>) -> arbitrary::Result<()> {
566        if self.wasmtime.consume_fuel || u.arbitrary()? {
567            self.wasmtime.async_config =
568                AsyncConfig::YieldWithFuel(u.int_in_range(1000..=100_000)?);
569            self.wasmtime.consume_fuel = true;
570        } else {
571            self.wasmtime.async_config = AsyncConfig::YieldWithEpochs {
572                dur: Duration::from_millis(u.int_in_range(1..=10)?),
573                ticks: u.int_in_range(1..=10)?,
574            };
575            self.wasmtime.epoch_interruption = true;
576        }
577        Ok(())
578    }
579}
580
581impl<'a> Arbitrary<'a> for Config {
582    fn arbitrary(u: &mut Unstructured<'a>) -> arbitrary::Result<Self> {
583        let mut config = Self {
584            wasmtime: u.arbitrary()?,
585            module_config: u.arbitrary()?,
586        };
587
588        config
589            .wasmtime
590            .update_module_config(&mut config.module_config, u)?;
591
592        Ok(config)
593    }
594}
595
596/// Configuration related to `wasmtime::Config` and the various settings which
597/// can be tweaked from within.
598#[derive(Arbitrary, Clone, Debug, Eq, Hash, PartialEq)]
599pub struct WasmtimeConfig {
600    opt_level: OptLevel,
601    regalloc_algorithm: RegallocAlgorithm,
602    debug_info: bool,
603    debug_symbols: bool,
604    canonicalize_nans: bool,
605    interruptible: bool,
606    pub(crate) consume_fuel: bool,
607    pub(crate) epoch_interruption: bool,
608    /// The Wasmtime memory configuration to use.
609    pub memory_config: MemoryConfig,
610    force_jump_veneers: bool,
611    memory_init_cow: bool,
612    memory_guaranteed_dense_image_size: u64,
613    inlining: Option<Inlining>,
614    inlining_small_callee_size: Option<u32>,
615    inlining_sum_size_threshold: Option<u32>,
616    use_precompiled_cwasm: bool,
617    async_stack_zeroing: bool,
618    /// Configuration for the instance allocation strategy to use.
619    pub strategy: InstanceAllocationStrategy,
620    codegen: CodegenSettings,
621    padding_between_functions: Option<u16>,
622    generate_address_map: bool,
623    native_unwind_info: bool,
624    /// Configuration for the compiler to use.
625    pub compiler_strategy: CompilerStrategy,
626    collector: Collector,
627    gc_zeal_alloc_counter: Option<NonZeroU32>,
628    table_lazy_init: bool,
629    metadata_for_internal_asserts: bool,
630    metadata_for_gc_heap_corruption: bool,
631    /// Whether the branch-hinting proposal is enabled. wasm-smith does not emit
632    /// `metadata.code.branch_hint` sections, so for generated modules this only
633    /// toggles the (otherwise no-op) parsing path.
634    branch_hinting: bool,
635
636    /// Configuration for whether wasm is invoked in an async fashion and how
637    /// it's cooperatively time-sliced.
638    pub async_config: AsyncConfig,
639
640    /// Whether or not host signal handlers are enabled for this configuration,
641    /// aka whether signal handlers are supported.
642    signals_based_traps: bool,
643}
644
645impl WasmtimeConfig {
646    /// Force `self` to be a configuration compatible with `other`. This is
647    /// useful for differential execution to avoid unhelpful fuzz crashes when
648    /// one engine has a feature enabled and the other does not.
649    pub fn make_compatible_with(&mut self, other: &Self) {
650        // Use the same allocation strategy between the two configs.
651        //
652        // Ideally this wouldn't be necessary, but, during differential
653        // evaluation, if the `lhs` is using ondemand and the `rhs` is using the
654        // pooling allocator (or vice versa), then the module may have been
655        // generated in such a way that is incompatible with the other
656        // allocation strategy.
657        //
658        // We can remove this in the future when it's possible to access the
659        // fields of `wasm_smith::Module` to constrain the pooling allocator
660        // based on what was actually generated.
661        self.strategy = other.strategy.clone();
662        if let InstanceAllocationStrategy::Pooling { .. } = &other.strategy {
663            // Also use the same memory configuration when using the pooling
664            // allocator.
665            self.memory_config = other.memory_config.clone();
666        }
667
668        self.make_internally_consistent();
669    }
670
671    /// Updates `config` to be compatible with `self` and the other way around
672    /// too.
673    pub fn update_module_config(
674        &mut self,
675        config: &mut ModuleConfig,
676        _u: &mut Unstructured<'_>,
677    ) -> arbitrary::Result<()> {
678        match self.compiler_strategy {
679            CompilerStrategy::CraneliftNative => {}
680
681            CompilerStrategy::Winch => {
682                // Winch doesn't support the same set of wasm proposal as Cranelift
683                // at this time, so if winch is selected be sure to disable wasm
684                // proposals in `Config` to ensure that Winch can compile the
685                // module that wasm-smith generates.
686                config.config.relaxed_simd_enabled = false;
687                config.config.gc_enabled = false;
688                config.config.reference_types_enabled = false;
689                config.function_references_enabled = false;
690                config.stack_switching = false;
691
692                // Winch's SIMD implementations require AVX and AVX2.
693                if self
694                    .codegen_flag("has_avx")
695                    .is_some_and(|value| value == "false")
696                    || self
697                        .codegen_flag("has_avx2")
698                        .is_some_and(|value| value == "false")
699                {
700                    config.config.simd_enabled = false;
701                }
702
703                // Account for the proposals that Winch only supports on x64.
704                if cfg!(target_arch = "aarch64") {
705                    config.config.wide_arithmetic_enabled = false;
706                    config.config.threads_enabled = false;
707                }
708
709                // Tuning  the following engine options is currently not supported
710                // by Winch.
711                self.signals_based_traps = true;
712                self.table_lazy_init = true;
713                self.debug_info = false;
714            }
715
716            CompilerStrategy::CraneliftPulley => {
717                config.config.threads_enabled = false;
718
719                // Pulley doesn't use signals anyway and this avoids configuring
720                // the engine on platorms which don't support signals anyway, so
721                // alway disable.
722                self.signals_based_traps = false;
723            }
724        }
725
726        // Unconditionally disable s390x signals because in CI they're disabled
727        // in Wasmtime due to possible QEMU emulation bugs (see wasmtime's
728        // `build.rs`). In such a situation if it were enabled here that'd lead
729        // to an error because Wasmtime would claim a lack of support.
730        if cfg!(target_arch = "s390x") {
731            self.signals_based_traps = false;
732        }
733
734        // If using the pooling allocator, constrain the memory and module configurations
735        // to the module limits.
736        if let InstanceAllocationStrategy::Pooling(pooling) = &mut self.strategy {
737            // If the pooling allocator is used, do not allow shared memory to
738            // be created. FIXME: see
739            // https://github.com/bytecodealliance/wasmtime/issues/4244.
740            config.config.threads_enabled = false;
741
742            // Ensure the pooling allocator can support the maximal size of
743            // memory, picking the smaller of the two to win.
744            let min_bytes = config
745                .config
746                .max_memory32_bytes
747                // memory64_bytes is a u128, but since we are taking the min
748                // we can truncate it down to a u64.
749                .min(
750                    config
751                        .config
752                        .max_memory64_bytes
753                        .try_into()
754                        .unwrap_or(u64::MAX),
755                );
756            let min = min_bytes
757                .min(pooling.max_memory_size as u64)
758                .min(self.memory_config.memory_reservation.unwrap_or(0));
759            pooling.max_memory_size = min as usize;
760            config.config.max_memory32_bytes = min;
761            config.config.max_memory64_bytes = min as u128;
762
763            // If traps are disallowed then memories must have at least one page
764            // of memory so if we still are only allowing 0 pages of memory then
765            // increase that to one here.
766            if config.config.disallow_traps {
767                if pooling.max_memory_size < (1 << 16) {
768                    pooling.max_memory_size = 1 << 16;
769                    config.config.max_memory32_bytes = 1 << 16;
770                    config.config.max_memory64_bytes = 1 << 16;
771                    let cfg = &mut self.memory_config;
772                    match &mut cfg.memory_reservation {
773                        Some(size) => *size = (*size).max(pooling.max_memory_size as u64),
774                        size @ None => *size = Some(pooling.max_memory_size as u64),
775                    }
776                }
777                // .. additionally update tables
778                if pooling.table_elements == 0 {
779                    pooling.table_elements = 1;
780                }
781            }
782
783            // Don't allow too many linear memories per instance since massive
784            // virtual mappings can fail to get allocated.
785            config.config.min_memories = config.config.min_memories.min(10);
786            config.config.max_memories = config.config.max_memories.min(10);
787
788            // Force this pooling allocator to always be able to accommodate the
789            // module that may be generated.
790            pooling.total_memories = config.config.max_memories as u32;
791            pooling.total_tables = config.config.max_tables as u32;
792        }
793
794        if !self.signals_based_traps {
795            // At this time shared memories require a "static" memory
796            // configuration but when signals-based traps are disabled all
797            // memories are forced to the "dynamic" configuration. This is
798            // fixable with some more work on the bounds-checks side of things
799            // to do a full bounds check even on static memories, but that's
800            // left for a future PR.
801            config.config.threads_enabled = false;
802
803            // Spectre-based heap mitigations require signal handlers so this
804            // must always be disabled if signals-based traps are disabled.
805            self.memory_config
806                .cranelift_enable_heap_access_spectre_mitigations = None;
807        }
808
809        self.make_internally_consistent();
810
811        Ok(())
812    }
813
814    /// Returns the codegen flag value, if any, for `name`.
815    pub(crate) fn codegen_flag(&self, name: &str) -> Option<&str> {
816        self.codegen.flags().iter().find_map(|(n, value)| {
817            if n == name {
818                Some(value.as_str())
819            } else {
820                None
821            }
822        })
823    }
824
825    /// Helper method to handle some dependencies between various configuration
826    /// options. This is intended to be called whenever a `Config` is created or
827    /// modified to ensure that the final result is an instantiable `Config`.
828    ///
829    /// Note that in general this probably shouldn't exist and anything here can
830    /// be considered a "TODO" to go implement more stuff in Wasmtime to accept
831    /// these sorts of configurations. For now though it's intended to reflect
832    /// the current state of the engine's development.
833    pub(crate) fn make_internally_consistent(&mut self) {
834        if !self.signals_based_traps {
835            // Spectre-based heap mitigations require signal handlers so
836            // this must always be disabled if signals-based traps are
837            // disabled.
838            self.memory_config
839                .cranelift_enable_heap_access_spectre_mitigations = None;
840        }
841
842        // If malloc-based memory is going to be used, which requires these
843        // options set to specific values (and Pulley auto-sets some of them)
844        // then be sure to cap `memory_reservation_for_growth` and
845        // `gc_heap_reservation_for_growth` at a smaller value than the
846        // default. For malloc-based memory/heaps, reservation beyond the end
847        // isn't captured by `StoreLimiter` so we need to be sure it's small
848        // enough to not blow OOM limits while fuzzing.
849        let is_pulley = self.compiler_strategy == CompilerStrategy::CraneliftPulley;
850        let mcfg = &mut self.memory_config;
851        if !self.signals_based_traps || is_pulley {
852            if (mcfg.memory_guard_size == Some(0) || is_pulley)
853                && mcfg.memory_reservation == Some(0)
854                && !mcfg.memory_init_cow
855            {
856                let growth = &mut mcfg.memory_reservation_for_growth;
857                let max = 1 << 20;
858                *growth = match *growth {
859                    Some(n) => Some(n.min(max)),
860                    None => Some(max),
861                };
862            }
863            if (mcfg.gc_heap_guard_size == Some(0) || is_pulley)
864                && mcfg.gc_heap_reservation == Some(0)
865            {
866                let growth = &mut mcfg.gc_heap_reservation_for_growth;
867                let max = 1 << 20;
868                *growth = match *growth {
869                    Some(n) => Some(n.min(max)),
870                    None => Some(max),
871                };
872            }
873        }
874
875        // When using the pooling allocator, GC heap tunables must match memory
876        // tunables.
877        if let InstanceAllocationStrategy::Pooling(pcfg) = &self.strategy {
878            let reservation = mcfg.gc_heap_reservation.max(mcfg.memory_reservation);
879            mcfg.gc_heap_reservation = reservation;
880            mcfg.memory_reservation = reservation;
881
882            let guard_size = mcfg.gc_heap_guard_size.max(mcfg.memory_guard_size);
883            mcfg.gc_heap_guard_size = guard_size;
884            mcfg.memory_guard_size = guard_size;
885
886            let res_for_growth = mcfg
887                .gc_heap_reservation_for_growth
888                .max(mcfg.memory_reservation_for_growth);
889            mcfg.gc_heap_reservation_for_growth = res_for_growth;
890            mcfg.memory_reservation_for_growth = res_for_growth;
891
892            // memory_may_move is not in MemoryConfig, but gc_heap_may_move
893            // must not conflict. Set it to None so the default matches.
894            mcfg.gc_heap_may_move = None;
895
896            // Don't let the initial size of a GC heap exceed the maximum
897            // allowed by the pooling allocator. Note that these sizes are
898            // rounded up to the wasm page size used by GC at this time as
899            // that's what happens internally.
900            if let Some(amt) = mcfg.gc_heap_initial_size {
901                let page_size = 64 * 1024;
902                let amt = amt.next_multiple_of(page_size);
903                // Round down so the GC's round-up-to-page-size doesn't push
904                // this back over the pooling limit.
905                let max = (pcfg.max_memory_size as u64) / page_size * page_size;
906                mcfg.gc_heap_initial_size = Some(amt.min(max));
907            }
908        }
909
910        if !self.debug_symbols {
911            self.debug_info = false;
912        }
913    }
914}
915
916#[derive(Arbitrary, Clone, Debug, PartialEq, Eq, Hash)]
917enum OptLevel {
918    None,
919    Speed,
920    SpeedAndSize,
921}
922
923impl OptLevel {
924    fn to_wasmtime(&self) -> wasmtime::OptLevel {
925        match self {
926            OptLevel::None => wasmtime::OptLevel::None,
927            OptLevel::Speed => wasmtime::OptLevel::Speed,
928            OptLevel::SpeedAndSize => wasmtime::OptLevel::SpeedAndSize,
929        }
930    }
931}
932
933#[derive(Arbitrary, Clone, Debug, PartialEq, Eq, Hash)]
934enum RegallocAlgorithm {
935    Backtracking,
936    SinglePass,
937}
938
939impl RegallocAlgorithm {
940    fn to_wasmtime(&self) -> wasmtime::RegallocAlgorithm {
941        match self {
942            RegallocAlgorithm::Backtracking => wasmtime::RegallocAlgorithm::Backtracking,
943            RegallocAlgorithm::SinglePass => {
944                const SINGLE_PASS_KNOWN_BUGGY_AT_THIS_TIME: bool = false;
945                if SINGLE_PASS_KNOWN_BUGGY_AT_THIS_TIME {
946                    wasmtime::RegallocAlgorithm::Backtracking
947                } else {
948                    wasmtime::RegallocAlgorithm::SinglePass
949                }
950            }
951        }
952    }
953}
954
955#[derive(Arbitrary, Clone, Copy, Debug, PartialEq, Eq, Hash)]
956enum Inlining {
957    Yes,
958    InterModuleAndIntraGc,
959    InterModule,
960    Intrinsics,
961    No,
962}
963
964impl From<Inlining> for wasmtime::Inlining {
965    fn from(i: Inlining) -> Self {
966        let ret = match i {
967            Inlining::Yes => wasmtime::Inlining::Yes,
968            Inlining::InterModuleAndIntraGc => wasmtime::Inlining::InterModuleAndIntraGc,
969            Inlining::InterModule => wasmtime::Inlining::InterModule,
970            Inlining::Intrinsics => wasmtime::Inlining::Intrinsics,
971            Inlining::No => wasmtime::Inlining::No,
972        };
973
974        match ret {
975            wasmtime::Inlining::Yes
976            | wasmtime::Inlining::No
977            | wasmtime::Inlining::InterModuleAndIntraGc
978            | wasmtime::Inlining::InterModule
979            | wasmtime::Inlining::Intrinsics
980            // NOTE: if you add another arm here, be sure to update the
981            // `Inlining` enum above.
982            => ret,
983        }
984    }
985}
986
987#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
988/// Compiler to use.
989pub enum CompilerStrategy {
990    /// Cranelift compiler for the native architecture.
991    CraneliftNative,
992    /// Winch compiler.
993    Winch,
994    /// Cranelift compiler for the native architecture.
995    CraneliftPulley,
996}
997
998impl CompilerStrategy {
999    /// Whether native Cranelift (`CraneliftNative`) can run on this host.
1000    pub const CRANELIFT_NATIVE_SUPPORTED: bool = cfg!(any(
1001        target_arch = "x86_64",
1002        target_arch = "aarch64",
1003        target_arch = "riscv64",
1004        target_arch = "s390x",
1005    ));
1006
1007    /// Whether Winch can run on this host.
1008    pub const WINCH_SUPPORTED: bool = cfg!(any(target_arch = "x86_64", target_arch = "aarch64"));
1009
1010    /// Configures `config` to use this compilation strategy
1011    pub fn configure(&self, config: &mut wasmtime_cli_flags::CommonOptions) {
1012        match self {
1013            CompilerStrategy::CraneliftNative => {
1014                config.codegen.compiler = Some(wasmtime::Strategy::Cranelift);
1015            }
1016            CompilerStrategy::Winch => {
1017                config.codegen.compiler = Some(wasmtime::Strategy::Winch);
1018            }
1019            CompilerStrategy::CraneliftPulley => {
1020                config.codegen.compiler = Some(wasmtime::Strategy::Cranelift);
1021                if cfg!(target_pointer_width = "32") {
1022                    config.target = Some("pulley32".to_string());
1023                } else if cfg!(target_endian = "big") {
1024                    config.target = Some("pulley64be".to_string());
1025                } else {
1026                    config.target = Some("pulley64".to_string());
1027                }
1028            }
1029        }
1030    }
1031}
1032
1033impl Arbitrary<'_> for CompilerStrategy {
1034    fn arbitrary(u: &mut Unstructured<'_>) -> arbitrary::Result<Self> {
1035        // Favor actually using native cranelift, but if it's not actually
1036        // supported on this platform then fall back to pulley instead.
1037        // Similarly, when winch is selected use that when it's supported,
1038        // otherwise fall back to whatever cranelift is.
1039        let native = if Self::CRANELIFT_NATIVE_SUPPORTED {
1040            Self::CraneliftNative
1041        } else {
1042            Self::CraneliftPulley
1043        };
1044        let winch = if Self::WINCH_SUPPORTED {
1045            Self::Winch
1046        } else {
1047            native
1048        };
1049
1050        // Favor fuzzing native cranelift, but if allowed also enable
1051        // winch/pulley.
1052        Ok(match u.int_in_range(0..=19)? {
1053            1 => Self::CraneliftPulley,
1054            2 => winch,
1055            _ => native,
1056        })
1057    }
1058}
1059
1060#[derive(Arbitrary, Clone, Debug, PartialEq, Eq, Hash)]
1061pub enum Collector {
1062    DeferredReferenceCounting,
1063    Null,
1064    Copying,
1065}
1066
1067impl Collector {
1068    fn to_wasmtime(&self) -> wasmtime::Collector {
1069        match self {
1070            Collector::DeferredReferenceCounting => wasmtime::Collector::DeferredReferenceCounting,
1071            Collector::Null => wasmtime::Collector::Null,
1072            Collector::Copying => wasmtime::Collector::Copying,
1073        }
1074    }
1075}