Skip to main content

i8051_disassembler/region/
weak.rs

1//! Auto-disassembly derivation: roots produce a weak code layer computed from
2//! the bytes and the barriers. [`Region`](super::Region) owns the strong layer
3//! and the [`CodeSource`] here, and composes strong over weak on read.
4
5use std::collections::{BTreeMap, BTreeSet};
6
7use crate::address::AddressValue;
8use crate::db::{Equivalent, EquivalentKind, EquivalentRange};
9use crate::platform::{ControlFlow, DecodedInsn};
10
11/// What the traversal reads from the region. Strong *code* is intentionally not
12/// exposed, so the traversal flows through code islands and re-derives them.
13pub(crate) trait CodeSource {
14    fn decode(&self, addr: AddressValue) -> Option<DecodedInsn>;
15    /// The kind of the first barrier overlapping `[addr, addr + len)`, if any.
16    fn barrier_in(&self, addr: AddressValue, len: AddressValue) -> Option<EquivalentKind>;
17}
18
19#[derive(Debug, Clone, PartialEq, Eq)]
20pub enum AutoDisassembleError {
21    /// Flow reached bytes that could not be claimed as code: a barrier, or an
22    /// overlap with other code.
23    Overlapped(EquivalentKind),
24}
25
26#[must_use]
27#[derive(Debug, Clone, PartialEq, Eq, Default)]
28pub struct AutoDisassembleResult {
29    pub success: Vec<AddressValue>,
30    pub errors: Vec<(AddressValue, AutoDisassembleError)>,
31}
32
33impl AutoDisassembleResult {
34    pub fn is_success(&self) -> bool {
35        self.errors.is_empty()
36    }
37
38    pub fn unwrap_success(self) -> Vec<AddressValue> {
39        if let Some((addr, _)) = self.errors.first() {
40            panic!("auto-disassembly failed at {addr:04X}");
41        }
42        self.success
43    }
44}
45
46/// The derived layer: the roots and the code reachable from them.
47#[derive(Debug, Default, Clone, PartialEq, Eq)]
48pub(crate) struct Weak {
49    roots: BTreeSet<AddressValue>,
50    code: BTreeMap<AddressValue, EquivalentRange>,
51}
52
53impl Weak {
54    pub fn code(&self) -> &BTreeMap<AddressValue, EquivalentRange> {
55        &self.code
56    }
57
58    pub fn roots(&self) -> impl Iterator<Item = AddressValue> + '_ {
59        self.roots.iter().copied()
60    }
61
62    pub fn contains_root(&self, root: AddressValue) -> bool {
63        self.roots.contains(&root)
64    }
65
66    pub fn remove_root(&mut self, root: AddressValue) -> bool {
67        self.roots.remove(&root)
68    }
69
70    /// Any derived code intersecting `[offset, offset + span)`.
71    pub fn overlaps(&self, offset: AddressValue, span: AddressValue) -> bool {
72        let end = offset.saturating_add(span);
73        self.code.range(offset..end).next().is_some()
74            || matches!(self.code.range(..offset).next_back(), Some((_, r)) if r.end > offset)
75    }
76
77    /// Re-derive from scratch for changes that can shrink the layer: a barrier
78    /// added over existing code, bytes changed, or a root removed.
79    pub fn refresh(&mut self, src: &impl CodeSource) {
80        self.code.clear();
81        let roots: Vec<AddressValue> = self.roots.iter().copied().collect();
82        for root in roots {
83            let _ = self.trace(src, root);
84        }
85    }
86
87    /// Record `root` and fold in its newly-reached code, halting at code already
88    /// derived so a root costs only its new reach. Returns the diagnostics.
89    pub fn extend(&mut self, src: &impl CodeSource, root: AddressValue) -> AutoDisassembleResult {
90        self.roots.insert(root);
91        self.trace(src, root)
92    }
93
94    fn trace(&mut self, src: &impl CodeSource, root: AddressValue) -> AutoDisassembleResult {
95        let overlap = |addr, kind| (addr, AutoDisassembleError::Overlapped(kind));
96        let mut result = AutoDisassembleResult::default();
97        let mut queue = vec![root];
98        while let Some(addr) = queue.pop() {
99            if let Some((start, _)) = covering(&self.code, addr) {
100                if start != addr {
101                    result.errors.push(overlap(addr, EquivalentKind::Code));
102                }
103                continue;
104            }
105            if let Some(kind) = src.barrier_in(addr, 1) {
106                result.errors.push(overlap(addr, kind));
107                continue;
108            }
109            let Some(insn) = src.decode(addr) else {
110                result.errors.push(overlap(addr, EquivalentKind::Code));
111                continue;
112            };
113            let len = insn.len() as AddressValue;
114            if let Some(kind) = src.barrier_in(addr, len) {
115                result.errors.push(overlap(addr, kind));
116                continue;
117            }
118            if self.overlaps(addr, len) {
119                result.errors.push(overlap(addr, EquivalentKind::Code));
120                continue;
121            }
122            self.code.insert(
123                addr,
124                EquivalentRange {
125                    end: addr + len,
126                    equivalent: Equivalent::Code,
127                },
128            );
129            result.success.push(addr);
130            match insn.control_flow() {
131                ControlFlow::Continue { next } => queue.push(next),
132                ControlFlow::Jump { target } => queue.push(target),
133                ControlFlow::Call { target, return_pc } => {
134                    queue.push(return_pc);
135                    queue.push(target);
136                }
137                ControlFlow::Choice {
138                    fall_through,
139                    branch_target,
140                } => {
141                    queue.push(fall_through);
142                    queue.push(branch_target);
143                }
144                ControlFlow::Diverge => {}
145            }
146        }
147        result
148    }
149}
150
151/// The entry covering `offset`: an exact start, or a preceding range containing it.
152fn covering(
153    code: &BTreeMap<AddressValue, EquivalentRange>,
154    offset: AddressValue,
155) -> Option<(AddressValue, &EquivalentRange)> {
156    if let Some(range) = code.get(&offset) {
157        return Some((offset, range));
158    }
159    match code.range(..=offset).next_back() {
160        Some((&start, range)) if offset < range.end => Some((start, range)),
161        _ => None,
162    }
163}