hao-runtime 0.0.16

Host the .net runtime (CoreCLR or Mono) in a rust process
Documentation
//! Support code for bindings generated by `hao-runtime-macros`.
//!
//! The generated thunk assembly has a static type [`THUNK_TYPE`] with methods
//! `f0`, `f1`, ... The first [`helper::COUNT`] are the helpers below, the rest
//! wrap the bound methods. Every thunk returns `void`, takes its arguments
//! followed by an optional pointer to the return value and a pointer that
//! receives a `GCHandle` to any exception thrown. Objects are passed as
//! `GCHandle`s.
//!
//! None of this is called by hand: `bind!` generates a [`BoundAssembly`] and a
//! struct per class wrapping an [`Object`], which looks like this to use:
//!
//! ```ignore
//! // Needs the `hao-runtime-macros` crate, which isn't a dependency of this
//! // one, and a built `dotnet/MyLib.dll` next to the calling crate.
//! mod my_lib {
//!     hao_runtime_macros::bind! {
//!         assembly = "dotnet/MyLib.dll",
//!     }
//! }
//!
//! let runtime = hao_runtime::Runtime::coreclr()?;
//! let calculator = my_lib::my_lib::Calculator::new(&runtime, 10)?;
//! assert_eq!(calculator.add(5)?, 15);
//! // The wrapped `Object` gives the managed `ToString()`.
//! println!("{}", calculator.object().to_managed_string()?);
//! ```

use std::{
    ffi::c_void,
    sync::{Mutex, OnceLock},
};

use crate::{Backend, Error, Result, Runtime};

/// The full name of the static type holding the thunks in every generated
/// thunk assembly.
pub const THUNK_TYPE: &str = "HaoThunks.Thunks";

/// Indexes of the helper thunks every generated thunk assembly starts with.
pub mod helper {
    /// `free(handle)`
    pub const FREE: usize = 0;
    /// `string_length(handle) -> i32`
    pub const STRING_LENGTH: usize = 1;
    /// `string_copy(handle, *mut u16)`
    pub const STRING_COPY: usize = 2;
    /// `to_string(handle) -> handle`
    pub const TO_STRING: usize = 3;
    /// How many helpers there are; bound methods' thunks start at this index.
    pub const COUNT: usize = 4;
}

/// Calls a thunk pointer with the calling convention of the runtime's backend.
#[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)
            },
        }
    }};
}

/// A .NET assembly bound with `hao_runtime_macros::bind!`.
#[cfg_attr(feature = "reflect", derive(facet::Facet))]
pub struct BoundAssembly {
    /// The bound assembly's name, e.g. `MyLib`.
    pub assembly_name: &'static str,
    /// Where the bound assembly is loaded from; empty when the runtime already
    /// has it (a framework assembly).
    pub assembly_path: &'static str,
    /// The generated thunk assembly's name.
    pub thunks_name: &'static str,
    /// The thunk assembly for CoreCLR, whose thunks are `[UnmanagedCallersOnly]`.
    pub coreclr_thunks: &'static [u8],
    /// The thunk assembly for Mono.
    pub mono_thunks: &'static [u8],
    /// How many thunks there are, the [`helper`]s included.
    pub function_count: usize,
    coreclr: OnceLock<Vec<usize>>,
    mono: OnceLock<Vec<usize>>,
    init: Mutex<()>,
}

impl BoundAssembly {
    /// Describes a bound assembly; `bind!` generates this call, so there is
    /// usually no need to write it.
    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,
        }
    }

    /// Loads the bound assembly and its thunks into `runtime`. Called on first use.
    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(())
    }

    /// A native pointer to thunk `f{index}`, loading the assembly and
    /// attaching the calling thread first. Call it with [`Runtime::backend`]'s
    /// calling convention.
    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)
    }

    /// Calls helper `index` on `handle`, returning a handle to the exception it
    /// threw (`0` if none) without interpreting it.
    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)),
        }
    }

    /// The exception's `ToString()` (type name, message and stack trace).
    /// Uses the raw helpers so an exception thrown while reading it can't
    /// recurse; it frees any such exception but not `handle`.
    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()))
    }

    /// Frees a `GCHandle` a thunk returned, letting the object be collected.
    pub fn free(&self, runtime: &Runtime, handle: isize) -> Result<()> {
        self.call_helper(runtime, helper::FREE, handle, std::ptr::null_mut())
    }

    /// Reads and frees a handle to a `System.String`. `0` is `null`.
    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)))
    }

    /// `ToString()` of the object behind `handle`, without freeing it.
    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())
    }

    /// Turns a handle to a thrown exception into an [`Error::Managed`], freeing it.
    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)
    }
}

/// An owned reference to a managed object.
pub struct Object {
    handle: isize,
    runtime: Runtime,
    assembly: &'static BoundAssembly,
}

impl Object {
    /// Takes ownership of a `GCHandle` returned by a thunk.
    ///
    /// # Safety
    /// `handle` must be a live `GCHandle` that nothing else will free.
    pub unsafe fn from_handle(
        handle: isize,
        runtime: Runtime,
        assembly: &'static BoundAssembly,
    ) -> Self {
        Self {
            handle,
            runtime,
            assembly,
        }
    }

    /// The `GCHandle` to pass to thunks for this object; still owned by `self`.
    pub fn handle(&self) -> isize {
        self.handle
    }

    /// The runtime the object lives in.
    pub fn runtime(&self) -> &Runtime {
        &self.runtime
    }

    /// The bound assembly whose thunks handle this object.
    pub fn assembly(&self) -> &'static BoundAssembly {
        self.assembly
    }

    /// The object's `ToString()`.
    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);
    }
}