1use std::{
18 ffi::{c_char, c_int, c_void},
19 sync::{
20 atomic::{AtomicBool, AtomicUsize, Ordering},
21 Mutex, OnceLock,
22 },
23};
24
25use crate::{Result, Runtime};
26
27type CoreclrInitialize = unsafe extern "C" fn(
29 *const c_char,
30 *const c_char,
31 c_int,
32 *const *const c_char,
33 *const *const c_char,
34 *mut *mut c_void,
35 *mut u32,
36) -> c_int;
37
38type CoreclrCreateDelegate = unsafe extern "C" fn(
40 *mut c_void,
41 u32,
42 *const c_char,
43 *const c_char,
44 *const c_char,
45 *mut *mut c_void,
46) -> c_int;
47
48const CORECLR: &str = if cfg!(windows) {
50 "coreclr.dll"
51} else {
52 "libcoreclr.so"
53};
54
55#[derive(Clone, Copy)]
57pub struct ClrHost {
58 pub handle: *mut c_void,
59 pub domain: u32,
60 create_delegate: CoreclrCreateDelegate,
61}
62
63unsafe impl Send for ClrHost {}
65unsafe impl Sync for ClrHost {}
66
67impl ClrHost {
68 pub fn create_delegate(
72 &self,
73 assembly: &str,
74 type_name: &str,
75 method: &str,
76 ) -> std::result::Result<*mut c_void, String> {
77 use std::ffi::CString;
78 let assembly = CString::new(assembly).map_err(|_| "assembly has a nul")?;
79 let type_name = CString::new(type_name).map_err(|_| "type has a nul")?;
80 let method = CString::new(method).map_err(|_| "method has a nul")?;
81 let mut delegate = std::ptr::null_mut();
82 let code = unsafe {
83 (self.create_delegate)(
84 self.handle,
85 self.domain,
86 assembly.as_ptr(),
87 type_name.as_ptr(),
88 method.as_ptr(),
89 &mut delegate,
90 )
91 };
92 if code != 0 {
93 return Err(format!("coreclr_create_delegate failed: 0x{code:x}"));
94 }
95 Ok(delegate)
96 }
97
98 pub fn attach(&self, major: u16) -> Result<Runtime> {
102 Runtime::coreclr_attach(
103 self.handle,
104 self.domain,
105 self.create_delegate as *const c_void,
106 major,
107 )
108 }
109}
110
111type Callback = Box<dyn FnOnce(ClrHost) + Send>;
112
113pub fn diag(msg: &str) {
117 use std::io::Write;
118 if let Ok(mut f) = std::fs::OpenOptions::new()
119 .create(true)
120 .append(true)
121 .open("/tmp/hao-diag.log")
122 {
123 let _ = writeln!(f, "[hao-diag] {msg}");
124 }
125}
126
127static CALLBACKS: Mutex<Vec<Callback>> = Mutex::new(Vec::new());
128static HOST: OnceLock<ClrHost> = OnceLock::new();
129static CREATE_DELEGATE: AtomicUsize = AtomicUsize::new(0);
130static LOADER_HOOKED: AtomicBool = AtomicBool::new(false);
131static INIT_HOOKED: AtomicBool = AtomicBool::new(false);
132
133pub fn ensure_loader_hook() {
140 install_loader_hook();
141}
142
143pub fn on_clr_init(callback: impl FnOnce(ClrHost) + Send + 'static) {
153 if let Some(host) = HOST.get() {
154 diag("on_clr_init: HOST already set, fast path");
155 let host = *host;
156 std::thread::spawn(move || callback(host));
157 return;
158 }
159 diag("on_clr_init: HOST not set, registering callback + loader hook");
160 CALLBACKS
161 .lock()
162 .unwrap_or_else(|e| e.into_inner())
163 .push(Box::new(callback));
164 install_loader_hook();
165}
166
167fn run_callbacks(host: ClrHost) {
169 std::thread::spawn(move || {
170 let callbacks = std::mem::take(&mut *CALLBACKS.lock().unwrap_or_else(|e| e.into_inner()));
171 for callback in callbacks {
172 callback(host);
173 }
174 });
175}
176
177fn hook_coreclr_init() {
178 if INIT_HOOKED.swap(true, Ordering::SeqCst) {
179 return;
180 }
181 let lib = match unsafe { libloading::Library::new(CORECLR) } {
182 Ok(lib) => lib,
183 Err(e) => {
184 tracing::error!("could not open {CORECLR}: {e}");
185 return;
186 }
187 };
188 let init = unsafe { lib.get::<CoreclrInitialize>(b"coreclr_initialize\0") };
189 let create = unsafe { lib.get::<CoreclrCreateDelegate>(b"coreclr_create_delegate\0") };
190 let (Ok(init), Ok(create)) = (init, create) else {
191 tracing::error!("coreclr_initialize or coreclr_create_delegate not found in {CORECLR}");
192 return;
193 };
194 let init_addr = (*init) as usize as *mut u8;
195 CREATE_DELEGATE.store((*create) as usize, Ordering::SeqCst);
196 std::mem::forget(lib); tracing::info!("hooking coreclr_initialize");
199 match unsafe { hooking::Hook::create(init_addr, coreclr_init_detour as *mut u8) } {
200 Ok(mut hook) => {
201 if let Err(e) = unsafe { hook.apply_hook() } {
202 tracing::error!("applying the coreclr_initialize hook failed: {e:?}");
203 }
204 std::mem::forget(hook);
205 }
206 Err(e) => tracing::error!("hooking coreclr_initialize failed: {e:?}"),
207 }
208}
209
210extern "C" fn coreclr_init_detour(
211 exe: *const c_char,
212 name: *const c_char,
213 count: c_int,
214 keys: *const *const c_char,
215 values: *const *const c_char,
216 host_handle: *mut *mut c_void,
217 domain_id: *mut u32,
218) -> c_int {
219 let original =
220 hooking::original_function_ptr().expect("original! inside the coreclr_initialize hook");
221 let original: CoreclrInitialize = unsafe { std::mem::transmute(original.as_ptr()) };
222
223 diag("coreclr_init_detour entered, arming interception");
229 #[cfg(all(unix, target_arch = "x86_64"))]
230 crate::rewrite::arm_interception();
231 diag("arm_interception done, calling original");
232
233 let result = unsafe { original(exe, name, count, keys, values, host_handle, domain_id) };
234 diag(&format!("coreclr_initialize returned 0x{result:x}"));
235 tracing::info!("coreclr_initialize returned 0x{result:x}");
236
237 if result == 0 && !host_handle.is_null() && !domain_id.is_null() {
238 let handle = unsafe { *host_handle };
239 let domain = unsafe { *domain_id };
240 let create = CREATE_DELEGATE.load(Ordering::SeqCst);
241 if create != 0 {
242 let host = ClrHost {
243 handle,
244 domain,
245 create_delegate: unsafe {
246 std::mem::transmute::<usize, CoreclrCreateDelegate>(create)
247 },
248 };
249 tracing::info!("captured CLR host: handle={handle:?}, domain={domain}");
250 let _ = HOST.set(host);
251 run_callbacks(host);
252 }
253 }
254 result
255}
256
257#[cfg(unix)]
260fn install_loader_hook() {
261 if LOADER_HOOKED.swap(true, Ordering::SeqCst) {
262 return;
263 }
264 unsafe extern "C" {
269 fn dlsym(handle: *mut c_void, symbol: *const c_char) -> *mut c_void;
270 }
271 const RTLD_DEFAULT: *mut c_void = std::ptr::null_mut();
272 let probe =
273 unsafe { dlsym(RTLD_DEFAULT, c"coreclr_initialize".as_ptr()) };
274 if !probe.is_null() {
275 diag("coreclr already loaded, hooking directly");
276 tracing::info!("{CORECLR} is already loaded, hooking coreclr_initialize directly");
277 hook_coreclr_init();
278 return;
279 }
280
281 diag("hooking dlopen to wait for coreclr");
282 tracing::info!("hooking dlopen to wait for {CORECLR}");
283 match unsafe { hooking::Hook::by_name(None, c"dlopen", dlopen_detour as *mut u8) } {
284 Ok(mut hook) => {
285 if let Err(e) = unsafe { hook.apply_hook() } {
286 tracing::error!("applying the dlopen hook failed: {e:?}");
287 }
288 std::mem::forget(hook);
289 }
290 Err(e) => tracing::error!("hooking dlopen failed: {e:?}"),
291 }
292}
293
294#[cfg(unix)]
295extern "C" fn dlopen_detour(filename: *const c_char, flags: c_int) -> *mut c_void {
296 let original = hooking::original_function_ptr().expect("original! inside the dlopen hook");
298 let original: unsafe extern "C" fn(*const c_char, c_int) -> *mut c_void =
299 unsafe { std::mem::transmute(original.as_ptr()) };
300 let handle = unsafe { original(filename, flags) };
301 if !handle.is_null() && !INIT_HOOKED.load(Ordering::SeqCst) {
302 if !filename.is_null() {
303 let name = unsafe { std::ffi::CStr::from_ptr(filename) }.to_string_lossy();
304 if name.contains(CORECLR) {
305 tracing::info!("{CORECLR} loaded: {name}");
306 hook_coreclr_init();
307 }
308 }
309 if !INIT_HOOKED.load(Ordering::SeqCst) {
313 unsafe extern "C" {
314 fn dlsym(handle: *mut c_void, symbol: *const c_char) -> *mut c_void;
315 }
316 let sym = unsafe {
317 dlsym(handle, c"coreclr_initialize".as_ptr())
318 };
319 if !sym.is_null() {
320 hook_coreclr_init();
321 }
322 }
323 }
324 handle
325}
326
327#[cfg(windows)]
328fn install_loader_hook() {
329 if LOADER_HOOKED.swap(true, Ordering::SeqCst) {
330 return;
331 }
332 tracing::info!("hooking LoadLibraryExW to wait for {CORECLR}");
333 match unsafe {
334 hooking::Hook::by_name(Some(c"kernelbase.dll"), c"LoadLibraryExW", loadlibrary_detour as *mut u8)
335 } {
336 Ok(mut hook) => {
337 if let Err(e) = unsafe { hook.apply_hook() } {
338 tracing::error!("applying the LoadLibraryExW hook failed: {e:?}");
339 }
340 std::mem::forget(hook);
341 }
342 Err(e) => tracing::error!("hooking LoadLibraryExW failed: {e:?}"),
343 }
344}
345
346#[cfg(windows)]
347extern "C" fn loadlibrary_detour(
348 filename: *const u16,
349 file: *mut c_void,
350 flags: u32,
351) -> *mut c_void {
352 let original = hooking::original_function_ptr().expect("original! inside the LoadLibraryExW hook");
353 let original: unsafe extern "C" fn(*const u16, *mut c_void, u32) -> *mut c_void =
354 unsafe { std::mem::transmute(original.as_ptr()) };
355 let handle = unsafe { original(filename, file, flags) };
356 if !handle.is_null() && !filename.is_null() && !INIT_HOOKED.load(Ordering::SeqCst) {
357 let mut len = 0;
358 while unsafe { *filename.add(len) } != 0 {
359 len += 1;
360 }
361 let name = String::from_utf16_lossy(unsafe { std::slice::from_raw_parts(filename, len) });
362 if name.to_ascii_lowercase().contains(CORECLR) {
363 tracing::info!("{CORECLR} loaded: {name}");
364 hook_coreclr_init();
365 }
366 }
367 handle
368}