Skip to main content

i8051_disassembler/platform/
m6805.rs

1//! The Motorola 6805 (M68HC05) driver.
2//!
3//! Adapts the [`::m6805`] decoder to the neutral [`DecodedInsn`]. Like the
4//! 6502, the 6805 has a single flat address space, data references are
5//! classified by the load/store/RMW/bit role of each mnemonic. Used to
6//! disassemble the "green LED" DEC LK201 keyboard ROM.
7
8use std::sync::Arc;
9
10use ::m6805::{Instruction, Mnemonic, Operand};
11
12use crate::address::{AddressSpace, XrefType};
13
14use super::{
15    Certainty, ControlFlow, DataRef, DecodedInsn, Platform, PlatformRef, RegionDef, RegionKind,
16};
17
18/// The 6805's single flat address space (RAM, I/O, and ROM).
19pub const CODE: AddressSpace = AddressSpace::new("CODE");
20
21/// The one 6805 region.
22static REGIONS: &[RegionDef] = &[RegionDef {
23    space: CODE,
24    kind: RegionKind::Code,
25    area_header: ".area CODE (CODE,ABS)\n",
26}];
27
28/// The 6805 driver.
29#[derive(Debug, Default, Clone, Copy)]
30pub struct M6805;
31
32/// A shared 6805 driver.
33pub fn platform() -> PlatformRef {
34    Arc::new(M6805)
35}
36
37impl Platform for M6805 {
38    fn name(&self) -> &str {
39        "m6805"
40    }
41
42    fn regions(&self) -> &[RegionDef] {
43        REGIONS
44    }
45
46    fn max_insn_len(&self) -> usize {
47        Instruction::MAX_LENGTH
48    }
49
50    fn decode(&self, pc: u32, bytes: &[u8]) -> DecodedInsn {
51        let insn = Instruction::decode_from_bytes(pc, bytes);
52        let control_flow = map_control_flow(insn.control_flow());
53        // The target is always the last operand: the lone operand of a branch or
54        // JMP/JSR, or the `rel` at the end of a BRSET/BRCLR.
55        let branch_operand_index = has_target(control_flow)
56            .then(|| insn.operands().as_slice().len().checked_sub(1))
57            .flatten();
58        DecodedInsn {
59            len: insn.len() as u8,
60            bytes: insn.bytes().to_vec(),
61            text: insn.as_string(),
62            control_flow,
63            branch_operand_index,
64            named_register: None,
65            data_refs: data_refs(&insn),
66        }
67    }
68}
69
70fn map_control_flow(cf: ::m6805::ControlFlow) -> ControlFlow {
71    use ::m6805::ControlFlow as M;
72    match cf {
73        M::Continue { next } => ControlFlow::Continue { next },
74        M::Jump { target } => ControlFlow::Jump { target },
75        M::Call { target, return_pc } => ControlFlow::Call { target, return_pc },
76        M::Choice {
77            fall_through,
78            branch_target,
79        } => ControlFlow::Choice {
80            fall_through,
81            branch_target,
82        },
83        M::Diverge => ControlFlow::Diverge,
84    }
85}
86
87fn has_target(cf: ControlFlow) -> bool {
88    matches!(
89        cf,
90        ControlFlow::Jump { .. } | ControlFlow::Call { .. } | ControlFlow::Choice { .. }
91    )
92}
93
94/// Read/write role of a memory-operand instruction.
95#[derive(Debug, Clone, Copy)]
96enum Access {
97    Read,
98    Write,
99    ReadWrite,
100}
101
102impl Access {
103    fn kind(self) -> XrefType {
104        match self {
105            Access::Read => XrefType::Read,
106            Access::Write => XrefType::Write,
107            Access::ReadWrite => XrefType::ReadWrite,
108        }
109    }
110}
111
112/// The access role of a mnemonic that touches memory. Register-only forms
113/// (`NEGA`, `CLRX`, ...) are distinct mnemonics with no memory operand, so they
114/// fall through to `None`. Control-flow mnemonics are handled by the neutral
115/// control flow, not here.
116fn memory_access(mnemonic: Mnemonic) -> Option<Access> {
117    use Mnemonic::*;
118    Some(match mnemonic {
119        STA | STX | CLR => Access::Write,
120        NEG | COM | LSR | ROR | ASR | LSL | ROL | DEC | INC | BSET | BCLR => Access::ReadWrite,
121        LDA | LDX | CMP | CPX | BIT | SUB | SBC | AND | EOR | ADC | ORA | ADD | TST | BRSET
122        | BRCLR => Access::Read,
123        _ => return None,
124    })
125}
126
127/// The static data reference an instruction makes, if any: the direct or
128/// extended address it names. Indexed and immediate operands have no static
129/// target and are skipped.
130fn data_refs(insn: &Instruction) -> Vec<DataRef> {
131    let Some(access) = memory_access(insn.mnemonic()) else {
132        return Vec::new();
133    };
134    let offset = insn.operands().as_slice().iter().find_map(|op| match op {
135        Operand::Direct(a) => Some(u32::from(*a)),
136        Operand::Extended(a) => Some(u32::from(*a)),
137        _ => None,
138    });
139    match offset {
140        Some(offset) => vec![DataRef {
141            space: CODE,
142            offset,
143            kind: access.kind(),
144            certainty: Certainty::Definite,
145            operand: Some(0),
146        }],
147        None => Vec::new(),
148    }
149}
150
151#[cfg(test)]
152mod tests {
153    use super::*;
154    use crate::platform::branch_target;
155    use crate::platform::test_util::edges;
156    use pretty_assertions::assert_eq;
157
158    #[test]
159    fn control_flow_and_targets() {
160        let decode = |bytes: &[u8]| M6805.decode(0x1000, bytes);
161
162        let jsr = decode(&[0xCD, 0x0C, 0xB5]);
163        assert!(matches!(
164            jsr.control_flow,
165            ControlFlow::Call { target: 0x0CB5, .. }
166        ));
167        assert_eq!(branch_target(&jsr), Some(0x0CB5));
168        assert_eq!(jsr.branch_operand_index, Some(0));
169
170        // BRSET's branch target is the third operand.
171        let brset = decode(&[0x0E, 0x50, 0x10]);
172        assert!(matches!(brset.control_flow, ControlFlow::Choice { .. }));
173        assert_eq!(brset.branch_operand_index, Some(2));
174
175        // Indexed jump has no static target.
176        assert_eq!(decode(&[0xFC]).control_flow, ControlFlow::Diverge);
177    }
178
179    #[test]
180    fn data_refs_classify_access() {
181        use XrefType::{Jump, Read, ReadWrite, Write};
182        let e = |bytes: &[u8]| edges(&M6805, bytes);
183        assert_eq!(e(&[0xB6, 0x50]), vec![(CODE, 0x50, Read)]); // LDA 0x50
184        assert_eq!(e(&[0xC7, 0x12, 0x34]), vec![(CODE, 0x1234, Write)]); // STA ext
185        assert_eq!(e(&[0x3A, 0x50]), vec![(CODE, 0x50, ReadWrite)]); // DEC 0x50
186        assert_eq!(e(&[0x16, 0x50]), vec![(CODE, 0x50, ReadWrite)]); // BSET 3,0x50
187        assert_eq!(e(&[0xCC, 0x12, 0x34]), vec![(CODE, 0x1234, Jump)]); // JMP is control
188        assert!(e(&[0xA6, 0x42]).is_empty()); // immediate makes no ref
189    }
190}