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