use std::cell::RefCell;
use std::ffi::{CStr, CString, c_char, c_int, c_void};
use std::os::unix::ffi::OsStrExt;
use std::ptr::{self, NonNull};
use crate::{Context, Error, OpenFlags};
pub type DldotaCtx = Context;
thread_local! {
static LAST_ERROR: RefCell<Option<CString>> = const { RefCell::new(None) };
}
fn set_error(e: Error) {
let msg = CString::new(e.to_string().replace('\0', "?")).unwrap_or_default();
LAST_ERROR.with(|slot| *slot.borrow_mut() = Some(msg));
}
fn ok_or_null<T>(r: crate::Result<NonNull<T>>) -> *mut T {
r.map_or_else(
|e| {
set_error(e);
ptr::null_mut()
},
NonNull::as_ptr,
)
}
#[unsafe(no_mangle)]
pub unsafe extern "C" fn dldota_ctx_new(interpreter: *const c_char) -> *mut DldotaCtx {
let mut builder = Context::builder();
if !interpreter.is_null() {
let path = unsafe { CStr::from_ptr(interpreter) };
builder = builder.interpreter(std::ffi::OsStr::from_bytes(path.to_bytes()));
}
ok_or_null(
builder
.build()
.map(|ctx| NonNull::from(Box::leak(Box::new(ctx)))),
)
}
#[unsafe(no_mangle)]
pub unsafe extern "C" fn dldota_ctx_free(ctx: *mut DldotaCtx) {
if !ctx.is_null() {
drop(unsafe { Box::from_raw(ctx) });
}
}
#[unsafe(no_mangle)]
pub unsafe extern "C" fn dldota_open(
ctx: *mut DldotaCtx,
name: *const c_char,
flags: c_int,
) -> *mut c_void {
let (ctx, name) = unsafe { (&*ctx, (!name.is_null()).then(|| CStr::from_ptr(name))) };
ok_or_null(ctx.open_raw(name, OpenFlags(flags)))
}
#[unsafe(no_mangle)]
pub unsafe extern "C" fn dldota_sym(
ctx: *mut DldotaCtx,
handle: *mut c_void,
name: *const c_char,
) -> *mut c_void {
let Some(handle) = NonNull::new(handle) else {
set_error(Error::Dl("NULL handle".into()));
return ptr::null_mut();
};
let (ctx, name) = unsafe { (&*ctx, CStr::from_ptr(name)) };
ok_or_null(ctx.symbol_raw(handle, name))
}
#[unsafe(no_mangle)]
pub unsafe extern "C" fn dldota_close(ctx: *mut DldotaCtx, handle: *mut c_void) -> c_int {
let Some(handle) = NonNull::new(handle) else {
return -1;
};
match unsafe { &*ctx }.close_raw(handle) {
Ok(()) => 0,
Err(e) => {
set_error(e);
-1
}
}
}
#[unsafe(no_mangle)]
pub extern "C" fn dldota_error() -> *const c_char {
thread_local! {
static RETURNED: RefCell<Option<CString>> = const { RefCell::new(None) };
}
let msg = LAST_ERROR.with(|slot| slot.borrow_mut().take());
RETURNED.with(|ret| {
let mut ret = ret.borrow_mut();
*ret = msg;
ret.as_deref().map_or(ptr::null(), CStr::as_ptr)
})
}