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