1use 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
22pub 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 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 {
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#[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 basename: String,
108 patch: PatchFn,
109 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 static BUILDING: Cell<bool> = const { Cell::new(false) };
120 }
121
122 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 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 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 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 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 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 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 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 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}