Skip to main content

quickjs/
buffers.rs

1//! `ArrayBuffer` and the typed-array views, from C.
2//!
3//! # Ownership, which is the whole difficulty here
4//!
5//! `JS_NewArrayBuffer(ctx, buf, len, free_func, opaque, is_shared)` takes ownership of a
6//! *C* block and calls `free_func` when the buffer dies. `JS_NewUint8Array` does the same for
7//! a view. So a buffer built this way cannot wrap an engine `Vec<u8>` without one of two
8//! losses: either the C block is copied (and `free_func` has to be called immediately, which
9//! contradicts the header) or the buffer holds a foreign pointer and every read goes through
10//! it.
11//!
12//! This layer takes the first option and is explicit about it: the bytes are copied into the
13//! engine's storage. What it does **not** do any more is call `free_func` right away — the
14//! block is released when the buffer is collected, which is what the header says and what a
15//! host that counts its own allocations can observe. The copy stays, because the alternative —
16//! a foreign-pointer storage kind threaded through every typed-array operation — would be a
17//! second representation of the same thing, and the callers of `JS_NewArrayBuffer` in the
18//! acceptance surface (`tests/bjson.c`) hand over a block they never touch again.
19//!
20//! The one difference left: a host that keeps writing into its block after the call does not
21//! see those writes in script, because script reads the copy. `JS_NewArrayBufferCopy` is the
22//! spelling that admits the copy; the plain one now at least releases at the documented time.
23//!
24//! # Detachment
25//!
26//! `JS_DetachArrayBuffer` zeroes the storage and sets the flag, which every view reads: a
27//! detached view answers `0` bytes and `undefined` elements. That is what
28//! `structuredClone`'s transfer path and `postMessage` rely on.
29
30use core::ffi::{c_int, c_void};
31
32use engine::Value;
33
34use crate::atoms::Atom;
35use crate::builtins_typed;
36use crate::cdefs::Bool;
37use crate::conversions::arg;
38use crate::jsvalue::{self, JsValue};
39use crate::runtime::{self, JsContext};
40use crate::value_helpers::jsvalue_of;
41
42/// `JSFreeArrayBufferDataFunc`: called when a C-supplied block is released.
43pub type FreeArrayBufferDataFunc = Option<unsafe extern "C" fn(*mut c_void, *mut c_void)>;
44
45/// The `JSTypedArrayEnum` values, in the header's order.
46///
47/// Kept as plain constants rather than an enum because the C side passes an `int` and the
48/// reference's own values are what a module's `JSTypedArrayEnum` argument already holds.
49pub mod typed_array_kind {
50    /// `JS_TYPED_ARRAY_UINT8C`.
51    pub const UINT8C: i32 = 0;
52    /// `JS_TYPED_ARRAY_INT8`.
53    pub const INT8: i32 = 1;
54    /// `JS_TYPED_ARRAY_UINT8`.
55    pub const UINT8: i32 = 2;
56    /// `JS_TYPED_ARRAY_INT16`.
57    pub const INT16: i32 = 3;
58    /// `JS_TYPED_ARRAY_UINT16`.
59    pub const UINT16: i32 = 4;
60    /// `JS_TYPED_ARRAY_INT32`.
61    pub const INT32: i32 = 5;
62    /// `JS_TYPED_ARRAY_UINT32`.
63    pub const UINT32: i32 = 6;
64    /// `JS_TYPED_ARRAY_BIG_INT64`.
65    pub const BIG_INT64: i32 = 7;
66    /// `JS_TYPED_ARRAY_BIG_UINT64`.
67    pub const BIG_UINT64: i32 = 8;
68    /// `JS_TYPED_ARRAY_FLOAT16`.
69    pub const FLOAT16: i32 = 9;
70    /// `JS_TYPED_ARRAY_FLOAT32`.
71    pub const FLOAT32: i32 = 10;
72    /// `JS_TYPED_ARRAY_FLOAT64`.
73    pub const FLOAT64: i32 = 11;
74}
75
76/// `JS_NewArrayBuffer`: an `ArrayBuffer` over `buf`, taking ownership of it.
77///
78/// `buf` may be null, which asks for a zero-filled buffer of `len` bytes — the reference's
79/// behaviour, and the only way to build a buffer whose contents C fills in later.
80///
81/// `free_func` is called immediately after the bytes are copied; see the module docs for why.
82///
83/// # Safety
84///
85/// `buf` must be null or point at `len` readable bytes it is safe to release through
86/// `free_func`.
87#[unsafe(no_mangle)]
88pub unsafe extern "C" fn JS_NewArrayBuffer(
89    ctx: *mut JsContext,
90    buf: *mut u8,
91    len: usize,
92    free_func: FreeArrayBufferDataFunc,
93    opaque: *mut c_void,
94    is_shared: Bool,
95) -> JsValue {
96    let Some(_context) = (unsafe { ctx.as_ref() }) else {
97        return jsvalue::EXCEPTION;
98    };
99    if is_shared != 0 {
100        // A shared buffer needs `SharedArrayBuffer`, which this engine installs only when a
101        // host asks for atomics; the C API's `is_shared` is honoured by answering the plain
102        // buffer, and the README records the gap.
103        let _ = is_shared;
104    }
105    let Some(context) = (unsafe { ctx.as_ref() }) else {
106        return jsvalue::EXCEPTION;
107    };
108    let bytes: Vec<u8> = if buf.is_null() {
109        vec![0; len]
110    } else {
111        // SAFETY: the caller guarantees `len` readable bytes.
112        unsafe { core::slice::from_raw_parts(buf, len) }.to_vec()
113    };
114    // The callback is attached to the storage and runs when *that* dies, which is when the
115    // reference runs it too. The closure captures the raw pointers, and the C API's contract
116    // is what makes that sound: `buf` belongs to the library from this call until `free_func`
117    // runs, so nothing else may release it in between.
118    let release: Option<Box<dyn FnOnce()>> = free_func.map(|free_func| {
119        let buf = buf.cast::<c_void>();
120        Box::new(move || {
121            // SAFETY: `free_func` and `opaque` are the caller's, and the block is still
122            // ours — this closure runs exactly once, from the storage's `Drop`.
123            unsafe { free_func(opaque, buf) };
124        }) as Box<dyn FnOnce()>
125    });
126    context.with_current_interp(|interp| {
127        let buffer = match release {
128            Some(release) => builtins_typed::new_array_buffer_with_release(interp, bytes, release),
129            None => builtins_typed::new_array_buffer(interp, bytes),
130        };
131        jsvalue_of(Value::Object(buffer))
132    })
133}
134
135/// `JS_DetachArrayBuffer`: take the storage away, leaving an empty detached buffer.
136///
137/// # Safety
138///
139/// `obj` must be a live `JSValue`.
140#[unsafe(no_mangle)]
141pub unsafe extern "C" fn JS_DetachArrayBuffer(ctx: *mut JsContext, obj: JsValue) {
142    let Some(_context) = (unsafe { ctx.as_ref() }) else {
143        return;
144    };
145    let Some(Value::Object(object)) = (unsafe { arg(obj) }) else {
146        return;
147    };
148    let Some(storage) = object.array_buffer_storage() else {
149        return;
150    };
151    let mut storage = storage.borrow_mut();
152    // `transfer()`'s semantics: the bytes stop being reachable through this buffer, and every
153    // view over it starts answering zero length. Freeing them here rather than clearing is
154    // what makes the detach observable as an allocation drop.
155    storage.bytes = Vec::new();
156    storage.detached = true;
157}
158
159/// `JS_NewTypedArray`: a view, built the way `new Uint8Array(...)` would be.
160///
161/// The arguments are the script constructor's, which is why this is one entry point rather
162/// than one per element type: `argc`/`argv` are passed straight to the constructor.
163///
164/// # Safety
165///
166/// `argv` must point at `argc` live `JSValue`s.
167#[unsafe(no_mangle)]
168pub unsafe extern "C" fn JS_NewTypedArray(
169    ctx: *mut JsContext,
170    argc: c_int,
171    argv: *const JsValue,
172    array_type: c_int,
173) -> JsValue {
174    let Some(context) = (unsafe { ctx.as_ref() }) else {
175        return jsvalue::EXCEPTION;
176    };
177    let element = match builtins_typed::element_from_kind(array_type) {
178        Some(element) => element,
179        None => {
180            return runtime::throw_error(context, "TypeError", "unknown typed array kind");
181        }
182    };
183    // SAFETY: the caller's contract on `argv`.
184    let args = unsafe { crate::calls::decode_args(argc, argv) };
185    let result = context
186        .with_current_interp(|interp| builtins_typed::construct_typed_array(interp, element, args));
187    runtime::result_value(context, result)
188}
189
190/// `JS_NewUint8Array`: a `Uint8Array` over a C block, taking ownership of it.
191///
192/// # Safety
193///
194/// `buf` must be null or point at `len` readable bytes.
195#[unsafe(no_mangle)]
196pub unsafe extern "C" fn JS_NewUint8Array(
197    ctx: *mut JsContext,
198    buf: *mut u8,
199    len: usize,
200    free_func: FreeArrayBufferDataFunc,
201    opaque: *mut c_void,
202    is_shared: Bool,
203) -> JsValue {
204    // SAFETY: the caller's contract is `JS_NewArrayBuffer`'s.
205    let buffer = unsafe { JS_NewArrayBuffer(ctx, buf, len, free_func, opaque, is_shared) };
206    if buffer.is_exception() {
207        return buffer;
208    }
209    // The view covers the whole buffer, which is what the reference builds.
210    let Some(context) = (unsafe { ctx.as_ref() }) else {
211        return jsvalue::EXCEPTION;
212    };
213    context.with_current_interp(|interp| match unsafe { arg(buffer) } {
214        Some(Value::Object(object)) => {
215            let view = builtins_typed::new_view(interp, &object, builtins_typed::UINT8, 0, len);
216            jsvalue_of(Value::Object(view))
217        }
218        _ => jsvalue::EXCEPTION,
219    })
220}
221
222/// `JS_NewUint8ArrayCopy`: a `Uint8Array` holding a copy of `buf`.
223///
224/// # Safety
225///
226/// `buf` must be null or point at `len` readable bytes.
227#[unsafe(no_mangle)]
228pub unsafe extern "C" fn JS_NewUint8ArrayCopy(
229    ctx: *mut JsContext,
230    buf: *const u8,
231    len: usize,
232) -> JsValue {
233    // SAFETY: the caller's contract is `JS_NewArrayBufferCopy`'s.
234    let buffer = unsafe { crate::bjson::JS_NewArrayBufferCopy(ctx, buf, len) };
235    if buffer.is_exception() {
236        return buffer;
237    }
238    let Some(context) = (unsafe { ctx.as_ref() }) else {
239        return jsvalue::EXCEPTION;
240    };
241    context.with_current_interp(|interp| match unsafe { arg(buffer) } {
242        Some(Value::Object(object)) => {
243            let view = builtins_typed::new_view(interp, &object, builtins_typed::UINT8, 0, len);
244            jsvalue_of(Value::Object(view))
245        }
246        _ => jsvalue::EXCEPTION,
247    })
248}
249
250/// `JS_NewUint8ArrayCopy2`: the same, optionally immutable.
251///
252/// This engine has no immutable-buffer extension, so `is_immutable` is refused rather than
253/// silently ignored — a caller that needs the guarantee must not believe it got it.
254///
255/// # Safety
256///
257/// As [`JS_NewUint8ArrayCopy`].
258#[unsafe(no_mangle)]
259pub unsafe extern "C" fn JS_NewUint8ArrayCopy2(
260    ctx: *mut JsContext,
261    buf: *const u8,
262    len: usize,
263    is_immutable: Bool,
264) -> JsValue {
265    if is_immutable != 0 {
266        let Some(context) = (unsafe { ctx.as_ref() }) else {
267            return jsvalue::EXCEPTION;
268        };
269        return runtime::throw_error(
270            context,
271            "TypeError",
272            "immutable ArrayBuffers are not supported",
273        );
274    }
275    // SAFETY: the caller's contract is `JS_NewUint8ArrayCopy`'s.
276    unsafe { JS_NewUint8ArrayCopy(ctx, buf, len) }
277}
278
279/// `JS_GetTypedArrayBuffer`: the view's buffer and its geometry.
280///
281/// # Safety
282///
283/// The three out-pointers must be null or writable; `obj` a live `JSValue`.
284#[unsafe(no_mangle)]
285pub unsafe extern "C" fn JS_GetTypedArrayBuffer(
286    ctx: *mut JsContext,
287    obj: JsValue,
288    pbyte_offset: *mut usize,
289    pbyte_length: *mut usize,
290    pbytes_per_element: *mut usize,
291) -> JsValue {
292    let Some(context) = (unsafe { ctx.as_ref() }) else {
293        return jsvalue::EXCEPTION;
294    };
295    let Some(Value::Object(object)) = (unsafe { arg(obj) }) else {
296        return runtime::throw_error(context, "TypeError", "not a typed array");
297    };
298    let Some((buffer, element, offset, length)) = object.typed_array_parts() else {
299        return runtime::throw_error(context, "TypeError", "not a typed array");
300    };
301    let size = element.size();
302    if !pbyte_offset.is_null() {
303        // SAFETY: the caller guarantees a writable pointer.
304        unsafe { *pbyte_offset = offset * size };
305    }
306    if !pbyte_length.is_null() {
307        // SAFETY: as above.
308        unsafe { *pbyte_length = length * size };
309    }
310    if !pbytes_per_element.is_null() {
311        // SAFETY: as above.
312        unsafe { *pbytes_per_element = size };
313    }
314    jsvalue_of(Value::Object(buffer))
315}
316
317/// `JS_GetTypedArrayType`: the view's `JSTypedArrayEnum`, or `-1`.
318///
319/// # Safety
320///
321/// `obj` must be a live `JSValue`.
322#[unsafe(no_mangle)]
323pub unsafe extern "C" fn JS_GetTypedArrayType(obj: JsValue) -> c_int {
324    let Some(Value::Object(object)) = (unsafe { arg(obj) }) else {
325        return -1;
326    };
327    match object.typed_array_element_type() {
328        Some(element) => builtins_typed::kind_from_element(element),
329        None => -1,
330    }
331}
332
333/// `JS_AtomicsPollWaiters`: how many waiters a `SharedArrayBuffer` has.
334///
335/// Atomics on a shared buffer need threads this engine does not have
336/// (`docs/m15-plan.md` §5 rejects the worker model), so there is never a waiter.
337///
338/// # Safety
339///
340/// `ctx` is ignored.
341#[unsafe(no_mangle)]
342pub unsafe extern "C" fn JS_AtomicsPollWaiters(_ctx: *mut JsContext) -> i64 {
343    0
344}
345
346/// `JS_AtomicsSetAsyncWaker`: register a wake-up callback for `Atomics.waitAsync`.
347///
348/// # Safety
349///
350/// The arguments are ignored.
351#[unsafe(no_mangle)]
352pub unsafe extern "C" fn JS_AtomicsSetAsyncWaker(_cb: *const c_void, _opaque: *mut c_void) {}
353
354/// `JS_SetSharedArrayBufferFunctions`: install the host's shared-memory allocator.
355///
356/// # Safety
357///
358/// `sf` is copied field-wise by the reference; here it is only recorded as "not supported".
359#[unsafe(no_mangle)]
360pub unsafe extern "C" fn JS_SetSharedArrayBufferFunctions(
361    _rt: *mut runtime::JsRuntime,
362    _sf: *const c_void,
363) {
364}
365
366/// `JS_JSONStringify`: `JSON.stringify(obj, replacer, space)`.
367///
368/// The engine's own `JSON.stringify` is reached through the global object rather than through
369/// a Rust entry point, because the replacer can be an arbitrary script function and the
370/// engine's implementation already handles every shape of it.
371///
372/// # Safety
373///
374/// All three values must be live.
375#[unsafe(no_mangle)]
376pub unsafe extern "C" fn JS_JSONStringify(
377    ctx: *mut JsContext,
378    obj: JsValue,
379    replacer: JsValue,
380    space0: JsValue,
381) -> JsValue {
382    let Some(context) = (unsafe { ctx.as_ref() }) else {
383        return jsvalue::EXCEPTION;
384    };
385    let value = unsafe { arg(obj) }.unwrap_or(Value::Undefined);
386    let replacer = unsafe { arg(replacer) }.unwrap_or(Value::Undefined);
387    let space = unsafe { arg(space0) }.unwrap_or(Value::Undefined);
388    let result = context.with_current_interp(|interp| {
389        let global = Value::Object(interp.realm.global.clone());
390        let json = interp.read_field(&global, "JSON")?;
391        let stringify = interp.read_field(&json, "stringify")?;
392        interp.call_value(stringify, json, vec![value, replacer, space])
393    });
394    runtime::result_value(context, result)
395}
396
397/// `JS_ParseJSON`: parse `buf_len` bytes as JSON.
398///
399/// # Safety
400///
401/// `buf` must point at `buf_len` readable bytes; `filename` may be null.
402#[unsafe(no_mangle)]
403pub unsafe extern "C" fn JS_ParseJSON(
404    ctx: *mut JsContext,
405    buf: *const core::ffi::c_char,
406    buf_len: usize,
407    filename: *const core::ffi::c_char,
408) -> JsValue {
409    // SAFETY: the caller's contract is `JS_ParseJSON2`'s with `flags == 0`.
410    unsafe { JS_ParseJSON2(ctx, buf, buf_len, filename, 0) }
411}
412
413/// `JS_ParseJSON2`: parse JSON, optionally as extended JSON.
414///
415/// `JS_PARSE_JSON_EXT` (bit 0) enables the reference's extension — comments, single quotes,
416/// trailing commas and `NaN`/`Infinity` — which the engine has as `parse_ext_json`.
417///
418/// # Safety
419///
420/// As [`JS_ParseJSON`].
421#[unsafe(no_mangle)]
422pub unsafe extern "C" fn JS_ParseJSON2(
423    ctx: *mut JsContext,
424    buf: *const core::ffi::c_char,
425    buf_len: usize,
426    _filename: *const core::ffi::c_char,
427    flags: c_int,
428) -> JsValue {
429    let Some(context) = (unsafe { ctx.as_ref() }) else {
430        return jsvalue::EXCEPTION;
431    };
432    if buf.is_null() {
433        return runtime::throw_error(context, "SyntaxError", "null JSON");
434    }
435    // SAFETY: the caller guarantees `buf_len` readable bytes.
436    let bytes = unsafe { core::slice::from_raw_parts(buf.cast::<u8>(), buf_len) };
437    let text = String::from_utf8_lossy(bytes).into_owned();
438    const JS_PARSE_JSON_EXT: c_int = 1 << 0;
439    let extended = flags & JS_PARSE_JSON_EXT != 0;
440    let result = context
441        .with_current_interp(|interp| engine::builtins::json::parse_text(interp, &text, extended));
442    runtime::result_value(context, result)
443}
444
445/// `JS_ParseJSON3`: the same, plus a record of where each value came from.
446///
447/// The parse record is a debug/IDE feature (source positions for a JSON document); this layer
448/// does not produce one, so it parses and leaves `pr` untouched. A caller that needs the record
449/// must not use this library — recorded in the README rather than pretended.
450///
451/// # Safety
452///
453/// As [`JS_ParseJSON2`]; `pr` may be null.
454#[unsafe(no_mangle)]
455pub unsafe extern "C" fn JS_ParseJSON3(
456    ctx: *mut JsContext,
457    buf: *const core::ffi::c_char,
458    buf_len: usize,
459    filename: *const core::ffi::c_char,
460    flags: c_int,
461    _pr: *mut c_void,
462) -> JsValue {
463    // SAFETY: the caller's contract is `JS_ParseJSON2`'s.
464    unsafe { JS_ParseJSON2(ctx, buf, buf_len, filename, flags) }
465}
466
467/// `JS_SameValue`: `Object.is(a, b)`.
468///
469/// # Safety
470///
471/// Both values must be live.
472#[unsafe(no_mangle)]
473pub unsafe extern "C" fn JS_SameValue(_ctx: *mut JsContext, op1: JsValue, op2: JsValue) -> Bool {
474    match (unsafe { arg(op1) }, unsafe { arg(op2) }) {
475        (Some(left), Some(right)) => c_int::from(left.same_value(&right)),
476        _ => 0,
477    }
478}
479
480/// `JS_SameValueZero`: `SameValueZero` — `Object.is` except that `±0` are equal.
481///
482/// # Safety
483///
484/// Both values must be live.
485#[unsafe(no_mangle)]
486pub unsafe extern "C" fn JS_SameValueZero(
487    _ctx: *mut JsContext,
488    op1: JsValue,
489    op2: JsValue,
490) -> Bool {
491    match (unsafe { arg(op1) }, unsafe { arg(op2) }) {
492        (Some(left), Some(right)) => c_int::from(left.same_value_zero(&right)),
493        _ => 0,
494    }
495}
496
497/// `JS_StrictEq`: `a === b`.
498///
499/// # Safety
500///
501/// Both values must be live.
502#[unsafe(no_mangle)]
503pub unsafe extern "C" fn JS_StrictEq(_ctx: *mut JsContext, op1: JsValue, op2: JsValue) -> Bool {
504    match (unsafe { arg(op1) }, unsafe { arg(op2) }) {
505        (Some(left), Some(right)) => c_int::from(left.strict_equals(&right)),
506        _ => 0,
507    }
508}
509
510/// `JS_NewSymbol`'s atom-keyed cousin: nothing here, but `Atom` is imported so a reader
511/// looking for the atom-keyed property family finds the reason it lives next door.
512const _: Option<Atom> = None;