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 arbitrary::Arbitrary; 16 use dummy::dummy_linker; 17 use log::debug; 18 use std::cell::Cell; 19 use std::rc::Rc; 20 use std::sync::atomic::{AtomicUsize, Ordering::SeqCst}; 21 use std::sync::{Arc, Condvar, Mutex}; 22 use std::time::{Duration, Instant}; 23 use wasmtime::*; 24 use wasmtime_wast::WastContext; 25 26 static CNT: AtomicUsize = AtomicUsize::new(0); 27 28 fn log_wasm(wasm: &[u8]) { 29 if !log::log_enabled!(log::Level::Debug) { 30 return; 31 } 32 33 let i = CNT.fetch_add(1, SeqCst); 34 let name = format!("testcase{}.wasm", i); 35 std::fs::write(&name, wasm).expect("failed to write wasm file"); 36 log::debug!("wrote wasm file to `{}`", name); 37 let wat = format!("testcase{}.wat", i); 38 match wasmprinter::print_bytes(wasm) { 39 Ok(s) => std::fs::write(&wat, s).expect("failed to write wat file"), 40 // If wasmprinter failed remove a `*.wat` file, if any, to avoid 41 // confusing a preexisting one with this wasm which failed to get 42 // printed. 43 Err(_) => drop(std::fs::remove_file(&wat)), 44 } 45 } 46 47 fn create_store(engine: &Engine) -> Store { 48 Store::new_with_limits( 49 &engine, 50 StoreLimitsBuilder::new() 51 // The limits here are chosen based on the default "maximum type size" 52 // configured in wasm-smith, which is 1000. This means that instances 53 // are allowed to, for example, export up to 1000 memories. We bump that 54 // a little bit here to give us some slop. 55 .instances(1100) 56 .tables(1100) 57 .memories(1100) 58 .build(), 59 ) 60 } 61 62 /// Methods of timing out execution of a WebAssembly module 63 #[derive(Debug)] 64 pub enum Timeout { 65 /// No timeout is used, it should be guaranteed via some other means that 66 /// the input does not infinite loop. 67 None, 68 /// A time-based timeout is used with a sleeping thread sending a signal 69 /// after the specified duration. 70 Time(Duration), 71 /// Fuel-based timeouts are used where the specified fuel is all that the 72 /// provided wasm module is allowed to consume. 73 Fuel(u64), 74 } 75 76 /// Instantiate the Wasm buffer, and implicitly fail if we have an unexpected 77 /// panic or segfault or anything else that can be detected "passively". 78 /// 79 /// Performs initial validation, and returns early if the Wasm is invalid. 80 /// 81 /// You can control which compiler is used via passing a `Strategy`. 82 pub fn instantiate(wasm: &[u8], known_valid: bool, strategy: Strategy) { 83 // Explicitly disable module linking for now since it's a breaking change to 84 // pre-module-linking modules due to imports 85 let mut cfg = crate::fuzz_default_config(strategy).unwrap(); 86 cfg.wasm_module_linking(false); 87 instantiate_with_config(wasm, known_valid, cfg, Timeout::None); 88 } 89 90 /// Instantiate the Wasm buffer, and implicitly fail if we have an unexpected 91 /// panic or segfault or anything else that can be detected "passively". 92 /// 93 /// The engine will be configured using provided config. 94 /// 95 /// See also `instantiate` functions. 96 pub fn instantiate_with_config( 97 wasm: &[u8], 98 known_valid: bool, 99 mut config: Config, 100 timeout: Timeout, 101 ) { 102 crate::init_fuzzing(); 103 104 config.interruptable(match &timeout { 105 Timeout::Time(_) => true, 106 _ => false, 107 }); 108 config.consume_fuel(match &timeout { 109 Timeout::Fuel(_) => true, 110 _ => false, 111 }); 112 let engine = Engine::new(&config).unwrap(); 113 let store = create_store(&engine); 114 115 let mut timeout_state = SignalOnDrop::default(); 116 match timeout { 117 Timeout::Fuel(fuel) => store.add_fuel(fuel).unwrap(), 118 // If a timeout is requested then we spawn a helper thread to wait for 119 // the requested time and then send us a signal to get interrupted. We 120 // also arrange for the thread's sleep to get interrupted if we return 121 // early (or the wasm returns within the time limit), which allows the 122 // thread to get torn down. 123 // 124 // This prevents us from creating a huge number of sleeping threads if 125 // this function is executed in a loop, like it does on nightly fuzzing 126 // infrastructure. 127 Timeout::Time(timeout) => { 128 let handle = store.interrupt_handle().unwrap(); 129 timeout_state.spawn_timeout(timeout, move || handle.interrupt()); 130 } 131 Timeout::None => {} 132 } 133 134 log_wasm(wasm); 135 let module = match Module::new(&engine, wasm) { 136 Ok(module) => module, 137 Err(_) if !known_valid => return, 138 Err(e) => panic!("failed to compile module: {:?}", e), 139 }; 140 let linker = dummy_linker(&store, &module); 141 142 match linker.instantiate(&module) { 143 Ok(_) => {} 144 Err(e) => { 145 let string = e.to_string(); 146 // Allow traps which can happen normally with `unreachable` or a 147 // timeout 148 if e.downcast_ref::<Trap>().is_some() 149 // Allow resource exhaustion since this is something that 150 // our wasm-smith generator doesn't guarantee is forbidden. 151 || string.contains("resource limit exceeded") 152 // Also allow errors related to fuel consumption 153 || string.contains("all fuel consumed") 154 // Currently we instantiate with a `Linker` which can't instantiate 155 // every single module under the sun due to using name-based resolution 156 // rather than positional-based resolution 157 || string.contains("incompatible import type") 158 { 159 return; 160 } 161 162 // Everything else should be a bug in the fuzzer 163 panic!("failed to instantiate {:?}", e); 164 } 165 } 166 } 167 168 /// Compile the Wasm buffer, and implicitly fail if we have an unexpected 169 /// panic or segfault or anything else that can be detected "passively". 170 /// 171 /// Performs initial validation, and returns early if the Wasm is invalid. 172 /// 173 /// You can control which compiler is used via passing a `Strategy`. 174 pub fn compile(wasm: &[u8], strategy: Strategy) { 175 crate::init_fuzzing(); 176 177 let engine = Engine::new(&crate::fuzz_default_config(strategy).unwrap()).unwrap(); 178 log_wasm(wasm); 179 let _ = Module::new(&engine, wasm); 180 } 181 182 /// Instantiate the given Wasm module with each `Config` and call all of its 183 /// exports. Modulo OOM, non-canonical NaNs, and usage of Wasm features that are 184 /// or aren't enabled for different configs, we should get the same results when 185 /// we call the exported functions for all of our different configs. 186 pub fn differential_execution( 187 module: &wasm_smith::Module, 188 configs: &[crate::generators::DifferentialConfig], 189 ) { 190 use std::collections::{HashMap, HashSet}; 191 192 crate::init_fuzzing(); 193 194 // We need at least two configs. 195 if configs.len() < 2 196 // And all the configs should be unique. 197 || configs.iter().collect::<HashSet<_>>().len() != configs.len() 198 { 199 return; 200 } 201 202 let configs: Vec<_> = match configs.iter().map(|c| c.to_wasmtime_config()).collect() { 203 Ok(cs) => cs, 204 // If the config is trying to use something that was turned off at 205 // compile time, eg lightbeam, just continue to the next fuzz input. 206 Err(_) => return, 207 }; 208 209 let mut export_func_results: HashMap<String, Result<Box<[Val]>, Trap>> = Default::default(); 210 let wasm = module.to_bytes(); 211 log_wasm(&wasm); 212 213 for mut config in configs { 214 // Disable module linking since it isn't enabled by default for 215 // `wasm_smith::Module` but is enabled by default for our fuzz config. 216 // Since module linking is currently a breaking change this is required 217 // to accept modules that would otherwise be broken by module linking. 218 config.wasm_module_linking(false); 219 220 let engine = Engine::new(&config).unwrap(); 221 let store = create_store(&engine); 222 223 let module = Module::new(&engine, &wasm).unwrap(); 224 225 // TODO: we should implement tracing versions of these dummy imports 226 // that record a trace of the order that imported functions were called 227 // in and with what values. Like the results of exported functions, 228 // calls to imports should also yield the same values for each 229 // configuration, and we should assert that. 230 let linker = dummy_linker(&store, &module); 231 232 // Don't unwrap this: there can be instantiation-/link-time errors that 233 // aren't caught during validation or compilation. For example, an imported 234 // table might not have room for an element segment that we want to 235 // initialize into it. 236 let instance = match linker.instantiate(&module) { 237 Ok(instance) => instance, 238 Err(e) => { 239 eprintln!( 240 "Warning: failed to instantiate `wasm-opt -ttf` module: {}", 241 e 242 ); 243 continue; 244 } 245 }; 246 247 for (name, f) in instance.exports().filter_map(|e| { 248 let name = e.name(); 249 e.into_func().map(|f| (name, f)) 250 }) { 251 // Always call the hang limit initializer first, so that we don't 252 // infinite loop when calling another export. 253 init_hang_limit(&instance); 254 255 let ty = f.ty(); 256 let params = dummy::dummy_values(ty.params()); 257 let this_result = f.call(¶ms).map_err(|e| e.downcast::<Trap>().unwrap()); 258 259 let existing_result = export_func_results 260 .entry(name.to_string()) 261 .or_insert_with(|| this_result.clone()); 262 assert_same_export_func_result(&existing_result, &this_result, name); 263 } 264 } 265 266 fn init_hang_limit(instance: &Instance) { 267 match instance.get_export("hangLimitInitializer") { 268 None => return, 269 Some(Extern::Func(f)) => { 270 f.call(&[]) 271 .expect("initializing the hang limit should not fail"); 272 } 273 Some(_) => panic!("unexpected hangLimitInitializer export"), 274 } 275 } 276 277 fn assert_same_export_func_result( 278 lhs: &Result<Box<[Val]>, Trap>, 279 rhs: &Result<Box<[Val]>, Trap>, 280 func_name: &str, 281 ) { 282 let fail = || { 283 panic!( 284 "differential fuzzing failed: exported func {} returned two \ 285 different results: {:?} != {:?}", 286 func_name, lhs, rhs 287 ) 288 }; 289 290 match (lhs, rhs) { 291 (Err(_), Err(_)) => {} 292 (Ok(lhs), Ok(rhs)) => { 293 if lhs.len() != rhs.len() { 294 fail(); 295 } 296 for (lhs, rhs) in lhs.iter().zip(rhs.iter()) { 297 match (lhs, rhs) { 298 (Val::I32(lhs), Val::I32(rhs)) if lhs == rhs => continue, 299 (Val::I64(lhs), Val::I64(rhs)) if lhs == rhs => continue, 300 (Val::V128(lhs), Val::V128(rhs)) if lhs == rhs => continue, 301 (Val::F32(lhs), Val::F32(rhs)) if f32_equal(*lhs, *rhs) => continue, 302 (Val::F64(lhs), Val::F64(rhs)) if f64_equal(*lhs, *rhs) => continue, 303 (Val::ExternRef(_), Val::ExternRef(_)) 304 | (Val::FuncRef(_), Val::FuncRef(_)) => continue, 305 _ => fail(), 306 } 307 } 308 } 309 _ => fail(), 310 } 311 } 312 } 313 314 fn f32_equal(a: u32, b: u32) -> bool { 315 let a = f32::from_bits(a); 316 let b = f32::from_bits(b); 317 a == b || (a.is_nan() && b.is_nan()) 318 } 319 320 fn f64_equal(a: u64, b: u64) -> bool { 321 let a = f64::from_bits(a); 322 let b = f64::from_bits(b); 323 a == b || (a.is_nan() && b.is_nan()) 324 } 325 326 /// Invoke the given API calls. 327 pub fn make_api_calls(api: crate::generators::api::ApiCalls) { 328 use crate::generators::api::ApiCall; 329 use std::collections::HashMap; 330 331 crate::init_fuzzing(); 332 333 let mut config: Option<Config> = None; 334 let mut engine: Option<Engine> = None; 335 let mut store: Option<Store> = None; 336 let mut modules: HashMap<usize, Module> = Default::default(); 337 let mut instances: HashMap<usize, Instance> = Default::default(); 338 339 for call in api.calls { 340 match call { 341 ApiCall::ConfigNew => { 342 log::trace!("creating config"); 343 assert!(config.is_none()); 344 config = Some(crate::fuzz_default_config(wasmtime::Strategy::Cranelift).unwrap()); 345 } 346 347 ApiCall::ConfigDebugInfo(b) => { 348 log::trace!("enabling debuginfo"); 349 config.as_mut().unwrap().debug_info(b); 350 } 351 352 ApiCall::ConfigInterruptable(b) => { 353 log::trace!("enabling interruption"); 354 config.as_mut().unwrap().interruptable(b); 355 } 356 357 ApiCall::EngineNew => { 358 log::trace!("creating engine"); 359 assert!(engine.is_none()); 360 engine = Some(Engine::new(config.as_ref().unwrap()).unwrap()); 361 } 362 363 ApiCall::StoreNew => { 364 log::trace!("creating store"); 365 assert!(store.is_none()); 366 store = Some(create_store(engine.as_ref().unwrap())); 367 } 368 369 ApiCall::ModuleNew { id, wasm } => { 370 log::debug!("creating module: {}", id); 371 let wasm = wasm.to_bytes(); 372 log_wasm(&wasm); 373 let module = match Module::new(engine.as_ref().unwrap(), &wasm) { 374 Ok(m) => m, 375 Err(_) => continue, 376 }; 377 let old = modules.insert(id, module); 378 assert!(old.is_none()); 379 } 380 381 ApiCall::ModuleDrop { id } => { 382 log::trace!("dropping module: {}", id); 383 drop(modules.remove(&id)); 384 } 385 386 ApiCall::InstanceNew { id, module } => { 387 log::trace!("instantiating module {} as {}", module, id); 388 let module = match modules.get(&module) { 389 Some(m) => m, 390 None => continue, 391 }; 392 393 let store = store.as_ref().unwrap(); 394 let linker = dummy_linker(store, module); 395 396 // Don't unwrap this: there can be instantiation-/link-time errors that 397 // aren't caught during validation or compilation. For example, an imported 398 // table might not have room for an element segment that we want to 399 // initialize into it. 400 if let Ok(instance) = linker.instantiate(&module) { 401 instances.insert(id, instance); 402 } 403 } 404 405 ApiCall::InstanceDrop { id } => { 406 log::trace!("dropping instance {}", id); 407 drop(instances.remove(&id)); 408 } 409 410 ApiCall::CallExportedFunc { instance, nth } => { 411 log::trace!("calling instance export {} / {}", instance, nth); 412 let instance = match instances.get(&instance) { 413 Some(i) => i, 414 None => { 415 // Note that we aren't guaranteed to instantiate valid 416 // modules, see comments in `InstanceNew` for details on 417 // that. But the API call generator can't know if 418 // instantiation failed, so we might not actually have 419 // this instance. When that's the case, just skip the 420 // API call and keep going. 421 continue; 422 } 423 }; 424 425 let funcs = instance 426 .exports() 427 .filter_map(|e| match e.into_extern() { 428 Extern::Func(f) => Some(f.clone()), 429 _ => None, 430 }) 431 .collect::<Vec<_>>(); 432 433 if funcs.is_empty() { 434 continue; 435 } 436 437 let nth = nth % funcs.len(); 438 let f = &funcs[nth]; 439 let ty = f.ty(); 440 let params = dummy::dummy_values(ty.params()); 441 let _ = f.call(¶ms); 442 } 443 } 444 } 445 } 446 447 /// Executes the wast `test` spectest with the `config` specified. 448 /// 449 /// Ensures that spec tests pass regardless of the `Config`. 450 pub fn spectest(fuzz_config: crate::generators::Config, test: crate::generators::SpecTest) { 451 crate::init_fuzzing(); 452 log::debug!("running {:?} with {:?}", test.file, fuzz_config); 453 let mut config = fuzz_config.to_wasmtime(); 454 config.wasm_reference_types(false); 455 config.wasm_bulk_memory(false); 456 config.wasm_module_linking(false); 457 let store = create_store(&Engine::new(&config).unwrap()); 458 if fuzz_config.consume_fuel { 459 store.add_fuel(u64::max_value()).unwrap(); 460 } 461 let mut wast_context = WastContext::new(store); 462 wast_context.register_spectest().unwrap(); 463 wast_context 464 .run_buffer(test.file, test.contents.as_bytes()) 465 .unwrap(); 466 } 467 468 /// Execute a series of `table.get` and `table.set` operations. 469 pub fn table_ops( 470 fuzz_config: crate::generators::Config, 471 ops: crate::generators::table_ops::TableOps, 472 ) { 473 let _ = env_logger::try_init(); 474 475 let num_dropped = Rc::new(Cell::new(0)); 476 477 { 478 let mut config = fuzz_config.to_wasmtime(); 479 config.wasm_reference_types(true); 480 let engine = Engine::new(&config).unwrap(); 481 let store = create_store(&engine); 482 if fuzz_config.consume_fuel { 483 store.add_fuel(u64::max_value()).unwrap(); 484 } 485 486 let wasm = ops.to_wasm_binary(); 487 log_wasm(&wasm); 488 let module = match Module::new(&engine, &wasm) { 489 Ok(m) => m, 490 Err(_) => return, 491 }; 492 493 // To avoid timeouts, limit the number of explicit GCs we perform per 494 // test case. 495 const MAX_GCS: usize = 5; 496 497 let num_gcs = Cell::new(0); 498 let gc = Func::wrap(&store, move |caller: Caller| { 499 if num_gcs.get() < MAX_GCS { 500 caller.store().gc(); 501 num_gcs.set(num_gcs.get() + 1); 502 } 503 }); 504 505 let instance = Instance::new(&store, &module, &[gc.into()]).unwrap(); 506 let run = instance.get_func("run").unwrap(); 507 508 let args: Vec<_> = (0..ops.num_params()) 509 .map(|_| Val::ExternRef(Some(ExternRef::new(CountDrops(num_dropped.clone()))))) 510 .collect(); 511 let _ = run.call(&args); 512 } 513 514 assert_eq!(num_dropped.get(), ops.num_params()); 515 return; 516 517 struct CountDrops(Rc<Cell<u8>>); 518 519 impl Drop for CountDrops { 520 fn drop(&mut self) { 521 self.0.set(self.0.get().checked_add(1).unwrap()); 522 } 523 } 524 } 525 526 /// Configuration options for wasm-smith such that generated modules always 527 /// conform to certain specifications. 528 #[derive(Default, Debug, Arbitrary, Clone)] 529 pub struct DifferentialWasmiModuleConfig; 530 531 impl wasm_smith::Config for DifferentialWasmiModuleConfig { 532 fn allow_start_export(&self) -> bool { 533 false 534 } 535 536 fn min_funcs(&self) -> usize { 537 1 538 } 539 540 fn max_funcs(&self) -> usize { 541 1 542 } 543 544 fn min_memories(&self) -> u32 { 545 1 546 } 547 548 fn max_memories(&self) -> usize { 549 1 550 } 551 552 fn max_imports(&self) -> usize { 553 0 554 } 555 556 fn min_exports(&self) -> usize { 557 2 558 } 559 560 fn max_memory_pages(&self) -> u32 { 561 1 562 } 563 564 fn memory_max_size_required(&self) -> bool { 565 true 566 } 567 } 568 569 /// Perform differential execution between Cranelift and wasmi, diffing the 570 /// resulting memory image when execution terminates. This relies on the 571 /// module-under-test to be instrumented to bound the execution time. Invoke 572 /// with a module generated by `wasm-smith` using the 573 /// `DiferentialWasmiModuleConfig` configuration type for best results. 574 /// 575 /// May return `None` if we early-out due to a rejected fuzz config; these 576 /// should be rare if modules are generated appropriately. 577 pub fn differential_wasmi_execution(wasm: &[u8], config: &crate::generators::Config) -> Option<()> { 578 crate::init_fuzzing(); 579 580 // Instantiate wasmi module and instance. 581 let wasmi_module = wasmi::Module::from_buffer(&wasm[..]).ok()?; 582 let wasmi_instance = 583 wasmi::ModuleInstance::new(&wasmi_module, &wasmi::ImportsBuilder::default()).ok()?; 584 let wasmi_instance = wasmi_instance.assert_no_start(); 585 586 // TODO(paritytech/wasmi#19): wasmi does not currently canonicalize NaNs. To avoid spurious 587 // fuzz failures, for now let's fuzz only integer Wasm programs. 588 if wasmi_module.deny_floating_point().is_err() { 589 return None; 590 } 591 592 // Instantiate wasmtime module and instance. 593 let mut wasmtime_config = config.to_wasmtime(); 594 wasmtime_config.cranelift_nan_canonicalization(true); 595 let wasmtime_engine = Engine::new(&wasmtime_config).unwrap(); 596 let wasmtime_store = create_store(&wasmtime_engine); 597 if config.consume_fuel { 598 wasmtime_store.add_fuel(u64::max_value()).unwrap(); 599 } 600 let wasmtime_module = 601 Module::new(&wasmtime_engine, &wasm).expect("Wasmtime can compile module"); 602 let wasmtime_instance = Instance::new(&wasmtime_store, &wasmtime_module, &[]) 603 .expect("Wasmtime can instantiate module"); 604 605 // Introspect wasmtime module to find name of an exported function and of an 606 // exported memory. Stop when we have one of each. (According to the config 607 // above, there should be at most one of each.) 608 let (func_name, memory_name) = { 609 let mut func_name = None; 610 let mut memory_name = None; 611 for e in wasmtime_module.exports() { 612 match e.ty() { 613 wasmtime::ExternType::Func(..) => func_name = Some(e.name().to_string()), 614 wasmtime::ExternType::Memory(..) => memory_name = Some(e.name().to_string()), 615 _ => {} 616 } 617 if func_name.is_some() && memory_name.is_some() { 618 break; 619 } 620 } 621 (func_name?, memory_name?) 622 }; 623 624 let wasmi_mem_export = wasmi_instance.export_by_name(&memory_name[..]).unwrap(); 625 let wasmi_mem = wasmi_mem_export.as_memory().unwrap(); 626 let wasmi_main_export = wasmi_instance.export_by_name(&func_name[..]).unwrap(); 627 let wasmi_main = wasmi_main_export.as_func().unwrap(); 628 let wasmi_val = wasmi::FuncInstance::invoke(&wasmi_main, &[], &mut wasmi::NopExternals); 629 630 let wasmtime_mem = wasmtime_instance 631 .get_memory(&memory_name[..]) 632 .expect("memory export is present"); 633 let wasmtime_main = wasmtime_instance 634 .get_func(&func_name[..]) 635 .expect("function export is present"); 636 let wasmtime_vals = wasmtime_main.call(&[]); 637 let wasmtime_val = wasmtime_vals.map(|v| v.iter().next().cloned()); 638 639 debug!( 640 "Successful execution: wasmi returned {:?}, wasmtime returned {:?}", 641 wasmi_val, wasmtime_val 642 ); 643 644 let show_wat = || { 645 if let Ok(s) = wasmprinter::print_bytes(&wasm[..]) { 646 eprintln!("wat:\n{}\n", s); 647 } 648 }; 649 650 match (&wasmi_val, &wasmtime_val) { 651 (&Ok(Some(wasmi::RuntimeValue::I32(a))), &Ok(Some(Val::I32(b)))) if a == b => {} 652 (&Ok(Some(wasmi::RuntimeValue::F32(a))), &Ok(Some(Val::F32(b)))) 653 if f32_equal(a.to_bits(), b) => {} 654 (&Ok(Some(wasmi::RuntimeValue::I64(a))), &Ok(Some(Val::I64(b)))) if a == b => {} 655 (&Ok(Some(wasmi::RuntimeValue::F64(a))), &Ok(Some(Val::F64(b)))) 656 if f64_equal(a.to_bits(), b) => {} 657 (&Ok(None), &Ok(None)) => {} 658 (&Err(_), &Err(_)) => {} 659 _ => { 660 show_wat(); 661 panic!( 662 "Values do not match: wasmi returned {:?}; wasmtime returned {:?}", 663 wasmi_val, wasmtime_val 664 ); 665 } 666 } 667 668 if wasmi_mem.current_size().0 != wasmtime_mem.size() as usize { 669 show_wat(); 670 panic!("resulting memories are not the same size"); 671 } 672 673 // Wasmi memory may be stored non-contiguously; copy it out to a contiguous chunk. 674 let mut wasmi_buf: Vec<u8> = vec![0; wasmtime_mem.data_size()]; 675 wasmi_mem 676 .get_into(0, &mut wasmi_buf[..]) 677 .expect("can access wasmi memory"); 678 679 let wasmtime_slice = unsafe { wasmtime_mem.data_unchecked() }; 680 681 if wasmi_buf.len() >= 64 { 682 debug!("-> First 64 bytes of wasmi heap: {:?}", &wasmi_buf[0..64]); 683 debug!( 684 "-> First 64 bytes of Wasmtime heap: {:?}", 685 &wasmtime_slice[0..64] 686 ); 687 } 688 689 if &wasmi_buf[..] != &wasmtime_slice[..] { 690 show_wat(); 691 panic!("memory contents are not equal"); 692 } 693 694 Some(()) 695 } 696 697 #[derive(Default)] 698 struct SignalOnDrop { 699 state: Arc<(Mutex<bool>, Condvar)>, 700 thread: Option<std::thread::JoinHandle<()>>, 701 } 702 703 impl SignalOnDrop { 704 fn spawn_timeout(&mut self, dur: Duration, closure: impl FnOnce() + Send + 'static) { 705 let state = self.state.clone(); 706 let start = Instant::now(); 707 self.thread = Some(std::thread::spawn(move || { 708 // Using our mutex/condvar we wait here for the first of `dur` to 709 // pass or the `SignalOnDrop` instance to get dropped. 710 let (lock, cvar) = &*state; 711 let mut signaled = lock.lock().unwrap(); 712 while !*signaled { 713 // Adjust our requested `dur` based on how much time has passed. 714 let dur = match dur.checked_sub(start.elapsed()) { 715 Some(dur) => dur, 716 None => break, 717 }; 718 let (lock, result) = cvar.wait_timeout(signaled, dur).unwrap(); 719 signaled = lock; 720 // If we timed out for sure then there's no need to continue 721 // since we'll just abort on the next `checked_sub` anyway. 722 if result.timed_out() { 723 break; 724 } 725 } 726 drop(signaled); 727 728 closure(); 729 })); 730 } 731 } 732 733 impl Drop for SignalOnDrop { 734 fn drop(&mut self) { 735 if let Some(thread) = self.thread.take() { 736 let (lock, cvar) = &*self.state; 737 // Signal our thread that we've been dropped and wake it up if it's 738 // blocked. 739 let mut g = lock.lock().unwrap(); 740 *g = true; 741 cvar.notify_one(); 742 drop(g); 743 744 // ... and then wait for the thread to exit to ensure we clean up 745 // after ourselves. 746 thread.join().unwrap(); 747 } 748 } 749 } 750