1 //! Test case generators.
2 //!
3 //! Test case generators take raw, unstructured input from a fuzzer
4 //! (e.g. libFuzzer) and translate that into a structured test case (e.g. a
5 //! valid Wasm binary).
6 //!
7 //! These are generally implementations of the `Arbitrary` trait, or some
8 //! wrapper over an external tool, such that the wrapper implements the
9 //! `Arbitrary` trait for the wrapped external tool.
10 
11 pub mod api;
12 pub mod table_ops;
13 
14 use crate::oracles::{StoreLimits, Timeout};
15 use anyhow::Result;
16 use arbitrary::{Arbitrary, Unstructured};
17 use std::sync::Arc;
18 use std::time::Duration;
19 use wasm_smith::SwarmConfig;
20 use wasmtime::{Engine, LinearMemory, MemoryCreator, MemoryType, Module, Store};
21 
22 #[derive(Arbitrary, Clone, Debug, PartialEq, Eq, Hash)]
23 enum OptLevel {
24     None,
25     Speed,
26     SpeedAndSize,
27 }
28 
29 impl OptLevel {
30     fn to_wasmtime(&self) -> wasmtime::OptLevel {
31         match self {
32             OptLevel::None => wasmtime::OptLevel::None,
33             OptLevel::Speed => wasmtime::OptLevel::Speed,
34             OptLevel::SpeedAndSize => wasmtime::OptLevel::SpeedAndSize,
35         }
36     }
37 }
38 
39 /// Configuration for `wasmtime::PoolingAllocationStrategy`.
40 #[derive(Arbitrary, Clone, Debug, PartialEq, Eq, Hash)]
41 pub enum PoolingAllocationStrategy {
42     /// Use next available instance slot.
43     NextAvailable,
44     /// Use random instance slot.
45     Random,
46     /// Use an affinity-based strategy.
47     ReuseAffinity,
48 }
49 
50 impl PoolingAllocationStrategy {
51     fn to_wasmtime(&self) -> wasmtime::PoolingAllocationStrategy {
52         match self {
53             PoolingAllocationStrategy::NextAvailable => {
54                 wasmtime::PoolingAllocationStrategy::NextAvailable
55             }
56             PoolingAllocationStrategy::Random => wasmtime::PoolingAllocationStrategy::Random,
57             PoolingAllocationStrategy::ReuseAffinity => {
58                 wasmtime::PoolingAllocationStrategy::ReuseAffinity
59             }
60         }
61     }
62 }
63 /// Configuration for `wasmtime::PoolingAllocationStrategy`.
64 #[derive(Debug, Clone, Eq, PartialEq, Hash)]
65 #[allow(missing_docs)]
66 pub struct InstanceLimits {
67     pub count: u32,
68     pub memories: u32,
69     pub tables: u32,
70     pub memory_pages: u64,
71     pub table_elements: u32,
72     pub size: usize,
73 }
74 
75 impl InstanceLimits {
76     fn to_wasmtime(&self) -> wasmtime::InstanceLimits {
77         wasmtime::InstanceLimits {
78             count: self.count,
79             memories: self.memories,
80             tables: self.tables,
81             memory_pages: self.memory_pages,
82             table_elements: self.table_elements,
83             size: self.size,
84         }
85     }
86 }
87 
88 impl<'a> Arbitrary<'a> for InstanceLimits {
89     fn arbitrary(u: &mut Unstructured<'a>) -> arbitrary::Result<Self> {
90         const MAX_COUNT: u32 = 100;
91 
92         const MAX_TABLES: u32 = 10;
93         const MAX_MEMORIES: u32 = 10;
94         const MAX_ELEMENTS: u32 = 1000;
95         const MAX_MEMORY_PAGES: u64 = 160; // 10 MiB
96         const MAX_SIZE: usize = 1 << 20; // 1 MiB
97 
98         Ok(Self {
99             tables: u.int_in_range(0..=MAX_TABLES)?,
100             memories: u.int_in_range(0..=MAX_MEMORIES)?,
101             table_elements: u.int_in_range(0..=MAX_ELEMENTS)?,
102             memory_pages: u.int_in_range(0..=MAX_MEMORY_PAGES)?,
103             count: u.int_in_range(1..=MAX_COUNT)?,
104             size: u.int_in_range(0..=MAX_SIZE)?,
105         })
106     }
107 }
108 
109 /// Configuration for `wasmtime::InstanceAllocationStrategy`.
110 #[derive(Arbitrary, Clone, Debug, Eq, PartialEq, Hash)]
111 pub enum InstanceAllocationStrategy {
112     /// Use the on-demand instance allocation strategy.
113     OnDemand,
114     /// Use the pooling instance allocation strategy.
115     Pooling {
116         /// The pooling strategy to use.
117         strategy: PoolingAllocationStrategy,
118         /// The instance limits.
119         instance_limits: InstanceLimits,
120     },
121 }
122 
123 impl InstanceAllocationStrategy {
124     fn to_wasmtime(&self) -> wasmtime::InstanceAllocationStrategy {
125         match self {
126             InstanceAllocationStrategy::OnDemand => wasmtime::InstanceAllocationStrategy::OnDemand,
127             InstanceAllocationStrategy::Pooling {
128                 strategy,
129                 instance_limits,
130             } => wasmtime::InstanceAllocationStrategy::Pooling {
131                 strategy: strategy.to_wasmtime(),
132                 instance_limits: instance_limits.to_wasmtime(),
133             },
134         }
135     }
136 }
137 
138 /// Configuration for `wasmtime::Config` and generated modules for a session of
139 /// fuzzing.
140 ///
141 /// This configuration guides what modules are generated, how wasmtime
142 /// configuration is generated, and is typically itself generated through a call
143 /// to `Arbitrary` which allows for a form of "swarm testing".
144 #[derive(Debug, Clone)]
145 pub struct Config {
146     /// Configuration related to the `wasmtime::Config`.
147     pub wasmtime: WasmtimeConfig,
148     /// Configuration related to generated modules.
149     pub module_config: ModuleConfig,
150 }
151 
152 impl<'a> Arbitrary<'a> for Config {
153     fn arbitrary(u: &mut Unstructured<'a>) -> arbitrary::Result<Self> {
154         let mut config = Self {
155             wasmtime: u.arbitrary()?,
156             module_config: u.arbitrary()?,
157         };
158 
159         // If using the pooling allocator, constrain the memory and module configurations
160         // to the module limits.
161         if let InstanceAllocationStrategy::Pooling {
162             instance_limits: limits,
163             ..
164         } = &config.wasmtime.strategy
165         {
166             // Force the use of a normal memory config when using the pooling allocator and
167             // limit the static memory maximum to be the same as the pooling allocator's memory
168             // page limit.
169             config.wasmtime.memory_config = match config.wasmtime.memory_config {
170                 MemoryConfig::Normal(mut config) => {
171                     config.static_memory_maximum_size = Some(limits.memory_pages * 0x10000);
172                     MemoryConfig::Normal(config)
173                 }
174                 MemoryConfig::CustomUnaligned => {
175                     let mut config: NormalMemoryConfig = u.arbitrary()?;
176                     config.static_memory_maximum_size = Some(limits.memory_pages * 0x10000);
177                     MemoryConfig::Normal(config)
178                 }
179             };
180 
181             let cfg = &mut config.module_config.config;
182             cfg.max_memories = limits.memories as usize;
183             cfg.max_tables = limits.tables as usize;
184             cfg.max_memory_pages = limits.memory_pages;
185 
186             // Force no aliases in any generated modules as they might count against the
187             // import limits above.
188             cfg.max_aliases = 0;
189         }
190 
191         Ok(config)
192     }
193 }
194 
195 /// Configuration related to `wasmtime::Config` and the various settings which
196 /// can be tweaked from within.
197 #[derive(Arbitrary, Clone, Debug, Eq, Hash, PartialEq)]
198 pub struct WasmtimeConfig {
199     opt_level: OptLevel,
200     debug_info: bool,
201     canonicalize_nans: bool,
202     interruptable: bool,
203     pub(crate) consume_fuel: bool,
204     epoch_interruption: bool,
205     /// The Wasmtime memory configuration to use.
206     pub memory_config: MemoryConfig,
207     force_jump_veneers: bool,
208     memory_init_cow: bool,
209     memory_guaranteed_dense_image_size: u64,
210     use_precompiled_cwasm: bool,
211     /// Configuration for the instance allocation strategy to use.
212     pub strategy: InstanceAllocationStrategy,
213     codegen: CodegenSettings,
214     padding_between_functions: Option<u16>,
215     generate_address_map: bool,
216 }
217 
218 /// Configuration for linear memories in Wasmtime.
219 #[derive(Arbitrary, Clone, Debug, Eq, Hash, PartialEq)]
220 pub enum MemoryConfig {
221     /// Configuration for linear memories which correspond to normal
222     /// configuration settings in `wasmtime` itself. This will tweak various
223     /// parameters about static/dynamic memories.
224     Normal(NormalMemoryConfig),
225 
226     /// Configuration to force use of a linear memory that's unaligned at its
227     /// base address to force all wasm addresses to be unaligned at the hardware
228     /// level, even if the wasm itself correctly aligns everything internally.
229     CustomUnaligned,
230 }
231 
232 /// Represents a normal memory configuration for Wasmtime with the given
233 /// static and dynamic memory sizes.
234 #[derive(Clone, Debug, Eq, Hash, PartialEq)]
235 pub struct NormalMemoryConfig {
236     static_memory_maximum_size: Option<u64>,
237     static_memory_guard_size: Option<u64>,
238     dynamic_memory_guard_size: Option<u64>,
239     guard_before_linear_memory: bool,
240 }
241 
242 impl<'a> Arbitrary<'a> for NormalMemoryConfig {
243     fn arbitrary(u: &mut Unstructured<'a>) -> arbitrary::Result<Self> {
244         // This attempts to limit memory and guard sizes to 32-bit ranges so
245         // we don't exhaust a 64-bit address space easily.
246         Ok(Self {
247             static_memory_maximum_size: <Option<u32> as Arbitrary>::arbitrary(u)?.map(Into::into),
248             static_memory_guard_size: <Option<u32> as Arbitrary>::arbitrary(u)?.map(Into::into),
249             dynamic_memory_guard_size: <Option<u32> as Arbitrary>::arbitrary(u)?.map(Into::into),
250             guard_before_linear_memory: u.arbitrary()?,
251         })
252     }
253 }
254 
255 impl Config {
256     /// Indicates that this configuration is being used for differential
257     /// execution so only a single function should be generated since that's all
258     /// that's going to be exercised.
259     pub fn set_differential_config(&mut self) {
260         let config = &mut self.module_config.config;
261 
262         config.allow_start_export = false;
263         // Make sure there's a type available for the function.
264         config.min_types = 1;
265         config.max_types = 1;
266 
267         // Generate one and only one function
268         config.min_funcs = 1;
269         config.max_funcs = 1;
270 
271         // Give the function a memory, but keep it small
272         config.min_memories = 1;
273         config.max_memories = 1;
274         config.max_memory_pages = 1;
275         config.memory_max_size_required = true;
276 
277         // While reference types are disabled below, only allow one table
278         config.max_tables = 1;
279 
280         // Don't allow any imports
281         config.max_imports = 0;
282 
283         // Try to get the function and the memory exported
284         config.min_exports = 2;
285         config.max_exports = 4;
286 
287         // NaN is canonicalized at the wasm level for differential fuzzing so we
288         // can paper over NaN differences between engines.
289         config.canonicalize_nans = true;
290 
291         // When diffing against a non-wasmtime engine then disable wasm
292         // features to get selectively re-enabled against each differential
293         // engine.
294         config.bulk_memory_enabled = false;
295         config.reference_types_enabled = false;
296         config.simd_enabled = false;
297         config.memory64_enabled = false;
298 
299         // If using the pooling allocator, update the instance limits too
300         if let InstanceAllocationStrategy::Pooling {
301             instance_limits: limits,
302             ..
303         } = &mut self.wasmtime.strategy
304         {
305             // One single-page memory
306             limits.memories = 1;
307             limits.memory_pages = 1;
308 
309             limits.tables = 1;
310 
311             match &mut self.wasmtime.memory_config {
312                 MemoryConfig::Normal(config) => {
313                     config.static_memory_maximum_size = Some(limits.memory_pages * 0x10000);
314                 }
315                 MemoryConfig::CustomUnaligned => unreachable!(), // Arbitrary impl for `Config` should have prevented this
316             }
317         }
318     }
319 
320     /// Uses this configuration and the supplied source of data to generate
321     /// a wasm module.
322     ///
323     /// If a `default_fuel` is provided, the resulting module will be configured
324     /// to ensure termination; as doing so will add an additional global to the module,
325     /// the pooling allocator, if configured, will also have its globals limit updated.
326     pub fn generate(
327         &mut self,
328         input: &mut Unstructured<'_>,
329         default_fuel: Option<u32>,
330     ) -> arbitrary::Result<wasm_smith::Module> {
331         let mut module = wasm_smith::Module::new(self.module_config.config.clone(), input)?;
332 
333         if let Some(default_fuel) = default_fuel {
334             module.ensure_termination(default_fuel);
335         }
336 
337         Ok(module)
338     }
339 
340     /// Indicates that this configuration should be spec-test-compliant,
341     /// disabling various features the spec tests assert are disabled.
342     pub fn set_spectest_compliant(&mut self) {
343         let config = &mut self.module_config.config;
344         config.memory64_enabled = false;
345         config.simd_enabled = false;
346         config.bulk_memory_enabled = true;
347         config.reference_types_enabled = true;
348         config.multi_value_enabled = true;
349         config.max_memories = 1;
350         config.max_tables = 5;
351 
352         if let InstanceAllocationStrategy::Pooling {
353             instance_limits: limits,
354             ..
355         } = &mut self.wasmtime.strategy
356         {
357             // Configure the lower bound of a number of limits to what's
358             // required to actually run the spec tests. Fuzz-generated inputs
359             // may have limits less than these thresholds which would cause the
360             // spec tests to fail which isn't particularly interesting.
361             limits.memories = limits.memories.max(1);
362             limits.tables = limits.memories.max(5);
363             limits.table_elements = limits.memories.max(1_000);
364             limits.memory_pages = limits.memory_pages.max(900);
365             limits.count = limits.count.max(500);
366             limits.size = limits.size.max(64 * 1024);
367 
368             match &mut self.wasmtime.memory_config {
369                 MemoryConfig::Normal(config) => {
370                     config.static_memory_maximum_size = Some(limits.memory_pages * 0x10000);
371                 }
372                 MemoryConfig::CustomUnaligned => unreachable!(), // Arbitrary impl for `Config` should have prevented this
373             }
374         }
375     }
376 
377     /// Converts this to a `wasmtime::Config` object
378     pub fn to_wasmtime(&self) -> wasmtime::Config {
379         crate::init_fuzzing();
380         log::debug!("creating wasmtime config with {:#?}", self.wasmtime);
381 
382         let mut cfg = wasmtime::Config::new();
383         cfg.wasm_bulk_memory(true)
384             .wasm_reference_types(true)
385             .wasm_multi_value(self.module_config.config.multi_value_enabled)
386             .wasm_multi_memory(self.module_config.config.max_memories > 1)
387             .wasm_simd(self.module_config.config.simd_enabled)
388             .wasm_memory64(self.module_config.config.memory64_enabled)
389             .cranelift_nan_canonicalization(self.wasmtime.canonicalize_nans)
390             .cranelift_opt_level(self.wasmtime.opt_level.to_wasmtime())
391             .consume_fuel(self.wasmtime.consume_fuel)
392             .epoch_interruption(self.wasmtime.epoch_interruption)
393             .memory_init_cow(self.wasmtime.memory_init_cow)
394             .memory_guaranteed_dense_image_size(std::cmp::min(
395                 // Clamp this at 16MiB so we don't get huge in-memory
396                 // images during fuzzing.
397                 16 << 20,
398                 self.wasmtime.memory_guaranteed_dense_image_size,
399             ))
400             .allocation_strategy(self.wasmtime.strategy.to_wasmtime())
401             .generate_address_map(self.wasmtime.generate_address_map);
402 
403         self.wasmtime.codegen.configure(&mut cfg);
404 
405         // If the wasm-smith-generated module use nan canonicalization then we
406         // don't need to enable it, but if it doesn't enable it already then we
407         // enable this codegen option.
408         cfg.cranelift_nan_canonicalization(!self.module_config.config.canonicalize_nans);
409 
410         // Enabling the verifier will at-least-double compilation time, which
411         // with a 20-30x slowdown in fuzzing can cause issues related to
412         // timeouts. If generated modules can have more than a small handful of
413         // functions then disable the verifier when fuzzing to try to lessen the
414         // impact of timeouts.
415         if self.module_config.config.max_funcs > 10 {
416             cfg.cranelift_debug_verifier(false);
417         }
418 
419         if self.wasmtime.force_jump_veneers {
420             unsafe {
421                 cfg.cranelift_flag_set("wasmtime_linkopt_force_jump_veneer", "true")
422                     .unwrap();
423             }
424         }
425 
426         if let Some(pad) = self.wasmtime.padding_between_functions {
427             unsafe {
428                 cfg.cranelift_flag_set(
429                     "wasmtime_linkopt_padding_between_functions",
430                     &pad.to_string(),
431                 )
432                 .unwrap();
433             }
434         }
435 
436         match &self.wasmtime.memory_config {
437             MemoryConfig::Normal(memory_config) => {
438                 cfg.static_memory_maximum_size(
439                     memory_config.static_memory_maximum_size.unwrap_or(0),
440                 )
441                 .static_memory_guard_size(memory_config.static_memory_guard_size.unwrap_or(0))
442                 .dynamic_memory_guard_size(memory_config.dynamic_memory_guard_size.unwrap_or(0))
443                 .guard_before_linear_memory(memory_config.guard_before_linear_memory);
444             }
445             MemoryConfig::CustomUnaligned => {
446                 cfg.with_host_memory(Arc::new(UnalignedMemoryCreator))
447                     .static_memory_maximum_size(0)
448                     .dynamic_memory_guard_size(0)
449                     .static_memory_guard_size(0)
450                     .guard_before_linear_memory(false);
451             }
452         }
453 
454         return cfg;
455     }
456 
457     /// Convenience function for generating a `Store<T>` using this
458     /// configuration.
459     pub fn to_store(&self) -> Store<StoreLimits> {
460         let engine = Engine::new(&self.to_wasmtime()).unwrap();
461         let mut store = Store::new(&engine, StoreLimits::new());
462         self.configure_store(&mut store);
463         store
464     }
465 
466     /// Configures a store based on this configuration.
467     pub fn configure_store(&self, store: &mut Store<StoreLimits>) {
468         store.limiter(|s| s as &mut dyn wasmtime::ResourceLimiter);
469         if self.wasmtime.consume_fuel {
470             store.add_fuel(u64::max_value()).unwrap();
471         }
472         if self.wasmtime.epoch_interruption {
473             // Without fuzzing of async execution, we can't test the
474             // "update deadline and continue" behavior, but we can at
475             // least test the codegen paths and checks with the
476             // trapping behavior, which works synchronously too. We'll
477             // set the deadline one epoch tick in the future; then
478             // this works exactly like an interrupt flag. We expect no
479             // traps/interrupts unless we bump the epoch, which we do
480             // as one particular Timeout mode (`Timeout::Epoch`).
481             store.epoch_deadline_trap();
482             store.set_epoch_deadline(1);
483         }
484     }
485 
486     /// Generates an arbitrary method of timing out an instance, ensuring that
487     /// this configuration supports the returned timeout.
488     pub fn generate_timeout(&mut self, u: &mut Unstructured<'_>) -> arbitrary::Result<Timeout> {
489         let time_duration = Duration::from_secs(20);
490         let timeout = u
491             .choose(&[Timeout::Fuel(100_000), Timeout::Epoch(time_duration)])?
492             .clone();
493         match &timeout {
494             Timeout::Fuel(..) => {
495                 self.wasmtime.consume_fuel = true;
496             }
497             Timeout::Epoch(..) => {
498                 self.wasmtime.epoch_interruption = true;
499             }
500             Timeout::None => unreachable!("Not an option given to choose()"),
501         }
502         Ok(timeout)
503     }
504 
505     /// Compiles the `wasm` within the `engine` provided.
506     ///
507     /// This notably will use `Module::{serialize,deserialize_file}` to
508     /// round-trip if configured in the fuzzer.
509     pub fn compile(&self, engine: &Engine, wasm: &[u8]) -> Result<Module> {
510         // Propagate this error in case the caller wants to handle
511         // valid-vs-invalid wasm.
512         let module = Module::new(engine, wasm)?;
513         if !self.wasmtime.use_precompiled_cwasm {
514             return Ok(module);
515         }
516 
517         // Don't propagate these errors to prevent them from accidentally being
518         // interpreted as invalid wasm, these should never fail on a
519         // well-behaved host system.
520         let file = tempfile::NamedTempFile::new().unwrap();
521         std::fs::write(file.path(), module.serialize().unwrap()).unwrap();
522         unsafe { Ok(Module::deserialize_file(engine, file.path()).unwrap()) }
523     }
524 }
525 
526 struct UnalignedMemoryCreator;
527 
528 unsafe impl MemoryCreator for UnalignedMemoryCreator {
529     fn new_memory(
530         &self,
531         _ty: MemoryType,
532         minimum: usize,
533         maximum: Option<usize>,
534         reserved_size_in_bytes: Option<usize>,
535         guard_size_in_bytes: usize,
536     ) -> Result<Box<dyn LinearMemory>, String> {
537         assert_eq!(guard_size_in_bytes, 0);
538         assert!(reserved_size_in_bytes.is_none() || reserved_size_in_bytes == Some(0));
539         Ok(Box::new(UnalignedMemory {
540             src: vec![0; minimum + 1],
541             maximum,
542         }))
543     }
544 }
545 
546 /// A custom "linear memory allocator" for wasm which only works with the
547 /// "dynamic" mode of configuration where wasm always does explicit bounds
548 /// checks.
549 ///
550 /// This memory attempts to always use unaligned host addresses for the base
551 /// address of linear memory with wasm. This means that all jit loads/stores
552 /// should be unaligned, which is a "big hammer way" of testing that all our JIT
553 /// code works with unaligned addresses since alignment is not required for
554 /// correctness in wasm itself.
555 struct UnalignedMemory {
556     /// This memory is always one byte larger than the actual size of linear
557     /// memory.
558     src: Vec<u8>,
559     maximum: Option<usize>,
560 }
561 
562 unsafe impl LinearMemory for UnalignedMemory {
563     fn byte_size(&self) -> usize {
564         // Chop off the extra byte reserved for the true byte size of this
565         // linear memory.
566         self.src.len() - 1
567     }
568 
569     fn maximum_byte_size(&self) -> Option<usize> {
570         self.maximum
571     }
572 
573     fn grow_to(&mut self, new_size: usize) -> Result<()> {
574         // Make sure to allocate an extra byte for our "unalignment"
575         self.src.resize(new_size + 1, 0);
576         Ok(())
577     }
578 
579     fn as_ptr(&self) -> *mut u8 {
580         // Return our allocated memory, offset by one, so that the base address
581         // of memory is always unaligned.
582         self.src[1..].as_ptr() as *mut _
583     }
584 }
585 
586 include!(concat!(env!("OUT_DIR"), "/spectests.rs"));
587 
588 /// A spec test from the upstream wast testsuite, arbitrarily chosen from the
589 /// list of known spec tests.
590 #[derive(Debug)]
591 pub struct SpecTest {
592     /// The filename of the spec test
593     pub file: &'static str,
594     /// The `*.wast` contents of the spec test
595     pub contents: &'static str,
596 }
597 
598 impl<'a> Arbitrary<'a> for SpecTest {
599     fn arbitrary(u: &mut Unstructured<'a>) -> arbitrary::Result<Self> {
600         // NB: this does get a uniform value in the provided range.
601         let i = u.int_in_range(0..=FILES.len() - 1)?;
602         let (file, contents) = FILES[i];
603         Ok(SpecTest { file, contents })
604     }
605 
606     fn size_hint(_depth: usize) -> (usize, Option<usize>) {
607         (1, Some(std::mem::size_of::<usize>()))
608     }
609 }
610 
611 /// Default module-level configuration for fuzzing Wasmtime.
612 ///
613 /// Internally this uses `wasm-smith`'s own `SwarmConfig` but we further refine
614 /// the defaults here as well.
615 #[derive(Debug, Clone)]
616 pub struct ModuleConfig {
617     #[allow(missing_docs)]
618     pub config: SwarmConfig,
619 }
620 
621 impl<'a> Arbitrary<'a> for ModuleConfig {
622     fn arbitrary(u: &mut Unstructured<'a>) -> arbitrary::Result<ModuleConfig> {
623         let mut config = SwarmConfig::arbitrary(u)?;
624 
625         // Allow multi-memory by default.
626         config.max_memories = config.max_memories.max(2);
627 
628         // Allow multi-table by default.
629         config.max_tables = config.max_tables.max(4);
630 
631         // Allow enabling some various wasm proposals by default. Note that
632         // these are all unconditionally turned off even with
633         // `SwarmConfig::arbitrary`.
634         config.memory64_enabled = u.arbitrary()?;
635 
636         Ok(ModuleConfig { config })
637     }
638 }
639 
640 #[derive(Clone, Debug, Eq, Hash, PartialEq)]
641 enum CodegenSettings {
642     Native,
643     #[allow(dead_code)]
644     Target {
645         target: String,
646         flags: Vec<(String, String)>,
647     },
648 }
649 
650 impl CodegenSettings {
651     fn configure(&self, config: &mut wasmtime::Config) {
652         match self {
653             CodegenSettings::Native => {}
654             CodegenSettings::Target { target, flags } => {
655                 config.target(target).unwrap();
656                 for (key, value) in flags {
657                     unsafe {
658                         config.cranelift_flag_set(key, value).unwrap();
659                     }
660                 }
661             }
662         }
663     }
664 }
665 
666 impl<'a> Arbitrary<'a> for CodegenSettings {
667     #[allow(unused_macros, unused_variables)]
668     fn arbitrary(u: &mut Unstructured<'a>) -> arbitrary::Result<Self> {
669         // Helper macro to enable clif features based on what the native host
670         // supports. If the input says to enable a feature and the host doesn't
671         // support it then that test case is rejected with a warning.
672         //
673         // Note that this specifically consumes bytes from the fuzz input for
674         // features for all targets, discarding anything which isn't applicable
675         // to the current target. The theory behind this is that most fuzz bugs
676         // won't be related to this feature selection so by consistently
677         // consuming input irrespective of the current platform reproducing fuzz
678         // bugs should be easier between different architectures.
679         macro_rules! target_features {
680             (
681                 $(
682                     $arch:tt => {
683                         test:$test:ident,
684                         $(std: $std:tt => clif: $clif:tt $(ratio: $a:tt in $b:tt)?,)*
685                     },
686                 )*
687             ) => ({
688                 let mut flags = Vec::new();
689                 $( // for each `$arch`
690                     $( // for each `$std`/`$clif` pair
691                         // Use the input to generate whether `$clif` will be
692                         // enabled. By default this is a 1 in 2 chance but each
693                         // feature supports a custom ratio as well which shadows
694                         // the (low, hi)
695                         let (low, hi) = (1, 2);
696                         $(let (low, hi) = ($a, $b);)?
697                         let enable = u.ratio(low, hi)?;
698 
699                         // If we're actually on the relevant platform and the
700                         // feature is enabled be sure to check that this host
701                         // supports it. If the host doesn't support it then
702                         // print a warning and return an error because this fuzz
703                         // input must be discarded.
704                         #[cfg(target_arch = $arch)]
705                         if enable && !std::$test!($std) {
706                             log::warn!("want to enable clif `{}` but host doesn't support it",
707                                 $clif);
708                             return Err(arbitrary::Error::EmptyChoose)
709                         }
710 
711                         // And finally actually push the feature into the set of
712                         // flags to enable, but only if we're on the right
713                         // architecture.
714                         if cfg!(target_arch = $arch) {
715                             flags.push((
716                                 $clif.to_string(),
717                                 enable.to_string(),
718                             ));
719                         }
720                     )*
721                 )*
722                 flags
723             })
724         }
725         if u.ratio(1, 10)? {
726             let flags = target_features! {
727                 "x86_64" => {
728                     test: is_x86_feature_detected,
729 
730                     // These features are considered to be baseline required by
731                     // Wasmtime. Currently some SIMD code generation will
732                     // fail if these features are disabled, so unconditionally
733                     // enable them as we're not interested in fuzzing without
734                     // them.
735                     std:"sse3" => clif:"has_sse3" ratio: 1 in 1,
736                     std:"ssse3" => clif:"has_ssse3" ratio: 1 in 1,
737                     std:"sse4.1" => clif:"has_sse41" ratio: 1 in 1,
738                     std:"sse4.2" => clif:"has_sse42" ratio: 1 in 1,
739 
740                     std:"popcnt" => clif:"has_popcnt",
741                     std:"avx" => clif:"has_avx",
742                     std:"avx2" => clif:"has_avx2",
743                     std:"bmi1" => clif:"has_bmi1",
744                     std:"bmi2" => clif:"has_bmi2",
745                     std:"lzcnt" => clif:"has_lzcnt",
746 
747                     // not a lot of of cpus support avx512 so these are weighted
748                     // to get enabled much less frequently.
749                     std:"avx512bitalg" => clif:"has_avx512bitalg" ratio:1 in 1000,
750                     std:"avx512dq" => clif:"has_avx512dq" ratio: 1 in 1000,
751                     std:"avx512f" => clif:"has_avx512f" ratio: 1 in 1000,
752                     std:"avx512vl" => clif:"has_avx512vl" ratio: 1 in 1000,
753                     std:"avx512vbmi" => clif:"has_avx512vbmi" ratio: 1 in 1000,
754                 },
755             };
756             return Ok(CodegenSettings::Target {
757                 target: target_lexicon::Triple::host().to_string(),
758                 flags,
759             });
760         }
761         Ok(CodegenSettings::Native)
762     }
763 }
764