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!`.
52pub struct BoundAssembly {
53    pub assembly_name: &'static str,
54    pub assembly_path: &'static str,
55    pub thunks_name: &'static str,
56    pub coreclr_thunks: &'static [u8],
57    pub mono_thunks: &'static [u8],
58    pub function_count: usize,
59    coreclr: OnceLock<Vec<usize>>,
60    mono: OnceLock<Vec<usize>>,
61    init: Mutex<()>,
62}
63
64impl BoundAssembly {
65    pub const fn new(
66        assembly_name: &'static str,
67        assembly_path: &'static str,
68        thunks_name: &'static str,
69        coreclr_thunks: &'static [u8],
70        mono_thunks: &'static [u8],
71        function_count: usize,
72    ) -> Self {
73        Self {
74            assembly_name,
75            assembly_path,
76            thunks_name,
77            coreclr_thunks,
78            mono_thunks,
79            function_count,
80            coreclr: OnceLock::new(),
81            mono: OnceLock::new(),
82            init: Mutex::new(()),
83        }
84    }
85
86    fn cache(&self, backend: Backend) -> &OnceLock<Vec<usize>> {
87        match backend {
88            Backend::CoreClr => &self.coreclr,
89            Backend::Mono => &self.mono,
90        }
91    }
92
93    /// Loads the bound assembly and its thunks into `runtime`. Called on first use.
94    pub fn load(&self, runtime: &Runtime) -> Result<()> {
95        let cache = self.cache(runtime.backend());
96        if cache.get().is_some() {
97            return Ok(());
98        }
99        let _guard = self.init.lock().unwrap_or_else(|e| e.into_inner());
100        if cache.get().is_some() {
101            return Ok(());
102        }
103        if !self.assembly_path.is_empty() {
104            runtime.load_assembly(self.assembly_path)?;
105        }
106        let thunks = match runtime.backend() {
107            Backend::CoreClr => self.coreclr_thunks,
108            Backend::Mono => self.mono_thunks,
109        };
110        runtime.load_assembly_bytes(self.thunks_name, thunks)?;
111        let functions = (0..self.function_count)
112            .map(|i| {
113                runtime
114                    .function_pointer(self.thunks_name, THUNK_TYPE, &format!("f{}", i))
115                    .map(|f| f as usize)
116            })
117            .collect::<Result<Vec<_>>>()?;
118        let _ = cache.set(functions);
119        Ok(())
120    }
121
122    pub fn function(&self, runtime: &Runtime, index: usize) -> Result<*const c_void> {
123        self.load(runtime)?;
124        runtime.attach_thread();
125        let functions = self.cache(runtime.backend()).get().expect("loaded above");
126        Ok(functions[index] as *const c_void)
127    }
128
129    fn call_helper(
130        &self,
131        runtime: &Runtime,
132        index: usize,
133        handle: isize,
134        out: *mut c_void,
135    ) -> Result<()> {
136        let f = self.function(runtime, index)?;
137        let mut exception: isize = 0;
138        if index == helper::FREE {
139            __call_thunk!(runtime, f, (isize = handle, *mut isize = &mut exception));
140        } else {
141            __call_thunk!(runtime, f, (isize = handle, *mut c_void = out, *mut isize = &mut exception));
142        }
143        if exception != 0 {
144            let _ = self.free(runtime, exception);
145            return Err(Error::Managed("exception in a binding helper".into()));
146        }
147        Ok(())
148    }
149
150    pub fn free(&self, runtime: &Runtime, handle: isize) -> Result<()> {
151        self.call_helper(runtime, helper::FREE, handle, std::ptr::null_mut())
152    }
153
154    /// Reads and frees a handle to a `System.String`. `0` is `null`.
155    pub fn take_string(&self, runtime: &Runtime, handle: isize) -> Result<Option<String>> {
156        if handle == 0 {
157            return Ok(None);
158        }
159        let mut length: i32 = 0;
160        self.call_helper(
161            runtime,
162            helper::STRING_LENGTH,
163            handle,
164            (&mut length as *mut i32).cast(),
165        )?;
166        let mut buffer = vec![0u16; length.max(0) as usize];
167        self.call_helper(
168            runtime,
169            helper::STRING_COPY,
170            handle,
171            buffer.as_mut_ptr().cast(),
172        )?;
173        self.free(runtime, handle)?;
174        Ok(Some(String::from_utf16_lossy(&buffer)))
175    }
176
177    /// `ToString()` of the object behind `handle`, without freeing it.
178    pub fn object_to_string(&self, runtime: &Runtime, handle: isize) -> Result<String> {
179        let mut string: isize = 0;
180        self.call_helper(
181            runtime,
182            helper::TO_STRING,
183            handle,
184            (&mut string as *mut isize).cast(),
185        )?;
186        Ok(self.take_string(runtime, string)?.unwrap_or_default())
187    }
188
189    /// Turns a handle to a thrown exception into an [`Error::Managed`], freeing it.
190    pub fn take_exception(&self, runtime: &Runtime, handle: isize) -> Error {
191        let message = self
192            .object_to_string(runtime, handle)
193            .unwrap_or_else(|e| format!("<could not read exception: {}>", e));
194        let _ = self.free(runtime, handle);
195        Error::Managed(message)
196    }
197}
198
199/// An owned reference to a managed object.
200pub struct Object {
201    handle: isize,
202    runtime: Runtime,
203    assembly: &'static BoundAssembly,
204}
205
206impl Object {
207    /// Takes ownership of a `GCHandle` returned by a thunk.
208    ///
209    /// # Safety
210    /// `handle` must be a live `GCHandle` that nothing else will free.
211    pub unsafe fn from_handle(
212        handle: isize,
213        runtime: Runtime,
214        assembly: &'static BoundAssembly,
215    ) -> Self {
216        Self {
217            handle,
218            runtime,
219            assembly,
220        }
221    }
222
223    pub fn handle(&self) -> isize {
224        self.handle
225    }
226
227    pub fn runtime(&self) -> &Runtime {
228        &self.runtime
229    }
230
231    pub fn assembly(&self) -> &'static BoundAssembly {
232        self.assembly
233    }
234
235    /// The object's `ToString()`.
236    pub fn to_managed_string(&self) -> Result<String> {
237        self.assembly.object_to_string(&self.runtime, self.handle)
238    }
239}
240
241impl std::fmt::Debug for Object {
242    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
243        write!(f, "Object({:#x})", self.handle)
244    }
245}
246
247impl Drop for Object {
248    fn drop(&mut self) {
249        let _ = self.assembly.free(&self.runtime, self.handle);
250    }
251}