1 use crate::generators::{Config, DiffValue, DiffValueType};
2 use crate::oracles::engine::{DiffEngine, DiffInstance};
3 use anyhow::{bail, Error, Result};
4 use std::cell::RefCell;
5 use std::rc::Rc;
6 use std::sync::Once;
7 use wasmtime::Trap;
8 
9 pub struct V8Engine {
10     isolate: Rc<RefCell<v8::OwnedIsolate>>,
11 }
12 
13 impl V8Engine {
14     pub fn new(config: &mut Config) -> V8Engine {
15         static INIT: Once = Once::new();
16 
17         INIT.call_once(|| {
18             let platform = v8::new_default_platform(0, false).make_shared();
19             v8::V8::initialize_platform(platform);
20             v8::V8::initialize();
21         });
22 
23         let config = &mut config.module_config.config;
24         // FIXME: reference types are disabled for now as we seemingly keep finding
25         // a segfault in v8. This is found relatively quickly locally and keeps
26         // getting found by oss-fuzz and currently we don't think that there's
27         // really much we can do about it. For the time being disable reference
28         // types entirely. An example bug is
29         // https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=45662
30         config.reference_types_enabled = false;
31 
32         config.min_memories = config.min_memories.min(1);
33         config.max_memories = config.max_memories.min(1);
34         config.memory64_enabled = false;
35 
36         Self {
37             isolate: Rc::new(RefCell::new(v8::Isolate::new(Default::default()))),
38         }
39     }
40 }
41 
42 impl DiffEngine for V8Engine {
43     fn name(&self) -> &'static str {
44         "v8"
45     }
46 
47     fn instantiate(&mut self, wasm: &[u8]) -> Result<Box<dyn DiffInstance>> {
48         // Setup a new `Context` in which we'll be creating this instance and
49         // executing code.
50         let mut isolate = self.isolate.borrow_mut();
51         let isolate = &mut **isolate;
52         let mut scope = v8::HandleScope::new(isolate);
53         let context = v8::Context::new(&mut scope);
54         let global = context.global(&mut scope);
55         let mut scope = v8::ContextScope::new(&mut scope, context);
56 
57         // Move the `wasm` into JS and then invoke `new WebAssembly.Module`.
58         let buf = v8::ArrayBuffer::new_backing_store_from_boxed_slice(wasm.into());
59         let buf = v8::SharedRef::from(buf);
60         let name = v8::String::new(&mut scope, "WASM_BINARY").unwrap();
61         let buf = v8::ArrayBuffer::with_backing_store(&mut scope, &buf);
62         global.set(&mut scope, name.into(), buf.into());
63         let module = eval(&mut scope, "new WebAssembly.Module(WASM_BINARY)").unwrap();
64         let name = v8::String::new(&mut scope, "WASM_MODULE").unwrap();
65         global.set(&mut scope, name.into(), module);
66 
67         // Using our `WASM_MODULE` run instantiation. Note that it's guaranteed
68         // that nothing is imported into differentially-executed modules so
69         // this is expected to only take the module argument.
70         let instance = eval(&mut scope, "new WebAssembly.Instance(WASM_MODULE)")?;
71 
72         Ok(Box::new(V8Instance {
73             isolate: self.isolate.clone(),
74             context: v8::Global::new(&mut scope, context),
75             instance: v8::Global::new(&mut scope, instance),
76         }))
77     }
78 
79     fn assert_error_match(&self, wasmtime: &Trap, err: &Error) {
80         let v8 = err.to_string();
81         let wasmtime_msg = wasmtime.to_string();
82         let verify_wasmtime = |msg: &str| {
83             assert!(wasmtime_msg.contains(msg), "{}\n!=\n{}", wasmtime_msg, v8);
84         };
85         let verify_v8 = |msg: &[&str]| {
86             assert!(
87                 msg.iter().any(|msg| v8.contains(msg)),
88                 "{:?}\n\t!=\n{}",
89                 wasmtime_msg,
90                 v8
91             );
92         };
93         match wasmtime {
94             Trap::MemoryOutOfBounds => {
95                 return verify_v8(&["memory access out of bounds", "is out of bounds"])
96             }
97             Trap::UnreachableCodeReached => {
98                 return verify_v8(&[
99                     "unreachable",
100                     // All the wasms we test use wasm-smith's
101                     // `ensure_termination` option which will `unreachable` when
102                     // "fuel" runs out within the wasm module itself. This
103                     // sometimes manifests as a call stack size exceeded in v8,
104                     // however, since v8 sometimes has different limits on the
105                     // call-stack especially when it's run multiple times. To
106                     // get these error messages to line up allow v8 to say the
107                     // call stack size exceeded when wasmtime says we hit
108                     // unreachable.
109                     "Maximum call stack size exceeded",
110                 ]);
111             }
112             Trap::IntegerDivisionByZero => {
113                 return verify_v8(&["divide by zero", "remainder by zero"])
114             }
115             Trap::StackOverflow => {
116                 return verify_v8(&[
117                     "call stack size exceeded",
118                     // Similar to the above comment in `UnreachableCodeReached`
119                     // if wasmtime hits a stack overflow but v8 ran all the way
120                     // to when the `unreachable` instruction was hit then that's
121                     // ok. This just means that wasmtime either has less optimal
122                     // codegen or different limits on the stack than v8 does,
123                     // which isn't an issue per-se.
124                     "unreachable",
125                 ]);
126             }
127             Trap::IndirectCallToNull => return verify_v8(&["null function"]),
128             Trap::TableOutOfBounds => {
129                 return verify_v8(&[
130                     "table initializer is out of bounds",
131                     "table index is out of bounds",
132                 ])
133             }
134             Trap::BadSignature => return verify_v8(&["function signature mismatch"]),
135             Trap::IntegerOverflow | Trap::BadConversionToInteger => {
136                 return verify_v8(&[
137                     "float unrepresentable in integer range",
138                     "divide result unrepresentable",
139                 ])
140             }
141             other => log::debug!("unknown code {:?}", other),
142         }
143 
144         verify_wasmtime("not possibly present in an error, just panic please");
145     }
146 
147     fn is_stack_overflow(&self, err: &Error) -> bool {
148         err.to_string().contains("Maximum call stack size exceeded")
149     }
150 }
151 
152 struct V8Instance {
153     isolate: Rc<RefCell<v8::OwnedIsolate>>,
154     context: v8::Global<v8::Context>,
155     instance: v8::Global<v8::Value>,
156 }
157 
158 impl DiffInstance for V8Instance {
159     fn name(&self) -> &'static str {
160         "v8"
161     }
162 
163     fn evaluate(
164         &mut self,
165         function_name: &str,
166         arguments: &[DiffValue],
167         result_tys: &[DiffValueType],
168     ) -> Result<Option<Vec<DiffValue>>> {
169         let mut isolate = self.isolate.borrow_mut();
170         let isolate = &mut **isolate;
171         let mut scope = v8::HandleScope::new(isolate);
172         let context = v8::Local::new(&mut scope, &self.context);
173         let global = context.global(&mut scope);
174         let mut scope = v8::ContextScope::new(&mut scope, context);
175 
176         // See https://webassembly.github.io/spec/js-api/index.html#tojsvalue
177         // for how the Wasm-to-JS conversions are done.
178         let mut params = Vec::new();
179         for arg in arguments {
180             params.push(match *arg {
181                 DiffValue::I32(n) => v8::Number::new(&mut scope, n.into()).into(),
182                 DiffValue::F32(n) => v8::Number::new(&mut scope, f32::from_bits(n).into()).into(),
183                 DiffValue::F64(n) => v8::Number::new(&mut scope, f64::from_bits(n)).into(),
184                 DiffValue::I64(n) => v8::BigInt::new_from_i64(&mut scope, n).into(),
185                 DiffValue::FuncRef { null } | DiffValue::ExternRef { null } => {
186                     assert!(null);
187                     v8::null(&mut scope).into()
188                 }
189                 // JS doesn't support v128 parameters
190                 DiffValue::V128(_) => return Ok(None),
191                 DiffValue::AnyRef { .. } => unimplemented!(),
192             });
193         }
194         // JS doesn't support v128 return values
195         for ty in result_tys {
196             if let DiffValueType::V128 = ty {
197                 return Ok(None);
198             }
199         }
200 
201         let name = v8::String::new(&mut scope, "WASM_INSTANCE").unwrap();
202         let instance = v8::Local::new(&mut scope, &self.instance);
203         global.set(&mut scope, name.into(), instance);
204         let name = v8::String::new(&mut scope, "EXPORT_NAME").unwrap();
205         let func_name = v8::String::new(&mut scope, function_name).unwrap();
206         global.set(&mut scope, name.into(), func_name.into());
207         let name = v8::String::new(&mut scope, "ARGS").unwrap();
208         let params = v8::Array::new_with_elements(&mut scope, &params);
209         global.set(&mut scope, name.into(), params.into());
210         let v8_vals = eval(&mut scope, "WASM_INSTANCE.exports[EXPORT_NAME](...ARGS)")?;
211 
212         let mut results = Vec::new();
213         match result_tys.len() {
214             0 => assert!(v8_vals.is_undefined()),
215             1 => results.push(get_diff_value(&v8_vals, result_tys[0], &mut scope)),
216             _ => {
217                 let array = v8::Local::<'_, v8::Array>::try_from(v8_vals).unwrap();
218                 for (i, ty) in result_tys.iter().enumerate() {
219                     let v8 = array.get_index(&mut scope, i as u32).unwrap();
220                     results.push(get_diff_value(&v8, *ty, &mut scope));
221                 }
222             }
223         }
224         Ok(Some(results))
225     }
226 
227     fn get_global(&mut self, global_name: &str, ty: DiffValueType) -> Option<DiffValue> {
228         if let DiffValueType::V128 = ty {
229             return None;
230         }
231         let mut isolate = self.isolate.borrow_mut();
232         let mut scope = v8::HandleScope::new(&mut *isolate);
233         let context = v8::Local::new(&mut scope, &self.context);
234         let global = context.global(&mut scope);
235         let mut scope = v8::ContextScope::new(&mut scope, context);
236 
237         let name = v8::String::new(&mut scope, "GLOBAL_NAME").unwrap();
238         let memory_name = v8::String::new(&mut scope, global_name).unwrap();
239         global.set(&mut scope, name.into(), memory_name.into());
240         let val = eval(&mut scope, "WASM_INSTANCE.exports[GLOBAL_NAME].value").unwrap();
241         Some(get_diff_value(&val, ty, &mut scope))
242     }
243 
244     fn get_memory(&mut self, memory_name: &str, shared: bool) -> Option<Vec<u8>> {
245         let mut isolate = self.isolate.borrow_mut();
246         let mut scope = v8::HandleScope::new(&mut *isolate);
247         let context = v8::Local::new(&mut scope, &self.context);
248         let global = context.global(&mut scope);
249         let mut scope = v8::ContextScope::new(&mut scope, context);
250 
251         let name = v8::String::new(&mut scope, "MEMORY_NAME").unwrap();
252         let memory_name = v8::String::new(&mut scope, memory_name).unwrap();
253         global.set(&mut scope, name.into(), memory_name.into());
254         let v8 = eval(&mut scope, "WASM_INSTANCE.exports[MEMORY_NAME].buffer").unwrap();
255         let v8_data = if shared {
256             v8::Local::<'_, v8::SharedArrayBuffer>::try_from(v8)
257                 .unwrap()
258                 .get_backing_store()
259         } else {
260             v8::Local::<'_, v8::ArrayBuffer>::try_from(v8)
261                 .unwrap()
262                 .get_backing_store()
263         };
264 
265         Some(v8_data.iter().map(|i| i.get()).collect())
266     }
267 }
268 
269 /// Evaluates the JS `code` within `scope`, returning either the result of the
270 /// computation or the stringified exception if one happened.
271 fn eval<'s>(scope: &mut v8::HandleScope<'s>, code: &str) -> Result<v8::Local<'s, v8::Value>> {
272     let mut tc = v8::TryCatch::new(scope);
273     let mut scope = v8::EscapableHandleScope::new(&mut tc);
274     let source = v8::String::new(&mut scope, code).unwrap();
275     let script = v8::Script::compile(&mut scope, source, None).unwrap();
276     match script.run(&mut scope) {
277         Some(val) => Ok(scope.escape(val)),
278         None => {
279             drop(scope);
280             assert!(tc.has_caught());
281             bail!(
282                 "{}",
283                 tc.message()
284                     .unwrap()
285                     .get(&mut tc)
286                     .to_rust_string_lossy(&mut tc)
287             )
288         }
289     }
290 }
291 
292 fn get_diff_value(
293     val: &v8::Local<'_, v8::Value>,
294     ty: DiffValueType,
295     scope: &mut v8::HandleScope<'_>,
296 ) -> DiffValue {
297     match ty {
298         DiffValueType::I32 => DiffValue::I32(val.to_int32(scope).unwrap().value()),
299         DiffValueType::I64 => {
300             let (val, todo) = val.to_big_int(scope).unwrap().i64_value();
301             assert!(todo);
302             DiffValue::I64(val)
303         }
304         DiffValueType::F32 => {
305             DiffValue::F32((val.to_number(scope).unwrap().value() as f32).to_bits())
306         }
307         DiffValueType::F64 => DiffValue::F64(val.to_number(scope).unwrap().value().to_bits()),
308         DiffValueType::FuncRef => DiffValue::FuncRef {
309             null: val.is_null(),
310         },
311         DiffValueType::ExternRef => DiffValue::ExternRef {
312             null: val.is_null(),
313         },
314         DiffValueType::AnyRef => unimplemented!(),
315         DiffValueType::V128 => unreachable!(),
316     }
317 }
318 
319 #[test]
320 fn smoke() {
321     crate::oracles::engine::smoke_test_engine(|_, config| Ok(V8Engine::new(config)))
322 }
323