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
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
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
//! 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(all(target_os = "windows", target_arch = "x86_64"))]

mod messages;
mod option;
mod utils;

use crate::messages::{
    GetTraceResponseHeader, Request, Response, SetPerImageTracingOption, TRACE_VERSION,
};
use crate::utils::ctl_code;
use core::iter::FusedIterator;
use core::mem::MaybeUninit;
pub use messages::{
    AddressFilterMode, AddressFilterRangeResponse, NUM_TRIES_UNLIMITED, TraceRecordHeader,
};
pub use option::{IptOption, MatchSettings, RingFilter, TimingMode, TraceMode};
use windows::Win32::Foundation::{ERROR_INVALID_DATA, 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::{Error, 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.
    /// Whatever [`Ipt::get_trace_buffer_size`] reports (it can be as low as `8`), `out` needs at
    /// least 24 bytes of capacity, or the driver rejects the call with `STATUS_INVALID_PARAMETER`.
    ///
    /// # Errors
    /// `out` is left describing exactly what the driver wrote whether this returns `Ok` or `Err`,
    /// so it is always safe to iterate afterwards.
    ///
    /// The error worth handling is `STATUS_BUFFER_OVERFLOW` (surfaced as `ERROR_MORE_DATA`):
    /// `out` was too small for the whole response, but the records that did fit are complete and
    /// `out` holds them.
    ///
    /// `STATUS_BUFFER_TOO_SMALL` (`ERROR_INSUFFICIENT_BUFFER`) means the driver wrote nothing at
    /// all; `out` ends up empty.
    pub fn get_trace_buffer(
        &self,
        process_handle: HANDLE,
        out: &mut TraceBuffer,
    ) -> windows::core::Result<()> {
        let request = Request::get_trace_buffer(process_handle);
        out.inner.clear();
        let (result, 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),
        );
        assert!(
            out_size as usize <= out.inner.capacity(),
            "driver reported writing {out_size} bytes into a {} byte buffer",
            out.inner.capacity()
        );

        if (out_size as usize) < size_of::<GetTraceResponseHeader>() {
            result?;
            return Err(Error::new(
                ERROR_INVALID_DATA.to_hresult(),
                "driver reported a response shorter than a trace response header",
            ));
        }

        // SAFETY: the driver wrote `out_size` bytes, asserted above to be within capacity.
        // Done before propagating `result` so that a `STATUS_BUFFER_OVERFLOW` response, which is
        // truncated but valid, stays iterable instead of being thrown away.
        // A hard failure reports `0` bytes, which empties `out` rather than leaving a stale trace.
        unsafe { out.inner.set_len(out_size as usize) };

        // SAFETY: `inner` was just checked to hold at least `size_of::<GetTraceResponseHeader>()`
        // initialized bytes, and the read is unaligned so `inner`'s alignment of 1 is enough.
        let header = unsafe {
            out.inner
                .as_ptr()
                .cast::<GetTraceResponseHeader>()
                .read_unaligned()
        };
        debug_assert_eq!(header.trace_version, TRACE_VERSION);
        #[cfg(feature = "log")]
        {
            if header.response_version != GetTraceResponseHeader::RESPONSE_VERSION_EXPECTED {
                log::warn!(
                    "Trace header field `response_version` has an unexpected value {}, expected: {}",
                    header.response_version,
                    GetTraceResponseHeader::RESPONSE_VERSION_EXPECTED
                );
            }
        }
        debug_assert_eq!(
            header.bytes_written as usize,
            out_size as usize - size_of::<GetTraceResponseHeader>()
        );

        result
    }

    /// Persists `ipt_option` to the driver's service registry key and immediately starts
    /// system-wide/per-core tracing with it. Requires `ipt_option`'s ring filter to be one of the
    /// system-wide values ([`RingFilter::UserSystemWide`], [`RingFilter::KernelSystemWide`],
    /// [`RingFilter::KernelUserSystemWide`]), 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`'s ring filter must be one of the
    /// per-image values ([`RingFilter::User`], [`RingFilter::Kernel`],
    /// [`RingFilter::KernelUser`]) 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`'s trace mode to be [`TraceMode::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
    /// ([`TraceMode::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 its ring
    /// filter set to exactly [`RingFilter::User`], match settings left at
    /// [`MatchSettings::None`], `inherit_to_children` unset, and a non-zero buffer size exponent.
    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 the thread was actively tracing before this call, i.e. whether this call
    /// actually paused it; `false` means it was already paused and this was a no-op.
    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_enabled } != 0)
    }

    /// Mirror of [`Ipt::pause_thread_trace`].
    ///
    /// Returns whether the thread was already tracing before this call, i.e. whether this was a
    /// no-op; `false` means it was paused and this call resumed it.
    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_enabled } != 0)
    }

    /// The [`IptOption`] `process_handle` was started with. An echo of the start-time
    /// configuration, not a live status query.
    ///
    /// # Errors
    /// A process that isn't currently being traced fails the call itself with
    /// `STATUS_UNSUCCESSFUL`: the driver only writes the option word once it has found a live
    /// process context. `ERROR_INVALID_DATA` means the driver reported success but returned a word
    /// this crate cannot decode, which would mean its layout has drifted.
    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>());
        let raw = unsafe { response.trace_config.ipt_option };
        IptOption::try_from(raw).map_err(|_| {
            Error::new(
                ERROR_INVALID_DATA.to_hresult(),
                "driver returned an option word that does not decode into an IptOption",
            )
        })
    }

    /// 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>());
        // The driver rejects a `mode` above `2` when *programming* a range, but this query returns
        // the raw 4-bit `IA32_RTIT_CTL.ADDRn_CFG` field, whose reserved encodings it does not
        // filter. Reject those before they reach the fieldless `AddressFilterMode`.
        // This is most likely unnecessary, just to stay on the safe side.
        if AddressFilterMode::from_repr(u32::from_ne_bytes(
            response.as_bytes()[0..size_of::<AddressFilterMode>()]
                .try_into()
                .unwrap(),
        ))
        .is_none()
        {
            return Err(Error::new(
                ERROR_INVALID_DATA.to_hresult(),
                "driver reported a reserved address filter mode",
            ));
        }
        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 (result, 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,
        );
        result?;
        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();
        self.send_ioctl_raw(
            ioctl_method,
            input,
            input_size,
            response.as_mut_ptr().cast(),
            size_of::<Response>() as u32,
        )
        .0?;
        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,
        )
    }

    /// Returns the outcome and the number of bytes the driver wrote, separately: the byte count
    /// stays meaningful when the call fails, which is what lets `GetTraceBuffer` keep the partial
    /// response a `STATUS_BUFFER_OVERFLOW` leaves behind.
    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;

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

        (result, 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 {
    /// Construct a new empty [`TraceBuffer`]
    #[must_use]
    pub const fn new() -> Self {
        Self { inner: Vec::new() }
    }

    /// 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),
        }
    }

    /// Bytes of trace data this buffer can hold without reallocating. This, not its current
    /// contents, is what [`Ipt::get_trace_buffer`] fills.
    #[must_use]
    pub const fn capacity(&self) -> u64 {
        self.inner.capacity() as u64
    }

    /// Bytes of trace data currently held by this buffer.
    #[must_use]
    pub const fn len(&self) -> usize {
        self.inner.len()
    }

    /// Returns `true` if this buffer holds no trace data.
    #[must_use]
    pub const fn is_empty(&self) -> bool {
        self.inner.is_empty()
    }

    /// Grows the buffer to hold at least `capacity` more bytes than it currently holds.
    ///
    /// Note that [`Ipt::get_trace_buffer`] fills from [`TraceBuffer::capacity`], not from
    /// [`TraceBuffer::len`], so calling this on a buffer that still holds a previous trace
    /// over-allocates by that trace's length. [`TraceBuffer::clear`] first to avoid it.
    pub fn reserve(&mut self, capacity: u64) {
        self.inner.reserve(capacity as usize)
    }

    /// Discards the trace data held by this buffer, keeping its allocated capacity.
    pub fn clear(&mut self) {
        self.inner.clear()
    }

    /// 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> {
        let remaining = self.buffer.inner.len().saturating_sub(self.i);
        if remaining < size_of::<TraceRecordHeader>() {
            #[cfg(feature = "log")]
            if remaining != 0 {
                log::warn!(
                    "Trace buffer ends with {remaining} trailing bytes, too few for a {} byte \
                     record header; the response is truncated",
                    size_of::<TraceRecordHeader>()
                );
            }
            return None;
        }

        let header_ptr = self.buffer.inner[self.i..self.i + size_of::<TraceRecordHeader>()]
            .as_ptr()
            .cast::<TraceRecordHeader>();
        // See the alignment note in `Ipt::get_trace_buffer`.
        debug_assert!(header_ptr.is_aligned());
        let header = unsafe { header_ptr.as_ref_unchecked() };

        // `payload_length` comes from the driver and is not implied by the buffer's length: a
        // `STATUS_BUFFER_OVERFLOW` response has records copied only partially.
        let payload_length = header.payload_length as usize;
        let payload_start = self.i + size_of::<TraceRecordHeader>();
        if self.buffer.inner.len() - payload_start < payload_length {
            #[cfg(feature = "log")]
            log::warn!(
                "Trace record for thread {} claims a {payload_length} byte payload but only {} \
                 bytes remain; the response is truncated",
                { header.thread_id },
                self.buffer.inner.len() - payload_start
            );
            return None;
        }

        self.i = payload_start + payload_length;
        let data = &self.buffer.inner[payload_start..self.i];

        Some((header, data))
    }
}

impl<'a> FusedIterator for TraceBufferIter<'a> {}

impl Default for TraceBuffer {
    fn default() -> Self {
        Self::new()
    }
}