quickjs-capi 0.13.0

C ABI compatibility layer: the QuickJS C API on top of the pure-Rust engine
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
//! C modules: `JS_NewCModule` and friends, and the `dlopen` that finds one.
//!
//! # What a C module is
//!
//! A `.so` built from `point.c` leaves every `JS_*` symbol undefined and exports exactly one
//! of its own:
//!
//! ```c
//! JSModuleDef *js_init_module(JSContext *ctx, const char *module_name)
//! {
//!     JSModuleDef *m = JS_NewCModule(ctx, module_name, js_point_init);
//!     if (!m) return NULL;
//!     JS_AddModuleExport(ctx, m, "Point");
//!     return m;
//! }
//! ```
//!
//! (`JS_INIT_MODULE` expands to that name when `JS_SHARED_LIBRARY` is defined.) The
//! *declarations* happen here; the init function — which calls `JS_SetModuleExport` with the
//! actual values — runs later, when the module is instantiated. Keeping that split matters:
//! `point.c`'s init sets an export the same call has just declared, and running init earlier
//! would fail on "no such export".
//!
//! # Why the loader lives here and not in `quickjs-host`
//!
//! The entry point takes a `JSContext *` and calls back into the C API, so the thing that
//! calls it has to be able to produce one. That is this crate. `quickjs-cli` supplies the
//! path and the `Interp`, and gets the exports back as ordinary engine values.
//!
//! # The `dlopen` handle is never closed
//!
//! A module's code, its static strings and its function pointers all live in the loaded
//! object. Unloading it while any of them is reachable — a `Point.prototype` method, a class
//! definition's finalizer — would be a jump into unmapped memory. The reference has the same
//! choice to make and makes the same one: `js_module_loader_so` closes the handle only on a
//! failure path.

use core::ffi::{CStr, c_char, c_int, c_void};

use engine::{Interp, Value};

use crate::cdefs::ModuleInitFunc;
use crate::cdefs::{self, JsModuleDef};
use crate::jsvalue::{self, JsValue};
use crate::runtime::{self, JsContext, JsRuntime};
use crate::value_helpers::jsvalue_of;

/// `JS_NewCModule`: create a module and remember how to fill it in.
///
/// The init function is *not* called here — it runs when the module is instantiated, which
/// is after every `JS_AddModuleExport` has declared the names. Answers a null pointer only
/// when `ctx` is null or `name_str` is null; allocation failure is not observable at this
/// level because the definition is a plain Rust allocation.
///
/// # Safety
///
/// `ctx` must be a live context and `name_str` a NUL-terminated string. `func` must be a
/// valid `JSModuleInitFunc`.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_NewCModule(
    ctx: *mut JsContext,
    name_str: *const c_char,
    func: ModuleInitFunc,
) -> *mut JsModuleDef {
    let Some(context) = (unsafe { ctx.as_ref() }) else {
        return std::ptr::null_mut();
    };
    if name_str.is_null() {
        return std::ptr::null_mut();
    }
    // SAFETY: the caller guarantees a NUL-terminated string.
    let name = unsafe { CStr::from_ptr(name_str) }
        .to_string_lossy()
        .into_owned();
    let definition = Box::new(JsModuleDef {
        name,
        declared: Vec::new(),
        values: Vec::new(),
        init: func,
        private: None,
    });
    let raw = Box::into_raw(definition);
    context.module_table().borrow_mut().push(raw);
    raw
}

/// `JS_AddModuleExport`: declare a name this module will export.
///
/// A declaration without a value leaves the export `undefined`, which is what the reference
/// does and what makes an init function that forgets a name visible rather than a hard
/// error.
///
/// # Safety
///
/// `m` must come from `JS_NewCModule`, and `export_name` must be NUL-terminated.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_AddModuleExport(
    _ctx: *mut JsContext,
    m: *mut JsModuleDef,
    export_name: *const c_char,
) -> c_int {
    let Some(definition) = (unsafe { m.as_mut() }) else {
        return -1;
    };
    if export_name.is_null() {
        return -1;
    }
    // SAFETY: the caller guarantees a NUL-terminated string.
    let name = unsafe { CStr::from_ptr(export_name) }
        .to_string_lossy()
        .into_owned();
    if !definition.declared.iter().any(|existing| existing == &name) {
        definition.declared.push(name);
    }
    0
}

/// `JS_AddModuleExportList`: declare every name in a function-list table.
///
/// # Safety
///
/// `tab` must point at `len` valid entries, and `m` must come from `JS_NewCModule`.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_AddModuleExportList(
    ctx: *mut JsContext,
    m: *mut JsModuleDef,
    tab: *const cdefs::JSCFunctionListEntry,
    len: c_int,
) -> c_int {
    if tab.is_null() || len < 0 {
        return -1;
    }
    for index in 0..len as usize {
        // SAFETY: the caller guarantees `len` entries.
        let entry = unsafe { &*tab.add(index) };
        // SAFETY: `m` came from `JS_NewCModule`, and the entry's name is NUL-terminated.
        if unsafe { JS_AddModuleExport(ctx, m, entry.name) } != 0 {
            return -1;
        }
    }
    0
}

/// `JS_SetModuleExport`: give a declared export its value, consuming `val`.
///
/// # Safety
///
/// `m` must come from `JS_NewCModule`, `export_name` must be NUL-terminated, and `val` must
/// be a live `JSValue` whose reference this call consumes.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_SetModuleExport(
    _ctx: *mut JsContext,
    m: *mut JsModuleDef,
    export_name: *const c_char,
    val: JsValue,
) -> c_int {
    let Some(definition) = (unsafe { m.as_mut() }) else {
        return -1;
    };
    if export_name.is_null() {
        return -1;
    }
    // SAFETY: the caller guarantees a NUL-terminated string.
    let name = unsafe { CStr::from_ptr(export_name) }
        .to_string_lossy()
        .into_owned();
    // The reference's `find_export_entry` fails for an undeclared name, and its caller then
    // frees the value. Mirroring the failure rather than quietly declaring it keeps a typo in
    // a module's own init visible.
    if !definition.declared.iter().any(|existing| existing == &name) {
        // SAFETY: the C API consumes `val` even on failure.
        unsafe { runtime::release(val) };
        return -1;
    }
    // SAFETY: `val` came from this crate or is a primitive.
    let value = unsafe { runtime::argument(val) }.unwrap_or(Value::Undefined);
    // SAFETY: the reference consumes the reference it was handed.
    unsafe { runtime::release(val) };
    if let Some(entry) = definition
        .values
        .iter_mut()
        .find(|(existing, _)| existing == &name)
    {
        entry.1 = value;
    } else {
        definition.values.push((name, value));
    }
    0
}

/// `JS_SetModuleExportList`: create each value from a function-list table and export it.
///
/// # Safety
///
/// `tab` must point at `len` valid entries, and `m` must come from `JS_NewCModule`.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_SetModuleExportList(
    ctx: *mut JsContext,
    m: *mut JsModuleDef,
    tab: *const cdefs::JSCFunctionListEntry,
    len: c_int,
) -> c_int {
    if tab.is_null() || len < 0 {
        return -1;
    }
    for index in 0..len as usize {
        // SAFETY: the caller guarantees `len` entries.
        let entry = unsafe { &*tab.add(index) };
        let value = match entry_value(ctx, entry) {
            Some(value) => value,
            None => return -1,
        };
        // SAFETY: `m` is a module definition and the entry's name is NUL-terminated.
        if unsafe { JS_SetModuleExport(ctx, m, entry.name, value) } != 0 {
            return -1;
        }
    }
    0
}

/// The `JSValue` a function-list entry defines, for the two kinds a module can export.
///
/// `JS_SetModuleExportList` in the reference handles `JS_DEF_CFUNC` and the `PROP_*` kinds
/// and nothing else — a getter/list pair has no meaning on a module namespace, which is a
/// fixed set of read-only bindings.
fn entry_value(ctx: *mut JsContext, entry: &cdefs::JSCFunctionListEntry) -> Option<JsValue> {
    match entry.def_type {
        cdefs::JS_DEF_CFUNC => {
            // SAFETY: `def_type` selects this arm of the union.
            let func = unsafe { &entry.u.func };
            // SAFETY: `ctx` is the caller's live context.
            Some(unsafe {
                crate::objects::JS_NewCFunction2(
                    ctx,
                    func.cfunc.as_ptr(),
                    entry.name,
                    c_int::from(func.length),
                    c_int::from(func.cproto),
                    c_int::from(entry.magic),
                )
            })
        }
        cdefs::JS_DEF_PROP_STRING => {
            // SAFETY: `def_type` selects this arm.
            let text = unsafe { entry.u.str_ };
            if text.is_null() {
                return Some(jsvalue::UNDEFINED);
            }
            // SAFETY: a `JS_PROP_STRING_DEF` names a NUL-terminated static string.
            let text = unsafe { CStr::from_ptr(text) }.to_string_lossy();
            // SAFETY: `ctx` is live, and a string needs an interpreter to intern it.
            let context = unsafe { ctx.as_ref() }?;
            Some(context.with_current_interp(|interp| jsvalue_of(interp.string(text.into_owned()))))
        }
        cdefs::JS_DEF_PROP_INT32 => {
            // SAFETY: `def_type` selects this arm.
            Some(jsvalue::new_int32(unsafe { entry.u.i32 }))
        }
        cdefs::JS_DEF_PROP_DOUBLE => {
            // SAFETY: `def_type` selects this arm.
            Some(jsvalue::new_float64(unsafe { entry.u.f64 }))
        }
        cdefs::JS_DEF_PROP_INT64 => {
            // SAFETY: `def_type` selects this arm.
            let number = unsafe { entry.u.i64 };
            Some(jsvalue::new_float64(number as f64))
        }
        cdefs::JS_DEF_PROP_UNDEFINED => Some(jsvalue::UNDEFINED),
        cdefs::JS_DEF_PROP_BOOL => {
            // SAFETY: `def_type` selects this arm; a bool stores an `i32`.
            Some(jsvalue::new_bool(unsafe { entry.u.i32 } != 0))
        }
        _ => None,
    }
}

/// Run a module's init function and collect what it exported.
///
/// # Safety
///
/// `definition` must be a live definition from `JS_NewCModule` whose context is still alive.
pub unsafe fn instantiate(
    context: &JsContext,
    definition: &mut JsModuleDef,
) -> Result<Vec<(String, Value)>, String> {
    if let Some(init) = definition.init {
        // SAFETY: the module registered this function as a `JSModuleInitFunc`, and the
        // context pointer is the one the module's own `js_init_module` received.
        let status = unsafe {
            init(
                context as *const JsContext as *mut JsContext,
                definition as *mut JsModuleDef,
            )
        };
        if status < 0 {
            return Err(format!(
                "could not load module filename '{}': initialization error",
                definition.name
            ));
        }
    }
    // Declared order, with `undefined` for a name the init function never set: that is what
    // the reference's namespace does for an unset export.
    let mut exports = Vec::with_capacity(definition.declared.len());
    for name in &definition.declared {
        let value = definition
            .values
            .iter()
            .find(|(existing, _)| existing == name)
            .map(|(_, value)| value.clone())
            .unwrap_or(Value::Undefined);
        exports.push((name.clone(), value));
    }
    // Anything set without a declaration cannot exist — `JS_SetModuleExport` refuses it —
    // so the two lists agree here by construction rather than by a second pass.
    Ok(exports)
}

// ---------------------------------------------------------------------------
// Loading a `.so`
// ---------------------------------------------------------------------------

/// The module entry point's signature: `JSModuleDef *(*)(JSContext *, const char *)`.
type InitModuleFunc = unsafe extern "C" fn(*mut JsContext, *const c_char) -> *mut JsModuleDef;

/// Load a native module and hand back its exports.
///
/// `interp` is the interpreter that is importing it; the module's `JSContext *` is an
/// attached handle over exactly that interpreter, so a class it registers and an object it
/// creates are the importing script's.
///
/// # Errors
///
/// The reference's three messages, verbatim: the library could not be opened, it has no
/// `js_init_module`, or its init function failed. A script sees them as `ReferenceError`s,
/// because `load_native`'s error becomes one.
pub fn load_native_module(
    interp: &mut Interp<'_>,
    runtime: *mut JsRuntime,
    module_name: &str,
) -> Result<Vec<(String, Value)>, String> {
    // The reference prefixes `./` when the name has no directory: `dlopen("point.so")`
    // searches the system library path, which would load a *different* library of that name
    // — or, worse, find one installed by something else.
    let path = if module_name.contains('/') {
        module_name.to_string()
    } else {
        format!("./{module_name}")
    };
    let handle = dlopen(&path).ok_or_else(|| {
        format!("could not load module filename '{module_name}' as shared library")
    })?;
    let Some(init) = dlsym(handle, "js_init_module") else {
        // The handle is deliberately not closed: a module that failed to load may still
        // have run static initialisers, and closing it would run their destructors inside
        // whatever state the failure left.
        return Err(format!(
            "could not load module filename '{module_name}': js_init_module not found"
        ));
    };

    // A stack context that stands for the running interpreter, published for as long as the
    // module's `js_init_module` runs.
    let context = JsContext::attached(runtime);
    let raw_interp: *mut Interp<'static> = unsafe {
        // SAFETY: the pointer is used only inside this function, and the guard restores the
        // previous value before `interp` is used again by the caller.
        std::mem::transmute::<&mut Interp<'_>, &mut Interp<'static>>(interp)
    };
    let guard = runtime::publish(raw_interp, &context);
    // Nothing may run after the guard is dropped: the init function is not the end of the
    // module's work. `JS_SetModuleExportList` builds each value by calling `JS_NewCFunction2`,
    // which needs the published interpreter exactly as `JS_NewClass` does — the first version
    // dropped the guard right after the entry point returned and every module whose init used
    // a function-list table aborted the process.
    let name = std::ffi::CString::new(module_name).unwrap_or_default();
    // SAFETY: `init` is the module's own entry point, whose signature this is; the context
    // pointer is the attached handle published just above.
    let definition = unsafe {
        init(
            &context as *const JsContext as *mut JsContext,
            name.as_ptr(),
        )
    };
    let exports = if definition.is_null() {
        Err(format!(
            "could not load module filename '{module_name}': initialization error"
        ))
    } else {
        // The definition is one of this context's own: `JS_NewCModule` created it during the
        // call above, so the table is where the real owner is.
        context
            .module_table()
            .borrow()
            .iter()
            .copied()
            .find(|&candidate| candidate == definition)
            .ok_or_else(|| {
                format!("could not load module filename '{module_name}': unknown module definition")
            })
            .and_then(|owned| {
                // SAFETY: `owned` was just matched against the table, so it is a live
                // definition created in this call.
                let definition = unsafe { &mut *owned };
                unsafe { instantiate(&context, definition) }
            })
    };
    drop(guard);
    exports
}

/// The `JSModuleDef` a native module's entry point answered, for a caller that has it.
///
/// Exposed because a host that loads modules itself — rather than through
/// [`load_native_module`] — needs to finish the same way.
///
/// # Safety
///
/// `definition` must be a live definition from `JS_NewCModule`.
pub unsafe fn exports_of(
    context: &JsContext,
    definition: *mut JsModuleDef,
) -> Result<Vec<(String, Value)>, String> {
    // SAFETY: the caller guarantees a live definition.
    let definition = unsafe { &mut *definition };
    unsafe { instantiate(context, definition) }
}

// ---------------------------------------------------------------------------
// dlopen, on unix
// ---------------------------------------------------------------------------

/// A loaded library, kept open for the life of the process.
struct Library(*mut c_void);

/// `dlopen(path, RTLD_NOW | RTLD_LOCAL)`.
#[cfg(unix)]
fn dlopen(path: &str) -> Option<Library> {
    let path = std::ffi::CString::new(path).ok()?;
    // SAFETY: `path` is a NUL-terminated string, and the flags are the reference's:
    // `RTLD_NOW` resolves every symbol immediately — a missing one is a load error rather
    // than a crash at the first call — and `RTLD_LOCAL` keeps this module's symbols out of
    // the global namespace, which is what lets two modules of the same name coexist.
    let handle = unsafe { libc::dlopen(path.as_ptr(), libc::RTLD_NOW | libc::RTLD_LOCAL) };
    if handle.is_null() {
        None
    } else {
        // Leaked on purpose: see the module docs. `Library` is only ever constructed to be
        // forgotten, and spelling that out keeps the "never closed" rule in one place.
        Some(Library(handle))
    }
}

/// `dlsym(handle, symbol)`, as the module entry point's type.
#[cfg(unix)]
fn dlsym(handle: Library, symbol: &str) -> Option<InitModuleFunc> {
    let symbol = std::ffi::CString::new(symbol).ok()?;
    // SAFETY: the handle came from `dlopen` and is never closed, so the symbol stays valid.
    let pointer = unsafe { libc::dlsym(handle.0, symbol.as_ptr()) };
    if pointer.is_null() {
        return None;
    }
    // SAFETY: the caller asked for `js_init_module`, whose signature `JS_SHARED_LIBRARY`
    // gives exactly this type.
    Some(unsafe { std::mem::transmute::<*mut c_void, InitModuleFunc>(pointer) })
}

/// A platform without `dlopen`: every native module is reported as unloadable.
///
/// The reference has the same shape (`js_module_loader_so` under `#ifdef _WIN32` throws
/// "shared library modules are not supported yet"), and the message is the same one.
#[cfg(not(unix))]
fn dlopen(_path: &str) -> Option<Library> {
    None
}

/// As [`dlsym`], for a platform with no dynamic loader.
#[cfg(not(unix))]
fn dlsym(_handle: Library, _symbol: &str) -> Option<InitModuleFunc> {
    None
}