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         let mut wasmi_config = wasmi::Config::default();
23         wasmi_config
24             .consume_fuel(false)
25             .floats(true)
26             .wasm_mutable_global(true)
27             .wasm_sign_extension(config.sign_extension_ops_enabled)
28             .wasm_saturating_float_to_int(config.saturating_float_to_int_enabled)
29             .wasm_multi_value(config.multi_value_enabled)
30             .wasm_bulk_memory(config.bulk_memory_enabled)
31             .wasm_reference_types(config.reference_types_enabled)
32             .wasm_tail_call(config.tail_call_enabled)
33             .wasm_multi_memory(config.max_memories > 1)
34             .wasm_extended_const(config.extended_const_enabled)
35             .wasm_custom_page_sizes(config.custom_page_sizes_enabled)
36             .wasm_memory64(config.memory64_enabled)
37             .wasm_simd(config.simd_enabled)
38             .wasm_wide_arithmetic(config.wide_arithmetic_enabled);
39         Self {
40             engine: wasmi::Engine::new(&wasmi_config),
41         }
42     }
43 
44     fn trap_code(&self, err: &Error) -> Option<wasmi::core::TrapCode> {
45         let err = err.downcast_ref::<wasmi::Error>()?;
46         if let Some(code) = err.as_trap_code() {
47             return Some(code);
48         }
49 
50         match err.kind() {
51             wasmi::errors::ErrorKind::Instantiation(
52                 wasmi::errors::InstantiationError::ElementSegmentDoesNotFit { .. },
53             ) => Some(wasmi::core::TrapCode::TableOutOfBounds),
54             wasmi::errors::ErrorKind::Memory(wasmi::errors::MemoryError::OutOfBoundsAccess) => {
55                 Some(wasmi::core::TrapCode::MemoryOutOfBounds)
56             }
57             wasmi::errors::ErrorKind::Table(wasmi::errors::TableError::CopyOutOfBounds) => {
58                 Some(wasmi::core::TrapCode::TableOutOfBounds)
59             }
60             _ => {
61                 log::trace!("unknown wasmi error: {:?}", err.kind());
62                 None
63             }
64         }
65     }
66 }
67 
68 impl DiffEngine for WasmiEngine {
69     fn name(&self) -> &'static str {
70         "wasmi"
71     }
72 
73     fn instantiate(&mut self, wasm: &[u8]) -> Result<Box<dyn DiffInstance>> {
74         let module =
75             wasmi::Module::new(&self.engine, wasm).context("unable to validate Wasm module")?;
76         let mut store = wasmi::Store::new(&self.engine, ());
77         let instance = wasmi::Linker::<()>::new(&self.engine)
78             .instantiate_and_start(&mut store, &module)
79             .context("unable to instantiate module in wasmi")?;
80         Ok(Box::new(WasmiInstance { store, instance }))
81     }
82 
83     fn assert_error_match(&self, lhs: &Error, rhs: &Trap) {
84         match self.trap_code(lhs) {
85             Some(code) => assert_eq!(wasmi_to_wasmtime_trap_code(code), *rhs),
86             None => panic!("unexpected wasmi error {lhs:?}"),
87         }
88     }
89 
90     fn is_non_deterministic_error(&self, err: &Error) -> bool {
91         matches!(
92             self.trap_code(err),
93             Some(wasmi::core::TrapCode::StackOverflow)
94         )
95     }
96 }
97 
98 /// Converts `wasmi` trap code to `wasmtime` trap code.
99 fn wasmi_to_wasmtime_trap_code(trap: wasmi::core::TrapCode) -> Trap {
100     use wasmi::core::TrapCode;
101     match trap {
102         TrapCode::UnreachableCodeReached => Trap::UnreachableCodeReached,
103         TrapCode::MemoryOutOfBounds => Trap::MemoryOutOfBounds,
104         TrapCode::TableOutOfBounds => Trap::TableOutOfBounds,
105         TrapCode::IndirectCallToNull => Trap::IndirectCallToNull,
106         TrapCode::IntegerDivisionByZero => Trap::IntegerDivisionByZero,
107         TrapCode::IntegerOverflow => Trap::IntegerOverflow,
108         TrapCode::BadConversionToInteger => Trap::BadConversionToInteger,
109         TrapCode::StackOverflow => Trap::StackOverflow,
110         TrapCode::BadSignature => Trap::BadSignature,
111         TrapCode::OutOfFuel => unimplemented!("built-in fuel metering is unused"),
112         TrapCode::GrowthOperationLimited => unimplemented!("resource limiter is unused"),
113     }
114 }
115 
116 /// A wrapper for `wasmi` Wasm instances.
117 struct WasmiInstance {
118     store: wasmi::Store<()>,
119     instance: wasmi::Instance,
120 }
121 
122 impl DiffInstance for WasmiInstance {
123     fn name(&self) -> &'static str {
124         "wasmi"
125     }
126 
127     fn evaluate(
128         &mut self,
129         function_name: &str,
130         arguments: &[DiffValue],
131         result_tys: &[DiffValueType],
132     ) -> Result<Option<Vec<DiffValue>>> {
133         let function = self
134             .instance
135             .get_export(&self.store, function_name)
136             .and_then(wasmi::Extern::into_func)
137             .unwrap();
138         let arguments: Vec<_> = arguments.iter().map(|x| x.into()).collect();
139         let mut results = vec![wasmi::Val::I32(0); result_tys.len()];
140         function
141             .call(&mut self.store, &arguments, &mut results)
142             .context("wasmi function trap")?;
143         Ok(Some(results.into_iter().map(Into::into).collect()))
144     }
145 
146     fn get_global(&mut self, name: &str, _ty: DiffValueType) -> Option<DiffValue> {
147         Some(
148             self.instance
149                 .get_export(&self.store, name)
150                 .unwrap()
151                 .into_global()
152                 .unwrap()
153                 .get(&self.store)
154                 .into(),
155         )
156     }
157 
158     fn get_memory(&mut self, name: &str, shared: bool) -> Option<Vec<u8>> {
159         assert!(!shared);
160         Some(
161             self.instance
162                 .get_export(&self.store, name)
163                 .unwrap()
164                 .into_memory()
165                 .unwrap()
166                 .data(&self.store)
167                 .to_vec(),
168         )
169     }
170 }
171 
172 impl From<&DiffValue> for wasmi::Val {
173     fn from(v: &DiffValue) -> Self {
174         use wasmi::Val as WasmiValue;
175         match *v {
176             DiffValue::I32(n) => WasmiValue::I32(n),
177             DiffValue::I64(n) => WasmiValue::I64(n),
178             DiffValue::F32(n) => WasmiValue::F32(wasmi::core::F32::from_bits(n)),
179             DiffValue::F64(n) => WasmiValue::F64(wasmi::core::F64::from_bits(n)),
180             DiffValue::V128(n) => WasmiValue::V128(wasmi::core::V128::from(n)),
181             DiffValue::FuncRef { null } => {
182                 assert!(null);
183                 WasmiValue::default(wasmi::ValType::FuncRef)
184             }
185             DiffValue::ExternRef { null } => {
186                 assert!(null);
187                 WasmiValue::default(wasmi::ValType::ExternRef)
188             }
189             DiffValue::AnyRef { .. } => unimplemented!(),
190             DiffValue::ExnRef { .. } => unimplemented!(),
191             DiffValue::ContRef { .. } => 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