ipt 0.1.0

Bindings to the undocumented Windows ipt.sys (Intel Processor Trace) driver interface
Documentation
//! The packed 64-bit trace configuration value.

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

/// Supplied directly 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 validation of its own — the driver is the
/// authority on which combinations are legal (see the field docs below for
/// what it currently enforces).
#[bitfield(u64)]
#[derive(Debug)]
pub struct IptOption {
    /// Output channel for captured trace data. Must be
    /// [`IptOption::TRACE_MODE_BUFFER`] or [`IptOption::TRACE_MODE_FILE`];
    /// any other value is rejected with `STATUS_INVALID_PARAMETER`.
    #[bits(0..=3, rw)]
    pub trace_mode: u4,
    /// Which extra timing packets are generated beyond the default TSC
    /// packets. One of the `TIMING_MODE_*` associated constants; values
    /// `>= 3` are rejected.
    #[bits(4..=7, rw)]
    pub timing_mode: u4,
    /// `IA32_RTIT_CTL.MTCFreq` (SDM bits 14:17 of the real MSR) — selects
    /// the periodicity of MTC packets. Must be a value the CPU advertises
    /// as legal (`CPUID.14H.1:EAX[31:16]` bitmap). Meaningful only when
    /// `timing_mode` is [`IptOption::TIMING_MODE_MTC`] or
    /// [`IptOption::TIMING_MODE_MTC_CYC`].
    #[bits(8..=11, rw)]
    pub mtc_freq: u4,
    /// `IA32_RTIT_CTL.CycThresh` (SDM bits 19:22 of the real MSR) — CYC
    /// packet threshold. Validated against `CPUID.14H.1:EBX[15:0]`.
    /// Meaningful only when `timing_mode` is
    /// [`IptOption::TIMING_MODE_MTC_CYC`].
    #[bits(12..=15, rw)]
    pub cyc_thresh: u4,
    /// Trace (`ToPA`) buffer size, as `4 KiB << buffer_size_exp` (legal up to
    /// `15` → 128 MiB). Honored in full on bare metal no matter how large;
    /// under Hyper'V without PT passthrough, values above `8` (1 MiB) make
    /// the start call fail outright instead of being scaled down. Must be
    /// non-zero for file-mode start.
    #[bits(16..=19, rw)]
    pub buffer_size_exp: u4,
    /// Reserved when tracing by process/thread handle (must be `0` for a
    /// direct `StartProcessTraceEx` (opcode 16) buffer/file-mode start).
    #[bits(20..=22, rw)]
    pub match_settings: u3,
    /// 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.
    #[bit(23, rw)]
    pub inherit_to_children: bool,
    /// Controls `IA32_RTIT_CTL.OS`/`.User`. One of the `RING_FILTER_*`
    /// associated constants. There are two parallel encodings depending on
    /// which API surface is setting it — see the constants' docs — using
    /// the wrong half for the wrong opcode is rejected. Kernel-inclusive
    /// values require `SeDebugPrivilege`.
    #[bits(24..=27, rw)]
    pub ring_filter: u4,
    #[bits(28..=63)]
    _reserved: u36,
}

impl IptOption {
    /// [`Self::trace_mode`]: capture into the driver-managed in-memory `ToPA`
    /// buffer(s), retrievable via `GetTraceBufferSize`/`GetTraceBuffer`
    pub const TRACE_MODE_BUFFER: u4 = u4::new(1);
    /// [`Self::trace_mode`]: continuously flush each thread's buffer
    /// straight to a caller-supplied file (`StartProcessTraceEx` only).
    /// Not retrievable via the buffer-mode opcodes.
    pub const TRACE_MODE_FILE: u4 = u4::new(2);

    /// [`Self::timing_mode`]: no extra timing packets beyond default TSC.
    pub const TIMING_MODE_OFF: u4 = u4::new(0);
    /// [`Self::timing_mode`]: MTC packets enabled.
    pub const TIMING_MODE_MTC: u4 = u4::new(1);
    /// [`Self::timing_mode`]: MTC and CYC packets enabled.
    pub const TIMING_MODE_MTC_CYC: u4 = u4::new(2);

    /// [`Self::ring_filter`]: user-mode only. Valid for
    /// `SetPerImageTracingOption` (opcode 4) and live per-process start
    /// (`StartProcessTrace`/`StartProcessTraceEx`, opcodes 5/16).
    pub const RING_FILTER_USER: u4 = u4::new(0);
    /// [`Self::ring_filter`]: kernel-mode only (per-image/live-start
    /// encoding). Requires `SeDebugPrivilege`.
    pub const RING_FILTER_KERNEL: u4 = u4::new(1);
    /// [`Self::ring_filter`]: kernel and user mode (per-image/live-start
    /// encoding). Requires `SeDebugPrivilege`. The only value file mode
    /// accepts.
    pub const RING_FILTER_KERNEL_USER: u4 = u4::new(2);
    /// [`Self::ring_filter`]: user-mode only. Valid for
    /// `SetSystemWideTracingOption` (opcode 3) only.
    pub const RING_FILTER_USER_SYSTEM_WIDE: u4 = u4::new(3);
    /// [`Self::ring_filter`]: kernel-mode only (system-wide encoding).
    /// Requires `SeDebugPrivilege`.
    pub const RING_FILTER_KERNEL_SYSTEM_WIDE: u4 = u4::new(4);
    /// [`Self::ring_filter`]: kernel and user mode (system-wide encoding).
    /// Requires `SeDebugPrivilege`.
    pub const RING_FILTER_KERNEL_USER_SYSTEM_WIDE: u4 = u4::new(5);
}

impl Default for IptOption {
    fn default() -> Self {
        Self::builder()
            .with_trace_mode(Self::TRACE_MODE_BUFFER)
            .with_timing_mode(Self::TIMING_MODE_OFF)
            .with_buffer_size_exp(u4::new(8))
            .with_inherit_to_children(false)
            .with_ring_filter(Self::RING_FILTER_USER)
            .value
    }
}

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

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

    #[test]
    fn field_round_trip() {
        let opt = IptOption::new_with_raw_value(0)
            .with_trace_mode(IptOption::TRACE_MODE_BUFFER)
            .with_buffer_size_exp(u4::new(12))
            .with_ring_filter(IptOption::RING_FILTER_USER)
            .with_inherit_to_children(true);

        assert_eq!(opt.trace_mode(), IptOption::TRACE_MODE_BUFFER);
        assert_eq!(opt.buffer_size_exp(), u4::new(12));
        assert_eq!(opt.ring_filter(), IptOption::RING_FILTER_USER);
        assert!(opt.inherit_to_children());
    }
}