158ba0667SNick Fitzgerald //! Oracles.
258ba0667SNick Fitzgerald //!
358ba0667SNick Fitzgerald //! Oracles take a test case and determine whether we have a bug. For example,
458ba0667SNick Fitzgerald //! one of the simplest oracles is to take a Wasm binary as our input test case,
558ba0667SNick Fitzgerald //! validate and instantiate it, and (implicitly) check that no assertions
658ba0667SNick Fitzgerald //! failed or segfaults happened. A more complicated oracle might compare the
758ba0667SNick Fitzgerald //! result of executing a Wasm file with and without optimizations enabled, and
858ba0667SNick Fitzgerald //! make sure that the two executions are observably identical.
958ba0667SNick Fitzgerald //!
1058ba0667SNick Fitzgerald //! When an oracle finds a bug, it should report it to the fuzzing engine by
1158ba0667SNick Fitzgerald //! panicking.
1258ba0667SNick Fitzgerald
135730c760SAlex Crichton pub mod component_api;
14fee9be21SAlex Crichton pub mod component_async;
155ec92d59SAndrew Brown #[cfg(feature = "fuzz-spec-interpreter")]
165ec92d59SAndrew Brown pub mod diff_spec;
175ec92d59SAndrew Brown pub mod diff_wasmi;
185ec92d59SAndrew Brown pub mod diff_wasmtime;
195429a939SNick Fitzgerald pub mod dummy;
205ec92d59SAndrew Brown pub mod engine;
217a37e313SNick Fitzgerald pub mod memory;
2246782b18SNick Fitzgerald mod stacks;
235429a939SNick Fitzgerald
245ec92d59SAndrew Brown use self::diff_wasmtime::WasmtimeInstance;
2510dbb199SAlex Crichton use self::engine::{DiffEngine, DiffInstance};
2646780983SChris Fallin use crate::generators::ExceptionOps;
27b6f59f05SKhagan (Khan) Karimov use crate::generators::GcOps;
284d75ebd1SJeffrey Charles use crate::generators::{self, CompilerStrategy, DiffValue, DiffValueType};
2904c03b31SAlex Crichton use crate::single_module_fuzzer::KnownValid;
30fee9be21SAlex Crichton use crate::{YieldN, block_on};
3141eb2257SPeter Huene use arbitrary::Arbitrary;
3246782b18SNick Fitzgerald pub use stacks::check_stacks;
33b4ecea38SAlex Crichton use std::future::Future;
34b4ecea38SAlex Crichton use std::pin::Pin;
35405e5295SAlex Crichton use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering::SeqCst};
36e09b9400SAlex Crichton use std::sync::{Arc, Condvar, Mutex};
370b9ff9bfSAlex Crichton use std::task::{Context, Poll};
38e09b9400SAlex Crichton use std::time::{Duration, Instant};
390cde3019SNick Fitzgerald use wasmtime::*;
406dde2229SAlex Crichton use wasmtime_wast::WastContext;
4158ba0667SNick Fitzgerald
42cdecc858Syuyang-ok #[cfg(not(any(windows, target_arch = "s390x", target_arch = "riscv64")))]
43fd98814bSAlex Crichton mod diff_v8;
444376cf26SAlex Crichton
45dfef71eaSAlex Crichton static CNT: AtomicUsize = AtomicUsize::new(0);
4698e899f6SNick Fitzgerald
47ab1d845aSAlex Crichton /// Logs a wasm file to the filesystem to make it easy to figure out what wasm
48ab1d845aSAlex Crichton /// was used when debugging.
log_wasm(wasm: &[u8])49ab1d845aSAlex Crichton pub fn log_wasm(wasm: &[u8]) {
50ab1d845aSAlex Crichton super::init_fuzzing();
51ab1d845aSAlex Crichton
52dfef71eaSAlex Crichton if !log::log_enabled!(log::Level::Debug) {
53dfef71eaSAlex Crichton return;
54dfef71eaSAlex Crichton }
55dfef71eaSAlex Crichton
56dfef71eaSAlex Crichton let i = CNT.fetch_add(1, SeqCst);
57a0442ea0SHamir Mahal let name = format!("testcase{i}.wasm");
58dfef71eaSAlex Crichton std::fs::write(&name, wasm).expect("failed to write wasm file");
592bac6574SAlex Crichton log::debug!("wrote wasm file to `{name}`");
60a0442ea0SHamir Mahal let wat = format!("testcase{i}.wat");
61516a97b3SAlex Crichton match wasmprinter::print_bytes(wasm) {
6206be7808SNick Fitzgerald Ok(s) => {
6306be7808SNick Fitzgerald std::fs::write(&wat, s).expect("failed to write wat file");
6406be7808SNick Fitzgerald log::debug!("wrote wat file to `{wat}`");
6506be7808SNick Fitzgerald }
66516a97b3SAlex Crichton // If wasmprinter failed remove a `*.wat` file, if any, to avoid
67516a97b3SAlex Crichton // confusing a preexisting one with this wasm which failed to get
68516a97b3SAlex Crichton // printed.
690b9ff9bfSAlex Crichton Err(e) => {
700b9ff9bfSAlex Crichton log::debug!("failed to print to wat: {e}");
7106be7808SNick Fitzgerald drop(std::fs::remove_file(&wat));
720b9ff9bfSAlex Crichton }
73dfef71eaSAlex Crichton }
74dfef71eaSAlex Crichton }
75dfef71eaSAlex Crichton
76ab1d845aSAlex Crichton /// The `T` in `Store<T>` for fuzzing stores, used to limit resource
77ab1d845aSAlex Crichton /// consumption during fuzzing.
78f425eb7eSAlex Crichton #[derive(Clone)]
79405e5295SAlex Crichton pub struct StoreLimits(Arc<LimitsState>);
80f425eb7eSAlex Crichton
81f425eb7eSAlex Crichton struct LimitsState {
82214c5f86SAlex Crichton /// Remaining memory, in bytes, left to allocate
83405e5295SAlex Crichton remaining_memory: AtomicUsize,
84bf1b863cSAlex Crichton /// Remaining amount of memory that's allowed to be copied via a growth.
85bf1b863cSAlex Crichton remaining_copy_allowance: AtomicUsize,
86214c5f86SAlex Crichton /// Whether or not an allocation request has been denied
87405e5295SAlex Crichton oom: AtomicBool,
88214c5f86SAlex Crichton }
89214c5f86SAlex Crichton
90bf1b863cSAlex Crichton /// Allow up to 1G which is well below the 2G limit on OSS-Fuzz and should allow
91bf1b863cSAlex Crichton /// most interesting behavior.
92bf1b863cSAlex Crichton const MAX_MEMORY: usize = 1 << 30;
93bf1b863cSAlex Crichton
94bf1b863cSAlex Crichton /// Allow up to 4G of bytes to be copied (conservatively) which should enable
95bf1b863cSAlex Crichton /// growth up to `MAX_MEMORY` or at least up to a relatively large amount.
96bf1b863cSAlex Crichton const MAX_MEMORY_MOVED: usize = 4 << 30;
97bf1b863cSAlex Crichton
98214c5f86SAlex Crichton impl StoreLimits {
99ab1d845aSAlex Crichton /// Creates the default set of limits for all fuzzing stores.
new() -> StoreLimits100ab1d845aSAlex Crichton pub fn new() -> StoreLimits {
101405e5295SAlex Crichton StoreLimits(Arc::new(LimitsState {
102bf1b863cSAlex Crichton remaining_memory: AtomicUsize::new(MAX_MEMORY),
103bf1b863cSAlex Crichton remaining_copy_allowance: AtomicUsize::new(MAX_MEMORY_MOVED),
104405e5295SAlex Crichton oom: AtomicBool::new(false),
105f425eb7eSAlex Crichton }))
106ab1d845aSAlex Crichton }
107ab1d845aSAlex Crichton
alloc(&mut self, amt: usize) -> bool108214c5f86SAlex Crichton fn alloc(&mut self, amt: usize) -> bool {
1094b703f9dSAlex Crichton log::trace!("alloc {amt:#x} bytes");
110bf1b863cSAlex Crichton
111bf1b863cSAlex Crichton // Assume that on each allocation of memory that all previous
112bf1b863cSAlex Crichton // allocations of memory are moved. This is pretty coarse but is used to
113bf1b863cSAlex Crichton // help prevent against fuzz test cases that just move tons of bytes
114bf1b863cSAlex Crichton // around continuously. This assumes that all previous memory was
115bf1b863cSAlex Crichton // allocated in a single linear memory and growing by `amt` will require
116bf1b863cSAlex Crichton // moving all the bytes to a new location. This isn't actually required
117bf1b863cSAlex Crichton // all the time nor does it accurately reflect what happens all the
118bf1b863cSAlex Crichton // time, but it's a coarse approximation that should be "good enough"
119bf1b863cSAlex Crichton // for allowing interesting fuzz behaviors to happen while not timing
120bf1b863cSAlex Crichton // out just copying bytes around.
121bf1b863cSAlex Crichton let prev_size = MAX_MEMORY - self.0.remaining_memory.load(SeqCst);
1228d320088SAlex Crichton if self
1238d320088SAlex Crichton .0
124bf1b863cSAlex Crichton .remaining_copy_allowance
125bf1b863cSAlex Crichton .fetch_update(SeqCst, SeqCst, |remaining| remaining.checked_sub(prev_size))
1268d320088SAlex Crichton .is_err()
1278d320088SAlex Crichton {
1288d320088SAlex Crichton self.0.oom.store(true, SeqCst);
129bf1b863cSAlex Crichton log::debug!("-> too many bytes moved, rejecting allocation");
1308d320088SAlex Crichton return false;
1318d320088SAlex Crichton }
132bf1b863cSAlex Crichton
133bf1b863cSAlex Crichton // If we're allowed to move the bytes, then also check if we're allowed
134bf1b863cSAlex Crichton // to actually have this much residence at once.
135405e5295SAlex Crichton match self
136405e5295SAlex Crichton .0
137405e5295SAlex Crichton .remaining_memory
138405e5295SAlex Crichton .fetch_update(SeqCst, SeqCst, |remaining| remaining.checked_sub(amt))
139405e5295SAlex Crichton {
140405e5295SAlex Crichton Ok(_) => true,
141405e5295SAlex Crichton Err(_) => {
142405e5295SAlex Crichton self.0.oom.store(true, SeqCst);
143bf1b863cSAlex Crichton log::debug!("-> OOM hit");
144214c5f86SAlex Crichton false
145214c5f86SAlex Crichton }
146214c5f86SAlex Crichton }
147214c5f86SAlex Crichton }
1484b703f9dSAlex Crichton
is_oom(&self) -> bool1494b703f9dSAlex Crichton fn is_oom(&self) -> bool {
150405e5295SAlex Crichton self.0.oom.load(SeqCst)
1514b703f9dSAlex Crichton }
152214c5f86SAlex Crichton }
153214c5f86SAlex Crichton
154214c5f86SAlex Crichton impl ResourceLimiter for StoreLimits {
memory_growing( &mut self, current: usize, desired: usize, _maximum: Option<usize>, ) -> Result<bool>15552e90532SAlex Crichton fn memory_growing(
15652e90532SAlex Crichton &mut self,
15752e90532SAlex Crichton current: usize,
15852e90532SAlex Crichton desired: usize,
15952e90532SAlex Crichton _maximum: Option<usize>,
16052e90532SAlex Crichton ) -> Result<bool> {
16152e90532SAlex Crichton Ok(self.alloc(desired - current))
162214c5f86SAlex Crichton }
163214c5f86SAlex Crichton
table_growing( &mut self, current: usize, desired: usize, _maximum: Option<usize>, ) -> Result<bool>164df69b9a7SLinwei Shang fn table_growing(
165df69b9a7SLinwei Shang &mut self,
166df69b9a7SLinwei Shang current: usize,
167df69b9a7SLinwei Shang desired: usize,
168df69b9a7SLinwei Shang _maximum: Option<usize>,
169df69b9a7SLinwei Shang ) -> Result<bool> {
170a17e5a19SAlex Crichton let delta = (desired - current).saturating_mul(std::mem::size_of::<usize>());
17152e90532SAlex Crichton Ok(self.alloc(delta))
172214c5f86SAlex Crichton }
173f12b4c46SPeter Huene }
174f12b4c46SPeter Huene
1750e418616SAlex Crichton /// Methods of timing out execution of a WebAssembly module
1764e26c13bSChris Fallin #[derive(Clone, Debug)]
1770e418616SAlex Crichton pub enum Timeout {
1780e418616SAlex Crichton /// No timeout is used, it should be guaranteed via some other means that
1790e418616SAlex Crichton /// the input does not infinite loop.
1800e418616SAlex Crichton None,
1810e418616SAlex Crichton /// Fuel-based timeouts are used where the specified fuel is all that the
1820e418616SAlex Crichton /// provided wasm module is allowed to consume.
1830e418616SAlex Crichton Fuel(u64),
1844e26c13bSChris Fallin /// An epoch-interruption-based timeout is used with a sleeping
1854e26c13bSChris Fallin /// thread bumping the epoch counter after the specified duration.
1864e26c13bSChris Fallin Epoch(Duration),
1870e418616SAlex Crichton }
1880e418616SAlex Crichton
18958ba0667SNick Fitzgerald /// Instantiate the Wasm buffer, and implicitly fail if we have an unexpected
19058ba0667SNick Fitzgerald /// panic or segfault or anything else that can be detected "passively".
19158ba0667SNick Fitzgerald ///
192b3ac7184SYury Delendik /// The engine will be configured using provided config.
instantiate( wasm: &[u8], known_valid: KnownValid, config: &generators::Config, timeout: Timeout, )19304c03b31SAlex Crichton pub fn instantiate(
19404c03b31SAlex Crichton wasm: &[u8],
19504c03b31SAlex Crichton known_valid: KnownValid,
19604c03b31SAlex Crichton config: &generators::Config,
19704c03b31SAlex Crichton timeout: Timeout,
19804c03b31SAlex Crichton ) {
199ab1d845aSAlex Crichton let mut store = config.to_store();
2005429a939SNick Fitzgerald
2010d570883SAlex Crichton let module = match compile_module(store.engine(), wasm, known_valid, config) {
2020d570883SAlex Crichton Some(module) => module,
2030d570883SAlex Crichton None => return,
2040d570883SAlex Crichton };
2050d570883SAlex Crichton
206b4ecea38SAlex Crichton let mut timeout_state = HelperThread::default();
2070e418616SAlex Crichton match timeout {
20885c0a2dfSTyler Rockwood Timeout::Fuel(fuel) => store.set_fuel(fuel).unwrap(),
20908a60a0fSAlex Crichton
2100e418616SAlex Crichton // If a timeout is requested then we spawn a helper thread to wait for
2110e418616SAlex Crichton // the requested time and then send us a signal to get interrupted. We
2120e418616SAlex Crichton // also arrange for the thread's sleep to get interrupted if we return
2130e418616SAlex Crichton // early (or the wasm returns within the time limit), which allows the
2140e418616SAlex Crichton // thread to get torn down.
2150e418616SAlex Crichton //
2160e418616SAlex Crichton // This prevents us from creating a huge number of sleeping threads if
2170e418616SAlex Crichton // this function is executed in a loop, like it does on nightly fuzzing
2180e418616SAlex Crichton // infrastructure.
2194e26c13bSChris Fallin Timeout::Epoch(timeout) => {
2204e26c13bSChris Fallin let engine = store.engine().clone();
221b4ecea38SAlex Crichton timeout_state.run_periodically(timeout, move || engine.increment_epoch());
2224e26c13bSChris Fallin }
2230e418616SAlex Crichton Timeout::None => {}
2240e418616SAlex Crichton }
22538428e1fSAlex Crichton
2263bdf6c7aSAlex Crichton instantiate_with_dummy(&mut store, &module);
2271047c4e1SAlex Crichton }
22841eb2257SPeter Huene
22941eb2257SPeter Huene /// Represents supported commands to the `instantiate_many` function.
23041eb2257SPeter Huene #[derive(Arbitrary, Debug)]
23141eb2257SPeter Huene pub enum Command {
23241eb2257SPeter Huene /// Instantiates a module.
23341eb2257SPeter Huene ///
23441eb2257SPeter Huene /// The value is the index of the module to instantiate.
23541eb2257SPeter Huene ///
23641eb2257SPeter Huene /// The module instantiated will be this value modulo the number of modules provided to `instantiate_many`.
23741eb2257SPeter Huene Instantiate(usize),
23841eb2257SPeter Huene /// Terminates a "running" instance.
23941eb2257SPeter Huene ///
24041eb2257SPeter Huene /// The value is the index of the instance to terminate.
24141eb2257SPeter Huene ///
24241eb2257SPeter Huene /// The instance terminated will be this value modulo the number of currently running
24341eb2257SPeter Huene /// instances.
24441eb2257SPeter Huene ///
24541eb2257SPeter Huene /// If no instances are running, the command will be ignored.
24641eb2257SPeter Huene Terminate(usize),
24741eb2257SPeter Huene }
24841eb2257SPeter Huene
24941eb2257SPeter Huene /// Instantiates many instances from the given modules.
25041eb2257SPeter Huene ///
25141eb2257SPeter Huene /// The engine will be configured using the provided config.
25241eb2257SPeter Huene ///
25341eb2257SPeter Huene /// The modules are expected to *not* have start functions as no timeouts are configured.
instantiate_many( modules: &[Vec<u8>], known_valid: KnownValid, config: &generators::Config, commands: &[Command], )25441eb2257SPeter Huene pub fn instantiate_many(
25541eb2257SPeter Huene modules: &[Vec<u8>],
25604c03b31SAlex Crichton known_valid: KnownValid,
25741eb2257SPeter Huene config: &generators::Config,
25841eb2257SPeter Huene commands: &[Command],
25941eb2257SPeter Huene ) {
2604a729d7bSNick Fitzgerald log::debug!("instantiate_many: {commands:#?}");
2614a729d7bSNick Fitzgerald
26241eb2257SPeter Huene assert!(!config.module_config.config.allow_start_export);
26341eb2257SPeter Huene
26441eb2257SPeter Huene let engine = Engine::new(&config.to_wasmtime()).unwrap();
26541eb2257SPeter Huene
26641eb2257SPeter Huene let modules = modules
26741eb2257SPeter Huene .iter()
2684a729d7bSNick Fitzgerald .enumerate()
2694a729d7bSNick Fitzgerald .filter_map(
2704a729d7bSNick Fitzgerald |(i, bytes)| match compile_module(&engine, bytes, known_valid, config) {
2714a729d7bSNick Fitzgerald Some(m) => {
2724a729d7bSNick Fitzgerald log::debug!("successfully compiled module {i}");
2734a729d7bSNick Fitzgerald Some(m)
2744a729d7bSNick Fitzgerald }
2754a729d7bSNick Fitzgerald None => {
2764a729d7bSNick Fitzgerald log::debug!("failed to compile module {i}");
2774a729d7bSNick Fitzgerald None
2784a729d7bSNick Fitzgerald }
2794a729d7bSNick Fitzgerald },
2804a729d7bSNick Fitzgerald )
28141eb2257SPeter Huene .collect::<Vec<_>>();
28241eb2257SPeter Huene
28341eb2257SPeter Huene // If no modules were valid, we're done
28441eb2257SPeter Huene if modules.is_empty() {
28541eb2257SPeter Huene return;
28641eb2257SPeter Huene }
28741eb2257SPeter Huene
28841eb2257SPeter Huene // This stores every `Store` where a successful instantiation takes place
28941eb2257SPeter Huene let mut stores = Vec::new();
290f425eb7eSAlex Crichton let limits = StoreLimits::new();
29141eb2257SPeter Huene
29241eb2257SPeter Huene for command in commands {
29341eb2257SPeter Huene match command {
29441eb2257SPeter Huene Command::Instantiate(index) => {
295f425eb7eSAlex Crichton let index = *index % modules.len();
2962bac6574SAlex Crichton log::info!("instantiating {index}");
297f425eb7eSAlex Crichton let module = &modules[index];
298f425eb7eSAlex Crichton let mut store = Store::new(&engine, limits.clone());
29941eb2257SPeter Huene config.configure_store(&mut store);
30041eb2257SPeter Huene
30141eb2257SPeter Huene if instantiate_with_dummy(&mut store, module).is_some() {
30241eb2257SPeter Huene stores.push(Some(store));
303f425eb7eSAlex Crichton } else {
304f425eb7eSAlex Crichton log::warn!("instantiation failed");
30541eb2257SPeter Huene }
30641eb2257SPeter Huene }
30741eb2257SPeter Huene Command::Terminate(index) => {
30841eb2257SPeter Huene if stores.is_empty() {
30941eb2257SPeter Huene continue;
31041eb2257SPeter Huene }
311f425eb7eSAlex Crichton let index = *index % stores.len();
31241eb2257SPeter Huene
3132bac6574SAlex Crichton log::info!("dropping {index}");
314f425eb7eSAlex Crichton stores.swap_remove(index);
31541eb2257SPeter Huene }
31641eb2257SPeter Huene }
31741eb2257SPeter Huene }
31841eb2257SPeter Huene }
31941eb2257SPeter Huene
compile_module( engine: &Engine, bytes: &[u8], known_valid: KnownValid, config: &generators::Config, ) -> Option<Module>32041eb2257SPeter Huene fn compile_module(
32141eb2257SPeter Huene engine: &Engine,
32241eb2257SPeter Huene bytes: &[u8],
32304c03b31SAlex Crichton known_valid: KnownValid,
32441eb2257SPeter Huene config: &generators::Config,
32541eb2257SPeter Huene ) -> Option<Module> {
32641eb2257SPeter Huene log_wasm(bytes);
327acbbf342SChris Fallin
32841eb2257SPeter Huene match config.compile(engine, bytes) {
32941eb2257SPeter Huene Ok(module) => Some(module),
33004c03b31SAlex Crichton Err(_) if known_valid == KnownValid::No => None,
33141eb2257SPeter Huene Err(e) => {
3321a11e25cSAlex Crichton if let generators::InstanceAllocationStrategy::Pooling(c) = &config.wasmtime.strategy {
3335ec92d59SAndrew Brown // When using the pooling allocator, accept failures to compile
3345ec92d59SAndrew Brown // when arbitrary table element limits have been exceeded as
3355ec92d59SAndrew Brown // there is currently no way to constrain the generated module
3365ec92d59SAndrew Brown // table types.
337b91f504bSAlex Crichton let string = format!("{e:?}");
33841eb2257SPeter Huene if string.contains("minimum element size") {
33941eb2257SPeter Huene return None;
34041eb2257SPeter Huene }
3412f48c890SAlex Crichton
3422f48c890SAlex Crichton // Allow modules-failing-to-compile which exceed the requested
3432f48c890SAlex Crichton // size for each instance. This is something that is difficult
3445ec92d59SAndrew Brown // to control and ensure it always succeeds, so we simply have a
3452f48c890SAlex Crichton // "random" instance size limit and if a module doesn't fit we
3462f48c890SAlex Crichton // move on to the next fuzz input.
3472f48c890SAlex Crichton if string.contains("instance allocation for this module requires") {
3482f48c890SAlex Crichton return None;
3492f48c890SAlex Crichton }
3501a11e25cSAlex Crichton
3511a11e25cSAlex Crichton // If the pooling allocator is more restrictive on the number of
3521a11e25cSAlex Crichton // tables and memories than we allowed wasm-smith to generate
3531a11e25cSAlex Crichton // then allow compilation errors along those lines.
3541a11e25cSAlex Crichton if c.max_tables_per_module < (config.module_config.config.max_tables as u32)
3551a11e25cSAlex Crichton && string.contains("defined tables count")
3561a11e25cSAlex Crichton && string.contains("exceeds the per-instance limit")
3571a11e25cSAlex Crichton {
3581a11e25cSAlex Crichton return None;
3591a11e25cSAlex Crichton }
3601a11e25cSAlex Crichton
3611a11e25cSAlex Crichton if c.max_memories_per_module < (config.module_config.config.max_memories as u32)
3621a11e25cSAlex Crichton && string.contains("defined memories count")
3631a11e25cSAlex Crichton && string.contains("exceeds the per-instance limit")
3641a11e25cSAlex Crichton {
3651a11e25cSAlex Crichton return None;
3661a11e25cSAlex Crichton }
36741eb2257SPeter Huene }
36841eb2257SPeter Huene
369a0442ea0SHamir Mahal panic!("failed to compile module: {e:?}");
37041eb2257SPeter Huene }
37141eb2257SPeter Huene }
37241eb2257SPeter Huene }
3733bdf6c7aSAlex Crichton
3745ec92d59SAndrew Brown /// Create a Wasmtime [`Instance`] from a [`Module`] and fill in all imports
3755ec92d59SAndrew Brown /// with dummy values (e.g., zeroed values, immediately-trapping functions).
3765ec92d59SAndrew Brown /// Also, this function catches certain fuzz-related instantiation failures and
3775ec92d59SAndrew Brown /// returns `None` instead of panicking.
3785ec92d59SAndrew Brown ///
3795ec92d59SAndrew Brown /// TODO: we should implement tracing versions of these dummy imports that
3805ec92d59SAndrew Brown /// record a trace of the order that imported functions were called in and with
3815ec92d59SAndrew Brown /// what values. Like the results of exported functions, calls to imports should
3825ec92d59SAndrew Brown /// also yield the same values for each configuration, and we should assert
3835ec92d59SAndrew Brown /// that.
instantiate_with_dummy(store: &mut Store<StoreLimits>, module: &Module) -> Option<Instance>3845ec92d59SAndrew Brown pub fn instantiate_with_dummy(store: &mut Store<StoreLimits>, module: &Module) -> Option<Instance> {
3853bdf6c7aSAlex Crichton // Creation of imports can fail due to resource limit constraints, and then
3863bdf6c7aSAlex Crichton // instantiation can naturally fail for a number of reasons as well. Bundle
3873bdf6c7aSAlex Crichton // the two steps together to match on the error below.
3885b9e8765SNick Fitzgerald let linker = dummy::dummy_linker(store, module);
3895b9e8765SNick Fitzgerald if let Err(e) = &linker {
3905b9e8765SNick Fitzgerald log::warn!("failed to create dummy linker: {e:?}");
3915b9e8765SNick Fitzgerald }
3925b9e8765SNick Fitzgerald let instance = linker.and_then(|l| l.instantiate(&mut *store, module));
393b4ecea38SAlex Crichton unwrap_instance(store, instance)
394b4ecea38SAlex Crichton }
3953bdf6c7aSAlex Crichton
unwrap_instance( store: &Store<StoreLimits>, instance: wasmtime::Result<Instance>, ) -> Option<Instance>396b4ecea38SAlex Crichton fn unwrap_instance(
397b4ecea38SAlex Crichton store: &Store<StoreLimits>,
39893d22fcdSNick Fitzgerald instance: wasmtime::Result<Instance>,
399b4ecea38SAlex Crichton ) -> Option<Instance> {
4003bdf6c7aSAlex Crichton let e = match instance {
4013bdf6c7aSAlex Crichton Ok(i) => return Some(i),
4023bdf6c7aSAlex Crichton Err(e) => e,
4031047c4e1SAlex Crichton };
4045429a939SNick Fitzgerald
405406d00bbSNick Fitzgerald log::debug!("failed to instantiate: {e:?}");
406406d00bbSNick Fitzgerald
407214c5f86SAlex Crichton // If the instantiation hit OOM for some reason then that's ok, it's
408214c5f86SAlex Crichton // expected that fuzz-generated programs try to allocate lots of
409214c5f86SAlex Crichton // stuff.
4104b703f9dSAlex Crichton if store.data().is_oom() {
4113bdf6c7aSAlex Crichton return None;
412214c5f86SAlex Crichton }
413214c5f86SAlex Crichton
414cff811b5SNick Fitzgerald // Allow traps which can happen normally with `unreachable` or a timeout or
415cff811b5SNick Fitzgerald // such.
416cff811b5SNick Fitzgerald if e.is::<Trap>()
417cff811b5SNick Fitzgerald // Also allow failures to instantiate as a result of hitting pooling
418cff811b5SNick Fitzgerald // limits.
419cff811b5SNick Fitzgerald || e.is::<wasmtime::PoolConcurrencyLimitError>()
420cff811b5SNick Fitzgerald // And GC heap OOMs.
421cff811b5SNick Fitzgerald || e.is::<wasmtime::GcHeapOutOfMemory<()>>()
422ecda6e33SChris Fallin // And thrown exceptions.
423ecda6e33SChris Fallin || e.is::<wasmtime::ThrownException>()
424cff811b5SNick Fitzgerald {
4253bdf6c7aSAlex Crichton return None;
426214c5f86SAlex Crichton }
427214c5f86SAlex Crichton
428214c5f86SAlex Crichton let string = e.to_string();
429406d00bbSNick Fitzgerald
430550c774cSAlex Crichton // Currently we instantiate with a `Linker` which can't instantiate
431550c774cSAlex Crichton // every single module under the sun due to using name-based resolution
432550c774cSAlex Crichton // rather than positional-based resolution
4339b7c5e31SAlex Crichton if string.contains("incompatible import type") {
4343bdf6c7aSAlex Crichton return None;
435550c774cSAlex Crichton }
436550c774cSAlex Crichton
4373bdf6c7aSAlex Crichton // Everything else should be a bug in the fuzzer or a bug in wasmtime
438a0442ea0SHamir Mahal panic!("failed to instantiate: {e:?}");
439550c774cSAlex Crichton }
44058ba0667SNick Fitzgerald
4415ec92d59SAndrew Brown /// Evaluate the function identified by `name` in two different engine
4425ec92d59SAndrew Brown /// instances--`lhs` and `rhs`.
4435ec92d59SAndrew Brown ///
44410dbb199SAlex Crichton /// Returns `Ok(true)` if more evaluations can happen or `Ok(false)` if the
44510dbb199SAlex Crichton /// instances may have drifted apart and no more evaluations can happen.
44610dbb199SAlex Crichton ///
4475ec92d59SAndrew Brown /// # Panics
4485ec92d59SAndrew Brown ///
4495ec92d59SAndrew Brown /// This will panic if the evaluation is different between engines (e.g.,
4505ec92d59SAndrew Brown /// results are different, hashed instance is different, one side traps, etc.).
differential( lhs: &mut dyn DiffInstance, lhs_engine: &dyn DiffEngine, rhs: &mut WasmtimeInstance, name: &str, args: &[DiffValue], result_tys: &[DiffValueType], ) -> wasmtime::Result<bool>4515ec92d59SAndrew Brown pub fn differential(
4525ec92d59SAndrew Brown lhs: &mut dyn DiffInstance,
45310dbb199SAlex Crichton lhs_engine: &dyn DiffEngine,
4545ec92d59SAndrew Brown rhs: &mut WasmtimeInstance,
4555ec92d59SAndrew Brown name: &str,
4565ec92d59SAndrew Brown args: &[DiffValue],
457fd98814bSAlex Crichton result_tys: &[DiffValueType],
45893d22fcdSNick Fitzgerald ) -> wasmtime::Result<bool> {
4592bac6574SAlex Crichton log::debug!("Evaluating: `{name}` with {args:?}");
460fd98814bSAlex Crichton let lhs_results = match lhs.evaluate(name, args, result_tys) {
461fd98814bSAlex Crichton Ok(Some(results)) => Ok(results),
462fd98814bSAlex Crichton Err(e) => Err(e),
463fd98814bSAlex Crichton // this engine couldn't execute this type signature, so discard this
464fd98814bSAlex Crichton // execution by returning success.
46510dbb199SAlex Crichton Ok(None) => return Ok(true),
466fd98814bSAlex Crichton };
467b3b50943SAlex Crichton log::debug!(" -> lhs results on {}: {:?}", lhs.name(), &lhs_results);
468fd98814bSAlex Crichton
469fd98814bSAlex Crichton let rhs_results = rhs
470fd98814bSAlex Crichton .evaluate(name, args, result_tys)
471fd98814bSAlex Crichton // wasmtime should be able to invoke any signature, so unwrap this result
472fd98814bSAlex Crichton .map(|results| results.unwrap());
473b3b50943SAlex Crichton log::debug!(" -> rhs results on {}: {:?}", rhs.name(), &rhs_results);
474fd98814bSAlex Crichton
4754b703f9dSAlex Crichton // If Wasmtime hit its OOM condition, which is possible since it's set
4764b703f9dSAlex Crichton // somewhat low while fuzzing, then don't return an error but return
4774b703f9dSAlex Crichton // `false` indicating that differential fuzzing must stop. There's no
4784b703f9dSAlex Crichton // guarantee the other engine has the same OOM limits as Wasmtime, and
4794b703f9dSAlex Crichton // it's assumed that Wasmtime is configured to have a more conservative
4804b703f9dSAlex Crichton // limit than the other engine.
4814b703f9dSAlex Crichton if rhs.is_oom() {
4824b703f9dSAlex Crichton return Ok(false);
4834b703f9dSAlex Crichton }
4844b703f9dSAlex Crichton
485c2184a10SAlex Crichton match DiffEqResult::new(lhs_engine, lhs_results, rhs_results) {
486c2184a10SAlex Crichton DiffEqResult::Success(lhs, rhs) => assert_eq!(lhs, rhs),
487c2184a10SAlex Crichton DiffEqResult::Poisoned => return Ok(false),
488c2184a10SAlex Crichton DiffEqResult::Failed => {}
48910dbb199SAlex Crichton }
4905ec92d59SAndrew Brown
491fd98814bSAlex Crichton for (global, ty) in rhs.exported_globals() {
492fd98814bSAlex Crichton log::debug!("Comparing global `{global}`");
493fd98814bSAlex Crichton let lhs = match lhs.get_global(&global, ty) {
494fd98814bSAlex Crichton Some(val) => val,
495fd98814bSAlex Crichton None => continue,
4965ec92d59SAndrew Brown };
497fd98814bSAlex Crichton let rhs = rhs.get_global(&global, ty).unwrap();
498fd98814bSAlex Crichton assert_eq!(lhs, rhs);
499fd98814bSAlex Crichton }
500fd98814bSAlex Crichton for (memory, shared) in rhs.exported_memories() {
501fd98814bSAlex Crichton log::debug!("Comparing memory `{memory}`");
502fd98814bSAlex Crichton let lhs = match lhs.get_memory(&memory, shared) {
503fd98814bSAlex Crichton Some(val) => val,
504fd98814bSAlex Crichton None => continue,
505fd98814bSAlex Crichton };
506fd98814bSAlex Crichton let rhs = rhs.get_memory(&memory, shared).unwrap();
507fd98814bSAlex Crichton if lhs == rhs {
508fd98814bSAlex Crichton continue;
509fd98814bSAlex Crichton }
5104b703f9dSAlex Crichton eprintln!("differential memory is {} bytes long", lhs.len());
5114b703f9dSAlex Crichton eprintln!("wasmtime memory is {} bytes long", rhs.len());
512fd98814bSAlex Crichton panic!("memories have differing values");
5135ec92d59SAndrew Brown }
5145ec92d59SAndrew Brown
51510dbb199SAlex Crichton Ok(true)
5165ec92d59SAndrew Brown }
5175ec92d59SAndrew Brown
518c2184a10SAlex Crichton /// Result of comparing the result of two operations during differential
519c2184a10SAlex Crichton /// execution.
520c2184a10SAlex Crichton pub enum DiffEqResult<T, U> {
521c2184a10SAlex Crichton /// Both engines succeeded.
522c2184a10SAlex Crichton Success(T, U),
523c2184a10SAlex Crichton /// The result has reached the state where engines may have diverged and
524c2184a10SAlex Crichton /// results can no longer be compared.
525c2184a10SAlex Crichton Poisoned,
526c2184a10SAlex Crichton /// Both engines failed with the same error message, and internal state
527c2184a10SAlex Crichton /// should still match between the two engines.
528c2184a10SAlex Crichton Failed,
529c2184a10SAlex Crichton }
530c2184a10SAlex Crichton
wasmtime_trap_is_non_deterministic(trap: &Trap) -> bool5315b9e8765SNick Fitzgerald fn wasmtime_trap_is_non_deterministic(trap: &Trap) -> bool {
5325b9e8765SNick Fitzgerald match trap {
5335b9e8765SNick Fitzgerald // Allocations being too large for the GC are
5345b9e8765SNick Fitzgerald // implementation-defined.
5355b9e8765SNick Fitzgerald Trap::AllocationTooLarge |
5365b9e8765SNick Fitzgerald // Stack size, and therefore when overflow happens, is
5375b9e8765SNick Fitzgerald // implementation-defined.
5385b9e8765SNick Fitzgerald Trap::StackOverflow => true,
5395b9e8765SNick Fitzgerald _ => false,
5405b9e8765SNick Fitzgerald }
5415b9e8765SNick Fitzgerald }
5425b9e8765SNick Fitzgerald
wasmtime_error_is_non_deterministic(error: &wasmtime::Error) -> bool5435b9e8765SNick Fitzgerald fn wasmtime_error_is_non_deterministic(error: &wasmtime::Error) -> bool {
5445b9e8765SNick Fitzgerald match error.downcast_ref::<Trap>() {
5455b9e8765SNick Fitzgerald Some(trap) => wasmtime_trap_is_non_deterministic(trap),
5465b9e8765SNick Fitzgerald
5475b9e8765SNick Fitzgerald // For general, unknown errors, we can't rely on this being
5485b9e8765SNick Fitzgerald // a deterministic Wasm failure that both engines handled
5495b9e8765SNick Fitzgerald // identically, leaving Wasm in identical states. We could
5505b9e8765SNick Fitzgerald // just as easily be hitting engine-specific failures, like
5515b9e8765SNick Fitzgerald // different implementation-defined limits. So simply poison
5525b9e8765SNick Fitzgerald // this execution and move on to the next test.
5535b9e8765SNick Fitzgerald None => true,
5545b9e8765SNick Fitzgerald }
5555b9e8765SNick Fitzgerald }
5565b9e8765SNick Fitzgerald
557c2184a10SAlex Crichton impl<T, U> DiffEqResult<T, U> {
558c2184a10SAlex Crichton /// Computes the differential result from executing in two different
559c2184a10SAlex Crichton /// engines.
new( lhs_engine: &dyn DiffEngine, lhs_result: Result<T>, rhs_result: Result<U>, ) -> DiffEqResult<T, U>560c2184a10SAlex Crichton pub fn new(
561c2184a10SAlex Crichton lhs_engine: &dyn DiffEngine,
562c2184a10SAlex Crichton lhs_result: Result<T>,
563c2184a10SAlex Crichton rhs_result: Result<U>,
564c2184a10SAlex Crichton ) -> DiffEqResult<T, U> {
565c2184a10SAlex Crichton match (lhs_result, rhs_result) {
566c2184a10SAlex Crichton (Ok(lhs_result), Ok(rhs_result)) => DiffEqResult::Success(lhs_result, rhs_result),
567c2184a10SAlex Crichton
5685b9e8765SNick Fitzgerald // Handle all non-deterministic errors by poisoning this execution's
5695b9e8765SNick Fitzgerald // state, so that we simply move on to the next test.
5705b9e8765SNick Fitzgerald (Err(lhs), _) if lhs_engine.is_non_deterministic_error(&lhs) => {
5715b9e8765SNick Fitzgerald log::debug!("lhs failed non-deterministically: {lhs:?}");
5725b9e8765SNick Fitzgerald DiffEqResult::Poisoned
5735b9e8765SNick Fitzgerald }
5745b9e8765SNick Fitzgerald (_, Err(rhs)) if wasmtime_error_is_non_deterministic(&rhs) => {
5755b9e8765SNick Fitzgerald log::debug!("rhs failed non-deterministically: {rhs:?}");
5765b9e8765SNick Fitzgerald DiffEqResult::Poisoned
5775b9e8765SNick Fitzgerald }
5785b9e8765SNick Fitzgerald
5795b9e8765SNick Fitzgerald // Both sides failed deterministically. Check that the trap and
5805b9e8765SNick Fitzgerald // state at the time of failure is the same.
581c2184a10SAlex Crichton (Err(lhs), Err(rhs)) => {
5825b9e8765SNick Fitzgerald let rhs = rhs
5835b9e8765SNick Fitzgerald .downcast::<Trap>()
5845b9e8765SNick Fitzgerald .expect("non-traps handled in earlier match arm");
58583bf774dSNick Fitzgerald
5865b9e8765SNick Fitzgerald debug_assert!(
5875b9e8765SNick Fitzgerald !lhs_engine.is_non_deterministic_error(&lhs),
5885b9e8765SNick Fitzgerald "non-deterministic traps handled in earlier match arm",
5895b9e8765SNick Fitzgerald );
5905b9e8765SNick Fitzgerald debug_assert!(
5915b9e8765SNick Fitzgerald !wasmtime_trap_is_non_deterministic(&rhs),
5925b9e8765SNick Fitzgerald "non-deterministic traps handled in earlier match arm",
5935b9e8765SNick Fitzgerald );
59483bf774dSNick Fitzgerald
595b3b50943SAlex Crichton lhs_engine.assert_error_match(&lhs, &rhs);
596c2184a10SAlex Crichton DiffEqResult::Failed
597c2184a10SAlex Crichton }
5985b9e8765SNick Fitzgerald
599c2184a10SAlex Crichton // A real bug is found if only one side fails.
6007b744a9dSAlex Crichton (Ok(_), Err(err)) => panic!("only the `rhs` failed for this input: {err:?}"),
6017b744a9dSAlex Crichton (Err(err), Ok(_)) => panic!("only the `lhs` failed for this input: {err:?}"),
602c2184a10SAlex Crichton }
603c2184a10SAlex Crichton }
604c2184a10SAlex Crichton }
605c2184a10SAlex Crichton
6060cde3019SNick Fitzgerald /// Invoke the given API calls.
make_api_calls(api: generators::api::ApiCalls)607ab1d845aSAlex Crichton pub fn make_api_calls(api: generators::api::ApiCalls) {
6080cde3019SNick Fitzgerald use crate::generators::api::ApiCall;
609210bfddfSAlex Crichton use std::collections::HashMap;
6100cde3019SNick Fitzgerald
6118b4bdf92SPat Hickey let mut store: Option<Store<StoreLimits>> = None;
6121fe76ef9SAlex Crichton let mut modules: HashMap<usize, Module> = Default::default();
6136571fb8fSAlex Crichton let mut instances: HashMap<usize, Instance> = Default::default();
6140cde3019SNick Fitzgerald
6150cde3019SNick Fitzgerald for call in api.calls {
6160cde3019SNick Fitzgerald match call {
617ab1d845aSAlex Crichton ApiCall::StoreNew(config) => {
618dfef71eaSAlex Crichton log::trace!("creating store");
6190cde3019SNick Fitzgerald assert!(store.is_none());
620ab1d845aSAlex Crichton store = Some(config.to_store());
6210cde3019SNick Fitzgerald }
6220cde3019SNick Fitzgerald
6230cde3019SNick Fitzgerald ApiCall::ModuleNew { id, wasm } => {
6242bac6574SAlex Crichton log::debug!("creating module: {id}");
625b73b8318SAlex Crichton log_wasm(&wasm);
626ab1d845aSAlex Crichton let module = match Module::new(store.as_ref().unwrap().engine(), &wasm) {
6270cde3019SNick Fitzgerald Ok(m) => m,
6280cde3019SNick Fitzgerald Err(_) => continue,
6291fe76ef9SAlex Crichton };
6300cde3019SNick Fitzgerald let old = modules.insert(id, module);
6310cde3019SNick Fitzgerald assert!(old.is_none());
6320cde3019SNick Fitzgerald }
6330cde3019SNick Fitzgerald
6340cde3019SNick Fitzgerald ApiCall::ModuleDrop { id } => {
6352bac6574SAlex Crichton log::trace!("dropping module: {id}");
6360cde3019SNick Fitzgerald drop(modules.remove(&id));
6370cde3019SNick Fitzgerald }
6380cde3019SNick Fitzgerald
6390cde3019SNick Fitzgerald ApiCall::InstanceNew { id, module } => {
6402bac6574SAlex Crichton log::trace!("instantiating module {module} as {id}");
6410cde3019SNick Fitzgerald let module = match modules.get(&module) {
6420cde3019SNick Fitzgerald Some(m) => m,
6430cde3019SNick Fitzgerald None => continue,
6440cde3019SNick Fitzgerald };
6450cde3019SNick Fitzgerald
6467a1b7cdfSAlex Crichton let store = store.as_mut().unwrap();
6473bdf6c7aSAlex Crichton if let Some(instance) = instantiate_with_dummy(store, module) {
6486571fb8fSAlex Crichton instances.insert(id, instance);
6490cde3019SNick Fitzgerald }
6500cde3019SNick Fitzgerald }
6510cde3019SNick Fitzgerald
6520cde3019SNick Fitzgerald ApiCall::InstanceDrop { id } => {
6532bac6574SAlex Crichton log::trace!("dropping instance {id}");
6547f0228c9SAlex Crichton instances.remove(&id);
6550cde3019SNick Fitzgerald }
6560cde3019SNick Fitzgerald
6570cde3019SNick Fitzgerald ApiCall::CallExportedFunc { instance, nth } => {
6582bac6574SAlex Crichton log::trace!("calling instance export {instance} / {nth}");
6590cde3019SNick Fitzgerald let instance = match instances.get(&instance) {
6600cde3019SNick Fitzgerald Some(i) => i,
6610cde3019SNick Fitzgerald None => {
6620cde3019SNick Fitzgerald // Note that we aren't guaranteed to instantiate valid
6630cde3019SNick Fitzgerald // modules, see comments in `InstanceNew` for details on
6640cde3019SNick Fitzgerald // that. But the API call generator can't know if
6650cde3019SNick Fitzgerald // instantiation failed, so we might not actually have
6660cde3019SNick Fitzgerald // this instance. When that's the case, just skip the
6670cde3019SNick Fitzgerald // API call and keep going.
6680cde3019SNick Fitzgerald continue;
6690cde3019SNick Fitzgerald }
6700cde3019SNick Fitzgerald };
6717a1b7cdfSAlex Crichton let store = store.as_mut().unwrap();
6720cde3019SNick Fitzgerald
6736571fb8fSAlex Crichton let funcs = instance
6747a1b7cdfSAlex Crichton .exports(&mut *store)
6759364eb1dSDan Gohman .filter_map(|e| match e.into_extern() {
6760c0153c1SNick Fitzgerald Extern::Func(f) => Some(f),
6770cde3019SNick Fitzgerald _ => None,
6780cde3019SNick Fitzgerald })
6796571fb8fSAlex Crichton .collect::<Vec<_>>();
6800cde3019SNick Fitzgerald
6810cde3019SNick Fitzgerald if funcs.is_empty() {
6820cde3019SNick Fitzgerald continue;
6830cde3019SNick Fitzgerald }
6840cde3019SNick Fitzgerald
6850cde3019SNick Fitzgerald let nth = nth % funcs.len();
6866571fb8fSAlex Crichton let f = &funcs[nth];
6877a1b7cdfSAlex Crichton let ty = f.ty(&store);
688df4cb6ebSGonzalo Silvalde if let Some(params) = ty
689df4cb6ebSGonzalo Silvalde .params()
690df4cb6ebSGonzalo Silvalde .map(|p| p.default_value())
691df4cb6ebSGonzalo Silvalde .collect::<Option<Vec<_>>>()
692df4cb6ebSGonzalo Silvalde {
693bcf35449SAlex Crichton let mut results = vec![Val::I32(0); ty.results().len()];
694bcf35449SAlex Crichton let _ = f.call(store, ¶ms, &mut results);
6950cde3019SNick Fitzgerald }
6960cde3019SNick Fitzgerald }
6970cde3019SNick Fitzgerald }
6980cde3019SNick Fitzgerald }
699ff93bce0SNick Fitzgerald }
7006dde2229SAlex Crichton
7011898b8c7SAlex Crichton /// Executes the wast `test` with the `config` specified.
7026dde2229SAlex Crichton ///
7031898b8c7SAlex Crichton /// Ensures that wast tests pass regardless of the `Config`.
wast_test(u: &mut arbitrary::Unstructured<'_>) -> arbitrary::Result<()>70483575995SAlex Crichton pub fn wast_test(u: &mut arbitrary::Unstructured<'_>) -> arbitrary::Result<()> {
7054ba3404cSAlex Crichton crate::init_fuzzing();
70683575995SAlex Crichton
70783575995SAlex Crichton let mut fuzz_config: generators::Config = u.arbitrary()?;
7080a55f804SAlex Crichton fuzz_config.module_config.shared_memory = true;
70983575995SAlex Crichton let test: generators::WastTest = u.arbitrary()?;
71083575995SAlex Crichton
711f406347aSAlex Crichton let test = &test.test;
712f406347aSAlex Crichton
713b221fca7SJoel Dice if test.config.component_model_async() || u.arbitrary()? {
714b221fca7SJoel Dice fuzz_config.enable_async(u)?;
715b221fca7SJoel Dice }
716b221fca7SJoel Dice
717f406347aSAlex Crichton // Discard tests that allocate a lot of memory as we don't want to OOM the
718f406347aSAlex Crichton // fuzzer and we also limit memory growth which would cause the test to
719f406347aSAlex Crichton // fail.
720f406347aSAlex Crichton if test.config.hogs_memory.unwrap_or(false) {
72183575995SAlex Crichton return Err(arbitrary::Error::IncorrectFormat);
722f406347aSAlex Crichton }
723f406347aSAlex Crichton
724f406347aSAlex Crichton // Transform `fuzz_config` to be valid for `test` and make sure that this
725f406347aSAlex Crichton // test is supposed to pass.
726f406347aSAlex Crichton let wast_config = fuzz_config.make_wast_test_compliant(test);
727f406347aSAlex Crichton if test.should_fail(&wast_config) {
72883575995SAlex Crichton return Err(arbitrary::Error::IncorrectFormat);
7291f534c57SAlex Crichton }
7301898b8c7SAlex Crichton
7314d75ebd1SJeffrey Charles // Winch requires AVX and AVX2 for SIMD tests to pass so don't run the test
7324d75ebd1SJeffrey Charles // if either isn't enabled.
7334d75ebd1SJeffrey Charles if fuzz_config.wasmtime.compiler_strategy == CompilerStrategy::Winch
7344d75ebd1SJeffrey Charles && test.config.simd()
7354d75ebd1SJeffrey Charles && (fuzz_config
7364d75ebd1SJeffrey Charles .wasmtime
7374d75ebd1SJeffrey Charles .codegen_flag("has_avx")
7384d75ebd1SJeffrey Charles .is_some_and(|value| value == "false")
7394d75ebd1SJeffrey Charles || fuzz_config
7404d75ebd1SJeffrey Charles .wasmtime
7414d75ebd1SJeffrey Charles .codegen_flag("has_avx2")
7424d75ebd1SJeffrey Charles .is_some_and(|value| value == "false"))
7434d75ebd1SJeffrey Charles {
7444d75ebd1SJeffrey Charles log::warn!(
7454d75ebd1SJeffrey Charles "Skipping Wast test because Winch doesn't support SIMD tests with AVX or AVX2 disabled"
7464d75ebd1SJeffrey Charles );
74783575995SAlex Crichton return Err(arbitrary::Error::IncorrectFormat);
7484d75ebd1SJeffrey Charles }
7494d75ebd1SJeffrey Charles
7501898b8c7SAlex Crichton // Fuel and epochs don't play well with threads right now, so exclude any
7511898b8c7SAlex Crichton // thread-spawning test if it looks like threads are spawned in that case.
7521898b8c7SAlex Crichton if fuzz_config.wasmtime.consume_fuel || fuzz_config.wasmtime.epoch_interruption {
7531898b8c7SAlex Crichton if test.contents.contains("(thread") {
75483575995SAlex Crichton return Err(arbitrary::Error::IncorrectFormat);
7551898b8c7SAlex Crichton }
7561898b8c7SAlex Crichton }
7571898b8c7SAlex Crichton
758f406347aSAlex Crichton log::debug!("running {:?}", test.path);
75983575995SAlex Crichton let async_ = if fuzz_config.wasmtime.async_config == generators::AsyncConfig::Disabled {
76083575995SAlex Crichton wasmtime_wast::Async::No
76183575995SAlex Crichton } else {
76283575995SAlex Crichton wasmtime_wast::Async::Yes
76383575995SAlex Crichton };
76423b9f3b0SAlex Crichton log::debug!("async: {async_:?}");
7656a66b9a0SAlex Crichton let engine = Engine::new(&fuzz_config.to_wasmtime()).unwrap();
7666a66b9a0SAlex Crichton let mut wast_context = WastContext::new(&engine, async_, move |store| {
7676a66b9a0SAlex Crichton fuzz_config.configure_store_epoch_and_fuel(store);
7686a66b9a0SAlex Crichton });
7691898b8c7SAlex Crichton wast_context
7701898b8c7SAlex Crichton .register_spectest(&wasmtime_wast::SpectestConfig {
771f406347aSAlex Crichton use_shared_memory: true,
7721898b8c7SAlex Crichton suppress_prints: true,
7731898b8c7SAlex Crichton })
7741898b8c7SAlex Crichton .unwrap();
775*071c4061Sr-near wast_context.register_wasmtime().unwrap();
7766dde2229SAlex Crichton wast_context
77798d06b61SAlex Crichton .run_wast(test.path.to_str().unwrap(), test.contents.as_bytes())
7786dde2229SAlex Crichton .unwrap();
77983575995SAlex Crichton Ok(())
7806dde2229SAlex Crichton }
78198e899f6SNick Fitzgerald
782b6f59f05SKhagan (Khan) Karimov /// Execute a series of `gc` operations.
7832154c63dSAlex Crichton ///
7842154c63dSAlex Crichton /// Returns the number of `gc` operations which occurred throughout the test
7852154c63dSAlex Crichton /// case -- used to test below that gc happens reasonably soon and eventually.
gc_ops(mut fuzz_config: generators::Config, mut ops: GcOps) -> Result<usize>786b6f59f05SKhagan (Khan) Karimov pub fn gc_ops(mut fuzz_config: generators::Config, mut ops: GcOps) -> Result<usize> {
787ce3c0739SNick Fitzgerald let expected_drops = Arc::new(AtomicUsize::new(0));
7887a1b7cdfSAlex Crichton let num_dropped = Arc::new(AtomicUsize::new(0));
78998e899f6SNick Fitzgerald
7902154c63dSAlex Crichton let num_gcs = Arc::new(AtomicUsize::new(0));
79198e899f6SNick Fitzgerald {
79224597764SAlex Crichton fuzz_config.wasmtime.consume_fuel = true;
793ab1d845aSAlex Crichton let mut store = fuzz_config.to_store();
79485c0a2dfSTyler Rockwood store.set_fuel(1_000).unwrap();
79524597764SAlex Crichton
79602260b7cSDavid Haynes let wasm = ops.to_wasm_binary();
79702260b7cSDavid Haynes log_wasm(&wasm);
79804c03b31SAlex Crichton let module = match compile_module(store.engine(), &wasm, KnownValid::No, &fuzz_config) {
7996ffcd4eaSPeter Huene Some(m) => m,
8000fa13013SNick Fitzgerald None => return Ok(0),
80198e899f6SNick Fitzgerald };
80298e899f6SNick Fitzgerald
803ab1d845aSAlex Crichton let mut linker = Linker::new(store.engine());
804d2ce1ac7SNick Fitzgerald
80598e899f6SNick Fitzgerald // To avoid timeouts, limit the number of explicit GCs we perform per
80698e899f6SNick Fitzgerald // test case.
80798e899f6SNick Fitzgerald const MAX_GCS: usize = 5;
80898e899f6SNick Fitzgerald
8098652011fSNick Fitzgerald let func_ty = FuncType::new(
8108652011fSNick Fitzgerald store.engine(),
811d2ce1ac7SNick Fitzgerald vec![],
812ff93bce0SNick Fitzgerald vec![ValType::EXTERNREF, ValType::EXTERNREF, ValType::EXTERNREF],
8138652011fSNick Fitzgerald );
8148652011fSNick Fitzgerald let func = Func::new(&mut store, func_ty, {
815d2ce1ac7SNick Fitzgerald let num_dropped = num_dropped.clone();
816d2ce1ac7SNick Fitzgerald let expected_drops = expected_drops.clone();
8172154c63dSAlex Crichton let num_gcs = num_gcs.clone();
818d2ce1ac7SNick Fitzgerald move |mut caller: Caller<'_, StoreLimits>, _params, results| {
819b6f59f05SKhagan (Khan) Karimov log::info!("gc_ops: GC");
8207a1b7cdfSAlex Crichton if num_gcs.fetch_add(1, SeqCst) < MAX_GCS {
821cc8d04f4SAlex Crichton caller.gc(None)?;
82298e899f6SNick Fitzgerald }
82398e899f6SNick Fitzgerald
824ce3c0739SNick Fitzgerald let a = ExternRef::new(
825ce3c0739SNick Fitzgerald &mut caller,
826ce3c0739SNick Fitzgerald CountDrops::new(&expected_drops, num_dropped.clone()),
827ce3c0739SNick Fitzgerald )?;
828ce3c0739SNick Fitzgerald let b = ExternRef::new(
829ce3c0739SNick Fitzgerald &mut caller,
830ce3c0739SNick Fitzgerald CountDrops::new(&expected_drops, num_dropped.clone()),
831ce3c0739SNick Fitzgerald )?;
832ce3c0739SNick Fitzgerald let c = ExternRef::new(
833ce3c0739SNick Fitzgerald &mut caller,
834ce3c0739SNick Fitzgerald CountDrops::new(&expected_drops, num_dropped.clone()),
835ce3c0739SNick Fitzgerald )?;
836edf7f9f2SNick Fitzgerald
837b6f59f05SKhagan (Khan) Karimov log::info!("gc_ops: gc() -> ({a:?}, {b:?}, {c:?})");
838edf7f9f2SNick Fitzgerald results[0] = Some(a).into();
839edf7f9f2SNick Fitzgerald results[1] = Some(b).into();
840edf7f9f2SNick Fitzgerald results[2] = Some(c).into();
841d2ce1ac7SNick Fitzgerald Ok(())
842d2ce1ac7SNick Fitzgerald }
8438652011fSNick Fitzgerald });
84463d80fc5SAlex Crichton linker.define(&store, "", "gc", func).unwrap();
845d2ce1ac7SNick Fitzgerald
846d2ce1ac7SNick Fitzgerald linker
847d2ce1ac7SNick Fitzgerald .func_wrap("", "take_refs", {
848d2ce1ac7SNick Fitzgerald let expected_drops = expected_drops.clone();
849bd2ea901SNick Fitzgerald move |caller: Caller<'_, StoreLimits>,
850bd2ea901SNick Fitzgerald a: Option<Rooted<ExternRef>>,
851bd2ea901SNick Fitzgerald b: Option<Rooted<ExternRef>>,
852bd2ea901SNick Fitzgerald c: Option<Rooted<ExternRef>>|
853bd2ea901SNick Fitzgerald -> Result<()> {
854b6f59f05SKhagan (Khan) Karimov log::info!("gc_ops: take_refs({a:?}, {b:?}, {c:?})",);
855edf7f9f2SNick Fitzgerald
856d2ce1ac7SNick Fitzgerald // Do the assertion on each ref's inner data, even though it
857d2ce1ac7SNick Fitzgerald // all points to the same atomic, so that if we happen to
858d2ce1ac7SNick Fitzgerald // run into a use-after-free bug with one of these refs we
859d2ce1ac7SNick Fitzgerald // are more likely to trigger a segfault.
860d2ce1ac7SNick Fitzgerald if let Some(a) = a {
86112c20b22SNick Fitzgerald let a = a
86212c20b22SNick Fitzgerald .data(&caller)?
86312c20b22SNick Fitzgerald .unwrap()
86412c20b22SNick Fitzgerald .downcast_ref::<CountDrops>()
86512c20b22SNick Fitzgerald .unwrap();
866d2ce1ac7SNick Fitzgerald assert!(a.0.load(SeqCst) <= expected_drops.load(SeqCst));
867d2ce1ac7SNick Fitzgerald }
868d2ce1ac7SNick Fitzgerald if let Some(b) = b {
86912c20b22SNick Fitzgerald let b = b
87012c20b22SNick Fitzgerald .data(&caller)?
87112c20b22SNick Fitzgerald .unwrap()
87212c20b22SNick Fitzgerald .downcast_ref::<CountDrops>()
87312c20b22SNick Fitzgerald .unwrap();
874d2ce1ac7SNick Fitzgerald assert!(b.0.load(SeqCst) <= expected_drops.load(SeqCst));
875d2ce1ac7SNick Fitzgerald }
876d2ce1ac7SNick Fitzgerald if let Some(c) = c {
87712c20b22SNick Fitzgerald let c = c
87812c20b22SNick Fitzgerald .data(&caller)?
87912c20b22SNick Fitzgerald .unwrap()
88012c20b22SNick Fitzgerald .downcast_ref::<CountDrops>()
88112c20b22SNick Fitzgerald .unwrap();
882d2ce1ac7SNick Fitzgerald assert!(c.0.load(SeqCst) <= expected_drops.load(SeqCst));
883d2ce1ac7SNick Fitzgerald }
884bd2ea901SNick Fitzgerald Ok(())
885d2ce1ac7SNick Fitzgerald }
886d2ce1ac7SNick Fitzgerald })
887d2ce1ac7SNick Fitzgerald .unwrap();
888d2ce1ac7SNick Fitzgerald
8898652011fSNick Fitzgerald let func_ty = FuncType::new(
8908652011fSNick Fitzgerald store.engine(),
891d2ce1ac7SNick Fitzgerald vec![],
892ff93bce0SNick Fitzgerald vec![ValType::EXTERNREF, ValType::EXTERNREF, ValType::EXTERNREF],
8938652011fSNick Fitzgerald );
8948652011fSNick Fitzgerald let func = Func::new(&mut store, func_ty, {
895d2ce1ac7SNick Fitzgerald let num_dropped = num_dropped.clone();
896d2ce1ac7SNick Fitzgerald let expected_drops = expected_drops.clone();
897bd2ea901SNick Fitzgerald move |mut caller, _params, results| {
898b6f59f05SKhagan (Khan) Karimov log::info!("gc_ops: make_refs");
8990fa13013SNick Fitzgerald
900ce3c0739SNick Fitzgerald let a = ExternRef::new(
901ce3c0739SNick Fitzgerald &mut caller,
902ce3c0739SNick Fitzgerald CountDrops::new(&expected_drops, num_dropped.clone()),
903ce3c0739SNick Fitzgerald )?;
904ce3c0739SNick Fitzgerald let b = ExternRef::new(
905ce3c0739SNick Fitzgerald &mut caller,
906ce3c0739SNick Fitzgerald CountDrops::new(&expected_drops, num_dropped.clone()),
907ce3c0739SNick Fitzgerald )?;
908ce3c0739SNick Fitzgerald let c = ExternRef::new(
909ce3c0739SNick Fitzgerald &mut caller,
910ce3c0739SNick Fitzgerald CountDrops::new(&expected_drops, num_dropped.clone()),
911ce3c0739SNick Fitzgerald )?;
9120fa13013SNick Fitzgerald
913b6f59f05SKhagan (Khan) Karimov log::info!("gc_ops: make_refs() -> ({a:?}, {b:?}, {c:?})");
9140fa13013SNick Fitzgerald
9150fa13013SNick Fitzgerald results[0] = Some(a).into();
9160fa13013SNick Fitzgerald results[1] = Some(b).into();
9170fa13013SNick Fitzgerald results[2] = Some(c).into();
9180fa13013SNick Fitzgerald
919d2ce1ac7SNick Fitzgerald Ok(())
920d2ce1ac7SNick Fitzgerald }
9218652011fSNick Fitzgerald });
92263d80fc5SAlex Crichton linker.define(&store, "", "make_refs", func).unwrap();
923d2ce1ac7SNick Fitzgerald
924250b9922SKhagan (Khan) Karimov let func_ty = FuncType::new(
925250b9922SKhagan (Khan) Karimov store.engine(),
9266592cf93SKhagan (Khan) Karimov vec![ValType::Ref(RefType::new(true, HeapType::Struct))],
927250b9922SKhagan (Khan) Karimov vec![],
928250b9922SKhagan (Khan) Karimov );
929250b9922SKhagan (Khan) Karimov
930250b9922SKhagan (Khan) Karimov let func = Func::new(&mut store, func_ty, {
931250b9922SKhagan (Khan) Karimov move |_caller: Caller<'_, StoreLimits>, _params, _results| {
9326592cf93SKhagan (Khan) Karimov log::info!("gc_ops: take_struct(<ref null struct>)");
933250b9922SKhagan (Khan) Karimov Ok(())
934250b9922SKhagan (Khan) Karimov }
935250b9922SKhagan (Khan) Karimov });
936250b9922SKhagan (Khan) Karimov
937250b9922SKhagan (Khan) Karimov linker.define(&store, "", "take_struct", func).unwrap();
938250b9922SKhagan (Khan) Karimov
939250b9922SKhagan (Khan) Karimov for imp in module.imports() {
940250b9922SKhagan (Khan) Karimov if imp.module() == "" {
941250b9922SKhagan (Khan) Karimov let name = imp.name();
942250b9922SKhagan (Khan) Karimov if name.starts_with("take_struct_") {
943250b9922SKhagan (Khan) Karimov if let wasmtime::ExternType::Func(ft) = imp.ty() {
944250b9922SKhagan (Khan) Karimov let imp_name = name.to_string();
945250b9922SKhagan (Khan) Karimov let func =
946250b9922SKhagan (Khan) Karimov Func::new(&mut store, ft.clone(), move |_caller, _params, _results| {
947b6f59f05SKhagan (Khan) Karimov log::info!("gc_ops: {imp_name}(<typed structref>)");
948250b9922SKhagan (Khan) Karimov Ok(())
949250b9922SKhagan (Khan) Karimov });
950250b9922SKhagan (Khan) Karimov linker.define(&store, "", name, func).unwrap();
951250b9922SKhagan (Khan) Karimov }
952250b9922SKhagan (Khan) Karimov }
953250b9922SKhagan (Khan) Karimov }
954250b9922SKhagan (Khan) Karimov }
955250b9922SKhagan (Khan) Karimov
956d2ce1ac7SNick Fitzgerald let instance = linker.instantiate(&mut store, &module).unwrap();
9577a1b7cdfSAlex Crichton let run = instance.get_func(&mut store, "run").unwrap();
95898e899f6SNick Fitzgerald
959bd2ea901SNick Fitzgerald {
960bd2ea901SNick Fitzgerald let mut scope = RootScope::new(&mut store);
961b2025eadSNick Fitzgerald
962b2025eadSNick Fitzgerald log::info!(
963b6f59f05SKhagan (Khan) Karimov "gc_ops: begin allocating {} externref arguments",
964bb7ec8e8SKhagan (Khan) Karimov ops.limits.num_globals
965b2025eadSNick Fitzgerald );
966bb7ec8e8SKhagan (Khan) Karimov let args: Vec<_> = (0..ops.limits.num_params)
967bd2ea901SNick Fitzgerald .map(|_| {
9680fa13013SNick Fitzgerald Ok(Val::ExternRef(Some(ExternRef::new(
969bd2ea901SNick Fitzgerald &mut scope,
970ce3c0739SNick Fitzgerald CountDrops::new(&expected_drops, num_dropped.clone()),
9710fa13013SNick Fitzgerald )?)))
972bd2ea901SNick Fitzgerald })
9730fa13013SNick Fitzgerald .collect::<Result<_>>()?;
974b2025eadSNick Fitzgerald log::info!(
975b6f59f05SKhagan (Khan) Karimov "gc_ops: end allocating {} externref arguments",
976bb7ec8e8SKhagan (Khan) Karimov ops.limits.num_globals
977b2025eadSNick Fitzgerald );
9782154c63dSAlex Crichton
9792154c63dSAlex Crichton // The generated function should always return a trap. The only two
9802154c63dSAlex Crichton // valid traps are table-out-of-bounds which happens through `table.get`
9812154c63dSAlex Crichton // and `table.set` generated or an out-of-fuel trap. Otherwise any other
9822154c63dSAlex Crichton // error is unexpected and should fail fuzzing.
983b6f59f05SKhagan (Khan) Karimov log::info!("gc_ops: calling into Wasm `run` function");
984ce3c0739SNick Fitzgerald let err = run.call(&mut scope, &args, &mut []).unwrap_err();
985250b9922SKhagan (Khan) Karimov if err.is::<GcHeapOutOfMemory<CountDrops>>() || err.is::<GcHeapOutOfMemory<()>>() {
986250b9922SKhagan (Khan) Karimov // Accept GC OOM as an allowed outcome for this fuzzer.
987250b9922SKhagan (Khan) Karimov } else {
988ce3c0739SNick Fitzgerald let trap = err
9892154c63dSAlex Crichton .downcast::<Trap>()
990ce3c0739SNick Fitzgerald .expect("if not GC oom, error should be a Wasm trap");
9912afaac51SAlex Crichton match trap {
992250b9922SKhagan (Khan) Karimov Trap::TableOutOfBounds | Trap::OutOfFuel | Trap::AllocationTooLarge => {}
9932afaac51SAlex Crichton _ => panic!("unexpected trap: {trap}"),
9942154c63dSAlex Crichton }
995bd2ea901SNick Fitzgerald }
996ce3c0739SNick Fitzgerald }
997f292ff55SNick Fitzgerald
998f292ff55SNick Fitzgerald // Do a final GC after running the Wasm.
999cc8d04f4SAlex Crichton store.gc(None)?;
100098e899f6SNick Fitzgerald }
100198e899f6SNick Fitzgerald
1002d2ce1ac7SNick Fitzgerald assert_eq!(num_dropped.load(SeqCst), expected_drops.load(SeqCst));
10030fa13013SNick Fitzgerald return Ok(num_gcs.load(SeqCst));
100498e899f6SNick Fitzgerald
10057a1b7cdfSAlex Crichton struct CountDrops(Arc<AtomicUsize>);
100698e899f6SNick Fitzgerald
1007ce3c0739SNick Fitzgerald impl CountDrops {
1008ce3c0739SNick Fitzgerald fn new(expected_drops: &AtomicUsize, num_dropped: Arc<AtomicUsize>) -> Self {
1009ce3c0739SNick Fitzgerald let expected = expected_drops.fetch_add(1, SeqCst);
1010ce3c0739SNick Fitzgerald log::info!(
1011ce3c0739SNick Fitzgerald "CountDrops::new: expected drops: {expected} -> {}",
1012ce3c0739SNick Fitzgerald expected + 1
1013ce3c0739SNick Fitzgerald );
1014ce3c0739SNick Fitzgerald Self(num_dropped)
1015ce3c0739SNick Fitzgerald }
1016ce3c0739SNick Fitzgerald }
1017ce3c0739SNick Fitzgerald
101898e899f6SNick Fitzgerald impl Drop for CountDrops {
101998e899f6SNick Fitzgerald fn drop(&mut self) {
1020ce3c0739SNick Fitzgerald let drops = self.0.fetch_add(1, SeqCst);
1021ce3c0739SNick Fitzgerald log::info!("CountDrops::drop: actual drops: {drops} -> {}", drops + 1);
102298e899f6SNick Fitzgerald }
102398e899f6SNick Fitzgerald }
102498e899f6SNick Fitzgerald }
1025bbdea06eSChris Fallin
102646780983SChris Fallin /// Execute a series of exception-related operations.
exception_ops(mut fuzz_config: generators::Config, mut ops: ExceptionOps) -> Result<()>102746780983SChris Fallin pub fn exception_ops(mut fuzz_config: generators::Config, mut ops: ExceptionOps) -> Result<()> {
102846780983SChris Fallin match fuzz_config.wasmtime.compiler_strategy {
102946780983SChris Fallin // Winch doesn't support exceptions; force to Cranelift.
103046780983SChris Fallin CompilerStrategy::Winch => {
103146780983SChris Fallin fuzz_config.wasmtime.compiler_strategy = CompilerStrategy::CraneliftNative;
103246780983SChris Fallin }
103346780983SChris Fallin CompilerStrategy::CraneliftNative | CompilerStrategy::CraneliftPulley => {}
103446780983SChris Fallin }
103546780983SChris Fallin
103646780983SChris Fallin let module_cfg = &mut fuzz_config.module_config.config;
103746780983SChris Fallin // Force exceptions + GC on (exceptions require GC).
103846780983SChris Fallin module_cfg.gc_enabled = true;
103946780983SChris Fallin module_cfg.exceptions_enabled = true;
104046780983SChris Fallin module_cfg.reference_types_enabled = true;
104146780983SChris Fallin
104246780983SChris Fallin let expected = ops.expected_result();
104346780983SChris Fallin
104446780983SChris Fallin let wasm = ops.to_wasm_binary();
104546780983SChris Fallin log_wasm(&wasm);
104646780983SChris Fallin
104746780983SChris Fallin let mut store = fuzz_config.to_store();
104846780983SChris Fallin
104946780983SChris Fallin let module = compile_module(store.engine(), &wasm, KnownValid::No, &fuzz_config)
105046780983SChris Fallin .ok_or_else(|| wasmtime::format_err!("Compilation failed"))?;
105146780983SChris Fallin let mut linker = Linker::new(store.engine());
105246780983SChris Fallin
105346780983SChris Fallin let check_ty = FuncType::new(store.engine(), [ValType::I32, ValType::I32], []);
105446780983SChris Fallin let check_func = Func::new(&mut store, check_ty, |_caller, params, _results| {
105546780983SChris Fallin let actual = params[0].unwrap_i32();
105646780983SChris Fallin let expected = params[1].unwrap_i32();
105746780983SChris Fallin assert_eq!(actual, expected, "check_i32 mismatch");
105846780983SChris Fallin Ok(())
105946780983SChris Fallin });
106046780983SChris Fallin linker.define(&store, "", "check_i32", check_func).unwrap();
106146780983SChris Fallin
106246780983SChris Fallin let instance = linker.instantiate(&mut store, &module).unwrap();
106346780983SChris Fallin let run = instance.get_func(&mut store, "run").unwrap();
106446780983SChris Fallin
106546780983SChris Fallin let mut results = [Val::I32(0)];
106646780983SChris Fallin match run.call(&mut store, &[], &mut results) {
106746780983SChris Fallin Ok(()) => {
106846780983SChris Fallin let actual = results[0].unwrap_i32();
106946780983SChris Fallin assert_eq!(
107046780983SChris Fallin actual, expected,
107146780983SChris Fallin "exception_ops: run returned {actual}, expected {expected} \
107246780983SChris Fallin (one catch per scenario)"
107346780983SChris Fallin );
107446780983SChris Fallin }
107546780983SChris Fallin Err(e) => {
107646780983SChris Fallin // AllocationTooLarge / GcHeapOutOfMemory are acceptable resource-limit traps.
107746780983SChris Fallin if let Some(trap) = e.downcast_ref::<Trap>() {
107846780983SChris Fallin match trap {
107946780983SChris Fallin Trap::AllocationTooLarge => return Ok(()),
108046780983SChris Fallin _ => {}
108146780983SChris Fallin }
108246780983SChris Fallin }
108346780983SChris Fallin if e.is::<GcHeapOutOfMemory<()>>() {
108446780983SChris Fallin return Ok(());
108546780983SChris Fallin }
108646780983SChris Fallin // Any other error (including ThrownException) is unexpected.
108746780983SChris Fallin panic!("exception_ops: unexpected error during execution: {e:?}");
108846780983SChris Fallin }
108946780983SChris Fallin }
109046780983SChris Fallin
109146780983SChris Fallin Ok(())
109246780983SChris Fallin }
109346780983SChris Fallin
1094e09b9400SAlex Crichton #[derive(Default)]
1095b4ecea38SAlex Crichton struct HelperThread {
1096b4ecea38SAlex Crichton state: Arc<HelperThreadState>,
1097e09b9400SAlex Crichton thread: Option<std::thread::JoinHandle<()>>,
1098e09b9400SAlex Crichton }
1099e09b9400SAlex Crichton
1100b4ecea38SAlex Crichton #[derive(Default)]
1101b4ecea38SAlex Crichton struct HelperThreadState {
1102b4ecea38SAlex Crichton should_exit: Mutex<bool>,
1103b4ecea38SAlex Crichton should_exit_cvar: Condvar,
1104b4ecea38SAlex Crichton }
1105b4ecea38SAlex Crichton
1106b4ecea38SAlex Crichton impl HelperThread {
run_periodically(&mut self, dur: Duration, mut closure: impl FnMut() + Send + 'static)1107b4ecea38SAlex Crichton fn run_periodically(&mut self, dur: Duration, mut closure: impl FnMut() + Send + 'static) {
1108e09b9400SAlex Crichton let state = self.state.clone();
1109e09b9400SAlex Crichton self.thread = Some(std::thread::spawn(move || {
1110e09b9400SAlex Crichton // Using our mutex/condvar we wait here for the first of `dur` to
1111b4ecea38SAlex Crichton // pass or the `HelperThread` instance to get dropped.
1112b4ecea38SAlex Crichton let mut should_exit = state.should_exit.lock().unwrap();
1113b4ecea38SAlex Crichton while !*should_exit {
1114b4ecea38SAlex Crichton let (lock, result) = state
1115b4ecea38SAlex Crichton .should_exit_cvar
1116b4ecea38SAlex Crichton .wait_timeout(should_exit, dur)
1117b4ecea38SAlex Crichton .unwrap();
1118b4ecea38SAlex Crichton should_exit = lock;
1119e09b9400SAlex Crichton // If we timed out for sure then there's no need to continue
1120e09b9400SAlex Crichton // since we'll just abort on the next `checked_sub` anyway.
1121e09b9400SAlex Crichton if result.timed_out() {
1122e09b9400SAlex Crichton closure();
1123b4ecea38SAlex Crichton }
1124b4ecea38SAlex Crichton }
1125e09b9400SAlex Crichton }));
1126e09b9400SAlex Crichton }
1127e09b9400SAlex Crichton }
1128e09b9400SAlex Crichton
1129b4ecea38SAlex Crichton impl Drop for HelperThread {
drop(&mut self)1130e09b9400SAlex Crichton fn drop(&mut self) {
1131b4ecea38SAlex Crichton let thread = match self.thread.take() {
1132b4ecea38SAlex Crichton Some(thread) => thread,
1133b4ecea38SAlex Crichton None => return,
1134b4ecea38SAlex Crichton };
1135b4ecea38SAlex Crichton // Signal our thread that it should exit and wake it up in case it's
1136b4ecea38SAlex Crichton // sleeping.
1137b4ecea38SAlex Crichton *self.state.should_exit.lock().unwrap() = true;
1138b4ecea38SAlex Crichton self.state.should_exit_cvar.notify_one();
1139e09b9400SAlex Crichton
1140e09b9400SAlex Crichton // ... and then wait for the thread to exit to ensure we clean up
1141e09b9400SAlex Crichton // after ourselves.
1142e09b9400SAlex Crichton thread.join().unwrap();
1143e09b9400SAlex Crichton }
1144e09b9400SAlex Crichton }
114508a60a0fSAlex Crichton
1146b4ecea38SAlex Crichton /// Instantiates a wasm module and runs its exports with dummy values, all in
1147b4ecea38SAlex Crichton /// an async fashion.
1148b4ecea38SAlex Crichton ///
1149b4ecea38SAlex Crichton /// Attempts to stress yields in host functions to ensure that exiting and
1150b4ecea38SAlex Crichton /// resuming a wasm function call works.
call_async(wasm: &[u8], config: &generators::Config, mut poll_amts: &[u32])1151b4ecea38SAlex Crichton pub fn call_async(wasm: &[u8], config: &generators::Config, mut poll_amts: &[u32]) {
1152b4ecea38SAlex Crichton let mut store = config.to_store();
1153b4ecea38SAlex Crichton let module = match compile_module(store.engine(), wasm, KnownValid::Yes, config) {
1154b4ecea38SAlex Crichton Some(module) => module,
1155b4ecea38SAlex Crichton None => return,
1156b4ecea38SAlex Crichton };
1157b4ecea38SAlex Crichton
1158b4ecea38SAlex Crichton // Configure a helper thread to periodically increment the epoch to
1159b4ecea38SAlex Crichton // forcibly enable yields-via-epochs if epochs are in use. Note that this
1160b4ecea38SAlex Crichton // is required because the wasm isn't otherwise guaranteed to necessarily
1161b4ecea38SAlex Crichton // call any imports which will also increment the epoch.
1162b4ecea38SAlex Crichton let mut helper_thread = HelperThread::default();
1163b4ecea38SAlex Crichton if let generators::AsyncConfig::YieldWithEpochs { dur, .. } = &config.wasmtime.async_config {
1164b4ecea38SAlex Crichton let engine = store.engine().clone();
1165b4ecea38SAlex Crichton helper_thread.run_periodically(*dur, move || engine.increment_epoch());
1166b4ecea38SAlex Crichton }
1167b4ecea38SAlex Crichton
1168b4ecea38SAlex Crichton // Generate a `Linker` where all function imports are custom-built to yield
1169b4ecea38SAlex Crichton // periodically and additionally increment the epoch.
1170b4ecea38SAlex Crichton let mut imports = Vec::new();
1171b4ecea38SAlex Crichton for import in module.imports() {
1172b4ecea38SAlex Crichton let item = match import.ty() {
1173b4ecea38SAlex Crichton ExternType::Func(ty) => {
1174b4ecea38SAlex Crichton let poll_amt = take_poll_amt(&mut poll_amts);
1175b4ecea38SAlex Crichton Func::new_async(&mut store, ty.clone(), move |caller, _, results| {
1176b4ecea38SAlex Crichton let ty = ty.clone();
1177b4ecea38SAlex Crichton Box::new(async move {
1178b4ecea38SAlex Crichton caller.engine().increment_epoch();
11792bac6574SAlex Crichton log::info!("yielding {poll_amt} times in import");
1180b4ecea38SAlex Crichton YieldN(poll_amt).await;
1181b4ecea38SAlex Crichton for (ret_ty, result) in ty.results().zip(results) {
1182df4cb6ebSGonzalo Silvalde *result = ret_ty.default_value().unwrap();
1183b4ecea38SAlex Crichton }
1184b4ecea38SAlex Crichton Ok(())
1185b4ecea38SAlex Crichton })
1186b4ecea38SAlex Crichton })
1187b4ecea38SAlex Crichton .into()
1188b4ecea38SAlex Crichton }
1189df4cb6ebSGonzalo Silvalde other_ty => match other_ty.default_value(&mut store) {
11905279f5c3SAlex Crichton Ok(item) => item,
11915279f5c3SAlex Crichton Err(e) => {
11925279f5c3SAlex Crichton log::warn!("couldn't create import for {import:?}: {e:?}");
1193b4ecea38SAlex Crichton return;
1194b4ecea38SAlex Crichton }
1195b4ecea38SAlex Crichton },
1196b4ecea38SAlex Crichton };
1197b4ecea38SAlex Crichton imports.push(item);
1198b4ecea38SAlex Crichton }
1199b4ecea38SAlex Crichton
1200b4ecea38SAlex Crichton // Run the instantiation process, asynchronously, and if everything
1201b4ecea38SAlex Crichton // succeeds then pull out the instance.
1202b4ecea38SAlex Crichton // log::info!("starting instantiation");
12030b9ff9bfSAlex Crichton let instance = block_on(Timeout {
1204b4ecea38SAlex Crichton future: Instance::new_async(&mut store, &module, &imports),
1205b4ecea38SAlex Crichton polls: take_poll_amt(&mut poll_amts),
1206b4ecea38SAlex Crichton end: Instant::now() + Duration::from_millis(2_000),
1207b4ecea38SAlex Crichton });
1208b4ecea38SAlex Crichton let instance = match instance {
1209b4ecea38SAlex Crichton Ok(instantiation_result) => match unwrap_instance(&store, instantiation_result) {
1210b4ecea38SAlex Crichton Some(instance) => instance,
1211b4ecea38SAlex Crichton None => {
1212b4ecea38SAlex Crichton log::info!("instantiation hit a nominal error");
1213b4ecea38SAlex Crichton return; // resource exhaustion or limits met
1214b4ecea38SAlex Crichton }
1215b4ecea38SAlex Crichton },
1216b4ecea38SAlex Crichton Err(_) => {
1217b4ecea38SAlex Crichton log::info!("instantiation failed to complete");
1218b4ecea38SAlex Crichton return; // Timed out or ran out of polls
1219b4ecea38SAlex Crichton }
1220b4ecea38SAlex Crichton };
1221b4ecea38SAlex Crichton
1222b4ecea38SAlex Crichton // Run each export of the instance in the same manner as instantiation
1223b4ecea38SAlex Crichton // above. Dummy values are passed in for argument values here:
1224b4ecea38SAlex Crichton //
1225b4ecea38SAlex Crichton // TODO: this should probably be more clever about passing in arguments for
1226b4ecea38SAlex Crichton // example they might be used as pointers or something and always using 0
1227b4ecea38SAlex Crichton // isn't too interesting.
1228b4ecea38SAlex Crichton let funcs = instance
1229b4ecea38SAlex Crichton .exports(&mut store)
1230b4ecea38SAlex Crichton .filter_map(|e| {
1231b4ecea38SAlex Crichton let name = e.name().to_string();
1232b4ecea38SAlex Crichton let func = e.into_extern().into_func()?;
1233b4ecea38SAlex Crichton Some((name, func))
1234b4ecea38SAlex Crichton })
1235b4ecea38SAlex Crichton .collect::<Vec<_>>();
1236b4ecea38SAlex Crichton for (name, func) in funcs {
1237b4ecea38SAlex Crichton let ty = func.ty(&store);
1238b4ecea38SAlex Crichton let params = ty
1239b4ecea38SAlex Crichton .params()
1240df4cb6ebSGonzalo Silvalde .map(|ty| ty.default_value().unwrap())
1241b4ecea38SAlex Crichton .collect::<Vec<_>>();
1242b4ecea38SAlex Crichton let mut results = ty
1243b4ecea38SAlex Crichton .results()
1244df4cb6ebSGonzalo Silvalde .map(|ty| ty.default_value().unwrap())
1245b4ecea38SAlex Crichton .collect::<Vec<_>>();
1246b4ecea38SAlex Crichton
12472bac6574SAlex Crichton log::info!("invoking export {name:?}");
1248b4ecea38SAlex Crichton let future = func.call_async(&mut store, ¶ms, &mut results);
12490b9ff9bfSAlex Crichton match block_on(Timeout {
1250b4ecea38SAlex Crichton future,
1251b4ecea38SAlex Crichton polls: take_poll_amt(&mut poll_amts),
1252b4ecea38SAlex Crichton end: Instant::now() + Duration::from_millis(2_000),
1253b4ecea38SAlex Crichton }) {
1254b4ecea38SAlex Crichton // On success or too many polls, try the next export.
1255b4ecea38SAlex Crichton Ok(_) | Err(Exhausted::Polls) => {}
1256b4ecea38SAlex Crichton
1257b4ecea38SAlex Crichton // If time ran out then stop the current test case as we might have
1258b4ecea38SAlex Crichton // already sucked up a lot of time for this fuzz test case so don't
1259b4ecea38SAlex Crichton // keep it going.
1260b4ecea38SAlex Crichton Err(Exhausted::Time) => return,
1261b4ecea38SAlex Crichton }
1262b4ecea38SAlex Crichton }
1263b4ecea38SAlex Crichton
1264b4ecea38SAlex Crichton fn take_poll_amt(polls: &mut &[u32]) -> u32 {
1265b4ecea38SAlex Crichton match polls.split_first() {
1266b4ecea38SAlex Crichton Some((a, rest)) => {
1267b4ecea38SAlex Crichton *polls = rest;
1268b4ecea38SAlex Crichton *a
1269b4ecea38SAlex Crichton }
1270b4ecea38SAlex Crichton None => 0,
1271b4ecea38SAlex Crichton }
1272b4ecea38SAlex Crichton }
1273b4ecea38SAlex Crichton
1274b4ecea38SAlex Crichton /// Helper future for applying a timeout to `future` up to either when `end`
1275b4ecea38SAlex Crichton /// is the current time or `polls` polls happen.
1276b4ecea38SAlex Crichton ///
1277b4ecea38SAlex Crichton /// Note that this helps to time out infinite loops in wasm, for example.
1278b4ecea38SAlex Crichton struct Timeout<F> {
1279b4ecea38SAlex Crichton future: F,
1280b4ecea38SAlex Crichton /// If the future isn't ready by this time then the `Timeout<F>` future
1281b4ecea38SAlex Crichton /// will return `None`.
1282b4ecea38SAlex Crichton end: Instant,
1283b4ecea38SAlex Crichton /// If the future doesn't resolve itself in this many calls to `poll`
1284b4ecea38SAlex Crichton /// then the `Timeout<F>` future will return `None`.
1285b4ecea38SAlex Crichton polls: u32,
1286b4ecea38SAlex Crichton }
1287b4ecea38SAlex Crichton
1288b4ecea38SAlex Crichton enum Exhausted {
1289b4ecea38SAlex Crichton Time,
1290b4ecea38SAlex Crichton Polls,
1291b4ecea38SAlex Crichton }
1292b4ecea38SAlex Crichton
1293b4ecea38SAlex Crichton impl<F: Future> Future for Timeout<F> {
1294b4ecea38SAlex Crichton type Output = Result<F::Output, Exhausted>;
1295b4ecea38SAlex Crichton
1296b4ecea38SAlex Crichton fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
1297b4ecea38SAlex Crichton let (end, polls, future) = unsafe {
1298b4ecea38SAlex Crichton let me = self.get_unchecked_mut();
1299b4ecea38SAlex Crichton (me.end, &mut me.polls, Pin::new_unchecked(&mut me.future))
1300b4ecea38SAlex Crichton };
1301b4ecea38SAlex Crichton match future.poll(cx) {
1302b4ecea38SAlex Crichton Poll::Ready(val) => Poll::Ready(Ok(val)),
1303b4ecea38SAlex Crichton Poll::Pending => {
1304b4ecea38SAlex Crichton if Instant::now() >= end {
1305b4ecea38SAlex Crichton log::warn!("future operation timed out");
1306b4ecea38SAlex Crichton return Poll::Ready(Err(Exhausted::Time));
1307b4ecea38SAlex Crichton }
1308b4ecea38SAlex Crichton if *polls == 0 {
1309b4ecea38SAlex Crichton log::warn!("future operation ran out of polls");
1310b4ecea38SAlex Crichton return Poll::Ready(Err(Exhausted::Polls));
1311b4ecea38SAlex Crichton }
1312b4ecea38SAlex Crichton *polls -= 1;
1313b4ecea38SAlex Crichton Poll::Pending
1314b4ecea38SAlex Crichton }
1315b4ecea38SAlex Crichton }
1316b4ecea38SAlex Crichton }
1317b4ecea38SAlex Crichton }
1318b4ecea38SAlex Crichton }
1319ec3b2d22SNick Fitzgerald
1320ec3b2d22SNick Fitzgerald #[cfg(test)]
1321ec3b2d22SNick Fitzgerald mod tests {
1322ec3b2d22SNick Fitzgerald use super::*;
1323882f22a7SAlex Crichton use crate::test::{gen_until_pass, test_n_times};
1324ad6030f6SAlex Crichton use wasmparser::{Validator, WasmFeatures};
1325ad6030f6SAlex Crichton
1326b6f59f05SKhagan (Khan) Karimov // Test that the `gc_ops` fuzzer eventually runs the gc function in the host.
1327ec3b2d22SNick Fitzgerald // We've historically had issues where this fuzzer accidentally wasn't fuzzing
1328ec3b2d22SNick Fitzgerald // anything for a long time so this is an attempt to prevent that from happening
1329ec3b2d22SNick Fitzgerald // again.
1330ec3b2d22SNick Fitzgerald #[test]
gc_ops_eventually_gcs()1331b6f59f05SKhagan (Khan) Karimov fn gc_ops_eventually_gcs() {
1332ec3b2d22SNick Fitzgerald // Skip if we're under emulation because some fuzz configurations will do
1333ec3b2d22SNick Fitzgerald // large address space reservations that QEMU doesn't handle well.
1334ec3b2d22SNick Fitzgerald if std::env::var("WASMTIME_TEST_NO_HOG_MEMORY").is_ok() {
1335ec3b2d22SNick Fitzgerald return;
1336ec3b2d22SNick Fitzgerald }
1337ec3b2d22SNick Fitzgerald
1338ad6030f6SAlex Crichton let ok = gen_until_pass(|(config, test), _| {
1339b6f59f05SKhagan (Khan) Karimov let result = gc_ops(config, test)?;
1340ad6030f6SAlex Crichton Ok(result > 0)
1341ad6030f6SAlex Crichton });
1342ec3b2d22SNick Fitzgerald
1343ad6030f6SAlex Crichton if !ok {
1344ad6030f6SAlex Crichton panic!("gc was never found");
1345ec3b2d22SNick Fitzgerald }
1346ec3b2d22SNick Fitzgerald }
1347ec3b2d22SNick Fitzgerald
1348ad6030f6SAlex Crichton #[test]
module_generation_uses_expected_proposals()1349ad6030f6SAlex Crichton fn module_generation_uses_expected_proposals() {
1350ad6030f6SAlex Crichton // Proposals that Wasmtime supports. Eventually a module should be
1351ad6030f6SAlex Crichton // generated that needs these proposals.
1352ad6030f6SAlex Crichton let mut expected = WasmFeatures::MUTABLE_GLOBAL
1353ad6030f6SAlex Crichton | WasmFeatures::FLOATS
1354ad6030f6SAlex Crichton | WasmFeatures::SIGN_EXTENSION
1355ad6030f6SAlex Crichton | WasmFeatures::SATURATING_FLOAT_TO_INT
1356ad6030f6SAlex Crichton | WasmFeatures::MULTI_VALUE
1357ad6030f6SAlex Crichton | WasmFeatures::BULK_MEMORY
1358ad6030f6SAlex Crichton | WasmFeatures::REFERENCE_TYPES
1359ad6030f6SAlex Crichton | WasmFeatures::SIMD
1360ad6030f6SAlex Crichton | WasmFeatures::MULTI_MEMORY
1361ad6030f6SAlex Crichton | WasmFeatures::RELAXED_SIMD
1362ad6030f6SAlex Crichton | WasmFeatures::TAIL_CALL
1363ad6030f6SAlex Crichton | WasmFeatures::WIDE_ARITHMETIC
1364ad6030f6SAlex Crichton | WasmFeatures::MEMORY64
13655b9e8765SNick Fitzgerald | WasmFeatures::FUNCTION_REFERENCES
13665b9e8765SNick Fitzgerald | WasmFeatures::GC
1367edad0bbcSNick Fitzgerald | WasmFeatures::GC_TYPES
13680e6c711fSPat Hickey | WasmFeatures::CUSTOM_PAGE_SIZES
13693aa39239SChris Fallin | WasmFeatures::EXTENDED_CONST
13703aa39239SChris Fallin | WasmFeatures::EXCEPTIONS;
1371ad6030f6SAlex Crichton
1372ad6030f6SAlex Crichton // All other features that wasmparser supports, which is presumably a
1373ad6030f6SAlex Crichton // superset of the features that wasm-smith supports, are listed here as
1374ad6030f6SAlex Crichton // unexpected. This means, for example, that if wasm-smith updates to
1375ad6030f6SAlex Crichton // include a new proposal by default that wasmtime implements then it
1376ad6030f6SAlex Crichton // will be required to be listed above.
1377ad6030f6SAlex Crichton let unexpected = WasmFeatures::all() ^ expected;
1378ad6030f6SAlex Crichton
1379ad6030f6SAlex Crichton let ok = gen_until_pass(|config: generators::Config, u| {
1380ad6030f6SAlex Crichton let wasm = config.generate(u, None)?.to_bytes();
1381ad6030f6SAlex Crichton
1382ad6030f6SAlex Crichton // Double-check the module is valid
1383ad6030f6SAlex Crichton Validator::new_with_features(WasmFeatures::all()).validate_all(&wasm)?;
1384ad6030f6SAlex Crichton
1385ad6030f6SAlex Crichton // If any of the unexpected features are removed then this module
1386ad6030f6SAlex Crichton // should always be valid, otherwise something went wrong.
1387ad6030f6SAlex Crichton for feature in unexpected.iter() {
1388ad6030f6SAlex Crichton let ok =
1389ad6030f6SAlex Crichton Validator::new_with_features(WasmFeatures::all() ^ feature).validate_all(&wasm);
1390ad6030f6SAlex Crichton if ok.is_err() {
139193d22fcdSNick Fitzgerald wasmtime::bail!("generated a module with {feature:?} but that wasn't expected");
1392ad6030f6SAlex Crichton }
1393ad6030f6SAlex Crichton }
1394ad6030f6SAlex Crichton
1395ad6030f6SAlex Crichton // If any of `expected` is removed and the module fails to validate,
1396ad6030f6SAlex Crichton // then that means the module requires that feature. Remove that
1397ad6030f6SAlex Crichton // from the set of features we're then expecting.
1398ad6030f6SAlex Crichton for feature in expected.iter() {
1399ad6030f6SAlex Crichton let ok =
1400ad6030f6SAlex Crichton Validator::new_with_features(WasmFeatures::all() ^ feature).validate_all(&wasm);
1401ad6030f6SAlex Crichton if ok.is_err() {
1402ad6030f6SAlex Crichton expected ^= feature;
1403ad6030f6SAlex Crichton }
1404ad6030f6SAlex Crichton }
1405ad6030f6SAlex Crichton
1406ad6030f6SAlex Crichton Ok(expected.is_empty())
1407ad6030f6SAlex Crichton });
1408ad6030f6SAlex Crichton
1409ad6030f6SAlex Crichton if !ok {
1410ad6030f6SAlex Crichton panic!("never generated wasm module using {expected:?}");
1411ad6030f6SAlex Crichton }
1412ec3b2d22SNick Fitzgerald }
141383575995SAlex Crichton
141483575995SAlex Crichton #[test]
wast_smoke_test()141583575995SAlex Crichton fn wast_smoke_test() {
141683575995SAlex Crichton test_n_times(50, |(), u| super::wast_test(u));
141783575995SAlex Crichton }
1418ec3b2d22SNick Fitzgerald }
1419