1use 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
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 = TypeDef::add_method(&declaring, 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.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 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 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 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 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 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 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 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 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}