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