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