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 platform: Option<PlatformRef>,
27 pub notes: NoteDb,
28}
29
30impl Db {
31 pub fn new() -> Self {
34 Self {
35 regions: BTreeMap::new(),
36 platform: None,
37 notes: NoteDb::default(),
38 }
39 }
40
41 pub fn with_platform(platform: PlatformRef) -> Self {
43 let mut db = Self::new();
44 db.set_platform(Some(platform));
45 db
46 }
47
48 pub fn platform(&self) -> Option<&dyn Platform> {
50 self.platform.as_deref()
51 }
52
53 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 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 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 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 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 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 Some(OperandType::Value) => false,
131 None => true,
132 }
133 }
134
135 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 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 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 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 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 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 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 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 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 commands.extend(region.to_commands(space));
317 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 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 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 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 pub fn search_notes(&self, query: &str) -> Vec<&Note> {
570 self.notes.search(query)
571 }
572
573 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 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 pub code: AddressValue,
668 pub data: AddressValue,
670 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#[derive(Debug)]
684pub struct CommandError {
685 pub what: ErrorKind,
686 pub suggested: Vec<String>,
688}
689
690pub type Error = CommandError;
692
693impl CommandError {
694 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#[derive(Debug, Serialize)]
739#[serde(tag = "kind", rename_all = "snake_case")]
740pub enum ErrorKind {
741 NoEnvironment,
743 NoCpu,
745 CpuAlreadySet { current: String },
747 UnknownCpu {
749 name: String,
750 suggestions: Vec<String>,
751 },
752 Overlap { at: String, marked: String },
754 PartialEquivalent { range: String, marked: String },
756 InvalidLabel { label: String, reason: &'static str },
758 InvalidArgument { value: String, reason: &'static str },
760 UnknownSpace {
762 name: String,
763 suggestion: Option<String>,
764 },
765 NothingMapped { at: String },
767 InvalidEquivalent,
769 AlreadyClassified {
771 at: String,
772 marked: String,
773 covering: String,
774 cleared: u64,
776 asked: u64,
778 },
779 Io { message: String },
781 CpuStillNeeded { cpu: String, decoded: u64 },
783 LabelTaken { label: String, holder: String },
785 LocalLabelTaken { label: String, holder: String },
787 GeneratedLabel { label: String },
789 RangeDoesNotDecode { count: usize, reasons: Vec<String> },
791 RangeCoversVectors { vectors: Vec<String> },
793 BarrierStopsAuto {
795 at: String,
796 barrier: String,
797 marked: String,
798 },
799 RangeSwallowsTargets {
801 targets: Vec<String>,
803 omitted: usize,
804 first_target: String,
805 first_source: String,
806 sources: usize,
807 },
808}
809
810pub(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
819pub(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
831pub(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, 0x74, 0x01, 0xF0, 0x90, 0x00, 0x10, 0x93, 0x80, 0xF7, ];
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 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 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 #[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 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 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 assert_eq!(reloaded.to_sdas(), db.to_sdas());
1090 }
1091
1092 #[test]
1093 fn map_bytes_command_undo() {
1094 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 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 let (mut db, env) = mapped("loop.bin", &[0x74, 0x01, 0x04, 0x80, 0xFB]);
1163 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 let (mut db, env) = mapped("b.bin", &[0x74, 0x01, 0x04, 0x00, 0x22]);
1180 db.apply(boxed(MarkUnknown::new((CODE, 0x3u32..0x4u32))), None)
1182 .unwrap();
1183 db.apply(boxed(AutoDisassemble::new((CODE, 0u32))), None)
1184 .unwrap();
1185
1186 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 let (mut db, _env) = mapped("b.bin", &[0x74, 0x01, 0x04, 0x00, 0x22]);
1210 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 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 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 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 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 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")); 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 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}