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