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 pub mod component_api;
14 pub mod component_async;
15 #[cfg(feature = "fuzz-spec-interpreter")]
16 pub mod diff_spec;
17 pub mod diff_wasmi;
18 pub mod diff_wasmtime;
19 pub mod dummy;
20 pub mod engine;
21 pub mod memory;
22 mod stacks;
23 
24 use self::diff_wasmtime::WasmtimeInstance;
25 use self::engine::{DiffEngine, DiffInstance};
26 use crate::generators::GcOps;
27 use crate::generators::{self, CompilerStrategy, DiffValue, DiffValueType};
28 use crate::single_module_fuzzer::KnownValid;
29 use crate::{YieldN, block_on};
30 use arbitrary::Arbitrary;
31 pub use stacks::check_stacks;
32 use std::future::Future;
33 use std::pin::Pin;
34 use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering::SeqCst};
35 use std::sync::{Arc, Condvar, Mutex};
36 use std::task::{Context, Poll};
37 use std::time::{Duration, Instant};
38 use wasmtime::*;
39 use wasmtime_wast::WastContext;
40 
41 #[cfg(not(any(windows, target_arch = "s390x", target_arch = "riscv64")))]
42 mod diff_v8;
43 
44 static CNT: AtomicUsize = AtomicUsize::new(0);
45 
46 /// Logs a wasm file to the filesystem to make it easy to figure out what wasm
47 /// was used when debugging.
48 pub fn log_wasm(wasm: &[u8]) {
49     super::init_fuzzing();
50 
51     if !log::log_enabled!(log::Level::Debug) {
52         return;
53     }
54 
55     let i = CNT.fetch_add(1, SeqCst);
56     let name = format!("testcase{i}.wasm");
57     std::fs::write(&name, wasm).expect("failed to write wasm file");
58     log::debug!("wrote wasm file to `{name}`");
59     let wat = format!("testcase{i}.wat");
60     match wasmprinter::print_bytes(wasm) {
61         Ok(s) => {
62             std::fs::write(&wat, s).expect("failed to write wat file");
63             log::debug!("wrote wat file to `{wat}`");
64         }
65         // If wasmprinter failed remove a `*.wat` file, if any, to avoid
66         // confusing a preexisting one with this wasm which failed to get
67         // printed.
68         Err(e) => {
69             log::debug!("failed to print to wat: {e}");
70             drop(std::fs::remove_file(&wat));
71         }
72     }
73 }
74 
75 /// The `T` in `Store<T>` for fuzzing stores, used to limit resource
76 /// consumption during fuzzing.
77 #[derive(Clone)]
78 pub struct StoreLimits(Arc<LimitsState>);
79 
80 struct LimitsState {
81     /// Remaining memory, in bytes, left to allocate
82     remaining_memory: AtomicUsize,
83     /// Remaining amount of memory that's allowed to be copied via a growth.
84     remaining_copy_allowance: AtomicUsize,
85     /// Whether or not an allocation request has been denied
86     oom: AtomicBool,
87 }
88 
89 /// Allow up to 1G which is well below the 2G limit on OSS-Fuzz and should allow
90 /// most interesting behavior.
91 const MAX_MEMORY: usize = 1 << 30;
92 
93 /// Allow up to 4G of bytes to be copied (conservatively) which should enable
94 /// growth up to `MAX_MEMORY` or at least up to a relatively large amount.
95 const MAX_MEMORY_MOVED: usize = 4 << 30;
96 
97 impl StoreLimits {
98     /// Creates the default set of limits for all fuzzing stores.
99     pub fn new() -> StoreLimits {
100         StoreLimits(Arc::new(LimitsState {
101             remaining_memory: AtomicUsize::new(MAX_MEMORY),
102             remaining_copy_allowance: AtomicUsize::new(MAX_MEMORY_MOVED),
103             oom: AtomicBool::new(false),
104         }))
105     }
106 
107     fn alloc(&mut self, amt: usize) -> bool {
108         log::trace!("alloc {amt:#x} bytes");
109 
110         // Assume that on each allocation of memory that all previous
111         // allocations of memory are moved. This is pretty coarse but is used to
112         // help prevent against fuzz test cases that just move tons of bytes
113         // around continuously. This assumes that all previous memory was
114         // allocated in a single linear memory and growing by `amt` will require
115         // moving all the bytes to a new location. This isn't actually required
116         // all the time nor does it accurately reflect what happens all the
117         // time, but it's a coarse approximation that should be "good enough"
118         // for allowing interesting fuzz behaviors to happen while not timing
119         // out just copying bytes around.
120         let prev_size = MAX_MEMORY - self.0.remaining_memory.load(SeqCst);
121         if self
122             .0
123             .remaining_copy_allowance
124             .fetch_update(SeqCst, SeqCst, |remaining| remaining.checked_sub(prev_size))
125             .is_err()
126         {
127             self.0.oom.store(true, SeqCst);
128             log::debug!("-> too many bytes moved, rejecting allocation");
129             return false;
130         }
131 
132         // If we're allowed to move the bytes, then also check if we're allowed
133         // to actually have this much residence at once.
134         match self
135             .0
136             .remaining_memory
137             .fetch_update(SeqCst, SeqCst, |remaining| remaining.checked_sub(amt))
138         {
139             Ok(_) => true,
140             Err(_) => {
141                 self.0.oom.store(true, SeqCst);
142                 log::debug!("-> OOM hit");
143                 false
144             }
145         }
146     }
147 
148     fn is_oom(&self) -> bool {
149         self.0.oom.load(SeqCst)
150     }
151 }
152 
153 impl ResourceLimiter for StoreLimits {
154     fn memory_growing(
155         &mut self,
156         current: usize,
157         desired: usize,
158         _maximum: Option<usize>,
159     ) -> Result<bool> {
160         Ok(self.alloc(desired - current))
161     }
162 
163     fn table_growing(
164         &mut self,
165         current: usize,
166         desired: usize,
167         _maximum: Option<usize>,
168     ) -> Result<bool> {
169         let delta = (desired - current).saturating_mul(std::mem::size_of::<usize>());
170         Ok(self.alloc(delta))
171     }
172 }
173 
174 /// Methods of timing out execution of a WebAssembly module
175 #[derive(Clone, Debug)]
176 pub enum Timeout {
177     /// No timeout is used, it should be guaranteed via some other means that
178     /// the input does not infinite loop.
179     None,
180     /// Fuel-based timeouts are used where the specified fuel is all that the
181     /// provided wasm module is allowed to consume.
182     Fuel(u64),
183     /// An epoch-interruption-based timeout is used with a sleeping
184     /// thread bumping the epoch counter after the specified duration.
185     Epoch(Duration),
186 }
187 
188 /// Instantiate the Wasm buffer, and implicitly fail if we have an unexpected
189 /// panic or segfault or anything else that can be detected "passively".
190 ///
191 /// The engine will be configured using provided config.
192 pub fn instantiate(
193     wasm: &[u8],
194     known_valid: KnownValid,
195     config: &generators::Config,
196     timeout: Timeout,
197 ) {
198     let mut store = config.to_store();
199 
200     let module = match compile_module(store.engine(), wasm, known_valid, config) {
201         Some(module) => module,
202         None => return,
203     };
204 
205     let mut timeout_state = HelperThread::default();
206     match timeout {
207         Timeout::Fuel(fuel) => store.set_fuel(fuel).unwrap(),
208 
209         // If a timeout is requested then we spawn a helper thread to wait for
210         // the requested time and then send us a signal to get interrupted. We
211         // also arrange for the thread's sleep to get interrupted if we return
212         // early (or the wasm returns within the time limit), which allows the
213         // thread to get torn down.
214         //
215         // This prevents us from creating a huge number of sleeping threads if
216         // this function is executed in a loop, like it does on nightly fuzzing
217         // infrastructure.
218         Timeout::Epoch(timeout) => {
219             let engine = store.engine().clone();
220             timeout_state.run_periodically(timeout, move || engine.increment_epoch());
221         }
222         Timeout::None => {}
223     }
224 
225     instantiate_with_dummy(&mut store, &module);
226 }
227 
228 /// Represents supported commands to the `instantiate_many` function.
229 #[derive(Arbitrary, Debug)]
230 pub enum Command {
231     /// Instantiates a module.
232     ///
233     /// The value is the index of the module to instantiate.
234     ///
235     /// The module instantiated will be this value modulo the number of modules provided to `instantiate_many`.
236     Instantiate(usize),
237     /// Terminates a "running" instance.
238     ///
239     /// The value is the index of the instance to terminate.
240     ///
241     /// The instance terminated will be this value modulo the number of currently running
242     /// instances.
243     ///
244     /// If no instances are running, the command will be ignored.
245     Terminate(usize),
246 }
247 
248 /// Instantiates many instances from the given modules.
249 ///
250 /// The engine will be configured using the provided config.
251 ///
252 /// The modules are expected to *not* have start functions as no timeouts are configured.
253 pub fn instantiate_many(
254     modules: &[Vec<u8>],
255     known_valid: KnownValid,
256     config: &generators::Config,
257     commands: &[Command],
258 ) {
259     log::debug!("instantiate_many: {commands:#?}");
260 
261     assert!(!config.module_config.config.allow_start_export);
262 
263     let engine = Engine::new(&config.to_wasmtime()).unwrap();
264 
265     let modules = modules
266         .iter()
267         .enumerate()
268         .filter_map(
269             |(i, bytes)| match compile_module(&engine, bytes, known_valid, config) {
270                 Some(m) => {
271                     log::debug!("successfully compiled module {i}");
272                     Some(m)
273                 }
274                 None => {
275                     log::debug!("failed to compile module {i}");
276                     None
277                 }
278             },
279         )
280         .collect::<Vec<_>>();
281 
282     // If no modules were valid, we're done
283     if modules.is_empty() {
284         return;
285     }
286 
287     // This stores every `Store` where a successful instantiation takes place
288     let mut stores = Vec::new();
289     let limits = StoreLimits::new();
290 
291     for command in commands {
292         match command {
293             Command::Instantiate(index) => {
294                 let index = *index % modules.len();
295                 log::info!("instantiating {index}");
296                 let module = &modules[index];
297                 let mut store = Store::new(&engine, limits.clone());
298                 config.configure_store(&mut store);
299 
300                 if instantiate_with_dummy(&mut store, module).is_some() {
301                     stores.push(Some(store));
302                 } else {
303                     log::warn!("instantiation failed");
304                 }
305             }
306             Command::Terminate(index) => {
307                 if stores.is_empty() {
308                     continue;
309                 }
310                 let index = *index % stores.len();
311 
312                 log::info!("dropping {index}");
313                 stores.swap_remove(index);
314             }
315         }
316     }
317 }
318 
319 fn compile_module(
320     engine: &Engine,
321     bytes: &[u8],
322     known_valid: KnownValid,
323     config: &generators::Config,
324 ) -> Option<Module> {
325     log_wasm(bytes);
326 
327     match config.compile(engine, bytes) {
328         Ok(module) => Some(module),
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: wasmtime::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 ) -> wasmtime::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     fuzz_config.module_config.shared_memory = true;
708     let test: generators::WastTest = u.arbitrary()?;
709 
710     let test = &test.test;
711 
712     if test.config.component_model_async() || u.arbitrary()? {
713         fuzz_config.enable_async(u)?;
714     }
715 
716     // Discard tests that allocate a lot of memory as we don't want to OOM the
717     // fuzzer and we also limit memory growth which would cause the test to
718     // fail.
719     if test.config.hogs_memory.unwrap_or(false) {
720         return Err(arbitrary::Error::IncorrectFormat);
721     }
722 
723     // Transform `fuzz_config` to be valid for `test` and make sure that this
724     // test is supposed to pass.
725     let wast_config = fuzz_config.make_wast_test_compliant(test);
726     if test.should_fail(&wast_config) {
727         return Err(arbitrary::Error::IncorrectFormat);
728     }
729 
730     // Winch requires AVX and AVX2 for SIMD tests to pass so don't run the test
731     // if either isn't enabled.
732     if fuzz_config.wasmtime.compiler_strategy == CompilerStrategy::Winch
733         && test.config.simd()
734         && (fuzz_config
735             .wasmtime
736             .codegen_flag("has_avx")
737             .is_some_and(|value| value == "false")
738             || fuzz_config
739                 .wasmtime
740                 .codegen_flag("has_avx2")
741                 .is_some_and(|value| value == "false"))
742     {
743         log::warn!(
744             "Skipping Wast test because Winch doesn't support SIMD tests with AVX or AVX2 disabled"
745         );
746         return Err(arbitrary::Error::IncorrectFormat);
747     }
748 
749     // Fuel and epochs don't play well with threads right now, so exclude any
750     // thread-spawning test if it looks like threads are spawned in that case.
751     if fuzz_config.wasmtime.consume_fuel || fuzz_config.wasmtime.epoch_interruption {
752         if test.contents.contains("(thread") {
753             return Err(arbitrary::Error::IncorrectFormat);
754         }
755     }
756 
757     log::debug!("running {:?}", test.path);
758     let async_ = if fuzz_config.wasmtime.async_config == generators::AsyncConfig::Disabled {
759         wasmtime_wast::Async::No
760     } else {
761         wasmtime_wast::Async::Yes
762     };
763     log::debug!("async: {async_:?}");
764     let engine = Engine::new(&fuzz_config.to_wasmtime()).unwrap();
765     let mut wast_context = WastContext::new(&engine, async_, move |store| {
766         fuzz_config.configure_store_epoch_and_fuel(store);
767     });
768     wast_context
769         .register_spectest(&wasmtime_wast::SpectestConfig {
770             use_shared_memory: true,
771             suppress_prints: true,
772         })
773         .unwrap();
774     wast_context
775         .run_wast(test.path.to_str().unwrap(), test.contents.as_bytes())
776         .unwrap();
777     Ok(())
778 }
779 
780 /// Execute a series of `gc` operations.
781 ///
782 /// Returns the number of `gc` operations which occurred throughout the test
783 /// case -- used to test below that gc happens reasonably soon and eventually.
784 pub fn gc_ops(mut fuzz_config: generators::Config, mut ops: GcOps) -> Result<usize> {
785     let expected_drops = Arc::new(AtomicUsize::new(0));
786     let num_dropped = Arc::new(AtomicUsize::new(0));
787 
788     let num_gcs = Arc::new(AtomicUsize::new(0));
789     {
790         fuzz_config.wasmtime.consume_fuel = true;
791         let mut store = fuzz_config.to_store();
792         store.set_fuel(1_000).unwrap();
793 
794         let wasm = ops.to_wasm_binary();
795         log_wasm(&wasm);
796         let module = match compile_module(store.engine(), &wasm, KnownValid::No, &fuzz_config) {
797             Some(m) => m,
798             None => return Ok(0),
799         };
800 
801         let mut linker = Linker::new(store.engine());
802 
803         // To avoid timeouts, limit the number of explicit GCs we perform per
804         // test case.
805         const MAX_GCS: usize = 5;
806 
807         let func_ty = FuncType::new(
808             store.engine(),
809             vec![],
810             vec![ValType::EXTERNREF, ValType::EXTERNREF, ValType::EXTERNREF],
811         );
812         let func = Func::new(&mut store, func_ty, {
813             let num_dropped = num_dropped.clone();
814             let expected_drops = expected_drops.clone();
815             let num_gcs = num_gcs.clone();
816             move |mut caller: Caller<'_, StoreLimits>, _params, results| {
817                 log::info!("gc_ops: GC");
818                 if num_gcs.fetch_add(1, SeqCst) < MAX_GCS {
819                     caller.gc(None)?;
820                 }
821 
822                 let a = ExternRef::new(
823                     &mut caller,
824                     CountDrops::new(&expected_drops, num_dropped.clone()),
825                 )?;
826                 let b = ExternRef::new(
827                     &mut caller,
828                     CountDrops::new(&expected_drops, num_dropped.clone()),
829                 )?;
830                 let c = ExternRef::new(
831                     &mut caller,
832                     CountDrops::new(&expected_drops, num_dropped.clone()),
833                 )?;
834 
835                 log::info!("gc_ops: gc() -> ({a:?}, {b:?}, {c:?})");
836                 results[0] = Some(a).into();
837                 results[1] = Some(b).into();
838                 results[2] = Some(c).into();
839                 Ok(())
840             }
841         });
842         linker.define(&store, "", "gc", func).unwrap();
843 
844         linker
845             .func_wrap("", "take_refs", {
846                 let expected_drops = expected_drops.clone();
847                 move |caller: Caller<'_, StoreLimits>,
848                       a: Option<Rooted<ExternRef>>,
849                       b: Option<Rooted<ExternRef>>,
850                       c: Option<Rooted<ExternRef>>|
851                       -> Result<()> {
852                     log::info!("gc_ops: take_refs({a:?}, {b:?}, {c:?})",);
853 
854                     // Do the assertion on each ref's inner data, even though it
855                     // all points to the same atomic, so that if we happen to
856                     // run into a use-after-free bug with one of these refs we
857                     // are more likely to trigger a segfault.
858                     if let Some(a) = a {
859                         let a = a
860                             .data(&caller)?
861                             .unwrap()
862                             .downcast_ref::<CountDrops>()
863                             .unwrap();
864                         assert!(a.0.load(SeqCst) <= expected_drops.load(SeqCst));
865                     }
866                     if let Some(b) = b {
867                         let b = b
868                             .data(&caller)?
869                             .unwrap()
870                             .downcast_ref::<CountDrops>()
871                             .unwrap();
872                         assert!(b.0.load(SeqCst) <= expected_drops.load(SeqCst));
873                     }
874                     if let Some(c) = c {
875                         let c = c
876                             .data(&caller)?
877                             .unwrap()
878                             .downcast_ref::<CountDrops>()
879                             .unwrap();
880                         assert!(c.0.load(SeqCst) <= expected_drops.load(SeqCst));
881                     }
882                     Ok(())
883                 }
884             })
885             .unwrap();
886 
887         let func_ty = FuncType::new(
888             store.engine(),
889             vec![],
890             vec![ValType::EXTERNREF, ValType::EXTERNREF, ValType::EXTERNREF],
891         );
892         let func = Func::new(&mut store, func_ty, {
893             let num_dropped = num_dropped.clone();
894             let expected_drops = expected_drops.clone();
895             move |mut caller, _params, results| {
896                 log::info!("gc_ops: make_refs");
897 
898                 let a = ExternRef::new(
899                     &mut caller,
900                     CountDrops::new(&expected_drops, num_dropped.clone()),
901                 )?;
902                 let b = ExternRef::new(
903                     &mut caller,
904                     CountDrops::new(&expected_drops, num_dropped.clone()),
905                 )?;
906                 let c = ExternRef::new(
907                     &mut caller,
908                     CountDrops::new(&expected_drops, num_dropped.clone()),
909                 )?;
910 
911                 log::info!("gc_ops: make_refs() -> ({a:?}, {b:?}, {c:?})");
912 
913                 results[0] = Some(a).into();
914                 results[1] = Some(b).into();
915                 results[2] = Some(c).into();
916 
917                 Ok(())
918             }
919         });
920         linker.define(&store, "", "make_refs", func).unwrap();
921 
922         let func_ty = FuncType::new(
923             store.engine(),
924             vec![ValType::Ref(RefType::new(true, HeapType::Struct))],
925             vec![],
926         );
927 
928         let func = Func::new(&mut store, func_ty, {
929             move |_caller: Caller<'_, StoreLimits>, _params, _results| {
930                 log::info!("gc_ops: take_struct(<ref null struct>)");
931                 Ok(())
932             }
933         });
934 
935         linker.define(&store, "", "take_struct", func).unwrap();
936 
937         for imp in module.imports() {
938             if imp.module() == "" {
939                 let name = imp.name();
940                 if name.starts_with("take_struct_") {
941                     if let wasmtime::ExternType::Func(ft) = imp.ty() {
942                         let imp_name = name.to_string();
943                         let func =
944                             Func::new(&mut store, ft.clone(), move |_caller, _params, _results| {
945                                 log::info!("gc_ops: {imp_name}(<typed structref>)");
946                                 Ok(())
947                             });
948                         linker.define(&store, "", name, func).unwrap();
949                     }
950                 }
951             }
952         }
953 
954         let instance = linker.instantiate(&mut store, &module).unwrap();
955         let run = instance.get_func(&mut store, "run").unwrap();
956 
957         {
958             let mut scope = RootScope::new(&mut store);
959 
960             log::info!(
961                 "gc_ops: begin allocating {} externref arguments",
962                 ops.limits.num_globals
963             );
964             let args: Vec<_> = (0..ops.limits.num_params)
965                 .map(|_| {
966                     Ok(Val::ExternRef(Some(ExternRef::new(
967                         &mut scope,
968                         CountDrops::new(&expected_drops, num_dropped.clone()),
969                     )?)))
970                 })
971                 .collect::<Result<_>>()?;
972             log::info!(
973                 "gc_ops: end allocating {} externref arguments",
974                 ops.limits.num_globals
975             );
976 
977             // The generated function should always return a trap. The only two
978             // valid traps are table-out-of-bounds which happens through `table.get`
979             // and `table.set` generated or an out-of-fuel trap. Otherwise any other
980             // error is unexpected and should fail fuzzing.
981             log::info!("gc_ops: calling into Wasm `run` function");
982             let err = run.call(&mut scope, &args, &mut []).unwrap_err();
983             if err.is::<GcHeapOutOfMemory<CountDrops>>() || err.is::<GcHeapOutOfMemory<()>>() {
984                 // Accept GC OOM as an allowed outcome for this fuzzer.
985             } else {
986                 let trap = err
987                     .downcast::<Trap>()
988                     .expect("if not GC oom, error should be a Wasm trap");
989                 match trap {
990                     Trap::TableOutOfBounds | Trap::OutOfFuel | Trap::AllocationTooLarge => {}
991                     _ => panic!("unexpected trap: {trap}"),
992                 }
993             }
994         }
995 
996         // Do a final GC after running the Wasm.
997         store.gc(None)?;
998     }
999 
1000     assert_eq!(num_dropped.load(SeqCst), expected_drops.load(SeqCst));
1001     return Ok(num_gcs.load(SeqCst));
1002 
1003     struct CountDrops(Arc<AtomicUsize>);
1004 
1005     impl CountDrops {
1006         fn new(expected_drops: &AtomicUsize, num_dropped: Arc<AtomicUsize>) -> Self {
1007             let expected = expected_drops.fetch_add(1, SeqCst);
1008             log::info!(
1009                 "CountDrops::new: expected drops: {expected} -> {}",
1010                 expected + 1
1011             );
1012             Self(num_dropped)
1013         }
1014     }
1015 
1016     impl Drop for CountDrops {
1017         fn drop(&mut self) {
1018             let drops = self.0.fetch_add(1, SeqCst);
1019             log::info!("CountDrops::drop: actual drops: {drops} -> {}", drops + 1);
1020         }
1021     }
1022 }
1023 
1024 #[derive(Default)]
1025 struct HelperThread {
1026     state: Arc<HelperThreadState>,
1027     thread: Option<std::thread::JoinHandle<()>>,
1028 }
1029 
1030 #[derive(Default)]
1031 struct HelperThreadState {
1032     should_exit: Mutex<bool>,
1033     should_exit_cvar: Condvar,
1034 }
1035 
1036 impl HelperThread {
1037     fn run_periodically(&mut self, dur: Duration, mut closure: impl FnMut() + Send + 'static) {
1038         let state = self.state.clone();
1039         self.thread = Some(std::thread::spawn(move || {
1040             // Using our mutex/condvar we wait here for the first of `dur` to
1041             // pass or the `HelperThread` instance to get dropped.
1042             let mut should_exit = state.should_exit.lock().unwrap();
1043             while !*should_exit {
1044                 let (lock, result) = state
1045                     .should_exit_cvar
1046                     .wait_timeout(should_exit, dur)
1047                     .unwrap();
1048                 should_exit = lock;
1049                 // If we timed out for sure then there's no need to continue
1050                 // since we'll just abort on the next `checked_sub` anyway.
1051                 if result.timed_out() {
1052                     closure();
1053                 }
1054             }
1055         }));
1056     }
1057 }
1058 
1059 impl Drop for HelperThread {
1060     fn drop(&mut self) {
1061         let thread = match self.thread.take() {
1062             Some(thread) => thread,
1063             None => return,
1064         };
1065         // Signal our thread that it should exit and wake it up in case it's
1066         // sleeping.
1067         *self.state.should_exit.lock().unwrap() = true;
1068         self.state.should_exit_cvar.notify_one();
1069 
1070         // ... and then wait for the thread to exit to ensure we clean up
1071         // after ourselves.
1072         thread.join().unwrap();
1073     }
1074 }
1075 
1076 /// Instantiates a wasm module and runs its exports with dummy values, all in
1077 /// an async fashion.
1078 ///
1079 /// Attempts to stress yields in host functions to ensure that exiting and
1080 /// resuming a wasm function call works.
1081 pub fn call_async(wasm: &[u8], config: &generators::Config, mut poll_amts: &[u32]) {
1082     let mut store = config.to_store();
1083     let module = match compile_module(store.engine(), wasm, KnownValid::Yes, config) {
1084         Some(module) => module,
1085         None => return,
1086     };
1087 
1088     // Configure a helper thread to periodically increment the epoch to
1089     // forcibly enable yields-via-epochs if epochs are in use. Note that this
1090     // is required because the wasm isn't otherwise guaranteed to necessarily
1091     // call any imports which will also increment the epoch.
1092     let mut helper_thread = HelperThread::default();
1093     if let generators::AsyncConfig::YieldWithEpochs { dur, .. } = &config.wasmtime.async_config {
1094         let engine = store.engine().clone();
1095         helper_thread.run_periodically(*dur, move || engine.increment_epoch());
1096     }
1097 
1098     // Generate a `Linker` where all function imports are custom-built to yield
1099     // periodically and additionally increment the epoch.
1100     let mut imports = Vec::new();
1101     for import in module.imports() {
1102         let item = match import.ty() {
1103             ExternType::Func(ty) => {
1104                 let poll_amt = take_poll_amt(&mut poll_amts);
1105                 Func::new_async(&mut store, ty.clone(), move |caller, _, results| {
1106                     let ty = ty.clone();
1107                     Box::new(async move {
1108                         caller.engine().increment_epoch();
1109                         log::info!("yielding {poll_amt} times in import");
1110                         YieldN(poll_amt).await;
1111                         for (ret_ty, result) in ty.results().zip(results) {
1112                             *result = ret_ty.default_value().unwrap();
1113                         }
1114                         Ok(())
1115                     })
1116                 })
1117                 .into()
1118             }
1119             other_ty => match other_ty.default_value(&mut store) {
1120                 Ok(item) => item,
1121                 Err(e) => {
1122                     log::warn!("couldn't create import for {import:?}: {e:?}");
1123                     return;
1124                 }
1125             },
1126         };
1127         imports.push(item);
1128     }
1129 
1130     // Run the instantiation process, asynchronously, and if everything
1131     // succeeds then pull out the instance.
1132     // log::info!("starting instantiation");
1133     let instance = block_on(Timeout {
1134         future: Instance::new_async(&mut store, &module, &imports),
1135         polls: take_poll_amt(&mut poll_amts),
1136         end: Instant::now() + Duration::from_millis(2_000),
1137     });
1138     let instance = match instance {
1139         Ok(instantiation_result) => match unwrap_instance(&store, instantiation_result) {
1140             Some(instance) => instance,
1141             None => {
1142                 log::info!("instantiation hit a nominal error");
1143                 return; // resource exhaustion or limits met
1144             }
1145         },
1146         Err(_) => {
1147             log::info!("instantiation failed to complete");
1148             return; // Timed out or ran out of polls
1149         }
1150     };
1151 
1152     // Run each export of the instance in the same manner as instantiation
1153     // above. Dummy values are passed in for argument values here:
1154     //
1155     // TODO: this should probably be more clever about passing in arguments for
1156     // example they might be used as pointers or something and always using 0
1157     // isn't too interesting.
1158     let funcs = instance
1159         .exports(&mut store)
1160         .filter_map(|e| {
1161             let name = e.name().to_string();
1162             let func = e.into_extern().into_func()?;
1163             Some((name, func))
1164         })
1165         .collect::<Vec<_>>();
1166     for (name, func) in funcs {
1167         let ty = func.ty(&store);
1168         let params = ty
1169             .params()
1170             .map(|ty| ty.default_value().unwrap())
1171             .collect::<Vec<_>>();
1172         let mut results = ty
1173             .results()
1174             .map(|ty| ty.default_value().unwrap())
1175             .collect::<Vec<_>>();
1176 
1177         log::info!("invoking export {name:?}");
1178         let future = func.call_async(&mut store, &params, &mut results);
1179         match block_on(Timeout {
1180             future,
1181             polls: take_poll_amt(&mut poll_amts),
1182             end: Instant::now() + Duration::from_millis(2_000),
1183         }) {
1184             // On success or too many polls, try the next export.
1185             Ok(_) | Err(Exhausted::Polls) => {}
1186 
1187             // If time ran out then stop the current test case as we might have
1188             // already sucked up a lot of time for this fuzz test case so don't
1189             // keep it going.
1190             Err(Exhausted::Time) => return,
1191         }
1192     }
1193 
1194     fn take_poll_amt(polls: &mut &[u32]) -> u32 {
1195         match polls.split_first() {
1196             Some((a, rest)) => {
1197                 *polls = rest;
1198                 *a
1199             }
1200             None => 0,
1201         }
1202     }
1203 
1204     /// Helper future for applying a timeout to `future` up to either when `end`
1205     /// is the current time or `polls` polls happen.
1206     ///
1207     /// Note that this helps to time out infinite loops in wasm, for example.
1208     struct Timeout<F> {
1209         future: F,
1210         /// If the future isn't ready by this time then the `Timeout<F>` future
1211         /// will return `None`.
1212         end: Instant,
1213         /// If the future doesn't resolve itself in this many calls to `poll`
1214         /// then the `Timeout<F>` future will return `None`.
1215         polls: u32,
1216     }
1217 
1218     enum Exhausted {
1219         Time,
1220         Polls,
1221     }
1222 
1223     impl<F: Future> Future for Timeout<F> {
1224         type Output = Result<F::Output, Exhausted>;
1225 
1226         fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
1227             let (end, polls, future) = unsafe {
1228                 let me = self.get_unchecked_mut();
1229                 (me.end, &mut me.polls, Pin::new_unchecked(&mut me.future))
1230             };
1231             match future.poll(cx) {
1232                 Poll::Ready(val) => Poll::Ready(Ok(val)),
1233                 Poll::Pending => {
1234                     if Instant::now() >= end {
1235                         log::warn!("future operation timed out");
1236                         return Poll::Ready(Err(Exhausted::Time));
1237                     }
1238                     if *polls == 0 {
1239                         log::warn!("future operation ran out of polls");
1240                         return Poll::Ready(Err(Exhausted::Polls));
1241                     }
1242                     *polls -= 1;
1243                     Poll::Pending
1244                 }
1245             }
1246         }
1247     }
1248 }
1249 
1250 #[cfg(test)]
1251 mod tests {
1252     use super::*;
1253     use crate::test::{gen_until_pass, test_n_times};
1254     use wasmparser::{Validator, WasmFeatures};
1255 
1256     // Test that the `gc_ops` fuzzer eventually runs the gc function in the host.
1257     // We've historically had issues where this fuzzer accidentally wasn't fuzzing
1258     // anything for a long time so this is an attempt to prevent that from happening
1259     // again.
1260     #[test]
1261     fn gc_ops_eventually_gcs() {
1262         // Skip if we're under emulation because some fuzz configurations will do
1263         // large address space reservations that QEMU doesn't handle well.
1264         if std::env::var("WASMTIME_TEST_NO_HOG_MEMORY").is_ok() {
1265             return;
1266         }
1267 
1268         let ok = gen_until_pass(|(config, test), _| {
1269             let result = gc_ops(config, test)?;
1270             Ok(result > 0)
1271         });
1272 
1273         if !ok {
1274             panic!("gc was never found");
1275         }
1276     }
1277 
1278     #[test]
1279     fn module_generation_uses_expected_proposals() {
1280         // Proposals that Wasmtime supports. Eventually a module should be
1281         // generated that needs these proposals.
1282         let mut expected = WasmFeatures::MUTABLE_GLOBAL
1283             | WasmFeatures::FLOATS
1284             | WasmFeatures::SIGN_EXTENSION
1285             | WasmFeatures::SATURATING_FLOAT_TO_INT
1286             | WasmFeatures::MULTI_VALUE
1287             | WasmFeatures::BULK_MEMORY
1288             | WasmFeatures::REFERENCE_TYPES
1289             | WasmFeatures::SIMD
1290             | WasmFeatures::MULTI_MEMORY
1291             | WasmFeatures::RELAXED_SIMD
1292             | WasmFeatures::TAIL_CALL
1293             | WasmFeatures::WIDE_ARITHMETIC
1294             | WasmFeatures::MEMORY64
1295             | WasmFeatures::FUNCTION_REFERENCES
1296             | WasmFeatures::GC
1297             | WasmFeatures::GC_TYPES
1298             | WasmFeatures::CUSTOM_PAGE_SIZES
1299             | WasmFeatures::EXTENDED_CONST
1300             | WasmFeatures::EXCEPTIONS;
1301 
1302         // All other features that wasmparser supports, which is presumably a
1303         // superset of the features that wasm-smith supports, are listed here as
1304         // unexpected. This means, for example, that if wasm-smith updates to
1305         // include a new proposal by default that wasmtime implements then it
1306         // will be required to be listed above.
1307         let unexpected = WasmFeatures::all() ^ expected;
1308 
1309         let ok = gen_until_pass(|config: generators::Config, u| {
1310             let wasm = config.generate(u, None)?.to_bytes();
1311 
1312             // Double-check the module is valid
1313             Validator::new_with_features(WasmFeatures::all()).validate_all(&wasm)?;
1314 
1315             // If any of the unexpected features are removed then this module
1316             // should always be valid, otherwise something went wrong.
1317             for feature in unexpected.iter() {
1318                 let ok =
1319                     Validator::new_with_features(WasmFeatures::all() ^ feature).validate_all(&wasm);
1320                 if ok.is_err() {
1321                     wasmtime::bail!("generated a module with {feature:?} but that wasn't expected");
1322                 }
1323             }
1324 
1325             // If any of `expected` is removed and the module fails to validate,
1326             // then that means the module requires that feature. Remove that
1327             // from the set of features we're then expecting.
1328             for feature in expected.iter() {
1329                 let ok =
1330                     Validator::new_with_features(WasmFeatures::all() ^ feature).validate_all(&wasm);
1331                 if ok.is_err() {
1332                     expected ^= feature;
1333                 }
1334             }
1335 
1336             Ok(expected.is_empty())
1337         });
1338 
1339         if !ok {
1340             panic!("never generated wasm module using {expected:?}");
1341         }
1342     }
1343 
1344     #[test]
1345     fn wast_smoke_test() {
1346         test_n_times(50, |(), u| super::wast_test(u));
1347     }
1348 }
1349