Skip to main content

i8051_disassembler/
platform.rs

1//! Processor drivers.
2//!
3//! The disassembler is generic over the CPU it decodes. A [`Platform`] driver
4//! turns raw bytes into a CPU-neutral [`DecodedInsn`] and declares the address
5//! [`regions`](Platform::regions) that CPU exposes, so the rest of the crate
6//! never names a concrete instruction set. The one built-in driver lives in
7//! [`i8051`], a caller can supply its own (including user-defined regions).
8
9use std::sync::Arc;
10
11use crate::address::{AddressSpace, AddressValue, PhysicalAddr, Xref, XrefType};
12
13pub mod i8051;
14pub mod m6805;
15pub mod mos6502;
16
17/// How execution proceeds after an instruction. CPU-neutral: every driver maps
18/// its own control flow onto these cases.
19#[derive(Debug, Clone, Copy, PartialEq, Eq)]
20pub enum ControlFlow {
21    /// Fall through to `next`.
22    Continue { next: AddressValue },
23    /// Unconditional jump to `target`.
24    Jump { target: AddressValue },
25    /// Call `target`, returning to `return_pc`.
26    Call {
27        target: AddressValue,
28        return_pc: AddressValue,
29    },
30    /// Branch to `branch_target` or fall through to `fall_through`.
31    Choice {
32        fall_through: AddressValue,
33        branch_target: AddressValue,
34    },
35    /// Unknown or data-dependent control flow.
36    Diverge,
37}
38
39/// A static data reference an instruction makes, already classified into an
40/// address space by the driver (which owns the CPU's memory-map semantics).
41#[derive(Debug, Clone, Copy, PartialEq, Eq)]
42pub struct DataRef {
43    pub space: AddressSpace,
44    pub offset: AddressValue,
45    pub kind: XrefType,
46    pub certainty: Certainty,
47    /// Which operand this is for, if any.
48    pub operand: Option<u8>,
49}
50
51/// Whether a reference is definite (unambiguous) or inferred (one of many
52/// options).
53#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
54pub enum Certainty {
55    /// The instruction names this target unambiguously.
56    Definite,
57    /// The instruction produces a value that may be this target.
58    Inferred,
59}
60
61/// A CPU-neutral decoded instruction: everything the disassembler needs to
62/// render, trace, and cross-reference an instruction without knowing the ISA.
63#[derive(Debug, Clone)]
64pub struct DecodedInsn {
65    /// Byte length of the instruction.
66    pub len: u8,
67    /// The instruction bytes (length `len`).
68    pub bytes: Vec<u8>,
69    /// Canonical text (mnemonic + operands), before label substitution.
70    pub text: String,
71    /// Control flow after this instruction.
72    pub control_flow: ControlFlow,
73    /// Which operand (0-based) holds the branch/jump target, for label
74    /// substitution during rendering. `None` if the instruction has no target.
75    pub branch_operand_index: Option<usize>,
76    /// A register-file address to surface by name in listings (the 8051 SFR
77    /// naming hook). `None` on CPUs without one.
78    pub named_register: Option<u8>,
79    /// Static data references, space-classified by the driver.
80    pub data_refs: Vec<DataRef>,
81}
82
83impl DecodedInsn {
84    #[inline]
85    pub fn len(&self) -> usize {
86        self.len as usize
87    }
88
89    #[inline]
90    pub fn is_empty(&self) -> bool {
91        self.len == 0
92    }
93
94    #[inline]
95    pub fn bytes(&self) -> &[u8] {
96        &self.bytes
97    }
98
99    #[inline]
100    pub fn control_flow(&self) -> ControlFlow {
101        self.control_flow
102    }
103
104    #[inline]
105    pub fn as_string(&self) -> &str {
106        &self.text
107    }
108
109    /// The register-file address to name, if any (see [`named_register`]).
110    ///
111    /// [`named_register`]: DecodedInsn::named_register
112    #[inline]
113    pub fn direct_addr(&self) -> Option<u8> {
114        self.named_register
115    }
116}
117
118/// What a region holds, advisory metadata a driver attaches to each space.
119#[derive(Debug, Clone, Copy, PartialEq, Eq)]
120pub enum RegionKind {
121    /// Executable code.
122    Code,
123    /// A register file (the 8051 `SFR`/`BIT` spaces, memory-mapped I/O, ...).
124    Register,
125    /// Plain data memory.
126    Data,
127}
128
129/// A driver-declared address region.
130#[derive(Debug, Clone)]
131pub struct RegionDef {
132    /// The space this region occupies.
133    pub space: AddressSpace,
134    /// What the region holds.
135    pub kind: RegionKind,
136    /// The `sdas` `.area` header emitted for this region.
137    pub area_header: &'static str,
138}
139
140/// A known CPU entry point.
141#[derive(Debug, Clone, Copy)]
142pub struct EntryPoint {
143    pub space: AddressSpace,
144    pub offset: AddressValue,
145    /// The architectural name, e.g. `INT_timer0`.
146    pub name: &'static str,
147    /// What the hardware does here.
148    pub reason: &'static str,
149}
150
151/// The canonical address for a location.
152///
153/// Some locations may be aliases (e.g.: on the 8051, bit registers are just
154/// subviews of other SFRs).
155#[derive(Debug, Clone, Copy, PartialEq, Eq)]
156pub struct CanonicalAddr {
157    pub space: AddressSpace,
158    pub offset: AddressValue,
159    /// The bit selected within that byte, when the reference was to a bit.
160    pub bit: Option<u8>,
161}
162
163/// A processor driver: decodes bytes and declares the CPU's address regions and
164/// known entry points.
165pub trait Platform: Send + Sync {
166    /// A short identifier for the CPU (`"i8051"`, `"mos6502"`, ...).
167    fn name(&self) -> &str;
168
169    /// The address regions this CPU exposes, in emission order. May include
170    /// user-defined regions.
171    fn regions(&self) -> &[RegionDef];
172
173    /// Where the hardware begins executing: reset and interrupt vectors. These
174    /// can be disabled if unused or not appropriate for a given database.
175    fn entry_points(&self) -> &[EntryPoint] {
176        &[]
177    }
178
179    /// Resolve an address to the storage it aliases (or itself if it is not an alias).
180    fn canonicalize(&self, space: AddressSpace, offset: AddressValue) -> CanonicalAddr {
181        CanonicalAddr {
182            space,
183            offset,
184            bit: None,
185        }
186    }
187
188    /// The longest instruction in bytes, the fetch window for decoding.
189    fn max_insn_len(&self) -> usize;
190
191    /// Decode the instruction starting at `pc` from `bytes` (a fetch window of
192    /// up to [`max_insn_len`](Platform::max_insn_len) bytes). Returns an
193    /// instruction even for unknown opcodes (with its length), mirroring the
194    /// underlying decoder, the caller rejects it if it runs past `bytes`.
195    fn decode(&self, pc: AddressValue, bytes: &[u8]) -> DecodedInsn;
196
197    /// The `.area` header for `space`, if this driver declares it.
198    fn area_header(&self, space: AddressSpace) -> Option<&'static str> {
199        self.regions()
200            .iter()
201            .find(|r| r.space == space)
202            .map(|r| r.area_header)
203    }
204}
205
206/// The control-flow and data cross-references an instruction makes from
207/// `source`. Control edges come from the neutral control flow, data edges are
208/// the driver's pre-classified [`DataRef`]s.
209pub fn xrefs_from_instruction(insn: &DecodedInsn, source: PhysicalAddr) -> Vec<Xref> {
210    let mut xrefs = Vec::new();
211    let mut push = |space, offset, xref_type, certainty| {
212        xrefs.push(Xref {
213            from: source,
214            to: PhysicalAddr { space, offset },
215            xref_type,
216            certainty,
217        });
218    };
219
220    match insn.control_flow {
221        ControlFlow::Jump { target } => {
222            push(source.space, target, XrefType::Jump, Certainty::Definite)
223        }
224        ControlFlow::Call { target, .. } => {
225            push(source.space, target, XrefType::Call, Certainty::Definite)
226        }
227        ControlFlow::Choice { branch_target, .. } => push(
228            source.space,
229            branch_target,
230            XrefType::Jump,
231            Certainty::Definite,
232        ),
233        _ => {}
234    }
235
236    for data_ref in &insn.data_refs {
237        push(
238            data_ref.space,
239            data_ref.offset,
240            data_ref.kind,
241            data_ref.certainty,
242        );
243    }
244
245    xrefs
246}
247
248/// The absolute branch/jump/call target of `insn`, if it has one.
249pub fn branch_target(insn: &DecodedInsn) -> Option<AddressValue> {
250    match insn.control_flow {
251        ControlFlow::Jump { target } | ControlFlow::Call { target, .. } => Some(target),
252        ControlFlow::Choice { branch_target, .. } => Some(branch_target),
253        _ => None,
254    }
255}
256
257/// Which operand holds the branch target (for label substitution), or `None`.
258pub fn branch_target_operand_index(insn: &DecodedInsn) -> Option<usize> {
259    insn.branch_operand_index
260}
261
262/// Handy alias for a shared driver.
263pub type PlatformRef = Arc<dyn Platform>;
264
265/// The built-in driver names, in a stable order.
266pub const BUILTIN_PLATFORMS: &[&str] = &["i8051", "mos6502", "m6805"];
267
268/// Look up a built-in driver by name (see [`BUILTIN_PLATFORMS`]).
269pub fn by_name(name: &str) -> Option<PlatformRef> {
270    match name {
271        "i8051" => Some(i8051::platform()),
272        "mos6502" => Some(mos6502::platform()),
273        "m6805" => Some(m6805::platform()),
274        _ => None,
275    }
276}
277
278/// Built-in CPU names closest to `query`, substring matches first, then by
279/// Levenshtein distance.
280pub fn suggest_names(query: &str) -> Vec<String> {
281    let q = query.to_ascii_lowercase();
282    let mut ranked: Vec<(bool, usize, &str)> = BUILTIN_PLATFORMS
283        .iter()
284        .map(|&name| {
285            let n = name.to_ascii_lowercase();
286            let substring = n.contains(&q) || q.contains(&n);
287            (substring, crate::strings::levenshtein(&q, &n), name)
288        })
289        .collect();
290    ranked.sort_by(|a, b| {
291        b.0.cmp(&a.0)
292            .then_with(|| a.1.cmp(&b.1))
293            .then_with(|| a.2.cmp(b.2))
294    });
295    ranked
296        .into_iter()
297        .map(|(_, _, name)| name.to_string())
298        .collect()
299}
300
301#[cfg(test)]
302mod suggest_tests {
303    use super::*;
304
305    #[test]
306    fn suggest_prefers_substring() {
307        assert_eq!(suggest_names("8051")[0], "i8051");
308        assert_eq!(suggest_names("6502")[0], "mos6502");
309    }
310
311    #[test]
312    fn suggest_orders_by_distance() {
313        let ranked = suggest_names("z80");
314        assert_eq!(ranked.len(), 3);
315        assert!(ranked.contains(&"i8051".to_string()));
316    }
317}
318
319/// Shared helpers for the per-driver test modules.
320#[cfg(test)]
321pub(crate) mod test_util {
322    use super::*;
323
324    /// Decode `bytes` with `driver` (at pc 0) and return the cross-reference
325    /// edges it makes from a source at offset 0, as `(space, offset, kind)`.
326    pub(crate) fn edges(
327        driver: &dyn Platform,
328        bytes: &[u8],
329    ) -> Vec<(AddressSpace, AddressValue, XrefType)> {
330        let source = PhysicalAddr {
331            space: driver.regions()[0].space,
332            offset: 0,
333        };
334        xrefs_from_instruction(&driver.decode(0, bytes), source)
335            .into_iter()
336            .map(|x| (x.to.space, x.to.offset, x.xref_type))
337            .collect()
338    }
339}