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