use std::{
ffi::c_void,
sync::{Mutex, OnceLock},
};
use crate::{Backend, Error, Result, Runtime};
pub const THUNK_TYPE: &str = "HaoThunks.Thunks";
pub mod helper {
pub const FREE: usize = 0;
pub const STRING_LENGTH: usize = 1;
pub const STRING_COPY: usize = 2;
pub const TO_STRING: usize = 3;
pub const COUNT: usize = 4;
}
#[doc(hidden)]
#[macro_export]
macro_rules! __call_thunk {
($runtime:expr, $function:expr, ($($ty:ty = $value:expr),* $(,)?)) => {{
let function: *const ::core::ffi::c_void = $function;
match $runtime.backend() {
$crate::Backend::CoreClr => unsafe {
let f: extern "C" fn($($ty),*) = ::core::mem::transmute(function);
f($($value),*)
},
$crate::Backend::Mono => unsafe {
let f: extern "C" fn($($ty,)* *mut *mut ::core::ffi::c_void) = ::core::mem::transmute(function);
let mut exception = ::core::ptr::null_mut();
f($($value,)* &mut exception)
},
}
}};
}
#[cfg_attr(feature = "reflect", derive(facet::Facet))]
pub struct BoundAssembly {
pub assembly_name: &'static str,
pub assembly_path: &'static str,
pub thunks_name: &'static str,
pub coreclr_thunks: &'static [u8],
pub mono_thunks: &'static [u8],
pub function_count: usize,
coreclr: OnceLock<Vec<usize>>,
mono: OnceLock<Vec<usize>>,
init: Mutex<()>,
}
impl BoundAssembly {
pub const fn new(
assembly_name: &'static str,
assembly_path: &'static str,
thunks_name: &'static str,
coreclr_thunks: &'static [u8],
mono_thunks: &'static [u8],
function_count: usize,
) -> Self {
Self {
assembly_name,
assembly_path,
thunks_name,
coreclr_thunks,
mono_thunks,
function_count,
coreclr: OnceLock::new(),
mono: OnceLock::new(),
init: Mutex::new(()),
}
}
fn cache(&self, backend: Backend) -> &OnceLock<Vec<usize>> {
match backend {
Backend::CoreClr => &self.coreclr,
Backend::Mono => &self.mono,
}
}
pub fn load(&self, runtime: &Runtime) -> Result<()> {
let cache = self.cache(runtime.backend());
if cache.get().is_some() {
return Ok(());
}
let _guard = self.init.lock().unwrap_or_else(|e| e.into_inner());
if cache.get().is_some() {
return Ok(());
}
if !self.assembly_path.is_empty() {
runtime.load_assembly(self.assembly_path)?;
}
let thunks = match runtime.backend() {
Backend::CoreClr => self.coreclr_thunks,
Backend::Mono => self.mono_thunks,
};
runtime.load_assembly_bytes(self.thunks_name, thunks)?;
let functions = (0..self.function_count)
.map(|i| {
runtime
.function_pointer(self.thunks_name, THUNK_TYPE, &format!("f{}", i))
.map(|f| f as usize)
})
.collect::<Result<Vec<_>>>()?;
let _ = cache.set(functions);
Ok(())
}
pub fn function(&self, runtime: &Runtime, index: usize) -> Result<*const c_void> {
self.load(runtime)?;
runtime.attach_thread();
let functions = self.cache(runtime.backend()).get().expect("loaded above");
Ok(functions[index] as *const c_void)
}
fn call_helper_raw(
&self,
runtime: &Runtime,
index: usize,
handle: isize,
out: *mut c_void,
) -> Result<isize> {
let f = self.function(runtime, index)?;
let mut exception: isize = 0;
if index == helper::FREE {
__call_thunk!(runtime, f, (isize = handle, *mut isize = &mut exception));
} else {
__call_thunk!(runtime, f, (isize = handle, *mut c_void = out, *mut isize = &mut exception));
}
Ok(exception)
}
fn call_helper(
&self,
runtime: &Runtime,
index: usize,
handle: isize,
out: *mut c_void,
) -> Result<()> {
match self.call_helper_raw(runtime, index, handle, out)? {
0 => Ok(()),
exception => Err(self.take_exception(runtime, exception)),
}
}
fn describe_exception(&self, runtime: &Runtime, handle: isize) -> Result<String> {
let mut nested: Option<isize> = None;
let mut raw = |index, handle, out: *mut c_void| -> Result<bool> {
match self.call_helper_raw(runtime, index, handle, out)? {
0 => Ok(true),
exception => {
nested = Some(exception);
Ok(false)
}
}
};
let mut string: isize = 0;
let mut text = None;
if raw(
helper::TO_STRING,
handle,
(&mut string as *mut isize).cast(),
)? && string != 0
{
let mut length: i32 = 0;
if raw(
helper::STRING_LENGTH,
string,
(&mut length as *mut i32).cast(),
)? {
let mut buffer = vec![0u16; length.max(0) as usize];
if raw(helper::STRING_COPY, string, buffer.as_mut_ptr().cast())? {
text = Some(String::from_utf16_lossy(&buffer));
}
}
let _ = self.call_helper_raw(runtime, helper::FREE, string, std::ptr::null_mut());
}
if let Some(exception) = nested {
let _ = self.call_helper_raw(runtime, helper::FREE, exception, std::ptr::null_mut());
}
text.ok_or_else(|| Error::Other("reading the exception threw".into()))
}
pub fn free(&self, runtime: &Runtime, handle: isize) -> Result<()> {
self.call_helper(runtime, helper::FREE, handle, std::ptr::null_mut())
}
pub fn take_string(&self, runtime: &Runtime, handle: isize) -> Result<Option<String>> {
if handle == 0 {
return Ok(None);
}
let mut length: i32 = 0;
self.call_helper(
runtime,
helper::STRING_LENGTH,
handle,
(&mut length as *mut i32).cast(),
)?;
let mut buffer = vec![0u16; length.max(0) as usize];
self.call_helper(
runtime,
helper::STRING_COPY,
handle,
buffer.as_mut_ptr().cast(),
)?;
self.free(runtime, handle)?;
Ok(Some(String::from_utf16_lossy(&buffer)))
}
pub fn object_to_string(&self, runtime: &Runtime, handle: isize) -> Result<String> {
let mut string: isize = 0;
self.call_helper(
runtime,
helper::TO_STRING,
handle,
(&mut string as *mut isize).cast(),
)?;
Ok(self.take_string(runtime, string)?.unwrap_or_default())
}
pub fn take_exception(&self, runtime: &Runtime, handle: isize) -> Error {
let message = self
.describe_exception(runtime, handle)
.unwrap_or_else(|e| format!("<could not read exception: {}>", e));
let _ = self.call_helper_raw(runtime, helper::FREE, handle, std::ptr::null_mut());
Error::Managed(message)
}
}
pub struct Object {
handle: isize,
runtime: Runtime,
assembly: &'static BoundAssembly,
}
impl Object {
pub unsafe fn from_handle(
handle: isize,
runtime: Runtime,
assembly: &'static BoundAssembly,
) -> Self {
Self {
handle,
runtime,
assembly,
}
}
pub fn handle(&self) -> isize {
self.handle
}
pub fn runtime(&self) -> &Runtime {
&self.runtime
}
pub fn assembly(&self) -> &'static BoundAssembly {
self.assembly
}
pub fn to_managed_string(&self) -> Result<String> {
self.assembly.object_to_string(&self.runtime, self.handle)
}
}
impl std::fmt::Debug for Object {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "Object({:#x})", self.handle)
}
}
impl Drop for Object {
fn drop(&mut self) {
let _ = self.assembly.free(&self.runtime, self.handle);
}
}