hao-runtime 0.0.17

Host the .net runtime (CoreCLR or Mono) in a rust process
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
//! Attach to a CoreCLR game's already-running runtime from a native mod loaded
//! before the runtime starts (via `LD_PRELOAD` on Linux, or an injected DLL on
//! Windows).
//!
//! CoreCLR has no public "attach to the running runtime" C API:
//! `coreclr_create_delegate` needs the host handle and domain id the game's host
//! created, and the runtime initialises only once per process. So we capture
//! them as the game creates them — inline-hooking the loader to see `coreclr`
//! arrive (it is loaded late and resolved dynamically, so symbol interposition
//! misses it), then inline-hooking `coreclr_initialize` to read its output.
//!
//! The loader differs per platform (`dlopen` / `LoadLibraryExW`); everything
//! else, including the `coreclr_initialize` hook, is shared. Requires x86_64,
//! where the inline-hook trampoline works. With the captured [`ClrHost`],
//! [`ClrHost::attach`] builds a [`Runtime`] bound to that CLR.
//!
//! ```no_run
//! // In the mod's entry point, which runs before the game starts .NET.
//! hao_runtime::attach::on_clr_init(|host| {
//!     // A .NET 8 game. This runs on a background thread, so call only
//!     // thread-agnostic methods here.
//!     let runtime = host.attach(8).expect("attach to the game's CoreCLR");
//!     let main = runtime.method_pointer("MyMod", "MyMod.Entry", "Run");
//!     # let _ = main;
//! });
//! ```

use std::{
    ffi::{c_char, c_int, c_void},
    sync::{
        atomic::{AtomicBool, AtomicUsize, Ordering},
        Mutex, OnceLock,
    },
};

use crate::{Result, Runtime};

/// `coreclr_initialize(exePath, friendlyName, propCount, keys, values, &hostHandle, &domainId)`.
type CoreclrInitialize = unsafe extern "C" fn(
    *const c_char,
    *const c_char,
    c_int,
    *const *const c_char,
    *const *const c_char,
    *mut *mut c_void,
    *mut u32,
) -> c_int;

/// `coreclr_create_delegate(hostHandle, domainId, assembly, type, method, &delegate)`.
type CoreclrCreateDelegate = unsafe extern "C" fn(
    *mut c_void,
    u32,
    *const c_char,
    *const c_char,
    *const c_char,
    *mut *mut c_void,
) -> c_int;

/// The CoreCLR shared library's file name on this platform.
const CORECLR: &str = if cfg!(windows) {
    "coreclr.dll"
} else {
    "libcoreclr.so"
};

/// A handle to the game's running CoreCLR, captured from `coreclr_initialize`.
#[derive(Clone, Copy)]
pub struct ClrHost {
    /// The host handle `coreclr_initialize` returned, which
    /// `coreclr_create_delegate` needs.
    pub handle: *mut c_void,
    /// The id of the app domain the game's host created.
    pub domain: u32,
    create_delegate: CoreclrCreateDelegate,
}

// The handle and domain are used across threads; the delegate is thread safe.
unsafe impl Send for ClrHost {}
unsafe impl Sync for ClrHost {}

impl ClrHost {
    /// A native-callable pointer to a static `[UnmanagedCallersOnly]` method
    /// `type_name::method` in `assembly` (CoreCLR only exposes such methods
    /// directly; arbitrary methods need a managed loader on top of this).
    pub fn create_delegate(
        &self,
        assembly: &str,
        type_name: &str,
        method: &str,
    ) -> std::result::Result<*mut c_void, String> {
        use std::ffi::CString;
        let assembly = CString::new(assembly).map_err(|_| "assembly has a nul")?;
        let type_name = CString::new(type_name).map_err(|_| "type has a nul")?;
        let method = CString::new(method).map_err(|_| "method has a nul")?;
        let mut delegate = std::ptr::null_mut();
        let code = unsafe {
            (self.create_delegate)(
                self.handle,
                self.domain,
                assembly.as_ptr(),
                type_name.as_ptr(),
                method.as_ptr(),
                &mut delegate,
            )
        };
        if code != 0 {
            return Err(format!("coreclr_create_delegate failed: 0x{code:x}"));
        }
        Ok(delegate)
    }

    /// Attaches hao's runtime to the game's CoreCLR, so any managed method can be
    /// called (via [`Runtime::method_pointer`]). `major` is the game's .NET major
    /// version (e.g. 9 for a .NET 9 game).
    pub fn attach(&self, major: u16) -> Result<Runtime> {
        Runtime::coreclr_attach(
            self.handle,
            self.domain,
            self.create_delegate as *const c_void,
            major,
        )
    }
}

type Callback = Box<dyn FnOnce(ClrHost) + Send>;

/// Logs an early-attach diagnostic at `debug` level (target
/// `hao_runtime::attach`), for tracing a mod's startup.
pub fn diag(msg: &str) {
    tracing::debug!("{msg}");
}

static CALLBACKS: Mutex<Vec<Callback>> = Mutex::new(Vec::new());
/// The game's CoreCLR, opened once it is loaded. Holding it here keeps the
/// library (and the function pointers taken from it) alive: the runtime is
/// never unloaded, so it is never closed.
static CORECLR_LIBRARY: OnceLock<libloading::Library> = OnceLock::new();
static HOST: OnceLock<ClrHost> = OnceLock::new();
static CREATE_DELEGATE: AtomicUsize = AtomicUsize::new(0);
static LOADER_HOOKED: AtomicBool = AtomicBool::new(false);
static INIT_HOOKED: AtomicBool = AtomicBool::new(false);

/// Installs the loader hook (`dlopen` / `LoadLibraryExW`) so that the
/// runtime's library load is detected as early as possible.
///
/// Safe to call more than once — subsequent calls are no-ops. Call it from
/// `.init_array` / `ctor()` when the mod needs the CLR but registers the
/// [`on_clr_init`] callback later (e.g. from a separate thread).
pub fn ensure_loader_hook() {
    install_loader_hook();
}

/// Runs `callback` once the game's CoreCLR host has been captured. Call it from
/// a mod's entry point (which the loader runs before the game starts the
/// runtime).
///
/// The callback runs on a background thread, **not** the game's init thread:
/// running managed code during `coreclr_initialize` corrupts the runtime's
/// bootstrap and crashes the game. It is therefore also not on any engine main
/// thread, so it may call thread-agnostic (corlib) methods but must not touch a
/// main-thread-only API until it has a main-thread callback to run on.
pub fn on_clr_init(callback: impl FnOnce(ClrHost) + Send + 'static) {
    if let Some(host) = HOST.get() {
        tracing::debug!("on_clr_init: host already captured");
        let host = *host;
        std::thread::spawn(move || callback(host));
        return;
    }
    // Attach-time injection: the stub may load *after* the game already ran
    // coreclr_initialize, so hooking it would never fire. If the CLR is already
    // up, capture its host directly from the exported GetCLRRuntimeHost and run
    // the callback now (the runtime is fully started, so managed code is safe).
    #[cfg(target_arch = "x86_64")]
    if let Some(host) = try_capture_running_host() {
        tracing::debug!("on_clr_init: captured the running CLR via GetCLRRuntimeHost");
        let host = *HOST.get_or_init(|| host);
        std::thread::spawn(move || callback(host));
        return;
    }

    tracing::debug!("on_clr_init: CLR not started, waiting for coreclr_initialize");
    CALLBACKS
        .lock()
        .unwrap_or_else(|e| e.into_inner())
        .push(Box::new(callback));
    install_loader_hook();
}

/// If CoreCLR is already loaded *and initialized* (attach-time injection, after
/// `coreclr_initialize` has run), capture the running host without hooking init.
///
/// hao runs inside the target process, so it can call the exported
/// `GetCLRRuntimeHost` directly: it returns the live `CorHost2` (the same object
/// `coreclr_create_delegate` expects), accepting `IID_IUnknown`. The default
/// AppDomain id is 1. Returns `None` if CoreCLR isn't loaded or isn't started
/// yet, in which case the caller falls back to hooking `coreclr_initialize`.
#[cfg(target_arch = "x86_64")]
fn try_capture_running_host() -> Option<ClrHost> {
    // IID_IUnknown {00000000-0000-0000-C000-000000000046}.
    const IID_IUNKNOWN: [u8; 16] = [0, 0, 0, 0, 0, 0, 0, 0, 0xc0, 0, 0, 0, 0, 0, 0, 0x46];
    type GetClrRuntimeHost = unsafe extern "C" fn(*const u8, *mut *mut c_void) -> c_int;

    let lib = loaded_coreclr()?;
    let get_host = unsafe { lib.get::<GetClrRuntimeHost>(b"GetCLRRuntimeHost\0") }.ok()?;
    let create = unsafe { lib.get::<CoreclrCreateDelegate>(b"coreclr_create_delegate\0") }.ok()?;
    let create_delegate: CoreclrCreateDelegate = *create;

    let mut host: *mut c_void = std::ptr::null_mut();
    let code = unsafe { (*get_host)(IID_IUNKNOWN.as_ptr(), &mut host) };

    if code != 0 || host.is_null() {
        return None; // not initialized yet → hook coreclr_initialize instead
    }
    Some(ClrHost {
        handle: host,
        domain: 1,
        create_delegate,
    })
}

/// The game's CoreCLR if it is already loaded, kept open for the life of the
/// process. Never loads it: opening `libcoreclr.so` / `coreclr.dll` by name
/// could otherwise load a different (system) copy before the game loads its own.
fn loaded_coreclr() -> Option<&'static libloading::Library> {
    if let Some(lib) = CORECLR_LIBRARY.get() {
        return Some(lib);
    }
    // Opened outside `get_or_init`: on Unix the open goes through the `dlopen`
    // hook, which may re-enter here. If both set it, the spare handle is closed
    // and the library stays loaded through the other.
    let lib = match open_already_loaded(CORECLR) {
        Ok(lib) => lib,
        Err(e) => {
            tracing::debug!("{CORECLR} is not loaded yet: {e}");
            return None;
        }
    };
    let _ = CORECLR_LIBRARY.set(lib);
    CORECLR_LIBRARY.get()
}

/// Opens the library `name` only if it is already loaded in the process
/// (`dlopen` with `RTLD_NOLOAD` / `GetModuleHandleExW`).
#[cfg(unix)]
fn open_already_loaded(name: &str) -> std::result::Result<libloading::Library, libloading::Error> {
    use libloading::os::unix::{Library, RTLD_NOW};
    // Not exported by libloading.
    #[cfg(any(target_os = "linux", target_os = "android"))]
    const RTLD_NOLOAD: c_int = 0x4;
    #[cfg(any(target_os = "macos", target_os = "ios"))]
    const RTLD_NOLOAD: c_int = 0x10;
    #[cfg(target_os = "freebsd")]
    const RTLD_NOLOAD: c_int = 0x2000;
    unsafe { Library::open(Some(name), RTLD_NOLOAD | RTLD_NOW) }.map(Into::into)
}

/// Opens the library `name` only if it is already loaded in the process
/// (`dlopen` with `RTLD_NOLOAD` / `GetModuleHandleExW`).
#[cfg(windows)]
fn open_already_loaded(name: &str) -> std::result::Result<libloading::Library, libloading::Error> {
    libloading::os::windows::Library::open_already_loaded(name).map(Into::into)
}

/// Runs the queued callbacks on a background thread, off the init thread.
fn run_callbacks(host: ClrHost) {
    std::thread::spawn(move || {
        let callbacks = std::mem::take(&mut *CALLBACKS.lock().unwrap_or_else(|e| e.into_inner()));
        for callback in callbacks {
            callback(host);
        }
    });
}

fn hook_coreclr_init() {
    if INIT_HOOKED.swap(true, Ordering::SeqCst) {
        return;
    }
    let Some(lib) = loaded_coreclr() else {
        tracing::error!("{CORECLR} is not loaded, not hooking coreclr_initialize");
        INIT_HOOKED.store(false, Ordering::SeqCst);
        return;
    };
    let init = unsafe { lib.get::<CoreclrInitialize>(b"coreclr_initialize\0") };
    let create = unsafe { lib.get::<CoreclrCreateDelegate>(b"coreclr_create_delegate\0") };
    let (Ok(init), Ok(create)) = (init, create) else {
        tracing::error!("coreclr_initialize or coreclr_create_delegate not found in {CORECLR}");
        return;
    };
    let init_addr = (*init) as usize as *mut u8;
    CREATE_DELEGATE.store((*create) as usize, Ordering::SeqCst);

    tracing::info!("hooking coreclr_initialize");
    match unsafe { hooking::Hook::create(init_addr, coreclr_init_detour as *mut u8) } {
        Ok(mut hook) => {
            if let Err(e) = unsafe { hook.apply_hook() } {
                tracing::error!("applying the coreclr_initialize hook failed: {e:?}");
            }
            std::mem::forget(hook);
        }
        Err(e) => tracing::error!("hooking coreclr_initialize failed: {e:?}"),
    }
}

extern "C" fn coreclr_init_detour(
    exe: *const c_char,
    name: *const c_char,
    count: c_int,
    keys: *const *const c_char,
    values: *const *const c_char,
    host_handle: *mut *mut c_void,
    domain_id: *mut u32,
) -> c_int {
    let original =
        hooking::original_function_ptr().expect("original! inside the coreclr_initialize hook");
    let original: CoreclrInitialize = unsafe { std::mem::transmute(original.as_ptr()) };

    // Arm assembly interception BEFORE the original coreclr_initialize runs.
    // The CLR opens assemblies (including GodotSharp.dll) during init, so
    // the open/openat hooks must be in place before the first assembly load.
    // The redirect() function only intercepts registered target basenames —
    // all other file opens pass through, so this is safe.
    tracing::debug!("coreclr_initialize called, arming assembly interception");
    #[cfg(all(unix, target_arch = "x86_64"))]
    crate::rewrite::arm_interception();

    let result = unsafe { original(exe, name, count, keys, values, host_handle, domain_id) };
    tracing::info!("coreclr_initialize returned 0x{result:x}");

    if result == 0 && !host_handle.is_null() && !domain_id.is_null() {
        let handle = unsafe { *host_handle };
        let domain = unsafe { *domain_id };
        let create = CREATE_DELEGATE.load(Ordering::SeqCst);
        if create != 0 {
            let host = ClrHost {
                handle,
                domain,
                create_delegate: unsafe {
                    std::mem::transmute::<usize, CoreclrCreateDelegate>(create)
                },
            };
            tracing::info!("captured CLR host: handle={handle:?}, domain={domain}");
            let _ = HOST.set(host);
            run_callbacks(host);
        }
    }
    result
}

// --- loader hook (the only platform-specific part) -----------------------

#[cfg(unix)]
fn install_loader_hook() {
    if LOADER_HOOKED.swap(true, Ordering::SeqCst) {
        return;
    }
    // The game's init may have loaded CoreCLR before this ran; if so, hook it
    // directly. (Not `dlsym(RTLD_DEFAULT, ..)`: the host loads CoreCLR
    // `RTLD_LOCAL`, so its symbols aren't in the global scope.)
    if loaded_coreclr().is_some() {
        tracing::info!("{CORECLR} is already loaded, hooking coreclr_initialize directly");
        hook_coreclr_init();
        return;
    }

    tracing::info!("hooking dlopen to wait for {CORECLR}");
    match unsafe { hooking::Hook::by_name(None, c"dlopen", dlopen_detour as *mut u8) } {
        Ok(mut hook) => {
            if let Err(e) = unsafe { hook.apply_hook() } {
                tracing::error!("applying the dlopen hook failed: {e:?}");
            }
            std::mem::forget(hook);
        }
        Err(e) => tracing::error!("hooking dlopen failed: {e:?}"),
    }
}

#[cfg(unix)]
extern "C" fn dlopen_detour(filename: *const c_char, flags: c_int) -> *mut c_void {
    // Must be the first thing the detour does (it reads scratch registers).
    let original = hooking::original_function_ptr().expect("original! inside the dlopen hook");
    let original: unsafe extern "C" fn(*const c_char, c_int) -> *mut c_void =
        unsafe { std::mem::transmute(original.as_ptr()) };
    let handle = unsafe { original(filename, flags) };
    if !handle.is_null() && !INIT_HOOKED.load(Ordering::SeqCst) {
        if !filename.is_null() {
            let name = unsafe { std::ffi::CStr::from_ptr(filename) }.to_string_lossy();
            if name.contains(CORECLR) {
                tracing::info!("{CORECLR} loaded: {name}");
                hook_coreclr_init();
            }
        }
        // CoreCLR may arrive through a chain (hostfxr → hostpolicy →
        // coreclr) where intermediate loads don't mention "coreclr" in
        // the filename.  Probe the specific handle for coreclr_initialize.
        if !INIT_HOOKED.load(Ordering::SeqCst) {
            unsafe extern "C" {
                fn dlsym(handle: *mut c_void, symbol: *const c_char) -> *mut c_void;
            }
            let sym = unsafe { dlsym(handle, c"coreclr_initialize".as_ptr()) };
            if !sym.is_null() {
                hook_coreclr_init();
            }
        }
    }
    handle
}

#[cfg(windows)]
fn install_loader_hook() {
    if LOADER_HOOKED.swap(true, Ordering::SeqCst) {
        return;
    }
    // The game's init may have loaded CoreCLR before this ran; if so, hook it
    // directly, as LoadLibraryExW won't be called for it again.
    if loaded_coreclr().is_some() {
        tracing::info!("{CORECLR} is already loaded, hooking coreclr_initialize directly");
        hook_coreclr_init();
        return;
    }

    tracing::info!("hooking LoadLibraryExW to wait for {CORECLR}");
    match unsafe {
        hooking::Hook::by_name(
            Some(c"kernelbase.dll"),
            c"LoadLibraryExW",
            loadlibrary_detour as *mut u8,
        )
    } {
        Ok(mut hook) => {
            if let Err(e) = unsafe { hook.apply_hook() } {
                tracing::error!("applying the LoadLibraryExW hook failed: {e:?}");
            }
            std::mem::forget(hook);
        }
        Err(e) => tracing::error!("hooking LoadLibraryExW failed: {e:?}"),
    }
}

#[cfg(windows)]
extern "C" fn loadlibrary_detour(
    filename: *const u16,
    file: *mut c_void,
    flags: u32,
) -> *mut c_void {
    let original =
        hooking::original_function_ptr().expect("original! inside the LoadLibraryExW hook");
    let original: unsafe extern "C" fn(*const u16, *mut c_void, u32) -> *mut c_void =
        unsafe { std::mem::transmute(original.as_ptr()) };
    let handle = unsafe { original(filename, file, flags) };
    if !handle.is_null() && !INIT_HOOKED.load(Ordering::SeqCst) {
        if !filename.is_null() {
            let mut len = 0;
            while unsafe { *filename.add(len) } != 0 {
                len += 1;
            }
            let name =
                String::from_utf16_lossy(unsafe { std::slice::from_raw_parts(filename, len) });
            if name.to_ascii_lowercase().contains(CORECLR) {
                tracing::info!("{CORECLR} loaded: {name}");
                hook_coreclr_init();
            }
        }
        // CoreCLR may arrive through a chain (hostfxr -> hostpolicy -> coreclr)
        // whose module name doesn't contain "coreclr", so the filename check
        // above misses it. Probe the just-loaded module for coreclr_initialize,
        // mirroring the dlopen hook's fallback on Unix.
        if !INIT_HOOKED.load(Ordering::SeqCst) {
            unsafe extern "system" {
                fn GetProcAddress(module: *mut c_void, name: *const u8) -> *mut c_void;
            }
            let sym = unsafe { GetProcAddress(handle, c"coreclr_initialize".as_ptr().cast()) };
            if !sym.is_null() {
                hook_coreclr_init();
            }
        }
    }
    handle
}

#[cfg(all(test, target_os = "linux"))]
mod tests {
    use super::open_already_loaded;

    fn mapped(name: &str) -> bool {
        std::fs::read_to_string("/proc/self/maps").is_ok_and(|maps| maps.contains(name))
    }

    #[test]
    fn opens_only_loaded_libraries() {
        // A library a Rust test binary doesn't link; skip if it isn't
        // installed or something already loaded it.
        const NAME: &str = "libbz2.so.1";
        if mapped("libbz2") {
            eprintln!("skipping: {NAME} is already loaded");
            return;
        }
        assert!(open_already_loaded(NAME).is_err(), "must not load {NAME}");
        assert!(!mapped("libbz2"), "opening {NAME} loaded it");

        let Ok(loaded) = (unsafe { libloading::Library::new(NAME) }) else {
            eprintln!("skipping: {NAME} is not installed");
            return;
        };
        assert!(open_already_loaded(NAME).is_ok(), "{NAME} is loaded");
        drop(loaded);
    }
}