1#[cfg(all(feature = "coreclr", target_arch = "x86_64"))]
13pub mod attach;
14pub mod bindings;
15pub mod console;
16#[cfg(feature = "coreclr")]
17mod coreclr;
18mod error;
19pub mod jit;
20#[cfg(feature = "coreclr")]
23mod loader;
24#[cfg(feature = "mono")]
25mod mono;
26#[cfg(feature = "coreclr")]
27pub mod profiler;
28#[cfg(feature = "reflect")]
29pub mod reflect;
30#[cfg(feature = "hao")]
31pub mod rewrite;
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!("hao-runtime requires a backend feature: enable `coreclr` (the default) or `mono`");
63
64enum Inner {
65 #[cfg(feature = "coreclr")]
66 CoreClr(coreclr::CoreClr),
67 #[cfg(feature = "mono")]
68 Mono(mono::Mono),
69}
70
71#[derive(Clone)]
73pub struct Runtime(Arc<Inner>);
74
75impl std::fmt::Debug for Runtime {
76 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
77 write!(f, "Runtime({:?})", self.backend())
78 }
79}
80
81impl Runtime {
82 #[cfg(feature = "coreclr")]
85 pub fn coreclr() -> Result<Self> {
86 Self::coreclr_with(&CoreClrOptions::default())
87 }
88
89 #[cfg(feature = "coreclr")]
91 pub fn coreclr_with(options: &CoreClrOptions) -> Result<Self> {
92 Self::coreclr_from(|| coreclr::CoreClr::new(options))
93 }
94
95 #[cfg(feature = "coreclr")]
102 pub fn coreclr_attach(
103 host_handle: *mut c_void,
104 domain_id: u32,
105 create_delegate: *const c_void,
106 major: u16,
107 ) -> Result<Self> {
108 Self::coreclr_from(|| {
109 coreclr::CoreClr::attach(host_handle, domain_id, create_delegate, major)
110 })
111 }
112
113 #[cfg(feature = "coreclr")]
114 fn coreclr_from(make: impl FnOnce() -> Result<coreclr::CoreClr>) -> Result<Self> {
115 static RUNTIME: std::sync::Mutex<Option<Runtime>> = std::sync::Mutex::new(None);
116 let mut runtime = RUNTIME.lock().unwrap_or_else(|e| e.into_inner());
117 if let Some(runtime) = runtime.as_ref() {
118 return Ok(runtime.clone());
119 }
120 let started = Runtime(Arc::new(Inner::CoreClr(make()?)));
121 *runtime = Some(started.clone());
122 Ok(started)
123 }
124
125 #[cfg(feature = "mono")]
127 pub fn mono(options: &MonoOptions) -> Result<Self> {
128 Self::mono_with(|| mono::Mono::new(options))
129 }
130
131 #[cfg(feature = "mono")]
136 pub fn mono_attach(options: &MonoOptions) -> Result<Self> {
137 Self::mono_with(|| mono::Mono::attach(options))
138 }
139
140 #[cfg(feature = "mono")]
141 fn mono_with(make: impl FnOnce() -> Result<mono::Mono>) -> Result<Self> {
142 static RUNTIME: std::sync::Mutex<Option<Runtime>> = std::sync::Mutex::new(None);
143 let mut runtime = RUNTIME.lock().unwrap_or_else(|e| e.into_inner());
144 if let Some(runtime) = runtime.as_ref() {
145 return Ok(runtime.clone());
146 }
147 let started = Runtime(Arc::new(Inner::Mono(make()?)));
148 *runtime = Some(started.clone());
149 Ok(started)
150 }
151
152 pub fn backend(&self) -> Backend {
153 match &*self.0 {
154 #[cfg(feature = "coreclr")]
155 Inner::CoreClr(_) => Backend::CoreClr,
156 #[cfg(feature = "mono")]
157 Inner::Mono(_) => Backend::Mono,
158 }
159 }
160
161 pub fn attach_thread(&self) {
164 match &*self.0 {
165 #[cfg(feature = "coreclr")]
166 Inner::CoreClr(_) => {}
167 #[cfg(feature = "mono")]
168 Inner::Mono(mono) => mono.attach_thread(),
169 }
170 }
171
172 pub fn load_assembly(&self, path: impl AsRef<Path>) -> Result<()> {
174 match &*self.0 {
175 #[cfg(feature = "coreclr")]
176 Inner::CoreClr(clr) => clr.load_assembly(path.as_ref()),
177 #[cfg(feature = "mono")]
178 Inner::Mono(mono) => mono.load_assembly(path.as_ref()),
179 }
180 }
181
182 pub fn load_assembly_bytes(&self, name: &str, bytes: &[u8]) -> Result<()> {
184 match &*self.0 {
185 #[cfg(feature = "coreclr")]
186 Inner::CoreClr(clr) => {
187 let _ = name;
188 clr.load_assembly_bytes(bytes)
189 }
190 #[cfg(feature = "mono")]
191 Inner::Mono(mono) => mono.load_assembly_bytes(name, bytes),
192 }
193 }
194
195 #[cfg(feature = "hao")]
197 pub fn load_module(&self, module: &hao::Module) -> Result<()> {
198 let bytes = module
199 .write()
200 .map_err(|e| Error::Other(format!("could not write {}: {}", module.name(), e)))?;
201 let name = match &module.assembly {
202 Some(assembly) => assembly.get().name.clone(),
203 None => module.name().trim_end_matches(".dll").to_string(),
204 };
205 self.load_assembly_bytes(&name, &bytes)
206 }
207
208 pub fn function_pointer(
215 &self,
216 assembly: &str,
217 type_name: &str,
218 method: &str,
219 ) -> Result<*const c_void> {
220 match &*self.0 {
221 #[cfg(feature = "coreclr")]
222 Inner::CoreClr(clr) => clr.function_pointer(assembly, type_name, method),
223 #[cfg(feature = "mono")]
224 Inner::Mono(mono) => mono.function_pointer(assembly, type_name, method),
225 }
226 }
227
228 pub fn method_pointer(
238 &self,
239 assembly: &str,
240 type_name: &str,
241 method: &str,
242 ) -> Result<*const c_void> {
243 match &*self.0 {
244 #[cfg(feature = "coreclr")]
245 Inner::CoreClr(clr) => clr.method_pointer(assembly, type_name, method),
246 #[cfg(feature = "mono")]
247 Inner::Mono(mono) => mono.method_pointer(assembly, type_name, method),
248 }
249 }
250
251 pub fn method_pointer_from_loaded(
257 &self,
258 assembly: &str,
259 type_name: &str,
260 method: &str,
261 ) -> Result<*const c_void> {
262 match &*self.0 {
263 #[cfg(feature = "coreclr")]
264 Inner::CoreClr(clr) => clr.method_pointer_from_loaded(assembly, type_name, method),
265 #[cfg(feature = "mono")]
266 Inner::Mono(mono) => mono.method_pointer(assembly, type_name, method),
267 }
268 }
269
270 #[cfg(feature = "hao")]
278 pub fn corlib_method_pointer(
279 &self,
280 method: hao::dotnet::entries::well_known::WellKnownMethod,
281 ) -> Result<*const c_void> {
282 let (namespace, name) = method.declaring().full_name();
283 match &*self.0 {
284 #[cfg(feature = "coreclr")]
285 Inner::CoreClr(clr) => {
286 let full_name = if namespace.is_empty() {
287 name.to_string()
288 } else {
289 format!("{namespace}.{name}")
290 };
291 clr.find_method_from_loaded(
292 "System.Private.CoreLib",
293 &full_name,
294 method.method_name(),
295 method.param_count() as i32,
296 )
297 }
298 #[cfg(feature = "mono")]
299 Inner::Mono(mono) => mono.corlib_method_pointer(
300 namespace,
301 name,
302 method.method_name(),
303 method.param_count() as i32,
304 ),
305 }
306 }
307
308 pub fn find_method_from_loaded(
311 &self,
312 assembly: &str,
313 type_name: &str,
314 method: &str,
315 param_count: i32,
316 ) -> Result<*const c_void> {
317 match &*self.0 {
318 #[cfg(feature = "coreclr")]
319 Inner::CoreClr(clr) => {
320 clr.find_method_from_loaded(assembly, type_name, method, param_count)
321 }
322 #[cfg(feature = "mono")]
323 Inner::Mono(mono) => mono.find_method(assembly, type_name, method, param_count),
324 }
325 }
326
327 #[cfg(target_arch = "x86_64")]
332 pub fn invoke(&self, ptr: usize, args: &[u64]) -> Result<u64> {
333 match &*self.0 {
334 #[cfg(feature = "coreclr")]
335 Inner::CoreClr(clr) => clr.invoke(ptr, args),
336 #[cfg(feature = "mono")]
337 Inner::Mono(_) => Ok(unsafe { jit::call_native(ptr, args) }),
338 }
339 }
340
341 #[cfg(target_arch = "x86_64")]
343 pub fn invoke_float(&self, ptr: usize, args: &[u64]) -> Result<f64> {
344 match &*self.0 {
345 #[cfg(feature = "coreclr")]
346 Inner::CoreClr(clr) => clr.invoke_float(ptr, args),
347 #[cfg(feature = "mono")]
348 Inner::Mono(_) => Ok(unsafe { jit::call_native_float(ptr, args) }),
349 }
350 }
351
352 pub fn suppress_gc(&self, budget: i64) -> Result<bool> {
358 match &*self.0 {
359 #[cfg(feature = "coreclr")]
360 Inner::CoreClr(clr) => clr.suppress_gc(budget),
361 #[cfg(feature = "mono")]
362 Inner::Mono(_) => {
363 let _ = budget;
364 Ok(false)
365 }
366 }
367 }
368
369 pub fn resume_gc(&self) -> Result<()> {
374 match &*self.0 {
375 #[cfg(feature = "coreclr")]
376 Inner::CoreClr(clr) => clr.resume_gc(),
377 #[cfg(feature = "mono")]
378 Inner::Mono(_) => Ok(()),
379 }
380 }
381
382 pub fn warm_enumerate(&self) -> Result<()> {
390 match &*self.0 {
391 #[cfg(feature = "coreclr")]
392 Inner::CoreClr(clr) => clr.warm_enumerate(),
393 #[cfg(feature = "mono")]
394 Inner::Mono(mono) => mono.warm_enumerate(),
395 }
396 }
397
398 pub fn enumerate(&self, obj: usize) -> Result<Vec<usize>> {
412 match &*self.0 {
413 #[cfg(feature = "coreclr")]
414 Inner::CoreClr(clr) => clr.enumerate(obj),
415 #[cfg(feature = "mono")]
416 Inner::Mono(mono) => mono.enumerate(obj),
417 }
418 }
419
420 pub fn dotnet_major(&self) -> Option<u16> {
423 match &*self.0 {
424 #[cfg(feature = "coreclr")]
425 Inner::CoreClr(clr) => Some(clr.major()),
426 #[cfg(feature = "mono")]
427 Inner::Mono(_) => None,
428 }
429 }
430
431 pub fn type_names(&self, assembly: &str) -> Result<Vec<String>> {
433 match &*self.0 {
434 #[cfg(feature = "coreclr")]
435 Inner::CoreClr(clr) => clr.type_names(assembly),
436 #[cfg(feature = "mono")]
437 Inner::Mono(mono) => mono.type_names(assembly),
438 }
439 }
440
441 pub fn method_names(&self, assembly: &str, type_name: &str) -> Result<Vec<String>> {
443 match &*self.0 {
444 #[cfg(feature = "coreclr")]
445 Inner::CoreClr(clr) => clr.method_names(assembly, type_name),
446 #[cfg(feature = "mono")]
447 Inner::Mono(mono) => mono.method_names(assembly, type_name),
448 }
449 }
450}