Skip to main content

hao_runtime/
coreclr.rs

1//! Hosting CoreCLR (.NET 8+) by loading `libcoreclr` directly.
2//!
3//! The runtime is configured in memory, and the delegates hostfxr would hand
4//! out come straight from `ComponentActivator` in `System.Private.CoreLib`, so
5//! no `.runtimeconfig.json` is needed.
6
7use std::{
8    ffi::{c_char, c_void, CString},
9    path::{Path, PathBuf},
10    ptr,
11    sync::OnceLock,
12};
13
14use libloading::Library;
15
16use crate::error::{Error, Result};
17
18/// A `char_t`, the character type the hosting APIs take. Wide on Windows.
19#[cfg(windows)]
20type CharT = u16;
21#[cfg(not(windows))]
22type CharT = c_char;
23
24/// Encodes a string as a nul-terminated `char_t` array.
25fn wide(value: &str) -> Vec<CharT> {
26    #[cfg(windows)]
27    return value.encode_utf16().chain([0]).collect();
28    #[cfg(not(windows))]
29    return value.bytes().map(|b| b as CharT).chain([0]).collect();
30}
31
32fn c_string(value: impl Into<Vec<u8>>) -> Result<CString> {
33    CString::new(value).map_err(|e| Error::Other(format!("nul byte in {:?}", e.into_vec())))
34}
35
36// coreclr_initialize / coreclr_create_delegate.
37type Initialize = unsafe extern "C" fn(
38    *const c_char,
39    *const c_char,
40    i32,
41    *const *const c_char,
42    *const *const c_char,
43    *mut *mut c_void,
44    *mut u32,
45) -> i32;
46type CreateDelegate = unsafe extern "C" fn(
47    *mut c_void,
48    u32,
49    *const c_char,
50    *const c_char,
51    *const c_char,
52    *mut *mut c_void,
53) -> i32;
54
55// Delegates from ComponentActivator.
56type GetFunctionPointer = unsafe extern "system" fn(
57    *const CharT,
58    *const CharT,
59    *const CharT,
60    *mut c_void,
61    *mut c_void,
62    *mut *mut c_void,
63) -> i32;
64type LoadAssemblyBytes =
65    unsafe extern "system" fn(*const u8, usize, *const u8, usize, *mut c_void, *mut c_void) -> i32;
66type LoadFrom = unsafe extern "system" fn(*const CharT) -> i32;
67type GetMethod = unsafe extern "system" fn(*const CharT, *const CharT) -> *mut c_void;
68type GetMethodFromLoaded =
69    unsafe extern "system" fn(*const CharT, *const CharT, *const CharT) -> *mut c_void;
70type FindMethodFromLoaded =
71    unsafe extern "system" fn(*const CharT, *const CharT, *const CharT, i32) -> *mut c_void;
72type ManagedInvoke = unsafe extern "system" fn(usize, u64, u64, u64, u64, u64, u64) -> u64;
73type ManagedInvokeFloat = unsafe extern "system" fn(usize, u64, u64, u64, u64, u64, u64) -> f64;
74type GetTypeNames = unsafe extern "system" fn(*const CharT) -> *mut CharT;
75type GetMethodNames = unsafe extern "system" fn(*const CharT, *const CharT) -> *mut CharT;
76type SuppressGC = unsafe extern "system" fn(i64) -> i64;
77type ResumeGC = unsafe extern "system" fn();
78/// `Hao.Loader::Enumerate` — `object[] Enumerate(object)`. Non-`[UnmanagedCallersOnly]`
79/// so it is callable from a cooperative-mode thread; both the argument and the
80/// returned `object[]` cross as the object's address.
81type Enumerate = unsafe extern "system" fn(usize) -> usize;
82
83/// `GetFunctionPointer`'s sentinel for a `[UnmanagedCallersOnly]` method.
84const UNMANAGED_CALLERS_ONLY: *const CharT = usize::MAX as *const CharT;
85
86const ACTIVATOR: &[u8] = b"Internal.Runtime.InteropServices.ComponentActivator\0";
87
88fn check(function: &'static str, code: i32) -> Result<()> {
89    // An HRESULT, negative on failure.
90    if code >= 0 {
91        Ok(())
92    } else {
93        Err(Error::Host {
94            function,
95            code: code as u32,
96        })
97    }
98}
99
100/// Where to find .NET and which framework version to run.
101#[derive(Debug, Clone, Default)]
102#[cfg_attr(feature = "reflect", derive(facet::Facet))]
103pub struct CoreClrOptions {
104    /// Defaults to `DOTNET_ROOT` or the standard install locations.
105    pub dotnet_root: Option<PathBuf>,
106    /// A `Microsoft.NETCore.App` version such as `9.0.21`. Defaults to the newest installed.
107    pub framework_version: Option<String>,
108}
109
110fn parse_version(name: &str) -> Vec<u32> {
111    name.split(['.', '-'])
112        .map(|p| p.parse().unwrap_or(0))
113        .collect()
114}
115
116fn newest_dir(dir: &Path) -> Option<PathBuf> {
117    std::fs::read_dir(dir)
118        .ok()?
119        .filter_map(|e| e.ok().map(|e| e.path()))
120        .filter(|p| p.is_dir())
121        .max_by_key(|p| parse_version(&p.file_name().unwrap_or_default().to_string_lossy()))
122}
123
124const DOTNET_ROOTS: &[&str] = &[
125    "/usr/share/dotnet",
126    "/usr/lib/dotnet",
127    "/usr/local/share/dotnet",
128    "/opt/dotnet",
129    r"C:\Program Files\dotnet",
130];
131
132pub fn find_dotnet_root() -> Option<PathBuf> {
133    std::env::var_os("DOTNET_ROOT")
134        .map(PathBuf::from)
135        .into_iter()
136        .chain(DOTNET_ROOTS.iter().map(PathBuf::from))
137        .find(|p| p.join("shared").join("Microsoft.NETCore.App").is_dir())
138}
139
140fn coreclr_name() -> &'static str {
141    if cfg!(windows) {
142        "coreclr.dll"
143    } else if cfg!(target_os = "macos") {
144        "libcoreclr.dylib"
145    } else {
146        "libcoreclr.so"
147    }
148}
149
150/// A resolved `Microsoft.NETCore.App` framework directory.
151struct Framework {
152    dir: PathBuf,
153    major: u16,
154}
155
156impl Framework {
157    fn find(options: &CoreClrOptions) -> Result<Self> {
158        let root = options
159            .dotnet_root
160            .clone()
161            .or_else(find_dotnet_root)
162            .ok_or_else(|| Error::NotFound("a .NET installation (set DOTNET_ROOT)".into()))?;
163        let frameworks = root.join("shared").join("Microsoft.NETCore.App");
164        let dir = match &options.framework_version {
165            Some(v) => frameworks.join(v),
166            None => newest_dir(&frameworks).ok_or_else(|| {
167                Error::NotFound(format!("Microsoft.NETCore.App in {}", root.display()))
168            })?,
169        };
170        let version = dir
171            .file_name()
172            .unwrap_or_default()
173            .to_string_lossy()
174            .into_owned();
175        let major = parse_version(&version)[0] as u16;
176        if major < 8 {
177            return Err(Error::Other(format!(
178                "hosting needs .NET 8 or newer, found {}",
179                version
180            )));
181        }
182        Ok(Self { dir, major })
183    }
184
185    /// The runtime properties CoreCLR needs: the trusted assemblies, where to
186    /// find native libraries, and the hosting switch the delegates need.
187    fn properties(&self) -> Result<Vec<(&'static str, String)>> {
188        let separator = if cfg!(windows) { ";" } else { ":" };
189        let trusted = std::fs::read_dir(&self.dir)?
190            .filter_map(|e| e.ok().map(|e| e.path()))
191            .filter(|p| p.extension().is_some_and(|e| e == "dll"))
192            .map(|p| p.to_string_lossy().into_owned())
193            .collect::<Vec<_>>()
194            .join(separator);
195        let exe = std::env::current_exe()?;
196        let app_dir = exe.parent().unwrap_or(Path::new("."));
197        Ok(vec![
198            ("TRUSTED_PLATFORM_ASSEMBLIES", trusted),
199            (
200                "NATIVE_DLL_SEARCH_DIRECTORIES",
201                format!("{}{}", self.dir.display(), separator),
202            ),
203            (
204                "APP_CONTEXT_BASE_DIRECTORY",
205                format!("{}{}", app_dir.display(), std::path::MAIN_SEPARATOR),
206            ),
207            (
208                "System.Runtime.InteropServices.EnableConsumingManagedCodeFromNativeHosting",
209                "true".into(),
210            ),
211        ])
212    }
213}
214
215/// A started runtime's host handle, used to fetch delegates.
216struct Host {
217    handle: *mut c_void,
218    domain: u32,
219    create_delegate: CreateDelegate,
220}
221
222impl Host {
223    /// Starts the runtime from `library` with `framework`'s properties.
224    fn start(library: &Library, framework: &Framework) -> Result<Self> {
225        let properties = framework.properties()?;
226        let keys = properties
227            .iter()
228            .map(|(k, _)| c_string(*k))
229            .collect::<Result<Vec<_>>>()?;
230        let values = properties
231            .iter()
232            .map(|(_, v)| c_string(v.as_str()))
233            .collect::<Result<Vec<_>>>()?;
234        let key_ptrs = keys.iter().map(|k| k.as_ptr()).collect::<Vec<_>>();
235        let value_ptrs = values.iter().map(|v| v.as_ptr()).collect::<Vec<_>>();
236        let exe = c_string(std::env::current_exe()?.to_string_lossy().into_owned())?;
237
238        unsafe {
239            let initialize: Initialize = *library
240                .get(b"coreclr_initialize\0")
241                .map_err(|e| Error::Library("coreclr_initialize".into(), e))?;
242            let create_delegate: CreateDelegate = *library
243                .get(b"coreclr_create_delegate\0")
244                .map_err(|e| Error::Library("coreclr_create_delegate".into(), e))?;
245            let (mut handle, mut domain) = (ptr::null_mut(), 0);
246            let code = initialize(
247                exe.as_ptr(),
248                c"hao-runtime".as_ptr(),
249                key_ptrs.len() as i32,
250                key_ptrs.as_ptr(),
251                value_ptrs.as_ptr(),
252                &mut handle,
253                &mut domain,
254            );
255            check("coreclr_initialize", code)?;
256            Ok(Self {
257                handle,
258                domain,
259                create_delegate,
260            })
261        }
262    }
263
264    /// A delegate for a static method of `ComponentActivator`.
265    fn activator_delegate<T>(&self, method: &'static str) -> Result<T> {
266        let name = c_string(method)?;
267        let mut delegate = ptr::null_mut();
268        let code = unsafe {
269            (self.create_delegate)(
270                self.handle,
271                self.domain,
272                c"System.Private.CoreLib".as_ptr(),
273                ACTIVATOR.as_ptr().cast(),
274                name.as_ptr(),
275                &mut delegate,
276            )
277        };
278        check(method, code)?;
279        assert_eq!(std::mem::size_of::<T>(), std::mem::size_of::<*mut c_void>());
280        Ok(unsafe { std::mem::transmute_copy(&delegate) })
281    }
282}
283
284/// The `Hao.Loader` helpers, built and loaded on first use.
285struct Loader {
286    load_from: LoadFrom,
287    get_method: GetMethod,
288    get_method_from_loaded: GetMethodFromLoaded,
289    find_method_from_loaded: FindMethodFromLoaded,
290    invoke: ManagedInvoke,
291    invoke_float: ManagedInvokeFloat,
292    get_type_names: GetTypeNames,
293    get_method_names: GetMethodNames,
294    suppress_gc: SuppressGC,
295    resume_gc: ResumeGC,
296}
297
298pub(crate) struct CoreClr {
299    // Kept so libcoreclr stays loaded when hao started it; `None` when attaching
300    // to a runtime the host already started and keeps alive.
301    _coreclr: Option<Library>,
302    major: u16,
303    get_function_pointer: GetFunctionPointer,
304    load_assembly_bytes: LoadAssemblyBytes,
305    loader: OnceLock<Loader>,
306    // Serializes `loader()` initialization so the loader assembly is loaded and
307    // its helpers resolved exactly once, even under concurrent first-calls.
308    loader_init: std::sync::Mutex<()>,
309    // `Hao.Loader::Enumerate`, JIT-compiled and cached by `warm_enumerate`.
310    // Resolution is `[UnmanagedCallersOnly]`-based and must happen off a
311    // cooperative-mode thread; the cached pointer is then callable on one.
312    enumerate: OnceLock<usize>,
313}
314
315// The ComponentActivator delegates are thread safe.
316unsafe impl Send for CoreClr {}
317unsafe impl Sync for CoreClr {}
318
319impl CoreClr {
320    pub fn new(options: &CoreClrOptions) -> Result<Self> {
321        let framework = Framework::find(options)?;
322        let path = framework.dir.join(coreclr_name());
323        let coreclr = unsafe { Library::new(&path) }
324            .map_err(|e| Error::Library(path.display().to_string(), e))?;
325        let host = Host::start(&coreclr, &framework)?;
326        Ok(Self {
327            major: framework.major,
328            get_function_pointer: host.activator_delegate("GetFunctionPointer")?,
329            load_assembly_bytes: host.activator_delegate("LoadAssemblyBytes")?,
330            loader: OnceLock::new(),
331            loader_init: std::sync::Mutex::new(()),
332            enumerate: OnceLock::new(),
333            _coreclr: Some(coreclr),
334        })
335    }
336
337    /// Attaches to a CoreCLR another host (e.g. a game) already started in this
338    /// process, using the host handle, domain and `coreclr_create_delegate`
339    /// captured as it initialised. `major` is the .NET major version (e.g. 9),
340    /// used to build the loader assembly. No new runtime is started.
341    pub fn attach(
342        handle: *mut c_void,
343        domain: u32,
344        create_delegate: *const c_void,
345        major: u16,
346    ) -> Result<Self> {
347        let host = Host {
348            handle,
349            domain,
350            create_delegate: unsafe {
351                std::mem::transmute::<*const c_void, CreateDelegate>(create_delegate)
352            },
353        };
354        Ok(Self {
355            major,
356            get_function_pointer: host.activator_delegate("GetFunctionPointer")?,
357            load_assembly_bytes: host.activator_delegate("LoadAssemblyBytes")?,
358            loader: OnceLock::new(),
359            loader_init: std::sync::Mutex::new(()),
360            enumerate: OnceLock::new(),
361            _coreclr: None,
362        })
363    }
364
365    /// The `Hao.Loader` helpers, generated with hao and loaded once.
366    fn loader(&self) -> Result<&Loader> {
367        if let Some(loader) = self.loader.get() {
368            return Ok(loader);
369        }
370        // Hold the init lock so the side-effecting assembly load and helper
371        // resolution below run exactly once, even if several threads reach here
372        // before initialization completes. Double-check after acquiring it.
373        let _guard = self.loader_init.lock().unwrap_or_else(|e| e.into_inner());
374        if let Some(loader) = self.loader.get() {
375            return Ok(loader);
376        }
377        self.load_assembly_bytes(&crate::loader::loader_assembly(self.major)?)?;
378        let load_from = self.function_pointer(LOADER, "Hao.Loader", "LoadFrom")?;
379        let get_method = self.function_pointer(LOADER, "Hao.Loader", "GetMethod")?;
380        let get_method_from_loaded =
381            self.function_pointer(LOADER, "Hao.Loader", "GetMethodFromLoaded")?;
382        let find_method_from_loaded =
383            self.function_pointer(LOADER, "Hao.Loader", "FindMethodFromLoaded")?;
384        let invoke = self.function_pointer(LOADER, "Hao.Loader", "Invoke")?;
385        let invoke_float = self.function_pointer(LOADER, "Hao.Loader", "InvokeFloat")?;
386        let get_type_names = self.function_pointer(LOADER, "Hao.Loader", "GetTypeNames")?;
387        let get_method_names = self.function_pointer(LOADER, "Hao.Loader", "GetMethodNames")?;
388        let suppress_gc = self.function_pointer(LOADER, "Hao.Loader", "SuppressGC")?;
389        let resume_gc = self.function_pointer(LOADER, "Hao.Loader", "ResumeGC")?;
390        let loader = unsafe {
391            Loader {
392                load_from: std::mem::transmute::<*const c_void, LoadFrom>(load_from),
393                get_method: std::mem::transmute::<*const c_void, GetMethod>(get_method),
394                get_method_from_loaded: std::mem::transmute::<*const c_void, GetMethodFromLoaded>(
395                    get_method_from_loaded,
396                ),
397                find_method_from_loaded: std::mem::transmute::<*const c_void, FindMethodFromLoaded>(
398                    find_method_from_loaded,
399                ),
400                invoke: std::mem::transmute::<*const c_void, ManagedInvoke>(invoke),
401                invoke_float: std::mem::transmute::<*const c_void, ManagedInvokeFloat>(
402                    invoke_float,
403                ),
404                get_type_names: std::mem::transmute::<*const c_void, GetTypeNames>(
405                    get_type_names,
406                ),
407                get_method_names: std::mem::transmute::<*const c_void, GetMethodNames>(
408                    get_method_names,
409                ),
410                suppress_gc: std::mem::transmute::<*const c_void, SuppressGC>(suppress_gc),
411                resume_gc: std::mem::transmute::<*const c_void, ResumeGC>(resume_gc),
412            }
413        };
414        // We hold the init lock and double-checked above, so no other thread can
415        // have set it; this initializes exactly once.
416        let _ = self.loader.set(loader);
417        Ok(self.loader.get().expect("loader just initialized"))
418    }
419
420    /// Loads with `Assembly.LoadFrom`, so dependencies next to the assembly
421    /// are found. `ComponentActivator.LoadAssembly` would need hostfxr.
422    pub fn load_assembly(&self, path: &Path) -> Result<()> {
423        let load_from = self.loader()?.load_from;
424        check("Assembly.LoadFrom", unsafe {
425            load_from(wide(&path.to_string_lossy()).as_ptr())
426        })
427    }
428
429    /// A native-callable pointer to a static method, whether or not it is
430    /// `[UnmanagedCallersOnly]`. The method is JIT-compiled first (so IL patched
431    /// before the assembly was loaded takes effect), and the pointer uses the
432    /// managed calling convention, which matches the C ABI for static methods
433    /// with primitive and pointer arguments.
434    pub fn method_pointer(
435        &self,
436        assembly: &str,
437        type_name: &str,
438        method: &str,
439    ) -> Result<*const c_void> {
440        let full_name = wide(&format!("{}, {}", type_name, assembly));
441        let name = wide(method);
442        let pointer = unsafe { (self.loader()?.get_method)(full_name.as_ptr(), name.as_ptr()) };
443        if pointer.is_null() {
444            return Err(Error::NotFound(format!(
445                "method {}::{} (is it a unique static method?)",
446                type_name, method
447            )));
448        }
449        Ok(pointer)
450    }
451
452    /// Like [`method_pointer`](Self::method_pointer), but finds the type by
453    /// iterating `AppDomain.CurrentDomain.GetAssemblies()` instead of
454    /// `Type.GetType`. This resolves the type from whichever
455    /// `AssemblyLoadContext` actually loaded the assembly (e.g. a game host's
456    /// ALC), rather than the default ALC where the helper assembly lives.
457    pub fn method_pointer_from_loaded(
458        &self,
459        assembly: &str,
460        type_name: &str,
461        method: &str,
462    ) -> Result<*const c_void> {
463        let type_name_w = wide(type_name);
464        let method_w = wide(method);
465        let asm_w = wide(assembly);
466        let pointer = unsafe {
467            (self.loader()?.get_method_from_loaded)(
468                type_name_w.as_ptr(),
469                method_w.as_ptr(),
470                asm_w.as_ptr(),
471            )
472        };
473        if pointer.is_null() {
474            return Err(Error::NotFound(format!(
475                "method {}::{} in loaded assembly \"{}\"",
476                type_name, method, assembly
477            )));
478        }
479        Ok(pointer)
480    }
481
482    /// Like [`method_pointer_from_loaded`](Self::method_pointer_from_loaded)
483    /// but matches by parameter count, so it works with overloaded methods.
484    pub fn find_method_from_loaded(
485        &self,
486        assembly: &str,
487        type_name: &str,
488        method: &str,
489        param_count: i32,
490    ) -> Result<*const c_void> {
491        let type_name_w = wide(type_name);
492        let method_w = wide(method);
493        let asm_w = wide(assembly);
494        let pointer = unsafe {
495            (self.loader()?.find_method_from_loaded)(
496                type_name_w.as_ptr(),
497                method_w.as_ptr(),
498                asm_w.as_ptr(),
499                param_count,
500            )
501        };
502        if pointer.is_null() {
503            return Err(Error::NotFound(format!(
504                "method {}::{}({} params) in loaded assembly \"{}\"",
505                type_name, method, param_count, assembly
506            )));
507        }
508        Ok(pointer)
509    }
510
511    pub fn load_assembly_bytes(&self, bytes: &[u8]) -> Result<()> {
512        let code = unsafe {
513            (self.load_assembly_bytes)(
514                bytes.as_ptr(),
515                bytes.len(),
516                ptr::null(),
517                0,
518                ptr::null_mut(),
519                ptr::null_mut(),
520            )
521        };
522        check("load_assembly_bytes", code)
523    }
524
525    /// A pointer to a static `[UnmanagedCallersOnly]` method.
526    pub fn function_pointer(
527        &self,
528        assembly: &str,
529        type_name: &str,
530        method: &str,
531    ) -> Result<*const c_void> {
532        let full_type = wide(&format!("{}, {}", type_name, assembly));
533        let method_name = wide(method);
534        let mut function = ptr::null_mut();
535        let code = unsafe {
536            (self.get_function_pointer)(
537                full_type.as_ptr(),
538                method_name.as_ptr(),
539                UNMANAGED_CALLERS_ONLY,
540                ptr::null_mut(),
541                ptr::null_mut(),
542                &mut function,
543            )
544        };
545        // GetFunctionPointer returns COR_E_INVALIDOPERATION for a method that
546        // isn't [UnmanagedCallersOnly]. Point at the method that handles those.
547        if code as u32 == 0x8013_1509 {
548            return Err(Error::Other(format!(
549                "{}::{} is not [UnmanagedCallersOnly]; use Runtime::method_pointer to call it",
550                type_name, method
551            )));
552        }
553        check("get_function_pointer", code)?;
554        Ok(function)
555    }
556
557    /// Calls a managed method pointer through a P/Invoke wrapper that
558    /// auto-registers the calling thread with the CLR's GC.
559    pub fn invoke(&self, ptr: usize, args: &[u64]) -> Result<u64> {
560        let loader = self.loader()?;
561        let a = |i: usize| args.get(i).copied().unwrap_or(0);
562        Ok(unsafe { (loader.invoke)(ptr, a(0), a(1), a(2), a(3), a(4), a(5)) })
563    }
564
565    /// Like [`invoke`](Self::invoke) but returns `f64` for floating-point
566    /// return values.
567    pub fn invoke_float(&self, ptr: usize, args: &[u64]) -> Result<f64> {
568        let loader = self.loader()?;
569        let a = |i: usize| args.get(i).copied().unwrap_or(0);
570        Ok(unsafe { (loader.invoke_float)(ptr, a(0), a(1), a(2), a(3), a(4), a(5)) })
571    }
572
573    /// Requests a no-GC region for the next `budget` bytes of managed
574    /// allocation.  Returns `true` if the runtime agreed to suppress GC.
575    /// Safe to call from any thread — the managed wrapper catches exceptions.
576    pub fn suppress_gc(&self, budget: i64) -> Result<bool> {
577        let loader = self.loader()?;
578        Ok(unsafe { (loader.suppress_gc)(budget) } != 0)
579    }
580
581    /// Ends a no-GC region previously started by [`suppress_gc`](Self::suppress_gc).
582    /// No-op if no region is active (the managed wrapper catches the exception).
583    pub fn resume_gc(&self) -> Result<()> {
584        let loader = self.loader()?;
585        unsafe { (loader.resume_gc)() };
586        Ok(())
587    }
588
589    /// JIT-compiles and caches `Hao.Loader::Enumerate` so [`enumerate`](Self::enumerate)
590    /// can call it from a cooperative-mode thread. Resolution goes through the
591    /// `[UnmanagedCallersOnly]` loader helpers, so this MUST be called off such a
592    /// thread (e.g. at init). Idempotent.
593    pub fn warm_enumerate(&self) -> Result<()> {
594        if self.enumerate.get().is_some() {
595            return Ok(());
596        }
597        let ptr = self.method_pointer(LOADER, "Hao.Loader", "Enumerate")? as usize;
598        let _ = self.enumerate.set(ptr);
599        Ok(())
600    }
601
602    /// Materializes any managed `IEnumerable` into the addresses of its elements,
603    /// by calling the `Hao.Loader::Enumerate` helper (a JIT-compiled `foreach`)
604    /// and reading the resulting `object[]`.
605    ///
606    /// Call [`warm_enumerate`](Self::warm_enumerate) once off a cooperative-mode
607    /// thread first; this call itself must run ON the cooperative (game) thread,
608    /// like any [`method_pointer`](Self::method_pointer) call. The returned
609    /// addresses are read while the thread holds the array with no safepoint in
610    /// between, so the GC cannot move it mid-read.
611    pub fn enumerate(&self, obj: usize) -> Result<Vec<usize>> {
612        if obj == 0 {
613            return Ok(Vec::new());
614        }
615        let ptr = *self.enumerate.get().ok_or_else(|| {
616            Error::Other("Enumerate not warmed; call warm_enumerate() off the game thread".into())
617        })?;
618        let func: Enumerate = unsafe { std::mem::transmute::<usize, Enumerate>(ptr) };
619        let array = unsafe { func(obj) };
620        if array == 0 {
621            return Ok(Vec::new());
622        }
623        // object[] layout: [MethodTable:8][length:i32 @ +8][pad][elements @ +16].
624        let len = unsafe { std::ptr::read((array + 8) as *const i32) };
625        if len <= 0 {
626            return Ok(Vec::new());
627        }
628        let len = len as usize;
629        let mut out = Vec::with_capacity(len);
630        for i in 0..len {
631            out.push(unsafe { std::ptr::read((array + 16 + i * 8) as *const usize) });
632        }
633        Ok(out)
634    }
635
636    /// The .NET major version this runtime was started or attached with.
637    pub fn major(&self) -> u16 {
638        self.major
639    }
640
641    /// Returns `\n`-separated type full names from a loaded assembly.
642    pub fn type_names(&self, assembly: &str) -> Result<Vec<String>> {
643        let asm_w = wide(assembly);
644        let ptr = unsafe { (self.loader()?.get_type_names)(asm_w.as_ptr()) };
645        if ptr.is_null() {
646            return Err(Error::NotFound(format!(
647                "no types in loaded assembly \"{}\"",
648                assembly,
649            )));
650        }
651        let s = read_cotask_utf16(ptr);
652        Ok(s.lines().map(String::from).collect())
653    }
654
655    /// Returns `\n`-separated method names from a type in a loaded assembly.
656    pub fn method_names(&self, assembly: &str, type_name: &str) -> Result<Vec<String>> {
657        let type_w = wide(type_name);
658        let asm_w = wide(assembly);
659        let ptr = unsafe { (self.loader()?.get_method_names)(type_w.as_ptr(), asm_w.as_ptr()) };
660        if ptr.is_null() {
661            return Err(Error::NotFound(format!(
662                "no methods for {} in loaded assembly \"{}\"",
663                type_name, assembly,
664            )));
665        }
666        let s = read_cotask_utf16(ptr);
667        Ok(s.lines().map(String::from).collect())
668    }
669}
670
671/// Reads a null-terminated UTF-16 LE string from a `CoTaskMem`-allocated
672/// pointer and frees the memory.  `Marshal.StringToCoTaskMemUni` always
673/// writes UTF-16 on all platforms.
674fn read_cotask_utf16(ptr: *mut CharT) -> String {
675    extern "C" {
676        fn free(ptr: *mut c_void);
677    }
678    unsafe {
679        let mut len = 0usize;
680        let base = ptr as *const u16;
681        while *base.add(len) != 0 {
682            len += 1;
683        }
684        let slice = std::slice::from_raw_parts(base, len);
685        let result = String::from_utf16_lossy(slice);
686        free(ptr as *mut c_void);
687        result
688    }
689}
690
691const LOADER: &str = "Hao.Loader";
692