Truly independent web browser
LibJS: Hand out shared array buffer words as typed atomics
Andreas Kling4fa6a307bec5
diff --git a/Libraries/LibJS/Rust/src/futex.rs b/Libraries/LibJS/Rust/src/futex.rsindex 3125a12e0ba..840d45e30cd 100644--- a/Libraries/LibJS/Rust/src/futex.rs+++ b/Libraries/LibJS/Rust/src/futex.rs@@ -18,36 +18,55 @@ pub enum AtomicWaitResult {TimedOut,}-fn read_word(address: *mut u8, size: usize) -> u64 {- // SAFETY: The caller passes the aligned word of a typed array element, which is only accessed atomically.- unsafe {- if size >= 8 {- return AtomicU64::from_ptr(address.cast()).load(Ordering::SeqCst);+/// The word of a shared typed array element that Atomics.wait waits on, which is 4 or 8 bytes wide.+#[derive(Clone, Copy)]+pub(crate) enum WaitWord<'a> {+ Word32(&'a AtomicU32),+ Word64(&'a AtomicU64),+}++impl WaitWord<'_> {+ /// The address waiters key on, which is that of the low 32-bit half of the word.+ #[cfg(any(target_os = "macos", target_os = "linux"))]+ fn address(self) -> *mut u32 {+ match self {+ WaitWord::Word32(word) => word.as_ptr(),+ WaitWord::Word64(word) => word.as_ptr().cast(),+ }+ }++ /// A sequentially-consistent read, matching the memory model's read for the wait comparison.+ fn load(self) -> u64 {+ match self {+ WaitWord::Word32(word) => u64::from(word.load(Ordering::SeqCst)),+ WaitWord::Word64(word) => word.load(Ordering::SeqCst),}- u64::from(AtomicU32::from_ptr(address.cast()).load(Ordering::SeqCst))}}-// Whether the word at address currently equals expected, masked to the wait size (Atomics.wait uses 4-byte or 8-byte-// words). A sequentially-consistent read, matching the memory model's read for the wait comparison.-fn word_equals(address: *mut u8, expected: u64, size: usize) -> bool {- let mask = if size >= 8 { u64::MAX } else { u64::from(u32::MAX) };- (read_word(address, size) & mask) == (expected & mask)+// Whether the word currently equals expected, masked to the wait size.+fn word_equals(word: WaitWord<'_>, expected: u64) -> bool {+ let mask = match word {+ WaitWord::Word32(_) => u64::from(u32::MAX),+ WaitWord::Word64(_) => u64::MAX,+ };+ (word.load() & mask) == (expected & mask)}// Fallback where there's no cross-process wait primitive: Poll for a change to the word. That observes value changes// rather than notifications — which matches the lock/futex protocol Emscripten uses (the waker writes the word before// notifying). The gap is a notify that leaves the word unchanged: It wakes no poll-waiter, and the paired atomic_notify// reports zero woken. An untimed wait whose only wake would be such a notify therefore never returns.-fn poll_wait(address: *mut u8, expected: u64, size: usize, timeout: Option<Duration>) -> AtomicWaitResult {- if !word_equals(address, expected, size) {+#[cfg(not(target_os = "linux"))]+fn poll_wait(word: WaitWord<'_>, expected: u64, timeout: Option<Duration>) -> AtomicWaitResult {+ if !word_equals(word, expected) {return AtomicWaitResult::NotEqual;}let start = Instant::now();loop {std::thread::sleep(Duration::from_micros(200));- if !word_equals(address, expected, size) {+ if !word_equals(word, expected) {return AtomicWaitResult::Woken;}if timeout.is_some_and(|timeout| start.elapsed() >= timeout) {@@ -110,13 +129,13 @@ fn errno() -> i32 {}#[cfg(target_os = "macos")]-pub(crate) fn atomic_wait(address: *mut u8, expected: u64, size: usize, timeout: Option<Duration>) -> AtomicWaitResult {+pub(crate) fn atomic_wait(word: WaitWord<'_>, expected: u64, timeout: Option<Duration>) -> AtomicWaitResult {// Compare the value in userspace first. os_sync_wait_on_address reports a value mismatch as a *successful* return// (it has no EAGAIN). So, without this, the "not-equal" result would be unreachable; it also faults the shared page// in — avoiding a transient first-touch EFAULT below. A store landing between this read and the kernel's own// comparison is reported as a wake, rather than "not-equal" — a nanoseconds-wide window inherent to the os_sync API// (Linux's kernel futex and the poll fallback don't have it).- if !word_equals(address, expected, size) {+ if !word_equals(word, expected) {return AtomicWaitResult::NotEqual;}@@ -138,7 +157,7 @@ pub(crate) fn atomic_wait(address: *mut u8, expected: u64, size: usize, timeout:// SAFETY: The address is the aligned word of a shared typed array element.unsafe {(functions.wait_on_address_with_timeout)(- address.cast(),+ word.address().cast(),u64::from(expected as u32),4,os_sync::OS_SYNC_WAIT_ON_ADDRESS_SHARED,@@ -150,7 +169,7 @@ pub(crate) fn atomic_wait(address: *mut u8, expected: u64, size: usize, timeout:// SAFETY: As above.unsafe {(functions.wait_on_address)(- address.cast(),+ word.address().cast(),u64::from(expected as u32),4,os_sync::OS_SYNC_WAIT_ON_ADDRESS_SHARED,@@ -166,7 +185,7 @@ pub(crate) fn atomic_wait(address: *mut u8, expected: u64, size: usize, timeout:// os_sync reports a value mismatch as a successful wake — so retrying with the original expected would// turn a store that landed while we slept into a spurious "ok". Re-read first: If the word changed,// report "not-equal" (as if the critical section were entered late) — matching the Linux EAGAIN path.- if !word_equals(address, expected, size) {+ if !word_equals(word, expected) {return AtomicWaitResult::NotEqual;}continue;@@ -183,13 +202,13 @@ pub(crate) fn atomic_wait(address: *mut u8, expected: u64, size: usize, timeout:}if let Some(deadline) = deadline {let remaining = deadline.saturating_duration_since(Instant::now());- return poll_wait(address, expected, size, Some(remaining));+ return poll_wait(word, expected, Some(remaining));}- poll_wait(address, expected, size, timeout)+ poll_wait(word, expected, timeout)}#[cfg(target_os = "macos")]-pub(crate) fn atomic_notify(address: *mut u8, _size: usize, max_count: usize) -> usize {+pub(crate) fn atomic_notify(word: &AtomicU32, max_count: usize) -> usize {// Waiters key on the low 32-bit half — so, wake with size 4 regardless of the notifying view's element size. That// lets a 4-byte notify wake an 8-byte waiter (and vice versa) at the same address — which the spec's single per-// address WaiterList requires.@@ -202,8 +221,9 @@ pub(crate) fn atomic_notify(address: *mut u8, _size: usize, max_count: usize) ->let mut woken = 0;while woken < max_count {// SAFETY: The address is the aligned word of a shared typed array element.- let result =- unsafe { (functions.wake_by_address_any)(address.cast(), 4, os_sync::OS_SYNC_WAKE_BY_ADDRESS_SHARED) };+ let result = unsafe {+ (functions.wake_by_address_any)(word.as_ptr().cast(), 4, os_sync::OS_SYNC_WAKE_BY_ADDRESS_SHARED)+ };if result == 0 {woken += 1;continue;@@ -218,18 +238,13 @@ pub(crate) fn atomic_notify(address: *mut u8, _size: usize, max_count: usize) ->}#[cfg(target_os = "linux")]-pub(crate) fn atomic_wait(address: *mut u8, expected: u64, size: usize, timeout: Option<Duration>) -> AtomicWaitResult {+pub(crate) fn atomic_wait(word: WaitWord<'_>, expected: u64, timeout: Option<Duration>) -> AtomicWaitResult {// Compare the value in userspace first — so a zero or already-elapsed timeout still yields "not-equal" (which the// spec orders before "timed-out"), and so 8-byte waits and the poll fallback share one compare.- if !word_equals(address, expected, size) {+ if !word_equals(word, expected) {return AtomicWaitResult::NotEqual;}- // Atomics.wait only ever uses size 4 or 8 (ValidateIntegerTypedArray); keep the poll fallback as a guard.- if size != 4 && size != 8 {- return poll_wait(address, expected, size, timeout);- }-// Anchor the timeout to a fixed deadline — so EINTR retries reduce the remaining time, rather than restarting the// full timeout (FUTEX_WAIT takes a relative timeout that the kernel doesn't update across a retry).let deadline = timeout.and_then(|timeout| Instant::now().checked_add(timeout));@@ -252,7 +267,7 @@ pub(crate) fn atomic_wait(address: *mut u8, expected: u64, size: usize, timeout:let result = unsafe {libc::syscall(libc::SYS_futex,- address,+ word.address(),libc::FUTEX_WAIT,expected as u32,timeout_pointer,@@ -276,15 +291,15 @@ pub(crate) fn atomic_wait(address: *mut u8, expected: u64, size: usize, timeout:}#[cfg(target_os = "linux")]-pub(crate) fn atomic_notify(address: *mut u8, _size: usize, max_count: usize) -> usize {- // FUTEX_WAKE wakes waiters keyed on the low 32-bit half at 'address'. That covers both 4-byte and 8-byte waiters+pub(crate) fn atomic_notify(word: &AtomicU32, max_count: usize) -> usize {+ // FUTEX_WAKE wakes waiters keyed on the low 32-bit half at the word's address. That covers both 4-byte and 8-byte waiters// (8-byte waits key on the low half too), and returns the exact number of waiters woken.let count = i32::try_from(max_count).unwrap_or(i32::MAX);// SAFETY: The address is the aligned word of a shared typed array element.let result = unsafe {libc::syscall(libc::SYS_futex,- address,+ word.as_ptr(),libc::FUTEX_WAKE,count,core::ptr::null::<libc::timespec>(),@@ -298,12 +313,12 @@ pub(crate) fn atomic_notify(address: *mut u8, _size: usize, max_count: usize) ->// No native wait/wake primitive is wired up on this platform. Poll for a change to the word, instead of reporting// "not-equal" unconditionally — which would make every Atomics.wait return immediately, and spin its caller.#[cfg(not(any(target_os = "macos", target_os = "linux")))]-pub(crate) fn atomic_wait(address: *mut u8, expected: u64, size: usize, timeout: Option<Duration>) -> AtomicWaitResult {- poll_wait(address, expected, size, timeout)+pub(crate) fn atomic_wait(word: WaitWord<'_>, expected: u64, timeout: Option<Duration>) -> AtomicWaitResult {+ poll_wait(word, expected, timeout)}#[cfg(not(any(target_os = "macos", target_os = "linux")))]-pub(crate) fn atomic_notify(_address: *mut u8, _size: usize, _max_count: usize) -> usize {+pub(crate) fn atomic_notify(_word: &AtomicU32, _max_count: usize) -> usize {// The waiters poll for the value change the waker has already made — so there's nothing to signal.0}diff --git a/Libraries/LibJS/Rust/src/runtime/array_buffer.rs b/Libraries/LibJS/Rust/src/runtime/array_buffer.rsindex 0964e68337f..3602bbd9154 100644--- a/Libraries/LibJS/Rust/src/runtime/array_buffer.rs+++ b/Libraries/LibJS/Rust/src/runtime/array_buffer.rs@@ -15,7 +15,7 @@ use core::time::Duration;use libjs_runtime_macros::Trace;use num_bigint::BigInt as NumBigInt;-use crate::futex::{self, AtomicWaitResult};+use crate::futex::{self, AtomicWaitResult, WaitWord};use crate::gc::capi::{GC_PRIMITIVE_STORAGE_NULL_HANDLE, GCPrimitiveStorageHandle, gc_cell_type_info};use crate::gc::class::{ExternalMemorySize, Finalize, GcCell, define_cell};use crate::gc::foreign::ForeignCellSlot;@@ -519,8 +519,22 @@ impl DataBlock {assert!(byte_offset == 0);return core::ptr::null_mut();}- // SAFETY: Callers only address bytes within the block.- unsafe { data.add(byte_offset) }+ // NB: This only forms the address, which callers that access the bytes check against the block.+ data.wrapping_add(byte_offset)+ }++ /// The aligned bytes at `byte_index` as an atomic, which every access to bytes that are shared goes through.+ pub(crate) fn atomic_at<A: AtomicWord>(&self, byte_index: usize) -> &A {+ assert!(+ byte_index+ .checked_add(size_of::<A>())+ .is_some_and(|end| end <= self.size())+ );+ let address = self.data_at(byte_index);+ assert!(address.addr().is_multiple_of(align_of::<A>()));+ // SAFETY: The block has the aligned bytes, which are only ever accessed atomically while they are shared, and+ // which stay in place for as long as the block is borrowed.+ unsafe { &*address.cast::<A>() }}#[inline]@@ -726,32 +740,23 @@ impl DataBlock {}fn atomic_load(&self, byte_index: usize, size: usize, ordering: Ordering) -> u64 {- let address = self.data_at(byte_index);- assert!(address.addr().is_multiple_of(size));- // SAFETY: The block has the aligned bytes, which are only ever accessed atomically while they are shared.- unsafe {- match size {- 1 => u64::from(AtomicU8::from_ptr(address).load(ordering)),- 2 => u64::from(AtomicU16::from_ptr(address.cast()).load(ordering)),- 4 => u64::from(AtomicU32::from_ptr(address.cast()).load(ordering)),- 8 => AtomicU64::from_ptr(address.cast()).load(ordering),- _ => unreachable!("atomic accesses are 1, 2, 4 or 8 bytes wide"),- }+ match size {+ 1 => u64::from(self.atomic_at::<AtomicU8>(byte_index).load(ordering)),+ 2 => u64::from(self.atomic_at::<AtomicU16>(byte_index).load(ordering)),+ 4 => u64::from(self.atomic_at::<AtomicU32>(byte_index).load(ordering)),+ 8 => self.atomic_at::<AtomicU64>(byte_index).load(ordering),+ _ => unreachable!("atomic accesses are 1, 2, 4 or 8 bytes wide"),}}+ /// Stores `value`, truncated to the access size.fn atomic_store(&self, byte_index: usize, size: usize, value: u64, ordering: Ordering) {- let address = self.data_at(byte_index);- assert!(address.addr().is_multiple_of(size));- // SAFETY: As for atomic_load(). The value is truncated to the access size.- unsafe {- match size {- 1 => AtomicU8::from_ptr(address).store(value as u8, ordering),- 2 => AtomicU16::from_ptr(address.cast()).store(value as u16, ordering),- 4 => AtomicU32::from_ptr(address.cast()).store(value as u32, ordering),- 8 => AtomicU64::from_ptr(address.cast()).store(value, ordering),- _ => unreachable!("atomic accesses are 1, 2, 4 or 8 bytes wide"),- }+ match size {+ 1 => self.atomic_at::<AtomicU8>(byte_index).store(value as u8, ordering),+ 2 => self.atomic_at::<AtomicU16>(byte_index).store(value as u16, ordering),+ 4 => self.atomic_at::<AtomicU32>(byte_index).store(value as u32, ordering),+ 8 => self.atomic_at::<AtomicU64>(byte_index).store(value, ordering),+ _ => unreachable!("atomic accesses are 1, 2, 4 or 8 bytes wide"),}}@@ -763,9 +768,8 @@ impl DataBlock {operand: u64,) -> u64 {macro_rules! perform {- ($atomic:ty, $address:expr, $operand:expr) => {{- // SAFETY: As for atomic_load().- let atomic = unsafe { <$atomic>::from_ptr($address) };+ ($atomic:ty, $operand:expr) => {{+ let atomic = self.atomic_at::<$atomic>(byte_index);let ordering = Ordering::SeqCst;u64::from(match operation {ReadWriteModifyOperation::Add => atomic.fetch_add($operand, ordering),@@ -778,22 +782,19 @@ impl DataBlock {}};}- let address = self.data_at(byte_index);- assert!(address.addr().is_multiple_of(size));match size {- 1 => perform!(AtomicU8, address, operand as u8),- 2 => perform!(AtomicU16, address.cast(), operand as u16),- 4 => perform!(AtomicU32, address.cast(), operand as u32),- 8 => perform!(AtomicU64, address.cast(), operand),+ 1 => perform!(AtomicU8, operand as u8),+ 2 => perform!(AtomicU16, operand as u16),+ 4 => perform!(AtomicU32, operand as u32),+ 8 => perform!(AtomicU64, operand),_ => unreachable!("atomic accesses are 1, 2, 4 or 8 bytes wide"),}}fn atomic_compare_exchange(&self, byte_index: usize, size: usize, expected: u64, replacement: u64) -> u64 {macro_rules! perform {- ($atomic:ty, $type:ty, $address:expr) => {{- // SAFETY: As for atomic_load().- let atomic = unsafe { <$atomic>::from_ptr($address) };+ ($atomic:ty, $type:ty) => {{+ let atomic = self.atomic_at::<$atomic>(byte_index);let observed = atomic.compare_exchange(expected as $type,replacement as $type,@@ -804,18 +805,24 @@ impl DataBlock {}};}- let address = self.data_at(byte_index);- assert!(address.addr().is_multiple_of(size));match size {- 1 => perform!(AtomicU8, u8, address),- 2 => perform!(AtomicU16, u16, address.cast()),- 4 => perform!(AtomicU32, u32, address.cast()),- 8 => perform!(AtomicU64, u64, address.cast()),+ 1 => perform!(AtomicU8, u8),+ 2 => perform!(AtomicU16, u16),+ 4 => perform!(AtomicU32, u32),+ 8 => perform!(AtomicU64, u64),_ => unreachable!("atomic accesses are 1, 2, 4 or 8 bytes wide"),}}}+/// The atomic integer types, the only types DataBlock::atomic_at() hands out, as every bit pattern is one of their+/// values.+pub(crate) trait AtomicWord {}+impl AtomicWord for AtomicU8 {}+impl AtomicWord for AtomicU16 {}+impl AtomicWord for AtomicU32 {}+impl AtomicWord for AtomicU64 {}+/// A large allocation that fails may succeed once dead buffers pinning address space are collected, so it is retried/// once after a collection before giving up, as WebKit does.fn allocate_or_retry_after_gc<T>(heap: &Heap, allocate: impl Fn() -> Result<T, OutOfMemory>) -> Result<T, OutOfMemory> {@@ -1410,15 +1417,20 @@ impl ArrayBuffer {size: usize,timeout: Option<Duration>,) -> AtomicWaitResult {- let address = self.data_block.borrow().data_at(byte_index);- // NB: The data block stays in place while the agent waits, since the agent is the only one that could change it.- futex::atomic_wait(address, expected, size, timeout)+ // NB: The data block stays borrowed while the agent waits, since the agent is the only one that could change it.+ let data_block = self.data_block.borrow();+ let word = match size {+ 4 => WaitWord::Word32(data_block.atomic_at(byte_index)),+ 8 => WaitWord::Word64(data_block.atomic_at(byte_index)),+ _ => unreachable!("Atomics.wait waits on 4-byte or 8-byte elements"),+ };+ futex::atomic_wait(word, expected, timeout)}/// Core::atomic_notify() on the word at `byte_index`.- pub fn atomic_notify(&self, byte_index: usize, size: usize, max_count: usize) -> usize {- let address = self.data_block.borrow().data_at(byte_index);- futex::atomic_notify(address, size, max_count)+ pub fn atomic_notify(&self, byte_index: usize, max_count: usize) -> usize {+ // NB: Waiters of both sizes key on the low 32-bit half of their word.+ futex::atomic_notify(self.data_block.borrow().atomic_at::<AtomicU32>(byte_index), max_count)}}diff --git a/Libraries/LibJS/Rust/src/runtime/atomics_object.rs b/Libraries/LibJS/Rust/src/runtime/atomics_object.rsindex 1a9b829a062..cd0e12f77e7 100644--- a/Libraries/LibJS/Rust/src/runtime/atomics_object.rs+++ b/Libraries/LibJS/Rust/src/runtime/atomics_object.rs@@ -513,7 +513,7 @@ impl AtomicsObject {} else {usize::MAX};- let woken = buffer.atomic_notify(byte_index_in_buffer, typed_array.element_size() as usize, max_count);+ let woken = buffer.atomic_notify(byte_index_in_buffer, max_count);// 16. Return 𝔽(n).Ok(Value::from_f64(woken as f64))