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) {
tracing::debug!("{msg}");
}
static CALLBACKS: Mutex<Vec<Callback>> = Mutex::new(Vec::new());
static CORECLR_LIBRARY: OnceLock<libloading::Library> = OnceLock::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() {
tracing::debug!("on_clr_init: host already captured");
let host = *host;
std::thread::spawn(move || callback(host));
return;
}
#[cfg(target_arch = "x86_64")]
if let Some(host) = try_capture_running_host() {
tracing::debug!("on_clr_init: captured the running CLR via GetCLRRuntimeHost");
let host = *HOST.get_or_init(|| host);
std::thread::spawn(move || callback(host));
return;
}
tracing::debug!("on_clr_init: CLR not started, waiting for coreclr_initialize");
CALLBACKS
.lock()
.unwrap_or_else(|e| e.into_inner())
.push(Box::new(callback));
install_loader_hook();
}
#[cfg(target_arch = "x86_64")]
fn try_capture_running_host() -> Option<ClrHost> {
const IID_IUNKNOWN: [u8; 16] = [0, 0, 0, 0, 0, 0, 0, 0, 0xc0, 0, 0, 0, 0, 0, 0, 0x46];
type GetClrRuntimeHost = unsafe extern "C" fn(*const u8, *mut *mut c_void) -> c_int;
let lib = loaded_coreclr()?;
let get_host = unsafe { lib.get::<GetClrRuntimeHost>(b"GetCLRRuntimeHost\0") }.ok()?;
let create = unsafe { lib.get::<CoreclrCreateDelegate>(b"coreclr_create_delegate\0") }.ok()?;
let create_delegate: CoreclrCreateDelegate = *create;
let mut host: *mut c_void = std::ptr::null_mut();
let code = unsafe { (*get_host)(IID_IUNKNOWN.as_ptr(), &mut host) };
if code != 0 || host.is_null() {
return None; }
Some(ClrHost {
handle: host,
domain: 1,
create_delegate,
})
}
fn loaded_coreclr() -> Option<&'static libloading::Library> {
if let Some(lib) = CORECLR_LIBRARY.get() {
return Some(lib);
}
let lib = match open_already_loaded(CORECLR) {
Ok(lib) => lib,
Err(e) => {
tracing::debug!("{CORECLR} is not loaded yet: {e}");
return None;
}
};
let _ = CORECLR_LIBRARY.set(lib);
CORECLR_LIBRARY.get()
}
#[cfg(unix)]
fn open_already_loaded(name: &str) -> std::result::Result<libloading::Library, libloading::Error> {
use libloading::os::unix::{Library, RTLD_NOW};
#[cfg(any(target_os = "linux", target_os = "android"))]
const RTLD_NOLOAD: c_int = 0x4;
#[cfg(any(target_os = "macos", target_os = "ios"))]
const RTLD_NOLOAD: c_int = 0x10;
#[cfg(target_os = "freebsd")]
const RTLD_NOLOAD: c_int = 0x2000;
unsafe { Library::open(Some(name), RTLD_NOLOAD | RTLD_NOW) }.map(Into::into)
}
#[cfg(windows)]
fn open_already_loaded(name: &str) -> std::result::Result<libloading::Library, libloading::Error> {
libloading::os::windows::Library::open_already_loaded(name).map(Into::into)
}
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 Some(lib) = loaded_coreclr() else {
tracing::error!("{CORECLR} is not loaded, not hooking coreclr_initialize");
INIT_HOOKED.store(false, Ordering::SeqCst);
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);
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()) };
tracing::debug!("coreclr_initialize called, arming assembly interception");
#[cfg(all(unix, target_arch = "x86_64"))]
crate::rewrite::arm_interception();
let result = unsafe { original(exe, name, count, keys, values, host_handle, domain_id) };
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;
}
if loaded_coreclr().is_some() {
tracing::info!("{CORECLR} is already loaded, hooking coreclr_initialize directly");
hook_coreclr_init();
return;
}
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;
}
if loaded_coreclr().is_some() {
tracing::info!("{CORECLR} is already loaded, hooking coreclr_initialize directly");
hook_coreclr_init();
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() && !INIT_HOOKED.load(Ordering::SeqCst) {
if !filename.is_null() {
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();
}
}
if !INIT_HOOKED.load(Ordering::SeqCst) {
unsafe extern "system" {
fn GetProcAddress(module: *mut c_void, name: *const u8) -> *mut c_void;
}
let sym = unsafe { GetProcAddress(handle, c"coreclr_initialize".as_ptr().cast()) };
if !sym.is_null() {
hook_coreclr_init();
}
}
}
handle
}
#[cfg(all(test, target_os = "linux"))]
mod tests {
use super::open_already_loaded;
fn mapped(name: &str) -> bool {
std::fs::read_to_string("/proc/self/maps").is_ok_and(|maps| maps.contains(name))
}
#[test]
fn opens_only_loaded_libraries() {
const NAME: &str = "libbz2.so.1";
if mapped("libbz2") {
eprintln!("skipping: {NAME} is already loaded");
return;
}
assert!(open_already_loaded(NAME).is_err(), "must not load {NAME}");
assert!(!mapped("libbz2"), "opening {NAME} loaded it");
let Ok(loaded) = (unsafe { libloading::Library::new(NAME) }) else {
eprintln!("skipping: {NAME} is not installed");
return;
};
assert!(open_already_loaded(NAME).is_ok(), "{NAME} is loaded");
drop(loaded);
}
}