1 //! Oracles.
2 //!
3 //! Oracles take a test case and determine whether we have a bug. For example,
4 //! one of the simplest oracles is to take a Wasm binary as our input test case,
5 //! validate and instantiate it, and (implicitly) check that no assertions
6 //! failed or segfaults happened. A more complicated oracle might compare the
7 //! result of executing a Wasm file with and without optimizations enabled, and
8 //! make sure that the two executions are observably identical.
9 //!
10 //! When an oracle finds a bug, it should report it to the fuzzing engine by
11 //! panicking.
12 
13 #[cfg(feature = "fuzz-spec-interpreter")]
14 pub mod diff_spec;
15 pub mod diff_wasmi;
16 pub mod diff_wasmtime;
17 pub mod dummy;
18 pub mod engine;
19 pub mod memory;
20 mod stacks;
21 
22 use self::diff_wasmtime::WasmtimeInstance;
23 use self::engine::{DiffEngine, DiffInstance};
24 use crate::generators::GcOps;
25 use crate::generators::{self, CompilerStrategy, DiffValue, DiffValueType};
26 use crate::single_module_fuzzer::KnownValid;
27 use arbitrary::Arbitrary;
28 pub use stacks::check_stacks;
29 use std::future::Future;
30 use std::pin::Pin;
31 use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering::SeqCst};
32 use std::sync::{Arc, Condvar, Mutex};
33 use std::task::{Context, Poll, Waker};
34 use std::time::{Duration, Instant};
35 use wasmtime::*;
36 use wasmtime_wast::WastContext;
37 
38 #[cfg(not(any(windows, target_arch = "s390x", target_arch = "riscv64")))]
39 mod diff_v8;
40 
41 static CNT: AtomicUsize = AtomicUsize::new(0);
42 
43 /// Logs a wasm file to the filesystem to make it easy to figure out what wasm
44 /// was used when debugging.
45 pub fn log_wasm(wasm: &[u8]) {
46     super::init_fuzzing();
47 
48     if !log::log_enabled!(log::Level::Debug) {
49         return;
50     }
51 
52     let i = CNT.fetch_add(1, SeqCst);
53     let name = format!("testcase{i}.wasm");
54     std::fs::write(&name, wasm).expect("failed to write wasm file");
55     log::debug!("wrote wasm file to `{name}`");
56     let wat = format!("testcase{i}.wat");
57     match wasmprinter::print_bytes(wasm) {
58         Ok(s) => std::fs::write(&wat, s).expect("failed to write wat file"),
59         // If wasmprinter failed remove a `*.wat` file, if any, to avoid
60         // confusing a preexisting one with this wasm which failed to get
61         // printed.
62         Err(_) => drop(std::fs::remove_file(&wat)),
63     }
64 }
65 
66 /// The `T` in `Store<T>` for fuzzing stores, used to limit resource
67 /// consumption during fuzzing.
68 #[derive(Clone)]
69 pub struct StoreLimits(Arc<LimitsState>);
70 
71 struct LimitsState {
72     /// Remaining memory, in bytes, left to allocate
73     remaining_memory: AtomicUsize,
74     /// Remaining amount of memory that's allowed to be copied via a growth.
75     remaining_copy_allowance: AtomicUsize,
76     /// Whether or not an allocation request has been denied
77     oom: AtomicBool,
78 }
79 
80 /// Allow up to 1G which is well below the 2G limit on OSS-Fuzz and should allow
81 /// most interesting behavior.
82 const MAX_MEMORY: usize = 1 << 30;
83 
84 /// Allow up to 4G of bytes to be copied (conservatively) which should enable
85 /// growth up to `MAX_MEMORY` or at least up to a relatively large amount.
86 const MAX_MEMORY_MOVED: usize = 4 << 30;
87 
88 impl StoreLimits {
89     /// Creates the default set of limits for all fuzzing stores.
90     pub fn new() -> StoreLimits {
91         StoreLimits(Arc::new(LimitsState {
92             remaining_memory: AtomicUsize::new(MAX_MEMORY),
93             remaining_copy_allowance: AtomicUsize::new(MAX_MEMORY_MOVED),
94             oom: AtomicBool::new(false),
95         }))
96     }
97 
98     fn alloc(&mut self, amt: usize) -> bool {
99         log::trace!("alloc {amt:#x} bytes");
100 
101         // Assume that on each allocation of memory that all previous
102         // allocations of memory are moved. This is pretty coarse but is used to
103         // help prevent against fuzz test cases that just move tons of bytes
104         // around continuously. This assumes that all previous memory was
105         // allocated in a single linear memory and growing by `amt` will require
106         // moving all the bytes to a new location. This isn't actually required
107         // all the time nor does it accurately reflect what happens all the
108         // time, but it's a coarse approximation that should be "good enough"
109         // for allowing interesting fuzz behaviors to happen while not timing
110         // out just copying bytes around.
111         let prev_size = MAX_MEMORY - self.0.remaining_memory.load(SeqCst);
112         if self
113             .0
114             .remaining_copy_allowance
115             .fetch_update(SeqCst, SeqCst, |remaining| remaining.checked_sub(prev_size))
116             .is_err()
117         {
118             self.0.oom.store(true, SeqCst);
119             log::debug!("-> too many bytes moved, rejecting allocation");
120             return false;
121         }
122 
123         // If we're allowed to move the bytes, then also check if we're allowed
124         // to actually have this much residence at once.
125         match self
126             .0
127             .remaining_memory
128             .fetch_update(SeqCst, SeqCst, |remaining| remaining.checked_sub(amt))
129         {
130             Ok(_) => true,
131             Err(_) => {
132                 self.0.oom.store(true, SeqCst);
133                 log::debug!("-> OOM hit");
134                 false
135             }
136         }
137     }
138 
139     fn is_oom(&self) -> bool {
140         self.0.oom.load(SeqCst)
141     }
142 }
143 
144 impl ResourceLimiter for StoreLimits {
145     fn memory_growing(
146         &mut self,
147         current: usize,
148         desired: usize,
149         _maximum: Option<usize>,
150     ) -> Result<bool> {
151         Ok(self.alloc(desired - current))
152     }
153 
154     fn table_growing(
155         &mut self,
156         current: usize,
157         desired: usize,
158         _maximum: Option<usize>,
159     ) -> Result<bool> {
160         let delta = (desired - current).saturating_mul(std::mem::size_of::<usize>());
161         Ok(self.alloc(delta))
162     }
163 }
164 
165 /// Methods of timing out execution of a WebAssembly module
166 #[derive(Clone, Debug)]
167 pub enum Timeout {
168     /// No timeout is used, it should be guaranteed via some other means that
169     /// the input does not infinite loop.
170     None,
171     /// Fuel-based timeouts are used where the specified fuel is all that the
172     /// provided wasm module is allowed to consume.
173     Fuel(u64),
174     /// An epoch-interruption-based timeout is used with a sleeping
175     /// thread bumping the epoch counter after the specified duration.
176     Epoch(Duration),
177 }
178 
179 /// Instantiate the Wasm buffer, and implicitly fail if we have an unexpected
180 /// panic or segfault or anything else that can be detected "passively".
181 ///
182 /// The engine will be configured using provided config.
183 pub fn instantiate(
184     wasm: &[u8],
185     known_valid: KnownValid,
186     config: &generators::Config,
187     timeout: Timeout,
188 ) {
189     let mut store = config.to_store();
190 
191     let module = match compile_module(store.engine(), wasm, known_valid, config) {
192         Some(module) => module,
193         None => return,
194     };
195 
196     let mut timeout_state = HelperThread::default();
197     match timeout {
198         Timeout::Fuel(fuel) => store.set_fuel(fuel).unwrap(),
199 
200         // If a timeout is requested then we spawn a helper thread to wait for
201         // the requested time and then send us a signal to get interrupted. We
202         // also arrange for the thread's sleep to get interrupted if we return
203         // early (or the wasm returns within the time limit), which allows the
204         // thread to get torn down.
205         //
206         // This prevents us from creating a huge number of sleeping threads if
207         // this function is executed in a loop, like it does on nightly fuzzing
208         // infrastructure.
209         Timeout::Epoch(timeout) => {
210             let engine = store.engine().clone();
211             timeout_state.run_periodically(timeout, move || engine.increment_epoch());
212         }
213         Timeout::None => {}
214     }
215 
216     instantiate_with_dummy(&mut store, &module);
217 }
218 
219 /// Represents supported commands to the `instantiate_many` function.
220 #[derive(Arbitrary, Debug)]
221 pub enum Command {
222     /// Instantiates a module.
223     ///
224     /// The value is the index of the module to instantiate.
225     ///
226     /// The module instantiated will be this value modulo the number of modules provided to `instantiate_many`.
227     Instantiate(usize),
228     /// Terminates a "running" instance.
229     ///
230     /// The value is the index of the instance to terminate.
231     ///
232     /// The instance terminated will be this value modulo the number of currently running
233     /// instances.
234     ///
235     /// If no instances are running, the command will be ignored.
236     Terminate(usize),
237 }
238 
239 /// Instantiates many instances from the given modules.
240 ///
241 /// The engine will be configured using the provided config.
242 ///
243 /// The modules are expected to *not* have start functions as no timeouts are configured.
244 pub fn instantiate_many(
245     modules: &[Vec<u8>],
246     known_valid: KnownValid,
247     config: &generators::Config,
248     commands: &[Command],
249 ) {
250     log::debug!("instantiate_many: {commands:#?}");
251 
252     assert!(!config.module_config.config.allow_start_export);
253 
254     let engine = Engine::new(&config.to_wasmtime()).unwrap();
255 
256     let modules = modules
257         .iter()
258         .enumerate()
259         .filter_map(
260             |(i, bytes)| match compile_module(&engine, bytes, known_valid, config) {
261                 Some(m) => {
262                     log::debug!("successfully compiled module {i}");
263                     Some(m)
264                 }
265                 None => {
266                     log::debug!("failed to compile module {i}");
267                     None
268                 }
269             },
270         )
271         .collect::<Vec<_>>();
272 
273     // If no modules were valid, we're done
274     if modules.is_empty() {
275         return;
276     }
277 
278     // This stores every `Store` where a successful instantiation takes place
279     let mut stores = Vec::new();
280     let limits = StoreLimits::new();
281 
282     for command in commands {
283         match command {
284             Command::Instantiate(index) => {
285                 let index = *index % modules.len();
286                 log::info!("instantiating {index}");
287                 let module = &modules[index];
288                 let mut store = Store::new(&engine, limits.clone());
289                 config.configure_store(&mut store);
290 
291                 if instantiate_with_dummy(&mut store, module).is_some() {
292                     stores.push(Some(store));
293                 } else {
294                     log::warn!("instantiation failed");
295                 }
296             }
297             Command::Terminate(index) => {
298                 if stores.is_empty() {
299                     continue;
300                 }
301                 let index = *index % stores.len();
302 
303                 log::info!("dropping {index}");
304                 stores.swap_remove(index);
305             }
306         }
307     }
308 }
309 
310 fn compile_module(
311     engine: &Engine,
312     bytes: &[u8],
313     known_valid: KnownValid,
314     config: &generators::Config,
315 ) -> Option<Module> {
316     log_wasm(bytes);
317 
318     fn is_pcc_error(e: &anyhow::Error) -> bool {
319         // NOTE: please keep this predicate in sync with the display format of CodegenError,
320         // defined in `wasmtime/cranelift/codegen/src/result.rs`
321         e.to_string().to_lowercase().contains("proof-carrying-code")
322     }
323 
324     match config.compile(engine, bytes) {
325         Ok(module) => Some(module),
326         Err(e) if is_pcc_error(&e) => {
327             panic!("pcc error in input: {e:#?}");
328         }
329         Err(_) if known_valid == KnownValid::No => None,
330         Err(e) => {
331             if let generators::InstanceAllocationStrategy::Pooling(c) = &config.wasmtime.strategy {
332                 // When using the pooling allocator, accept failures to compile
333                 // when arbitrary table element limits have been exceeded as
334                 // there is currently no way to constrain the generated module
335                 // table types.
336                 let string = format!("{e:?}");
337                 if string.contains("minimum element size") {
338                     return None;
339                 }
340 
341                 // Allow modules-failing-to-compile which exceed the requested
342                 // size for each instance. This is something that is difficult
343                 // to control and ensure it always succeeds, so we simply have a
344                 // "random" instance size limit and if a module doesn't fit we
345                 // move on to the next fuzz input.
346                 if string.contains("instance allocation for this module requires") {
347                     return None;
348                 }
349 
350                 // If the pooling allocator is more restrictive on the number of
351                 // tables and memories than we allowed wasm-smith to generate
352                 // then allow compilation errors along those lines.
353                 if c.max_tables_per_module < (config.module_config.config.max_tables as u32)
354                     && string.contains("defined tables count")
355                     && string.contains("exceeds the per-instance limit")
356                 {
357                     return None;
358                 }
359 
360                 if c.max_memories_per_module < (config.module_config.config.max_memories as u32)
361                     && string.contains("defined memories count")
362                     && string.contains("exceeds the per-instance limit")
363                 {
364                     return None;
365                 }
366             }
367 
368             panic!("failed to compile module: {e:?}");
369         }
370     }
371 }
372 
373 /// Create a Wasmtime [`Instance`] from a [`Module`] and fill in all imports
374 /// with dummy values (e.g., zeroed values, immediately-trapping functions).
375 /// Also, this function catches certain fuzz-related instantiation failures and
376 /// returns `None` instead of panicking.
377 ///
378 /// TODO: we should implement tracing versions of these dummy imports that
379 /// record a trace of the order that imported functions were called in and with
380 /// what values. Like the results of exported functions, calls to imports should
381 /// also yield the same values for each configuration, and we should assert
382 /// that.
383 pub fn instantiate_with_dummy(store: &mut Store<StoreLimits>, module: &Module) -> Option<Instance> {
384     // Creation of imports can fail due to resource limit constraints, and then
385     // instantiation can naturally fail for a number of reasons as well. Bundle
386     // the two steps together to match on the error below.
387     let linker = dummy::dummy_linker(store, module);
388     if let Err(e) = &linker {
389         log::warn!("failed to create dummy linker: {e:?}");
390     }
391     let instance = linker.and_then(|l| l.instantiate(&mut *store, module));
392     unwrap_instance(store, instance)
393 }
394 
395 fn unwrap_instance(
396     store: &Store<StoreLimits>,
397     instance: anyhow::Result<Instance>,
398 ) -> Option<Instance> {
399     let e = match instance {
400         Ok(i) => return Some(i),
401         Err(e) => e,
402     };
403 
404     log::debug!("failed to instantiate: {e:?}");
405 
406     // If the instantiation hit OOM for some reason then that's ok, it's
407     // expected that fuzz-generated programs try to allocate lots of
408     // stuff.
409     if store.data().is_oom() {
410         return None;
411     }
412 
413     // Allow traps which can happen normally with `unreachable` or a timeout or
414     // such.
415     if e.is::<Trap>()
416         // Also allow failures to instantiate as a result of hitting pooling
417         // limits.
418         || e.is::<wasmtime::PoolConcurrencyLimitError>()
419         // And GC heap OOMs.
420         || e.is::<wasmtime::GcHeapOutOfMemory<()>>()
421         // And thrown exceptions.
422         || e.is::<wasmtime::ThrownException>()
423     {
424         return None;
425     }
426 
427     let string = e.to_string();
428 
429     // Currently we instantiate with a `Linker` which can't instantiate
430     // every single module under the sun due to using name-based resolution
431     // rather than positional-based resolution
432     if string.contains("incompatible import type") {
433         return None;
434     }
435 
436     // Everything else should be a bug in the fuzzer or a bug in wasmtime
437     panic!("failed to instantiate: {e:?}");
438 }
439 
440 /// Evaluate the function identified by `name` in two different engine
441 /// instances--`lhs` and `rhs`.
442 ///
443 /// Returns `Ok(true)` if more evaluations can happen or `Ok(false)` if the
444 /// instances may have drifted apart and no more evaluations can happen.
445 ///
446 /// # Panics
447 ///
448 /// This will panic if the evaluation is different between engines (e.g.,
449 /// results are different, hashed instance is different, one side traps, etc.).
450 pub fn differential(
451     lhs: &mut dyn DiffInstance,
452     lhs_engine: &dyn DiffEngine,
453     rhs: &mut WasmtimeInstance,
454     name: &str,
455     args: &[DiffValue],
456     result_tys: &[DiffValueType],
457 ) -> anyhow::Result<bool> {
458     log::debug!("Evaluating: `{name}` with {args:?}");
459     let lhs_results = match lhs.evaluate(name, args, result_tys) {
460         Ok(Some(results)) => Ok(results),
461         Err(e) => Err(e),
462         // this engine couldn't execute this type signature, so discard this
463         // execution by returning success.
464         Ok(None) => return Ok(true),
465     };
466     log::debug!(" -> lhs results on {}: {:?}", lhs.name(), &lhs_results);
467 
468     let rhs_results = rhs
469         .evaluate(name, args, result_tys)
470         // wasmtime should be able to invoke any signature, so unwrap this result
471         .map(|results| results.unwrap());
472     log::debug!(" -> rhs results on {}: {:?}", rhs.name(), &rhs_results);
473 
474     // If Wasmtime hit its OOM condition, which is possible since it's set
475     // somewhat low while fuzzing, then don't return an error but return
476     // `false` indicating that differential fuzzing must stop. There's no
477     // guarantee the other engine has the same OOM limits as Wasmtime, and
478     // it's assumed that Wasmtime is configured to have a more conservative
479     // limit than the other engine.
480     if rhs.is_oom() {
481         return Ok(false);
482     }
483 
484     match DiffEqResult::new(lhs_engine, lhs_results, rhs_results) {
485         DiffEqResult::Success(lhs, rhs) => assert_eq!(lhs, rhs),
486         DiffEqResult::Poisoned => return Ok(false),
487         DiffEqResult::Failed => {}
488     }
489 
490     for (global, ty) in rhs.exported_globals() {
491         log::debug!("Comparing global `{global}`");
492         let lhs = match lhs.get_global(&global, ty) {
493             Some(val) => val,
494             None => continue,
495         };
496         let rhs = rhs.get_global(&global, ty).unwrap();
497         assert_eq!(lhs, rhs);
498     }
499     for (memory, shared) in rhs.exported_memories() {
500         log::debug!("Comparing memory `{memory}`");
501         let lhs = match lhs.get_memory(&memory, shared) {
502             Some(val) => val,
503             None => continue,
504         };
505         let rhs = rhs.get_memory(&memory, shared).unwrap();
506         if lhs == rhs {
507             continue;
508         }
509         eprintln!("differential memory is {} bytes long", lhs.len());
510         eprintln!("wasmtime memory is     {} bytes long", rhs.len());
511         panic!("memories have differing values");
512     }
513 
514     Ok(true)
515 }
516 
517 /// Result of comparing the result of two operations during differential
518 /// execution.
519 pub enum DiffEqResult<T, U> {
520     /// Both engines succeeded.
521     Success(T, U),
522     /// The result has reached the state where engines may have diverged and
523     /// results can no longer be compared.
524     Poisoned,
525     /// Both engines failed with the same error message, and internal state
526     /// should still match between the two engines.
527     Failed,
528 }
529 
530 fn wasmtime_trap_is_non_deterministic(trap: &Trap) -> bool {
531     match trap {
532         // Allocations being too large for the GC are
533         // implementation-defined.
534         Trap::AllocationTooLarge |
535         // Stack size, and therefore when overflow happens, is
536         // implementation-defined.
537         Trap::StackOverflow => true,
538         _ => false,
539     }
540 }
541 
542 fn wasmtime_error_is_non_deterministic(error: &wasmtime::Error) -> bool {
543     match error.downcast_ref::<Trap>() {
544         Some(trap) => wasmtime_trap_is_non_deterministic(trap),
545 
546         // For general, unknown errors, we can't rely on this being
547         // a deterministic Wasm failure that both engines handled
548         // identically, leaving Wasm in identical states. We could
549         // just as easily be hitting engine-specific failures, like
550         // different implementation-defined limits. So simply poison
551         // this execution and move on to the next test.
552         None => true,
553     }
554 }
555 
556 impl<T, U> DiffEqResult<T, U> {
557     /// Computes the differential result from executing in two different
558     /// engines.
559     pub fn new(
560         lhs_engine: &dyn DiffEngine,
561         lhs_result: Result<T>,
562         rhs_result: Result<U>,
563     ) -> DiffEqResult<T, U> {
564         match (lhs_result, rhs_result) {
565             (Ok(lhs_result), Ok(rhs_result)) => DiffEqResult::Success(lhs_result, rhs_result),
566 
567             // Handle all non-deterministic errors by poisoning this execution's
568             // state, so that we simply move on to the next test.
569             (Err(lhs), _) if lhs_engine.is_non_deterministic_error(&lhs) => {
570                 log::debug!("lhs failed non-deterministically: {lhs:?}");
571                 DiffEqResult::Poisoned
572             }
573             (_, Err(rhs)) if wasmtime_error_is_non_deterministic(&rhs) => {
574                 log::debug!("rhs failed non-deterministically: {rhs:?}");
575                 DiffEqResult::Poisoned
576             }
577 
578             // Both sides failed deterministically. Check that the trap and
579             // state at the time of failure is the same.
580             (Err(lhs), Err(rhs)) => {
581                 let rhs = rhs
582                     .downcast::<Trap>()
583                     .expect("non-traps handled in earlier match arm");
584 
585                 debug_assert!(
586                     !lhs_engine.is_non_deterministic_error(&lhs),
587                     "non-deterministic traps handled in earlier match arm",
588                 );
589                 debug_assert!(
590                     !wasmtime_trap_is_non_deterministic(&rhs),
591                     "non-deterministic traps handled in earlier match arm",
592                 );
593 
594                 lhs_engine.assert_error_match(&lhs, &rhs);
595                 DiffEqResult::Failed
596             }
597 
598             // A real bug is found if only one side fails.
599             (Ok(_), Err(err)) => panic!("only the `rhs` failed for this input: {err:?}"),
600             (Err(err), Ok(_)) => panic!("only the `lhs` failed for this input: {err:?}"),
601         }
602     }
603 }
604 
605 /// Invoke the given API calls.
606 pub fn make_api_calls(api: generators::api::ApiCalls) {
607     use crate::generators::api::ApiCall;
608     use std::collections::HashMap;
609 
610     let mut store: Option<Store<StoreLimits>> = None;
611     let mut modules: HashMap<usize, Module> = Default::default();
612     let mut instances: HashMap<usize, Instance> = Default::default();
613 
614     for call in api.calls {
615         match call {
616             ApiCall::StoreNew(config) => {
617                 log::trace!("creating store");
618                 assert!(store.is_none());
619                 store = Some(config.to_store());
620             }
621 
622             ApiCall::ModuleNew { id, wasm } => {
623                 log::debug!("creating module: {id}");
624                 log_wasm(&wasm);
625                 let module = match Module::new(store.as_ref().unwrap().engine(), &wasm) {
626                     Ok(m) => m,
627                     Err(_) => continue,
628                 };
629                 let old = modules.insert(id, module);
630                 assert!(old.is_none());
631             }
632 
633             ApiCall::ModuleDrop { id } => {
634                 log::trace!("dropping module: {id}");
635                 drop(modules.remove(&id));
636             }
637 
638             ApiCall::InstanceNew { id, module } => {
639                 log::trace!("instantiating module {module} as {id}");
640                 let module = match modules.get(&module) {
641                     Some(m) => m,
642                     None => continue,
643                 };
644 
645                 let store = store.as_mut().unwrap();
646                 if let Some(instance) = instantiate_with_dummy(store, module) {
647                     instances.insert(id, instance);
648                 }
649             }
650 
651             ApiCall::InstanceDrop { id } => {
652                 log::trace!("dropping instance {id}");
653                 instances.remove(&id);
654             }
655 
656             ApiCall::CallExportedFunc { instance, nth } => {
657                 log::trace!("calling instance export {instance} / {nth}");
658                 let instance = match instances.get(&instance) {
659                     Some(i) => i,
660                     None => {
661                         // Note that we aren't guaranteed to instantiate valid
662                         // modules, see comments in `InstanceNew` for details on
663                         // that. But the API call generator can't know if
664                         // instantiation failed, so we might not actually have
665                         // this instance. When that's the case, just skip the
666                         // API call and keep going.
667                         continue;
668                     }
669                 };
670                 let store = store.as_mut().unwrap();
671 
672                 let funcs = instance
673                     .exports(&mut *store)
674                     .filter_map(|e| match e.into_extern() {
675                         Extern::Func(f) => Some(f),
676                         _ => None,
677                     })
678                     .collect::<Vec<_>>();
679 
680                 if funcs.is_empty() {
681                     continue;
682                 }
683 
684                 let nth = nth % funcs.len();
685                 let f = &funcs[nth];
686                 let ty = f.ty(&store);
687                 if let Some(params) = ty
688                     .params()
689                     .map(|p| p.default_value())
690                     .collect::<Option<Vec<_>>>()
691                 {
692                     let mut results = vec![Val::I32(0); ty.results().len()];
693                     let _ = f.call(store, &params, &mut results);
694                 }
695             }
696         }
697     }
698 }
699 
700 /// Executes the wast `test` with the `config` specified.
701 ///
702 /// Ensures that wast tests pass regardless of the `Config`.
703 pub fn wast_test(u: &mut arbitrary::Unstructured<'_>) -> arbitrary::Result<()> {
704     crate::init_fuzzing();
705 
706     let mut fuzz_config: generators::Config = u.arbitrary()?;
707     let test: generators::WastTest = u.arbitrary()?;
708 
709     let test = &test.test;
710 
711     if test.config.component_model_async() || u.arbitrary()? {
712         fuzz_config.enable_async(u)?;
713     }
714 
715     // Discard tests that allocate a lot of memory as we don't want to OOM the
716     // fuzzer and we also limit memory growth which would cause the test to
717     // fail.
718     if test.config.hogs_memory.unwrap_or(false) {
719         return Err(arbitrary::Error::IncorrectFormat);
720     }
721 
722     // Transform `fuzz_config` to be valid for `test` and make sure that this
723     // test is supposed to pass.
724     let wast_config = fuzz_config.make_wast_test_compliant(test);
725     if test.should_fail(&wast_config) {
726         return Err(arbitrary::Error::IncorrectFormat);
727     }
728 
729     // Winch requires AVX and AVX2 for SIMD tests to pass so don't run the test
730     // if either isn't enabled.
731     if fuzz_config.wasmtime.compiler_strategy == CompilerStrategy::Winch
732         && test.config.simd()
733         && (fuzz_config
734             .wasmtime
735             .codegen_flag("has_avx")
736             .is_some_and(|value| value == "false")
737             || fuzz_config
738                 .wasmtime
739                 .codegen_flag("has_avx2")
740                 .is_some_and(|value| value == "false"))
741     {
742         log::warn!(
743             "Skipping Wast test because Winch doesn't support SIMD tests with AVX or AVX2 disabled"
744         );
745         return Err(arbitrary::Error::IncorrectFormat);
746     }
747 
748     // Fuel and epochs don't play well with threads right now, so exclude any
749     // thread-spawning test if it looks like threads are spawned in that case.
750     if fuzz_config.wasmtime.consume_fuel || fuzz_config.wasmtime.epoch_interruption {
751         if test.contents.contains("(thread") {
752             return Err(arbitrary::Error::IncorrectFormat);
753         }
754     }
755 
756     log::debug!("running {:?}", test.path);
757     let async_ = if fuzz_config.wasmtime.async_config == generators::AsyncConfig::Disabled {
758         wasmtime_wast::Async::No
759     } else {
760         wasmtime_wast::Async::Yes
761     };
762     log::debug!("async: {async_:?}");
763     let engine = Engine::new(&fuzz_config.to_wasmtime()).unwrap();
764     let mut wast_context = WastContext::new(&engine, async_, move |store| {
765         fuzz_config.configure_store_epoch_and_fuel(store);
766     });
767     wast_context
768         .register_spectest(&wasmtime_wast::SpectestConfig {
769             use_shared_memory: true,
770             suppress_prints: true,
771         })
772         .unwrap();
773     wast_context
774         .run_wast(test.path.to_str().unwrap(), test.contents.as_bytes())
775         .unwrap();
776     Ok(())
777 }
778 
779 /// Execute a series of `gc` operations.
780 ///
781 /// Returns the number of `gc` operations which occurred throughout the test
782 /// case -- used to test below that gc happens reasonably soon and eventually.
783 pub fn gc_ops(mut fuzz_config: generators::Config, mut ops: GcOps) -> Result<usize> {
784     let expected_drops = Arc::new(AtomicUsize::new(0));
785     let num_dropped = Arc::new(AtomicUsize::new(0));
786 
787     let num_gcs = Arc::new(AtomicUsize::new(0));
788     {
789         fuzz_config.wasmtime.consume_fuel = true;
790         let mut store = fuzz_config.to_store();
791         store.set_fuel(1_000).unwrap();
792 
793         let wasm = ops.to_wasm_binary();
794         log_wasm(&wasm);
795         let module = match compile_module(store.engine(), &wasm, KnownValid::No, &fuzz_config) {
796             Some(m) => m,
797             None => return Ok(0),
798         };
799 
800         let mut linker = Linker::new(store.engine());
801 
802         // To avoid timeouts, limit the number of explicit GCs we perform per
803         // test case.
804         const MAX_GCS: usize = 5;
805 
806         let func_ty = FuncType::new(
807             store.engine(),
808             vec![],
809             vec![ValType::EXTERNREF, ValType::EXTERNREF, ValType::EXTERNREF],
810         );
811         let func = Func::new(&mut store, func_ty, {
812             let num_dropped = num_dropped.clone();
813             let expected_drops = expected_drops.clone();
814             let num_gcs = num_gcs.clone();
815             move |mut caller: Caller<'_, StoreLimits>, _params, results| {
816                 log::info!("gc_ops: GC");
817                 if num_gcs.fetch_add(1, SeqCst) < MAX_GCS {
818                     caller.gc(None);
819                 }
820 
821                 let a = ExternRef::new(
822                     &mut caller,
823                     CountDrops::new(&expected_drops, num_dropped.clone()),
824                 )?;
825                 let b = ExternRef::new(
826                     &mut caller,
827                     CountDrops::new(&expected_drops, num_dropped.clone()),
828                 )?;
829                 let c = ExternRef::new(
830                     &mut caller,
831                     CountDrops::new(&expected_drops, num_dropped.clone()),
832                 )?;
833 
834                 log::info!("gc_ops: gc() -> ({a:?}, {b:?}, {c:?})");
835                 results[0] = Some(a).into();
836                 results[1] = Some(b).into();
837                 results[2] = Some(c).into();
838                 Ok(())
839             }
840         });
841         linker.define(&store, "", "gc", func).unwrap();
842 
843         linker
844             .func_wrap("", "take_refs", {
845                 let expected_drops = expected_drops.clone();
846                 move |caller: Caller<'_, StoreLimits>,
847                       a: Option<Rooted<ExternRef>>,
848                       b: Option<Rooted<ExternRef>>,
849                       c: Option<Rooted<ExternRef>>|
850                       -> Result<()> {
851                     log::info!("gc_ops: take_refs({a:?}, {b:?}, {c:?})",);
852 
853                     // Do the assertion on each ref's inner data, even though it
854                     // all points to the same atomic, so that if we happen to
855                     // run into a use-after-free bug with one of these refs we
856                     // are more likely to trigger a segfault.
857                     if let Some(a) = a {
858                         let a = a
859                             .data(&caller)?
860                             .unwrap()
861                             .downcast_ref::<CountDrops>()
862                             .unwrap();
863                         assert!(a.0.load(SeqCst) <= expected_drops.load(SeqCst));
864                     }
865                     if let Some(b) = b {
866                         let b = b
867                             .data(&caller)?
868                             .unwrap()
869                             .downcast_ref::<CountDrops>()
870                             .unwrap();
871                         assert!(b.0.load(SeqCst) <= expected_drops.load(SeqCst));
872                     }
873                     if let Some(c) = c {
874                         let c = c
875                             .data(&caller)?
876                             .unwrap()
877                             .downcast_ref::<CountDrops>()
878                             .unwrap();
879                         assert!(c.0.load(SeqCst) <= expected_drops.load(SeqCst));
880                     }
881                     Ok(())
882                 }
883             })
884             .unwrap();
885 
886         let func_ty = FuncType::new(
887             store.engine(),
888             vec![],
889             vec![ValType::EXTERNREF, ValType::EXTERNREF, ValType::EXTERNREF],
890         );
891         let func = Func::new(&mut store, func_ty, {
892             let num_dropped = num_dropped.clone();
893             let expected_drops = expected_drops.clone();
894             move |mut caller, _params, results| {
895                 log::info!("gc_ops: make_refs");
896 
897                 let a = ExternRef::new(
898                     &mut caller,
899                     CountDrops::new(&expected_drops, num_dropped.clone()),
900                 )?;
901                 let b = ExternRef::new(
902                     &mut caller,
903                     CountDrops::new(&expected_drops, num_dropped.clone()),
904                 )?;
905                 let c = ExternRef::new(
906                     &mut caller,
907                     CountDrops::new(&expected_drops, num_dropped.clone()),
908                 )?;
909 
910                 log::info!("gc_ops: make_refs() -> ({a:?}, {b:?}, {c:?})");
911 
912                 results[0] = Some(a).into();
913                 results[1] = Some(b).into();
914                 results[2] = Some(c).into();
915 
916                 Ok(())
917             }
918         });
919         linker.define(&store, "", "make_refs", func).unwrap();
920 
921         let func_ty = FuncType::new(
922             store.engine(),
923             vec![ValType::Ref(RefType::new(false, HeapType::Any))],
924             vec![],
925         );
926 
927         let func = Func::new(&mut store, func_ty, {
928             move |_caller: Caller<'_, StoreLimits>, _params, _results| {
929                 log::info!("gc_ops: take_struct(<ref any>)");
930                 Ok(())
931             }
932         });
933 
934         linker.define(&store, "", "take_struct", func).unwrap();
935 
936         for imp in module.imports() {
937             if imp.module() == "" {
938                 let name = imp.name();
939                 if name.starts_with("take_struct_") {
940                     if let wasmtime::ExternType::Func(ft) = imp.ty() {
941                         let imp_name = name.to_string();
942                         let func =
943                             Func::new(&mut store, ft.clone(), move |_caller, _params, _results| {
944                                 log::info!("gc_ops: {imp_name}(<typed structref>)");
945                                 Ok(())
946                             });
947                         linker.define(&store, "", name, func).unwrap();
948                     }
949                 }
950             }
951         }
952 
953         let instance = linker.instantiate(&mut store, &module).unwrap();
954         let run = instance.get_func(&mut store, "run").unwrap();
955 
956         {
957             let mut scope = RootScope::new(&mut store);
958 
959             log::info!(
960                 "gc_ops: begin allocating {} externref arguments",
961                 ops.limits.num_globals
962             );
963             let args: Vec<_> = (0..ops.limits.num_params)
964                 .map(|_| {
965                     Ok(Val::ExternRef(Some(ExternRef::new(
966                         &mut scope,
967                         CountDrops::new(&expected_drops, num_dropped.clone()),
968                     )?)))
969                 })
970                 .collect::<Result<_>>()?;
971             log::info!(
972                 "gc_ops: end allocating {} externref arguments",
973                 ops.limits.num_globals
974             );
975 
976             // The generated function should always return a trap. The only two
977             // valid traps are table-out-of-bounds which happens through `table.get`
978             // and `table.set` generated or an out-of-fuel trap. Otherwise any other
979             // error is unexpected and should fail fuzzing.
980             log::info!("gc_ops: calling into Wasm `run` function");
981             let err = run.call(&mut scope, &args, &mut []).unwrap_err();
982             if err.is::<GcHeapOutOfMemory<CountDrops>>() || err.is::<GcHeapOutOfMemory<()>>() {
983                 // Accept GC OOM as an allowed outcome for this fuzzer.
984             } else {
985                 let trap = err
986                     .downcast::<Trap>()
987                     .expect("if not GC oom, error should be a Wasm trap");
988                 match trap {
989                     Trap::TableOutOfBounds | Trap::OutOfFuel | Trap::AllocationTooLarge => {}
990                     _ => panic!("unexpected trap: {trap}"),
991                 }
992             }
993         }
994 
995         // Do a final GC after running the Wasm.
996         store.gc(None);
997     }
998 
999     assert_eq!(num_dropped.load(SeqCst), expected_drops.load(SeqCst));
1000     return Ok(num_gcs.load(SeqCst));
1001 
1002     struct CountDrops(Arc<AtomicUsize>);
1003 
1004     impl CountDrops {
1005         fn new(expected_drops: &AtomicUsize, num_dropped: Arc<AtomicUsize>) -> Self {
1006             let expected = expected_drops.fetch_add(1, SeqCst);
1007             log::info!(
1008                 "CountDrops::new: expected drops: {expected} -> {}",
1009                 expected + 1
1010             );
1011             Self(num_dropped)
1012         }
1013     }
1014 
1015     impl Drop for CountDrops {
1016         fn drop(&mut self) {
1017             let drops = self.0.fetch_add(1, SeqCst);
1018             log::info!("CountDrops::drop: actual drops: {drops} -> {}", drops + 1);
1019         }
1020     }
1021 }
1022 
1023 #[derive(Default)]
1024 struct HelperThread {
1025     state: Arc<HelperThreadState>,
1026     thread: Option<std::thread::JoinHandle<()>>,
1027 }
1028 
1029 #[derive(Default)]
1030 struct HelperThreadState {
1031     should_exit: Mutex<bool>,
1032     should_exit_cvar: Condvar,
1033 }
1034 
1035 impl HelperThread {
1036     fn run_periodically(&mut self, dur: Duration, mut closure: impl FnMut() + Send + 'static) {
1037         let state = self.state.clone();
1038         self.thread = Some(std::thread::spawn(move || {
1039             // Using our mutex/condvar we wait here for the first of `dur` to
1040             // pass or the `HelperThread` instance to get dropped.
1041             let mut should_exit = state.should_exit.lock().unwrap();
1042             while !*should_exit {
1043                 let (lock, result) = state
1044                     .should_exit_cvar
1045                     .wait_timeout(should_exit, dur)
1046                     .unwrap();
1047                 should_exit = lock;
1048                 // If we timed out for sure then there's no need to continue
1049                 // since we'll just abort on the next `checked_sub` anyway.
1050                 if result.timed_out() {
1051                     closure();
1052                 }
1053             }
1054         }));
1055     }
1056 }
1057 
1058 impl Drop for HelperThread {
1059     fn drop(&mut self) {
1060         let thread = match self.thread.take() {
1061             Some(thread) => thread,
1062             None => return,
1063         };
1064         // Signal our thread that it should exit and wake it up in case it's
1065         // sleeping.
1066         *self.state.should_exit.lock().unwrap() = true;
1067         self.state.should_exit_cvar.notify_one();
1068 
1069         // ... and then wait for the thread to exit to ensure we clean up
1070         // after ourselves.
1071         thread.join().unwrap();
1072     }
1073 }
1074 
1075 /// Generate and execute a `crate::generators::component_types::TestCase` using the specified `input` to create
1076 /// arbitrary types and values.
1077 pub fn dynamic_component_api_target(input: &mut arbitrary::Unstructured) -> arbitrary::Result<()> {
1078     use crate::generators::component_types;
1079     use wasmtime::component::{Component, Linker, Val};
1080     use wasmtime_test_util::component::FuncExt;
1081     use wasmtime_test_util::component_fuzz::{
1082         EXPORT_FUNCTION, IMPORT_FUNCTION, MAX_TYPE_DEPTH, TestCase, Type,
1083     };
1084 
1085     crate::init_fuzzing();
1086 
1087     let mut types = Vec::new();
1088     let mut type_fuel = 500;
1089 
1090     for _ in 0..5 {
1091         types.push(Type::generate(input, MAX_TYPE_DEPTH, &mut type_fuel)?);
1092     }
1093     let params = (0..input.int_in_range(0..=5)?)
1094         .map(|_| input.choose(&types))
1095         .collect::<arbitrary::Result<Vec<_>>>()?;
1096     let result = if input.arbitrary()? {
1097         Some(input.choose(&types)?)
1098     } else {
1099         None
1100     };
1101 
1102     let case = TestCase {
1103         params,
1104         result,
1105         encoding1: input.arbitrary()?,
1106         encoding2: input.arbitrary()?,
1107     };
1108 
1109     let mut config = wasmtime_test_util::component::config();
1110     config.debug_adapter_modules(input.arbitrary()?);
1111     let engine = Engine::new(&config).unwrap();
1112     let mut store = Store::new(&engine, (Vec::new(), None));
1113     let wat = case.declarations().make_component();
1114     let wat = wat.as_bytes();
1115     log_wasm(wat);
1116     let component = Component::new(&engine, wat).unwrap();
1117     let mut linker = Linker::new(&engine);
1118 
1119     linker
1120         .root()
1121         .func_new(IMPORT_FUNCTION, {
1122             move |mut cx: StoreContextMut<'_, (Vec<Val>, Option<Vec<Val>>)>,
1123                   _,
1124                   params: &[Val],
1125                   results: &mut [Val]|
1126                   -> Result<()> {
1127                 log::trace!("received params {params:?}");
1128                 let (expected_args, expected_results) = cx.data_mut();
1129                 assert_eq!(params.len(), expected_args.len());
1130                 for (expected, actual) in expected_args.iter().zip(params) {
1131                     assert_eq!(expected, actual);
1132                 }
1133                 results.clone_from_slice(&expected_results.take().unwrap());
1134                 log::trace!("returning results {results:?}");
1135                 Ok(())
1136             }
1137         })
1138         .unwrap();
1139 
1140     let instance = linker.instantiate(&mut store, &component).unwrap();
1141     let func = instance.get_func(&mut store, EXPORT_FUNCTION).unwrap();
1142     let ty = func.ty(&store);
1143 
1144     while input.arbitrary()? {
1145         let params = ty
1146             .params()
1147             .map(|(_, ty)| component_types::arbitrary_val(&ty, input))
1148             .collect::<arbitrary::Result<Vec<_>>>()?;
1149         let results = ty
1150             .results()
1151             .map(|ty| component_types::arbitrary_val(&ty, input))
1152             .collect::<arbitrary::Result<Vec<_>>>()?;
1153 
1154         *store.data_mut() = (params.clone(), Some(results.clone()));
1155 
1156         log::trace!("passing params {params:?}");
1157         let mut actual = vec![Val::Bool(false); results.len()];
1158         func.call_and_post_return(&mut store, &params, &mut actual)
1159             .unwrap();
1160         log::trace!("received results {actual:?}");
1161         assert_eq!(actual, results);
1162     }
1163 
1164     Ok(())
1165 }
1166 
1167 /// Instantiates a wasm module and runs its exports with dummy values, all in
1168 /// an async fashion.
1169 ///
1170 /// Attempts to stress yields in host functions to ensure that exiting and
1171 /// resuming a wasm function call works.
1172 pub fn call_async(wasm: &[u8], config: &generators::Config, mut poll_amts: &[u32]) {
1173     let mut store = config.to_store();
1174     let module = match compile_module(store.engine(), wasm, KnownValid::Yes, config) {
1175         Some(module) => module,
1176         None => return,
1177     };
1178 
1179     // Configure a helper thread to periodically increment the epoch to
1180     // forcibly enable yields-via-epochs if epochs are in use. Note that this
1181     // is required because the wasm isn't otherwise guaranteed to necessarily
1182     // call any imports which will also increment the epoch.
1183     let mut helper_thread = HelperThread::default();
1184     if let generators::AsyncConfig::YieldWithEpochs { dur, .. } = &config.wasmtime.async_config {
1185         let engine = store.engine().clone();
1186         helper_thread.run_periodically(*dur, move || engine.increment_epoch());
1187     }
1188 
1189     // Generate a `Linker` where all function imports are custom-built to yield
1190     // periodically and additionally increment the epoch.
1191     let mut imports = Vec::new();
1192     for import in module.imports() {
1193         let item = match import.ty() {
1194             ExternType::Func(ty) => {
1195                 let poll_amt = take_poll_amt(&mut poll_amts);
1196                 Func::new_async(&mut store, ty.clone(), move |caller, _, results| {
1197                     let ty = ty.clone();
1198                     Box::new(async move {
1199                         caller.engine().increment_epoch();
1200                         log::info!("yielding {poll_amt} times in import");
1201                         YieldN(poll_amt).await;
1202                         for (ret_ty, result) in ty.results().zip(results) {
1203                             *result = ret_ty.default_value().unwrap();
1204                         }
1205                         Ok(())
1206                     })
1207                 })
1208                 .into()
1209             }
1210             other_ty => match other_ty.default_value(&mut store) {
1211                 Ok(item) => item,
1212                 Err(e) => {
1213                     log::warn!("couldn't create import for {import:?}: {e:?}");
1214                     return;
1215                 }
1216             },
1217         };
1218         imports.push(item);
1219     }
1220 
1221     // Run the instantiation process, asynchronously, and if everything
1222     // succeeds then pull out the instance.
1223     // log::info!("starting instantiation");
1224     let instance = run(Timeout {
1225         future: Instance::new_async(&mut store, &module, &imports),
1226         polls: take_poll_amt(&mut poll_amts),
1227         end: Instant::now() + Duration::from_millis(2_000),
1228     });
1229     let instance = match instance {
1230         Ok(instantiation_result) => match unwrap_instance(&store, instantiation_result) {
1231             Some(instance) => instance,
1232             None => {
1233                 log::info!("instantiation hit a nominal error");
1234                 return; // resource exhaustion or limits met
1235             }
1236         },
1237         Err(_) => {
1238             log::info!("instantiation failed to complete");
1239             return; // Timed out or ran out of polls
1240         }
1241     };
1242 
1243     // Run each export of the instance in the same manner as instantiation
1244     // above. Dummy values are passed in for argument values here:
1245     //
1246     // TODO: this should probably be more clever about passing in arguments for
1247     // example they might be used as pointers or something and always using 0
1248     // isn't too interesting.
1249     let funcs = instance
1250         .exports(&mut store)
1251         .filter_map(|e| {
1252             let name = e.name().to_string();
1253             let func = e.into_extern().into_func()?;
1254             Some((name, func))
1255         })
1256         .collect::<Vec<_>>();
1257     for (name, func) in funcs {
1258         let ty = func.ty(&store);
1259         let params = ty
1260             .params()
1261             .map(|ty| ty.default_value().unwrap())
1262             .collect::<Vec<_>>();
1263         let mut results = ty
1264             .results()
1265             .map(|ty| ty.default_value().unwrap())
1266             .collect::<Vec<_>>();
1267 
1268         log::info!("invoking export {name:?}");
1269         let future = func.call_async(&mut store, &params, &mut results);
1270         match run(Timeout {
1271             future,
1272             polls: take_poll_amt(&mut poll_amts),
1273             end: Instant::now() + Duration::from_millis(2_000),
1274         }) {
1275             // On success or too many polls, try the next export.
1276             Ok(_) | Err(Exhausted::Polls) => {}
1277 
1278             // If time ran out then stop the current test case as we might have
1279             // already sucked up a lot of time for this fuzz test case so don't
1280             // keep it going.
1281             Err(Exhausted::Time) => return,
1282         }
1283     }
1284 
1285     fn take_poll_amt(polls: &mut &[u32]) -> u32 {
1286         match polls.split_first() {
1287             Some((a, rest)) => {
1288                 *polls = rest;
1289                 *a
1290             }
1291             None => 0,
1292         }
1293     }
1294 
1295     /// Helper future to yield N times before resolving.
1296     struct YieldN(u32);
1297 
1298     impl Future for YieldN {
1299         type Output = ();
1300 
1301         fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<()> {
1302             if self.0 == 0 {
1303                 Poll::Ready(())
1304             } else {
1305                 self.0 -= 1;
1306                 cx.waker().wake_by_ref();
1307                 Poll::Pending
1308             }
1309         }
1310     }
1311 
1312     /// Helper future for applying a timeout to `future` up to either when `end`
1313     /// is the current time or `polls` polls happen.
1314     ///
1315     /// Note that this helps to time out infinite loops in wasm, for example.
1316     struct Timeout<F> {
1317         future: F,
1318         /// If the future isn't ready by this time then the `Timeout<F>` future
1319         /// will return `None`.
1320         end: Instant,
1321         /// If the future doesn't resolve itself in this many calls to `poll`
1322         /// then the `Timeout<F>` future will return `None`.
1323         polls: u32,
1324     }
1325 
1326     enum Exhausted {
1327         Time,
1328         Polls,
1329     }
1330 
1331     impl<F: Future> Future for Timeout<F> {
1332         type Output = Result<F::Output, Exhausted>;
1333 
1334         fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
1335             let (end, polls, future) = unsafe {
1336                 let me = self.get_unchecked_mut();
1337                 (me.end, &mut me.polls, Pin::new_unchecked(&mut me.future))
1338             };
1339             match future.poll(cx) {
1340                 Poll::Ready(val) => Poll::Ready(Ok(val)),
1341                 Poll::Pending => {
1342                     if Instant::now() >= end {
1343                         log::warn!("future operation timed out");
1344                         return Poll::Ready(Err(Exhausted::Time));
1345                     }
1346                     if *polls == 0 {
1347                         log::warn!("future operation ran out of polls");
1348                         return Poll::Ready(Err(Exhausted::Polls));
1349                     }
1350                     *polls -= 1;
1351                     Poll::Pending
1352                 }
1353             }
1354         }
1355     }
1356 
1357     fn run<F: Future>(future: F) -> F::Output {
1358         let mut f = Box::pin(future);
1359         let mut cx = Context::from_waker(Waker::noop());
1360         loop {
1361             match f.as_mut().poll(&mut cx) {
1362                 Poll::Ready(val) => break val,
1363                 Poll::Pending => {}
1364             }
1365         }
1366     }
1367 }
1368 
1369 #[cfg(test)]
1370 mod tests {
1371     use super::*;
1372     use arbitrary::Unstructured;
1373     use rand::prelude::*;
1374     use wasmparser::{Validator, WasmFeatures};
1375 
1376     fn gen_until_pass<T: for<'a> Arbitrary<'a>>(
1377         mut f: impl FnMut(T, &mut Unstructured<'_>) -> Result<bool>,
1378     ) -> bool {
1379         let mut rng = SmallRng::seed_from_u64(0);
1380         let mut buf = vec![0; 2048];
1381         let n = 3000;
1382         for _ in 0..n {
1383             rng.fill_bytes(&mut buf);
1384             let mut u = Unstructured::new(&buf);
1385 
1386             if let Ok(config) = u.arbitrary() {
1387                 if f(config, &mut u).unwrap() {
1388                     return true;
1389                 }
1390             }
1391         }
1392         false
1393     }
1394 
1395     /// Runs `f` with random data until it returns `Ok(())` `iters` times.
1396     fn test_n_times<T: for<'a> Arbitrary<'a>>(
1397         iters: u32,
1398         mut f: impl FnMut(T, &mut Unstructured<'_>) -> arbitrary::Result<()>,
1399     ) {
1400         let mut to_test = 0..iters;
1401         let ok = gen_until_pass(|a, b| {
1402             if f(a, b).is_ok() {
1403                 Ok(to_test.next().is_none())
1404             } else {
1405                 Ok(false)
1406             }
1407         });
1408         assert!(ok);
1409     }
1410 
1411     // Test that the `gc_ops` fuzzer eventually runs the gc function in the host.
1412     // We've historically had issues where this fuzzer accidentally wasn't fuzzing
1413     // anything for a long time so this is an attempt to prevent that from happening
1414     // again.
1415     #[test]
1416     fn gc_ops_eventually_gcs() {
1417         // Skip if we're under emulation because some fuzz configurations will do
1418         // large address space reservations that QEMU doesn't handle well.
1419         if std::env::var("WASMTIME_TEST_NO_HOG_MEMORY").is_ok() {
1420             return;
1421         }
1422 
1423         let ok = gen_until_pass(|(config, test), _| {
1424             let result = gc_ops(config, test)?;
1425             Ok(result > 0)
1426         });
1427 
1428         if !ok {
1429             panic!("gc was never found");
1430         }
1431     }
1432 
1433     #[test]
1434     fn module_generation_uses_expected_proposals() {
1435         // Proposals that Wasmtime supports. Eventually a module should be
1436         // generated that needs these proposals.
1437         let mut expected = WasmFeatures::MUTABLE_GLOBAL
1438             | WasmFeatures::FLOATS
1439             | WasmFeatures::SIGN_EXTENSION
1440             | WasmFeatures::SATURATING_FLOAT_TO_INT
1441             | WasmFeatures::MULTI_VALUE
1442             | WasmFeatures::BULK_MEMORY
1443             | WasmFeatures::REFERENCE_TYPES
1444             | WasmFeatures::SIMD
1445             | WasmFeatures::MULTI_MEMORY
1446             | WasmFeatures::RELAXED_SIMD
1447             | WasmFeatures::THREADS
1448             | WasmFeatures::TAIL_CALL
1449             | WasmFeatures::WIDE_ARITHMETIC
1450             | WasmFeatures::MEMORY64
1451             | WasmFeatures::FUNCTION_REFERENCES
1452             | WasmFeatures::GC
1453             | WasmFeatures::GC_TYPES
1454             | WasmFeatures::CUSTOM_PAGE_SIZES
1455             | WasmFeatures::EXTENDED_CONST
1456             | WasmFeatures::EXCEPTIONS;
1457 
1458         // All other features that wasmparser supports, which is presumably a
1459         // superset of the features that wasm-smith supports, are listed here as
1460         // unexpected. This means, for example, that if wasm-smith updates to
1461         // include a new proposal by default that wasmtime implements then it
1462         // will be required to be listed above.
1463         let unexpected = WasmFeatures::all() ^ expected;
1464 
1465         let ok = gen_until_pass(|config: generators::Config, u| {
1466             let wasm = config.generate(u, None)?.to_bytes();
1467 
1468             // Double-check the module is valid
1469             Validator::new_with_features(WasmFeatures::all()).validate_all(&wasm)?;
1470 
1471             // If any of the unexpected features are removed then this module
1472             // should always be valid, otherwise something went wrong.
1473             for feature in unexpected.iter() {
1474                 let ok =
1475                     Validator::new_with_features(WasmFeatures::all() ^ feature).validate_all(&wasm);
1476                 if ok.is_err() {
1477                     anyhow::bail!("generated a module with {feature:?} but that wasn't expected");
1478                 }
1479             }
1480 
1481             // If any of `expected` is removed and the module fails to validate,
1482             // then that means the module requires that feature. Remove that
1483             // from the set of features we're then expecting.
1484             for feature in expected.iter() {
1485                 let ok =
1486                     Validator::new_with_features(WasmFeatures::all() ^ feature).validate_all(&wasm);
1487                 if ok.is_err() {
1488                     expected ^= feature;
1489                 }
1490             }
1491 
1492             Ok(expected.is_empty())
1493         });
1494 
1495         if !ok {
1496             panic!("never generated wasm module using {expected:?}");
1497         }
1498     }
1499 
1500     #[test]
1501     fn wast_smoke_test() {
1502         test_n_times(50, |(), u| super::wast_test(u));
1503     }
1504 }
1505