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::{
103    read_value_span, repatch_jump_span, repatch_jump_span_mt_safe, repatch_value_span,
104    rewrite_region_span,
105};
106#[cfg(feature = "aarch64")]
107pub use core::target::AArch64Feature;
108#[cfg(feature = "riscv")]
109pub use core::target::RiscVFeature;
110#[cfg(feature = "x86")]
111pub use core::target::X86Feature;
112pub use core::{
113    arch_traits::Arch,
114    buffer::{
115        Addend, AsmReloc, CodeBuffer, CodeBufferFinalized, CodeOffset, Constant, ConstantData,
116        ExternalName, LabelUse, Reloc, RelocDistance, RelocTarget, UserExternalName,
117    },
118    builder::{Builder, InstSink, Node},
119    globals::{CondCode, InstOptions},
120    inst::Inst,
121    linker::{LinkError, Linker},
122    operand::{
123        BaseMem, BaseReg, Imm, ImmType, Label, Operand, OperandCast, OperandSignature, OperandType,
124        RegGroup, RegMask, RegTraits, RegType, Sym, imm,
125    },
126    patch::{
127        CodeLocationData, CodeLocationJump, CodeLocationRegion, DataLabel, PatchMark,
128        PatchableJump, PatchableRegion, read_value, repatch_jump, repatch_value, rewrite_region,
129    },
130    rwinfo::{
131        CpuRwFlags, INVALID_PHYS_ID, InstControlFlow, InstRwFlags, InstRwInfo, InstSameRegHint,
132        OpRwFlags, OpRwInfo,
133    },
134    section::{FinalizedSection, Section},
135    target::Environment,
136};
137
138use ::core::fmt;
139
140/// Error type shared by all backends and the core code-management machinery.
141///
142/// The variant set follows AsmJit's `Error` codes where the same failure mode
143/// exists here; detailed context is carried by nested backend and linker
144/// errors such as [`AsmError::X86`] and [`AsmError::Link`].
145#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Debug)]
146pub enum AsmError {
147    InvalidPrefix,
148    InvalidOperand,
149    InvalidImmediate,
150    InvalidInstruction,
151    OutOfMemory,
152    InvalidState,
153    TooManyHandles,
154    InvalidArgument,
155    /// Invalid or incompatible architecture (AsmJit's `kErrorInvalidArch`).
156    InvalidArch,
157    /// No code was generated (AsmJit's `kErrorNoCodeGenerated`), e.g. linking
158    /// with no sections.
159    NoCodeGenerated,
160    /// A relocation or defined symbol references a label that was never bound.
161    UnboundLabel,
162    FailedToOpenAnonymousMemory,
163    TooLarge,
164    /// A live patch field is not 4-aligned, so no single atomic store can
165    /// rewrite it.
166    UnalignedPatch,
167    /// An in-memory image link failed; the nested error identifies the
168    /// section, symbol, or relocation involved.
169    Link(LinkError),
170    X86(X86Error),
171    /// The selected instruction requires a CPU feature disabled by the target.
172    MissingCpuFeature {
173        feature: &'static str,
174    },
175    UnsupportedInstruction {
176        reason: &'static str,
177    },
178}
179
180impl fmt::Display for AsmError {
181    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
182        match self {
183            AsmError::InvalidPrefix => write!(f, "invalid prefix"),
184            AsmError::InvalidOperand => write!(f, "invalid operand"),
185            AsmError::InvalidInstruction => write!(f, "invalid instruction"),
186            AsmError::OutOfMemory => write!(f, "out of memory"),
187            AsmError::InvalidState => write!(f, "invalid state"),
188            AsmError::TooManyHandles => write!(f, "too many handles"),
189            AsmError::InvalidArgument => write!(f, "invalid argument"),
190            AsmError::InvalidImmediate => write!(f, "invalid immediate"),
191            AsmError::InvalidArch => write!(f, "invalid or incompatible architecture"),
192            AsmError::NoCodeGenerated => write!(f, "no code generated"),
193            AsmError::UnboundLabel => write!(f, "unbound label"),
194            AsmError::FailedToOpenAnonymousMemory => {
195                write!(f, "failed to open anonymous memory")
196            }
197            AsmError::TooLarge => write!(f, "too large"),
198            AsmError::UnalignedPatch => write!(f, "patch field is not 4 byte aligned"),
199            AsmError::Link(error) => write!(f, "link error: {error}"),
200            AsmError::X86(e) => write!(f, "x86 error: {}", e),
201            AsmError::MissingCpuFeature { feature } => {
202                write!(f, "missing CPU feature: {}", feature)
203            }
204            AsmError::UnsupportedInstruction { reason } => {
205                write!(f, "unsupported instruction: {}", reason)
206            }
207        }
208    }
209}
210
211impl From<X86Error> for AsmError {
212    fn from(err: X86Error) -> Self {
213        AsmError::X86(err)
214    }
215}
216
217impl ::core::error::Error for AsmError {
218    fn source(&self) -> Option<&(dyn ::core::error::Error + 'static)> {
219        match self {
220            AsmError::Link(error) => Some(error),
221            AsmError::X86(error) => Some(error),
222            _ => None,
223        }
224    }
225}
226
227/// Detailed x86/x64 encoding error, wrapped by [`AsmError::X86`].
228#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Debug)]
229pub enum X86Error {
230    InvalidPrefix {
231        prefix: u64,
232        reason: &'static str,
233    },
234    InvalidOperand {
235        operand_index: usize,
236        reason: &'static str,
237    },
238    InvalidInstruction {
239        opcode: u64,
240        reason: &'static str,
241    },
242    InvalidEncoding {
243        encoding: u8,
244        reason: &'static str,
245    },
246    InvalidModRM {
247        modrm: u8,
248        reason: &'static str,
249    },
250    InvalidSIB {
251        sib: u8,
252        reason: &'static str,
253    },
254    InvalidDisplacement {
255        value: i64,
256        size: usize,
257        reason: &'static str,
258    },
259    InvalidImmediate {
260        value: i64,
261        size: usize,
262        reason: &'static str,
263    },
264    InvalidRegister {
265        reg_id: u32,
266        reg_type: &'static str,
267        reason: &'static str,
268    },
269    InvalidMemoryOperand {
270        base: Option<u32>,
271        index: Option<u32>,
272        scale: u8,
273        offset: i64,
274        reason: &'static str,
275    },
276    InvalidVSIB {
277        index_reg: u32,
278        reason: &'static str,
279    },
280    InvalidMasking {
281        mask_reg: u32,
282        reason: &'static str,
283    },
284    InvalidBroadcast {
285        reason: &'static str,
286    },
287    InvalidRoundingControl {
288        rc: u64,
289        reason: &'static str,
290    },
291    InvalidEVEX {
292        field: &'static str,
293        reason: &'static str,
294    },
295    InvalidVEX {
296        field: &'static str,
297        reason: &'static str,
298    },
299    TooLongInstruction {
300        length: usize,
301        max_length: usize,
302    },
303    SegmentOverrideNotAllowed {
304        segment: u8,
305        reason: &'static str,
306    },
307    AddressSizeMismatch {
308        expected: usize,
309        actual: usize,
310    },
311    OperandSizeMismatch {
312        expected: usize,
313        actual: usize,
314    },
315    InvalidRIPRelative {
316        offset: i64,
317        reason: &'static str,
318    },
319    InvalidLabel {
320        label_id: u32,
321        reason: &'static str,
322    },
323    InvalidSymbol {
324        symbol_id: u32,
325        reason: &'static str,
326    },
327    InvalidRelocation {
328        reloc_type: &'static str,
329        reason: &'static str,
330    },
331    InvalidOperandCombination {
332        mnemonic: &'static str,
333    },
334}
335
336impl fmt::Display for X86Error {
337    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
338        match self {
339            X86Error::InvalidPrefix { prefix, reason } => {
340                write!(f, "invalid prefix 0x{:x}: {}", prefix, reason)
341            }
342            X86Error::InvalidOperand {
343                operand_index,
344                reason,
345            } => write!(f, "invalid operand {}: {}", operand_index, reason),
346            X86Error::InvalidInstruction { opcode, reason } => {
347                write!(f, "invalid instruction 0x{:x}: {}", opcode, reason)
348            }
349            X86Error::InvalidEncoding { encoding, reason } => {
350                write!(f, "invalid encoding {}: {}", encoding, reason)
351            }
352            X86Error::InvalidModRM { modrm, reason } => {
353                write!(f, "invalid ModRM byte 0x{:02x}: {}", modrm, reason)
354            }
355            X86Error::InvalidSIB { sib, reason } => {
356                write!(f, "invalid SIB byte 0x{:02x}: {}", sib, reason)
357            }
358            X86Error::InvalidDisplacement {
359                value,
360                size,
361                reason,
362            } => write!(
363                f,
364                "invalid displacement 0x{:x} (size {}): {}",
365                value, size, reason
366            ),
367            X86Error::InvalidImmediate {
368                value,
369                size,
370                reason,
371            } => {
372                write!(
373                    f,
374                    "invalid immediate 0x{:x} (size {}): {}",
375                    value, size, reason
376                )
377            }
378            X86Error::InvalidRegister {
379                reg_id,
380                reg_type,
381                reason,
382            } => write!(
383                f,
384                "invalid register {} (type {}): {}",
385                reg_id, reg_type, reason
386            ),
387            X86Error::InvalidMemoryOperand {
388                base,
389                index,
390                scale,
391                offset,
392                reason,
393            } => write!(
394                f,
395                "invalid memory operand [base={:?}, index={:?}, scale={}, offset={}]: {}",
396                base, index, scale, offset, reason
397            ),
398            X86Error::InvalidVSIB { index_reg, reason } => {
399                write!(f, "invalid VSIB index register {}: {}", index_reg, reason)
400            }
401            X86Error::InvalidMasking { mask_reg, reason } => {
402                write!(f, "invalid mask register {}: {}", mask_reg, reason)
403            }
404            X86Error::InvalidBroadcast { reason } => {
405                write!(f, "invalid broadcast: {}", reason)
406            }
407            X86Error::InvalidRoundingControl { rc, reason } => {
408                write!(f, "invalid rounding control 0x{:x}: {}", rc, reason)
409            }
410            X86Error::InvalidEVEX { field, reason } => {
411                write!(f, "invalid EVEX field '{}': {}", field, reason)
412            }
413            X86Error::InvalidVEX { field, reason } => {
414                write!(f, "invalid VEX field '{}': {}", field, reason)
415            }
416            X86Error::TooLongInstruction { length, max_length } => write!(
417                f,
418                "instruction too long: {} bytes (max {})",
419                length, max_length
420            ),
421            X86Error::SegmentOverrideNotAllowed { segment, reason } => {
422                write!(f, "segment override {} not allowed: {}", segment, reason)
423            }
424            X86Error::AddressSizeMismatch { expected, actual } => write!(
425                f,
426                "address size mismatch: expected {} bytes, got {}",
427                expected, actual
428            ),
429            X86Error::OperandSizeMismatch { expected, actual } => write!(
430                f,
431                "operand size mismatch: expected {} bytes, got {}",
432                expected, actual
433            ),
434            X86Error::InvalidRIPRelative { offset, reason } => {
435                write!(f, "invalid RIP-relative offset {}: {}", offset, reason)
436            }
437            X86Error::InvalidLabel { label_id, reason } => {
438                write!(f, "invalid label {}: {}", label_id, reason)
439            }
440            X86Error::InvalidSymbol { symbol_id, reason } => {
441                write!(f, "invalid symbol {}: {}", symbol_id, reason)
442            }
443            X86Error::InvalidRelocation { reloc_type, reason } => {
444                write!(f, "invalid relocation {}: {}", reloc_type, reason)
445            }
446            X86Error::InvalidOperandCombination { mnemonic } => {
447                write!(
448                    f,
449                    "invalid operand combination for instruction `{}`",
450                    mnemonic
451                )
452            }
453        }
454    }
455}
456
457impl ::core::error::Error for X86Error {}