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},
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 = declaring.add_method(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
136            .lock()
137            .unwrap_or_else(|e| e.into_inner())
138            .push(Target {
139                basename: basename.to_string(),
140                patch: Box::new(patch),
141                patched: Mutex::new(None),
142            });
143    }
144
145    /// Installs the open/openat hooks so registered targets are intercepted.
146    /// Called automatically after `coreclr_initialize` returns — the CLR is
147    /// loaded but managed assemblies haven't been opened yet.
148    pub fn arm() {
149        if TARGETS.lock().unwrap_or_else(|e| e.into_inner()).is_empty() {
150            return;
151        }
152        install();
153    }
154
155    fn install() {
156        if HOOKED.swap(true, Ordering::SeqCst) {
157            return;
158        }
159        // Hook libc's file-open entry points. On many systems open==open64 and
160        // openat==openat64 (64-bit offsets are the default), so deduplicate by
161        // resolved address to avoid double-patching the same function.
162        let mut hooked_addrs = Vec::new();
163        hook_dedup(c"open", open_detour as *mut u8, &mut hooked_addrs);
164        hook_dedup(c"open64", open_detour as *mut u8, &mut hooked_addrs);
165        hook_dedup(c"openat", openat_detour as *mut u8, &mut hooked_addrs);
166        hook_dedup(c"openat64", openat_detour as *mut u8, &mut hooked_addrs);
167    }
168
169    fn hook_dedup(name: &CStr, detour: *mut u8, seen: &mut Vec<usize>) {
170        let addr = unsafe { dlsym(RTLD_DEFAULT, name.as_ptr()) } as usize;
171        if addr == 0 {
172            tracing::debug!("not hooking {name:?}: symbol not found");
173            return;
174        }
175        if seen.contains(&addr) {
176            tracing::debug!("{name:?} shares address with an already-hooked function, skipping");
177            return;
178        }
179        seen.push(addr);
180        match unsafe { hooking::Hook::by_name(None, name, detour) } {
181            Ok(mut hook) => {
182                if let Err(e) = unsafe { hook.apply_hook() } {
183                    tracing::warn!("applying the {name:?} hook failed: {e:?}");
184                }
185                std::mem::forget(hook);
186            }
187            Err(e) => tracing::debug!("not hooking {name:?}: {e:?}"),
188        }
189    }
190
191    /// If `path` names a target assembly, the path of its rewritten copy.
192    fn redirect(path: *const c_char) -> Option<CString> {
193        if path.is_null() || BUILDING.with(Cell::get) {
194            return None;
195        }
196        let path = unsafe { CStr::from_ptr(path) }
197            .to_string_lossy()
198            .into_owned();
199        let name = path.rsplit('/').next().unwrap_or(&path);
200        // Lock scope: find target and get/build cached result, then drop lock
201        // before any I/O (a log write opens files → open_detour → redirect →
202        // deadlock if the lock is still held).
203        let result = {
204            let targets = TARGETS.lock().unwrap_or_else(|e| e.into_inner());
205            let target = targets.iter().find(|t| t.basename == name)?;
206            let mut cache = target.patched.lock().unwrap_or_else(|e| e.into_inner());
207            if cache.is_none() {
208                *cache = build(&path, &target.patch);
209            }
210            cache.clone()
211        };
212        result
213    }
214
215    /// Reads the original assembly, rewrites it, and serves the copy from an
216    /// anonymous in-memory file (`memfd_create`), returning a
217    /// `/proc/self/fd/{fd}` path that the CLR can open.
218    fn build(path: &str, patch: &PatchFn) -> Option<CString> {
219        BUILDING.with(|b| b.set(true));
220        let result = (|| {
221            let original = std::fs::read(path).ok()?;
222            BUILDING.with(|b| b.set(false));
223            let patched = match patch(&original) {
224                Ok(bytes) => bytes,
225                Err(e) => {
226                    tracing::error!("rewriting {path} failed: {e}");
227                    return None;
228                }
229            };
230            let fd = unsafe { memfd_create(c"hao-rewrite".as_ptr(), 0) };
231            if fd < 0 {
232                tracing::error!("memfd_create failed for {path}");
233                return None;
234            }
235            let written =
236                unsafe { libc_write(fd, patched.as_ptr() as *const c_void, patched.len()) };
237            if written < 0 || written as usize != patched.len() {
238                unsafe { libc_close(fd) };
239                tracing::error!("write to memfd failed for {path}");
240                return None;
241            }
242            tracing::info!("serving a rewritten {path} from memfd (fd {fd})");
243            CString::new(format!("/proc/self/fd/{fd}")).ok()
244        })();
245        BUILDING.with(|b| b.set(false));
246        result
247    }
248
249    unsafe fn libc_write(fd: c_int, buf: *const c_void, count: usize) -> isize {
250        unsafe extern "C" {
251            fn write(fd: c_int, buf: *const c_void, count: usize) -> isize;
252        }
253        unsafe { write(fd, buf, count) }
254    }
255
256    unsafe fn libc_close(fd: c_int) -> c_int {
257        unsafe extern "C" {
258            fn close(fd: c_int) -> c_int;
259        }
260        unsafe { close(fd) }
261    }
262
263    extern "C" fn open_detour(path: *const c_char, flags: c_int, mode: c_int) -> c_int {
264        let original = hooking::original_function_ptr().expect("original! inside the open hook");
265        let original: unsafe extern "C" fn(*const c_char, c_int, c_int) -> c_int =
266            unsafe { std::mem::transmute(original.as_ptr()) };
267        match redirect(path) {
268            Some(temp) => unsafe { original(temp.as_ptr(), flags, mode) },
269            None => unsafe { original(path, flags, mode) },
270        }
271    }
272
273    extern "C" fn openat_detour(
274        dirfd: c_int,
275        path: *const c_char,
276        flags: c_int,
277        mode: c_int,
278    ) -> c_int {
279        let original = hooking::original_function_ptr().expect("original! inside the openat hook");
280        let original: unsafe extern "C" fn(c_int, *const c_char, c_int, c_int) -> c_int =
281            unsafe { std::mem::transmute(original.as_ptr()) };
282        match redirect(path) {
283            Some(temp) => unsafe { original(dirfd, temp.as_ptr(), flags, mode) },
284            None => unsafe { original(dirfd, path, flags, mode) },
285        }
286    }
287}
288
289#[cfg(test)]
290mod tests {
291    use super::*;
292    use hao::dotnet::{
293        entries::{TypeDef, Version},
294        il::{MethodBody, OpCode},
295        md::streams::tables_stream::TypeAttributes,
296        module::{ModuleKind, TargetRuntime},
297    };
298
299    /// A tiny assembly with `Game.Loop::Tick()` whose body is just `ret`.
300    fn sample() -> Vec<u8> {
301        let mut module = Module::new("Patchee", ModuleKind::Dll, TargetRuntime::NetCore(9));
302        module.add_assembly_ref((
303            "System.Runtime",
304            Version {
305                major: 9,
306                ..Default::default()
307            },
308            &TargetRuntime::NetCore(9).framework_token()[..],
309        ));
310        let object = module.corlib_type("System.Object").unwrap();
311        let ty = module.add_type(TypeDef::new(
312            TypeAttributes::Public | TypeAttributes::BeforeFieldInit,
313            "Game",
314            "Loop",
315            Some(object),
316        ));
317        let tick = ty.add_method(Method::public_static(
318            "Tick",
319            MethodSig::new_static(TypeSig::VOID, vec![]),
320        ));
321        tick.get_mut().body = Some(MethodBody {
322            instructions: vec![Instruction::ret()],
323            ..Default::default()
324        });
325        module.write().unwrap()
326    }
327
328    #[test]
329    fn splices_a_pinvoke_call() {
330        let patched = patch_call(&sample(), "Game.Loop", "Tick", "libhook.so", "hao_tick").unwrap();
331        let reloaded = Module::from_bytes(&patched).unwrap();
332
333        // The P/Invoke method was added, forwarded to our library.
334        let pinvoke = reloaded
335            .find_method("Game.Loop", "hao_tick")
336            .expect("pinvoke method");
337        let pinvoke = pinvoke.get();
338        let impl_map = pinvoke.impl_map.as_ref().expect("impl map");
339        assert_eq!(impl_map.import_name, "hao_tick");
340        assert_eq!(impl_map.scope.get().name, "libhook.so");
341
342        // Tick now calls it before anything else.
343        let tick = reloaded.find_method("Game.Loop", "Tick").unwrap();
344        let tick = tick.get();
345        let body = tick.body.as_ref().unwrap();
346        assert_eq!(body.instructions[0].opcode, OpCode::Call);
347        assert_eq!(body.instructions.last().unwrap().opcode, OpCode::Ret);
348    }
349
350    #[test]
351    fn roundtrip_size() {
352        let path = "/games/SteamLibrary/steamapps/common/Slay the Spire 2/data_sts2_linuxbsd_x86_64/GodotSharp.dll";
353        let Ok(original) = std::fs::read(path) else {
354            eprintln!("skipping: {path} not found");
355            return;
356        };
357        let module = Module::from_bytes(&original).unwrap();
358        let roundtripped = module.write().unwrap();
359        eprintln!(
360            "original: {} bytes, roundtripped: {} bytes, ratio: {:.2}x",
361            original.len(),
362            roundtripped.len(),
363            roundtripped.len() as f64 / original.len() as f64
364        );
365        assert!(
366            roundtripped.len() < original.len() * 3 / 2,
367            "roundtripped size ({}) is more than 1.5x the original ({})",
368            roundtripped.len(),
369            original.len()
370        );
371    }
372
373    #[test]
374    fn patches_real_godotsharp() {
375        let path = "/games/SteamLibrary/steamapps/common/Slay the Spire 2/data_sts2_linuxbsd_x86_64/GodotSharp.dll";
376        let Ok(original) = std::fs::read(path) else {
377            eprintln!("skipping: {path} not found");
378            return;
379        };
380        let patched = patch_call(
381            &original,
382            "Godot.SceneTree",
383            "InvokeGodotClassMethod",
384            "/home/samm/src/projects/xur/target/release/libxur_stub.so",
385            "hao_godot_tick",
386        )
387        .expect("patch_call failed");
388
389        let reloaded = Module::from_bytes(&patched).expect("reload failed");
390        let pinvoke = reloaded
391            .find_method("Godot.SceneTree", "hao_godot_tick")
392            .expect("hao_godot_tick not found");
393        let p = pinvoke.get();
394        eprintln!("flags: {:?}", p.flags);
395        let impl_map = p.impl_map.as_ref().expect("NO IMPL_MAP on hao_godot_tick");
396        eprintln!(
397            "impl_map: import={} scope={}",
398            impl_map.import_name,
399            impl_map.scope.get().name
400        );
401        assert_eq!(impl_map.import_name, "hao_godot_tick");
402        assert!(
403            impl_map.scope.get().name.contains("libxur_stub"),
404            "scope should reference libxur_stub.so, got: {}",
405            impl_map.scope.get().name
406        );
407
408        eprintln!("module_refs: {}", reloaded.module_refs.len());
409        for mr in &reloaded.module_refs {
410            eprintln!("  {}", mr.get().name);
411        }
412    }
413}