Skip to main content

i8051_disassembler/
region.rs

1use std::collections::BTreeMap;
2use std::ops::RangeBounds;
3use std::range::Range;
4use std::sync::OnceLock;
5
6mod weak;
7mod xrefs;
8
9pub use weak::{AutoDisassembleError, AutoDisassembleResult};
10use weak::{CodeSource, Weak};
11use xrefs::Xrefs;
12
13use crate::address::{AddressRange, AddressSpace, AddressValue, PhysicalAddr, Xref, XrefType};
14use crate::commands::{
15    AutoDisassemble, Command, DisassembleRange, MapBytes, MarkData, MarkUnknown, OverrideOperand,
16    SetComment, SetConstantBytes, SetFunction, SetLabel, boxed,
17};
18use crate::db::{
19    Equivalent, EquivalentAt, EquivalentKind, EquivalentRange, Error, ErrorKind, Function,
20    OperandOverride, SpaceUsage,
21};
22use crate::labels::{ImplicitLabels, LabelCollector, LabelKind, Labels};
23use crate::pattern::BytePattern;
24use crate::platform::{
25    ControlFlow, DecodedInsn, PlatformRef, branch_target, branch_target_operand_index,
26    xrefs_from_instruction,
27};
28use crate::render::Line;
29
30#[derive(Debug, Clone)]
31pub enum ByteRange {
32    Mapped(String, usize, Vec<u8>),
33    Constant(AddressValue, u8),
34}
35
36impl ByteRange {
37    pub fn len(&self) -> AddressValue {
38        match self {
39            ByteRange::Mapped(_, _, data) => data.len() as AddressValue,
40            ByteRange::Constant(size, _) => *size,
41        }
42    }
43
44    pub fn is_empty(&self) -> bool {
45        self.len() == 0
46    }
47}
48
49/// A basic block in a routine's control-flow graph: a maximal straight-line run
50/// of instructions `[start, end)` with the starts of its successor blocks.
51#[derive(Debug, Clone, PartialEq, Eq)]
52pub struct Block {
53    pub start: AddressValue,
54    pub end: AddressValue,
55    pub successors: Vec<AddressValue>,
56}
57
58/// A referenced control-flow target that is not a clean instruction start.
59/// Either the decode has not reached it (`misaligned` false), or it lands
60/// inside an already-decoded instruction (`misaligned` true, a decode error
61/// upstream).
62#[derive(Debug, Clone, Copy)]
63pub(crate) struct ControlTarget {
64    pub target: AddressValue,
65    pub kind: XrefType,
66    pub from: AddressValue,
67    pub misaligned: bool,
68}
69
70/// A decoded run whose successor is not code: execution leaves known code.
71#[derive(Debug, Clone, Copy)]
72pub(crate) struct FlowLeak {
73    pub from: AddressValue,
74    pub to: AddressValue,
75    pub kind: LeakKind,
76}
77
78/// Where a [`FlowLeak`] lands.
79#[derive(Debug, Clone, Copy, PartialEq, Eq)]
80pub(crate) enum LeakKind {
81    /// Into mapped bytes carrying no equivalent yet.
82    IntoUndefined,
83    /// Into bytes typed as data.
84    IntoData,
85    /// Past the end of mapped bytes.
86    OffEnd,
87}
88
89/// One instruction from a scratch decode (see [`Region::scratch_decode`]).
90#[derive(Debug, Clone)]
91pub struct ScratchInsn {
92    pub addr: AddressValue,
93    pub text: String,
94    pub bytes: Vec<u8>,
95    /// The branch/call target, if the instruction has one.
96    pub target: Option<AddressValue>,
97    /// Whether `target` points at a mapped byte. A target beyond the loaded
98    /// image is strong evidence the bytes are not really code.
99    pub target_mapped: bool,
100    /// Whether `target` lands inside an existing instruction rather than at its
101    /// start. Also strong evidence the bytes are not really code.
102    pub target_misaligned: bool,
103    /// Whether `target` lands inside another instruction of this same decode (a
104    /// self-misalignment suggests this is not code).
105    pub target_self_misaligned: bool,
106}
107
108/// The result of decoding bytes as code without committing them: a look before
109/// leaping to a real disassemble.
110#[derive(Debug, Clone, Default)]
111pub struct ScratchDecode {
112    pub lines: Vec<ScratchInsn>,
113    /// Flow ended at a return or unconditional jump (a clean block end).
114    pub terminates: bool,
115    /// Decoding stopped early because an opcode ran past the mapped bytes.
116    pub ran_out: bool,
117    /// How many decoded targets point outside the loaded image.
118    pub out_of_range_targets: usize,
119    /// How many decoded targets land inside an existing instruction.
120    pub misaligned_targets: usize,
121    /// How many decoded targets land inside another instruction of this same
122    /// decode.
123    pub self_misaligned_targets: usize,
124}
125
126/// Flag every target that lands inside another instruction of the same decode,
127/// and total them into [`ScratchDecode::self_misaligned_targets`].
128///
129/// Run after the decode completes, because a target may point forward at an
130/// instruction not yet decoded when its branch was read.
131fn mark_self_misaligned(decode: &mut ScratchDecode) {
132    let starts: std::collections::BTreeSet<AddressValue> =
133        decode.lines.iter().map(|insn| insn.addr).collect();
134    let (Some(first), Some(last)) = (decode.lines.first(), decode.lines.last()) else {
135        return;
136    };
137    let span = first.addr..last.addr.saturating_add(last.bytes.len() as AddressValue);
138
139    let mut count = 0;
140    for insn in &mut decode.lines {
141        let Some(target) = insn.target else { continue };
142        if span.contains(&target) && !starts.contains(&target) {
143            insn.target_self_misaligned = true;
144            count += 1;
145        }
146    }
147    decode.self_misaligned_targets = count;
148}
149
150/// What an instruction's ambiguous operand resolves to.
151#[derive(Debug, Clone, Copy, PartialEq, Eq)]
152pub enum OperandType {
153    /// An address in this space.
154    Pointer(AddressSpace),
155    /// A number, e.g.: a count, a mask, a register being cleared.
156    Value,
157}
158
159/// How a label behaves beyond its text.
160#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
161pub struct LabelAttrs {
162    /// A working guess, left on the naming worklist.
163    pub provisional: bool,
164    /// Scoped to the enclosing routine, so its name need only be unique there.
165    pub local: bool,
166}
167
168/// The nearest scope-delimiting label at or before `offset`.
169fn scope_in(
170    globals: &std::collections::BTreeSet<AddressValue>,
171    offset: AddressValue,
172) -> Option<AddressValue> {
173    globals.range(..=offset).next_back().copied()
174}
175
176pub struct Region {
177    space: AddressSpace,
178    /// The driver that decodes this region's bytes. `None` until a CPU is set,
179    /// in which case nothing decodes.
180    platform: Option<PlatformRef>,
181    byte_ranges: BTreeMap<AddressValue, ByteRange>,
182    equivalents: BTreeMap<AddressValue, EquivalentRange>,
183    labels: BTreeMap<AddressValue, String>,
184    /// Addresses whose label is a working guess.
185    draft_labels: std::collections::BTreeSet<AddressValue>,
186    /// Addresses whose label is scoped to the routine containing it. Its name
187    /// only has to be unique within that routine, so the same `.loop` may name
188    /// a loop in every routine that has one.
189    local_labels: std::collections::BTreeSet<AddressValue>,
190    /// What an instruction's ambiguous operand turned out to mean, keyed by the
191    /// instruction.
192    operand_types: BTreeMap<AddressValue, OperandType>,
193    /// Platform addresses we've chosen to disable (w/ a reason).
194    disabled_platform_addresses: BTreeMap<AddressValue, String>,
195    /// How many address lines the board actually decodes for this space, `None`
196    /// means every line is decoded.
197    address_bits: Option<u8>,
198    comments: BTreeMap<AddressValue, String>,
199    functions: BTreeMap<AddressValue, Function>,
200    /// Operand overrides, keyed by `(instruction address, operand index)`.
201    overrides: BTreeMap<(AddressValue, u8), OperandOverride>,
202    /// The derived auto-disassembly layer (roots + their code). Reads overlay
203    /// `equivalents` over `weak.code()`. Never serialized.
204    weak: Weak,
205    /// Reverse cross-reference index, derived from the code. Cleared on every
206    /// code change and rebuilt on the next read. Never serialized.
207    xrefs: OnceLock<Xrefs>,
208}
209
210impl Region {
211    pub fn new(space: AddressSpace, platform: Option<PlatformRef>) -> Self {
212        Self {
213            space,
214            platform,
215            byte_ranges: BTreeMap::new(),
216            equivalents: BTreeMap::new(),
217            labels: BTreeMap::new(),
218            address_bits: None,
219            disabled_platform_addresses: BTreeMap::new(),
220            operand_types: BTreeMap::new(),
221            draft_labels: std::collections::BTreeSet::new(),
222            local_labels: std::collections::BTreeSet::new(),
223            comments: BTreeMap::new(),
224            functions: BTreeMap::new(),
225            overrides: BTreeMap::new(),
226            weak: Weak::default(),
227            xrefs: OnceLock::new(),
228        }
229    }
230
231    /// Swap the decoding driver and re-derive, since decode results change.
232    pub(crate) fn set_platform(&mut self, platform: Option<PlatformRef>) {
233        self.platform = platform;
234        self.refresh_weak();
235        self.invalidate_xrefs();
236    }
237
238    /// Record what the ambiguous operand of the instruction at `offset` names.
239    pub fn set_operand_type(
240        &mut self,
241        offset: AddressValue,
242        kind: OperandType,
243    ) -> Option<OperandType> {
244        self.operand_types.insert(offset, kind)
245    }
246
247    /// Forget the decision for the instruction at `offset`.
248    pub fn clear_operand_type(&mut self, offset: AddressValue) -> Option<OperandType> {
249        self.operand_types.remove(&offset)
250    }
251
252    pub fn operand_type(&self, offset: AddressValue) -> Option<OperandType> {
253        self.operand_types.get(&offset).copied()
254    }
255
256    /// Every disambiguated operand, in address order.
257    pub fn operand_types(&self) -> impl Iterator<Item = (AddressValue, OperandType)> + '_ {
258        self.operand_types.iter().map(|(&addr, &kind)| (addr, kind))
259    }
260
261    /// Targets reached only by inferred pointer references, as
262    /// `(target, how many, the earliest source)`.
263    pub(crate) fn inferred_pointer_candidates(&self) -> Vec<(PhysicalAddr, usize, AddressValue)> {
264        let mut out = Vec::new();
265        for (target, edges) in self.xref_index().targets() {
266            let sources: Vec<AddressValue> = edges
267                .iter()
268                .filter(|e| {
269                    e.kind == XrefType::Pointer
270                        && e.certainty == crate::platform::Certainty::Inferred
271                })
272                .map(|e| e.from)
273                .collect();
274            let Some(&first) = sources.iter().min() else {
275                continue;
276            };
277            out.push((*target, sources.len(), first));
278        }
279        out.sort_unstable_by_key(|(t, _, _)| (t.offset, t.space));
280        out
281    }
282
283    /// The instructions that produce an inferred pointer to `target`.
284    pub(crate) fn pointer_sources(&self, target: &PhysicalAddr) -> Vec<AddressValue> {
285        self.xref_index()
286            .to(target)
287            .iter()
288            .filter(|e| {
289                e.kind == XrefType::Pointer && e.certainty == crate::platform::Certainty::Inferred
290            })
291            .map(|e| e.from)
292            .collect()
293    }
294
295    /// Record that a platform address is disabled. Returns the previous reason,
296    /// if it was already disabled.
297    pub fn disable_platform_address(
298        &mut self,
299        offset: AddressValue,
300        reason: String,
301    ) -> Option<String> {
302        self.disabled_platform_addresses.insert(offset, reason)
303    }
304
305    /// Restore the platform's claim about `offset`, returning the reason it had.
306    pub fn enable_platform_address(&mut self, offset: AddressValue) -> Option<String> {
307        self.disabled_platform_addresses.remove(&offset)
308    }
309
310    pub fn platform_address_disabled(&self, offset: AddressValue) -> bool {
311        self.disabled_platform_addresses.contains_key(&offset)
312    }
313
314    /// Every disabled address with its reason, in address order.
315    pub fn disabled_platform_addresses(&self) -> impl Iterator<Item = (AddressValue, &str)> + '_ {
316        self.disabled_platform_addresses
317            .iter()
318            .map(|(&addr, reason)| (addr, reason.as_str()))
319    }
320
321    /// Narrow this space to the address lines the board decodes. `None` restores
322    /// the full width. Returns the previous setting.
323    pub fn set_address_bits(&mut self, bits: Option<u8>) -> Option<u8> {
324        let previous = self.address_bits;
325        self.address_bits = bits;
326        self.invalidate_xrefs();
327        previous
328    }
329
330    pub fn address_bits(&self) -> Option<u8> {
331        self.address_bits
332    }
333
334    /// The byte an address actually reaches after `set_address_bits` is applied.
335    pub fn effective(&self, offset: AddressValue) -> AddressValue {
336        match self.address_bits {
337            Some(bits) if (bits as u32) < AddressValue::BITS => offset & ((1u32 << bits) - 1),
338            _ => offset,
339        }
340    }
341
342    /// Set or clear the override at `(addr, index)`, returning the prior value.
343    pub fn set_operand_override(
344        &mut self,
345        addr: AddressValue,
346        index: u8,
347        value: Option<OperandOverride>,
348    ) -> Option<OperandOverride> {
349        match value {
350            Some(value) => self.overrides.insert((addr, index), value),
351            None => self.overrides.remove(&(addr, index)),
352        }
353    }
354
355    /// Operand overrides for the instruction at `addr`, as a positional vec.
356    fn operand_overrides_at(&self, addr: AddressValue) -> Vec<Option<OperandOverride>> {
357        let mut out = Vec::new();
358        for (&(_, index), value) in self.overrides.range((addr, 0)..=(addr, u8::MAX)) {
359            let index = index as usize;
360            if out.len() <= index {
361                out.resize(index + 1, None);
362            }
363            out[index] = Some(value.clone());
364        }
365        out
366    }
367
368    /// Lift the weak layer out to derive against `self` (which supplies the
369    /// bytes and barriers via [`CodeSource`]), then put it back. The take avoids
370    /// borrowing `self` mutably and immutably at once.
371    fn with_weak<R>(&mut self, f: impl FnOnce(&mut Weak, &Self) -> R) -> R {
372        let mut weak = std::mem::take(&mut self.weak);
373        let result = f(&mut weak, self);
374        self.weak = weak;
375        result
376    }
377
378    fn refresh_weak(&mut self) {
379        self.with_weak(|weak, src| weak.refresh(src));
380    }
381
382    /// Drop the cached xref index. Cheap: the rebuild is deferred to the next
383    /// read, so a bulk load pays for one rebuild, not one per command.
384    fn invalidate_xrefs(&mut self) {
385        self.xrefs.take();
386    }
387
388    /// The reverse xref index, built on demand and cached until the next code
389    /// change. Reads `self` (bytes, equivalents, weak) to derive the edges.
390    fn xref_index(&self) -> &Xrefs {
391        self.xrefs.get_or_init(|| Xrefs::build(self))
392    }
393
394    /// Auto-disassemble from `start`, recording it as a root (so the export is
395    /// one `auto_disassemble` command). Returns the traversal diagnostics.
396    pub fn auto_disassemble(&mut self, start: AddressValue) -> AutoDisassembleResult {
397        let result = self.with_weak(|weak, src| weak.extend(src, start));
398        self.invalidate_xrefs();
399        result
400    }
401
402    pub fn add_auto_root(&mut self, start: AddressValue) {
403        let _ = self.auto_disassemble(start);
404    }
405
406    /// Removing a root re-derives weak, so code reachable only through it drops.
407    pub fn remove_auto_root(&mut self, start: AddressValue) -> bool {
408        let removed = self.weak.remove_root(start);
409        if removed {
410            self.refresh_weak();
411            self.invalidate_xrefs();
412        }
413        removed
414    }
415
416    pub fn is_auto_root(&self, start: AddressValue) -> bool {
417        self.weak.contains_root(start)
418    }
419
420    fn is_code_start(&self, offset: AddressValue) -> bool {
421        matches!(
422            self.equivalents.get(&offset).map(|r| r.equivalent.kind()),
423            Some(EquivalentKind::Code)
424        ) || self.weak.code().contains_key(&offset)
425    }
426
427    /// If `addr` is a pure thunk, its forwarding target. A pure thunk is a code
428    /// instruction whose entire body is one unconditional jump.
429    fn thunk_target(&self, addr: AddressValue) -> Option<AddressValue> {
430        if !self.is_code_start(addr) {
431            return None;
432        }
433        match self.decode_at(addr)?.control_flow() {
434            ControlFlow::Jump { target } => Some(target),
435            _ => None,
436        }
437    }
438
439    /// Follow pure jump thunks from `addr` to the ultimate target. Returns
440    /// `addr` unchanged when it is not a thunk, and treats a jump cycle as not
441    /// a thunk at all. The hop cap bounds degenerate chains.
442    pub(crate) fn resolve_thunks(&self, addr: AddressValue) -> AddressValue {
443        const MAX_HOPS: usize = 16;
444        let mut seen = [addr; MAX_HOPS];
445        let mut current = addr;
446        for hops in 1..MAX_HOPS {
447            let Some(next) = self.thunk_target(current) else {
448                break;
449            };
450            if seen[..hops].contains(&next) {
451                return addr;
452            }
453            seen[hops] = next;
454            current = next;
455        }
456        current
457    }
458
459    /// The control-flow graph of the routine rooted at `entry`: maximal
460    /// straight-line blocks split at branch targets and terminators. Calls fall
461    /// through, except a call to a `noreturn` function, which ends its block.
462    /// Derived on demand from the xref index and the linear code.
463    pub(crate) fn basic_blocks(&self, entry: AddressValue) -> Vec<Block> {
464        let index = self.xref_index();
465        // Only control-flow edges make a leader. A data reference to a code
466        // address (a table read, say) does not split a block.
467        let is_leader = |addr: AddressValue| {
468            index
469                .to(&PhysicalAddr {
470                    space: self.space,
471                    offset: addr,
472                })
473                .iter()
474                .any(|e| matches!(e.kind, XrefType::Call | XrefType::Jump))
475        };
476        let mut blocks: BTreeMap<AddressValue, Block> = BTreeMap::new();
477        let mut worklist = vec![entry];
478        while let Some(start) = worklist.pop() {
479            if blocks.contains_key(&start) || !self.is_code_start(start) {
480                continue;
481            }
482            let mut addr = start;
483            let (end, successors) = loop {
484                let Some(insn) = self.decode_at(addr) else {
485                    break (addr, vec![]);
486                };
487                let next = addr + insn.len() as AddressValue;
488                // `Some` ends the block with those successors. `None` extends it.
489                let ended = match insn.control_flow() {
490                    ControlFlow::Jump { target } => Some(vec![target]),
491                    ControlFlow::Choice {
492                        fall_through,
493                        branch_target,
494                    } => Some(vec![fall_through, branch_target]),
495                    ControlFlow::Diverge => Some(vec![]),
496                    ControlFlow::Call { target, return_pc } => {
497                        if self.functions.get(&target).is_some_and(|f| f.noreturn) {
498                            Some(vec![])
499                        } else if is_leader(return_pc) {
500                            Some(vec![return_pc])
501                        } else {
502                            None
503                        }
504                    }
505                    ControlFlow::Continue { next } => is_leader(next).then(|| vec![next]),
506                };
507                match ended {
508                    Some(successors) => break (next, successors),
509                    None => addr = next,
510                }
511            };
512            for &succ in &successors {
513                worklist.push(succ);
514            }
515            blocks.insert(
516                start,
517                Block {
518                    start,
519                    end,
520                    successors,
521                },
522            );
523        }
524        blocks.into_values().collect()
525    }
526
527    /// Every code instruction start across both layers, deduplicated.
528    fn code_offsets(&self) -> Vec<AddressValue> {
529        let mut offsets: Vec<AddressValue> = self
530            .equivalents
531            .iter()
532            .filter(|(_, range)| matches!(range.equivalent, Equivalent::Code))
533            .map(|(&offset, _)| offset)
534            .collect();
535        for &offset in self.weak.code().keys() {
536            if !self.equivalents.contains_key(&offset) {
537                offsets.push(offset);
538            }
539        }
540        offsets
541    }
542
543    /// Nearest strong or weak start at/after `after`. Bounds undefined runs.
544    fn next_equivalent_boundary(&self, after: AddressValue) -> Option<AddressValue> {
545        let next_strong = self.equivalents.range(after..).next().map(|(&k, _)| k);
546        let next_weak = self.weak.code().range(after..).next().map(|(&k, _)| k);
547        [next_strong, next_weak].into_iter().flatten().min()
548    }
549
550    pub fn set_bytes(
551        &mut self,
552        file: &str,
553        file_offset: usize,
554        offset: AddressValue,
555        bytes: &[u8],
556    ) {
557        self.map_bytes(file, file_offset, offset, bytes);
558    }
559
560    pub fn map_bytes(
561        &mut self,
562        file: &str,
563        file_offset: usize,
564        offset: AddressValue,
565        bytes: &[u8],
566    ) {
567        if !bytes.is_empty() {
568            self.unmap_bytes(offset, bytes.len() as AddressValue);
569        }
570        self.byte_ranges.insert(
571            offset,
572            ByteRange::Mapped(file.to_string(), file_offset, bytes.to_vec()),
573        );
574        self.refresh_weak();
575        self.invalidate_xrefs();
576    }
577
578    pub fn set_constant(&mut self, offset: AddressValue, size: AddressValue, value: u8) {
579        if size == 0 {
580            return;
581        }
582        self.unmap_bytes(offset, size);
583        self.byte_ranges
584            .insert(offset, ByteRange::Constant(size, value));
585        self.refresh_weak();
586        self.invalidate_xrefs();
587    }
588
589    pub fn find_bytes(&self, pattern: &BytePattern) -> impl Iterator<Item = Range<AddressValue>> {
590        self.find_bytes_in(pattern, ..)
591    }
592
593    /// Find bytes in a specific range (`..` searches the whole region).
594    ///
595    /// Cross-byte-range matches and constant-byte-range matches do not
596    /// currently work.
597    pub fn find_bytes_in(
598        &self,
599        pattern: &BytePattern,
600        range: impl RangeBounds<AddressValue>,
601    ) -> impl Iterator<Item = Range<AddressValue>> {
602        let range = AddressRange::from(range);
603        let end_inclusive = range.end.saturating_sub(1);
604        self.byte_ranges
605            .iter()
606            .filter_map(move |(addr, byte_range)| match byte_range {
607                ByteRange::Mapped(_, _, data) => {
608                    if ranges_overlap_inclusive(
609                        range.start,
610                        end_inclusive,
611                        *addr,
612                        *addr + data.len() as AddressValue,
613                    ) {
614                        let data_start = range.start.saturating_sub(*addr) as usize;
615                        let data_end = end_inclusive
616                            .saturating_sub(*addr)
617                            .min((data.len() - 1) as AddressValue)
618                            as usize;
619                        Some(
620                            pattern
621                                .find_all(&data[data_start..=data_end])
622                                .map(move |range| {
623                                    Range::from(
624                                        range
625                                            .start
626                                            .saturating_add(data_start)
627                                            .saturating_add(*addr as usize)
628                                            ..range
629                                                .end
630                                                .saturating_add(data_start)
631                                                .saturating_add(*addr as usize),
632                                    )
633                                }),
634                        )
635                    } else {
636                        None
637                    }
638                }
639                ByteRange::Constant(..) => None,
640            })
641            .flatten()
642            .map(|range| Range::from(range.start as AddressValue..range.end as AddressValue))
643    }
644
645    pub(crate) fn snapshot_byte_ranges(
646        &self,
647        offset: AddressValue,
648        size: AddressValue,
649    ) -> Vec<(AddressValue, ByteRange)> {
650        if size == 0 {
651            return Vec::new();
652        }
653        let end = offset.saturating_add(size);
654        self.byte_ranges
655            .iter()
656            .filter(|(start, range)| range.len() > offset && **start < end)
657            .map(|(start, range)| (*start as AddressValue, range.clone()))
658            .collect()
659    }
660
661    pub fn unmap_bytes(&mut self, offset: AddressValue, size: AddressValue) {
662        if size == 0 {
663            return;
664        }
665        let end = offset.saturating_add(size);
666        let mut kept = BTreeMap::new();
667
668        for (&start, range) in &self.byte_ranges {
669            match range {
670                ByteRange::Mapped(file, file_offset, data) => {
671                    let range_end = start.saturating_add(data.len() as AddressValue);
672                    if range_end <= offset || start >= end {
673                        kept.insert(start, range.clone());
674                        continue;
675                    }
676                    if start < offset {
677                        let keep_len = offset - start;
678                        kept.insert(
679                            start,
680                            ByteRange::Mapped(
681                                file.clone(),
682                                *file_offset,
683                                data[..keep_len as usize].to_vec(),
684                            ),
685                        );
686                    }
687                    if range_end > end {
688                        let skip = end.saturating_sub(start);
689                        kept.insert(
690                            end,
691                            ByteRange::Mapped(
692                                file.clone(),
693                                file_offset.saturating_add(skip as usize),
694                                data[skip as _..].to_vec(),
695                            ),
696                        );
697                    }
698                }
699                ByteRange::Constant(count, value) => {
700                    let range_end = start.saturating_add(*count);
701                    if range_end <= offset || start >= end {
702                        kept.insert(start, range.clone());
703                        continue;
704                    }
705                    if start < offset {
706                        kept.insert(start, ByteRange::Constant(offset - start, *value));
707                    }
708                    if range_end > end {
709                        kept.insert(end, ByteRange::Constant(range_end - end, *value));
710                    }
711                }
712            }
713        }
714
715        self.byte_ranges = kept;
716        self.refresh_weak();
717        self.invalidate_xrefs();
718    }
719
720    pub fn set_equivalent(
721        &mut self,
722        offset: AddressValue,
723        equivalent: Equivalent,
724    ) -> Result<&EquivalentRange, Error> {
725        if self.has_equivalent(offset) {
726            let (start, end, existing) = match self.get_equivalent(offset) {
727                EquivalentAt::Defined { start, range } => {
728                    (start, range.end, range.equivalent.kind())
729                }
730                EquivalentAt::Undefined(range) => (range.start, range.end, EquivalentKind::Unknown),
731            };
732            let requested_end = self
733                .equivalent_span(offset, &equivalent)
734                .map(|span| offset.saturating_add(span))
735                .unwrap_or(offset.saturating_add(1));
736            return Err(crate::db::already_classified(
737                (self.space, offset).into(),
738                existing,
739                start,
740                end,
741                requested_end,
742            ));
743        }
744
745        let span = self.equivalent_span(offset, &equivalent)?;
746        self.validate_equivalent_bounds(offset, span)?;
747        self.validate_no_equivalent_overlap(offset, span)?;
748
749        // Only a barrier landing on already-derived code forces a re-derive (a
750        // chop). A code island, or a barrier over undefined bytes, leaves weak as-is.
751        let kind = equivalent.kind();
752        let chops_weak = kind != EquivalentKind::Code && self.weak.overlaps(offset, span);
753        self.equivalents.insert(
754            offset,
755            EquivalentRange {
756                end: offset.saturating_add(span),
757                equivalent,
758            },
759        );
760        if chops_weak {
761            self.refresh_weak();
762            self.invalidate_xrefs();
763        } else if kind == EquivalentKind::Code {
764            // A strong code island adds a new instruction source.
765            self.invalidate_xrefs();
766        }
767        Ok(&self.equivalents[&offset])
768    }
769
770    pub fn clear_equivalents(&mut self, offset: AddressValue, size: AddressValue) {
771        if size == 0 {
772            return;
773        }
774        let end = offset.saturating_add(size);
775        self.equivalents
776            .retain(|&start, range| range.end <= offset || start >= end);
777        self.refresh_weak();
778        self.invalidate_xrefs();
779    }
780
781    /// Linear-sweep `[start, end)` as strong code. Errors (mutating nothing) on
782    /// a byte that doesn't decode or a strong overlap. The final instruction may
783    /// run past `end`. Returns the actual end.
784    pub(crate) fn disassemble_linear(
785        &mut self,
786        start: AddressValue,
787        end: AddressValue,
788    ) -> Result<AddressValue, Error> {
789        // Validate up front so the inserts below can't fail, then re-derive weak once.
790        let mut addr = start;
791        let mut spans = Vec::new();
792        while addr < end {
793            let insn = self
794                .decode_at(addr)
795                .ok_or_else(|| Error::from(ErrorKind::InvalidEquivalent))?;
796            let insn_end = addr.saturating_add(insn.len() as AddressValue);
797            let overlaps = self.snapshot_equivalents(addr, insn_end - addr);
798            if let Some((at, range)) = overlaps.first() {
799                return Err(ErrorKind::Overlap {
800                    at: self.space.dsl_addr(*at),
801                    marked: crate::db::marked_word(range.equivalent.kind()).to_string(),
802                }
803                .into());
804            }
805            spans.push((addr, insn_end));
806            addr = insn_end;
807        }
808        for (offset, insn_end) in spans {
809            self.equivalents.insert(
810                offset,
811                EquivalentRange {
812                    end: insn_end,
813                    equivalent: Equivalent::Code,
814                },
815            );
816        }
817        self.refresh_weak();
818        self.invalidate_xrefs();
819        Ok(addr)
820    }
821
822    pub fn snapshot_equivalents(
823        &self,
824        offset: AddressValue,
825        size: AddressValue,
826    ) -> Vec<(AddressValue, EquivalentRange)> {
827        if size == 0 {
828            return Vec::new();
829        }
830        let end = offset.saturating_add(size);
831        self.equivalents
832            .iter()
833            .filter(|(start, range)| ranges_overlap(**start, range.end, offset, end))
834            .map(|(&start, range)| (start, range.clone()))
835            .collect()
836    }
837
838    /// Whether a *strong* equivalent covers `offset`. Strong-only: a barrier may
839    /// overwrite weak code, which then re-derives.
840    pub fn has_equivalent(&self, offset: AddressValue) -> bool {
841        lookup_in(&self.equivalents, offset).is_some()
842    }
843
844    pub fn get_equivalent_kind(&self, offset: AddressValue) -> Option<EquivalentKind> {
845        match self.equivalent_at(offset) {
846            EquivalentAt::Defined { range, .. } => Some(range.equivalent.kind()),
847            EquivalentAt::Undefined(_) => None,
848        }
849    }
850
851    pub fn get_equivalent(&self, offset: AddressValue) -> EquivalentAt<'_> {
852        self.equivalent_at(offset)
853    }
854
855    fn equivalent_at(&self, offset: AddressValue) -> EquivalentAt<'_> {
856        // Strong (data / unknown / code islands) overlays weak (derived code).
857        match lookup_in(&self.equivalents, offset).or_else(|| lookup_in(self.weak.code(), offset)) {
858            Some((start, range)) => EquivalentAt::Defined { start, range },
859            None => EquivalentAt::Undefined(self.undefined_range_at(offset)),
860        }
861    }
862
863    fn undefined_range_at(&self, offset: AddressValue) -> Range<AddressValue> {
864        let after = offset.saturating_add(1);
865        let next_eq = self.next_equivalent_boundary(after);
866        let next_lbl = self.labels.range(after..).next().map(|(&k, _)| k);
867        let next_cmt = self.comments.range(after..).next().map(|(&k, _)| k);
868        let end = [Some(self.end()), next_eq, next_lbl, next_cmt]
869            .into_iter()
870            .flatten()
871            .min()
872            .unwrap_or(self.end());
873        (offset..end).into()
874    }
875
876    /// Name `offset`.
877    pub fn set_label(&mut self, offset: AddressValue, label: &str, attrs: LabelAttrs) {
878        self.labels.insert(offset, label.to_string());
879        if attrs.provisional {
880            self.draft_labels.insert(offset);
881        } else {
882            self.draft_labels.remove(&offset);
883        }
884        if attrs.local {
885            self.local_labels.insert(offset);
886        } else {
887            self.local_labels.remove(&offset);
888        }
889    }
890
891    /// Whether the label at `offset` is scoped to its enclosing routine.
892    pub fn is_local_label(&self, offset: AddressValue) -> bool {
893        self.local_labels.contains(&offset)
894    }
895
896    /// The nearest non-local label at or before `offset`.
897    pub fn scope_of(&self, offset: AddressValue) -> Option<AddressValue> {
898        self.labels
899            .range(..=offset)
900            .rev()
901            .map(|(&at, _)| at)
902            .find(|at| !self.local_labels.contains(at))
903    }
904
905    /// Whether every reference to the local at `offset` comes from inside its
906    /// own scope.
907    fn local_is_self_contained(
908        &self,
909        offset: AddressValue,
910        globals: &std::collections::BTreeSet<AddressValue>,
911    ) -> bool {
912        let scope = scope_in(globals, offset);
913        let target = PhysicalAddr {
914            space: self.space,
915            offset,
916        };
917        self.xref_index()
918            .to(&target)
919            .iter()
920            .all(|edge| scope_in(globals, edge.from) == scope)
921    }
922
923    /// The name to emit for each labelled address as *assembly*.
924    pub(crate) fn export_names(&self, implicit: &Labels) -> BTreeMap<AddressValue, String> {
925        let globals: std::collections::BTreeSet<AddressValue> = self
926            .labels
927            .keys()
928            .copied()
929            .filter(|at| !self.local_labels.contains(at))
930            .chain(implicit.keys().copied())
931            .collect();
932
933        let mut out = BTreeMap::new();
934        let mut per_scope: BTreeMap<Option<AddressValue>, usize> = BTreeMap::new();
935        let mut seen: BTreeMap<String, usize> = BTreeMap::new();
936        for (&offset, name) in &self.labels {
937            if self.local_labels.contains(&offset) && self.local_is_self_contained(offset, &globals)
938            {
939                let n = per_scope.entry(scope_in(&globals, offset)).or_insert(0);
940                *n += 1;
941                out.insert(offset, format!("{n}$"));
942            } else {
943                let count = seen.entry(name.clone()).or_insert(0);
944                *count += 1;
945                let unique = if *count > 1 {
946                    format!("{name}_{}", *count - 1)
947                } else {
948                    name.clone()
949                };
950                out.insert(offset, unique);
951            }
952        }
953        out
954    }
955
956    /// Addresses reached only by pointer references and still unnamed, as
957    /// `(offset, how many, earliest source, every reference inferred)`.
958    pub(crate) fn unnamed_pointer_targets(&self) -> Vec<(AddressValue, usize, AddressValue, bool)> {
959        let mut out = Vec::new();
960        for (target, edges) in self.xref_index().targets() {
961            if target.space != self.space {
962                continue;
963            }
964            let offset = target.offset;
965            let pointers: Vec<&crate::region::xrefs::Edge> = edges
966                .iter()
967                .filter(|e| e.kind == XrefType::Pointer)
968                .collect();
969            if pointers.is_empty()
970                || self.get_label(offset).is_some()
971                || self.read_byte(offset).is_none()
972                // A pointer into decoded code is a code reference; the naming
973                // worklist already covers those.
974                || matches!(self.get_equivalent_kind(offset), Some(EquivalentKind::Code))
975            {
976                continue;
977            }
978            let first = pointers.iter().map(|e| e.from).min().unwrap_or(offset);
979            let inferred = pointers
980                .iter()
981                .all(|e| e.certainty == crate::platform::Certainty::Inferred);
982            out.push((offset, pointers.len(), first, inferred));
983        }
984        out.sort_unstable();
985        out
986    }
987
988    /// The extent of the instruction decoded at `offset`, if one starts there.
989    pub fn instruction_range(&self, offset: AddressValue) -> Option<(AddressValue, AddressValue)> {
990        match self.get_equivalent(offset) {
991            EquivalentAt::Defined { range, .. } if matches!(range.equivalent, Equivalent::Code) => {
992                Some((offset, range.end))
993            }
994            _ => None,
995        }
996    }
997
998    /// The instruction `offset` falls inside, if it is not at its start.
999    pub fn covering_instruction(
1000        &self,
1001        offset: AddressValue,
1002    ) -> Option<(AddressValue, AddressValue)> {
1003        match self.get_equivalent(offset) {
1004            EquivalentAt::Defined { start, range }
1005                if matches!(range.equivalent, Equivalent::Code) && start != offset =>
1006            {
1007                Some((start, range.end))
1008            }
1009            _ => None,
1010        }
1011    }
1012
1013    /// Narrowest address width covering every mapped byte.
1014    pub fn covering_address_bits(&self) -> u8 {
1015        let end = self.end();
1016        let mut bits = 1u8;
1017        while bits < 32 && (1u64 << bits) < u64::from(end) {
1018            bits += 1;
1019        }
1020        bits
1021    }
1022
1023    /// Unmapped stretches sitting between mapped bytes that should arguably be
1024    /// mapper or filled.
1025    pub fn mapping_gaps(&self) -> Vec<(AddressValue, AddressValue)> {
1026        let mut gaps = Vec::new();
1027        let mut previous_end: Option<AddressValue> = None;
1028        for (&start, range) in &self.byte_ranges {
1029            if let Some(end) = previous_end
1030                && start > end
1031            {
1032                gaps.push((end, start));
1033            }
1034            previous_end = Some(start + range.len());
1035        }
1036        gaps
1037    }
1038
1039    /// Whether `offset` has a mapped byte.
1040    pub fn has_byte(&self, offset: AddressValue) -> bool {
1041        self.read_byte(offset).is_some()
1042    }
1043
1044    /// Whether the label at `offset` is a working guess rather than finalized.
1045    pub fn is_draft_label(&self, offset: AddressValue) -> bool {
1046        self.draft_labels.contains(&offset)
1047    }
1048
1049    pub fn clear_label(&mut self, offset: AddressValue) {
1050        self.labels.remove(&offset);
1051        self.draft_labels.remove(&offset);
1052        self.local_labels.remove(&offset);
1053    }
1054
1055    pub fn get_label(&self, offset: AddressValue) -> Option<&str> {
1056        self.labels
1057            .get(&(offset as AddressValue))
1058            .map(String::as_str)
1059    }
1060
1061    pub fn set_comment(&mut self, offset: AddressValue, comment: &str) {
1062        self.comments
1063            .insert(offset as AddressValue, comment.to_string());
1064    }
1065
1066    pub fn clear_comment(&mut self, offset: AddressValue) {
1067        self.comments.remove(&(offset as AddressValue));
1068    }
1069
1070    pub fn get_comment(&self, offset: AddressValue) -> Option<&str> {
1071        self.comments
1072            .get(&(offset as AddressValue))
1073            .map(String::as_str)
1074    }
1075
1076    pub fn set_function(&mut self, function: Function) {
1077        self.functions
1078            .insert(function.addr.offset as AddressValue, function);
1079    }
1080
1081    pub fn get_function(&self, offset: AddressValue) -> Option<&Function> {
1082        self.functions.get(&(offset as AddressValue))
1083    }
1084
1085    /// Every label in this region, in ascending address order.
1086    pub fn labels(&self) -> impl Iterator<Item = (AddressValue, &str)> {
1087        self.labels
1088            .iter()
1089            .map(|(&addr, name)| (addr, name.as_str()))
1090    }
1091
1092    /// Every function in this region, in ascending address order.
1093    pub fn functions(&self) -> impl Iterator<Item = (AddressValue, &Function)> {
1094        self.functions.iter().map(|(&addr, func)| (addr, func))
1095    }
1096
1097    pub fn clear_function(&mut self, offset: AddressValue) {
1098        self.functions.remove(&(offset as AddressValue));
1099    }
1100
1101    /// Remove every label in `range`, returning the removed `(address, label)`
1102    /// pairs (for undo).
1103    pub fn clear_labels_in(
1104        &mut self,
1105        range: impl RangeBounds<AddressValue>,
1106    ) -> Vec<(AddressValue, String)> {
1107        let keys: Vec<AddressValue> = self.labels.range(range).map(|(&k, _)| k).collect();
1108        keys.into_iter()
1109            .filter_map(|k| {
1110                self.draft_labels.remove(&k);
1111                self.local_labels.remove(&k);
1112                self.labels.remove(&k).map(|v| (k, v))
1113            })
1114            .collect()
1115    }
1116
1117    /// Remove every comment in `range`, returning the removed pairs.
1118    pub fn clear_comments_in(
1119        &mut self,
1120        range: impl RangeBounds<AddressValue>,
1121    ) -> Vec<(AddressValue, String)> {
1122        let keys: Vec<AddressValue> = self.comments.range(range).map(|(&k, _)| k).collect();
1123        keys.into_iter()
1124            .filter_map(|k| self.comments.remove(&k).map(|v| (k, v)))
1125            .collect()
1126    }
1127
1128    /// Remove every function in `range`, returning the removed `(address,
1129    /// function)` pairs.
1130    pub fn clear_functions_in(
1131        &mut self,
1132        range: impl RangeBounds<AddressValue>,
1133    ) -> Vec<(AddressValue, Function)> {
1134        let keys: Vec<AddressValue> = self.functions.range(range).map(|(&k, _)| k).collect();
1135        keys.into_iter()
1136            .filter_map(|k| self.functions.remove(&k).map(|v| (k, v)))
1137            .collect()
1138    }
1139
1140    pub fn byte_at(&self, offset: AddressValue) -> Option<u8> {
1141        self.read_byte(offset)
1142    }
1143
1144    pub fn read_u16_le(&self, offset: AddressValue) -> Option<u16> {
1145        let low = self.read_byte(offset)?;
1146        let high = self.read_byte(offset.saturating_add(1))?;
1147        Some((low as u16) | ((high as u16) << 8))
1148    }
1149
1150    pub fn read_u16_be(&self, offset: AddressValue) -> Option<u16> {
1151        let high = self.read_byte(offset)?;
1152        let low = self.read_byte(offset.saturating_add(1))?;
1153        Some((high as u16) | ((low as u16) << 8))
1154    }
1155
1156    pub fn bytes_at(&self, offset: AddressValue, size: AddressValue) -> Vec<u8> {
1157        (0..size)
1158            .filter_map(|i| self.read_byte(offset + i))
1159            .collect()
1160    }
1161
1162    /// Count mapped bytes classified as code, data, or undefined (no equivalent).
1163    pub fn space_usage(&self) -> SpaceUsage {
1164        let mut usage = SpaceUsage::default();
1165        for (&start, range) in &self.equivalents {
1166            let span = range.end.saturating_sub(start);
1167            match &range.equivalent {
1168                Equivalent::Code => usage.code += span,
1169                Equivalent::Data(_, _) => usage.data += span,
1170                Equivalent::Unknown(_) => {} // counts as undefined, via subtraction below
1171            }
1172        }
1173        // Weak code, minus strong islands already counted.
1174        for (&start, range) in self.weak.code() {
1175            if !self.equivalents.contains_key(&start) {
1176                usage.code += range.end.saturating_sub(start);
1177            }
1178        }
1179
1180        let mapped: AddressValue = self.byte_ranges.values().map(ByteRange::len).sum();
1181
1182        usage.undefined = mapped.saturating_sub(usage.code).saturating_sub(usage.data);
1183
1184        usage
1185    }
1186
1187    /// Byte counts for the completeness assessment, deriving `undefined` from
1188    /// the actual undefined spans (so it is correct regardless of where mapped
1189    /// ranges are based).
1190    pub(crate) fn coverage(&self) -> SpaceUsage {
1191        let mut usage = SpaceUsage::default();
1192        for (&start, range) in &self.equivalents {
1193            let span = range.end.saturating_sub(start);
1194            match &range.equivalent {
1195                Equivalent::Code => usage.code += span,
1196                Equivalent::Data(_, _) => usage.data += span,
1197                Equivalent::Unknown(_) => {}
1198            }
1199        }
1200        for (&start, range) in self.weak.code() {
1201            if !self.equivalents.contains_key(&start) {
1202                usage.code += range.end.saturating_sub(start);
1203            }
1204        }
1205        usage.undefined = self.undefined_spans().iter().map(|(a, b)| b - a).sum();
1206        usage
1207    }
1208
1209    /// Half-open `[start, end)` spans of mapped bytes carrying no equivalent
1210    /// (rendered raw). Adjacent spans across byte-range boundaries coalesce.
1211    pub(crate) fn undefined_spans(&self) -> Vec<(AddressValue, AddressValue)> {
1212        let mut spans: Vec<(AddressValue, AddressValue)> = Vec::new();
1213        for (&start, byte_range) in &self.byte_ranges {
1214            let range_end = start.saturating_add(byte_range.len());
1215            let mut addr = start;
1216            while addr < range_end {
1217                match self.get_equivalent(addr) {
1218                    EquivalentAt::Undefined(run) => {
1219                        let end = run.end.min(range_end);
1220                        match spans.last_mut() {
1221                            Some(last) if last.1 == addr => last.1 = end,
1222                            _ => spans.push((addr, end)),
1223                        }
1224                        addr = end.max(addr.saturating_add(1));
1225                    }
1226                    EquivalentAt::Defined { range, .. } => {
1227                        addr = range.end.min(range_end).max(addr.saturating_add(1));
1228                    }
1229                }
1230            }
1231        }
1232        spans
1233    }
1234
1235    /// Control-flow targets (calls/jumps) that are not clean instruction starts.
1236    pub(crate) fn unresolved_control_targets(&self) -> Vec<ControlTarget> {
1237        let index = self.xref_index();
1238        let mut out = Vec::new();
1239        for (target, edges) in index.targets() {
1240            if target.space != self.space || self.is_code_start(target.offset) {
1241                continue;
1242            }
1243            let edge = edges
1244                .iter()
1245                .find(|e| e.kind == XrefType::Call)
1246                .or_else(|| edges.iter().find(|e| e.kind == XrefType::Jump));
1247            let Some(edge) = edge else {
1248                continue;
1249            };
1250            let misaligned = matches!(
1251                self.get_equivalent_kind(target.offset),
1252                Some(EquivalentKind::Code)
1253            );
1254            out.push(ControlTarget {
1255                target: target.offset,
1256                kind: edge.kind,
1257                from: edge.from,
1258                misaligned,
1259            });
1260        }
1261        out
1262    }
1263
1264    /// Decoded runs whose successor is not code (execution leaves known code).
1265    pub(crate) fn flow_leaks(&self) -> Vec<FlowLeak> {
1266        let mut leaks = Vec::new();
1267        for offset in self.code_offsets() {
1268            let Some(insn) = self.decode_at(offset) else {
1269                continue;
1270            };
1271            let successor = match insn.control_flow() {
1272                ControlFlow::Continue { next } => Some(next),
1273                ControlFlow::Choice { fall_through, .. } => Some(fall_through),
1274                ControlFlow::Call { return_pc, .. } => Some(return_pc),
1275                ControlFlow::Jump { .. } | ControlFlow::Diverge => None,
1276            };
1277            let Some(to) = successor else {
1278                continue;
1279            };
1280            if self.is_code_start(to) {
1281                continue;
1282            }
1283            let kind = if self.read_byte(to).is_none() {
1284                LeakKind::OffEnd
1285            } else if matches!(self.get_equivalent_kind(to), Some(EquivalentKind::Data)) {
1286                LeakKind::IntoData
1287            } else {
1288                LeakKind::IntoUndefined
1289            };
1290            leaks.push(FlowLeak {
1291                from: offset,
1292                to,
1293                kind,
1294            });
1295        }
1296        leaks
1297    }
1298
1299    /// Decode bytes as code from `start` to `end` in a linear fashion without
1300    /// committing anything, ignoring control flow. Detects if a run is code
1301    /// before disassembling it (out-of-range targets flags likely garbage).
1302    pub(crate) fn scratch_decode_linear(
1303        &self,
1304        start: AddressValue,
1305        end: AddressValue,
1306    ) -> ScratchDecode {
1307        let mut result = ScratchDecode::default();
1308        let mut addr = start;
1309        while addr < end {
1310            let Some(insn) = self.decode_at(addr) else {
1311                result.ran_out = true;
1312                break;
1313            };
1314            let target = branch_target(&insn).map(|t| self.effective(t));
1315            let target_mapped = target.is_none_or(|t| self.read_byte(t).is_some());
1316            let target_misaligned = target.is_some_and(|t| {
1317                matches!(self.get_equivalent_kind(t), Some(EquivalentKind::Code))
1318                    && !self.is_code_start(t)
1319            });
1320            if !target_mapped {
1321                result.out_of_range_targets += 1;
1322            }
1323            if target_misaligned {
1324                result.misaligned_targets += 1;
1325            }
1326            result.lines.push(ScratchInsn {
1327                addr,
1328                text: insn.as_string().to_string(),
1329                bytes: insn.bytes().to_vec(),
1330                target,
1331                target_mapped,
1332                target_misaligned,
1333                target_self_misaligned: false,
1334            });
1335            addr = addr.saturating_add(insn.len() as AddressValue);
1336        }
1337        mark_self_misaligned(&mut result);
1338        result
1339    }
1340
1341    /// Decode bytes as code from `start` without committing anything, following
1342    /// fall-through up to `max_lines` instructions and stopping at the first
1343    /// return or unconditional jump. Lets a caller judge whether a run is code
1344    /// before disassembling it (out-of-range targets flag likely garbage).
1345    pub(crate) fn scratch_decode(&self, start: AddressValue, max_lines: usize) -> ScratchDecode {
1346        let mut result = ScratchDecode::default();
1347        let mut addr = start;
1348        for _ in 0..max_lines {
1349            let Some(insn) = self.decode_at(addr) else {
1350                result.ran_out = true;
1351                break;
1352            };
1353            let target = branch_target(&insn).map(|t| self.effective(t));
1354            let target_mapped = target.is_none_or(|t| self.read_byte(t).is_some());
1355            // Misaligned only makes sense for a mapped target already decoded as
1356            // code.
1357            let target_misaligned = target.is_some_and(|t| {
1358                matches!(self.get_equivalent_kind(t), Some(EquivalentKind::Code))
1359                    && !self.is_code_start(t)
1360            });
1361            if !target_mapped {
1362                result.out_of_range_targets += 1;
1363            }
1364            if target_misaligned {
1365                result.misaligned_targets += 1;
1366            }
1367            result.lines.push(ScratchInsn {
1368                addr,
1369                text: insn.as_string().to_string(),
1370                bytes: insn.bytes().to_vec(),
1371                target,
1372                target_mapped,
1373                target_misaligned,
1374                target_self_misaligned: false,
1375            });
1376            addr = match insn.control_flow() {
1377                ControlFlow::Continue { next } => next,
1378                ControlFlow::Choice { fall_through, .. } => fall_through,
1379                ControlFlow::Call { return_pc, .. } => return_pc,
1380                ControlFlow::Jump { .. } | ControlFlow::Diverge => {
1381                    result.terminates = true;
1382                    break;
1383                }
1384            };
1385        }
1386        mark_self_misaligned(&mut result);
1387        result
1388    }
1389
1390    /// The rendered mnemonic of the instruction at `offset`, if one decodes
1391    /// there. Used to give a caller enough context to name a routine.
1392    pub(crate) fn instruction_text(&self, offset: AddressValue) -> Option<String> {
1393        self.decode_at(offset)
1394            .map(|insn| insn.as_string().trim().to_string())
1395    }
1396
1397    /// Referenced code targets in this region carrying only an auto-generated
1398    /// name (`sub_`/`loc_`), the provisional labels an assessment flags for
1399    /// naming. Mirrors [`collect_refs`](Region::collect_refs).
1400    pub(crate) fn provisional_labels(&self) -> Vec<(AddressValue, LabelKind)> {
1401        let index = self.xref_index();
1402        let mut out = Vec::new();
1403        for (target, edges) in index.targets() {
1404            let finalized =
1405                self.get_label(target.offset).is_some() && !self.is_draft_label(target.offset);
1406            if target.space != self.space || finalized {
1407                continue;
1408            }
1409            let kind = if edges.iter().any(|e| e.kind == XrefType::Call) {
1410                LabelKind::Sub
1411            } else if edges.iter().any(|e| e.kind == XrefType::Jump) {
1412                LabelKind::Loc
1413            } else {
1414                continue;
1415            };
1416            out.push((target.offset, kind));
1417        }
1418        out
1419    }
1420
1421    /// Named routines in this region: code entries that carry a real
1422    /// (non-provisional) label and are either called or marked as functions.
1423    pub(crate) fn named_routines(&self) -> Vec<(AddressValue, String)> {
1424        let index = self.xref_index();
1425        let mut out: Vec<(AddressValue, String)> = Vec::new();
1426        let mut seen = std::collections::BTreeSet::new();
1427        for (target, edges) in index.targets() {
1428            if target.space != self.space {
1429                continue;
1430            }
1431            let Some(name) = self.get_label(target.offset) else {
1432                continue;
1433            };
1434            if edges.iter().any(|e| e.kind == XrefType::Call) && seen.insert(target.offset) {
1435                out.push((target.offset, name.to_string()));
1436            }
1437        }
1438        for (offset, _func) in self.functions() {
1439            if let Some(name) = self.get_label(offset)
1440                && seen.insert(offset)
1441            {
1442                out.push((offset, name.to_string()));
1443            }
1444        }
1445        out.sort_by_key(|(offset, _)| *offset);
1446        out
1447    }
1448
1449    pub(crate) fn render(
1450        &self,
1451        space: AddressSpace,
1452        implicit_labels: &ImplicitLabels,
1453    ) -> Vec<Line> {
1454        self.render_named(space, implicit_labels, None)
1455    }
1456
1457    /// `render`, but emitting `names` in place of each address's stored label.
1458    pub(crate) fn render_named(
1459        &self,
1460        space: AddressSpace,
1461        implicit_labels: &ImplicitLabels,
1462        names: Option<&BTreeMap<AddressValue, String>>,
1463    ) -> Vec<Line> {
1464        let mut lines = Vec::new();
1465        let start = self.start();
1466        let end = self.end();
1467        if start >= end {
1468            return lines;
1469        }
1470
1471        let default_labels = Labels::default();
1472        let labels = implicit_labels.get(&space).unwrap_or(&default_labels);
1473
1474        let mut addr = start;
1475        let mut need_org = true;
1476        while addr < end {
1477            if need_org {
1478                lines.push(Line::Org { addr });
1479                lines.push(Line::Blank);
1480                need_org = false;
1481            }
1482
1483            if let Some(function) = self.get_function(addr) {
1484                lines.push(Line::Function {
1485                    addr,
1486                    name: function.name.clone(),
1487                    signature: function.signature.clone(),
1488                    length: function.length,
1489                    noreturn: function.noreturn,
1490                });
1491            }
1492            if let Some(comment) = self.get_comment(addr) {
1493                lines.push(Line::Comment {
1494                    addr,
1495                    text: comment.to_string(),
1496                });
1497            }
1498            let exported = names.and_then(|m| m.get(&addr)).map(String::as_str);
1499            if let Some(label) = exported.or_else(|| self.get_label(addr)) {
1500                lines.push(Line::Label {
1501                    addr,
1502                    name: label.to_string(),
1503                });
1504            } else if let Some(label) = labels.get(&addr) {
1505                lines.push(Line::Label {
1506                    addr,
1507                    name: label.to_string(),
1508                });
1509            }
1510
1511            match self.get_equivalent(addr) {
1512                EquivalentAt::Defined { start: _, range } => match &range.equivalent {
1513                    Equivalent::Code => {
1514                        let insn = self
1515                            .decode_at(addr)
1516                            .expect("validated code equivalent must decode");
1517                        let overrides = self.operand_overrides_at(addr);
1518                        let text = self.format_instruction(addr, &insn, &overrides, labels, names);
1519                        lines.push(Line::Instruction {
1520                            addr,
1521                            direct: insn.direct_addr(),
1522                            text,
1523                            bytes: insn.bytes().to_vec(),
1524                            target: branch_target(&insn),
1525                        });
1526                        addr = range.end;
1527                    }
1528                    Equivalent::Data(data_type, size) => {
1529                        // Swallowing a label undefines its references.
1530                        let end = self
1531                            .next_annotation(addr, labels)
1532                            .map_or(range.end, |next| range.end.min(next));
1533                        let size = end.saturating_sub(addr).min(*size).max(1);
1534                        let bytes = self.bytes_at(addr, size);
1535                        lines.push(Line::Data {
1536                            addr,
1537                            data_type: data_type.clone(),
1538                            bytes,
1539                        });
1540                        addr = addr.saturating_add(size);
1541                    }
1542                    Equivalent::Unknown(_) => {
1543                        let span = self.raw_span(addr, labels);
1544                        let bytes = self.bytes_at(addr, span);
1545                        lines.push(Line::Raw { addr, bytes });
1546                        addr += span;
1547                    }
1548                },
1549                EquivalentAt::Undefined(undefined) => {
1550                    let span = self.raw_span(addr, labels);
1551                    if span == 0 {
1552                        if let Some((&next_mapped, _)) =
1553                            self.byte_ranges.range(addr.saturating_add(1)..).next()
1554                            && next_mapped < undefined.end
1555                        {
1556                            addr = next_mapped;
1557                            need_org = true;
1558                            continue;
1559                        }
1560                        addr += 1;
1561                        continue;
1562                    }
1563                    let bytes = self.bytes_at(addr, span);
1564                    lines.push(Line::Raw { addr, bytes });
1565                    addr += span;
1566                }
1567            }
1568        }
1569
1570        lines
1571    }
1572
1573    pub(crate) fn to_commands(&self, space: AddressSpace) -> Vec<Box<dyn Command>> {
1574        let mut commands = Vec::new();
1575        for (&offset, range) in &self.byte_ranges {
1576            match range {
1577                ByteRange::Mapped(file, file_offset, data) => {
1578                    commands.push(boxed(MapBytes::new(
1579                        (space, offset),
1580                        file.clone(),
1581                        *file_offset,
1582                        data.len() as AddressValue,
1583                    )));
1584                }
1585                ByteRange::Constant(size, value) => {
1586                    commands.push(boxed(SetConstantBytes::new(
1587                        (space, offset..offset + *size),
1588                        *value,
1589                    )));
1590                }
1591            }
1592        }
1593
1594        // Barriers must precede the roots so they're in place when reload re-derives.
1595        for (&offset, equivalent_range) in &self.equivalents {
1596            match &equivalent_range.equivalent {
1597                Equivalent::Data(data_type, _) => {
1598                    commands.push(boxed(MarkData::new(
1599                        (space, offset..equivalent_range.end),
1600                        data_type.clone(),
1601                    )));
1602                }
1603                Equivalent::Unknown(_) => {
1604                    commands.push(boxed(MarkUnknown::new((
1605                        space,
1606                        offset..equivalent_range.end,
1607                    ))));
1608                }
1609                Equivalent::Code => {}
1610            }
1611        }
1612
1613        for root in self.weak.roots() {
1614            commands.push(boxed(AutoDisassemble::new((space, root))));
1615        }
1616
1617        // Manual code islands (strong code no root covers), coalesced into one
1618        // `disassemble_range` per contiguous run.
1619        let mut run: Option<(AddressValue, AddressValue)> = None;
1620        for (&offset, equivalent_range) in &self.equivalents {
1621            let island = matches!(equivalent_range.equivalent, Equivalent::Code)
1622                && !self.weak.code().contains_key(&offset);
1623            match (run, island) {
1624                (Some((start, end)), true) if end == offset => {
1625                    run = Some((start, equivalent_range.end));
1626                }
1627                (Some((start, end)), _) => {
1628                    commands.push(boxed(DisassembleRange::new((space, start..end), true)));
1629                    run = island.then_some((offset, equivalent_range.end));
1630                }
1631                (None, true) => run = Some((offset, equivalent_range.end)),
1632                (None, false) => {}
1633            }
1634        }
1635        if let Some((start, end)) = run {
1636            commands.push(boxed(DisassembleRange::new((space, start..end), true)));
1637        }
1638
1639        for (&(offset, index), value) in &self.overrides {
1640            commands.push(boxed(OverrideOperand::new(
1641                (space, offset),
1642                index,
1643                Some(value.clone()),
1644            )));
1645        }
1646
1647        for (&offset, label) in &self.labels {
1648            commands.push(boxed(SetLabel::new(
1649                (space, offset),
1650                label.clone(),
1651                self.draft_labels.contains(&offset),
1652                self.local_labels.contains(&offset),
1653            )));
1654        }
1655        for (&offset, comment) in &self.comments {
1656            commands.push(boxed(SetComment::new((space, offset), comment.clone())));
1657        }
1658        for (&offset, function) in &self.functions {
1659            commands.push(boxed(SetFunction::new((space, offset), function.clone())));
1660        }
1661        commands
1662    }
1663
1664    pub(crate) fn xrefs_to(&self, target: &PhysicalAddr) -> Vec<Xref> {
1665        self.xref_index()
1666            .to(target)
1667            .iter()
1668            .map(|edge| Xref {
1669                from: PhysicalAddr {
1670                    space: self.space,
1671                    offset: edge.from,
1672                },
1673                to: *target,
1674                xref_type: edge.kind,
1675                certainty: edge.certainty,
1676            })
1677            .collect()
1678    }
1679
1680    pub(crate) fn xrefs_from(&self, source: &PhysicalAddr) -> Vec<Xref> {
1681        let offset = source.offset;
1682        if !self.is_code_start(offset) {
1683            return Vec::new();
1684        }
1685        let Some(instruction) = self.decode_at(offset) else {
1686            return Vec::new();
1687        };
1688        xrefs_from_instruction(&instruction, *source)
1689    }
1690
1691    /// Feed implicit code labels from the xref index: every code target with an
1692    /// inbound call (`sub_`) or jump (`loc_`) that lacks an explicit name.
1693    pub(crate) fn collect_refs(&self, refs: &mut LabelCollector) {
1694        let index = self.xref_index();
1695        for (target, edges) in index.targets() {
1696            // Implicit code labels only apply to targets in this region's own
1697            // (code) space, data references into other spaces are not labelled.
1698            let finalized =
1699                self.get_label(target.offset).is_some() && !self.is_draft_label(target.offset);
1700            if target.space != self.space || finalized {
1701                continue;
1702            }
1703            let kind = if edges.iter().any(|e| e.kind == XrefType::Call) {
1704                LabelKind::Sub
1705            } else if edges.iter().any(|e| e.kind == XrefType::Jump) {
1706                LabelKind::Loc
1707            } else {
1708                continue;
1709            };
1710            refs.collect(*target, kind);
1711        }
1712    }
1713
1714    fn start(&self) -> AddressValue {
1715        [
1716            self.byte_ranges.keys().copied().next(),
1717            self.equivalents.keys().copied().next(),
1718            self.labels.keys().copied().next(),
1719            self.comments.keys().copied().next(),
1720        ]
1721        .into_iter()
1722        .flatten()
1723        .min()
1724        .unwrap_or(0) as AddressValue
1725    }
1726
1727    /// Upper bound (exclusive) of mapped bytes and equivalents.
1728    fn end(&self) -> AddressValue {
1729        [
1730            self.byte_ranges
1731                .iter()
1732                .next_back()
1733                .map(|(&start, range)| start + range.len()),
1734            self.equivalents
1735                .iter()
1736                .next_back()
1737                .map(|(&start, range)| start + range.end),
1738            self.labels.keys().next_back().copied(),
1739            self.comments.keys().next_back().copied(),
1740            self.functions.keys().next_back().copied(),
1741        ]
1742        .into_iter()
1743        .flatten()
1744        .max()
1745        .map(|addr| addr + 1)
1746        .unwrap_or(0)
1747    }
1748
1749    fn read_byte(&self, offset: AddressValue) -> Option<u8> {
1750        let (&start, range) = self.byte_ranges.range(..=offset).next_back()?;
1751        match range {
1752            ByteRange::Mapped(_, _, data) => data.get((offset - start) as usize).copied(),
1753            ByteRange::Constant(size, value) if offset - start < *size => Some(*value),
1754            ByteRange::Constant(_, _) => None,
1755        }
1756    }
1757
1758    fn decode_at(&self, address: AddressValue) -> Option<DecodedInsn> {
1759        // No CPU means nothing decodes.
1760        let platform = self.platform.as_ref()?;
1761        let max = platform.max_insn_len();
1762        let mut available = Vec::with_capacity(max);
1763
1764        for i in 0..max as AddressValue {
1765            if let Some(b) = self.read_byte(address + i) {
1766                available.push(b);
1767            } else {
1768                break;
1769            }
1770        }
1771        if available.is_empty() {
1772            return None;
1773        }
1774
1775        let ins = platform.decode(address, &available);
1776        if ins.len() > available.len() {
1777            return None;
1778        }
1779
1780        Some(ins)
1781    }
1782
1783    pub(crate) fn equivalent_span(
1784        &self,
1785        offset: AddressValue,
1786        equivalent: &Equivalent,
1787    ) -> Result<AddressValue, Error> {
1788        match equivalent {
1789            Equivalent::Code => self
1790                .decode_at(offset)
1791                .map(|insn| insn.len() as AddressValue)
1792                .ok_or_else(|| Error::from(ErrorKind::InvalidEquivalent)),
1793            Equivalent::Data(_, size) => Ok(*size),
1794            Equivalent::Unknown(size) => Ok(*size),
1795        }
1796    }
1797
1798    fn validate_equivalent_bounds(
1799        &self,
1800        offset: AddressValue,
1801        span: AddressValue,
1802    ) -> Result<(), Error> {
1803        for i in 0..span {
1804            if self.read_byte(offset + i).is_none() {
1805                return Err(crate::db::nothing_mapped(self.space, offset + i));
1806            }
1807        }
1808        Ok(())
1809    }
1810
1811    fn validate_no_equivalent_overlap(
1812        &self,
1813        offset: AddressValue,
1814        span: AddressValue,
1815    ) -> Result<(), Error> {
1816        let end = offset.saturating_add(span);
1817        if let Some((&other_start, other)) = self.equivalents.range(..end).next_back()
1818            && other.end > offset
1819        {
1820            return Err(ErrorKind::Overlap {
1821                at: self.space.dsl_addr(other_start),
1822                marked: crate::db::marked_word(other.equivalent.kind()).to_string(),
1823            }
1824            .into());
1825        }
1826        Ok(())
1827    }
1828
1829    /// Nearest address after `addr` needing its own line.
1830    fn next_annotation(
1831        &self,
1832        addr: AddressValue,
1833        implicit_labels: &Labels,
1834    ) -> Option<AddressValue> {
1835        let after = addr.saturating_add(1);
1836        [
1837            self.labels.range(after..).next().map(|(&k, _)| k),
1838            self.comments.range(after..).next().map(|(&k, _)| k),
1839            self.functions.range(after..).next().map(|(&k, _)| k),
1840            implicit_labels.range(after..).next().map(|(&k, _)| k),
1841        ]
1842        .into_iter()
1843        .flatten()
1844        .min()
1845    }
1846
1847    /// The length of the coalesced raw region at `addr`.
1848    fn raw_span(&self, addr: AddressValue, implicit_labels: &Labels) -> AddressValue {
1849        let boundary = self
1850            .next_annotation(addr, implicit_labels)
1851            .map_or(self.end(), |next| self.end().min(next));
1852
1853        let mut cur = addr;
1854        while cur < boundary {
1855            match self.get_equivalent(cur) {
1856                EquivalentAt::Defined { range, .. } => match &range.equivalent {
1857                    Equivalent::Unknown(_) => cur = range.end.min(boundary),
1858                    Equivalent::Code | Equivalent::Data(..) => break,
1859                },
1860                EquivalentAt::Undefined(undefined) => {
1861                    let limit = boundary.min(undefined.end);
1862                    let mut end = cur;
1863                    while end < limit && self.read_byte(end).is_some() {
1864                        end += 1;
1865                    }
1866                    if end == cur {
1867                        break; // an unmapped byte at the run's edge
1868                    }
1869                    cur = end;
1870                    if cur < undefined.end {
1871                        break; // stopped short on an unmapped hole
1872                    }
1873                }
1874            }
1875        }
1876        cur - addr
1877    }
1878
1879    fn format_instruction(
1880        &self,
1881        _addr: AddressValue,
1882        insn: &DecodedInsn,
1883        overrides: &[Option<OperandOverride>],
1884        implicit_labels: &Labels,
1885        names: Option<&BTreeMap<AddressValue, String>>,
1886    ) -> String {
1887        let decoded = insn.as_string();
1888        let mut merged = overrides.to_vec();
1889
1890        if let (Some(target), Some(idx)) = (branch_target(insn), branch_target_operand_index(insn))
1891        {
1892            while merged.len() <= idx {
1893                merged.push(None);
1894            }
1895            if merged[idx].is_none() {
1896                let label = names
1897                    .and_then(|m| m.get(&target))
1898                    .map(String::as_str)
1899                    .or_else(|| self.get_label(target))
1900                    .or_else(|| implicit_labels.get(&target).map(String::as_str));
1901                if let Some(label) = label {
1902                    merged[idx] = Some(OperandOverride::Label(label.to_string()));
1903                }
1904            }
1905        }
1906
1907        // Does this operand have a better name?
1908        let decided = self.operand_type(_addr);
1909        for data_ref in &insn.data_refs {
1910            let Some(idx) = data_ref.operand.map(usize::from) else {
1911                continue;
1912            };
1913            if data_ref.space != self.space {
1914                continue;
1915            }
1916            if data_ref.certainty == crate::platform::Certainty::Inferred
1917                && !matches!(decided, Some(OperandType::Pointer(space)) if space == self.space)
1918            {
1919                continue;
1920            }
1921            while merged.len() <= idx {
1922                merged.push(None);
1923            }
1924            if merged[idx].is_some() {
1925                continue;
1926            }
1927            if let Some(label) = names
1928                .and_then(|m| m.get(&data_ref.offset))
1929                .map(String::as_str)
1930                .or_else(|| self.get_label(data_ref.offset))
1931                .or_else(|| implicit_labels.get(&data_ref.offset).map(String::as_str))
1932            {
1933                let text = match data_ref.kind {
1934                    XrefType::Pointer => format!("#{label}"),
1935                    _ => label.to_string(),
1936                };
1937                merged[idx] = Some(OperandOverride::Label(text));
1938            }
1939        }
1940
1941        let text = if merged.iter().all(|o| o.is_none()) {
1942            decoded.to_string()
1943        } else {
1944            apply_operand_overrides(decoded, &merged)
1945        };
1946        sdas_indent_instruction(&text)
1947    }
1948}
1949
1950impl CodeSource for Region {
1951    fn decode(&self, addr: AddressValue) -> Option<DecodedInsn> {
1952        self.decode_at(addr)
1953    }
1954
1955    fn barrier_in(&self, addr: AddressValue, len: AddressValue) -> Option<EquivalentKind> {
1956        let end = addr.saturating_add(len);
1957        // Strong equivalents don't overlap, so scanning back from `end` until one
1958        // ends at/before `addr` covers every entry touching the range.
1959        for (_, range) in self.equivalents.range(..end).rev() {
1960            if range.end <= addr {
1961                break;
1962            }
1963            let kind = range.equivalent.kind();
1964            if kind != EquivalentKind::Code {
1965                return Some(kind);
1966            }
1967        }
1968        None
1969    }
1970}
1971
1972fn sdas_indent_instruction(text: &str) -> String {
1973    if let Some((mnemonic, operands)) = text.split_once(' ') {
1974        format!("    {mnemonic:<8}{operands}")
1975    } else {
1976        format!("    {text}")
1977    }
1978}
1979
1980fn split_instruction(decoded: &str) -> (&str, Vec<&str>) {
1981    let (mnemonic, rest) = decoded.split_once(' ').unwrap_or((decoded, ""));
1982    let operands = if rest.is_empty() {
1983        Vec::new()
1984    } else {
1985        rest.split(',').map(str::trim).collect()
1986    };
1987    (mnemonic, operands)
1988}
1989
1990fn apply_operand_overrides(decoded: &str, overrides: &[Option<OperandOverride>]) -> String {
1991    if overrides.is_empty() {
1992        return decoded.to_string();
1993    }
1994    let (mnemonic, operands) = split_instruction(decoded);
1995    let mut out = mnemonic.to_string();
1996    let operand_count = operands.len().max(overrides.len());
1997    for idx in 0..operand_count {
1998        if idx > 0 {
1999            out.push(',');
2000        } else {
2001            out.push(' ');
2002        }
2003        match overrides.get(idx).and_then(|o| o.as_ref()) {
2004            Some(OperandOverride::Label(label)) => out.push_str(label),
2005            Some(OperandOverride::LabelOffset { label, offset }) => {
2006                if *offset >= 0 {
2007                    out.push_str(&format!("{label}+{offset}"));
2008                } else {
2009                    out.push_str(&format!("{label}{offset}"));
2010                }
2011            }
2012            Some(OperandOverride::Text(text)) => out.push_str(text),
2013            None => {
2014                if let Some(default) = operands.get(idx) {
2015                    out.push_str(default);
2016                }
2017            }
2018        }
2019    }
2020    out
2021}
2022
2023/// Find the entry covering `offset` in one equivalent layer: an exact start, or
2024/// a preceding range that still contains it.
2025fn lookup_in(
2026    map: &BTreeMap<AddressValue, EquivalentRange>,
2027    offset: AddressValue,
2028) -> Option<(AddressValue, &EquivalentRange)> {
2029    if let Some(range) = map.get(&offset) {
2030        return Some((offset, range));
2031    }
2032    match map.range(..=offset).next_back() {
2033        Some((&start, range)) if offset < range.end => Some((start, range)),
2034        _ => None,
2035    }
2036}
2037
2038/// A and B are inclusive start, exclusive end.
2039fn ranges_overlap(
2040    a_start: AddressValue,
2041    a_end: AddressValue,
2042    b_start: AddressValue,
2043    b_end: AddressValue,
2044) -> bool {
2045    a_start < b_end && b_start < a_end
2046}
2047
2048/// A and B are inclusive start, inclusive end.
2049fn ranges_overlap_inclusive(
2050    a_start: AddressValue,
2051    a_end: AddressValue,
2052    b_start: AddressValue,
2053    b_end: AddressValue,
2054) -> bool {
2055    a_start <= b_end && b_start <= a_end
2056}
2057
2058#[cfg(test)]
2059mod tests {
2060    use super::*;
2061    use crate::db::{DataType, Equivalent, OperandOverride, SpaceUsage};
2062    use crate::platform::i8051::{CODE, platform};
2063
2064    #[test]
2065    fn overlap_names_space_kind() {
2066        let mut region = Region::new(CODE, Some(platform()));
2067        region.set_bytes("test.bin", 0, 0, &[0x00, 0x00, 0x22]);
2068        region.set_equivalent(0, Equivalent::Code).unwrap();
2069        let err = region
2070            .disassemble_linear(0, 2)
2071            .expect_err("second instruction overlaps code at 0");
2072        assert!(matches!(
2073            &err.what,
2074            ErrorKind::Overlap { at, marked } if at == "CODE:0x0" && marked == "code"
2075        ));
2076    }
2077
2078    #[test]
2079    fn overlapping_equivalents_are_rejected() {
2080        let mut region = Region::new(CODE, Some(platform()));
2081        region.set_bytes(
2082            "test.bin",
2083            0,
2084            0,
2085            &[0x02, 0x00, 0x10, 0x74, 0x01, 0x00, 0x00, 0x00],
2086        );
2087        region.set_equivalent(0, Equivalent::Code).unwrap();
2088        assert!(matches!(
2089            region.set_equivalent(1, Equivalent::Code),
2090            Err(e) if matches!(&e.what, ErrorKind::AlreadyClassified { at, .. } if at == "CODE:0x1")
2091        ));
2092        region.set_equivalent(6, Equivalent::Code).unwrap();
2093        assert!(matches!(
2094            region.set_equivalent(4, Equivalent::Data(DataType::Byte, 3)),
2095            Err(e) if matches!(&e.what, ErrorKind::Overlap { at, marked } if at == "CODE:0x6" && marked == "code")
2096        ));
2097    }
2098
2099    #[test]
2100    fn unmap_splits_straddling_range() {
2101        let mut region = Region::new(CODE, Some(platform()));
2102        region.set_bytes("test.bin", 0, 0, &[1, 2, 3, 4, 5]);
2103        region.unmap_bytes(1, 2);
2104        assert_eq!(region.bytes_at(0, 5), vec![1, 4, 5]);
2105    }
2106
2107    #[test]
2108    fn decode_without_zero_bytes() {
2109        let mut region = Region::new(CODE, Some(platform()));
2110        region.set_bytes("test.bin", 0, 0x100, &[0x74, 0x42]);
2111        let insn = region.decode_at(0x100).unwrap();
2112        assert_eq!(insn.len(), 2);
2113        assert_eq!(insn.as_string(), "MOV A,#0x42");
2114    }
2115
2116    #[test]
2117    fn decode_requires_full_length() {
2118        let mut region = Region::new(CODE, Some(platform()));
2119        region.set_bytes("test.bin", 0, 0, &[0x02, 0x00]);
2120        assert!(
2121            region.decode_at(0).is_none(),
2122            "Expected None, got {:?}",
2123            region.decode_at(0).unwrap().as_string()
2124        );
2125    }
2126
2127    #[test]
2128    fn branch_uses_implicit_label() {
2129        let mut region = Region::new(CODE, Some(platform()));
2130        region.set_bytes("test.bin", 0, 0, &[0x12, 0x01, 0x6D, 0x02, 0x03, 0x04]);
2131        region.set_equivalent(0, Equivalent::Code).unwrap();
2132        region.set_equivalent(3, Equivalent::Code).unwrap();
2133
2134        let mut collector = LabelCollector::default();
2135        region.collect_refs(&mut collector);
2136        let implicit_labels = collector.into_implicit_labels();
2137
2138        let lines = region.render(CODE, &implicit_labels);
2139        let insn = lines
2140            .iter()
2141            .find_map(|line| match line {
2142                Line::Instruction { addr: 0, text, .. } => Some(text.clone()),
2143                _ => None,
2144            })
2145            .unwrap();
2146        assert!(insn.contains("LCALL"), "{insn}");
2147        // A call target is named `sub_`, not `loc_`.
2148        assert!(insn.contains("sub_016D"), "{insn}");
2149        assert!(!insn.contains("#0x016D"), "{insn}");
2150    }
2151
2152    #[test]
2153    fn xref_index_reflects_chop() {
2154        let mut region = Region::new(CODE, Some(platform()));
2155        // LJMP 0x0006 / NOP x4. Auto-disassembly flows through the jump.
2156        region.set_bytes("t.bin", 0, 0, &[0x02, 0x00, 0x06, 0x00, 0x00, 0x00, 0x00]);
2157        region.add_auto_root(0);
2158
2159        let target = PhysicalAddr {
2160            space: CODE,
2161            offset: 6,
2162        };
2163        let before = region.xrefs_to(&target);
2164        assert_eq!(before.len(), 1);
2165        assert_eq!(before[0].from.offset, 0);
2166        assert_eq!(before[0].xref_type, XrefType::Jump);
2167
2168        // A barrier over the LJMP chops the derived code, so its edge drops.
2169        region.set_equivalent(0, Equivalent::Unknown(3)).unwrap();
2170        assert!(region.xrefs_to(&target).is_empty());
2171    }
2172
2173    #[test]
2174    fn blocks_split_at_targets() {
2175        let mut region = Region::new(CODE, Some(platform()));
2176        // 0: JZ 0x03 / 2: NOP / 3: RET
2177        region.set_bytes("t.bin", 0, 0, &[0x60, 0x01, 0x00, 0x22]);
2178        region.add_auto_root(0);
2179
2180        let blocks = region.basic_blocks(0);
2181        let starts: Vec<_> = blocks.iter().map(|b| b.start).collect();
2182        assert_eq!(starts, vec![0, 2, 3]);
2183        // The JZ block falls through to 2 and branches to 3.
2184        assert_eq!(blocks[0].end, 2);
2185        assert_eq!(blocks[0].successors, vec![2, 3]);
2186        // The NOP block ends where the branch target (a leader) begins.
2187        assert_eq!(blocks[1].successors, vec![3]);
2188    }
2189
2190    #[test]
2191    fn thunk_render_stays_faithful() {
2192        let mut region = Region::new(CODE, Some(platform()));
2193        // 0: LCALL 0x0003 / 3: LJMP 0x0006 (a pure thunk) / 6: RET
2194        region.set_bytes("t.bin", 0, 0, &[0x12, 0x00, 0x03, 0x02, 0x00, 0x06, 0x22]);
2195        region.add_auto_root(0);
2196
2197        // Resolution follows the lone jump at 3 through to 6. 6 is not a thunk.
2198        assert_eq!(region.resolve_thunks(3), 6);
2199        assert_eq!(region.resolve_thunks(6), 6);
2200
2201        // Rendering stays faithful to the bytes: the LCALL shows the stub it
2202        // actually targets (sub_0003), so the text reassembles to the ROM.
2203        let mut collector = LabelCollector::default();
2204        region.collect_refs(&mut collector);
2205        let implicit = collector.into_implicit_labels();
2206        let call = region
2207            .render(CODE, &implicit)
2208            .into_iter()
2209            .find_map(|l| match l {
2210                Line::Instruction { addr: 0, text, .. } => Some(text),
2211                _ => None,
2212            })
2213            .unwrap();
2214        assert!(call.contains("0003"), "{call}");
2215        assert!(!call.contains("0006"), "{call}");
2216    }
2217
2218    #[test]
2219    fn override_preserves_operands() {
2220        let mut region = Region::new(CODE, Some(platform()));
2221        region.set_bytes("test.bin", 0, 0, &[0xB5, 0x20, 0x10]);
2222        region.set_label(0x13, "target", crate::region::LabelAttrs::default());
2223        region.set_equivalent(0, Equivalent::Code).unwrap();
2224        region.set_operand_override(0, 2, Some(OperandOverride::Label("target".into())));
2225        let implicit_labels = ImplicitLabels::default();
2226        let lines = region.render(CODE, &implicit_labels);
2227        let insn = lines
2228            .iter()
2229            .find_map(|line| match line {
2230                Line::Instruction { text, .. } => Some(text.clone()),
2231                _ => None,
2232            })
2233            .unwrap();
2234        assert!(insn.contains("0x20,target"));
2235    }
2236
2237    #[test]
2238    fn adjacent_unknown_barriers_coalesce() {
2239        let mut region = Region::new(CODE, Some(platform()));
2240        region.set_bytes("test.bin", 0, 0, &[1, 2, 3, 4, 5, 6]);
2241        // Undefine the range in three small adjacent chunks.
2242        region.set_equivalent(0, Equivalent::Unknown(2)).unwrap();
2243        region.set_equivalent(2, Equivalent::Unknown(2)).unwrap();
2244        region.set_equivalent(4, Equivalent::Unknown(2)).unwrap();
2245        let raws: Vec<_> = region
2246            .render(CODE, &ImplicitLabels::default())
2247            .into_iter()
2248            .filter_map(|line| match line {
2249                Line::Raw { addr, bytes } => Some((addr, bytes.len())),
2250                _ => None,
2251            })
2252            .collect();
2253        assert_eq!(raws, vec![(0, 6)], "adjacent barriers render together");
2254    }
2255
2256    #[test]
2257    fn label_splits_raw_run() {
2258        let mut region = Region::new(CODE, Some(platform()));
2259        region.set_bytes("test.bin", 0, 0, &[1, 2, 3, 4]);
2260        region.set_equivalent(0, Equivalent::Unknown(2)).unwrap();
2261        region.set_equivalent(2, Equivalent::Unknown(2)).unwrap();
2262        region.set_label(2, "mid", crate::region::LabelAttrs::default());
2263        let raws: Vec<_> = region
2264            .render(CODE, &ImplicitLabels::default())
2265            .into_iter()
2266            .filter_map(|line| match line {
2267                Line::Raw { addr, bytes } => Some((addr, bytes.len())),
2268                _ => None,
2269            })
2270            .collect();
2271        assert_eq!(raws, vec![(0, 2), (2, 2)], "label breaks the run");
2272    }
2273
2274    #[test]
2275    fn render_emits_org() {
2276        let mut region = Region::new(CODE, Some(platform()));
2277        region.set_bytes("test.bin", 0, 0, &[1, 2, 3]);
2278        region.set_bytes("test.bin", 3, 0x10, &[4, 5]);
2279        let implicit_labels = ImplicitLabels::default();
2280        let lines = region.render(CODE, &implicit_labels);
2281        let orgs: Vec<_> = lines
2282            .iter()
2283            .filter_map(|line| match line {
2284                Line::Org { addr } => Some(*addr),
2285                _ => None,
2286            })
2287            .collect();
2288        assert_eq!(orgs, vec![0, 0x10]);
2289    }
2290
2291    #[test]
2292    fn usage_counts_each_kind() {
2293        let mut region = Region::new(CODE, Some(platform()));
2294        region.set_bytes(
2295            "test.bin",
2296            0,
2297            0,
2298            &[0x02, 0x00, 0x10, 0x74, 0x01, 0xFF, 0xFF],
2299        );
2300        region.set_equivalent(0, Equivalent::Code).unwrap();
2301        region.set_equivalent(3, Equivalent::Code).unwrap();
2302        region
2303            .set_equivalent(5, Equivalent::Data(DataType::Word, 2))
2304            .unwrap();
2305
2306        assert_eq!(
2307            region.space_usage(),
2308            SpaceUsage {
2309                code: 5,
2310                data: 2,
2311                undefined: 0,
2312            }
2313        );
2314
2315        region.clear_equivalents(5, 2);
2316        assert_eq!(
2317            region.space_usage(),
2318            SpaceUsage {
2319                code: 5,
2320                data: 0,
2321                undefined: 2,
2322            }
2323        );
2324    }
2325
2326    #[test]
2327    fn usage_counts_nonzero_base() {
2328        // A byte range based at a nonzero offset must still count in full.
2329        let mut region = Region::new(CODE, Some(platform()));
2330        region.set_bytes("test.bin", 0, 0x1000, &[0xAA, 0xBB, 0xCC, 0xDD]);
2331
2332        let usage = region.space_usage();
2333        assert_eq!(usage.undefined, 4);
2334        assert_eq!(usage.code, 0);
2335        assert_eq!(usage.data, 0);
2336        // The completeness `coverage()` derives `undefined` from the spans and
2337        // must agree.
2338        assert_eq!(region.coverage().undefined, 4);
2339    }
2340
2341    use crate::commands::{MapBytes, boxed};
2342    use crate::db::Db;
2343
2344    struct Env(&'static [u8]);
2345    impl crate::commands::Environment for Env {
2346        fn load_file_bytes(
2347            &self,
2348            _f: &str,
2349            offset: usize,
2350            size: AddressValue,
2351        ) -> Result<Vec<u8>, std::io::Error> {
2352            Ok(self.0[offset..offset + size as usize].to_vec())
2353        }
2354    }
2355
2356    fn peek(image: &'static [u8]) -> ScratchDecode {
2357        let env = Env(image);
2358        let mut db = Db::with_platform(crate::platform::i8051::platform());
2359        db.apply(
2360            boxed(MapBytes::new((CODE, 0), "img", 0usize, image.len() as u32)),
2361            Some(&env),
2362        )
2363        .unwrap();
2364        db.peek_linear(CODE, 0, image.len() as AddressValue)
2365    }
2366
2367    /// One signature of data decoded as code: a branch landing partway through
2368    /// a neighbour.
2369    #[test]
2370    fn branch_into_neighbour_counted() {
2371        // 0: SJMP 0x03 — lands inside the instruction at 0x02.
2372        // 2: SJMP 0x04 — lands on a real boundary.
2373        // 4: NOP, 5: RET.
2374        let decode = peek(&[0x80, 0x01, 0x80, 0x00, 0x00, 0x22]);
2375
2376        assert_eq!(decode.self_misaligned_targets, 1);
2377        assert!(decode.lines[0].target_self_misaligned, "0x00 -> 0x03");
2378        assert!(
2379            !decode.lines[1].target_self_misaligned,
2380            "0x02 -> 0x04 is aligned"
2381        );
2382    }
2383
2384    /// Real code branches to boundaries.
2385    #[test]
2386    fn boundary_branches_clean() {
2387        // 0: SJMP 0x02, 2: NOP, 3: NOP, 4: NOP, 5: RET.
2388        let decode = peek(&[0x80, 0x00, 0x00, 0x00, 0x00, 0x22]);
2389
2390        assert_eq!(decode.self_misaligned_targets, 0);
2391        assert_eq!(decode.out_of_range_targets, 0);
2392        assert!(decode.lines.iter().all(|l| !l.target_self_misaligned));
2393    }
2394
2395    /// A target beyond the image counts into `out_of_range_targets`.
2396    #[test]
2397    fn outside_target_not_misaligned() {
2398        // LJMP 0x4321 — far outside a six-byte image.
2399        let decode = peek(&[0x02, 0x43, 0x21, 0x00, 0x00, 0x22]);
2400
2401        assert_eq!(decode.out_of_range_targets, 1);
2402        assert_eq!(decode.self_misaligned_targets, 0);
2403    }
2404
2405    /// The linear decode covers the whole range.
2406    #[test]
2407    fn linear_ignores_return() {
2408        let image: &[u8] = &[0x22, 0x00, 0x00, 0x22];
2409        let env = Env(image);
2410        let mut db = Db::with_platform(crate::platform::i8051::platform());
2411        db.apply(
2412            boxed(MapBytes::new((CODE, 0), "img", 0usize, 4u32)),
2413            Some(&env),
2414        )
2415        .unwrap();
2416
2417        assert_eq!(db.peek(CODE, 0, 16).lines.len(), 1, "flow stops at the RET");
2418        assert_eq!(
2419            db.peek_linear(CODE, 0, 4).lines.len(),
2420            4,
2421            "linear keeps going"
2422        );
2423    }
2424
2425    /// The same local name in two routines must survive into valid assembly,
2426    /// and a global name used twice must be made unique rather than emitted.
2427    #[test]
2428    fn locals_repeat_globals_unique() {
2429        struct Img;
2430        impl crate::commands::Environment for Img {
2431            fn load_file_bytes(
2432                &self,
2433                _f: &str,
2434                offset: usize,
2435                size: AddressValue,
2436            ) -> Result<Vec<u8>, std::io::Error> {
2437                // main: MOV R0,#5 / DJNZ R0,-2 / RET; other: the same shape.
2438                const IMAGE: [u8; 10] =
2439                    [0x78, 0x05, 0xD8, 0xFE, 0x22, 0x78, 0x03, 0xD8, 0xFE, 0x22];
2440                Ok(IMAGE[offset..offset + size as usize].to_vec())
2441            }
2442        }
2443        use crate::commands::{AutoDisassemble, MapBytes, SetLabel};
2444        use crate::db::Db;
2445
2446        let mut db = Db::with_platform(platform());
2447        db.apply(
2448            boxed(MapBytes::new((CODE, 0), "img", 0usize, 10u32)),
2449            Some(&Img),
2450        )
2451        .unwrap();
2452        for entry in [0u32, 5] {
2453            db.apply(boxed(AutoDisassemble::new((CODE, entry))), Some(&Img))
2454                .unwrap();
2455        }
2456        db.apply(
2457            boxed(SetLabel::new(
2458                (CODE, 0u32),
2459                "main".to_string(),
2460                false,
2461                false,
2462            )),
2463            None,
2464        )
2465        .unwrap();
2466        db.apply(
2467            boxed(SetLabel::new(
2468                (CODE, 5u32),
2469                "other".to_string(),
2470                false,
2471                false,
2472            )),
2473            None,
2474        )
2475        .unwrap();
2476        // One name, two routines — legal only because each is scoped to its own.
2477        for at in [2u32, 7] {
2478            db.apply(
2479                boxed(SetLabel::new((CODE, at), ".loop".to_string(), false, true)),
2480                None,
2481            )
2482            .unwrap();
2483        }
2484
2485        let asm = db.to_sdas();
2486        assert!(
2487            asm.contains("1$:"),
2488            "locals export as ASxxxx locals:\n{asm}"
2489        );
2490        assert!(!asm.contains(".loop:"), "not a local to sdas:\n{asm}");
2491        // Each scope restarts numbering, so both routines get their own `1$`.
2492        assert_eq!(asm.matches("1$:").count(), 2, "one local per scope:\n{asm}");
2493        // References must follow the definitions, or the output assembles wrong.
2494        assert_eq!(asm.matches("DJNZ").count(), 2, "{asm}");
2495        assert!(
2496            !asm.contains("DJNZ    R0,.loop"),
2497            "reference not rewritten:\n{asm}"
2498        );
2499    }
2500
2501    /// A global name reused at two addresses is disambiguated, since emitting
2502    /// it twice would be a duplicate symbol.
2503    #[test]
2504    fn repeated_global_made_unique() {
2505        let mut region = Region::new(CODE, Some(platform()));
2506        region.set_bytes("test.bin", 0, 0, &[0x00, 0x00, 0x00, 0x22]);
2507        region.set_label(0, "handler", LabelAttrs::default());
2508        region.set_label(2, "handler", LabelAttrs::default());
2509
2510        let names = region.export_names(&Labels::default());
2511        assert_eq!(names.get(&0).map(String::as_str), Some("handler"));
2512        assert_eq!(names.get(&2).map(String::as_str), Some("handler_1"));
2513    }
2514
2515    #[test]
2516    fn cross_scope_local_named() {
2517        struct Img;
2518        impl crate::commands::Environment for Img {
2519            fn load_file_bytes(
2520                &self,
2521                _f: &str,
2522                offset: usize,
2523                size: AddressValue,
2524            ) -> Result<Vec<u8>, std::io::Error> {
2525                // main: MOV R0,#5 / NOP / RET; other: MOV R0,#3 / SJMP 0x2 / RET.
2526                // The SJMP reaches back into main's body, across `other`'s label.
2527                const IMAGE: [u8; 9] = [0x78, 0x05, 0x00, 0x22, 0x78, 0x03, 0x80, 0xFA, 0x22];
2528                Ok(IMAGE[offset..offset + size as usize].to_vec())
2529            }
2530        }
2531        use crate::commands::{AutoDisassemble, MapBytes, SetLabel};
2532        use crate::db::Db;
2533
2534        let mut db = Db::with_platform(platform());
2535        db.apply(
2536            boxed(MapBytes::new((CODE, 0), "img", 0usize, 9u32)),
2537            Some(&Img),
2538        )
2539        .unwrap();
2540        for entry in [0u32, 4] {
2541            db.apply(boxed(AutoDisassemble::new((CODE, entry))), Some(&Img))
2542                .unwrap();
2543        }
2544        db.apply(
2545            boxed(SetLabel::new(
2546                (CODE, 0u32),
2547                "main".to_string(),
2548                false,
2549                false,
2550            )),
2551            None,
2552        )
2553        .unwrap();
2554        db.apply(
2555            boxed(SetLabel::new(
2556                (CODE, 4u32),
2557                "other".to_string(),
2558                false,
2559                false,
2560            )),
2561            None,
2562        )
2563        .unwrap();
2564        db.apply(
2565            boxed(SetLabel::new(
2566                (CODE, 2u32),
2567                "inner".to_string(),
2568                false,
2569                true,
2570            )),
2571            None,
2572        )
2573        .unwrap();
2574
2575        let region = db.region(CODE).unwrap();
2576        assert!(region.is_local_label(2));
2577        assert_eq!(region.scope_of(2), Some(0), "its routine is `main`");
2578
2579        let asm = db.to_sdas();
2580        assert!(
2581            asm.contains("inner:"),
2582            "the local falls back to its name:\n{asm}"
2583        );
2584        assert!(!asm.contains("1$:"), "it cannot be an ASxxxx local:\n{asm}");
2585        assert!(
2586            asm.contains("SJMP    inner"),
2587            "the reference matches:\n{asm}"
2588        );
2589    }
2590
2591    /// A swallowed label undefines every reference to it.
2592    #[test]
2593    fn data_run_stops_early() {
2594        let mut region = Region::new(CODE, Some(platform()));
2595        region.set_bytes("test.bin", 0, 0, &[0x11, 0x22, 0x33, 0x44]);
2596        region
2597            .set_equivalent(0, Equivalent::Data(DataType::Byte, 4))
2598            .unwrap();
2599        region.set_label(2, "table_hi", LabelAttrs::default());
2600
2601        let lines = region.render(CODE, &ImplicitLabels::default());
2602        let labelled: Vec<AddressValue> = lines
2603            .iter()
2604            .filter_map(|l| match l {
2605                Line::Label { addr, .. } => Some(*addr),
2606                _ => None,
2607            })
2608            .collect();
2609        assert_eq!(
2610            labelled,
2611            vec![2],
2612            "the label must survive the run: {lines:#?}"
2613        );
2614
2615        // The run splits rather than losing bytes.
2616        let data: Vec<(AddressValue, usize)> = lines
2617            .iter()
2618            .filter_map(|l| match l {
2619                Line::Data { addr, bytes, .. } => Some((*addr, bytes.len())),
2620                _ => None,
2621            })
2622            .collect();
2623        assert_eq!(data, vec![(0, 2), (2, 2)], "{lines:#?}");
2624    }
2625
2626    #[test]
2627    fn clearing_label_clears_attributes() {
2628        let mut region = Region::new(CODE, Some(platform()));
2629        region.set_bytes("test.bin", 0, 0, &[0x00, 0x00, 0x00, 0x22]);
2630
2631        region.set_label(
2632            0,
2633            "guess",
2634            LabelAttrs {
2635                provisional: true,
2636                local: true,
2637            },
2638        );
2639        assert!(region.is_draft_label(0) && region.is_local_label(0));
2640
2641        region.clear_label(0);
2642        assert!(!region.is_draft_label(0), "draft flag outlived the label");
2643        assert!(!region.is_local_label(0), "local flag outlived the label");
2644
2645        // A plain name set afterwards must be plain.
2646        region.set_label(0, "settled", LabelAttrs::default());
2647        assert!(!region.is_draft_label(0) && !region.is_local_label(0));
2648
2649        // The range form has to do the same.
2650        region.set_label(
2651            2,
2652            "spot",
2653            LabelAttrs {
2654                provisional: true,
2655                local: true,
2656            },
2657        );
2658        region.clear_labels_in(2..3);
2659        assert!(!region.is_draft_label(2) && !region.is_local_label(2));
2660    }
2661
2662    #[test]
2663    fn peek_reports_self_misaligned() {
2664        struct Img;
2665        impl crate::commands::Environment for Img {
2666            fn load_file_bytes(
2667                &self,
2668                _f: &str,
2669                offset: usize,
2670                size: AddressValue,
2671            ) -> Result<Vec<u8>, std::io::Error> {
2672                // JNZ 0x3 falls through to the MOV at 0x2, and its target
2673                // lands inside that instruction.
2674                const BYTES: [u8; 5] = [0x70, 0x01, 0x74, 0x00, 0x22];
2675                Ok(BYTES[offset..offset + size as usize].to_vec())
2676            }
2677        }
2678        use crate::commands::MapBytes;
2679        use crate::db::Db;
2680
2681        let mut db = Db::with_platform(platform());
2682        db.apply(
2683            boxed(MapBytes::new((CODE, 0), "img", 0usize, 5u32)),
2684            Some(&Img),
2685        )
2686        .unwrap();
2687
2688        assert_eq!(db.peek(CODE, 0, 16).self_misaligned_targets, 1);
2689    }
2690
2691    #[test]
2692    fn retyping_says_clearing_cost() {
2693        let mut region = Region::new(CODE, Some(platform()));
2694        region.set_bytes("test.bin", 0, 0, &[0x00; 0x40]);
2695        region
2696            .set_equivalent(0, Equivalent::Data(DataType::Byte, 0x40))
2697            .unwrap();
2698
2699        let err = region
2700            .set_equivalent(0x10, Equivalent::Data(DataType::Byte, 4))
2701            .expect_err("those bytes already carry a classification");
2702        assert!(matches!(
2703            &err.what,
2704            ErrorKind::AlreadyClassified { marked, cleared: 0x40, asked: 0x4, .. }
2705                if marked == "data"
2706        ));
2707        // The clear, and how to put back what was not being retyped.
2708        let text = err.to_string();
2709        assert!(text.contains("clear_equivalents"), "{text}");
2710        assert!(
2711            text.contains("mark_data(range=CODE:0x0..0x10"),
2712            "restore before: {text}"
2713        );
2714        assert!(
2715            text.contains("mark_data(range=CODE:0x14..0x40"),
2716            "restore after: {text}"
2717        );
2718    }
2719
2720    #[test]
2721    fn unmapped_address_names_space() {
2722        let mut region = Region::new(CODE, Some(platform()));
2723        region.set_bytes("test.bin", 0, 0, &[0x00, 0x00]);
2724
2725        let err = region
2726            .set_equivalent(0, Equivalent::Data(DataType::Byte, 8))
2727            .expect_err("the run runs past the mapped bytes");
2728        assert!(matches!(
2729            &err.what,
2730            ErrorKind::NothingMapped { at } if at == "CODE:0x2"
2731        ));
2732    }
2733}