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    // `Hao.Loader::Enumerate`, JIT-compiled and cached by `warm_enumerate`.
307    // Resolution is `[UnmanagedCallersOnly]`-based and must happen off a
308    // cooperative-mode thread; the cached pointer is then callable on one.
309    enumerate: OnceLock<usize>,
310}
311
312// The ComponentActivator delegates are thread safe.
313unsafe impl Send for CoreClr {}
314unsafe impl Sync for CoreClr {}
315
316impl CoreClr {
317    pub fn new(options: &CoreClrOptions) -> Result<Self> {
318        let framework = Framework::find(options)?;
319        let path = framework.dir.join(coreclr_name());
320        let coreclr = unsafe { Library::new(&path) }
321            .map_err(|e| Error::Library(path.display().to_string(), e))?;
322        let host = Host::start(&coreclr, &framework)?;
323        Ok(Self {
324            major: framework.major,
325            get_function_pointer: host.activator_delegate("GetFunctionPointer")?,
326            load_assembly_bytes: host.activator_delegate("LoadAssemblyBytes")?,
327            loader: OnceLock::new(),
328            enumerate: OnceLock::new(),
329            _coreclr: Some(coreclr),
330        })
331    }
332
333    /// Attaches to a CoreCLR another host (e.g. a game) already started in this
334    /// process, using the host handle, domain and `coreclr_create_delegate`
335    /// captured as it initialised. `major` is the .NET major version (e.g. 9),
336    /// used to build the loader assembly. No new runtime is started.
337    pub fn attach(
338        handle: *mut c_void,
339        domain: u32,
340        create_delegate: *const c_void,
341        major: u16,
342    ) -> Result<Self> {
343        let host = Host {
344            handle,
345            domain,
346            create_delegate: unsafe {
347                std::mem::transmute::<*const c_void, CreateDelegate>(create_delegate)
348            },
349        };
350        Ok(Self {
351            major,
352            get_function_pointer: host.activator_delegate("GetFunctionPointer")?,
353            load_assembly_bytes: host.activator_delegate("LoadAssemblyBytes")?,
354            loader: OnceLock::new(),
355            enumerate: OnceLock::new(),
356            _coreclr: None,
357        })
358    }
359
360    /// The `Hao.Loader` helpers, generated with hao and loaded once.
361    fn loader(&self) -> Result<&Loader> {
362        if let Some(loader) = self.loader.get() {
363            return Ok(loader);
364        }
365        self.load_assembly_bytes(&crate::loader::loader_assembly(self.major)?)?;
366        let load_from = self.function_pointer(LOADER, "Hao.Loader", "LoadFrom")?;
367        let get_method = self.function_pointer(LOADER, "Hao.Loader", "GetMethod")?;
368        let get_method_from_loaded =
369            self.function_pointer(LOADER, "Hao.Loader", "GetMethodFromLoaded")?;
370        let find_method_from_loaded =
371            self.function_pointer(LOADER, "Hao.Loader", "FindMethodFromLoaded")?;
372        let invoke = self.function_pointer(LOADER, "Hao.Loader", "Invoke")?;
373        let invoke_float = self.function_pointer(LOADER, "Hao.Loader", "InvokeFloat")?;
374        let get_type_names = self.function_pointer(LOADER, "Hao.Loader", "GetTypeNames")?;
375        let get_method_names = self.function_pointer(LOADER, "Hao.Loader", "GetMethodNames")?;
376        let suppress_gc = self.function_pointer(LOADER, "Hao.Loader", "SuppressGC")?;
377        let resume_gc = self.function_pointer(LOADER, "Hao.Loader", "ResumeGC")?;
378        Ok(self.loader.get_or_init(|| unsafe {
379            Loader {
380                load_from: std::mem::transmute::<*const c_void, LoadFrom>(load_from),
381                get_method: std::mem::transmute::<*const c_void, GetMethod>(get_method),
382                get_method_from_loaded: std::mem::transmute::<*const c_void, GetMethodFromLoaded>(
383                    get_method_from_loaded,
384                ),
385                find_method_from_loaded: std::mem::transmute::<*const c_void, FindMethodFromLoaded>(
386                    find_method_from_loaded,
387                ),
388                invoke: std::mem::transmute::<*const c_void, ManagedInvoke>(invoke),
389                invoke_float: std::mem::transmute::<*const c_void, ManagedInvokeFloat>(
390                    invoke_float,
391                ),
392                get_type_names: std::mem::transmute::<*const c_void, GetTypeNames>(
393                    get_type_names,
394                ),
395                get_method_names: std::mem::transmute::<*const c_void, GetMethodNames>(
396                    get_method_names,
397                ),
398                suppress_gc: std::mem::transmute::<*const c_void, SuppressGC>(suppress_gc),
399                resume_gc: std::mem::transmute::<*const c_void, ResumeGC>(resume_gc),
400            }
401        }))
402    }
403
404    /// Loads with `Assembly.LoadFrom`, so dependencies next to the assembly
405    /// are found. `ComponentActivator.LoadAssembly` would need hostfxr.
406    pub fn load_assembly(&self, path: &Path) -> Result<()> {
407        let load_from = self.loader()?.load_from;
408        check("Assembly.LoadFrom", unsafe {
409            load_from(wide(&path.to_string_lossy()).as_ptr())
410        })
411    }
412
413    /// A native-callable pointer to a static method, whether or not it is
414    /// `[UnmanagedCallersOnly]`. The method is JIT-compiled first (so IL patched
415    /// before the assembly was loaded takes effect), and the pointer uses the
416    /// managed calling convention, which matches the C ABI for static methods
417    /// with primitive and pointer arguments.
418    pub fn method_pointer(
419        &self,
420        assembly: &str,
421        type_name: &str,
422        method: &str,
423    ) -> Result<*const c_void> {
424        let full_name = wide(&format!("{}, {}", type_name, assembly));
425        let name = wide(method);
426        let pointer = unsafe { (self.loader()?.get_method)(full_name.as_ptr(), name.as_ptr()) };
427        if pointer.is_null() {
428            return Err(Error::NotFound(format!(
429                "method {}::{} (is it a unique static method?)",
430                type_name, method
431            )));
432        }
433        Ok(pointer)
434    }
435
436    /// Like [`method_pointer`](Self::method_pointer), but finds the type by
437    /// iterating `AppDomain.CurrentDomain.GetAssemblies()` instead of
438    /// `Type.GetType`. This resolves the type from whichever
439    /// `AssemblyLoadContext` actually loaded the assembly (e.g. a game host's
440    /// ALC), rather than the default ALC where the helper assembly lives.
441    pub fn method_pointer_from_loaded(
442        &self,
443        assembly: &str,
444        type_name: &str,
445        method: &str,
446    ) -> Result<*const c_void> {
447        let type_name_w = wide(type_name);
448        let method_w = wide(method);
449        let asm_w = wide(assembly);
450        let pointer = unsafe {
451            (self.loader()?.get_method_from_loaded)(
452                type_name_w.as_ptr(),
453                method_w.as_ptr(),
454                asm_w.as_ptr(),
455            )
456        };
457        if pointer.is_null() {
458            return Err(Error::NotFound(format!(
459                "method {}::{} in loaded assembly \"{}\"",
460                type_name, method, assembly
461            )));
462        }
463        Ok(pointer)
464    }
465
466    /// Like [`method_pointer_from_loaded`](Self::method_pointer_from_loaded)
467    /// but matches by parameter count, so it works with overloaded methods.
468    pub fn find_method_from_loaded(
469        &self,
470        assembly: &str,
471        type_name: &str,
472        method: &str,
473        param_count: i32,
474    ) -> Result<*const c_void> {
475        let type_name_w = wide(type_name);
476        let method_w = wide(method);
477        let asm_w = wide(assembly);
478        let pointer = unsafe {
479            (self.loader()?.find_method_from_loaded)(
480                type_name_w.as_ptr(),
481                method_w.as_ptr(),
482                asm_w.as_ptr(),
483                param_count,
484            )
485        };
486        if pointer.is_null() {
487            return Err(Error::NotFound(format!(
488                "method {}::{}({} params) in loaded assembly \"{}\"",
489                type_name, method, param_count, assembly
490            )));
491        }
492        Ok(pointer)
493    }
494
495    pub fn load_assembly_bytes(&self, bytes: &[u8]) -> Result<()> {
496        let code = unsafe {
497            (self.load_assembly_bytes)(
498                bytes.as_ptr(),
499                bytes.len(),
500                ptr::null(),
501                0,
502                ptr::null_mut(),
503                ptr::null_mut(),
504            )
505        };
506        check("load_assembly_bytes", code)
507    }
508
509    /// A pointer to a static `[UnmanagedCallersOnly]` method.
510    pub fn function_pointer(
511        &self,
512        assembly: &str,
513        type_name: &str,
514        method: &str,
515    ) -> Result<*const c_void> {
516        let full_type = wide(&format!("{}, {}", type_name, assembly));
517        let method_name = wide(method);
518        let mut function = ptr::null_mut();
519        let code = unsafe {
520            (self.get_function_pointer)(
521                full_type.as_ptr(),
522                method_name.as_ptr(),
523                UNMANAGED_CALLERS_ONLY,
524                ptr::null_mut(),
525                ptr::null_mut(),
526                &mut function,
527            )
528        };
529        // GetFunctionPointer returns COR_E_INVALIDOPERATION for a method that
530        // isn't [UnmanagedCallersOnly]. Point at the method that handles those.
531        if code as u32 == 0x8013_1509 {
532            return Err(Error::Other(format!(
533                "{}::{} is not [UnmanagedCallersOnly]; use Runtime::method_pointer to call it",
534                type_name, method
535            )));
536        }
537        check("get_function_pointer", code)?;
538        Ok(function)
539    }
540
541    /// Calls a managed method pointer through a P/Invoke wrapper that
542    /// auto-registers the calling thread with the CLR's GC.
543    pub fn invoke(&self, ptr: usize, args: &[u64]) -> Result<u64> {
544        let loader = self.loader()?;
545        let a = |i: usize| args.get(i).copied().unwrap_or(0);
546        Ok(unsafe { (loader.invoke)(ptr, a(0), a(1), a(2), a(3), a(4), a(5)) })
547    }
548
549    /// Like [`invoke`](Self::invoke) but returns `f64` for floating-point
550    /// return values.
551    pub fn invoke_float(&self, ptr: usize, args: &[u64]) -> Result<f64> {
552        let loader = self.loader()?;
553        let a = |i: usize| args.get(i).copied().unwrap_or(0);
554        Ok(unsafe { (loader.invoke_float)(ptr, a(0), a(1), a(2), a(3), a(4), a(5)) })
555    }
556
557    /// Requests a no-GC region for the next `budget` bytes of managed
558    /// allocation.  Returns `true` if the runtime agreed to suppress GC.
559    /// Safe to call from any thread — the managed wrapper catches exceptions.
560    pub fn suppress_gc(&self, budget: i64) -> Result<bool> {
561        let loader = self.loader()?;
562        Ok(unsafe { (loader.suppress_gc)(budget) } != 0)
563    }
564
565    /// Ends a no-GC region previously started by [`suppress_gc`](Self::suppress_gc).
566    /// No-op if no region is active (the managed wrapper catches the exception).
567    pub fn resume_gc(&self) -> Result<()> {
568        let loader = self.loader()?;
569        unsafe { (loader.resume_gc)() };
570        Ok(())
571    }
572
573    /// JIT-compiles and caches `Hao.Loader::Enumerate` so [`enumerate`](Self::enumerate)
574    /// can call it from a cooperative-mode thread. Resolution goes through the
575    /// `[UnmanagedCallersOnly]` loader helpers, so this MUST be called off such a
576    /// thread (e.g. at init). Idempotent.
577    pub fn warm_enumerate(&self) -> Result<()> {
578        if self.enumerate.get().is_some() {
579            return Ok(());
580        }
581        let ptr = self.method_pointer(LOADER, "Hao.Loader", "Enumerate")? as usize;
582        let _ = self.enumerate.set(ptr);
583        Ok(())
584    }
585
586    /// Materializes any managed `IEnumerable` into the addresses of its elements,
587    /// by calling the `Hao.Loader::Enumerate` helper (a JIT-compiled `foreach`)
588    /// and reading the resulting `object[]`.
589    ///
590    /// Call [`warm_enumerate`](Self::warm_enumerate) once off a cooperative-mode
591    /// thread first; this call itself must run ON the cooperative (game) thread,
592    /// like any [`method_pointer`](Self::method_pointer) call. The returned
593    /// addresses are read while the thread holds the array with no safepoint in
594    /// between, so the GC cannot move it mid-read.
595    pub fn enumerate(&self, obj: usize) -> Result<Vec<usize>> {
596        if obj == 0 {
597            return Ok(Vec::new());
598        }
599        let ptr = *self.enumerate.get().ok_or_else(|| {
600            Error::Other("Enumerate not warmed; call warm_enumerate() off the game thread".into())
601        })?;
602        let func: Enumerate = unsafe { std::mem::transmute::<usize, Enumerate>(ptr) };
603        let array = unsafe { func(obj) };
604        if array == 0 {
605            return Ok(Vec::new());
606        }
607        // object[] layout: [MethodTable:8][length:i32 @ +8][pad][elements @ +16].
608        let len = unsafe { std::ptr::read((array + 8) as *const i32) };
609        if len <= 0 {
610            return Ok(Vec::new());
611        }
612        let len = len as usize;
613        let mut out = Vec::with_capacity(len);
614        for i in 0..len {
615            out.push(unsafe { std::ptr::read((array + 16 + i * 8) as *const usize) });
616        }
617        Ok(out)
618    }
619
620    /// The .NET major version this runtime was started or attached with.
621    pub fn major(&self) -> u16 {
622        self.major
623    }
624
625    /// Returns `\n`-separated type full names from a loaded assembly.
626    pub fn type_names(&self, assembly: &str) -> Result<Vec<String>> {
627        let asm_w = wide(assembly);
628        let ptr = unsafe { (self.loader()?.get_type_names)(asm_w.as_ptr()) };
629        if ptr.is_null() {
630            return Err(Error::NotFound(format!(
631                "no types in loaded assembly \"{}\"",
632                assembly,
633            )));
634        }
635        let s = read_cotask_utf16(ptr);
636        Ok(s.lines().map(String::from).collect())
637    }
638
639    /// Returns `\n`-separated method names from a type in a loaded assembly.
640    pub fn method_names(&self, assembly: &str, type_name: &str) -> Result<Vec<String>> {
641        let type_w = wide(type_name);
642        let asm_w = wide(assembly);
643        let ptr = unsafe { (self.loader()?.get_method_names)(type_w.as_ptr(), asm_w.as_ptr()) };
644        if ptr.is_null() {
645            return Err(Error::NotFound(format!(
646                "no methods for {} in loaded assembly \"{}\"",
647                type_name, assembly,
648            )));
649        }
650        let s = read_cotask_utf16(ptr);
651        Ok(s.lines().map(String::from).collect())
652    }
653}
654
655/// Reads a null-terminated UTF-16 LE string from a `CoTaskMem`-allocated
656/// pointer and frees the memory.  `Marshal.StringToCoTaskMemUni` always
657/// writes UTF-16 on all platforms.
658fn read_cotask_utf16(ptr: *mut CharT) -> String {
659    extern "C" {
660        fn free(ptr: *mut c_void);
661    }
662    unsafe {
663        let mut len = 0usize;
664        let base = ptr as *const u16;
665        while *base.add(len) != 0 {
666            len += 1;
667        }
668        let slice = std::slice::from_raw_parts(base, len);
669        let result = String::from_utf16_lossy(slice);
670        free(ptr as *mut c_void);
671        result
672    }
673}
674
675const LOADER: &str = "Hao.Loader";
676