use core::ffi::{CStr, c_char, c_int, c_void};
use engine::{Interp, Value};
use crate::cdefs::ModuleInitFunc;
use crate::cdefs::{self, JsModuleDef};
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_NewCModule(
ctx: *mut JsContext,
name_str: *const c_char,
func: ModuleInitFunc,
) -> *mut JsModuleDef {
let Some(context) = (unsafe { ctx.as_ref() }) else {
return std::ptr::null_mut();
};
if name_str.is_null() {
return std::ptr::null_mut();
}
let name = unsafe { CStr::from_ptr(name_str) }
.to_string_lossy()
.into_owned();
let definition = Box::new(JsModuleDef {
name,
declared: Vec::new(),
values: Vec::new(),
init: func,
private: None,
});
let raw = Box::into_raw(definition);
context.module_table().borrow_mut().push(raw);
raw
}
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_AddModuleExport(
_ctx: *mut JsContext,
m: *mut JsModuleDef,
export_name: *const c_char,
) -> c_int {
let Some(definition) = (unsafe { m.as_mut() }) else {
return -1;
};
if export_name.is_null() {
return -1;
}
let name = unsafe { CStr::from_ptr(export_name) }
.to_string_lossy()
.into_owned();
if !definition.declared.iter().any(|existing| existing == &name) {
definition.declared.push(name);
}
0
}
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_AddModuleExportList(
ctx: *mut JsContext,
m: *mut JsModuleDef,
tab: *const cdefs::JSCFunctionListEntry,
len: c_int,
) -> c_int {
if tab.is_null() || len < 0 {
return -1;
}
for index in 0..len as usize {
let entry = unsafe { &*tab.add(index) };
if unsafe { JS_AddModuleExport(ctx, m, entry.name) } != 0 {
return -1;
}
}
0
}
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_SetModuleExport(
_ctx: *mut JsContext,
m: *mut JsModuleDef,
export_name: *const c_char,
val: JsValue,
) -> c_int {
let Some(definition) = (unsafe { m.as_mut() }) else {
return -1;
};
if export_name.is_null() {
return -1;
}
let name = unsafe { CStr::from_ptr(export_name) }
.to_string_lossy()
.into_owned();
if !definition.declared.iter().any(|existing| existing == &name) {
unsafe { runtime::release(val) };
return -1;
}
let value = unsafe { runtime::argument(val) }.unwrap_or(Value::Undefined);
unsafe { runtime::release(val) };
if let Some(entry) = definition
.values
.iter_mut()
.find(|(existing, _)| existing == &name)
{
entry.1 = value;
} else {
definition.values.push((name, value));
}
0
}
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_SetModuleExportList(
ctx: *mut JsContext,
m: *mut JsModuleDef,
tab: *const cdefs::JSCFunctionListEntry,
len: c_int,
) -> c_int {
if tab.is_null() || len < 0 {
return -1;
}
for index in 0..len as usize {
let entry = unsafe { &*tab.add(index) };
let value = match entry_value(ctx, entry) {
Some(value) => value,
None => return -1,
};
if unsafe { JS_SetModuleExport(ctx, m, entry.name, value) } != 0 {
return -1;
}
}
0
}
fn entry_value(ctx: *mut JsContext, entry: &cdefs::JSCFunctionListEntry) -> Option<JsValue> {
match entry.def_type {
cdefs::JS_DEF_CFUNC => {
let func = unsafe { &entry.u.func };
Some(unsafe {
crate::objects::JS_NewCFunction2(
ctx,
func.cfunc.as_ptr(),
entry.name,
c_int::from(func.length),
c_int::from(func.cproto),
c_int::from(entry.magic),
)
})
}
cdefs::JS_DEF_PROP_STRING => {
let text = unsafe { entry.u.str_ };
if text.is_null() {
return Some(jsvalue::UNDEFINED);
}
let text = unsafe { CStr::from_ptr(text) }.to_string_lossy();
let context = unsafe { ctx.as_ref() }?;
Some(context.with_current_interp(|interp| jsvalue_of(interp.string(text.into_owned()))))
}
cdefs::JS_DEF_PROP_INT32 => {
Some(jsvalue::new_int32(unsafe { entry.u.i32 }))
}
cdefs::JS_DEF_PROP_DOUBLE => {
Some(jsvalue::new_float64(unsafe { entry.u.f64 }))
}
cdefs::JS_DEF_PROP_INT64 => {
let number = unsafe { entry.u.i64 };
Some(jsvalue::new_float64(number as f64))
}
cdefs::JS_DEF_PROP_UNDEFINED => Some(jsvalue::UNDEFINED),
cdefs::JS_DEF_PROP_BOOL => {
Some(jsvalue::new_bool(unsafe { entry.u.i32 } != 0))
}
_ => None,
}
}
pub unsafe fn instantiate(
context: &JsContext,
definition: &mut JsModuleDef,
) -> Result<Vec<(String, Value)>, String> {
if let Some(init) = definition.init {
let status = unsafe {
init(
context as *const JsContext as *mut JsContext,
definition as *mut JsModuleDef,
)
};
if status < 0 {
return Err(format!(
"could not load module filename '{}': initialization error",
definition.name
));
}
}
let mut exports = Vec::with_capacity(definition.declared.len());
for name in &definition.declared {
let value = definition
.values
.iter()
.find(|(existing, _)| existing == name)
.map(|(_, value)| value.clone())
.unwrap_or(Value::Undefined);
exports.push((name.clone(), value));
}
Ok(exports)
}
type InitModuleFunc = unsafe extern "C" fn(*mut JsContext, *const c_char) -> *mut JsModuleDef;
pub fn load_native_module(
interp: &mut Interp<'_>,
runtime: *mut JsRuntime,
module_name: &str,
) -> Result<Vec<(String, Value)>, String> {
let path = if module_name.contains('/') {
module_name.to_string()
} else {
format!("./{module_name}")
};
let handle = dlopen(&path).ok_or_else(|| {
format!("could not load module filename '{module_name}' as shared library")
})?;
let Some(init) = dlsym(handle, "js_init_module") else {
return Err(format!(
"could not load module filename '{module_name}': js_init_module not found"
));
};
let context = JsContext::attached(runtime);
let raw_interp: *mut Interp<'static> = unsafe {
std::mem::transmute::<&mut Interp<'_>, &mut Interp<'static>>(interp)
};
let guard = runtime::publish(raw_interp, &context);
let name = std::ffi::CString::new(module_name).unwrap_or_default();
let definition = unsafe {
init(
&context as *const JsContext as *mut JsContext,
name.as_ptr(),
)
};
let exports = if definition.is_null() {
Err(format!(
"could not load module filename '{module_name}': initialization error"
))
} else {
context
.module_table()
.borrow()
.iter()
.copied()
.find(|&candidate| candidate == definition)
.ok_or_else(|| {
format!("could not load module filename '{module_name}': unknown module definition")
})
.and_then(|owned| {
let definition = unsafe { &mut *owned };
unsafe { instantiate(&context, definition) }
})
};
drop(guard);
exports
}
pub unsafe fn exports_of(
context: &JsContext,
definition: *mut JsModuleDef,
) -> Result<Vec<(String, Value)>, String> {
let definition = unsafe { &mut *definition };
unsafe { instantiate(context, definition) }
}
struct Library(*mut c_void);
#[cfg(unix)]
fn dlopen(path: &str) -> Option<Library> {
let path = std::ffi::CString::new(path).ok()?;
let handle = unsafe { libc::dlopen(path.as_ptr(), libc::RTLD_NOW | libc::RTLD_LOCAL) };
if handle.is_null() {
None
} else {
Some(Library(handle))
}
}
#[cfg(unix)]
fn dlsym(handle: Library, symbol: &str) -> Option<InitModuleFunc> {
let symbol = std::ffi::CString::new(symbol).ok()?;
let pointer = unsafe { libc::dlsym(handle.0, symbol.as_ptr()) };
if pointer.is_null() {
return None;
}
Some(unsafe { std::mem::transmute::<*mut c_void, InitModuleFunc>(pointer) })
}
#[cfg(not(unix))]
fn dlopen(_path: &str) -> Option<Library> {
None
}
#[cfg(not(unix))]
fn dlsym(_handle: Library, _symbol: &str) -> Option<InitModuleFunc> {
None
}