-
Notifications
You must be signed in to change notification settings - Fork 662
Expand file tree
/
Copy pathquic_platform_winuser.h
More file actions
1477 lines (1281 loc) · 37.5 KB
/
quic_platform_winuser.h
File metadata and controls
1477 lines (1281 loc) · 37.5 KB
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
/*++
Copyright (c) Microsoft Corporation.
Licensed under the MIT License.
Abstract:
This file contains Windows User Mode implementations of the
QUIC Platform Interfaces.
Environment:
Windows user mode
--*/
#pragma once
#ifndef CX_PLATFORM_TYPE
#error "Must be included from quic_platform.h"
#endif
#ifdef _KERNEL_MODE
#error "Incorrectly including Windows User Platform Header"
#endif
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN 1
#endif
#pragma warning(push) // Don't care about OACR warnings in publics
#pragma warning(disable:26036)
#pragma warning(disable:28251)
#pragma warning(disable:28252)
#pragma warning(disable:28253)
#pragma warning(disable:28301)
#pragma warning(disable:6553) // Bad SAL annotation in public header
#pragma warning(disable:5105) // The conformant preprocessor along with the newest SDK throws this warning for a macro.
#include <windows.h>
#include <winsock2.h>
#include <ws2ipdef.h>
#include <iphlpapi.h>
#include <bcrypt.h>
#include <stdlib.h>
#include <winternl.h>
#include "msquic_winuser.h"
#ifdef _M_X64
#pragma warning(disable:28251) // Inconsistent annotation for function
#include <intrin.h>
#endif
#pragma warning(pop)
#pragma warning(disable:4201) // nonstandard extension used: nameless struct/union
#pragma warning(disable:4324) // 'CXPLAT_POOL': structure was padded due to alignment specifier
#if defined(__cplusplus)
extern "C" {
#endif
#ifndef NDEBUG
#define DBG 1
#define DEBUG 1
#endif
#if _WIN64
#define QUIC_64BIT 1
#else
#define QUIC_32BIT 1
#endif
#define INITCODE
#define PAGEDX
#define QUIC_CACHEALIGN DECLSPEC_CACHEALIGN
#define ALIGN_DOWN(length, type) \
((ULONG)(length) & ~(sizeof(type) - 1))
#define ALIGN_UP(length, type) \
(ALIGN_DOWN(((ULONG)(length) + sizeof(type) - 1), type))
#define INIT_NO_SAL(X) // No-op since Windows supports SAL
#ifdef QUIC_RESTRICTED_BUILD
#ifndef NT_SUCCESS
#define NT_SUCCESS(Status) (((NTSTATUS)(Status)) >= 0)
#endif
_When_(Status < 0, _Out_range_(>, 0))
_When_(Status >= 0, _Out_range_(==, 0))
ULONG
NTAPI
RtlNtStatusToDosError (
NTSTATUS Status
);
#endif
//
// Static Analysis Interfaces
//
#define QUIC_NO_SANITIZE(X)
#if defined(_PREFAST_)
// _Analysis_assume_ will never result in any code generation for _exp,
// so using it will not have runtime impact, even if _exp has side effects.
#define CXPLAT_ANALYSIS_ASSUME(_exp) _Analysis_assume_(_exp)
#else // _PREFAST_
// CXPLAT_ANALYSIS_ASSUME ensures that _exp is parsed in non-analysis compile.
// On DEBUG, it's guaranteed to be parsed as part of the normal compile, but
// with non-DEBUG, use __noop to ensure _exp is parseable but without code
// generation.
#if DEBUG
#define CXPLAT_ANALYSIS_ASSUME(_exp) ((void) 0)
#else // DEBUG
#define CXPLAT_ANALYSIS_ASSUME(_exp) __noop(_exp)
#endif // DEBUG
#endif // _PREFAST_
#ifdef __clang__
#define CXPLAT_STATIC_ASSERT(X,Y) _Static_assert(X,Y)
#else
#define CXPLAT_STATIC_ASSERT(X,Y) static_assert(X,Y)
#endif
#define CXPLAT_ANALYSIS_ASSERT(X) __analysis_assert(X)
//
// Assertion Interfaces
_IRQL_requires_max_(DISPATCH_LEVEL)
void
CxPlatLogAssert(
_In_z_ const char* File,
_In_ int Line,
_In_z_ const char* Expr
);
#define CXPLAT_WIDE_STRING(_str) L##_str
#define CXPLAT_ASSERT_NOOP(_exp, _msg) \
(CXPLAT_ANALYSIS_ASSUME(_exp), 0)
#define CXPLAT_ASSERT_LOG(_exp, _msg) \
(CXPLAT_ANALYSIS_ASSUME(_exp), \
((!(_exp)) ? (CxPlatLogAssert(__FILE__, __LINE__, #_exp), FALSE) : TRUE))
#define CXPLAT_ASSERT_CRASH(_exp, _msg) \
(CXPLAT_ANALYSIS_ASSUME(_exp), \
((!(_exp)) ? \
(CxPlatLogAssert(__FILE__, __LINE__, #_exp), \
__annotation(L"Debug", L"AssertFail", _msg), \
DbgRaiseAssertionFailure(), FALSE) : \
TRUE))
//
// MsQuic uses three types of asserts:
//
// CXPLAT_DBG_ASSERT - Asserts that are too expensive to evaluate all the time.
// CXPLAT_TEL_ASSERT - Asserts that are acceptable to always evaluate, but not
// always crash the system.
// CXPLAT_FRE_ASSERT - Asserts that must always crash the system.
//
#if DEBUG
#define CXPLAT_DBG_ASSERT(_exp) CXPLAT_ASSERT_CRASH(_exp, CXPLAT_WIDE_STRING(#_exp))
#define CXPLAT_DBG_ASSERTMSG(_exp, _msg) CXPLAT_ASSERT_CRASH(_exp, CXPLAT_WIDE_STRING(_msg))
#else
#define CXPLAT_DBG_ASSERT(_exp) CXPLAT_ASSERT_NOOP(_exp, CXPLAT_WIDE_STRING(#_exp))
#define CXPLAT_DBG_ASSERTMSG(_exp, _msg) CXPLAT_ASSERT_NOOP(_exp, CXPLAT_WIDE_STRING(_msg))
#endif
#if DEBUG
#define CXPLAT_TEL_ASSERT(_exp) CXPLAT_ASSERT_CRASH(_exp, CXPLAT_WIDE_STRING(#_exp))
#define CXPLAT_TEL_ASSERTMSG(_exp, _msg) CXPLAT_ASSERT_CRASH(_exp, CXPLAT_WIDE_STRING(_msg))
#define CXPLAT_TEL_ASSERTMSG_ARGS(_exp, _msg, _origin, _bucketArg1, _bucketArg2) \
CXPLAT_ASSERT_CRASH(_exp, CXPLAT_WIDE_STRING(_msg))
#elif QUIC_TELEMETRY_ASSERTS
#define CXPLAT_TEL_ASSERT(_exp) CXPLAT_ASSERT_LOG(_exp, CXPLAT_WIDE_STRING(#_exp))
#define CXPLAT_TEL_ASSERTMSG(_exp, _msg) CXPLAT_ASSERT_LOG(_exp, CXPLAT_WIDE_STRING(_msg))
#define CXPLAT_TEL_ASSERTMSG_ARGS(_exp, _msg, _origin, _bucketArg1, _bucketArg2) \
CXPLAT_ASSERT_LOG(_exp, CXPLAT_WIDE_STRING(_msg))
#else
#define CXPLAT_TEL_ASSERT(_exp) CXPLAT_ASSERT_NOOP(_exp, CXPLAT_WIDE_STRING(#_exp))
#define CXPLAT_TEL_ASSERTMSG(_exp, _msg) CXPLAT_ASSERT_NOOP(_exp, CXPLAT_WIDE_STRING(_msg))
#define CXPLAT_TEL_ASSERTMSG_ARGS(_exp, _msg, _origin, _bucketArg1, _bucketArg2) \
CXPLAT_ASSERT_NOOP(_exp, CXPLAT_WIDE_STRING(_msg))
#endif
#define CXPLAT_FRE_ASSERT(_exp) CXPLAT_ASSERT_CRASH(_exp, CXPLAT_WIDE_STRING(#_exp))
#define CXPLAT_FRE_ASSERTMSG(_exp, _msg) CXPLAT_ASSERT_CRASH(_exp, CXPLAT_WIDE_STRING(_msg))
#ifdef QUIC_UWP_BUILD
WINBASEAPI
_When_(lpModuleName == NULL,_Ret_notnull_)
_When_(lpModuleName != NULL,_Ret_maybenull_)
HMODULE
WINAPI
GetModuleHandleW(
_In_opt_ LPCWSTR lpModuleName
);
#endif
//
// Verifier is enabled.
//
#define CxPlatVerifierEnabled(Flags) \
(GetModuleHandleW(L"verifier.dll") != NULL && \
GetModuleHandleW(L"vrfcore.dll") != NULL), \
Flags = 0
//
// Debugger check.
//
#define CxPlatDebuggerPresent() IsDebuggerPresent()
//
// Interrupt ReQuest Level
//
#define CXPLAT_IRQL() PASSIVE_LEVEL
#define CXPLAT_PASSIVE_CODE() CXPLAT_DBG_ASSERT(CXPLAT_IRQL() == PASSIVE_LEVEL)
#define CXPLAT_AT_DISPATCH() FALSE
//
// Wrapper functions
//
QUIC_INLINE
void*
InterlockedFetchAndClearPointer(
_Inout_ _Interlocked_operand_ void* volatile *Target
)
{
return InterlockedExchangePointer(Target, NULL);
}
QUIC_INLINE
BOOLEAN
InterlockedFetchAndClearBoolean(
_Inout_ _Interlocked_operand_ BOOLEAN volatile *Target
)
{
return (BOOLEAN)InterlockedAnd8((char*)Target, 0);
}
QUIC_INLINE
BOOLEAN
InterlockedFetchAndSetBoolean(
_Inout_ _Interlocked_operand_ BOOLEAN volatile *Target
)
{
return (BOOLEAN)InterlockedOr8((char*)Target, 1);
}
//
// CloseHandle has an incorrect SAL annotation, so call through a wrapper.
//
_IRQL_requires_max_(PASSIVE_LEVEL)
QUIC_INLINE
void
CxPlatCloseHandle(_Pre_notnull_ HANDLE Handle) {
CloseHandle(Handle);
}
//
// Allocation/Memory Interfaces
//
extern uint64_t CxPlatTotalMemory;
_Ret_maybenull_
_Post_writable_byte_size_(ByteCount)
DECLSPEC_ALLOCATOR
void*
CxPlatAlloc(
_In_ size_t ByteCount,
_In_ uint32_t Tag
);
void*
CxPlatAllocUninitialized(
_In_ size_t ByteCount,
_In_ uint32_t Tag
);
void
CxPlatFree(
__drv_freesMem(Mem) _Frees_ptr_ void* Mem,
_In_ uint32_t Tag
);
#define CXPLAT_ALLOC_PAGED(Size, Tag) CxPlatAlloc(Size, Tag)
#define CXPLAT_ALLOC_NONPAGED(Size, Tag) CxPlatAlloc(Size, Tag)
#define CXPLAT_ALLOC_PAGED_UNINITIALIZED(Size, Tag) CxPlatAllocUninitialized(Size, Tag)
#define CXPLAT_ALLOC_NONPAGED_UNINITIALIZED(Size, Tag) CxPlatAllocUninitialized(Size, Tag)
#define CXPLAT_FREE(Mem, Tag) CxPlatFree((void*)Mem, Tag)
typedef struct CXPLAT_POOL CXPLAT_POOL;
typedef struct DECLSPEC_ALIGN(MEMORY_ALLOCATION_ALIGNMENT) CXPLAT_POOL_HEADER {
union {
CXPLAT_POOL* Owner;
CXPLAT_SLIST_ENTRY Entry;
};
#if DEBUG
uint64_t SpecialFlag;
#endif
} CXPLAT_POOL_HEADER;
#define CXPLAT_POOL_FREE_FLAG 0xAAAAAAAAAAAAAAAAui64
#define CXPLAT_POOL_ALLOC_FLAG 0xE9E9E9E9E9E9E9E9ui64
typedef
CXPLAT_POOL_HEADER*
(*CXPLAT_POOL_ALLOC_FN)(
_In_ uint32_t Size,
_In_ uint32_t Tag,
_Inout_ CXPLAT_POOL* Pool
);
typedef
void
(*CXPLAT_POOL_FREE_FN)(
_In_ CXPLAT_POOL_HEADER* Entry,
_In_ uint32_t Tag,
_Inout_ CXPLAT_POOL* Pool
);
typedef struct CXPLAT_POOL {
SLIST_HEADER ListHead;
uint32_t Size;
uint32_t Tag;
uint32_t MaxDepth;
CXPLAT_POOL_ALLOC_FN Allocate;
CXPLAT_POOL_FREE_FN Free;
} CXPLAT_POOL;
#ifndef DISABLE_CXPLAT_POOL
#define CXPLAT_POOL_MAXIMUM_DEPTH 0x4000 // 16384
#define CXPLAT_POOL_DEFAULT_MAX_DEPTH 256 // Copied from EX_MAXIMUM_LOOKASIDE_DEPTH_BASE
#else
#define CXPLAT_POOL_MAXIMUM_DEPTH 0 // TODO - Optimize this scenario better
#define CXPLAT_POOL_DEFAULT_MAX_DEPTH 0
#endif
#if DEBUG
int32_t
CxPlatGetAllocFailDenominator(
);
#endif
QUIC_INLINE
CXPLAT_POOL_HEADER*
CxPlatPoolGenericAlloc(
_In_ uint32_t Size,
_In_ uint32_t Tag,
_Inout_ CXPLAT_POOL* Pool
)
{
UNREFERENCED_PARAMETER(Pool);
return (CXPLAT_POOL_HEADER*)CxPlatAlloc(Size, Tag);
}
QUIC_INLINE
void
CxPlatPoolGenericFree(
_In_ CXPLAT_POOL_HEADER* Entry,
_In_ uint32_t Tag,
_Inout_ CXPLAT_POOL* Pool
)
{
UNREFERENCED_PARAMETER(Pool);
CxPlatFree(Entry, Tag);
}
QUIC_INLINE
void
CxPlatPoolInitialize(
_In_ BOOLEAN IsPaged,
_In_ uint32_t Size,
_In_ uint32_t Tag,
_Inout_ CXPLAT_POOL* Pool
)
{
Pool->Size = Size + sizeof(CXPLAT_POOL_HEADER); // Add space for the object header
Pool->Tag = Tag;
Pool->MaxDepth = CXPLAT_POOL_DEFAULT_MAX_DEPTH;
Pool->Allocate = CxPlatPoolGenericAlloc;
Pool->Free = CxPlatPoolGenericFree;
InitializeSListHead(&(Pool)->ListHead);
UNREFERENCED_PARAMETER(IsPaged);
}
QUIC_INLINE
void
CxPlatPoolInitializeEx(
_In_ BOOLEAN IsPaged,
_In_ uint32_t Size,
_In_ uint32_t Tag,
_In_ uint32_t MaxDepth,
_In_opt_ CXPLAT_POOL_ALLOC_FN Allocate,
_In_opt_ CXPLAT_POOL_FREE_FN Free,
_Inout_ CXPLAT_POOL* Pool
)
{
Pool->Size = Size + sizeof(CXPLAT_POOL_HEADER); // Add space for the object header
Pool->Tag = Tag;
Pool->Allocate = Allocate ? Allocate : CxPlatPoolGenericAlloc;
Pool->Free = Free ? Free : CxPlatPoolGenericFree;
InitializeSListHead(&(Pool)->ListHead);
UNREFERENCED_PARAMETER(IsPaged);
if (MaxDepth != 0) {
Pool->MaxDepth = CXPLAT_MIN(MaxDepth, CXPLAT_POOL_MAXIMUM_DEPTH);
} else {
Pool->MaxDepth = CXPLAT_POOL_DEFAULT_MAX_DEPTH;
}
}
QUIC_INLINE
void
CxPlatPoolUninitialize(
_Inout_ CXPLAT_POOL* Pool
)
{
CXPLAT_POOL_HEADER* Entry;
while ((Entry = (CXPLAT_POOL_HEADER*)InterlockedPopEntrySList(&Pool->ListHead)) != NULL) {
#if DEBUG
CXPLAT_DBG_ASSERT(Entry->SpecialFlag == CXPLAT_POOL_FREE_FLAG);
#endif
Pool->Free(Entry, Pool->Tag, Pool);
}
}
QUIC_INLINE
void*
CxPlatPoolAlloc(
_Inout_ CXPLAT_POOL* Pool
)
{
CXPLAT_POOL_HEADER* Header =
#if DEBUG
CxPlatGetAllocFailDenominator() ? NULL : // No pool when using simulated alloc failures
#endif
(CXPLAT_POOL_HEADER*)InterlockedPopEntrySList(&Pool->ListHead);
if (Header == NULL) {
Header = Pool->Allocate(Pool->Size, Pool->Tag, Pool);
if (Header == NULL) {
return NULL;
}
}
#if DEBUG
else {
CXPLAT_DBG_ASSERT(Header->SpecialFlag == CXPLAT_POOL_FREE_FLAG);
}
Header->SpecialFlag = CXPLAT_POOL_ALLOC_FLAG;
#endif
Header->Owner = Pool;
void* Result = (void*)(Header + 1);
RtlZeroMemory(Result, Pool->Size - sizeof(CXPLAT_POOL_HEADER));
return Result;
}
QUIC_INLINE
void*
CxPlatPoolAllocUninitialized(
_Inout_ CXPLAT_POOL* Pool
)
{
CXPLAT_POOL_HEADER* Header =
#if DEBUG
CxPlatGetAllocFailDenominator() ? NULL : // No pool when using simulated alloc failures
#endif
(CXPLAT_POOL_HEADER*)InterlockedPopEntrySList(&Pool->ListHead);
if (Header == NULL) {
Header = Pool->Allocate(Pool->Size, Pool->Tag, Pool);
if (Header == NULL) {
return NULL;
}
}
#if DEBUG
else {
CXPLAT_DBG_ASSERT(Header->SpecialFlag == CXPLAT_POOL_FREE_FLAG);
}
Header->SpecialFlag = CXPLAT_POOL_ALLOC_FLAG;
#endif
Header->Owner = Pool;
return (void*)(Header + 1);
}
QUIC_INLINE
void
CxPlatPoolFree(
_In_ void* Memory
)
{
CXPLAT_POOL_HEADER* Header = (CXPLAT_POOL_HEADER*)Memory - 1;
CXPLAT_POOL* Pool = Header->Owner;
#if DEBUG
CXPLAT_DBG_ASSERT(Header->SpecialFlag == CXPLAT_POOL_ALLOC_FLAG);
if (CxPlatGetAllocFailDenominator()) {
Pool->Free(Header, Pool->Tag, Pool);
return;
}
Header->SpecialFlag = CXPLAT_POOL_FREE_FLAG;
#endif
if (QueryDepthSList(&Pool->ListHead) >= Pool->MaxDepth) {
Pool->Free(Header, Pool->Tag, Pool);
} else {
InterlockedPushEntrySList(&Pool->ListHead, (PSLIST_ENTRY)Header);
}
}
QUIC_INLINE
BOOLEAN
CxPlatPoolPrune(
_Inout_ CXPLAT_POOL* Pool
)
{
CXPLAT_POOL_HEADER* Entry =
(CXPLAT_POOL_HEADER*)InterlockedPopEntrySList(&Pool->ListHead);
if (Entry == NULL) {
return FALSE;
}
#if DEBUG
CXPLAT_DBG_ASSERT(Entry->SpecialFlag == CXPLAT_POOL_FREE_FLAG);
#endif
Pool->Free(Entry, Pool->Tag, Pool);
return TRUE;
}
#define CxPlatZeroMemory RtlZeroMemory
#define CxPlatCopyMemory RtlCopyMemory
#define CxPlatMoveMemory RtlMoveMemory
#define CxPlatSecureZeroMemory RtlSecureZeroMemory
#define CxPlatByteSwapUint16 _byteswap_ushort
#define CxPlatByteSwapUint32 _byteswap_ulong
#define CxPlatByteSwapUint64 _byteswap_uint64
//
// Locking Interfaces
//
typedef CRITICAL_SECTION CXPLAT_LOCK;
#define CxPlatLockInitialize(Lock) InitializeCriticalSection(Lock)
#define CxPlatLockUninitialize(Lock) DeleteCriticalSection(Lock)
#define CxPlatLockAcquire(Lock) EnterCriticalSection(Lock)
#define CxPlatLockRelease(Lock) LeaveCriticalSection(Lock)
typedef CRITICAL_SECTION CXPLAT_DISPATCH_LOCK;
#define CxPlatDispatchLockInitialize(Lock) InitializeCriticalSection(Lock)
#define CxPlatDispatchLockUninitialize(Lock) DeleteCriticalSection(Lock)
#define CxPlatDispatchLockAcquire(Lock) EnterCriticalSection(Lock)
#define CxPlatDispatchLockRelease(Lock) LeaveCriticalSection(Lock)
typedef SRWLOCK CXPLAT_RW_LOCK;
#define CxPlatRwLockInitialize(Lock) InitializeSRWLock(Lock)
#define CxPlatRwLockUninitialize(Lock)
#define CxPlatRwLockAcquireShared(Lock) AcquireSRWLockShared(Lock)
#define CxPlatRwLockAcquireExclusive(Lock) AcquireSRWLockExclusive(Lock)
#define CxPlatRwLockReleaseShared(Lock) ReleaseSRWLockShared(Lock)
#define CxPlatRwLockReleaseExclusive(Lock) ReleaseSRWLockExclusive(Lock)
typedef SRWLOCK CXPLAT_DISPATCH_RW_LOCK;
#define CxPlatDispatchRwLockInitialize(Lock) InitializeSRWLock(Lock)
#define CxPlatDispatchRwLockUninitialize(Lock)
#define CxPlatDispatchRwLockAcquireShared(Lock, PrevIrql) AcquireSRWLockShared(Lock)
#define CxPlatDispatchRwLockAcquireExclusive(Lock, PrevIrql) AcquireSRWLockExclusive(Lock)
#define CxPlatDispatchRwLockReleaseShared(Lock, PrevIrql) ReleaseSRWLockShared(Lock)
#define CxPlatDispatchRwLockReleaseExclusive(Lock, PrevIrql) ReleaseSRWLockExclusive(Lock)
//
// Reference Count Interface
//
#if defined(_X86_) || defined(_AMD64_)
#define QuicBarrierAfterInterlock()
#elif defined(_ARM64_)
#define QuicBarrierAfterInterlock() __dmb(_ARM64_BARRIER_ISH)
#elif defined(_ARM_)
#define QuicBarrierAfterInterlock() __dmb(_ARM_BARRIER_ISH)
#else
#error Unsupported architecture.
#endif
#if defined (_WIN64)
#define QuicIncrementLongPtrNoFence InterlockedIncrementNoFence64
#define QuicDecrementLongPtrRelease InterlockedDecrementRelease64
#define QuicCompareExchangeLongPtrNoFence InterlockedCompareExchangeNoFence64
#ifdef QUIC_RESTRICTED_BUILD
#define QuicReadLongPtrNoFence(p) ((LONG64)(*p))
#else
#define QuicReadLongPtrNoFence ReadNoFence64
#endif
#else
#define QuicIncrementLongPtrNoFence InterlockedIncrementNoFence
#define QuicDecrementLongPtrRelease InterlockedDecrementRelease
#define QuicCompareExchangeLongPtrNoFence InterlockedCompareExchangeNoFence
#ifdef QUIC_RESTRICTED_BUILD
#define QuicReadLongPtrNoFence(p) ((LONG)(*p))
#else
#define QuicReadLongPtrNoFence ReadNoFence
#endif
#endif
#ifdef QUIC_RESTRICTED_BUILD
#define QuicReadPtrNoFence(p) ((void*)(*p))
#else
#define QuicReadPtrNoFence ReadPointerNoFence
#endif
typedef LONG_PTR CXPLAT_REF_COUNT;
QUIC_INLINE
void
CxPlatRefInitialize(
_Out_ CXPLAT_REF_COUNT* RefCount
)
{
*RefCount = 1;
}
QUIC_INLINE
void
CxPlatRefInitializeEx(
_Out_ CXPLAT_REF_COUNT* RefCount,
_In_ uint32_t Initial
)
{
*RefCount = (LONG_PTR)Initial;
}
QUIC_INLINE
void
CxPlatRefInitializeMultiple(
_Out_writes_(Count) CXPLAT_REF_COUNT* RefCounts,
_In_ uint32_t Count
)
{
for (uint32_t i = 0; i < Count; i++) {
CxPlatRefInitialize(&RefCounts[i]);
}
}
#define CxPlatRefUninitialize(RefCount)
QUIC_INLINE
void
CxPlatRefIncrement(
_Inout_ CXPLAT_REF_COUNT* RefCount
)
{
if (QuicIncrementLongPtrNoFence(RefCount) > 1) {
return;
}
__fastfail(FAST_FAIL_INVALID_REFERENCE_COUNT);
}
QUIC_INLINE
BOOLEAN
CxPlatRefIncrementNonZero(
_Inout_ volatile CXPLAT_REF_COUNT *RefCount,
_In_ ULONG Bias
)
{
CXPLAT_REF_COUNT NewValue;
CXPLAT_REF_COUNT OldValue;
PrefetchForWrite(RefCount);
OldValue = QuicReadLongPtrNoFence(RefCount);
for (;;) {
NewValue = OldValue + Bias;
if ((ULONG_PTR)NewValue > Bias) {
NewValue = QuicCompareExchangeLongPtrNoFence(RefCount,
NewValue,
OldValue);
if (NewValue == OldValue) {
return TRUE;
}
OldValue = NewValue;
} else if ((ULONG_PTR)NewValue == Bias) {
return FALSE;
} else {
__fastfail(FAST_FAIL_INVALID_REFERENCE_COUNT);
return FALSE;
}
}
}
QUIC_INLINE
BOOLEAN
CxPlatRefDecrement(
_Inout_ CXPLAT_REF_COUNT* RefCount
)
{
CXPLAT_REF_COUNT NewValue;
//
// A release fence is required to ensure all guarded memory accesses are
// complete before any thread can begin destroying the object.
//
NewValue = QuicDecrementLongPtrRelease(RefCount);
if (NewValue > 0) {
return FALSE;
} else if (NewValue == 0) {
//
// An acquire fence is required before object destruction to ensure
// that the destructor cannot observe values changing on other threads.
//
QuicBarrierAfterInterlock();
return TRUE;
}
__fastfail(FAST_FAIL_INVALID_REFERENCE_COUNT);
return FALSE;
}
//
// Event Interfaces
//
typedef HANDLE CXPLAT_EVENT;
#define CxPlatEventInitialize(Event, ManualReset, InitialState) \
*(Event) = CreateEvent(NULL, ManualReset, InitialState, NULL); \
CXPLAT_DBG_ASSERT(*Event != NULL)
#define CxPlatEventUninitialize(Event) CxPlatCloseHandle(Event)
#define CxPlatEventSet(Event) SetEvent(Event)
#define CxPlatEventReset(Event) ResetEvent(Event)
#define CxPlatEventWaitForever(Event) WaitForSingleObject(Event, INFINITE)
QUIC_INLINE
BOOLEAN
CxPlatEventWaitWithTimeout(
_In_ CXPLAT_EVENT Event,
_In_ uint32_t TimeoutMs
)
{
CXPLAT_DBG_ASSERT(TimeoutMs != UINT32_MAX);
return WAIT_OBJECT_0 == WaitForSingleObject(Event, TimeoutMs);
}
//
// Event Queue Interfaces
//
typedef HANDLE CXPLAT_EVENTQ;
typedef OVERLAPPED_ENTRY CXPLAT_CQE;
typedef
_IRQL_requires_max_(PASSIVE_LEVEL)
void
(CXPLAT_EVENT_COMPLETION)(
_In_ CXPLAT_CQE* Cqe
);
typedef CXPLAT_EVENT_COMPLETION *CXPLAT_EVENT_COMPLETION_HANDLER;
typedef struct CXPLAT_SQE {
OVERLAPPED Overlapped;
CXPLAT_EVENT_COMPLETION_HANDLER Completion;
#if DEBUG
BOOLEAN IsQueued; // Debug flag to catch double queueing.
#endif
} CXPLAT_SQE;
// Extended SQE with Wait Completion Packet support for manual events
typedef struct CXPLAT_SQE_WCP {
CXPLAT_SQE BaseSqe; // Base SQE must be first for correct casting.
HANDLE WcpEvent; // Manual-reset event for wake packets
HANDLE WaitCompletionPacket; // Wait completion packet bound to Event
} CXPLAT_SQE_WCP;
//
// Wait Completion Packet functions from ntdll.dll.
//
typedef NTSTATUS (NTAPI *FuncNtCreateWaitCompletionPacket)(
_Out_ PHANDLE WaitCompletionPacketHandle,
_In_ ACCESS_MASK DesiredAccess,
_In_opt_ PVOID ObjectAttributes
);
typedef NTSTATUS (NTAPI *FuncNtAssociateWaitCompletionPacket)(
_In_ HANDLE WaitCompletionPacketHandle,
_In_ HANDLE IoCompletionHandle,
_In_ HANDLE TargetObjectHandle,
_In_opt_ PVOID KeyContext,
_In_opt_ PVOID ApcContext,
_In_ NTSTATUS IoStatus,
_In_ ULONG_PTR IoStatusInformation,
_Out_opt_ PBOOLEAN TargetApcInvoked
);
typedef NTSTATUS (NTAPI *FuncNtCancelWaitCompletionPacket)(
_In_ HANDLE WaitCompletionPacketHandle,
_In_ BOOLEAN RemoveSignaledPacket
);
// Global function pointers (initialized in CxPlatInitialize)
extern FuncNtCreateWaitCompletionPacket NtCreateWaitCompletionPacket;
extern FuncNtAssociateWaitCompletionPacket NtAssociateWaitCompletionPacket;
extern FuncNtCancelWaitCompletionPacket NtCancelWaitCompletionPacket;
// Helper to check if WCP APIs are available
QUIC_INLINE
BOOLEAN
CxPlatWcpAvailable(void)
{
return NtCreateWaitCompletionPacket != NULL &&
NtAssociateWaitCompletionPacket != NULL &&
NtCancelWaitCompletionPacket != NULL;
}
QUIC_INLINE
BOOLEAN
CxPlatEventQInitialize(
_Out_ CXPLAT_EVENTQ* queue
)
{
return (*queue = CreateIoCompletionPort(INVALID_HANDLE_VALUE, NULL, 0, 1)) != NULL;
}
QUIC_INLINE
void
CxPlatEventQCleanup(
_In_ CXPLAT_EVENTQ* queue
)
{
CloseHandle(*queue);
}
QUIC_INLINE
BOOLEAN
CxPlatEventQAssociateHandle(
_In_ CXPLAT_EVENTQ* queue,
_In_ HANDLE fileHandle
)
{
return *queue == CreateIoCompletionPort(fileHandle, *queue, 0, 0);
}
QUIC_INLINE
BOOLEAN
CxPlatEventQEnqueue(
_In_ CXPLAT_EVENTQ* queue,
_In_ CXPLAT_SQE* sqe
)
{
#if DEBUG
CXPLAT_DBG_ASSERT(!sqe->IsQueued);
sqe->IsQueued;
#endif
CxPlatZeroMemory(&sqe->Overlapped, sizeof(sqe->Overlapped));
return PostQueuedCompletionStatus(*queue, 0, 0, &sqe->Overlapped) != 0;
}
QUIC_INLINE
BOOLEAN
CxPlatEventQEnqueueEx( // Windows specific extension
_In_ CXPLAT_EVENTQ* queue,
_In_ CXPLAT_SQE* sqe,
_In_ uint32_t num_bytes
)
{
#if DEBUG
CXPLAT_DBG_ASSERT(!sqe->IsQueued);
sqe->IsQueued;
#endif
CxPlatZeroMemory(&sqe->Overlapped, sizeof(sqe->Overlapped));
return PostQueuedCompletionStatus(*queue, num_bytes, 0, &sqe->Overlapped) != 0;
}
// Enqueue WCP-based SQE to the event queue.
// Falls back to standard PQCS if WCP is unavailable.
QUIC_INLINE
void
CxPlatEventQEnqueueWcp(
_In_ CXPLAT_EVENTQ* queue,
_In_ CXPLAT_SQE_WCP* sqe
)
{
if (sqe->WcpEvent) {
CxPlatEventSet(sqe->WcpEvent);
} else {
CxPlatEventQEnqueue(queue, &sqe->BaseSqe);
}
}
QUIC_INLINE
uint32_t
CxPlatEventQDequeue(
_In_ CXPLAT_EVENTQ* queue,
_Out_ CXPLAT_CQE* events,
_In_ uint32_t count,
_In_ uint32_t wait_time // milliseconds
)
{
ULONG out_count = 0;
if (!GetQueuedCompletionStatusEx(*queue, events, count, &out_count, wait_time, FALSE)) {
return 0;
}
CXPLAT_DBG_ASSERT(out_count != 0);
CXPLAT_DBG_ASSERT(events[0].lpOverlapped != NULL || out_count == 1);
#if DEBUG
if (events[0].lpOverlapped) {
for (uint32_t i = 0; i < (uint32_t)out_count; ++i) {
CXPLAT_CONTAINING_RECORD(events[i].lpOverlapped, CXPLAT_SQE, Overlapped)->IsQueued = FALSE;
}
}
#endif
return events[0].lpOverlapped == NULL ? 0 : (uint32_t)out_count;
}
QUIC_INLINE
void
CxPlatEventQReturn(
_In_ CXPLAT_EVENTQ* queue,
_In_ uint32_t count
)
{
UNREFERENCED_PARAMETER(queue);
UNREFERENCED_PARAMETER(count);
}
// Only WakeSqe and UpdatePollSqe will be using this.
QUIC_INLINE
BOOLEAN
CxPlatSqeInitialize(
_In_ CXPLAT_EVENTQ* queue,
_In_ CXPLAT_EVENT_COMPLETION completion,
_Out_ CXPLAT_SQE* sqe
)
{
UNREFERENCED_PARAMETER(queue);
CxPlatZeroMemory(sqe, sizeof(*sqe));
sqe->Completion = completion;
return TRUE;
}
// Currently only ShutdownSqe will be using this, but it can be used by any SQE that wants to take advantage of WCP for manual events.
QUIC_INLINE
BOOLEAN
CxPlatSqeInitializeWcp(
_In_ CXPLAT_EVENTQ* queue,
_In_ CXPLAT_EVENT_COMPLETION completion,
_Out_ CXPLAT_SQE_WCP* sqe
)
{
UNREFERENCED_PARAMETER(queue);
CxPlatZeroMemory(sqe, sizeof(*sqe));
sqe->BaseSqe.Completion = completion;
// Only attempt WCP initialization if APIs are available
if (!CxPlatWcpAvailable()) {
// WCP not available - this is acceptable on older Windows versions
// SQE will fall back to standard PQCS (with OOM risk)
return TRUE;
}
if (sqe->WcpEvent == NULL) {
CxPlatEventInitialize(&sqe->WcpEvent, TRUE, FALSE);
}
if (sqe->WcpEvent == NULL) {
return FALSE;
}
NTSTATUS status = NtCreateWaitCompletionPacket(&sqe->WaitCompletionPacket,
GENERIC_ALL,
NULL);
if (!NT_SUCCESS(status)) {
CloseHandle(sqe->WcpEvent);
return FALSE;
}
status = NtAssociateWaitCompletionPacket(
sqe->WaitCompletionPacket,
*queue,
sqe->WcpEvent,
NULL,
&sqe->BaseSqe,
0, // IoStatus STATUS_SUCCESS
0,
NULL);
if (!NT_SUCCESS(status)) {
NTSTATUS CancelStatus = NtCancelWaitCompletionPacket(