Skip to main content

hao_runtime/
lib.rs

1//! Host the .NET runtime in a Rust process and call into managed code.
2//!
3//! Two backends are available behind features:
4//! - `coreclr` (default): .NET 8+, loading `libcoreclr` directly.
5//! - `mono`: the Mono embedding API, as used by Unity.
6//!
7//! Managed methods are called through native function pointers, so the
8//! methods have to be callable from native code: `[UnmanagedCallersOnly]`
9//! static methods on CoreCLR, or any static method on Mono. Bindings generated
10//! by `hao-runtime-macros` produce such methods for you.
11
12#[cfg(all(feature = "coreclr", target_arch = "x86_64"))]
13pub mod attach;
14pub mod bindings;
15pub mod console;
16#[cfg(feature = "coreclr")]
17mod coreclr;
18mod error;
19pub mod jit;
20// Only CoreCLR consumes the `Hao.Loader` helper assembly; the `coreclr`
21// feature always enables `hao`, so this is where it belongs.
22#[cfg(feature = "coreclr")]
23mod loader;
24#[cfg(feature = "mono")]
25mod mono;
26#[cfg(feature = "coreclr")]
27pub mod profiler;
28#[cfg(feature = "reflect")]
29pub mod reflect;
30#[cfg(feature = "hao")]
31pub mod rewrite;
32
33use std::{ffi::c_void, path::Path, sync::Arc};
34
35pub use bindings::{BoundAssembly, Object};
36pub use error::{Error, Result};
37
38/// The `hao` assembly-editing crate, re-exported so downstream crates can
39/// build modules to load with [`Runtime::load_module`] without pinning
40/// their own (possibly mismatched) `hao` version.
41#[cfg(feature = "hao")]
42pub use hao;
43
44#[cfg(feature = "coreclr")]
45pub use coreclr::{find_dotnet_root, CoreClrOptions};
46#[cfg(feature = "mono")]
47pub use mono::MonoOptions;
48
49#[derive(Debug, Clone, Copy, PartialEq, Eq)]
50#[cfg_attr(feature = "reflect", derive(facet::Facet))]
51#[cfg_attr(feature = "reflect", repr(C))]
52pub enum Backend {
53    CoreClr,
54    Mono,
55}
56
57// hao-runtime wraps a *running* .NET runtime, so it needs a backend: without
58// one `Inner` has no variants, `Runtime` has no constructor, and every
59// `match &*self.0` is a non-exhaustive match on the (still inhabited) `&Inner`.
60// Require a backend explicitly rather than emit a wall of E0004s.
61#[cfg(not(any(feature = "coreclr", feature = "mono")))]
62compile_error!("hao-runtime requires a backend feature: enable `coreclr` (the default) or `mono`");
63
64enum Inner {
65    #[cfg(feature = "coreclr")]
66    CoreClr(coreclr::CoreClr),
67    #[cfg(feature = "mono")]
68    Mono(mono::Mono),
69}
70
71/// A handle to a running .NET runtime. Cheap to clone.
72#[derive(Clone)]
73pub struct Runtime(Arc<Inner>);
74
75impl std::fmt::Debug for Runtime {
76    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
77        write!(f, "Runtime({:?})", self.backend())
78    }
79}
80
81impl Runtime {
82    /// Starts CoreCLR with the newest installed framework, or returns the
83    /// already running instance. Only one CoreCLR can run per process.
84    #[cfg(feature = "coreclr")]
85    pub fn coreclr() -> Result<Self> {
86        Self::coreclr_with(&CoreClrOptions::default())
87    }
88
89    /// Starts CoreCLR with `options`. The options are ignored if it is already running.
90    #[cfg(feature = "coreclr")]
91    pub fn coreclr_with(options: &CoreClrOptions) -> Result<Self> {
92        Self::coreclr_from(|| coreclr::CoreClr::new(options))
93    }
94
95    /// Attaches to a CoreCLR already running in this process, for a native mod
96    /// loaded into a .NET game (e.g. Godot on CoreCLR). `host_handle`, `domain_id`
97    /// and `create_delegate` (`coreclr_create_delegate`) are captured as the
98    /// game's runtime initialises — see the `hao-godot` crate; `major` is the
99    /// .NET major version. After this, assemblies can be loaded and methods
100    /// called as usual. Returns the existing handle if hao already has one.
101    #[cfg(feature = "coreclr")]
102    pub fn coreclr_attach(
103        host_handle: *mut c_void,
104        domain_id: u32,
105        create_delegate: *const c_void,
106        major: u16,
107    ) -> Result<Self> {
108        Self::coreclr_from(|| {
109            coreclr::CoreClr::attach(host_handle, domain_id, create_delegate, major)
110        })
111    }
112
113    #[cfg(feature = "coreclr")]
114    fn coreclr_from(make: impl FnOnce() -> Result<coreclr::CoreClr>) -> Result<Self> {
115        static RUNTIME: std::sync::Mutex<Option<Runtime>> = std::sync::Mutex::new(None);
116        let mut runtime = RUNTIME.lock().unwrap_or_else(|e| e.into_inner());
117        if let Some(runtime) = runtime.as_ref() {
118            return Ok(runtime.clone());
119        }
120        let started = Runtime(Arc::new(Inner::CoreClr(make()?)));
121        *runtime = Some(started.clone());
122        Ok(started)
123    }
124
125    /// Starts Mono, or returns the already running instance.
126    #[cfg(feature = "mono")]
127    pub fn mono(options: &MonoOptions) -> Result<Self> {
128        Self::mono_with(|| mono::Mono::new(options))
129    }
130
131    /// Attaches to a Mono runtime already running in this process, for a mod
132    /// loaded into a Unity Mono game. `options.library` should point at the
133    /// game's own Mono. After this, assemblies can be loaded and methods called
134    /// as usual. Returns the existing handle if hao already has one.
135    #[cfg(feature = "mono")]
136    pub fn mono_attach(options: &MonoOptions) -> Result<Self> {
137        Self::mono_with(|| mono::Mono::attach(options))
138    }
139
140    #[cfg(feature = "mono")]
141    fn mono_with(make: impl FnOnce() -> Result<mono::Mono>) -> Result<Self> {
142        static RUNTIME: std::sync::Mutex<Option<Runtime>> = std::sync::Mutex::new(None);
143        let mut runtime = RUNTIME.lock().unwrap_or_else(|e| e.into_inner());
144        if let Some(runtime) = runtime.as_ref() {
145            return Ok(runtime.clone());
146        }
147        let started = Runtime(Arc::new(Inner::Mono(make()?)));
148        *runtime = Some(started.clone());
149        Ok(started)
150    }
151
152    pub fn backend(&self) -> Backend {
153        match &*self.0 {
154            #[cfg(feature = "coreclr")]
155            Inner::CoreClr(_) => Backend::CoreClr,
156            #[cfg(feature = "mono")]
157            Inner::Mono(_) => Backend::Mono,
158        }
159    }
160
161    /// Lets the calling thread run managed code. Needed for Mono on threads it
162    /// didn't start, a no-op on CoreCLR. Binding calls do this automatically.
163    pub fn attach_thread(&self) {
164        match &*self.0 {
165            #[cfg(feature = "coreclr")]
166            Inner::CoreClr(_) => {}
167            #[cfg(feature = "mono")]
168            Inner::Mono(mono) => mono.attach_thread(),
169        }
170    }
171
172    /// Loads an assembly and makes it available to later loads by name.
173    pub fn load_assembly(&self, path: impl AsRef<Path>) -> Result<()> {
174        match &*self.0 {
175            #[cfg(feature = "coreclr")]
176            Inner::CoreClr(clr) => clr.load_assembly(path.as_ref()),
177            #[cfg(feature = "mono")]
178            Inner::Mono(mono) => mono.load_assembly(path.as_ref()),
179        }
180    }
181
182    /// Loads an assembly from memory. `name` is its assembly name.
183    pub fn load_assembly_bytes(&self, name: &str, bytes: &[u8]) -> Result<()> {
184        match &*self.0 {
185            #[cfg(feature = "coreclr")]
186            Inner::CoreClr(clr) => {
187                let _ = name;
188                clr.load_assembly_bytes(bytes)
189            }
190            #[cfg(feature = "mono")]
191            Inner::Mono(mono) => mono.load_assembly_bytes(name, bytes),
192        }
193    }
194
195    /// Loads a module built or edited with hao, without writing it to disk.
196    #[cfg(feature = "hao")]
197    pub fn load_module(&self, module: &hao::Module) -> Result<()> {
198        let bytes = module
199            .write()
200            .map_err(|e| Error::Other(format!("could not write {}: {}", module.name(), e)))?;
201        let name = match &module.assembly {
202            Some(assembly) => assembly.get().name.clone(),
203            None => module.name().trim_end_matches(".dll").to_string(),
204        };
205        self.load_assembly_bytes(&name, &bytes)
206    }
207
208    /// A native pointer to the static method `type_name::method` in `assembly`.
209    ///
210    /// On CoreCLR the method must be `[UnmanagedCallersOnly]`; for a method that
211    /// isn't, use [`method_pointer`](Self::method_pointer) instead, which calls
212    /// any method by JIT-compiling it. On Mono the returned thunk takes an extra
213    /// trailing `*mut *mut c_void` exception argument.
214    pub fn function_pointer(
215        &self,
216        assembly: &str,
217        type_name: &str,
218        method: &str,
219    ) -> Result<*const c_void> {
220        match &*self.0 {
221            #[cfg(feature = "coreclr")]
222            Inner::CoreClr(clr) => clr.function_pointer(assembly, type_name, method),
223            #[cfg(feature = "mono")]
224            Inner::Mono(mono) => mono.function_pointer(assembly, type_name, method),
225        }
226    }
227
228    /// A native-callable pointer to a static method, whether or not it is
229    /// `[UnmanagedCallersOnly]`. The method is JIT-compiled first, so IL patched
230    /// before the assembly was loaded takes effect.
231    ///
232    /// The pointer uses the managed calling convention, which matches a plain
233    /// `extern "C" fn(args) -> ret` for static methods with primitive and
234    /// pointer arguments. Unlike [`function_pointer`](Self::function_pointer),
235    /// it takes no trailing exception argument on either backend, so a managed
236    /// exception crosses it as an unhandled error.
237    pub fn method_pointer(
238        &self,
239        assembly: &str,
240        type_name: &str,
241        method: &str,
242    ) -> Result<*const c_void> {
243        match &*self.0 {
244            #[cfg(feature = "coreclr")]
245            Inner::CoreClr(clr) => clr.method_pointer(assembly, type_name, method),
246            #[cfg(feature = "mono")]
247            Inner::Mono(mono) => mono.method_pointer(assembly, type_name, method),
248        }
249    }
250
251    /// Like [`method_pointer`](Self::method_pointer), but resolves the type
252    /// from whichever `AssemblyLoadContext` actually loaded the assembly.
253    ///
254    /// Mono has no `AssemblyLoadContext`, so there it is identical to
255    /// [`method_pointer`](Self::method_pointer).
256    pub fn method_pointer_from_loaded(
257        &self,
258        assembly: &str,
259        type_name: &str,
260        method: &str,
261    ) -> Result<*const c_void> {
262        match &*self.0 {
263            #[cfg(feature = "coreclr")]
264            Inner::CoreClr(clr) => clr.method_pointer_from_loaded(assembly, type_name, method),
265            #[cfg(feature = "mono")]
266            Inner::Mono(mono) => mono.method_pointer(assembly, type_name, method),
267        }
268    }
269
270    /// Resolves a well-known corlib method to a native-callable pointer,
271    /// deriving the type name, method name and overload arity from the
272    /// [`WellKnownMethod`](hao::dotnet::entries::well_known::WellKnownMethod)
273    /// vocabulary instead of raw strings.
274    ///
275    /// On CoreCLR the method is found in the loaded `System.Private.CoreLib`;
276    /// on Mono it is found in `mono_get_corlib` (`mscorlib`).
277    #[cfg(feature = "hao")]
278    pub fn corlib_method_pointer(
279        &self,
280        method: hao::dotnet::entries::well_known::WellKnownMethod,
281    ) -> Result<*const c_void> {
282        let (namespace, name) = method.declaring().full_name();
283        match &*self.0 {
284            #[cfg(feature = "coreclr")]
285            Inner::CoreClr(clr) => {
286                let full_name = if namespace.is_empty() {
287                    name.to_string()
288                } else {
289                    format!("{namespace}.{name}")
290                };
291                clr.find_method_from_loaded(
292                    "System.Private.CoreLib",
293                    &full_name,
294                    method.method_name(),
295                    method.param_count() as i32,
296                )
297            }
298            #[cfg(feature = "mono")]
299            Inner::Mono(mono) => mono.corlib_method_pointer(
300                namespace,
301                name,
302                method.method_name(),
303                method.param_count() as i32,
304            ),
305        }
306    }
307
308    /// Like [`method_pointer_from_loaded`](Self::method_pointer_from_loaded)
309    /// but matches by parameter count, so it works with overloaded methods.
310    pub fn find_method_from_loaded(
311        &self,
312        assembly: &str,
313        type_name: &str,
314        method: &str,
315        param_count: i32,
316    ) -> Result<*const c_void> {
317        match &*self.0 {
318            #[cfg(feature = "coreclr")]
319            Inner::CoreClr(clr) => {
320                clr.find_method_from_loaded(assembly, type_name, method, param_count)
321            }
322            #[cfg(feature = "mono")]
323            Inner::Mono(mono) => mono.find_method(assembly, type_name, method, param_count),
324        }
325    }
326
327    /// Calls a managed method pointer through a P/Invoke wrapper that
328    /// ensures the calling thread is registered with the CLR's GC.
329    /// Falls back to `jit::call_native` on Mono (which handles thread
330    /// attach separately).
331    #[cfg(target_arch = "x86_64")]
332    pub fn invoke(&self, ptr: usize, args: &[u64]) -> Result<u64> {
333        match &*self.0 {
334            #[cfg(feature = "coreclr")]
335            Inner::CoreClr(clr) => clr.invoke(ptr, args),
336            #[cfg(feature = "mono")]
337            Inner::Mono(_) => Ok(unsafe { jit::call_native(ptr, args) }),
338        }
339    }
340
341    /// Like [`invoke`](Self::invoke) but returns `f64`.
342    #[cfg(target_arch = "x86_64")]
343    pub fn invoke_float(&self, ptr: usize, args: &[u64]) -> Result<f64> {
344        match &*self.0 {
345            #[cfg(feature = "coreclr")]
346            Inner::CoreClr(clr) => clr.invoke_float(ptr, args),
347            #[cfg(feature = "mono")]
348            Inner::Mono(_) => Ok(unsafe { jit::call_native_float(ptr, args) }),
349        }
350    }
351
352    /// Requests a no-GC region for the next `budget` bytes of managed
353    /// allocation.  Returns `true` if the runtime agreed to suppress GC.
354    ///
355    /// Mono (SGen) has no `GC.TryStartNoGCRegion` equivalent, so this is an
356    /// honest no-op there that always returns `false`.
357    pub fn suppress_gc(&self, budget: i64) -> Result<bool> {
358        match &*self.0 {
359            #[cfg(feature = "coreclr")]
360            Inner::CoreClr(clr) => clr.suppress_gc(budget),
361            #[cfg(feature = "mono")]
362            Inner::Mono(_) => {
363                let _ = budget;
364                Ok(false)
365            }
366        }
367    }
368
369    /// Ends a no-GC region started by [`suppress_gc`](Self::suppress_gc).
370    ///
371    /// A no-op on Mono, which has no no-GC-region to end (see
372    /// [`suppress_gc`](Self::suppress_gc)).
373    pub fn resume_gc(&self) -> Result<()> {
374        match &*self.0 {
375            #[cfg(feature = "coreclr")]
376            Inner::CoreClr(clr) => clr.resume_gc(),
377            #[cfg(feature = "mono")]
378            Inner::Mono(_) => Ok(()),
379        }
380    }
381
382    /// Warms [`enumerate`](Self::enumerate) so it does no lazy setup on the
383    /// game thread.
384    ///
385    /// On CoreCLR this JIT-compiles and caches the `Hao.Loader::Enumerate`
386    /// helper, and MUST be called off a cooperative-mode thread (e.g. at init).
387    /// On Mono it resolves and caches the corlib enumerator methods; `enumerate`
388    /// resolves them lazily too, so warming is only an optimisation there.
389    pub fn warm_enumerate(&self) -> Result<()> {
390        match &*self.0 {
391            #[cfg(feature = "coreclr")]
392            Inner::CoreClr(clr) => clr.warm_enumerate(),
393            #[cfg(feature = "mono")]
394            Inner::Mono(mono) => mono.warm_enumerate(),
395        }
396    }
397
398    /// Materializes any managed `IEnumerable` into the addresses of its
399    /// elements, by calling a JIT-compiled `foreach` helper and reading the
400    /// resulting `object[]`. This handles concrete types native code cannot
401    /// read by hand — lazy iterators, LINQ chains, dictionary views.
402    ///
403    /// Call [`warm_enumerate`](Self::warm_enumerate) once off a cooperative-mode
404    /// thread first; this call must run ON the cooperative (game) thread, like
405    /// any [`method_pointer`](Self::method_pointer) call.
406    ///
407    /// On Mono the returned addresses are live `MonoObject*`s that SGen may move
408    /// at the next GC (each step of the walk is a safepoint), so read or pin
409    /// them before continuing — the same raw-pointer contract as the rest of the
410    /// Mono backend.
411    pub fn enumerate(&self, obj: usize) -> Result<Vec<usize>> {
412        match &*self.0 {
413            #[cfg(feature = "coreclr")]
414            Inner::CoreClr(clr) => clr.enumerate(obj),
415            #[cfg(feature = "mono")]
416            Inner::Mono(mono) => mono.enumerate(obj),
417        }
418    }
419
420    /// The .NET major version (e.g. 9) the runtime was started or attached
421    /// with. `None` on Mono, where no CoreCLR framework version applies.
422    pub fn dotnet_major(&self) -> Option<u16> {
423        match &*self.0 {
424            #[cfg(feature = "coreclr")]
425            Inner::CoreClr(clr) => Some(clr.major()),
426            #[cfg(feature = "mono")]
427            Inner::Mono(_) => None,
428        }
429    }
430
431    /// Returns all type full names from a loaded assembly.
432    pub fn type_names(&self, assembly: &str) -> Result<Vec<String>> {
433        match &*self.0 {
434            #[cfg(feature = "coreclr")]
435            Inner::CoreClr(clr) => clr.type_names(assembly),
436            #[cfg(feature = "mono")]
437            Inner::Mono(mono) => mono.type_names(assembly),
438        }
439    }
440
441    /// Returns all method names from a type in a loaded assembly.
442    pub fn method_names(&self, assembly: &str, type_name: &str) -> Result<Vec<String>> {
443        match &*self.0 {
444            #[cfg(feature = "coreclr")]
445            Inner::CoreClr(clr) => clr.method_names(assembly, type_name),
446            #[cfg(feature = "mono")]
447            Inner::Mono(mono) => mono.method_names(assembly, type_name),
448        }
449    }
450}