wdext 0.1.0

A DbgEng wrapper framework
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
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
// SPDX-FileCopyrightText: 2026 takubokudori
// SPDX-License-Identifier: MIT OR Apache-2.0
//! IDebugClient
use crate::dbgeng::{callbacks::*, *};
use windows::core::Interface;
use windows_core::{PCSTR, PCWSTR, PSTR, PWSTR};
use windy::{ACPStr, ACPString, WStr, WString};
use windy_macros::{acpstr, wstr};

impl_debug_interface!(DebugClient, DebugClientRef, IDebugClient7, IDebugClient);

enum_flags! {
    pub enum DebugAttachKernelFlags: u32 {
        KernelConnection = DEBUG_ATTACH_KERNEL_CONNECTION,
        ExdiDriver = DEBUG_ATTACH_EXDI_DRIVER,
    }
}

bitflags::bitflags! {
    #[derive(Clone, Copy, Eq, PartialEq)]
    pub struct DebugAttachProcessFlags: u32 {
        const Default = DEBUG_ATTACH_DEFAULT;
        const Noninvasive = DEBUG_ATTACH_NONINVASIVE;
        const Existing = DEBUG_ATTACH_EXISTING;
        const NoninvasiveNoSuspend = DEBUG_ATTACH_NONINVASIVE_NO_SUSPEND;
        const InvasiveNoInitialBreak = DEBUG_ATTACH_INVASIVE_NO_INITIAL_BREAK;
        const InvasiveResumeProcess = DEBUG_ATTACH_INVASIVE_RESUME_PROCESS;
    }
}

bitflags::bitflags! {
    #[derive(Clone, Copy, Eq, PartialEq)]
    pub struct DebugConnectSessionFlags: u32 {
        const NoVersion = DEBUG_CONNECT_SESSION_NO_VERSION;
        const NoAnnounce = DEBUG_CONNECT_SESSION_NO_ANNOUNCE;
    }
}

pub const DEBUG_CREATE_PROCESS_NO_DEBUG_HEAP: u32 = 0x400;
pub const DEBUG_CREATE_PROCESS_THROUGH_RTL: u32 = 0x10000;
pub const DEBUG_PROCESS: u32 = 0x1;
pub const DEBUG_ONLY_THIS_PROCESS: u32 = 0x2;

bitflags::bitflags! {
    #[derive(Clone, Copy, Eq, PartialEq)]
    pub struct DebugCreateProcessCreateFlags: u32 {
        const NoDebugHeap = DEBUG_CREATE_PROCESS_NO_DEBUG_HEAP;
        const ThroughRtl = DEBUG_CREATE_PROCESS_THROUGH_RTL;
        const DebugProcess = DEBUG_PROCESS;
        const OnlyThisProcess = DEBUG_ONLY_THIS_PROCESS;
    }
}

bitflags::bitflags! {
    #[derive(Clone, Copy, Eq, PartialEq)]
    pub struct DebugCreateProcessEngCreateFlags: u32 {
        const InheritHandles = DEBUG_ECREATE_PROCESS_INHERIT_HANDLES;
        const UseVerifierFlags = DEBUG_ECREATE_PROCESS_USE_VERIFIER_FLAGS;
        const UseImplicitCommandLine = DEBUG_ECREATE_PROCESS_USE_IMPLICIT_COMMAND_LINE;
    }
}

enum_flags! {
    pub enum DebugEndFlags: u32 {
        Passive = DEBUG_END_PASSIVE,
        ActiveTerminate = DEBUG_END_ACTIVE_TERMINATE,
        ActiveDetach = DEBUG_END_ACTIVE_DETACH,
        Reentrant = DEBUG_END_REENTRANT,
        EndDisconnect = DEBUG_END_DISCONNECT,
    }
}

bitflags::bitflags! {
    #[derive(Clone, Copy, Eq, PartialEq)]
    pub struct DebugServersFlags: u32 {
        const Debugger = DEBUG_SERVERS_DEBUGGER;
        const Process = DEBUG_SERVERS_PROCESS;
    }
}

enum_flags! {
    pub enum DebugClassFlags: u32 {
        Uninitialized = DEBUG_CLASS_UNINITIALIZED,
        Kernel = DEBUG_CLASS_KERNEL,
        UserWindows = DEBUG_CLASS_USER_WINDOWS,
        ImageFile = DEBUG_CLASS_IMAGE_FILE,
    }
}

enum_flags! {
    pub enum DebugDumpFlags: u32 {
        Small = DEBUG_DUMP_SMALL,
        Default = DEBUG_DUMP_DEFAULT,
        Full = DEBUG_DUMP_FULL,
        ImageFile = DEBUG_DUMP_IMAGE_FILE,
        TraceLog = DEBUG_DUMP_TRACE_LOG,
        WindowsCe = DEBUG_DUMP_WINDOWS_CE,
        Active = DEBUG_DUMP_ACTIVE,
    }
}

enum_flags! {
    pub enum DebugDumpFileType: u32 {
        Base = DEBUG_DUMP_FILE_BASE,
        PageFileDump = DEBUG_DUMP_FILE_PAGE_FILE_DUMP,
    }
}

bitflags::bitflags! {
    #[derive(Clone, Copy, Eq, PartialEq)]
    pub struct DebugFormatFlags: u32 {
        const WriteCab = DEBUG_FORMAT_WRITE_CAB;
        const WriteCabSecondaryFiles = DEBUG_FORMAT_CAB_SECONDARY_FILES;
        const NoOverwrite = DEBUG_FORMAT_NO_OVERWRITE;
        const UserSmallFullMemory = DEBUG_FORMAT_USER_SMALL_FULL_MEMORY;
        const UserSmallHandleData = DEBUG_FORMAT_USER_SMALL_HANDLE_DATA;
        const UserSmallUnloadedModules = DEBUG_FORMAT_USER_SMALL_UNLOADED_MODULES;
        const UserSmallIndirectMemory = DEBUG_FORMAT_USER_SMALL_INDIRECT_MEMORY;
        const UserSmallDataSegments = DEBUG_FORMAT_USER_SMALL_DATA_SEGMENTS;
        const UserSmallFilterMemory = DEBUG_FORMAT_USER_SMALL_FILTER_MEMORY;
        const UserSmallFilterPaths = DEBUG_FORMAT_USER_SMALL_FILTER_PATHS;
        const UserSmallProcessThreadData = DEBUG_FORMAT_USER_SMALL_PROCESS_THREAD_DATA;
        const UserSmallPrivateReadWriteMemory = DEBUG_FORMAT_USER_SMALL_PRIVATE_READ_WRITE_MEMORY;
        const UserSmallNoOptionalData = DEBUG_FORMAT_USER_SMALL_NO_OPTIONAL_DATA;
        const UserSmallFullMemoryInfo = DEBUG_FORMAT_USER_SMALL_FULL_MEMORY_INFO;
        const UserSmallThreadInfo = DEBUG_FORMAT_USER_SMALL_THREAD_INFO;
        const UserSmallCodeSegments = DEBUG_FORMAT_USER_SMALL_CODE_SEGMENTS;
    }
}

#[repr(transparent)]
#[derive(Debug, Clone)]
pub struct DebugCreateProcessOptions(pub DEBUG_CREATE_PROCESS_OPTIONS);

impl DebugCreateProcessOptions {
    pub fn new(
        create_flags: DebugCreateProcessCreateFlags,
        eng_create_flags: DebugCreateProcessEngCreateFlags,
        verifier_flags: u32,
    ) -> Self {
        Self(DEBUG_CREATE_PROCESS_OPTIONS {
            CreateFlags: create_flags.bits(),
            EngCreateFlags: eng_create_flags.bits(),
            VerifierFlags: verifier_flags,
            Reserved: 0,
        })
    }

    pub fn create_flags(&self) -> DebugCreateProcessCreateFlags {
        DebugCreateProcessCreateFlags::from_bits_retain(self.0.CreateFlags)
    }

    pub fn eng_create_flags(&self) -> DebugCreateProcessEngCreateFlags {
        DebugCreateProcessEngCreateFlags::from_bits_retain(
            self.0.EngCreateFlags,
        )
    }

    pub fn verifier_flags(&self) -> u32 { self.0.VerifierFlags }

    pub fn reserved(&self) -> u32 { self.0.Reserved }
}

impl From<DEBUG_CREATE_PROCESS_OPTIONS> for DebugCreateProcessOptions {
    fn from(value: DEBUG_CREATE_PROCESS_OPTIONS) -> Self { Self(value) }
}

#[derive(Debug, Clone, Copy, Eq, PartialEq, Hash)]
pub enum ProcessServer {
    /// Local process
    Local,
    /// Process server
    Server(u64),
}

impl From<ProcessServer> for u64 {
    fn from(value: ProcessServer) -> Self {
        match value {
            ProcessServer::Local => 0,
            ProcessServer::Server(x) => x,
        }
    }
}

impl From<u64> for ProcessServer {
    fn from(value: u64) -> Self {
        match value {
            0 => ProcessServer::Local,
            x => ProcessServer::Server(x),
        }
    }
}

#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
pub enum KernelConnectionOptions {
    Resync,
    CycleSpeed,
}

impl KernelConnectionOptions {
    pub fn get_str(&self) -> &str {
        match self {
            KernelConnectionOptions::Resync => "resync",
            KernelConnectionOptions::CycleSpeed => "cycle_speed",
        }
    }

    pub(crate) fn get_astr(&self) -> &ACPStr {
        match self {
            KernelConnectionOptions::Resync => acpstr!("resync"),
            KernelConnectionOptions::CycleSpeed => acpstr!("cycle_speed"),
        }
    }

    pub(crate) fn get_wstr(&self) -> &WStr {
        match self {
            KernelConnectionOptions::Resync => wstr!("resync"),
            KernelConnectionOptions::CycleSpeed => wstr!("cycle_speed"),
        }
    }
}

impl DebugClient {
    pub fn attach_kernel(
        &self,
        flags: DebugAttachKernelFlags,
        connect_options: impl AsRef<ACPStr>,
    ) -> WinResult<()> {
        unsafe { self.0.AttachKernel(flags as u32, pca!(connect_options)) }
    }

    pub fn get_kernel_connection_options(&self) -> WinResult<ACPString> {
        unsafe {
            astring_with_capacity(32, |v, s| {
                vcall!(
                    self,
                    GetKernelConnectionOptions,
                    pa!(v),
                    v.len().try_into().unwrap(),
                    s
                )
            })
        }
    }

    pub fn set_kernel_connection_options(
        &self,
        options: KernelConnectionOptions,
    ) -> WinResult<()> {
        unsafe {
            self.0.SetKernelConnectionOptions(PCSTR(
                options.get_astr().as_u8_ptr(),
            ))
        }
    }

    pub fn start_process_server(
        &self,
        flags: DebugClassFlags,
        options: impl AsRef<ACPStr>,
        /* reserved: Option<*mut c_void>, */
    ) -> WinResult<()> {
        unsafe { self.0.StartProcessServer(flags as u32, pca!(options), None) }
    }

    pub fn connect_process_server(
        &self,
        remote_options: impl AsRef<ACPStr>,
    ) -> WinResult<ProcessServer> {
        unsafe { Ok(self.0.ConnectProcessServer(pca!(remote_options))?.into()) }
    }

    pub fn disconnect_process_server(
        &self,
        server: ProcessServer,
    ) -> WinResult<()> {
        unsafe { self.0.DisconnectProcessServer(server.into()) }
    }

    // GetRunningProcessSystemIds

    // GetRunningProcessSystemIdByExecutableName

    // GetRunningProcessDescription

    pub fn attach_process(
        &self,
        server: ProcessServer,
        process_id: impl Into<ProcessId>,
        attach_flags: DebugAttachProcessFlags,
    ) -> WinResult<()> {
        unsafe {
            self.0.AttachProcess(
                server.into(),
                process_id.into().0,
                attach_flags.bits(),
            )
        }
    }

    pub fn create_process(
        &self,
        server: ProcessServer,
        command_line: impl AsRef<ACPStr>,
        create_flags: DebugCreateProcessCreateFlags,
    ) -> WinResult<()> {
        // DbgEng takes PSTR/PWSTR for process command lines and is allowed to
        // modify the supplied buffer. Never hand it memory borrowed from an
        // immutable string. The temporary Vec is intentionally not
        // interpreted as an ACP string after the native call returns.
        let mut command_line =
            command_line.as_ref().as_bytes_with_nul().to_vec();
        unsafe {
            self.0.CreateProcessA(
                server.into(),
                PSTR(command_line.as_mut_ptr()),
                create_flags.bits(),
            )
        }
    }

    pub fn create_process_and_attach(
        &self,
        server: ProcessServer,
        command_line: impl AsRef<ACPStr>,
        create_flags: DebugCreateProcessCreateFlags,
        process_id: Option<u32>,
        attach_flags: DebugAttachProcessFlags,
    ) -> WinResult<()> {
        let mut command_line =
            command_line.as_ref().as_bytes_with_nul().to_vec();
        unsafe {
            self.0.CreateProcessAndAttach(
                server.into(),
                PSTR(command_line.as_mut_ptr()),
                create_flags.bits(),
                process_id.unwrap_or(0),
                attach_flags.bits(),
            )
        }
    }

    pub fn get_process_options(&self) -> WinResult<DebugProcessFlags> {
        unsafe {
            Ok(DebugProcessFlags::from_bits_retain(
                self.0.GetProcessOptions()?,
            ))
        }
    }

    pub fn add_process_options(
        &self,
        options: DebugProcessFlags,
    ) -> WinResult<()> {
        unsafe { self.0.AddProcessOptions(options.bits()) }
    }

    pub fn remove_process_options(
        &self,
        options: DebugProcessFlags,
    ) -> WinResult<()> {
        unsafe { self.0.RemoveProcessOptions(options.bits()) }
    }

    pub fn set_process_options(
        &self,
        options: DebugProcessFlags,
    ) -> WinResult<()> {
        unsafe { self.0.SetProcessOptions(options.bits()) }
    }

    pub fn open_dump_file(
        &self,
        dump_file: impl AsRef<ACPStr>,
    ) -> WinResult<()> {
        unsafe { self.0.OpenDumpFile(pca!(dump_file)) }
    }

    pub fn write_dump_file(
        &self,
        dump_file: impl AsRef<ACPStr>,
        qualifier: DebugDumpFlags,
    ) -> WinResult<()> {
        unsafe { self.0.WriteDumpFile(pca!(dump_file), qualifier as u32) }
    }

    pub fn connect_session(
        &self,
        flags: DebugConnectSessionFlags,
        history_limit: u32,
    ) -> WinResult<()> {
        unsafe { self.0.ConnectSession(flags.bits(), history_limit) }
    }

    pub fn start_server(&self, options: impl AsRef<ACPStr>) -> WinResult<()> {
        unsafe { self.0.StartServer(pca!(options)) }
    }

    pub fn output_servers(
        &self,
        output_control: DebugOutctlFlags,
        machine: impl AsRef<ACPStr>,
        flags: DebugServersFlags,
    ) -> WinResult<()> {
        unsafe {
            self.0.OutputServers(
                output_control.bits(),
                pca!(machine),
                flags.bits(),
            )
        }
    }

    pub fn terminate_processes(&self) -> WinResult<()> {
        unsafe { self.0.TerminateProcesses() }
    }

    pub fn detach_processes(&self) -> WinResult<()> {
        unsafe { self.0.DetachProcesses() }
    }

    pub fn end_session(&self, flags: DebugEndFlags) -> WinResult<()> {
        unsafe { self.0.EndSession(flags as u32) }
    }

    pub fn get_exit_code(&self) -> WinResult<(u32, bool)> {
        let mut code = 0;
        unsafe {
            let b = hr!(vcall!(self, GetExitCode, &mut code))?;
            Ok((code, b))
        }
    }

    pub fn dispatch_callbacks(&self, timeout: u32) -> WinResult<bool> {
        unsafe { hr!(vcall!(self, DispatchCallbacks, timeout)) }
    }

    pub fn exit_dispatch(&self, client: &DebugClient) -> WinResult<()> {
        unsafe {
            self.0.ExitDispatch(IDebugClient::from_raw_borrowed(
                &client.0.as_raw(),
            ))
        }
    }

    pub fn create_client(&self) -> WinResult<Self> {
        unsafe { Self::from_interface(&self.0.CreateClient()?) }
    }

    pub fn get_input_callbacks(
        &self,
    ) -> WinResult<Option<DebugInputCallbacks>> {
        unsafe {
            match self.0.GetInputCallbacks() {
                Ok(x) => Ok(Some(x.into())),
                Err(x) if x.code() == S_OK => Ok(None),
                Err(x) => Err(x),
            }
        }
    }

    pub fn set_input_callbacks(
        &self,
        callbacks: Option<DebugInputCallbacksAdapter>,
    ) -> WinResult<()> {
        unsafe { self.0.SetInputCallbacks(callbacks.map(Into::into).as_ref()) }
    }

    pub(crate) unsafe fn _set_input_callbacks_raw(
        &self,
        callbacks: Option<IDebugInputCallbacks>,
    ) -> WinResult<()> {
        unsafe { self.0.SetInputCallbacks(callbacks.as_ref()) }
    }

    pub(crate) fn _get_output_callbacks_raw(
        &self,
    ) -> WinResult<Option<IDebugOutputCallbacks>> {
        unsafe {
            match self.0.GetOutputCallbacks() {
                Ok(x) => Ok(Some(x)),
                Err(x) if x.code() == S_OK => Ok(None),
                Err(x) => Err(x),
            }
        }
    }

    /// Returns the registered output callbacks when they expose
    /// `IDebugOutputCallbacks2`.
    ///
    /// DbgEng may return an `IDebugOutputCallbacks` conversion thunk when a
    /// legacy or wide callback is installed. Such a thunk is not required to
    /// implement `IDebugOutputCallbacks2`, so callers that only need callback
    /// identity/restoration must use the raw internal getter instead.
    pub fn get_output_callbacks(
        &self,
    ) -> WinResult<Option<DebugOutputCallbacks>> {
        self._get_output_callbacks_raw()?
            .map(|callbacks| DebugOutputCallbacks::from_interface(&callbacks))
            .transpose()
    }

    pub fn set_output_callbacks(
        &self,
        callbacks: Option<DebugOutputCallbacksAdapter>,
    ) -> WinResult<()> {
        unsafe {
            self.0
                .SetOutputCallbacks(callbacks.map(Into::into).as_ref())
        }
    }

    pub(crate) unsafe fn _set_output_callbacks_raw(
        &self,
        callbacks: Option<IDebugOutputCallbacks>,
    ) -> WinResult<()> {
        unsafe { self.0.SetOutputCallbacks(callbacks.as_ref()) }
    }

    pub fn get_output_mask(&self) -> WinResult<DebugOutputFlags> {
        unsafe {
            Ok(DebugOutputFlags::from_bits_retain(self.0.GetOutputMask()?))
        }
    }

    pub fn set_output_mask(&self, mask: DebugOutputFlags) -> WinResult<()> {
        unsafe { self.0.SetOutputMask(mask.bits()) }
    }

    pub fn get_other_output_mask(
        &self,
        client: &DebugClient,
    ) -> WinResult<DebugOutputFlags> {
        unsafe {
            Ok(DebugOutputFlags::from_bits_retain(
                self.0.GetOtherOutputMask(IDebugClient::from_raw_borrowed(
                    &client.0.as_raw(),
                ))?,
            ))
        }
    }

    pub fn set_other_output_mask(
        &self,
        client: &DebugClient,
        mask: DebugOutputFlags,
    ) -> WinResult<()> {
        unsafe {
            self.0.SetOtherOutputMask(
                IDebugClient::from_raw_borrowed(&client.0.as_raw()),
                mask.bits(),
            )
        }
    }

    pub fn get_output_width(&self) -> WinResult<u32> {
        unsafe { self.0.GetOutputWidth() }
    }

    pub fn set_output_width(&self, width: u32) -> WinResult<()> {
        unsafe { self.0.SetOutputWidth(width) }
    }

    pub fn get_output_line_prefix(&self) -> WinResult<ACPString> {
        unsafe {
            astring_with_capacity(32, |v, s| {
                vcall!(
                    self,
                    GetOutputLinePrefix,
                    pa!(v),
                    v.len().try_into().unwrap(),
                    s
                )
            })
        }
    }

    pub fn set_output_line_prefix(
        &self,
        prefix: impl AsRef<ACPStr>,
    ) -> WinResult<()> {
        unsafe { self.0.SetOutputLinePrefix(pca!(prefix)) }
    }

    pub fn get_identity(&self) -> WinResult<ACPString> {
        unsafe {
            astring_with_capacity(32, |v, s| {
                vcall!(
                    self,
                    GetIdentity,
                    pa!(v),
                    v.len().try_into().unwrap(),
                    s
                )
            })
        }
    }

    pub fn output_identity(
        &self,
        output_control: DebugOutctlFlags,
        flags: u32,
        format: impl AsRef<ACPStr>,
    ) -> WinResult<()> {
        unsafe {
            self.0
                .OutputIdentity(output_control.bits(), flags, pca!(format))
        }
    }

    pub fn get_event_callbacks(
        &self,
    ) -> WinResult<Option<DebugEventCallbacks>> {
        unsafe {
            match self.0.GetEventCallbacks() {
                Ok(x) => Ok(Some(x.into())),
                Err(x) if x.code() == S_OK => Ok(None),
                Err(x) => Err(x),
            }
        }
    }

    pub fn set_event_callbacks(
        &self,
        callbacks: Option<DebugEventCallbacksAdapter>,
    ) -> WinResult<()> {
        unsafe { self.0.SetEventCallbacks(callbacks.map(Into::into).as_ref()) }
    }

    pub(crate) unsafe fn _set_event_callbacks_raw(
        &self,
        callbacks: Option<IDebugEventCallbacks>,
    ) -> WinResult<()> {
        unsafe { self.0.SetEventCallbacks(callbacks.as_ref()) }
    }

    pub fn flush_callbacks(&self) -> WinResult<()> {
        unsafe { self.0.FlushCallbacks() }
    }
}

// IDebugClient2
impl DebugClient {
    // WriteDumpFile2

    pub fn add_dump_information_file(
        &self,
        info_file: impl AsRef<ACPStr>,
        r#type: DebugDumpFileType,
    ) -> WinResult<()> {
        unsafe {
            self.0
                .AddDumpInformationFile(pca!(info_file), r#type as u32)
        }
    }

    pub fn end_process_server(&self, server: ProcessServer) -> WinResult<()> {
        unsafe { self.0.EndProcessServer(server.into()) }
    }

    pub fn wait_for_process_server_end(&self, timeout: u32) -> WinResult<bool> {
        unsafe { hr!(vcall!(self, WaitForProcessServerEnd, timeout)) }
    }

    pub fn is_kernel_debugger_enabled(&self) -> WinResult<bool> {
        unsafe { hr!(vcall!(self, IsKernelDebuggerEnabled)) }
    }

    pub fn terminate_current_process(&self) -> WinResult<()> {
        unsafe { self.0.TerminateCurrentProcess() }
    }

    pub fn detach_current_process(&self) -> WinResult<()> {
        unsafe { self.0.DetachCurrentProcess() }
    }

    pub fn abandon_current_process(&self) -> WinResult<()> {
        unsafe { self.0.AbandonCurrentProcess() }
    }
}

// IDebugClient3
impl DebugClient {
    // GetRunningProcessSystemIdByExecutableNameWide

    // GetRunningProcessDescriptionWide

    pub fn create_process_wide(
        &self,
        server: ProcessServer,
        command_line: impl AsRef<WStr>,
        create_flags: DebugCreateProcessCreateFlags,
    ) -> WinResult<()> {
        let mut command_line =
            command_line.as_ref().as_bytes_with_nul().to_vec();
        unsafe {
            self.0.CreateProcessWide(
                server.into(),
                PWSTR(command_line.as_mut_ptr()),
                create_flags.bits(),
            )
        }
    }

    pub fn create_process_and_attach_wide(
        &self,
        server: ProcessServer,
        command_line: impl AsRef<WStr>,
        create_flags: DebugCreateProcessCreateFlags,
        process_id: Option<u32>,
        attach_flags: DebugAttachProcessFlags,
    ) -> WinResult<()> {
        let mut command_line =
            command_line.as_ref().as_bytes_with_nul().to_vec();
        unsafe {
            self.0.CreateProcessAndAttachWide(
                server.into(),
                PWSTR(command_line.as_mut_ptr()),
                create_flags.bits(),
                process_id.unwrap_or(0),
                attach_flags.bits(),
            )
        }
    }
}

// IDebugClient4
impl DebugClient {
    pub fn open_dump_file_wide<'a>(
        &self,
        file_name: impl Into<Option<&'a WStr>>,
        file_handle: Option<u64>,
    ) -> WinResult<()> {
        let file_name = file_name.into();
        let file_name = file_name
            .map_or(PCWSTR(std::ptr::null()), |name| PCWSTR(name.as_ptr()));
        unsafe {
            self.0
                .OpenDumpFileWide(file_name, file_handle.unwrap_or_default())
        }
    }

    pub fn write_dump_file_wide<'a>(
        &self,
        file_name: impl Into<Option<&'a WStr>>,
        file_handle: Option<u64>,
        qualifier: DebugDumpFlags,
        format_flags: DebugFormatFlags,
        comment: impl AsRef<WStr>,
    ) -> WinResult<()> {
        let file_name = file_name.into();
        let file_name = file_name
            .map_or(PCWSTR(std::ptr::null()), |name| PCWSTR(name.as_ptr()));
        unsafe {
            self.0.WriteDumpFileWide(
                file_name,
                file_handle.unwrap_or_default(),
                qualifier as u32,
                format_flags.bits(),
                pcw!(comment),
            )
        }
    }

    pub fn add_dump_information_file_wide(
        &self,
        info_file: impl AsRef<WStr>,
        file_handle: u64,
        r#type: DebugDumpFileType,
    ) -> WinResult<()> {
        unsafe {
            self.0.AddDumpInformationFileWide(
                pcw!(info_file),
                file_handle,
                r#type as u32,
            )
        }
    }

    pub fn get_number_dump_files(&self) -> WinResult<u32> {
        unsafe { self.0.GetNumberDumpFiles() }
    }

    // GetDumpFile

    // GetDumpFileWide
}

// IDebugClient5
impl DebugClient {
    pub fn attach_kernel_wide(
        &self,
        flags: DebugAttachKernelFlags,
        connect_options: impl AsRef<WStr>,
    ) -> WinResult<()> {
        unsafe { self.0.AttachKernelWide(flags as u32, pcw!(connect_options)) }
    }

    pub fn get_kernel_connection_options_wide(&self) -> WinResult<WString> {
        unsafe {
            wstring_with_capacity(32, |v, s| {
                vcall!(
                    self,
                    GetKernelConnectionOptionsWide,
                    pw!(v),
                    v.len().try_into().unwrap(),
                    s
                )
            })
        }
    }

    pub fn set_kernel_connection_options_wide(
        &self,
        options: KernelConnectionOptions,
    ) -> WinResult<()> {
        unsafe {
            self.0.SetKernelConnectionOptionsWide(PCWSTR(
                options.get_wstr().as_ptr(),
            ))
        }
    }

    pub fn start_process_server_wide(
        &self,
        flags: DebugClassFlags,
        options: impl AsRef<WStr>,
        /* reserved: Option<*mut c_void>, */
    ) -> WinResult<()> {
        unsafe {
            self.0
                .StartProcessServerWide(flags as u32, pcw!(options), None)
        }
    }

    pub fn connect_process_server_wide(
        &self,
        remote_options: impl AsRef<WStr>,
    ) -> WinResult<ProcessServer> {
        unsafe {
            Ok(self
                .0
                .ConnectProcessServerWide(pcw!(remote_options))?
                .into())
        }
    }

    pub fn start_server_wide(
        &self,
        options: impl AsRef<WStr>,
    ) -> WinResult<()> {
        unsafe { self.0.StartServerWide(pcw!(options)) }
    }

    pub fn output_servers_wide(
        &self,
        output_control: DebugOutctlFlags,
        machine: impl AsRef<WStr>,
        flags: DebugServersFlags,
    ) -> WinResult<()> {
        unsafe {
            self.0.OutputServersWide(
                output_control.bits(),
                pcw!(machine),
                flags.bits(),
            )
        }
    }

    pub fn get_output_callbacks_wide(
        &self,
    ) -> WinResult<Option<DebugOutputCallbacksWide>> {
        unsafe {
            match self.0.GetOutputCallbacksWide() {
                Ok(x) => Ok(Some(x.into())),
                Err(x) if x.code() == S_OK => Ok(None),
                Err(x) => Err(x),
            }
        }
    }

    pub fn set_output_callbacks_wide(
        &self,
        callbacks: Option<DebugOutputCallbacksWideAdapter>,
    ) -> WinResult<()> {
        unsafe {
            self.0
                .SetOutputCallbacksWide(callbacks.map(Into::into).as_ref())
        }
    }

    pub(crate) unsafe fn _set_output_callbacks_wide(
        &self,
        callbacks: Option<IDebugOutputCallbacksWide>,
    ) -> WinResult<()> {
        unsafe { self.0.SetOutputCallbacksWide(callbacks.as_ref()) }
    }

    pub fn get_output_line_prefix_wide(&self) -> WinResult<WString> {
        unsafe {
            wstring_with_capacity(32, |v, s| {
                vcall!(
                    self,
                    GetOutputLinePrefixWide,
                    pw!(v),
                    v.len().try_into().unwrap(),
                    s
                )
            })
        }
    }

    pub fn set_output_line_prefix_wide(
        &self,
        prefix: impl AsRef<WStr>,
    ) -> WinResult<()> {
        unsafe { self.0.SetOutputLinePrefixWide(pcw!(prefix)) }
    }

    pub fn get_identity_wide(&self) -> WinResult<WString> {
        unsafe {
            wstring_with_capacity(32, |v, s| {
                vcall!(
                    self,
                    GetIdentityWide,
                    pw!(v),
                    v.len().try_into().unwrap(),
                    s
                )
            })
        }
    }

    pub fn output_identity_wide(
        &self,
        output_control: DebugOutctlFlags,
        flags: u32,
        format: impl AsRef<WStr>,
    ) -> WinResult<()> {
        unsafe {
            self.0.OutputIdentityWide(
                output_control.bits(),
                flags,
                pcw!(format),
            )
        }
    }

    pub fn get_event_callbacks_wide(
        &self,
    ) -> WinResult<Option<DebugEventCallbacksWide>> {
        unsafe {
            match self.0.GetEventCallbacksWide() {
                Ok(x) => Ok(Some(x.into())),
                Err(x) if x.code() == S_OK => Ok(None),
                Err(x) => Err(x),
            }
        }
    }

    pub fn set_event_callbacks_wide(
        &self,
        callbacks: Option<DebugEventCallbacksWideAdapter>,
    ) -> WinResult<()> {
        unsafe {
            self.0
                .SetEventCallbacksWide(callbacks.map(Into::into).as_ref())
        }
    }

    pub(crate) unsafe fn _set_event_callbacks_wide(
        &self,
        callbacks: Option<IDebugEventCallbacksWide>,
    ) -> WinResult<()> {
        unsafe { self.0.SetEventCallbacksWide(callbacks.as_ref()) }
    }

    // CreateProcess2

    // CreateProcess2Wide

    // CreateProcessAndAttach2

    #[allow(clippy::too_many_arguments)]
    pub fn create_process_and_attach2_wide<'a>(
        &self,
        server: ProcessServer,
        command_line: impl AsRef<WStr>,
        options: &DebugCreateProcessOptions,
        initial_directory: impl Into<Option<&'a WStr>>,
        environment: Option<&[u16]>,
        process_id: Option<u32>,
        attach_flags: DebugAttachProcessFlags,
    ) -> WinResult<()> {
        let initial_directory = initial_directory.into();

        if options
            .create_flags()
            .contains(DebugCreateProcessCreateFlags::ThroughRtl)
            && environment.is_some()
        {
            return Err(E_INVALIDARG.into());
        }

        let initial_directory = initial_directory
            .map_or(PCWSTR(std::ptr::null()), |directory| {
                PCWSTR(directory.as_ptr())
            });

        let environment = match environment {
            None => PCWSTR(std::ptr::null()),
            Some(environment)
                if environment.len() >= 2
                    && environment[environment.len() - 2..] == [0, 0] =>
            {
                PCWSTR(environment.as_ptr())
            }
            Some(_) => return Err(E_INVALIDARG.into()),
        };

        let mut command_line =
            command_line.as_ref().as_bytes_with_nul().to_vec();

        unsafe {
            self.0.CreateProcessAndAttach2Wide(
                server.into(),
                PWSTR(command_line.as_mut_ptr()),
                std::ptr::from_ref(&options.0).cast(),
                size_of::<DEBUG_CREATE_PROCESS_OPTIONS>() as u32,
                initial_directory,
                environment,
                process_id.unwrap_or_default(),
                attach_flags.bits(),
            )
        }
    }

    // PushOutputLinePrefix

    // PushOutputLinePrefixWide

    // PopOutputLinePrefix

    pub fn get_number_input_callbacks(&self) -> WinResult<u32> {
        unsafe { self.0.GetNumberInputCallbacks() }
    }

    pub fn get_number_output_callbacks(&self) -> WinResult<u32> {
        unsafe { self.0.GetNumberOutputCallbacks() }
    }

    pub fn get_number_event_callbacks(
        &self,
        event_flags: DebugEventFlags,
    ) -> WinResult<u32> {
        unsafe { self.0.GetNumberEventCallbacks(event_flags.bits()) }
    }

    pub fn get_quit_lock_string(&self) -> WinResult<ACPString> {
        unsafe {
            astring_with_capacity(32, |v, s| {
                vcall!(
                    self,
                    GetQuitLockString,
                    pa!(v),
                    v.len().try_into().unwrap(),
                    s
                )
            })
        }
    }

    pub fn set_quit_lock_string(
        &self,
        string: impl AsRef<ACPStr>,
    ) -> WinResult<()> {
        unsafe { self.0.SetQuitLockString(pca!(string)) }
    }

    pub fn get_quit_lock_string_wide(&self) -> WinResult<WString> {
        unsafe {
            wstring_with_capacity(32, |v, s| {
                vcall!(
                    self,
                    GetQuitLockStringWide,
                    pw!(v),
                    v.len().try_into().unwrap(),
                    s
                )
            })
        }
    }

    pub fn set_quit_lock_string_wide(
        &self,
        string: impl AsRef<WStr>,
    ) -> WinResult<()> {
        unsafe { self.0.SetQuitLockStringWide(pcw!(string)) }
    }
}

// IDebugClient6
impl DebugClient {
    // SetEventContextCallbacks
}

// IDebugClient7
impl DebugClient {
    /// Internal function.
    ///
    /// # Safety
    ///
    /// Unknown.
    #[doc(hidden)]
    pub unsafe fn set_client_context(
        &self,
        context: *mut c_void,
        context_size: u32,
    ) -> WinResult<()> {
        unsafe { self.0.SetClientContext(context, context_size) }
    }

    // SetClientContext
}

// IDebugClient8
impl DebugClient {
    // OpenDumpFileWide2
}

// IDebugClient9
impl DebugClient {
    // OpenDumpDirectoryWide

    // OpenDumpDirectory
}