quickjs-capi 0.12.0

C ABI compatibility layer: the QuickJS C API on top of the pure-Rust engine
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
//! The allocator the C side shares with us, and the boxes that hold engine values.
//!
//! # Why there is an allocator here at all
//!
//! `quickjs.h` decrements a reference count *inline*, in the caller's translation unit:
//!
//! ```c
//! static inline void JS_FreeValue(JSContext *ctx, JSValue v) {
//!     if (JS_VALUE_HAS_REF_COUNT(v)) {
//!         JSRefCountHeader *p = __js_rc(JS_VALUE_GET_PTR(v));  /* (uint32_t *)ptr - 1 */
//!         if (--p->ref_count <= 0) __JS_FreeValue(ctx, v);
//!     }
//! }
//! ```
//!
//! `__js_rc` is `(uint32_t *)ptr - 1`, so **the four bytes immediately before every
//! reference-counted payload must be a writable `int`**. No Rust container can promise
//! that, so the payloads C sees are allocated here, with the reference's own header
//! shape:
//!
//! ```text
//! block + 0 : u32  kind and size   (see Kind::slot)
//! block + 4 : i32  ref_count       <- what __js_rc(payload) points at
//! block + 8 : ...  payload         <- JS_VALUE_GET_PTR
//! ```
//!
//! That is also why `js_malloc` / `js_free` live in the same allocator as the boxes:
//! `bjson.c` hands us a buffer from `JS_WriteObject` and then calls `js_free` on it, and
//! two allocators would mean freeing a pointer we never allocated.
//!
//! # Two families, one header
//!
//! * [`alloc_raw`] / [`free_raw`] — untyped bytes, for `js_malloc` and the buffers behind
//!   `JS_WriteObject`.
//! * [`box_value`] / [`free_value`] — a header plus one engine [`Value`], for every
//!   reference-counted `JSValue` that crosses the boundary.
//!
//! Both put `ref_count` at `+4` and the payload at `+8`, so C's `--p->ref_count` is
//! correct for either, and [`free_value`] is the one place an engine value is released on
//! the C side's say-so — which is where a host class's finalizer runs.
//!
//! # Alignment and size limits
//!
//! Payloads are 8-byte aligned, matching the reference's `JS_MALLOC_ALIGN`. That is enough
//! for a `double`, a pointer, and the `uint64_t` arrays `tests/bjson.c` builds.
//!
//! The size of a byte block is recorded in the same 32-bit word as its kind, so a single
//! block tops out at 1 GiB − 8 bytes. Nothing in the C API asks for more: the one large
//! buffer it produces is `JS_WriteObject`'s output, and a 1 GiB serialisation is already
//! beyond what `test_bjson.js` exercises. A block that big is answered with a null pointer,
//! which every caller already has to handle.

use std::alloc::{Layout, alloc, alloc_zeroed, dealloc, realloc as raw_realloc};

use engine::Value;

use crate::jsvalue::{ENGINE_BOX_TAG, ENGINE_STRING_TAG, JsValue};

/// Size of the header in front of every payload: two 32-bit words.
pub const HEADER_SIZE: usize = 8;

/// Offset of `ref_count` inside a block. `__js_rc(payload)` is `payload - 4`, so this is
/// the number that must not move.
pub const REF_COUNT_OFFSET: usize = 4;

/// Offset of the first payload byte inside a block.
pub const PAYLOAD_OFFSET: usize = HEADER_SIZE;

/// Alignment every block is allocated with.
pub const ALIGN: usize = 8;

/// The largest payload a block may hold.
///
/// A byte block records its size in the same word as its kind, with two bits taken by the
/// kind, so 30 bits are left: 1 GiB − 8 bytes in total. Anything larger is answered with a
/// null pointer, which is the C API's "allocation failed" answer.
pub const MAX_PAYLOAD: usize = (u32::MAX >> 2) as usize - HEADER_SIZE;

/// What a block holds, as stored in the header word.
///
/// The kind shares its word with the size because the only other free slot is `+4`, and
/// that one belongs to `ref_count`. `Value` blocks take the low bit; byte blocks take the
/// low *two* bits as zero and shift the size up, so a fresh `js_malloc(0)` cannot be
/// mistaken for a box.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Kind {
    /// Untyped bytes from `js_malloc` and friends.
    Bytes,
    /// One engine [`Value`], boxed.
    Value,
}

impl Kind {
    /// The header word for a block of this kind: kind bits plus the payload size.
    fn slot(self, size: usize) -> u32 {
        match self {
            // `...10`: a byte block. The trailing bits are not decoration — a fresh
            // `js_malloc(ctx, 0)` records size 0, and a header of all zeros has to be
            // distinguishable from one this allocator never wrote.
            Kind::Bytes => {
                debug_assert!(size <= MAX_PAYLOAD);
                ((size as u32) << 2) | 0b10
            }
            // `...01`: a box, whose size is fixed by its type, so nothing is recorded.
            Kind::Value => 0b01,
        }
    }

    /// The kind and payload size a header word claims.
    fn decode(slot: u32) -> Option<(Kind, usize)> {
        match slot & 0b11 {
            0b01 if slot == Kind::Value.slot(0) => Some((Kind::Value, size_of::<Value>())),
            0b10 => Some((Kind::Bytes, (slot >> 2) as usize)),
            _ => None,
        }
    }
}

/// The header at the front of every block.
#[repr(C)]
struct Header {
    /// [`Kind`] and payload size, packed as [`Kind::slot`] describes.
    slot: u32,
    /// `int ref_count`, at `REF_COUNT_OFFSET`, so `__js_rc(payload)` lands on it.
    ref_count: i32,
}

// The two offsets C depends on. A change here is a silent ABI break — `__js_rc` would
// decrement a field of the engine's `Value` instead of the count — so it is a compile-time
// failure rather than a test that might not run.
const _: () = assert!(core::mem::offset_of!(Header, ref_count) == REF_COUNT_OFFSET);
const _: () = assert!(core::mem::align_of::<Value>() <= ALIGN);

/// The allocation layout for a block holding `size` payload bytes.
fn layout_for(size: usize) -> Option<Layout> {
    if size > MAX_PAYLOAD {
        return None;
    }
    // Never zero: `Layout` refuses a zero size, and `js_malloc(ctx, 0)` must still answer a
    // pointer C can pass back to `js_free`.
    let padded = size.max(size_of::<Value>());
    Layout::from_size_align(padded.checked_add(HEADER_SIZE)?, ALIGN).ok()
}

/// The payload size a live block was allocated with.
///
/// # Safety
///
/// `block` must point at a live block from this allocator.
unsafe fn header_of(block: *mut u8) -> Option<(Kind, usize)> {
    // SAFETY: the caller guarantees a live block, whose first word is the header slot.
    let slot = unsafe { (block as *const u32).read() };
    Kind::decode(slot)
}

/// Write the header of a fresh block.
///
/// `ref_count` starts at 1 — the caller holds the only reference. For a byte block it is
/// never read, but keeping it in the layout is what makes the two families interchangeable
/// here and in [`free_raw`].
///
/// # Safety
///
/// `block` must point at `HEADER_SIZE` writable bytes.
unsafe fn write_header(block: *mut u8, kind: Kind, size: usize) {
    // SAFETY: the caller guarantees the header is writable and 4-byte aligned.
    unsafe {
        (block as *mut u32).write(kind.slot(size));
        (block.add(REF_COUNT_OFFSET) as *mut i32).write(1);
    }
}

/// `js_malloc`: `size` bytes, uninitialised, with a header in front.
///
/// Answers a null pointer when the size cannot be represented or the allocator is out of
/// memory, which is what the reference does rather than aborting: a script asking for 2^60
/// bytes must get a `RangeError`, not a dead process.
///
/// # Safety
///
/// The answer must be released exactly once with [`free_raw`], and the whole
/// `HEADER_SIZE + size` range is writable until then.
pub unsafe fn alloc_raw(size: usize) -> *mut u8 {
    let Some(layout) = layout_for(size) else {
        return std::ptr::null_mut();
    };
    // SAFETY: `layout` has a non-zero size, as `alloc` requires.
    let block = unsafe { alloc(layout) };
    if block.is_null() {
        return std::ptr::null_mut();
    }
    // SAFETY: `block` covers `layout.size()` writable bytes, which includes the header.
    unsafe {
        write_header(block, Kind::Bytes, size);
        block.add(PAYLOAD_OFFSET)
    }
}

/// `js_mallocz`: [`alloc_raw`], zeroed.
///
/// # Safety
///
/// Same contract as [`alloc_raw`].
pub unsafe fn alloc_raw_zeroed(size: usize) -> *mut u8 {
    let Some(layout) = layout_for(size) else {
        return std::ptr::null_mut();
    };
    // SAFETY: `layout` has a non-zero size, as `alloc_zeroed` requires.
    let block = unsafe { alloc_zeroed(layout) };
    if block.is_null() {
        return std::ptr::null_mut();
    }
    // SAFETY: the header is inside the allocation; zeroing cleared it, so it is written now.
    unsafe {
        write_header(block, Kind::Bytes, size);
        block.add(PAYLOAD_OFFSET)
    }
}

/// `js_realloc`: resize a block from [`alloc_raw`], keeping its contents.
///
/// # Safety
///
/// `payload` must be null or come from [`alloc_raw`]/[`alloc_raw_zeroed`]/[`realloc_raw`]
/// together with the size it currently has, and must not be used again afterwards.
pub unsafe fn realloc_raw(payload: *mut u8, old_size: usize, new_size: usize) -> *mut u8 {
    if payload.is_null() {
        // SAFETY: `alloc_raw`'s contract, which the caller already holds.
        return unsafe { alloc_raw(new_size) };
    }
    if new_size == 0 {
        // SAFETY: `payload` is a live block with `old_size`.
        unsafe { free_raw(payload) };
        return std::ptr::null_mut();
    }
    let (Some(old_layout), Some(new_layout)) = (layout_for(old_size), layout_for(new_size)) else {
        // The original block is untouched, which is `realloc`'s contract on failure.
        return std::ptr::null_mut();
    };
    // SAFETY: `payload - HEADER_SIZE` is the block `alloc_raw` returned, still alive.
    let block = unsafe { payload.sub(PAYLOAD_OFFSET) };
    // SAFETY: the same allocation with the layout it was created with; `new_layout` is
    // non-zero and at least as aligned as the old one.
    let moved = unsafe { raw_realloc(block, old_layout, new_layout.size()) };
    if moved.is_null() {
        return std::ptr::null_mut();
    }
    // SAFETY: `moved` is a fresh block of `new_layout`, and its header came along with the
    // bytes. The size word has to be refreshed because `realloc` may have grown the block.
    unsafe {
        write_header(moved, Kind::Bytes, new_size);
        moved.add(PAYLOAD_OFFSET)
    }
}

/// `js_free`: release a block from [`alloc_raw`], or do nothing for a null pointer.
///
/// # Safety
///
/// `payload` must be null, or come from [`alloc_raw`]/[`alloc_raw_zeroed`]/[`realloc_raw`]
/// with its current size, and the caller must not use it afterwards.
pub unsafe fn free_raw(payload: *mut u8) {
    if payload.is_null() {
        return;
    }
    // SAFETY: the caller guarantees `payload` came from this allocator.
    let block = unsafe { payload.sub(PAYLOAD_OFFSET) };
    // SAFETY: the block is live, so its header is readable.
    let Some((kind, size)) = (unsafe { header_of(block) }) else {
        debug_assert!(false, "js_free on a block this allocator did not produce");
        return;
    };
    debug_assert_eq!(kind, Kind::Bytes, "js_free on a value box");
    // SAFETY: `size` came from the header of a live block, so `layout_for` reproduces the
    // layout `alloc_raw` used.
    if let Some(layout) = layout_for(size) {
        // SAFETY: exactly that layout, and the block is still alive.
        unsafe { dealloc(block, layout) };
    }
}

/// The payload size recorded in a block's header.
///
/// # Safety
///
/// `payload` must be null or come from this allocator.
pub unsafe fn payload_size(payload: *mut u8) -> usize {
    if payload.is_null() {
        return 0;
    }
    // SAFETY: the caller guarantees a live block.
    let block = unsafe { payload.sub(PAYLOAD_OFFSET) };
    // SAFETY: the header of a live block is readable.
    unsafe { header_of(block) }.map_or(0, |(_, size)| size)
}

/// One engine [`Value`] in a block whose payload pointer is also a `JSValue`.
///
/// The layout is load-bearing: `header.ref_count` sits at `+4` and `value` at `+8`, so
/// `JS_VALUE_GET_PTR(v) - 4` addresses the count, and [`free_value`] recovers the `Value`
/// from the payload pointer alone. Both offsets are asserted at compile time by the
/// `offset_of!` lines above, and again from the C side of the arithmetic in
/// `tests/abi.rs`.
#[repr(C)]
pub struct ValueBox {
    header: Header,
    value: Value,
}

const _: () = assert!(core::mem::offset_of!(ValueBox, value) == PAYLOAD_OFFSET);
const _: () = assert!(core::mem::offset_of!(ValueBox, header) == 0);

impl ValueBox {
    /// `ref_count` as C's `__js_rc` reads it: an `int` four bytes before the payload.
    ///
    /// Public because the test that proves the arrangement has to do C's arithmetic, and
    /// doing it from Rust is the point — the alternative is trusting the comment.
    ///
    /// # Safety
    ///
    /// `payload` must be a live payload from [`box_value`].
    pub unsafe fn ref_count(payload: *mut ()) -> i32 {
        // SAFETY: the caller guarantees a live payload, whose header precedes it.
        unsafe { (payload.cast::<u8>().sub(4) as *const i32).read() }
    }

    /// Set the count the way C's inline `JS_DupValue` / `JS_FreeValue` do.
    ///
    /// # Safety
    ///
    /// `payload` must be a live payload from [`box_value`].
    pub unsafe fn set_ref_count(payload: *mut (), count: i32) {
        // SAFETY: the caller guarantees a live payload, whose header precedes it.
        unsafe {
            (payload.cast::<u8>().sub(4) as *mut i32).write(count);
        }
    }
}

/// Box `value` so that `JS_VALUE_GET_PTR` on the answer can be `--`'d from C.
///
/// The box owns one strong reference to the engine value, so the engine keeps the payload
/// alive exactly as long as the C side holds a `JSValue`, and not one moment longer: the
/// reference implementation's determinism comes from precisely this.
///
/// The tag is chosen by what the value *is*, because C's `JS_IsString` reads the tag:
/// strings answer `JS_TAG_STRING`, everything else `JS_TAG_OBJECT`. Both are negative, so
/// both carry a reference count.
pub fn box_value(value: Value) -> JsValue {
    let tag = match &value {
        Value::String(_) => ENGINE_STRING_TAG,
        _ => ENGINE_BOX_TAG,
    };
    let block = Box::new(ValueBox {
        header: Header {
            slot: Kind::Value.slot(0),
            ref_count: 1,
        },
        value,
    });
    let payload = (&raw const block.value) as *mut ();
    // Leaked on purpose: the reference count *is* the ownership, and C's inline decrement
    // plus `__JS_FreeValue` reclaims the box. Forgetting here is what hands ownership over.
    std::mem::forget(block);
    JsValue::mkptr(tag, payload)
}

/// The engine value behind a payload pointer.
///
/// # Safety
///
/// `payload` must be a live payload from [`box_value`].
pub unsafe fn value_of(payload: *mut ()) -> Value {
    // SAFETY: the caller guarantees the payload is a live `ValueBox`'s `value` field.
    unsafe { (&*(payload as *const Value)).clone() }
}

/// Reclaim a value box, dropping the engine value it held.
///
/// This is `__JS_FreeValue` once the count reaches zero, and therefore the moment a host
/// class's `finalizer` runs (see `ClassDef` in the engine). It is the seam NFR-4's
/// "deterministic release" rests on: without it, a script's garbage would be freed by Rust
/// at some unrelated later point.
///
/// # Safety
///
/// `payload` must be a live payload from [`box_value`] whose count has reached zero, and
/// must not be used again.
pub unsafe fn free_value(payload: *mut ()) {
    if payload.is_null() {
        return;
    }
    // SAFETY: the payload is `ValueBox::value` of a live box, and `value` is at
    // `PAYLOAD_OFFSET`, so subtracting that recovers the block.
    let block = unsafe { payload.cast::<u8>().sub(PAYLOAD_OFFSET) as *mut ValueBox };
    debug_assert_eq!(
        // SAFETY: the header of a live box.
        unsafe { (*block).header.slot },
        Kind::Value.slot(0),
        "__JS_FreeValue on something that is not a value box"
    );
    // SAFETY: `box_value` leaked this box and the count is zero, so this is the unique
    // owner. Dropping it drops the engine `Value`, which is the whole point.
    drop(unsafe { Box::from_raw(block) });
}