Skip to main content

i8051_disassembler/
db.rs

1use std::collections::BTreeMap;
2use std::range::Range;
3
4use serde::{Deserialize, Serialize};
5
6use crate::address::{AddressSpace, AddressValue, PhysicalAddr, SpaceAddressValue, Xref};
7use crate::commands::{Command, Environment, SetCpu, SetNote, boxed};
8use crate::labels::{ImplicitLabels, LabelCollector};
9pub use crate::note::{
10    Note, NoteAddressIndex, NoteDb, NoteField, NoteGlobalIndex, NoteId, NotePath, Notes,
11    ProximateNote,
12};
13use crate::platform::{Certainty, Platform, PlatformRef};
14pub use crate::region::{
15    Block, ByteRange, LabelAttrs, OperandType, Region, ScratchDecode, ScratchInsn,
16};
17use crate::render::Line;
18use crate::render::sdas::SdasWriter;
19use crate::store::dsl;
20
21pub struct Db {
22    regions: BTreeMap<AddressSpace, Region>,
23    /// The processor driver: decodes bytes and declares the address regions.
24    /// `None` until a `set_cpu` command (or [`with_platform`](Db::with_platform))
25    /// selects one. Disassembly requires a CPU.
26    platform: Option<PlatformRef>,
27    pub notes: NoteDb,
28}
29
30impl Db {
31    /// A database with no CPU selected. A `set_cpu` command must run before any
32    /// disassembly.
33    pub fn new() -> Self {
34        Self {
35            regions: BTreeMap::new(),
36            platform: None,
37            notes: NoteDb::default(),
38        }
39    }
40
41    /// A database with `platform` already selected.
42    pub fn with_platform(platform: PlatformRef) -> Self {
43        let mut db = Self::new();
44        db.set_platform(Some(platform));
45        db
46    }
47
48    /// The selected processor driver, or `None` if no CPU is set.
49    pub fn platform(&self) -> Option<&dyn Platform> {
50        self.platform.as_deref()
51    }
52
53    /// Select the CPU (or clear it with `None`), propagating it to every region
54    /// so their code re-derives. Returns the previous selection.
55    pub fn set_platform(&mut self, platform: Option<PlatformRef>) -> Option<PlatformRef> {
56        let prev = self.platform.take();
57        self.platform = platform.clone();
58        for region in self.regions.values_mut() {
59            region.set_platform(platform.clone());
60        }
61        prev
62    }
63
64    /// The address spaces to render, in order: the driver's regions when a CPU
65    /// is set, otherwise whatever spaces already hold mapped bytes.
66    pub fn spaces(&self) -> Vec<AddressSpace> {
67        match &self.platform {
68            Some(p) => p.regions().iter().map(|r| r.space).collect(),
69            None => self.regions.keys().copied().collect(),
70        }
71    }
72
73    /// Space names are driver-defined.
74    pub fn resolve_space(&self, name: &str) -> Result<AddressSpace, Error> {
75        let spaces = self.spaces();
76        match AddressSpace::from_dsl_name(name) {
77            Some(space) if spaces.contains(&space) => Ok(space),
78            _ => Err(ErrorKind::UnknownSpace {
79                name: name.to_string(),
80                suggestion: crate::commands::closest(name, spaces.iter().map(|s| s.dsl_name()))
81                    .map(str::to_string),
82            }
83            .into()),
84        }
85    }
86
87    /// The `.area` header for `space`: the driver's when a CPU is set, else a
88    /// plain default built from the space name.
89    fn area_header(&self, space: AddressSpace) -> String {
90        self.platform
91            .as_ref()
92            .and_then(|p| p.area_header(space))
93            .map(str::to_string)
94            .unwrap_or_else(|| format!(".area {} (ABS)\n", space.dsl_name()))
95    }
96
97    pub fn region(&self, space: AddressSpace) -> Option<&Region> {
98        self.regions.get(&space)
99    }
100
101    pub fn region_mut(&mut self, space: AddressSpace) -> &mut Region {
102        let platform = self.platform.clone();
103        self.regions
104            .entry(space)
105            .or_insert_with(|| Region::new(space, platform))
106    }
107
108    pub fn xrefs_to(&self, target: &PhysicalAddr) -> Vec<Xref> {
109        // Each region indexes only its own instructions. Regions without code
110        // carry an empty index and contribute nothing.
111        self.regions
112            .values()
113            .flat_map(|region| region.xrefs_to(target))
114            .filter(|x| self.pointer_candidate_survives(x))
115            .collect()
116    }
117
118    /// Whether an inferred pointer candidate is still alive.
119    fn pointer_candidate_survives(&self, xref: &Xref) -> bool {
120        if xref.certainty != Certainty::Inferred {
121            return true;
122        }
123        match self
124            .regions
125            .get(&xref.from.space)
126            .and_then(|r| r.operand_type(xref.from.offset))
127        {
128            Some(OperandType::Pointer(space)) => xref.to.space == space,
129            // A number references nothing, so no candidate survives.
130            Some(OperandType::Value) => false,
131            None => true,
132        }
133    }
134
135    /// Instructions with ambiguous operands, as `(instruction, value, candidate
136    /// spaces)`.
137    pub fn undecided_operands(&self) -> Vec<(SpaceAddressValue, AddressValue, Vec<AddressSpace>)> {
138        let mut by_site: BTreeMap<(AddressSpace, AddressValue, AddressValue), Vec<AddressSpace>> =
139            BTreeMap::new();
140        for (&space, region) in &self.regions {
141            for (target, _, _) in region.inferred_pointer_candidates() {
142                for from in region.pointer_sources(&target) {
143                    if region.operand_type(from).is_some() {
144                        continue;
145                    }
146                    let spaces = by_site.entry((space, from, target.offset)).or_default();
147                    if !spaces.contains(&target.space) {
148                        spaces.push(target.space);
149                    }
150                }
151            }
152        }
153        by_site
154            .into_iter()
155            .filter(|(_, spaces)| spaces.len() > 1)
156            .map(|((space, from, value), spaces)| ((space, from).into(), value, spaces))
157            .collect()
158    }
159
160    pub fn xrefs_from(&self, source: &PhysicalAddr) -> Vec<Xref> {
161        let Some(region) = self.regions.get(&source.space) else {
162            return Vec::new();
163        };
164        region
165            .xrefs_from(source)
166            .into_iter()
167            .filter(|x| self.pointer_candidate_survives(x))
168            .collect()
169    }
170
171    /// The control-flow graph of the routine rooted at `entry` in `space`.
172    pub fn basic_blocks(&self, space: AddressSpace, entry: AddressValue) -> Vec<Block> {
173        self.region(space)
174            .map(|region| region.basic_blocks(entry))
175            .unwrap_or_default()
176    }
177
178    /// Decode bytes as code from `start` without committing, for a caller to
179    /// judge whether a run is really code (see [`Region::scratch_decode`]).
180    pub fn peek(
181        &self,
182        space: AddressSpace,
183        start: AddressValue,
184        max_lines: usize,
185    ) -> ScratchDecode {
186        self.region(space)
187            .map(|region| region.scratch_decode(start, max_lines))
188            .unwrap_or_default()
189    }
190
191    /// Test-decode `start..end` as one straight run without committing, for a
192    /// caller about to commit the whole range as code (see
193    /// [`Region::scratch_decode_linear`]).
194    pub fn peek_linear(
195        &self,
196        space: AddressSpace,
197        start: AddressValue,
198        end: AddressValue,
199    ) -> ScratchDecode {
200        self.region(space)
201            .map(|region| region.scratch_decode_linear(start, end))
202            .unwrap_or_default()
203    }
204
205    pub fn undecoded_entry_points(&self) -> Vec<crate::platform::EntryPoint> {
206        let Some(platform) = &self.platform else {
207            return Vec::new();
208        };
209        platform
210            .entry_points()
211            .iter()
212            .filter(|e| {
213                self.region(e.space).is_some_and(|r| {
214                    r.has_byte(e.offset)
215                        && !r.platform_address_disabled(e.offset)
216                        && !matches!(
217                            r.get_equivalent_kind(e.offset),
218                            Some(crate::db::EquivalentKind::Code)
219                        )
220                })
221            })
222            .copied()
223            .collect()
224    }
225
226    /// Follow pure jump thunks from `addr` to the ultimate target. Rendering
227    /// stays faithful to the bytes, so this is how a consumer asks where a call
228    /// or jump really ends up. Returns `addr` when it is not a thunk.
229    pub fn resolve_thunk(&self, space: AddressSpace, addr: AddressValue) -> AddressValue {
230        self.region(space)
231            .map_or(addr, |region| region.resolve_thunks(addr))
232    }
233
234    fn implicit_labels(&self) -> ImplicitLabels {
235        let mut label_collector = LabelCollector::default();
236        for region in self.regions.values() {
237            region.collect_refs(&mut label_collector);
238        }
239        let mut labels = label_collector.into_implicit_labels();
240        // Prefer platform names
241        if let Some(platform) = &self.platform {
242            for entry in platform.entry_points() {
243                let decoded = self.region(entry.space).is_some_and(|r| {
244                    matches!(
245                        r.get_equivalent_kind(entry.offset),
246                        Some(EquivalentKind::Code)
247                    )
248                });
249                if decoded {
250                    labels.insert_if_absent(entry.space, entry.offset, entry.name);
251                }
252            }
253        }
254        labels
255    }
256
257    pub fn render(&self, space: AddressSpace) -> Vec<Line> {
258        let implicit_labels = self.implicit_labels();
259
260        self.regions
261            .get(&space)
262            .map(|region| region.render(space, &implicit_labels))
263            .unwrap_or_default()
264    }
265
266    pub fn render_range(
267        &self,
268        space: AddressSpace,
269        start: AddressValue,
270        end: AddressValue,
271    ) -> Vec<Line> {
272        self.render(space)
273            .into_iter()
274            .filter(|line| {
275                let addr = line.addr();
276                addr >= start && addr < end
277            })
278            .collect()
279    }
280
281    pub fn to_sdas(&self) -> String {
282        let mut writer = SdasWriter::default();
283        let implicit_labels = self.implicit_labels();
284
285        for space in self.spaces() {
286            let Some(region) = self.regions.get(&space) else {
287                continue;
288            };
289            writer.write(&self.area_header(space));
290            // Assembly names, not listing names
291            let names =
292                region.export_names(implicit_labels.get(&space).unwrap_or(&Default::default()));
293            for line in region.render_named(space, &implicit_labels, Some(&names)) {
294                writer.write_line(&line);
295            }
296        }
297
298        writer.into_string()
299    }
300
301    pub fn to_commands(&self) -> Vec<Box<dyn Command>> {
302        let mut commands = Vec::new();
303        // The CPU comes first: the rest of the script decodes against it.
304        if let Some(platform) = &self.platform {
305            commands.push(boxed(SetCpu::new(platform.name().to_string())));
306        }
307        for (&space, region) in &self.regions {
308            // Emit SetAddressBits first ...
309            if let Some(bits) = region.address_bits() {
310                commands.push(boxed(crate::commands::SetAddressBits {
311                    space: space.dsl_name().to_string(),
312                    bits: AddressValue::from(bits),
313                }));
314            }
315            // ... then the region's own commands
316            commands.extend(region.to_commands(space));
317            // ... then any disabled platform addresses
318            for (offset, reason) in region.disabled_platform_addresses() {
319                commands.push(boxed(crate::commands::DisablePlatformAddress {
320                    address: (space, offset).into(),
321                    reason: reason.to_string(),
322                }));
323            }
324            for (offset, kind) in region.operand_types() {
325                commands.push(match kind {
326                    OperandType::Pointer(target) => boxed(crate::commands::SetOperandPointer {
327                        address: (space, offset).into(),
328                        space: target.dsl_name().to_string(),
329                    }),
330                    OperandType::Value => boxed(crate::commands::SetOperandValue {
331                        address: (space, offset).into(),
332                    }),
333                });
334            }
335        }
336
337        for (id, note) in self.notes.notes.iter() {
338            if let Some((space, range)) = self.notes.location(id) {
339                commands.push(boxed(SetNote {
340                    address: (space, range).into(),
341                    note: note.clone(),
342                }));
343            }
344        }
345        commands
346    }
347
348    pub fn apply(
349        &mut self,
350        command: Box<dyn Command>,
351        env: Option<&dyn Environment>,
352    ) -> Result<Vec<Box<dyn Command>>, Error> {
353        self.check(command.as_ref())?;
354        command.apply(self, env)
355    }
356
357    /// Judgment safe to run on replay.
358    fn check(&self, command: &dyn Command) -> Result<(), CommandError> {
359        self.check_cpu_still_needed(command)?;
360        self.check_label(command)?;
361        self.check_speculative_decode(command)
362    }
363
364    fn check_cpu_still_needed(&self, command: &dyn Command) -> Result<(), CommandError> {
365        if command
366            .as_any()
367            .downcast_ref::<crate::commands::ClearCpu>()
368            .is_none()
369        {
370            return Ok(());
371        }
372        let Some(cpu) = self.platform().map(|p| p.name().to_string()) else {
373            return Ok(());
374        };
375        let decoded: u64 = self
376            .regions
377            .values()
378            .map(|region| u64::from(region.coverage().code))
379            .sum();
380        if decoded == 0 {
381            return Ok(());
382        }
383        Err(ErrorKind::CpuStillNeeded { cpu, decoded }.into())
384    }
385
386    fn check_label(&self, command: &dyn Command) -> Result<(), CommandError> {
387        let Some(set) = command.as_any().downcast_ref::<crate::commands::SetLabel>() else {
388            return Ok(());
389        };
390        let Ok(name) = crate::commands::normalize_label(&set.label) else {
391            return Ok(());
392        };
393        let here = set.address.space.dsl_addr(set.address.offset);
394        if crate::labels::is_provisional_name(&name) {
395            return Err(
396                CommandError::from(ErrorKind::GeneratedLabel { label: name }).suggest(vec![
397                    dsl!(set_label(address = {here}, label = "...")
398                        # "a name that says what the code does, e.g. uart_tx"),
399                    dsl!(set_note(address = {here}, note = Note(content = "..."))
400                        # "record what you know if you cannot tell yet"),
401                ]),
402            );
403        }
404        if set.local {
405            return self.check_duplicate_local(set, &name);
406        }
407        for (&space, region) in &self.regions {
408            let clash = region
409                .labels()
410                .map(|(offset, label)| (offset, label.to_string()))
411                .chain(
412                    region
413                        .functions()
414                        .map(|(offset, f)| (offset, f.name.clone())),
415                )
416                .find(|(offset, label)| {
417                    *label == name && (space, *offset) != (set.address.space, set.address.offset)
418                });
419            let Some((offset, _)) = clash else { continue };
420            let holder = space.dsl_addr(offset);
421            return Err(CommandError::from(ErrorKind::LabelTaken {
422                label: name.clone(),
423                holder: holder.clone(),
424            })
425            .suggest(vec![
426                dsl!(set_label(address = {here}, label = "...")
427                    # "a name that distinguishes it from {holder}"),
428                dsl!(set_label(address = {here}, label = "{name}", local = True)
429                    # "if this is a spot inside a routine, not a routine of its own"),
430                dsl!(set_label(address = {holder}, label = "...")
431                    # "to free the name if this is its better home"),
432            ]));
433        }
434        Ok(())
435    }
436
437    fn check_duplicate_local(
438        &self,
439        set: &crate::commands::SetLabel,
440        name: &str,
441    ) -> Result<(), CommandError> {
442        let space = set.address.space;
443        let Some(region) = self.region(space) else {
444            return Ok(());
445        };
446        let Some(scope) = region.scope_of(set.address.offset) else {
447            return Ok(());
448        };
449        let clash = region
450            .labels()
451            .find(|&(at, other)| {
452                at != set.address.offset && other == name && region.scope_of(at) == Some(scope)
453            })
454            .map(|(at, _)| space.dsl_addr(at));
455        let Some(clash) = clash else { return Ok(()) };
456        let here = space.dsl_addr(set.address.offset);
457        Err(CommandError::from(ErrorKind::LocalLabelTaken {
458            label: name.to_string(),
459            holder: clash,
460        })
461        .suggest(vec![
462            dsl!(set_label(address = {here}, label = "...", local = True)
463            # "a name unused in this routine"),
464        ]))
465    }
466
467    fn check_speculative_decode(&self, command: &dyn Command) -> Result<(), CommandError> {
468        let Some(range) = command
469            .as_any()
470            .downcast_ref::<crate::commands::DisassembleRange>()
471        else {
472            return Ok(());
473        };
474        if range.force {
475            return Ok(());
476        }
477        let space = range.range.space;
478        let decode = self.peek_linear(space, range.range.start, range.range.end);
479        let mut reasons = Vec::new();
480        if decode.out_of_range_targets > 0 {
481            reasons.push(format!(
482                "{} branch target(s) point outside the loaded image",
483                decode.out_of_range_targets
484            ));
485        }
486        if decode.self_misaligned_targets > 0 {
487            reasons.push(format!(
488                "{} branch target(s) land midway through another instruction in the same range",
489                decode.self_misaligned_targets
490            ));
491        }
492        if decode.misaligned_targets > 0 {
493            reasons.push(format!(
494                "{} branch target(s) land inside existing instructions",
495                decode.misaligned_targets
496            ));
497        }
498        if reasons.is_empty() {
499            return Ok(());
500        }
501        Err(CommandError::from(ErrorKind::RangeDoesNotDecode {
502            count: decode.lines.len(),
503            reasons,
504        })
505        .suggest(vec![
506            dsl!(auto_disassemble(address = {space.dsl_addr(range.range.start)})
507                    # "follows flow and stops where it stops"),
508            dsl!(mark_data(
509                    range = {space.dsl_range(range.range.start, range.range.end)},
510                    data_type = DataType::Byte
511                ) # "if the whole range is data"),
512            dsl!(disassemble_range(
513                    range = {space.dsl_range(range.range.start, range.range.end)},
514                    force = True
515                ) # "to decode the bytes as-is"),
516        ]))
517    }
518
519    /// Byte counts for mapped content classified by equivalent kind.
520    pub fn space_usage(&self, space: AddressSpace) -> SpaceUsage {
521        self.regions
522            .get(&space)
523            .map(Region::space_usage)
524            .unwrap_or_default()
525    }
526
527    pub fn clear_note(
528        &mut self,
529        id: &NoteId,
530    ) -> Option<(AddressSpace, crate::address::AddressRange, Note)> {
531        self.notes.clear_address(id)
532    }
533
534    pub fn note_tip(&self) -> Option<NoteId> {
535        self.notes.tip()
536    }
537
538    pub fn create_note(&mut self, content: impl Into<String>) -> Note {
539        self.notes.create(content)
540    }
541
542    pub fn get_notes_overlapping(
543        &self,
544        space: AddressSpace,
545        range: impl std::ops::RangeBounds<AddressValue>,
546    ) -> Vec<&Note> {
547        self.notes.get_notes_overlapping(space, range)
548    }
549
550    pub fn get_notes_inside(
551        &self,
552        space: AddressSpace,
553        range: impl std::ops::RangeBounds<AddressValue>,
554    ) -> Vec<&Note> {
555        self.notes.get_notes_inside(space, range)
556    }
557
558    /// Notes within `window` bytes of `addr`, nearest first.
559    pub fn notes_near(
560        &self,
561        space: AddressSpace,
562        addr: AddressValue,
563        window: AddressValue,
564    ) -> Vec<crate::note::ProximateNote<'_>> {
565        self.notes.notes_near(space, addr, window)
566    }
567
568    /// Notes matching `query` (case-insensitive over content, tags, fields).
569    pub fn search_notes(&self, query: &str) -> Vec<&Note> {
570        self.notes.search(query)
571    }
572
573    /// Where a note is attached, if anywhere.
574    pub fn note_location(
575        &self,
576        id: &NoteId,
577    ) -> Option<(AddressSpace, crate::address::AddressRange)> {
578        self.notes.location(id)
579    }
580}
581
582impl Default for Db {
583    fn default() -> Self {
584        Self::new()
585    }
586}
587
588#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
589pub struct Function {
590    pub addr: PhysicalAddr,
591    pub name: String,
592    pub signature: Option<String>,
593    pub length: AddressValue,
594    pub noreturn: bool,
595}
596
597#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize)]
598pub enum DataType {
599    Byte,
600    Word,
601    Dword,
602    Qword,
603    Reference(Box<DataType>),
604    Equivalent(Box<DataType>, String),
605    Array(Box<DataType>, usize),
606    String(usize),
607    Struct(Vec<DataType>),
608}
609
610#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize)]
611pub enum OperandOverride {
612    Label(String),
613    LabelOffset { label: String, offset: i32 },
614    Text(String),
615}
616
617#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize)]
618pub enum Equivalent {
619    Code,
620    Data(DataType, AddressValue),
621    /// A barrier of the given byte length: renders raw, but blocks
622    /// auto-disassembly (unlike undefined bytes, which it flows into).
623    Unknown(AddressValue),
624}
625
626impl Equivalent {
627    pub fn kind(&self) -> EquivalentKind {
628        match self {
629            Self::Code => EquivalentKind::Code,
630            Self::Data(_, _) => EquivalentKind::Data,
631            Self::Unknown(_) => EquivalentKind::Unknown,
632        }
633    }
634}
635
636#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize)]
637pub enum EquivalentKind {
638    Code,
639    Data,
640    Unknown,
641}
642
643#[derive(Debug, Clone, Eq, PartialEq)]
644pub struct EquivalentRange {
645    pub end: AddressValue,
646    pub equivalent: Equivalent,
647}
648
649#[derive(Debug, Clone, Eq, PartialEq)]
650pub enum EquivalentAt<'a> {
651    Undefined(Range<AddressValue>),
652    Defined {
653        start: AddressValue,
654        range: &'a EquivalentRange,
655    },
656}
657
658impl<'a> EquivalentAt<'a> {
659    pub fn is_defined(&self) -> bool {
660        matches!(self, Self::Defined { .. })
661    }
662}
663
664#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
665pub struct SpaceUsage {
666    /// Bytes covered by a `Equivalent::Code` range.
667    pub code: AddressValue,
668    /// Bytes covered by a `Equivalent::Data` range.
669    pub data: AddressValue,
670    /// Mapped bytes with no equivalent (rendered as raw data).
671    pub undefined: AddressValue,
672}
673
674impl SpaceUsage {
675    pub fn total(&self) -> AddressValue {
676        self.code
677            .saturating_add(self.data)
678            .saturating_add(self.undefined)
679    }
680}
681
682/// A refused command: facts plus commands that resolve it.
683#[derive(Debug)]
684pub struct CommandError {
685    pub what: ErrorKind,
686    /// Commands that resolve it, runnable verbatim.
687    pub suggested: Vec<String>,
688}
689
690/// Kept for existing signatures.
691pub type Error = CommandError;
692
693impl CommandError {
694    /// Attach commands that resolve this error.
695    pub fn suggest(mut self, suggested: Vec<String>) -> Self {
696        #[cfg(debug_assertions)]
697        for suggestion in &suggested {
698            if let Err(e) = crate::store::parse_call(suggestion) {
699                panic!("error suggestion does not parse: {suggestion:?}: {e}");
700            }
701        }
702        self.suggested = suggested;
703        self
704    }
705}
706
707impl From<ErrorKind> for CommandError {
708    fn from(what: ErrorKind) -> Self {
709        Self {
710            what,
711            suggested: Vec::new(),
712        }
713    }
714}
715
716impl From<std::io::Error> for CommandError {
717    fn from(error: std::io::Error) -> Self {
718        ErrorKind::Io {
719            message: error.to_string(),
720        }
721        .into()
722    }
723}
724
725impl std::fmt::Display for CommandError {
726    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
727        write!(f, "{:?}", self.what)?;
728        for suggestion in &self.suggested {
729            write!(f, "\n  {suggestion}")?;
730        }
731        Ok(())
732    }
733}
734
735impl std::error::Error for CommandError {}
736
737/// The facts of a refused command, rendered elsewhere.
738#[derive(Debug, Serialize)]
739#[serde(tag = "kind", rename_all = "snake_case")]
740pub enum ErrorKind {
741    /// File access needed, none attached.
742    NoEnvironment,
743    /// A disassembly command with no CPU selected.
744    NoCpu,
745    /// `set_cpu` while a CPU is selected.
746    CpuAlreadySet { current: String },
747    /// A CPU with no built-in driver.
748    UnknownCpu {
749        name: String,
750        suggestions: Vec<String>,
751    },
752    /// A range overlapping an existing classification.
753    Overlap { at: String, marked: String },
754    /// An unmap cutting a longer classification.
755    PartialEquivalent { range: String, marked: String },
756    /// An illegal assembler symbol.
757    InvalidLabel { label: String, reason: &'static str },
758    /// A value the command cannot take.
759    InvalidArgument { value: String, reason: &'static str },
760    /// An address space this database lacks.
761    UnknownSpace {
762        name: String,
763        suggestion: Option<String>,
764    },
765    /// A classify target with no mapped byte.
766    NothingMapped { at: String },
767    /// A classification the bytes cannot take.
768    InvalidEquivalent,
769    /// A mark over already-classified bytes.
770    AlreadyClassified {
771        at: String,
772        marked: String,
773        covering: String,
774        /// Bytes the unblocking clear takes.
775        cleared: u64,
776        /// Bytes the command asked about.
777        asked: u64,
778    },
779    /// A filesystem failure.
780    Io { message: String },
781    /// A cleared CPU with decoded bytes.
782    CpuStillNeeded { cpu: String, decoded: u64 },
783    /// A label another address already holds.
784    LabelTaken { label: String, holder: String },
785    /// A local label reused inside one routine.
786    LocalLabelTaken { label: String, holder: String },
787    /// A label equal to the generated form.
788    GeneratedLabel { label: String },
789    /// A range that decodes badly.
790    RangeDoesNotDecode { count: usize, reasons: Vec<String> },
791    /// A classify range covering live vectors.
792    RangeCoversVectors { vectors: Vec<String> },
793    /// An auto-disassemble root under a barrier.
794    BarrierStopsAuto {
795        at: String,
796        barrier: String,
797        marked: String,
798    },
799    /// A classify range covering branch targets.
800    RangeSwallowsTargets {
801        /// `addr (from callers)` phrases, at most four.
802        targets: Vec<String>,
803        omitted: usize,
804        first_target: String,
805        first_source: String,
806        sources: usize,
807    },
808}
809
810/// The word for a classification in messages.
811pub(crate) fn marked_word(kind: EquivalentKind) -> &'static str {
812    match kind {
813        EquivalentKind::Code => "code",
814        EquivalentKind::Data => "data",
815        EquivalentKind::Unknown => "barrier",
816    }
817}
818
819/// A [`ErrorKind::NothingMapped`] with its fixes.
820pub(crate) fn nothing_mapped(space: AddressSpace, offset: AddressValue) -> CommandError {
821    let at = space.dsl_addr(offset);
822    let range = space.dsl_range(offset, offset.saturating_add(1));
823    CommandError::from(ErrorKind::NothingMapped { at: at.clone() }).suggest(vec![
824        dsl!(map_bytes(address = {at}, file = "...", file_offset = 0x0, size = 0x0)
825            # "bring bytes in from the image file"),
826        dsl!(set_constant_bytes(range = {range}, value = 0x0)
827            # "fill the gap with a value, then classify again"),
828    ])
829}
830
831/// An [`ErrorKind::AlreadyClassified`] with its unblocking clear.
832pub(crate) fn already_classified(
833    at: SpaceAddressValue,
834    existing: EquivalentKind,
835    start: AddressValue,
836    end: AddressValue,
837    requested_end: AddressValue,
838) -> CommandError {
839    let space = at.space;
840    let mut suggested = vec![dsl!(clear_equivalents(
841        addresses = { space.dsl_set(start, end) }
842    ))];
843    if at.offset > start {
844        suggested.push(dsl!(mark_data(
845            range = {space.dsl_range(start, at.offset)},
846            data_type = DataType::Byte
847        ) # "restore this remainder after the clear"));
848    }
849    if requested_end < end {
850        suggested.push(dsl!(mark_data(
851            range = {space.dsl_range(requested_end, end)},
852            data_type = DataType::Byte
853        ) # "restore this remainder after the clear"));
854    }
855    CommandError::from(ErrorKind::AlreadyClassified {
856        at: space.dsl_addr(at.offset),
857        marked: marked_word(existing).to_string(),
858        covering: space.dsl_range(start, end),
859        cleared: u64::from(end.saturating_sub(start)),
860        asked: u64::from(requested_end.saturating_sub(at.offset)),
861    })
862    .suggest(suggested)
863}
864
865#[cfg(test)]
866mod tests {
867    use std::collections::HashMap;
868    use std::io;
869
870    use super::*;
871    use crate::address::SpaceAddressSet;
872    use crate::address::XrefType;
873    use crate::commands::{
874        AutoDisassemble, ClearLabel, Command, MapBytes, SetConstantBytes, UnmapBytes, boxed,
875    };
876    use crate::platform::{Certainty, i8051::CODE};
877    use pretty_assertions::assert_eq;
878
879    static TEST_BINARY: [u8; 12] = [
880        0x02, 0x00, 0x10, // LJMP 0x10
881        0x74, 0x01, // MOV A, #0x1
882        0xF0, // MOVX @DPTR, A
883        0x90, 0x00, 0x10, // MOV DPTR, #0x10
884        0x93, // MOVC A, @A+DPTR
885        0x80, 0xF7, // SJMP 0x3 (rel = 3 - (10 + 2))
886    ];
887
888    struct TestEnvironment {
889        files: HashMap<String, Vec<u8>>,
890    }
891
892    impl TestEnvironment {
893        fn new() -> Self {
894            Self {
895                files: HashMap::new(),
896            }
897        }
898
899        fn with_file(mut self, name: impl Into<String>, bytes: Vec<u8>) -> Self {
900            self.files.insert(name.into(), bytes);
901            self
902        }
903    }
904
905    impl Environment for TestEnvironment {
906        fn load_file_bytes(
907            &self,
908            file: &str,
909            offset: usize,
910            size: AddressValue,
911        ) -> Result<Vec<u8>, io::Error> {
912            let data = self.files.get(file).ok_or_else(|| {
913                io::Error::new(io::ErrorKind::NotFound, format!("file not found: {file}"))
914            })?;
915            let end = offset.saturating_add(size as usize);
916            if end > data.len() {
917                return Err(io::Error::new(
918                    io::ErrorKind::UnexpectedEof,
919                    "read past end of file",
920                ));
921            }
922            Ok(data[offset..end].to_vec())
923        }
924    }
925
926    fn apply_all(db: &mut Db, commands: Vec<Box<dyn Command>>, env: &TestEnvironment) {
927        for command in commands {
928            db.apply(command, Some(env)).unwrap();
929        }
930    }
931
932    #[test]
933    fn decoded_vectors_named() {
934        let mut db = Db::with_platform(crate::platform::i8051::platform());
935        let code = db.region_mut(CODE);
936        code.set_bytes("test.bin", 0, 0, &[0x00; 0x30]);
937        code.set_equivalent(0, Equivalent::Code).unwrap();
938        code.set_equivalent(0x0B, Equivalent::Code).unwrap();
939
940        let labels = db.implicit_labels();
941        let named = &labels[&CODE];
942        assert_eq!(named.get(&0).map(String::as_str), Some("INT_reset"));
943        assert_eq!(named.get(&0x0B).map(String::as_str), Some("INT_timer0"));
944        assert_eq!(named.get(&0x03), None, "filler must not be labelled");
945    }
946
947    fn make_test_db() -> Db {
948        let mut db = Db::with_platform(crate::platform::i8051::platform());
949
950        let code = db.region_mut(CODE);
951        code.set_bytes("test.bin", 0, 0, &TEST_BINARY);
952
953        code.set_label(0, "start", LabelAttrs::default());
954        code.set_equivalent(0, Equivalent::Code).unwrap();
955
956        code.set_comment(3, "Start of loop");
957        code.set_label(3, "loop", LabelAttrs::default());
958        code.set_equivalent(3, Equivalent::Code).unwrap();
959        code.set_equivalent(5, Equivalent::Code).unwrap();
960        code.set_equivalent(6, Equivalent::Code).unwrap();
961        code.set_equivalent(9, Equivalent::Code).unwrap();
962        code.set_equivalent(10, Equivalent::Code).unwrap();
963        db
964    }
965
966    /// An i8051 DB with `bytes` mapped from `file` at CODE:0, plus its env.
967    fn mapped(file: &str, bytes: &[u8]) -> (Db, TestEnvironment) {
968        let env = TestEnvironment::new().with_file(file, bytes.to_vec());
969        let mut db = Db::with_platform(crate::platform::i8051::platform());
970        let size = bytes.len() as AddressValue;
971        db.apply(
972            boxed(MapBytes::new((CODE, 0), file, 0usize, size)),
973            Some(&env),
974        )
975        .unwrap();
976        (db, env)
977    }
978
979    /// Export `db` to DSL and rebuild from scratch (resolving `map_bytes` files
980    /// against `env`): the save/reload path.
981    fn reload(db: &Db, env: &TestEnvironment) -> Db {
982        use crate::store::{from_dsl_many, to_dsl_many};
983        let mut reloaded = Db::new();
984        for command in from_dsl_many(&to_dsl_many(&db.to_commands())).unwrap() {
985            let env = (command.name() == "map_bytes").then_some(env as &dyn Environment);
986            reloaded.apply(command, env).unwrap();
987        }
988        reloaded
989    }
990
991    #[test]
992    fn test_db() {
993        let db = make_test_db();
994        assert_eq!(
995            db.xrefs_to(&PhysicalAddr {
996                space: CODE,
997                offset: 3
998            }),
999            vec![Xref {
1000                xref_type: XrefType::Jump,
1001                from: PhysicalAddr {
1002                    space: CODE,
1003                    offset: 10
1004                },
1005                to: PhysicalAddr {
1006                    space: CODE,
1007                    offset: 3
1008                },
1009                certainty: Certainty::Definite,
1010            }]
1011        );
1012
1013        assert_eq!(
1014            db.xrefs_from(&PhysicalAddr {
1015                space: CODE,
1016                offset: 10
1017            }),
1018            vec![Xref {
1019                xref_type: XrefType::Jump,
1020                from: PhysicalAddr {
1021                    space: CODE,
1022                    offset: 10
1023                },
1024                to: PhysicalAddr {
1025                    space: CODE,
1026                    offset: 3
1027                },
1028                certainty: Certainty::Definite,
1029            }]
1030        );
1031
1032        let expected = r#"
1033.area CODE (CODE,ABS)
1034.org 0x0
1035
1036start:
1037    LJMP    loc_0010
1038; Start of loop
1039loop:
1040    MOV     A,#01
1041    MOVX    @DPTR,A
1042    MOV     DPTR,#0x0010
1043    MOVC    A,@A+DPTR
1044    SJMP    loop
1045loc_0010:
1046        "#;
1047        assert_eq!(db.to_sdas().trim(), expected.trim());
1048    }
1049
1050    // Also the general round-trip test: the full `make_test_db` listing (labels,
1051    // comments, strong code) survives export to DSL and reload.
1052    #[test]
1053    fn round_trips_with_notes() {
1054        use crate::address::AddressRange;
1055        use crate::commands::SetNote;
1056
1057        let env = TestEnvironment::new().with_file("test.bin", TEST_BINARY.to_vec());
1058        let mut db = make_test_db();
1059
1060        // Attach two notes (one tagged) to address ranges.
1061        let mut first = Note::new(None, "reset handler");
1062        first.tags.insert("entry".into());
1063        let second = Note::new(Some(&first.id), "jump table");
1064        db.apply(boxed(SetNote::new((CODE, 0x0..0x3), first.clone())), None)
1065            .unwrap();
1066        db.apply(boxed(SetNote::new((CODE, 0x3..0x5), second.clone())), None)
1067            .unwrap();
1068
1069        assert!(
1070            crate::store::to_dsl_many(&db.to_commands()).contains("set_note("),
1071            "notes must be exported"
1072        );
1073        let reloaded = reload(&db, &env);
1074
1075        // Both notes survived with their ids, content, tags, and locations.
1076        assert_eq!(reloaded.notes.notes.len(), 2);
1077        assert_eq!(reloaded.notes.get(&first.id), Some(&first));
1078        assert_eq!(reloaded.notes.get(&second.id), Some(&second));
1079        assert_eq!(
1080            reloaded.note_location(&first.id),
1081            Some((CODE, AddressRange::new(0x0, 0x3)))
1082        );
1083        assert_eq!(
1084            reloaded.note_location(&second.id),
1085            Some((CODE, AddressRange::new(0x3, 0x5)))
1086        );
1087
1088        // The listing (which excludes notes) is unchanged.
1089        assert_eq!(reloaded.to_sdas(), db.to_sdas());
1090    }
1091
1092    #[test]
1093    fn map_bytes_command_undo() {
1094        // Mapping over existing bytes undoes back to the originals.
1095        let env = TestEnvironment::new()
1096            .with_file("test.bin", vec![1, 2, 3])
1097            .with_file("other.bin", vec![4, 5]);
1098        let mut db = Db::with_platform(crate::platform::i8051::platform());
1099        db.apply(
1100            boxed(MapBytes::new((CODE, 0), "test.bin", 0usize, 3u32)),
1101            Some(&env),
1102        )
1103        .unwrap();
1104
1105        let undo = db
1106            .apply(
1107                boxed(MapBytes::new((CODE, 0), "other.bin", 0usize, 2u32)),
1108                Some(&env),
1109            )
1110            .unwrap();
1111        assert_eq!(db.region(CODE).unwrap().bytes_at(0, 2), vec![4, 5]);
1112
1113        apply_all(&mut db, undo, &env);
1114        assert_eq!(db.region(CODE).unwrap().bytes_at(0, 3), vec![1, 2, 3]);
1115    }
1116
1117    #[test]
1118    fn unmap_bytes_command_undo() {
1119        let (mut db, env) = mapped("t.bin", &[1, 2, 3, 4, 5]);
1120        let undo = db
1121            .apply(boxed(UnmapBytes::new((CODE, 1..3))), None)
1122            .unwrap();
1123        assert_eq!(db.region(CODE).unwrap().bytes_at(0, 5), vec![1, 4, 5]);
1124
1125        apply_all(&mut db, undo, &env);
1126        assert_eq!(db.region(CODE).unwrap().bytes_at(0, 5), vec![1, 2, 3, 4, 5]);
1127    }
1128
1129    #[test]
1130    fn constant_bytes_undo() {
1131        let (mut db, env) = mapped("t.bin", &[1, 2, 3]);
1132        let undo = db
1133            .apply(boxed(SetConstantBytes::new((CODE, 0..2), 0xFF)), None)
1134            .unwrap();
1135        assert_eq!(db.region(CODE).unwrap().bytes_at(0, 3), vec![0xFF, 0xFF, 3]);
1136
1137        apply_all(&mut db, undo, &env);
1138        assert_eq!(db.region(CODE).unwrap().bytes_at(0, 3), vec![1, 2, 3]);
1139    }
1140
1141    #[test]
1142    fn sweep_undo_removes_code() {
1143        let (mut db, env) = mapped("t.bin", &TEST_BINARY);
1144        let undo = db
1145            .apply(boxed(AutoDisassemble::new((CODE, 0))), None)
1146            .unwrap();
1147
1148        // Derived code, so the undo is just the root-clear. Nothing to un-set.
1149        assert!(db.space_usage(CODE).code > 0);
1150        assert!(db.region(CODE).unwrap().is_auto_root(0));
1151        assert_eq!(undo.len(), 1);
1152        assert_eq!(undo[0].name(), "clear_auto_disassemble_root");
1153
1154        apply_all(&mut db, undo, &env);
1155        assert_eq!(db.space_usage(CODE).code, 0);
1156        assert!(!db.region(CODE).unwrap().is_auto_root(0));
1157    }
1158
1159    #[test]
1160    fn sweep_exports_as_root() {
1161        // MOV A,#1 / INC A / SJMP back: a self-contained loop.
1162        let (mut db, env) = mapped("loop.bin", &[0x74, 0x01, 0x04, 0x80, 0xFB]);
1163        // The region method (which library callers use) must record a root.
1164        assert!(db.region_mut(CODE).auto_disassemble(0).is_success());
1165        assert!(db.region(CODE).unwrap().is_auto_root(0));
1166
1167        let dsl = crate::store::to_dsl_many(&db.to_commands());
1168        assert!(dsl.contains("auto_disassemble(address=CODE:0x0)"), "{dsl}");
1169        assert!(!dsl.contains("disassemble_range"), "{dsl}");
1170
1171        assert_eq!(reload(&db, &env).to_sdas(), db.to_sdas());
1172    }
1173
1174    #[test]
1175    fn barrier_chops_sweep() {
1176        use crate::commands::MarkUnknown;
1177
1178        // MOV A,#1 / INC A / NOP / RET: a straight-line run.
1179        let (mut db, env) = mapped("b.bin", &[0x74, 0x01, 0x04, 0x00, 0x22]);
1180        // Barrier at 0x3, set before disassembling.
1181        db.apply(boxed(MarkUnknown::new((CODE, 0x3u32..0x4u32))), None)
1182            .unwrap();
1183        db.apply(boxed(AutoDisassemble::new((CODE, 0u32))), None)
1184            .unwrap();
1185
1186        // Flow stops at the barrier: 0x3 stays unknown, 0x4 is never reached.
1187        let region = db.region(CODE).unwrap();
1188        assert_eq!(region.get_equivalent_kind(0x0), Some(EquivalentKind::Code));
1189        assert_eq!(region.get_equivalent_kind(0x2), Some(EquivalentKind::Code));
1190        assert_eq!(
1191            region.get_equivalent_kind(0x3),
1192            Some(EquivalentKind::Unknown)
1193        );
1194        assert_eq!(region.get_equivalent_kind(0x4), None);
1195
1196        assert!(
1197            crate::store::to_dsl_many(&db.to_commands())
1198                .contains("mark_unknown(range=CODE:0x3..0x4)"),
1199            "barrier is exported as a verb"
1200        );
1201        assert_eq!(reload(&db, &env).to_sdas(), db.to_sdas());
1202    }
1203
1204    #[test]
1205    fn barrier_chops_retroactively() {
1206        use crate::commands::MarkUnknown;
1207
1208        // MOV A,#1 / INC A / NOP / RET: a straight-line run.
1209        let (mut db, _env) = mapped("b.bin", &[0x74, 0x01, 0x04, 0x00, 0x22]);
1210        // Disassemble the whole run first.
1211        db.apply(boxed(AutoDisassemble::new((CODE, 0u32))), None)
1212            .unwrap();
1213        let region = db.region(CODE).unwrap();
1214        assert_eq!(region.get_equivalent_kind(0x3), Some(EquivalentKind::Code));
1215        assert_eq!(region.get_equivalent_kind(0x4), Some(EquivalentKind::Code));
1216
1217        // Drop a barrier mid-flow. Derived code re-derives, so 0x3 onward vanish.
1218        db.apply(boxed(MarkUnknown::new((CODE, 0x3u32..0x4u32))), None)
1219            .unwrap();
1220        let region = db.region(CODE).unwrap();
1221        assert_eq!(region.get_equivalent_kind(0x0), Some(EquivalentKind::Code));
1222        assert_eq!(region.get_equivalent_kind(0x2), Some(EquivalentKind::Code));
1223        assert_eq!(
1224            region.get_equivalent_kind(0x3),
1225            Some(EquivalentKind::Unknown)
1226        );
1227        assert_eq!(region.get_equivalent_kind(0x4), None);
1228    }
1229
1230    #[test]
1231    fn extents_coalesce_on_export() {
1232        use crate::commands::{DisassembleRange, MarkData};
1233
1234        // MOV A,#1 / INC A (a 3-byte code block), then 2 data bytes.
1235        let (mut db, env) = mapped("m.bin", &[0x74, 0x01, 0x04, 0xAA, 0xBB]);
1236        db.apply(
1237            boxed(DisassembleRange::new((CODE, 0u32..3u32), false)),
1238            None,
1239        )
1240        .unwrap();
1241        db.apply(
1242            boxed(MarkData::new((CODE, 3u32..5u32), DataType::Byte)),
1243            None,
1244        )
1245        .unwrap();
1246
1247        let dsl = crate::store::to_dsl_many(&db.to_commands());
1248        assert!(
1249            dsl.contains("disassemble_range(range=CODE:0x0..0x3, force=True)"),
1250            "code island coalesced: {dsl}"
1251        );
1252        assert!(
1253            dsl.contains("mark_data(range=CODE:0x3..0x5, data_type=DataType::Byte)"),
1254            "data as a verb: {dsl}"
1255        );
1256        assert!(
1257            !dsl.contains("set_equivalent"),
1258            "no low-level command: {dsl}"
1259        );
1260
1261        assert_eq!(reload(&db, &env).to_sdas(), db.to_sdas());
1262    }
1263
1264    #[test]
1265    fn override_operand_undoes() {
1266        use crate::commands::{DisassembleRange, OverrideOperand};
1267        use crate::db::OperandOverride;
1268
1269        // CJNE A,0x20,rel: three operands. We override the third.
1270        let (mut db, env) = mapped("b.bin", &[0xB5, 0x20, 0x10]);
1271        db.apply(boxed(DisassembleRange::new((CODE, 0u32..3u32), true)), None)
1272            .unwrap();
1273        let undo = db
1274            .apply(
1275                boxed(OverrideOperand::new(
1276                    (CODE, 0u32),
1277                    2u8,
1278                    Some(OperandOverride::Text("HOT".into())),
1279                )),
1280                None,
1281            )
1282            .unwrap();
1283        assert!(db.to_sdas().contains("HOT"), "{}", db.to_sdas());
1284
1285        assert!(crate::store::to_dsl_many(&db.to_commands()).contains("override_operand("));
1286        assert_eq!(reload(&db, &env).to_sdas(), db.to_sdas());
1287
1288        // Undo clears the override.
1289        apply_all(&mut db, undo, &env);
1290        assert!(!db.to_sdas().contains("HOT"), "{}", db.to_sdas());
1291    }
1292
1293    #[test]
1294    fn clear_labels_undo_restores() {
1295        let mut db = Db::with_platform(crate::platform::i8051::platform());
1296        let code = db.region_mut(CODE);
1297        code.set_label(0x10, "a", LabelAttrs::default());
1298        code.set_label(0x14, "b", LabelAttrs::default());
1299        code.set_label(0x20, "c", LabelAttrs::default());
1300
1301        // Clear a single range covering the first two labels in one command.
1302        let mut set = SpaceAddressSet::new(CODE);
1303        set.insert(0x10..0x18);
1304        let undo = db.apply(boxed(ClearLabel::new(set)), None).unwrap();
1305
1306        let code = db.region(CODE).unwrap();
1307        assert_eq!(code.get_label(0x10), None);
1308        assert_eq!(code.get_label(0x14), None);
1309        assert_eq!(code.get_label(0x20), Some("c")); // outside the set, untouched
1310
1311        // The undo restores both cleared labels.
1312        apply_all(&mut db, undo, &TestEnvironment::new());
1313        let code = db.region(CODE).unwrap();
1314        assert_eq!(code.get_label(0x10), Some("a"));
1315        assert_eq!(code.get_label(0x14), Some("b"));
1316    }
1317
1318    #[test]
1319    fn refusal_names_restore_bytes() {
1320        let err = crate::db::already_classified(
1321            (CODE, 0xb6eu32).into(),
1322            EquivalentKind::Data,
1323            0xad5,
1324            0x1000,
1325            0xb72,
1326        );
1327        assert!(matches!(
1328            err.what,
1329            ErrorKind::AlreadyClassified { cleared: 0x52b, .. }
1330        ));
1331        let text = err.to_string();
1332        assert!(
1333            text.contains("clear_equivalents(addresses=CODE:{0xad5..0x1000})"),
1334            "the clear has to be named: {text}"
1335        );
1336        assert!(
1337            text.contains("mark_data(range=CODE:0xad5..0xb6e"),
1338            "the bytes before the request have to be restorable: {text}"
1339        );
1340        assert!(
1341            text.contains("mark_data(range=CODE:0xb72..0x1000"),
1342            "the bytes after the request have to be restorable: {text}"
1343        );
1344    }
1345
1346    #[test]
1347    fn refusals_name_unblocking_command() {
1348        let occupied = crate::db::already_classified(
1349            (CODE, 0x8u32).into(),
1350            EquivalentKind::Code,
1351            0x8,
1352            0xA,
1353            0xA,
1354        );
1355        assert!(matches!(
1356            &occupied.what,
1357            ErrorKind::AlreadyClassified { marked, .. } if marked == "code"
1358        ));
1359        let text = occupied.to_string();
1360        assert!(
1361            text.contains("clear_equivalents(addresses=CODE:{0x8..0xa})"),
1362            "the message must carry a runnable command: {text}"
1363        );
1364        // Request and equivalent coincide, so there is no remainder to restore.
1365        assert!(!text.contains("mark_data"), "{text}");
1366
1367        let unmapped = crate::db::nothing_mapped(CODE, 0x8);
1368        assert!(matches!(
1369            &unmapped.what,
1370            ErrorKind::NothingMapped { at } if at == "CODE:0x8"
1371        ));
1372    }
1373}