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