ipt 0.1.3

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
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
//! Rust bindings to the Windows `ipt.sys` driver.
//!
//! `ipt.sys` is the Windows kernel driver that manages Intel Processor Trace (Intel PT).
//! There is no public Microsoft header or documentation for this interface; this crate provides
//! its own typed request/response layouts for it.
//!
//! [`Ipt::open`] the device, then call one [`Ipt`] method per driver operation (e.g.
//! [`Ipt::start_process_trace`], [`Ipt::get_trace_buffer`]). Each method builds its own request,
//! issues the `DeviceIoControl` call and decodes the response — no manual buffer/IOCTL plumbing
//! needed.
//!
//! # Platform
//!
//! This crate targets x86_64 on Windows only.
//!
//! # Stability
//!
//! `ipt.sys` is an internal OS component, not a supported public API. Its  shape can change between
//! Windows builds without notice. Treat this crate as best effort, only Microsoft & friends know
//! how stable this really is.

#![cfg(target_os = "windows")]

mod messages;
mod option;
mod utils;

use crate::messages::{
    GetTraceResponseHeader, Request, Response, SetPerImageTracingOption, TRACE_VERSION,
    TraceRecordHeader,
};
use crate::utils::ctl_code;
use core::mem::MaybeUninit;
pub use messages::{AddressFilterMode, AddressFilterRangeResponse, NUM_TRIES_UNLIMITED};
pub use option::IptOption;
use windows::Win32::Foundation::HANDLE;
use windows::Win32::Storage::FileSystem::{
    CreateFileW, FILE_ATTRIBUTE_NORMAL, FILE_FLAG_NO_BUFFERING, FILE_FLAG_SEQUENTIAL_SCAN,
    FILE_GENERIC_READ, FILE_SHARE_READ, OPEN_EXISTING,
};
use windows::Win32::System::IO::DeviceIoControl;
use windows::Win32::System::Ioctl::{
    FILE_ANY_ACCESS, FILE_DEVICE_UNKNOWN, METHOD_BUFFERED, METHOD_OUT_DIRECT,
};
use windows::core::{Owned, w};

/// Handle to the `ipt.sys` device, and the entry point for every operation in this crate.
#[derive(Debug, PartialEq, Eq)]
pub struct Ipt {
    ipt_handle: Owned<HANDLE>,
}

impl Ipt {
    /// Opens `\\.\IPT` to communicate with the ipt driver. Fails if the `ipt` service isn't running
    /// (run in an admin cmd `sc start ipt`).
    pub fn open() -> windows::core::Result<Self> {
        let ipt_path = w!("\\\\.\\IPT");
        unsafe {
            CreateFileW(
                ipt_path,
                FILE_GENERIC_READ.0,
                FILE_SHARE_READ,
                None,
                OPEN_EXISTING,
                FILE_ATTRIBUTE_NORMAL | FILE_FLAG_SEQUENTIAL_SCAN | FILE_FLAG_NO_BUFFERING,
                None,
            )
        }
        .map(|h| Self {
            ipt_handle: unsafe { Owned::new(h) },
        })
        .inspect_err(|e| {
            #[cfg(feature = "log")]
            log::error!(
                "Failed to open IPT device: {e};\nMake sure the ipt service is running with\
                `sc start ipt` from an admin shell."
            );
        })
    }

    /// The driver's protocol interface version (currently always `1`).
    ///
    /// Can be used as a cheap capability probe; always succeeds if the device opened.
    pub fn get_interface_version(&self) -> windows::core::Result<u16> {
        let request = Request::get_interface_version();
        let (response, response_size) = self.send_ioctl(METHOD_BUFFERED, &request)?;
        debug_assert_eq!(response_size as usize, size_of::<Response>());
        Ok(unsafe { response.interface_version })
    }

    /// Total output buffer size that a subsequent [`Ipt::get_trace_buffer`] call needs to drain.
    /// Usable as the length of the buffer passed to that call.
    pub fn get_trace_buffer_size(&self, process_handle: HANDLE) -> windows::core::Result<u64> {
        let request = Request::get_trace_buffer_size(process_handle);
        let (response, response_size) = self.send_ioctl(METHOD_BUFFERED, &request)?;
        debug_assert_eq!(response_size as usize, size_of::<Response>());
        let trace_buffer_size = unsafe { response.trace_buffer_size };
        debug_assert_eq!(trace_buffer_size.trace_version, TRACE_VERSION);
        Ok(trace_buffer_size.trace_size)
    }

    /// Copies `process_handle`'s currently-captured Intel PT trace data (buffer-mode tracing only)
    /// into `out`, replacing its contents. Iterate the per-thread records afterward with
    /// [`TraceBuffer::iter`]. Size `out` using [`Ipt::get_trace_buffer_size`] first, a too-small
    /// buffer is likely to raise an error (`STATUS_BUFFER_OVERFLOW` or `STATUS_BUFFER_TOO_SMALL`)
    /// even though the driver may have partially filled it.
    pub fn get_trace_buffer(
        &self,
        process_handle: HANDLE,
        out: &mut TraceBuffer,
    ) -> windows::core::Result<()> {
        let request = Request::get_trace_buffer(process_handle);
        let out_size = self.send_ioctl_raw_out(
            METHOD_OUT_DIRECT,
            &request,
            out.inner.as_mut_ptr().cast(),
            out.inner.capacity().try_into().unwrap_or(u32::MAX),
        )?;
        debug_assert!(out_size as usize <= out.inner.capacity());
        // SAFETY: Windows driver should not overflow user buffer
        unsafe { out.inner.set_len(out_size as usize) };

        debug_assert!(
            out.inner
                .as_ptr()
                .cast::<GetTraceResponseHeader>()
                .is_aligned()
        );
        let header = unsafe {
            out.inner
                .as_ptr()
                .cast::<GetTraceResponseHeader>()
                .as_ref_unchecked()
        };
        debug_assert_eq!(header.trace_version, TRACE_VERSION);
        #[cfg(feature = "log")]
        {
            if header.unknown != GetTraceResponseHeader::UNKNOWN_EXPECTED {
                log::warn!(
                    "Trace header field `unknown` has an unexpected value {}, expected: {} ",
                    header.unknown,
                    GetTraceResponseHeader::UNKNOWN_EXPECTED
                );
            }
        }
        debug_assert_eq!(
            header.bytes_written as usize,
            out_size as usize - size_of::<GetTraceResponseHeader>()
        );

        Ok(())
    }

    /// Persists `ipt_option` to the driver's service registry key and  immediately starts
    /// system-wide/per-core tracing with it. Requires `ipt_option.ring_filter()` to be one of the
    /// `..._SYSTEM_WIDE` values, and admin rights to write the service key. `num_tries` is the
    /// watchdog's retry-attempt budget, clamped to at most `8` (use [`NUM_TRIES_UNLIMITED`] for no
    /// limit); `ttl_seconds` auto-stops tracing that many seconds after being armed.
    pub fn set_system_wide_tracing_option(
        &self,
        ipt_option: IptOption,
        num_tries: u32,
        ttl_seconds: u32,
    ) -> windows::core::Result<()> {
        let request = Request::set_system_wide_tracing_option(ipt_option, num_tries, ttl_seconds);
        self.send_ioctl(METHOD_BUFFERED, &request)?;
        Ok(())
    }

    /// # TODO: This method was not tested!
    ///
    /// Persists `ipt_option` under `image_name`'s Image File Execution Options key so the driver
    /// auto-starts tracing whenever a process with that image name is created.
    /// `image_name`/`second_string` are UTF-16 code units (no trailing NUL required). `num_tries`/
    /// `ttl_seconds` are the same watchdog settings as
    /// [`Ipt::set_system_wide_tracing_option`]; `ipt_option.ring_filter()`
    /// must be one of the per-image values instead of the system-wide ones.
    pub fn set_per_image_tracing_option(
        &self,
        ipt_option: IptOption,
        num_tries: u32,
        ttl_seconds: u32,
        image_name: &[u16],
        second_string: Option<&[u16]>,
    ) -> windows::core::Result<()> {
        let req = SetPerImageTracingOption::raw_request(
            ipt_option,
            num_tries,
            ttl_seconds,
            image_name,
            second_string,
        );
        self.send_ioctl_raw_in(METHOD_BUFFERED, req.as_ptr().cast(), req.len() as u32)?;
        Ok(())
    }

    /// Starts tracing `process_handle` (or the `-1` pseudo-handle for the current process) into the
    /// driver-managed in-memory buffer(s), retrievable via [`Ipt::get_trace_buffer_size`]/
    /// [`Ipt::get_trace_buffer`]. Requires `ipt_option.trace_mode()` to be
    /// [`IptOption::TRACE_MODE_BUFFER`].
    pub fn start_process_trace(
        &self,
        process_handle: HANDLE,
        ipt_option: IptOption,
    ) -> windows::core::Result<()> {
        let request = Request::start_process_trace(process_handle, ipt_option);
        self.send_ioctl(METHOD_BUFFERED, &request)?;
        Ok(())
    }

    /// General form of [`Ipt::start_process_trace`] (`process_handle` also accepts the `-1`
    /// pseudo-handle): also supports file mode
    /// (`ipt_option.trace_mode() ==` [`IptOption::TRACE_MODE_FILE`]), continuously flushing to
    /// `trace_file_handle` instead of the in-memory buffer. `trace_file_handle` is ignored in
    /// buffer mode; in file mode it must be an already-open, write-capable file handle, and
    /// `ipt_option` must additionally have `ring_filter()` set to exactly
    /// [`IptOption::RING_FILTER_KERNEL_USER`], `match_settings()` clear, and a non-zero
    /// `buffer_size_exp()`.
    pub fn start_process_trace_ex(
        &self,
        process_handle: HANDLE,
        trace_file_handle: HANDLE,
        ipt_option: IptOption,
    ) -> windows::core::Result<()> {
        let request =
            Request::start_process_trace_ex(process_handle, trace_file_handle, ipt_option);
        self.send_ioctl(METHOD_BUFFERED, &request)?;
        Ok(())
    }

    /// Tears down tracing for every thread of `process_handle`.
    pub fn stop_process_trace(&self, process_handle: HANDLE) -> windows::core::Result<()> {
        let request = Request::stop_process_trace(process_handle);
        self.send_ioctl(METHOD_BUFFERED, &request)?;
        Ok(())
    }

    /// Suspends PT recording for `thread_handle` without discarding its  buffer or configuration.
    /// Returns whether it was already paused before this call.
    pub fn pause_thread_trace(&self, thread_handle: HANDLE) -> windows::core::Result<bool> {
        let request = Request::pause_thread_trace(thread_handle);
        let (response, response_size) = self.send_ioctl(METHOD_BUFFERED, &request)?;
        debug_assert_eq!(response_size as usize, size_of::<Response>());
        Ok(unsafe { response.pause_state.previously_paused } != 0)
    }

    /// Mirror of [`Ipt::pause_thread_trace`]. Returns whether the thread was already paused before
    /// this call (i.e. this was a no-op).
    pub fn resume_thread_trace(&self, thread_handle: HANDLE) -> windows::core::Result<bool> {
        let request = Request::resume_thread_trace(thread_handle);
        let (response, response_size) = self.send_ioctl(METHOD_BUFFERED, &request)?;
        debug_assert_eq!(response_size as usize, size_of::<Response>());
        Ok(unsafe { response.pause_state.previously_paused } != 0)
    }

    /// The [`IptOption`] `process_handle` was started with, or an all-zero value if it isn't
    /// currently being traced. An echo of the start-time configuration, not a live status query.
    pub fn query_process_trace_configuration(
        &self,
        process_handle: HANDLE,
    ) -> windows::core::Result<IptOption> {
        let request = Request::query_process_trace_configuration(process_handle);
        let (response, response_size) = self.send_ioctl(METHOD_BUFFERED, &request)?;
        debug_assert_eq!(response_size as usize, size_of::<Response>());
        Ok(unsafe { response.trace_config.ipt_option })
    }

    /// Non-zero while system-wide tracing ([`Ipt::set_system_wide_tracing_option`] or the ETW path)
    /// is active, `0` otherwise.
    pub fn query_system_wide_tracing_state(&self) -> windows::core::Result<u64> {
        let request = Request::query_system_wide_tracing_state();
        let (response, response_size) = self.send_ioctl(METHOD_BUFFERED, &request)?;
        debug_assert_eq!(response_size as usize, size_of::<Response>());
        Ok(unsafe { response.core_tracing_state.state })
    }

    /// Mirrors [`Ipt::set_system_wide_tracing_option`]'s start.
    pub fn stop_system_wide_tracing(&self) -> windows::core::Result<()> {
        let request = Request::stop_system_wide_tracing();
        self.send_ioctl(METHOD_BUFFERED, &request)?;
        Ok(())
    }

    /// Programs IP-filtering range `range_index` (`0..RANGECNT`, CPU-reported via
    /// `CPUID.14H.01H:EAX[2:0]`, commonly `2` or `4`) for `thread_handle` (or the `-2`
    /// pseudo-handle for the current thread).
    pub fn configure_thread_address_filter_range(
        &self,
        thread_handle: HANDLE,
        range_index: u32,
        mode: AddressFilterMode,
        start_address: u64,
        end_address: u64,
    ) -> windows::core::Result<()> {
        let request = Request::configure_thread_address_filter_range(
            thread_handle,
            range_index,
            mode,
            start_address,
            end_address,
        );
        self.send_ioctl(METHOD_BUFFERED, &request)?;
        Ok(())
    }

    /// Reads back the range last programmed by [`Ipt::configure_thread_address_filter_range`] for
    /// `thread_handle` (or the `-2` pseudo-handle for the current thread).
    pub fn query_thread_address_filter_range(
        &self,
        thread_handle: HANDLE,
        range_index: u32,
    ) -> windows::core::Result<AddressFilterRangeResponse> {
        let request = Request::query_thread_address_filter_range(thread_handle, range_index);
        let (response, response_size) = self.send_ioctl(METHOD_BUFFERED, &request)?;
        debug_assert_eq!(response_size as usize, size_of::<Response>());
        Ok(unsafe { response.address_filter_range })
    }

    /// Whether `thread_handle`'s instruction pointer has entered a configured
    /// [`AddressFilterMode::TraceStop`] range since tracing began (`IA32_RTIT_STATUS.Stopped`).
    pub fn query_thread_trace_stop_range_entered(
        &self,
        thread_handle: HANDLE,
    ) -> windows::core::Result<bool> {
        let request = Request::query_thread_trace_stop_range_entered(thread_handle);
        let (response, response_size) = self.send_ioctl(METHOD_BUFFERED, &request)?;
        debug_assert_eq!(response_size as usize, size_of::<Response>());
        Ok(unsafe { response.trace_stop_entered.entered } != 0)
    }

    fn send_ioctl(
        &self,
        ioctl_method: u32,
        request: &Request,
    ) -> windows::core::Result<(Response, u32)> {
        let mut response = MaybeUninit::<Response>::uninit();
        let out_size = self.send_ioctl_raw(
            ioctl_method,
            (&raw const *request).cast(),
            size_of::<Request>() as u32,
            response.as_mut_ptr().cast(),
            size_of::<Response>() as u32,
        )?;
        Ok((unsafe { response.assume_init() }, out_size))
    }

    fn send_ioctl_raw_in(
        &self,
        ioctl_method: u32,
        input: *const core::ffi::c_void,
        input_size: u32,
    ) -> windows::core::Result<Response> {
        let mut response = MaybeUninit::<Response>::uninit();
        let out_size = self.send_ioctl_raw(
            ioctl_method,
            input,
            input_size,
            response.as_mut_ptr().cast(),
            size_of::<Response>() as u32,
        )?;
        debug_assert_eq!(out_size as usize, size_of::<Response>());
        Ok(unsafe { response.assume_init() })
    }

    fn send_ioctl_raw_out(
        &self,
        ioctl_method: u32,
        request: &Request,
        out: *mut core::ffi::c_void,
        out_capacity: u32,
    ) -> windows::core::Result<u32> {
        self.send_ioctl_raw(
            ioctl_method,
            (&raw const *request).cast(),
            size_of::<Request>() as u32,
            out,
            out_capacity,
        )
    }

    fn send_ioctl_raw(
        &self,
        ioctl_method: u32,
        input: *const core::ffi::c_void,
        input_size: u32,
        out: *mut core::ffi::c_void,
        out_capacity: u32,
    ) -> windows::core::Result<u32> {
        let ioctl = ctl_code(FILE_DEVICE_UNKNOWN, 1, ioctl_method, FILE_ANY_ACCESS);
        let mut out_size = 0;

        unsafe {
            DeviceIoControl(
                *self.ipt_handle,
                ioctl,
                Some(input),
                input_size,
                Some(out),
                out_capacity,
                Some(&raw mut out_size),
                None,
            )
        }?;

        Ok(out_size)
    }
}

/// Output buffer for [`Ipt::get_trace_buffer`] sized to hold a `GetTraceBuffer` response.
/// Iterate the per-thread records it holds with [`TraceBuffer::iter`].
#[derive(Debug, Clone, PartialEq)]
pub struct TraceBuffer {
    inner: Vec<u8>,
}

impl TraceBuffer {
    /// Allocates space for at least `capacity` bytes of trace data (size it with
    /// [`Ipt::get_trace_buffer_size`]).
    // use u64 for capacity to use the same data type as get_trace_buffer_size
    #[must_use]
    pub fn with_capacity(capacity: u64) -> Self {
        Self {
            inner: Vec::with_capacity(capacity as usize),
        }
    }

    /// Iterates the per-thread `(header, raw Intel PT trace)`
    /// records
    #[must_use]
    pub const fn iter(&self) -> TraceBufferIter<'_> {
        TraceBufferIter {
            buffer: self,
            i: size_of::<GetTraceResponseHeader>(),
        }
    }
}

impl<'a> IntoIterator for &'a TraceBuffer {
    type Item = (&'a TraceRecordHeader, &'a [u8]);
    type IntoIter = TraceBufferIter<'a>;
    fn into_iter(self) -> TraceBufferIter<'a> {
        self.iter()
    }
}

/// Iterator over a [`TraceBuffer`]'s per-thread trace records, returned by
/// [`TraceBuffer::iter`].
pub struct TraceBufferIter<'a> {
    buffer: &'a TraceBuffer,
    i: usize,
}

impl<'a> Iterator for TraceBufferIter<'a> {
    type Item = (&'a TraceRecordHeader, &'a [u8]);

    fn next(&mut self) -> Option<Self::Item> {
        if self.buffer.inner.len() < self.i + size_of::<TraceRecordHeader>() {
            return None;
        }

        let header_ptr = self.buffer.inner[self.i..self.i + size_of::<TraceRecordHeader>()]
            .as_ptr()
            .cast::<TraceRecordHeader>();
        self.i += size_of::<TraceRecordHeader>();
        debug_assert!(header_ptr.is_aligned());
        let header = unsafe { header_ptr.as_ref_unchecked() };

        let data = &self.buffer.inner[self.i..self.i + header.payload_length as usize];
        self.i += header.payload_length as usize;

        Some((header, data))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    #[test]
    fn test() {
        let ipt = Ipt::open().unwrap();
        assert_eq!(ipt.get_interface_version().unwrap(), 1);
    }
}