Skip to main content

Assembler

Struct Assembler 

Source
pub struct Assembler { /* private fields */ }
Expand description

Builder-pattern assembler.

§Examples

use asm_rs::{Assembler, Arch};

let mut asm = Assembler::new(Arch::X86_64);
asm.emit("push rbp").unwrap();
asm.emit("mov rbp, rsp").unwrap();
asm.emit("pop rbp").unwrap();
asm.emit("ret").unwrap();
let result = asm.finish().unwrap();
assert!(!result.is_empty());

Implementations§

Source§

impl Assembler

Source

pub fn new(arch: Arch) -> Self

Create a new assembler for the given architecture.

Source

pub fn limits(&mut self, limits: ResourceLimits) -> &mut Self

Set resource limits for defense against pathological inputs.

See ResourceLimits for the available limits and their defaults.

Source

pub fn syntax(&mut self, syntax: Syntax) -> &mut Self

Set the syntax dialect.

Currently only Syntax::Intel is supported. Attempting to emit code after selecting an unsupported dialect will return an error.

Source

pub fn optimize(&mut self, level: OptLevel) -> &mut Self

Set the optimization level.

OptLevel::Size (default) prefers shortest encodings. OptLevel::None disables encoding optimizations for predictable output. Extended peephole optimizations (zero-idiom, REX elimination) are planned.

Source

pub fn enable_listing(&mut self) -> &mut Self

Enable source annotations for listing output.

When enabled, the assembler records source text for each emitted fragment, making it available in AssemblyResult::listing(). This adds a per-statement String allocation; leave disabled (the default) when listing output is not needed.

§Examples
use asm_rs::{Assembler, Arch};

let mut asm = Assembler::new(Arch::X86_64);
asm.enable_listing();
asm.emit("nop")?;
let result = asm.finish()?;
let listing = result.listing();
assert!(listing.contains("90")); // NOP opcode in hex listing
Source

pub fn base_address(&mut self, addr: u64) -> &mut Self

Set the base virtual address for the assembly.

Source

pub fn define_external(&mut self, name: &str, addr: u64) -> &mut Self

Define an external label at a known absolute address.

§Examples
use asm_rs::{Assembler, Arch};

let mut asm = Assembler::new(Arch::X86_64);
asm.define_external("puts", 0x4000);
asm.emit("call puts")?;
let result = asm.finish()?;
assert!(!result.bytes().is_empty());
Source

pub fn define_constant(&mut self, name: &str, value: i128) -> &mut Self

Define a named constant value.

Source

pub fn emit(&mut self, source: &str) -> Result<&mut Self, AsmError>

Emit assembly source text. Can be called multiple times.

§Errors

Returns AsmError on parse or encoding errors, unsupported syntax, or if resource limits are exceeded.

Source

pub fn define_preprocessor_symbol( &mut self, name: &str, value: i128, ) -> &mut Self

Define a preprocessor symbol for conditional assembly.

Symbols defined here are available in .ifdef/.ifndef and .if defined() conditionals within assembly source.

Source

pub fn label(&mut self, name: &str) -> Result<&mut Self, AsmError>

Add a label at the current position (builder API).

§Examples
use asm_rs::{Assembler, Arch};

let mut asm = Assembler::new(Arch::X86_64);
asm.label("entry")?;
asm.emit("nop")?;
let result = asm.finish()?;
assert_eq!(result.label_address("entry"), Some(0));
§Errors

Returns AsmError::DuplicateLabel if the label was already defined, or AsmError::ResourceLimitExceeded if the label limit is reached.

Source

pub fn db(&mut self, bytes: &[u8]) -> Result<&mut Self, AsmError>

Emit raw bytes (builder API for .byte/.db).

§Errors

Returns AsmError::ResourceLimitExceeded if the output size limit would be exceeded.

Source

pub fn dw(&mut self, value: u16) -> Result<&mut Self, AsmError>

Emit a 16-bit value (builder API for .word/.dw).

§Errors

Returns AsmError::ResourceLimitExceeded if the output size limit would be exceeded.

Source

pub fn dd(&mut self, value: u32) -> Result<&mut Self, AsmError>

Emit a 32-bit value (builder API for .long/.dd).

§Errors

Returns AsmError::ResourceLimitExceeded if the output size limit would be exceeded.

Source

pub fn dq(&mut self, value: u64) -> Result<&mut Self, AsmError>

Emit a 64-bit value (builder API for .quad/.dq).

§Errors

Returns AsmError::ResourceLimitExceeded if the output size limit would be exceeded.

Source

pub fn ascii(&mut self, s: &str) -> Result<&mut Self, AsmError>

Emit a string without NUL terminator (builder API for .ascii).

§Errors

Returns AsmError::ResourceLimitExceeded if the output size limit would be exceeded.

Source

pub fn asciz(&mut self, s: &str) -> Result<&mut Self, AsmError>

Emit a NUL-terminated string (builder API for .asciz/.string).

§Errors

Returns AsmError::ResourceLimitExceeded if the output size limit would be exceeded.

Source

pub fn align(&mut self, alignment: u32) -> &mut Self

Align to a byte boundary (builder API for .align).

Uses multi-byte NOP padding for x86/x86-64 architectures.

Source

pub fn align_with_fill(&mut self, alignment: u32, fill: u8) -> &mut Self

Align to a byte boundary with explicit fill byte (builder API).

Source

pub fn org(&mut self, target: u64) -> &mut Self

Set the location counter to an absolute address (builder API for .org).

Source

pub fn org_with_fill(&mut self, target: u64, fill: u8) -> &mut Self

Set the location counter with explicit fill byte (builder API for .org).

Source

pub fn fill( &mut self, count: u32, size: u8, value: i64, ) -> Result<&mut Self, AsmError>

Emit fill bytes (builder API for .fill).

Produces count * size bytes, each size-byte unit filled with value.

§Errors

Returns AsmError::ResourceLimitExceeded if the output size limit would be exceeded.

Source

pub fn space(&mut self, n: u32) -> Result<&mut Self, AsmError>

Emit zero-filled space (builder API for .space/.skip).

§Errors

Returns AsmError::ResourceLimitExceeded if the output size limit would be exceeded.

Source

pub fn current_fragment_count(&self) -> usize

Returns the current number of fragments (instructions + data) emitted so far.

Useful for estimating output size before calling finish().

Source

pub fn encode_one(&self, source: &str) -> Result<Vec<u8>, AsmError>

Assemble a single instruction and return its raw bytes immediately, without label resolution.

This is useful for one-shot encoding when labels are not needed. The instruction is NOT added to the assembler’s internal state.

§Examples
use asm_rs::{Assembler, Arch};

let asm = Assembler::new(Arch::X86_64);
let bytes = asm.encode_one("xor eax, eax")?;
assert_eq!(bytes, [0x31, 0xC0]);
§Errors

Returns AsmError if the instruction cannot be parsed or encoded.

Source

pub fn reset(&mut self) -> &mut Self

Reset the assembler to its initial state, keeping configuration (architecture, syntax, optimization level, limits) intact.

This allows reusing the same Assembler for multiple assembly operations without reallocating configuration state.

§Examples
use asm_rs::{Assembler, Arch};

let mut asm = Assembler::new(Arch::X86_64);
asm.emit("nop")?;
asm.reset();
asm.emit("ret")?;
let result = asm.finish()?;
assert_eq!(result.bytes(), &[0xC3]); // only ret, nop was reset
Source

pub fn finish(self) -> Result<AssemblyResult, AsmError>

Finalize assembly: resolve labels, apply relocations, return result.

§Errors

Returns AsmError if label resolution fails, relocations cannot be applied, accumulated errors exist, or resource limits are exceeded.

Trait Implementations§

Source§

impl Debug for Assembler

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.