Skip to main content

hao_runtime/
profiler.rs

1//! A minimal CoreCLR profiler, implemented as COM objects by hand.
2//!
3//! Registered as a startup profiler (the host sets `CORECLR_ENABLE_PROFILING=1`,
4//! `CORECLR_PROFILER={`[`CLSID_STRING`]`}` and `CORECLR_PROFILER_PATH` to the
5//! `.so` that re-exports [`dll_get_class_object`] as `DllGetClassObject`), the
6//! runtime loads it and calls [`ICorProfilerCallback::Initialize`], where we grab
7//! `ICorProfilerInfo` and ask to monitor JIT compilation and to enable ReJIT.
8//!
9//! This is the registration layer. ReJIT (replacing a method's IL with hao's)
10//! and native code-address lookup (for patching machine code with `iced`) build
11//! on the `ICorProfilerInfo` captured here.
12//!
13//! COM on Linux uses the C calling convention; every callback returns an
14//! `HRESULT`, so unused vtable slots share one stub that returns `S_OK`.
15
16#![allow(clippy::missing_safety_doc)]
17
18use std::{
19    collections::HashMap,
20    ffi::c_void,
21    sync::{
22        atomic::{AtomicPtr, Ordering},
23        Mutex,
24    },
25};
26
27type Hresult = i32;
28const S_OK: Hresult = 0;
29const E_NOINTERFACE: Hresult = 0x8000_4002u32 as Hresult;
30const E_POINTER: Hresult = 0x8000_4003u32 as Hresult;
31const CLASS_E_CLASSNOTAVAILABLE: Hresult = 0x8004_0111u32 as Hresult;
32
33// COR_PRF_MONITOR flags (corprof.idl).
34const COR_PRF_MONITOR_MODULE_LOADS: u32 = 0x0000_0004;
35const COR_PRF_MONITOR_JIT_COMPILATION: u32 = 0x0000_0020;
36const COR_PRF_ENABLE_REJIT: u32 = 0x0004_0000;
37
38// ICorProfilerInfo vtable slots (3 IUnknown methods precede ICorProfilerInfo;
39// Info2 follows all 33 Info1 methods). Resolved from corprof.idl.
40const SLOT_GET_FUNCTION_FROM_TOKEN: usize = 8;
41const SLOT_GET_FUNCTION_INFO: usize = 15;
42const SLOT_SET_EVENT_MASK: usize = 16;
43const SLOT_GET_MODULE_INFO: usize = 20;
44const SLOT_GET_CODE_INFO2: usize = 42;
45
46/// `COR_PRF_CODE_INFO`: one contiguous block of a method's native code.
47#[repr(C)]
48#[derive(Clone, Copy, Default)]
49struct CodeInfo {
50    start: usize,
51    size: usize,
52}
53
54/// Loaded modules by id, for naming JIT events and resolving `native_code`.
55static MODULES: Mutex<Option<HashMap<usize, String>>> = Mutex::new(None);
56/// A substring: JIT events are logged only for modules whose name contains it.
57static WATCH: Mutex<Option<String>> = Mutex::new(None);
58
59/// Log JITed methods of modules whose name contains `substring` (e.g. the game
60/// assembly). Without this, module loads are still logged but JITs are not.
61pub fn watch_module(substring: &str) {
62    *WATCH.lock().unwrap_or_else(|e| e.into_inner()) = Some(substring.to_string());
63}
64
65/// A COM interface id / class id.
66#[repr(C)]
67#[derive(Clone, Copy, PartialEq, Eq)]
68#[cfg_attr(feature = "reflect", derive(facet::Facet))]
69pub struct Guid {
70    data1: u32,
71    data2: u16,
72    data3: u16,
73    data4: [u8; 8],
74}
75
76const fn guid(data1: u32, data2: u16, data3: u16, data4: [u8; 8]) -> Guid {
77    Guid { data1, data2, data3, data4 }
78}
79
80// The CLSID a host passes as CORECLR_PROFILER. Ours; not a well-known value.
81const CLSID_HAO_PROFILER: Guid = guid(0x7F9A_1B2C, 0x3D4E, 0x4F50, [0x9A, 0x1B, 0x2C, 0x3D, 0x4E, 0x5F, 0x60, 0x71]);
82/// The string form of our profiler CLSID, for `CORECLR_PROFILER`.
83pub const CLSID_STRING: &str = "{7F9A1B2C-3D4E-4F50-9A1B-2C3D4E5F6071}";
84
85const IID_IUNKNOWN: Guid = guid(0, 0, 0, [0xC0, 0, 0, 0, 0, 0, 0, 0x46]);
86const IID_ICLASSFACTORY: Guid = guid(1, 0, 0, [0xC0, 0, 0, 0, 0, 0, 0, 0x46]);
87const IID_ICORPROFILERCALLBACK: Guid = guid(0x176F_BED1, 0xA55C, 0x4796, [0x98, 0xCA, 0xA9, 0xDA, 0x0E, 0xF8, 0x83, 0xE7]);
88const IID_ICORPROFILERCALLBACK2: Guid = guid(0x8A8C_C829, 0xCCF2, 0x49FE, [0xBB, 0xAE, 0x0F, 0x02, 0x22, 0x28, 0x07, 0x1A]);
89const IID_ICORPROFILERCALLBACK3: Guid = guid(0x4FD2_ED52, 0x7731, 0x4B8D, [0x94, 0x69, 0x03, 0xD2, 0xCC, 0x30, 0x86, 0xC5]);
90const IID_ICORPROFILERCALLBACK4: Guid = guid(0x7B63_B2E3, 0x107D, 0x4D48, [0xB2, 0xF6, 0xF6, 0x1E, 0x22, 0x94, 0x70, 0xD2]);
91const IID_ICORPROFILERINFO: Guid = guid(0x28B5_557D, 0x3F3F, 0x48B4, [0x90, 0xB2, 0x5F, 0x9E, 0xEA, 0x2F, 0x6C, 0x48]);
92
93use tracing::info;
94
95/// The captured `ICorProfilerInfo` (really the highest version the runtime gave
96/// us via the base IID). ReJIT and code-info layers read this.
97static INFO: AtomicPtr<c_void> = AtomicPtr::new(std::ptr::null_mut());
98
99// --- ICorProfilerCallback ------------------------------------------------
100
101/// The callback object: a pointer to its vtable, as COM requires, and nothing
102/// else — it is a process-lifetime singleton, so it needs no ref counting.
103#[repr(C)]
104struct Callback {
105    vtable: *const CallbackVtbl,
106}
107
108// The vtables are immutable, and the objects are process-lifetime singletons
109// reached only through raw pointers, so sharing them across threads is sound.
110unsafe impl Sync for CallbackVtbl {}
111unsafe impl Sync for FactoryVtbl {}
112
113// ICorProfilerCallback(1..4) has 95 methods after IUnknown's 3, so the vtable
114// is 98 slots. We implement Initialize (slot 3), ModuleLoadFinished (14) and
115// JITCompilationFinished (24); the gaps between them are filled with one S_OK
116// stub. Slot positions are from the method order in corprof.idl.
117#[repr(C)]
118struct CallbackVtbl {
119    query_interface: unsafe extern "C" fn(*mut Callback, *const Guid, *mut *mut c_void) -> Hresult,
120    add_ref: unsafe extern "C" fn(*mut Callback) -> u32,
121    release: unsafe extern "C" fn(*mut Callback) -> u32,
122    initialize: unsafe extern "C" fn(*mut Callback, *mut c_void) -> Hresult,
123    gap_a: [*const c_void; 10], // slots 4..=13
124    module_load_finished: unsafe extern "C" fn(*mut Callback, usize, Hresult) -> Hresult, // 14
125    gap_b: [*const c_void; 9], // slots 15..=23
126    jit_compilation_finished: unsafe extern "C" fn(*mut Callback, usize, Hresult, i32) -> Hresult, // 24
127    gap_c: [*const c_void; 73], // slots 25..=97
128}
129
130unsafe extern "C" fn cb_query_interface(
131    this: *mut Callback,
132    riid: *const Guid,
133    ppv: *mut *mut c_void,
134) -> Hresult {
135    if riid.is_null() || ppv.is_null() {
136        return E_POINTER;
137    }
138    let riid = unsafe { *riid };
139    if riid == IID_IUNKNOWN
140        || riid == IID_ICORPROFILERCALLBACK
141        || riid == IID_ICORPROFILERCALLBACK2
142        || riid == IID_ICORPROFILERCALLBACK3
143        || riid == IID_ICORPROFILERCALLBACK4
144    {
145        unsafe { *ppv = this as *mut c_void };
146        S_OK
147    } else {
148        unsafe { *ppv = std::ptr::null_mut() };
149        E_NOINTERFACE
150    }
151}
152
153unsafe extern "C" fn cb_add_ref(_this: *mut Callback) -> u32 {
154    1
155}
156
157unsafe extern "C" fn cb_release(_this: *mut Callback) -> u32 {
158    1
159}
160
161/// A vtable slot we don't implement. Every `ICorProfilerCallback` method returns
162/// `HRESULT`, and on the C calling convention the callee ignores extra argument
163/// registers, so one `S_OK` stub serves them all.
164unsafe extern "C" fn cb_stub(_this: *mut Callback) -> Hresult {
165    S_OK
166}
167
168unsafe extern "C" fn cb_initialize(_this: *mut Callback, unk: *mut c_void) -> Hresult {
169    if unk.is_null() {
170        return E_POINTER;
171    }
172    // QueryInterface the given IUnknown for ICorProfilerInfo.
173    let info = unsafe { query_interface(unk, &IID_ICORPROFILERINFO) };
174    let Some(info) = info else {
175        tracing::error!("Initialize: ICorProfilerInfo not available");
176        return E_NOINTERFACE;
177    };
178    INFO.store(info, Ordering::SeqCst);
179    *MODULES.lock().unwrap_or_else(|e| e.into_inner()) = Some(HashMap::new());
180
181    // Monitor module loads and JIT, and enable ReJIT.
182    let mask =
183        COR_PRF_MONITOR_MODULE_LOADS | COR_PRF_MONITOR_JIT_COMPILATION | COR_PRF_ENABLE_REJIT;
184    let hr = unsafe { call_slot_u32(info, SLOT_SET_EVENT_MASK, mask) };
185    info!("profiler initialized: ICorProfilerInfo={info:?}, SetEventMask(0x{mask:x})=0x{hr:x}");
186    S_OK
187}
188
189unsafe extern "C" fn cb_module_load_finished(
190    _this: *mut Callback,
191    module_id: usize,
192    _hr_status: Hresult,
193) -> Hresult {
194    let info = INFO.load(Ordering::SeqCst);
195    if let Some(name) = unsafe { get_module_name(info, module_id) } {
196        info!("module loaded: {name} (id={module_id:#x})");
197        if let Some(map) = MODULES.lock().unwrap_or_else(|e| e.into_inner()).as_mut() {
198            map.insert(module_id, name);
199        }
200    }
201    S_OK
202}
203
204unsafe extern "C" fn cb_jit_compilation_finished(
205    _this: *mut Callback,
206    function_id: usize,
207    _hr_status: Hresult,
208    _is_safe_to_block: i32,
209) -> Hresult {
210    let watch = WATCH.lock().unwrap_or_else(|e| e.into_inner()).clone();
211    let Some(watch) = watch else { return S_OK };
212    let info = INFO.load(Ordering::SeqCst);
213    let Some((module_id, token)) = (unsafe { get_function_info(info, function_id) }) else {
214        return S_OK;
215    };
216    let name = MODULES
217        .lock()
218        .unwrap_or_else(|e| e.into_inner())
219        .as_ref()
220        .and_then(|m| m.get(&module_id).cloned());
221    let Some(name) = name else { return S_OK };
222    if !name.contains(&watch) {
223        return S_OK;
224    }
225    match unsafe { get_code_info(info, function_id) } {
226        Some(code) => info!(
227            "jit {name} token={token:#010x} -> code {:#x} ({} bytes)",
228            code.start, code.size
229        ),
230        None => info!("jit {name} token={token:#010x} (no code info)"),
231    }
232    S_OK
233}
234
235static CALLBACK_VTBL: CallbackVtbl = CallbackVtbl {
236    query_interface: cb_query_interface,
237    add_ref: cb_add_ref,
238    release: cb_release,
239    initialize: cb_initialize,
240    gap_a: [cb_stub as *const c_void; 10],
241    module_load_finished: cb_module_load_finished,
242    gap_b: [cb_stub as *const c_void; 9],
243    jit_compilation_finished: cb_jit_compilation_finished,
244    gap_c: [cb_stub as *const c_void; 73],
245};
246
247static mut CALLBACK: Callback = Callback {
248    vtable: &CALLBACK_VTBL,
249};
250
251// --- IClassFactory -------------------------------------------------------
252
253#[repr(C)]
254struct Factory {
255    vtable: *const FactoryVtbl,
256}
257
258#[repr(C)]
259struct FactoryVtbl {
260    query_interface: unsafe extern "C" fn(*mut Factory, *const Guid, *mut *mut c_void) -> Hresult,
261    add_ref: unsafe extern "C" fn(*mut Factory) -> u32,
262    release: unsafe extern "C" fn(*mut Factory) -> u32,
263    create_instance:
264        unsafe extern "C" fn(*mut Factory, *mut c_void, *const Guid, *mut *mut c_void) -> Hresult,
265    lock_server: unsafe extern "C" fn(*mut Factory, i32) -> Hresult,
266}
267
268unsafe extern "C" fn factory_query_interface(
269    this: *mut Factory,
270    riid: *const Guid,
271    ppv: *mut *mut c_void,
272) -> Hresult {
273    if riid.is_null() || ppv.is_null() {
274        return E_POINTER;
275    }
276    let riid = unsafe { *riid };
277    if riid == IID_IUNKNOWN || riid == IID_ICLASSFACTORY {
278        unsafe { *ppv = this as *mut c_void };
279        S_OK
280    } else {
281        unsafe { *ppv = std::ptr::null_mut() };
282        E_NOINTERFACE
283    }
284}
285
286unsafe extern "C" fn factory_add_ref(_this: *mut Factory) -> u32 {
287    1
288}
289
290unsafe extern "C" fn factory_release(_this: *mut Factory) -> u32 {
291    1
292}
293
294unsafe extern "C" fn factory_create_instance(
295    _this: *mut Factory,
296    outer: *mut c_void,
297    _riid: *const Guid,
298    ppv: *mut *mut c_void,
299) -> Hresult {
300    if ppv.is_null() {
301        return E_POINTER;
302    }
303    if !outer.is_null() {
304        // No aggregation.
305        return 0x8004_0110u32 as Hresult; // CLASS_E_NOAGGREGATION
306    }
307    unsafe { *ppv = std::ptr::addr_of_mut!(CALLBACK) as *mut c_void };
308    S_OK
309}
310
311unsafe extern "C" fn factory_lock_server(_this: *mut Factory, _lock: i32) -> Hresult {
312    S_OK
313}
314
315static FACTORY_VTBL: FactoryVtbl = FactoryVtbl {
316    query_interface: factory_query_interface,
317    add_ref: factory_add_ref,
318    release: factory_release,
319    create_instance: factory_create_instance,
320    lock_server: factory_lock_server,
321};
322
323static mut FACTORY: Factory = Factory {
324    vtable: &FACTORY_VTBL,
325};
326
327/// The entry CoreCLR looks up by name in the profiler library. A host re-exports
328/// it as `DllGetClassObject`.
329pub unsafe extern "C" fn dll_get_class_object(
330    rclsid: *const Guid,
331    riid: *const Guid,
332    ppv: *mut *mut c_void,
333) -> Hresult {
334    if rclsid.is_null() || riid.is_null() || ppv.is_null() {
335        return E_POINTER;
336    }
337    if unsafe { *rclsid } != CLSID_HAO_PROFILER {
338        return CLASS_E_CLASSNOTAVAILABLE;
339    }
340    let riid = unsafe { *riid };
341    if riid == IID_ICLASSFACTORY || riid == IID_IUNKNOWN {
342        unsafe { *ppv = std::ptr::addr_of_mut!(FACTORY) as *mut c_void };
343        S_OK
344    } else {
345        E_NOINTERFACE
346    }
347}
348
349// --- COM call helpers ----------------------------------------------------
350
351/// Calls `IUnknown::QueryInterface(riid)` on a raw interface pointer.
352unsafe fn query_interface(unk: *mut c_void, riid: *const Guid) -> Option<*mut c_void> {
353    let vtable = unsafe { *(unk as *const *const *const c_void) };
354    let qi: unsafe extern "C" fn(*mut c_void, *const Guid, *mut *mut c_void) -> Hresult =
355        unsafe { std::mem::transmute(*vtable) };
356    let mut out = std::ptr::null_mut();
357    if unsafe { qi(unk, riid, &mut out) } == S_OK && !out.is_null() {
358        Some(out)
359    } else {
360        None
361    }
362}
363
364/// Calls the method at `slot` on `iface`, passing one `u32`, returning its HRESULT.
365unsafe fn call_slot_u32(iface: *mut c_void, slot: usize, arg: u32) -> Hresult {
366    let vtable = unsafe { *(iface as *const *const *const c_void) };
367    let f: unsafe extern "C" fn(*mut c_void, u32) -> Hresult =
368        unsafe { std::mem::transmute(*vtable.add(slot)) };
369    unsafe { f(iface, arg) }
370}
371
372/// The raw function pointer at a vtable `slot` on `iface`.
373unsafe fn slot(iface: *mut c_void, slot: usize) -> *const c_void {
374    let vtable = unsafe { *(iface as *const *const *const c_void) };
375    unsafe { *vtable.add(slot) }
376}
377
378/// `ICorProfilerInfo::GetModuleInfo`, returning just the module name.
379unsafe fn get_module_name(info: *mut c_void, module_id: usize) -> Option<String> {
380    if info.is_null() {
381        return None;
382    }
383    type Fn = unsafe extern "C" fn(
384        *mut c_void,
385        usize,            // moduleId
386        *mut *const u8,   // ppBaseLoadAddress
387        u32,              // cchName
388        *mut u32,         // pcchName
389        *mut u16,         // szName[]
390        *mut usize,       // pAssemblyId
391    ) -> Hresult;
392    let f: Fn = unsafe { std::mem::transmute(slot(info, SLOT_GET_MODULE_INFO)) };
393    let mut base = std::ptr::null();
394    let mut needed = 0u32;
395    let mut assembly = 0usize;
396    // First call learns the name length.
397    unsafe {
398        f(info, module_id, &mut base, 0, &mut needed, std::ptr::null_mut(), &mut assembly);
399    }
400    if needed == 0 {
401        return None;
402    }
403    let mut buf = vec![0u16; needed as usize];
404    let hr = unsafe {
405        f(info, module_id, &mut base, needed, &mut needed, buf.as_mut_ptr(), &mut assembly)
406    };
407    if hr != S_OK {
408        return None;
409    }
410    let end = buf.iter().position(|&c| c == 0).unwrap_or(buf.len());
411    Some(String::from_utf16_lossy(&buf[..end]))
412}
413
414/// `ICorProfilerInfo::GetFunctionInfo`, returning `(moduleId, metadata token)`.
415unsafe fn get_function_info(info: *mut c_void, function_id: usize) -> Option<(usize, u32)> {
416    if info.is_null() {
417        return None;
418    }
419    type Fn = unsafe extern "C" fn(*mut c_void, usize, *mut usize, *mut usize, *mut u32) -> Hresult;
420    let f: Fn = unsafe { std::mem::transmute(slot(info, SLOT_GET_FUNCTION_INFO)) };
421    let (mut class_id, mut module_id, mut token) = (0usize, 0usize, 0u32);
422    if unsafe { f(info, function_id, &mut class_id, &mut module_id, &mut token) } == S_OK {
423        Some((module_id, token))
424    } else {
425        None
426    }
427}
428
429/// `ICorProfilerInfo::GetFunctionFromToken`, resolving a `FunctionID`.
430unsafe fn get_function_from_token(info: *mut c_void, module_id: usize, token: u32) -> Option<usize> {
431    if info.is_null() {
432        return None;
433    }
434    type Fn = unsafe extern "C" fn(*mut c_void, usize, u32, *mut usize) -> Hresult;
435    let f: Fn = unsafe { std::mem::transmute(slot(info, SLOT_GET_FUNCTION_FROM_TOKEN)) };
436    let mut function_id = 0usize;
437    if unsafe { f(info, module_id, token, &mut function_id) } == S_OK && function_id != 0 {
438        Some(function_id)
439    } else {
440        None
441    }
442}
443
444/// `ICorProfilerInfo2::GetCodeInfo2`, returning the first native code block.
445unsafe fn get_code_info(info: *mut c_void, function_id: usize) -> Option<CodeInfo> {
446    if info.is_null() {
447        return None;
448    }
449    type Fn = unsafe extern "C" fn(*mut c_void, usize, u32, *mut u32, *mut CodeInfo) -> Hresult;
450    let f: Fn = unsafe { std::mem::transmute(slot(info, SLOT_GET_CODE_INFO2)) };
451    let mut count = 0u32;
452    let mut block = CodeInfo::default();
453    if unsafe { f(info, function_id, 1, &mut count, &mut block) } == S_OK && count > 0 {
454        Some(block)
455    } else {
456        None
457    }
458}
459
460/// The native code address and size of a method, for patching it in place (for
461/// example with `iced`). `module_substring` matches a loaded module's name, and
462/// `token` is the method's metadata token (`mdMethodDef`). Returns `None` until
463/// the method has been JIT-compiled.
464///
465/// Available once the profiler is initialised; the method must belong to an
466/// already-loaded module.
467pub fn native_code(module_substring: &str, token: u32) -> Option<(usize, usize)> {
468    let info = INFO.load(Ordering::SeqCst);
469    if info.is_null() {
470        return None;
471    }
472    let module_id = *MODULES
473        .lock()
474        .unwrap_or_else(|e| e.into_inner())
475        .as_ref()?
476        .iter()
477        .find(|(_, name)| name.contains(module_substring))
478        .map(|(id, _)| id)?;
479    let function_id = unsafe { get_function_from_token(info, module_id, token) }?;
480    let code = unsafe { get_code_info(info, function_id) }?;
481    Some((code.start, code.size))
482}