quickjs-capi 0.15.0

C ABI compatibility layer: the QuickJS C API on top of the pure-Rust engine
Documentation
//! The ABI, asserted against what `gcc` says.
//!
//! Every literal below was printed by a C program compiled against the reference
//! `quickjs.h` on this machine:
//!
//! ```sh
//! gcc -O1 -o abi abi.c -Ioracle/quickjs-master && ./abi
//! ```
//!
//! Writing the numbers down rather than recomputing them means a drift in the encoding is a
//! failing test instead of a C program that reads the wrong field. The reproduction command
//! is in `docs/m15-plan.md` §2.
//!
//! The second half of the file does C's arithmetic *on our boxes* from Rust: a `JSValue`
//! from [`box_value`], `(uint32_t *)ptr - 1` read and written through raw pointers, exactly
//! as the inline `JS_DupValue` and `JS_FreeValue` in `quickjs.h` do. That is the only way to
//! show the arrangement is right without linking a C program — and linking one is what
//! `scripts/m15-capi.sh` does once S3 lands.

use quickjs::alloc::{self, ValueBox};
use quickjs::jsvalue::{
    self, EXCEPTION, FALSE, JsValue, NULL, TAG_BOOL, TAG_EXCEPTION, TAG_FLOAT64, TAG_INT, TAG_NULL,
    TAG_OBJECT, TAG_STRING, TAG_UNDEFINED, TRUE, UNDEFINED,
};

// ---------------------------------------------------------------------------
// The encoding, against gcc's numbers
// ---------------------------------------------------------------------------

#[test]
fn constants_match_the_reference() {
    assert_eq!(UNDEFINED.bits(), 0x0001_8000_0000_0000, "JS_UNDEFINED");
    assert_eq!(NULL.bits(), 0x0001_0000_0000_0000, "JS_NULL");
    assert_eq!(EXCEPTION.bits(), 0x0003_0000_0000_0000, "JS_EXCEPTION");
    assert_eq!(FALSE.bits(), 0x0000_8000_0000_0000, "JS_FALSE");
    assert_eq!(TRUE.bits(), FALSE.bits() | 1, "JS_TRUE is JS_FALSE | 1");
}

#[test]
fn integers_and_doubles_match_the_reference() {
    assert_eq!(jsvalue::new_int32(42).bits(), 0x0000_0000_0000_002a);
    assert_eq!(jsvalue::new_int32(-1).bits(), 0x0000_0000_ffff_ffff);
    assert_eq!(jsvalue::new_float64(1.5).bits(), 0xbffc_0000_0000_0000);
    assert_eq!(jsvalue::NAN, 0x7ffc_0000_0000_0000, "JS_NAN");
    assert_eq!(
        jsvalue::FLOAT64_ADDEND,
        0x7ffc_0000_0000_0000,
        "JS_FLOAT64_ADDEND"
    );
}

#[test]
fn tags_match_the_reference() {
    assert_eq!(TAG_OBJECT, -1);
    assert_eq!(TAG_INT, 0);
    assert_eq!(TAG_BOOL, 1);
    assert_eq!(TAG_NULL, 2);
    assert_eq!(TAG_UNDEFINED, 3);
    assert_eq!(TAG_EXCEPTION, 6);
    assert_eq!(TAG_FLOAT64, 8);
    assert_eq!(TAG_STRING, -5);
    assert_eq!(jsvalue::TAG_FIRST, -8);
    // `sizeof(JSValue) == 8`: the whole reason for NaN boxing.
    assert_eq!(core::mem::size_of::<JsValue>(), 8);
    // `sizeof(JSRefCountHeader) == 4`: `__js_rc` points at an `int`.
    assert_eq!(alloc::REF_COUNT_OFFSET, 4);
    assert_eq!(core::mem::size_of::<i32>(), 4);
}

#[test]
fn a_value_is_undefined_after_the_default_constructor() {
    // Not a natural identity: bits `0` decode as the integer `0`, so a `JSValue` that was
    // zero-initialised by C would be a number. `JS_UNDEFINED` has to be written.
    assert_ne!(JsValue::new(0), UNDEFINED);
    assert_eq!(JsValue::default(), UNDEFINED);
}

// ---------------------------------------------------------------------------
// C's arithmetic on our boxes
// ---------------------------------------------------------------------------

/// The inline `JS_DupValue`: `p->ref_count++`.
///
/// # Safety
///
/// `payload` must be a live payload from `box_value`.
unsafe fn c_dup(payload: *mut ()) {
    // SAFETY: the caller guarantees a live payload, which is all `__js_rc` needs.
    let count = unsafe { ValueBox::ref_count(payload) };
    // SAFETY: as above.
    unsafe { ValueBox::set_ref_count(payload, count + 1) };
}

/// The inline `JS_FreeValue`: decrement, and call `__JS_FreeValue` on the way to zero.
///
/// # Safety
///
/// `value` must be a live `JSValue` from `box_value`, and must not be used again.
unsafe fn c_free(value: JsValue) {
    if !value.has_ref_count() {
        return;
    }
    let payload = value.as_ptr().expect("a refcounted value has a payload");
    // SAFETY: the caller guarantees a live payload.
    let count = unsafe { ValueBox::ref_count(payload) };
    // SAFETY: as above.
    unsafe { ValueBox::set_ref_count(payload, count - 1) };
    if count - 1 <= 0 {
        // SAFETY: the count has just reached zero, so this is the last reference.
        unsafe { quickjs::__JS_FreeValue(core::ptr::null_mut(), value) };
    }
}

/// A string value plus the `Gc` handle, so the test can watch the engine side.
fn engine_string(
    ctx: &mut engine::Context<'_>,
    text: &str,
) -> (engine::Value, engine::Gc<engine::JsString>) {
    let value = ctx.new_string(text);
    let engine::Value::String(handle) = value.clone() else {
        panic!("new_string must answer a string");
    };
    (value, handle)
}

#[test]
fn ref_count_sits_four_bytes_before_the_payload() {
    let runtime = engine::Runtime::new();
    let mut ctx = engine::Context::new(&runtime);
    let (value, _handle) = engine_string(&mut ctx, "hello");

    let boxed = alloc::box_value(value);
    let payload = boxed.as_ptr().expect("a string carries a count");

    // This is `__js_rc`: `(uint32_t *)ptr - 1`, so four bytes before the payload, not
    // eight. Writing through that address must change the count the API reads.
    // SAFETY: `boxed` came from `box_value`, so the payload is live.
    unsafe {
        assert_eq!(ValueBox::ref_count(payload), 1);
        let slot = payload.cast::<u8>().sub(4) as *mut i32;
        slot.write(5);
        assert_eq!(
            ValueBox::ref_count(payload),
            5,
            "the count lives at payload - 4"
        );
        slot.write(1);
    }
    assert!(boxed.is_string(), "a boxed string keeps JS_TAG_STRING");

    // Duplicate twice, free twice: still alive, because one reference is left.
    // SAFETY: the payload is live throughout.
    unsafe {
        c_dup(payload);
        c_dup(payload);
        assert_eq!(ValueBox::ref_count(payload), 3);
        c_free(boxed);
        c_free(boxed);
        assert_eq!(ValueBox::ref_count(payload), 1);
        c_free(boxed);
    }
}

#[test]
fn the_last_free_releases_the_engine_value() {
    let runtime = engine::Runtime::new();
    let mut ctx = engine::Context::new(&runtime);
    let (value, handle) = engine_string(&mut ctx, "hello");
    // Two handles on the engine string: the `Value` and the test's clone of its `Gc`.
    let baseline = handle.strong_count();

    let boxed = alloc::box_value(value.clone());
    assert_eq!(
        handle.strong_count(),
        baseline + 1,
        "the box holds a reference"
    );

    // SAFETY: the payload is live; one decrement takes the count from 1 to 0.
    unsafe { c_free(boxed) };
    assert_eq!(
        handle.strong_count(),
        baseline,
        "the box's reference is gone, and with it the engine value"
    );

    // The engine value itself outlives the box here because the test still holds two
    // handles on it; the count is what proves the box's reference went away.
    drop(value);
    drop(handle);
    drop(ctx);
    let _ = &runtime;
}

#[test]
fn a_primitive_needs_no_allocation_at_all() {
    // The whole point of NaN boxing: `JS_NewInt32(7)` allocates nothing, so there is no
    // count to decrement and `JS_FreeValue` on it must do nothing.
    let encoded = quickjs::convert::encode(&engine::Value::Int(7));
    assert!(!encoded.has_ref_count());
    assert_eq!(encoded.bits(), 7, "an int is the bare payload");
    // SAFETY: nothing was allocated, and the function checks the tag before touching a
    // payload.
    unsafe { quickjs::__JS_FreeValue(core::ptr::null_mut(), encoded) };
    // A null payload never reaches the allocator either.
    // SAFETY: as above.
    unsafe { quickjs::__JS_FreeValue(core::ptr::null_mut(), jsvalue::UNDEFINED) };
}

// ---------------------------------------------------------------------------
// js_malloc
// ---------------------------------------------------------------------------

#[test]
fn js_mallocz_zeroes_and_js_free_releases() {
    // SAFETY: the pointer comes back from `js_mallocz` and is released once.
    unsafe {
        let bytes = quickjs::js_mallocz(core::ptr::null_mut(), 64).cast::<u8>();
        assert!(!bytes.is_null());
        for index in 0..64 {
            assert_eq!(*bytes.add(index), 0, "byte {index} was not zeroed");
        }
        assert_eq!(
            quickjs::js_malloc_usable_size(core::ptr::null_mut(), bytes.cast()),
            64
        );
        quickjs::js_free(core::ptr::null_mut(), bytes.cast());
    }
}

#[test]
fn js_malloc_payload_is_aligned_and_writable() {
    // SAFETY: fresh block, written and released once.
    unsafe {
        let bytes = quickjs::js_malloc(core::ptr::null_mut(), 32).cast::<u8>();
        assert!(!bytes.is_null());
        assert_eq!(
            bytes as usize % alloc::ALIGN,
            0,
            "payload must be 8-byte aligned"
        );
        // A `uint64_t` store at the first byte, which is what `bjson.c` does to its output.
        bytes.cast::<u64>().write(0x1234_5678_9abc_def0);
        assert_eq!(bytes.cast::<u64>().read(), 0x1234_5678_9abc_def0);
        quickjs::js_free(core::ptr::null_mut(), bytes.cast());
    }
}

#[test]
fn js_realloc_keeps_the_contents() {
    // SAFETY: one block, grown and then released once.
    unsafe {
        let first = quickjs::js_malloc(core::ptr::null_mut(), 8).cast::<u8>();
        first.write(b'x');
        let grown = quickjs::js_realloc(core::ptr::null_mut(), first.cast(), 4096).cast::<u8>();
        assert!(!grown.is_null());
        assert_eq!(grown.read(), b'x', "contents survived the move");
        assert_eq!(
            quickjs::js_malloc_usable_size(core::ptr::null_mut(), grown.cast()),
            4096,
            "the header records the new size"
        );
        quickjs::js_free(core::ptr::null_mut(), grown.cast());
    }
}

#[test]
fn a_zero_byte_allocation_is_still_freeable() {
    // `js_malloc(ctx, 0)` may answer anything but null, and `js_free` must accept it: the
    // reference's allocator gives a real block, and callers rely on the round trip.
    // SAFETY: allocated and released once.
    unsafe {
        let bytes = quickjs::js_mallocz(core::ptr::null_mut(), 0);
        assert!(!bytes.is_null());
        quickjs::js_free(core::ptr::null_mut(), bytes);
        // A null pointer is a no-op, as in C.
        quickjs::js_free(core::ptr::null_mut(), core::ptr::null_mut());
        quickjs::js_free_rt(core::ptr::null_mut(), core::ptr::null_mut());
    }
}

#[test]
fn an_impossible_size_answers_null() {
    // 2^60 bytes must not abort the process: the C API's contract is a null pointer, and
    // `js_mallocz` is how a script asking for a huge typed array finds out.
    // SAFETY: no allocation happens, so nothing has to be freed.
    unsafe {
        assert!(quickjs::js_mallocz(core::ptr::null_mut(), usize::MAX).is_null());
        assert!(quickjs::js_malloc(core::ptr::null_mut(), usize::MAX / 2).is_null());
    }
}

#[test]
fn the_two_allocator_families_share_one_header() {
    // `bjson.c` frees a `JS_WriteObject` buffer with `js_free`, so a byte block has to
    // carry the same header as a value box: `ref_count` four bytes before the payload. The
    // count is meaningless for bytes, but the *offset* is what makes one allocator enough.
    // SAFETY: one block, written and released once.
    unsafe {
        let bytes = quickjs::js_malloc(core::ptr::null_mut(), 16).cast::<u8>();
        assert!(!bytes.is_null());
        assert_eq!(
            (bytes.sub(4) as *const i32).read(),
            1,
            "ref_count at payload - 4"
        );
        quickjs::js_free(core::ptr::null_mut(), bytes.cast());
    }
}