Truly independent web browser
LibJS+LibWeb: Implement Atomics.waitAsync
sideshowbarker6e8c67a2758d
diff --git a/AK/Rust/src/waiter_list.rs b/AK/Rust/src/waiter_list.rsindex 7827830a224..b02832a7345 100644--- a/AK/Rust/src/waiter_list.rs+++ b/AK/Rust/src/waiter_list.rs@@ -13,9 +13,8 @@//! 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.+//! Blocking and asynchronous waits share the list, so notifications select both kinds in their registration order.+//! Asynchronous completions run after releasing the lock, and can register or notify another wait.use core::sync::atomic::{AtomicBool, AtomicU32, AtomicU64, Ordering};use core::time::Duration;@@ -83,7 +82,9 @@ impl AgentWaiter {/// 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))+ lists()+ .iter()+ .any(|waiting| matches!(&waiting.waiter, Waiter::Blocking(waiter) if Arc::ptr_eq(waiter, self)))}/// Ends the wait of this agent with AtomicWaitResult::Interrupted, and every later one at once. Any thread may call@@ -98,7 +99,24 @@ impl AgentWaiter {struct Waiting {address: usize,- waiter: Arc<AgentWaiter>,+ waiter: Waiter,+}++enum Waiter {+ Blocking(Arc<AgentWaiter>),+ Async(Arc<AsyncWaiter>),+}++pub struct AsyncWaiter {+ completion: Box<dyn Fn(AtomicWaitResult) + Send + Sync>,+}++impl AsyncWaiter {+ pub fn new(completion: impl Fn(AtomicWaitResult) + Send + Sync + 'static) -> Arc<Self> {+ Arc::new(Self {+ completion: Box::new(completion),+ })+ }}type Lists = VecDeque<Waiting>;@@ -109,7 +127,7 @@ fn lists() -> MutexGuard<'static, Lists> {}fn remove(lists: &mut Lists, waiter: &Arc<AgentWaiter>) {- lists.retain(|waiting| !Arc::ptr_eq(&waiting.waiter, waiter));+ lists.retain(|waiting| !matches!(&waiting.waiter, Waiter::Blocking(other) if Arc::ptr_eq(other, waiter)));}/// Puts `waiter` on the list of the word unless it holds something else than `expected`, and sleeps until a notify takes@@ -136,7 +154,7 @@ pub fn atomic_wait(waiter.was_notified.store(false, Ordering::Relaxed);lists.push_back(Waiting {address,- waiter: Arc::clone(waiter),+ waiter: Waiter::Blocking(Arc::clone(waiter)),});// NB: The condition variable can wake for no reason, so only what the wake left behind counts. A notify that came@@ -170,26 +188,74 @@ pub fn atomic_wait(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- });+ let mut asynchronous = Vec::new();+ {+ let mut lists = lists();+ lists.retain(|waiting| {+ if waiting.address != address {+ return true;+ }+ if let Waiter::Blocking(waiter) = &waiting.waiter+ && waiter.is_interrupted()+ {+ return false;+ }+ if count == max_count {+ return true;+ }+ count += 1;+ match &waiting.waiter {+ Waiter::Blocking(waiter) => {+ waiter.was_notified.store(true, Ordering::Relaxed);+ waiter.condition.notify_one();+ }+ Waiter::Async(waiter) => asynchronous.push(Arc::clone(waiter)),+ }+ false+ });+ }+ for waiter in asynchronous {+ (waiter.completion)(AtomicWaitResult::Woken);+ }count}+/// Compares and registers under the same lock as synchronous waits and notifications.+/// None means the waiter was registered; Some is an immediate result.+pub fn atomic_wait_async(+ word: WaitWord<'_>,+ expected: u64,+ immediate_timeout: bool,+ waiter: &Arc<AsyncWaiter>,+) -> Option<AtomicWaitResult> {+ let mut lists = lists();+ if !word.equals(expected) {+ return Some(AtomicWaitResult::NotEqual);+ }+ if immediate_timeout {+ return Some(AtomicWaitResult::TimedOut);+ }+ lists.push_back(Waiting {+ address: word.address(),+ waiter: Waiter::Async(Arc::clone(waiter)),+ });+ None+}++/// Removes a registration if a notification has not already removed it.+pub fn cancel_async_waiter(waiter: &Arc<AsyncWaiter>) -> bool {+ let mut lists = lists();+ let old_length = lists.len();+ lists.retain(|waiting| !matches!(&waiting.waiter, Waiter::Async(other) if Arc::ptr_eq(other, waiter)));+ lists.len() != old_length+}++pub fn timeout_async_waiter(waiter: &Arc<AsyncWaiter>) {+ if cancel_async_waiter(waiter) {+ (waiter.completion)(AtomicWaitResult::TimedOut);+ }+}+#[cfg(test)]mod tests {use super::*;@@ -213,6 +279,86 @@ mod tests {}}+ #[test]+ fn asynchronous_waits_compare_before_testing_zero_timeout() {+ let word = AtomicU32::new(1);+ let waiter = AsyncWaiter::new(|_| panic!("an immediate result must not dispatch"));+ assert_eq!(+ atomic_wait_async(WaitWord::Word32(&word), 0, true, &waiter),+ Some(AtomicWaitResult::NotEqual)+ );+ assert_eq!(+ atomic_wait_async(WaitWord::Word32(&word), 1, true, &waiter),+ Some(AtomicWaitResult::TimedOut)+ );+ assert_eq!(atomic_notify(&word, usize::MAX), 0);+ }++ #[test]+ fn blocking_and_asynchronous_waits_share_fifo_order() {+ let word = AtomicU32::new(0);+ let results = Arc::new(Mutex::new(Vec::new()));+ let first_results = Arc::clone(&results);+ let first = AsyncWaiter::new(move |result| first_results.lock().unwrap().push((1, result)));+ assert_eq!(atomic_wait_async(WaitWord::Word32(&word), 0, false, &first), None);+ std::thread::scope(|scope| {+ let blocking = scope.spawn(|| wait(&word, 0, None, &AgentWaiter::new()));+ wait_for_waiters(&word, 2);+ let last_results = Arc::clone(&results);+ let last = AsyncWaiter::new(move |result| last_results.lock().unwrap().push((3, result)));+ assert_eq!(atomic_wait_async(WaitWord::Word32(&word), 0, false, &last), None);+ assert_eq!(atomic_notify(&word, 1), 1);+ assert_eq!(*results.lock().unwrap(), vec![(1, AtomicWaitResult::Woken)]);+ assert_eq!(atomic_notify(&word, 1), 1);+ assert_eq!(blocking.join().unwrap(), AtomicWaitResult::Woken);+ assert_eq!(results.lock().unwrap().len(), 1);+ timeout_async_waiter(&last);+ assert_eq!(+ *results.lock().unwrap(),+ vec![(1, AtomicWaitResult::Woken), (3, AtomicWaitResult::TimedOut)]+ );+ assert_eq!(atomic_notify(&word, usize::MAX), 0);+ });+ }++ #[test]+ fn asynchronous_notification_and_timeout_complete_once() {+ for _ in 0..50 {+ let word = Arc::new(AtomicU32::new(0));+ let completions = Arc::new(Mutex::new(Vec::new()));+ let results = Arc::clone(&completions);+ let waiter = AsyncWaiter::new(move |result| results.lock().unwrap().push(result));+ assert_eq!(atomic_wait_async(WaitWord::Word32(&word), 0, false, &waiter), None);+ let barrier = Arc::new(std::sync::Barrier::new(2));+ let notifier_barrier = Arc::clone(&barrier);+ let notifier_word = Arc::clone(&word);+ let notifier = std::thread::spawn(move || {+ notifier_barrier.wait();+ atomic_notify(¬ifier_word, 1)+ });+ barrier.wait();+ timeout_async_waiter(&waiter);+ let notified = notifier.join().unwrap();+ let expected = if notified == 1 {+ AtomicWaitResult::Woken+ } else {+ AtomicWaitResult::TimedOut+ };+ assert_eq!(*completions.lock().unwrap(), [expected]);+ assert_eq!(waiters_of(&word), 0);+ }+ }++ #[test]+ fn cancellation_removes_waiters_without_resolving_them() {+ let word = AtomicU32::new(0);+ let waiter = AsyncWaiter::new(|_| panic!("a canceled wait must not dispatch"));+ assert_eq!(atomic_wait_async(WaitWord::Word32(&word), 0, false, &waiter), None);+ assert!(cancel_async_waiter(&waiter));+ timeout_async_waiter(&waiter);+ assert_eq!(atomic_notify(&word, usize::MAX), 0);+ }+#[test]fn notifies_wake_waiters_of_a_word_that_did_not_change() {let word = AtomicU32::new(0);@@ -347,7 +493,7 @@ mod tests {for waiter in [&interrupted_agent, &waiting_agent] {held_lists.push_back(Waiting {address,- waiter: Arc::clone(waiter),+ waiter: Waiter::Blocking(Arc::clone(waiter)),});}interrupted_agent.is_interrupted.store(true, Ordering::SeqCst);diff --git a/Libraries/LibJS/Runtime/VM.cpp b/Libraries/LibJS/Runtime/VM.cppindex 3973b3d08e8..2cfd5e4cab8 100644--- a/Libraries/LibJS/Runtime/VM.cpp+++ b/Libraries/LibJS/Runtime/VM.cpp@@ -584,6 +584,59 @@ void VM::set_source_text_syntaxes(StackFrameSyntax stack_frames, NativeFunctionSjs_vm_set_source_text_syntaxes(to_underlying(stack_frames), to_underlying(native_functions));}+void VM::set_async_wait_hooks(AsyncWaitHooks hooks)+{+ JSAsyncWaitHooks abi_hooks {};+ abi_hooks.data = new AsyncWaitHooks(hooks);+ abi_hooks.wake = [](void* data, JSAsyncWaitQueue const* queue) {+ auto& hooks = *static_cast<AsyncWaitHooks*>(data);+ hooks.wake(hooks.data, reinterpret_cast<AsyncWaitQueue const*>(queue));+ };+ abi_hooks.destroy = [](void* data) {+ auto* hooks = static_cast<AsyncWaitHooks*>(data);+ hooks->destroy(hooks->data);+ delete hooks;+ };+ abi_hooks.enqueue_resolution = [](void* data, JSVM*, u64 id, JSRealm* realm) {+ auto& hooks = *static_cast<AsyncWaitHooks*>(data);+ hooks.enqueue_resolution(hooks.data, id, *reinterpret_cast<Realm*>(realm));+ };+ abi_hooks.schedule_timeout = [](void* data, JSVM*, u64 id, JSRealm* realm, double milliseconds) {+ auto& hooks = *static_cast<AsyncWaitHooks*>(data);+ return hooks.schedule_timeout(hooks.data, id, *reinterpret_cast<Realm*>(realm), milliseconds);+ };+ abi_hooks.cancel_timeout = [](void* data, JSVM*, JSRealm* realm, i32 timer) {+ auto& hooks = *static_cast<AsyncWaitHooks*>(data);+ hooks.cancel_timeout(hooks.data, *reinterpret_cast<Realm*>(realm), timer);+ };+ js_vm_set_async_wait_hooks(vm_abi(*this), &abi_hooks);+}++void VM::dispatch_async_wait_queue(AsyncWaitQueue const* queue)+{+ js_async_wait_queue_dispatch(reinterpret_cast<JSAsyncWaitQueue const*>(queue));+}++void VM::release_async_wait_queue(AsyncWaitQueue const* queue)+{+ js_async_wait_queue_release(reinterpret_cast<JSAsyncWaitQueue const*>(queue));+}++void VM::resolve_async_wait(u64 id)+{+ js_vm_resolve_async_wait(vm_abi(*this), id);+}++void VM::timeout_async_wait(u64 id)+{+ js_vm_timeout_async_wait(vm_abi(*this), id);+}++void VM::async_wait_timer_fired(u64 id)+{+ js_vm_async_wait_timer_fired(vm_abi(*this), id);+}+void VM::set_agent(OwnPtr<Agent> agent){m_agent = move(agent);diff --git a/Libraries/LibJS/Runtime/VM.h b/Libraries/LibJS/Runtime/VM.hindex 77afeb82e7b..8666cf4ef9e 100644--- a/Libraries/LibJS/Runtime/VM.h+++ b/Libraries/LibJS/Runtime/VM.h@@ -56,6 +56,22 @@namespace JS {+struct AsyncWaitQueue;++// wake() receives an owned native queue reference on any thread. Dispatch it on the VM's thread, and release it even+// if dispatch is canceled. destroy() runs on any thread after the final wake() returns; the other callbacks run on+// the VM's thread, while their realm is live.+struct AsyncWaitHooks {+ AK_ALLOC_WITH_KMALLOC;++ void* data;+ void (*wake)(void*, AsyncWaitQueue const*);+ void (*destroy)(void*);+ void (*enqueue_resolution)(void*, u64, Realm&);+ i32 (*schedule_timeout)(void*, u64, Realm&, double);+ void (*cancel_timeout)(void*, Realm&, i32);+};+enum class HandledByHost {Handled,Unhandled,@@ -392,6 +408,12 @@ public:Function<void(Object const&, PropertyKey const&)> on_unimplemented_property_access;void set_agent(OwnPtr<Agent>);+ void set_async_wait_hooks(AsyncWaitHooks);+ static void dispatch_async_wait_queue(AsyncWaitQueue const*);+ static void release_async_wait_queue(AsyncWaitQueue const*);+ void resolve_async_wait(u64 id);+ void timeout_async_wait(u64 id);+ void async_wait_timer_fired(u64 id);// How Error.prototype.stack writes its frames and how Function.prototype.toString writes a built-in function: the// embedder's choice, since scripts read both to tell engines apart. This goes for all the VMs of the process, on anydiff --git a/Libraries/LibJS/Rust/src/contrib/test262/agent_object.rs b/Libraries/LibJS/Rust/src/contrib/test262/agent_object.rsindex 9cd00d7d99d..054b2b65f8b 100644--- a/Libraries/LibJS/Rust/src/contrib/test262/agent_object.rs+++ b/Libraries/LibJS/Rust/src/contrib/test262/agent_object.rs@@ -207,6 +207,8 @@ impl AgentObject {#[allow(clippy::unnecessary_wraps, reason = "native functions return a completion")]fn leaving(_vm: &Vm) -> ThrowCompletionOr<Value> {+ #[cfg(unix)]+ agents::leave();Ok(Value::UNDEFINED)}}diff --git a/Libraries/LibJS/Rust/src/contrib/test262/agents.rs b/Libraries/LibJS/Rust/src/contrib/test262/agents.rsindex 120c64a04c5..5c249225edc 100644--- a/Libraries/LibJS/Rust/src/contrib/test262/agents.rs+++ b/Libraries/LibJS/Rust/src/contrib/test262/agents.rs@@ -70,6 +70,7 @@ pub fn role() -> AgentRole {pub type AgentEntry = fn(&[u8]);thread_local! {+ static LEAVING: core::cell::Cell<bool> = const { core::cell::Cell::new(false) };static AGENT_ENTRY: core::cell::Cell<Option<AgentEntry>> = const { core::cell::Cell::new(None) };static RUNNING_AGENTS: RefCell<RunningAgents> = RefCell::new(RunningAgents::default());static THIS_AGENT: RefCell<Option<Arc<Agent>>> = const { RefCell::new(None) };@@ -295,3 +296,10 @@ pub fn report_uncaught_exception(name: &str, message: &str) {message: message.to_string(),});}++pub fn leave() {+ LEAVING.set(true);+}+pub fn is_leaving() -> bool {+ LEAVING.get()+}diff --git a/Libraries/LibJS/Rust/src/contrib/test262/global_object.rs b/Libraries/LibJS/Rust/src/contrib/test262/global_object.rsindex a81064192b3..4b9e51f1960 100644--- a/Libraries/LibJS/Rust/src/contrib/test262/global_object.rs+++ b/Libraries/LibJS/Rust/src/contrib/test262/global_object.rs@@ -5,6 +5,7 @@*/use core::cell::Cell;+use std::time::Duration;use ak::Utf16FlyString;use libjs_runtime_macros::Trace;@@ -13,11 +14,14 @@ use libjs_runtime_macros::Trace;use crate::contrib::test262::agents::{self, AgentRole};use crate::contrib::test262::dollar_262_object::Dollar262Object;use crate::gc::class::{GcCell, cast_ref, define_cell};+use crate::gc::heap_function::create_heap_function;use crate::interpreter::vm::Vm;use crate::layout::cell::Gc;use crate::layout::object::Object;use crate::layout::value::Value;+use crate::runtime::abstract_operations::call;use crate::runtime::completion::ThrowCompletionOr;+use crate::runtime::error::ErrorKind;use crate::runtime::global_object::GlobalObject;use crate::runtime::native_function::raw_native;use crate::runtime::object::{ORDINARY_OBJECT_METHODS, allocate_object, define_object_class};@@ -33,6 +37,7 @@ use crate::utf16::Utf16View;pub struct Test262GlobalObject {base: GlobalObject,dollar_262: Cell<Option<Gc<Dollar262Object>>>,+ async_test_complete: Cell<bool>,}define_object_class!(Test262GlobalObject, extends: [GlobalObject, Object], methods: {@@ -47,6 +52,7 @@ impl Test262GlobalObject {allocate_object(vm, |_| Test262GlobalObject {base: GlobalObject::new(vm, Self::CLASS, realm),dollar_262: Cell::new(None),+ async_test_complete: Cell::new(false),})}@@ -78,12 +84,40 @@ impl Test262GlobalObject {Value::from_object(dollar_262),attr,);+ object.define_native_function(+ vm,+ realm,+ &PropertyKey::from_utf8("setTimeout"),+ raw_native!(Test262GlobalObject::set_timeout),+ 2,+ attr,+ None,+ );}pub fn dollar_262(&self) -> Gc<Dollar262Object> {self.dollar_262.get().expect("the test262 global object has its $262")}+ pub fn async_test_complete(&self) -> bool {+ self.async_test_complete.get()+ }++ fn set_timeout(vm: &Vm) -> ThrowCompletionOr<Value> {+ let callback = vm.argument(0);+ if !callback.is_function() {+ return vm.throw_completion_with_message(+ ErrorKind::TypeError,+ "setTimeout requires a callable callback".to_string(),+ );+ }+ let delay = vm.argument(1).to_number(vm)?.as_f64().max(0.0);+ let delay = Duration::try_from_secs_f64(delay / 1000.0).unwrap_or_default();+ let job = create_heap_function(vm, callback, |vm, &callback| call(vm, callback, Value::UNDEFINED, &[]));+ vm.enqueue_timeout_job(job, delay);+ Ok(Value::UNDEFINED)+ }+fn print(vm: &Vm) -> ThrowCompletionOr<Value> {let string = vm.argument(0).to_utf16_string(vm)?;// NB: What a test prints is its result, which agents have no say in.@@ -91,7 +125,14 @@ impl Test262GlobalObject {if agents::role() == AgentRole::Agent {return Ok(Value::UNDEFINED);}- outln(&Utf16View::of_string(&string).to_wtf8());+ let bytes = Utf16View::of_string(&string).to_wtf8();+ if bytes.starts_with(b"Test262:AsyncTestComplete") || bytes.starts_with(b"Test262:AsyncTestFailure") {+ let realm = vm.current_realm().expect("print has a current realm");+ let global_object = realm.global_object();+ let global: &Test262GlobalObject = cast_ref(&*global_object);+ global.async_test_complete.set(true);+ }+ outln(&bytes);Ok(Value::UNDEFINED)}}diff --git a/Libraries/LibJS/Rust/src/embedding/async_wait.rs b/Libraries/LibJS/Rust/src/embedding/async_wait.rsnew file mode 100644index 00000000000..43e33e40ddc--- /dev/null+++ b/Libraries/LibJS/Rust/src/embedding/async_wait.rs@@ -0,0 +1,147 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++use core::ffi::c_void;+use std::sync::{Arc, PoisonError};++use crate::embedding::abi_types::{JSRealm, cell_into_abi, vm_from_abi};+use crate::interpreter::vm::Vm;+use crate::layout::cell::Gc;+use crate::layout::host_class::JSVM;+use crate::runtime::async_wait::AsyncWaitAgent;+use crate::runtime::realm::Realm;++pub struct JSAsyncWaitQueue {+ _private: [u8; 0],+}++/// Scheduling for asynchronous atomic waits. wake() can run on any thread and receives an owned queue reference.+/// It must arrange dispatch on the owning thread, then release that reference, including if dispatch is canceled.+/// The other scheduling callbacks run on the VM's thread. destroy() can run on any thread after the last wake returns.+#[repr(C)]+#[derive(Clone, Copy)]+pub struct JSAsyncWaitHooks {+ pub data: *mut c_void,+ pub wake: unsafe extern "C" fn(*mut c_void, *const JSAsyncWaitQueue),+ pub destroy: unsafe extern "C" fn(*mut c_void),+ pub enqueue_resolution: unsafe extern "C" fn(*mut c_void, *mut JSVM, u64, *mut JSRealm),+ pub schedule_timeout: unsafe extern "C" fn(*mut c_void, *mut JSVM, u64, *mut JSRealm, f64) -> i32,+ pub cancel_timeout: unsafe extern "C" fn(*mut c_void, *mut JSVM, *mut JSRealm, i32),+}++pub(crate) struct AsyncWaitHooks(JSAsyncWaitHooks);++// SAFETY: The installer guarantees that wake/destroy and their context can be used from any thread. The runtime+// calls the other hooks only on the VM's thread.+unsafe impl Send for AsyncWaitHooks {}+// SAFETY: As above; concurrent wake calls are permitted by the installation contract.+unsafe impl Sync for AsyncWaitHooks {}++impl Drop for AsyncWaitHooks {+ fn drop(&mut self) {+ // SAFETY: The last owner releases the context after every callback has returned.+ unsafe { (self.0.destroy)(self.0.data) };+ }+}++impl AsyncWaitHooks {+ pub(crate) fn wake(&self, agent: Arc<AsyncWaitAgent>) {+ // SAFETY: The host owns this retained reference and must release it after dispatch or cancellation.+ unsafe { (self.0.wake)(self.0.data, Arc::into_raw(agent).cast()) };+ }++ pub(crate) fn enqueue_resolution(&self, vm: &Vm, id: u64, realm: Gc<Realm>) {+ // SAFETY: The callback runs on the VM's thread and borrows a live realm.+ unsafe {+ (self.0.enqueue_resolution)(+ self.0.data,+ core::ptr::from_ref(vm).cast_mut().cast(),+ id,+ cell_into_abi(realm),+ );+ }+ }++ pub(crate) fn schedule_timeout(&self, vm: &Vm, id: u64, realm: Gc<Realm>, milliseconds: f64) -> i32 {+ // SAFETY: The callback runs on the VM's thread and borrows a live realm.+ unsafe {+ (self.0.schedule_timeout)(+ self.0.data,+ core::ptr::from_ref(vm).cast_mut().cast(),+ id,+ cell_into_abi(realm),+ milliseconds,+ )+ }+ }+ pub(crate) fn cancel_timeout(&self, vm: &Vm, realm: Gc<Realm>, timer: i32) {+ // SAFETY: Only the owning VM cancels its timer, while the realm is still live.+ unsafe {+ (self.0.cancel_timeout)(+ self.0.data,+ core::ptr::from_ref(vm).cast_mut().cast(),+ cell_into_abi(realm),+ timer,+ );+ }+ }+}++/// # Safety+/// vm must be live on this thread. hooks must be readable and satisfy JSAsyncWaitHooks' threading contract.+/// Ownership of hooks.data transfers to the VM; the host must keep any realm it queues alive until its callback runs.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn js_vm_set_async_wait_hooks(vm: *mut JSVM, hooks: &JSAsyncWaitHooks) {+ // SAFETY: Guaranteed by the caller.+ let vm = unsafe { vm_from_abi(vm) };+ *vm.async_wait_agent()+ .hooks+ .lock()+ .unwrap_or_else(PoisonError::into_inner) = Some(Arc::new(AsyncWaitHooks(*hooks)));+}++/// # Safety+/// queue must be a retained reference passed to wake(), and this must be its owning thread.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn js_async_wait_queue_dispatch(queue: *const JSAsyncWaitQueue) {+ // SAFETY: The caller keeps the queue reference alive throughout this call.+ unsafe { &*queue.cast::<AsyncWaitAgent>() }.dispatch();+}++/// # Safety+/// queue must be an owned reference passed to wake(), and must not be used again.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn js_async_wait_queue_release(queue: *const JSAsyncWaitQueue) {+ // SAFETY: This consumes exactly the reference transferred to wake().+ drop(unsafe { Arc::from_raw(queue.cast::<AsyncWaitAgent>()) });+}++/// # Safety+/// vm must be live on its owning thread.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn js_vm_resolve_async_wait(vm: *mut JSVM, id: u64) {+ // SAFETY: Guaranteed by the caller.+ unsafe { vm_from_abi(vm) }.resolve_async_wait(id);+}++/// # Safety+/// vm must be live on its owning thread.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn js_vm_timeout_async_wait(vm: *mut JSVM, id: u64) {+ // SAFETY: Guaranteed by the caller.+ unsafe { vm_from_abi(vm) }.timeout_async_wait(id);+}++/// # Safety+/// vm must be live on its owning thread. Call this when the timer fires, before queuing its timeout job.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn js_vm_async_wait_timer_fired(vm: *mut JSVM, id: u64) {+ // SAFETY: Guaranteed by the caller.+ let vm = unsafe { vm_from_abi(vm) };+ if let Some(wait) = vm.async_waits().borrow_mut(vm).iter_mut().find(|wait| wait.id == id) {+ wait.host_timer = None;+ }+}diff --git a/Libraries/LibJS/Rust/src/embedding/mod.rs b/Libraries/LibJS/Rust/src/embedding/mod.rsindex d7d2e760de0..e94d1bf64bb 100644--- a/Libraries/LibJS/Rust/src/embedding/mod.rs+++ b/Libraries/LibJS/Rust/src/embedding/mod.rs@@ -22,6 +22,7 @@pub mod abi_types;pub mod array;pub mod array_buffer;+pub mod async_wait;pub mod bigint;pub mod collections;pub mod compile;diff --git a/Libraries/LibJS/Rust/src/interpreter/run.rs b/Libraries/LibJS/Rust/src/interpreter/run.rsindex 7aa6b1d159e..d3249b5937f 100644--- a/Libraries/LibJS/Rust/src/interpreter/run.rs+++ b/Libraries/LibJS/Rust/src/interpreter/run.rs@@ -14,6 +14,7 @@ use ak::ScopeGuard;use super::vm::Vm;use crate::bytecode::executable::Executable;+use crate::gc::root::Root;use crate::jit::code::EntryStatus;use crate::layout::cell::Gc;use crate::layout::execution_context::{ExecutionContext, ScriptOrModule};@@ -25,6 +26,7 @@ use crate::runtime::environment::Environment;use crate::runtime::error::ErrorKind;use crate::runtime::error_types::ErrorType;use crate::runtime::native_javascript_backed_function::NativeJavaScriptBackedFunction;+use crate::runtime::promise::Promise;use crate::runtime::source_text_module::SourceTextModule;use crate::script::Script;use libjs_abi::register;@@ -355,17 +357,17 @@ impl Vm {result}- pub fn run_module(&self, module: Gc<SourceTextModule>) -> ThrowCompletionOr<Value> {+ pub fn run_module(&self, module: Gc<SourceTextModule>) -> ThrowCompletionOr<Gc<Promise>> {// FIXME: This is not a entry point as defined in the spec, but is convenient.// To avoid work we use link_and_eval_module however that can already be// dangerous if the vm loaded other modules.- self.link_and_eval_module(module.upcast())?;+ let evaluation = Root::new(self, self.link_and_eval_module(module.upcast())?);self.run_queued_promise_jobs();self.run_queued_finalization_registry_cleanup_jobs();- Ok(Value::UNDEFINED)+ Ok(evaluation.value())}/// Enters a frame for a call of `callee_function` that the interpreter runs inline, as Return leaves it: thediff --git a/Libraries/LibJS/Rust/src/interpreter/vm.rs b/Libraries/LibJS/Rust/src/interpreter/vm.rsindex 3d0ab9c78c0..2a943af64e5 100644--- a/Libraries/LibJS/Rust/src/interpreter/vm.rs+++ b/Libraries/LibJS/Rust/src/interpreter/vm.rs@@ -37,7 +37,7 @@ use crate::gc::foreign::ForeignCellSlot;use crate::gc::gc_ref_cell::GcRefCell;use crate::gc::heap::Heap;use crate::gc::heap_function::HeapFunction;-use crate::gc::root::{MarkedVec, RootSet};+use crate::gc::root::{MarkedVec, Root, RootSet};use crate::gc::sweep::Sweep;use crate::gc::visitor::{Trace, Visitor};use crate::gc::weak_container::WeakContainer;@@ -272,13 +272,16 @@ pub(crate) fn default_host_system_utc_epoch_nanoseconds(_: &Vm, _: &Object) -> Snanoseconds.clamp(NANOSECONDS_MIN_INSTANT.clone(), NANOSECONDS_MAX_INSTANT.clone())}-/// The VM's queues of promise jobs and finalization registry cleanup jobs, in a cell the VM roots.+/// The VM's promise jobs, cleanup jobs, standalone timer tasks, and pending async waits, in a cell the VM roots.#[repr(C)]#[derive(Trace)]pub struct JobQueues {header: CellHeader,promise_jobs: GcRefCell<VecDeque<Gc<HeapFunction>>>,finalization_registry_cleanup_jobs: GcRefCell<Vec<Gc<FinalizationRegistry>>>,+ // Ephemerons must be visited during marking, not by the VM's root-gathering visitor.+ async_waits: GcRefCell<Vec<crate::runtime::async_wait::PendingWait>>,+ timeout_jobs: GcRefCell<Vec<crate::runtime::async_wait::TimeoutJob>>,}define_cell!(JobQueues, Other);@@ -523,6 +526,8 @@ pub struct Vm {interrupt_requested: AtomicBool,/// This agent's node in the WaiterLists, which Atomics.wait() and memory.atomic.wait sleep on.agent_waiter: Arc<AgentWaiter>,+ pub(crate) async_wait_agent: std::sync::OnceLock<Arc<crate::runtime::async_wait::AsyncWaitAgent>>,+ pub(crate) next_async_wait_id: Cell<u64>,/// 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.@@ -703,6 +708,8 @@ impl Vm {jit_native_stack_limit: AtomicUsize::new(0),interrupt_requested: AtomicBool::new(false),agent_waiter: AgentWaiter::new(),+ async_wait_agent: std::sync::OnceLock::new(),+ next_async_wait_id: Cell::new(1),own_dispatch_tables: VmDispatchTables::new(),wasm_stack_limit_word: Mutex::new(core::ptr::null()),heap: OnceCell::new(),@@ -860,6 +867,8 @@ impl Vm {header: CellHeader::for_class(JobQueues::CLASS),promise_jobs: GcRefCell::new(VecDeque::new()),finalization_registry_cleanup_jobs: GcRefCell::new(Vec::new()),+ async_waits: GcRefCell::new(Vec::new()),+ timeout_jobs: GcRefCell::new(Vec::new()),}));let _ = self.loaded_modules.set(self.heap().allocate(|_| LoadedModules {header: CellHeader::for_class(LoadedModules::CLASS),@@ -922,6 +931,9 @@ impl Vm {word.store(u64::MAX, Ordering::Relaxed);}self.agent_waiter.interrupt();+ if let Some(agent) = self.async_wait_agent.get() {+ agent.wake();+ }}/// This agent's node in the WaiterLists.@@ -1744,6 +1756,26 @@ impl Vm {*self.job_queues.get().expect("the VM allocates its job queues")}+ pub(crate) fn async_waits(&self) -> &GcRefCell<Vec<crate::runtime::async_wait::PendingWait>> {+ &self+ .job_queues+ .get()+ .expect("the VM allocates its job queues")+ .async_waits+ }++ pub(crate) fn timeout_jobs(&self) -> &GcRefCell<Vec<crate::runtime::async_wait::TimeoutJob>> {+ &self+ .job_queues+ .get()+ .expect("the VM allocates its job queues")+ .timeout_jobs+ }++ pub(crate) fn is_running_promise_jobs(&self) -> bool {+ self.running_promise_jobs.get()+ }+pub fn run_executable_depth(&self) -> &Cell<u32> {&self.run_executable_depth}@@ -2245,6 +2277,13 @@ impl Vm {impl Drop for Vm {fn drop(&mut self) {+ if let Some(agent) = self.async_wait_agent.get() {+ agent.close();+ }+ for wait in self.async_waits().borrow().iter() {+ ak::waiter_list::cancel_async_waiter(&wait.waiter);+ }+ self.async_waits().borrow_mut(self).clear();if self.options.become_thread_default_heap {libregex_rust::vm::set_interrupt_flag_of_this_thread(core::ptr::null());}@@ -2282,6 +2321,7 @@ unsafe extern "C" fn sweep(context: *mut c_void) {vm.code_flushing.finish_pass(vm, &sweep);crate::parser::release_idle_reparse_contexts();crate::source_text::park_idle_source_texts();+ vm.remove_dead_async_waits(&sweep);vm.remove_dead_cells_from_weak_containers(&sweep);vm.remove_dead_strings_from_weak_caches(&sweep);vm.remove_dead_cells_from_property_lookup_caches(&sweep);@@ -2500,7 +2540,7 @@ impl Vm {});}- pub fn link_and_eval_module(&self, module: Gc<CyclicModule>) -> ThrowCompletionOr<()> {+ pub fn link_and_eval_module(&self, module: Gc<CyclicModule>) -> ThrowCompletionOr<Gc<Promise>> {let filename = module.filename().to_string();if !filename.is_empty() {let absolute_filename = resolve_module_filename(&lexical_path::absolute_path(".", &filename), "");@@ -2525,20 +2565,17 @@ impl Vm {module.link(self)?;- let evaluated_value = promise_of(module.evaluate(self)?);+ let evaluated_value = Root::new(self, promise_of(module.evaluate(self)?));self.run_queued_promise_jobs();- assert!(self.job_queues().promise_jobs.borrow().is_empty());-- // FIXME: This will break if we start doing promises actually asynchronously.- assert!(evaluated_value.state() != PromiseState::Pending);- if evaluated_value.state() == PromiseState::Rejected {- crate::embedding::completion::log_exception_if_enabled(self, evaluated_value.result());- return Err(Throw::new(evaluated_value.result()));+ if evaluated_value.get().state() == PromiseState::Rejected {+ crate::embedding::completion::log_exception_if_enabled(self, evaluated_value.get().result());+ return Err(Throw::new(evaluated_value.get().result()));}- Ok(())+ // The host owns the tasks that can resume a suspended module, so it also observes the evaluation promise.+ Ok(evaluated_value.value())}// 16.2.1.8 HostLoadImportedModule ( referrer, specifier, hostDefined, payload ), https://tc39.es/ecma262/#sec-HostLoadImportedModulediff --git a/Libraries/LibJS/Rust/src/runtime/array_buffer.rs b/Libraries/LibJS/Rust/src/runtime/array_buffer.rsindex 0ff6d9d0c24..1ff841567b4 100644--- a/Libraries/LibJS/Rust/src/runtime/array_buffer.rs+++ b/Libraries/LibJS/Rust/src/runtime/array_buffer.rs@@ -1421,6 +1421,23 @@ impl ArrayBuffer {waiter_list::atomic_wait(word, expected, timeout, waiter)}+ pub fn atomic_wait_async(+ &self,+ byte_index: usize,+ expected: u64,+ size: usize,+ immediate_timeout: bool,+ waiter: &Arc<waiter_list::AsyncWaiter>,+ ) -> Option<AtomicWaitResult> {+ let data_block = self.data_block.borrow();+ let word = match size {+ 4 => WaitWord::Word32(data_block.atomic_at(byte_index)),+ 8 => WaitWord::Word64(data_block.atomic_at(byte_index)),+ _ => unreachable!("atomic waits require a 4-byte or 8-byte element"),+ };+ waiter_list::atomic_wait_async(word, expected, immediate_timeout, waiter)+ }+/// 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 are on the list of the address of their word.diff --git a/Libraries/LibJS/Rust/src/runtime/async_wait.rs b/Libraries/LibJS/Rust/src/runtime/async_wait.rsnew file mode 100644index 00000000000..4964ccc385a--- /dev/null+++ b/Libraries/LibJS/Rust/src/runtime/async_wait.rs@@ -0,0 +1,422 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++use core::sync::atomic::{AtomicPtr, Ordering};+use std::collections::VecDeque;+use std::sync::{Arc, Condvar, Mutex, PoisonError};+use std::thread::ThreadId;+use std::time::{Duration, Instant};++use ak::waiter_list::{self, AsyncWaiter, AtomicWaitResult};+use libjs_runtime_macros::Trace;++use crate::embedding::async_wait::AsyncWaitHooks;+use crate::gc::heap_function::HeapFunction;+use crate::gc::sweep::Sweep;+use crate::gc::visitor::{Trace, Visitor};+use crate::interpreter::vm::Vm;+use crate::layout::cell::Gc;+use crate::layout::function_object::FunctionObject;+use crate::layout::object::Object;+use crate::layout::value::Value;+use crate::runtime::abstract_operations::call_function_object;+use crate::runtime::array_buffer::ArrayBuffer;+use crate::runtime::completion::{Must, ThrowCompletionOr};+use crate::runtime::primitive_string::PrimitiveString;+use crate::runtime::promise_capability::new_promise_capability;+use crate::runtime::property_key::PropertyKey;+use crate::runtime::realm::Realm;++pub(crate) struct PendingWait {+ pub id: u64,+ pub resolve: Gc<FunctionObject>,+ pub realm: Gc<Realm>,+ pub buffer: Gc<ArrayBuffer>,+ pub waiter: Arc<AsyncWaiter>,+ pub deadline: Option<Instant>,+ pub result: Option<AtomicWaitResult>,+ pub host_timer: Option<i32>,+}++#[derive(Trace)]+pub(crate) struct TimeoutJob {+ #[gc(untraced)]+ pub deadline: Instant,+ pub callback: Gc<HeapFunction>,+}++// SAFETY: The resolver and buffer are reachable while the realm is. The sweep callback removes waits whose realm+// died, before any of their cells can be freed. The native waiter never dereferences a GC pointer.+unsafe impl Trace for PendingWait {+ fn trace(&self, visitor: &mut Visitor) {+ visitor.visit_ephemeron(self.realm, &Value::from_object(self.resolve));+ visitor.visit_ephemeron(self.realm, &Value::from_object(self.buffer));+ }+}++/// Only completion identifiers cross threads. The VM pointer can only be dereferenced on its owning thread, and is+/// cleared on that thread before the VM's heap is destroyed. A queued host callback keeps this record, not the VM.+pub struct AsyncWaitAgent {+ vm: AtomicPtr<Vm>,+ owner: ThreadId,+ ready: Mutex<VecDeque<(u64, AtomicWaitResult)>>,+ changed: Condvar,+ pub(crate) hooks: Mutex<Option<Arc<AsyncWaitHooks>>>,+}++impl AsyncWaitAgent {+ pub(crate) fn new(vm: &Vm) -> Arc<Self> {+ Arc::new(Self {+ vm: AtomicPtr::new(core::ptr::from_ref(vm).cast_mut()),+ owner: std::thread::current().id(),+ ready: Mutex::new(VecDeque::new()),+ changed: Condvar::new(),+ hooks: Mutex::new(None),+ })+ }++ pub(crate) fn host_hooks(&self) -> Option<Arc<AsyncWaitHooks>> {+ self.hooks.lock().unwrap_or_else(PoisonError::into_inner).clone()+ }++ fn complete(self: &Arc<Self>, id: u64, result: AtomicWaitResult) {+ if self.owner == std::thread::current().id() {+ let vm = self.vm.load(Ordering::Acquire);+ if vm.is_null() {+ return;+ }+ // SAFETY: The owner clears this pointer before destroying its VM.+ let vm = unsafe { &*vm };+ {+ let mut pending = vm.async_waits().borrow_mut(vm);+ let Some(wait) = pending.iter_mut().find(|wait| wait.id == id) else {+ return;+ };+ wait.result = Some(result);+ }+ vm.resolve_async_wait(id);+ return;+ }+ self.ready+ .lock()+ .unwrap_or_else(PoisonError::into_inner)+ .push_back((id, result));+ self.changed.notify_all();+ if let Some(hooks) = self.host_hooks() {+ hooks.wake(Arc::clone(self));+ }+ }++ pub fn dispatch(&self) {+ assert_eq!(self.owner, std::thread::current().id());+ let vm = self.vm.load(Ordering::Acquire);+ if vm.is_null() {+ return;+ }+ // SAFETY: Only the owning thread reads the VM, and it clears this pointer before destroying it.+ let vm = unsafe { &*vm };+ loop {+ let Some((id, result)) = self.ready.lock().unwrap_or_else(PoisonError::into_inner).pop_front() else {+ break;+ };+ let realm = {+ let mut pending = vm.async_waits().borrow_mut(vm);+ let Some(wait) = pending.iter_mut().find(|wait| wait.id == id) else {+ continue;+ };+ wait.result = Some(result);+ wait.realm+ };+ // https://tc39.es/ecma262/#sec-notifywaiter+ if let Some(hooks) = self.host_hooks() {+ // 4.a. Perform EnqueueResolveInAgentJob(waiterRecord.[[AgentSignifier]], waiterRecord.[[PromiseCapability]], waiterRecord.[[Result]]).+ hooks.enqueue_resolution(vm, id, realm);+ } else {+ vm.resolve_async_wait(id);+ }+ }+ }++ pub(crate) fn wake(&self) {+ let _ready = self.ready.lock().unwrap_or_else(PoisonError::into_inner);+ self.changed.notify_all();+ }++ pub(crate) fn close(&self) {+ self.vm.store(core::ptr::null_mut(), Ordering::Release);+ self.hooks.lock().unwrap_or_else(PoisonError::into_inner).take();+ self.changed.notify_all();+ }+}++impl Vm {+ pub(crate) fn enqueue_timeout_job(&self, callback: Gc<HeapFunction>, delay: Duration) {+ let now = Instant::now();+ self.timeout_jobs().borrow_mut(self).push(TimeoutJob {+ deadline: now.checked_add(delay).unwrap_or(now),+ callback,+ });+ }++ fn run_ready_timeout_job(&self) -> ThrowCompletionOr<()> {+ let callback = {+ let mut jobs = self.timeout_jobs().borrow_mut(self);+ let Some(index) = jobs+ .iter()+ .enumerate()+ .min_by_key(|(_, job)| job.deadline)+ .map(|(index, _)| index)+ else {+ return Ok(());+ };+ if jobs[index].deadline > Instant::now() {+ return Ok(());+ }+ jobs.remove(index).callback+ };+ HeapFunction::call(callback, self).map(|_| ())+ }++ pub(crate) fn remove_dead_async_waits(&self, sweep: &Sweep<'_>) {+ self.async_waits().borrow_mut_in_sweep(sweep).retain(|wait| {+ if !sweep.is_dead(wait.realm) {+ return true;+ }+ waiter_list::cancel_async_waiter(&wait.waiter);+ false+ });+ }++ pub(crate) fn async_wait_agent(&self) -> &Arc<AsyncWaitAgent> {+ self.async_wait_agent.get_or_init(|| AsyncWaitAgent::new(self))+ }++ pub(crate) fn start_async_wait(+ &self,+ buffer: Gc<ArrayBuffer>,+ byte_index: usize,+ expected: u64,+ element_size: usize,+ timeout: f64,+ ) -> Value {+ let realm = self.current_realm().expect("an atomic wait has a current realm");+ // https://tc39.es/ecma262/#sec-dowait+ // 16.a. Let promiseCapability be ! NewPromiseCapability(%Promise%).+ let capability =+ new_promise_capability(self, Value::from_object(realm.intrinsics().promise_constructor(self))).must();+ // 16.b. Let resultObj be OrdinaryObjectCreate(%Object.prototype%).+ let object = Object::create(self, realm, Some(realm.intrinsics().object_prototype(self).upcast()));+ let agent = Arc::clone(self.async_wait_agent());+ let id = self.next_async_wait_id.get();+ self.next_async_wait_id+ .set(id.checked_add(1).expect("async wait identifiers fit in u64"));+ let weak_agent = Arc::downgrade(&agent);+ let waiter = AsyncWaiter::new(move |result| {+ if let Some(agent) = weak_agent.upgrade() {+ agent.complete(id, result);+ }+ });+ let deadline = Duration::try_from_secs_f64(timeout / 1000.0)+ .ok()+ .and_then(|duration| Instant::now().checked_add(duration));+ self.async_waits().borrow_mut(self).push(PendingWait {+ id,+ resolve: capability.resolve(),+ realm,+ buffer,+ waiter: Arc::clone(&waiter),+ deadline,+ result: None,+ host_timer: None,+ });+ // NB: The shared waiter list combines steps 17-21 and 28. Its lock covers both the value comparison and+ // registration, so a notification cannot pass between them.+ let immediate = buffer.atomic_wait_async(byte_index, expected, element_size, timeout == 0.0, &waiter);+ let value = if let Some(result) = immediate {+ self.async_waits().borrow_mut(self).retain(|wait| wait.id != id);+ Value::from_string(PrimitiveString::create_from_utf8(+ self,+ if result == AtomicWaitResult::NotEqual {+ "not-equal"+ } else {+ "timed-out"+ },+ ))+ } else {+ // 30. Else if timeoutTime is finite, then+ if let Some(deadline) = deadline+ && let Some(hooks) = agent.host_hooks()+ {+ // a. Perform EnqueueAtomicsWaitAsyncTimeoutJob(waiterList, waiterRecord).+ let timer = hooks.schedule_timeout(+ self,+ id,+ realm,+ deadline.saturating_duration_since(Instant::now()).as_secs_f64() * 1000.0,+ );+ if let Some(wait) = self+ .async_waits()+ .borrow_mut(self)+ .iter_mut()+ .find(|wait| wait.id == id)+ {+ wait.host_timer = Some(timer);+ }+ }+ Value::from_object(capability.promise())+ };+ // 33. Perform ! CreateDataPropertyOrThrow(resultObj, "async", true).+ // 34. Perform ! CreateDataPropertyOrThrow(resultObj, "value", promiseCapability.[[Promise]]).+ // NB: Steps 20 and 21 use the same properties with false and an immediate string result.+ object+ .create_data_property_or_throw(+ self,+ &PropertyKey::from_utf8("async"),+ Value::from_bool(immediate.is_none()),+ )+ .must();+ object+ .create_data_property_or_throw(self, &PropertyKey::from_utf8("value"), value)+ .must();+ // 35. Return resultObj.+ Value::from_object(object)+ }++ pub fn resolve_async_wait(&self, id: u64) {+ let wait = {+ let mut waits = self.async_waits().borrow_mut(self);+ let Some(index) = waits.iter().position(|wait| wait.id == id && wait.result.is_some()) else {+ return;+ };+ waits.remove(index)+ };+ if let Some(timer) = wait.host_timer+ && let Some(hooks) = self.async_wait_agent().host_hooks()+ {+ hooks.cancel_timeout(self, wait.realm, timer);+ }+ let result = PrimitiveString::create_from_utf8(+ self,+ if wait.result == Some(AtomicWaitResult::Woken) {+ "ok"+ } else {+ "timed-out"+ },+ );+ // https://tc39.es/ecma262/#sec-notifywaiter+ // 3.b. Perform ! Call(promiseCapability.[[Resolve]], undefined, « waiterRecord.[[Result]] »).+ call_function_object(self, wait.resolve, Value::UNDEFINED, &[Value::from_string(result)]).must();+ }++ pub fn timeout_async_wait(&self, id: u64) {+ let wait = self+ .async_waits()+ .borrow()+ .iter()+ .find(|wait| wait.id == id)+ .map(|wait| (Arc::clone(&wait.waiter), wait.deadline, wait.realm));+ let Some((waiter, Some(deadline), realm)) = wait else {+ return;+ };+ if deadline > Instant::now() {+ if let Some(hooks) = self.async_wait_agent().host_hooks() {+ let timer = hooks.schedule_timeout(+ self,+ id,+ realm,+ deadline.saturating_duration_since(Instant::now()).as_secs_f64() * 1000.0,+ );+ if let Some(wait) = self+ .async_waits()+ .borrow_mut(self)+ .iter_mut()+ .find(|wait| wait.id == id)+ {+ wait.host_timer = Some(timer);+ }+ }+ return;+ }+ // https://tc39.es/ecma262/#sec-enqueueatomicswaitasynctimeoutjob+ // 1.b. If waiterList.[[Waiters]] contains waiterRecord, then+ // iv. Perform RemoveWaiter(waiterList, waiterRecord).+ // v. Perform NotifyWaiter(waiterList, waiterRecord).+ waiter_list::timeout_async_waiter(&waiter);+ }++ /// Completes the waits that are ready: those notified from another agent, and those whose timeout expired.+ fn complete_ready_async_waits(&self, agent: &AsyncWaitAgent) {+ agent.dispatch();+ let expired = self+ .async_waits()+ .borrow()+ .iter()+ .filter(|wait| wait.deadline.is_some_and(|deadline| deadline <= Instant::now()))+ .map(|wait| wait.id)+ .collect::<Vec<_>>();+ for id in expired {+ self.timeout_async_wait(id);+ }+ }++ /// Runs the promise jobs queued, and completes the waits that are ready, without sleeping for the others: a+ /// REPL line returns to the prompt, from which a later line may notify them.+ pub fn run_ready_async_wait_jobs(&self) {+ self.run_queued_promise_jobs();+ if self.async_waits().borrow().is_empty() {+ return;+ }+ let agent = Arc::clone(self.async_wait_agent());+ self.complete_ready_async_waits(&agent);+ self.run_queued_promise_jobs();+ }++ /// The standalone host runs tasks between promise checkpoints, sleeping until notification or the next timeout.+ pub fn run_async_wait_jobs_until(&self, done: impl Fn() -> bool) -> ThrowCompletionOr<()> {+ self.run_queued_promise_jobs();+ if done() || (self.async_waits().borrow().is_empty() && self.timeout_jobs().borrow().is_empty()) {+ return Ok(());+ }+ let agent = Arc::clone(self.async_wait_agent());+ while !done() && !self.interrupt_requested() {+ self.complete_ready_async_waits(&agent);+ self.run_queued_promise_jobs();+ if done() {+ break;+ }+ self.run_ready_timeout_job()?;+ self.run_queued_promise_jobs();+ if done() || (self.async_waits().borrow().is_empty() && self.timeout_jobs().borrow().is_empty()) {+ break;+ }+ let next = self+ .async_waits()+ .borrow()+ .iter()+ .filter_map(|wait| wait.deadline)+ .chain(self.timeout_jobs().borrow().iter().map(|job| job.deadline))+ .min();+ let ready = agent.ready.lock().unwrap_or_else(PoisonError::into_inner);+ if !ready.is_empty() {+ continue;+ }+ if self.interrupt_requested() {+ break;+ }+ if let Some(deadline) = next {+ drop(+ agent+ .changed+ .wait_timeout(ready, deadline.saturating_duration_since(Instant::now()))+ .unwrap_or_else(PoisonError::into_inner),+ );+ } else {+ drop(agent.changed.wait(ready).unwrap_or_else(PoisonError::into_inner));+ }+ }+ Ok(())+ }+}diff --git a/Libraries/LibJS/Rust/src/runtime/atomics_object.rs b/Libraries/LibJS/Rust/src/runtime/atomics_object.rsindex 82b1fac61dc..53448a460c4 100644--- a/Libraries/LibJS/Rust/src/runtime/atomics_object.rs+++ b/Libraries/LibJS/Rust/src/runtime/atomics_object.rs@@ -187,7 +187,7 @@ fn do_wait(expected_value: Value,timeout_value: Value,) -> ThrowCompletionOr<Value> {- // 1. Let taRecord be ? ValidateIntegerTypedArray(typedArray, true).+ // 1. Let taRecord be ? ValidateIntegerTypedArray(ta, true).let typed_array_record = validate_integer_typed_array(vm, typed_array, true)?;// 2. Let buffer be taRecord.[[Object]].[[ViewedArrayBuffer]].@@ -201,42 +201,46 @@ fn do_wait(// 4. Let byteIndexInBuffer be ? ValidateAtomicAccess(taRecord, index).let byte_index_in_buffer = validate_atomic_access(vm, &typed_array_record, index)?;- // 5. Let arrayTypeName be typedArray.[[TypedArrayName]].- // 6. If arrayTypeName is "BigInt64Array", let v be ? ToBigInt64(value).+ // 5. Let arrayTypeName be ta.[[TypedArrayName]].+ // 6. If arrayTypeName is "BigInt64Array", let expected be ? ToBigInt64(value).let value: i64 = if typed_array.kind() == Kind::BigInt64Array {expected_value.to_bigint_int64(vm)?}- // 7. Else, let v be ? ToInt32(value).+ // 7. Else, let expected be ? ToInt32(value).else {i64::from(expected_value.to_i32(vm)?)};- // 8. Let q be ? ToNumber(timeout).+ // 8. Let timeoutNumber be ? ToNumber(timeout).let timeout_number = timeout_value.to_number(vm)?;- // 9. If q is either NaN or +∞𝔽, let t be +∞; else if q is -∞𝔽, let t be 0; else let t be max(ℝ(q), 0).+ // 9. If timeoutNumber is either NaN or +∞𝔽, let realTimeout be +∞.let timeout = if timeout_number.is_nan() || timeout_number.is_positive_infinity() {f64::INFINITY- } else if timeout_number.is_negative_infinity() {+ }+ // 10. Else if timeoutNumber is -∞𝔽, let realTimeout be 0.+ else if timeout_number.is_negative_infinity() {0.0- } else {+ }+ // 11. Else, let realTimeout be max(ℝ(timeoutNumber), 0).+ else {timeout_number.as_f64().max(0.0)};- // 10. If mode is sync and AgentCanSuspend() is false, throw a TypeError exception.+ // 12. If mode is sync and AgentCanSuspend() is false, throw a TypeError exception.if mode == WaitMode::Sync && !agent_can_suspend(vm) {return vm.throw_completion(ErrorKind::TypeError, ErrorType::AgentCannotSuspend, &[]);}- // 11. Let block be buffer.[[ArrayBufferData]].- // 12-24. AD-HOC: The WaiterLists of the process are in ak::waiter_list. We don't yet implement Atomics.waitAsync- // (async mode).+ // 13. Let block be buffer.[[ArrayBufferData]].if mode == WaitMode::Async {- return vm.throw_completion(- ErrorKind::InternalError,- ErrorType::NotImplemented,- &[&"Atomics.waitAsync"],- );+ return Ok(vm.start_async_wait(+ buffer,+ byte_index_in_buffer,+ value as u64,+ typed_array.element_size(),+ timeout,+ ));}// t is in milliseconds. Convert to nanoseconds in floating point — so sub-millisecond timeouts survive, and guard@@ -257,13 +261,11 @@ fn do_wait(wait_timeout,vm.agent_waiter(),);+ // 32. If mode is sync, return waiterRecord.[[Result]].let result = match result {AtomicWaitResult::Interrupted => return vm.throw_interrupt(),- // 25. If waiterRecord.[[Result]] is "not-equal", return the String "not-equal".AtomicWaitResult::NotEqual => "not-equal",- // 26. If waiterRecord.[[Result]] is "timed-out", return the String "timed-out".AtomicWaitResult::TimedOut => "timed-out",- // 27. Return the String "ok".AtomicWaitResult::Woken => "ok",};Ok(Value::from_string(PrimitiveString::create_from_utf8(vm, result)))diff --git a/Libraries/LibJS/Rust/src/runtime/mod.rs b/Libraries/LibJS/Rust/src/runtime/mod.rsindex 6a6729fd888..fda4295da7f 100644--- a/Libraries/LibJS/Rust/src/runtime/mod.rs+++ b/Libraries/LibJS/Rust/src/runtime/mod.rs@@ -35,6 +35,7 @@ pub mod async_generator_function_prototype;pub mod async_generator_prototype;pub mod async_generator_request;pub mod async_iterator_prototype;+pub mod async_wait;pub mod atomics_object;pub mod big_fraction;pub mod big_int;diff --git a/Libraries/LibJS/Rust/src/utilities/js.rs b/Libraries/LibJS/Rust/src/utilities/js.rsindex 290953b2ac6..c77b36a159f 100644--- a/Libraries/LibJS/Rust/src/utilities/js.rs+++ b/Libraries/LibJS/Rust/src/utilities/js.rs@@ -37,7 +37,7 @@ use crate::layout::object::Object;use crate::layout::value::Value;use crate::lexical_path;use crate::parser_error::ParserError;-use crate::runtime::completion::ThrowCompletionOr;+use crate::runtime::completion::{Throw, ThrowCompletionOr};use crate::runtime::error::{Error, ErrorKind};use crate::runtime::error_data::CompactTraceback;use crate::runtime::error_types::ErrorType;@@ -47,7 +47,7 @@ use crate::runtime::native_function::raw_native;use crate::runtime::object::{ORDINARY_OBJECT_METHODS, PropertyLookupPhase, allocate_object, define_object_class};use crate::runtime::primitive_string::PrimitiveString;use crate::runtime::print::{PrintContext, print};-use crate::runtime::promise::Promise;+use crate::runtime::promise::{Promise, PromiseState};use crate::runtime::property_attributes::{Attribute, PropertyAttributes};use crate::runtime::property_key::PropertyKey;use crate::runtime::realm::Realm;@@ -1245,8 +1245,10 @@ fn parse_and_run(source: &[u8],source_name: &str,parse_only: bool,+ sleep_for_async_waits: bool,) -> Result<bool, String> {let mut result: ThrowCompletionOr<Value> = Ok(Value::UNDEFINED);+ let mut module_evaluation = None;// Like Utf16String::from_utf8(), this stops the process for a source that is not valid UTF-8, which the caller// has ruled out.let source_text = Utf16String::from_utf8(core::str::from_utf8(source).expect("the source is valid UTF-8"));@@ -1286,8 +1288,38 @@ fn parse_and_run(} else {let module = SourceTextModule::create_from_parsed(vm, parsed, source_code, realm, source_name);if !parse_only {- result = vm.run_module(module);+ result = vm.run_module(module).map(|evaluation| {+ module_evaluation = Some(Root::new(vm, evaluation));+ Value::UNDEFINED+ });+ }+ }+ }++ if result.is_ok() && !parse_only {+ if sleep_for_async_waits {+ if let Err(error) = vm.run_async_wait_jobs_until(|| {+ module_evaluation+ .as_ref()+ .is_some_and(|evaluation| evaluation.get().state() == PromiseState::Rejected)+ }) {+ result = Err(error);+ }+ } else {+ vm.run_ready_async_wait_jobs();+ }+ }++ if let Some(evaluation) = module_evaluation {+ match evaluation.get().state() {+ PromiseState::Pending if sleep_for_async_waits && result.is_ok() => {+ return Err("Module evaluation did not complete".to_string());+ }+ PromiseState::Rejected => {+ evaluation.get().mark_handled(vm);+ result = Err(Throw::new(evaluation.get().result()));}+ _ => {}}}@@ -1930,7 +1962,7 @@ mod repl {}REPL_STATEMENTS.with_borrow_mut(|statements| statements.push(piece.clone()));- parse_and_run(vm, realm, options, &piece, "REPL", false)?;+ parse_and_run(vm, realm, options, &piece, "REPL", false, false)?;}Ok(())}@@ -2176,7 +2208,7 @@ fn ladybird_main(arguments: &[String], line_editor: Option<JSLineEditor>) -> c_i// We resolve modules as if it is the first file- let result = parse_and_run(vm, realm, &options, &builder, source_name, options.parse_only);+ let result = parse_and_run(vm, realm, &options, &builder, source_name, options.parse_only, true);// NB: The VM lives until the process exits.vm.jit.flush_coverage();match result {diff --git a/Libraries/LibJS/Rust/src/utilities/test262_runner.rs b/Libraries/LibJS/Rust/src/utilities/test262_runner.rsindex c3695a8037e..b65d3a7a76e 100644--- a/Libraries/LibJS/Rust/src/utilities/test262_runner.rs+++ b/Libraries/LibJS/Rust/src/utilities/test262_runner.rs@@ -32,11 +32,14 @@ use crate::compile::parse;#[cfg(unix)]use crate::contrib::test262::agents::{self, AgentFailure};use crate::contrib::test262::global_object::Test262GlobalObject;+use crate::gc::root::Root;use crate::interpreter::vm::{Vm, VmOptions};use crate::layout::cell::Gc;use crate::layout::realm::Realm;use crate::layout::value::Value;use crate::parser_error::ParserError;+use crate::runtime::completion::Throw;+use crate::runtime::promise::PromiseState;use crate::runtime::source_text_module::SourceTextModule;use crate::script::Script;use crate::source_code::SourceCode;@@ -590,7 +593,29 @@ fn describe_thrown_value(vm: &Vm, error_value: Value) -> TestError {fn run_program(vm: &Vm, program: ScriptOrModuleProgram) -> Result<(), TestError> {let result = match program {ScriptOrModuleProgram::Script(script) => vm.run_script(script, None),- ScriptOrModuleProgram::Module(module) => vm.run_module(module),+ ScriptOrModuleProgram::Module(module) => {+ let evaluation = vm+ .run_module(module)+ .map_err(|throw| describe_thrown_value(vm, throw.value()))?;+ let evaluation = Root::new(vm, evaluation);+ vm.run_async_wait_jobs_until(|| evaluation.get().state() != PromiseState::Pending)+ .map_err(|throw| describe_thrown_value(vm, throw.value()))?;+ match evaluation.get().state() {+ PromiseState::Pending => {+ return Err(TestError {+ phase: NegativePhase::Harness,+ error_type: "Error".to_string(),+ details: "Module evaluation did not complete".to_string(),+ harness_file: "<module evaluation>".to_string(),+ });+ }+ PromiseState::Rejected => {+ evaluation.get().mark_handled(vm);+ Err(Throw::new(evaluation.get().result()))+ }+ PromiseState::Fulfilled => Ok(Value::UNDEFINED),+ }+ }};result.map(|_| ())@@ -650,7 +675,14 @@ fn run_test(}}- run_program(&vm, program)+ run_program(&vm, program)?;+ if metadata.is_async {+ let global = realm.global_object();+ let global: &Test262GlobalObject = crate::gc::class::cast_ref(&*global);+ vm.run_async_wait_jobs_until(|| global.async_test_complete())+ .map_err(|throw| describe_thrown_value(&vm, throw.value()))?;+ }+ Ok(())}fn error_to_json(error: &TestError) -> JsonObject {@@ -1032,6 +1064,10 @@ mod agent_mode {let script = Script::parse_with_filename(vm, &source, realm, "<agent>").map_err(|errors| TestError::syntax_error(NegativePhase::ParseOrEarly, first_parser_error(&errors), ""))?;run_program(vm, ScriptOrModuleProgram::Script(script))?;+ vm.run_async_wait_jobs_until(|| {+ agents::is_leaving() || UNHANDLED_REJECTIONS.with_borrow(|rejections| !rejections.is_empty())+ })+ .map_err(|throw| describe_thrown_value(vm, throw.value()))?;match UNHANDLED_REJECTIONS.take().into_iter().next() {Some((_, error)) => Err(error),None => Ok(()),diff --git a/Libraries/LibJS/Rust/src/utilities/test_js/test_js_functions.rs b/Libraries/LibJS/Rust/src/utilities/test_js/test_js_functions.rsindex ed5646fb4a9..89f3f128e6d 100644--- a/Libraries/LibJS/Rust/src/utilities/test_js/test_js_functions.rs+++ b/Libraries/LibJS/Rust/src/utilities/test_js/test_js_functions.rs@@ -63,6 +63,7 @@ pub const EXPOSED_GLOBAL_FUNCTIONS: &[(&str, RawNativeFunctionPointer)] = &[("evaluateSource", raw_native!(evaluate_source)),("evaluateModule", raw_native!(evaluate_module)),("runQueuedPromiseJobs", raw_native!(run_queued_promise_jobs)),+ ("runAsyncWaitJobs", raw_native!(run_async_wait_jobs)),("clearKeptObjects", raw_native!(clear_kept_objects)),("runQueuedFinalizationRegistryCleanupJobs",@@ -205,7 +206,7 @@ fn evaluate_module(vm: &Vm) -> ThrowCompletionOr<Value> {Err(error) => return vm.throw_completion_with_message(ErrorKind::SyntaxError, error.error.to_string()),};- vm.run_module(module)+ vm.run_module(module).map(Value::from_object)}#[allow(clippy::unnecessary_wraps, reason = "native functions return a completion")]@@ -214,6 +215,17 @@ fn run_queued_promise_jobs(vm: &Vm) -> ThrowCompletionOr<Value> {Ok(Value::UNDEFINED)}+fn run_async_wait_jobs(vm: &Vm) -> ThrowCompletionOr<Value> {+ if vm.is_running_promise_jobs() {+ return vm.throw_completion_with_message(+ ErrorKind::Error,+ "runAsyncWaitJobs cannot run inside a promise job".to_owned(),+ );+ }+ vm.run_async_wait_jobs_until(|| false)?;+ Ok(Value::UNDEFINED)+}+#[allow(clippy::unnecessary_wraps, reason = "native functions return a completion")]fn clear_kept_objects(vm: &Vm) -> ThrowCompletionOr<Value> {// VM::finish_execution_generation()diff --git a/Libraries/LibWeb/Bindings/MainThreadVM.cpp b/Libraries/LibWeb/Bindings/MainThreadVM.cppindex 4c961355d00..0d98dd248c9 100644--- a/Libraries/LibWeb/Bindings/MainThreadVM.cpp+++ b/Libraries/LibWeb/Bindings/MainThreadVM.cpp@@ -10,8 +10,10 @@#include <AK/Atomic.h>#include <AK/FFIHelpers.h>+#include <AK/Math.h>#include <AK/NeverDestroyed.h>#include <LibCore/AnonymousBuffer.h>+#include <LibCore/EventLoop.h>#include <LibCore/Platform/ThreadQoS.h>#include <LibCore/ThreadEventQueue.h>#include <LibGC/CellAllocator.h>@@ -166,6 +168,74 @@ void set_collect_garbage_on_every_allocation_in_new_agents(bool enabled)s_collect_garbage_on_every_allocation = enabled;}+struct AsyncWaitQueueReference {+ AK_ALLOC_WITH_KMALLOC;+ JS::AsyncWaitQueue const* queue;+ ~AsyncWaitQueueReference() { JS::VM::release_async_wait_queue(queue); }+};++struct AsyncWaitEventLoop {+ AK_ALLOC_WITH_KMALLOC;+ NonnullRefPtr<Core::WeakEventLoopReference> loop;+};++static void install_async_wait_hooks(JS::VM& vm)+{+ auto* event_loop = new AsyncWaitEventLoop { Core::EventLoop::current_weak() };+ JS::AsyncWaitHooks hooks {};+ hooks.data = event_loop;+ hooks.wake = [](void* context, JS::AsyncWaitQueue const* queue) {+ auto reference = make<AsyncWaitQueueReference>(queue);+ auto& weak_loop = static_cast<AsyncWaitEventLoop*>(context)->loop;+ if (auto loop = weak_loop->take()) {+ loop->deferred_invoke([reference = move(reference)] {+ JS::VM::dispatch_async_wait_queue(reference->queue);+ });+ }+ };+ hooks.destroy = [](void* context) {+ delete static_cast<AsyncWaitEventLoop*>(context);+ };+ hooks.enqueue_resolution = [](void*, u64 id, JS::Realm& realm) {+ // https://html.spec.whatwg.org/multipage/webappapis.html#hostenqueuegenericjob+ // 1. Let global be realm's global object.+ auto& global = realm.global_object();+ // 2. Queue a global task on the JavaScript engine task source given global to perform job().+ HTML::queue_global_task(HTML::Task::Source::JavaScriptEngine, global, GC::create_function(realm.heap(), GC::captures(realm, id), [](auto& realm, auto& id) {+ HTML::TemporaryExecutionContext context { realm };+ realm.vm().resolve_async_wait(id);+ }));+ };+ hooks.schedule_timeout = [](void*, u64 id, JS::Realm& realm, double milliseconds) {+ // https://html.spec.whatwg.org/multipage/webappapis.html#hostenqueuetimeoutjob+ // 1. Let global be realm's global object.+ auto& global = realm.global_object();+ // 2. Let timeoutStep be an algorithm step which queues a global task on the JavaScript engine task source+ // given global to perform job().+ auto timeout_step = GC::create_function(realm.heap(), GC::captures(realm, id), [](auto& realm, auto& id) {+ realm.vm().async_wait_timer_fired(id);+ HTML::queue_global_task(HTML::Task::Source::JavaScriptEngine, realm.global_object(), GC::create_function(realm.heap(), GC::captures(realm, id), [](auto& realm, auto& id) {+ HTML::TemporaryExecutionContext context { realm };+ realm.vm().timeout_async_wait(id);+ }));+ });+ // AD-HOC: The timer interface takes signed 32-bit milliseconds. Round up fractional waits, and split longer+ // waits into chunks; the runtime checks the deadline before timing out the waiter.+ auto delay = static_cast<i32>(min(ceil(milliseconds), static_cast<double>(NumericLimits<i32>::max())));+ // 3. Run steps after a timeout given global, "JavaScript", milliseconds, and timeoutStep.+ if (auto* worklet = impl_from<HTML::WorkletGlobalScope>(&global))+ return worklet->run_steps_after_a_timeout(delay, timeout_step);+ return HTML::relevant_window_or_worker_global_scope(global).run_steps_after_a_timeout(delay, timeout_step);+ };+ hooks.cancel_timeout = [](void*, JS::Realm& realm, i32 timer) {+ if (auto* worklet = impl_from<HTML::WorkletGlobalScope>(&realm.global_object()))+ worklet->cancel_timeout_steps(timer);+ else+ HTML::relevant_window_or_worker_global_scope(realm.global_object()).cancel_timeout_steps(timer);+ };+ vm.set_async_wait_hooks(hooks);+}+void initialize_agent(HTML::AgentType type){auto new_vm = JS::VM::create();@@ -178,6 +248,8 @@ void initialize_agent(HTML::AgentType type)ladybird_did_start_short_lived_thread();}vm.set_agent(create_agent(vm.heap(), type));+ if (Core::EventLoop::is_running())+ install_async_wait_hooks(vm);vm.heap().set_should_collect_on_every_allocation(s_collect_garbage_on_every_allocation);diff --git a/Libraries/LibWeb/HTML/Window.cpp b/Libraries/LibWeb/HTML/Window.cppindex c566b40afc9..7d8b7b4acf2 100644--- a/Libraries/LibWeb/HTML/Window.cpp+++ b/Libraries/LibWeb/HTML/Window.cpp@@ -1022,7 +1022,7 @@ void Window::invoke_idle_callbacks()// 1. Pop the top callback from window's list of runnable idle callbacks.auto callback = m_runnable_idle_callbacks.take_first();if (callback->timeout_timer_id().has_value()) {- clear_timeout(*callback->timeout_timer_id());+ cancel_timeout_steps(*callback->timeout_timer_id());callback->clear_timeout_timer_id();}// 2. Let deadlineArg be a new IdleDeadline whose [get deadline time algorithm] is getDeadline.@@ -2244,7 +2244,7 @@ void Window::cancel_idle_callback(u32 handle)if (!callback.has_value())return;if ((*callback)->timeout_timer_id().has_value())- clear_timeout(*(*callback)->timeout_timer_id());+ cancel_timeout_steps(*(*callback)->timeout_timer_id());};remove_callback(m_idle_request_callbacks);remove_callback(m_runnable_idle_callbacks);diff --git a/Libraries/LibWeb/HTML/WindowOrWorkerGlobalScope.cpp b/Libraries/LibWeb/HTML/WindowOrWorkerGlobalScope.cppindex 62c1c6c5e78..e61eb98b5c8 100644--- a/Libraries/LibWeb/HTML/WindowOrWorkerGlobalScope.cpp+++ b/Libraries/LibWeb/HTML/WindowOrWorkerGlobalScope.cpp@@ -836,17 +836,24 @@ WebIDL::ExceptionOr<i32> WindowOrWorkerGlobalScopeMixin::set_interval(TimerHandl// https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#dom-cleartimeoutvoid WindowOrWorkerGlobalScopeMixin::clear_timeout(i32 id){- if (auto timer = m_timers.get(id); timer.has_value())- timer.value()->stop();- m_timers.remove(id);+ // The clearTimeout(id) and clearInterval(id) method steps are to remove this's map of setTimeout and setInterval IDs[id].+ if (m_internal_timer_ids.contains(id))+ return;+ cancel_timeout_steps(id);}// https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#dom-clearintervalvoid WindowOrWorkerGlobalScopeMixin::clear_interval(i32 id){- if (auto timer = m_timers.get(id); timer.has_value())+ clear_timeout(id);+}++void WindowOrWorkerGlobalScopeMixin::cancel_timeout_steps(i32 timer_key)+{+ if (auto timer = m_timers.get(timer_key); timer.has_value())timer.value()->stop();- m_timers.remove(id);+ m_timers.remove(timer_key);+ m_internal_timer_ids.remove(timer_key);}void WindowOrWorkerGlobalScopeMixin::clear_map_of_active_timers()@@ -854,6 +861,7 @@ void WindowOrWorkerGlobalScopeMixin::clear_map_of_active_timers()for (auto& it : m_timers)it.value->stop();m_timers.clear();+ m_internal_timer_ids.clear();}// https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#timer-initialisation-steps@@ -1137,8 +1145,11 @@ WindowOrWorkerGlobalScopeMixin::AffectedAnyWebSockets WindowOrWorkerGlobalScopeMi32 WindowOrWorkerGlobalScopeMixin::run_steps_after_a_timeout(i32 timeout, GC::Ref<GC::Function<void()>> completion_step){auto timer_key = m_timer_id_allocator.allocate();+ m_internal_timer_ids.set(timer_key);auto remove_timer_and_complete = GC::create_function(GC::Heap::the(), GC::captures(this_impl(), timer_key, completion_step), [](auto& this_object, auto& timer_key, auto& completion_step) {- as<WindowOrWorkerGlobalScopeMixin>(this_object).m_timers.remove(timer_key);+ auto& global_scope = as<WindowOrWorkerGlobalScopeMixin>(this_object);+ global_scope.m_timers.remove(timer_key);+ global_scope.m_internal_timer_ids.remove(timer_key);completion_step->function()();});// NB: A timeout another specification waits on — an idle callback's, an AbortSignal's — isn't one of the page'sdiff --git a/Libraries/LibWeb/HTML/WindowOrWorkerGlobalScope.h b/Libraries/LibWeb/HTML/WindowOrWorkerGlobalScope.hindex 92e21c43d17..30a0944e264 100644--- a/Libraries/LibWeb/HTML/WindowOrWorkerGlobalScope.h+++ b/Libraries/LibWeb/HTML/WindowOrWorkerGlobalScope.h@@ -9,6 +9,7 @@#include <AK/Forward.h>#include <AK/HashMap.h>+#include <AK/HashTable.h>#include <AK/IDAllocator.h>#include <AK/Utf16FlyString.h>#include <AK/Utf16String.h>@@ -51,6 +52,7 @@ public:void clear_interval(i32);void clear_map_of_active_timers();size_t active_timer_count(Badge<Internals::Internals>) const { return m_timers.size(); }+ Vector<i32> active_timer_ids(Badge<Internals::Internals>) const { return m_timers.keys(); }void queue_microtask(WebIDL::CallbackType&);@@ -91,6 +93,7 @@ public:void clear_objects_with_pending_activity() { m_objects_with_pending_activity.clear(); }i32 run_steps_after_a_timeout(i32 timeout, GC::Ref<GC::Function<void()>> completion_step);+ void cancel_timeout_steps(i32 timer_key);void document_visibility_state_changed(Badge<DOM::Document>);void document_audio_play_state_changed(Badge<DOM::Document>);@@ -157,6 +160,7 @@ private:IDAllocator m_timer_id_allocator;HashMap<int, GC::Ref<Timer>> m_timers;+ HashTable<int> m_internal_timer_ids;double m_earliest_timer_deadline { NumericLimits<double>::max() };// The interval between the wake-ups a hidden document holds its delayed timers back to; a test can shorten it.diff --git a/Libraries/LibWeb/HTML/WorkletGlobalScope.cpp b/Libraries/LibWeb/HTML/WorkletGlobalScope.cppindex 6ddf9bdba05..6bd16ffb2da 100644--- a/Libraries/LibWeb/HTML/WorkletGlobalScope.cpp+++ b/Libraries/LibWeb/HTML/WorkletGlobalScope.cpp@@ -50,6 +50,42 @@ void WorkletGlobalScope::visit_edges(Cell::Visitor& visitor)Base::visit_edges(visitor);UniversalGlobalScopeMixin::visit_edges(visitor);visitor.visit(m_settings_object);+ for (auto& timeout : m_timers)+ visitor.visit(timeout.value.completion_step);+}++void WorkletGlobalScope::finalize()+{+ for (auto& timer : m_timers)+ timer.value.timer->stop();+ m_timers.clear();+ Base::finalize();+}++// https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#run-steps-after-a-timeout+// AD-HOC: The timeout algorithm only defines Window and WorkerGlobalScope globals. Worklet globals also need internal+// timeouts for JavaScript engine jobs, even though they don't expose the setTimeout/setInterval API.+i32 WorkletGlobalScope::run_steps_after_a_timeout(i32 timeout, GC::Ref<GC::Function<void()>> completion_step)+{+ auto timer_key = m_timer_id_allocator.allocate();+ auto timer = Core::Timer::create_single_shot(AK::Duration::from_milliseconds(timeout), [this, timer_key] {+ auto timeout = m_timers.take(timer_key);+ if (!timeout.has_value())+ return;+ m_timer_id_allocator.deallocate(timer_key);+ (*timeout->completion_step)();+ });+ m_timers.set(timer_key, Timeout { timer, completion_step });+ timer->start();+ return timer_key;+}++void WorkletGlobalScope::cancel_timeout_steps(i32 timer_key)+{+ if (auto timer = m_timers.take(timer_key); timer.has_value()) {+ timer->timer->stop();+ m_timer_id_allocator.deallocate(timer_key);+ }}}diff --git a/Libraries/LibWeb/HTML/WorkletGlobalScope.h b/Libraries/LibWeb/HTML/WorkletGlobalScope.hindex ec2ade9edb8..8523161786a 100644--- a/Libraries/LibWeb/HTML/WorkletGlobalScope.h+++ b/Libraries/LibWeb/HTML/WorkletGlobalScope.h@@ -6,6 +6,10 @@#pragma once+#include <AK/HashMap.h>+#include <AK/IDAllocator.h>+#include <LibCore/Timer.h>+#include <LibGC/Function.h>#include <LibURL/URL.h>#include <LibWeb/DOM/EventTarget.h>#include <LibWeb/Export.h>@@ -44,6 +48,9 @@ public:URL::URL const& url() const { return m_url; }void set_url(URL::URL url) { m_url = move(url); }+ i32 run_steps_after_a_timeout(i32 timeout, GC::Ref<GC::Function<void()>> completion_step);+ void cancel_timeout_steps(i32 timer_key);+// Called once the realm's [[HostDefined]] is installed; subclass overrides are generated from IDL// and install the global's exposed interfaces and mixin members.virtual void initialize_web_interfaces_impl() { }@@ -52,6 +59,7 @@ protected:WorkletGlobalScope();virtual void visit_edges(Cell::Visitor&) override;+ virtual void finalize() override;private:friend JS::Realm& Bindings::main_world_realm(WorkletGlobalScope const&);@@ -60,6 +68,12 @@ private:GC::Ptr<EnvironmentSettingsObject> m_settings_object;URL::URL m_url;+ IDAllocator m_timer_id_allocator;+ struct Timeout {+ NonnullRefPtr<Core::Timer> timer;+ GC::Ref<GC::Function<void()>> completion_step;+ };+ HashMap<i32, Timeout> m_timers;};}diff --git a/Libraries/LibWeb/Internals/Internals.cpp b/Libraries/LibWeb/Internals/Internals.cppindex ea937d611ec..189fa424e11 100644--- a/Libraries/LibWeb/Internals/Internals.cpp+++ b/Libraries/LibWeb/Internals/Internals.cpp@@ -3546,6 +3546,18 @@ WebIDL::UnsignedLongLong Internals::active_timer_count(JS::Object& object)return 0;}+Vector<WebIDL::Long> Internals::active_timer_ids(JS::Object& object)+{+ if (auto* window_proxy = HTML::WindowProxy::from_object(object)) {+ if (auto window = window_proxy->window())+ return window->active_timer_ids({});+ return {};+ }+ if (auto* window = HTML::window_from_global_object(object))+ return window->active_timer_ids({});+ return {};+}+WebIDL::UnsignedLongLong Internals::task_queue_length(){return HTML::main_thread_event_loop().task_queue().size_slow();diff --git a/Libraries/LibWeb/Internals/Internals.h b/Libraries/LibWeb/Internals/Internals.hindex 6835db1a3ef..f71b9985a19 100644--- a/Libraries/LibWeb/Internals/Internals.h+++ b/Libraries/LibWeb/Internals/Internals.h@@ -349,6 +349,7 @@ public:void set_hidden_document_timer_wake_up_interval(double milliseconds);void set_hidden_document_intensive_timer_throttling(double wake_up_interval, double grace_period_once_loaded, double grace_period_while_loading);WebIDL::UnsignedLongLong active_timer_count(JS::Object& window);+ Vector<WebIDL::Long> active_timer_ids(JS::Object& window);WebIDL::UnsignedLongLong task_queue_length();Utf16String canvas_color_scheme();Vector<String> image_request_urls(DOM::Document const&) const;diff --git a/Libraries/LibWeb/Internals/Internals.idl b/Libraries/LibWeb/Internals/Internals.idlindex cabe5b1728c..74ac645e7a0 100644--- a/Libraries/LibWeb/Internals/Internals.idl+++ b/Libraries/LibWeb/Internals/Internals.idl@@ -471,6 +471,7 @@ interface Internals {undefined setHiddenDocumentIntensiveTimerThrottling(double wakeUpInterval, double gracePeriodOnceLoaded, double gracePeriodWhileLoading);// Returns how many timers are armed on the given window (a Window or WindowProxy object).unsigned long long activeTimerCount(object window);+ sequence<long> activeTimerIds(object window);// Returns how many tasks sit in the main thread event loop's task queue, runnable or not.unsigned long long taskQueueLength();DOMString canvasColorScheme();diff --git a/Tests/LibJS/CMakeLists.txt b/Tests/LibJS/CMakeLists.txtindex 070c13f368c..4b6fdf36533 100644--- a/Tests/LibJS/CMakeLists.txt+++ b/Tests/LibJS/CMakeLists.txt@@ -16,6 +16,15 @@ add_dependencies(test-js test-js-runtime test-js-script js)add_test(NAME test-js COMMAND test-js)set_tests_properties(test-js PROPERTIES ENVIRONMENT "LADYBIRD_SOURCE_DIR=${LADYBIRD_SOURCE_DIR}" RUN_SERIAL TRUE)+set(module_host_test_arguments --js "$<TARGET_FILE:js>")+if (NOT WIN32)+ list(APPEND module_host_test_arguments --test262-runner "$<TARGET_FILE:test262-runner>")+endif()+add_test(+ NAME test-js-module-hosts+ COMMAND "${Python3_EXECUTABLE}" "${ladybird_SOURCE_DIR}/Tests/LibJS/test-js-module-hosts.py" ${module_host_test_arguments}+)+# The JIT's tests: the runtime tests (each run three times, so that the functions they call get compiled with# feedback) and the programs in Tests/LibJS/JIT/programs, under the fast tier of JIT stress modes and compared with the# interpreter; and the checks of the IR the JIT's passes produce. Tests/LibJS/JIT/matrix.py runs more modes and suites.diff --git a/Tests/LibJS/Runtime/builtins/Atomics/Atomics.waitAsync-nested-jobs.js b/Tests/LibJS/Runtime/builtins/Atomics/Atomics.waitAsync-nested-jobs.jsnew file mode 100644index 00000000000..2b0060b2a4e--- /dev/null+++ b/Tests/LibJS/Runtime/builtins/Atomics/Atomics.waitAsync-nested-jobs.js@@ -0,0 +1,16 @@+test("running async wait jobs from a promise reaction is rejected", () => {+ const view = new Int32Array(new SharedArrayBuffer(4));+ const result = Atomics.waitAsync(view, 0, 0);+ const order = [];+ Promise.resolve().then(() => {+ expect(() => runAsyncWaitJobs()).toThrow(Error);+ order.push("reaction");+ });+ Promise.resolve().then(() => {+ order.push("notify");+ Atomics.notify(view, 0);+ });+ result.value.then(value => order.push(value));+ runAsyncWaitJobs();+ expect(order).toEqual(["reaction", "notify", "ok"]);+});diff --git a/Tests/LibJS/Runtime/builtins/Atomics/Atomics.waitAsync.js b/Tests/LibJS/Runtime/builtins/Atomics/Atomics.waitAsync.jsindex b2aaad8b067..1d822122bd1 100644--- a/Tests/LibJS/Runtime/builtins/Atomics/Atomics.waitAsync.js+++ b/Tests/LibJS/Runtime/builtins/Atomics/Atomics.waitAsync.js@@ -71,3 +71,51 @@ test("basic functionality", () => {expect(Atomics.waitAsync).toHaveLength(4);});});++for (const TypedArray of [Int32Array, BigInt64Array]) {+ describe(TypedArray.name, () => {+ const zero = TypedArray === BigInt64Array ? 0n : 0;+ const one = TypedArray === BigInt64Array ? 1n : 1;+ const createArray = () => new TypedArray(new SharedArrayBuffer(TypedArray.BYTES_PER_ELEMENT));++ test("a mismatched value returns an immediate result, even with timeout zero", () => {+ const array = createArray();+ expect(Atomics.waitAsync(array, 0, one, 0)).toEqual({ async: false, value: "not-equal" });+ expect(Atomics.notify(array, 0)).toBe(0);+ });++ test("timeout zero returns an immediate result without registering a waiter", () => {+ const array = createArray();+ expect(Atomics.waitAsync(array, 0, zero, 0)).toEqual({ async: false, value: "timed-out" });+ expect(Atomics.notify(array, 0)).toBe(0);+ });++ test("same-agent notification resolves before subsequently queued promise jobs", () => {+ const array = createArray();+ const result = Atomics.waitAsync(array, 0, zero);+ expect(result.async).toBeTrue();+ expect(result.value).toBeInstanceOf(Promise);+ const values = [];+ result.value.then(value => values.push(value));+ expect(Atomics.notify(array, 0, 1)).toBe(1);+ Promise.resolve().then(() => values.push("later promise job"));+ runQueuedPromiseJobs();+ expect(values).toEqual(["ok", "later promise job"]);+ expect(Atomics.notify(array, 0)).toBe(0);+ });++ test("a finite timeout resolves the promise and removes the waiter", () => {+ const array = createArray();+ const result = Atomics.waitAsync(array, 0, zero, 1);+ expect(result.async).toBeTrue();+ expect(result.value).toBeInstanceOf(Promise);+ let value;+ result.value.then(result => {+ value = result;+ });+ runAsyncWaitJobs();+ expect(value).toBe("timed-out");+ expect(Atomics.notify(array, 0)).toBe(0);+ });+ });+}diff --git a/Tests/LibJS/Runtime/modules/atomics-wait-async-entry-reject.mjs b/Tests/LibJS/Runtime/modules/atomics-wait-async-entry-reject.mjsnew file mode 100644index 00000000000..a3dba593985--- /dev/null+++ b/Tests/LibJS/Runtime/modules/atomics-wait-async-entry-reject.mjs@@ -0,0 +1,3 @@+const array = new Int32Array(new SharedArrayBuffer(4));+await Atomics.waitAsync(array, 0, 0, 1).value;+throw new Error("module failed after waiting");diff --git a/Tests/LibJS/Runtime/modules/atomics-wait-async-entry.js b/Tests/LibJS/Runtime/modules/atomics-wait-async-entry.jsnew file mode 100644index 00000000000..00737a139c8--- /dev/null+++ b/Tests/LibJS/Runtime/modules/atomics-wait-async-entry.js@@ -0,0 +1,31 @@+test("entry module can suspend on an async wait", () => {+ const evaluation = evaluateModule("./modules/atomics-wait-async-entry.mjs");+ expect(evaluation).toBeInstanceOf(Promise);+ expect(globalThis.asyncWaitModuleResult).toBeUndefined();+ gc();+ runAsyncWaitJobs();+ expect(globalThis.asyncWaitModuleResult).toBe("timed-out");+});++test("entry module evaluation does not block a promise reaction", () => {+ globalThis.asyncWaitModuleResult = undefined;+ const order = [];+ Promise.resolve().then(() => {+ evaluateModule("./modules/atomics-wait-async-entry.mjs").then(() => {+ order.push(globalThis.asyncWaitModuleResult);+ });+ order.push("evaluation returned");+ });+ Promise.resolve().then(() => order.push("next reaction"));+ runAsyncWaitJobs();+ expect(order).toEqual(["evaluation returned", "next reaction", "timed-out"]);+});++test("entry module rejection after an async wait is observable", () => {+ let message;+ evaluateModule("./modules/atomics-wait-async-entry-reject.mjs").catch(error => {+ message = error.message;+ });+ runAsyncWaitJobs();+ expect(message).toBe("module failed after waiting");+});diff --git a/Tests/LibJS/Runtime/modules/atomics-wait-async-entry.mjs b/Tests/LibJS/Runtime/modules/atomics-wait-async-entry.mjsnew file mode 100644index 00000000000..7fb846ec080--- /dev/null+++ b/Tests/LibJS/Runtime/modules/atomics-wait-async-entry.mjs@@ -0,0 +1,2 @@+const array = new Int32Array(new SharedArrayBuffer(4));+globalThis.asyncWaitModuleResult = await Atomics.waitAsync(array, 0, 0, 1).value;diff --git a/Tests/LibJS/test-js-module-hosts.py b/Tests/LibJS/test-js-module-hosts.pynew file mode 100644index 00000000000..0efbc6c8ff3--- /dev/null+++ b/Tests/LibJS/test-js-module-hosts.py@@ -0,0 +1,201 @@+#!/usr/bin/env python3+#+# Copyright (c) 2026-present, the Ladybird developers.+#+# SPDX-License-Identifier: BSD-2-Clause++import argparse+import json+import subprocess+import sys+import tempfile+import unittest++from pathlib import Path+from typing import Optional++REJECT_AFTER_WAIT = """+globalThis.view = new Int32Array(new SharedArrayBuffer(8));+globalThis.pending = Atomics.waitAsync(view, 0, 0).value;+await Atomics.waitAsync(view, 1, 0, 1).value;+throw new Error("module rejection sentinel");+"""+++class ModuleHostTests(unittest.TestCase):+ js: Path+ test262_runner: Optional[Path]++ def setUp(self):+ directory = tempfile.TemporaryDirectory(prefix="libjs-module-host-")+ self.addCleanup(directory.cleanup)+ self.directory = Path(directory.name)++ def run_process(self, command, **kwargs):+ try:+ return subprocess.run(command, capture_output=True, text=True, timeout=30, **kwargs)+ except subprocess.TimeoutExpired as error:+ self.fail(f"Module execution did not finish: {error}")++ def run_cli_module(self, source):+ path = self.directory / "module.mjs"+ path.write_text(source, encoding="utf-8")+ return self.run_process([str(self.js), "--as-module", str(path)])++ def run_test262_module(self, source, negative=False, flags="module, raw"):+ if self.test262_runner is None:+ self.skipTest("test262-runner is not built on this platform")+ metadata = f"flags: [{flags}]\n"+ if negative:+ metadata += "negative:\n phase: runtime\n type: Error\n"+ path = self.directory / "module.js"+ path.write_text(f"/*---\n{metadata}---*/\n{source}", encoding="utf-8")+ process = self.run_process(+ [str(self.test262_runner), "--harness-location", str(self.directory)], input=f"{path}\n"+ )+ self.assertEqual(process.returncode, 0, process.stderr)+ results = [+ json.loads(line.removeprefix("RESULT ").rstrip("\0"))+ for line in process.stdout.splitlines()+ if line.startswith("RESULT ")+ ]+ self.assertEqual(len(results), 1, process.stdout)+ return results[0]++ def test_cli_rejection_stops_an_unrelated_infinite_wait(self):+ process = self.run_cli_module(REJECT_AFTER_WAIT)+ self.assertEqual(process.returncode, 1, process.stderr)+ self.assertIn("module rejection sentinel", process.stderr)++ def test_cli_fulfilled_module_still_drains_waits(self):+ process = self.run_cli_module("""+globalThis.view = new Int32Array(new SharedArrayBuffer(4));+Atomics.waitAsync(view, 0, 0, 1).value.then(() => print("wait drained"));+""")+ self.assertEqual(process.returncode, 0, process.stderr)+ self.assertIn("wait drained", process.stdout)++ def test_cli_pending_module_fails(self):+ for prefix in ["", "await Atomics.waitAsync(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 1).value;"]:+ with self.subTest(prefix=prefix):+ process = self.run_cli_module(prefix + "\nawait new Promise(() => {});")+ self.assertEqual(process.returncode, 1, process.stderr)+ self.assertIn("Module evaluation did not complete", process.stderr)++ @unittest.skipIf(sys.platform == "win32", "The REPL is not built on this platform")+ def test_repl_pending_module_can_complete_in_a_later_input(self):+ process = self.run_process(+ [str(self.js), "--as-module"],+ input='await new Promise(resolve => globalThis.finish = resolve); print("module completed");\nfinish();\n',+ )+ self.assertEqual(process.returncode, 0, process.stderr)+ self.assertIn("module completed", process.stdout)+ self.assertNotIn("Module evaluation did not complete", process.stderr)++ def test_runner_pending_module_cannot_pass(self):+ for prefix in ["", "await Atomics.waitAsync(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 1).value;"]:+ with self.subTest(prefix=prefix):+ result = self.run_test262_module(prefix + "\nawait new Promise(() => {});")+ self.assertNotEqual(result["result"], "passed", result)++ def test_runner_pending_module_cannot_match_an_expected_exception(self):+ result = self.run_test262_module("await new Promise(() => {});", negative=True)+ self.assertNotEqual(result["result"], "passed", result)++ def test_runner_rejection_matches_an_expected_exception(self):+ result = self.run_test262_module(REJECT_AFTER_WAIT, negative=True)+ self.assertEqual(result["result"], "passed", result)++ def test_runner_fulfilled_module_passes(self):+ result = self.run_test262_module("""+await Atomics.waitAsync(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 1).value;+print("module completed");+""")+ self.assertEqual(result["result"], "passed", result)+ self.assertIn("module completed", result["output"])++ def test_runner_timer_polling_allows_async_wait_timeouts(self):+ result = self.run_test262_module(+ """+let outcome;+let order = [];+Atomics.waitAsync(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 1).value.then(value => outcome = value);+Promise.resolve().then(() => order.push("promise"));+function poll() {+ if (order[0] !== "promise") throw new Error("Timer ran before the promise checkpoint");+ if (outcome === "timed-out") {+ print("Test262:AsyncTestComplete");+ return;+ }+ setTimeout(poll, 0);+}+setTimeout(poll, 0);+$262.gc();+""",+ flags="async, raw",+ )+ self.assertEqual(result["result"], "passed", result)++ def test_runner_agent_rejection_stops_an_unrelated_infinite_wait(self):+ for reaction in [+ "Promise.resolve()",+ "Atomics.waitAsync(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 1).value",+ ]:+ with self.subTest(reaction=reaction):+ result = self.run_test262_module(+ f"""+$262.agent.start(`+ globalThis.pending = Atomics.waitAsync(new Int32Array(new SharedArrayBuffer(4)), 0, 0).value;+ {reaction}.then(() => {{ throw new Error("agent rejection sentinel"); }});+`);+while ($262.agent.getReport() === null) {{+ $262.agent.sleep(1);+}}+""",+ flags="raw",+ )+ self.assertEqual(result["result"], "failed", result)+ self.assertIn("agent rejection sentinel", json.dumps(result))++ def test_runner_agent_rejection_handled_at_checkpoint_can_continue(self):+ result = self.run_test262_module(+ """+$262.agent.start(`+ globalThis.pending = Atomics.waitAsync(new Int32Array(new SharedArrayBuffer(4)), 0, 0).value;+ const rejected = Promise.reject(new Error("handled agent rejection"));+ Promise.resolve().then(() => rejected.catch(() => {}));+ Atomics.waitAsync(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 1).value.then(() => {+ $262.agent.report("agent continued");+ $262.agent.leaving();+ });+`);+let report;+while ((report = $262.agent.getReport()) === null) {+ $262.agent.sleep(1);+}+if (report !== "agent continued") throw new Error("Unexpected agent report");+""",+ flags="raw",+ )+ self.assertEqual(result["result"], "passed", result)++ def test_runner_timer_exception_fails(self):+ result = self.run_test262_module(+ """+setTimeout(() => { throw new Error("timer exception sentinel"); }, 0);+setTimeout(() => print("Test262:AsyncTestComplete"), 0);+""",+ flags="async, raw",+ )+ self.assertNotEqual(result["result"], "passed", result)+ self.assertIn("timer exception sentinel", json.dumps(result))+++if __name__ == "__main__":+ parser = argparse.ArgumentParser()+ parser.add_argument("--js", required=True, type=Path)+ parser.add_argument("--test262-runner", type=Path)+ arguments, remaining = parser.parse_known_args()+ ModuleHostTests.js = arguments.js.resolve()+ ModuleHostTests.test262_runner = arguments.test262_runner.resolve() if arguments.test262_runner else None+ unittest.main(argv=[sys.argv[0], *remaining])diff --git a/Tests/LibWeb/Text/expected/WebAudio/AudioWorklet-atomics-wait-async-crash.txt b/Tests/LibWeb/Text/expected/WebAudio/AudioWorklet-atomics-wait-async-crash.txtnew file mode 100644index 00000000000..38bd6d99ace--- /dev/null+++ b/Tests/LibWeb/Text/expected/WebAudio/AudioWorklet-atomics-wait-async-crash.txt@@ -0,0 +1,3 @@+crossOriginIsolated: false, typeof Atomics.waitAsync: function+addModule resolved+page surviveddiff --git a/Tests/LibWeb/Text/expected/WebAudio/AudioWorklet-atomics-wait-async-gc.txt b/Tests/LibWeb/Text/expected/WebAudio/AudioWorklet-atomics-wait-async-gc.txtnew file mode 100644index 00000000000..ee1901664d9--- /dev/null+++ b/Tests/LibWeb/Text/expected/WebAudio/AudioWorklet-atomics-wait-async-gc.txt@@ -0,0 +1 @@+collected closed context: truediff --git a/Tests/LibWeb/Text/expected/WebAudio/AudioWorklet-atomics-wait-async.txt b/Tests/LibWeb/Text/expected/WebAudio/AudioWorklet-atomics-wait-async.txtnew file mode 100644index 00000000000..6c4d85260a1--- /dev/null+++ b/Tests/LibWeb/Text/expected/WebAudio/AudioWorklet-atomics-wait-async.txt@@ -0,0 +1,4 @@+waitAsync: function; setTimeout: undefined+async: true,true+results: timed-out,ok; notified: 1+completeddiff --git a/Tests/LibWeb/Text/expected/atomics-wait-async-clear-timeout.txt b/Tests/LibWeb/Text/expected/atomics-wait-async-clear-timeout.txtnew file mode 100644index 00000000000..1a70820b834--- /dev/null+++ b/Tests/LibWeb/Text/expected/atomics-wait-async-clear-timeout.txt@@ -0,0 +1,2 @@+results: timed-out, timed-out+remaining waiters: 0diff --git a/Tests/LibWeb/Text/expected/atomics-wait-async-realm-gc.txt b/Tests/LibWeb/Text/expected/atomics-wait-async-realm-gc.txtnew file mode 100644index 00000000000..beb751d4c5a--- /dev/null+++ b/Tests/LibWeb/Text/expected/atomics-wait-async-realm-gc.txt@@ -0,0 +1,2 @@+reachable waiters: 1+retained promise: okdiff --git a/Tests/LibWeb/Text/expected/atomics-wait-async-unreachable-realm.txt b/Tests/LibWeb/Text/expected/atomics-wait-async-unreachable-realm.txtnew file mode 100644index 00000000000..d6ff461592c--- /dev/null+++ b/Tests/LibWeb/Text/expected/atomics-wait-async-unreachable-realm.txt@@ -0,0 +1,3 @@+collected: prototype=true, buffer=true, promise=true+collected: prototype=true, buffer=true, promise=true+collected: prototype=true, buffer=true, promise=truediff --git a/Tests/LibWeb/Text/expected/atomics-wait-async-worker-termination.txt b/Tests/LibWeb/Text/expected/atomics-wait-async-worker-termination.txtnew file mode 100644index 00000000000..64d18bdd40f--- /dev/null+++ b/Tests/LibWeb/Text/expected/atomics-wait-async-worker-termination.txt@@ -0,0 +1,2 @@+registered+waiters after termination: 0diff --git a/Tests/LibWeb/Text/expected/atomics-wait-async-worker.txt b/Tests/LibWeb/Text/expected/atomics-wait-async-worker.txtnew file mode 100644index 00000000000..18c17f25cdc--- /dev/null+++ b/Tests/LibWeb/Text/expected/atomics-wait-async-worker.txt@@ -0,0 +1,9 @@+async: true, true+results: ok, ok+notified: 2, order: 1,2, stored: 42+worker timeout: timed-out+timeout: true, timed-out+after timeout: 0+wait timer: 1+canceled timer: 0+microtasks: waiter,nextdiff --git a/Tests/LibWeb/Text/input/WebAudio/AudioWorklet-atomics-wait-async-crash.html b/Tests/LibWeb/Text/input/WebAudio/AudioWorklet-atomics-wait-async-crash.htmlnew file mode 100644index 00000000000..c477d627caa--- /dev/null+++ b/Tests/LibWeb/Text/input/WebAudio/AudioWorklet-atomics-wait-async-crash.html@@ -0,0 +1,22 @@+<!DOCTYPE html>+<script src="../include.js"></script>+<script>+ promiseTest(async () => {+ const source = `+ const buffer = new WebAssembly.Memory({ initial: 1, maximum: 1, shared: true }).buffer;+ Atomics.waitAsync(new Int32Array(buffer), 0, 0, 10);+ `;+ const url = URL.createObjectURL(new Blob([source], { type: "text/javascript" }));+ println(`crossOriginIsolated: ${self.crossOriginIsolated}, typeof Atomics.waitAsync: ${typeof Atomics.waitAsync}`);+ const context = new AudioContext();+ try {+ await context.audioWorklet.addModule(url);+ println("addModule resolved");+ } catch (error) {+ println(`addModule rejected: ${error}`);+ }+ await new Promise(resolve => setTimeout(resolve, 100));+ println("page survived");+ await context.close();+ });+</script>diff --git a/Tests/LibWeb/Text/input/WebAudio/AudioWorklet-atomics-wait-async-gc.html b/Tests/LibWeb/Text/input/WebAudio/AudioWorklet-atomics-wait-async-gc.htmlnew file mode 100644index 00000000000..79d736df132--- /dev/null+++ b/Tests/LibWeb/Text/input/WebAudio/AudioWorklet-atomics-wait-async-gc.html@@ -0,0 +1,24 @@+<!doctype html>+<script src="../include.js"></script>+<script>+ promiseTest(async () => {+ async function createClosedContext() {+ const context = new AudioContext();+ context.keepWrapper = true;+ const url = URL.createObjectURL(new Blob([`+ const buffer = new WebAssembly.Memory({ initial: 1, maximum: 1, shared: true }).buffer;+ globalThis.pending = Atomics.waitAsync(new Int32Array(buffer), 0, 0, 60000).value;+ `], { type: "text/javascript" }));+ try {+ await context.audioWorklet.addModule(url);+ } finally {+ URL.revokeObjectURL(url);+ await context.close();+ }+ return new WeakRef(context);+ }+ const reference = await createClosedContext();+ await collectGarbageUntilCleared([reference]);+ println(`collected closed context: ${reference.deref() === undefined}`);+ });+</script>diff --git a/Tests/LibWeb/Text/input/WebAudio/AudioWorklet-atomics-wait-async.html b/Tests/LibWeb/Text/input/WebAudio/AudioWorklet-atomics-wait-async.htmlnew file mode 100644index 00000000000..41499c65f97--- /dev/null+++ b/Tests/LibWeb/Text/input/WebAudio/AudioWorklet-atomics-wait-async.html@@ -0,0 +1,42 @@+<!doctype html>+<script src="../include.js"></script>+<script>+ promiseTest(async () => {+ const context = new AudioContext();+ const source = `+ class WaitProcessor extends AudioWorkletProcessor {+ constructor() {+ super();+ const buffer = new WebAssembly.Memory({ initial: 1, maximum: 1, shared: true }).buffer;+ const view = new Int32Array(buffer);+ this.port.postMessage("waitAsync: " + typeof Atomics.waitAsync + "; setTimeout: " + typeof setTimeout);+ const timeout = Atomics.waitAsync(view, 0, 0, 10);+ const notified = Atomics.waitAsync(view, 1, 0, 60000);+ this.port.postMessage("async: " + timeout.async + "," + notified.async);+ const count = Atomics.notify(view, 1);+ Promise.all([timeout.value, notified.value]).then(results => {+ this.port.postMessage("results: " + results.join(",") + "; notified: " + count);+ });+ }+ process() { return true; }+ }+ registerProcessor("wait", WaitProcessor);+ `;+ const url = URL.createObjectURL(new Blob([source], { type: "text/javascript" }));+ try {+ await context.audioWorklet.addModule(url);+ const node = new AudioWorkletNode(context, "wait");+ await new Promise((resolve, reject) => {+ node.onprocessorerror = () => reject(new Error("processor failed"));+ node.port.onmessage = event => {+ println(event.data);+ if (event.data.startsWith("results:")) resolve();+ };+ });+ println("completed");+ } finally {+ URL.revokeObjectURL(url);+ await context.close();+ }+ });+</script>diff --git a/Tests/LibWeb/Text/input/atomics-wait-async-clear-timeout.html b/Tests/LibWeb/Text/input/atomics-wait-async-clear-timeout.htmlnew file mode 100644index 00000000000..9c923408fca--- /dev/null+++ b/Tests/LibWeb/Text/input/atomics-wait-async-clear-timeout.html@@ -0,0 +1,26 @@+<!doctype html>+<script src="include.js"></script>+<script>+ asyncTest(async done => {+ try {+ const view = new Int32Array(new SharedArrayBuffer(4));+ const first = Atomics.waitAsync(view, 0, 0, 10);+ const second = Atomics.waitAsync(view, 0, 0, 20);+ const end = setTimeout(() => {}, 1000000);+ const ids = internals.activeTimerIds?.(window) ?? Array.from({ length: end }, (_, i) => i + 1);+ for (const id of ids) {+ clearTimeout(id);+ clearInterval(id);+ }+ const results = await Promise.race([+ Promise.all([first.value, second.value]),+ new Promise(resolve => setTimeout(() => resolve(["not resolved"]), 1000)),+ ]);+ println(`results: ${results.join(", ")}`);+ println(`remaining waiters: ${Atomics.notify(view, 0)}`);+ } catch (error) {+ println(`${error.name}: ${error.message}`);+ }+ done();+ });+</script>diff --git a/Tests/LibWeb/Text/input/atomics-wait-async-clear-timeout.html.headers b/Tests/LibWeb/Text/input/atomics-wait-async-clear-timeout.html.headersnew file mode 100644index 00000000000..63b60e490f4--- /dev/null+++ b/Tests/LibWeb/Text/input/atomics-wait-async-clear-timeout.html.headers@@ -0,0 +1,2 @@+Cross-Origin-Opener-Policy: same-origin+Cross-Origin-Embedder-Policy: require-corpdiff --git a/Tests/LibWeb/Text/input/atomics-wait-async-realm-gc.html b/Tests/LibWeb/Text/input/atomics-wait-async-realm-gc.htmlnew file mode 100644index 00000000000..015936f1790--- /dev/null+++ b/Tests/LibWeb/Text/input/atomics-wait-async-realm-gc.html@@ -0,0 +1,29 @@+<!doctype html>+<script src="include.js"></script>+<script>+ asyncTest(async done => {+ const view = new Int32Array(new SharedArrayBuffer(4));+ let retainedPromise;+ function createWait() {+ const frame = document.createElement("iframe");+ document.body.append(frame);+ frame.contentWindow.view = view;+ const result = frame.contentWindow.eval("Atomics.waitAsync(view, 0, 0)");+ retainedPromise = result.value;+ frame.remove();+ }+ try {+ createWait();+ for (let i = 0; i < 5; ++i) {+ await new Promise(resolve => setTimeout(resolve, 0));+ internals.gc();+ internals.gc();+ }+ println(`reachable waiters: ${Atomics.notify(view, 0)}`);+ println(`retained promise: ${await retainedPromise}`);+ } catch (error) {+ println(`${error.name}: ${error.message}`);+ }+ done();+ });+</script>diff --git a/Tests/LibWeb/Text/input/atomics-wait-async-realm-gc.html.headers b/Tests/LibWeb/Text/input/atomics-wait-async-realm-gc.html.headersnew file mode 100644index 00000000000..63b60e490f4--- /dev/null+++ b/Tests/LibWeb/Text/input/atomics-wait-async-realm-gc.html.headers@@ -0,0 +1,2 @@+Cross-Origin-Opener-Policy: same-origin+Cross-Origin-Embedder-Policy: require-corpdiff --git a/Tests/LibWeb/Text/input/atomics-wait-async-unreachable-realm.html b/Tests/LibWeb/Text/input/atomics-wait-async-unreachable-realm.htmlnew file mode 100644index 00000000000..011ebf2acaf--- /dev/null+++ b/Tests/LibWeb/Text/input/atomics-wait-async-unreachable-realm.html@@ -0,0 +1,33 @@+<!doctype html>+<script src="include.js"></script>+<script>+ asyncTest(async done => {+ async function createWait() {+ const frame = document.createElement("iframe");+ document.body.append(frame);+ const result = frame.contentWindow.eval(`+ globalThis.view = new Int32Array(new SharedArrayBuffer(4));+ Atomics.waitAsync(view, 0, 0)+ `);+ const references = [+ new WeakRef(frame.contentWindow.Object.prototype),+ new WeakRef(frame.contentWindow.view.buffer),+ new WeakRef(result.value),+ ];+ await new Promise(resolve => {+ frame.contentWindow.addEventListener("unload", resolve, { once: true });+ frame.remove();+ });+ return references;+ }+ const references = await Promise.all([createWait(), createWait(), createWait()]);+ // Iframe creation keeps its navigable rooted until the session-history operation completes.+ await internals.flushSessionHistoryTraversalQueue();+ // Release the parent's layout references after the removed frames have unloaded.+ document.body.getBoundingClientRect();+ await collectGarbageUntilCleared(references.flat());+ for (const [prototype, buffer, promise] of references)+ println(`collected: prototype=${prototype.deref() === undefined}, buffer=${buffer.deref() === undefined}, promise=${promise.deref() === undefined}`);+ done();+ });+</script>diff --git a/Tests/LibWeb/Text/input/atomics-wait-async-unreachable-realm.html.headers b/Tests/LibWeb/Text/input/atomics-wait-async-unreachable-realm.html.headersnew file mode 100644index 00000000000..63b60e490f4--- /dev/null+++ b/Tests/LibWeb/Text/input/atomics-wait-async-unreachable-realm.html.headers@@ -0,0 +1,2 @@+Cross-Origin-Opener-Policy: same-origin+Cross-Origin-Embedder-Policy: require-corpdiff --git a/Tests/LibWeb/Text/input/atomics-wait-async-worker-termination.html b/Tests/LibWeb/Text/input/atomics-wait-async-worker-termination.htmlnew file mode 100644index 00000000000..74be57382fe--- /dev/null+++ b/Tests/LibWeb/Text/input/atomics-wait-async-worker-termination.html@@ -0,0 +1,28 @@+<!doctype html>+<script src="include.js"></script>+<script>+ asyncTest(async done => {+ const before = internals.workerAgentCount();+ const view = new Int32Array(new SharedArrayBuffer(8));+ const source = `onmessage = event => {+ const view = new Int32Array(event.data);+ Atomics.waitAsync(view, 0, 0);+ Atomics.waitAsync(view, 0, 0, 1000000000);+ postMessage("registered");+ };`;+ const worker = new Worker(URL.createObjectURL(new Blob([source], { type: "text/javascript" })));+ worker.onerror = event => {+ println(`worker error: ${event.message}`);+ done();+ };+ const ready = new Promise(resolve => {+ worker.onmessage = event => resolve(event.data);+ });+ worker.postMessage(view.buffer);+ println(await ready);+ worker.terminate();+ while (internals.workerAgentCount() !== before) await new Promise(resolve => setTimeout(resolve, 10));+ println(`waiters after termination: ${Atomics.notify(view, 0)}`);+ done();+ });+</script>diff --git a/Tests/LibWeb/Text/input/atomics-wait-async-worker-termination.html.headers b/Tests/LibWeb/Text/input/atomics-wait-async-worker-termination.html.headersnew file mode 100644index 00000000000..63b60e490f4--- /dev/null+++ b/Tests/LibWeb/Text/input/atomics-wait-async-worker-termination.html.headers@@ -0,0 +1,2 @@+Cross-Origin-Opener-Policy: same-origin+Cross-Origin-Embedder-Policy: require-corpdiff --git a/Tests/LibWeb/Text/input/atomics-wait-async-worker.html b/Tests/LibWeb/Text/input/atomics-wait-async-worker.htmlnew file mode 100644index 00000000000..142f0aa4427--- /dev/null+++ b/Tests/LibWeb/Text/input/atomics-wait-async-worker.html@@ -0,0 +1,74 @@+<!doctype html>+<script src="include.js"></script>+<script>+ asyncTest(async done => {+ const worker = new Worker(+ URL.createObjectURL(+ new Blob(+ [+ `+ onmessage = async event => {+ const view = new Int32Array(event.data);+ Atomics.store(view, 1, 42);+ const notified = Atomics.notify(view, 0);+ const timeout = await Atomics.waitAsync(view, 1, 42, 1).value;+ postMessage({ notified, timeout });+ };+ `,+ ],+ { type: "text/javascript" }+ )+ )+ );+ worker.onerror = event => {+ println(`worker error: ${event.message}`);+ done();+ };+ try {+ const view = new Int32Array(new SharedArrayBuffer(8));+ const first = Atomics.waitAsync(view, 0, 0);+ const second = Atomics.waitAsync(view, 0, 0);+ println(`async: ${first.async}, ${second.async}`);+ const order = [];+ const firstDone = first.value.then(value => {+ order.push(1);+ return value;+ });+ const secondDone = second.value.then(value => {+ order.push(2);+ return value;+ });+ const notification = new Promise(resolve => {+ worker.onmessage = event => resolve(event.data);+ });+ internals.gc();+ internals.gc();+ worker.postMessage(view.buffer);+ println(`results: ${await firstDone}, ${await secondDone}`);+ const workerResult = await notification;+ println(`notified: ${workerResult.notified}, order: ${order}, stored: ${Atomics.load(view, 1)}`);+ println(`worker timeout: ${workerResult.timeout}`);+ const timeout = Atomics.waitAsync(view, 0, 0, 10);+ println(`timeout: ${timeout.async}, ${await timeout.value}`);+ println(`after timeout: ${Atomics.notify(view, 0)}`);+ const beforeTimers = internals.activeTimerCount(window);+ const longWait = Atomics.waitAsync(view, 0, 0, 1000000000);+ println(`wait timer: ${internals.activeTimerCount(window) - beforeTimers}`);+ Atomics.notify(view, 0);+ await longWait.value;+ println(`canceled timer: ${internals.activeTimerCount(window) - beforeTimers}`);+ const sameAgent = Atomics.waitAsync(view, 0, 0);+ const microtasks = [];+ sameAgent.value.then(() => microtasks.push("waiter"));+ Atomics.notify(view, 0);+ Promise.resolve().then(() => microtasks.push("next"));+ await Promise.resolve();+ println(`microtasks: ${microtasks}`);+ } catch (error) {+ println(`${error.name}: ${error.message}`);+ } finally {+ worker.terminate();+ done();+ }+ });+</script>diff --git a/Tests/LibWeb/Text/input/atomics-wait-async-worker.html.headers b/Tests/LibWeb/Text/input/atomics-wait-async-worker.html.headersnew file mode 100644index 00000000000..63b60e490f4--- /dev/null+++ b/Tests/LibWeb/Text/input/atomics-wait-async-worker.html.headers@@ -0,0 +1,2 @@+Cross-Origin-Opener-Policy: same-origin+Cross-Origin-Embedder-Policy: require-corp