Skip to main content

quickjs/
runtime.rs

1//! `JSRuntime` and `JSContext`: the objects C holds, and how a callback finds its way back.
2//!
3//! # The re-entrancy problem
4//!
5//! A C function installed by a module looks like this:
6//!
7//! ```c
8//! static JSValue js_point_ctor(JSContext *ctx, JSValueConst new_target,
9//!                              int argc, JSValueConst *argv) {
10//!     JSPointData *s = js_mallocz(ctx, sizeof(*s));
11//!     if (JS_ToInt32(ctx, &s->x, argv[0])) goto fail;
12//!     JSValue obj = JS_NewObjectProtoClass(ctx, proto, js_point_class_id);
13//!     ...
14//! }
15//! ```
16//!
17//! Every line of it calls back into us with nothing but a `JSContext *`. Meanwhile the
18//! engine is *inside* a call — it holds a `&mut Interp` while it invokes the function, and
19//! that same interpreter is what `JS_ToInt32` has to use. There is no second interpreter to
20//! hand out.
21//!
22//! So a callback needs a channel back to the live interpreter that does not go through the
23//! `Context` (which is mutably borrowed for the whole call). That channel is a
24//! thread-local raw pointer, set around each C function invocation
25//! ([`InterpGuard`]) and read by the API functions ([`current_interp`]). It is
26//! expressible only with `unsafe`, and it is the reason this crate is on the `unsafe`
27//! allow-list — see `docs/m15-plan.md` §3.
28//!
29//! # Why the context is boxed at a stable address
30//!
31//! `engine::Context<'rt>` borrows the runtime. `JS_NewContext` therefore has to promise the
32//! borrow outlives the context, and it does so the only way an FFI layer can: the runtime
33//! lives in a `Box` owned by the `JSRuntime`, and the context keeps `&'static Runtime` to
34//! it. Free order is enforced — `JS_FreeRuntime` drops every context before the runtime —
35//! so the reference never dangles, and the `'static` is a promise about the C handle's
36//! lifetime rather than a lie about the Rust types.
37
38use std::cell::{Cell, RefCell};
39use std::rc::Rc;
40
41use core::ffi::c_int;
42
43use engine::Value;
44use engine::interp::{Interp, JsResult, Signal};
45
46use crate::alloc;
47use crate::cdefs::{ClassFinalizer, ClassGCMark, ClassId, JSClassExoticMethods};
48use crate::convert;
49use crate::jsvalue::{self, JsValue};
50
51/// The engine runtime plus the tables whose lifetime is the runtime's, not a context's.
52pub struct JsRuntime {
53    /// The engine runtime.
54    ///
55    /// Boxed twice over: the `Box` gives the address the contexts borrow, and it does not
56    /// move when the `JSRuntime` itself is moved, which is what makes the `'static` borrow
57    /// in `JS_NewContext` honest.
58    pub(crate) engine: Box<engine::Runtime>,
59    /// `JS_SetRuntimeOpaque`: the host's pointer, handed back untouched.
60    opaque: Cell<*mut core::ffi::c_void>,
61    /// `JS_SetRuntimeInfo`: a diagnostic label. Borrowed, per the header's lifetime note.
62    info: Cell<*const core::ffi::c_char>,
63    /// `JS_SetGCThreshold`: when the heap should collect.
64    gc_threshold: Cell<usize>,
65    /// `JS_SetInterruptHandler`'s callback and its opaque argument.
66    ///
67    /// One `Option` deep, not two: [`crate::cdefs::InterruptHandler`] is itself
68    /// `Option<unsafe extern "C" fn>`, because that is how the header spells a nullable
69    /// function pointer. Storing it with the opaque keeps the pair in one `Cell` read.
70    interrupt: Cell<
71        Option<(
72            unsafe extern "C" fn(*mut JsRuntime, *mut core::ffi::c_void) -> core::ffi::c_int,
73            *mut core::ffi::c_void,
74        )>,
75    >,
76    /// `JS_SetCanBlock`.
77    can_block: Cell<bool>,
78    /// `JS_SetStripInfo`'s flags, recorded and not acted on.
79    strip_info: Cell<core::ffi::c_int>,
80    /// The atoms this runtime has interned.
81    pub(crate) atoms: RefCell<crate::atoms::AtomTable>,
82    /// `JS_SetModuleLoaderFunc`'s pair plus its opaque argument.
83    module_loader: RefCell<Option<ModuleLoaderHooks>>,
84    /// Every live context, so `JS_FreeRuntime` can drop them before the runtime goes.
85    contexts: RefCell<Vec<*mut JsContext>>,
86    /// Of those, the ones a host session owns and the runtime must not free.
87    session_contexts: RefCell<Vec<*mut JsContext>>,
88    /// The class table: what each id registered on this runtime does.
89    ///
90    /// Classes live on the runtime in the C API and on the interpreter here, so this table
91    /// is the authority and each context mirrors it. That is what lets `JS_NewClass` take a
92    /// `JSRuntime *` and still register somewhere a script can see.
93    ///
94    /// A `BTreeMap` rather than a `Vec` indexed by id, because ids are global (see
95    /// [`allocate_class_id`]): a second runtime would otherwise have to allocate a slot for
96    /// every id the first one ever handed out.
97    classes: RefCell<std::collections::BTreeMap<ClassId, Rc<ClassDecl>>>,
98}
99
100/// What `JS_SetModuleLoaderFunc`/`JS_SetModuleLoaderFunc2` installed.
101///
102/// Kept on the runtime rather than pushed into a context, because the reference's signature
103/// takes a `JSRuntime *` and a context created later has to inherit it.
104#[derive(Clone, Copy)]
105pub struct ModuleLoaderHooks {
106    /// `JSModuleNormalizeFunc`.
107    pub normalize: crate::cdefs::ModuleNormalizeFunc,
108    /// `JSModuleLoaderFunc` — the one-argument form.
109    pub loader: crate::cdefs::ModuleLoaderFunc,
110    /// `JSModuleLoaderFunc2`, the form that also receives the import attributes.
111    pub loader2: crate::cdefs::ModuleLoaderFunc2,
112    /// `JSModuleCheckSupportedImportAttributes`.
113    pub check_attrs: crate::cdefs::ModuleCheckAttrs,
114    /// The host's context pointer.
115    pub opaque: *mut core::ffi::c_void,
116}
117
118/// The next class id, shared by every runtime in the process.
119///
120/// The reference does the same (`js_class_id_alloc` is a file-level counter behind a mutex),
121/// and the reason is that a class id lives in a C module's static data: the module is loaded
122/// once, its `JS_NewClassID` runs once, and the id it remembers has to mean that class in
123/// whichever runtime it is later registered with.
124static NEXT_CLASS_ID: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(1);
125
126/// Allocate a class id (`JS_NewClassID`).
127///
128/// Starts at 1: zero is `JS_INVALID_CLASS_ID`, and `JS_GetOpaque(val, 0)` has to match
129/// nothing. Needs no runtime, which is what makes it callable from a module's `JS_InitClass`
130/// before any context exists.
131pub fn allocate_class_id() -> ClassId {
132    NEXT_CLASS_ID.fetch_add(1, std::sync::atomic::Ordering::SeqCst)
133}
134
135/// One class, as the C side declared it.
136///
137/// A copy of the `JSClassDef` fields rather than the struct itself, because the same class
138/// has to be registered into every context's interpreter, and the engine's `ClassDef` owns
139/// boxed closures — it cannot be cloned and must not be shared between interpreters.
140#[derive(Clone, Copy)]
141pub struct ClassDecl {
142    /// `JSClassDef::finalizer`, called with the payload when an instance is released.
143    pub finalizer: ClassFinalizer,
144    /// `JSClassDef::gc_mark`.
145    pub gc_mark: ClassGCMark,
146    /// `JSClassDef::exotic`.
147    pub exotic: *const JSClassExoticMethods,
148    /// The name, for diagnostics.
149    pub name: *const core::ffi::c_char,
150}
151
152/// `JSContext`: one interpreter, its pending exception, and its runtime back-pointer.
153pub struct JsContext {
154    /// Where this context's interpreter comes from.
155    source: ContextSource,
156    /// The exception a failed API call left for `JS_GetException`.
157    ///
158    /// The reference keeps exactly one per context, and the rule is the same: a C function
159    /// that raises stores it and answers [`jsvalue::EXCEPTION`]; the caller either
160    /// propagates that (`return JS_EXCEPTION`) or clears it with `JS_GetException`.
161    pending: RefCell<Option<Value>>,
162    /// The runtime this context belongs to, for `JS_GetRuntime`.
163    runtime: Cell<*mut JsRuntime>,
164    /// The C modules this context created, so they are freed with it.
165    ///
166    /// `JS_NewCModule` hands C a `JSModuleDef *` that C keeps for as long as the module
167    /// lives, and the reference frees it with the context. Ownership therefore sits here,
168    /// with the pointers leaked on purpose until [`JsContext::free_modules`] runs.
169    modules: RefCell<Vec<*mut crate::cdefs::JsModuleDef>>,
170    /// `JS_SetContextOpaque`: the host's pointer.
171    opaque: Cell<*mut core::ffi::c_void>,
172    /// `JS_SetContextValue`'s slots, indexed by `idx` (a `BTreeMap` so a sparse index
173    /// costs only the slots used).
174    values: RefCell<std::collections::BTreeMap<core::ffi::c_int, Value>>,
175    /// `JS_DupContext`'s count: how many `JS_FreeContext` calls are still owed.
176    ///
177    /// The reference keeps the same count in the context's header. Without it a host that
178    /// duplicates a context it hands to a callback — the documented reason the function
179    /// exists — would free the context out from under itself on the first release, which is
180    /// a use-after-free that shows up as a crash somewhere else entirely.
181    dups: Cell<usize>,
182}
183
184/// Where a context's interpreter comes from.
185pub enum ContextSource {
186    /// A context that owns one (`JS_NewContext`). The `RefCell` is what lets the API's
187    /// `*mut JSContext` be a shared reference: the alternative is one long-lived `&mut` per
188    /// entry point, which the re-entrant callback path would alias on every call.
189    Owned(RefCell<Box<engine::Context<'static>>>),
190    /// A context that *is* whatever interpreter is current — the one a `.so` module's
191    /// `js_init_module` runs against.
192    ///
193    /// A native module is loaded from inside a running script, so its `JSContext *` has to
194    /// be the interpreter the engine is already inside. There is no second interpreter to
195    /// own, and owning one would be wrong: `JS_GetOpaque` and class registration have to
196    /// reach the same objects the importing script sees.
197    Attached,
198}
199
200thread_local! {
201    /// The interpreter of the C function currently running, if any.
202    ///
203    /// Raw and lifetime-erased on purpose: the pointee is a `&mut Interp<'rt>` the engine
204    /// is holding one frame up, and the only thing that may be done with it here is to use
205    /// it for the duration of the callback. [`InterpGuard`] restores the previous value on
206    /// drop, so nesting works.
207    static CURRENT_INTERP: Cell<*mut Interp<'static>> = const { Cell::new(std::ptr::null_mut()) };
208    /// The context of the C function currently running, if any.
209    static CURRENT_CONTEXT: Cell<*mut JsContext> = const { Cell::new(std::ptr::null_mut()) };
210    /// The runtime whose finalizer is running, plus the payload it was given.
211    ///
212    /// A finalizer is called with `(JSRuntime *, JSValue val)` and by definition the object
213    /// behind `val` is already being destroyed — there is no `JSValue` left to pass. So the
214    /// value handed over is a *sentinel* whose payload is [`FINALIZER_SENTINEL`], and
215    /// `JS_GetOpaque` answers from this cell instead of from an object. It is the one place
216    /// where "read the payload off the value" cannot work, and the reference has the same
217    /// hole (it keeps the half-dead object's fields readable).
218    static FINALIZING: Cell<Option<(*mut JsRuntime, ClassId, *mut ())>> = const { Cell::new(None) };
219}
220
221/// The payload of the `JSValue` a finalizer is handed.
222///
223/// Address 1 is never a real allocation: every block this crate allocates is at least
224/// 8-byte aligned, and no allocator returns a pointer into the first page. Written as a
225/// `const` dereference of the canonical dangling pointer rather than a cast, which is the
226/// same address through a spelling `clippy` does not have to guess about.
227pub const FINALIZER_SENTINEL: *mut () = std::ptr::dangling_mut::<()>();
228
229impl JsRuntime {
230    /// `JS_NewRuntime`.
231    pub fn new() -> Box<JsRuntime> {
232        Box::new(JsRuntime {
233            engine: Box::new(engine::Runtime::new()),
234            opaque: Cell::new(std::ptr::null_mut()),
235            info: Cell::new(std::ptr::null()),
236            gc_threshold: Cell::new(0),
237            interrupt: Cell::new(None),
238            can_block: Cell::new(true),
239            strip_info: Cell::new(0),
240            atoms: RefCell::new(crate::atoms::AtomTable::new()),
241            module_loader: RefCell::new(None),
242            contexts: RefCell::new(Vec::new()),
243            session_contexts: RefCell::new(Vec::new()),
244            classes: RefCell::new(std::collections::BTreeMap::new()),
245        })
246    }
247
248    /// `JS_GetRuntimeOpaque`.
249    pub fn opaque(&self) -> *mut core::ffi::c_void {
250        self.opaque.get()
251    }
252
253    /// `JS_SetRuntimeOpaque`.
254    pub fn set_opaque(&self, opaque: *mut core::ffi::c_void) {
255        self.opaque.set(opaque);
256    }
257
258    /// `JS_GetRuntimeInfo`, which the reference does not export but `JS_SetRuntimeInfo` sets.
259    pub fn info(&self) -> *const core::ffi::c_char {
260        self.info.get()
261    }
262
263    /// `JS_SetRuntimeInfo`.
264    pub fn set_info(&self, info: *const core::ffi::c_char) {
265        self.info.set(info);
266    }
267
268    /// `JS_SetGCThreshold`. A threshold of `0` means "collect on every allocation", which is
269    /// not worth reproducing; the value is kept and used by [`JsRuntime::maybe_collect`].
270    pub fn set_gc_threshold(&self, threshold: usize) {
271        self.gc_threshold.set(threshold);
272    }
273
274    /// `JS_GetGCThreshold`, our addition: the threshold the host set.
275    pub fn gc_threshold(&self) -> usize {
276        self.gc_threshold.get()
277    }
278
279    /// `JS_SetInterruptHandler`.
280    pub fn set_interrupt_handler(
281        &self,
282        callback: crate::cdefs::InterruptHandler,
283        opaque: *mut core::ffi::c_void,
284    ) {
285        // `callback` is already an `Option<fn>`: the header's handler pointer, null or not.
286        self.interrupt
287            .set(callback.map(|callback| (callback, opaque)));
288    }
289
290    /// The installed interrupt handler, if any.
291    pub fn interrupt_handler(
292        &self,
293    ) -> Option<(
294        unsafe extern "C" fn(*mut JsRuntime, *mut core::ffi::c_void) -> core::ffi::c_int,
295        *mut core::ffi::c_void,
296    )> {
297        self.interrupt.get()
298    }
299
300    /// `JS_SetCanBlock`.
301    pub fn set_can_block(&self, can_block: bool) {
302        self.can_block.set(can_block);
303    }
304
305    /// Whether a blocking operation is allowed (`JS_SetCanBlock`'s answer).
306    pub fn can_block(&self) -> bool {
307        self.can_block.get()
308    }
309
310    /// `JS_SetModuleLoaderFunc`/`JS_SetModuleLoaderFunc2`'s state.
311    pub fn module_loader_hooks(&self) -> Option<ModuleLoaderHooks> {
312        *self.module_loader.borrow()
313    }
314
315    /// Record the module loader hooks.
316    pub fn set_module_loader_hooks(&self, hooks: ModuleLoaderHooks) {
317        *self.module_loader.borrow_mut() = Some(hooks);
318    }
319
320    /// Every live context, for the API functions that take a `JSRuntime *`.
321    pub fn live_contexts(&self) -> Vec<*mut JsContext> {
322        self.contexts.borrow().clone()
323    }
324
325    /// The engine runtime as a raw pointer, for the API functions that need `&mut`.
326    ///
327    /// A `*mut` rather than a reference because `JS_SetMemoryLimit` takes a `JSRuntime *` and
328    /// has no borrow to hand out; the caller forms the `&mut` under the single-threaded-per-
329    /// runtime contract the C API states.
330    pub fn engine_ptr(&self) -> *const engine::Runtime {
331        self.engine.as_ref() as *const engine::Runtime
332    }
333
334    /// `JS_SetStripInfo`'s recorded flags.
335    pub fn strip_info(&self) -> core::ffi::c_int {
336        self.strip_info.get()
337    }
338
339    /// Record the strip-info flags.
340    pub fn set_strip_info(&self, flags: core::ffi::c_int) {
341        self.strip_info.set(flags);
342    }
343
344    /// The engine runtime, for the context that has to borrow it.
345    fn engine_ref(&self) -> &'static engine::Runtime {
346        // SAFETY: `engine` is a `Box` owned by this runtime, and the borrow is handed to a
347        // context that this runtime outlives — `JS_FreeRuntime` drops every context first.
348        unsafe { &*(self.engine.as_ref() as *const engine::Runtime) }
349    }
350
351    /// `JS_NewClass`: register (or replace) the class under `id`.
352    ///
353    /// Answers `false` for `JS_INVALID_CLASS_ID`, which the C API reports as `-1`.
354    pub fn define_class(&self, id: ClassId, decl: ClassDecl) -> bool {
355        if id == 0 {
356            return false;
357        }
358        self.classes.borrow_mut().insert(id, Rc::new(decl));
359        // Mirror it into every live context: a class registered before a context existed,
360        // or after another one did, has to be visible from all of them.
361        for &context in self.contexts.borrow().iter() {
362            // SAFETY: the pointer is live until `JS_FreeContext`, which removes it from
363            // this list.
364            unsafe { (*context).register_class(id, decl) };
365        }
366        true
367    }
368
369    /// The class registered under `id`, if any.
370    pub fn class(&self, id: ClassId) -> Option<Rc<ClassDecl>> {
371        self.classes.borrow().get(&id).cloned()
372    }
373
374    /// Whether `id` names a registered class.
375    pub fn has_class(&self, id: ClassId) -> bool {
376        self.class(id).is_some()
377    }
378
379    /// Track a context so it can be dropped with the runtime.
380    fn adopt(&self, context: *mut JsContext) {
381        self.contexts.borrow_mut().push(context);
382    }
383
384    /// Track a context the host owns, for as long as a script runs.
385    ///
386    /// The context is *not* dropped with the runtime: the host session owns it, and the
387    /// runtime only borrows it to reach the interpreter class registration has to write to.
388    /// `JS_FreeRuntime` therefore skips it, which is why this is a separate entry point from
389    /// [`JsRuntime::adopt`].
390    ///
391    /// # Safety
392    ///
393    /// `context` must stay alive until [`JsRuntime::disown`] is called with it.
394    pub unsafe fn adopt_for_session(&self, context: *mut JsContext) {
395        self.session_contexts.borrow_mut().push(context);
396        self.adopt(context);
397    }
398
399    /// Forget a context from [`JsRuntime::adopt_for_session`].
400    ///
401    /// # Safety
402    ///
403    /// `context` must have been adopted by `adopt_for_session` and not disowned since.
404    pub unsafe fn disown(&self, context: *mut JsContext) {
405        self.contexts.borrow_mut().retain(|&live| live != context);
406        self.session_contexts
407            .borrow_mut()
408            .retain(|&live| live != context);
409    }
410
411    /// `JS_FreeRuntime`: drop every context, then the runtime.
412    ///
413    /// # Safety
414    ///
415    /// `runtime` must come from [`JsRuntime::new`] via `Box::into_raw`, and no context or
416    /// class handle may be used afterwards.
417    pub unsafe fn free(runtime: *mut JsRuntime) {
418        if runtime.is_null() {
419            return;
420        }
421        // SAFETY: the caller guarantees this pointer came from `Box::into_raw`.
422        let runtime = unsafe { Box::from_raw(runtime) };
423        // Contexts first: each one borrows the runtime, so dropping them afterwards would
424        // be a use-after-free. `drain` also keeps the vector from being seen half-empty.
425        let contexts: Vec<*mut JsContext> = runtime.contexts.borrow_mut().drain(..).collect();
426        let borrowed: Vec<*mut JsContext> =
427            runtime.session_contexts.borrow_mut().drain(..).collect();
428        for context in contexts {
429            if borrowed.contains(&context) {
430                // A host session's context: someone else owns it, and it is about to be
431                // dropped by them. Freeing it here would be a double free.
432                continue;
433            }
434            // SAFETY: each pointer was created by `Box::into_raw` in `JsContext::new` and is
435            // still owned here.
436            drop(unsafe { Box::from_raw(context) });
437        }
438    }
439}
440
441impl JsContext {
442    /// `JS_DupContext`: one more release is owed before this context dies.
443    pub fn raise_refs(&self) {
444        self.dups.set(self.dups.get().saturating_add(1));
445    }
446
447    /// `JS_FreeContext`: answer whether this call released the context or only a count.
448    ///
449    /// Split out so [`JS_FreeContext`] stays a three-line function: the count is only valid
450    /// while the context is alive, so it has to be read *before* the `Box` is rebuilt.
451    fn release_ref(&self) -> bool {
452        let count = self.dups.get();
453        if count == 0 {
454            return true;
455        }
456        self.dups.set(count - 1);
457        false
458    }
459
460    /// `JS_NewContext`.
461    ///
462    /// # Safety
463    ///
464    /// `runtime` must be a live pointer from `Box::into_raw(JsRuntime::new())`.
465    pub unsafe fn new(runtime: *mut JsRuntime) -> *mut JsContext {
466        // SAFETY: the caller guarantees the runtime is live.
467        let runtime_ref = unsafe { &*runtime };
468        let engine = engine::Context::new(runtime_ref.engine_ref());
469        let context = Box::new(JsContext {
470            source: ContextSource::Owned(RefCell::new(Box::new(engine))),
471            pending: RefCell::new(None),
472            runtime: Cell::new(runtime),
473            modules: RefCell::new(Vec::new()),
474            opaque: Cell::new(std::ptr::null_mut()),
475            values: RefCell::new(std::collections::BTreeMap::new()),
476            dups: Cell::new(0),
477        });
478        // The classes the runtime already knows about have to exist in this interpreter
479        // too: `JS_NewClass` may well have been called before `JS_NewContext`.
480        let classes: Vec<(ClassId, ClassDecl)> = runtime_ref
481            .classes
482            .borrow()
483            .iter()
484            .map(|(&id, decl)| (id, **decl))
485            .collect();
486        let context = context;
487        for (id, decl) in classes {
488            context.register_class(id, decl);
489        }
490        let raw = Box::into_raw(context);
491        runtime_ref.adopt(raw);
492        raw
493    }
494
495    /// A context standing for whatever interpreter is running.
496    ///
497    /// Used by the native module loader: `js_init_module` is called from inside a script's
498    /// `import`, so the `JSContext *` it receives has to address the interpreter that is
499    /// already executing. The returned handle borrows nothing for the same reason — it has
500    /// no interpreter of its own, and only ever reads the published one.
501    pub fn attached(runtime: *mut JsRuntime) -> JsContext {
502        JsContext {
503            source: ContextSource::Attached,
504            pending: RefCell::new(None),
505            runtime: Cell::new(runtime),
506            modules: RefCell::new(Vec::new()),
507            opaque: Cell::new(std::ptr::null_mut()),
508            values: RefCell::new(std::collections::BTreeMap::new()),
509            // An attached context is a borrowed view of a running interpreter; it is never
510            // freed through `JS_FreeContext`, so it has no releases owed.
511            dups: Cell::new(0),
512        }
513    }
514
515    /// `JS_GetContextOpaque`.
516    pub fn opaque(&self) -> *mut core::ffi::c_void {
517        self.opaque.get()
518    }
519
520    /// `JS_SetContextOpaque`.
521    pub fn set_opaque(&self, opaque: *mut core::ffi::c_void) {
522        self.opaque.set(opaque);
523    }
524
525    /// `JS_GetContextValue`: the value at slot `idx`, if one was stored.
526    pub fn value(&self, idx: core::ffi::c_int) -> Option<Value> {
527        self.values.borrow().get(&idx).cloned()
528    }
529
530    /// `JS_SetContextValue`.
531    pub fn set_value(&self, idx: core::ffi::c_int, value: Value) {
532        self.values.borrow_mut().insert(idx, value);
533    }
534
535    /// The runtime this context belongs to.
536    pub fn runtime(&self) -> *mut JsRuntime {
537        self.runtime.get()
538    }
539
540    /// Register `decl` under `id` in this context's interpreter.
541    fn register_class(&self, id: ClassId, decl: ClassDecl) {
542        let definition = self.class_definition(id, decl);
543        self.with_current_interp(|interp| {
544            interp.define_host_class(engine::ClassId::from_raw(id), definition);
545        });
546    }
547
548    /// Turn a C class declaration into the engine's `ClassDef`.
549    ///
550    /// The finalizer and `gc_mark` become closures that call back into C. The finalizer
551    /// needs a `JSRuntime *`, which it gets from the thread-local that
552    /// [`JsContext::with_interp`] set — a finalizer runs from `Drop`, at which point there
553    /// is no interpreter to ask.
554    fn class_definition(&self, id: ClassId, decl: ClassDecl) -> engine::ClassDef {
555        let name = if decl.name.is_null() {
556            format!("<class {id}>")
557        } else {
558            // SAFETY: `JSClassDef::class_name` is a NUL-terminated string the C module
559            // keeps alive for the life of the module, which is the life of the process.
560            unsafe { core::ffi::CStr::from_ptr(decl.name) }
561                .to_string_lossy()
562                .into_owned()
563        };
564        let mut definition = engine::ClassDef::new(name);
565        if let Some(finalizer) = decl.finalizer {
566            let runtime = self.runtime.get();
567            definition = definition.with_finalizer(Box::new(move |_class_id, opaque| {
568                call_finalizer(runtime, id, finalizer, opaque);
569            }));
570        }
571        let _ = decl.gc_mark;
572        let _ = decl.exotic;
573        definition
574    }
575
576    /// Run `f` with the interpreter a C API call should use.
577    ///
578    /// Two cases, and they are the whole re-entrancy story:
579    ///
580    /// * a C callback is running — [`current_interp`] has the interpreter the engine is
581    ///   inside, and re-borrowing this context's would panic;
582    /// * nothing is running — the call came from C at top level, so this context's own
583    ///   interpreter is the right one and [`JsContext::with_interp`] can lend it out.
584    ///
585    /// Every exported function that has to run JavaScript goes through here, which is why
586    /// none of them carries its own "am I inside a callback" check.
587    pub fn with_current_interp<R>(&self, f: impl FnOnce(&mut Interp<'static>) -> R) -> R {
588        match current_interp() {
589            Some(interp) => f(interp),
590            None => self.with_interp(f),
591        }
592    }
593
594    /// Run `f` with the engine context, publishing its interpreter for the C code `f` may
595    /// call.
596    ///
597    /// Every *entry point* — `JS_Eval`, and later `JS_Call` — goes through here rather than
598    /// straight to the engine. Without the guard a script that calls a C function arrives
599    /// with no current context, and every API call inside that function answers an exception
600    /// it cannot even describe. The failure looks like a broken C module rather than a
601    /// missed guard, which is why this is the one helper everything funnels through.
602    pub fn with_context<R>(&self, f: impl FnOnce(&mut engine::Context<'static>) -> R) -> R {
603        let ContextSource::Owned(engine) = &self.source else {
604            panic!("an attached context has no engine of its own");
605        };
606        let mut engine = engine.borrow_mut();
607        let engine: &mut engine::Context<'static> = &mut engine;
608        self.sync_interrupt_hook(engine.interp_mut());
609        // SAFETY: the pointer is only used while the borrow lives, and the guard clears it
610        // before this scope ends.
611        let interp: *mut Interp<'static> = engine.interp_mut();
612        let guard = InterpGuard::enter(interp, self);
613        let result = f(engine);
614        drop(guard);
615        result
616    }
617
618    /// Set the interpreter's stack budget, for a limit set after the context was created.
619    pub fn set_stack_limit(&self, limit: usize) {
620        if matches!(self.source, ContextSource::Attached) {
621            // An attached context has no engine of its own: its stack budget belongs to the
622            // host's interpreter, which the host already set.
623            return;
624        }
625        self.with_context(|engine| {
626            // `with_context` installs the *interrupt* hook on the way in; the budget is a
627            // plain field of the interpreter, so it is written here.
628            engine.interp_mut().stack_limit = limit;
629        });
630    }
631
632    /// Install the interrupt closure into this context's interpreter, if it has one.
633    ///
634    /// Called from `JS_SetInterruptHandler`, because a context that already evaluated
635    /// something owns its interpreter and would otherwise never see a handler set afterwards.
636    pub fn install_interrupt_hook(&self) {
637        let runtime = self.runtime.get();
638        // SAFETY: the runtime outlives this context, and the pointer is only read.
639        if unsafe { runtime.as_ref() }.is_none() {
640            return;
641        }
642        if matches!(self.source, ContextSource::Attached) {
643            // An attached context has no engine of its own: it is the C API's view of the
644            // interpreter the *host* is running, so the hook belongs to the host's engine.
645            return;
646        }
647        self.with_context(|engine| {
648            let _ = engine;
649        });
650    }
651
652    /// Whether the runtime has no interrupt handler, read through the back-pointer.
653    fn runtime_interrupt_is_unset(&self) -> bool {
654        // SAFETY: the runtime outlives this context.
655        match unsafe { self.runtime.get().as_ref() } {
656            Some(runtime) => runtime.interrupt_handler().is_none(),
657            None => true,
658        }
659    }
660
661    /// Make sure the engine polls this runtime's interrupt handler.
662    ///
663    /// Installed once per interpreter, as a closure that re-reads the runtime's `Cell` on every
664    /// poll — so a handler set *after* the first evaluation still takes effect, which is the
665    /// ordering a host that sets it late expects. The pointer is the runtime's, and the runtime
666    /// outlives every context it adopted, which is what makes the `'static` box sound.
667    pub(crate) fn sync_interrupt_hook(&self, interp: &mut Interp<'static>) {
668        if interp.interrupt.is_some() || self.runtime_interrupt_is_unset() {
669            // Nothing to install, or nothing to install it *for*: a runtime whose host never
670            // asked for an interrupt keeps the zero-cost path, which is every benchmark and
671            // every test262 run.
672            return;
673        }
674        // SAFETY: the runtime outlives the interpreter (a context is freed before its
675        // runtime), so the raw pointer stays valid for as long as the closure can run.
676        let runtime: *const JsRuntime = self.runtime.get();
677        interp.interrupt = Some(Box::new(move || {
678            let Some(runtime) = (unsafe { runtime.as_ref() }) else {
679                return false;
680            };
681            match runtime.interrupt_handler() {
682                // SAFETY: the callback is the host's; the header's contract is that it is a
683                // `JSInterruptHandler` and the runtime is live, both of which the setter
684                // guarantees.
685                Some((callback, opaque)) => {
686                    // SAFETY: the callback is the host's `JSInterruptHandler`, set through
687                    // `JS_SetInterruptHandler`, and the runtime it was given is this one.
688                    unsafe { callback(runtime as *const _ as *mut _, opaque) != 0 }
689                }
690                None => false,
691            }
692        }));
693    }
694
695    /// Run `f` with the interpreter, publishing it for the C code `f` may call.
696    ///
697    /// The guard is what makes a nested API call work: while `f` runs, `JS_*` functions
698    /// called from C find this interpreter through [`current_interp`]. `f` receives the
699    /// same `&mut` the guard published, so nothing is aliased that `f` itself did not hand
700    /// to C.
701    pub fn with_interp<R>(&self, f: impl FnOnce(&mut Interp<'static>) -> R) -> R {
702        self.with_context(|engine| f(engine.interp_mut()))
703    }
704
705    /// `JS_GetException`: take the pending exception, if there is one.
706    pub fn take_pending(&self) -> Option<Value> {
707        self.pending.borrow_mut().take()
708    }
709
710    /// Store an exception for `JS_GetException` to return.
711    pub fn set_pending(&self, value: Value) {
712        *self.pending.borrow_mut() = Some(value);
713    }
714
715    /// Whether a call left an exception behind.
716    pub fn has_pending(&self) -> bool {
717        self.pending.borrow().is_some()
718    }
719}
720
721/// Publishes a live interpreter for the duration of a C callback.
722pub struct InterpGuard {
723    previous_interp: *mut Interp<'static>,
724    previous_context: *mut JsContext,
725}
726
727impl InterpGuard {
728    /// Make `interp` and `context` the current ones until the guard is dropped.
729    fn enter(interp: *mut Interp<'static>, context: &JsContext) -> InterpGuard {
730        // The pointer C will pass back to us has to be the boxed context, not this borrow;
731        // `JsContext::with_interp` is only ever reached through `*mut JSContext`, so the
732        // borrow and the box are the same address.
733        let pointer = context as *const JsContext as *mut JsContext;
734        let previous_interp = CURRENT_INTERP.with(|cell| cell.replace(interp));
735        let previous_context = CURRENT_CONTEXT.with(|cell| cell.replace(pointer));
736        InterpGuard {
737            previous_interp,
738            previous_context,
739        }
740    }
741}
742
743impl Drop for InterpGuard {
744    fn drop(&mut self) {
745        CURRENT_INTERP.with(|cell| cell.set(self.previous_interp));
746        CURRENT_CONTEXT.with(|cell| cell.set(self.previous_context));
747    }
748}
749
750/// Publish `interp` (and `context`) for as long as the guard lives.
751///
752/// The native module loader uses this: it has the running interpreter as a `&mut` and needs
753/// the C API to see it. Everything the module does — `JS_NewClass`, `JS_ToInt32`,
754/// `JS_NewObject` — then runs against that interpreter rather than a second one.
755pub fn publish(interp: *mut Interp<'static>, context: &JsContext) -> InterpGuard {
756    InterpGuard::enter(interp, context)
757}
758
759/// The interpreter of the C code currently running.
760///
761/// `None` outside a callback: a C module must not call the API from its own thread with no
762/// call in progress, and the reference would have no `ctx` to pass either.
763pub fn current_interp() -> Option<&'static mut Interp<'static>> {
764    CURRENT_INTERP.with(|cell| {
765        let pointer = cell.get();
766        if pointer.is_null() {
767            None
768        } else {
769            // SAFETY: `InterpGuard` published a live interpreter for exactly the duration of
770            // the callback this call is running inside; the engine's own `&mut` is
771            // suspended while the callback runs.
772            Some(unsafe { &mut *pointer })
773        }
774    })
775}
776
777/// The context of the C code currently running.
778pub fn current_context() -> Option<&'static JsContext> {
779    CURRENT_CONTEXT.with(|cell| {
780        let pointer = cell.get();
781        if pointer.is_null() {
782            None
783        } else {
784            // SAFETY: as `current_interp` — the pointer was published for this callback.
785            Some(unsafe { &*pointer })
786        }
787    })
788}
789
790/// Call a C finalizer, with the runtime and the sentinel value it expects.
791fn call_finalizer(
792    runtime: *mut JsRuntime,
793    class_id: ClassId,
794    finalizer: unsafe extern "C" fn(*mut core::ffi::c_void, JsValue),
795    opaque: engine::Opaque,
796) {
797    let sentinel = JsValue::mkptr(jsvalue::TAG_OBJECT, FINALIZER_SENTINEL);
798    let previous = FINALIZING.with(|cell| cell.replace(Some((runtime, class_id, opaque.as_ptr()))));
799    // SAFETY: the C module registered this function pointer as a `JSClassFinalizer`, whose
800    // signature it is; the sentinel is only ever read by `JS_GetOpaque`, which consults
801    // `FINALIZING` rather than dereferencing it.
802    unsafe { finalizer(runtime.cast(), sentinel) };
803    FINALIZING.with(|cell| cell.set(previous));
804}
805
806/// The payload a finalizer's sentinel value stands for, when `class_id` matches.
807pub fn finalizer_opaque(class_id: ClassId) -> Option<*mut ()> {
808    FINALIZING.with(|cell| match cell.get() {
809        Some((_, id, opaque)) if id == class_id => Some(opaque),
810        _ => None,
811    })
812}
813
814/// The runtime a finalizer is running for.
815pub fn finalizer_runtime() -> Option<*mut JsRuntime> {
816    FINALIZING.with(|cell| cell.get().map(|(runtime, _, _)| runtime))
817}
818
819/// Whether `value` is the sentinel a finalizer is handed.
820pub fn is_finalizer_sentinel(value: JsValue) -> bool {
821    value.payload() == FINALIZER_SENTINEL as usize as u64 && value.is_object()
822}
823
824// ---------------------------------------------------------------------------
825// The conventions every exported function shares
826// ---------------------------------------------------------------------------
827
828/// Turn an engine result into the `JSValue` a C caller expects.
829///
830/// The one rule the whole API follows: an owned value becomes a boxed `JSValue`, and a
831/// failure becomes [`jsvalue::EXCEPTION`] with the reason stored as the context's pending
832/// exception. `JS_ToInt32(ctx, …, v)` then answers `-1`, the C function returns
833/// `JS_EXCEPTION`, and the trampoline that invoked it turns the pending exception into the
834/// engine's `Signal::Throw`.
835pub fn result_value(context: &JsContext, result: JsResult<Value>) -> JsValue {
836    match result {
837        Ok(value) => convert::encode(&value),
838        Err(signal) => {
839            let thrown = match signal {
840                Signal::Throw(value) => value,
841                Signal::OutOfMemory => context.throw_out_of_memory(),
842            };
843            context.set_pending(thrown);
844            jsvalue::EXCEPTION
845        }
846    }
847}
848
849impl JsContext {
850    /// Free the C modules this context created.
851    ///
852    /// Called from `JS_FreeContext`, before the context's interpreter goes: a module's
853    /// `JSModuleDef` holds export values, which are engine handles.
854    fn free_modules(&self) {
855        for pointer in self.modules.borrow_mut().drain(..) {
856            // SAFETY: each pointer was created by `JS_NewCModule` in this context and is
857            // still owned here.
858            drop(unsafe { Box::from_raw(pointer) });
859        }
860    }
861
862    /// The C modules this context created.
863    pub fn module_table(&self) -> &RefCell<Vec<*mut crate::cdefs::JsModuleDef>> {
864        &self.modules
865    }
866
867    /// A `RangeError`/`InternalError` for a failed allocation, as a pending exception.
868    pub fn throw_out_of_memory(&self) -> Value {
869        // Through `with_current_interp`, not `engine.borrow_mut()`: this is reached from a
870        // failing allocation *inside* a callback, where the context's own borrow is already
871        // held by the entry point that is running us.
872        self.with_current_interp(|interp| interp.make_error("InternalError", "out of memory"))
873    }
874}
875
876/// `JS_ThrowRangeError`-style error, stored as the pending exception of `context`.
877pub fn throw_error(context: &JsContext, name: &str, message: &str) -> JsValue {
878    // Build the error with whichever interpreter is current: this is called from inside a
879    // callback as often as from a top-level API call, and the borrow has to follow.
880    let value = context.with_current_interp(|interp| interp.make_error(name, message));
881    context.set_pending(value);
882    jsvalue::EXCEPTION
883}
884
885/// Decode an argument a C caller passed in.
886///
887/// A reference-counted value is a box this crate produced; the clone keeps the engine value
888/// alive independently, so nothing has to be freed here. `argv` entries are *borrowed* by
889/// the C API's convention and must not be released by us.
890///
891/// # Safety
892///
893/// `value` must be a `JSValue` from this crate, and a reference-counted one must be live.
894pub unsafe fn argument(value: JsValue) -> Option<Value> {
895    // SAFETY: the caller guarantees the value is ours and alive.
896    unsafe { convert::decode(value) }
897}
898
899/// Release the reference a returned `JSValue` held, after taking what we need from it.
900///
901/// The C API's convention is that every function returning a `JSValue` returns a *new* reference:
902/// the caller owns it and must free it. When the caller is us — the trampoline around a C
903/// function, or a Rust-side test — the box has to be released once the engine value has been
904/// cloned out, or the payload leaks for the life of the process.
905///
906/// # Safety
907///
908/// `value` must be an owned `JSValue` from this crate that is not used afterwards.
909pub unsafe fn release(value: JsValue) {
910    if !value.has_ref_count() {
911        return;
912    }
913    if is_finalizer_sentinel(value) {
914        return;
915    }
916    let Some(payload) = value.as_ptr() else {
917        return;
918    };
919    // Exactly what the header's inline `JS_FreeValue` does, and for the same reason: a value
920    // can have several owners. `JS_DupValue` exists precisely so that two holders can each
921    // free their own claim, and handing a duplicated value to an API function that consumes
922    // it must not free the other holder's payload. An earlier version of this function freed
923    // unconditionally and made `JS_SetClassProto(ctx, id, JS_DupValue(ctx, ctor))` — the
924    // reference's own idiom — a use-after-free.
925    // SAFETY: the caller owns one reference to a live box.
926    let count = unsafe { alloc::ValueBox::ref_count(payload) } - 1;
927    // SAFETY: as above.
928    unsafe { alloc::ValueBox::set_ref_count(payload, count) };
929    if count <= 0 {
930        // SAFETY: the count just reached zero, so this was the last reference.
931        unsafe { alloc::free_value(payload) };
932    }
933}
934
935// ---------------------------------------------------------------------------
936// The exported entry points: runtime, context, evaluation, exceptions
937// ---------------------------------------------------------------------------
938
939/// `JS_NewRuntime`.
940#[unsafe(no_mangle)]
941pub extern "C" fn JS_NewRuntime() -> *mut JsRuntime {
942    Box::into_raw(JsRuntime::new())
943}
944
945/// `JS_FreeRuntime`: drop the runtime and every context it still owns.
946///
947/// # Safety
948///
949/// `rt` must come from `JS_NewRuntime`, and every `JSContext *` derived from it must be
950/// considered dead afterwards.
951#[unsafe(no_mangle)]
952pub unsafe extern "C" fn JS_FreeRuntime(rt: *mut JsRuntime) {
953    // SAFETY: the caller's contract.
954    unsafe { JsRuntime::free(rt) }
955}
956
957/// `JS_NewContext`.
958///
959/// # Safety
960///
961/// `rt` must be a live runtime.
962#[unsafe(no_mangle)]
963pub unsafe extern "C" fn JS_NewContext(rt: *mut JsRuntime) -> *mut JsContext {
964    if rt.is_null() {
965        return std::ptr::null_mut();
966    }
967    // SAFETY: the caller's contract.
968    unsafe { JsContext::new(rt) }
969}
970
971/// `JS_FreeContext`: drop one context, leaving its runtime alive.
972///
973/// # Safety
974///
975/// `ctx` must come from `JS_NewContext` and not have been freed.
976#[unsafe(no_mangle)]
977pub unsafe extern "C" fn JS_FreeContext(ctx: *mut JsContext) {
978    if ctx.is_null() {
979        return;
980    }
981    // A duplicated context is not freed until every `JS_DupContext` has been paired with a
982    // release, which is the reference's contract and the whole point of the function.
983    if let Some(context) = unsafe { ctx.as_ref() } {
984        if !context.release_ref() {
985            return;
986        }
987    }
988    // SAFETY: the caller's contract.
989    let context = unsafe { Box::from_raw(ctx) };
990    context.free_modules();
991    // SAFETY: the runtime outlives every context it adopted — `JS_FreeRuntime` drops
992    // contexts first — so the back-pointer is still valid here.
993    if let Some(runtime) = unsafe { context.runtime().as_ref() } {
994        // SAFETY: `ctx` is the context being freed, and it is removed from the runtime's
995        // lists before the runtime could ever reach it again.
996        unsafe { runtime.disown(ctx) };
997    }
998}
999
1000/// `JS_GetException`: the pending exception as a new reference, or `null` when there is
1001/// none.
1002///
1003/// # Safety
1004///
1005/// `ctx` must be a live context.
1006#[unsafe(no_mangle)]
1007pub unsafe extern "C" fn JS_GetException(ctx: *mut JsContext) -> JsValue {
1008    let Some(context) = (unsafe { ctx.as_ref() }) else {
1009        return jsvalue::NULL;
1010    };
1011    match context.take_pending() {
1012        Some(value) => convert::encode(&value),
1013        // The reference answers `JS_NULL` rather than `JS_UNDEFINED`, so a script that
1014        // reads `.message` off it gets a `TypeError` instead of `undefined`.
1015        None => jsvalue::NULL,
1016    }
1017}
1018
1019/// `JS_Throw`: replace the pending exception with `obj`, answering `JS_EXCEPTION`.
1020///
1021/// # Safety
1022///
1023/// `ctx` must be a live context and `obj` a live `JSValue` whose reference this call
1024/// consumes.
1025#[unsafe(no_mangle)]
1026pub unsafe extern "C" fn JS_Throw(ctx: *mut JsContext, obj: JsValue) -> JsValue {
1027    let Some(context) = (unsafe { ctx.as_ref() }) else {
1028        return jsvalue::EXCEPTION;
1029    };
1030    let value = unsafe { argument(obj) }.unwrap_or(Value::Undefined);
1031    // SAFETY: the C API consumes the reference it was handed.
1032    unsafe { release(obj) };
1033    context.set_pending(value);
1034    jsvalue::EXCEPTION
1035}
1036
1037/// `JS_Eval`: compile and run `input` as global (or module) code.
1038///
1039/// The thrown value travels through the pending-exception slot rather than being turned
1040/// into text, which is the whole point: `JS_GetException` then hands C the object the script
1041/// threw, with its `message`, its `stack` and any property a host put on it.
1042///
1043/// Module evaluation needs a module loader, which is S4's `dlopen` work; a module eval here
1044/// reports a `TypeError` instead of pretending to have run.
1045///
1046/// # Safety
1047///
1048/// `ctx` must be a live context, and `input` must point at `input_len` readable bytes;
1049/// `filename` may be null or a NUL-terminated string.
1050#[unsafe(no_mangle)]
1051pub unsafe extern "C" fn JS_Eval(
1052    ctx: *mut JsContext,
1053    input: *const core::ffi::c_char,
1054    input_len: usize,
1055    filename: *const core::ffi::c_char,
1056    eval_flags: core::ffi::c_int,
1057) -> JsValue {
1058    // SAFETY: the caller's contract is this function's.
1059    unsafe { eval_with_this_raw(ctx, input, input_len, filename, eval_flags, None) }
1060}
1061
1062/// The body of `JS_Eval` and `JS_EvalThis`, which differ only in the receiver.
1063///
1064/// Split out rather than duplicated because everything below — the null and module checks,
1065/// the choice between the running interpreter and this context's own, the pending-exception
1066/// protocol — has to be identical for the two. A second copy is how `JS_EvalThis` came to
1067/// ignore its `this_obj` in the first place.
1068///
1069/// # Safety
1070///
1071/// As [`JS_Eval`]; `this` must be a live engine value when present.
1072pub(crate) unsafe fn eval_with_this_raw(
1073    ctx: *mut JsContext,
1074    input: *const core::ffi::c_char,
1075    input_len: usize,
1076    filename: *const core::ffi::c_char,
1077    eval_flags: core::ffi::c_int,
1078    this: Option<Value>,
1079) -> JsValue {
1080    let Some(context) = (unsafe { ctx.as_ref() }) else {
1081        return jsvalue::EXCEPTION;
1082    };
1083    if input.is_null() {
1084        return throw_error(context, "TypeError", "null source");
1085    }
1086    // SAFETY: the caller guarantees `input_len` readable bytes.
1087    let bytes = unsafe { core::slice::from_raw_parts(input.cast::<u8>(), input_len) };
1088    let source = String::from_utf8_lossy(bytes).into_owned();
1089    let name = if filename.is_null() {
1090        "<input>".to_string()
1091    } else {
1092        // SAFETY: the caller guarantees a NUL-terminated string.
1093        unsafe { core::ffi::CStr::from_ptr(filename) }
1094            .to_string_lossy()
1095            .into_owned()
1096    };
1097
1098    const JS_EVAL_TYPE_MODULE: core::ffi::c_int = 1 << 0;
1099    if eval_flags & JS_EVAL_TYPE_MODULE != 0 {
1100        return throw_error(
1101            context,
1102            "TypeError",
1103            "module evaluation arrives with native module loading (M15 S4)",
1104        );
1105    }
1106
1107    // A nested `JS_Eval` — one called from inside a C function the engine is running — must
1108    // use the interpreter the engine already holds; borrowing the context's own would panic
1109    // with "RefCell already borrowed". `with_current_interp` picks the right one, and answers
1110    // the same result shape, so the match below is shared.
1111    if let Some(interp) = current_interp() {
1112        // Re-entrant: the engine is inside a call, so this is the eval path — a script
1113        // compiled with `run_script_with_this` would be a *second* top-level script, and a
1114        // script cannot start while another is running.
1115        let outcome = match this {
1116            Some(this) => interp.eval_script_with_this(&source, &name, this),
1117            None => interp.eval_in_global_named(&source, &name, false),
1118        };
1119        return match outcome {
1120            Ok(value) => convert::encode(&value),
1121            Err(Signal::Throw(value)) => {
1122                context.set_pending(value);
1123                jsvalue::EXCEPTION
1124            }
1125            Err(Signal::OutOfMemory) => {
1126                let error = interp.make_error("InternalError", "out of memory");
1127                context.set_pending(error);
1128                jsvalue::EXCEPTION
1129            }
1130        };
1131    }
1132
1133    // No receiver asked for: `JS_Eval`'s own path, unchanged. It parses with
1134    // `parse_script` rather than as an eval body, and the difference is visible — a `class`
1135    // in an eval body is a *lexical* declaration confined to that eval, while a script's
1136    // class is script-scoped. `tests/objects.rs` caught exactly that when this function
1137    // served both entry points.
1138    if this.is_none() {
1139        return context.with_context(|engine| match engine.eval_detailed(&source, &name) {
1140            Ok(value) => convert::encode(&value),
1141            Err(engine::EvalError::Throw(value)) => {
1142                context.set_pending(value);
1143                jsvalue::EXCEPTION
1144            }
1145            Err(engine::EvalError::Syntax(text)) => {
1146                // A compile error has no object behind it, so the pending exception is a
1147                // `SyntaxError` built from the message — which is what the reference does too
1148                // (`JS_ThrowSyntaxError` from the compiler).
1149                let error = engine.interp_mut().make_error("SyntaxError", &text);
1150                context.set_pending(error);
1151                jsvalue::EXCEPTION
1152            }
1153            Err(engine::EvalError::OutOfMemory) => {
1154                let error = engine
1155                    .interp_mut()
1156                    .make_error("InternalError", "out of memory");
1157                context.set_pending(error);
1158                jsvalue::EXCEPTION
1159            }
1160        });
1161    }
1162
1163    // `JS_EvalThis`: the script path with the caller's receiver, which is what the
1164    // reference does — its `this_obj` reaches the same evaluation `JS_Eval` uses.
1165    context.with_context(|engine| {
1166        let interp = engine.interp_mut();
1167        match interp.eval_script_with_this(&source, &name, this.unwrap_or(Value::Undefined)) {
1168            Ok(value) => convert::encode(&value),
1169            Err(Signal::Throw(value)) => {
1170                context.set_pending(value);
1171                jsvalue::EXCEPTION
1172            }
1173            Err(Signal::OutOfMemory) => {
1174                let error = interp.make_error("InternalError", "out of memory");
1175                context.set_pending(error);
1176                jsvalue::EXCEPTION
1177            }
1178        }
1179    })
1180}
1181
1182/// `JS_EvalThis`'s entry point into the shared body.
1183///
1184/// # Safety
1185///
1186/// As [`JS_Eval`].
1187pub(crate) unsafe fn eval_with_this(
1188    context: &JsContext,
1189    input: *const core::ffi::c_char,
1190    input_len: usize,
1191    filename: *const core::ffi::c_char,
1192    eval_flags: core::ffi::c_int,
1193    this: Option<Value>,
1194) -> JsValue {
1195    // SAFETY: `context` came from a live `JSContext`; the rest is the caller's contract.
1196    unsafe {
1197        eval_with_this_raw(
1198            context as *const JsContext as *mut JsContext,
1199            input,
1200            input_len,
1201            filename,
1202            eval_flags,
1203            this,
1204        )
1205    }
1206}
1207
1208/// `JS_IsException` — exported for the rare caller that takes its address.
1209///
1210/// The header spells this one `static inline`, so no C object refers to it; it is here
1211/// because a Rust-side test and a future `--symbols` entry may want it.
1212#[unsafe(no_mangle)]
1213pub extern "C" fn JS_IsException(value: JsValue) -> c_int {
1214    c_int::from(value.is_exception())
1215}