Skip to main content

hao_runtime/
bindings.rs

1//! Support code for bindings generated by `hao-runtime-macros`.
2//!
3//! The generated thunk assembly has a static type [`THUNK_TYPE`] with methods
4//! `f0`, `f1`, ... The first [`helper::COUNT`] are the helpers below, the rest
5//! wrap the bound methods. Every thunk returns `void`, takes its arguments
6//! followed by an optional pointer to the return value and a pointer that
7//! receives a `GCHandle` to any exception thrown. Objects are passed as
8//! `GCHandle`s.
9
10use std::{
11    ffi::c_void,
12    sync::{Mutex, OnceLock},
13};
14
15use crate::{Backend, Error, Result, Runtime};
16
17pub const THUNK_TYPE: &str = "HaoThunks.Thunks";
18
19pub mod helper {
20    /// `free(handle)`
21    pub const FREE: usize = 0;
22    /// `string_length(handle) -> i32`
23    pub const STRING_LENGTH: usize = 1;
24    /// `string_copy(handle, *mut u16)`
25    pub const STRING_COPY: usize = 2;
26    /// `to_string(handle) -> handle`
27    pub const TO_STRING: usize = 3;
28    pub const COUNT: usize = 4;
29}
30
31/// Calls a thunk pointer with the calling convention of the runtime's backend.
32#[doc(hidden)]
33#[macro_export]
34macro_rules! __call_thunk {
35    ($runtime:expr, $function:expr, ($($ty:ty = $value:expr),* $(,)?)) => {{
36        let function: *const ::core::ffi::c_void = $function;
37        match $runtime.backend() {
38            $crate::Backend::CoreClr => unsafe {
39                let f: extern "C" fn($($ty),*) = ::core::mem::transmute(function);
40                f($($value),*)
41            },
42            $crate::Backend::Mono => unsafe {
43                let f: extern "C" fn($($ty,)* *mut *mut ::core::ffi::c_void) = ::core::mem::transmute(function);
44                let mut exception = ::core::ptr::null_mut();
45                f($($value,)* &mut exception)
46            },
47        }
48    }};
49}
50
51/// A .NET assembly bound with `hao_runtime_macros::bind!`.
52#[cfg_attr(feature = "reflect", derive(facet::Facet))]
53pub struct BoundAssembly {
54    pub assembly_name: &'static str,
55    pub assembly_path: &'static str,
56    pub thunks_name: &'static str,
57    pub coreclr_thunks: &'static [u8],
58    pub mono_thunks: &'static [u8],
59    pub function_count: usize,
60    coreclr: OnceLock<Vec<usize>>,
61    mono: OnceLock<Vec<usize>>,
62    init: Mutex<()>,
63}
64
65impl BoundAssembly {
66    pub const fn new(
67        assembly_name: &'static str,
68        assembly_path: &'static str,
69        thunks_name: &'static str,
70        coreclr_thunks: &'static [u8],
71        mono_thunks: &'static [u8],
72        function_count: usize,
73    ) -> Self {
74        Self {
75            assembly_name,
76            assembly_path,
77            thunks_name,
78            coreclr_thunks,
79            mono_thunks,
80            function_count,
81            coreclr: OnceLock::new(),
82            mono: OnceLock::new(),
83            init: Mutex::new(()),
84        }
85    }
86
87    fn cache(&self, backend: Backend) -> &OnceLock<Vec<usize>> {
88        match backend {
89            Backend::CoreClr => &self.coreclr,
90            Backend::Mono => &self.mono,
91        }
92    }
93
94    /// Loads the bound assembly and its thunks into `runtime`. Called on first use.
95    pub fn load(&self, runtime: &Runtime) -> Result<()> {
96        let cache = self.cache(runtime.backend());
97        if cache.get().is_some() {
98            return Ok(());
99        }
100        let _guard = self.init.lock().unwrap_or_else(|e| e.into_inner());
101        if cache.get().is_some() {
102            return Ok(());
103        }
104        if !self.assembly_path.is_empty() {
105            runtime.load_assembly(self.assembly_path)?;
106        }
107        let thunks = match runtime.backend() {
108            Backend::CoreClr => self.coreclr_thunks,
109            Backend::Mono => self.mono_thunks,
110        };
111        runtime.load_assembly_bytes(self.thunks_name, thunks)?;
112        let functions = (0..self.function_count)
113            .map(|i| {
114                runtime
115                    .function_pointer(self.thunks_name, THUNK_TYPE, &format!("f{}", i))
116                    .map(|f| f as usize)
117            })
118            .collect::<Result<Vec<_>>>()?;
119        let _ = cache.set(functions);
120        Ok(())
121    }
122
123    pub fn function(&self, runtime: &Runtime, index: usize) -> Result<*const c_void> {
124        self.load(runtime)?;
125        runtime.attach_thread();
126        let functions = self.cache(runtime.backend()).get().expect("loaded above");
127        Ok(functions[index] as *const c_void)
128    }
129
130    fn call_helper(
131        &self,
132        runtime: &Runtime,
133        index: usize,
134        handle: isize,
135        out: *mut c_void,
136    ) -> Result<()> {
137        let f = self.function(runtime, index)?;
138        let mut exception: isize = 0;
139        if index == helper::FREE {
140            __call_thunk!(runtime, f, (isize = handle, *mut isize = &mut exception));
141        } else {
142            __call_thunk!(runtime, f, (isize = handle, *mut c_void = out, *mut isize = &mut exception));
143        }
144        if exception != 0 {
145            let _ = self.free(runtime, exception);
146            return Err(Error::Managed("exception in a binding helper".into()));
147        }
148        Ok(())
149    }
150
151    pub fn free(&self, runtime: &Runtime, handle: isize) -> Result<()> {
152        self.call_helper(runtime, helper::FREE, handle, std::ptr::null_mut())
153    }
154
155    /// Reads and frees a handle to a `System.String`. `0` is `null`.
156    pub fn take_string(&self, runtime: &Runtime, handle: isize) -> Result<Option<String>> {
157        if handle == 0 {
158            return Ok(None);
159        }
160        let mut length: i32 = 0;
161        self.call_helper(
162            runtime,
163            helper::STRING_LENGTH,
164            handle,
165            (&mut length as *mut i32).cast(),
166        )?;
167        let mut buffer = vec![0u16; length.max(0) as usize];
168        self.call_helper(
169            runtime,
170            helper::STRING_COPY,
171            handle,
172            buffer.as_mut_ptr().cast(),
173        )?;
174        self.free(runtime, handle)?;
175        Ok(Some(String::from_utf16_lossy(&buffer)))
176    }
177
178    /// `ToString()` of the object behind `handle`, without freeing it.
179    pub fn object_to_string(&self, runtime: &Runtime, handle: isize) -> Result<String> {
180        let mut string: isize = 0;
181        self.call_helper(
182            runtime,
183            helper::TO_STRING,
184            handle,
185            (&mut string as *mut isize).cast(),
186        )?;
187        Ok(self.take_string(runtime, string)?.unwrap_or_default())
188    }
189
190    /// Turns a handle to a thrown exception into an [`Error::Managed`], freeing it.
191    pub fn take_exception(&self, runtime: &Runtime, handle: isize) -> Error {
192        let message = self
193            .object_to_string(runtime, handle)
194            .unwrap_or_else(|e| format!("<could not read exception: {}>", e));
195        let _ = self.free(runtime, handle);
196        Error::Managed(message)
197    }
198}
199
200/// An owned reference to a managed object.
201pub struct Object {
202    handle: isize,
203    runtime: Runtime,
204    assembly: &'static BoundAssembly,
205}
206
207impl Object {
208    /// Takes ownership of a `GCHandle` returned by a thunk.
209    ///
210    /// # Safety
211    /// `handle` must be a live `GCHandle` that nothing else will free.
212    pub unsafe fn from_handle(
213        handle: isize,
214        runtime: Runtime,
215        assembly: &'static BoundAssembly,
216    ) -> Self {
217        Self {
218            handle,
219            runtime,
220            assembly,
221        }
222    }
223
224    pub fn handle(&self) -> isize {
225        self.handle
226    }
227
228    pub fn runtime(&self) -> &Runtime {
229        &self.runtime
230    }
231
232    pub fn assembly(&self) -> &'static BoundAssembly {
233        self.assembly
234    }
235
236    /// The object's `ToString()`.
237    pub fn to_managed_string(&self) -> Result<String> {
238        self.assembly.object_to_string(&self.runtime, self.handle)
239    }
240}
241
242impl std::fmt::Debug for Object {
243    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
244        write!(f, "Object({:#x})", self.handle)
245    }
246}
247
248impl Drop for Object {
249    fn drop(&mut self) {
250        let _ = self.assembly.free(&self.runtime, self.handle);
251    }
252}