Skip to main content

binbun_x86/
decode.rs

1//! Full decoding: length, then which instruction it is.
2
3pub mod flags;
4pub mod flow;
5pub mod format;
6pub mod operand;
7
8use flags::FlagsRule;
9use flow::FlowKind;
10
11use binbun_isa::FlowStep;
12
13use crate::fast;
14use crate::generated::form::{Attribute, Category, Extension, Form, INSTRUCTIONS, IsaSet};
15use crate::generated::handlers::{HANDLERS, HANDLERS64, Handler, generic};
16use crate::generated::state::{Fields, State};
17use crate::{DecodeError, Mnemonic, Mode, Register, RegisterClass};
18
19/// A set of [`Attribute`]s.
20#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
21pub struct Attributes(pub u128);
22
23impl Attributes {
24    /// Whether `attribute` is in the set.
25    pub const fn contains(self, attribute: Attribute) -> bool {
26        self.0 & (1 << attribute as u8) != 0
27    }
28}
29
30/// What the decoder knows about one instruction of its table.
31#[derive(Debug, Clone, Copy, PartialEq, Eq)]
32pub struct InstructionInfo {
33    pub form: Form,
34    pub attributes: Attributes,
35    pub category: Category,
36    pub extension: Extension,
37    pub isa_set: IsaSet,
38    /// The instruction's operand list: first index into
39    /// `generated::operand::SEQUENCES`.
40    pub operands: u16,
41    /// Number of operands.
42    pub operand_count: u8,
43    /// The mnemonic in Intel syntax, lower case (`movsb` for `REP_MOVSB`,
44    /// `call far` for `CALL_FAR`).
45    pub intel: &'static str,
46    /// Which flags record applies.
47    pub flags: FlagsRule,
48    /// How the instruction transfers control.
49    pub flow: FlowKind,
50}
51
52/// A decoded instruction.
53///
54/// It keeps the decoder fields that operand values and text are read from.
55#[derive(Debug, Clone, PartialEq, Eq)]
56pub struct Instruction {
57    /// The instruction's number: its [`INSTRUCTIONS`] entry plus one.
58    number: u16,
59    fields: Fields,
60}
61
62impl Instruction {
63    /// Length in bytes, 1 to 15.
64    #[allow(clippy::len_without_is_empty, reason = "an instruction is never empty")]
65    pub const fn len(&self) -> usize {
66        self.fields.pos
67    }
68
69    #[expect(
70        clippy::indexing_slicing,
71        reason = "`decode` only returns numbers of table entries"
72    )]
73    #[inline]
74    fn info(&self) -> &'static InstructionInfo {
75        &INSTRUCTIONS[usize::from(self.number) - 1]
76    }
77
78    /// The instruction's form (XED's iform).
79    pub fn form(&self) -> Form {
80        self.info().form
81    }
82
83    /// The instruction's mnemonic (XED's iclass).
84    #[inline]
85    pub fn mnemonic(&self) -> Mnemonic {
86        self.info().form.mnemonic()
87    }
88
89    /// The instruction's attributes.
90    pub fn attributes(&self) -> Attributes {
91        self.info().attributes
92    }
93
94    /// The instruction's category.
95    pub fn category(&self) -> Category {
96        self.info().category
97    }
98
99    /// The ISA extension the instruction belongs to.
100    pub fn extension(&self) -> Extension {
101        self.info().extension
102    }
103
104    /// The feature set the instruction needs.
105    pub fn isa_set(&self) -> IsaSet {
106        self.info().isa_set
107    }
108
109    /// How the instruction is encoded (XED's `VEXVALID`).
110    pub const fn encoding(&self) -> Encoding {
111        match self.fields.vexvalid {
112            1 => Encoding::Vex,
113            2 => Encoding::Evex,
114            3 => Encoding::Xop,
115            _ => Encoding::Legacy,
116        }
117    }
118}
119
120/// An instruction's prefix family.
121#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
122pub enum Encoding {
123    /// Legacy prefixes, with REX or REX2 or neither.
124    Legacy,
125    /// A VEX prefix.
126    Vex,
127    /// An EVEX prefix.
128    Evex,
129    /// AMD's XOP prefix.
130    Xop,
131}
132
133/// Decodes the instruction at the start of `bytes`.
134///
135/// # Errors
136///
137/// As XED's `xed_decode`. Length-decoding errors come first; truncated
138/// input is [`DecodeError::TooShort`], or [`DecodeError::TooLong`] when 15
139/// bytes were available. Then [`DecodeError::Invalid`] when no instruction
140/// has this encoding, errors of its operands, and finally the checks of
141/// [`finalize`].
142pub fn decode(bytes: &[u8], mode: Mode) -> Result<Instruction, DecodeError> {
143    // In 64-bit mode the fast path, which falls back to a copy of the
144    // reference decoder where every mode test folds.
145    if mode == Mode::Bits64 {
146        fast::decode(bytes)
147    } else {
148        decode_other(bytes, mode)
149    }
150}
151
152/// What control-flow recovery needs of the instruction at the start of
153/// `bytes`, which is at `address`: [`FlowStep::of`] the [`decode`]d
154/// instruction, without decoding what flow does not depend on where the
155/// 64-bit fast path applies.
156///
157/// # Errors
158///
159/// As [`decode`].
160pub fn decode_flow(bytes: &[u8], mode: Mode, address: u64) -> Result<FlowStep, DecodeError> {
161    if mode == Mode::Bits64 {
162        fast::decode_flow(bytes, address)
163    } else {
164        decode_other(bytes, mode).map(|i| i.flow_step(address))
165    }
166}
167
168/// The reference decoder outside 64-bit mode, out of line: the fast path
169/// calls nothing else and needs no stack frame of its size.
170#[inline(never)]
171fn decode_other(bytes: &[u8], mode: Mode) -> Result<Instruction, DecodeError> {
172    decode_in::<false>(bytes, mode)
173}
174
175/// [`decode`] by the reference decoder alone, without the 64-bit fast path
176/// (with feature `internal-reference`, for differential fuzzing: the two must agree
177/// on every input).
178///
179/// # Errors
180///
181/// As [`decode`].
182#[cfg(feature = "internal-reference")]
183#[doc(hidden)]
184pub fn decode_reference(bytes: &[u8], mode: Mode) -> Result<Instruction, DecodeError> {
185    if mode == Mode::Bits64 {
186        decode_in::<true>(bytes, mode)
187    } else {
188        decode_other(bytes, mode)
189    }
190}
191
192/// The reference decoder ([`decode`] without the fast path); `MODE64` when
193/// `mode` is [`Mode::Bits64`].
194#[expect(
195    clippy::inline_always,
196    reason = "each copy folds its mode into the inlined length decoder"
197)]
198#[inline(always)]
199pub fn decode_in<const MODE64: bool>(bytes: &[u8], mode: Mode) -> Result<Instruction, DecodeError> {
200    let mut state = State::default();
201    state.load(bytes, mode);
202    let table = state.head();
203    let number = if state.out_of_bytes == 0 {
204        handler::<MODE64>(table, state.nominal_opcode)(&mut state)
205    } else {
206        0
207    };
208    if let Some(error) = DecodeError::from_code(state.error) {
209        return Err(error);
210    }
211    let info = usize::from(number)
212        .checked_sub(1)
213        .and_then(|index| INSTRUCTIONS.get(index))
214        .ok_or(DecodeError::Invalid)?;
215    if let Some(error) = finalize(&state, info) {
216        return Err(error);
217    }
218    Ok(Instruction {
219        number,
220        fields: state.fields,
221    })
222}
223
224/// The handler of `opcode` in the map with handler table `table`: a 64-bit
225/// one for `MODE64` if the map has them.
226#[inline]
227fn handler<const MODE64: bool>(table: usize, opcode: u8) -> Handler {
228    let handlers = match HANDLERS64.get(table) {
229        Some(handlers) if MODE64 => Some(handlers),
230        _ => HANDLERS.get(table),
231    };
232    handlers
233        .and_then(|table| table.get(usize::from(opcode)))
234        .copied()
235        .unwrap_or(generic)
236}
237
238/// Instruction `number` (a number of a table entry) with `fields`, unless
239/// [`finalize`] rejects it: the fast path's result.
240#[expect(
241    clippy::inline_always,
242    reason = "with a constant `number` the checks fold away"
243)]
244#[inline(always)]
245pub fn checked(number: u16, fields: Fields) -> Option<Instruction> {
246    let info = usize::from(number)
247        .checked_sub(1)
248        .and_then(|index| INSTRUCTIONS.get(index))?;
249    if needs_finalize(&fields, info) && finalize(&fields, info).is_some() {
250        return None;
251    }
252    Some(Instruction { number, fields })
253}
254
255/// Whether [`finalize`] may reject an instruction.
256#[inline]
257fn needs_finalize(s: &Fields, info: &InstructionInfo) -> bool {
258    s.lock != 0 || s.realmode != 0 || info.attributes.0 & FINALIZED != 0
259}
260
261/// The attributes that have checks in [`finalize`].
262const FINALIZED: u128 = 1 << Attribute::NoSrcDestMatch as u32
263    | 1 << Attribute::NoRegMatch as u32
264    | 1 << Attribute::Gather as u32
265    | 1 << Attribute::NoRipRel as u32;
266
267/// XED's `xed_decode_finalize_operand_storage_fields`: encodings that decode
268/// but are not allowed. A later check's error replaces an earlier one's.
269fn finalize(s: &Fields, info: &InstructionInfo) -> Option<DecodeError> {
270    if !needs_finalize(s, info) {
271        return None;
272    }
273    let has = |attribute| info.attributes.contains(attribute);
274    if s.lock != 0 && !has(Attribute::Locked) {
275        return Some(DecodeError::BadLockPrefix);
276    }
277    let mut error = None;
278    // AVX-512 forms with a mask register have it as the second register.
279    let second = if has(Attribute::MaskopEvex) {
280        s.reg3
281    } else {
282        s.reg1
283    };
284    if has(Attribute::NoSrcDestMatch) && (s.reg0 == second || s.reg0 == s.reg2) {
285        error = Some(DecodeError::BadRegisterMatch);
286    }
287    if has(Attribute::NoRegMatch) && (s.reg0 == second || second == s.reg2 || s.reg0 == s.reg2) {
288        error = Some(DecodeError::BadRegisterMatch);
289    }
290    if has(Attribute::Gather) {
291        let id = vector_number;
292        if info.extension == Extension::Avx2gather {
293            // Index, destination and mask must all differ.
294            let (index, dest, mask) = (id(s.index), id(s.reg0), id(s.reg1));
295            if index == mask || index == dest || mask == dest {
296                error = Some(DecodeError::GatherRegisters);
297            }
298        } else if has(Attribute::MaskopEvex) && id(s.index) == id(s.reg0) {
299            error = Some(DecodeError::GatherRegisters);
300        }
301    }
302    // BNDLDX/BNDSTX: no RIP-relative addressing in 64-bit mode.
303    if has(Attribute::NoRipRel) && s.rm == 5 && s.mod_ == 0 && s.mode == 2 {
304        error = Some(DecodeError::Invalid);
305    }
306    if s.realmode != 0
307        && (s.vexvalid != 0 || has(Attribute::ProtectedMode))
308        && !matches!(info.isa_set, IsaSet::Sep | IsaSet::Smx)
309    {
310        error = Some(DecodeError::InvalidMode);
311    }
312    error
313}
314
315/// A vector register's number within its class (`XMM3`, `YMM3` and `ZMM3`
316/// are all 3), as XED compares gather registers; `raw` is a state register.
317fn vector_number(raw: u16) -> u16 {
318    let first = match Register::from_raw(raw).map(Register::class) {
319        Some(RegisterClass::Zmm) => Register::ZMM0,
320        Some(RegisterClass::Ymm) => Register::YMM0,
321        _ => Register::XMM0,
322    };
323    raw.wrapping_sub(first as u16)
324}