use std::cell::{Cell, RefCell};
use std::rc::Rc;
use core::ffi::c_int;
use engine::Value;
use engine::interp::{Interp, JsResult, Signal};
use crate::alloc;
use crate::cdefs::{ClassFinalizer, ClassGCMark, ClassId, JSClassExoticMethods};
use crate::convert;
use crate::jsvalue::{self, JsValue};
pub struct JsRuntime {
pub(crate) engine: Box<engine::Runtime>,
opaque: Cell<*mut core::ffi::c_void>,
info: Cell<*const core::ffi::c_char>,
gc_threshold: Cell<usize>,
interrupt: Cell<
Option<(
unsafe extern "C" fn(*mut JsRuntime, *mut core::ffi::c_void) -> core::ffi::c_int,
*mut core::ffi::c_void,
)>,
>,
can_block: Cell<bool>,
strip_info: Cell<core::ffi::c_int>,
pub(crate) atoms: RefCell<crate::atoms::AtomTable>,
module_loader: RefCell<Option<ModuleLoaderHooks>>,
contexts: RefCell<Vec<*mut JsContext>>,
session_contexts: RefCell<Vec<*mut JsContext>>,
classes: RefCell<std::collections::BTreeMap<ClassId, Rc<ClassDecl>>>,
}
#[derive(Clone, Copy)]
pub struct ModuleLoaderHooks {
pub normalize: crate::cdefs::ModuleNormalizeFunc,
pub loader: crate::cdefs::ModuleLoaderFunc,
pub loader2: crate::cdefs::ModuleLoaderFunc2,
pub check_attrs: crate::cdefs::ModuleCheckAttrs,
pub opaque: *mut core::ffi::c_void,
}
static NEXT_CLASS_ID: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(1);
pub fn allocate_class_id() -> ClassId {
NEXT_CLASS_ID.fetch_add(1, std::sync::atomic::Ordering::SeqCst)
}
#[derive(Clone, Copy)]
pub struct ClassDecl {
pub finalizer: ClassFinalizer,
pub gc_mark: ClassGCMark,
pub exotic: *const JSClassExoticMethods,
pub name: *const core::ffi::c_char,
}
pub struct JsContext {
source: ContextSource,
pending: RefCell<Option<Value>>,
runtime: Cell<*mut JsRuntime>,
modules: RefCell<Vec<*mut crate::cdefs::JsModuleDef>>,
opaque: Cell<*mut core::ffi::c_void>,
values: RefCell<std::collections::BTreeMap<core::ffi::c_int, Value>>,
dups: Cell<usize>,
}
pub enum ContextSource {
Owned(RefCell<Box<engine::Context<'static>>>),
Attached,
}
thread_local! {
static CURRENT_INTERP: Cell<*mut Interp<'static>> = const { Cell::new(std::ptr::null_mut()) };
static CURRENT_CONTEXT: Cell<*mut JsContext> = const { Cell::new(std::ptr::null_mut()) };
static FINALIZING: Cell<Option<(*mut JsRuntime, ClassId, *mut ())>> = const { Cell::new(None) };
}
pub const FINALIZER_SENTINEL: *mut () = std::ptr::dangling_mut::<()>();
impl JsRuntime {
pub fn new() -> Box<JsRuntime> {
Box::new(JsRuntime {
engine: Box::new(engine::Runtime::new()),
opaque: Cell::new(std::ptr::null_mut()),
info: Cell::new(std::ptr::null()),
gc_threshold: Cell::new(0),
interrupt: Cell::new(None),
can_block: Cell::new(true),
strip_info: Cell::new(0),
atoms: RefCell::new(crate::atoms::AtomTable::new()),
module_loader: RefCell::new(None),
contexts: RefCell::new(Vec::new()),
session_contexts: RefCell::new(Vec::new()),
classes: RefCell::new(std::collections::BTreeMap::new()),
})
}
pub fn opaque(&self) -> *mut core::ffi::c_void {
self.opaque.get()
}
pub fn set_opaque(&self, opaque: *mut core::ffi::c_void) {
self.opaque.set(opaque);
}
pub fn info(&self) -> *const core::ffi::c_char {
self.info.get()
}
pub fn set_info(&self, info: *const core::ffi::c_char) {
self.info.set(info);
}
pub fn set_gc_threshold(&self, threshold: usize) {
self.gc_threshold.set(threshold);
}
pub fn gc_threshold(&self) -> usize {
self.gc_threshold.get()
}
pub fn set_interrupt_handler(
&self,
callback: crate::cdefs::InterruptHandler,
opaque: *mut core::ffi::c_void,
) {
self.interrupt
.set(callback.map(|callback| (callback, opaque)));
}
pub fn interrupt_handler(
&self,
) -> Option<(
unsafe extern "C" fn(*mut JsRuntime, *mut core::ffi::c_void) -> core::ffi::c_int,
*mut core::ffi::c_void,
)> {
self.interrupt.get()
}
pub fn set_can_block(&self, can_block: bool) {
self.can_block.set(can_block);
}
pub fn can_block(&self) -> bool {
self.can_block.get()
}
pub fn module_loader_hooks(&self) -> Option<ModuleLoaderHooks> {
*self.module_loader.borrow()
}
pub fn set_module_loader_hooks(&self, hooks: ModuleLoaderHooks) {
*self.module_loader.borrow_mut() = Some(hooks);
}
pub fn live_contexts(&self) -> Vec<*mut JsContext> {
self.contexts.borrow().clone()
}
pub fn engine_ptr(&self) -> *const engine::Runtime {
self.engine.as_ref() as *const engine::Runtime
}
pub fn strip_info(&self) -> core::ffi::c_int {
self.strip_info.get()
}
pub fn set_strip_info(&self, flags: core::ffi::c_int) {
self.strip_info.set(flags);
}
fn engine_ref(&self) -> &'static engine::Runtime {
unsafe { &*(self.engine.as_ref() as *const engine::Runtime) }
}
pub fn define_class(&self, id: ClassId, decl: ClassDecl) -> bool {
if id == 0 {
return false;
}
self.classes.borrow_mut().insert(id, Rc::new(decl));
for &context in self.contexts.borrow().iter() {
unsafe { (*context).register_class(id, decl) };
}
true
}
pub fn class(&self, id: ClassId) -> Option<Rc<ClassDecl>> {
self.classes.borrow().get(&id).cloned()
}
pub fn has_class(&self, id: ClassId) -> bool {
self.class(id).is_some()
}
fn adopt(&self, context: *mut JsContext) {
self.contexts.borrow_mut().push(context);
}
pub unsafe fn adopt_for_session(&self, context: *mut JsContext) {
self.session_contexts.borrow_mut().push(context);
self.adopt(context);
}
pub unsafe fn disown(&self, context: *mut JsContext) {
self.contexts.borrow_mut().retain(|&live| live != context);
self.session_contexts
.borrow_mut()
.retain(|&live| live != context);
}
pub unsafe fn free(runtime: *mut JsRuntime) {
if runtime.is_null() {
return;
}
let runtime = unsafe { Box::from_raw(runtime) };
let contexts: Vec<*mut JsContext> = runtime.contexts.borrow_mut().drain(..).collect();
let borrowed: Vec<*mut JsContext> =
runtime.session_contexts.borrow_mut().drain(..).collect();
for context in contexts {
if borrowed.contains(&context) {
continue;
}
drop(unsafe { Box::from_raw(context) });
}
}
}
impl JsContext {
pub fn raise_refs(&self) {
self.dups.set(self.dups.get().saturating_add(1));
}
fn release_ref(&self) -> bool {
let count = self.dups.get();
if count == 0 {
return true;
}
self.dups.set(count - 1);
false
}
pub unsafe fn new(runtime: *mut JsRuntime) -> *mut JsContext {
let runtime_ref = unsafe { &*runtime };
let engine = engine::Context::new(runtime_ref.engine_ref());
let context = Box::new(JsContext {
source: ContextSource::Owned(RefCell::new(Box::new(engine))),
pending: RefCell::new(None),
runtime: Cell::new(runtime),
modules: RefCell::new(Vec::new()),
opaque: Cell::new(std::ptr::null_mut()),
values: RefCell::new(std::collections::BTreeMap::new()),
dups: Cell::new(0),
});
let classes: Vec<(ClassId, ClassDecl)> = runtime_ref
.classes
.borrow()
.iter()
.map(|(&id, decl)| (id, **decl))
.collect();
let context = context;
for (id, decl) in classes {
context.register_class(id, decl);
}
let raw = Box::into_raw(context);
runtime_ref.adopt(raw);
raw
}
pub fn attached(runtime: *mut JsRuntime) -> JsContext {
JsContext {
source: ContextSource::Attached,
pending: RefCell::new(None),
runtime: Cell::new(runtime),
modules: RefCell::new(Vec::new()),
opaque: Cell::new(std::ptr::null_mut()),
values: RefCell::new(std::collections::BTreeMap::new()),
dups: Cell::new(0),
}
}
pub fn opaque(&self) -> *mut core::ffi::c_void {
self.opaque.get()
}
pub fn set_opaque(&self, opaque: *mut core::ffi::c_void) {
self.opaque.set(opaque);
}
pub fn value(&self, idx: core::ffi::c_int) -> Option<Value> {
self.values.borrow().get(&idx).cloned()
}
pub fn set_value(&self, idx: core::ffi::c_int, value: Value) {
self.values.borrow_mut().insert(idx, value);
}
pub fn runtime(&self) -> *mut JsRuntime {
self.runtime.get()
}
fn register_class(&self, id: ClassId, decl: ClassDecl) {
let definition = self.class_definition(id, decl);
self.with_current_interp(|interp| {
interp.define_host_class(engine::ClassId::from_raw(id), definition);
});
}
fn class_definition(&self, id: ClassId, decl: ClassDecl) -> engine::ClassDef {
let name = if decl.name.is_null() {
format!("<class {id}>")
} else {
unsafe { core::ffi::CStr::from_ptr(decl.name) }
.to_string_lossy()
.into_owned()
};
let mut definition = engine::ClassDef::new(name);
if let Some(finalizer) = decl.finalizer {
let runtime = self.runtime.get();
definition = definition.with_finalizer(Box::new(move |_class_id, opaque| {
call_finalizer(runtime, id, finalizer, opaque);
}));
}
let _ = decl.gc_mark;
let _ = decl.exotic;
definition
}
pub fn with_current_interp<R>(&self, f: impl FnOnce(&mut Interp<'static>) -> R) -> R {
match current_interp() {
Some(interp) => f(interp),
None => self.with_interp(f),
}
}
pub fn with_context<R>(&self, f: impl FnOnce(&mut engine::Context<'static>) -> R) -> R {
let ContextSource::Owned(engine) = &self.source else {
panic!("an attached context has no engine of its own");
};
let mut engine = engine.borrow_mut();
let engine: &mut engine::Context<'static> = &mut engine;
self.sync_interrupt_hook(engine.interp_mut());
let interp: *mut Interp<'static> = engine.interp_mut();
let guard = InterpGuard::enter(interp, self);
let result = f(engine);
drop(guard);
result
}
pub fn set_stack_limit(&self, limit: usize) {
if matches!(self.source, ContextSource::Attached) {
return;
}
self.with_context(|engine| {
engine.interp_mut().stack_limit = limit;
});
}
pub fn install_interrupt_hook(&self) {
let runtime = self.runtime.get();
if unsafe { runtime.as_ref() }.is_none() {
return;
}
if matches!(self.source, ContextSource::Attached) {
return;
}
self.with_context(|engine| {
let _ = engine;
});
}
fn runtime_interrupt_is_unset(&self) -> bool {
match unsafe { self.runtime.get().as_ref() } {
Some(runtime) => runtime.interrupt_handler().is_none(),
None => true,
}
}
pub(crate) fn sync_interrupt_hook(&self, interp: &mut Interp<'static>) {
if interp.interrupt.is_some() || self.runtime_interrupt_is_unset() {
return;
}
let runtime: *const JsRuntime = self.runtime.get();
interp.interrupt = Some(Box::new(move || {
let Some(runtime) = (unsafe { runtime.as_ref() }) else {
return false;
};
match runtime.interrupt_handler() {
Some((callback, opaque)) => {
unsafe { callback(runtime as *const _ as *mut _, opaque) != 0 }
}
None => false,
}
}));
}
pub fn with_interp<R>(&self, f: impl FnOnce(&mut Interp<'static>) -> R) -> R {
self.with_context(|engine| f(engine.interp_mut()))
}
pub fn take_pending(&self) -> Option<Value> {
self.pending.borrow_mut().take()
}
pub fn set_pending(&self, value: Value) {
*self.pending.borrow_mut() = Some(value);
}
pub fn has_pending(&self) -> bool {
self.pending.borrow().is_some()
}
}
pub struct InterpGuard {
previous_interp: *mut Interp<'static>,
previous_context: *mut JsContext,
}
impl InterpGuard {
fn enter(interp: *mut Interp<'static>, context: &JsContext) -> InterpGuard {
let pointer = context as *const JsContext as *mut JsContext;
let previous_interp = CURRENT_INTERP.with(|cell| cell.replace(interp));
let previous_context = CURRENT_CONTEXT.with(|cell| cell.replace(pointer));
InterpGuard {
previous_interp,
previous_context,
}
}
}
impl Drop for InterpGuard {
fn drop(&mut self) {
CURRENT_INTERP.with(|cell| cell.set(self.previous_interp));
CURRENT_CONTEXT.with(|cell| cell.set(self.previous_context));
}
}
pub fn publish(interp: *mut Interp<'static>, context: &JsContext) -> InterpGuard {
InterpGuard::enter(interp, context)
}
pub fn current_interp() -> Option<&'static mut Interp<'static>> {
CURRENT_INTERP.with(|cell| {
let pointer = cell.get();
if pointer.is_null() {
None
} else {
Some(unsafe { &mut *pointer })
}
})
}
pub fn current_context() -> Option<&'static JsContext> {
CURRENT_CONTEXT.with(|cell| {
let pointer = cell.get();
if pointer.is_null() {
None
} else {
Some(unsafe { &*pointer })
}
})
}
fn call_finalizer(
runtime: *mut JsRuntime,
class_id: ClassId,
finalizer: unsafe extern "C" fn(*mut core::ffi::c_void, JsValue),
opaque: engine::Opaque,
) {
let sentinel = JsValue::mkptr(jsvalue::TAG_OBJECT, FINALIZER_SENTINEL);
let previous = FINALIZING.with(|cell| cell.replace(Some((runtime, class_id, opaque.as_ptr()))));
unsafe { finalizer(runtime.cast(), sentinel) };
FINALIZING.with(|cell| cell.set(previous));
}
pub fn finalizer_opaque(class_id: ClassId) -> Option<*mut ()> {
FINALIZING.with(|cell| match cell.get() {
Some((_, id, opaque)) if id == class_id => Some(opaque),
_ => None,
})
}
pub fn finalizer_runtime() -> Option<*mut JsRuntime> {
FINALIZING.with(|cell| cell.get().map(|(runtime, _, _)| runtime))
}
pub fn is_finalizer_sentinel(value: JsValue) -> bool {
value.payload() == FINALIZER_SENTINEL as usize as u64 && value.is_object()
}
pub fn result_value(context: &JsContext, result: JsResult<Value>) -> JsValue {
match result {
Ok(value) => convert::encode(&value),
Err(signal) => {
let thrown = match signal {
Signal::Throw(value) => value,
Signal::OutOfMemory => context.throw_out_of_memory(),
};
context.set_pending(thrown);
jsvalue::EXCEPTION
}
}
}
impl JsContext {
fn free_modules(&self) {
for pointer in self.modules.borrow_mut().drain(..) {
drop(unsafe { Box::from_raw(pointer) });
}
}
pub fn module_table(&self) -> &RefCell<Vec<*mut crate::cdefs::JsModuleDef>> {
&self.modules
}
pub fn throw_out_of_memory(&self) -> Value {
self.with_current_interp(|interp| interp.make_error("InternalError", "out of memory"))
}
}
pub fn throw_error(context: &JsContext, name: &str, message: &str) -> JsValue {
let value = context.with_current_interp(|interp| interp.make_error(name, message));
context.set_pending(value);
jsvalue::EXCEPTION
}
pub unsafe fn argument(value: JsValue) -> Option<Value> {
unsafe { convert::decode(value) }
}
pub unsafe fn release(value: JsValue) {
if !value.has_ref_count() {
return;
}
if is_finalizer_sentinel(value) {
return;
}
let Some(payload) = value.as_ptr() else {
return;
};
let count = unsafe { alloc::ValueBox::ref_count(payload) } - 1;
unsafe { alloc::ValueBox::set_ref_count(payload, count) };
if count <= 0 {
unsafe { alloc::free_value(payload) };
}
}
#[unsafe(no_mangle)]
pub extern "C" fn JS_NewRuntime() -> *mut JsRuntime {
Box::into_raw(JsRuntime::new())
}
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_FreeRuntime(rt: *mut JsRuntime) {
unsafe { JsRuntime::free(rt) }
}
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_NewContext(rt: *mut JsRuntime) -> *mut JsContext {
if rt.is_null() {
return std::ptr::null_mut();
}
unsafe { JsContext::new(rt) }
}
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_FreeContext(ctx: *mut JsContext) {
if ctx.is_null() {
return;
}
if let Some(context) = unsafe { ctx.as_ref() } {
if !context.release_ref() {
return;
}
}
let context = unsafe { Box::from_raw(ctx) };
context.free_modules();
if let Some(runtime) = unsafe { context.runtime().as_ref() } {
unsafe { runtime.disown(ctx) };
}
}
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_GetException(ctx: *mut JsContext) -> JsValue {
let Some(context) = (unsafe { ctx.as_ref() }) else {
return jsvalue::NULL;
};
match context.take_pending() {
Some(value) => convert::encode(&value),
None => jsvalue::NULL,
}
}
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_Throw(ctx: *mut JsContext, obj: JsValue) -> JsValue {
let Some(context) = (unsafe { ctx.as_ref() }) else {
return jsvalue::EXCEPTION;
};
let value = unsafe { argument(obj) }.unwrap_or(Value::Undefined);
unsafe { release(obj) };
context.set_pending(value);
jsvalue::EXCEPTION
}
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_Eval(
ctx: *mut JsContext,
input: *const core::ffi::c_char,
input_len: usize,
filename: *const core::ffi::c_char,
eval_flags: core::ffi::c_int,
) -> JsValue {
unsafe { eval_with_this_raw(ctx, input, input_len, filename, eval_flags, None) }
}
pub(crate) unsafe fn eval_with_this_raw(
ctx: *mut JsContext,
input: *const core::ffi::c_char,
input_len: usize,
filename: *const core::ffi::c_char,
eval_flags: core::ffi::c_int,
this: Option<Value>,
) -> JsValue {
let Some(context) = (unsafe { ctx.as_ref() }) else {
return jsvalue::EXCEPTION;
};
if input.is_null() {
return throw_error(context, "TypeError", "null source");
}
let bytes = unsafe { core::slice::from_raw_parts(input.cast::<u8>(), input_len) };
let source = String::from_utf8_lossy(bytes).into_owned();
let name = if filename.is_null() {
"<input>".to_string()
} else {
unsafe { core::ffi::CStr::from_ptr(filename) }
.to_string_lossy()
.into_owned()
};
const JS_EVAL_TYPE_MODULE: core::ffi::c_int = 1 << 0;
if eval_flags & JS_EVAL_TYPE_MODULE != 0 {
return throw_error(
context,
"TypeError",
"module evaluation arrives with native module loading (M15 S4)",
);
}
if let Some(interp) = current_interp() {
let outcome = match this {
Some(this) => interp.eval_script_with_this(&source, &name, this),
None => interp.eval_in_global_named(&source, &name, false),
};
return match outcome {
Ok(value) => convert::encode(&value),
Err(Signal::Throw(value)) => {
context.set_pending(value);
jsvalue::EXCEPTION
}
Err(Signal::OutOfMemory) => {
let error = interp.make_error("InternalError", "out of memory");
context.set_pending(error);
jsvalue::EXCEPTION
}
};
}
if this.is_none() {
return context.with_context(|engine| match engine.eval_detailed(&source, &name) {
Ok(value) => convert::encode(&value),
Err(engine::EvalError::Throw(value)) => {
context.set_pending(value);
jsvalue::EXCEPTION
}
Err(engine::EvalError::Syntax(text)) => {
let error = engine.interp_mut().make_error("SyntaxError", &text);
context.set_pending(error);
jsvalue::EXCEPTION
}
Err(engine::EvalError::OutOfMemory) => {
let error = engine
.interp_mut()
.make_error("InternalError", "out of memory");
context.set_pending(error);
jsvalue::EXCEPTION
}
});
}
context.with_context(|engine| {
let interp = engine.interp_mut();
match interp.eval_script_with_this(&source, &name, this.unwrap_or(Value::Undefined)) {
Ok(value) => convert::encode(&value),
Err(Signal::Throw(value)) => {
context.set_pending(value);
jsvalue::EXCEPTION
}
Err(Signal::OutOfMemory) => {
let error = interp.make_error("InternalError", "out of memory");
context.set_pending(error);
jsvalue::EXCEPTION
}
}
})
}
pub(crate) unsafe fn eval_with_this(
context: &JsContext,
input: *const core::ffi::c_char,
input_len: usize,
filename: *const core::ffi::c_char,
eval_flags: core::ffi::c_int,
this: Option<Value>,
) -> JsValue {
unsafe {
eval_with_this_raw(
context as *const JsContext as *mut JsContext,
input,
input_len,
filename,
eval_flags,
this,
)
}
}
#[unsafe(no_mangle)]
pub extern "C" fn JS_IsException(value: JsValue) -> c_int {
c_int::from(value.is_exception())
}