use core::ffi::{c_char, c_int, c_void};
use engine::Value;
use crate::cdefs::{Bool, JSMemoryUsage, JSPrintValueOptions, PrintValueWrite};
use crate::conversions::arg;
use crate::jsvalue::{self, JsValue};
use crate::runtime::{self, JsContext, JsRuntime};
use crate::value_helpers::jsvalue_of;
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_SetMemoryLimit(rt: *mut JsRuntime, limit: usize) {
let Some(runtime) = (unsafe { rt.as_ref() }) else {
return;
};
let engine = unsafe { &mut *(runtime.engine_ptr() as *mut engine::Runtime) };
engine.set_memory_limit(if limit == usize::MAX {
None
} else {
Some(limit)
});
}
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_SetMaxStackSize(rt: *mut JsRuntime, stack_size: usize) {
let Some(runtime) = (unsafe { rt.as_ref() }) else {
return;
};
let engine = unsafe { &mut *(runtime.engine_ptr() as *mut engine::Runtime) };
let limit = if stack_size == 0 {
None
} else {
Some(stack_size)
};
engine.set_stack_size(limit);
if let Some(limit) = limit {
for context in runtime.live_contexts() {
if let Some(context) = unsafe { context.as_ref() } {
context.set_stack_limit(limit);
}
}
}
}
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_SetGCThreshold(rt: *mut JsRuntime, gc_threshold: usize) {
let Some(runtime) = (unsafe { rt.as_ref() }) else {
return;
};
runtime.set_gc_threshold(gc_threshold);
runtime.engine.heap().set_threshold(gc_threshold);
}
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_SetInterruptHandler(
rt: *mut JsRuntime,
cb: crate::cdefs::InterruptHandler,
opaque: *mut c_void,
) {
let Some(runtime) = (unsafe { rt.as_ref() }) else {
return;
};
runtime.set_interrupt_handler(cb, opaque);
for context in runtime.live_contexts() {
if let Some(context) = unsafe { context.as_ref() } {
context.install_interrupt_hook();
}
}
}
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_RunGC(rt: *mut JsRuntime) {
let Some(runtime) = (unsafe { rt.as_ref() }) else {
return;
};
runtime.engine.run_gc();
}
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_UpdateStackTop(_rt: *mut JsRuntime) {}
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_SetCanBlock(rt: *mut JsRuntime, can_block: Bool) {
let Some(runtime) = (unsafe { rt.as_ref() }) else {
return;
};
runtime.set_can_block(can_block != 0);
}
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_SetStripInfo(rt: *mut JsRuntime, flags: c_int) {
if let Some(runtime) = unsafe { rt.as_ref() } {
runtime.set_strip_info(flags);
}
}
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_GetStripInfo(rt: *mut JsRuntime) -> c_int {
match unsafe { rt.as_ref() } {
Some(runtime) => runtime.strip_info(),
None => 0,
}
}
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_SetRuntimeInfo(rt: *mut JsRuntime, info: *const c_char) {
if let Some(runtime) = unsafe { rt.as_ref() } {
runtime.set_info(info);
}
}
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_GetRuntimeOpaque(rt: *mut JsRuntime) -> *mut c_void {
match unsafe { rt.as_ref() } {
Some(runtime) => runtime.opaque(),
None => std::ptr::null_mut(),
}
}
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_SetRuntimeOpaque(rt: *mut JsRuntime, opaque: *mut c_void) {
if let Some(runtime) = unsafe { rt.as_ref() } {
runtime.set_opaque(opaque);
}
}
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_NewRuntime2(
_mf: *const crate::cdefs::JSMallocFunctions,
_opaque: *mut c_void,
) -> *mut JsRuntime {
Box::into_raw(JsRuntime::new())
}
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_DupContext(ctx: *mut JsContext) -> *mut JsContext {
if let Some(context) = unsafe { ctx.as_ref() } {
context.raise_refs();
}
ctx
}
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_GetContextOpaque(ctx: *mut JsContext) -> *mut c_void {
match unsafe { ctx.as_ref() } {
Some(context) => context.opaque(),
None => std::ptr::null_mut(),
}
}
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_SetContextOpaque(ctx: *mut JsContext, opaque: *mut c_void) {
if let Some(context) = unsafe { ctx.as_ref() } {
context.set_opaque(opaque);
}
}
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_SetContextValue(ctx: *mut JsContext, idx: c_int, val: JsValue) {
let Some(context) = (unsafe { ctx.as_ref() }) else {
unsafe { runtime::release(val) };
return;
};
let value = unsafe { arg(val) }.unwrap_or(Value::Undefined);
unsafe { runtime::release(val) };
context.set_value(idx, value);
}
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_GetContextValue(ctx: *mut JsContext, idx: c_int) -> JsValue {
let Some(context) = (unsafe { ctx.as_ref() }) else {
return jsvalue::EXCEPTION;
};
match context.value(idx) {
Some(value) => jsvalue_of(value),
None => jsvalue::UNDEFINED,
}
}
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_NewContextRaw(rt: *mut JsRuntime) -> *mut JsContext {
unsafe { crate::runtime::JS_NewContext(rt) }
}
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_ComputeMemoryUsage(rt: *mut JsRuntime, s: *mut JSMemoryUsage) {
if s.is_null() {
return;
}
let mut usage = JSMemoryUsage::default();
if let Some(runtime) = unsafe { rt.as_ref() } {
let heap = runtime.engine.heap();
let live = heap.live_count();
let bytes = heap.allocated_bytes();
usage.obj_count = i64::try_from(live).unwrap_or(i64::MAX);
usage.obj_size = i64::try_from(bytes).unwrap_or(i64::MAX);
usage.malloc_size = usage.obj_size;
usage.malloc_count = usage.obj_count;
if let Some(limit) = runtime.engine.memory_limit() {
usage.malloc_limit = i64::try_from(limit).unwrap_or(i64::MAX);
let used = runtime.engine.heap().allocated_bytes();
usage.memory_used_size = i64::try_from(limit.saturating_sub(used)).unwrap_or(0);
}
usage.atom_count = i64::try_from(runtime.atoms.borrow().len()).unwrap_or(i64::MAX);
}
unsafe { s.write(usage) };
}
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_DumpMemoryUsage(
fp: *mut c_void,
s: *const JSMemoryUsage,
_rt: *mut JsRuntime,
) {
if fp.is_null() || s.is_null() {
return;
}
let usage = unsafe { &*s };
let report = format!(
"objects: {}\nobject bytes: {}\natoms: {}\nmalloc limit: {}\n",
usage.obj_count, usage.obj_size, usage.atom_count, usage.malloc_limit
);
unsafe {
let write: unsafe extern "C" fn(*const c_void, usize, usize, *mut c_void) -> usize =
core::mem::transmute(libc::fwrite as unsafe extern "C" fn(_, _, _, _) -> _);
write(report.as_ptr().cast(), 1, report.len(), fp);
}
}
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_PrintValueSetDefaultOptions(options: *mut JSPrintValueOptions) {
if options.is_null() {
return;
}
unsafe {
options.write(JSPrintValueOptions {
show_hidden: 0,
raw_dump: 0,
max_depth: 2,
max_string_length: 1000,
max_item_count: 100,
});
}
}
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_PrintValue(
ctx: *mut JsContext,
write_func: PrintValueWrite,
write_opaque: *mut c_void,
val: JsValue,
options: *const JSPrintValueOptions,
) {
let Some(context) = (unsafe { ctx.as_ref() }) else {
return;
};
let Some(value) = (unsafe { arg(val) }) else {
return;
};
let limits = if options.is_null() {
engine::print::PrintLimits::default()
} else {
let options = unsafe { &*options };
engine::print::PrintLimits {
max_depth: if options.max_depth == 0 {
usize::MAX
} else {
options.max_depth as usize
},
max_string_length: if options.max_string_length == 0 {
usize::MAX
} else {
options.max_string_length as usize
},
max_item_count: if options.max_item_count == 0 {
usize::MAX
} else {
options.max_item_count as usize
},
}
};
let text = context.with_current_interp(|interp| {
match engine::print::sprint_limited(interp, &value, limits) {
Ok(text) => text,
Err(_) => format!("[{}]", value.type_of()),
}
});
emit(write_func, write_opaque, &text);
}
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_PrintValueRT(
rt: *mut JsRuntime,
write_func: PrintValueWrite,
write_opaque: *mut c_void,
val: JsValue,
options: *const JSPrintValueOptions,
) {
let Some(runtime) = (unsafe { rt.as_ref() }) else {
return;
};
let contexts = runtime.live_contexts();
if let Some(&context) = contexts.first() {
unsafe { JS_PrintValue(context, write_func, write_opaque, val, options) }
}
}
fn emit(write_func: PrintValueWrite, write_opaque: *mut c_void, text: &str) {
let Some(write_func) = write_func else {
return;
};
unsafe { write_func(write_opaque, text.as_ptr().cast(), text.len()) };
}
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_HasException(ctx: *mut JsContext) -> Bool {
match unsafe { ctx.as_ref() } {
Some(context) => c_int::from(context.has_pending()),
None => 0,
}
}
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_ThrowOutOfMemory(ctx: *mut JsContext) -> JsValue {
let Some(context) = (unsafe { ctx.as_ref() }) else {
return jsvalue::EXCEPTION;
};
let value = context.throw_out_of_memory();
context.set_pending(value);
jsvalue::EXCEPTION
}
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_ThrowSyntaxError(ctx: *mut JsContext, fmt: *const c_char) -> JsValue {
unsafe { throw_named(ctx, "SyntaxError", fmt) }
}
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_ThrowTypeError(ctx: *mut JsContext, fmt: *const c_char) -> JsValue {
unsafe { throw_named(ctx, "TypeError", fmt) }
}
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_ThrowReferenceError(
ctx: *mut JsContext,
fmt: *const c_char,
) -> JsValue {
unsafe { throw_named(ctx, "ReferenceError", fmt) }
}
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_ThrowInternalError(ctx: *mut JsContext, fmt: *const c_char) -> JsValue {
unsafe { throw_named(ctx, "InternalError", fmt) }
}
unsafe fn throw_named(ctx: *mut JsContext, name: &str, fmt: *const c_char) -> JsValue {
let Some(context) = (unsafe { ctx.as_ref() }) else {
return jsvalue::EXCEPTION;
};
let message = unsafe { crate::conversions::c_text(fmt) };
runtime::throw_error(context, name, &message)
}