Skip to main content

quickjs/
alloc.rs

1//! The allocator the C side shares with us, and the boxes that hold engine values.
2//!
3//! # Why there is an allocator here at all
4//!
5//! `quickjs.h` decrements a reference count *inline*, in the caller's translation unit:
6//!
7//! ```c
8//! static inline void JS_FreeValue(JSContext *ctx, JSValue v) {
9//!     if (JS_VALUE_HAS_REF_COUNT(v)) {
10//!         JSRefCountHeader *p = __js_rc(JS_VALUE_GET_PTR(v));  /* (uint32_t *)ptr - 1 */
11//!         if (--p->ref_count <= 0) __JS_FreeValue(ctx, v);
12//!     }
13//! }
14//! ```
15//!
16//! `__js_rc` is `(uint32_t *)ptr - 1`, so **the four bytes immediately before every
17//! reference-counted payload must be a writable `int`**. No Rust container can promise
18//! that, so the payloads C sees are allocated here, with the reference's own header
19//! shape:
20//!
21//! ```text
22//! block + 0 : u32  kind and size   (see Kind::slot)
23//! block + 4 : i32  ref_count       <- what __js_rc(payload) points at
24//! block + 8 : ...  payload         <- JS_VALUE_GET_PTR
25//! ```
26//!
27//! That is also why `js_malloc` / `js_free` live in the same allocator as the boxes:
28//! `bjson.c` hands us a buffer from `JS_WriteObject` and then calls `js_free` on it, and
29//! two allocators would mean freeing a pointer we never allocated.
30//!
31//! # Two families, one header
32//!
33//! * [`alloc_raw`] / [`free_raw`] — untyped bytes, for `js_malloc` and the buffers behind
34//!   `JS_WriteObject`.
35//! * [`box_value`] / [`free_value`] — a header plus one engine [`Value`], for every
36//!   reference-counted `JSValue` that crosses the boundary.
37//!
38//! Both put `ref_count` at `+4` and the payload at `+8`, so C's `--p->ref_count` is
39//! correct for either, and [`free_value`] is the one place an engine value is released on
40//! the C side's say-so — which is where a host class's finalizer runs.
41//!
42//! # Alignment and size limits
43//!
44//! Payloads are 8-byte aligned, matching the reference's `JS_MALLOC_ALIGN`. That is enough
45//! for a `double`, a pointer, and the `uint64_t` arrays `tests/bjson.c` builds.
46//!
47//! The size of a byte block is recorded in the same 32-bit word as its kind, so a single
48//! block tops out at 1 GiB − 8 bytes. Nothing in the C API asks for more: the one large
49//! buffer it produces is `JS_WriteObject`'s output, and a 1 GiB serialisation is already
50//! beyond what `test_bjson.js` exercises. A block that big is answered with a null pointer,
51//! which every caller already has to handle.
52
53use std::alloc::{Layout, alloc, alloc_zeroed, dealloc, realloc as raw_realloc};
54
55use engine::Value;
56
57use crate::jsvalue::{ENGINE_BOX_TAG, ENGINE_STRING_TAG, JsValue};
58
59/// Size of the header in front of every payload: two 32-bit words.
60pub const HEADER_SIZE: usize = 8;
61
62/// Offset of `ref_count` inside a block. `__js_rc(payload)` is `payload - 4`, so this is
63/// the number that must not move.
64pub const REF_COUNT_OFFSET: usize = 4;
65
66/// Offset of the first payload byte inside a block.
67pub const PAYLOAD_OFFSET: usize = HEADER_SIZE;
68
69/// Alignment every block is allocated with.
70pub const ALIGN: usize = 8;
71
72/// The largest payload a block may hold.
73///
74/// A byte block records its size in the same word as its kind, with two bits taken by the
75/// kind, so 30 bits are left: 1 GiB − 8 bytes in total. Anything larger is answered with a
76/// null pointer, which is the C API's "allocation failed" answer.
77pub const MAX_PAYLOAD: usize = (u32::MAX >> 2) as usize - HEADER_SIZE;
78
79/// What a block holds, as stored in the header word.
80///
81/// The kind shares its word with the size because the only other free slot is `+4`, and
82/// that one belongs to `ref_count`. `Value` blocks take the low bit; byte blocks take the
83/// low *two* bits as zero and shift the size up, so a fresh `js_malloc(0)` cannot be
84/// mistaken for a box.
85#[derive(Clone, Copy, PartialEq, Eq, Debug)]
86pub enum Kind {
87    /// Untyped bytes from `js_malloc` and friends.
88    Bytes,
89    /// One engine [`Value`], boxed.
90    Value,
91}
92
93impl Kind {
94    /// The header word for a block of this kind: kind bits plus the payload size.
95    fn slot(self, size: usize) -> u32 {
96        match self {
97            // `...10`: a byte block. The trailing bits are not decoration — a fresh
98            // `js_malloc(ctx, 0)` records size 0, and a header of all zeros has to be
99            // distinguishable from one this allocator never wrote.
100            Kind::Bytes => {
101                debug_assert!(size <= MAX_PAYLOAD);
102                ((size as u32) << 2) | 0b10
103            }
104            // `...01`: a box, whose size is fixed by its type, so nothing is recorded.
105            Kind::Value => 0b01,
106        }
107    }
108
109    /// The kind and payload size a header word claims.
110    fn decode(slot: u32) -> Option<(Kind, usize)> {
111        match slot & 0b11 {
112            0b01 if slot == Kind::Value.slot(0) => Some((Kind::Value, size_of::<Value>())),
113            0b10 => Some((Kind::Bytes, (slot >> 2) as usize)),
114            _ => None,
115        }
116    }
117}
118
119/// The header at the front of every block.
120#[repr(C)]
121struct Header {
122    /// [`Kind`] and payload size, packed as [`Kind::slot`] describes.
123    slot: u32,
124    /// `int ref_count`, at `REF_COUNT_OFFSET`, so `__js_rc(payload)` lands on it.
125    ref_count: i32,
126}
127
128// The two offsets C depends on. A change here is a silent ABI break — `__js_rc` would
129// decrement a field of the engine's `Value` instead of the count — so it is a compile-time
130// failure rather than a test that might not run.
131const _: () = assert!(core::mem::offset_of!(Header, ref_count) == REF_COUNT_OFFSET);
132const _: () = assert!(core::mem::align_of::<Value>() <= ALIGN);
133
134/// The allocation layout for a block holding `size` payload bytes.
135fn layout_for(size: usize) -> Option<Layout> {
136    if size > MAX_PAYLOAD {
137        return None;
138    }
139    // Never zero: `Layout` refuses a zero size, and `js_malloc(ctx, 0)` must still answer a
140    // pointer C can pass back to `js_free`.
141    let padded = size.max(size_of::<Value>());
142    Layout::from_size_align(padded.checked_add(HEADER_SIZE)?, ALIGN).ok()
143}
144
145/// The payload size a live block was allocated with.
146///
147/// # Safety
148///
149/// `block` must point at a live block from this allocator.
150unsafe fn header_of(block: *mut u8) -> Option<(Kind, usize)> {
151    // SAFETY: the caller guarantees a live block, whose first word is the header slot.
152    let slot = unsafe { (block as *const u32).read() };
153    Kind::decode(slot)
154}
155
156/// Write the header of a fresh block.
157///
158/// `ref_count` starts at 1 — the caller holds the only reference. For a byte block it is
159/// never read, but keeping it in the layout is what makes the two families interchangeable
160/// here and in [`free_raw`].
161///
162/// # Safety
163///
164/// `block` must point at `HEADER_SIZE` writable bytes.
165unsafe fn write_header(block: *mut u8, kind: Kind, size: usize) {
166    // SAFETY: the caller guarantees the header is writable and 4-byte aligned.
167    unsafe {
168        (block as *mut u32).write(kind.slot(size));
169        (block.add(REF_COUNT_OFFSET) as *mut i32).write(1);
170    }
171}
172
173/// `js_malloc`: `size` bytes, uninitialised, with a header in front.
174///
175/// Answers a null pointer when the size cannot be represented or the allocator is out of
176/// memory, which is what the reference does rather than aborting: a script asking for 2^60
177/// bytes must get a `RangeError`, not a dead process.
178///
179/// # Safety
180///
181/// The answer must be released exactly once with [`free_raw`], and the whole
182/// `HEADER_SIZE + size` range is writable until then.
183pub unsafe fn alloc_raw(size: usize) -> *mut u8 {
184    let Some(layout) = layout_for(size) else {
185        return std::ptr::null_mut();
186    };
187    // SAFETY: `layout` has a non-zero size, as `alloc` requires.
188    let block = unsafe { alloc(layout) };
189    if block.is_null() {
190        return std::ptr::null_mut();
191    }
192    // SAFETY: `block` covers `layout.size()` writable bytes, which includes the header.
193    unsafe {
194        write_header(block, Kind::Bytes, size);
195        block.add(PAYLOAD_OFFSET)
196    }
197}
198
199/// `js_mallocz`: [`alloc_raw`], zeroed.
200///
201/// # Safety
202///
203/// Same contract as [`alloc_raw`].
204pub unsafe fn alloc_raw_zeroed(size: usize) -> *mut u8 {
205    let Some(layout) = layout_for(size) else {
206        return std::ptr::null_mut();
207    };
208    // SAFETY: `layout` has a non-zero size, as `alloc_zeroed` requires.
209    let block = unsafe { alloc_zeroed(layout) };
210    if block.is_null() {
211        return std::ptr::null_mut();
212    }
213    // SAFETY: the header is inside the allocation; zeroing cleared it, so it is written now.
214    unsafe {
215        write_header(block, Kind::Bytes, size);
216        block.add(PAYLOAD_OFFSET)
217    }
218}
219
220/// `js_realloc`: resize a block from [`alloc_raw`], keeping its contents.
221///
222/// # Safety
223///
224/// `payload` must be null or come from [`alloc_raw`]/[`alloc_raw_zeroed`]/[`realloc_raw`]
225/// together with the size it currently has, and must not be used again afterwards.
226pub unsafe fn realloc_raw(payload: *mut u8, old_size: usize, new_size: usize) -> *mut u8 {
227    if payload.is_null() {
228        // SAFETY: `alloc_raw`'s contract, which the caller already holds.
229        return unsafe { alloc_raw(new_size) };
230    }
231    if new_size == 0 {
232        // SAFETY: `payload` is a live block with `old_size`.
233        unsafe { free_raw(payload) };
234        return std::ptr::null_mut();
235    }
236    let (Some(old_layout), Some(new_layout)) = (layout_for(old_size), layout_for(new_size)) else {
237        // The original block is untouched, which is `realloc`'s contract on failure.
238        return std::ptr::null_mut();
239    };
240    // SAFETY: `payload - HEADER_SIZE` is the block `alloc_raw` returned, still alive.
241    let block = unsafe { payload.sub(PAYLOAD_OFFSET) };
242    // SAFETY: the same allocation with the layout it was created with; `new_layout` is
243    // non-zero and at least as aligned as the old one.
244    let moved = unsafe { raw_realloc(block, old_layout, new_layout.size()) };
245    if moved.is_null() {
246        return std::ptr::null_mut();
247    }
248    // SAFETY: `moved` is a fresh block of `new_layout`, and its header came along with the
249    // bytes. The size word has to be refreshed because `realloc` may have grown the block.
250    unsafe {
251        write_header(moved, Kind::Bytes, new_size);
252        moved.add(PAYLOAD_OFFSET)
253    }
254}
255
256/// `js_free`: release a block from [`alloc_raw`], or do nothing for a null pointer.
257///
258/// # Safety
259///
260/// `payload` must be null, or come from [`alloc_raw`]/[`alloc_raw_zeroed`]/[`realloc_raw`]
261/// with its current size, and the caller must not use it afterwards.
262pub unsafe fn free_raw(payload: *mut u8) {
263    if payload.is_null() {
264        return;
265    }
266    // SAFETY: the caller guarantees `payload` came from this allocator.
267    let block = unsafe { payload.sub(PAYLOAD_OFFSET) };
268    // SAFETY: the block is live, so its header is readable.
269    let Some((kind, size)) = (unsafe { header_of(block) }) else {
270        debug_assert!(false, "js_free on a block this allocator did not produce");
271        return;
272    };
273    debug_assert_eq!(kind, Kind::Bytes, "js_free on a value box");
274    // SAFETY: `size` came from the header of a live block, so `layout_for` reproduces the
275    // layout `alloc_raw` used.
276    if let Some(layout) = layout_for(size) {
277        // SAFETY: exactly that layout, and the block is still alive.
278        unsafe { dealloc(block, layout) };
279    }
280}
281
282/// The payload size recorded in a block's header.
283///
284/// # Safety
285///
286/// `payload` must be null or come from this allocator.
287pub unsafe fn payload_size(payload: *mut u8) -> usize {
288    if payload.is_null() {
289        return 0;
290    }
291    // SAFETY: the caller guarantees a live block.
292    let block = unsafe { payload.sub(PAYLOAD_OFFSET) };
293    // SAFETY: the header of a live block is readable.
294    unsafe { header_of(block) }.map_or(0, |(_, size)| size)
295}
296
297/// One engine [`Value`] in a block whose payload pointer is also a `JSValue`.
298///
299/// The layout is load-bearing: `header.ref_count` sits at `+4` and `value` at `+8`, so
300/// `JS_VALUE_GET_PTR(v) - 4` addresses the count, and [`free_value`] recovers the `Value`
301/// from the payload pointer alone. Both offsets are asserted at compile time by the
302/// `offset_of!` lines above, and again from the C side of the arithmetic in
303/// `tests/abi.rs`.
304#[repr(C)]
305pub struct ValueBox {
306    header: Header,
307    value: Value,
308}
309
310const _: () = assert!(core::mem::offset_of!(ValueBox, value) == PAYLOAD_OFFSET);
311const _: () = assert!(core::mem::offset_of!(ValueBox, header) == 0);
312
313impl ValueBox {
314    /// `ref_count` as C's `__js_rc` reads it: an `int` four bytes before the payload.
315    ///
316    /// Public because the test that proves the arrangement has to do C's arithmetic, and
317    /// doing it from Rust is the point — the alternative is trusting the comment.
318    ///
319    /// # Safety
320    ///
321    /// `payload` must be a live payload from [`box_value`].
322    pub unsafe fn ref_count(payload: *mut ()) -> i32 {
323        // SAFETY: the caller guarantees a live payload, whose header precedes it.
324        unsafe { (payload.cast::<u8>().sub(4) as *const i32).read() }
325    }
326
327    /// Set the count the way C's inline `JS_DupValue` / `JS_FreeValue` do.
328    ///
329    /// # Safety
330    ///
331    /// `payload` must be a live payload from [`box_value`].
332    pub unsafe fn set_ref_count(payload: *mut (), count: i32) {
333        // SAFETY: the caller guarantees a live payload, whose header precedes it.
334        unsafe {
335            (payload.cast::<u8>().sub(4) as *mut i32).write(count);
336        }
337    }
338}
339
340/// Box `value` so that `JS_VALUE_GET_PTR` on the answer can be `--`'d from C.
341///
342/// The box owns one strong reference to the engine value, so the engine keeps the payload
343/// alive exactly as long as the C side holds a `JSValue`, and not one moment longer: the
344/// reference implementation's determinism comes from precisely this.
345///
346/// The tag is chosen by what the value *is*, because C's `JS_IsString` reads the tag:
347/// strings answer `JS_TAG_STRING`, everything else `JS_TAG_OBJECT`. Both are negative, so
348/// both carry a reference count.
349pub fn box_value(value: Value) -> JsValue {
350    let tag = match &value {
351        Value::String(_) => ENGINE_STRING_TAG,
352        _ => ENGINE_BOX_TAG,
353    };
354    let block = Box::new(ValueBox {
355        header: Header {
356            slot: Kind::Value.slot(0),
357            ref_count: 1,
358        },
359        value,
360    });
361    let payload = (&raw const block.value) as *mut ();
362    // Leaked on purpose: the reference count *is* the ownership, and C's inline decrement
363    // plus `__JS_FreeValue` reclaims the box. Forgetting here is what hands ownership over.
364    std::mem::forget(block);
365    JsValue::mkptr(tag, payload)
366}
367
368/// The engine value behind a payload pointer.
369///
370/// # Safety
371///
372/// `payload` must be a live payload from [`box_value`].
373pub unsafe fn value_of(payload: *mut ()) -> Value {
374    // SAFETY: the caller guarantees the payload is a live `ValueBox`'s `value` field.
375    unsafe { (&*(payload as *const Value)).clone() }
376}
377
378/// Reclaim a value box, dropping the engine value it held.
379///
380/// This is `__JS_FreeValue` once the count reaches zero, and therefore the moment a host
381/// class's `finalizer` runs (see `ClassDef` in the engine). It is the seam NFR-4's
382/// "deterministic release" rests on: without it, a script's garbage would be freed by Rust
383/// at some unrelated later point.
384///
385/// # Safety
386///
387/// `payload` must be a live payload from [`box_value`] whose count has reached zero, and
388/// must not be used again.
389pub unsafe fn free_value(payload: *mut ()) {
390    if payload.is_null() {
391        return;
392    }
393    // SAFETY: the payload is `ValueBox::value` of a live box, and `value` is at
394    // `PAYLOAD_OFFSET`, so subtracting that recovers the block.
395    let block = unsafe { payload.cast::<u8>().sub(PAYLOAD_OFFSET) as *mut ValueBox };
396    debug_assert_eq!(
397        // SAFETY: the header of a live box.
398        unsafe { (*block).header.slot },
399        Kind::Value.slot(0),
400        "__JS_FreeValue on something that is not a value box"
401    );
402    // SAFETY: `box_value` leaked this box and the count is zero, so this is the unique
403    // owner. Dropping it drops the engine `Value`, which is the whole point.
404    drop(unsafe { Box::from_raw(block) });
405}