1pub 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#[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#[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#[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#[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 #[cfg(feature = "coreclr")]
87 pub fn coreclr() -> Result<Self> {
88 Self::coreclr_with(&CoreClrOptions::default())
89 }
90
91 #[cfg(feature = "coreclr")]
93 pub fn coreclr_with(options: &CoreClrOptions) -> Result<Self> {
94 Self::coreclr_from(|| coreclr::CoreClr::new(options))
95 }
96
97 #[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 #[cfg(feature = "mono")]
129 pub fn mono(options: &MonoOptions) -> Result<Self> {
130 Self::mono_with(|| mono::Mono::new(options))
131 }
132
133 #[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 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 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 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 #[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 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 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 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 #[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 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 #[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 #[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 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 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 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 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 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 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 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}