Skip to main content

hao_runtime/
jit.rs

1//! CoreCLR JIT helpers — resolve precode indirections and call JIT'd methods.
2//!
3//! CoreCLR compiles methods lazily. Before a method is JIT'd, calls go through
4//! a *precode* stub that triggers compilation and then patches itself to jump
5//! directly to the native code. The two common precode forms on x86-64 are:
6//!
7//! - **`ff 25 <disp32>`** — indirect jump through a pointer slot
8//! - **`e9 <disp32>`** — relative jump to the JIT'd body
9//!
10//! [`resolve_jit`] follows one level of indirection so you get the actual
11//! native address, and [`patch_precode_target`] rewrites the indirect-jump
12//! slot to redirect a method.
13//!
14//! [`call_native`] and [`call_native_float`] are small trampolines that call a
15//! native function pointer with up to 6 integer arguments, used by script
16//! runtimes to invoke managed methods generically.
17
18use std::fmt;
19
20/// Errors returned by JIT helpers.
21#[derive(Debug)]
22pub enum JitError {
23    NotAPrecode,
24}
25
26impl fmt::Display for JitError {
27    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
28        match self {
29            JitError::NotAPrecode => write!(f, "not a precode (expected ff 25)"),
30        }
31    }
32}
33
34impl std::error::Error for JitError {}
35
36/// Follow one level of CoreCLR precode indirection.
37///
38/// Given a method's precode address, returns the address it currently points
39/// to — either the JIT'd native body or the prestub. If the address is not a
40/// recognised precode form, returns the input unchanged.
41///
42/// # Safety
43///
44/// `addr` must point to readable memory containing a valid precode or native
45/// code. The caller must ensure the memory remains mapped.
46#[cfg(target_arch = "x86_64")]
47pub unsafe fn resolve_jit(addr: usize) -> usize {
48    let p = addr as *const u8;
49    let b0 = unsafe { *p };
50    let b1 = unsafe { *p.add(1) };
51    if b0 == 0xff && b1 == 0x25 {
52        let disp = unsafe { std::ptr::read_unaligned(p.add(2) as *const i32) };
53        let slot = unsafe { p.add(6).offset(disp as isize) as *const usize };
54        unsafe { *slot }
55    } else if b0 == 0xe9 {
56        let disp = unsafe { std::ptr::read_unaligned(p.add(1) as *const i32) };
57        unsafe { p.add(5).offset(disp as isize) as usize }
58    } else {
59        addr
60    }
61}
62
63/// Rewrite a `ff 25` precode's target pointer to redirect the method.
64///
65/// # Safety
66///
67/// `precode_addr` must point to an `ff 25 <disp32>` instruction whose
68/// pointer slot is writable (or has been made writable).
69#[cfg(target_arch = "x86_64")]
70pub unsafe fn patch_precode_target(precode_addr: usize, new_target: usize) -> Result<(), JitError> {
71    let p = precode_addr as *const u8;
72    let b0 = unsafe { *p };
73    let b1 = unsafe { *p.add(1) };
74    if b0 == 0xff && b1 == 0x25 {
75        let disp = unsafe { std::ptr::read_unaligned(p.add(2) as *const i32) };
76        let slot = unsafe { p.add(6).offset(disp as isize) as *mut usize };
77        unsafe { *slot = new_target };
78        Ok(())
79    } else {
80        Err(JitError::NotAPrecode)
81    }
82}
83
84/// Read `count` bytes starting at `addr` as a hex string, capped at 64.
85///
86/// # Safety
87///
88/// `addr` must point to at least `min(count, 64)` bytes of readable memory.
89pub unsafe fn peek_bytes(addr: usize, count: usize) -> String {
90    let n = count.min(64);
91    let bytes: Vec<u8> = (0..n).map(|i| unsafe { *((addr + i) as *const u8) }).collect();
92    let hex: Vec<String> = bytes.iter().map(|b| format!("{b:02x}")).collect();
93    hex.join(" ")
94}
95
96/// Call a native function pointer with up to 6 integer/pointer arguments.
97///
98/// This is the generic trampoline for calling managed methods through the
99/// raw pointers returned by [`Runtime::method_pointer`](crate::Runtime::method_pointer).
100///
101/// # Safety
102///
103/// `ptr` must be a valid function pointer. `args` must contain the correct
104/// number and types of arguments for the target function.
105#[cfg(target_arch = "x86_64")]
106pub unsafe fn call_native(ptr: usize, args: &[u64]) -> u64 {
107    type F0 = unsafe extern "C" fn() -> u64;
108    type F1 = unsafe extern "C" fn(u64) -> u64;
109    type F2 = unsafe extern "C" fn(u64, u64) -> u64;
110    type F3 = unsafe extern "C" fn(u64, u64, u64) -> u64;
111    type F4 = unsafe extern "C" fn(u64, u64, u64, u64) -> u64;
112    type F5 = unsafe extern "C" fn(u64, u64, u64, u64, u64) -> u64;
113    type F6 = unsafe extern "C" fn(u64, u64, u64, u64, u64, u64) -> u64;
114
115    unsafe {
116        match args.len() {
117            0 => std::mem::transmute::<usize, F0>(ptr)(),
118            1 => std::mem::transmute::<usize, F1>(ptr)(args[0]),
119            2 => std::mem::transmute::<usize, F2>(ptr)(args[0], args[1]),
120            3 => std::mem::transmute::<usize, F3>(ptr)(args[0], args[1], args[2]),
121            4 => std::mem::transmute::<usize, F4>(ptr)(args[0], args[1], args[2], args[3]),
122            5 => std::mem::transmute::<usize, F5>(ptr)(args[0], args[1], args[2], args[3], args[4]),
123            6 => std::mem::transmute::<usize, F6>(ptr)(
124                args[0], args[1], args[2], args[3], args[4], args[5],
125            ),
126            _ => panic!("too many arguments for call_native (max 6)"),
127        }
128    }
129}
130
131/// Like [`call_native`], but for methods returning a small struct of floats
132/// (up to 4 × f32) via xmm0+xmm1 on x86-64 SysV ABI.
133///
134/// # Safety
135///
136/// Same requirements as [`call_native`].
137#[cfg(target_arch = "x86_64")]
138pub unsafe fn call_native_f32x4(ptr: usize, args: &[u64]) -> [f32; 4] {
139    #[repr(C)]
140    #[derive(Copy, Clone)]
141    struct F4(f32, f32, f32, f32);
142
143    type F1 = unsafe extern "C" fn(u64) -> F4;
144
145    let r = unsafe {
146        match args.len() {
147            1 => std::mem::transmute::<usize, F1>(ptr)(args[0]),
148            _ => panic!("call_native_f32x4: only 1-arg supported"),
149        }
150    };
151    [r.0, r.1, r.2, r.3]
152}
153
154/// Like [`call_native`], but for methods returning a float (xmm0 on x86-64).
155/// Supports up to 3 integer arguments.
156///
157/// # Safety
158///
159/// Same requirements as [`call_native`].
160#[cfg(target_arch = "x86_64")]
161pub unsafe fn call_native_float(ptr: usize, args: &[u64]) -> f64 {
162    type F0 = unsafe extern "C" fn() -> f64;
163    type F1 = unsafe extern "C" fn(u64) -> f64;
164    type F2 = unsafe extern "C" fn(u64, u64) -> f64;
165    type F3 = unsafe extern "C" fn(u64, u64, u64) -> f64;
166
167    unsafe {
168        match args.len() {
169            0 => std::mem::transmute::<usize, F0>(ptr)(),
170            1 => std::mem::transmute::<usize, F1>(ptr)(args[0]),
171            2 => std::mem::transmute::<usize, F2>(ptr)(args[0], args[1]),
172            3 => std::mem::transmute::<usize, F3>(ptr)(args[0], args[1], args[2]),
173            _ => panic!("too many arguments for call_native_float (max 3)"),
174        }
175    }
176}