quickjs-capi 0.14.2

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. This is M15 in docs/m15-plan.md: the library that makes libquickjs.so replaceable at link time, so the existing Go, Python and Rust bindings — and every C module written against quickjs.h — keep working.

Status: M15 done (S1–S7). All 211 symbols the reference exports are exported here, plus the 11 js_* allocator entry points and JS_IsException (the header's static inline, exported so Rust tests can take its address) — 223 in all. A real C class — Point, with an opaque payload, magic accessors and a finalizer — compiles against the reference header and links against this library, and qjs -m loads fib.so/point.so/bjson.so with output byte-identical to the reference.

"All 223 exported" is not "all 223 behave identically": 194 are exact, 17 are partial and 12 are present and refuse, and each one says so in tests/symbols.rs — a literal 223-row table of symbol plus a one-line verdict (yes, partly, no), with a test that fails when a symbol is added without a row or a row outlives its symbol. The gaps are named and reasoned below. The crate stays publish = false until S7's from-scratch embedding path is exercised from C.

Why this is not a shim

quickjs.h ships 119 of its "functions" as static inline, and they run in the caller's translation unit:

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);
    }
}

Compiled C never asks the library how a JSValue is laid out — it decodes the bits and writes through a raw pointer. So the boundary cannot be a conversion layer, and a handle table (a JSValue that is really an index) segfaults on the first JS_DupValue. Two things have to be bit-compatible:

what it is where
JSValue 8 bytes, NaN-boxed: tag in bits 47..64, payload below src/jsvalue.rs
reference counts an int at payload - 4, written by the caller src/alloc.rs

The parts

  • src/jsvalue.rs — tags, encode/decode of the bit patterns, and the constructors. Pure integer arithmetic, no unsafe. tests/abi.rs pins every constant against what gcc printed for the same expression in the reference header.
  • src/alloc.rs — the magic-header allocator. Every block is [u32 kind+size][i32 ref_count][payload], so payload - 4 is the count and payload is what JS_VALUE_GET_PTR returns. js_malloc/js_free use the same allocator as the value boxes, because bjson.c frees a JS_WriteObject buffer we allocated.
  • src/convert.rs — engine Value ⇄ JsValue. Primitives map to bits; anything with a reference count is boxed with a count of one, and the last JS_FreeValue drops the box and with it the engine's handle. That is where a host class's finalizer runs.
  • src/cdefs.rs — the C structs C fills in and we read (JSCFunctionListEntry, JSClassDef, the exotic traps), every offset asserted against offsetof on this platform.
  • src/runtime.rs — JSRuntime/JSContext, JS_Eval, pending exceptions, and the thread-local that lets a C callback find the live interpreter it was called from.
  • src/objects.rs — the object/property/function/class API.
  • src/modules.rs — JS_NewCModule and friends, and the dlopen/dlsym that finds a .so's js_init_module.
  • src/host.rs — the host session: publishes the running interpreter so a C function called from a script can reach the API.
  • src/bjson.rs — JS_WriteObject/JS_ReadObject (a format of this crate's own; see the module docs for why that is legitimate) and the ArrayBuffer bridge.
  • src/calls.rs — calls and construction, promises, jobs, instanceof, iterators.
  • src/properties.rs, src/conversions.rs, src/atoms.rs — the property/coercion/atom families, which are the bulk of the surface a binding touches first.
  • src/buffers.rs, src/builtins_typed.rs — ArrayBuffer, the views, JSON, SameValue/StrictEq, and the JSTypedArrayEnum translation.
  • src/intrinsics.rs — the sixteen JS_AddIntrinsic* calls. A context here is born with every intrinsic installed, so they answer 0; Intl and Temporal are the two the engine does not have and they answer -1 rather than lying.
  • src/module_api.rs — JS_LoadModule, the loader hooks, module private values and names, JS_DetectModule, JS_EvalThis, JS_WriteObject2.
  • src/state.rs — limits (JS_SetMemoryLimit/JS_SetMaxStackSize/JS_SetGCThreshold), GC, opaque pointers, context values, memory reporting and JS_PrintValue.

The one test that matters for "all 223"

tests/symbols.rs opens with a literal table — one row per exported symbol, each row a verdict (yes, partly, no) and one line of behaviour — and every_reference_symbol_has_a_documented_behaviour reads the reference's own nm -D output and fails when a row and a symbol disagree in either direction. scripts/verify-claims.py re-checks the same three counts against README.md, so the published numbers cannot drift from the table the way "56 of 211" did.

The re-entrancy channel

A C function installed by a module is called with nothing but a JSContext *, and the engine is inside a call while it runs — it holds the &mut Interp that JS_ToInt32 has to use. There is no second interpreter to hand out, so a callback reaches the live one through a thread-local raw pointer that every entry point installs and every API function reads. Miss that and the failure looks like a broken module: each API call answers an exception with no message, because there is no current context to describe it.

Limitations

Twenty-nine symbols are exported so a binding links, and either refuse or do a documented subset rather than pretend. Grouped by why:

  • Not in the engine at all — JS_AddIntrinsicIntl, JS_SetLocaleCallbacks (no Intl, no locale database; toLocaleString is toString), JS_AddIntrinsicTemporal (M13, unstarted), JS_SetSharedArrayBufferFunctions, JS_AtomicsSetAsyncWaker (no threads, so nothing waits), JS_SetHostPromiseRejectionTracker (the engine reports unhandled rejections itself), JS_SetIsHTMLDDA.
  • A representation this engine does not have — JS_IsImmutableArrayBuffer (always 0) and JS_SetImmutableArrayBuffer (-1), JS_NewUint8ArrayCopy2 (refuses is_immutable), JS_NewRuntime2 (a per-runtime C allocator would have to be threaded through the GC, so the default allocator is used), JS_GetImportMeta (undefined: a C module was never parsed), JS_ParseJSON3 (parses, writes no source-position record).
  • Accepted and recorded, no observable effect — JS_SetCanBlock, JS_SetStripInfo (debug info is never stripped), JS_SetRuntimeInfo, JS_UpdateStackTop (depth is measured in frames, not bytes), JS_MarkValue (reference counting, not tracing).
  • Partial by design, documented at the call site — JS_NewArrayBuffer/JS_NewUint8Array copy the C block (so writes the host makes afterwards are invisible to script) though free_func now runs at collection, as the header says; JS_SetInterruptHandler is polled at loop back-edges and calls, which is where the reference polls too; JS_NewContextRaw is JS_NewContext (a context here is born with every intrinsic, so a host that adds them gets a superset); JS_ComputeMemoryUsage fills the fields it can account for and zeroes the rest; JS_PrintValue honours all three limits but renders a class the engine's printer does not walk as its class name; JS_IsLiveObject/JS_IsCFunction answer for values the caller can legitimately hold; JS_ValueToAtom refuses a symbol, whose atom would have to keep its symbolness; JS_WriteObject2 always answers an empty shared-buffer table.

Checking it

cargo test -p quickjs-capi                 # bit encoding, allocator, C's own arithmetic
cargo test -p quickjs-capi --test symbols  # one test per behaviour, plus the 223-row table
./scripts/m15-capi.sh --abi                # a C program linked against libquickjs.so
./scripts/m15-capi.sh --exports            # our nm -D vs the reference's, name for name
./scripts/m15-capi.sh --embed              # tests/c/embed.c built twice and compared
./scripts/m15-capi.sh --symbols            # what the acceptance files need vs what we export

--abi is the one that matters for the ABI: it compiles a C file against the reference quickjs.h and links it against our library, so the header's inline constructors expand in that translation unit and js_mallocz resolves from our .so. --exports is the one that matters for a binding: a Go or Python binding links against whatever its cgo/cffi preamble names, and the only honest proof that one can work is that our nm -D listing is a superset of the reference's. Both are part of scripts/check.sh, and both skip loudly when the reference build is absent.

--embed is the one that matters for an embedder: tests/c/embed.c builds the runtime itself instead of running a script through qjs, and the script compiles it twice — once against the reference's own object files, once against our .so — then compares stdout and stderr byte for byte. Read that file if you are writing a binding; it is the shortest complete host.

Embedding it

A Go/Python/Rust binding and this file are the same program shape. The whole thing, minus the error handling tests/c/embed.c demonstrates:

#include <stdio.h>
#include <string.h>
#include "quickjs.h"

int main(void) {
    /* 1. Engine. Nothing is installed yet; `JS_NewContext` is what brings the intrinsics. */
    JSRuntime *rt = JS_NewRuntime();
    JSContext *ctx = JS_NewContext(rt);

    /* 2. Limits. `(size_t)-1` means "no limit" — and **not** `0`, which refuses every
     *    allocation. Both limits may be set after the first evaluation. */
    JS_SetMemoryLimit(rt, 64u * 1024 * 1024);
    JS_SetMaxStackSize(rt, 1024 * 1024);

    /* 3. Evaluation. The completion value is a new reference: you own it. */
    const char *src = "JSON.stringify({sum: [1,2,3].reduce((a, b) => a + b)})";
    JSValue v = JS_Eval(ctx, src, strlen(src), "<host>", JS_EVAL_TYPE_GLOBAL);
    if (JS_IsException(v)) {
        JSValue e = JS_GetException(ctx);            /* takes the pending exception */
        const char *text = JS_ToCString(ctx, e);
        fprintf(stderr, "host: %s\n", text ? text : "?");
        JS_FreeCString(ctx, text);
        JS_FreeValue(ctx, e);
    } else {
        const char *text = JS_ToCString(ctx, v);
        printf("%s\n", text);                       /* {"sum":6} */
        JS_FreeCString(ctx, text);
    }
    JS_FreeValue(ctx, v);

    /* 4. Teardown, in this order: the context borrows the runtime. */
    JS_FreeContext(ctx);
    JS_FreeRuntime(rt);
    return 0;
}

Three rules that are not obvious from quickjs.h and that cost the most to discover:

  1. JS_SetPropertyStr and JS_DefineProperty* consume the value's reference. Passing a value and then JS_FreeValue-ing it yourself is a double free — it corrupts the heap and the crash lands somewhere else, often after the test suite has passed.
  2. A JSValue returned by any API function is a new reference. JS_GetPropertyStr, JS_Eval, JS_GetException — all of them. The header's static inline JS_FreeValue decrements the count in the caller's translation unit, so an engine that did not box exactly the way the header expects would corrupt memory on the first free.
  3. A C function called from script may re-enter the API. JS_ToInt32, JS_GetPropertyStr and friends all work inside a callback; they go through the interpreter the engine is already running. What does not work is calling JS_Eval from a callback and expecting a separate interpreter — it evaluates in the same global scope, on the same stack.

For an interrupt — "this script has run too long" — install the handler with JS_SetInterruptHandler(rt, cb, opaque) then return non-zero from cb. It is polled every 10000 instructions and at every loop back-edge; the script fails with InternalError: interrupted. Two differences from the reference, both visible: the error is catchable here (the reference makes it uncatchable), and a catch around the call therefore behaves differently. JS_SetUncatchableException is accepted and does nothing, which is honest rather than silent: a pending exception is already past every script catch.