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;
70
71/// `GetFunctionPointer`'s sentinel for a `[UnmanagedCallersOnly]` method.
72const UNMANAGED_CALLERS_ONLY: *const CharT = usize::MAX as *const CharT;
73
74const ACTIVATOR: &[u8] = b"Internal.Runtime.InteropServices.ComponentActivator\0";
75
76fn check(function: &'static str, code: i32) -> Result<()> {
77    // An HRESULT, negative on failure.
78    if code >= 0 {
79        Ok(())
80    } else {
81        Err(Error::Host {
82            function,
83            code: code as u32,
84        })
85    }
86}
87
88/// Where to find .NET and which framework version to run.
89#[derive(Debug, Clone, Default)]
90#[cfg_attr(feature = "reflect", derive(facet::Facet))]
91pub struct CoreClrOptions {
92    /// Defaults to `DOTNET_ROOT` or the standard install locations.
93    pub dotnet_root: Option<PathBuf>,
94    /// A `Microsoft.NETCore.App` version such as `9.0.21`. Defaults to the newest installed.
95    pub framework_version: Option<String>,
96}
97
98fn parse_version(name: &str) -> Vec<u32> {
99    name.split(['.', '-'])
100        .map(|p| p.parse().unwrap_or(0))
101        .collect()
102}
103
104fn newest_dir(dir: &Path) -> Option<PathBuf> {
105    std::fs::read_dir(dir)
106        .ok()?
107        .filter_map(|e| e.ok().map(|e| e.path()))
108        .filter(|p| p.is_dir())
109        .max_by_key(|p| parse_version(&p.file_name().unwrap_or_default().to_string_lossy()))
110}
111
112const DOTNET_ROOTS: &[&str] = &[
113    "/usr/share/dotnet",
114    "/usr/lib/dotnet",
115    "/usr/local/share/dotnet",
116    "/opt/dotnet",
117    r"C:\Program Files\dotnet",
118];
119
120pub fn find_dotnet_root() -> Option<PathBuf> {
121    std::env::var_os("DOTNET_ROOT")
122        .map(PathBuf::from)
123        .into_iter()
124        .chain(DOTNET_ROOTS.iter().map(PathBuf::from))
125        .find(|p| p.join("shared").join("Microsoft.NETCore.App").is_dir())
126}
127
128fn coreclr_name() -> &'static str {
129    if cfg!(windows) {
130        "coreclr.dll"
131    } else if cfg!(target_os = "macos") {
132        "libcoreclr.dylib"
133    } else {
134        "libcoreclr.so"
135    }
136}
137
138/// A resolved `Microsoft.NETCore.App` framework directory.
139struct Framework {
140    dir: PathBuf,
141    major: u16,
142}
143
144impl Framework {
145    fn find(options: &CoreClrOptions) -> Result<Self> {
146        let root = options
147            .dotnet_root
148            .clone()
149            .or_else(find_dotnet_root)
150            .ok_or_else(|| Error::NotFound("a .NET installation (set DOTNET_ROOT)".into()))?;
151        let frameworks = root.join("shared").join("Microsoft.NETCore.App");
152        let dir = match &options.framework_version {
153            Some(v) => frameworks.join(v),
154            None => newest_dir(&frameworks).ok_or_else(|| {
155                Error::NotFound(format!("Microsoft.NETCore.App in {}", root.display()))
156            })?,
157        };
158        let version = dir
159            .file_name()
160            .unwrap_or_default()
161            .to_string_lossy()
162            .into_owned();
163        let major = parse_version(&version)[0] as u16;
164        if major < 8 {
165            return Err(Error::Other(format!(
166                "hosting needs .NET 8 or newer, found {}",
167                version
168            )));
169        }
170        Ok(Self { dir, major })
171    }
172
173    /// The runtime properties CoreCLR needs: the trusted assemblies, where to
174    /// find native libraries, and the hosting switch the delegates need.
175    fn properties(&self) -> Result<Vec<(&'static str, String)>> {
176        let separator = if cfg!(windows) { ";" } else { ":" };
177        let trusted = std::fs::read_dir(&self.dir)?
178            .filter_map(|e| e.ok().map(|e| e.path()))
179            .filter(|p| p.extension().is_some_and(|e| e == "dll"))
180            .map(|p| p.to_string_lossy().into_owned())
181            .collect::<Vec<_>>()
182            .join(separator);
183        let exe = std::env::current_exe()?;
184        let app_dir = exe.parent().unwrap_or(Path::new("."));
185        Ok(vec![
186            ("TRUSTED_PLATFORM_ASSEMBLIES", trusted),
187            (
188                "NATIVE_DLL_SEARCH_DIRECTORIES",
189                format!("{}{}", self.dir.display(), separator),
190            ),
191            (
192                "APP_CONTEXT_BASE_DIRECTORY",
193                format!("{}{}", app_dir.display(), std::path::MAIN_SEPARATOR),
194            ),
195            (
196                "System.Runtime.InteropServices.EnableConsumingManagedCodeFromNativeHosting",
197                "true".into(),
198            ),
199        ])
200    }
201}
202
203/// A started runtime's host handle, used to fetch delegates.
204struct Host {
205    handle: *mut c_void,
206    domain: u32,
207    create_delegate: CreateDelegate,
208}
209
210impl Host {
211    /// Starts the runtime from `library` with `framework`'s properties.
212    fn start(library: &Library, framework: &Framework) -> Result<Self> {
213        let properties = framework.properties()?;
214        let keys = properties
215            .iter()
216            .map(|(k, _)| c_string(*k))
217            .collect::<Result<Vec<_>>>()?;
218        let values = properties
219            .iter()
220            .map(|(_, v)| c_string(v.as_str()))
221            .collect::<Result<Vec<_>>>()?;
222        let key_ptrs = keys.iter().map(|k| k.as_ptr()).collect::<Vec<_>>();
223        let value_ptrs = values.iter().map(|v| v.as_ptr()).collect::<Vec<_>>();
224        let exe = c_string(std::env::current_exe()?.to_string_lossy().into_owned())?;
225
226        unsafe {
227            let initialize: Initialize = *library
228                .get(b"coreclr_initialize\0")
229                .map_err(|e| Error::Library("coreclr_initialize".into(), e))?;
230            let create_delegate: CreateDelegate = *library
231                .get(b"coreclr_create_delegate\0")
232                .map_err(|e| Error::Library("coreclr_create_delegate".into(), e))?;
233            let (mut handle, mut domain) = (ptr::null_mut(), 0);
234            let code = initialize(
235                exe.as_ptr(),
236                c"hao-runtime".as_ptr(),
237                key_ptrs.len() as i32,
238                key_ptrs.as_ptr(),
239                value_ptrs.as_ptr(),
240                &mut handle,
241                &mut domain,
242            );
243            check("coreclr_initialize", code)?;
244            Ok(Self {
245                handle,
246                domain,
247                create_delegate,
248            })
249        }
250    }
251
252    /// A delegate for a static method of `ComponentActivator`.
253    fn activator_delegate<T>(&self, method: &'static str) -> Result<T> {
254        let name = c_string(method)?;
255        let mut delegate = ptr::null_mut();
256        let code = unsafe {
257            (self.create_delegate)(
258                self.handle,
259                self.domain,
260                c"System.Private.CoreLib".as_ptr(),
261                ACTIVATOR.as_ptr().cast(),
262                name.as_ptr(),
263                &mut delegate,
264            )
265        };
266        check(method, code)?;
267        assert_eq!(std::mem::size_of::<T>(), std::mem::size_of::<*mut c_void>());
268        Ok(unsafe { std::mem::transmute_copy(&delegate) })
269    }
270}
271
272/// The `Hao.Loader` helpers, built and loaded on first use.
273struct Loader {
274    load_from: LoadFrom,
275    get_method: GetMethod,
276    get_method_from_loaded: GetMethodFromLoaded,
277}
278
279pub(crate) struct CoreClr {
280    // Kept so libcoreclr stays loaded when hao started it; `None` when attaching
281    // to a runtime the host already started and keeps alive.
282    _coreclr: Option<Library>,
283    major: u16,
284    get_function_pointer: GetFunctionPointer,
285    load_assembly_bytes: LoadAssemblyBytes,
286    loader: OnceLock<Loader>,
287}
288
289// The ComponentActivator delegates are thread safe.
290unsafe impl Send for CoreClr {}
291unsafe impl Sync for CoreClr {}
292
293impl CoreClr {
294    pub fn new(options: &CoreClrOptions) -> Result<Self> {
295        let framework = Framework::find(options)?;
296        let path = framework.dir.join(coreclr_name());
297        let coreclr = unsafe { Library::new(&path) }
298            .map_err(|e| Error::Library(path.display().to_string(), e))?;
299        let host = Host::start(&coreclr, &framework)?;
300        Ok(Self {
301            major: framework.major,
302            get_function_pointer: host.activator_delegate("GetFunctionPointer")?,
303            load_assembly_bytes: host.activator_delegate("LoadAssemblyBytes")?,
304            loader: OnceLock::new(),
305            _coreclr: Some(coreclr),
306        })
307    }
308
309    /// Attaches to a CoreCLR another host (e.g. a game) already started in this
310    /// process, using the host handle, domain and `coreclr_create_delegate`
311    /// captured as it initialised. `major` is the .NET major version (e.g. 9),
312    /// used to build the loader assembly. No new runtime is started.
313    pub fn attach(
314        handle: *mut c_void,
315        domain: u32,
316        create_delegate: *const c_void,
317        major: u16,
318    ) -> Result<Self> {
319        let host = Host {
320            handle,
321            domain,
322            create_delegate: unsafe {
323                std::mem::transmute::<*const c_void, CreateDelegate>(create_delegate)
324            },
325        };
326        Ok(Self {
327            major,
328            get_function_pointer: host.activator_delegate("GetFunctionPointer")?,
329            load_assembly_bytes: host.activator_delegate("LoadAssemblyBytes")?,
330            loader: OnceLock::new(),
331            _coreclr: None,
332        })
333    }
334
335    /// The `Hao.Loader` helpers, generated with hao and loaded once.
336    fn loader(&self) -> Result<&Loader> {
337        if let Some(loader) = self.loader.get() {
338            return Ok(loader);
339        }
340        self.load_assembly_bytes(&loader_assembly(self.major)?)?;
341        let load_from = self.function_pointer(LOADER, "Hao.Loader", "LoadFrom")?;
342        let get_method = self.function_pointer(LOADER, "Hao.Loader", "GetMethod")?;
343        let get_method_from_loaded =
344            self.function_pointer(LOADER, "Hao.Loader", "GetMethodFromLoaded")?;
345        Ok(self.loader.get_or_init(|| unsafe {
346            Loader {
347                load_from: std::mem::transmute::<*const c_void, LoadFrom>(load_from),
348                get_method: std::mem::transmute::<*const c_void, GetMethod>(get_method),
349                get_method_from_loaded: std::mem::transmute::<*const c_void, GetMethodFromLoaded>(
350                    get_method_from_loaded,
351                ),
352            }
353        }))
354    }
355
356    /// Loads with `Assembly.LoadFrom`, so dependencies next to the assembly
357    /// are found. `ComponentActivator.LoadAssembly` would need hostfxr.
358    pub fn load_assembly(&self, path: &Path) -> Result<()> {
359        let load_from = self.loader()?.load_from;
360        check("Assembly.LoadFrom", unsafe {
361            load_from(wide(&path.to_string_lossy()).as_ptr())
362        })
363    }
364
365    /// A native-callable pointer to a static method, whether or not it is
366    /// `[UnmanagedCallersOnly]`. The method is JIT-compiled first (so IL patched
367    /// before the assembly was loaded takes effect), and the pointer uses the
368    /// managed calling convention, which matches the C ABI for static methods
369    /// with primitive and pointer arguments.
370    pub fn method_pointer(
371        &self,
372        assembly: &str,
373        type_name: &str,
374        method: &str,
375    ) -> Result<*const c_void> {
376        let full_name = wide(&format!("{}, {}", type_name, assembly));
377        let name = wide(method);
378        let pointer = unsafe { (self.loader()?.get_method)(full_name.as_ptr(), name.as_ptr()) };
379        if pointer.is_null() {
380            return Err(Error::NotFound(format!(
381                "method {}::{} (is it a unique static method?)",
382                type_name, method
383            )));
384        }
385        Ok(pointer)
386    }
387
388    /// Like [`method_pointer`](Self::method_pointer), but finds the type by
389    /// iterating `AppDomain.CurrentDomain.GetAssemblies()` instead of
390    /// `Type.GetType`. This resolves the type from whichever
391    /// `AssemblyLoadContext` actually loaded the assembly (e.g. a game host's
392    /// ALC), rather than the default ALC where the helper assembly lives.
393    pub fn method_pointer_from_loaded(
394        &self,
395        assembly: &str,
396        type_name: &str,
397        method: &str,
398    ) -> Result<*const c_void> {
399        let type_name_w = wide(type_name);
400        let method_w = wide(method);
401        let asm_w = wide(assembly);
402        let pointer = unsafe {
403            (self.loader()?.get_method_from_loaded)(
404                type_name_w.as_ptr(),
405                method_w.as_ptr(),
406                asm_w.as_ptr(),
407            )
408        };
409        if pointer.is_null() {
410            return Err(Error::NotFound(format!(
411                "method {}::{} in loaded assembly \"{}\"",
412                type_name, method, assembly
413            )));
414        }
415        Ok(pointer)
416    }
417
418    pub fn load_assembly_bytes(&self, bytes: &[u8]) -> Result<()> {
419        let code = unsafe {
420            (self.load_assembly_bytes)(
421                bytes.as_ptr(),
422                bytes.len(),
423                ptr::null(),
424                0,
425                ptr::null_mut(),
426                ptr::null_mut(),
427            )
428        };
429        check("load_assembly_bytes", code)
430    }
431
432    /// A pointer to a static `[UnmanagedCallersOnly]` method.
433    pub fn function_pointer(
434        &self,
435        assembly: &str,
436        type_name: &str,
437        method: &str,
438    ) -> Result<*const c_void> {
439        let full_type = wide(&format!("{}, {}", type_name, assembly));
440        let method_name = wide(method);
441        let mut function = ptr::null_mut();
442        let code = unsafe {
443            (self.get_function_pointer)(
444                full_type.as_ptr(),
445                method_name.as_ptr(),
446                UNMANAGED_CALLERS_ONLY,
447                ptr::null_mut(),
448                ptr::null_mut(),
449                &mut function,
450            )
451        };
452        // GetFunctionPointer returns COR_E_INVALIDOPERATION for a method that
453        // isn't [UnmanagedCallersOnly]. Point at the method that handles those.
454        if code as u32 == 0x8013_1509 {
455            return Err(Error::Other(format!(
456                "{}::{} is not [UnmanagedCallersOnly]; use Runtime::method_pointer to call it",
457                type_name, method
458            )));
459        }
460        check("get_function_pointer", code)?;
461        Ok(function)
462    }
463}
464
465const LOADER: &str = "Hao.Loader";
466
467/// A small `Hao.Loader` assembly with two `[UnmanagedCallersOnly]` helpers:
468///
469/// - `int LoadFrom(IntPtr path)`: `Assembly.LoadFrom`, returning the exception's HResult on failure.
470/// - `IntPtr GetMethod(IntPtr fullName, IntPtr name)`: looks up a static method by reflection,
471///   JIT-compiles it and returns its native entry point (0 on failure), so any method can be
472///   called, not only `[UnmanagedCallersOnly]` ones.
473fn loader_assembly(major: u16) -> Result<Vec<u8>> {
474    use hao::{
475        dotnet::{
476            entries::{Method, TypeDef},
477            il::{Emitter, OpCode},
478            module::{ModuleKind, TargetRuntime},
479            signature::{MethodSig, TypeSig},
480        },
481        Module,
482    };
483    let build = || -> hao::error::Result<Vec<u8>> {
484        let mut module = Module::new(
485            LOADER,
486            ModuleKind::Dll,
487            TargetRuntime::NetCoreImplementation(major),
488        );
489        let uco = module
490            .corlib_attribute("System.Runtime.InteropServices.UnmanagedCallersOnlyAttribute")?;
491        let to_string = module.import_corlib_method(
492            "System.Runtime.InteropServices.Marshal",
493            "PtrToStringAuto",
494            MethodSig::new_static(TypeSig::STRING, vec![TypeSig::NATIVE_INT]),
495        )?;
496        let exception = module.corlib_type("System.Exception")?;
497
498        // int LoadFrom(IntPtr path):
499        //   try { Assembly.LoadFrom(Marshal.PtrToStringAuto(path)); } catch (Exception e) { result = e.HResult; }
500        let assembly = module.corlib_type("System.Reflection.Assembly")?;
501        let load_from = module.import_method_on(
502            &assembly,
503            "LoadFrom",
504            MethodSig::new_static(TypeSig::class(assembly.clone()), vec![TypeSig::STRING]),
505        )?;
506        let hresult = module.import_method_on(
507            &exception,
508            "get_HResult",
509            MethodSig::new_instance(TypeSig::INT32, vec![]),
510        )?;
511        let load_from_body = Emitter::build(|e| {
512            let result = e.declare_local(TypeSig::INT32);
513            e.try_catch(
514                exception.clone(),
515                |e| {
516                    e.ldarg(0).call(&to_string).call(load_from).pop();
517                },
518                |e| {
519                    e.callvirt(hresult).stloc(result);
520                },
521            );
522            e.ldloc(result).ret();
523        });
524
525        // IntPtr GetMethod(IntPtr fullName, IntPtr name):
526        //   var m = Type.GetType(fullName).GetMethod(name, flags);
527        //   RuntimeHelpers.PrepareMethod(m.MethodHandle);
528        //   return m.MethodHandle.GetFunctionPointer();   // 0 on any exception
529        let type_ty = module.corlib_type("System.Type")?;
530        let method_info = module.corlib_type("System.Reflection.MethodInfo")?;
531        let method_base = module.corlib_type("System.Reflection.MethodBase")?;
532        let handle_ty = module.corlib_type("System.RuntimeMethodHandle")?;
533        let binding_flags = module.corlib_type("System.Reflection.BindingFlags")?;
534        let get_type = module.import_method_on(
535            &type_ty,
536            "GetType",
537            MethodSig::new_static(TypeSig::class(type_ty.clone()), vec![TypeSig::STRING]),
538        )?;
539        let get_method = module.import_method_on(
540            &type_ty,
541            "GetMethod",
542            MethodSig::new_instance(
543                TypeSig::class(method_info.clone()),
544                vec![TypeSig::STRING, TypeSig::value_type(binding_flags)],
545            ),
546        )?;
547        let method_handle = module.import_method_on(
548            &method_base,
549            "get_MethodHandle",
550            MethodSig::new_instance(TypeSig::value_type(handle_ty.clone()), vec![]),
551        )?;
552        let prepare = module.import_corlib_method(
553            "System.Runtime.CompilerServices.RuntimeHelpers",
554            "PrepareMethod",
555            MethodSig::new_static(TypeSig::VOID, vec![TypeSig::value_type(handle_ty.clone())]),
556        )?;
557        // GetFunctionPointer returns `nint`, encoded as the native-int primitive, not System.IntPtr.
558        let function_pointer = module.import_method_on(
559            &handle_ty,
560            "GetFunctionPointer",
561            MethodSig::new_instance(TypeSig::NATIVE_INT, vec![]),
562        )?;
563
564        // Instance | Static | Public | NonPublic
565        const BINDING_FLAGS: i32 = 4 | 8 | 16 | 32;
566
567        let to_string2 = to_string.clone();
568        let get_method2 = get_method.clone();
569        let method_handle2 = method_handle.clone();
570        let prepare2 = prepare.clone();
571        let function_pointer2 = function_pointer.clone();
572        let type_ty2 = type_ty.clone();
573        let method_info2 = method_info.clone();
574        let handle_ty2 = handle_ty.clone();
575        let assembly2 = assembly.clone();
576
577        let get_method_body = Emitter::build(|e| {
578            let found_type = e.declare_local(TypeSig::class(type_ty.clone()));
579            let method = e.declare_local(TypeSig::class(method_info.clone()));
580            let handle = e.declare_local(TypeSig::value_type(handle_ty.clone()));
581            let result = e.declare_local(TypeSig::NATIVE_INT);
582            e.ldc_i4(0).op(OpCode::Conv_I).stloc(result);
583            e.try_catch(
584                exception.clone(),
585                |e| {
586                    e.ldarg(0).call(&to_string).call(get_type).stloc(found_type);
587                    e.ldloc(found_type)
588                        .ldarg(1)
589                        .call(&to_string)
590                        .ldc_i4(BINDING_FLAGS)
591                        .callvirt(get_method)
592                        .stloc(method);
593                    e.ldloc(method).callvirt(method_handle).stloc(handle);
594                    e.ldloc(handle).call(prepare);
595                    e.ldloca(handle).call(function_pointer).stloc(result);
596                },
597                |e| {
598                    e.pop(); // discard the exception; result stays 0
599                },
600            );
601            e.ldloc(result).ret();
602        });
603
604        // IntPtr GetMethodFromLoaded(IntPtr typeName, IntPtr methodName, IntPtr asmName):
605        //   foreach (var asm in AppDomain.CurrentDomain.GetAssemblies())
606        //     if (asm.GetName().Name == asmName)
607        //       var t = asm.GetType(typeName); if (t != null) ...
608        let app_domain = module.corlib_type("System.AppDomain")?;
609        let assembly_name_ty = module.corlib_type("System.Reflection.AssemblyName")?;
610        let get_current_domain = module.import_method_on(
611            &app_domain,
612            "get_CurrentDomain",
613            MethodSig::new_static(TypeSig::class(app_domain.clone()), vec![]),
614        )?;
615        let get_assemblies = module.import_method_on(
616            &app_domain,
617            "GetAssemblies",
618            MethodSig::new_instance(
619                TypeSig::sz_array(TypeSig::class(assembly.clone())),
620                vec![],
621            ),
622        )?;
623        let get_asm_name = module.import_method_on(
624            &assembly,
625            "GetName",
626            MethodSig::new_instance(TypeSig::class(assembly_name_ty.clone()), vec![]),
627        )?;
628        let get_name_prop = module.import_method_on(
629            &assembly_name_ty,
630            "get_Name",
631            MethodSig::new_instance(TypeSig::STRING, vec![]),
632        )?;
633        let asm_get_type = module.import_method_on(
634            &assembly,
635            "GetType",
636            MethodSig::new_instance(TypeSig::class(type_ty.clone()), vec![TypeSig::STRING]),
637        )?;
638        let string_equals = module.import_corlib_method(
639            "System.String",
640            "op_Equality",
641            MethodSig::new_static(TypeSig::BOOL, vec![TypeSig::STRING, TypeSig::STRING]),
642        )?;
643
644        let get_method_from_loaded_body = Emitter::build(|e| {
645            let type_name_local = e.declare_local(TypeSig::STRING);
646            let method_name_local = e.declare_local(TypeSig::STRING);
647            let asm_name_local = e.declare_local(TypeSig::STRING);
648            let assemblies = e.declare_local(TypeSig::sz_array(TypeSig::class(
649                assembly2.clone(),
650            )));
651            let idx = e.declare_local(TypeSig::INT32);
652            let current_asm = e.declare_local(TypeSig::class(assembly2.clone()));
653            let found_type_local = e.declare_local(TypeSig::class(type_ty2.clone()));
654            let method_local = e.declare_local(TypeSig::class(method_info2.clone()));
655            let handle_local = e.declare_local(TypeSig::value_type(handle_ty2.clone()));
656            let result_local = e.declare_local(TypeSig::NATIVE_INT);
657
658            // Marshal string args
659            e.ldarg(0).call(&to_string2).stloc(type_name_local);
660            e.ldarg(1).call(&to_string2).stloc(method_name_local);
661            e.ldarg(2).call(&to_string2).stloc(asm_name_local);
662
663            // result = 0
664            e.ldc_i4(0).op(OpCode::Conv_I).stloc(result_local);
665
666            let loop_check = e.label();
667            let loop_body = e.label();
668            let done = e.label();
669
670            e.try_catch(
671                exception.clone(),
672                |e| {
673                    // assemblies = AppDomain.CurrentDomain.GetAssemblies()
674                    e.call(get_current_domain)
675                        .callvirt(get_assemblies)
676                        .stloc(assemblies);
677                    // idx = 0
678                    e.ldc_i4(0).stloc(idx);
679                    e.branch(OpCode::Br, loop_check);
680
681                    // loop body
682                    e.mark(loop_body);
683                    e.ldloc(assemblies).ldloc(idx).op(OpCode::Ldelem_Ref).stloc(current_asm);
684                    // if (currentAsm.GetName().Name == asmName)
685                    e.ldloc(current_asm)
686                        .callvirt(get_asm_name)
687                        .callvirt(get_name_prop);
688                    e.ldloc(asm_name_local);
689                    e.call(string_equals);
690                    let skip = e.label();
691                    e.branch(OpCode::Brfalse, skip);
692
693                    // type = asm.GetType(typeName)
694                    e.ldloc(current_asm)
695                        .ldloc(type_name_local)
696                        .callvirt(asm_get_type)
697                        .stloc(found_type_local);
698                    e.ldloc(found_type_local).branch(OpCode::Brfalse, skip);
699
700                    // method = type.GetMethod(methodName, flags)
701                    e.ldloc(found_type_local)
702                        .ldloc(method_name_local)
703                        .ldc_i4(BINDING_FLAGS)
704                        .callvirt(get_method2)
705                        .stloc(method_local);
706                    e.ldloc(method_local).branch(OpCode::Brfalse, skip);
707
708                    // PrepareMethod + GetFunctionPointer
709                    e.ldloc(method_local)
710                        .callvirt(method_handle2)
711                        .stloc(handle_local);
712                    e.ldloc(handle_local).call(prepare2);
713                    e.ldloca(handle_local)
714                        .call(function_pointer2)
715                        .stloc(result_local);
716                    e.branch(OpCode::Leave, done);
717
718                    e.mark(skip);
719                    // idx++
720                    e.ldloc(idx).ldc_i4(1).op(OpCode::Add).stloc(idx);
721
722                    // loop check: idx < assemblies.Length
723                    e.mark(loop_check);
724                    e.ldloc(idx)
725                        .ldloc(assemblies)
726                        .op(OpCode::Ldlen)
727                        .op(OpCode::Conv_I4);
728                    e.branch(OpCode::Blt, loop_body);
729                },
730                |e| {
731                    e.pop(); // discard exception
732                },
733            );
734
735            e.mark(done);
736            e.ldloc(result_local).ret();
737        });
738
739        let loader = module.add_static_class("Hao", "Loader")?;
740        TypeDef::add_method(
741            &loader,
742            Method::public_static(
743                "LoadFrom",
744                MethodSig::new_static(TypeSig::INT32, vec![TypeSig::NATIVE_INT]),
745            )
746            .with_attribute(uco.clone())
747            .with_body(load_from_body),
748        );
749        TypeDef::add_method(
750            &loader,
751            Method::public_static(
752                "GetMethod",
753                MethodSig::new_static(
754                    TypeSig::NATIVE_INT,
755                    vec![TypeSig::NATIVE_INT, TypeSig::NATIVE_INT],
756                ),
757            )
758            .with_attribute(uco.clone())
759            .with_body(get_method_body),
760        );
761        TypeDef::add_method(
762            &loader,
763            Method::public_static(
764                "GetMethodFromLoaded",
765                MethodSig::new_static(
766                    TypeSig::NATIVE_INT,
767                    vec![TypeSig::NATIVE_INT, TypeSig::NATIVE_INT, TypeSig::NATIVE_INT],
768                ),
769            )
770            .with_attribute(uco)
771            .with_body(get_method_from_loaded_body),
772        );
773        module.write()
774    };
775    build().map_err(|e| Error::Other(format!("could not build the loader assembly: {}", e)))
776}