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
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
//! Request/response layouts for every `RequestType`, used internally by [`crate::Ipt`]'s methods.
//! Not part of the public API.
//!
//! Every request is a single, fixed 48-byte [`Request`] value — 16-byte header plus a
//! `RequestPayload` union — built through one of `Request`'s constructor functions, one per
//! opcode, named after the `RequestType` variant.
//!
//! One opcode does not fit this shape: `SetPerImageTracingOption` (opcode 4)
//! carries a variable-length trailing image name (and optional second
//! string) that cannot live in a fixed-size struct — see [`SetPerImageTracingOption::raw_request`].

use crate::IptOption;
use crate::option::IptOptionRaw;
use core::slice;
use windows::Win32::Foundation::HANDLE;

/// Format version tag for `GetTraceBuffer`'s `trace_version` field; the only value the driver
/// currently accepts.
pub const TRACE_VERSION: u16 = 1;

/// Sentinel for `num_tries` meaning "unlimited auto-start attempts".
pub const NUM_TRIES_UNLIMITED: u32 = 0xFEDC_BA98;

/// A complete IOCTL request: 16-byte header followed by the opcode-specific payload, always exactly
/// 48 bytes. Build one with the constructor matching the operation you want and write it directly
/// into the IOCTL input buffer.
#[repr(C)]
pub struct Request {
    /// Protocol version. Must be exactly [`Request::VERSION`].
    /// Any other value is rejected with `STATUS_INVALID_DEVICE_REQUEST`.
    version: [u32; 2],
    request_type: RequestType,
    _reserved: u32,
    payload: RequestPayload,
}

impl Request {
    const VERSION: [u32; 2] = [1, 0];

    #[must_use]
    const fn new(request_type: RequestType, payload: RequestPayload) -> Self {
        Self {
            version: Self::VERSION,
            request_type,
            _reserved: 0,
            payload,
        }
    }

    pub const fn get_interface_version() -> Self {
        Self::new(RequestType::GetInterfaceVersion, RequestPayload::empty())
    }

    pub fn get_trace_buffer_size(process_handle: HANDLE) -> Self {
        Self::new(
            RequestType::GetTraceBufferSize,
            GetTraceBuffer::new(process_handle).into(),
        )
    }

    pub fn get_trace_buffer(process_handle: HANDLE) -> Self {
        Self::new(
            RequestType::GetTraceBuffer,
            GetTraceBuffer::new(process_handle).into(),
        )
    }

    pub fn set_system_wide_tracing_option(
        ipt_option: IptOption,
        num_tries: u32,
        ttl_seconds: u32,
    ) -> Self {
        Self::new(
            RequestType::SetSystemWideTracingOption,
            SetSystemWideTracingOption::new(ipt_option, num_tries, ttl_seconds).into(),
        )
    }

    pub fn start_process_trace(process_handle: HANDLE, ipt_option: IptOption) -> Self {
        Self::new(
            RequestType::StartProcessTrace,
            StartProcessTrace::new(process_handle, ipt_option).into(),
        )
    }

    pub fn stop_process_trace(process_handle: HANDLE) -> Self {
        Self::new(RequestType::StopProcessTrace, process_handle.into())
    }

    pub fn pause_thread_trace(thread_handle: HANDLE) -> Self {
        Self::new(RequestType::PauseThreadTrace, thread_handle.into())
    }

    pub fn resume_thread_trace(thread_handle: HANDLE) -> Self {
        Self::new(RequestType::ResumeThreadTrace, thread_handle.into())
    }

    pub fn query_process_trace_configuration(process_handle: HANDLE) -> Self {
        Self::new(
            RequestType::QueryProcessTraceConfiguration,
            process_handle.into(),
        )
    }

    pub const fn query_system_wide_tracing_state() -> Self {
        Self::new(
            RequestType::QuerySystemWideTracingState,
            RequestPayload::empty(),
        )
    }

    pub const fn stop_system_wide_tracing() -> Self {
        Self::new(RequestType::StopSystemWideTracing, RequestPayload::empty())
    }

    pub fn configure_thread_address_filter_range(
        thread_handle: HANDLE,
        range_index: u32,
        mode: AddressFilterMode,
        start_address: u64,
        end_address: u64,
    ) -> Self {
        Self::new(
            RequestType::ConfigureThreadAddressFilterRange,
            ConfigureThreadAddressFilterRange::new(
                thread_handle,
                range_index,
                mode,
                start_address,
                end_address,
            )
            .into(),
        )
    }

    pub fn query_thread_address_filter_range(thread_handle: HANDLE, range_index: u32) -> Self {
        Self::new(
            RequestType::QueryThreadAddressFilterRange,
            QueryThreadAddressFilterRange::new(thread_handle, range_index).into(),
        )
    }

    pub fn query_thread_trace_stop_range_entered(thread_handle: HANDLE) -> Self {
        Self::new(
            RequestType::QueryThreadTraceStopRangeEntered,
            thread_handle.into(),
        )
    }

    pub fn start_process_trace_ex(
        process_handle: HANDLE,
        trace_file_handle: HANDLE,
        ipt_option: IptOption,
    ) -> Self {
        Self::new(
            RequestType::StartProcessTraceEx,
            StartProcessTraceEx::new(process_handle, trace_file_handle, ipt_option).into(),
        )
    }
}

/// Opcode carried in [`Request`]'s header, selecting which operation a request performs.
///
/// Value `11` is intentionally absent: the driver returns `STATUS_INVALID_PARAMETER` if used.
#[repr(u32)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum RequestType {
    GetInterfaceVersion = 0,
    GetTraceBufferSize = 1,
    GetTraceBuffer = 2,
    SetSystemWideTracingOption = 3,
    SetPerImageTracingOption = 4,
    StartProcessTrace = 5,
    StopProcessTrace = 6,
    PauseThreadTrace = 7,
    ResumeThreadTrace = 8,
    QueryProcessTraceConfiguration = 9,
    QuerySystemWideTracingState = 10,
    StopSystemWideTracing = 12,
    ConfigureThreadAddressFilterRange = 13,
    QueryThreadAddressFilterRange = 14,
    QueryThreadTraceStopRangeEntered = 15,
    StartProcessTraceEx = 16,
}

#[repr(C)]
union RequestPayload {
    /// Same for both `GetTraceBufferSize` and `GetTraceBuffer`.
    get_trace_buffer: GetTraceBuffer,
    set_system_wide_tracing_option: SetSystemWideTracingOption,
    start_process_trace: StartProcessTrace,
    start_process_trace_ex: StartProcessTraceEx,
    /// Same for `StopProcessTrace`, `QueryProcessTraceConfiguration`, `PauseThreadTrace`,
    /// `ResumeThreadTrace` and `QueryThreadTraceStopRangeEntered`.
    handle: HANDLE,
    configure_thread_address_filter_range: ConfigureThreadAddressFilterRange,
    query_thread_address_filter_range: QueryThreadAddressFilterRange,
    set_per_image_tracing_option: SetPerImageTracingOption,
    /// Minimum `InputBufferLength`, in bytes, required by every real message
    _pad: [u8; 32],
}

impl RequestPayload {
    const fn empty() -> Self {
        Self { _pad: [0; 32] }
    }
}

impl From<GetTraceBuffer> for RequestPayload {
    fn from(get_trace_buffer: GetTraceBuffer) -> Self {
        Self { get_trace_buffer }
    }
}

impl From<SetSystemWideTracingOption> for RequestPayload {
    fn from(set_system_wide_tracing_option: SetSystemWideTracingOption) -> Self {
        Self {
            set_system_wide_tracing_option,
        }
    }
}

impl From<StartProcessTrace> for RequestPayload {
    fn from(start_process_trace: StartProcessTrace) -> Self {
        Self {
            start_process_trace,
        }
    }
}

impl From<StartProcessTraceEx> for RequestPayload {
    fn from(start_process_trace_ex: StartProcessTraceEx) -> Self {
        Self {
            start_process_trace_ex,
        }
    }
}

impl From<HANDLE> for RequestPayload {
    fn from(handle: HANDLE) -> Self {
        Self { handle }
    }
}

impl From<ConfigureThreadAddressFilterRange> for RequestPayload {
    fn from(configure_thread_address_filter_range: ConfigureThreadAddressFilterRange) -> Self {
        Self {
            configure_thread_address_filter_range,
        }
    }
}

impl From<QueryThreadAddressFilterRange> for RequestPayload {
    fn from(query_thread_address_filter_range: QueryThreadAddressFilterRange) -> Self {
        Self {
            query_thread_address_filter_range,
        }
    }
}

impl From<SetPerImageTracingOption> for RequestPayload {
    fn from(set_per_image_tracing_option: SetPerImageTracingOption) -> Self {
        Self {
            set_per_image_tracing_option,
        }
    }
}

#[repr(C)]
pub union Response {
    pub interface_version: u16,
    pub trace_buffer_size: TraceBufferSizeResponse,
    /// `PauseThreadTrace`/`ResumeThreadTrace` (opcodes 7/8).
    pub pause_state: PreviouslyEnabledResponse,
    /// `QueryProcessTraceConfiguration` (opcode 9).
    pub trace_config: IptOptionResponse,
    /// `QuerySystemWideTracingState` (opcode 10).
    pub core_tracing_state: SystemWideTracingStateResponse,
    pub address_filter_range: AddressFilterRangeResponse,
    pub trace_stop_entered: TraceStopRangeEnteredResponse,
    /// Minimum `OutputBufferLength` required by every message.
    _pad: [u8; 24],
}

impl Response {
    /// The raw response bytes, for inspecting a field before decoding it into a type that cannot
    /// represent every bit pattern (e.g. [`AddressFilterMode`]).
    pub(crate) const fn as_bytes(&self) -> &[u8] {
        // SAFETY: `_pad` is the union's largest variant and every variant is made of integers and
        // `#[repr(u32)]` enums, so any of them is valid to read back as bytes.
        unsafe { &self._pad }
    }
}

#[repr(C)]
#[derive(Debug, Clone, Copy)]
pub struct TraceBufferSizeResponse {
    /// Echoed [`GetTraceBuffer::trace_version`].
    pub trace_version: u16,
    _padding: [u8; 6],
    /// `8` (opcode 2's own [`GetTraceResponseHeader`]) `+ Σ(28 + PayloadLength)` over every traced
    /// thread.
    pub trace_size: u64,
}

/// Shared payload for `GetTraceBufferSize` and `GetTraceBuffer`
#[repr(C)]
#[derive(Debug, Clone, Copy)]
struct GetTraceBuffer {
    trace_version: u16,
    _padding: [u8; 6],
    process_handle: HANDLE,
}

impl GetTraceBuffer {
    pub const fn new(process_handle: HANDLE) -> Self {
        Self {
            trace_version: TRACE_VERSION,
            _padding: [0; 6],
            process_handle,
        }
    }
}

/// Fixed 8-byte header at the start of a `GetTraceBuffer` response, followed by `bytes_written`
/// bytes made up of zero or more back-to-back [`TraceRecordHeader`] + raw packet payload records,
/// one per thread.
#[repr(C)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct GetTraceResponseHeader {
    /// Echoed `GetTraceBuffer::trace_version`, always [`TRACE_VERSION`].
    pub trace_version: u16,
    /// Version tag of the response format itself, separate from `trace_version`. Always
    /// [`GetTraceResponseHeader::RESPONSE_VERSION_EXPECTED`].
    pub response_version: u16,
    /// Total payload bytes actually copied after this header (i.e. the combined size of all
    /// [`TraceRecordHeader`]s and their packet data that follow).
    pub bytes_written: u32,
}

impl GetTraceResponseHeader {
    #[cfg(feature = "log")]
    pub const RESPONSE_VERSION_EXPECTED: u16 = 1;
}

/// Per-thread record header inside a `GetTraceBuffer` response, immediately followed by
/// `payload_length` bytes of raw Intel PT packets for that thread.
#[repr(C, packed(4))]
#[derive(Debug)]
#[non_exhaustive]
pub struct TraceRecordHeader {
    /// ID of the thread this record's packets came from.
    pub thread_id: u64,
    /// The owning trace's [`IptOption::timing_mode`](IptOption::timing_mode)
    /// (bits 4:7 of `IptOption`; `0`=off, `1`=MTC, `2`=MTC+CYC).
    pub timing_settings: u32,
    /// The owning trace's [`IptOption::mtc_freq`](IptOption::mtc_freq) (bits 8:11 of `IptOption`).
    pub mtc_frequency: u32,
    /// TSC/core-crystal-clock ratio (`CPUID.15H`), for host-side time correlation.
    pub frequency_to_tsc_ratio: u32,
    /// Current write offset at the moment this record was captured.
    pub output_offset: u32,
    /// Size in bytes of the buffer for PT packets immediately following this header.
    pub payload_length: u32,
}

#[repr(C)]
#[derive(Debug, Clone, Copy)]
struct SetSystemWideTracingOption {
    ipt_option: IptOptionRaw,
    num_tries: u32,
    ttl_seconds: u32,
}

impl SetSystemWideTracingOption {
    pub fn new(ipt_option: IptOption, num_tries: u32, ttl_seconds: u32) -> Self {
        Self {
            ipt_option: ipt_option.into(),
            num_tries,
            ttl_seconds,
        }
    }
}

/// Fixed-size header of the request for `SetPerImageTracingOption`.
/// Doesn't fit the [`Request`] pattern used by every other opcode: this message has a
/// variable-length tail that no fixed-size Rust struct can represent — `image_name_length`
/// bytes of UTF-16 image name, immediately followed by `second_string_length` bytes of a second
/// UTF-16 string (when present).
#[repr(C, packed(4))]
#[derive(Debug, Clone, Copy)]
pub struct SetPerImageTracingOption {
    /// `ring_filter` must be one of the per-image values (like [`crate::RingFilter::User`]).
    ipt_option: IptOptionRaw,
    num_tries: u32,
    ttl_seconds: u32,
    /// Byte length of the image name that follows the header. Must be even and non-zero.
    image_name_length: u16,
    /// Byte length of an optional second string following the image name. Must be even; `0` if
    /// unused.
    second_string_length: u16,
}

impl SetPerImageTracingOption {
    /// Serializes a complete opcode-4 request.
    ///
    /// # Panics
    /// Panics if `image_name` is empty, if either string is longer than `u16::MAX` bytes.
    pub fn raw_request(
        ipt_option: IptOption,
        num_tries: u32,
        ttl_seconds: u32,
        image_name: &[u16],
        second_string: Option<&[u16]>,
    ) -> Vec<u8> {
        let header_size = size_of::<Request>() - size_of::<RequestPayload>() + size_of::<Self>();
        let mut out = Vec::new();

        assert!(!image_name.is_empty(), "image_name must not be empty");
        let image_name_length = u16::try_from(image_name.len() * 2)
            .expect("image_name too long to encode as a u16 byte length");
        let second_string_length = second_string
            .map(|s| {
                u16::try_from(s.len() * 2)
                    .expect("second_string length too long to encode as a u16 byte length")
            })
            .unwrap_or(0);

        let request_payload = Self {
            ipt_option: ipt_option.into(),
            num_tries,
            ttl_seconds,
            image_name_length,
            second_string_length,
        };
        let request = Request {
            version: Request::VERSION,
            request_type: RequestType::SetPerImageTracingOption,
            _reserved: 0,
            payload: request_payload.into(),
        };

        out.extend_from_slice(unsafe {
            slice::from_raw_parts((&raw const request).cast(), header_size)
        });

        out.extend(image_name.iter().flat_map(|c| c.to_ne_bytes()));
        out.extend(
            second_string
                .unwrap_or(&[])
                .iter()
                .flat_map(|c| c.to_ne_bytes()),
        );

        // The driver rejects any request shorter than a fixed-size [`Request`] before it even
        // looks at the opcode, so a short image name has to be padded up to that floor. Both
        // strings are located from the header's explicit length fields, so the tail is ignored.
        out.extend_from_slice(&vec![0; size_of::<Request>().saturating_sub(out.len())]);

        out
    }
}

#[repr(C)]
#[derive(Debug, Clone, Copy)]
struct StartProcessTrace {
    process_handle: HANDLE,
    ipt_option: IptOptionRaw,
}

impl StartProcessTrace {
    pub fn new(process_handle: HANDLE, ipt_option: IptOption) -> Self {
        Self {
            process_handle,
            ipt_option: ipt_option.into(),
        }
    }
}

#[repr(C)]
#[derive(Debug, Clone, Copy)]
struct StartProcessTraceEx {
    process_handle: HANDLE,
    trace_file_handle: HANDLE,
    ipt_option: IptOptionRaw,
}

impl StartProcessTraceEx {
    pub fn new(process_handle: HANDLE, trace_file_handle: HANDLE, ipt_option: IptOption) -> Self {
        Self {
            process_handle,
            trace_file_handle,
            ipt_option: ipt_option.into(),
        }
    }
}

/// Response to `PauseThreadTrace` and `ResumeThreadTrace`: the thread's trace-enable state
/// *before* this call took effect.
#[repr(C)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct PreviouslyEnabledResponse {
    /// `IA32_RTIT_CTL.TraceEn` (MSR `0x570` bit 0) as it was before the call: non-zero if the
    /// thread was actively tracing, i.e. *not* paused.
    pub previously_enabled: u8,
}

/// Response to `QueryProcessTraceConfiguration`.
#[repr(C)]
#[derive(Debug, Clone, Copy)]
pub struct IptOptionResponse {
    /// The exact option word the process was started with. Only written once the driver has found
    /// a live process context: a process that is not currently being traced fails the call itself
    /// with `STATUS_UNSUCCESSFUL` instead.
    pub ipt_option: IptOptionRaw,
}

#[repr(C)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct SystemWideTracingStateResponse {
    /// An internal handle/state value from the global core-tracing control block: non-zero while
    /// system-wide tracing is active, `0` otherwise.
    pub state: u64,
}

/// One IP-filtering range's mode, as used by the `ConfigureThreadAddressFilterRange` request's
/// `mode`.
#[repr(u32)]
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AddressFilterMode {
    /// Range is not active.
    Disabled = 0,
    /// The CPU only emits packets while `RIP` is inside this range
    /// (combined with any other enabled filter ranges via OR).
    Filter = 1,
    /// Branching execution into this range hardware-stops tracing
    TraceStop = 2,
}

impl AddressFilterMode {
    /// Decodes a raw `mode` word as the driver reports it, returning [`None`] for the reserved
    /// `IA32_RTIT_CTL.ADDRn_CFG` encodings `3..=15`.
    ///
    /// `pub(crate)` because [`AddressFilterMode`] is re-exported from the crate root, so an
    /// inherent `pub fn` would become public API.
    pub(crate) const fn from_repr(repr: u32) -> Option<Self> {
        match repr {
            0 => Some(Self::Disabled),
            1 => Some(Self::Filter),
            2 => Some(Self::TraceStop),
            _ => None,
        }
    }
}

#[repr(C)]
#[derive(Debug, Clone, Copy)]
struct ConfigureThreadAddressFilterRange {
    thread_handle: HANDLE,
    range_index: u32,
    mode: AddressFilterMode,
    /// Inclusive start address.
    start_address: u64,
    /// Inclusive end address. Must be `>= start_address`.
    end_address: u64,
}

impl ConfigureThreadAddressFilterRange {
    pub const fn new(
        thread_handle: HANDLE,
        range_index: u32,
        mode: AddressFilterMode,
        start_address: u64,
        end_address: u64,
    ) -> Self {
        Self {
            thread_handle,
            range_index,
            mode,
            start_address,
            end_address,
        }
    }
}

#[repr(C)]
#[derive(Debug, Clone, Copy)]
struct QueryThreadAddressFilterRange {
    thread_handle: HANDLE,
    range_index: u32,
}

impl QueryThreadAddressFilterRange {
    pub const fn new(thread_handle: HANDLE, range_index: u32) -> Self {
        Self {
            thread_handle,
            range_index,
        }
    }
}

/// Response to `QueryThreadAddressFilterRange`.
#[repr(C)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct AddressFilterRangeResponse {
    /// This filter mode
    pub mode: AddressFilterMode,
    /// Inclusive start address.
    pub start_address: u64,
    /// Inclusive end address.
    pub end_address: u64,
}

/// Response to `QueryThreadTraceStopRangeEntered`.
#[repr(C)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct TraceStopRangeEnteredResponse {
    /// Non-zero if the thread's instruction pointer has entered a configured
    /// `AddressFilterMode::TraceStop` range since tracing began.
    pub entered: u8,
}

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

    #[test]
    fn new_sets_version_and_zeroes_reserved() {
        let request = Request::new(RequestType::PauseThreadTrace, RequestPayload::empty());
        assert_eq!(request.version, Request::VERSION);
        assert_eq!(request.request_type, RequestType::PauseThreadTrace);
        assert_eq!(request._reserved, 0);
    }

    #[test]
    fn message_sizes_match_driver_minimums() {
        // The driver rejects a request or response buffer smaller than these with
        // STATUS_INVALID_PARAMETER.
        assert_eq!(size_of::<Request>(), 0x30);
        assert_eq!(size_of::<Response>(), 0x18);
    }

    #[test]
    fn trace_record_header_size() {
        assert_eq!(size_of::<TraceRecordHeader>(), 28);
    }

    #[test]
    fn get_trace_buffer_layout() {
        assert_eq!(offset_of!(GetTraceBuffer, trace_version), 0);
        assert_eq!(offset_of!(GetTraceBuffer, process_handle), 8);
    }

    #[test]
    fn get_trace_buffer_size_response_layout() {
        assert_eq!(offset_of!(TraceBufferSizeResponse, trace_version), 0);
        assert_eq!(offset_of!(TraceBufferSizeResponse, trace_size), 8);
    }

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

    #[test]
    fn set_system_wide_tracing_option_layout() {
        assert_eq!(offset_of!(SetSystemWideTracingOption, ipt_option), 0);
        assert_eq!(offset_of!(SetSystemWideTracingOption, num_tries), 8);
        assert_eq!(offset_of!(SetSystemWideTracingOption, ttl_seconds), 12);
    }

    #[test]
    fn set_per_image_tracing_option_layout() {
        assert_eq!(offset_of!(SetPerImageTracingOption, ipt_option), 0);
        assert_eq!(offset_of!(SetPerImageTracingOption, num_tries), 8);
        assert_eq!(offset_of!(SetPerImageTracingOption, ttl_seconds), 12);
        assert_eq!(offset_of!(SetPerImageTracingOption, image_name_length), 16);
        assert_eq!(
            offset_of!(SetPerImageTracingOption, second_string_length),
            18
        );
    }

    #[test]
    fn set_per_image_tracing_option_write_request() {
        let image_name: [u16; 3] = [b'a' as u16, b'b' as u16, b'c' as u16];
        let second_string: [u16; 2] = [b'x' as u16, b'y' as u16];
        let ipt_option = IptOption::default();
        let raw_option = IptOptionRaw::from(ipt_option).raw_value();

        let out = SetPerImageTracingOption::raw_request(
            ipt_option,
            NUM_TRIES_UNLIMITED,
            42,
            &image_name,
            Some(&second_string),
        );

        assert!(out.len() >= 0x30);
        assert_eq!(u32::from_ne_bytes(out[0..4].try_into().unwrap()), 1); // version.0
        assert_eq!(u32::from_ne_bytes(out[4..8].try_into().unwrap()), 0); // version.1
        assert_eq!(u32::from_ne_bytes(out[8..12].try_into().unwrap()), 4); // SetPerImageTracingOption opcode
        assert_eq!(u32::from_ne_bytes(out[12..16].try_into().unwrap()), 0); // reserved
        assert_eq!(
            u64::from_ne_bytes(out[16..24].try_into().unwrap()),
            raw_option
        );
        assert_eq!(
            u32::from_ne_bytes(out[24..28].try_into().unwrap()),
            NUM_TRIES_UNLIMITED
        );
        assert_eq!(u32::from_ne_bytes(out[28..32].try_into().unwrap()), 42);
        assert_eq!(u16::from_ne_bytes(out[32..34].try_into().unwrap()), 6);
        assert_eq!(u16::from_ne_bytes(out[34..36].try_into().unwrap()), 4);
        assert_eq!(&out[36..42], [b'a', 0, b'b', 0, b'c', 0]);
        assert_eq!(&out[42..46], [b'x', 0, b'y', 0]);
    }

    #[test]
    fn start_process_trace_layout() {
        assert_eq!(offset_of!(StartProcessTrace, process_handle), 0);
        assert_eq!(offset_of!(StartProcessTrace, ipt_option), 8);
    }

    #[test]
    fn start_process_trace_ex_layout() {
        assert_eq!(offset_of!(StartProcessTraceEx, process_handle), 0);
        assert_eq!(offset_of!(StartProcessTraceEx, trace_file_handle), 8);
        assert_eq!(offset_of!(StartProcessTraceEx, ipt_option), 16);
    }

    #[test]
    fn configure_thread_address_filter_range_layout() {
        assert_eq!(
            offset_of!(ConfigureThreadAddressFilterRange, thread_handle),
            0
        );
        assert_eq!(
            offset_of!(ConfigureThreadAddressFilterRange, range_index),
            8
        );
        assert_eq!(offset_of!(ConfigureThreadAddressFilterRange, mode), 12);
        assert_eq!(
            offset_of!(ConfigureThreadAddressFilterRange, start_address),
            16
        );
        assert_eq!(
            offset_of!(ConfigureThreadAddressFilterRange, end_address),
            24
        );
        assert_eq!(size_of::<ConfigureThreadAddressFilterRange>(), 32);
    }

    #[test]
    fn query_thread_address_filter_range_layout() {
        assert_eq!(offset_of!(QueryThreadAddressFilterRange, thread_handle), 0);
        assert_eq!(offset_of!(QueryThreadAddressFilterRange, range_index), 8);
    }

    #[test]
    fn address_filter_range_response_layout() {
        assert_eq!(offset_of!(AddressFilterRangeResponse, mode), 0);
        assert_eq!(offset_of!(AddressFilterRangeResponse, start_address), 8);
        assert_eq!(offset_of!(AddressFilterRangeResponse, end_address), 16);
    }
}