ipt 0.2.0

Bindings to the undocumented Windows ipt.sys (Intel Processor Trace) driver interface
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
//! Trace configuration options.

use arbitrary_int::traits::Integer;
use arbitrary_int::{u3, u4};
use bitbybit::bitfield;

/// Options to be supplied by the caller when starting a trace
/// (`StartProcessTrace`/`StartProcessTraceEx`), echoed back by
/// `QueryProcessTraceConfiguration`, and the same layout is written to/read from the registry by
/// `SetSystemWideTracingOption`/`SetPerImageTracingOption`.
///
/// This type performs no deep validation of its own — the driver is the authority on which
/// combinations are legal.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct IptOption {
    trace_mode: TraceMode,
    timing_mode: TimingMode,
    mtc_freq: u8,
    cyc_thresh: u8,
    buffer_size_exp: u8,
    match_settings: MatchSettings,
    inherit_to_children: bool,
    ring_filter: RingFilter,
}

impl Default for IptOption {
    fn default() -> Self {
        IptOption {
            trace_mode: TraceMode::default(),
            timing_mode: TimingMode::default(),
            mtc_freq: 0,
            cyc_thresh: 0,
            buffer_size_exp: 8,
            match_settings: MatchSettings::default(),
            inherit_to_children: false,
            ring_filter: RingFilter::default(),
        }
    }
}

impl IptOption {
    /// Output channel for captured trace data.
    #[must_use]
    pub const fn with_trace_mode(mut self, trace_mode: TraceMode) -> Self {
        self.trace_mode = trace_mode;
        self
    }

    /// Output channel for captured trace data, see [`IptOption::with_trace_mode`].
    #[must_use]
    pub const fn trace_mode(&self) -> TraceMode {
        self.trace_mode
    }

    /// Which extra timing packets are generated beyond the default TSC packets.
    #[must_use]
    pub const fn with_timing_mode(mut self, timing_mode: TimingMode) -> Self {
        self.timing_mode = timing_mode;
        self
    }

    /// Which extra timing packets are generated beyond the default TSC packets, see
    /// [`IptOption::with_timing_mode`].
    #[must_use]
    pub const fn timing_mode(&self) -> TimingMode {
        self.timing_mode
    }

    /// `IA32_RTIT_CTL.MTCFreq` — periodicity of MTC packets. Meaningful only when the timing mode
    /// is [`TimingMode::Mtc`] or [`TimingMode::MtcCyc`].
    ///
    /// Returns [`None`] if `mtc_freq` does not fit in the 4 bits the option word reserves for it.
    /// A value that fits here may still be rejected by the driver if the CPU does not advertise it
    /// as legal (`CPUID.14H.1:EAX[31:16]` bitmap).
    #[must_use]
    pub const fn with_mtc_freq(mut self, mtc_freq: u8) -> Option<Self> {
        if mtc_freq > MAX_U4 {
            return None;
        }
        self.mtc_freq = mtc_freq;
        Some(self)
    }

    /// `IA32_RTIT_CTL.MTCFreq` — periodicity of MTC packets, see [`IptOption::with_mtc_freq`].
    #[must_use]
    pub const fn mtc_freq(&self) -> u8 {
        self.mtc_freq
    }

    /// `IA32_RTIT_CTL.CycThresh` — CYC packet threshold. Meaningful only when the timing mode is
    /// [`TimingMode::MtcCyc`].
    ///
    /// Returns [`None`] if `cyc_thresh` does not fit in the 4 bits the option word reserves for it.
    /// A value that fits here may still be rejected by the driver if the CPU does not advertise it
    /// as legal (`CPUID.14H.1:EBX[15:0]` bitmap).
    #[must_use]
    pub const fn with_cyc_thresh(mut self, cyc_thresh: u8) -> Option<Self> {
        if cyc_thresh > MAX_U4 {
            return None;
        }
        self.cyc_thresh = cyc_thresh;
        Some(self)
    }

    /// `IA32_RTIT_CTL.CycThresh` — CYC packet threshold, see [`IptOption::with_cyc_thresh`].
    #[must_use]
    pub const fn cyc_thresh(&self) -> u8 {
        self.cyc_thresh
    }

    /// Trace (`ToPA`) buffer size, as `4 KiB << buffer_size_exp`.
    ///
    /// Returns [`None`] if `buffer_size_exp` does not fit in the 4 bits the option word reserves
    /// for it, i.e. if it is greater than `15` (128 MiB). Must be non-zero for
    /// [`TraceMode::File`]; under Hyper-V without PT passthrough, values above `8` (1 MiB) make the
    /// start call fail.
    #[must_use]
    pub const fn with_buffer_size_exp(mut self, buffer_size_exp: u8) -> Option<Self> {
        if buffer_size_exp > MAX_U4 {
            return None;
        }
        self.buffer_size_exp = buffer_size_exp;
        Some(self)
    }

    /// Trace (`ToPA`) buffer size, as `4 KiB << buffer_size_exp`, see
    /// [`IptOption::with_buffer_size_exp`].
    #[must_use]
    pub const fn buffer_size_exp(&self) -> u8 {
        self.buffer_size_exp
    }

    /// Which identity auto-started traces are grouped under. Only meaningful for
    /// [`Ipt::set_per_image_tracing_option`](crate::Ipt::set_per_image_tracing_option) and
    /// [`Ipt::set_system_wide_tracing_option`](crate::Ipt::set_system_wide_tracing_option); see
    /// [`MatchSettings`].
    #[must_use]
    pub const fn with_match_settings(mut self, match_settings: MatchSettings) -> Self {
        self.match_settings = match_settings;
        self
    }

    /// Which identity auto-started traces are grouped under, see
    /// [`IptOption::with_match_settings`].
    #[must_use]
    pub const fn match_settings(&self) -> MatchSettings {
        self.match_settings
    }

    /// If set, a process started with this option causes child processes it creates to
    /// automatically start tracing with the same option value, bypassing the per-image IFEO
    /// registry lookup.
    #[must_use]
    pub const fn with_inherit_to_children(mut self, inherit_to_children: bool) -> Self {
        self.inherit_to_children = inherit_to_children;
        self
    }

    /// Whether child processes automatically start tracing with this option, see
    /// [`IptOption::with_inherit_to_children`].
    #[must_use]
    pub const fn inherit_to_children(&self) -> bool {
        self.inherit_to_children
    }

    /// Controls `IA32_RTIT_CTL.OS`/`.User`. The encoding depends on which API surface consumes the
    /// option; kernel-inclusive values require `SeDebugPrivilege`.
    #[must_use]
    pub const fn with_ring_filter(mut self, ring_filter: RingFilter) -> Self {
        self.ring_filter = ring_filter;
        self
    }

    /// Which privilege rings are traced, see [`IptOption::with_ring_filter`].
    #[must_use]
    pub const fn ring_filter(&self) -> RingFilter {
        self.ring_filter
    }
}

/// Largest value representable in the 4-bit fields of [`IptOptionRaw`].
const MAX_U4: u8 = u4::MAX.value();

/// Where captured trace data is written.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
#[non_exhaustive]
#[repr(u8)]
pub enum TraceMode {
    /// Capture into the driver-managed in-memory `ToPA` buffer(s), retrievable via
    /// `GetTraceBufferSize`/`GetTraceBuffer`
    #[default]
    Buffer = 1,
    /// Continuously flush each thread's buffer straight to a caller-supplied file
    /// (`StartProcessTraceEx` only). Not retrievable via the buffer-mode opcodes.
    File = 2,
}

impl TraceMode {
    const fn from_repr(repr: u8) -> Option<Self> {
        match repr {
            1 => Some(Self::Buffer),
            2 => Some(Self::File),
            _ => None,
        }
    }
}

/// Which extra timing packets are generated beyond the default TSC packets.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
#[non_exhaustive]
#[repr(u8)]
pub enum TimingMode {
    /// No extra timing packets beyond default TSC.
    #[default]
    Off = 0,
    /// MTC packets enabled.
    Mtc = 1,
    /// MTC and CYC packets enabled.
    MtcCyc = 2,
}

impl TimingMode {
    const fn from_repr(repr: u8) -> Option<Self> {
        match repr {
            0 => Some(Self::Off),
            1 => Some(Self::Mtc),
            2 => Some(Self::MtcCyc),
            _ => None,
        }
    }
}

/// Which identity the driver groups auto-started traces under.
///
/// When an image's IFEO entry makes the driver start tracing a newly created process, a non-`None`
/// value registers that process in a global *session* keyed by the chosen string. The driver
/// consults those sessions before the registry, so every later process matching the same key is
/// traced with the same option word without needing its own IFEO entry. It is the sibling-wise
/// counterpart of `inherit_to_children`, which spreads a configuration down a parent/child lineage
/// instead.
///
/// Only meaningful on the registry-backed paths
/// ([`Ipt::set_per_image_tracing_option`](crate::Ipt::set_per_image_tracing_option),
/// [`Ipt::set_system_wide_tracing_option`](crate::Ipt::set_system_wide_tracing_option)). A live
/// start by handle never builds a session key: file mode rejects a non-`None` value outright, and
/// buffer mode stores it but never acts on it.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[non_exhaustive]
#[repr(u8)]
pub enum MatchSettings {
    /// No grouping: the configuration applies only to the process it started with.
    #[default]
    None = 0,
    /// Key sessions by the full image file name.
    ImageName = 1,
    /// Key sessions by the package identity full name (`RtlQueryPackageIdentity`). Reachable only
    /// for a packaged app, whose IFEO entry lives under a package-family subkey — the
    /// `second_string` of
    /// [`Ipt::set_per_image_tracing_option`](crate::Ipt::set_per_image_tracing_option).
    PackageIdentity = 3,
}

impl MatchSettings {
    const fn from_repr(repr: u8) -> Option<Self> {
        match repr {
            0 => Some(Self::None),
            1 => Some(Self::ImageName),
            3 => Some(Self::PackageIdentity),
            _ => None,
        }
    }
}

/// Which privilege rings are traced (`IA32_RTIT_CTL.OS`/`.User`). Two parallel encodings exist
/// depending on which API surface consumes the option; using the wrong half for the wrong opcode
/// is rejected by the driver.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
#[non_exhaustive]
#[repr(u8)]
pub enum RingFilter {
    /// User-mode only. Valid for `SetPerImageTracingOption` (opcode 4) and live per-process start
    /// (`StartProcessTrace`/`StartProcessTraceEx`, opcodes 5/16). The only value file mode
    /// accepts.
    #[default]
    User = 0,
    /// Kernel-mode only (per-image/live-start encoding). Requires `SeDebugPrivilege`.
    Kernel = 1,
    /// Kernel and user mode (per-image/live-start encoding). Requires `SeDebugPrivilege`.
    KernelUser = 2,
    /// User-mode only. Valid for `SetSystemWideTracingOption` (opcode 3) only.
    UserSystemWide = 3,
    /// Kernel-mode only (system-wide encoding). Requires `SeDebugPrivilege`.
    KernelSystemWide = 4,
    /// Kernel and user mode (system-wide encoding). Requires `SeDebugPrivilege`.
    KernelUserSystemWide = 5,
}

impl RingFilter {
    const fn from_repr(repr: u8) -> Option<Self> {
        match repr {
            0 => Some(Self::User),
            1 => Some(Self::Kernel),
            2 => Some(Self::KernelUser),
            3 => Some(Self::UserSystemWide),
            4 => Some(Self::KernelSystemWide),
            5 => Some(Self::KernelUserSystemWide),
            _ => None,
        }
    }
}

/// The 64-bit option word as the driver reads and writes it.
#[bitfield(u64, default = 0x8_0001)]
#[derive(Debug, PartialEq, Eq)]
pub struct IptOptionRaw {
    #[bits(0..=3, rw)]
    pub trace_mode: u4,
    #[bits(4..=7, rw)]
    pub timing_mode: u4,
    #[bits(8..=11, rw)]
    pub mtc_freq: u4,
    #[bits(12..=15, rw)]
    pub cyc_thresh: u4,
    #[bits(16..=19, rw)]
    pub buffer_size_exp: u4,
    #[bits(20..=22, rw)]
    pub match_settings: u3,
    #[bit(23, rw)]
    pub inherit_to_children: bool,
    #[bits(24..=27, rw)]
    pub ring_filter: u4,
    #[bits(28..=63)]
    _reserved: u36,
}

impl From<IptOption> for IptOptionRaw {
    fn from(value: IptOption) -> Self {
        IptOptionRaw::builder()
            .with_trace_mode(u4::new(value.trace_mode as u8))
            .with_timing_mode(u4::new(value.timing_mode as u8))
            .with_mtc_freq(u4::new(value.mtc_freq))
            .with_cyc_thresh(u4::new(value.cyc_thresh))
            .with_buffer_size_exp(u4::new(value.buffer_size_exp))
            .with_match_settings(u3::new(value.match_settings as u8))
            .with_inherit_to_children(value.inherit_to_children)
            .with_ring_filter(u4::new(value.ring_filter as u8))
            .build()
    }
}

impl TryFrom<IptOptionRaw> for IptOption {
    type Error = ();

    fn try_from(value: IptOptionRaw) -> Result<Self, Self::Error> {
        Ok(IptOption {
            trace_mode: TraceMode::from_repr(value.trace_mode().value()).ok_or(())?,
            timing_mode: TimingMode::from_repr(value.timing_mode().value()).ok_or(())?,
            mtc_freq: value.mtc_freq().value(),
            cyc_thresh: value.cyc_thresh().value(),
            buffer_size_exp: value.buffer_size_exp().value(),
            match_settings: MatchSettings::from_repr(value.match_settings().value()).ok_or(())?,
            inherit_to_children: value.inherit_to_children(),
            ring_filter: RingFilter::from_repr(value.ring_filter().value()).ok_or(())?,
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn default() {
        let default: IptOptionRaw = IptOption::default().into();
        let raw_default = IptOptionRaw::default();
        assert_eq!(default, raw_default);
    }

    #[test]
    fn size_matches_msr_width() {
        assert_eq!(size_of::<IptOptionRaw>(), 8);
    }

    #[test]
    fn field_round_trip() {
        let opt = IptOption::default()
            .with_trace_mode(TraceMode::File)
            .with_timing_mode(TimingMode::MtcCyc)
            .with_mtc_freq(3)
            .unwrap()
            .with_cyc_thresh(15)
            .unwrap()
            .with_buffer_size_exp(12)
            .unwrap()
            .with_match_settings(MatchSettings::PackageIdentity)
            .with_inherit_to_children(true)
            .with_ring_filter(RingFilter::KernelUser);

        assert_eq!(opt.trace_mode(), TraceMode::File);
        assert_eq!(opt.timing_mode(), TimingMode::MtcCyc);
        assert_eq!(opt.mtc_freq(), 3);
        assert_eq!(opt.cyc_thresh(), 15);
        assert_eq!(opt.buffer_size_exp(), 12);
        assert_eq!(opt.match_settings(), MatchSettings::PackageIdentity);
        assert!(opt.inherit_to_children());
        assert_eq!(opt.ring_filter(), RingFilter::KernelUser);

        let raw: IptOptionRaw = opt.into();
        assert_eq!(raw.trace_mode(), u4::new(TraceMode::File as u8));
        assert_eq!(raw.timing_mode(), u4::new(TimingMode::MtcCyc as u8));
        assert_eq!(raw.mtc_freq(), u4::new(3));
        assert_eq!(raw.cyc_thresh(), u4::new(15));
        assert_eq!(raw.buffer_size_exp(), u4::new(12));
        assert_eq!(
            raw.match_settings(),
            u3::new(MatchSettings::PackageIdentity as u8)
        );
        assert!(raw.inherit_to_children());
        assert_eq!(raw.ring_filter(), u4::new(RingFilter::KernelUser as u8));
    }

    #[test]
    fn raw_round_trip() {
        let opt = IptOption::default()
            .with_trace_mode(TraceMode::File)
            .with_timing_mode(TimingMode::MtcCyc)
            .with_mtc_freq(3)
            .unwrap()
            .with_ring_filter(RingFilter::KernelUserSystemWide);

        assert_eq!(IptOption::try_from(IptOptionRaw::from(opt)), Ok(opt));
    }

    #[test]
    fn raw_with_unknown_discriminants_is_rejected() {
        // trace_mode 0 — rejected by the driver's own `CheckIptOption`, so no option word it
        // hands back should ever carry it.
        let zeroed = IptOptionRaw::new_with_raw_value(0);
        assert_eq!(IptOption::try_from(zeroed), Err(()));

        let bad_ring_filter = IptOptionRaw::from(IptOption::default()).with_ring_filter(u4::new(6));
        assert_eq!(IptOption::try_from(bad_ring_filter), Err(()));

        // 2 and 4..=7 are accepted by a buffer-mode start but the driver never acts on them.
        let inert_match_settings =
            IptOptionRaw::from(IptOption::default()).with_match_settings(u3::new(2));
        assert_eq!(IptOption::try_from(inert_match_settings), Err(()));
    }

    #[test]
    fn u8_setters_reject_out_of_range() {
        assert!(IptOption::default().with_mtc_freq(16).is_none());
        assert!(IptOption::default().with_cyc_thresh(16).is_none());
        assert!(IptOption::default().with_buffer_size_exp(16).is_none());

        assert!(IptOption::default().with_mtc_freq(15).is_some());
        assert!(IptOption::default().with_cyc_thresh(15).is_some());
        assert!(IptOption::default().with_buffer_size_exp(15).is_some());
    }
}