1use std::{
4 collections::HashMap,
5 ffi::{c_char, c_int, c_void, CString},
6 path::{Path, PathBuf},
7 sync::{Mutex, OnceLock},
8};
9
10use libloading::Library;
11
12use crate::error::{Error, Result};
13
14type Ptr = *mut c_void;
15
16#[derive(Debug, Clone, Default)]
18#[cfg_attr(feature = "reflect", derive(facet::Facet))]
19pub struct MonoOptions {
20 pub library: Option<PathBuf>,
23 pub assemblies_dir: Option<PathBuf>,
26 pub config_dir: Option<PathBuf>,
28}
29
30struct Api {
31 set_dirs: unsafe extern "C" fn(*const c_char, *const c_char),
32 jit_init_version: unsafe extern "C" fn(*const c_char, *const c_char) -> Ptr,
33 thread_attach: unsafe extern "C" fn(Ptr) -> Ptr,
34 domain_assembly_open: unsafe extern "C" fn(Ptr, *const c_char) -> Ptr,
35 image_open_from_data_with_name:
36 unsafe extern "C" fn(*const c_char, u32, c_int, *mut c_int, c_int, *const c_char) -> Ptr,
37 assembly_load_from_full: unsafe extern "C" fn(Ptr, *const c_char, *mut c_int, c_int) -> Ptr,
38 assembly_get_image: unsafe extern "C" fn(Ptr) -> Ptr,
39 class_from_name: unsafe extern "C" fn(Ptr, *const c_char, *const c_char) -> Ptr,
40 class_get_method_from_name: unsafe extern "C" fn(Ptr, *const c_char, c_int) -> Ptr,
41 method_get_unmanaged_thunk: unsafe extern "C" fn(Ptr) -> Ptr,
42 compile_method: unsafe extern "C" fn(Ptr) -> Ptr,
43 get_root_domain: unsafe extern "C" fn() -> Ptr,
44 #[allow(dead_code)]
48 object_get_class: unsafe extern "C" fn(Ptr) -> Ptr,
49 object_get_virtual_method: unsafe extern "C" fn(Ptr, Ptr) -> Ptr,
50 runtime_invoke: unsafe extern "C" fn(Ptr, Ptr, *mut Ptr, *mut Ptr) -> Ptr,
51 object_unbox: unsafe extern "C" fn(Ptr) -> Ptr,
52 class_get_methods: unsafe extern "C" fn(Ptr, *mut Ptr) -> Ptr,
53 method_get_name: unsafe extern "C" fn(Ptr) -> *const c_char,
54 class_get_name: unsafe extern "C" fn(Ptr) -> *const c_char,
55 class_get_namespace: unsafe extern "C" fn(Ptr) -> *const c_char,
56 image_get_table_rows: unsafe extern "C" fn(Ptr, c_int) -> c_int,
57 class_get: unsafe extern "C" fn(Ptr, u32) -> Ptr,
58 get_corlib: unsafe extern "C" fn() -> Ptr,
59}
60
61const MONO_TABLE_TYPEDEF: c_int = 2;
63const MONO_TOKEN_TYPE_DEF: u32 = 0x0200_0000;
65
66struct EnumMethods {
69 get_enumerator: usize,
70 move_next: usize,
71 get_current: usize,
72}
73
74pub(crate) struct Mono {
75 _library: Library,
76 api: Api,
77 domain: Ptr,
78 images: Mutex<HashMap<String, usize>>,
79 enum_methods: OnceLock<EnumMethods>,
80}
81
82unsafe impl Send for Mono {}
84unsafe impl Sync for Mono {}
85
86fn default_library() -> Option<PathBuf> {
87 let names: &[&str] = if cfg!(windows) {
88 &["mono-2.0-sgen.dll", "mono-2.0-bdwgc.dll"]
89 } else if cfg!(target_os = "macos") {
90 &["libmonosgen-2.0.dylib"]
91 } else {
92 &["libmonosgen-2.0.so", "libmonosgen-2.0.so.1"]
93 };
94 let dirs = [
95 "/usr/lib",
96 "/usr/local/lib",
97 "/usr/lib/x86_64-linux-gnu",
98 "/Library/Frameworks/Mono.framework/Versions/Current/lib",
99 r"C:\Program Files\Mono\bin",
100 ];
101 dirs.iter()
102 .flat_map(|d| names.iter().map(move |n| Path::new(d).join(n)))
103 .find(|p| p.exists())
104}
105
106fn cstring(value: &str) -> Result<CString> {
107 CString::new(value).map_err(|_| Error::Other(format!("{:?} contains a nul byte", value)))
108}
109
110fn cstr(ptr: *const c_char) -> String {
114 if ptr.is_null() {
115 return String::new();
116 }
117 unsafe { std::ffi::CStr::from_ptr(ptr) }
118 .to_string_lossy()
119 .into_owned()
120}
121
122impl Mono {
123 fn open(options: &MonoOptions) -> Result<(Library, Api)> {
126 let path = options
127 .library
128 .clone()
129 .or_else(default_library)
130 .ok_or_else(|| Error::NotFound("the Mono runtime library".into()))?;
131 let library = unsafe { Library::new(&path) }
132 .map_err(|e| Error::Library(path.display().to_string(), e))?;
133
134 macro_rules! symbol {
135 ($name:literal) => {
136 *unsafe { library.get(concat!($name, "\0").as_bytes()) }
137 .map_err(|e| Error::Library($name.into(), e))?
138 };
139 }
140 let api = Api {
141 set_dirs: symbol!("mono_set_dirs"),
142 jit_init_version: symbol!("mono_jit_init_version"),
143 thread_attach: symbol!("mono_thread_attach"),
144 domain_assembly_open: symbol!("mono_domain_assembly_open"),
145 image_open_from_data_with_name: symbol!("mono_image_open_from_data_with_name"),
146 assembly_load_from_full: symbol!("mono_assembly_load_from_full"),
147 assembly_get_image: symbol!("mono_assembly_get_image"),
148 class_from_name: symbol!("mono_class_from_name"),
149 class_get_method_from_name: symbol!("mono_class_get_method_from_name"),
150 method_get_unmanaged_thunk: symbol!("mono_method_get_unmanaged_thunk"),
151 compile_method: symbol!("mono_compile_method"),
152 get_root_domain: symbol!("mono_get_root_domain"),
153 object_get_class: symbol!("mono_object_get_class"),
154 object_get_virtual_method: symbol!("mono_object_get_virtual_method"),
155 runtime_invoke: symbol!("mono_runtime_invoke"),
156 object_unbox: symbol!("mono_object_unbox"),
157 class_get_methods: symbol!("mono_class_get_methods"),
158 method_get_name: symbol!("mono_method_get_name"),
159 class_get_name: symbol!("mono_class_get_name"),
160 class_get_namespace: symbol!("mono_class_get_namespace"),
161 image_get_table_rows: symbol!("mono_image_get_table_rows"),
162 class_get: symbol!("mono_class_get"),
163 get_corlib: symbol!("mono_get_corlib"),
164 };
165 Ok((library, api))
166 }
167
168 pub fn attach(options: &MonoOptions) -> Result<Self> {
173 let (library, api) = Self::open(options)?;
174 let domain = unsafe { (api.get_root_domain)() };
175 if domain.is_null() {
176 return Err(Error::Other(
177 "no Mono runtime is running in this process".into(),
178 ));
179 }
180 unsafe { (api.thread_attach)(domain) };
181 Ok(Self {
182 _library: library,
183 api,
184 domain,
185 images: Mutex::new(HashMap::new()),
186 enum_methods: OnceLock::new(),
187 })
188 }
189
190 pub fn new(options: &MonoOptions) -> Result<Self> {
191 let (library, api) = Self::open(options)?;
192
193 let assemblies = options
194 .assemblies_dir
195 .as_ref()
196 .map(|p| cstring(&p.to_string_lossy()))
197 .transpose()?;
198 let config = options
199 .config_dir
200 .as_ref()
201 .map(|p| cstring(&p.to_string_lossy()))
202 .transpose()?;
203 let domain_name = cstring("hao")?;
204 let version = cstring("v4.0.30319")?;
205 let domain = unsafe {
206 if assemblies.is_some() || config.is_some() {
207 let default_config = cstring("/etc")?;
208 let default_assemblies = cstring("/usr/lib")?;
209 (api.set_dirs)(
210 assemblies.as_ref().unwrap_or(&default_assemblies).as_ptr(),
211 config.as_ref().unwrap_or(&default_config).as_ptr(),
212 );
213 }
214 (api.jit_init_version)(domain_name.as_ptr(), version.as_ptr())
215 };
216 if domain.is_null() {
217 return Err(Error::Other("mono_jit_init_version failed".into()));
218 }
219
220 Ok(Self {
221 _library: library,
222 api,
223 domain,
224 images: Mutex::new(HashMap::new()),
225 enum_methods: OnceLock::new(),
226 })
227 }
228
229 pub fn attach_thread(&self) {
231 unsafe { (self.api.thread_attach)(self.domain) };
232 }
233
234 fn register(&self, name: &str, assembly: Ptr) -> Result<()> {
235 let image = unsafe { (self.api.assembly_get_image)(assembly) };
236 if image.is_null() {
237 return Err(Error::Other(format!("{} has no image", name)));
238 }
239 self.images
240 .lock()
241 .unwrap_or_else(|e| e.into_inner())
242 .insert(name.to_owned(), image as usize);
243 Ok(())
244 }
245
246 pub fn load_assembly(&self, path: &Path) -> Result<()> {
247 self.attach_thread();
248 let name = path
249 .file_stem()
250 .map(|s| s.to_string_lossy().into_owned())
251 .unwrap_or_default();
252 let c_path = cstring(&path.to_string_lossy())?;
253 let assembly = unsafe { (self.api.domain_assembly_open)(self.domain, c_path.as_ptr()) };
254 if assembly.is_null() {
255 return Err(Error::NotFound(path.display().to_string()));
256 }
257 self.register(&name, assembly)
258 }
259
260 pub fn load_assembly_bytes(&self, name: &str, bytes: &[u8]) -> Result<()> {
261 self.attach_thread();
262 let c_name = cstring(name)?;
263 let mut status = 0;
264 unsafe {
265 let image = (self.api.image_open_from_data_with_name)(
266 bytes.as_ptr().cast(),
267 bytes.len() as u32,
268 1,
269 &mut status,
270 0,
271 c_name.as_ptr(),
272 );
273 if image.is_null() {
274 return Err(Error::Other(format!(
275 "could not open image {} ({})",
276 name, status
277 )));
278 }
279 let assembly =
280 (self.api.assembly_load_from_full)(image, c_name.as_ptr(), &mut status, 0);
281 if assembly.is_null() {
282 return Err(Error::Other(format!(
283 "could not load assembly {} ({})",
284 name, status
285 )));
286 }
287 self.register(name, assembly)
288 }
289 }
290
291 fn image(&self, assembly: &str) -> Result<Ptr> {
293 let image = *self
294 .images
295 .lock()
296 .unwrap_or_else(|e| e.into_inner())
297 .get(assembly)
298 .ok_or_else(|| Error::NotFound(format!("loaded assembly {}", assembly)))?;
299 Ok(image as Ptr)
300 }
301
302 fn resolve_method(&self, assembly: &str, type_name: &str, method: &str) -> Result<Ptr> {
304 self.resolve_method_arity(assembly, type_name, method, -1)
305 }
306
307 fn resolve_method_arity(
310 &self,
311 assembly: &str,
312 type_name: &str,
313 method: &str,
314 params: c_int,
315 ) -> Result<Ptr> {
316 self.attach_thread();
317 let image = self.image(assembly)?;
318 let (namespace, name) = type_name.rsplit_once('.').unwrap_or(("", type_name));
319 let (namespace, name, method_name) =
320 (cstring(namespace)?, cstring(name)?, cstring(method)?);
321 unsafe {
322 let class = (self.api.class_from_name)(image, namespace.as_ptr(), name.as_ptr());
323 if class.is_null() {
324 return Err(Error::NotFound(format!(
325 "type {} in {}",
326 type_name, assembly
327 )));
328 }
329 let method_ptr =
330 (self.api.class_get_method_from_name)(class, method_name.as_ptr(), params);
331 if method_ptr.is_null() {
332 return Err(Error::NotFound(format!("method {}::{}", type_name, method)));
333 }
334 Ok(method_ptr)
335 }
336 }
337
338 pub fn function_pointer(
339 &self,
340 assembly: &str,
341 type_name: &str,
342 method: &str,
343 ) -> Result<*const c_void> {
344 let method_ptr = self.resolve_method(assembly, type_name, method)?;
345 let thunk = unsafe { (self.api.method_get_unmanaged_thunk)(method_ptr) };
346 if thunk.is_null() {
347 return Err(Error::Other(format!(
348 "no unmanaged thunk for {}::{}",
349 type_name, method
350 )));
351 }
352 Ok(thunk)
353 }
354
355 pub fn method_pointer(
359 &self,
360 assembly: &str,
361 type_name: &str,
362 method: &str,
363 ) -> Result<*const c_void> {
364 let method_ptr = self.resolve_method(assembly, type_name, method)?;
365 let code = unsafe { (self.api.compile_method)(method_ptr) };
366 if code.is_null() {
367 return Err(Error::Other(format!(
368 "could not compile {}::{}",
369 type_name, method
370 )));
371 }
372 Ok(code)
373 }
374
375 pub fn find_method(
379 &self,
380 assembly: &str,
381 type_name: &str,
382 method: &str,
383 param_count: c_int,
384 ) -> Result<*const c_void> {
385 let method_ptr = self.resolve_method_arity(assembly, type_name, method, param_count)?;
386 let code = unsafe { (self.api.compile_method)(method_ptr) };
387 if code.is_null() {
388 return Err(Error::Other(format!(
389 "could not compile {}::{}({} params)",
390 type_name, method, param_count
391 )));
392 }
393 Ok(code)
394 }
395
396 #[cfg(feature = "hao")]
401 pub fn corlib_method_pointer(
402 &self,
403 namespace: &str,
404 name: &str,
405 method: &str,
406 arity: c_int,
407 ) -> Result<*const c_void> {
408 self.attach_thread();
409 let corlib = unsafe { (self.api.get_corlib)() };
410 if corlib.is_null() {
411 return Err(Error::Other("mono_get_corlib returned null".into()));
412 }
413 let (namespace_c, name_c, method_c) =
414 (cstring(namespace)?, cstring(name)?, cstring(method)?);
415 unsafe {
416 let class = (self.api.class_from_name)(corlib, namespace_c.as_ptr(), name_c.as_ptr());
417 if class.is_null() {
418 return Err(Error::NotFound(format!("corlib type {}.{}", namespace, name)));
419 }
420 let method_ptr = (self.api.class_get_method_from_name)(class, method_c.as_ptr(), arity);
421 if method_ptr.is_null() {
422 return Err(Error::NotFound(format!(
423 "corlib method {}.{}::{}",
424 namespace, name, method
425 )));
426 }
427 let code = (self.api.compile_method)(method_ptr);
428 if code.is_null() {
429 return Err(Error::Other(format!(
430 "could not compile corlib {}::{}",
431 name, method
432 )));
433 }
434 Ok(code)
435 }
436 }
437
438 pub fn type_names(&self, assembly: &str) -> Result<Vec<String>> {
442 self.attach_thread();
443 let image = self.image(assembly)?;
444 let rows = unsafe { (self.api.image_get_table_rows)(image, MONO_TABLE_TYPEDEF) };
445 let mut out = Vec::new();
446 for row in 2..=rows.max(0) as u32 {
448 let class = unsafe { (self.api.class_get)(image, MONO_TOKEN_TYPE_DEF | row) };
449 if class.is_null() {
450 continue;
451 }
452 let namespace = cstr(unsafe { (self.api.class_get_namespace)(class) });
453 let name = cstr(unsafe { (self.api.class_get_name)(class) });
454 out.push(if namespace.is_empty() {
455 name
456 } else {
457 format!("{}.{}", namespace, name)
458 });
459 }
460 Ok(out)
461 }
462
463 pub fn method_names(&self, assembly: &str, type_name: &str) -> Result<Vec<String>> {
466 self.attach_thread();
467 let image = self.image(assembly)?;
468 let (namespace, name) = type_name.rsplit_once('.').unwrap_or(("", type_name));
469 let (namespace_c, name_c) = (cstring(namespace)?, cstring(name)?);
470 let class =
471 unsafe { (self.api.class_from_name)(image, namespace_c.as_ptr(), name_c.as_ptr()) };
472 if class.is_null() {
473 return Err(Error::NotFound(format!(
474 "type {} in {}",
475 type_name, assembly
476 )));
477 }
478 let mut out = Vec::new();
479 let mut iter: Ptr = std::ptr::null_mut();
481 loop {
482 let method = unsafe { (self.api.class_get_methods)(class, &mut iter) };
483 if method.is_null() {
484 break;
485 }
486 out.push(cstr(unsafe { (self.api.method_get_name)(method) }));
487 }
488 Ok(out)
489 }
490
491 fn enum_methods(&self) -> Result<&EnumMethods> {
496 if let Some(methods) = self.enum_methods.get() {
497 return Ok(methods);
498 }
499 self.attach_thread();
500 let corlib = unsafe { (self.api.get_corlib)() };
501 if corlib.is_null() {
502 return Err(Error::Other("mono_get_corlib returned null".into()));
503 }
504 let resolve = |ns: &str, ty: &str, m: &str| -> Result<usize> {
505 let (ns_c, ty_c, m_c) = (cstring(ns)?, cstring(ty)?, cstring(m)?);
506 unsafe {
507 let class = (self.api.class_from_name)(corlib, ns_c.as_ptr(), ty_c.as_ptr());
508 if class.is_null() {
509 return Err(Error::NotFound(format!("corlib type {}.{}", ns, ty)));
510 }
511 let method = (self.api.class_get_method_from_name)(class, m_c.as_ptr(), 0);
512 if method.is_null() {
513 return Err(Error::NotFound(format!("corlib method {}.{}::{}", ns, ty, m)));
514 }
515 Ok(method as usize)
516 }
517 };
518 let methods = EnumMethods {
519 get_enumerator: resolve("System.Collections", "IEnumerable", "GetEnumerator")?,
520 move_next: resolve("System.Collections", "IEnumerator", "MoveNext")?,
521 get_current: resolve("System.Collections", "IEnumerator", "get_Current")?,
522 };
523 Ok(self.enum_methods.get_or_init(|| methods))
524 }
525
526 unsafe fn invoke_virtual(&self, target: Ptr, method: Ptr) -> Option<Ptr> {
535 let concrete = (self.api.object_get_virtual_method)(target, method);
536 if concrete.is_null() {
537 return None;
538 }
539 let mut exc: Ptr = std::ptr::null_mut();
540 let result = (self.api.runtime_invoke)(concrete, target, std::ptr::null_mut(), &mut exc);
541 if exc.is_null() {
542 Some(result)
543 } else {
544 None
545 }
546 }
547
548 pub fn warm_enumerate(&self) -> Result<()> {
552 self.enum_methods()?;
553 Ok(())
554 }
555
556 pub fn enumerate(&self, obj: usize) -> Result<Vec<usize>> {
566 self.attach_thread();
567 if obj == 0 {
568 return Ok(Vec::new());
569 }
570 let methods = self.enum_methods()?;
571 let target = obj as Ptr;
572 let enumerator = match unsafe { self.invoke_virtual(target, methods.get_enumerator as Ptr) }
574 {
575 Some(e) if !e.is_null() => e,
576 _ => return Ok(Vec::new()),
577 };
578 let mut out = Vec::new();
579 loop {
580 let moved = match unsafe { self.invoke_virtual(enumerator, methods.move_next as Ptr) } {
582 Some(m) if !m.is_null() => m,
583 _ => break,
584 };
585 let unboxed = unsafe { (self.api.object_unbox)(moved) };
586 if unboxed.is_null() || unsafe { std::ptr::read(unboxed as *const u8) } == 0 {
587 break;
588 }
589 match unsafe { self.invoke_virtual(enumerator, methods.get_current as Ptr) } {
591 Some(current) => out.push(current as usize),
592 None => break,
593 }
594 }
595 Ok(out)
596 }
597}