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