1 //! Evaluate an exported Wasm function using the wasmi interpreter.
2 
3 use crate::generators::{Config, DiffValue, DiffValueType};
4 use crate::oracles::engine::{DiffEngine, DiffInstance};
5 use anyhow::{Context, Error, Result};
6 use wasmtime::Trap;
7 
8 /// A wrapper for `wasmi` as a [`DiffEngine`].
9 pub struct WasmiEngine {
10     engine: wasmi::Engine,
11 }
12 
13 impl WasmiEngine {
14     pub(crate) fn new(config: &mut Config) -> Self {
15         let config = &mut config.module_config.config;
16         // Force generated Wasm modules to never have features that Wasmi doesn't support.
17         config.relaxed_simd_enabled = false;
18         config.threads_enabled = false;
19         config.exceptions_enabled = false;
20         config.gc_enabled = false;
21 
22         // FIXME: once the active fuzz bug for wasmi's simd differential fuzzing
23         // has been fixed and we've updated then this should be re-enabled.
24         config.simd_enabled = false;
25 
26         let mut wasmi_config = wasmi::Config::default();
27         wasmi_config
28             .consume_fuel(false)
29             .floats(true)
30             .wasm_mutable_global(true)
31             .wasm_sign_extension(config.sign_extension_ops_enabled)
32             .wasm_saturating_float_to_int(config.saturating_float_to_int_enabled)
33             .wasm_multi_value(config.multi_value_enabled)
34             .wasm_bulk_memory(config.bulk_memory_enabled)
35             .wasm_reference_types(config.reference_types_enabled)
36             .wasm_tail_call(config.tail_call_enabled)
37             .wasm_multi_memory(config.max_memories > 1)
38             .wasm_extended_const(config.extended_const_enabled)
39             .wasm_custom_page_sizes(config.custom_page_sizes_enabled)
40             .wasm_memory64(config.memory64_enabled)
41             .wasm_simd(config.simd_enabled)
42             .wasm_wide_arithmetic(config.wide_arithmetic_enabled);
43         Self {
44             engine: wasmi::Engine::new(&wasmi_config),
45         }
46     }
47 
48     fn trap_code(&self, err: &Error) -> Option<wasmi::core::TrapCode> {
49         let err = err.downcast_ref::<wasmi::Error>()?;
50         if let Some(code) = err.as_trap_code() {
51             return Some(code);
52         }
53 
54         match err.kind() {
55             wasmi::errors::ErrorKind::Instantiation(
56                 wasmi::errors::InstantiationError::ElementSegmentDoesNotFit { .. },
57             ) => Some(wasmi::core::TrapCode::TableOutOfBounds),
58             wasmi::errors::ErrorKind::Memory(wasmi::errors::MemoryError::OutOfBoundsAccess) => {
59                 Some(wasmi::core::TrapCode::MemoryOutOfBounds)
60             }
61             _ => {
62                 log::trace!("unknown wasmi error: {:?}", err.kind());
63                 None
64             }
65         }
66     }
67 }
68 
69 impl DiffEngine for WasmiEngine {
70     fn name(&self) -> &'static str {
71         "wasmi"
72     }
73 
74     fn instantiate(&mut self, wasm: &[u8]) -> Result<Box<dyn DiffInstance>> {
75         let module =
76             wasmi::Module::new(&self.engine, wasm).context("unable to validate Wasm module")?;
77         let mut store = wasmi::Store::new(&self.engine, ());
78         let instance = wasmi::Linker::<()>::new(&self.engine)
79             .instantiate(&mut store, &module)
80             .and_then(|i| i.start(&mut store))
81             .context("unable to instantiate module in wasmi")?;
82         Ok(Box::new(WasmiInstance { store, instance }))
83     }
84 
85     fn assert_error_match(&self, lhs: &Error, rhs: &Trap) {
86         match self.trap_code(lhs) {
87             Some(code) => assert_eq!(wasmi_to_wasmtime_trap_code(code), *rhs),
88             None => panic!("unexpected wasmi error {lhs:?}"),
89         }
90     }
91 
92     fn is_non_deterministic_error(&self, err: &Error) -> bool {
93         matches!(
94             self.trap_code(err),
95             Some(wasmi::core::TrapCode::StackOverflow)
96         )
97     }
98 }
99 
100 /// Converts `wasmi` trap code to `wasmtime` trap code.
101 fn wasmi_to_wasmtime_trap_code(trap: wasmi::core::TrapCode) -> Trap {
102     use wasmi::core::TrapCode;
103     match trap {
104         TrapCode::UnreachableCodeReached => Trap::UnreachableCodeReached,
105         TrapCode::MemoryOutOfBounds => Trap::MemoryOutOfBounds,
106         TrapCode::TableOutOfBounds => Trap::TableOutOfBounds,
107         TrapCode::IndirectCallToNull => Trap::IndirectCallToNull,
108         TrapCode::IntegerDivisionByZero => Trap::IntegerDivisionByZero,
109         TrapCode::IntegerOverflow => Trap::IntegerOverflow,
110         TrapCode::BadConversionToInteger => Trap::BadConversionToInteger,
111         TrapCode::StackOverflow => Trap::StackOverflow,
112         TrapCode::BadSignature => Trap::BadSignature,
113         TrapCode::OutOfFuel => unimplemented!("built-in fuel metering is unused"),
114         TrapCode::GrowthOperationLimited => unimplemented!("resource limiter is unused"),
115     }
116 }
117 
118 /// A wrapper for `wasmi` Wasm instances.
119 struct WasmiInstance {
120     store: wasmi::Store<()>,
121     instance: wasmi::Instance,
122 }
123 
124 impl DiffInstance for WasmiInstance {
125     fn name(&self) -> &'static str {
126         "wasmi"
127     }
128 
129     fn evaluate(
130         &mut self,
131         function_name: &str,
132         arguments: &[DiffValue],
133         result_tys: &[DiffValueType],
134     ) -> Result<Option<Vec<DiffValue>>> {
135         let function = self
136             .instance
137             .get_export(&self.store, function_name)
138             .and_then(wasmi::Extern::into_func)
139             .unwrap();
140         let arguments: Vec<_> = arguments.iter().map(|x| x.into()).collect();
141         let mut results = vec![wasmi::Val::I32(0); result_tys.len()];
142         function
143             .call(&mut self.store, &arguments, &mut results)
144             .context("wasmi function trap")?;
145         Ok(Some(results.into_iter().map(Into::into).collect()))
146     }
147 
148     fn get_global(&mut self, name: &str, _ty: DiffValueType) -> Option<DiffValue> {
149         Some(
150             self.instance
151                 .get_export(&self.store, name)
152                 .unwrap()
153                 .into_global()
154                 .unwrap()
155                 .get(&self.store)
156                 .into(),
157         )
158     }
159 
160     fn get_memory(&mut self, name: &str, shared: bool) -> Option<Vec<u8>> {
161         assert!(!shared);
162         Some(
163             self.instance
164                 .get_export(&self.store, name)
165                 .unwrap()
166                 .into_memory()
167                 .unwrap()
168                 .data(&self.store)
169                 .to_vec(),
170         )
171     }
172 }
173 
174 impl From<&DiffValue> for wasmi::Val {
175     fn from(v: &DiffValue) -> Self {
176         use wasmi::Val as WasmiValue;
177         match *v {
178             DiffValue::I32(n) => WasmiValue::I32(n),
179             DiffValue::I64(n) => WasmiValue::I64(n),
180             DiffValue::F32(n) => WasmiValue::F32(wasmi::core::F32::from_bits(n)),
181             DiffValue::F64(n) => WasmiValue::F64(wasmi::core::F64::from_bits(n)),
182             DiffValue::V128(n) => WasmiValue::V128(wasmi::core::V128::from(n)),
183             DiffValue::FuncRef { null } => {
184                 assert!(null);
185                 WasmiValue::FuncRef(wasmi::FuncRef::null())
186             }
187             DiffValue::ExternRef { null } => {
188                 assert!(null);
189                 WasmiValue::ExternRef(wasmi::ExternRef::null())
190             }
191             DiffValue::AnyRef { .. } => unimplemented!(),
192         }
193     }
194 }
195 
196 impl From<wasmi::Val> for DiffValue {
197     fn from(value: wasmi::Val) -> Self {
198         use wasmi::Val as WasmiValue;
199         match value {
200             WasmiValue::I32(n) => DiffValue::I32(n),
201             WasmiValue::I64(n) => DiffValue::I64(n),
202             WasmiValue::F32(n) => DiffValue::F32(n.to_bits()),
203             WasmiValue::F64(n) => DiffValue::F64(n.to_bits()),
204             WasmiValue::V128(n) => DiffValue::V128(n.as_u128()),
205             WasmiValue::FuncRef(f) => DiffValue::FuncRef { null: f.is_null() },
206             WasmiValue::ExternRef(e) => DiffValue::ExternRef { null: e.is_null() },
207         }
208     }
209 }
210 
211 #[cfg(test)]
212 mod tests {
213     use super::*;
214 
215     #[test]
216     fn smoke() {
217         crate::oracles::engine::smoke_test_engine(|_, config| Ok(WasmiEngine::new(config)))
218     }
219 }
220