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.simd_enabled = false;
18         config.relaxed_simd_enabled = false;
19         config.memory64_enabled = false;
20         config.threads_enabled = false;
21         config.exceptions_enabled = false;
22         config.gc_enabled = false;
23         config.max_memories = config.max_memories.min(1);
24         config.min_memories = config.min_memories.min(1);
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_extended_const(true);
38         Self {
39             engine: wasmi::Engine::new(&wasmi_config),
40         }
41     }
42 }
43 
44 impl DiffEngine for WasmiEngine {
45     fn name(&self) -> &'static str {
46         "wasmi"
47     }
48 
49     fn instantiate(&mut self, wasm: &[u8]) -> Result<Box<dyn DiffInstance>> {
50         let module =
51             wasmi::Module::new(&self.engine, wasm).context("unable to validate Wasm module")?;
52         let mut store = wasmi::Store::new(&self.engine, ());
53         let instance = wasmi::Linker::<()>::new(&self.engine)
54             .instantiate(&mut store, &module)
55             .and_then(|i| i.start(&mut store))
56             .context("unable to instantiate module in wasmi")?;
57         Ok(Box::new(WasmiInstance { store, instance }))
58     }
59 
60     fn assert_error_match(&self, trap: &Trap, err: &Error) {
61         // Acquire a `wasmi::Trap` from the wasmi error which we'll use to
62         // assert that it has the same kind of trap as the wasmtime-based trap.
63         let wasmi = match err.downcast_ref::<wasmi::Error>() {
64             Some(wasmi::Error::Trap(trap)) => trap,
65 
66             // Out-of-bounds data segments turn into this category which
67             // Wasmtime reports as a `MemoryOutOfBounds`.
68             Some(wasmi::Error::Memory(msg)) => {
69                 assert_eq!(
70                     *trap,
71                     Trap::MemoryOutOfBounds,
72                     "wasmtime error did not match wasmi: {msg}"
73                 );
74                 return;
75             }
76 
77             // Ignore this for now, looks like "elements segment does not fit"
78             // falls into this category and to avoid doing string matching this
79             // is just ignored.
80             Some(wasmi::Error::Instantiation(msg)) => {
81                 log::debug!("ignoring wasmi instantiation error: {msg}");
82                 return;
83             }
84 
85             Some(other) => panic!("unexpected wasmi error: {other}"),
86 
87             None => err
88                 .downcast_ref::<wasmi::core::Trap>()
89                 .expect(&format!("not a trap: {err:?}")),
90         };
91         assert!(wasmi.trap_code().is_some());
92         assert_eq!(
93             wasmi_to_wasmtime_trap_code(wasmi.trap_code().unwrap()),
94             *trap
95         );
96     }
97 
98     fn is_stack_overflow(&self, err: &Error) -> bool {
99         let trap = match err.downcast_ref::<wasmi::Error>() {
100             Some(wasmi::Error::Trap(trap)) => trap,
101             Some(_) => return false,
102             None => match err.downcast_ref::<wasmi::core::Trap>() {
103                 Some(trap) => trap,
104                 None => return false,
105             },
106         };
107         matches!(trap.trap_code(), Some(wasmi::core::TrapCode::StackOverflow))
108     }
109 }
110 
111 /// Converts `wasmi` trap code to `wasmtime` trap code.
112 fn wasmi_to_wasmtime_trap_code(trap: wasmi::core::TrapCode) -> Trap {
113     use wasmi::core::TrapCode;
114     match trap {
115         TrapCode::UnreachableCodeReached => Trap::UnreachableCodeReached,
116         TrapCode::MemoryOutOfBounds => Trap::MemoryOutOfBounds,
117         TrapCode::TableOutOfBounds => Trap::TableOutOfBounds,
118         TrapCode::IndirectCallToNull => Trap::IndirectCallToNull,
119         TrapCode::IntegerDivisionByZero => Trap::IntegerDivisionByZero,
120         TrapCode::IntegerOverflow => Trap::IntegerOverflow,
121         TrapCode::BadConversionToInteger => Trap::BadConversionToInteger,
122         TrapCode::StackOverflow => Trap::StackOverflow,
123         TrapCode::BadSignature => Trap::BadSignature,
124         TrapCode::OutOfFuel => unimplemented!("built-in fuel metering is unused"),
125         TrapCode::GrowthOperationLimited => unimplemented!("resource limiter is unused"),
126     }
127 }
128 
129 /// A wrapper for `wasmi` Wasm instances.
130 struct WasmiInstance {
131     store: wasmi::Store<()>,
132     instance: wasmi::Instance,
133 }
134 
135 impl DiffInstance for WasmiInstance {
136     fn name(&self) -> &'static str {
137         "wasmi"
138     }
139 
140     fn evaluate(
141         &mut self,
142         function_name: &str,
143         arguments: &[DiffValue],
144         result_tys: &[DiffValueType],
145     ) -> Result<Option<Vec<DiffValue>>> {
146         let function = self
147             .instance
148             .get_export(&self.store, function_name)
149             .and_then(wasmi::Extern::into_func)
150             .unwrap();
151         let arguments: Vec<_> = arguments.iter().map(|x| x.into()).collect();
152         let mut results = vec![wasmi::Value::I32(0); result_tys.len()];
153         function
154             .call(&mut self.store, &arguments, &mut results)
155             .context("wasmi function trap")?;
156         Ok(Some(results.into_iter().map(Into::into).collect()))
157     }
158 
159     fn get_global(&mut self, name: &str, _ty: DiffValueType) -> Option<DiffValue> {
160         Some(
161             self.instance
162                 .get_export(&self.store, name)
163                 .unwrap()
164                 .into_global()
165                 .unwrap()
166                 .get(&self.store)
167                 .into(),
168         )
169     }
170 
171     fn get_memory(&mut self, name: &str, shared: bool) -> Option<Vec<u8>> {
172         assert!(!shared);
173         Some(
174             self.instance
175                 .get_export(&self.store, name)
176                 .unwrap()
177                 .into_memory()
178                 .unwrap()
179                 .data(&self.store)
180                 .to_vec(),
181         )
182     }
183 }
184 
185 impl From<&DiffValue> for wasmi::Value {
186     fn from(v: &DiffValue) -> Self {
187         use wasmi::Value as WasmiValue;
188         match *v {
189             DiffValue::I32(n) => WasmiValue::I32(n),
190             DiffValue::I64(n) => WasmiValue::I64(n),
191             DiffValue::F32(n) => WasmiValue::F32(wasmi::core::F32::from_bits(n)),
192             DiffValue::F64(n) => WasmiValue::F64(wasmi::core::F64::from_bits(n)),
193             DiffValue::V128(_) => unimplemented!(),
194             DiffValue::FuncRef { null } => {
195                 assert!(null);
196                 WasmiValue::FuncRef(wasmi::FuncRef::null())
197             }
198             DiffValue::ExternRef { null } => {
199                 assert!(null);
200                 WasmiValue::ExternRef(wasmi::ExternRef::null())
201             }
202             DiffValue::AnyRef { .. } => unimplemented!(),
203         }
204     }
205 }
206 
207 impl From<wasmi::Value> for DiffValue {
208     fn from(value: wasmi::Value) -> Self {
209         use wasmi::Value as WasmiValue;
210         match value {
211             WasmiValue::I32(n) => DiffValue::I32(n),
212             WasmiValue::I64(n) => DiffValue::I64(n),
213             WasmiValue::F32(n) => DiffValue::F32(n.to_bits()),
214             WasmiValue::F64(n) => DiffValue::F64(n.to_bits()),
215             WasmiValue::FuncRef(f) => DiffValue::FuncRef { null: f.is_null() },
216             WasmiValue::ExternRef(e) => DiffValue::ExternRef { null: e.is_null() },
217         }
218     }
219 }
220 
221 #[cfg(test)]
222 mod tests {
223     use super::*;
224 
225     #[test]
226     fn smoke() {
227         crate::oracles::engine::smoke_test_engine(|_, config| Ok(WasmiEngine::new(config)))
228     }
229 }
230