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
17use std::{
18    ffi::{c_char, c_int, c_void},
19    sync::{
20        atomic::{AtomicBool, AtomicUsize, Ordering},
21        Mutex, OnceLock,
22    },
23};
24
25use crate::{Result, Runtime};
26
27/// `coreclr_initialize(exePath, friendlyName, propCount, keys, values, &hostHandle, &domainId)`.
28type CoreclrInitialize = unsafe extern "C" fn(
29    *const c_char,
30    *const c_char,
31    c_int,
32    *const *const c_char,
33    *const *const c_char,
34    *mut *mut c_void,
35    *mut u32,
36) -> c_int;
37
38/// `coreclr_create_delegate(hostHandle, domainId, assembly, type, method, &delegate)`.
39type CoreclrCreateDelegate = unsafe extern "C" fn(
40    *mut c_void,
41    u32,
42    *const c_char,
43    *const c_char,
44    *const c_char,
45    *mut *mut c_void,
46) -> c_int;
47
48/// The CoreCLR shared library's file name on this platform.
49const CORECLR: &str = if cfg!(windows) {
50    "coreclr.dll"
51} else {
52    "libcoreclr.so"
53};
54
55/// A handle to the game's running CoreCLR, captured from `coreclr_initialize`.
56#[derive(Clone, Copy)]
57pub struct ClrHost {
58    pub handle: *mut c_void,
59    pub domain: u32,
60    create_delegate: CoreclrCreateDelegate,
61}
62
63// The handle and domain are used across threads; the delegate is thread safe.
64unsafe impl Send for ClrHost {}
65unsafe impl Sync for ClrHost {}
66
67impl ClrHost {
68    /// A native-callable pointer to a static `[UnmanagedCallersOnly]` method
69    /// `type_name::method` in `assembly` (CoreCLR only exposes such methods
70    /// directly; arbitrary methods need a managed loader on top of this).
71    pub fn create_delegate(
72        &self,
73        assembly: &str,
74        type_name: &str,
75        method: &str,
76    ) -> std::result::Result<*mut c_void, String> {
77        use std::ffi::CString;
78        let assembly = CString::new(assembly).map_err(|_| "assembly has a nul")?;
79        let type_name = CString::new(type_name).map_err(|_| "type has a nul")?;
80        let method = CString::new(method).map_err(|_| "method has a nul")?;
81        let mut delegate = std::ptr::null_mut();
82        let code = unsafe {
83            (self.create_delegate)(
84                self.handle,
85                self.domain,
86                assembly.as_ptr(),
87                type_name.as_ptr(),
88                method.as_ptr(),
89                &mut delegate,
90            )
91        };
92        if code != 0 {
93            return Err(format!("coreclr_create_delegate failed: 0x{code:x}"));
94        }
95        Ok(delegate)
96    }
97
98    /// Attaches hao's runtime to the game's CoreCLR, so any managed method can be
99    /// called (via [`Runtime::method_pointer`]). `major` is the game's .NET major
100    /// version (e.g. 9 for a .NET 9 game).
101    pub fn attach(&self, major: u16) -> Result<Runtime> {
102        Runtime::coreclr_attach(
103            self.handle,
104            self.domain,
105            self.create_delegate as *const c_void,
106            major,
107        )
108    }
109}
110
111type Callback = Box<dyn FnOnce(ClrHost) + Send>;
112
113/// Appends a line to `/tmp/hao-diag.log` — early-attach diagnostics that
114/// work before any tracing subscriber exists (and from signal-unsafe spots
115/// where stdout may be redirected by the host process).
116pub fn diag(msg: &str) {
117    use std::io::Write;
118    if let Ok(mut f) = std::fs::OpenOptions::new()
119        .create(true)
120        .append(true)
121        .open("/tmp/hao-diag.log")
122    {
123        let _ = writeln!(f, "[hao-diag] {msg}");
124    }
125}
126
127static CALLBACKS: Mutex<Vec<Callback>> = Mutex::new(Vec::new());
128static HOST: OnceLock<ClrHost> = OnceLock::new();
129static CREATE_DELEGATE: AtomicUsize = AtomicUsize::new(0);
130static LOADER_HOOKED: AtomicBool = AtomicBool::new(false);
131static INIT_HOOKED: AtomicBool = AtomicBool::new(false);
132
133/// Installs the loader hook (`dlopen` / `LoadLibraryExW`) so that the
134/// runtime's library load is detected as early as possible.
135///
136/// Safe to call more than once — subsequent calls are no-ops. Call it from
137/// `.init_array` / `ctor()` when the mod needs the CLR but registers the
138/// [`on_clr_init`] callback later (e.g. from a separate thread).
139pub fn ensure_loader_hook() {
140    install_loader_hook();
141}
142
143/// Runs `callback` once the game's CoreCLR host has been captured. Call it from
144/// a mod's entry point (which the loader runs before the game starts the
145/// runtime).
146///
147/// The callback runs on a background thread, **not** the game's init thread:
148/// running managed code during `coreclr_initialize` corrupts the runtime's
149/// bootstrap and crashes the game. It is therefore also not on any engine main
150/// thread, so it may call thread-agnostic (corlib) methods but must not touch a
151/// main-thread-only API until it has a main-thread callback to run on.
152pub fn on_clr_init(callback: impl FnOnce(ClrHost) + Send + 'static) {
153    if let Some(host) = HOST.get() {
154        diag("on_clr_init: HOST already set, fast path");
155        let host = *host;
156        std::thread::spawn(move || callback(host));
157        return;
158    }
159    // Attach-time injection: the stub may load *after* the game already ran
160    // coreclr_initialize, so hooking it would never fire. If the CLR is already
161    // up, capture its host directly from the exported GetCLRRuntimeHost and run
162    // the callback now (the runtime is fully started, so managed code is safe).
163    #[cfg(target_arch = "x86_64")]
164    if let Some(host) = try_capture_running_host() {
165        diag("on_clr_init: captured already-running CLR via GetCLRRuntimeHost");
166        let host = *HOST.get_or_init(|| host);
167        std::thread::spawn(move || callback(host));
168        return;
169    }
170
171    diag("on_clr_init: HOST not set, registering callback + loader hook");
172    CALLBACKS
173        .lock()
174        .unwrap_or_else(|e| e.into_inner())
175        .push(Box::new(callback));
176    install_loader_hook();
177}
178
179/// If CoreCLR is already loaded *and initialized* (attach-time injection, after
180/// `coreclr_initialize` has run), capture the running host without hooking init.
181///
182/// hao runs inside the target process, so it can call the exported
183/// `GetCLRRuntimeHost` directly: it returns the live `CorHost2` (the same object
184/// `coreclr_create_delegate` expects), accepting `IID_IUnknown`. The default
185/// AppDomain id is 1. Returns `None` if CoreCLR isn't loaded or isn't started
186/// yet, in which case the caller falls back to hooking `coreclr_initialize`.
187#[cfg(target_arch = "x86_64")]
188fn try_capture_running_host() -> Option<ClrHost> {
189    // IID_IUnknown {00000000-0000-0000-C000-000000000046}.
190    const IID_IUNKNOWN: [u8; 16] = [0, 0, 0, 0, 0, 0, 0, 0, 0xc0, 0, 0, 0, 0, 0, 0, 0x46];
191    type GetClrRuntimeHost = unsafe extern "C" fn(*const u8, *mut *mut c_void) -> c_int;
192
193    // CoreCLR is loaded by full path; dlopen by soname returns the same handle
194    // (no second copy). If it isn't loaded, this fails → fall back.
195    let lib = unsafe { libloading::Library::new(CORECLR) }.ok()?;
196    let get_host = unsafe { lib.get::<GetClrRuntimeHost>(b"GetCLRRuntimeHost\0") }.ok()?;
197    let create = unsafe { lib.get::<CoreclrCreateDelegate>(b"coreclr_create_delegate\0") }.ok()?;
198    let create_delegate: CoreclrCreateDelegate = *create;
199
200    let mut host: *mut c_void = std::ptr::null_mut();
201    let code = unsafe { (*get_host)(IID_IUNKNOWN.as_ptr(), &mut host) };
202    std::mem::forget(lib); // keep CoreCLR mapped for the life of the process
203
204    if code != 0 || host.is_null() {
205        return None; // not initialized yet → hook coreclr_initialize instead
206    }
207    Some(ClrHost {
208        handle: host,
209        domain: 1,
210        create_delegate,
211    })
212}
213
214/// Runs the queued callbacks on a background thread, off the init thread.
215fn run_callbacks(host: ClrHost) {
216    std::thread::spawn(move || {
217        let callbacks = std::mem::take(&mut *CALLBACKS.lock().unwrap_or_else(|e| e.into_inner()));
218        for callback in callbacks {
219            callback(host);
220        }
221    });
222}
223
224fn hook_coreclr_init() {
225    if INIT_HOOKED.swap(true, Ordering::SeqCst) {
226        return;
227    }
228    let lib = match unsafe { libloading::Library::new(CORECLR) } {
229        Ok(lib) => lib,
230        Err(e) => {
231            tracing::error!("could not open {CORECLR}: {e}");
232            return;
233        }
234    };
235    let init = unsafe { lib.get::<CoreclrInitialize>(b"coreclr_initialize\0") };
236    let create = unsafe { lib.get::<CoreclrCreateDelegate>(b"coreclr_create_delegate\0") };
237    let (Ok(init), Ok(create)) = (init, create) else {
238        tracing::error!("coreclr_initialize or coreclr_create_delegate not found in {CORECLR}");
239        return;
240    };
241    let init_addr = (*init) as usize as *mut u8;
242    CREATE_DELEGATE.store((*create) as usize, Ordering::SeqCst);
243    std::mem::forget(lib); // keep CoreCLR loaded for the life of the process
244
245    tracing::info!("hooking coreclr_initialize");
246    match unsafe { hooking::Hook::create(init_addr, coreclr_init_detour as *mut u8) } {
247        Ok(mut hook) => {
248            if let Err(e) = unsafe { hook.apply_hook() } {
249                tracing::error!("applying the coreclr_initialize hook failed: {e:?}");
250            }
251            std::mem::forget(hook);
252        }
253        Err(e) => tracing::error!("hooking coreclr_initialize failed: {e:?}"),
254    }
255}
256
257extern "C" fn coreclr_init_detour(
258    exe: *const c_char,
259    name: *const c_char,
260    count: c_int,
261    keys: *const *const c_char,
262    values: *const *const c_char,
263    host_handle: *mut *mut c_void,
264    domain_id: *mut u32,
265) -> c_int {
266    let original =
267        hooking::original_function_ptr().expect("original! inside the coreclr_initialize hook");
268    let original: CoreclrInitialize = unsafe { std::mem::transmute(original.as_ptr()) };
269
270    // Arm assembly interception BEFORE the original coreclr_initialize runs.
271    // The CLR opens assemblies (including GodotSharp.dll) during init, so
272    // the open/openat hooks must be in place before the first assembly load.
273    // The redirect() function only intercepts registered target basenames —
274    // all other file opens pass through, so this is safe.
275    diag("coreclr_init_detour entered, arming interception");
276    #[cfg(all(unix, target_arch = "x86_64"))]
277    crate::rewrite::arm_interception();
278    diag("arm_interception done, calling original");
279
280    let result = unsafe { original(exe, name, count, keys, values, host_handle, domain_id) };
281    diag(&format!("coreclr_initialize returned 0x{result:x}"));
282    tracing::info!("coreclr_initialize returned 0x{result:x}");
283
284    if result == 0 && !host_handle.is_null() && !domain_id.is_null() {
285        let handle = unsafe { *host_handle };
286        let domain = unsafe { *domain_id };
287        let create = CREATE_DELEGATE.load(Ordering::SeqCst);
288        if create != 0 {
289            let host = ClrHost {
290                handle,
291                domain,
292                create_delegate: unsafe {
293                    std::mem::transmute::<usize, CoreclrCreateDelegate>(create)
294                },
295            };
296            tracing::info!("captured CLR host: handle={handle:?}, domain={domain}");
297            let _ = HOST.set(host);
298            run_callbacks(host);
299        }
300    }
301    result
302}
303
304// --- loader hook (the only platform-specific part) -----------------------
305
306#[cfg(unix)]
307fn install_loader_hook() {
308    if LOADER_HOOKED.swap(true, Ordering::SeqCst) {
309        return;
310    }
311    // Check whether CoreCLR is already loaded (the game's init may have
312    // loaded it before our thread started).  RTLD_DEFAULT searches all
313    // loaded shared objects — if coreclr_initialize is resolvable, the
314    // runtime is already in the process and we hook it directly.
315    unsafe extern "C" {
316        fn dlsym(handle: *mut c_void, symbol: *const c_char) -> *mut c_void;
317    }
318    const RTLD_DEFAULT: *mut c_void = std::ptr::null_mut();
319    let probe = unsafe { dlsym(RTLD_DEFAULT, c"coreclr_initialize".as_ptr()) };
320    if !probe.is_null() {
321        diag("coreclr already loaded, hooking directly");
322        tracing::info!("{CORECLR} is already loaded, hooking coreclr_initialize directly");
323        hook_coreclr_init();
324        return;
325    }
326
327    diag("hooking dlopen to wait for coreclr");
328    tracing::info!("hooking dlopen to wait for {CORECLR}");
329    match unsafe { hooking::Hook::by_name(None, c"dlopen", dlopen_detour as *mut u8) } {
330        Ok(mut hook) => {
331            if let Err(e) = unsafe { hook.apply_hook() } {
332                tracing::error!("applying the dlopen hook failed: {e:?}");
333            }
334            std::mem::forget(hook);
335        }
336        Err(e) => tracing::error!("hooking dlopen failed: {e:?}"),
337    }
338}
339
340#[cfg(unix)]
341extern "C" fn dlopen_detour(filename: *const c_char, flags: c_int) -> *mut c_void {
342    // Must be the first thing the detour does (it reads scratch registers).
343    let original = hooking::original_function_ptr().expect("original! inside the dlopen hook");
344    let original: unsafe extern "C" fn(*const c_char, c_int) -> *mut c_void =
345        unsafe { std::mem::transmute(original.as_ptr()) };
346    let handle = unsafe { original(filename, flags) };
347    if !handle.is_null() && !INIT_HOOKED.load(Ordering::SeqCst) {
348        if !filename.is_null() {
349            let name = unsafe { std::ffi::CStr::from_ptr(filename) }.to_string_lossy();
350            if name.contains(CORECLR) {
351                tracing::info!("{CORECLR} loaded: {name}");
352                hook_coreclr_init();
353            }
354        }
355        // CoreCLR may arrive through a chain (hostfxr → hostpolicy →
356        // coreclr) where intermediate loads don't mention "coreclr" in
357        // the filename.  Probe the specific handle for coreclr_initialize.
358        if !INIT_HOOKED.load(Ordering::SeqCst) {
359            unsafe extern "C" {
360                fn dlsym(handle: *mut c_void, symbol: *const c_char) -> *mut c_void;
361            }
362            let sym = unsafe { dlsym(handle, c"coreclr_initialize".as_ptr()) };
363            if !sym.is_null() {
364                hook_coreclr_init();
365            }
366        }
367    }
368    handle
369}
370
371#[cfg(windows)]
372fn install_loader_hook() {
373    if LOADER_HOOKED.swap(true, Ordering::SeqCst) {
374        return;
375    }
376    tracing::info!("hooking LoadLibraryExW to wait for {CORECLR}");
377    match unsafe {
378        hooking::Hook::by_name(
379            Some(c"kernelbase.dll"),
380            c"LoadLibraryExW",
381            loadlibrary_detour as *mut u8,
382        )
383    } {
384        Ok(mut hook) => {
385            if let Err(e) = unsafe { hook.apply_hook() } {
386                tracing::error!("applying the LoadLibraryExW hook failed: {e:?}");
387            }
388            std::mem::forget(hook);
389        }
390        Err(e) => tracing::error!("hooking LoadLibraryExW failed: {e:?}"),
391    }
392}
393
394#[cfg(windows)]
395extern "C" fn loadlibrary_detour(
396    filename: *const u16,
397    file: *mut c_void,
398    flags: u32,
399) -> *mut c_void {
400    let original =
401        hooking::original_function_ptr().expect("original! inside the LoadLibraryExW hook");
402    let original: unsafe extern "C" fn(*const u16, *mut c_void, u32) -> *mut c_void =
403        unsafe { std::mem::transmute(original.as_ptr()) };
404    let handle = unsafe { original(filename, file, flags) };
405    if !handle.is_null() && !filename.is_null() && !INIT_HOOKED.load(Ordering::SeqCst) {
406        let mut len = 0;
407        while unsafe { *filename.add(len) } != 0 {
408            len += 1;
409        }
410        let name = String::from_utf16_lossy(unsafe { std::slice::from_raw_parts(filename, len) });
411        if name.to_ascii_lowercase().contains(CORECLR) {
412            tracing::info!("{CORECLR} loaded: {name}");
413            hook_coreclr_init();
414        }
415    }
416    handle
417}