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 #[cfg(feature = "fuzz-spec-interpreter")] 14 pub mod diff_spec; 15 pub mod diff_wasmi; 16 pub mod diff_wasmtime; 17 pub mod dummy; 18 pub mod engine; 19 pub mod memory; 20 mod stacks; 21 22 use self::diff_wasmtime::WasmtimeInstance; 23 use self::engine::{DiffEngine, DiffInstance}; 24 use crate::block_on; 25 use crate::generators::GcOps; 26 use crate::generators::{self, CompilerStrategy, DiffValue, DiffValueType}; 27 use crate::single_module_fuzzer::KnownValid; 28 use arbitrary::Arbitrary; 29 pub use stacks::check_stacks; 30 use std::future::Future; 31 use std::pin::Pin; 32 use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering::SeqCst}; 33 use std::sync::{Arc, Condvar, Mutex}; 34 use std::task::{Context, Poll}; 35 use std::time::{Duration, Instant}; 36 use wasmtime::component::Accessor; 37 use wasmtime::*; 38 use wasmtime_wast::WastContext; 39 40 #[cfg(not(any(windows, target_arch = "s390x", target_arch = "riscv64")))] 41 mod diff_v8; 42 43 static CNT: AtomicUsize = AtomicUsize::new(0); 44 45 /// Logs a wasm file to the filesystem to make it easy to figure out what wasm 46 /// was used when debugging. 47 pub fn log_wasm(wasm: &[u8]) { 48 super::init_fuzzing(); 49 50 if !log::log_enabled!(log::Level::Debug) { 51 return; 52 } 53 54 let i = CNT.fetch_add(1, SeqCst); 55 let name = format!("testcase{i}.wasm"); 56 std::fs::write(&name, wasm).expect("failed to write wasm file"); 57 log::debug!("wrote wasm file to `{name}`"); 58 let wat = format!("testcase{i}.wat"); 59 match wasmprinter::print_bytes(wasm) { 60 Ok(s) => std::fs::write(&wat, s).expect("failed to write wat file"), 61 // If wasmprinter failed remove a `*.wat` file, if any, to avoid 62 // confusing a preexisting one with this wasm which failed to get 63 // printed. 64 Err(e) => { 65 log::debug!("failed to print to wat: {e}"); 66 drop(std::fs::remove_file(&wat)) 67 } 68 } 69 } 70 71 /// The `T` in `Store<T>` for fuzzing stores, used to limit resource 72 /// consumption during fuzzing. 73 #[derive(Clone)] 74 pub struct StoreLimits(Arc<LimitsState>); 75 76 struct LimitsState { 77 /// Remaining memory, in bytes, left to allocate 78 remaining_memory: AtomicUsize, 79 /// Remaining amount of memory that's allowed to be copied via a growth. 80 remaining_copy_allowance: AtomicUsize, 81 /// Whether or not an allocation request has been denied 82 oom: AtomicBool, 83 } 84 85 /// Allow up to 1G which is well below the 2G limit on OSS-Fuzz and should allow 86 /// most interesting behavior. 87 const MAX_MEMORY: usize = 1 << 30; 88 89 /// Allow up to 4G of bytes to be copied (conservatively) which should enable 90 /// growth up to `MAX_MEMORY` or at least up to a relatively large amount. 91 const MAX_MEMORY_MOVED: usize = 4 << 30; 92 93 impl StoreLimits { 94 /// Creates the default set of limits for all fuzzing stores. 95 pub fn new() -> StoreLimits { 96 StoreLimits(Arc::new(LimitsState { 97 remaining_memory: AtomicUsize::new(MAX_MEMORY), 98 remaining_copy_allowance: AtomicUsize::new(MAX_MEMORY_MOVED), 99 oom: AtomicBool::new(false), 100 })) 101 } 102 103 fn alloc(&mut self, amt: usize) -> bool { 104 log::trace!("alloc {amt:#x} bytes"); 105 106 // Assume that on each allocation of memory that all previous 107 // allocations of memory are moved. This is pretty coarse but is used to 108 // help prevent against fuzz test cases that just move tons of bytes 109 // around continuously. This assumes that all previous memory was 110 // allocated in a single linear memory and growing by `amt` will require 111 // moving all the bytes to a new location. This isn't actually required 112 // all the time nor does it accurately reflect what happens all the 113 // time, but it's a coarse approximation that should be "good enough" 114 // for allowing interesting fuzz behaviors to happen while not timing 115 // out just copying bytes around. 116 let prev_size = MAX_MEMORY - self.0.remaining_memory.load(SeqCst); 117 if self 118 .0 119 .remaining_copy_allowance 120 .fetch_update(SeqCst, SeqCst, |remaining| remaining.checked_sub(prev_size)) 121 .is_err() 122 { 123 self.0.oom.store(true, SeqCst); 124 log::debug!("-> too many bytes moved, rejecting allocation"); 125 return false; 126 } 127 128 // If we're allowed to move the bytes, then also check if we're allowed 129 // to actually have this much residence at once. 130 match self 131 .0 132 .remaining_memory 133 .fetch_update(SeqCst, SeqCst, |remaining| remaining.checked_sub(amt)) 134 { 135 Ok(_) => true, 136 Err(_) => { 137 self.0.oom.store(true, SeqCst); 138 log::debug!("-> OOM hit"); 139 false 140 } 141 } 142 } 143 144 fn is_oom(&self) -> bool { 145 self.0.oom.load(SeqCst) 146 } 147 } 148 149 impl ResourceLimiter for StoreLimits { 150 fn memory_growing( 151 &mut self, 152 current: usize, 153 desired: usize, 154 _maximum: Option<usize>, 155 ) -> Result<bool> { 156 Ok(self.alloc(desired - current)) 157 } 158 159 fn table_growing( 160 &mut self, 161 current: usize, 162 desired: usize, 163 _maximum: Option<usize>, 164 ) -> Result<bool> { 165 let delta = (desired - current).saturating_mul(std::mem::size_of::<usize>()); 166 Ok(self.alloc(delta)) 167 } 168 } 169 170 /// Methods of timing out execution of a WebAssembly module 171 #[derive(Clone, Debug)] 172 pub enum Timeout { 173 /// No timeout is used, it should be guaranteed via some other means that 174 /// the input does not infinite loop. 175 None, 176 /// Fuel-based timeouts are used where the specified fuel is all that the 177 /// provided wasm module is allowed to consume. 178 Fuel(u64), 179 /// An epoch-interruption-based timeout is used with a sleeping 180 /// thread bumping the epoch counter after the specified duration. 181 Epoch(Duration), 182 } 183 184 /// Instantiate the Wasm buffer, and implicitly fail if we have an unexpected 185 /// panic or segfault or anything else that can be detected "passively". 186 /// 187 /// The engine will be configured using provided config. 188 pub fn instantiate( 189 wasm: &[u8], 190 known_valid: KnownValid, 191 config: &generators::Config, 192 timeout: Timeout, 193 ) { 194 let mut store = config.to_store(); 195 196 let module = match compile_module(store.engine(), wasm, known_valid, config) { 197 Some(module) => module, 198 None => return, 199 }; 200 201 let mut timeout_state = HelperThread::default(); 202 match timeout { 203 Timeout::Fuel(fuel) => store.set_fuel(fuel).unwrap(), 204 205 // If a timeout is requested then we spawn a helper thread to wait for 206 // the requested time and then send us a signal to get interrupted. We 207 // also arrange for the thread's sleep to get interrupted if we return 208 // early (or the wasm returns within the time limit), which allows the 209 // thread to get torn down. 210 // 211 // This prevents us from creating a huge number of sleeping threads if 212 // this function is executed in a loop, like it does on nightly fuzzing 213 // infrastructure. 214 Timeout::Epoch(timeout) => { 215 let engine = store.engine().clone(); 216 timeout_state.run_periodically(timeout, move || engine.increment_epoch()); 217 } 218 Timeout::None => {} 219 } 220 221 instantiate_with_dummy(&mut store, &module); 222 } 223 224 /// Represents supported commands to the `instantiate_many` function. 225 #[derive(Arbitrary, Debug)] 226 pub enum Command { 227 /// Instantiates a module. 228 /// 229 /// The value is the index of the module to instantiate. 230 /// 231 /// The module instantiated will be this value modulo the number of modules provided to `instantiate_many`. 232 Instantiate(usize), 233 /// Terminates a "running" instance. 234 /// 235 /// The value is the index of the instance to terminate. 236 /// 237 /// The instance terminated will be this value modulo the number of currently running 238 /// instances. 239 /// 240 /// If no instances are running, the command will be ignored. 241 Terminate(usize), 242 } 243 244 /// Instantiates many instances from the given modules. 245 /// 246 /// The engine will be configured using the provided config. 247 /// 248 /// The modules are expected to *not* have start functions as no timeouts are configured. 249 pub fn instantiate_many( 250 modules: &[Vec<u8>], 251 known_valid: KnownValid, 252 config: &generators::Config, 253 commands: &[Command], 254 ) { 255 log::debug!("instantiate_many: {commands:#?}"); 256 257 assert!(!config.module_config.config.allow_start_export); 258 259 let engine = Engine::new(&config.to_wasmtime()).unwrap(); 260 261 let modules = modules 262 .iter() 263 .enumerate() 264 .filter_map( 265 |(i, bytes)| match compile_module(&engine, bytes, known_valid, config) { 266 Some(m) => { 267 log::debug!("successfully compiled module {i}"); 268 Some(m) 269 } 270 None => { 271 log::debug!("failed to compile module {i}"); 272 None 273 } 274 }, 275 ) 276 .collect::<Vec<_>>(); 277 278 // If no modules were valid, we're done 279 if modules.is_empty() { 280 return; 281 } 282 283 // This stores every `Store` where a successful instantiation takes place 284 let mut stores = Vec::new(); 285 let limits = StoreLimits::new(); 286 287 for command in commands { 288 match command { 289 Command::Instantiate(index) => { 290 let index = *index % modules.len(); 291 log::info!("instantiating {index}"); 292 let module = &modules[index]; 293 let mut store = Store::new(&engine, limits.clone()); 294 config.configure_store(&mut store); 295 296 if instantiate_with_dummy(&mut store, module).is_some() { 297 stores.push(Some(store)); 298 } else { 299 log::warn!("instantiation failed"); 300 } 301 } 302 Command::Terminate(index) => { 303 if stores.is_empty() { 304 continue; 305 } 306 let index = *index % stores.len(); 307 308 log::info!("dropping {index}"); 309 stores.swap_remove(index); 310 } 311 } 312 } 313 } 314 315 fn compile_module( 316 engine: &Engine, 317 bytes: &[u8], 318 known_valid: KnownValid, 319 config: &generators::Config, 320 ) -> Option<Module> { 321 log_wasm(bytes); 322 323 fn is_pcc_error(e: &anyhow::Error) -> bool { 324 // NOTE: please keep this predicate in sync with the display format of CodegenError, 325 // defined in `wasmtime/cranelift/codegen/src/result.rs` 326 e.to_string().to_lowercase().contains("proof-carrying-code") 327 } 328 329 match config.compile(engine, bytes) { 330 Ok(module) => Some(module), 331 Err(e) if is_pcc_error(&e) => { 332 panic!("pcc error in input: {e:#?}"); 333 } 334 Err(_) if known_valid == KnownValid::No => None, 335 Err(e) => { 336 if let generators::InstanceAllocationStrategy::Pooling(c) = &config.wasmtime.strategy { 337 // When using the pooling allocator, accept failures to compile 338 // when arbitrary table element limits have been exceeded as 339 // there is currently no way to constrain the generated module 340 // table types. 341 let string = format!("{e:?}"); 342 if string.contains("minimum element size") { 343 return None; 344 } 345 346 // Allow modules-failing-to-compile which exceed the requested 347 // size for each instance. This is something that is difficult 348 // to control and ensure it always succeeds, so we simply have a 349 // "random" instance size limit and if a module doesn't fit we 350 // move on to the next fuzz input. 351 if string.contains("instance allocation for this module requires") { 352 return None; 353 } 354 355 // If the pooling allocator is more restrictive on the number of 356 // tables and memories than we allowed wasm-smith to generate 357 // then allow compilation errors along those lines. 358 if c.max_tables_per_module < (config.module_config.config.max_tables as u32) 359 && string.contains("defined tables count") 360 && string.contains("exceeds the per-instance limit") 361 { 362 return None; 363 } 364 365 if c.max_memories_per_module < (config.module_config.config.max_memories as u32) 366 && string.contains("defined memories count") 367 && string.contains("exceeds the per-instance limit") 368 { 369 return None; 370 } 371 } 372 373 panic!("failed to compile module: {e:?}"); 374 } 375 } 376 } 377 378 /// Create a Wasmtime [`Instance`] from a [`Module`] and fill in all imports 379 /// with dummy values (e.g., zeroed values, immediately-trapping functions). 380 /// Also, this function catches certain fuzz-related instantiation failures and 381 /// returns `None` instead of panicking. 382 /// 383 /// TODO: we should implement tracing versions of these dummy imports that 384 /// record a trace of the order that imported functions were called in and with 385 /// what values. Like the results of exported functions, calls to imports should 386 /// also yield the same values for each configuration, and we should assert 387 /// that. 388 pub fn instantiate_with_dummy(store: &mut Store<StoreLimits>, module: &Module) -> Option<Instance> { 389 // Creation of imports can fail due to resource limit constraints, and then 390 // instantiation can naturally fail for a number of reasons as well. Bundle 391 // the two steps together to match on the error below. 392 let linker = dummy::dummy_linker(store, module); 393 if let Err(e) = &linker { 394 log::warn!("failed to create dummy linker: {e:?}"); 395 } 396 let instance = linker.and_then(|l| l.instantiate(&mut *store, module)); 397 unwrap_instance(store, instance) 398 } 399 400 fn unwrap_instance( 401 store: &Store<StoreLimits>, 402 instance: anyhow::Result<Instance>, 403 ) -> Option<Instance> { 404 let e = match instance { 405 Ok(i) => return Some(i), 406 Err(e) => e, 407 }; 408 409 log::debug!("failed to instantiate: {e:?}"); 410 411 // If the instantiation hit OOM for some reason then that's ok, it's 412 // expected that fuzz-generated programs try to allocate lots of 413 // stuff. 414 if store.data().is_oom() { 415 return None; 416 } 417 418 // Allow traps which can happen normally with `unreachable` or a timeout or 419 // such. 420 if e.is::<Trap>() 421 // Also allow failures to instantiate as a result of hitting pooling 422 // limits. 423 || e.is::<wasmtime::PoolConcurrencyLimitError>() 424 // And GC heap OOMs. 425 || e.is::<wasmtime::GcHeapOutOfMemory<()>>() 426 // And thrown exceptions. 427 || e.is::<wasmtime::ThrownException>() 428 { 429 return None; 430 } 431 432 let string = e.to_string(); 433 434 // Currently we instantiate with a `Linker` which can't instantiate 435 // every single module under the sun due to using name-based resolution 436 // rather than positional-based resolution 437 if string.contains("incompatible import type") { 438 return None; 439 } 440 441 // Everything else should be a bug in the fuzzer or a bug in wasmtime 442 panic!("failed to instantiate: {e:?}"); 443 } 444 445 /// Evaluate the function identified by `name` in two different engine 446 /// instances--`lhs` and `rhs`. 447 /// 448 /// Returns `Ok(true)` if more evaluations can happen or `Ok(false)` if the 449 /// instances may have drifted apart and no more evaluations can happen. 450 /// 451 /// # Panics 452 /// 453 /// This will panic if the evaluation is different between engines (e.g., 454 /// results are different, hashed instance is different, one side traps, etc.). 455 pub fn differential( 456 lhs: &mut dyn DiffInstance, 457 lhs_engine: &dyn DiffEngine, 458 rhs: &mut WasmtimeInstance, 459 name: &str, 460 args: &[DiffValue], 461 result_tys: &[DiffValueType], 462 ) -> anyhow::Result<bool> { 463 log::debug!("Evaluating: `{name}` with {args:?}"); 464 let lhs_results = match lhs.evaluate(name, args, result_tys) { 465 Ok(Some(results)) => Ok(results), 466 Err(e) => Err(e), 467 // this engine couldn't execute this type signature, so discard this 468 // execution by returning success. 469 Ok(None) => return Ok(true), 470 }; 471 log::debug!(" -> lhs results on {}: {:?}", lhs.name(), &lhs_results); 472 473 let rhs_results = rhs 474 .evaluate(name, args, result_tys) 475 // wasmtime should be able to invoke any signature, so unwrap this result 476 .map(|results| results.unwrap()); 477 log::debug!(" -> rhs results on {}: {:?}", rhs.name(), &rhs_results); 478 479 // If Wasmtime hit its OOM condition, which is possible since it's set 480 // somewhat low while fuzzing, then don't return an error but return 481 // `false` indicating that differential fuzzing must stop. There's no 482 // guarantee the other engine has the same OOM limits as Wasmtime, and 483 // it's assumed that Wasmtime is configured to have a more conservative 484 // limit than the other engine. 485 if rhs.is_oom() { 486 return Ok(false); 487 } 488 489 match DiffEqResult::new(lhs_engine, lhs_results, rhs_results) { 490 DiffEqResult::Success(lhs, rhs) => assert_eq!(lhs, rhs), 491 DiffEqResult::Poisoned => return Ok(false), 492 DiffEqResult::Failed => {} 493 } 494 495 for (global, ty) in rhs.exported_globals() { 496 log::debug!("Comparing global `{global}`"); 497 let lhs = match lhs.get_global(&global, ty) { 498 Some(val) => val, 499 None => continue, 500 }; 501 let rhs = rhs.get_global(&global, ty).unwrap(); 502 assert_eq!(lhs, rhs); 503 } 504 for (memory, shared) in rhs.exported_memories() { 505 log::debug!("Comparing memory `{memory}`"); 506 let lhs = match lhs.get_memory(&memory, shared) { 507 Some(val) => val, 508 None => continue, 509 }; 510 let rhs = rhs.get_memory(&memory, shared).unwrap(); 511 if lhs == rhs { 512 continue; 513 } 514 eprintln!("differential memory is {} bytes long", lhs.len()); 515 eprintln!("wasmtime memory is {} bytes long", rhs.len()); 516 panic!("memories have differing values"); 517 } 518 519 Ok(true) 520 } 521 522 /// Result of comparing the result of two operations during differential 523 /// execution. 524 pub enum DiffEqResult<T, U> { 525 /// Both engines succeeded. 526 Success(T, U), 527 /// The result has reached the state where engines may have diverged and 528 /// results can no longer be compared. 529 Poisoned, 530 /// Both engines failed with the same error message, and internal state 531 /// should still match between the two engines. 532 Failed, 533 } 534 535 fn wasmtime_trap_is_non_deterministic(trap: &Trap) -> bool { 536 match trap { 537 // Allocations being too large for the GC are 538 // implementation-defined. 539 Trap::AllocationTooLarge | 540 // Stack size, and therefore when overflow happens, is 541 // implementation-defined. 542 Trap::StackOverflow => true, 543 _ => false, 544 } 545 } 546 547 fn wasmtime_error_is_non_deterministic(error: &wasmtime::Error) -> bool { 548 match error.downcast_ref::<Trap>() { 549 Some(trap) => wasmtime_trap_is_non_deterministic(trap), 550 551 // For general, unknown errors, we can't rely on this being 552 // a deterministic Wasm failure that both engines handled 553 // identically, leaving Wasm in identical states. We could 554 // just as easily be hitting engine-specific failures, like 555 // different implementation-defined limits. So simply poison 556 // this execution and move on to the next test. 557 None => true, 558 } 559 } 560 561 impl<T, U> DiffEqResult<T, U> { 562 /// Computes the differential result from executing in two different 563 /// engines. 564 pub fn new( 565 lhs_engine: &dyn DiffEngine, 566 lhs_result: Result<T>, 567 rhs_result: Result<U>, 568 ) -> DiffEqResult<T, U> { 569 match (lhs_result, rhs_result) { 570 (Ok(lhs_result), Ok(rhs_result)) => DiffEqResult::Success(lhs_result, rhs_result), 571 572 // Handle all non-deterministic errors by poisoning this execution's 573 // state, so that we simply move on to the next test. 574 (Err(lhs), _) if lhs_engine.is_non_deterministic_error(&lhs) => { 575 log::debug!("lhs failed non-deterministically: {lhs:?}"); 576 DiffEqResult::Poisoned 577 } 578 (_, Err(rhs)) if wasmtime_error_is_non_deterministic(&rhs) => { 579 log::debug!("rhs failed non-deterministically: {rhs:?}"); 580 DiffEqResult::Poisoned 581 } 582 583 // Both sides failed deterministically. Check that the trap and 584 // state at the time of failure is the same. 585 (Err(lhs), Err(rhs)) => { 586 let rhs = rhs 587 .downcast::<Trap>() 588 .expect("non-traps handled in earlier match arm"); 589 590 debug_assert!( 591 !lhs_engine.is_non_deterministic_error(&lhs), 592 "non-deterministic traps handled in earlier match arm", 593 ); 594 debug_assert!( 595 !wasmtime_trap_is_non_deterministic(&rhs), 596 "non-deterministic traps handled in earlier match arm", 597 ); 598 599 lhs_engine.assert_error_match(&lhs, &rhs); 600 DiffEqResult::Failed 601 } 602 603 // A real bug is found if only one side fails. 604 (Ok(_), Err(err)) => panic!("only the `rhs` failed for this input: {err:?}"), 605 (Err(err), Ok(_)) => panic!("only the `lhs` failed for this input: {err:?}"), 606 } 607 } 608 } 609 610 /// Invoke the given API calls. 611 pub fn make_api_calls(api: generators::api::ApiCalls) { 612 use crate::generators::api::ApiCall; 613 use std::collections::HashMap; 614 615 let mut store: Option<Store<StoreLimits>> = None; 616 let mut modules: HashMap<usize, Module> = Default::default(); 617 let mut instances: HashMap<usize, Instance> = Default::default(); 618 619 for call in api.calls { 620 match call { 621 ApiCall::StoreNew(config) => { 622 log::trace!("creating store"); 623 assert!(store.is_none()); 624 store = Some(config.to_store()); 625 } 626 627 ApiCall::ModuleNew { id, wasm } => { 628 log::debug!("creating module: {id}"); 629 log_wasm(&wasm); 630 let module = match Module::new(store.as_ref().unwrap().engine(), &wasm) { 631 Ok(m) => m, 632 Err(_) => continue, 633 }; 634 let old = modules.insert(id, module); 635 assert!(old.is_none()); 636 } 637 638 ApiCall::ModuleDrop { id } => { 639 log::trace!("dropping module: {id}"); 640 drop(modules.remove(&id)); 641 } 642 643 ApiCall::InstanceNew { id, module } => { 644 log::trace!("instantiating module {module} as {id}"); 645 let module = match modules.get(&module) { 646 Some(m) => m, 647 None => continue, 648 }; 649 650 let store = store.as_mut().unwrap(); 651 if let Some(instance) = instantiate_with_dummy(store, module) { 652 instances.insert(id, instance); 653 } 654 } 655 656 ApiCall::InstanceDrop { id } => { 657 log::trace!("dropping instance {id}"); 658 instances.remove(&id); 659 } 660 661 ApiCall::CallExportedFunc { instance, nth } => { 662 log::trace!("calling instance export {instance} / {nth}"); 663 let instance = match instances.get(&instance) { 664 Some(i) => i, 665 None => { 666 // Note that we aren't guaranteed to instantiate valid 667 // modules, see comments in `InstanceNew` for details on 668 // that. But the API call generator can't know if 669 // instantiation failed, so we might not actually have 670 // this instance. When that's the case, just skip the 671 // API call and keep going. 672 continue; 673 } 674 }; 675 let store = store.as_mut().unwrap(); 676 677 let funcs = instance 678 .exports(&mut *store) 679 .filter_map(|e| match e.into_extern() { 680 Extern::Func(f) => Some(f), 681 _ => None, 682 }) 683 .collect::<Vec<_>>(); 684 685 if funcs.is_empty() { 686 continue; 687 } 688 689 let nth = nth % funcs.len(); 690 let f = &funcs[nth]; 691 let ty = f.ty(&store); 692 if let Some(params) = ty 693 .params() 694 .map(|p| p.default_value()) 695 .collect::<Option<Vec<_>>>() 696 { 697 let mut results = vec![Val::I32(0); ty.results().len()]; 698 let _ = f.call(store, ¶ms, &mut results); 699 } 700 } 701 } 702 } 703 } 704 705 /// Executes the wast `test` with the `config` specified. 706 /// 707 /// Ensures that wast tests pass regardless of the `Config`. 708 pub fn wast_test(u: &mut arbitrary::Unstructured<'_>) -> arbitrary::Result<()> { 709 crate::init_fuzzing(); 710 711 let mut fuzz_config: generators::Config = u.arbitrary()?; 712 let test: generators::WastTest = u.arbitrary()?; 713 714 let test = &test.test; 715 716 if test.config.component_model_async() || u.arbitrary()? { 717 fuzz_config.enable_async(u)?; 718 } 719 720 // Discard tests that allocate a lot of memory as we don't want to OOM the 721 // fuzzer and we also limit memory growth which would cause the test to 722 // fail. 723 if test.config.hogs_memory.unwrap_or(false) { 724 return Err(arbitrary::Error::IncorrectFormat); 725 } 726 727 // Transform `fuzz_config` to be valid for `test` and make sure that this 728 // test is supposed to pass. 729 let wast_config = fuzz_config.make_wast_test_compliant(test); 730 if test.should_fail(&wast_config) { 731 return Err(arbitrary::Error::IncorrectFormat); 732 } 733 734 // Winch requires AVX and AVX2 for SIMD tests to pass so don't run the test 735 // if either isn't enabled. 736 if fuzz_config.wasmtime.compiler_strategy == CompilerStrategy::Winch 737 && test.config.simd() 738 && (fuzz_config 739 .wasmtime 740 .codegen_flag("has_avx") 741 .is_some_and(|value| value == "false") 742 || fuzz_config 743 .wasmtime 744 .codegen_flag("has_avx2") 745 .is_some_and(|value| value == "false")) 746 { 747 log::warn!( 748 "Skipping Wast test because Winch doesn't support SIMD tests with AVX or AVX2 disabled" 749 ); 750 return Err(arbitrary::Error::IncorrectFormat); 751 } 752 753 // Fuel and epochs don't play well with threads right now, so exclude any 754 // thread-spawning test if it looks like threads are spawned in that case. 755 if fuzz_config.wasmtime.consume_fuel || fuzz_config.wasmtime.epoch_interruption { 756 if test.contents.contains("(thread") { 757 return Err(arbitrary::Error::IncorrectFormat); 758 } 759 } 760 761 log::debug!("running {:?}", test.path); 762 let async_ = if fuzz_config.wasmtime.async_config == generators::AsyncConfig::Disabled { 763 wasmtime_wast::Async::No 764 } else { 765 wasmtime_wast::Async::Yes 766 }; 767 log::debug!("async: {async_:?}"); 768 let engine = Engine::new(&fuzz_config.to_wasmtime()).unwrap(); 769 let mut wast_context = WastContext::new(&engine, async_, move |store| { 770 fuzz_config.configure_store_epoch_and_fuel(store); 771 }); 772 wast_context 773 .register_spectest(&wasmtime_wast::SpectestConfig { 774 use_shared_memory: true, 775 suppress_prints: true, 776 }) 777 .unwrap(); 778 wast_context 779 .run_wast(test.path.to_str().unwrap(), test.contents.as_bytes()) 780 .unwrap(); 781 Ok(()) 782 } 783 784 /// Execute a series of `gc` operations. 785 /// 786 /// Returns the number of `gc` operations which occurred throughout the test 787 /// case -- used to test below that gc happens reasonably soon and eventually. 788 pub fn gc_ops(mut fuzz_config: generators::Config, mut ops: GcOps) -> Result<usize> { 789 let expected_drops = Arc::new(AtomicUsize::new(0)); 790 let num_dropped = Arc::new(AtomicUsize::new(0)); 791 792 let num_gcs = Arc::new(AtomicUsize::new(0)); 793 { 794 fuzz_config.wasmtime.consume_fuel = true; 795 let mut store = fuzz_config.to_store(); 796 store.set_fuel(1_000).unwrap(); 797 798 let wasm = ops.to_wasm_binary(); 799 log_wasm(&wasm); 800 let module = match compile_module(store.engine(), &wasm, KnownValid::No, &fuzz_config) { 801 Some(m) => m, 802 None => return Ok(0), 803 }; 804 805 let mut linker = Linker::new(store.engine()); 806 807 // To avoid timeouts, limit the number of explicit GCs we perform per 808 // test case. 809 const MAX_GCS: usize = 5; 810 811 let func_ty = FuncType::new( 812 store.engine(), 813 vec![], 814 vec![ValType::EXTERNREF, ValType::EXTERNREF, ValType::EXTERNREF], 815 ); 816 let func = Func::new(&mut store, func_ty, { 817 let num_dropped = num_dropped.clone(); 818 let expected_drops = expected_drops.clone(); 819 let num_gcs = num_gcs.clone(); 820 move |mut caller: Caller<'_, StoreLimits>, _params, results| { 821 log::info!("gc_ops: GC"); 822 if num_gcs.fetch_add(1, SeqCst) < MAX_GCS { 823 caller.gc(None); 824 } 825 826 let a = ExternRef::new( 827 &mut caller, 828 CountDrops::new(&expected_drops, num_dropped.clone()), 829 )?; 830 let b = ExternRef::new( 831 &mut caller, 832 CountDrops::new(&expected_drops, num_dropped.clone()), 833 )?; 834 let c = ExternRef::new( 835 &mut caller, 836 CountDrops::new(&expected_drops, num_dropped.clone()), 837 )?; 838 839 log::info!("gc_ops: gc() -> ({a:?}, {b:?}, {c:?})"); 840 results[0] = Some(a).into(); 841 results[1] = Some(b).into(); 842 results[2] = Some(c).into(); 843 Ok(()) 844 } 845 }); 846 linker.define(&store, "", "gc", func).unwrap(); 847 848 linker 849 .func_wrap("", "take_refs", { 850 let expected_drops = expected_drops.clone(); 851 move |caller: Caller<'_, StoreLimits>, 852 a: Option<Rooted<ExternRef>>, 853 b: Option<Rooted<ExternRef>>, 854 c: Option<Rooted<ExternRef>>| 855 -> Result<()> { 856 log::info!("gc_ops: take_refs({a:?}, {b:?}, {c:?})",); 857 858 // Do the assertion on each ref's inner data, even though it 859 // all points to the same atomic, so that if we happen to 860 // run into a use-after-free bug with one of these refs we 861 // are more likely to trigger a segfault. 862 if let Some(a) = a { 863 let a = a 864 .data(&caller)? 865 .unwrap() 866 .downcast_ref::<CountDrops>() 867 .unwrap(); 868 assert!(a.0.load(SeqCst) <= expected_drops.load(SeqCst)); 869 } 870 if let Some(b) = b { 871 let b = b 872 .data(&caller)? 873 .unwrap() 874 .downcast_ref::<CountDrops>() 875 .unwrap(); 876 assert!(b.0.load(SeqCst) <= expected_drops.load(SeqCst)); 877 } 878 if let Some(c) = c { 879 let c = c 880 .data(&caller)? 881 .unwrap() 882 .downcast_ref::<CountDrops>() 883 .unwrap(); 884 assert!(c.0.load(SeqCst) <= expected_drops.load(SeqCst)); 885 } 886 Ok(()) 887 } 888 }) 889 .unwrap(); 890 891 let func_ty = FuncType::new( 892 store.engine(), 893 vec![], 894 vec![ValType::EXTERNREF, ValType::EXTERNREF, ValType::EXTERNREF], 895 ); 896 let func = Func::new(&mut store, func_ty, { 897 let num_dropped = num_dropped.clone(); 898 let expected_drops = expected_drops.clone(); 899 move |mut caller, _params, results| { 900 log::info!("gc_ops: make_refs"); 901 902 let a = ExternRef::new( 903 &mut caller, 904 CountDrops::new(&expected_drops, num_dropped.clone()), 905 )?; 906 let b = ExternRef::new( 907 &mut caller, 908 CountDrops::new(&expected_drops, num_dropped.clone()), 909 )?; 910 let c = ExternRef::new( 911 &mut caller, 912 CountDrops::new(&expected_drops, num_dropped.clone()), 913 )?; 914 915 log::info!("gc_ops: make_refs() -> ({a:?}, {b:?}, {c:?})"); 916 917 results[0] = Some(a).into(); 918 results[1] = Some(b).into(); 919 results[2] = Some(c).into(); 920 921 Ok(()) 922 } 923 }); 924 linker.define(&store, "", "make_refs", func).unwrap(); 925 926 let func_ty = FuncType::new( 927 store.engine(), 928 vec![ValType::Ref(RefType::new(false, HeapType::Any))], 929 vec![], 930 ); 931 932 let func = Func::new(&mut store, func_ty, { 933 move |_caller: Caller<'_, StoreLimits>, _params, _results| { 934 log::info!("gc_ops: take_struct(<ref any>)"); 935 Ok(()) 936 } 937 }); 938 939 linker.define(&store, "", "take_struct", func).unwrap(); 940 941 for imp in module.imports() { 942 if imp.module() == "" { 943 let name = imp.name(); 944 if name.starts_with("take_struct_") { 945 if let wasmtime::ExternType::Func(ft) = imp.ty() { 946 let imp_name = name.to_string(); 947 let func = 948 Func::new(&mut store, ft.clone(), move |_caller, _params, _results| { 949 log::info!("gc_ops: {imp_name}(<typed structref>)"); 950 Ok(()) 951 }); 952 linker.define(&store, "", name, func).unwrap(); 953 } 954 } 955 } 956 } 957 958 let instance = linker.instantiate(&mut store, &module).unwrap(); 959 let run = instance.get_func(&mut store, "run").unwrap(); 960 961 { 962 let mut scope = RootScope::new(&mut store); 963 964 log::info!( 965 "gc_ops: begin allocating {} externref arguments", 966 ops.limits.num_globals 967 ); 968 let args: Vec<_> = (0..ops.limits.num_params) 969 .map(|_| { 970 Ok(Val::ExternRef(Some(ExternRef::new( 971 &mut scope, 972 CountDrops::new(&expected_drops, num_dropped.clone()), 973 )?))) 974 }) 975 .collect::<Result<_>>()?; 976 log::info!( 977 "gc_ops: end allocating {} externref arguments", 978 ops.limits.num_globals 979 ); 980 981 // The generated function should always return a trap. The only two 982 // valid traps are table-out-of-bounds which happens through `table.get` 983 // and `table.set` generated or an out-of-fuel trap. Otherwise any other 984 // error is unexpected and should fail fuzzing. 985 log::info!("gc_ops: calling into Wasm `run` function"); 986 let err = run.call(&mut scope, &args, &mut []).unwrap_err(); 987 if err.is::<GcHeapOutOfMemory<CountDrops>>() || err.is::<GcHeapOutOfMemory<()>>() { 988 // Accept GC OOM as an allowed outcome for this fuzzer. 989 } else { 990 let trap = err 991 .downcast::<Trap>() 992 .expect("if not GC oom, error should be a Wasm trap"); 993 match trap { 994 Trap::TableOutOfBounds | Trap::OutOfFuel | Trap::AllocationTooLarge => {} 995 _ => panic!("unexpected trap: {trap}"), 996 } 997 } 998 } 999 1000 // Do a final GC after running the Wasm. 1001 store.gc(None); 1002 } 1003 1004 assert_eq!(num_dropped.load(SeqCst), expected_drops.load(SeqCst)); 1005 return Ok(num_gcs.load(SeqCst)); 1006 1007 struct CountDrops(Arc<AtomicUsize>); 1008 1009 impl CountDrops { 1010 fn new(expected_drops: &AtomicUsize, num_dropped: Arc<AtomicUsize>) -> Self { 1011 let expected = expected_drops.fetch_add(1, SeqCst); 1012 log::info!( 1013 "CountDrops::new: expected drops: {expected} -> {}", 1014 expected + 1 1015 ); 1016 Self(num_dropped) 1017 } 1018 } 1019 1020 impl Drop for CountDrops { 1021 fn drop(&mut self) { 1022 let drops = self.0.fetch_add(1, SeqCst); 1023 log::info!("CountDrops::drop: actual drops: {drops} -> {}", drops + 1); 1024 } 1025 } 1026 } 1027 1028 #[derive(Default)] 1029 struct HelperThread { 1030 state: Arc<HelperThreadState>, 1031 thread: Option<std::thread::JoinHandle<()>>, 1032 } 1033 1034 #[derive(Default)] 1035 struct HelperThreadState { 1036 should_exit: Mutex<bool>, 1037 should_exit_cvar: Condvar, 1038 } 1039 1040 impl HelperThread { 1041 fn run_periodically(&mut self, dur: Duration, mut closure: impl FnMut() + Send + 'static) { 1042 let state = self.state.clone(); 1043 self.thread = Some(std::thread::spawn(move || { 1044 // Using our mutex/condvar we wait here for the first of `dur` to 1045 // pass or the `HelperThread` instance to get dropped. 1046 let mut should_exit = state.should_exit.lock().unwrap(); 1047 while !*should_exit { 1048 let (lock, result) = state 1049 .should_exit_cvar 1050 .wait_timeout(should_exit, dur) 1051 .unwrap(); 1052 should_exit = lock; 1053 // If we timed out for sure then there's no need to continue 1054 // since we'll just abort on the next `checked_sub` anyway. 1055 if result.timed_out() { 1056 closure(); 1057 } 1058 } 1059 })); 1060 } 1061 } 1062 1063 impl Drop for HelperThread { 1064 fn drop(&mut self) { 1065 let thread = match self.thread.take() { 1066 Some(thread) => thread, 1067 None => return, 1068 }; 1069 // Signal our thread that it should exit and wake it up in case it's 1070 // sleeping. 1071 *self.state.should_exit.lock().unwrap() = true; 1072 self.state.should_exit_cvar.notify_one(); 1073 1074 // ... and then wait for the thread to exit to ensure we clean up 1075 // after ourselves. 1076 thread.join().unwrap(); 1077 } 1078 } 1079 1080 /// Generate and execute a `crate::generators::component_types::TestCase` using the specified `input` to create 1081 /// arbitrary types and values. 1082 pub fn dynamic_component_api_target(input: &mut arbitrary::Unstructured) -> arbitrary::Result<()> { 1083 use crate::generators::component_types; 1084 use wasmtime::component::{Component, Linker, Val}; 1085 use wasmtime_test_util::component_fuzz::{ 1086 EXPORT_FUNCTION, IMPORT_FUNCTION, MAX_TYPE_DEPTH, TestCase, Type, 1087 }; 1088 1089 crate::init_fuzzing(); 1090 1091 let mut types = Vec::new(); 1092 let mut type_fuel = 500; 1093 1094 for _ in 0..5 { 1095 types.push(Type::generate(input, MAX_TYPE_DEPTH, &mut type_fuel)?); 1096 } 1097 1098 let case = TestCase::generate(&types, input)?; 1099 1100 let mut config = wasmtime_test_util::component::config(); 1101 config.async_support(true); 1102 config.wasm_component_model_async(true); 1103 config.wasm_component_model_async_stackful(true); 1104 config.debug_adapter_modules(input.arbitrary()?); 1105 let engine = Engine::new(&config).unwrap(); 1106 let mut store = Store::new(&engine, (Vec::new(), None)); 1107 let wat = case.declarations().make_component(); 1108 let wat = wat.as_bytes(); 1109 log_wasm(wat); 1110 let component = Component::new(&engine, wat).unwrap(); 1111 let mut linker = Linker::new(&engine); 1112 1113 fn host_function( 1114 mut cx: StoreContextMut<'_, (Vec<Val>, Option<Vec<Val>>)>, 1115 params: &[Val], 1116 results: &mut [Val], 1117 ) -> Result<()> { 1118 log::trace!("received params {params:?}"); 1119 let (expected_args, expected_results) = cx.data_mut(); 1120 assert_eq!(params.len(), expected_args.len()); 1121 for (expected, actual) in expected_args.iter().zip(params) { 1122 assert_eq!(expected, actual); 1123 } 1124 results.clone_from_slice(&expected_results.take().unwrap()); 1125 log::trace!("returning results {results:?}"); 1126 Ok(()) 1127 } 1128 1129 if case.options.host_async { 1130 linker 1131 .root() 1132 .func_new_concurrent(IMPORT_FUNCTION, { 1133 move |cx: &Accessor<_, _>, _, params: &[Val], results: &mut [Val]| { 1134 Box::pin(async move { 1135 cx.with(|mut store| host_function(store.as_context_mut(), params, results)) 1136 }) 1137 } 1138 }) 1139 .unwrap(); 1140 } else { 1141 linker 1142 .root() 1143 .func_new(IMPORT_FUNCTION, { 1144 move |cx, _, params, results| host_function(cx, params, results) 1145 }) 1146 .unwrap(); 1147 } 1148 1149 block_on(async { 1150 let instance = linker 1151 .instantiate_async(&mut store, &component) 1152 .await 1153 .unwrap(); 1154 let func = instance.get_func(&mut store, EXPORT_FUNCTION).unwrap(); 1155 let ty = func.ty(&store); 1156 1157 while input.arbitrary()? { 1158 let params = ty 1159 .params() 1160 .map(|(_, ty)| component_types::arbitrary_val(&ty, input)) 1161 .collect::<arbitrary::Result<Vec<_>>>()?; 1162 let results = ty 1163 .results() 1164 .map(|ty| component_types::arbitrary_val(&ty, input)) 1165 .collect::<arbitrary::Result<Vec<_>>>()?; 1166 1167 *store.data_mut() = (params.clone(), Some(results.clone())); 1168 1169 log::trace!("passing params {params:?}"); 1170 let mut actual = vec![Val::Bool(false); results.len()]; 1171 if case.options.guest_caller_async { 1172 store 1173 .run_concurrent(async |a| { 1174 func.call_concurrent(a, ¶ms, &mut actual).await.unwrap(); 1175 }) 1176 .await 1177 .unwrap(); 1178 } else { 1179 func.call_async(&mut store, ¶ms, &mut actual) 1180 .await 1181 .unwrap(); 1182 func.post_return_async(&mut store).await.unwrap(); 1183 } 1184 log::trace!("received results {actual:?}"); 1185 assert_eq!(actual, results); 1186 } 1187 Ok(()) 1188 }) 1189 } 1190 1191 /// Instantiates a wasm module and runs its exports with dummy values, all in 1192 /// an async fashion. 1193 /// 1194 /// Attempts to stress yields in host functions to ensure that exiting and 1195 /// resuming a wasm function call works. 1196 pub fn call_async(wasm: &[u8], config: &generators::Config, mut poll_amts: &[u32]) { 1197 let mut store = config.to_store(); 1198 let module = match compile_module(store.engine(), wasm, KnownValid::Yes, config) { 1199 Some(module) => module, 1200 None => return, 1201 }; 1202 1203 // Configure a helper thread to periodically increment the epoch to 1204 // forcibly enable yields-via-epochs if epochs are in use. Note that this 1205 // is required because the wasm isn't otherwise guaranteed to necessarily 1206 // call any imports which will also increment the epoch. 1207 let mut helper_thread = HelperThread::default(); 1208 if let generators::AsyncConfig::YieldWithEpochs { dur, .. } = &config.wasmtime.async_config { 1209 let engine = store.engine().clone(); 1210 helper_thread.run_periodically(*dur, move || engine.increment_epoch()); 1211 } 1212 1213 // Generate a `Linker` where all function imports are custom-built to yield 1214 // periodically and additionally increment the epoch. 1215 let mut imports = Vec::new(); 1216 for import in module.imports() { 1217 let item = match import.ty() { 1218 ExternType::Func(ty) => { 1219 let poll_amt = take_poll_amt(&mut poll_amts); 1220 Func::new_async(&mut store, ty.clone(), move |caller, _, results| { 1221 let ty = ty.clone(); 1222 Box::new(async move { 1223 caller.engine().increment_epoch(); 1224 log::info!("yielding {poll_amt} times in import"); 1225 YieldN(poll_amt).await; 1226 for (ret_ty, result) in ty.results().zip(results) { 1227 *result = ret_ty.default_value().unwrap(); 1228 } 1229 Ok(()) 1230 }) 1231 }) 1232 .into() 1233 } 1234 other_ty => match other_ty.default_value(&mut store) { 1235 Ok(item) => item, 1236 Err(e) => { 1237 log::warn!("couldn't create import for {import:?}: {e:?}"); 1238 return; 1239 } 1240 }, 1241 }; 1242 imports.push(item); 1243 } 1244 1245 // Run the instantiation process, asynchronously, and if everything 1246 // succeeds then pull out the instance. 1247 // log::info!("starting instantiation"); 1248 let instance = block_on(Timeout { 1249 future: Instance::new_async(&mut store, &module, &imports), 1250 polls: take_poll_amt(&mut poll_amts), 1251 end: Instant::now() + Duration::from_millis(2_000), 1252 }); 1253 let instance = match instance { 1254 Ok(instantiation_result) => match unwrap_instance(&store, instantiation_result) { 1255 Some(instance) => instance, 1256 None => { 1257 log::info!("instantiation hit a nominal error"); 1258 return; // resource exhaustion or limits met 1259 } 1260 }, 1261 Err(_) => { 1262 log::info!("instantiation failed to complete"); 1263 return; // Timed out or ran out of polls 1264 } 1265 }; 1266 1267 // Run each export of the instance in the same manner as instantiation 1268 // above. Dummy values are passed in for argument values here: 1269 // 1270 // TODO: this should probably be more clever about passing in arguments for 1271 // example they might be used as pointers or something and always using 0 1272 // isn't too interesting. 1273 let funcs = instance 1274 .exports(&mut store) 1275 .filter_map(|e| { 1276 let name = e.name().to_string(); 1277 let func = e.into_extern().into_func()?; 1278 Some((name, func)) 1279 }) 1280 .collect::<Vec<_>>(); 1281 for (name, func) in funcs { 1282 let ty = func.ty(&store); 1283 let params = ty 1284 .params() 1285 .map(|ty| ty.default_value().unwrap()) 1286 .collect::<Vec<_>>(); 1287 let mut results = ty 1288 .results() 1289 .map(|ty| ty.default_value().unwrap()) 1290 .collect::<Vec<_>>(); 1291 1292 log::info!("invoking export {name:?}"); 1293 let future = func.call_async(&mut store, ¶ms, &mut results); 1294 match block_on(Timeout { 1295 future, 1296 polls: take_poll_amt(&mut poll_amts), 1297 end: Instant::now() + Duration::from_millis(2_000), 1298 }) { 1299 // On success or too many polls, try the next export. 1300 Ok(_) | Err(Exhausted::Polls) => {} 1301 1302 // If time ran out then stop the current test case as we might have 1303 // already sucked up a lot of time for this fuzz test case so don't 1304 // keep it going. 1305 Err(Exhausted::Time) => return, 1306 } 1307 } 1308 1309 fn take_poll_amt(polls: &mut &[u32]) -> u32 { 1310 match polls.split_first() { 1311 Some((a, rest)) => { 1312 *polls = rest; 1313 *a 1314 } 1315 None => 0, 1316 } 1317 } 1318 1319 /// Helper future to yield N times before resolving. 1320 struct YieldN(u32); 1321 1322 impl Future for YieldN { 1323 type Output = (); 1324 1325 fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<()> { 1326 if self.0 == 0 { 1327 Poll::Ready(()) 1328 } else { 1329 self.0 -= 1; 1330 cx.waker().wake_by_ref(); 1331 Poll::Pending 1332 } 1333 } 1334 } 1335 1336 /// Helper future for applying a timeout to `future` up to either when `end` 1337 /// is the current time or `polls` polls happen. 1338 /// 1339 /// Note that this helps to time out infinite loops in wasm, for example. 1340 struct Timeout<F> { 1341 future: F, 1342 /// If the future isn't ready by this time then the `Timeout<F>` future 1343 /// will return `None`. 1344 end: Instant, 1345 /// If the future doesn't resolve itself in this many calls to `poll` 1346 /// then the `Timeout<F>` future will return `None`. 1347 polls: u32, 1348 } 1349 1350 enum Exhausted { 1351 Time, 1352 Polls, 1353 } 1354 1355 impl<F: Future> Future for Timeout<F> { 1356 type Output = Result<F::Output, Exhausted>; 1357 1358 fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> { 1359 let (end, polls, future) = unsafe { 1360 let me = self.get_unchecked_mut(); 1361 (me.end, &mut me.polls, Pin::new_unchecked(&mut me.future)) 1362 }; 1363 match future.poll(cx) { 1364 Poll::Ready(val) => Poll::Ready(Ok(val)), 1365 Poll::Pending => { 1366 if Instant::now() >= end { 1367 log::warn!("future operation timed out"); 1368 return Poll::Ready(Err(Exhausted::Time)); 1369 } 1370 if *polls == 0 { 1371 log::warn!("future operation ran out of polls"); 1372 return Poll::Ready(Err(Exhausted::Polls)); 1373 } 1374 *polls -= 1; 1375 Poll::Pending 1376 } 1377 } 1378 } 1379 } 1380 } 1381 1382 #[cfg(test)] 1383 mod tests { 1384 use super::*; 1385 use crate::test::{gen_until_pass, test_n_times}; 1386 use wasmparser::{Validator, WasmFeatures}; 1387 1388 // Test that the `gc_ops` fuzzer eventually runs the gc function in the host. 1389 // We've historically had issues where this fuzzer accidentally wasn't fuzzing 1390 // anything for a long time so this is an attempt to prevent that from happening 1391 // again. 1392 #[test] 1393 fn gc_ops_eventually_gcs() { 1394 // Skip if we're under emulation because some fuzz configurations will do 1395 // large address space reservations that QEMU doesn't handle well. 1396 if std::env::var("WASMTIME_TEST_NO_HOG_MEMORY").is_ok() { 1397 return; 1398 } 1399 1400 let ok = gen_until_pass(|(config, test), _| { 1401 let result = gc_ops(config, test)?; 1402 Ok(result > 0) 1403 }); 1404 1405 if !ok { 1406 panic!("gc was never found"); 1407 } 1408 } 1409 1410 #[test] 1411 fn module_generation_uses_expected_proposals() { 1412 // Proposals that Wasmtime supports. Eventually a module should be 1413 // generated that needs these proposals. 1414 let mut expected = WasmFeatures::MUTABLE_GLOBAL 1415 | WasmFeatures::FLOATS 1416 | WasmFeatures::SIGN_EXTENSION 1417 | WasmFeatures::SATURATING_FLOAT_TO_INT 1418 | WasmFeatures::MULTI_VALUE 1419 | WasmFeatures::BULK_MEMORY 1420 | WasmFeatures::REFERENCE_TYPES 1421 | WasmFeatures::SIMD 1422 | WasmFeatures::MULTI_MEMORY 1423 | WasmFeatures::RELAXED_SIMD 1424 | WasmFeatures::THREADS 1425 | WasmFeatures::TAIL_CALL 1426 | WasmFeatures::WIDE_ARITHMETIC 1427 | WasmFeatures::MEMORY64 1428 | WasmFeatures::FUNCTION_REFERENCES 1429 | WasmFeatures::GC 1430 | WasmFeatures::GC_TYPES 1431 | WasmFeatures::CUSTOM_PAGE_SIZES 1432 | WasmFeatures::EXTENDED_CONST 1433 | WasmFeatures::EXCEPTIONS; 1434 1435 // All other features that wasmparser supports, which is presumably a 1436 // superset of the features that wasm-smith supports, are listed here as 1437 // unexpected. This means, for example, that if wasm-smith updates to 1438 // include a new proposal by default that wasmtime implements then it 1439 // will be required to be listed above. 1440 let unexpected = WasmFeatures::all() ^ expected; 1441 1442 let ok = gen_until_pass(|config: generators::Config, u| { 1443 let wasm = config.generate(u, None)?.to_bytes(); 1444 1445 // Double-check the module is valid 1446 Validator::new_with_features(WasmFeatures::all()).validate_all(&wasm)?; 1447 1448 // If any of the unexpected features are removed then this module 1449 // should always be valid, otherwise something went wrong. 1450 for feature in unexpected.iter() { 1451 let ok = 1452 Validator::new_with_features(WasmFeatures::all() ^ feature).validate_all(&wasm); 1453 if ok.is_err() { 1454 anyhow::bail!("generated a module with {feature:?} but that wasn't expected"); 1455 } 1456 } 1457 1458 // If any of `expected` is removed and the module fails to validate, 1459 // then that means the module requires that feature. Remove that 1460 // from the set of features we're then expecting. 1461 for feature in expected.iter() { 1462 let ok = 1463 Validator::new_with_features(WasmFeatures::all() ^ feature).validate_all(&wasm); 1464 if ok.is_err() { 1465 expected ^= feature; 1466 } 1467 } 1468 1469 Ok(expected.is_empty()) 1470 }); 1471 1472 if !ok { 1473 panic!("never generated wasm module using {expected:?}"); 1474 } 1475 } 1476 1477 #[test] 1478 fn wast_smoke_test() { 1479 test_n_times(50, |(), u| super::wast_test(u)); 1480 } 1481 1482 #[test] 1483 fn dynamic_component_api_smoke_test() { 1484 test_n_times(50, |(), u| super::dynamic_component_api_target(u)); 1485 } 1486 } 1487