sftool_lib/common/
debug_sequence.rs1use crate::{Error, Result};
2use std::fs::File;
3use std::io::{BufReader, Read, Seek, SeekFrom};
4
5pub const DEBUG_SEQUENCE: [u8; 8] = [0x41, 0x54, 0x53, 0x46, 0x33, 0x32, 0x05, 0x21];
6pub const REPLACEMENT_BYTE: u8 = 0xAA;
7pub const FLASH_WRITE_PAGE_SIZE: u64 = 128 * 1024;
8pub const REPLACE_MAX: usize = 50;
9pub const REPLACE_HEADER1: u32 = 0xABAB_BABA;
10pub const REPLACE_HEADER2: u32 = 0x3535_5353;
11pub const REPLACE_INFO_SIZE: usize = 4 + 4 + REPLACE_MAX * 8 + 4;
12
13#[derive(Debug, Clone, PartialEq, Eq)]
16pub struct DebugSequenceReplacementInfo {
17 offsets: Vec<u64>,
18}
19
20impl DebugSequenceReplacementInfo {
21 pub fn empty() -> Self {
22 Self {
23 offsets: Vec::new(),
24 }
25 }
26
27 pub fn scan_file(file: &File) -> Result<Self> {
28 let mut reader = BufReader::new(file.try_clone()?);
29 reader.seek(SeekFrom::Start(0))?;
30
31 let mut offsets = Vec::new();
32 let mut buffer = [0u8; 64 * 1024];
33 let mut tail = Vec::with_capacity(DEBUG_SEQUENCE.len() - 1);
34 let mut bytes_read_total = 0u64;
35
36 loop {
37 let bytes_read = reader.read(&mut buffer)?;
38 if bytes_read == 0 {
39 break;
40 }
41
42 let window_start = bytes_read_total.saturating_sub(tail.len() as u64);
43 let mut window = Vec::with_capacity(tail.len() + bytes_read);
44 window.extend_from_slice(&tail);
45 window.extend_from_slice(&buffer[..bytes_read]);
46
47 for (index, candidate) in window.windows(DEBUG_SEQUENCE.len()).enumerate() {
48 if candidate != DEBUG_SEQUENCE {
49 continue;
50 }
51
52 if offsets.len() == REPLACE_MAX {
53 return Err(Error::invalid_input(format!(
54 "debug sequence replacement count exceeds {REPLACE_MAX}"
55 )));
56 }
57 offsets.push(window_start + index as u64);
58 }
59
60 tail.clear();
61 let tail_start = window.len().saturating_sub(DEBUG_SEQUENCE.len() - 1);
62 tail.extend_from_slice(&window[tail_start..]);
63 bytes_read_total += bytes_read as u64;
64 }
65
66 Ok(Self { offsets })
67 }
68
69 pub fn is_empty(&self) -> bool {
70 self.offsets.is_empty()
71 }
72
73 pub fn len(&self) -> usize {
74 self.offsets.len()
75 }
76
77 pub fn encode(&self) -> Result<[u8; REPLACE_INFO_SIZE]> {
78 if self.offsets.len() > REPLACE_MAX {
79 return Err(Error::invalid_input(format!(
80 "debug sequence replacement count exceeds {REPLACE_MAX}"
81 )));
82 }
83
84 let mut data = [0u8; REPLACE_INFO_SIZE];
85 data[0..4].copy_from_slice(&REPLACE_HEADER1.to_le_bytes());
86 data[4..8].copy_from_slice(&(self.offsets.len() as u32).to_le_bytes());
87
88 for (index, offset) in self.offsets.iter().copied().enumerate() {
89 let block = u32::try_from(offset / FLASH_WRITE_PAGE_SIZE).map_err(|_| {
90 Error::invalid_input("debug sequence replacement block exceeds u32")
91 })?;
92 let position = u32::try_from(offset % FLASH_WRITE_PAGE_SIZE).map_err(|_| {
93 Error::invalid_input("debug sequence replacement position exceeds u32")
94 })?;
95 let start = 8 + index * 8;
96 data[start..start + 4].copy_from_slice(&block.to_le_bytes());
97 data[start + 4..start + 8].copy_from_slice(&position.to_le_bytes());
98 }
99
100 data[REPLACE_INFO_SIZE - 4..].copy_from_slice(&REPLACE_HEADER2.to_le_bytes());
101 Ok(data)
102 }
103
104 pub fn apply_to_chunk(&self, chunk_offset: u64, data: &mut [u8]) {
107 let chunk_end = chunk_offset.saturating_add(data.len() as u64);
108 for offset in &self.offsets {
109 if *offset >= chunk_offset && *offset < chunk_end {
110 data[(*offset - chunk_offset) as usize] = REPLACEMENT_BYTE;
111 }
112 }
113 }
114}
115
116#[cfg(test)]
117mod tests {
118 use super::*;
119 use std::io::Write;
120
121 fn scan(data: &[u8]) -> DebugSequenceReplacementInfo {
122 let mut file = tempfile::NamedTempFile::new().unwrap();
123 file.write_all(data).unwrap();
124 DebugSequenceReplacementInfo::scan_file(file.as_file()).unwrap()
125 }
126
127 #[test]
128 fn encodes_empty_info_with_fixed_layout() {
129 let info = scan(b"no debug marker here");
130
131 let encoded = info.encode().unwrap();
132
133 assert!(info.is_empty());
134 assert_eq!(REPLACE_MAX, 50);
135 assert_eq!(encoded.len(), 412);
136 assert_eq!(encoded.len(), REPLACE_INFO_SIZE);
137 assert_eq!(&encoded[0..4], &REPLACE_HEADER1.to_le_bytes());
138 assert_eq!(&encoded[4..8], &0u32.to_le_bytes());
139 assert_eq!(
140 &encoded[REPLACE_INFO_SIZE - 4..],
141 &REPLACE_HEADER2.to_le_bytes()
142 );
143 }
144
145 #[test]
146 fn detects_markers_across_scan_and_flash_write_boundaries() {
147 let mut data = vec![0u8; FLASH_WRITE_PAGE_SIZE as usize + 64];
148 let scan_boundary = 64 * 1024 - 3;
149 let page_boundary = FLASH_WRITE_PAGE_SIZE as usize - 4;
150 let second_page = FLASH_WRITE_PAGE_SIZE as usize + 10;
151 data[scan_boundary..scan_boundary + DEBUG_SEQUENCE.len()].copy_from_slice(&DEBUG_SEQUENCE);
152 data[page_boundary..page_boundary + DEBUG_SEQUENCE.len()].copy_from_slice(&DEBUG_SEQUENCE);
153 data[second_page..second_page + DEBUG_SEQUENCE.len()].copy_from_slice(&DEBUG_SEQUENCE);
154
155 let info = scan(&data);
156 let encoded = info.encode().unwrap();
157
158 assert_eq!(
159 info.offsets,
160 vec![
161 scan_boundary as u64,
162 page_boundary as u64,
163 second_page as u64
164 ]
165 );
166 assert_eq!(&encoded[8..12], &0u32.to_le_bytes());
167 assert_eq!(&encoded[12..16], &(scan_boundary as u32).to_le_bytes());
168 assert_eq!(&encoded[16..20], &0u32.to_le_bytes());
169 assert_eq!(&encoded[20..24], &(page_boundary as u32).to_le_bytes());
170 assert_eq!(&encoded[24..28], &1u32.to_le_bytes());
171 assert_eq!(&encoded[28..32], &10u32.to_le_bytes());
172 }
173
174 #[test]
175 fn only_replaces_recorded_bytes_in_the_transfer_buffer() {
176 let mut data = Vec::from(&b"prefix"[..]);
177 data.extend_from_slice(&DEBUG_SEQUENCE);
178 data.extend_from_slice(b"suffix");
179 let info = scan(&data);
180 let source = data.clone();
181
182 info.apply_to_chunk(0, &mut data);
183
184 assert_eq!(data[6], REPLACEMENT_BYTE);
185 assert_eq!(&data[7..14], &DEBUG_SEQUENCE[1..]);
186 assert_eq!(source[6], DEBUG_SEQUENCE[0]);
187 }
188
189 #[test]
190 fn supports_exactly_the_protocol_limit() {
191 let mut data = Vec::new();
192 for _ in 0..REPLACE_MAX {
193 data.extend_from_slice(&DEBUG_SEQUENCE);
194 }
195
196 let info = scan(&data);
197 let encoded = info.encode().unwrap();
198
199 assert_eq!(info.len(), REPLACE_MAX);
200 assert_eq!(&encoded[4..8], &(REPLACE_MAX as u32).to_le_bytes());
201 assert_eq!(encoded.len(), 412);
202 }
203
204 #[test]
205 fn rejects_more_than_the_protocol_limit() {
206 let mut data = Vec::new();
207 for _ in 0..=REPLACE_MAX {
208 data.extend_from_slice(&DEBUG_SEQUENCE);
209 }
210
211 let mut file = tempfile::NamedTempFile::new().unwrap();
212 file.write_all(&data).unwrap();
213 let error = DebugSequenceReplacementInfo::scan_file(file.as_file()).unwrap_err();
214
215 let expected_message = format!("exceeds {REPLACE_MAX}");
216 assert!(
217 matches!(error, Error::InvalidInput(message) if message.contains(&expected_message))
218 );
219 }
220}