Skip to main content

hao_runtime/
rewrite.rs

1//! Rewrite a managed assembly's IL with hao before the runtime JITs it.
2//!
3//! The Godot/CoreCLR modding path: a native mod intercepts the game assembly's
4//! load (see [`intercept_assembly`]) and hands CoreCLR a hao-rewritten copy. The
5//! rewrite ([`patch_call`]) adds a `[DllImport]`-style P/Invoke to a function the
6//! mod exports and calls it from a lifecycle method — so the method the engine
7//! already runs each frame on the main thread now also calls back into Rust. No
8//! injected assembly, no C#; pure LD_PRELOAD + hao.
9
10use hao::{
11    dotnet::{
12        entries::{Entry, ImplMap, Method, ModuleRef, TypeDef},
13        il::Instruction,
14        md::streams::tables_stream::{MethodFlags, PInvokeMapFlags},
15        signature::{MethodSig, TypeSig},
16    },
17    Module,
18};
19
20use crate::{Error, Result};
21
22/// Rewrites `assembly` so `type_name::method_name` begins by calling the native
23/// function `symbol`, exported from `library` (resolved as a `[DllImport]`).
24/// Returns the patched assembly bytes.
25///
26/// The native function is bound as `static extern void symbol()`, so it takes no
27/// arguments; it runs wherever the engine calls the patched method.
28pub fn patch_call(
29    assembly: &[u8],
30    type_name: &str,
31    method_name: &str,
32    library: &str,
33    symbol: &str,
34) -> Result<Vec<u8>> {
35    let mut module =
36        Module::from_bytes(assembly).map_err(|e| Error::Other(format!("reading assembly: {e}")))?;
37
38    let target = module
39        .find_method(type_name, method_name)
40        .ok_or_else(|| Error::NotFound(format!("{type_name}::{method_name}")))?;
41    let declaring = target
42        .get()
43        .declaring_type
44        .upgrade()
45        .ok_or_else(|| Error::Other(format!("{type_name} has no declaring type")))?;
46
47    // Add `static extern void symbol()`, forwarded to `library` via P/Invoke.
48    let module_ref = Entry::new(ModuleRef {
49        name: library.to_string(),
50        ..Default::default()
51    });
52    module.module_refs.push(module_ref.clone());
53    let mut pinvoke = Method::public_static(symbol, MethodSig::new_static(TypeSig::VOID, vec![]));
54    pinvoke.flags |= MethodFlags::PinvokeImpl;
55    pinvoke.impl_map = Some(ImplMap {
56        flags: PInvokeMapFlags::CallConvCdecl | PInvokeMapFlags::NoMangle,
57        import_name: symbol.to_string(),
58        scope: module_ref,
59    });
60    let pinvoke = TypeDef::add_method(&declaring, pinvoke);
61
62    // Call it first thing in the target method.
63    {
64        let mut method = target.get_mut();
65        let body = method
66            .body
67            .as_mut()
68            .ok_or_else(|| Error::Other(format!("{type_name}::{method_name} has no body")))?;
69        body.insert(0, [Instruction::call(pinvoke)]);
70    }
71
72    module
73        .write()
74        .map_err(|e| Error::Other(format!("writing assembly: {e}")))
75}
76
77#[cfg(all(unix, target_arch = "x86_64"))]
78pub use intercept::{arm as arm_interception, intercept_assembly};
79
80/// Hooks the file loader so that when the runtime opens a target assembly, it
81/// gets a rewritten copy instead. The only platform-specific part of the
82/// assembly-rewrite path.
83#[cfg(all(unix, target_arch = "x86_64"))]
84mod intercept {
85    use std::{
86        cell::Cell,
87        ffi::{c_char, c_int, c_void, CStr, CString},
88        sync::{
89            atomic::{AtomicBool, Ordering},
90            Mutex,
91        },
92    };
93
94    const RTLD_DEFAULT: *mut c_void = std::ptr::null_mut();
95
96    unsafe extern "C" {
97        fn dlsym(handle: *mut c_void, symbol: *const c_char) -> *mut c_void;
98        fn memfd_create(name: *const c_char, flags: c_int) -> c_int;
99    }
100
101    use crate::Result;
102
103    type PatchFn = Box<dyn Fn(&[u8]) -> Result<Vec<u8>> + Send + Sync>;
104
105    struct Target {
106        /// The file name (not path) to match, e.g. `sts2.dll`.
107        basename: String,
108        patch: PatchFn,
109        /// A `/proc/self/fd/{fd}` path to the rewritten copy, built on first open.
110        patched: Mutex<Option<CString>>,
111    }
112
113    static TARGETS: Mutex<Vec<Target>> = Mutex::new(Vec::new());
114    static HOOKED: AtomicBool = AtomicBool::new(false);
115
116    thread_local! {
117        // Set while we read/write the rewritten copy, so our own file I/O isn't
118        // itself intercepted.
119        static BUILDING: Cell<bool> = const { Cell::new(false) };
120    }
121
122    /// Serves a rewritten copy of `basename` (matched by file name) whenever the
123    /// runtime opens it. `patch` receives the original bytes and returns the
124    /// replacement (see [`patch_call`](super::patch_call)). Call it from a mod's
125    /// entry point, before the runtime loads the assembly.
126    ///
127    /// The file-open hooks are NOT installed immediately — they are armed by
128    /// [`arm`] (called automatically from `coreclr_init_detour` after
129    /// `coreclr_initialize` returns). This avoids the open/openat hooks
130    /// interfering with `dlopen` during early game startup.
131    pub fn intercept_assembly(
132        basename: &str,
133        patch: impl Fn(&[u8]) -> Result<Vec<u8>> + Send + Sync + 'static,
134    ) {
135        TARGETS.lock().unwrap_or_else(|e| e.into_inner()).push(Target {
136            basename: basename.to_string(),
137            patch: Box::new(patch),
138            patched: Mutex::new(None),
139        });
140    }
141
142    /// Installs the open/openat hooks so registered targets are intercepted.
143    /// Called automatically after `coreclr_initialize` returns — the CLR is
144    /// loaded but managed assemblies haven't been opened yet.
145    pub fn arm() {
146        if TARGETS.lock().unwrap_or_else(|e| e.into_inner()).is_empty() {
147            return;
148        }
149        install();
150    }
151
152    fn install() {
153        if HOOKED.swap(true, Ordering::SeqCst) {
154            return;
155        }
156        // Hook libc's file-open entry points. On many systems open==open64 and
157        // openat==openat64 (64-bit offsets are the default), so deduplicate by
158        // resolved address to avoid double-patching the same function.
159        let mut hooked_addrs = Vec::new();
160        hook_dedup(c"open", open_detour as *mut u8, &mut hooked_addrs);
161        hook_dedup(c"open64", open_detour as *mut u8, &mut hooked_addrs);
162        hook_dedup(c"openat", openat_detour as *mut u8, &mut hooked_addrs);
163        hook_dedup(c"openat64", openat_detour as *mut u8, &mut hooked_addrs);
164    }
165
166    fn hook_dedup(name: &CStr, detour: *mut u8, seen: &mut Vec<usize>) {
167        let addr = unsafe { dlsym(RTLD_DEFAULT, name.as_ptr()) } as usize;
168        if addr == 0 {
169            tracing::debug!("not hooking {name:?}: symbol not found");
170            return;
171        }
172        if seen.contains(&addr) {
173            tracing::debug!("{name:?} shares address with an already-hooked function, skipping");
174            return;
175        }
176        seen.push(addr);
177        match unsafe { hooking::Hook::by_name(None, name, detour) } {
178            Ok(mut hook) => {
179                if let Err(e) = unsafe { hook.apply_hook() } {
180                    tracing::warn!("applying the {name:?} hook failed: {e:?}");
181                }
182                std::mem::forget(hook);
183            }
184            Err(e) => tracing::debug!("not hooking {name:?}: {e:?}"),
185        }
186    }
187
188    /// If `path` names a target assembly, the path of its rewritten copy.
189    fn redirect(path: *const c_char) -> Option<CString> {
190        if path.is_null() || BUILDING.with(Cell::get) {
191            return None;
192        }
193        let path = unsafe { CStr::from_ptr(path) }.to_string_lossy().into_owned();
194        let name = path.rsplit('/').next().unwrap_or(&path);
195        // Lock scope: find target and get/build cached result, then drop lock
196        // before any I/O (diag opens files → open_detour → redirect → deadlock
197        // if the lock is still held).
198        let result = {
199            let targets = TARGETS.lock().unwrap_or_else(|e| e.into_inner());
200            let target = targets.iter().find(|t| t.basename == name)?;
201            let mut cache = target.patched.lock().unwrap_or_else(|e| e.into_inner());
202            if cache.is_none() {
203                *cache = build(&path, &target.patch);
204            }
205            cache.clone()
206        };
207        result
208    }
209
210    /// Reads the original assembly, rewrites it, and serves the copy from an
211    /// anonymous in-memory file (`memfd_create`), returning a
212    /// `/proc/self/fd/{fd}` path that the CLR can open.
213    fn build(path: &str, patch: &PatchFn) -> Option<CString> {
214        BUILDING.with(|b| b.set(true));
215        let result = (|| {
216            let original = std::fs::read(path).ok()?;
217            BUILDING.with(|b| b.set(false));
218            let patched = match patch(&original) {
219                Ok(bytes) => bytes,
220                Err(e) => {
221                    tracing::error!("rewriting {path} failed: {e}");
222                    return None;
223                }
224            };
225            let fd = unsafe { memfd_create(c"hao-rewrite".as_ptr(), 0) };
226            if fd < 0 {
227                tracing::error!("memfd_create failed for {path}");
228                return None;
229            }
230            let written = unsafe {
231                libc_write(fd, patched.as_ptr() as *const c_void, patched.len())
232            };
233            if written < 0 || written as usize != patched.len() {
234                unsafe { libc_close(fd) };
235                tracing::error!("write to memfd failed for {path}");
236                return None;
237            }
238            tracing::info!("serving a rewritten {path} from memfd (fd {fd})");
239            CString::new(format!("/proc/self/fd/{fd}")).ok()
240        })();
241        BUILDING.with(|b| b.set(false));
242        result
243    }
244
245    unsafe fn libc_write(fd: c_int, buf: *const c_void, count: usize) -> isize {
246        unsafe extern "C" {
247            fn write(fd: c_int, buf: *const c_void, count: usize) -> isize;
248        }
249        unsafe { write(fd, buf, count) }
250    }
251
252    unsafe fn libc_close(fd: c_int) -> c_int {
253        unsafe extern "C" {
254            fn close(fd: c_int) -> c_int;
255        }
256        unsafe { close(fd) }
257    }
258
259    extern "C" fn open_detour(path: *const c_char, flags: c_int, mode: c_int) -> c_int {
260        let original = hooking::original_function_ptr().expect("original! inside the open hook");
261        let original: unsafe extern "C" fn(*const c_char, c_int, c_int) -> c_int =
262            unsafe { std::mem::transmute(original.as_ptr()) };
263        match redirect(path) {
264            Some(temp) => unsafe { original(temp.as_ptr(), flags, mode) },
265            None => unsafe { original(path, flags, mode) },
266        }
267    }
268
269    extern "C" fn openat_detour(
270        dirfd: c_int,
271        path: *const c_char,
272        flags: c_int,
273        mode: c_int,
274    ) -> c_int {
275        let original = hooking::original_function_ptr().expect("original! inside the openat hook");
276        let original: unsafe extern "C" fn(c_int, *const c_char, c_int, c_int) -> c_int =
277            unsafe { std::mem::transmute(original.as_ptr()) };
278        match redirect(path) {
279            Some(temp) => unsafe { original(dirfd, temp.as_ptr(), flags, mode) },
280            None => unsafe { original(dirfd, path, flags, mode) },
281        }
282    }
283}
284
285#[cfg(test)]
286mod tests {
287    use super::*;
288    use hao::dotnet::{
289        entries::Version,
290        il::{MethodBody, OpCode},
291        md::streams::tables_stream::TypeAttributes,
292        module::{ModuleKind, TargetRuntime},
293    };
294
295    /// A tiny assembly with `Game.Loop::Tick()` whose body is just `ret`.
296    fn sample() -> Vec<u8> {
297        let mut module = Module::new("Patchee", ModuleKind::Dll, TargetRuntime::NetCore(9));
298        module.add_assembly_ref(
299            "System.Runtime",
300            Version {
301                major: 9,
302                ..Default::default()
303            },
304            &TargetRuntime::NetCore(9).framework_token(),
305        );
306        let object = module.corlib_type("System.Object").unwrap();
307        let ty = module.add_type(TypeDef::new(
308            TypeAttributes::Public | TypeAttributes::BeforeFieldInit,
309            "Game",
310            "Loop",
311            Some(object),
312        ));
313        let tick = TypeDef::add_method(
314            &ty,
315            Method::public_static("Tick", MethodSig::new_static(TypeSig::VOID, vec![])),
316        );
317        tick.get_mut().body = Some(MethodBody {
318            instructions: vec![Instruction::ret()],
319            ..Default::default()
320        });
321        module.write().unwrap()
322    }
323
324    #[test]
325    fn splices_a_pinvoke_call() {
326        let patched = patch_call(&sample(), "Game.Loop", "Tick", "libhook.so", "hao_tick").unwrap();
327        let reloaded = Module::from_bytes(&patched).unwrap();
328
329        // The P/Invoke method was added, forwarded to our library.
330        let pinvoke = reloaded
331            .find_method("Game.Loop", "hao_tick")
332            .expect("pinvoke method");
333        let pinvoke = pinvoke.get();
334        let impl_map = pinvoke.impl_map.as_ref().expect("impl map");
335        assert_eq!(impl_map.import_name, "hao_tick");
336        assert_eq!(impl_map.scope.get().name, "libhook.so");
337
338        // Tick now calls it before anything else.
339        let tick = reloaded.find_method("Game.Loop", "Tick").unwrap();
340        let tick = tick.get();
341        let body = tick.body.as_ref().unwrap();
342        assert_eq!(body.instructions[0].opcode, OpCode::Call);
343        assert_eq!(body.instructions.last().unwrap().opcode, OpCode::Ret);
344    }
345
346    #[test]
347    fn roundtrip_size() {
348        let path = "/games/SteamLibrary/steamapps/common/Slay the Spire 2/data_sts2_linuxbsd_x86_64/GodotSharp.dll";
349        let Ok(original) = std::fs::read(path) else {
350            eprintln!("skipping: {path} not found");
351            return;
352        };
353        let module = Module::from_bytes(&original).unwrap();
354        let roundtripped = module.write().unwrap();
355        eprintln!(
356            "original: {} bytes, roundtripped: {} bytes, ratio: {:.2}x",
357            original.len(),
358            roundtripped.len(),
359            roundtripped.len() as f64 / original.len() as f64
360        );
361        assert!(
362            roundtripped.len() < original.len() * 3 / 2,
363            "roundtripped size ({}) is more than 1.5x the original ({})",
364            roundtripped.len(),
365            original.len()
366        );
367    }
368
369    #[test]
370    fn patches_real_godotsharp() {
371        let path = "/games/SteamLibrary/steamapps/common/Slay the Spire 2/data_sts2_linuxbsd_x86_64/GodotSharp.dll";
372        let Ok(original) = std::fs::read(path) else {
373            eprintln!("skipping: {path} not found");
374            return;
375        };
376        let patched = patch_call(
377            &original,
378            "Godot.SceneTree",
379            "InvokeGodotClassMethod",
380            "/home/samm/src/projects/xur/target/release/libxur_stub.so",
381            "hao_godot_tick",
382        )
383        .expect("patch_call failed");
384
385        let reloaded = Module::from_bytes(&patched).expect("reload failed");
386        let pinvoke = reloaded
387            .find_method("Godot.SceneTree", "hao_godot_tick")
388            .expect("hao_godot_tick not found");
389        let p = pinvoke.get();
390        eprintln!("flags: {:?}", p.flags);
391        let impl_map = p.impl_map.as_ref().expect("NO IMPL_MAP on hao_godot_tick");
392        eprintln!(
393            "impl_map: import={} scope={}",
394            impl_map.import_name,
395            impl_map.scope.get().name
396        );
397        assert_eq!(impl_map.import_name, "hao_godot_tick");
398        assert!(
399            impl_map.scope.get().name.contains("libxur_stub"),
400            "scope should reference libxur_stub.so, got: {}",
401            impl_map.scope.get().name
402        );
403
404        eprintln!("module_refs: {}", reloaded.module_refs.len());
405        for mr in &reloaded.module_refs {
406            eprintln!("  {}", mr.get().name);
407        }
408    }
409}