Skip to main content

quickjs/
modules.rs

1//! C modules: `JS_NewCModule` and friends, and the `dlopen` that finds one.
2//!
3//! # What a C module is
4//!
5//! A `.so` built from `point.c` leaves every `JS_*` symbol undefined and exports exactly one
6//! of its own:
7//!
8//! ```c
9//! JSModuleDef *js_init_module(JSContext *ctx, const char *module_name)
10//! {
11//!     JSModuleDef *m = JS_NewCModule(ctx, module_name, js_point_init);
12//!     if (!m) return NULL;
13//!     JS_AddModuleExport(ctx, m, "Point");
14//!     return m;
15//! }
16//! ```
17//!
18//! (`JS_INIT_MODULE` expands to that name when `JS_SHARED_LIBRARY` is defined.) The
19//! *declarations* happen here; the init function — which calls `JS_SetModuleExport` with the
20//! actual values — runs later, when the module is instantiated. Keeping that split matters:
21//! `point.c`'s init sets an export the same call has just declared, and running init earlier
22//! would fail on "no such export".
23//!
24//! # Why the loader lives here and not in `quickjs-host`
25//!
26//! The entry point takes a `JSContext *` and calls back into the C API, so the thing that
27//! calls it has to be able to produce one. That is this crate. `quickjs-cli` supplies the
28//! path and the `Interp`, and gets the exports back as ordinary engine values.
29//!
30//! # The `dlopen` handle is never closed
31//!
32//! A module's code, its static strings and its function pointers all live in the loaded
33//! object. Unloading it while any of them is reachable — a `Point.prototype` method, a class
34//! definition's finalizer — would be a jump into unmapped memory. The reference has the same
35//! choice to make and makes the same one: `js_module_loader_so` closes the handle only on a
36//! failure path.
37
38use core::ffi::{CStr, c_char, c_int, c_void};
39
40use engine::{Interp, Value};
41
42use crate::cdefs::ModuleInitFunc;
43use crate::cdefs::{self, JsModuleDef};
44use crate::jsvalue::{self, JsValue};
45use crate::runtime::{self, JsContext, JsRuntime};
46use crate::value_helpers::jsvalue_of;
47
48/// `JS_NewCModule`: create a module and remember how to fill it in.
49///
50/// The init function is *not* called here — it runs when the module is instantiated, which
51/// is after every `JS_AddModuleExport` has declared the names. Answers a null pointer only
52/// when `ctx` is null or `name_str` is null; allocation failure is not observable at this
53/// level because the definition is a plain Rust allocation.
54///
55/// # Safety
56///
57/// `ctx` must be a live context and `name_str` a NUL-terminated string. `func` must be a
58/// valid `JSModuleInitFunc`.
59#[unsafe(no_mangle)]
60pub unsafe extern "C" fn JS_NewCModule(
61    ctx: *mut JsContext,
62    name_str: *const c_char,
63    func: ModuleInitFunc,
64) -> *mut JsModuleDef {
65    let Some(context) = (unsafe { ctx.as_ref() }) else {
66        return std::ptr::null_mut();
67    };
68    if name_str.is_null() {
69        return std::ptr::null_mut();
70    }
71    // SAFETY: the caller guarantees a NUL-terminated string.
72    let name = unsafe { CStr::from_ptr(name_str) }
73        .to_string_lossy()
74        .into_owned();
75    let definition = Box::new(JsModuleDef {
76        name,
77        declared: Vec::new(),
78        values: Vec::new(),
79        init: func,
80        private: None,
81    });
82    let raw = Box::into_raw(definition);
83    context.module_table().borrow_mut().push(raw);
84    raw
85}
86
87/// `JS_AddModuleExport`: declare a name this module will export.
88///
89/// A declaration without a value leaves the export `undefined`, which is what the reference
90/// does and what makes an init function that forgets a name visible rather than a hard
91/// error.
92///
93/// # Safety
94///
95/// `m` must come from `JS_NewCModule`, and `export_name` must be NUL-terminated.
96#[unsafe(no_mangle)]
97pub unsafe extern "C" fn JS_AddModuleExport(
98    _ctx: *mut JsContext,
99    m: *mut JsModuleDef,
100    export_name: *const c_char,
101) -> c_int {
102    let Some(definition) = (unsafe { m.as_mut() }) else {
103        return -1;
104    };
105    if export_name.is_null() {
106        return -1;
107    }
108    // SAFETY: the caller guarantees a NUL-terminated string.
109    let name = unsafe { CStr::from_ptr(export_name) }
110        .to_string_lossy()
111        .into_owned();
112    if !definition.declared.iter().any(|existing| existing == &name) {
113        definition.declared.push(name);
114    }
115    0
116}
117
118/// `JS_AddModuleExportList`: declare every name in a function-list table.
119///
120/// # Safety
121///
122/// `tab` must point at `len` valid entries, and `m` must come from `JS_NewCModule`.
123#[unsafe(no_mangle)]
124pub unsafe extern "C" fn JS_AddModuleExportList(
125    ctx: *mut JsContext,
126    m: *mut JsModuleDef,
127    tab: *const cdefs::JSCFunctionListEntry,
128    len: c_int,
129) -> c_int {
130    if tab.is_null() || len < 0 {
131        return -1;
132    }
133    for index in 0..len as usize {
134        // SAFETY: the caller guarantees `len` entries.
135        let entry = unsafe { &*tab.add(index) };
136        // SAFETY: `m` came from `JS_NewCModule`, and the entry's name is NUL-terminated.
137        if unsafe { JS_AddModuleExport(ctx, m, entry.name) } != 0 {
138            return -1;
139        }
140    }
141    0
142}
143
144/// `JS_SetModuleExport`: give a declared export its value, consuming `val`.
145///
146/// # Safety
147///
148/// `m` must come from `JS_NewCModule`, `export_name` must be NUL-terminated, and `val` must
149/// be a live `JSValue` whose reference this call consumes.
150#[unsafe(no_mangle)]
151pub unsafe extern "C" fn JS_SetModuleExport(
152    _ctx: *mut JsContext,
153    m: *mut JsModuleDef,
154    export_name: *const c_char,
155    val: JsValue,
156) -> c_int {
157    let Some(definition) = (unsafe { m.as_mut() }) else {
158        return -1;
159    };
160    if export_name.is_null() {
161        return -1;
162    }
163    // SAFETY: the caller guarantees a NUL-terminated string.
164    let name = unsafe { CStr::from_ptr(export_name) }
165        .to_string_lossy()
166        .into_owned();
167    // The reference's `find_export_entry` fails for an undeclared name, and its caller then
168    // frees the value. Mirroring the failure rather than quietly declaring it keeps a typo in
169    // a module's own init visible.
170    if !definition.declared.iter().any(|existing| existing == &name) {
171        // SAFETY: the C API consumes `val` even on failure.
172        unsafe { runtime::release(val) };
173        return -1;
174    }
175    // SAFETY: `val` came from this crate or is a primitive.
176    let value = unsafe { runtime::argument(val) }.unwrap_or(Value::Undefined);
177    // SAFETY: the reference consumes the reference it was handed.
178    unsafe { runtime::release(val) };
179    if let Some(entry) = definition
180        .values
181        .iter_mut()
182        .find(|(existing, _)| existing == &name)
183    {
184        entry.1 = value;
185    } else {
186        definition.values.push((name, value));
187    }
188    0
189}
190
191/// `JS_SetModuleExportList`: create each value from a function-list table and export it.
192///
193/// # Safety
194///
195/// `tab` must point at `len` valid entries, and `m` must come from `JS_NewCModule`.
196#[unsafe(no_mangle)]
197pub unsafe extern "C" fn JS_SetModuleExportList(
198    ctx: *mut JsContext,
199    m: *mut JsModuleDef,
200    tab: *const cdefs::JSCFunctionListEntry,
201    len: c_int,
202) -> c_int {
203    if tab.is_null() || len < 0 {
204        return -1;
205    }
206    for index in 0..len as usize {
207        // SAFETY: the caller guarantees `len` entries.
208        let entry = unsafe { &*tab.add(index) };
209        let value = match entry_value(ctx, entry) {
210            Some(value) => value,
211            None => return -1,
212        };
213        // SAFETY: `m` is a module definition and the entry's name is NUL-terminated.
214        if unsafe { JS_SetModuleExport(ctx, m, entry.name, value) } != 0 {
215            return -1;
216        }
217    }
218    0
219}
220
221/// The `JSValue` a function-list entry defines, for the two kinds a module can export.
222///
223/// `JS_SetModuleExportList` in the reference handles `JS_DEF_CFUNC` and the `PROP_*` kinds
224/// and nothing else — a getter/list pair has no meaning on a module namespace, which is a
225/// fixed set of read-only bindings.
226fn entry_value(ctx: *mut JsContext, entry: &cdefs::JSCFunctionListEntry) -> Option<JsValue> {
227    match entry.def_type {
228        cdefs::JS_DEF_CFUNC => {
229            // SAFETY: `def_type` selects this arm of the union.
230            let func = unsafe { &entry.u.func };
231            // SAFETY: `ctx` is the caller's live context.
232            Some(unsafe {
233                crate::objects::JS_NewCFunction2(
234                    ctx,
235                    func.cfunc.as_ptr(),
236                    entry.name,
237                    c_int::from(func.length),
238                    c_int::from(func.cproto),
239                    c_int::from(entry.magic),
240                )
241            })
242        }
243        cdefs::JS_DEF_PROP_STRING => {
244            // SAFETY: `def_type` selects this arm.
245            let text = unsafe { entry.u.str_ };
246            if text.is_null() {
247                return Some(jsvalue::UNDEFINED);
248            }
249            // SAFETY: a `JS_PROP_STRING_DEF` names a NUL-terminated static string.
250            let text = unsafe { CStr::from_ptr(text) }.to_string_lossy();
251            // SAFETY: `ctx` is live, and a string needs an interpreter to intern it.
252            let context = unsafe { ctx.as_ref() }?;
253            Some(context.with_current_interp(|interp| jsvalue_of(interp.string(text.into_owned()))))
254        }
255        cdefs::JS_DEF_PROP_INT32 => {
256            // SAFETY: `def_type` selects this arm.
257            Some(jsvalue::new_int32(unsafe { entry.u.i32 }))
258        }
259        cdefs::JS_DEF_PROP_DOUBLE => {
260            // SAFETY: `def_type` selects this arm.
261            Some(jsvalue::new_float64(unsafe { entry.u.f64 }))
262        }
263        cdefs::JS_DEF_PROP_INT64 => {
264            // SAFETY: `def_type` selects this arm.
265            let number = unsafe { entry.u.i64 };
266            Some(jsvalue::new_float64(number as f64))
267        }
268        cdefs::JS_DEF_PROP_UNDEFINED => Some(jsvalue::UNDEFINED),
269        cdefs::JS_DEF_PROP_BOOL => {
270            // SAFETY: `def_type` selects this arm; a bool stores an `i32`.
271            Some(jsvalue::new_bool(unsafe { entry.u.i32 } != 0))
272        }
273        _ => None,
274    }
275}
276
277/// Run a module's init function and collect what it exported.
278///
279/// # Safety
280///
281/// `definition` must be a live definition from `JS_NewCModule` whose context is still alive.
282pub unsafe fn instantiate(
283    context: &JsContext,
284    definition: &mut JsModuleDef,
285) -> Result<Vec<(String, Value)>, String> {
286    if let Some(init) = definition.init {
287        // SAFETY: the module registered this function as a `JSModuleInitFunc`, and the
288        // context pointer is the one the module's own `js_init_module` received.
289        let status = unsafe {
290            init(
291                context as *const JsContext as *mut JsContext,
292                definition as *mut JsModuleDef,
293            )
294        };
295        if status < 0 {
296            return Err(format!(
297                "could not load module filename '{}': initialization error",
298                definition.name
299            ));
300        }
301    }
302    // Declared order, with `undefined` for a name the init function never set: that is what
303    // the reference's namespace does for an unset export.
304    let mut exports = Vec::with_capacity(definition.declared.len());
305    for name in &definition.declared {
306        let value = definition
307            .values
308            .iter()
309            .find(|(existing, _)| existing == name)
310            .map(|(_, value)| value.clone())
311            .unwrap_or(Value::Undefined);
312        exports.push((name.clone(), value));
313    }
314    // Anything set without a declaration cannot exist — `JS_SetModuleExport` refuses it —
315    // so the two lists agree here by construction rather than by a second pass.
316    Ok(exports)
317}
318
319// ---------------------------------------------------------------------------
320// Loading a `.so`
321// ---------------------------------------------------------------------------
322
323/// The module entry point's signature: `JSModuleDef *(*)(JSContext *, const char *)`.
324type InitModuleFunc = unsafe extern "C" fn(*mut JsContext, *const c_char) -> *mut JsModuleDef;
325
326/// Load a native module and hand back its exports.
327///
328/// `interp` is the interpreter that is importing it; the module's `JSContext *` is an
329/// attached handle over exactly that interpreter, so a class it registers and an object it
330/// creates are the importing script's.
331///
332/// # Errors
333///
334/// The reference's three messages, verbatim: the library could not be opened, it has no
335/// `js_init_module`, or its init function failed. A script sees them as `ReferenceError`s,
336/// because `load_native`'s error becomes one.
337pub fn load_native_module(
338    interp: &mut Interp<'_>,
339    runtime: *mut JsRuntime,
340    module_name: &str,
341) -> Result<Vec<(String, Value)>, String> {
342    // The reference prefixes `./` when the name has no directory: `dlopen("point.so")`
343    // searches the system library path, which would load a *different* library of that name
344    // — or, worse, find one installed by something else.
345    let path = if module_name.contains('/') {
346        module_name.to_string()
347    } else {
348        format!("./{module_name}")
349    };
350    let handle = dlopen(&path).ok_or_else(|| {
351        format!("could not load module filename '{module_name}' as shared library")
352    })?;
353    let Some(init) = dlsym(handle, "js_init_module") else {
354        // The handle is deliberately not closed: a module that failed to load may still
355        // have run static initialisers, and closing it would run their destructors inside
356        // whatever state the failure left.
357        return Err(format!(
358            "could not load module filename '{module_name}': js_init_module not found"
359        ));
360    };
361
362    // A stack context that stands for the running interpreter, published for as long as the
363    // module's `js_init_module` runs.
364    let context = JsContext::attached(runtime);
365    let raw_interp: *mut Interp<'static> = unsafe {
366        // SAFETY: the pointer is used only inside this function, and the guard restores the
367        // previous value before `interp` is used again by the caller.
368        std::mem::transmute::<&mut Interp<'_>, &mut Interp<'static>>(interp)
369    };
370    let guard = runtime::publish(raw_interp, &context);
371    // Nothing may run after the guard is dropped: the init function is not the end of the
372    // module's work. `JS_SetModuleExportList` builds each value by calling `JS_NewCFunction2`,
373    // which needs the published interpreter exactly as `JS_NewClass` does — the first version
374    // dropped the guard right after the entry point returned and every module whose init used
375    // a function-list table aborted the process.
376    let name = std::ffi::CString::new(module_name).unwrap_or_default();
377    // SAFETY: `init` is the module's own entry point, whose signature this is; the context
378    // pointer is the attached handle published just above.
379    let definition = unsafe {
380        init(
381            &context as *const JsContext as *mut JsContext,
382            name.as_ptr(),
383        )
384    };
385    let exports = if definition.is_null() {
386        Err(format!(
387            "could not load module filename '{module_name}': initialization error"
388        ))
389    } else {
390        // The definition is one of this context's own: `JS_NewCModule` created it during the
391        // call above, so the table is where the real owner is.
392        context
393            .module_table()
394            .borrow()
395            .iter()
396            .copied()
397            .find(|&candidate| candidate == definition)
398            .ok_or_else(|| {
399                format!("could not load module filename '{module_name}': unknown module definition")
400            })
401            .and_then(|owned| {
402                // SAFETY: `owned` was just matched against the table, so it is a live
403                // definition created in this call.
404                let definition = unsafe { &mut *owned };
405                unsafe { instantiate(&context, definition) }
406            })
407    };
408    drop(guard);
409    exports
410}
411
412/// The `JSModuleDef` a native module's entry point answered, for a caller that has it.
413///
414/// Exposed because a host that loads modules itself — rather than through
415/// [`load_native_module`] — needs to finish the same way.
416///
417/// # Safety
418///
419/// `definition` must be a live definition from `JS_NewCModule`.
420pub unsafe fn exports_of(
421    context: &JsContext,
422    definition: *mut JsModuleDef,
423) -> Result<Vec<(String, Value)>, String> {
424    // SAFETY: the caller guarantees a live definition.
425    let definition = unsafe { &mut *definition };
426    unsafe { instantiate(context, definition) }
427}
428
429// ---------------------------------------------------------------------------
430// dlopen, on unix
431// ---------------------------------------------------------------------------
432
433/// A loaded library, kept open for the life of the process.
434///
435/// The field is `never read` on a platform without `dlopen`: [`dlopen`] there always answers
436/// `None`, so no `Library` is ever constructed and [`dlsym`] never sees one. Keeping the type
437/// rather than `cfg`-ing it away means the code above it — [`load_native_module`] — has one
438/// shape on both platforms, which is the point of the split.
439struct Library(#[allow(dead_code)] *mut c_void);
440
441/// `dlopen(path, RTLD_NOW | RTLD_LOCAL)`.
442#[cfg(unix)]
443fn dlopen(path: &str) -> Option<Library> {
444    let path = std::ffi::CString::new(path).ok()?;
445    // SAFETY: `path` is a NUL-terminated string, and the flags are the reference's:
446    // `RTLD_NOW` resolves every symbol immediately — a missing one is a load error rather
447    // than a crash at the first call — and `RTLD_LOCAL` keeps this module's symbols out of
448    // the global namespace, which is what lets two modules of the same name coexist.
449    let handle = unsafe { libc::dlopen(path.as_ptr(), libc::RTLD_NOW | libc::RTLD_LOCAL) };
450    if handle.is_null() {
451        None
452    } else {
453        // Leaked on purpose: see the module docs. `Library` is only ever constructed to be
454        // forgotten, and spelling that out keeps the "never closed" rule in one place.
455        Some(Library(handle))
456    }
457}
458
459/// `dlsym(handle, symbol)`, as the module entry point's type.
460#[cfg(unix)]
461fn dlsym(handle: Library, symbol: &str) -> Option<InitModuleFunc> {
462    let symbol = std::ffi::CString::new(symbol).ok()?;
463    // SAFETY: the handle came from `dlopen` and is never closed, so the symbol stays valid.
464    let pointer = unsafe { libc::dlsym(handle.0, symbol.as_ptr()) };
465    if pointer.is_null() {
466        return None;
467    }
468    // SAFETY: the caller asked for `js_init_module`, whose signature `JS_SHARED_LIBRARY`
469    // gives exactly this type.
470    Some(unsafe { std::mem::transmute::<*mut c_void, InitModuleFunc>(pointer) })
471}
472
473/// A platform without `dlopen`: every native module is reported as unloadable.
474///
475/// The reference has the same shape (`js_module_loader_so` under `#ifdef _WIN32` throws
476/// "shared library modules are not supported yet"), and the message is the same one.
477#[cfg(not(unix))]
478fn dlopen(_path: &str) -> Option<Library> {
479    None
480}
481
482/// As [`dlsym`], for a platform with no dynamic loader.
483#[cfg(not(unix))]
484fn dlsym(_handle: Library, _symbol: &str) -> Option<InitModuleFunc> {
485    None
486}