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