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;
68
69/// `GetFunctionPointer`'s sentinel for a `[UnmanagedCallersOnly]` method.
70const UNMANAGED_CALLERS_ONLY: *const CharT = usize::MAX as *const CharT;
71
72const ACTIVATOR: &[u8] = b"Internal.Runtime.InteropServices.ComponentActivator\0";
73
74fn check(function: &'static str, code: i32) -> Result<()> {
75    // An HRESULT, negative on failure.
76    if code >= 0 {
77        Ok(())
78    } else {
79        Err(Error::Host {
80            function,
81            code: code as u32,
82        })
83    }
84}
85
86/// Where to find .NET and which framework version to run.
87#[derive(Debug, Clone, Default)]
88#[cfg_attr(feature = "reflect", derive(facet::Facet))]
89pub struct CoreClrOptions {
90    /// Defaults to `DOTNET_ROOT` or the standard install locations.
91    pub dotnet_root: Option<PathBuf>,
92    /// A `Microsoft.NETCore.App` version such as `9.0.21`. Defaults to the newest installed.
93    pub framework_version: Option<String>,
94}
95
96fn parse_version(name: &str) -> Vec<u32> {
97    name.split(['.', '-'])
98        .map(|p| p.parse().unwrap_or(0))
99        .collect()
100}
101
102fn newest_dir(dir: &Path) -> Option<PathBuf> {
103    std::fs::read_dir(dir)
104        .ok()?
105        .filter_map(|e| e.ok().map(|e| e.path()))
106        .filter(|p| p.is_dir())
107        .max_by_key(|p| parse_version(&p.file_name().unwrap_or_default().to_string_lossy()))
108}
109
110const DOTNET_ROOTS: &[&str] = &[
111    "/usr/share/dotnet",
112    "/usr/lib/dotnet",
113    "/usr/local/share/dotnet",
114    "/opt/dotnet",
115    r"C:\Program Files\dotnet",
116];
117
118pub fn find_dotnet_root() -> Option<PathBuf> {
119    std::env::var_os("DOTNET_ROOT")
120        .map(PathBuf::from)
121        .into_iter()
122        .chain(DOTNET_ROOTS.iter().map(PathBuf::from))
123        .find(|p| p.join("shared").join("Microsoft.NETCore.App").is_dir())
124}
125
126fn coreclr_name() -> &'static str {
127    if cfg!(windows) {
128        "coreclr.dll"
129    } else if cfg!(target_os = "macos") {
130        "libcoreclr.dylib"
131    } else {
132        "libcoreclr.so"
133    }
134}
135
136/// A resolved `Microsoft.NETCore.App` framework directory.
137struct Framework {
138    dir: PathBuf,
139    major: u16,
140}
141
142impl Framework {
143    fn find(options: &CoreClrOptions) -> Result<Self> {
144        let root = options
145            .dotnet_root
146            .clone()
147            .or_else(find_dotnet_root)
148            .ok_or_else(|| Error::NotFound("a .NET installation (set DOTNET_ROOT)".into()))?;
149        let frameworks = root.join("shared").join("Microsoft.NETCore.App");
150        let dir = match &options.framework_version {
151            Some(v) => frameworks.join(v),
152            None => newest_dir(&frameworks).ok_or_else(|| {
153                Error::NotFound(format!("Microsoft.NETCore.App in {}", root.display()))
154            })?,
155        };
156        let version = dir
157            .file_name()
158            .unwrap_or_default()
159            .to_string_lossy()
160            .into_owned();
161        let major = parse_version(&version)[0] as u16;
162        if major < 8 {
163            return Err(Error::Other(format!(
164                "hosting needs .NET 8 or newer, found {}",
165                version
166            )));
167        }
168        Ok(Self { dir, major })
169    }
170
171    /// The runtime properties CoreCLR needs: the trusted assemblies, where to
172    /// find native libraries, and the hosting switch the delegates need.
173    fn properties(&self) -> Result<Vec<(&'static str, String)>> {
174        let separator = if cfg!(windows) { ";" } else { ":" };
175        let trusted = std::fs::read_dir(&self.dir)?
176            .filter_map(|e| e.ok().map(|e| e.path()))
177            .filter(|p| p.extension().is_some_and(|e| e == "dll"))
178            .map(|p| p.to_string_lossy().into_owned())
179            .collect::<Vec<_>>()
180            .join(separator);
181        let exe = std::env::current_exe()?;
182        let app_dir = exe.parent().unwrap_or(Path::new("."));
183        Ok(vec![
184            ("TRUSTED_PLATFORM_ASSEMBLIES", trusted),
185            (
186                "NATIVE_DLL_SEARCH_DIRECTORIES",
187                format!("{}{}", self.dir.display(), separator),
188            ),
189            (
190                "APP_CONTEXT_BASE_DIRECTORY",
191                format!("{}{}", app_dir.display(), std::path::MAIN_SEPARATOR),
192            ),
193            (
194                "System.Runtime.InteropServices.EnableConsumingManagedCodeFromNativeHosting",
195                "true".into(),
196            ),
197        ])
198    }
199}
200
201/// A started runtime's host handle, used to fetch delegates.
202struct Host {
203    handle: *mut c_void,
204    domain: u32,
205    create_delegate: CreateDelegate,
206}
207
208impl Host {
209    /// Starts the runtime from `library` with `framework`'s properties.
210    fn start(library: &Library, framework: &Framework) -> Result<Self> {
211        let properties = framework.properties()?;
212        let keys = properties
213            .iter()
214            .map(|(k, _)| c_string(*k))
215            .collect::<Result<Vec<_>>>()?;
216        let values = properties
217            .iter()
218            .map(|(_, v)| c_string(v.as_str()))
219            .collect::<Result<Vec<_>>>()?;
220        let key_ptrs = keys.iter().map(|k| k.as_ptr()).collect::<Vec<_>>();
221        let value_ptrs = values.iter().map(|v| v.as_ptr()).collect::<Vec<_>>();
222        let exe = c_string(std::env::current_exe()?.to_string_lossy().into_owned())?;
223
224        unsafe {
225            let initialize: Initialize = *library
226                .get(b"coreclr_initialize\0")
227                .map_err(|e| Error::Library("coreclr_initialize".into(), e))?;
228            let create_delegate: CreateDelegate = *library
229                .get(b"coreclr_create_delegate\0")
230                .map_err(|e| Error::Library("coreclr_create_delegate".into(), e))?;
231            let (mut handle, mut domain) = (ptr::null_mut(), 0);
232            let code = initialize(
233                exe.as_ptr(),
234                c"hao-runtime".as_ptr(),
235                key_ptrs.len() as i32,
236                key_ptrs.as_ptr(),
237                value_ptrs.as_ptr(),
238                &mut handle,
239                &mut domain,
240            );
241            check("coreclr_initialize", code)?;
242            Ok(Self {
243                handle,
244                domain,
245                create_delegate,
246            })
247        }
248    }
249
250    /// A delegate for a static method of `ComponentActivator`.
251    fn activator_delegate<T>(&self, method: &'static str) -> Result<T> {
252        let name = c_string(method)?;
253        let mut delegate = ptr::null_mut();
254        let code = unsafe {
255            (self.create_delegate)(
256                self.handle,
257                self.domain,
258                c"System.Private.CoreLib".as_ptr(),
259                ACTIVATOR.as_ptr().cast(),
260                name.as_ptr(),
261                &mut delegate,
262            )
263        };
264        check(method, code)?;
265        assert_eq!(std::mem::size_of::<T>(), std::mem::size_of::<*mut c_void>());
266        Ok(unsafe { std::mem::transmute_copy(&delegate) })
267    }
268}
269
270/// The `Hao.Loader` helpers, built and loaded on first use.
271struct Loader {
272    load_from: LoadFrom,
273    get_method: GetMethod,
274}
275
276pub(crate) struct CoreClr {
277    // Kept so libcoreclr stays loaded when hao started it; `None` when attaching
278    // to a runtime the host already started and keeps alive.
279    _coreclr: Option<Library>,
280    major: u16,
281    get_function_pointer: GetFunctionPointer,
282    load_assembly_bytes: LoadAssemblyBytes,
283    loader: OnceLock<Loader>,
284}
285
286// The ComponentActivator delegates are thread safe.
287unsafe impl Send for CoreClr {}
288unsafe impl Sync for CoreClr {}
289
290impl CoreClr {
291    pub fn new(options: &CoreClrOptions) -> Result<Self> {
292        let framework = Framework::find(options)?;
293        let path = framework.dir.join(coreclr_name());
294        let coreclr = unsafe { Library::new(&path) }
295            .map_err(|e| Error::Library(path.display().to_string(), e))?;
296        let host = Host::start(&coreclr, &framework)?;
297        Ok(Self {
298            major: framework.major,
299            get_function_pointer: host.activator_delegate("GetFunctionPointer")?,
300            load_assembly_bytes: host.activator_delegate("LoadAssemblyBytes")?,
301            loader: OnceLock::new(),
302            _coreclr: Some(coreclr),
303        })
304    }
305
306    /// Attaches to a CoreCLR another host (e.g. a game) already started in this
307    /// process, using the host handle, domain and `coreclr_create_delegate`
308    /// captured as it initialised. `major` is the .NET major version (e.g. 9),
309    /// used to build the loader assembly. No new runtime is started.
310    pub fn attach(
311        handle: *mut c_void,
312        domain: u32,
313        create_delegate: *const c_void,
314        major: u16,
315    ) -> Result<Self> {
316        let host = Host {
317            handle,
318            domain,
319            create_delegate: unsafe {
320                std::mem::transmute::<*const c_void, CreateDelegate>(create_delegate)
321            },
322        };
323        Ok(Self {
324            major,
325            get_function_pointer: host.activator_delegate("GetFunctionPointer")?,
326            load_assembly_bytes: host.activator_delegate("LoadAssemblyBytes")?,
327            loader: OnceLock::new(),
328            _coreclr: None,
329        })
330    }
331
332    /// The `Hao.Loader` helpers, generated with hao and loaded once.
333    fn loader(&self) -> Result<&Loader> {
334        if let Some(loader) = self.loader.get() {
335            return Ok(loader);
336        }
337        self.load_assembly_bytes(&loader_assembly(self.major)?)?;
338        let load_from = self.function_pointer(LOADER, "Hao.Loader", "LoadFrom")?;
339        let get_method = self.function_pointer(LOADER, "Hao.Loader", "GetMethod")?;
340        Ok(self.loader.get_or_init(|| unsafe {
341            Loader {
342                load_from: std::mem::transmute::<*const c_void, LoadFrom>(load_from),
343                get_method: std::mem::transmute::<*const c_void, GetMethod>(get_method),
344            }
345        }))
346    }
347
348    /// Loads with `Assembly.LoadFrom`, so dependencies next to the assembly
349    /// are found. `ComponentActivator.LoadAssembly` would need hostfxr.
350    pub fn load_assembly(&self, path: &Path) -> Result<()> {
351        let load_from = self.loader()?.load_from;
352        check("Assembly.LoadFrom", unsafe {
353            load_from(wide(&path.to_string_lossy()).as_ptr())
354        })
355    }
356
357    /// A native-callable pointer to a static method, whether or not it is
358    /// `[UnmanagedCallersOnly]`. The method is JIT-compiled first (so IL patched
359    /// before the assembly was loaded takes effect), and the pointer uses the
360    /// managed calling convention, which matches the C ABI for static methods
361    /// with primitive and pointer arguments.
362    pub fn method_pointer(
363        &self,
364        assembly: &str,
365        type_name: &str,
366        method: &str,
367    ) -> Result<*const c_void> {
368        let full_name = wide(&format!("{}, {}", type_name, assembly));
369        let name = wide(method);
370        let pointer = unsafe { (self.loader()?.get_method)(full_name.as_ptr(), name.as_ptr()) };
371        if pointer.is_null() {
372            return Err(Error::NotFound(format!(
373                "method {}::{} (is it a unique static method?)",
374                type_name, method
375            )));
376        }
377        Ok(pointer)
378    }
379
380    pub fn load_assembly_bytes(&self, bytes: &[u8]) -> Result<()> {
381        let code = unsafe {
382            (self.load_assembly_bytes)(
383                bytes.as_ptr(),
384                bytes.len(),
385                ptr::null(),
386                0,
387                ptr::null_mut(),
388                ptr::null_mut(),
389            )
390        };
391        check("load_assembly_bytes", code)
392    }
393
394    /// A pointer to a static `[UnmanagedCallersOnly]` method.
395    pub fn function_pointer(
396        &self,
397        assembly: &str,
398        type_name: &str,
399        method: &str,
400    ) -> Result<*const c_void> {
401        let full_type = wide(&format!("{}, {}", type_name, assembly));
402        let method_name = wide(method);
403        let mut function = ptr::null_mut();
404        let code = unsafe {
405            (self.get_function_pointer)(
406                full_type.as_ptr(),
407                method_name.as_ptr(),
408                UNMANAGED_CALLERS_ONLY,
409                ptr::null_mut(),
410                ptr::null_mut(),
411                &mut function,
412            )
413        };
414        // GetFunctionPointer returns COR_E_INVALIDOPERATION for a method that
415        // isn't [UnmanagedCallersOnly]. Point at the method that handles those.
416        if code as u32 == 0x8013_1509 {
417            return Err(Error::Other(format!(
418                "{}::{} is not [UnmanagedCallersOnly]; use Runtime::method_pointer to call it",
419                type_name, method
420            )));
421        }
422        check("get_function_pointer", code)?;
423        Ok(function)
424    }
425}
426
427const LOADER: &str = "Hao.Loader";
428
429/// A small `Hao.Loader` assembly with two `[UnmanagedCallersOnly]` helpers:
430///
431/// - `int LoadFrom(IntPtr path)`: `Assembly.LoadFrom`, returning the exception's HResult on failure.
432/// - `IntPtr GetMethod(IntPtr fullName, IntPtr name)`: looks up a static method by reflection,
433///   JIT-compiles it and returns its native entry point (0 on failure), so any method can be
434///   called, not only `[UnmanagedCallersOnly]` ones.
435fn loader_assembly(major: u16) -> Result<Vec<u8>> {
436    use hao::{
437        dotnet::{
438            entries::{Method, TypeDef},
439            il::{Emitter, OpCode},
440            module::{ModuleKind, TargetRuntime},
441            signature::{MethodSig, TypeSig},
442        },
443        Module,
444    };
445    let build = || -> hao::error::Result<Vec<u8>> {
446        let mut module = Module::new(
447            LOADER,
448            ModuleKind::Dll,
449            TargetRuntime::NetCoreImplementation(major),
450        );
451        let uco = module
452            .corlib_attribute("System.Runtime.InteropServices.UnmanagedCallersOnlyAttribute")?;
453        let to_string = module.import_corlib_method(
454            "System.Runtime.InteropServices.Marshal",
455            "PtrToStringAuto",
456            MethodSig::new_static(TypeSig::STRING, vec![TypeSig::NATIVE_INT]),
457        )?;
458        let exception = module.corlib_type("System.Exception")?;
459
460        // int LoadFrom(IntPtr path):
461        //   try { Assembly.LoadFrom(Marshal.PtrToStringAuto(path)); } catch (Exception e) { result = e.HResult; }
462        let assembly = module.corlib_type("System.Reflection.Assembly")?;
463        let load_from = module.import_method_on(
464            &assembly,
465            "LoadFrom",
466            MethodSig::new_static(TypeSig::class(assembly.clone()), vec![TypeSig::STRING]),
467        )?;
468        let hresult = module.import_method_on(
469            &exception,
470            "get_HResult",
471            MethodSig::new_instance(TypeSig::INT32, vec![]),
472        )?;
473        let load_from_body = Emitter::build(|e| {
474            let result = e.declare_local(TypeSig::INT32);
475            e.try_catch(
476                exception.clone(),
477                |e| {
478                    e.ldarg(0).call(&to_string).call(load_from).pop();
479                },
480                |e| {
481                    e.callvirt(hresult).stloc(result);
482                },
483            );
484            e.ldloc(result).ret();
485        });
486
487        // IntPtr GetMethod(IntPtr fullName, IntPtr name):
488        //   var m = Type.GetType(fullName).GetMethod(name, flags);
489        //   RuntimeHelpers.PrepareMethod(m.MethodHandle);
490        //   return m.MethodHandle.GetFunctionPointer();   // 0 on any exception
491        let type_ty = module.corlib_type("System.Type")?;
492        let method_info = module.corlib_type("System.Reflection.MethodInfo")?;
493        let method_base = module.corlib_type("System.Reflection.MethodBase")?;
494        let handle_ty = module.corlib_type("System.RuntimeMethodHandle")?;
495        let binding_flags = module.corlib_type("System.Reflection.BindingFlags")?;
496        let get_type = module.import_method_on(
497            &type_ty,
498            "GetType",
499            MethodSig::new_static(TypeSig::class(type_ty.clone()), vec![TypeSig::STRING]),
500        )?;
501        let get_method = module.import_method_on(
502            &type_ty,
503            "GetMethod",
504            MethodSig::new_instance(
505                TypeSig::class(method_info.clone()),
506                vec![TypeSig::STRING, TypeSig::value_type(binding_flags)],
507            ),
508        )?;
509        let method_handle = module.import_method_on(
510            &method_base,
511            "get_MethodHandle",
512            MethodSig::new_instance(TypeSig::value_type(handle_ty.clone()), vec![]),
513        )?;
514        let prepare = module.import_corlib_method(
515            "System.Runtime.CompilerServices.RuntimeHelpers",
516            "PrepareMethod",
517            MethodSig::new_static(TypeSig::VOID, vec![TypeSig::value_type(handle_ty.clone())]),
518        )?;
519        // GetFunctionPointer returns `nint`, encoded as the native-int primitive, not System.IntPtr.
520        let function_pointer = module.import_method_on(
521            &handle_ty,
522            "GetFunctionPointer",
523            MethodSig::new_instance(TypeSig::NATIVE_INT, vec![]),
524        )?;
525
526        // Instance | Static | Public | NonPublic
527        const BINDING_FLAGS: i32 = 4 | 8 | 16 | 32;
528        let get_method_body = Emitter::build(|e| {
529            let found_type = e.declare_local(TypeSig::class(type_ty.clone()));
530            let method = e.declare_local(TypeSig::class(method_info.clone()));
531            let handle = e.declare_local(TypeSig::value_type(handle_ty.clone()));
532            let result = e.declare_local(TypeSig::NATIVE_INT);
533            e.ldc_i4(0).op(OpCode::Conv_I).stloc(result);
534            e.try_catch(
535                exception,
536                |e| {
537                    e.ldarg(0).call(&to_string).call(get_type).stloc(found_type);
538                    e.ldloc(found_type)
539                        .ldarg(1)
540                        .call(&to_string)
541                        .ldc_i4(BINDING_FLAGS)
542                        .callvirt(get_method)
543                        .stloc(method);
544                    e.ldloc(method).callvirt(method_handle).stloc(handle);
545                    e.ldloc(handle).call(prepare);
546                    e.ldloca(handle).call(function_pointer).stloc(result);
547                },
548                |e| {
549                    e.pop(); // discard the exception; result stays 0
550                },
551            );
552            e.ldloc(result).ret();
553        });
554
555        let loader = module.add_static_class("Hao", "Loader")?;
556        TypeDef::add_method(
557            &loader,
558            Method::public_static(
559                "LoadFrom",
560                MethodSig::new_static(TypeSig::INT32, vec![TypeSig::NATIVE_INT]),
561            )
562            .with_attribute(uco.clone())
563            .with_body(load_from_body),
564        );
565        TypeDef::add_method(
566            &loader,
567            Method::public_static(
568                "GetMethod",
569                MethodSig::new_static(
570                    TypeSig::NATIVE_INT,
571                    vec![TypeSig::NATIVE_INT, TypeSig::NATIVE_INT],
572                ),
573            )
574            .with_attribute(uco)
575            .with_body(get_method_body),
576        );
577        module.write()
578    };
579    build().map_err(|e| Error::Other(format!("could not build the loader assembly: {}", e)))
580}