use std::{
ffi::{c_char, c_int, c_void},
sync::{
atomic::{AtomicBool, AtomicUsize, Ordering},
Mutex, OnceLock,
},
};
use crate::{Result, Runtime};
type CoreclrInitialize = unsafe extern "C" fn(
*const c_char,
*const c_char,
c_int,
*const *const c_char,
*const *const c_char,
*mut *mut c_void,
*mut u32,
) -> c_int;
type CoreclrCreateDelegate = unsafe extern "C" fn(
*mut c_void,
u32,
*const c_char,
*const c_char,
*const c_char,
*mut *mut c_void,
) -> c_int;
const CORECLR: &str = if cfg!(windows) {
"coreclr.dll"
} else {
"libcoreclr.so"
};
#[derive(Clone, Copy)]
pub struct ClrHost {
pub handle: *mut c_void,
pub domain: u32,
create_delegate: CoreclrCreateDelegate,
}
unsafe impl Send for ClrHost {}
unsafe impl Sync for ClrHost {}
impl ClrHost {
pub fn create_delegate(
&self,
assembly: &str,
type_name: &str,
method: &str,
) -> std::result::Result<*mut c_void, String> {
use std::ffi::CString;
let assembly = CString::new(assembly).map_err(|_| "assembly has a nul")?;
let type_name = CString::new(type_name).map_err(|_| "type has a nul")?;
let method = CString::new(method).map_err(|_| "method has a nul")?;
let mut delegate = std::ptr::null_mut();
let code = unsafe {
(self.create_delegate)(
self.handle,
self.domain,
assembly.as_ptr(),
type_name.as_ptr(),
method.as_ptr(),
&mut delegate,
)
};
if code != 0 {
return Err(format!("coreclr_create_delegate failed: 0x{code:x}"));
}
Ok(delegate)
}
pub fn attach(&self, major: u16) -> Result<Runtime> {
Runtime::coreclr_attach(
self.handle,
self.domain,
self.create_delegate as *const c_void,
major,
)
}
}
type Callback = Box<dyn FnOnce(ClrHost) + Send>;
pub fn diag(msg: &str) {
use std::io::Write;
if let Ok(mut f) = std::fs::OpenOptions::new()
.create(true)
.append(true)
.open("/tmp/hao-diag.log")
{
let _ = writeln!(f, "[hao-diag] {msg}");
}
}
static CALLBACKS: Mutex<Vec<Callback>> = Mutex::new(Vec::new());
static HOST: OnceLock<ClrHost> = OnceLock::new();
static CREATE_DELEGATE: AtomicUsize = AtomicUsize::new(0);
static LOADER_HOOKED: AtomicBool = AtomicBool::new(false);
static INIT_HOOKED: AtomicBool = AtomicBool::new(false);
pub fn ensure_loader_hook() {
install_loader_hook();
}
pub fn on_clr_init(callback: impl FnOnce(ClrHost) + Send + 'static) {
if let Some(host) = HOST.get() {
diag("on_clr_init: HOST already set, fast path");
let host = *host;
std::thread::spawn(move || callback(host));
return;
}
diag("on_clr_init: HOST not set, registering callback + loader hook");
CALLBACKS
.lock()
.unwrap_or_else(|e| e.into_inner())
.push(Box::new(callback));
install_loader_hook();
}
fn run_callbacks(host: ClrHost) {
std::thread::spawn(move || {
let callbacks = std::mem::take(&mut *CALLBACKS.lock().unwrap_or_else(|e| e.into_inner()));
for callback in callbacks {
callback(host);
}
});
}
fn hook_coreclr_init() {
if INIT_HOOKED.swap(true, Ordering::SeqCst) {
return;
}
let lib = match unsafe { libloading::Library::new(CORECLR) } {
Ok(lib) => lib,
Err(e) => {
tracing::error!("could not open {CORECLR}: {e}");
return;
}
};
let init = unsafe { lib.get::<CoreclrInitialize>(b"coreclr_initialize\0") };
let create = unsafe { lib.get::<CoreclrCreateDelegate>(b"coreclr_create_delegate\0") };
let (Ok(init), Ok(create)) = (init, create) else {
tracing::error!("coreclr_initialize or coreclr_create_delegate not found in {CORECLR}");
return;
};
let init_addr = (*init) as usize as *mut u8;
CREATE_DELEGATE.store((*create) as usize, Ordering::SeqCst);
std::mem::forget(lib);
tracing::info!("hooking coreclr_initialize");
match unsafe { hooking::Hook::create(init_addr, coreclr_init_detour as *mut u8) } {
Ok(mut hook) => {
if let Err(e) = unsafe { hook.apply_hook() } {
tracing::error!("applying the coreclr_initialize hook failed: {e:?}");
}
std::mem::forget(hook);
}
Err(e) => tracing::error!("hooking coreclr_initialize failed: {e:?}"),
}
}
extern "C" fn coreclr_init_detour(
exe: *const c_char,
name: *const c_char,
count: c_int,
keys: *const *const c_char,
values: *const *const c_char,
host_handle: *mut *mut c_void,
domain_id: *mut u32,
) -> c_int {
let original =
hooking::original_function_ptr().expect("original! inside the coreclr_initialize hook");
let original: CoreclrInitialize = unsafe { std::mem::transmute(original.as_ptr()) };
diag("coreclr_init_detour entered, arming interception");
#[cfg(all(unix, target_arch = "x86_64"))]
crate::rewrite::arm_interception();
diag("arm_interception done, calling original");
let result = unsafe { original(exe, name, count, keys, values, host_handle, domain_id) };
diag(&format!("coreclr_initialize returned 0x{result:x}"));
tracing::info!("coreclr_initialize returned 0x{result:x}");
if result == 0 && !host_handle.is_null() && !domain_id.is_null() {
let handle = unsafe { *host_handle };
let domain = unsafe { *domain_id };
let create = CREATE_DELEGATE.load(Ordering::SeqCst);
if create != 0 {
let host = ClrHost {
handle,
domain,
create_delegate: unsafe {
std::mem::transmute::<usize, CoreclrCreateDelegate>(create)
},
};
tracing::info!("captured CLR host: handle={handle:?}, domain={domain}");
let _ = HOST.set(host);
run_callbacks(host);
}
}
result
}
#[cfg(unix)]
fn install_loader_hook() {
if LOADER_HOOKED.swap(true, Ordering::SeqCst) {
return;
}
unsafe extern "C" {
fn dlsym(handle: *mut c_void, symbol: *const c_char) -> *mut c_void;
}
const RTLD_DEFAULT: *mut c_void = std::ptr::null_mut();
let probe =
unsafe { dlsym(RTLD_DEFAULT, c"coreclr_initialize".as_ptr()) };
if !probe.is_null() {
diag("coreclr already loaded, hooking directly");
tracing::info!("{CORECLR} is already loaded, hooking coreclr_initialize directly");
hook_coreclr_init();
return;
}
diag("hooking dlopen to wait for coreclr");
tracing::info!("hooking dlopen to wait for {CORECLR}");
match unsafe { hooking::Hook::by_name(None, c"dlopen", dlopen_detour as *mut u8) } {
Ok(mut hook) => {
if let Err(e) = unsafe { hook.apply_hook() } {
tracing::error!("applying the dlopen hook failed: {e:?}");
}
std::mem::forget(hook);
}
Err(e) => tracing::error!("hooking dlopen failed: {e:?}"),
}
}
#[cfg(unix)]
extern "C" fn dlopen_detour(filename: *const c_char, flags: c_int) -> *mut c_void {
let original = hooking::original_function_ptr().expect("original! inside the dlopen hook");
let original: unsafe extern "C" fn(*const c_char, c_int) -> *mut c_void =
unsafe { std::mem::transmute(original.as_ptr()) };
let handle = unsafe { original(filename, flags) };
if !handle.is_null() && !INIT_HOOKED.load(Ordering::SeqCst) {
if !filename.is_null() {
let name = unsafe { std::ffi::CStr::from_ptr(filename) }.to_string_lossy();
if name.contains(CORECLR) {
tracing::info!("{CORECLR} loaded: {name}");
hook_coreclr_init();
}
}
if !INIT_HOOKED.load(Ordering::SeqCst) {
unsafe extern "C" {
fn dlsym(handle: *mut c_void, symbol: *const c_char) -> *mut c_void;
}
let sym = unsafe {
dlsym(handle, c"coreclr_initialize".as_ptr())
};
if !sym.is_null() {
hook_coreclr_init();
}
}
}
handle
}
#[cfg(windows)]
fn install_loader_hook() {
if LOADER_HOOKED.swap(true, Ordering::SeqCst) {
return;
}
tracing::info!("hooking LoadLibraryExW to wait for {CORECLR}");
match unsafe {
hooking::Hook::by_name(Some(c"kernelbase.dll"), c"LoadLibraryExW", loadlibrary_detour as *mut u8)
} {
Ok(mut hook) => {
if let Err(e) = unsafe { hook.apply_hook() } {
tracing::error!("applying the LoadLibraryExW hook failed: {e:?}");
}
std::mem::forget(hook);
}
Err(e) => tracing::error!("hooking LoadLibraryExW failed: {e:?}"),
}
}
#[cfg(windows)]
extern "C" fn loadlibrary_detour(
filename: *const u16,
file: *mut c_void,
flags: u32,
) -> *mut c_void {
let original = hooking::original_function_ptr().expect("original! inside the LoadLibraryExW hook");
let original: unsafe extern "C" fn(*const u16, *mut c_void, u32) -> *mut c_void =
unsafe { std::mem::transmute(original.as_ptr()) };
let handle = unsafe { original(filename, file, flags) };
if !handle.is_null() && !filename.is_null() && !INIT_HOOKED.load(Ordering::SeqCst) {
let mut len = 0;
while unsafe { *filename.add(len) } != 0 {
len += 1;
}
let name = String::from_utf16_lossy(unsafe { std::slice::from_raw_parts(filename, len) });
if name.to_ascii_lowercase().contains(CORECLR) {
tracing::info!("{CORECLR} loaded: {name}");
hook_coreclr_init();
}
}
handle
}