// SPDX-License-Identifier: MIT //! Bus traces as JSON Lines, one object per bus cycle in chip order. //! //! Transcribed from `arm7tdmi_python/trace.py`. The family schema (as in sm83-python) with //! ARM's extra fields: //! //! ```text //! {"cycle": 12, "kind": "read", "address": 134217736, "width": 32, "access": 3, "value": 3818127360} //! {"cycle": 13, "kind": "internal", "address": 134217740} //! ``` //! //! `kind` is `read`, `write` or `internal`; `access` is the SEQ/CODE/LOCK bit set the core //! reported (the TRM's, before any board mapping such as [`crate::gba_access`]). The lines are //! byte for byte what the reference's `json.dumps` writes. //! //! Also here: the CRC-32 the lockstep gate's slice lines use (zlib's, as Python's //! `zlib.crc32`), so both sides hash the same bytes the same way. use std::io::Write; /// An observer for [`crate::harness::Harness`] that writes JSON Lines. pub struct TraceWriter { pub stream: W, pub cycle: u64, } impl TraceWriter { pub fn new(stream: W) -> Self { TraceWriter { stream, cycle: 0 } } pub fn record(&mut self, kind: &str, address: u32, width: u32, access: u32, value: u32) { let result = if kind != "internal" { writeln!( self.stream, "{{\"cycle\": {}, \"kind\": \"{}\", \"address\": {}, \"width\": {}, \"access\": {}, \"value\": {}}}", self.cycle, kind, address, width, access, value ) } else { writeln!( self.stream, "{{\"cycle\": {}, \"kind\": \"{}\", \"address\": {}}}", self.cycle, kind, address ) }; result.expect("trace write failed"); self.cycle += 1; } } /// zlib's CRC-32 (the polynomial 0xEDB88320, reflected), continued from `crc` as /// `zlib.crc32(data, crc)` does. pub fn crc32(crc: u32, data: &[u8]) -> u32 { static TABLE: [u32; 256] = { let mut table = [0u32; 256]; let mut n = 0; while n < 256 { let mut c = n as u32; let mut k = 0; while k < 8 { c = if c & 1 != 0 { 0xEDB8_8320 ^ (c >> 1) } else { c >> 1 }; k += 1; } table[n] = c; n += 1; } table }; let mut c = !crc; for &byte in data { c = TABLE[((c ^ byte as u32) & 0xFF) as usize] ^ (c >> 8); } !c } #[cfg(test)] mod tests { use super::crc32; #[test] fn crc32_is_zlibs() { // zlib.crc32(b"123456789") == 0xCBF43926 assert_eq!(crc32(0, b"123456789"), 0xCBF4_3926); assert_eq!(crc32(crc32(0, b"1234"), b"56789"), 0xCBF4_3926); } }