Truly independent web browser
AK+LibJS+LibWasm+LibWeb: Replace the futex with waiter lists
Andreas Kling6b8b7ed395ea
diff --git a/AK/Rust/src/futex.rs b/AK/Rust/src/futex.rsdeleted file mode 100644index 92e369febdf..00000000000--- a/AK/Rust/src/futex.rs+++ /dev/null@@ -1,915 +0,0 @@-/*- * Copyright (c) 2026-present, the Ladybird developers.- *- * SPDX-License-Identifier: BSD-2-Clause- */--//! Libraries/LibCore/Futex.cpp: waiting on and waking a word of memory, which Atomics.wait, Atomics.notify and their-//! WebAssembly counterparts use.--#[cfg(any(target_os = "macos", target_os = "linux"))]-use core::sync::atomic::AtomicPtr;-use core::sync::atomic::{AtomicBool, AtomicU32, AtomicU64, Ordering};-use core::time::Duration;-#[cfg(target_os = "macos")]-use std::time::Instant;--/// Core::AtomicWaitResult.-#[derive(Clone, Copy, Debug, PartialEq, Eq)]-pub enum AtomicWaitResult {- Woken,- NotEqual,- TimedOut,- Interrupted,-}--/// The word of a shared typed array element that Atomics.wait waits on, which is 4 or 8 bytes wide.-#[derive(Clone, Copy)]-pub enum WaitWord<'a> {- Word32(&'a AtomicU32),- Word64(&'a AtomicU64),-}--impl WaitWord<'_> {- /// The address waiters key on, which is that of the low 32-bit half of the word.- fn address(self) -> *mut u32 {- match self {- WaitWord::Word32(word) => word.as_ptr(),- WaitWord::Word64(word) => word.as_ptr().cast(),- }- }-- /// A sequentially-consistent read, matching the memory model's read for the wait comparison.- fn load(self) -> u64 {- match self {- WaitWord::Word32(word) => u64::from(word.load(Ordering::SeqCst)),- WaitWord::Word64(word) => word.load(Ordering::SeqCst),- }- }-}--// Whether the word currently equals expected, masked to the wait size.-fn word_equals(word: WaitWord<'_>, expected: u64) -> bool {- let mask = match word {- WaitWord::Word32(_) => u64::from(u32::MAX),- WaitWord::Word64(_) => u64::MAX,- };- (word.load() & mask) == (expected & mask)-}--/// Stops the waits of one agent for good, from any thread. Only a notify ends a wait otherwise, and a wait that ends-/// and starts over would lose its place among the waiters, and any notify that came in between.-///-/// A thread that sleeps in the kernel cannot be woken alone: a wake reaches the waiters of a word. On Linux, a waiter-/// also sleeps on a bit of its interrupt, which is what its interrupt wakes, but only 31 bits go around. On macOS,-/// every waiter of the word wakes. A waiter that such a wake was not for goes back to sleep (see-/// was_woken_by_an_interrupt()).-pub struct WaitInterrupt {- is_requested: AtomicBool,- /// The word a thread of this agent sleeps on, for as long as it may be asleep in the kernel.- #[cfg(any(target_os = "macos", target_os = "linux"))]- sleeping_on: AtomicPtr<u32>,- /// Where in INTERRUPT_WAKES this interrupt wakes.- #[cfg(any(target_os = "macos", target_os = "linux"))]- wake_slot: usize,- /// The thread of this agent that waits in the waiter lists.- #[cfg(any(test, not(target_os = "linux")))]- waiter: std::sync::Mutex<Option<std::sync::Arc<waiter_list::Waiter>>>,-}--/// The bit of a wake that a notify is, which every waiter sleeps on.-#[cfg(target_os = "linux")]-const NOTIFY_BIT: u32 = 1;--/// How many interrupts can wake waiters without that reaching a waiter of another one.-#[cfg(target_os = "linux")]-const INTERRUPT_WAKE_SLOTS: usize = 31;-#[cfg(target_os = "macos")]-const INTERRUPT_WAKE_SLOTS: usize = 1;--/// The word that an interrupt is waking, by wake slot, which tells a waiter that a wake may not have been for it.-#[cfg(any(target_os = "macos", target_os = "linux"))]-static INTERRUPT_WAKES: [AtomicPtr<u32>; INTERRUPT_WAKE_SLOTS] =- [const { AtomicPtr::new(core::ptr::null_mut()) }; INTERRUPT_WAKE_SLOTS];--/// How long an interrupt waits for a thread to stop sleeping before it wakes the word again.-#[cfg(any(target_os = "macos", target_os = "linux"))]-const INTERRUPT_WAKE_INTERVAL: Duration = Duration::from_micros(50);--impl Default for WaitInterrupt {- fn default() -> Self {- Self::new()- }-}--impl WaitInterrupt {- pub fn new() -> Self {- #[cfg(any(target_os = "macos", target_os = "linux"))]- static NEXT_WAKE_SLOT: AtomicU32 = AtomicU32::new(0);- Self {- is_requested: AtomicBool::new(false),- #[cfg(any(target_os = "macos", target_os = "linux"))]- sleeping_on: AtomicPtr::new(core::ptr::null_mut()),- // NB: A word can have waiters in other processes. Starting at the process ID spreads those over the bits as- // well, which is all this can do for them: their waits are out of reach of INTERRUPT_WAKES.- #[cfg(any(target_os = "macos", target_os = "linux"))]- wake_slot: std::process::id().wrapping_add(NEXT_WAKE_SLOT.fetch_add(1, Ordering::Relaxed)) as usize- % INTERRUPT_WAKE_SLOTS,- #[cfg(any(test, not(target_os = "linux")))]- waiter: std::sync::Mutex::default(),- }- }-- /// Whether interrupt() was called.- pub fn is_requested(&self) -> bool {- self.is_requested.load(Ordering::SeqCst)- }-- /// Ends the wait of this agent's thread with AtomicWaitResult::Interrupted, and every later one at once. Blocks until- /// that thread is awake.- pub fn interrupt(&self) {- self.is_requested.store(true, Ordering::SeqCst);- #[cfg(any(test, not(target_os = "linux")))]- waiter_list::wake_interrupted(self);- #[cfg(any(target_os = "macos", target_os = "linux"))]- self.wake_sleeping_thread();- }-- // NB: The kernel compares the word before a thread sleeps, but it cannot look at is_requested. A thread that looked at- // it just before it got set is about to sleep, and a wake would go past it. So the wake has to go on until the- // thread is known to be awake, which also covers that thread going away: a word that stopped being one only- // gets a wake that finds nothing, or wakes a waiter that has to cope with this anyway.- #[cfg(any(target_os = "macos", target_os = "linux"))]- fn wake_sleeping_thread(&self) {- let interrupt_wake = &INTERRUPT_WAKES[self.wake_slot];- let mut did_wake = false;- loop {- let word = self.sleeping_on.load(Ordering::SeqCst);- if word.is_null() {- break;- }- interrupt_wake.store(word, Ordering::SeqCst);- did_wake = true;- self.wake_word(word);- std::thread::sleep(INTERRUPT_WAKE_INTERVAL);- }- if did_wake {- interrupt_wake.store(core::ptr::null_mut(), Ordering::SeqCst);- }- }-- /// Whether a thread that this interrupt lets sleep on `word` was woken by an interrupt, of this agent or another.- ///- /// NB: Telling those apart from a notify only works for an interrupt of this process. A waiter in another process- /// that an interrupt wakes takes it for a notify. And a notify that arrives right while an interrupt wakes- /// the word is taken for that interrupt's wake, if it is one for the same bit, so that it gets lost.- #[cfg(any(target_os = "macos", target_os = "linux"))]- fn was_woken_by_an_interrupt(&self, word: *mut u32) -> bool {- INTERRUPT_WAKES[self.wake_slot].load(Ordering::SeqCst) == word- }-- /// Lets interrupt() know that this agent's thread may sleep on `word` until the result goes away. The thread has to- /// look at is_requested() after this.- #[cfg(any(target_os = "macos", target_os = "linux"))]- fn will_sleep_on(&self, word: *mut u32) -> SleepingOn<'_> {- self.sleeping_on.store(word, Ordering::SeqCst);- SleepingOn(self)- }-- #[cfg(target_os = "linux")]- fn wake_bit(&self) -> u32 {- NOTIFY_BIT << (self.wake_slot + 1)- }-- #[cfg(target_os = "linux")]- fn wake_word(&self, word: *mut u32) {- wake_waiters_on_bit(word, i32::MAX, self.wake_bit());- }-- #[cfg(target_os = "macos")]- fn wake_word(&self, word: *mut u32) {- if let Some(functions) = os_sync::functions() {- // SAFETY: A wake of an address only compares it with those that waiters sleep on.- unsafe {- (functions.wake_by_address_all)(word.cast(), 4, os_sync::OS_SYNC_WAKE_BY_ADDRESS_SHARED);- }- }- }-}--#[cfg(any(target_os = "macos", target_os = "linux"))]-struct SleepingOn<'a>(&'a WaitInterrupt);--#[cfg(any(target_os = "macos", target_os = "linux"))]-impl Drop for SleepingOn<'_> {- fn drop(&mut self) {- self.0.sleeping_on.store(core::ptr::null_mut(), Ordering::SeqCst);- }-}--// Fallback where there's no wait/wake primitive of the operating system's: Each waiter waits on a condition variable of-// its own, in a list per address that atomic_notify() wakes waiters of in the order they began waiting. These lists only-// reach the waiters of this process. So, a waiter also polls for a change to the word, which observes the wakes of other-// processes that write the word before notifying (as the lock/futex protocol Emscripten uses does). A notify from-// another process that leaves the word unchanged wakes no waiter here.-#[cfg(any(test, not(target_os = "linux")))]-mod waiter_list {- use super::{AtomicWaitResult, WaitInterrupt, WaitWord, word_equals};- use core::sync::atomic::{AtomicBool, Ordering};- use core::time::Duration;- use std::collections::{HashMap, VecDeque};- use std::sync::{Arc, Condvar, Mutex, MutexGuard, OnceLock, PoisonError};- use std::time::Instant;-- const POLL_INTERVAL: Duration = Duration::from_micros(200);-- pub(super) struct Waiter {- woken: AtomicBool,- condition: Condvar,- }-- type Lists = HashMap<usize, VecDeque<Arc<Waiter>>>;-- fn lists() -> MutexGuard<'static, Lists> {- static LISTS: OnceLock<Mutex<Lists>> = OnceLock::new();- LISTS- .get_or_init(Mutex::default)- .lock()- .unwrap_or_else(|error| error.into_inner())- }-- fn remove(lists: &mut Lists, address: usize, waiter: &Arc<Waiter>) {- let Some(list) = lists.get_mut(&address) else {- return;- };- list.retain(|other| !Arc::ptr_eq(other, waiter));- if list.is_empty() {- lists.remove(&address);- }- }-- fn set_waiter_of_interrupt(interrupt: Option<&WaitInterrupt>, waiter: Option<Arc<Waiter>>) {- if let Some(interrupt) = interrupt {- *interrupt.waiter.lock().unwrap_or_else(PoisonError::into_inner) = waiter;- }- }-- /// Wakes the waiter of an interrupt that is already requested.- pub(super) fn wake_interrupted(interrupt: &WaitInterrupt) {- // NB: A waiter looks at the request and goes to sleep while the lists are locked, so this cannot go past it.- let _lists = lists();- if let Some(waiter) = &*interrupt.waiter.lock().unwrap_or_else(PoisonError::into_inner) {- waiter.condition.notify_one();- }- }-- pub(super) fn wait(- word: WaitWord<'_>,- expected: u64,- timeout: Option<Duration>,- interrupt: Option<&WaitInterrupt>,- ) -> AtomicWaitResult {- let address = word.address().addr();- let deadline = timeout.and_then(|timeout| Instant::now().checked_add(timeout));- // NB: The word is compared while the lists are locked, so a notify that follows a store to it finds this- // waiter in its list if the comparison did not see the store.- let mut lists = lists();- if interrupt.is_some_and(WaitInterrupt::is_requested) {- return AtomicWaitResult::Interrupted;- }- if !word_equals(word, expected) {- return AtomicWaitResult::NotEqual;- }- let waiter = Arc::new(Waiter {- woken: AtomicBool::new(false),- condition: Condvar::new(),- });- lists.entry(address).or_default().push_back(waiter.clone());- set_waiter_of_interrupt(interrupt, Some(waiter.clone()));- let result = loop {- let interval = match deadline {- Some(deadline) => {- let remaining = deadline.saturating_duration_since(Instant::now());- if remaining.is_zero() {- remove(&mut lists, address, &waiter);- break AtomicWaitResult::TimedOut;- }- remaining.min(POLL_INTERVAL)- }- None => POLL_INTERVAL,- };- lists = waiter- .condition- .wait_timeout(lists, interval)- .unwrap_or_else(|error| error.into_inner())- .0;- if interrupt.is_some_and(WaitInterrupt::is_requested) {- remove(&mut lists, address, &waiter);- break AtomicWaitResult::Interrupted;- }- // A notify removed the waiter from its list before setting this.- if waiter.woken.load(Ordering::Relaxed) {- break AtomicWaitResult::Woken;- }- if !word_equals(word, expected) {- remove(&mut lists, address, &waiter);- break AtomicWaitResult::Woken;- }- };- set_waiter_of_interrupt(interrupt, None);- result- }-- pub(super) fn notify(address: *mut u32, max_count: usize) -> usize {- let mut lists = lists();- let address = address.addr();- let Some(list) = lists.get_mut(&address) else {- return 0;- };- let count = max_count.min(list.len());- for waiter in list.drain(..count) {- waiter.woken.store(true, Ordering::Relaxed);- waiter.condition.notify_one();- }- if list.is_empty() {- lists.remove(&address);- }- count- }-}--#[cfg(target_os = "macos")]-mod os_sync {- use core::ffi::{c_int, c_void};- use std::sync::OnceLock;-- pub const OS_SYNC_WAIT_ON_ADDRESS_SHARED: u32 = 0x1;- pub const OS_SYNC_WAKE_BY_ADDRESS_SHARED: u32 = 0x1;- pub const OS_CLOCK_MACH_ABSOLUTE_TIME: u32 = 32;-- pub type WaitOnAddress = unsafe extern "C" fn(*mut c_void, u64, usize, u32) -> c_int;- pub type WaitOnAddressWithTimeout = unsafe extern "C" fn(*mut c_void, u64, usize, u32, u32, u64) -> c_int;- pub type WakeByAddressAny = unsafe extern "C" fn(*mut c_void, usize, u32) -> c_int;-- /// The os_sync functions, which exist from macOS 14.4 on, looked up at runtime as __builtin_available() checks for- /// them.- pub struct Functions {- pub wait_on_address: WaitOnAddress,- pub wait_on_address_with_timeout: WaitOnAddressWithTimeout,- pub wake_by_address_any: WakeByAddressAny,- pub wake_by_address_all: WakeByAddressAny,- }-- pub fn functions() -> Option<&'static Functions> {- static FUNCTIONS: OnceLock<Option<Functions>> = OnceLock::new();- FUNCTIONS- .get_or_init(|| {- let lookup = |name: &core::ffi::CStr| {- // SAFETY: Looks up a symbol by its NUL-terminated name.- let symbol = unsafe { libc::dlsym(libc::RTLD_DEFAULT, name.as_ptr()) };- (!symbol.is_null()).then_some(symbol)- };- let wait_on_address = lookup(c"os_sync_wait_on_address")?;- let wait_on_address_with_timeout = lookup(c"os_sync_wait_on_address_with_timeout")?;- let wake_by_address_any = lookup(c"os_sync_wake_by_address_any")?;- let wake_by_address_all = lookup(c"os_sync_wake_by_address_all")?;- // SAFETY: The symbols are the libSystem functions with these signatures.- unsafe {- Some(Functions {- wait_on_address: core::mem::transmute::<*mut c_void, WaitOnAddress>(wait_on_address),- wait_on_address_with_timeout: core::mem::transmute::<*mut c_void, WaitOnAddressWithTimeout>(- wait_on_address_with_timeout,- ),- wake_by_address_any: core::mem::transmute::<*mut c_void, WakeByAddressAny>(wake_by_address_any),- wake_by_address_all: core::mem::transmute::<*mut c_void, WakeByAddressAny>(wake_by_address_all),- })- }- })- .as_ref()- }-}--#[cfg(target_os = "macos")]-fn errno() -> i32 {- std::io::Error::last_os_error().raw_os_error().unwrap_or(0)-}--#[cfg(target_os = "macos")]-pub fn atomic_wait(- word: WaitWord<'_>,- expected: u64,- timeout: Option<Duration>,- interrupt: Option<&WaitInterrupt>,-) -> AtomicWaitResult {- if interrupt.is_some_and(WaitInterrupt::is_requested) {- return AtomicWaitResult::Interrupted;- }-- // Compare the value in userspace first. os_sync_wait_on_address reports a value mismatch as a *successful* return- // (it has no EAGAIN). So, without this, the "not-equal" result would be unreachable; it also faults the shared page- // in — avoiding a transient first-touch EFAULT below. A store landing between this read and the kernel's own- // comparison is reported as a wake, rather than "not-equal" — a nanoseconds-wide window inherent to the os_sync API- // (Linux's kernel futex and the waiter lists don't have it).- if !word_equals(word, expected) {- return AtomicWaitResult::NotEqual;- }-- // Anchor the timeout to a fixed deadline — so that nothing restarts it. Both an EINTR retry and the fallback to- // polling below continue with only the time that's left.- let deadline = timeout.and_then(|timeout| Instant::now().checked_add(timeout));-- if let Some(functions) = os_sync::functions() {- // os_sync_wait_on_address makes the element size part of the wait/wake key. Wait on the low 32-bit half (size- // 4) for both 4-byte and 8-byte waits: the full-width userspace pre-compare above already rejected any full-- // value mismatch, so the low half only has to close the lost-wake race at entry — and normalizing the size lets- // 4-byte and 8-byte waiters at one address share kernel state (a single spec WaiterList) and cross-wake.- let _sleeping_on = interrupt.map(|interrupt| interrupt.will_sleep_on(word.address()));- loop {- if interrupt.is_some_and(WaitInterrupt::is_requested) {- return AtomicWaitResult::Interrupted;- }- let result = if let Some(deadline) = deadline {- let remaining = deadline.saturating_duration_since(Instant::now());- if remaining.is_zero() {- return AtomicWaitResult::TimedOut;- }- // SAFETY: The address is the aligned word of a shared typed array element.- unsafe {- (functions.wait_on_address_with_timeout)(- word.address().cast(),- u64::from(expected as u32),- 4,- os_sync::OS_SYNC_WAIT_ON_ADDRESS_SHARED,- os_sync::OS_CLOCK_MACH_ABSOLUTE_TIME,- u64::try_from(remaining.as_nanos()).unwrap_or(u64::MAX),- )- }- } else {- // SAFETY: As above.- unsafe {- (functions.wait_on_address)(- word.address().cast(),- u64::from(expected as u32),- 4,- os_sync::OS_SYNC_WAIT_ON_ADDRESS_SHARED,- )- }- };-- if result >= 0 {- if !interrupt.is_some_and(|interrupt| interrupt.was_woken_by_an_interrupt(word.address())) {- return AtomicWaitResult::Woken;- }- // NB: This waiter may go back to sleep, and os_sync would report a value mismatch as a wake.- if !word_equals(word, expected) && !interrupt.is_some_and(WaitInterrupt::is_requested) {- return AtomicWaitResult::NotEqual;- }- continue;- }- let error = errno();- if error == libc::EINTR {- // os_sync reports a value mismatch as a successful wake — so retrying with the original expected would- // turn a store that landed while we slept into a spurious "ok". Re-read first: If the word changed,- // report "not-equal" (as if the critical section were entered late) — matching the Linux EAGAIN path.- if !word_equals(word, expected) {- return AtomicWaitResult::NotEqual;- }- continue;- }- if error == libc::ETIMEDOUT {- return AtomicWaitResult::TimedOut;- }- if error == libc::EAGAIN {- return AtomicWaitResult::NotEqual;- }- // os_sync couldn't key this memory (rare once faulted in above); fall back to the waiter lists.- break;- }- }- let remaining = deadline.map(|deadline| deadline.saturating_duration_since(Instant::now()));- waiter_list::wait(word, expected, remaining.or(timeout), interrupt)-}--#[cfg(target_os = "macos")]-pub fn atomic_notify(word: &AtomicU32, max_count: usize) -> usize {- // Waiters key on the low 32-bit half — so, wake with size 4 regardless of the notifying view's element size. That- // lets a 4-byte notify wake an 8-byte waiter (and vice versa) at the same address — which the spec's single per-- // address WaiterList requires.- // NB: Waiters that os_sync could not serve wait in the fallback's lists.- let mut woken = waiter_list::notify(word.as_ptr(), max_count);- let Some(functions) = os_sync::functions() else {- return woken;- };- // os_sync wakes a single waiter at a time. So, wake up to max_count of them — stopping once there are none left.- // ENOENT is that stop: it means the wait set is empty.- while woken < max_count {- // SAFETY: The address is the aligned word of a shared typed array element.- let result = unsafe {- (functions.wake_by_address_any)(word.as_ptr().cast(), 4, os_sync::OS_SYNC_WAKE_BY_ADDRESS_SHARED)- };- if result == 0 {- woken += 1;- continue;- }- let error = errno();- if error != libc::ENOENT {- eprintln!("Core::atomic_notify: os_sync_wake_by_address_any failed with errno {error}");- }- break;- }- woken-}--// FUTEX_WAIT_BITSET takes a deadline, on the monotonic clock.-#[cfg(target_os = "linux")]-fn monotonic_deadline(timeout: Duration) -> libc::timespec {- let mut now = libc::timespec { tv_sec: 0, tv_nsec: 0 };- // SAFETY: The clock always exists, and `now` is a timespec.- unsafe { libc::clock_gettime(libc::CLOCK_MONOTONIC, &raw mut now) };- let nanoseconds = now.tv_nsec + libc::c_long::from(timeout.subsec_nanos() as i32);- let seconds = libc::time_t::try_from(timeout.as_secs()).unwrap_or(libc::time_t::MAX);- libc::timespec {- tv_sec: now- .tv_sec- .saturating_add(seconds)- .saturating_add(libc::time_t::from(nanoseconds >= 1_000_000_000)),- tv_nsec: nanoseconds % 1_000_000_000,- }-}--#[cfg(target_os = "linux")]-pub fn atomic_wait(- word: WaitWord<'_>,- expected: u64,- timeout: Option<Duration>,- interrupt: Option<&WaitInterrupt>,-) -> AtomicWaitResult {- if interrupt.is_some_and(WaitInterrupt::is_requested) {- return AtomicWaitResult::Interrupted;- }-- // Compare the value in userspace first — so a zero or already-elapsed timeout still yields "not-equal" (which the- // spec orders before "timed-out"), and so 8-byte waits share one compare.- if !word_equals(word, expected) {- return AtomicWaitResult::NotEqual;- }-- // A fixed deadline — so that neither EINTR nor a wake that wasn't for this waiter restarts the timeout.- let deadline = timeout.map(monotonic_deadline);- let deadline_pointer = deadline.as_ref().map_or(core::ptr::null(), core::ptr::from_ref);- let bits = NOTIFY_BIT | interrupt.map_or(0, WaitInterrupt::wake_bit);- let _sleeping_on = interrupt.map(|interrupt| interrupt.will_sleep_on(word.address()));-- loop {- if interrupt.is_some_and(WaitInterrupt::is_requested) {- return AtomicWaitResult::Interrupted;- }-- // A shared (non-private) futex keys on the underlying page — so it coordinates across processes.- // SAFETY: The address is the aligned word of a shared typed array element.- let result = unsafe {- libc::syscall(- libc::SYS_futex,- word.address(),- libc::FUTEX_WAIT_BITSET,- expected as u32,- deadline_pointer,- core::ptr::null::<u32>(),- bits,- )- };- if result == 0 {- if interrupt.is_some_and(|interrupt| interrupt.was_woken_by_an_interrupt(word.address())) {- continue;- }- return AtomicWaitResult::Woken;- }- let error = std::io::Error::last_os_error().raw_os_error().unwrap_or(0);- if error == libc::EINTR {- continue;- }- if error == libc::ETIMEDOUT {- return AtomicWaitResult::TimedOut;- }- // EAGAIN means the value at the address no longer equals expected.- return AtomicWaitResult::NotEqual;- }-}--// Wakes up to `count` waiters of the word with one of `bits` among those they sleep on, and returns how many it woke.-#[cfg(target_os = "linux")]-fn wake_waiters_on_bit(word: *mut u32, count: i32, bits: u32) -> usize {- // SAFETY: Only the address of the word goes to the kernel, which gets nothing out of one that is no longer mapped.- let result = unsafe {- libc::syscall(- libc::SYS_futex,- word,- libc::FUTEX_WAKE_BITSET,- count,- core::ptr::null::<libc::timespec>(),- core::ptr::null::<u32>(),- bits,- )- };- usize::try_from(result).unwrap_or(0)-}--#[cfg(target_os = "linux")]-pub fn atomic_notify(word: &AtomicU32, max_count: usize) -> usize {- // FUTEX_WAKE_BITSET wakes a waiter even when the requested count is zero.- if max_count == 0 {- return 0;- }-- // This wakes waiters keyed on the low 32-bit half at the word's address. That covers both 4-byte and 8-byte waiters- // (8-byte waits key on the low half too), and returns the exact number of waiters woken.- wake_waiters_on_bit(word.as_ptr(), i32::try_from(max_count).unwrap_or(i32::MAX), NOTIFY_BIT)-}--// No native wait/wake primitive is wired up on this platform.-#[cfg(not(any(target_os = "macos", target_os = "linux")))]-pub fn atomic_wait(- word: WaitWord<'_>,- expected: u64,- timeout: Option<Duration>,- interrupt: Option<&WaitInterrupt>,-) -> AtomicWaitResult {- waiter_list::wait(word, expected, timeout, interrupt)-}--#[cfg(not(any(target_os = "macos", target_os = "linux")))]-pub fn atomic_notify(word: &AtomicU32, max_count: usize) -> usize {- waiter_list::notify(word.as_ptr(), max_count)-}--#[cfg(test)]-mod tests {- use super::*;- use std::sync::atomic::AtomicUsize;-- /// Long enough for a thread that was just started to get to sleep.- const TIME_TO_SLEEP: Duration = Duration::from_millis(30);-- type Wait = fn(&AtomicU32, u64, Option<Duration>, Option<&WaitInterrupt>) -> AtomicWaitResult;- type Notify = fn(&AtomicU32, usize) -> usize;-- fn wait_in_kernel(- word: &AtomicU32,- expected: u64,- timeout: Option<Duration>,- interrupt: Option<&WaitInterrupt>,- ) -> AtomicWaitResult {- atomic_wait(WaitWord::Word32(word), expected, timeout, interrupt)- }-- fn wait_in_list(- word: &AtomicU32,- expected: u64,- timeout: Option<Duration>,- interrupt: Option<&WaitInterrupt>,- ) -> AtomicWaitResult {- waiter_list::wait(WaitWord::Word32(word), expected, timeout, interrupt)- }-- fn notify_in_list(word: &AtomicU32, max_count: usize) -> usize {- waiter_list::notify(word.as_ptr(), max_count)- }-- fn for_each_primitive(test: impl Fn(Wait, Notify)) {- test(wait_in_kernel, atomic_notify);- test(wait_in_list, notify_in_list);- }-- #[test]- fn notifies_wake_waiters_of_a_word_that_did_not_change() {- for_each_primitive(|wait, notify| {- let word = AtomicU32::new(0);- std::thread::scope(|scope| {- let waiter = scope.spawn(|| wait(&word, 0, None, None));- // The waiter is among the waiters once a notify wakes it.- while notify(&word, 1) == 0 {- std::thread::yield_now();- }- assert_eq!(waiter.join().unwrap(), AtomicWaitResult::Woken);- });- });- }-- #[cfg(target_os = "linux")]- #[test]- fn a_change_of_the_word_wakes_nobody_in_the_kernel() {- let word = AtomicU32::new(0);- std::thread::scope(|scope| {- let waiter = scope.spawn(|| wait_in_kernel(&word, 0, Some(TIME_TO_SLEEP * 4), None));- std::thread::sleep(TIME_TO_SLEEP);- word.store(1, Ordering::SeqCst);- assert_eq!(waiter.join().unwrap(), AtomicWaitResult::TimedOut);- });- }-- #[test]- fn waits_time_out() {- for_each_primitive(|wait, notify| {- let word = AtomicU32::new(0);- assert_eq!(- wait(&word, 0, Some(Duration::from_millis(1)), None),- AtomicWaitResult::TimedOut- );- assert_eq!(wait(&word, 0, Some(Duration::ZERO), None), AtomicWaitResult::TimedOut);- assert_eq!(wait(&word, 1, Some(Duration::ZERO), None), AtomicWaitResult::NotEqual);- assert_eq!(notify(&word, 1), 0);- });- }-- #[test]- fn notifies_wake_in_the_order_of_the_waits_and_count_what_they_wake() {- for_each_primitive(|wait, notify| {- const WAITER_COUNT: usize = 5;- let word = AtomicU32::new(0);- let woken_count = AtomicUsize::new(0);- let positions: [AtomicUsize; WAITER_COUNT] = Default::default();- std::thread::scope(|scope| {- for position in &positions {- let (word, woken_count) = (&word, &woken_count);- scope.spawn(move || {- assert_eq!(wait(word, 0, None, None), AtomicWaitResult::Woken);- position.store(woken_count.fetch_add(1, Ordering::SeqCst) + 1, Ordering::SeqCst);- });- std::thread::sleep(TIME_TO_SLEEP);- }- for (index, position) in positions.iter().take(2).enumerate() {- assert_eq!(notify(&word, 1), 1);- while position.load(Ordering::SeqCst) == 0 {- std::thread::yield_now();- }- assert_eq!(position.load(Ordering::SeqCst), index + 1);- }- assert_eq!(notify(&word, 0), 0);- assert_eq!(notify(&word, usize::MAX), WAITER_COUNT - 2);- });- assert_eq!(notify(&word, usize::MAX), 0);- });- }-- #[test]- fn interrupts_end_waits_with_and_without_a_timeout() {- for_each_primitive(|wait, notify| {- for timeout in [None, Some(Duration::from_secs(600))] {- let word = AtomicU32::new(0);- let interrupt = WaitInterrupt::new();- std::thread::scope(|scope| {- let waiter = scope.spawn(|| wait(&word, 0, timeout, Some(&interrupt)));- std::thread::sleep(TIME_TO_SLEEP);- interrupt.interrupt();- assert_eq!(waiter.join().unwrap(), AtomicWaitResult::Interrupted);- });- assert_eq!(notify(&word, 1), 0);- }- });- }-- #[test]- fn interrupted_waits_end_at_once() {- for_each_primitive(|wait, _| {- let word = AtomicU32::new(0);- let interrupt = WaitInterrupt::new();- interrupt.interrupt();- assert_eq!(wait(&word, 0, None, Some(&interrupt)), AtomicWaitResult::Interrupted);- assert_eq!(wait(&word, 1, None, Some(&interrupt)), AtomicWaitResult::Interrupted);- });- }-- // An interrupt can come at any point of a wait, which is what a thread on its way to sleep is at risk from.- #[test]- fn interrupts_reach_waits_that_are_just_starting() {- for_each_primitive(|wait, _| {- for round in 0..2000 {- let word = AtomicU32::new(0);- let interrupt = WaitInterrupt::new();- std::thread::scope(|scope| {- let waiter = scope.spawn(|| wait(&word, 0, None, Some(&interrupt)));- for _ in 0..(round % 200) * 20 {- core::hint::spin_loop();- }- interrupt.interrupt();- assert_eq!(waiter.join().unwrap(), AtomicWaitResult::Interrupted);- });- }- });- }-- #[test]- fn interrupts_leave_the_other_waiters_of_a_word_alone() {- for_each_primitive(|wait, notify| {- let word = AtomicU32::new(0);- let interrupted = WaitInterrupt::new();- let other = WaitInterrupt::new();- std::thread::scope(|scope| {- let first = scope.spawn(|| wait(&word, 0, None, Some(&other)));- std::thread::sleep(TIME_TO_SLEEP);- let second = scope.spawn(|| wait(&word, 0, None, Some(&interrupted)));- std::thread::sleep(TIME_TO_SLEEP);- interrupted.interrupt();- assert_eq!(second.join().unwrap(), AtomicWaitResult::Interrupted);- assert!(!first.is_finished());- assert_eq!(notify(&word, 2), 1);- assert_eq!(first.join().unwrap(), AtomicWaitResult::Woken);- });- });- }-- #[cfg(target_os = "linux")]- #[test]- fn waiters_that_share_a_wake_bit_go_back_to_sleep_without_reporting_anything() {- let word = AtomicU32::new(0);- let interrupted = WaitInterrupt::new();- let mut other = WaitInterrupt::new();- other.wake_slot = interrupted.wake_slot;- std::thread::scope(|scope| {- let (victim, timed) = (- scope.spawn(|| wait_in_kernel(&word, 0, None, Some(&other))),- scope.spawn(|| wait_in_kernel(&word, 0, Some(TIME_TO_SLEEP * 6), Some(&other))),- );- std::thread::sleep(TIME_TO_SLEEP);- let target = scope.spawn(|| wait_in_kernel(&word, 0, None, Some(&interrupted)));- std::thread::sleep(TIME_TO_SLEEP);- interrupted.interrupt();- assert_eq!(target.join().unwrap(), AtomicWaitResult::Interrupted);- std::thread::sleep(TIME_TO_SLEEP);- assert!(!victim.is_finished());- assert_eq!(timed.join().unwrap(), AtomicWaitResult::TimedOut);- assert_eq!(atomic_notify(&word, 1), 1);- assert_eq!(victim.join().unwrap(), AtomicWaitResult::Woken);- });- }-- #[cfg(target_os = "linux")]- #[test]- fn zero_count_does_not_wake_waiters() {- let word = AtomicU64::new(0);- // SAFETY: The storage is aligned for AtomicU32, and neither view writes to it. Both wait widths use this- // address as their futex key.- let notify_word = unsafe { &*word.as_ptr().cast::<AtomicU32>() };- for wait_word in [WaitWord::Word32(notify_word), WaitWord::Word64(&word)] {- std::thread::scope(|scope| {- let waiter = scope.spawn(|| atomic_wait(wait_word, 0, Some(Duration::from_millis(100)), None));- while !waiter.is_finished() {- assert_eq!(atomic_notify(notify_word, 0), 0);- std::thread::yield_now();- }- assert_eq!(waiter.join().unwrap(), AtomicWaitResult::TimedOut);- });- }- }-- // SharedArrayBuffers cross processes, where a waiter sleeps on a word that the notifier has at another address.- #[cfg(target_os = "linux")]- #[test]- fn notifies_and_interrupts_cross_processes() {- // SAFETY: A new mapping, which the words below live in and which is never unmapped.- let shared = unsafe {- libc::mmap(- core::ptr::null_mut(),- 4096,- libc::PROT_READ | libc::PROT_WRITE,- libc::MAP_SHARED | libc::MAP_ANONYMOUS,- -1,- 0,- )- };- assert_ne!(shared, libc::MAP_FAILED);- // SAFETY: The mapping is zeroed, aligned and large enough.- let (word, other_word) = unsafe { (&*shared.cast::<AtomicU32>(), &*shared.cast::<AtomicU32>().add(1)) };-- // SAFETY: The child only sleeps and exits, without anything that another thread could hold a lock of.- let child = unsafe { libc::fork() };- assert!(child >= 0);- if child == 0 {- let result = atomic_wait(WaitWord::Word32(word), 0, Some(Duration::from_secs(20)), None);- // SAFETY: Ends the child without running anything of the test harness.- unsafe { libc::_exit(i32::from(result != AtomicWaitResult::Woken)) };- }-- let start = std::time::Instant::now();- while atomic_notify(word, 1) == 0 {- assert!(- start.elapsed() < Duration::from_secs(10),- "the child never started waiting"- );- std::thread::sleep(Duration::from_millis(1));- }- let mut status = 0;- // SAFETY: Waits for the child of this thread.- assert_eq!(unsafe { libc::waitpid(child, &raw mut status, 0) }, child);- assert!(libc::WIFEXITED(status) && libc::WEXITSTATUS(status) == 0);-- // A waiter that shares a mapping with another process still has its interrupt.- let interrupt = WaitInterrupt::new();- std::thread::scope(|scope| {- let waiter = scope.spawn(|| atomic_wait(WaitWord::Word32(other_word), 0, None, Some(&interrupt)));- std::thread::sleep(TIME_TO_SLEEP);- interrupt.interrupt();- assert_eq!(waiter.join().unwrap(), AtomicWaitResult::Interrupted);- });- }-}diff --git a/AK/Rust/src/lib.rs b/AK/Rust/src/lib.rsindex f6bc4760c4d..0fb4061bd8d 100644--- a/AK/Rust/src/lib.rs+++ b/AK/Rust/src/lib.rs@@ -6,12 +6,12 @@//! Rust views of shared AK data structures.-pub mod futex;mod generic_lexer;pub mod math;pub mod perf_map;mod scope_guard;mod slice;+pub mod waiter_list;pub use generic_lexer::GenericLexer;pub use scope_guard::ScopeGuard;diff --git a/AK/Rust/src/waiter_list.rs b/AK/Rust/src/waiter_list.rsnew file mode 100644index 00000000000..7827830a224--- /dev/null+++ b/AK/Rust/src/waiter_list.rs@@ -0,0 +1,454 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! The WaiterLists of a process, which Atomics.wait, Atomics.notify and their WebAssembly counterparts use: one list of+//! all that wait, in the order the agents began to wait, under one lock, with a condition variable per agent. The+//! WaiterList of an address is what has that address in this list.+//!+//! A word has one address in a process, as every agent shares one mapping of it, and it never has waiters in another+//! process, as shared memory stays in its agent cluster, and an agent cluster stays in its process. Having a condition+//! variable per agent means that a notify wakes the agents it took off the list, and that an interrupt wakes its agent,+//! and nobody else.+//!+//! An agent waits on one word at a time, so this list is as long as the number of agents that are asleep, and a process+//! has few of those. Going through it takes less time than a wait that allocates a list of its own, and frees it on+//! another thread.++use core::sync::atomic::{AtomicBool, AtomicU32, AtomicU64, Ordering};+use core::time::Duration;+use std::collections::VecDeque;+use std::sync::{Arc, Condvar, Mutex, MutexGuard, PoisonError};+use std::time::Instant;++/// Core::AtomicWaitResult.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum AtomicWaitResult {+ Woken,+ NotEqual,+ TimedOut,+ Interrupted,+}++/// The word of a shared typed array element that Atomics.wait waits on, which is 4 or 8 bytes wide.+#[derive(Clone, Copy)]+pub enum WaitWord<'a> {+ Word32(&'a AtomicU32),+ Word64(&'a AtomicU64),+}++impl WaitWord<'_> {+ /// The address of the word, which is what the WaiterList of a location is found by: a 4-byte and an 8-byte view of+ /// the same location share it.+ fn address(self) -> usize {+ match self {+ WaitWord::Word32(word) => word.as_ptr().addr(),+ WaitWord::Word64(word) => word.as_ptr().addr(),+ }+ }++ /// Whether the word equals `expected`, by a sequentially-consistent read, which matches the memory model's read for+ /// the wait comparison.+ fn equals(self, expected: u64) -> bool {+ match self {+ WaitWord::Word32(word) => word.load(Ordering::SeqCst) == expected as u32,+ WaitWord::Word64(word) => word.load(Ordering::SeqCst) == expected,+ }+ }+}++/// The node of one agent in the WaiterLists. An agent has one thread, so it is in one list at most.+pub struct AgentWaiter {+ condition: Condvar,+ is_interrupted: AtomicBool,+ /// Set by the notify that took the agent off its list.+ was_notified: AtomicBool,+}++impl AgentWaiter {+ pub fn new() -> Arc<Self> {+ Arc::new(Self {+ condition: Condvar::new(),+ is_interrupted: AtomicBool::new(false),+ was_notified: AtomicBool::new(false),+ })+ }++ /// Whether interrupt() was called.+ pub fn is_interrupted(&self) -> bool {+ self.is_interrupted.load(Ordering::SeqCst)+ }++ /// Whether the agent is on the list of a word, waiting for a notify. Any thread may call this.+ pub fn is_waiting(self: &Arc<Self>) -> bool {+ lists().iter().any(|waiting| Arc::ptr_eq(&waiting.waiter, self))+ }++ /// Ends the wait of this agent with AtomicWaitResult::Interrupted, and every later one at once. Any thread may call+ /// this. The agent loses its place in its list, which does not matter, as it never comes back.+ pub fn interrupt(&self) {+ self.is_interrupted.store(true, Ordering::SeqCst);+ // NB: A waiter looks at the flag and goes to sleep with the lock held, so this cannot go past it.+ let _lists = lists();+ self.condition.notify_one();+ }+}++struct Waiting {+ address: usize,+ waiter: Arc<AgentWaiter>,+}++type Lists = VecDeque<Waiting>;++fn lists() -> MutexGuard<'static, Lists> {+ static LISTS: Mutex<Lists> = Mutex::new(VecDeque::new());+ LISTS.lock().unwrap_or_else(PoisonError::into_inner)+}++fn remove(lists: &mut Lists, waiter: &Arc<AgentWaiter>) {+ lists.retain(|waiting| !Arc::ptr_eq(&waiting.waiter, waiter));+}++/// Puts `waiter` on the list of the word unless it holds something else than `expected`, and sleeps until a notify takes+/// it off, its interrupt comes, or `timeout` passes.+pub fn atomic_wait(+ word: WaitWord<'_>,+ expected: u64,+ timeout: Option<Duration>,+ waiter: &Arc<AgentWaiter>,+) -> AtomicWaitResult {+ let address = word.address();+ // NB: A deadline too far away to express is no deadline.+ let deadline = timeout.and_then(|timeout| Instant::now().checked_add(timeout));++ // NB: The word is compared with the lock held, so a notify that follows a store to it finds this waiter on the list+ // if the comparison did not see the store.+ let mut lists = lists();+ if waiter.is_interrupted() {+ return AtomicWaitResult::Interrupted;+ }+ if !word.equals(expected) {+ return AtomicWaitResult::NotEqual;+ }+ waiter.was_notified.store(false, Ordering::Relaxed);+ lists.push_back(Waiting {+ address,+ waiter: Arc::clone(waiter),+ });++ // NB: The condition variable can wake for no reason, so only what the wake left behind counts. A notify that came+ // along with the timeout already counted this waiter, so it wins.+ loop {+ if waiter.is_interrupted() {+ remove(&mut lists, waiter);+ return AtomicWaitResult::Interrupted;+ }+ if waiter.was_notified.load(Ordering::Relaxed) {+ return AtomicWaitResult::Woken;+ }+ let Some(deadline) = deadline else {+ lists = waiter.condition.wait(lists).unwrap_or_else(PoisonError::into_inner);+ continue;+ };+ let remaining = deadline.saturating_duration_since(Instant::now());+ if remaining.is_zero() {+ remove(&mut lists, waiter);+ return AtomicWaitResult::TimedOut;+ }+ lists = waiter+ .condition+ .wait_timeout(lists, remaining)+ .unwrap_or_else(PoisonError::into_inner)+ .0;+ }+}++/// Takes the first `max_count` agents off the list of the word, wakes them, and returns how many there were.+pub fn atomic_notify(word: &AtomicU32, max_count: usize) -> usize {+ let address = word.as_ptr().addr();+ let mut count = 0;+ lists().retain(|waiting| {+ if waiting.address != address {+ return true;+ }+ // NB: An interrupted agent is on its way out, and only has to get the lock to leave. Counting it would take the+ // wake from an agent that is really waiting.+ if waiting.waiter.is_interrupted() {+ return false;+ }+ if count == max_count {+ return true;+ }+ count += 1;+ waiting.waiter.was_notified.store(true, Ordering::Relaxed);+ waiting.waiter.condition.notify_one();+ false+ });+ count+}++#[cfg(test)]+mod tests {+ use super::*;+ use std::sync::atomic::AtomicUsize;++ /// Long enough for a thread that was just started to get to sleep.+ const TIME_TO_SLEEP: Duration = Duration::from_millis(30);++ fn wait(word: &AtomicU32, expected: u64, timeout: Option<Duration>, waiter: &Arc<AgentWaiter>) -> AtomicWaitResult {+ atomic_wait(WaitWord::Word32(word), expected, timeout, waiter)+ }++ fn waiters_of(word: &AtomicU32) -> usize {+ let address = word.as_ptr().addr();+ lists().iter().filter(|waiting| waiting.address == address).count()+ }++ fn wait_for_waiters(word: &AtomicU32, count: usize) {+ while waiters_of(word) != count {+ std::thread::yield_now();+ }+ }++ #[test]+ fn notifies_wake_waiters_of_a_word_that_did_not_change() {+ let word = AtomicU32::new(0);+ std::thread::scope(|scope| {+ let waiter = scope.spawn(|| wait(&word, 0, None, &AgentWaiter::new()));+ wait_for_waiters(&word, 1);+ assert_eq!(atomic_notify(&word, 1), 1);+ assert_eq!(waiter.join().unwrap(), AtomicWaitResult::Woken);+ });+ }++ #[test]+ fn a_word_that_differs_is_not_waited_on() {+ let word = AtomicU32::new(1);+ assert_eq!(+ wait(&word, 0, Some(Duration::ZERO), &AgentWaiter::new()),+ AtomicWaitResult::NotEqual+ );+ // NB: Only the low half of a 4-byte word's expected value counts.+ assert_eq!(+ wait(&word, 0x1_0000_0001, Some(Duration::ZERO), &AgentWaiter::new()),+ AtomicWaitResult::TimedOut+ );+ let wide_word = AtomicU64::new(0x1_0000_0000);+ assert_eq!(+ atomic_wait(WaitWord::Word64(&wide_word), 0, None, &AgentWaiter::new()),+ AtomicWaitResult::NotEqual+ );+ }++ #[test]+ fn a_change_of_the_word_wakes_nobody() {+ let word = AtomicU32::new(0);+ std::thread::scope(|scope| {+ let waiter = scope.spawn(|| wait(&word, 0, Some(Duration::from_millis(100)), &AgentWaiter::new()));+ wait_for_waiters(&word, 1);+ word.store(1, Ordering::SeqCst);+ assert_eq!(waiter.join().unwrap(), AtomicWaitResult::TimedOut);+ });+ }++ #[test]+ fn waits_time_out_and_leave_the_list() {+ let word = AtomicU32::new(0);+ let start = Instant::now();+ assert_eq!(+ wait(&word, 0, Some(Duration::from_millis(20)), &AgentWaiter::new()),+ AtomicWaitResult::TimedOut+ );+ assert!(start.elapsed() >= Duration::from_millis(20));+ assert_eq!(atomic_notify(&word, 1), 0);+ }++ #[test]+ fn notifies_wake_in_the_order_of_the_waits_and_count_what_they_wake() {+ let word = AtomicU32::new(0);+ let wake_order = Mutex::new(Vec::new());+ std::thread::scope(|scope| {+ for index in 0..4 {+ let word = &word;+ let wake_order = &wake_order;+ scope.spawn(move || {+ let result = wait(word, 0, None, &AgentWaiter::new());+ assert_eq!(result, AtomicWaitResult::Woken);+ wake_order.lock().unwrap().push(index);+ });+ wait_for_waiters(&word, index + 1);+ }+ for index in 0..4 {+ assert_eq!(atomic_notify(&word, 1), 1);+ while wake_order.lock().unwrap().len() != index + 1 {+ std::thread::yield_now();+ }+ }+ assert_eq!(atomic_notify(&word, 1), 0);+ });+ assert_eq!(*wake_order.lock().unwrap(), vec![0, 1, 2, 3]);+ }++ #[test]+ fn notifies_wake_no_more_than_they_are_asked_to() {+ let word = AtomicU32::new(0);+ std::thread::scope(|scope| {+ for _ in 0..3 {+ scope.spawn(|| wait(&word, 0, None, &AgentWaiter::new()));+ }+ wait_for_waiters(&word, 3);+ assert_eq!(atomic_notify(&word, 0), 0);+ assert_eq!(waiters_of(&word), 3);+ assert_eq!(atomic_notify(&word, 2), 2);+ assert_eq!(waiters_of(&word), 1);+ assert_eq!(atomic_notify(&word, usize::MAX), 1);+ });+ }++ #[test]+ fn views_of_both_widths_share_a_list() {+ let word = AtomicU64::new(0);+ // SAFETY: The low half of the word is a valid 4-byte word, as this is little-endian.+ let low_half = unsafe { AtomicU32::from_ptr(word.as_ptr().cast()) };+ std::thread::scope(|scope| {+ let waiter = scope.spawn(|| atomic_wait(WaitWord::Word64(&word), 0, None, &AgentWaiter::new()));+ wait_for_waiters(low_half, 1);+ assert_eq!(atomic_notify(low_half, 1), 1);+ assert_eq!(waiter.join().unwrap(), AtomicWaitResult::Woken);+ });+ }++ #[test]+ fn interrupts_end_waits_with_and_without_a_timeout() {+ for timeout in [None, Some(Duration::from_secs(600))] {+ let word = AtomicU32::new(0);+ let agent = AgentWaiter::new();+ std::thread::scope(|scope| {+ let waiter = scope.spawn(|| wait(&word, 0, timeout, &agent));+ wait_for_waiters(&word, 1);+ agent.interrupt();+ assert_eq!(waiter.join().unwrap(), AtomicWaitResult::Interrupted);+ });+ assert_eq!(waiters_of(&word), 0);+ }+ }++ #[test]+ fn notifies_pass_over_interrupted_agents_that_did_not_leave_yet() {+ let word = AtomicU32::new(0);+ let interrupted_agent = AgentWaiter::new();+ let waiting_agent = AgentWaiter::new();+ // NB: The lock stops the interrupted agent from leaving, as if its thread did not run yet.+ let mut held_lists = lists();+ let address = word.as_ptr().addr();+ for waiter in [&interrupted_agent, &waiting_agent] {+ held_lists.push_back(Waiting {+ address,+ waiter: Arc::clone(waiter),+ });+ }+ interrupted_agent.is_interrupted.store(true, Ordering::SeqCst);+ drop(held_lists);+ assert_eq!(atomic_notify(&word, 1), 1);+ assert!(waiting_agent.was_notified.load(Ordering::Relaxed));+ assert!(!interrupted_agent.was_notified.load(Ordering::Relaxed));+ assert_eq!(waiters_of(&word), 0);+ }++ #[test]+ fn interrupted_agents_do_not_wait_again() {+ let word = AtomicU32::new(0);+ let agent = AgentWaiter::new();+ agent.interrupt();+ assert_eq!(wait(&word, 0, None, &agent), AtomicWaitResult::Interrupted);+ assert_eq!(wait(&word, 1, None, &agent), AtomicWaitResult::Interrupted);+ }++ #[test]+ fn interrupts_reach_waits_that_are_just_starting() {+ for _ in 0..2000 {+ let word = AtomicU32::new(0);+ let agent = AgentWaiter::new();+ std::thread::scope(|scope| {+ let waiter = scope.spawn(|| wait(&word, 0, None, &agent));+ agent.interrupt();+ assert_eq!(waiter.join().unwrap(), AtomicWaitResult::Interrupted);+ });+ }+ }++ #[test]+ fn interrupts_leave_the_other_waiters_of_a_word_alone() {+ let word = AtomicU32::new(0);+ let interrupted_agent = AgentWaiter::new();+ let woken = AtomicUsize::new(0);+ std::thread::scope(|scope| {+ let first = scope.spawn(|| wait(&word, 0, None, &interrupted_agent));+ wait_for_waiters(&word, 1);+ let second = scope.spawn(|| {+ let result = wait(&word, 0, None, &AgentWaiter::new());+ woken.fetch_add(1, Ordering::SeqCst);+ result+ });+ wait_for_waiters(&word, 2);+ interrupted_agent.interrupt();+ assert_eq!(first.join().unwrap(), AtomicWaitResult::Interrupted);+ std::thread::sleep(TIME_TO_SLEEP);+ assert_eq!(woken.load(Ordering::SeqCst), 0);+ assert_eq!(waiters_of(&word), 1);+ // NB: The interrupted agent gave its place up, so nothing is lost to it.+ assert_eq!(atomic_notify(&word, 1), 1);+ assert_eq!(second.join().unwrap(), AtomicWaitResult::Woken);+ });+ }++ #[test]+ fn every_agent_that_a_notify_counts_wakes_whatever_the_order_on_the_list() {+ let word = AtomicU32::new(0);+ std::thread::scope(|scope| {+ let waiters: Vec<_> = (0..64)+ .map(|_| scope.spawn(|| wait(&word, 0, None, &AgentWaiter::new())))+ .collect();+ wait_for_waiters(&word, waiters.len());+ for _ in 0..waiters.len() {+ assert_eq!(atomic_notify(&word, 1), 1);+ }+ assert_eq!(atomic_notify(&word, 1), 0);+ for waiter in waiters {+ assert_eq!(waiter.join().unwrap(), AtomicWaitResult::Woken);+ }+ });+ }++ #[test]+ fn many_agents_can_wait_on_one_word_and_be_interrupted_one_by_one() {+ // NB: More agents than the 31 interrupt slots that the futex path had.+ let word = AtomicU32::new(0);+ let agents: Vec<_> = (0..64).map(|_| AgentWaiter::new()).collect();+ std::thread::scope(|scope| {+ // NB: One at a time, as a notify wakes the first on the list, which the loop below expects to be this order.+ let waiters: Vec<_> = agents+ .iter()+ .enumerate()+ .map(|(index, agent)| {+ let word = &word;+ let waiter = scope.spawn(move || wait(word, 0, None, agent));+ wait_for_waiters(word, index + 1);+ waiter+ })+ .collect();+ for (index, (agent, waiter)) in agents.iter().zip(waiters).enumerate() {+ if index % 2 == 0 {+ agent.interrupt();+ assert_eq!(waiter.join().unwrap(), AtomicWaitResult::Interrupted);+ } else {+ assert_eq!(atomic_notify(&word, 1), 1);+ assert_eq!(waiter.join().unwrap(), AtomicWaitResult::Woken);+ }+ }+ });+ }+}diff --git a/Libraries/LibCore/CMakeLists.txt b/Libraries/LibCore/CMakeLists.txtindex e5cfab1e9ce..b0d4824147d 100644--- a/Libraries/LibCore/CMakeLists.txt+++ b/Libraries/LibCore/CMakeLists.txt@@ -8,7 +8,6 @@ set(SOURCESDirectoryEntry.cppElapsedTimer.cppEnvironment.cpp- Futex.cppEventLoop.cppEventLoopImplementation.cppEventReceiver.cppdiff --git a/Libraries/LibCore/Futex.cpp b/Libraries/LibCore/Futex.cppdeleted file mode 100644index d39197d7f5f..00000000000--- a/Libraries/LibCore/Futex.cpp+++ /dev/null@@ -1,244 +0,0 @@-/*- * Copyright (c) 2026-present, the Ladybird developers.- *- * SPDX-License-Identifier: BSD-2-Clause- */--#include <AK/Endian.h>-#include <AK/Format.h>-#include <AK/NumericLimits.h>-#include <AK/Platform.h>-#include <AK/Time.h>-#include <LibCore/Futex.h>--#include <errno.h>--#if defined(AK_OS_MACOS)-# include <os/os_sync_wait_on_address.h>-# include <unistd.h>-#elif defined(AK_OS_LINUX)-# include <linux/futex.h>-# include <sys/syscall.h>-# include <time.h>-# include <unistd.h>-#elif !defined(AK_OS_WINDOWS)-# include <unistd.h>-#endif--#ifdef AK_OS_WINDOWS-# include <AK/Windows.h>-#endif--namespace Core {--static u64 read_word(void* address, size_t size)-{- if (size >= 8)- return __atomic_load_n(reinterpret_cast<u64 volatile*>(address), __ATOMIC_SEQ_CST);- return __atomic_load_n(reinterpret_cast<u32 volatile*>(address), __ATOMIC_SEQ_CST);-}--// Whether the word at address currently equals expected, masked to the wait size (Atomics.wait uses 4-byte or 8-byte-// words). A sequentially-consistent read, matching the memory model's read for the wait comparison.-static bool word_equals(void* address, u64 expected, size_t size)-{- auto mask = size >= 8 ? NumericLimits<u64>::max() : NumericLimits<u32>::max();- return (read_word(address, size) & mask) == (expected & mask);-}--// Fallback where there's no cross-process wait primitive: Poll for a change to the word. That observes value changes-// rather than notifications — which matches the lock/futex protocol Emscripten uses (the waker writes the word before-// notifying). The gap is a notify that leaves the word unchanged: It wakes no poll-waiter, and the paired atomic_notify-// reports zero woken. An untimed wait whose only wake would be such a notify therefore never returns. Closing that gap-// would take a waiter registry in shared memory — at the cost a lot of extra machinery most modern platforms would-// never use, but instead just for the benefit of limited number of platforms/legacy environments. Not a good tradeoff.-static AtomicWaitResult poll_wait(void* address, u64 expected, size_t size, Optional<AK::Duration> timeout)-{- if (!word_equals(address, expected, size))- return AtomicWaitResult::NotEqual;-- auto start = MonotonicTime::now();- for (;;) {-#if defined(AK_OS_WINDOWS)- // Sleep takes whole milliseconds; 1 is its shortest non-zero wait.- Sleep(1);-#else- usleep(200);-#endif- if (!word_equals(address, expected, size))- return AtomicWaitResult::Woken;- if (timeout.has_value() && (MonotonicTime::now() - start) >= *timeout)- return AtomicWaitResult::TimedOut;- }-}--#if defined(AK_OS_MACOS)--AtomicWaitResult atomic_wait(void* address, u64 expected, size_t size, Optional<AK::Duration> timeout)-{- // Compare the value in userspace first. os_sync_wait_on_address reports a value mismatch as a *successful* return- // (it has no EAGAIN). So, without this, the "not-equal" result would be unreachable; it also faults the shared page- // in — avoiding a transient first-touch EFAULT below. A store landing between this read and the kernel's own- // comparison is reported as a wake, rather than "not-equal" — a nanoseconds-wide window inherent to the os_sync API- // (Linux's kernel futex and the poll fallback don't have it).- if (!word_equals(address, expected, size))- return AtomicWaitResult::NotEqual;-- // Anchor the timeout to a fixed deadline — so that nothing restarts it. Both an EINTR retry and the fallback to- // polling below continue with only the time that's left.- Optional<MonotonicTime> deadline;- if (timeout.has_value())- deadline = MonotonicTime::now() + *timeout;-- if (__builtin_available(macOS 14.4, *)) {- // os_sync_wait_on_address makes the element size part of the wait/wake key. Wait on the low 32-bit half (size- // 4) for both 4-byte and 8-byte waits: the full-width userspace pre-compare above already rejected any full-- // value mismatch, so the low half only has to close the lost-wake race at entry — and normalizing the size lets- // 4-byte and 8-byte waiters at one address share kernel state (a single spec WaiterList) and cross-wake.- // Passing the real size instead makes os_sync reject a mixed-size wait/notify pair with EINVAL. On little-- // endian, the low half is the word at 'address' (byte offset 0).- static_assert(AK::HostIsLittleEndian, "8-byte os_sync waits assume the low 32-bit half is at byte offset 0");-- for (;;) {- int result;- if (deadline.has_value()) {- auto remaining = (*deadline - MonotonicTime::now()).to_nanoseconds();- if (remaining <= 0)- return AtomicWaitResult::TimedOut;- result = os_sync_wait_on_address_with_timeout(address, static_cast<u32>(expected), 4, OS_SYNC_WAIT_ON_ADDRESS_SHARED, OS_CLOCK_MACH_ABSOLUTE_TIME, static_cast<uint64_t>(remaining));- } else {- result = os_sync_wait_on_address(address, static_cast<u32>(expected), 4, OS_SYNC_WAIT_ON_ADDRESS_SHARED);- }-- if (result >= 0)- return AtomicWaitResult::Woken;- if (errno == EINTR) {- // os_sync reports a value mismatch as a successful wake — so retrying with the original expected would- // turn a store that landed while we slept into a spurious "ok". Re-read first: If the word changed,- // report "not-equal" (as if the critical section were entered late) — matching the Linux EAGAIN path.- if (!word_equals(address, expected, size))- return AtomicWaitResult::NotEqual;- continue;- }- if (errno == ETIMEDOUT)- return AtomicWaitResult::TimedOut;- if (errno == EAGAIN)- return AtomicWaitResult::NotEqual;- // os_sync couldn't key this memory (rare once faulted in above); fall back to polling for a change.- break;- }- }- if (deadline.has_value()) {- auto remaining = *deadline - MonotonicTime::now();- return poll_wait(address, expected, size, remaining > AK::Duration::zero() ? remaining : AK::Duration::zero());- }- return poll_wait(address, expected, size, timeout);-}--size_t atomic_notify(void* address, size_t size, size_t max_count)-{- // Waiters key on the low 32-bit half — so, wake with size 4 regardless of the notifying view's element size. That- // lets a 4-byte notify wake an 8-byte waiter (and vice versa) at the same address — which the spec's single per-- // address WaiterList requires. Passing the view's own size would make os_sync reject a mixed-size wake with EINVAL.- (void)size;- if (__builtin_available(macOS 14.4, *)) {- // os_sync wakes a single waiter at a time. So, wake up to max_count of them — stopping once there are none- // left. ENOENT is that stop: it means the wait set is empty. Every other error is a real failure: EINVAL for a- // size mismatch or a flag mismatch against the waiters, EFAULT for an address the kernel can't read. So, report- // those — rather than letting them pass as an empty wait set.- size_t woken = 0;- while (woken < max_count) {- if (os_sync_wake_by_address_any(address, 4, OS_SYNC_WAKE_BY_ADDRESS_SHARED) == 0) {- ++woken;- continue;- }- if (errno != ENOENT)- dbgln("Core::atomic_notify: os_sync_wake_by_address_any failed with errno {}", errno);- break;- }- return woken;- }- // The poll_wait fallback observes value changes directly — so no explicit wake is required.- (void)address;- (void)max_count;- return 0;-}--#elif defined(AK_OS_LINUX)--AtomicWaitResult atomic_wait(void* address, u64 expected, size_t size, Optional<AK::Duration> timeout)-{- // Compare the value in userspace first — so a zero or already-elapsed timeout still yields "not-equal" (which the- // spec orders before "timed-out"), and so 8-byte waits and the poll fallback share one compare.- if (!word_equals(address, expected, size))- return AtomicWaitResult::NotEqual;-- // FUTEX_WAIT compares a 32-bit word. An 8-byte wait waits on the low 32-bit half instead: The full-width userspace- // pre-compare above already rejected any full-value mismatch — so the low half only has to close the lost-wake race- // at entry. On little-endian, the low half is the word at 'address' (byte offset 0) — so no offset is needed.- static_assert(AK::HostIsLittleEndian, "8-byte futex waits assume the low 32-bit half is at byte offset 0");- // Atomics.wait only ever uses size 4 or 8 (ValidateIntegerTypedArray); keep the poll fallback as a guard.- if (size != 4 && size != 8)- return poll_wait(address, expected, size, timeout);-- // Anchor the timeout to a fixed deadline — so EINTR retries reduce the remaining time, rather than restarting the- // full timeout (FUTEX_WAIT takes a relative timeout that the kernel doesn't update across a retry).- Optional<MonotonicTime> deadline;- if (timeout.has_value())- deadline = MonotonicTime::now() + *timeout;-- for (;;) {- struct timespec relative_timeout;- struct timespec* timeout_pointer = nullptr;- if (deadline.has_value()) {- auto remaining = (*deadline - MonotonicTime::now()).to_nanoseconds();- if (remaining <= 0)- return AtomicWaitResult::TimedOut;- relative_timeout.tv_sec = static_cast<time_t>(remaining / 1'000'000'000);- relative_timeout.tv_nsec = static_cast<long>(remaining % 1'000'000'000);- timeout_pointer = &relative_timeout;- }-- // A shared (non-private) FUTEX_WAIT keys on the underlying page — so it coordinates across processes.- long result = syscall(SYS_futex, address, FUTEX_WAIT, static_cast<u32>(expected), timeout_pointer, nullptr, 0);- if (result == 0)- return AtomicWaitResult::Woken;- if (errno == EINTR)- continue;- if (errno == ETIMEDOUT)- return AtomicWaitResult::TimedOut;- // EAGAIN means the value at the address no longer equals expected.- return AtomicWaitResult::NotEqual;- }-}--size_t atomic_notify(void* address, size_t size, size_t max_count)-{- // FUTEX_WAKE wakes waiters keyed on the low 32-bit half at 'address'. That covers both 4-byte and 8-byte waiters- // (8-byte waits key on the low half too), and returns the exact number of waiters woken.- (void)size;- auto count = max_count > static_cast<size_t>(NumericLimits<i32>::max()) ? NumericLimits<i32>::max() : static_cast<i32>(max_count);- long result = syscall(SYS_futex, address, FUTEX_WAKE, count, nullptr, nullptr, 0);- return result < 0 ? 0 : static_cast<size_t>(result);-}--#else--// No native wait/wake primitive is wired up on this platform. Poll for a change to the word, instead of reporting-// "not-equal" unconditionally — which would make every Atomics.wait return immediately, and spin its caller. Polling-// observes the waker's store directly — so, it works across processes for memory shared between agents.-AtomicWaitResult atomic_wait(void* address, u64 expected, size_t size, Optional<AK::Duration> timeout)-{- return poll_wait(address, expected, size, timeout);-}--size_t atomic_notify(void*, size_t, size_t)-{- // The waiters poll for the value change the waker has already made — so there's nothing to signal. This reports no- // waiters woken, which Atomics.notify returns to script.- return 0;-}--#endif--}diff --git a/Libraries/LibCore/Futex.h b/Libraries/LibCore/Futex.hdeleted file mode 100644index dc589e07773..00000000000--- a/Libraries/LibCore/Futex.h+++ /dev/null@@ -1,38 +0,0 @@-/*- * Copyright (c) 2026-present, the Ladybird developers.- *- * SPDX-License-Identifier: BSD-2-Clause- */--#pragma once--#include <AK/Optional.h>-#include <AK/Time.h>-#include <AK/Types.h>-#include <LibCore/Export.h>--namespace Core {--enum class AtomicWaitResult : u8 {- Woken,- NotEqual,- TimedOut,-};--// Compare-and-wait on a shared-memory word (size is 4 or 8 bytes). If the value at address doesn't equal expected,-// returns NotEqual immediately; otherwise, blocks until woken by atomic_notify on the same address, or the (optional)-// timeout elapses. For cross-agent coordination the address must live in memory shared across processes.-//-// PLATFORM CAVEAT: where no cross-process wait primitive is wired up, this polls for a change to the word — instead of-// waiting for a notification. See poll_wait() in Futex.cpp. On that path, a wake is inferred from the store — not from-// the notification — which in practice the waker protocols (Emscripten's included) always perform first. What it can't-// observe is a notify that leaves the word unchanged: Such a notify wakes nobody — so an untimed wait paired only with-// one blocks until its agent goes away. That path is only taken on platforms other than Linux and modern macOS.-CORE_API AtomicWaitResult atomic_wait(void* address, u64 expected, size_t size, Optional<AK::Duration> timeout);--// Wakes up to max_count waiters blocked on address; returns the number actually woken. On the polling path described-// above, there's nothing to signal, and no waiter registry to count — so, this reports zero however many waiters exist-// (a count Atomics.notify hands straight back to script).-CORE_API size_t atomic_notify(void* address, size_t size, size_t max_count);--}diff --git a/Libraries/LibJS/Runtime/VM.cpp b/Libraries/LibJS/Runtime/VM.cppindex 28a3c8049c2..5d783e83048 100644--- a/Libraries/LibJS/Runtime/VM.cpp+++ b/Libraries/LibJS/Runtime/VM.cpp@@ -457,6 +457,11 @@ bool VM::interrupt_requested() constreturn js_vm_interrupt_requested(vm_abi(*this));}+bool VM::is_waiting_on_shared_memory() const+{+ return js_vm_is_waiting_on_shared_memory(vm_abi(*this));+}+Debugger* VM::debugger(){if (!debugging_enabled())diff --git a/Libraries/LibJS/Runtime/VM.h b/Libraries/LibJS/Runtime/VM.hindex 397049cd58e..1887f82a72c 100644--- a/Libraries/LibJS/Runtime/VM.h+++ b/Libraries/LibJS/Runtime/VM.h@@ -166,6 +166,10 @@ public:void request_interrupt();[[nodiscard]] bool interrupt_requested() const;+ // Whether the thread of this VM sleeps in Atomics.wait() or memory.atomic.wait, on the list that a notify takes it+ // off. Any thread may call this, as long as the VM stays alive until it returns.+ [[nodiscard]] bool is_waiting_on_shared_memory() const;+#define __JS_ENUMERATE(SymbolName, snake_name) \GC::Ref<Symbol> well_known_symbol_##snake_name() const \{ \diff --git a/Libraries/LibJS/Rust/src/embedding/vm.rs b/Libraries/LibJS/Rust/src/embedding/vm.rsindex e48ca15b8a6..24ac2b10e1b 100644--- a/Libraries/LibJS/Rust/src/embedding/vm.rs+++ b/Libraries/LibJS/Rust/src/embedding/vm.rs@@ -247,6 +247,18 @@ pub unsafe extern "C" fn js_vm_interrupt_requested(vm: *mut JSVM) -> bool {unsafe { vm_from_abi(vm) }.interrupt_requested()}+/// Whether the thread of the VM waits on a word of shared memory, on the list that a notify takes it off. Any thread may+/// call this.+///+/// # Safety+///+/// `vm` must stay alive until this returns.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn js_vm_is_waiting_on_shared_memory(vm: *mut JSVM) -> bool {+ // SAFETY: The caller keeps the VM alive, and the call only touches its agent waiter.+ unsafe { vm_from_abi(vm) }.agent_waiter().is_waiting()+}+/// Makes `agent` the surrounding agent of the VM: its [[CanBlock]] says whether Atomics.wait() may block, and await in/// native code spins its event loop until the awaited promise settles. Without an agent, which a null `agent` sets,/// Atomics.wait() may block and await runs the VM's own queue of promise jobs, which is empty if an enqueue_promise_jobdiff --git a/Libraries/LibJS/Rust/src/interpreter/vm.rs b/Libraries/LibJS/Rust/src/interpreter/vm.rsindex c5bfc7a38b5..dc4d2a4c79b 100644--- a/Libraries/LibJS/Rust/src/interpreter/vm.rs+++ b/Libraries/LibJS/Rust/src/interpreter/vm.rs@@ -15,7 +15,7 @@ use std::collections::VecDeque;use std::rc::Rc;use std::sync::{Arc, Mutex, PoisonError};-use ak::futex::WaitInterrupt;+use ak::waiter_list::AgentWaiter;use ak::{Utf16FlyString, Utf16String};use libjs_runtime_macros::Trace;@@ -519,8 +519,8 @@ pub struct Vm {pub jit_native_stack_limit: AtomicUsize,/// Set once script on this VM has to stop for good (see request_interrupt()). Any thread may set it.interrupt_requested: AtomicBool,- /// What wakes this VM's thread from Atomics.wait() and memory.atomic.wait for an interrupt.- wait_interrupt: Arc<WaitInterrupt>,+ /// This agent's node in the WaiterLists, which Atomics.wait() and memory.atomic.wait sleep on.+ agent_waiter: Arc<AgentWaiter>,/// The tables `VmHead::dispatch_tables` points to.pub(crate) own_dispatch_tables: VmDispatchTables,/// The word that stops the WebAssembly code of this VM's agent (see set_wasm_stack_limit_word()), if it has any.@@ -697,7 +697,7 @@ impl Vm {},jit_native_stack_limit: AtomicUsize::new(0),interrupt_requested: AtomicBool::new(false),- wait_interrupt: Arc::new(WaitInterrupt::new()),+ agent_waiter: AgentWaiter::new(),own_dispatch_tables: VmDispatchTables::new(),wasm_stack_limit_word: Mutex::new(core::ptr::null()),heap: OnceCell::new(),@@ -895,7 +895,7 @@ impl Vm {/// Script costs nothing to run for this: the interpreter stops at its next dispatch, as every dispatch table entry/// becomes the fallback handler, and JIT code stops at its next call or loop back edge, which compare the stack/// pointer with a limit anyway, so raising the limit past every stack pointer does it. A thread that sleeps on a word- /// of shared memory gets woken. This returns once it is awake.+ /// of shared memory gets woken.////// Script unwinds with interrupt_exception(), past every handler. The flag is never cleared: every later attempt to/// run code fails at once, which is what makes the places in native code that catch exceptions harmless. They can@@ -913,12 +913,12 @@ impl Vm {if let Some(word) = unsafe { word.as_ref() } {word.store(u64::MAX, Ordering::Relaxed);}- self.wait_interrupt.interrupt();+ self.agent_waiter.interrupt();}- /// What ends a wait of this VM's thread on a word of shared memory.- pub fn wait_interrupt(&self) -> &Arc<WaitInterrupt> {- &self.wait_interrupt+ /// This agent's node in the WaiterLists.+ pub fn agent_waiter(&self) -> &Arc<AgentWaiter> {+ &self.agent_waiter}/// Has an interrupt also store the highest address to `word` (null for none), which is how the embedder'sdiff --git a/Libraries/LibJS/Rust/src/runtime/array_buffer.rs b/Libraries/LibJS/Rust/src/runtime/array_buffer.rsindex 9376ceb61e7..0ff6d9d0c24 100644--- a/Libraries/LibJS/Rust/src/runtime/array_buffer.rs+++ b/Libraries/LibJS/Rust/src/runtime/array_buffer.rs@@ -44,7 +44,7 @@ use crate::runtime::typed_array::TypedArrayBase;use crate::runtime::value::same_value;use crate::runtime::value_conversions;use crate::runtime::value_conversions::MAX_ARRAY_LIKE_INDEX;-use ak::futex::{self, AtomicWaitResult, WaitInterrupt, WaitWord};+use ak::waiter_list::{self, AgentWaiter, AtomicWaitResult, WaitWord};pub use crate::gc::primitive_storage::cage_base as primitive_storage_cage_base;pub use crate::gc::primitive_storage::{OutOfMemory, ZeroFillNewBytes};@@ -1402,14 +1402,14 @@ impl ArrayBuffer {.to_le_bytes()}- /// Core::atomic_wait() on the word at `byte_index`.+ /// waiter_list::atomic_wait() on the word at `byte_index`.pub fn atomic_wait(&self,byte_index: usize,expected: u64,size: usize,timeout: Option<Duration>,- interrupt: &WaitInterrupt,+ waiter: &Arc<AgentWaiter>,) -> AtomicWaitResult {// NB: The data block stays borrowed while the agent waits, since the agent is the only one that could change it.let data_block = self.data_block.borrow();@@ -1418,13 +1418,13 @@ impl ArrayBuffer {8 => WaitWord::Word64(data_block.atomic_at(byte_index)),_ => unreachable!("Atomics.wait waits on 4-byte or 8-byte elements"),};- futex::atomic_wait(word, expected, timeout, Some(interrupt))+ waiter_list::atomic_wait(word, expected, timeout, waiter)}- /// Core::atomic_notify() on the word at `byte_index`.+ /// waiter_list::atomic_notify() on the word at `byte_index`.pub fn atomic_notify(&self, byte_index: usize, max_count: usize) -> usize {- // NB: Waiters of both sizes key on the low 32-bit half of their word.- futex::atomic_notify(self.data_block.borrow().atomic_at::<AtomicU32>(byte_index), max_count)+ // NB: Waiters of both sizes are on the list of the address of their word.+ waiter_list::atomic_notify(self.data_block.borrow().atomic_at::<AtomicU32>(byte_index), max_count)}}diff --git a/Libraries/LibJS/Rust/src/runtime/atomics_object.rs b/Libraries/LibJS/Rust/src/runtime/atomics_object.rsindex eca668f1493..82b1fac61dc 100644--- a/Libraries/LibJS/Rust/src/runtime/atomics_object.rs+++ b/Libraries/LibJS/Rust/src/runtime/atomics_object.rs@@ -28,7 +28,7 @@ use crate::runtime::typed_array::{ContentType, Kind, TypedArrayBase, TypedArrayWithBufferWitness, is_typed_array_out_of_bounds,make_typed_array_with_buffer_witness_record, typed_array_from, typed_array_length, validate_typed_array,};-use ak::futex::AtomicWaitResult;+use ak::waiter_list::AtomicWaitResult;#[repr(C)]#[derive(Trace)]@@ -229,9 +229,8 @@ fn do_wait(}// 11. Let block be buffer.[[ArrayBufferData]].- // 12-24. AD-HOC: Rather than maintaining the spec's WaiterList, we wait on the shared-memory word using an OS- // futex. The word lives in memory mapped into every agent's process — so wait and notify coordinate across- // processes. We don't yet implement Atomics.waitAsync (async mode).+ // 12-24. AD-HOC: The WaiterLists of the process are in ak::waiter_list. We don't yet implement Atomics.waitAsync+ // (async mode).if mode == WaitMode::Async {return vm.throw_completion(ErrorKind::InternalError,@@ -256,7 +255,7 @@ fn do_wait(value as u64,typed_array.element_size(),wait_timeout,- vm.wait_interrupt(),+ vm.agent_waiter(),);let result = match result {AtomicWaitResult::Interrupted => return vm.throw_interrupt(),@@ -505,7 +504,7 @@ impl AtomicsObject {return Ok(Value::from_i32(0));}- // 7-15. AD-HOC: Wake up to 'count' agents waiting on the shared-memory word via the OS futex (see do_wait).+ // 7-15. AD-HOC: Wake up to 'count' agents on the WaiterList of the word (see do_wait).// count is >= 0 (step 3b). But a huge finite value would overflow size_t (UB on the cast). So, treat anything at or// beyond size_t's range (and non-finite counts) as "wake every waiter".let max_count = if count.is_finite() && count < usize::MAX as f64 {diff --git a/Libraries/LibWasm/Engine/src/runtime/helpers.rs b/Libraries/LibWasm/Engine/src/runtime/helpers.rsindex 9c4a0ce669f..6c4226b24b3 100644--- a/Libraries/LibWasm/Engine/src/runtime/helpers.rs+++ b/Libraries/LibWasm/Engine/src/runtime/helpers.rs@@ -13,7 +13,7 @@ use crate::abi::{TableData,};use crate::validator::{CatchKind, NO_EXCEPTION_LOCAL, NOT_DELEGATED};-use ak::futex::{self, AtomicWaitResult, WaitWord};+use ak::waiter_list::{self, AgentWaiter, AtomicWaitResult, WaitWord};export_runtime_functions! {wasm_runtime_memory_grow => memory_grow,@@ -269,9 +269,9 @@ unsafe fn wait(context: *mut ExecutionContext) -> u64 {));return crate::abi::WAIT_CANNOT_BLOCK;}- // NB: The waits and wakes are those of Atomics.wait and Atomics.notify (ak::futex), whose waiter lists are- // the operating system's, per address: JavaScript and WebAssembly wake each other, as the memory model's- // single WaiterList per location requires.+ // NB: The waits and wakes are those of Atomics.wait and Atomics.notify, in the waiter lists of the process, per+ // address: JavaScript and WebAssembly wake each other, as the memory model's single WaiterList per location+ // requires.let word = unsafe {if size == 4 {WaitWord::Word32(&*(address as *const std::sync::atomic::AtomicU32))@@ -280,7 +280,9 @@ unsafe fn wait(context: *mut ExecutionContext) -> u64 {}};let timeout = (timeout >= 0).then(|| std::time::Duration::from_nanos(timeout as u64));- match futex::atomic_wait(word, expected, timeout, store.wait_interrupt.as_deref()) {+ // NB: A store without an agent has nothing to interrupt it, as a test's has not.+ let waiter = store.agent_waiter.clone().unwrap_or_else(AgentWaiter::new);+ match waiter_list::atomic_wait(word, expected, timeout, &waiter) {AtomicWaitResult::Woken => 0,AtomicWaitResult::NotEqual => 1,AtomicWaitResult::TimedOut => 2,@@ -300,5 +302,5 @@ unsafe fn wait(context: *mut ExecutionContext) -> u64 {unsafe fn notify(context: *mut ExecutionContext) -> u64 {let (address, count) = unsafe { ((*context).arguments[0], (*context).arguments[1]) };let word = unsafe { &*(address as *const std::sync::atomic::AtomicU32) };- futex::atomic_notify(word, usize::try_from(count).unwrap_or(usize::MAX)) as u64+ waiter_list::atomic_notify(word, usize::try_from(count).unwrap_or(usize::MAX)) as u64}diff --git a/Libraries/LibWasm/Engine/src/runtime/mod.rs b/Libraries/LibWasm/Engine/src/runtime/mod.rsindex 8e21d4c9b7b..d1cfacd4ecd 100644--- a/Libraries/LibWasm/Engine/src/runtime/mod.rs+++ b/Libraries/LibWasm/Engine/src/runtime/mod.rs@@ -50,7 +50,7 @@ use crate::abi::{};use crate::module::{DataMode, ElementItems, ElementMode, ExternalKind, ImportDescription, Module};use crate::types::{FuncType, GlobalType, HeapType, RefType, TableType, TypeCanonicalizer, ValType};-use ak::futex::WaitInterrupt;+use ak::waiter_list::AgentWaiter;use memory::MemoryInstance;use std::collections::HashMap;use std::rc::Rc;@@ -392,7 +392,7 @@ pub struct Store {pub can_block: bool,/// What lets another thread end a `memory.atomic.wait` of this store's code. The embedder sets this, along with/// whatever makes it stop the store.- pub wait_interrupt: Option<Arc<WaitInterrupt>>,+ pub agent_waiter: Option<Arc<AgentWaiter>>,/// The store's compiled code, once it has some.jit: Option<jit::StoreJit>,}@@ -447,7 +447,7 @@ impl Store {rtt_pointers: Vec::new(),memory_grow_callback: None,can_block: true,- wait_interrupt: None,+ agent_waiter: None,jit: None,}}diff --git a/Libraries/LibWasm/Engine/tests/execution.rs b/Libraries/LibWasm/Engine/tests/execution.rsindex d4a299c782a..c6478ad7670 100644--- a/Libraries/LibWasm/Engine/tests/execution.rs+++ b/Libraries/LibWasm/Engine/tests/execution.rs@@ -372,9 +372,8 @@ fn constant_arrays_too_large_for_memory_trap() {}}-/// memory.atomic.wait waits where Atomics.wait does, on the operating system's waiter list for the address, so that-/// a wake of the address from outside WebAssembly (here a FUTEX_WAKE, as Atomics.notify does) ends it.-#[cfg(target_os = "linux")]+/// memory.atomic.wait waits where Atomics.wait does, on the waiter lists of the process, so that a notify of the address+/// from outside WebAssembly, as Atomics.notify does it, ends it.#[test]fn waits_end_with_wakes_from_outside_webassembly() {let (sender, receiver) = std::sync::mpsc::channel();@@ -397,17 +396,8 @@ fn waits_end_with_wakes_from_outside_webassembly() {let start = std::time::Instant::now();loop {// Until the wait has started: a wake before it wakes nobody.- let woken = unsafe {- libc::syscall(- libc::SYS_futex,- address as *mut u32,- libc::FUTEX_WAKE,- 1,- std::ptr::null::<libc::timespec>(),- std::ptr::null::<u32>(),- 0,- )- };+ // SAFETY: The word is in the memory of the store, which lives until the wait is over.+ let woken = ak::waiter_list::atomic_notify(unsafe { &*(address as *const std::sync::atomic::AtomicU32) }, 1);if woken == 1 {break;}@@ -514,7 +504,7 @@ fn another_thread_interrupts_a_compiled_loop() {/// Starts a memory.atomic.wait on a thread of its own, which `interrupt` can end, and returns the address of its word.fn start_wait(timeout: i64,- interrupt: Arc<ak::futex::WaitInterrupt>,+ interrupt: Arc<ak::waiter_list::AgentWaiter>,disable_jit: bool,) -> (usize, std::thread::JoinHandle<Result<Vec<Value>, Trap>>) {let (sender, receiver) = std::sync::mpsc::channel();@@ -523,7 +513,7 @@ fn start_wait(if disable_jit {store.disable_jit();}- store.wait_interrupt = Some(interrupt);+ store.agent_waiter = Some(interrupt);let instance = instantiate(&mut store, "shared_memory_export.wasm");let Some(ExternValue::Memory(memory)) = store.instance(instance).export("memory") else {panic!("no memory export");@@ -544,7 +534,7 @@ fn another_thread_interrupts_a_wait() {for disable_jit in [false, true] {// No timeout, and ten minutes.for timeout in [-1, 600_000_000_000] {- let interrupt = Arc::new(ak::futex::WaitInterrupt::new());+ let interrupt = ak::waiter_list::AgentWaiter::new();let (_, waiter) = start_wait(timeout, interrupt.clone(), disable_jit);std::thread::sleep(std::time::Duration::from_millis(50));interrupt.interrupt();@@ -554,10 +544,9 @@ fn another_thread_interrupts_a_wait() {}/// Only a wake ends a wait: it does not look at the word again.-#[cfg(target_os = "linux")]#[test]fn a_change_of_the_word_does_not_end_a_wait() {- let interrupt = Arc::new(ak::futex::WaitInterrupt::new());+ let interrupt = ak::waiter_list::AgentWaiter::new();let (address, waiter) = start_wait(300_000_000, interrupt, false);std::thread::sleep(std::time::Duration::from_millis(100));// SAFETY: The word is in the memory of the store, which lives until the wait is over.diff --git a/Libraries/LibWeb/Bindings/Rust/src/web_assembly/mod.rs b/Libraries/LibWeb/Bindings/Rust/src/web_assembly/mod.rsindex 76600240629..746c7f53e34 100644--- a/Libraries/LibWeb/Bindings/Rust/src/web_assembly/mod.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/web_assembly/mod.rs@@ -225,7 +225,7 @@ impl Agent {// NB: An interrupt of the agent's VM has to stop the store's code too.// SAFETY: The word is in the boxed store, which does not move, and shut_down() clears it before the store goes.unsafe { vm.set_wasm_stack_limit_word(store.stack_limit_word()) };- store.wait_interrupt = Some(vm.wait_interrupt().clone());+ store.agent_waiter = Some(vm.agent_waiter().clone());// NB: The store is the agent's, whose [[CanBlock]] decides whether memory.atomic.wait may block.store.can_block = libjs_rust::api::agent_can_suspend(vm);diff --git a/Meta/Linters/check_rust_process_wide_state.py b/Meta/Linters/check_rust_process_wide_state.pyindex 62100139f27..ab4d4771209 100755--- a/Meta/Linters/check_rust_process_wide_state.py+++ b/Meta/Linters/check_rust_process_wide_state.py@@ -30,6 +30,7 @@ import sys# or a stub in a test binary.ALLOWED = {"Libraries/LibGfx/Rust/src/text_layout.rs:SHAPING_CACHE": "per-thread memo of a pure function; a second copy costs memory, never an answer",+ "AK/Rust/src/waiter_list.rs:LISTS": "only libjs_rust and libwasm_engine use it, which are in one library of a process, so they share a copy; a caller in another library needs the state moved to C++","Libraries/LibCompositing/Rust/src/test_stubs.rs:NEXT": "test stub for LibGfx's C++ counters, in the cargo test binary that has no C++ side","Libraries/LibCompositing/Rust/src/display_list/replay.rs:WARM_REPLAY_SCRATCH_STORAGE": "per-thread replay scratch; a second copy costs memory, never an answer","Libraries/LibJS/Flap/src/low_ir/lowering.rs:LABELS": "per-thread scratch buffer; a second copy costs memory, never an answer",diff --git a/Tests/LibCore/CMakeLists.txt b/Tests/LibCore/CMakeLists.txtindex 2a2543393ee..734036217f2 100644--- a/Tests/LibCore/CMakeLists.txt+++ b/Tests/LibCore/CMakeLists.txt@@ -24,7 +24,6 @@ endif()if (APPLE OR LINUX)list(APPEND TEST_SOURCES- TestLibCoreFutex.cppTestLibCoreProcess.cppTestLibCoreStandardPaths.cpp)diff --git a/Tests/LibCore/TestLibCoreFutex.cpp b/Tests/LibCore/TestLibCoreFutex.cppdeleted file mode 100644index 3229cc79863..00000000000--- a/Tests/LibCore/TestLibCoreFutex.cpp+++ /dev/null@@ -1,224 +0,0 @@-/*- * Copyright (c) 2026-present, the Ladybird developers.- *- * SPDX-License-Identifier: BSD-2-Clause- */--#include <AK/Atomic.h>-#include <AK/Function.h>-#include <AK/Time.h>-#include <LibCore/AnonymousBuffer.h>-#include <LibCore/Futex.h>-#include <LibCore/System.h>-#include <LibTest/TestCase.h>-#include <LibThreading/Thread.h>--// Back the word with cross-process shared memory — as a real SharedArrayBuffer word is — so os_sync and the kernel-// futex operate on the same kind of memory they do in production.-static Core::AnonymousBuffer make_word_buffer()-{- return MUST(Core::AnonymousBuffer::create_with_size(sizeof(u64)));-}--TEST_CASE(wait_returns_not_equal_on_mismatch)-{- auto buffer = make_word_buffer();- auto* word = buffer.data<u32>();- *word = 42;-- // A mismatched value must return "not-equal" immediately without blocking — even with no timeout. On macOS, this is- // the regression guard: os_sync_wait_on_address reports a mismatch as a successful (wake) return — so without the- // userspace pre-compare, this would wrongly report "ok".- EXPECT(Core::atomic_wait(word, 99, sizeof(u32), {}) == Core::AtomicWaitResult::NotEqual);-}--TEST_CASE(wait_not_equal_beats_zero_timeout)-{- auto buffer = make_word_buffer();- auto* word = buffer.data<u32>();- *word = 42;-- // With a zero (or sub-tick) timeout and a mismatched value, "not-equal" must win over "timed-out".- EXPECT(Core::atomic_wait(word, 99, sizeof(u32), AK::Duration::from_milliseconds(0)) == Core::AtomicWaitResult::NotEqual);-}--TEST_CASE(wait_not_equal_with_finite_timeout)-{- auto buffer = make_word_buffer();- auto* word = buffer.data<u32>();- *word = 42;-- EXPECT(Core::atomic_wait(word, 99, sizeof(u32), AK::Duration::from_milliseconds(50)) == Core::AtomicWaitResult::NotEqual);-}--TEST_CASE(wait_times_out_when_value_matches)-{- auto buffer = make_word_buffer();- auto* word = buffer.data<u32>();- *word = 42;-- auto start = MonotonicTime::now();- // The value matches and nothing notifies — so the wait must run to the timeout.- EXPECT(Core::atomic_wait(word, 42, sizeof(u32), AK::Duration::from_milliseconds(50)) == Core::AtomicWaitResult::TimedOut);- // And it must actually have waited, not returned instantly.- EXPECT((MonotonicTime::now() - start) >= AK::Duration::from_milliseconds(20));-}--TEST_CASE(wait_zero_timeout_when_value_matches)-{- auto buffer = make_word_buffer();- auto* word = buffer.data<u32>();- *word = 42;-- // The value matches but the timeout is zero — so it times out immediately.- EXPECT(Core::atomic_wait(word, 42, sizeof(u32), AK::Duration::from_milliseconds(0)) == Core::AtomicWaitResult::TimedOut);-}--TEST_CASE(wait_eight_byte_not_equal_in_high_half)-{- auto buffer = make_word_buffer();- auto* word = buffer.data<u64>();- *word = 0x0000000100000042ULL; // low half 0x42, high half 1-- // The low 32 bits match, but the high 32 differ; a full 64-bit compare must report "not-equal".- EXPECT(Core::atomic_wait(word, 0x0000000200000042ULL, sizeof(u64), {}) == Core::AtomicWaitResult::NotEqual);-}--TEST_CASE(wait_eight_byte_times_out_when_value_matches)-{- auto buffer = make_word_buffer();- auto* word = buffer.data<u64>();- *word = 0x0000000100000042ULL;-- EXPECT(Core::atomic_wait(word, 0x0000000100000042ULL, sizeof(u64), AK::Duration::from_milliseconds(50)) == Core::AtomicWaitResult::TimedOut);-}--TEST_CASE(notify_wakes_a_waiter)-{- auto buffer = make_word_buffer();- IGNORE_USE_IN_ESCAPING_LAMBDA auto* word = buffer.data<u32>();- *word = 42;-- IGNORE_USE_IN_ESCAPING_LAMBDA AK::Atomic<bool> waiter_ready { false };- IGNORE_USE_IN_ESCAPING_LAMBDA AK::Atomic<int> result { -1 };-- auto thread = Threading::Thread::construct("FutexWaiter"sv, [&]() {- waiter_ready.store(true);- // The value stays 42 — so this blocks until notified; a generous timeout keeps a slow scheduler from timing us- // out during the retry loop below.- auto wait_result = Core::atomic_wait(word, 42, sizeof(u32), AK::Duration::from_milliseconds(5000));- result.store(static_cast<int>(wait_result));- return 0;- });- thread->start();-- while (!waiter_ready.load())- (void)Core::System::sleep_ms(1);-- // Retry to cover the window between the ready flag and the thread actually entering the kernel wait.- for (int i = 0; i < 200 && result.load() == -1; ++i) {- (void)Core::System::sleep_ms(5);- Core::atomic_notify(word, sizeof(u32), 1);- }-- (void)thread->join();- EXPECT(result.load() == static_cast<int>(Core::AtomicWaitResult::Woken));-}--TEST_CASE(notify_wakes_an_eight_byte_waiter)-{- auto buffer = make_word_buffer();- IGNORE_USE_IN_ESCAPING_LAMBDA auto* word = buffer.data<u64>();- *word = 0x0000000100000042ULL;-- IGNORE_USE_IN_ESCAPING_LAMBDA AK::Atomic<bool> waiter_ready { false };- IGNORE_USE_IN_ESCAPING_LAMBDA AK::Atomic<int> result { -1 };-- auto thread = Threading::Thread::construct("FutexWaiter64"sv, [&]() {- waiter_ready.store(true);- // The value never changes — so only a real notify (not a value change) can wake this 8-byte waiter. Under the- // old poll fallback, this hangs to the timeout — since polling only ever observes value changes.- auto wait_result = Core::atomic_wait(word, 0x0000000100000042ULL, sizeof(u64), AK::Duration::from_milliseconds(5000));- result.store(static_cast<int>(wait_result));- return 0;- });- thread->start();-- while (!waiter_ready.load())- (void)Core::System::sleep_ms(1);-- size_t max_woken = 0;- for (int i = 0; i < 200 && result.load() == -1; ++i) {- (void)Core::System::sleep_ms(5);- auto woken = Core::atomic_notify(word, sizeof(u64), 1);- if (woken > max_woken)- max_woken = woken;- }-- (void)thread->join();- EXPECT(result.load() == static_cast<int>(Core::AtomicWaitResult::Woken));- // An 8-byte notify now reports the woken count accurately (the poll fallback always returned 0).- EXPECT(max_woken == 1u);-}--TEST_CASE(notify_from_a_four_byte_view_wakes_an_eight_byte_waiter)-{- auto buffer = make_word_buffer();- IGNORE_USE_IN_ESCAPING_LAMBDA auto* word = buffer.data<u64>();- *word = 0x0000000100000042ULL;-- IGNORE_USE_IN_ESCAPING_LAMBDA AK::Atomic<bool> waiter_ready { false };- IGNORE_USE_IN_ESCAPING_LAMBDA AK::Atomic<int> result { -1 };-- // An 8-byte (BigInt64) waiter and a 4-byte (Int32) notify at the same address are one WaiterList — so, the notify- // must wake the waiter. Keying the kernel wait/wake by element size (as os_sync does natively) rejects this- // mixed-size pair with EINVAL, and the waiter never wakes — unless both normalize to the low 32-bit half.- auto thread = Threading::Thread::construct("FutexWaiterMixed64"sv, [&]() {- waiter_ready.store(true);- auto wait_result = Core::atomic_wait(word, 0x0000000100000042ULL, sizeof(u64), AK::Duration::from_milliseconds(5000));- result.store(static_cast<int>(wait_result));- return 0;- });- thread->start();-- while (!waiter_ready.load())- (void)Core::System::sleep_ms(1);-- for (int i = 0; i < 200 && result.load() == -1; ++i) {- (void)Core::System::sleep_ms(5);- Core::atomic_notify(word, sizeof(u32), 1);- }-- (void)thread->join();- EXPECT(result.load() == static_cast<int>(Core::AtomicWaitResult::Woken));-}--TEST_CASE(notify_from_an_eight_byte_view_wakes_a_four_byte_waiter)-{- auto buffer = make_word_buffer();- IGNORE_USE_IN_ESCAPING_LAMBDA auto* word = buffer.data<u64>();- *word = 0x0000000100000042ULL;-- IGNORE_USE_IN_ESCAPING_LAMBDA AK::Atomic<bool> waiter_ready { false };- IGNORE_USE_IN_ESCAPING_LAMBDA AK::Atomic<int> result { -1 };-- // The mirror of the above: A 4-byte waiter (on the low half, value 0x42) must be woken by an 8-byte notify.- auto thread = Threading::Thread::construct("FutexWaiterMixed32"sv, [&]() {- waiter_ready.store(true);- auto wait_result = Core::atomic_wait(word, 0x42, sizeof(u32), AK::Duration::from_milliseconds(5000));- result.store(static_cast<int>(wait_result));- return 0;- });- thread->start();-- while (!waiter_ready.load())- (void)Core::System::sleep_ms(1);-- for (int i = 0; i < 200 && result.load() == -1; ++i) {- (void)Core::System::sleep_ms(5);- Core::atomic_notify(word, sizeof(u64), 1);- }-- (void)thread->join();- EXPECT(result.load() == static_cast<int>(Core::AtomicWaitResult::Woken));-}diff --git a/Tests/LibJS/TestVMThreads.cpp b/Tests/LibJS/TestVMThreads.cppindex 1c314d30ea9..62c5137c506 100644--- a/Tests/LibJS/TestVMThreads.cpp+++ b/Tests/LibJS/TestVMThreads.cpp@@ -405,8 +405,9 @@ public:index);while (word(STARTED_COUNT_WORD).load() == started)MUST(Core::System::sleep_ms(1));- // NB: Nothing tells when the thread got to sleep, and each test needs it to be there.- MUST(Core::System::sleep_ms(50));+ // NB: A wait with a short timeout may be over before this sees it.+ while (!has_result(index) && !m_vms[index].load()->is_waiting_on_shared_memory())+ MUST(Core::System::sleep_ms(1));}// What Atomics.notify() returned, in a VM of its own.@@ -512,7 +513,7 @@ TEST_CASE(a_notify_wakes_a_waiter_of_a_word_that_did_not_change)TEST_CASE(a_word_that_changes_without_a_notify_ends_no_wait){SharedMemoryScripts scripts;- scripts.start_waiter(0, "300"sv);+ scripts.start_waiter(0, "30"sv);scripts.word(WAIT_WORD).store(1);EXPECT_EQ(scripts.wait_for_result(0), RESULT_TIMED_OUT * 256 + 1);}diff --git a/Tests/LibWeb/Text/expected/Workers/worker-atomics-waiters.txt b/Tests/LibWeb/Text/expected/Workers/worker-atomics-waiters.txtnew file mode 100644index 00000000000..ee4849ee5bd--- /dev/null+++ b/Tests/LibWeb/Text/expected/Workers/worker-atomics-waiters.txt@@ -0,0 +1,13 @@+notify of 0: 0+notify of another word: 0+notify of 1 woke at most 1: true+all woken once: true+notify with nobody left: 0+all ok: true+timeout of 20: timed-out, waited long enough: true+timeout of 0: timed-out+notify after the timeouts: 0+other value: not-equal+woken after the first waiter was terminated: 1 2+notify woke all 40: 40+all ok: truediff --git a/Tests/LibWeb/Text/input/Workers/worker-atomics-waiters.html b/Tests/LibWeb/Text/input/Workers/worker-atomics-waiters.htmlnew file mode 100644index 00000000000..5cd6212ea52--- /dev/null+++ b/Tests/LibWeb/Text/input/Workers/worker-atomics-waiters.html@@ -0,0 +1,126 @@+<!DOCTYPE html>+<script src="../include.js"></script>+<script>+ const WAITER = `+ self.onmessage = ({ data: { memory, index, expected, timeout, word } }) => {+ const words = new Int32Array(memory);+ const started = performance.now();+ Atomics.add(words, 1, 1);+ const result = Atomics.wait(words, word, expected, timeout);+ const position = Atomics.add(words, 2, 1);+ self.postMessage({ index, result, position, elapsed: performance.now() - started });+ };+ `;+ const script = URL.createObjectURL(new Blob([WAITER], { type: "text/javascript" }));++ const memory = new SharedArrayBuffer(64);+ const words = new Int32Array(memory);+ const WORD = 0;++ function startWaiter(results, index, { timeout = Infinity, expected = 0, word = WORD } = {}) {+ const worker = new Worker(script);+ worker.onmessage = ({ data }) => results.push(data);+ worker.postMessage({ memory, index, expected, timeout, word });+ return worker;+ }++ // NB: The counter goes up just before the wait, and nothing tells when a worker is asleep. So the tests below notify+ // until the waiters they expect woke, and check what the notifies add up to. The order of the wakes is tested in+ // Tests/LibJS/TestVMThreads.cpp, which can tell when a waiter is asleep.+ async function waitForStarted(count) {+ await waitForCondition(() => Atomics.load(words, 1) >= count, 5000, 1);+ }++ // Notifies `count` waiters at a time until `isDone()`, and returns what the notifies woke in all, and at most at once.+ async function notifyUntil(isDone, count) {+ let total = 0;+ let most = 0;+ while (!isDone()) {+ const woken = Atomics.notify(words, WORD, count);+ total += woken;+ most = Math.max(most, woken);+ await timeout(1);+ }+ return { total, most };+ }++ function reset() {+ Atomics.store(words, 1, 0);+ Atomics.store(words, 2, 0);+ }++ async function notifyCounts() {+ reset();+ const results = [];+ const workers = [];+ for (let index = 0; index < 4; ++index) workers.push(startWaiter(results, index));+ await waitForStarted(4);++ println(`notify of 0: ${Atomics.notify(words, WORD, 0)}`);+ println(`notify of another word: ${Atomics.notify(words, WORD + 3, 4)}`);+ const ones = await notifyUntil(() => results.length >= 2, 1);+ println(`notify of 1 woke at most 1: ${ones.most === 1}`);+ const rest = await notifyUntil(() => results.length === 4, 5);+ println(`all woken once: ${ones.total + rest.total === 4 && new Set(results.map(result => result.index)).size === 4}`);+ println(`notify with nobody left: ${Atomics.notify(words, WORD, 1)}`);+ println(`all ok: ${results.every(result => result.result === "ok")}`);+ workers.forEach(worker => worker.terminate());+ }++ async function timeouts() {+ reset();+ const results = [];+ const workers = [startWaiter(results, 0, { timeout: 20 }), startWaiter(results, 1, { timeout: 0 })];+ await waitForCondition(() => results.length === 2, 5000, 1);+ results.sort((a, b) => a.index - b.index);+ println(`timeout of 20: ${results[0].result}, waited long enough: ${results[0].elapsed >= 19}`);+ println(`timeout of 0: ${results[1].result}`);+ println(`notify after the timeouts: ${Atomics.notify(words, WORD, 2)}`);+ workers.forEach(worker => worker.terminate());+ }++ async function notEqual() {+ reset();+ const results = [];+ const worker = startWaiter(results, 0, { expected: 1 });+ await waitForCondition(() => results.length === 1, 5000, 1);+ println(`other value: ${results[0].result}`);+ worker.terminate();+ }++ // NB: A notify may still wake the terminated worker until its interrupt arrives.+ async function terminatedWaitersLeaveOthersWaiting() {+ reset();+ const results = [];+ const workers = [];+ for (let index = 0; index < 3; ++index) workers.push(startWaiter(results, index));+ await waitForStarted(3);+ workers[0].terminate();+ const others = () => results.filter(result => result.index !== 0);+ await notifyUntil(() => others().length === 2, 1);+ println(`woken after the first waiter was terminated: ${others().map(result => result.index).sort().join(" ")}`);+ workers.forEach(worker => worker.terminate());+ }++ // NB: More agents than a word of wake bits could tell apart.+ async function manyWaiters() {+ reset();+ const COUNT = 40;+ const results = [];+ const workers = [];+ for (let index = 0; index < COUNT; ++index) workers.push(startWaiter(results, index));+ await waitForStarted(COUNT);+ const all = await notifyUntil(() => results.length === COUNT, Infinity);+ println(`notify woke all ${COUNT}: ${all.total}`);+ println(`all ok: ${results.every(result => result.result === "ok")}`);+ workers.forEach(worker => worker.terminate());+ }++ promiseTest(async () => {+ await notifyCounts();+ await timeouts();+ await notEqual();+ await terminatedWaitersLeaveOthersWaiting();+ await manyWaiters();+ });+</script>diff --git a/Tests/LibWeb/Text/input/Workers/worker-atomics-waiters.html.headers b/Tests/LibWeb/Text/input/Workers/worker-atomics-waiters.html.headersnew file mode 100644index 00000000000..63b60e490f4--- /dev/null+++ b/Tests/LibWeb/Text/input/Workers/worker-atomics-waiters.html.headers@@ -0,0 +1,2 @@+Cross-Origin-Opener-Policy: same-origin+Cross-Origin-Embedder-Policy: require-corp