iptr-decoder 0.1.3

Idiomatic Rust-style low-level Intel PT trace handler.
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
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
#![doc = include_str!("../README.md")]
#![no_std]
#![deny(missing_docs)]
#![cfg_attr(docsrs, feature(doc_cfg))]

#[cfg(feature = "alloc")]
extern crate alloc;

pub mod error;
pub mod packet_handler;
mod raw_packet_handler;
pub mod utils;

use core::num::NonZero;

pub use raw_packet_handler::{level1::IpReconstructionPattern, level2::PtwPayload};

use crate::error::{DecoderError, DecoderResult};

/// Packet handler trait
///
/// The default implementations of all packet handlers
/// are nops.
pub trait HandlePacket {
    /// Custom error type
    type Error: core::error::Error;

    /// Callback at begin of decoding.
    ///
    /// This is useful when using the same handler to process multiple Intel PT
    /// traces
    fn at_decode_begin(&mut self) -> Result<(), Self::Error>;

    /// Handle short TNT packet
    ///
    /// `packet_byte` is the whole byte of short TNT packet. `highest_bit`
    /// is the index of highest bit that represents a valid Taken/Not-taken bit,
    /// guaranteed to be in range 0..=6
    ///
    /// If `highest_bit` is 0, this means there is no Taken/Not-taken bits.
    #[expect(unused)]
    fn on_short_tnt_packet(
        &mut self,
        context: &DecoderContext,
        packet_byte: NonZero<u8>,
        highest_bit: u32,
    ) -> Result<(), Self::Error> {
        Ok(())
    }

    /// Handle short TNT packet
    ///
    /// `packet_bytes` is the whole 6 bytes of long TNT packet payload. The
    /// upper 2 bytes are guaranteed to be cleared.
    /// `highest_bit` is the index of highest bit that represents a valid
    /// Taken/Not-taken bit, guaranteed to be in range 0..=46 or [`u32::MAX`]
    ///
    /// If `highest_bit` is [`u32::MAX`], this means there is no Taken/Not-taken bits.
    #[expect(unused)]
    fn on_long_tnt_packet(
        &mut self,
        context: &DecoderContext,
        packet_bytes: NonZero<u64>,
        highest_bit: u32,
    ) -> Result<(), Self::Error> {
        Ok(())
    }

    /// Handle TIP packet
    #[expect(unused)]
    fn on_tip_packet(
        &mut self,
        context: &DecoderContext,
        ip_reconstruction_pattern: IpReconstructionPattern,
    ) -> Result<(), Self::Error> {
        Ok(())
    }

    /// Handle TIP.PGD packet
    #[expect(unused)]
    fn on_tip_pgd_packet(
        &mut self,
        context: &DecoderContext,
        ip_reconstruction_pattern: IpReconstructionPattern,
    ) -> Result<(), Self::Error> {
        Ok(())
    }

    /// Handle TIP.PGE packet
    #[expect(unused)]
    fn on_tip_pge_packet(
        &mut self,
        context: &DecoderContext,
        ip_reconstruction_pattern: IpReconstructionPattern,
    ) -> Result<(), Self::Error> {
        Ok(())
    }

    /// Handle FUP packet
    #[expect(unused)]
    fn on_fup_packet(
        &mut self,
        context: &DecoderContext,
        ip_reconstruction_pattern: IpReconstructionPattern,
    ) -> Result<(), Self::Error> {
        Ok(())
    }

    /// Handle PAD packet
    #[expect(unused)]
    fn on_pad_packet(&mut self, context: &DecoderContext) -> Result<(), Self::Error> {
        Ok(())
    }

    /// Handle CYC packet
    ///
    /// `cyc_packet` is the total content of the CYC packet
    #[expect(unused)]
    fn on_cyc_packet(
        &mut self,
        context: &DecoderContext,
        cyc_packet: &[u8],
    ) -> Result<(), Self::Error> {
        Ok(())
    }

    /// Handle MODE packet
    ///
    /// `leaf_id` and `mode` is the leaf ID and mode of MODE packet.
    #[expect(unused)]
    fn on_mode_packet(
        &mut self,
        context: &DecoderContext,
        leaf_id: u8,
        mode: u8,
    ) -> Result<(), Self::Error> {
        Ok(())
    }

    /// Handle MTC packet
    ///
    /// `ctc_payload` is the 8-bit CTC payload value
    #[expect(unused)]
    fn on_mtc_packet(
        &mut self,
        context: &DecoderContext,
        ctc_payload: u8,
    ) -> Result<(), Self::Error> {
        Ok(())
    }

    /// Handle TSC packet
    ///
    /// `tsc_value` is the lower 7 bytes of current TSC value
    #[expect(unused)]
    fn on_tsc_packet(
        &mut self,
        context: &DecoderContext,
        tsc_value: u64,
    ) -> Result<(), Self::Error> {
        Ok(())
    }

    /// Handle CBR packet
    ///
    /// `core_bus_ratio` is Core:Bus Ratio
    #[expect(unused)]
    fn on_cbr_packet(
        &mut self,
        context: &DecoderContext,
        core_bus_ratio: u8,
    ) -> Result<(), Self::Error> {
        Ok(())
    }

    /// Handle TMA packet
    ///
    /// `ctc` is `CTC[15:0]`, `fast_counter` is `FastCounter[7:0]`, `fc8` is `FC[8]`
    #[expect(unused)]
    fn on_tma_packet(
        &mut self,
        context: &DecoderContext,
        ctc: u16,
        fast_counter: u8,
        fc8: bool,
    ) -> Result<(), Self::Error> {
        Ok(())
    }

    /// Handle VMCS packet
    ///
    /// `vmcs_pointer`'s 12..=51 bits are `VMCS pointer [51:12]` (other bits guaranteed cleared)
    #[expect(unused)]
    fn on_vmcs_packet(
        &mut self,
        context: &DecoderContext,
        vmcs_pointer: u64,
    ) -> Result<(), Self::Error> {
        Ok(())
    }

    /// Handle OVF packet
    #[expect(unused)]
    fn on_ovf_packet(&mut self, context: &DecoderContext) -> Result<(), Self::Error> {
        Ok(())
    }

    /// Handle PSB packet
    #[expect(unused)]
    fn on_psb_packet(&mut self, context: &DecoderContext) -> Result<(), Self::Error> {
        Ok(())
    }

    /// Handle PSBEND packet
    #[expect(unused)]
    fn on_psbend_packet(&mut self, context: &DecoderContext) -> Result<(), Self::Error> {
        Ok(())
    }

    /// Handle TraceStop packet
    #[expect(unused)]
    fn on_trace_stop_packet(&mut self, context: &DecoderContext) -> Result<(), Self::Error> {
        Ok(())
    }

    /// Handle PIP packet
    ///
    /// `cr3`'s 5..=51 bits are `CR3[51:5]` (other bits guaranteed cleared),
    /// `rsvd_nr` is RSVD/NR
    #[expect(unused)]
    fn on_pip_packet(
        &mut self,
        context: &DecoderContext,
        cr3: u64,
        rsvd_nr: bool,
    ) -> Result<(), Self::Error> {
        Ok(())
    }

    /// Handle MNT packet
    ///
    /// `payload` is `Payload[63:0]`
    #[expect(unused)]
    fn on_mnt_packet(&mut self, context: &DecoderContext, payload: u64) -> Result<(), Self::Error> {
        Ok(())
    }

    /// Handle PTW packet
    ///
    /// `ip_bit` is the IP bit, `payload` is either 4 bytes or 8 bytes
    #[expect(unused)]
    fn on_ptw_packet(
        &mut self,
        context: &DecoderContext,
        ip_bit: bool,
        payload: PtwPayload,
    ) -> Result<(), Self::Error> {
        Ok(())
    }

    /// Handle EXSTOP packet
    ///
    /// `ip_bit` is the IP bit
    #[expect(unused)]
    fn on_exstop_packet(
        &mut self,
        context: &DecoderContext,
        ip_bit: bool,
    ) -> Result<(), Self::Error> {
        Ok(())
    }

    /// Handle MWAIT packet
    ///
    /// `mwait_hints` is `MWAIT Hints[7:0]`, `ext` is `EXT[1:0]` (upper 6 bits guaranteed cleared)
    #[expect(unused)]
    fn on_mwait_packet(
        &mut self,
        context: &DecoderContext,
        mwait_hints: u8,
        ext: u8,
    ) -> Result<(), Self::Error> {
        Ok(())
    }

    /// Handle PWRE packet
    ///
    /// `hw` is HW, `resolved_thread_c_state` is Resolved Thread C-State (upper 4 bits guaranteed cleared),
    /// `resolved_thread_sub_c_state` is Resolved Thread Sub C-State (upper 4 bits guaranteed cleared)
    #[expect(unused)]
    fn on_pwre_packet(
        &mut self,
        context: &DecoderContext,
        hw: bool,
        resolved_thread_c_state: u8,
        resolved_thread_sub_c_state: u8,
    ) -> Result<(), Self::Error> {
        Ok(())
    }

    /// Handle PWRX packet
    ///
    /// `last_core_c_state` is Last Core C-State (upper 4 bits guaranteed cleared),
    /// `deepest_core_c_state` is Deepest Core C-State (upper 4 bits guaranteed cleared),
    /// `wake_reason` is Wake Reason (upper 4 bits guaranteed cleared)
    #[expect(unused)]
    fn on_pwrx_packet(
        &mut self,
        context: &DecoderContext,
        last_core_c_state: u8,
        deepest_core_c_state: u8,
        wake_reason: u8,
    ) -> Result<(), Self::Error> {
        Ok(())
    }

    /// Handle EVD packet
    ///
    /// `r#type` is `Type[5:0]` (upper 2 bits guaranteed cleared), `payload` is `Payload[63:0]`
    #[expect(unused)]
    fn on_evd_packet(
        &mut self,
        context: &DecoderContext,
        r#type: u8,
        payload: u64,
    ) -> Result<(), Self::Error> {
        Ok(())
    }

    /// Handle CFE packet
    ///
    /// `ip_bit` is the IP bit, `r#type` is `Type[4:0]` (upper 3 bits guaranteed cleared),
    /// `vector` is the `Vector[7:0]`
    #[expect(unused)]
    fn on_cfe_packet(
        &mut self,
        context: &DecoderContext,
        ip_bit: bool,
        r#type: u8,
        vector: u8,
    ) -> Result<(), Self::Error> {
        Ok(())
    }

    /// Handle BBP packet
    ///
    /// `sz_bit` is the SZ bit, `r#type` is `Type[4:0]` (upper 3 bits guaranteed cleared).
    #[expect(unused)]
    fn on_bbp_packet(
        &mut self,
        context: &DecoderContext,
        sz_bit: bool,
        r#type: u8,
    ) -> Result<(), Self::Error> {
        Ok(())
    }

    /// Handle BEP packet
    ///
    /// `ip_bit` is the IP bit.
    #[expect(unused)]
    fn on_bep_packet(&mut self, context: &DecoderContext, ip_bit: bool) -> Result<(), Self::Error> {
        Ok(())
    }

    /// Handle BIP packet
    ///
    /// `id` is `ID[5:0]`, `payload`'s size is 4 or 8 according to
    /// the `SZ` bit in BBP packet. `bbp_type` is the `type` field
    /// of the preceding BBP packet.
    #[expect(unused)]
    fn on_bip_packet(
        &mut self,
        context: &DecoderContext,
        id: u8,
        payload: &[u8],
        bbp_type: u8,
    ) -> Result<(), Self::Error> {
        Ok(())
    }
}

/// Execution mode
#[derive(Clone, Copy)]
pub enum TraceeMode {
    /// 16-bit mode
    Mode16 = 16,
    /// 32-bit mode
    Mode32 = 32,
    /// 64-bit mode
    Mode64 = 64,
}

impl TraceeMode {
    /// Get the bitness of current tracee mode
    #[must_use]
    pub fn bitness(self) -> u32 {
        self as u32
    }
}

/// Decoder context during decoding
pub struct DecoderContext {
    /// Next position in target buffer
    pos: usize,
    /// Current tracee mode (will be modified by MODE.exec packet)
    tracee_mode: TraceeMode,
    /// Information about packet block.
    ///
    /// If this field is [`Some`], this indicates that current mode
    /// is packet block mode, which means we are between a BBP and BEP
    packet_block: Option<PacketBlockInformation>,
}

/// Size of packet block
#[derive(Clone, Copy)]
enum PacketBlockSize {
    /// 4-byte block items
    Dword = 4,
    /// 8-byte block items
    Qword = 8,
}

impl PacketBlockSize {
    /// Create from the `SZ` bit in BBP packet
    #[must_use]
    fn from_sz_bit(sz: bool) -> Self {
        if sz { Self::Qword } else { Self::Dword }
    }

    /// Get block items size
    const fn size(self) -> usize {
        self as usize
    }
}

/// Information about packet blocks, derived from BBP packet
#[derive(Clone, Copy)]
struct PacketBlockInformation {
    /// Size of packet block items
    size: PacketBlockSize,
    /// Type of packet block items, retrieved from BBP packet's `Type[4:0]`
    r#type: u8,
}

impl DecoderContext {
    /// Get current tracee mode
    #[must_use]
    pub fn tracee_mode(&self) -> TraceeMode {
        self.tracee_mode
    }

    /// Whether we are between a BBP and BEP packets.
    ///
    /// When you invokes this method in a BBP packet handler,
    /// this will return the status **before** current BBP packet.
    /// Same for BEP and OVF packet.
    #[must_use]
    pub fn is_in_packet_blocks(&self) -> bool {
        self.packet_block.is_some()
    }
}

/// Options for [`decode`].
///
/// You can create default options via [`DecodeOptions::default`].
#[derive(Clone, Copy)]
pub struct DecodeOptions {
    tracee_mode: TraceeMode,
    no_sync: bool,
}

impl Default for DecodeOptions {
    fn default() -> Self {
        Self {
            tracee_mode: TraceeMode::Mode64,
            no_sync: false,
        }
    }
}

impl DecodeOptions {
    /// Set default mode of tracee before encountering any valid MODE.exec packets.
    ///
    /// Default is [`TraceeMode::Mode64`]
    pub fn tracee_mode(&mut self, tracee_mode: TraceeMode) -> &mut Self {
        self.tracee_mode = tracee_mode;
        self
    }

    /// Set whether the decoder will firstly sync forward for a PSB packet instead of
    /// decoding at 0 offset.
    ///
    /// Default is `true`.
    pub fn sync(&mut self, sync: bool) -> &mut Self {
        self.no_sync = !sync;
        self
    }
}

const PSB_BYTES: [u8; 16] = [
    0x02, 0x82, 0x02, 0x82, 0x02, 0x82, 0x02, 0x82, 0x02, 0x82, 0x02, 0x82, 0x02, 0x82, 0x02, 0x82,
];

/// Decode the given Intel PT buffer.
///
/// Note that the Linux Perf tool records more than raw Intel PT packets,
/// some sideband data is also recorded. As a result, you need to extract AUX data
/// from the `perf.data` in order to use this method.
///
/// # SAFETY
///
/// We assume that you can never construct a buf whose length can overflow a usize.
/// As a result, we do not check any arithmetic overflow when manipulating the postion
/// of buf cursor (unless you use a debug-build or enable `overflow-checks` in your
/// build profile).
pub fn decode<H: HandlePacket>(
    buf: &[u8],
    options: DecodeOptions,
    packet_handler: &mut H,
) -> DecoderResult<(), H> {
    let DecodeOptions {
        tracee_mode,
        no_sync,
    } = options;

    packet_handler
        .at_decode_begin()
        .map_err(DecoderError::PacketHandler)?;

    let start_pos = if no_sync {
        0
    } else {
        let Some(start_pos) = memchr::memmem::find(buf, &PSB_BYTES) else {
            return Err(DecoderError::NoPsb);
        };
        start_pos
    };

    let mut context = DecoderContext {
        pos: start_pos,
        tracee_mode,
        packet_block: None,
    };

    raw_packet_handler::level1::decode(buf, &mut context, packet_handler)
}