A lightweight WebAssembly runtime that is fast, secure, and standards-compliant
Fix panic in `atomic_wait{32,64}` with massive timeouts (#13038)
Alex Crichtonf4b58a70ff43
diff --git a/crates/wasmtime/src/runtime/vm/memory/shared_memory.rs b/crates/wasmtime/src/runtime/vm/memory/shared_memory.rsindex a34352b734..51c9248beb 100644--- a/crates/wasmtime/src/runtime/vm/memory/shared_memory.rs+++ b/crates/wasmtime/src/runtime/vm/memory/shared_memory.rs@@ -138,7 +138,12 @@ impl SharedMemory {assert!(std::mem::size_of::<AtomicU32>() == 4);assert!(std::mem::align_of::<AtomicU32>() <= 4);let atomic = unsafe { AtomicU32::from_ptr(addr.cast()) };- let deadline = timeout.map(|d| Instant::now() + d);++ // Note that `checked_add` is used such that when `timeout` is too large+ // it'll cause there to be no timeout at all if we can't represent the+ // deadline. That effectively maps to the requested timeout since if we+ // can't represent the deadline we'll be here awhile.+ let deadline = timeout.and_then(|d| Instant::now().checked_add(d));WAITER.with(|waiter| {let mut waiter = waiter.borrow_mut();@@ -162,7 +167,9 @@ impl SharedMemory {assert!(std::mem::size_of::<AtomicU64>() == 8);assert!(std::mem::align_of::<AtomicU64>() <= 8);let atomic = unsafe { AtomicU64::from_ptr(addr.cast()) };- let deadline = timeout.map(|d| Instant::now() + d);++ // See `atomic_wait32` for why this is using `checked_add`.+ let deadline = timeout.and_then(|d| Instant::now().checked_add(d));WAITER.with(|waiter| {let mut waiter = waiter.borrow_mut();diff --git a/tests/all/memory.rs b/tests/all/memory.rsindex 57d7501bc8..94fd7e2398 100644--- a/tests/all/memory.rs+++ b/tests/all/memory.rs@@ -1,5 +1,7 @@use rayon::prelude::*;-use std::sync::atomic::{AtomicU32, Ordering::SeqCst};+use std::sync::Arc;+use std::sync::atomic::{AtomicBool, AtomicU32, Ordering::SeqCst};+use std::thread;use std::time::Duration;use wasmtime::*;use wasmtime_test_macros::wasmtime_test;@@ -777,3 +779,39 @@ fn configure_zero(config: &mut Config) -> Result<()> {Ok(())}++#[test]+fn atomic_wait_massive_timeout() -> Result<()> {+ let mut config = Config::new();+ config.shared_memory(true);+ let engine = Engine::new(&config)?;++ let memory = SharedMemory::new(&engine, MemoryType::shared(1, 1))?;+ let result = memory.atomic_wait32(0, 1, Some(Duration::MAX));+ assert_eq!(result, Ok(WaitResult::Mismatch));+ let result = memory.atomic_wait64(0, 1, Some(Duration::MAX));+ assert_eq!(result, Ok(WaitResult::Mismatch));++ let done = Arc::new(AtomicBool::new(false));+ let t = thread::spawn({+ let memory = memory.clone();+ let done = done.clone();+ move || {+ while !done.load(SeqCst) {+ memory.atomic_notify(0, 1).unwrap();+ memory.atomic_notify(8, 1).unwrap();+ }+ }+ });++ let result = memory.atomic_wait32(0, 0, Some(Duration::MAX));+ assert_eq!(result, Ok(WaitResult::Ok));+ let result = memory.atomic_wait64(8, 0, Some(Duration::MAX));+ assert_eq!(result, Ok(WaitResult::Ok));++ done.store(true, SeqCst);++ t.join().unwrap();++ Ok(())+}