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
113static CALLBACKS: Mutex<Vec<Callback>> = Mutex::new(Vec::new());
114static HOST: OnceLock<ClrHost> = OnceLock::new();
115static CREATE_DELEGATE: AtomicUsize = AtomicUsize::new(0);
116static LOADER_HOOKED: AtomicBool = AtomicBool::new(false);
117static INIT_HOOKED: AtomicBool = AtomicBool::new(false);
118
119pub fn on_clr_init(callback: impl FnOnce(ClrHost) + Send + 'static) {
129 if let Some(host) = HOST.get() {
130 let host = *host;
131 std::thread::spawn(move || callback(host));
132 return;
133 }
134 CALLBACKS
135 .lock()
136 .unwrap_or_else(|e| e.into_inner())
137 .push(Box::new(callback));
138 install_loader_hook();
139}
140
141fn run_callbacks(host: ClrHost) {
143 std::thread::spawn(move || {
144 let callbacks = std::mem::take(&mut *CALLBACKS.lock().unwrap_or_else(|e| e.into_inner()));
145 for callback in callbacks {
146 callback(host);
147 }
148 });
149}
150
151fn hook_coreclr_init() {
154 if INIT_HOOKED.swap(true, Ordering::SeqCst) {
155 return;
156 }
157 let lib = match unsafe { libloading::Library::new(CORECLR) } {
158 Ok(lib) => lib,
159 Err(e) => {
160 tracing::error!("could not open {CORECLR}: {e}");
161 return;
162 }
163 };
164 let init = unsafe { lib.get::<CoreclrInitialize>(b"coreclr_initialize\0") };
165 let create = unsafe { lib.get::<CoreclrCreateDelegate>(b"coreclr_create_delegate\0") };
166 let (Ok(init), Ok(create)) = (init, create) else {
167 tracing::error!("coreclr_initialize or coreclr_create_delegate not found in {CORECLR}");
168 return;
169 };
170 let init_addr = (*init) as usize as *mut u8;
171 CREATE_DELEGATE.store((*create) as usize, Ordering::SeqCst);
172 std::mem::forget(lib); tracing::info!("hooking coreclr_initialize");
175 match unsafe { hooking::Hook::create(init_addr, coreclr_init_detour as *mut u8) } {
176 Ok(mut hook) => {
177 if let Err(e) = unsafe { hook.apply_hook() } {
178 tracing::error!("applying the coreclr_initialize hook failed: {e:?}");
179 }
180 std::mem::forget(hook);
181 }
182 Err(e) => tracing::error!("hooking coreclr_initialize failed: {e:?}"),
183 }
184}
185
186extern "C" fn coreclr_init_detour(
187 exe: *const c_char,
188 name: *const c_char,
189 count: c_int,
190 keys: *const *const c_char,
191 values: *const *const c_char,
192 host_handle: *mut *mut c_void,
193 domain_id: *mut u32,
194) -> c_int {
195 let original =
196 hooking::original_function_ptr().expect("original! inside the coreclr_initialize hook");
197 let original: CoreclrInitialize = unsafe { std::mem::transmute(original.as_ptr()) };
198 let result = unsafe { original(exe, name, count, keys, values, host_handle, domain_id) };
199 tracing::info!("coreclr_initialize returned 0x{result:x}");
200 if result == 0 && !host_handle.is_null() && !domain_id.is_null() {
201 let handle = unsafe { *host_handle };
202 let domain = unsafe { *domain_id };
203 let create = CREATE_DELEGATE.load(Ordering::SeqCst);
204 if create != 0 {
205 let host = ClrHost {
206 handle,
207 domain,
208 create_delegate: unsafe {
209 std::mem::transmute::<usize, CoreclrCreateDelegate>(create)
210 },
211 };
212 tracing::info!("captured CLR host: handle={handle:?}, domain={domain}");
213 let _ = HOST.set(host);
214 run_callbacks(host);
217 }
218 }
219 result
220}
221
222#[cfg(unix)]
225fn install_loader_hook() {
226 if LOADER_HOOKED.swap(true, Ordering::SeqCst) {
227 return;
228 }
229 tracing::info!("hooking dlopen to wait for {CORECLR}");
230 match unsafe { hooking::Hook::by_name(None, c"dlopen", dlopen_detour as *mut u8) } {
231 Ok(mut hook) => {
232 if let Err(e) = unsafe { hook.apply_hook() } {
233 tracing::error!("applying the dlopen hook failed: {e:?}");
234 }
235 std::mem::forget(hook);
236 }
237 Err(e) => tracing::error!("hooking dlopen failed: {e:?}"),
238 }
239}
240
241#[cfg(unix)]
242extern "C" fn dlopen_detour(filename: *const c_char, flags: c_int) -> *mut c_void {
243 let original = hooking::original_function_ptr().expect("original! inside the dlopen hook");
245 let original: unsafe extern "C" fn(*const c_char, c_int) -> *mut c_void =
246 unsafe { std::mem::transmute(original.as_ptr()) };
247 let handle = unsafe { original(filename, flags) };
248 if !handle.is_null() && !filename.is_null() && !INIT_HOOKED.load(Ordering::SeqCst) {
249 let name = unsafe { std::ffi::CStr::from_ptr(filename) }.to_string_lossy();
250 if name.contains(CORECLR) {
251 tracing::info!("{CORECLR} loaded: {name}");
252 hook_coreclr_init();
253 }
254 }
255 handle
256}
257
258#[cfg(windows)]
259fn install_loader_hook() {
260 if LOADER_HOOKED.swap(true, Ordering::SeqCst) {
261 return;
262 }
263 tracing::info!("hooking LoadLibraryExW to wait for {CORECLR}");
264 match unsafe {
265 hooking::Hook::by_name(Some(c"kernelbase.dll"), c"LoadLibraryExW", loadlibrary_detour as *mut u8)
266 } {
267 Ok(mut hook) => {
268 if let Err(e) = unsafe { hook.apply_hook() } {
269 tracing::error!("applying the LoadLibraryExW hook failed: {e:?}");
270 }
271 std::mem::forget(hook);
272 }
273 Err(e) => tracing::error!("hooking LoadLibraryExW failed: {e:?}"),
274 }
275}
276
277#[cfg(windows)]
278extern "C" fn loadlibrary_detour(
279 filename: *const u16,
280 file: *mut c_void,
281 flags: u32,
282) -> *mut c_void {
283 let original = hooking::original_function_ptr().expect("original! inside the LoadLibraryExW hook");
284 let original: unsafe extern "C" fn(*const u16, *mut c_void, u32) -> *mut c_void =
285 unsafe { std::mem::transmute(original.as_ptr()) };
286 let handle = unsafe { original(filename, file, flags) };
287 if !handle.is_null() && !filename.is_null() && !INIT_HOOKED.load(Ordering::SeqCst) {
288 let mut len = 0;
289 while unsafe { *filename.add(len) } != 0 {
290 len += 1;
291 }
292 let name = String::from_utf16_lossy(unsafe { std::slice::from_raw_parts(filename, len) });
293 if name.to_ascii_lowercase().contains(CORECLR) {
294 tracing::info!("{CORECLR} loaded: {name}");
295 hook_coreclr_init();
296 }
297 }
298 handle
299}