Skip to main content

Crate onlineasm

Crate onlineasm 

Source
Expand description

onlineasm: a minimal, portable runtime assembler.

use onlineasm::{onlineasm, Assembler, JitAllocator, Target};

let mut asm = Assembler::native();

let (arg0, arg1) = match asm.target() {
    Target::X64 => (onlineasm::regs::t6, onlineasm::regs::t1),
    Target::AArch64 | Target::RISCV64 => (onlineasm::regs::t0, onlineasm::regs::t1),
};
onlineasm!(asm;
    =>add;
    move t0, {arg0};
    addq t0, {arg1};
    ret;
);
let code = asm.finish()?;
let entry = code.offset(add).ok_or("add is unbound")?;
let mut jit = JitAllocator::new(Default::default());
let span = code.allocate(&mut jit)?;
let f: extern "C" fn(u64, u64) -> u64 =
    unsafe { std::mem::transmute(span.rx().add(entry as usize)) };
assert_eq!(f(40, 2), 42);

§Backward assembly

BackwardAssembler records all calls to assembler, onlineasm!() invocations, and then replays them in reverse order at finish, so last emitted instruction executes first:

use onlineasm::{onlineasm, BackwardAssembler, JitAllocator};

let mut asm = BackwardAssembler::native_backward();
onlineasm!(asm;
    ret;
    addq t0, 41;
    move t0, 1;
);
let code = asm.finish()?;
let mut jit = JitAllocator::new(Default::default());
let span = code.allocate(&mut jit)?;
let f: extern "C" fn() -> u64 = unsafe { std::mem::transmute(span.rx()) };
assert_eq!(f(), 42);

§Reusing an assembler

Assembler::finish leaves the assembler ready for the next image (it clears the code buffer but keeps its allocations), so a JIT that compiles many small functions can build them through one assembler:

use onlineasm::{onlineasm, Assembler, JitAllocator};

let mut asm = Assembler::native();
let mut jit = JitAllocator::new(Default::default());
for value in [41u64, 42] {
    onlineasm!(asm;
        =>entry;
        move t0, {value};
        ret;
    );
    let code = asm.finish()?;
    let entry = code.offset(entry).ok_or("entry is unbound")?;
    let span = code.allocate(&mut jit)?;
    let f: extern "C" fn() -> u64 =
        unsafe { std::mem::transmute(span.rx().add(entry as usize)) };
    assert_eq!(f(), value);
}

Assembler::reset discards a partially assembled image instead of finalizing it. Handles from a finished or discarded image stay valid through Finished, but must not be used to emit further code; label and virtual-patch handles from an earlier image are rejected by the next one.

§External symbols

Generated code references host functions and data by ExternalName and resolves them when the code is loaded:

ⓘ
let helper = ExternalName::user(0, 3);
onlineasm!(asm;
    call extern {helper.clone()};
);
let code = asm.finish()?.load(&mut jit, |name| {
    if *name == helper { helper_fn as *const u8 } else { std::ptr::null() }
})?;

A far extern (Assembler::extern_far, extern in the macro) is reached through an address table placed after the code, so it can be anywhere, and LoadedCode::rebind binds it later. A near extern (Assembler::extern_near, extern near) is a direct PC-relative reference and must be within the instruction’s range of the code (x86-64 and RISC-V 64: +/-2 GiB; AArch64 bl/b: +/-128 MiB, adrp: +/-4 GiB); loading fails otherwise.

§Patching emitted code

A #[patch = name] instruction in onlineasm! (or Assembler::emit_patched) emits through a patchable site and binds its PatchHandle to name. After finish, Finished::location turns the handle into a PatchLocation: either a jump, retargeted with asmkit::repatch_jump_span, or a 64-bit immediate, rewritten with repatch_u64. Jumps and calls with an absolute (non-label) target use #[patch_abs = name] instead, which reserves a 64-bit address slot and branches to it indirectly. See Assembler::emit_patched for the patchable instructions, and the patch example (cargo run -p onlineasm --example patch) for all three flows.

§Instruction reference

See crate::reference.

Re-exports§

pub use asmkit;

Modules§

mnem
reference
regs
Maps portable register names to per-target physical registers.

Macros§

onlineasm
Emits runtime assembly using offlineasm mnemonics.

Structs§

Assembler
Runtime assembler for onlineasm.
AssemblerOptions
Configuration options for Assembler.
CodeLocationData
Where a DataLabel is in a finished image.
CodeLocationJump
Where a PatchableJump is in a finished image.
DataLabel
A patchable immediate: a fixed-size mov immediate on x86, a movz/movk sequence on AArch64, or a literal on RISC-V.
Extern
Refers to an external symbol.
Finished
A finalized machine-code image plus the offsets of the labels.
Fpr
Names a floating-point or vector register by its architecture physical number.
Gpr
Names a general-purpose register by its architecture physical number.
JitAllocator
A simple implementation of memory manager that uses [virtual_memory]. functions to manage virtual memory for JIT compiled code.
JitAllocatorOptions
Label
Identifies a code label with a frontend-owned handle.
LoadedCode
Executable memory holding a relocated image, returned by CodeBufferFinalized::load.
Mem
Holds a resolved machine address: disp(base, index, scale). Every backend lowers this. RISC backends synthesize the index/scale part with the expansion scratch registers.
PatchableJump
A jump or call emitted with a fixed-size displacement whose target can be changed after finalization.
RegInfo
Pairs a portable register name with its class.
Scratch
Supplies the scratch registers an expansion may use.
SymId
Identifies a symbolic operand with a frontend-owned handle.
UserExternalName
An external name in a user-defined symbol table.
VReg
Identifies a portable register by class and vreg id.

Enums§

Abi
Calling convention to use during code generation.
BackwardFinishError
Failure to replay a backward assembler’s tape at finish.
Disp
Holds a memory displacement: a folded constant, a frontend-owned symbol, or the address of a code label.
ExternalName
Name of an external (or exported) symbol.
LowerError
Lowering failure from the shared expansion. Reports a mnemonic expansion failure.
Mnemonic
Names one operation shared by one or more mnemonic spellings.
Op
Holds one operand of a mnemonic invocation.
PatchHandle
Mark for one #[patch] site in the emitted code.
PatchLocation
Where a PatchHandle is in a Finished image.
Reach
Says how generated code reaches an external symbol.
RegKind
Names a portable register class.
ResetPolicy
A policy that can be used with reset() functions.
Target
Target for the assembler.

Constants§

SUPPORTED_MNEMONICS
Lists every mnemonic spelling both assemblers accept, in reference order.

Traits§

IntoOperand
Converts a Rust value into an assembler operand.

Functions§

repatch_u64⚠
Writes value into the immediate at location in loaded code.

Type Aliases§

BackwardAssembler
An Assembler that replays recorded calls in reverse at finish, so the last emitted instruction executes first.
ForwardAssembler
An Assembler that lowers each call in program order.