quickjs-capi 0.13.0

C ABI compatibility layer: the QuickJS C API on top of the pure-Rust engine
Documentation
//! `quickjs-capi` — the QuickJS C API on top of the pure-Rust engine.
//!
//! The library this crate produces is `libquickjs.so`, and it is meant to be a drop-in
//! replacement for the reference implementation's at link time: same exported symbols,
//! same `JSValue` bit layout, same struct offsets. `docs/m15-plan.md` is the reasoning;
//! this is the code.
//!
//! # How the two representations meet
//!
//! The engine's `Value` is a 16-byte enum. C's `JSValue` is 8 bytes of NaN boxing. The
//! mapping has to be *bit*-compatible rather than a conversion at the boundary, because
//! `quickjs.h` ships 119 of its "functions" as `static inline` and they run in the
//! caller's translation unit — `JS_DupValue` increments a count through a raw pointer that
//! only exists because we put it there.
//!
//! * [`jsvalue`] is the bit half: tags, encode, decode. No `unsafe`.
//! * [`alloc`] is the memory half: the header that puts `ref_count` four bytes before the
//!   payload, and the boxes that hold engine values.
//!
//! # `unsafe` is the whole point of this crate
//!
//! Everything a C caller can do to a `JSValue` — duplicate it, free it, read a field of a
//! struct we handed over — happens outside Rust's type system. `scripts/check-unsafe.sh`
//! lists this crate as a deliberate exception for that reason, and each `unsafe` block
//! below carries the argument for why it is sound.
//!
//! # Status
//!
//! M15's S2: the value/allocator layer plus the `js_malloc` family of exports. The
//! remaining symbols are S3–S7 in `docs/m15-plan.md` §5. This crate is `publish = false`
//! until that surface is complete — a `libquickjs` missing half its symbols is worse than
//! no `libquickjs`.

#![deny(unsafe_op_in_unsafe_fn)]
#![warn(missing_docs)]

use core::ffi::c_void;

pub mod alloc;
pub mod atoms;
pub mod bjson;
pub mod buffers;
pub mod builtins_typed;
pub mod calls;
pub mod cdefs;
pub mod conversions;
pub mod convert;
pub mod host;
pub mod intrinsics;
pub mod jsvalue;
pub mod module_api;
pub mod modules;
pub mod objects;
pub mod properties;
pub mod runtime;
pub mod state;
pub mod value_helpers;

pub use jsvalue::JsValue;

pub use runtime::{JsContext, JsRuntime};

// `release` and `argument` are the two halves of the ownership rule the whole API follows
// (a returned value is a new reference; an argument is borrowed), so they are reachable
// from a Rust-side caller as well as from this crate's own exports.
pub use runtime::{argument, release};

// ---------------------------------------------------------------------------
// js_malloc and friends
//
// Signatures and nullptr behaviour are the reference's: a size that cannot be represented
// gives a null pointer rather than an abort, so a script asking for 2^60 bytes gets a
// RangeError instead of a dead process.
// ---------------------------------------------------------------------------

/// `js_malloc`: `size` bytes owned by the runtime, zeroed by nobody.
///
/// # Safety
///
/// The answer must be released with `js_free`/`js_free_rt` (or `js_realloc`), and `size`
/// bytes from it may be written in the meantime.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn js_malloc(_ctx: *mut JsContext, size: usize) -> *mut c_void {
    // SAFETY: the caller's contract is exactly `alloc_raw`'s.
    unsafe { alloc::alloc_raw(size) }.cast()
}

/// `js_mallocz`: [`js_malloc`], zeroed.
///
/// # Safety
///
/// Same as [`js_malloc`].
#[unsafe(no_mangle)]
pub unsafe extern "C" fn js_mallocz(_ctx: *mut JsContext, size: usize) -> *mut c_void {
    // SAFETY: the caller's contract is exactly `alloc_raw_zeroed`'s.
    unsafe { alloc::alloc_raw_zeroed(size) }.cast()
}

/// `js_malloc_rt`: the runtime-level spelling of [`js_malloc`].
///
/// # Safety
///
/// Same as [`js_malloc`].
#[unsafe(no_mangle)]
pub unsafe extern "C" fn js_malloc_rt(_rt: *mut JsRuntime, size: usize) -> *mut c_void {
    // SAFETY: the caller's contract is exactly `alloc_raw`'s.
    unsafe { alloc::alloc_raw(size) }.cast()
}

/// `js_mallocz_rt`: the runtime-level spelling of [`js_mallocz`].
///
/// # Safety
///
/// Same as [`js_malloc`].
#[unsafe(no_mangle)]
pub unsafe extern "C" fn js_mallocz_rt(_rt: *mut JsRuntime, size: usize) -> *mut c_void {
    // SAFETY: the caller's contract is exactly `alloc_raw_zeroed`'s.
    unsafe { alloc::alloc_raw_zeroed(size) }.cast()
}

/// `js_free`: release a block from [`js_malloc`], or do nothing for a null pointer.
///
/// # Safety
///
/// `ptr` must be null or a live pointer from the `js_malloc` family, and must not be used
/// afterwards.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn js_free(_ctx: *mut JsContext, ptr: *mut c_void) {
    // SAFETY: the caller's contract is exactly `free_raw`'s.
    unsafe { alloc::free_raw(ptr.cast()) }
}

/// `js_free_rt`: the runtime-level spelling of [`js_free`].
///
/// # Safety
///
/// Same as [`js_free`].
#[unsafe(no_mangle)]
pub unsafe extern "C" fn js_free_rt(_rt: *mut JsRuntime, ptr: *mut c_void) {
    // SAFETY: the caller's contract is exactly `free_raw`'s.
    unsafe { alloc::free_raw(ptr.cast()) }
}

/// `js_realloc`: resize a block from [`js_malloc`], keeping its contents.
///
/// # Safety
///
/// `ptr` must be null or a live pointer from the `js_malloc` family with `size` bytes, and
/// must not be used again afterwards.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn js_realloc(
    _ctx: *mut JsContext,
    ptr: *mut c_void,
    size: usize,
) -> *mut c_void {
    // `js_realloc` has no way to be told the old size — the reference asks its allocator,
    // which records it. Ours records the payload size in the block header, so this is the
    // one place the two contracts differ, and reading the header is what closes the gap.
    let old_size = unsafe { alloc::payload_size(ptr.cast()) };
    // SAFETY: `ptr` is a live block of `old_size`, as `realloc_raw` requires.
    unsafe { alloc::realloc_raw(ptr.cast(), old_size, size) }.cast()
}

/// `js_realloc_rt`: the runtime-level spelling of [`js_realloc`].
///
/// # Safety
///
/// Same as [`js_realloc`].
#[unsafe(no_mangle)]
pub unsafe extern "C" fn js_realloc_rt(
    _rt: *mut JsRuntime,
    ptr: *mut c_void,
    size: usize,
) -> *mut c_void {
    let old_size = unsafe { alloc::payload_size(ptr.cast()) };
    // SAFETY: `ptr` is a live block of `old_size`, as `realloc_raw` requires.
    unsafe { alloc::realloc_raw(ptr.cast(), old_size, size) }.cast()
}

/// `js_realloc2`: [`js_realloc`] that also reports the slack.
///
/// The reference answers `NULL` without reallocating when growing would not be worth it;
/// ours always reallocates and reports the difference. `*pslack` is only written when the
/// pointer is non-null, which is what the callers in `quickjs-libc.c` rely on.
///
/// # Safety
///
/// Same as [`js_realloc`]; `pslack` must be null or writable.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn js_realloc2(
    _ctx: *mut JsContext,
    ptr: *mut c_void,
    size: usize,
    pslack: *mut usize,
) -> *mut c_void {
    let old_size = unsafe { alloc::payload_size(ptr.cast()) };
    // SAFETY: `ptr` is a live block of `old_size`.
    let answer = unsafe { alloc::realloc_raw(ptr.cast(), old_size, size) };
    if !answer.is_null() && !pslack.is_null() {
        // SAFETY: the caller promised `pslack` is writable.
        unsafe { *pslack = size };
    }
    answer.cast()
}

/// `js_malloc_usable_size`: how big a block actually is.
///
/// Ours records the requested size rather than the allocation's, so this answers what was
/// asked for. The reference answers the same number for its small blocks and a rounded one
/// for large ones; nothing in the C API depends on the difference — `quickjs-libc.c` uses
/// it only to size a read.
///
/// # Safety
///
/// `ptr` must be null or a live pointer from the `js_malloc` family.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn js_malloc_usable_size(_ctx: *mut JsContext, ptr: *const c_void) -> usize {
    // SAFETY: the caller's contract is `payload_size`'s.
    unsafe { alloc::payload_size(ptr.cast_mut().cast()) }
}

/// `js_malloc_usable_size_rt`: the runtime-level spelling of
/// [`js_malloc_usable_size`].
///
/// # Safety
///
/// Same as [`js_malloc_usable_size`].
#[unsafe(no_mangle)]
pub unsafe extern "C" fn js_malloc_usable_size_rt(
    _rt: *mut JsRuntime,
    ptr: *const c_void,
) -> usize {
    // SAFETY: the caller's contract is `payload_size`'s.
    unsafe { alloc::payload_size(ptr.cast_mut().cast()) }
}

// ---------------------------------------------------------------------------
// Reference counting
// ---------------------------------------------------------------------------

/// `__JS_FreeValue`: drop a value whose count just reached zero.
///
/// Never called directly by C: the inline `JS_FreeValue` decrements first and calls this
/// only on the transition to zero. A value that carries no reference count is a no-op,
/// which the inline already filtered out — the check is here too so that a caller which
/// gets it wrong leaks nothing and crashes nothing.
///
/// # Safety
///
/// `value` must be a payload from this crate whose count has reached zero, and must not be
/// used again.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn __JS_FreeValue(_ctx: *mut JsContext, value: JsValue) {
    let Some(payload) = value.as_ptr() else {
        return;
    };
    // SAFETY: the caller guarantees the count reached zero, so this box has no other owner.
    unsafe { alloc::free_value(payload) }
}

/// `__JS_FreeValueRT`: the runtime-level spelling of [`__JS_FreeValue`].
///
/// # Safety
///
/// Same as [`__JS_FreeValue`].
#[unsafe(no_mangle)]
pub unsafe extern "C" fn __JS_FreeValueRT(_rt: *mut JsRuntime, value: JsValue) {
    let Some(payload) = value.as_ptr() else {
        return;
    };
    // SAFETY: the caller guarantees the count reached zero.
    unsafe { alloc::free_value(payload) }
}