Skip to main content

binbun_disasm/
lib.rs

1//! Architecture-independent instruction decoding and inspection for x86 and AArch64.
2//!
3//! [`decode`] and [`Decoder`] take an [`Arch`] chosen by the caller (nothing
4//! is guessed from the bytes) and give an [`Insn`]: its address, the bytes
5//! it was decoded from (borrowed from the caller's buffer), its length, its
6//! mnemonic, its text, its control flow and the registers it reads and
7//! writes, whichever the architecture. Everything else stays with the
8//! native decoders, [`binbun_x86`] and [`binbun_aarch64`]
9//! (re-exported as [`x86`] and [`aarch64`]), whose instruction
10//! [`Insn::as_x86`] and [`Insn::as_aarch64`] return: operands, flags,
11//! conditions, encodings, text options and tokens.
12//!
13//! The crate is `no_std` and allocates nothing: an [`Insn`] is the native
14//! instruction behind an enum, and its facts are computed when asked.
15//! Features `x86` and `aarch64` (both default) choose the architectures:
16//! without one, its [`Arch`] variant, [`Insn`]'s `as_` method and its
17//! decoder crate are left out. [`Flow`] and [`Target`] are re-exported, so
18//! that no other crate is needed.
19//!
20//! - [`Insn::mnemonic`] is the mnemonic the text writes, lower case: on
21//!   x86 the word after any prefix words (`movsb` of `rep movsb`, not
22//!   XED's iclass `REP_MOVSB`), on AArch64 after alias selection, with its
23//!   suffix (`mov`, `b.eq`).
24//! - The text (`Display`) is each decoder's own default: Intel syntax as
25//!   XED writes it on x86, LLVM's on AArch64 (a tab after the mnemonic);
26//!   branch targets as addresses on both. Nothing is normalised.
27//! - [`Insn::registers_read`] and [`Insn::registers_written`] are what
28//!   the decoders report an instruction *may* read and write; see
29//!   [`Registers`].
30//!
31//! ```
32//! use binbun_disasm::{Arch, Decoder, Flow, Target, x86};
33//!
34//! let code = [0x55, 0xe8, 0x00, 0x00, 0x00, 0x00, 0xc3]; // push rbp; call; ret
35//! let mut decoder = Decoder::new(Arch::X86(x86::Mode::Bits64), &code, 0x1000);
36//! let (address, push) = decoder.next().unwrap();
37//! let push = push?;
38//! assert_eq!((address, push.mnemonic(), push.to_string()), (0x1000, "push", "push rbp".into()));
39//! assert_eq!(push.bytes(), [0x55]);
40//! let names = |registers: &binbun_disasm::Registers| {
41//!     registers.iter().map(ToString::to_string).collect::<Vec<_>>()
42//! };
43//! assert_eq!(names(&push.registers_read()), ["rbp", "rsp"]);
44//! assert_eq!(names(&push.registers_written()), ["rsp"]);
45//! let (_, call) = decoder.next().unwrap();
46//! assert_eq!(call?.flow(), Flow::Call(Target::Address(0x1006)));
47//!
48//! let a64 = [0xe0, 0x03, 0x01, 0xaa]; // orr x0, xzr, x1
49//! let mov = binbun_disasm::decode(Arch::AArch64, &a64, 0x2000)?;
50//! assert_eq!((mov.mnemonic(), mov.to_string()), ("mov", "mov\tx0, x1".into()));
51//! assert_eq!(mov.as_aarch64().unwrap().encoding().mnemonic(), "ORR");
52//! # Ok::<(), binbun_disasm::DecodeError>(())
53//! ```
54
55#![no_std]
56#![forbid(unsafe_code)]
57
58mod registers;
59
60#[cfg(not(any(feature = "x86", feature = "aarch64")))]
61compile_error!("binbun-disasm needs feature `x86` or `aarch64` (or both)");
62
63use core::fmt;
64use core::iter::FusedIterator;
65
66#[cfg(feature = "aarch64")]
67pub use binbun_aarch64 as aarch64;
68pub use binbun_isa::{Flow, Target};
69#[cfg(feature = "x86")]
70pub use binbun_x86 as x86;
71#[cfg(feature = "aarch64")]
72pub use registers::AArch64Register;
73pub use registers::{Register, Registers};
74
75/// The architecture to decode for, with x86's processor mode.
76#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
77pub enum Arch {
78    /// x86 in a mode: 16, 32 or 64-bit ([`x86::Mode`]).
79    #[cfg(feature = "x86")]
80    X86(x86::Mode),
81    /// AArch64's A64 instruction set.
82    #[cfg(feature = "aarch64")]
83    AArch64,
84}
85
86impl Arch {
87    /// The longest instruction, in bytes: 15 on x86, 4 on AArch64 (whose
88    /// instructions are all 4 bytes).
89    pub const fn max_length(self) -> usize {
90        match self {
91            #[cfg(feature = "x86")]
92            Self::X86(_) => x86::MAX_LENGTH,
93            #[cfg(feature = "aarch64")]
94            Self::AArch64 => 4,
95        }
96    }
97
98    /// How far a [`Decoder`] moves past bytes that are no instruction: one
99    /// byte on x86, so that a sweep resynchronises; four on AArch64.
100    pub const fn invalid_step(self) -> usize {
101        match self {
102            #[cfg(feature = "x86")]
103            Self::X86(_) => 1,
104            #[cfg(feature = "aarch64")]
105            Self::AArch64 => 4,
106        }
107    }
108}
109
110/// Why bytes are no instruction: the native decoder's error.
111#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
112pub enum DecodeError {
113    /// The x86 decoder's.
114    #[cfg(feature = "x86")]
115    X86(x86::DecodeError),
116    /// The AArch64 decoder's.
117    #[cfg(feature = "aarch64")]
118    AArch64(aarch64::Error),
119}
120
121impl DecodeError {
122    /// Whether the bytes end before the instruction does.
123    pub const fn is_truncated(self) -> bool {
124        match self {
125            #[cfg(feature = "x86")]
126            Self::X86(error) => matches!(error, x86::DecodeError::TooShort),
127            #[cfg(feature = "aarch64")]
128            Self::AArch64(error) => matches!(error, aarch64::Error::TooShort),
129        }
130    }
131}
132
133impl fmt::Display for DecodeError {
134    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
135        match self {
136            #[cfg(feature = "x86")]
137            Self::X86(error) => error.fmt(f),
138            #[cfg(feature = "aarch64")]
139            Self::AArch64(error) => error.fmt(f),
140        }
141    }
142}
143
144impl core::error::Error for DecodeError {}
145
146#[cfg(feature = "x86")]
147impl From<x86::DecodeError> for DecodeError {
148    fn from(error: x86::DecodeError) -> Self {
149        Self::X86(error)
150    }
151}
152
153#[cfg(feature = "aarch64")]
154impl From<aarch64::Error> for DecodeError {
155    fn from(error: aarch64::Error) -> Self {
156        Self::AArch64(error)
157    }
158}
159
160/// The native instruction.
161#[derive(Clone, Debug, PartialEq, Eq)]
162enum Native {
163    #[cfg(feature = "x86")]
164    X86(x86::Instruction, x86::Mode),
165    #[cfg(feature = "aarch64")]
166    AArch64(aarch64::Instruction),
167}
168
169/// A decoded instruction at its address, with the bytes it was decoded
170/// from.
171///
172/// Its `Display` is its text, as the native decoder writes it by default
173/// (see the [crate] documentation).
174#[derive(Clone, Debug, PartialEq, Eq)]
175pub struct Insn<'a> {
176    address: u64,
177    bytes: &'a [u8],
178    native: Native,
179}
180
181impl<'a> Insn<'a> {
182    /// The x86 instruction `instruction`, which a decode in `mode` made
183    /// from `bytes` at `address`, as [`decode`] would give it: for code
184    /// that keeps native instructions and asks them again, without
185    /// decoding twice (binbun's C API). `bytes` past the instruction's
186    /// length are left out.
187    #[cfg(feature = "x86")]
188    pub fn from_x86(
189        instruction: x86::Instruction,
190        mode: x86::Mode,
191        bytes: &'a [u8],
192        address: u64,
193    ) -> Self {
194        Self {
195            address,
196            bytes: bytes.get(..instruction.len()).unwrap_or(bytes),
197            native: Native::X86(instruction, mode),
198        }
199    }
200
201    /// The AArch64 instruction `instruction`, decoded from `bytes` at
202    /// `address`, as [`decode`] would give it; see [`Insn::from_x86`].
203    #[cfg(feature = "aarch64")]
204    pub fn from_aarch64(instruction: aarch64::Instruction, bytes: &'a [u8], address: u64) -> Self {
205        Self {
206            address,
207            bytes: bytes.get(..4).unwrap_or(bytes),
208            native: Native::AArch64(instruction),
209        }
210    }
211
212    /// The architecture it was decoded for.
213    pub const fn arch(&self) -> Arch {
214        match self.native {
215            #[cfg(feature = "x86")]
216            Native::X86(_, mode) => Arch::X86(mode),
217            #[cfg(feature = "aarch64")]
218            Native::AArch64(_) => Arch::AArch64,
219        }
220    }
221
222    /// Its address.
223    pub const fn address(&self) -> u64 {
224        self.address
225    }
226
227    /// Its length in bytes: 1 to 15 on x86, 4 on AArch64.
228    #[allow(clippy::len_without_is_empty, reason = "an instruction is never empty")]
229    pub const fn len(&self) -> usize {
230        self.bytes.len()
231    }
232
233    /// The bytes it was decoded from, borrowed from the buffer decoded
234    /// (AArch64's are the word, little-endian).
235    pub const fn bytes(&self) -> &'a [u8] {
236        self.bytes
237    }
238
239    /// The mnemonic its text writes, lower case: on x86 the word after any
240    /// prefix words (`movsb` of `rep movsb`; `call far`), on AArch64 after
241    /// alias selection, with its suffix (`mov`, `b.eq`). The native
242    /// mnemonics, XED's iclass and Arm's encoding mnemonic, are the native
243    /// instruction's.
244    pub fn mnemonic(&self) -> &'static str {
245        match &self.native {
246            #[cfg(feature = "x86")]
247            Native::X86(instruction, _) => instruction.intel_mnemonic(),
248            #[cfg(feature = "aarch64")]
249            Native::AArch64(instruction) => instruction.mnemonic(),
250        }
251    }
252
253    /// What it does to the flow of control at its address.
254    pub fn flow(&self) -> Flow {
255        match &self.native {
256            #[cfg(feature = "x86")]
257            Native::X86(instruction, _) => binbun_isa::Instruction::flow(instruction, self.address),
258            #[cfg(feature = "aarch64")]
259            Native::AArch64(instruction) => instruction.flow(self.address),
260        }
261    }
262
263    /// The registers it may read; see [`Registers`].
264    pub fn registers_read(&self) -> Registers {
265        match &self.native {
266            #[cfg(feature = "x86")]
267            Native::X86(instruction, _) => registers::x86(instruction, registers::Side::Read),
268            #[cfg(feature = "aarch64")]
269            Native::AArch64(instruction) => registers::aarch64(*instruction, registers::Side::Read),
270        }
271    }
272
273    /// The registers it may write; see [`Registers`].
274    pub fn registers_written(&self) -> Registers {
275        match &self.native {
276            #[cfg(feature = "x86")]
277            Native::X86(instruction, _) => registers::x86(instruction, registers::Side::Write),
278            #[cfg(feature = "aarch64")]
279            Native::AArch64(instruction) => {
280                registers::aarch64(*instruction, registers::Side::Write)
281            }
282        }
283    }
284
285    /// The x86 decoder's instruction, if it is one.
286    #[cfg(feature = "x86")]
287    pub const fn as_x86(&self) -> Option<&x86::Instruction> {
288        match &self.native {
289            Native::X86(instruction, _) => Some(instruction),
290            #[cfg(feature = "aarch64")]
291            Native::AArch64(_) => None,
292        }
293    }
294
295    /// The AArch64 decoder's instruction, if it is one.
296    #[cfg(feature = "aarch64")]
297    pub const fn as_aarch64(&self) -> Option<&aarch64::Instruction> {
298        match &self.native {
299            #[cfg(feature = "x86")]
300            Native::X86(..) => None,
301            Native::AArch64(instruction) => Some(instruction),
302        }
303    }
304}
305
306impl fmt::Display for Insn<'_> {
307    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
308        match &self.native {
309            #[cfg(feature = "x86")]
310            Native::X86(instruction, _) => instruction.intel(self.address).fmt(f),
311            #[cfg(feature = "aarch64")]
312            Native::AArch64(instruction) => instruction.display(self.address).fmt(f),
313        }
314    }
315}
316
317/// Decodes the instruction at the start of `bytes`, which is at
318/// `address`, for `arch`.
319///
320/// # Errors
321///
322/// The native decoder's: [`x86::decode`]'s or
323/// [`aarch64::decode_bytes`]'s.
324pub fn decode(arch: Arch, bytes: &[u8], address: u64) -> Result<Insn<'_>, DecodeError> {
325    let native = match arch {
326        #[cfg(feature = "x86")]
327        Arch::X86(mode) => Native::X86(x86::decode(bytes, mode)?, mode),
328        #[cfg(feature = "aarch64")]
329        Arch::AArch64 => Native::AArch64(aarch64::decode_bytes(bytes)?),
330    };
331    let len = match &native {
332        #[cfg(feature = "x86")]
333        Native::X86(instruction, _) => instruction.len(),
334        #[cfg(feature = "aarch64")]
335        Native::AArch64(_) => 4,
336    };
337    Ok(Insn {
338        address,
339        bytes: bytes.get(..len).unwrap_or(bytes),
340        native,
341    })
342}
343
344/// Decodes the instructions of a buffer one after another (a linear
345/// sweep), for an architecture.
346///
347/// Each item is the address and the decode result. After an instruction
348/// the decoder moves past it; after bytes that are no instruction, as the
349/// native decoders do ([`Arch::invalid_step`]): one byte on x86, so that a
350/// sweep over data or misaligned code resynchronises, four on AArch64 (a
351/// last piece shorter than 4 bytes is one truncated step).
352#[derive(Debug, Clone)]
353pub struct Decoder<'a> {
354    arch: Arch,
355    bytes: &'a [u8],
356    /// Address of `bytes[0]`.
357    base: u64,
358    /// Offset of the next instruction in `bytes`.
359    offset: usize,
360}
361
362impl<'a> Decoder<'a> {
363    /// A decoder of `bytes`, which are at `address`, for `arch`.
364    pub const fn new(arch: Arch, bytes: &'a [u8], address: u64) -> Self {
365        Self {
366            arch,
367            bytes,
368            base: address,
369            offset: 0,
370        }
371    }
372
373    /// The architecture it decodes for.
374    pub const fn arch(&self) -> Arch {
375        self.arch
376    }
377
378    /// Offset in the buffer of the next instruction.
379    pub const fn offset(&self) -> usize {
380        self.offset
381    }
382
383    /// Address of the next instruction.
384    pub const fn address(&self) -> u64 {
385        self.base.wrapping_add(self.offset as u64)
386    }
387
388    /// Continues at `offset` in the buffer (past the end: nothing more).
389    pub const fn set_offset(&mut self, offset: usize) {
390        self.offset = offset;
391    }
392
393    /// The bytes not decoded yet.
394    pub fn remaining(&self) -> &'a [u8] {
395        self.bytes.get(self.offset..).unwrap_or_default()
396    }
397}
398
399impl<'a> Iterator for Decoder<'a> {
400    type Item = (u64, Result<Insn<'a>, DecodeError>);
401
402    fn next(&mut self) -> Option<Self::Item> {
403        let rest = self.remaining();
404        if rest.is_empty() {
405            return None;
406        }
407        let address = self.address();
408        let result = decode(self.arch, rest, address);
409        let step = result.as_ref().map_or(self.arch.invalid_step(), Insn::len);
410        self.offset = self.offset.saturating_add(step);
411        Some((address, result))
412    }
413
414    fn size_hint(&self) -> (usize, Option<usize>) {
415        let rest = self.remaining().len();
416        match self.arch {
417            #[cfg(feature = "x86")]
418            Arch::X86(_) => (rest.div_ceil(x86::MAX_LENGTH), Some(rest)),
419            #[cfg(feature = "aarch64")]
420            Arch::AArch64 => (rest.div_ceil(4), Some(rest.div_ceil(4))),
421        }
422    }
423}
424
425impl FusedIterator for Decoder<'_> {}