1pub 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#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
21pub struct Attributes(pub u128);
22
23impl Attributes {
24 pub const fn contains(self, attribute: Attribute) -> bool {
26 self.0 & (1 << attribute as u8) != 0
27 }
28}
29
30#[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 pub operands: u16,
41 pub operand_count: u8,
43 pub intel: &'static str,
46 pub flags: FlagsRule,
48 pub flow: FlowKind,
50}
51
52#[derive(Debug, Clone, PartialEq, Eq)]
56pub struct Instruction {
57 number: u16,
59 fields: Fields,
60}
61
62impl Instruction {
63 #[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 pub fn form(&self) -> Form {
80 self.info().form
81 }
82
83 #[inline]
85 pub fn mnemonic(&self) -> Mnemonic {
86 self.info().form.mnemonic()
87 }
88
89 pub fn attributes(&self) -> Attributes {
91 self.info().attributes
92 }
93
94 pub fn category(&self) -> Category {
96 self.info().category
97 }
98
99 pub fn extension(&self) -> Extension {
101 self.info().extension
102 }
103
104 pub fn isa_set(&self) -> IsaSet {
106 self.info().isa_set
107 }
108
109 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#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
122pub enum Encoding {
123 Legacy,
125 Vex,
127 Evex,
129 Xop,
131}
132
133pub fn decode(bytes: &[u8], mode: Mode) -> Result<Instruction, DecodeError> {
143 if mode == Mode::Bits64 {
146 fast::decode(bytes)
147 } else {
148 decode_other(bytes, mode)
149 }
150}
151
152pub 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#[inline(never)]
171fn decode_other(bytes: &[u8], mode: Mode) -> Result<Instruction, DecodeError> {
172 decode_in::<false>(bytes, mode)
173}
174
175#[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#[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#[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#[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#[inline]
257fn needs_finalize(s: &Fields, info: &InstructionInfo) -> bool {
258 s.lock != 0 || s.realmode != 0 || info.attributes.0 & FINALIZED != 0
259}
260
261const 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
267fn 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 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 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 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
315fn 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}