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