binbun_isa/lib.rs
1//! The vocabulary analyses use to work with any instruction set: how an
2//! instruction transfers control ([`Flow`], [`Target`]) and the traits every
3//! binbun decoder implements ([`Architecture`], [`Instruction`]).
4//! Control-flow recovery needs only [`FlowStep`]s, which
5//! [`Architecture::decode_flow`] may give faster than a full decode.
6//!
7//! Analyses (CFG recovery, later lifting) are written against these traits
8//! only. Architecture-specific detail, such as which condition a branch
9//! tests, stays in the decoder crates.
10//!
11//! `no_std`, no dependencies.
12
13#![no_std]
14
15use core::fmt::Debug;
16
17/// Where a jump or call goes, as far as the instruction alone tells.
18#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
19pub enum Target {
20 /// A known address.
21 Address(u64),
22 /// The address stored in memory (an x86 `jmp [rip+disp]`, the usual
23 /// way to reach an import through its GOT or IAT slot).
24 Pointer {
25 /// Where the address is stored.
26 address: u64,
27 /// Its size in bytes.
28 size: u8,
29 },
30 /// A register or a computed memory operand.
31 Indirect,
32 /// A segmented address (an x86 far pointer), which needs the segment's
33 /// base to become an address.
34 Far {
35 /// The segment selector.
36 selector: u16,
37 /// The offset in the segment.
38 offset: u64,
39 },
40}
41
42impl Target {
43 /// The address, if known.
44 pub const fn address(self) -> Option<u64> {
45 match self {
46 Self::Address(address) => Some(address),
47 Self::Pointer { .. } | Self::Indirect | Self::Far { .. } => None,
48 }
49 }
50}
51
52/// How an instruction transfers control.
53#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
54pub enum Flow {
55 /// Execution continues with the next instruction.
56 Next,
57 /// An unconditional jump.
58 Jump(Target),
59 /// A conditional jump: to the target, or on with the next instruction.
60 Branch(Target),
61 /// A call; the callee normally returns to the next instruction.
62 Call(Target),
63 /// A return from a call.
64 Return,
65 /// A software interrupt or deliberate exception (`INT3`, `UD2`, `BRK`);
66 /// `conditional` ones (`INTO`) continue with the next instruction when
67 /// they do not trap.
68 Trap {
69 /// Whether it only traps on a condition.
70 conditional: bool,
71 },
72 /// An entry to the operating system or hypervisor (`SYSCALL`, `SVC`),
73 /// which normally returns to the next instruction.
74 SystemCall,
75 /// A return from an interrupt, exception or system call (`IRET`,
76 /// `SYSRET`, `ERET`).
77 ExceptionReturn,
78 /// A halt until the next interrupt (`HLT`).
79 Halt,
80}
81
82impl Flow {
83 /// Whether execution can continue with the next instruction.
84 pub const fn falls_through(self) -> bool {
85 match self {
86 Self::Next | Self::Branch(_) | Self::Call(_) | Self::SystemCall => true,
87 Self::Trap { conditional } => conditional,
88 Self::Jump(_) | Self::Return | Self::ExceptionReturn | Self::Halt => false,
89 }
90 }
91}
92
93/// A decoded instruction, as analyses see it.
94#[expect(clippy::len_without_is_empty, reason = "an instruction is never empty")]
95pub trait Instruction {
96 /// Length in bytes.
97 fn len(&self) -> usize;
98
99 /// How it transfers control, for the instruction at `address`.
100 fn flow(&self, address: u64) -> Flow;
101
102 /// An address the instruction at `address` computes as a value instead
103 /// of accessing it (an x86 RIP-relative `lea`): a pointer it may pass
104 /// on, such as a function's address given to a call.
105 fn computed_address(&self, address: u64) -> Option<u64> {
106 let _ = address;
107 None
108 }
109}
110
111/// What control-flow recovery needs of the instruction at an address: its
112/// length, how it transfers control and the address it computes
113/// ([`Instruction::len`], [`Instruction::flow`] and
114/// [`Instruction::computed_address`]).
115#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
116pub struct FlowStep {
117 /// Length in bytes.
118 pub len: usize,
119 /// How it transfers control.
120 pub flow: Flow,
121 /// An address it computes as a value.
122 pub computed_address: Option<u64>,
123}
124
125impl FlowStep {
126 /// The step of `instruction` at `address`.
127 pub fn of<I: Instruction + ?Sized>(instruction: &I, address: u64) -> Self {
128 Self {
129 len: instruction.len(),
130 flow: instruction.flow(address),
131 computed_address: instruction.computed_address(address),
132 }
133 }
134}
135
136/// An instruction set and its decoder.
137pub trait Architecture {
138 /// A decoded instruction.
139 type Instruction: Instruction;
140 /// Why bytes do not decode.
141 type Error: Copy + Debug;
142 /// The processor mode instructions are decoded for (x86's 16/32/64-bit
143 /// modes; AArch64 has one).
144 type Mode: Copy + Debug + Eq;
145
146 /// The longest instruction, in bytes: reading this many always
147 /// suffices to decode one.
148 const MAX_LENGTH: usize;
149
150 /// Decodes the instruction at the start of `bytes` in `mode`.
151 ///
152 /// # Errors
153 ///
154 /// When the bytes are no instruction, or end before one does.
155 fn decode(&self, bytes: &[u8], mode: Self::Mode) -> Result<Self::Instruction, Self::Error>;
156
157 /// The [`FlowStep`] of the instruction at the start of `bytes`, which is
158 /// at `address`: as from [`Architecture::decode`], which decoders may do
159 /// faster by skipping what control flow does not need.
160 ///
161 /// # Errors
162 ///
163 /// Exactly when [`Architecture::decode`] fails, with its error.
164 fn decode_flow(
165 &self,
166 bytes: &[u8],
167 mode: Self::Mode,
168 address: u64,
169 ) -> Result<FlowStep, Self::Error> {
170 self.decode(bytes, mode)
171 .map(|instruction| FlowStep::of(&instruction, address))
172 }
173}