hao-runtime 0.0.13

Host the .net runtime (CoreCLR or Mono) in a rust process
Documentation
//! CoreCLR JIT helpers — resolve precode indirections and call JIT'd methods.
//!
//! CoreCLR compiles methods lazily. Before a method is JIT'd, calls go through
//! a *precode* stub that triggers compilation and then patches itself to jump
//! directly to the native code. The two common precode forms on x86-64 are:
//!
//! - **`ff 25 <disp32>`** — indirect jump through a pointer slot
//! - **`e9 <disp32>`** — relative jump to the JIT'd body
//!
//! [`resolve_jit`] follows one level of indirection so you get the actual
//! native address, and [`patch_precode_target`] rewrites the indirect-jump
//! slot to redirect a method. Both decode the instruction with iced-x86 rather
//! than matching raw opcode bytes.
//!
//! With tiered compilation a not-yet-promoted method's precode points at a
//! *CallCountingStub* (a call counter) rather than the body; [`resolve_jit_body`]
//! sees through that stub to the method's current native code.
//!
//! [`call_native`] and [`call_native_float`] are small trampolines that call a
//! native function pointer with up to 6 integer arguments, used by script
//! runtimes to invoke managed methods generically.

use std::fmt;

#[cfg(target_arch = "x86_64")]
use iced_x86::{Decoder, DecoderOptions, Instruction, Mnemonic, OpKind};

/// Errors returned by JIT helpers.
#[derive(Debug)]
pub enum JitError {
    NotAPrecode,
}

impl fmt::Display for JitError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            JitError::NotAPrecode => write!(f, "not a precode (expected ff 25)"),
        }
    }
}

impl std::error::Error for JitError {}

/// Follow one level of CoreCLR precode indirection.
///
/// Given a method's precode address, returns the address it currently points
/// to — either the JIT'd native body or the prestub. A `jmp qword ptr [slot]`
/// returns the pointer stored in `slot`; a `jmp rel32` returns its target. If
/// the address is not a jump, returns the input unchanged.
///
/// # Safety
///
/// `addr` must point to at least 16 bytes (one x86 instruction) of readable
/// memory containing a valid precode or native code, mapped for the call.
#[cfg(target_arch = "x86_64")]
pub unsafe fn resolve_jit(addr: usize) -> usize {
    let Some(insn) = (unsafe { decode_at(addr) }) else {
        return addr;
    };
    if insn.mnemonic() == Mnemonic::Jmp {
        if let Some(slot) = indirect_jmp_slot(&insn) {
            // `jmp qword ptr [slot]` — the pointer the precode currently targets.
            return unsafe { *(slot as *const usize) };
        }
        if insn.op0_kind() == OpKind::NearBranch64 {
            // `jmp rel32` — a direct branch to the JIT'd body.
            return insn.near_branch_target() as usize;
        }
    }
    addr
}

/// Rewrite an indirect-jump precode's target pointer to redirect the method.
///
/// # Safety
///
/// `precode_addr` must point to a `jmp qword ptr [slot]` instruction whose
/// pointer slot is writable (or has been made writable), with at least 16
/// readable bytes at the instruction.
#[cfg(target_arch = "x86_64")]
pub unsafe fn patch_precode_target(precode_addr: usize, new_target: usize) -> Result<(), JitError> {
    let insn = unsafe { decode_at(precode_addr) }.ok_or(JitError::NotAPrecode)?;
    match indirect_jmp_slot(&insn) {
        Some(slot) => {
            unsafe { *(slot as *mut usize) = new_target };
            Ok(())
        }
        None => Err(JitError::NotAPrecode),
    }
}

/// Decode the single instruction at `addr`, reading a 16-byte window (the
/// maximum x86 instruction length). `None` if the bytes don't decode.
///
/// # Safety
///
/// `addr` must point to at least 16 bytes of readable memory.
#[cfg(target_arch = "x86_64")]
unsafe fn decode_at(addr: usize) -> Option<Instruction> {
    let code = unsafe { std::slice::from_raw_parts(addr as *const u8, 16) };
    let mut decoder = Decoder::with_ip(64, code, addr as u64, DecoderOptions::NONE);
    let insn = decoder.decode();
    (!insn.is_invalid()).then_some(insn)
}

/// The absolute address of the pointer slot a `jmp qword ptr [mem]` reads
/// through, or `None` if `insn` is not an indirect memory jump.
#[cfg(target_arch = "x86_64")]
fn indirect_jmp_slot(insn: &Instruction) -> Option<usize> {
    if insn.mnemonic() != Mnemonic::Jmp || insn.op0_kind() != OpKind::Memory {
        return None;
    }
    let cell = if insn.is_ip_rel_memory_operand() {
        insn.ip_rel_memory_address()
    } else {
        insn.memory_displacement64()
    };
    Some(cell as usize)
}

/// If `addr` is a CoreCLR tiered-compilation CallCountingStub, returns the
/// method's current native body (the target of its `jmp qword ptr [cell]`);
/// otherwise returns `addr`. The stub decrements a call counter and, until it
/// trips, jumps to the real code:
///
/// ```text
/// mov rax, [counter_cell]
/// dec word ptr [rax]          <- fingerprint
/// je  <promote>
/// jmp qword ptr [target_cell] <- *target_cell = current body
/// ```
///
/// Requiring the `dec [mem]` before following the `jmp [mem]` keeps a real
/// method body's indirect jump from being mistaken for a stub.
///
/// # Safety
///
/// `addr` must point to readable code (at least the stub's length).
#[cfg(target_arch = "x86_64")]
unsafe fn follow_call_counting_stub(addr: usize) -> usize {
    let code = unsafe { std::slice::from_raw_parts(addr as *const u8, 32) };
    let mut decoder = Decoder::with_ip(64, code, addr as u64, DecoderOptions::NONE);
    let mut saw_counter_dec = false;
    let mut insn = Instruction::default();
    while decoder.can_decode() {
        decoder.decode_out(&mut insn);
        if insn.is_invalid() {
            break;
        }
        match insn.mnemonic() {
            // `dec word ptr [rax]` — the call-counter decrement, the fingerprint.
            Mnemonic::Dec if insn.op0_kind() == OpKind::Memory => saw_counter_dec = true,
            // `jmp qword ptr [cell]` after the counter — dispatches to the body.
            Mnemonic::Jmp if saw_counter_dec => {
                if let Some(slot) = indirect_jmp_slot(&insn) {
                    let body = unsafe { *(slot as *const usize) };
                    if body != 0 {
                        return body;
                    }
                }
                break;
            }
            // A control-flow transfer before the counter: not a counting stub.
            Mnemonic::Jmp | Mnemonic::Ret | Mnemonic::Call => break,
            _ => {}
        }
    }
    addr
}

/// Like [`resolve_jit`], but additionally sees through a CoreCLR tiered-
/// compilation CallCountingStub to the method's current native body. Use this
/// to get real code to hook; use [`resolve_jit`] for the raw one-level precode
/// target.
///
/// # Safety
///
/// Same as [`resolve_jit`]; `addr` and any stub it points to must be readable.
#[cfg(target_arch = "x86_64")]
pub unsafe fn resolve_jit_body(addr: usize) -> usize {
    unsafe { follow_call_counting_stub(resolve_jit(addr)) }
}

/// Read `count` bytes starting at `addr` as a hex string, capped at 64.
///
/// # Safety
///
/// `addr` must point to at least `min(count, 64)` bytes of readable memory.
pub unsafe fn peek_bytes(addr: usize, count: usize) -> String {
    let n = count.min(64);
    let bytes: Vec<u8> = (0..n)
        .map(|i| unsafe { *((addr + i) as *const u8) })
        .collect();
    let hex: Vec<String> = bytes.iter().map(|b| format!("{b:02x}")).collect();
    hex.join(" ")
}

/// Call a native function pointer with up to 6 integer/pointer arguments.
///
/// This is the generic trampoline for calling managed methods through the
/// raw pointers returned by [`Runtime::method_pointer`](crate::Runtime::method_pointer).
///
/// # Safety
///
/// `ptr` must be a valid function pointer. `args` must contain the correct
/// number and types of arguments for the target function.
#[cfg(target_arch = "x86_64")]
pub unsafe fn call_native(ptr: usize, args: &[u64]) -> u64 {
    type F0 = unsafe extern "C" fn() -> u64;
    type F1 = unsafe extern "C" fn(u64) -> u64;
    type F2 = unsafe extern "C" fn(u64, u64) -> u64;
    type F3 = unsafe extern "C" fn(u64, u64, u64) -> u64;
    type F4 = unsafe extern "C" fn(u64, u64, u64, u64) -> u64;
    type F5 = unsafe extern "C" fn(u64, u64, u64, u64, u64) -> u64;
    type F6 = unsafe extern "C" fn(u64, u64, u64, u64, u64, u64) -> u64;

    unsafe {
        match args.len() {
            0 => std::mem::transmute::<usize, F0>(ptr)(),
            1 => std::mem::transmute::<usize, F1>(ptr)(args[0]),
            2 => std::mem::transmute::<usize, F2>(ptr)(args[0], args[1]),
            3 => std::mem::transmute::<usize, F3>(ptr)(args[0], args[1], args[2]),
            4 => std::mem::transmute::<usize, F4>(ptr)(args[0], args[1], args[2], args[3]),
            5 => std::mem::transmute::<usize, F5>(ptr)(args[0], args[1], args[2], args[3], args[4]),
            6 => std::mem::transmute::<usize, F6>(ptr)(
                args[0], args[1], args[2], args[3], args[4], args[5],
            ),
            _ => panic!("too many arguments for call_native (max 6)"),
        }
    }
}

/// Like [`call_native`], but for methods returning a small struct of floats
/// (up to 4 × f32) via xmm0+xmm1 on x86-64 SysV ABI.
///
/// # Safety
///
/// Same requirements as [`call_native`].
#[cfg(target_arch = "x86_64")]
pub unsafe fn call_native_f32x4(ptr: usize, args: &[u64]) -> [f32; 4] {
    #[repr(C)]
    #[derive(Copy, Clone)]
    struct F4(f32, f32, f32, f32);

    type F1 = unsafe extern "C" fn(u64) -> F4;

    let r = unsafe {
        match args.len() {
            1 => std::mem::transmute::<usize, F1>(ptr)(args[0]),
            _ => panic!("call_native_f32x4: only 1-arg supported"),
        }
    };
    [r.0, r.1, r.2, r.3]
}

/// Like [`call_native`], but for methods returning a float (xmm0 on x86-64).
/// Supports up to 3 integer arguments.
///
/// # Safety
///
/// Same requirements as [`call_native`].
#[cfg(target_arch = "x86_64")]
pub unsafe fn call_native_float(ptr: usize, args: &[u64]) -> f64 {
    type F0 = unsafe extern "C" fn() -> f64;
    type F1 = unsafe extern "C" fn(u64) -> f64;
    type F2 = unsafe extern "C" fn(u64, u64) -> f64;
    type F3 = unsafe extern "C" fn(u64, u64, u64) -> f64;

    unsafe {
        match args.len() {
            0 => std::mem::transmute::<usize, F0>(ptr)(),
            1 => std::mem::transmute::<usize, F1>(ptr)(args[0]),
            2 => std::mem::transmute::<usize, F2>(ptr)(args[0], args[1]),
            3 => std::mem::transmute::<usize, F3>(ptr)(args[0], args[1], args[2]),
            _ => panic!("too many arguments for call_native_float (max 3)"),
        }
    }
}

#[cfg(all(test, target_arch = "x86_64"))]
mod tests {
    use super::*;

    /// A 64-byte buffer with `bytes` at the front. Its address is stable while
    /// it lives; RIP-relative displacements below are offset-based, so they do
    /// not depend on the absolute address.
    fn buf(bytes: &[u8]) -> Vec<u8> {
        let mut v = vec![0u8; 64];
        v[..bytes.len()].copy_from_slice(bytes);
        v
    }

    fn write_usize(v: &mut [u8], off: usize, val: usize) {
        v[off..off + 8].copy_from_slice(&val.to_le_bytes());
    }

    #[test]
    fn resolve_jit_ff25_derefs_slot() {
        // jmp qword ptr [rip+2]  -> slot at offset 8 (next_ip 6 + disp 2)
        let mut v = buf(&[0xff, 0x25, 0x02, 0x00, 0x00, 0x00]);
        write_usize(&mut v, 8, 0x1234_5678);
        assert_eq!(unsafe { resolve_jit(v.as_ptr() as usize) }, 0x1234_5678);
    }

    #[test]
    fn resolve_jit_e9_returns_target() {
        // jmp rel32 (+0x20): target = base + 5 + 0x20
        let v = buf(&[0xe9, 0x20, 0x00, 0x00, 0x00]);
        let base = v.as_ptr() as usize;
        assert_eq!(unsafe { resolve_jit(base) }, base + 5 + 0x20);
    }

    #[test]
    fn resolve_jit_non_jump_returns_addr() {
        // push rbp; mov rbp,rsp
        let v = buf(&[0x55, 0x48, 0x89, 0xe5]);
        let base = v.as_ptr() as usize;
        assert_eq!(unsafe { resolve_jit(base) }, base);
    }

    #[test]
    fn patch_precode_target_writes_slot() {
        let mut v = buf(&[0xff, 0x25, 0x02, 0x00, 0x00, 0x00]);
        write_usize(&mut v, 8, 0);
        let base = v.as_ptr() as usize;
        unsafe { patch_precode_target(base, 0xABCD).unwrap() };
        assert_eq!(usize::from_le_bytes(v[8..16].try_into().unwrap()), 0xABCD);
    }

    #[test]
    fn patch_precode_target_rejects_non_precode() {
        let v = buf(&[0x55, 0x48, 0x89, 0xe5]);
        let base = v.as_ptr() as usize;
        assert!(matches!(
            unsafe { patch_precode_target(base, 0x1) },
            Err(JitError::NotAPrecode)
        ));
    }

    #[test]
    fn resolve_jit_body_follows_counting_stub() {
        // mov rax,[rip+0x11]; dec word ptr [rax]; je +2; jmp qword ptr [rip+0x0e]
        // mov(0..7) dec(7..10) je(10..12) jmp(12..18); target cell at offset 32.
        let mut v = buf(&[
            0x48, 0x8b, 0x05, 0x11, 0x00, 0x00, 0x00, // mov rax,[rip+0x11]
            0x66, 0xff, 0x08, // dec word ptr [rax]
            0x74, 0x02, // je +2
            0xff, 0x25, 0x0e, 0x00, 0x00, 0x00, // jmp qword ptr [rip+0x0e] -> cell@32
        ]);
        write_usize(&mut v, 32, 0xDEAD_BEEF);
        let base = v.as_ptr() as usize;
        // resolve_jit alone stops at the stub; resolve_jit_body sees through it.
        assert_eq!(unsafe { resolve_jit(base) }, base);
        assert_eq!(unsafe { resolve_jit_body(base) }, 0xDEAD_BEEF);
    }

    #[test]
    fn resolve_jit_body_passthrough_on_real_body() {
        let v = buf(&[0x55, 0x48, 0x89, 0xe5]); // push rbp; mov rbp,rsp
        let base = v.as_ptr() as usize;
        assert_eq!(unsafe { resolve_jit_body(base) }, base);
    }
}