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;
16#[cfg(feature = "coreclr")]
17mod coreclr;
18mod error;
19#[cfg(feature = "coreclr")]
20pub mod profiler;
21#[cfg(feature = "hao")]
22pub mod rewrite;
23#[cfg(feature = "reflect")]
24pub mod reflect;
25#[cfg(feature = "mono")]
26mod mono;
27
28use std::{ffi::c_void, path::Path, sync::Arc};
29
30pub use bindings::{BoundAssembly, Object};
31pub use error::{Error, Result};
32
33#[cfg(feature = "coreclr")]
34pub use coreclr::{find_dotnet_root, CoreClrOptions};
35#[cfg(feature = "mono")]
36pub use mono::MonoOptions;
37
38#[derive(Debug, Clone, Copy, PartialEq, Eq)]
39#[cfg_attr(feature = "reflect", derive(facet::Facet))]
40#[cfg_attr(feature = "reflect", repr(C))]
41pub enum Backend {
42    CoreClr,
43    Mono,
44}
45
46enum Inner {
47    #[cfg(feature = "coreclr")]
48    CoreClr(coreclr::CoreClr),
49    #[cfg(feature = "mono")]
50    Mono(mono::Mono),
51}
52
53/// A handle to a running .NET runtime. Cheap to clone.
54#[derive(Clone)]
55pub struct Runtime(Arc<Inner>);
56
57impl std::fmt::Debug for Runtime {
58    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
59        write!(f, "Runtime({:?})", self.backend())
60    }
61}
62
63impl Runtime {
64    /// Starts CoreCLR with the newest installed framework, or returns the
65    /// already running instance. Only one CoreCLR can run per process.
66    #[cfg(feature = "coreclr")]
67    pub fn coreclr() -> Result<Self> {
68        Self::coreclr_with(&CoreClrOptions::default())
69    }
70
71    /// Starts CoreCLR with `options`. The options are ignored if it is already running.
72    #[cfg(feature = "coreclr")]
73    pub fn coreclr_with(options: &CoreClrOptions) -> Result<Self> {
74        Self::coreclr_from(|| coreclr::CoreClr::new(options))
75    }
76
77    /// Attaches to a CoreCLR already running in this process, for a native mod
78    /// loaded into a .NET game (e.g. Godot on CoreCLR). `host_handle`, `domain_id`
79    /// and `create_delegate` (`coreclr_create_delegate`) are captured as the
80    /// game's runtime initialises — see the `hao-godot` crate; `major` is the
81    /// .NET major version. After this, assemblies can be loaded and methods
82    /// called as usual. Returns the existing handle if hao already has one.
83    #[cfg(feature = "coreclr")]
84    pub fn coreclr_attach(
85        host_handle: *mut c_void,
86        domain_id: u32,
87        create_delegate: *const c_void,
88        major: u16,
89    ) -> Result<Self> {
90        Self::coreclr_from(|| {
91            coreclr::CoreClr::attach(host_handle, domain_id, create_delegate, major)
92        })
93    }
94
95    #[cfg(feature = "coreclr")]
96    fn coreclr_from(make: impl FnOnce() -> Result<coreclr::CoreClr>) -> Result<Self> {
97        static RUNTIME: std::sync::Mutex<Option<Runtime>> = std::sync::Mutex::new(None);
98        let mut runtime = RUNTIME.lock().unwrap_or_else(|e| e.into_inner());
99        if let Some(runtime) = runtime.as_ref() {
100            return Ok(runtime.clone());
101        }
102        let started = Runtime(Arc::new(Inner::CoreClr(make()?)));
103        *runtime = Some(started.clone());
104        Ok(started)
105    }
106
107    /// Starts Mono, or returns the already running instance.
108    #[cfg(feature = "mono")]
109    pub fn mono(options: &MonoOptions) -> Result<Self> {
110        Self::mono_with(|| mono::Mono::new(options))
111    }
112
113    /// Attaches to a Mono runtime already running in this process, for a mod
114    /// loaded into a Unity Mono game. `options.library` should point at the
115    /// game's own Mono. After this, assemblies can be loaded and methods called
116    /// as usual. Returns the existing handle if hao already has one.
117    #[cfg(feature = "mono")]
118    pub fn mono_attach(options: &MonoOptions) -> Result<Self> {
119        Self::mono_with(|| mono::Mono::attach(options))
120    }
121
122    #[cfg(feature = "mono")]
123    fn mono_with(make: impl FnOnce() -> Result<mono::Mono>) -> Result<Self> {
124        static RUNTIME: std::sync::Mutex<Option<Runtime>> = std::sync::Mutex::new(None);
125        let mut runtime = RUNTIME.lock().unwrap_or_else(|e| e.into_inner());
126        if let Some(runtime) = runtime.as_ref() {
127            return Ok(runtime.clone());
128        }
129        let started = Runtime(Arc::new(Inner::Mono(make()?)));
130        *runtime = Some(started.clone());
131        Ok(started)
132    }
133
134    pub fn backend(&self) -> Backend {
135        match &*self.0 {
136            #[cfg(feature = "coreclr")]
137            Inner::CoreClr(_) => Backend::CoreClr,
138            #[cfg(feature = "mono")]
139            Inner::Mono(_) => Backend::Mono,
140        }
141    }
142
143    /// Lets the calling thread run managed code. Needed for Mono on threads it
144    /// didn't start, a no-op on CoreCLR. Binding calls do this automatically.
145    pub fn attach_thread(&self) {
146        match &*self.0 {
147            #[cfg(feature = "coreclr")]
148            Inner::CoreClr(_) => {}
149            #[cfg(feature = "mono")]
150            Inner::Mono(mono) => mono.attach_thread(),
151        }
152    }
153
154    /// Loads an assembly and makes it available to later loads by name.
155    pub fn load_assembly(&self, path: impl AsRef<Path>) -> Result<()> {
156        match &*self.0 {
157            #[cfg(feature = "coreclr")]
158            Inner::CoreClr(clr) => clr.load_assembly(path.as_ref()),
159            #[cfg(feature = "mono")]
160            Inner::Mono(mono) => mono.load_assembly(path.as_ref()),
161        }
162    }
163
164    /// Loads an assembly from memory. `name` is its assembly name.
165    pub fn load_assembly_bytes(&self, name: &str, bytes: &[u8]) -> Result<()> {
166        match &*self.0 {
167            #[cfg(feature = "coreclr")]
168            Inner::CoreClr(clr) => {
169                let _ = name;
170                clr.load_assembly_bytes(bytes)
171            }
172            #[cfg(feature = "mono")]
173            Inner::Mono(mono) => mono.load_assembly_bytes(name, bytes),
174        }
175    }
176
177    /// Loads a module built or edited with hao, without writing it to disk.
178    #[cfg(feature = "hao")]
179    pub fn load_module(&self, module: &hao::Module) -> Result<()> {
180        let bytes = module
181            .write()
182            .map_err(|e| Error::Other(format!("could not write {}: {}", module.name(), e)))?;
183        let name = match &module.assembly {
184            Some(assembly) => assembly.get().name.clone(),
185            None => module.name().trim_end_matches(".dll").to_string(),
186        };
187        self.load_assembly_bytes(&name, &bytes)
188    }
189
190    /// A native pointer to the static method `type_name::method` in `assembly`.
191    ///
192    /// On CoreCLR the method must be `[UnmanagedCallersOnly]`; for a method that
193    /// isn't, use [`method_pointer`](Self::method_pointer) instead, which calls
194    /// any method by JIT-compiling it. On Mono the returned thunk takes an extra
195    /// trailing `*mut *mut c_void` exception argument.
196    pub fn function_pointer(
197        &self,
198        assembly: &str,
199        type_name: &str,
200        method: &str,
201    ) -> Result<*const c_void> {
202        match &*self.0 {
203            #[cfg(feature = "coreclr")]
204            Inner::CoreClr(clr) => clr.function_pointer(assembly, type_name, method),
205            #[cfg(feature = "mono")]
206            Inner::Mono(mono) => mono.function_pointer(assembly, type_name, method),
207        }
208    }
209
210    /// A native-callable pointer to a static method, whether or not it is
211    /// `[UnmanagedCallersOnly]`. The method is JIT-compiled first, so IL patched
212    /// before the assembly was loaded takes effect.
213    ///
214    /// The pointer uses the managed calling convention, which matches a plain
215    /// `extern "C" fn(args) -> ret` for static methods with primitive and
216    /// pointer arguments. Unlike [`function_pointer`](Self::function_pointer),
217    /// it takes no trailing exception argument on either backend, so a managed
218    /// exception crosses it as an unhandled error.
219    pub fn method_pointer(
220        &self,
221        assembly: &str,
222        type_name: &str,
223        method: &str,
224    ) -> Result<*const c_void> {
225        match &*self.0 {
226            #[cfg(feature = "coreclr")]
227            Inner::CoreClr(clr) => clr.method_pointer(assembly, type_name, method),
228            #[cfg(feature = "mono")]
229            Inner::Mono(mono) => mono.method_pointer(assembly, type_name, method),
230        }
231    }
232
233    /// Like [`method_pointer`](Self::method_pointer), but resolves the type
234    /// from whichever `AssemblyLoadContext` actually loaded the assembly.
235    /// CoreCLR only.
236    pub fn method_pointer_from_loaded(
237        &self,
238        assembly: &str,
239        type_name: &str,
240        method: &str,
241    ) -> Result<*const c_void> {
242        match &*self.0 {
243            #[cfg(feature = "coreclr")]
244            Inner::CoreClr(clr) => clr.method_pointer_from_loaded(assembly, type_name, method),
245            #[cfg(feature = "mono")]
246            Inner::Mono(_) => Err(Error::Other(
247                "method_pointer_from_loaded is CoreCLR-only".into(),
248            )),
249        }
250    }
251}