Skip to main content

Crate asmkit

Crate asmkit 

Source
Expand description

§asmkit

§Overview

asmkit is a portable assembler toolkit built around an AsmJit-style instruction-database model. It is a small, efficient, no_std library for encoding machine code without being tied to a specific platform. Key features include:

  • Multi-Architecture Support: x86/x64, RISC-V, and AArch64.
  • Generated emitter traits: per-mnemonic traits (e.g. MovEmitter) with impls for the sized register wrappers, so register constants and integer immediates are passed directly (asm.mov(RAX, 42)).
  • Read/write effects: query_rw_info(&Inst) -> InstRwInfo per architecture, over the architecture-tagged Inst.
  • Deferred emission: Builder allows to emit instructions lazily.
  • Minimal Dependencies:
    • libc, intrusive-collections, errno - For JIT support.
    • paste, bitflags, cfgenius, num-traits - Utility crates that simplify repetitive arch-specific declarations.
    • smallvec - Avoids frequent heap allocation during code generation.
  • Code Relocations: Provides a CodeBuffer interface to handle relocations, allowing the use of external symbols.
  • Portability: Built to run on any platform, with the architecture-specific parts of the library being independent of the platform on which asmkit is built.

§From assembly to execution

  1. Emit into a CodeBuffer through a backend Assembler.
  2. Finalize with CodeBuffer::finish, optionally combining several modules — Sections or plain buffers: into one image with Linker.
  3. Load with CodeBufferFinalized::load, which applies relocations and resolves external symbols by ExternalName, or with CodeBufferFinalized::allocate when the image has no relocations. CodeBufferFinalized::relocate_to_base does the relocation step into memory you manage yourself.
  4. Find entry points with LoadedCode::symbol / symbol_by_name.

External names are either string ExternalName::Symbols or Cranelift-style ExternalName::User namespace+index keys (extern_user / bind_symbol).

§Usage

To use the library simply import the module for the architecture you want to emit code for, e.g. use asmkit::x86::*;; this includes all the code required to generate code for that platform.

Example:

use asmkit::{Arch, CodeBuffer, Environment, JitAllocator};
use asmkit::x86::*;

let mut buf = CodeBuffer::new(Environment::new(Arch::X64));
{
let mut asm = Assembler::new(&mut buf);

// Typed sized registers and plain integer immediates.
asm.mov(RAX, 5);
asm.add(RAX, 37);
asm.ret();
}

let result = buf.finish().expect("assembly failed");
let mut jit = JitAllocator::new(Default::default());
// you can also use jit.alloc + jit.write manually.
let span = result
    .allocate(&mut jit)
    .expect("failed to allocate JIT-code");

// JIT Allocator uses dual-mapping: it allocates two pages which map to same physical space
// and you write to executable code through `span.rw()` pointer while you can execute `span.rx()`.
let f: extern "C" fn() -> u64 = unsafe { std::mem::transmute(span.rx()) };
#[cfg(all(unix, target_arch = "x86_64"))] // can run only on x64 and on SystemV platforms.
assert_eq!(f(), 42);

Modules§

aarch64
riscv
x86
X86 Assembler.

Structs§

AsmReloc
A relocation resulting from emitting assembly.
BaseMem
BaseReg
Builder
Records instructions and label-bind points for deferred emission.
CodeBuffer
A buffer of output to be produced, fixed up, and then emitted to a CodeSink in bulk.
CodeBufferFinalized
A CodeBuffer once emission is completed: holds generated code and records, without fixups. This allows the type to be independent of the backend.
CodeLocationData
Where a DataLabel is in a finished image.
CodeLocationJump
Where a PatchableJump is in a finished image.
CodeLocationRegion
Where a PatchableRegion is in a finished image.
Constant
A use of a constant by one or mroe assembly instructions.
CpuRwFlags
CPU read/write flags used by InstRwInfo.
DataLabel
A patchable immediate: a fixed-size mov immediate on x86, a movz/movk sequence on AArch64, or a literal on RISC-V.
Environment
FinalizedSection
A section whose buffer has been finalized, ready for linking.
Imm
Inst
A generic instruction: id + options + extra register + inline operand array.
InstOptions
InstRwFlags
Flags used by InstRwInfo.
InstRwInfo
Read/write information of an instruction.
JitAllocator
A simple implementation of memory manager that uses [virtual_memory]. functions to manage virtual memory for JIT compiled code.
JitAllocatorOptions
Label
Linker
Links finalized sections and buffers into one in-memory image.
LoadedCode
Executable memory holding a relocated image, returned by CodeBufferFinalized::load.
OpRwFlags
Operand read/write flags describe how the operand is accessed and additional features.
OpRwInfo
Read/write information related to a single operand, used by InstRwInfo.
Operand
Base struct representing an operand in asmkit.
OperandSignature
PatchableJump
A jump or call emitted with a fixed-size displacement whose target can be changed after finalization.
PatchableRegion
A nop-filled code region reserved for later rewriting.
Section
A named section: its own code buffer plus an alignment requirement.
Span
A region of executable memory returned by JitAllocator::alloc.
Sym
UserExternalName
An external name in a user-defined symbol table.

Enums§

AArch64Feature
AArch64 architectural features present in the pinned AsmJit ISA metadata.
Arch
Instruction set architecture (ISA).
AsmError
Error type shared by all backends and the core code-management machinery.
CondCode
ConstantData
ExternalName
Name of an external (or exported) symbol.
ImmType
InstControlFlow
Instruction control flow.
InstSameRegHint
Hint used when two or more operands of an instruction are the same register.
LabelUse
LinkError
Context for an in-memory image-link failure.
Node
A node recorded by a Builder.
OperandType
Operand type used by Operand
RegGroup
RegType
Register type.
Reloc
Relocation kinds for every ISA
RelocDistance
RelocTarget
ResetPolicy
A policy that can be used with reset() functions.
RiscVFeature
RISC-V extension identifiers from the pinned riscv-opcodes input files.
X86Error
Detailed x86/x64 encoding error, wrapped by AsmError::X86.
X86Feature
X86 CPU feature identifiers.

Constants§

INVALID_PHYS_ID
Physical register id used when an operand is not tied to any specific physical register.

Traits§

InstSink
Sink that consumes replayed nodes: implemented by each architecture’s Assembler.
OperandCast
A helper trait to help cast Operand to Architecture dependent operands and vice-versa.
PatchMark
A mark that CodeBufferFinalized::location_of turns into a location.
RegTraits

Functions§

imm
read_value
Reads back the immediate at data.
read_value_span⚠
Reads back the immediate at data in loaded code.
repatch_jump
Points jump at target, an offset in the same image.
repatch_jump_span⚠
Points jump in loaded code at the absolute address target.
repatch_jump_span_mt_safe⚠
Points jump in loaded code at the absolute address target while other threads may execute it: one aligned 4-byte store plus a targeted icache flush (based on NativeCall::set_destination_mt_safe in HotSpot). Only 4-byte displacement fields are supported.
repatch_value
Writes value into the immediate at data. Fails with AsmError::TooLarge when value does not fit the field.
repatch_value_span⚠
Writes value into the immediate at data in loaded code.
rewrite_region
Overwrites region with new_bytes, padding the rest with nops.
rewrite_region_span⚠
Overwrites region in loaded code with new_bytes, padding the rest with nops.

Type Aliases§

Addend
Addend to add to the symbol value.
CodeOffset
Offset in bytes from the beginning of the function.
RegMask
Register mask is a convenience typedef that describes a mask where each bit describes a physical register id in the same RegGroup. At the moment 32 bits are enough as asmkit doesn’t support any architecture that would provide more than 32 registers for a register group.