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::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, CStr, CString},
88        os::unix::ffi::OsStrExt,
89        sync::{
90            atomic::{AtomicBool, AtomicUsize, Ordering},
91            Mutex,
92        },
93    };
94
95    use crate::Result;
96
97    type PatchFn = Box<dyn Fn(&[u8]) -> Result<Vec<u8>> + Send + Sync>;
98
99    struct Target {
100        /// The file name (not path) to match, e.g. `sts2.dll`.
101        basename: String,
102        patch: PatchFn,
103        /// The rewritten copy on disk, built on first open.
104        patched: Mutex<Option<CString>>,
105    }
106
107    static TARGETS: Mutex<Vec<Target>> = Mutex::new(Vec::new());
108    static HOOKED: AtomicBool = AtomicBool::new(false);
109    static COUNTER: AtomicUsize = AtomicUsize::new(0);
110
111    thread_local! {
112        // Set while we read/write the rewritten copy, so our own file I/O isn't
113        // itself intercepted.
114        static BUILDING: Cell<bool> = const { Cell::new(false) };
115    }
116
117    /// Serves a rewritten copy of `basename` (matched by file name) whenever the
118    /// runtime opens it. `patch` receives the original bytes and returns the
119    /// replacement (see [`patch_call`](super::patch_call)). Call it from a mod's
120    /// entry point, before the runtime loads the assembly.
121    pub fn intercept_assembly(
122        basename: &str,
123        patch: impl Fn(&[u8]) -> Result<Vec<u8>> + Send + Sync + 'static,
124    ) {
125        TARGETS.lock().unwrap_or_else(|e| e.into_inner()).push(Target {
126            basename: basename.to_string(),
127            patch: Box::new(patch),
128            patched: Mutex::new(None),
129        });
130        install();
131    }
132
133    fn install() {
134        if HOOKED.swap(true, Ordering::SeqCst) {
135            return;
136        }
137        // Hook the common libc entry points for opening a file by path. Which one
138        // the runtime uses varies, so hook them all; a missing symbol is skipped.
139        hook(c"open", open_detour as *mut u8);
140        hook(c"open64", open_detour as *mut u8);
141        hook(c"openat", openat_detour as *mut u8);
142        hook(c"openat64", openat_detour as *mut u8);
143    }
144
145    fn hook(name: &CStr, detour: *mut u8) {
146        match unsafe { hooking::Hook::by_name(None, name, detour) } {
147            Ok(mut hook) => {
148                if let Err(e) = unsafe { hook.apply_hook() } {
149                    tracing::warn!("applying the {name:?} hook failed: {e:?}");
150                }
151                std::mem::forget(hook);
152            }
153            Err(e) => tracing::debug!("not hooking {name:?}: {e:?}"),
154        }
155    }
156
157    /// If `path` names a target assembly, the path of its rewritten copy.
158    fn redirect(path: *const c_char) -> Option<CString> {
159        if path.is_null() || BUILDING.with(Cell::get) {
160            return None;
161        }
162        let path = unsafe { CStr::from_ptr(path) }.to_string_lossy().into_owned();
163        let name = path.rsplit('/').next().unwrap_or(&path);
164        let targets = TARGETS.lock().unwrap_or_else(|e| e.into_inner());
165        let target = targets.iter().find(|t| t.basename == name)?;
166        let mut cache = target.patched.lock().unwrap_or_else(|e| e.into_inner());
167        if cache.is_none() {
168            *cache = build(&path, &target.patch);
169        }
170        cache.clone()
171    }
172
173    /// Reads the original assembly, rewrites it, and writes the copy to a temp
174    /// file, returning its path.
175    fn build(path: &str, patch: &PatchFn) -> Option<CString> {
176        BUILDING.with(|b| b.set(true));
177        let result = (|| {
178            let original = std::fs::read(path).ok()?;
179            let patched = match patch(&original) {
180                Ok(bytes) => bytes,
181                Err(e) => {
182                    tracing::error!("rewriting {path} failed: {e}");
183                    return None;
184                }
185            };
186            let n = COUNTER.fetch_add(1, Ordering::Relaxed);
187            let out = std::env::temp_dir().join(format!("hao-rewrite-{}-{n}.bin", std::process::id()));
188            std::fs::write(&out, &patched).ok()?;
189            tracing::info!("serving a rewritten {path} from {}", out.display());
190            CString::new(out.as_os_str().as_bytes()).ok()
191        })();
192        BUILDING.with(|b| b.set(false));
193        result
194    }
195
196    extern "C" fn open_detour(path: *const c_char, flags: c_int, mode: c_int) -> c_int {
197        let original = hooking::original_function_ptr().expect("original! inside the open hook");
198        let original: unsafe extern "C" fn(*const c_char, c_int, c_int) -> c_int =
199            unsafe { std::mem::transmute(original.as_ptr()) };
200        match redirect(path) {
201            Some(temp) => unsafe { original(temp.as_ptr(), flags, mode) },
202            None => unsafe { original(path, flags, mode) },
203        }
204    }
205
206    extern "C" fn openat_detour(
207        dirfd: c_int,
208        path: *const c_char,
209        flags: c_int,
210        mode: c_int,
211    ) -> c_int {
212        let original = hooking::original_function_ptr().expect("original! inside the openat hook");
213        let original: unsafe extern "C" fn(c_int, *const c_char, c_int, c_int) -> c_int =
214            unsafe { std::mem::transmute(original.as_ptr()) };
215        match redirect(path) {
216            Some(temp) => unsafe { original(dirfd, temp.as_ptr(), flags, mode) },
217            None => unsafe { original(dirfd, path, flags, mode) },
218        }
219    }
220}
221
222#[cfg(test)]
223mod tests {
224    use super::*;
225    use hao::dotnet::{
226        entries::Version,
227        il::{MethodBody, OpCode},
228        md::streams::tables_stream::TypeAttributes,
229        module::{ModuleKind, TargetRuntime},
230    };
231
232    /// A tiny assembly with `Game.Loop::Tick()` whose body is just `ret`.
233    fn sample() -> Vec<u8> {
234        let mut module = Module::new("Patchee", ModuleKind::Dll, TargetRuntime::NetCore(9));
235        module.add_assembly_ref(
236            "System.Runtime",
237            Version {
238                major: 9,
239                ..Default::default()
240            },
241            &TargetRuntime::NetCore(9).framework_token(),
242        );
243        let object = module.corlib_type("System.Object").unwrap();
244        let ty = module.add_type(TypeDef::new(
245            TypeAttributes::Public | TypeAttributes::BeforeFieldInit,
246            "Game",
247            "Loop",
248            Some(object),
249        ));
250        let tick = TypeDef::add_method(
251            &ty,
252            Method::public_static("Tick", MethodSig::new_static(TypeSig::VOID, vec![])),
253        );
254        tick.get_mut().body = Some(MethodBody {
255            instructions: vec![Instruction::ret()],
256            ..Default::default()
257        });
258        module.write().unwrap()
259    }
260
261    #[test]
262    fn splices_a_pinvoke_call() {
263        let patched = patch_call(&sample(), "Game.Loop", "Tick", "libhook.so", "hao_tick").unwrap();
264        let reloaded = Module::from_bytes(&patched).unwrap();
265
266        // The P/Invoke method was added, forwarded to our library.
267        let pinvoke = reloaded
268            .find_method("Game.Loop", "hao_tick")
269            .expect("pinvoke method");
270        let pinvoke = pinvoke.get();
271        let impl_map = pinvoke.impl_map.as_ref().expect("impl map");
272        assert_eq!(impl_map.import_name, "hao_tick");
273        assert_eq!(impl_map.scope.get().name, "libhook.so");
274
275        // Tick now calls it before anything else.
276        let tick = reloaded.find_method("Game.Loop", "Tick").unwrap();
277        let tick = tick.get();
278        let body = tick.body.as_ref().unwrap();
279        assert_eq!(body.instructions[0].opcode, OpCode::Call);
280        assert_eq!(body.instructions.last().unwrap().opcode, OpCode::Ret);
281    }
282}