1use std::sync::Arc;
9
10use ::i8051::{Instruction, Mnemonic, Operand};
11
12pub use ::i8051::format_direct;
13
14use crate::address::{AddressSpace, AddressValue, XrefType};
15
16use super::{
17 CanonicalAddr, Certainty, ControlFlow, DataRef, DecodedInsn, EntryPoint, Platform, PlatformRef,
18 RegionDef, RegionKind,
19};
20
21pub const CODE: AddressSpace = AddressSpace::new("CODE");
23pub const IDATA: AddressSpace = AddressSpace::new("IDATA");
25pub const SFR: AddressSpace = AddressSpace::new("SFR");
27pub const BIT: AddressSpace = AddressSpace::new("BIT");
29pub const XDATA: AddressSpace = AddressSpace::new("XDATA");
31
32static REGIONS: &[RegionDef] = &[
34 RegionDef {
35 space: CODE,
36 kind: RegionKind::Code,
37 area_header: ".area CODE (CODE,ABS)\n",
38 },
39 RegionDef {
40 space: IDATA,
41 kind: RegionKind::Data,
42 area_header: ".area IDATA (IDATA,ABS)\n",
43 },
44 RegionDef {
45 space: SFR,
46 kind: RegionKind::Register,
47 area_header: ".area SFR (SFR,ABS)\n",
48 },
49 RegionDef {
50 space: BIT,
51 kind: RegionKind::Register,
52 area_header: ".area BIT (BIT,ABS)\n",
53 },
54 RegionDef {
55 space: XDATA,
56 kind: RegionKind::Data,
57 area_header: ".area XDATA (XDATA,ABS)\n",
58 },
59];
60
61static ENTRY_POINTS: &[EntryPoint] = &[
63 EntryPoint {
64 space: CODE,
65 offset: 0x00,
66 name: "INT_reset",
67 reason: "power-on reset",
68 },
69 EntryPoint {
70 space: CODE,
71 offset: 0x03,
72 name: "INT_ext0",
73 reason: "external interrupt 0",
74 },
75 EntryPoint {
76 space: CODE,
77 offset: 0x0B,
78 name: "INT_timer0",
79 reason: "timer 0 overflow",
80 },
81 EntryPoint {
82 space: CODE,
83 offset: 0x13,
84 name: "INT_ext1",
85 reason: "external interrupt 1",
86 },
87 EntryPoint {
88 space: CODE,
89 offset: 0x1B,
90 name: "INT_timer1",
91 reason: "timer 1 overflow",
92 },
93 EntryPoint {
94 space: CODE,
95 offset: 0x23,
96 name: "INT_serial",
97 reason: "serial port",
98 },
99];
100
101#[derive(Debug, Default, Clone, Copy)]
103pub struct I8051;
104
105pub fn platform() -> PlatformRef {
107 Arc::new(I8051)
108}
109
110impl Platform for I8051 {
111 fn name(&self) -> &str {
112 "i8051"
113 }
114
115 fn regions(&self) -> &[RegionDef] {
116 REGIONS
117 }
118
119 fn entry_points(&self) -> &[EntryPoint] {
120 ENTRY_POINTS
121 }
122
123 fn canonicalize(&self, space: AddressSpace, offset: AddressValue) -> CanonicalAddr {
125 if space != BIT || offset > 0xFF {
126 return CanonicalAddr {
127 space,
128 offset,
129 bit: None,
130 };
131 }
132 let n = offset as u8;
133 if n < 0x80 {
134 CanonicalAddr {
135 space: IDATA,
136 offset: AddressValue::from(0x20 + n / 8),
137 bit: Some(n % 8),
138 }
139 } else {
140 CanonicalAddr {
141 space: SFR,
142 offset: AddressValue::from(n & 0xF8),
143 bit: Some(n & 0x07),
144 }
145 }
146 }
147
148 fn max_insn_len(&self) -> usize {
149 Instruction::MAX_LENGTH
150 }
151
152 fn decode(&self, pc: u32, bytes: &[u8]) -> DecodedInsn {
153 let insn = Instruction::decode_from_bytes(pc, bytes);
154 let control_flow = map_control_flow(insn.control_flow());
155 DecodedInsn {
156 len: insn.len() as u8,
157 bytes: insn.bytes().to_vec(),
158 text: insn.as_string(),
159 control_flow,
160 branch_operand_index: branch_operand_index(&insn, control_flow),
161 named_register: insn.direct_addr(),
162 data_refs: data_refs(&insn),
163 }
164 }
165}
166
167fn map_control_flow(cf: ::i8051::ControlFlow) -> ControlFlow {
168 use ::i8051::ControlFlow as I;
169 match cf {
170 I::Continue { next } => ControlFlow::Continue { next },
171 I::Jump { target } => ControlFlow::Jump { target },
172 I::Call { target, return_pc } => ControlFlow::Call { target, return_pc },
173 I::Choice {
174 fall_through,
175 branch_target,
176 } => ControlFlow::Choice {
177 fall_through,
178 branch_target,
179 },
180 I::Diverge => ControlFlow::Diverge,
181 }
182}
183
184fn branch_operand_index(insn: &Instruction, cf: ControlFlow) -> Option<usize> {
188 match cf {
190 ControlFlow::Jump { .. } | ControlFlow::Call { .. } | ControlFlow::Choice { .. } => {}
191 _ => return None,
192 }
193 match insn.mnemonic() {
194 Mnemonic::LJMP | Mnemonic::LCALL | Mnemonic::AJMP | Mnemonic::ACALL | Mnemonic::SJMP => {
195 Some(0)
196 }
197 _ => {
198 let decoded = insn.as_string();
199 let operand_count = decoded.split_once(' ').map_or(0, |(_, rest)| {
200 if rest.is_empty() {
201 0
202 } else {
203 rest.split(',').count()
204 }
205 });
206 operand_count.checked_sub(1)
207 }
208 }
209}
210
211#[derive(Debug, Clone, Copy)]
213enum Access {
214 Read,
215 Write,
216 ReadWrite,
217}
218
219impl Access {
220 fn kind(self) -> XrefType {
221 match self {
222 Access::Read => XrefType::Read,
223 Access::Write => XrefType::Write,
224 Access::ReadWrite => XrefType::ReadWrite,
225 }
226 }
227}
228
229fn memory_access(mnemonic: Mnemonic, index: usize) -> Option<Access> {
234 use Mnemonic::*;
235 Some(match mnemonic {
236 MOV => {
237 if index == 0 {
238 Access::Write
239 } else {
240 Access::Read
241 }
242 }
243 ANL | ORL | XRL => {
244 if index == 0 {
245 Access::ReadWrite
246 } else {
247 Access::Read
248 }
249 }
250 CJNE | ADD | ADDC | SUBB | PUSH | JB | JNB => Access::Read,
251 POP | CLR | SETB => Access::Write,
252 INC | DEC | CPL | DJNZ | XCH | JBC => Access::ReadWrite,
253 _ => return None,
254 })
255}
256
257fn is_dptr_load(insn: &Instruction) -> bool {
258 insn.mnemonic() == Mnemonic::MOV
259 && matches!(
260 insn.operands().as_slice(),
261 [Operand::Dptr, Operand::Imm16(_)]
262 )
263}
264
265fn data_refs(insn: &Instruction) -> Vec<DataRef> {
270 let mut refs = Vec::new();
271 let dptr_load = is_dptr_load(insn);
272 for (index, operand) in insn.operands().as_slice().iter().enumerate() {
273 match operand {
274 Operand::Direct(addr) => {
275 if let Some(access) = memory_access(insn.mnemonic(), index) {
276 let space = if *addr >= 0x80 { SFR } else { IDATA };
277 refs.push(DataRef {
278 space,
279 offset: u32::from(*addr),
280 kind: access.kind(),
281 certainty: Certainty::Definite,
282 operand: u8::try_from(index).ok(),
283 });
284 }
285 }
286 Operand::Bit(addr) | Operand::BitNot(addr) => {
287 if let Some(access) = memory_access(insn.mnemonic(), index) {
288 refs.push(DataRef {
289 space: BIT,
290 offset: u32::from(*addr),
291 kind: access.kind(),
292 certainty: Certainty::Definite,
293 operand: u8::try_from(index).ok(),
294 });
295 }
296 }
297 Operand::Imm16(value) if dptr_load => {
298 for space in [CODE, XDATA] {
299 refs.push(DataRef {
300 space,
301 offset: u32::from(*value),
302 kind: XrefType::Pointer,
303 certainty: Certainty::Inferred,
304 operand: u8::try_from(index).ok(),
305 });
306 }
307 }
308 _ => {}
309 }
310 }
311 refs
312}
313
314#[cfg(test)]
315mod tests {
316 use super::*;
317 use crate::platform::test_util::edges;
318 use pretty_assertions::assert_eq;
319
320 #[test]
321 fn data_xrefs_classify_space() {
322 use XrefType::{Jump, Pointer, Read, ReadWrite, Write};
323 let e = |bytes: &[u8]| edges(&I8051, bytes);
324
325 assert_eq!(e(&[0xE5, 0x90]), vec![(SFR, 0x90, Read)]);
327 assert_eq!(e(&[0xF5, 0x90]), vec![(SFR, 0x90, Write)]);
328 assert_eq!(e(&[0x05, 0x30]), vec![(IDATA, 0x30, ReadWrite)]);
330 assert_eq!(
332 e(&[0x90, 0x12, 0x34]),
333 vec![(CODE, 0x1234, Pointer), (XDATA, 0x1234, Pointer)]
334 );
335 assert_eq!(
337 e(&[0x85, 0x40, 0x30]),
338 vec![(IDATA, 0x30, Write), (IDATA, 0x40, Read)]
339 );
340 assert_eq!(
342 e(&[0x20, 0x20, 0x05]),
343 vec![(CODE, 8, Jump), (BIT, 0x20, Read)]
344 );
345 }
346
347 #[test]
348 fn bit_addresses_resolve() {
349 let p = I8051;
350 let bit = |n| p.canonicalize(BIT, n);
351
352 assert_eq!(
354 bit(0x65),
355 CanonicalAddr {
356 space: IDATA,
357 offset: 0x2C,
358 bit: Some(5)
359 }
360 );
361 assert_eq!(
362 bit(0x00),
363 CanonicalAddr {
364 space: IDATA,
365 offset: 0x20,
366 bit: Some(0)
367 }
368 );
369 assert_eq!(
370 bit(0x7F),
371 CanonicalAddr {
372 space: IDATA,
373 offset: 0x2F,
374 bit: Some(7)
375 }
376 );
377
378 assert_eq!(
380 bit(0x99),
381 CanonicalAddr {
382 space: SFR,
383 offset: 0x98,
384 bit: Some(1)
385 }
386 );
387 assert_eq!(
388 bit(0xB3),
389 CanonicalAddr {
390 space: SFR,
391 offset: 0xB0,
392 bit: Some(3)
393 }
394 );
395
396 assert_eq!(
397 p.canonicalize(IDATA, 0x2C),
398 CanonicalAddr {
399 space: IDATA,
400 offset: 0x2C,
401 bit: None
402 }
403 );
404 assert_eq!(
405 p.canonicalize(SFR, 0x99),
406 CanonicalAddr {
407 space: SFR,
408 offset: 0x99,
409 bit: None
410 }
411 );
412
413 assert_ne!(bit(0x99).offset, p.canonicalize(SFR, 0x99).offset);
414 }
415}