ipt 0.2.0-beta1

Bindings to the undocumented Windows ipt.sys (Intel Processor Trace) driver interface
Documentation
//! Trace configuration options.

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

/// 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,
    /// Controls `IA32_RTIT_CTL.OS`/`.User`. There are two parallel encodings depending on
    /// which API surface is setting it: using the wrong half for the wrong opcode is rejected.
    /// Kernel-inclusive values require `SeDebugPrivilege`.
    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.
    pub const fn trace_mode(mut self, trace_mode: TraceMode) -> Self {
        self.trace_mode = trace_mode;
        self
    }

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

    /// `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).
    pub const fn 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.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).
    pub const fn cyc_thresh(mut self, cyc_thresh: u8) -> Option<Self> {
        if cyc_thresh > MAX_U4 {
            return None;
        }
        self.cyc_thresh = cyc_thresh;
        Some(self)
    }

    /// 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.
    pub const fn 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)
    }

    /// 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`].
    pub const fn match_settings(mut self, match_settings: MatchSettings) -> Self {
        self.match_settings = match_settings;
        self
    }

    /// 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.
    pub const fn inherit_to_children(mut self, inherit_to_children: bool) -> Self {
        self.inherit_to_children = inherit_to_children;
        self
    }

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

/// 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, FromRepr)]
#[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,
}

/// Which extra timing packets are generated beyond the default TSC packets.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, FromRepr)]
#[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,
}

/// 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, FromRepr)]
#[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,
}

/// 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, FromRepr)]
#[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).
    #[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`. The only
    /// value file mode accepts.
    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,
}

/// 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()
            .trace_mode(TraceMode::File)
            .timing_mode(TimingMode::MtcCyc)
            .mtc_freq(3)
            .unwrap()
            .cyc_thresh(15)
            .unwrap()
            .buffer_size_exp(12)
            .unwrap()
            .match_settings(MatchSettings::PackageIdentity)
            .inherit_to_children(true)
            .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()
            .trace_mode(TraceMode::File)
            .timing_mode(TimingMode::MtcCyc)
            .mtc_freq(3)
            .unwrap()
            .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().mtc_freq(16).is_none());
        assert!(IptOption::default().cyc_thresh(16).is_none());
        assert!(IptOption::default().buffer_size_exp(16).is_none());

        assert!(IptOption::default().mtc_freq(15).is_some());
        assert!(IptOption::default().cyc_thresh(15).is_some());
        assert!(IptOption::default().buffer_size_exp(15).is_some());
    }
}