1use std::{
29 ffi::{c_char, c_int, c_void},
30 sync::{
31 atomic::{AtomicBool, AtomicUsize, Ordering},
32 Mutex, OnceLock,
33 },
34};
35
36use crate::{Result, Runtime};
37
38type CoreclrInitialize = unsafe extern "C" fn(
40 *const c_char,
41 *const c_char,
42 c_int,
43 *const *const c_char,
44 *const *const c_char,
45 *mut *mut c_void,
46 *mut u32,
47) -> c_int;
48
49type CoreclrCreateDelegate = unsafe extern "C" fn(
51 *mut c_void,
52 u32,
53 *const c_char,
54 *const c_char,
55 *const c_char,
56 *mut *mut c_void,
57) -> c_int;
58
59const CORECLR: &str = if cfg!(windows) {
61 "coreclr.dll"
62} else {
63 "libcoreclr.so"
64};
65
66#[derive(Clone, Copy)]
68pub struct ClrHost {
69 pub handle: *mut c_void,
72 pub domain: u32,
74 create_delegate: CoreclrCreateDelegate,
75}
76
77unsafe impl Send for ClrHost {}
79unsafe impl Sync for ClrHost {}
80
81impl ClrHost {
82 pub fn create_delegate(
86 &self,
87 assembly: &str,
88 type_name: &str,
89 method: &str,
90 ) -> std::result::Result<*mut c_void, String> {
91 use std::ffi::CString;
92 let assembly = CString::new(assembly).map_err(|_| "assembly has a nul")?;
93 let type_name = CString::new(type_name).map_err(|_| "type has a nul")?;
94 let method = CString::new(method).map_err(|_| "method has a nul")?;
95 let mut delegate = std::ptr::null_mut();
96 let code = unsafe {
97 (self.create_delegate)(
98 self.handle,
99 self.domain,
100 assembly.as_ptr(),
101 type_name.as_ptr(),
102 method.as_ptr(),
103 &mut delegate,
104 )
105 };
106 if code != 0 {
107 return Err(format!("coreclr_create_delegate failed: 0x{code:x}"));
108 }
109 Ok(delegate)
110 }
111
112 pub fn attach(&self, major: u16) -> Result<Runtime> {
116 Runtime::coreclr_attach(
117 self.handle,
118 self.domain,
119 self.create_delegate as *const c_void,
120 major,
121 )
122 }
123}
124
125type Callback = Box<dyn FnOnce(ClrHost) + Send>;
126
127pub fn diag(msg: &str) {
130 tracing::debug!("{msg}");
131}
132
133static CALLBACKS: Mutex<Vec<Callback>> = Mutex::new(Vec::new());
134static CORECLR_LIBRARY: OnceLock<libloading::Library> = OnceLock::new();
138static HOST: OnceLock<ClrHost> = OnceLock::new();
139static CREATE_DELEGATE: AtomicUsize = AtomicUsize::new(0);
140static LOADER_HOOKED: AtomicBool = AtomicBool::new(false);
141static INIT_HOOKED: AtomicBool = AtomicBool::new(false);
142
143pub fn ensure_loader_hook() {
150 install_loader_hook();
151}
152
153pub fn on_clr_init(callback: impl FnOnce(ClrHost) + Send + 'static) {
163 if let Some(host) = HOST.get() {
164 tracing::debug!("on_clr_init: host already captured");
165 let host = *host;
166 std::thread::spawn(move || callback(host));
167 return;
168 }
169 #[cfg(target_arch = "x86_64")]
174 if let Some(host) = try_capture_running_host() {
175 tracing::debug!("on_clr_init: captured the running CLR via GetCLRRuntimeHost");
176 let host = *HOST.get_or_init(|| host);
177 std::thread::spawn(move || callback(host));
178 return;
179 }
180
181 tracing::debug!("on_clr_init: CLR not started, waiting for coreclr_initialize");
182 CALLBACKS
183 .lock()
184 .unwrap_or_else(|e| e.into_inner())
185 .push(Box::new(callback));
186 install_loader_hook();
187}
188
189#[cfg(target_arch = "x86_64")]
198fn try_capture_running_host() -> Option<ClrHost> {
199 const IID_IUNKNOWN: [u8; 16] = [0, 0, 0, 0, 0, 0, 0, 0, 0xc0, 0, 0, 0, 0, 0, 0, 0x46];
201 type GetClrRuntimeHost = unsafe extern "C" fn(*const u8, *mut *mut c_void) -> c_int;
202
203 let lib = loaded_coreclr()?;
204 let get_host = unsafe { lib.get::<GetClrRuntimeHost>(b"GetCLRRuntimeHost\0") }.ok()?;
205 let create = unsafe { lib.get::<CoreclrCreateDelegate>(b"coreclr_create_delegate\0") }.ok()?;
206 let create_delegate: CoreclrCreateDelegate = *create;
207
208 let mut host: *mut c_void = std::ptr::null_mut();
209 let code = unsafe { (*get_host)(IID_IUNKNOWN.as_ptr(), &mut host) };
210
211 if code != 0 || host.is_null() {
212 return None; }
214 Some(ClrHost {
215 handle: host,
216 domain: 1,
217 create_delegate,
218 })
219}
220
221fn loaded_coreclr() -> Option<&'static libloading::Library> {
225 if let Some(lib) = CORECLR_LIBRARY.get() {
226 return Some(lib);
227 }
228 let lib = match open_already_loaded(CORECLR) {
232 Ok(lib) => lib,
233 Err(e) => {
234 tracing::debug!("{CORECLR} is not loaded yet: {e}");
235 return None;
236 }
237 };
238 let _ = CORECLR_LIBRARY.set(lib);
239 CORECLR_LIBRARY.get()
240}
241
242#[cfg(unix)]
245fn open_already_loaded(name: &str) -> std::result::Result<libloading::Library, libloading::Error> {
246 use libloading::os::unix::{Library, RTLD_NOW};
247 #[cfg(any(target_os = "linux", target_os = "android"))]
249 const RTLD_NOLOAD: c_int = 0x4;
250 #[cfg(any(target_os = "macos", target_os = "ios"))]
251 const RTLD_NOLOAD: c_int = 0x10;
252 #[cfg(target_os = "freebsd")]
253 const RTLD_NOLOAD: c_int = 0x2000;
254 unsafe { Library::open(Some(name), RTLD_NOLOAD | RTLD_NOW) }.map(Into::into)
255}
256
257#[cfg(windows)]
260fn open_already_loaded(name: &str) -> std::result::Result<libloading::Library, libloading::Error> {
261 libloading::os::windows::Library::open_already_loaded(name).map(Into::into)
262}
263
264fn run_callbacks(host: ClrHost) {
266 std::thread::spawn(move || {
267 let callbacks = std::mem::take(&mut *CALLBACKS.lock().unwrap_or_else(|e| e.into_inner()));
268 for callback in callbacks {
269 callback(host);
270 }
271 });
272}
273
274fn hook_coreclr_init() {
275 if INIT_HOOKED.swap(true, Ordering::SeqCst) {
276 return;
277 }
278 let Some(lib) = loaded_coreclr() else {
279 tracing::error!("{CORECLR} is not loaded, not hooking coreclr_initialize");
280 INIT_HOOKED.store(false, Ordering::SeqCst);
281 return;
282 };
283 let init = unsafe { lib.get::<CoreclrInitialize>(b"coreclr_initialize\0") };
284 let create = unsafe { lib.get::<CoreclrCreateDelegate>(b"coreclr_create_delegate\0") };
285 let (Ok(init), Ok(create)) = (init, create) else {
286 tracing::error!("coreclr_initialize or coreclr_create_delegate not found in {CORECLR}");
287 return;
288 };
289 let init_addr = (*init) as usize as *mut u8;
290 CREATE_DELEGATE.store((*create) as usize, Ordering::SeqCst);
291
292 tracing::info!("hooking coreclr_initialize");
293 match unsafe { hooking::Hook::create(init_addr, coreclr_init_detour as *mut u8) } {
294 Ok(mut hook) => {
295 if let Err(e) = unsafe { hook.apply_hook() } {
296 tracing::error!("applying the coreclr_initialize hook failed: {e:?}");
297 }
298 std::mem::forget(hook);
299 }
300 Err(e) => tracing::error!("hooking coreclr_initialize failed: {e:?}"),
301 }
302}
303
304extern "C" fn coreclr_init_detour(
305 exe: *const c_char,
306 name: *const c_char,
307 count: c_int,
308 keys: *const *const c_char,
309 values: *const *const c_char,
310 host_handle: *mut *mut c_void,
311 domain_id: *mut u32,
312) -> c_int {
313 let original =
314 hooking::original_function_ptr().expect("original! inside the coreclr_initialize hook");
315 let original: CoreclrInitialize = unsafe { std::mem::transmute(original.as_ptr()) };
316
317 tracing::debug!("coreclr_initialize called, arming assembly interception");
323 #[cfg(all(unix, target_arch = "x86_64"))]
324 crate::rewrite::arm_interception();
325
326 let result = unsafe { original(exe, name, count, keys, values, host_handle, domain_id) };
327 tracing::info!("coreclr_initialize returned 0x{result:x}");
328
329 if result == 0 && !host_handle.is_null() && !domain_id.is_null() {
330 let handle = unsafe { *host_handle };
331 let domain = unsafe { *domain_id };
332 let create = CREATE_DELEGATE.load(Ordering::SeqCst);
333 if create != 0 {
334 let host = ClrHost {
335 handle,
336 domain,
337 create_delegate: unsafe {
338 std::mem::transmute::<usize, CoreclrCreateDelegate>(create)
339 },
340 };
341 tracing::info!("captured CLR host: handle={handle:?}, domain={domain}");
342 let _ = HOST.set(host);
343 run_callbacks(host);
344 }
345 }
346 result
347}
348
349#[cfg(unix)]
352fn install_loader_hook() {
353 if LOADER_HOOKED.swap(true, Ordering::SeqCst) {
354 return;
355 }
356 if loaded_coreclr().is_some() {
360 tracing::info!("{CORECLR} is already loaded, hooking coreclr_initialize directly");
361 hook_coreclr_init();
362 return;
363 }
364
365 tracing::info!("hooking dlopen to wait for {CORECLR}");
366 match unsafe { hooking::Hook::by_name(None, c"dlopen", dlopen_detour as *mut u8) } {
367 Ok(mut hook) => {
368 if let Err(e) = unsafe { hook.apply_hook() } {
369 tracing::error!("applying the dlopen hook failed: {e:?}");
370 }
371 std::mem::forget(hook);
372 }
373 Err(e) => tracing::error!("hooking dlopen failed: {e:?}"),
374 }
375}
376
377#[cfg(unix)]
378extern "C" fn dlopen_detour(filename: *const c_char, flags: c_int) -> *mut c_void {
379 let original = hooking::original_function_ptr().expect("original! inside the dlopen hook");
381 let original: unsafe extern "C" fn(*const c_char, c_int) -> *mut c_void =
382 unsafe { std::mem::transmute(original.as_ptr()) };
383 let handle = unsafe { original(filename, flags) };
384 if !handle.is_null() && !INIT_HOOKED.load(Ordering::SeqCst) {
385 if !filename.is_null() {
386 let name = unsafe { std::ffi::CStr::from_ptr(filename) }.to_string_lossy();
387 if name.contains(CORECLR) {
388 tracing::info!("{CORECLR} loaded: {name}");
389 hook_coreclr_init();
390 }
391 }
392 if !INIT_HOOKED.load(Ordering::SeqCst) {
396 unsafe extern "C" {
397 fn dlsym(handle: *mut c_void, symbol: *const c_char) -> *mut c_void;
398 }
399 let sym = unsafe { dlsym(handle, c"coreclr_initialize".as_ptr()) };
400 if !sym.is_null() {
401 hook_coreclr_init();
402 }
403 }
404 }
405 handle
406}
407
408#[cfg(windows)]
409fn install_loader_hook() {
410 if LOADER_HOOKED.swap(true, Ordering::SeqCst) {
411 return;
412 }
413 if loaded_coreclr().is_some() {
416 tracing::info!("{CORECLR} is already loaded, hooking coreclr_initialize directly");
417 hook_coreclr_init();
418 return;
419 }
420
421 tracing::info!("hooking LoadLibraryExW to wait for {CORECLR}");
422 match unsafe {
423 hooking::Hook::by_name(
424 Some(c"kernelbase.dll"),
425 c"LoadLibraryExW",
426 loadlibrary_detour as *mut u8,
427 )
428 } {
429 Ok(mut hook) => {
430 if let Err(e) = unsafe { hook.apply_hook() } {
431 tracing::error!("applying the LoadLibraryExW hook failed: {e:?}");
432 }
433 std::mem::forget(hook);
434 }
435 Err(e) => tracing::error!("hooking LoadLibraryExW failed: {e:?}"),
436 }
437}
438
439#[cfg(windows)]
440extern "C" fn loadlibrary_detour(
441 filename: *const u16,
442 file: *mut c_void,
443 flags: u32,
444) -> *mut c_void {
445 let original =
446 hooking::original_function_ptr().expect("original! inside the LoadLibraryExW hook");
447 let original: unsafe extern "C" fn(*const u16, *mut c_void, u32) -> *mut c_void =
448 unsafe { std::mem::transmute(original.as_ptr()) };
449 let handle = unsafe { original(filename, file, flags) };
450 if !handle.is_null() && !INIT_HOOKED.load(Ordering::SeqCst) {
451 if !filename.is_null() {
452 let mut len = 0;
453 while unsafe { *filename.add(len) } != 0 {
454 len += 1;
455 }
456 let name =
457 String::from_utf16_lossy(unsafe { std::slice::from_raw_parts(filename, len) });
458 if name.to_ascii_lowercase().contains(CORECLR) {
459 tracing::info!("{CORECLR} loaded: {name}");
460 hook_coreclr_init();
461 }
462 }
463 if !INIT_HOOKED.load(Ordering::SeqCst) {
468 unsafe extern "system" {
469 fn GetProcAddress(module: *mut c_void, name: *const u8) -> *mut c_void;
470 }
471 let sym = unsafe { GetProcAddress(handle, c"coreclr_initialize".as_ptr().cast()) };
472 if !sym.is_null() {
473 hook_coreclr_init();
474 }
475 }
476 }
477 handle
478}
479
480#[cfg(all(test, target_os = "linux"))]
481mod tests {
482 use super::open_already_loaded;
483
484 fn mapped(name: &str) -> bool {
485 std::fs::read_to_string("/proc/self/maps").is_ok_and(|maps| maps.contains(name))
486 }
487
488 #[test]
489 fn opens_only_loaded_libraries() {
490 const NAME: &str = "libbz2.so.1";
493 if mapped("libbz2") {
494 eprintln!("skipping: {NAME} is already loaded");
495 return;
496 }
497 assert!(open_already_loaded(NAME).is_err(), "must not load {NAME}");
498 assert!(!mapped("libbz2"), "opening {NAME} loaded it");
499
500 let Ok(loaded) = (unsafe { libloading::Library::new(NAME) }) else {
501 eprintln!("skipping: {NAME} is not installed");
502 return;
503 };
504 assert!(open_already_loaded(NAME).is_ok(), "{NAME} is loaded");
505 drop(loaded);
506 }
507}