Skip to main content

crash/
record.rs

1use core::{fmt, str};
2
3use crate::{checksum, write_marker};
4
5pub const MAGIC: [u8; 4] = *b"XCR1";
6pub const VERSION: u16 = 1;
7pub const HEADER_SIZE: usize = 256;
8pub const ESPRESSIF_RECORD_CAPACITY: usize = 4096;
9pub const NATIVE_RECORD_CAPACITY: usize = 16_384;
10
11pub const MESSAGE_TRUNCATED: u16 = 1 << 0;
12pub const STACK_TRUNCATED: u16 = 1 << 1;
13pub const LOG_SKIPPED_CONTENTION: u16 = 1 << 2;
14pub const FRAMES_TRUNCATED: u16 = 1 << 3;
15pub const SECONDARY_CORE_UNHALTED: u16 = 1 << 4;
16
17macro_rules! tag {
18    ($name:ident { $($variant:ident = $value:literal),+ $(,)? }) => {
19        #[derive(Clone, Copy, Debug, PartialEq, Eq)]
20        #[repr(u8)]
21        pub enum $name { $($variant = $value),+ }
22
23        impl TryFrom<u8> for $name {
24            type Error = DecodeError;
25
26            fn try_from(value: u8) -> Result<Self, Self::Error> {
27                match value {
28                    $($value => Ok(Self::$variant),)+
29                    _ => Err(DecodeError::InvalidField),
30                }
31            }
32        }
33    };
34}
35
36tag!(RecordKind {
37    KernelPanic = 1,
38    KernelException = 2,
39    WatchdogReset = 3,
40    AbnormalHardwareReset = 4,
41    ApplicationCrash = 5,
42});
43
44tag!(Architecture {
45    XtensaEsp32 = 1,
46    XtensaEsp32S3 = 2,
47    Riscv32 = 3,
48    ArmThumbv7em = 4,
49    NativeX86_64 = 5,
50    NativeAarch64 = 6,
51    Wasm32 = 7,
52});
53
54tag!(ResetReason {
55    Unknown = 0,
56    SoftwareReset = 1,
57    Watchdog = 2,
58    BrownOut = 3,
59    CpuLockup = 4,
60    PinReset = 5,
61    PowerOn = 6,
62    HostSignal = 7,
63    HostPanic = 8,
64});
65
66tag!(BuildIdentifierKind {
67    None = 0,
68    ElfSha256 = 1,
69    GnuBuildIdentifier = 2,
70    WasmFingerprint = 3,
71});
72
73#[derive(Clone, Copy, Debug, PartialEq, Eq)]
74pub enum BuildIdentifier {
75    None,
76    ElfSha256([u8; 32]),
77    GnuBuildIdentifier([u8; 20]),
78    WasmFingerprint([u8; 32]),
79}
80
81#[derive(Clone, Copy, Debug, PartialEq, Eq)]
82pub struct Header<'a> {
83    pub kind: RecordKind,
84    pub architecture: Architecture,
85    pub reset_reason: ResetReason,
86    pub raw_reset_reason: u32,
87    pub exception_code: u32,
88    pub consecutive_crashes: u32,
89    pub uptime_microseconds: u64,
90    pub build_epoch: u64,
91    pub program_counter: u64,
92    pub stack_pointer: u64,
93    pub link_register: u64,
94    pub fault_address: u64,
95    pub stack_base: u64,
96    pub code_load_offset: u64,
97    pub core_identifier: u32,
98    pub task_identifier: u32,
99    pub build_identifier: BuildIdentifier,
100    pub task_name: &'a str,
101    pub target_name: &'a str,
102    pub firmware_version: &'a str,
103    pub flags: u16,
104}
105
106impl Header<'_> {
107    pub const fn new(kind: RecordKind, architecture: Architecture) -> Self {
108        Self {
109            kind,
110            architecture,
111            reset_reason: ResetReason::Unknown,
112            raw_reset_reason: 0,
113            exception_code: 0,
114            consecutive_crashes: 0,
115            uptime_microseconds: 0,
116            build_epoch: 0,
117            program_counter: 0,
118            stack_pointer: 0,
119            link_register: 0,
120            fault_address: 0,
121            stack_base: 0,
122            code_load_offset: 0,
123            core_identifier: 0,
124            task_identifier: 0,
125            build_identifier: BuildIdentifier::None,
126            task_name: "",
127            target_name: "",
128            firmware_version: "",
129            flags: 0,
130        }
131    }
132}
133
134#[derive(Clone, Copy, Debug)]
135pub struct Limits {
136    pub frames: u8,
137    pub message: u16,
138    pub stack: u16,
139    pub log_tail: u16,
140}
141
142impl Limits {
143    pub const ESPRESSIF: Self = Self {
144        frames: 24,
145        message: 512,
146        stack: 1024,
147        log_tail: 2048,
148    };
149    pub const NATIVE: Self = Self {
150        frames: 64,
151        message: 2048,
152        stack: 2048,
153        log_tail: 10_240,
154    };
155}
156
157/// Writes the payload in place. Dropping this writer before `finish` leaves
158/// the record invalid.
159pub struct Writer<'a> {
160    output: &'a mut [u8],
161    limits: Limits,
162    frame_count: u8,
163    flags: u16,
164}
165
166impl<'a> Writer<'a> {
167    /// Returns `None` if the slot cannot hold the fixed header.
168    pub fn new(output: &'a mut [u8], header: &Header<'_>, limits: Limits) -> Option<Self> {
169        let bytes = output.get_mut(..HEADER_SIZE)?;
170        write_marker(bytes, [0; 4]);
171        bytes[4..].fill(0);
172        put(bytes, 8, VERSION.to_le_bytes());
173        put(bytes, 10, (HEADER_SIZE as u16).to_le_bytes());
174        bytes[16] = header.kind as u8;
175        bytes[17] = header.architecture as u8;
176        bytes[18] = header.reset_reason as u8;
177        let identifier = &mut bytes[104..136];
178        let identifier_kind = match &header.build_identifier {
179            BuildIdentifier::None => BuildIdentifierKind::None,
180            BuildIdentifier::ElfSha256(value) => {
181                identifier.copy_from_slice(value);
182                BuildIdentifierKind::ElfSha256
183            }
184            BuildIdentifier::GnuBuildIdentifier(value) => {
185                identifier[..value.len()].copy_from_slice(value);
186                BuildIdentifierKind::GnuBuildIdentifier
187            }
188            BuildIdentifier::WasmFingerprint(value) => {
189                identifier.copy_from_slice(value);
190                BuildIdentifierKind::WasmFingerprint
191            }
192        };
193        bytes[19] = identifier_kind as u8;
194        put(bytes, 20, header.raw_reset_reason.to_le_bytes());
195        put(bytes, 24, header.exception_code.to_le_bytes());
196        put(bytes, 28, header.consecutive_crashes.to_le_bytes());
197        put(bytes, 32, header.uptime_microseconds.to_le_bytes());
198        put(bytes, 40, header.build_epoch.to_le_bytes());
199        put(bytes, 48, header.program_counter.to_le_bytes());
200        put(bytes, 56, header.stack_pointer.to_le_bytes());
201        put(bytes, 64, header.link_register.to_le_bytes());
202        put(bytes, 72, header.fault_address.to_le_bytes());
203        put(bytes, 80, header.stack_base.to_le_bytes());
204        put(bytes, 88, header.code_load_offset.to_le_bytes());
205        put(bytes, 96, header.core_identifier.to_le_bytes());
206        put(bytes, 100, header.task_identifier.to_le_bytes());
207        bytes[216] = put_text(bytes, 136, 32, header.task_name);
208        bytes[217] = put_text(bytes, 168, 32, header.target_name);
209        bytes[218] = put_text(bytes, 200, 16, header.firmware_version);
210        Some(Self {
211            output,
212            limits,
213            frame_count: 0,
214            flags: header.flags,
215        })
216    }
217
218    /// Returns false and sets `FRAMES_TRUNCATED` when the frame does not fit.
219    pub fn push_frame(&mut self, address: u64) -> bool {
220        let end = HEADER_SIZE + usize::from(self.frame_count) * 8;
221        if self.frame_count == self.limits.frames || self.output.len() - end < 8 {
222            self.flags |= FRAMES_TRUNCATED;
223            return false;
224        }
225        put(self.output, end, address.to_le_bytes());
226        self.frame_count += 1;
227        true
228    }
229
230    /// Commits the record and returns its valid bytes. The log callback copies
231    /// a UTF-8 tail into the supplied buffer, or returns `None` on contention.
232    pub fn finish(
233        self,
234        message: fmt::Arguments<'_>,
235        stack: &[u8],
236        snapshot_log: impl FnOnce(&mut [u8]) -> Option<usize>,
237    ) -> &'a [u8] {
238        self.finish_with_stack(
239            message,
240            stack.len(),
241            |output| output.copy_from_slice(&stack[..output.len()]),
242            snapshot_log,
243        )
244    }
245
246    /// Like `finish`, but copies the stack directly into the output slot.
247    /// The callback must fill the supplied window starting at `stack_base`.
248    pub fn finish_with_stack(
249        self,
250        message: fmt::Arguments<'_>,
251        stack_length: usize,
252        copy_stack: impl FnOnce(&mut [u8]),
253        snapshot_log: impl FnOnce(&mut [u8]) -> Option<usize>,
254    ) -> &'a [u8] {
255        use fmt::Write as _;
256
257        let mut flags = self.flags;
258        let mut end = HEADER_SIZE + usize::from(self.frame_count) * 8;
259        let capacity = self.output.len() - end;
260        let message_capacity = capacity.min(usize::from(self.limits.message));
261        let mut writer = MessageWriter {
262            buffer: &mut self.output[end..end + message_capacity],
263            length: 0,
264            truncated: false,
265        };
266        if writer.write_fmt(message).is_err() || writer.truncated {
267            flags |= MESSAGE_TRUNCATED;
268        }
269        let message_length = writer.length;
270        end += message_length;
271
272        let captured = stack_length
273            .min(usize::from(self.limits.stack))
274            .min(self.output.len() - end);
275        if captured < stack_length {
276            flags |= STACK_TRUNCATED;
277        }
278        let stack_output = &mut self.output[end..end + captured];
279        stack_output.fill(0);
280        copy_stack(stack_output);
281        end += captured;
282
283        let log_capacity = (self.output.len() - end).min(usize::from(self.limits.log_tail));
284        let log = &mut self.output[end..end + log_capacity];
285        // Initialize the buffer in case the callback reports bytes it did not write.
286        log.fill(0);
287        let log_length = match snapshot_log(log) {
288            Some(length) if length <= log.len() && str::from_utf8(&log[..length]).is_ok() => length,
289            Some(_) => 0,
290            None => {
291                flags |= LOG_SKIPPED_CONTENTION;
292                0
293            }
294        };
295        end += log_length;
296
297        self.output[219] = self.frame_count;
298        put(self.output, 220, (message_length as u16).to_le_bytes());
299        put(self.output, 222, (captured as u16).to_le_bytes());
300        put(self.output, 224, (log_length as u16).to_le_bytes());
301        put(self.output, 226, flags.to_le_bytes());
302        commit(&mut self.output[..end]);
303        &self.output[..end]
304    }
305}
306
307struct MessageWriter<'a> {
308    buffer: &'a mut [u8],
309    length: usize,
310    truncated: bool,
311}
312
313impl fmt::Write for MessageWriter<'_> {
314    fn write_str(&mut self, value: &str) -> fmt::Result {
315        let remaining = self.buffer.len() - self.length;
316        let length = value.floor_char_boundary(remaining);
317        self.buffer[self.length..self.length + length].copy_from_slice(&value.as_bytes()[..length]);
318        self.length += length;
319        if length < value.len() {
320            self.truncated = true;
321            return Err(fmt::Error);
322        }
323        Ok(())
324    }
325}
326
327fn commit(record: &mut [u8]) {
328    put(record, 12, (record.len() as u32).to_le_bytes());
329    let checksum = checksum(&record[8..]);
330    put(record, 4, checksum.to_le_bytes());
331    write_marker(record, MAGIC);
332}
333
334/// Clear the retained magic. The caller must exclude other slot users.
335pub fn invalidate(storage: &mut [u8; 4]) {
336    write_marker(storage, [0; 4]);
337}
338
339/// Fill a missing reset reason and recompute the checksum of a valid record.
340/// Returns the total record length, which can be smaller than the slot.
341pub fn complete_reset_reason(
342    bytes: &mut [u8],
343    reason: ResetReason,
344    raw_reason: u32,
345) -> Result<usize, DecodeError> {
346    let report = Record::read(bytes)?;
347    let length = report.bytes().len();
348    if report.header.reset_reason == ResetReason::Unknown {
349        write_marker(bytes, [0; 4]);
350        bytes[18] = reason as u8;
351        put(bytes, 20, raw_reason.to_le_bytes());
352        commit(&mut bytes[..length]);
353    }
354    Ok(length)
355}
356
357#[derive(Clone, Copy, Debug, PartialEq, Eq)]
358pub enum DecodeError {
359    Truncated,
360    InvalidMagic,
361    UnsupportedVersion(u16),
362    InvalidLength,
363    InvalidChecksum,
364    InvalidField,
365    InvalidText,
366}
367
368impl fmt::Display for DecodeError {
369    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
370        formatter.write_str(match self {
371            Self::Truncated => "Truncated crash record",
372            Self::InvalidMagic => "Invalid crash record magic",
373            Self::UnsupportedVersion(_) => "Unsupported crash record version",
374            Self::InvalidLength => "Invalid crash record length",
375            Self::InvalidChecksum => "Invalid crash record checksum",
376            Self::InvalidField => "Invalid crash record field",
377            Self::InvalidText => "Invalid UTF-8 in crash record",
378        })
379    }
380}
381
382impl core::error::Error for DecodeError {}
383
384#[derive(Debug)]
385pub struct Record<'a> {
386    bytes: &'a [u8],
387    frames: &'a [u8],
388    pub header: Header<'a>,
389    pub message: &'a str,
390    pub stack_window: &'a [u8],
391    pub log_tail: &'a str,
392}
393
394impl<'a> Record<'a> {
395    /// Validate one record at the start of a retained slot or file buffer.
396    pub fn read(bytes: &'a [u8]) -> Result<Self, DecodeError> {
397        let header = bytes.get(..HEADER_SIZE).ok_or(DecodeError::Truncated)?;
398        if header[..4] != MAGIC {
399            return Err(DecodeError::InvalidMagic);
400        }
401        let version = u16::from_le_bytes(get(header, 8));
402        if version != VERSION {
403            return Err(DecodeError::UnsupportedVersion(version));
404        }
405        if usize::from(u16::from_le_bytes(get(header, 10))) != HEADER_SIZE {
406            return Err(DecodeError::InvalidLength);
407        }
408
409        let frames_end = HEADER_SIZE + usize::from(header[219]) * 8;
410        let message_end = frames_end + usize::from(u16::from_le_bytes(get(header, 220)));
411        let stack_end = message_end + usize::from(u16::from_le_bytes(get(header, 222)));
412        let log_end = stack_end + usize::from(u16::from_le_bytes(get(header, 224)));
413        if u32::from_le_bytes(get(header, 12)) != log_end as u32 {
414            return Err(DecodeError::InvalidLength);
415        }
416        let bytes = bytes.get(..log_end).ok_or(DecodeError::Truncated)?;
417        if checksum(&bytes[8..]).to_le_bytes() != get::<4>(header, 4) {
418            return Err(DecodeError::InvalidChecksum);
419        }
420
421        let build_identifier = match BuildIdentifierKind::try_from(header[19])? {
422            BuildIdentifierKind::None => BuildIdentifier::None,
423            BuildIdentifierKind::ElfSha256 => BuildIdentifier::ElfSha256(get(header, 104)),
424            BuildIdentifierKind::GnuBuildIdentifier => {
425                BuildIdentifier::GnuBuildIdentifier(get(header, 104))
426            }
427            BuildIdentifierKind::WasmFingerprint => {
428                BuildIdentifier::WasmFingerprint(get(header, 104))
429            }
430        };
431        Ok(Self {
432            bytes,
433            frames: &bytes[HEADER_SIZE..frames_end],
434            header: Header {
435                kind: RecordKind::try_from(header[16])?,
436                architecture: Architecture::try_from(header[17])?,
437                reset_reason: ResetReason::try_from(header[18])?,
438                raw_reset_reason: u32::from_le_bytes(get(header, 20)),
439                exception_code: u32::from_le_bytes(get(header, 24)),
440                consecutive_crashes: u32::from_le_bytes(get(header, 28)),
441                uptime_microseconds: u64::from_le_bytes(get(header, 32)),
442                build_epoch: u64::from_le_bytes(get(header, 40)),
443                program_counter: u64::from_le_bytes(get(header, 48)),
444                stack_pointer: u64::from_le_bytes(get(header, 56)),
445                link_register: u64::from_le_bytes(get(header, 64)),
446                fault_address: u64::from_le_bytes(get(header, 72)),
447                stack_base: u64::from_le_bytes(get(header, 80)),
448                code_load_offset: u64::from_le_bytes(get(header, 88)),
449                core_identifier: u32::from_le_bytes(get(header, 96)),
450                task_identifier: u32::from_le_bytes(get(header, 100)),
451                build_identifier,
452                task_name: get_text(header, 136, 32, header[216])?,
453                target_name: get_text(header, 168, 32, header[217])?,
454                firmware_version: get_text(header, 200, 16, header[218])?,
455                flags: u16::from_le_bytes(get(header, 226)),
456            },
457            message: text(&bytes[frames_end..message_end])?,
458            stack_window: &bytes[message_end..stack_end],
459            log_tail: text(&bytes[stack_end..])?,
460        })
461    }
462
463    pub fn bytes(&self) -> &'a [u8] {
464        self.bytes
465    }
466
467    pub fn frames(&self) -> impl ExactSizeIterator<Item = u64> + 'a {
468        self.frames
469            .chunks_exact(8)
470            .map(|chunk| u64::from_le_bytes(chunk.try_into().unwrap()))
471    }
472}
473
474fn put<const SIZE: usize>(bytes: &mut [u8], offset: usize, value: [u8; SIZE]) {
475    bytes[offset..offset + SIZE].copy_from_slice(&value);
476}
477
478fn get<const SIZE: usize>(bytes: &[u8], offset: usize) -> [u8; SIZE] {
479    bytes[offset..offset + SIZE].try_into().unwrap()
480}
481
482fn put_text(bytes: &mut [u8], offset: usize, capacity: usize, value: &str) -> u8 {
483    let length = value.floor_char_boundary(capacity);
484    bytes[offset..offset + length].copy_from_slice(&value.as_bytes()[..length]);
485    length as u8
486}
487
488fn get_text(bytes: &[u8], offset: usize, capacity: usize, length: u8) -> Result<&str, DecodeError> {
489    let length = usize::from(length);
490    if length > capacity {
491        return Err(DecodeError::InvalidLength);
492    }
493    text(&bytes[offset..offset + length])
494}
495
496fn text(bytes: &[u8]) -> Result<&str, DecodeError> {
497    str::from_utf8(bytes).map_err(|_| DecodeError::InvalidText)
498}
499
500#[cfg(test)]
501mod tests {
502    use super::*;
503
504    fn header() -> Header<'static> {
505        Header {
506            task_name: "Shell",
507            target_name: "wt32-sc01-plus",
508            firmware_version: "0.1.0",
509            program_counter: 0x1234_5678,
510            core_identifier: 1,
511            task_identifier: 42,
512            build_identifier: BuildIdentifier::ElfSha256([0xAB; 32]),
513            ..Header::new(RecordKind::KernelPanic, Architecture::XtensaEsp32S3)
514        }
515    }
516
517    #[test]
518    fn round_trips_header_and_payload_at_fixed_offsets() {
519        let mut slot = [0xFF; 512];
520        let header = header();
521        let mut writer = Writer::new(&mut slot, &header, Limits::ESPRESSIF).unwrap();
522        assert!(writer.push_frame(0x0102_0304_0506_0708));
523        let encoded = writer.finish(format_args!("Panic"), &[0xFF, 0xAA], |log| {
524            log[..2].copy_from_slice(b"x\n");
525            Some(2)
526        });
527        let length = encoded.len();
528        assert_eq!(&encoded[..4], b"XCR1");
529        assert_eq!(&encoded[8..12], &[1, 0, 0, 1]);
530        assert_eq!(&encoded[48..56], &[0x78, 0x56, 0x34, 0x12, 0, 0, 0, 0]);
531        assert_eq!(&encoded[216..220], &[5, 14, 5, 1]);
532        assert_eq!(&encoded[228..256], &[0; 28]);
533        assert_eq!(&encoded[256..264], &[8, 7, 6, 5, 4, 3, 2, 1]);
534
535        let record = Record::read(&slot).unwrap();
536        assert_eq!(record.bytes().len(), length);
537        assert_eq!(record.header, header);
538        assert!(record.frames().eq([0x0102_0304_0506_0708]));
539        assert_eq!(record.message, "Panic");
540        assert_eq!(record.stack_window, [0xFF, 0xAA]);
541        assert_eq!(record.log_tail, "x\n");
542    }
543
544    #[test]
545    fn truncates_utf8_and_marks_limited_parts() {
546        let mut slot = [0; HEADER_SIZE + 12];
547        let limits = Limits {
548            frames: 1,
549            message: 2,
550            stack: 1,
551            log_tail: 0,
552        };
553        let mut writer = Writer::new(&mut slot, &header(), limits).unwrap();
554        assert!(writer.push_frame(1));
555        assert!(!writer.push_frame(2));
556        let bytes = writer.finish(format_args!("aƩ"), &[1, 2], |_| None);
557        let record = Record::read(bytes).unwrap();
558        assert_eq!(record.message, "a");
559        assert_eq!(record.stack_window, [1]);
560        assert_eq!(record.log_tail, "");
561        assert_eq!(
562            record.header.flags,
563            MESSAGE_TRUNCATED | STACK_TRUNCATED | FRAMES_TRUNCATED | LOG_SKIPPED_CONTENTION
564        );
565    }
566
567    #[test]
568    fn rejects_torn_truncated_and_corrupt_records() {
569        let mut slot = [0; 512];
570        Writer::new(&mut slot, &header(), Limits::ESPRESSIF).unwrap();
571        assert_eq!(Record::read(&slot).unwrap_err(), DecodeError::InvalidMagic);
572        let encoded = Writer::new(&mut slot, &header(), Limits::ESPRESSIF)
573            .unwrap()
574            .finish(format_args!("Panic"), &[], |_| Some(0));
575        for length in 0..encoded.len() {
576            assert_eq!(
577                Record::read(&encoded[..length]).unwrap_err(),
578                DecodeError::Truncated
579            );
580        }
581        slot[HEADER_SIZE] ^= 1;
582        assert_eq!(
583            Record::read(&slot).unwrap_err(),
584            DecodeError::InvalidChecksum
585        );
586        slot[12] ^= 1;
587        assert_eq!(Record::read(&slot).unwrap_err(), DecodeError::InvalidLength);
588        slot[8] = 2;
589        assert_eq!(
590            Record::read(&slot).unwrap_err(),
591            DecodeError::UnsupportedVersion(2)
592        );
593    }
594
595    #[test]
596    fn completes_reason_only_once() {
597        let mut slot = [0; 512];
598        Writer::new(&mut slot, &header(), Limits::ESPRESSIF)
599            .unwrap()
600            .finish(format_args!("Panic"), &[], |_| Some(0));
601        complete_reset_reason(&mut slot, ResetReason::SoftwareReset, 4).unwrap();
602        complete_reset_reason(&mut slot, ResetReason::Watchdog, 9).unwrap();
603        let record = Record::read(&slot).unwrap();
604        assert_eq!(record.header.reset_reason, ResetReason::SoftwareReset);
605        assert_eq!(record.header.raw_reset_reason, 4);
606    }
607}