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