Skip to main content

asmkit/
lib.rs

1//! # asmkit
2//!
3//! ### Overview
4//! asmkit is a portable assembler toolkit built around an AsmJit-style instruction-database
5//! model. It is a small, efficient, `no_std` library for encoding machine code without being
6//! tied to a specific platform. Key features include:
7//!
8//! - **Multi-Architecture Support**: x86/x64, RISC-V, and AArch64. Each backend follows the
9//!   same uniform model: a dense `InstId` enum backed by generated instdb tables,
10//!   and a single checked raw emit entry point.
11//! - **Generated emitter traits**: per-mnemonic traits (e.g. `MovEmitter`) with impls for
12//!   the sized register wrappers, so register constants and integer immediates are passed
13//!   directly (`asm.mov(RAX, 42)`: no dereferencing).
14//! - **Read/write effects**: `query_rw_info(&Inst) -> InstRwInfo` per architecture, over the
15//!   architecture-tagged [`Inst`].
16//! - **Deferred emission**: [`Builder`] records instructions and label binds
17//!   and replays them into any [`InstSink`] (implemented by every architecture's `Assembler`).
18//! - **Minimal Dependencies**:
19//! - - `libc`, `intrusive-collections`, `errno` - For JIT support.
20//! - - `paste`, `bitflags`, `cfgenius`, `num-traits` - Utility crates that simplify repetitive
21//!     arch-specific declarations.
22//! - - `smallvec` - Avoids frequent heap allocation during code generation.
23//! - **Code Relocations**: Provides a CodeBuffer interface to handle relocations, allowing
24//!   the insertion of symbols into the API seamlessly.
25//! - **Portability**: Built to run on any platform, with the architecture-specific parts of
26//!   the library being independent of the platform on which asmkit is built.
27//!
28//! ### From assembly to execution
29//!
30//! The API story mirrors AsmJit's (`CodeHolder` → `JitAllocator`), with
31//! [`CodeBuffer`] playing the `CodeHolder` role:
32//!
33//! 1. Emit into a [`CodeBuffer`] through a backend `Assembler`.
34//! 2. Finalize with [`CodeBuffer::finish`], optionally combining several modules —
35//!    [`Section`]s or plain buffers: into one image with [`Linker`].
36//! 3. Load with [`CodeBufferFinalized::load`], which applies relocations and
37//!    resolves external symbols by [`ExternalName`], or with
38//!    [`CodeBufferFinalized::allocate`] when the image has no relocations.
39//!    [`CodeBufferFinalized::relocate_to_base`] does the relocation step into
40//!    memory you manage yourself.
41//! 4. Find entry points with [`LoadedCode::symbol`] /
42//!    [`symbol_by_name`](LoadedCode::symbol_by_name).
43//!
44//! External names are either string [`ExternalName::Symbol`]s or Cranelift-style
45//! [`ExternalName::User`] namespace+index keys (`extern_user` / `bind_symbol`), so
46//! hosts that do not use string symbols can still link and resolve.
47//!
48//! Void mnemonic methods retain the first emission error in the [`CodeBuffer`].
49//! [`CodeBuffer::finish`] returns it, alongside finalization, linking, loading,
50//! and patching errors, as [`AsmError`].
51//!
52//! ### Usage
53//!
54//! To use the library simply import the module for the architecture you want to emit code
55//! for, e.g. `use asmkit::x86::*;`; this includes all the code required to generate code for
56//! that platform.
57//!
58//! Example:
59//!
60//! ```rust
61//! # #[cfg(all(feature = "jit", feature = "x86"))]
62//! # {
63//! use asmkit::{Arch, CodeBuffer, Environment, JitAllocator};
64//! use asmkit::x86::*;
65//!
66//! let mut buf = CodeBuffer::new(Environment::new(Arch::X64));
67//! {
68//! let mut asm = Assembler::new(&mut buf);
69//!
70//! // Typed sized registers and plain integer immediates.
71//! asm.mov(RAX, 5);
72//! asm.add(RAX, 37);
73//! asm.ret();
74//! }
75//!
76//! let result = buf.finish().expect("assembly failed");
77//! let mut jit = JitAllocator::new(Default::default());
78//! // you can also use jit.alloc + jit.write manually.
79//! let span = result
80//!     .allocate(&mut jit)
81//!     .expect("failed to allocate JIT-code");
82//!
83//! // JIT Allocator uses dual-mapping: it allocates two pages which map to same physical space
84//! // and you write to executable code through `span.rw()` pointer while you can execute `span.rx()`.
85//! let f: extern "C" fn() -> u64 = unsafe { std::mem::transmute(span.rx()) };
86//! #[cfg(all(unix, target_arch = "x86_64"))] // can run only on x64 and on SystemV platforms.
87//! assert_eq!(f(), 42);
88//! # }
89//! ```
90
91#![no_std]
92#![deny(unsafe_op_in_unsafe_fn)]
93#![warn(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
94
95extern crate alloc;
96
97#[cfg(feature = "aarch64")]
98pub mod aarch64;
99pub(crate) mod core;
100#[cfg(feature = "riscv")]
101pub mod riscv;
102#[cfg(feature = "jit")]
103pub(crate) mod util;
104#[cfg(feature = "x86")]
105pub mod x86;
106
107#[cfg(feature = "jit")]
108pub use core::buffer::LoadedCode;
109#[cfg(feature = "jit")]
110pub use core::jit_allocator::{JitAllocator, JitAllocatorOptions, ResetPolicy, Span};
111#[cfg(feature = "jit")]
112pub use core::patch::{read_value_span, repatch_jump_span, repatch_value_span, rewrite_region_span};
113#[cfg(feature = "aarch64")]
114pub use core::target::AArch64Feature;
115#[cfg(feature = "riscv")]
116pub use core::target::RiscVFeature;
117#[cfg(feature = "x86")]
118pub use core::target::X86Feature;
119pub use core::{
120    arch_traits::Arch,
121    buffer::{
122        Addend, AsmReloc, CodeBuffer, CodeBufferFinalized, CodeOffset, Constant, ConstantData,
123        ExternalName, LabelUse, Reloc, RelocDistance, RelocTarget, UserExternalName,
124    },
125    builder::{Builder, InstSink, Node},
126    globals::{CondCode, InstOptions},
127    inst::Inst,
128    linker::{LinkError, Linker},
129    operand::{
130        BaseMem, BaseReg, Imm, ImmType, Label, Operand, OperandCast, OperandSignature, OperandType,
131        RegGroup, RegMask, RegTraits, RegType, Sym, imm,
132    },
133    patch::{
134        CodeLocationData, CodeLocationJump, CodeLocationRegion, DataLabel, PatchMark,
135        PatchableJump, PatchableRegion, read_value, repatch_jump, repatch_value, rewrite_region,
136    },
137    rwinfo::{
138        CpuRwFlags, INVALID_PHYS_ID, InstControlFlow, InstRwFlags, InstRwInfo, InstSameRegHint,
139        OpRwFlags, OpRwInfo,
140    },
141    section::{FinalizedSection, Section},
142    target::Environment,
143};
144
145use ::core::fmt;
146
147/// Error type shared by all backends and the core code-management machinery.
148///
149/// The variant set follows AsmJit's `Error` codes where the same failure mode
150/// exists here; detailed context is carried by nested backend and linker
151/// errors such as [`AsmError::X86`] and [`AsmError::Link`].
152#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Debug)]
153pub enum AsmError {
154    InvalidPrefix,
155    InvalidOperand,
156    InvalidImmediate,
157    InvalidInstruction,
158    OutOfMemory,
159    InvalidState,
160    TooManyHandles,
161    InvalidArgument,
162    /// Invalid or incompatible architecture (AsmJit's `kErrorInvalidArch`).
163    InvalidArch,
164    /// No code was generated (AsmJit's `kErrorNoCodeGenerated`), e.g. linking
165    /// with no sections.
166    NoCodeGenerated,
167    /// A relocation or defined symbol references a label that was never bound
168    /// (AsmJit's unbound-label diagnostics).
169    UnboundLabel,
170    FailedToOpenAnonymousMemory,
171    TooLarge,
172    /// An in-memory image link failed; the nested error identifies the
173    /// section, symbol, or relocation involved.
174    Link(LinkError),
175    X86(X86Error),
176    /// The selected instruction requires a CPU feature disabled by the target.
177    MissingCpuFeature {
178        feature: &'static str,
179    },
180    UnsupportedInstruction {
181        reason: &'static str,
182    },
183}
184
185impl fmt::Display for AsmError {
186    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
187        match self {
188            AsmError::InvalidPrefix => write!(f, "invalid prefix"),
189            AsmError::InvalidOperand => write!(f, "invalid operand"),
190            AsmError::InvalidInstruction => write!(f, "invalid instruction"),
191            AsmError::OutOfMemory => write!(f, "out of memory"),
192            AsmError::InvalidState => write!(f, "invalid state"),
193            AsmError::TooManyHandles => write!(f, "too many handles"),
194            AsmError::InvalidArgument => write!(f, "invalid argument"),
195            AsmError::InvalidImmediate => write!(f, "invalid immediate"),
196            AsmError::InvalidArch => write!(f, "invalid or incompatible architecture"),
197            AsmError::NoCodeGenerated => write!(f, "no code generated"),
198            AsmError::UnboundLabel => write!(f, "unbound label"),
199            AsmError::FailedToOpenAnonymousMemory => {
200                write!(f, "failed to open anonymous memory")
201            }
202            AsmError::TooLarge => write!(f, "too large"),
203            AsmError::Link(error) => write!(f, "link error: {error}"),
204            AsmError::X86(e) => write!(f, "x86 error: {}", e),
205            AsmError::MissingCpuFeature { feature } => {
206                write!(f, "missing CPU feature: {}", feature)
207            }
208            AsmError::UnsupportedInstruction { reason } => {
209                write!(f, "unsupported instruction: {}", reason)
210            }
211        }
212    }
213}
214
215impl From<X86Error> for AsmError {
216    fn from(err: X86Error) -> Self {
217        AsmError::X86(err)
218    }
219}
220
221impl ::core::error::Error for AsmError {
222    fn source(&self) -> Option<&(dyn ::core::error::Error + 'static)> {
223        match self {
224            AsmError::Link(error) => Some(error),
225            AsmError::X86(error) => Some(error),
226            _ => None,
227        }
228    }
229}
230
231/// Detailed x86/x64 encoding error, wrapped by [`AsmError::X86`].
232#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Debug)]
233pub enum X86Error {
234    InvalidPrefix {
235        prefix: u64,
236        reason: &'static str,
237    },
238    InvalidOperand {
239        operand_index: usize,
240        reason: &'static str,
241    },
242    InvalidInstruction {
243        opcode: u64,
244        reason: &'static str,
245    },
246    InvalidEncoding {
247        encoding: u8,
248        reason: &'static str,
249    },
250    InvalidModRM {
251        modrm: u8,
252        reason: &'static str,
253    },
254    InvalidSIB {
255        sib: u8,
256        reason: &'static str,
257    },
258    InvalidDisplacement {
259        value: i64,
260        size: usize,
261        reason: &'static str,
262    },
263    InvalidImmediate {
264        value: i64,
265        size: usize,
266        reason: &'static str,
267    },
268    InvalidRegister {
269        reg_id: u32,
270        reg_type: &'static str,
271        reason: &'static str,
272    },
273    InvalidMemoryOperand {
274        base: Option<u32>,
275        index: Option<u32>,
276        scale: u8,
277        offset: i64,
278        reason: &'static str,
279    },
280    InvalidVSIB {
281        index_reg: u32,
282        reason: &'static str,
283    },
284    InvalidMasking {
285        mask_reg: u32,
286        reason: &'static str,
287    },
288    InvalidBroadcast {
289        reason: &'static str,
290    },
291    InvalidRoundingControl {
292        rc: u64,
293        reason: &'static str,
294    },
295    InvalidEVEX {
296        field: &'static str,
297        reason: &'static str,
298    },
299    InvalidVEX {
300        field: &'static str,
301        reason: &'static str,
302    },
303    TooLongInstruction {
304        length: usize,
305        max_length: usize,
306    },
307    SegmentOverrideNotAllowed {
308        segment: u8,
309        reason: &'static str,
310    },
311    AddressSizeMismatch {
312        expected: usize,
313        actual: usize,
314    },
315    OperandSizeMismatch {
316        expected: usize,
317        actual: usize,
318    },
319    InvalidRIPRelative {
320        offset: i64,
321        reason: &'static str,
322    },
323    InvalidLabel {
324        label_id: u32,
325        reason: &'static str,
326    },
327    InvalidSymbol {
328        symbol_id: u32,
329        reason: &'static str,
330    },
331    InvalidRelocation {
332        reloc_type: &'static str,
333        reason: &'static str,
334    },
335    InvalidOperandCombination {
336        mnemonic: &'static str,
337    },
338}
339
340impl fmt::Display for X86Error {
341    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
342        match self {
343            X86Error::InvalidPrefix { prefix, reason } => {
344                write!(f, "invalid prefix 0x{:x}: {}", prefix, reason)
345            }
346            X86Error::InvalidOperand {
347                operand_index,
348                reason,
349            } => write!(f, "invalid operand {}: {}", operand_index, reason),
350            X86Error::InvalidInstruction { opcode, reason } => {
351                write!(f, "invalid instruction 0x{:x}: {}", opcode, reason)
352            }
353            X86Error::InvalidEncoding { encoding, reason } => {
354                write!(f, "invalid encoding {}: {}", encoding, reason)
355            }
356            X86Error::InvalidModRM { modrm, reason } => {
357                write!(f, "invalid ModRM byte 0x{:02x}: {}", modrm, reason)
358            }
359            X86Error::InvalidSIB { sib, reason } => {
360                write!(f, "invalid SIB byte 0x{:02x}: {}", sib, reason)
361            }
362            X86Error::InvalidDisplacement {
363                value,
364                size,
365                reason,
366            } => write!(
367                f,
368                "invalid displacement 0x{:x} (size {}): {}",
369                value, size, reason
370            ),
371            X86Error::InvalidImmediate {
372                value,
373                size,
374                reason,
375            } => {
376                write!(
377                    f,
378                    "invalid immediate 0x{:x} (size {}): {}",
379                    value, size, reason
380                )
381            }
382            X86Error::InvalidRegister {
383                reg_id,
384                reg_type,
385                reason,
386            } => write!(
387                f,
388                "invalid register {} (type {}): {}",
389                reg_id, reg_type, reason
390            ),
391            X86Error::InvalidMemoryOperand {
392                base,
393                index,
394                scale,
395                offset,
396                reason,
397            } => write!(
398                f,
399                "invalid memory operand [base={:?}, index={:?}, scale={}, offset={}]: {}",
400                base, index, scale, offset, reason
401            ),
402            X86Error::InvalidVSIB { index_reg, reason } => {
403                write!(f, "invalid VSIB index register {}: {}", index_reg, reason)
404            }
405            X86Error::InvalidMasking { mask_reg, reason } => {
406                write!(f, "invalid mask register {}: {}", mask_reg, reason)
407            }
408            X86Error::InvalidBroadcast { reason } => {
409                write!(f, "invalid broadcast: {}", reason)
410            }
411            X86Error::InvalidRoundingControl { rc, reason } => {
412                write!(f, "invalid rounding control 0x{:x}: {}", rc, reason)
413            }
414            X86Error::InvalidEVEX { field, reason } => {
415                write!(f, "invalid EVEX field '{}': {}", field, reason)
416            }
417            X86Error::InvalidVEX { field, reason } => {
418                write!(f, "invalid VEX field '{}': {}", field, reason)
419            }
420            X86Error::TooLongInstruction { length, max_length } => write!(
421                f,
422                "instruction too long: {} bytes (max {})",
423                length, max_length
424            ),
425            X86Error::SegmentOverrideNotAllowed { segment, reason } => {
426                write!(f, "segment override {} not allowed: {}", segment, reason)
427            }
428            X86Error::AddressSizeMismatch { expected, actual } => write!(
429                f,
430                "address size mismatch: expected {} bytes, got {}",
431                expected, actual
432            ),
433            X86Error::OperandSizeMismatch { expected, actual } => write!(
434                f,
435                "operand size mismatch: expected {} bytes, got {}",
436                expected, actual
437            ),
438            X86Error::InvalidRIPRelative { offset, reason } => {
439                write!(f, "invalid RIP-relative offset {}: {}", offset, reason)
440            }
441            X86Error::InvalidLabel { label_id, reason } => {
442                write!(f, "invalid label {}: {}", label_id, reason)
443            }
444            X86Error::InvalidSymbol { symbol_id, reason } => {
445                write!(f, "invalid symbol {}: {}", symbol_id, reason)
446            }
447            X86Error::InvalidRelocation { reloc_type, reason } => {
448                write!(f, "invalid relocation {}: {}", reloc_type, reason)
449            }
450            X86Error::InvalidOperandCombination { mnemonic } => {
451                write!(
452                    f,
453                    "invalid operand combination for instruction `{}`",
454                    mnemonic
455                )
456            }
457        }
458    }
459}
460
461impl ::core::error::Error for X86Error {}