Skip to main content

quickjs_jit_stdlib/llrt/llrt_utils/
array_buffer.rs

1// Vendored from LLRT d9fd873e793c (libs/llrt_utils/src/array_buffer.rs); module paths and
2// feature names adapted by scripts/import-stdlib.py.
3// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
4// SPDX-License-Identifier: Apache-2.0
5//! Zero-copy `ArrayBuffer` helpers built on QuickJS-NG primitives.
6//!
7//! `rquickjs` doesn't yet ship safe wrappers for QuickJS-NG's
8//! [immutable ArrayBuffer](https://tc39.es/proposal-immutable-arraybuffer/)
9//! support, so we go through `rquickjs::qjs::*` directly. The two
10//! capabilities exposed here are:
11//!
12//! * [`shared_array_buffer_view`] — create a fresh `ArrayBuffer` that
13//!   borrows the bytes of an existing one (no memcpy), kept alive via a
14//!   dup'd `JSValue` reference. The view is marked immutable, which is
15//!   both a correctness guarantee (consumer mutations can't leak into the
16//!   source) and a hard safety rail (the only QuickJS code path that
17//!   would lose our refcount handle is `.transfer()`, which immutability
18//!   blocks at the JS layer).
19//! * [`set_immutable`] — flip the immutable flag on an existing
20//!   `ArrayBuffer` (used when the source is a freshly-allocated buffer
21//!   we own and want to seal before handing out).
22//!
23//! These are used by `Blob.stream()` / `Blob.slice()` and by fetch's
24//! `Response.body` / `Request.body` getters to hand out aliased,
25//! transfer-safe views into producer-owned storage.
26
27use std::ffi::c_void;
28
29use rquickjs::{qjs, ArrayBuffer, Ctx, Exception, Result, Value};
30
31const FIXED_SIZE: qjs::size_t = 0;
32const FREE: qjs::size_t = 0;
33
34/// Mark an `ArrayBuffer` as immutable: subsequent writes through any
35/// `Uint8Array` / `DataView` view silently fail (or `TypeError` in strict
36/// mode), and `.transfer()` throws `TypeError: ArrayBuffer is immutable`.
37///
38/// Calling this on an already-immutable buffer is a no-op. Calling it on
39/// a detached buffer is a no-op (QuickJS returns -1 internally). The flag
40/// is checked at write/transfer time, not at create time, so the buffer
41/// can be initialised with bytes before being sealed.
42pub fn set_immutable(ab: &ArrayBuffer<'_>) {
43    // Safety: the JSValue is owned by `ab`; we only flip a boolean flag
44    // on the underlying `JSArrayBuffer` struct.
45    unsafe {
46        qjs::JS_SetImmutableArrayBuffer(ab.as_value().as_raw(), true);
47    }
48}
49
50/// Create a fresh, **immutable** `ArrayBuffer` that shares storage with
51/// `source` at `[offset..offset+len]` without copying any bytes. The
52/// returned buffer holds a dup'd reference to the source's `JSValue`, so
53/// the backing allocation stays alive exactly as long as any view (or
54/// transferred descendant of it) is reachable.
55///
56/// Immutability is what makes this sound:
57///
58///   * Writes through `Uint8Array` / `DataView` views silently no-op
59///     (strict mode: `TypeError`) — aliased consumers can't corrupt the
60///     source.
61///   * `buffer.transfer()` throws `TypeError: ArrayBuffer is immutable`
62///     — so a consumer can't detach the view and drop the `opaque`
63///     pointer that keeps the source alive. Without this guard the
64///     `free_func` would later fire with `opaque=NULL` (QuickJS strips
65///     `opaque` on transfer; see `js_array_buffer_constructor3`) and
66///     panic in `Box::from_raw(null)`. Because immutability blocks
67///     transfer at the JS layer, that path is unreachable.
68///
69/// If a future caller wants a *mutable* shared view, they need a
70/// different cleanup strategy (ptr-keyed side table, upstream QuickJS
71/// patch, or accepting a per-transfer leak).
72pub fn shared_array_buffer_view<'js>(
73    ctx: &Ctx<'js>,
74    source: &ArrayBuffer<'js>,
75    offset: usize,
76    len: usize,
77) -> Result<ArrayBuffer<'js>> {
78    let raw = source
79        .as_raw()
80        .ok_or_else(|| Exception::throw_type(ctx, "cannot view a detached ArrayBuffer"))?;
81    debug_assert!(
82        offset.checked_add(len).is_some_and(|e| e <= raw.len()),
83        "shared_array_buffer_view: slice out of range"
84    );
85    let ptr = unsafe { raw.cast::<u8>().as_ptr().add(offset) };
86
87    // Dup the source's JSValue. The returned ArrayBuffer's free-callback
88    // (below) will drop this reference.
89    let ctx_ptr = ctx.as_raw().as_ptr();
90    let rt = unsafe { qjs::JS_GetRuntime(ctx_ptr) };
91    let source_val = unsafe { qjs::JS_DupValueRT(rt, source.as_value().as_raw()) };
92    let opaque = Box::into_raw(Box::new(source_val)) as *mut c_void;
93
94    extern "C" fn free_shared(
95        rt: *mut qjs::JSRuntime,
96        opaque: *mut c_void,
97        _ptr: *mut c_void,
98        size: qjs::size_t,
99    ) -> *mut c_void {
100        if size != FREE {
101            return std::ptr::null_mut();
102        }
103        // `opaque` is guaranteed non-null: the only QuickJS code path
104        // that loses it is `.transfer()`, which is blocked by the
105        // immutability flag we set below.
106        unsafe {
107            let boxed = Box::from_raw(opaque as *mut qjs::JSValue);
108            qjs::JS_FreeValueRT(rt, *boxed);
109        }
110        std::ptr::null_mut()
111    }
112
113    let view = unsafe {
114        let val = qjs::JS_NewArrayBuffer(
115            ctx_ptr,
116            ptr,
117            len as _,
118            FIXED_SIZE,
119            Some(free_shared),
120            opaque,
121            /*is_shared=*/ false,
122        );
123        if qjs::JS_IsException(val) {
124            // QuickJS didn't take ownership of `opaque`; drop it ourselves.
125            free_shared(rt, opaque, ptr as *mut c_void, FREE);
126            return Err(ctx.throw(ctx.catch()));
127        }
128        let value = Value::from_raw(ctx.clone(), val);
129        ArrayBuffer::from_value(value)
130            .ok_or_else(|| Exception::throw_type(ctx, "expected ArrayBuffer"))?
131    };
132
133    set_immutable(&view);
134    Ok(view)
135}