Skip to content

Truly independent web browser

LibWasm+LibWeb: Keep WebAssembly objects and waits right

Andreas Kling3afe88dd4f0b
diff --git a/Libraries/LibJS/Rust/src/futex.rs b/Libraries/LibJS/Rust/src/futex.rs
index 840d45e30cd..2f932ea9c9c 100644
--- a/Libraries/LibJS/Rust/src/futex.rs
+++ b/Libraries/LibJS/Rust/src/futex.rs
@@ -8,6 +8,7 @@
use core::sync::atomic::{AtomicU32, AtomicU64, Ordering};
use core::time::Duration;
+#[cfg(any(target_os = "macos", target_os = "linux"))]
use std::time::Instant;
/// Core::AtomicWaitResult.
@@ -27,7 +28,6 @@ pub(crate) enum WaitWord<'a> {
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(),
@@ -53,26 +53,105 @@ fn word_equals(word: WaitWord<'_>, expected: u64) -> bool {
(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.
+// Fallback where there's no wait/wake primitive of the operating system's: Each waiter waits on a condition variable of
+// its own, in a list per address that atomic_notify() wakes waiters of in the order they began waiting. These lists only
+// reach the waiters of this process. So, a waiter also polls for a change to the word, which observes the wakes of other
+// processes that write the word before notifying (as the lock/futex protocol Emscripten uses does). A notify from
+// another process that leaves the word unchanged wakes no waiter here.
#[cfg(not(target_os = "linux"))]
-fn poll_wait(word: WaitWord<'_>, expected: u64, timeout: Option<Duration>) -> AtomicWaitResult {
- if !word_equals(word, expected) {
- return AtomicWaitResult::NotEqual;
+mod waiter_list {
+ use super::{AtomicWaitResult, WaitWord, word_equals};
+ use core::sync::atomic::{AtomicBool, Ordering};
+ use core::time::Duration;
+ use std::collections::{HashMap, VecDeque};
+ use std::sync::{Arc, Condvar, Mutex, MutexGuard, OnceLock};
+ use std::time::Instant;
+
+ const POLL_INTERVAL: Duration = Duration::from_micros(200);
+
+ struct Waiter {
+ woken: AtomicBool,
+ condition: Condvar,
}
- let start = Instant::now();
- loop {
- std::thread::sleep(Duration::from_micros(200));
+ type Lists = HashMap<usize, VecDeque<Arc<Waiter>>>;
+
+ fn lists() -> MutexGuard<'static, Lists> {
+ static LISTS: OnceLock<Mutex<Lists>> = OnceLock::new();
+ LISTS
+ .get_or_init(Mutex::default)
+ .lock()
+ .unwrap_or_else(|error| error.into_inner())
+ }
+
+ fn remove(lists: &mut Lists, address: usize, waiter: &Arc<Waiter>) {
+ let Some(list) = lists.get_mut(&address) else {
+ return;
+ };
+ list.retain(|other| !Arc::ptr_eq(other, waiter));
+ if list.is_empty() {
+ lists.remove(&address);
+ }
+ }
+
+ pub(super) fn wait(word: WaitWord<'_>, expected: u64, timeout: Option<Duration>) -> AtomicWaitResult {
+ let address = word.address().addr();
+ let deadline = timeout.and_then(|timeout| Instant::now().checked_add(timeout));
+ // NB: The word is compared while the lists are locked, so a notify that follows a store to it finds this
+ // waiter in its list if the comparison did not see the store.
+ let mut lists = lists();
if !word_equals(word, expected) {
- return AtomicWaitResult::Woken;
+ return AtomicWaitResult::NotEqual;
}
- if timeout.is_some_and(|timeout| start.elapsed() >= timeout) {
- return AtomicWaitResult::TimedOut;
+ let waiter = Arc::new(Waiter {
+ woken: AtomicBool::new(false),
+ condition: Condvar::new(),
+ });
+ lists.entry(address).or_default().push_back(waiter.clone());
+ loop {
+ let interval = match deadline {
+ Some(deadline) => {
+ let remaining = deadline.saturating_duration_since(Instant::now());
+ if remaining.is_zero() {
+ remove(&mut lists, address, &waiter);
+ return AtomicWaitResult::TimedOut;
+ }
+ remaining.min(POLL_INTERVAL)
+ }
+ None => POLL_INTERVAL,
+ };
+ lists = waiter
+ .condition
+ .wait_timeout(lists, interval)
+ .unwrap_or_else(|error| error.into_inner())
+ .0;
+ // A notify removed the waiter from its list before setting this.
+ if waiter.woken.load(Ordering::Relaxed) {
+ return AtomicWaitResult::Woken;
+ }
+ if !word_equals(word, expected) {
+ remove(&mut lists, address, &waiter);
+ return AtomicWaitResult::Woken;
+ }
}
}
+
+ pub(super) fn notify(address: *mut u32, max_count: usize) -> usize {
+ let mut lists = lists();
+ let address = address.addr();
+ let Some(list) = lists.get_mut(&address) else {
+ return 0;
+ };
+ let count = max_count.min(list.len());
+ for waiter in list.drain(..count) {
+ waiter.woken.store(true, Ordering::Relaxed);
+ waiter.condition.notify_one();
+ }
+ if list.is_empty() {
+ lists.remove(&address);
+ }
+ count
+ }
}
#[cfg(target_os = "macos")]
@@ -134,7 +213,7 @@ pub(crate) fn atomic_wait(word: WaitWord<'_>, expected: u64, timeout: Option<Dur
// (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).
+ // (Linux's kernel futex and the waiter lists don't have it).
if !word_equals(word, expected) {
return AtomicWaitResult::NotEqual;
}
@@ -196,15 +275,12 @@ pub(crate) fn atomic_wait(word: WaitWord<'_>, expected: u64, timeout: Option<Dur
if error == libc::EAGAIN {
return AtomicWaitResult::NotEqual;
}
- // os_sync couldn't key this memory (rare once faulted in above); fall back to polling for a change.
+ // os_sync couldn't key this memory (rare once faulted in above); fall back to the waiter lists.
break;
}
}
- if let Some(deadline) = deadline {
- let remaining = deadline.saturating_duration_since(Instant::now());
- return poll_wait(word, expected, Some(remaining));
- }
- poll_wait(word, expected, timeout)
+ let remaining = deadline.map(|deadline| deadline.saturating_duration_since(Instant::now()));
+ waiter_list::wait(word, expected, remaining.or(timeout))
}
#[cfg(target_os = "macos")]
@@ -212,13 +288,13 @@ 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.
+ // NB: Waiters that os_sync could not serve wait in the fallback's lists.
+ let mut woken = waiter_list::notify(word.as_ptr(), max_count);
let Some(functions) = os_sync::functions() else {
- // The poll_wait fallback observes value changes directly — so no explicit wake is required.
- return 0;
+ return woken;
};
// os_sync wakes a single waiter at a time. So, wake up to max_count of them — stopping once there are none left.
// ENOENT is that stop: it means the wait set is empty.
- let mut woken = 0;
while woken < max_count {
// SAFETY: The address is the aligned word of a shared typed array element.
let result = unsafe {
@@ -240,7 +316,7 @@ pub(crate) fn atomic_notify(word: &AtomicU32, max_count: usize) -> usize {
#[cfg(target_os = "linux")]
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.
+ // spec orders before "timed-out"), and so 8-byte waits share one compare.
if !word_equals(word, expected) {
return AtomicWaitResult::NotEqual;
}
@@ -310,15 +386,38 @@ pub(crate) fn atomic_notify(word: &AtomicU32, max_count: usize) -> usize {
usize::try_from(result).unwrap_or(0)
}
-// 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.
+// No native wait/wake primitive is wired up on this platform.
#[cfg(not(any(target_os = "macos", target_os = "linux")))]
pub(crate) fn atomic_wait(word: WaitWord<'_>, expected: u64, timeout: Option<Duration>) -> AtomicWaitResult {
- poll_wait(word, expected, timeout)
+ waiter_list::wait(word, expected, timeout)
}
#[cfg(not(any(target_os = "macos", target_os = "linux")))]
-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
+pub(crate) fn atomic_notify(word: &AtomicU32, max_count: usize) -> usize {
+ waiter_list::notify(word.as_ptr(), max_count)
+}
+
+#[cfg(all(test, not(target_os = "linux")))]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn waiter_lists_wake_waiters_of_a_word_that_did_not_change() {
+ static WORD: AtomicU32 = AtomicU32::new(0);
+ let waiter = std::thread::spawn(|| waiter_list::wait(WaitWord::Word32(&WORD), 0, None));
+ // The waiter is in its list once a notify wakes it.
+ while waiter_list::notify(WORD.as_ptr(), 1) == 0 {
+ std::thread::yield_now();
+ }
+ assert_eq!(waiter.join().unwrap(), AtomicWaitResult::Woken);
+ assert_eq!(WORD.load(Ordering::SeqCst), 0);
+ }
+
+ #[test]
+ fn waiter_lists_time_out() {
+ static WORD: AtomicU32 = AtomicU32::new(0);
+ let result = waiter_list::wait(WaitWord::Word32(&WORD), 0, Some(Duration::from_millis(1)));
+ assert_eq!(result, AtomicWaitResult::TimedOut);
+ assert_eq!(waiter_list::notify(WORD.as_ptr(), 1), 0);
+ }
}
diff --git a/Libraries/LibWasm/Engine/src/capi.rs b/Libraries/LibWasm/Engine/src/capi.rs
index 4df897ed8e9..2a63988bb62 100644
--- a/Libraries/LibWasm/Engine/src/capi.rs
+++ b/Libraries/LibWasm/Engine/src/capi.rs
@@ -694,6 +694,10 @@ impl HostFunction for HostFunctionData {
fn visit_edges(&self, visitor: &Visitor) {
unsafe { (self.visit)(self.user_data, visitor.raw()) };
}
+
+ fn user_data(&self) -> *mut c_void {
+ self.user_data
+ }
}
/// Add a host function of the given type to the store, and return its cell. The function visits what its user data
@@ -1360,6 +1364,22 @@ pub unsafe extern "C" fn wasm_store_function_index(
true
}
+/// The user data a host function was allocated with, or null if the function is no host function.
+///
+/// # Safety
+///
+/// `store` must be a live store with a function at `function`.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn wasm_store_host_function_user_data(
+ store: *mut WasmStore,
+ function: *mut c_void,
+) -> *mut c_void {
+ match &store_of(store).function(entity(function)).kind {
+ FunctionKind::Host(callback) => callback.user_data(),
+ FunctionKind::Wasm { .. } => core::ptr::null_mut(),
+ }
+}
+
/// The handle of the LibGC primitive storage a memory lives in, or zero if the store has no heap.
///
/// # Safety
@@ -1411,6 +1431,17 @@ pub unsafe extern "C" fn wasm_store_set_can_block(store: *mut WasmStore, can_blo
store_of(store).can_block = can_block;
}
+/// Has `cell`, an entity, or an exception or a GC object (whose references are their cells), keep the embedder's cell
+/// `object` alive for as long as it lives itself.
+///
+/// # Safety
+///
+/// `cell` must be a live cell of a store with a LibGC heap, and `object` a cell of the same heap.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn wasm_set_host_object(cell: *mut c_void, object: *mut c_void) {
+ unsafe { crate::runtime::heap::set_host_object(cell.cast(), object) };
+}
+
// WASI.
/// The state of a WASI command, whose functions a store gets with `wasm_wasi_allocate_function()`.
diff --git a/Libraries/LibWasm/Engine/src/runtime/entity.rs b/Libraries/LibWasm/Engine/src/runtime/entity.rs
index f9315573152..14e8f700aae 100644
--- a/Libraries/LibWasm/Engine/src/runtime/entity.rs
+++ b/Libraries/LibWasm/Engine/src/runtime/entity.rs
@@ -11,7 +11,7 @@
//!
//! The first word of an entity's cell says what it is, so that a handle an embedder passes in can be checked.
-use super::heap::{CELL_HEADER_SIZE, CellType, Heap, Visitor};
+use super::heap::{CELL_HEADER_SIZE, CellType, Heap, Visitor, forget_host_object, visit_host_object};
use super::memory::MemoryInstance;
use super::{FunctionInstance, FunctionKind, GlobalInstance, Instance, TableInstance, TagInstance};
use core::ffi::c_void;
@@ -167,6 +167,7 @@ pub unsafe extern "C" fn entity_visit_edges(cell: *mut c_void, visitor: *mut c_v
unsafe { handle.get() }.visit_edges(&Visitor::new(visitor));
}
unsafe {
+ visit_host_object(cell, &Visitor::new(visitor));
match kind_of(cell) {
ENTITY_FUNCTION => visit::<FunctionInstance>(cell, visitor),
ENTITY_TABLE => visit::<TableInstance>(cell, visitor),
@@ -194,6 +195,7 @@ pub unsafe extern "C" fn destroy_entity(cell: *mut u8) {
}
}
unsafe {
+ forget_host_object(cell.cast());
match kind_of(cell.cast()) {
ENTITY_FUNCTION => destroy::<FunctionInstance>(cell),
ENTITY_TABLE => destroy::<TableInstance>(cell),
diff --git a/Libraries/LibWasm/Engine/src/runtime/gc.rs b/Libraries/LibWasm/Engine/src/runtime/gc.rs
index c25f6052ea4..ff75896f709 100644
--- a/Libraries/LibWasm/Engine/src/runtime/gc.rs
+++ b/Libraries/LibWasm/Engine/src/runtime/gc.rs
@@ -14,7 +14,7 @@
use super::heap::{
CELL_HEADER_SIZE, CellFunctions, CellType, Heap, TRACE_FUNCTION, TRACE_NONE, TRACE_REFERENCE, Visitor,
- object_size_class,
+ forget_host_object, object_size_class, visit_host_object,
};
use super::{Store, TagAddress, Value};
pub use crate::abi::EXCEPTION_CELL_SIZE;
@@ -241,6 +241,7 @@ unsafe fn out_of_line_data(cell: *const c_void) -> Option<(*mut u64, usize)> {
unsafe extern "C" fn object_visit_edges(cell: *mut c_void, visitor: *mut c_void) {
let visitor = Visitor::new(visitor);
unsafe {
+ visit_host_object(cell, &visitor);
let rtt: *const Rtt = read(cell, 0);
visitor.visit_cell(cell_of_rtt(rtt));
let rtt = &*rtt;
@@ -267,6 +268,7 @@ unsafe extern "C" fn object_visit_edges(cell: *mut c_void, visitor: *mut c_void)
unsafe extern "C" fn object_destroy(cell: *mut c_void) {
unsafe {
+ forget_host_object(cell);
if let Some((block, words)) = out_of_line_data(cell) {
free(block, words);
}
@@ -318,6 +320,7 @@ pub fn exception(reference: u64) -> Exception {
unsafe extern "C" fn exception_visit_edges(cell: *mut c_void, visitor: *mut c_void) {
let visitor = Visitor::new(visitor);
unsafe {
+ visit_host_object(cell, &visitor);
let payload: *const u64 = read(cell, EXCEPTION_PAYLOAD_OFFSET);
let length: u64 = read(cell, EXCEPTION_LENGTH_OFFSET);
let kinds: *const u8 = read(cell, EXCEPTION_KINDS_OFFSET);
@@ -331,6 +334,7 @@ unsafe extern "C" fn exception_visit_edges(cell: *mut c_void, visitor: *mut c_vo
unsafe extern "C" fn exception_destroy(cell: *mut c_void) {
unsafe {
+ forget_host_object(cell);
let length: u64 = read(cell, EXCEPTION_LENGTH_OFFSET);
free(read::<*const u64>(cell, EXCEPTION_PAYLOAD_OFFSET), length as usize);
free(read::<*const u8>(cell, EXCEPTION_KINDS_OFFSET), length as usize);
diff --git a/Libraries/LibWasm/Engine/src/runtime/heap.rs b/Libraries/LibWasm/Engine/src/runtime/heap.rs
index 17a998c4004..aab8fda86f7 100644
--- a/Libraries/LibWasm/Engine/src/runtime/heap.rs
+++ b/Libraries/LibWasm/Engine/src/runtime/heap.rs
@@ -107,6 +107,57 @@ pub const CELL_HEADER_SIZE: usize = 16;
const CELL_STATE_LIVE: u8 = 0;
const CELL_KIND_OTHER: u8 = 0;
+/// The byte after LibGC's in a cell, which holds the runtime's flags for the cell.
+const CELL_FLAGS_OFFSET: usize = 11;
+/// The cell keeps an object of the embedder's alive (see set_host_object()).
+const CELL_FLAG_HOST_OBJECT: u8 = 1;
+
+thread_local! {
+ /// The object of the embedder's each cell of this thread's heap keeps alive, by cell.
+ static HOST_OBJECTS: core::cell::RefCell<std::collections::HashMap<usize, *mut c_void>> = Default::default();
+}
+
+/// Have `cell` keep the embedder's cell `object` alive for as long as it lives itself, as an edge the collector follows
+/// from it. An embedder's object that stands for `cell` and refers to it then stays the same object while `cell` lives,
+/// and goes away with it.
+///
+/// # Safety
+///
+/// `cell` must be a live cell of the runtime, and `object` a cell of the same LibGC heap.
+pub unsafe fn set_host_object(cell: *mut u8, object: *mut c_void) {
+ HOST_OBJECTS.with_borrow_mut(|objects| objects.insert(cell.addr(), object));
+ unsafe { *cell.add(CELL_FLAGS_OFFSET) |= CELL_FLAG_HOST_OBJECT };
+}
+
+/// Visit the object `cell` keeps alive, if it keeps one.
+///
+/// # Safety
+///
+/// `cell` must be a live cell of the runtime.
+pub unsafe fn visit_host_object(cell: *mut c_void, visitor: &Visitor) {
+ if unsafe { *cell.cast::<u8>().add(CELL_FLAGS_OFFSET) } & CELL_FLAG_HOST_OBJECT == 0 {
+ return;
+ }
+ if let Some(object) = HOST_OBJECTS.with_borrow(|objects| objects.get(&cell.addr()).copied()) {
+ visitor.visit_cell(object.cast());
+ }
+}
+
+/// Forget the object `cell` keeps alive, as `cell` is going away.
+///
+/// # Safety
+///
+/// `cell` must be a cell of the runtime.
+pub unsafe fn forget_host_object(cell: *mut c_void) {
+ let flags = unsafe { &mut *cell.cast::<u8>().add(CELL_FLAGS_OFFSET) };
+ if *flags & CELL_FLAG_HOST_OBJECT == 0 {
+ return;
+ }
+ *flags &= !CELL_FLAG_HOST_OBJECT;
+ // NB: A thread's cells are destroyed on the thread, unless it is exiting, when its table is gone already.
+ let _ = HOST_OBJECTS.try_with(|objects| objects.borrow_mut().remove(&cell.addr()));
+}
+
/// The cell types of the runtime, in the order of their allocators.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum CellType {
@@ -301,6 +352,16 @@ impl Heap {
layout.cell_mark_offset as usize >= 8 && (layout.cell_kind_offset as usize) < CELL_HEADER_SIZE,
"LibGC keeps its cell header in the second word"
);
+ assert!(
+ [
+ layout.cell_mark_offset,
+ layout.cell_state_offset,
+ layout.cell_kind_offset
+ ]
+ .iter()
+ .all(|&offset| (offset as usize) < CELL_FLAGS_OFFSET),
+ "the runtime's flags follow LibGC's cell header"
+ );
let allocators = ALLOCATORS.get_or_init(|| Allocators::new(&interface, functions));
FUNCTIONS.get_or_init(|| Functions(interface));
Self::Gc(Box::new(GcHeap {
diff --git a/Libraries/LibWasm/Engine/src/runtime/mod.rs b/Libraries/LibWasm/Engine/src/runtime/mod.rs
index f2be4ab66e9..0366658daac 100644
--- a/Libraries/LibWasm/Engine/src/runtime/mod.rs
+++ b/Libraries/LibWasm/Engine/src/runtime/mod.rs
@@ -177,6 +177,11 @@ pub trait HostFunction {
/// Visit the cells the function refers to, which its function keeps alive.
fn visit_edges(&self, _visitor: &heap::Visitor) {}
+
+ /// The data of the embedder's of a function made through the C interface.
+ fn user_data(&self) -> *mut core::ffi::c_void {
+ core::ptr::null_mut()
+ }
}
impl<F: Fn(&mut Store, &[Value]) -> Result<Vec<Value>, Trap>> HostFunction for F {
diff --git a/Libraries/LibWasm/Engine/src/wasi.rs b/Libraries/LibWasm/Engine/src/wasi.rs
index 2c431264a89..18736125255 100644
--- a/Libraries/LibWasm/Engine/src/wasi.rs
+++ b/Libraries/LibWasm/Engine/src/wasi.rs
@@ -48,6 +48,19 @@ pub struct Wasi {
exit_code: Cell<Option<i32>>,
}
+impl Drop for Wasi {
+ fn drop(&mut self) {
+ // The descriptors path_open created that the guest left open, and the preopens something opened, are the
+ // state's own.
+ for file in self.files.get_mut().values().filter(|file| file.owned) {
+ let _ = platform::close(file.host_fd);
+ }
+ for fd in self.preopens.iter().filter_map(|preopen| preopen.host_fd.get()) {
+ let _ = platform::close(fd);
+ }
+ }
+}
+
/// A guest descriptor's host descriptor.
#[derive(Clone, Copy)]
struct File {
@@ -467,6 +480,8 @@ mod platform {
/// Whether `directory` is a descriptor of the resolution's own, which it closes.
owned: bool,
name: CString,
+ /// Whether the path ended in a slash, which only a directory may be named with.
+ must_be_directory: bool,
}
impl Drop for Beneath {
@@ -495,13 +510,17 @@ mod platform {
if length < 0 {
return Err(last_errno());
}
+ // NB: readlinkat() truncates a target that does not fit without saying so.
+ if length as usize == target.len() {
+ return Err(errno_of(libc::ENAMETOOLONG));
+ }
target.truncate(length as usize);
Ok(Some(target))
}
/// Resolves `path` beneath the directory `base`, one component at a time, so that it never leaves it: absolute
/// paths and symbolic links, and `..` above `base`, are not capable. Symbolic links in the middle are followed
- /// (beneath `base`), and the last one too if `follow_last`.
+ /// (beneath `base`), and the last one too if `follow_last`, or if the path ends in a slash, as POSIX resolves it.
fn resolve_beneath(base: i32, path: &[u8], follow_last: bool) -> Result<Beneath, Errno> {
if path.is_empty() {
return Err(errno_of(libc::ENOENT));
@@ -517,6 +536,7 @@ mod platform {
}
};
let mut queue: VecDeque<Vec<u8>> = components(path).map(<[u8]>::to_vec).collect();
+ let mut must_be_directory = path.last() == Some(&b'/');
let mut links = 0;
let result = loop {
let Some(component) = queue.pop_front() else {
@@ -537,7 +557,7 @@ mod platform {
Err(errno) => break Err(errno),
};
let last = queue.is_empty();
- if !last || follow_last {
+ if !last || follow_last || must_be_directory {
match link_target(current, &name) {
Ok(Some(target)) => {
links += 1;
@@ -547,6 +567,9 @@ mod platform {
if target.first() == Some(&b'/') {
break Err(ERRNO_NOTCAPABLE);
}
+ if last && target.last() == Some(&b'/') {
+ must_be_directory = true;
+ }
for component in components(&target).rev() {
queue.push_front(component.to_vec());
}
@@ -579,6 +602,7 @@ mod platform {
directory: directory.unwrap_or(base),
owned: directory.is_some(),
name,
+ must_be_directory,
})
}
Err(errno) => {
@@ -681,6 +705,13 @@ mod platform {
if options.open_flags & OFLAGS_DIRECTORY != 0 {
flags = libc::O_RDONLY | libc::O_DIRECTORY | libc::O_CLOEXEC;
}
+ if resolved.must_be_directory {
+ // NB: As on Linux, a file cannot be created with a name that ends in a slash.
+ if options.open_flags & OFLAGS_CREAT != 0 {
+ return Err(errno_of(libc::EISDIR));
+ }
+ flags |= libc::O_DIRECTORY;
+ }
if options.open_flags & OFLAGS_CREAT != 0 {
flags |= libc::O_CREAT;
}
@@ -801,6 +832,9 @@ mod platform {
if unsafe { libc::fstatat(directory, name, &raw mut status, libc::AT_SYMLINK_NOFOLLOW) } != 0 {
return Err(last_errno());
}
+ if resolved.must_be_directory && status.st_mode & libc::S_IFMT != libc::S_IFDIR {
+ return Err(errno_of(libc::ENOTDIR));
+ }
Ok(status_of(&status))
}
diff --git a/Libraries/LibWasm/Engine/tests/wasi.rs b/Libraries/LibWasm/Engine/tests/wasi.rs
index 2f6669fb408..8f8d897a43e 100644
--- a/Libraries/LibWasm/Engine/tests/wasi.rs
+++ b/Libraries/LibWasm/Engine/tests/wasi.rs
@@ -231,3 +231,43 @@ fn directories_and_status_stay_beneath_their_preopen() {
assert_eq!(guest.call("path_filestat_get", &arguments), errno, "{path}");
}
}
+
+const ERRNO_ISDIR: i32 = 31;
+const ERRNO_NOTDIR: i32 = 54;
+
+#[test]
+fn trailing_slashes_name_only_directories() {
+ let tree = Tree::new("slash");
+ let mut guest = tree.guest();
+ assert_eq!(guest.open(3, "sub/", false, 0), ERRNO_SUCCESS);
+ assert_eq!(guest.open(3, "inside.txt/", false, 0), ERRNO_NOTDIR);
+ // A trailing slash follows the link in the last place, beneath the preopen only.
+ assert_eq!(guest.open(3, "link_in/", false, 0), ERRNO_NOTDIR);
+ assert_eq!(guest.open(3, "link_out/", false, 0), ERRNO_NOTCAPABLE);
+ assert_eq!(guest.open(3, "created/", false, OFLAGS_CREAT), ERRNO_ISDIR);
+ assert!(!tree.0.join("sandbox/created").exists());
+ for (path, errno) in [
+ ("sub/", ERRNO_SUCCESS),
+ ("inside.txt/", ERRNO_NOTDIR),
+ ("link_in/", ERRNO_NOTDIR),
+ ] {
+ let length = guest.path(path);
+ let arguments = [
+ Value::I32(3),
+ Value::I32(0),
+ Value::I32(16),
+ Value::I32(length),
+ Value::I32(1024),
+ ];
+ assert_eq!(guest.call("path_filestat_get", &arguments), errno, "{path}");
+ }
+ let length = guest.path("sub/made/");
+ assert_eq!(
+ guest.call(
+ "path_create_directory",
+ &[Value::I32(3), Value::I32(16), Value::I32(length)]
+ ),
+ ERRNO_SUCCESS
+ );
+ assert!(tree.0.join("sandbox/sub/made").is_dir());
+}
diff --git a/Libraries/LibWasm/Runtime.cpp b/Libraries/LibWasm/Runtime.cpp
index bdb6bf7f48c..c190173e4b1 100644
--- a/Libraries/LibWasm/Runtime.cpp
+++ b/Libraries/LibWasm/Runtime.cpp
@@ -171,8 +171,11 @@ static Entity entity_from_ffi(void* cell) { return static_cast<GC::ForeignCell*>
namespace {
struct HostFunctionData {
+ AK_ALLOC_WITH_KMALLOC;
+
Store& store;
Store::HostFunction function;
+ Optional<u32> index;
};
}
@@ -205,7 +208,7 @@ static void release_host_function(void* user_data)
delete static_cast<HostFunctionData*>(user_data);
}
-Entity Store::allocate_host_function(FunctionType const& type, HostFunction function)
+Entity Store::allocate_host_function(FunctionType const& type, HostFunction function, Optional<u32> index)
{
Vector<FFI::WasmValueType> parameters;
Vector<FFI::WasmValueType> results;
@@ -213,10 +216,18 @@ Entity Store::allocate_host_function(FunctionType const& type, HostFunction func
parameters.append(to_ffi(parameter));
for (auto result : type.results)
results.append(to_ffi(result));
- auto* data = new HostFunctionData { *this, move(function) };
+ auto* data = new HostFunctionData { *this, move(function), index };
return entity_from_ffi(FFI::wasm_store_allocate_host_function(m_store, parameters.data(), parameters.size(), results.data(), results.size(), call_host_function, visit_host_function, release_host_function, data));
}
+Optional<u32> Store::host_function_index(Entity function)
+{
+ auto* data = FFI::wasm_store_host_function_user_data(m_store, to_ffi(function));
+ if (!data)
+ return {};
+ return static_cast<HostFunctionData*>(data)->index;
+}
+
Optional<Entity> Store::allocate_memory(Limits limits)
{
void* memory = nullptr;
@@ -430,6 +441,16 @@ void Store::set_can_block(bool can_block)
FFI::wasm_store_set_can_block(m_store, can_block);
}
+void Store::set_host_object(GC::ForeignCell* cell, GC::Cell& object)
+{
+ FFI::wasm_set_host_object(cell, &object);
+}
+
+void Store::set_host_object(GC::ForeignCell* cell, GC::ForeignCell& object)
+{
+ FFI::wasm_set_host_object(cell, &object);
+}
+
u64 Store::table_size(Entity table)
{
return FFI::wasm_store_table_size(m_store, to_ffi(table));
diff --git a/Libraries/LibWasm/Runtime.h b/Libraries/LibWasm/Runtime.h
index 946ffae6ef7..268c71e08c4 100644
--- a/Libraries/LibWasm/Runtime.h
+++ b/Libraries/LibWasm/Runtime.h
@@ -240,7 +240,8 @@ public:
// function visits the cells it captures, so it must not capture roots.
using HostFunction = Function<ErrorOr<void, HostError>(Store&, ReadonlySpan<Value> arguments, Span<Value> results)>;
- Entity allocate_host_function(FunctionType const&, HostFunction);
+ // `index` is the embedder's index of the host function, if it has one, which host_function_index() returns.
+ Entity allocate_host_function(FunctionType const&, HostFunction, Optional<u32> index = {});
Optional<Entity> allocate_memory(Limits);
Optional<Entity> allocate_table(ValueType element, Limits, u64 initial);
Entity allocate_global(ValueType, bool is_mutable, Value);
@@ -258,6 +259,8 @@ public:
// The index of a WebAssembly function in the function index space of the module that defines it, or nothing for
// a host function.
Optional<u32> function_index(Entity function);
+ // The index a host function was allocated with, or nothing.
+ Optional<u32> host_function_index(Entity function);
// The types of functions, tables, globals, and tags of the store name concrete heap types by store-wide
// identities, where the types of a module name them by their indices in the module. This is a type of `module`
@@ -286,6 +289,10 @@ public:
void set_memory_grow_callback(Function<void(Entity memory)>);
// Whether the agent the store runs code for may block ([[CanBlock]]); memory.atomic.wait traps where it may not.
void set_can_block(bool);
+ // Has an entity, or the cell of an exception or a GC object, keep `object` alive for as long as it lives itself.
+ // An object that stands for the cell and refers to it then stays the same object while the cell lives.
+ void set_host_object(GC::ForeignCell* cell, GC::Cell& object);
+ void set_host_object(GC::ForeignCell* cell, GC::ForeignCell& object);
u64 table_size(Entity table);
ValueType table_element_type(Entity table);
diff --git a/Libraries/LibWeb/Bindings/HostDefined.cpp b/Libraries/LibWeb/Bindings/HostDefined.cpp
index f2d53ccd3d9..618c1f3797f 100644
--- a/Libraries/LibWeb/Bindings/HostDefined.cpp
+++ b/Libraries/LibWeb/Bindings/HostDefined.cpp
@@ -7,6 +7,7 @@
#include <LibWeb/Bindings/HostDefined.h>
#include <LibWeb/Bindings/Intrinsics.h>
#include <LibWeb/Bindings/WrapperWorld.h>
+#include <LibWeb/WebAssembly/Tag.h>
namespace Web::Bindings {
@@ -31,6 +32,7 @@ void HostDefined::visit_edges(Cell::Visitor& visitor)
visitor.visit(intrinsics);
visitor.visit(wrapper_world);
visitor.visit(principal_realm);
+ visitor.visit(wasm_js_tag);
}
}
diff --git a/Libraries/LibWeb/Bindings/HostDefined.h b/Libraries/LibWeb/Bindings/HostDefined.h
index ef81f2091d5..b1b9b64a5e4 100644
--- a/Libraries/LibWeb/Bindings/HostDefined.h
+++ b/Libraries/LibWeb/Bindings/HostDefined.h
@@ -37,6 +37,9 @@ public:
// Principal realms point this at themselves via PrincipalHostDefined's construction path. Non-principal realms must
// point at an already-created principal realm with a PrincipalHostDefined.
GC::Ref<JS::Realm> principal_realm;
+ // The Tag object of the JavaScript exception tag in this realm. The tag lives as long as the agent, but a Tag object
+ // belongs to the realm it is first wrapped in, so each realm has one of its own.
+ GC::Ptr<WebAssembly::Tag> wasm_js_tag;
protected:
HostDefined(GC::Ref<Intrinsics> intrinsics, GC::Ref<WrapperWorld> wrapper_world, GC::Ref<JS::Realm> principal_realm, PrincipalRealmUnderConstruction principal_realm_under_construction = PrincipalRealmUnderConstruction::No);
diff --git a/Libraries/LibWeb/Forward.h b/Libraries/LibWeb/Forward.h
index cfedd36d3b2..3e6e59646e1 100644
--- a/Libraries/LibWeb/Forward.h
+++ b/Libraries/LibWeb/Forward.h
@@ -1236,6 +1236,7 @@ class Instance;
class Memory;
class Module;
class Table;
+class Tag;
namespace Detail {
diff --git a/Libraries/LibWeb/WebAssembly/Instance.cpp b/Libraries/LibWeb/WebAssembly/Instance.cpp
index daf7becc3e9..185ad0d0364 100644
--- a/Libraries/LibWeb/WebAssembly/Instance.cpp
+++ b/Libraries/LibWeb/WebAssembly/Instance.cpp
@@ -33,16 +33,17 @@ GC_DEFINE_ALLOCATOR(Instance);
WebIDL::ExceptionOr<GC::Ref<Instance>> Instance::create(JS::Realm& realm, Module& module, GC::Ptr<JS::Object> import_object)
{
auto instance = TRY(Detail::instantiate_module(realm.vm(), *module.compiled_module()->module, import_object));
- return Instance::create(instance);
+ return Instance::create(realm, instance);
}
-GC::Ref<Instance> Instance::create(Wasm::Runtime::Entity instance)
+GC::Ref<Instance> Instance::create(JS::Realm& realm, Wasm::Runtime::Entity instance)
{
- return GC::Heap::the().allocate<Instance>(instance);
+ return GC::Heap::the().allocate<Instance>(Bindings::host_defined_wrapper_world(realm), instance);
}
-Instance::Instance(Wasm::Runtime::Entity instance)
+Instance::Instance(Bindings::WrapperWorld& wrapper_world, Wasm::Runtime::Entity instance)
: m_instance(instance)
+ , m_wrapper_world(wrapper_world)
{
}
@@ -73,6 +74,7 @@ void Instance::visit_edges(Visitor& visitor)
{
Base::visit_edges(visitor);
visitor.visit(m_instance);
+ visitor.visit(m_wrapper_world);
}
}
@@ -141,7 +143,7 @@ static GC::Ref<JS::Object> create_exports_object(JS::Realm& realm, WebAssembly::
exports->define_direct_property(name, table(realm, instance.table_instance(address)), JS::default_attributes);
break;
case Wasm::Runtime::ExternKind::Tag:
- exports->define_direct_property(name, wrap(host_defined_wrapper_world(realm), realm, WebAssembly::Tag::from_address(address)), JS::default_attributes);
+ exports->define_direct_property(name, wrap(host_defined_wrapper_world(realm), realm, WebAssembly::Tag::from_address(realm, address)), JS::default_attributes);
break;
}
}
@@ -152,6 +154,8 @@ static GC::Ref<JS::Object> create_exports_object(JS::Realm& realm, WebAssembly::
GC::Ref<JS::Object const> exports(JS::Realm& realm, GC::Ref<WebAssembly::Instance> instance)
{
+ // NB: An instance's exports, like its memories and tables, belong to the world it was created in.
+ VERIFY(&host_defined_wrapper_world(realm) == &instance->wrapper_world());
auto& cache = instance_exports_cache_for(instance);
if (cache.exports)
diff --git a/Libraries/LibWeb/WebAssembly/Instance.h b/Libraries/LibWeb/WebAssembly/Instance.h
index 170f54ae664..22e557b5342 100644
--- a/Libraries/LibWeb/WebAssembly/Instance.h
+++ b/Libraries/LibWeb/WebAssembly/Instance.h
@@ -22,19 +22,22 @@ class Instance : public Bindings::GCAllocatedWrappable {
public:
static WebIDL::ExceptionOr<GC::Ref<Instance>> create(JS::Realm&, Module& module, GC::Ptr<JS::Object> import_object);
- static GC::Ref<Instance> create(Wasm::Runtime::Entity instance);
+ static GC::Ref<Instance> create(JS::Realm&, Wasm::Runtime::Entity instance);
Wasm::Runtime::Entity instance_address() const { return m_instance; }
+ // The world of the realm the instance was created in, the only one whose realms may read its exports.
+ Bindings::WrapperWorld const& wrapper_world() const { return *m_wrapper_world; }
GC::Ref<Global> global_instance(Wasm::Runtime::Entity);
GC::Ref<Memory> memory_instance(Wasm::Runtime::Entity);
GC::Ref<Table> table_instance(Wasm::Runtime::Entity);
private:
- explicit Instance(Wasm::Runtime::Entity instance);
+ Instance(Bindings::WrapperWorld&, Wasm::Runtime::Entity instance);
virtual void visit_edges(Visitor&) override;
Wasm::Runtime::Entity m_instance { nullptr };
+ GC::Ref<Bindings::WrapperWorld> m_wrapper_world;
};
}
diff --git a/Libraries/LibWeb/WebAssembly/Tag.cpp b/Libraries/LibWeb/WebAssembly/Tag.cpp
index b7484ab2079..fe3406dd720 100644
--- a/Libraries/LibWeb/WebAssembly/Tag.cpp
+++ b/Libraries/LibWeb/WebAssembly/Tag.cpp
@@ -5,6 +5,7 @@
*/
#include <LibGC/Heap.h>
+#include <LibWeb/Bindings/HostDefined.h>
#include <LibWeb/Bindings/Tag.h>
#include <LibWeb/WebAssembly/BindingsGlue.h>
#include <LibWeb/WebAssembly/Global.h>
@@ -23,11 +24,24 @@ GC::Ref<Tag> Tag::create(ReadonlySpan<Wasm::Runtime::ValueType> parameters)
auto tag = Detail::WebAssemblyCache::the().store().allocate_tag(parameters);
// 7. Initialize this from tagAddress.
- return from_address(tag);
+ return from_address_in_agent(tag);
+}
+
+GC::Ref<Tag> Tag::from_address(JS::Realm& realm, Wasm::Runtime::Entity tag)
+{
+ // NB: The JavaScript exception tag lives as long as the agent, while a Tag object belongs to the realm it is first
+ // wrapped in, so every realm has a Tag object of its own for it.
+ if (tag == Detail::WebAssemblyCache::the().js_tag()) {
+ auto& host_defined = Bindings::host_defined_of(realm);
+ if (!host_defined.wasm_js_tag)
+ host_defined.wasm_js_tag = GC::Heap::the().allocate<Tag>(tag);
+ return *host_defined.wasm_js_tag;
+ }
+ return from_address_in_agent(tag);
}
// https://webassembly.github.io/spec/js-api/#create-a-tag-object
-GC::Ref<Tag> Tag::from_address(Wasm::Runtime::Entity tag)
+GC::Ref<Tag> Tag::from_address_in_agent(Wasm::Runtime::Entity tag)
{
// 1. Let map be the surrounding agent's associated tag object cache.
// 2. If map[tagAddress] exists,
diff --git a/Libraries/LibWeb/WebAssembly/Tag.h b/Libraries/LibWeb/WebAssembly/Tag.h
index c54acbdb242..adb73476c68 100644
--- a/Libraries/LibWeb/WebAssembly/Tag.h
+++ b/Libraries/LibWeb/WebAssembly/Tag.h
@@ -19,13 +19,16 @@ class Tag : public Bindings::GCAllocatedWrappable {
public:
static GC::Ref<Tag> create(ReadonlySpan<Wasm::Runtime::ValueType> parameters);
// The Tag object of a tag, which is the same object for as long as it lives.
- static GC::Ref<Tag> from_address(Wasm::Runtime::Entity tag);
+ static GC::Ref<Tag> from_address(JS::Realm&, Wasm::Runtime::Entity tag);
Wasm::Runtime::Entity address() const { return m_tag; }
private:
explicit Tag(Wasm::Runtime::Entity tag);
+ // The Tag object of a tag other than the JavaScript exception tag, from the agent's tag object cache.
+ static GC::Ref<Tag> from_address_in_agent(Wasm::Runtime::Entity tag);
+
virtual void visit_edges(Visitor&) override;
Wasm::Runtime::Entity m_tag { nullptr };
diff --git a/Libraries/LibWeb/WebAssembly/WebAssembly.cpp b/Libraries/LibWeb/WebAssembly/WebAssembly.cpp
index a150e1b26f0..b9bf1f3d752 100644
--- a/Libraries/LibWeb/WebAssembly/WebAssembly.cpp
+++ b/Libraries/LibWeb/WebAssembly/WebAssembly.cpp
@@ -97,21 +97,55 @@ void WebAssemblyCache::ObjectCache<T, Key>::for_each(Function<void(T&)> const& c
}
}
+// Exceptions and GC objects are the cells their references are the addresses of.
+static GC::ForeignCell* cell_of_reference(u64 reference)
+{
+ return reinterpret_cast<GC::ForeignCell*>(static_cast<FlatPtr>(reference));
+}
+
GC::Ptr<JS::NativeFunction> WebAssemblyCache::function_object(Entity function) const { return m_function_objects.get(function); }
-void WebAssemblyCache::set_function_object(Entity function, JS::NativeFunction& object) { m_function_objects.set(function, object); }
+void WebAssemblyCache::set_function_object(Entity function, JS::NativeFunction& object)
+{
+ m_function_objects.set(function, object);
+ m_store->set_host_object(function, object);
+}
GC::Ptr<Global> WebAssemblyCache::global_object(Entity global) const { return m_global_objects.get(global); }
-void WebAssemblyCache::set_global_object(Entity global, Global& object) { m_global_objects.set(global, object); }
+void WebAssemblyCache::set_global_object(Entity global, Global& object)
+{
+ m_global_objects.set(global, object);
+ m_store->set_host_object(global, object);
+}
GC::Ptr<Memory> WebAssemblyCache::memory_object(Entity memory) const { return m_memory_objects.get(memory); }
-void WebAssemblyCache::set_memory_object(Entity memory, Memory& object) { m_memory_objects.set(memory, object); }
+void WebAssemblyCache::set_memory_object(Entity memory, Memory& object)
+{
+ m_memory_objects.set(memory, object);
+ m_store->set_host_object(memory, object);
+}
GC::Ptr<Table> WebAssemblyCache::table_object(Entity table) const { return m_table_objects.get(table); }
-void WebAssemblyCache::set_table_object(Entity table, Table& object) { m_table_objects.set(table, object); }
+void WebAssemblyCache::set_table_object(Entity table, Table& object)
+{
+ m_table_objects.set(table, object);
+ m_store->set_host_object(table, object);
+}
void WebAssemblyCache::for_each_memory_object(Function<void(Memory&)> const& callback) const { m_memory_objects.for_each(callback); }
GC::Ptr<Tag> WebAssemblyCache::tag_object(Entity tag) const { return m_tag_objects.get(tag); }
-void WebAssemblyCache::set_tag_object(Entity tag, Tag& object) { m_tag_objects.set(tag, object); }
+void WebAssemblyCache::set_tag_object(Entity tag, Tag& object)
+{
+ m_tag_objects.set(tag, object);
+ m_store->set_host_object(tag, object);
+}
GC::Ptr<Exception> WebAssemblyCache::exception_object(u64 exception) const { return m_exception_objects.get(exception); }
-void WebAssemblyCache::set_exception_object(u64 exception, Exception& object) { m_exception_objects.set(exception, object); }
+void WebAssemblyCache::set_exception_object(u64 exception, Exception& object)
+{
+ m_exception_objects.set(exception, object);
+ m_store->set_host_object(cell_of_reference(exception), object);
+}
GC::Ptr<JS::Object> WebAssemblyCache::gc_object(u64 object) const { return m_gc_objects.get(object); }
-void WebAssemblyCache::set_gc_object(u64 object, JS::Object& gc_object) { m_gc_objects.set(object, gc_object); }
+void WebAssemblyCache::set_gc_object(u64 object, JS::Object& gc_object)
+{
+ m_gc_objects.set(object, gc_object);
+ m_store->set_host_object(cell_of_reference(object), gc_object);
+}
WebAssemblyCache::~WebAssemblyCache() = default;
@@ -170,7 +204,7 @@ void initialize(JS::Object& self, JS::Realm& realm)
// 2. Let JSTagObject be the result of creating a Tag object from JSTagAddr.
// 3. Return JSTagObject.
auto& current_realm = *vm.current_realm();
- auto tag = Tag::from_address(Detail::WebAssemblyCache::the().js_tag());
+ auto tag = Tag::from_address(current_realm, Detail::WebAssemblyCache::the().js_tag());
return Bindings::wrap(Bindings::host_defined_wrapper_world(current_realm), current_realm, tag);
};
namespace_object.define_native_accessor(realm, "JSTag"_utf16_fly_string, move(js_tag_getter), Function<JS::ThrowCompletionOr<JS::Value>(JS::VM&)> {}, JS::Attribute::Enumerable | JS::Attribute::Configurable);
@@ -272,8 +306,6 @@ static constexpr u64 I31_REFERENCE_BIT = 0b01;
static constexpr u64 HOST_REFERENCE_TAG = 0b10;
static constexpr u64 REFERENCE_TAG_MASK = 0b11;
-namespace {
-
// A JavaScript value that is not a cell, boxed so that WebAssembly can refer to it as a host value.
class ExternValueBox final : public GC::Cell {
GC_CELL(ExternValueBox, GC::Cell);
@@ -301,15 +333,25 @@ private:
GC_DEFINE_ALLOCATOR(ExternValueBox);
-}
+GC::Ptr<ExternValueBox> WebAssemblyCache::extern_value_box(JS::Value value) const { return m_extern_value_boxes.get(value); }
+void WebAssemblyCache::set_extern_value_box(JS::Value value, ExternValueBox& box) { m_extern_value_boxes.set(value, box); }
static u64 host_reference_of(JS::VM& vm, JS::Value value)
{
GC::Cell const* cell = nullptr;
- if (value.is_cell())
+ if (value.is_cell()) {
cell = &value.as_cell();
- else
- cell = vm.heap().allocate<ExternValueBox>(value).ptr();
+ } else {
+ // NB: A value gets the same box while references to the box keep it alive, so that it converts to the same
+ // reference.
+ auto& cache = WebAssemblyCache::the();
+ auto box = cache.extern_value_box(value);
+ if (!box) {
+ box = vm.heap().allocate<ExternValueBox>(value);
+ cache.set_extern_value_box(value, *box);
+ }
+ cell = box.ptr();
+ }
return static_cast<u64>(reinterpret_cast<FlatPtr>(cell)) | HOST_REFERENCE_TAG;
}
@@ -523,7 +565,7 @@ Wasm::Runtime::Entity create_host_function(JS::VM& vm, JS::FunctionObject& funct
// 2. Let stored settings be the incumbent settings object.
// 3. Let hostfunc be a host function which performs the following steps when called with arguments arguments:
// NB: The function's entity visits what the steps capture, which keeps the JavaScript function alive with it.
- auto address = cache.store().allocate_host_function(type, [&vm, function = GC::Ref { function }, type](Wasm::Runtime::Store& store, ReadonlySpan<WasmValue> arguments, Span<WasmValue> results) -> ErrorOr<void, Wasm::Runtime::HostError> {
+ auto host_function = [&vm, function = GC::Ref { function }, type](Wasm::Runtime::Store& store, ReadonlySpan<WasmValue> arguments, Span<WasmValue> results) -> ErrorOr<void, Wasm::Runtime::HostError> {
auto result = run_a_host_function(vm, function, type, arguments, results);
if (!result.is_error())
return {};
@@ -544,10 +586,8 @@ Wasm::Runtime::Entity create_host_function(JS::VM& vm, JS::FunctionObject& funct
// leaves WebAssembly.
Array<WasmValue, 1> payload { WasmValue::from_reference(value.is_null() ? 0 : host_reference_of(vm, value)) };
return Wasm::Runtime::HostError::exception(store.allocate_exception(WebAssemblyCache::the().js_tag(), payload));
- });
-
- cache.set_host_function_index(address, function_index);
- return address;
+ };
+ return cache.store().allocate_host_function(type, move(host_function), static_cast<u32>(function_index));
}
Wasm::Runtime::FunctionType function_type_in_store(Wasm::Runtime::Module const& module, u32 type_index)
@@ -940,9 +980,9 @@ Utf16FlyString name_of_webassembly_function(Wasm::Runtime::Entity function)
// 2. Assert: funcaddr is contained in moduleinst.funcaddrs.
// 3. Let index be the index of moduleinst.funcaddrs where funcaddr is found.
auto& cache = WebAssemblyCache::the();
- auto index = cache.store().function_index(function).map([](u32 index) -> size_t { return index; });
+ auto index = cache.store().function_index(function);
if (!index.has_value())
- index = cache.host_function_index(function);
+ index = cache.store().host_function_index(function);
VERIFY(index.has_value());
// 5. Return ! ToString(index).
@@ -1252,7 +1292,7 @@ GC::Ref<WebIDL::Promise> asynchronously_instantiate_webassembly_module(JS::Realm
// 2. Let instanceObject be a new Instance.
// 3. Initialize instanceObject from module and instance. If this throws an exception, catch it, reject promise with the exception, and terminate these substeps.
// FIXME: Investigate whether we are doing all the proper steps for "initialize an instance object"
- auto instance_object = Instance::create(instance);
+ auto instance_object = Instance::create(realm, instance);
// 4. Resolve promise with instanceObject.
Bindings::resolve_webassembly_instance_promise(realm, promise, instance_object);
diff --git a/Libraries/LibWeb/WebAssembly/WebAssembly.h b/Libraries/LibWeb/WebAssembly/WebAssembly.h
index 0d6f3e9eb87..f1acf53a5ba 100644
--- a/Libraries/LibWeb/WebAssembly/WebAssembly.h
+++ b/Libraries/LibWeb/WebAssembly/WebAssembly.h
@@ -43,6 +43,8 @@ WEB_API WebIDL::ExceptionOr<GC::Ref<WebIDL::Promise>> instantiate_streaming(JS::
namespace Detail {
+class ExternValueBox;
+
struct CompiledWebAssemblyModule : public RefCounted<CompiledWebAssemblyModule> {
explicit CompiledWebAssemblyModule(NonnullRefPtr<Wasm::Runtime::Module> module)
: module(move(module))
@@ -54,8 +56,9 @@ struct CompiledWebAssemblyModule : public RefCounted<CompiledWebAssemblyModule>
// The surrounding agent's associated store, and the agent's Exported Function, Global, Memory, Table, Tag, Exception, and
// Exported GC Object caches.
-// The store holds no wasm entity: each lives while the objects that stand for it, or other entities, refer to it. The
-// caches only map entities to their objects for as long as both live.
+// The store holds no wasm entity: each lives while the objects that stand for it, or other entities, refer to it. An
+// entity, exception, or GC object keeps the object of the caches that stands for it alive in turn, so that the object
+// stays the same one for as long as both live, and both go away together.
class WebAssemblyCache {
AK_MAKE_NONCOPYABLE(WebAssemblyCache);
AK_MAKE_NONMOVABLE(WebAssemblyCache);
@@ -88,17 +91,17 @@ public:
GC::Ptr<JS::Object> gc_object(u64 object) const;
void set_gc_object(u64 object, JS::Object&);
void for_each_memory_object(Function<void(WebAssembly::Memory&)> const&) const;
-
- // The index of a host function: how many functions were imported before it.
- void set_host_function_index(Entity function, size_t index) { m_host_function_indices.set(function, index); }
- Optional<size_t> host_function_index(Entity function) const { return m_host_function_indices.get(function); }
+ // The host value cache, for JavaScript values that are not cells: the box that stands for a value in WebAssembly,
+ // which it converts to for as long as the box lives.
+ GC::Ptr<ExternValueBox> extern_value_box(JS::Value) const;
+ void set_extern_value_box(JS::Value, ExternValueBox&);
private:
explicit WebAssemblyCache(GC::Heap&);
~WebAssemblyCache();
// Objects by entity, or by reference for exceptions and GC objects. An entry whose object is gone is stale: its
- // entity may be gone too, and its address reused.
+ // entity is gone too, and its address may be reused.
template<typename T, typename Key = Entity>
class ObjectCache {
public:
@@ -121,8 +124,7 @@ private:
ObjectCache<WebAssembly::Tag> m_tag_objects;
ObjectCache<WebAssembly::Exception, u64> m_exception_objects;
ObjectCache<JS::Object, u64> m_gc_objects;
- // NB: An entry outlives its function, but every host function sets its own, so a live one's entry is right.
- HashMap<Entity, size_t> m_host_function_indices;
+ ObjectCache<ExternValueBox, JS::Value> m_extern_value_boxes;
};
// https://webassembly.github.io/spec/js-api/#exported-function
diff --git a/Libraries/LibWeb/WebAssembly/WebAssemblyModule.cpp b/Libraries/LibWeb/WebAssembly/WebAssemblyModule.cpp
index 864a0caf295..fe2c45542f6 100644
--- a/Libraries/LibWeb/WebAssembly/WebAssemblyModule.cpp
+++ b/Libraries/LibWeb/WebAssembly/WebAssemblyModule.cpp
@@ -456,7 +456,7 @@ JS::ThrowCompletionOr<void> WebAssemblyModuleTraits::execute_module(JS::HostModu
auto instance_address = TRY(Detail::instantiate_core_module(vm, module, imports));
// 7. Set record.[[Instance]] to instance.
- auto instance = Instance::create(instance_address);
+ auto instance = Instance::create(realm, instance_address);
record_host_data.set_instance(instance);
// 8. For each (name, externtype) of module_exports(module),
diff --git a/Meta/Linters/check_libweb_realm_mentions.py b/Meta/Linters/check_libweb_realm_mentions.py
index 9a079811747..02a3321a6a5 100755
--- a/Meta/Linters/check_libweb_realm_mentions.py
+++ b/Meta/Linters/check_libweb_realm_mentions.py
@@ -75,8 +75,8 @@ ALLOWED_REALM_MENTIONS = {
),
"TrustedTypes": (2, 9, "Trusted Types policy factory operations still use selected realms"),
"WebAssembly": (
- 14,
- 85,
+ 15,
+ 89,
"WebAssembly constructors/exports instantiate JS objects/functions in spec-selected realms",
),
"WebAudio": (
diff --git a/Tests/LibWeb/Text/expected/Wasm/WebAssembly-object-identity-survives-collection.txt b/Tests/LibWeb/Text/expected/Wasm/WebAssembly-object-identity-survives-collection.txt
new file mode 100644
index 00000000000..367ae9559eb
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/Wasm/WebAssembly-object-identity-survives-collection.txt
@@ -0,0 +1,3 @@
+exported function keeps its expando: kept
+exported GC object keeps its WeakMap entry: kept
+exported function collected with its instance: true
diff --git a/Tests/LibWeb/Text/input/Wasm/WebAssembly-object-identity-survives-collection.html b/Tests/LibWeb/Text/input/Wasm/WebAssembly-object-identity-survives-collection.html
new file mode 100644
index 00000000000..d89401f66eb
--- /dev/null
+++ b/Tests/LibWeb/Text/input/Wasm/WebAssembly-object-identity-survives-collection.html
@@ -0,0 +1,57 @@
+<!doctype html>
+<script src="../include.js"></script>
+<script>
+ // (module
+ // (type $point (struct (field i32)))
+ // (global $kept (mut (ref null $point)) (ref.null $point))
+ // (table (export "table") 1 funcref)
+ // (elem (i32.const 0) func $answer)
+ // (func $answer (result i32) (i32.const 42))
+ // (func (export "make") (result anyref) (struct.new $point (i32.const 7)))
+ // (func (export "keep") (param anyref) (global.set $kept (ref.cast (ref null $point) (local.get 0))))
+ // (func (export "kept") (result anyref) (global.get $kept)))
+ const bytes = new Uint8Array([
+ 0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00, 0x01, 0x11, 0x04, 0x5f, 0x01, 0x7f, 0x00, 0x60,
+ 0x00, 0x01, 0x7f, 0x60, 0x00, 0x01, 0x6e, 0x60, 0x01, 0x6e, 0x00, 0x03, 0x05, 0x04, 0x01, 0x02,
+ 0x03, 0x02, 0x04, 0x04, 0x01, 0x70, 0x00, 0x01, 0x06, 0x07, 0x01, 0x63, 0x00, 0x01, 0xd0, 0x00,
+ 0x0b, 0x07, 0x1e, 0x04, 0x05, 0x74, 0x61, 0x62, 0x6c, 0x65, 0x01, 0x00, 0x04, 0x6d, 0x61, 0x6b,
+ 0x65, 0x00, 0x01, 0x04, 0x6b, 0x65, 0x65, 0x70, 0x00, 0x02, 0x04, 0x6b, 0x65, 0x70, 0x74, 0x00,
+ 0x03, 0x09, 0x07, 0x01, 0x00, 0x41, 0x00, 0x0b, 0x01, 0x00, 0x0a, 0x1d, 0x04, 0x04, 0x00, 0x41,
+ 0x2a, 0x0b, 0x07, 0x00, 0x41, 0x07, 0xfb, 0x00, 0x00, 0x0b, 0x09, 0x00, 0x20, 0x00, 0xfb, 0x17,
+ 0x00, 0x24, 0x00, 0x0b, 0x04, 0x00, 0x23, 0x00, 0x0b,
+ ]);
+
+ async function collectGarbage() {
+ for (let index = 0; index < 4; ++index) {
+ await animationFrame();
+ await internals.gcAsync();
+ }
+ }
+
+ // Only wasm keeps the function and the struct, not the objects that stand for them.
+ function markObjects(instance, weakMap) {
+ instance.exports.table.get(0).expando = "kept";
+ const point = instance.exports.make();
+ weakMap.set(point, "kept");
+ instance.exports.keep(point);
+ }
+
+ function createDroppedInstance() {
+ const instance = new WebAssembly.Instance(new WebAssembly.Module(bytes));
+ return new WeakRef(instance.exports.table.get(0));
+ }
+
+ asyncTest(async done => {
+ const instance = new WebAssembly.Instance(new WebAssembly.Module(bytes));
+ const weakMap = new WeakMap();
+ markObjects(instance, weakMap);
+ await collectGarbage();
+ println(`exported function keeps its expando: ${instance.exports.table.get(0).expando}`);
+ println(`exported GC object keeps its WeakMap entry: ${weakMap.get(instance.exports.kept())}`);
+
+ const weakFunction = createDroppedInstance();
+ await collectGarbage();
+ println(`exported function collected with its instance: ${weakFunction.deref() === undefined}`);
+ done();
+ });
+</script>