1use std::sync::Arc;
10
11use crate::address::{AddressSpace, AddressValue, PhysicalAddr, Xref, XrefType};
12
13pub mod i8051;
14pub mod m6805;
15pub mod mos6502;
16
17#[derive(Debug, Clone, Copy, PartialEq, Eq)]
20pub enum ControlFlow {
21 Continue { next: AddressValue },
23 Jump { target: AddressValue },
25 Call {
27 target: AddressValue,
28 return_pc: AddressValue,
29 },
30 Choice {
32 fall_through: AddressValue,
33 branch_target: AddressValue,
34 },
35 Diverge,
37}
38
39#[derive(Debug, Clone, Copy, PartialEq, Eq)]
42pub struct DataRef {
43 pub space: AddressSpace,
44 pub offset: AddressValue,
45 pub kind: XrefType,
46 pub certainty: Certainty,
47 pub operand: Option<u8>,
49}
50
51#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
54pub enum Certainty {
55 Definite,
57 Inferred,
59}
60
61#[derive(Debug, Clone)]
64pub struct DecodedInsn {
65 pub len: u8,
67 pub bytes: Vec<u8>,
69 pub text: String,
71 pub control_flow: ControlFlow,
73 pub branch_operand_index: Option<usize>,
76 pub named_register: Option<u8>,
79 pub data_refs: Vec<DataRef>,
81}
82
83impl DecodedInsn {
84 #[inline]
85 pub fn len(&self) -> usize {
86 self.len as usize
87 }
88
89 #[inline]
90 pub fn is_empty(&self) -> bool {
91 self.len == 0
92 }
93
94 #[inline]
95 pub fn bytes(&self) -> &[u8] {
96 &self.bytes
97 }
98
99 #[inline]
100 pub fn control_flow(&self) -> ControlFlow {
101 self.control_flow
102 }
103
104 #[inline]
105 pub fn as_string(&self) -> &str {
106 &self.text
107 }
108
109 #[inline]
113 pub fn direct_addr(&self) -> Option<u8> {
114 self.named_register
115 }
116}
117
118#[derive(Debug, Clone, Copy, PartialEq, Eq)]
120pub enum RegionKind {
121 Code,
123 Register,
125 Data,
127}
128
129#[derive(Debug, Clone)]
131pub struct RegionDef {
132 pub space: AddressSpace,
134 pub kind: RegionKind,
136 pub area_header: &'static str,
138}
139
140#[derive(Debug, Clone, Copy)]
142pub struct EntryPoint {
143 pub space: AddressSpace,
144 pub offset: AddressValue,
145 pub name: &'static str,
147 pub reason: &'static str,
149}
150
151#[derive(Debug, Clone, Copy, PartialEq, Eq)]
156pub struct CanonicalAddr {
157 pub space: AddressSpace,
158 pub offset: AddressValue,
159 pub bit: Option<u8>,
161}
162
163pub trait Platform: Send + Sync {
166 fn name(&self) -> &str;
168
169 fn regions(&self) -> &[RegionDef];
172
173 fn entry_points(&self) -> &[EntryPoint] {
176 &[]
177 }
178
179 fn canonicalize(&self, space: AddressSpace, offset: AddressValue) -> CanonicalAddr {
181 CanonicalAddr {
182 space,
183 offset,
184 bit: None,
185 }
186 }
187
188 fn max_insn_len(&self) -> usize;
190
191 fn decode(&self, pc: AddressValue, bytes: &[u8]) -> DecodedInsn;
196
197 fn area_header(&self, space: AddressSpace) -> Option<&'static str> {
199 self.regions()
200 .iter()
201 .find(|r| r.space == space)
202 .map(|r| r.area_header)
203 }
204}
205
206pub fn xrefs_from_instruction(insn: &DecodedInsn, source: PhysicalAddr) -> Vec<Xref> {
210 let mut xrefs = Vec::new();
211 let mut push = |space, offset, xref_type, certainty| {
212 xrefs.push(Xref {
213 from: source,
214 to: PhysicalAddr { space, offset },
215 xref_type,
216 certainty,
217 });
218 };
219
220 match insn.control_flow {
221 ControlFlow::Jump { target } => {
222 push(source.space, target, XrefType::Jump, Certainty::Definite)
223 }
224 ControlFlow::Call { target, .. } => {
225 push(source.space, target, XrefType::Call, Certainty::Definite)
226 }
227 ControlFlow::Choice { branch_target, .. } => push(
228 source.space,
229 branch_target,
230 XrefType::Jump,
231 Certainty::Definite,
232 ),
233 _ => {}
234 }
235
236 for data_ref in &insn.data_refs {
237 push(
238 data_ref.space,
239 data_ref.offset,
240 data_ref.kind,
241 data_ref.certainty,
242 );
243 }
244
245 xrefs
246}
247
248pub fn branch_target(insn: &DecodedInsn) -> Option<AddressValue> {
250 match insn.control_flow {
251 ControlFlow::Jump { target } | ControlFlow::Call { target, .. } => Some(target),
252 ControlFlow::Choice { branch_target, .. } => Some(branch_target),
253 _ => None,
254 }
255}
256
257pub fn branch_target_operand_index(insn: &DecodedInsn) -> Option<usize> {
259 insn.branch_operand_index
260}
261
262pub type PlatformRef = Arc<dyn Platform>;
264
265pub const BUILTIN_PLATFORMS: &[&str] = &["i8051", "mos6502", "m6805"];
267
268pub fn by_name(name: &str) -> Option<PlatformRef> {
270 match name {
271 "i8051" => Some(i8051::platform()),
272 "mos6502" => Some(mos6502::platform()),
273 "m6805" => Some(m6805::platform()),
274 _ => None,
275 }
276}
277
278pub fn suggest_names(query: &str) -> Vec<String> {
281 let q = query.to_ascii_lowercase();
282 let mut ranked: Vec<(bool, usize, &str)> = BUILTIN_PLATFORMS
283 .iter()
284 .map(|&name| {
285 let n = name.to_ascii_lowercase();
286 let substring = n.contains(&q) || q.contains(&n);
287 (substring, crate::strings::levenshtein(&q, &n), name)
288 })
289 .collect();
290 ranked.sort_by(|a, b| {
291 b.0.cmp(&a.0)
292 .then_with(|| a.1.cmp(&b.1))
293 .then_with(|| a.2.cmp(b.2))
294 });
295 ranked
296 .into_iter()
297 .map(|(_, _, name)| name.to_string())
298 .collect()
299}
300
301#[cfg(test)]
302mod suggest_tests {
303 use super::*;
304
305 #[test]
306 fn suggest_prefers_substring() {
307 assert_eq!(suggest_names("8051")[0], "i8051");
308 assert_eq!(suggest_names("6502")[0], "mos6502");
309 }
310
311 #[test]
312 fn suggest_orders_by_distance() {
313 let ranked = suggest_names("z80");
314 assert_eq!(ranked.len(), 3);
315 assert!(ranked.contains(&"i8051".to_string()));
316 }
317}
318
319#[cfg(test)]
321pub(crate) mod test_util {
322 use super::*;
323
324 pub(crate) fn edges(
327 driver: &dyn Platform,
328 bytes: &[u8],
329 ) -> Vec<(AddressSpace, AddressValue, XrefType)> {
330 let source = PhysicalAddr {
331 space: driver.regions()[0].space,
332 offset: 0,
333 };
334 xrefs_from_instruction(&driver.decode(0, bytes), source)
335 .into_iter()
336 .map(|x| (x.to.space, x.to.offset, x.xref_type))
337 .collect()
338 }
339}