Skip to main content Skip to main content
Pigweed's logo Pigweed
code_xml
  1. Home
  2. Reference
  3. Rust
  4. pw_kernel
  5. src
  6. pw_kernel_tracing/record.rs

pw_kernel_tracing/
record.rs

1// Copyright 2026 The Pigweed Authors
2//
3// Licensed under the Apache License, Version 2.0 (the "License"); you may not
4// use this file except in compliance with the License. You may obtain a copy of
5// the License at
6//
7//     https://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12// License for the specific language governing permissions and limitations under
13// the License.
14
15#[cfg(feature = "std")]
16use byteorder::ByteOrder;
17
18/// A trace record.
19///
20/// Trace records are fixed-size, 16-byte structures consisting of a header (timestamp,
21/// and event type) and event specific data.
22///
23/// # Structure
24/// | Bits       | Field      | Description                 |
25/// |------------|------------|-----------------------------|
26/// | \[0:25\]   | time_stamp | Time stamp of the event     |
27/// | \[26:31\]  | event_type | [`EventType`] of the record |
28/// | \[32:127\] | event_data | Event specific data         |
29#[derive(Debug, Clone, Copy)]
30pub struct Record {
31    pub event_type: EventType,
32    pub time_stamp: u32,
33    pub event_data: [u32; 3],
34}
35
36impl Record {
37    /// Reads a record from a byte buffer.
38    ///
39    /// The buffer must be at least 16 bytes long.
40    /// The endianness `T` determines how the bytes are interpreted.
41    ///
42    /// # Arguments
43    /// * `buffer`: A slice of at least 16 bytes.
44    ///
45    /// # Returns
46    /// * `Some(Record)` if the buffer is large enough and the event type is valid.
47    /// * `None` otherwise.
48    ///
49    /// # Example
50    /// ```
51    /// use pw_kernel_tracing::{Record, EventType};
52    /// use byteorder::LittleEndian;
53    ///
54    /// let bytes = [
55    ///     0x00, 0x00, 0x00, 0x00, // Header (Timestamp 0, EventType ContextSwitch)
56    ///     0x01, 0x00, 0x00, 0x00, // Data 0
57    ///     0x02, 0x00, 0x00, 0x00, // Data 1
58    ///     0x03, 0x00, 0x00, 0x00, // Data 2
59    /// ];
60    /// let record = Record::read_from_buffer::<LittleEndian>(&bytes).unwrap();
61    /// assert_eq!(record.event_type, EventType::ContextSwitch);
62    /// ```
63    #[cfg(feature = "std")]
64    #[must_use]
65    pub fn read_from_buffer<T: ByteOrder>(buffer: &[u8]) -> Option<Self> {
66        if buffer.len() < 16 {
67            return None;
68        }
69
70        let header = T::read_u32(&buffer[0..4]);
71        let time_stamp = header & 0x03ff_ffff;
72        let event_type_val = (header >> 26) & 0x3f;
73
74        let event_type = EventType::try_from(event_type_val as u8).ok()?;
75
76        let event_data = [
77            T::read_u32(&buffer[4..8]),
78            T::read_u32(&buffer[8..12]),
79            T::read_u32(&buffer[12..16]),
80        ];
81
82        Some(Self {
83            event_type,
84            time_stamp,
85            event_data,
86        })
87    }
88
89    /// Encodes the record into a `[u32; 4]` array.
90    ///
91    /// The encoding is endian-agnostic in the sense that the `u32` words contain the
92    /// architectural values. When writing these to bytes, care must be taken to maintain
93    /// consistency.
94    ///
95    /// # Returns
96    /// A `[u32; 4]` buffer containing the encoded record.
97    #[must_use]
98    pub const fn encode(&self) -> [u32; 4] {
99        let header =
100            (self.time_stamp & 0x03ff_ffff) | (((self.event_type as u8 & 0x3f) as u32) << 26);
101
102        // Though these use from_le_bytes, the bytes are explicitly added in little
103        // endian order so that the endianness of the target does not matter.
104        // This is done to avoid unsafe transmutes and optimizes out 32 bit word
105        // assignments.
106        [
107            header,
108            self.event_data[0],
109            self.event_data[1],
110            self.event_data[2],
111        ]
112    }
113
114    /// Parses the event data into a strongly-typed [`EventPayload`].
115    ///
116    /// # Returns
117    /// * `Some(EventPayload)` if the event data can be parsed for the record's `event_type`.
118    /// * `None` if parsing fails.
119    #[must_use]
120    pub fn payload(&self) -> Option<EventPayload> {
121        match self.event_type {
122            EventType::ContextSwitch => Some(EventPayload::ContextSwitch(
123                ContextSwitchEvent::read_from_buffer(&self.event_data)?,
124            )),
125            EventType::SpanStart => Some(EventPayload::Span(TraceSpanEvent::read_from_buffer(
126                &self.event_data,
127            )?)),
128            EventType::SpanEnd => Some(EventPayload::Span(TraceSpanEvent::read_from_buffer(
129                &self.event_data,
130            )?)),
131        }
132    }
133}
134
135/// Strongly-typed payload for defined event types.
136#[derive(Debug, Clone, Copy, PartialEq, Eq)]
137pub enum EventPayload {
138    /// A context switch event.
139    ContextSwitch(ContextSwitchEvent),
140    Span(TraceSpanEvent),
141}
142
143/// Supported trace event types.
144#[derive(Debug, Clone, Copy, PartialEq, Eq)]
145#[repr(u8)]
146pub enum EventType {
147    // NOTE: The values here must be less than 64 to fit in the 6 bit field in the header.
148    /// Context Switch Event
149    ContextSwitch = 0,
150    SpanStart = 1,
151    SpanEnd = 2,
152}
153
154impl TryFrom<u8> for EventType {
155    type Error = ();
156
157    fn try_from(value: u8) -> Result<Self, Self::Error> {
158        match value {
159            0 => Ok(EventType::ContextSwitch),
160            1 => Ok(EventType::SpanStart),
161            2 => Ok(EventType::SpanEnd),
162            _ => Err(()),
163        }
164    }
165}
166
167/// Context switch event data
168///
169/// | Bits      | Field            | Description                                                    |
170/// |-----------|------------------|----------------------------------------------------------------|
171/// | \[0:31\]  | old_thread_id    | ID of the thread that was running before the context switch    |
172/// | \[32:63\] | new_thread_id    | ID of the thread that is running after the context switch      |
173/// | \[64:71\] | old_thread_state | State of the thread that was running before the context switch |
174/// | \[72:95\] | reserved         | Read Ignored Write Zero                                        |
175#[repr(C)]
176#[derive(Debug, Clone, Copy, PartialEq, Eq)]
177pub struct ContextSwitchEvent {
178    pub old_thread_id: u32,
179    pub new_thread_id: u32,
180    pub old_thread_state: u8,
181}
182
183impl ContextSwitchEvent {
184    /// Encodes the event into a `u32` buffer
185    #[must_use]
186    pub const fn encode(&self) -> [u32; 3] {
187        [
188            self.old_thread_id,
189            self.new_thread_id,
190            self.old_thread_state as u32,
191        ]
192    }
193
194    /// Reads a context switch event from a `u32` buffer.
195    ///
196    /// # Arguments
197    /// * `buffer`: A slice of at least 3 `u32` words.
198    #[must_use]
199    pub fn read_from_buffer(buffer: &[u32]) -> Option<Self> {
200        if buffer.len() < 3 {
201            return None;
202        }
203
204        let old_thread_id = buffer[0];
205        let new_thread_id = buffer[1];
206        let old_thread_state = (buffer[2] & 0xff) as u8;
207
208        Some(Self {
209            old_thread_id,
210            new_thread_id,
211            old_thread_state,
212        })
213    }
214}
215
216/// Trace span event data
217///
218/// | Bits      | Field            | Description                                                    |
219/// |-----------|------------------|----------------------------------------------------------------|
220/// | \[0:96\] | message          | The message associated with this span, encoded with pw_tokenizer|
221#[repr(C)]
222#[derive(Debug, Clone, Copy, PartialEq, Eq)]
223pub struct TraceSpanEvent {
224    pub message: [u8; 12],
225}
226
227impl TraceSpanEvent {
228    /// Encodes the event into a `u32` buffer
229    #[must_use]
230    pub const fn encode(&self) -> [u32; 3] {
231        let (first, second, third): ([u8; 4], [u8; 4], [u8; 4]) = match self.message {
232            [a, b, c, d, e, f, g, h, i, j, k, l] => ([a, b, c, d], [e, f, g, h], [i, j, k, l]),
233        };
234
235        // Always keep the buffer in little endian, so it doesn't get reordered by the target
236        // endianness or the host endianness
237        [
238            u32::from_le_bytes(first).to_le(),
239            u32::from_le_bytes(second).to_le(),
240            u32::from_le_bytes(third).to_le(),
241        ]
242    }
243
244    /// Reads a context switch event from a `u32` buffer.
245    ///
246    /// # Arguments
247    /// * `buffer`: A slice of at least 3 `u32` words.
248    #[must_use]
249    pub fn read_from_buffer(buffer: &[u32]) -> Option<Self> {
250        if buffer.len() < 3 {
251            return None;
252        }
253
254        let (first, second, third) = (
255            buffer[0].to_le_bytes(),
256            buffer[1].to_le_bytes(),
257            buffer[2].to_le_bytes(),
258        );
259        let message: [u8; 12] = {
260            let [a, b, c, d] = first;
261            let [e, f, g, h] = second;
262            let [i, j, k, l] = third;
263
264            [a, b, c, d, e, f, g, h, i, j, k, l]
265        };
266
267        Some(Self { message })
268    }
269}
270
271#[cfg(test)]
272#[allow(unused_imports)]
273mod tests {
274    #[cfg(feature = "std")]
275    use byteorder::{BigEndian, LittleEndian};
276    use unittest::test;
277
278    use super::{ContextSwitchEvent, EventPayload, EventType, Record, TraceSpanEvent};
279
280    #[test]
281    fn context_switch_read_from_buffer_reads_correct_values() -> unittest::Result<()> {
282        let buffer = [
283            1, // old_thread_id = 1
284            2, // new_thread_id = 2
285            3, // old_thread_state = 3
286        ];
287
288        let event = ContextSwitchEvent::read_from_buffer(&buffer).unwrap();
289
290        unittest::assert_eq!(event.old_thread_id, 1);
291        unittest::assert_eq!(event.new_thread_id, 2);
292        unittest::assert_eq!(event.old_thread_state, 3);
293
294        Ok(())
295    }
296
297    #[test]
298    fn context_switch_encode_generates_correct_values() -> unittest::Result<()> {
299        let event = ContextSwitchEvent {
300            old_thread_id: 0x01020304,
301            new_thread_id: 0x05060708,
302            old_thread_state: 0x09,
303        };
304
305        let buffer = event.encode();
306
307        unittest::assert_eq!(
308            buffer,
309            [
310                0x01020304, // old_thread_id
311                0x05060708, // new_thread_id
312                0x00000009, // old (09) | reserved (0) << 8
313            ]
314        );
315
316        Ok(())
317    }
318
319    #[cfg(feature = "std")]
320    #[test]
321    fn record_read_little_endian_reads_correct_values() -> unittest::Result<()> {
322        let buffer = [
323            // Header:
324            // bits 0-25 (time): 0x123456
325            // bits 26-31 (type): 0 (ContextSwitch)
326            // Value: 0x123456 | (0x00 << 26)
327            // 0x00123456
328            // LE bytes: 0x56, 0x34, 0x12, 0x00
329            0x56, 0x34, 0x12, 0x00, // Event data (12 bytes)
330            0x00, 0x01, 0x02, 0x03, // word 0 = 0x03020100
331            0x04, 0x05, 0x06, 0x07, // word 1 = 0x07060504
332            0x08, 0x09, 0x0a, 0x0b, // word 2 = 0x0b0a0908
333        ];
334
335        let record = Record::read_from_buffer::<LittleEndian>(&buffer).unwrap();
336
337        unittest::assert_eq!(record.event_type, EventType::ContextSwitch);
338        unittest::assert_eq!(record.time_stamp, 0x123456);
339        unittest::assert_eq!(record.event_data, [0x03020100, 0x07060504, 0x0b0a0908]);
340
341        Ok(())
342    }
343
344    #[cfg(feature = "std")]
345    #[test]
346    fn record_read_big_endian_returns_correct_values() -> unittest::Result<()> {
347        let buffer = [
348            // Header:
349            // bits 0-25 (time): 0x123456
350            // bits 26-31 (type): 0 (ContextSwitch)
351            // Value: 0x123456 | (0x00 << 26)
352            // 0x00123456
353            // BE:
354            // Byte 0-3: 0x00, 0x12, 0x34, 0x56
355            0x00, 0x12, 0x34, 0x56, // Event data (12 bytes)
356            0x00, 0x01, 0x02, 0x03, // word 0 = 0x00010203
357            0x04, 0x05, 0x06, 0x07, // word 1 = 0x04050607
358            0x08, 0x09, 0x0a, 0x0b, // word 2 = 0x08090a0b
359        ];
360
361        let record = Record::read_from_buffer::<BigEndian>(&buffer).unwrap();
362
363        unittest::assert_eq!(record.event_type, EventType::ContextSwitch);
364        unittest::assert_eq!(record.time_stamp, 0x123456);
365        unittest::assert_eq!(record.event_data, [0x00010203, 0x04050607, 0x08090a0b]);
366
367        Ok(())
368    }
369
370    #[test]
371    fn record_encode_generates_correct_values() -> unittest::Result<()> {
372        let record = Record {
373            event_type: EventType::ContextSwitch,
374            time_stamp: 0x123456,
375            event_data: [0x03020100, 0x07060504, 0x0b0a0908],
376        };
377        let buffer = record.encode();
378
379        // buffer[0] = 0x00123456 because:
380        // time (0x123456) | type (0<<26)
381        unittest::assert_eq!(buffer[0], 0x00123456);
382        unittest::assert_eq!(buffer[1], 0x03020100);
383        unittest::assert_eq!(buffer[2], 0x07060504);
384        unittest::assert_eq!(buffer[3], 0x0b0a0908);
385
386        Ok(())
387    }
388
389    #[test]
390    fn record_payload_returns_correct_context_switch_event() -> unittest::Result<()> {
391        let event = ContextSwitchEvent {
392            old_thread_id: 1,
393            new_thread_id: 2,
394            old_thread_state: 3,
395        };
396        let encoded_event = event.encode();
397
398        let record = Record {
399            event_type: EventType::ContextSwitch,
400            time_stamp: 0,
401            event_data: encoded_event,
402        };
403
404        let decoded_event = unittest::unwrap!(match record.payload().unwrap() {
405            EventPayload::ContextSwitch(e) => Ok(e),
406            _ => Err(()),
407        });
408        unittest::assert_eq!(decoded_event.old_thread_id, 1);
409        unittest::assert_eq!(decoded_event.new_thread_id, 2);
410        unittest::assert_eq!(decoded_event.old_thread_state, 3);
411
412        Ok(())
413    }
414
415    #[test]
416    fn record_payload_returns_correct_trace_span_event() -> unittest::Result<()> {
417        let event = TraceSpanEvent {
418            message: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12],
419        };
420        let encoded_event = event.encode();
421
422        let record = Record {
423            event_type: EventType::SpanStart,
424            time_stamp: 0,
425            event_data: encoded_event,
426        };
427
428        let decoded_event = unittest::unwrap!(match record.payload().unwrap() {
429            EventPayload::Span(e) => Ok(e),
430            _ => Err(()),
431        });
432        unittest::assert_eq!(
433            decoded_event.message,
434            [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
435        );
436
437        Ok(())
438    }
439
440    #[test]
441    fn trace_span_read_from_buffer_reads_correct_values() -> unittest::Result<()> {
442        let buffer = [
443            0x04030201, // message[0..3] = [1, 2, 3, 4]
444            0x08070605, // message[4..8] = [5, 6, 7, 8]
445            0x0c0b0a09, // message[9..12] = [9, 10, 11, 12]
446        ];
447
448        let event = TraceSpanEvent::read_from_buffer(&buffer).unwrap();
449
450        unittest::assert_eq!(event.message, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]);
451
452        Ok(())
453    }
454
455    #[test]
456    fn trace_span_encode_generates_correct_values() -> unittest::Result<()> {
457        let event = TraceSpanEvent {
458            message: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12],
459        };
460
461        let buffer = event.encode();
462
463        unittest::assert_eq!(
464            buffer,
465            [
466                0x04030201, // message[0..3] = [1, 2, 3, 4]
467                0x08070605, // message[4..8] = [5, 6, 7, 8]
468                0x0c0b0a09, // message[9..12] = [9, 10, 11, 12]
469            ]
470        );
471
472        Ok(())
473    }
474
475    #[cfg(feature = "std")]
476    #[test]
477    fn trace_span_preserves_buffer_order_with_different_endianness_round_trip()
478    -> unittest::Result<()> {
479        let event = TraceSpanEvent {
480            message: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12],
481        };
482        let encoded_event = event.encode();
483
484        let record = Record {
485            event_type: EventType::SpanStart,
486            time_stamp: 0,
487            event_data: encoded_event,
488        };
489
490        let buffer = record.encode();
491
492        // Encode and decode the record in big endian
493        let big_endian_record = {
494            let buffer = buffer
495                .into_iter()
496                .flat_map(|x| x.to_be_bytes())
497                .collect::<Vec<u8>>();
498            Record::read_from_buffer::<BigEndian>(&buffer).unwrap()
499        };
500
501        unittest::assert_eq!(big_endian_record.event_type, EventType::SpanStart);
502        unittest::assert_eq!(big_endian_record.time_stamp, 0);
503
504        let decoded_event = unittest::unwrap!(match big_endian_record.payload().unwrap() {
505            EventPayload::Span(e) => Ok(e),
506            _ => Err(()),
507        });
508        unittest::assert_eq!(
509            decoded_event.message,
510            [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
511        );
512
513        // Encode and decode the record in little endian
514        let little_endian_record = {
515            let buffer = buffer
516                .into_iter()
517                .flat_map(|x| x.to_le_bytes())
518                .collect::<Vec<u8>>();
519            Record::read_from_buffer::<LittleEndian>(&buffer).unwrap()
520        };
521
522        unittest::assert_eq!(little_endian_record.event_type, EventType::SpanStart);
523        unittest::assert_eq!(little_endian_record.time_stamp, 0);
524
525        let decoded_event = unittest::unwrap!(match little_endian_record.payload().unwrap() {
526            EventPayload::Span(e) => Ok(e),
527            _ => Err(()),
528        });
529        unittest::assert_eq!(
530            decoded_event.message,
531            [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
532        );
533
534        Ok(())
535    }
536}