#![no_std]
use core::fmt::Debug;
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Target {
Address(u64),
Pointer {
address: u64,
size: u8,
},
Indirect,
Far {
selector: u16,
offset: u64,
},
}
impl Target {
pub const fn address(self) -> Option<u64> {
match self {
Self::Address(address) => Some(address),
Self::Pointer { .. } | Self::Indirect | Self::Far { .. } => None,
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Flow {
Next,
Jump(Target),
Branch(Target),
Call(Target),
Return,
Trap {
conditional: bool,
},
SystemCall,
ExceptionReturn,
Halt,
}
impl Flow {
pub const fn falls_through(self) -> bool {
match self {
Self::Next | Self::Branch(_) | Self::Call(_) | Self::SystemCall => true,
Self::Trap { conditional } => conditional,
Self::Jump(_) | Self::Return | Self::ExceptionReturn | Self::Halt => false,
}
}
}
#[expect(clippy::len_without_is_empty, reason = "an instruction is never empty")]
pub trait Instruction {
fn len(&self) -> usize;
fn flow(&self, address: u64) -> Flow;
fn computed_address(&self, address: u64) -> Option<u64> {
let _ = address;
None
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct FlowStep {
pub len: usize,
pub flow: Flow,
pub computed_address: Option<u64>,
}
impl FlowStep {
pub fn of<I: Instruction + ?Sized>(instruction: &I, address: u64) -> Self {
Self {
len: instruction.len(),
flow: instruction.flow(address),
computed_address: instruction.computed_address(address),
}
}
}
pub trait Architecture {
type Instruction: Instruction;
type Error: Copy + Debug;
type Mode: Copy + Debug + Eq;
const MAX_LENGTH: usize;
fn decode(&self, bytes: &[u8], mode: Self::Mode) -> Result<Self::Instruction, Self::Error>;
fn decode_flow(
&self,
bytes: &[u8],
mode: Self::Mode,
address: u64,
) -> Result<FlowStep, Self::Error> {
self.decode(bytes, mode)
.map(|instruction| FlowStep::of(&instruction, address))
}
}