tracepoint_decode 0.4.1

Rust API for decoding tracepoints
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.

use core::mem;
use core::ops;

use crate::display;
use crate::perf_abi;
use crate::perf_session;

use crate::byte_reader::PerfByteReader;
use crate::perf_event_desc::PerfEventDesc;
use crate::perf_event_format::PerfEventFormat;

/// Represents the header and raw data of a perf event.
///
/// - If this is a sample event (i.e. if `header.header_type == PerfEventHeaderType::Sample`),
///   you will usually need to get additional information about the event (timestamp,
///   cpu, decoding information, etc.) by calling `reader.get_sample_event_info(&bytes)`.
///
/// - If this is a non-sample event (i.e. if `header.header_type != PerfEventHeaderType::Sample`),
///   you may be able to get additional information about the event (timestamp, cpu, etc.)
///   by calling `reader.get_non_sample_event_info(&bytes)`. However, this is not always
///   necessary, e.g. in many cases the `header_type` alone is all you need, and in other
///   cases, the payload is in a known location within the event content. In addition, many
///   non-sample events do not support this additional information, e.g. if
///   `header_type >= UserTypeStart` or if the event appears before the `FinishedInit`
///   event has been processed.
#[derive(Clone, Copy, Debug, Default)]
pub struct PerfEventBytes<'dat> {
    /// The header of the event, in host-endian byte order.
    ///
    /// The header comes from `data[0..8]`, but has been byte-swapped if appropriate (i.e.
    /// if the event byte order does not match the host byte order).
    pub header: perf_abi::PerfEventHeader,

    /// The bytes of the event, including header and content, in event byte order.
    ///
    /// If this is a `Sample` event (i.e. if `header.header_type == PerfEventHeaderType::Sample`)
    /// then `data` will contain:
    ///
    /// - The 8 byte header (same data as `header`, but in event byte order).
    /// - A sequence of fields, one field for each bit set in the event's `sample_type`.
    ///   These fields include items like `id`, `time`, `ip`, `cpu`, `pid`, `tid`, and raw
    ///   data.
    ///   - The raw data field contains the content of the event, which includes both
    ///     "common" fields (the same for all `Sample` events on the current system) and
    ///     "user" fields (different for different tracepoints). The raw data should be
    ///     decoded uses the event's `format` (if available).
    ///
    /// You will normally use `reader.get_sample_event_info(&bytes)` to help parse the
    /// fields from the data of the `Sample` event.
    ///
    /// If this is a non-sample event (i.e. if `header.header_type != PerfEventHeaderType::Sample`)
    /// then `data` will contain:
    ///
    /// - The 8 byte header (same data as `header`, but in event byte order).
    /// - The content of the event (if any), which is in a format determined by the event's
    ///   `header_type`.
    /// - The event may contain additional fields after the content, one field for each bit
    ///   set in the event's `sample_type`. These fields include items like `id`, `time`,
    ///   `cpu`, pid, tid.
    ///
    /// If additional fields are present, you will normally use
    /// `reader.get_non_sample_event_info(&bytes)` to parse them. Note that these addtional
    /// fields are not always present. In particular, they are generally not present for
    /// events with `header_type >= UserTypeStart` or for events that appear before the
    /// `FinishedInit` event has been processed.
    pub data: &'dat [u8],
}

impl<'dat> PerfEventBytes<'dat> {
    /// Constructs a new PerfEventBytes instance.
    pub const fn new(header: perf_abi::PerfEventHeader, data: &'dat [u8]) -> PerfEventBytes<'dat> {
        debug_assert!(data.len() >= mem::size_of::<perf_abi::PerfEventHeader>());
        return PerfEventBytes { header, data };
    }
}

/// Information about a non-sample event, typically returned by
/// `reader.get_non_sample_event_info(&bytes)`.
#[derive(Clone, Debug)]
pub struct PerfNonSampleEventInfo<'a> {
    /// The bytes of the event, including header and content, in event byte order.
    ///
    /// The data consists of the 8-byte header followed by the content, both in event byte order.
    /// The format of the content depends on `header_type`.
    ///
    /// Valid always.
    pub data: &'a [u8],

    /// Information about the session that collected the event, e.g. clock id and
    /// clock offset.
    ///
    /// Valid always.
    pub session_info: &'a perf_session::PerfSessionInfo,

    /// Information about the event (shared by all events with the same `id`).
    ///
    /// Valid always.
    pub event_desc: &'a PerfEventDesc,

    /// Valid if `sample_type()` contains `Identifier` or `Id`.
    pub id: u64,

    /// Valid if `sample_type()` contains `Cpu`.
    pub cpu: u32,

    /// Valid if `sample_type()` contains `Cpu`.
    pub cpu_reserved: u32,

    /// Valid if `sample_type()` contains `StreamId`.
    pub stream_id: u64,

    /// Use SessionInfo.TimeToTimeSpec() to convert to a TimeSpec.
    ///
    /// Valid if `sample_type()` contains `Time`.
    pub time: u64,

    /// Valid if `sample_type()` contains `Tid`.
    pub pid: u32,

    /// Valid if `sample_type()` contains `Tid`.
    pub tid: u32,
}

impl<'a> PerfNonSampleEventInfo<'a> {
    /// Constructs a new PerfNonSampleEventInfo instance.
    /// Requires that `data` is at least 8 bytes long (must start with the [`crate::PerfEventHeader`]).
    pub const fn new(
        data: &'a [u8],
        session_info: &'a perf_session::PerfSessionInfo,
        event_desc: &'a PerfEventDesc,
    ) -> Self {
        debug_assert!(data.len() >= mem::size_of::<perf_abi::PerfEventHeader>());
        return Self {
            data,
            session_info,
            event_desc,
            id: 0,
            cpu: 0,
            cpu_reserved: 0,
            stream_id: 0,
            time: 0,
            pid: 0,
            tid: 0,
        };
    }

    /// Returns true if the the session's event data is formatted in big-endian
    /// byte order.
    ///
    /// If directly accessing the session's event data, you may want to use
    /// `byte_reader()` to help with reading values since it will automatically
    /// perform appropriate byte-swapping based on the data source's byte order.
    pub const fn source_big_endian(&self) -> bool {
        self.session_info.source_big_endian()
    }

    /// Returns a [`PerfByteReader`] configured for the byte order of the events
    /// in this session, i.e. `PerfByteReader::new(source_big_endian())`.
    ///
    /// If directly accessing the session's event data, you may want to use
    /// `byte_reader()` to help with reading values since it will automatically
    /// perform appropriate byte-swapping based on the data source's byte order.
    pub const fn byte_reader(&self) -> PerfByteReader {
        self.session_info.byte_reader()
    }

    /// Returns the header of the event, in host-endian byte order.
    /// (Reads the header from `data[0..8]` and byte-swaps as appropriate based on
    /// the session's byte order.)
    pub fn header(&self) -> perf_abi::PerfEventHeader {
        let array = self.data[..8].try_into().unwrap();
        return perf_abi::PerfEventHeader::from_bytes(&array, self.session_info.byte_reader());
    }

    /// Returns flags indicating which data was present in the event.
    pub const fn sample_type(&self) -> perf_abi::PerfEventAttrSampleType {
        self.event_desc.attr().sample_type
    }

    /// Gets the event's name, e.g. "sched:sched_switch".
    ///
    /// - If name is available from `PERF_HEADER_EVENT_DESC`, return it.
    /// - Otherwise, return empty string.
    pub fn name(&self) -> &str {
        self.event_desc.name()
    }

    /// Gets a `Display` object for a JSON-escaped event name, e.g. `sched:sched_switch`.
    ///
    /// - If name is available from `PERF_HEADER_EVENT_DESC`, return it.
    /// - Otherwise, if name is available from format, return it.
    /// - Otherwise, return empty string.
    ///
    /// The returned `Display` object can be used with format macros like `write!` or
    /// `println!` to write the name as a JSON-escaped string. This returns the same
    /// value as the [PerfNonSampleEventInfo::name] method, but as a Display object (can
    /// be passed to a format macro) and with JSON escaping applied (control chars,
    /// quotes, and backslashes are escaped)
    pub fn json_name_display(&self) -> display::JsonEscapeDisplay {
        display::JsonEscapeDisplay::new(self.name())
    }

    /// Gets the event's `time` as a [`crate::PerfTimeSpec`], using offset information from `session_info`.
    pub const fn time_spec(&self) -> perf_session::PerfTimeSpec {
        self.session_info.time_to_time_spec(self.time)
    }

    /// Returns a formatter for the event's "meta" suffix.
    ///
    /// The returned formatter writes event metadata as a comma-separated list of 0 or more
    /// JSON name-value pairs, e.g. `"time": "...", "cpu": 3` (including the quotation marks).
    ///
    /// The included items default to [`crate::PerfMetaOptions::Default`], but can be customized with
    /// the `meta_options()` property.
    ///
    /// One name-value pair is appended for each metadata item that is both requested
    /// by `meta_options` and has a meaningful value available in the event. For example,
    /// the "cpu" metadata item is only appended if the event has a non-zero `Cpu` value,
    /// even if the `meta_options` property includes [`crate::PerfMetaOptions::Cpu`].
    ///
    /// The following metadata items are supported:
    ///
    /// - `"time": "2024-01-01T23:59:59.123456789Z"` if clock offset is known, or a float number of seconds
    ///   (assumes the clock value is in nanoseconds), or omitted if not present.
    /// - `"cpu": 3` (omitted if unavailable)
    /// - `"pid": 123` (omitted if unavailable)
    /// - `"tid": 124` (omitted if unavailable or if pid is shown and pid == tid)
    /// - `"provider": "SystemName"` (omitted if unavailable)
    /// - `"event": "TracepointName"` (omitted if unavailable)
    pub const fn json_meta_display(&self) -> display::EventInfoJsonMetaDisplay {
        display::EventInfoJsonMetaDisplay::new(
            self.session_info,
            self.event_desc,
            self.time,
            self.cpu,
            self.pid,
            self.tid,
        )
    }
}

/// Information about a sample event, typically returned by
/// `reader.get_sample_event_info(&bytes)`.
///
/// If the `format()` property is non-empty, you can use it to access event
/// information, including the event's fields.
#[derive(Clone, Debug)]
pub struct PerfSampleEventInfo<'a> {
    /// The bytes of the event, including header and content, in event byte order.
    ///
    /// The data consists of the 8-byte header followed by the content, both in event byte order.
    /// The format of the content depends on `header_type`.
    ///
    /// Valid always.
    pub data: &'a [u8],

    /// Information about the session that collected the event, e.g. clock id and
    /// clock offset.
    ///
    /// Valid always.
    pub session_info: &'a perf_session::PerfSessionInfo,

    /// Information about the event (shared by all events with the same `id`).
    ///
    /// Valid always.
    pub event_desc: &'a PerfEventDesc,

    /// Valid if `sample_type()` contains `Identifier` or `Id`.
    pub id: u64,

    /// Valid if `sample_type()` contains `IP`.
    pub ip: u64,

    /// Valid if `sample_type()` contains `Tid`.
    pub pid: u32,

    /// Valid if `sample_type()` contains `Tid`.
    pub tid: u32,

    /// Use SessionInfo.TimeToTimeSpec() to convert to a TimeSpec.
    ///
    /// Valid if `sample_type()` contains `Time`.
    pub time: u64,

    /// Valid if `sample_type()` contains `Addr`.
    pub addr: u64,

    /// Valid if `sample_type()` contains `StreamId`.
    pub stream_id: u64,

    /// Valid if `sample_type()` contains `Cpu`.
    pub cpu: u32,

    /// Valid if `sample_type()` contains `Cpu`.
    pub cpu_reserved: u32,

    /// Valid if `sample_type()` contains `Period`.
    pub period: u64,

    /// Read format data.
    ///
    /// Valid if `sample_type()` contains `Read`.
    pub read_range: ops::Range<u16>,

    /// Callchain data.
    ///
    /// Valid if `sample_type()` contains `Callchain`.
    pub callchain_range: ops::Range<u16>,

    /// Raw event data.
    ///
    /// Valid if `sample_type()` contains `Raw`.
    pub raw_range: ops::Range<u16>,
}

impl<'a> PerfSampleEventInfo<'a> {
    /// Constructs a new PerfSampleEventInfo instance.
    /// Requires that `data` is at least 8 bytes long (must start with the [`crate::PerfEventHeader`]).
    pub const fn new(
        data: &'a [u8],
        session_info: &'a perf_session::PerfSessionInfo,
        event_desc: &'a PerfEventDesc,
    ) -> Self {
        debug_assert!(data.len() >= mem::size_of::<perf_abi::PerfEventHeader>());
        return Self {
            data,
            session_info,
            event_desc,
            id: 0,
            ip: 0,
            pid: 0,
            tid: 0,
            time: 0,
            addr: 0,
            stream_id: 0,
            cpu: 0,
            cpu_reserved: 0,
            period: 0,
            read_range: 0..0,
            callchain_range: 0..0,
            raw_range: 0..0,
        };
    }

    /// Returns true if the the session's event data is formatted in big-endian
    /// byte order.
    ///
    /// If directly accessing the session's event data, you may want to use
    /// `byte_reader()` to help with reading values since it will automatically
    /// perform appropriate byte-swapping based on the data source's byte order.
    pub const fn source_big_endian(&self) -> bool {
        self.session_info.source_big_endian()
    }

    /// Returns a [`PerfByteReader`] configured for the byte order of the events
    /// in this session, i.e. `PerfByteReader::new(source_big_endian())`.
    ///
    /// If directly accessing the session's event data, you may want to use
    /// `byte_reader()` to help with reading values since it will automatically
    /// perform appropriate byte-swapping based on the data source's byte order.
    pub const fn byte_reader(&self) -> PerfByteReader {
        self.session_info.byte_reader()
    }

    /// Returns the header of the event, in host-endian byte order.
    /// (Reads the header from `data[0..8]` and byte-swaps as appropriate based on
    /// the session's byte order.)
    pub fn header(&self) -> perf_abi::PerfEventHeader {
        let array = self.data[..8].try_into().unwrap();
        return perf_abi::PerfEventHeader::from_bytes(&array, self.session_info.byte_reader());
    }

    /// Returns flags indicating which data was present in the event.
    pub const fn sample_type(&self) -> perf_abi::PerfEventAttrSampleType {
        self.event_desc.attr().sample_type
    }

    /// Gets the event's name, e.g. "sched:sched_switch".
    ///
    /// - If name is available from `PERF_HEADER_EVENT_DESC`, return it.
    /// - Otherwise, if name is available from format, return it.
    /// - Otherwise, return empty string.
    pub fn name(&self) -> &str {
        self.event_desc.name()
    }

    /// Gets a `Display` object for a JSON-escaped event name, e.g. `sched:sched_switch`.
    ///
    /// - If name is available from `PERF_HEADER_EVENT_DESC`, return it.
    /// - Otherwise, if name is available from format, return it.
    /// - Otherwise, return empty string.
    ///
    /// The returned `Display` object can be used with format macros like `write!` or
    /// `println!` to write the name as a JSON-escaped string. This returns the same
    /// value as the [PerfSampleEventInfo::name] method, but as a Display object (can
    /// be passed to a format macro) and with JSON escaping applied (control chars,
    /// quotes, and backslashes are escaped)
    pub fn json_name_display(&self) -> display::JsonEscapeDisplay {
        display::JsonEscapeDisplay::new(self.name())
    }

    /// Gets the event's `time` as a [`crate::PerfTimeSpec`], using offset information from `session_info`.
    pub const fn time_spec(&self) -> perf_session::PerfTimeSpec {
        self.session_info.time_to_time_spec(self.time)
    }

    /// Event's format, or None if no format data available.
    pub fn format(&self) -> Option<&PerfEventFormat> {
        self.event_desc.format()
    }

    /// Gets the read format data from the event in event-endian byte order.
    ///
    /// Valid if `sample_type()` contains `Read`.
    pub fn read_format(&self) -> &'a [u8] {
        &self.data[self.read_range.start as usize..self.read_range.end as usize]
    }

    /// Gets the callchain data from the event in event-endian byte order.
    ///
    /// Valid if `sample_type()` contains `Callchain`.
    pub fn callchain(&self) -> &'a [u8] {
        &self.data[self.callchain_range.start as usize..self.callchain_range.end as usize]
    }

    /// Gets the raw data from the event in event-endian byte order.
    ///
    /// Valid if `sample_type()` contains `Raw`.
    pub fn raw_data(&self) -> &'a [u8] {
        &self.data[self.raw_range.start as usize..self.raw_range.end as usize]
    }

    /// Gets the user data from the event in event-endian byte order.
    /// The user data is the raw data after the common fields.
    ///
    /// Valid if `sample_type()` contains `Raw` and format is available.
    pub fn user_data(&self) -> &'a [u8] {
        if let Some(format) = self.format() {
            let raw_len = self.raw_range.end - self.raw_range.start;
            let user_offset = format.common_fields_size();
            if user_offset <= raw_len {
                return &self.data
                    [(self.raw_range.start + user_offset) as usize..self.raw_range.end as usize];
            }
        }
        return &[];
    }

    /// Returns a formatter for the event's "meta" suffix.
    ///
    /// The returned formatter writes event metadata as a comma-separated list of 0 or more
    /// JSON name-value pairs, e.g. `"time": "...", "cpu": 3` (including the quotation marks).
    ///
    /// The included items default to [`crate::PerfMetaOptions::Default`], but can be customized with
    /// the `meta_options()` property.
    ///
    /// One name-value pair is appended for each metadata item that is both requested
    /// by `meta_options` and has a meaningful value available in the event. For example,
    /// the "cpu" metadata item is only appended if the event has a non-zero `Cpu` value,
    /// even if the `meta_options` property includes [`crate::PerfMetaOptions::Cpu`].
    ///
    /// The following metadata items are supported:
    ///
    /// - `"time": "2024-01-01T23:59:59.123456789Z"` if clock offset is known, or a float number of seconds
    ///   (assumes the clock value is in nanoseconds), or omitted if not present.
    /// - `"cpu": 3` (omitted if unavailable)
    /// - `"pid": 123` (omitted if unavailable)
    /// - `"tid": 124` (omitted if unavailable or if pid is shown and pid == tid)
    /// - `"provider": "SystemName"` (omitted if unavailable)
    /// - `"event": "TracepointName"` (omitted if unavailable)
    pub const fn json_meta_display(&self) -> display::EventInfoJsonMetaDisplay {
        display::EventInfoJsonMetaDisplay::new(
            self.session_info,
            self.event_desc,
            self.time,
            self.cpu,
            self.pid,
            self.tid,
        )
    }
}