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::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, 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 basename: String,
102 patch: PatchFn,
103 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 static BUILDING: Cell<bool> = const { Cell::new(false) };
115 }
116
117 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(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 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 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 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 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 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}