Skip to main content

i8051_disassembler/
diff.rs

1//! Computing a "diff DB": the commands that turn one DB's state into another's.
2//!
3//! A user maintains a *base* DB by hand (memory layout, disassembly roots, known
4//! data). Everything discovered on top of it is saved as a diff: the minimal
5//! command sequence D such that applying D on top of the base reproduces the
6//! working state. Facts identical to the base are omitted; facts added, changed,
7//! or removed relative to the base are captured.
8
9use std::collections::HashSet;
10
11use crate::commands::{
12    AutoDisassemble, ClearAutoDisassembleRoot, ClearComment, ClearEquivalents, ClearFunction,
13    ClearLabel, ClearNote, Command, DisassembleRange, MapBytes, MarkData, MarkUnknown,
14    OverrideOperand, SetComment, SetConstantBytes, SetFunction, SetLabel, SetNote, UnmapBytes,
15    boxed,
16};
17use crate::db::Db;
18use crate::store::to_dsl;
19
20impl Db {
21    /// The commands that transform `base`'s state into this DB's state: a clear
22    /// for every base fact this DB changed or dropped, then a set for every fact
23    /// this DB has that base does not. Both sides are taken from the canonical
24    /// [`to_commands`](Db::to_commands) form, so identical facts cancel out.
25    ///
26    /// Applying the result on top of `base` reproduces this DB exactly. Clears
27    /// come first so a shrunk range is wiped before the survivor is re-set.
28    pub fn diff_from(&self, base: &Db) -> Vec<Box<dyn Command>> {
29        let base_cmds = base.to_commands();
30        let cur_cmds = self.to_commands();
31        let base_dsl: HashSet<String> = base_cmds.iter().map(|c| to_dsl(c.as_ref())).collect();
32        let cur_dsl: HashSet<String> = cur_cmds.iter().map(|c| to_dsl(c.as_ref())).collect();
33
34        let mut diff = Vec::new();
35        for b in &base_cmds {
36            if cur_dsl.contains(&to_dsl(b.as_ref())) {
37                continue;
38            }
39            if let Some(clear) = clear_for(b.as_ref()) {
40                diff.push(clear);
41            }
42        }
43        for c in cur_cmds {
44            if !base_dsl.contains(&to_dsl(c.as_ref())) {
45                diff.push(c);
46            }
47        }
48        diff
49    }
50}
51
52/// The command that undoes one canonical state-producing command, for clearing a
53/// base fact the working state changed or removed. `None` for a command with no
54/// clear counterpart (there is none among [`Db::to_commands`]'s output).
55fn clear_for(cmd: &dyn Command) -> Option<Box<dyn Command>> {
56    let any = cmd.as_any();
57    if let Some(c) = any.downcast_ref::<SetLabel>() {
58        return Some(boxed(ClearLabel::new((c.address.space, c.address.offset))));
59    }
60    if let Some(c) = any.downcast_ref::<SetComment>() {
61        return Some(boxed(ClearComment::new((
62            c.address.space,
63            c.address.offset,
64        ))));
65    }
66    if let Some(c) = any.downcast_ref::<SetFunction>() {
67        return Some(boxed(ClearFunction::new((
68            c.address.space,
69            c.address.offset,
70        ))));
71    }
72    if let Some(c) = any.downcast_ref::<AutoDisassemble>() {
73        return Some(boxed(ClearAutoDisassembleRoot::new((
74            c.address.space,
75            c.address.offset,
76        ))));
77    }
78    if let Some(c) = any.downcast_ref::<OverrideOperand>() {
79        return Some(boxed(OverrideOperand::new(
80            (c.address.space, c.address.offset),
81            c.index,
82            None,
83        )));
84    }
85    if let Some(c) = any.downcast_ref::<MapBytes>() {
86        let range = c.address.offset..c.address.offset + c.size;
87        return Some(boxed(UnmapBytes::new((c.address.space, range))));
88    }
89    if let Some(c) = any.downcast_ref::<SetConstantBytes>() {
90        return Some(boxed(UnmapBytes::new((c.range.space, c.range.range))));
91    }
92    if let Some(c) = any.downcast_ref::<MarkData>() {
93        return Some(boxed(ClearEquivalents::new((c.range.space, c.range.range))));
94    }
95    if let Some(c) = any.downcast_ref::<MarkUnknown>() {
96        return Some(boxed(ClearEquivalents::new((c.range.space, c.range.range))));
97    }
98    if let Some(c) = any.downcast_ref::<DisassembleRange>() {
99        return Some(boxed(ClearEquivalents::new((c.range.space, c.range.range))));
100    }
101    if let Some(c) = any.downcast_ref::<SetNote>() {
102        return Some(boxed(ClearNote::new(c.note.id.clone())));
103    }
104    None
105}
106
107#[cfg(test)]
108mod tests {
109    use crate::commands::Environment;
110    use crate::db::Db;
111    use crate::platform::i8051::CODE;
112    use crate::store::{from_dsl_many, to_dsl_many};
113
114    /// Build a DB by applying DSL commands to a fresh i8051 database.
115    fn db(commands: &str) -> Db {
116        let mut db = Db::with_platform(crate::platform::i8051::platform());
117        // A small constant-byte program so labels/comments have somewhere to land.
118        db.region_mut(CODE).set_bytes(
119            "t.bin",
120            0,
121            0x0,
122            &[0x00, 0x22, 0x00, 0x22, 0x00, 0x22, 0x00, 0x22],
123        );
124        for command in from_dsl_many(commands).expect("parse") {
125            db.apply(command, None::<&dyn Environment>).expect("apply");
126        }
127        db
128    }
129
130    /// Apply a diff on top of a base and assert it reproduces the target exactly.
131    fn assert_roundtrip(base_src: &str, target_src: &str) {
132        let base = db(base_src);
133        let target = db(target_src);
134        let diff = target.diff_from(&base);
135
136        let mut reconstructed = db(base_src);
137        for command in diff {
138            reconstructed
139                .apply(command, None::<&dyn Environment>)
140                .expect("apply diff");
141        }
142        assert_eq!(
143            to_dsl_many(&reconstructed.to_commands()),
144            to_dsl_many(&target.to_commands()),
145        );
146    }
147
148    #[test]
149    fn identical_states_empty_diff() {
150        let base = db(r#"set_label(address=CODE:0x0, label="reset")"#);
151        assert!(base.diff_from(&base).is_empty());
152    }
153
154    #[test]
155    fn added_facts_become_sets() {
156        let base = db("");
157        let target = db(r#"set_label(address=CODE:0x0, label="reset")"#);
158        let diff = to_dsl_many(&target.diff_from(&base));
159        assert!(diff.contains("set_label(address=CODE:0x0"), "diff: {diff}");
160        assert_roundtrip("", r#"set_label(address=CODE:0x0, label="reset")"#);
161    }
162
163    #[test]
164    fn changed_facts_reset() {
165        assert_roundtrip(
166            r#"set_label(address=CODE:0x0, label="old")"#,
167            r#"set_label(address=CODE:0x0, label="new")"#,
168        );
169    }
170
171    #[test]
172    fn removed_facts_emit_clear() {
173        let base = db(r#"set_label(address=CODE:0x0, label="reset")
174set_comment(address=CODE:0x2, comment="hi")"#);
175        // Working state kept the comment but dropped the label.
176        let target = db(r#"set_comment(address=CODE:0x2, comment="hi")"#);
177        let diff = to_dsl_many(&target.diff_from(&base));
178        assert!(
179            diff.contains("clear_label(addresses=CODE:{0x0})"),
180            "diff: {diff}"
181        );
182        assert!(
183            !diff.contains("clear_comment"),
184            "unchanged comment must not clear: {diff}"
185        );
186        assert_roundtrip(
187            r#"set_label(address=CODE:0x0, label="reset")
188set_comment(address=CODE:0x2, comment="hi")"#,
189            r#"set_comment(address=CODE:0x2, comment="hi")"#,
190        );
191    }
192}