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