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 (measured, _) = engine::memory::compute(runtime.engine.heap());
usage.malloc_count = measured.malloc_count;
usage.malloc_size = measured.malloc_size;
usage.memory_used_count = measured.memory_used_count;
usage.memory_used_size = measured.memory_used_size;
usage.malloc_limit = measured.malloc_limit;
usage.str_count = measured.str_count;
usage.str_size = measured.str_size;
usage.obj_count = measured.obj_count;
usage.obj_size = measured.obj_size;
usage.prop_count = measured.prop_count;
usage.prop_size = measured.prop_size;
usage.shape_count = measured.shape_count;
usage.shape_size = measured.shape_size;
usage.js_func_count = measured.js_func_count;
usage.js_func_size = measured.js_func_size;
usage.js_func_code_size = measured.js_func_code_size;
usage.js_func_pc2line_count = measured.js_func_pc2line_count;
usage.js_func_pc2line_size = measured.js_func_pc2line_size;
usage.c_func_count = measured.c_func_count;
usage.array_count = measured.array_count;
usage.fast_array_count = measured.fast_array_count;
usage.fast_array_elements = measured.fast_array_elements;
usage.binary_object_count = measured.binary_object_count;
usage.binary_object_size = measured.binary_object_size;
let atoms = runtime.atoms.borrow();
usage.atom_count = i64::try_from(atoms.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 census = match unsafe { rt.as_ref() } {
Some(runtime) => engine::memory::compute(runtime.engine.heap()).1,
None => engine::memory::ClassCensus::default(),
};
let report = engine::memory::dump(&memory_usage_of(usage), &census);
unsafe { fwrite(report.as_ptr().cast(), 1, report.len(), fp) };
}
unsafe extern "C" {
fn fwrite(ptr: *const c_void, size: usize, count: usize, stream: *mut c_void) -> usize;
}
fn memory_usage_of(usage: &JSMemoryUsage) -> engine::memory::MemoryUsage {
engine::memory::MemoryUsage {
malloc_count: usage.malloc_count,
malloc_size: usage.malloc_size,
memory_used_count: usage.memory_used_count,
memory_used_size: usage.memory_used_size,
malloc_limit: usage.malloc_limit,
str_count: usage.str_count,
str_size: usage.str_size,
obj_count: usage.obj_count,
obj_size: usage.obj_size,
prop_count: usage.prop_count,
prop_size: usage.prop_size,
shape_count: usage.shape_count,
shape_size: usage.shape_size,
js_func_count: usage.js_func_count,
js_func_size: usage.js_func_size,
js_func_code_size: usage.js_func_code_size,
js_func_pc2line_count: usage.js_func_pc2line_count,
js_func_pc2line_size: usage.js_func_pc2line_size,
c_func_count: usage.c_func_count,
array_count: usage.array_count,
fast_array_count: usage.fast_array_count,
fast_array_elements: usage.fast_array_elements,
binary_object_count: usage.binary_object_count,
binary_object_size: usage.binary_object_size,
}
}
#[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)
}