hao-runtime 0.0.11

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
//! 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.

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 {
    pub handle: *mut c_void,
    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>;

/// Appends a line to `/tmp/hao-diag.log` — early-attach diagnostics that
/// work before any tracing subscriber exists (and from signal-unsafe spots
/// where stdout may be redirected by the host process).
pub fn diag(msg: &str) {
    use std::io::Write;
    if let Ok(mut f) = std::fs::OpenOptions::new()
        .create(true)
        .append(true)
        .open("/tmp/hao-diag.log")
    {
        let _ = writeln!(f, "[hao-diag] {msg}");
    }
}

static CALLBACKS: Mutex<Vec<Callback>> = Mutex::new(Vec::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() {
        diag("on_clr_init: HOST already set, fast path");
        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() {
        diag("on_clr_init: captured already-running CLR via GetCLRRuntimeHost");
        let host = *HOST.get_or_init(|| host);
        std::thread::spawn(move || callback(host));
        return;
    }

    diag("on_clr_init: HOST not set, registering callback + loader hook");
    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;

    // CoreCLR is loaded by full path; dlopen by soname returns the same handle
    // (no second copy). If it isn't loaded, this fails → fall back.
    let lib = unsafe { libloading::Library::new(CORECLR) }.ok()?;
    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) };
    std::mem::forget(lib); // keep CoreCLR mapped for the life of the process

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

/// 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 lib = match unsafe { libloading::Library::new(CORECLR) } {
        Ok(lib) => lib,
        Err(e) => {
            tracing::error!("could not open {CORECLR}: {e}");
            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);
    std::mem::forget(lib); // keep CoreCLR loaded for the life of the process

    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.
    diag("coreclr_init_detour entered, arming interception");
    #[cfg(all(unix, target_arch = "x86_64"))]
    crate::rewrite::arm_interception();
    diag("arm_interception done, calling original");

    let result = unsafe { original(exe, name, count, keys, values, host_handle, domain_id) };
    diag(&format!("coreclr_initialize returned 0x{result:x}"));
    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;
    }
    // Check whether CoreCLR is already loaded (the game's init may have
    // loaded it before our thread started).  RTLD_DEFAULT searches all
    // loaded shared objects — if coreclr_initialize is resolvable, the
    // runtime is already in the process and we hook it directly.
    unsafe extern "C" {
        fn dlsym(handle: *mut c_void, symbol: *const c_char) -> *mut c_void;
    }
    const RTLD_DEFAULT: *mut c_void = std::ptr::null_mut();
    let probe = unsafe { dlsym(RTLD_DEFAULT, c"coreclr_initialize".as_ptr()) };
    if !probe.is_null() {
        diag("coreclr already loaded, hooking directly");
        tracing::info!("{CORECLR} is already loaded, hooking coreclr_initialize directly");
        hook_coreclr_init();
        return;
    }

    diag("hooking dlopen to wait for coreclr");
    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;
    }
    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() && !filename.is_null() && !INIT_HOOKED.load(Ordering::SeqCst) {
        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();
        }
    }
    handle
}