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. Both decode the instruction with iced-x86 rather
13//! than matching raw opcode bytes.
14//!
15//! With tiered compilation a not-yet-promoted method's precode points at a
16//! *CallCountingStub* (a call counter) rather than the body; [`resolve_jit_body`]
17//! sees through that stub to the method's current native code.
18//!
19//! [`call_native`] and [`call_native_float`] are small trampolines that call a
20//! native function pointer with up to 6 integer arguments, used by script
21//! runtimes to invoke managed methods generically.
22
23use std::fmt;
24
25#[cfg(target_arch = "x86_64")]
26use iced_x86::{Decoder, DecoderOptions, Instruction, Mnemonic, OpKind};
27
28/// Errors returned by JIT helpers.
29#[derive(Debug)]
30pub enum JitError {
31    NotAPrecode,
32}
33
34impl fmt::Display for JitError {
35    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
36        match self {
37            JitError::NotAPrecode => write!(f, "not a precode (expected ff 25)"),
38        }
39    }
40}
41
42impl std::error::Error for JitError {}
43
44/// Follow one level of CoreCLR precode indirection.
45///
46/// Given a method's precode address, returns the address it currently points
47/// to — either the JIT'd native body or the prestub. A `jmp qword ptr [slot]`
48/// returns the pointer stored in `slot`; a `jmp rel32` returns its target. If
49/// the address is not a jump, returns the input unchanged.
50///
51/// # Safety
52///
53/// `addr` must point to at least 16 bytes (one x86 instruction) of readable
54/// memory containing a valid precode or native code, mapped for the call.
55#[cfg(target_arch = "x86_64")]
56pub unsafe fn resolve_jit(addr: usize) -> usize {
57    let Some(insn) = (unsafe { decode_at(addr) }) else {
58        return addr;
59    };
60    if insn.mnemonic() == Mnemonic::Jmp {
61        if let Some(slot) = indirect_jmp_slot(&insn) {
62            // `jmp qword ptr [slot]` — the pointer the precode currently targets.
63            return unsafe { *(slot as *const usize) };
64        }
65        if insn.op0_kind() == OpKind::NearBranch64 {
66            // `jmp rel32` — a direct branch to the JIT'd body.
67            return insn.near_branch_target() as usize;
68        }
69    }
70    addr
71}
72
73/// Rewrite an indirect-jump precode's target pointer to redirect the method.
74///
75/// # Safety
76///
77/// `precode_addr` must point to a `jmp qword ptr [slot]` instruction whose
78/// pointer slot is writable (or has been made writable), with at least 16
79/// readable bytes at the instruction.
80#[cfg(target_arch = "x86_64")]
81pub unsafe fn patch_precode_target(precode_addr: usize, new_target: usize) -> Result<(), JitError> {
82    let insn = unsafe { decode_at(precode_addr) }.ok_or(JitError::NotAPrecode)?;
83    match indirect_jmp_slot(&insn) {
84        Some(slot) => {
85            unsafe { *(slot as *mut usize) = new_target };
86            Ok(())
87        }
88        None => Err(JitError::NotAPrecode),
89    }
90}
91
92/// Decode the single instruction at `addr`, reading a 16-byte window (the
93/// maximum x86 instruction length). `None` if the bytes don't decode.
94///
95/// # Safety
96///
97/// `addr` must point to at least 16 bytes of readable memory.
98#[cfg(target_arch = "x86_64")]
99unsafe fn decode_at(addr: usize) -> Option<Instruction> {
100    let code = unsafe { std::slice::from_raw_parts(addr as *const u8, 16) };
101    let mut decoder = Decoder::with_ip(64, code, addr as u64, DecoderOptions::NONE);
102    let insn = decoder.decode();
103    (!insn.is_invalid()).then_some(insn)
104}
105
106/// The absolute address of the pointer slot a `jmp qword ptr [mem]` reads
107/// through, or `None` if `insn` is not an indirect memory jump.
108#[cfg(target_arch = "x86_64")]
109fn indirect_jmp_slot(insn: &Instruction) -> Option<usize> {
110    if insn.mnemonic() != Mnemonic::Jmp || insn.op0_kind() != OpKind::Memory {
111        return None;
112    }
113    let cell = if insn.is_ip_rel_memory_operand() {
114        insn.ip_rel_memory_address()
115    } else {
116        insn.memory_displacement64()
117    };
118    Some(cell as usize)
119}
120
121/// If `addr` is a CoreCLR tiered-compilation CallCountingStub, returns the
122/// method's current native body (the target of its `jmp qword ptr [cell]`);
123/// otherwise returns `addr`. The stub decrements a call counter and, until it
124/// trips, jumps to the real code:
125///
126/// ```text
127/// mov rax, [counter_cell]
128/// dec word ptr [rax]          <- fingerprint
129/// je  <promote>
130/// jmp qword ptr [target_cell] <- *target_cell = current body
131/// ```
132///
133/// Requiring the `dec [mem]` before following the `jmp [mem]` keeps a real
134/// method body's indirect jump from being mistaken for a stub.
135///
136/// # Safety
137///
138/// `addr` must point to readable code (at least the stub's length).
139#[cfg(target_arch = "x86_64")]
140unsafe fn follow_call_counting_stub(addr: usize) -> usize {
141    let code = unsafe { std::slice::from_raw_parts(addr as *const u8, 32) };
142    let mut decoder = Decoder::with_ip(64, code, addr as u64, DecoderOptions::NONE);
143    let mut saw_counter_dec = false;
144    let mut insn = Instruction::default();
145    while decoder.can_decode() {
146        decoder.decode_out(&mut insn);
147        if insn.is_invalid() {
148            break;
149        }
150        match insn.mnemonic() {
151            // `dec word ptr [rax]` — the call-counter decrement, the fingerprint.
152            Mnemonic::Dec if insn.op0_kind() == OpKind::Memory => saw_counter_dec = true,
153            // `jmp qword ptr [cell]` after the counter — dispatches to the body.
154            Mnemonic::Jmp if saw_counter_dec => {
155                if let Some(slot) = indirect_jmp_slot(&insn) {
156                    let body = unsafe { *(slot as *const usize) };
157                    if body != 0 {
158                        return body;
159                    }
160                }
161                break;
162            }
163            // A control-flow transfer before the counter: not a counting stub.
164            Mnemonic::Jmp | Mnemonic::Ret | Mnemonic::Call => break,
165            _ => {}
166        }
167    }
168    addr
169}
170
171/// Like [`resolve_jit`], but additionally sees through a CoreCLR tiered-
172/// compilation CallCountingStub to the method's current native body. Use this
173/// to get real code to hook; use [`resolve_jit`] for the raw one-level precode
174/// target.
175///
176/// # Safety
177///
178/// Same as [`resolve_jit`]; `addr` and any stub it points to must be readable.
179#[cfg(target_arch = "x86_64")]
180pub unsafe fn resolve_jit_body(addr: usize) -> usize {
181    unsafe { follow_call_counting_stub(resolve_jit(addr)) }
182}
183
184/// Read `count` bytes starting at `addr` as a hex string, capped at 64.
185///
186/// # Safety
187///
188/// `addr` must point to at least `min(count, 64)` bytes of readable memory.
189pub unsafe fn peek_bytes(addr: usize, count: usize) -> String {
190    let n = count.min(64);
191    let bytes: Vec<u8> = (0..n)
192        .map(|i| unsafe { *((addr + i) as *const u8) })
193        .collect();
194    let hex: Vec<String> = bytes.iter().map(|b| format!("{b:02x}")).collect();
195    hex.join(" ")
196}
197
198/// Call a native function pointer with up to 6 integer/pointer arguments.
199///
200/// This is the generic trampoline for calling managed methods through the
201/// raw pointers returned by [`Runtime::method_pointer`](crate::Runtime::method_pointer).
202///
203/// # Safety
204///
205/// `ptr` must be a valid function pointer. `args` must contain the correct
206/// number and types of arguments for the target function.
207#[cfg(target_arch = "x86_64")]
208pub unsafe fn call_native(ptr: usize, args: &[u64]) -> u64 {
209    type F0 = unsafe extern "C" fn() -> u64;
210    type F1 = unsafe extern "C" fn(u64) -> u64;
211    type F2 = unsafe extern "C" fn(u64, u64) -> u64;
212    type F3 = unsafe extern "C" fn(u64, u64, u64) -> u64;
213    type F4 = unsafe extern "C" fn(u64, u64, u64, u64) -> u64;
214    type F5 = unsafe extern "C" fn(u64, u64, u64, u64, u64) -> u64;
215    type F6 = unsafe extern "C" fn(u64, u64, u64, u64, u64, u64) -> u64;
216
217    unsafe {
218        match args.len() {
219            0 => std::mem::transmute::<usize, F0>(ptr)(),
220            1 => std::mem::transmute::<usize, F1>(ptr)(args[0]),
221            2 => std::mem::transmute::<usize, F2>(ptr)(args[0], args[1]),
222            3 => std::mem::transmute::<usize, F3>(ptr)(args[0], args[1], args[2]),
223            4 => std::mem::transmute::<usize, F4>(ptr)(args[0], args[1], args[2], args[3]),
224            5 => std::mem::transmute::<usize, F5>(ptr)(args[0], args[1], args[2], args[3], args[4]),
225            6 => std::mem::transmute::<usize, F6>(ptr)(
226                args[0], args[1], args[2], args[3], args[4], args[5],
227            ),
228            _ => panic!("too many arguments for call_native (max 6)"),
229        }
230    }
231}
232
233/// Like [`call_native`], but for methods returning a small struct of floats
234/// (up to 4 × f32) via xmm0+xmm1 on x86-64 SysV ABI.
235///
236/// # Safety
237///
238/// Same requirements as [`call_native`].
239#[cfg(target_arch = "x86_64")]
240pub unsafe fn call_native_f32x4(ptr: usize, args: &[u64]) -> [f32; 4] {
241    #[repr(C)]
242    #[derive(Copy, Clone)]
243    struct F4(f32, f32, f32, f32);
244
245    type F1 = unsafe extern "C" fn(u64) -> F4;
246
247    let r = unsafe {
248        match args.len() {
249            1 => std::mem::transmute::<usize, F1>(ptr)(args[0]),
250            _ => panic!("call_native_f32x4: only 1-arg supported"),
251        }
252    };
253    [r.0, r.1, r.2, r.3]
254}
255
256/// Like [`call_native`], but for methods returning a float (xmm0 on x86-64).
257/// Supports up to 3 integer arguments.
258///
259/// # Safety
260///
261/// Same requirements as [`call_native`].
262#[cfg(target_arch = "x86_64")]
263pub unsafe fn call_native_float(ptr: usize, args: &[u64]) -> f64 {
264    type F0 = unsafe extern "C" fn() -> f64;
265    type F1 = unsafe extern "C" fn(u64) -> f64;
266    type F2 = unsafe extern "C" fn(u64, u64) -> f64;
267    type F3 = unsafe extern "C" fn(u64, u64, u64) -> f64;
268
269    unsafe {
270        match args.len() {
271            0 => std::mem::transmute::<usize, F0>(ptr)(),
272            1 => std::mem::transmute::<usize, F1>(ptr)(args[0]),
273            2 => std::mem::transmute::<usize, F2>(ptr)(args[0], args[1]),
274            3 => std::mem::transmute::<usize, F3>(ptr)(args[0], args[1], args[2]),
275            _ => panic!("too many arguments for call_native_float (max 3)"),
276        }
277    }
278}
279
280#[cfg(all(test, target_arch = "x86_64"))]
281mod tests {
282    use super::*;
283
284    /// A 64-byte buffer with `bytes` at the front. Its address is stable while
285    /// it lives; RIP-relative displacements below are offset-based, so they do
286    /// not depend on the absolute address.
287    fn buf(bytes: &[u8]) -> Vec<u8> {
288        let mut v = vec![0u8; 64];
289        v[..bytes.len()].copy_from_slice(bytes);
290        v
291    }
292
293    fn write_usize(v: &mut [u8], off: usize, val: usize) {
294        v[off..off + 8].copy_from_slice(&val.to_le_bytes());
295    }
296
297    #[test]
298    fn resolve_jit_ff25_derefs_slot() {
299        // jmp qword ptr [rip+2]  -> slot at offset 8 (next_ip 6 + disp 2)
300        let mut v = buf(&[0xff, 0x25, 0x02, 0x00, 0x00, 0x00]);
301        write_usize(&mut v, 8, 0x1234_5678);
302        assert_eq!(unsafe { resolve_jit(v.as_ptr() as usize) }, 0x1234_5678);
303    }
304
305    #[test]
306    fn resolve_jit_e9_returns_target() {
307        // jmp rel32 (+0x20): target = base + 5 + 0x20
308        let v = buf(&[0xe9, 0x20, 0x00, 0x00, 0x00]);
309        let base = v.as_ptr() as usize;
310        assert_eq!(unsafe { resolve_jit(base) }, base + 5 + 0x20);
311    }
312
313    #[test]
314    fn resolve_jit_non_jump_returns_addr() {
315        // push rbp; mov rbp,rsp
316        let v = buf(&[0x55, 0x48, 0x89, 0xe5]);
317        let base = v.as_ptr() as usize;
318        assert_eq!(unsafe { resolve_jit(base) }, base);
319    }
320
321    #[test]
322    fn patch_precode_target_writes_slot() {
323        let mut v = buf(&[0xff, 0x25, 0x02, 0x00, 0x00, 0x00]);
324        write_usize(&mut v, 8, 0);
325        let base = v.as_ptr() as usize;
326        unsafe { patch_precode_target(base, 0xABCD).unwrap() };
327        assert_eq!(usize::from_le_bytes(v[8..16].try_into().unwrap()), 0xABCD);
328    }
329
330    #[test]
331    fn patch_precode_target_rejects_non_precode() {
332        let v = buf(&[0x55, 0x48, 0x89, 0xe5]);
333        let base = v.as_ptr() as usize;
334        assert!(matches!(
335            unsafe { patch_precode_target(base, 0x1) },
336            Err(JitError::NotAPrecode)
337        ));
338    }
339
340    #[test]
341    fn resolve_jit_body_follows_counting_stub() {
342        // mov rax,[rip+0x11]; dec word ptr [rax]; je +2; jmp qword ptr [rip+0x0e]
343        // mov(0..7) dec(7..10) je(10..12) jmp(12..18); target cell at offset 32.
344        let mut v = buf(&[
345            0x48, 0x8b, 0x05, 0x11, 0x00, 0x00, 0x00, // mov rax,[rip+0x11]
346            0x66, 0xff, 0x08, // dec word ptr [rax]
347            0x74, 0x02, // je +2
348            0xff, 0x25, 0x0e, 0x00, 0x00, 0x00, // jmp qword ptr [rip+0x0e] -> cell@32
349        ]);
350        write_usize(&mut v, 32, 0xDEAD_BEEF);
351        let base = v.as_ptr() as usize;
352        // resolve_jit alone stops at the stub; resolve_jit_body sees through it.
353        assert_eq!(unsafe { resolve_jit(base) }, base);
354        assert_eq!(unsafe { resolve_jit_body(base) }, 0xDEAD_BEEF);
355    }
356
357    #[test]
358    fn resolve_jit_body_passthrough_on_real_body() {
359        let v = buf(&[0x55, 0x48, 0x89, 0xe5]); // push rbp; mov rbp,rsp
360        let base = v.as_ptr() as usize;
361        assert_eq!(unsafe { resolve_jit_body(base) }, base);
362    }
363}