Skip to main content

quickjs/
lib.rs

1//! `quickjs-capi` — the QuickJS C API on top of the pure-Rust engine.
2//!
3//! The library this crate produces is `libquickjs.so`, and it is meant to be a drop-in
4//! replacement for the reference implementation's at link time: same exported symbols,
5//! same `JSValue` bit layout, same struct offsets. `docs/m15-plan.md` is the reasoning;
6//! this is the code.
7//!
8//! # How the two representations meet
9//!
10//! The engine's `Value` is a 16-byte enum. C's `JSValue` is 8 bytes of NaN boxing. The
11//! mapping has to be *bit*-compatible rather than a conversion at the boundary, because
12//! `quickjs.h` ships 119 of its "functions" as `static inline` and they run in the
13//! caller's translation unit — `JS_DupValue` increments a count through a raw pointer that
14//! only exists because we put it there.
15//!
16//! * [`jsvalue`] is the bit half: tags, encode, decode. No `unsafe`.
17//! * [`alloc`] is the memory half: the header that puts `ref_count` four bytes before the
18//!   payload, and the boxes that hold engine values.
19//!
20//! # `unsafe` is the whole point of this crate
21//!
22//! Everything a C caller can do to a `JSValue` — duplicate it, free it, read a field of a
23//! struct we handed over — happens outside Rust's type system. `scripts/check-unsafe.sh`
24//! lists this crate as a deliberate exception for that reason, and each `unsafe` block
25//! below carries the argument for why it is sound.
26//!
27//! # Status
28//!
29//! M15's S2: the value/allocator layer plus the `js_malloc` family of exports. The
30//! remaining symbols are S3–S7 in `docs/m15-plan.md` §5. This crate is `publish = false`
31//! until that surface is complete — a `libquickjs` missing half its symbols is worse than
32//! no `libquickjs`.
33
34#![deny(unsafe_op_in_unsafe_fn)]
35#![warn(missing_docs)]
36
37use core::ffi::c_void;
38
39pub mod alloc;
40pub mod atoms;
41pub mod bjson;
42pub mod buffers;
43pub mod builtins_typed;
44pub mod calls;
45pub mod cdefs;
46pub mod conversions;
47pub mod convert;
48pub mod host;
49pub mod intrinsics;
50pub mod jsvalue;
51pub mod module_api;
52pub mod modules;
53pub mod objects;
54pub mod properties;
55pub mod runtime;
56pub mod state;
57pub mod value_helpers;
58
59pub use jsvalue::JsValue;
60
61pub use runtime::{JsContext, JsRuntime};
62
63// `release` and `argument` are the two halves of the ownership rule the whole API follows
64// (a returned value is a new reference; an argument is borrowed), so they are reachable
65// from a Rust-side caller as well as from this crate's own exports.
66pub use runtime::{argument, release};
67
68// ---------------------------------------------------------------------------
69// js_malloc and friends
70//
71// Signatures and nullptr behaviour are the reference's: a size that cannot be represented
72// gives a null pointer rather than an abort, so a script asking for 2^60 bytes gets a
73// RangeError instead of a dead process.
74// ---------------------------------------------------------------------------
75
76/// `js_malloc`: `size` bytes owned by the runtime, zeroed by nobody.
77///
78/// # Safety
79///
80/// The answer must be released with `js_free`/`js_free_rt` (or `js_realloc`), and `size`
81/// bytes from it may be written in the meantime.
82#[unsafe(no_mangle)]
83pub unsafe extern "C" fn js_malloc(_ctx: *mut JsContext, size: usize) -> *mut c_void {
84    // SAFETY: the caller's contract is exactly `alloc_raw`'s.
85    unsafe { alloc::alloc_raw(size) }.cast()
86}
87
88/// `js_mallocz`: [`js_malloc`], zeroed.
89///
90/// # Safety
91///
92/// Same as [`js_malloc`].
93#[unsafe(no_mangle)]
94pub unsafe extern "C" fn js_mallocz(_ctx: *mut JsContext, size: usize) -> *mut c_void {
95    // SAFETY: the caller's contract is exactly `alloc_raw_zeroed`'s.
96    unsafe { alloc::alloc_raw_zeroed(size) }.cast()
97}
98
99/// `js_malloc_rt`: the runtime-level spelling of [`js_malloc`].
100///
101/// # Safety
102///
103/// Same as [`js_malloc`].
104#[unsafe(no_mangle)]
105pub unsafe extern "C" fn js_malloc_rt(_rt: *mut JsRuntime, size: usize) -> *mut c_void {
106    // SAFETY: the caller's contract is exactly `alloc_raw`'s.
107    unsafe { alloc::alloc_raw(size) }.cast()
108}
109
110/// `js_mallocz_rt`: the runtime-level spelling of [`js_mallocz`].
111///
112/// # Safety
113///
114/// Same as [`js_malloc`].
115#[unsafe(no_mangle)]
116pub unsafe extern "C" fn js_mallocz_rt(_rt: *mut JsRuntime, size: usize) -> *mut c_void {
117    // SAFETY: the caller's contract is exactly `alloc_raw_zeroed`'s.
118    unsafe { alloc::alloc_raw_zeroed(size) }.cast()
119}
120
121/// `js_free`: release a block from [`js_malloc`], or do nothing for a null pointer.
122///
123/// # Safety
124///
125/// `ptr` must be null or a live pointer from the `js_malloc` family, and must not be used
126/// afterwards.
127#[unsafe(no_mangle)]
128pub unsafe extern "C" fn js_free(_ctx: *mut JsContext, ptr: *mut c_void) {
129    // SAFETY: the caller's contract is exactly `free_raw`'s.
130    unsafe { alloc::free_raw(ptr.cast()) }
131}
132
133/// `js_free_rt`: the runtime-level spelling of [`js_free`].
134///
135/// # Safety
136///
137/// Same as [`js_free`].
138#[unsafe(no_mangle)]
139pub unsafe extern "C" fn js_free_rt(_rt: *mut JsRuntime, ptr: *mut c_void) {
140    // SAFETY: the caller's contract is exactly `free_raw`'s.
141    unsafe { alloc::free_raw(ptr.cast()) }
142}
143
144/// `js_realloc`: resize a block from [`js_malloc`], keeping its contents.
145///
146/// # Safety
147///
148/// `ptr` must be null or a live pointer from the `js_malloc` family with `size` bytes, and
149/// must not be used again afterwards.
150#[unsafe(no_mangle)]
151pub unsafe extern "C" fn js_realloc(
152    _ctx: *mut JsContext,
153    ptr: *mut c_void,
154    size: usize,
155) -> *mut c_void {
156    // `js_realloc` has no way to be told the old size — the reference asks its allocator,
157    // which records it. Ours records the payload size in the block header, so this is the
158    // one place the two contracts differ, and reading the header is what closes the gap.
159    let old_size = unsafe { alloc::payload_size(ptr.cast()) };
160    // SAFETY: `ptr` is a live block of `old_size`, as `realloc_raw` requires.
161    unsafe { alloc::realloc_raw(ptr.cast(), old_size, size) }.cast()
162}
163
164/// `js_realloc_rt`: the runtime-level spelling of [`js_realloc`].
165///
166/// # Safety
167///
168/// Same as [`js_realloc`].
169#[unsafe(no_mangle)]
170pub unsafe extern "C" fn js_realloc_rt(
171    _rt: *mut JsRuntime,
172    ptr: *mut c_void,
173    size: usize,
174) -> *mut c_void {
175    let old_size = unsafe { alloc::payload_size(ptr.cast()) };
176    // SAFETY: `ptr` is a live block of `old_size`, as `realloc_raw` requires.
177    unsafe { alloc::realloc_raw(ptr.cast(), old_size, size) }.cast()
178}
179
180/// `js_realloc2`: [`js_realloc`] that also reports the slack.
181///
182/// The reference answers `NULL` without reallocating when growing would not be worth it;
183/// ours always reallocates and reports the difference. `*pslack` is only written when the
184/// pointer is non-null, which is what the callers in `quickjs-libc.c` rely on.
185///
186/// # Safety
187///
188/// Same as [`js_realloc`]; `pslack` must be null or writable.
189#[unsafe(no_mangle)]
190pub unsafe extern "C" fn js_realloc2(
191    _ctx: *mut JsContext,
192    ptr: *mut c_void,
193    size: usize,
194    pslack: *mut usize,
195) -> *mut c_void {
196    let old_size = unsafe { alloc::payload_size(ptr.cast()) };
197    // SAFETY: `ptr` is a live block of `old_size`.
198    let answer = unsafe { alloc::realloc_raw(ptr.cast(), old_size, size) };
199    if !answer.is_null() && !pslack.is_null() {
200        // SAFETY: the caller promised `pslack` is writable.
201        unsafe { *pslack = size };
202    }
203    answer.cast()
204}
205
206/// `js_malloc_usable_size`: how big a block actually is.
207///
208/// Ours records the requested size rather than the allocation's, so this answers what was
209/// asked for. The reference answers the same number for its small blocks and a rounded one
210/// for large ones; nothing in the C API depends on the difference — `quickjs-libc.c` uses
211/// it only to size a read.
212///
213/// # Safety
214///
215/// `ptr` must be null or a live pointer from the `js_malloc` family.
216#[unsafe(no_mangle)]
217pub unsafe extern "C" fn js_malloc_usable_size(_ctx: *mut JsContext, ptr: *const c_void) -> usize {
218    // SAFETY: the caller's contract is `payload_size`'s.
219    unsafe { alloc::payload_size(ptr.cast_mut().cast()) }
220}
221
222/// `js_malloc_usable_size_rt`: the runtime-level spelling of
223/// [`js_malloc_usable_size`].
224///
225/// # Safety
226///
227/// Same as [`js_malloc_usable_size`].
228#[unsafe(no_mangle)]
229pub unsafe extern "C" fn js_malloc_usable_size_rt(
230    _rt: *mut JsRuntime,
231    ptr: *const c_void,
232) -> usize {
233    // SAFETY: the caller's contract is `payload_size`'s.
234    unsafe { alloc::payload_size(ptr.cast_mut().cast()) }
235}
236
237// ---------------------------------------------------------------------------
238// Reference counting
239// ---------------------------------------------------------------------------
240
241/// `__JS_FreeValue`: drop a value whose count just reached zero.
242///
243/// Never called directly by C: the inline `JS_FreeValue` decrements first and calls this
244/// only on the transition to zero. A value that carries no reference count is a no-op,
245/// which the inline already filtered out — the check is here too so that a caller which
246/// gets it wrong leaks nothing and crashes nothing.
247///
248/// # Safety
249///
250/// `value` must be a payload from this crate whose count has reached zero, and must not be
251/// used again.
252#[unsafe(no_mangle)]
253pub unsafe extern "C" fn __JS_FreeValue(_ctx: *mut JsContext, value: JsValue) {
254    let Some(payload) = value.as_ptr() else {
255        return;
256    };
257    // SAFETY: the caller guarantees the count reached zero, so this box has no other owner.
258    unsafe { alloc::free_value(payload) }
259}
260
261/// `__JS_FreeValueRT`: the runtime-level spelling of [`__JS_FreeValue`].
262///
263/// # Safety
264///
265/// Same as [`__JS_FreeValue`].
266#[unsafe(no_mangle)]
267pub unsafe extern "C" fn __JS_FreeValueRT(_rt: *mut JsRuntime, value: JsValue) {
268    let Some(payload) = value.as_ptr() else {
269        return;
270    };
271    // SAFETY: the caller guarantees the count reached zero.
272    unsafe { alloc::free_value(payload) }
273}