Skip to main content

binbun_x86/
decoder.rs

1//! Decoding a buffer of code instruction by instruction.
2
3use core::iter::FusedIterator;
4
5use crate::{DecodeError, Instruction, MAX_LENGTH, Mode, decode};
6
7/// Decodes the instructions of a buffer one after another (a linear sweep).
8///
9/// Each item is the instruction's address and the decode result. After an
10/// instruction the decoder moves past it; after an error, by one byte, so
11/// that a sweep over data or misaligned code resynchronises.
12///
13/// ```
14/// use binbun_x86::{Decoder, Mode};
15///
16/// let code = [0x48, 0x89, 0xc7, 0xc3]; // mov rdi, rax; ret
17/// let mut decoder = Decoder::new(&code, Mode::Bits64, 0x1000);
18/// let (address, mov) = decoder.next().unwrap();
19/// assert_eq!((address, mov.unwrap().intel(address).to_string()), (0x1000, "mov rdi, rax".into()));
20/// let (address, ret) = decoder.next().unwrap();
21/// assert_eq!((address, ret.unwrap().len()), (0x1003, 1));
22/// assert!(decoder.next().is_none());
23/// ```
24#[derive(Debug, Clone)]
25pub struct Decoder<'a> {
26    bytes: &'a [u8],
27    mode: Mode,
28    /// Address of `bytes[0]`.
29    base: u64,
30    /// Offset of the next instruction in `bytes`.
31    offset: usize,
32}
33
34impl<'a> Decoder<'a> {
35    /// A decoder of `bytes`, which are at `address`, in `mode`.
36    pub const fn new(bytes: &'a [u8], mode: Mode, address: u64) -> Self {
37        Self {
38            bytes,
39            mode,
40            base: address,
41            offset: 0,
42        }
43    }
44
45    /// Offset in the buffer of the next instruction.
46    pub const fn offset(&self) -> usize {
47        self.offset
48    }
49
50    /// Address of the next instruction.
51    pub const fn address(&self) -> u64 {
52        self.base.wrapping_add(self.offset as u64)
53    }
54
55    /// Continues at `offset` in the buffer (past the end: nothing more).
56    pub const fn set_offset(&mut self, offset: usize) {
57        self.offset = offset;
58    }
59
60    /// The bytes not decoded yet.
61    pub fn remaining(&self) -> &'a [u8] {
62        self.bytes.get(self.offset..).unwrap_or_default()
63    }
64}
65
66impl Iterator for Decoder<'_> {
67    type Item = (u64, Result<Instruction, DecodeError>);
68
69    fn next(&mut self) -> Option<Self::Item> {
70        let rest = self.remaining();
71        if rest.is_empty() {
72            return None;
73        }
74        let address = self.address();
75        let result = decode(rest, self.mode);
76        self.offset += result.as_ref().map_or(1, Instruction::len);
77        Some((address, result))
78    }
79
80    fn size_hint(&self) -> (usize, Option<usize>) {
81        let rest = self.remaining().len();
82        (rest.div_ceil(MAX_LENGTH), Some(rest))
83    }
84}
85
86impl FusedIterator for Decoder<'_> {}