quickjs/host.rs
1//! The host session: what makes a C function callable from a script `qjs` is running.
2//!
3//! # The problem this solves
4//!
5//! When `qjs -m test_fib.js` runs `fib(10)`, the call arrives in a C function whose first act
6//! is `JS_ToInt32(ctx, &n, argv[0])`. That call needs a `JSContext *` and, behind it, the
7//! interpreter that is executing the script. The engine is inside `Interp::run_script` while
8//! this happens, and a program that never asked the C API for anything has never published
9//! that interpreter — so the C function receives a null context and answers `JS_EXCEPTION`
10//! for no stated reason.
11//!
12//! [`session`] is the fix: for the duration of a script or module run, the interpreter is
13//! published (through the same thread-local a C callback uses) along with a context that
14//! stands for it. Everything a `.so` module does then works exactly as it does inside an
15//! embedding that called `JS_NewContext`.
16//!
17//! # Why one session per thread
18//!
19//! A class id lives in a module's static data and is registered against a runtime, so the
20//! runtime has to be the same object for every native import in the process — a fresh one per
21//! import would hand a module a different `JSRuntime *` each time. One thread-local session
22//! per thread matches how the reference's `JSRuntime` is per-process, and keeps the CLI free
23//! of any lifetime plumbing.
24//!
25//! # Why a guard rather than a callback
26//!
27//! The obvious shape is `enter(ctx, || ctx.eval(src))`, and it does not compile: the borrow
28//! of `ctx` that produces the interpreter pointer and the borrow the closure needs are the
29//! same one. A guard splits them — the borrow ends when [`session`] returns, and the guard
30//! holds raw pointers that are valid because the interpreter lives in the `Context` and does
31//! not move.
32
33use std::cell::RefCell;
34
35use engine::Interp;
36
37use crate::runtime::{self, JsContext, JsRuntime};
38
39thread_local! {
40 /// The process's host session, created on first use.
41 static SESSION: RefCell<Option<Session>> = const { RefCell::new(None) };
42}
43
44/// The runtime plus the context that stands for whatever interpreter is running.
45struct Session {
46 runtime: Box<JsRuntime>,
47 context: JsContext,
48}
49
50impl Session {
51 fn new() -> Session {
52 let runtime = JsRuntime::new();
53 let pointer = &*runtime as *const JsRuntime as *mut JsRuntime;
54 Session {
55 runtime,
56 context: JsContext::attached(pointer),
57 }
58 }
59}
60
61/// The runtime native modules register their classes against.
62///
63/// Stable for the life of the thread, which is what a module's static `JSClassID` needs:
64/// `JS_GetRuntime` may be called from any of its functions, at any time.
65pub fn runtime_ptr() -> *mut JsRuntime {
66 SESSION.with(|slot| {
67 let mut slot = slot.borrow_mut();
68 let session = slot.get_or_insert_with(Session::new);
69 &*session.runtime as *const JsRuntime as *mut JsRuntime
70 })
71}
72
73/// Publish `context`'s interpreter for the C API until the returned guard is dropped.
74///
75/// The context is also adopted by the session's runtime for the duration, so `JS_NewClass` —
76/// which takes a `JSRuntime *` — mirrors its definition into *this* interpreter. That is the
77/// one piece of state a native module needs and cannot get any other way.
78pub fn session(context: &mut engine::Context<'_>) -> SessionGuard {
79 // Taken and erased in one expression, so the `&mut` borrow of `context` ends before this
80 // function returns and the caller is free to run the script.
81 let interp: *mut Interp<'static> = {
82 let interp = context.interp_mut();
83 // SAFETY: a `&mut Interp<'a>` and a `&mut Interp<'static>` are one pointer; the
84 // lifetime is erased only for the guard to hold, and the guard does not outlive the
85 // interpreter's real lifetime because the caller owns it.
86 unsafe { std::mem::transmute::<&mut Interp<'_>, &mut Interp<'static>>(interp) as *mut _ }
87 };
88 let runtime = runtime_ptr();
89 SESSION.with(|slot| {
90 let mut slot = slot.borrow_mut();
91 let session = slot.get_or_insert_with(Session::new);
92 let context = &session.context as *const JsContext as *mut JsContext;
93 // SAFETY: the session's runtime and context both live in the thread-local, so the
94 // pointers stay valid for as long as the guard exists.
95 unsafe { (*runtime).adopt_for_session(context) };
96 SessionGuard {
97 runtime,
98 context,
99 published: Some(runtime::publish(interp, &session.context)),
100 }
101 })
102}
103
104/// Keeps an interpreter published for as long as it lives.
105pub struct SessionGuard {
106 runtime: *mut JsRuntime,
107 context: *mut JsContext,
108 published: Option<runtime::InterpGuard>,
109}
110
111impl Drop for SessionGuard {
112 fn drop(&mut self) {
113 // The publication goes first: a C function must not be able to reach the interpreter
114 // after the runtime has forgotten the context it belongs to.
115 drop(self.published.take());
116 // SAFETY: both pointers were adopted by `session` and are still live in the
117 // thread-local.
118 unsafe { (*self.runtime).disown(self.context) };
119 }
120}