Skip to main content

hao_runtime/
attach.rs

1//! Attach to a CoreCLR game's already-running runtime from a native mod loaded
2//! before the runtime starts (via `LD_PRELOAD` on Linux, or an injected DLL on
3//! Windows).
4//!
5//! CoreCLR has no public "attach to the running runtime" C API:
6//! `coreclr_create_delegate` needs the host handle and domain id the game's host
7//! created, and the runtime initialises only once per process. So we capture
8//! them as the game creates them — inline-hooking the loader to see `coreclr`
9//! arrive (it is loaded late and resolved dynamically, so symbol interposition
10//! misses it), then inline-hooking `coreclr_initialize` to read its output.
11//!
12//! The loader differs per platform (`dlopen` / `LoadLibraryExW`); everything
13//! else, including the `coreclr_initialize` hook, is shared. Requires x86_64,
14//! where the inline-hook trampoline works. With the captured [`ClrHost`],
15//! [`ClrHost::attach`] builds a [`Runtime`] bound to that CLR.
16//!
17//! ```no_run
18//! // In the mod's entry point, which runs before the game starts .NET.
19//! hao_runtime::attach::on_clr_init(|host| {
20//!     // A .NET 8 game. This runs on a background thread, so call only
21//!     // thread-agnostic methods here.
22//!     let runtime = host.attach(8).expect("attach to the game's CoreCLR");
23//!     let main = runtime.method_pointer("MyMod", "MyMod.Entry", "Run");
24//!     # let _ = main;
25//! });
26//! ```
27
28use std::{
29    ffi::{c_char, c_int, c_void},
30    sync::{
31        atomic::{AtomicBool, AtomicUsize, Ordering},
32        Mutex, OnceLock,
33    },
34};
35
36use crate::{Result, Runtime};
37
38/// `coreclr_initialize(exePath, friendlyName, propCount, keys, values, &hostHandle, &domainId)`.
39type CoreclrInitialize = unsafe extern "C" fn(
40    *const c_char,
41    *const c_char,
42    c_int,
43    *const *const c_char,
44    *const *const c_char,
45    *mut *mut c_void,
46    *mut u32,
47) -> c_int;
48
49/// `coreclr_create_delegate(hostHandle, domainId, assembly, type, method, &delegate)`.
50type CoreclrCreateDelegate = unsafe extern "C" fn(
51    *mut c_void,
52    u32,
53    *const c_char,
54    *const c_char,
55    *const c_char,
56    *mut *mut c_void,
57) -> c_int;
58
59/// The CoreCLR shared library's file name on this platform.
60const CORECLR: &str = if cfg!(windows) {
61    "coreclr.dll"
62} else {
63    "libcoreclr.so"
64};
65
66/// A handle to the game's running CoreCLR, captured from `coreclr_initialize`.
67#[derive(Clone, Copy)]
68pub struct ClrHost {
69    /// The host handle `coreclr_initialize` returned, which
70    /// `coreclr_create_delegate` needs.
71    pub handle: *mut c_void,
72    /// The id of the app domain the game's host created.
73    pub domain: u32,
74    create_delegate: CoreclrCreateDelegate,
75}
76
77// The handle and domain are used across threads; the delegate is thread safe.
78unsafe impl Send for ClrHost {}
79unsafe impl Sync for ClrHost {}
80
81impl ClrHost {
82    /// A native-callable pointer to a static `[UnmanagedCallersOnly]` method
83    /// `type_name::method` in `assembly` (CoreCLR only exposes such methods
84    /// directly; arbitrary methods need a managed loader on top of this).
85    pub fn create_delegate(
86        &self,
87        assembly: &str,
88        type_name: &str,
89        method: &str,
90    ) -> std::result::Result<*mut c_void, String> {
91        use std::ffi::CString;
92        let assembly = CString::new(assembly).map_err(|_| "assembly has a nul")?;
93        let type_name = CString::new(type_name).map_err(|_| "type has a nul")?;
94        let method = CString::new(method).map_err(|_| "method has a nul")?;
95        let mut delegate = std::ptr::null_mut();
96        let code = unsafe {
97            (self.create_delegate)(
98                self.handle,
99                self.domain,
100                assembly.as_ptr(),
101                type_name.as_ptr(),
102                method.as_ptr(),
103                &mut delegate,
104            )
105        };
106        if code != 0 {
107            return Err(format!("coreclr_create_delegate failed: 0x{code:x}"));
108        }
109        Ok(delegate)
110    }
111
112    /// Attaches hao's runtime to the game's CoreCLR, so any managed method can be
113    /// called (via [`Runtime::method_pointer`]). `major` is the game's .NET major
114    /// version (e.g. 9 for a .NET 9 game).
115    pub fn attach(&self, major: u16) -> Result<Runtime> {
116        Runtime::coreclr_attach(
117            self.handle,
118            self.domain,
119            self.create_delegate as *const c_void,
120            major,
121        )
122    }
123}
124
125type Callback = Box<dyn FnOnce(ClrHost) + Send>;
126
127/// Logs an early-attach diagnostic at `debug` level (target
128/// `hao_runtime::attach`), for tracing a mod's startup.
129pub fn diag(msg: &str) {
130    tracing::debug!("{msg}");
131}
132
133static CALLBACKS: Mutex<Vec<Callback>> = Mutex::new(Vec::new());
134/// The game's CoreCLR, opened once it is loaded. Holding it here keeps the
135/// library (and the function pointers taken from it) alive: the runtime is
136/// never unloaded, so it is never closed.
137static CORECLR_LIBRARY: OnceLock<libloading::Library> = OnceLock::new();
138static HOST: OnceLock<ClrHost> = OnceLock::new();
139static CREATE_DELEGATE: AtomicUsize = AtomicUsize::new(0);
140static LOADER_HOOKED: AtomicBool = AtomicBool::new(false);
141static INIT_HOOKED: AtomicBool = AtomicBool::new(false);
142
143/// Installs the loader hook (`dlopen` / `LoadLibraryExW`) so that the
144/// runtime's library load is detected as early as possible.
145///
146/// Safe to call more than once — subsequent calls are no-ops. Call it from
147/// `.init_array` / `ctor()` when the mod needs the CLR but registers the
148/// [`on_clr_init`] callback later (e.g. from a separate thread).
149pub fn ensure_loader_hook() {
150    install_loader_hook();
151}
152
153/// Runs `callback` once the game's CoreCLR host has been captured. Call it from
154/// a mod's entry point (which the loader runs before the game starts the
155/// runtime).
156///
157/// The callback runs on a background thread, **not** the game's init thread:
158/// running managed code during `coreclr_initialize` corrupts the runtime's
159/// bootstrap and crashes the game. It is therefore also not on any engine main
160/// thread, so it may call thread-agnostic (corlib) methods but must not touch a
161/// main-thread-only API until it has a main-thread callback to run on.
162pub fn on_clr_init(callback: impl FnOnce(ClrHost) + Send + 'static) {
163    if let Some(host) = HOST.get() {
164        tracing::debug!("on_clr_init: host already captured");
165        let host = *host;
166        std::thread::spawn(move || callback(host));
167        return;
168    }
169    // Attach-time injection: the stub may load *after* the game already ran
170    // coreclr_initialize, so hooking it would never fire. If the CLR is already
171    // up, capture its host directly from the exported GetCLRRuntimeHost and run
172    // the callback now (the runtime is fully started, so managed code is safe).
173    #[cfg(target_arch = "x86_64")]
174    if let Some(host) = try_capture_running_host() {
175        tracing::debug!("on_clr_init: captured the running CLR via GetCLRRuntimeHost");
176        let host = *HOST.get_or_init(|| host);
177        std::thread::spawn(move || callback(host));
178        return;
179    }
180
181    tracing::debug!("on_clr_init: CLR not started, waiting for coreclr_initialize");
182    CALLBACKS
183        .lock()
184        .unwrap_or_else(|e| e.into_inner())
185        .push(Box::new(callback));
186    install_loader_hook();
187}
188
189/// If CoreCLR is already loaded *and initialized* (attach-time injection, after
190/// `coreclr_initialize` has run), capture the running host without hooking init.
191///
192/// hao runs inside the target process, so it can call the exported
193/// `GetCLRRuntimeHost` directly: it returns the live `CorHost2` (the same object
194/// `coreclr_create_delegate` expects), accepting `IID_IUnknown`. The default
195/// AppDomain id is 1. Returns `None` if CoreCLR isn't loaded or isn't started
196/// yet, in which case the caller falls back to hooking `coreclr_initialize`.
197#[cfg(target_arch = "x86_64")]
198fn try_capture_running_host() -> Option<ClrHost> {
199    // IID_IUnknown {00000000-0000-0000-C000-000000000046}.
200    const IID_IUNKNOWN: [u8; 16] = [0, 0, 0, 0, 0, 0, 0, 0, 0xc0, 0, 0, 0, 0, 0, 0, 0x46];
201    type GetClrRuntimeHost = unsafe extern "C" fn(*const u8, *mut *mut c_void) -> c_int;
202
203    let lib = loaded_coreclr()?;
204    let get_host = unsafe { lib.get::<GetClrRuntimeHost>(b"GetCLRRuntimeHost\0") }.ok()?;
205    let create = unsafe { lib.get::<CoreclrCreateDelegate>(b"coreclr_create_delegate\0") }.ok()?;
206    let create_delegate: CoreclrCreateDelegate = *create;
207
208    let mut host: *mut c_void = std::ptr::null_mut();
209    let code = unsafe { (*get_host)(IID_IUNKNOWN.as_ptr(), &mut host) };
210
211    if code != 0 || host.is_null() {
212        return None; // not initialized yet → hook coreclr_initialize instead
213    }
214    Some(ClrHost {
215        handle: host,
216        domain: 1,
217        create_delegate,
218    })
219}
220
221/// The game's CoreCLR if it is already loaded, kept open for the life of the
222/// process. Never loads it: opening `libcoreclr.so` / `coreclr.dll` by name
223/// could otherwise load a different (system) copy before the game loads its own.
224fn loaded_coreclr() -> Option<&'static libloading::Library> {
225    if let Some(lib) = CORECLR_LIBRARY.get() {
226        return Some(lib);
227    }
228    // Opened outside `get_or_init`: on Unix the open goes through the `dlopen`
229    // hook, which may re-enter here. If both set it, the spare handle is closed
230    // and the library stays loaded through the other.
231    let lib = match open_already_loaded(CORECLR) {
232        Ok(lib) => lib,
233        Err(e) => {
234            tracing::debug!("{CORECLR} is not loaded yet: {e}");
235            return None;
236        }
237    };
238    let _ = CORECLR_LIBRARY.set(lib);
239    CORECLR_LIBRARY.get()
240}
241
242/// Opens the library `name` only if it is already loaded in the process
243/// (`dlopen` with `RTLD_NOLOAD` / `GetModuleHandleExW`).
244#[cfg(unix)]
245fn open_already_loaded(name: &str) -> std::result::Result<libloading::Library, libloading::Error> {
246    use libloading::os::unix::{Library, RTLD_NOW};
247    // Not exported by libloading.
248    #[cfg(any(target_os = "linux", target_os = "android"))]
249    const RTLD_NOLOAD: c_int = 0x4;
250    #[cfg(any(target_os = "macos", target_os = "ios"))]
251    const RTLD_NOLOAD: c_int = 0x10;
252    #[cfg(target_os = "freebsd")]
253    const RTLD_NOLOAD: c_int = 0x2000;
254    unsafe { Library::open(Some(name), RTLD_NOLOAD | RTLD_NOW) }.map(Into::into)
255}
256
257/// Opens the library `name` only if it is already loaded in the process
258/// (`dlopen` with `RTLD_NOLOAD` / `GetModuleHandleExW`).
259#[cfg(windows)]
260fn open_already_loaded(name: &str) -> std::result::Result<libloading::Library, libloading::Error> {
261    libloading::os::windows::Library::open_already_loaded(name).map(Into::into)
262}
263
264/// Runs the queued callbacks on a background thread, off the init thread.
265fn run_callbacks(host: ClrHost) {
266    std::thread::spawn(move || {
267        let callbacks = std::mem::take(&mut *CALLBACKS.lock().unwrap_or_else(|e| e.into_inner()));
268        for callback in callbacks {
269            callback(host);
270        }
271    });
272}
273
274fn hook_coreclr_init() {
275    if INIT_HOOKED.swap(true, Ordering::SeqCst) {
276        return;
277    }
278    let Some(lib) = loaded_coreclr() else {
279        tracing::error!("{CORECLR} is not loaded, not hooking coreclr_initialize");
280        INIT_HOOKED.store(false, Ordering::SeqCst);
281        return;
282    };
283    let init = unsafe { lib.get::<CoreclrInitialize>(b"coreclr_initialize\0") };
284    let create = unsafe { lib.get::<CoreclrCreateDelegate>(b"coreclr_create_delegate\0") };
285    let (Ok(init), Ok(create)) = (init, create) else {
286        tracing::error!("coreclr_initialize or coreclr_create_delegate not found in {CORECLR}");
287        return;
288    };
289    let init_addr = (*init) as usize as *mut u8;
290    CREATE_DELEGATE.store((*create) as usize, Ordering::SeqCst);
291
292    tracing::info!("hooking coreclr_initialize");
293    match unsafe { hooking::Hook::create(init_addr, coreclr_init_detour as *mut u8) } {
294        Ok(mut hook) => {
295            if let Err(e) = unsafe { hook.apply_hook() } {
296                tracing::error!("applying the coreclr_initialize hook failed: {e:?}");
297            }
298            std::mem::forget(hook);
299        }
300        Err(e) => tracing::error!("hooking coreclr_initialize failed: {e:?}"),
301    }
302}
303
304extern "C" fn coreclr_init_detour(
305    exe: *const c_char,
306    name: *const c_char,
307    count: c_int,
308    keys: *const *const c_char,
309    values: *const *const c_char,
310    host_handle: *mut *mut c_void,
311    domain_id: *mut u32,
312) -> c_int {
313    let original =
314        hooking::original_function_ptr().expect("original! inside the coreclr_initialize hook");
315    let original: CoreclrInitialize = unsafe { std::mem::transmute(original.as_ptr()) };
316
317    // Arm assembly interception BEFORE the original coreclr_initialize runs.
318    // The CLR opens assemblies (including GodotSharp.dll) during init, so
319    // the open/openat hooks must be in place before the first assembly load.
320    // The redirect() function only intercepts registered target basenames —
321    // all other file opens pass through, so this is safe.
322    tracing::debug!("coreclr_initialize called, arming assembly interception");
323    #[cfg(all(unix, target_arch = "x86_64"))]
324    crate::rewrite::arm_interception();
325
326    let result = unsafe { original(exe, name, count, keys, values, host_handle, domain_id) };
327    tracing::info!("coreclr_initialize returned 0x{result:x}");
328
329    if result == 0 && !host_handle.is_null() && !domain_id.is_null() {
330        let handle = unsafe { *host_handle };
331        let domain = unsafe { *domain_id };
332        let create = CREATE_DELEGATE.load(Ordering::SeqCst);
333        if create != 0 {
334            let host = ClrHost {
335                handle,
336                domain,
337                create_delegate: unsafe {
338                    std::mem::transmute::<usize, CoreclrCreateDelegate>(create)
339                },
340            };
341            tracing::info!("captured CLR host: handle={handle:?}, domain={domain}");
342            let _ = HOST.set(host);
343            run_callbacks(host);
344        }
345    }
346    result
347}
348
349// --- loader hook (the only platform-specific part) -----------------------
350
351#[cfg(unix)]
352fn install_loader_hook() {
353    if LOADER_HOOKED.swap(true, Ordering::SeqCst) {
354        return;
355    }
356    // The game's init may have loaded CoreCLR before this ran; if so, hook it
357    // directly. (Not `dlsym(RTLD_DEFAULT, ..)`: the host loads CoreCLR
358    // `RTLD_LOCAL`, so its symbols aren't in the global scope.)
359    if loaded_coreclr().is_some() {
360        tracing::info!("{CORECLR} is already loaded, hooking coreclr_initialize directly");
361        hook_coreclr_init();
362        return;
363    }
364
365    tracing::info!("hooking dlopen to wait for {CORECLR}");
366    match unsafe { hooking::Hook::by_name(None, c"dlopen", dlopen_detour as *mut u8) } {
367        Ok(mut hook) => {
368            if let Err(e) = unsafe { hook.apply_hook() } {
369                tracing::error!("applying the dlopen hook failed: {e:?}");
370            }
371            std::mem::forget(hook);
372        }
373        Err(e) => tracing::error!("hooking dlopen failed: {e:?}"),
374    }
375}
376
377#[cfg(unix)]
378extern "C" fn dlopen_detour(filename: *const c_char, flags: c_int) -> *mut c_void {
379    // Must be the first thing the detour does (it reads scratch registers).
380    let original = hooking::original_function_ptr().expect("original! inside the dlopen hook");
381    let original: unsafe extern "C" fn(*const c_char, c_int) -> *mut c_void =
382        unsafe { std::mem::transmute(original.as_ptr()) };
383    let handle = unsafe { original(filename, flags) };
384    if !handle.is_null() && !INIT_HOOKED.load(Ordering::SeqCst) {
385        if !filename.is_null() {
386            let name = unsafe { std::ffi::CStr::from_ptr(filename) }.to_string_lossy();
387            if name.contains(CORECLR) {
388                tracing::info!("{CORECLR} loaded: {name}");
389                hook_coreclr_init();
390            }
391        }
392        // CoreCLR may arrive through a chain (hostfxr → hostpolicy →
393        // coreclr) where intermediate loads don't mention "coreclr" in
394        // the filename.  Probe the specific handle for coreclr_initialize.
395        if !INIT_HOOKED.load(Ordering::SeqCst) {
396            unsafe extern "C" {
397                fn dlsym(handle: *mut c_void, symbol: *const c_char) -> *mut c_void;
398            }
399            let sym = unsafe { dlsym(handle, c"coreclr_initialize".as_ptr()) };
400            if !sym.is_null() {
401                hook_coreclr_init();
402            }
403        }
404    }
405    handle
406}
407
408#[cfg(windows)]
409fn install_loader_hook() {
410    if LOADER_HOOKED.swap(true, Ordering::SeqCst) {
411        return;
412    }
413    // The game's init may have loaded CoreCLR before this ran; if so, hook it
414    // directly, as LoadLibraryExW won't be called for it again.
415    if loaded_coreclr().is_some() {
416        tracing::info!("{CORECLR} is already loaded, hooking coreclr_initialize directly");
417        hook_coreclr_init();
418        return;
419    }
420
421    tracing::info!("hooking LoadLibraryExW to wait for {CORECLR}");
422    match unsafe {
423        hooking::Hook::by_name(
424            Some(c"kernelbase.dll"),
425            c"LoadLibraryExW",
426            loadlibrary_detour as *mut u8,
427        )
428    } {
429        Ok(mut hook) => {
430            if let Err(e) = unsafe { hook.apply_hook() } {
431                tracing::error!("applying the LoadLibraryExW hook failed: {e:?}");
432            }
433            std::mem::forget(hook);
434        }
435        Err(e) => tracing::error!("hooking LoadLibraryExW failed: {e:?}"),
436    }
437}
438
439#[cfg(windows)]
440extern "C" fn loadlibrary_detour(
441    filename: *const u16,
442    file: *mut c_void,
443    flags: u32,
444) -> *mut c_void {
445    let original =
446        hooking::original_function_ptr().expect("original! inside the LoadLibraryExW hook");
447    let original: unsafe extern "C" fn(*const u16, *mut c_void, u32) -> *mut c_void =
448        unsafe { std::mem::transmute(original.as_ptr()) };
449    let handle = unsafe { original(filename, file, flags) };
450    if !handle.is_null() && !INIT_HOOKED.load(Ordering::SeqCst) {
451        if !filename.is_null() {
452            let mut len = 0;
453            while unsafe { *filename.add(len) } != 0 {
454                len += 1;
455            }
456            let name =
457                String::from_utf16_lossy(unsafe { std::slice::from_raw_parts(filename, len) });
458            if name.to_ascii_lowercase().contains(CORECLR) {
459                tracing::info!("{CORECLR} loaded: {name}");
460                hook_coreclr_init();
461            }
462        }
463        // CoreCLR may arrive through a chain (hostfxr -> hostpolicy -> coreclr)
464        // whose module name doesn't contain "coreclr", so the filename check
465        // above misses it. Probe the just-loaded module for coreclr_initialize,
466        // mirroring the dlopen hook's fallback on Unix.
467        if !INIT_HOOKED.load(Ordering::SeqCst) {
468            unsafe extern "system" {
469                fn GetProcAddress(module: *mut c_void, name: *const u8) -> *mut c_void;
470            }
471            let sym = unsafe { GetProcAddress(handle, c"coreclr_initialize".as_ptr().cast()) };
472            if !sym.is_null() {
473                hook_coreclr_init();
474            }
475        }
476    }
477    handle
478}
479
480#[cfg(all(test, target_os = "linux"))]
481mod tests {
482    use super::open_already_loaded;
483
484    fn mapped(name: &str) -> bool {
485        std::fs::read_to_string("/proc/self/maps").is_ok_and(|maps| maps.contains(name))
486    }
487
488    #[test]
489    fn opens_only_loaded_libraries() {
490        // A library a Rust test binary doesn't link; skip if it isn't
491        // installed or something already loaded it.
492        const NAME: &str = "libbz2.so.1";
493        if mapped("libbz2") {
494            eprintln!("skipping: {NAME} is already loaded");
495            return;
496        }
497        assert!(open_already_loaded(NAME).is_err(), "must not load {NAME}");
498        assert!(!mapped("libbz2"), "opening {NAME} loaded it");
499
500        let Ok(loaded) = (unsafe { libloading::Library::new(NAME) }) else {
501            eprintln!("skipping: {NAME} is not installed");
502            return;
503        };
504        assert!(open_already_loaded(NAME).is_ok(), "{NAME} is loaded");
505        drop(loaded);
506    }
507}