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 }
215 
216 /// Configuration for linear memories in Wasmtime.
217 #[derive(Arbitrary, Clone, Debug, Eq, Hash, PartialEq)]
218 pub enum MemoryConfig {
219     /// Configuration for linear memories which correspond to normal
220     /// configuration settings in `wasmtime` itself. This will tweak various
221     /// parameters about static/dynamic memories.
222     Normal(NormalMemoryConfig),
223 
224     /// Configuration to force use of a linear memory that's unaligned at its
225     /// base address to force all wasm addresses to be unaligned at the hardware
226     /// level, even if the wasm itself correctly aligns everything internally.
227     CustomUnaligned,
228 }
229 
230 /// Represents a normal memory configuration for Wasmtime with the given
231 /// static and dynamic memory sizes.
232 #[derive(Clone, Debug, Eq, Hash, PartialEq)]
233 pub struct NormalMemoryConfig {
234     static_memory_maximum_size: Option<u64>,
235     static_memory_guard_size: Option<u64>,
236     dynamic_memory_guard_size: Option<u64>,
237     guard_before_linear_memory: bool,
238 }
239 
240 impl<'a> Arbitrary<'a> for NormalMemoryConfig {
241     fn arbitrary(u: &mut Unstructured<'a>) -> arbitrary::Result<Self> {
242         // This attempts to limit memory and guard sizes to 32-bit ranges so
243         // we don't exhaust a 64-bit address space easily.
244         Ok(Self {
245             static_memory_maximum_size: <Option<u32> as Arbitrary>::arbitrary(u)?.map(Into::into),
246             static_memory_guard_size: <Option<u32> as Arbitrary>::arbitrary(u)?.map(Into::into),
247             dynamic_memory_guard_size: <Option<u32> as Arbitrary>::arbitrary(u)?.map(Into::into),
248             guard_before_linear_memory: u.arbitrary()?,
249         })
250     }
251 }
252 
253 impl Config {
254     /// Indicates that this configuration is being used for differential
255     /// execution so only a single function should be generated since that's all
256     /// that's going to be exercised.
257     pub fn set_differential_config(&mut self) {
258         let config = &mut self.module_config.config;
259 
260         config.allow_start_export = false;
261         // Make sure there's a type available for the function.
262         config.min_types = 1;
263         config.max_types = 1;
264 
265         // Generate one and only one function
266         config.min_funcs = 1;
267         config.max_funcs = 1;
268 
269         // Give the function a memory, but keep it small
270         config.min_memories = 1;
271         config.max_memories = 1;
272         config.max_memory_pages = 1;
273         config.memory_max_size_required = true;
274 
275         // While reference types are disabled below, only allow one table
276         config.max_tables = 1;
277 
278         // Don't allow any imports
279         config.max_imports = 0;
280 
281         // Try to get the function and the memory exported
282         config.min_exports = 2;
283         config.max_exports = 4;
284 
285         // NaN is canonicalized at the wasm level for differential fuzzing so we
286         // can paper over NaN differences between engines.
287         config.canonicalize_nans = true;
288 
289         // When diffing against a non-wasmtime engine then disable wasm
290         // features to get selectively re-enabled against each differential
291         // engine.
292         config.bulk_memory_enabled = false;
293         config.reference_types_enabled = false;
294         config.simd_enabled = false;
295         config.memory64_enabled = false;
296 
297         // If using the pooling allocator, update the instance limits too
298         if let InstanceAllocationStrategy::Pooling {
299             instance_limits: limits,
300             ..
301         } = &mut self.wasmtime.strategy
302         {
303             // One single-page memory
304             limits.memories = 1;
305             limits.memory_pages = 1;
306 
307             match &mut self.wasmtime.memory_config {
308                 MemoryConfig::Normal(config) => {
309                     config.static_memory_maximum_size = Some(limits.memory_pages * 0x10000);
310                 }
311                 MemoryConfig::CustomUnaligned => unreachable!(), // Arbitrary impl for `Config` should have prevented this
312             }
313         }
314     }
315 
316     /// Uses this configuration and the supplied source of data to generate
317     /// a wasm module.
318     ///
319     /// If a `default_fuel` is provided, the resulting module will be configured
320     /// to ensure termination; as doing so will add an additional global to the module,
321     /// the pooling allocator, if configured, will also have its globals limit updated.
322     pub fn generate(
323         &mut self,
324         input: &mut Unstructured<'_>,
325         default_fuel: Option<u32>,
326     ) -> arbitrary::Result<wasm_smith::Module> {
327         let mut module = wasm_smith::Module::new(self.module_config.config.clone(), input)?;
328 
329         if let Some(default_fuel) = default_fuel {
330             module.ensure_termination(default_fuel);
331         }
332 
333         Ok(module)
334     }
335 
336     /// Indicates that this configuration should be spec-test-compliant,
337     /// disabling various features the spec tests assert are disabled.
338     pub fn set_spectest_compliant(&mut self) {
339         let config = &mut self.module_config.config;
340         config.memory64_enabled = false;
341         config.simd_enabled = false;
342         config.bulk_memory_enabled = true;
343         config.reference_types_enabled = true;
344         config.multi_value_enabled = true;
345         config.max_memories = 1;
346 
347         if let InstanceAllocationStrategy::Pooling {
348             instance_limits: limits,
349             ..
350         } = &mut self.wasmtime.strategy
351         {
352             limits.memories = 1;
353             // Set a lower bound of 10 pages as the spec tests define memories with at
354             // least a few pages and some tests do memory grow operations.
355             limits.memory_pages = std::cmp::max(limits.memory_pages, 10);
356 
357             match &mut self.wasmtime.memory_config {
358                 MemoryConfig::Normal(config) => {
359                     config.static_memory_maximum_size = Some(limits.memory_pages * 0x10000);
360                 }
361                 MemoryConfig::CustomUnaligned => unreachable!(), // Arbitrary impl for `Config` should have prevented this
362             }
363         }
364     }
365 
366     /// Converts this to a `wasmtime::Config` object
367     pub fn to_wasmtime(&self) -> wasmtime::Config {
368         crate::init_fuzzing();
369 
370         let mut cfg = wasmtime::Config::new();
371         cfg.wasm_bulk_memory(true)
372             .wasm_reference_types(true)
373             .wasm_module_linking(self.module_config.config.module_linking_enabled)
374             .wasm_multi_value(self.module_config.config.multi_value_enabled)
375             .wasm_multi_memory(self.module_config.config.max_memories > 1)
376             .wasm_simd(self.module_config.config.simd_enabled)
377             .wasm_memory64(self.module_config.config.memory64_enabled)
378             .cranelift_nan_canonicalization(self.wasmtime.canonicalize_nans)
379             .cranelift_opt_level(self.wasmtime.opt_level.to_wasmtime())
380             .interruptable(self.wasmtime.interruptable)
381             .consume_fuel(self.wasmtime.consume_fuel)
382             .epoch_interruption(self.wasmtime.epoch_interruption)
383             .memory_init_cow(self.wasmtime.memory_init_cow)
384             .memory_guaranteed_dense_image_size(std::cmp::min(
385                 // Clamp this at 16MiB so we don't get huge in-memory
386                 // images during fuzzing.
387                 16 << 20,
388                 self.wasmtime.memory_guaranteed_dense_image_size,
389             ))
390             .allocation_strategy(self.wasmtime.strategy.to_wasmtime());
391 
392         self.wasmtime.codegen.configure(&mut cfg);
393 
394         // If the wasm-smith-generated module use nan canonicalization then we
395         // don't need to enable it, but if it doesn't enable it already then we
396         // enable this codegen option.
397         cfg.cranelift_nan_canonicalization(!self.module_config.config.canonicalize_nans);
398 
399         // Enabling the verifier will at-least-double compilation time, which
400         // with a 20-30x slowdown in fuzzing can cause issues related to
401         // timeouts. If generated modules can have more than a small handful of
402         // functions then disable the verifier when fuzzing to try to lessen the
403         // impact of timeouts.
404         if self.module_config.config.max_funcs > 10 {
405             cfg.cranelift_debug_verifier(false);
406         }
407 
408         if self.wasmtime.force_jump_veneers {
409             unsafe {
410                 cfg.cranelift_flag_set("wasmtime_linkopt_force_jump_veneer", "true")
411                     .unwrap();
412             }
413         }
414 
415         match &self.wasmtime.memory_config {
416             MemoryConfig::Normal(memory_config) => {
417                 cfg.static_memory_maximum_size(
418                     memory_config.static_memory_maximum_size.unwrap_or(0),
419                 )
420                 .static_memory_guard_size(memory_config.static_memory_guard_size.unwrap_or(0))
421                 .dynamic_memory_guard_size(memory_config.dynamic_memory_guard_size.unwrap_or(0))
422                 .guard_before_linear_memory(memory_config.guard_before_linear_memory);
423             }
424             MemoryConfig::CustomUnaligned => {
425                 cfg.with_host_memory(Arc::new(UnalignedMemoryCreator))
426                     .static_memory_maximum_size(0)
427                     .dynamic_memory_guard_size(0)
428                     .static_memory_guard_size(0)
429                     .guard_before_linear_memory(false);
430             }
431         }
432 
433         return cfg;
434     }
435 
436     /// Convenience function for generating a `Store<T>` using this
437     /// configuration.
438     pub fn to_store(&self) -> Store<StoreLimits> {
439         let engine = Engine::new(&self.to_wasmtime()).unwrap();
440         let mut store = Store::new(&engine, StoreLimits::new());
441         self.configure_store(&mut store);
442         store
443     }
444 
445     /// Configures a store based on this configuration.
446     pub fn configure_store(&self, store: &mut Store<StoreLimits>) {
447         store.limiter(|s| s as &mut dyn wasmtime::ResourceLimiter);
448         if self.wasmtime.consume_fuel {
449             store.add_fuel(u64::max_value()).unwrap();
450         }
451         if self.wasmtime.epoch_interruption {
452             // Without fuzzing of async execution, we can't test the
453             // "update deadline and continue" behavior, but we can at
454             // least test the codegen paths and checks with the
455             // trapping behavior, which works synchronously too. We'll
456             // set the deadline one epoch tick in the future; then
457             // this works exactly like an interrupt flag. We expect no
458             // traps/interrupts unless we bump the epoch, which we do
459             // as one particular Timeout mode (`Timeout::Epoch`).
460             store.epoch_deadline_trap();
461             store.set_epoch_deadline(1);
462         }
463     }
464 
465     /// Generates an arbitrary method of timing out an instance, ensuring that
466     /// this configuration supports the returned timeout.
467     pub fn generate_timeout(&mut self, u: &mut Unstructured<'_>) -> arbitrary::Result<Timeout> {
468         let time_duration = Duration::from_secs(20);
469         let timeout = u
470             .choose(&[
471                 Timeout::Time(time_duration),
472                 Timeout::Fuel(100_000),
473                 Timeout::Epoch(time_duration),
474             ])?
475             .clone();
476         match &timeout {
477             &Timeout::Time(..) => {
478                 self.wasmtime.interruptable = true;
479             }
480             &Timeout::Fuel(..) => {
481                 self.wasmtime.consume_fuel = true;
482             }
483             &Timeout::Epoch(..) => {
484                 self.wasmtime.epoch_interruption = true;
485             }
486             &Timeout::None => unreachable!("Not an option given to choose()"),
487         }
488         Ok(timeout)
489     }
490 
491     /// Compiles the `wasm` within the `engine` provided.
492     ///
493     /// This notably will use `Module::{serialize,deserialize_file}` to
494     /// round-trip if configured in the fuzzer.
495     pub fn compile(&self, engine: &Engine, wasm: &[u8]) -> Result<Module> {
496         // Propagate this error in case the caller wants to handle
497         // valid-vs-invalid wasm.
498         let module = Module::new(engine, wasm)?;
499         if !self.wasmtime.use_precompiled_cwasm {
500             return Ok(module);
501         }
502 
503         // Don't propagate these errors to prevent them from accidentally being
504         // interpreted as invalid wasm, these should never fail on a
505         // well-behaved host system.
506         let file = tempfile::NamedTempFile::new().unwrap();
507         std::fs::write(file.path(), module.serialize().unwrap()).unwrap();
508         unsafe { Ok(Module::deserialize_file(engine, file.path()).unwrap()) }
509     }
510 }
511 
512 struct UnalignedMemoryCreator;
513 
514 unsafe impl MemoryCreator for UnalignedMemoryCreator {
515     fn new_memory(
516         &self,
517         _ty: MemoryType,
518         minimum: usize,
519         maximum: Option<usize>,
520         reserved_size_in_bytes: Option<usize>,
521         guard_size_in_bytes: usize,
522     ) -> Result<Box<dyn LinearMemory>, String> {
523         assert_eq!(guard_size_in_bytes, 0);
524         assert!(reserved_size_in_bytes.is_none() || reserved_size_in_bytes == Some(0));
525         Ok(Box::new(UnalignedMemory {
526             src: vec![0; minimum + 1],
527             maximum,
528         }))
529     }
530 }
531 
532 /// A custom "linear memory allocator" for wasm which only works with the
533 /// "dynamic" mode of configuration where wasm always does explicit bounds
534 /// checks.
535 ///
536 /// This memory attempts to always use unaligned host addresses for the base
537 /// address of linear memory with wasm. This means that all jit loads/stores
538 /// should be unaligned, which is a "big hammer way" of testing that all our JIT
539 /// code works with unaligned addresses since alignment is not required for
540 /// correctness in wasm itself.
541 struct UnalignedMemory {
542     /// This memory is always one byte larger than the actual size of linear
543     /// memory.
544     src: Vec<u8>,
545     maximum: Option<usize>,
546 }
547 
548 unsafe impl LinearMemory for UnalignedMemory {
549     fn byte_size(&self) -> usize {
550         // Chop off the extra byte reserved for the true byte size of this
551         // linear memory.
552         self.src.len() - 1
553     }
554 
555     fn maximum_byte_size(&self) -> Option<usize> {
556         self.maximum
557     }
558 
559     fn grow_to(&mut self, new_size: usize) -> Result<()> {
560         // Make sure to allocate an extra byte for our "unalignment"
561         self.src.resize(new_size + 1, 0);
562         Ok(())
563     }
564 
565     fn as_ptr(&self) -> *mut u8 {
566         // Return our allocated memory, offset by one, so that the base address
567         // of memory is always unaligned.
568         self.src[1..].as_ptr() as *mut _
569     }
570 }
571 
572 include!(concat!(env!("OUT_DIR"), "/spectests.rs"));
573 
574 /// A spec test from the upstream wast testsuite, arbitrarily chosen from the
575 /// list of known spec tests.
576 #[derive(Debug)]
577 pub struct SpecTest {
578     /// The filename of the spec test
579     pub file: &'static str,
580     /// The `*.wast` contents of the spec test
581     pub contents: &'static str,
582 }
583 
584 impl<'a> Arbitrary<'a> for SpecTest {
585     fn arbitrary(u: &mut Unstructured<'a>) -> arbitrary::Result<Self> {
586         // NB: this does get a uniform value in the provided range.
587         let i = u.int_in_range(0..=FILES.len() - 1)?;
588         let (file, contents) = FILES[i];
589         Ok(SpecTest { file, contents })
590     }
591 
592     fn size_hint(_depth: usize) -> (usize, Option<usize>) {
593         (1, Some(std::mem::size_of::<usize>()))
594     }
595 }
596 
597 /// Default module-level configuration for fuzzing Wasmtime.
598 ///
599 /// Internally this uses `wasm-smith`'s own `SwarmConfig` but we further refine
600 /// the defaults here as well.
601 #[derive(Debug, Clone)]
602 pub struct ModuleConfig {
603     #[allow(missing_docs)]
604     pub config: SwarmConfig,
605 }
606 
607 impl<'a> Arbitrary<'a> for ModuleConfig {
608     fn arbitrary(u: &mut Unstructured<'a>) -> arbitrary::Result<ModuleConfig> {
609         let mut config = SwarmConfig::arbitrary(u)?;
610 
611         // Allow multi-memory by default.
612         config.max_memories = config.max_memories.max(2);
613 
614         // Allow multi-table by default.
615         config.max_tables = config.max_tables.max(4);
616 
617         // Allow enabling some various wasm proposals by default. Note that
618         // these are all unconditionally turned off even with
619         // `SwarmConfig::arbitrary`.
620         config.memory64_enabled = u.arbitrary()?;
621 
622         Ok(ModuleConfig { config })
623     }
624 }
625 
626 #[derive(Clone, Debug, Eq, Hash, PartialEq)]
627 enum CodegenSettings {
628     Native,
629     #[allow(dead_code)]
630     Target {
631         target: String,
632         flags: Vec<(String, String)>,
633     },
634 }
635 
636 impl CodegenSettings {
637     fn configure(&self, config: &mut wasmtime::Config) {
638         match self {
639             CodegenSettings::Native => {}
640             CodegenSettings::Target { target, flags } => {
641                 config.target(target).unwrap();
642                 for (key, value) in flags {
643                     unsafe {
644                         config.cranelift_flag_set(key, value).unwrap();
645                     }
646                 }
647             }
648         }
649     }
650 }
651 
652 impl<'a> Arbitrary<'a> for CodegenSettings {
653     #[allow(unused_macros, unused_variables)]
654     fn arbitrary(u: &mut Unstructured<'a>) -> arbitrary::Result<Self> {
655         // Helper macro to enable clif features based on what the native host
656         // supports. If the input says to enable a feature and the host doesn't
657         // support it then that test case is rejected with a warning.
658         //
659         // Note that this specifically consumes bytes from the fuzz input for
660         // features for all targets, discarding anything which isn't applicable
661         // to the current target. The theory behind this is that most fuzz bugs
662         // won't be related to this feature selection so by consistently
663         // consuming input irrespective of the current platform reproducing fuzz
664         // bugs should be easier between different architectures.
665         macro_rules! target_features {
666             (
667                 $(
668                     $arch:tt => {
669                         test:$test:ident,
670                         $(std: $std:tt => clif: $clif:tt $(ratio: $a:tt in $b:tt)?,)*
671                     },
672                 )*
673             ) => ({
674                 let mut flags = Vec::new();
675                 $( // for each `$arch`
676                     $( // for each `$std`/`$clif` pair
677                         // Use the input to generate whether `$clif` will be
678                         // enabled. By default this is a 1 in 2 chance but each
679                         // feature supports a custom ratio as well which shadows
680                         // the (low, hi)
681                         let (low, hi) = (1, 2);
682                         $(let (low, hi) = ($a, $b);)?
683                         let enable = u.ratio(low, hi)?;
684 
685                         // If we're actually on the relevant platform and the
686                         // feature is enabled be sure to check that this host
687                         // supports it. If the host doesn't support it then
688                         // print a warning and return an error because this fuzz
689                         // input must be discarded.
690                         #[cfg(target_arch = $arch)]
691                         if enable && !std::$test!($std) {
692                             log::warn!("want to enable clif `{}` but host doesn't support it",
693                                 $clif);
694                             return Err(arbitrary::Error::EmptyChoose)
695                         }
696 
697                         // And finally actually push the feature into the set of
698                         // flags to enable, but only if we're on the right
699                         // architecture.
700                         if cfg!(target_arch = $arch) {
701                             flags.push((
702                                 $clif.to_string(),
703                                 enable.to_string(),
704                             ));
705                         }
706                     )*
707                 )*
708                 flags
709             })
710         }
711         if u.ratio(1, 10)? {
712             let flags = target_features! {
713                 "x86_64" => {
714                     test: is_x86_feature_detected,
715 
716                     // These features are considered to be baseline required by
717                     // Wasmtime. Currently some SIMD code generation will
718                     // fail if these features are disabled, so unconditionally
719                     // enable them as we're not interested in fuzzing without
720                     // them.
721                     std:"sse3" => clif:"has_sse3" ratio: 1 in 1,
722                     std:"ssse3" => clif:"has_ssse3" ratio: 1 in 1,
723                     std:"sse4.1" => clif:"has_sse41" ratio: 1 in 1,
724                     std:"sse4.2" => clif:"has_sse42" ratio: 1 in 1,
725 
726                     std:"popcnt" => clif:"has_popcnt",
727                     std:"avx" => clif:"has_avx",
728                     std:"avx2" => clif:"has_avx2",
729                     std:"bmi1" => clif:"has_bmi1",
730                     std:"bmi2" => clif:"has_bmi2",
731                     std:"lzcnt" => clif:"has_lzcnt",
732 
733                     // not a lot of of cpus support avx512 so these are weighted
734                     // to get enabled much less frequently.
735                     std:"avx512bitalg" => clif:"has_avx512bitalg" ratio:1 in 1000,
736                     std:"avx512dq" => clif:"has_avx512dq" ratio: 1 in 1000,
737                     std:"avx512f" => clif:"has_avx512f" ratio: 1 in 1000,
738                     std:"avx512vl" => clif:"has_avx512vl" ratio: 1 in 1000,
739                     std:"avx512vbmi" => clif:"has_avx512vbmi" ratio: 1 in 1000,
740                 },
741             };
742             return Ok(CodegenSettings::Target {
743                 target: target_lexicon::Triple::host().to_string(),
744                 flags,
745             });
746         }
747         Ok(CodegenSettings::Native)
748     }
749 }
750