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