add/
add.rs

1// SPDX-License-Identifier: MIT
2//
3// Copyright (c) 2023, Johannes Stoelp <dev@memzero.de>
4
5//! Add example.
6//!
7//! Jit compile a function at runtime (generate native host code) which calls a function defined in
8//! the example based on the SystemV abi to demonstrate the [`juicebox_asm`] crate.
9
10#[cfg(not(any(target_arch = "x86_64", target_os = "linux")))]
11compile_error!("Only supported on x86_64 with SystemV abi");
12
13use juicebox_asm::insn::*;
14use juicebox_asm::Runtime;
15use juicebox_asm::{Asm, Imm64, Reg64::*};
16
17extern "C" fn add(a: u32, b: u32) -> u32 {
18    a + b
19}
20
21fn main() {
22    let mut asm = Asm::new();
23
24    // SystemV abi:
25    //   rdi -> first argument
26    //   rsi -> second argument
27    //   rax -> return value
28
29    asm.mov(rsi, Imm64::from(42));
30    asm.mov(rax, Imm64::from(add as usize));
31    asm.call(rax);
32    asm.ret();
33
34    let mut rt = Runtime::new();
35    let add42 = unsafe { rt.add_code::<extern "C" fn(u32) -> u32>(asm.into_code()) };
36
37    // Disassemble JIT code and write to stdout.
38    rt.disasm();
39
40    let res = add42(5);
41    assert_eq!(res, 47);
42}