Skip to main content

i8051_disassembler/commands/
pointer.rs

1use crate::address::{SpaceAddressSet, SpaceAddressValue};
2use crate::db::{Db, Error, OperandType};
3
4use super::{Apply, Command, Environment, boxed};
5
6#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
7pub struct SetOperandPointer {
8    pub address: SpaceAddressValue,
9    pub space: String,
10}
11
12register!(SetOperandPointer(
13    /// Mark an instruction as loading an address into `space`.
14    ///
15    /// Registers may be used to address addresses in any number of spaces, so
16    /// this command marks an instruction as loading an address into `space`.
17    address: SpaceAddressValue,
18    space: String,
19));
20
21impl Apply for SetOperandPointer {
22    fn apply(
23        self,
24        db: &mut Db,
25        _env: Option<&dyn Environment>,
26    ) -> Result<Vec<Box<dyn Command>>, Error> {
27        let Self { address, space } = self;
28        let target = db.resolve_space(&space)?;
29        let previous = db
30            .region_mut(address.space)
31            .set_operand_type(address.offset, OperandType::Pointer(target));
32        Ok(undo_for(address, previous))
33    }
34}
35
36#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
37pub struct SetOperandValue {
38    pub address: SpaceAddressValue,
39}
40
41register!(SetOperandValue(
42    /// Mark an instruction as loading a scalar value, not an address.
43    address: SpaceAddressValue,
44));
45
46impl Apply for SetOperandValue {
47    fn apply(
48        self,
49        db: &mut Db,
50        _env: Option<&dyn Environment>,
51    ) -> Result<Vec<Box<dyn Command>>, Error> {
52        let Self { address } = self;
53        let previous = db
54            .region_mut(address.space)
55            .set_operand_type(address.offset, OperandType::Value);
56        Ok(undo_for(address, previous))
57    }
58}
59
60#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
61pub struct ClearOperandType {
62    pub addresses: SpaceAddressSet,
63}
64
65register!(ClearOperandType(
66    /// Forget what these instructions' ambiguous operands resolve to.
67    addresses: SpaceAddressSet,
68));
69
70impl Apply for ClearOperandType {
71    fn apply(
72        self,
73        db: &mut Db,
74        _env: Option<&dyn Environment>,
75    ) -> Result<Vec<Box<dyn Command>>, Error> {
76        let Self { addresses } = self;
77        let space = addresses.space;
78        let region = db.region_mut(space);
79        let mut undo = Vec::new();
80        for range in addresses.ranges() {
81            for offset in range {
82                if let Some(previous) = region.clear_operand_type(offset) {
83                    undo.extend(undo_for((space, offset).into(), Some(previous)));
84                }
85            }
86        }
87        Ok(undo)
88    }
89}
90
91fn undo_for(address: SpaceAddressValue, previous: Option<OperandType>) -> Vec<Box<dyn Command>> {
92    match previous {
93        Some(OperandType::Pointer(space)) => vec![boxed(SetOperandPointer {
94            address,
95            space: space.dsl_name().to_string(),
96        })],
97        Some(OperandType::Value) => vec![boxed(SetOperandValue { address })],
98        None => vec![boxed(ClearOperandType::new((
99            address.space,
100            address.offset,
101        )))],
102    }
103}
104
105#[cfg(test)]
106mod tests {
107    use super::*;
108    use crate::address::PhysicalAddr;
109    use crate::commands::{AutoDisassemble, MapBytes};
110    use crate::platform::i8051::{CODE, XDATA};
111
112    struct Env;
113    impl crate::commands::Environment for Env {
114        fn load_file_bytes(
115            &self,
116            _f: &str,
117            offset: usize,
118            size: crate::address::AddressValue,
119        ) -> Result<Vec<u8>, std::io::Error> {
120            // MOV DPTR,#0x0008 / RET, then two table bytes.
121            const IMAGE: [u8; 6] = [0x90, 0x00, 0x08, 0x22, 0xAA, 0xBB];
122            Ok(IMAGE[offset..offset + size as usize].to_vec())
123        }
124    }
125
126    fn fixture() -> Db {
127        let mut db = Db::with_platform(crate::platform::i8051::platform());
128        db.apply(
129            boxed(MapBytes::new((CODE, 0), "img", 0usize, 6u32)),
130            Some(&Env),
131        )
132        .unwrap();
133        db.apply(boxed(AutoDisassemble::new((CODE, 0u32))), Some(&Env))
134            .unwrap();
135        db
136    }
137
138    fn replay(db: &Db) -> Db {
139        let dsl = crate::store::to_dsl_many(&db.to_commands());
140        let mut fresh = Db::new();
141        for command in crate::store::from_dsl_many(&dsl).expect("export parses") {
142            fresh.apply(command, Some(&Env)).expect("export replays");
143        }
144        fresh
145    }
146
147    const CODE_8: PhysicalAddr = PhysicalAddr {
148        space: CODE,
149        offset: 8,
150    };
151    const XDATA_8: PhysicalAddr = PhysicalAddr {
152        space: XDATA,
153        offset: 8,
154    };
155
156    /// Deciding at the instruction picks one candidate and drops the rest.
157    #[test]
158    fn deciding_collapses_candidates() {
159        let mut db = fixture();
160        assert_eq!(db.xrefs_to(&CODE_8).len(), 1, "both candidates start open");
161        assert_eq!(db.xrefs_to(&XDATA_8).len(), 1);
162        assert_eq!(db.undecided_operands().len(), 1);
163
164        let undo = db
165            .apply(
166                boxed(SetOperandPointer {
167                    address: (CODE, 0u32).into(),
168                    space: "CODE".to_string(),
169                }),
170                None,
171            )
172            .unwrap();
173        assert_eq!(db.xrefs_to(&CODE_8).len(), 1, "there can be only one");
174        assert!(db.xrefs_to(&XDATA_8).is_empty(), "the rejected one is gone");
175        assert!(db.undecided_operands().is_empty(), "this is the way");
176
177        let reloaded = replay(&db);
178        assert!(reloaded.xrefs_to(&XDATA_8).is_empty(), "survives a reload");
179
180        for command in undo {
181            db.apply(command, None).unwrap();
182        }
183        assert_eq!(db.xrefs_to(&XDATA_8).len(), 1, "undo reopens");
184    }
185
186    /// `MOV DPTR,#0x0008` may just be loading a number.
187    #[test]
188    fn number_references_nothing() {
189        let mut db = fixture();
190        db.apply(
191            boxed(SetOperandValue {
192                address: (CODE, 0u32).into(),
193            }),
194            None,
195        )
196        .unwrap();
197
198        assert!(
199            db.xrefs_to(&CODE_8).is_empty(),
200            "a number doesn't reference anything"
201        );
202        assert!(db.xrefs_to(&XDATA_8).is_empty());
203        assert!(replay(&db).xrefs_to(&CODE_8).is_empty(), "and it reloads");
204    }
205
206    /// Clearing restores every candidate.
207    #[test]
208    fn clearing_restores_the_candidates() {
209        let mut db = fixture();
210        db.apply(
211            boxed(SetOperandValue {
212                address: (CODE, 0u32).into(),
213            }),
214            None,
215        )
216        .unwrap();
217        db.apply(boxed(ClearOperandType::new((CODE, 0u32))), None)
218            .unwrap();
219
220        assert_eq!(db.xrefs_to(&CODE_8).len(), 1);
221        assert_eq!(db.xrefs_to(&XDATA_8).len(), 1);
222    }
223}