1use crate::{checksum, write_marker};
2
3pub const BOOT_GUARD_SIZE: usize = 16;
4pub const CRASH_LOOP_LIMIT: u32 = 3;
5
6const MAGIC: [u8; 4] = *b"XBG1";
7
8pub struct BootGuard<'a>(&'a mut [u8; BOOT_GUARD_SIZE]);
10
11impl<'a> BootGuard<'a> {
12 pub fn new(storage: &'a mut [u8; BOOT_GUARD_SIZE]) -> Self {
13 Self(storage)
14 }
15
16 pub fn consecutive_crashes(&self) -> u32 {
17 if self.0[..4] != MAGIC || self.0[8..12] != checksum(&self.0[4..8]).to_le_bytes() {
18 return 0;
19 }
20 u32::from_le_bytes(self.0[4..8].try_into().unwrap())
21 }
22
23 pub fn record_crash(&mut self) -> u32 {
24 let count = self.consecutive_crashes().saturating_add(1);
25 self.set_count(count);
26 count
27 }
28
29 pub fn mark_stable(&mut self) {
30 self.set_count(0);
31 }
32
33 fn set_count(&mut self, count: u32) {
34 write_marker(self.0, [0; 4]);
35 self.0[4..8].copy_from_slice(&count.to_le_bytes());
36 let checksum = checksum(&self.0[4..8]);
37 self.0[8..12].copy_from_slice(&checksum.to_le_bytes());
38 self.0[12..].fill(0);
39 write_marker(self.0, MAGIC);
40 }
41}
42
43#[cfg(test)]
44mod tests {
45 use super::*;
46
47 #[test]
48 fn retains_counter_until_stable_and_rejects_corruption() {
49 let mut storage = [0; BOOT_GUARD_SIZE];
50 for expected in 1..=CRASH_LOOP_LIMIT {
51 assert_eq!(BootGuard::new(&mut storage).record_crash(), expected);
52 }
53 BootGuard::new(&mut storage).mark_stable();
54 assert_eq!(BootGuard::new(&mut storage).consecutive_crashes(), 0);
55 BootGuard::new(&mut storage).record_crash();
56 storage[4] ^= 1;
57 assert_eq!(BootGuard::new(&mut storage).consecutive_crashes(), 0);
58 }
59}