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//!
10//! None of this is called by hand: `bind!` generates a [`BoundAssembly`] and a
11//! struct per class wrapping an [`Object`], which looks like this to use:
12//!
13//! ```ignore
14//! // Needs the `hao-runtime-macros` crate, which isn't a dependency of this
15//! // one, and a built `dotnet/MyLib.dll` next to the calling crate.
16//! mod my_lib {
17//!     hao_runtime_macros::bind! {
18//!         assembly = "dotnet/MyLib.dll",
19//!     }
20//! }
21//!
22//! let runtime = hao_runtime::Runtime::coreclr()?;
23//! let calculator = my_lib::my_lib::Calculator::new(&runtime, 10)?;
24//! assert_eq!(calculator.add(5)?, 15);
25//! // The wrapped `Object` gives the managed `ToString()`.
26//! println!("{}", calculator.object().to_managed_string()?);
27//! ```
28
29use std::{
30    ffi::c_void,
31    sync::{Mutex, OnceLock},
32};
33
34use crate::{Backend, Error, Result, Runtime};
35
36/// The full name of the static type holding the thunks in every generated
37/// thunk assembly.
38pub const THUNK_TYPE: &str = "HaoThunks.Thunks";
39
40/// Indexes of the helper thunks every generated thunk assembly starts with.
41pub mod helper {
42    /// `free(handle)`
43    pub const FREE: usize = 0;
44    /// `string_length(handle) -> i32`
45    pub const STRING_LENGTH: usize = 1;
46    /// `string_copy(handle, *mut u16)`
47    pub const STRING_COPY: usize = 2;
48    /// `to_string(handle) -> handle`
49    pub const TO_STRING: usize = 3;
50    /// How many helpers there are; bound methods' thunks start at this index.
51    pub const COUNT: usize = 4;
52}
53
54/// Calls a thunk pointer with the calling convention of the runtime's backend.
55#[doc(hidden)]
56#[macro_export]
57macro_rules! __call_thunk {
58    ($runtime:expr, $function:expr, ($($ty:ty = $value:expr),* $(,)?)) => {{
59        let function: *const ::core::ffi::c_void = $function;
60        match $runtime.backend() {
61            $crate::Backend::CoreClr => unsafe {
62                let f: extern "C" fn($($ty),*) = ::core::mem::transmute(function);
63                f($($value),*)
64            },
65            $crate::Backend::Mono => unsafe {
66                let f: extern "C" fn($($ty,)* *mut *mut ::core::ffi::c_void) = ::core::mem::transmute(function);
67                let mut exception = ::core::ptr::null_mut();
68                f($($value,)* &mut exception)
69            },
70        }
71    }};
72}
73
74/// A .NET assembly bound with `hao_runtime_macros::bind!`.
75#[cfg_attr(feature = "reflect", derive(facet::Facet))]
76pub struct BoundAssembly {
77    /// The bound assembly's name, e.g. `MyLib`.
78    pub assembly_name: &'static str,
79    /// Where the bound assembly is loaded from; empty when the runtime already
80    /// has it (a framework assembly).
81    pub assembly_path: &'static str,
82    /// The generated thunk assembly's name.
83    pub thunks_name: &'static str,
84    /// The thunk assembly for CoreCLR, whose thunks are `[UnmanagedCallersOnly]`.
85    pub coreclr_thunks: &'static [u8],
86    /// The thunk assembly for Mono.
87    pub mono_thunks: &'static [u8],
88    /// How many thunks there are, the [`helper`]s included.
89    pub function_count: usize,
90    coreclr: OnceLock<Vec<usize>>,
91    mono: OnceLock<Vec<usize>>,
92    init: Mutex<()>,
93}
94
95impl BoundAssembly {
96    /// Describes a bound assembly; `bind!` generates this call, so there is
97    /// usually no need to write it.
98    pub const fn new(
99        assembly_name: &'static str,
100        assembly_path: &'static str,
101        thunks_name: &'static str,
102        coreclr_thunks: &'static [u8],
103        mono_thunks: &'static [u8],
104        function_count: usize,
105    ) -> Self {
106        Self {
107            assembly_name,
108            assembly_path,
109            thunks_name,
110            coreclr_thunks,
111            mono_thunks,
112            function_count,
113            coreclr: OnceLock::new(),
114            mono: OnceLock::new(),
115            init: Mutex::new(()),
116        }
117    }
118
119    fn cache(&self, backend: Backend) -> &OnceLock<Vec<usize>> {
120        match backend {
121            Backend::CoreClr => &self.coreclr,
122            Backend::Mono => &self.mono,
123        }
124    }
125
126    /// Loads the bound assembly and its thunks into `runtime`. Called on first use.
127    pub fn load(&self, runtime: &Runtime) -> Result<()> {
128        let cache = self.cache(runtime.backend());
129        if cache.get().is_some() {
130            return Ok(());
131        }
132        let _guard = self.init.lock().unwrap_or_else(|e| e.into_inner());
133        if cache.get().is_some() {
134            return Ok(());
135        }
136        if !self.assembly_path.is_empty() {
137            runtime.load_assembly(self.assembly_path)?;
138        }
139        let thunks = match runtime.backend() {
140            Backend::CoreClr => self.coreclr_thunks,
141            Backend::Mono => self.mono_thunks,
142        };
143        runtime.load_assembly_bytes(self.thunks_name, thunks)?;
144        let functions = (0..self.function_count)
145            .map(|i| {
146                runtime
147                    .function_pointer(self.thunks_name, THUNK_TYPE, &format!("f{}", i))
148                    .map(|f| f as usize)
149            })
150            .collect::<Result<Vec<_>>>()?;
151        let _ = cache.set(functions);
152        Ok(())
153    }
154
155    /// A native pointer to thunk `f{index}`, loading the assembly and
156    /// attaching the calling thread first. Call it with [`Runtime::backend`]'s
157    /// calling convention.
158    pub fn function(&self, runtime: &Runtime, index: usize) -> Result<*const c_void> {
159        self.load(runtime)?;
160        runtime.attach_thread();
161        let functions = self.cache(runtime.backend()).get().expect("loaded above");
162        Ok(functions[index] as *const c_void)
163    }
164
165    /// Calls helper `index` on `handle`, returning a handle to the exception it
166    /// threw (`0` if none) without interpreting it.
167    fn call_helper_raw(
168        &self,
169        runtime: &Runtime,
170        index: usize,
171        handle: isize,
172        out: *mut c_void,
173    ) -> Result<isize> {
174        let f = self.function(runtime, index)?;
175        let mut exception: isize = 0;
176        if index == helper::FREE {
177            __call_thunk!(runtime, f, (isize = handle, *mut isize = &mut exception));
178        } else {
179            __call_thunk!(runtime, f, (isize = handle, *mut c_void = out, *mut isize = &mut exception));
180        }
181        Ok(exception)
182    }
183
184    fn call_helper(
185        &self,
186        runtime: &Runtime,
187        index: usize,
188        handle: isize,
189        out: *mut c_void,
190    ) -> Result<()> {
191        match self.call_helper_raw(runtime, index, handle, out)? {
192            0 => Ok(()),
193            exception => Err(self.take_exception(runtime, exception)),
194        }
195    }
196
197    /// The exception's `ToString()` (type name, message and stack trace).
198    /// Uses the raw helpers so an exception thrown while reading it can't
199    /// recurse; it frees any such exception but not `handle`.
200    fn describe_exception(&self, runtime: &Runtime, handle: isize) -> Result<String> {
201        let mut nested: Option<isize> = None;
202        let mut raw = |index, handle, out: *mut c_void| -> Result<bool> {
203            match self.call_helper_raw(runtime, index, handle, out)? {
204                0 => Ok(true),
205                exception => {
206                    nested = Some(exception);
207                    Ok(false)
208                }
209            }
210        };
211        let mut string: isize = 0;
212        let mut text = None;
213        if raw(
214            helper::TO_STRING,
215            handle,
216            (&mut string as *mut isize).cast(),
217        )? && string != 0
218        {
219            let mut length: i32 = 0;
220            if raw(
221                helper::STRING_LENGTH,
222                string,
223                (&mut length as *mut i32).cast(),
224            )? {
225                let mut buffer = vec![0u16; length.max(0) as usize];
226                if raw(helper::STRING_COPY, string, buffer.as_mut_ptr().cast())? {
227                    text = Some(String::from_utf16_lossy(&buffer));
228                }
229            }
230            let _ = self.call_helper_raw(runtime, helper::FREE, string, std::ptr::null_mut());
231        }
232        if let Some(exception) = nested {
233            let _ = self.call_helper_raw(runtime, helper::FREE, exception, std::ptr::null_mut());
234        }
235        text.ok_or_else(|| Error::Other("reading the exception threw".into()))
236    }
237
238    /// Frees a `GCHandle` a thunk returned, letting the object be collected.
239    pub fn free(&self, runtime: &Runtime, handle: isize) -> Result<()> {
240        self.call_helper(runtime, helper::FREE, handle, std::ptr::null_mut())
241    }
242
243    /// Reads and frees a handle to a `System.String`. `0` is `null`.
244    pub fn take_string(&self, runtime: &Runtime, handle: isize) -> Result<Option<String>> {
245        if handle == 0 {
246            return Ok(None);
247        }
248        let mut length: i32 = 0;
249        self.call_helper(
250            runtime,
251            helper::STRING_LENGTH,
252            handle,
253            (&mut length as *mut i32).cast(),
254        )?;
255        let mut buffer = vec![0u16; length.max(0) as usize];
256        self.call_helper(
257            runtime,
258            helper::STRING_COPY,
259            handle,
260            buffer.as_mut_ptr().cast(),
261        )?;
262        self.free(runtime, handle)?;
263        Ok(Some(String::from_utf16_lossy(&buffer)))
264    }
265
266    /// `ToString()` of the object behind `handle`, without freeing it.
267    pub fn object_to_string(&self, runtime: &Runtime, handle: isize) -> Result<String> {
268        let mut string: isize = 0;
269        self.call_helper(
270            runtime,
271            helper::TO_STRING,
272            handle,
273            (&mut string as *mut isize).cast(),
274        )?;
275        Ok(self.take_string(runtime, string)?.unwrap_or_default())
276    }
277
278    /// Turns a handle to a thrown exception into an [`Error::Managed`], freeing it.
279    pub fn take_exception(&self, runtime: &Runtime, handle: isize) -> Error {
280        let message = self
281            .describe_exception(runtime, handle)
282            .unwrap_or_else(|e| format!("<could not read exception: {}>", e));
283        let _ = self.call_helper_raw(runtime, helper::FREE, handle, std::ptr::null_mut());
284        Error::Managed(message)
285    }
286}
287
288/// An owned reference to a managed object.
289pub struct Object {
290    handle: isize,
291    runtime: Runtime,
292    assembly: &'static BoundAssembly,
293}
294
295impl Object {
296    /// Takes ownership of a `GCHandle` returned by a thunk.
297    ///
298    /// # Safety
299    /// `handle` must be a live `GCHandle` that nothing else will free.
300    pub unsafe fn from_handle(
301        handle: isize,
302        runtime: Runtime,
303        assembly: &'static BoundAssembly,
304    ) -> Self {
305        Self {
306            handle,
307            runtime,
308            assembly,
309        }
310    }
311
312    /// The `GCHandle` to pass to thunks for this object; still owned by `self`.
313    pub fn handle(&self) -> isize {
314        self.handle
315    }
316
317    /// The runtime the object lives in.
318    pub fn runtime(&self) -> &Runtime {
319        &self.runtime
320    }
321
322    /// The bound assembly whose thunks handle this object.
323    pub fn assembly(&self) -> &'static BoundAssembly {
324        self.assembly
325    }
326
327    /// The object's `ToString()`.
328    pub fn to_managed_string(&self) -> Result<String> {
329        self.assembly.object_to_string(&self.runtime, self.handle)
330    }
331}
332
333impl std::fmt::Debug for Object {
334    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
335        write!(f, "Object({:#x})", self.handle)
336    }
337}
338
339impl Drop for Object {
340    fn drop(&mut self) {
341        let _ = self.assembly.free(&self.runtime, self.handle);
342    }
343}