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