use onlineasm::{onlineasm, Assembler, JitAllocator, PatchLocation, Target};
fn patched_constant() -> Result<(), Box<dyn std::error::Error>> {
let mut asm = Assembler::native();
onlineasm!(asm;
#[patch = slot] move t0, 0;
ret;
);
let code = asm.finish()?;
let location = code.location(slot).ok_or("slot is unbound")?;
assert!(matches!(location, PatchLocation::Data(_)));
let mut jit = JitAllocator::new(Default::default());
let mut span = code.allocate(&mut jit)?;
unsafe { onlineasm::repatch_u64(&mut jit, &mut span, &location, 42)? };
let f: extern "C" fn() -> u64 = unsafe { std::mem::transmute(span.rx()) };
assert_eq!(f(), 42);
unsafe { onlineasm::repatch_u64(&mut jit, &mut span, &location, 7)? };
assert_eq!(f(), 7);
println!("patched `move` immediate: 42, then 7");
Ok(())
}
fn retargeted_jump() -> Result<(), Box<dyn std::error::Error>> {
let mut asm = Assembler::native();
onlineasm!(asm;
#[patch = j] jmp .slow;
=>fast;
move t0, 2;
ret;
.slow:
move t0, 1;
ret;
);
let code = asm.finish()?;
let PatchLocation::Jump(jump) = code.location(j).ok_or("jump is unbound")? else {
panic!("a patched `jmp` is a jump, not an immediate");
};
let fast = code.offset(fast).ok_or("fast is unbound")?;
let mut jit = JitAllocator::new(Default::default());
let mut span = code.allocate(&mut jit)?;
let f: extern "C" fn() -> u64 = unsafe { std::mem::transmute(span.rx()) };
assert_eq!(f(), 1);
let target = unsafe { span.rx().add(fast as usize) };
unsafe { onlineasm::asmkit::repatch_jump_span(&mut jit, &mut span, jump, target)? };
assert_eq!(f(), 2);
println!("retargeted `jmp`: 1, then 2");
Ok(())
}
fn absolute_call() -> Result<(), Box<dyn std::error::Error>> {
extern "C" fn helper() -> u64 {
99
}
let mut asm = Assembler::native();
let frame: i32 = if asm.target() == Target::X64 { 8 } else { 16 };
onlineasm!(asm;
subp sp, {frame};
);
if asm.target() != Target::X64 {
onlineasm!(asm; storeq [sp], lr;);
}
onlineasm!(asm;
#[patch_abs = callee] call {0i64};
);
if asm.target() != Target::X64 {
onlineasm!(asm; loadq lr, [sp];);
}
onlineasm!(asm;
addp sp, {frame};
ret;
);
let code = asm.finish()?;
let location = code.location(callee).ok_or("callee is unbound")?;
assert!(matches!(location, PatchLocation::Data(_)));
let mut jit = JitAllocator::new(Default::default());
let mut span = code.allocate(&mut jit)?;
unsafe {
onlineasm::repatch_u64(&mut jit, &mut span, &location, helper as *const () as u64)?;
}
let f: extern "C" fn() -> u64 = unsafe { std::mem::transmute(span.rx()) };
assert_eq!(f(), 99);
println!("`#[patch_abs]` call: 99");
Ok(())
}
fn main() -> Result<(), Box<dyn std::error::Error>> {
patched_constant()?;
retargeted_jump()?;
absolute_call()?;
println!("ok");
Ok(())
}