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