1use std::{
30 ffi::c_void,
31 sync::{Mutex, OnceLock},
32};
33
34use crate::{Backend, Error, Result, Runtime};
35
36pub const THUNK_TYPE: &str = "HaoThunks.Thunks";
39
40pub mod helper {
42 pub const FREE: usize = 0;
44 pub const STRING_LENGTH: usize = 1;
46 pub const STRING_COPY: usize = 2;
48 pub const TO_STRING: usize = 3;
50 pub const COUNT: usize = 4;
52}
53
54#[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#[cfg_attr(feature = "reflect", derive(facet::Facet))]
76pub struct BoundAssembly {
77 pub assembly_name: &'static str,
79 pub assembly_path: &'static str,
82 pub thunks_name: &'static str,
84 pub coreclr_thunks: &'static [u8],
86 pub mono_thunks: &'static [u8],
88 pub function_count: usize,
90 coreclr: OnceLock<Vec<usize>>,
91 mono: OnceLock<Vec<usize>>,
92 init: Mutex<()>,
93}
94
95impl BoundAssembly {
96 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 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 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 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 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 pub fn free(&self, runtime: &Runtime, handle: isize) -> Result<()> {
240 self.call_helper(runtime, helper::FREE, handle, std::ptr::null_mut())
241 }
242
243 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 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 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
288pub struct Object {
290 handle: isize,
291 runtime: Runtime,
292 assembly: &'static BoundAssembly,
293}
294
295impl Object {
296 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 pub fn handle(&self) -> isize {
314 self.handle
315 }
316
317 pub fn runtime(&self) -> &Runtime {
319 &self.runtime
320 }
321
322 pub fn assembly(&self) -> &'static BoundAssembly {
324 self.assembly
325 }
326
327 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}