Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
98 changes: 98 additions & 0 deletions src/rust/jsg-test/tests/buffer_types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -273,6 +273,104 @@ fn array_buffer_try_from_fails_for_typed_array() {
});
}

// =============================================================================
// SharedArrayBuffer
// =============================================================================

#[test]
fn shared_array_buffer_is_not_an_array_buffer() {
let harness = crate::Harness::new();
harness.run_in_context(|lock, ctx| {
let val = ctx.eval_raw(lock, "new SharedArrayBuffer(4)").unwrap();
assert!(v8::Local::<v8::ArrayBuffer>::try_from(val).is_err());
assert!(v8::Local::<v8::SharedArrayBuffer>::try_from(val).is_ok());

let val = ctx.eval_raw(lock, "new ArrayBuffer(4)").unwrap();
assert!(v8::Local::<v8::SharedArrayBuffer>::try_from(val).is_err());
Ok(())
});
}

#[test]
fn shared_array_buffer_to_vec_copies_its_bytes() {
let harness = crate::Harness::new();
harness.run_in_context(|lock, ctx| {
let val = ctx
.eval_raw(
lock,
"const sab = new SharedArrayBuffer(3, { maxByteLength: 8 }); \
new Uint8Array(sab).set([5, 6, 7]); sab.grow(4); sab",
)
.unwrap();
let buf = v8::Local::<v8::SharedArrayBuffer>::try_from(val).unwrap();
assert_eq!(buf.byte_length(), 4);
assert_eq!(buf.to_vec(), vec![5u8, 6, 7, 0]);

let val = ctx.eval_raw(lock, "new SharedArrayBuffer(0)").unwrap();
let buf = v8::Local::<v8::SharedArrayBuffer>::try_from(val).unwrap();
assert!(buf.is_empty());
assert_eq!(buf.to_vec(), Vec::<u8>::new());
Ok(())
});
}

#[test]
fn array_buffer_view_over_shared_array_buffer_to_vec_copies_its_bytes() {
let harness = crate::Harness::new();
harness.run_in_context(|lock, ctx| {
// A view at an offset, a DataView, and a length-tracking view over a growable buffer
// each copy exactly the bytes they cover.
let val = ctx
.eval_raw(
lock,
"globalThis.sab = new SharedArrayBuffer(4, { maxByteLength: 8 }); \
new Uint8Array(sab).set([1, 2, 3, 4]); new Uint8Array(sab, 1, 2)",
)
.unwrap();
let view = v8::Local::<v8::ArrayBufferView>::try_from(val).unwrap();
assert_eq!(view.to_vec(), vec![2u8, 3]);

let val = ctx.eval_raw(lock, "new DataView(sab, 2)").unwrap();
let view = v8::Local::<v8::ArrayBufferView>::try_from(val).unwrap();
assert_eq!(view.to_vec(), vec![3u8, 4]);

let val = ctx
.eval_raw(
lock,
"globalThis.tracking = new Uint8Array(sab); sab.grow(6); tracking",
)
.unwrap();
let view = v8::Local::<v8::ArrayBufferView>::try_from(val).unwrap();
assert_eq!(view.to_vec(), vec![1u8, 2, 3, 4, 0, 0]);

let val = ctx.eval_raw(lock, "new Uint8Array(sab, 6)").unwrap();
let view = v8::Local::<v8::ArrayBufferView>::try_from(val).unwrap();
assert!(view.to_vec().is_empty());
Ok(())
});
}

#[test]
fn shared_buffer_of_a_view_to_vec_copies_its_bytes() {
let harness = crate::Harness::new();
harness.run_in_context(|lock, ctx| {
// V8 hands out a view's `SharedArrayBuffer` as an `ArrayBuffer`; its `to_vec()` copies
// every byte of the buffer, not just the view's.
let val = ctx
.eval_raw(
lock,
"const sab = new SharedArrayBuffer(4); new Uint8Array(sab).set([1, 2, 3, 4]); \
new Uint8Array(sab, 1, 2)",
)
.unwrap();
let view = v8::Local::<v8::ArrayBufferView>::try_from(val).unwrap();
let buffer = view.buffer(lock);
assert!(buffer.is_shared());
assert_eq!(buffer.to_vec(), vec![1u8, 2, 3, 4]);
Ok(())
});
}

#[test]
fn array_buffer_into_object() {
let harness = crate::Harness::new();
Expand Down
7 changes: 7 additions & 0 deletions src/rust/jsg/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -920,6 +920,13 @@ lock, and can be handed to C++ with `into_ffi()` as a `kj::Own<v8::CompiledWasmM
which C++ makes another module object without recompiling. As in C++, RTTI describes the module
as `unknown`; a TypeScript override names it `WebAssembly.Module`.

A `Local<SharedArrayBuffer>` is not a `Local<ArrayBuffer>`, as in V8. Its `to_vec()`, like that
of a `Local<ArrayBufferView>`, whose buffer may be shared, copies the bytes in C++, so it never
borrows memory that another agent may write. So does that of a `Local<ArrayBuffer>`, since the
`buffer()` of a view over a `SharedArrayBuffer` returns it as one, as V8 does. The `as_slice()` of
an `ArrayBuffer`, an `ArrayBufferView` or a typed array does borrow its bytes, so it suits only a
buffer that isn't shared.

### `Global<T>`

A persistent handle that outlives `HandleScope`s, for handles that Rust code owns outside
Expand Down
32 changes: 32 additions & 0 deletions src/rust/jsg/ffi.c++
Original file line number Diff line number Diff line change
Expand Up @@ -953,6 +953,29 @@ size_t local_array_buffer_get_backing_store(const Local& buffer) {
local_as_ref_from_ffi<v8::ArrayBuffer>(buffer)->GetBackingStore()));
}

size_t local_array_buffer_copy_to(const Local& buffer, ::rust::Slice<uint8_t> out) {
auto buf = local_as_ref_from_ffi<v8::ArrayBuffer>(buffer);
auto size = kj::min(buf->ByteLength(), out.size());
if (size > 0) {
memcpy(out.data(), buf->Data(), size);
}
return size;
}

// Local<SharedArrayBuffer>
size_t local_shared_array_buffer_byte_length(const Local& buffer) {
return local_as_ref_from_ffi<v8::SharedArrayBuffer>(buffer)->ByteLength();
}

size_t local_shared_array_buffer_copy_to(const Local& buffer, ::rust::Slice<uint8_t> out) {
auto buf = local_as_ref_from_ffi<v8::SharedArrayBuffer>(buffer);
auto size = kj::min(buf->ByteLength(), out.size());
if (size > 0) {
memcpy(out.data(), buf->Data(), size);
}
return size;
}

// Local<WasmModuleObject>
kj::Own<CompiledWasmModule> local_wasm_module_object_get_compiled_module(const Local& module) {
return kj::heap(local_as_ref_from_ffi<v8::WasmModuleObject>(module)->GetCompiledModule());
Expand Down Expand Up @@ -988,6 +1011,15 @@ uintptr_t local_array_buffer_view_data(const Local& view, size_t& byte_length) {
return reinterpret_cast<uintptr_t>(bytes.begin());
}

size_t local_array_buffer_view_copy_to(const Local& view, ::rust::Slice<uint8_t> out) {
auto bytes = viewBytes(local_as_ref_from_ffi<v8::ArrayBufferView>(view));
auto size = kj::min(bytes.size(), out.size());
if (size > 0) {
memcpy(out.data(), bytes.begin(), size);
}
return size;
}

Local local_array_buffer_view_get_buffer(Isolate* isolate, const Local& view) {
return to_ffi(local_as_ref_from_ffi<v8::ArrayBufferView>(view)->Buffer());
}
Expand Down
12 changes: 12 additions & 0 deletions src/rust/jsg/ffi.h
Original file line number Diff line number Diff line change
Expand Up @@ -558,6 +558,15 @@ uint8_t* local_array_buffer_data(const Local& buffer);
// its byte length.
uintptr_t local_array_buffer_contents(const Local& buffer, size_t& byteLength);
size_t local_array_buffer_get_backing_store(const Local& buffer);
// Copies the first `out.size()` bytes of the buffer, or all of them if it has fewer, into `out`,
// and returns how many it copied.
size_t local_array_buffer_copy_to(const Local& buffer, ::rust::Slice<uint8_t> out);

// Local<SharedArrayBuffer>
size_t local_shared_array_buffer_byte_length(const Local& buffer);
// Copies the first `out.size()` bytes of the buffer, or all of them if it has fewer, into `out`,
// and returns how many it copied.
size_t local_shared_array_buffer_copy_to(const Local& buffer, ::rust::Slice<uint8_t> out);

// Local<WasmModuleObject>
kj::Own<CompiledWasmModule> local_wasm_module_object_get_compiled_module(const Local& module);
Expand All @@ -575,6 +584,9 @@ uint8_t* local_array_buffer_view_buffer_data(const Local& view);
// Returns the address of the first byte the view covers and sets `byte_length` to how many it
// covers, which is zero for a view that is detached or that does not lie within its buffer.
uintptr_t local_array_buffer_view_data(const Local& view, size_t& byte_length);
// Copies the first `out.size()` bytes the view covers, or all of them if it covers fewer, into
// `out`, and returns how many it copied.
size_t local_array_buffer_view_copy_to(const Local& view, ::rust::Slice<uint8_t> out);
Local local_array_buffer_view_get_buffer(Isolate* isolate, const Local& view);
size_t local_array_buffer_view_element_size(const Local& view);
bool local_array_buffer_view_is_integer_type(const Local& view);
Expand Down
87 changes: 81 additions & 6 deletions src/rust/jsg/v8.rs
Original file line number Diff line number Diff line change
Expand Up @@ -385,6 +385,14 @@ pub mod ffi {
pub unsafe fn local_array_buffer_contents(buffer: &Local, byte_length: &mut usize)
-> usize;
pub unsafe fn local_array_buffer_get_backing_store(buffer: &Local) -> usize;
#[nothrow]
pub unsafe fn local_array_buffer_copy_to(buffer: &Local, out: &mut [u8]) -> usize;

// Local<SharedArrayBuffer>
#[nothrow]
pub unsafe fn local_shared_array_buffer_byte_length(buffer: &Local) -> usize;
#[nothrow]
pub unsafe fn local_shared_array_buffer_copy_to(buffer: &Local, out: &mut [u8]) -> usize;

// Local<WasmModuleObject>
pub unsafe fn local_wasm_module_object_get_compiled_module(
Expand All @@ -403,6 +411,8 @@ pub mod ffi {
pub unsafe fn local_array_buffer_view_byte_length(view: &Local) -> usize;
pub unsafe fn local_array_buffer_view_buffer_data(view: &Local) -> *mut u8;
pub unsafe fn local_array_buffer_view_data(view: &Local, byte_length: &mut usize) -> usize;
#[nothrow]
pub unsafe fn local_array_buffer_view_copy_to(view: &Local, out: &mut [u8]) -> usize;
pub unsafe fn local_array_buffer_view_get_buffer(
isolate: *mut Isolate,
view: &Local,
Expand Down Expand Up @@ -1431,7 +1441,7 @@ impl ffi::ExceptionType {
// Deliberately left unimplemented because we didn't need them yet:
// - Primitive, Numeric
// - NumberObject, BooleanObject, StringObject, SymbolObject, BigIntObject
// - Map, Set, Proxy, RegExp, External, DataView, SharedArrayBuffer, Float16Array
// - Map, Set, Proxy, RegExp, External, DataView, Float16Array
// - WasmMemoryObject
// - Context, Template, ObjectTemplate, Signature, Module, Script, Private, PrimitiveArray
//
Expand Down Expand Up @@ -1710,6 +1720,8 @@ pub struct BigInt64Array;
pub struct BigUint64Array;
pub struct Uint8ClampedArray;
pub struct ArrayBuffer;
/// Marker for `v8::SharedArrayBuffer` handles, which are not `ArrayBuffer`s.
pub struct SharedArrayBuffer;
pub struct ArrayBufferView;
/// Marker for `v8::WasmModuleObject` handles: a `WebAssembly.Module`.
pub struct WasmModuleObject;
Expand Down Expand Up @@ -2758,6 +2770,7 @@ impl_local_cast!(Function: Object, Value; is_function);
impl_local_cast!(Promise: Object, Value; is_promise);
impl_local_cast!(Array: Object, Value; is_array);
impl_local_cast!(ArrayBuffer: Object, Value; is_array_buffer);
impl_local_cast!(SharedArrayBuffer: Object, Value; is_shared_array_buffer);
impl_local_cast!(ArrayBufferView: Object, Value; is_array_buffer_view);
impl_local_cast!(WasmModuleObject: Object, Value; is_wasm_module_object);
impl_local_cast!(TypedArray: ArrayBufferView, Object, Value; is_typed_array);
Expand Down Expand Up @@ -3059,6 +3072,10 @@ impl<'s> Local<'s, ArrayBuffer> {
/// resize or write to the buffer) needs `&mut Lock`, so none of it can happen while
/// the slice is live.
///
/// The buffer may be a `SharedArrayBuffer`, as the one an `ArrayBufferView`'s `buffer()`
/// returns may be ([`is_shared`](Self::is_shared) tells), and another agent may write its
/// bytes while the slice is live; [`to_vec`](Self::to_vec) copies them without borrowing.
///
/// TODO(soon): When there is a safe aliasing model for Rust mutable access,
/// integrate this method with that somehow.
#[inline]
Expand Down Expand Up @@ -3096,10 +3113,18 @@ impl<'s> Local<'s, ArrayBuffer> {
}

/// Copies the `ArrayBuffer` contents into a new `Vec<u8>`.
///
/// The buffer may be a `SharedArrayBuffer` (see [`is_shared`](Self::is_shared)), which another
/// agent may write to at any time, so C++ copies the bytes and Rust never borrows them.
pub fn to_vec(&self) -> Vec<u8> {
// SAFETY: the FFI returns this region's bytes, and no JavaScript runs
// before the copy completes.
unsafe { &*self.as_raw_slice() }.to_vec()
let mut bytes = vec![0; self.byte_length()];
// SAFETY: handle is valid within the current HandleScope.
let copied = unsafe { ffi::local_array_buffer_copy_to(self.raw(), &mut bytes) };
// No JavaScript runs between reading the length and copying, so the buffer can't have
// shrunk. Another agent may grow a `SharedArrayBuffer` in the meantime, but the copy stops
// at `bytes.len()`.
debug_assert_eq!(copied, bytes.len());
bytes
}

/// A raw pointer to the buffer's bytes, read from V8 in one call. It is dangling, with no
Expand Down Expand Up @@ -3179,6 +3204,35 @@ impl<'s> Local<'s, ArrayBuffer> {
}
}

impl Local<'_, SharedArrayBuffer> {
/// Returns the byte length of this `SharedArrayBuffer`.
#[inline]
pub fn byte_length(&self) -> usize {
// SAFETY: handle is valid within the current HandleScope.
unsafe { ffi::local_shared_array_buffer_byte_length(self.raw()) }
}

/// Returns `true` if this `SharedArrayBuffer` has zero bytes.
#[inline]
pub fn is_empty(&self) -> bool {
self.byte_length() == 0
}

/// Copies the `SharedArrayBuffer`'s contents into a new `Vec<u8>`.
///
/// Another agent may write to shared memory at any time, so Rust never borrows it: C++
/// copies the bytes, as C++ JSG reads them.
pub fn to_vec(&self) -> Vec<u8> {
let mut bytes = vec![0; self.byte_length()];
// SAFETY: handle is valid within the current HandleScope.
let copied = unsafe { ffi::local_shared_array_buffer_copy_to(self.raw(), &mut bytes) };
// Another agent may grow the buffer between reading the length and copying, but the copy
// stops at `bytes.len()`, and a `SharedArrayBuffer` never shrinks.
debug_assert_eq!(copied, bytes.len());
bytes
}
}

impl Local<'_, WasmModuleObject> {
/// Returns the module's compiled code, which outlives this handle.
///
Expand Down Expand Up @@ -3250,6 +3304,10 @@ impl<'s> Local<'s, ArrayBufferView> {
}

/// Returns the backing `ArrayBuffer` of this view.
///
/// As in V8, the buffer may be a `SharedArrayBuffer` even though the handle is a
/// `Local<ArrayBuffer>`. Its `is_shared()` tells, and its `to_vec()`, unlike its
/// `as_slice()`, reads a shared buffer without borrowing it.
pub fn buffer(self, lock: &mut Lock<'s>) -> Local<'s, ArrayBuffer> {
// SAFETY: lock guarantees the isolate is locked; the new handle is created in the
// lock's scope.
Expand All @@ -3267,6 +3325,9 @@ impl<'s> Local<'s, ArrayBufferView> {
/// no JavaScript (which could detach, resize or write to the buffer) can run while
/// it is live.
///
/// For a view over a `SharedArrayBuffer`, another agent may write the bytes while the slice
/// is live; [`to_vec`](Self::to_vec) copies them without borrowing.
///
/// TODO(soon): When there is a safe aliasing model for Rust mutable access,
/// integrate this method with that somehow.
#[inline]
Expand Down Expand Up @@ -3304,9 +3365,18 @@ impl<'s> Local<'s, ArrayBufferView> {
}

/// Copies the view's visible byte range into a new `Vec<u8>`.
///
/// The view's buffer may be a `SharedArrayBuffer`, which another agent may write to at any
/// time, so C++ copies the bytes and Rust never borrows them.
pub fn to_vec(&self) -> Vec<u8> {
// SAFETY: the bytes are this view's, and no JavaScript runs before the copy completes.
unsafe { &*self.as_raw_slice() }.to_vec()
let mut bytes = vec![0; self.as_raw_slice().len()];
// SAFETY: handle is valid within the current HandleScope.
let copied = unsafe { ffi::local_array_buffer_view_copy_to(self.raw(), &mut bytes) };
// No JavaScript runs between reading the length and copying, so the view can't have
// shrunk. Another agent may grow a `SharedArrayBuffer` under a length-tracking view in
// the meantime, but the copy stops at `bytes.len()`.
debug_assert_eq!(copied, bytes.len());
bytes
}

/// A raw pointer to the view's visible bytes, read from V8 in one call. It is dangling, with
Expand Down Expand Up @@ -3474,6 +3544,11 @@ macro_rules! impl_typed_array {
/// The slice borrows `lock`, so no JavaScript (which could detach, resize
/// or write to the buffer) can run while it is live.
///
/// For a typed array over a `SharedArrayBuffer`, another agent may write the
/// elements while the slice is live; converting it into a
/// `Local<ArrayBufferView>` and calling `to_vec()` copies its bytes without
/// borrowing.
///
/// TODO(soon): When there is a safe aliasing model for Rust mutable access,
/// integrate this method with that somehow.
#[inline]
Expand Down
3 changes: 2 additions & 1 deletion src/rust/jsg/wrappable.rs
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,8 @@
//!
//! From JavaScript, a `Vec<T>` or `&[T]` parameter reads an `Array` whose elements convert to
//! `T`. A typed array parameter is a handle, `v8::Local<'s, v8::Uint8Array>` and so on, which
//! reads its memory in place with `as_slice(lock)`. An `ArrayBuffer` is a
//! reads its memory in place with `as_slice(lock)`; for one over a `SharedArrayBuffer`, convert it
//! into a `Local<ArrayBufferView>` and copy its bytes with `to_vec()` instead. An `ArrayBuffer` is a
//! `v8::Local<'s, v8::ArrayBuffer>`, and `v8::Local<'s, v8::ArrayBufferView>` accepts any view.
//!
//! ## Integers
Expand Down
Loading