1 //! Oracles.
2 //!
3 //! Oracles take a test case and determine whether we have a bug. For example,
4 //! one of the simplest oracles is to take a Wasm binary as our input test case,
5 //! validate and instantiate it, and (implicitly) check that no assertions
6 //! failed or segfaults happened. A more complicated oracle might compare the
7 //! result of executing a Wasm file with and without optimizations enabled, and
8 //! make sure that the two executions are observably identical.
9 //!
10 //! When an oracle finds a bug, it should report it to the fuzzing engine by
11 //! panicking.
12 
13 pub mod dummy;
14 
15 use anyhow::Context;
16 use arbitrary::Arbitrary;
17 use log::{debug, warn};
18 use std::sync::atomic::{AtomicUsize, Ordering::SeqCst};
19 use std::sync::{Arc, Condvar, Mutex};
20 use std::time::{Duration, Instant};
21 use wasmtime::*;
22 use wasmtime_wast::WastContext;
23 
24 static CNT: AtomicUsize = AtomicUsize::new(0);
25 
26 fn log_wasm(wasm: &[u8]) {
27     if !log::log_enabled!(log::Level::Debug) {
28         return;
29     }
30 
31     let i = CNT.fetch_add(1, SeqCst);
32     let name = format!("testcase{}.wasm", i);
33     std::fs::write(&name, wasm).expect("failed to write wasm file");
34     log::debug!("wrote wasm file to `{}`", name);
35     let wat = format!("testcase{}.wat", i);
36     match wasmprinter::print_bytes(wasm) {
37         Ok(s) => std::fs::write(&wat, s).expect("failed to write wat file"),
38         // If wasmprinter failed remove a `*.wat` file, if any, to avoid
39         // confusing a preexisting one with this wasm which failed to get
40         // printed.
41         Err(_) => drop(std::fs::remove_file(&wat)),
42     }
43 }
44 
45 fn create_store(engine: &Engine) -> Store<StoreLimits> {
46     let mut store = Store::new(
47         &engine,
48         StoreLimits {
49             // Limits tables/memories within a store to at most 1gb for now to
50             // exercise some larger address but not overflow various limits.
51             remaining_memory: 1 << 30,
52             oom: false,
53         },
54     );
55     store.limiter(|s| s as &mut dyn ResourceLimiter);
56     return store;
57 }
58 
59 struct StoreLimits {
60     /// Remaining memory, in bytes, left to allocate
61     remaining_memory: usize,
62     /// Whether or not an allocation request has been denied
63     oom: bool,
64 }
65 
66 impl StoreLimits {
67     fn alloc(&mut self, amt: usize) -> bool {
68         match self.remaining_memory.checked_sub(amt) {
69             Some(mem) => {
70                 self.remaining_memory = mem;
71                 true
72             }
73             None => {
74                 self.oom = true;
75                 false
76             }
77         }
78     }
79 }
80 
81 impl ResourceLimiter for StoreLimits {
82     fn memory_growing(&mut self, current: usize, desired: usize, _maximum: Option<usize>) -> bool {
83         self.alloc(desired - current)
84     }
85 
86     fn table_growing(&mut self, current: u32, desired: u32, _maximum: Option<u32>) -> bool {
87         let delta = (desired - current) as usize * std::mem::size_of::<usize>();
88         self.alloc(delta)
89     }
90 }
91 
92 /// Methods of timing out execution of a WebAssembly module
93 #[derive(Debug)]
94 pub enum Timeout {
95     /// No timeout is used, it should be guaranteed via some other means that
96     /// the input does not infinite loop.
97     None,
98     /// A time-based timeout is used with a sleeping thread sending a signal
99     /// after the specified duration.
100     Time(Duration),
101     /// Fuel-based timeouts are used where the specified fuel is all that the
102     /// provided wasm module is allowed to consume.
103     Fuel(u64),
104 }
105 
106 /// Instantiate the Wasm buffer, and implicitly fail if we have an unexpected
107 /// panic or segfault or anything else that can be detected "passively".
108 ///
109 /// Performs initial validation, and returns early if the Wasm is invalid.
110 ///
111 /// You can control which compiler is used via passing a `Strategy`.
112 pub fn instantiate(wasm: &[u8], known_valid: bool, strategy: Strategy) {
113     // Explicitly disable module linking for now since it's a breaking change to
114     // pre-module-linking modules due to imports
115     let mut cfg = crate::fuzz_default_config(strategy).unwrap();
116     cfg.wasm_module_linking(false);
117     instantiate_with_config(wasm, known_valid, cfg, Timeout::None);
118 }
119 
120 /// Instantiate the Wasm buffer, and implicitly fail if we have an unexpected
121 /// panic or segfault or anything else that can be detected "passively".
122 ///
123 /// The engine will be configured using provided config.
124 ///
125 /// See also `instantiate` functions.
126 pub fn instantiate_with_config(
127     wasm: &[u8],
128     known_valid: bool,
129     mut config: Config,
130     timeout: Timeout,
131 ) {
132     crate::init_fuzzing();
133 
134     config.interruptable(match &timeout {
135         Timeout::Time(_) => true,
136         _ => false,
137     });
138     config.consume_fuel(match &timeout {
139         Timeout::Fuel(_) => true,
140         _ => false,
141     });
142     let engine = Engine::new(&config).unwrap();
143     let mut store = create_store(&engine);
144 
145     let mut timeout_state = SignalOnDrop::default();
146     match timeout {
147         Timeout::Fuel(fuel) => store.add_fuel(fuel).unwrap(),
148         // If a timeout is requested then we spawn a helper thread to wait for
149         // the requested time and then send us a signal to get interrupted. We
150         // also arrange for the thread's sleep to get interrupted if we return
151         // early (or the wasm returns within the time limit), which allows the
152         // thread to get torn down.
153         //
154         // This prevents us from creating a huge number of sleeping threads if
155         // this function is executed in a loop, like it does on nightly fuzzing
156         // infrastructure.
157         Timeout::Time(timeout) => {
158             let handle = store.interrupt_handle().unwrap();
159             timeout_state.spawn_timeout(timeout, move || handle.interrupt());
160         }
161         Timeout::None => {}
162     }
163 
164     log_wasm(wasm);
165     let module = match Module::new(&engine, wasm) {
166         Ok(module) => module,
167         Err(_) if !known_valid => return,
168         Err(e) => panic!("failed to compile module: {:?}", e),
169     };
170 
171     instantiate_with_dummy(&mut store, &module);
172 }
173 
174 fn instantiate_with_dummy(store: &mut Store<StoreLimits>, module: &Module) -> Option<Instance> {
175     // Creation of imports can fail due to resource limit constraints, and then
176     // instantiation can naturally fail for a number of reasons as well. Bundle
177     // the two steps together to match on the error below.
178     let instance =
179         dummy::dummy_linker(store, module).and_then(|l| l.instantiate(&mut *store, module));
180 
181     let e = match instance {
182         Ok(i) => return Some(i),
183         Err(e) => e,
184     };
185 
186     // If the instantiation hit OOM for some reason then that's ok, it's
187     // expected that fuzz-generated programs try to allocate lots of
188     // stuff.
189     if store.data().oom {
190         return None;
191     }
192 
193     // Allow traps which can happen normally with `unreachable` or a
194     // timeout or such
195     if e.downcast_ref::<Trap>().is_some() {
196         return None;
197     }
198 
199     let string = e.to_string();
200     // Also allow errors related to fuel consumption
201     if string.contains("all fuel consumed")
202         // Currently we instantiate with a `Linker` which can't instantiate
203         // every single module under the sun due to using name-based resolution
204         // rather than positional-based resolution
205         || string.contains("incompatible import type")
206     {
207         return None;
208     }
209 
210     // Everything else should be a bug in the fuzzer or a bug in wasmtime
211     panic!("failed to instantiate {:?}", e);
212 }
213 
214 /// Compile the Wasm buffer, and implicitly fail if we have an unexpected
215 /// panic or segfault or anything else that can be detected "passively".
216 ///
217 /// Performs initial validation, and returns early if the Wasm is invalid.
218 ///
219 /// You can control which compiler is used via passing a `Strategy`.
220 pub fn compile(wasm: &[u8], strategy: Strategy) {
221     crate::init_fuzzing();
222 
223     let engine = Engine::new(&crate::fuzz_default_config(strategy).unwrap()).unwrap();
224     log_wasm(wasm);
225     let _ = Module::new(&engine, wasm);
226 }
227 
228 /// Instantiate the given Wasm module with each `Config` and call all of its
229 /// exports. Modulo OOM, non-canonical NaNs, and usage of Wasm features that are
230 /// or aren't enabled for different configs, we should get the same results when
231 /// we call the exported functions for all of our different configs.
232 pub fn differential_execution(
233     module: &crate::generators::GeneratedModule,
234     configs: &[crate::generators::DifferentialConfig],
235 ) {
236     use std::collections::{HashMap, HashSet};
237 
238     crate::init_fuzzing();
239 
240     // We need at least two configs.
241     if configs.len() < 2
242         // And all the configs should be unique.
243         || configs.iter().collect::<HashSet<_>>().len() != configs.len()
244     {
245         return;
246     }
247 
248     let configs: Vec<_> = match configs.iter().map(|c| c.to_wasmtime_config()).collect() {
249         Ok(cs) => cs,
250         // If the config is trying to use something that was turned off at
251         // compile time, eg lightbeam, just continue to the next fuzz input.
252         Err(_) => return,
253     };
254 
255     let mut export_func_results: HashMap<String, Result<Box<[Val]>, Trap>> = Default::default();
256     let wasm = module.module.to_bytes();
257     log_wasm(&wasm);
258 
259     for mut config in configs {
260         // Disable module linking since it isn't enabled by default for
261         // `GeneratedModule` but is enabled by default for our fuzz config.
262         // Since module linking is currently a breaking change this is required
263         // to accept modules that would otherwise be broken by module linking.
264         config.wasm_module_linking(false);
265 
266         let engine = Engine::new(&config).unwrap();
267         let mut store = create_store(&engine);
268 
269         let module = Module::new(&engine, &wasm).unwrap();
270 
271         // TODO: we should implement tracing versions of these dummy imports
272         // that record a trace of the order that imported functions were called
273         // in and with what values. Like the results of exported functions,
274         // calls to imports should also yield the same values for each
275         // configuration, and we should assert that.
276         let instance = match instantiate_with_dummy(&mut store, &module) {
277             Some(instance) => instance,
278             None => continue,
279         };
280 
281         let exports = instance
282             .exports(&mut store)
283             .filter_map(|e| {
284                 let name = e.name().to_string();
285                 e.into_func().map(|f| (name, f))
286             })
287             .collect::<Vec<_>>();
288         for (name, f) in exports {
289             // Always call the hang limit initializer first, so that we don't
290             // infinite loop when calling another export.
291             init_hang_limit(&mut store, instance);
292 
293             let ty = f.ty(&store);
294             let params = dummy::dummy_values(ty.params());
295             let this_result = f
296                 .call(&mut store, &params)
297                 .map_err(|e| e.downcast::<Trap>().unwrap());
298 
299             let existing_result = export_func_results
300                 .entry(name.to_string())
301                 .or_insert_with(|| this_result.clone());
302             assert_same_export_func_result(&existing_result, &this_result, &name);
303         }
304     }
305 
306     fn init_hang_limit<T>(store: &mut Store<T>, instance: Instance) {
307         match instance.get_export(&mut *store, "hangLimitInitializer") {
308             None => return,
309             Some(Extern::Func(f)) => {
310                 f.call(store, &[])
311                     .expect("initializing the hang limit should not fail");
312             }
313             Some(_) => panic!("unexpected hangLimitInitializer export"),
314         }
315     }
316 
317     fn assert_same_export_func_result(
318         lhs: &Result<Box<[Val]>, Trap>,
319         rhs: &Result<Box<[Val]>, Trap>,
320         func_name: &str,
321     ) {
322         let fail = || {
323             panic!(
324                 "differential fuzzing failed: exported func {} returned two \
325                  different results: {:?} != {:?}",
326                 func_name, lhs, rhs
327             )
328         };
329 
330         match (lhs, rhs) {
331             (Err(_), Err(_)) => {}
332             (Ok(lhs), Ok(rhs)) => {
333                 if lhs.len() != rhs.len() {
334                     fail();
335                 }
336                 for (lhs, rhs) in lhs.iter().zip(rhs.iter()) {
337                     match (lhs, rhs) {
338                         (Val::I32(lhs), Val::I32(rhs)) if lhs == rhs => continue,
339                         (Val::I64(lhs), Val::I64(rhs)) if lhs == rhs => continue,
340                         (Val::V128(lhs), Val::V128(rhs)) if lhs == rhs => continue,
341                         (Val::F32(lhs), Val::F32(rhs)) if f32_equal(*lhs, *rhs) => continue,
342                         (Val::F64(lhs), Val::F64(rhs)) if f64_equal(*lhs, *rhs) => continue,
343                         (Val::ExternRef(_), Val::ExternRef(_))
344                         | (Val::FuncRef(_), Val::FuncRef(_)) => continue,
345                         _ => fail(),
346                     }
347                 }
348             }
349             _ => fail(),
350         }
351     }
352 }
353 
354 fn f32_equal(a: u32, b: u32) -> bool {
355     let a = f32::from_bits(a);
356     let b = f32::from_bits(b);
357     a == b || (a.is_nan() && b.is_nan())
358 }
359 
360 fn f64_equal(a: u64, b: u64) -> bool {
361     let a = f64::from_bits(a);
362     let b = f64::from_bits(b);
363     a == b || (a.is_nan() && b.is_nan())
364 }
365 
366 /// Invoke the given API calls.
367 pub fn make_api_calls(api: crate::generators::api::ApiCalls) {
368     use crate::generators::api::ApiCall;
369     use std::collections::HashMap;
370 
371     crate::init_fuzzing();
372 
373     let mut config: Option<Config> = None;
374     let mut engine: Option<Engine> = None;
375     let mut store: Option<Store<StoreLimits>> = None;
376     let mut modules: HashMap<usize, Module> = Default::default();
377     let mut instances: HashMap<usize, Instance> = Default::default();
378 
379     for call in api.calls {
380         match call {
381             ApiCall::ConfigNew => {
382                 log::trace!("creating config");
383                 assert!(config.is_none());
384                 config = Some(crate::fuzz_default_config(wasmtime::Strategy::Cranelift).unwrap());
385             }
386 
387             ApiCall::ConfigDebugInfo(b) => {
388                 log::trace!("enabling debuginfo");
389                 config.as_mut().unwrap().debug_info(b);
390             }
391 
392             ApiCall::ConfigInterruptable(b) => {
393                 log::trace!("enabling interruption");
394                 config.as_mut().unwrap().interruptable(b);
395             }
396 
397             ApiCall::EngineNew => {
398                 log::trace!("creating engine");
399                 assert!(engine.is_none());
400                 engine = Some(Engine::new(config.as_ref().unwrap()).unwrap());
401             }
402 
403             ApiCall::StoreNew => {
404                 log::trace!("creating store");
405                 assert!(store.is_none());
406                 store = Some(create_store(engine.as_ref().unwrap()));
407             }
408 
409             ApiCall::ModuleNew { id, wasm } => {
410                 log::debug!("creating module: {}", id);
411                 let wasm = wasm.module.to_bytes();
412                 log_wasm(&wasm);
413                 let module = match Module::new(engine.as_ref().unwrap(), &wasm) {
414                     Ok(m) => m,
415                     Err(_) => continue,
416                 };
417                 let old = modules.insert(id, module);
418                 assert!(old.is_none());
419             }
420 
421             ApiCall::ModuleDrop { id } => {
422                 log::trace!("dropping module: {}", id);
423                 drop(modules.remove(&id));
424             }
425 
426             ApiCall::InstanceNew { id, module } => {
427                 log::trace!("instantiating module {} as {}", module, id);
428                 let module = match modules.get(&module) {
429                     Some(m) => m,
430                     None => continue,
431                 };
432 
433                 let store = store.as_mut().unwrap();
434                 if let Some(instance) = instantiate_with_dummy(store, module) {
435                     instances.insert(id, instance);
436                 }
437             }
438 
439             ApiCall::InstanceDrop { id } => {
440                 log::trace!("dropping instance {}", id);
441                 drop(instances.remove(&id));
442             }
443 
444             ApiCall::CallExportedFunc { instance, nth } => {
445                 log::trace!("calling instance export {} / {}", instance, nth);
446                 let instance = match instances.get(&instance) {
447                     Some(i) => i,
448                     None => {
449                         // Note that we aren't guaranteed to instantiate valid
450                         // modules, see comments in `InstanceNew` for details on
451                         // that. But the API call generator can't know if
452                         // instantiation failed, so we might not actually have
453                         // this instance. When that's the case, just skip the
454                         // API call and keep going.
455                         continue;
456                     }
457                 };
458                 let store = store.as_mut().unwrap();
459 
460                 let funcs = instance
461                     .exports(&mut *store)
462                     .filter_map(|e| match e.into_extern() {
463                         Extern::Func(f) => Some(f.clone()),
464                         _ => None,
465                     })
466                     .collect::<Vec<_>>();
467 
468                 if funcs.is_empty() {
469                     continue;
470                 }
471 
472                 let nth = nth % funcs.len();
473                 let f = &funcs[nth];
474                 let ty = f.ty(&store);
475                 let params = dummy::dummy_values(ty.params());
476                 let _ = f.call(store, &params);
477             }
478         }
479     }
480 }
481 
482 /// Executes the wast `test` spectest with the `config` specified.
483 ///
484 /// Ensures that spec tests pass regardless of the `Config`.
485 pub fn spectest(fuzz_config: crate::generators::Config, test: crate::generators::SpecTest) {
486     crate::init_fuzzing();
487     log::debug!("running {:?} with {:?}", test.file, fuzz_config);
488     let mut config = fuzz_config.to_wasmtime();
489     config.wasm_memory64(false);
490     config.wasm_reference_types(false);
491     config.wasm_bulk_memory(false);
492     config.wasm_module_linking(false);
493     config.wasm_multi_memory(false);
494     let mut store = create_store(&Engine::new(&config).unwrap());
495     if fuzz_config.consume_fuel {
496         store.add_fuel(u64::max_value()).unwrap();
497     }
498     let mut wast_context = WastContext::new(store);
499     wast_context.register_spectest().unwrap();
500     wast_context
501         .run_buffer(test.file, test.contents.as_bytes())
502         .unwrap();
503 }
504 
505 /// Execute a series of `table.get` and `table.set` operations.
506 pub fn table_ops(
507     fuzz_config: crate::generators::Config,
508     ops: crate::generators::table_ops::TableOps,
509 ) {
510     let _ = env_logger::try_init();
511 
512     let num_dropped = Arc::new(AtomicUsize::new(0));
513 
514     {
515         let mut config = fuzz_config.to_wasmtime();
516         config.wasm_reference_types(true);
517         let engine = Engine::new(&config).unwrap();
518         let mut store = create_store(&engine);
519         if fuzz_config.consume_fuel {
520             store.add_fuel(u64::max_value()).unwrap();
521         }
522 
523         let wasm = ops.to_wasm_binary();
524         log_wasm(&wasm);
525         let module = match Module::new(&engine, &wasm) {
526             Ok(m) => m,
527             Err(_) => return,
528         };
529 
530         // To avoid timeouts, limit the number of explicit GCs we perform per
531         // test case.
532         const MAX_GCS: usize = 5;
533 
534         let num_gcs = AtomicUsize::new(0);
535         let gc = Func::wrap(&mut store, move |mut caller: Caller<'_, StoreLimits>| {
536             if num_gcs.fetch_add(1, SeqCst) < MAX_GCS {
537                 caller.gc();
538             }
539         });
540 
541         let instance = Instance::new(&mut store, &module, &[gc.into()]).unwrap();
542         let run = instance.get_func(&mut store, "run").unwrap();
543 
544         let args: Vec<_> = (0..ops.num_params())
545             .map(|_| Val::ExternRef(Some(ExternRef::new(CountDrops(num_dropped.clone())))))
546             .collect();
547         let _ = run.call(&mut store, &args);
548     }
549 
550     assert_eq!(num_dropped.load(SeqCst), ops.num_params() as usize);
551     return;
552 
553     struct CountDrops(Arc<AtomicUsize>);
554 
555     impl Drop for CountDrops {
556         fn drop(&mut self) {
557             self.0.fetch_add(1, SeqCst);
558         }
559     }
560 }
561 
562 /// Configuration options for wasm-smith such that generated modules always
563 /// conform to certain specifications: one exported function, one exported
564 /// memory.
565 #[derive(Default, Debug, Arbitrary, Clone)]
566 pub struct SingleFunctionModuleConfig;
567 
568 impl wasm_smith::Config for SingleFunctionModuleConfig {
569     fn allow_start_export(&self) -> bool {
570         false
571     }
572 
573     fn min_types(&self) -> usize {
574         1
575     }
576 
577     fn min_funcs(&self) -> usize {
578         1
579     }
580 
581     fn max_funcs(&self) -> usize {
582         1
583     }
584 
585     fn min_memories(&self) -> u32 {
586         1
587     }
588 
589     fn max_memories(&self) -> usize {
590         1
591     }
592 
593     fn max_imports(&self) -> usize {
594         0
595     }
596 
597     fn min_exports(&self) -> usize {
598         2
599     }
600 
601     fn max_memory_pages(&self, _is_64: bool) -> u64 {
602         1
603     }
604 
605     fn memory_max_size_required(&self) -> bool {
606         true
607     }
608 
609     // NaN is canonicalized at the wasm level for differential fuzzing so we
610     // can paper over NaN differences between engines.
611     fn canonicalize_nans(&self) -> bool {
612         true
613     }
614 }
615 
616 /// Perform differential execution between Cranelift and wasmi, diffing the
617 /// resulting memory image when execution terminates. This relies on the
618 /// module-under-test to be instrumented to bound the execution time. Invoke
619 /// with a module generated by `wasm-smith` using the
620 /// `SingleFunctionModuleConfig` configuration type for best results.
621 ///
622 /// May return `None` if we early-out due to a rejected fuzz config; these
623 /// should be rare if modules are generated appropriately.
624 pub fn differential_wasmi_execution(wasm: &[u8], config: &crate::generators::Config) -> Option<()> {
625     crate::init_fuzzing();
626     log_wasm(wasm);
627 
628     // Instantiate wasmi module and instance.
629     let wasmi_module = wasmi::Module::from_buffer(&wasm[..]).ok()?;
630     let wasmi_instance =
631         wasmi::ModuleInstance::new(&wasmi_module, &wasmi::ImportsBuilder::default()).ok()?;
632     let wasmi_instance = wasmi_instance.assert_no_start();
633 
634     // If wasmi succeeded then we assert that wasmtime will also succeed.
635     let (wasmtime_module, mut wasmtime_store) = differential_store(wasm, config);
636     let wasmtime_instance = Instance::new(&mut wasmtime_store, &wasmtime_module, &[])
637         .expect("Wasmtime can instantiate module");
638 
639     // Introspect wasmtime module to find name of an exported function and of an
640     // exported memory.
641     let func_name = first_exported_function(&wasmtime_module)?;
642     let memory_name = first_exported_memory(&wasmtime_module)?;
643 
644     let wasmi_mem_export = wasmi_instance.export_by_name(memory_name).unwrap();
645     let wasmi_mem = wasmi_mem_export.as_memory().unwrap();
646     let wasmi_main_export = wasmi_instance.export_by_name(func_name).unwrap();
647     let wasmi_main = wasmi_main_export.as_func().unwrap();
648     let wasmi_val = wasmi::FuncInstance::invoke(&wasmi_main, &[], &mut wasmi::NopExternals);
649 
650     let wasmtime_mem = wasmtime_instance
651         .get_memory(&mut wasmtime_store, memory_name)
652         .expect("memory export is present");
653     let wasmtime_main = wasmtime_instance
654         .get_func(&mut wasmtime_store, func_name)
655         .expect("function export is present");
656     let wasmtime_vals = wasmtime_main.call(&mut wasmtime_store, &[]);
657     let wasmtime_val = wasmtime_vals.map(|v| v.iter().next().cloned());
658 
659     debug!(
660         "Successful execution: wasmi returned {:?}, wasmtime returned {:?}",
661         wasmi_val, wasmtime_val
662     );
663 
664     match (&wasmi_val, &wasmtime_val) {
665         (&Ok(Some(wasmi::RuntimeValue::I32(a))), &Ok(Some(Val::I32(b)))) if a == b => {}
666         (&Ok(Some(wasmi::RuntimeValue::F32(a))), &Ok(Some(Val::F32(b))))
667             if f32_equal(a.to_bits(), b) => {}
668         (&Ok(Some(wasmi::RuntimeValue::I64(a))), &Ok(Some(Val::I64(b)))) if a == b => {}
669         (&Ok(Some(wasmi::RuntimeValue::F64(a))), &Ok(Some(Val::F64(b))))
670             if f64_equal(a.to_bits(), b) => {}
671         (&Ok(None), &Ok(None)) => {}
672         (&Err(_), &Err(_)) => {}
673         _ => {
674             panic!(
675                 "Values do not match: wasmi returned {:?}; wasmtime returned {:?}",
676                 wasmi_val, wasmtime_val
677             );
678         }
679     }
680 
681     if wasmi_mem.current_size().0 != wasmtime_mem.size(&wasmtime_store) as usize {
682         panic!("resulting memories are not the same size");
683     }
684 
685     // Wasmi memory may be stored non-contiguously; copy it out to a contiguous chunk.
686     let mut wasmi_buf: Vec<u8> = vec![0; wasmtime_mem.data_size(&wasmtime_store)];
687     wasmi_mem
688         .get_into(0, &mut wasmi_buf[..])
689         .expect("can access wasmi memory");
690 
691     let wasmtime_slice = wasmtime_mem.data(&wasmtime_store);
692 
693     if wasmi_buf.len() >= 64 {
694         debug!("-> First 64 bytes of wasmi heap: {:?}", &wasmi_buf[0..64]);
695         debug!(
696             "-> First 64 bytes of Wasmtime heap: {:?}",
697             &wasmtime_slice[0..64]
698         );
699     }
700 
701     if &wasmi_buf[..] != &wasmtime_slice[..] {
702         panic!("memory contents are not equal");
703     }
704 
705     Some(())
706 }
707 
708 /// Perform differential execution between Wasmtime and the official WebAssembly
709 /// specification interpreter.
710 ///
711 /// May return `None` if we early-out due to a rejected fuzz config.
712 pub fn differential_spec_execution(wasm: &[u8], config: &crate::generators::Config) -> Option<()> {
713     crate::init_fuzzing();
714     debug!("config: {:#?}", config);
715     log_wasm(wasm);
716 
717     // Run the spec interpreter first, then Wasmtime. The order is important
718     // because both sides (OCaml runtime and Wasmtime) register signal handlers;
719     // Wasmtime uses these signal handlers for catching various WebAssembly
720     // failures. On certain OSes (e.g. Linux x86_64), the signal handlers
721     // interfere, observable as an uncaught `SIGSEGV`--not even caught by
722     // libFuzzer. By running Wasmtime second, its signal handlers are registered
723     // most recently and they catch failures appropriately.
724     let spec_vals = wasm_spec_interpreter::interpret(wasm, vec![]);
725     debug!("spec interpreter returned: {:?}", &spec_vals);
726     let wasmtime_vals = run_in_wasmtime(wasm, config, &[]);
727     debug!("Wasmtime returned: {:?}", wasmtime_vals);
728 
729     // Match a spec interpreter value against a Wasmtime value. Eventually this
730     // should support references and `v128` (TODO).
731     fn matches(spec_val: &wasm_spec_interpreter::Value, wasmtime_val: &wasmtime::Val) -> bool {
732         match (spec_val, wasmtime_val) {
733             (wasm_spec_interpreter::Value::I32(a), wasmtime::Val::I32(b)) => a == b,
734             (wasm_spec_interpreter::Value::I64(a), wasmtime::Val::I64(b)) => a == b,
735             (wasm_spec_interpreter::Value::F32(a), wasmtime::Val::F32(b)) => {
736                 f32_equal(*a as u32, *b)
737             }
738             (wasm_spec_interpreter::Value::F64(a), wasmtime::Val::F64(b)) => {
739                 f64_equal(*a as u64, *b)
740             }
741             (_, _) => unreachable!("fuzzing non-scalar value types is still TODO"),
742         }
743     }
744 
745     match (&spec_vals, &wasmtime_vals) {
746         // Compare the returned values, failing if they do not match.
747         (Ok(spec_vals), Ok(wasmtime_vals)) => {
748             let all_match = spec_vals
749                 .iter()
750                 .zip(wasmtime_vals)
751                 .all(|(s, w)| matches(s, w));
752             if !all_match {
753                 panic!(
754                     "Values do not match: spec returned {:?}; wasmtime returned {:?}",
755                     spec_vals, wasmtime_vals
756                 );
757             }
758         }
759         // If both sides fail, skip this fuzz execution.
760         (Err(spec_error), Err(wasmtime_error)) => {
761             // The `None` value returned here indicates that both sides
762             // failed--if we see too many of these we might be failing too often
763             // to check instruction semantics. At some point it would be
764             // beneficial to compare the error messages from both sides (TODO).
765             // It would also be good to keep track of statistics about the
766             // ratios of the kinds of errors the fuzzer sees (TODO).
767             warn!(
768                 "Both sides failed: spec returned '{}'; wasmtime returned {:?}",
769                 spec_error, wasmtime_error
770             );
771             return None;
772         }
773         // If only one side fails, fail the fuzz the test.
774         _ => {
775             panic!(
776                 "Only one side failed: spec returned {:?}; wasmtime returned {:?}",
777                 &spec_vals, &wasmtime_vals
778             );
779         }
780     }
781 
782     // TODO Compare memory contents.
783 
784     Some(())
785 }
786 
787 fn differential_store(
788     wasm: &[u8],
789     fuzz_config: &crate::generators::Config,
790 ) -> (Module, Store<StoreLimits>) {
791     let mut config = fuzz_config.to_wasmtime();
792     // forcibly disable NaN canonicalization because wasm-smith has already
793     // been configured to canonicalize everything at the wasm level.
794     config.cranelift_nan_canonicalization(false);
795     let engine = Engine::new(&config).unwrap();
796     let mut store = create_store(&engine);
797     if fuzz_config.consume_fuel {
798         store.add_fuel(u64::max_value()).unwrap();
799     }
800 
801     let module = Module::new(&engine, &wasm).expect("Wasmtime can compile module");
802 
803     (module, store)
804 }
805 
806 /// Helper for instantiating and running a Wasm module in Wasmtime and returning
807 /// its `Val` results.
808 fn run_in_wasmtime(
809     wasm: &[u8],
810     config: &crate::generators::Config,
811     params: &[Val],
812 ) -> anyhow::Result<Vec<Val>> {
813     // Instantiate wasmtime module and instance.
814     let (wasmtime_module, mut wasmtime_store) = differential_store(wasm, config);
815     let wasmtime_instance = Instance::new(&mut wasmtime_store, &wasmtime_module, &[])
816         .context("Wasmtime cannot instantiate module")?;
817 
818     // Find the first exported function.
819     let func_name =
820         first_exported_function(&wasmtime_module).context("Cannot find exported function")?;
821     let wasmtime_main = wasmtime_instance
822         .get_func(&mut wasmtime_store, &func_name[..])
823         .expect("function export is present");
824 
825     // Execute the function and return the values.
826     let wasmtime_vals = wasmtime_main.call(&mut wasmtime_store, params);
827     wasmtime_vals.map(|v| v.to_vec())
828 }
829 
830 // Introspect wasmtime module to find the name of the first exported function.
831 fn first_exported_function(module: &wasmtime::Module) -> Option<&str> {
832     for e in module.exports() {
833         match e.ty() {
834             wasmtime::ExternType::Func(..) => return Some(e.name()),
835             _ => {}
836         }
837     }
838     None
839 }
840 
841 fn first_exported_memory(module: &Module) -> Option<&str> {
842     for e in module.exports() {
843         match e.ty() {
844             wasmtime::ExternType::Memory(..) => return Some(e.name()),
845             _ => {}
846         }
847     }
848     None
849 }
850 
851 #[derive(Default)]
852 struct SignalOnDrop {
853     state: Arc<(Mutex<bool>, Condvar)>,
854     thread: Option<std::thread::JoinHandle<()>>,
855 }
856 
857 impl SignalOnDrop {
858     fn spawn_timeout(&mut self, dur: Duration, closure: impl FnOnce() + Send + 'static) {
859         let state = self.state.clone();
860         let start = Instant::now();
861         self.thread = Some(std::thread::spawn(move || {
862             // Using our mutex/condvar we wait here for the first of `dur` to
863             // pass or the `SignalOnDrop` instance to get dropped.
864             let (lock, cvar) = &*state;
865             let mut signaled = lock.lock().unwrap();
866             while !*signaled {
867                 // Adjust our requested `dur` based on how much time has passed.
868                 let dur = match dur.checked_sub(start.elapsed()) {
869                     Some(dur) => dur,
870                     None => break,
871                 };
872                 let (lock, result) = cvar.wait_timeout(signaled, dur).unwrap();
873                 signaled = lock;
874                 // If we timed out for sure then there's no need to continue
875                 // since we'll just abort on the next `checked_sub` anyway.
876                 if result.timed_out() {
877                     break;
878                 }
879             }
880             drop(signaled);
881 
882             closure();
883         }));
884     }
885 }
886 
887 impl Drop for SignalOnDrop {
888     fn drop(&mut self) {
889         if let Some(thread) = self.thread.take() {
890             let (lock, cvar) = &*self.state;
891             // Signal our thread that we've been dropped and wake it up if it's
892             // blocked.
893             let mut g = lock.lock().unwrap();
894             *g = true;
895             cvar.notify_one();
896             drop(g);
897 
898             // ... and then wait for the thread to exit to ensure we clean up
899             // after ourselves.
900             thread.join().unwrap();
901         }
902     }
903 }
904