/*

+===========================================================+
|           THIS FILE WAS AUTOMATICALLY GENERATED           |
+===========================================================+
| Source: https://github.com/winsiderss/systeminformer      |
| Commit: 4d1b102f28f2f1dd317ddcab6745c7e44a942d46          |
| Generator: https://github.com/mrexodia/phnt-single-header |
+===========================================================+

MIT License

Copyright (c) 2022 Winsider Seminars & Solutions, Inc.

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/

#ifndef _PHNT_AMALGAMATE_H
#define _PHNT_AMALGAMATE_H

#ifdef _WINTERNL_
#error Do not mix Winternl.h and phnt.h
#endif // _WINTERNL_
#define _WINTERNL_ // Pretend the header was included

#ifdef _KERNEL_MODE
#define PHNT_DETECTED_MODE PHNT_MODE_KERNEL
#else
#define PHNT_DETECTED_MODE PHNT_MODE_USER
/*
 * Win32 definition support
 *
 * This file is part of System Informer.
 */

#ifndef _PHNT_WINDOWS_H
#define _PHNT_WINDOWS_H

 // This header file provides access to Win32, plus NTSTATUS values and some access mask values.

#ifndef __cplusplus
#ifndef CINTERFACE
#define CINTERFACE
#endif

#ifndef COBJMACROS
#define COBJMACROS
#endif
#endif

#ifndef NOMINMAX
#define NOMINMAX
#endif

#ifndef INT_ERROR
#define INT_ERROR (-1)
#endif

#ifndef ULONG64_MAX
#define ULONG64_MAX 0xffffffffffffffffui64
#endif

#ifndef SIZE_T_MAX
#ifdef _WIN64
#define SIZE_T_MAX 0xffffffffffffffffui64
#else
#define SIZE_T_MAX 0xffffffffUL
#endif
#endif

#ifndef ENABLE_RTL_NUMBER_OF_V2
#define ENABLE_RTL_NUMBER_OF_V2
#endif

#ifndef INITGUID
#define INITGUID
#endif

#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif

#ifndef WIN32_NO_STATUS
#define WIN32_NO_STATUS
#endif

#ifndef __cplusplus
// This is needed to workaround C17 preprocessor errors when using legacy versions of the Windows SDK. (dmex)
#ifndef MICROSOFT_WINDOWS_WINBASE_H_DEFINE_INTERLOCKED_CPLUSPLUS_OVERLOADS
#define MICROSOFT_WINDOWS_WINBASE_H_DEFINE_INTERLOCKED_CPLUSPLUS_OVERLOADS 0
#endif
#endif

#include <windows.h>
#include <windowsx.h>
#undef WIN32_NO_STATUS
#include <ntstatus.h>
#include <winioctl.h>
#include <evntrace.h>

typedef double DOUBLE;
typedef GUID* PGUID;

// Desktop access rights
#define DESKTOP_ALL_ACCESS \
    (DESKTOP_CREATEMENU | DESKTOP_CREATEWINDOW | DESKTOP_ENUMERATE | \
    DESKTOP_HOOKCONTROL | DESKTOP_JOURNALPLAYBACK | DESKTOP_JOURNALRECORD | \
    DESKTOP_READOBJECTS | DESKTOP_SWITCHDESKTOP | DESKTOP_WRITEOBJECTS | \
    STANDARD_RIGHTS_REQUIRED)
#define DESKTOP_GENERIC_READ \
    (DESKTOP_ENUMERATE | DESKTOP_READOBJECTS | STANDARD_RIGHTS_READ)
#define DESKTOP_GENERIC_WRITE \
    (DESKTOP_CREATEMENU | DESKTOP_CREATEWINDOW | DESKTOP_HOOKCONTROL | \
    DESKTOP_JOURNALPLAYBACK | DESKTOP_JOURNALRECORD | DESKTOP_WRITEOBJECTS | \
    STANDARD_RIGHTS_WRITE)
#define DESKTOP_GENERIC_EXECUTE \
    (DESKTOP_SWITCHDESKTOP | STANDARD_RIGHTS_EXECUTE)

// Window station access rights
#define WINSTA_GENERIC_READ \
    (WINSTA_ENUMDESKTOPS | WINSTA_ENUMERATE | WINSTA_READATTRIBUTES | \
    WINSTA_READSCREEN | STANDARD_RIGHTS_READ)
#define WINSTA_GENERIC_WRITE \
    (WINSTA_ACCESSCLIPBOARD | WINSTA_CREATEDESKTOP | WINSTA_WRITEATTRIBUTES | \
    STANDARD_RIGHTS_WRITE)
#define WINSTA_GENERIC_EXECUTE \
    (WINSTA_ACCESSGLOBALATOMS | WINSTA_EXITWINDOWS | STANDARD_RIGHTS_EXECUTE)

// WMI access rights
#define WMIGUID_GENERIC_READ \
    (WMIGUID_QUERY | WMIGUID_NOTIFICATION | WMIGUID_READ_DESCRIPTION | \
    STANDARD_RIGHTS_READ)
#define WMIGUID_GENERIC_WRITE \
    (WMIGUID_SET | TRACELOG_CREATE_REALTIME | TRACELOG_CREATE_ONDISK | \
    STANDARD_RIGHTS_WRITE)
#define WMIGUID_GENERIC_EXECUTE \
    (WMIGUID_EXECUTE | TRACELOG_GUID_ENABLE | TRACELOG_LOG_EVENT | \
    TRACELOG_ACCESS_REALTIME | TRACELOG_REGISTER_GUIDS | \
    STANDARD_RIGHTS_EXECUTE)

// Note: Some parts of the Windows Runtime, COM or third party hooks are returning
// S_FALSE and null pointers on errors when S_FALSE is a success code. (dmex)
#define HR_SUCCESS(hr) (((HRESULT)(hr)) == S_OK)
#define HR_FAILED(hr) (((HRESULT)(hr)) != S_OK)

// Note: The CONTAINING_RECORD macro doesn't support UBSan and generates false positives,
// we redefine the macro with FIELD_OFFSET as a workaround until the WinSDK is fixed (dmex)
#undef CONTAINING_RECORD
#define CONTAINING_RECORD(address, type, field) \
    ((type *)((ULONG_PTR)(address) - UFIELD_OFFSET(type, field)))

#ifndef __PCGUID_DEFINED__
#define __PCGUID_DEFINED__
typedef const GUID* PCGUID;
#endif

#endif
#endif // _KERNEL_MODE

#ifndef PHNT_MODE
#define PHNT_MODE PHNT_DETECTED_MODE
#endif // PHNT_MODE

/*
 * NT Header annotations
 *
 * This file is part of System Informer.
 */

#ifndef _PHNT_H
#define _PHNT_H

 // This header file provides access to NT APIs.

 // Definitions are annotated to indicate their source. If a definition is not annotated, it has been
 // retrieved from an official Microsoft source (NT headers, DDK headers, winnt.h).

 // * "winbase" indicates that a definition has been reconstructed from a Win32-ized NT definition in
 //   winbase.h.
 // * "rev" indicates that a definition has been reverse-engineered.
 // * "dbg" indicates that a definition has been obtained from a debug message or assertion in a
 //   checked build of the kernel or file.

 // Reliability:
 // 1. No annotation.
 // 2. dbg.
 // 3. symbols, private. Types may be incorrect.
 // 4. winbase. Names and types may be incorrect.
 // 5. rev.

 // Mode
#define PHNT_MODE_KERNEL 0
#define PHNT_MODE_USER 1

// Version
#define PHNT_WIN2K 50
#define PHNT_WINXP 51
#define PHNT_WS03 52
#define PHNT_VISTA 60
#define PHNT_WIN7 61
#define PHNT_WIN8 62
#define PHNT_WINBLUE 63
#define PHNT_THRESHOLD 100
#define PHNT_THRESHOLD2 101
#define PHNT_REDSTONE 102
#define PHNT_REDSTONE2 103
#define PHNT_REDSTONE3 104
#define PHNT_REDSTONE4 105
#define PHNT_REDSTONE5 106
#define PHNT_19H1 107
#define PHNT_19H2 108
#define PHNT_20H1 109
#define PHNT_20H2 110
#define PHNT_21H1 111
#define PHNT_WIN10_21H2 112
#define PHNT_WIN10_22H2 113
#define PHNT_WIN11 114
#define PHNT_WIN11_22H2 115
#define PHNT_WIN11_23H2 116

#ifndef PHNT_MODE
#define PHNT_MODE PHNT_MODE_USER
#endif

#ifndef PHNT_VERSION
#define PHNT_VERSION PHNT_WIN11
#endif

// Options

//#define PHNT_NO_INLINE_INIT_STRING

#ifdef __cplusplus
extern "C" {
#endif

#if (PHNT_MODE != PHNT_MODE_KERNEL)
    /*
     * Native definition support
     *
     * This file is part of System Informer.
     */

#ifndef _PHNT_NTDEF_H
#define _PHNT_NTDEF_H

#ifndef _NTDEF_
#define _NTDEF_

     // This header file provides basic NT types not included in Win32. If you have included winnt.h
     // (perhaps indirectly), you must use this file instead of ntdef.h.

#ifndef NOTHING
#define NOTHING
#endif

// Basic types

    typedef struct _QUAD
    {
        union
        {
            __int64 UseThisFieldToCopy;
            double DoNotUseThisField;
        };
    } QUAD, * PQUAD;

    // This isn't in NT, but it's useful.
    typedef struct DECLSPEC_ALIGN(MEMORY_ALLOCATION_ALIGNMENT) _QUAD_PTR
    {
        ULONG_PTR DoNotUseThisField1;
        ULONG_PTR DoNotUseThisField2;
    } QUAD_PTR, * PQUAD_PTR;

    typedef ULONG LOGICAL;
    typedef ULONG* PLOGICAL;

    typedef _Return_type_success_(return >= 0) LONG NTSTATUS;
    typedef NTSTATUS* PNTSTATUS;

    // Cardinal types

    typedef char CCHAR;
    typedef short CSHORT;
    typedef ULONG CLONG;

    typedef CCHAR* PCCHAR;
    typedef CSHORT* PCSHORT;
    typedef CLONG* PCLONG;

    typedef PCSTR PCSZ;

    typedef PVOID* PPVOID;

    // Specific

    typedef UCHAR KIRQL, * PKIRQL;
    typedef LONG KPRIORITY, * PKPRIORITY;
    typedef USHORT RTL_ATOM, * PRTL_ATOM;

    typedef LARGE_INTEGER PHYSICAL_ADDRESS, * PPHYSICAL_ADDRESS;

    typedef struct _LARGE_INTEGER_128
    {
        LONGLONG QuadPart[2];
    } LARGE_INTEGER_128, * PLARGE_INTEGER_128;

    // NT status macros

#define NT_SUCCESS(Status) (((NTSTATUS)(Status)) >= 0)
#define NT_INFORMATION(Status) ((((ULONG)(Status)) >> 30) == 1)
#define NT_WARNING(Status) ((((ULONG)(Status)) >> 30) == 2)
#define NT_ERROR(Status) ((((ULONG)(Status)) >> 30) == 3)

#define NT_CUSTOMER_SHIFT 29
#define NT_CUSTOMER(Status) ((((ULONG)(Status)) >> NT_CUSTOMER_SHIFT) & 1)

#define NT_FACILITY_MASK 0xfff
#define NT_FACILITY_SHIFT 16
#define NT_FACILITY(Status) ((((ULONG)(Status)) >> NT_FACILITY_SHIFT) & NT_FACILITY_MASK)

#define NT_NTWIN32(Status) (NT_FACILITY(Status) == FACILITY_NTWIN32)
#define WIN32_FROM_NTSTATUS(Status) (((ULONG)(Status)) & 0xffff)

// Functions

#ifndef _WIN64
#define FASTCALL __fastcall
#else
#define FASTCALL
#endif

// Synchronization enumerations

    typedef enum _EVENT_TYPE
    {
        NotificationEvent,
        SynchronizationEvent
    } EVENT_TYPE;

    typedef enum _TIMER_TYPE
    {
        NotificationTimer,
        SynchronizationTimer
    } TIMER_TYPE;

    typedef enum _WAIT_TYPE
    {
        WaitAll,
        WaitAny,
        WaitNotification
    } WAIT_TYPE;

    // Strings

    typedef struct _STRING
    {
        USHORT Length;
        USHORT MaximumLength;
        _Field_size_bytes_part_opt_(MaximumLength, Length) PCHAR Buffer;
    } STRING, * PSTRING, ANSI_STRING, * PANSI_STRING, OEM_STRING, * POEM_STRING;

    typedef STRING UTF8_STRING;
    typedef PSTRING PUTF8_STRING;

    typedef const STRING* PCSTRING;
    typedef const ANSI_STRING* PCANSI_STRING;
    typedef const OEM_STRING* PCOEM_STRING;

    typedef struct _UNICODE_STRING
    {
        USHORT Length;
        USHORT MaximumLength;
        _Field_size_bytes_part_opt_(MaximumLength, Length) PWCH Buffer;
    } UNICODE_STRING, * PUNICODE_STRING;

    typedef const UNICODE_STRING* PCUNICODE_STRING;

#define RTL_CONSTANT_STRING(s) { sizeof(s) - sizeof((s)[0]), sizeof(s), s }

#define DECLARE_CONST_UNICODE_STRING(_var, _str) \
const WCHAR _var ## _buffer[] = _str; \
const UNICODE_STRING _var = { sizeof(_str) - sizeof(WCHAR), sizeof(_str), (PWCH) _var ## _buffer }

#define DECLARE_GLOBAL_CONST_UNICODE_STRING(_var, _str) \
extern const DECLSPEC_SELECTANY UNICODE_STRING _var = RTL_CONSTANT_STRING(_str)

#define DECLARE_UNICODE_STRING_SIZE(_var, _size) \
WCHAR _var ## _buffer[_size]; \
UNICODE_STRING _var = { 0, (_size) * sizeof(WCHAR) , _var ## _buffer }

    // Balanced tree node

#define RTL_BALANCED_NODE_RESERVED_PARENT_MASK 3

    typedef struct _RTL_BALANCED_NODE
    {
        union
        {
            struct _RTL_BALANCED_NODE* Children[2];
            struct
            {
                struct _RTL_BALANCED_NODE* Left;
                struct _RTL_BALANCED_NODE* Right;
            };
        };
        union
        {
            UCHAR Red : 1;
            UCHAR Balance : 2;
            ULONG_PTR ParentValue;
        };
    } RTL_BALANCED_NODE, * PRTL_BALANCED_NODE;

#define RTL_BALANCED_NODE_GET_PARENT_POINTER(Node) \
    ((PRTL_BALANCED_NODE)((Node)->ParentValue & ~RTL_BALANCED_NODE_RESERVED_PARENT_MASK))

    // Portability

    typedef struct _SINGLE_LIST_ENTRY32
    {
        ULONG Next;
    } SINGLE_LIST_ENTRY32, * PSINGLE_LIST_ENTRY32;

    typedef struct _STRING32
    {
        USHORT Length;
        USHORT MaximumLength;
        ULONG Buffer;
    } STRING32, * PSTRING32;

    typedef STRING32 UNICODE_STRING32, * PUNICODE_STRING32;
    typedef STRING32 ANSI_STRING32, * PANSI_STRING32;

    typedef struct _STRING64
    {
        USHORT Length;
        USHORT MaximumLength;
        ULONGLONG Buffer;
    } STRING64, * PSTRING64;

    typedef STRING64 UNICODE_STRING64, * PUNICODE_STRING64;
    typedef STRING64 ANSI_STRING64, * PANSI_STRING64;

    // Object attributes

#define OBJ_PROTECT_CLOSE                   0x00000001L
#define OBJ_INHERIT                         0x00000002L
#define OBJ_AUDIT_OBJECT_CLOSE              0x00000004L
#define OBJ_NO_RIGHTS_UPGRADE               0x00000008L
#define OBJ_PERMANENT                       0x00000010L
#define OBJ_EXCLUSIVE                       0x00000020L
#define OBJ_CASE_INSENSITIVE                0x00000040L
#define OBJ_OPENIF                          0x00000080L
#define OBJ_OPENLINK                        0x00000100L
#define OBJ_KERNEL_HANDLE                   0x00000200L
#define OBJ_FORCE_ACCESS_CHECK              0x00000400L
#define OBJ_IGNORE_IMPERSONATED_DEVICEMAP   0x00000800L
#define OBJ_DONT_REPARSE                    0x00001000L
#define OBJ_VALID_ATTRIBUTES                0x00001FF2L

    typedef struct _OBJECT_ATTRIBUTES
    {
        ULONG Length;
        HANDLE RootDirectory;
        PUNICODE_STRING ObjectName;
        ULONG Attributes;
        PVOID SecurityDescriptor; // PSECURITY_DESCRIPTOR;
        PVOID SecurityQualityOfService; // PSECURITY_QUALITY_OF_SERVICE
    } OBJECT_ATTRIBUTES, * POBJECT_ATTRIBUTES;

    typedef const OBJECT_ATTRIBUTES* PCOBJECT_ATTRIBUTES;

#define InitializeObjectAttributes(p, n, a, r, s) { \
    (p)->Length = sizeof(OBJECT_ATTRIBUTES); \
    (p)->RootDirectory = r; \
    (p)->Attributes = a; \
    (p)->ObjectName = n; \
    (p)->SecurityDescriptor = s; \
    (p)->SecurityQualityOfService = NULL; \
    }

#define RTL_CONSTANT_OBJECT_ATTRIBUTES(n, a) { sizeof(OBJECT_ATTRIBUTES), NULL, n, a, NULL, NULL }
#define RTL_INIT_OBJECT_ATTRIBUTES(n, a) RTL_CONSTANT_OBJECT_ATTRIBUTES(n, a)

#define OBJ_NAME_PATH_SEPARATOR ((WCHAR)L'\\')
#define OBJ_NAME_ALTPATH_SEPARATOR ((WCHAR)L'/')

    // Portability

    typedef struct _OBJECT_ATTRIBUTES64
    {
        ULONG Length;
        ULONG64 RootDirectory;
        ULONG64 ObjectName;
        ULONG Attributes;
        ULONG64 SecurityDescriptor;
        ULONG64 SecurityQualityOfService;
    } OBJECT_ATTRIBUTES64, * POBJECT_ATTRIBUTES64;

    typedef const OBJECT_ATTRIBUTES64* PCOBJECT_ATTRIBUTES64;

    typedef struct _OBJECT_ATTRIBUTES32
    {
        ULONG Length;
        ULONG RootDirectory;
        ULONG ObjectName;
        ULONG Attributes;
        ULONG SecurityDescriptor;
        ULONG SecurityQualityOfService;
    } OBJECT_ATTRIBUTES32, * POBJECT_ATTRIBUTES32;

    typedef const OBJECT_ATTRIBUTES32* PCOBJECT_ATTRIBUTES32;

    // Product types

    typedef enum _NT_PRODUCT_TYPE
    {
        NtProductWinNt = 1,
        NtProductLanManNt,
        NtProductServer
    } NT_PRODUCT_TYPE, * PNT_PRODUCT_TYPE;

    typedef enum _SUITE_TYPE
    {
        SmallBusiness,
        Enterprise,
        BackOffice,
        CommunicationServer,
        TerminalServer,
        SmallBusinessRestricted,
        EmbeddedNT,
        DataCenter,
        SingleUserTS,
        Personal,
        Blade,
        EmbeddedRestricted,
        SecurityAppliance,
        StorageServer,
        ComputeServer,
        WHServer,
        PhoneNT,
        MaxSuiteType
    } SUITE_TYPE;

    // Specific

    typedef struct _CLIENT_ID
    {
        HANDLE UniqueProcess;
        HANDLE UniqueThread;
    } CLIENT_ID, * PCLIENT_ID;

    typedef struct _CLIENT_ID32
    {
        ULONG UniqueProcess;
        ULONG UniqueThread;
    } CLIENT_ID32, * PCLIENT_ID32;

    typedef struct _CLIENT_ID64
    {
        ULONGLONG UniqueProcess;
        ULONGLONG UniqueThread;
    } CLIENT_ID64, * PCLIENT_ID64;

#include <pshpack4.h>

    typedef struct _KSYSTEM_TIME
    {
        ULONG LowPart;
        LONG High1Time;
        LONG High2Time;
    } KSYSTEM_TIME, * PKSYSTEM_TIME;

#include <poppack.h>

#ifndef AFFINITY_MASK
#define AFFINITY_MASK(n) ((KAFFINITY)1 << (n))
#endif

#ifndef FlagOn
#define FlagOn(_F, _SF) ((_F) & (_SF))
#endif
#ifndef BooleanFlagOn
#define BooleanFlagOn(F, SF) ((BOOLEAN)(((F) & (SF)) != 0))
#endif
#ifndef SetFlag
#define SetFlag(_F, _SF) ((_F) |= (_SF))
#endif
#ifndef ClearFlag
#define ClearFlag(_F, _SF) ((_F) &= ~(_SF))
#endif

#endif

#endif
    /*
     * National Language Support functions
     *
     * This file is part of System Informer.
     */

#ifndef _NTNLS_H
#define _NTNLS_H

#define MAXIMUM_LEADBYTES 12

    typedef struct _CPTABLEINFO
    {
        USHORT CodePage;
        USHORT MaximumCharacterSize;
        USHORT DefaultChar;
        USHORT UniDefaultChar;
        USHORT TransDefaultChar;
        USHORT TransUniDefaultChar;
        USHORT DBCSCodePage;
        UCHAR LeadByte[MAXIMUM_LEADBYTES];
        PUSHORT MultiByteTable;
        PVOID WideCharTable;
        PUSHORT DBCSRanges;
        PUSHORT DBCSOffsets;
    } CPTABLEINFO, * PCPTABLEINFO;

    typedef struct _NLSTABLEINFO
    {
        CPTABLEINFO OemTableInfo;
        CPTABLEINFO AnsiTableInfo;
        PUSHORT UpperCaseTable;
        PUSHORT LowerCaseTable;
    } NLSTABLEINFO, * PNLSTABLEINFO;

#if (PHNT_MODE != PHNT_MODE_KERNEL)
    NTSYSAPI USHORT NlsAnsiCodePage;
    NTSYSAPI BOOLEAN NlsMbCodePageTag;
    NTSYSAPI BOOLEAN NlsMbOemCodePageTag;
#endif

#endif
#endif

    /*
     * Kernel executive support library
     *
     * This file is part of System Informer.
     */

#ifndef _NTKEAPI_H
#define _NTKEAPI_H

#if (PHNT_MODE != PHNT_MODE_KERNEL)
#define LOW_PRIORITY 0 // Lowest thread priority level
#define LOW_REALTIME_PRIORITY 16 // Lowest realtime priority level
#define HIGH_PRIORITY 31 // Highest thread priority level
#define MAXIMUM_PRIORITY 32 // Number of thread priority levels
#endif

    typedef enum _KTHREAD_STATE
    {
        Initialized,
        Ready,
        Running,
        Standby,
        Terminated,
        Waiting,
        Transition,
        DeferredReady,
        GateWaitObsolete,
        WaitingForProcessInSwap,
        MaximumThreadState
    } KTHREAD_STATE, * PKTHREAD_STATE;

    // private
    typedef enum _KHETERO_CPU_POLICY
    {
        KHeteroCpuPolicyAll = 0,
        KHeteroCpuPolicyLarge = 1,
        KHeteroCpuPolicyLargeOrIdle = 2,
        KHeteroCpuPolicySmall = 3,
        KHeteroCpuPolicySmallOrIdle = 4,
        KHeteroCpuPolicyDynamic = 5,
        KHeteroCpuPolicyStaticMax = 5, // valid
        KHeteroCpuPolicyBiasedSmall = 6,
        KHeteroCpuPolicyBiasedLarge = 7,
        KHeteroCpuPolicyDefault = 8,
        KHeteroCpuPolicyMax = 9
    } KHETERO_CPU_POLICY, * PKHETERO_CPU_POLICY;

#if (PHNT_MODE != PHNT_MODE_KERNEL)

    typedef enum _KWAIT_REASON
    {
        Executive,
        FreePage,
        PageIn,
        PoolAllocation,
        DelayExecution,
        Suspended,
        UserRequest,
        WrExecutive,
        WrFreePage,
        WrPageIn,
        WrPoolAllocation,
        WrDelayExecution,
        WrSuspended,
        WrUserRequest,
        WrEventPair,
        WrQueue,
        WrLpcReceive,
        WrLpcReply,
        WrVirtualMemory,
        WrPageOut,
        WrRendezvous,
        WrKeyedEvent,
        WrTerminated,
        WrProcessInSwap,
        WrCpuRateControl,
        WrCalloutStack,
        WrKernel,
        WrResource,
        WrPushLock,
        WrMutex,
        WrQuantumEnd,
        WrDispatchInt,
        WrPreempted,
        WrYieldExecution,
        WrFastMutex,
        WrGuardedMutex,
        WrRundown,
        WrAlertByThreadId,
        WrDeferredPreempt,
        WrPhysicalFault,
        WrIoRing,
        WrMdlCache,
        MaximumWaitReason
    } KWAIT_REASON, * PKWAIT_REASON;

    typedef enum _KPROFILE_SOURCE
    {
        ProfileTime,
        ProfileAlignmentFixup,
        ProfileTotalIssues,
        ProfilePipelineDry,
        ProfileLoadInstructions,
        ProfilePipelineFrozen,
        ProfileBranchInstructions,
        ProfileTotalNonissues,
        ProfileDcacheMisses,
        ProfileIcacheMisses,
        ProfileCacheMisses,
        ProfileBranchMispredictions,
        ProfileStoreInstructions,
        ProfileFpInstructions,
        ProfileIntegerInstructions,
        Profile2Issue,
        Profile3Issue,
        Profile4Issue,
        ProfileSpecialInstructions,
        ProfileTotalCycles,
        ProfileIcacheIssues,
        ProfileDcacheAccesses,
        ProfileMemoryBarrierCycles,
        ProfileLoadLinkedIssues,
        ProfileMaximum
    } KPROFILE_SOURCE;

#endif

#if (PHNT_MODE != PHNT_MODE_KERNEL)

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtCallbackReturn(
            _In_reads_bytes_opt_(OutputLength) PVOID OutputBuffer,
            _In_ ULONG OutputLength,
            _In_ NTSTATUS Status
        );

#if (PHNT_VERSION >= PHNT_VISTA)
    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtFlushProcessWriteBuffers(
            VOID
        );
#endif

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtQueryDebugFilterState(
            _In_ ULONG ComponentId,
            _In_ ULONG Level
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtSetDebugFilterState(
            _In_ ULONG ComponentId,
            _In_ ULONG Level,
            _In_ BOOLEAN State
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtYieldExecution(
            VOID
        );

#endif

#endif
    /*
     * Loader support functions
     *
     * This file is part of System Informer.
     */

#ifndef _NTLDR_H
#define _NTLDR_H

     // DLLs

    typedef BOOLEAN(NTAPI* PLDR_INIT_ROUTINE)(
        _In_ PVOID DllHandle,
        _In_ ULONG Reason,
        _In_opt_ PVOID Context
        );

    // symbols
    typedef struct _LDR_SERVICE_TAG_RECORD
    {
        struct _LDR_SERVICE_TAG_RECORD* Next;
        ULONG ServiceTag;
    } LDR_SERVICE_TAG_RECORD, * PLDR_SERVICE_TAG_RECORD;

    // symbols
    typedef struct _LDRP_CSLIST
    {
        PSINGLE_LIST_ENTRY Tail;
    } LDRP_CSLIST, * PLDRP_CSLIST;

    // symbols
    typedef enum _LDR_DDAG_STATE
    {
        LdrModulesMerged = -5,
        LdrModulesInitError = -4,
        LdrModulesSnapError = -3,
        LdrModulesUnloaded = -2,
        LdrModulesUnloading = -1,
        LdrModulesPlaceHolder = 0,
        LdrModulesMapping = 1,
        LdrModulesMapped = 2,
        LdrModulesWaitingForDependencies = 3,
        LdrModulesSnapping = 4,
        LdrModulesSnapped = 5,
        LdrModulesCondensed = 6,
        LdrModulesReadyToInit = 7,
        LdrModulesInitializing = 8,
        LdrModulesReadyToRun = 9
    } LDR_DDAG_STATE;

    // symbols
    typedef struct _LDR_DDAG_NODE
    {
        LIST_ENTRY Modules;
        PLDR_SERVICE_TAG_RECORD ServiceTagList;
        ULONG LoadCount;
        ULONG LoadWhileUnloadingCount;
        ULONG LowestLink;
        union
        {
            LDRP_CSLIST Dependencies;
            SINGLE_LIST_ENTRY RemovalLink;
        };
        LDRP_CSLIST IncomingDependencies;
        LDR_DDAG_STATE State;
        SINGLE_LIST_ENTRY CondenseLink;
        ULONG PreorderNumber;
    } LDR_DDAG_NODE, * PLDR_DDAG_NODE;

    // rev
    typedef struct _LDR_DEPENDENCY_RECORD
    {
        SINGLE_LIST_ENTRY DependencyLink;
        PLDR_DDAG_NODE DependencyNode;
        SINGLE_LIST_ENTRY IncomingDependencyLink;
        PLDR_DDAG_NODE IncomingDependencyNode;
    } LDR_DEPENDENCY_RECORD, * PLDR_DEPENDENCY_RECORD;

    // symbols
    typedef enum _LDR_DLL_LOAD_REASON
    {
        LoadReasonStaticDependency,
        LoadReasonStaticForwarderDependency,
        LoadReasonDynamicForwarderDependency,
        LoadReasonDelayloadDependency,
        LoadReasonDynamicLoad,
        LoadReasonAsImageLoad,
        LoadReasonAsDataLoad,
        LoadReasonEnclavePrimary, // since REDSTONE3
        LoadReasonEnclaveDependency,
        LoadReasonPatchImage, // since WIN11
        LoadReasonUnknown = -1
    } LDR_DLL_LOAD_REASON, * PLDR_DLL_LOAD_REASON;

    typedef enum _LDR_HOT_PATCH_STATE
    {
        LdrHotPatchBaseImage,
        LdrHotPatchNotApplied,
        LdrHotPatchAppliedReverse,
        LdrHotPatchAppliedForward,
        LdrHotPatchFailedToPatch,
        LdrHotPatchStateMax,
    } LDR_HOT_PATCH_STATE, * PLDR_HOT_PATCH_STATE;

    typedef struct _ACTIVATION_CONTEXT* PACTIVATION_CONTEXT;
    typedef struct _LDRP_LOAD_CONTEXT* PLDRP_LOAD_CONTEXT;

    // LDR_DATA_TABLE_ENTRY->Flags
#define LDRP_PACKAGED_BINARY 0x00000001
#define LDRP_MARKED_FOR_REMOVAL 0x00000002
#define LDRP_IMAGE_DLL 0x00000004
#define LDRP_LOAD_NOTIFICATIONS_SENT 0x00000008
#define LDRP_TELEMETRY_ENTRY_PROCESSED 0x00000010
#define LDRP_PROCESS_STATIC_IMPORT 0x00000020
#define LDRP_IN_LEGACY_LISTS 0x00000040
#define LDRP_IN_INDEXES 0x00000080
#define LDRP_SHIM_DLL 0x00000100
#define LDRP_IN_EXCEPTION_TABLE 0x00000200
#define LDRP_LOAD_IN_PROGRESS 0x00001000
#define LDRP_LOAD_CONFIG_PROCESSED 0x00002000
#define LDRP_ENTRY_PROCESSED 0x00004000
#define LDRP_PROTECT_DELAY_LOAD 0x00008000
#define LDRP_DONT_CALL_FOR_THREADS 0x00040000
#define LDRP_PROCESS_ATTACH_CALLED 0x00080000
#define LDRP_PROCESS_ATTACH_FAILED 0x00100000
#define LDRP_COR_DEFERRED_VALIDATE 0x00200000
#define LDRP_COR_IMAGE 0x00400000
#define LDRP_DONT_RELOCATE 0x00800000
#define LDRP_COR_IL_ONLY 0x01000000
#define LDRP_CHPE_IMAGE 0x02000000
#define LDRP_CHPE_EMULATOR_IMAGE 0x04000000
#define LDRP_REDIRECTED 0x10000000
#define LDRP_COMPAT_DATABASE_PROCESSED 0x80000000

#define LDR_DATA_TABLE_ENTRY_SIZE_WINXP FIELD_OFFSET(LDR_DATA_TABLE_ENTRY, DdagNode)
#define LDR_DATA_TABLE_ENTRY_SIZE_WIN7 FIELD_OFFSET(LDR_DATA_TABLE_ENTRY, BaseNameHashValue)
#define LDR_DATA_TABLE_ENTRY_SIZE_WIN8 FIELD_OFFSET(LDR_DATA_TABLE_ENTRY, ImplicitPathOptions)
#define LDR_DATA_TABLE_ENTRY_SIZE_WIN10 FIELD_OFFSET(LDR_DATA_TABLE_ENTRY, SigningLevel)
#define LDR_DATA_TABLE_ENTRY_SIZE_WIN11 sizeof(LDR_DATA_TABLE_ENTRY)

// symbols
    typedef struct _LDR_DATA_TABLE_ENTRY
    {
        LIST_ENTRY InLoadOrderLinks;
        LIST_ENTRY InMemoryOrderLinks;
        LIST_ENTRY InInitializationOrderLinks;
        PVOID DllBase;
        PLDR_INIT_ROUTINE EntryPoint;
        ULONG SizeOfImage;
        UNICODE_STRING FullDllName;
        UNICODE_STRING BaseDllName;
        union
        {
            UCHAR FlagGroup[4];
            ULONG Flags;
            struct
            {
                ULONG PackagedBinary : 1;
                ULONG MarkedForRemoval : 1;
                ULONG ImageDll : 1;
                ULONG LoadNotificationsSent : 1;
                ULONG TelemetryEntryProcessed : 1;
                ULONG ProcessStaticImport : 1;
                ULONG InLegacyLists : 1;
                ULONG InIndexes : 1;
                ULONG ShimDll : 1;
                ULONG InExceptionTable : 1;
                ULONG ReservedFlags1 : 2;
                ULONG LoadInProgress : 1;
                ULONG LoadConfigProcessed : 1;
                ULONG EntryProcessed : 1;
                ULONG ProtectDelayLoad : 1;
                ULONG ReservedFlags3 : 2;
                ULONG DontCallForThreads : 1;
                ULONG ProcessAttachCalled : 1;
                ULONG ProcessAttachFailed : 1;
                ULONG CorDeferredValidate : 1;
                ULONG CorImage : 1;
                ULONG DontRelocate : 1;
                ULONG CorILOnly : 1;
                ULONG ChpeImage : 1;
                ULONG ChpeEmulatorImage : 1;
                ULONG ReservedFlags5 : 1;
                ULONG Redirected : 1;
                ULONG ReservedFlags6 : 2;
                ULONG CompatDatabaseProcessed : 1;
            };
        };
        USHORT ObsoleteLoadCount;
        USHORT TlsIndex;
        LIST_ENTRY HashLinks;
        ULONG TimeDateStamp;
        PACTIVATION_CONTEXT EntryPointActivationContext;
        PVOID Lock; // RtlAcquireSRWLockExclusive
        PLDR_DDAG_NODE DdagNode;
        LIST_ENTRY NodeModuleLink;
        PLDRP_LOAD_CONTEXT LoadContext;
        PVOID ParentDllBase;
        PVOID SwitchBackContext;
        RTL_BALANCED_NODE BaseAddressIndexNode;
        RTL_BALANCED_NODE MappingInfoIndexNode;
        ULONG_PTR OriginalBase;
        LARGE_INTEGER LoadTime;
        ULONG BaseNameHashValue;
        LDR_DLL_LOAD_REASON LoadReason; // since WIN8
        ULONG ImplicitPathOptions;
        ULONG ReferenceCount; // since WIN10
        ULONG DependentLoadFlags;
        UCHAR SigningLevel; // since REDSTONE2
        ULONG CheckSum; // since 22H1
        PVOID ActivePatchImageBase;
        LDR_HOT_PATCH_STATE HotPatchState;
    } LDR_DATA_TABLE_ENTRY, * PLDR_DATA_TABLE_ENTRY;

#define LDR_IS_DATAFILE(DllHandle) (((ULONG_PTR)(DllHandle)) & (ULONG_PTR)1)
#define LDR_IS_IMAGEMAPPING(DllHandle) (((ULONG_PTR)(DllHandle)) & (ULONG_PTR)2)
#define LDR_IS_RESOURCE(DllHandle) (LDR_IS_IMAGEMAPPING(DllHandle) || LDR_IS_DATAFILE(DllHandle))
#define LDR_MAPPEDVIEW_TO_DATAFILE(BaseAddress) ((PVOID)(((ULONG_PTR)(BaseAddress)) | (ULONG_PTR)1))
#define LDR_MAPPEDVIEW_TO_IMAGEMAPPING(BaseAddress) ((PVOID)(((ULONG_PTR)(BaseAddress)) | (ULONG_PTR)2))
#define LDR_DATAFILE_TO_MAPPEDVIEW(DllHandle) ((PVOID)(((ULONG_PTR)(DllHandle)) & ~(ULONG_PTR)1))
#define LDR_IMAGEMAPPING_TO_MAPPEDVIEW(DllHandle) ((PVOID)(((ULONG_PTR)(DllHandle)) & ~(ULONG_PTR)2))

#if (PHNT_MODE != PHNT_MODE_KERNEL)

    NTSYSAPI
        NTSTATUS
        NTAPI
        LdrLoadDll(
            _In_opt_ PWSTR DllPath,
            _In_opt_ PULONG DllCharacteristics,
            _In_ PUNICODE_STRING DllName,
            _Out_ PVOID* DllHandle
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        LdrUnloadDll(
            _In_ PVOID DllHandle
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        LdrGetDllHandle(
            _In_opt_ PWSTR DllPath,
            _In_opt_ PULONG DllCharacteristics,
            _In_ PUNICODE_STRING DllName,
            _Out_ PVOID* DllHandle
        );

#define LDR_GET_DLL_HANDLE_EX_UNCHANGED_REFCOUNT 0x00000001
#define LDR_GET_DLL_HANDLE_EX_PIN 0x00000002

    NTSYSAPI
        NTSTATUS
        NTAPI
        LdrGetDllHandleEx(
            _In_ ULONG Flags,
            _In_opt_ PWSTR DllPath,
            _In_opt_ PULONG DllCharacteristics,
            _In_ PUNICODE_STRING DllName,
            _Out_ PVOID* DllHandle
        );

#if (PHNT_VERSION >= PHNT_WIN7)
    // rev
    NTSYSAPI
        NTSTATUS
        NTAPI
        LdrGetDllHandleByMapping(
            _In_ PVOID BaseAddress,
            _Out_ PVOID* DllHandle
        );
#endif

#if (PHNT_VERSION >= PHNT_WIN7)
    // rev
    NTSYSAPI
        NTSTATUS
        NTAPI
        LdrGetDllHandleByName(
            _In_opt_ PUNICODE_STRING BaseDllName,
            _In_opt_ PUNICODE_STRING FullDllName,
            _Out_ PVOID* DllHandle
        );
#endif

#if (PHNT_VERSION >= PHNT_WIN8)
    // rev
    NTSYSAPI
        NTSTATUS
        NTAPI
        LdrGetDllFullName(
            _In_ PVOID DllHandle,
            _Out_ PUNICODE_STRING FullDllName
        );

    // rev
    NTSYSAPI
        NTSTATUS
        NTAPI
        LdrGetDllPath(
            _In_  PCWSTR DllName,
            _In_  ULONG  Flags, // LOAD_LIBRARY_SEARCH_*
            _Out_ PWSTR* DllPath,
            _Out_ PWSTR* SearchPaths
        );

    // rev
    NTSYSAPI
        NTSTATUS
        NTAPI
        LdrGetDllDirectory(
            _Out_ PUNICODE_STRING DllDirectory
        );

    // rev
    NTSYSAPI
        NTSTATUS
        NTAPI
        LdrSetDllDirectory(
            _In_ PUNICODE_STRING DllDirectory
        );
#endif

#define LDR_ADDREF_DLL_PIN 0x00000001

    NTSYSAPI
        NTSTATUS
        NTAPI
        LdrAddRefDll(
            _In_ ULONG Flags,
            _In_ PVOID DllHandle
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        LdrGetProcedureAddress(
            _In_ PVOID DllHandle,
            _In_opt_ PANSI_STRING ProcedureName,
            _In_opt_ ULONG ProcedureNumber,
            _Out_ PVOID* ProcedureAddress
        );

    // rev
#define LDR_GET_PROCEDURE_ADDRESS_DONT_RECORD_FORWARDER 0x00000001

#if (PHNT_VERSION >= PHNT_VISTA)
// private
    NTSYSAPI
        NTSTATUS
        NTAPI
        LdrGetProcedureAddressEx(
            _In_ PVOID DllHandle,
            _In_opt_ PANSI_STRING ProcedureName,
            _In_opt_ ULONG ProcedureNumber,
            _Out_ PVOID* ProcedureAddress,
            _In_ ULONG Flags
        );
#endif

    NTSYSAPI
        NTSTATUS
        NTAPI
        LdrGetKnownDllSectionHandle(
            _In_ PCWSTR DllName,
            _In_ BOOLEAN KnownDlls32,
            _Out_ PHANDLE Section
        );

#if (PHNT_VERSION >= PHNT_THRESHOLD)
    // rev
    NTSYSAPI
        NTSTATUS
        NTAPI
        LdrGetProcedureAddressForCaller(
            _In_ PVOID DllHandle,
            _In_opt_ PANSI_STRING ProcedureName,
            _In_opt_ ULONG ProcedureNumber,
            _Out_ PVOID* ProcedureAddress,
            _In_ ULONG Flags,
            _In_ PVOID* Callback
        );
#endif

#define LDR_LOCK_LOADER_LOCK_FLAG_RAISE_ON_ERRORS 0x00000001
#define LDR_LOCK_LOADER_LOCK_FLAG_TRY_ONLY 0x00000002

#define LDR_LOCK_LOADER_LOCK_DISPOSITION_INVALID 0
#define LDR_LOCK_LOADER_LOCK_DISPOSITION_LOCK_ACQUIRED 1
#define LDR_LOCK_LOADER_LOCK_DISPOSITION_LOCK_NOT_ACQUIRED 2

    NTSYSAPI
        NTSTATUS
        NTAPI
        LdrLockLoaderLock(
            _In_ ULONG Flags,
            _Out_opt_ ULONG* Disposition,
            _Out_opt_ PVOID* Cookie
        );

#define LDR_UNLOCK_LOADER_LOCK_FLAG_RAISE_ON_ERRORS 0x00000001

    NTSYSAPI
        NTSTATUS
        NTAPI
        LdrUnlockLoaderLock(
            _In_ ULONG Flags,
            _In_opt_ PVOID Cookie
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        LdrRelocateImage(
            _In_ PVOID NewBase,
            _In_opt_ PSTR LoaderName,
            _In_ NTSTATUS Success,
            _In_ NTSTATUS Conflict,
            _In_ NTSTATUS Invalid
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        LdrRelocateImageWithBias(
            _In_ PVOID NewBase,
            _In_opt_ LONGLONG Bias,
            _In_opt_ PSTR LoaderName,
            _In_ NTSTATUS Success,
            _In_ NTSTATUS Conflict,
            _In_ NTSTATUS Invalid
        );

    NTSYSAPI
        PIMAGE_BASE_RELOCATION
        NTAPI
        LdrProcessRelocationBlock(
            _In_ ULONG_PTR VA,
            _In_ ULONG SizeOfBlock,
            _In_ PUSHORT NextOffset,
            _In_ LONG_PTR Diff
        );

#if (PHNT_VERSION >= PHNT_WIN8)
    NTSYSAPI
        PIMAGE_BASE_RELOCATION
        NTAPI
        LdrProcessRelocationBlockEx(
            _In_ ULONG Machine, // IMAGE_FILE_MACHINE_AMD64|IMAGE_FILE_MACHINE_ARM|IMAGE_FILE_MACHINE_THUMB|IMAGE_FILE_MACHINE_ARMNT
            _In_ ULONG_PTR VA,
            _In_ ULONG SizeOfBlock,
            _In_ PUSHORT NextOffset,
            _In_ LONG_PTR Diff
        );
#endif

    NTSYSAPI
        BOOLEAN
        NTAPI
        LdrVerifyMappedImageMatchesChecksum(
            _In_ PVOID BaseAddress,
            _In_ SIZE_T NumberOfBytes,
            _In_ ULONG FileLength
        );

    typedef VOID(NTAPI* PLDR_IMPORT_MODULE_CALLBACK)(
        _In_ PVOID Parameter,
        _In_ PSTR ModuleName
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        LdrVerifyImageMatchesChecksum(
            _In_ HANDLE ImageFileHandle,
            _In_opt_ PLDR_IMPORT_MODULE_CALLBACK ImportCallbackRoutine,
            _In_ PVOID ImportCallbackParameter,
            _Out_opt_ PUSHORT ImageCharacteristics
        );

    // private
    typedef struct _LDR_IMPORT_CALLBACK_INFO
    {
        PLDR_IMPORT_MODULE_CALLBACK ImportCallbackRoutine;
        PVOID ImportCallbackParameter;
    } LDR_IMPORT_CALLBACK_INFO, * PLDR_IMPORT_CALLBACK_INFO;

    // private
    typedef struct _LDR_SECTION_INFO
    {
        HANDLE SectionHandle;
        ACCESS_MASK DesiredAccess;
        POBJECT_ATTRIBUTES ObjA;
        ULONG SectionPageProtection;
        ULONG AllocationAttributes;
    } LDR_SECTION_INFO, * PLDR_SECTION_INFO;

    // private
    typedef struct _LDR_VERIFY_IMAGE_INFO
    {
        ULONG Size;
        ULONG Flags;
        LDR_IMPORT_CALLBACK_INFO CallbackInfo;
        LDR_SECTION_INFO SectionInfo;
        USHORT ImageCharacteristics;
    } LDR_VERIFY_IMAGE_INFO, * PLDR_VERIFY_IMAGE_INFO;

#if (PHNT_VERSION >= PHNT_VISTA)
    // private
    NTSYSAPI
        NTSTATUS
        NTAPI
        LdrVerifyImageMatchesChecksumEx(
            _In_ HANDLE ImageFileHandle,
            _Inout_ PLDR_VERIFY_IMAGE_INFO VerifyInfo
        );
#endif

#if (PHNT_VERSION >= PHNT_VISTA)
    // private
    NTSYSAPI
        NTSTATUS
        NTAPI
        LdrQueryModuleServiceTags(
            _In_ PVOID DllHandle,
            _Out_writes_(*BufferSize) PULONG ServiceTagBuffer,
            _Inout_ PULONG BufferSize
        );
#endif

    // begin_msdn:"DLL Load Notification"

#define LDR_DLL_NOTIFICATION_REASON_LOADED 1
#define LDR_DLL_NOTIFICATION_REASON_UNLOADED 2

    typedef struct _LDR_DLL_LOADED_NOTIFICATION_DATA
    {
        ULONG Flags;
        PUNICODE_STRING FullDllName;
        PUNICODE_STRING BaseDllName;
        PVOID DllBase;
        ULONG SizeOfImage;
    } LDR_DLL_LOADED_NOTIFICATION_DATA, * PLDR_DLL_LOADED_NOTIFICATION_DATA;

    typedef struct _LDR_DLL_UNLOADED_NOTIFICATION_DATA
    {
        ULONG Flags;
        PCUNICODE_STRING FullDllName;
        PCUNICODE_STRING BaseDllName;
        PVOID DllBase;
        ULONG SizeOfImage;
    } LDR_DLL_UNLOADED_NOTIFICATION_DATA, * PLDR_DLL_UNLOADED_NOTIFICATION_DATA;

    typedef union _LDR_DLL_NOTIFICATION_DATA
    {
        LDR_DLL_LOADED_NOTIFICATION_DATA Loaded;
        LDR_DLL_UNLOADED_NOTIFICATION_DATA Unloaded;
    } LDR_DLL_NOTIFICATION_DATA, * PLDR_DLL_NOTIFICATION_DATA;

    typedef VOID(NTAPI* PLDR_DLL_NOTIFICATION_FUNCTION)(
        _In_ ULONG NotificationReason,
        _In_ PLDR_DLL_NOTIFICATION_DATA NotificationData,
        _In_opt_ PVOID Context
        );

#if (PHNT_VERSION >= PHNT_VISTA)

    NTSYSAPI
        NTSTATUS
        NTAPI
        LdrRegisterDllNotification(
            _In_ ULONG Flags,
            _In_ PLDR_DLL_NOTIFICATION_FUNCTION NotificationFunction,
            _In_opt_ PVOID Context,
            _Out_ PVOID* Cookie
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        LdrUnregisterDllNotification(
            _In_ PVOID Cookie
        );

#endif

    // end_msdn

    // rev
    NTSYSAPI
        PUNICODE_STRING
        NTAPI
        LdrStandardizeSystemPath(
            _In_ PUNICODE_STRING SystemPath
        );

#if (PHNT_VERSION >= PHNT_WINBLUE)
    typedef struct _LDR_FAILURE_DATA
    {
        NTSTATUS Status;
        WCHAR DllName[0x20];
        WCHAR AdditionalInfo[0x20];
    } LDR_FAILURE_DATA, * PLDR_FAILURE_DATA;

    NTSYSAPI
        PLDR_FAILURE_DATA
        NTAPI
        LdrGetFailureData(
            VOID
        );
#endif

    // private
    typedef struct _PS_MITIGATION_OPTIONS_MAP
    {
        ULONG_PTR Map[3]; // 2 < 20H1
    } PS_MITIGATION_OPTIONS_MAP, * PPS_MITIGATION_OPTIONS_MAP;

    // private
    typedef struct _PS_MITIGATION_AUDIT_OPTIONS_MAP
    {
        ULONG_PTR Map[3]; // 2 < 20H1
    } PS_MITIGATION_AUDIT_OPTIONS_MAP, * PPS_MITIGATION_AUDIT_OPTIONS_MAP;

    // private
    typedef struct _PS_SYSTEM_DLL_INIT_BLOCK
    {
        ULONG Size;
        ULONG_PTR SystemDllWowRelocation;
        ULONG_PTR SystemDllNativeRelocation;
        ULONG_PTR Wow64SharedInformation[16]; // use WOW64_SHARED_INFORMATION as index
        ULONG RngData;
        union
        {
            ULONG Flags;
            struct
            {
                ULONG CfgOverride : 1;
                ULONG Reserved : 31;
            };
        };
        PS_MITIGATION_OPTIONS_MAP MitigationOptionsMap;
        ULONG_PTR CfgBitMap;
        ULONG_PTR CfgBitMapSize;
        ULONG_PTR Wow64CfgBitMap;
        ULONG_PTR Wow64CfgBitMapSize;
        PS_MITIGATION_AUDIT_OPTIONS_MAP MitigationAuditOptionsMap; // REDSTONE3
    } PS_SYSTEM_DLL_INIT_BLOCK, * PPS_SYSTEM_DLL_INIT_BLOCK;

#if (PHNT_VERSION >= PHNT_THRESHOLD)
    // rev
    NTSYSAPI PS_SYSTEM_DLL_INIT_BLOCK LdrSystemDllInitBlock;
#endif

    // Load as data table

#if (PHNT_VERSION >= PHNT_VISTA)

    typedef struct _ACTIVATION_CONTEXT* PACTIVATION_CONTEXT;

    // private
    NTSYSAPI
        NTSTATUS
        NTAPI
        LdrAddLoadAsDataTable(
            _In_ PVOID Module,
            _In_ PWSTR FilePath,
            _In_ SIZE_T Size,
            _In_ HANDLE Handle,
            _In_opt_ PACTIVATION_CONTEXT ActCtx
        );

    // private
    NTSYSAPI
        NTSTATUS
        NTAPI
        LdrRemoveLoadAsDataTable(
            _In_ PVOID InitModule,
            _Out_opt_ PVOID* BaseModule,
            _Out_opt_ PSIZE_T Size,
            _In_ ULONG Flags
        );

    // private
    NTSYSAPI
        NTSTATUS
        NTAPI
        LdrGetFileNameFromLoadAsDataTable(
            _In_ PVOID Module,
            _Out_ PVOID* pFileNamePrt
        );

#endif

    NTSYSAPI
        NTSTATUS
        NTAPI
        LdrDisableThreadCalloutsForDll(
            _In_ PVOID DllImageBase
        );

    // Resources

    NTSYSAPI
        NTSTATUS
        NTAPI
        LdrAccessResource(
            _In_ PVOID DllHandle,
            _In_ PIMAGE_RESOURCE_DATA_ENTRY ResourceDataEntry,
            _Out_opt_ PVOID* ResourceBuffer,
            _Out_opt_ ULONG* ResourceLength
        );

    typedef struct _LDR_RESOURCE_INFO
    {
        ULONG_PTR Type;
        ULONG_PTR Name;
        ULONG_PTR Language;
    } LDR_RESOURCE_INFO, * PLDR_RESOURCE_INFO;

#define RESOURCE_TYPE_LEVEL 0
#define RESOURCE_NAME_LEVEL 1
#define RESOURCE_LANGUAGE_LEVEL 2
#define RESOURCE_DATA_LEVEL 3

    NTSYSAPI
        NTSTATUS
        NTAPI
        LdrFindResource_U(
            _In_ PVOID DllHandle,
            _In_ PLDR_RESOURCE_INFO ResourceInfo,
            _In_ ULONG Level,
            _Out_ PIMAGE_RESOURCE_DATA_ENTRY* ResourceDataEntry
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        LdrFindResourceEx_U(
            _In_ ULONG Flags,
            _In_ PVOID DllHandle,
            _In_ PLDR_RESOURCE_INFO ResourceInfo,
            _In_ ULONG Level,
            _Out_ PIMAGE_RESOURCE_DATA_ENTRY* ResourceDataEntry
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        LdrFindResourceDirectory_U(
            _In_ PVOID DllHandle,
            _In_ PLDR_RESOURCE_INFO ResourceInfo,
            _In_ ULONG Level,
            _Out_ PIMAGE_RESOURCE_DIRECTORY* ResourceDirectory
        );

    // private
    typedef struct _LDR_ENUM_RESOURCE_ENTRY
    {
        union
        {
            ULONG_PTR NameOrId;
            PIMAGE_RESOURCE_DIRECTORY_STRING Name;
            struct
            {
                USHORT Id;
                USHORT NameIsPresent;
            };
        } Path[3];
        PVOID Data;
        ULONG Size;
        ULONG Reserved;
    } LDR_ENUM_RESOURCE_ENTRY, * PLDR_ENUM_RESOURCE_ENTRY;

#define NAME_FROM_RESOURCE_ENTRY(RootDirectory, Entry) \
    ((Entry)->NameIsString ? (ULONG_PTR)PTR_ADD_OFFSET((RootDirectory), (Entry)->NameOffset) : (Entry)->Id)

    NTSYSAPI
        NTSTATUS
        NTAPI
        LdrEnumResources(
            _In_ PVOID DllHandle,
            _In_ PLDR_RESOURCE_INFO ResourceInfo,
            _In_ ULONG Level,
            _Inout_ ULONG* ResourceCount,
            _Out_writes_to_opt_(*ResourceCount, *ResourceCount) PLDR_ENUM_RESOURCE_ENTRY Resources
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        LdrFindEntryForAddress(
            _In_ PVOID DllHandle,
            _Out_ PLDR_DATA_TABLE_ENTRY* Entry
        );

    // rev
    NTSYSAPI
        NTSTATUS
        NTAPI
        LdrLoadAlternateResourceModule(
            _In_ PVOID DllHandle,
            _Out_ PVOID* ResourceDllBase,
            _Out_opt_ ULONG_PTR* ResourceOffset,
            _In_ ULONG Flags
        );

    // rev
    NTSYSAPI
        NTSTATUS
        NTAPI
        LdrLoadAlternateResourceModuleEx(
            _In_ PVOID DllHandle,
            _In_ LANGID LanguageId,
            _Out_ PVOID* ResourceDllBase,
            _Out_opt_ ULONG_PTR* ResourceOffset,
            _In_ ULONG Flags
        );

    // rev
    NTSYSAPI
        BOOLEAN
        NTAPI
        LdrUnloadAlternateResourceModule(
            _In_ PVOID DllHandle
        );

    // rev
    NTSYSAPI
        BOOLEAN
        NTAPI
        LdrUnloadAlternateResourceModuleEx(
            _In_ PVOID DllHandle,
            _In_ ULONG Flags
        );

#endif // (PHNT_MODE != PHNT_MODE_KERNEL)

    // Module information

    typedef struct _RTL_PROCESS_MODULE_INFORMATION
    {
        PVOID Section;
        PVOID MappedBase;
        PVOID ImageBase;
        ULONG ImageSize;
        ULONG Flags;
        USHORT LoadOrderIndex;
        USHORT InitOrderIndex;
        USHORT LoadCount;
        USHORT OffsetToFileName;
        UCHAR FullPathName[256];
    } RTL_PROCESS_MODULE_INFORMATION, * PRTL_PROCESS_MODULE_INFORMATION;

    typedef struct _RTL_PROCESS_MODULES
    {
        ULONG NumberOfModules;
        _Field_size_(NumberOfModules) RTL_PROCESS_MODULE_INFORMATION Modules[1];
    } RTL_PROCESS_MODULES, * PRTL_PROCESS_MODULES;

    // private
    typedef struct _RTL_PROCESS_MODULE_INFORMATION_EX
    {
        USHORT NextOffset;
        RTL_PROCESS_MODULE_INFORMATION BaseInfo;
        ULONG ImageChecksum;
        ULONG TimeDateStamp;
        PVOID DefaultBase;
    } RTL_PROCESS_MODULE_INFORMATION_EX, * PRTL_PROCESS_MODULE_INFORMATION_EX;

#if (PHNT_MODE != PHNT_MODE_KERNEL)

    NTSYSAPI
        NTSTATUS
        NTAPI
        LdrQueryProcessModuleInformation(
            _In_opt_ PRTL_PROCESS_MODULES ModuleInformation,
            _In_opt_ ULONG Size,
            _Out_ PULONG ReturnedSize
        );

    typedef VOID(NTAPI* PLDR_ENUM_CALLBACK)(
        _In_ PLDR_DATA_TABLE_ENTRY ModuleInformation,
        _In_ PVOID Parameter,
        _Out_ BOOLEAN* Stop
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        LdrEnumerateLoadedModules(
            _In_ BOOLEAN ReservedFlag,
            _In_ PLDR_ENUM_CALLBACK EnumProc,
            _In_ PVOID Context
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        LdrOpenImageFileOptionsKey(
            _In_ PUNICODE_STRING SubKey,
            _In_ BOOLEAN Wow64,
            _Out_ PHANDLE NewKeyHandle
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        LdrQueryImageFileKeyOption(
            _In_ HANDLE KeyHandle,
            _In_ PCWSTR ValueName,
            _In_ ULONG Type,
            _Out_ PVOID Buffer,
            _In_ ULONG BufferSize,
            _Out_opt_ PULONG ReturnedLength
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        LdrQueryImageFileExecutionOptions(
            _In_ PUNICODE_STRING SubKey,
            _In_ PCWSTR ValueName,
            _In_ ULONG ValueSize,
            _Out_ PVOID Buffer,
            _In_ ULONG BufferSize,
            _Out_opt_ PULONG ReturnedLength
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        LdrQueryImageFileExecutionOptionsEx(
            _In_ PUNICODE_STRING SubKey,
            _In_ PCWSTR ValueName,
            _In_ ULONG Type,
            _Out_ PVOID Buffer,
            _In_ ULONG BufferSize,
            _Out_opt_ PULONG ReturnedLength,
            _In_ BOOLEAN Wow64
        );

    // private
    typedef struct _DELAYLOAD_PROC_DESCRIPTOR
    {
        ULONG ImportDescribedByName;
        union
        {
            PCSTR Name;
            ULONG Ordinal;
        } Description;
    } DELAYLOAD_PROC_DESCRIPTOR, * PDELAYLOAD_PROC_DESCRIPTOR;

    // private
    typedef struct _DELAYLOAD_INFO
    {
        ULONG Size;
        PCIMAGE_DELAYLOAD_DESCRIPTOR DelayloadDescriptor;
        PIMAGE_THUNK_DATA ThunkAddress;
        PCSTR TargetDllName;
        DELAYLOAD_PROC_DESCRIPTOR TargetApiDescriptor;
        PVOID TargetModuleBase;
        PVOID Unused;
        ULONG LastError;
    } DELAYLOAD_INFO, * PDELAYLOAD_INFO;

    // private
    typedef PVOID(NTAPI* PDELAYLOAD_FAILURE_DLL_CALLBACK)(
        _In_ ULONG NotificationReason,
        _In_ PDELAYLOAD_INFO DelayloadInfo
        );

    // rev
    typedef PVOID(NTAPI* PDELAYLOAD_FAILURE_SYSTEM_ROUTINE)(
        _In_ PCSTR DllName,
        _In_ PCSTR ProcedureName
        );

#if (PHNT_VERSION >= PHNT_THRESHOLD)
    // rev from QueryOptionalDelayLoadedAPI
    NTSYSAPI
        NTSTATUS
        NTAPI
        LdrQueryOptionalDelayLoadedAPI(
            _In_ PVOID ParentModuleBase,
            _In_ PCSTR DllName,
            _In_ PCSTR ProcedureName,
            _Reserved_ ULONG Flags
        );
#endif

#if (PHNT_VERSION >= PHNT_WIN8)
    // rev from ResolveDelayLoadedAPI
    NTSYSAPI
        PVOID
        NTAPI
        LdrResolveDelayLoadedAPI(
            _In_ PVOID ParentModuleBase,
            _In_ PCIMAGE_DELAYLOAD_DESCRIPTOR DelayloadDescriptor,
            _In_opt_ PDELAYLOAD_FAILURE_DLL_CALLBACK FailureDllHook,
            _In_opt_ PDELAYLOAD_FAILURE_SYSTEM_ROUTINE FailureSystemHook, // kernel32.DelayLoadFailureHook
            _Out_ PIMAGE_THUNK_DATA ThunkAddress,
            _Reserved_ ULONG Flags
        );

    // rev from ResolveDelayLoadsFromDll
    NTSYSAPI
        NTSTATUS
        NTAPI
        LdrResolveDelayLoadsFromDll(
            _In_ PVOID ParentModuleBase,
            _In_ PCSTR TargetDllName,
            _Reserved_ ULONG Flags
        );

    // rev from SetDefaultDllDirectories
    NTSYSAPI
        NTSTATUS
        NTAPI
        LdrSetDefaultDllDirectories(
            _In_ ULONG DirectoryFlags
        );

    // rev from AddDllDirectory
    NTSYSAPI
        NTSTATUS
        NTAPI
        LdrAddDllDirectory(
            _In_ PUNICODE_STRING NewDirectory,
            _Out_ PDLL_DIRECTORY_COOKIE Cookie
        );

    // rev from RemoveDllDirectory
    NTSYSAPI
        NTSTATUS
        NTAPI
        LdrRemoveDllDirectory(
            _In_ DLL_DIRECTORY_COOKIE Cookie
        );
#endif

    // rev
    DECLSPEC_NORETURN
        NTSYSAPI
        VOID
        NTAPI
        LdrShutdownProcess(
            VOID
        );

    // rev
    DECLSPEC_NORETURN
        NTSYSAPI
        VOID
        NTAPI
        LdrShutdownThread(
            VOID
        );

#if (PHNT_VERSION >= PHNT_WINBLUE)
    // rev
    NTSYSAPI
        NTSTATUS
        NTAPI
        LdrSetImplicitPathOptions(
            _In_ ULONG ImplicitPathOptions
        );

    // rev
    NTSYSAPI
        BOOLEAN
        NTAPI
        LdrControlFlowGuardEnforced(
            VOID
        );
#endif

#if (PHNT_VERSION >= PHNT_19H1)
    // rev
    NTSYSAPI
        BOOLEAN
        NTAPI
        LdrIsModuleSxsRedirected(
            _In_ PVOID DllHandle
        );
#endif

#if (PHNT_VERSION >= PHNT_THRESHOLD)
    // rev
    NTSYSAPI
        NTSTATUS
        NTAPI
        LdrUpdatePackageSearchPath(
            _In_ PWSTR SearchPath
        );
#endif

#if (PHNT_VERSION >= PHNT_THRESHOLD)

    // rev
#define ENCLAVE_STATE_CREATED         0x00000000ul // LdrpCreateSoftwareEnclave initial state
#define ENCLAVE_STATE_INITIALIZED     0x00000001ul // ZwInitializeEnclave successful (LdrInitializeEnclave)
#define ENCLAVE_STATE_INITIALIZED_VBS 0x00000002ul // only for ENCLAVE_TYPE_VBS (LdrInitializeEnclave)

// rev
    typedef struct _LDR_SOFTWARE_ENCLAVE
    {
        LIST_ENTRY Links; // ntdll!LdrpEnclaveList
        RTL_CRITICAL_SECTION CriticalSection;
        ULONG EnclaveType; // ENCLAVE_TYPE_*
        LONG ReferenceCount;
        ULONG EnclaveState; // ENCLAVE_STATE_*
        PVOID BaseAddress;
        SIZE_T Size;
        PVOID PreviousBaseAddress;
        LIST_ENTRY Modules; // LDR_DATA_TABLE_ENTRY.InLoadOrderLinks
        PLDR_DATA_TABLE_ENTRY PrimaryModule;
        PLDR_DATA_TABLE_ENTRY BCryptModule;
        PLDR_DATA_TABLE_ENTRY BCryptPrimitivesModule;
    } LDR_SOFTWARE_ENCLAVE, * PLDR_SOFTWARE_ENCLAVE;

    // rev from CreateEnclave
    NTSYSAPI
        NTSTATUS
        NTAPI
        LdrCreateEnclave(
            _In_ HANDLE ProcessHandle,
            _Inout_ PVOID* BaseAddress,
            _In_ ULONG Reserved,
            _In_ SIZE_T Size,
            _In_ SIZE_T InitialCommitment,
            _In_ ULONG EnclaveType,
            _In_reads_bytes_(EnclaveInformationLength) PVOID EnclaveInformation,
            _In_ ULONG EnclaveInformationLength,
            _Out_ PULONG EnclaveError
        );

    // rev from InitializeEnclave
    NTSYSAPI
        NTSTATUS
        NTAPI
        LdrInitializeEnclave(
            _In_ HANDLE ProcessHandle,
            _In_ PVOID BaseAddress,
            _In_reads_bytes_(EnclaveInformationLength) PVOID EnclaveInformation,
            _In_ ULONG EnclaveInformationLength,
            _Out_ PULONG EnclaveError
        );

    // rev from DeleteEnclave
    NTSYSAPI
        NTSTATUS
        NTAPI
        LdrDeleteEnclave(
            _In_ PVOID BaseAddress
        );

    // rev from CallEnclave
    NTSYSAPI
        NTSTATUS
        NTAPI
        LdrCallEnclave(
            _In_ PENCLAVE_ROUTINE Routine,
            _In_ ULONG Flags, // ENCLAVE_CALL_FLAG_*
            _Inout_ PVOID* RoutineParamReturn
        );

    // rev from LoadEnclaveImage
    NTSYSAPI
        NTSTATUS
        NTAPI
        LdrLoadEnclaveModule(
            _In_ PVOID BaseAddress,
            _In_opt_ PWSTR DllPath,
            _In_ PUNICODE_STRING DllName
        );

#endif

#endif // (PHNT_MODE != PHNT_MODE_KERNEL)

#endif
    /*
     * Executive support library functions
     *
     * This file is part of System Informer.
     */

#ifndef _NTEXAPI_H
#define _NTEXAPI_H


#if (PHNT_MODE != PHNT_MODE_KERNEL)

     // Thread execution

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtDelayExecution(
            _In_ BOOLEAN Alertable,
            _In_ PLARGE_INTEGER DelayInterval
        );

    // Environment values

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtQuerySystemEnvironmentValue(
            _In_ PUNICODE_STRING VariableName,
            _Out_writes_bytes_(ValueLength) PWSTR VariableValue,
            _In_ USHORT ValueLength,
            _Out_opt_ PUSHORT ReturnLength
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtSetSystemEnvironmentValue(
            _In_ PUNICODE_STRING VariableName,
            _In_ PUNICODE_STRING VariableValue
        );

#define EFI_VARIABLE_NON_VOLATILE 0x00000001
#define EFI_VARIABLE_BOOTSERVICE_ACCESS 0x00000002
#define EFI_VARIABLE_RUNTIME_ACCESS 0x00000004
#define EFI_VARIABLE_HARDWARE_ERROR_RECORD 0x00000008
#define EFI_VARIABLE_AUTHENTICATED_WRITE_ACCESS 0x00000010
#define EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS 0x00000020
#define EFI_VARIABLE_APPEND_WRITE 0x00000040
#define EFI_VARIABLE_ENHANCED_AUTHENTICATED_ACCESS 0x00000080

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtQuerySystemEnvironmentValueEx(
            _In_ PUNICODE_STRING VariableName,
            _In_ PCGUID VendorGuid,
            _Out_writes_bytes_opt_(*ValueLength) PVOID Value,
            _Inout_ PULONG ValueLength,
            _Out_opt_ PULONG Attributes // EFI_VARIABLE_*
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtSetSystemEnvironmentValueEx(
            _In_ PUNICODE_STRING VariableName,
            _In_ PCGUID VendorGuid,
            _In_reads_bytes_opt_(ValueLength) PVOID Value,
            _In_ ULONG ValueLength, // 0 = delete variable
            _In_ ULONG Attributes // EFI_VARIABLE_*
        );

    typedef enum _SYSTEM_ENVIRONMENT_INFORMATION_CLASS
    {
        SystemEnvironmentNameInformation = 1, // q: VARIABLE_NAME
        SystemEnvironmentValueInformation = 2, // q: VARIABLE_NAME_AND_VALUE
        MaxSystemEnvironmentInfoClass
    } SYSTEM_ENVIRONMENT_INFORMATION_CLASS;

    typedef struct _VARIABLE_NAME
    {
        ULONG NextEntryOffset;
        GUID VendorGuid;
        WCHAR Name[ANYSIZE_ARRAY];
    } VARIABLE_NAME, * PVARIABLE_NAME;

    typedef struct _VARIABLE_NAME_AND_VALUE
    {
        ULONG NextEntryOffset;
        ULONG ValueOffset;
        ULONG ValueLength;
        ULONG Attributes;
        GUID VendorGuid;
        WCHAR Name[ANYSIZE_ARRAY];
        //BYTE Value[ANYSIZE_ARRAY];
    } VARIABLE_NAME_AND_VALUE, * PVARIABLE_NAME_AND_VALUE;

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtEnumerateSystemEnvironmentValuesEx(
            _In_ ULONG InformationClass, // SYSTEM_ENVIRONMENT_INFORMATION_CLASS
            _Out_ PVOID Buffer,
            _Inout_ PULONG BufferLength
        );

    // EFI

    // private
    typedef struct _BOOT_ENTRY
    {
        ULONG Version;
        ULONG Length;
        ULONG Id;
        ULONG Attributes;
        ULONG FriendlyNameOffset;
        ULONG BootFilePathOffset;
        ULONG OsOptionsLength;
        _Field_size_bytes_(OsOptionsLength) UCHAR OsOptions[1];
    } BOOT_ENTRY, * PBOOT_ENTRY;

    // private
    typedef struct _BOOT_ENTRY_LIST
    {
        ULONG NextEntryOffset;
        BOOT_ENTRY BootEntry;
    } BOOT_ENTRY_LIST, * PBOOT_ENTRY_LIST;

    // private
    typedef struct _BOOT_OPTIONS
    {
        ULONG Version;
        ULONG Length;
        ULONG Timeout;
        ULONG CurrentBootEntryId;
        ULONG NextBootEntryId;
        WCHAR HeadlessRedirection[1];
    } BOOT_OPTIONS, * PBOOT_OPTIONS;

    // private
    typedef struct _FILE_PATH
    {
        ULONG Version;
        ULONG Length;
        ULONG Type;
        _Field_size_bytes_(Length) UCHAR FilePath[1];
    } FILE_PATH, * PFILE_PATH;

    // private
    typedef struct _EFI_DRIVER_ENTRY
    {
        ULONG Version;
        ULONG Length;
        ULONG Id;
        ULONG FriendlyNameOffset;
        ULONG DriverFilePathOffset;
    } EFI_DRIVER_ENTRY, * PEFI_DRIVER_ENTRY;

    // private
    typedef struct _EFI_DRIVER_ENTRY_LIST
    {
        ULONG NextEntryOffset;
        EFI_DRIVER_ENTRY DriverEntry;
    } EFI_DRIVER_ENTRY_LIST, * PEFI_DRIVER_ENTRY_LIST;

#if (PHNT_VERSION >= PHNT_WINXP)

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtAddBootEntry(
            _In_ PBOOT_ENTRY BootEntry,
            _Out_opt_ PULONG Id
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtDeleteBootEntry(
            _In_ ULONG Id
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtModifyBootEntry(
            _In_ PBOOT_ENTRY BootEntry
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtEnumerateBootEntries(
            _Out_writes_bytes_opt_(*BufferLength) PVOID Buffer,
            _Inout_ PULONG BufferLength
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtQueryBootEntryOrder(
            _Out_writes_opt_(*Count) PULONG Ids,
            _Inout_ PULONG Count
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtSetBootEntryOrder(
            _In_reads_(Count) PULONG Ids,
            _In_ ULONG Count
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtQueryBootOptions(
            _Out_writes_bytes_opt_(*BootOptionsLength) PBOOT_OPTIONS BootOptions,
            _Inout_ PULONG BootOptionsLength
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtSetBootOptions(
            _In_ PBOOT_OPTIONS BootOptions,
            _In_ ULONG FieldsToChange
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtTranslateFilePath(
            _In_ PFILE_PATH InputFilePath,
            _In_ ULONG OutputType,
            _Out_writes_bytes_opt_(*OutputFilePathLength) PFILE_PATH OutputFilePath,
            _Inout_opt_ PULONG OutputFilePathLength
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtAddDriverEntry(
            _In_ PEFI_DRIVER_ENTRY DriverEntry,
            _Out_opt_ PULONG Id
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtDeleteDriverEntry(
            _In_ ULONG Id
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtModifyDriverEntry(
            _In_ PEFI_DRIVER_ENTRY DriverEntry
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtEnumerateDriverEntries(
            _Out_writes_bytes_opt_(*BufferLength) PVOID Buffer,
            _Inout_ PULONG BufferLength
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtQueryDriverEntryOrder(
            _Out_writes_opt_(*Count) PULONG Ids,
            _Inout_ PULONG Count
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtSetDriverEntryOrder(
            _In_reads_(Count) PULONG Ids,
            _In_ ULONG Count
        );

#endif

    typedef enum _FILTER_BOOT_OPTION_OPERATION
    {
        FilterBootOptionOperationOpenSystemStore,
        FilterBootOptionOperationSetElement,
        FilterBootOptionOperationDeleteElement,
        FilterBootOptionOperationMax
    } FILTER_BOOT_OPTION_OPERATION;

#if (PHNT_VERSION >= PHNT_WIN8)

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtFilterBootOption(
            _In_ FILTER_BOOT_OPTION_OPERATION FilterOperation,
            _In_ ULONG ObjectType,
            _In_ ULONG ElementType,
            _In_reads_bytes_opt_(DataSize) PVOID Data,
            _In_ ULONG DataSize
        );

#endif

    // Event

#ifndef EVENT_QUERY_STATE
#define EVENT_QUERY_STATE 0x0001
#endif

#ifndef EVENT_MODIFY_STATE
#define EVENT_MODIFY_STATE 0x0002
#endif

#ifndef EVENT_ALL_ACCESS
#define EVENT_ALL_ACCESS (EVENT_QUERY_STATE|EVENT_MODIFY_STATE|STANDARD_RIGHTS_REQUIRED|SYNCHRONIZE)
#endif

    typedef enum _EVENT_INFORMATION_CLASS
    {
        EventBasicInformation
    } EVENT_INFORMATION_CLASS;

    typedef struct _EVENT_BASIC_INFORMATION
    {
        EVENT_TYPE EventType;
        LONG EventState;
    } EVENT_BASIC_INFORMATION, * PEVENT_BASIC_INFORMATION;

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtCreateEvent(
            _Out_ PHANDLE EventHandle,
            _In_ ACCESS_MASK DesiredAccess,
            _In_opt_ POBJECT_ATTRIBUTES ObjectAttributes,
            _In_ EVENT_TYPE EventType,
            _In_ BOOLEAN InitialState
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtOpenEvent(
            _Out_ PHANDLE EventHandle,
            _In_ ACCESS_MASK DesiredAccess,
            _In_ POBJECT_ATTRIBUTES ObjectAttributes
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtSetEvent(
            _In_ HANDLE EventHandle,
            _Out_opt_ PLONG PreviousState
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtSetEventBoostPriority(
            _In_ HANDLE EventHandle
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtClearEvent(
            _In_ HANDLE EventHandle
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtResetEvent(
            _In_ HANDLE EventHandle,
            _Out_opt_ PLONG PreviousState
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtPulseEvent(
            _In_ HANDLE EventHandle,
            _Out_opt_ PLONG PreviousState
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtQueryEvent(
            _In_ HANDLE EventHandle,
            _In_ EVENT_INFORMATION_CLASS EventInformationClass,
            _Out_writes_bytes_(EventInformationLength) PVOID EventInformation,
            _In_ ULONG EventInformationLength,
            _Out_opt_ PULONG ReturnLength
        );

    // Event Pair

#define EVENT_PAIR_ALL_ACCESS (STANDARD_RIGHTS_REQUIRED | SYNCHRONIZE)

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtCreateEventPair(
            _Out_ PHANDLE EventPairHandle,
            _In_ ACCESS_MASK DesiredAccess,
            _In_opt_ POBJECT_ATTRIBUTES ObjectAttributes
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtOpenEventPair(
            _Out_ PHANDLE EventPairHandle,
            _In_ ACCESS_MASK DesiredAccess,
            _In_ POBJECT_ATTRIBUTES ObjectAttributes
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtSetLowEventPair(
            _In_ HANDLE EventPairHandle
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtSetHighEventPair(
            _In_ HANDLE EventPairHandle
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtWaitLowEventPair(
            _In_ HANDLE EventPairHandle
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtWaitHighEventPair(
            _In_ HANDLE EventPairHandle
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtSetLowWaitHighEventPair(
            _In_ HANDLE EventPairHandle
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtSetHighWaitLowEventPair(
            _In_ HANDLE EventPairHandle
        );

    // Mutant

#ifndef MUTANT_QUERY_STATE
#define MUTANT_QUERY_STATE 0x0001
#endif

#ifndef MUTANT_ALL_ACCESS
#define MUTANT_ALL_ACCESS (MUTANT_QUERY_STATE|STANDARD_RIGHTS_REQUIRED|SYNCHRONIZE)
#endif

    typedef enum _MUTANT_INFORMATION_CLASS
    {
        MutantBasicInformation, // MUTANT_BASIC_INFORMATION
        MutantOwnerInformation // MUTANT_OWNER_INFORMATION
    } MUTANT_INFORMATION_CLASS;

    typedef struct _MUTANT_BASIC_INFORMATION
    {
        LONG CurrentCount;
        BOOLEAN OwnedByCaller;
        BOOLEAN AbandonedState;
    } MUTANT_BASIC_INFORMATION, * PMUTANT_BASIC_INFORMATION;

    typedef struct _MUTANT_OWNER_INFORMATION
    {
        CLIENT_ID ClientId;
    } MUTANT_OWNER_INFORMATION, * PMUTANT_OWNER_INFORMATION;

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtCreateMutant(
            _Out_ PHANDLE MutantHandle,
            _In_ ACCESS_MASK DesiredAccess,
            _In_opt_ POBJECT_ATTRIBUTES ObjectAttributes,
            _In_ BOOLEAN InitialOwner
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtOpenMutant(
            _Out_ PHANDLE MutantHandle,
            _In_ ACCESS_MASK DesiredAccess,
            _In_ POBJECT_ATTRIBUTES ObjectAttributes
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtReleaseMutant(
            _In_ HANDLE MutantHandle,
            _Out_opt_ PLONG PreviousCount
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtQueryMutant(
            _In_ HANDLE MutantHandle,
            _In_ MUTANT_INFORMATION_CLASS MutantInformationClass,
            _Out_writes_bytes_(MutantInformationLength) PVOID MutantInformation,
            _In_ ULONG MutantInformationLength,
            _Out_opt_ PULONG ReturnLength
        );

    // Semaphore

#ifndef SEMAPHORE_QUERY_STATE
#define SEMAPHORE_QUERY_STATE 0x0001
#endif

#ifndef SEMAPHORE_MODIFY_STATE
#define SEMAPHORE_MODIFY_STATE 0x0002
#endif

#ifndef SEMAPHORE_ALL_ACCESS
#define SEMAPHORE_ALL_ACCESS (SEMAPHORE_QUERY_STATE|SEMAPHORE_MODIFY_STATE|STANDARD_RIGHTS_REQUIRED|SYNCHRONIZE)
#endif

    typedef enum _SEMAPHORE_INFORMATION_CLASS
    {
        SemaphoreBasicInformation
    } SEMAPHORE_INFORMATION_CLASS;

    typedef struct _SEMAPHORE_BASIC_INFORMATION
    {
        LONG CurrentCount;
        LONG MaximumCount;
    } SEMAPHORE_BASIC_INFORMATION, * PSEMAPHORE_BASIC_INFORMATION;

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtCreateSemaphore(
            _Out_ PHANDLE SemaphoreHandle,
            _In_ ACCESS_MASK DesiredAccess,
            _In_opt_ POBJECT_ATTRIBUTES ObjectAttributes,
            _In_ LONG InitialCount,
            _In_ LONG MaximumCount
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtOpenSemaphore(
            _Out_ PHANDLE SemaphoreHandle,
            _In_ ACCESS_MASK DesiredAccess,
            _In_ POBJECT_ATTRIBUTES ObjectAttributes
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtReleaseSemaphore(
            _In_ HANDLE SemaphoreHandle,
            _In_ LONG ReleaseCount,
            _Out_opt_ PLONG PreviousCount
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtQuerySemaphore(
            _In_ HANDLE SemaphoreHandle,
            _In_ SEMAPHORE_INFORMATION_CLASS SemaphoreInformationClass,
            _Out_writes_bytes_(SemaphoreInformationLength) PVOID SemaphoreInformation,
            _In_ ULONG SemaphoreInformationLength,
            _Out_opt_ PULONG ReturnLength
        );

    // Timer

#ifndef TIMER_QUERY_STATE
#define TIMER_QUERY_STATE 0x0001
#endif

#ifndef TIMER_MODIFY_STATE
#define TIMER_MODIFY_STATE 0x0002
#endif

#ifndef TIMER_ALL_ACCESS
#define TIMER_ALL_ACCESS (TIMER_QUERY_STATE|TIMER_MODIFY_STATE|STANDARD_RIGHTS_REQUIRED|SYNCHRONIZE)
#endif

    typedef enum _TIMER_INFORMATION_CLASS
    {
        TimerBasicInformation // TIMER_BASIC_INFORMATION
    } TIMER_INFORMATION_CLASS;

    typedef struct _TIMER_BASIC_INFORMATION
    {
        LARGE_INTEGER RemainingTime;
        BOOLEAN TimerState;
    } TIMER_BASIC_INFORMATION, * PTIMER_BASIC_INFORMATION;

    typedef VOID(NTAPI* PTIMER_APC_ROUTINE)(
        _In_ PVOID TimerContext,
        _In_ ULONG TimerLowValue,
        _In_ LONG TimerHighValue
        );

    typedef enum _TIMER_SET_INFORMATION_CLASS
    {
        TimerSetCoalescableTimer, // TIMER_SET_COALESCABLE_TIMER_INFO
        MaxTimerInfoClass
    } TIMER_SET_INFORMATION_CLASS;

#if (PHNT_VERSION >= PHNT_WIN7)
    typedef struct _COUNTED_REASON_CONTEXT* PCOUNTED_REASON_CONTEXT;

    typedef struct _TIMER_SET_COALESCABLE_TIMER_INFO
    {
        _In_ LARGE_INTEGER DueTime;
        _In_opt_ PTIMER_APC_ROUTINE TimerApcRoutine;
        _In_opt_ PVOID TimerContext;
        _In_opt_ PCOUNTED_REASON_CONTEXT WakeContext;
        _In_opt_ ULONG Period;
        _In_ ULONG TolerableDelay;
        _Out_opt_ PBOOLEAN PreviousState;
    } TIMER_SET_COALESCABLE_TIMER_INFO, * PTIMER_SET_COALESCABLE_TIMER_INFO;
#endif

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtCreateTimer(
            _Out_ PHANDLE TimerHandle,
            _In_ ACCESS_MASK DesiredAccess,
            _In_opt_ POBJECT_ATTRIBUTES ObjectAttributes,
            _In_ TIMER_TYPE TimerType
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtOpenTimer(
            _Out_ PHANDLE TimerHandle,
            _In_ ACCESS_MASK DesiredAccess,
            _In_ POBJECT_ATTRIBUTES ObjectAttributes
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtSetTimer(
            _In_ HANDLE TimerHandle,
            _In_ PLARGE_INTEGER DueTime,
            _In_opt_ PTIMER_APC_ROUTINE TimerApcRoutine,
            _In_opt_ PVOID TimerContext,
            _In_ BOOLEAN ResumeTimer,
            _In_opt_ LONG Period,
            _Out_opt_ PBOOLEAN PreviousState
        );

#if (PHNT_VERSION >= PHNT_WIN7)
    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtSetTimerEx(
            _In_ HANDLE TimerHandle,
            _In_ TIMER_SET_INFORMATION_CLASS TimerSetInformationClass,
            _Inout_updates_bytes_opt_(TimerSetInformationLength) PVOID TimerSetInformation,
            _In_ ULONG TimerSetInformationLength
        );
#endif

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtCancelTimer(
            _In_ HANDLE TimerHandle,
            _Out_opt_ PBOOLEAN CurrentState
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtQueryTimer(
            _In_ HANDLE TimerHandle,
            _In_ TIMER_INFORMATION_CLASS TimerInformationClass,
            _Out_writes_bytes_(TimerInformationLength) PVOID TimerInformation,
            _In_ ULONG TimerInformationLength,
            _Out_opt_ PULONG ReturnLength
        );

#if (PHNT_VERSION >= PHNT_WIN8)

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtCreateIRTimer(
            _Out_ PHANDLE TimerHandle,
            _In_ ACCESS_MASK DesiredAccess
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtSetIRTimer(
            _In_ HANDLE TimerHandle,
            _In_opt_ PLARGE_INTEGER DueTime
        );

#endif

    typedef struct _T2_SET_PARAMETERS_V0
    {
        ULONG Version;
        ULONG Reserved;
        LONGLONG NoWakeTolerance;
    } T2_SET_PARAMETERS, * PT2_SET_PARAMETERS;

    typedef PVOID PT2_CANCEL_PARAMETERS;

#if (PHNT_VERSION >= PHNT_THRESHOLD)

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtCreateTimer2(
            _Out_ PHANDLE TimerHandle,
            _In_opt_ PVOID Reserved1,
            _In_opt_ POBJECT_ATTRIBUTES ObjectAttributes,
            _In_ ULONG Attributes,
            _In_ ACCESS_MASK DesiredAccess
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtSetTimer2(
            _In_ HANDLE TimerHandle,
            _In_ PLARGE_INTEGER DueTime,
            _In_opt_ PLARGE_INTEGER Period,
            _In_ PT2_SET_PARAMETERS Parameters
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtCancelTimer2(
            _In_ HANDLE TimerHandle,
            _In_ PT2_CANCEL_PARAMETERS Parameters
        );

#endif

    // Profile

#define PROFILE_CONTROL 0x0001
#define PROFILE_ALL_ACCESS (STANDARD_RIGHTS_REQUIRED | PROFILE_CONTROL)

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtCreateProfile(
            _Out_ PHANDLE ProfileHandle,
            _In_opt_ HANDLE Process,
            _In_ PVOID ProfileBase,
            _In_ SIZE_T ProfileSize,
            _In_ ULONG BucketSize,
            _In_reads_bytes_(BufferSize) PULONG Buffer,
            _In_ ULONG BufferSize,
            _In_ KPROFILE_SOURCE ProfileSource,
            _In_ KAFFINITY Affinity
        );

#if (PHNT_VERSION >= PHNT_WIN7)
    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtCreateProfileEx(
            _Out_ PHANDLE ProfileHandle,
            _In_opt_ HANDLE Process,
            _In_ PVOID ProfileBase,
            _In_ SIZE_T ProfileSize,
            _In_ ULONG BucketSize,
            _In_reads_bytes_(BufferSize) PULONG Buffer,
            _In_ ULONG BufferSize,
            _In_ KPROFILE_SOURCE ProfileSource,
            _In_ USHORT GroupCount,
            _In_reads_(GroupCount) PGROUP_AFFINITY GroupAffinity
        );
#endif

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtStartProfile(
            _In_ HANDLE ProfileHandle
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtStopProfile(
            _In_ HANDLE ProfileHandle
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtQueryIntervalProfile(
            _In_ KPROFILE_SOURCE ProfileSource,
            _Out_ PULONG Interval
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtSetIntervalProfile(
            _In_ ULONG Interval,
            _In_ KPROFILE_SOURCE Source
        );

    // Keyed Event

#define KEYEDEVENT_WAIT 0x0001
#define KEYEDEVENT_WAKE 0x0002
#define KEYEDEVENT_ALL_ACCESS \
    (STANDARD_RIGHTS_REQUIRED | KEYEDEVENT_WAIT | KEYEDEVENT_WAKE)

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtCreateKeyedEvent(
            _Out_ PHANDLE KeyedEventHandle,
            _In_ ACCESS_MASK DesiredAccess,
            _In_opt_ POBJECT_ATTRIBUTES ObjectAttributes,
            _Reserved_ ULONG Flags
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtOpenKeyedEvent(
            _Out_ PHANDLE KeyedEventHandle,
            _In_ ACCESS_MASK DesiredAccess,
            _In_ POBJECT_ATTRIBUTES ObjectAttributes
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtReleaseKeyedEvent(
            _In_opt_ HANDLE KeyedEventHandle,
            _In_ PVOID KeyValue,
            _In_ BOOLEAN Alertable,
            _In_opt_ PLARGE_INTEGER Timeout
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtWaitForKeyedEvent(
            _In_opt_ HANDLE KeyedEventHandle,
            _In_ PVOID KeyValue,
            _In_ BOOLEAN Alertable,
            _In_opt_ PLARGE_INTEGER Timeout
        );

    // UMS

#if (PHNT_VERSION >= PHNT_WIN7)
    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtUmsThreadYield(
            _In_ PVOID SchedulerParam
        );
#endif

    // WNF

    // begin_private

    typedef struct _WNF_STATE_NAME
    {
        ULONG Data[2];
    } WNF_STATE_NAME, * PWNF_STATE_NAME;

    typedef const WNF_STATE_NAME* PCWNF_STATE_NAME;

    typedef enum _WNF_STATE_NAME_LIFETIME
    {
        WnfWellKnownStateName,
        WnfPermanentStateName,
        WnfPersistentStateName,
        WnfTemporaryStateName
    } WNF_STATE_NAME_LIFETIME;

    typedef enum _WNF_STATE_NAME_INFORMATION
    {
        WnfInfoStateNameExist,
        WnfInfoSubscribersPresent,
        WnfInfoIsQuiescent
    } WNF_STATE_NAME_INFORMATION;

    typedef enum _WNF_DATA_SCOPE
    {
        WnfDataScopeSystem,
        WnfDataScopeSession,
        WnfDataScopeUser,
        WnfDataScopeProcess,
        WnfDataScopeMachine, // REDSTONE3
        WnfDataScopePhysicalMachine, // WIN11
    } WNF_DATA_SCOPE;

    typedef struct _WNF_TYPE_ID
    {
        GUID TypeId;
    } WNF_TYPE_ID, * PWNF_TYPE_ID;

    typedef const WNF_TYPE_ID* PCWNF_TYPE_ID;

    // rev
    typedef ULONG WNF_CHANGE_STAMP, * PWNF_CHANGE_STAMP;

    typedef struct _WNF_DELIVERY_DESCRIPTOR
    {
        ULONGLONG SubscriptionId;
        WNF_STATE_NAME StateName;
        WNF_CHANGE_STAMP ChangeStamp;
        ULONG StateDataSize;
        ULONG EventMask;
        WNF_TYPE_ID TypeId;
        ULONG StateDataOffset;
    } WNF_DELIVERY_DESCRIPTOR, * PWNF_DELIVERY_DESCRIPTOR;

    // end_private

#if (PHNT_VERSION >= PHNT_WIN8)

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtCreateWnfStateName(
            _Out_ PWNF_STATE_NAME StateName,
            _In_ WNF_STATE_NAME_LIFETIME NameLifetime,
            _In_ WNF_DATA_SCOPE DataScope,
            _In_ BOOLEAN PersistData,
            _In_opt_ PCWNF_TYPE_ID TypeId,
            _In_ ULONG MaximumStateSize,
            _In_ PSECURITY_DESCRIPTOR SecurityDescriptor
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtDeleteWnfStateName(
            _In_ PCWNF_STATE_NAME StateName
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtUpdateWnfStateData(
            _In_ PCWNF_STATE_NAME StateName,
            _In_reads_bytes_opt_(Length) const VOID* Buffer,
            _In_opt_ ULONG Length,
            _In_opt_ PCWNF_TYPE_ID TypeId,
            _In_opt_ const VOID* ExplicitScope,
            _In_ WNF_CHANGE_STAMP MatchingChangeStamp,
            _In_ LOGICAL CheckStamp
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtDeleteWnfStateData(
            _In_ PCWNF_STATE_NAME StateName,
            _In_opt_ const VOID* ExplicitScope
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtQueryWnfStateData(
            _In_ PCWNF_STATE_NAME StateName,
            _In_opt_ PCWNF_TYPE_ID TypeId,
            _In_opt_ const VOID* ExplicitScope,
            _Out_ PWNF_CHANGE_STAMP ChangeStamp,
            _Out_writes_bytes_opt_(*BufferSize) PVOID Buffer,
            _Inout_ PULONG BufferSize
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtQueryWnfStateNameInformation(
            _In_ PCWNF_STATE_NAME StateName,
            _In_ WNF_STATE_NAME_INFORMATION NameInfoClass,
            _In_opt_ const VOID* ExplicitScope,
            _Out_writes_bytes_(InfoBufferSize) PVOID InfoBuffer,
            _In_ ULONG InfoBufferSize
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtSubscribeWnfStateChange(
            _In_ PCWNF_STATE_NAME StateName,
            _In_opt_ WNF_CHANGE_STAMP ChangeStamp,
            _In_ ULONG EventMask,
            _Out_opt_ PULONG64 SubscriptionId
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtUnsubscribeWnfStateChange(
            _In_ PCWNF_STATE_NAME StateName
        );

#endif

#if (PHNT_VERSION >= PHNT_THRESHOLD)

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtGetCompleteWnfStateSubscription(
            _In_opt_ PWNF_STATE_NAME OldDescriptorStateName,
            _In_opt_ ULONG64* OldSubscriptionId,
            _In_opt_ ULONG OldDescriptorEventMask,
            _In_opt_ ULONG OldDescriptorStatus,
            _Out_writes_bytes_(DescriptorSize) PWNF_DELIVERY_DESCRIPTOR NewDeliveryDescriptor,
            _In_ ULONG DescriptorSize
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtSetWnfProcessNotificationEvent(
            _In_ HANDLE NotificationEvent
        );

#endif

    // Worker factory

    // begin_rev

#define WORKER_FACTORY_RELEASE_WORKER 0x0001
#define WORKER_FACTORY_WAIT 0x0002
#define WORKER_FACTORY_SET_INFORMATION 0x0004
#define WORKER_FACTORY_QUERY_INFORMATION 0x0008
#define WORKER_FACTORY_READY_WORKER 0x0010
#define WORKER_FACTORY_SHUTDOWN 0x0020

#define WORKER_FACTORY_ALL_ACCESS ( \
    STANDARD_RIGHTS_REQUIRED | \
    WORKER_FACTORY_RELEASE_WORKER | \
    WORKER_FACTORY_WAIT | \
    WORKER_FACTORY_SET_INFORMATION | \
    WORKER_FACTORY_QUERY_INFORMATION | \
    WORKER_FACTORY_READY_WORKER | \
    WORKER_FACTORY_SHUTDOWN \
    )

// end_rev

// begin_private

    typedef enum _WORKERFACTORYINFOCLASS
    {
        WorkerFactoryTimeout, // LARGE_INTEGER
        WorkerFactoryRetryTimeout, // LARGE_INTEGER
        WorkerFactoryIdleTimeout, // s: LARGE_INTEGER
        WorkerFactoryBindingCount, // s: ULONG
        WorkerFactoryThreadMinimum, // s: ULONG
        WorkerFactoryThreadMaximum, // s: ULONG
        WorkerFactoryPaused, // ULONG or BOOLEAN
        WorkerFactoryBasicInformation, // q: WORKER_FACTORY_BASIC_INFORMATION
        WorkerFactoryAdjustThreadGoal,
        WorkerFactoryCallbackType,
        WorkerFactoryStackInformation, // 10
        WorkerFactoryThreadBasePriority, // s: ULONG
        WorkerFactoryTimeoutWaiters, // s: ULONG, since THRESHOLD
        WorkerFactoryFlags, // s: ULONG
        WorkerFactoryThreadSoftMaximum, // s: ULONG
        WorkerFactoryThreadCpuSets, // since REDSTONE5
        MaxWorkerFactoryInfoClass
    } WORKERFACTORYINFOCLASS, * PWORKERFACTORYINFOCLASS;

    typedef struct _WORKER_FACTORY_BASIC_INFORMATION
    {
        LARGE_INTEGER Timeout;
        LARGE_INTEGER RetryTimeout;
        LARGE_INTEGER IdleTimeout;
        BOOLEAN Paused;
        BOOLEAN TimerSet;
        BOOLEAN QueuedToExWorker;
        BOOLEAN MayCreate;
        BOOLEAN CreateInProgress;
        BOOLEAN InsertedIntoQueue;
        BOOLEAN Shutdown;
        ULONG BindingCount;
        ULONG ThreadMinimum;
        ULONG ThreadMaximum;
        ULONG PendingWorkerCount;
        ULONG WaitingWorkerCount;
        ULONG TotalWorkerCount;
        ULONG ReleaseCount;
        LONGLONG InfiniteWaitGoal;
        PVOID StartRoutine;
        PVOID StartParameter;
        HANDLE ProcessId;
        SIZE_T StackReserve;
        SIZE_T StackCommit;
        NTSTATUS LastThreadCreationStatus;
    } WORKER_FACTORY_BASIC_INFORMATION, * PWORKER_FACTORY_BASIC_INFORMATION;

    // end_private

#if (PHNT_VERSION >= PHNT_VISTA)

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtCreateWorkerFactory(
            _Out_ PHANDLE WorkerFactoryHandleReturn,
            _In_ ACCESS_MASK DesiredAccess,
            _In_opt_ POBJECT_ATTRIBUTES ObjectAttributes,
            _In_ HANDLE CompletionPortHandle,
            _In_ HANDLE WorkerProcessHandle,
            _In_ PVOID StartRoutine,
            _In_opt_ PVOID StartParameter,
            _In_opt_ ULONG MaxThreadCount,
            _In_opt_ SIZE_T StackReserve,
            _In_opt_ SIZE_T StackCommit
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtQueryInformationWorkerFactory(
            _In_ HANDLE WorkerFactoryHandle,
            _In_ WORKERFACTORYINFOCLASS WorkerFactoryInformationClass,
            _Out_writes_bytes_(WorkerFactoryInformationLength) PVOID WorkerFactoryInformation,
            _In_ ULONG WorkerFactoryInformationLength,
            _Out_opt_ PULONG ReturnLength
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtSetInformationWorkerFactory(
            _In_ HANDLE WorkerFactoryHandle,
            _In_ WORKERFACTORYINFOCLASS WorkerFactoryInformationClass,
            _In_reads_bytes_(WorkerFactoryInformationLength) PVOID WorkerFactoryInformation,
            _In_ ULONG WorkerFactoryInformationLength
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtShutdownWorkerFactory(
            _In_ HANDLE WorkerFactoryHandle,
            _Inout_ volatile LONG* PendingWorkerCount
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtReleaseWorkerFactoryWorker(
            _In_ HANDLE WorkerFactoryHandle
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtWorkerFactoryWorkerReady(
            _In_ HANDLE WorkerFactoryHandle
        );

#if (PHNT_VERSION >= PHNT_WIN8)

    typedef struct _FILE_IO_COMPLETION_INFORMATION* PFILE_IO_COMPLETION_INFORMATION;
    typedef struct _PORT_MESSAGE* PPORT_MESSAGE;

    typedef struct _WORKER_FACTORY_DEFERRED_WORK
    {
        PPORT_MESSAGE AlpcSendMessage;
        PVOID AlpcSendMessagePort;
        ULONG AlpcSendMessageFlags;
        ULONG Flags;
    } WORKER_FACTORY_DEFERRED_WORK, * PWORKER_FACTORY_DEFERRED_WORK;

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtWaitForWorkViaWorkerFactory(
            _In_ HANDLE WorkerFactoryHandle,
            _Out_writes_to_(Count, *PacketsReturned) PFILE_IO_COMPLETION_INFORMATION MiniPackets,
            _In_ ULONG Count,
            _Out_ PULONG PacketsReturned,
            _In_ PWORKER_FACTORY_DEFERRED_WORK DeferredWork
        );

#else

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtWaitForWorkViaWorkerFactory(
            _In_ HANDLE WorkerFactoryHandle,
            _Out_ PFILE_IO_COMPLETION_INFORMATION MiniPacket
        );

#endif

#endif

    // Time

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtQuerySystemTime(
            _Out_ PLARGE_INTEGER SystemTime
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtSetSystemTime(
            _In_opt_ PLARGE_INTEGER SystemTime,
            _Out_opt_ PLARGE_INTEGER PreviousTime
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtQueryTimerResolution(
            _Out_ PULONG MaximumTime,
            _Out_ PULONG MinimumTime,
            _Out_ PULONG CurrentTime
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtSetTimerResolution(
            _In_ ULONG DesiredTime,
            _In_ BOOLEAN SetResolution,
            _Out_ PULONG ActualTime
        );

    // Performance Counter

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtQueryPerformanceCounter(
            _Out_ PLARGE_INTEGER PerformanceCounter,
            _Out_opt_ PLARGE_INTEGER PerformanceFrequency
        );

#if (PHNT_VERSION >= PHNT_REDSTONE2)
    // rev
    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtQueryAuxiliaryCounterFrequency(
            _Out_ PLARGE_INTEGER AuxiliaryCounterFrequency
        );

    // rev
    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtConvertBetweenAuxiliaryCounterAndPerformanceCounter(
            _In_opt_ PLARGE_INTEGER AuxiliaryCounterValue,
            _Inout_ PLARGE_INTEGER PerformanceCounterValue,
            _Out_ PLARGE_INTEGER PerformanceOrAuxiliaryCounterValue,
            _Out_ PLARGE_INTEGER ConversionError
        );
#endif

    // LUIDs

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtAllocateLocallyUniqueId(
            _Out_ PLUID Luid
        );

    // UUIDs

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtSetUuidSeed(
            _In_ PCHAR Seed
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtAllocateUuids(
            _Out_ PULARGE_INTEGER Time,
            _Out_ PULONG Range,
            _Out_ PULONG Sequence,
            _Out_ PCHAR Seed
        );

    // System Information

#endif // (PHNT_MODE != PHNT_MODE_KERNEL)

// rev
// private
    typedef enum _SYSTEM_INFORMATION_CLASS
    {
        SystemBasicInformation, // q: SYSTEM_BASIC_INFORMATION
        SystemProcessorInformation, // q: SYSTEM_PROCESSOR_INFORMATION
        SystemPerformanceInformation, // q: SYSTEM_PERFORMANCE_INFORMATION
        SystemTimeOfDayInformation, // q: SYSTEM_TIMEOFDAY_INFORMATION
        SystemPathInformation, // not implemented
        SystemProcessInformation, // q: SYSTEM_PROCESS_INFORMATION
        SystemCallCountInformation, // q: SYSTEM_CALL_COUNT_INFORMATION
        SystemDeviceInformation, // q: SYSTEM_DEVICE_INFORMATION
        SystemProcessorPerformanceInformation, // q: SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION (EX in: USHORT ProcessorGroup)
        SystemFlagsInformation, // q: SYSTEM_FLAGS_INFORMATION
        SystemCallTimeInformation, // not implemented // SYSTEM_CALL_TIME_INFORMATION // 10
        SystemModuleInformation, // q: RTL_PROCESS_MODULES
        SystemLocksInformation, // q: RTL_PROCESS_LOCKS
        SystemStackTraceInformation, // q: RTL_PROCESS_BACKTRACES
        SystemPagedPoolInformation, // not implemented
        SystemNonPagedPoolInformation, // not implemented
        SystemHandleInformation, // q: SYSTEM_HANDLE_INFORMATION
        SystemObjectInformation, // q: SYSTEM_OBJECTTYPE_INFORMATION mixed with SYSTEM_OBJECT_INFORMATION
        SystemPageFileInformation, // q: SYSTEM_PAGEFILE_INFORMATION
        SystemVdmInstemulInformation, // q: SYSTEM_VDM_INSTEMUL_INFO
        SystemVdmBopInformation, // not implemented // 20
        SystemFileCacheInformation, // q: SYSTEM_FILECACHE_INFORMATION; s (requires SeIncreaseQuotaPrivilege) (info for WorkingSetTypeSystemCache)
        SystemPoolTagInformation, // q: SYSTEM_POOLTAG_INFORMATION
        SystemInterruptInformation, // q: SYSTEM_INTERRUPT_INFORMATION (EX in: USHORT ProcessorGroup)
        SystemDpcBehaviorInformation, // q: SYSTEM_DPC_BEHAVIOR_INFORMATION; s: SYSTEM_DPC_BEHAVIOR_INFORMATION (requires SeLoadDriverPrivilege)
        SystemFullMemoryInformation, // not implemented // SYSTEM_MEMORY_USAGE_INFORMATION
        SystemLoadGdiDriverInformation, // s (kernel-mode only)
        SystemUnloadGdiDriverInformation, // s (kernel-mode only)
        SystemTimeAdjustmentInformation, // q: SYSTEM_QUERY_TIME_ADJUST_INFORMATION; s: SYSTEM_SET_TIME_ADJUST_INFORMATION (requires SeSystemtimePrivilege)
        SystemSummaryMemoryInformation, // not implemented // SYSTEM_MEMORY_USAGE_INFORMATION
        SystemMirrorMemoryInformation, // s (requires license value "Kernel-MemoryMirroringSupported") (requires SeShutdownPrivilege) // 30
        SystemPerformanceTraceInformation, // q; s: (type depends on EVENT_TRACE_INFORMATION_CLASS)
        SystemObsolete0, // not implemented
        SystemExceptionInformation, // q: SYSTEM_EXCEPTION_INFORMATION
        SystemCrashDumpStateInformation, // s: SYSTEM_CRASH_DUMP_STATE_INFORMATION (requires SeDebugPrivilege)
        SystemKernelDebuggerInformation, // q: SYSTEM_KERNEL_DEBUGGER_INFORMATION
        SystemContextSwitchInformation, // q: SYSTEM_CONTEXT_SWITCH_INFORMATION
        SystemRegistryQuotaInformation, // q: SYSTEM_REGISTRY_QUOTA_INFORMATION; s (requires SeIncreaseQuotaPrivilege)
        SystemExtendServiceTableInformation, // s (requires SeLoadDriverPrivilege) // loads win32k only
        SystemPrioritySeperation, // s (requires SeTcbPrivilege)
        SystemVerifierAddDriverInformation, // s (requires SeDebugPrivilege) // 40
        SystemVerifierRemoveDriverInformation, // s (requires SeDebugPrivilege)
        SystemProcessorIdleInformation, // q: SYSTEM_PROCESSOR_IDLE_INFORMATION (EX in: USHORT ProcessorGroup)
        SystemLegacyDriverInformation, // q: SYSTEM_LEGACY_DRIVER_INFORMATION
        SystemCurrentTimeZoneInformation, // q; s: RTL_TIME_ZONE_INFORMATION
        SystemLookasideInformation, // q: SYSTEM_LOOKASIDE_INFORMATION
        SystemTimeSlipNotification, // s: HANDLE (NtCreateEvent) (requires SeSystemtimePrivilege)
        SystemSessionCreate, // not implemented
        SystemSessionDetach, // not implemented
        SystemSessionInformation, // not implemented (SYSTEM_SESSION_INFORMATION)
        SystemRangeStartInformation, // q: SYSTEM_RANGE_START_INFORMATION // 50
        SystemVerifierInformation, // q: SYSTEM_VERIFIER_INFORMATION; s (requires SeDebugPrivilege)
        SystemVerifierThunkExtend, // s (kernel-mode only)
        SystemSessionProcessInformation, // q: SYSTEM_SESSION_PROCESS_INFORMATION
        SystemLoadGdiDriverInSystemSpace, // s: SYSTEM_GDI_DRIVER_INFORMATION (kernel-mode only) (same as SystemLoadGdiDriverInformation)
        SystemNumaProcessorMap, // q: SYSTEM_NUMA_INFORMATION
        SystemPrefetcherInformation, // q; s: PREFETCHER_INFORMATION // PfSnQueryPrefetcherInformation
        SystemExtendedProcessInformation, // q: SYSTEM_PROCESS_INFORMATION
        SystemRecommendedSharedDataAlignment, // q: ULONG // KeGetRecommendedSharedDataAlignment
        SystemComPlusPackage, // q; s: ULONG
        SystemNumaAvailableMemory, // q: SYSTEM_NUMA_INFORMATION // 60
        SystemProcessorPowerInformation, // q: SYSTEM_PROCESSOR_POWER_INFORMATION (EX in: USHORT ProcessorGroup)
        SystemEmulationBasicInformation, // q: SYSTEM_BASIC_INFORMATION
        SystemEmulationProcessorInformation, // q: SYSTEM_PROCESSOR_INFORMATION
        SystemExtendedHandleInformation, // q: SYSTEM_HANDLE_INFORMATION_EX
        SystemLostDelayedWriteInformation, // q: ULONG
        SystemBigPoolInformation, // q: SYSTEM_BIGPOOL_INFORMATION
        SystemSessionPoolTagInformation, // q: SYSTEM_SESSION_POOLTAG_INFORMATION
        SystemSessionMappedViewInformation, // q: SYSTEM_SESSION_MAPPED_VIEW_INFORMATION
        SystemHotpatchInformation, // q; s: SYSTEM_HOTPATCH_CODE_INFORMATION
        SystemObjectSecurityMode, // q: ULONG // 70
        SystemWatchdogTimerHandler, // s: SYSTEM_WATCHDOG_HANDLER_INFORMATION // (kernel-mode only)
        SystemWatchdogTimerInformation, // q: SYSTEM_WATCHDOG_TIMER_INFORMATION // (kernel-mode only)
        SystemLogicalProcessorInformation, // q: SYSTEM_LOGICAL_PROCESSOR_INFORMATION (EX in: USHORT ProcessorGroup)
        SystemWow64SharedInformationObsolete, // not implemented
        SystemRegisterFirmwareTableInformationHandler, // s: SYSTEM_FIRMWARE_TABLE_HANDLER // (kernel-mode only)
        SystemFirmwareTableInformation, // SYSTEM_FIRMWARE_TABLE_INFORMATION
        SystemModuleInformationEx, // q: RTL_PROCESS_MODULE_INFORMATION_EX
        SystemVerifierTriageInformation, // not implemented
        SystemSuperfetchInformation, // q; s: SUPERFETCH_INFORMATION // PfQuerySuperfetchInformation
        SystemMemoryListInformation, // q: SYSTEM_MEMORY_LIST_INFORMATION; s: SYSTEM_MEMORY_LIST_COMMAND (requires SeProfileSingleProcessPrivilege) // 80
        SystemFileCacheInformationEx, // q: SYSTEM_FILECACHE_INFORMATION; s (requires SeIncreaseQuotaPrivilege) (same as SystemFileCacheInformation)
        SystemThreadPriorityClientIdInformation, // s: SYSTEM_THREAD_CID_PRIORITY_INFORMATION (requires SeIncreaseBasePriorityPrivilege)
        SystemProcessorIdleCycleTimeInformation, // q: SYSTEM_PROCESSOR_IDLE_CYCLE_TIME_INFORMATION[] (EX in: USHORT ProcessorGroup)
        SystemVerifierCancellationInformation, // SYSTEM_VERIFIER_CANCELLATION_INFORMATION // name:wow64:whNT32QuerySystemVerifierCancellationInformation
        SystemProcessorPowerInformationEx, // not implemented
        SystemRefTraceInformation, // q; s: SYSTEM_REF_TRACE_INFORMATION // ObQueryRefTraceInformation
        SystemSpecialPoolInformation, // q; s: SYSTEM_SPECIAL_POOL_INFORMATION (requires SeDebugPrivilege) // MmSpecialPoolTag, then MmSpecialPoolCatchOverruns != 0
        SystemProcessIdInformation, // q: SYSTEM_PROCESS_ID_INFORMATION
        SystemErrorPortInformation, // s (requires SeTcbPrivilege)
        SystemBootEnvironmentInformation, // q: SYSTEM_BOOT_ENVIRONMENT_INFORMATION // 90
        SystemHypervisorInformation, // q: SYSTEM_HYPERVISOR_QUERY_INFORMATION
        SystemVerifierInformationEx, // q; s: SYSTEM_VERIFIER_INFORMATION_EX
        SystemTimeZoneInformation, // q; s: RTL_TIME_ZONE_INFORMATION (requires SeTimeZonePrivilege)
        SystemImageFileExecutionOptionsInformation, // s: SYSTEM_IMAGE_FILE_EXECUTION_OPTIONS_INFORMATION (requires SeTcbPrivilege)
        SystemCoverageInformation, // q: COVERAGE_MODULES s: COVERAGE_MODULE_REQUEST // ExpCovQueryInformation (requires SeDebugPrivilege)
        SystemPrefetchPatchInformation, // SYSTEM_PREFETCH_PATCH_INFORMATION
        SystemVerifierFaultsInformation, // s: SYSTEM_VERIFIER_FAULTS_INFORMATION (requires SeDebugPrivilege)
        SystemSystemPartitionInformation, // q: SYSTEM_SYSTEM_PARTITION_INFORMATION
        SystemSystemDiskInformation, // q: SYSTEM_SYSTEM_DISK_INFORMATION
        SystemProcessorPerformanceDistribution, // q: SYSTEM_PROCESSOR_PERFORMANCE_DISTRIBUTION (EX in: USHORT ProcessorGroup) // 100
        SystemNumaProximityNodeInformation, // q; s: SYSTEM_NUMA_PROXIMITY_MAP
        SystemDynamicTimeZoneInformation, // q; s: RTL_DYNAMIC_TIME_ZONE_INFORMATION (requires SeTimeZonePrivilege)
        SystemCodeIntegrityInformation, // q: SYSTEM_CODEINTEGRITY_INFORMATION // SeCodeIntegrityQueryInformation
        SystemProcessorMicrocodeUpdateInformation, // s: SYSTEM_PROCESSOR_MICROCODE_UPDATE_INFORMATION
        SystemProcessorBrandString, // q: CHAR[] // HaliQuerySystemInformation -> HalpGetProcessorBrandString, info class 23
        SystemVirtualAddressInformation, // q: SYSTEM_VA_LIST_INFORMATION[]; s: SYSTEM_VA_LIST_INFORMATION[] (requires SeIncreaseQuotaPrivilege) // MmQuerySystemVaInformation
        SystemLogicalProcessorAndGroupInformation, // q: SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX (EX in: LOGICAL_PROCESSOR_RELATIONSHIP RelationshipType) // since WIN7 // KeQueryLogicalProcessorRelationship
        SystemProcessorCycleTimeInformation, // q: SYSTEM_PROCESSOR_CYCLE_TIME_INFORMATION[] (EX in: USHORT ProcessorGroup)
        SystemStoreInformation, // q; s: SYSTEM_STORE_INFORMATION (requires SeProfileSingleProcessPrivilege) // SmQueryStoreInformation
        SystemRegistryAppendString, // s: SYSTEM_REGISTRY_APPEND_STRING_PARAMETERS // 110
        SystemAitSamplingValue, // s: ULONG (requires SeProfileSingleProcessPrivilege)
        SystemVhdBootInformation, // q: SYSTEM_VHD_BOOT_INFORMATION
        SystemCpuQuotaInformation, // q; s: PS_CPU_QUOTA_QUERY_INFORMATION
        SystemNativeBasicInformation, // q: SYSTEM_BASIC_INFORMATION
        SystemErrorPortTimeouts, // SYSTEM_ERROR_PORT_TIMEOUTS
        SystemLowPriorityIoInformation, // q: SYSTEM_LOW_PRIORITY_IO_INFORMATION
        SystemTpmBootEntropyInformation, // q: TPM_BOOT_ENTROPY_NT_RESULT // ExQueryTpmBootEntropyInformation
        SystemVerifierCountersInformation, // q: SYSTEM_VERIFIER_COUNTERS_INFORMATION
        SystemPagedPoolInformationEx, // q: SYSTEM_FILECACHE_INFORMATION; s (requires SeIncreaseQuotaPrivilege) (info for WorkingSetTypePagedPool)
        SystemSystemPtesInformationEx, // q: SYSTEM_FILECACHE_INFORMATION; s (requires SeIncreaseQuotaPrivilege) (info for WorkingSetTypeSystemPtes) // 120
        SystemNodeDistanceInformation, // q: USHORT[4*NumaNodes] // (EX in: USHORT NodeNumber)
        SystemAcpiAuditInformation, // q: SYSTEM_ACPI_AUDIT_INFORMATION // HaliQuerySystemInformation -> HalpAuditQueryResults, info class 26
        SystemBasicPerformanceInformation, // q: SYSTEM_BASIC_PERFORMANCE_INFORMATION // name:wow64:whNtQuerySystemInformation_SystemBasicPerformanceInformation
        SystemQueryPerformanceCounterInformation, // q: SYSTEM_QUERY_PERFORMANCE_COUNTER_INFORMATION // since WIN7 SP1
        SystemSessionBigPoolInformation, // q: SYSTEM_SESSION_POOLTAG_INFORMATION // since WIN8
        SystemBootGraphicsInformation, // q; s: SYSTEM_BOOT_GRAPHICS_INFORMATION (kernel-mode only)
        SystemScrubPhysicalMemoryInformation, // q; s: MEMORY_SCRUB_INFORMATION
        SystemBadPageInformation,
        SystemProcessorProfileControlArea, // q; s: SYSTEM_PROCESSOR_PROFILE_CONTROL_AREA
        SystemCombinePhysicalMemoryInformation, // s: MEMORY_COMBINE_INFORMATION, MEMORY_COMBINE_INFORMATION_EX, MEMORY_COMBINE_INFORMATION_EX2 // 130
        SystemEntropyInterruptTimingInformation, // q; s: SYSTEM_ENTROPY_TIMING_INFORMATION
        SystemConsoleInformation, // q; s: SYSTEM_CONSOLE_INFORMATION
        SystemPlatformBinaryInformation, // q: SYSTEM_PLATFORM_BINARY_INFORMATION (requires SeTcbPrivilege)
        SystemPolicyInformation, // q: SYSTEM_POLICY_INFORMATION (Warbird/Encrypt/Decrypt/Execute)
        SystemHypervisorProcessorCountInformation, // q: SYSTEM_HYPERVISOR_PROCESSOR_COUNT_INFORMATION
        SystemDeviceDataInformation, // q: SYSTEM_DEVICE_DATA_INFORMATION
        SystemDeviceDataEnumerationInformation, // q: SYSTEM_DEVICE_DATA_INFORMATION
        SystemMemoryTopologyInformation, // q: SYSTEM_MEMORY_TOPOLOGY_INFORMATION
        SystemMemoryChannelInformation, // q: SYSTEM_MEMORY_CHANNEL_INFORMATION
        SystemBootLogoInformation, // q: SYSTEM_BOOT_LOGO_INFORMATION // 140
        SystemProcessorPerformanceInformationEx, // q: SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION_EX // (EX in: USHORT ProcessorGroup) // since WINBLUE
        SystemCriticalProcessErrorLogInformation,
        SystemSecureBootPolicyInformation, // q: SYSTEM_SECUREBOOT_POLICY_INFORMATION
        SystemPageFileInformationEx, // q: SYSTEM_PAGEFILE_INFORMATION_EX
        SystemSecureBootInformation, // q: SYSTEM_SECUREBOOT_INFORMATION
        SystemEntropyInterruptTimingRawInformation,
        SystemPortableWorkspaceEfiLauncherInformation, // q: SYSTEM_PORTABLE_WORKSPACE_EFI_LAUNCHER_INFORMATION
        SystemFullProcessInformation, // q: SYSTEM_PROCESS_INFORMATION with SYSTEM_PROCESS_INFORMATION_EXTENSION (requires admin)
        SystemKernelDebuggerInformationEx, // q: SYSTEM_KERNEL_DEBUGGER_INFORMATION_EX
        SystemBootMetadataInformation, // 150
        SystemSoftRebootInformation, // q: ULONG
        SystemElamCertificateInformation, // s: SYSTEM_ELAM_CERTIFICATE_INFORMATION
        SystemOfflineDumpConfigInformation, // q: OFFLINE_CRASHDUMP_CONFIGURATION_TABLE_V2
        SystemProcessorFeaturesInformation, // q: SYSTEM_PROCESSOR_FEATURES_INFORMATION
        SystemRegistryReconciliationInformation, // s: NULL (requires admin) (flushes registry hives)
        SystemEdidInformation, // q: SYSTEM_EDID_INFORMATION
        SystemManufacturingInformation, // q: SYSTEM_MANUFACTURING_INFORMATION // since THRESHOLD
        SystemEnergyEstimationConfigInformation, // q: SYSTEM_ENERGY_ESTIMATION_CONFIG_INFORMATION
        SystemHypervisorDetailInformation, // q: SYSTEM_HYPERVISOR_DETAIL_INFORMATION
        SystemProcessorCycleStatsInformation, // q: SYSTEM_PROCESSOR_CYCLE_STATS_INFORMATION (EX in: USHORT ProcessorGroup) // 160
        SystemVmGenerationCountInformation,
        SystemTrustedPlatformModuleInformation, // q: SYSTEM_TPM_INFORMATION
        SystemKernelDebuggerFlags, // SYSTEM_KERNEL_DEBUGGER_FLAGS
        SystemCodeIntegrityPolicyInformation, // q; s: SYSTEM_CODEINTEGRITYPOLICY_INFORMATION
        SystemIsolatedUserModeInformation, // q: SYSTEM_ISOLATED_USER_MODE_INFORMATION
        SystemHardwareSecurityTestInterfaceResultsInformation,
        SystemSingleModuleInformation, // q: SYSTEM_SINGLE_MODULE_INFORMATION
        SystemAllowedCpuSetsInformation, // s: SYSTEM_WORKLOAD_ALLOWED_CPU_SET_INFORMATION
        SystemVsmProtectionInformation, // q: SYSTEM_VSM_PROTECTION_INFORMATION (previously SystemDmaProtectionInformation)
        SystemInterruptCpuSetsInformation, // q: SYSTEM_INTERRUPT_CPU_SET_INFORMATION // 170
        SystemSecureBootPolicyFullInformation, // q: SYSTEM_SECUREBOOT_POLICY_FULL_INFORMATION
        SystemCodeIntegrityPolicyFullInformation,
        SystemAffinitizedInterruptProcessorInformation, // (requires SeIncreaseBasePriorityPrivilege)
        SystemRootSiloInformation, // q: SYSTEM_ROOT_SILO_INFORMATION
        SystemCpuSetInformation, // q: SYSTEM_CPU_SET_INFORMATION // since THRESHOLD2
        SystemCpuSetTagInformation, // q: SYSTEM_CPU_SET_TAG_INFORMATION
        SystemWin32WerStartCallout,
        SystemSecureKernelProfileInformation, // q: SYSTEM_SECURE_KERNEL_HYPERGUARD_PROFILE_INFORMATION
        SystemCodeIntegrityPlatformManifestInformation, // q: SYSTEM_SECUREBOOT_PLATFORM_MANIFEST_INFORMATION // since REDSTONE
        SystemInterruptSteeringInformation, // q: in: SYSTEM_INTERRUPT_STEERING_INFORMATION_INPUT, out: SYSTEM_INTERRUPT_STEERING_INFORMATION_OUTPUT // NtQuerySystemInformationEx // 180
        SystemSupportedProcessorArchitectures, // p: in opt: HANDLE, out: SYSTEM_SUPPORTED_PROCESSOR_ARCHITECTURES_INFORMATION[] // NtQuerySystemInformationEx
        SystemMemoryUsageInformation, // q: SYSTEM_MEMORY_USAGE_INFORMATION
        SystemCodeIntegrityCertificateInformation, // q: SYSTEM_CODEINTEGRITY_CERTIFICATE_INFORMATION
        SystemPhysicalMemoryInformation, // q: SYSTEM_PHYSICAL_MEMORY_INFORMATION // since REDSTONE2
        SystemControlFlowTransition, // (Warbird/Encrypt/Decrypt/Execute)
        SystemKernelDebuggingAllowed, // s: ULONG
        SystemActivityModerationExeState, // SYSTEM_ACTIVITY_MODERATION_EXE_STATE
        SystemActivityModerationUserSettings, // SYSTEM_ACTIVITY_MODERATION_USER_SETTINGS
        SystemCodeIntegrityPoliciesFullInformation,
        SystemCodeIntegrityUnlockInformation, // SYSTEM_CODEINTEGRITY_UNLOCK_INFORMATION // 190
        SystemIntegrityQuotaInformation,
        SystemFlushInformation, // q: SYSTEM_FLUSH_INFORMATION
        SystemProcessorIdleMaskInformation, // q: ULONG_PTR[ActiveGroupCount] // since REDSTONE3
        SystemSecureDumpEncryptionInformation,
        SystemWriteConstraintInformation, // SYSTEM_WRITE_CONSTRAINT_INFORMATION
        SystemKernelVaShadowInformation, // SYSTEM_KERNEL_VA_SHADOW_INFORMATION
        SystemHypervisorSharedPageInformation, // SYSTEM_HYPERVISOR_SHARED_PAGE_INFORMATION // since REDSTONE4
        SystemFirmwareBootPerformanceInformation,
        SystemCodeIntegrityVerificationInformation, // SYSTEM_CODEINTEGRITYVERIFICATION_INFORMATION
        SystemFirmwarePartitionInformation, // SYSTEM_FIRMWARE_PARTITION_INFORMATION // 200
        SystemSpeculationControlInformation, // SYSTEM_SPECULATION_CONTROL_INFORMATION // (CVE-2017-5715) REDSTONE3 and above.
        SystemDmaGuardPolicyInformation, // SYSTEM_DMA_GUARD_POLICY_INFORMATION
        SystemEnclaveLaunchControlInformation, // SYSTEM_ENCLAVE_LAUNCH_CONTROL_INFORMATION
        SystemWorkloadAllowedCpuSetsInformation, // SYSTEM_WORKLOAD_ALLOWED_CPU_SET_INFORMATION // since REDSTONE5
        SystemCodeIntegrityUnlockModeInformation, // SYSTEM_CODEINTEGRITY_UNLOCK_INFORMATION
        SystemLeapSecondInformation, // SYSTEM_LEAP_SECOND_INFORMATION
        SystemFlags2Information, // q: SYSTEM_FLAGS_INFORMATION
        SystemSecurityModelInformation, // SYSTEM_SECURITY_MODEL_INFORMATION // since 19H1
        SystemCodeIntegritySyntheticCacheInformation,
        SystemFeatureConfigurationInformation, // SYSTEM_FEATURE_CONFIGURATION_INFORMATION // since 20H1 // 210
        SystemFeatureConfigurationSectionInformation, // SYSTEM_FEATURE_CONFIGURATION_SECTIONS_INFORMATION
        SystemFeatureUsageSubscriptionInformation, // SYSTEM_FEATURE_USAGE_SUBSCRIPTION_DETAILS
        SystemSecureSpeculationControlInformation, // SECURE_SPECULATION_CONTROL_INFORMATION
        SystemSpacesBootInformation, // since 20H2
        SystemFwRamdiskInformation, // SYSTEM_FIRMWARE_RAMDISK_INFORMATION
        SystemWheaIpmiHardwareInformation,
        SystemDifSetRuleClassInformation, // SYSTEM_DIF_VOLATILE_INFORMATION
        SystemDifClearRuleClassInformation,
        SystemDifApplyPluginVerificationOnDriver, // SYSTEM_DIF_PLUGIN_DRIVER_INFORMATION
        SystemDifRemovePluginVerificationOnDriver, // SYSTEM_DIF_PLUGIN_DRIVER_INFORMATION // 220
        SystemShadowStackInformation, // SYSTEM_SHADOW_STACK_INFORMATION
        SystemBuildVersionInformation, // q: in: ULONG (LayerNumber), out: SYSTEM_BUILD_VERSION_INFORMATION // NtQuerySystemInformationEx // 222
        SystemPoolLimitInformation, // SYSTEM_POOL_LIMIT_INFORMATION (requires SeIncreaseQuotaPrivilege)
        SystemCodeIntegrityAddDynamicStore,
        SystemCodeIntegrityClearDynamicStores,
        SystemDifPoolTrackingInformation,
        SystemPoolZeroingInformation, // q: SYSTEM_POOL_ZEROING_INFORMATION
        SystemDpcWatchdogInformation, // q; s: SYSTEM_DPC_WATCHDOG_CONFIGURATION_INFORMATION
        SystemDpcWatchdogInformation2, // q; s: SYSTEM_DPC_WATCHDOG_CONFIGURATION_INFORMATION_V2
        SystemSupportedProcessorArchitectures2, // q: in opt: HANDLE, out: SYSTEM_SUPPORTED_PROCESSOR_ARCHITECTURES_INFORMATION[] // NtQuerySystemInformationEx // 230
        SystemSingleProcessorRelationshipInformation, // q: SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX // (EX in: PROCESSOR_NUMBER Processor)
        SystemXfgCheckFailureInformation, // q: SYSTEM_XFG_FAILURE_INFORMATION
        SystemIommuStateInformation, // SYSTEM_IOMMU_STATE_INFORMATION // since 22H1
        SystemHypervisorMinrootInformation, // SYSTEM_HYPERVISOR_MINROOT_INFORMATION
        SystemHypervisorBootPagesInformation, // SYSTEM_HYPERVISOR_BOOT_PAGES_INFORMATION
        SystemPointerAuthInformation, // SYSTEM_POINTER_AUTH_INFORMATION
        SystemSecureKernelDebuggerInformation,
        SystemOriginalImageFeatureInformation, // q: in: SYSTEM_ORIGINAL_IMAGE_FEATURE_INFORMATION_INPUT, out: SYSTEM_ORIGINAL_IMAGE_FEATURE_INFORMATION_OUTPUT // NtQuerySystemInformationEx
        MaxSystemInfoClass
    } SYSTEM_INFORMATION_CLASS;

    typedef struct _SYSTEM_BASIC_INFORMATION
    {
        ULONG Reserved;
        ULONG TimerResolution;
        ULONG PageSize;
        ULONG NumberOfPhysicalPages;
        ULONG LowestPhysicalPageNumber;
        ULONG HighestPhysicalPageNumber;
        ULONG AllocationGranularity;
        ULONG_PTR MinimumUserModeAddress;
        ULONG_PTR MaximumUserModeAddress;
        KAFFINITY ActiveProcessorsAffinityMask;
        CCHAR NumberOfProcessors;
    } SYSTEM_BASIC_INFORMATION, * PSYSTEM_BASIC_INFORMATION;

    typedef struct _SYSTEM_PROCESSOR_INFORMATION
    {
        USHORT ProcessorArchitecture;
        USHORT ProcessorLevel;
        USHORT ProcessorRevision;
        USHORT MaximumProcessors;
        ULONG ProcessorFeatureBits;
    } SYSTEM_PROCESSOR_INFORMATION, * PSYSTEM_PROCESSOR_INFORMATION;

    typedef struct _SYSTEM_PERFORMANCE_INFORMATION
    {
        LARGE_INTEGER IdleProcessTime;
        LARGE_INTEGER IoReadTransferCount;
        LARGE_INTEGER IoWriteTransferCount;
        LARGE_INTEGER IoOtherTransferCount;
        ULONG IoReadOperationCount;
        ULONG IoWriteOperationCount;
        ULONG IoOtherOperationCount;
        ULONG AvailablePages;
        ULONG CommittedPages;
        ULONG CommitLimit;
        ULONG PeakCommitment;
        ULONG PageFaultCount;
        ULONG CopyOnWriteCount;
        ULONG TransitionCount;
        ULONG CacheTransitionCount;
        ULONG DemandZeroCount;
        ULONG PageReadCount;
        ULONG PageReadIoCount;
        ULONG CacheReadCount;
        ULONG CacheIoCount;
        ULONG DirtyPagesWriteCount;
        ULONG DirtyWriteIoCount;
        ULONG MappedPagesWriteCount;
        ULONG MappedWriteIoCount;
        ULONG PagedPoolPages;
        ULONG NonPagedPoolPages;
        ULONG PagedPoolAllocs;
        ULONG PagedPoolFrees;
        ULONG NonPagedPoolAllocs;
        ULONG NonPagedPoolFrees;
        ULONG FreeSystemPtes;
        ULONG ResidentSystemCodePage;
        ULONG TotalSystemDriverPages;
        ULONG TotalSystemCodePages;
        ULONG NonPagedPoolLookasideHits;
        ULONG PagedPoolLookasideHits;
        ULONG AvailablePagedPoolPages;
        ULONG ResidentSystemCachePage;
        ULONG ResidentPagedPoolPage;
        ULONG ResidentSystemDriverPage;
        ULONG CcFastReadNoWait;
        ULONG CcFastReadWait;
        ULONG CcFastReadResourceMiss;
        ULONG CcFastReadNotPossible;
        ULONG CcFastMdlReadNoWait;
        ULONG CcFastMdlReadWait;
        ULONG CcFastMdlReadResourceMiss;
        ULONG CcFastMdlReadNotPossible;
        ULONG CcMapDataNoWait;
        ULONG CcMapDataWait;
        ULONG CcMapDataNoWaitMiss;
        ULONG CcMapDataWaitMiss;
        ULONG CcPinMappedDataCount;
        ULONG CcPinReadNoWait;
        ULONG CcPinReadWait;
        ULONG CcPinReadNoWaitMiss;
        ULONG CcPinReadWaitMiss;
        ULONG CcCopyReadNoWait;
        ULONG CcCopyReadWait;
        ULONG CcCopyReadNoWaitMiss;
        ULONG CcCopyReadWaitMiss;
        ULONG CcMdlReadNoWait;
        ULONG CcMdlReadWait;
        ULONG CcMdlReadNoWaitMiss;
        ULONG CcMdlReadWaitMiss;
        ULONG CcReadAheadIos;
        ULONG CcLazyWriteIos;
        ULONG CcLazyWritePages;
        ULONG CcDataFlushes;
        ULONG CcDataPages;
        ULONG ContextSwitches;
        ULONG FirstLevelTbFills;
        ULONG SecondLevelTbFills;
        ULONG SystemCalls;
        ULONGLONG CcTotalDirtyPages; // since THRESHOLD
        ULONGLONG CcDirtyPageThreshold; // since THRESHOLD
        LONGLONG ResidentAvailablePages; // since THRESHOLD
        ULONGLONG SharedCommittedPages; // since THRESHOLD
    } SYSTEM_PERFORMANCE_INFORMATION, * PSYSTEM_PERFORMANCE_INFORMATION;

    typedef struct _SYSTEM_TIMEOFDAY_INFORMATION
    {
        LARGE_INTEGER BootTime;
        LARGE_INTEGER CurrentTime;
        LARGE_INTEGER TimeZoneBias;
        ULONG TimeZoneId;
        ULONG Reserved;
        ULONGLONG BootTimeBias;
        ULONGLONG SleepTimeBias;
    } SYSTEM_TIMEOFDAY_INFORMATION, * PSYSTEM_TIMEOFDAY_INFORMATION;

    typedef struct _SYSTEM_THREAD_INFORMATION
    {
        LARGE_INTEGER KernelTime;
        LARGE_INTEGER UserTime;
        LARGE_INTEGER CreateTime;
        ULONG WaitTime;
        ULONG_PTR StartAddress;
        CLIENT_ID ClientId;
        KPRIORITY Priority;
        KPRIORITY BasePriority;
        ULONG ContextSwitches;
        KTHREAD_STATE ThreadState;
        KWAIT_REASON WaitReason;
    } SYSTEM_THREAD_INFORMATION, * PSYSTEM_THREAD_INFORMATION;

    typedef struct _TEB* PTEB;

    // private
    typedef struct _SYSTEM_EXTENDED_THREAD_INFORMATION
    {
        SYSTEM_THREAD_INFORMATION ThreadInfo;
        PVOID StackBase;
        PVOID StackLimit;
        ULONG_PTR Win32StartAddress;
        PTEB TebBase; // since VISTA
        ULONG_PTR Reserved2;
        ULONG_PTR Reserved3;
        ULONG_PTR Reserved4;
    } SYSTEM_EXTENDED_THREAD_INFORMATION, * PSYSTEM_EXTENDED_THREAD_INFORMATION;

    typedef struct _SYSTEM_PROCESS_INFORMATION
    {
        ULONG NextEntryOffset;
        ULONG NumberOfThreads;
        LARGE_INTEGER WorkingSetPrivateSize; // since VISTA
        ULONG HardFaultCount; // since WIN7
        ULONG NumberOfThreadsHighWatermark; // since WIN7
        ULONGLONG CycleTime; // since WIN7
        LARGE_INTEGER CreateTime;
        LARGE_INTEGER UserTime;
        LARGE_INTEGER KernelTime;
        UNICODE_STRING ImageName;
        KPRIORITY BasePriority;
        HANDLE UniqueProcessId;
        HANDLE InheritedFromUniqueProcessId;
        ULONG HandleCount;
        ULONG SessionId;
        ULONG_PTR UniqueProcessKey; // since VISTA (requires SystemExtendedProcessInformation)
        SIZE_T PeakVirtualSize;
        SIZE_T VirtualSize;
        ULONG PageFaultCount;
        SIZE_T PeakWorkingSetSize;
        SIZE_T WorkingSetSize;
        SIZE_T QuotaPeakPagedPoolUsage;
        SIZE_T QuotaPagedPoolUsage;
        SIZE_T QuotaPeakNonPagedPoolUsage;
        SIZE_T QuotaNonPagedPoolUsage;
        SIZE_T PagefileUsage;
        SIZE_T PeakPagefileUsage;
        SIZE_T PrivatePageCount;
        LARGE_INTEGER ReadOperationCount;
        LARGE_INTEGER WriteOperationCount;
        LARGE_INTEGER OtherOperationCount;
        LARGE_INTEGER ReadTransferCount;
        LARGE_INTEGER WriteTransferCount;
        LARGE_INTEGER OtherTransferCount;
        SYSTEM_THREAD_INFORMATION Threads[1]; // SystemProcessInformation
        // SYSTEM_EXTENDED_THREAD_INFORMATION Threads[1]; // SystemExtendedProcessinformation
        // SYSTEM_EXTENDED_THREAD_INFORMATION + SYSTEM_PROCESS_INFORMATION_EXTENSION // SystemFullProcessInformation
    } SYSTEM_PROCESS_INFORMATION, * PSYSTEM_PROCESS_INFORMATION;

    typedef struct _SYSTEM_CALL_COUNT_INFORMATION
    {
        ULONG Length;
        ULONG NumberOfTables;
    } SYSTEM_CALL_COUNT_INFORMATION, * PSYSTEM_CALL_COUNT_INFORMATION;

    typedef struct _SYSTEM_DEVICE_INFORMATION
    {
        ULONG NumberOfDisks;
        ULONG NumberOfFloppies;
        ULONG NumberOfCdRoms;
        ULONG NumberOfTapes;
        ULONG NumberOfSerialPorts;
        ULONG NumberOfParallelPorts;
    } SYSTEM_DEVICE_INFORMATION, * PSYSTEM_DEVICE_INFORMATION;

    typedef struct _SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION
    {
        LARGE_INTEGER IdleTime;
        LARGE_INTEGER KernelTime;
        LARGE_INTEGER UserTime;
        LARGE_INTEGER DpcTime;
        LARGE_INTEGER InterruptTime;
        ULONG InterruptCount;
    } SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION, * PSYSTEM_PROCESSOR_PERFORMANCE_INFORMATION;

    typedef struct _SYSTEM_FLAGS_INFORMATION
    {
        ULONG Flags; // NtGlobalFlag
    } SYSTEM_FLAGS_INFORMATION, * PSYSTEM_FLAGS_INFORMATION;

    // private
    typedef struct _SYSTEM_CALL_TIME_INFORMATION
    {
        ULONG Length;
        ULONG TotalCalls;
        LARGE_INTEGER TimeOfCalls[1];
    } SYSTEM_CALL_TIME_INFORMATION, * PSYSTEM_CALL_TIME_INFORMATION;

    // private
    typedef struct _RTL_PROCESS_LOCK_INFORMATION
    {
        PVOID Address;
        USHORT Type;
        USHORT CreatorBackTraceIndex;
        HANDLE OwningThread;
        LONG LockCount;
        ULONG ContentionCount;
        ULONG EntryCount;
        LONG RecursionCount;
        ULONG NumberOfWaitingShared;
        ULONG NumberOfWaitingExclusive;
    } RTL_PROCESS_LOCK_INFORMATION, * PRTL_PROCESS_LOCK_INFORMATION;

    // private
    typedef struct _RTL_PROCESS_LOCKS
    {
        ULONG NumberOfLocks;
        _Field_size_(NumberOfLocks) RTL_PROCESS_LOCK_INFORMATION Locks[1];
    } RTL_PROCESS_LOCKS, * PRTL_PROCESS_LOCKS;

    // private
    typedef struct _RTL_PROCESS_BACKTRACE_INFORMATION
    {
        PCHAR SymbolicBackTrace;
        ULONG TraceCount;
        USHORT Index;
        USHORT Depth;
        PVOID BackTrace[32];
    } RTL_PROCESS_BACKTRACE_INFORMATION, * PRTL_PROCESS_BACKTRACE_INFORMATION;

    // private
    typedef struct _RTL_PROCESS_BACKTRACES
    {
        ULONG CommittedMemory;
        ULONG ReservedMemory;
        ULONG NumberOfBackTraceLookups;
        ULONG NumberOfBackTraces;
        _Field_size_(NumberOfBackTraces) RTL_PROCESS_BACKTRACE_INFORMATION BackTraces[1];
    } RTL_PROCESS_BACKTRACES, * PRTL_PROCESS_BACKTRACES;

    typedef struct _SYSTEM_HANDLE_TABLE_ENTRY_INFO
    {
        USHORT UniqueProcessId;
        USHORT CreatorBackTraceIndex;
        UCHAR ObjectTypeIndex;
        UCHAR HandleAttributes;
        USHORT HandleValue;
        PVOID Object;
        ULONG GrantedAccess;
    } SYSTEM_HANDLE_TABLE_ENTRY_INFO, * PSYSTEM_HANDLE_TABLE_ENTRY_INFO;

    typedef struct _SYSTEM_HANDLE_INFORMATION
    {
        ULONG NumberOfHandles;
        _Field_size_(NumberOfHandles) SYSTEM_HANDLE_TABLE_ENTRY_INFO Handles[1];
    } SYSTEM_HANDLE_INFORMATION, * PSYSTEM_HANDLE_INFORMATION;

    typedef struct _SYSTEM_OBJECTTYPE_INFORMATION
    {
        ULONG NextEntryOffset;
        ULONG NumberOfObjects;
        ULONG NumberOfHandles;
        ULONG TypeIndex;
        ULONG InvalidAttributes;
        GENERIC_MAPPING GenericMapping;
        ULONG ValidAccessMask;
        ULONG PoolType;
        BOOLEAN SecurityRequired;
        BOOLEAN WaitableObject;
        UNICODE_STRING TypeName;
    } SYSTEM_OBJECTTYPE_INFORMATION, * PSYSTEM_OBJECTTYPE_INFORMATION;

    typedef struct _SYSTEM_OBJECT_INFORMATION
    {
        ULONG NextEntryOffset;
        PVOID Object;
        HANDLE CreatorUniqueProcess;
        USHORT CreatorBackTraceIndex;
        USHORT Flags;
        LONG PointerCount;
        LONG HandleCount;
        ULONG PagedPoolCharge;
        ULONG NonPagedPoolCharge;
        HANDLE ExclusiveProcessId;
        PVOID SecurityDescriptor;
        UNICODE_STRING NameInfo;
    } SYSTEM_OBJECT_INFORMATION, * PSYSTEM_OBJECT_INFORMATION;

    typedef struct _SYSTEM_PAGEFILE_INFORMATION
    {
        ULONG NextEntryOffset;
        ULONG TotalSize;
        ULONG TotalInUse;
        ULONG PeakUsage;
        UNICODE_STRING PageFileName;
    } SYSTEM_PAGEFILE_INFORMATION, * PSYSTEM_PAGEFILE_INFORMATION;

    typedef struct _SYSTEM_VDM_INSTEMUL_INFO
    {
        ULONG SegmentNotPresent;
        ULONG VdmOpcode0F;
        ULONG OpcodeESPrefix;
        ULONG OpcodeCSPrefix;
        ULONG OpcodeSSPrefix;
        ULONG OpcodeDSPrefix;
        ULONG OpcodeFSPrefix;
        ULONG OpcodeGSPrefix;
        ULONG OpcodeOPER32Prefix;
        ULONG OpcodeADDR32Prefix;
        ULONG OpcodeINSB;
        ULONG OpcodeINSW;
        ULONG OpcodeOUTSB;
        ULONG OpcodeOUTSW;
        ULONG OpcodePUSHF;
        ULONG OpcodePOPF;
        ULONG OpcodeINTnn;
        ULONG OpcodeINTO;
        ULONG OpcodeIRET;
        ULONG OpcodeINBimm;
        ULONG OpcodeINWimm;
        ULONG OpcodeOUTBimm;
        ULONG OpcodeOUTWimm;
        ULONG OpcodeINB;
        ULONG OpcodeINW;
        ULONG OpcodeOUTB;
        ULONG OpcodeOUTW;
        ULONG OpcodeLOCKPrefix;
        ULONG OpcodeREPNEPrefix;
        ULONG OpcodeREPPrefix;
        ULONG OpcodeHLT;
        ULONG OpcodeCLI;
        ULONG OpcodeSTI;
        ULONG BopCount;
    } SYSTEM_VDM_INSTEMUL_INFO, * PSYSTEM_VDM_INSTEMUL_INFO;

#define MM_WORKING_SET_MAX_HARD_ENABLE 0x1
#define MM_WORKING_SET_MAX_HARD_DISABLE 0x2
#define MM_WORKING_SET_MIN_HARD_ENABLE 0x4
#define MM_WORKING_SET_MIN_HARD_DISABLE 0x8

    typedef struct _SYSTEM_FILECACHE_INFORMATION
    {
        SIZE_T CurrentSize;
        SIZE_T PeakSize;
        ULONG PageFaultCount;
        SIZE_T MinimumWorkingSet;
        SIZE_T MaximumWorkingSet;
        SIZE_T CurrentSizeIncludingTransitionInPages;
        SIZE_T PeakSizeIncludingTransitionInPages;
        ULONG TransitionRePurposeCount;
        ULONG Flags;
    } SYSTEM_FILECACHE_INFORMATION, * PSYSTEM_FILECACHE_INFORMATION;

    // Can be used instead of SYSTEM_FILECACHE_INFORMATION
    typedef struct _SYSTEM_BASIC_WORKING_SET_INFORMATION
    {
        SIZE_T CurrentSize;
        SIZE_T PeakSize;
        ULONG PageFaultCount;
    } SYSTEM_BASIC_WORKING_SET_INFORMATION, * PSYSTEM_BASIC_WORKING_SET_INFORMATION;

    typedef struct _SYSTEM_POOLTAG
    {
        union
        {
            UCHAR Tag[4];
            ULONG TagUlong;
        };
        ULONG PagedAllocs;
        ULONG PagedFrees;
        SIZE_T PagedUsed;
        ULONG NonPagedAllocs;
        ULONG NonPagedFrees;
        SIZE_T NonPagedUsed;
    } SYSTEM_POOLTAG, * PSYSTEM_POOLTAG;

    typedef struct _SYSTEM_POOLTAG_INFORMATION
    {
        ULONG Count;
        _Field_size_(Count) SYSTEM_POOLTAG TagInfo[1];
    } SYSTEM_POOLTAG_INFORMATION, * PSYSTEM_POOLTAG_INFORMATION;

    typedef struct _SYSTEM_INTERRUPT_INFORMATION
    {
        ULONG ContextSwitches;
        ULONG DpcCount;
        ULONG DpcRate;
        ULONG TimeIncrement;
        ULONG DpcBypassCount;
        ULONG ApcBypassCount;
    } SYSTEM_INTERRUPT_INFORMATION, * PSYSTEM_INTERRUPT_INFORMATION;

    typedef struct _SYSTEM_DPC_BEHAVIOR_INFORMATION
    {
        ULONG Spare;
        ULONG DpcQueueDepth;
        ULONG MinimumDpcRate;
        ULONG AdjustDpcThreshold;
        ULONG IdealDpcRate;
    } SYSTEM_DPC_BEHAVIOR_INFORMATION, * PSYSTEM_DPC_BEHAVIOR_INFORMATION;

    typedef struct _SYSTEM_QUERY_TIME_ADJUST_INFORMATION
    {
        ULONG TimeAdjustment;
        ULONG TimeIncrement;
        BOOLEAN Enable;
    } SYSTEM_QUERY_TIME_ADJUST_INFORMATION, * PSYSTEM_QUERY_TIME_ADJUST_INFORMATION;

    typedef struct _SYSTEM_QUERY_TIME_ADJUST_INFORMATION_PRECISE
    {
        ULONGLONG TimeAdjustment;
        ULONGLONG TimeIncrement;
        BOOLEAN Enable;
    } SYSTEM_QUERY_TIME_ADJUST_INFORMATION_PRECISE, * PSYSTEM_QUERY_TIME_ADJUST_INFORMATION_PRECISE;

    typedef struct _SYSTEM_SET_TIME_ADJUST_INFORMATION
    {
        ULONG TimeAdjustment;
        BOOLEAN Enable;
    } SYSTEM_SET_TIME_ADJUST_INFORMATION, * PSYSTEM_SET_TIME_ADJUST_INFORMATION;

    typedef struct _SYSTEM_SET_TIME_ADJUST_INFORMATION_PRECISE
    {
        ULONGLONG TimeAdjustment;
        BOOLEAN Enable;
    } SYSTEM_SET_TIME_ADJUST_INFORMATION_PRECISE, * PSYSTEM_SET_TIME_ADJUST_INFORMATION_PRECISE;

#ifndef _TRACEHANDLE_DEFINED
#define _TRACEHANDLE_DEFINED
    typedef ULONG64 TRACEHANDLE, * PTRACEHANDLE;
#endif

    typedef enum _EVENT_TRACE_INFORMATION_CLASS
    {
        EventTraceKernelVersionInformation, // EVENT_TRACE_VERSION_INFORMATION
        EventTraceGroupMaskInformation, // EVENT_TRACE_GROUPMASK_INFORMATION
        EventTracePerformanceInformation, // EVENT_TRACE_PERFORMANCE_INFORMATION
        EventTraceTimeProfileInformation, // EVENT_TRACE_TIME_PROFILE_INFORMATION
        EventTraceSessionSecurityInformation, // EVENT_TRACE_SESSION_SECURITY_INFORMATION
        EventTraceSpinlockInformation, // EVENT_TRACE_SPINLOCK_INFORMATION
        EventTraceStackTracingInformation, // EVENT_TRACE_STACK_TRACING_INFORMATION
        EventTraceExecutiveResourceInformation, // EVENT_TRACE_EXECUTIVE_RESOURCE_INFORMATION
        EventTraceHeapTracingInformation, // EVENT_TRACE_HEAP_TRACING_INFORMATION
        EventTraceHeapSummaryTracingInformation, // EVENT_TRACE_HEAP_TRACING_INFORMATION
        EventTracePoolTagFilterInformation, // EVENT_TRACE_POOLTAG_FILTER_INFORMATION
        EventTracePebsTracingInformation, // EVENT_TRACE_PEBS_TRACING_INFORMATION
        EventTraceProfileConfigInformation, // EVENT_TRACE_PROFILE_CONFIG_INFORMATION
        EventTraceProfileSourceListInformation, // EVENT_TRACE_PROFILE_LIST_INFORMATION
        EventTraceProfileEventListInformation, // EVENT_TRACE_PROFILE_EVENT_INFORMATION
        EventTraceProfileCounterListInformation, // EVENT_TRACE_PROFILE_COUNTER_INFORMATION
        EventTraceStackCachingInformation, // EVENT_TRACE_STACK_CACHING_INFORMATION
        EventTraceObjectTypeFilterInformation, // EVENT_TRACE_OBJECT_TYPE_FILTER_INFORMATION
        EventTraceSoftRestartInformation, // EVENT_TRACE_SOFT_RESTART_INFORMATION
        EventTraceLastBranchConfigurationInformation, // REDSTONE3
        EventTraceLastBranchEventListInformation,
        EventTraceProfileSourceAddInformation, // EVENT_TRACE_PROFILE_ADD_INFORMATION // REDSTONE4
        EventTraceProfileSourceRemoveInformation, // EVENT_TRACE_PROFILE_REMOVE_INFORMATION
        EventTraceProcessorTraceConfigurationInformation,
        EventTraceProcessorTraceEventListInformation,
        EventTraceCoverageSamplerInformation, // EVENT_TRACE_COVERAGE_SAMPLER_INFORMATION
        EventTraceUnifiedStackCachingInformation, // since 21H1
        MaxEventTraceInfoClass
    } EVENT_TRACE_INFORMATION_CLASS;

    typedef struct _TRACE_ENABLE_FLAG_EXTENSION
    {
        USHORT Offset; // Offset to the flag array in structure
        UCHAR Length; // Length of flag array in ULONGs
        UCHAR Flag; // Must be set to EVENT_TRACE_FLAG_EXTENSION
    } TRACE_ENABLE_FLAG_EXTENSION, * PTRACE_ENABLE_FLAG_EXTENSION;

    typedef struct _TRACE_ENABLE_FLAG_EXT_HEADER
    {
        USHORT Length; // Length in ULONGs
        USHORT Items; // # of items
    } TRACE_ENABLE_FLAG_EXT_HEADER, * PTRACE_ENABLE_FLAG_EXT_HEADER;

    typedef struct _TRACE_ENABLE_FLAG_EXT_ITEM
    {
        USHORT Offset; // Offset to the next block
        USHORT Type; // Extension type
    } TRACE_ENABLE_FLAG_EXT_ITEM, * PTRACE_ENABLE_FLAG_EXT_ITEM;

#define EVENT_TRACE_FLAG_EXT_ITEMS 0x80FF0000    // New extension structure
#define EVENT_TRACE_FLAG_EXT_LEN_NEW_STRUCT 0xFF // Pseudo length to denote new struct format

#define ETW_MINIMUM_CACHED_STACK_LENGTH 4
#define ETW_SW_ARRAY_SIZE          256     // Frame Count allocated in lookaside list
#define ETW_STACK_SW_ARRAY_SIZE    192     // Frame Count allocated in stack
#define ETW_MAX_STACKWALK_FILTER   256 // Max number of HookId's
#define ETW_MAX_TAG_FILTER         4
#define ETW_MAX_POOLTAG_FILTER     ETW_MAX_TAG_FILTER

#define ETW_EXT_ENABLE_FLAGS       0x0001
#define ETW_EXT_PIDS               0x0002
#define ETW_EXT_STACKWALK_FILTER   0x0003
#define ETW_EXT_POOLTAG_FILTER     0x0004
#define ETW_EXT_STACK_CACHING      0x0005

    // Extended item for configuring stack caching.
    typedef struct _ETW_STACK_CACHING_CONFIG
    {
        ULONG CacheSize;
        ULONG BucketCount;
    } ETW_STACK_CACHING_CONFIG, * PETW_STACK_CACHING_CONFIG;

    // The second bit is set if the trace is used by PM & CP (fixed headers)
    // If not, the data block is used by for finer data for performance analysis
    //
#define TRACE_HEADER_EVENT_TRACE 0x40000000
//
// If set, the data block is SYSTEM_TRACE_HEADER
//
#define TRACE_HEADER_ENUM_MASK 0x00FF0000

#define PERF_MASK_INDEX (0xe0000000)
#define PERF_MASK_GROUP (~PERF_MASK_INDEX)
#define PERF_NUM_MASKS 8

#define PERF_GET_MASK_INDEX(GM) (((GM) & PERF_MASK_INDEX) >> 29)
#define PERF_GET_MASK_GROUP(GM) ((GM) & PERF_MASK_GROUP)
#define PERFINFO_OR_GROUP_WITH_GROUPMASK(Group, pGroupMask) \
    (pGroupMask)->Masks[PERF_GET_MASK_INDEX(Group)] |= PERF_GET_MASK_GROUP(Group);

// Masks[0]
#define PERF_PROCESS            EVENT_TRACE_FLAG_PROCESS
#define PERF_THREAD             EVENT_TRACE_FLAG_THREAD
#define PERF_PROC_THREAD        EVENT_TRACE_FLAG_PROCESS | EVENT_TRACE_FLAG_THREAD
#define PERF_LOADER             EVENT_TRACE_FLAG_IMAGE_LOAD
#define PERF_PERF_COUNTER       EVENT_TRACE_FLAG_PROCESS_COUNTERS
#define PERF_FILENAME           EVENT_TRACE_FLAG_DISK_FILE_IO
#define PERF_DISK_IO            EVENT_TRACE_FLAG_DISK_FILE_IO | EVENT_TRACE_FLAG_DISK_IO
#define PERF_DISK_IO_INIT       EVENT_TRACE_FLAG_DISK_IO_INIT
#define PERF_ALL_FAULTS         EVENT_TRACE_FLAG_MEMORY_PAGE_FAULTS
#define PERF_HARD_FAULTS        EVENT_TRACE_FLAG_MEMORY_HARD_FAULTS
#define PERF_VAMAP              EVENT_TRACE_FLAG_VAMAP
#define PERF_NETWORK            EVENT_TRACE_FLAG_NETWORK_TCPIP
#define PERF_REGISTRY           EVENT_TRACE_FLAG_REGISTRY
#define PERF_DBGPRINT           EVENT_TRACE_FLAG_DBGPRINT
#define PERF_JOB                EVENT_TRACE_FLAG_JOB
#define PERF_ALPC               EVENT_TRACE_FLAG_ALPC
#define PERF_SPLIT_IO           EVENT_TRACE_FLAG_SPLIT_IO
#define PERF_DEBUG_EVENTS       EVENT_TRACE_FLAG_DEBUG_EVENTS
#define PERF_FILE_IO            EVENT_TRACE_FLAG_FILE_IO
#define PERF_FILE_IO_INIT       EVENT_TRACE_FLAG_FILE_IO_INIT
#define PERF_NO_SYSCONFIG       EVENT_TRACE_FLAG_NO_SYSCONFIG

// Masks[1]
#define PERF_MEMORY             0x20000001
#define PERF_PROFILE            0x20000002  // equivalent to EVENT_TRACE_FLAG_PROFILE
#define PERF_CONTEXT_SWITCH     0x20000004  // equivalent to EVENT_TRACE_FLAG_CSWITCH
#define PERF_FOOTPRINT          0x20000008
#define PERF_DRIVERS            0x20000010  // equivalent to EVENT_TRACE_FLAG_DRIVER
#define PERF_REFSET             0x20000020
#define PERF_POOL               0x20000040
#define PERF_POOLTRACE          0x20000041
#define PERF_DPC                0x20000080  // equivalent to EVENT_TRACE_FLAG_DPC
#define PERF_COMPACT_CSWITCH    0x20000100
#define PERF_DISPATCHER         0x20000200  // equivalent to EVENT_TRACE_FLAG_DISPATCHER
#define PERF_PMC_PROFILE        0x20000400
#define PERF_PROFILING          0x20000402
#define PERF_PROCESS_INSWAP     0x20000800
#define PERF_AFFINITY           0x20001000
#define PERF_PRIORITY           0x20002000
#define PERF_INTERRUPT          0x20004000  // equivalent to EVENT_TRACE_FLAG_INTERRUPT
#define PERF_VIRTUAL_ALLOC      0x20008000  // equivalent to EVENT_TRACE_FLAG_VIRTUAL_ALLOC
#define PERF_SPINLOCK           0x20010000
#define PERF_SYNC_OBJECTS       0x20020000
#define PERF_DPC_QUEUE          0x20040000
#define PERF_MEMINFO            0x20080000
#define PERF_CONTMEM_GEN        0x20100000
#define PERF_SPINLOCK_CNTRS     0x20200000
#define PERF_SPININSTR          0x20210000
#define PERF_SESSION            0x20400000
#define PERF_PFSECTION          0x20400000
#define PERF_MEMINFO_WS         0x20800000
#define PERF_KERNEL_QUEUE       0x21000000
#define PERF_INTERRUPT_STEER    0x22000000
#define PERF_SHOULD_YIELD       0x24000000
#define PERF_WS                 0x28000000
//#define PERF_POOLTRACE (PERF_MEMORY | PERF_POOL)
//#define PERF_PROFILING (PERF_PROFILE | PERF_PMC_PROFILE)
//#define PERF_SPININSTR (PERF_SPINLOCK | PERF_SPINLOCK_CNTRS)

// Masks[2]
#define PERF_ANTI_STARVATION    0x40000001
#define PERF_PROCESS_FREEZE     0x40000002
#define PERF_PFN_LIST           0x40000004
#define PERF_WS_DETAIL          0x40000008
#define PERF_WS_ENTRY           0x40000010
#define PERF_HEAP               0x40000020
#define PERF_SYSCALL            0x40000040  // equivalent to EVENT_TRACE_FLAG_SYSTEMCALL
#define PERF_UMS                0x40000080
#define PERF_BACKTRACE          0x40000100
#define PERF_VULCAN             0x40000200
#define PERF_OBJECTS            0x40000400
#define PERF_EVENTS             0x40000800
#define PERF_FULLTRACE          0x40001000
#define PERF_DFSS               0x40002000
#define PERF_PREFETCH           0x40004000
#define PERF_PROCESSOR_IDLE     0x40008000
#define PERF_CPU_CONFIG         0x40010000
#define PERF_TIMER              0x40020000
#define PERF_CLOCK_INTERRUPT    0x40040000
#define PERF_LOAD_BALANCER      0x40080000
#define PERF_CLOCK_TIMER        0x40100000
#define PERF_IDLE_SELECTION     0x40200000
#define PERF_IPI                0x40400000
#define PERF_IO_TIMER           0x40800000
#define PERF_REG_HIVE           0x41000000
#define PERF_REG_NOTIF          0x42000000
#define PERF_PPM_EXIT_LATENCY   0x44000000
#define PERF_WORKER_THREAD      0x48000000

// Masks[4]
#define PERF_OPTICAL_IO         0x80000001
#define PERF_OPTICAL_IO_INIT    0x80000002
// Reserved                     0x80000004
#define PERF_DLL_INFO           0x80000008
#define PERF_DLL_FLUSH_WS       0x80000010
// Reserved                     0x80000020
#define PERF_OB_HANDLE          0x80000040
#define PERF_OB_OBJECT          0x80000080
// Reserved                     0x80000100
#define PERF_WAKE_DROP          0x80000200
#define PERF_WAKE_EVENT         0x80000400
#define PERF_DEBUGGER           0x80000800
#define PERF_PROC_ATTACH        0x80001000
#define PERF_WAKE_COUNTER       0x80002000
// Reserved                     0x80004000
#define PERF_POWER              0x80008000
#define PERF_SOFT_TRIM          0x80010000
#define PERF_CC                 0x80020000
// Reserved                     0x80040000
#define PERF_FLT_IO_INIT        0x80080000
#define PERF_FLT_IO             0x80100000
#define PERF_FLT_FASTIO         0x80200000
#define PERF_FLT_IO_FAILURE     0x80400000
#define PERF_HV_PROFILE         0x80800000
#define PERF_WDF_DPC            0x81000000
#define PERF_WDF_INTERRUPT      0x82000000
#define PERF_CACHE_FLUSH        0x84000000

// Masks[5]
#define PERF_HIBER_RUNDOWN      0xA0000001

// Masks[6]
#define PERF_SYSCFG_SYSTEM      0xC0000001
#define PERF_SYSCFG_GRAPHICS    0xC0000002
#define PERF_SYSCFG_STORAGE     0xC0000004
#define PERF_SYSCFG_NETWORK     0xC0000008
#define PERF_SYSCFG_SERVICES    0xC0000010
#define PERF_SYSCFG_PNP         0xC0000020
#define PERF_SYSCFG_OPTICAL     0xC0000040
#define PERF_SYSCFG_ALL         0xDFFFFFFF

// Masks[7] - Control Mask. All flags that change system behavior go here.
#define PERF_CLUSTER_OFF        0xE0000001
#define PERF_MEMORY_CONTROL     0xE0000002

// The predefined event groups or families for NT subsystems
#define EVENT_TRACE_GROUP_HEADER               0x0000
#define EVENT_TRACE_GROUP_IO                   0x0100
#define EVENT_TRACE_GROUP_MEMORY               0x0200
#define EVENT_TRACE_GROUP_PROCESS              0x0300
#define EVENT_TRACE_GROUP_FILE                 0x0400
#define EVENT_TRACE_GROUP_THREAD               0x0500
#define EVENT_TRACE_GROUP_TCPIP                0x0600
#define EVENT_TRACE_GROUP_JOB                  0x0700
#define EVENT_TRACE_GROUP_UDPIP                0x0800
#define EVENT_TRACE_GROUP_REGISTRY             0x0900
#define EVENT_TRACE_GROUP_DBGPRINT             0x0A00
#define EVENT_TRACE_GROUP_CONFIG               0x0B00
#define EVENT_TRACE_GROUP_SPARE1               0x0C00   // Spare1
#define EVENT_TRACE_GROUP_WNF                  0x0D00
#define EVENT_TRACE_GROUP_POOL                 0x0E00
#define EVENT_TRACE_GROUP_PERFINFO             0x0F00
#define EVENT_TRACE_GROUP_HEAP                 0x1000
#define EVENT_TRACE_GROUP_OBJECT               0x1100
#define EVENT_TRACE_GROUP_POWER                0x1200
#define EVENT_TRACE_GROUP_MODBOUND             0x1300
#define EVENT_TRACE_GROUP_IMAGE                0x1400
#define EVENT_TRACE_GROUP_DPC                  0x1500
#define EVENT_TRACE_GROUP_CC                   0x1600
#define EVENT_TRACE_GROUP_CRITSEC              0x1700
#define EVENT_TRACE_GROUP_STACKWALK            0x1800
#define EVENT_TRACE_GROUP_UMS                  0x1900
#define EVENT_TRACE_GROUP_ALPC                 0x1A00
#define EVENT_TRACE_GROUP_SPLITIO              0x1B00
#define EVENT_TRACE_GROUP_THREAD_POOL          0x1C00
#define EVENT_TRACE_GROUP_HYPERVISOR           0x1D00
#define EVENT_TRACE_GROUP_HYPERVISORX          0x1E00

//
// Event for header
//
#define WMI_LOG_TYPE_HEADER                       (EVENT_TRACE_GROUP_HEADER | EVENT_TRACE_TYPE_INFO)
#define WMI_LOG_TYPE_HEADER_EXTENSION             (EVENT_TRACE_GROUP_HEADER | EVENT_TRACE_TYPE_EXTENSION)
#define WMI_LOG_TYPE_RUNDOWN_COMPLETE             (EVENT_TRACE_GROUP_HEADER | EVENT_TRACE_TYPE_CHECKPOINT)
#define WMI_LOG_TYPE_GROUP_MASKS_END              (EVENT_TRACE_GROUP_HEADER | 0x20)
#define WMI_LOG_TYPE_RUNDOWN_BEGIN                (EVENT_TRACE_GROUP_HEADER | 0x30)
#define WMI_LOG_TYPE_RUNDOWN_END                  (EVENT_TRACE_GROUP_HEADER | 0x31)
#define WMI_LOG_TYPE_DBGID_RSDS                   (EVENT_TRACE_GROUP_HEADER | EVENT_TRACE_TYPE_DBGID_RSDS)
#define WMI_LOG_TYPE_DBGID_NB10                   (EVENT_TRACE_GROUP_HEADER | 0x41)
#define WMI_LOG_TYPE_BUILD_LAB                    (EVENT_TRACE_GROUP_HEADER | 0x42)
#define WMI_LOG_TYPE_BINARY_PATH                  (EVENT_TRACE_GROUP_HEADER | 0x43)

//
// Event for system config
//
#define WMI_LOG_TYPE_CONFIG_CPU                   (EVENT_TRACE_GROUP_CONFIG | EVENT_TRACE_TYPE_CONFIG_CPU)
#define WMI_LOG_TYPE_CONFIG_PHYSICALDISK          (EVENT_TRACE_GROUP_CONFIG | EVENT_TRACE_TYPE_CONFIG_PHYSICALDISK)
#define WMI_LOG_TYPE_CONFIG_LOGICALDISK           (EVENT_TRACE_GROUP_CONFIG | EVENT_TRACE_TYPE_CONFIG_LOGICALDISK)
#define WMI_LOG_TYPE_CONFIG_OPTICALMEDIA          (EVENT_TRACE_GROUP_CONFIG | EVENT_TRACE_TYPE_CONFIG_OPTICALMEDIA)
#define WMI_LOG_TYPE_CONFIG_NIC                   (EVENT_TRACE_GROUP_CONFIG | EVENT_TRACE_TYPE_CONFIG_NIC)
#define WMI_LOG_TYPE_CONFIG_VIDEO                 (EVENT_TRACE_GROUP_CONFIG | EVENT_TRACE_TYPE_CONFIG_VIDEO)
#define WMI_LOG_TYPE_CONFIG_SERVICES              (EVENT_TRACE_GROUP_CONFIG | EVENT_TRACE_TYPE_CONFIG_SERVICES)
#define WMI_LOG_TYPE_CONFIG_POWER                 (EVENT_TRACE_GROUP_CONFIG | EVENT_TRACE_TYPE_CONFIG_POWER)
#define WMI_LOG_TYPE_CONFIG_OSVERSION             (EVENT_TRACE_GROUP_CONFIG | EVENT_TRACE_TYPE_CONFIG_OSVERSION)
#define WMI_LOG_TYPE_CONFIG_VISUALTHEME           (EVENT_TRACE_GROUP_CONFIG | EVENT_TRACE_TYPE_CONFIG_VISUALTHEME)
#define WMI_LOG_TYPE_CONFIG_SYSTEMRANGE           (EVENT_TRACE_GROUP_CONFIG | EVENT_TRACE_TYPE_CONFIG_SYSTEMRANGE)
#define WMI_LOG_TYPE_CONFIG_SYSDLLINFO            (EVENT_TRACE_GROUP_CONFIG | EVENT_TRACE_TYPE_CONFIG_SYSDLLINFO)
#define WMI_LOG_TYPE_CONFIG_IRQ                   (EVENT_TRACE_GROUP_CONFIG | EVENT_TRACE_TYPE_CONFIG_IRQ)
#define WMI_LOG_TYPE_CONFIG_PNP                   (EVENT_TRACE_GROUP_CONFIG | EVENT_TRACE_TYPE_CONFIG_PNP)
#define WMI_LOG_TYPE_CONFIG_IDECHANNEL            (EVENT_TRACE_GROUP_CONFIG | EVENT_TRACE_TYPE_CONFIG_IDECHANNEL)
#define WMI_LOG_TYPE_CONFIG_NUMANODE              (EVENT_TRACE_GROUP_CONFIG | EVENT_TRACE_TYPE_CONFIG_NUMANODE)
#define WMI_LOG_TYPE_CONFIG_PLATFORM              (EVENT_TRACE_GROUP_CONFIG | EVENT_TRACE_TYPE_CONFIG_PLATFORM)
#define WMI_LOG_TYPE_CONFIG_PROCESSORGROUP        (EVENT_TRACE_GROUP_CONFIG | EVENT_TRACE_TYPE_CONFIG_PROCESSORGROUP)
#define WMI_LOG_TYPE_CONFIG_PROCESSORNUMBER       (EVENT_TRACE_GROUP_CONFIG | EVENT_TRACE_TYPE_CONFIG_PROCESSORNUMBER)
#define WMI_LOG_TYPE_CONFIG_DPI                   (EVENT_TRACE_GROUP_CONFIG | EVENT_TRACE_TYPE_CONFIG_DPI)
#define WMI_LOG_TYPE_CONFIG_CODEINTEGRITY         (EVENT_TRACE_GROUP_CONFIG | EVENT_TRACE_TYPE_CONFIG_CI_INFO)
#define WMI_LOG_TYPE_CONFIG_MACHINEID             (EVENT_TRACE_GROUP_CONFIG | EVENT_TRACE_TYPE_CONFIG_MACHINEID)

//
// Event for Image and File Name
//
#define PERFINFO_LOG_TYPE_FILENAME                  (EVENT_TRACE_GROUP_FILE | EVENT_TRACE_TYPE_INFO)
#define PERFINFO_LOG_TYPE_FILENAME_CREATE           (EVENT_TRACE_GROUP_FILE | 0x20)
#define PERFINFO_LOG_TYPE_FILENAME_SAME             (EVENT_TRACE_GROUP_FILE | 0x21)
#define PERFINFO_LOG_TYPE_FILENAME_NULL             (EVENT_TRACE_GROUP_FILE | 0x22)
#define PERFINFO_LOG_TYPE_FILENAME_DELETE           (EVENT_TRACE_GROUP_FILE | 0x23)
#define PERFINFO_LOG_TYPE_FILENAME_RUNDOWN          (EVENT_TRACE_GROUP_FILE | 0x24)

#define PERFINFO_LOG_TYPE_MAPFILE                   (EVENT_TRACE_GROUP_FILE | 0x25)
#define PERFINFO_LOG_TYPE_UNMAPFILE                 (EVENT_TRACE_GROUP_FILE | 0x26)
#define PERFINFO_LOG_TYPE_MAPFILE_DC_START          (EVENT_TRACE_GROUP_FILE | 0x27)
#define PERFINFO_LOG_TYPE_MAPFILE_DC_END            (EVENT_TRACE_GROUP_FILE | 0x28)

#define PERFINFO_LOG_TYPE_FILE_IO_CREATE            (EVENT_TRACE_GROUP_FILE | 0x40)
#define PERFINFO_LOG_TYPE_FILE_IO_CLEANUP           (EVENT_TRACE_GROUP_FILE | 0x41)
#define PERFINFO_LOG_TYPE_FILE_IO_CLOSE             (EVENT_TRACE_GROUP_FILE | 0x42)
#define PERFINFO_LOG_TYPE_FILE_IO_READ              (EVENT_TRACE_GROUP_FILE | 0x43)
#define PERFINFO_LOG_TYPE_FILE_IO_WRITE             (EVENT_TRACE_GROUP_FILE | 0x44)
#define PERFINFO_LOG_TYPE_FILE_IO_SET_INFORMATION   (EVENT_TRACE_GROUP_FILE | 0x45)
#define PERFINFO_LOG_TYPE_FILE_IO_DELETE            (EVENT_TRACE_GROUP_FILE | 0x46)
#define PERFINFO_LOG_TYPE_FILE_IO_RENAME            (EVENT_TRACE_GROUP_FILE | 0x47)
#define PERFINFO_LOG_TYPE_FILE_IO_DIRENUM           (EVENT_TRACE_GROUP_FILE | 0x48)
#define PERFINFO_LOG_TYPE_FILE_IO_FLUSH             (EVENT_TRACE_GROUP_FILE | 0x49)
#define PERFINFO_LOG_TYPE_FILE_IO_QUERY_INFORMATION (EVENT_TRACE_GROUP_FILE | 0x4A)
#define PERFINFO_LOG_TYPE_FILE_IO_FS_CONTROL        (EVENT_TRACE_GROUP_FILE | 0x4B)
#define PERFINFO_LOG_TYPE_FILE_IO_OPERATION_END     (EVENT_TRACE_GROUP_FILE | 0x4C)
#define PERFINFO_LOG_TYPE_FILE_IO_DIRNOTIFY         (EVENT_TRACE_GROUP_FILE | 0x4D)
#define PERFINFO_LOG_TYPE_FILE_IO_CREATE_NEW        (EVENT_TRACE_GROUP_FILE | 0x4E)
#define PERFINFO_LOG_TYPE_FILE_IO_DELETE_PATH       (EVENT_TRACE_GROUP_FILE | 0x4F)
#define PERFINFO_LOG_TYPE_FILE_IO_RENAME_PATH       (EVENT_TRACE_GROUP_FILE | 0x50)
#define PERFINFO_LOG_TYPE_FILE_IO_SETLINK_PATH      (EVENT_TRACE_GROUP_FILE | 0x51)
#define PERFINFO_LOG_TYPE_FILE_IO_SETLINK           (EVENT_TRACE_GROUP_FILE | 0x52)

//
//  Event types for minifilter callbacks
//

#define PERFINFO_LOG_TYPE_FLT_PREOP_INIT        (EVENT_TRACE_GROUP_FILE | EVENT_TRACE_TYPE_FLT_PREOP_INIT)
#define PERFINFO_LOG_TYPE_FLT_POSTOP_INIT       (EVENT_TRACE_GROUP_FILE | EVENT_TRACE_TYPE_FLT_POSTOP_INIT)
#define PERFINFO_LOG_TYPE_FLT_PREOP_COMPLETION  (EVENT_TRACE_GROUP_FILE | EVENT_TRACE_TYPE_FLT_PREOP_COMPLETION)
#define PERFINFO_LOG_TYPE_FLT_POSTOP_COMPLETION (EVENT_TRACE_GROUP_FILE | EVENT_TRACE_TYPE_FLT_POSTOP_COMPLETION)
#define PERFINFO_LOG_TYPE_FLT_PREOP_FAILURE     (EVENT_TRACE_GROUP_FILE | EVENT_TRACE_TYPE_FLT_PREOP_FAILURE)
#define PERFINFO_LOG_TYPE_FLT_POSTOP_FAILURE    (EVENT_TRACE_GROUP_FILE | EVENT_TRACE_TYPE_FLT_POSTOP_FAILURE)

//
// Event types for Job
//

#define WMI_LOG_TYPE_JOB_CREATE                     (EVENT_TRACE_GROUP_JOB | 0x20)
#define WMI_LOG_TYPE_JOB_TERMINATE                  (EVENT_TRACE_GROUP_JOB | 0x21)
#define WMI_LOG_TYPE_JOB_OPEN                       (EVENT_TRACE_GROUP_JOB | 0x22)
#define WMI_LOG_TYPE_JOB_ASSIGN_PROCESS             (EVENT_TRACE_GROUP_JOB | 0x23)
#define WMI_LOG_TYPE_JOB_REMOVE_PROCESS             (EVENT_TRACE_GROUP_JOB | 0x24)
#define WMI_LOG_TYPE_JOB_SET                        (EVENT_TRACE_GROUP_JOB | 0x25)
#define WMI_LOG_TYPE_JOB_QUERY                      (EVENT_TRACE_GROUP_JOB | 0x26)
#define WMI_LOG_TYPE_JOB_SET_FAILED                 (EVENT_TRACE_GROUP_JOB | 0x27)
#define WMI_LOG_TYPE_JOB_QUERY_FAILED               (EVENT_TRACE_GROUP_JOB | 0x28)
#define WMI_LOG_TYPE_JOB_SET_NOTIFICATION           (EVENT_TRACE_GROUP_JOB | 0x29)
#define WMI_LOG_TYPE_JOB_SEND_NOTIFICATION          (EVENT_TRACE_GROUP_JOB | 0x2A)
#define WMI_LOG_TYPE_JOB_QUERY_VIOLATION            (EVENT_TRACE_GROUP_JOB | 0x2B)
#define WMI_LOG_TYPE_JOB_SET_CPU_RATE               (EVENT_TRACE_GROUP_JOB | 0x2C)
#define WMI_LOG_TYPE_JOB_SET_NET_RATE               (EVENT_TRACE_GROUP_JOB | 0x2D)

//
// Event types for Process
//

#define WMI_LOG_TYPE_PROCESS_CREATE                 (EVENT_TRACE_GROUP_PROCESS | EVENT_TRACE_TYPE_START)
#define WMI_LOG_TYPE_PROCESS_DELETE                 (EVENT_TRACE_GROUP_PROCESS | EVENT_TRACE_TYPE_END)
#define WMI_LOG_TYPE_PROCESS_DC_START               (EVENT_TRACE_GROUP_PROCESS | EVENT_TRACE_TYPE_DC_START)
#define WMI_LOG_TYPE_PROCESS_DC_END                 (EVENT_TRACE_GROUP_PROCESS | EVENT_TRACE_TYPE_DC_END)
#define WMI_LOG_TYPE_PROCESS_LOAD_IMAGE             (EVENT_TRACE_GROUP_PROCESS | EVENT_TRACE_TYPE_LOAD)
#define WMI_LOG_TYPE_PROCESS_TERMINATE              (EVENT_TRACE_GROUP_PROCESS | EVENT_TRACE_TYPE_TERMINATE)

#define PERFINFO_LOG_TYPE_PROCESS_PERFCTR_END       (EVENT_TRACE_GROUP_PROCESS | 0x20)
#define PERFINFO_LOG_TYPE_PROCESS_PERFCTR_RD        (EVENT_TRACE_GROUP_PROCESS | 0x21)
// Reserved                                         (EVENT_TRACE_GROUP_PROCESS | 0x22)
#define PERFINFO_LOG_TYPE_INSWAPPROCESS             (EVENT_TRACE_GROUP_PROCESS | 0x23)
#define PERFINFO_LOG_TYPE_PROCESS_FREEZE            (EVENT_TRACE_GROUP_PROCESS | 0x24)
#define PERFINFO_LOG_TYPE_PROCESS_THAW              (EVENT_TRACE_GROUP_PROCESS | 0x25)
#define PERFINFO_LOG_TYPE_BOOT_PHASE_START          (EVENT_TRACE_GROUP_PROCESS | 0x26)
#define PERFINFO_LOG_TYPE_ZOMBIE_PROCESS            (EVENT_TRACE_GROUP_PROCESS | 0x27)
#define PERFINFO_LOG_TYPE_PROCESS_SET_AFFINITY      (EVENT_TRACE_GROUP_PROCESS | 0x28)

#define PERFINFO_LOG_TYPE_CHARGE_WAKE_COUNTER_USER             (EVENT_TRACE_GROUP_PROCESS | 0x30)
#define PERFINFO_LOG_TYPE_CHARGE_WAKE_COUNTER_EXECUTION        (EVENT_TRACE_GROUP_PROCESS | 0x31)
#define PERFINFO_LOG_TYPE_CHARGE_WAKE_COUNTER_KERNEL           (EVENT_TRACE_GROUP_PROCESS | 0x32)
#define PERFINFO_LOG_TYPE_CHARGE_WAKE_COUNTER_INSTRUMENTATION  (EVENT_TRACE_GROUP_PROCESS | 0x33)
#define PERFINFO_LOG_TYPE_CHARGE_WAKE_COUNTER_PRESERVE_PROCESS (EVENT_TRACE_GROUP_PROCESS | 0x34)

#define PERFINFO_LOG_TYPE_RELEASE_WAKE_COUNTER_USER            (EVENT_TRACE_GROUP_PROCESS | 0x40)
#define PERFINFO_LOG_TYPE_RELEASE_WAKE_COUNTER_EXECUTION       (EVENT_TRACE_GROUP_PROCESS | 0x41)
#define PERFINFO_LOG_TYPE_RELEASE_WAKE_COUNTER_KERNEL          (EVENT_TRACE_GROUP_PROCESS | 0x42)
#define PERFINFO_LOG_TYPE_RELEASE_WAKE_COUNTER_INSTRUMENTATION (EVENT_TRACE_GROUP_PROCESS | 0x43)
#define PERFINFO_LOG_TYPE_RELEASE_WAKE_COUNTER_PRESERVE_PROCESS (EVENT_TRACE_GROUP_PROCESS | 0x44)

#define PERFINFO_LOG_TYPE_WAKE_DROP_USER                       (EVENT_TRACE_GROUP_PROCESS | 0x50)
#define PERFINFO_LOG_TYPE_WAKE_DROP_EXECUTION                  (EVENT_TRACE_GROUP_PROCESS | 0x51)
#define PERFINFO_LOG_TYPE_WAKE_DROP_KERNEL                     (EVENT_TRACE_GROUP_PROCESS | 0x52)
#define PERFINFO_LOG_TYPE_WAKE_DROP_INSTRUMENTATION            (EVENT_TRACE_GROUP_PROCESS | 0x53)
#define PERFINFO_LOG_TYPE_WAKE_DROP_PRESERVE_PROCESS           (EVENT_TRACE_GROUP_PROCESS | 0x54)

#define PERFINFO_LOG_TYPE_WAKE_EVENT_USER                      (EVENT_TRACE_GROUP_PROCESS | 0x60)
#define PERFINFO_LOG_TYPE_WAKE_EVENT_EXECUTION                 (EVENT_TRACE_GROUP_PROCESS | 0x61)
#define PERFINFO_LOG_TYPE_WAKE_EVENT_KERNEL                    (EVENT_TRACE_GROUP_PROCESS | 0x62)
#define PERFINFO_LOG_TYPE_WAKE_EVENT_INSTRUMENTATION           (EVENT_TRACE_GROUP_PROCESS | 0x63)
#define PERFINFO_LOG_TYPE_WAKE_EVENT_PRESERVE_PROCESS          (EVENT_TRACE_GROUP_PROCESS | 0x64)

#define PERFINFO_LOG_TYPE_DEBUG_EVENT                          (EVENT_TRACE_GROUP_PROCESS | 0x70)

//
// Event types for Image and Library Loader
//

#define WMI_LOG_TYPE_IMAGE_LOAD                     (EVENT_TRACE_GROUP_IMAGE | EVENT_TRACE_TYPE_START) // reserved for future
#define WMI_LOG_TYPE_IMAGE_UNLOAD                   (EVENT_TRACE_GROUP_IMAGE | EVENT_TRACE_TYPE_END)
#define WMI_LOG_TYPE_IMAGE_DC_START                 (EVENT_TRACE_GROUP_IMAGE | EVENT_TRACE_TYPE_DC_START)
#define WMI_LOG_TYPE_IMAGE_DC_END                   (EVENT_TRACE_GROUP_IMAGE | EVENT_TRACE_TYPE_DC_END)
#define WMI_LOG_TYPE_IMAGE_RELOCATION               (EVENT_TRACE_GROUP_IMAGE | 0x20)
#define WMI_LOG_TYPE_IMAGE_KERNEL_BASE              (EVENT_TRACE_GROUP_IMAGE | 0x21)
#define WMI_LOG_TYPE_IMAGE_HYPERCALL_PAGE           (EVENT_TRACE_GROUP_IMAGE | 0x22)

#define PERFINFO_LOG_TYPE_LDR_LOCK_ACQUIRE_ATTEMPT          (EVENT_TRACE_GROUP_IMAGE | 0x80) // 128
#define PERFINFO_LOG_TYPE_LDR_LOCK_ACQUIRE_SUCCESS          (EVENT_TRACE_GROUP_IMAGE | 0x81)
#define PERFINFO_LOG_TYPE_LDR_LOCK_ACQUIRE_FAIL             (EVENT_TRACE_GROUP_IMAGE | 0x82)
#define PERFINFO_LOG_TYPE_LDR_LOCK_ACQUIRE_WAIT             (EVENT_TRACE_GROUP_IMAGE | 0x83)
#define PERFINFO_LOG_TYPE_LDR_PROC_INIT_DONE                (EVENT_TRACE_GROUP_IMAGE | 0x84) // 132
#define PERFINFO_LOG_TYPE_LDR_CREATE_SECTION                (EVENT_TRACE_GROUP_IMAGE | 0x85)
#define PERFINFO_LOG_TYPE_LDR_SECTION_CREATED               (EVENT_TRACE_GROUP_IMAGE | 0x86)
#define PERFINFO_LOG_TYPE_LDR_MAP_VIEW                      (EVENT_TRACE_GROUP_IMAGE | 0x87)

#define PERFINFO_LOG_TYPE_LDR_RELOCATE_IMAGE                (EVENT_TRACE_GROUP_IMAGE | 0x90) // 144
#define PERFINFO_LOG_TYPE_LDR_IMAGE_RELOCATED               (EVENT_TRACE_GROUP_IMAGE | 0x91)
#define PERFINFO_LOG_TYPE_LDR_HANDLE_OLD_DESCRIPTORS        (EVENT_TRACE_GROUP_IMAGE | 0x92)
#define PERFINFO_LOG_TYPE_LDR_OLD_DESCRIPTORS_HANDLED       (EVENT_TRACE_GROUP_IMAGE | 0x93)
#define PERFINFO_LOG_TYPE_LDR_HANDLE_NEW_DESCRIPTORS        (EVENT_TRACE_GROUP_IMAGE | 0x94) // 148
#define PERFINFO_LOG_TYPE_LDR_NEW_DESCRIPTORS_HANDLED       (EVENT_TRACE_GROUP_IMAGE | 0x95)
#define PERFINFO_LOG_TYPE_LDR_DLLMAIN_EXIT                  (EVENT_TRACE_GROUP_IMAGE | 0x96)

#define PERFINFO_LOG_TYPE_LDR_FIND_DLL                      (EVENT_TRACE_GROUP_IMAGE | 0xA0) // 160
#define PERFINFO_LOG_TYPE_LDR_VIEW_MAPPED                   (EVENT_TRACE_GROUP_IMAGE | 0xA1)
#define PERFINFO_LOG_TYPE_LDR_LOCK_RELEASE                  (EVENT_TRACE_GROUP_IMAGE | 0xA2)
#define PERFINFO_LOG_TYPE_LDR_DLLMAIN_ENTER                 (EVENT_TRACE_GROUP_IMAGE | 0xA3)
#define PERFINFO_LOG_TYPE_LDR_ERROR                         (EVENT_TRACE_GROUP_IMAGE | 0xA4) // 164

#define PERFINFO_LOG_TYPE_LDR_VIEW_MAPPING                  (EVENT_TRACE_GROUP_IMAGE | 0xA5) // 165
#define PERFINFO_LOG_TYPE_LDR_SNAPPING                      (EVENT_TRACE_GROUP_IMAGE | 0xA6)
#define PERFINFO_LOG_TYPE_LDR_SNAPPED                       (EVENT_TRACE_GROUP_IMAGE | 0xA7)
#define PERFINFO_LOG_TYPE_LDR_LOADING                       (EVENT_TRACE_GROUP_IMAGE | 0xA8)
#define PERFINFO_LOG_TYPE_LDR_LOADED                        (EVENT_TRACE_GROUP_IMAGE | 0xA9)
#define PERFINFO_LOG_TYPE_LDR_FOUND_KNOWN_DLL               (EVENT_TRACE_GROUP_IMAGE | 0xAA) // 170
#define PERFINFO_LOG_TYPE_LDR_ABNORMAL                      (EVENT_TRACE_GROUP_IMAGE | 0xAB)
#define PERFINFO_LOG_TYPE_LDR_PLACEHOLDER                   (EVENT_TRACE_GROUP_IMAGE | 0xAC)
#define PERFINFO_LOG_TYPE_LDR_RDY_TO_INIT                   (EVENT_TRACE_GROUP_IMAGE | 0xAD)
#define PERFINFO_LOG_TYPE_LDR_RDY_TO_RUN                    (EVENT_TRACE_GROUP_IMAGE | 0xAE) // 174


#define PERFINFO_LOG_TYPE_LDR_NEW_DLL_LOAD                  (EVENT_TRACE_GROUP_IMAGE | 0xB0) // 176
#define PERFINFO_LOG_TYPE_LDR_NEW_DLL_AS_DATA               (EVENT_TRACE_GROUP_IMAGE | 0xB1) // 177

#define PERFINFO_LOG_TYPE_LDR_EXTERNAL_PATH                 (EVENT_TRACE_GROUP_IMAGE | 0xC0) // 192
#define PERFINFO_LOG_TYPE_LDR_GENERATED_PATH                (EVENT_TRACE_GROUP_IMAGE | 0xC1)

#define PERFINFO_LOG_TYPE_LDR_APISET_RESOLVING              (EVENT_TRACE_GROUP_IMAGE | 0xD0) // 208
#define PERFINFO_LOG_TYPE_LDR_APISET_HOSTED                 (EVENT_TRACE_GROUP_IMAGE | 0xD1) // 209
#define PERFINFO_LOG_TYPE_LDR_APISET_UNHOSTED               (EVENT_TRACE_GROUP_IMAGE | 0xD2) // 210
#define PERFINFO_LOG_TYPE_LDR_APISET_UNRESOLVED             (EVENT_TRACE_GROUP_IMAGE | 0xD3) // 211

#define PERFINFO_LOG_TYPE_LDR_SEARCH_SECURITY               (EVENT_TRACE_GROUP_IMAGE | 0xD4) // 212
#define PERFINFO_LOG_TYPE_LDR_SEARCH_PATH_SECURITY          (EVENT_TRACE_GROUP_IMAGE | 0xD5) // 213

//
// Event types for Thread
//

#define WMI_LOG_TYPE_THREAD_CREATE                  (EVENT_TRACE_GROUP_THREAD | EVENT_TRACE_TYPE_START)
#define WMI_LOG_TYPE_THREAD_DELETE                  (EVENT_TRACE_GROUP_THREAD | EVENT_TRACE_TYPE_END)
#define WMI_LOG_TYPE_THREAD_DC_START                (EVENT_TRACE_GROUP_THREAD | EVENT_TRACE_TYPE_DC_START)
#define WMI_LOG_TYPE_THREAD_DC_END                  (EVENT_TRACE_GROUP_THREAD | EVENT_TRACE_TYPE_DC_END)

// Reserved                                         (EVENT_TRACE_GROUP_THREAD | 0x20)
// Reserved                                         (EVENT_TRACE_GROUP_THREAD | 0x21)
// Reserved                                         (EVENT_TRACE_GROUP_THREAD | 0x22)
// Reserved                                         (EVENT_TRACE_GROUP_THREAD | 0x23)
#define PERFINFO_LOG_TYPE_CONTEXTSWAP               (EVENT_TRACE_GROUP_THREAD | 0x24)
#define PERFINFO_LOG_TYPE_CONTEXTSWAP_BATCH         (EVENT_TRACE_GROUP_THREAD | 0x25)
// Reserved                                         (EVENT_TRACE_GROUP_THREAD | 0x26)
// Reserved                                         (EVENT_TRACE_GROUP_THREAD | 0x27)
// Reserved                                         (EVENT_TRACE_GROUP_THREAD | 0x28)
#define PERFINFO_LOG_TYPE_SPINLOCK                  (EVENT_TRACE_GROUP_THREAD | 0x29)
#define PERFINFO_LOG_TYPE_QUEUE                     (EVENT_TRACE_GROUP_THREAD | 0x2A)
#define PERFINFO_LOG_TYPE_RESOURCE                  (EVENT_TRACE_GROUP_THREAD | 0x2B)
#define PERFINFO_LOG_TYPE_PUSHLOCK                  (EVENT_TRACE_GROUP_THREAD | 0x2C)
#define PERFINFO_LOG_TYPE_WAIT_SINGLE               (EVENT_TRACE_GROUP_THREAD | 0x2D)
#define PERFINFO_LOG_TYPE_WAIT_MULTIPLE             (EVENT_TRACE_GROUP_THREAD | 0x2E)
#define PERFINFO_LOG_TYPE_DELAY_EXECUTION           (EVENT_TRACE_GROUP_THREAD | 0x2F)
#define PERFINFO_LOG_TYPE_THREAD_SET_PRIORITY       (EVENT_TRACE_GROUP_THREAD | 0x30)
#define PERFINFO_LOT_TYPE_THREAD_SET_BASE_PRIORITY  (EVENT_TRACE_GROUP_THREAD | 0x31)
#define PERFINFO_LOG_TYPE_THREAD_SET_BASE_PRIORITY  (EVENT_TRACE_GROUP_THREAD | 0x31)
#define PERFINFO_LOG_TYPE_READY_THREAD              (EVENT_TRACE_GROUP_THREAD | 0x32)
#define PERFINFO_LOG_TYPE_THREAD_SET_PAGE_PRIORITY  (EVENT_TRACE_GROUP_THREAD | 0x33)
#define PERFINFO_LOG_TYPE_THREAD_SET_IO_PRIORITY    (EVENT_TRACE_GROUP_THREAD | 0x34)
#define PERFINFO_LOG_TYPE_THREAD_SET_AFFINITY       (EVENT_TRACE_GROUP_THREAD | 0x35)
#define PERFINFO_LOG_TYPE_WORKER_THREAD_ITEM        (EVENT_TRACE_GROUP_THREAD | 0x39)
#define PERFINFO_LOG_TYPE_DFSS_START_NEW_INTERVAL   (EVENT_TRACE_GROUP_THREAD | 0x3A)
#define PERFINFO_LOG_TYPE_DFSS_PROCESS_IDLE_ONLY_QUEUE (EVENT_TRACE_GROUP_THREAD | 0x3B)
#define PERFINFO_LOG_TYPE_ANTI_STARVATION_BOOST     (EVENT_TRACE_GROUP_THREAD | 0x3C)
#define PERFINFO_LOG_TYPE_THREAD_MIGRATION          (EVENT_TRACE_GROUP_THREAD | 0x3D)
#define PERFINFO_LOG_TYPE_KQUEUE_ENQUEUE            (EVENT_TRACE_GROUP_THREAD | 0x3E)
#define PERFINFO_LOG_TYPE_KQUEUE_DEQUEUE            (EVENT_TRACE_GROUP_THREAD | 0x3F)
#define PERFINFO_LOG_TYPE_WORKER_THREAD_ITEM_START  (EVENT_TRACE_GROUP_THREAD | 0x40)
#define PERFINFO_LOG_TYPE_WORKER_THREAD_ITEM_END    (EVENT_TRACE_GROUP_THREAD | 0x41)
#define PERFINFO_LOG_TYPE_AUTO_BOOST_SET_FLOOR      (EVENT_TRACE_GROUP_THREAD | 0x42)
#define PERFINFO_LOG_TYPE_AUTO_BOOST_CLEAR_FLOOR    (EVENT_TRACE_GROUP_THREAD | 0x43)
#define PERFINFO_LOG_TYPE_AUTO_BOOST_NO_ENTRIES     (EVENT_TRACE_GROUP_THREAD | 0x44)
#define PERFINFO_LOG_TYPE_THREAD_SUBPROCESSTAG_CHANGED (EVENT_TRACE_GROUP_THREAD | 0x45)

//
// Event types for Network subsystem (TCPIP/UDPIP)
//

#define WMI_LOG_TYPE_TCPIP_SEND                     (EVENT_TRACE_GROUP_TCPIP | EVENT_TRACE_TYPE_SEND)
#define WMI_LOG_TYPE_TCPIP_RECEIVE                  (EVENT_TRACE_GROUP_TCPIP | EVENT_TRACE_TYPE_RECEIVE)
#define WMI_LOG_TYPE_TCPIP_CONNECT                  (EVENT_TRACE_GROUP_TCPIP | EVENT_TRACE_TYPE_CONNECT)
#define WMI_LOG_TYPE_TCPIP_DISCONNECT               (EVENT_TRACE_GROUP_TCPIP | EVENT_TRACE_TYPE_DISCONNECT)
#define WMI_LOG_TYPE_TCPIP_RETRANSMIT               (EVENT_TRACE_GROUP_TCPIP | EVENT_TRACE_TYPE_RETRANSMIT)
#define WMI_LOG_TYPE_TCPIP_ACCEPT                   (EVENT_TRACE_GROUP_TCPIP | EVENT_TRACE_TYPE_ACCEPT)
#define WMI_LOG_TYPE_TCPIP_RECONNECT                (EVENT_TRACE_GROUP_TCPIP | EVENT_TRACE_TYPE_RECONNECT)
#define WMI_LOG_TYPE_TCPIP_FAIL                     (EVENT_TRACE_GROUP_TCPIP | EVENT_TRACE_TYPE_CONNFAIL)
#define WMI_LOG_TYPE_TCPIP_TCPCOPY                  (EVENT_TRACE_GROUP_TCPIP | EVENT_TRACE_TYPE_COPY_TCP)
#define WMI_LOG_TYPE_TCPIP_ARPCOPY                  (EVENT_TRACE_GROUP_TCPIP | EVENT_TRACE_TYPE_COPY_ARP)
#define WMI_LOG_TYPE_TCPIP_FULLACK                  (EVENT_TRACE_GROUP_TCPIP | EVENT_TRACE_TYPE_ACKFULL)
#define WMI_LOG_TYPE_TCPIP_PARTACK                  (EVENT_TRACE_GROUP_TCPIP | EVENT_TRACE_TYPE_ACKPART)
#define WMI_LOG_TYPE_TCPIP_DUPACK                   (EVENT_TRACE_GROUP_TCPIP | EVENT_TRACE_TYPE_ACKDUP)

#define WMI_LOG_TYPE_UDP_SEND                       (EVENT_TRACE_GROUP_UDPIP | EVENT_TRACE_TYPE_SEND)
#define WMI_LOG_TYPE_UDP_RECEIVE                    (EVENT_TRACE_GROUP_UDPIP | EVENT_TRACE_TYPE_RECEIVE)
#define WMI_LOG_TYPE_UDP_FAIL                       (EVENT_TRACE_GROUP_UDPIP | EVENT_TRACE_TYPE_CONNFAIL)

//
// Network events with IPV6
//
#define WMI_LOG_TYPE_TCPIP_SEND_IPV6                (EVENT_TRACE_GROUP_TCPIP | 0x1A)
#define WMI_LOG_TYPE_TCPIP_RECEIVE_IPV6             (EVENT_TRACE_GROUP_TCPIP | 0x1B)
#define WMI_LOG_TYPE_TCPIP_CONNECT_IPV6             (EVENT_TRACE_GROUP_TCPIP | 0x1C)
#define WMI_LOG_TYPE_TCPIP_DISCONNECT_IPV6          (EVENT_TRACE_GROUP_TCPIP | 0x1D)
#define WMI_LOG_TYPE_TCPIP_RETRANSMIT_IPV6          (EVENT_TRACE_GROUP_TCPIP | 0x1E)
#define WMI_LOG_TYPE_TCPIP_ACCEPT_IPV6              (EVENT_TRACE_GROUP_TCPIP | 0x1F)
#define WMI_LOG_TYPE_TCPIP_RECONNECT_IPV6           (EVENT_TRACE_GROUP_TCPIP | 0x20)
#define WMI_LOG_TYPE_TCPIP_FAIL_IPV6                (EVENT_TRACE_GROUP_TCPIP | 0x21)
#define WMI_LOG_TYPE_TCPIP_TCPCOPY_IPV6             (EVENT_TRACE_GROUP_TCPIP | 0x22)
#define WMI_LOG_TYPE_TCPIP_ARPCOPY_IPV6             (EVENT_TRACE_GROUP_TCPIP | 0x23)
#define WMI_LOG_TYPE_TCPIP_FULLACK_IPV6             (EVENT_TRACE_GROUP_TCPIP | 0x24)
#define WMI_LOG_TYPE_TCPIP_PARTACK_IPV6             (EVENT_TRACE_GROUP_TCPIP | 0x25)
#define WMI_LOG_TYPE_TCPIP_DUPACK_IPV6              (EVENT_TRACE_GROUP_TCPIP | 0x26)

#define WMI_LOG_TYPE_UDP_SEND_IPV6                  (EVENT_TRACE_GROUP_UDPIP | 0x1A)
#define WMI_LOG_TYPE_UDP_RECEIVE_IPV6               (EVENT_TRACE_GROUP_UDPIP | 0x1B)

//
// Event types for IO subsystem
//

#define WMI_LOG_TYPE_IO_READ                        (EVENT_TRACE_GROUP_IO | EVENT_TRACE_TYPE_IO_READ)
#define WMI_LOG_TYPE_IO_WRITE                       (EVENT_TRACE_GROUP_IO | EVENT_TRACE_TYPE_IO_WRITE)
#define WMI_LOG_TYPE_IO_READ_INIT                   (EVENT_TRACE_GROUP_IO | EVENT_TRACE_TYPE_IO_READ_INIT)
#define WMI_LOG_TYPE_IO_WRITE_INIT                  (EVENT_TRACE_GROUP_IO | EVENT_TRACE_TYPE_IO_WRITE_INIT)
#define WMI_LOG_TYPE_IO_FLUSH                       (EVENT_TRACE_GROUP_IO | EVENT_TRACE_TYPE_IO_FLUSH)
#define WMI_LOG_TYPE_IO_FLUSH_INIT                  (EVENT_TRACE_GROUP_IO | EVENT_TRACE_TYPE_IO_FLUSH_INIT)
#define WMI_LOG_TYPE_IO_REDIRECTED_INIT             (EVENT_TRACE_GROUP_IO | EVENT_TRACE_TYPE_IO_REDIRECTED_INIT)

#define PERFINFO_LOG_TYPE_DRIVER_INIT                       (EVENT_TRACE_GROUP_IO | 0x20)
#define PERFINFO_LOG_TYPE_DRIVER_INIT_COMPLETE              (EVENT_TRACE_GROUP_IO | 0x21)
#define PERFINFO_LOG_TYPE_DRIVER_MAJORFUNCTION_CALL         (EVENT_TRACE_GROUP_IO | 0x22)
#define PERFINFO_LOG_TYPE_DRIVER_MAJORFUNCTION_RETURN       (EVENT_TRACE_GROUP_IO | 0x23)
#define PERFINFO_LOG_TYPE_DRIVER_COMPLETIONROUTINE_CALL     (EVENT_TRACE_GROUP_IO | 0x24)
#define PERFINFO_LOG_TYPE_DRIVER_COMPLETIONROUTINE_RETURN   (EVENT_TRACE_GROUP_IO | 0x25)
#define PERFINFO_LOG_TYPE_DRIVER_ADD_DEVICE_CALL            (EVENT_TRACE_GROUP_IO | 0x26)
#define PERFINFO_LOG_TYPE_DRIVER_ADD_DEVICE_RETURN          (EVENT_TRACE_GROUP_IO | 0x27)
#define PERFINFO_LOG_TYPE_DRIVER_STARTIO_CALL               (EVENT_TRACE_GROUP_IO | 0x28)
#define PERFINFO_LOG_TYPE_DRIVER_STARTIO_RETURN             (EVENT_TRACE_GROUP_IO | 0x29)
// Reserved                                                 (EVENT_TRACE_GROUP_IO | 0x2a)
// Reserved                                                 (EVENT_TRACE_GROUP_IO | 0x2b)
// Reserved                                                 (EVENT_TRACE_GROUP_IO | 0x2c)
// Reserved                                                 (EVENT_TRACE_GROUP_IO | 0x2d)
// Reserved                                                 (EVENT_TRACE_GROUP_IO | 0x2e)
// Reserved                                                 (EVENT_TRACE_GROUP_IO | 0x2f)
#define PERFINFO_LOG_TYPE_PREFETCH_ACTION                   (EVENT_TRACE_GROUP_IO | 0x30)
#define PERFINFO_LOG_TYPE_PREFETCH_REQUEST                  (EVENT_TRACE_GROUP_IO | 0x31)
#define PERFINFO_LOG_TYPE_PREFETCH_READLIST                 (EVENT_TRACE_GROUP_IO | 0x32)
#define PERFINFO_LOG_TYPE_PREFETCH_READ                     (EVENT_TRACE_GROUP_IO | 0x33)
#define PERFINFO_LOG_TYPE_DRIVER_COMPLETE_REQUEST           (EVENT_TRACE_GROUP_IO | 0x34)
#define PERFINFO_LOG_TYPE_DRIVER_COMPLETE_REQUEST_RETURN    (EVENT_TRACE_GROUP_IO | 0x35)
#define PERFINFO_LOG_TYPE_BOOT_PREFETCH_INFORMATION         (EVENT_TRACE_GROUP_IO | 0x36)
#define PERFINFO_LOG_TYPE_OPTICAL_IO_READ                   (EVENT_TRACE_GROUP_IO | EVENT_TRACE_TYPE_OPTICAL_IO_READ)
#define PERFINFO_LOG_TYPE_OPTICAL_IO_WRITE                  (EVENT_TRACE_GROUP_IO | EVENT_TRACE_TYPE_OPTICAL_IO_WRITE)
#define PERFINFO_LOG_TYPE_OPTICAL_IO_FLUSH                  (EVENT_TRACE_GROUP_IO | EVENT_TRACE_TYPE_OPTICAL_IO_FLUSH)
#define PERFINFO_LOG_TYPE_OPTICAL_IO_READ_INIT              (EVENT_TRACE_GROUP_IO | EVENT_TRACE_TYPE_OPTICAL_IO_READ_INIT)
#define PERFINFO_LOG_TYPE_OPTICAL_IO_WRITE_INIT             (EVENT_TRACE_GROUP_IO | EVENT_TRACE_TYPE_OPTICAL_IO_WRITE_INIT)
#define PERFINFO_LOG_TYPE_OPTICAL_IO_FLUSH_INIT             (EVENT_TRACE_GROUP_IO | EVENT_TRACE_TYPE_OPTICAL_IO_FLUSH_INIT)

//
// Event types for Memory subsystem
//
#define WMI_LOG_TYPE_PAGE_FAULT_TRANSITION         (EVENT_TRACE_GROUP_MEMORY | EVENT_TRACE_TYPE_MM_TF)
#define WMI_LOG_TYPE_PAGE_FAULT_DEMAND_ZERO        (EVENT_TRACE_GROUP_MEMORY | EVENT_TRACE_TYPE_MM_DZF)
#define WMI_LOG_TYPE_PAGE_FAULT_COPY_ON_WRITE      (EVENT_TRACE_GROUP_MEMORY | EVENT_TRACE_TYPE_MM_COW)
#define WMI_LOG_TYPE_PAGE_FAULT_GUARD_PAGE         (EVENT_TRACE_GROUP_MEMORY | EVENT_TRACE_TYPE_MM_GPF)
#define WMI_LOG_TYPE_PAGE_FAULT_HARD_PAGE_FAULT    (EVENT_TRACE_GROUP_MEMORY | EVENT_TRACE_TYPE_MM_HPF)
#define WMI_LOG_TYPE_PAGE_FAULT_ACCESS_VIOLATION   (EVENT_TRACE_GROUP_MEMORY | EVENT_TRACE_TYPE_MM_AV)

#define PERFINFO_LOG_TYPE_HARDFAULT                (EVENT_TRACE_GROUP_MEMORY | 0x20)
#define PERFINFO_LOG_TYPE_REMOVEPAGEBYCOLOR        (EVENT_TRACE_GROUP_MEMORY | 0x21)
#define PERFINFO_LOG_TYPE_REMOVEPAGEFROMLIST       (EVENT_TRACE_GROUP_MEMORY | 0x22)
#define PERFINFO_LOG_TYPE_PAGEINMEMORY             (EVENT_TRACE_GROUP_MEMORY | 0x23)
#define PERFINFO_LOG_TYPE_INSERTINFREELIST         (EVENT_TRACE_GROUP_MEMORY | 0x24)
#define PERFINFO_LOG_TYPE_INSERTINMODIFIEDLIST     (EVENT_TRACE_GROUP_MEMORY | 0x25)
#define PERFINFO_LOG_TYPE_INSERTINLIST             (EVENT_TRACE_GROUP_MEMORY | 0x26)
#define PERFINFO_LOG_TYPE_INSERTATFRONT            (EVENT_TRACE_GROUP_MEMORY | 0x28)
#define PERFINFO_LOG_TYPE_UNLINKFROMSTANDBY        (EVENT_TRACE_GROUP_MEMORY | 0x29)
#define PERFINFO_LOG_TYPE_UNLINKFFREEORZERO        (EVENT_TRACE_GROUP_MEMORY | 0x2a)
#define PERFINFO_LOG_TYPE_WORKINGSETMANAGER        (EVENT_TRACE_GROUP_MEMORY | 0x2b)
#define PERFINFO_LOG_TYPE_TRIMPROCESS              (EVENT_TRACE_GROUP_MEMORY | 0x2c)
// Reserved                                        (EVENT_TRACE_GROUP_MEMORY | 0x2d)
#define PERFINFO_LOG_TYPE_ZEROSHARECOUNT           (EVENT_TRACE_GROUP_MEMORY | 0x2e)
// Reserved                                        (EVENT_TRACE_GROUP_MEMORY | 0x2f)
// Reserved                                        (EVENT_TRACE_GROUP_MEMORY | 0x30)
// Reserved                                        (EVENT_TRACE_GROUP_MEMORY | 0x31)
// Reserved                                        (EVENT_TRACE_GROUP_MEMORY | 0x32)
// Reserved                                        (EVENT_TRACE_GROUP_MEMORY | 0x33)
// Reserved                                        (EVENT_TRACE_GROUP_MEMORY | 0x34)
// Reserved                                        (EVENT_TRACE_GROUP_MEMORY | 0x35)
// Reserved                                        (EVENT_TRACE_GROUP_MEMORY | 0x36)
// Reserved                                        (EVENT_TRACE_GROUP_MEMORY | 0x37)
// Reserved                                        (EVENT_TRACE_GROUP_MEMORY | 0x38)
// Reserved                                        (EVENT_TRACE_GROUP_MEMORY | 0x39)
// Reserved                                        (EVENT_TRACE_GROUP_MEMORY | 0x3a)
// Reserved                                        (EVENT_TRACE_GROUP_MEMORY | 0x3b)
#define PERFINFO_LOG_TYPE_WSINFOPROCESS            (EVENT_TRACE_GROUP_MEMORY | 0x3c)
// Reserved                                        (EVENT_TRACE_GROUP_MEMORY | 0x3d)
// Reserved                                        (EVENT_TRACE_GROUP_MEMORY | 0x3e)
// Reserved                                        (EVENT_TRACE_GROUP_MEMORY | 0x3f)
// Reserved                                        (EVENT_TRACE_GROUP_MEMORY | 0x40)
// Reserved                                        (EVENT_TRACE_GROUP_MEMORY | 0x41)
// Reserved                                        (EVENT_TRACE_GROUP_MEMORY | 0x42)
// Reserved                                        (EVENT_TRACE_GROUP_MEMORY | 0x43)
// Reserved                                        (EVENT_TRACE_GROUP_MEMORY | 0x44)
#define PERFINFO_LOG_TYPE_FAULTADDR_WITH_IP        (EVENT_TRACE_GROUP_MEMORY | 0x45)
#define PERFINFO_LOG_TYPE_TRIMSESSION              (EVENT_TRACE_GROUP_MEMORY | 0x46)
#define PERFINFO_LOG_TYPE_MEMORYSNAPLITE           (EVENT_TRACE_GROUP_MEMORY | 0x47)
#define PERFINFO_LOG_TYPE_PFMAPPED_SECTION_RUNDOWN (EVENT_TRACE_GROUP_MEMORY | 0x48)
#define PERFINFO_LOG_TYPE_PFMAPPED_SECTION_CREATE  (EVENT_TRACE_GROUP_MEMORY | 0x49)
#define PERFINFO_LOG_TYPE_WSINFOSESSION            (EVENT_TRACE_GROUP_MEMORY | 0x4a)
#define PERFINFO_LOG_TYPE_CREATE_SESSION           (EVENT_TRACE_GROUP_MEMORY | 0x4b)
#define PERFINFO_LOG_TYPE_SESSION_RUNDOWN_DC_END   (EVENT_TRACE_GROUP_MEMORY | 0x4c)
#define PERFINFO_LOG_TYPE_SESSION_RUNDOWN_DC_START (EVENT_TRACE_GROUP_MEMORY | 0x4d)
#define PERFINFO_LOG_TYPE_SESSION_DELETE           (EVENT_TRACE_GROUP_MEMORY | 0x4e)
#define PERFINFO_LOG_TYPE_PFMAPPED_SECTION_DELETE  (EVENT_TRACE_GROUP_MEMORY | 0x4f)

#define PERFINFO_LOG_TYPE_VIRTUAL_ALLOC            (EVENT_TRACE_GROUP_MEMORY | 0x62)
#define PERFINFO_LOG_TYPE_VIRTUAL_FREE             (EVENT_TRACE_GROUP_MEMORY | 0x63)
#define PERFINFO_LOG_TYPE_HEAP_RANGE_RUNDOWN       (EVENT_TRACE_GROUP_MEMORY | 0x64)
#define PERFINFO_LOG_TYPE_HEAP_RANGE_CREATE        (EVENT_TRACE_GROUP_MEMORY | 0x65)
#define PERFINFO_LOG_TYPE_HEAP_RANGE_RESERVE       (EVENT_TRACE_GROUP_MEMORY | 0x66)
#define PERFINFO_LOG_TYPE_HEAP_RANGE_RELEASE       (EVENT_TRACE_GROUP_MEMORY | 0x67)
#define PERFINFO_LOG_TYPE_HEAP_RANGE_DESTROY       (EVENT_TRACE_GROUP_MEMORY | 0x68)

#define PERFINFO_LOG_TYPE_PAGEFILE_BACK            (EVENT_TRACE_GROUP_MEMORY | 0x69)
#define PERFINFO_LOG_TYPE_MEMINFO                  (EVENT_TRACE_GROUP_MEMORY | 0x70)
#define PERFINFO_LOG_TYPE_CONTMEM_GENERATE         (EVENT_TRACE_GROUP_MEMORY | 0x71)
#define PERFINFO_LOG_TYPE_FILE_STORE_FAULT         (EVENT_TRACE_GROUP_MEMORY | 0x72)
#define PERFINFO_LOG_TYPE_INMEMORY_STORE_FAULT     (EVENT_TRACE_GROUP_MEMORY | 0x73)
#define PERFINFO_LOG_TYPE_COMPRESSED_PAGE          (EVENT_TRACE_GROUP_MEMORY | 0x74)
#define PERFINFO_LOG_TYPE_PAGEINMEMORY_ACTIVE      (EVENT_TRACE_GROUP_MEMORY | 0x75)
#define PERFINFO_LOG_TYPE_PAGE_ACCESS              (EVENT_TRACE_GROUP_MEMORY | 0x76)
#define PERFINFO_LOG_TYPE_PAGE_RELEASE             (EVENT_TRACE_GROUP_MEMORY | 0x77)
#define PERFINFO_LOG_TYPE_PAGE_RANGE_ACCESS        (EVENT_TRACE_GROUP_MEMORY | 0x78)
#define PERFINFO_LOG_TYPE_PAGE_RANGE_RELEASE       (EVENT_TRACE_GROUP_MEMORY | 0x79)
#define PERFINFO_LOG_TYPE_PAGE_COMBINE             (EVENT_TRACE_GROUP_MEMORY | 0x7a)
#define PERFINFO_LOG_TYPE_KERNEL_MEMUSAGE          (EVENT_TRACE_GROUP_MEMORY | 0x7b)
#define PERFINFO_LOG_TYPE_MM_STATS                 (EVENT_TRACE_GROUP_MEMORY | 0x7c)
#define PERFINFO_LOG_TYPE_MEMINFOEX_WS             (EVENT_TRACE_GROUP_MEMORY | 0x7d)
#define PERFINFO_LOG_TYPE_MEMINFOEX_SESSIONWS      (EVENT_TRACE_GROUP_MEMORY | 0x7e)

#define PERFINFO_LOG_TYPE_VIRTUAL_ROTATE           (EVENT_TRACE_GROUP_MEMORY | 0x7f)
#define PERFINFO_LOG_TYPE_VIRTUAL_ALLOC_DC_START   (EVENT_TRACE_GROUP_MEMORY | 0x80)
#define PERFINFO_LOG_TYPE_VIRTUAL_ALLOC_DC_END     (EVENT_TRACE_GROUP_MEMORY | 0x81)

#define PERFINFO_LOG_TYPE_PAGE_ACCESS_EX           (EVENT_TRACE_GROUP_MEMORY | 0x82)
#define PERFINFO_LOG_TYPE_REMOVEFROMWS             (EVENT_TRACE_GROUP_MEMORY | 0x83)
#define PERFINFO_LOG_TYPE_WSSHAREABLE_RUNDOWN      (EVENT_TRACE_GROUP_MEMORY | 0x84)
#define PERFINFO_LOG_TYPE_INMEMORYACTIVE_RUNDOWN   (EVENT_TRACE_GROUP_MEMORY | 0x85)

#define PERFINFO_LOG_TYPE_MEM_RESET_INFO           (EVENT_TRACE_GROUP_MEMORY | 0x86)
#define PERFINFO_LOG_TYPE_PFMAPPED_SECTION_OBJECT_CREATE  (EVENT_TRACE_GROUP_MEMORY | 0x87)
#define PERFINFO_LOG_TYPE_PFMAPPED_SECTION_OBJECT_DELETE  (EVENT_TRACE_GROUP_MEMORY | 0x88)

//
//
// Event types for Registry subsystem
//
#define WMI_LOG_TYPE_REG_RUNDOWNBEGIN      (EVENT_TRACE_GROUP_REGISTRY | EVENT_TRACE_TYPE_REGKCBRUNDOWNBEGIN)
#define WMI_LOG_TYPE_REG_RUNDOWNEND        (EVENT_TRACE_GROUP_REGISTRY | EVENT_TRACE_TYPE_REGKCBRUNDOWNEND)

#define PERFINFO_LOG_TYPE_CMCELLREFERRED            (EVENT_TRACE_GROUP_REGISTRY | 0x20)
#define PERFINFO_LOG_TYPE_REG_SET_VALUE             (EVENT_TRACE_GROUP_REGISTRY | 0x21)
#define PERFINFO_LOG_TYPE_REG_COUNTERS              (EVENT_TRACE_GROUP_REGISTRY | 0x22)
#define PERFINFO_LOG_TYPE_REG_CONFIG                (EVENT_TRACE_GROUP_REGISTRY | 0x23)
#define PERFINFO_LOG_TYPE_REG_HIVE_INITIALIZE       (EVENT_TRACE_GROUP_REGISTRY | 0x24)
#define PERFINFO_LOG_TYPE_REG_HIVE_DESTROY          (EVENT_TRACE_GROUP_REGISTRY | 0x25)
#define PERFINFO_LOG_TYPE_REG_HIVE_LINK             (EVENT_TRACE_GROUP_REGISTRY | 0x26)
#define PERFINFO_LOG_TYPE_REG_HIVE_RUNDOWN_DC_END   (EVENT_TRACE_GROUP_REGISTRY | 0x27)
#define PERFINFO_LOG_TYPE_REG_HIVE_DIRTY            (EVENT_TRACE_GROUP_REGISTRY | 0x28)
// Reserved
#define PERFINFO_LOG_TYPE_REG_NOTIF_REGISTER        (EVENT_TRACE_GROUP_REGISTRY | 0x30)
#define PERFINFO_LOG_TYPE_REG_NOTIF_DELIVER         (EVENT_TRACE_GROUP_REGISTRY | 0x31)

//
// Event types for PERF tracing specific subsystem
//
#define PERFINFO_LOG_TYPE_RUNDOWN_CHECKPOINT           (EVENT_TRACE_GROUP_PERFINFO | 0x20)
// Reserved                                            (EVENT_TRACE_GROUP_PERFINFO | 0x21)
#define PERFINFO_LOG_TYPE_MARK                         (EVENT_TRACE_GROUP_PERFINFO | 0x22)
// Reserved                                            (EVENT_TRACE_GROUP_PERFINFO | 0x23)
#define PERFINFO_LOG_TYPE_ASYNCMARK                    (EVENT_TRACE_GROUP_PERFINFO | 0x24)
// Reserved                                            (EVENT_TRACE_GROUP_PERFINFO | 0x25)
#define PERFINFO_LOG_TYPE_IMAGENAME                    (EVENT_TRACE_GROUP_PERFINFO | 0x26)
#define PERFINFO_LOG_TYPE_DELAYS_CC_CAN_I_WRITE        (EVENT_TRACE_GROUP_PERFINFO | 0x27)
// Reserved                                            (EVENT_TRACE_GROUP_PERFINFO | 0x28)
// Reserved                                            (EVENT_TRACE_GROUP_PERFINFO | 0x29)
// Reserved                                            (EVENT_TRACE_GROUP_PERFINFO | 0x2a)
// Reserved                                            (EVENT_TRACE_GROUP_PERFINFO | 0x2b)
// Reserved                                            (EVENT_TRACE_GROUP_PERFINFO | 0x2c)
// Reserved                                            (EVENT_TRACE_GROUP_PERFINFO | 0x2d)
#define PERFINFO_LOG_TYPE_SAMPLED_PROFILE              (EVENT_TRACE_GROUP_PERFINFO | 0x2e)
#define PERFINFO_LOG_TYPE_PMC_INTERRUPT                (EVENT_TRACE_GROUP_PERFINFO | 0x2f)
#define PERFINFO_LOG_TYPE_PMC_CONFIG                   (EVENT_TRACE_GROUP_PERFINFO | 0x30)
// Reserved                                            (EVENT_TRACE_GROUP_PERFINFO | 0x31)
#define PERFINFO_LOG_TYPE_MSI_INTERRUPT                (EVENT_TRACE_GROUP_PERFINFO | 0x32)
#define PERFINFO_LOG_TYPE_SYSCALL_ENTER                (EVENT_TRACE_GROUP_PERFINFO | 0x33)
#define PERFINFO_LOG_TYPE_SYSCALL_EXIT                 (EVENT_TRACE_GROUP_PERFINFO | 0x34)
#define PERFINFO_LOG_TYPE_BACKTRACE                    (EVENT_TRACE_GROUP_PERFINFO | 0x35)
#define PERFINFO_LOG_TYPE_BACKTRACE_USERSTACK          (EVENT_TRACE_GROUP_PERFINFO | 0x36)
#define PERFINFO_LOG_TYPE_SAMPLED_PROFILE_CACHE        (EVENT_TRACE_GROUP_PERFINFO | 0x37)
#define PERFINFO_LOG_TYPE_EXCEPTION_STACK              (EVENT_TRACE_GROUP_PERFINFO | 0x38)
#define PERFINFO_LOG_TYPE_BRANCH_TRACE                 (EVENT_TRACE_GROUP_PERFINFO | 0x39)
#define PERFINFO_LOG_TYPE_DEBUGGER_ENABLED             (EVENT_TRACE_GROUP_PERFINFO | 0x3a)
#define PERFINFO_LOG_TYPE_DEBUGGER_EXIT                (EVENT_TRACE_GROUP_PERFINFO | 0x3b)
#define PERFINFO_LOG_TYPE_BRANCH_TRACE_DEBUG           (EVENT_TRACE_GROUP_PERFINFO | 0x40)
#define PERFINFO_LOG_TYPE_BRANCH_ADDRESS_DEBUG         (EVENT_TRACE_GROUP_PERFINFO | 0x41)
#define PERFINFO_LOG_TYPE_THREADED_DPC                 (EVENT_TRACE_GROUP_PERFINFO | 0x42)
#define PERFINFO_LOG_TYPE_INTERRUPT                    (EVENT_TRACE_GROUP_PERFINFO | 0x43)
#define PERFINFO_LOG_TYPE_DPC                          (EVENT_TRACE_GROUP_PERFINFO | 0x44)
#define PERFINFO_LOG_TYPE_TIMERDPC                     (EVENT_TRACE_GROUP_PERFINFO | 0x45)
#define PERFINFO_LOG_TYPE_IOTIMER_EXPIRATION           (EVENT_TRACE_GROUP_PERFINFO | 0x46)
#define PERFINFO_LOG_TYPE_SAMPLED_PROFILE_NMI          (EVENT_TRACE_GROUP_PERFINFO | 0x47)
#define PERFINFO_LOG_TYPE_SAMPLED_PROFILE_SET_INTERVAL (EVENT_TRACE_GROUP_PERFINFO | 0x48)
#define PERFINFO_LOG_TYPE_SAMPLED_PROFILE_DC_START     (EVENT_TRACE_GROUP_PERFINFO | 0x49)
#define PERFINFO_LOG_TYPE_SAMPLED_PROFILE_DC_END       (EVENT_TRACE_GROUP_PERFINFO | 0x4a)
#define PERFINFO_LOG_TYPE_SPINLOCK_DC_START            (EVENT_TRACE_GROUP_PERFINFO | 0x4b)
#define PERFINFO_LOG_TYPE_SPINLOCK_DC_END              (EVENT_TRACE_GROUP_PERFINFO | 0x4c)
#define PERFINFO_LOG_TYPE_ERESOURCE_DC_START           (EVENT_TRACE_GROUP_PERFINFO | 0x4d)
#define PERFINFO_LOG_TYPE_ERESOURCE_DC_END             (EVENT_TRACE_GROUP_PERFINFO | 0x4e)
#define PERFINFO_LOG_TYPE_CLOCK_INTERRUPT              (EVENT_TRACE_GROUP_PERFINFO | 0x4f)
#define PERFINFO_LOG_TYPE_TIMER_EXPIRATION_START       (EVENT_TRACE_GROUP_PERFINFO | 0x50)
#define PERFINFO_LOG_TYPE_TIMER_EXPIRATION             (EVENT_TRACE_GROUP_PERFINFO | 0x51)
#define PERFINFO_LOG_TYPE_TIMER_SET_PERIODIC           (EVENT_TRACE_GROUP_PERFINFO | 0x52)
#define PERFINFO_LOG_TYPE_TIMER_SET_ONE_SHOT           (EVENT_TRACE_GROUP_PERFINFO | 0x53)
#define PERFINFO_LOG_TYPE_TIMER_SET_THREAD             (EVENT_TRACE_GROUP_PERFINFO | 0x54)
#define PERFINFO_LOG_TYPE_TIMER_CANCEL                 (EVENT_TRACE_GROUP_PERFINFO | 0x55)
#define PERFINFO_LOG_TYPE_TIME_ADJUSTMENT              (EVENT_TRACE_GROUP_PERFINFO | 0x56)
#define PERFINFO_LOG_TYPE_CLOCK_MODE_SWITCH            (EVENT_TRACE_GROUP_PERFINFO | 0x57)
#define PERFINFO_LOG_TYPE_CLOCK_TIME_UPDATE            (EVENT_TRACE_GROUP_PERFINFO | 0x58)
#define PERFINFO_LOG_TYPE_CLOCK_DYNAMIC_TICK_VETO      (EVENT_TRACE_GROUP_PERFINFO | 0x59)
#define PERFINFO_LOG_TYPE_CLOCK_CONFIGURATION          (EVENT_TRACE_GROUP_PERFINFO | 0x5a)
#define PERFINFO_LOG_TYPE_IPI                          (EVENT_TRACE_GROUP_PERFINFO | 0x5b)
#define PERFINFO_LOG_TYPE_UNEXPECTED_INTERRUPT         (EVENT_TRACE_GROUP_PERFINFO | 0x5c)
#define PERFINFO_LOG_TYPE_IOTIMER_START                (EVENT_TRACE_GROUP_PERFINFO | 0x5d)
#define PERFINFO_LOG_TYPE_IOTIMER_STOP                 (EVENT_TRACE_GROUP_PERFINFO | 0x5e)
#define PERFINFO_LOG_TYPE_PASSIVE_INTERRUPT            (EVENT_TRACE_GROUP_PERFINFO | 0x5f)
#define PERFINFO_LOG_TYPE_WDF_INTERRUPT                (EVENT_TRACE_GROUP_PERFINFO | 0x60)
#define PERFINFO_LOG_TYPE_WDF_PASSIVE_INTERRUPT        (EVENT_TRACE_GROUP_PERFINFO | 0x61)
#define PERFINFO_LOG_TYPE_WDF_DPC                      (EVENT_TRACE_GROUP_PERFINFO | 0x62)
#define PERFINFO_LOG_TYPE_CPU_CACHE_FLUSH              (EVENT_TRACE_GROUP_PERFINFO | 0x63)
#define PERFINFO_LOG_TYPE_DPC_ENQUEUE                  (EVENT_TRACE_GROUP_PERFINFO | 0x64)
#define PERFINFO_LOG_TYPE_DPC_EXECUTION                (EVENT_TRACE_GROUP_PERFINFO | 0x65)
#define PERFINFO_LOG_TYPE_INTERRUPT_STEERING           (EVENT_TRACE_GROUP_PERFINFO | 0x66)
#define PERFINFO_LOG_TYPE_WDF_WORK_ITEM                (EVENT_TRACE_GROUP_PERFINFO | 0x67)
#define PERFINFO_LOG_TYPE_KTIMER2_SET                  (EVENT_TRACE_GROUP_PERFINFO | 0x68)
#define PERFINFO_LOG_TYPE_KTIMER2_EXPIRATION           (EVENT_TRACE_GROUP_PERFINFO | 0x69)
#define PERFINFO_LOG_TYPE_KTIMER2_CANCEL               (EVENT_TRACE_GROUP_PERFINFO | 0x6a)
#define PERFINFO_LOG_TYPE_KTIMER2_DISABLE              (EVENT_TRACE_GROUP_PERFINFO | 0x6b)
#define PERFINFO_LOG_TYPE_KTIMER2_FINALIZATION         (EVENT_TRACE_GROUP_PERFINFO | 0x6c)
#define PERFINFO_LOG_TYPE_SHOULD_YIELD_PROCESSOR       (EVENT_TRACE_GROUP_PERFINFO | 0x6d)

//
// Event types for ICE.
//

#define PERFINFO_LOG_TYPE_FUNCTION_CALL                (EVENT_TRACE_GROUP_PERFINFO | 0x80)
#define PERFINFO_LOG_TYPE_FUNCTION_RETURN              (EVENT_TRACE_GROUP_PERFINFO | 0x81)
#define PERFINFO_LOG_TYPE_FUNCTION_ENTER               (EVENT_TRACE_GROUP_PERFINFO | 0x82)
#define PERFINFO_LOG_TYPE_FUNCTION_EXIT                (EVENT_TRACE_GROUP_PERFINFO | 0x83)
#define PERFINFO_LOG_TYPE_TAILCALL                     (EVENT_TRACE_GROUP_PERFINFO | 0x84)
#define PERFINFO_LOG_TYPE_TRAP                         (EVENT_TRACE_GROUP_PERFINFO | 0x85)
#define PERFINFO_LOG_TYPE_SPINLOCK_ACQUIRE             (EVENT_TRACE_GROUP_PERFINFO | 0x86)
#define PERFINFO_LOG_TYPE_SPINLOCK_RELEASE             (EVENT_TRACE_GROUP_PERFINFO | 0x87)
#define PERFINFO_LOG_TYPE_CAP_COMMENT                  (EVENT_TRACE_GROUP_PERFINFO | 0x88)
#define PERFINFO_LOG_TYPE_CAP_RUNDOWN                  (EVENT_TRACE_GROUP_PERFINFO | 0x89)

//
// Event types for Debugger subsystem.
//

#define PERFINFO_LOG_TYPE_DEBUG_PRINT                  (EVENT_TRACE_GROUP_DBGPRINT | 0x20)

//
// Event types for WNF facility
//

#define PERFINFO_LOG_TYPE_WNF_SUBSCRIBE                (EVENT_TRACE_GROUP_WNF | 0x20)
#define PERFINFO_LOG_TYPE_WNF_UNSUBSCRIBE              (EVENT_TRACE_GROUP_WNF | 0x21)
#define PERFINFO_LOG_TYPE_WNF_CALLBACK                 (EVENT_TRACE_GROUP_WNF | 0x22)
#define PERFINFO_LOG_TYPE_WNF_PUBLISH                  (EVENT_TRACE_GROUP_WNF | 0x23)
#define PERFINFO_LOG_TYPE_WNF_NAME_SUB_RUNDOWN         (EVENT_TRACE_GROUP_WNF | 0x24)

//
// Event types for Pool subsystem.
//

#define PERFINFO_LOG_TYPE_ALLOCATEPOOL                 (EVENT_TRACE_GROUP_POOL | 0x20)
#define PERFINFO_LOG_TYPE_ALLOCATEPOOL_SESSION         (EVENT_TRACE_GROUP_POOL | 0x21)
#define PERFINFO_LOG_TYPE_FREEPOOL                     (EVENT_TRACE_GROUP_POOL | 0x22)
#define PERFINFO_LOG_TYPE_FREEPOOL_SESSION             (EVENT_TRACE_GROUP_POOL | 0x23)
#define PERFINFO_LOG_TYPE_ADDPOOLPAGE                  (EVENT_TRACE_GROUP_POOL | 0x24)
#define PERFINFO_LOG_TYPE_ADDPOOLPAGE_SESSION          (EVENT_TRACE_GROUP_POOL | 0x25)
#define PERFINFO_LOG_TYPE_BIGPOOLPAGE                  (EVENT_TRACE_GROUP_POOL | 0x26)
#define PERFINFO_LOG_TYPE_BIGPOOLPAGE_SESSION          (EVENT_TRACE_GROUP_POOL | 0x27)
#define PERFINFO_LOG_TYPE_POOLSNAP_DC_START            (EVENT_TRACE_GROUP_POOL | 0x28)
#define PERFINFO_LOG_TYPE_POOLSNAP_DC_END              (EVENT_TRACE_GROUP_POOL | 0x29)
#define PERFINFO_LOG_TYPE_BIGPOOLSNAP_DC_START         (EVENT_TRACE_GROUP_POOL | 0x2a)
#define PERFINFO_LOG_TYPE_BIGPOOLSNAP_DC_END           (EVENT_TRACE_GROUP_POOL | 0x2b)
#define PERFINFO_LOG_TYPE_POOLSNAP_SESSION_DC_START    (EVENT_TRACE_GROUP_POOL | 0x2c)
#define PERFINFO_LOG_TYPE_POOLSNAP_SESSION_DC_END      (EVENT_TRACE_GROUP_POOL | 0x2d)
#define PERFINFO_LOG_TYPE_SESSIONBIGPOOLSNAP_DC_START  (EVENT_TRACE_GROUP_POOL | 0x2e)
#define PERFINFO_LOG_TYPE_SESSIONBIGPOOLSNAP_DC_END    (EVENT_TRACE_GROUP_POOL | 0x2f)

//
// Event types for Heap subsystem
//
#define PERFINFO_LOG_TYPE_HEAP_CREATE                  (EVENT_TRACE_GROUP_HEAP | 0x20)
#define PERFINFO_LOG_TYPE_HEAP_ALLOC                   (EVENT_TRACE_GROUP_HEAP | 0x21)
#define PERFINFO_LOG_TYPE_HEAP_REALLOC                 (EVENT_TRACE_GROUP_HEAP | 0x22)
#define PERFINFO_LOG_TYPE_HEAP_DESTROY                 (EVENT_TRACE_GROUP_HEAP | 0x23)
#define PERFINFO_LOG_TYPE_HEAP_FREE                    (EVENT_TRACE_GROUP_HEAP | 0x24)
#define PERFINFO_LOG_TYPE_HEAP_EXTEND                  (EVENT_TRACE_GROUP_HEAP | 0x25)
#define PERFINFO_LOG_TYPE_HEAP_SNAPSHOT                (EVENT_TRACE_GROUP_HEAP | 0x26)
#define PERFINFO_LOG_TYPE_HEAP_CREATE_SNAPSHOT         (EVENT_TRACE_GROUP_HEAP | 0x27)
#define PERFINFO_LOG_TYPE_HEAP_DESTROY_SNAPSHOT        (EVENT_TRACE_GROUP_HEAP | 0x28)
#define PERFINFO_LOG_TYPE_HEAP_EXTEND_SNAPSHOT         (EVENT_TRACE_GROUP_HEAP | 0x29)
#define PERFINFO_LOG_TYPE_HEAP_CONTRACT                (EVENT_TRACE_GROUP_HEAP | 0x2a)
#define PERFINFO_LOG_TYPE_HEAP_LOCK                    (EVENT_TRACE_GROUP_HEAP | 0x2b)
#define PERFINFO_LOG_TYPE_HEAP_UNLOCK                  (EVENT_TRACE_GROUP_HEAP | 0x2c)
#define PERFINFO_LOG_TYPE_HEAP_VALIDATE                (EVENT_TRACE_GROUP_HEAP | 0x2d)
#define PERFINFO_LOG_TYPE_HEAP_WALK                    (EVENT_TRACE_GROUP_HEAP | 0x2e)

#define PERFINFO_LOG_TYPE_HEAP_SUBSEGMENT_ALLOC          (EVENT_TRACE_GROUP_HEAP | 0x2f)
#define PERFINFO_LOG_TYPE_HEAP_SUBSEGMENT_FREE           (EVENT_TRACE_GROUP_HEAP | 0x30)
#define PERFINFO_LOG_TYPE_HEAP_SUBSEGMENT_ALLOC_CACHE    (EVENT_TRACE_GROUP_HEAP | 0x31)
#define PERFINFO_LOG_TYPE_HEAP_SUBSEGMENT_FREE_CACHE     (EVENT_TRACE_GROUP_HEAP | 0x32)
#define PERFINFO_LOG_TYPE_HEAP_COMMIT                    (EVENT_TRACE_GROUP_HEAP | 0x33)
#define PERFINFO_LOG_TYPE_HEAP_DECOMMIT                  (EVENT_TRACE_GROUP_HEAP | 0x34)
#define PERFINFO_LOG_TYPE_HEAP_SUBSEGMENT_INIT           (EVENT_TRACE_GROUP_HEAP | 0x35)
#define PERFINFO_LOG_TYPE_HEAP_AFFINITY_ENABLE           (EVENT_TRACE_GROUP_HEAP | 0x36)
//Reserved                                               (EVENT_TRACE_GROUP_HEAP | 0x37)
#define PERFINFO_LOG_TYPE_HEAP_SUBSEGMENT_ACTIVATED      (EVENT_TRACE_GROUP_HEAP | 0x38)
#define PERFINFO_LOG_TYPE_HEAP_AFFINITY_ASSIGN           (EVENT_TRACE_GROUP_HEAP | 0x39)
#define PERFINFO_LOG_TYPE_HEAP_REUSE_THRESHOLD_ACTIVATED (EVENT_TRACE_GROUP_HEAP | 0x3a)

//
// Event Types for Critical Section Subsystem
//

#define PERFINFO_LOG_TYPE_CRITSEC_ENTER                (EVENT_TRACE_GROUP_CRITSEC | 0x20)
#define PERFINFO_LOG_TYPE_CRITSEC_LEAVE                (EVENT_TRACE_GROUP_CRITSEC | 0x21)
#define PERFINFO_LOG_TYPE_CRITSEC_COLLISION            (EVENT_TRACE_GROUP_CRITSEC | 0x22)
#define PERFINFO_LOG_TYPE_CRITSEC_INITIALIZE           (EVENT_TRACE_GROUP_CRITSEC | 0x23)

//
// Event types for Stackwalk subsystem
//

#define PERFINFO_LOG_TYPE_STACKWALK                    (EVENT_TRACE_GROUP_STACKWALK | 0x20)
//Reserved                                             (EVENT_TRACE_GROUP_STACKWALK | 0x21)
#define PERFINFO_LOG_TYPE_STACKTRACE_CREATE            (EVENT_TRACE_GROUP_STACKWALK | 0x22)
#define PERFINFO_LOG_TYPE_STACKTRACE_DELETE            (EVENT_TRACE_GROUP_STACKWALK | 0x23)
#define PERFINFO_LOG_TYPE_STACKTRACE_RUNDOWN           (EVENT_TRACE_GROUP_STACKWALK | 0x24)
#define PERFINFO_LOG_TYPE_STACKTRACE_KEY_KERNEL        (EVENT_TRACE_GROUP_STACKWALK | 0x25)
#define PERFINFO_LOG_TYPE_STACKTRACE_KEY_USER          (EVENT_TRACE_GROUP_STACKWALK | 0x26)

//
// Event types for ALPC
//

#define WMI_LOG_TYPE_ALPC_SEND_MESSAGE                  (EVENT_TRACE_GROUP_ALPC | 0x21)
#define WMI_LOG_TYPE_ALPC_RECEIVE_MESSAGE               (EVENT_TRACE_GROUP_ALPC | 0x22)
#define WMI_LOG_TYPE_ALPC_WAIT_FOR_REPLY                (EVENT_TRACE_GROUP_ALPC | 0x23)
#define WMI_LOG_TYPE_ALPC_WAIT_FOR_NEW_MESSAGE          (EVENT_TRACE_GROUP_ALPC | 0x24)
#define WMI_LOG_TYPE_ALPC_UNWAIT                        (EVENT_TRACE_GROUP_ALPC | 0x25)
#define WMI_LOG_TYPE_ALPC_CONNECT_REQUEST               (EVENT_TRACE_GROUP_ALPC | 0x26)
#define WMI_LOG_TYPE_ALPC_CONNECT_SUCCESS               (EVENT_TRACE_GROUP_ALPC | 0x27)
#define WMI_LOG_TYPE_ALPC_CONNECT_FAIL                  (EVENT_TRACE_GROUP_ALPC | 0x28)
#define WMI_LOG_TYPE_ALPC_CLOSE_PORT                    (EVENT_TRACE_GROUP_ALPC | 0x29)


//
// Event types for Object Manager subsystem
//

#define PERFINFO_LOG_TYPE_CREATE_HANDLE                (EVENT_TRACE_GROUP_OBJECT | 0x20)
#define PERFINFO_LOG_TYPE_CLOSE_HANDLE                 (EVENT_TRACE_GROUP_OBJECT | 0x21)
#define PERFINFO_LOG_TYPE_DUPLICATE_HANDLE             (EVENT_TRACE_GROUP_OBJECT | 0x22)
//Reserved                                             (EVENT_TRACE_GROUP_OBJECT | 0x23)
#define PERFINFO_LOG_TYPE_OBJECT_TYPE_DC_START         (EVENT_TRACE_GROUP_OBJECT | 0x24)
#define PERFINFO_LOG_TYPE_OBJECT_TYPE_DC_END           (EVENT_TRACE_GROUP_OBJECT | 0x25)
#define PERFINFO_LOG_TYPE_OBJECT_HANDLE_DC_START       (EVENT_TRACE_GROUP_OBJECT | 0x26)
#define PERFINFO_LOG_TYPE_OBJECT_HANDLE_DC_END         (EVENT_TRACE_GROUP_OBJECT | 0x27)
//Reserved                                             (EVENT_TRACE_GROUP_OBJECT | 0x28)
//Reserved                                             (EVENT_TRACE_GROUP_OBJECT | 0x29)
//Reserved                                             (EVENT_TRACE_GROUP_OBJECT | 0x2a)
//Reserved                                             (EVENT_TRACE_GROUP_OBJECT | 0x2b)
//Reserved                                             (EVENT_TRACE_GROUP_OBJECT | 0x2c)
//Reserved                                             (EVENT_TRACE_GROUP_OBJECT | 0x2d)
//Reserved                                             (EVENT_TRACE_GROUP_OBJECT | 0x2e)
//Reserved                                             (EVENT_TRACE_GROUP_OBJECT | 0x2f)
#define PERFINFO_LOG_TYPE_CREATE_OBJECT                (EVENT_TRACE_GROUP_OBJECT | 0x30)
#define PERFINFO_LOG_TYPE_DELETE_OBJECT                (EVENT_TRACE_GROUP_OBJECT | 0x31)
#define PERFINFO_LOG_TYPE_REFERENCE_OBJECT             (EVENT_TRACE_GROUP_OBJECT | 0x32)
#define PERFINFO_LOG_TYPE_DEREFERENCE_OBJECT           (EVENT_TRACE_GROUP_OBJECT | 0x33)

//
// Event types for Power subsystem
//

#define PERFINFO_LOG_TYPE_BATTERY_LIFE_INFO            (EVENT_TRACE_GROUP_POWER | 0x20)
#define PERFINFO_LOG_TYPE_IDLE_STATE_CHANGE            (EVENT_TRACE_GROUP_POWER | 0x21)
#define PERFINFO_LOG_TYPE_SET_POWER_ACTION             (EVENT_TRACE_GROUP_POWER | 0x22)
#define PERFINFO_LOG_TYPE_SET_POWER_ACTION_RET         (EVENT_TRACE_GROUP_POWER | 0x23)
#define PERFINFO_LOG_TYPE_SET_DEVICES_STATE            (EVENT_TRACE_GROUP_POWER | 0x24)
#define PERFINFO_LOG_TYPE_SET_DEVICES_STATE_RET        (EVENT_TRACE_GROUP_POWER | 0x25)
#define PERFINFO_LOG_TYPE_PO_NOTIFY_DEVICE             (EVENT_TRACE_GROUP_POWER | 0x26)
#define PERFINFO_LOG_TYPE_PO_NOTIFY_DEVICE_COMPLETE    (EVENT_TRACE_GROUP_POWER | 0x27)
#define PERFINFO_LOG_TYPE_PO_SESSION_CALLOUT           (EVENT_TRACE_GROUP_POWER | 0x28)
#define PERFINFO_LOG_TYPE_PO_SESSION_CALLOUT_RET       (EVENT_TRACE_GROUP_POWER | 0x29)
#define PERFINFO_LOG_TYPE_PO_PRESLEEP                  (EVENT_TRACE_GROUP_POWER | 0x30)
#define PERFINFO_LOG_TYPE_PO_POSTSLEEP                 (EVENT_TRACE_GROUP_POWER | 0x31)
#define PERFINFO_LOG_TYPE_PO_CALIBRATED_PERFCOUNTER    (EVENT_TRACE_GROUP_POWER | 0x32)
#define PERFINFO_LOG_TYPE_PPM_PERF_STATE_CHANGE        (EVENT_TRACE_GROUP_POWER | 0x33)
#define PERFINFO_LOG_TYPE_PPM_THROTTLE_STATE_CHANGE    (EVENT_TRACE_GROUP_POWER | 0x34)
#define PERFINFO_LOG_TYPE_PPM_IDLE_STATE_CHANGE        (EVENT_TRACE_GROUP_POWER | 0x35)
#define PERFINFO_LOG_TYPE_PPM_THERMAL_CONSTRAINT       (EVENT_TRACE_GROUP_POWER | 0x36)
#define PERFINFO_LOG_TYPE_PO_SIGNAL_RESUME_UI          (EVENT_TRACE_GROUP_POWER | 0x37)
#define PERFINFO_LOG_TYPE_PO_SIGNAL_VIDEO_ON           (EVENT_TRACE_GROUP_POWER | 0x38)
#define PERFINFO_LOG_TYPE_PPM_IDLE_STATE_ENTER         (EVENT_TRACE_GROUP_POWER | 0x39)
#define PERFINFO_LOG_TYPE_PPM_IDLE_STATE_EXIT          (EVENT_TRACE_GROUP_POWER | 0x3a)
#define PERFINFO_LOG_TYPE_PPM_PLATFORM_IDLE_STATE_ENTER (EVENT_TRACE_GROUP_POWER | 0x3b)
#define PERFINFO_LOG_TYPE_PPM_IDLE_EXIT_LATENCY        (EVENT_TRACE_GROUP_POWER | 0x3c)
#define PERFINFO_LOG_TYPE_PPM_IDLE_PROCESSOR_SELECTION (EVENT_TRACE_GROUP_POWER | 0x3d)
#define PERFINFO_LOG_TYPE_PPM_IDLE_PLATFORM_SELECTION  (EVENT_TRACE_GROUP_POWER | 0x3e)
#define PERFINFO_LOG_TYPE_PPM_COORDINATED_IDLE_ENTER   (EVENT_TRACE_GROUP_POWER | 0x3f)
#define PERFINFO_LOG_TYPE_PPM_COORDINATED_IDLE_EXIT    (EVENT_TRACE_GROUP_POWER | 0x40)

//
// Event types for MODBound subsystem
//
#define PERFINFO_LOG_TYPE_COWHEADER                    (EVENT_TRACE_GROUP_MODBOUND | 0x18)
#define PERFINFO_LOG_TYPE_COWBLOB                      (EVENT_TRACE_GROUP_MODBOUND | 0x19)
#define PERFINFO_LOG_TYPE_COWBLOB_CLOSED               (EVENT_TRACE_GROUP_MODBOUND | 0x1a)
#define PERFINFO_LOG_TYPE_MODULEBOUND_ENT              (EVENT_TRACE_GROUP_MODBOUND | 0x20)
#define PERFINFO_LOG_TYPE_MODULEBOUND_JUMP             (EVENT_TRACE_GROUP_MODBOUND | 0x21)
#define PERFINFO_LOG_TYPE_MODULEBOUND_RET              (EVENT_TRACE_GROUP_MODBOUND | 0x22)
#define PERFINFO_LOG_TYPE_MODULEBOUND_CALL             (EVENT_TRACE_GROUP_MODBOUND | 0x23)
#define PERFINFO_LOG_TYPE_MODULEBOUND_CALLRET          (EVENT_TRACE_GROUP_MODBOUND | 0x24)
#define PERFINFO_LOG_TYPE_MODULEBOUND_INT2E            (EVENT_TRACE_GROUP_MODBOUND | 0x25)
#define PERFINFO_LOG_TYPE_MODULEBOUND_INT2B            (EVENT_TRACE_GROUP_MODBOUND | 0x26)
#define PERFINFO_LOG_TYPE_MODULEBOUND_FULLTRACE        (EVENT_TRACE_GROUP_MODBOUND | 0x27)

//
// Event types for the thread class scheduler
//
// TODO: Because MMCSS is a DLL it doesn't need to use UMGL.
//
#define PERFINFO_LOG_TYPE_MMCSS_START                  (0x20)
#define PERFINFO_LOG_TYPE_MMCSS_STOP                   (0x21)
#define PERFINFO_LOG_TYPE_MMCSS_SCHEDULER_EVENT        (0x22)
#define PERFINFO_LOG_TYPE_MMCSS_SCHEDULER_WAKEUP       (0x23)
#define PERFINFO_LOG_TYPE_MMCSS_SCHEDULER_SLEEP        (0x24)
#define PERFINFO_LOG_TYPE_MMCSS_SCHEDULER_SLEEP_RESP   (0x25)


//
// Event types for SplitIo
//

#define PERFINFO_LOG_TYPE_SPLITIO_VOLMGR                    (EVENT_TRACE_GROUP_SPLITIO | 0x20)

// Event types for ThreadPool
#define PERFINFO_LOG_TYPE_TP_CALLBACK_ENQUEUE               (EVENT_TRACE_GROUP_THREAD_POOL | 0x20)
#define PERFINFO_LOG_TYPE_TP_CALLBACK_DEQUEUE               (EVENT_TRACE_GROUP_THREAD_POOL | 0x21)
#define PERFINFO_LOG_TYPE_TP_CALLBACK_START                 (EVENT_TRACE_GROUP_THREAD_POOL | 0x22)
#define PERFINFO_LOG_TYPE_TP_CALLBACK_STOP                  (EVENT_TRACE_GROUP_THREAD_POOL | 0x23)
#define PERFINFO_LOG_TYPE_TP_CALLBACK_CANCEL                (EVENT_TRACE_GROUP_THREAD_POOL | 0x24)
#define PERFINFO_LOG_TYPE_TP_POOL_CREATE                    (EVENT_TRACE_GROUP_THREAD_POOL | 0x25)
#define PERFINFO_LOG_TYPE_TP_POOL_CLOSE                     (EVENT_TRACE_GROUP_THREAD_POOL | 0x26)
#define PERFINFO_LOG_TYPE_TP_POOL_TH_MIN_SET                (EVENT_TRACE_GROUP_THREAD_POOL | 0x27)
#define PERFINFO_LOG_TYPE_TP_POOL_TH_MAX_SET                (EVENT_TRACE_GROUP_THREAD_POOL | 0x28)
#define PERFINFO_LOG_TYPE_TP_WORKER_NUMANODE_SWITCH         (EVENT_TRACE_GROUP_THREAD_POOL | 0x29)
#define PERFINFO_LOG_TYPE_TP_TIMER_SET                      (EVENT_TRACE_GROUP_THREAD_POOL | 0x2a)
#define PERFINFO_LOG_TYPE_TP_TIMER_CANCELLED                (EVENT_TRACE_GROUP_THREAD_POOL | 0x2b)
#define PERFINFO_LOG_TYPE_TP_TIMER_SET_NTTIMER              (EVENT_TRACE_GROUP_THREAD_POOL | 0x2c)
#define PERFINFO_LOG_TYPE_TP_TIMER_CANCEL_NTTIMER           (EVENT_TRACE_GROUP_THREAD_POOL | 0x2d)
#define PERFINFO_LOG_TYPE_TP_TIMER_EXPIRATION_BEGIN         (EVENT_TRACE_GROUP_THREAD_POOL | 0x2e)
#define PERFINFO_LOG_TYPE_TP_TIMER_EXPIRATION_END           (EVENT_TRACE_GROUP_THREAD_POOL | 0x2f)
#define PERFINFO_LOG_TYPE_TP_TIMER_EXPIRATION               (EVENT_TRACE_GROUP_THREAD_POOL | 0x30)

// Event types for UMS
#define PERFINFO_LOG_TYPE_UMS_DIRECTED_SWITCH_START         (EVENT_TRACE_GROUP_UMS | 0x20)
#define PERFINFO_LOG_TYPE_UMS_DIRECTED_SWITCH_END           (EVENT_TRACE_GROUP_UMS | 0x21)
#define PERFINFO_LOG_TYPE_UMS_PARK                          (EVENT_TRACE_GROUP_UMS | 0x22)
#define PERFINFO_LOG_TYPE_UMS_DISASSOCIATE                  (EVENT_TRACE_GROUP_UMS | 0x23)
#define PERFINFO_LOG_TYPE_UMS_CONTEXT_SWITCH                (EVENT_TRACE_GROUP_UMS | 0x24)

// Event types for Cache manager
#define PERFINFO_LOG_TYPE_CC_WORKITEM_ENQUEUE               (EVENT_TRACE_GROUP_CC | 0x00)
#define PERFINFO_LOG_TYPE_CC_WORKITEM_DEQUEUE               (EVENT_TRACE_GROUP_CC | 0x01)
#define PERFINFO_LOG_TYPE_CC_WORKITEM_COMPLETE              (EVENT_TRACE_GROUP_CC | 0x02)
#define PERFINFO_LOG_TYPE_CC_READ_AHEAD                     (EVENT_TRACE_GROUP_CC | 0x03)
#define PERFINFO_LOG_TYPE_CC_WRITE_BEHIND                   (EVENT_TRACE_GROUP_CC | 0x04)
#define PERFINFO_LOG_TYPE_CC_LAZY_WRITE_SCAN                (EVENT_TRACE_GROUP_CC | 0x05)
#define PERFINFO_LOG_TYPE_CC_CAN_I_WRITE_FAIL               (EVENT_TRACE_GROUP_CC | 0x06)
//#define PERFINFO_LOG_TYPE_CC_MAP_VIEW                       (EVENT_TRACE_GROUP_CC | 0x07)
//#define PERFINFO_LOG_TYPE_CC_UNMAP_VIEW                     (EVENT_TRACE_GROUP_CC | 0x08)
#define PERFINFO_LOG_TYPE_CC_FLUSH_CACHE                    (EVENT_TRACE_GROUP_CC | 0x09)
#define PERFINFO_LOG_TYPE_CC_FLUSH_SECTION                  (EVENT_TRACE_GROUP_CC | 0x0a)
#define PERFINFO_LOG_TYPE_CC_READ_AHEAD_PREFETCH            (EVENT_TRACE_GROUP_CC | 0x0b)
#define PERFINFO_LOG_TYPE_CC_SCHEDULE_READ_AHEAD            (EVENT_TRACE_GROUP_CC | 0x0c)
#define PERFINFO_LOG_TYPE_CC_LOGGED_STREAM_INFO             (EVENT_TRACE_GROUP_CC | 0x0d)
#define PERFINFO_LOG_TYPE_CC_EXTRA_WRITEBEHIND_THREAD       (EVENT_TRACE_GROUP_CC | 0x0e)

    typedef ULONG PERFINFO_MASK;

    typedef struct _PERFINFO_GROUPMASK
    {
        ULONG Masks[PERF_NUM_MASKS];
    } PERFINFO_GROUPMASK, * PPERFINFO_GROUPMASK;

    typedef struct _EVENT_TRACE_VERSION_INFORMATION
    {
        EVENT_TRACE_INFORMATION_CLASS EventTraceInformationClass;
        ULONG EventTraceKernelVersion;
    } EVENT_TRACE_VERSION_INFORMATION, * PEVENT_TRACE_VERSION_INFORMATION;

    typedef struct _EVENT_TRACE_GROUPMASK_INFORMATION
    {
        EVENT_TRACE_INFORMATION_CLASS EventTraceInformationClass;
        TRACEHANDLE TraceHandle;
        PERFINFO_GROUPMASK EventTraceGroupMasks;
    } EVENT_TRACE_GROUPMASK_INFORMATION, * PEVENT_TRACE_GROUPMASK_INFORMATION;

    typedef struct _EVENT_TRACE_PERFORMANCE_INFORMATION
    {
        EVENT_TRACE_INFORMATION_CLASS EventTraceInformationClass;
        LARGE_INTEGER LogfileBytesWritten;
    } EVENT_TRACE_PERFORMANCE_INFORMATION, * PEVENT_TRACE_PERFORMANCE_INFORMATION;

    typedef struct _EVENT_TRACE_TIME_PROFILE_INFORMATION
    {
        EVENT_TRACE_INFORMATION_CLASS EventTraceInformationClass;
        ULONG ProfileInterval;
    } EVENT_TRACE_TIME_PROFILE_INFORMATION, * PEVENT_TRACE_TIME_PROFILE_INFORMATION;

    typedef struct _EVENT_TRACE_SESSION_SECURITY_INFORMATION
    {
        EVENT_TRACE_INFORMATION_CLASS EventTraceInformationClass;
        ULONG SecurityInformation;
        TRACEHANDLE TraceHandle;
        UCHAR SecurityDescriptor[1];
    } EVENT_TRACE_SESSION_SECURITY_INFORMATION, * PEVENT_TRACE_SESSION_SECURITY_INFORMATION;

    typedef struct _EVENT_TRACE_SPINLOCK_INFORMATION
    {
        EVENT_TRACE_INFORMATION_CLASS EventTraceInformationClass;
        ULONG SpinLockSpinThreshold;
        ULONG SpinLockAcquireSampleRate;
        ULONG SpinLockContentionSampleRate;
        ULONG SpinLockHoldThreshold;
    } EVENT_TRACE_SPINLOCK_INFORMATION, * PEVENT_TRACE_SPINLOCK_INFORMATION;

    typedef struct _EVENT_TRACE_SYSTEM_EVENT_INFORMATION
    {
        EVENT_TRACE_INFORMATION_CLASS EventTraceInformationClass;
        TRACEHANDLE TraceHandle;
        ULONG HookId[1];
    } EVENT_TRACE_SYSTEM_EVENT_INFORMATION, * PEVENT_TRACE_SYSTEM_EVENT_INFORMATION;

    typedef EVENT_TRACE_SYSTEM_EVENT_INFORMATION EVENT_TRACE_STACK_TRACING_INFORMATION, * PEVENT_TRACE_STACK_TRACING_INFORMATION;
    typedef EVENT_TRACE_SYSTEM_EVENT_INFORMATION EVENT_TRACE_PEBS_TRACING_INFORMATION, * PEVENT_TRACE_PEBS_TRACING_INFORMATION;
    typedef EVENT_TRACE_SYSTEM_EVENT_INFORMATION EVENT_TRACE_PROFILE_EVENT_INFORMATION, * PEVENT_TRACE_PROFILE_EVENT_INFORMATION;

    typedef struct _EVENT_TRACE_EXECUTIVE_RESOURCE_INFORMATION
    {
        EVENT_TRACE_INFORMATION_CLASS EventTraceInformationClass;
        ULONG ReleaseSamplingRate;
        ULONG ContentionSamplingRate;
        ULONG NumberOfExcessiveTimeouts;
    } EVENT_TRACE_EXECUTIVE_RESOURCE_INFORMATION, * PEVENT_TRACE_EXECUTIVE_RESOURCE_INFORMATION;

    typedef struct _EVENT_TRACE_HEAP_TRACING_INFORMATION
    {
        EVENT_TRACE_INFORMATION_CLASS EventTraceInformationClass;
        ULONG ProcessId[1];
    } EVENT_TRACE_HEAP_TRACING_INFORMATION, * PEVENT_TRACE_HEAP_TRACING_INFORMATION;

    typedef struct _EVENT_TRACE_TAG_FILTER_INFORMATION
    {
        EVENT_TRACE_INFORMATION_CLASS EventTraceInformationClass;
        TRACEHANDLE TraceHandle;
        ULONG Filter[1];
    } EVENT_TRACE_TAG_FILTER_INFORMATION, * PEVENT_TRACE_TAG_FILTER_INFORMATION;

    typedef EVENT_TRACE_TAG_FILTER_INFORMATION EVENT_TRACE_POOLTAG_FILTER_INFORMATION, * PEVENT_TRACE_POOLTAG_FILTER_INFORMATION;
    typedef EVENT_TRACE_TAG_FILTER_INFORMATION EVENT_TRACE_OBJECT_TYPE_FILTER_INFORMATION, * PEVENT_TRACE_OBJECT_TYPE_FILTER_INFORMATION;

    // ProfileSource
#define ETW_MAX_PROFILING_SOURCES 4
#define ETW_MAX_PMC_EVENTS        4
#define ETW_MAX_PMC_COUNTERS      4

    typedef struct _EVENT_TRACE_PROFILE_COUNTER_INFORMATION
    {
        EVENT_TRACE_INFORMATION_CLASS EventTraceInformationClass;
        TRACEHANDLE TraceHandle;
        ULONG ProfileSource[1];
    } EVENT_TRACE_PROFILE_COUNTER_INFORMATION, * PEVENT_TRACE_PROFILE_COUNTER_INFORMATION;

    typedef EVENT_TRACE_PROFILE_COUNTER_INFORMATION EVENT_TRACE_PROFILE_CONFIG_INFORMATION, * PEVENT_TRACE_PROFILE_CONFIG_INFORMATION;

    //typedef struct _PROFILE_SOURCE_INFO
    //{
    //    ULONG NextEntryOffset;
    //    ULONG Source;
    //    ULONG MinInterval;
    //    ULONG MaxInterval;
    //    PVOID Reserved;
    //    WCHAR Description[1];
    //} PROFILE_SOURCE_INFO, *PPROFILE_SOURCE_INFO;

    typedef struct _PROFILE_SOURCE_INFO* PPROFILE_SOURCE_INFO;

    typedef struct _EVENT_TRACE_PROFILE_LIST_INFORMATION
    {
        EVENT_TRACE_INFORMATION_CLASS EventTraceInformationClass;
        ULONG Spare;
        PPROFILE_SOURCE_INFO Profile[1];
    } EVENT_TRACE_PROFILE_LIST_INFORMATION, * PEVENT_TRACE_PROFILE_LIST_INFORMATION;

    typedef struct _EVENT_TRACE_STACK_CACHING_INFORMATION
    {
        EVENT_TRACE_INFORMATION_CLASS EventTraceInformationClass;
        TRACEHANDLE TraceHandle;
        BOOLEAN Enabled;
        UCHAR Reserved[3];
        ULONG CacheSize;
        ULONG BucketCount;
    } EVENT_TRACE_STACK_CACHING_INFORMATION, * PEVENT_TRACE_STACK_CACHING_INFORMATION;

    typedef struct _EVENT_TRACE_SOFT_RESTART_INFORMATION
    {
        EVENT_TRACE_INFORMATION_CLASS EventTraceInformationClass;
        TRACEHANDLE TraceHandle;
        BOOLEAN PersistTraceBuffers;
        WCHAR FileName[1];
    } EVENT_TRACE_SOFT_RESTART_INFORMATION, * PEVENT_TRACE_SOFT_RESTART_INFORMATION;

    typedef struct _EVENT_TRACE_PROFILE_ADD_INFORMATION
    {
        EVENT_TRACE_INFORMATION_CLASS EventTraceInformationClass;
        BOOLEAN PerfEvtEventSelect;
        BOOLEAN PerfEvtUnitSelect;
        ULONG PerfEvtType;
        ULONG CpuInfoHierarchy[0x3];
        ULONG InitialInterval;
        BOOLEAN AllowsHalt;
        BOOLEAN Persist;
        WCHAR ProfileSourceDescription[0x1];
    } EVENT_TRACE_PROFILE_ADD_INFORMATION, * PEVENT_TRACE_PROFILE_ADD_INFORMATION;

    typedef struct _EVENT_TRACE_PROFILE_REMOVE_INFORMATION
    {
        EVENT_TRACE_INFORMATION_CLASS EventTraceInformationClass;
        KPROFILE_SOURCE ProfileSource;
        ULONG CpuInfoHierarchy[0x3];
    } EVENT_TRACE_PROFILE_REMOVE_INFORMATION, * PEVENT_TRACE_PROFILE_REMOVE_INFORMATION;

    typedef struct _EVENT_TRACE_COVERAGE_SAMPLER_INFORMATION
    {
        EVENT_TRACE_INFORMATION_CLASS EventTraceInformationClass;
        UCHAR CoverageSamplerInformationClass;
        UCHAR MajorVersion;
        UCHAR MinorVersion;
        UCHAR Reserved;
        HANDLE SamplerHandle;
    } EVENT_TRACE_COVERAGE_SAMPLER_INFORMATION, * PEVENT_TRACE_COVERAGE_SAMPLER_INFORMATION;

    typedef struct _SYSTEM_EXCEPTION_INFORMATION
    {
        ULONG AlignmentFixupCount;
        ULONG ExceptionDispatchCount;
        ULONG FloatingEmulationCount;
        ULONG ByteWordEmulationCount;
    } SYSTEM_EXCEPTION_INFORMATION, * PSYSTEM_EXCEPTION_INFORMATION;

    typedef enum _SYSTEM_CRASH_DUMP_CONFIGURATION_CLASS
    {
        SystemCrashDumpDisable,
        SystemCrashDumpReconfigure,
        SystemCrashDumpInitializationComplete
    } SYSTEM_CRASH_DUMP_CONFIGURATION_CLASS, * PSYSTEM_CRASH_DUMP_CONFIGURATION_CLASS;

    typedef struct _SYSTEM_CRASH_DUMP_STATE_INFORMATION
    {
        SYSTEM_CRASH_DUMP_CONFIGURATION_CLASS CrashDumpConfigurationClass;
    } SYSTEM_CRASH_DUMP_STATE_INFORMATION, * PSYSTEM_CRASH_DUMP_STATE_INFORMATION;

    typedef struct _SYSTEM_KERNEL_DEBUGGER_INFORMATION
    {
        BOOLEAN KernelDebuggerEnabled;
        BOOLEAN KernelDebuggerNotPresent;
    } SYSTEM_KERNEL_DEBUGGER_INFORMATION, * PSYSTEM_KERNEL_DEBUGGER_INFORMATION;

    typedef struct _SYSTEM_CONTEXT_SWITCH_INFORMATION
    {
        ULONG ContextSwitches;
        ULONG FindAny;
        ULONG FindLast;
        ULONG FindIdeal;
        ULONG IdleAny;
        ULONG IdleCurrent;
        ULONG IdleLast;
        ULONG IdleIdeal;
        ULONG PreemptAny;
        ULONG PreemptCurrent;
        ULONG PreemptLast;
        ULONG SwitchToIdle;
    } SYSTEM_CONTEXT_SWITCH_INFORMATION, * PSYSTEM_CONTEXT_SWITCH_INFORMATION;

    typedef struct _SYSTEM_REGISTRY_QUOTA_INFORMATION
    {
        ULONG RegistryQuotaAllowed;
        ULONG RegistryQuotaUsed;
        SIZE_T PagedPoolSize;
    } SYSTEM_REGISTRY_QUOTA_INFORMATION, * PSYSTEM_REGISTRY_QUOTA_INFORMATION;

    typedef struct _SYSTEM_PROCESSOR_IDLE_INFORMATION
    {
        ULONGLONG IdleTime;
        ULONGLONG C1Time;
        ULONGLONG C2Time;
        ULONGLONG C3Time;
        ULONG C1Transitions;
        ULONG C2Transitions;
        ULONG C3Transitions;
        ULONG Padding;
    } SYSTEM_PROCESSOR_IDLE_INFORMATION, * PSYSTEM_PROCESSOR_IDLE_INFORMATION;

    typedef struct _SYSTEM_LEGACY_DRIVER_INFORMATION
    {
        ULONG VetoType;
        UNICODE_STRING VetoList;
    } SYSTEM_LEGACY_DRIVER_INFORMATION, * PSYSTEM_LEGACY_DRIVER_INFORMATION;

    typedef struct _SYSTEM_LOOKASIDE_INFORMATION
    {
        USHORT CurrentDepth;
        USHORT MaximumDepth;
        ULONG TotalAllocates;
        ULONG AllocateMisses;
        ULONG TotalFrees;
        ULONG FreeMisses;
        ULONG Type;
        ULONG Tag;
        ULONG Size;
    } SYSTEM_LOOKASIDE_INFORMATION, * PSYSTEM_LOOKASIDE_INFORMATION;

    // private
    typedef struct _SYSTEM_RANGE_START_INFORMATION
    {
        ULONG_PTR SystemRangeStart;
    } SYSTEM_RANGE_START_INFORMATION, * PSYSTEM_RANGE_START_INFORMATION;

    typedef struct _SYSTEM_VERIFIER_INFORMATION_LEGACY // pre-19H1
    {
        ULONG NextEntryOffset;
        ULONG Level;
        UNICODE_STRING DriverName;

        ULONG RaiseIrqls;
        ULONG AcquireSpinLocks;
        ULONG SynchronizeExecutions;
        ULONG AllocationsAttempted;

        ULONG AllocationsSucceeded;
        ULONG AllocationsSucceededSpecialPool;
        ULONG AllocationsWithNoTag;
        ULONG TrimRequests;

        ULONG Trims;
        ULONG AllocationsFailed;
        ULONG AllocationsFailedDeliberately;
        ULONG Loads;

        ULONG Unloads;
        ULONG UnTrackedPool;
        ULONG CurrentPagedPoolAllocations;
        ULONG CurrentNonPagedPoolAllocations;

        ULONG PeakPagedPoolAllocations;
        ULONG PeakNonPagedPoolAllocations;

        SIZE_T PagedPoolUsageInBytes;
        SIZE_T NonPagedPoolUsageInBytes;
        SIZE_T PeakPagedPoolUsageInBytes;
        SIZE_T PeakNonPagedPoolUsageInBytes;
    } SYSTEM_VERIFIER_INFORMATION_LEGACY, * PSYSTEM_VERIFIER_INFORMATION_LEGACY;

    typedef struct _SYSTEM_VERIFIER_INFORMATION
    {
        ULONG NextEntryOffset;
        ULONG Level;
        ULONG RuleClasses[2];
        ULONG TriageContext;
        ULONG AreAllDriversBeingVerified;

        UNICODE_STRING DriverName;

        ULONG RaiseIrqls;
        ULONG AcquireSpinLocks;
        ULONG SynchronizeExecutions;
        ULONG AllocationsAttempted;

        ULONG AllocationsSucceeded;
        ULONG AllocationsSucceededSpecialPool;
        ULONG AllocationsWithNoTag;
        ULONG TrimRequests;

        ULONG Trims;
        ULONG AllocationsFailed;
        ULONG AllocationsFailedDeliberately;
        ULONG Loads;

        ULONG Unloads;
        ULONG UnTrackedPool;
        ULONG CurrentPagedPoolAllocations;
        ULONG CurrentNonPagedPoolAllocations;

        ULONG PeakPagedPoolAllocations;
        ULONG PeakNonPagedPoolAllocations;

        SIZE_T PagedPoolUsageInBytes;
        SIZE_T NonPagedPoolUsageInBytes;
        SIZE_T PeakPagedPoolUsageInBytes;
        SIZE_T PeakNonPagedPoolUsageInBytes;
    } SYSTEM_VERIFIER_INFORMATION, * PSYSTEM_VERIFIER_INFORMATION;

    // private
    typedef struct _SYSTEM_SESSION_PROCESS_INFORMATION
    {
        ULONG SessionId;
        ULONG SizeOfBuf;
        PVOID Buffer;
    } SYSTEM_SESSION_PROCESS_INFORMATION, * PSYSTEM_SESSION_PROCESS_INFORMATION;

#if (PHNT_MODE != PHNT_MODE_KERNEL)

    typedef struct _IMAGE_EXPORT_DIRECTORY* PIMAGE_EXPORT_DIRECTORY; // from ntrtl.h

    // private
    typedef struct _SYSTEM_GDI_DRIVER_INFORMATION
    {
        UNICODE_STRING DriverName;
        PVOID ImageAddress;
        PVOID SectionPointer;
        PVOID EntryPoint;
        PIMAGE_EXPORT_DIRECTORY ExportSectionPointer;
        ULONG ImageLength;
    } SYSTEM_GDI_DRIVER_INFORMATION, * PSYSTEM_GDI_DRIVER_INFORMATION;
#endif

    // geoffchappell
#ifdef _WIN64
#define MAXIMUM_NODE_COUNT 0x40
#else
#define MAXIMUM_NODE_COUNT 0x10
#endif

// private
    typedef struct _SYSTEM_NUMA_INFORMATION
    {
        ULONG HighestNodeNumber;
        ULONG Reserved;
        union
        {
            GROUP_AFFINITY ActiveProcessorsGroupAffinity[MAXIMUM_NODE_COUNT];
            ULONGLONG AvailableMemory[MAXIMUM_NODE_COUNT];
            ULONGLONG Pad[MAXIMUM_NODE_COUNT * 2];
        };
    } SYSTEM_NUMA_INFORMATION, * PSYSTEM_NUMA_INFORMATION;

    typedef struct _SYSTEM_PROCESSOR_POWER_INFORMATION
    {
        UCHAR CurrentFrequency;
        UCHAR ThermalLimitFrequency;
        UCHAR ConstantThrottleFrequency;
        UCHAR DegradedThrottleFrequency;
        UCHAR LastBusyFrequency;
        UCHAR LastC3Frequency;
        UCHAR LastAdjustedBusyFrequency;
        UCHAR ProcessorMinThrottle;
        UCHAR ProcessorMaxThrottle;
        ULONG NumberOfFrequencies;
        ULONG PromotionCount;
        ULONG DemotionCount;
        ULONG ErrorCount;
        ULONG RetryCount;
        ULONGLONG CurrentFrequencyTime;
        ULONGLONG CurrentProcessorTime;
        ULONGLONG CurrentProcessorIdleTime;
        ULONGLONG LastProcessorTime;
        ULONGLONG LastProcessorIdleTime;
        ULONGLONG Energy;
    } SYSTEM_PROCESSOR_POWER_INFORMATION, * PSYSTEM_PROCESSOR_POWER_INFORMATION;

    typedef struct _SYSTEM_HANDLE_TABLE_ENTRY_INFO_EX
    {
        PVOID Object;
        ULONG_PTR UniqueProcessId;
        ULONG_PTR HandleValue;
        ULONG GrantedAccess;
        USHORT CreatorBackTraceIndex;
        USHORT ObjectTypeIndex;
        ULONG HandleAttributes;
        ULONG Reserved;
    } SYSTEM_HANDLE_TABLE_ENTRY_INFO_EX, * PSYSTEM_HANDLE_TABLE_ENTRY_INFO_EX;

    typedef struct _SYSTEM_HANDLE_INFORMATION_EX
    {
        ULONG_PTR NumberOfHandles;
        ULONG_PTR Reserved;
        _Field_size_(NumberOfHandles) SYSTEM_HANDLE_TABLE_ENTRY_INFO_EX Handles[1];
    } SYSTEM_HANDLE_INFORMATION_EX, * PSYSTEM_HANDLE_INFORMATION_EX;

    typedef struct _SYSTEM_BIGPOOL_ENTRY
    {
        union
        {
            PVOID VirtualAddress;
            ULONG_PTR NonPaged : 1;
        };
        SIZE_T SizeInBytes;
        union
        {
            UCHAR Tag[4];
            ULONG TagUlong;
        };
    } SYSTEM_BIGPOOL_ENTRY, * PSYSTEM_BIGPOOL_ENTRY;

    typedef struct _SYSTEM_BIGPOOL_INFORMATION
    {
        ULONG Count;
        _Field_size_(Count) SYSTEM_BIGPOOL_ENTRY AllocatedInfo[1];
    } SYSTEM_BIGPOOL_INFORMATION, * PSYSTEM_BIGPOOL_INFORMATION;

    typedef struct _SYSTEM_POOL_ENTRY
    {
        BOOLEAN Allocated;
        BOOLEAN Spare0;
        USHORT AllocatorBackTraceIndex;
        ULONG Size;
        union
        {
            UCHAR Tag[4];
            ULONG TagUlong;
            PVOID ProcessChargedQuota;
        };
    } SYSTEM_POOL_ENTRY, * PSYSTEM_POOL_ENTRY;

    typedef struct _SYSTEM_POOL_INFORMATION
    {
        SIZE_T TotalSize;
        PVOID FirstEntry;
        USHORT EntryOverhead;
        BOOLEAN PoolTagPresent;
        BOOLEAN Spare0;
        ULONG NumberOfEntries;
        _Field_size_(NumberOfEntries) SYSTEM_POOL_ENTRY Entries[1];
    } SYSTEM_POOL_INFORMATION, * PSYSTEM_POOL_INFORMATION;

    typedef struct _SYSTEM_SESSION_POOLTAG_INFORMATION
    {
        SIZE_T NextEntryOffset;
        ULONG SessionId;
        ULONG Count;
        _Field_size_(Count) SYSTEM_POOLTAG TagInfo[1];
    } SYSTEM_SESSION_POOLTAG_INFORMATION, * PSYSTEM_SESSION_POOLTAG_INFORMATION;

    typedef struct _SYSTEM_SESSION_MAPPED_VIEW_INFORMATION
    {
        SIZE_T NextEntryOffset;
        ULONG SessionId;
        ULONG ViewFailures;
        SIZE_T NumberOfBytesAvailable;
        SIZE_T NumberOfBytesAvailableContiguous;
    } SYSTEM_SESSION_MAPPED_VIEW_INFORMATION, * PSYSTEM_SESSION_MAPPED_VIEW_INFORMATION;

    typedef enum _WATCHDOG_HANDLER_ACTION
    {
        WdActionSetTimeoutValue,
        WdActionQueryTimeoutValue,
        WdActionResetTimer,
        WdActionStopTimer,
        WdActionStartTimer,
        WdActionSetTriggerAction,
        WdActionQueryTriggerAction,
        WdActionQueryState
    } WATCHDOG_HANDLER_ACTION;

    typedef NTSTATUS(NTAPI* PSYSTEM_WATCHDOG_HANDLER)(_In_ WATCHDOG_HANDLER_ACTION Action, _In_ PVOID Context, _Inout_ PULONG DataValue, _In_ BOOLEAN NoLocks);

    // private
    typedef struct _SYSTEM_WATCHDOG_HANDLER_INFORMATION
    {
        PSYSTEM_WATCHDOG_HANDLER WdHandler;
        PVOID Context;
    } SYSTEM_WATCHDOG_HANDLER_INFORMATION, * PSYSTEM_WATCHDOG_HANDLER_INFORMATION;

    typedef enum _WATCHDOG_INFORMATION_CLASS
    {
        WdInfoTimeoutValue = 0,
        WdInfoResetTimer = 1,
        WdInfoStopTimer = 2,
        WdInfoStartTimer = 3,
        WdInfoTriggerAction = 4,
        WdInfoState = 5,
        WdInfoTriggerReset = 6,
        WdInfoNop = 7,
        WdInfoGeneratedLastReset = 8,
        WdInfoInvalid = 9,
    } WATCHDOG_INFORMATION_CLASS;

    // private
    typedef struct _SYSTEM_WATCHDOG_TIMER_INFORMATION
    {
        WATCHDOG_INFORMATION_CLASS WdInfoClass;
        ULONG DataValue;
    } SYSTEM_WATCHDOG_TIMER_INFORMATION, * PSYSTEM_WATCHDOG_TIMER_INFORMATION;

#if (PHNT_MODE != PHNT_MODE_KERNEL)
    // private
    typedef enum _SYSTEM_FIRMWARE_TABLE_ACTION
    {
        SystemFirmwareTableEnumerate,
        SystemFirmwareTableGet,
        SystemFirmwareTableMax
    } SYSTEM_FIRMWARE_TABLE_ACTION;

    // private
    typedef struct _SYSTEM_FIRMWARE_TABLE_INFORMATION
    {
        ULONG ProviderSignature; // (same as the GetSystemFirmwareTable function)
        SYSTEM_FIRMWARE_TABLE_ACTION Action;
        ULONG TableID;
        ULONG TableBufferLength;
        _Field_size_bytes_(TableBufferLength) UCHAR TableBuffer[1];
    } SYSTEM_FIRMWARE_TABLE_INFORMATION, * PSYSTEM_FIRMWARE_TABLE_INFORMATION;
#endif

#if (PHNT_MODE != PHNT_MODE_KERNEL)
    // private
    typedef NTSTATUS(__cdecl* PFNFTH)(
        _Inout_ PSYSTEM_FIRMWARE_TABLE_INFORMATION SystemFirmwareTableInfo
        );

    // private
    typedef struct _SYSTEM_FIRMWARE_TABLE_HANDLER
    {
        ULONG ProviderSignature;
        BOOLEAN Register;
        PFNFTH FirmwareTableHandler;
        PVOID DriverObject;
    } SYSTEM_FIRMWARE_TABLE_HANDLER, * PSYSTEM_FIRMWARE_TABLE_HANDLER;
#endif

    // private
    typedef struct _SYSTEM_MEMORY_LIST_INFORMATION
    {
        ULONG_PTR ZeroPageCount;
        ULONG_PTR FreePageCount;
        ULONG_PTR ModifiedPageCount;
        ULONG_PTR ModifiedNoWritePageCount;
        ULONG_PTR BadPageCount;
        ULONG_PTR PageCountByPriority[8];
        ULONG_PTR RepurposedPagesByPriority[8];
        ULONG_PTR ModifiedPageCountPageFile;
    } SYSTEM_MEMORY_LIST_INFORMATION, * PSYSTEM_MEMORY_LIST_INFORMATION;

    // private
    typedef enum _SYSTEM_MEMORY_LIST_COMMAND
    {
        MemoryCaptureAccessedBits,
        MemoryCaptureAndResetAccessedBits,
        MemoryEmptyWorkingSets,
        MemoryFlushModifiedList,
        MemoryPurgeStandbyList,
        MemoryPurgeLowPriorityStandbyList,
        MemoryCommandMax
    } SYSTEM_MEMORY_LIST_COMMAND;

    // private
    typedef struct _SYSTEM_THREAD_CID_PRIORITY_INFORMATION
    {
        CLIENT_ID ClientId;
        KPRIORITY Priority;
    } SYSTEM_THREAD_CID_PRIORITY_INFORMATION, * PSYSTEM_THREAD_CID_PRIORITY_INFORMATION;

    // private
    typedef struct _SYSTEM_PROCESSOR_IDLE_CYCLE_TIME_INFORMATION
    {
        ULONGLONG CycleTime;
    } SYSTEM_PROCESSOR_IDLE_CYCLE_TIME_INFORMATION, * PSYSTEM_PROCESSOR_IDLE_CYCLE_TIME_INFORMATION;

    // private
    typedef struct _SYSTEM_VERIFIER_ISSUE
    {
        ULONGLONG IssueType;
        PVOID Address;
        ULONGLONG Parameters[2];
    } SYSTEM_VERIFIER_ISSUE, * PSYSTEM_VERIFIER_ISSUE;

    // private
    typedef struct _SYSTEM_VERIFIER_CANCELLATION_INFORMATION
    {
        ULONG CancelProbability;
        ULONG CancelThreshold;
        ULONG CompletionThreshold;
        ULONG CancellationVerifierDisabled;
        ULONG AvailableIssues;
        SYSTEM_VERIFIER_ISSUE Issues[128];
    } SYSTEM_VERIFIER_CANCELLATION_INFORMATION, * PSYSTEM_VERIFIER_CANCELLATION_INFORMATION;

    // private
    typedef struct _SYSTEM_REF_TRACE_INFORMATION
    {
        BOOLEAN TraceEnable;
        BOOLEAN TracePermanent;
        UNICODE_STRING TraceProcessName;
        UNICODE_STRING TracePoolTags;
    } SYSTEM_REF_TRACE_INFORMATION, * PSYSTEM_REF_TRACE_INFORMATION;

    // private
    typedef struct _SYSTEM_SPECIAL_POOL_INFORMATION
    {
        ULONG PoolTag;
        ULONG Flags;
    } SYSTEM_SPECIAL_POOL_INFORMATION, * PSYSTEM_SPECIAL_POOL_INFORMATION;

    // private
    typedef struct _SYSTEM_PROCESS_ID_INFORMATION
    {
        HANDLE ProcessId;
        UNICODE_STRING ImageName;
    } SYSTEM_PROCESS_ID_INFORMATION, * PSYSTEM_PROCESS_ID_INFORMATION;

    // private
    typedef struct _SYSTEM_HYPERVISOR_QUERY_INFORMATION
    {
        BOOLEAN HypervisorConnected;
        BOOLEAN HypervisorDebuggingEnabled;
        BOOLEAN HypervisorPresent;
        BOOLEAN Spare0[5];
        ULONGLONG EnabledEnlightenments;
    } SYSTEM_HYPERVISOR_QUERY_INFORMATION, * PSYSTEM_HYPERVISOR_QUERY_INFORMATION;

    // private
    typedef struct _SYSTEM_BOOT_ENVIRONMENT_INFORMATION
    {
        GUID BootIdentifier;
        FIRMWARE_TYPE FirmwareType;
        union
        {
            ULONGLONG BootFlags;
            struct
            {
                ULONGLONG DbgMenuOsSelection : 1; // REDSTONE4
                ULONGLONG DbgHiberBoot : 1;
                ULONGLONG DbgSoftBoot : 1;
                ULONGLONG DbgMeasuredLaunch : 1;
                ULONGLONG DbgMeasuredLaunchCapable : 1; // 19H1
                ULONGLONG DbgSystemHiveReplace : 1;
                ULONGLONG DbgMeasuredLaunchSmmProtections : 1;
                ULONGLONG DbgMeasuredLaunchSmmLevel : 7; // 20H1
            };
        };
    } SYSTEM_BOOT_ENVIRONMENT_INFORMATION, * PSYSTEM_BOOT_ENVIRONMENT_INFORMATION;

    // private
    typedef struct _SYSTEM_IMAGE_FILE_EXECUTION_OPTIONS_INFORMATION
    {
        ULONG FlagsToEnable;
        ULONG FlagsToDisable;
    } SYSTEM_IMAGE_FILE_EXECUTION_OPTIONS_INFORMATION, * PSYSTEM_IMAGE_FILE_EXECUTION_OPTIONS_INFORMATION;

    // private
    typedef enum _COVERAGE_REQUEST_CODES
    {
        CoverageAllModules = 0,
        CoverageSearchByHash = 1,
        CoverageSearchByName = 2
    } COVERAGE_REQUEST_CODES;

    // private
    typedef struct _COVERAGE_MODULE_REQUEST
    {
        COVERAGE_REQUEST_CODES RequestType;
        union
        {
            UCHAR MD5Hash[16];
            UNICODE_STRING ModuleName;
        } SearchInfo;
    } COVERAGE_MODULE_REQUEST, * PCOVERAGE_MODULE_REQUEST;

    // private
    typedef struct _COVERAGE_MODULE_INFO
    {
        ULONG ModuleInfoSize;
        ULONG IsBinaryLoaded;
        UNICODE_STRING ModulePathName;
        ULONG CoverageSectionSize;
        UCHAR CoverageSection[1];
    } COVERAGE_MODULE_INFO, * PCOVERAGE_MODULE_INFO;

    // private
    typedef struct _COVERAGE_MODULES
    {
        ULONG ListAndReset;
        ULONG NumberOfModules;
        COVERAGE_MODULE_REQUEST ModuleRequestInfo;
        COVERAGE_MODULE_INFO Modules[1];
    } COVERAGE_MODULES, * PCOVERAGE_MODULES;

    // private
    typedef struct _SYSTEM_PREFETCH_PATCH_INFORMATION
    {
        ULONG PrefetchPatchCount;
    } SYSTEM_PREFETCH_PATCH_INFORMATION, * PSYSTEM_PREFETCH_PATCH_INFORMATION;

    // private
    typedef struct _SYSTEM_VERIFIER_FAULTS_INFORMATION
    {
        ULONG Probability;
        ULONG MaxProbability;
        UNICODE_STRING PoolTags;
        UNICODE_STRING Applications;
    } SYSTEM_VERIFIER_FAULTS_INFORMATION, * PSYSTEM_VERIFIER_FAULTS_INFORMATION;

    // private
    typedef struct _SYSTEM_VERIFIER_INFORMATION_EX
    {
        ULONG VerifyMode;
        ULONG OptionChanges;
        UNICODE_STRING PreviousBucketName;
        ULONG IrpCancelTimeoutMsec;
        ULONG VerifierExtensionEnabled;
#ifdef _WIN64
        ULONG Reserved[1];
#else
        ULONG Reserved[3];
#endif
    } SYSTEM_VERIFIER_INFORMATION_EX, * PSYSTEM_VERIFIER_INFORMATION_EX;

    // private
    typedef struct _SYSTEM_SYSTEM_PARTITION_INFORMATION
    {
        UNICODE_STRING SystemPartition;
    } SYSTEM_SYSTEM_PARTITION_INFORMATION, * PSYSTEM_SYSTEM_PARTITION_INFORMATION;

    // private
    typedef struct _SYSTEM_SYSTEM_DISK_INFORMATION
    {
        UNICODE_STRING SystemDisk;
    } SYSTEM_SYSTEM_DISK_INFORMATION, * PSYSTEM_SYSTEM_DISK_INFORMATION;

    // private
    typedef struct _SYSTEM_NUMA_PROXIMITY_MAP
    {
        ULONG NodeProximityId;
        USHORT NodeNumber;
    } SYSTEM_NUMA_PROXIMITY_MAP, * PSYSTEM_NUMA_PROXIMITY_MAP;

    // private (Windows 8.1 and above)
    typedef struct _SYSTEM_PROCESSOR_PERFORMANCE_HITCOUNT
    {
        ULONGLONG Hits;
        UCHAR PercentFrequency;
    } SYSTEM_PROCESSOR_PERFORMANCE_HITCOUNT, * PSYSTEM_PROCESSOR_PERFORMANCE_HITCOUNT;

    // private (Windows 7 and Windows 8)
    typedef struct _SYSTEM_PROCESSOR_PERFORMANCE_HITCOUNT_WIN8
    {
        ULONG Hits;
        UCHAR PercentFrequency;
    } SYSTEM_PROCESSOR_PERFORMANCE_HITCOUNT_WIN8, * PSYSTEM_PROCESSOR_PERFORMANCE_HITCOUNT_WIN8;

    // private
    typedef struct _SYSTEM_PROCESSOR_PERFORMANCE_STATE_DISTRIBUTION
    {
        ULONG ProcessorNumber;
        ULONG StateCount;
        _Field_size_(StateCount) SYSTEM_PROCESSOR_PERFORMANCE_HITCOUNT States[1];
    } SYSTEM_PROCESSOR_PERFORMANCE_STATE_DISTRIBUTION, * PSYSTEM_PROCESSOR_PERFORMANCE_STATE_DISTRIBUTION;

    // private
    typedef struct _SYSTEM_PROCESSOR_PERFORMANCE_DISTRIBUTION
    {
        ULONG ProcessorCount;
        ULONG Offsets[1];
    } SYSTEM_PROCESSOR_PERFORMANCE_DISTRIBUTION, * PSYSTEM_PROCESSOR_PERFORMANCE_DISTRIBUTION;

#define CODEINTEGRITY_OPTION_ENABLED 0x01
#define CODEINTEGRITY_OPTION_TESTSIGN 0x02
#define CODEINTEGRITY_OPTION_UMCI_ENABLED 0x04
#define CODEINTEGRITY_OPTION_UMCI_AUDITMODE_ENABLED 0x08
#define CODEINTEGRITY_OPTION_UMCI_EXCLUSIONPATHS_ENABLED 0x10
#define CODEINTEGRITY_OPTION_TEST_BUILD 0x20
#define CODEINTEGRITY_OPTION_PREPRODUCTION_BUILD 0x40
#define CODEINTEGRITY_OPTION_DEBUGMODE_ENABLED 0x80
#define CODEINTEGRITY_OPTION_FLIGHT_BUILD 0x100
#define CODEINTEGRITY_OPTION_FLIGHTING_ENABLED 0x200
#define CODEINTEGRITY_OPTION_HVCI_KMCI_ENABLED 0x400
#define CODEINTEGRITY_OPTION_HVCI_KMCI_AUDITMODE_ENABLED 0x800
#define CODEINTEGRITY_OPTION_HVCI_KMCI_STRICTMODE_ENABLED 0x1000
#define CODEINTEGRITY_OPTION_HVCI_IUM_ENABLED 0x2000
#define CODEINTEGRITY_OPTION_WHQL_ENFORCEMENT_ENABLED 0x4000
#define CODEINTEGRITY_OPTION_WHQL_AUDITMODE_ENABLED 0x8000

    // private
    typedef struct _SYSTEM_CODEINTEGRITY_INFORMATION
    {
        ULONG Length;
        ULONG CodeIntegrityOptions;
    } SYSTEM_CODEINTEGRITY_INFORMATION, * PSYSTEM_CODEINTEGRITY_INFORMATION;

    // private
    typedef struct _SYSTEM_PROCESSOR_MICROCODE_UPDATE_INFORMATION
    {
        ULONG Operation;
    } SYSTEM_PROCESSOR_MICROCODE_UPDATE_INFORMATION, * PSYSTEM_PROCESSOR_MICROCODE_UPDATE_INFORMATION;

    // private
    typedef enum _SYSTEM_VA_TYPE
    {
        SystemVaTypeAll,
        SystemVaTypeNonPagedPool,
        SystemVaTypePagedPool,
        SystemVaTypeSystemCache,
        SystemVaTypeSystemPtes,
        SystemVaTypeSessionSpace,
        SystemVaTypeMax
    } SYSTEM_VA_TYPE, * PSYSTEM_VA_TYPE;

    // private
    typedef struct _SYSTEM_VA_LIST_INFORMATION
    {
        SIZE_T VirtualSize;
        SIZE_T VirtualPeak;
        SIZE_T VirtualLimit;
        SIZE_T AllocationFailures;
    } SYSTEM_VA_LIST_INFORMATION, * PSYSTEM_VA_LIST_INFORMATION;

    // rev
    typedef enum _STORE_INFORMATION_CLASS
    {
        StorePageRequest = 1,
        StoreStatsRequest = 2, // q: SM_STATS_REQUEST // SmProcessStatsRequest
        StoreCreateRequest = 3, // s: SM_CREATE_REQUEST (requires SeProfileSingleProcessPrivilege)
        StoreDeleteRequest = 4, // s: SM_DELETE_REQUEST (requires SeProfileSingleProcessPrivilege)
        StoreListRequest = 5, // q: SM_STORE_LIST_REQUEST / SM_STORE_LIST_REQUEST_EX // SmProcessListRequest
        Available1 = 6,
        StoreEmptyRequest = 7,
        CacheListRequest = 8, // q: SMC_CACHE_LIST_REQUEST // SmcProcessListRequest
        CacheCreateRequest = 9, // s: SMC_CACHE_CREATE_REQUEST (requires SeProfileSingleProcessPrivilege)
        CacheDeleteRequest = 10, // s: SMC_CACHE_DELETE_REQUEST (requires SeProfileSingleProcessPrivilege)
        CacheStoreCreateRequest = 11, // s: SMC_STORE_CREATE_REQUEST (requires SeProfileSingleProcessPrivilege)
        CacheStoreDeleteRequest = 12, // s: SMC_STORE_DELETE_REQUEST (requires SeProfileSingleProcessPrivilege)
        CacheStatsRequest = 13, // q: SMC_CACHE_STATS_REQUEST // SmcProcessStatsRequest
        Available2 = 14,
        RegistrationRequest = 15, // q: SM_REGISTRATION_REQUEST (requires SeProfileSingleProcessPrivilege) // SmProcessRegistrationRequest
        GlobalCacheStatsRequest = 16,
        StoreResizeRequest = 17, // s: SM_STORE_RESIZE_REQUEST (requires SeProfileSingleProcessPrivilege)
        CacheStoreResizeRequest = 18, // s: SMC_STORE_RESIZE_REQUEST (requires SeProfileSingleProcessPrivilege)
        SmConfigRequest = 19, // s: SM_CONFIG_REQUEST (requires SeProfileSingleProcessPrivilege)
        StoreHighMemoryPriorityRequest = 20, // s: SM_STORE_HIGH_MEM_PRIORITY_REQUEST (requires SeProfileSingleProcessPrivilege)
        SystemStoreTrimRequest = 21, // s: SM_SYSTEM_STORE_TRIM_REQUEST (requires SeProfileSingleProcessPrivilege)
        MemCompressionInfoRequest = 22,  // q: SM_MEM_COMPRESSION_INFO_REQUEST // SmProcessCompressionInfoRequest
        ProcessStoreInfoRequest = 23, // SmProcessProcessStoreInfoRequest
        StoreInformationMax
    } STORE_INFORMATION_CLASS;

    // rev
#define SYSTEM_STORE_INFORMATION_VERSION 1

// rev
    typedef struct _SYSTEM_STORE_INFORMATION
    {
        _In_ ULONG Version;
        _In_ STORE_INFORMATION_CLASS StoreInformationClass;
        _Inout_ PVOID Data;
        _Inout_ ULONG Length;
    } SYSTEM_STORE_INFORMATION, * PSYSTEM_STORE_INFORMATION;

#define SYSTEM_STORE_STATS_INFORMATION_VERSION 2

    typedef enum _ST_STATS_LEVEL
    {
        StStatsLevelBasic = 0,
        StStatsLevelIoStats = 1,
        StStatsLevelRegionSpace = 2, // requires SeProfileSingleProcessPrivilege
        StStatsLevelSpaceBitmap = 3, // requires SeProfileSingleProcessPrivilege
        StStatsLevelMax = 4
    } ST_STATS_LEVEL;

    typedef struct _SM_STATS_REQUEST
    {
        ULONG Version : 8; // SYSTEM_STORE_STATS_INFORMATION_VERSION
        ULONG DetailLevel : 8; // ST_STATS_LEVEL
        ULONG StoreId : 16;
        ULONG BufferSize;
        PVOID Buffer; // PST_STATS
    } SM_STATS_REQUEST, * PSM_STATS_REQUEST;

    typedef struct _ST_DATA_MGR_STATS
    {
        ULONG RegionCount;
        ULONG PagesStored;
        ULONG UniquePagesStored;
        ULONG LazyCleanupRegionCount;
        struct {
            ULONG RegionsInUse;
            ULONG SpaceUsed;
        } Space[8];
    } ST_DATA_MGR_STATS, * PST_DATA_MGR_STATS;

    typedef struct _ST_IO_STATS_PERIOD
    {
        ULONG PageCounts[5];
    } ST_IO_STATS_PERIOD, * PST_IO_STATS_PERIOD;

    typedef struct _ST_IO_STATS
    {
        ULONG PeriodCount;
        ST_IO_STATS_PERIOD Periods[64];
    } ST_IO_STATS, * PST_IO_STATS;

    typedef struct _ST_READ_LATENCY_BUCKET
    {
        ULONG LatencyUs;
        ULONG Count;
    } ST_READ_LATENCY_BUCKET, * PST_READ_LATENCY_BUCKET;

    typedef struct _ST_READ_LATENCY_STATS
    {
        ST_READ_LATENCY_BUCKET Buckets[8];
    } ST_READ_LATENCY_STATS, * PST_READ_LATENCY_STATS;

    // rev
    typedef struct _ST_STATS_REGION_INFO
    {
        USHORT SpaceUsed;
        UCHAR Priority;
        UCHAR Spare;
    } ST_STATS_REGION_INFO, * PST_STATS_REGION_INFO;

    // rev
    typedef struct _ST_STATS_SPACE_BITMAP
    {
        SIZE_T CompressedBytes;
        ULONG BytesPerBit;
        UCHAR StoreBitmap[1];
    } ST_STATS_SPACE_BITMAP, * PST_STATS_SPACE_BITMAP;

    // rev
    typedef struct _ST_STATS
    {
        ULONG Version : 8;
        ULONG Level : 4;
        ULONG StoreType : 4;
        ULONG NoDuplication : 1;
        ULONG NoCompression : 1;
        ULONG EncryptionStrength : 12;
        ULONG VirtualRegions : 1;
        ULONG Spare0 : 1;
        ULONG Size;
        USHORT CompressionFormat;
        USHORT Spare;

        struct
        {
            ULONG RegionSize;
            ULONG RegionCount;
            ULONG RegionCountMax;
            ULONG Granularity;
            ST_DATA_MGR_STATS UserData;
            ST_DATA_MGR_STATS Metadata;
        } Basic;

        struct
        {
            ST_IO_STATS IoStats;
            ST_READ_LATENCY_STATS ReadLatencyStats;
        } Io;

        // ST_STATS_REGION_INFO[RegionCountMax]
        // ST_STATS_SPACE_BITMAP
    } ST_STATS, * PST_STATS;

#define SYSTEM_STORE_CREATE_INFORMATION_VERSION 6

    typedef enum _SM_STORE_TYPE
    {
        StoreTypeInMemory = 0,
        StoreTypeFile = 1,
        StoreTypeMax = 2
    } SM_STORE_TYPE;

    typedef struct _SM_STORE_BASIC_PARAMS
    {
        union
        {
            struct
            {
                ULONG StoreType : 8; // SM_STORE_TYPE
                ULONG NoDuplication : 1;
                ULONG FailNoCompression : 1;
                ULONG NoCompression : 1;
                ULONG NoEncryption : 1;
                ULONG NoEvictOnAdd : 1;
                ULONG PerformsFileIo : 1;
                ULONG VdlNotSet : 1;
                ULONG UseIntermediateAddBuffer : 1;
                ULONG CompressNoHuff : 1;
                ULONG LockActiveRegions : 1;
                ULONG VirtualRegions : 1;
                ULONG Spare : 13;
            };
            ULONG StoreFlags;
        };
        ULONG Granularity;
        ULONG RegionSize;
        ULONG RegionCountMax;
    } SM_STORE_BASIC_PARAMS, * PSM_STORE_BASIC_PARAMS;

    typedef struct _SMKM_REGION_EXTENT
    {
        ULONG RegionCount;
        SIZE_T ByteOffset;
    } SMKM_REGION_EXTENT, * PSMKM_REGION_EXTENT;

    typedef struct _FILE_OBJECT* PFILE_OBJECT;
    typedef struct _DEVICE_OBJECT* PDEVICE_OBJECT;
    typedef struct _IRP* PIRP;
    typedef struct _RTL_BITMAP* PRTL_BITMAP;

    typedef struct _SMKM_FILE_INFO
    {
        HANDLE FileHandle;
        PFILE_OBJECT FileObject;
        PFILE_OBJECT VolumeFileObject;
        PDEVICE_OBJECT VolumeDeviceObject;
        HANDLE VolumePnpHandle;
        PIRP UsageNotificationIrp;
        PSMKM_REGION_EXTENT Extents;
        ULONG ExtentCount;
    } SMKM_FILE_INFO, * PSMKM_FILE_INFO;

    typedef struct _SM_STORE_CACHE_BACKED_PARAMS
    {
        ULONG SectorSize;
        PCHAR EncryptionKey;
        ULONG EncryptionKeySize;
        PSMKM_FILE_INFO FileInfo;
        PVOID EtaContext;
        PRTL_BITMAP StoreRegionBitmap;
    } SM_STORE_CACHE_BACKED_PARAMS, * PSM_STORE_CACHE_BACKED_PARAMS;

    typedef struct _SM_STORE_PARAMETERS
    {
        SM_STORE_BASIC_PARAMS Store;
        ULONG Priority;
        ULONG Flags;
        SM_STORE_CACHE_BACKED_PARAMS CacheBacked;
    } SM_STORE_PARAMETERS, * PSM_STORE_PARAMETERS;

    typedef struct _SM_CREATE_REQUEST
    {
        ULONG Version : 8; // SYSTEM_STORE_CREATE_INFORMATION_VERSION
        ULONG AcquireReference : 1;
        ULONG KeyedStore : 1;
        ULONG Spare : 22;
        SM_STORE_PARAMETERS Params;
        ULONG StoreId;
    } SM_CREATE_REQUEST, * PSM_CREATE_REQUEST;

#define SYSTEM_STORE_DELETE_INFORMATION_VERSION 1

    typedef struct _SM_DELETE_REQUEST
    {
        ULONG Version : 8; // SYSTEM_STORE_DELETE_INFORMATION_VERSION
        ULONG Spare : 24;
        ULONG StoreId;
    } SM_DELETE_REQUEST, * PSM_DELETE_REQUEST;

#define SYSTEM_STORE_LIST_INFORMATION_VERSION 2

    typedef struct _SM_STORE_LIST_REQUEST
    {
        ULONG Version : 8; // SYSTEM_STORE_LIST_INFORMATION_VERSION
        ULONG StoreCount : 8; // = 0
        ULONG ExtendedRequest : 1; // SM_STORE_LIST_REQUEST_EX if set
        ULONG Spare : 15;
        ULONG StoreId[32];
    } SM_STORE_LIST_REQUEST, * PSM_STORE_LIST_REQUEST;

    typedef struct _SM_STORE_LIST_REQUEST_EX
    {
        SM_STORE_LIST_REQUEST Request;
        WCHAR NameBuffer[32][64];
    } SM_STORE_LIST_REQUEST_EX, * PSM_STORE_LIST_REQUEST_EX;

#define SYSTEM_CACHE_LIST_INFORMATION_VERSION 2

    typedef struct _SMC_CACHE_LIST_REQUEST
    {
        ULONG Version : 8; // SYSTEM_CACHE_LIST_INFORMATION_VERSION
        ULONG CacheCount : 8; // = 0
        ULONG Spare : 16;
        ULONG CacheId[16];
    } SMC_CACHE_LIST_REQUEST, * PSMC_CACHE_LIST_REQUEST;

#define SYSTEM_CACHE_CREATE_INFORMATION_VERSION 3

    typedef struct _SMC_CACHE_PARAMETERS
    {
        SIZE_T CacheFileSize;
        ULONG StoreAlignment;
        ULONG PerformsFileIo : 1;
        ULONG VdlNotSet : 1;
        ULONG Spare : 30;
        ULONG CacheFlags;
        ULONG Priority;
    } SMC_CACHE_PARAMETERS, * PSMC_CACHE_PARAMETERS;

    typedef struct _SMC_CACHE_CREATE_PARAMETERS
    {
        SMC_CACHE_PARAMETERS CacheParameters;
        WCHAR TemplateFilePath[512];
    } SMC_CACHE_CREATE_PARAMETERS, * PSMC_CACHE_CREATE_PARAMETERS;

    typedef struct _SMC_CACHE_CREATE_REQUEST
    {
        ULONG Version : 8; // SYSTEM_CACHE_CREATE_INFORMATION_VERSION
        ULONG Spare : 24;
        ULONG CacheId;
        SMC_CACHE_CREATE_PARAMETERS CacheCreateParams;
    } SMC_CACHE_CREATE_REQUEST, * PSMC_CACHE_CREATE_REQUEST;

#define SYSTEM_CACHE_DELETE_INFORMATION_VERSION 1

    typedef struct _SMC_CACHE_DELETE_REQUEST
    {
        ULONG Version : 8; // SYSTEM_CACHE_DELETE_INFORMATION_VERSION
        ULONG Spare : 24;
        ULONG CacheId;
    } SMC_CACHE_DELETE_REQUEST, * PSMC_CACHE_DELETE_REQUEST;

#define SYSTEM_CACHE_STORE_CREATE_INFORMATION_VERSION 2

    typedef enum _SM_STORE_MANAGER_TYPE
    {
        SmStoreManagerTypePhysical = 0,
        SmStoreManagerTypeVirtual = 1,
        SmStoreManagerTypeMax = 2
    } SM_STORE_MANAGER_TYPE;

    typedef struct _SMC_STORE_CREATE_REQUEST
    {
        ULONG Version : 8; // SYSTEM_CACHE_STORE_CREATE_INFORMATION_VERSION
        ULONG Spare : 24;
        SM_STORE_BASIC_PARAMS StoreParams;
        ULONG CacheId;
        SM_STORE_MANAGER_TYPE StoreManagerType;
        ULONG StoreId;
    } SMC_STORE_CREATE_REQUEST, * PSMC_STORE_CREATE_REQUEST;

#define SYSTEM_CACHE_STORE_DELETE_INFORMATION_VERSION 1

    typedef struct _SMC_STORE_DELETE_REQUEST
    {
        ULONG Version : 8; // SYSTEM_CACHE_STORE_DELETE_INFORMATION_VERSION
        ULONG Spare : 24;
        ULONG CacheId;
        SM_STORE_MANAGER_TYPE StoreManagerType;
        ULONG StoreId;
    } SMC_STORE_DELETE_REQUEST, * PSMC_STORE_DELETE_REQUEST;

#define SYSTEM_CACHE_STATS_INFORMATION_VERSION 3

    typedef struct _SMC_CACHE_STATS
    {
        SIZE_T TotalFileSize;
        ULONG StoreCount;
        ULONG RegionCount;
        ULONG RegionSizeBytes;
        ULONG FileCount : 6;
        ULONG PerformsFileIo : 1;
        ULONG Spare : 25;
        ULONG StoreIds[16];
        ULONG PhysicalStoreBitmap;
        ULONG Priority;
        WCHAR TemplateFilePath[512];
    } SMC_CACHE_STATS, * PSMC_CACHE_STATS;

    typedef struct _SMC_CACHE_STATS_REQUEST
    {
        ULONG Version : 8; // SYSTEM_CACHE_STATS_INFORMATION_VERSION
        ULONG NoFilePath : 1;
        ULONG Spare : 23;
        ULONG CacheId;
        SMC_CACHE_STATS CacheStats;
    } SMC_CACHE_STATS_REQUEST, * PSMC_CACHE_STATS_REQUEST;

#define SYSTEM_STORE_REGISTRATION_INFORMATION_VERSION 2

    typedef struct _SM_REGISTRATION_INFO
    {
        HANDLE CachesUpdatedEvent;
    } SM_REGISTRATION_INFO, * PSM_REGISTRATION_INFO;

    typedef struct _SM_REGISTRATION_REQUEST
    {
        ULONG Version : 8; // SYSTEM_STORE_REGISTRATION_INFORMATION_VERSION
        ULONG Spare : 24;
        SM_REGISTRATION_INFO RegInfo;
    } SM_REGISTRATION_REQUEST, * PSM_REGISTRATION_REQUEST;

    typedef struct _RTL_BITMAP* PRTL_BITMAP;

#define SYSTEM_STORE_RESIZE_INFORMATION_VERSION 6

    typedef struct _SM_STORE_RESIZE_REQUEST
    {
        ULONG Version : 8; // SYSTEM_STORE_RESIZE_INFORMATION_VERSION
        ULONG AddRegions : 1;
        ULONG Spare : 23;
        ULONG StoreId;
        ULONG NumberOfRegions;
        PRTL_BITMAP RegionBitmap;
    } SM_STORE_RESIZE_REQUEST, * PSM_STORE_RESIZE_REQUEST;

#define SYSTEM_CACHE_STORE_RESIZE_INFORMATION_VERSION 1

    typedef struct _SMC_STORE_RESIZE_REQUEST
    {
        ULONG Version : 8; // SYSTEM_CACHE_STORE_RESIZE_INFORMATION_VERSION
        ULONG AddRegions : 1;
        ULONG Spare : 23;
        ULONG CacheId;
        ULONG StoreId;
        SM_STORE_MANAGER_TYPE StoreManagerType;
        ULONG RegionCount;
    } SMC_STORE_RESIZE_REQUEST, * PSMC_STORE_RESIZE_REQUEST;

#define SYSTEM_STORE_CONFIG_INFORMATION_VERSION 4

    typedef enum _SM_CONFIG_TYPE
    {
        SmConfigDirtyPageCompression = 0,
        SmConfigAsyncInswap = 1,
        SmConfigPrefetchSeekThreshold = 2,
        SmConfigTypeMax = 3
    } SM_CONFIG_TYPE;

    typedef struct _SM_CONFIG_REQUEST
    {
        ULONG Version : 8; // SYSTEM_STORE_CONFIG_INFORMATION_VERSION
        ULONG Spare : 16;
        ULONG ConfigType : 8; // SM_CONFIG_TYPE
        ULONG ConfigValue;
    } SM_CONFIG_REQUEST, * PSM_CONFIG_REQUEST;

#define SYSTEM_STORE_HIGH_MEM_PRIORITY_INFORMATION_VERSION 1

    // rev
    typedef struct _SM_STORE_HIGH_MEM_PRIORITY_REQUEST
    {
        ULONG Version : 8; // SYSTEM_STORE_HIGH_MEM_PRIORITY_INFORMATION_VERSION
        ULONG SetHighMemoryPriority : 1;
        ULONG Spare : 23;
        HANDLE ProcessHandle;
    } SM_STORE_HIGH_MEM_PRIORITY_REQUEST, * PSM_STORE_HIGH_MEM_PRIORITY_REQUEST;

#define SYSTEM_STORE_TRIM_INFORMATION_VERSION 1

    // rev
    typedef struct _SM_SYSTEM_STORE_TRIM_REQUEST
    {
        ULONG Version : 8; // SYSTEM_STORE_TRIM_INFORMATION_VERSION
        ULONG Spare : 24;
        SIZE_T PagesToTrim; // ULONG?
    } SM_SYSTEM_STORE_TRIM_REQUEST, * PSM_SYSTEM_STORE_TRIM_REQUEST;

    // rev
#define SYSTEM_STORE_COMPRESSION_INFORMATION_VERSION 3

// rev
    typedef struct _SM_MEM_COMPRESSION_INFO_REQUEST
    {
        ULONG Version : 8; // SYSTEM_STORE_COMPRESSION_INFORMATION_VERSION
        ULONG Spare : 24;
        ULONG CompressionPid;
        ULONG WorkingSetSize;
        SIZE_T TotalDataCompressed;
        SIZE_T TotalCompressedSize;
        SIZE_T TotalUniqueDataCompressed;
    } SM_MEM_COMPRESSION_INFO_REQUEST, * PSM_MEM_COMPRESSION_INFO_REQUEST;

    // private
    typedef struct _SYSTEM_REGISTRY_APPEND_STRING_PARAMETERS
    {
        HANDLE KeyHandle;
        PUNICODE_STRING ValueNamePointer;
        PULONG RequiredLengthPointer;
        PUCHAR Buffer;
        ULONG BufferLength;
        ULONG Type;
        PUCHAR AppendBuffer;
        ULONG AppendBufferLength;
        BOOLEAN CreateIfDoesntExist;
        BOOLEAN TruncateExistingValue;
    } SYSTEM_REGISTRY_APPEND_STRING_PARAMETERS, * PSYSTEM_REGISTRY_APPEND_STRING_PARAMETERS;

    // msdn
    typedef struct _SYSTEM_VHD_BOOT_INFORMATION
    {
        BOOLEAN OsDiskIsVhd;
        ULONG OsVhdFilePathOffset;
        WCHAR OsVhdParentVolume[1];
    } SYSTEM_VHD_BOOT_INFORMATION, * PSYSTEM_VHD_BOOT_INFORMATION;

    // private
    typedef struct _PS_CPU_QUOTA_QUERY_ENTRY
    {
        ULONG SessionId;
        ULONG Weight;
    } PS_CPU_QUOTA_QUERY_ENTRY, * PPS_CPU_QUOTA_QUERY_ENTRY;

    // private
    typedef struct _PS_CPU_QUOTA_QUERY_INFORMATION
    {
        ULONG SessionCount;
        PS_CPU_QUOTA_QUERY_ENTRY SessionInformation[1];
    } PS_CPU_QUOTA_QUERY_INFORMATION, * PPS_CPU_QUOTA_QUERY_INFORMATION;

    // private
    typedef struct _SYSTEM_ERROR_PORT_TIMEOUTS
    {
        ULONG StartTimeout;
        ULONG CommTimeout;
    } SYSTEM_ERROR_PORT_TIMEOUTS, * PSYSTEM_ERROR_PORT_TIMEOUTS;

    // private
    typedef struct _SYSTEM_LOW_PRIORITY_IO_INFORMATION
    {
        ULONG LowPriReadOperations;
        ULONG LowPriWriteOperations;
        ULONG KernelBumpedToNormalOperations;
        ULONG LowPriPagingReadOperations;
        ULONG KernelPagingReadsBumpedToNormal;
        ULONG LowPriPagingWriteOperations;
        ULONG KernelPagingWritesBumpedToNormal;
        ULONG BoostedIrpCount;
        ULONG BoostedPagingIrpCount;
        ULONG BlanketBoostCount;
    } SYSTEM_LOW_PRIORITY_IO_INFORMATION, * PSYSTEM_LOW_PRIORITY_IO_INFORMATION;

    // symbols
    typedef enum _TPM_BOOT_ENTROPY_RESULT_CODE
    {
        TpmBootEntropyStructureUninitialized,
        TpmBootEntropyDisabledByPolicy,
        TpmBootEntropyNoTpmFound,
        TpmBootEntropyTpmError,
        TpmBootEntropySuccess
    } TPM_BOOT_ENTROPY_RESULT_CODE;

    // Contents of KeLoaderBlock->Extension->TpmBootEntropyResult (TPM_BOOT_ENTROPY_LDR_RESULT).
    // EntropyData is truncated to 40 bytes.

    // private
    typedef struct _TPM_BOOT_ENTROPY_NT_RESULT
    {
        ULONGLONG Policy;
        TPM_BOOT_ENTROPY_RESULT_CODE ResultCode;
        NTSTATUS ResultStatus;
        ULONGLONG Time;
        ULONG EntropyLength;
        UCHAR EntropyData[40];
    } TPM_BOOT_ENTROPY_NT_RESULT, * PTPM_BOOT_ENTROPY_NT_RESULT;

    // private
    typedef struct _SYSTEM_VERIFIER_COUNTERS_INFORMATION
    {
        SYSTEM_VERIFIER_INFORMATION Legacy;
        ULONG RaiseIrqls;
        ULONG AcquireSpinLocks;
        ULONG SynchronizeExecutions;
        ULONG AllocationsWithNoTag;
        ULONG AllocationsFailed;
        ULONG AllocationsFailedDeliberately;
        SIZE_T LockedBytes;
        SIZE_T PeakLockedBytes;
        SIZE_T MappedLockedBytes;
        SIZE_T PeakMappedLockedBytes;
        SIZE_T MappedIoSpaceBytes;
        SIZE_T PeakMappedIoSpaceBytes;
        SIZE_T PagesForMdlBytes;
        SIZE_T PeakPagesForMdlBytes;
        SIZE_T ContiguousMemoryBytes;
        SIZE_T PeakContiguousMemoryBytes;
        ULONG ExecutePoolTypes; // REDSTONE2
        ULONG ExecutePageProtections;
        ULONG ExecutePageMappings;
        ULONG ExecuteWriteSections;
        ULONG SectionAlignmentFailures;
        ULONG UnsupportedRelocs;
        ULONG IATInExecutableSection;
    } SYSTEM_VERIFIER_COUNTERS_INFORMATION, * PSYSTEM_VERIFIER_COUNTERS_INFORMATION;

    // private
    typedef struct _SYSTEM_ACPI_AUDIT_INFORMATION
    {
        ULONG RsdpCount;
        ULONG SameRsdt : 1;
        ULONG SlicPresent : 1;
        ULONG SlicDifferent : 1;
    } SYSTEM_ACPI_AUDIT_INFORMATION, * PSYSTEM_ACPI_AUDIT_INFORMATION;

    // private
    typedef struct _SYSTEM_BASIC_PERFORMANCE_INFORMATION
    {
        SIZE_T AvailablePages;
        SIZE_T CommittedPages;
        SIZE_T CommitLimit;
        SIZE_T PeakCommitment;
    } SYSTEM_BASIC_PERFORMANCE_INFORMATION, * PSYSTEM_BASIC_PERFORMANCE_INFORMATION;

    // begin_msdn

    typedef struct _QUERY_PERFORMANCE_COUNTER_FLAGS
    {
        union
        {
            struct
            {
                ULONG KernelTransition : 1;
                ULONG Reserved : 31;
            };
            ULONG ul;
        };
    } QUERY_PERFORMANCE_COUNTER_FLAGS;

    typedef struct _SYSTEM_QUERY_PERFORMANCE_COUNTER_INFORMATION
    {
        ULONG Version;
        QUERY_PERFORMANCE_COUNTER_FLAGS Flags;
        QUERY_PERFORMANCE_COUNTER_FLAGS ValidFlags;
    } SYSTEM_QUERY_PERFORMANCE_COUNTER_INFORMATION, * PSYSTEM_QUERY_PERFORMANCE_COUNTER_INFORMATION;

    // end_msdn

    // private
    typedef enum _SYSTEM_PIXEL_FORMAT
    {
        SystemPixelFormatUnknown,
        SystemPixelFormatR8G8B8,
        SystemPixelFormatR8G8B8X8,
        SystemPixelFormatB8G8R8,
        SystemPixelFormatB8G8R8X8
    } SYSTEM_PIXEL_FORMAT;

    // private
    typedef struct _SYSTEM_BOOT_GRAPHICS_INFORMATION
    {
        LARGE_INTEGER FrameBuffer;
        ULONG Width;
        ULONG Height;
        ULONG PixelStride;
        ULONG Flags;
        SYSTEM_PIXEL_FORMAT Format;
        ULONG DisplayRotation;
    } SYSTEM_BOOT_GRAPHICS_INFORMATION, * PSYSTEM_BOOT_GRAPHICS_INFORMATION;

    // private
    typedef struct _MEMORY_SCRUB_INFORMATION
    {
        HANDLE Handle;
        ULONG PagesScrubbed;
    } MEMORY_SCRUB_INFORMATION, * PMEMORY_SCRUB_INFORMATION;

    // private
    typedef struct _PEBS_DS_SAVE_AREA32
    {
        ULONG BtsBufferBase;
        ULONG BtsIndex;
        ULONG BtsAbsoluteMaximum;
        ULONG BtsInterruptThreshold;
        ULONG PebsBufferBase;
        ULONG PebsIndex;
        ULONG PebsAbsoluteMaximum;
        ULONG PebsInterruptThreshold;
        ULONG PebsGpCounterReset[8];
        ULONG PebsFixedCounterReset[4];
    } PEBS_DS_SAVE_AREA32, * PPEBS_DS_SAVE_AREA32;

    // private
    typedef struct _PEBS_DS_SAVE_AREA64
    {
        ULONGLONG BtsBufferBase;
        ULONGLONG BtsIndex;
        ULONGLONG BtsAbsoluteMaximum;
        ULONGLONG BtsInterruptThreshold;
        ULONGLONG PebsBufferBase;
        ULONGLONG PebsIndex;
        ULONGLONG PebsAbsoluteMaximum;
        ULONGLONG PebsInterruptThreshold;
        ULONGLONG PebsGpCounterReset[8];
        ULONGLONG PebsFixedCounterReset[4];
    } PEBS_DS_SAVE_AREA64, * PPEBS_DS_SAVE_AREA64;

    // private
    typedef union _PEBS_DS_SAVE_AREA
    {
        PEBS_DS_SAVE_AREA32 As32Bit;
        PEBS_DS_SAVE_AREA64 As64Bit;
    } PEBS_DS_SAVE_AREA, * PPEBS_DS_SAVE_AREA;

    // private
    typedef struct _PROCESSOR_PROFILE_CONTROL_AREA
    {
        PEBS_DS_SAVE_AREA PebsDsSaveArea;
    } PROCESSOR_PROFILE_CONTROL_AREA, * PPROCESSOR_PROFILE_CONTROL_AREA;

    // private
    typedef struct _SYSTEM_PROCESSOR_PROFILE_CONTROL_AREA
    {
        PROCESSOR_PROFILE_CONTROL_AREA ProcessorProfileControlArea;
        BOOLEAN Allocate;
    } SYSTEM_PROCESSOR_PROFILE_CONTROL_AREA, * PSYSTEM_PROCESSOR_PROFILE_CONTROL_AREA;

    // private
    typedef struct _MEMORY_COMBINE_INFORMATION
    {
        HANDLE Handle;
        ULONG_PTR PagesCombined;
    } MEMORY_COMBINE_INFORMATION, * PMEMORY_COMBINE_INFORMATION;

    // rev
#define MEMORY_COMBINE_FLAGS_COMMON_PAGES_ONLY 0x4

// private
    typedef struct _MEMORY_COMBINE_INFORMATION_EX
    {
        HANDLE Handle;
        ULONG_PTR PagesCombined;
        ULONG Flags;
    } MEMORY_COMBINE_INFORMATION_EX, * PMEMORY_COMBINE_INFORMATION_EX;

    // private
    typedef struct _MEMORY_COMBINE_INFORMATION_EX2
    {
        HANDLE Handle;
        ULONG_PTR PagesCombined;
        ULONG Flags;
        HANDLE ProcessHandle;
    } MEMORY_COMBINE_INFORMATION_EX2, * PMEMORY_COMBINE_INFORMATION_EX2;

    // private
    typedef struct _SYSTEM_ENTROPY_TIMING_INFORMATION
    {
        VOID(NTAPI* EntropyRoutine)(PVOID, ULONG);
        VOID(NTAPI* InitializationRoutine)(PVOID, ULONG, PVOID);
        PVOID InitializationContext;
    } SYSTEM_ENTROPY_TIMING_INFORMATION, * PSYSTEM_ENTROPY_TIMING_INFORMATION;

    // private
    typedef struct _SYSTEM_CONSOLE_INFORMATION
    {
        ULONG DriverLoaded : 1;
        ULONG Spare : 31;
    } SYSTEM_CONSOLE_INFORMATION, * PSYSTEM_CONSOLE_INFORMATION;

    // private
    typedef struct _SYSTEM_PLATFORM_BINARY_INFORMATION
    {
        ULONG64 PhysicalAddress;
        PVOID HandoffBuffer;
        PVOID CommandLineBuffer;
        ULONG HandoffBufferSize;
        ULONG CommandLineBufferSize;
    } SYSTEM_PLATFORM_BINARY_INFORMATION, * PSYSTEM_PLATFORM_BINARY_INFORMATION;

    // private
    typedef struct _SYSTEM_POLICY_INFORMATION
    {
        PVOID InputData;
        PVOID OutputData;
        ULONG InputDataSize;
        ULONG OutputDataSize;
        ULONG Version;
    } SYSTEM_POLICY_INFORMATION, * PSYSTEM_POLICY_INFORMATION;

    // private
    typedef struct _SYSTEM_HYPERVISOR_PROCESSOR_COUNT_INFORMATION
    {
        ULONG NumberOfLogicalProcessors;
        ULONG NumberOfCores;
    } SYSTEM_HYPERVISOR_PROCESSOR_COUNT_INFORMATION, * PSYSTEM_HYPERVISOR_PROCESSOR_COUNT_INFORMATION;

    // private
    typedef struct _SYSTEM_DEVICE_DATA_INFORMATION
    {
        UNICODE_STRING DeviceId;
        UNICODE_STRING DataName;
        ULONG DataType;
        ULONG DataBufferLength;
        PVOID DataBuffer;
    } SYSTEM_DEVICE_DATA_INFORMATION, * PSYSTEM_DEVICE_DATA_INFORMATION;

    // private
    typedef struct _PHYSICAL_CHANNEL_RUN
    {
        ULONG NodeNumber;
        ULONG ChannelNumber;
        ULONGLONG BasePage;
        ULONGLONG PageCount;
        ULONG Flags;
    } PHYSICAL_CHANNEL_RUN, * PPHYSICAL_CHANNEL_RUN;

    // private
    typedef struct _SYSTEM_MEMORY_TOPOLOGY_INFORMATION
    {
        ULONGLONG NumberOfRuns;
        ULONG NumberOfNodes;
        ULONG NumberOfChannels;
        PHYSICAL_CHANNEL_RUN Run[1];
    } SYSTEM_MEMORY_TOPOLOGY_INFORMATION, * PSYSTEM_MEMORY_TOPOLOGY_INFORMATION;

    // private
    typedef struct _SYSTEM_MEMORY_CHANNEL_INFORMATION
    {
        ULONG ChannelNumber;
        ULONG ChannelHeatIndex;
        ULONGLONG TotalPageCount;
        ULONGLONG ZeroPageCount;
        ULONGLONG FreePageCount;
        ULONGLONG StandbyPageCount;
    } SYSTEM_MEMORY_CHANNEL_INFORMATION, * PSYSTEM_MEMORY_CHANNEL_INFORMATION;

    // private
    typedef struct _SYSTEM_BOOT_LOGO_INFORMATION
    {
        ULONG Flags;
        ULONG BitmapOffset;
    } SYSTEM_BOOT_LOGO_INFORMATION, * PSYSTEM_BOOT_LOGO_INFORMATION;

    // private
    typedef struct _SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION_EX
    {
        LARGE_INTEGER IdleTime;
        LARGE_INTEGER KernelTime;
        LARGE_INTEGER UserTime;
        LARGE_INTEGER DpcTime;
        LARGE_INTEGER InterruptTime;
        ULONG InterruptCount;
        ULONG Spare0;
        LARGE_INTEGER AvailableTime;
        LARGE_INTEGER Spare1;
        LARGE_INTEGER Spare2;
    } SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION_EX, * PSYSTEM_PROCESSOR_PERFORMANCE_INFORMATION_EX;

    // private
    typedef struct _SYSTEM_SECUREBOOT_POLICY_INFORMATION
    {
        GUID PolicyPublisher;
        ULONG PolicyVersion;
        ULONG PolicyOptions;
    } SYSTEM_SECUREBOOT_POLICY_INFORMATION, * PSYSTEM_SECUREBOOT_POLICY_INFORMATION;

    // private
    typedef struct _SYSTEM_PAGEFILE_INFORMATION_EX
    {
        union // HACK union declaration for convenience (dmex)
        {
            SYSTEM_PAGEFILE_INFORMATION Info;
            struct
            {
                ULONG NextEntryOffset;
                ULONG TotalSize;
                ULONG TotalInUse;
                ULONG PeakUsage;
                UNICODE_STRING PageFileName;
            };
        };

        ULONG MinimumSize;
        ULONG MaximumSize;
    } SYSTEM_PAGEFILE_INFORMATION_EX, * PSYSTEM_PAGEFILE_INFORMATION_EX;

    // private
    typedef struct _SYSTEM_SECUREBOOT_INFORMATION
    {
        BOOLEAN SecureBootEnabled;
        BOOLEAN SecureBootCapable;
    } SYSTEM_SECUREBOOT_INFORMATION, * PSYSTEM_SECUREBOOT_INFORMATION;

    // private
    typedef struct _PROCESS_DISK_COUNTERS
    {
        ULONGLONG BytesRead;
        ULONGLONG BytesWritten;
        ULONGLONG ReadOperationCount;
        ULONGLONG WriteOperationCount;
        ULONGLONG FlushOperationCount;
    } PROCESS_DISK_COUNTERS, * PPROCESS_DISK_COUNTERS;

    // private
    typedef union _ENERGY_STATE_DURATION
    {
        ULONGLONG Value;
        struct
        {
            ULONG LastChangeTime;
            ULONG Duration : 31;
            ULONG IsInState : 1;
        };
    } ENERGY_STATE_DURATION, * PENERGY_STATE_DURATION;

    typedef struct _PROCESS_ENERGY_VALUES
    {
        ULONGLONG Cycles[4][2];
        ULONGLONG DiskEnergy;
        ULONGLONG NetworkTailEnergy;
        ULONGLONG MBBTailEnergy;
        ULONGLONG NetworkTxRxBytes;
        ULONGLONG MBBTxRxBytes;
        union
        {
            ENERGY_STATE_DURATION Durations[3];
            struct
            {
                ENERGY_STATE_DURATION ForegroundDuration;
                ENERGY_STATE_DURATION DesktopVisibleDuration;
                ENERGY_STATE_DURATION PSMForegroundDuration;
            };
        };
        ULONG CompositionRendered;
        ULONG CompositionDirtyGenerated;
        ULONG CompositionDirtyPropagated;
        ULONG Reserved1;
        ULONGLONG AttributedCycles[4][2];
        ULONGLONG WorkOnBehalfCycles[4][2];
    } PROCESS_ENERGY_VALUES, * PPROCESS_ENERGY_VALUES;

    typedef union _TIMELINE_BITMAP
    {
        ULONGLONG Value;
        struct
        {
            ULONG EndTime;
            ULONG Bitmap;
        };
    } TIMELINE_BITMAP, * PTIMELINE_BITMAP;

    typedef struct _PROCESS_ENERGY_VALUES_EXTENSION
    {
        union
        {
            TIMELINE_BITMAP Timelines[14]; // 9 for REDSTONE2, 14 for REDSTONE3/4/5
            struct
            {
                TIMELINE_BITMAP CpuTimeline;
                TIMELINE_BITMAP DiskTimeline;
                TIMELINE_BITMAP NetworkTimeline;
                TIMELINE_BITMAP MBBTimeline;
                TIMELINE_BITMAP ForegroundTimeline;
                TIMELINE_BITMAP DesktopVisibleTimeline;
                TIMELINE_BITMAP CompositionRenderedTimeline;
                TIMELINE_BITMAP CompositionDirtyGeneratedTimeline;
                TIMELINE_BITMAP CompositionDirtyPropagatedTimeline;
                TIMELINE_BITMAP InputTimeline; // REDSTONE3
                TIMELINE_BITMAP AudioInTimeline;
                TIMELINE_BITMAP AudioOutTimeline;
                TIMELINE_BITMAP DisplayRequiredTimeline;
                TIMELINE_BITMAP KeyboardInputTimeline;
            };
        };

        union // REDSTONE3
        {
            ENERGY_STATE_DURATION Durations[5];
            struct
            {
                ENERGY_STATE_DURATION InputDuration;
                ENERGY_STATE_DURATION AudioInDuration;
                ENERGY_STATE_DURATION AudioOutDuration;
                ENERGY_STATE_DURATION DisplayRequiredDuration;
                ENERGY_STATE_DURATION PSMBackgroundDuration;
            };
        };

        ULONG KeyboardInput;
        ULONG MouseInput;
    } PROCESS_ENERGY_VALUES_EXTENSION, * PPROCESS_ENERGY_VALUES_EXTENSION;

    typedef struct _PROCESS_EXTENDED_ENERGY_VALUES
    {
        PROCESS_ENERGY_VALUES Base;
        PROCESS_ENERGY_VALUES_EXTENSION Extension;
    } PROCESS_EXTENDED_ENERGY_VALUES, * PPROCESS_EXTENDED_ENERGY_VALUES;

    // private
    typedef enum _SYSTEM_PROCESS_CLASSIFICATION
    {
        SystemProcessClassificationNormal,
        SystemProcessClassificationSystem,
        SystemProcessClassificationSecureSystem,
        SystemProcessClassificationMemCompression,
        SystemProcessClassificationRegistry, // REDSTONE4
        SystemProcessClassificationMaximum
    } SYSTEM_PROCESS_CLASSIFICATION;

    // private
    typedef struct _SYSTEM_PROCESS_INFORMATION_EXTENSION
    {
        PROCESS_DISK_COUNTERS DiskCounters;
        ULONGLONG ContextSwitches;
        union
        {
            ULONG Flags;
            struct
            {
                ULONG HasStrongId : 1;
                ULONG Classification : 4; // SYSTEM_PROCESS_CLASSIFICATION
                ULONG BackgroundActivityModerated : 1;
                ULONG Spare : 26;
            };
        };
        ULONG UserSidOffset;
        ULONG PackageFullNameOffset; // since THRESHOLD
        PROCESS_ENERGY_VALUES EnergyValues; // since THRESHOLD
        ULONG AppIdOffset; // since THRESHOLD
        SIZE_T SharedCommitCharge; // since THRESHOLD2
        ULONG JobObjectId; // since REDSTONE
        ULONG SpareUlong; // since REDSTONE
        ULONGLONG ProcessSequenceNumber;
    } SYSTEM_PROCESS_INFORMATION_EXTENSION, * PSYSTEM_PROCESS_INFORMATION_EXTENSION;

    // private
    typedef struct _SYSTEM_PORTABLE_WORKSPACE_EFI_LAUNCHER_INFORMATION
    {
        BOOLEAN EfiLauncherEnabled;
    } SYSTEM_PORTABLE_WORKSPACE_EFI_LAUNCHER_INFORMATION, * PSYSTEM_PORTABLE_WORKSPACE_EFI_LAUNCHER_INFORMATION;

    // private
    typedef struct _SYSTEM_KERNEL_DEBUGGER_INFORMATION_EX
    {
        BOOLEAN DebuggerAllowed;
        BOOLEAN DebuggerEnabled;
        BOOLEAN DebuggerPresent;
    } SYSTEM_KERNEL_DEBUGGER_INFORMATION_EX, * PSYSTEM_KERNEL_DEBUGGER_INFORMATION_EX;

    // private
    typedef struct _SYSTEM_ELAM_CERTIFICATE_INFORMATION
    {
        HANDLE ElamDriverFile;
    } SYSTEM_ELAM_CERTIFICATE_INFORMATION, * PSYSTEM_ELAM_CERTIFICATE_INFORMATION;

    // private
    typedef struct _OFFLINE_CRASHDUMP_CONFIGURATION_TABLE_V2
    {
        ULONG Version;
        ULONG AbnormalResetOccurred;
        ULONG OfflineMemoryDumpCapable;
        LARGE_INTEGER ResetDataAddress;
        ULONG ResetDataSize;
    } OFFLINE_CRASHDUMP_CONFIGURATION_TABLE_V2, * POFFLINE_CRASHDUMP_CONFIGURATION_TABLE_V2;

    // private
    typedef struct _OFFLINE_CRASHDUMP_CONFIGURATION_TABLE_V1
    {
        ULONG Version;
        ULONG AbnormalResetOccurred;
        ULONG OfflineMemoryDumpCapable;
    } OFFLINE_CRASHDUMP_CONFIGURATION_TABLE_V1, * POFFLINE_CRASHDUMP_CONFIGURATION_TABLE_V1;

    // private
    typedef struct _SYSTEM_PROCESSOR_FEATURES_INFORMATION
    {
        ULONGLONG ProcessorFeatureBits;
        ULONGLONG Reserved[3];
    } SYSTEM_PROCESSOR_FEATURES_INFORMATION, * PSYSTEM_PROCESSOR_FEATURES_INFORMATION;

    // EDID v1.4 standard data format
    typedef struct _SYSTEM_EDID_INFORMATION
    {
        UCHAR Edid[128];
    } SYSTEM_EDID_INFORMATION, * PSYSTEM_EDID_INFORMATION;

    // private
    typedef struct _SYSTEM_MANUFACTURING_INFORMATION
    {
        ULONG Options;
        UNICODE_STRING ProfileName;
    } SYSTEM_MANUFACTURING_INFORMATION, * PSYSTEM_MANUFACTURING_INFORMATION;

    // private
    typedef struct _SYSTEM_ENERGY_ESTIMATION_CONFIG_INFORMATION
    {
        BOOLEAN Enabled;
    } SYSTEM_ENERGY_ESTIMATION_CONFIG_INFORMATION, * PSYSTEM_ENERGY_ESTIMATION_CONFIG_INFORMATION;

    // private
    typedef struct _HV_DETAILS
    {
        ULONG Data[4];
    } HV_DETAILS, * PHV_DETAILS;

    // private
    typedef struct _SYSTEM_HYPERVISOR_DETAIL_INFORMATION
    {
        HV_DETAILS HvVendorAndMaxFunction;
        HV_DETAILS HypervisorInterface;
        HV_DETAILS HypervisorVersion;
        HV_DETAILS HvFeatures;
        HV_DETAILS HwFeatures;
        HV_DETAILS EnlightenmentInfo;
        HV_DETAILS ImplementationLimits;
    } SYSTEM_HYPERVISOR_DETAIL_INFORMATION, * PSYSTEM_HYPERVISOR_DETAIL_INFORMATION;

    // private
    typedef struct _SYSTEM_PROCESSOR_CYCLE_STATS_INFORMATION
    {
        ULONGLONG Cycles[4][2];
    } SYSTEM_PROCESSOR_CYCLE_STATS_INFORMATION, * PSYSTEM_PROCESSOR_CYCLE_STATS_INFORMATION;

    // private
    typedef struct _SYSTEM_TPM_INFORMATION
    {
        ULONG Flags;
    } SYSTEM_TPM_INFORMATION, * PSYSTEM_TPM_INFORMATION;

    // private
    typedef struct _SYSTEM_VSM_PROTECTION_INFORMATION
    {
        BOOLEAN DmaProtectionsAvailable;
        BOOLEAN DmaProtectionsInUse;
        BOOLEAN HardwareMbecAvailable; // REDSTONE4 (CVE-2018-3639)
        BOOLEAN ApicVirtualizationAvailable; // 20H1
    } SYSTEM_VSM_PROTECTION_INFORMATION, * PSYSTEM_VSM_PROTECTION_INFORMATION;

    // private
    typedef struct _SYSTEM_KERNEL_DEBUGGER_FLAGS
    {
        BOOLEAN KernelDebuggerIgnoreUmExceptions;
    } SYSTEM_KERNEL_DEBUGGER_FLAGS, * PSYSTEM_KERNEL_DEBUGGER_FLAGS;

    // SYSTEM_CODEINTEGRITYPOLICY_INFORMATION Options
#define CODEINTEGRITYPOLICY_OPTION_ENABLED 0x01
#define CODEINTEGRITYPOLICY_OPTION_AUDIT 0x02
#define CODEINTEGRITYPOLICY_OPTION_REQUIRE_WHQL 0x04
#define CODEINTEGRITYPOLICY_OPTION_DISABLED_FLIGHTSIGNING 0x08
#define CODEINTEGRITYPOLICY_OPTION_ENABLED_UMCI 0x10
#define CODEINTEGRITYPOLICY_OPTION_ENABLED_UPDATE_POLICY_NOREBOOT 0x20
#define CODEINTEGRITYPOLICY_OPTION_ENABLED_SECURE_SETTING_POLICY 0x40
#define CODEINTEGRITYPOLICY_OPTION_ENABLED_UNSIGNED_SYSTEMINTEGRITY_POLICY 0x80
#define CODEINTEGRITYPOLICY_OPTION_DYNAMIC_CODE_POLICY_ENABLED 0x100
#define CODEINTEGRITYPOLICY_OPTION_RELOAD_POLICY_NO_REBOOT 0x10000000 // NtSetSystemInformation reloads SiPolicy.p7b
#define CODEINTEGRITYPOLICY_OPTION_CONDITIONAL_LOCKDOWN 0x20000000
#define CODEINTEGRITYPOLICY_OPTION_NOLOCKDOWN 0x40000000
#define CODEINTEGRITYPOLICY_OPTION_LOCKDOWN 0x80000000

// SYSTEM_CODEINTEGRITYPOLICY_INFORMATION HVCIOptions
#define CODEINTEGRITYPOLICY_HVCIOPTION_ENABLED 0x01
#define CODEINTEGRITYPOLICY_HVCIOPTION_STRICT 0x02
#define CODEINTEGRITYPOLICY_HVCIOPTION_DEBUG 0x04

// private
    typedef struct _SYSTEM_CODEINTEGRITYPOLICY_INFORMATION
    {
        ULONG Options;
        ULONG HVCIOptions;
        ULONGLONG Version;
        GUID PolicyGuid;
    } SYSTEM_CODEINTEGRITYPOLICY_INFORMATION, * PSYSTEM_CODEINTEGRITYPOLICY_INFORMATION;

    // private
    typedef struct _SYSTEM_ISOLATED_USER_MODE_INFORMATION
    {
        BOOLEAN SecureKernelRunning : 1;
        BOOLEAN HvciEnabled : 1;
        BOOLEAN HvciStrictMode : 1;
        BOOLEAN DebugEnabled : 1;
        BOOLEAN FirmwarePageProtection : 1;
        BOOLEAN EncryptionKeyAvailable : 1;
        BOOLEAN SpareFlags : 2;
        BOOLEAN TrustletRunning : 1;
        BOOLEAN HvciDisableAllowed : 1;
        BOOLEAN SpareFlags2 : 6;
        BOOLEAN Spare0[6];
        ULONGLONG Spare1;
    } SYSTEM_ISOLATED_USER_MODE_INFORMATION, * PSYSTEM_ISOLATED_USER_MODE_INFORMATION;

    // private
    typedef struct _SYSTEM_SINGLE_MODULE_INFORMATION
    {
        PVOID TargetModuleAddress;
        RTL_PROCESS_MODULE_INFORMATION_EX ExInfo;
    } SYSTEM_SINGLE_MODULE_INFORMATION, * PSYSTEM_SINGLE_MODULE_INFORMATION;

    // private
    typedef struct _SYSTEM_INTERRUPT_CPU_SET_INFORMATION
    {
        ULONG Gsiv;
        USHORT Group;
        ULONGLONG CpuSets;
    } SYSTEM_INTERRUPT_CPU_SET_INFORMATION, * PSYSTEM_INTERRUPT_CPU_SET_INFORMATION;

    // private
    typedef struct _SYSTEM_SECUREBOOT_POLICY_FULL_INFORMATION
    {
        SYSTEM_SECUREBOOT_POLICY_INFORMATION PolicyInformation;
        ULONG PolicySize;
        UCHAR Policy[1];
    } SYSTEM_SECUREBOOT_POLICY_FULL_INFORMATION, * PSYSTEM_SECUREBOOT_POLICY_FULL_INFORMATION;

    // private
    typedef struct _SYSTEM_ROOT_SILO_INFORMATION
    {
        ULONG NumberOfSilos;
        ULONG SiloIdList[1];
    } SYSTEM_ROOT_SILO_INFORMATION, * PSYSTEM_ROOT_SILO_INFORMATION;

    // private
    typedef struct _SYSTEM_CPU_SET_TAG_INFORMATION
    {
        ULONGLONG Tag;
        ULONGLONG CpuSets[1];
    } SYSTEM_CPU_SET_TAG_INFORMATION, * PSYSTEM_CPU_SET_TAG_INFORMATION;

    // private
    typedef struct _SYSTEM_SECURE_KERNEL_HYPERGUARD_PROFILE_INFORMATION
    {
        ULONG ExtentCount;
        ULONG ValidStructureSize;
        ULONG NextExtentIndex;
        ULONG ExtentRestart;
        ULONG CycleCount;
        ULONG TimeoutCount;
        ULONGLONG CycleTime;
        ULONGLONG CycleTimeMax;
        ULONGLONG ExtentTime;
        ULONG ExtentTimeIndex;
        ULONG ExtentTimeMaxIndex;
        ULONGLONG ExtentTimeMax;
        ULONGLONG HyperFlushTimeMax;
        ULONGLONG TranslateVaTimeMax;
        ULONGLONG DebugExemptionCount;
        ULONGLONG TbHitCount;
        ULONGLONG TbMissCount;
        ULONGLONG VinaPendingYield;
        ULONGLONG HashCycles;
        ULONG HistogramOffset;
        ULONG HistogramBuckets;
        ULONG HistogramShift;
        ULONG Reserved1;
        ULONGLONG PageNotPresentCount;
    } SYSTEM_SECURE_KERNEL_HYPERGUARD_PROFILE_INFORMATION, * PSYSTEM_SECURE_KERNEL_HYPERGUARD_PROFILE_INFORMATION;

    // private
    typedef struct _SYSTEM_SECUREBOOT_PLATFORM_MANIFEST_INFORMATION
    {
        ULONG PlatformManifestSize;
        UCHAR PlatformManifest[1];
    } SYSTEM_SECUREBOOT_PLATFORM_MANIFEST_INFORMATION, * PSYSTEM_SECUREBOOT_PLATFORM_MANIFEST_INFORMATION;

    // private
    typedef struct _SYSTEM_INTERRUPT_STEERING_INFORMATION_INPUT
    {
        ULONG Gsiv;
        UCHAR ControllerInterrupt;
        UCHAR EdgeInterrupt;
        UCHAR IsPrimaryInterrupt;
        GROUP_AFFINITY TargetAffinity;
    } SYSTEM_INTERRUPT_STEERING_INFORMATION_INPUT, * PSYSTEM_INTERRUPT_STEERING_INFORMATION_INPUT;

    // private
    typedef union _SYSTEM_INTERRUPT_STEERING_INFORMATION_OUTPUT
    {
        ULONG AsULONG;
        struct
        {
            ULONG Enabled : 1;
            ULONG Reserved : 31;
        };
    } SYSTEM_INTERRUPT_STEERING_INFORMATION_OUTPUT, * PSYSTEM_INTERRUPT_STEERING_INFORMATION_OUTPUT;

#if !defined(NTDDI_WIN10_FE) || (NTDDI_VERSION < NTDDI_WIN10_FE)
    // private
    typedef struct _SYSTEM_SUPPORTED_PROCESSOR_ARCHITECTURES_INFORMATION
    {
        ULONG Machine : 16;
        ULONG KernelMode : 1;
        ULONG UserMode : 1;
        ULONG Native : 1;
        ULONG Process : 1;
        ULONG WoW64Container : 1;
        ULONG ReservedZero0 : 11;
    } SYSTEM_SUPPORTED_PROCESSOR_ARCHITECTURES_INFORMATION, * PSYSTEM_SUPPORTED_PROCESSOR_ARCHITECTURES_INFORMATION;
#endif

    // private
    typedef struct _SYSTEM_MEMORY_USAGE_INFORMATION
    {
        ULONGLONG TotalPhysicalBytes;
        ULONGLONG AvailableBytes;
        LONGLONG ResidentAvailableBytes;
        ULONGLONG CommittedBytes;
        ULONGLONG SharedCommittedBytes;
        ULONGLONG CommitLimitBytes;
        ULONGLONG PeakCommitmentBytes;
    } SYSTEM_MEMORY_USAGE_INFORMATION, * PSYSTEM_MEMORY_USAGE_INFORMATION;

    // private
    typedef struct _SYSTEM_CODEINTEGRITY_CERTIFICATE_INFORMATION
    {
        HANDLE ImageFile;
        ULONG Type; // REDSTONE4
    } SYSTEM_CODEINTEGRITY_CERTIFICATE_INFORMATION, * PSYSTEM_CODEINTEGRITY_CERTIFICATE_INFORMATION;

    // private
    typedef struct _SYSTEM_PHYSICAL_MEMORY_INFORMATION
    {
        ULONGLONG TotalPhysicalBytes;
        ULONGLONG LowestPhysicalAddress;
        ULONGLONG HighestPhysicalAddress;
    } SYSTEM_PHYSICAL_MEMORY_INFORMATION, * PSYSTEM_PHYSICAL_MEMORY_INFORMATION;

    // private
    typedef enum _SYSTEM_ACTIVITY_MODERATION_STATE
    {
        SystemActivityModerationStateSystemManaged,
        SystemActivityModerationStateUserManagedAllowThrottling,
        SystemActivityModerationStateUserManagedDisableThrottling,
        MaxSystemActivityModerationState
    } SYSTEM_ACTIVITY_MODERATION_STATE;

    // private - REDSTONE2
    typedef struct _SYSTEM_ACTIVITY_MODERATION_EXE_STATE // REDSTONE3: Renamed SYSTEM_ACTIVITY_MODERATION_INFO
    {
        UNICODE_STRING ExePathNt;
        SYSTEM_ACTIVITY_MODERATION_STATE ModerationState;
    } SYSTEM_ACTIVITY_MODERATION_EXE_STATE, * PSYSTEM_ACTIVITY_MODERATION_EXE_STATE;

    typedef enum _SYSTEM_ACTIVITY_MODERATION_APP_TYPE
    {
        SystemActivityModerationAppTypeClassic,
        SystemActivityModerationAppTypePackaged,
        MaxSystemActivityModerationAppType
    } SYSTEM_ACTIVITY_MODERATION_APP_TYPE;

    // private - REDSTONE3
    typedef struct _SYSTEM_ACTIVITY_MODERATION_INFO
    {
        UNICODE_STRING Identifier;
        SYSTEM_ACTIVITY_MODERATION_STATE ModerationState;
        SYSTEM_ACTIVITY_MODERATION_APP_TYPE AppType;
    } SYSTEM_ACTIVITY_MODERATION_INFO, * PSYSTEM_ACTIVITY_MODERATION_INFO;

    // private
    typedef struct _SYSTEM_ACTIVITY_MODERATION_USER_SETTINGS
    {
        HANDLE UserKeyHandle;
    } SYSTEM_ACTIVITY_MODERATION_USER_SETTINGS, * PSYSTEM_ACTIVITY_MODERATION_USER_SETTINGS;

    // private
    typedef struct _SYSTEM_CODEINTEGRITY_UNLOCK_INFORMATION
    {
        union
        {
            ULONG Flags;
            struct
            {
                ULONG Locked : 1;
                ULONG UnlockApplied : 1; // Unlockable field removed 19H1
                ULONG UnlockIdValid : 1;
                ULONG Reserved : 29;
            };
        };
        UCHAR UnlockId[32]; // REDSTONE4
    } SYSTEM_CODEINTEGRITY_UNLOCK_INFORMATION, * PSYSTEM_CODEINTEGRITY_UNLOCK_INFORMATION;

    // private
    typedef struct _SYSTEM_FLUSH_INFORMATION
    {
        ULONG SupportedFlushMethods;
        ULONG ProcessorCacheFlushSize;
        ULONGLONG SystemFlushCapabilities;
        ULONGLONG Reserved[2];
    } SYSTEM_FLUSH_INFORMATION, * PSYSTEM_FLUSH_INFORMATION;

    // private
    typedef struct _SYSTEM_WRITE_CONSTRAINT_INFORMATION
    {
        ULONG WriteConstraintPolicy;
        ULONG Reserved;
    } SYSTEM_WRITE_CONSTRAINT_INFORMATION, * PSYSTEM_WRITE_CONSTRAINT_INFORMATION;

    // private
    typedef struct _SYSTEM_KERNEL_VA_SHADOW_INFORMATION
    {
        union
        {
            ULONG KvaShadowFlags;
            struct
            {
                ULONG KvaShadowEnabled : 1;
                ULONG KvaShadowUserGlobal : 1;
                ULONG KvaShadowPcid : 1;
                ULONG KvaShadowInvpcid : 1;
                ULONG KvaShadowRequired : 1; // REDSTONE4
                ULONG KvaShadowRequiredAvailable : 1;
                ULONG InvalidPteBit : 6;
                ULONG L1DataCacheFlushSupported : 1;
                ULONG L1TerminalFaultMitigationPresent : 1;
                ULONG Reserved : 18;
            };
        };
    } SYSTEM_KERNEL_VA_SHADOW_INFORMATION, * PSYSTEM_KERNEL_VA_SHADOW_INFORMATION;

    // private
    typedef struct _SYSTEM_CODEINTEGRITYVERIFICATION_INFORMATION
    {
        HANDLE FileHandle;
        ULONG ImageSize;
        PVOID Image;
    } SYSTEM_CODEINTEGRITYVERIFICATION_INFORMATION, * PSYSTEM_CODEINTEGRITYVERIFICATION_INFORMATION;

    // private
    typedef struct _SYSTEM_HYPERVISOR_SHARED_PAGE_INFORMATION
    {
        PVOID HypervisorSharedUserVa;
    } SYSTEM_HYPERVISOR_SHARED_PAGE_INFORMATION, * PSYSTEM_HYPERVISOR_SHARED_PAGE_INFORMATION;

    // private
    typedef struct _SYSTEM_FIRMWARE_PARTITION_INFORMATION
    {
        UNICODE_STRING FirmwarePartition;
    } SYSTEM_FIRMWARE_PARTITION_INFORMATION, * PSYSTEM_FIRMWARE_PARTITION_INFORMATION;

    // private
    typedef struct _SYSTEM_SPECULATION_CONTROL_INFORMATION
    {
        union
        {
            ULONG Flags;
            struct
            {
                ULONG BpbEnabled : 1;
                ULONG BpbDisabledSystemPolicy : 1;
                ULONG BpbDisabledNoHardwareSupport : 1;
                ULONG SpecCtrlEnumerated : 1;
                ULONG SpecCmdEnumerated : 1;
                ULONG IbrsPresent : 1;
                ULONG StibpPresent : 1;
                ULONG SmepPresent : 1;
                ULONG SpeculativeStoreBypassDisableAvailable : 1; // REDSTONE4 (CVE-2018-3639)
                ULONG SpeculativeStoreBypassDisableSupported : 1;
                ULONG SpeculativeStoreBypassDisabledSystemWide : 1;
                ULONG SpeculativeStoreBypassDisabledKernel : 1;
                ULONG SpeculativeStoreBypassDisableRequired : 1;
                ULONG BpbDisabledKernelToUser : 1;
                ULONG SpecCtrlRetpolineEnabled : 1;
                ULONG SpecCtrlImportOptimizationEnabled : 1;
                ULONG EnhancedIbrs : 1; // since 19H1
                ULONG HvL1tfStatusAvailable : 1;
                ULONG HvL1tfProcessorNotAffected : 1;
                ULONG HvL1tfMigitationEnabled : 1;
                ULONG HvL1tfMigitationNotEnabled_Hardware : 1;
                ULONG HvL1tfMigitationNotEnabled_LoadOption : 1;
                ULONG HvL1tfMigitationNotEnabled_CoreScheduler : 1;
                ULONG EnhancedIbrsReported : 1;
                ULONG MdsHardwareProtected : 1; // since 19H2
                ULONG MbClearEnabled : 1;
                ULONG MbClearReported : 1;
                ULONG ReservedTaa : 4;
                ULONG Reserved : 1;
            };
        } SpeculationControlFlags;
        union
        {
            ULONG Flags; // Since KB4074629 (2023)
            struct
            {
                ULONG Reserved1 : 5;
                ULONG BhbEnabled : 1;
                ULONG BhbDisabledSystemPolicy : 1;
                ULONG BhbDisabledNoHardwareSupport : 1;
                ULONG Reserved2 : 3;
                ULONG RdclHardwareProtectedReported : 1;
                ULONG RdclHardwareProtected : 1;
                ULONG Reserved : 19;
            };
        } SpeculationControlFlags2;
    } SYSTEM_SPECULATION_CONTROL_INFORMATION, * PSYSTEM_SPECULATION_CONTROL_INFORMATION;

    // private
    typedef struct _SYSTEM_DMA_GUARD_POLICY_INFORMATION
    {
        BOOLEAN DmaGuardPolicyEnabled;
    } SYSTEM_DMA_GUARD_POLICY_INFORMATION, * PSYSTEM_DMA_GUARD_POLICY_INFORMATION;

    // private
    typedef struct _SYSTEM_ENCLAVE_LAUNCH_CONTROL_INFORMATION
    {
        UCHAR EnclaveLaunchSigner[32];
    } SYSTEM_ENCLAVE_LAUNCH_CONTROL_INFORMATION, * PSYSTEM_ENCLAVE_LAUNCH_CONTROL_INFORMATION;

    // private
    typedef struct _SYSTEM_WORKLOAD_ALLOWED_CPU_SET_INFORMATION
    {
        ULONGLONG WorkloadClass;
        ULONGLONG CpuSets[1];
    } SYSTEM_WORKLOAD_ALLOWED_CPU_SET_INFORMATION, * PSYSTEM_WORKLOAD_ALLOWED_CPU_SET_INFORMATION;

    // private
    typedef struct _SYSTEM_SECURITY_MODEL_INFORMATION
    {
        union
        {
            ULONG SecurityModelFlags;
            struct
            {
                ULONG SModeAdminlessEnabled : 1;
                ULONG AllowDeviceOwnerProtectionDowngrade : 1;
                ULONG Reserved : 30;
            };
        };
    } SYSTEM_SECURITY_MODEL_INFORMATION, * PSYSTEM_SECURITY_MODEL_INFORMATION;

    typedef struct _RTL_FEATURE_CONFIGURATION* PRTL_FEATURE_CONFIGURATION; // from ntrtl.h

    // private
    typedef struct _SYSTEM_FEATURE_CONFIGURATION_INFORMATION
    {
        ULONGLONG ChangeStamp;
        PRTL_FEATURE_CONFIGURATION Configuration;
    } SYSTEM_FEATURE_CONFIGURATION_INFORMATION, * PSYSTEM_FEATURE_CONFIGURATION_INFORMATION;

    // private
    typedef struct _SYSTEM_FEATURE_CONFIGURATION_SECTIONS_INFORMATION_ENTRY
    {
        ULONGLONG ChangeStamp;
        PVOID Section;
        ULONGLONG Size;
    } SYSTEM_FEATURE_CONFIGURATION_SECTIONS_INFORMATION_ENTRY, * PSYSTEM_FEATURE_CONFIGURATION_SECTIONS_INFORMATION_ENTRY;

    // private
    typedef struct _SYSTEM_FEATURE_CONFIGURATION_SECTIONS_INFORMATION
    {
        ULONGLONG OverallChangeStamp;
        SYSTEM_FEATURE_CONFIGURATION_SECTIONS_INFORMATION_ENTRY Descriptors[3];
    } SYSTEM_FEATURE_CONFIGURATION_SECTIONS_INFORMATION, * PSYSTEM_FEATURE_CONFIGURATION_SECTIONS_INFORMATION;

    // private
    typedef struct _RTL_FEATURE_USAGE_SUBSCRIPTION_TARGET
    {
        ULONG Data[2];
    } RTL_FEATURE_USAGE_SUBSCRIPTION_TARGET, * PRTL_FEATURE_USAGE_SUBSCRIPTION_TARGET;

    // private
    typedef struct _SYSTEM_FEATURE_USAGE_SUBSCRIPTION_DETAILS
    {
        ULONG FeatureId;
        USHORT ReportingKind;
        USHORT ReportingOptions;
        RTL_FEATURE_USAGE_SUBSCRIPTION_TARGET ReportingTarget;
    } SYSTEM_FEATURE_USAGE_SUBSCRIPTION_DETAILS, * PSYSTEM_FEATURE_USAGE_SUBSCRIPTION_DETAILS;

    // private
    typedef union _SECURE_SPECULATION_CONTROL_INFORMATION
    {
        ULONG KvaShadowSupported : 1;
        ULONG KvaShadowEnabled : 1;
        ULONG KvaShadowUserGlobal : 1;
        ULONG KvaShadowPcid : 1;
        ULONG MbClearEnabled : 1;
        ULONG L1TFMitigated : 1; // since 20H2
        ULONG BpbEnabled : 1;
        ULONG IbrsPresent : 1;
        ULONG EnhancedIbrs : 1;
        ULONG StibpPresent : 1;
        ULONG SsbdSupported : 1;
        ULONG SsbdRequired : 1;
        ULONG BpbKernelToUser : 1;
        ULONG BpbUserToKernel : 1;
        ULONG ReturnSpeculate : 1;
        ULONG BranchConfusionSafe : 1;
        ULONG Reserved : 16;
    } SECURE_SPECULATION_CONTROL_INFORMATION, * PSECURE_SPECULATION_CONTROL_INFORMATION;

    // private
    typedef struct _SYSTEM_FIRMWARE_RAMDISK_INFORMATION
    {
        ULONG Version;
        ULONG BlockSize;
        ULONG_PTR BaseAddress;
        SIZE_T Size;
    } SYSTEM_FIRMWARE_RAMDISK_INFORMATION, * PSYSTEM_FIRMWARE_RAMDISK_INFORMATION;

    // private
    typedef struct _SYSTEM_SHADOW_STACK_INFORMATION
    {
        union
        {
            ULONG Flags;
            struct
            {
                ULONG CetCapable : 1;
                ULONG UserCetAllowed : 1;
                ULONG ReservedForUserCet : 6;
                ULONG KernelCetEnabled : 1;
                ULONG KernelCetAuditModeEnabled : 1;
                ULONG ReservedForKernelCet : 6; // since Windows 10 build 21387
                ULONG Reserved : 16;
            };
        };
    } SYSTEM_SHADOW_STACK_INFORMATION, * PSYSTEM_SHADOW_STACK_INFORMATION;

    // private
    typedef union _SYSTEM_BUILD_VERSION_INFORMATION_FLAGS
    {
        ULONG Value32;
        struct
        {
            ULONG IsTopLevel : 1;
            ULONG IsChecked : 1;
        };
    } SYSTEM_BUILD_VERSION_INFORMATION_FLAGS, * PSYSTEM_BUILD_VERSION_INFORMATION_FLAGS;

    // private
    typedef struct _SYSTEM_BUILD_VERSION_INFORMATION
    {
        USHORT LayerNumber;
        USHORT LayerCount;
        ULONG OsMajorVersion;
        ULONG OsMinorVersion;
        ULONG NtBuildNumber;
        ULONG NtBuildQfe;
        UCHAR LayerName[128];
        UCHAR NtBuildBranch[128];
        UCHAR NtBuildLab[128];
        UCHAR NtBuildLabEx[128];
        UCHAR NtBuildStamp[26];
        UCHAR NtBuildArch[16];
        SYSTEM_BUILD_VERSION_INFORMATION_FLAGS Flags;
    } SYSTEM_BUILD_VERSION_INFORMATION, * PSYSTEM_BUILD_VERSION_INFORMATION;

    // private
    typedef struct _SYSTEM_POOL_LIMIT_MEM_INFO
    {
        ULONGLONG MemoryLimit;
        ULONGLONG NotificationLimit;
    } SYSTEM_POOL_LIMIT_MEM_INFO, * PSYSTEM_POOL_LIMIT_MEM_INFO;

    // private
    typedef struct _SYSTEM_POOL_LIMIT_INFO
    {
        ULONG PoolTag;
        SYSTEM_POOL_LIMIT_MEM_INFO MemLimits[2];
        WNF_STATE_NAME NotificationHandle;
    } SYSTEM_POOL_LIMIT_INFO, * PSYSTEM_POOL_LIMIT_INFO;

    // private
    typedef struct _SYSTEM_POOL_LIMIT_INFORMATION
    {
        ULONG Version;
        ULONG EntryCount;
        _Field_size_(EntryCount) SYSTEM_POOL_LIMIT_INFO LimitEntries[1];
    } SYSTEM_POOL_LIMIT_INFORMATION, * PSYSTEM_POOL_LIMIT_INFORMATION;

    // private
    //typedef struct _SYSTEM_POOL_ZEROING_INFORMATION
    //{
    //    BOOLEAN PoolZeroingSupportPresent;
    //} SYSTEM_POOL_ZEROING_INFORMATION, *PSYSTEM_POOL_ZEROING_INFORMATION;

    // private
    typedef struct _HV_MINROOT_NUMA_LPS
    {
        ULONG NodeIndex;
        ULONG_PTR Mask[16];
    } HV_MINROOT_NUMA_LPS, * PHV_MINROOT_NUMA_LPS;

    // private
    typedef struct _SYSTEM_XFG_FAILURE_INFORMATION
    {
        PVOID ReturnAddress;
        PVOID TargetAddress;
        ULONG DispatchMode;
        ULONGLONG XfgValue;
    } SYSTEM_XFG_FAILURE_INFORMATION, * PSYSTEM_XFG_FAILURE_INFORMATION;

    // private
    typedef enum _SYSTEM_IOMMU_STATE
    {
        IommuStateBlock,
        IommuStateUnblock
    } SYSTEM_IOMMU_STATE;

    // private
    typedef struct _SYSTEM_IOMMU_STATE_INFORMATION
    {
        SYSTEM_IOMMU_STATE State;
        PVOID Pdo;
    } SYSTEM_IOMMU_STATE_INFORMATION, * PSYSTEM_IOMMU_STATE_INFORMATION;

    // private
    typedef struct _SYSTEM_HYPERVISOR_MINROOT_INFORMATION
    {
        ULONG NumProc;
        ULONG RootProc;
        ULONG RootProcNumaNodesSpecified;
        USHORT RootProcNumaNodes[64];
        ULONG RootProcPerCore;
        ULONG RootProcPerNode;
        ULONG RootProcNumaNodesLpsSpecified;
        HV_MINROOT_NUMA_LPS RootProcNumaNodeLps[64];
    } SYSTEM_HYPERVISOR_MINROOT_INFORMATION, * PSYSTEM_HYPERVISOR_MINROOT_INFORMATION;

    // private
    typedef struct _SYSTEM_HYPERVISOR_BOOT_PAGES_INFORMATION
    {
        ULONG RangeCount;
        ULONG_PTR RangeArray[1];
    } SYSTEM_HYPERVISOR_BOOT_PAGES_INFORMATION, * PSYSTEM_HYPERVISOR_BOOT_PAGES_INFORMATION;

    // private
    typedef struct _SYSTEM_POINTER_AUTH_INFORMATION
    {
        union
        {
            USHORT SupportedFlags;
            struct
            {
                USHORT AddressAuthSupported : 1;
                USHORT AddressAuthQarma : 1;
                USHORT GenericAuthSupported : 1;
                USHORT GenericAuthQarma : 1;
                USHORT SupportedReserved : 12;
            };
        };
        union
        {
            USHORT EnabledFlags;
            struct
            {
                USHORT UserPerProcessIpAuthEnabled : 1;
                USHORT UserGlobalIpAuthEnabled : 1;
                USHORT UserEnabledReserved : 6;
                USHORT KernelIpAuthEnabled : 1;
                USHORT KernelEnabledReserved : 7;
            };
        };
    } SYSTEM_POINTER_AUTH_INFORMATION, * PSYSTEM_POINTER_AUTH_INFORMATION;

    // private
    typedef struct _SYSTEM_ORIGINAL_IMAGE_FEATURE_INFORMATION_INPUT
    {
        ULONG Version;
        PWSTR FeatureName;
        ULONG BornOnVersion;
    } SYSTEM_ORIGINAL_IMAGE_FEATURE_INFORMATION_INPUT, * PSYSTEM_ORIGINAL_IMAGE_FEATURE_INFORMATION_INPUT;

    // private
    typedef struct _SYSTEM_ORIGINAL_IMAGE_FEATURE_INFORMATION_OUTPUT
    {
        ULONG Version;
        BOOLEAN FeatureIsEnabled;
    } SYSTEM_ORIGINAL_IMAGE_FEATURE_INFORMATION_OUTPUT, * PSYSTEM_ORIGINAL_IMAGE_FEATURE_INFORMATION_OUTPUT;

#if (PHNT_MODE != PHNT_MODE_KERNEL)

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtQuerySystemInformation(
            _In_ SYSTEM_INFORMATION_CLASS SystemInformationClass,
            _Out_writes_bytes_opt_(SystemInformationLength) PVOID SystemInformation,
            _In_ ULONG SystemInformationLength,
            _Out_opt_ PULONG ReturnLength
        );

#if (PHNT_VERSION >= PHNT_WIN7)
    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtQuerySystemInformationEx(
            _In_ SYSTEM_INFORMATION_CLASS SystemInformationClass,
            _In_reads_bytes_(InputBufferLength) PVOID InputBuffer,
            _In_ ULONG InputBufferLength,
            _Out_writes_bytes_opt_(SystemInformationLength) PVOID SystemInformation,
            _In_ ULONG SystemInformationLength,
            _Out_opt_ PULONG ReturnLength
        );
#endif

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtSetSystemInformation(
            _In_ SYSTEM_INFORMATION_CLASS SystemInformationClass,
            _In_reads_bytes_opt_(SystemInformationLength) PVOID SystemInformation,
            _In_ ULONG SystemInformationLength
        );

    // SysDbg APIs

    // private
    typedef enum _SYSDBG_COMMAND
    {
        SysDbgQueryModuleInformation,
        SysDbgQueryTraceInformation,
        SysDbgSetTracepoint,
        SysDbgSetSpecialCall, // PVOID
        SysDbgClearSpecialCalls, // void
        SysDbgQuerySpecialCalls,
        SysDbgBreakPoint,
        SysDbgQueryVersion, // DBGKD_GET_VERSION64
        SysDbgReadVirtual, // SYSDBG_VIRTUAL
        SysDbgWriteVirtual, // SYSDBG_VIRTUAL
        SysDbgReadPhysical, // SYSDBG_PHYSICAL // 10
        SysDbgWritePhysical, // SYSDBG_PHYSICAL
        SysDbgReadControlSpace, // SYSDBG_CONTROL_SPACE
        SysDbgWriteControlSpace, // SYSDBG_CONTROL_SPACE
        SysDbgReadIoSpace, // SYSDBG_IO_SPACE
        SysDbgWriteIoSpace, // SYSDBG_IO_SPACE
        SysDbgReadMsr, // SYSDBG_MSR
        SysDbgWriteMsr, // SYSDBG_MSR
        SysDbgReadBusData, // SYSDBG_BUS_DATA
        SysDbgWriteBusData, // SYSDBG_BUS_DATA
        SysDbgCheckLowMemory, // 20
        SysDbgEnableKernelDebugger,
        SysDbgDisableKernelDebugger,
        SysDbgGetAutoKdEnable,
        SysDbgSetAutoKdEnable,
        SysDbgGetPrintBufferSize,
        SysDbgSetPrintBufferSize,
        SysDbgGetKdUmExceptionEnable,
        SysDbgSetKdUmExceptionEnable,
        SysDbgGetTriageDump, // SYSDBG_TRIAGE_DUMP
        SysDbgGetKdBlockEnable, // 30
        SysDbgSetKdBlockEnable,
        SysDbgRegisterForUmBreakInfo,
        SysDbgGetUmBreakPid,
        SysDbgClearUmBreakPid,
        SysDbgGetUmAttachPid,
        SysDbgClearUmAttachPid,
        SysDbgGetLiveKernelDump, // SYSDBG_LIVEDUMP_CONTROL
        SysDbgKdPullRemoteFile, // SYSDBG_KD_PULL_REMOTE_FILE
        SysDbgMaxInfoClass
    } SYSDBG_COMMAND, * PSYSDBG_COMMAND;

    typedef struct _SYSDBG_VIRTUAL
    {
        PVOID Address;
        PVOID Buffer;
        ULONG Request;
    } SYSDBG_VIRTUAL, * PSYSDBG_VIRTUAL;

    typedef struct _SYSDBG_PHYSICAL
    {
        PHYSICAL_ADDRESS Address;
        PVOID Buffer;
        ULONG Request;
    } SYSDBG_PHYSICAL, * PSYSDBG_PHYSICAL;

    typedef struct _SYSDBG_CONTROL_SPACE
    {
        ULONG64 Address;
        PVOID Buffer;
        ULONG Request;
        ULONG Processor;
    } SYSDBG_CONTROL_SPACE, * PSYSDBG_CONTROL_SPACE;

    enum _INTERFACE_TYPE;

    typedef struct _SYSDBG_IO_SPACE
    {
        ULONG64 Address;
        PVOID Buffer;
        ULONG Request;
        enum _INTERFACE_TYPE InterfaceType;
        ULONG BusNumber;
        ULONG AddressSpace;
    } SYSDBG_IO_SPACE, * PSYSDBG_IO_SPACE;

    typedef struct _SYSDBG_MSR
    {
        ULONG Msr;
        ULONG64 Data;
    } SYSDBG_MSR, * PSYSDBG_MSR;

    enum _BUS_DATA_TYPE;

    typedef struct _SYSDBG_BUS_DATA
    {
        ULONG Address;
        PVOID Buffer;
        ULONG Request;
        enum _BUS_DATA_TYPE BusDataType;
        ULONG BusNumber;
        ULONG SlotNumber;
    } SYSDBG_BUS_DATA, * PSYSDBG_BUS_DATA;

    // private
    typedef struct _SYSDBG_TRIAGE_DUMP
    {
        ULONG Flags;
        ULONG BugCheckCode;
        ULONG_PTR BugCheckParam1;
        ULONG_PTR BugCheckParam2;
        ULONG_PTR BugCheckParam3;
        ULONG_PTR BugCheckParam4;
        ULONG ProcessHandles;
        ULONG ThreadHandles;
        PHANDLE Handles;
    } SYSDBG_TRIAGE_DUMP, * PSYSDBG_TRIAGE_DUMP;

    // private
    typedef union _SYSDBG_LIVEDUMP_CONTROL_FLAGS
    {
        struct
        {
            ULONG UseDumpStorageStack : 1;
            ULONG CompressMemoryPagesData : 1;
            ULONG IncludeUserSpaceMemoryPages : 1;
            ULONG AbortIfMemoryPressure : 1; // REDSTONE4
            ULONG SelectiveDump : 1; // WIN11
            ULONG Reserved : 27;
        };
        ULONG AsUlong;
    } SYSDBG_LIVEDUMP_CONTROL_FLAGS, * PSYSDBG_LIVEDUMP_CONTROL_FLAGS;

    // private
    typedef union _SYSDBG_LIVEDUMP_CONTROL_ADDPAGES
    {
        struct
        {
            ULONG HypervisorPages : 1;
            ULONG NonEssentialHypervisorPages : 1; // since WIN11
            ULONG Reserved : 30;
        };
        ULONG AsUlong;
    } SYSDBG_LIVEDUMP_CONTROL_ADDPAGES, * PSYSDBG_LIVEDUMP_CONTROL_ADDPAGES;

#define SYSDBG_LIVEDUMP_SELECTIVE_CONTROL_VERSION 1

    // rev
    typedef struct _SYSDBG_LIVEDUMP_SELECTIVE_CONTROL
    {
        ULONG Version;
        ULONG Size;
        union
        {
            ULONGLONG Flags;
            struct
            {
                ULONGLONG ThreadKernelStacks : 1;
                ULONGLONG ReservedFlags : 63;
            };
        };
        ULONGLONG Reserved[4];
    } SYSDBG_LIVEDUMP_SELECTIVE_CONTROL, * PSYSDBG_LIVEDUMP_SELECTIVE_CONTROL;

#define SYSDBG_LIVEDUMP_CONTROL_VERSION 1
#define SYSDBG_LIVEDUMP_CONTROL_VERSION_WIN11 2

    // private
    typedef struct _SYSDBG_LIVEDUMP_CONTROL
    {
        ULONG Version;
        ULONG BugCheckCode;
        ULONG_PTR BugCheckParam1;
        ULONG_PTR BugCheckParam2;
        ULONG_PTR BugCheckParam3;
        ULONG_PTR BugCheckParam4;
        HANDLE DumpFileHandle;
        HANDLE CancelEventHandle;
        SYSDBG_LIVEDUMP_CONTROL_FLAGS Flags;
        SYSDBG_LIVEDUMP_CONTROL_ADDPAGES AddPagesControl;
        PSYSDBG_LIVEDUMP_SELECTIVE_CONTROL SelectiveControl; // since WIN11
    } SYSDBG_LIVEDUMP_CONTROL, * PSYSDBG_LIVEDUMP_CONTROL;

#define SYSDBG_LIVEDUMP_CONTROL_SIZE RTL_SIZEOF_THROUGH_FIELD(SYSDBG_LIVEDUMP_CONTROL, AddPagesControl)
#define SYSDBG_LIVEDUMP_CONTROL_SIZE_WIN11 sizeof(SYSDBG_LIVEDUMP_CONTROL)

    // private
    typedef struct _SYSDBG_KD_PULL_REMOTE_FILE
    {
        UNICODE_STRING ImageFileName;
    } SYSDBG_KD_PULL_REMOTE_FILE, * PSYSDBG_KD_PULL_REMOTE_FILE;

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtSystemDebugControl(
            _In_ SYSDBG_COMMAND Command,
            _Inout_updates_bytes_opt_(InputBufferLength) PVOID InputBuffer,
            _In_ ULONG InputBufferLength,
            _Out_writes_bytes_opt_(OutputBufferLength) PVOID OutputBuffer,
            _In_ ULONG OutputBufferLength,
            _Out_opt_ PULONG ReturnLength
        );

    // Hard errors

    typedef enum _HARDERROR_RESPONSE_OPTION
    {
        OptionAbortRetryIgnore,
        OptionOk,
        OptionOkCancel,
        OptionRetryCancel,
        OptionYesNo,
        OptionYesNoCancel,
        OptionShutdownSystem,
        OptionOkNoWait,
        OptionCancelTryContinue
    } HARDERROR_RESPONSE_OPTION;

    typedef enum _HARDERROR_RESPONSE
    {
        ResponseReturnToCaller,
        ResponseNotHandled,
        ResponseAbort,
        ResponseCancel,
        ResponseIgnore,
        ResponseNo,
        ResponseOk,
        ResponseRetry,
        ResponseYes,
        ResponseTryAgain,
        ResponseContinue
    } HARDERROR_RESPONSE;

#define HARDERROR_OVERRIDE_ERRORMODE 0x10000000

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtRaiseHardError(
            _In_ NTSTATUS ErrorStatus,
            _In_ ULONG NumberOfParameters,
            _In_ ULONG UnicodeStringParameterMask,
            _In_reads_(NumberOfParameters) PULONG_PTR Parameters,
            _In_ ULONG ValidResponseOptions,
            _Out_ PULONG Response
        );

    // Kernel-user shared data

    typedef enum _ALTERNATIVE_ARCHITECTURE_TYPE
    {
        StandardDesign,
        NEC98x86,
        EndAlternatives
    } ALTERNATIVE_ARCHITECTURE_TYPE;

#define PROCESSOR_FEATURE_MAX 64

#define MAX_WOW64_SHARED_ENTRIES 16

#define NX_SUPPORT_POLICY_ALWAYSOFF 0
#define NX_SUPPORT_POLICY_ALWAYSON 1
#define NX_SUPPORT_POLICY_OPTIN 2
#define NX_SUPPORT_POLICY_OPTOUT 3

    typedef struct _KUSER_SHARED_DATA
    {
        //
        // Current low 32-bit of tick count and tick count multiplier.
        //
        // N.B. The tick count is updated each time the clock ticks.
        //

        ULONG TickCountLowDeprecated;
        ULONG TickCountMultiplier;

        //
        // Current 64-bit interrupt time in 100ns units.
        //

        volatile KSYSTEM_TIME InterruptTime;

        //
        // Current 64-bit system time in 100ns units.
        //

        volatile KSYSTEM_TIME SystemTime;

        //
        // Current 64-bit time zone bias.
        //

        volatile KSYSTEM_TIME TimeZoneBias;

        //
        // Support image magic number range for the host system.
        //
        // N.B. This is an inclusive range.
        //

        USHORT ImageNumberLow;
        USHORT ImageNumberHigh;

        //
        // Copy of system root in unicode.
        //
        // N.B. This field must be accessed via the RtlGetNtSystemRoot API for
        //      an accurate result.
        //

        WCHAR NtSystemRoot[260];

        //
        // Maximum stack trace depth if tracing enabled.
        //

        ULONG MaxStackTraceDepth;

        //
        // Crypto exponent value.
        //

        ULONG CryptoExponent;

        //
        // Time zone ID.
        //

        ULONG TimeZoneId;
        ULONG LargePageMinimum;

        //
        // This value controls the AIT Sampling rate.
        //

        ULONG AitSamplingValue;

        //
        // This value controls switchback processing.
        //

        ULONG AppCompatFlag;

        //
        // Current Kernel Root RNG state seed version
        //

        ULONGLONG RNGSeedVersion;

        //
        // This value controls assertion failure handling.
        //

        ULONG GlobalValidationRunlevel;

        volatile LONG TimeZoneBiasStamp;

        //
        // The shared collective build number undecorated with C or F.
        // GetVersionEx hides the real number
        //

        ULONG NtBuildNumber;

        //
        // Product type.
        //
        // N.B. This field must be accessed via the RtlGetNtProductType API for
        //      an accurate result.
        //

        NT_PRODUCT_TYPE NtProductType;
        BOOLEAN ProductTypeIsValid;
        BOOLEAN Reserved0[1];
        USHORT NativeProcessorArchitecture;

        //
        // The NT Version.
        //
        // N. B. Note that each process sees a version from its PEB, but if the
        //       process is running with an altered view of the system version,
        //       the following two fields are used to correctly identify the
        //       version
        //

        ULONG NtMajorVersion;
        ULONG NtMinorVersion;

        //
        // Processor features.
        //

        BOOLEAN ProcessorFeatures[PROCESSOR_FEATURE_MAX];

        //
        // Reserved fields - do not use.
        //

        ULONG Reserved1;
        ULONG Reserved3;

        //
        // Time slippage while in debugger.
        //

        volatile ULONG TimeSlip;

        //
        // Alternative system architecture, e.g., NEC PC98xx on x86.
        //

        ALTERNATIVE_ARCHITECTURE_TYPE AlternativeArchitecture;

        //
        // Boot sequence, incremented for each boot attempt by the OS loader.
        //

        ULONG BootId;

        //
        // If the system is an evaluation unit, the following field contains the
        // date and time that the evaluation unit expires. A value of 0 indicates
        // that there is no expiration. A non-zero value is the UTC absolute time
        // that the system expires.
        //

        LARGE_INTEGER SystemExpirationDate;

        //
        // Suite support.
        //
        // N.B. This field must be accessed via the RtlGetSuiteMask API for
        //      an accurate result.
        //

        ULONG SuiteMask;

        //
        // TRUE if a kernel debugger is connected/enabled.
        //

        BOOLEAN KdDebuggerEnabled;

        //
        // Mitigation policies.
        //

        union
        {
            UCHAR MitigationPolicies;
            struct
            {
                UCHAR NXSupportPolicy : 2;
                UCHAR SEHValidationPolicy : 2;
                UCHAR CurDirDevicesSkippedForDlls : 2;
                UCHAR Reserved : 2;
            };
        };

        //
        // Measured duration of a single processor yield, in cycles. This is used by
        // lock packages to determine how many times to spin waiting for a state
        // change before blocking.
        //

        USHORT CyclesPerYield;

        //
        // Current console session Id. Always zero on non-TS systems.
        //
        // N.B. This field must be accessed via the RtlGetActiveConsoleId API for an
        //      accurate result.
        //

        volatile ULONG ActiveConsoleId;

        //
        // Force-dismounts cause handles to become invalid. Rather than always
        // probe handles, a serial number of dismounts is maintained that clients
        // can use to see if they need to probe handles.
        //

        volatile ULONG DismountCount;

        //
        // This field indicates the status of the 64-bit COM+ package on the
        // system. It indicates whether the Itermediate Language (IL) COM+
        // images need to use the 64-bit COM+ runtime or the 32-bit COM+ runtime.
        //

        ULONG ComPlusPackage;

        //
        // Time in tick count for system-wide last user input across all terminal
        // sessions. For MP performance, it is not updated all the time (e.g. once
        // a minute per session). It is used for idle detection.
        //

        ULONG LastSystemRITEventTickCount;

        //
        // Number of physical pages in the system. This can dynamically change as
        // physical memory can be added or removed from a running system.
        //

        ULONG NumberOfPhysicalPages;

        //
        // True if the system was booted in safe boot mode.
        //

        BOOLEAN SafeBootMode;

        //
        // Virtualization flags.
        //

        union
        {
            UCHAR VirtualizationFlags;

#if defined(_ARM64_)

            //
            // N.B. Keep this bitfield in sync with the one in arc.w.
            //

            struct
            {
                UCHAR ArchStartedInEl2 : 1;
                UCHAR QcSlIsSupported : 1;
                UCHAR : 6;
            };

#endif

        };

        //
        // Reserved (available for reuse).
        //

        UCHAR Reserved12[2];

        //
        // This is a packed bitfield that contains various flags concerning
        // the system state. They must be manipulated using interlocked
        // operations.
        //
        // N.B. DbgMultiSessionSku must be accessed via the RtlIsMultiSessionSku
        //      API for an accurate result
        //

        union
        {
            ULONG SharedDataFlags;
            struct
            {

                //
                // The following bit fields are for the debugger only. Do not use.
                // Use the bit definitions instead.
                //

                ULONG DbgErrorPortPresent : 1;
                ULONG DbgElevationEnabled : 1;
                ULONG DbgVirtEnabled : 1;
                ULONG DbgInstallerDetectEnabled : 1;
                ULONG DbgLkgEnabled : 1;
                ULONG DbgDynProcessorEnabled : 1;
                ULONG DbgConsoleBrokerEnabled : 1;
                ULONG DbgSecureBootEnabled : 1;
                ULONG DbgMultiSessionSku : 1;
                ULONG DbgMultiUsersInSessionSku : 1;
                ULONG DbgStateSeparationEnabled : 1;
                ULONG SpareBits : 21;
            } DUMMYSTRUCTNAME2;
        } DUMMYUNIONNAME2;

        ULONG DataFlagsPad[1];

        //
        // Depending on the processor, the code for fast system call will differ,
        // Stub code is provided pointers below to access the appropriate code.
        //
        // N.B. The following field is only used on 32-bit systems.
        //

        ULONGLONG TestRetInstruction;
        LONGLONG QpcFrequency;

        //
        // On AMD64, this value is initialized to a nonzero value if the system
        // operates with an altered view of the system service call mechanism.
        //

        ULONG SystemCall;

        //
        // Reserved field - do not use. Used to be UserCetAvailableEnvironments.
        //

        ULONG Reserved2;

        //
        // Reserved, available for reuse.
        //

        ULONGLONG SystemCallPad[2];

        //
        // The 64-bit tick count.
        //

        union
        {
            volatile KSYSTEM_TIME TickCount;
            volatile ULONG64 TickCountQuad;
            struct
            {
                ULONG ReservedTickCountOverlay[3];
                ULONG TickCountPad[1];
            } DUMMYSTRUCTNAME;
        } DUMMYUNIONNAME3;

        //
        // Cookie for encoding pointers system wide.
        //

        ULONG Cookie;
        ULONG CookiePad[1];

        //
        // Client id of the process having the focus in the current
        // active console session id.
        //
        // N.B. This field must be accessed via the
        //      RtlGetConsoleSessionForegroundProcessId API for an accurate result.
        //

        LONGLONG ConsoleSessionForegroundProcessId;

        //
        // N.B. The following data is used to implement the precise time
        //      services. It is aligned on a 64-byte cache-line boundary and
        //      arranged in the order of typical accesses.
        //
        // Placeholder for the (internal) time update lock.
        //

        ULONGLONG TimeUpdateLock;

        //
        // The performance counter value used to establish the current system time.
        //

        ULONGLONG BaselineSystemTimeQpc;

        //
        // The performance counter value used to compute the last interrupt time.
        //

        ULONGLONG BaselineInterruptTimeQpc;

        //
        // The scaled number of system time seconds represented by a single
        // performance count (this value may vary to achieve time synchronization).
        //

        ULONGLONG QpcSystemTimeIncrement;

        //
        // The scaled number of interrupt time seconds represented by a single
        // performance count (this value is constant after the system is booted).
        //

        ULONGLONG QpcInterruptTimeIncrement;

        //
        // The scaling shift count applied to the performance counter system time
        // increment.
        //

        UCHAR QpcSystemTimeIncrementShift;

        //
        // The scaling shift count applied to the performance counter interrupt time
        // increment.
        //

        UCHAR QpcInterruptTimeIncrementShift;

        //
        // The count of unparked processors.
        //

        USHORT UnparkedProcessorCount;

        //
        // A bitmask of enclave features supported on this system.
        //
        // N.B. This field must be accessed via the RtlIsEnclaveFeaturePresent API for an
        //      accurate result.
        //

        ULONG EnclaveFeatureMask[4];

        //
        // Current coverage round for telemetry based coverage.
        //

        ULONG TelemetryCoverageRound;

        //
        // The following field is used for ETW user mode global logging
        // (UMGL).
        //

        USHORT UserModeGlobalLogger[16];

        //
        // Settings that can enable the use of Image File Execution Options
        // from HKCU in addition to the original HKLM.
        //

        ULONG ImageFileExecutionOptions;

        //
        // Generation of the kernel structure holding system language information
        //

        ULONG LangGenerationCount;

        //
        // Reserved (available for reuse).
        //

        ULONGLONG Reserved4;

        //
        // Current 64-bit interrupt time bias in 100ns units.
        //

        volatile ULONGLONG InterruptTimeBias;

        //
        // Current 64-bit performance counter bias, in performance counter units
        // before the shift is applied.
        //

        volatile ULONGLONG QpcBias;

        //
        // Number of active processors and groups.
        //

        ULONG ActiveProcessorCount;
        volatile UCHAR ActiveGroupCount;

        //
        // Reserved (available for re-use).
        //

        UCHAR Reserved9;

        union
        {
            USHORT QpcData;
            struct
            {

                //
                // A boolean indicating whether performance counter queries
                // can read the counter directly (bypassing the system call).
                //

                volatile UCHAR QpcBypassEnabled;

                //
                // Shift applied to the raw counter value to derive the
                // QPC count.
                //

                UCHAR QpcShift;
            };
        };

        LARGE_INTEGER TimeZoneBiasEffectiveStart;
        LARGE_INTEGER TimeZoneBiasEffectiveEnd;

        //
        // Extended processor state configuration
        //

        XSTATE_CONFIGURATION XState;

        KSYSTEM_TIME FeatureConfigurationChangeStamp;
        ULONG Spare;

        ULONG64 UserPointerAuthMask;

    } KUSER_SHARED_DATA, * PKUSER_SHARED_DATA;

    C_ASSERT(FIELD_OFFSET(KUSER_SHARED_DATA, TickCountLowDeprecated) == 0x0);
    C_ASSERT(FIELD_OFFSET(KUSER_SHARED_DATA, TickCountMultiplier) == 0x4);
    C_ASSERT(__alignof(KSYSTEM_TIME) == 4);
    C_ASSERT(FIELD_OFFSET(KUSER_SHARED_DATA, InterruptTime) == 0x08);
    C_ASSERT(FIELD_OFFSET(KUSER_SHARED_DATA, SystemTime) == 0x014);
    C_ASSERT(FIELD_OFFSET(KUSER_SHARED_DATA, TimeZoneBias) == 0x020);
    C_ASSERT(FIELD_OFFSET(KUSER_SHARED_DATA, ImageNumberLow) == 0x02c);
    C_ASSERT(FIELD_OFFSET(KUSER_SHARED_DATA, ImageNumberHigh) == 0x02e);
    C_ASSERT(FIELD_OFFSET(KUSER_SHARED_DATA, NtSystemRoot) == 0x030);
    C_ASSERT(FIELD_OFFSET(KUSER_SHARED_DATA, MaxStackTraceDepth) == 0x238);
    C_ASSERT(FIELD_OFFSET(KUSER_SHARED_DATA, CryptoExponent) == 0x23c);
    C_ASSERT(FIELD_OFFSET(KUSER_SHARED_DATA, TimeZoneId) == 0x240);
    C_ASSERT(FIELD_OFFSET(KUSER_SHARED_DATA, LargePageMinimum) == 0x244);
    C_ASSERT(FIELD_OFFSET(KUSER_SHARED_DATA, AitSamplingValue) == 0x248);
    C_ASSERT(FIELD_OFFSET(KUSER_SHARED_DATA, AppCompatFlag) == 0x24c);
    C_ASSERT(FIELD_OFFSET(KUSER_SHARED_DATA, RNGSeedVersion) == 0x250);
    C_ASSERT(FIELD_OFFSET(KUSER_SHARED_DATA, GlobalValidationRunlevel) == 0x258);
    C_ASSERT(FIELD_OFFSET(KUSER_SHARED_DATA, TimeZoneBiasStamp) == 0x25c);
    C_ASSERT(FIELD_OFFSET(KUSER_SHARED_DATA, NtBuildNumber) == 0x260);
    C_ASSERT(FIELD_OFFSET(KUSER_SHARED_DATA, NtProductType) == 0x264);
    C_ASSERT(FIELD_OFFSET(KUSER_SHARED_DATA, ProductTypeIsValid) == 0x268);
    C_ASSERT(FIELD_OFFSET(KUSER_SHARED_DATA, NativeProcessorArchitecture) == 0x26a);
    C_ASSERT(FIELD_OFFSET(KUSER_SHARED_DATA, NtMajorVersion) == 0x26c);
    C_ASSERT(FIELD_OFFSET(KUSER_SHARED_DATA, NtMinorVersion) == 0x270);
    C_ASSERT(FIELD_OFFSET(KUSER_SHARED_DATA, ProcessorFeatures) == 0x274);
    C_ASSERT(FIELD_OFFSET(KUSER_SHARED_DATA, Reserved1) == 0x2b4);
    C_ASSERT(FIELD_OFFSET(KUSER_SHARED_DATA, Reserved3) == 0x2b8);
    C_ASSERT(FIELD_OFFSET(KUSER_SHARED_DATA, TimeSlip) == 0x2bc);
    C_ASSERT(FIELD_OFFSET(KUSER_SHARED_DATA, AlternativeArchitecture) == 0x2c0);
    C_ASSERT(FIELD_OFFSET(KUSER_SHARED_DATA, SystemExpirationDate) == 0x2c8);
    C_ASSERT(FIELD_OFFSET(KUSER_SHARED_DATA, SuiteMask) == 0x2d0);
    C_ASSERT(FIELD_OFFSET(KUSER_SHARED_DATA, KdDebuggerEnabled) == 0x2d4);
    C_ASSERT(FIELD_OFFSET(KUSER_SHARED_DATA, MitigationPolicies) == 0x2d5);
    C_ASSERT(FIELD_OFFSET(KUSER_SHARED_DATA, CyclesPerYield) == 0x2d6);
    C_ASSERT(FIELD_OFFSET(KUSER_SHARED_DATA, ActiveConsoleId) == 0x2d8);
    C_ASSERT(FIELD_OFFSET(KUSER_SHARED_DATA, DismountCount) == 0x2dc);
    C_ASSERT(FIELD_OFFSET(KUSER_SHARED_DATA, ComPlusPackage) == 0x2e0);
    C_ASSERT(FIELD_OFFSET(KUSER_SHARED_DATA, LastSystemRITEventTickCount) == 0x2e4);
    C_ASSERT(FIELD_OFFSET(KUSER_SHARED_DATA, NumberOfPhysicalPages) == 0x2e8);
    C_ASSERT(FIELD_OFFSET(KUSER_SHARED_DATA, SafeBootMode) == 0x2ec);
    C_ASSERT(FIELD_OFFSET(KUSER_SHARED_DATA, VirtualizationFlags) == 0x2ed);
    C_ASSERT(FIELD_OFFSET(KUSER_SHARED_DATA, Reserved12) == 0x2ee);
#if defined(_MSC_EXTENSIONS)
    C_ASSERT(FIELD_OFFSET(KUSER_SHARED_DATA, SharedDataFlags) == 0x2f0);
#endif
    C_ASSERT(FIELD_OFFSET(KUSER_SHARED_DATA, TestRetInstruction) == 0x2f8);
    C_ASSERT(FIELD_OFFSET(KUSER_SHARED_DATA, QpcFrequency) == 0x300);
    C_ASSERT(FIELD_OFFSET(KUSER_SHARED_DATA, SystemCall) == 0x308);
    C_ASSERT(FIELD_OFFSET(KUSER_SHARED_DATA, Reserved2) == 0x30c);
    C_ASSERT(FIELD_OFFSET(KUSER_SHARED_DATA, SystemCallPad) == 0x310);
#if defined(_MSC_EXTENSIONS)
    C_ASSERT(FIELD_OFFSET(KUSER_SHARED_DATA, TickCount) == 0x320);
    C_ASSERT(FIELD_OFFSET(KUSER_SHARED_DATA, TickCountQuad) == 0x320);
#endif
    C_ASSERT(FIELD_OFFSET(KUSER_SHARED_DATA, Cookie) == 0x330);
    C_ASSERT(FIELD_OFFSET(KUSER_SHARED_DATA, ConsoleSessionForegroundProcessId) == 0x338);
    C_ASSERT(FIELD_OFFSET(KUSER_SHARED_DATA, TimeUpdateLock) == 0x340);
    C_ASSERT(FIELD_OFFSET(KUSER_SHARED_DATA, BaselineSystemTimeQpc) == 0x348);
    C_ASSERT(FIELD_OFFSET(KUSER_SHARED_DATA, BaselineInterruptTimeQpc) == 0x350);
    C_ASSERT(FIELD_OFFSET(KUSER_SHARED_DATA, QpcSystemTimeIncrement) == 0x358);
    C_ASSERT(FIELD_OFFSET(KUSER_SHARED_DATA, QpcInterruptTimeIncrement) == 0x360);
    C_ASSERT(FIELD_OFFSET(KUSER_SHARED_DATA, QpcSystemTimeIncrementShift) == 0x368);
    C_ASSERT(FIELD_OFFSET(KUSER_SHARED_DATA, QpcInterruptTimeIncrementShift) == 0x369);
    C_ASSERT(FIELD_OFFSET(KUSER_SHARED_DATA, UnparkedProcessorCount) == 0x36a);
    C_ASSERT(FIELD_OFFSET(KUSER_SHARED_DATA, EnclaveFeatureMask) == 0x36c);
    C_ASSERT(FIELD_OFFSET(KUSER_SHARED_DATA, TelemetryCoverageRound) == 0x37c);
    C_ASSERT(FIELD_OFFSET(KUSER_SHARED_DATA, UserModeGlobalLogger) == 0x380);
    C_ASSERT(FIELD_OFFSET(KUSER_SHARED_DATA, ImageFileExecutionOptions) == 0x3a0);
    C_ASSERT(FIELD_OFFSET(KUSER_SHARED_DATA, LangGenerationCount) == 0x3a4);
    C_ASSERT(FIELD_OFFSET(KUSER_SHARED_DATA, Reserved4) == 0x3a8);
    C_ASSERT(FIELD_OFFSET(KUSER_SHARED_DATA, InterruptTimeBias) == 0x3b0);
    C_ASSERT(FIELD_OFFSET(KUSER_SHARED_DATA, QpcBias) == 0x3b8);
    C_ASSERT(FIELD_OFFSET(KUSER_SHARED_DATA, ActiveProcessorCount) == 0x3c0);
    C_ASSERT(FIELD_OFFSET(KUSER_SHARED_DATA, ActiveGroupCount) == 0x3c4);
    C_ASSERT(FIELD_OFFSET(KUSER_SHARED_DATA, Reserved9) == 0x3c5);
    C_ASSERT(FIELD_OFFSET(KUSER_SHARED_DATA, QpcData) == 0x3c6);
    C_ASSERT(FIELD_OFFSET(KUSER_SHARED_DATA, QpcBypassEnabled) == 0x3c6);
    C_ASSERT(FIELD_OFFSET(KUSER_SHARED_DATA, QpcShift) == 0x3c7);
    C_ASSERT(FIELD_OFFSET(KUSER_SHARED_DATA, TimeZoneBiasEffectiveStart) == 0x3c8);
    C_ASSERT(FIELD_OFFSET(KUSER_SHARED_DATA, TimeZoneBiasEffectiveEnd) == 0x3d0);
    C_ASSERT(FIELD_OFFSET(KUSER_SHARED_DATA, XState) == 0x3d8);
    C_ASSERT(FIELD_OFFSET(KUSER_SHARED_DATA, FeatureConfigurationChangeStamp) == 0x720);
    C_ASSERT(FIELD_OFFSET(KUSER_SHARED_DATA, UserPointerAuthMask) == 0x730);
#if !defined(WINDOWS_IGNORE_PACKING_MISMATCH)
    C_ASSERT(sizeof(KUSER_SHARED_DATA) == 0x738);
#endif

#define USER_SHARED_DATA ((KUSER_SHARED_DATA * const)0x7ffe0000)

    FORCEINLINE
        ULONGLONG
        NtGetTickCount64(
            VOID
        )
    {
        ULARGE_INTEGER tickCount;

#ifdef _WIN64

        tickCount.QuadPart = USER_SHARED_DATA->TickCountQuad;

#else

        while (TRUE)
        {
            tickCount.HighPart = (ULONG)USER_SHARED_DATA->TickCount.High1Time;
            tickCount.LowPart = USER_SHARED_DATA->TickCount.LowPart;

            if (tickCount.HighPart == (ULONG)USER_SHARED_DATA->TickCount.High2Time)
                break;

            YieldProcessor();
        }

#endif

        return (UInt32x32To64(tickCount.LowPart, USER_SHARED_DATA->TickCountMultiplier) >> 24) +
            (UInt32x32To64(tickCount.HighPart, USER_SHARED_DATA->TickCountMultiplier) << 8);
    }

    FORCEINLINE
        ULONG
        NtGetTickCount(
            VOID
        )
    {
#ifdef _WIN64

        return (ULONG)((USER_SHARED_DATA->TickCountQuad * USER_SHARED_DATA->TickCountMultiplier) >> 24);

#else

        ULARGE_INTEGER tickCount;

        while (TRUE)
        {
            tickCount.HighPart = (ULONG)USER_SHARED_DATA->TickCount.High1Time;
            tickCount.LowPart = USER_SHARED_DATA->TickCount.LowPart;

            if (tickCount.HighPart == (ULONG)USER_SHARED_DATA->TickCount.High2Time)
                break;

            YieldProcessor();
        }

        return (ULONG)((UInt32x32To64(tickCount.LowPart, USER_SHARED_DATA->TickCountMultiplier) >> 24) +
            UInt32x32To64((tickCount.HighPart << 8) & 0xffffffff, USER_SHARED_DATA->TickCountMultiplier));

#endif
    }

    // Locale

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtQueryDefaultLocale(
            _In_ BOOLEAN UserProfile,
            _Out_ PLCID DefaultLocaleId
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtSetDefaultLocale(
            _In_ BOOLEAN UserProfile,
            _In_ LCID DefaultLocaleId
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtQueryInstallUILanguage(
            _Out_ LANGID* InstallUILanguageId
        );

#if (PHNT_VERSION >= PHNT_VISTA)
    // private
    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtFlushInstallUILanguage(
            _In_ LANGID InstallUILanguage,
            _In_ ULONG SetComittedFlag
        );
#endif

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtQueryDefaultUILanguage(
            _Out_ LANGID* DefaultUILanguageId
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtSetDefaultUILanguage(
            _In_ LANGID DefaultUILanguageId
        );

#if (PHNT_VERSION >= PHNT_VISTA)
    // private
    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtIsUILanguageComitted(
            VOID
        );
#endif

    // NLS

    // begin_private

#if (PHNT_VERSION >= PHNT_VISTA)

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtInitializeNlsFiles(
            _Out_ PVOID* BaseAddress,
            _Out_ PLCID DefaultLocaleId,
            _Out_ PLARGE_INTEGER DefaultCasingTableSize,
            _Out_opt_ PULONG CurrentNLSVersion
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtGetNlsSectionPtr(
            _In_ ULONG SectionType,
            _In_ ULONG SectionData,
            _In_ PVOID ContextData,
            _Out_ PVOID* SectionPointer,
            _Out_ PULONG SectionSize
        );

#if (PHNT_VERSION < PHNT_WIN7)

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtAcquireCMFViewOwnership(
            _Out_ PULONGLONG TimeStamp,
            _Out_ PBOOLEAN tokenTaken,
            _In_ BOOLEAN replaceExisting
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtReleaseCMFViewOwnership(
            VOID
        );

#endif

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtMapCMFModule(
            _In_ ULONG What,
            _In_ ULONG Index,
            _Out_opt_ PULONG CacheIndexOut,
            _Out_opt_ PULONG CacheFlagsOut,
            _Out_opt_ PULONG ViewSizeOut,
            _Out_opt_ PVOID* BaseAddress
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtGetMUIRegistryInfo(
            _In_ ULONG Flags,
            _Inout_ PULONG DataSize,
            _Out_ PVOID Data
        );

#endif

    // end_private

    // Global atoms

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtAddAtom(
            _In_reads_bytes_opt_(Length) PWSTR AtomName,
            _In_ ULONG Length,
            _Out_opt_ PRTL_ATOM Atom
        );

#if (PHNT_VERSION >= PHNT_WIN8)

#define ATOM_FLAG_GLOBAL 0x2

    // rev
    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtAddAtomEx(
            _In_reads_bytes_opt_(Length) PWSTR AtomName,
            _In_ ULONG Length,
            _Out_opt_ PRTL_ATOM Atom,
            _In_ ULONG Flags
        );

#endif

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtFindAtom(
            _In_reads_bytes_opt_(Length) PWSTR AtomName,
            _In_ ULONG Length,
            _Out_opt_ PRTL_ATOM Atom
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtDeleteAtom(
            _In_ RTL_ATOM Atom
        );

    typedef enum _ATOM_INFORMATION_CLASS
    {
        AtomBasicInformation,
        AtomTableInformation
    } ATOM_INFORMATION_CLASS;

    typedef struct _ATOM_BASIC_INFORMATION
    {
        USHORT UsageCount;
        USHORT Flags;
        USHORT NameLength;
        _Field_size_bytes_(NameLength) WCHAR Name[1];
    } ATOM_BASIC_INFORMATION, * PATOM_BASIC_INFORMATION;

    typedef struct _ATOM_TABLE_INFORMATION
    {
        ULONG NumberOfAtoms;
        _Field_size_(NumberOfAtoms) RTL_ATOM Atoms[1];
    } ATOM_TABLE_INFORMATION, * PATOM_TABLE_INFORMATION;

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtQueryInformationAtom(
            _In_ RTL_ATOM Atom,
            _In_ ATOM_INFORMATION_CLASS AtomInformationClass,
            _Out_writes_bytes_(AtomInformationLength) PVOID AtomInformation,
            _In_ ULONG AtomInformationLength,
            _Out_opt_ PULONG ReturnLength
        );

    // Global flags

#define FLG_STOP_ON_EXCEPTION 0x00000001 // uk
#define FLG_SHOW_LDR_SNAPS 0x00000002 // uk
#define FLG_DEBUG_INITIAL_COMMAND 0x00000004 // k
#define FLG_STOP_ON_HUNG_GUI 0x00000008 // k

#define FLG_HEAP_ENABLE_TAIL_CHECK 0x00000010 // u
#define FLG_HEAP_ENABLE_FREE_CHECK 0x00000020 // u
#define FLG_HEAP_VALIDATE_PARAMETERS 0x00000040 // u
#define FLG_HEAP_VALIDATE_ALL 0x00000080 // u

#define FLG_APPLICATION_VERIFIER 0x00000100 // u
#define FLG_MONITOR_SILENT_PROCESS_EXIT 0x00000200 // uk
#define FLG_POOL_ENABLE_TAGGING 0x00000400 // k
#define FLG_HEAP_ENABLE_TAGGING 0x00000800 // u

#define FLG_USER_STACK_TRACE_DB 0x00001000 // u,32
#define FLG_KERNEL_STACK_TRACE_DB 0x00002000 // k,32
#define FLG_MAINTAIN_OBJECT_TYPELIST 0x00004000 // k
#define FLG_HEAP_ENABLE_TAG_BY_DLL 0x00008000 // u

#define FLG_DISABLE_STACK_EXTENSION 0x00010000 // u
#define FLG_ENABLE_CSRDEBUG 0x00020000 // k
#define FLG_ENABLE_KDEBUG_SYMBOL_LOAD 0x00040000 // k
#define FLG_DISABLE_PAGE_KERNEL_STACKS 0x00080000 // k

#define FLG_ENABLE_SYSTEM_CRIT_BREAKS 0x00100000 // u
#define FLG_HEAP_DISABLE_COALESCING 0x00200000 // u
#define FLG_ENABLE_CLOSE_EXCEPTIONS 0x00400000 // k
#define FLG_ENABLE_EXCEPTION_LOGGING 0x00800000 // k

#define FLG_ENABLE_HANDLE_TYPE_TAGGING 0x01000000 // k
#define FLG_HEAP_PAGE_ALLOCS 0x02000000 // u
#define FLG_DEBUG_INITIAL_COMMAND_EX 0x04000000 // k
#define FLG_DISABLE_DBGPRINT 0x08000000 // k

#define FLG_CRITSEC_EVENT_CREATION 0x10000000 // u
#define FLG_STOP_ON_UNHANDLED_EXCEPTION 0x20000000 // u,64
#define FLG_ENABLE_HANDLE_EXCEPTIONS 0x40000000 // k
#define FLG_DISABLE_PROTDLLS 0x80000000 // u

#define FLG_VALID_BITS 0xfffffdff

#define FLG_USERMODE_VALID_BITS (FLG_STOP_ON_EXCEPTION | \
    FLG_SHOW_LDR_SNAPS | \
    FLG_HEAP_ENABLE_TAIL_CHECK | \
    FLG_HEAP_ENABLE_FREE_CHECK | \
    FLG_HEAP_VALIDATE_PARAMETERS | \
    FLG_HEAP_VALIDATE_ALL | \
    FLG_APPLICATION_VERIFIER | \
    FLG_HEAP_ENABLE_TAGGING | \
    FLG_USER_STACK_TRACE_DB | \
    FLG_HEAP_ENABLE_TAG_BY_DLL | \
    FLG_DISABLE_STACK_EXTENSION | \
    FLG_ENABLE_SYSTEM_CRIT_BREAKS | \
    FLG_HEAP_DISABLE_COALESCING | \
    FLG_DISABLE_PROTDLLS | \
    FLG_HEAP_PAGE_ALLOCS | \
    FLG_CRITSEC_EVENT_CREATION | \
    FLG_LDR_TOP_DOWN)

#define FLG_BOOTONLY_VALID_BITS (FLG_KERNEL_STACK_TRACE_DB | \
    FLG_MAINTAIN_OBJECT_TYPELIST | \
    FLG_ENABLE_CSRDEBUG | \
    FLG_DEBUG_INITIAL_COMMAND | \
    FLG_DEBUG_INITIAL_COMMAND_EX | \
    FLG_DISABLE_PAGE_KERNEL_STACKS)

#define FLG_KERNELMODE_VALID_BITS (FLG_STOP_ON_EXCEPTION | \
    FLG_SHOW_LDR_SNAPS | \
    FLG_STOP_ON_HUNG_GUI | \
    FLG_POOL_ENABLE_TAGGING | \
    FLG_ENABLE_KDEBUG_SYMBOL_LOAD | \
    FLG_ENABLE_CLOSE_EXCEPTIONS | \
    FLG_ENABLE_EXCEPTION_LOGGING | \
    FLG_ENABLE_HANDLE_TYPE_TAGGING | \
    FLG_DISABLE_DBGPRINT | \
    FLG_ENABLE_HANDLE_EXCEPTIONS)

// Licensing

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtQueryLicenseValue(
            _In_ PUNICODE_STRING ValueName,
            _Out_opt_ PULONG Type,
            _Out_writes_bytes_to_opt_(DataSize, *ResultDataSize) PVOID Data,
            _In_ ULONG DataSize,
            _Out_ PULONG ResultDataSize
        );

    // Misc.

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtSetDefaultHardErrorPort(
            _In_ HANDLE DefaultHardErrorPort
        );

    typedef enum _SHUTDOWN_ACTION
    {
        ShutdownNoReboot,
        ShutdownReboot,
        ShutdownPowerOff,
        ShutdownRebootForRecovery // since WIN11
    } SHUTDOWN_ACTION;

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtShutdownSystem(
            _In_ SHUTDOWN_ACTION Action
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtDisplayString(
            _In_ PUNICODE_STRING String
        );

    // Boot graphics

#if (PHNT_VERSION >= PHNT_WIN7)
// rev
    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtDrawText(
            _In_ PUNICODE_STRING Text
        );
#endif

#endif // (PHNT_MODE != PHNT_MODE_KERNEL)

#endif

    /*
     * Boot Configuration Data (BCD) support functions
     *
     * This file is part of System Informer.
     */

#ifndef _NTBCD_H
#define _NTBCD_H

#ifndef PHNT_INLINE_BCD_GUIDS
     // 5189B25C-5558-4BF2-BCA4-289B11BD29E2 // {badmemory}
    DEFINE_GUID(GUID_BAD_MEMORY_GROUP, 0x5189B25C, 0x5558, 0x4BF2, 0xBC, 0xA4, 0x28, 0x9B, 0x11, 0xBD, 0x29, 0xE2);
    // 6EFB52BF-1766-41DB-A6B3-0EE5EFF72BD7 // {bootloadersettings}
    DEFINE_GUID(GUID_BOOT_LOADER_SETTINGS_GROUP, 0x6EFB52BF, 0x1766, 0x41DB, 0xA6, 0xB3, 0x0E, 0xE5, 0xEF, 0xF7, 0x2B, 0xD7);
    // FA926493-6F1C-4193-A414-58F0B2456D1E // {current}
    DEFINE_GUID(GUID_CURRENT_BOOT_ENTRY, 0xFA926493, 0x6F1C, 0x4193, 0xA4, 0x14, 0x58, 0xF0, 0xB2, 0x45, 0x6D, 0x1E);
    // 4636856E-540F-4170-A130-A84776F4C654 // {eventsettings} {dbgsettings}
    DEFINE_GUID(GUID_DEBUGGER_SETTINGS_GROUP, 0x4636856E, 0x540F, 0x4170, 0xA1, 0x30, 0xA8, 0x47, 0x76, 0xF4, 0xC6, 0x54);
    // 1CAE1EB7-A0DF-4D4D-9851-4860E34EF535 // {default}
    DEFINE_GUID(GUID_DEFAULT_BOOT_ENTRY, 0x1CAE1EB7, 0xA0DF, 0x4D4D, 0x98, 0x51, 0x48, 0x60, 0xE3, 0x4E, 0xF5, 0x35);
    // 0CE4991B-E6B3-4B16-B23C-5E0D9250E5D9 // {emssettings}
    DEFINE_GUID(GUID_EMS_SETTINGS_GROUP, 0x0CE4991B, 0xE6B3, 0x4B16, 0xB2, 0x3C, 0x5E, 0x0D, 0x92, 0x50, 0xE5, 0xD9);
    // A5A30FA2-3D06-4E9F-B5F4-A01DF9D1FCBA // {fwbootmgr}
    DEFINE_GUID(GUID_FIRMWARE_BOOTMGR, 0xA5A30FA2, 0x3D06, 0x4E9F, 0xB5, 0xF4, 0xA0, 0x1D, 0xF9, 0xD1, 0xFC, 0xBA);
    // 7EA2E1AC-2E61-4728-AAA3-896D9D0A9F0E // {globalsettings}
    DEFINE_GUID(GUID_GLOBAL_SETTINGS_GROUP, 0x7EA2E1AC, 0x2E61, 0x4728, 0xAA, 0xA3, 0x89, 0x6D, 0x9D, 0x0A, 0x9F, 0x0E);
    // 7FF607E0-4395-11DB-B0DE-0800200C9A66 // {hypervisorsettings}
    DEFINE_GUID(GUID_HYPERVISOR_SETTINGS_GROUP, 0x7FF607E0, 0x4395, 0x11DB, 0xB0, 0xDE, 0x08, 0x00, 0x20, 0x0C, 0x9A, 0x66);
    // 313E8EED-7098-4586-A9BF-309C61F8D449 // {kerneldbgsettings}
    DEFINE_GUID(GUID_KERNEL_DEBUGGER_SETTINGS_GROUP, 0x313E8EED, 0x7098, 0x4586, 0xA9, 0xBF, 0x30, 0x9C, 0x61, 0xF8, 0xD4, 0x49);
    // 1AFA9C49-16AB-4A5C-4A90-212802DA9460 // {resumeloadersettings}
    DEFINE_GUID(GUID_RESUME_LOADER_SETTINGS_GROUP, 0x1AFA9C49, 0x16AB, 0x4A5C, 0x4A, 0x90, 0x21, 0x28, 0x02, 0xDA, 0x94, 0x60);
    // 9DEA862C-5CDD-4E70-ACC1-F32B344D4795 // {bootmgr}
    DEFINE_GUID(GUID_WINDOWS_BOOTMGR, 0x9DEA862C, 0x5CDD, 0x4E70, 0xAC, 0xC1, 0xF3, 0x2B, 0x34, 0x4D, 0x47, 0x95);
    // 466F5A88-0AF2-4F76-9038-095B170DC21C // {ntldr} {legacy}
    DEFINE_GUID(GUID_WINDOWS_LEGACY_NTLDR, 0x466F5A88, 0x0AF2, 0x4F76, 0x90, 0x38, 0x09, 0x5B, 0x17, 0x0D, 0xC2, 0x1C);
    // B2721D73-1DB4-4C62-BF78-C548A880142D // {memdiag}
    DEFINE_GUID(GUID_WINDOWS_MEMORY_TESTER, 0xB2721D73, 0x1DB4, 0x4C62, 0xBF, 0x78, 0xC5, 0x48, 0xA8, 0x80, 0x14, 0x2D);
    // B012B84D-C47C-4ED5-B722-C0C42163E569
    DEFINE_GUID(GUID_WINDOWS_OS_TARGET_TEMPLATE_EFI, 0xB012B84D, 0xC47C, 0x4ED5, 0xB7, 0x22, 0xC0, 0xC4, 0x21, 0x63, 0xE5, 0x69);
    // A1943BBC-EA85-487C-97C7-C9EDE908A38A
    DEFINE_GUID(GUID_WINDOWS_OS_TARGET_TEMPLATE_PCAT, 0xA1943BBC, 0xEA85, 0x487C, 0x97, 0xC7, 0xC9, 0xED, 0xE9, 0x08, 0xA3, 0x8A);
    // {0C334284-9A41-4DE1-99B3-A7E87E8FF07E}
    DEFINE_GUID(GUID_WINDOWS_RESUME_TARGET_TEMPLATE_EFI, 0x0C334284, 0x9A41, 0x4DE1, 0x99, 0xB3, 0xA7, 0xE8, 0x7E, 0x8F, 0xF0, 0x7E);
    // {98B02A23-0674-4CE7-BDAD-E0A15A8FF97B}
    DEFINE_GUID(GUID_WINDOWS_RESUME_TARGET_TEMPLATE_PCAT, 0x98B02A23, 0x0674, 0x4CE7, 0xBD, 0xAD, 0xE0, 0xA1, 0x5A, 0x8F, 0xF9, 0x7B);
    // A1943BBC-EA85-487C-97C7-C9EDE908A38A
    DEFINE_GUID(GUID_WINDOWS_SETUP_EFI, 0x7254A080, 0x1510, 0x4E85, 0xAC, 0x0F, 0xE7, 0xFB, 0x3D, 0x44, 0x47, 0x36);
    // CBD971BF-B7B8-4885-951A-FA03044F5D71
    DEFINE_GUID(GUID_WINDOWS_SETUP_PCAT, 0xCBD971BF, 0xB7B8, 0x4885, 0x95, 0x1A, 0xFA, 0x03, 0x04, 0x4F, 0x5D, 0x71);
    // AE5534E0-A924-466C-B836-758539A3EE3A // {ramdiskoptions}
    DEFINE_GUID(GUID_WINDOWS_SETUP_RAMDISK_OPTIONS, 0xAE5534E0, 0xA924, 0x466C, 0xB8, 0x36, 0x75, 0x85, 0x39, 0xA3, 0xEE, 0x3A);
    // {7619dcc9-fafe-11d9-b411-000476eba25f}
    DEFINE_GUID(GUID_WINDOWS_SETUP_BOOT_ENTRY, 0x7619dcc9, 0xfafe, 0x11d9, 0xb4, 0x11, 0x00, 0x04, 0x76, 0xeb, 0xa2, 0x5f);
#else
    NTSYSAPI GUID GUID_BAD_MEMORY_GROUP; // {badmemory}
    NTSYSAPI GUID GUID_BOOT_LOADER_SETTINGS_GROUP; // {bootloadersettings}
    NTSYSAPI GUID GUID_CURRENT_BOOT_ENTRY; // {current}
    NTSYSAPI GUID GUID_DEBUGGER_SETTINGS_GROUP; // {eventsettings} {dbgsettings}
    NTSYSAPI GUID GUID_DEFAULT_BOOT_ENTRY; // {default}
    NTSYSAPI GUID GUID_EMS_SETTINGS_GROUP; // {emssettings}
    NTSYSAPI GUID GUID_FIRMWARE_BOOTMGR; // {fwbootmgr}
    NTSYSAPI GUID GUID_GLOBAL_SETTINGS_GROUP; // {globalsettings}
    NTSYSAPI GUID GUID_HYPERVISOR_SETTINGS_GROUP; // {hypervisorsettings}
    NTSYSAPI GUID GUID_KERNEL_DEBUGGER_SETTINGS_GROUP; // {kerneldbgsettings}
    NTSYSAPI GUID GUID_RESUME_LOADER_SETTINGS_GROUP; // {resumeloadersettings}
    NTSYSAPI GUID GUID_WINDOWS_BOOTMGR; // {bootmgr}
    NTSYSAPI GUID GUID_WINDOWS_LEGACY_NTLDR; // {ntldr} {legacy}
    NTSYSAPI GUID GUID_WINDOWS_MEMORY_TESTER; // {memdiag}
    NTSYSAPI GUID GUID_WINDOWS_OS_TARGET_TEMPLATE_EFI;
    NTSYSAPI GUID GUID_WINDOWS_OS_TARGET_TEMPLATE_PCAT;
    NTSYSAPI GUID GUID_WINDOWS_RESUME_TARGET_TEMPLATE_EFI;
    NTSYSAPI GUID GUID_WINDOWS_RESUME_TARGET_TEMPLATE_PCAT;
    NTSYSAPI GUID GUID_WINDOWS_SETUP_EFI;
    NTSYSAPI GUID GUID_WINDOWS_SETUP_PCAT;
    NTSYSAPI GUID GUID_WINDOWS_SETUP_RAMDISK_OPTIONS; // {ramdiskoptions}
#endif

    typedef enum _BCD_MESSAGE_TYPE
    {
        BCD_MESSAGE_TYPE_NONE,
        BCD_MESSAGE_TYPE_TRACE,
        BCD_MESSAGE_TYPE_INFORMATION,
        BCD_MESSAGE_TYPE_WARNING,
        BCD_MESSAGE_TYPE_ERROR,
        BCD_MESSAGE_TYPE_MAXIMUM
    } BCD_MESSAGE_TYPE;

    typedef VOID(NTAPI* BCD_MESSAGE_CALLBACK)(
        _In_ BCD_MESSAGE_TYPE type,
        _In_ PWSTR Message
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        BcdSetLogging(
            _In_ BCD_MESSAGE_TYPE BcdLoggingLevel,
            _In_ BCD_MESSAGE_CALLBACK BcdMessageCallbackRoutine
        );

    NTSYSAPI
        VOID
        NTAPI
        BcdInitializeBcdSyncMutant(
            VOID
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        BcdGetSystemStorePath(
            _Out_ PWSTR* BcdSystemStorePath // RtlFreeHeap(RtlProcessHeap(), 0, BcdSystemStorePath);
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        BcdSetSystemStoreDevice(
            _In_ UNICODE_STRING SystemPartition
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        BcdOpenSystemStore(
            _Out_ PHANDLE BcdStoreHandle
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        BcdOpenStoreFromFile(
            _In_ UNICODE_STRING BcdFilePath,
            _Out_ PHANDLE BcdStoreHandle
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        BcdCreateStore(
            _In_ UNICODE_STRING BcdFilePath,
            _Out_ PHANDLE BcdStoreHandle
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        BcdExportStore(
            _In_ UNICODE_STRING BcdFilePath
        );

#if (PHNT_VERSION > PHNT_WIN11)
    NTSYSAPI
        NTSTATUS
        NTAPI
        BcdExportStoreEx(
            _In_ HANDLE BcdStoreHandle,
            _In_ ULONG Flags,
            _In_ UNICODE_STRING BcdFilePath
        );
#endif

    NTSYSAPI
        NTSTATUS
        NTAPI
        BcdImportStore(
            _In_ UNICODE_STRING BcdFilePath
        );

    typedef enum _BCD_IMPORT_FLAGS
    {
        BCD_IMPORT_NONE,
        BCD_IMPORT_DELETE_FIRMWARE_OBJECTS
    } BCD_IMPORT_FLAGS;

    NTSYSAPI
        NTSTATUS
        NTAPI
        BcdImportStoreWithFlags(
            _In_ UNICODE_STRING BcdFilePath,
            _In_ BCD_IMPORT_FLAGS BcdImportFlags
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        BcdDeleteObjectReferences(
            _In_ HANDLE BcdStoreHandle,
            _In_ PGUID Identifier
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        BcdDeleteSystemStore(
            VOID
        );

    typedef enum _BCD_OPEN_FLAGS
    {
        BCD_OPEN_NONE,
        BCD_OPEN_OPEN_STORE_OFFLINE,
        BCD_OPEN_SYNC_FIRMWARE_ENTRIES
    } BCD_OPEN_FLAGS;

    NTSYSAPI
        NTSTATUS
        NTAPI
        BcdOpenStore(
            _In_ UNICODE_STRING BcdFilePath,
            _In_ BCD_OPEN_FLAGS BcdOpenFlags,
            _Out_ PHANDLE BcdStoreHandle
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        BcdCloseStore(
            _In_ HANDLE BcdStoreHandle
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        BcdFlushStore(
            _In_ HANDLE BcdStoreHandle
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        BcdForciblyUnloadStore(
            _In_ HANDLE BcdStoreHandle
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        BcdMarkAsSystemStore(
            _In_ HANDLE BcdStoreHandle
        );

    typedef enum _BCD_OBJECT_TYPE
    {
        BCD_OBJECT_TYPE_NONE,
        BCD_OBJECT_TYPE_APPLICATION, // 0x10000000
        BCD_OBJECT_TYPE_INHERITED, // 0x20000000
        BCD_OBJECT_TYPE_DEVICE, // 0x30000000
    } BCD_OBJECT_TYPE;

    typedef enum _BCD_APPLICATION_OBJECT_TYPE
    {
        BCD_APPLICATION_OBJECT_NONE = 0,
        BCD_APPLICATION_OBJECT_FIRMWARE_BOOT_MANAGER = 1, // 0x00000001
        BCD_APPLICATION_OBJECT_WINDOWS_BOOT_MANAGER = 2, // 0x00000002
        BCD_APPLICATION_OBJECT_WINDOWS_BOOT_LOADER = 3, // 0x00000003
        BCD_APPLICATION_OBJECT_WINDOWS_RESUME_APPLICATION = 4, // 0x00000004
        BCD_APPLICATION_OBJECT_MEMORY_TESTER = 5, // 0x00000005
        BCD_APPLICATION_OBJECT_LEGACY_NTLDR = 6, // 0x00000006
        BCD_APPLICATION_OBJECT_LEGACY_SETUPLDR = 7, // 0x00000007
        BCD_APPLICATION_OBJECT_BOOT_SECTOR = 8, // 0x00000008
        BCD_APPLICATION_OBJECT_STARTUP_MODULE = 9, // 0x00000009
        BCD_APPLICATION_OBJECT_GENERIC_APPLICATION = 10, // 0x0000000a
        BCD_APPLICATION_OBJECT_RESERVED = 0xFFFFF // 0x000fffff
    } BCD_APPLICATION_OBJECT_TYPE;

    typedef enum _BCD_APPLICATION_IMAGE_TYPE
    {
        BCD_APPLICATION_IMAGE_NONE,
        BCD_APPLICATION_IMAGE_FIRMWARE_APPLICATION, // 0x00100000
        BCD_APPLICATION_IMAGE_BOOT_APPLICATION, // 0x00200000
        BCD_APPLICATION_IMAGE_LEGACY_LOADER, // 0x00300000
        BCD_APPLICATION_IMAGE_REALMODE_CODE, // 0x00400000
    } BCD_APPLICATION_IMAGE_TYPE;

    typedef enum _BCD_INHERITED_CLASS_TYPE
    {
        BCD_INHERITED_CLASS_NONE,
        BCD_INHERITED_CLASS_LIBRARY,
        BCD_INHERITED_CLASS_APPLICATION,
        BCD_INHERITED_CLASS_DEVICE
    } BCD_INHERITED_CLASS_TYPE;

#define MAKE_BCD_OBJECT(ObjectType, ImageType, ApplicationType) \
    (((ULONG)(ObjectType) << 28) | \
    (((ULONG)(ImageType) & 0xF) << 20) | \
    ((ULONG)(ApplicationType) & 0xFFFFF))

#define MAKE_BCD_APPLICATION_OBJECT(ImageType, ApplicationType) \
    MAKE_BCD_OBJECT(BCD_OBJECT_TYPE_APPLICATION, (ULONG)(ImageType), (ULONG)(ApplicationType))

#define GET_BCD_OBJECT_TYPE(DataType) \
    ((BCD_OBJECT_TYPE)(((((ULONG)DataType)) >> 28) & 0xF))
#define GET_BCD_APPLICATION_IMAGE(DataType) \
    ((BCD_APPLICATION_IMAGE_TYPE)(((((ULONG)DataType)) >> 20) & 0xF))
#define GET_BCD_APPLICATION_OBJECT(DataType) \
    ((BCD_APPLICATION_OBJECT_TYPE)((((ULONG)DataType)) & 0xFFFFF))

#define BCD_OBJECT_OSLOADER_TYPE \
    MAKE_BCD_APPLICATION_OBJECT(BCD_APPLICATION_IMAGE_BOOT_APPLICATION, BCD_APPLICATION_OBJECT_WINDOWS_BOOT_LOADER)

    typedef union _BCD_OBJECT_DATATYPE
    {
        ULONG PackedValue;
        union
        {
            struct
            {
                ULONG Reserved : 28;
                BCD_OBJECT_TYPE ObjectType : 4;
            };
            struct
            {
                BCD_APPLICATION_OBJECT_TYPE ApplicationType : 20;
                BCD_APPLICATION_IMAGE_TYPE ImageType : 4;
                ULONG Reserved : 4;
                BCD_OBJECT_TYPE ObjectType : 4;
            } Application;
            struct
            {
                ULONG Value : 20;
                BCD_INHERITED_CLASS_TYPE Class : 4;
                ULONG Reserved : 4;
                BCD_OBJECT_TYPE ObjectType : 4;
            } Inherit;
            struct
            {
                ULONG Reserved : 28;
                BCD_OBJECT_TYPE ObjectType : 4;
            } Device;
        };
    } BCD_OBJECT_DATATYPE, * PBCD_OBJECT_DATATYPE;

    static_assert(sizeof(BCD_OBJECT_DATATYPE) == sizeof(ULONG), "sizeof(BCD_OBJECT_DATATYPE) is invalid.");

#define BCD_OBJECT_DESCRIPTION_VERSION 0x1

    typedef struct _BCD_OBJECT_DESCRIPTION
    {
        ULONG Version; // BCD_OBJECT_DESCRIPTION_VERSION
        ULONG Type; // BCD_OBJECT_DATATYPE
    } BCD_OBJECT_DESCRIPTION, * PBCD_OBJECT_DESCRIPTION;

    typedef struct _BCD_OBJECT
    {
        GUID Identifer;
        PBCD_OBJECT_DESCRIPTION Description;
    } BCD_OBJECT, * PBCD_OBJECT;

    NTSYSAPI
        NTSTATUS
        NTAPI
        BcdEnumerateObjects(
            _In_ HANDLE BcdStoreHandle,
            _In_ PBCD_OBJECT_DESCRIPTION BcdEnumDescriptor,
            _Out_writes_bytes_opt_(*BufferSize) PVOID Buffer, // BCD_OBJECT[]
            _Inout_ PULONG BufferSize,
            _Out_ PULONG ObjectCount
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        BcdOpenObject(
            _In_ HANDLE BcdStoreHandle,
            _In_ const GUID* Identifier,
            _Out_ PHANDLE BcdObjectHandle
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        BcdCreateObject(
            _In_ HANDLE BcdStoreHandle,
            _In_ PGUID Identifier,
            _In_ PBCD_OBJECT_DESCRIPTION Description,
            _Out_ PHANDLE BcdObjectHandle
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        BcdDeleteObject(
            _In_ HANDLE BcdObjectHandle
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        BcdCloseObject(
            _In_ HANDLE BcdObjectHandle
        );

    typedef enum _BCD_COPY_FLAGS
    {
        BCD_COPY_NONE = 0x0,
        BCD_COPY_COPY_CREATE_NEW_OBJECT_IDENTIFIER = 0x1,
        BCD_COPY_COPY_DELETE_EXISTING_OBJECT = 0x2,
        BCD_COPY_COPY_UNKNOWN_FIRMWARE_APPLICATION = 0x4,
        BCD_COPY_IGNORE_SETUP_TEMPLATE_ELEMENTS = 0x8,
        BCD_COPY_RETAIN_ELEMENT_DATA = 0x10,
        BCD_COPY_MIGRATE_ELEMENT_DATA = 0x20
    } BCD_COPY_FLAGS;

    NTSYSAPI
        NTSTATUS
        NTAPI
        BcdCopyObject(
            _In_ HANDLE BcdStoreHandle,
            _In_ HANDLE BcdObjectHandle,
            _In_ BCD_COPY_FLAGS BcdCopyFlags,
            _In_ HANDLE TargetStoreHandle,
            _Out_ PHANDLE TargetObjectHandle
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        BcdCopyObjectEx(
            _In_ HANDLE BcdStoreHandle,
            _In_ HANDLE BcdObjectHandle,
            _In_ BCD_COPY_FLAGS BcdCopyFlags,
            _In_ HANDLE TargetStoreHandle,
            _In_ PGUID TargetObjectId,
            _Out_ PHANDLE TargetObjectHandle
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        BcdCopyObjects(
            _In_ HANDLE BcdStoreHandle,
            _In_ BCD_OBJECT_DESCRIPTION Characteristics,
            _In_ BCD_COPY_FLAGS BcdCopyFlags,
            _In_ HANDLE TargetStoreHandle
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        BcdMigrateObjectElementValues(
            _In_ HANDLE TemplateObjectHandle,
            _In_ HANDLE SourceObjectHandle,
            _In_ HANDLE TargetObjectHandle
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        BcdQueryObject(
            _In_ HANDLE BcdObjectHandle,
            _In_ ULONG BcdVersion, // BCD_OBJECT_DESCRIPTION_VERSION
            _Out_ BCD_OBJECT_DESCRIPTION Description,
            _Out_ PGUID Identifier
        );

    typedef enum _BCD_ELEMENT_DATATYPE_FORMAT
    {
        BCD_ELEMENT_DATATYPE_FORMAT_UNKNOWN,
        BCD_ELEMENT_DATATYPE_FORMAT_DEVICE, // 0x01000000
        BCD_ELEMENT_DATATYPE_FORMAT_STRING, // 0x02000000
        BCD_ELEMENT_DATATYPE_FORMAT_OBJECT, // 0x03000000
        BCD_ELEMENT_DATATYPE_FORMAT_OBJECTLIST, // 0x04000000
        BCD_ELEMENT_DATATYPE_FORMAT_INTEGER, // 0x05000000
        BCD_ELEMENT_DATATYPE_FORMAT_BOOLEAN, // 0x06000000
        BCD_ELEMENT_DATATYPE_FORMAT_INTEGERLIST, // 0x07000000
        BCD_ELEMENT_DATATYPE_FORMAT_BINARY // 0x08000000
    } BCD_ELEMENT_DATATYPE_FORMAT;

    typedef enum _BCD_ELEMENT_DATATYPE_CLASS
    {
        BCD_ELEMENT_DATATYPE_CLASS_NONE,
        BCD_ELEMENT_DATATYPE_CLASS_LIBRARY, // 0x10000000
        BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, // 0x20000000
        BCD_ELEMENT_DATATYPE_CLASS_DEVICE, // 0x30000000
        BCD_ELEMENT_DATATYPE_CLASS_SETUPTEMPLATE, // 0x40000000
        BCD_ELEMENT_DATATYPE_CLASS_OEM // 0x50000000
    } BCD_ELEMENT_DATATYPE_CLASS;

    typedef enum _BCD_ELEMENT_DEVICE_TYPE
    {
        BCD_ELEMENT_DEVICE_TYPE_NONE,
        BCD_ELEMENT_DEVICE_TYPE_BOOT_DEVICE,
        BCD_ELEMENT_DEVICE_TYPE_PARTITION,
        BCD_ELEMENT_DEVICE_TYPE_FILE,
        BCD_ELEMENT_DEVICE_TYPE_RAMDISK,
        BCD_ELEMENT_DEVICE_TYPE_UNKNOWN,
        BCD_ELEMENT_DEVICE_TYPE_QUALIFIED_PARTITION,
        BCD_ELEMENT_DEVICE_TYPE_VMBUS,
        BCD_ELEMENT_DEVICE_TYPE_LOCATE_DEVICE,
        BCD_ELEMENT_DEVICE_TYPE_URI,
        BCD_ELEMENT_DEVICE_TYPE_COMPOSITE
    } BCD_ELEMENT_DEVICE_TYPE;

#define MAKE_BCDE_DATA_TYPE(Class, Format, Subtype) \
    (((((ULONG)Class) & 0xF) << 28) | ((((ULONG)Format) & 0xF) << 24) | (((ULONG)Subtype) & 0x00FFFFFF))

#define GET_BCDE_DATA_CLASS(DataType) \
    ((BCD_ELEMENT_DATATYPE_CLASS)(((((ULONG)DataType)) >> 28) & 0xF))
#define GET_BCDE_DATA_FORMAT(DataType) \
    ((BCD_ELEMENT_DATATYPE_FORMAT)(((((ULONG)DataType)) >> 24) & 0xF))
#define GET_BCDE_DATA_SUBTYPE(DataType) \
    ((ULONG)((((ULONG)DataType)) & 0x00FFFFFF))

    typedef union _BCD_ELEMENT_DATATYPE
    {
        ULONG PackedValue;
        struct
        {
            ULONG SubType : 24;
            BCD_ELEMENT_DATATYPE_FORMAT Format : 4;
            BCD_ELEMENT_DATATYPE_CLASS Class : 4;
        };
    } BCD_ELEMENT_DATATYPE, * PBCD_ELEMENT_DATATYPE;

    static_assert(sizeof(BCD_ELEMENT_DATATYPE) == sizeof(ULONG), "sizeof(BCD_ELEMENT_DATATYPE) is invalid.");

    NTSYSAPI
        NTSTATUS
        NTAPI
        BcdEnumerateElementTypes(
            _In_ HANDLE BcdObjectHandle,
            _Out_writes_bytes_opt_(*BufferSize) PVOID Buffer, // BCD_ELEMENT_DATATYPE[]
            _Inout_ PULONG BufferSize,
            _Out_ PULONG ElementCount
        );

    typedef struct _BCD_ELEMENT_DEVICE_QUALIFIED_PARTITION
    {
        ULONG PartitionStyle;
        ULONG Reserved;
        struct
        {
            union
            {
                ULONG DiskSignature;
                ULONG64 PartitionOffset;
            } Mbr;
            union
            {
                GUID DiskSignature;
                GUID PartitionSignature;
            } Gpt;
        };
    } BCD_ELEMENT_DEVICE_QUALIFIED_PARTITION, * PBCD_ELEMENT_DEVICE_QUALIFIED_PARTITION;

    typedef struct _BCD_ELEMENT_DEVICE
    {
        ULONG DeviceType;
        GUID AdditionalOptions;
        struct
        {
            union
            {
                ULONG ParentOffset;
                WCHAR Path[ANYSIZE_ARRAY];
            } File;
            union
            {
                WCHAR Path[ANYSIZE_ARRAY];
            } Partition;
            union
            {
                ULONG Type;
                ULONG ParentOffset;
                ULONG ElementType;
                WCHAR Path[ANYSIZE_ARRAY];
            } Locate;
            union
            {
                GUID InterfaceInstance;
            } Vmbus;
            union
            {
                ULONG Data[ANYSIZE_ARRAY];
            } Unknown;
            BCD_ELEMENT_DEVICE_QUALIFIED_PARTITION QualifiedPartition;
        };
    } BCD_ELEMENT_DEVICE, * PBCD_ELEMENT_DEVICE;

    typedef struct _BCD_ELEMENT_STRING
    {
        WCHAR Value[ANYSIZE_ARRAY];
    } BCD_ELEMENT_STRING, * PBCD_ELEMENT_STRING;

    typedef struct _BCD_ELEMENT_OBJECT
    {
        GUID Object;
    } BCD_ELEMENT_OBJECT, * PBCD_ELEMENT_OBJECT;

    typedef struct _BCD_ELEMENT_OBJECT_LIST
    {
        GUID ObjectList[ANYSIZE_ARRAY];
    } BCD_ELEMENT_OBJECT_LIST, * PBCD_ELEMENT_OBJECT_LIST;

    typedef struct _BCD_ELEMENT_INTEGER
    {
        ULONG64 Value;
    } BCD_ELEMENT_INTEGER, * PBCD_ELEMENT_INTEGER;

    typedef struct _BCD_ELEMENT_INTEGER_LIST
    {
        ULONG64 Value[ANYSIZE_ARRAY];
    } BCD_ELEMENT_INTEGER_LIST, * PBCD_ELEMENT_INTEGER_LIST;

    typedef struct _BCD_ELEMENT_BOOLEAN
    {
        BOOLEAN Value;
        //BOOLEAN Pad; // sym
    } BCD_ELEMENT_BOOLEAN, * PBCD_ELEMENT_BOOLEAN;

#define BCD_ELEMENT_DESCRIPTION_VERSION 0x1

    typedef struct BCD_ELEMENT_DESCRIPTION
    {
        ULONG Version; // BCD_ELEMENT_DESCRIPTION_VERSION
        ULONG Type;
        ULONG DataSize;
    } BCD_ELEMENT_DESCRIPTION, * PBCD_ELEMENT_DESCRIPTION;

    typedef struct _BCD_ELEMENT
    {
        PBCD_ELEMENT_DESCRIPTION Description;
        PVOID Data;
    } BCD_ELEMENT, * PBCD_ELEMENT;

    NTSYSAPI
        NTSTATUS
        NTAPI
        BcdEnumerateElements(
            _In_ HANDLE BcdObjectHandle,
            _Out_writes_bytes_opt_(*BufferSize) PVOID Buffer, // BCD_ELEMENT[]
            _Inout_ PULONG BufferSize,
            _Out_ PULONG ElementCount
        );

    typedef enum _BCD_FLAGS
    {
        BCD_FLAG_NONE = 0x0,
        BCD_FLAG_QUALIFIED_PARTITION = 0x1,
        BCD_FLAG_NO_DEVICE_TRANSLATION = 0x2,
        BCD_FLAG_ENUMERATE_INHERITED_OBJECTS = 0x4,
        BCD_FLAG_ENUMERATE_DEVICE_OPTIONS = 0x8,
        BCD_FLAG_OBSERVE_PRECEDENCE = 0x10,
        BCD_FLAG_DISABLE_VHD_NT_TRANSLATION = 0x20,
        BCD_FLAG_DISABLE_VHD_DEVICE_DETECTION = 0x40,
        BCD_FLAG_DISABLE_POLICY_CHECKS = 0x80
    } BCD_FLAGS;

    NTSYSAPI
        NTSTATUS
        NTAPI
        BcdEnumerateElementsWithFlags(
            _In_ HANDLE BcdObjectHandle,
            _In_ BCD_FLAGS BcdFlags,
            _Out_writes_bytes_opt_(*BufferSize) PVOID Buffer, // BCD_ELEMENT[]
            _Inout_ PULONG BufferSize,
            _Out_ PULONG ElementCount
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        BcdEnumerateAndUnpackElements(
            _In_ HANDLE BcdStoreHandle,
            _In_ HANDLE BcdObjectHandle,
            _In_ BCD_FLAGS BcdFlags,
            _Out_writes_bytes_opt_(*BufferSize) PVOID Buffer, // BCD_ELEMENT[]
            _Inout_ PULONG BufferSize,
            _Out_ PULONG ElementCount
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        BcdGetElementData(
            _In_ HANDLE BcdObjectHandle,
            _In_ ULONG BcdElement, // BCD_ELEMENT_DATATYPE
            _Out_writes_bytes_opt_(*BufferSize) PVOID Buffer,
            _Inout_ PULONG BufferSize
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        BcdGetElementDataWithFlags(
            _In_ HANDLE BcdObjectHandle,
            _In_ ULONG BcdElement, // BCD_ELEMENT_DATATYPE
            _In_ BCD_FLAGS BcdFlags,
            _Out_writes_bytes_opt_(*BufferSize) PVOID Buffer,
            _Inout_ PULONG BufferSize
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        BcdSetElementData(
            _In_ HANDLE BcdObjectHandle,
            _In_ ULONG BcdElement, // BCD_ELEMENT_DATATYPE
            _In_reads_bytes_opt_(BufferSize) PVOID Buffer,
            _In_ ULONG BufferSize
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        BcdSetElementDataWithFlags(
            _In_ HANDLE BcdObjectHandle,
            _In_ ULONG BcdElement, // BCD_ELEMENT_DATATYPE
            _In_ BCD_FLAGS BcdFlags,
            _In_reads_bytes_opt_(BufferSize) PVOID Buffer,
            _In_ ULONG BufferSize
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        BcdDeleteElement(
            _In_ HANDLE BcdObjectHandle,
            _In_ ULONG BcdElement // BCD_ELEMENT_DATATYPE
        );

    // Element types

    typedef enum _BcdBootMgrElementTypes
    {
        /// <summary>
        /// The order in which BCD objects should be displayed.
        /// Objects are displayed using the string specified by the BcdLibraryString_Description element.
        /// </summary>
        /// <remarks>0x24000001</remarks>
        BcdBootMgrObjectList_DisplayOrder = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_OBJECTLIST, 1),
        /// <summary>
        /// List of boot environment applications the boot manager should execute.
        /// The applications are executed in the order they appear in this list.
        /// If the firmware boot manager does not support loading multiple applications, this list cannot contain more than one entry.
        /// </summary>
        /// <remarks>0x24000002</remarks>
        BcdBootMgrObjectList_BootSequence = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_OBJECTLIST, 2),
        /// <summary>
        /// The default boot environment application to load if the user does not select one.
        /// </summary>
        /// <remarks>0x23000003</remarks>
        BcdBootMgrObject_DefaultObject = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_OBJECT, 3),
        /// <summary>
        /// The maximum number of seconds a boot selection menu is to be displayed to the user.
        /// The menu is displayed until the user selects an option or the time-out expires.
        /// If this value is not specified, the boot manager waits for the user to make a selection.
        /// </summary>
        /// <remarks>0x25000004</remarks>
        BcdBootMgrInteger_Timeout = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_INTEGER, 4),
        /// <summary>
        /// Indicates that a resume operation should be attempted during a system restart.
        /// </summary>
        /// <remarks>0x26000005</remarks>
        BcdBootMgrBoolean_AttemptResume = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_BOOLEAN, 5),
        /// <summary>
        /// The resume application object.
        /// </summary>
        /// <remarks>0x23000006</remarks>
        BcdBootMgrObject_ResumeObject = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_OBJECT, 6),
        /// <summary>
        ///
        /// </summary>
        /// <remarks>0x24000007</remarks>
        BcdBootMgrObjectList_StartupSequence = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_OBJECTLIST, 7),
        /// <summary>
        /// The boot manager tools display order list.
        /// </summary>
        /// <remarks>0x24000010</remarks>
        BcdBootMgrObjectList_ToolsDisplayOrder = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_OBJECTLIST, 16),
        /// <summary>
        /// Forces the display of the legacy boot menu, regardless of the number of OS entries in the BCD store and their BcdOSLoaderInteger_BootMenuPolicy.
        /// </summary>
        /// <remarks>0x26000020</remarks>
        BcdBootMgrBoolean_DisplayBootMenu = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_BOOLEAN, 32),
        /// <summary>
        /// Indicates whether the display of errors should be suppressed.
        /// If this setting is enabled, the boot manager exits to the multi-OS menu on OS launch error.
        /// </summary>
        /// <remarks>0x26000021</remarks>
        BcdBootMgrBoolean_NoErrorDisplay = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_BOOLEAN, 33),
        /// <summary>
        /// The device on which the boot application resides.
        /// </summary>
        /// <remarks>0x21000022</remarks>
        BcdBootMgrDevice_BcdDevice = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_DEVICE, 34),
        /// <summary>
        /// The boot application.
        /// </summary>
        /// <remarks>0x22000023</remarks>
        BcdBootMgrString_BcdFilePath = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_STRING, 35),
        /// <summary>
        ///
        /// </summary>
        /// <remarks>0x26000024</remarks>
        BcdBootMgrBoolean_HormEnabled = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_BOOLEAN, 36),
        /// <summary>
        ///
        /// </summary>
        /// <remarks>0x26000025</remarks>
        BcdBootMgrBoolean_HiberRoot = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_BOOLEAN, 37),
        /// <summary>
        ///
        /// </summary>
        /// <remarks>0x22000026</remarks>
        BcdBootMgrString_PasswordOverride = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_STRING, 38),
        /// <summary>
        ///
        /// </summary>
        /// <remarks>0x22000027</remarks>
        BcdBootMgrString_PinpassPhraseOverride = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_STRING, 39),
        /// <summary>
        /// Controls whether custom actions are processed before a boot sequence.
        /// Note This value is supported starting in Windows 8 and Windows Server 2012.
        /// </summary>
        /// <remarks>0x26000028</remarks>
        BcdBootMgrBoolean_ProcessCustomActionsFirst = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_BOOLEAN, 40),
        /// <summary>
        /// Custom Bootstrap Actions.
        /// </summary>
        /// <remarks>0x27000030</remarks>
        BcdBootMgrIntegerList_CustomActionsList = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_INTEGERLIST, 48),
        /// <summary>
        /// Controls whether a boot sequence persists across multiple boots.
        /// Note This value is supported starting in Windows 8 and Windows Server 2012.
        /// </summary>
        /// <remarks>0x26000031</remarks>
        BcdBootMgrBoolean_PersistBootSequence = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_BOOLEAN, 49),
        /// <summary>
        ///
        /// </summary>
        /// <remarks>0x26000032</remarks>
        BcdBootMgrBoolean_SkipStartupSequence = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_BOOLEAN, 50),
    } BcdBootMgrElementTypes;

    typedef enum _BcdLibrary_FirstMegabytePolicy
    {
        /// <summary>
        /// Use none of the first megabyte of memory.
        /// </summary>
        FirstMegabytePolicyUseNone,
        /// <summary>
        /// Use all of the first megabyte of memory.
        /// </summary>
        FirstMegabytePolicyUseAll,
        /// <summary>
        /// Reserved for future use.
        /// </summary>
        FirstMegabytePolicyUsePrivate
    } BcdLibrary_FirstMegabytePolicy;

    typedef enum _BcdLibrary_DebuggerType
    {
        DebuggerSerial = 0,
        Debugger1394 = 1,
        DebuggerUsb = 2,
        DebuggerNet = 3,
        DebuggerLocal = 4
    } BcdLibrary_DebuggerType;

    typedef enum _BcdLibrary_DebuggerStartPolicy
    {
        /// <summary>
        /// The debugger will start active.
        /// </summary>
        DebuggerStartActive,
        /// <summary>
        /// The debugger will start in the auto-enabled state.
        /// If a debugger is attached it will be used; otherwise the debugger port will be available for other applications.
        /// </summary>
        DebuggerStartAutoEnable,
        /// <summary>
        /// The debugger will not start.
        /// </summary>
        DebuggerStartDisable
    } BcdLibrary_DebuggerStartPolicy;

    typedef enum _BcdLibrary_ConfigAccessPolicy
    {
        /// <summary>
        /// Access to PCI configuration space through the memory-mapped region is allowed.
        /// </summary>
        ConfigAccessPolicyDefault,
        /// <summary>
        /// Access to PCI configuration space through the memory-mapped region is not allowed.
        /// This setting is used for platforms that implement memory-mapped configuration space incorrectly.
        /// The CFC/CF8 access mechanism can be used to access configuration space on these platforms.
        /// </summary>
        ConfigAccessPolicyDisallowMmConfig
    } BcdLibrary_ConfigAccessPolicy;

    typedef enum _BcdLibrary_UxDisplayMessageType
    {
        DisplayMessageTypeDefault = 0,
        DisplayMessageTypeResume = 1,
        DisplayMessageTypeHyperV = 2,
        DisplayMessageTypeRecovery = 3,
        DisplayMessageTypeStartupRepair = 4,
        DisplayMessageTypeSystemImageRecovery = 5,
        DisplayMessageTypeCommandPrompt = 6,
        DisplayMessageTypeSystemRestore = 7,
        DisplayMessageTypePushButtonReset = 8,
    } BcdLibrary_UxDisplayMessageType;

    typedef enum BcdLibrary_SafeBoot
    {
        /// <summary>
        /// Load the drivers and services specified by name or group under the following registry key:
        /// HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SafeBoot\Minimal.
        /// </summary>
        SafemodeMinimal = 0,
        /// <summary>
        /// Load the drivers and services specified by name or group under the following registry key:
        /// HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SafeBoot\Network
        /// </summary>
        SafemodeNetwork = 1,
        /// <summary>
        /// Boot the system into a repair mode that restores the Active Directory service from backup medium.
        /// </summary>
        SafemodeDsRepair = 2
    } BcdLibrary_SafeBoot;

    // BcdLibraryElementTypes based on geoffchappell: https://www.geoffchappell.com/notes/windows/boot/bcd/elements.htm (dmex)
    typedef enum _BcdLibraryElementTypes
    {
        /// <summary>
        /// Device on which a boot environment application resides.
        /// </summary>
        /// <remarks>0x11000001</remarks>
        BcdLibraryDevice_ApplicationDevice = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_LIBRARY, BCD_ELEMENT_DATATYPE_FORMAT_DEVICE, 1),
        /// <summary>
        /// Path to a boot environment application.
        /// </summary>
        /// <remarks>0x12000002</remarks>
        BcdLibraryString_ApplicationPath = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_LIBRARY, BCD_ELEMENT_DATATYPE_FORMAT_STRING, 2),
        /// <summary>
        /// Display name of the boot environment application.
        /// </summary>
        /// <remarks>0x12000004</remarks>
        BcdLibraryString_Description = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_LIBRARY, BCD_ELEMENT_DATATYPE_FORMAT_STRING, 4),
        /// <summary>
        /// Preferred locale, in RFC 3066 format.
        /// </summary>
        /// <remarks>0x12000005</remarks>
        BcdLibraryString_PreferredLocale = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_LIBRARY, BCD_ELEMENT_DATATYPE_FORMAT_STRING, 5),
        /// <summary>
        /// List of BCD objects from which the current object should inherit elements.
        /// </summary>
        /// <remarks>0x14000006</remarks>
        BcdLibraryObjectList_InheritedObjects = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_LIBRARY, BCD_ELEMENT_DATATYPE_FORMAT_OBJECTLIST, 6),
        /// <summary>
        /// Maximum physical address a boot environment application should recognize. All memory above this address is ignored.
        /// </summary>
        /// <remarks>0x15000007</remarks>
        BcdLibraryInteger_TruncatePhysicalMemory = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_LIBRARY, BCD_ELEMENT_DATATYPE_FORMAT_INTEGER, 7),
        /// <summary>
        /// List of boot environment applications to be executed if the associated application fails. The applications are executed in the order they appear in this list.
        /// </summary>
        /// <remarks>0x14000008</remarks>
        BcdLibraryObjectList_RecoverySequence = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_LIBRARY, BCD_ELEMENT_DATATYPE_FORMAT_OBJECTLIST, 8),
        /// <summary>
        /// Indicates whether the recovery sequence executes automatically if the boot application fails. Otherwise, the recovery sequence only runs on demand.
        /// </summary>
        /// <remarks>0x16000009</remarks>
        BcdLibraryBoolean_AutoRecoveryEnabled = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_LIBRARY, BCD_ELEMENT_DATATYPE_FORMAT_BOOLEAN, 9),
        /// <summary>
        /// List of page frame numbers describing faulty memory in the system.
        /// </summary>
        /// <remarks>0x1700000A</remarks>
        BcdLibraryIntegerList_BadMemoryList = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_LIBRARY, BCD_ELEMENT_DATATYPE_FORMAT_INTEGERLIST, 10),
        /// <summary>
        /// If TRUE, indicates that a boot application can use memory listed in the BcdLibraryIntegerList_BadMemoryList.
        /// </summary>
        /// <remarks>0x1600000B</remarks>
        BcdLibraryBoolean_AllowBadMemoryAccess = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_LIBRARY, BCD_ELEMENT_DATATYPE_FORMAT_BOOLEAN, 11),
        /// <summary>
        /// Indicates how the first megabyte of memory is to be used. The Integer property is one of the values from the BcdLibrary_FirstMegabytePolicy enumeration.
        /// </summary>
        /// <remarks>0x1500000C</remarks>
        BcdLibraryInteger_FirstMegabytePolicy = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_LIBRARY, BCD_ELEMENT_DATATYPE_FORMAT_INTEGER, 12),
        /// <summary>
        /// Relocates physical memory on certain AMD processors.
        /// This value is not used in Windows 8 or Windows Server 2012.
        /// </summary>
        /// <remarks>0x1500000D</remarks>
        BcdLibraryInteger_RelocatePhysicalMemory = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_LIBRARY, BCD_ELEMENT_DATATYPE_FORMAT_INTEGER, 13),
        /// <summary>
        /// Specifies a minimum physical address to use in the boot environment.
        /// </summary>
        /// <remarks>0x1500000E</remarks>
        BcdLibraryInteger_AvoidLowPhysicalMemory = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_LIBRARY, BCD_ELEMENT_DATATYPE_FORMAT_INTEGER, 14),
        /// <summary>
        ///
        /// </summary>
        /// <remarks>0x1600000F</remarks>
        BcdLibraryBoolean_TraditionalKsegMappings = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_LIBRARY, BCD_ELEMENT_DATATYPE_FORMAT_BOOLEAN, 15),
        /// <summary>
        /// Indicates whether the boot debugger should be enabled.
        /// </summary>
        /// <remarks>0x16000010</remarks>
        BcdLibraryBoolean_DebuggerEnabled = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_LIBRARY, BCD_ELEMENT_DATATYPE_FORMAT_BOOLEAN, 16),
        /// <summary>
        /// Debugger type. The Integer property is one of the values from the BcdLibrary_DebuggerType enumeration.
        /// </summary>
        /// <remarks>0x15000011</remarks>
        BcdLibraryInteger_DebuggerType = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_LIBRARY, BCD_ELEMENT_DATATYPE_FORMAT_INTEGER, 17),
        /// <summary>
        /// I/O port address for the serial debugger.
        /// </summary>
        /// <remarks>0x15000012</remarks>
        BcdLibraryInteger_SerialDebuggerPortAddress = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_LIBRARY, BCD_ELEMENT_DATATYPE_FORMAT_INTEGER, 18),
        /// <summary>
        /// Serial port number for serial debugging.
        /// If this value is not specified, the default is specified by the DBGP ACPI table settings.
        /// </summary>
        /// <remarks>0x15000013</remarks>
        BcdLibraryInteger_SerialDebuggerPort = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_LIBRARY, BCD_ELEMENT_DATATYPE_FORMAT_INTEGER, 19),
        /// <summary>
        /// Baud rate for serial debugging.
        /// </summary>
        /// <remarks>0x15000014</remarks>
        BcdLibraryInteger_SerialDebuggerBaudRate = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_LIBRARY, BCD_ELEMENT_DATATYPE_FORMAT_INTEGER, 20),
        /// <summary>
        /// Channel number for 1394 debugging.
        /// </summary>
        /// <remarks>0x15000015</remarks>
        BcdLibraryInteger_1394DebuggerChannel = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_LIBRARY, BCD_ELEMENT_DATATYPE_FORMAT_INTEGER, 21),
        /// <summary>
        /// The target name for the USB debugger. The target name is arbitrary but must match between the debugger and the debug target.
        /// </summary>
        /// <remarks>0x12000016</remarks>
        BcdLibraryString_UsbDebuggerTargetName = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_LIBRARY, BCD_ELEMENT_DATATYPE_FORMAT_STRING, 22),
        /// <summary>
        /// If TRUE, the debugger will ignore user mode exceptions and only stop for kernel mode exceptions.
        /// </summary>
        /// <remarks>0x16000017</remarks>
        BcdLibraryBoolean_DebuggerIgnoreUsermodeExceptions = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_LIBRARY, BCD_ELEMENT_DATATYPE_FORMAT_BOOLEAN, 23),
        /// <summary>
        /// Indicates the debugger start policy. The Integer property is one of the values from the BcdLibrary_DebuggerStartPolicy enumeration.
        /// </summary>
        /// <remarks>0x15000018</remarks>
        BcdLibraryInteger_DebuggerStartPolicy = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_LIBRARY, BCD_ELEMENT_DATATYPE_FORMAT_INTEGER, 24),
        /// <summary>
        /// Defines the PCI bus, device, and function numbers of the debugging device. For example, 1.5.0 describes the debugging device on bus 1, device 5, function 0.
        /// </summary>
        /// <remarks>0x12000019</remarks>
        BcdLibraryString_DebuggerBusParameters = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_LIBRARY, BCD_ELEMENT_DATATYPE_FORMAT_STRING, 25),
        /// <summary>
        /// Defines the host IP address for the network debugger.
        /// </summary>
        /// <remarks>0x1500001A</remarks>
        BcdLibraryInteger_DebuggerNetHostIP = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_LIBRARY, BCD_ELEMENT_DATATYPE_FORMAT_INTEGER, 26),
        /// <summary>
        /// Defines the network port for the network debugger.
        /// </summary>
        /// <remarks>0x1500001B</remarks>
        BcdLibraryInteger_DebuggerNetPort = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_LIBRARY, BCD_ELEMENT_DATATYPE_FORMAT_INTEGER, 27),
        /// <summary>
        /// Controls the use of DHCP by the network debugger. Setting this to false causes the OS to only use link-local addresses.
        /// This value is supported starting in Windows 8 and Windows Server 2012.
        /// </summary>
        /// <remarks>0x1600001C</remarks>
        BcdLibraryBoolean_DebuggerNetDhcp = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_LIBRARY, BCD_ELEMENT_DATATYPE_FORMAT_BOOLEAN, 28),
        /// <summary>
        /// Holds the key used to encrypt the network debug connection.
        /// This value is supported starting in Windows 8 and Windows Server 2012.
        /// </summary>
        /// <remarks>0x1200001D</remarks>
        BcdLibraryString_DebuggerNetKey = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_LIBRARY, BCD_ELEMENT_DATATYPE_FORMAT_STRING, 29),
        /// <summary>
        ///
        /// </summary>
        /// <remarks>0x1600001E</remarks>
        BcdLibraryBoolean_DebuggerNetVM = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_LIBRARY, BCD_ELEMENT_DATATYPE_FORMAT_BOOLEAN, 30),
        /// <summary>
        ///
        /// </summary>
        /// <remarks>0x1200001F</remarks>
        BcdLibraryString_DebuggerNetHostIpv6 = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_LIBRARY, BCD_ELEMENT_DATATYPE_FORMAT_STRING, 31),
        /// <summary>
        /// Indicates whether EMS redirection should be enabled.
        /// </summary>
        /// <remarks>0x16000020</remarks>
        BcdLibraryBoolean_EmsEnabled = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_LIBRARY, BCD_ELEMENT_DATATYPE_FORMAT_BOOLEAN, 32),
        /// <summary>
        /// COM port number for EMS redirection.
        /// </summary>
        /// <remarks>0x15000022</remarks>
        BcdLibraryInteger_EmsPort = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_LIBRARY, BCD_ELEMENT_DATATYPE_FORMAT_INTEGER, 34),
        /// <summary>
        /// Baud rate for EMS redirection.
        /// </summary>
        /// <remarks>0x15000023</remarks>
        BcdLibraryInteger_EmsBaudRate = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_LIBRARY, BCD_ELEMENT_DATATYPE_FORMAT_INTEGER, 35),
        /// <summary>
        /// String that is appended to the load options string passed to the kernel to be consumed by kernel-mode components.
        /// This is useful for communicating with kernel-mode components that are not BCD-aware.
        /// </summary>
        /// <remarks>0x12000030</remarks>
        BcdLibraryString_LoadOptionsString = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_LIBRARY, BCD_ELEMENT_DATATYPE_FORMAT_STRING, 48),
        /// <summary>
        ///
        /// </summary>
        /// <remarks>0x16000031</remarks>
        BcdLibraryBoolean_AttemptNonBcdStart = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_LIBRARY, BCD_ELEMENT_DATATYPE_FORMAT_BOOLEAN, 49),
        /// <summary>
        /// Indicates whether the advanced options boot menu (F8) is displayed.
        /// </summary>
        /// <remarks>0x16000040</remarks>
        BcdLibraryBoolean_DisplayAdvancedOptions = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_LIBRARY, BCD_ELEMENT_DATATYPE_FORMAT_BOOLEAN, 64),
        /// <summary>
        /// Indicates whether the boot options editor is enabled.
        /// </summary>
        /// <remarks>0x16000041</remarks>
        BcdLibraryBoolean_DisplayOptionsEdit = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_LIBRARY, BCD_ELEMENT_DATATYPE_FORMAT_BOOLEAN, 65),
        /// <summary>
        ///
        /// </summary>
        /// <remarks>0x15000042</remarks>
        BcdLibraryInteger_FVEKeyRingAddress = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_LIBRARY, BCD_ELEMENT_DATATYPE_FORMAT_INTEGER, 66),
        /// <summary>
        /// Allows a device override for the bootstat.dat log in the boot manager and winload.exe.
        /// </summary>
        /// <remarks>0x11000043</remarks>
        BcdLibraryDevice_BsdLogDevice = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_LIBRARY, BCD_ELEMENT_DATATYPE_FORMAT_DEVICE, 67),
        /// <summary>
        /// Allows a path override for the bootstat.dat log file in the boot manager and winload.exe.
        /// </summary>
        /// <remarks>0x12000044</remarks>
        BcdLibraryString_BsdLogPath = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_LIBRARY, BCD_ELEMENT_DATATYPE_FORMAT_STRING, 68),
        /// <summary>
        /// Indicates whether graphics mode is disabled and boot applications must use text mode display.
        /// </summary>
        /// <remarks>0x16000045</remarks>
        BcdLibraryBoolean_BsdPreserveLog = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_LIBRARY, BCD_ELEMENT_DATATYPE_FORMAT_BOOLEAN, 69),
        /// <summary>
        ///
        /// </summary>
        /// <remarks>0x16000046</remarks>
        BcdLibraryBoolean_GraphicsModeDisabled = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_LIBRARY, BCD_ELEMENT_DATATYPE_FORMAT_BOOLEAN, 70),
        /// <summary>
        /// Indicates the access policy for PCI configuration space.
        /// </summary>
        /// <remarks>0x15000047</remarks>
        BcdLibraryInteger_ConfigAccessPolicy = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_LIBRARY, BCD_ELEMENT_DATATYPE_FORMAT_INTEGER, 71),
        /// <summary>
        /// Disables integrity checks.
        /// Cannot be set when secure boot is enabled.
        /// This value is ignored by Windows 7 and Windows 8.
        /// </summary>
        /// <remarks>0x16000048</remarks>
        BcdLibraryBoolean_DisableIntegrityChecks = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_LIBRARY, BCD_ELEMENT_DATATYPE_FORMAT_BOOLEAN, 72),
        /// <summary>
        /// Indicates whether the test code signing certificate is supported.
        /// </summary>
        /// <remarks>0x16000049</remarks>
        BcdLibraryBoolean_AllowPrereleaseSignatures = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_LIBRARY, BCD_ELEMENT_DATATYPE_FORMAT_BOOLEAN, 73),
        /// <summary>
        /// Overrides the default location of the boot fonts.
        /// </summary>
        /// <remarks>0x1200004A</remarks>
        BcdLibraryString_FontPath = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_LIBRARY, BCD_ELEMENT_DATATYPE_FORMAT_STRING, 74),
        /// <summary>
        ///
        /// </summary>
        /// <remarks>0x1500004B</remarks>
        BcdLibraryInteger_SiPolicy = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_LIBRARY, BCD_ELEMENT_DATATYPE_FORMAT_INTEGER, 75),
        /// <summary>
        /// This value (if present) should not be modified.
        /// </summary>
        /// <remarks>0x1500004C</remarks>
        BcdLibraryInteger_FveBandId = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_LIBRARY, BCD_ELEMENT_DATATYPE_FORMAT_INTEGER, 76),
        /// <summary>
        /// Specifies that legacy BIOS systems should use INT 16h Function 10h for console input instead of INT 16h Function 0h.
        /// </summary>
        /// <remarks>0x16000050</remarks>
        BcdLibraryBoolean_ConsoleExtendedInput = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_LIBRARY, BCD_ELEMENT_DATATYPE_FORMAT_BOOLEAN, 80),
        /// <summary>
        ///
        /// </summary>
        /// <remarks>0x15000051</remarks>
        BcdLibraryInteger_InitialConsoleInput = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_LIBRARY, BCD_ELEMENT_DATATYPE_FORMAT_INTEGER, 81),
        /// <summary>
        /// Forces a specific graphics resolution at boot.
        /// Possible values include GraphicsResolution1024x768 (0), GraphicsResolution800x600 (1), and GraphicsResolution1024x600 (2).
        /// </summary>
        /// <remarks>0x15000052</remarks>
        BcdLibraryInteger_GraphicsResolution = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_LIBRARY, BCD_ELEMENT_DATATYPE_FORMAT_INTEGER, 82),
        /// <summary>
        /// If enabled, specifies that boot error screens are not shown when OS launch errors occur, and the system is reset rather than exiting directly back to the firmware.
        /// </summary>
        /// <remarks>0x16000053</remarks>
        BcdLibraryBoolean_RestartOnFailure = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_LIBRARY, BCD_ELEMENT_DATATYPE_FORMAT_BOOLEAN, 83),
        /// <summary>
        /// Forces highest available graphics resolution at boot.
        /// This value can only be used on UEFI systems.
        /// This value is supported starting in Windows 8 and Windows Server 2012.
        /// </summary>
        /// <remarks>0x16000054</remarks>
        BcdLibraryBoolean_GraphicsForceHighestMode = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_LIBRARY, BCD_ELEMENT_DATATYPE_FORMAT_BOOLEAN, 84),
        /// <summary>
        /// This setting is used to differentiate between the Windows 7 and Windows 8 implementations of UEFI.
        /// Do not modify this setting.
        /// If this setting is removed from a Windows 8 installation, it will not boot.
        /// If this setting is added to a Windows 7 installation, it will not boot.
        /// </summary>
        /// <remarks>0x16000060</remarks>
        BcdLibraryBoolean_IsolatedExecutionContext = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_LIBRARY, BCD_ELEMENT_DATATYPE_FORMAT_BOOLEAN, 96),
        /// <summary>
        /// This setting disables the progress bar and default Windows logo. If a custom text string has been defined, it is also disabled by this setting.
        /// The Integer property is one of the values from the BcdLibrary_UxDisplayMessageType enumeration.
        /// </summary>
        /// <remarks>0x15000065</remarks>
        BcdLibraryInteger_BootUxDisplayMessage = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_LIBRARY, BCD_ELEMENT_DATATYPE_FORMAT_INTEGER, 101),
        /// <summary>
        ///
        /// </summary>
        /// <remarks>0x15000066</remarks>
        BcdLibraryInteger_BootUxDisplayMessageOverride = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_LIBRARY, BCD_ELEMENT_DATATYPE_FORMAT_INTEGER, 102),
        /// <summary>
        /// This setting disables the boot logo.
        /// </summary>
        /// <remarks>0x16000067</remarks>
        BcdLibraryBoolean_BootUxLogoDisable = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_LIBRARY, BCD_ELEMENT_DATATYPE_FORMAT_BOOLEAN, 103),
        /// <summary>
        /// This setting disables the boot status text.
        /// </summary>
        /// <remarks>0x16000068</remarks>
        BcdLibraryBoolean_BootUxTextDisable = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_LIBRARY, BCD_ELEMENT_DATATYPE_FORMAT_BOOLEAN, 104),
        /// <summary>
        /// This setting disables the boot progress bar.
        /// </summary>
        /// <remarks>0x16000069</remarks>
        BcdLibraryBoolean_BootUxProgressDisable = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_LIBRARY, BCD_ELEMENT_DATATYPE_FORMAT_BOOLEAN, 105),
        /// <summary>
        /// This setting disables the boot transition fading.
        /// </summary>
        /// <remarks>0x1600006A</remarks>
        BcdLibraryBoolean_BootUxFadeDisable = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_LIBRARY, BCD_ELEMENT_DATATYPE_FORMAT_BOOLEAN, 106),
        /// <summary>
        ///
        /// </summary>
        /// <remarks>0x1600006B</remarks>
        BcdLibraryBoolean_BootUxReservePoolDebug = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_LIBRARY, BCD_ELEMENT_DATATYPE_FORMAT_BOOLEAN, 107),
        /// <summary>
        ///
        /// </summary>
        /// <remarks>0x1600006C</remarks>
        BcdLibraryBoolean_BootUxDisable = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_LIBRARY, BCD_ELEMENT_DATATYPE_FORMAT_BOOLEAN, 108),
        /// <summary>
        ///
        /// </summary>
        /// <remarks>0x1500006D</remarks>
        BcdLibraryInteger_BootUxFadeFrames = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_LIBRARY, BCD_ELEMENT_DATATYPE_FORMAT_INTEGER, 109),
        /// <summary>
        ///
        /// </summary>
        /// <remarks>0x1600006E</remarks>
        BcdLibraryBoolean_BootUxDumpStats = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_LIBRARY, BCD_ELEMENT_DATATYPE_FORMAT_BOOLEAN, 110),
        /// <summary>
        ///
        /// </summary>
        /// <remarks>0x1600006F</remarks>
        BcdLibraryBoolean_BootUxShowStats = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_LIBRARY, BCD_ELEMENT_DATATYPE_FORMAT_BOOLEAN, 111),
        /// <summary>
        ///
        /// </summary>
        /// <remarks>0x16000071</remarks>
        BcdLibraryBoolean_MultiBootSystem = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_LIBRARY, BCD_ELEMENT_DATATYPE_FORMAT_BOOLEAN, 113),
        /// <summary>
        ///
        /// </summary>
        /// <remarks>0x16000072</remarks>
        BcdLibraryBoolean_ForceNoKeyboard = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_LIBRARY, BCD_ELEMENT_DATATYPE_FORMAT_BOOLEAN, 114),
        /// <summary>
        ///
        /// </summary>
        /// <remarks>0x15000073</remarks>
        BcdLibraryInteger_AliasWindowsKey = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_LIBRARY, BCD_ELEMENT_DATATYPE_FORMAT_INTEGER, 115),
        /// <summary>
        /// Disables the 1-minute timer that triggers shutdown on boot error screens, and the F8 menu, on UEFI systems.
        /// </summary>
        /// <remarks>0x16000074</remarks>
        BcdLibraryBoolean_BootShutdownDisabled = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_LIBRARY, BCD_ELEMENT_DATATYPE_FORMAT_BOOLEAN, 116),
        /// <summary>
        ///
        /// </summary>
        /// <remarks>0x15000075</remarks>
        BcdLibraryInteger_PerformanceFrequency = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_LIBRARY, BCD_ELEMENT_DATATYPE_FORMAT_INTEGER, 117),
        /// <summary>
        ///
        /// </summary>
        /// <remarks>0x15000076</remarks>
        BcdLibraryInteger_SecurebootRawPolicy = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_LIBRARY, BCD_ELEMENT_DATATYPE_FORMAT_INTEGER, 118),
        /// <summary>
        /// Indicates whether or not an in-memory BCD setting passed between boot apps will trigger BitLocker recovery.
        /// This value should not be modified as it could trigger a BitLocker recovery action.
        /// </summary>
        /// <remarks>0x17000077</remarks>
        BcdLibraryIntegerList_AllowedInMemorySettings = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_LIBRARY, BCD_ELEMENT_DATATYPE_FORMAT_INTEGER, 119),
        /// <summary>
        ///
        /// </summary>
        /// <remarks>0x15000079</remarks>
        BcdLibraryInteger_BootUxBitmapTransitionTime = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_LIBRARY, BCD_ELEMENT_DATATYPE_FORMAT_INTEGER, 121),
        /// <summary>
        ///
        /// </summary>
        /// <remarks>0x1600007A</remarks>
        BcdLibraryBoolean_TwoBootImages = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_LIBRARY, BCD_ELEMENT_DATATYPE_FORMAT_BOOLEAN, 122),
        /// <summary>
        /// Force the use of FIPS cryptography checks on boot applications.
        /// BcdLibraryBoolean_ForceFipsCrypto is documented with wrong value 0x16000079
        /// </summary>
        /// <remarks>0x1600007B</remarks>
        BcdLibraryBoolean_ForceFipsCrypto = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_LIBRARY, BCD_ELEMENT_DATATYPE_FORMAT_BOOLEAN, 123),
        /// <summary>
        ///
        /// </summary>
        /// <remarks>0x1500007D</remarks>
        BcdLibraryInteger_BootErrorUx = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_LIBRARY, BCD_ELEMENT_DATATYPE_FORMAT_INTEGER, 125),
        /// <summary>
        ///
        /// </summary>
        /// <remarks>0x1600007E</remarks>
        BcdLibraryBoolean_AllowFlightSignatures = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_LIBRARY, BCD_ELEMENT_DATATYPE_FORMAT_BOOLEAN, 126),
        /// <summary>
        ///
        /// </summary>
        /// <remarks>0x1500007F</remarks>
        BcdLibraryInteger_BootMeasurementLogFormat = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_LIBRARY, BCD_ELEMENT_DATATYPE_FORMAT_INTEGER, 127),
        /// <summary>
        ///
        /// </summary>
        /// <remarks>0x15000080</remarks>
        BcdLibraryInteger_DisplayRotation = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_LIBRARY, BCD_ELEMENT_DATATYPE_FORMAT_INTEGER, 128),
        /// <summary>
        ///
        /// </summary>
        /// <remarks>0x15000081</remarks>
        BcdLibraryInteger_LogControl = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_LIBRARY, BCD_ELEMENT_DATATYPE_FORMAT_INTEGER, 129),
        /// <summary>
        ///
        /// </summary>
        /// <remarks>0x16000082</remarks>
        BcdLibraryBoolean_NoFirmwareSync = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_LIBRARY, BCD_ELEMENT_DATATYPE_FORMAT_BOOLEAN, 130),
        /// <summary>
        ///
        /// </summary>
        /// <remarks>0x11000084</remarks>
        BcdLibraryDevice_WindowsSystemDevice = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_LIBRARY, BCD_ELEMENT_DATATYPE_FORMAT_DEVICE, 132),
        /// <summary>
        ///
        /// </summary>
        /// <remarks>0x16000087</remarks>
        BcdLibraryBoolean_NumLockOn = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_LIBRARY, BCD_ELEMENT_DATATYPE_FORMAT_BOOLEAN, 135),
        /// <summary>
        ///
        /// </summary>
        /// <remarks>0x12000088</remarks>
        BcdLibraryString_AdditionalCiPolicy = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_LIBRARY, BCD_ELEMENT_DATATYPE_FORMAT_STRING, 136),
    } BcdLibraryElementTypes;

    typedef enum _BcdTemplateElementTypes
    {
        /// <summary>
        ///
        /// </summary>
        /// <remarks>0x45000001</remarks>
        BcdSetupInteger_DeviceType = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_SETUPTEMPLATE, BCD_ELEMENT_DATATYPE_FORMAT_INTEGER, 1),
        /// <summary>
        ///
        /// </summary>
        /// <remarks>0x42000002</remarks>
        BcdSetupString_ApplicationRelativePath = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_SETUPTEMPLATE, BCD_ELEMENT_DATATYPE_FORMAT_STRING, 2),
        /// <summary>
        ///
        /// </summary>
        /// <remarks>0x42000003</remarks>
        BcdSetupString_RamdiskDeviceRelativePath = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_SETUPTEMPLATE, BCD_ELEMENT_DATATYPE_FORMAT_STRING, 3),
        /// <summary>
        ///
        /// </summary>
        /// <remarks>0x46000004</remarks>
        BcdSetupBoolean_OmitOsLoaderElements = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_SETUPTEMPLATE, BCD_ELEMENT_DATATYPE_FORMAT_BOOLEAN, 4),
        /// <summary>
        ///
        /// </summary>
        /// <remarks>0x47000006</remarks>
        BcdSetupIntegerList_ElementsToMigrateList = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_SETUPTEMPLATE, BCD_ELEMENT_DATATYPE_FORMAT_INTEGERLIST, 6),
        /// <summary>
        ///
        /// </summary>
        /// <remarks>0x46000010</remarks>
        BcdSetupBoolean_RecoveryOs = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_SETUPTEMPLATE, BCD_ELEMENT_DATATYPE_FORMAT_BOOLEAN, 16),
    } BcdTemplateElementTypes;

    /// <summary>
    /// Specifies the no-execute page protection policies.
    /// </summary>
    typedef enum _BcdOSLoader_NxPolicy
    {
        /// <summary>
        /// The no-execute page protection is off by default.
        /// </summary>
        NxPolicyOptIn = 0,
        /// <summary>
        /// The no-execute page protection is on by default.
        /// </summary>
        NxPolicyOptOut = 1,
        /// <summary>
        /// The no-execute page protection is always off.
        /// </summary>
        NxPolicyAlwaysOff = 2,
        /// <summary>
        /// The no-execute page protection is always on.
        /// </summary>
        NxPolicyAlwaysOn = 3
    } BcdOSLoader_NxPolicy;

    /// <summary>
    /// Specifies the Physical Address Extension (PAE) policies.
    /// </summary>
    typedef enum _BcdOSLoader_PAEPolicy
    {
        /// <summary>
        /// Enable PAE if hot-pluggable memory is defined above 4GB.
        /// </summary>
        PaePolicyDefault = 0,
        /// <summary>
        /// PAE is enabled.
        /// </summary>
        PaePolicyForceEnable = 1,
        /// <summary>
        /// PAE is disabled.
        /// </summary>
        PaePolicyForceDisable = 2
    } BcdOSLoader_PAEPolicy;

    typedef enum _BcdOSLoader_BootStatusPolicy
    {
        /// <summary>
        /// Display all boot failures.
        /// </summary>
        BootStatusPolicyDisplayAllFailures = 0,
        /// <summary>
        /// Ignore all boot failures.
        /// </summary>
        BootStatusPolicyIgnoreAllFailures = 1,
        /// <summary>
        /// Ignore all shutdown failures.
        /// </summary>
        BootStatusPolicyIgnoreShutdownFailures = 2,
        /// <summary>
        /// Ignore all boot failures.
        /// </summary>
        BootStatusPolicyIgnoreBootFailures = 3,
        /// <summary>
        /// Ignore checkpoint failures.
        /// </summary>
        BootStatusPolicyIgnoreCheckpointFailures = 4,
        /// <summary>
        /// Display shutdown failures.
        /// </summary>
        BootStatusPolicyDisplayShutdownFailures = 5,
        /// <summary>
        /// Display boot failures.
        /// </summary>
        BootStatusPolicyDisplayBootFailures = 6,
        /// <summary>
        /// Display checkpoint failures.
        /// </summary>
        BootStatusPolicyDisplayCheckpointFailures = 7
    } BcdOSLoaderBootStatusPolicy;

    // BcdOSLoaderElementTypes based on geoffchappell: https://www.geoffchappell.com/notes/windows/boot/bcd/elements.htm (dmex)
    typedef enum _BcdOSLoaderElementTypes
    {
        /// <summary>
        /// The device on which the operating system resides.
        /// </summary>
        /// <remarks>0x21000001</remarks>
        BcdOSLoaderDevice_OSDevice = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_DEVICE, 1),
        /// <summary>
        /// The file path to the operating system (%SystemRoot% minus the volume).
        /// </summary>
        /// <remarks>0x22000002</remarks>
        BcdOSLoaderString_SystemRoot = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_STRING, 2),
        /// <summary>
        /// The resume application associated with the operating system.
        /// </summary>
        /// <remarks>0x23000003</remarks>
        BcdOSLoaderObject_AssociatedResumeObject = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_OBJECT, 3),
        /// <summary>
        ///
        /// </summary>
        /// <remarks>0x26000004</remarks>
        BcdOSLoaderBoolean_StampDisks = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_BOOLEAN, 4),
        /// <summary>
        /// Indicates whether the operating system loader should determine the kernel and HAL to load based on the platform features.
        /// </summary>
        /// <remarks>0x26000010</remarks>
        BcdOSLoaderBoolean_DetectKernelAndHal = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_BOOLEAN, 16),
        /// <summary>
        /// The kernel to be loaded by the operating system loader. This value overrides the default kernel.
        /// </summary>
        /// <remarks>0x22000011</remarks>
        BcdOSLoaderString_KernelPath = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_STRING, 17),
        /// <summary>
        /// The HAL to be loaded by the operating system loader. This value overrides the default HAL.
        /// </summary>
        /// <remarks>0x22000012</remarks>
        BcdOSLoaderString_HalPath = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_STRING, 18),
        /// <summary>
        /// The transport DLL to be loaded by the operating system loader. This value overrides the default Kdcom.dll.
        /// </summary>
        /// <remarks>0x22000013</remarks>
        BcdOSLoaderString_DbgTransportPath = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_STRING, 19),
        /// <summary>
        /// The no-execute page protection policy. The Integer property is one of the values from the BcdOSLoader_NxPolicy enumeration.
        /// </summary>
        /// <remarks>0x25000020</remarks>
        BcdOSLoaderInteger_NxPolicy = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_INTEGER, 32),
        /// <summary>
        /// The Physical Address Extension (PAE) policy. The Integer property is one of the values from the BcdOSLoader_PAEPolicy enumeration.
        /// </summary>
        /// <remarks>0x25000021</remarks>
        BcdOSLoaderInteger_PAEPolicy = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_INTEGER, 33),
        /// <summary>
        /// Indicates that the system should be started in Windows Preinstallation Environment (Windows PE) mode.
        /// </summary>
        /// <remarks>0x26000022</remarks>
        BcdOSLoaderBoolean_WinPEMode = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_BOOLEAN, 34),
        /// <summary>
        /// Indicates that the system should not automatically reboot when it crashes.
        /// </summary>
        /// <remarks>0x26000024</remarks>
        BcdOSLoaderBoolean_DisableCrashAutoReboot = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_BOOLEAN, 36),
        /// <summary>
        /// Indicates that the system should use the last-known good settings.
        /// </summary>
        /// <remarks>0x26000025</remarks>
        BcdOSLoaderBoolean_UseLastGoodSettings = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_BOOLEAN, 37),
        /// <summary>
        ///
        /// </summary>
        /// <remarks>0x26000026</remarks>
        BcdOSLoaderBoolean_DisableCodeIntegrityChecks = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_BOOLEAN, 38),
        /// <summary>
        /// Indicates whether the test code signing certificate is supported.
        /// </summary>
        /// <remarks>0x26000027</remarks>
        BcdOSLoaderBoolean_AllowPrereleaseSignatures = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_BOOLEAN, 39),
        /// <summary>
        /// Indicates whether the system should utilize the first 4GB of physical memory.
        /// This option requires 5GB of physical memory, and on x86 systems it requires PAE to be enabled.
        /// </summary>
        /// <remarks>0x26000030</remarks>
        BcdOSLoaderBoolean_NoLowMemory = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_BOOLEAN, 48),
        /// <summary>
        /// The amount of memory the system should ignore.
        /// </summary>
        /// <remarks>0x25000031</remarks>
        BcdOSLoaderInteger_RemoveMemory = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_INTEGER, 49),
        /// <summary>
        /// The amount of memory that should be utilized by the process address space, in bytes.
        /// This value should be between 2GB and 3GB.
        /// Increasing this value from the default 2GB decreases the amount of virtual address space available to the system and device drivers.
        /// </summary>
        /// <remarks>0x25000032</remarks>
        BcdOSLoaderInteger_IncreaseUserVa = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_INTEGER, 50),
        /// <summary>
        ///
        /// </summary>
        /// <remarks>0x25000033</remarks>
        BcdOSLoaderInteger_PerformaceDataMemory = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_INTEGER, 51),
        /// <summary>
        /// Indicates whether the system should use the standard VGA display driver instead of a high-performance display driver.
        /// </summary>
        /// <remarks>0x26000040</remarks>
        BcdOSLoaderBoolean_UseVgaDriver = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_BOOLEAN, 64),
        /// <summary>
        /// Indicates whether the system should initialize the VGA driver responsible for displaying simple graphics during the boot process.
        /// If not, there is no display is presented during the boot process.
        /// </summary>
        /// <remarks>0x26000041</remarks>
        BcdOSLoaderBoolean_DisableBootDisplay = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_BOOLEAN, 65),
        /// <summary>
        /// Indicates whether the VGA driver should avoid VESA BIOS calls.
        /// Note This value is ignored by Windows 8 and Windows Server 2012.
        /// </summary>
        /// <remarks>0x26000042</remarks>
        BcdOSLoaderBoolean_DisableVesaBios = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_BOOLEAN, 66),
        /// <summary>
        /// Disables the use of VGA modes in the OS.
        /// </summary>
        /// <remarks>0x26000043</remarks>
        BcdOSLoaderBoolean_DisableVgaMode = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_BOOLEAN, 67),
        /// <summary>
        /// Indicates that cluster-mode APIC addressing should be utilized, and the value is the maximum number of processors per cluster.
        /// </summary>
        /// <remarks>0x25000050</remarks>
        BcdOSLoaderInteger_ClusterModeAddressing = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_INTEGER, 80),
        /// <summary>
        /// Indicates whether to enable physical-destination mode for all APIC messages.
        /// </summary>
        /// <remarks>0x26000051</remarks>
        BcdOSLoaderBoolean_UsePhysicalDestination = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_BOOLEAN, 81),
        /// <summary>
        /// The maximum number of APIC clusters that should be used by cluster-mode addressing.
        /// </summary>
        /// <remarks>0x25000052</remarks>
        BcdOSLoaderInteger_RestrictApicCluster = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_INTEGER, 82),
        /// <summary>
        ///
        /// </summary>
        /// <remarks>0x22000053</remarks>
        BcdOSLoaderString_OSLoaderTypeEVStore = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_STRING, 83),
        /// <summary>
        /// Used to force legacy APIC mode, even if the processors and chipset support extended APIC mode.
        /// </summary>
        /// <remarks>0x26000054</remarks>
        BcdOSLoaderBoolean_UseLegacyApicMode = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_BOOLEAN, 84),
        /// <summary>
        /// Enables the use of extended APIC mode, if supported.
        /// Zero (0) indicates default behavior, one (1) indicates that extended APIC mode is disabled, and two (2) indicates that extended APIC mode is enabled.
        /// The system defaults to using extended APIC mode if available.
        /// </summary>
        /// <remarks>0x25000055</remarks>
        BcdOSLoaderInteger_X2ApicPolicy = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_INTEGER, 85),
        /// <summary>
        /// Indicates whether the operating system should initialize or start non-boot processors.
        /// </summary>
        /// <remarks>0x26000060</remarks>
        BcdOSLoaderBoolean_UseBootProcessorOnly = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_BOOLEAN, 96),
        /// <summary>
        /// The maximum number of processors that can be utilized by the system; all other processors are ignored.
        /// </summary>
        /// <remarks>0x25000061</remarks>
        BcdOSLoaderInteger_NumberOfProcessors = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_INTEGER, 97),
        /// <summary>
        /// Indicates whether the system should use the maximum number of processors.
        /// </summary>
        /// <remarks>0x26000062</remarks>
        BcdOSLoaderBoolean_ForceMaximumProcessors = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_BOOLEAN, 98),
        /// <summary>
        /// Indicates whether processor specific configuration flags are to be used.
        /// </summary>
        /// <remarks>0x25000063</remarks>
        BcdOSLoaderBoolean_ProcessorConfigurationFlags = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_INTEGER, 99),
        /// <summary>
        /// Maximizes the number of groups created when assigning nodes to processor groups.
        /// </summary>
        /// <remarks>0x26000064</remarks>
        BcdOSLoaderBoolean_MaximizeGroupsCreated = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_BOOLEAN, 100),
        /// <summary>
        /// This setting makes drivers group aware and can be used to determine improper group usage.
        /// </summary>
        /// <remarks>0x26000065</remarks>
        BcdOSLoaderBoolean_ForceGroupAwareness = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_BOOLEAN, 101),
        /// <summary>
        /// Specifies the size of all processor groups. Must be set to a power of 2.
        /// </summary>
        /// <remarks>0x25000066</remarks>
        BcdOSLoaderInteger_GroupSize = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_INTEGER, 102),
        /// <summary>
        /// Indicates whether the system should use I/O and IRQ resources created by the system firmware instead of using dynamically configured resources.
        /// </summary>
        /// <remarks>0x26000070</remarks>
        BcdOSLoaderInteger_UseFirmwarePciSettings = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_BOOLEAN, 112),
        /// <summary>
        /// The PCI Message Signaled Interrupt (MSI) policy. Zero (0) indicates default, and one (1) indicates that MSI interrupts are disabled.
        /// </summary>
        /// <remarks>0x25000071</remarks>
        BcdOSLoaderInteger_MsiPolicy = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_INTEGER, 113),
        /// <summary>
        /// Undocumented. Zero (0) indicates default, and one (1) indicates that PCI Express is forcefully disabled.
        /// </summary>
        /// <remarks>0x25000072</remarks>
        BcdOSLoaderInteger_PciExpressPolicy = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_INTEGER, 114),
        /// <summary>
        /// The Integer property is one of the values from the BcdLibrary_SafeBoot enumeration.
        /// </summary>
        /// <remarks>0x25000080</remarks>
        BcdOSLoaderInteger_SafeBoot = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_INTEGER, 128),
        /// <summary>
        /// Indicates whether the system should use the shell specified under the following registry key instead of the default shell:
        /// HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SafeBoot\AlternateShell.
        /// </summary>
        /// <remarks>0x26000081</remarks>
        BcdOSLoaderBoolean_SafeBootAlternateShell = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_BOOLEAN, 129),
        /// <summary>
        /// Indicates whether the system should write logging information to %SystemRoot%\Ntbtlog.txt during initialization.
        /// </summary>
        /// <remarks>0x26000090</remarks>
        BcdOSLoaderBoolean_BootLogInitialization = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_BOOLEAN, 144),
        /// <summary>
        /// Indicates whether the system should display verbose information.
        /// </summary>
        /// <remarks>0x26000091</remarks>
        BcdOSLoaderBoolean_VerboseObjectLoadMode = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_BOOLEAN, 145),
        /// <summary>
        /// Indicates whether the kernel debugger should be enabled using the settings in the inherited debugger object.
        /// </summary>
        /// <remarks>0x260000A0</remarks>
        BcdOSLoaderBoolean_KernelDebuggerEnabled = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_BOOLEAN, 160),
        /// <summary>
        /// Indicates whether the HAL should call DbgBreakPoint at the start of HalInitSystem for phase 0 initialization of the kernel.
        /// </summary>
        /// <remarks>0x260000A1</remarks>
        BcdOSLoaderBoolean_DebuggerHalBreakpoint = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_BOOLEAN, 161),
        /// <summary>
        /// Forces the use of the platform clock as the system's performance counter.
        /// </summary>
        /// <remarks>0x260000A2</remarks>
        BcdOSLoaderBoolean_UsePlatformClock = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_BOOLEAN, 162),
        /// <summary>
        /// Forces the OS to assume the presence of legacy PC devices like CMOS and keyboard controllers.
        /// This value should only be used for debugging.
        /// </summary>
        /// <remarks>0x260000A3</remarks>
        BcdOSLoaderBoolean_ForceLegacyPlatform = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_BOOLEAN, 163),
        /// <summary>
        ///
        /// </summary>
        /// <remarks>0x260000A4</remarks>
        BcdOSLoaderBoolean_UsePlatformTick = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_BOOLEAN, 164),
        /// <summary>
        ///
        /// </summary>
        /// <remarks>0x260000A5</remarks>
        BcdOSLoaderBoolean_DisableDynamicTick = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_BOOLEAN, 165),
        /// <summary>
        /// Controls the TSC synchronization policy. Possible values include default (0), legacy (1), or enhanced (2).
        /// This value is supported starting in Windows 8 and Windows Server 2012.
        /// </summary>
        /// <remarks>0x250000A6</remarks>
        BcdOSLoaderInteger_TscSyncPolicy = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_INTEGER, 166),
        /// <summary>
        /// Indicates whether EMS should be enabled in the kernel.
        /// </summary>
        /// <remarks>0x260000B0</remarks>
        BcdOSLoaderBoolean_EmsEnabled = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_BOOLEAN, 176),
        /// <summary>
        ///
        /// </summary>
        /// <remarks>0x250000C0</remarks>
        BcdOSLoaderInteger_ForceFailure = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_INTEGER, 192),
        /// <summary>
        /// Indicates the driver load failure policy. Zero (0) indicates that a failed driver load is fatal and the boot will not continue,
        /// one (1) indicates that the standard error control is used.
        /// </summary>
        /// <remarks>0x250000C1</remarks>
        BcdOSLoaderInteger_DriverLoadFailurePolicy = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_INTEGER, 193),
        /// <summary>
        /// Defines the type of boot menus the system will use. Possible values include menupolicylegacy (0) or menupolicystandard (1).
        /// The default value is menupolicylegacy (0).
        /// </summary>
        /// <remarks>0x250000C2</remarks>
        BcdOSLoaderInteger_BootMenuPolicy = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_INTEGER, 194),
        /// <summary>
        /// Controls whether the system boots to the legacy menu (F8 menu) on the next boot.
        /// Note This value is supported starting in Windows 8 and Windows Server 2012.
        /// </summary>
        /// <remarks>0x260000C3</remarks>
        BcdOSLoaderBoolean_AdvancedOptionsOneTime = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_BOOLEAN, 195),
        /// <summary>
        ///
        /// </summary>
        /// <remarks>0x260000C4</remarks>
        BcdOSLoaderBoolean_OptionsEditOneTime = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_BOOLEAN, 196),
        /// <summary>
        /// The boot status policy. The Integer property is one of the values from the BcdOSLoaderBootStatusPolicy enumeration
        /// </summary>
        /// <remarks>0x250000E0</remarks>
        BcdOSLoaderInteger_BootStatusPolicy = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_INTEGER, 224),
        /// <summary>
        /// The OS loader removes this entry for security reasons. This option can only be triggered by using the F8 menu; a user must be physically present to trigger this option.
        /// This value is supported starting in Windows 8 and Windows Server 2012.
        /// </summary>
        /// <remarks>0x260000E1</remarks>
        BcdOSLoaderBoolean_DisableElamDrivers = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_BOOLEAN, 225),
        /// <summary>
        /// Controls the hypervisor launch type. Options are HyperVisorLaunchOff (0) and HypervisorLaunchAuto (1).
        /// </summary>
        /// <remarks>0x250000F0</remarks>
        BcdOSLoaderInteger_HypervisorLaunchType = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_INTEGER, 240),
        /// <summary>
        ///
        /// </summary>
        /// <remarks>0x250000F1</remarks>
        BcdOSLoaderString_HypervisorPath = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_INTEGER, 241),
        /// <summary>
        /// Controls whether the hypervisor debugger is enabled.
        /// </summary>
        /// <remarks>0x260000F2</remarks>
        BcdOSLoaderBoolean_HypervisorDebuggerEnabled = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_BOOLEAN, 242),
        /// <summary>
        /// Controls the hypervisor debugger type. Can be set to SERIAL (0), 1394 (1), or NET (2).
        /// </summary>
        /// <remarks>0x250000F3</remarks>
        BcdOSLoaderInteger_HypervisorDebuggerType = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_INTEGER, 243),
        /// <summary>
        /// Specifies the serial port number for serial debugging.
        /// </summary>
        /// <remarks>0x250000F4</remarks>
        BcdOSLoaderInteger_HypervisorDebuggerPortNumber = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_INTEGER, 244),
        /// <summary>
        /// Specifies the baud rate for serial debugging.
        /// </summary>
        /// <remarks>0x250000F5</remarks>
        BcdOSLoaderInteger_HypervisorDebuggerBaudrate = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_INTEGER, 245),
        /// <summary>
        /// Specifies the channel number for 1394 debugging.
        /// </summary>
        /// <remarks>0x250000F6</remarks>
        BcdOSLoaderInteger_HypervisorDebugger1394Channel = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_INTEGER, 246),
        /// <summary>
        /// Values are Disabled (0), Basic (1), and Standard (2).
        /// </summary>
        /// <remarks>0x250000F7</remarks>
        BcdOSLoaderInteger_BootUxPolicy = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_INTEGER, 247),
        /// <summary>
        ///
        /// </summary>
        /// <remarks>0x220000F8</remarks>
        BcdOSLoaderInteger_HypervisorSlatDisabled = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_STRING, 248),
        /// <summary>
        /// Defines the PCI bus, device, and function numbers of the debugging device used with the hypervisor.
        /// For example, 1.5.0 describes the debugging device on bus 1, device 5, function 0.
        /// </summary>
        /// <remarks>0x220000F9</remarks>
        BcdOSLoaderString_HypervisorDebuggerBusParams = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_STRING, 249),
        /// <summary>
        ///
        /// </summary>
        /// <remarks>0x250000FA</remarks>
        BcdOSLoaderInteger_HypervisorNumProc = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_INTEGER, 250),
        /// <summary>
        ///
        /// </summary>
        /// <remarks>0x250000FB</remarks>
        BcdOSLoaderInteger_HypervisorRootProcPerNode = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_INTEGER, 251),
        /// <summary>
        ///
        /// </summary>
        /// <remarks>0x260000FC</remarks>
        BcdOSLoaderBoolean_HypervisorUseLargeVTlb = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_BOOLEAN, 252),
        /// <summary>
        ///
        /// </summary>
        /// <remarks>0x250000FD</remarks>
        BcdOSLoaderInteger_HypervisorDebuggerNetHostIp = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_INTEGER, 253),
        /// <summary>
        ///
        /// </summary>
        /// <remarks>0x250000FE</remarks>
        BcdOSLoaderInteger_HypervisorDebuggerNetHostPort = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_INTEGER, 254),
        /// <summary>
        ///
        /// </summary>
        /// <remarks>0x250000FF</remarks>
        BcdOSLoaderInteger_HypervisorDebuggerPages = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_INTEGER, 255),
        /// <summary>
        ///
        /// </summary>
        /// <remarks>0x25000100</remarks>
        BcdOSLoaderInteger_TpmBootEntropyPolicy = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_INTEGER, 256),
        /// <summary>
        ///
        /// </summary>
        /// <remarks>0x22000110</remarks>
        BcdOSLoaderString_HypervisorDebuggerNetKey = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_STRING, 272),
        /// <summary>
        ///
        /// </summary>
        /// <remarks>0x22000112</remarks>
        BcdOSLoaderString_HypervisorProductSkuType = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_STRING, 274),
        /// <summary>
        ///
        /// </summary>
        /// <remarks>0x22000113</remarks>
        BcdOSLoaderInteger_HypervisorRootProc = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_STRING, 275),
        /// <summary>
        ///
        /// </summary>
        /// <remarks>0x26000114</remarks>
        BcdOSLoaderBoolean_HypervisorDebuggerNetDhcp = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_BOOLEAN, 276),
        /// <summary>
        ///
        /// </summary>
        /// <remarks>0x25000115</remarks>
        BcdOSLoaderInteger_HypervisorIommuPolicy = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_INTEGER, 277),
        /// <summary>
        ///
        /// </summary>
        /// <remarks>0x26000116</remarks>
        BcdOSLoaderBoolean_HypervisorUseVApic = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_BOOLEAN, 278),
        /// <summary>
        ///
        /// </summary>
        /// <remarks>0x22000117</remarks>
        BcdOSLoaderString_HypervisorLoadOptions = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_STRING, 279),
        /// <summary>
        ///
        /// </summary>
        /// <remarks>0x25000118</remarks>
        BcdOSLoaderInteger_HypervisorMsrFilterPolicy = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_INTEGER, 280),
        /// <summary>
        ///
        /// </summary>
        /// <remarks>0x25000119</remarks>
        BcdOSLoaderInteger_HypervisorMmioNxPolicy = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_INTEGER, 281),
        /// <summary>
        ///
        /// </summary>
        /// <remarks>0x2500011A</remarks>
        BcdOSLoaderInteger_HypervisorSchedulerType = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_INTEGER, 282),
        /// <summary>
        ///
        /// </summary>
        /// <remarks>0x2200011B</remarks>
        BcdOSLoaderString_HypervisorRootProcNumaNodes = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_STRING, 283),
        /// <summary>
        ///
        /// </summary>
        /// <remarks>0x2500011C</remarks>
        BcdOSLoaderInteger_HypervisorPerfmon = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_INTEGER, 284),
        /// <summary>
        ///
        /// </summary>
        /// <remarks>0x2500011D</remarks>
        BcdOSLoaderInteger_HypervisorRootProcPerCore = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_INTEGER, 285),
        /// <summary>
        ///
        /// </summary>
        /// <remarks>0x2200011E</remarks>
        BcdOSLoaderString_HypervisorRootProcNumaNodeLps = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_STRING, 286),
        /// <summary>
        ///
        /// </summary>
        /// <remarks>0x25000120</remarks>
        BcdOSLoaderInteger_XSavePolicy = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_INTEGER, 288),
        /// <summary>
        ///
        /// </summary>
        /// <remarks>0x25000121</remarks>
        BcdOSLoaderInteger_XSaveAddFeature0 = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_INTEGER, 289),
        /// <summary>
        ///
        /// </summary>
        /// <remarks>0x25000122</remarks>
        BcdOSLoaderInteger_XSaveAddFeature1 = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_INTEGER, 290),
        /// <summary>
        ///
        /// </summary>
        /// <remarks>0x25000123</remarks>
        BcdOSLoaderInteger_XSaveAddFeature2 = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_INTEGER, 291),
        /// <summary>
        ///
        /// </summary>
        /// <remarks>0x25000124</remarks>
        BcdOSLoaderInteger_XSaveAddFeature3 = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_INTEGER, 292),
        /// <summary>
        ///
        /// </summary>
        /// <remarks>0x25000125</remarks>
        BcdOSLoaderInteger_XSaveAddFeature4 = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_INTEGER, 293),
        /// <summary>
        ///
        /// </summary>
        /// <remarks>0x25000126</remarks>
        BcdOSLoaderInteger_XSaveAddFeature5 = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_INTEGER, 294),
        /// <summary>
        ///
        /// </summary>
        /// <remarks>0x25000127</remarks>
        BcdOSLoaderInteger_XSaveAddFeature6 = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_INTEGER, 295),
        /// <summary>
        ///
        /// </summary>
        /// <remarks>0x25000128</remarks>
        BcdOSLoaderInteger_XSaveAddFeature7 = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_INTEGER, 296),
        /// <summary>
        ///
        /// </summary>
        /// <remarks>0x25000129</remarks>
        BcdOSLoaderInteger_XSaveRemoveFeature = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_INTEGER, 297),
        /// <summary>
        ///
        /// </summary>
        /// <remarks>0x2500012A</remarks>
        BcdOSLoaderInteger_XSaveProcessorsMask = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_INTEGER, 298),
        /// <summary>
        ///
        /// </summary>
        /// <remarks>0x2500012B</remarks>
        BcdOSLoaderInteger_XSaveDisable = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_INTEGER, 299),
        /// <summary>
        ///
        /// </summary>
        /// <remarks>0x2500012C</remarks>
        BcdOSLoaderInteger_KernelDebuggerType = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_INTEGER, 300),
        /// <summary>
        ///
        /// </summary>
        /// <remarks>0x2200012D</remarks>
        BcdOSLoaderString_KernelDebuggerBusParameters = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_STRING, 301),
        /// <summary>
        ///
        /// </summary>
        /// <remarks>0x2500012E</remarks>
        BcdOSLoaderInteger_KernelDebuggerPortAddress = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_INTEGER, 302),
        /// <summary>
        ///
        /// </summary>
        /// <remarks>0x2500012F</remarks>
        BcdOSLoaderInteger_KernelDebuggerPortNumber = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_INTEGER, 303),
        /// <summary>
        ///
        /// </summary>
        /// <remarks>0x25000130</remarks>
        BcdOSLoaderInteger_ClaimedTpmCounter = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_INTEGER, 304),
        /// <summary>
        ///
        /// </summary>
        /// <remarks>0x25000131</remarks>
        BcdOSLoaderInteger_KernelDebugger1394Channel = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_INTEGER, 305),
        /// <summary>
        ///
        /// </summary>
        /// <remarks>0x22000132</remarks>
        BcdOSLoaderString_KernelDebuggerUsbTargetname = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_STRING, 306),
        /// <summary>
        ///
        /// </summary>
        /// <remarks>0x25000133</remarks>
        BcdOSLoaderInteger_KernelDebuggerNetHostIp = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_INTEGER, 307),
        /// <summary>
        ///
        /// </summary>
        /// <remarks>0x25000134</remarks>
        BcdOSLoaderInteger_KernelDebuggerNetHostPort = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_INTEGER, 308),
        /// <summary>
        ///
        /// </summary>
        /// <remarks>0x26000135</remarks>
        BcdOSLoaderBoolean_KernelDebuggerNetDhcp = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_BOOLEAN, 309),
        /// <summary>
        ///
        /// </summary>
        /// <remarks>0x22000136</remarks>
        BcdOSLoaderString_KernelDebuggerNetKey = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_STRING, 310),
        /// <summary>
        ///
        /// </summary>
        /// <remarks>0x22000137</remarks>
        BcdOSLoaderString_IMCHiveName = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_STRING, 311),
        /// <summary>
        ///
        /// </summary>
        /// <remarks>0x21000138</remarks>
        BcdOSLoaderDevice_IMCDevice = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_DEVICE, 312),
        /// <summary>
        ///
        /// </summary>
        /// <remarks>0x25000139</remarks>
        BcdOSLoaderInteger_KernelDebuggerBaudrate = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_INTEGER, 313),
        /// <summary>
        ///
        /// </summary>
        /// <remarks>0x22000140</remarks>
        BcdOSLoaderString_ManufacturingMode = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_STRING, 320),
        /// <summary>
        ///
        /// </summary>
        /// <remarks>0x26000141</remarks>
        BcdOSLoaderBoolean_EventLoggingEnabled = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_BOOLEAN, 321),
        /// <summary>
        ///
        /// </summary>
        /// <remarks>0x25000142</remarks>
        BcdOSLoaderInteger_VsmLaunchType = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_INTEGER, 322),
        /// <summary>
        /// Undocumented. Zero (0) indicates default, one (1) indicates that disabled and two (2) indicates strict mode.
        /// </summary>
        /// <remarks>0x25000144</remarks>
        BcdOSLoaderInteger_HypervisorEnforcedCodeIntegrity = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_INTEGER, 324),
        /// <summary>
        ///
        /// </summary>
        /// <remarks>0x26000145</remarks>
        BcdOSLoaderBoolean_DtraceEnabled = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_BOOLEAN, 325),
        /// <summary>
        ///
        /// </summary>
        /// <remarks>0x21000150</remarks>
        BcdOSLoaderDevice_SystemDataDevice = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_DEVICE, 336),
        /// <summary>
        ///
        /// </summary>
        /// <remarks>0x21000151</remarks>
        BcdOSLoaderDevice_OsArcDevice = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_DEVICE, 337),
        /// <summary>
        ///
        /// </summary>
        /// <remarks>0x21000153</remarks>
        BcdOSLoaderDevice_OsDataDevice = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_DEVICE, 339),
        /// <summary>
        ///
        /// </summary>
        /// <remarks>0x21000154</remarks>
        BcdOSLoaderDevice_BspDevice = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_DEVICE, 340),
        /// <summary>
        ///
        /// </summary>
        /// <remarks>0x21000155</remarks>
        BcdOSLoaderDevice_BspFilepath = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_DEVICE, 341),
        /// <summary>
        ///
        /// </summary>
        /// <remarks>0x22000156</remarks>
        BcdOSLoaderString_KernelDebuggerNetHostIpv6 = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_STRING, 342),
        /// <summary>
        ///
        /// </summary>
        /// <remarks>0x22000161</remarks>
        BcdOSLoaderString_HypervisorDebuggerNetHostIpv6 = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_STRING, 353),
    } BcdOSLoaderElementTypes;

#endif
    /*
     * Memory Manager Support functions
     *
     * This file is part of System Informer.
     */

#ifndef _NTMMAPI_H
#define _NTMMAPI_H

     // Protection constants

#define PAGE_NOACCESS 0x01
#define PAGE_READONLY 0x02
#define PAGE_READWRITE 0x04
#define PAGE_WRITECOPY 0x08
#define PAGE_EXECUTE 0x10
#define PAGE_EXECUTE_READ 0x20
#define PAGE_EXECUTE_READWRITE 0x40
#define PAGE_EXECUTE_WRITECOPY 0x80
#define PAGE_GUARD 0x100
#define PAGE_NOCACHE 0x200
#define PAGE_WRITECOMBINE 0x400

#define PAGE_REVERT_TO_FILE_MAP     0x80000000
#define PAGE_ENCLAVE_THREAD_CONTROL 0x80000000
#define PAGE_TARGETS_NO_UPDATE      0x40000000
#define PAGE_TARGETS_INVALID        0x40000000
#define PAGE_ENCLAVE_UNVALIDATED    0x20000000
#define PAGE_ENCLAVE_NO_CHANGE      0x20000000
#define PAGE_ENCLAVE_MASK           0x10000000
#define PAGE_ENCLAVE_DECOMMIT       (PAGE_ENCLAVE_MASK | 0)
#define PAGE_ENCLAVE_SS_FIRST       (PAGE_ENCLAVE_MASK | 1)
#define PAGE_ENCLAVE_SS_REST        (PAGE_ENCLAVE_MASK | 2)

// Region and section constants

#define MEM_COMMIT 0x00001000
#define MEM_RESERVE 0x00002000
#define MEM_DECOMMIT 0x00004000
#define MEM_RELEASE 0x00008000
#define MEM_FREE 0x00010000
#define MEM_PRIVATE 0x00020000
#define MEM_MAPPED 0x00040000
#define MEM_RESET 0x00080000
#define MEM_TOP_DOWN 0x00100000
#define MEM_WRITE_WATCH 0x00200000
#define MEM_PHYSICAL 0x00400000
#define MEM_ROTATE 0x00800000
#define MEM_DIFFERENT_IMAGE_BASE_OK 0x00800000
#define MEM_RESET_UNDO 0x01000000
#define MEM_LARGE_PAGES 0x20000000
#define MEM_DOS_LIM 0x40000000
#define MEM_4MB_PAGES 0x80000000
#define MEM_64K_PAGES (MEM_LARGE_PAGES | MEM_PHYSICAL)

#define MEM_UNMAP_WITH_TRANSIENT_BOOST 0x00000001
#define MEM_COALESCE_PLACEHOLDERS 0x00000001
#define MEM_PRESERVE_PLACEHOLDER 0x00000002
#define MEM_REPLACE_PLACEHOLDER 0x00004000
#define MEM_RESERVE_PLACEHOLDER 0x00040000

#define SEC_HUGE_PAGES 0x00020000
#define SEC_PARTITION_OWNER_HANDLE 0x00040000
#define SEC_64K_PAGES 0x00080000
#define SEC_BASED 0x00200000
#define SEC_NO_CHANGE 0x00400000
#define SEC_FILE 0x00800000
#define SEC_IMAGE 0x01000000
#define SEC_PROTECTED_IMAGE 0x02000000
#define SEC_RESERVE 0x04000000
#define SEC_COMMIT 0x08000000
#define SEC_NOCACHE 0x10000000
#define SEC_GLOBAL 0x20000000
#define SEC_WRITECOMBINE 0x40000000
#define SEC_LARGE_PAGES 0x80000000
#define SEC_IMAGE_NO_EXECUTE (SEC_IMAGE | SEC_NOCACHE)
#if (PHNT_MODE == PHNT_MODE_KERNEL)
#define MEM_IMAGE SEC_IMAGE
#endif

#if (PHNT_MODE != PHNT_MODE_KERNEL)
    typedef enum _MEMORY_INFORMATION_CLASS
    {
        MemoryBasicInformation, // q: MEMORY_BASIC_INFORMATION
        MemoryWorkingSetInformation, // q: MEMORY_WORKING_SET_INFORMATION
        MemoryMappedFilenameInformation, // q: UNICODE_STRING
        MemoryRegionInformation, // q: MEMORY_REGION_INFORMATION
        MemoryWorkingSetExInformation, // q: MEMORY_WORKING_SET_EX_INFORMATION // since VISTA
        MemorySharedCommitInformation, // q: MEMORY_SHARED_COMMIT_INFORMATION // since WIN8
        MemoryImageInformation, // q: MEMORY_IMAGE_INFORMATION
        MemoryRegionInformationEx, // MEMORY_REGION_INFORMATION
        MemoryPrivilegedBasicInformation, // MEMORY_BASIC_INFORMATION
        MemoryEnclaveImageInformation, // MEMORY_ENCLAVE_IMAGE_INFORMATION // since REDSTONE3
        MemoryBasicInformationCapped, // 10
        MemoryPhysicalContiguityInformation, // MEMORY_PHYSICAL_CONTIGUITY_INFORMATION // since 20H1
        MemoryBadInformation, // since WIN11
        MemoryBadInformationAllProcesses, // since 22H1
        MaxMemoryInfoClass
    } MEMORY_INFORMATION_CLASS;
#else
#define MemoryBasicInformation 0x0
#define MemoryWorkingSetInformation 0x1
#define MemoryMappedFilenameInformation 0x2
#define MemoryRegionInformation 0x3
#define MemoryWorkingSetExInformation 0x4
#define MemorySharedCommitInformation 0x5
#define MemoryImageInformation 0x6
#define MemoryRegionInformationEx 0x7
#define MemoryPrivilegedBasicInformation 0x8
#define MemoryEnclaveImageInformation 0x9
#define MemoryBasicInformationCapped 0xA
#define MemoryPhysicalContiguityInformation 0xB
#define MemoryBadInformation 0xC
#define MemoryBadInformationAllProcesses 0xD
#endif

    typedef struct _MEMORY_WORKING_SET_BLOCK
    {
        ULONG_PTR Protection : 5;
        ULONG_PTR ShareCount : 3;
        ULONG_PTR Shared : 1;
        ULONG_PTR Node : 3;
#ifdef _WIN64
        ULONG_PTR VirtualPage : 52;
#else
        ULONG VirtualPage : 20;
#endif
    } MEMORY_WORKING_SET_BLOCK, * PMEMORY_WORKING_SET_BLOCK;

    typedef struct _MEMORY_WORKING_SET_INFORMATION
    {
        ULONG_PTR NumberOfEntries;
        _Field_size_(NumberOfEntries) MEMORY_WORKING_SET_BLOCK WorkingSetInfo[1];
    } MEMORY_WORKING_SET_INFORMATION, * PMEMORY_WORKING_SET_INFORMATION;

    // private
    typedef struct _MEMORY_REGION_INFORMATION
    {
        PVOID AllocationBase;
        ULONG AllocationProtect;
        union
        {
            ULONG RegionType;
            struct
            {
                ULONG Private : 1;
                ULONG MappedDataFile : 1;
                ULONG MappedImage : 1;
                ULONG MappedPageFile : 1;
                ULONG MappedPhysical : 1;
                ULONG DirectMapped : 1;
                ULONG SoftwareEnclave : 1; // REDSTONE3
                ULONG PageSize64K : 1;
                ULONG PlaceholderReservation : 1; // REDSTONE4
                ULONG MappedAwe : 1; // 21H1
                ULONG MappedWriteWatch : 1;
                ULONG PageSizeLarge : 1;
                ULONG PageSizeHuge : 1;
                ULONG Reserved : 19;
            };
        };
        SIZE_T RegionSize;
        SIZE_T CommitSize;
        ULONG_PTR PartitionId; // 19H1
        ULONG_PTR NodePreference; // 20H1
    } MEMORY_REGION_INFORMATION, * PMEMORY_REGION_INFORMATION;

    // private
    typedef enum _MEMORY_WORKING_SET_EX_LOCATION
    {
        MemoryLocationInvalid,
        MemoryLocationResident,
        MemoryLocationPagefile,
        MemoryLocationReserved
    } MEMORY_WORKING_SET_EX_LOCATION;

    // private
    typedef struct _MEMORY_WORKING_SET_EX_BLOCK
    {
        union
        {
            struct
            {
                ULONG_PTR Valid : 1;
                ULONG_PTR ShareCount : 3;
                ULONG_PTR Win32Protection : 11;
                ULONG_PTR Shared : 1;
                ULONG_PTR Node : 6;
                ULONG_PTR Locked : 1;
                ULONG_PTR LargePage : 1;
                ULONG_PTR Priority : 3;
                ULONG_PTR Reserved : 3;
                ULONG_PTR SharedOriginal : 1;
                ULONG_PTR Bad : 1;
                ULONG_PTR Win32GraphicsProtection : 4; // 19H1
#ifdef _WIN64
                ULONG_PTR ReservedUlong : 28;
#endif
            };
            struct
            {
                ULONG_PTR Valid : 1;
                ULONG_PTR Reserved0 : 14;
                ULONG_PTR Shared : 1;
                ULONG_PTR Reserved1 : 5;
                ULONG_PTR PageTable : 1;
                ULONG_PTR Location : 2;
                ULONG_PTR Priority : 3;
                ULONG_PTR ModifiedList : 1;
                ULONG_PTR Reserved2 : 2;
                ULONG_PTR SharedOriginal : 1;
                ULONG_PTR Bad : 1;
#ifdef _WIN64
                ULONG_PTR ReservedUlong : 32;
#endif
            } Invalid;
        };
    } MEMORY_WORKING_SET_EX_BLOCK, * PMEMORY_WORKING_SET_EX_BLOCK;

    // private
    typedef struct _MEMORY_WORKING_SET_EX_INFORMATION
    {
        PVOID VirtualAddress;
        union
        {
            MEMORY_WORKING_SET_EX_BLOCK VirtualAttributes;
            ULONG_PTR Long;
        } u1;
    } MEMORY_WORKING_SET_EX_INFORMATION, * PMEMORY_WORKING_SET_EX_INFORMATION;

    // private
    typedef struct _MEMORY_SHARED_COMMIT_INFORMATION
    {
        SIZE_T CommitSize;
    } MEMORY_SHARED_COMMIT_INFORMATION, * PMEMORY_SHARED_COMMIT_INFORMATION;

    // private
    typedef struct _MEMORY_IMAGE_INFORMATION
    {
        PVOID ImageBase;
        SIZE_T SizeOfImage;
        union
        {
            ULONG ImageFlags;
            struct
            {
                ULONG ImagePartialMap : 1;
                ULONG ImageNotExecutable : 1;
                ULONG ImageSigningLevel : 4; // REDSTONE3
                ULONG Reserved : 26;
            };
        };
    } MEMORY_IMAGE_INFORMATION, * PMEMORY_IMAGE_INFORMATION;

    // private
    typedef struct _MEMORY_ENCLAVE_IMAGE_INFORMATION
    {
        MEMORY_IMAGE_INFORMATION ImageInfo;
        UCHAR UniqueID[32];
        UCHAR AuthorID[32];
    } MEMORY_ENCLAVE_IMAGE_INFORMATION, * PMEMORY_ENCLAVE_IMAGE_INFORMATION;

    // private
    typedef enum _MEMORY_PHYSICAL_CONTIGUITY_UNIT_STATE
    {
        MemoryNotContiguous,
        MemoryAlignedAndContiguous,
        MemoryNotResident,
        MemoryNotEligibleToMakeContiguous,
        MemoryContiguityStateMax,
    } MEMORY_PHYSICAL_CONTIGUITY_UNIT_STATE;

    // private
    typedef struct _MEMORY_PHYSICAL_CONTIGUITY_UNIT_INFORMATION
    {
        union
        {
            struct
            {
                ULONG State : 2;
                ULONG Reserved : 30;
            };
            ULONG AllInformation;
        };
    } MEMORY_PHYSICAL_CONTIGUITY_UNIT_INFORMATION, * PMEMORY_PHYSICAL_CONTIGUITY_UNIT_INFORMATION;

    // private
    typedef struct _MEMORY_PHYSICAL_CONTIGUITY_INFORMATION
    {
        PVOID VirtualAddress;
        ULONG_PTR Size;
        ULONG_PTR ContiguityUnitSize;
        ULONG Flags;
        PMEMORY_PHYSICAL_CONTIGUITY_UNIT_INFORMATION ContiguityUnitInformation;
    } MEMORY_PHYSICAL_CONTIGUITY_INFORMATION, * PMEMORY_PHYSICAL_CONTIGUITY_INFORMATION;

#define MMPFNLIST_ZERO 0
#define MMPFNLIST_FREE 1
#define MMPFNLIST_STANDBY 2
#define MMPFNLIST_MODIFIED 3
#define MMPFNLIST_MODIFIEDNOWRITE 4
#define MMPFNLIST_BAD 5
#define MMPFNLIST_ACTIVE 6
#define MMPFNLIST_TRANSITION 7

    //typedef enum _MMLISTS
    //{
    //    ZeroedPageList = 0,
    //    FreePageList = 1,
    //    StandbyPageList = 2,
    //    ModifiedPageList = 3,
    //    ModifiedNoWritePageList = 4,
    //    BadPageList = 5,
    //    ActiveAndValid = 6,
    //    TransitionPage = 7
    //} MMLISTS;

#define MMPFNUSE_PROCESSPRIVATE 0
#define MMPFNUSE_FILE 1
#define MMPFNUSE_PAGEFILEMAPPED 2
#define MMPFNUSE_PAGETABLE 3
#define MMPFNUSE_PAGEDPOOL 4
#define MMPFNUSE_NONPAGEDPOOL 5
#define MMPFNUSE_SYSTEMPTE 6
#define MMPFNUSE_SESSIONPRIVATE 7
#define MMPFNUSE_METAFILE 8
#define MMPFNUSE_AWEPAGE 9
#define MMPFNUSE_DRIVERLOCKPAGE 10
#define MMPFNUSE_KERNELSTACK 11

//typedef enum _MMPFNUSE
//{
//    ProcessPrivatePage,
//    MemoryMappedFilePage,
//    PageFileMappedPage,
//    PageTablePage,
//    PagedPoolPage,
//    NonPagedPoolPage,
//    SystemPTEPage,
//    SessionPrivatePage,
//    MetafilePage,
//    AWEPage,
//    DriverLockedPage,
//    KernelStackPage
//} MMPFNUSE;

// private
    typedef struct _MEMORY_FRAME_INFORMATION
    {
        ULONGLONG UseDescription : 4; // MMPFNUSE_*
        ULONGLONG ListDescription : 3; // MMPFNLIST_*
        ULONGLONG Cold : 1; // 19H1
        ULONGLONG Pinned : 1; // 1 - pinned, 0 - not pinned
        ULONGLONG DontUse : 48; // *_INFORMATION overlay
        ULONGLONG Priority : 3;
        ULONGLONG NonTradeable : 1;
        ULONGLONG Reserved : 3;
    } MEMORY_FRAME_INFORMATION;

    // private
    typedef struct _FILEOFFSET_INFORMATION
    {
        ULONGLONG DontUse : 9; // MEMORY_FRAME_INFORMATION overlay
        ULONGLONG Offset : 48; // mapped files
        ULONGLONG Reserved : 7;
    } FILEOFFSET_INFORMATION;

    // private
    typedef struct _PAGEDIR_INFORMATION
    {
        ULONGLONG DontUse : 9; // MEMORY_FRAME_INFORMATION overlay
        ULONGLONG PageDirectoryBase : 48; // private pages
        ULONGLONG Reserved : 7;
    } PAGEDIR_INFORMATION;

    // private
    typedef struct _UNIQUE_PROCESS_INFORMATION
    {
        ULONGLONG DontUse : 9; // MEMORY_FRAME_INFORMATION overlay
        ULONGLONG UniqueProcessKey : 48; // ProcessId
        ULONGLONG Reserved : 7;
    } UNIQUE_PROCESS_INFORMATION, * PUNIQUE_PROCESS_INFORMATION;

    // private
    typedef struct _MMPFN_IDENTITY
    {
        union
        {
            MEMORY_FRAME_INFORMATION e1; // all
            FILEOFFSET_INFORMATION e2; // mapped files
            PAGEDIR_INFORMATION e3; // private pages
            UNIQUE_PROCESS_INFORMATION e4; // owning process
        } u1;
        ULONG_PTR PageFrameIndex; // all
        union
        {
            struct
            {
                ULONG_PTR Image : 1;
                ULONG_PTR Mismatch : 1;
            } e1;
            struct
            {
                ULONG_PTR CombinedPage;
            } e2;
            ULONG_PTR FileObject; // mapped files
            ULONG_PTR UniqueFileObjectKey;
            ULONG_PTR ProtoPteAddress;
            ULONG_PTR VirtualAddress;  // everything else
        } u2;
    } MMPFN_IDENTITY, * PMMPFN_IDENTITY;

    typedef struct _MMPFN_MEMSNAP_INFORMATION
    {
        ULONG_PTR InitialPageFrameIndex;
        ULONG_PTR Count;
    } MMPFN_MEMSNAP_INFORMATION, * PMMPFN_MEMSNAP_INFORMATION;

    typedef enum _SECTION_INFORMATION_CLASS
    {
        SectionBasicInformation, // q; SECTION_BASIC_INFORMATION
        SectionImageInformation, // q; SECTION_IMAGE_INFORMATION
        SectionRelocationInformation, // q; ULONG_PTR RelocationDelta // name:wow64:whNtQuerySection_SectionRelocationInformation // since WIN7
        SectionOriginalBaseInformation, // q; PVOID BaseAddress // since REDSTONE
        SectionInternalImageInformation, // SECTION_INTERNAL_IMAGE_INFORMATION // since REDSTONE2
        MaxSectionInfoClass
    } SECTION_INFORMATION_CLASS;

    typedef struct _SECTION_BASIC_INFORMATION
    {
        PVOID BaseAddress;
        ULONG AllocationAttributes;
        LARGE_INTEGER MaximumSize;
    } SECTION_BASIC_INFORMATION, * PSECTION_BASIC_INFORMATION;

    // symbols
    typedef struct _SECTION_IMAGE_INFORMATION
    {
        PVOID TransferAddress;
        ULONG ZeroBits;
        SIZE_T MaximumStackSize;
        SIZE_T CommittedStackSize;
        ULONG SubSystemType;
        union
        {
            struct
            {
                USHORT SubSystemMinorVersion;
                USHORT SubSystemMajorVersion;
            };
            ULONG SubSystemVersion;
        };
        union
        {
            struct
            {
                USHORT MajorOperatingSystemVersion;
                USHORT MinorOperatingSystemVersion;
            };
            ULONG OperatingSystemVersion;
        };
        USHORT ImageCharacteristics;
        USHORT DllCharacteristics;
        USHORT Machine;
        BOOLEAN ImageContainsCode;
        union
        {
            UCHAR ImageFlags;
            struct
            {
                UCHAR ComPlusNativeReady : 1;
                UCHAR ComPlusILOnly : 1;
                UCHAR ImageDynamicallyRelocated : 1;
                UCHAR ImageMappedFlat : 1;
                UCHAR BaseBelow4gb : 1;
                UCHAR ComPlusPrefer32bit : 1;
                UCHAR Reserved : 2;
            };
        };
        ULONG LoaderFlags;
        ULONG ImageFileSize;
        ULONG CheckSum;
    } SECTION_IMAGE_INFORMATION, * PSECTION_IMAGE_INFORMATION;

    // symbols
    typedef struct _SECTION_INTERNAL_IMAGE_INFORMATION
    {
        SECTION_IMAGE_INFORMATION SectionInformation;
        union
        {
            ULONG ExtendedFlags;
            struct
            {
                ULONG ImageExportSuppressionEnabled : 1;
                ULONG ImageCetShadowStacksReady : 1; // 20H1
                ULONG ImageXfgEnabled : 1; // 20H2
                ULONG ImageCetShadowStacksStrictMode : 1;
                ULONG ImageCetSetContextIpValidationRelaxedMode : 1;
                ULONG ImageCetDynamicApisAllowInProc : 1;
                ULONG ImageCetDowngradeReserved1 : 1;
                ULONG ImageCetDowngradeReserved2 : 1;
                ULONG Reserved : 24;
            };
        };
    } SECTION_INTERNAL_IMAGE_INFORMATION, * PSECTION_INTERNAL_IMAGE_INFORMATION;

#if (PHNT_MODE != PHNT_MODE_KERNEL)
    typedef enum _SECTION_INHERIT
    {
        ViewShare = 1,
        ViewUnmap = 2
    } SECTION_INHERIT;
#endif

#define MEM_EXECUTE_OPTION_ENABLE 0x1
#define MEM_EXECUTE_OPTION_DISABLE 0x2
#define MEM_EXECUTE_OPTION_DISABLE_THUNK_EMULATION 0x4
#define MEM_EXECUTE_OPTION_PERMANENT 0x8
#define MEM_EXECUTE_OPTION_EXECUTE_DISPATCH_ENABLE 0x10
#define MEM_EXECUTE_OPTION_IMAGE_DISPATCH_ENABLE 0x20
#define MEM_EXECUTE_OPTION_VALID_FLAGS 0x3f

    // Virtual memory

#if (PHNT_MODE != PHNT_MODE_KERNEL)

    _Must_inspect_result_
        _When_(return == 0, __drv_allocatesMem(mem))
        NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtAllocateVirtualMemory(
            _In_ HANDLE ProcessHandle,
            _Inout_ _At_(*BaseAddress, _Readable_bytes_(*RegionSize) _Writable_bytes_(*RegionSize) _Post_readable_byte_size_(*RegionSize)) PVOID* BaseAddress,
            _In_ ULONG_PTR ZeroBits,
            _Inout_ PSIZE_T RegionSize,
            _In_ ULONG AllocationType,
            _In_ ULONG Protect
        );

#if (PHNT_VERSION >= PHNT_REDSTONE5)

    _Must_inspect_result_
        _When_(return == 0, __drv_allocatesMem(mem))
        NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtAllocateVirtualMemoryEx(
            _In_ HANDLE ProcessHandle,
            _Inout_ _At_(*BaseAddress, _Readable_bytes_(*RegionSize) _Writable_bytes_(*RegionSize) _Post_readable_byte_size_(*RegionSize)) PVOID* BaseAddress,
            _Inout_ PSIZE_T RegionSize,
            _In_ ULONG AllocationType,
            _In_ ULONG PageProtection,
            _Inout_updates_opt_(ExtendedParameterCount) PMEM_EXTENDED_PARAMETER ExtendedParameters,
            _In_ ULONG ExtendedParameterCount
        );

#endif

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtFreeVirtualMemory(
            _In_ HANDLE ProcessHandle,
            _Inout_ PVOID* BaseAddress,
            _Inout_ PSIZE_T RegionSize,
            _In_ ULONG FreeType
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtReadVirtualMemory(
            _In_ HANDLE ProcessHandle,
            _In_opt_ PVOID BaseAddress,
            _Out_writes_bytes_(BufferSize) PVOID Buffer,
            _In_ SIZE_T BufferSize,
            _Out_opt_ PSIZE_T NumberOfBytesRead
        );

#if (PHNT_VERSION >= PHNT_WIN11)
    // rev
    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtReadVirtualMemoryEx(
            _In_ HANDLE ProcessHandle,
            _In_opt_ PVOID BaseAddress,
            _Out_writes_bytes_(BufferSize) PVOID Buffer,
            _In_ SIZE_T BufferSize,
            _Out_opt_ PSIZE_T NumberOfBytesRead,
            _In_ ULONG Flags
        );
#endif

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtWriteVirtualMemory(
            _In_ HANDLE ProcessHandle,
            _In_opt_ PVOID BaseAddress,
            _In_reads_bytes_(BufferSize) PVOID Buffer,
            _In_ SIZE_T BufferSize,
            _Out_opt_ PSIZE_T NumberOfBytesWritten
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtProtectVirtualMemory(
            _In_ HANDLE ProcessHandle,
            _Inout_ PVOID* BaseAddress,
            _Inout_ PSIZE_T RegionSize,
            _In_ ULONG NewProtect,
            _Out_ PULONG OldProtect
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtQueryVirtualMemory(
            _In_ HANDLE ProcessHandle,
            _In_opt_ PVOID BaseAddress,
            _In_ MEMORY_INFORMATION_CLASS MemoryInformationClass,
            _Out_writes_bytes_(MemoryInformationLength) PVOID MemoryInformation,
            _In_ SIZE_T MemoryInformationLength,
            _Out_opt_ PSIZE_T ReturnLength
        );

    typedef struct _IO_STATUS_BLOCK* PIO_STATUS_BLOCK;

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtFlushVirtualMemory(
            _In_ HANDLE ProcessHandle,
            _Inout_ PVOID* BaseAddress,
            _Inout_ PSIZE_T RegionSize,
            _Out_ PIO_STATUS_BLOCK IoStatus
        );

#endif

    // begin_private
#if (PHNT_MODE != PHNT_MODE_KERNEL)
    typedef enum _VIRTUAL_MEMORY_INFORMATION_CLASS
    {
        VmPrefetchInformation, // ULONG
        VmPagePriorityInformation, // OFFER_PRIORITY
        VmCfgCallTargetInformation, // CFG_CALL_TARGET_LIST_INFORMATION // REDSTONE2
        VmPageDirtyStateInformation, // REDSTONE3
        VmImageHotPatchInformation, // 19H1
        VmPhysicalContiguityInformation, // 20H1
        VmVirtualMachinePrepopulateInformation,
        VmRemoveFromWorkingSetInformation,
        MaxVmInfoClass
    } VIRTUAL_MEMORY_INFORMATION_CLASS;
#else
#define VmPrefetchInformation 0x0
#define VmPagePriorityInformation 0x1
#define VmCfgCallTargetInformation 0x2
#define VmPageDirtyStateInformation 0x3
#define VmImageHotPatchInformation 0x4
#define VmPhysicalContiguityInformation 0x5
#define VmVirtualMachinePrepopulateInformation 0x6
#define VmRemoveFromWorkingSetInformation 0x7
#define MaxVmInfoClass 0x8
#endif

#if (PHNT_MODE != PHNT_MODE_KERNEL)
    typedef struct _MEMORY_RANGE_ENTRY
    {
        PVOID VirtualAddress;
        SIZE_T NumberOfBytes;
    } MEMORY_RANGE_ENTRY, * PMEMORY_RANGE_ENTRY;

    typedef struct _CFG_CALL_TARGET_LIST_INFORMATION
    {
        ULONG NumberOfEntries;
        ULONG Reserved;
        PULONG NumberOfEntriesProcessed;
        PCFG_CALL_TARGET_INFO CallTargetInfo;
        PVOID Section; // since REDSTONE5
        ULONGLONG FileOffset;
    } CFG_CALL_TARGET_LIST_INFORMATION, * PCFG_CALL_TARGET_LIST_INFORMATION;
#endif
    // end_private

#if (PHNT_MODE != PHNT_MODE_KERNEL)

#if (PHNT_VERSION >= PHNT_WIN8)

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtSetInformationVirtualMemory(
            _In_ HANDLE ProcessHandle,
            _In_ VIRTUAL_MEMORY_INFORMATION_CLASS VmInformationClass,
            _In_ ULONG_PTR NumberOfEntries,
            _In_reads_(NumberOfEntries) PMEMORY_RANGE_ENTRY VirtualAddresses,
            _In_reads_bytes_(VmInformationLength) PVOID VmInformation,
            _In_ ULONG VmInformationLength
        );

#endif

#define MAP_PROCESS 1
#define MAP_SYSTEM 2

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtLockVirtualMemory(
            _In_ HANDLE ProcessHandle,
            _Inout_ PVOID* BaseAddress,
            _Inout_ PSIZE_T RegionSize,
            _In_ ULONG MapType
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtUnlockVirtualMemory(
            _In_ HANDLE ProcessHandle,
            _Inout_ PVOID* BaseAddress,
            _Inout_ PSIZE_T RegionSize,
            _In_ ULONG MapType
        );

#endif

    // Sections

#if (PHNT_MODE != PHNT_MODE_KERNEL)

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtCreateSection(
            _Out_ PHANDLE SectionHandle,
            _In_ ACCESS_MASK DesiredAccess,
            _In_opt_ POBJECT_ATTRIBUTES ObjectAttributes,
            _In_opt_ PLARGE_INTEGER MaximumSize,
            _In_ ULONG SectionPageProtection,
            _In_ ULONG AllocationAttributes,
            _In_opt_ HANDLE FileHandle
        );

#if (PHNT_VERSION >= PHNT_REDSTONE5)
    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtCreateSectionEx(
            _Out_ PHANDLE SectionHandle,
            _In_ ACCESS_MASK DesiredAccess,
            _In_opt_ POBJECT_ATTRIBUTES ObjectAttributes,
            _In_opt_ PLARGE_INTEGER MaximumSize,
            _In_ ULONG SectionPageProtection,
            _In_ ULONG AllocationAttributes,
            _In_opt_ HANDLE FileHandle,
            _Inout_updates_opt_(ExtendedParameterCount) PMEM_EXTENDED_PARAMETER ExtendedParameters,
            _In_ ULONG ExtendedParameterCount
        );
#endif

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtOpenSection(
            _Out_ PHANDLE SectionHandle,
            _In_ ACCESS_MASK DesiredAccess,
            _In_ POBJECT_ATTRIBUTES ObjectAttributes
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtMapViewOfSection(
            _In_ HANDLE SectionHandle,
            _In_ HANDLE ProcessHandle,
            _Inout_ _At_(*BaseAddress, _Readable_bytes_(*ViewSize) _Writable_bytes_(*ViewSize) _Post_readable_byte_size_(*ViewSize)) PVOID* BaseAddress,
            _In_ ULONG_PTR ZeroBits,
            _In_ SIZE_T CommitSize,
            _Inout_opt_ PLARGE_INTEGER SectionOffset,
            _Inout_ PSIZE_T ViewSize,
            _In_ SECTION_INHERIT InheritDisposition,
            _In_ ULONG AllocationType,
            _In_ ULONG Win32Protect
        );

#if (PHNT_VERSION >= PHNT_REDSTONE5)
    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtMapViewOfSectionEx(
            _In_ HANDLE SectionHandle,
            _In_ HANDLE ProcessHandle,
            _Inout_ _At_(*BaseAddress, _Readable_bytes_(*ViewSize) _Writable_bytes_(*ViewSize) _Post_readable_byte_size_(*ViewSize)) PVOID* BaseAddress,
            _Inout_opt_ PLARGE_INTEGER SectionOffset,
            _Inout_ PSIZE_T ViewSize,
            _In_ ULONG AllocationType,
            _In_ ULONG Win32Protect,
            _Inout_updates_opt_(ExtendedParameterCount) PMEM_EXTENDED_PARAMETER ExtendedParameters,
            _In_ ULONG ExtendedParameterCount
        );
#endif

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtUnmapViewOfSection(
            _In_ HANDLE ProcessHandle,
            _In_opt_ PVOID BaseAddress
        );

#if (PHNT_VERSION >= PHNT_WIN8)
    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtUnmapViewOfSectionEx(
            _In_ HANDLE ProcessHandle,
            _In_opt_ PVOID BaseAddress,
            _In_ ULONG Flags
        );
#endif

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtExtendSection(
            _In_ HANDLE SectionHandle,
            _Inout_ PLARGE_INTEGER NewSectionSize
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtQuerySection(
            _In_ HANDLE SectionHandle,
            _In_ SECTION_INFORMATION_CLASS SectionInformationClass,
            _Out_writes_bytes_(SectionInformationLength) PVOID SectionInformation,
            _In_ SIZE_T SectionInformationLength,
            _Out_opt_ PSIZE_T ReturnLength
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtAreMappedFilesTheSame(
            _In_ PVOID File1MappedAsAnImage,
            _In_ PVOID File2MappedAsFile
        );

#endif

    // Partitions

#ifndef MEMORY_PARTITION_QUERY_ACCESS
#define MEMORY_PARTITION_QUERY_ACCESS 0x0001
#define MEMORY_PARTITION_MODIFY_ACCESS 0x0002
#define MEMORY_PARTITION_ALL_ACCESS \
    (STANDARD_RIGHTS_REQUIRED | SYNCHRONIZE | \
     MEMORY_PARTITION_QUERY_ACCESS | MEMORY_PARTITION_MODIFY_ACCESS)
#endif

#if (PHNT_MODE != PHNT_MODE_KERNEL)
// private
    typedef enum _PARTITION_INFORMATION_CLASS
    {
        SystemMemoryPartitionInformation, // q: MEMORY_PARTITION_CONFIGURATION_INFORMATION
        SystemMemoryPartitionMoveMemory, // s: MEMORY_PARTITION_TRANSFER_INFORMATION
        SystemMemoryPartitionAddPagefile, // s: MEMORY_PARTITION_PAGEFILE_INFORMATION
        SystemMemoryPartitionCombineMemory, // q; s: MEMORY_PARTITION_PAGE_COMBINE_INFORMATION
        SystemMemoryPartitionInitialAddMemory, // q; s: MEMORY_PARTITION_INITIAL_ADD_INFORMATION
        SystemMemoryPartitionGetMemoryEvents, // MEMORY_PARTITION_MEMORY_EVENTS_INFORMATION // since REDSTONE2
        SystemMemoryPartitionSetAttributes,
        SystemMemoryPartitionNodeInformation,
        SystemMemoryPartitionCreateLargePages,
        SystemMemoryPartitionDedicatedMemoryInformation,
        SystemMemoryPartitionOpenDedicatedMemory, // 10
        SystemMemoryPartitionMemoryChargeAttributes,
        SystemMemoryPartitionClearAttributes,
        SystemMemoryPartitionSetMemoryThresholds, // since WIN11
        SystemMemoryPartitionMax
    } PARTITION_INFORMATION_CLASS, * PPARTITION_INFORMATION_CLASS;
#else
#define SystemMemoryPartitionInformation 0x0
#define SystemMemoryPartitionMoveMemory 0x1
#define SystemMemoryPartitionAddPagefile 0x2
#define SystemMemoryPartitionCombineMemory 0x3
#define SystemMemoryPartitionInitialAddMemory 0x4
#define SystemMemoryPartitionGetMemoryEvents 0x5
#define SystemMemoryPartitionSetAttributes 0x6
#define SystemMemoryPartitionNodeInformation 0x7
#define SystemMemoryPartitionCreateLargePages 0x8
#define SystemMemoryPartitionDedicatedMemoryInformation 0x9
#define SystemMemoryPartitionOpenDedicatedMemory 0xA
#define SystemMemoryPartitionMemoryChargeAttributes 0xB
#define SystemMemoryPartitionClearAttributes 0xC
#define SystemMemoryPartitionSetMemoryThresholds 0xD
#define SystemMemoryPartitionMax 0xE
#endif

// private
    typedef struct _MEMORY_PARTITION_CONFIGURATION_INFORMATION
    {
        ULONG Flags;
        ULONG NumaNode;
        ULONG Channel;
        ULONG NumberOfNumaNodes;
        ULONG_PTR ResidentAvailablePages;
        ULONG_PTR CommittedPages;
        ULONG_PTR CommitLimit;
        ULONG_PTR PeakCommitment;
        ULONG_PTR TotalNumberOfPages;
        ULONG_PTR AvailablePages;
        ULONG_PTR ZeroPages;
        ULONG_PTR FreePages;
        ULONG_PTR StandbyPages;
        ULONG_PTR StandbyPageCountByPriority[8]; // since REDSTONE2
        ULONG_PTR RepurposedPagesByPriority[8];
        ULONG_PTR MaximumCommitLimit;
        ULONG_PTR Reserved; // DonatedPagesToPartitions
        ULONG PartitionId; // since REDSTONE3
    } MEMORY_PARTITION_CONFIGURATION_INFORMATION, * PMEMORY_PARTITION_CONFIGURATION_INFORMATION;

    // private
    typedef struct _MEMORY_PARTITION_TRANSFER_INFORMATION
    {
        ULONG_PTR NumberOfPages;
        ULONG NumaNode;
        ULONG Flags;
    } MEMORY_PARTITION_TRANSFER_INFORMATION, * PMEMORY_PARTITION_TRANSFER_INFORMATION;

    // private
    typedef struct _MEMORY_PARTITION_PAGEFILE_INFORMATION
    {
        UNICODE_STRING PageFileName;
        LARGE_INTEGER MinimumSize;
        LARGE_INTEGER MaximumSize;
        ULONG Flags;
    } MEMORY_PARTITION_PAGEFILE_INFORMATION, * PMEMORY_PARTITION_PAGEFILE_INFORMATION;

    // private
    typedef struct _MEMORY_PARTITION_PAGE_COMBINE_INFORMATION
    {
        HANDLE StopHandle;
        ULONG Flags;
        ULONG_PTR TotalNumberOfPages;
    } MEMORY_PARTITION_PAGE_COMBINE_INFORMATION, * PMEMORY_PARTITION_PAGE_COMBINE_INFORMATION;

    // private
    typedef struct _MEMORY_PARTITION_PAGE_RANGE
    {
        ULONG_PTR StartPage;
        ULONG_PTR NumberOfPages;
    } MEMORY_PARTITION_PAGE_RANGE, * PMEMORY_PARTITION_PAGE_RANGE;

    // private
    typedef struct _MEMORY_PARTITION_INITIAL_ADD_INFORMATION
    {
        ULONG Flags;
        ULONG NumberOfRanges;
        ULONG_PTR NumberOfPagesAdded;
        MEMORY_PARTITION_PAGE_RANGE PartitionRanges[1];
    } MEMORY_PARTITION_INITIAL_ADD_INFORMATION, * PMEMORY_PARTITION_INITIAL_ADD_INFORMATION;

    // private
    typedef struct _MEMORY_PARTITION_MEMORY_EVENTS_INFORMATION
    {
        union
        {
            struct
            {
                ULONG CommitEvents : 1;
                ULONG Spare : 31;
            };
            ULONG AllFlags;
        } Flags;

        ULONG HandleAttributes;
        ULONG DesiredAccess;
        HANDLE LowCommitCondition; // \KernelObjects\LowCommitCondition
        HANDLE HighCommitCondition; // \KernelObjects\HighCommitCondition
        HANDLE MaximumCommitCondition; // \KernelObjects\MaximumCommitCondition
    } MEMORY_PARTITION_MEMORY_EVENTS_INFORMATION, * PMEMORY_PARTITION_MEMORY_EVENTS_INFORMATION;

#if (PHNT_MODE != PHNT_MODE_KERNEL)

#if (PHNT_VERSION >= PHNT_THRESHOLD)

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtCreatePartition(
            _In_opt_ HANDLE ParentPartitionHandle,
            _Out_ PHANDLE PartitionHandle,
            _In_ ACCESS_MASK DesiredAccess,
            _In_opt_ POBJECT_ATTRIBUTES ObjectAttributes,
            _In_ ULONG PreferredNode
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtOpenPartition(
            _Out_ PHANDLE PartitionHandle,
            _In_ ACCESS_MASK DesiredAccess,
            _In_ POBJECT_ATTRIBUTES ObjectAttributes
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtManagePartition(
            _In_ HANDLE TargetHandle,
            _In_opt_ HANDLE SourceHandle,
            _In_ PARTITION_INFORMATION_CLASS PartitionInformationClass,
            _Inout_updates_bytes_(PartitionInformationLength) PVOID PartitionInformation,
            _In_ ULONG PartitionInformationLength
        );

#endif

#endif

    // User physical pages

#if (PHNT_MODE != PHNT_MODE_KERNEL)

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtMapUserPhysicalPages(
            _In_ PVOID VirtualAddress,
            _In_ ULONG_PTR NumberOfPages,
            _In_reads_opt_(NumberOfPages) PULONG_PTR UserPfnArray
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtMapUserPhysicalPagesScatter(
            _In_reads_(NumberOfPages) PVOID* VirtualAddresses,
            _In_ ULONG_PTR NumberOfPages,
            _In_reads_opt_(NumberOfPages) PULONG_PTR UserPfnArray
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtAllocateUserPhysicalPages(
            _In_ HANDLE ProcessHandle,
            _Inout_ PULONG_PTR NumberOfPages,
            _Out_writes_(*NumberOfPages) PULONG_PTR UserPfnArray
        );

#if (PHNT_VERSION >= PHNT_THRESHOLD)
    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtAllocateUserPhysicalPagesEx(
            _In_ HANDLE ProcessHandle,
            _Inout_ PULONG_PTR NumberOfPages,
            _Out_writes_(*NumberOfPages) PULONG_PTR UserPfnArray,
            _Inout_updates_opt_(ParameterCount) PMEM_EXTENDED_PARAMETER ExtendedParameters,
            _In_ ULONG ExtendedParameterCount
        );
#endif

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtFreeUserPhysicalPages(
            _In_ HANDLE ProcessHandle,
            _Inout_ PULONG_PTR NumberOfPages,
            _In_reads_(*NumberOfPages) PULONG_PTR UserPfnArray
        );

#endif

    // Misc.

#if (PHNT_MODE != PHNT_MODE_KERNEL)

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtGetWriteWatch(
            _In_ HANDLE ProcessHandle,
            _In_ ULONG Flags,
            _In_ PVOID BaseAddress,
            _In_ SIZE_T RegionSize,
            _Out_writes_(*EntriesInUserAddressArray) PVOID* UserAddressArray,
            _Inout_ PULONG_PTR EntriesInUserAddressArray,
            _Out_ PULONG Granularity
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtResetWriteWatch(
            _In_ HANDLE ProcessHandle,
            _In_ PVOID BaseAddress,
            _In_ SIZE_T RegionSize
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtCreatePagingFile(
            _In_ PUNICODE_STRING PageFileName,
            _In_ PLARGE_INTEGER MinimumSize,
            _In_ PLARGE_INTEGER MaximumSize,
            _In_ ULONG Priority
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtFlushInstructionCache(
            _In_ HANDLE ProcessHandle,
            _In_opt_ PVOID BaseAddress,
            _In_ SIZE_T Length
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtFlushWriteBuffer(
            VOID
        );

#endif

#if (PHNT_VERSION >= PHNT_THRESHOLD)
    // Enclave support

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtCreateEnclave(
            _In_ HANDLE ProcessHandle,
            _Inout_ PVOID* BaseAddress,
            _In_ ULONG_PTR ZeroBits,
            _In_ SIZE_T Size,
            _In_ SIZE_T InitialCommitment,
            _In_ ULONG EnclaveType,
            _In_reads_bytes_(EnclaveInformationLength) PVOID EnclaveInformation,
            _In_ ULONG EnclaveInformationLength,
            _Out_opt_ PULONG EnclaveError
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtLoadEnclaveData(
            _In_ HANDLE ProcessHandle,
            _In_ PVOID BaseAddress,
            _In_reads_bytes_(BufferSize) PVOID Buffer,
            _In_ SIZE_T BufferSize,
            _In_ ULONG Protect,
            _In_reads_bytes_(PageInformationLength) PVOID PageInformation,
            _In_ ULONG PageInformationLength,
            _Out_opt_ PSIZE_T NumberOfBytesWritten,
            _Out_opt_ PULONG EnclaveError
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtInitializeEnclave(
            _In_ HANDLE ProcessHandle,
            _In_ PVOID BaseAddress,
            _In_reads_bytes_(EnclaveInformationLength) PVOID EnclaveInformation,
            _In_ ULONG EnclaveInformationLength,
            _Out_opt_ PULONG EnclaveError
        );

    // rev
#define TERMINATE_ENCLAVE_VALID_FLAGS     0x00000005ul
#define TERMINATE_ENCLAVE_FLAG_NO_WAIT    0x00000001ul
#define TERMINATE_ENCLAVE_FLAG_WAIT_ERROR 0x00000004ul // STATUS_PENDING -> STATUS_ENCLAVE_NOT_TERMINATED

// rev
    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtTerminateEnclave(
            _In_ PVOID BaseAddress,
            _In_ ULONG Flags // TERMINATE_ENCLAVE_FLAG_*
        );

#if (PHNT_MODE != PHNT_MODE_KERNEL)

    // rev
#define ENCLAVE_CALL_VALID_FLAGS  0x00000001ul
#define ENCLAVE_CALL_FLAG_NO_WAIT 0x00000001ul

// rev
    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtCallEnclave(
            _In_ PENCLAVE_ROUTINE Routine,
            _In_ PVOID Reserved,              // reserved for dispatch (RtlEnclaveCallDispatch)
            _In_ ULONG Flags,                 // ENCLAVE_CALL_FLAG_*
            _Inout_ PVOID* RoutineParamReturn // input routine parameter, output routine return value
        );
#endif

#endif

#endif
    /*
     * Object Manager support functions
     *
     * This file is part of System Informer.
     */

#ifndef _NTOBAPI_H
#define _NTOBAPI_H

#if (PHNT_MODE != PHNT_MODE_KERNEL)
#define OBJECT_TYPE_CREATE 0x0001
#define OBJECT_TYPE_ALL_ACCESS (STANDARD_RIGHTS_REQUIRED | OBJECT_TYPE_CREATE)
#endif

#if (PHNT_MODE != PHNT_MODE_KERNEL)
#define DIRECTORY_QUERY 0x0001
#define DIRECTORY_TRAVERSE 0x0002
#define DIRECTORY_CREATE_OBJECT 0x0004
#define DIRECTORY_CREATE_SUBDIRECTORY 0x0008
#define DIRECTORY_ALL_ACCESS (STANDARD_RIGHTS_REQUIRED | DIRECTORY_QUERY | DIRECTORY_TRAVERSE | DIRECTORY_CREATE_OBJECT | DIRECTORY_CREATE_SUBDIRECTORY)
#endif

#if (PHNT_MODE != PHNT_MODE_KERNEL)
#define SYMBOLIC_LINK_QUERY 0x0001
#define SYMBOLIC_LINK_SET 0x0002
#define SYMBOLIC_LINK_ALL_ACCESS (STANDARD_RIGHTS_REQUIRED | SYMBOLIC_LINK_QUERY)
#define SYMBOLIC_LINK_ALL_ACCESS_EX (STANDARD_RIGHTS_REQUIRED | 0xFFFF)
#endif

#ifndef OBJ_PROTECT_CLOSE
#define OBJ_PROTECT_CLOSE 0x00000001
#endif
#ifndef OBJ_INHERIT
#define OBJ_INHERIT 0x00000002
#endif
#ifndef OBJ_AUDIT_OBJECT_CLOSE
#define OBJ_AUDIT_OBJECT_CLOSE 0x00000004
#endif

#if (PHNT_MODE != PHNT_MODE_KERNEL)
    typedef enum _OBJECT_INFORMATION_CLASS
    {
        ObjectBasicInformation, // q: OBJECT_BASIC_INFORMATION
        ObjectNameInformation, // q: OBJECT_NAME_INFORMATION
        ObjectTypeInformation, // q: OBJECT_TYPE_INFORMATION
        ObjectTypesInformation, // q: OBJECT_TYPES_INFORMATION
        ObjectHandleFlagInformation, // qs: OBJECT_HANDLE_FLAG_INFORMATION
        ObjectSessionInformation, // s: void // change object session // (requires SeTcbPrivilege)
        ObjectSessionObjectInformation, // s: void // change object session // (requires SeTcbPrivilege)
        MaxObjectInfoClass
    } OBJECT_INFORMATION_CLASS;
#else
#define ObjectBasicInformation 0
#define ObjectNameInformation 1
#define ObjectTypeInformation 2
#define ObjectTypesInformation 3
#define ObjectHandleFlagInformation 4
#define ObjectSessionInformation 5
#define ObjectSessionObjectInformation 6
#endif

    typedef struct _OBJECT_BASIC_INFORMATION
    {
        ULONG Attributes;
        ACCESS_MASK GrantedAccess;
        ULONG HandleCount;
        ULONG PointerCount;
        ULONG PagedPoolCharge;
        ULONG NonPagedPoolCharge;
        ULONG Reserved[3];
        ULONG NameInfoSize;
        ULONG TypeInfoSize;
        ULONG SecurityDescriptorSize;
        LARGE_INTEGER CreationTime;
    } OBJECT_BASIC_INFORMATION, * POBJECT_BASIC_INFORMATION;

#if (PHNT_MODE != PHNT_MODE_KERNEL)
    typedef struct _OBJECT_NAME_INFORMATION
    {
        UNICODE_STRING Name;
    } OBJECT_NAME_INFORMATION, * POBJECT_NAME_INFORMATION;
#endif

    typedef struct _OBJECT_TYPE_INFORMATION
    {
        UNICODE_STRING TypeName;
        ULONG TotalNumberOfObjects;
        ULONG TotalNumberOfHandles;
        ULONG TotalPagedPoolUsage;
        ULONG TotalNonPagedPoolUsage;
        ULONG TotalNamePoolUsage;
        ULONG TotalHandleTableUsage;
        ULONG HighWaterNumberOfObjects;
        ULONG HighWaterNumberOfHandles;
        ULONG HighWaterPagedPoolUsage;
        ULONG HighWaterNonPagedPoolUsage;
        ULONG HighWaterNamePoolUsage;
        ULONG HighWaterHandleTableUsage;
        ULONG InvalidAttributes;
        GENERIC_MAPPING GenericMapping;
        ULONG ValidAccessMask;
        BOOLEAN SecurityRequired;
        BOOLEAN MaintainHandleCount;
        UCHAR TypeIndex; // since WINBLUE
        CHAR ReservedByte;
        ULONG PoolType;
        ULONG DefaultPagedPoolCharge;
        ULONG DefaultNonPagedPoolCharge;
    } OBJECT_TYPE_INFORMATION, * POBJECT_TYPE_INFORMATION;

    typedef struct _OBJECT_TYPES_INFORMATION
    {
        ULONG NumberOfTypes;
    } OBJECT_TYPES_INFORMATION, * POBJECT_TYPES_INFORMATION;

    typedef struct _OBJECT_HANDLE_FLAG_INFORMATION
    {
        BOOLEAN Inherit;
        BOOLEAN ProtectFromClose;
    } OBJECT_HANDLE_FLAG_INFORMATION, * POBJECT_HANDLE_FLAG_INFORMATION;

    // Objects, handles

#if (PHNT_MODE != PHNT_MODE_KERNEL)

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtQueryObject(
            _In_opt_ HANDLE Handle,
            _In_ OBJECT_INFORMATION_CLASS ObjectInformationClass,
            _Out_writes_bytes_opt_(ObjectInformationLength) PVOID ObjectInformation,
            _In_ ULONG ObjectInformationLength,
            _Out_opt_ PULONG ReturnLength
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtSetInformationObject(
            _In_ HANDLE Handle,
            _In_ OBJECT_INFORMATION_CLASS ObjectInformationClass,
            _In_reads_bytes_(ObjectInformationLength) PVOID ObjectInformation,
            _In_ ULONG ObjectInformationLength
        );

#define DUPLICATE_CLOSE_SOURCE 0x00000001
#define DUPLICATE_SAME_ACCESS 0x00000002
#define DUPLICATE_SAME_ATTRIBUTES 0x00000004

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtDuplicateObject(
            _In_ HANDLE SourceProcessHandle,
            _In_ HANDLE SourceHandle,
            _In_opt_ HANDLE TargetProcessHandle,
            _Out_opt_ PHANDLE TargetHandle,
            _In_ ACCESS_MASK DesiredAccess,
            _In_ ULONG HandleAttributes,
            _In_ ULONG Options
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtMakeTemporaryObject(
            _In_ HANDLE Handle
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtMakePermanentObject(
            _In_ HANDLE Handle
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtSignalAndWaitForSingleObject(
            _In_ HANDLE SignalHandle,
            _In_ HANDLE WaitHandle,
            _In_ BOOLEAN Alertable,
            _In_opt_ PLARGE_INTEGER Timeout
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtWaitForSingleObject(
            _In_ HANDLE Handle,
            _In_ BOOLEAN Alertable,
            _In_opt_ PLARGE_INTEGER Timeout
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtWaitForMultipleObjects(
            _In_ ULONG Count,
            _In_reads_(Count) HANDLE Handles[],
            _In_ WAIT_TYPE WaitType,
            _In_ BOOLEAN Alertable,
            _In_opt_ PLARGE_INTEGER Timeout
        );

#if (PHNT_VERSION >= PHNT_WS03)
    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtWaitForMultipleObjects32(
            _In_ ULONG Count,
            _In_reads_(Count) LONG Handles[],
            _In_ WAIT_TYPE WaitType,
            _In_ BOOLEAN Alertable,
            _In_opt_ PLARGE_INTEGER Timeout
        );
#endif

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtSetSecurityObject(
            _In_ HANDLE Handle,
            _In_ SECURITY_INFORMATION SecurityInformation,
            _In_ PSECURITY_DESCRIPTOR SecurityDescriptor
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtQuerySecurityObject(
            _In_ HANDLE Handle,
            _In_ SECURITY_INFORMATION SecurityInformation,
            _Out_writes_bytes_opt_(Length) PSECURITY_DESCRIPTOR SecurityDescriptor,
            _In_ ULONG Length,
            _Out_ PULONG LengthNeeded
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtClose(
            _In_ _Post_ptr_invalid_ HANDLE Handle
        );

#if (PHNT_VERSION >= PHNT_THRESHOLD)
    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtCompareObjects(
            _In_ HANDLE FirstObjectHandle,
            _In_ HANDLE SecondObjectHandle
        );
#endif

#endif

    // Directory objects

#if (PHNT_MODE != PHNT_MODE_KERNEL)

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtCreateDirectoryObject(
            _Out_ PHANDLE DirectoryHandle,
            _In_ ACCESS_MASK DesiredAccess,
            _In_ POBJECT_ATTRIBUTES ObjectAttributes
        );

#if (PHNT_VERSION >= PHNT_WIN8)
    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtCreateDirectoryObjectEx(
            _Out_ PHANDLE DirectoryHandle,
            _In_ ACCESS_MASK DesiredAccess,
            _In_ POBJECT_ATTRIBUTES ObjectAttributes,
            _In_ HANDLE ShadowDirectoryHandle,
            _In_ ULONG Flags
        );
#endif

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtOpenDirectoryObject(
            _Out_ PHANDLE DirectoryHandle,
            _In_ ACCESS_MASK DesiredAccess,
            _In_ POBJECT_ATTRIBUTES ObjectAttributes
        );

    typedef struct _OBJECT_DIRECTORY_INFORMATION
    {
        UNICODE_STRING Name;
        UNICODE_STRING TypeName;
    } OBJECT_DIRECTORY_INFORMATION, * POBJECT_DIRECTORY_INFORMATION;

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtQueryDirectoryObject(
            _In_ HANDLE DirectoryHandle,
            _Out_writes_bytes_opt_(Length) PVOID Buffer,
            _In_ ULONG Length,
            _In_ BOOLEAN ReturnSingleEntry,
            _In_ BOOLEAN RestartScan,
            _Inout_ PULONG Context,
            _Out_opt_ PULONG ReturnLength
        );

#endif

    // Private namespaces

#if (PHNT_MODE != PHNT_MODE_KERNEL)

#if (PHNT_VERSION >= PHNT_VISTA)

// private
    typedef enum _BOUNDARY_ENTRY_TYPE
    {
        OBNS_Invalid,
        OBNS_Name,
        OBNS_SID,
        OBNS_IL
    } BOUNDARY_ENTRY_TYPE;

    // private
    typedef struct _OBJECT_BOUNDARY_ENTRY
    {
        BOUNDARY_ENTRY_TYPE EntryType;
        ULONG EntrySize;
    } OBJECT_BOUNDARY_ENTRY, * POBJECT_BOUNDARY_ENTRY;

    // rev
#define OBJECT_BOUNDARY_DESCRIPTOR_VERSION 1

// private
    typedef struct _OBJECT_BOUNDARY_DESCRIPTOR
    {
        ULONG Version;
        ULONG Items;
        ULONG TotalSize;
        union
        {
            ULONG Flags;
            struct
            {
                ULONG AddAppContainerSid : 1;
                ULONG Reserved : 31;
            };
        };
    } OBJECT_BOUNDARY_DESCRIPTOR, * POBJECT_BOUNDARY_DESCRIPTOR;

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtCreatePrivateNamespace(
            _Out_ PHANDLE NamespaceHandle,
            _In_ ACCESS_MASK DesiredAccess,
            _In_opt_ POBJECT_ATTRIBUTES ObjectAttributes,
            _In_ POBJECT_BOUNDARY_DESCRIPTOR BoundaryDescriptor
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtOpenPrivateNamespace(
            _Out_ PHANDLE NamespaceHandle,
            _In_ ACCESS_MASK DesiredAccess,
            _In_opt_ POBJECT_ATTRIBUTES ObjectAttributes,
            _In_ POBJECT_BOUNDARY_DESCRIPTOR BoundaryDescriptor
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtDeletePrivateNamespace(
            _In_ HANDLE NamespaceHandle
        );

#endif

#endif

    // Symbolic links

#if (PHNT_MODE != PHNT_MODE_KERNEL)

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtCreateSymbolicLinkObject(
            _Out_ PHANDLE LinkHandle,
            _In_ ACCESS_MASK DesiredAccess,
            _In_ POBJECT_ATTRIBUTES ObjectAttributes,
            _In_ PUNICODE_STRING LinkTarget
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtOpenSymbolicLinkObject(
            _Out_ PHANDLE LinkHandle,
            _In_ ACCESS_MASK DesiredAccess,
            _In_ POBJECT_ATTRIBUTES ObjectAttributes
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtQuerySymbolicLinkObject(
            _In_ HANDLE LinkHandle,
            _Inout_ PUNICODE_STRING LinkTarget,
            _Out_opt_ PULONG ReturnedLength
        );

    typedef enum _SYMBOLIC_LINK_INFO_CLASS
    {
        SymbolicLinkGlobalInformation = 1, // s: ULONG
        SymbolicLinkAccessMask, // s: ACCESS_MASK
        MaxnSymbolicLinkInfoClass
    } SYMBOLIC_LINK_INFO_CLASS;

#if (PHNT_VERSION >= PHNT_THRESHOLD)
    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtSetInformationSymbolicLink(
            _In_ HANDLE LinkHandle,
            _In_ SYMBOLIC_LINK_INFO_CLASS SymbolicLinkInformationClass,
            _In_reads_bytes_(SymbolicLinkInformationLength) PVOID SymbolicLinkInformation,
            _In_ ULONG SymbolicLinkInformationLength
        );
#endif

#endif

#endif
    /*
     * Process support functions
     *
     * This file is part of System Informer.
     */

#ifndef _NTPSAPI_H
#define _NTPSAPI_H

#if (PHNT_MODE == PHNT_MODE_KERNEL)
#define PROCESS_TERMINATE 0x0001
#define PROCESS_CREATE_THREAD 0x0002
#define PROCESS_SET_SESSIONID 0x0004
#define PROCESS_VM_OPERATION 0x0008
#define PROCESS_VM_READ 0x0010
#define PROCESS_VM_WRITE 0x0020
     //#define PROCESS_DUP_HANDLE 0x0040
#define PROCESS_CREATE_PROCESS 0x0080
#define PROCESS_SET_QUOTA 0x0100
#define PROCESS_SET_INFORMATION 0x0200
#define PROCESS_QUERY_INFORMATION 0x0400
#define PROCESS_SET_PORT 0x0800
#define PROCESS_SUSPEND_RESUME 0x0800
#define PROCESS_QUERY_LIMITED_INFORMATION 0x1000
#else
#ifndef PROCESS_SET_PORT
#define PROCESS_SET_PORT 0x0800
#endif
#endif

#if (PHNT_MODE == PHNT_MODE_KERNEL)
#define THREAD_QUERY_INFORMATION 0x0040
#define THREAD_SET_THREAD_TOKEN 0x0080
#define THREAD_IMPERSONATE 0x0100
#define THREAD_DIRECT_IMPERSONATION 0x0200
#else
#ifndef THREAD_ALERT
#define THREAD_ALERT 0x0004
#endif
#endif

#if (PHNT_MODE == PHNT_MODE_KERNEL)
#define JOB_OBJECT_ASSIGN_PROCESS 0x0001
#define JOB_OBJECT_SET_ATTRIBUTES 0x0002
#define JOB_OBJECT_QUERY 0x0004
#define JOB_OBJECT_TERMINATE 0x0008
#define JOB_OBJECT_SET_SECURITY_ATTRIBUTES 0x0010
#define JOB_OBJECT_ALL_ACCESS (STANDARD_RIGHTS_REQUIRED | SYNCHRONIZE | 0x3F)
     //#define JOB_OBJECT_ALL_ACCESS (STANDARD_RIGHTS_REQUIRED | SYNCHRONIZE | 0x1f) // pre-Vista full access
#endif

#define GDI_HANDLE_BUFFER_SIZE32 34
#define GDI_HANDLE_BUFFER_SIZE64 60

#ifndef _WIN64
#define GDI_HANDLE_BUFFER_SIZE GDI_HANDLE_BUFFER_SIZE32
#else
#define GDI_HANDLE_BUFFER_SIZE GDI_HANDLE_BUFFER_SIZE64
#endif

    typedef ULONG GDI_HANDLE_BUFFER[GDI_HANDLE_BUFFER_SIZE];

    typedef ULONG GDI_HANDLE_BUFFER32[GDI_HANDLE_BUFFER_SIZE32];
    typedef ULONG GDI_HANDLE_BUFFER64[GDI_HANDLE_BUFFER_SIZE64];

#ifndef FLS_MAXIMUM_AVAILABLE
#define FLS_MAXIMUM_AVAILABLE 128
#endif
#ifndef TLS_MINIMUM_AVAILABLE
#define TLS_MINIMUM_AVAILABLE 64
#endif
#ifndef TLS_EXPANSION_SLOTS
#define TLS_EXPANSION_SLOTS 1024
#endif

    // symbols
    typedef struct _PEB_LDR_DATA
    {
        ULONG Length;
        BOOLEAN Initialized;
        HANDLE SsHandle;
        LIST_ENTRY InLoadOrderModuleList;
        LIST_ENTRY InMemoryOrderModuleList;
        LIST_ENTRY InInitializationOrderModuleList;
        PVOID EntryInProgress;
        BOOLEAN ShutdownInProgress;
        HANDLE ShutdownThreadId;
    } PEB_LDR_DATA, * PPEB_LDR_DATA;

    typedef struct _INITIAL_TEB
    {
        struct
        {
            PVOID OldStackBase;
            PVOID OldStackLimit;
        } OldInitialTeb;
        PVOID StackBase;
        PVOID StackLimit;
        PVOID StackAllocationBase;
    } INITIAL_TEB, * PINITIAL_TEB;

    typedef struct _WOW64_PROCESS
    {
        PVOID Wow64;
    } WOW64_PROCESS, * PWOW64_PROCESS;

    /*
     * Process and Thread Environment Block support functions
     *
     * This file is part of System Informer.
     */

#ifndef _NTPEBTEB_H
#define _NTPEBTEB_H

    typedef struct _RTL_USER_PROCESS_PARAMETERS* PRTL_USER_PROCESS_PARAMETERS;
    typedef struct _RTL_CRITICAL_SECTION* PRTL_CRITICAL_SECTION;
    typedef struct _SILO_USER_SHARED_DATA* PSILO_USER_SHARED_DATA;
    typedef struct _LEAP_SECOND_DATA* PLEAP_SECOND_DATA;

    /*
     * Side-by-side assembly support definitions.
     *
     * This file is part of System Informer.
     */

#ifndef _NTSXS_H
#define _NTSXS_H

#define ACTIVATION_CONTEXT_DATA_MAGIC ('xtcA')
#define ACTIVATION_CONTEXT_DATA_FORMAT_WHISTLER 1

#define ACTIVATION_CONTEXT_FLAG_NO_INHERIT 0x00000001

#if (PHNT_MODE == PHNT_MODE_KERNEL)
    typedef enum _ACTCTX_REQUESTED_RUN_LEVEL
    {
        ACTCTX_RUN_LEVEL_UNSPECIFIED = 0,
        ACTCTX_RUN_LEVEL_AS_INVOKER,
        ACTCTX_RUN_LEVEL_HIGHEST_AVAILABLE,
        ACTCTX_RUN_LEVEL_REQUIRE_ADMIN,
        ACTCTX_RUN_LEVEL_NUMBERS
    } ACTCTX_REQUESTED_RUN_LEVEL;

    typedef enum _ACTCTX_COMPATIBILITY_ELEMENT_TYPE
    {
        ACTCTX_COMPATIBILITY_ELEMENT_TYPE_UNKNOWN = 0,
        ACTCTX_COMPATIBILITY_ELEMENT_TYPE_OS,
        ACTCTX_COMPATIBILITY_ELEMENT_TYPE_MITIGATION,
        ACTCTX_COMPATIBILITY_ELEMENT_TYPE_MAXVERSIONTESTED
    } ACTCTX_COMPATIBILITY_ELEMENT_TYPE;
#endif

#include <pshpack4.h>

    typedef struct _ACTIVATION_CONTEXT_DATA
    {
        ULONG Magic;
        ULONG HeaderSize;
        ULONG FormatVersion;
        ULONG TotalSize;
        ULONG DefaultTocOffset; // to ACTIVATION_CONTEXT_DATA_TOC_HEADER
        ULONG ExtendedTocOffset; // to ACTIVATION_CONTEXT_DATA_EXTENDED_TOC_HEADER
        ULONG AssemblyRosterOffset; // to ACTIVATION_CONTEXT_DATA_ASSEMBLY_ROSTER_HEADER
        ULONG Flags; // ACTIVATION_CONTEXT_FLAG_*
    } ACTIVATION_CONTEXT_DATA, * PACTIVATION_CONTEXT_DATA;

#define ACTIVATION_CONTEXT_DATA_TOC_HEADER_DENSE 0x00000001
#define ACTIVATION_CONTEXT_DATA_TOC_HEADER_INORDER 0x00000002

    typedef struct _ACTIVATION_CONTEXT_DATA_TOC_HEADER
    {
        ULONG HeaderSize;
        ULONG EntryCount;
        ULONG FirstEntryOffset; // to ACTIVATION_CONTEXT_DATA_TOC_ENTRY[], from ACTIVATION_CONTEXT_DATA base
        ULONG Flags; // ACTIVATION_CONTEXT_DATA_TOC_HEADER_*
    } ACTIVATION_CONTEXT_DATA_TOC_HEADER, * PACTIVATION_CONTEXT_DATA_TOC_HEADER;

    typedef struct _ACTIVATION_CONTEXT_DATA_TOC_ENTRY
    {
        ULONG Id; // ACTIVATION_CONTEXT_SECTION_*
        ULONG Offset; // to ACTIVATION_CONTEXT_*_SECTION_HEADER, from ACTIVATION_CONTEXT_DATA base
        ULONG Length;
        ULONG Format; // ACTIVATION_CONTEXT_SECTION_FORMAT_*
    } ACTIVATION_CONTEXT_DATA_TOC_ENTRY, * PACTIVATION_CONTEXT_DATA_TOC_ENTRY;

    typedef struct _ACTIVATION_CONTEXT_DATA_EXTENDED_TOC_HEADER
    {
        ULONG HeaderSize;
        ULONG EntryCount;
        ULONG FirstEntryOffset; // to ACTIVATION_CONTEXT_DATA_EXTENDED_TOC_ENTRY[], from ACTIVATION_CONTEXT_DATA base
        ULONG Flags;
    } ACTIVATION_CONTEXT_DATA_EXTENDED_TOC_HEADER, * PACTIVATION_CONTEXT_DATA_EXTENDED_TOC_HEADER;

    typedef struct _ACTIVATION_CONTEXT_DATA_EXTENDED_TOC_ENTRY
    {
        GUID ExtensionGuid;
        ULONG TocOffset; // to ACTIVATION_CONTEXT_DATA_TOC_HEADER, from ACTIVATION_CONTEXT_DATA base
        ULONG Length;
    } ACTIVATION_CONTEXT_DATA_EXTENDED_TOC_ENTRY, * PACTIVATION_CONTEXT_DATA_EXTENDED_TOC_ENTRY;

#define ACTIVATION_CONTEXT_DATA_ASSEMBLY_ROSTER_ENTRY_INVALID 0x00000001
#define ACTIVATION_CONTEXT_DATA_ASSEMBLY_ROSTER_ENTRY_ROOT 0x00000002

    typedef struct _ACTIVATION_CONTEXT_DATA_ASSEMBLY_ROSTER_HEADER
    {
        ULONG HeaderSize;
        ULONG HashAlgorithm; // HASH_STRING_ALGORITHM_*
        ULONG EntryCount;
        ULONG FirstEntryOffset; // to ACTIVATION_CONTEXT_DATA_ASSEMBLY_ROSTER_ENTRY[], from ACTIVATION_CONTEXT_DATA base
        ULONG AssemblyInformationSectionOffset; // to resolve section-relative offsets
    } ACTIVATION_CONTEXT_DATA_ASSEMBLY_ROSTER_HEADER, * PACTIVATION_CONTEXT_DATA_ASSEMBLY_ROSTER_HEADER;

    typedef struct _ACTIVATION_CONTEXT_DATA_ASSEMBLY_ROSTER_ENTRY
    {
        ULONG Flags;
        ULONG PseudoKey;
        ULONG AssemblyNameOffset; // to WCHAR[], from ACTIVATION_CONTEXT_DATA base
        ULONG AssemblyNameLength;
        ULONG AssemblyInformationOffset; // to ACTIVATION_CONTEXT_DATA_ASSEMBLY_INFORMATION, from ACTIVATION_CONTEXT_DATA base
        ULONG AssemblyInformationLength;
    } ACTIVATION_CONTEXT_DATA_ASSEMBLY_ROSTER_ENTRY, * PACTIVATION_CONTEXT_DATA_ASSEMBLY_ROSTER_ENTRY;

#define ACTIVATION_CONTEXT_SECTION_FORMAT_UNKNOWN 0
#define ACTIVATION_CONTEXT_SECTION_FORMAT_STRING_TABLE 1 // ACTIVATION_CONTEXT_STRING_SECTION_HEADER
#define ACTIVATION_CONTEXT_SECTION_FORMAT_GUID_TABLE 2 // ACTIVATION_CONTEXT_GUID_SECTION_HEADER

#define ACTIVATION_CONTEXT_STRING_SECTION_MAGIC ('dHsS')
#define ACTIVATION_CONTEXT_STRING_SECTION_FORMAT_WHISTLER 1

#define ACTIVATION_CONTEXT_STRING_SECTION_CASE_INSENSITIVE 0x00000001
#define ACTIVATION_CONTEXT_STRING_SECTION_ENTRIES_IN_PSEUDOKEY_ORDER 0x00000002

    typedef struct _ACTIVATION_CONTEXT_STRING_SECTION_HEADER
    {
        ULONG Magic;
        ULONG HeaderSize;
        ULONG FormatVersion;
        ULONG DataFormatVersion;
        ULONG Flags; // ACTIVATION_CONTEXT_STRING_SECTION_*
        ULONG ElementCount;
        ULONG ElementListOffset; // to ACTIVATION_CONTEXT_STRING_SECTION_ENTRY[], from this struct base
        ULONG HashAlgorithm; // HASH_STRING_ALGORITHM_*
        ULONG SearchStructureOffset; // to ACTIVATION_CONTEXT_STRING_SECTION_HASH_TABLE, from this struct base
        ULONG UserDataOffset; // to data depending on section Id, from this struct base
        ULONG UserDataSize;
    } ACTIVATION_CONTEXT_STRING_SECTION_HEADER, * PACTIVATION_CONTEXT_STRING_SECTION_HEADER;

    typedef struct _ACTIVATION_CONTEXT_STRING_SECTION_ENTRY
    {
        ULONG PseudoKey;
        ULONG KeyOffset; // to WCHAR[], from section header
        ULONG KeyLength;
        ULONG Offset; // to data depending on section Id, from section header
        ULONG Length;
        ULONG AssemblyRosterIndex;
    } ACTIVATION_CONTEXT_STRING_SECTION_ENTRY, * PACTIVATION_CONTEXT_STRING_SECTION_ENTRY;

    typedef struct _ACTIVATION_CONTEXT_STRING_SECTION_HASH_TABLE
    {
        ULONG BucketTableEntryCount;
        ULONG BucketTableOffset; // to ACTIVATION_CONTEXT_STRING_SECTION_HASH_BUCKET[], from section header
    } ACTIVATION_CONTEXT_STRING_SECTION_HASH_TABLE, * PACTIVATION_CONTEXT_STRING_SECTION_HASH_TABLE;

    typedef struct _ACTIVATION_CONTEXT_STRING_SECTION_HASH_BUCKET
    {
        ULONG ChainCount;
        ULONG ChainOffset; // to LONG[], from section header
    } ACTIVATION_CONTEXT_STRING_SECTION_HASH_BUCKET, * PACTIVATION_CONTEXT_STRING_SECTION_HASH_BUCKET;

#define ACTIVATION_CONTEXT_GUID_SECTION_MAGIC ('dHsG')
#define ACTIVATION_CONTEXT_GUID_SECTION_FORMAT_WHISTLER 1

#define ACTIVATION_CONTEXT_GUID_SECTION_ENTRIES_IN_ORDER 0x00000001

    typedef struct _ACTIVATION_CONTEXT_GUID_SECTION_HEADER
    {
        ULONG Magic;
        ULONG HeaderSize;
        ULONG FormatVersion;
        ULONG DataFormatVersion;
        ULONG Flags; // ACTIVATION_CONTEXT_GUID_SECTION_*
        ULONG ElementCount;
        ULONG ElementListOffset; // to ACTIVATION_CONTEXT_GUID_SECTION_ENTRY[], from this struct base
        ULONG SearchStructureOffset; // to ACTIVATION_CONTEXT_GUID_SECTION_HASH_TABLE, from this struct base
        ULONG UserDataOffset; // to data depending on section Id, from this struct base
        ULONG UserDataSize;
    } ACTIVATION_CONTEXT_GUID_SECTION_HEADER, * PACTIVATION_CONTEXT_GUID_SECTION_HEADER;

    typedef struct _ACTIVATION_CONTEXT_GUID_SECTION_ENTRY
    {
        GUID Guid;
        ULONG Offset; // to data depending on section Id, from section header
        ULONG Length;
        ULONG AssemblyRosterIndex;
    } ACTIVATION_CONTEXT_GUID_SECTION_ENTRY, * PACTIVATION_CONTEXT_GUID_SECTION_ENTRY;

    typedef struct _ACTIVATION_CONTEXT_GUID_SECTION_HASH_TABLE
    {
        ULONG BucketTableEntryCount;
        ULONG BucketTableOffset; // to ACTIVATION_CONTEXT_GUID_SECTION_HASH_BUCKET, from section header
    } ACTIVATION_CONTEXT_GUID_SECTION_HASH_TABLE, * PACTIVATION_CONTEXT_GUID_SECTION_HASH_TABLE;

    typedef struct _ACTIVATION_CONTEXT_GUID_SECTION_HASH_BUCKET
    {
        ULONG ChainCount;
        ULONG ChainOffset; // to LONG[], from section header
    } ACTIVATION_CONTEXT_GUID_SECTION_HASH_BUCKET, * PACTIVATION_CONTEXT_GUID_SECTION_HASH_BUCKET;

    // winnt.h - known section IDs
    // #define ACTIVATION_CONTEXT_SECTION_ASSEMBLY_INFORMATION         (1) // ACTIVATION_CONTEXT_SECTION_ASSEMBLY_INFORMATION + ACTIVATION_CONTEXT_DATA_ASSEMBLY_GLOBAL_INFORMATION
    // #define ACTIVATION_CONTEXT_SECTION_DLL_REDIRECTION              (2) // ACTIVATION_CONTEXT_DATA_DLL_REDIRECTION
    // #define ACTIVATION_CONTEXT_SECTION_WINDOW_CLASS_REDIRECTION     (3) // ACTIVATION_CONTEXT_DATA_WINDOW_CLASS_REDIRECTION
    // #define ACTIVATION_CONTEXT_SECTION_COM_SERVER_REDIRECTION       (4) // ACTIVATION_CONTEXT_DATA_COM_SERVER_REDIRECTION
    // #define ACTIVATION_CONTEXT_SECTION_COM_INTERFACE_REDIRECTION    (5) // ACTIVATION_CONTEXT_DATA_COM_INTERFACE_REDIRECTION
    // #define ACTIVATION_CONTEXT_SECTION_COM_TYPE_LIBRARY_REDIRECTION (6) // ACTIVATION_CONTEXT_DATA_COM_TYPE_LIBRARY_REDIRECTION
    // #define ACTIVATION_CONTEXT_SECTION_COM_PROGID_REDIRECTION       (7) // ACTIVATION_CONTEXT_DATA_COM_PROGID_REDIRECTION
    // #define ACTIVATION_CONTEXT_SECTION_GLOBAL_OBJECT_RENAME_TABLE   (8)
    // #define ACTIVATION_CONTEXT_SECTION_CLR_SURROGATES               (9) // ACTIVATION_CONTEXT_DATA_CLR_SURROGATE
    // #define ACTIVATION_CONTEXT_SECTION_APPLICATION_SETTINGS         (10) // ACTIVATION_CONTEXT_DATA_APPLICATION_SETTINGS
    // #define ACTIVATION_CONTEXT_SECTION_COMPATIBILITY_INFO           (11) // ACTIVATION_CONTEXT_COMPATIBILITY_INFORMATION[_LEGACY]
    // #define ACTIVATION_CONTEXT_SECTION_WINRT_ACTIVATABLE_CLASSES    (12) // since 19H1

#define ACTIVATION_CONTEXT_DATA_ASSEMBLY_INFORMATION_FORMAT_WHISTLER 1

#define ACTIVATION_CONTEXT_DATA_ASSEMBLY_INFORMATION_ROOT_ASSEMBLY 0x00000001
#define ACTIVATION_CONTEXT_DATA_ASSEMBLY_INFORMATION_POLICY_APPLIED 0x00000002
#define ACTIVATION_CONTEXT_DATA_ASSEMBLY_INFORMATION_ASSEMBLY_POLICY_APPLIED 0x00000004
#define ACTIVATION_CONTEXT_DATA_ASSEMBLY_INFORMATION_ROOT_POLICY_APPLIED 0x00000008
#define ACTIVATION_CONTEXT_DATA_ASSEMBLY_INFORMATION_PRIVATE_ASSEMBLY 0x00000010

    typedef struct _ACTIVATION_CONTEXT_DATA_ASSEMBLY_INFORMATION
    {
        ULONG Size;
        ULONG Flags; // ACTIVATION_CONTEXT_DATA_ASSEMBLY_INFORMATION_*
        ULONG EncodedAssemblyIdentityLength;
        ULONG EncodedAssemblyIdentityOffset; // to WCHAR[], from section header
        ULONG ManifestPathType; // ACTIVATION_CONTEXT_PATH_TYPE_*
        ULONG ManifestPathLength;
        ULONG ManifestPathOffset; // to WCHAR[], from section header
        LARGE_INTEGER ManifestLastWriteTime;
        ULONG PolicyPathType; // ACTIVATION_CONTEXT_PATH_TYPE_*
        ULONG PolicyPathLength;
        ULONG PolicyPathOffset; // to WCHAR[], from section header
        LARGE_INTEGER PolicyLastWriteTime;
        ULONG MetadataSatelliteRosterIndex;
        ULONG Unused2;
        ULONG ManifestVersionMajor;
        ULONG ManifestVersionMinor;
        ULONG PolicyVersionMajor;
        ULONG PolicyVersionMinor;
        ULONG AssemblyDirectoryNameLength;
        ULONG AssemblyDirectoryNameOffset; // to WCHAR[], from section header
        ULONG NumOfFilesInAssembly;
        ULONG LanguageLength;
        ULONG LanguageOffset; // to WCHAR[], from section header
        ACTCTX_REQUESTED_RUN_LEVEL RunLevel;
        ULONG UiAccess;
    } ACTIVATION_CONTEXT_DATA_ASSEMBLY_INFORMATION, * PACTIVATION_CONTEXT_DATA_ASSEMBLY_INFORMATION;

    // via UserData
    typedef struct _ACTIVATION_CONTEXT_DATA_ASSEMBLY_GLOBAL_INFORMATION
    {
        ULONG Size;
        ULONG Flags;
        GUID PolicyCoherencyGuid;
        GUID PolicyOverrideGuid;
        ULONG ApplicationDirectoryPathType; // ACTIVATION_CONTEXT_PATH_TYPE_*
        ULONG ApplicationDirectoryLength;
        ULONG ApplicationDirectoryOffset; // to WCHAR[], from this struct base
        ULONG ResourceName;
    } ACTIVATION_CONTEXT_DATA_ASSEMBLY_GLOBAL_INFORMATION, * PACTIVATION_CONTEXT_DATA_ASSEMBLY_GLOBAL_INFORMATION;

#define ACTIVATION_CONTEXT_DATA_DLL_REDIRECTION_FORMAT_WHISTLER 1

#define ACTIVATION_CONTEXT_DATA_DLL_REDIRECTION_PATH_INCLUDES_BASE_NAME 0x00000001
#define ACTIVATION_CONTEXT_DATA_DLL_REDIRECTION_PATH_OMITS_ASSEMBLY_ROOT 0x00000002
#define ACTIVATION_CONTEXT_DATA_DLL_REDIRECTION_PATH_EXPAND 0x00000004
#define ACTIVATION_CONTEXT_DATA_DLL_REDIRECTION_PATH_SYSTEM_DEFAULT_REDIRECTED_SYSTEM32_DLL 0x00000008

    typedef struct _ACTIVATION_CONTEXT_DATA_DLL_REDIRECTION
    {
        ULONG Size;
        ULONG Flags; // ACTIVATION_CONTEXT_DATA_DLL_REDIRECTION_*
        ULONG TotalPathLength;
        ULONG PathSegmentCount;
        ULONG PathSegmentOffset; // to ACTIVATION_CONTEXT_DATA_DLL_REDIRECTION_PATH_SEGMENT[], from section header
    } ACTIVATION_CONTEXT_DATA_DLL_REDIRECTION, * PACTIVATION_CONTEXT_DATA_DLL_REDIRECTION;

    typedef struct _ACTIVATION_CONTEXT_DATA_DLL_REDIRECTION_PATH_SEGMENT
    {
        ULONG Length;
        ULONG Offset; // to WCHAR[], from section header
    } ACTIVATION_CONTEXT_DATA_DLL_REDIRECTION_PATH_SEGMENT, * PACTIVATION_CONTEXT_DATA_DLL_REDIRECTION_PATH_SEGMENT;

#define ACTIVATION_CONTEXT_DATA_WINDOW_CLASS_REDIRECTION_FORMAT_WHISTLER 1

    typedef struct _ACTIVATION_CONTEXT_DATA_WINDOW_CLASS_REDIRECTION
    {
        ULONG Size;
        ULONG Flags;
        ULONG VersionSpecificClassNameLength;
        ULONG VersionSpecificClassNameOffset; // to WHCAR[], from this struct base
        ULONG DllNameLength;
        ULONG DllNameOffset; // to WCHAR[], from section header
    } ACTIVATION_CONTEXT_DATA_WINDOW_CLASS_REDIRECTION, * PACTIVATION_CONTEXT_DATA_WINDOW_CLASS_REDIRECTION;

#define ACTIVATION_CONTEXT_DATA_COM_SERVER_REDIRECTION_FORMAT_WHISTLER 1

#define ACTIVATION_CONTEXT_DATA_COM_SERVER_REDIRECTION_THREADING_MODEL_INVALID 0
#define ACTIVATION_CONTEXT_DATA_COM_SERVER_REDIRECTION_THREADING_MODEL_APARTMENT 1
#define ACTIVATION_CONTEXT_DATA_COM_SERVER_REDIRECTION_THREADING_MODEL_FREE 2
#define ACTIVATION_CONTEXT_DATA_COM_SERVER_REDIRECTION_THREADING_MODEL_SINGLE 3
#define ACTIVATION_CONTEXT_DATA_COM_SERVER_REDIRECTION_THREADING_MODEL_BOTH 4
#define ACTIVATION_CONTEXT_DATA_COM_SERVER_REDIRECTION_THREADING_MODEL_NEUTRAL 5

#define ACTIVATION_CONTEXT_DATA_COM_SERVER_MISCSTATUS_FLAG_OFFSET 8
#define ACTIVATION_CONTEXT_DATA_COM_SERVER_MISCSTATUS_HAS_DEFAULT (0x01 << ACTIVATION_CONTEXT_DATA_COM_SERVER_MISCSTATUS_FLAG_OFFSET)
#define ACTIVATION_CONTEXT_DATA_COM_SERVER_MISCSTATUS_HAS_ICON (0x02 << ACTIVATION_CONTEXT_DATA_COM_SERVER_MISCSTATUS_FLAG_OFFSET)
#define ACTIVATION_CONTEXT_DATA_COM_SERVER_MISCSTATUS_HAS_CONTENT (0x04 << ACTIVATION_CONTEXT_DATA_COM_SERVER_MISCSTATUS_FLAG_OFFSET)
#define ACTIVATION_CONTEXT_DATA_COM_SERVER_MISCSTATUS_HAS_THUMBNAIL (0x08 << ACTIVATION_CONTEXT_DATA_COM_SERVER_MISCSTATUS_FLAG_OFFSET)
#define ACTIVATION_CONTEXT_DATA_COM_SERVER_MISCSTATUS_HAS_DOCPRINT (0x10 << ACTIVATION_CONTEXT_DATA_COM_SERVER_MISCSTATUS_FLAG_OFFSET)

    typedef struct _ACTIVATION_CONTEXT_DATA_COM_SERVER_REDIRECTION
    {
        ULONG Size;
        ULONG Flags;
        ULONG ThreadingModel; // ACTIVATION_CONTEXT_DATA_COM_SERVER_REDIRECTION_THREADING_MODEL_*
        GUID ReferenceClsid;
        GUID ConfiguredClsid;
        GUID ImplementedClsid;
        GUID TypeLibraryId;
        ULONG ModuleLength;
        ULONG ModuleOffset; // to WCHAR[], from section header
        ULONG ProgIdLength;
        ULONG ProgIdOffset; // to WCHAR[], from this struct base
        ULONG ShimDataLength;
        ULONG ShimDataOffset; // to ACTIVATION_CONTEXT_DATA_COM_SERVER_REDIRECTION_SHIM, from this struct base
        ULONG MiscStatusDefault;
        ULONG MiscStatusContent;
        ULONG MiscStatusThumbnail;
        ULONG MiscStatusIcon;
        ULONG MiscStatusDocPrint;
    } ACTIVATION_CONTEXT_DATA_COM_SERVER_REDIRECTION, * PACTIVATION_CONTEXT_DATA_COM_SERVER_REDIRECTION;

#define ACTIVATION_CONTEXT_DATA_COM_SERVER_REDIRECTION_SHIM_TYPE_OTHER 1
#define ACTIVATION_CONTEXT_DATA_COM_SERVER_REDIRECTION_SHIM_TYPE_CLR_CLASS 2

    typedef struct _ACTIVATION_CONTEXT_DATA_COM_SERVER_REDIRECTION_SHIM
    {
        ULONG Size;
        ULONG Flags;
        ULONG Type; // ACTIVATION_CONTEXT_DATA_COM_SERVER_REDIRECTION_SHIM_TYPE_*
        ULONG ModuleLength;
        ULONG ModuleOffset; // to WCHAR[], from section header
        ULONG TypeLength;
        ULONG TypeOffset; // to WCHAR[], from this struct base
        ULONG ShimVersionLength;
        ULONG ShimVersionOffset; // to WCHAR[], from this struct base
        ULONG DataLength;
        ULONG DataOffset; // from this struct base
    } ACTIVATION_CONTEXT_DATA_COM_SERVER_REDIRECTION_SHIM, * PACTIVATION_CONTEXT_DATA_COM_SERVER_REDIRECTION_SHIM;

#define ACTIVATION_CONTEXT_DATA_COM_INTERFACE_REDIRECTION_FORMAT_WHISTLER 1

#define ACTIVATION_CONTEXT_DATA_COM_INTERFACE_REDIRECTION_FLAG_NUM_METHODS_VALID 0x00000001
#define ACTIVATION_CONTEXT_DATA_COM_INTERFACE_REDIRECTION_FLAG_BASE_INTERFACE_VALID 0x00000002

    typedef struct _ACTIVATION_CONTEXT_DATA_COM_INTERFACE_REDIRECTION
    {
        ULONG Size;
        ULONG Flags; // ACTIVATION_CONTEXT_DATA_COM_INTERFACE_REDIRECTION_FLAG_*
        GUID ProxyStubClsid32;
        ULONG NumMethods;
        GUID TypeLibraryId;
        GUID BaseInterface;
        ULONG NameLength;
        ULONG NameOffset; // to WCHAR[], from this struct base
    } ACTIVATION_CONTEXT_DATA_COM_INTERFACE_REDIRECTION, * PACTIVATION_CONTEXT_DATA_COM_INTERFACE_REDIRECTION;

#define ACTIVATION_CONTEXT_DATA_COM_TYPE_LIBRARY_REDIRECTION_FORMAT_WHISTLER 1

    typedef struct _ACTIVATION_CONTEXT_DATA_TYPE_LIBRARY_VERSION
    {
        USHORT Major;
        USHORT Minor;
    } ACTIVATION_CONTEXT_DATA_TYPE_LIBRARY_VERSION, * PACTIVATION_CONTEXT_DATA_TYPE_LIBRARY_VERSION;

    typedef struct _ACTIVATION_CONTEXT_DATA_COM_TYPE_LIBRARY_REDIRECTION
    {
        ULONG   Size;
        ULONG   Flags;
        ULONG   NameLength;
        ULONG   NameOffset; // to WCHAR[], from section header
        USHORT  ResourceId;
        USHORT  LibraryFlags; // LIBFLAG_* oaidl.h
        ULONG   HelpDirLength;
        ULONG   HelpDirOffset; // to WCHAR[], from this struct base
        ACTIVATION_CONTEXT_DATA_TYPE_LIBRARY_VERSION Version;
    } ACTIVATION_CONTEXT_DATA_COM_TYPE_LIBRARY_REDIRECTION, * PACTIVATION_CONTEXT_DATA_COM_TYPE_LIBRARY_REDIRECTION;

#define ACTIVATION_CONTEXT_DATA_COM_PROGID_REDIRECTION_FORMAT_WHISTLER 1

    typedef struct _ACTIVATION_CONTEXT_DATA_COM_PROGID_REDIRECTION
    {
        ULONG Size;
        ULONG Flags;
        ULONG ConfiguredClsidOffset; // to CLSID, from section header
    } ACTIVATION_CONTEXT_DATA_COM_PROGID_REDIRECTION, * PACTIVATION_CONTEXT_DATA_COM_PROGID_REDIRECTION;

#define ACTIVATION_CONTEXT_DATA_CLR_SURROGATE_FORMAT_WHISTLER 1

    typedef struct _ACTIVATION_CONTEXT_DATA_CLR_SURROGATE
    {
        ULONG   Size;
        ULONG   Flags;
        GUID    SurrogateIdent;
        ULONG   VersionOffset;
        ULONG   VersionLength;
        ULONG   TypeNameOffset;
        ULONG   TypeNameLength; // to WCHAR[], from this struct base
    } ACTIVATION_CONTEXT_DATA_CLR_SURROGATE, * PACTIVATION_CONTEXT_DATA_CLR_SURROGATE;

#define ACTIVATION_CONTEXT_DATA_APPLICATION_SETTINGS_FORMAT_LONGHORN 1

#define SXS_WINDOWS_SETTINGS_NAMESPACE L"http://schemas.microsoft.com/SMI/2005/WindowsSettings"
#define SXS_WINDOWS_SETTINGS_2011_NAMESPACE L"http://schemas.microsoft.com/SMI/2011/WindowsSettings"
#define SXS_WINDOWS_SETTINGS_2013_NAMESPACE L"http://schemas.microsoft.com/SMI/2013/WindowsSettings"
#define SXS_WINDOWS_SETTINGS_2014_NAMESPACE L"http://schemas.microsoft.com/SMI/2014/WindowsSettings"
#define SXS_WINDOWS_SETTINGS_2016_NAMESPACE L"http://schemas.microsoft.com/SMI/2016/WindowsSettings"
#define SXS_WINDOWS_SETTINGS_2017_NAMESPACE L"http://schemas.microsoft.com/SMI/2017/WindowsSettings"
#define SXS_WINDOWS_SETTINGS_2019_NAMESPACE L"http://schemas.microsoft.com/SMI/2019/WindowsSettings"
#define SXS_WINDOWS_SETTINGS_2020_NAMESPACE L"http://schemas.microsoft.com/SMI/2020/WindowsSettings"

    typedef struct _ACTIVATION_CONTEXT_DATA_APPLICATION_SETTINGS
    {
        ULONG Size;
        ULONG Flags;
        ULONG SettingNamespaceLength;
        ULONG SettingNamespaceOffset; // to WCHAR[], from this struct base
        ULONG SettingNameLength;
        ULONG SettingNameOffset; // to WCHAR[], from this struct base
        ULONG SettingValueLength;
        ULONG SettingValueOffset; // to WCHAR[], from this struct base
    } ACTIVATION_CONTEXT_DATA_APPLICATION_SETTINGS, * PACTIVATION_CONTEXT_DATA_APPLICATION_SETTINGS;

    // COMPATIBILITY_CONTEXT_ELEMENT from winnt.h before 19H1
    typedef struct _COMPATIBILITY_CONTEXT_ELEMENT_LEGACY
    {
        GUID Id;
        ACTCTX_COMPATIBILITY_ELEMENT_TYPE Type;
    } COMPATIBILITY_CONTEXT_ELEMENT_LEGACY, * PCOMPATIBILITY_CONTEXT_ELEMENT_LEGACY;

    // ACTIVATION_CONTEXT_COMPATIBILITY_INFORMATION from winnt.h before 19H1
    typedef struct _ACTIVATION_CONTEXT_COMPATIBILITY_INFORMATION_LEGACY
    {
        DWORD ElementCount;
        COMPATIBILITY_CONTEXT_ELEMENT_LEGACY Elements[ANYSIZE_ARRAY];
    } ACTIVATION_CONTEXT_COMPATIBILITY_INFORMATION_LEGACY, * PACTIVATION_CONTEXT_COMPATIBILITY_INFORMATION_LEGACY;

#include <poppack.h>

    // begin_private

    typedef struct _ASSEMBLY_STORAGE_MAP_ENTRY
    {
        ULONG Flags;
        UNICODE_STRING DosPath;
        HANDLE Handle;
    } ASSEMBLY_STORAGE_MAP_ENTRY, * PASSEMBLY_STORAGE_MAP_ENTRY;

#define ASSEMBLY_STORAGE_MAP_ASSEMBLY_ARRAY_IS_HEAP_ALLOCATED 0x00000001

    typedef struct _ASSEMBLY_STORAGE_MAP
    {
        ULONG Flags;
        ULONG AssemblyCount;
        PASSEMBLY_STORAGE_MAP_ENTRY* AssemblyArray;
    } ASSEMBLY_STORAGE_MAP, * PASSEMBLY_STORAGE_MAP;

    typedef struct _ACTIVATION_CONTEXT* PACTIVATION_CONTEXT;

#define ACTIVATION_CONTEXT_NOTIFICATION_DESTROY 1
#define ACTIVATION_CONTEXT_NOTIFICATION_ZOMBIFY 2
#define ACTIVATION_CONTEXT_NOTIFICATION_USED 3

    typedef VOID(NTAPI* PACTIVATION_CONTEXT_NOTIFY_ROUTINE)(
        _In_ ULONG NotificationType, // ACTIVATION_CONTEXT_NOTIFICATION_*
        _In_ PACTIVATION_CONTEXT ActivationContext,
        _In_ PACTIVATION_CONTEXT_DATA ActivationContextData,
        _In_opt_ PVOID NotificationContext,
        _In_opt_ PVOID NotificationData,
        _Inout_ PBOOLEAN DisableThisNotification
        );

    typedef struct _ACTIVATION_CONTEXT
    {
        LONG RefCount;
        ULONG Flags;
        PACTIVATION_CONTEXT_DATA ActivationContextData;
        PACTIVATION_CONTEXT_NOTIFY_ROUTINE NotificationRoutine;
        PVOID NotificationContext;
        ULONG SentNotifications[8];
        ULONG DisabledNotifications[8];
        ASSEMBLY_STORAGE_MAP StorageMap;
        PASSEMBLY_STORAGE_MAP_ENTRY InlineStorageMapEntries[32];
    } ACTIVATION_CONTEXT, * PACTIVATION_CONTEXT;

#define RTL_ACTIVATION_CONTEXT_STACK_FRAME_FLAG_RELEASE_ON_DEACTIVATION 0x00000001
#define RTL_ACTIVATION_CONTEXT_STACK_FRAME_FLAG_NO_DEACTIVATE 0x00000002
#define RTL_ACTIVATION_CONTEXT_STACK_FRAME_FLAG_ON_FREE_LIST 0x00000004
#define RTL_ACTIVATION_CONTEXT_STACK_FRAME_FLAG_HEAP_ALLOCATED 0x00000008
#define RTL_ACTIVATION_CONTEXT_STACK_FRAME_FLAG_NOT_REALLY_ACTIVATED 0x00000010

    typedef struct _RTL_ACTIVATION_CONTEXT_STACK_FRAME
    {
        struct _RTL_ACTIVATION_CONTEXT_STACK_FRAME* Previous;
        PACTIVATION_CONTEXT ActivationContext;
        ULONG Flags; // RTL_ACTIVATION_CONTEXT_STACK_FRAME_FLAG_*
    } RTL_ACTIVATION_CONTEXT_STACK_FRAME, * PRTL_ACTIVATION_CONTEXT_STACK_FRAME;

#define ACTIVATION_CONTEXT_STACK_FLAG_QUERIES_DISABLED 0x00000001

    typedef struct _ACTIVATION_CONTEXT_STACK
    {
        PRTL_ACTIVATION_CONTEXT_STACK_FRAME ActiveFrame;
        LIST_ENTRY FrameListCache;
        ULONG Flags; // ACTIVATION_CONTEXT_STACK_FLAG_*
        ULONG NextCookieSequenceNumber;
        ULONG StackId;
    } ACTIVATION_CONTEXT_STACK, * PACTIVATION_CONTEXT_STACK;

    // end_private

#endif

// private
#define KACF_OLDGETSHORTPATHNAME 0x00000001
#define KACF_VERSIONLIE_NOT_USED 0x00000002
#define KACF_GETDISKFREESPACE 0x00000008
#define KACF_FTMFROMCURRENTAPT 0x00000020
#define KACF_DISALLOWORBINDINGCHANGES 0x00000040
#define KACF_OLE32VALIDATEPTRS 0x00000080
#define KACF_DISABLECICERO 0x00000100
#define KACF_OLE32ENABLEASYNCDOCFILE 0x00000200
#define KACF_OLE32ENABLELEGACYEXCEPTIONHANDLING 0x00000400 
#define KACF_RPCDISABLENDRCLIENTHARDENING 0x00000800
#define KACF_RPCDISABLENDRMAYBENULL_SIZEIS 0x00001000
#define KACF_DISABLEALLDDEHACK_NOT_USED 0x00002000
#define KACF_RPCDISABLENDR61_RANGE 0x00004000
#define KACF_RPC32ENABLELEGACYEXCEPTIONHANDLING 0x00008000
#define KACF_OLE32DOCFILEUSELEGACYNTFSFLAGS 0x00010000
#define KACF_RPCDISABLENDRCONSTIIDCHECK 0x00020000
#define KACF_USERDISABLEFORWARDERPATCH 0x00040000
#define KACF_OLE32DISABLENEW_WMPAINT_DISPATCH 0x00100000
#define KACF_ADDRESTRICTEDSIDINCOINITIALIZESECURITY 0x00200000
#define KACF_ALLOCDEBUGINFOFORCRITSECTIONS 0x00400000
#define KACF_OLEAUT32ENABLEUNSAFELOADTYPELIBRELATIVE 0x00800000
#define KACF_ALLOWMAXIMIZEDWINDOWGAMMA 0x01000000
#define KACF_DONOTADDTOCACHE 0x80000000

// private
    typedef struct _API_SET_NAMESPACE
    {
        ULONG Version;
        ULONG Size;
        ULONG Flags;
        ULONG Count;
        ULONG EntryOffset;
        ULONG HashOffset;
        ULONG HashFactor;
    } API_SET_NAMESPACE, * PAPI_SET_NAMESPACE;

    // private
    typedef struct _API_SET_HASH_ENTRY
    {
        ULONG Hash;
        ULONG Index;
    } API_SET_HASH_ENTRY, * PAPI_SET_HASH_ENTRY;

    // private
    typedef struct _API_SET_NAMESPACE_ENTRY
    {
        ULONG Flags;
        ULONG NameOffset;
        ULONG NameLength;
        ULONG HashedLength;
        ULONG ValueOffset;
        ULONG ValueCount;
    } API_SET_NAMESPACE_ENTRY, * PAPI_SET_NAMESPACE_ENTRY;

    // private
    typedef struct _API_SET_VALUE_ENTRY
    {
        ULONG Flags;
        ULONG NameOffset;
        ULONG NameLength;
        ULONG ValueOffset;
        ULONG ValueLength;
    } API_SET_VALUE_ENTRY, * PAPI_SET_VALUE_ENTRY;

    // symbols
    typedef struct _PEB
    {
        BOOLEAN InheritedAddressSpace;
        BOOLEAN ReadImageFileExecOptions;
        BOOLEAN BeingDebugged;
        union
        {
            BOOLEAN BitField;
            struct
            {
                BOOLEAN ImageUsesLargePages : 1;
                BOOLEAN IsProtectedProcess : 1;
                BOOLEAN IsImageDynamicallyRelocated : 1;
                BOOLEAN SkipPatchingUser32Forwarders : 1;
                BOOLEAN IsPackagedProcess : 1;
                BOOLEAN IsAppContainer : 1;
                BOOLEAN IsProtectedProcessLight : 1;
                BOOLEAN IsLongPathAwareProcess : 1;
            };
        };

        HANDLE Mutant;

        PVOID ImageBaseAddress;
        PPEB_LDR_DATA Ldr;
        PRTL_USER_PROCESS_PARAMETERS ProcessParameters;
        PVOID SubSystemData;
        PVOID ProcessHeap;
        PRTL_CRITICAL_SECTION FastPebLock;
        PSLIST_HEADER AtlThunkSListPtr;
        PVOID IFEOKey;

        union
        {
            ULONG CrossProcessFlags;
            struct
            {
                ULONG ProcessInJob : 1;
                ULONG ProcessInitializing : 1;
                ULONG ProcessUsingVEH : 1;
                ULONG ProcessUsingVCH : 1;
                ULONG ProcessUsingFTH : 1;
                ULONG ProcessPreviouslyThrottled : 1;
                ULONG ProcessCurrentlyThrottled : 1;
                ULONG ProcessImagesHotPatched : 1; // REDSTONE5
                ULONG ReservedBits0 : 24;
            };
        };
        union
        {
            PVOID KernelCallbackTable;
            PVOID UserSharedInfoPtr;
        };
        ULONG SystemReserved;
        ULONG AtlThunkSListPtr32;
        PAPI_SET_NAMESPACE ApiSetMap;
        ULONG TlsExpansionCounter;
        PVOID TlsBitmap;
        ULONG TlsBitmapBits[2]; // TLS_MINIMUM_AVAILABLE

        PVOID ReadOnlySharedMemoryBase;
        PSILO_USER_SHARED_DATA SharedData; // HotpatchInformation
        PVOID* ReadOnlyStaticServerData;

        PVOID AnsiCodePageData; // PCPTABLEINFO
        PVOID OemCodePageData; // PCPTABLEINFO
        PVOID UnicodeCaseTableData; // PNLSTABLEINFO

        ULONG NumberOfProcessors;
        ULONG NtGlobalFlag;

        ULARGE_INTEGER CriticalSectionTimeout;
        SIZE_T HeapSegmentReserve;
        SIZE_T HeapSegmentCommit;
        SIZE_T HeapDeCommitTotalFreeThreshold;
        SIZE_T HeapDeCommitFreeBlockThreshold;

        ULONG NumberOfHeaps;
        ULONG MaximumNumberOfHeaps;
        PVOID* ProcessHeaps; // PHEAP

        PVOID GdiSharedHandleTable; // PGDI_SHARED_MEMORY
        PVOID ProcessStarterHelper;
        ULONG GdiDCAttributeList;

        PRTL_CRITICAL_SECTION LoaderLock;

        ULONG OSMajorVersion;
        ULONG OSMinorVersion;
        USHORT OSBuildNumber;
        USHORT OSCSDVersion;
        ULONG OSPlatformId;
        ULONG ImageSubsystem;
        ULONG ImageSubsystemMajorVersion;
        ULONG ImageSubsystemMinorVersion;
        KAFFINITY ActiveProcessAffinityMask;
        GDI_HANDLE_BUFFER GdiHandleBuffer;
        PVOID PostProcessInitRoutine;

        PVOID TlsExpansionBitmap;
        ULONG TlsExpansionBitmapBits[32]; // TLS_EXPANSION_SLOTS

        ULONG SessionId;

        ULARGE_INTEGER AppCompatFlags; // KACF_*
        ULARGE_INTEGER AppCompatFlagsUser;
        PVOID pShimData;
        PVOID AppCompatInfo; // APPCOMPAT_EXE_DATA

        UNICODE_STRING CSDVersion;

        PACTIVATION_CONTEXT_DATA ActivationContextData;
        PASSEMBLY_STORAGE_MAP ProcessAssemblyStorageMap;
        PACTIVATION_CONTEXT_DATA SystemDefaultActivationContextData;
        PASSEMBLY_STORAGE_MAP SystemAssemblyStorageMap;

        SIZE_T MinimumStackCommit;

        PVOID SparePointers[2]; // 19H1 (previously FlsCallback to FlsHighIndex)
        PVOID PatchLoaderData;
        PVOID ChpeV2ProcessInfo; // _CHPEV2_PROCESS_INFO

        ULONG AppModelFeatureState;
        ULONG SpareUlongs[2];

        USHORT ActiveCodePage;
        USHORT OemCodePage;
        USHORT UseCaseMapping;
        USHORT UnusedNlsField;

        PVOID WerRegistrationData;
        PVOID WerShipAssertPtr;

        union
        {
            PVOID pContextData; // WIN7
            PVOID pUnused; // WIN10
            PVOID EcCodeBitMap; // WIN11
        };

        PVOID pImageHeaderHash;
        union
        {
            ULONG TracingFlags;
            struct
            {
                ULONG HeapTracingEnabled : 1;
                ULONG CritSecTracingEnabled : 1;
                ULONG LibLoaderTracingEnabled : 1;
                ULONG SpareTracingBits : 29;
            };
        };
        ULONGLONG CsrServerReadOnlySharedMemoryBase;
        PRTL_CRITICAL_SECTION TppWorkerpListLock;
        LIST_ENTRY TppWorkerpList;
        PVOID WaitOnAddressHashTable[128];
        PVOID TelemetryCoverageHeader; // REDSTONE3
        ULONG CloudFileFlags;
        ULONG CloudFileDiagFlags; // REDSTONE4
        CHAR PlaceholderCompatibilityMode;
        CHAR PlaceholderCompatibilityModeReserved[7];
        PLEAP_SECOND_DATA LeapSecondData; // REDSTONE5
        union
        {
            ULONG LeapSecondFlags;
            struct
            {
                ULONG SixtySecondEnabled : 1;
                ULONG Reserved : 31;
            };
        };
        ULONG NtGlobalFlag2;
        ULONGLONG ExtendedFeatureDisableMask; // since WIN11
    } PEB, * PPEB;

#ifdef _WIN64
    C_ASSERT(FIELD_OFFSET(PEB, SessionId) == 0x2C0);
    //C_ASSERT(sizeof(PEB) == 0x7B0); // REDSTONE3
    //C_ASSERT(sizeof(PEB) == 0x7B8); // REDSTONE4
    //C_ASSERT(sizeof(PEB) == 0x7C8); // REDSTONE5 // 19H1
    C_ASSERT(sizeof(PEB) == 0x7d0); // WIN11
#else
    C_ASSERT(FIELD_OFFSET(PEB, SessionId) == 0x1D4);
    //C_ASSERT(sizeof(PEB) == 0x468); // REDSTONE3
    //C_ASSERT(sizeof(PEB) == 0x470); // REDSTONE4
    //C_ASSERT(sizeof(PEB) == 0x480); // REDSTONE5 // 19H1
    C_ASSERT(sizeof(PEB) == 0x488); // WIN11
#endif

#define GDI_BATCH_BUFFER_SIZE 310

    typedef struct _GDI_TEB_BATCH
    {
        ULONG Offset;
        ULONG_PTR HDC;
        ULONG Buffer[GDI_BATCH_BUFFER_SIZE];
    } GDI_TEB_BATCH, * PGDI_TEB_BATCH;

    typedef struct _TEB_ACTIVE_FRAME_CONTEXT
    {
        ULONG Flags;
        PSTR FrameName;
    } TEB_ACTIVE_FRAME_CONTEXT, * PTEB_ACTIVE_FRAME_CONTEXT;

    typedef struct _TEB_ACTIVE_FRAME_CONTEXT_EX
    {
        TEB_ACTIVE_FRAME_CONTEXT BasicContext;
        PSTR SourceLocation;
    } TEB_ACTIVE_FRAME_CONTEXT_EX, * PTEB_ACTIVE_FRAME_CONTEXT_EX;

    typedef struct _TEB_ACTIVE_FRAME
    {
        ULONG Flags;
        struct _TEB_ACTIVE_FRAME* Previous;
        PTEB_ACTIVE_FRAME_CONTEXT Context;
    } TEB_ACTIVE_FRAME, * PTEB_ACTIVE_FRAME;

    typedef struct _TEB_ACTIVE_FRAME_EX
    {
        TEB_ACTIVE_FRAME BasicFrame;
        PVOID ExtensionIdentifier;
    } TEB_ACTIVE_FRAME_EX, * PTEB_ACTIVE_FRAME_EX;

#define STATIC_UNICODE_BUFFER_LENGTH 261
#define WIN32_CLIENT_INFO_LENGTH 62

    typedef struct _TEB
    {
        NT_TIB NtTib;

        PVOID EnvironmentPointer;
        CLIENT_ID ClientId;
        PVOID ActiveRpcHandle;
        PVOID ThreadLocalStoragePointer;
        PPEB ProcessEnvironmentBlock;

        ULONG LastErrorValue;
        ULONG CountOfOwnedCriticalSections;
        PVOID CsrClientThread;
        PVOID Win32ThreadInfo;
        ULONG User32Reserved[26];
        ULONG UserReserved[5];
        PVOID WOW32Reserved;
        LCID CurrentLocale;
        ULONG FpSoftwareStatusRegister;
        PVOID ReservedForDebuggerInstrumentation[16];
#ifdef _WIN64
        PVOID SystemReserved1[30];
#else
        PVOID SystemReserved1[26];
#endif

        CHAR PlaceholderCompatibilityMode;
        BOOLEAN PlaceholderHydrationAlwaysExplicit;
        CHAR PlaceholderReserved[10];

        ULONG ProxiedProcessId;
        ACTIVATION_CONTEXT_STACK ActivationStack;

        UCHAR WorkingOnBehalfTicket[8];
        NTSTATUS ExceptionCode;

        PACTIVATION_CONTEXT_STACK ActivationContextStackPointer;
        ULONG_PTR InstrumentationCallbackSp;
        ULONG_PTR InstrumentationCallbackPreviousPc;
        ULONG_PTR InstrumentationCallbackPreviousSp;
#ifdef _WIN64
        ULONG TxFsContext;
#endif

        BOOLEAN InstrumentationCallbackDisabled;
#ifdef _WIN64
        BOOLEAN UnalignedLoadStoreExceptions;
#endif
#ifndef _WIN64
        UCHAR SpareBytes[23];
        ULONG TxFsContext;
#endif
        GDI_TEB_BATCH GdiTebBatch;
        CLIENT_ID RealClientId;
        HANDLE GdiCachedProcessHandle;
        ULONG GdiClientPID;
        ULONG GdiClientTID;
        PVOID GdiThreadLocalInfo;
        ULONG_PTR Win32ClientInfo[WIN32_CLIENT_INFO_LENGTH];

        PVOID glDispatchTable[233];
        ULONG_PTR glReserved1[29];
        PVOID glReserved2;
        PVOID glSectionInfo;
        PVOID glSection;
        PVOID glTable;
        PVOID glCurrentRC;
        PVOID glContext;

        NTSTATUS LastStatusValue;
        UNICODE_STRING StaticUnicodeString;
        WCHAR StaticUnicodeBuffer[STATIC_UNICODE_BUFFER_LENGTH];

        PVOID DeallocationStack;
        PVOID TlsSlots[TLS_MINIMUM_AVAILABLE];
        LIST_ENTRY TlsLinks;

        PVOID Vdm;
        PVOID ReservedForNtRpc;
        PVOID DbgSsReserved[2];

        ULONG HardErrorMode;
#ifdef _WIN64
        PVOID Instrumentation[11];
#else
        PVOID Instrumentation[9];
#endif
        GUID ActivityId;

        PVOID SubProcessTag;
        PVOID PerflibData;
        PVOID EtwTraceData;
        PVOID WinSockData;
        ULONG GdiBatchCount;

        union
        {
            PROCESSOR_NUMBER CurrentIdealProcessor;
            ULONG IdealProcessorValue;
            struct
            {
                UCHAR ReservedPad0;
                UCHAR ReservedPad1;
                UCHAR ReservedPad2;
                UCHAR IdealProcessor;
            };
        };

        ULONG GuaranteedStackBytes;
        PVOID ReservedForPerf;
        PVOID ReservedForOle; // tagSOleTlsData
        ULONG WaitingOnLoaderLock;
        PVOID SavedPriorityState;
        ULONG_PTR ReservedForCodeCoverage;
        PVOID ThreadPoolData;
        PVOID* TlsExpansionSlots;
#ifdef _WIN64
        PVOID DeallocationBStore;
        PVOID BStoreLimit;
#endif
        ULONG MuiGeneration;
        ULONG IsImpersonating;
        PVOID NlsCache;
        PVOID pShimData;
        ULONG HeapData;
        HANDLE CurrentTransactionHandle;
        PTEB_ACTIVE_FRAME ActiveFrame;
        PVOID FlsData;

        PVOID PreferredLanguages;
        PVOID UserPrefLanguages;
        PVOID MergedPrefLanguages;
        ULONG MuiImpersonation;

        union
        {
            USHORT CrossTebFlags;
            USHORT SpareCrossTebBits : 16;
        };
        union
        {
            USHORT SameTebFlags;
            struct
            {
                USHORT SafeThunkCall : 1;
                USHORT InDebugPrint : 1;
                USHORT HasFiberData : 1;
                USHORT SkipThreadAttach : 1;
                USHORT WerInShipAssertCode : 1;
                USHORT RanProcessInit : 1;
                USHORT ClonedThread : 1;
                USHORT SuppressDebugMsg : 1;
                USHORT DisableUserStackWalk : 1;
                USHORT RtlExceptionAttached : 1;
                USHORT InitialThread : 1;
                USHORT SessionAware : 1;
                USHORT LoadOwner : 1;
                USHORT LoaderWorker : 1;
                USHORT SkipLoaderInit : 1;
                USHORT SkipFileAPIBrokering : 1;
            };
        };

        PVOID TxnScopeEnterCallback;
        PVOID TxnScopeExitCallback;
        PVOID TxnScopeContext;
        ULONG LockCount;
        LONG WowTebOffset;
        PVOID ResourceRetValue;
        PVOID ReservedForWdf;
        ULONGLONG ReservedForCrt;
        GUID EffectiveContainerId;
        ULONGLONG LastSleepCounter; // Win11
        ULONG SpinCallCount;
        ULONGLONG ExtendedFeatureDisableMask;
    } TEB, * PTEB;

#ifdef _WIN64
    C_ASSERT(sizeof(TEB) == 0x1850); // WIN11
#else
    C_ASSERT(sizeof(TEB) == 0x1018); // WIN11
#endif

#endif

#if (PHNT_MODE != PHNT_MODE_KERNEL)
    typedef enum _PROCESSINFOCLASS
    {
        ProcessBasicInformation, // q: PROCESS_BASIC_INFORMATION, PROCESS_EXTENDED_BASIC_INFORMATION
        ProcessQuotaLimits, // qs: QUOTA_LIMITS, QUOTA_LIMITS_EX
        ProcessIoCounters, // q: IO_COUNTERS
        ProcessVmCounters, // q: VM_COUNTERS, VM_COUNTERS_EX, VM_COUNTERS_EX2
        ProcessTimes, // q: KERNEL_USER_TIMES
        ProcessBasePriority, // s: KPRIORITY
        ProcessRaisePriority, // s: ULONG
        ProcessDebugPort, // q: HANDLE
        ProcessExceptionPort, // s: PROCESS_EXCEPTION_PORT (requires SeTcbPrivilege)
        ProcessAccessToken, // s: PROCESS_ACCESS_TOKEN
        ProcessLdtInformation, // qs: PROCESS_LDT_INFORMATION // 10
        ProcessLdtSize, // s: PROCESS_LDT_SIZE
        ProcessDefaultHardErrorMode, // qs: ULONG
        ProcessIoPortHandlers, // (kernel-mode only) // PROCESS_IO_PORT_HANDLER_INFORMATION
        ProcessPooledUsageAndLimits, // q: POOLED_USAGE_AND_LIMITS
        ProcessWorkingSetWatch, // q: PROCESS_WS_WATCH_INFORMATION[]; s: void
        ProcessUserModeIOPL, // qs: ULONG (requires SeTcbPrivilege)
        ProcessEnableAlignmentFaultFixup, // s: BOOLEAN
        ProcessPriorityClass, // qs: PROCESS_PRIORITY_CLASS
        ProcessWx86Information, // qs: ULONG (requires SeTcbPrivilege) (VdmAllowed)
        ProcessHandleCount, // q: ULONG, PROCESS_HANDLE_INFORMATION // 20
        ProcessAffinityMask, // (q >WIN7)s: KAFFINITY, qs: GROUP_AFFINITY
        ProcessPriorityBoost, // qs: ULONG
        ProcessDeviceMap, // qs: PROCESS_DEVICEMAP_INFORMATION, PROCESS_DEVICEMAP_INFORMATION_EX
        ProcessSessionInformation, // q: PROCESS_SESSION_INFORMATION
        ProcessForegroundInformation, // s: PROCESS_FOREGROUND_BACKGROUND
        ProcessWow64Information, // q: ULONG_PTR
        ProcessImageFileName, // q: UNICODE_STRING
        ProcessLUIDDeviceMapsEnabled, // q: ULONG
        ProcessBreakOnTermination, // qs: ULONG
        ProcessDebugObjectHandle, // q: HANDLE // 30
        ProcessDebugFlags, // qs: ULONG
        ProcessHandleTracing, // q: PROCESS_HANDLE_TRACING_QUERY; s: size 0 disables, otherwise enables
        ProcessIoPriority, // qs: IO_PRIORITY_HINT
        ProcessExecuteFlags, // qs: ULONG
        ProcessTlsInformation, // PROCESS_TLS_INFORMATION // ProcessResourceManagement
        ProcessCookie, // q: ULONG
        ProcessImageInformation, // q: SECTION_IMAGE_INFORMATION
        ProcessCycleTime, // q: PROCESS_CYCLE_TIME_INFORMATION // since VISTA
        ProcessPagePriority, // qs: PAGE_PRIORITY_INFORMATION
        ProcessInstrumentationCallback, // s: PVOID or PROCESS_INSTRUMENTATION_CALLBACK_INFORMATION // 40
        ProcessThreadStackAllocation, // s: PROCESS_STACK_ALLOCATION_INFORMATION, PROCESS_STACK_ALLOCATION_INFORMATION_EX
        ProcessWorkingSetWatchEx, // q: PROCESS_WS_WATCH_INFORMATION_EX[]
        ProcessImageFileNameWin32, // q: UNICODE_STRING
        ProcessImageFileMapping, // q: HANDLE (input)
        ProcessAffinityUpdateMode, // qs: PROCESS_AFFINITY_UPDATE_MODE
        ProcessMemoryAllocationMode, // qs: PROCESS_MEMORY_ALLOCATION_MODE
        ProcessGroupInformation, // q: USHORT[]
        ProcessTokenVirtualizationEnabled, // s: ULONG
        ProcessConsoleHostProcess, // qs: ULONG_PTR // ProcessOwnerInformation
        ProcessWindowInformation, // q: PROCESS_WINDOW_INFORMATION // 50
        ProcessHandleInformation, // q: PROCESS_HANDLE_SNAPSHOT_INFORMATION // since WIN8
        ProcessMitigationPolicy, // s: PROCESS_MITIGATION_POLICY_INFORMATION
        ProcessDynamicFunctionTableInformation,
        ProcessHandleCheckingMode, // qs: ULONG; s: 0 disables, otherwise enables
        ProcessKeepAliveCount, // q: PROCESS_KEEPALIVE_COUNT_INFORMATION
        ProcessRevokeFileHandles, // s: PROCESS_REVOKE_FILE_HANDLES_INFORMATION
        ProcessWorkingSetControl, // s: PROCESS_WORKING_SET_CONTROL (requires SeDebugPrivilege)
        ProcessHandleTable, // q: ULONG[] // since WINBLUE
        ProcessCheckStackExtentsMode, // qs: ULONG // KPROCESS->CheckStackExtents (CFG)
        ProcessCommandLineInformation, // q: UNICODE_STRING // 60
        ProcessProtectionInformation, // q: PS_PROTECTION
        ProcessMemoryExhaustion, // PROCESS_MEMORY_EXHAUSTION_INFO // since THRESHOLD
        ProcessFaultInformation, // PROCESS_FAULT_INFORMATION
        ProcessTelemetryIdInformation, // q: PROCESS_TELEMETRY_ID_INFORMATION
        ProcessCommitReleaseInformation, // PROCESS_COMMIT_RELEASE_INFORMATION
        ProcessDefaultCpuSetsInformation, // SYSTEM_CPU_SET_INFORMATION[5]
        ProcessAllowedCpuSetsInformation, // SYSTEM_CPU_SET_INFORMATION[5]
        ProcessSubsystemProcess,
        ProcessJobMemoryInformation, // q: PROCESS_JOB_MEMORY_INFO
        ProcessInPrivate, // s: void // ETW // since THRESHOLD2 // 70
        ProcessRaiseUMExceptionOnInvalidHandleClose, // qs: ULONG; s: 0 disables, otherwise enables
        ProcessIumChallengeResponse,
        ProcessChildProcessInformation, // q: PROCESS_CHILD_PROCESS_INFORMATION
        ProcessHighGraphicsPriorityInformation, // qs: BOOLEAN (requires SeTcbPrivilege)
        ProcessSubsystemInformation, // q: SUBSYSTEM_INFORMATION_TYPE // since REDSTONE2
        ProcessEnergyValues, // q: PROCESS_ENERGY_VALUES, PROCESS_EXTENDED_ENERGY_VALUES
        ProcessPowerThrottlingState, // qs: POWER_THROTTLING_PROCESS_STATE
        ProcessReserved3Information, // ProcessActivityThrottlePolicy // PROCESS_ACTIVITY_THROTTLE_POLICY
        ProcessWin32kSyscallFilterInformation, // q: WIN32K_SYSCALL_FILTER
        ProcessDisableSystemAllowedCpuSets, // 80
        ProcessWakeInformation, // PROCESS_WAKE_INFORMATION
        ProcessEnergyTrackingState, // qs: PROCESS_ENERGY_TRACKING_STATE
        ProcessManageWritesToExecutableMemory, // MANAGE_WRITES_TO_EXECUTABLE_MEMORY // since REDSTONE3
        ProcessCaptureTrustletLiveDump,
        ProcessTelemetryCoverage,
        ProcessEnclaveInformation,
        ProcessEnableReadWriteVmLogging, // PROCESS_READWRITEVM_LOGGING_INFORMATION
        ProcessUptimeInformation, // q: PROCESS_UPTIME_INFORMATION
        ProcessImageSection, // q: HANDLE
        ProcessDebugAuthInformation, // since REDSTONE4 // 90
        ProcessSystemResourceManagement, // PROCESS_SYSTEM_RESOURCE_MANAGEMENT
        ProcessSequenceNumber, // q: ULONGLONG
        ProcessLoaderDetour, // since REDSTONE5
        ProcessSecurityDomainInformation, // PROCESS_SECURITY_DOMAIN_INFORMATION
        ProcessCombineSecurityDomainsInformation, // PROCESS_COMBINE_SECURITY_DOMAINS_INFORMATION
        ProcessEnableLogging, // PROCESS_LOGGING_INFORMATION
        ProcessLeapSecondInformation, // PROCESS_LEAP_SECOND_INFORMATION
        ProcessFiberShadowStackAllocation, // PROCESS_FIBER_SHADOW_STACK_ALLOCATION_INFORMATION // since 19H1
        ProcessFreeFiberShadowStackAllocation, // PROCESS_FREE_FIBER_SHADOW_STACK_ALLOCATION_INFORMATION
        ProcessAltSystemCallInformation, // since 20H1 // 100
        ProcessDynamicEHContinuationTargets, // PROCESS_DYNAMIC_EH_CONTINUATION_TARGETS_INFORMATION
        ProcessDynamicEnforcedCetCompatibleRanges, // PROCESS_DYNAMIC_ENFORCED_ADDRESS_RANGE_INFORMATION // since 20H2
        ProcessCreateStateChange, // since WIN11
        ProcessApplyStateChange,
        ProcessEnableOptionalXStateFeatures, // ULONG64 // optional XState feature bitmask
        ProcessAltPrefetchParam, // since 22H1
        ProcessAssignCpuPartitions,
        ProcessPriorityClassEx, // s: PROCESS_PRIORITY_CLASS_EX
        ProcessMembershipInformation, // PROCESS_MEMBERSHIP_INFORMATION
        ProcessEffectiveIoPriority, // q: IO_PRIORITY_HINT
        ProcessEffectivePagePriority, // q: ULONG
        MaxProcessInfoClass
    } PROCESSINFOCLASS;
#endif

#if (PHNT_MODE != PHNT_MODE_KERNEL)
    typedef enum _THREADINFOCLASS
    {
        ThreadBasicInformation, // q: THREAD_BASIC_INFORMATION
        ThreadTimes, // q: KERNEL_USER_TIMES
        ThreadPriority, // s: KPRIORITY (requires SeIncreaseBasePriorityPrivilege)
        ThreadBasePriority, // s: KPRIORITY
        ThreadAffinityMask, // s: KAFFINITY
        ThreadImpersonationToken, // s: HANDLE
        ThreadDescriptorTableEntry, // q: DESCRIPTOR_TABLE_ENTRY (or WOW64_DESCRIPTOR_TABLE_ENTRY)
        ThreadEnableAlignmentFaultFixup, // s: BOOLEAN
        ThreadEventPair,
        ThreadQuerySetWin32StartAddress, // q: ULONG_PTR
        ThreadZeroTlsCell, // s: ULONG // TlsIndex // 10
        ThreadPerformanceCount, // q: LARGE_INTEGER
        ThreadAmILastThread, // q: ULONG
        ThreadIdealProcessor, // s: ULONG
        ThreadPriorityBoost, // qs: ULONG
        ThreadSetTlsArrayAddress, // s: ULONG_PTR // Obsolete
        ThreadIsIoPending, // q: ULONG
        ThreadHideFromDebugger, // q: BOOLEAN; s: void
        ThreadBreakOnTermination, // qs: ULONG
        ThreadSwitchLegacyState, // s: void // NtCurrentThread // NPX/FPU
        ThreadIsTerminated, // q: ULONG // 20
        ThreadLastSystemCall, // q: THREAD_LAST_SYSCALL_INFORMATION
        ThreadIoPriority, // qs: IO_PRIORITY_HINT (requires SeIncreaseBasePriorityPrivilege)
        ThreadCycleTime, // q: THREAD_CYCLE_TIME_INFORMATION
        ThreadPagePriority, // qs: PAGE_PRIORITY_INFORMATION
        ThreadActualBasePriority, // s: LONG (requires SeIncreaseBasePriorityPrivilege)
        ThreadTebInformation, // q: THREAD_TEB_INFORMATION (requires THREAD_GET_CONTEXT + THREAD_SET_CONTEXT)
        ThreadCSwitchMon, // Obsolete
        ThreadCSwitchPmu,
        ThreadWow64Context, // qs: WOW64_CONTEXT, ARM_NT_CONTEXT since 20H1
        ThreadGroupInformation, // qs: GROUP_AFFINITY // 30
        ThreadUmsInformation, // q: THREAD_UMS_INFORMATION // Obsolete
        ThreadCounterProfiling, // q: BOOLEAN; s: THREAD_PROFILING_INFORMATION?
        ThreadIdealProcessorEx, // qs: PROCESSOR_NUMBER; s: previous PROCESSOR_NUMBER on return
        ThreadCpuAccountingInformation, // q: BOOLEAN; s: HANDLE (NtOpenSession) // NtCurrentThread // since WIN8
        ThreadSuspendCount, // q: ULONG // since WINBLUE
        ThreadHeterogeneousCpuPolicy, // q: KHETERO_CPU_POLICY // since THRESHOLD
        ThreadContainerId, // q: GUID
        ThreadNameInformation, // qs: THREAD_NAME_INFORMATION
        ThreadSelectedCpuSets,
        ThreadSystemThreadInformation, // q: SYSTEM_THREAD_INFORMATION // 40
        ThreadActualGroupAffinity, // q: GROUP_AFFINITY // since THRESHOLD2
        ThreadDynamicCodePolicyInfo, // q: ULONG; s: ULONG (NtCurrentThread)
        ThreadExplicitCaseSensitivity, // qs: ULONG; s: 0 disables, otherwise enables
        ThreadWorkOnBehalfTicket, // RTL_WORK_ON_BEHALF_TICKET_EX
        ThreadSubsystemInformation, // q: SUBSYSTEM_INFORMATION_TYPE // since REDSTONE2
        ThreadDbgkWerReportActive, // s: ULONG; s: 0 disables, otherwise enables
        ThreadAttachContainer, // s: HANDLE (job object) // NtCurrentThread
        ThreadManageWritesToExecutableMemory, // MANAGE_WRITES_TO_EXECUTABLE_MEMORY // since REDSTONE3
        ThreadPowerThrottlingState, // POWER_THROTTLING_THREAD_STATE
        ThreadWorkloadClass, // THREAD_WORKLOAD_CLASS // since REDSTONE5 // 50
        ThreadCreateStateChange, // since WIN11
        ThreadApplyStateChange,
        ThreadStrongerBadHandleChecks, // since 22H1
        ThreadEffectiveIoPriority, // q: IO_PRIORITY_HINT
        ThreadEffectivePagePriority, // q: ULONG
        MaxThreadInfoClass
    } THREADINFOCLASS;
#endif

#if (PHNT_MODE != PHNT_MODE_KERNEL)
    // Use with both ProcessPagePriority and ThreadPagePriority
    typedef struct _PAGE_PRIORITY_INFORMATION
    {
        ULONG PagePriority;
    } PAGE_PRIORITY_INFORMATION, * PPAGE_PRIORITY_INFORMATION;
#endif

    // Process information structures

#if (PHNT_MODE != PHNT_MODE_KERNEL)

    typedef struct _PROCESS_BASIC_INFORMATION
    {
        NTSTATUS ExitStatus;
        PPEB PebBaseAddress;
        KAFFINITY AffinityMask;
        KPRIORITY BasePriority;
        HANDLE UniqueProcessId;
        HANDLE InheritedFromUniqueProcessId;
    } PROCESS_BASIC_INFORMATION, * PPROCESS_BASIC_INFORMATION;

    typedef struct _PROCESS_EXTENDED_BASIC_INFORMATION
    {
        SIZE_T Size; // set to sizeof structure on input
        PROCESS_BASIC_INFORMATION BasicInfo;
        union
        {
            ULONG Flags;
            struct
            {
                ULONG IsProtectedProcess : 1;
                ULONG IsWow64Process : 1;
                ULONG IsProcessDeleting : 1;
                ULONG IsCrossSessionCreate : 1;
                ULONG IsFrozen : 1;
                ULONG IsBackground : 1;
                ULONG IsStronglyNamed : 1;
                ULONG IsSecureProcess : 1;
                ULONG IsSubsystemProcess : 1;
                ULONG SpareBits : 23;
            };
        };
    } PROCESS_EXTENDED_BASIC_INFORMATION, * PPROCESS_EXTENDED_BASIC_INFORMATION;

    typedef struct _VM_COUNTERS
    {
        SIZE_T PeakVirtualSize;
        SIZE_T VirtualSize;
        ULONG PageFaultCount;
        SIZE_T PeakWorkingSetSize;
        SIZE_T WorkingSetSize;
        SIZE_T QuotaPeakPagedPoolUsage;
        SIZE_T QuotaPagedPoolUsage;
        SIZE_T QuotaPeakNonPagedPoolUsage;
        SIZE_T QuotaNonPagedPoolUsage;
        SIZE_T PagefileUsage;
        SIZE_T PeakPagefileUsage;
    } VM_COUNTERS, * PVM_COUNTERS;

    typedef struct _VM_COUNTERS_EX
    {
        SIZE_T PeakVirtualSize;
        SIZE_T VirtualSize;
        ULONG PageFaultCount;
        SIZE_T PeakWorkingSetSize;
        SIZE_T WorkingSetSize;
        SIZE_T QuotaPeakPagedPoolUsage;
        SIZE_T QuotaPagedPoolUsage;
        SIZE_T QuotaPeakNonPagedPoolUsage;
        SIZE_T QuotaNonPagedPoolUsage;
        SIZE_T PagefileUsage;
        SIZE_T PeakPagefileUsage;
        SIZE_T PrivateUsage;
    } VM_COUNTERS_EX, * PVM_COUNTERS_EX;

    typedef struct _VM_COUNTERS_EX2
    {
        VM_COUNTERS_EX CountersEx;
        SIZE_T PrivateWorkingSetSize;
        SIZE_T SharedCommitUsage;
    } VM_COUNTERS_EX2, * PVM_COUNTERS_EX2;

    typedef struct _KERNEL_USER_TIMES
    {
        LARGE_INTEGER CreateTime;
        LARGE_INTEGER ExitTime;
        LARGE_INTEGER KernelTime;
        LARGE_INTEGER UserTime;
    } KERNEL_USER_TIMES, * PKERNEL_USER_TIMES;

    typedef struct _POOLED_USAGE_AND_LIMITS
    {
        SIZE_T PeakPagedPoolUsage;
        SIZE_T PagedPoolUsage;
        SIZE_T PagedPoolLimit;
        SIZE_T PeakNonPagedPoolUsage;
        SIZE_T NonPagedPoolUsage;
        SIZE_T NonPagedPoolLimit;
        SIZE_T PeakPagefileUsage;
        SIZE_T PagefileUsage;
        SIZE_T PagefileLimit;
    } POOLED_USAGE_AND_LIMITS, * PPOOLED_USAGE_AND_LIMITS;

#define PROCESS_EXCEPTION_PORT_ALL_STATE_BITS 0x00000003
#define PROCESS_EXCEPTION_PORT_ALL_STATE_FLAGS ((ULONG_PTR)((1UL << PROCESS_EXCEPTION_PORT_ALL_STATE_BITS) - 1))

    typedef struct _PROCESS_EXCEPTION_PORT
    {
        _In_ HANDLE ExceptionPortHandle; // Handle to the exception port. No particular access required.
        _Inout_ ULONG StateFlags; // Miscellaneous state flags to be cached along with the exception port in the kernel.
    } PROCESS_EXCEPTION_PORT, * PPROCESS_EXCEPTION_PORT;

    typedef struct _PROCESS_ACCESS_TOKEN
    {
        HANDLE Token; // needs TOKEN_ASSIGN_PRIMARY access
        HANDLE Thread; // handle to initial/only thread; needs THREAD_QUERY_INFORMATION access
    } PROCESS_ACCESS_TOKEN, * PPROCESS_ACCESS_TOKEN;

    typedef struct _PROCESS_LDT_INFORMATION
    {
        ULONG Start;
        ULONG Length;
        LDT_ENTRY LdtEntries[1];
    } PROCESS_LDT_INFORMATION, * PPROCESS_LDT_INFORMATION;

    typedef struct _PROCESS_LDT_SIZE
    {
        ULONG Length;
    } PROCESS_LDT_SIZE, * PPROCESS_LDT_SIZE;

    typedef struct _PROCESS_WS_WATCH_INFORMATION
    {
        PVOID FaultingPc;
        PVOID FaultingVa;
    } PROCESS_WS_WATCH_INFORMATION, * PPROCESS_WS_WATCH_INFORMATION;

#endif

    // psapi:PSAPI_WS_WATCH_INFORMATION_EX
    typedef struct _PROCESS_WS_WATCH_INFORMATION_EX
    {
        PROCESS_WS_WATCH_INFORMATION BasicInfo;
        ULONG_PTR FaultingThreadId;
        ULONG_PTR Flags;
    } PROCESS_WS_WATCH_INFORMATION_EX, * PPROCESS_WS_WATCH_INFORMATION_EX;

#define PROCESS_PRIORITY_CLASS_UNKNOWN 0
#define PROCESS_PRIORITY_CLASS_IDLE 1
#define PROCESS_PRIORITY_CLASS_NORMAL 2
#define PROCESS_PRIORITY_CLASS_HIGH 3
#define PROCESS_PRIORITY_CLASS_REALTIME 4
#define PROCESS_PRIORITY_CLASS_BELOW_NORMAL 5
#define PROCESS_PRIORITY_CLASS_ABOVE_NORMAL 6

    typedef struct _PROCESS_PRIORITY_CLASS
    {
        BOOLEAN Foreground;
        UCHAR PriorityClass;
    } PROCESS_PRIORITY_CLASS, * PPROCESS_PRIORITY_CLASS;

    typedef struct _PROCESS_PRIORITY_CLASS_EX
    {
        union
        {
            struct
            {
                USHORT ForegroundValid : 1;
                USHORT PriorityClassValid : 1;
            };
            USHORT AllFlags;
        };
        UCHAR PriorityClass;
        BOOLEAN Foreground;
    } PROCESS_PRIORITY_CLASS_EX, * PPROCESS_PRIORITY_CLASS_EX;

    typedef struct _PROCESS_FOREGROUND_BACKGROUND
    {
        BOOLEAN Foreground;
    } PROCESS_FOREGROUND_BACKGROUND, * PPROCESS_FOREGROUND_BACKGROUND;

#if (PHNT_MODE != PHNT_MODE_KERNEL)

    typedef struct _PROCESS_DEVICEMAP_INFORMATION
    {
        union
        {
            struct
            {
                HANDLE DirectoryHandle;
            } Set;
            struct
            {
                ULONG DriveMap;
                UCHAR DriveType[32];
            } Query;
        };
    } PROCESS_DEVICEMAP_INFORMATION, * PPROCESS_DEVICEMAP_INFORMATION;

#define PROCESS_LUID_DOSDEVICES_ONLY 0x00000001

    typedef struct _PROCESS_DEVICEMAP_INFORMATION_EX
    {
        union
        {
            struct
            {
                HANDLE DirectoryHandle;
            } Set;
            struct
            {
                ULONG DriveMap;
                UCHAR DriveType[32];
            } Query;
        };
        ULONG Flags; // PROCESS_LUID_DOSDEVICES_ONLY
    } PROCESS_DEVICEMAP_INFORMATION_EX, * PPROCESS_DEVICEMAP_INFORMATION_EX;

    typedef struct _PROCESS_SESSION_INFORMATION
    {
        ULONG SessionId;
    } PROCESS_SESSION_INFORMATION, * PPROCESS_SESSION_INFORMATION;

#define PROCESS_HANDLE_EXCEPTIONS_ENABLED 0x00000001

#define PROCESS_HANDLE_RAISE_EXCEPTION_ON_INVALID_HANDLE_CLOSE_DISABLED 0x00000000
#define PROCESS_HANDLE_RAISE_EXCEPTION_ON_INVALID_HANDLE_CLOSE_ENABLED 0x00000001

    typedef struct _PROCESS_HANDLE_TRACING_ENABLE
    {
        ULONG Flags;
    } PROCESS_HANDLE_TRACING_ENABLE, * PPROCESS_HANDLE_TRACING_ENABLE;

#define PROCESS_HANDLE_TRACING_MAX_SLOTS 0x20000

    typedef struct _PROCESS_HANDLE_TRACING_ENABLE_EX
    {
        ULONG Flags;
        ULONG TotalSlots;
    } PROCESS_HANDLE_TRACING_ENABLE_EX, * PPROCESS_HANDLE_TRACING_ENABLE_EX;

#define PROCESS_HANDLE_TRACING_MAX_STACKS 16

#define PROCESS_HANDLE_TRACE_TYPE_OPEN 1
#define PROCESS_HANDLE_TRACE_TYPE_CLOSE 2
#define PROCESS_HANDLE_TRACE_TYPE_BADREF 3

    typedef struct _PROCESS_HANDLE_TRACING_ENTRY
    {
        HANDLE Handle;
        CLIENT_ID ClientId;
        ULONG Type;
        PVOID Stacks[PROCESS_HANDLE_TRACING_MAX_STACKS];
    } PROCESS_HANDLE_TRACING_ENTRY, * PPROCESS_HANDLE_TRACING_ENTRY;

    typedef struct _PROCESS_HANDLE_TRACING_QUERY
    {
        HANDLE Handle;
        ULONG TotalTraces;
        _Field_size_(TotalTraces) PROCESS_HANDLE_TRACING_ENTRY HandleTrace[1];
    } PROCESS_HANDLE_TRACING_QUERY, * PPROCESS_HANDLE_TRACING_QUERY;

#endif

    typedef struct _THREAD_TLS_INFORMATION
    {
        ULONG Flags;
        PVOID NewTlsData;
        PVOID OldTlsData;
        HANDLE ThreadId;
    } THREAD_TLS_INFORMATION, * PTHREAD_TLS_INFORMATION;

    typedef enum _PROCESS_TLS_INFORMATION_TYPE
    {
        ProcessTlsReplaceIndex,
        ProcessTlsReplaceVector,
        MaxProcessTlsOperation
    } PROCESS_TLS_INFORMATION_TYPE, * PPROCESS_TLS_INFORMATION_TYPE;

    typedef struct _PROCESS_TLS_INFORMATION
    {
        ULONG Flags;
        ULONG OperationType;
        ULONG ThreadDataCount;
        ULONG TlsIndex;
        ULONG PreviousCount;
        _Field_size_(ThreadDataCount) THREAD_TLS_INFORMATION ThreadData[1];
    } PROCESS_TLS_INFORMATION, * PPROCESS_TLS_INFORMATION;

    typedef struct _PROCESS_INSTRUMENTATION_CALLBACK_INFORMATION
    {
        ULONG Version;
        ULONG Reserved;
        PVOID Callback;
    } PROCESS_INSTRUMENTATION_CALLBACK_INFORMATION, * PPROCESS_INSTRUMENTATION_CALLBACK_INFORMATION;

    typedef struct _PROCESS_STACK_ALLOCATION_INFORMATION
    {
        SIZE_T ReserveSize;
        SIZE_T ZeroBits;
        PVOID StackBase;
    } PROCESS_STACK_ALLOCATION_INFORMATION, * PPROCESS_STACK_ALLOCATION_INFORMATION;

    typedef struct _PROCESS_STACK_ALLOCATION_INFORMATION_EX
    {
        ULONG PreferredNode;
        ULONG Reserved0;
        ULONG Reserved1;
        ULONG Reserved2;
        PROCESS_STACK_ALLOCATION_INFORMATION AllocInfo;
    } PROCESS_STACK_ALLOCATION_INFORMATION_EX, * PPROCESS_STACK_ALLOCATION_INFORMATION_EX;

    typedef union _PROCESS_AFFINITY_UPDATE_MODE
    {
        ULONG Flags;
        struct
        {
            ULONG EnableAutoUpdate : 1;
            ULONG Permanent : 1;
            ULONG Reserved : 30;
        };
    } PROCESS_AFFINITY_UPDATE_MODE, * PPROCESS_AFFINITY_UPDATE_MODE;

    typedef union _PROCESS_MEMORY_ALLOCATION_MODE
    {
        ULONG Flags;
        struct
        {
            ULONG TopDown : 1;
            ULONG Reserved : 31;
        };
    } PROCESS_MEMORY_ALLOCATION_MODE, * PPROCESS_MEMORY_ALLOCATION_MODE;

    typedef struct _PROCESS_HANDLE_INFORMATION
    {
        ULONG HandleCount;
        ULONG HandleCountHighWatermark;
    } PROCESS_HANDLE_INFORMATION, * PPROCESS_HANDLE_INFORMATION;

    typedef struct _PROCESS_CYCLE_TIME_INFORMATION
    {
        ULONGLONG AccumulatedCycles;
        ULONGLONG CurrentCycleCount;
    } PROCESS_CYCLE_TIME_INFORMATION, * PPROCESS_CYCLE_TIME_INFORMATION;

    typedef struct _PROCESS_WINDOW_INFORMATION
    {
        ULONG WindowFlags;
        USHORT WindowTitleLength;
        _Field_size_bytes_(WindowTitleLength) WCHAR WindowTitle[1];
    } PROCESS_WINDOW_INFORMATION, * PPROCESS_WINDOW_INFORMATION;

    typedef struct _PROCESS_HANDLE_TABLE_ENTRY_INFO
    {
        HANDLE HandleValue;
        ULONG_PTR HandleCount;
        ULONG_PTR PointerCount;
        ULONG GrantedAccess;
        ULONG ObjectTypeIndex;
        ULONG HandleAttributes;
        ULONG Reserved;
    } PROCESS_HANDLE_TABLE_ENTRY_INFO, * PPROCESS_HANDLE_TABLE_ENTRY_INFO;

    typedef struct _PROCESS_HANDLE_SNAPSHOT_INFORMATION
    {
        ULONG_PTR NumberOfHandles;
        ULONG_PTR Reserved;
        _Field_size_(NumberOfHandles) PROCESS_HANDLE_TABLE_ENTRY_INFO Handles[1];
    } PROCESS_HANDLE_SNAPSHOT_INFORMATION, * PPROCESS_HANDLE_SNAPSHOT_INFORMATION;

#if (PHNT_MODE != PHNT_MODE_KERNEL)

#if !defined(NTDDI_WIN10_FE) || (NTDDI_VERSION < NTDDI_WIN10_FE)
    typedef struct _PROCESS_MITIGATION_REDIRECTION_TRUST_POLICY
    {
        union {
            ULONG Flags;
            struct {
                ULONG EnforceRedirectionTrust : 1;
                ULONG AuditRedirectionTrust : 1;
                ULONG ReservedFlags : 30;
            };
        };
    } PROCESS_MITIGATION_REDIRECTION_TRUST_POLICY, * PPROCESS_MITIGATION_REDIRECTION_TRUST_POLICY;
#endif

#if !defined(NTDDI_WIN10_NI) || (NTDDI_VERSION < NTDDI_WIN10_NI)
#define ProcessUserPointerAuthPolicy 17
#define ProcessSEHOPPolicy 18

    typedef struct _PROCESS_MITIGATION_USER_POINTER_AUTH_POLICY {
        union {
            ULONG Flags;
            struct {
                ULONG EnablePointerAuthUserIp : 1;
                ULONG ReservedFlags : 31;
            };
        };
    } PROCESS_MITIGATION_USER_POINTER_AUTH_POLICY, * PPROCESS_MITIGATION_USER_POINTER_AUTH_POLICY;

    typedef struct _PROCESS_MITIGATION_SEHOP_POLICY {
        union {
            ULONG Flags;
            struct {
                ULONG EnableSehop : 1;
                ULONG ReservedFlags : 31;
            };
        };
    } PROCESS_MITIGATION_SEHOP_POLICY, * PPROCESS_MITIGATION_SEHOP_POLICY;
#endif

    typedef struct _PROCESS_MITIGATION_POLICY_INFORMATION
    {
        PROCESS_MITIGATION_POLICY Policy;
        union
        {
            PROCESS_MITIGATION_ASLR_POLICY ASLRPolicy;
            PROCESS_MITIGATION_STRICT_HANDLE_CHECK_POLICY StrictHandleCheckPolicy;
            PROCESS_MITIGATION_SYSTEM_CALL_DISABLE_POLICY SystemCallDisablePolicy;
            PROCESS_MITIGATION_EXTENSION_POINT_DISABLE_POLICY ExtensionPointDisablePolicy;
            PROCESS_MITIGATION_DYNAMIC_CODE_POLICY DynamicCodePolicy;
            PROCESS_MITIGATION_CONTROL_FLOW_GUARD_POLICY ControlFlowGuardPolicy;
            PROCESS_MITIGATION_BINARY_SIGNATURE_POLICY SignaturePolicy;
            PROCESS_MITIGATION_FONT_DISABLE_POLICY FontDisablePolicy;
            PROCESS_MITIGATION_IMAGE_LOAD_POLICY ImageLoadPolicy;
            PROCESS_MITIGATION_SYSTEM_CALL_FILTER_POLICY SystemCallFilterPolicy;
            PROCESS_MITIGATION_PAYLOAD_RESTRICTION_POLICY PayloadRestrictionPolicy;
            PROCESS_MITIGATION_CHILD_PROCESS_POLICY ChildProcessPolicy;
            PROCESS_MITIGATION_SIDE_CHANNEL_ISOLATION_POLICY SideChannelIsolationPolicy;
            PROCESS_MITIGATION_USER_SHADOW_STACK_POLICY UserShadowStackPolicy;
            PROCESS_MITIGATION_REDIRECTION_TRUST_POLICY RedirectionTrustPolicy;
            PROCESS_MITIGATION_USER_POINTER_AUTH_POLICY UserPointerAuthPolicy;
            PROCESS_MITIGATION_SEHOP_POLICY SEHOPPolicy;
        };
    } PROCESS_MITIGATION_POLICY_INFORMATION, * PPROCESS_MITIGATION_POLICY_INFORMATION;

    typedef struct _PROCESS_KEEPALIVE_COUNT_INFORMATION
    {
        ULONG WakeCount;
        ULONG NoWakeCount;
    } PROCESS_KEEPALIVE_COUNT_INFORMATION, * PPROCESS_KEEPALIVE_COUNT_INFORMATION;

    typedef struct _PROCESS_REVOKE_FILE_HANDLES_INFORMATION
    {
        UNICODE_STRING TargetDevicePath;
    } PROCESS_REVOKE_FILE_HANDLES_INFORMATION, * PPROCESS_REVOKE_FILE_HANDLES_INFORMATION;

    // begin_private

    typedef enum _PROCESS_WORKING_SET_OPERATION
    {
        ProcessWorkingSetSwap,
        ProcessWorkingSetEmpty,
        ProcessWorkingSetOperationMax
    } PROCESS_WORKING_SET_OPERATION;

    typedef struct _PROCESS_WORKING_SET_CONTROL
    {
        ULONG Version;
        PROCESS_WORKING_SET_OPERATION Operation;
        ULONG Flags;
    } PROCESS_WORKING_SET_CONTROL, * PPROCESS_WORKING_SET_CONTROL;

    typedef enum _PS_PROTECTED_TYPE
    {
        PsProtectedTypeNone,
        PsProtectedTypeProtectedLight,
        PsProtectedTypeProtected,
        PsProtectedTypeMax
    } PS_PROTECTED_TYPE;

    typedef enum _PS_PROTECTED_SIGNER
    {
        PsProtectedSignerNone,
        PsProtectedSignerAuthenticode,
        PsProtectedSignerCodeGen,
        PsProtectedSignerAntimalware,
        PsProtectedSignerLsa,
        PsProtectedSignerWindows,
        PsProtectedSignerWinTcb,
        PsProtectedSignerWinSystem,
        PsProtectedSignerApp,
        PsProtectedSignerMax
    } PS_PROTECTED_SIGNER;

#define PS_PROTECTED_SIGNER_MASK 0xFF
#define PS_PROTECTED_AUDIT_MASK 0x08
#define PS_PROTECTED_TYPE_MASK 0x07

    // vProtectionLevel.Level = PsProtectedValue(PsProtectedSignerCodeGen, FALSE, PsProtectedTypeProtectedLight)
#define PsProtectedValue(aSigner, aAudit, aType) ( \
    ((aSigner & PS_PROTECTED_SIGNER_MASK) << 4) | \
    ((aAudit & PS_PROTECTED_AUDIT_MASK) << 3) | \
    (aType & PS_PROTECTED_TYPE_MASK)\
    )

// InitializePsProtection(&vProtectionLevel, PsProtectedSignerCodeGen, FALSE, PsProtectedTypeProtectedLight)
#define InitializePsProtection(aProtectionLevelPtr, aSigner, aAudit, aType) { \
    (aProtectionLevelPtr)->Signer = aSigner; \
    (aProtectionLevelPtr)->Audit = aAudit; \
    (aProtectionLevelPtr)->Type = aType; \
    }

    typedef struct _PS_PROTECTION
    {
        union
        {
            UCHAR Level;
            struct
            {
                UCHAR Type : 3;
                UCHAR Audit : 1;
                UCHAR Signer : 4;
            };
        };
    } PS_PROTECTION, * PPS_PROTECTION;

    typedef struct _PROCESS_FAULT_INFORMATION
    {
        ULONG FaultFlags;
        ULONG AdditionalInfo;
    } PROCESS_FAULT_INFORMATION, * PPROCESS_FAULT_INFORMATION;

    typedef struct _PROCESS_TELEMETRY_ID_INFORMATION
    {
        ULONG HeaderSize;
        ULONG ProcessId;
        ULONGLONG ProcessStartKey;
        ULONGLONG CreateTime;
        ULONGLONG CreateInterruptTime;
        ULONGLONG CreateUnbiasedInterruptTime;
        ULONGLONG ProcessSequenceNumber;
        ULONGLONG SessionCreateTime;
        ULONG SessionId;
        ULONG BootId;
        ULONG ImageChecksum;
        ULONG ImageTimeDateStamp;
        ULONG UserSidOffset;
        ULONG ImagePathOffset;
        ULONG PackageNameOffset;
        ULONG RelativeAppNameOffset;
        ULONG CommandLineOffset;
    } PROCESS_TELEMETRY_ID_INFORMATION, * PPROCESS_TELEMETRY_ID_INFORMATION;

    typedef struct _PROCESS_COMMIT_RELEASE_INFORMATION
    {
        ULONG Version;
        struct
        {
            ULONG Eligible : 1;
            ULONG ReleaseRepurposedMemResetCommit : 1;
            ULONG ForceReleaseMemResetCommit : 1;
            ULONG Spare : 29;
        };
        SIZE_T CommitDebt;
        SIZE_T CommittedMemResetSize;
        SIZE_T RepurposedMemResetSize;
    } PROCESS_COMMIT_RELEASE_INFORMATION, * PPROCESS_COMMIT_RELEASE_INFORMATION;

    typedef struct _PROCESS_JOB_MEMORY_INFO
    {
        ULONGLONG SharedCommitUsage;
        ULONGLONG PrivateCommitUsage;
        ULONGLONG PeakPrivateCommitUsage;
        ULONGLONG PrivateCommitLimit;
        ULONGLONG TotalCommitLimit;
    } PROCESS_JOB_MEMORY_INFO, * PPROCESS_JOB_MEMORY_INFO;

    typedef struct _PROCESS_CHILD_PROCESS_INFORMATION
    {
        BOOLEAN ProhibitChildProcesses;
        BOOLEAN AlwaysAllowSecureChildProcess; // REDSTONE3
        BOOLEAN AuditProhibitChildProcesses;
    } PROCESS_CHILD_PROCESS_INFORMATION, * PPROCESS_CHILD_PROCESS_INFORMATION;

#define POWER_THROTTLING_PROCESS_CURRENT_VERSION 1
#define POWER_THROTTLING_PROCESS_EXECUTION_SPEED 0x1
#define POWER_THROTTLING_PROCESS_DELAYTIMERS 0x2
#define POWER_THROTTLING_PROCESS_IGNORE_TIMER_RESOLUTION 0x4 // since WIN11
#define POWER_THROTTLING_PROCESS_VALID_FLAGS ((POWER_THROTTLING_PROCESS_EXECUTION_SPEED | POWER_THROTTLING_PROCESS_DELAYTIMERS | POWER_THROTTLING_PROCESS_IGNORE_TIMER_RESOLUTION))

    typedef struct _POWER_THROTTLING_PROCESS_STATE
    {
        ULONG Version;
        ULONG ControlMask;
        ULONG StateMask;
    } POWER_THROTTLING_PROCESS_STATE, * PPOWER_THROTTLING_PROCESS_STATE;

    // rev (tyranid)
#define WIN32K_SYSCALL_FILTER_STATE_ENABLE 0x1
#define WIN32K_SYSCALL_FILTER_STATE_AUDIT 0x2

    typedef struct _WIN32K_SYSCALL_FILTER
    {
        ULONG FilterState;
        ULONG FilterSet;
    } WIN32K_SYSCALL_FILTER, * PWIN32K_SYSCALL_FILTER;

    typedef struct _JOBOBJECT_WAKE_FILTER* PJOBOBJECT_WAKE_FILTER; // from ntpsapi.h

    typedef struct _PROCESS_WAKE_INFORMATION
    {
        ULONGLONG NotificationChannel;
        ULONG WakeCounters[7];
        PJOBOBJECT_WAKE_FILTER WakeFilter;
    } PROCESS_WAKE_INFORMATION, * PPROCESS_WAKE_INFORMATION;

    typedef struct _PROCESS_ENERGY_TRACKING_STATE
    {
        ULONG StateUpdateMask;
        ULONG StateDesiredValue;
        ULONG StateSequence;
        ULONG UpdateTag : 1;
        WCHAR Tag[64];
    } PROCESS_ENERGY_TRACKING_STATE, * PPROCESS_ENERGY_TRACKING_STATE;

    typedef struct _MANAGE_WRITES_TO_EXECUTABLE_MEMORY
    {
        ULONG Version : 8;
        ULONG ProcessEnableWriteExceptions : 1;
        ULONG ThreadAllowWrites : 1;
        ULONG Spare : 22;
        PVOID KernelWriteToExecutableSignal; // 19H1
    } MANAGE_WRITES_TO_EXECUTABLE_MEMORY, * PMANAGE_WRITES_TO_EXECUTABLE_MEMORY;

#define POWER_THROTTLING_THREAD_CURRENT_VERSION 1
#define POWER_THROTTLING_THREAD_EXECUTION_SPEED 0x1
#define POWER_THROTTLING_THREAD_VALID_FLAGS (POWER_THROTTLING_THREAD_EXECUTION_SPEED)

    typedef struct _POWER_THROTTLING_THREAD_STATE
    {
        ULONG Version;
        ULONG ControlMask;
        ULONG StateMask;
    } POWER_THROTTLING_THREAD_STATE, * PPOWER_THROTTLING_THREAD_STATE;

#define PROCESS_READWRITEVM_LOGGING_ENABLE_READVM 1
#define PROCESS_READWRITEVM_LOGGING_ENABLE_WRITEVM 2
#define PROCESS_READWRITEVM_LOGGING_ENABLE_READVM_V 1UL
#define PROCESS_READWRITEVM_LOGGING_ENABLE_WRITEVM_V 2UL

    typedef union _PROCESS_READWRITEVM_LOGGING_INFORMATION
    {
        UCHAR Flags;
        struct
        {
            UCHAR EnableReadVmLogging : 1;
            UCHAR EnableWriteVmLogging : 1;
            UCHAR Unused : 6;
        };
    } PROCESS_READWRITEVM_LOGGING_INFORMATION, * PPROCESS_READWRITEVM_LOGGING_INFORMATION;

    typedef struct _PROCESS_UPTIME_INFORMATION
    {
        ULONGLONG QueryInterruptTime;
        ULONGLONG QueryUnbiasedTime;
        ULONGLONG EndInterruptTime;
        ULONGLONG TimeSinceCreation;
        ULONGLONG Uptime;
        ULONGLONG SuspendedTime;
        union
        {
            ULONG HangCount : 4;
            ULONG GhostCount : 4;
            ULONG Crashed : 1;
            ULONG Terminated : 1;
        };
    } PROCESS_UPTIME_INFORMATION, * PPROCESS_UPTIME_INFORMATION;

    typedef union _PROCESS_SYSTEM_RESOURCE_MANAGEMENT
    {
        ULONG Flags;
        struct
        {
            ULONG Foreground : 1;
            ULONG Reserved : 31;
        };
    } PROCESS_SYSTEM_RESOURCE_MANAGEMENT, * PPROCESS_SYSTEM_RESOURCE_MANAGEMENT;

    typedef struct _PROCESS_SECURITY_DOMAIN_INFORMATION
    {
        ULONGLONG SecurityDomain;
    } PROCESS_SECURITY_DOMAIN_INFORMATION, * PPROCESS_SECURITY_DOMAIN_INFORMATION;

    typedef struct _PROCESS_COMBINE_SECURITY_DOMAINS_INFORMATION
    {
        HANDLE ProcessHandle;
    } PROCESS_COMBINE_SECURITY_DOMAINS_INFORMATION, * PPROCESS_COMBINE_SECURITY_DOMAINS_INFORMATION;

    typedef union _PROCESS_LOGGING_INFORMATION
    {
        ULONG Flags;
        struct
        {
            ULONG EnableReadVmLogging : 1;
            ULONG EnableWriteVmLogging : 1;
            ULONG EnableProcessSuspendResumeLogging : 1;
            ULONG EnableThreadSuspendResumeLogging : 1;
            ULONG EnableLocalExecProtectVmLogging : 1;
            ULONG EnableRemoteExecProtectVmLogging : 1;
            ULONG Reserved : 26;
        };
    } PROCESS_LOGGING_INFORMATION, * PPROCESS_LOGGING_INFORMATION;

    typedef struct _PROCESS_LEAP_SECOND_INFORMATION
    {
        ULONG Flags;
        ULONG Reserved;
    } PROCESS_LEAP_SECOND_INFORMATION, * PPROCESS_LEAP_SECOND_INFORMATION;

    typedef struct _PROCESS_FIBER_SHADOW_STACK_ALLOCATION_INFORMATION
    {
        ULONGLONG ReserveSize;
        ULONGLONG CommitSize;
        ULONG PreferredNode;
        ULONG Reserved;
        PVOID Ssp;
    } PROCESS_FIBER_SHADOW_STACK_ALLOCATION_INFORMATION, * PPROCESS_FIBER_SHADOW_STACK_ALLOCATION_INFORMATION;

    typedef struct _PROCESS_FREE_FIBER_SHADOW_STACK_ALLOCATION_INFORMATION
    {
        PVOID Ssp;
    } PROCESS_FREE_FIBER_SHADOW_STACK_ALLOCATION_INFORMATION, * PPROCESS_FREE_FIBER_SHADOW_STACK_ALLOCATION_INFORMATION;

    //typedef struct _PROCESS_DYNAMIC_ENFORCED_ADDRESS_RANGE
    //{
    //    ULONG_PTR BaseAddress;
    //    SIZE_T Size;
    //    ULONG Flags;
    //} PROCESS_DYNAMIC_ENFORCED_ADDRESS_RANGE, *PPROCESS_DYNAMIC_ENFORCED_ADDRESS_RANGE;
    //
    //typedef struct _PROCESS_DYNAMIC_ENFORCED_ADDRESS_RANGES_INFORMATION
    //{
    //    USHORT NumberOfRanges;
    //    USHORT Reserved;
    //    ULONG Reserved2;
    //    PPROCESS_DYNAMIC_ENFORCED_ADDRESS_RANGE Ranges;
    //} PROCESS_DYNAMIC_ENFORCED_ADDRESS_RANGES_INFORMATION, *PPROCESS_DYNAMIC_ENFORCED_ADDRESS_RANGES_INFORMATION;

    typedef struct _PROCESS_MEMBERSHIP_INFORMATION
    {
        ULONG ServerSiloId;
    } PROCESS_MEMBERSHIP_INFORMATION, * PPROCESS_MEMBERSHIP_INFORMATION;

    // end_private

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtQueryPortInformationProcess(
            VOID
        );

#endif

    // Thread information structures

    typedef struct _THREAD_BASIC_INFORMATION
    {
        NTSTATUS ExitStatus;
        PTEB TebBaseAddress;
        CLIENT_ID ClientId;
        KAFFINITY AffinityMask;
        KPRIORITY Priority;
        KPRIORITY BasePriority;
    } THREAD_BASIC_INFORMATION, * PTHREAD_BASIC_INFORMATION;

    typedef struct _THREAD_LAST_SYSCALL_INFORMATION
    {
        PVOID FirstArgument;
        USHORT SystemCallNumber;
#ifdef WIN64
        USHORT Pad[0x3]; // since REDSTONE2
#else
        USHORT Pad[0x1]; // since REDSTONE2
#endif
        ULONG64 WaitTime;
    } THREAD_LAST_SYSCALL_INFORMATION, * PTHREAD_LAST_SYSCALL_INFORMATION;

    typedef struct _THREAD_CYCLE_TIME_INFORMATION
    {
        ULONGLONG AccumulatedCycles;
        ULONGLONG CurrentCycleCount;
    } THREAD_CYCLE_TIME_INFORMATION, * PTHREAD_CYCLE_TIME_INFORMATION;

    typedef struct _THREAD_TEB_INFORMATION
    {
        PVOID TebInformation; // buffer to place data in
        ULONG TebOffset; // offset in TEB to begin reading from
        ULONG BytesToRead; // number of bytes to read
    } THREAD_TEB_INFORMATION, * PTHREAD_TEB_INFORMATION;

    // symbols
    typedef struct _COUNTER_READING
    {
        HARDWARE_COUNTER_TYPE Type;
        ULONG Index;
        ULONG64 Start;
        ULONG64 Total;
    } COUNTER_READING, * PCOUNTER_READING;

    // symbols
    typedef struct _THREAD_PERFORMANCE_DATA
    {
        USHORT Size;
        USHORT Version;
        PROCESSOR_NUMBER ProcessorNumber;
        ULONG ContextSwitches;
        ULONG HwCountersCount;
        ULONG64 UpdateCount;
        ULONG64 WaitReasonBitMap;
        ULONG64 HardwareCounters;
        COUNTER_READING CycleTime;
        COUNTER_READING HwCounters[MAX_HW_COUNTERS];
    } THREAD_PERFORMANCE_DATA, * PTHREAD_PERFORMANCE_DATA;

    typedef struct _THREAD_PROFILING_INFORMATION
    {
        ULONG64 HardwareCounters;
        ULONG Flags;
        ULONG Enable;
        PTHREAD_PERFORMANCE_DATA PerformanceData;
    } THREAD_PROFILING_INFORMATION, * PTHREAD_PROFILING_INFORMATION;

    typedef struct _RTL_UMS_CONTEXT
    {
        SINGLE_LIST_ENTRY Link;
        CONTEXT Context;
        PVOID Teb;
        PVOID UserContext;
        volatile ULONG ScheduledThread : 1;
        volatile ULONG Suspended : 1;
        volatile ULONG VolatileContext : 1;
        volatile ULONG Terminated : 1;
        volatile ULONG DebugActive : 1;
        volatile ULONG RunningOnSelfThread : 1;
        volatile ULONG DenyRunningOnSelfThread : 1;
        volatile LONG Flags;
        volatile ULONG64 KernelUpdateLock : 2;
        volatile ULONG64 PrimaryClientID : 62;
        volatile ULONG64 ContextLock;
        struct _RTL_UMS_CONTEXT* PrimaryUmsContext;
        ULONG SwitchCount;
        ULONG KernelYieldCount;
        ULONG MixedYieldCount;
        ULONG YieldCount;
    } RTL_UMS_CONTEXT, * PRTL_UMS_CONTEXT;

    typedef enum _THREAD_UMS_INFORMATION_COMMAND
    {
        UmsInformationCommandInvalid,
        UmsInformationCommandAttach,
        UmsInformationCommandDetach,
        UmsInformationCommandQuery
    } THREAD_UMS_INFORMATION_COMMAND;

    typedef struct _RTL_UMS_COMPLETION_LIST
    {
        PSINGLE_LIST_ENTRY ThreadListHead;
        PVOID CompletionEvent;
        ULONG CompletionFlags;
        SINGLE_LIST_ENTRY InternalListHead;
    } RTL_UMS_COMPLETION_LIST, * PRTL_UMS_COMPLETION_LIST;

    typedef struct _THREAD_UMS_INFORMATION
    {
        THREAD_UMS_INFORMATION_COMMAND Command;
        PRTL_UMS_COMPLETION_LIST CompletionList;
        PRTL_UMS_CONTEXT UmsContext;
        union
        {
            ULONG Flags;
            struct
            {
                ULONG IsUmsSchedulerThread : 1;
                ULONG IsUmsWorkerThread : 1;
                ULONG SpareBits : 30;
            };
        };
    } THREAD_UMS_INFORMATION, * PTHREAD_UMS_INFORMATION;

    typedef struct _THREAD_NAME_INFORMATION
    {
        UNICODE_STRING ThreadName;
    } THREAD_NAME_INFORMATION, * PTHREAD_NAME_INFORMATION;

    typedef struct _ALPC_WORK_ON_BEHALF_TICKET
    {
        ULONG ThreadId;
        ULONG ThreadCreationTimeLow;
    } ALPC_WORK_ON_BEHALF_TICKET, * PALPC_WORK_ON_BEHALF_TICKET;

    typedef struct _RTL_WORK_ON_BEHALF_TICKET_EX
    {
        ALPC_WORK_ON_BEHALF_TICKET Ticket;
        union
        {
            ULONG Flags;
            struct
            {
                ULONG CurrentThread : 1;
                ULONG Reserved1 : 31;
            };
        };
        ULONG Reserved2;
    } RTL_WORK_ON_BEHALF_TICKET_EX, * PRTL_WORK_ON_BEHALF_TICKET_EX;

#if (PHNT_MODE != PHNT_MODE_KERNEL)

    typedef enum _SUBSYSTEM_INFORMATION_TYPE
    {
        SubsystemInformationTypeWin32,
        SubsystemInformationTypeWSL,
        MaxSubsystemInformationType
    } SUBSYSTEM_INFORMATION_TYPE;
#endif

    typedef enum _THREAD_WORKLOAD_CLASS
    {
        ThreadWorkloadClassDefault,
        ThreadWorkloadClassGraphics,
        MaxThreadWorkloadClass
    } THREAD_WORKLOAD_CLASS;

#if defined(_ARM64_)

#define CONTEXT_ARM   0x00200000L

#define CONTEXT_ARM_CONTROL (CONTEXT_ARM | 0x1L)
#define CONTEXT_ARM_INTEGER (CONTEXT_ARM | 0x2L)
#define CONTEXT_ARM_FLOATING_POINT  (CONTEXT_ARM | 0x4L)
#define CONTEXT_ARM_DEBUG_REGISTERS (CONTEXT_ARM | 0x8L)

#define CONTEXT_ARM_FULL (CONTEXT_ARM_CONTROL | CONTEXT_ARM_INTEGER | CONTEXT_ARM_FLOATING_POINT)

#define CONTEXT_ARM_ALL (CONTEXT_ARM_CONTROL | CONTEXT_ARM_INTEGER | CONTEXT_ARM_FLOATING_POINT | CONTEXT_ARM_DEBUG_REGISTERS)

#define ARM_MAX_BREAKPOINTS     8
#define ARM_MAX_WATCHPOINTS     1

    typedef struct _ARM_NT_NEON128 {
        ULONGLONG Low;
        LONGLONG High;
    } ARM_NT_NEON128, * PARM_NT_NEON128;

    typedef struct DECLSPEC_ALIGN(8) DECLSPEC_NOINITALL _ARM_NT_CONTEXT {

        //
        // Control flags.
        //

        DWORD ContextFlags;

        //
        // Integer registers
        //

        DWORD R0;
        DWORD R1;
        DWORD R2;
        DWORD R3;
        DWORD R4;
        DWORD R5;
        DWORD R6;
        DWORD R7;
        DWORD R8;
        DWORD R9;
        DWORD R10;
        DWORD R11;
        DWORD R12;

        //
        // Control Registers
        //

        DWORD Sp;
        DWORD Lr;
        DWORD Pc;
        DWORD Cpsr;

        //
        // Floating Point/NEON Registers
        //

        DWORD Fpscr;
        DWORD Padding;
        union {
            ARM_NT_NEON128 Q[16];
            ULONGLONG D[32];
            DWORD S[32];
        } DUMMYUNIONNAME;

        //
        // Debug registers
        //

        DWORD Bvr[ARM_MAX_BREAKPOINTS];
        DWORD Bcr[ARM_MAX_BREAKPOINTS];
        DWORD Wvr[ARM_MAX_WATCHPOINTS];
        DWORD Wcr[ARM_MAX_WATCHPOINTS];

        DWORD Padding2[2];

    } ARM_NT_CONTEXT, * PARM_NT_CONTEXT;

#endif

    // Processes

#if (PHNT_MODE != PHNT_MODE_KERNEL)

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtCreateProcess(
            _Out_ PHANDLE ProcessHandle,
            _In_ ACCESS_MASK DesiredAccess,
            _In_opt_ POBJECT_ATTRIBUTES ObjectAttributes,
            _In_ HANDLE ParentProcess,
            _In_ BOOLEAN InheritObjectTable,
            _In_opt_ HANDLE SectionHandle,
            _In_opt_ HANDLE DebugPort,
            _In_opt_ HANDLE TokenHandle
        );

    // begin_rev
#define PROCESS_CREATE_FLAGS_BREAKAWAY 0x00000001 // NtCreateProcessEx & NtCreateUserProcess
#define PROCESS_CREATE_FLAGS_NO_DEBUG_INHERIT 0x00000002 // NtCreateProcessEx & NtCreateUserProcess
#define PROCESS_CREATE_FLAGS_INHERIT_HANDLES 0x00000004 // NtCreateProcessEx & NtCreateUserProcess
#define PROCESS_CREATE_FLAGS_OVERRIDE_ADDRESS_SPACE 0x00000008 // NtCreateProcessEx only
#define PROCESS_CREATE_FLAGS_LARGE_PAGES 0x00000010 // NtCreateProcessEx only, requires SeLockMemory
#define PROCESS_CREATE_FLAGS_LARGE_PAGE_SYSTEM_DLL 0x00000020 // NtCreateProcessEx only, requires SeLockMemory
#define PROCESS_CREATE_FLAGS_PROTECTED_PROCESS 0x00000040 // NtCreateUserProcess only
#define PROCESS_CREATE_FLAGS_CREATE_SESSION 0x00000080 // NtCreateProcessEx & NtCreateUserProcess, requires SeLoadDriver
#define PROCESS_CREATE_FLAGS_INHERIT_FROM_PARENT 0x00000100 // NtCreateProcessEx & NtCreateUserProcess
#define PROCESS_CREATE_FLAGS_SUSPENDED 0x00000200 // NtCreateProcessEx & NtCreateUserProcess
#define PROCESS_CREATE_FLAGS_FORCE_BREAKAWAY 0x00000400 // NtCreateProcessEx & NtCreateUserProcess, requires SeTcb
#define PROCESS_CREATE_FLAGS_MINIMAL_PROCESS 0x00000800 // NtCreateProcessEx only
#define PROCESS_CREATE_FLAGS_RELEASE_SECTION 0x00001000 // NtCreateProcessEx & NtCreateUserProcess
#define PROCESS_CREATE_FLAGS_CLONE_MINIMAL 0x00002000 // NtCreateProcessEx only
#define PROCESS_CREATE_FLAGS_CLONE_MINIMAL_REDUCED_COMMIT 0x00004000 //
#define PROCESS_CREATE_FLAGS_AUXILIARY_PROCESS 0x00008000 // NtCreateProcessEx & NtCreateUserProcess, requires SeTcb
#define PROCESS_CREATE_FLAGS_CREATE_STORE 0x00020000 // NtCreateProcessEx & NtCreateUserProcess
#define PROCESS_CREATE_FLAGS_USE_PROTECTED_ENVIRONMENT 0x00040000 // NtCreateProcessEx & NtCreateUserProcess
// end_rev

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtCreateProcessEx(
            _Out_ PHANDLE ProcessHandle,
            _In_ ACCESS_MASK DesiredAccess,
            _In_opt_ POBJECT_ATTRIBUTES ObjectAttributes,
            _In_ HANDLE ParentProcess,
            _In_ ULONG Flags, // PROCESS_CREATE_FLAGS_*
            _In_opt_ HANDLE SectionHandle,
            _In_opt_ HANDLE DebugPort,
            _In_opt_ HANDLE TokenHandle,
            _Reserved_ ULONG Reserved // JobMemberLevel
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtOpenProcess(
            _Out_ PHANDLE ProcessHandle,
            _In_ ACCESS_MASK DesiredAccess,
            _In_ POBJECT_ATTRIBUTES ObjectAttributes,
            _In_opt_ PCLIENT_ID ClientId
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtTerminateProcess(
            _In_opt_ HANDLE ProcessHandle,
            _In_ NTSTATUS ExitStatus
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtSuspendProcess(
            _In_ HANDLE ProcessHandle
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtResumeProcess(
            _In_ HANDLE ProcessHandle
        );

#define NtCurrentProcess() ((HANDLE)(LONG_PTR)-1)
#define ZwCurrentProcess() NtCurrentProcess()
#define NtCurrentThread() ((HANDLE)(LONG_PTR)-2)
#define ZwCurrentThread() NtCurrentThread()
#define NtCurrentSession() ((HANDLE)(LONG_PTR)-3)
#define ZwCurrentSession() NtCurrentSession()
#define NtCurrentPeb() (NtCurrentTeb()->ProcessEnvironmentBlock)

    // Windows 8 and above
#define NtCurrentProcessToken() ((HANDLE)(LONG_PTR)-4) // NtOpenProcessToken(NtCurrentProcess())
#define NtCurrentThreadToken() ((HANDLE)(LONG_PTR)-5) // NtOpenThreadToken(NtCurrentThread())
#define NtCurrentThreadEffectiveToken() ((HANDLE)(LONG_PTR)-6) // NtOpenThreadToken(NtCurrentThread()) + NtOpenProcessToken(NtCurrentProcess())

#define NtCurrentSilo() ((HANDLE)(LONG_PTR)-1)

// Not NT, but useful.
    EXTERN_C IMAGE_DOS_HEADER __ImageBase;
#define NtCurrentImageBase() ((PVOID)&__ImageBase)

    // Not NT, but useful.
#define NtCurrentProcessId() (NtCurrentTeb()->ClientId.UniqueProcess)
#define NtCurrentThreadId() (NtCurrentTeb()->ClientId.UniqueThread)

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtQueryInformationProcess(
            _In_ HANDLE ProcessHandle,
            _In_ PROCESSINFOCLASS ProcessInformationClass,
            _Out_writes_bytes_(ProcessInformationLength) PVOID ProcessInformation,
            _In_ ULONG ProcessInformationLength,
            _Out_opt_ PULONG ReturnLength
        );

#if (PHNT_VERSION >= PHNT_WS03)

#define PROCESS_GET_NEXT_FLAGS_PREVIOUS_PROCESS 0x00000001

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtGetNextProcess(
            _In_opt_ HANDLE ProcessHandle,
            _In_ ACCESS_MASK DesiredAccess,
            _In_ ULONG HandleAttributes,
            _In_ ULONG Flags,
            _Out_ PHANDLE NewProcessHandle
        );
#endif

#if (PHNT_VERSION >= PHNT_WS03)
    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtGetNextThread(
            _In_ HANDLE ProcessHandle,
            _In_opt_ HANDLE ThreadHandle,
            _In_ ACCESS_MASK DesiredAccess,
            _In_ ULONG HandleAttributes,
            _In_ ULONG Flags,
            _Out_ PHANDLE NewThreadHandle
        );
#endif

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtSetInformationProcess(
            _In_ HANDLE ProcessHandle,
            _In_ PROCESSINFOCLASS ProcessInformationClass,
            _In_reads_bytes_(ProcessInformationLength) PVOID ProcessInformation,
            _In_ ULONG ProcessInformationLength
        );

#endif

#define STATECHANGE_SET_ATTRIBUTES 0x0001

    typedef enum _PROCESS_STATE_CHANGE_TYPE
    {
        ProcessStateChangeSuspend,
        ProcessStateChangeResume,
        ProcessStateChangeMax,
    } PROCESS_STATE_CHANGE_TYPE, * PPROCESS_STATE_CHANGE_TYPE;

#if (PHNT_VERSION >= PHNT_WIN11)

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtCreateProcessStateChange(
            _Out_ PHANDLE ProcessStateChangeHandle,
            _In_ ACCESS_MASK DesiredAccess,
            _In_opt_ POBJECT_ATTRIBUTES ObjectAttributes,
            _In_ HANDLE ProcessHandle,
            _In_opt_ ULONG64 Reserved
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtChangeProcessState(
            _In_ HANDLE ProcessStateChangeHandle,
            _In_ HANDLE ProcessHandle,
            _In_ PROCESS_STATE_CHANGE_TYPE StateChangeType,
            _In_opt_ PVOID ExtendedInformation,
            _In_opt_ SIZE_T ExtendedInformationLength,
            _In_opt_ ULONG64 Reserved
        );

#endif

    typedef enum _THREAD_STATE_CHANGE_TYPE
    {
        ThreadStateChangeSuspend,
        ThreadStateChangeResume,
        ThreadStateChangeMax,
    } THREAD_STATE_CHANGE_TYPE, * PTHREAD_STATE_CHANGE_TYPE;

#if (PHNT_VERSION >= PHNT_WIN11)

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtCreateThreadStateChange(
            _Out_ PHANDLE ThreadStateChangeHandle,
            _In_ ACCESS_MASK DesiredAccess,
            _In_opt_ POBJECT_ATTRIBUTES ObjectAttributes,
            _In_ HANDLE ThreadHandle,
            _In_opt_ ULONG64 Reserved
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtChangeThreadState(
            _In_ HANDLE ThreadStateChangeHandle,
            _In_ HANDLE ThreadHandle,
            _In_ THREAD_STATE_CHANGE_TYPE StateChangeType,
            _In_opt_ PVOID ExtendedInformation,
            _In_opt_ SIZE_T ExtendedInformationLength,
            _In_opt_ ULONG64 Reserved
        );

#endif

    // Threads

#if (PHNT_MODE != PHNT_MODE_KERNEL)

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtCreateThread(
            _Out_ PHANDLE ThreadHandle,
            _In_ ACCESS_MASK DesiredAccess,
            _In_opt_ POBJECT_ATTRIBUTES ObjectAttributes,
            _In_ HANDLE ProcessHandle,
            _Out_ PCLIENT_ID ClientId,
            _In_ PCONTEXT ThreadContext,
            _In_ PINITIAL_TEB InitialTeb,
            _In_ BOOLEAN CreateSuspended
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtOpenThread(
            _Out_ PHANDLE ThreadHandle,
            _In_ ACCESS_MASK DesiredAccess,
            _In_ POBJECT_ATTRIBUTES ObjectAttributes,
            _In_opt_ PCLIENT_ID ClientId
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtTerminateThread(
            _In_opt_ HANDLE ThreadHandle,
            _In_ NTSTATUS ExitStatus
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtSuspendThread(
            _In_ HANDLE ThreadHandle,
            _Out_opt_ PULONG PreviousSuspendCount
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtResumeThread(
            _In_ HANDLE ThreadHandle,
            _Out_opt_ PULONG PreviousSuspendCount
        );

    NTSYSCALLAPI
        ULONG
        NTAPI
        NtGetCurrentProcessorNumber(
            VOID
        );

#if (PHNT_VERSION >= PHNT_WIN7)
    NTSYSCALLAPI
        ULONG
        NTAPI
        NtGetCurrentProcessorNumberEx(
            _Out_opt_ PPROCESSOR_NUMBER ProcessorNumber
        );
#endif

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtGetContextThread(
            _In_ HANDLE ThreadHandle,
            _Inout_ PCONTEXT ThreadContext
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtSetContextThread(
            _In_ HANDLE ThreadHandle,
            _In_ PCONTEXT ThreadContext
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtQueryInformationThread(
            _In_ HANDLE ThreadHandle,
            _In_ THREADINFOCLASS ThreadInformationClass,
            _Out_writes_bytes_(ThreadInformationLength) PVOID ThreadInformation,
            _In_ ULONG ThreadInformationLength,
            _Out_opt_ PULONG ReturnLength
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtSetInformationThread(
            _In_ HANDLE ThreadHandle,
            _In_ THREADINFOCLASS ThreadInformationClass,
            _In_reads_bytes_(ThreadInformationLength) PVOID ThreadInformation,
            _In_ ULONG ThreadInformationLength
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtAlertThread(
            _In_ HANDLE ThreadHandle
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtAlertResumeThread(
            _In_ HANDLE ThreadHandle,
            _Out_opt_ PULONG PreviousSuspendCount
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtTestAlert(
            VOID
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtImpersonateThread(
            _In_ HANDLE ServerThreadHandle,
            _In_ HANDLE ClientThreadHandle,
            _In_ PSECURITY_QUALITY_OF_SERVICE SecurityQos
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtRegisterThreadTerminatePort(
            _In_ HANDLE PortHandle
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtSetLdtEntries(
            _In_ ULONG Selector0,
            _In_ ULONG Entry0Low,
            _In_ ULONG Entry0Hi,
            _In_ ULONG Selector1,
            _In_ ULONG Entry1Low,
            _In_ ULONG Entry1Hi
        );

    typedef VOID(NTAPI* PPS_APC_ROUTINE)(
        _In_opt_ PVOID ApcArgument1,
        _In_opt_ PVOID ApcArgument2,
        _In_opt_ PVOID ApcArgument3
        );

#define Wow64EncodeApcRoutine(ApcRoutine) \
    ((PVOID)((0 - ((LONG_PTR)(ApcRoutine))) << 2))

#define Wow64DecodeApcRoutine(ApcRoutine) \
    ((PVOID)(0 - (((LONG_PTR)(ApcRoutine)) >> 2)))

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtQueueApcThread(
            _In_ HANDLE ThreadHandle,
            _In_ PPS_APC_ROUTINE ApcRoutine,
            _In_opt_ PVOID ApcArgument1,
            _In_opt_ PVOID ApcArgument2,
            _In_opt_ PVOID ApcArgument3
        );

#if (PHNT_VERSION >= PHNT_WIN7)

#define QUEUE_USER_APC_SPECIAL_USER_APC ((HANDLE)0x1)

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtQueueApcThreadEx(
            _In_ HANDLE ThreadHandle,
            _In_opt_ HANDLE ReserveHandle, // NtAllocateReserveObject // SPECIAL_USER_APC
            _In_ PPS_APC_ROUTINE ApcRoutine,
            _In_opt_ PVOID ApcArgument1,
            _In_opt_ PVOID ApcArgument2,
            _In_opt_ PVOID ApcArgument3
        );

#endif

#if (PHNT_VERSION >= PHNT_WIN11)

    // QUEUE_USER_APC_FLAGS enum (dmex)
#define QUEUE_USER_APC_FLAGS_NONE               0x0
#define QUEUE_USER_APC_FLAGS_SPECIAL_USER_APC   0x1
#define QUEUE_USER_APC_CALLBACK_DATA_CONTEXT    0x00010000 // APC_CALLBACK_DATA

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtQueueApcThreadEx2(
            _In_ HANDLE ThreadHandle,
            _In_opt_ HANDLE ReserveHandle, // NtAllocateReserveObject
            _In_ ULONG ApcFlags, // QUEUE_USER_APC_FLAGS
            _In_ PPS_APC_ROUTINE ApcRoutine,
            _In_opt_ PVOID ApcArgument1,
            _In_opt_ PVOID ApcArgument2,
            _In_opt_ PVOID ApcArgument3
        );

#endif

#if (PHNT_VERSION >= PHNT_WIN8)

    // rev
    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtAlertThreadByThreadId(
            _In_ HANDLE ThreadId
        );

    // rev
    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtWaitForAlertByThreadId(
            _In_ PVOID Address,
            _In_opt_ PLARGE_INTEGER Timeout
        );

#endif

#endif

    // User processes and threads

#if (PHNT_MODE != PHNT_MODE_KERNEL)

// Attributes (Win32 CreateProcess)

// PROC_THREAD_ATTRIBUTE_NUM (dmex)
#define ProcThreadAttributeParentProcess 0 // in HANDLE
#define ProcThreadAttributeExtendedFlags 1 // in ULONG (EXTENDED_PROCESS_CREATION_FLAG_*)
#define ProcThreadAttributeHandleList 2 // in HANDLE[]
#define ProcThreadAttributeGroupAffinity 3 // in GROUP_AFFINITY // since WIN7
#define ProcThreadAttributePreferredNode 4 // in USHORT
#define ProcThreadAttributeIdealProcessor 5 // in PROCESSOR_NUMBER
#define ProcThreadAttributeUmsThread 6 // in UMS_CREATE_THREAD_ATTRIBUTES
#define ProcThreadAttributeMitigationPolicy 7 // in ULONG, ULONG64, or ULONG64[2]
#define ProcThreadAttributePackageFullName 8 // in WCHAR[] // since WIN8
#define ProcThreadAttributeSecurityCapabilities 9 // in SECURITY_CAPABILITIES
#define ProcThreadAttributeConsoleReference 10 // BaseGetConsoleReference (kernelbase.dll)
#define ProcThreadAttributeProtectionLevel 11 // in ULONG (PROTECTION_LEVEL_*) // since WINBLUE
#define ProcThreadAttributeOsMaxVersionTested 12 // in MAXVERSIONTESTED_INFO // since THRESHOLD // (from exe.manifest)
#define ProcThreadAttributeJobList 13 // in HANDLE[]
#define ProcThreadAttributeChildProcessPolicy 14 // in ULONG (PROCESS_CREATION_CHILD_PROCESS_*) // since THRESHOLD2
#define ProcThreadAttributeAllApplicationPackagesPolicy 15 // in ULONG (PROCESS_CREATION_ALL_APPLICATION_PACKAGES_*) // since REDSTONE
#define ProcThreadAttributeWin32kFilter 16 // in WIN32K_SYSCALL_FILTER
#define ProcThreadAttributeSafeOpenPromptOriginClaim 17 // in SE_SAFE_OPEN_PROMPT_RESULTS
#define ProcThreadAttributeDesktopAppPolicy 18 // in ULONG (PROCESS_CREATION_DESKTOP_APP_*) // since RS2
#define ProcThreadAttributeBnoIsolation 19 // in PROC_THREAD_BNOISOLATION_ATTRIBUTE
#define ProcThreadAttributePseudoConsole 22 // in HANDLE (HPCON) // since RS5
#define ProcThreadAttributeIsolationManifest 23 // in ISOLATION_MANIFEST_PROPERTIES // rev (diversenok) // since 19H2+
#define ProcThreadAttributeMitigationAuditPolicy 24 // in ULONG, ULONG64, or ULONG64[2] // since 21H1
#define ProcThreadAttributeMachineType 25 // in USHORT // since 21H2
#define ProcThreadAttributeComponentFilter 26 // in ULONG
#define ProcThreadAttributeEnableOptionalXStateFeatures 27 // in ULONG64 // since WIN11
#define ProcThreadAttributeCreateStore 28 // ULONG // rev (diversenok)
#define ProcThreadAttributeTrustedApp 29

#ifndef PROC_THREAD_ATTRIBUTE_EXTENDED_FLAGS
#define PROC_THREAD_ATTRIBUTE_EXTENDED_FLAGS \
    ProcThreadAttributeValue(ProcThreadAttributeExtendedFlags, FALSE, TRUE, TRUE)
#endif
#ifndef PROC_THREAD_ATTRIBUTE_PACKAGE_FULL_NAME
#define PROC_THREAD_ATTRIBUTE_PACKAGE_FULL_NAME \
    ProcThreadAttributeValue(ProcThreadAttributePackageFullName, FALSE, TRUE, FALSE)
#endif
#ifndef PROC_THREAD_ATTRIBUTE_CONSOLE_REFERENCE
#define PROC_THREAD_ATTRIBUTE_CONSOLE_REFERENCE \
    ProcThreadAttributeValue(ProcThreadAttributeConsoleReference, FALSE, TRUE, FALSE)
#endif
#ifndef PROC_THREAD_ATTRIBUTE_OSMAXVERSIONTESTED
#define PROC_THREAD_ATTRIBUTE_OSMAXVERSIONTESTED \
    ProcThreadAttributeValue(ProcThreadAttributeOsMaxVersionTested, FALSE, TRUE, FALSE)
#endif
#ifndef PROC_THREAD_ATTRIBUTE_SAFE_OPEN_PROMPT_ORIGIN_CLAIM
#define PROC_THREAD_ATTRIBUTE_SAFE_OPEN_PROMPT_ORIGIN_CLAIM \
    ProcThreadAttributeValue(ProcThreadAttributeSafeOpenPromptOriginClaim, FALSE, TRUE, FALSE)
#endif
#ifndef PROC_THREAD_ATTRIBUTE_BNO_ISOLATION
#define PROC_THREAD_ATTRIBUTE_BNO_ISOLATION \
    ProcThreadAttributeValue(ProcThreadAttributeBnoIsolation, FALSE, TRUE, FALSE)
#endif
#ifndef PROC_THREAD_ATTRIBUTE_ISOLATION_MANIFEST
#define PROC_THREAD_ATTRIBUTE_ISOLATION_MANIFEST \
    ProcThreadAttributeValue(ProcThreadAttributeIsolationManifest, FALSE, TRUE, FALSE)
#endif
#ifndef PROC_THREAD_ATTRIBUTE_CREATE_STORE
#define PROC_THREAD_ATTRIBUTE_CREATE_STORE \
    ProcThreadAttributeValue(ProcThreadAttributeCreateStore, FALSE, TRUE, FALSE)
#endif

// private
    typedef struct _PROC_THREAD_ATTRIBUTE
    {
        ULONG_PTR Attribute;
        SIZE_T Size;
        ULONG_PTR Value;
    } PROC_THREAD_ATTRIBUTE, * PPROC_THREAD_ATTRIBUTE;

    // private
    typedef struct _PROC_THREAD_ATTRIBUTE_LIST
    {
        ULONG PresentFlags;
        ULONG AttributeCount;
        ULONG LastAttribute;
        ULONG SpareUlong0;
        PPROC_THREAD_ATTRIBUTE ExtendedFlagsAttribute;
        _Field_size_(AttributeCount) PROC_THREAD_ATTRIBUTE Attributes[1];
    } PROC_THREAD_ATTRIBUTE_LIST, * PPROC_THREAD_ATTRIBUTE_LIST;

    // private
#define EXTENDED_PROCESS_CREATION_FLAG_ELEVATION_HANDLED 0x00000001
#define EXTENDED_PROCESS_CREATION_FLAG_FORCELUA 0x00000002
#define EXTENDED_PROCESS_CREATION_FLAG_FORCE_BREAKAWAY 0x00000004 // requires SeTcbPrivilege // since WINBLUE

// private
#define PROTECTION_LEVEL_WINTCB_LIGHT 0x00000000
#define PROTECTION_LEVEL_WINDOWS 0x00000001
#define PROTECTION_LEVEL_WINDOWS_LIGHT 0x00000002
#define PROTECTION_LEVEL_ANTIMALWARE_LIGHT 0x00000003
#define PROTECTION_LEVEL_LSA_LIGHT 0x00000004
#define PROTECTION_LEVEL_WINTCB 0x00000005
#define PROTECTION_LEVEL_CODEGEN_LIGHT 0x00000006
#define PROTECTION_LEVEL_AUTHENTICODE 0x00000007

// private
    typedef enum _SE_SAFE_OPEN_PROMPT_EXPERIENCE_RESULTS
    {
        SeSafeOpenExperienceNone = 0x00,
        SeSafeOpenExperienceCalled = 0x01,
        SeSafeOpenExperienceAppRepCalled = 0x02,
        SeSafeOpenExperiencePromptDisplayed = 0x04,
        SeSafeOpenExperienceUAC = 0x08,
        SeSafeOpenExperienceUninstaller = 0x10,
        SeSafeOpenExperienceIgnoreUnknownOrBad = 0x20,
        SeSafeOpenExperienceDefenderTrustedInstaller = 0x40,
        SeSafeOpenExperienceMOTWPresent = 0x80,
        SeSafeOpenExperienceElevatedNoPropagation = 0x100
    } SE_SAFE_OPEN_PROMPT_EXPERIENCE_RESULTS;

    // private
    typedef struct _SE_SAFE_OPEN_PROMPT_RESULTS
    {
        SE_SAFE_OPEN_PROMPT_EXPERIENCE_RESULTS Results;
        WCHAR Path[MAX_PATH];
    } SE_SAFE_OPEN_PROMPT_RESULTS, * PSE_SAFE_OPEN_PROMPT_RESULTS;

    typedef struct _PROC_THREAD_BNOISOLATION_ATTRIBUTE
    {
        BOOL IsolationEnabled;
        WCHAR IsolationPrefix[0x88];
    } PROC_THREAD_BNOISOLATION_ATTRIBUTE, * PPROC_THREAD_BNOISOLATION_ATTRIBUTE;

    // private
    typedef struct _ISOLATION_MANIFEST_PROPERTIES
    {
        UNICODE_STRING InstancePath;
        UNICODE_STRING FriendlyName;
        UNICODE_STRING Description;
        ULONG_PTR Level;
    } ISOLATION_MANIFEST_PROPERTIES, * PISOLATION_MANIFEST_PROPERTIES;

    // Attributes (Native)

    // private
    typedef enum _PS_ATTRIBUTE_NUM
    {
        PsAttributeParentProcess, // in HANDLE
        PsAttributeDebugObject, // in HANDLE
        PsAttributeToken, // in HANDLE
        PsAttributeClientId, // out PCLIENT_ID
        PsAttributeTebAddress, // out PTEB *
        PsAttributeImageName, // in PWSTR
        PsAttributeImageInfo, // out PSECTION_IMAGE_INFORMATION
        PsAttributeMemoryReserve, // in PPS_MEMORY_RESERVE
        PsAttributePriorityClass, // in UCHAR
        PsAttributeErrorMode, // in ULONG
        PsAttributeStdHandleInfo, // 10, in PPS_STD_HANDLE_INFO
        PsAttributeHandleList, // in HANDLE[]
        PsAttributeGroupAffinity, // in PGROUP_AFFINITY
        PsAttributePreferredNode, // in PUSHORT
        PsAttributeIdealProcessor, // in PPROCESSOR_NUMBER
        PsAttributeUmsThread, // ? in PUMS_CREATE_THREAD_ATTRIBUTES
        PsAttributeMitigationOptions, // in PPS_MITIGATION_OPTIONS_MAP (PROCESS_CREATION_MITIGATION_POLICY_*) // since WIN8
        PsAttributeProtectionLevel, // in PS_PROTECTION // since WINBLUE
        PsAttributeSecureProcess, // in PPS_TRUSTLET_CREATE_ATTRIBUTES, since THRESHOLD
        PsAttributeJobList, // in HANDLE[]
        PsAttributeChildProcessPolicy, // 20, in PULONG (PROCESS_CREATION_CHILD_PROCESS_*) // since THRESHOLD2
        PsAttributeAllApplicationPackagesPolicy, // in PULONG (PROCESS_CREATION_ALL_APPLICATION_PACKAGES_*) // since REDSTONE
        PsAttributeWin32kFilter, // in PWIN32K_SYSCALL_FILTER
        PsAttributeSafeOpenPromptOriginClaim, // in SE_SAFE_OPEN_PROMPT_RESULTS
        PsAttributeBnoIsolation, // in PPS_BNO_ISOLATION_PARAMETERS // since REDSTONE2
        PsAttributeDesktopAppPolicy, // in PULONG (PROCESS_CREATION_DESKTOP_APP_*)
        PsAttributeChpe, // in BOOLEAN // since REDSTONE3
        PsAttributeMitigationAuditOptions, // in PPS_MITIGATION_AUDIT_OPTIONS_MAP (PROCESS_CREATION_MITIGATION_AUDIT_POLICY_*) // since 21H1
        PsAttributeMachineType, // in USHORT // since 21H2
        PsAttributeComponentFilter,
        PsAttributeEnableOptionalXStateFeatures, // since WIN11
        PsAttributeMax
    } PS_ATTRIBUTE_NUM;

    // private
#define PS_ATTRIBUTE_NUMBER_MASK 0x0000ffff
#define PS_ATTRIBUTE_THREAD 0x00010000 // may be used with thread creation
#define PS_ATTRIBUTE_INPUT 0x00020000 // input only
#define PS_ATTRIBUTE_ADDITIVE 0x00040000 // "accumulated" e.g. bitmasks, counters, etc.

// begin_rev

#define PsAttributeValue(Number, Thread, Input, Additive) \
    (((Number) & PS_ATTRIBUTE_NUMBER_MASK) | \
    ((Thread) ? PS_ATTRIBUTE_THREAD : 0) | \
    ((Input) ? PS_ATTRIBUTE_INPUT : 0) | \
    ((Additive) ? PS_ATTRIBUTE_ADDITIVE : 0))

#define PS_ATTRIBUTE_PARENT_PROCESS \
    PsAttributeValue(PsAttributeParentProcess, FALSE, TRUE, TRUE)
#define PS_ATTRIBUTE_DEBUG_OBJECT \
    PsAttributeValue(PsAttributeDebugObject, FALSE, TRUE, TRUE)
#define PS_ATTRIBUTE_TOKEN \
    PsAttributeValue(PsAttributeToken, FALSE, TRUE, TRUE)
#define PS_ATTRIBUTE_CLIENT_ID \
    PsAttributeValue(PsAttributeClientId, TRUE, FALSE, FALSE)
#define PS_ATTRIBUTE_TEB_ADDRESS \
    PsAttributeValue(PsAttributeTebAddress, TRUE, FALSE, FALSE)
#define PS_ATTRIBUTE_IMAGE_NAME \
    PsAttributeValue(PsAttributeImageName, FALSE, TRUE, FALSE)
#define PS_ATTRIBUTE_IMAGE_INFO \
    PsAttributeValue(PsAttributeImageInfo, FALSE, FALSE, FALSE)
#define PS_ATTRIBUTE_MEMORY_RESERVE \
    PsAttributeValue(PsAttributeMemoryReserve, FALSE, TRUE, FALSE)
#define PS_ATTRIBUTE_PRIORITY_CLASS \
    PsAttributeValue(PsAttributePriorityClass, FALSE, TRUE, FALSE)
#define PS_ATTRIBUTE_ERROR_MODE \
    PsAttributeValue(PsAttributeErrorMode, FALSE, TRUE, FALSE)
#define PS_ATTRIBUTE_STD_HANDLE_INFO \
    PsAttributeValue(PsAttributeStdHandleInfo, FALSE, TRUE, FALSE)
#define PS_ATTRIBUTE_HANDLE_LIST \
    PsAttributeValue(PsAttributeHandleList, FALSE, TRUE, FALSE)
#define PS_ATTRIBUTE_GROUP_AFFINITY \
    PsAttributeValue(PsAttributeGroupAffinity, TRUE, TRUE, FALSE)
#define PS_ATTRIBUTE_PREFERRED_NODE \
    PsAttributeValue(PsAttributePreferredNode, FALSE, TRUE, FALSE)
#define PS_ATTRIBUTE_IDEAL_PROCESSOR \
    PsAttributeValue(PsAttributeIdealProcessor, TRUE, TRUE, FALSE)
#define PS_ATTRIBUTE_UMS_THREAD \
    PsAttributeValue(PsAttributeUmsThread, TRUE, TRUE, FALSE)
#define PS_ATTRIBUTE_MITIGATION_OPTIONS \
    PsAttributeValue(PsAttributeMitigationOptions, FALSE, TRUE, FALSE)
#define PS_ATTRIBUTE_PROTECTION_LEVEL \
    PsAttributeValue(PsAttributeProtectionLevel, FALSE, TRUE, TRUE)
#define PS_ATTRIBUTE_SECURE_PROCESS \
    PsAttributeValue(PsAttributeSecureProcess, FALSE, TRUE, FALSE)
#define PS_ATTRIBUTE_JOB_LIST \
    PsAttributeValue(PsAttributeJobList, FALSE, TRUE, FALSE)
#define PS_ATTRIBUTE_CHILD_PROCESS_POLICY \
    PsAttributeValue(PsAttributeChildProcessPolicy, FALSE, TRUE, FALSE)
#define PS_ATTRIBUTE_ALL_APPLICATION_PACKAGES_POLICY \
    PsAttributeValue(PsAttributeAllApplicationPackagesPolicy, FALSE, TRUE, FALSE)
#define PS_ATTRIBUTE_WIN32K_FILTER \
    PsAttributeValue(PsAttributeWin32kFilter, FALSE, TRUE, FALSE)
#define PS_ATTRIBUTE_SAFE_OPEN_PROMPT_ORIGIN_CLAIM \
    PsAttributeValue(PsAttributeSafeOpenPromptOriginClaim, FALSE, TRUE, FALSE)
#define PS_ATTRIBUTE_BNO_ISOLATION \
    PsAttributeValue(PsAttributeBnoIsolation, FALSE, TRUE, FALSE)
#define PS_ATTRIBUTE_DESKTOP_APP_POLICY \
    PsAttributeValue(PsAttributeDesktopAppPolicy, FALSE, TRUE, FALSE)
#define PS_ATTRIBUTE_CHPE \
    PsAttributeValue(PsAttributeChpe, FALSE, TRUE, TRUE)
#define PS_ATTRIBUTE_MITIGATION_AUDIT_OPTIONS \
    PsAttributeValue(PsAttributeMitigationAuditOptions, FALSE, TRUE, FALSE)
#define PS_ATTRIBUTE_MACHINE_TYPE \
    PsAttributeValue(PsAttributeMachineType, FALSE, TRUE, TRUE)
#define PS_ATTRIBUTE_COMPONENT_FILTER \
    PsAttributeValue(PsAttributeComponentFilter, FALSE, TRUE, FALSE)
#define PS_ATTRIBUTE_ENABLE_OPTIONAL_XSTATE_FEATURES \
    PsAttributeValue(PsAttributeEnableOptionalXStateFeatures, TRUE, TRUE, FALSE)

// end_rev

// begin_private

    typedef struct _PS_ATTRIBUTE
    {
        ULONG_PTR Attribute;
        SIZE_T Size;
        union
        {
            ULONG_PTR Value;
            PVOID ValuePtr;
        };
        PSIZE_T ReturnLength;
    } PS_ATTRIBUTE, * PPS_ATTRIBUTE;

    typedef struct _PS_ATTRIBUTE_LIST
    {
        SIZE_T TotalLength;
        PS_ATTRIBUTE Attributes[1];
    } PS_ATTRIBUTE_LIST, * PPS_ATTRIBUTE_LIST;

    typedef struct _PS_MEMORY_RESERVE
    {
        PVOID ReserveAddress;
        SIZE_T ReserveSize;
    } PS_MEMORY_RESERVE, * PPS_MEMORY_RESERVE;

    typedef enum _PS_STD_HANDLE_STATE
    {
        PsNeverDuplicate,
        PsRequestDuplicate, // duplicate standard handles specified by PseudoHandleMask, and only if StdHandleSubsystemType matches the image subsystem
        PsAlwaysDuplicate, // always duplicate standard handles
        PsMaxStdHandleStates
    } PS_STD_HANDLE_STATE;

    // begin_rev
#define PS_STD_INPUT_HANDLE 0x1
#define PS_STD_OUTPUT_HANDLE 0x2
#define PS_STD_ERROR_HANDLE 0x4
// end_rev

    typedef struct _PS_STD_HANDLE_INFO
    {
        union
        {
            ULONG Flags;
            struct
            {
                ULONG StdHandleState : 2; // PS_STD_HANDLE_STATE
                ULONG PseudoHandleMask : 3; // PS_STD_*
            };
        };
        ULONG StdHandleSubsystemType;
    } PS_STD_HANDLE_INFO, * PPS_STD_HANDLE_INFO;

    typedef union _PS_TRUSTLET_ATTRIBUTE_ACCESSRIGHTS
    {
        UCHAR Trustlet : 1;
        UCHAR Ntos : 1;
        UCHAR WriteHandle : 1;
        UCHAR ReadHandle : 1;
        UCHAR Reserved : 4;
        UCHAR AccessRights;
    } PS_TRUSTLET_ATTRIBUTE_ACCESSRIGHTS, * PPS_TRUSTLET_ATTRIBUTE_ACCESSRIGHTS;

    typedef struct _PS_TRUSTLET_ATTRIBUTE_TYPE
    {
        union
        {
            struct
            {
                UCHAR Version;
                UCHAR DataCount;
                UCHAR SemanticType;
                PS_TRUSTLET_ATTRIBUTE_ACCESSRIGHTS AccessRights;
            };
            ULONG AttributeType;
        };
    } PS_TRUSTLET_ATTRIBUTE_TYPE, * PPS_TRUSTLET_ATTRIBUTE_TYPE;

    typedef struct _PS_TRUSTLET_ATTRIBUTE_HEADER
    {
        PS_TRUSTLET_ATTRIBUTE_TYPE AttributeType;
        ULONG InstanceNumber : 8;
        ULONG Reserved : 24;
    } PS_TRUSTLET_ATTRIBUTE_HEADER, * PPS_TRUSTLET_ATTRIBUTE_HEADER;

    typedef struct _PS_TRUSTLET_ATTRIBUTE_DATA
    {
        PS_TRUSTLET_ATTRIBUTE_HEADER Header;
        ULONGLONG Data[1];
    } PS_TRUSTLET_ATTRIBUTE_DATA, * PPS_TRUSTLET_ATTRIBUTE_DATA;

    typedef struct _PS_TRUSTLET_CREATE_ATTRIBUTES
    {
        ULONGLONG TrustletIdentity;
        PS_TRUSTLET_ATTRIBUTE_DATA Attributes[1];
    } PS_TRUSTLET_CREATE_ATTRIBUTES, * PPS_TRUSTLET_CREATE_ATTRIBUTES;

    // private
    typedef struct _PS_BNO_ISOLATION_PARAMETERS
    {
        UNICODE_STRING IsolationPrefix;
        ULONG HandleCount;
        PVOID* Handles;
        BOOLEAN IsolationEnabled;
    } PS_BNO_ISOLATION_PARAMETERS, * PPS_BNO_ISOLATION_PARAMETERS;

    // private
    typedef enum _PS_MITIGATION_OPTION
    {
        PS_MITIGATION_OPTION_NX,
        PS_MITIGATION_OPTION_SEHOP,
        PS_MITIGATION_OPTION_FORCE_RELOCATE_IMAGES,
        PS_MITIGATION_OPTION_HEAP_TERMINATE,
        PS_MITIGATION_OPTION_BOTTOM_UP_ASLR,
        PS_MITIGATION_OPTION_HIGH_ENTROPY_ASLR,
        PS_MITIGATION_OPTION_STRICT_HANDLE_CHECKS,
        PS_MITIGATION_OPTION_WIN32K_SYSTEM_CALL_DISABLE,
        PS_MITIGATION_OPTION_EXTENSION_POINT_DISABLE,
        PS_MITIGATION_OPTION_PROHIBIT_DYNAMIC_CODE,
        PS_MITIGATION_OPTION_CONTROL_FLOW_GUARD,
        PS_MITIGATION_OPTION_BLOCK_NON_MICROSOFT_BINARIES,
        PS_MITIGATION_OPTION_FONT_DISABLE,
        PS_MITIGATION_OPTION_IMAGE_LOAD_NO_REMOTE,
        PS_MITIGATION_OPTION_IMAGE_LOAD_NO_LOW_LABEL,
        PS_MITIGATION_OPTION_IMAGE_LOAD_PREFER_SYSTEM32,
        PS_MITIGATION_OPTION_RETURN_FLOW_GUARD,
        PS_MITIGATION_OPTION_LOADER_INTEGRITY_CONTINUITY,
        PS_MITIGATION_OPTION_STRICT_CONTROL_FLOW_GUARD,
        PS_MITIGATION_OPTION_RESTRICT_SET_THREAD_CONTEXT,
        PS_MITIGATION_OPTION_ROP_STACKPIVOT, // since REDSTONE3
        PS_MITIGATION_OPTION_ROP_CALLER_CHECK,
        PS_MITIGATION_OPTION_ROP_SIMEXEC,
        PS_MITIGATION_OPTION_EXPORT_ADDRESS_FILTER,
        PS_MITIGATION_OPTION_EXPORT_ADDRESS_FILTER_PLUS,
        PS_MITIGATION_OPTION_RESTRICT_CHILD_PROCESS_CREATION,
        PS_MITIGATION_OPTION_IMPORT_ADDRESS_FILTER,
        PS_MITIGATION_OPTION_MODULE_TAMPERING_PROTECTION,
        PS_MITIGATION_OPTION_RESTRICT_INDIRECT_BRANCH_PREDICTION,
        PS_MITIGATION_OPTION_SPECULATIVE_STORE_BYPASS_DISABLE, // since REDSTONE5
        PS_MITIGATION_OPTION_ALLOW_DOWNGRADE_DYNAMIC_CODE_POLICY,
        PS_MITIGATION_OPTION_CET_USER_SHADOW_STACKS,
        PS_MITIGATION_OPTION_USER_CET_SET_CONTEXT_IP_VALIDATION, // since 21H1
        PS_MITIGATION_OPTION_BLOCK_NON_CET_BINARIES,
        PS_MITIGATION_OPTION_CET_DYNAMIC_APIS_OUT_OF_PROC_ONLY,
        PS_MITIGATION_OPTION_REDIRECTION_TRUST, // since 22H1
        PS_MITIGATION_OPTION_RESTRICT_CORE_SHARING,
    } PS_MITIGATION_OPTION;

    // windows-internals-book:"Chapter 5"
    typedef enum _PS_CREATE_STATE
    {
        PsCreateInitialState,
        PsCreateFailOnFileOpen,
        PsCreateFailOnSectionCreate,
        PsCreateFailExeFormat,
        PsCreateFailMachineMismatch,
        PsCreateFailExeName, // Debugger specified
        PsCreateSuccess,
        PsCreateMaximumStates
    } PS_CREATE_STATE;

    typedef struct _PS_CREATE_INFO
    {
        SIZE_T Size;
        PS_CREATE_STATE State;
        union
        {
            // PsCreateInitialState
            struct
            {
                union
                {
                    ULONG InitFlags;
                    struct
                    {
                        UCHAR WriteOutputOnExit : 1;
                        UCHAR DetectManifest : 1;
                        UCHAR IFEOSkipDebugger : 1;
                        UCHAR IFEODoNotPropagateKeyState : 1;
                        UCHAR SpareBits1 : 4;
                        UCHAR SpareBits2 : 8;
                        USHORT ProhibitedImageCharacteristics : 16;
                    };
                };
                ACCESS_MASK AdditionalFileAccess;
            } InitState;

            // PsCreateFailOnSectionCreate
            struct
            {
                HANDLE FileHandle;
            } FailSection;

            // PsCreateFailExeFormat
            struct
            {
                USHORT DllCharacteristics;
            } ExeFormat;

            // PsCreateFailExeName
            struct
            {
                HANDLE IFEOKey;
            } ExeName;

            // PsCreateSuccess
            struct
            {
                union
                {
                    ULONG OutputFlags;
                    struct
                    {
                        UCHAR ProtectedProcess : 1;
                        UCHAR AddressSpaceOverride : 1;
                        UCHAR DevOverrideEnabled : 1; // from Image File Execution Options
                        UCHAR ManifestDetected : 1;
                        UCHAR ProtectedProcessLight : 1;
                        UCHAR SpareBits1 : 3;
                        UCHAR SpareBits2 : 8;
                        USHORT SpareBits3 : 16;
                    };
                };
                HANDLE FileHandle;
                HANDLE SectionHandle;
                ULONGLONG UserProcessParametersNative;
                ULONG UserProcessParametersWow64;
                ULONG CurrentParameterFlags;
                ULONGLONG PebAddressNative;
                ULONG PebAddressWow64;
                ULONGLONG ManifestAddress;
                ULONG ManifestSize;
            } SuccessState;
        };
    } PS_CREATE_INFO, * PPS_CREATE_INFO;

    // end_private

#if (PHNT_VERSION >= PHNT_VISTA)
    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtCreateUserProcess(
            _Out_ PHANDLE ProcessHandle,
            _Out_ PHANDLE ThreadHandle,
            _In_ ACCESS_MASK ProcessDesiredAccess,
            _In_ ACCESS_MASK ThreadDesiredAccess,
            _In_opt_ POBJECT_ATTRIBUTES ProcessObjectAttributes,
            _In_opt_ POBJECT_ATTRIBUTES ThreadObjectAttributes,
            _In_ ULONG ProcessFlags, // PROCESS_CREATE_FLAGS_*
            _In_ ULONG ThreadFlags, // THREAD_CREATE_FLAGS_*
            _In_opt_ PVOID ProcessParameters, // PRTL_USER_PROCESS_PARAMETERS
            _Inout_ PPS_CREATE_INFO CreateInfo,
            _In_opt_ PPS_ATTRIBUTE_LIST AttributeList
        );
#endif

    // begin_rev
#define THREAD_CREATE_FLAGS_NONE 0x00000000
#define THREAD_CREATE_FLAGS_CREATE_SUSPENDED 0x00000001 // NtCreateUserProcess & NtCreateThreadEx
#define THREAD_CREATE_FLAGS_SKIP_THREAD_ATTACH 0x00000002 // NtCreateThreadEx only
#define THREAD_CREATE_FLAGS_HIDE_FROM_DEBUGGER 0x00000004 // NtCreateThreadEx only
#define THREAD_CREATE_FLAGS_LOADER_WORKER 0x00000010 // NtCreateThreadEx only
#define THREAD_CREATE_FLAGS_SKIP_LOADER_INIT 0x00000020 // NtCreateThreadEx only
#define THREAD_CREATE_FLAGS_BYPASS_PROCESS_FREEZE 0x00000040 // NtCreateThreadEx only
// end_rev

#if (PHNT_VERSION >= PHNT_VISTA)

    typedef NTSTATUS(NTAPI* PUSER_THREAD_START_ROUTINE)(
        _In_ PVOID ThreadParameter
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtCreateThreadEx(
            _Out_ PHANDLE ThreadHandle,
            _In_ ACCESS_MASK DesiredAccess,
            _In_opt_ POBJECT_ATTRIBUTES ObjectAttributes,
            _In_ HANDLE ProcessHandle,
            _In_ PUSER_THREAD_START_ROUTINE StartRoutine,
            _In_opt_ PVOID Argument,
            _In_ ULONG CreateFlags, // THREAD_CREATE_FLAGS_*
            _In_ SIZE_T ZeroBits,
            _In_ SIZE_T StackSize,
            _In_ SIZE_T MaximumStackSize,
            _In_opt_ PPS_ATTRIBUTE_LIST AttributeList
        );

#endif

#endif

    // Job objects

#if (PHNT_MODE != PHNT_MODE_KERNEL)

// JOBOBJECTINFOCLASS
// Note: We don't use an enum since it conflicts with the Windows SDK.
#define JobObjectBasicAccountingInformation 1 // q: JOBOBJECT_BASIC_ACCOUNTING_INFORMATION
#define JobObjectBasicLimitInformation 2 // q; s: JOBOBJECT_BASIC_LIMIT_INFORMATION
#define JobObjectBasicProcessIdList 3 // q: JOBOBJECT_BASIC_PROCESS_ID_LIST
#define JobObjectBasicUIRestrictions 4 // q; s: JOBOBJECT_BASIC_UI_RESTRICTIONS
#define JobObjectSecurityLimitInformation 5 // JOBOBJECT_SECURITY_LIMIT_INFORMATION
#define JobObjectEndOfJobTimeInformation 6 // q; s: JOBOBJECT_END_OF_JOB_TIME_INFORMATION
#define JobObjectAssociateCompletionPortInformation 7 // s: JOBOBJECT_ASSOCIATE_COMPLETION_PORT
#define JobObjectBasicAndIoAccountingInformation 8 // q: JOBOBJECT_BASIC_AND_IO_ACCOUNTING_INFORMATION
#define JobObjectExtendedLimitInformation 9 // q; s: JOBOBJECT_EXTENDED_LIMIT_INFORMATION[V2]
#define JobObjectJobSetInformation 10 // JOBOBJECT_JOBSET_INFORMATION
#define JobObjectGroupInformation 11 // USHORT
#define JobObjectNotificationLimitInformation 12 // JOBOBJECT_NOTIFICATION_LIMIT_INFORMATION
#define JobObjectLimitViolationInformation 13 // JOBOBJECT_LIMIT_VIOLATION_INFORMATION
#define JobObjectGroupInformationEx 14 // GROUP_AFFINITY (ARRAY)
#define JobObjectCpuRateControlInformation 15 // JOBOBJECT_CPU_RATE_CONTROL_INFORMATION
#define JobObjectCompletionFilter 16
#define JobObjectCompletionCounter 17
#define JobObjectFreezeInformation 18 // JOBOBJECT_FREEZE_INFORMATION
#define JobObjectExtendedAccountingInformation 19 // JOBOBJECT_EXTENDED_ACCOUNTING_INFORMATION
#define JobObjectWakeInformation 20 // JOBOBJECT_WAKE_INFORMATION
#define JobObjectBackgroundInformation 21
#define JobObjectSchedulingRankBiasInformation 22
#define JobObjectTimerVirtualizationInformation 23
#define JobObjectCycleTimeNotification 24
#define JobObjectClearEvent 25
#define JobObjectInterferenceInformation 26 // JOBOBJECT_INTERFERENCE_INFORMATION
#define JobObjectClearPeakJobMemoryUsed 27
#define JobObjectMemoryUsageInformation 28 // JOBOBJECT_MEMORY_USAGE_INFORMATION // JOBOBJECT_MEMORY_USAGE_INFORMATION_V2
#define JobObjectSharedCommit 29
#define JobObjectContainerId 30 // JOBOBJECT_CONTAINER_IDENTIFIER_V2
#define JobObjectIoRateControlInformation 31 // JOBOBJECT_IO_RATE_CONTROL_INFORMATION_NATIVE, JOBOBJECT_IO_RATE_CONTROL_INFORMATION_NATIVE_V2, JOBOBJECT_IO_RATE_CONTROL_INFORMATION_NATIVE_V3
#define JobObjectNetRateControlInformation 32 // JOBOBJECT_NET_RATE_CONTROL_INFORMATION
#define JobObjectNotificationLimitInformation2 33 // JOBOBJECT_NOTIFICATION_LIMIT_INFORMATION_2
#define JobObjectLimitViolationInformation2 34 // JOBOBJECT_LIMIT_VIOLATION_INFORMATION_2
#define JobObjectCreateSilo 35
#define JobObjectSiloBasicInformation 36 // SILOOBJECT_BASIC_INFORMATION
#define JobObjectSiloRootDirectory 37 // SILOOBJECT_ROOT_DIRECTORY
#define JobObjectServerSiloBasicInformation 38 // SERVERSILO_BASIC_INFORMATION
#define JobObjectServerSiloUserSharedData 39 // SILO_USER_SHARED_DATA // NtQueryInformationJobObject(NULL, 39, Buffer, sizeof(SILO_USER_SHARED_DATA), 0);
#define JobObjectServerSiloInitialize 40 // SERVERSILO_INIT_INFORMATION
#define JobObjectServerSiloRunningState 41
#define JobObjectIoAttribution 42 // JOBOBJECT_IO_ATTRIBUTION_INFORMATION
#define JobObjectMemoryPartitionInformation 43
#define JobObjectContainerTelemetryId 44
#define JobObjectSiloSystemRoot 45
#define JobObjectEnergyTrackingState 46 // JOBOBJECT_ENERGY_TRACKING_STATE
#define JobObjectThreadImpersonationInformation 47
#define JobObjectIoPriorityLimit 48 // JOBOBJECT_IO_PRIORITY_LIMIT
#define JobObjectPagePriorityLimit 49 // JOBOBJECT_PAGE_PRIORITY_LIMIT
#define MaxJobObjectInfoClass 50

// rev // extended limit v2
#define JOB_OBJECT_LIMIT_SILO_READY 0x00400000

// private
    typedef struct _JOBOBJECT_EXTENDED_LIMIT_INFORMATION_V2
    {
        JOBOBJECT_BASIC_LIMIT_INFORMATION BasicLimitInformation;
        IO_COUNTERS IoInfo;
        SIZE_T ProcessMemoryLimit;
        SIZE_T JobMemoryLimit;
        SIZE_T PeakProcessMemoryUsed;
        SIZE_T PeakJobMemoryUsed;
        SIZE_T JobTotalMemoryLimit;
    } JOBOBJECT_EXTENDED_LIMIT_INFORMATION_V2, * PJOBOBJECT_EXTENDED_LIMIT_INFORMATION_V2;

    // private
    typedef struct _JOBOBJECT_EXTENDED_ACCOUNTING_INFORMATION
    {
        JOBOBJECT_BASIC_ACCOUNTING_INFORMATION BasicInfo;
        IO_COUNTERS IoInfo;
        PROCESS_DISK_COUNTERS DiskIoInfo;
        ULONG64 ContextSwitches;
        LARGE_INTEGER TotalCycleTime;
        ULONG64 ReadyTime;
        PROCESS_ENERGY_VALUES EnergyValues;
    } JOBOBJECT_EXTENDED_ACCOUNTING_INFORMATION, * PJOBOBJECT_EXTENDED_ACCOUNTING_INFORMATION;

    // private
    typedef struct _JOBOBJECT_WAKE_INFORMATION
    {
        HANDLE NotificationChannel;
        ULONG64 WakeCounters[7];
    } JOBOBJECT_WAKE_INFORMATION, * PJOBOBJECT_WAKE_INFORMATION;

    // private
    typedef struct _JOBOBJECT_WAKE_INFORMATION_V1
    {
        HANDLE NotificationChannel;
        ULONG64 WakeCounters[4];
    } JOBOBJECT_WAKE_INFORMATION_V1, * PJOBOBJECT_WAKE_INFORMATION_V1;

    // private
    typedef struct _JOBOBJECT_INTERFERENCE_INFORMATION
    {
        ULONG64 Count;
    } JOBOBJECT_INTERFERENCE_INFORMATION, * PJOBOBJECT_INTERFERENCE_INFORMATION;

    // private
    typedef struct _JOBOBJECT_WAKE_FILTER
    {
        ULONG HighEdgeFilter;
        ULONG LowEdgeFilter;
    } JOBOBJECT_WAKE_FILTER, * PJOBOBJECT_WAKE_FILTER;

    // private
    typedef struct _JOBOBJECT_FREEZE_INFORMATION
    {
        union
        {
            ULONG Flags;
            struct
            {
                ULONG FreezeOperation : 1;
                ULONG FilterOperation : 1;
                ULONG SwapOperation : 1;
                ULONG Reserved : 29;
            };
        };
        BOOLEAN Freeze;
        BOOLEAN Swap;
        UCHAR Reserved0[2];
        JOBOBJECT_WAKE_FILTER WakeFilter;
    } JOBOBJECT_FREEZE_INFORMATION, * PJOBOBJECT_FREEZE_INFORMATION;

    // private
    typedef struct _JOBOBJECT_CONTAINER_IDENTIFIER_V2
    {
        GUID ContainerId;
        GUID ContainerTelemetryId;
        ULONG JobId;
    } JOBOBJECT_CONTAINER_IDENTIFIER_V2, * PJOBOBJECT_CONTAINER_IDENTIFIER_V2;

    // private
    typedef struct _JOBOBJECT_MEMORY_USAGE_INFORMATION
    {
        ULONG64 JobMemory;
        ULONG64 PeakJobMemoryUsed;
    } JOBOBJECT_MEMORY_USAGE_INFORMATION, * PJOBOBJECT_MEMORY_USAGE_INFORMATION;

    // private
    typedef struct _JOBOBJECT_MEMORY_USAGE_INFORMATION_V2
    {
        JOBOBJECT_MEMORY_USAGE_INFORMATION BasicInfo;
        ULONG64 JobSharedMemory;
        ULONG64 Reserved[2];
    } JOBOBJECT_MEMORY_USAGE_INFORMATION_V2, * PJOBOBJECT_MEMORY_USAGE_INFORMATION_V2;

    // private
    typedef struct _SILO_USER_SHARED_DATA
    {
        ULONG ServiceSessionId;
        ULONG ActiveConsoleId;
        LONGLONG ConsoleSessionForegroundProcessId;
        NT_PRODUCT_TYPE NtProductType;
        ULONG SuiteMask;
        ULONG SharedUserSessionId; // since RS2
        BOOLEAN IsMultiSessionSku;
        WCHAR NtSystemRoot[260];
        USHORT UserModeGlobalLogger[16];
        ULONG TimeZoneId; // since 21H2
        LONG TimeZoneBiasStamp;
        KSYSTEM_TIME TimeZoneBias;
        LARGE_INTEGER TimeZoneBiasEffectiveStart;
        LARGE_INTEGER TimeZoneBiasEffectiveEnd;
    } SILO_USER_SHARED_DATA, * PSILO_USER_SHARED_DATA;

    // rev
#define SILO_OBJECT_ROOT_DIRECTORY_SHADOW_ROOT 0x00000001
#define SILO_OBJECT_ROOT_DIRECTORY_INITIALIZE 0x00000002
#define SILO_OBJECT_ROOT_DIRECTORY_SHADOW_DOS_DEVICES 0x00000004

// private
    typedef struct _SILOOBJECT_ROOT_DIRECTORY
    {
        union
        {
            ULONG ControlFlags; // SILO_OBJECT_ROOT_DIRECTORY_*
            UNICODE_STRING Path;
        };
    } SILOOBJECT_ROOT_DIRECTORY, * PSILOOBJECT_ROOT_DIRECTORY;

    // private
    typedef struct _SERVERSILO_INIT_INFORMATION
    {
        HANDLE DeleteEvent;
        BOOLEAN IsDownlevelContainer;
    } SERVERSILO_INIT_INFORMATION, * PSERVERSILO_INIT_INFORMATION;

    // private
    typedef struct _JOBOBJECT_ENERGY_TRACKING_STATE
    {
        ULONG64 Value;
        ULONG UpdateMask;
        ULONG DesiredState;
    } JOBOBJECT_ENERGY_TRACKING_STATE, * PJOBOBJECT_ENERGY_TRACKING_STATE;

    // private
    typedef enum _JOBOBJECT_IO_PRIORITY_LIMIT_FLAGS
    {
        JOBOBJECT_IO_PRIORITY_LIMIT_ENABLE = 0x1,
        JOBOBJECT_IO_PRIORITY_LIMIT_VALID_FLAGS = 0x1,
    } JOBOBJECT_IO_PRIORITY_LIMIT_FLAGS;

    // private
    typedef struct _JOBOBJECT_IO_PRIORITY_LIMIT
    {
        JOBOBJECT_IO_PRIORITY_LIMIT_FLAGS Flags;
        ULONG Priority;
    } JOBOBJECT_IO_PRIORITY_LIMIT, * PJOBOBJECT_IO_PRIORITY_LIMIT;

    // private
    typedef enum _JOBOBJECT_PAGE_PRIORITY_LIMIT_FLAGS
    {
        JOBOBJECT_PAGE_PRIORITY_LIMIT_ENABLE = 0x1,
        JOBOBJECT_PAGE_PRIORITY_LIMIT_VALID_FLAGS = 0x1,
    } JOBOBJECT_PAGE_PRIORITY_LIMIT_FLAGS;

    // private
    typedef struct _JOBOBJECT_PAGE_PRIORITY_LIMIT
    {
        JOBOBJECT_PAGE_PRIORITY_LIMIT_FLAGS Flags;
        ULONG Priority;
    } JOBOBJECT_PAGE_PRIORITY_LIMIT, * PJOBOBJECT_PAGE_PRIORITY_LIMIT;

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtCreateJobObject(
            _Out_ PHANDLE JobHandle,
            _In_ ACCESS_MASK DesiredAccess,
            _In_opt_ POBJECT_ATTRIBUTES ObjectAttributes
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtOpenJobObject(
            _Out_ PHANDLE JobHandle,
            _In_ ACCESS_MASK DesiredAccess,
            _In_ POBJECT_ATTRIBUTES ObjectAttributes
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtAssignProcessToJobObject(
            _In_ HANDLE JobHandle,
            _In_ HANDLE ProcessHandle
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtTerminateJobObject(
            _In_ HANDLE JobHandle,
            _In_ NTSTATUS ExitStatus
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtIsProcessInJob(
            _In_ HANDLE ProcessHandle,
            _In_opt_ HANDLE JobHandle
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtQueryInformationJobObject(
            _In_opt_ HANDLE JobHandle,
            _In_ JOBOBJECTINFOCLASS JobObjectInformationClass,
            _Out_writes_bytes_(JobObjectInformationLength) PVOID JobObjectInformation,
            _In_ ULONG JobObjectInformationLength,
            _Out_opt_ PULONG ReturnLength
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtSetInformationJobObject(
            _In_ HANDLE JobHandle,
            _In_ JOBOBJECTINFOCLASS JobObjectInformationClass,
            _In_reads_bytes_(JobObjectInformationLength) PVOID JobObjectInformation,
            _In_ ULONG JobObjectInformationLength
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtCreateJobSet(
            _In_ ULONG NumJob,
            _In_reads_(NumJob) PJOB_SET_ARRAY UserJobSet,
            _In_ ULONG Flags
        );

#if (PHNT_VERSION >= PHNT_THRESHOLD)
    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtRevertContainerImpersonation(
            VOID
        );
#endif

#endif

    // Reserve objects

#if (PHNT_MODE != PHNT_MODE_KERNEL)

// private
    typedef enum _MEMORY_RESERVE_TYPE
    {
        MemoryReserveUserApc,
        MemoryReserveIoCompletion,
        MemoryReserveTypeMax
    } MEMORY_RESERVE_TYPE;

#if (PHNT_VERSION >= PHNT_WIN7)
    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtAllocateReserveObject(
            _Out_ PHANDLE MemoryReserveHandle,
            _In_ POBJECT_ATTRIBUTES ObjectAttributes,
            _In_ MEMORY_RESERVE_TYPE Type
        );
#endif

    // Process snapshotting

#if (PHNT_VERSION >= PHNT_WINBLUE)
// rev
    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        PssNtCaptureSnapshot(
            _Out_ PHANDLE SnapshotHandle,
            _In_ HANDLE ProcessHandle,
            _In_ ULONG CaptureFlags,
            _In_ ULONG ThreadContextFlags
        );
#endif

#if (PHNT_VERSION >= PHNT_20H1)
    // rev
#define MEMORY_BULK_INFORMATION_FLAG_BASIC 0x00000001

// rev
    typedef struct _NTPSS_MEMORY_BULK_INFORMATION
    {
        ULONG QueryFlags;
        ULONG NumberOfEntries;
        PVOID NextValidAddress;
    } NTPSS_MEMORY_BULK_INFORMATION, * PNTPSS_MEMORY_BULK_INFORMATION;

    // rev
    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtPssCaptureVaSpaceBulk(
            _In_ HANDLE ProcessHandle,
            _In_opt_ PVOID BaseAddress,
            _In_ PNTPSS_MEMORY_BULK_INFORMATION BulkInformation,
            _In_ SIZE_T BulkInformationLength,
            _Out_opt_ PSIZE_T ReturnLength
        );
#endif

#endif

#endif

#if (PHNT_MODE != PHNT_MODE_KERNEL)
#include <cfg.h>
    /*
     * Debugger support functions
     *
     * This file is part of System Informer.
     */

#ifndef _NTDBG_H
#define _NTDBG_H

     // Debugging

    NTSYSAPI
        VOID
        NTAPI
        DbgUserBreakPoint(
            VOID
        );

    NTSYSAPI
        VOID
        NTAPI
        DbgBreakPoint(
            VOID
        );

    NTSYSAPI
        VOID
        NTAPI
        DbgBreakPointWithStatus(
            _In_ ULONG Status
        );

#define DBG_STATUS_CONTROL_C 1
#define DBG_STATUS_SYSRQ 2
#define DBG_STATUS_BUGCHECK_FIRST 3
#define DBG_STATUS_BUGCHECK_SECOND 4
#define DBG_STATUS_FATAL 5
#define DBG_STATUS_DEBUG_CONTROL 6
#define DBG_STATUS_WORKER 7

    NTSYSAPI
        ULONG
        STDAPIVCALLTYPE
        DbgPrint(
            _In_z_ _Printf_format_string_ PCSTR Format,
            ...
        );

    NTSYSAPI
        ULONG
        STDAPIVCALLTYPE
        DbgPrintEx(
            _In_ ULONG ComponentId,
            _In_ ULONG Level,
            _In_z_ _Printf_format_string_ PCSTR Format,
            ...
        );

    NTSYSAPI
        ULONG
        NTAPI
        vDbgPrintEx(
            _In_ ULONG ComponentId,
            _In_ ULONG Level,
            _In_z_ PCCH Format,
            _In_ va_list arglist
        );

    NTSYSAPI
        ULONG
        NTAPI
        vDbgPrintExWithPrefix(
            _In_z_ PCCH Prefix,
            _In_ ULONG ComponentId,
            _In_ ULONG Level,
            _In_z_ PCCH Format,
            _In_ va_list arglist
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        DbgQueryDebugFilterState(
            _In_ ULONG ComponentId,
            _In_ ULONG Level
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        DbgSetDebugFilterState(
            _In_ ULONG ComponentId,
            _In_ ULONG Level,
            _In_ BOOLEAN State
        );

    NTSYSAPI
        ULONG
        NTAPI
        DbgPrompt(
            _In_ PCCH Prompt,
            _Out_writes_bytes_(Length) PCH Response,
            _In_ ULONG Length
        );

    // Definitions

    typedef struct _DBGKM_EXCEPTION
    {
        EXCEPTION_RECORD ExceptionRecord;
        ULONG FirstChance;
    } DBGKM_EXCEPTION, * PDBGKM_EXCEPTION;

    typedef struct _DBGKM_CREATE_THREAD
    {
        ULONG SubSystemKey;
        PVOID StartAddress;
    } DBGKM_CREATE_THREAD, * PDBGKM_CREATE_THREAD;

    typedef struct _DBGKM_CREATE_PROCESS
    {
        ULONG SubSystemKey;
        HANDLE FileHandle;
        PVOID BaseOfImage;
        ULONG DebugInfoFileOffset;
        ULONG DebugInfoSize;
        DBGKM_CREATE_THREAD InitialThread;
    } DBGKM_CREATE_PROCESS, * PDBGKM_CREATE_PROCESS;

    typedef struct _DBGKM_EXIT_THREAD
    {
        NTSTATUS ExitStatus;
    } DBGKM_EXIT_THREAD, * PDBGKM_EXIT_THREAD;

    typedef struct _DBGKM_EXIT_PROCESS
    {
        NTSTATUS ExitStatus;
    } DBGKM_EXIT_PROCESS, * PDBGKM_EXIT_PROCESS;

    typedef struct _DBGKM_LOAD_DLL
    {
        HANDLE FileHandle;
        PVOID BaseOfDll;
        ULONG DebugInfoFileOffset;
        ULONG DebugInfoSize;
        PVOID NamePointer;
    } DBGKM_LOAD_DLL, * PDBGKM_LOAD_DLL;

    typedef struct _DBGKM_UNLOAD_DLL
    {
        PVOID BaseAddress;
    } DBGKM_UNLOAD_DLL, * PDBGKM_UNLOAD_DLL;

    typedef enum _DBG_STATE
    {
        DbgIdle,
        DbgReplyPending,
        DbgCreateThreadStateChange,
        DbgCreateProcessStateChange,
        DbgExitThreadStateChange,
        DbgExitProcessStateChange,
        DbgExceptionStateChange,
        DbgBreakpointStateChange,
        DbgSingleStepStateChange,
        DbgLoadDllStateChange,
        DbgUnloadDllStateChange
    } DBG_STATE, * PDBG_STATE;

    typedef struct _DBGUI_CREATE_THREAD
    {
        HANDLE HandleToThread;
        DBGKM_CREATE_THREAD NewThread;
    } DBGUI_CREATE_THREAD, * PDBGUI_CREATE_THREAD;

    typedef struct _DBGUI_CREATE_PROCESS
    {
        HANDLE HandleToProcess;
        HANDLE HandleToThread;
        DBGKM_CREATE_PROCESS NewProcess;
    } DBGUI_CREATE_PROCESS, * PDBGUI_CREATE_PROCESS;

    typedef struct _DBGUI_WAIT_STATE_CHANGE
    {
        DBG_STATE NewState;
        CLIENT_ID AppClientId;
        union
        {
            DBGKM_EXCEPTION Exception;
            DBGUI_CREATE_THREAD CreateThread;
            DBGUI_CREATE_PROCESS CreateProcessInfo;
            DBGKM_EXIT_THREAD ExitThread;
            DBGKM_EXIT_PROCESS ExitProcess;
            DBGKM_LOAD_DLL LoadDll;
            DBGKM_UNLOAD_DLL UnloadDll;
        } StateInfo;
    } DBGUI_WAIT_STATE_CHANGE, * PDBGUI_WAIT_STATE_CHANGE;

#define DEBUG_READ_EVENT 0x0001
#define DEBUG_PROCESS_ASSIGN 0x0002
#define DEBUG_SET_INFORMATION 0x0004
#define DEBUG_QUERY_INFORMATION 0x0008
#define DEBUG_ALL_ACCESS (STANDARD_RIGHTS_REQUIRED | SYNCHRONIZE | \
    DEBUG_READ_EVENT | DEBUG_PROCESS_ASSIGN | DEBUG_SET_INFORMATION | \
    DEBUG_QUERY_INFORMATION)

#define DEBUG_KILL_ON_CLOSE 0x1

    typedef enum _DEBUGOBJECTINFOCLASS
    {
        DebugObjectUnusedInformation,
        DebugObjectKillProcessOnExitInformation, // s: ULONG
        MaxDebugObjectInfoClass
    } DEBUGOBJECTINFOCLASS, * PDEBUGOBJECTINFOCLASS;

    // System calls

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtCreateDebugObject(
            _Out_ PHANDLE DebugObjectHandle,
            _In_ ACCESS_MASK DesiredAccess,
            _In_opt_ POBJECT_ATTRIBUTES ObjectAttributes,
            _In_ ULONG Flags
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtDebugActiveProcess(
            _In_ HANDLE ProcessHandle,
            _In_ HANDLE DebugObjectHandle
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtDebugContinue(
            _In_ HANDLE DebugObjectHandle,
            _In_ PCLIENT_ID ClientId,
            _In_ NTSTATUS ContinueStatus
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtRemoveProcessDebug(
            _In_ HANDLE ProcessHandle,
            _In_ HANDLE DebugObjectHandle
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtSetInformationDebugObject(
            _In_ HANDLE DebugObjectHandle,
            _In_ DEBUGOBJECTINFOCLASS DebugObjectInformationClass,
            _In_ PVOID DebugInformation,
            _In_ ULONG DebugInformationLength,
            _Out_opt_ PULONG ReturnLength
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtWaitForDebugEvent(
            _In_ HANDLE DebugObjectHandle,
            _In_ BOOLEAN Alertable,
            _In_opt_ PLARGE_INTEGER Timeout,
            _Out_ PDBGUI_WAIT_STATE_CHANGE WaitStateChange
        );

    // Debugging UI

    NTSYSAPI
        NTSTATUS
        NTAPI
        DbgUiConnectToDbg(
            VOID
        );

    NTSYSAPI
        HANDLE
        NTAPI
        DbgUiGetThreadDebugObject(
            VOID
        );

    NTSYSAPI
        VOID
        NTAPI
        DbgUiSetThreadDebugObject(
            _In_ HANDLE DebugObject
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        DbgUiWaitStateChange(
            _Out_ PDBGUI_WAIT_STATE_CHANGE StateChange,
            _In_opt_ PLARGE_INTEGER Timeout
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        DbgUiContinue(
            _In_ PCLIENT_ID AppClientId,
            _In_ NTSTATUS ContinueStatus
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        DbgUiStopDebugging(
            _In_ HANDLE Process
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        DbgUiDebugActiveProcess(
            _In_ HANDLE Process
        );

    NTSYSAPI
        VOID
        NTAPI
        DbgUiRemoteBreakin(
            _In_ PVOID Context
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        DbgUiIssueRemoteBreakin(
            _In_ HANDLE Process
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        DbgUiConvertStateChangeStructure(
            _In_ PDBGUI_WAIT_STATE_CHANGE StateChange,
            _Out_ LPDEBUG_EVENT DebugEvent
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        DbgUiConvertStateChangeStructureEx(
            _In_ PDBGUI_WAIT_STATE_CHANGE StateChange,
            _Out_ LPDEBUG_EVENT DebugEvent
        );

    typedef struct _EVENT_FILTER_DESCRIPTOR* PEVENT_FILTER_DESCRIPTOR;

    typedef VOID(NTAPI* PENABLECALLBACK)(
        _In_ LPCGUID SourceId,
        _In_ ULONG IsEnabled,
        _In_ UCHAR Level,
        _In_ ULONGLONG MatchAnyKeyword,
        _In_ ULONGLONG MatchAllKeyword,
        _In_opt_ PEVENT_FILTER_DESCRIPTOR FilterData,
        _Inout_opt_ PVOID CallbackContext
        );

    typedef ULONGLONG REGHANDLE, * PREGHANDLE;

    NTSYSAPI
        NTSTATUS
        NTAPI
        EtwEventRegister(
            _In_ LPCGUID ProviderId,
            _In_opt_ PENABLECALLBACK EnableCallback,
            _In_opt_ PVOID CallbackContext,
            _Out_ PREGHANDLE RegHandle
        );

#endif
    /*
     * File management support
     *
     * This file is part of System Informer.
     */

#ifndef _NTIOAPI_H
#define _NTIOAPI_H

     // Create disposition

#define FILE_SUPERSEDE                      0x00000000
#define FILE_OPEN                           0x00000001
#define FILE_CREATE                         0x00000002
#define FILE_OPEN_IF                        0x00000003
#define FILE_OVERWRITE                      0x00000004
#define FILE_OVERWRITE_IF                   0x00000005
#define FILE_MAXIMUM_DISPOSITION            0x00000005

// Create/open flags

#define FILE_DIRECTORY_FILE                 0x00000001
#define FILE_WRITE_THROUGH                  0x00000002
#define FILE_SEQUENTIAL_ONLY                0x00000004
#define FILE_NO_INTERMEDIATE_BUFFERING      0x00000008

#define FILE_SYNCHRONOUS_IO_ALERT           0x00000010
#define FILE_SYNCHRONOUS_IO_NONALERT        0x00000020
#define FILE_NON_DIRECTORY_FILE             0x00000040
#define FILE_CREATE_TREE_CONNECTION         0x00000080

#if (PHNT_VERSION >= PHNT_REDSTONE5)
#define TREE_CONNECT_NO_CLIENT_BUFFERING    0x00000008
#define TREE_CONNECT_WRITE_THROUGH          0x00000002
#endif

#define FILE_COMPLETE_IF_OPLOCKED           0x00000100
#define FILE_NO_EA_KNOWLEDGE                0x00000200
#define FILE_OPEN_REMOTE_INSTANCE           0x00000400
#define FILE_RANDOM_ACCESS                  0x00000800

#define FILE_DELETE_ON_CLOSE                0x00001000
#define FILE_OPEN_BY_FILE_ID                0x00002000
#define FILE_OPEN_FOR_BACKUP_INTENT         0x00004000
#define FILE_NO_COMPRESSION                 0x00008000

#if (PHNT_VERSION >= PHNT_WIN7)
#define FILE_OPEN_REQUIRING_OPLOCK          0x00010000
#define FILE_DISALLOW_EXCLUSIVE             0x00020000
#endif
#if (PHNT_VERSION >= PHNT_WIN8)
#define FILE_SESSION_AWARE                  0x00040000
#endif

#define FILE_RESERVE_OPFILTER               0x00100000
#define FILE_OPEN_REPARSE_POINT             0x00200000
#define FILE_OPEN_NO_RECALL                 0x00400000
#define FILE_OPEN_FOR_FREE_SPACE_QUERY      0x00800000

// Extended create/open flags

#define FILE_CONTAINS_EXTENDED_CREATE_INFORMATION   0x10000000
#define FILE_VALID_EXTENDED_OPTION_FLAGS            0x10000000

#if (PHNT_VERSION >= PHNT_WIN11)
    typedef struct _EXTENDED_CREATE_INFORMATION
    {
        LONGLONG ExtendedCreateFlags;
        PVOID EaBuffer;
        ULONG EaLength;
    } EXTENDED_CREATE_INFORMATION, * PEXTENDED_CREATE_INFORMATION;

#define EX_CREATE_FLAG_FILE_SOURCE_OPEN_FOR_COPY 0x00000001
#define EX_CREATE_FLAG_FILE_DEST_OPEN_FOR_COPY   0x00000002
#endif

#define FILE_VALID_OPTION_FLAGS             0x00ffffff
#define FILE_VALID_PIPE_OPTION_FLAGS        0x00000032
#define FILE_VALID_MAILSLOT_OPTION_FLAGS    0x00000032
#define FILE_VALID_SET_FLAGS                0x00000036

#define FILE_COPY_STRUCTURED_STORAGE        0x00000041
#define FILE_STRUCTURED_STORAGE             0x00000441

    // I/O status information values for NtCreateFile/NtOpenFile

#define FILE_SUPERSEDED                 0x00000000
#define FILE_OPENED                     0x00000001
#define FILE_CREATED                    0x00000002
#define FILE_OVERWRITTEN                0x00000003
#define FILE_EXISTS                     0x00000004
#define FILE_DOES_NOT_EXIST             0x00000005

// Special ByteOffset parameters

#define FILE_WRITE_TO_END_OF_FILE       0xffffffff
#define FILE_USE_FILE_POINTER_POSITION  0xfffffffe

// Alignment requirement values

#define FILE_BYTE_ALIGNMENT             0x00000000
#define FILE_WORD_ALIGNMENT             0x00000001
#define FILE_LONG_ALIGNMENT             0x00000003
#define FILE_QUAD_ALIGNMENT             0x00000007
#define FILE_OCTA_ALIGNMENT             0x0000000f
#define FILE_32_BYTE_ALIGNMENT          0x0000001f
#define FILE_64_BYTE_ALIGNMENT          0x0000003f
#define FILE_128_BYTE_ALIGNMENT         0x0000007f
#define FILE_256_BYTE_ALIGNMENT         0x000000ff
#define FILE_512_BYTE_ALIGNMENT         0x000001ff

// Maximum length of a filename string

#define DOS_MAX_COMPONENT_LENGTH 255
#define DOS_MAX_PATH_LENGTH (DOS_MAX_COMPONENT_LENGTH + 5)

#define MAXIMUM_FILENAME_LENGTH 256

// Extended attributes

#define FILE_NEED_EA                    0x00000080

#define FILE_EA_TYPE_BINARY             0xfffe
#define FILE_EA_TYPE_ASCII              0xfffd
#define FILE_EA_TYPE_BITMAP             0xfffb
#define FILE_EA_TYPE_METAFILE           0xfffa
#define FILE_EA_TYPE_ICON               0xfff9
#define FILE_EA_TYPE_EA                 0xffee
#define FILE_EA_TYPE_MVMT               0xffdf
#define FILE_EA_TYPE_MVST               0xffde
#define FILE_EA_TYPE_ASN1               0xffdd
#define FILE_EA_TYPE_FAMILY_IDS         0xff01

// Device characteristics

#define FILE_REMOVABLE_MEDIA                        0x00000001
#define FILE_READ_ONLY_DEVICE                       0x00000002
#define FILE_FLOPPY_DISKETTE                        0x00000004
#define FILE_WRITE_ONCE_MEDIA                       0x00000008
#define FILE_REMOTE_DEVICE                          0x00000010
#define FILE_DEVICE_IS_MOUNTED                      0x00000020
#define FILE_VIRTUAL_VOLUME                         0x00000040
#define FILE_AUTOGENERATED_DEVICE_NAME              0x00000080
#define FILE_DEVICE_SECURE_OPEN                     0x00000100
#define FILE_CHARACTERISTIC_PNP_DEVICE              0x00000800
#define FILE_CHARACTERISTIC_TS_DEVICE               0x00001000
#define FILE_CHARACTERISTIC_WEBDAV_DEVICE           0x00002000
#define FILE_CHARACTERISTIC_CSV                     0x00010000
#define FILE_DEVICE_ALLOW_APPCONTAINER_TRAVERSAL    0x00020000
#define FILE_PORTABLE_DEVICE                        0x00040000
#define FILE_REMOTE_DEVICE_VSMB                     0x00080000
#define FILE_DEVICE_REQUIRE_SECURITY_CHECK          0x00100000

// Named pipe values

// NamedPipeType for NtCreateNamedPipeFile
#define FILE_PIPE_BYTE_STREAM_TYPE      0x00000000
#define FILE_PIPE_MESSAGE_TYPE          0x00000001
#define FILE_PIPE_ACCEPT_REMOTE_CLIENTS 0x00000000
#define FILE_PIPE_REJECT_REMOTE_CLIENTS 0x00000002
#define FILE_PIPE_TYPE_VALID_MASK       0x00000003

// CompletionMode for NtCreateNamedPipeFile
#define FILE_PIPE_QUEUE_OPERATION       0x00000000
#define FILE_PIPE_COMPLETE_OPERATION    0x00000001

// ReadMode for NtCreateNamedPipeFile
#define FILE_PIPE_BYTE_STREAM_MODE      0x00000000
#define FILE_PIPE_MESSAGE_MODE          0x00000001

// NamedPipeConfiguration for NtQueryInformationFile
#define FILE_PIPE_INBOUND               0x00000000
#define FILE_PIPE_OUTBOUND              0x00000001
#define FILE_PIPE_FULL_DUPLEX           0x00000002

// NamedPipeState for NtQueryInformationFile
#define FILE_PIPE_DISCONNECTED_STATE    0x00000001
#define FILE_PIPE_LISTENING_STATE       0x00000002
#define FILE_PIPE_CONNECTED_STATE       0x00000003
#define FILE_PIPE_CLOSING_STATE         0x00000004

// NamedPipeEnd for NtQueryInformationFile
#define FILE_PIPE_CLIENT_END            0x00000000
#define FILE_PIPE_SERVER_END            0x00000001

// Win32 pipe instance limit (0xff)
#define FILE_PIPE_UNLIMITED_INSTANCES   0xffffffff

// Mailslot values

#define MAILSLOT_SIZE_AUTO 0

    typedef struct _IO_STATUS_BLOCK
    {
        union
        {
            NTSTATUS Status;
            PVOID Pointer;
        };
        ULONG_PTR Information;
    } IO_STATUS_BLOCK, * PIO_STATUS_BLOCK;

    typedef VOID(NTAPI* PIO_APC_ROUTINE)(
        _In_ PVOID ApcContext,
        _In_ PIO_STATUS_BLOCK IoStatusBlock,
        _In_ ULONG Reserved
        );

    // private
    typedef struct _FILE_IO_COMPLETION_INFORMATION
    {
        PVOID KeyContext;
        PVOID ApcContext;
        IO_STATUS_BLOCK IoStatusBlock;
    } FILE_IO_COMPLETION_INFORMATION, * PFILE_IO_COMPLETION_INFORMATION;

    typedef enum _FILE_INFORMATION_CLASS
    {
        FileDirectoryInformation = 1, // q: FILE_DIRECTORY_INFORMATION (requires FILE_LIST_DIRECTORY) (NtQueryDirectoryFile[Ex])
        FileFullDirectoryInformation, // q: FILE_FULL_DIR_INFORMATION (requires FILE_LIST_DIRECTORY) (NtQueryDirectoryFile[Ex])
        FileBothDirectoryInformation, // q: FILE_BOTH_DIR_INFORMATION (requires FILE_LIST_DIRECTORY) (NtQueryDirectoryFile[Ex])
        FileBasicInformation, // q; s: FILE_BASIC_INFORMATION (q: requires FILE_READ_ATTRIBUTES; s: requires FILE_WRITE_ATTRIBUTES)
        FileStandardInformation, // q: FILE_STANDARD_INFORMATION, FILE_STANDARD_INFORMATION_EX
        FileInternalInformation, // q: FILE_INTERNAL_INFORMATION
        FileEaInformation, // q: FILE_EA_INFORMATION
        FileAccessInformation, // q: FILE_ACCESS_INFORMATION
        FileNameInformation, // q: FILE_NAME_INFORMATION
        FileRenameInformation, // s: FILE_RENAME_INFORMATION (requires DELETE) // 10
        FileLinkInformation, // s: FILE_LINK_INFORMATION
        FileNamesInformation, // q: FILE_NAMES_INFORMATION (requires FILE_LIST_DIRECTORY) (NtQueryDirectoryFile[Ex])
        FileDispositionInformation, // s: FILE_DISPOSITION_INFORMATION (requires DELETE)
        FilePositionInformation, // q; s: FILE_POSITION_INFORMATION
        FileFullEaInformation, // FILE_FULL_EA_INFORMATION
        FileModeInformation, // q; s: FILE_MODE_INFORMATION
        FileAlignmentInformation, // q: FILE_ALIGNMENT_INFORMATION
        FileAllInformation, // q: FILE_ALL_INFORMATION (requires FILE_READ_ATTRIBUTES)
        FileAllocationInformation, // s: FILE_ALLOCATION_INFORMATION (requires FILE_WRITE_DATA)
        FileEndOfFileInformation, // s: FILE_END_OF_FILE_INFORMATION (requires FILE_WRITE_DATA) // 20
        FileAlternateNameInformation, // q: FILE_NAME_INFORMATION
        FileStreamInformation, // q: FILE_STREAM_INFORMATION
        FilePipeInformation, // q; s: FILE_PIPE_INFORMATION (q: requires FILE_READ_ATTRIBUTES; s: requires FILE_WRITE_ATTRIBUTES)
        FilePipeLocalInformation, // q: FILE_PIPE_LOCAL_INFORMATION (requires FILE_READ_ATTRIBUTES)
        FilePipeRemoteInformation, // q; s: FILE_PIPE_REMOTE_INFORMATION (q: requires FILE_READ_ATTRIBUTES; s: requires FILE_WRITE_ATTRIBUTES)
        FileMailslotQueryInformation, // q: FILE_MAILSLOT_QUERY_INFORMATION
        FileMailslotSetInformation, // s: FILE_MAILSLOT_SET_INFORMATION
        FileCompressionInformation, // q: FILE_COMPRESSION_INFORMATION
        FileObjectIdInformation, // q: FILE_OBJECTID_INFORMATION (requires FILE_LIST_DIRECTORY) (NtQueryDirectoryFile[Ex])
        FileCompletionInformation, // s: FILE_COMPLETION_INFORMATION // 30
        FileMoveClusterInformation, // s: FILE_MOVE_CLUSTER_INFORMATION (requires FILE_WRITE_DATA)
        FileQuotaInformation, // q: FILE_QUOTA_INFORMATION (requires FILE_LIST_DIRECTORY) (NtQueryDirectoryFile[Ex])
        FileReparsePointInformation, // q: FILE_REPARSE_POINT_INFORMATION (requires FILE_LIST_DIRECTORY) (NtQueryDirectoryFile[Ex])
        FileNetworkOpenInformation, // q: FILE_NETWORK_OPEN_INFORMATION (requires FILE_READ_ATTRIBUTES)
        FileAttributeTagInformation, // q: FILE_ATTRIBUTE_TAG_INFORMATION (requires FILE_READ_ATTRIBUTES)
        FileTrackingInformation, // s: FILE_TRACKING_INFORMATION (requires FILE_WRITE_DATA)
        FileIdBothDirectoryInformation, // q: FILE_ID_BOTH_DIR_INFORMATION (requires FILE_LIST_DIRECTORY) (NtQueryDirectoryFile[Ex])
        FileIdFullDirectoryInformation, // q: FILE_ID_FULL_DIR_INFORMATION (requires FILE_LIST_DIRECTORY) (NtQueryDirectoryFile[Ex])
        FileValidDataLengthInformation, // s: FILE_VALID_DATA_LENGTH_INFORMATION (requires FILE_WRITE_DATA and/or SeManageVolumePrivilege)
        FileShortNameInformation, // s: FILE_NAME_INFORMATION (requires DELETE) // 40
        FileIoCompletionNotificationInformation, // q; s: FILE_IO_COMPLETION_NOTIFICATION_INFORMATION (q: requires FILE_READ_ATTRIBUTES) // since VISTA
        FileIoStatusBlockRangeInformation, // s: FILE_IOSTATUSBLOCK_RANGE_INFORMATION (requires SeLockMemoryPrivilege)
        FileIoPriorityHintInformation, // q; s: FILE_IO_PRIORITY_HINT_INFORMATION, FILE_IO_PRIORITY_HINT_INFORMATION_EX (q: requires FILE_READ_DATA)
        FileSfioReserveInformation, // q; s: FILE_SFIO_RESERVE_INFORMATION (q: requires FILE_READ_DATA)
        FileSfioVolumeInformation, // q: FILE_SFIO_VOLUME_INFORMATION (requires FILE_READ_ATTRIBUTES)
        FileHardLinkInformation, // q: FILE_LINKS_INFORMATION
        FileProcessIdsUsingFileInformation, // q: FILE_PROCESS_IDS_USING_FILE_INFORMATION (requires FILE_READ_ATTRIBUTES)
        FileNormalizedNameInformation, // q: FILE_NAME_INFORMATION
        FileNetworkPhysicalNameInformation, // q: FILE_NETWORK_PHYSICAL_NAME_INFORMATION
        FileIdGlobalTxDirectoryInformation, // q: FILE_ID_GLOBAL_TX_DIR_INFORMATION (requires FILE_LIST_DIRECTORY) (NtQueryDirectoryFile[Ex]) // since WIN7 // 50
        FileIsRemoteDeviceInformation, // q: FILE_IS_REMOTE_DEVICE_INFORMATION (requires FILE_READ_ATTRIBUTES)
        FileUnusedInformation,
        FileNumaNodeInformation, // q: FILE_NUMA_NODE_INFORMATION
        FileStandardLinkInformation, // q: FILE_STANDARD_LINK_INFORMATION
        FileRemoteProtocolInformation, // q: FILE_REMOTE_PROTOCOL_INFORMATION
        FileRenameInformationBypassAccessCheck, // (kernel-mode only); s: FILE_RENAME_INFORMATION // since WIN8
        FileLinkInformationBypassAccessCheck, // (kernel-mode only); s: FILE_LINK_INFORMATION
        FileVolumeNameInformation, // q: FILE_VOLUME_NAME_INFORMATION
        FileIdInformation, // q: FILE_ID_INFORMATION
        FileIdExtdDirectoryInformation, // q: FILE_ID_EXTD_DIR_INFORMATION (requires FILE_LIST_DIRECTORY) (NtQueryDirectoryFile[Ex]) // 60
        FileReplaceCompletionInformation, // s: FILE_COMPLETION_INFORMATION // since WINBLUE
        FileHardLinkFullIdInformation, // q: FILE_LINK_ENTRY_FULL_ID_INFORMATION // FILE_LINKS_FULL_ID_INFORMATION
        FileIdExtdBothDirectoryInformation, // q: FILE_ID_EXTD_BOTH_DIR_INFORMATION (requires FILE_LIST_DIRECTORY) (NtQueryDirectoryFile[Ex]) // since THRESHOLD
        FileDispositionInformationEx, // s: FILE_DISPOSITION_INFO_EX (requires DELETE) // since REDSTONE
        FileRenameInformationEx, // s: FILE_RENAME_INFORMATION_EX
        FileRenameInformationExBypassAccessCheck, // (kernel-mode only); s: FILE_RENAME_INFORMATION_EX
        FileDesiredStorageClassInformation, // q; s: FILE_DESIRED_STORAGE_CLASS_INFORMATION (q: requires FILE_READ_ATTRIBUTES; s: requires FILE_WRITE_ATTRIBUTES) // since REDSTONE2
        FileStatInformation, // q: FILE_STAT_INFORMATION (requires FILE_READ_ATTRIBUTES)
        FileMemoryPartitionInformation, // s: FILE_MEMORY_PARTITION_INFORMATION // since REDSTONE3
        FileStatLxInformation, // q: FILE_STAT_LX_INFORMATION (requires FILE_READ_ATTRIBUTES and FILE_READ_EA) // since REDSTONE4 // 70
        FileCaseSensitiveInformation, // q; s: FILE_CASE_SENSITIVE_INFORMATION (q: requires FILE_READ_ATTRIBUTES; s: requires FILE_WRITE_ATTRIBUTES)
        FileLinkInformationEx, // s: FILE_LINK_INFORMATION_EX // since REDSTONE5
        FileLinkInformationExBypassAccessCheck, // (kernel-mode only); s: FILE_LINK_INFORMATION_EX
        FileStorageReserveIdInformation, // q; s: FILE_STORAGE_RESERVE_ID_INFORMATION (q: requires FILE_READ_ATTRIBUTES; s: requires FILE_WRITE_ATTRIBUTES)
        FileCaseSensitiveInformationForceAccessCheck, // q; s: FILE_CASE_SENSITIVE_INFORMATION
        FileKnownFolderInformation, // q; s: FILE_KNOWN_FOLDER_INFORMATION (q: requires FILE_READ_ATTRIBUTES; s: requires FILE_WRITE_ATTRIBUTES) // since WIN11
        FileMaximumInformation
    } FILE_INFORMATION_CLASS, * PFILE_INFORMATION_CLASS;

    // NtQueryInformationFile/NtSetInformationFile types

    typedef struct _FILE_BASIC_INFORMATION
    {
        LARGE_INTEGER CreationTime;
        LARGE_INTEGER LastAccessTime;
        LARGE_INTEGER LastWriteTime;
        LARGE_INTEGER ChangeTime;
        ULONG FileAttributes;
    } FILE_BASIC_INFORMATION, * PFILE_BASIC_INFORMATION;

    typedef struct _FILE_STANDARD_INFORMATION
    {
        LARGE_INTEGER AllocationSize;
        LARGE_INTEGER EndOfFile;
        ULONG NumberOfLinks;
        BOOLEAN DeletePending;
        BOOLEAN Directory;
    } FILE_STANDARD_INFORMATION, * PFILE_STANDARD_INFORMATION;

    //#if (PHNT_VERSION >= PHNT_THRESHOLD)
    typedef struct _FILE_STANDARD_INFORMATION_EX
    {
        LARGE_INTEGER AllocationSize;
        LARGE_INTEGER EndOfFile;
        ULONG NumberOfLinks;
        BOOLEAN DeletePending;
        BOOLEAN Directory;
        BOOLEAN AlternateStream;
        BOOLEAN MetadataAttribute;
    } FILE_STANDARD_INFORMATION_EX, * PFILE_STANDARD_INFORMATION_EX;
    //#endif

    typedef struct _FILE_INTERNAL_INFORMATION
    {
        union
        {
            LARGE_INTEGER IndexNumber;
            struct
            {
                LONGLONG MftRecordIndex : 48; // rev
                LONGLONG SequenceNumber : 16; // rev
            };
        };
    } FILE_INTERNAL_INFORMATION, * PFILE_INTERNAL_INFORMATION;

    typedef struct _FILE_EA_INFORMATION
    {
        ULONG EaSize;
    } FILE_EA_INFORMATION, * PFILE_EA_INFORMATION;

    typedef struct _FILE_ACCESS_INFORMATION
    {
        ACCESS_MASK AccessFlags;
    } FILE_ACCESS_INFORMATION, * PFILE_ACCESS_INFORMATION;

    typedef struct _FILE_POSITION_INFORMATION
    {
        LARGE_INTEGER CurrentByteOffset;
    } FILE_POSITION_INFORMATION, * PFILE_POSITION_INFORMATION;

    typedef struct _FILE_MODE_INFORMATION
    {
        ULONG Mode;
    } FILE_MODE_INFORMATION, * PFILE_MODE_INFORMATION;

    typedef struct _FILE_ALIGNMENT_INFORMATION
    {
        ULONG AlignmentRequirement;
    } FILE_ALIGNMENT_INFORMATION, * PFILE_ALIGNMENT_INFORMATION;

    typedef struct _FILE_NAME_INFORMATION
    {
        ULONG FileNameLength;
        _Field_size_bytes_(FileNameLength) WCHAR FileName[1];
    } FILE_NAME_INFORMATION, * PFILE_NAME_INFORMATION;

    typedef struct _FILE_ALL_INFORMATION
    {
        FILE_BASIC_INFORMATION BasicInformation;
        FILE_STANDARD_INFORMATION StandardInformation;
        FILE_INTERNAL_INFORMATION InternalInformation;
        FILE_EA_INFORMATION EaInformation;
        FILE_ACCESS_INFORMATION AccessInformation;
        FILE_POSITION_INFORMATION PositionInformation;
        FILE_MODE_INFORMATION ModeInformation;
        FILE_ALIGNMENT_INFORMATION AlignmentInformation;
        FILE_NAME_INFORMATION NameInformation;
    } FILE_ALL_INFORMATION, * PFILE_ALL_INFORMATION;

    typedef struct _FILE_NETWORK_OPEN_INFORMATION
    {
        LARGE_INTEGER CreationTime;
        LARGE_INTEGER LastAccessTime;
        LARGE_INTEGER LastWriteTime;
        LARGE_INTEGER ChangeTime;
        LARGE_INTEGER AllocationSize;
        LARGE_INTEGER EndOfFile;
        ULONG FileAttributes;
    } FILE_NETWORK_OPEN_INFORMATION, * PFILE_NETWORK_OPEN_INFORMATION;

    typedef struct _FILE_ATTRIBUTE_TAG_INFORMATION
    {
        ULONG FileAttributes;
        ULONG ReparseTag;
    } FILE_ATTRIBUTE_TAG_INFORMATION, * PFILE_ATTRIBUTE_TAG_INFORMATION;

    typedef struct _FILE_ALLOCATION_INFORMATION
    {
        LARGE_INTEGER AllocationSize;
    } FILE_ALLOCATION_INFORMATION, * PFILE_ALLOCATION_INFORMATION;

    typedef struct _FILE_COMPRESSION_INFORMATION
    {
        LARGE_INTEGER CompressedFileSize;
        USHORT CompressionFormat;
        UCHAR CompressionUnitShift;
        UCHAR ChunkShift;
        UCHAR ClusterShift;
        UCHAR Reserved[3];
    } FILE_COMPRESSION_INFORMATION, * PFILE_COMPRESSION_INFORMATION;

    typedef struct _FILE_DISPOSITION_INFORMATION
    {
        BOOLEAN DeleteFile;
    } FILE_DISPOSITION_INFORMATION, * PFILE_DISPOSITION_INFORMATION;

    typedef struct _FILE_END_OF_FILE_INFORMATION
    {
        LARGE_INTEGER EndOfFile;
    } FILE_END_OF_FILE_INFORMATION, * PFILE_END_OF_FILE_INFORMATION;

    //#if (PHNT_VERSION >= PHNT_REDSTONE5)
#define FLAGS_END_OF_FILE_INFO_EX_EXTEND_PAGING             0x00000001
#define FLAGS_END_OF_FILE_INFO_EX_NO_EXTRA_PAGING_EXTEND    0x00000002
#define FLAGS_END_OF_FILE_INFO_EX_TIME_CONSTRAINED          0x00000004
#define FLAGS_DELAY_REASONS_LOG_FILE_FULL                   0x00000001
#define FLAGS_DELAY_REASONS_BITMAP_SCANNED                  0x00000002

    typedef struct _FILE_END_OF_FILE_INFORMATION_EX
    {
        LARGE_INTEGER EndOfFile;
        LARGE_INTEGER PagingFileSizeInMM;
        LARGE_INTEGER PagingFileMaxSize;
        ULONG Flags;
    } FILE_END_OF_FILE_INFORMATION_EX, * PFILE_END_OF_FILE_INFORMATION_EX;
    //#endif

    typedef struct _FILE_VALID_DATA_LENGTH_INFORMATION
    {
        LARGE_INTEGER ValidDataLength;
    } FILE_VALID_DATA_LENGTH_INFORMATION, * PFILE_VALID_DATA_LENGTH_INFORMATION;

#define FILE_LINK_REPLACE_IF_EXISTS 0x00000001 // since RS5
#define FILE_LINK_POSIX_SEMANTICS   0x00000002

#define FILE_LINK_SUPPRESS_STORAGE_RESERVE_INHERITANCE  0x00000008
#define FILE_LINK_NO_INCREASE_AVAILABLE_SPACE           0x00000010
#define FILE_LINK_NO_DECREASE_AVAILABLE_SPACE           0x00000020
#define FILE_LINK_PRESERVE_AVAILABLE_SPACE              0x00000030
#define FILE_LINK_IGNORE_READONLY_ATTRIBUTE             0x00000040
#define FILE_LINK_FORCE_RESIZE_TARGET_SR                0x00000080 // since 19H1
#define FILE_LINK_FORCE_RESIZE_SOURCE_SR                0x00000100
#define FILE_LINK_FORCE_RESIZE_SR                       0x00000180

    typedef struct _FILE_LINK_INFORMATION
    {
        BOOLEAN ReplaceIfExists;
        HANDLE RootDirectory;
        ULONG FileNameLength;
        _Field_size_bytes_(FileNameLength) WCHAR FileName[1];
    } FILE_LINK_INFORMATION, * PFILE_LINK_INFORMATION;

    typedef struct _FILE_LINK_INFORMATION_EX
    {
        ULONG Flags;
        HANDLE RootDirectory;
        ULONG FileNameLength;
        _Field_size_bytes_(FileNameLength) WCHAR FileName[1];
    } FILE_LINK_INFORMATION_EX, * PFILE_LINK_INFORMATION_EX;

    typedef struct _FILE_MOVE_CLUSTER_INFORMATION
    {
        ULONG ClusterCount;
        HANDLE RootDirectory;
        ULONG FileNameLength;
        _Field_size_bytes_(FileNameLength) WCHAR FileName[1];
    } FILE_MOVE_CLUSTER_INFORMATION, * PFILE_MOVE_CLUSTER_INFORMATION;

    typedef struct _FILE_RENAME_INFORMATION
    {
        BOOLEAN ReplaceIfExists;
        HANDLE RootDirectory;
        ULONG FileNameLength;
        _Field_size_bytes_(FileNameLength) WCHAR FileName[1];
    } FILE_RENAME_INFORMATION, * PFILE_RENAME_INFORMATION;

#define FILE_RENAME_REPLACE_IF_EXISTS                       0x00000001 // since REDSTONE
#define FILE_RENAME_POSIX_SEMANTICS                         0x00000002
#define FILE_RENAME_SUPPRESS_PIN_STATE_INHERITANCE          0x00000004 // since REDSTONE3
#define FILE_RENAME_SUPPRESS_STORAGE_RESERVE_INHERITANCE    0x00000008 // since REDSTONE5
#define FILE_RENAME_NO_INCREASE_AVAILABLE_SPACE             0x00000010
#define FILE_RENAME_NO_DECREASE_AVAILABLE_SPACE             0x00000020
#define FILE_RENAME_PRESERVE_AVAILABLE_SPACE                0x00000030
#define FILE_RENAME_IGNORE_READONLY_ATTRIBUTE               0x00000040
#define FILE_RENAME_FORCE_RESIZE_TARGET_SR                  0x00000080 // since 19H1
#define FILE_RENAME_FORCE_RESIZE_SOURCE_SR                  0x00000100
#define FILE_RENAME_FORCE_RESIZE_SR                         0x00000180

    typedef struct _FILE_RENAME_INFORMATION_EX
    {
        ULONG Flags;
        HANDLE RootDirectory;
        ULONG FileNameLength;
        _Field_size_bytes_(FileNameLength) WCHAR FileName[1];
    } FILE_RENAME_INFORMATION_EX, * PFILE_RENAME_INFORMATION_EX;

    typedef struct _FILE_STREAM_INFORMATION
    {
        ULONG NextEntryOffset;
        ULONG StreamNameLength;
        LARGE_INTEGER StreamSize;
        LARGE_INTEGER StreamAllocationSize;
        _Field_size_bytes_(StreamNameLength) WCHAR StreamName[1];
    } FILE_STREAM_INFORMATION, * PFILE_STREAM_INFORMATION;

    typedef struct _FILE_TRACKING_INFORMATION
    {
        HANDLE DestinationFile;
        ULONG ObjectInformationLength;
        _Field_size_bytes_(ObjectInformationLength) CHAR ObjectInformation[1];
    } FILE_TRACKING_INFORMATION, * PFILE_TRACKING_INFORMATION;

    typedef struct _FILE_COMPLETION_INFORMATION
    {
        HANDLE Port;
        PVOID Key;
    } FILE_COMPLETION_INFORMATION, * PFILE_COMPLETION_INFORMATION;

    typedef struct _FILE_PIPE_INFORMATION
    {
        ULONG ReadMode;
        ULONG CompletionMode;
    } FILE_PIPE_INFORMATION, * PFILE_PIPE_INFORMATION;

    typedef struct _FILE_PIPE_LOCAL_INFORMATION
    {
        ULONG NamedPipeType;
        ULONG NamedPipeConfiguration;
        ULONG MaximumInstances;
        ULONG CurrentInstances;
        ULONG InboundQuota;
        ULONG ReadDataAvailable;
        ULONG OutboundQuota;
        ULONG WriteQuotaAvailable;
        ULONG NamedPipeState;
        ULONG NamedPipeEnd;
    } FILE_PIPE_LOCAL_INFORMATION, * PFILE_PIPE_LOCAL_INFORMATION;

    typedef struct _FILE_PIPE_REMOTE_INFORMATION
    {
        LARGE_INTEGER CollectDataTime;
        ULONG MaximumCollectionCount;
    } FILE_PIPE_REMOTE_INFORMATION, * PFILE_PIPE_REMOTE_INFORMATION;

    typedef struct _FILE_MAILSLOT_QUERY_INFORMATION
    {
        ULONG MaximumMessageSize;
        ULONG MailslotQuota;
        ULONG NextMessageSize;
        ULONG MessagesAvailable;
        LARGE_INTEGER ReadTimeout;
    } FILE_MAILSLOT_QUERY_INFORMATION, * PFILE_MAILSLOT_QUERY_INFORMATION;

    typedef struct _FILE_MAILSLOT_SET_INFORMATION
    {
        PLARGE_INTEGER ReadTimeout;
    } FILE_MAILSLOT_SET_INFORMATION, * PFILE_MAILSLOT_SET_INFORMATION;

    typedef struct _FILE_REPARSE_POINT_INFORMATION
    {
        LONGLONG FileReference;
        ULONG Tag;
    } FILE_REPARSE_POINT_INFORMATION, * PFILE_REPARSE_POINT_INFORMATION;

    typedef struct _FILE_LINK_ENTRY_INFORMATION
    {
        ULONG NextEntryOffset;
        LONGLONG ParentFileId; // LARGE_INTEGER
        ULONG FileNameLength;
        _Field_size_bytes_(FileNameLength) WCHAR FileName[1];
    } FILE_LINK_ENTRY_INFORMATION, * PFILE_LINK_ENTRY_INFORMATION;

    typedef struct _FILE_LINKS_INFORMATION
    {
        ULONG BytesNeeded;
        ULONG EntriesReturned;
        FILE_LINK_ENTRY_INFORMATION Entry;
    } FILE_LINKS_INFORMATION, * PFILE_LINKS_INFORMATION;

    typedef struct _FILE_NETWORK_PHYSICAL_NAME_INFORMATION
    {
        ULONG FileNameLength;
        _Field_size_bytes_(FileNameLength) WCHAR FileName[1];
    } FILE_NETWORK_PHYSICAL_NAME_INFORMATION, * PFILE_NETWORK_PHYSICAL_NAME_INFORMATION;

    typedef struct _FILE_STANDARD_LINK_INFORMATION
    {
        ULONG NumberOfAccessibleLinks;
        ULONG TotalNumberOfLinks;
        BOOLEAN DeletePending;
        BOOLEAN Directory;
    } FILE_STANDARD_LINK_INFORMATION, * PFILE_STANDARD_LINK_INFORMATION;

    typedef struct _FILE_SFIO_RESERVE_INFORMATION
    {
        ULONG RequestsPerPeriod;
        ULONG Period;
        BOOLEAN RetryFailures;
        BOOLEAN Discardable;
        ULONG RequestSize;
        ULONG NumOutstandingRequests;
    } FILE_SFIO_RESERVE_INFORMATION, * PFILE_SFIO_RESERVE_INFORMATION;

    typedef struct _FILE_SFIO_VOLUME_INFORMATION
    {
        ULONG MaximumRequestsPerPeriod;
        ULONG MinimumPeriod;
        ULONG MinimumTransferSize;
    } FILE_SFIO_VOLUME_INFORMATION, * PFILE_SFIO_VOLUME_INFORMATION;

    typedef enum _IO_PRIORITY_HINT
    {
        IoPriorityVeryLow = 0, // Defragging, content indexing and other background I/Os.
        IoPriorityLow, // Prefetching for applications.
        IoPriorityNormal, // Normal I/Os.
        IoPriorityHigh, // Used by filesystems for checkpoint I/O.
        IoPriorityCritical, // Used by memory manager. Not available for applications.
        MaxIoPriorityTypes
    } IO_PRIORITY_HINT;

    typedef struct DECLSPEC_ALIGN(8) _FILE_IO_PRIORITY_HINT_INFORMATION
    {
        IO_PRIORITY_HINT PriorityHint;
    } FILE_IO_PRIORITY_HINT_INFORMATION, * PFILE_IO_PRIORITY_HINT_INFORMATION;

    typedef struct _FILE_IO_PRIORITY_HINT_INFORMATION_EX
    {
        IO_PRIORITY_HINT PriorityHint;
        BOOLEAN BoostOutstanding;
    } FILE_IO_PRIORITY_HINT_INFORMATION_EX, * PFILE_IO_PRIORITY_HINT_INFORMATION_EX;

#define FILE_SKIP_COMPLETION_PORT_ON_SUCCESS 0x1
#define FILE_SKIP_SET_EVENT_ON_HANDLE 0x2
#define FILE_SKIP_SET_USER_EVENT_ON_FAST_IO 0x4

    typedef struct _FILE_IO_COMPLETION_NOTIFICATION_INFORMATION
    {
        ULONG Flags;
    } FILE_IO_COMPLETION_NOTIFICATION_INFORMATION, * PFILE_IO_COMPLETION_NOTIFICATION_INFORMATION;

    typedef struct _FILE_PROCESS_IDS_USING_FILE_INFORMATION
    {
        ULONG NumberOfProcessIdsInList;
        _Field_size_(NumberOfProcessIdsInList) ULONG_PTR ProcessIdList[1];
    } FILE_PROCESS_IDS_USING_FILE_INFORMATION, * PFILE_PROCESS_IDS_USING_FILE_INFORMATION;

    typedef struct _FILE_IS_REMOTE_DEVICE_INFORMATION
    {
        BOOLEAN IsRemote;
    } FILE_IS_REMOTE_DEVICE_INFORMATION, * PFILE_IS_REMOTE_DEVICE_INFORMATION;

    typedef struct _FILE_NUMA_NODE_INFORMATION
    {
        USHORT NodeNumber;
    } FILE_NUMA_NODE_INFORMATION, * PFILE_NUMA_NODE_INFORMATION;

    typedef struct _FILE_IOSTATUSBLOCK_RANGE_INFORMATION
    {
        PUCHAR IoStatusBlockRange;
        ULONG Length;
    } FILE_IOSTATUSBLOCK_RANGE_INFORMATION, * PFILE_IOSTATUSBLOCK_RANGE_INFORMATION;

    // Win32 FILE_REMOTE_PROTOCOL_INFO
    typedef struct _FILE_REMOTE_PROTOCOL_INFORMATION
    {
        // Structure Version
        USHORT StructureVersion;     // 1 for Win7, 2 for Win8 SMB3, 3 for Blue SMB3, 4 for RS5
        USHORT StructureSize;        // sizeof(FILE_REMOTE_PROTOCOL_INFORMATION)

        ULONG Protocol;             // Protocol (WNNC_NET_*) defined in winnetwk.h or ntifs.h.

        // Protocol Version & Type
        USHORT ProtocolMajorVersion;
        USHORT ProtocolMinorVersion;
        USHORT ProtocolRevision;

        USHORT Reserved;

        // Protocol-Generic Information
        ULONG Flags;

        struct
        {
            ULONG Reserved[8];
        } GenericReserved;

        // Protocol specific information

#if (_WIN32_WINNT < PHNT_WIN8)
        struct
        {
            ULONG Reserved[16];
        } ProtocolSpecificReserved;
#endif

#if (PHNT_VERSION >= PHNT_WIN8)
        union
        {
            struct
            {
                struct
                {
                    ULONG Capabilities;
                } Server;
                struct
                {
                    ULONG Capabilities;
#if (PHNT_VERSION >= PHNT_21H1)
                    ULONG ShareFlags;
#else
                    ULONG CachingFlags;
#endif
#if (PHNT_VERSION >= PHNT_REDSTONE5)
                    UCHAR ShareType;
                    UCHAR Reserved0[3];
                    ULONG Reserved1;
#endif
                } Share;
            } Smb2;
            ULONG Reserved[16];
        } ProtocolSpecific;
#endif
    } FILE_REMOTE_PROTOCOL_INFORMATION, * PFILE_REMOTE_PROTOCOL_INFORMATION;

#define CHECKSUM_ENFORCEMENT_OFF 0x00000001

    typedef struct _FILE_INTEGRITY_STREAM_INFORMATION
    {
        USHORT ChecksumAlgorithm;
        UCHAR ChecksumChunkShift;
        UCHAR ClusterShift;
        ULONG Flags;
    } FILE_INTEGRITY_STREAM_INFORMATION, * PFILE_INTEGRITY_STREAM_INFORMATION;

    typedef struct _FILE_VOLUME_NAME_INFORMATION
    {
        ULONG DeviceNameLength;
        _Field_size_bytes_(DeviceNameLength) WCHAR DeviceName[1];
    } FILE_VOLUME_NAME_INFORMATION, * PFILE_VOLUME_NAME_INFORMATION;

#ifndef FILE_INVALID_FILE_ID
#define FILE_INVALID_FILE_ID ((LONGLONG)-1LL)
#endif

#define FILE_ID_IS_INVALID(FID) ((FID).QuadPart == FILE_INVALID_FILE_ID)

#define FILE_ID_128_IS_INVALID(FID128) \
    (((FID128).Identifier[0] == (UCHAR)-1) && \
    ((FID128).Identifier[1] == (UCHAR)-1) && \
    ((FID128).Identifier[2] == (UCHAR)-1) && \
    ((FID128).Identifier[3] == (UCHAR)-1) && \
    ((FID128).Identifier[4] == (UCHAR)-1) && \
    ((FID128).Identifier[5] == (UCHAR)-1) && \
    ((FID128).Identifier[6] == (UCHAR)-1) && \
    ((FID128).Identifier[7] == (UCHAR)-1) && \
    ((FID128).Identifier[8] == (UCHAR)-1) && \
    ((FID128).Identifier[9] == (UCHAR)-1) && \
    ((FID128).Identifier[10] == (UCHAR)-1) && \
    ((FID128).Identifier[11] == (UCHAR)-1) && \
    ((FID128).Identifier[12] == (UCHAR)-1) && \
    ((FID128).Identifier[13] == (UCHAR)-1) && \
    ((FID128).Identifier[14] == (UCHAR)-1) && \
    ((FID128).Identifier[15] == (UCHAR)-1))

#define MAKE_INVALID_FILE_ID_128(FID128) { \
    ((FID128).Identifier[0] = (UCHAR)-1); \
    ((FID128).Identifier[1] = (UCHAR)-1); \
    ((FID128).Identifier[2] = (UCHAR)-1); \
    ((FID128).Identifier[3] = (UCHAR)-1); \
    ((FID128).Identifier[4] = (UCHAR)-1); \
    ((FID128).Identifier[5] = (UCHAR)-1); \
    ((FID128).Identifier[6] = (UCHAR)-1); \
    ((FID128).Identifier[7] = (UCHAR)-1); \
    ((FID128).Identifier[8] = (UCHAR)-1); \
    ((FID128).Identifier[9] = (UCHAR)-1); \
    ((FID128).Identifier[10] = (UCHAR)-1); \
    ((FID128).Identifier[11] = (UCHAR)-1); \
    ((FID128).Identifier[12] = (UCHAR)-1); \
    ((FID128).Identifier[13] = (UCHAR)-1); \
    ((FID128).Identifier[14] = (UCHAR)-1); \
    ((FID128).Identifier[15] = (UCHAR)-1); \
}

    typedef struct _FILE_ID_INFORMATION
    {
        ULONGLONG VolumeSerialNumber;
        union
        {
            FILE_ID_128 FileId;
            struct
            {
                LONGLONG FileIdLowPart : 64; // rev
                LONGLONG FileIdHighPart : 64; // rev
            };
        };
    } FILE_ID_INFORMATION, * PFILE_ID_INFORMATION;

    typedef struct _FILE_ID_EXTD_DIR_INFORMATION
    {
        ULONG NextEntryOffset;
        ULONG FileIndex;
        LARGE_INTEGER CreationTime;
        LARGE_INTEGER LastAccessTime;
        LARGE_INTEGER LastWriteTime;
        LARGE_INTEGER ChangeTime;
        LARGE_INTEGER EndOfFile;
        LARGE_INTEGER AllocationSize;
        ULONG FileAttributes;
        ULONG FileNameLength;
        ULONG EaSize;
        ULONG ReparsePointTag;
        FILE_ID_128 FileId;
        _Field_size_bytes_(FileNameLength) WCHAR FileName[1];
    } FILE_ID_EXTD_DIR_INFORMATION, * PFILE_ID_EXTD_DIR_INFORMATION;

    typedef struct _FILE_LINK_ENTRY_FULL_ID_INFORMATION
    {
        ULONG NextEntryOffset;
        FILE_ID_128 ParentFileId;
        ULONG FileNameLength;
        _Field_size_bytes_(FileNameLength) WCHAR FileName[1];
    } FILE_LINK_ENTRY_FULL_ID_INFORMATION, * PFILE_LINK_ENTRY_FULL_ID_INFORMATION;

    typedef struct _FILE_LINKS_FULL_ID_INFORMATION
    {
        ULONG BytesNeeded;
        ULONG EntriesReturned;
        FILE_LINK_ENTRY_FULL_ID_INFORMATION Entry;
    } FILE_LINKS_FULL_ID_INFORMATION, * PFILE_LINKS_FULL_ID_INFORMATION;

    typedef struct _FILE_ID_EXTD_BOTH_DIR_INFORMATION
    {
        ULONG NextEntryOffset;
        ULONG FileIndex;
        LARGE_INTEGER CreationTime;
        LARGE_INTEGER LastAccessTime;
        LARGE_INTEGER LastWriteTime;
        LARGE_INTEGER ChangeTime;
        LARGE_INTEGER EndOfFile;
        LARGE_INTEGER AllocationSize;
        ULONG FileAttributes;
        ULONG FileNameLength;
        ULONG EaSize;
        ULONG ReparsePointTag;
        FILE_ID_128 FileId;
        CCHAR ShortNameLength;
        WCHAR ShortName[12];
        _Field_size_bytes_(FileNameLength) WCHAR FileName[1];
    } FILE_ID_EXTD_BOTH_DIR_INFORMATION, * PFILE_ID_EXTD_BOTH_DIR_INFORMATION;

    typedef struct _FILE_STAT_INFORMATION
    {
        LARGE_INTEGER FileId;
        LARGE_INTEGER CreationTime;
        LARGE_INTEGER LastAccessTime;
        LARGE_INTEGER LastWriteTime;
        LARGE_INTEGER ChangeTime;
        LARGE_INTEGER AllocationSize;
        LARGE_INTEGER EndOfFile;
        ULONG FileAttributes;
        ULONG ReparseTag;
        ULONG NumberOfLinks;
        ACCESS_MASK EffectiveAccess;
    } FILE_STAT_INFORMATION, * PFILE_STAT_INFORMATION;

    typedef struct _FILE_MEMORY_PARTITION_INFORMATION
    {
        HANDLE OwnerPartitionHandle;
        union
        {
            struct
            {
                UCHAR NoCrossPartitionAccess;
                UCHAR Spare[3];
            };
            ULONG AllFlags;
        } Flags;
    } FILE_MEMORY_PARTITION_INFORMATION, * PFILE_MEMORY_PARTITION_INFORMATION;

    // LxFlags
#define LX_FILE_METADATA_HAS_UID 0x1
#define LX_FILE_METADATA_HAS_GID 0x2
#define LX_FILE_METADATA_HAS_MODE 0x4
#define LX_FILE_METADATA_HAS_DEVICE_ID 0x8
#define LX_FILE_CASE_SENSITIVE_DIR 0x10

    typedef struct _FILE_STAT_LX_INFORMATION
    {
        LARGE_INTEGER FileId;
        LARGE_INTEGER CreationTime;
        LARGE_INTEGER LastAccessTime;
        LARGE_INTEGER LastWriteTime;
        LARGE_INTEGER ChangeTime;
        LARGE_INTEGER AllocationSize;
        LARGE_INTEGER EndOfFile;
        ULONG FileAttributes;
        ULONG ReparseTag;
        ULONG NumberOfLinks;
        ACCESS_MASK EffectiveAccess;
        ULONG LxFlags;
        ULONG LxUid;
        ULONG LxGid;
        ULONG LxMode;
        ULONG LxDeviceIdMajor;
        ULONG LxDeviceIdMinor;
    } FILE_STAT_LX_INFORMATION, * PFILE_STAT_LX_INFORMATION;

    typedef struct _FILE_STORAGE_RESERVE_ID_INFORMATION {
        STORAGE_RESERVE_ID StorageReserveId;
    } FILE_STORAGE_RESERVE_ID_INFORMATION, * PFILE_STORAGE_RESERVE_ID_INFORMATION;

#define FILE_CS_FLAG_CASE_SENSITIVE_DIR     0x00000001

    typedef struct _FILE_CASE_SENSITIVE_INFORMATION
    {
        ULONG Flags;
    } FILE_CASE_SENSITIVE_INFORMATION, * PFILE_CASE_SENSITIVE_INFORMATION;

    typedef enum _FILE_KNOWN_FOLDER_TYPE
    {
        KnownFolderNone,
        KnownFolderDesktop,
        KnownFolderDocuments,
        KnownFolderDownloads,
        KnownFolderMusic,
        KnownFolderPictures,
        KnownFolderVideos,
        KnownFolderOther,
        KnownFolderMax = 7
    } FILE_KNOWN_FOLDER_TYPE;

    typedef struct _FILE_KNOWN_FOLDER_INFORMATION
    {
        FILE_KNOWN_FOLDER_TYPE Type;
    } FILE_KNOWN_FOLDER_INFORMATION, * PFILE_KNOWN_FOLDER_INFORMATION;

    // NtQueryDirectoryFile types

    typedef struct _FILE_DIRECTORY_INFORMATION
    {
        ULONG NextEntryOffset;
        ULONG FileIndex;
        LARGE_INTEGER CreationTime;
        LARGE_INTEGER LastAccessTime;
        LARGE_INTEGER LastWriteTime;
        LARGE_INTEGER ChangeTime;
        LARGE_INTEGER EndOfFile;
        LARGE_INTEGER AllocationSize;
        ULONG FileAttributes;
        ULONG FileNameLength;
        _Field_size_bytes_(FileNameLength) WCHAR FileName[1];
    } FILE_DIRECTORY_INFORMATION, * PFILE_DIRECTORY_INFORMATION;

    typedef struct _FILE_FULL_DIR_INFORMATION
    {
        ULONG NextEntryOffset;
        ULONG FileIndex;
        LARGE_INTEGER CreationTime;
        LARGE_INTEGER LastAccessTime;
        LARGE_INTEGER LastWriteTime;
        LARGE_INTEGER ChangeTime;
        LARGE_INTEGER EndOfFile;
        LARGE_INTEGER AllocationSize;
        ULONG FileAttributes;
        ULONG FileNameLength;
        ULONG EaSize;
        _Field_size_bytes_(FileNameLength) WCHAR FileName[1];
    } FILE_FULL_DIR_INFORMATION, * PFILE_FULL_DIR_INFORMATION;

    typedef struct _FILE_ID_FULL_DIR_INFORMATION
    {
        ULONG NextEntryOffset;
        ULONG FileIndex;
        LARGE_INTEGER CreationTime;
        LARGE_INTEGER LastAccessTime;
        LARGE_INTEGER LastWriteTime;
        LARGE_INTEGER ChangeTime;
        LARGE_INTEGER EndOfFile;
        LARGE_INTEGER AllocationSize;
        ULONG FileAttributes;
        ULONG FileNameLength;
        ULONG EaSize;
        LARGE_INTEGER FileId;
        _Field_size_bytes_(FileNameLength) WCHAR FileName[1];
    } FILE_ID_FULL_DIR_INFORMATION, * PFILE_ID_FULL_DIR_INFORMATION;

    typedef struct _FILE_BOTH_DIR_INFORMATION
    {
        ULONG NextEntryOffset;
        ULONG FileIndex;
        LARGE_INTEGER CreationTime;
        LARGE_INTEGER LastAccessTime;
        LARGE_INTEGER LastWriteTime;
        LARGE_INTEGER ChangeTime;
        LARGE_INTEGER EndOfFile;
        LARGE_INTEGER AllocationSize;
        ULONG FileAttributes;
        ULONG FileNameLength;
        ULONG EaSize;
        CCHAR ShortNameLength;
        WCHAR ShortName[12];
        _Field_size_bytes_(FileNameLength) WCHAR FileName[1];
    } FILE_BOTH_DIR_INFORMATION, * PFILE_BOTH_DIR_INFORMATION;

    typedef struct _FILE_ID_BOTH_DIR_INFORMATION
    {
        ULONG NextEntryOffset;
        ULONG FileIndex;
        LARGE_INTEGER CreationTime;
        LARGE_INTEGER LastAccessTime;
        LARGE_INTEGER LastWriteTime;
        LARGE_INTEGER ChangeTime;
        LARGE_INTEGER EndOfFile;
        LARGE_INTEGER AllocationSize;
        ULONG FileAttributes;
        ULONG FileNameLength;
        ULONG EaSize;
        CCHAR ShortNameLength;
        WCHAR ShortName[12];
        LARGE_INTEGER FileId;
        _Field_size_bytes_(FileNameLength) WCHAR FileName[1];
    } FILE_ID_BOTH_DIR_INFORMATION, * PFILE_ID_BOTH_DIR_INFORMATION;

    typedef struct _FILE_NAMES_INFORMATION
    {
        ULONG NextEntryOffset;
        ULONG FileIndex;
        ULONG FileNameLength;
        _Field_size_bytes_(FileNameLength) WCHAR FileName[1];
    } FILE_NAMES_INFORMATION, * PFILE_NAMES_INFORMATION;

    typedef struct _FILE_ID_GLOBAL_TX_DIR_INFORMATION
    {
        ULONG NextEntryOffset;
        ULONG FileIndex;
        LARGE_INTEGER CreationTime;
        LARGE_INTEGER LastAccessTime;
        LARGE_INTEGER LastWriteTime;
        LARGE_INTEGER ChangeTime;
        LARGE_INTEGER EndOfFile;
        LARGE_INTEGER AllocationSize;
        ULONG FileAttributes;
        ULONG FileNameLength;
        LARGE_INTEGER FileId;
        GUID LockingTransactionId;
        ULONG TxInfoFlags;
        _Field_size_bytes_(FileNameLength) WCHAR FileName[1];
    } FILE_ID_GLOBAL_TX_DIR_INFORMATION, * PFILE_ID_GLOBAL_TX_DIR_INFORMATION;

#define FILE_ID_GLOBAL_TX_DIR_INFO_FLAG_WRITELOCKED 0x00000001
#define FILE_ID_GLOBAL_TX_DIR_INFO_FLAG_VISIBLE_TO_TX 0x00000002
#define FILE_ID_GLOBAL_TX_DIR_INFO_FLAG_VISIBLE_OUTSIDE_TX 0x00000004

    typedef struct _FILE_OBJECTID_INFORMATION
    {
        LONGLONG FileReference;
        UCHAR ObjectId[16]; // GUID
        union
        {
            struct
            {
                UCHAR BirthVolumeId[16];
                UCHAR BirthObjectId[16];
                UCHAR DomainId[16];
            };
            UCHAR ExtendedInfo[48];
        };
    } FILE_OBJECTID_INFORMATION, * PFILE_OBJECTID_INFORMATION;

    typedef struct _FILE_DIRECTORY_NEXT_INFORMATION
    {
        ULONG NextEntryOffset;
    } FILE_DIRECTORY_NEXT_INFORMATION, * PFILE_DIRECTORY_NEXT_INFORMATION;

    // NtQueryEaFile/NtSetEaFile types

    typedef struct _FILE_FULL_EA_INFORMATION
    {
        ULONG NextEntryOffset;
        UCHAR Flags;
        UCHAR EaNameLength;
        USHORT EaValueLength;
        _Field_size_bytes_(EaNameLength) CHAR EaName[1];
        // ...
        // UCHAR EaValue[1]
    } FILE_FULL_EA_INFORMATION, * PFILE_FULL_EA_INFORMATION;

    typedef struct _FILE_GET_EA_INFORMATION
    {
        ULONG NextEntryOffset;
        UCHAR EaNameLength;
        _Field_size_bytes_(EaNameLength) CHAR EaName[1];
    } FILE_GET_EA_INFORMATION, * PFILE_GET_EA_INFORMATION;

    // NtQueryQuotaInformationFile/NtSetQuotaInformationFile types

    typedef struct _FILE_GET_QUOTA_INFORMATION
    {
        ULONG NextEntryOffset;
        ULONG SidLength;
        _Field_size_bytes_(SidLength) SID Sid;
    } FILE_GET_QUOTA_INFORMATION, * PFILE_GET_QUOTA_INFORMATION;

    typedef struct _FILE_QUOTA_INFORMATION
    {
        ULONG NextEntryOffset;
        ULONG SidLength;
        LARGE_INTEGER ChangeTime;
        LARGE_INTEGER QuotaUsed;
        LARGE_INTEGER QuotaThreshold;
        LARGE_INTEGER QuotaLimit;
        _Field_size_bytes_(SidLength) SID Sid;
    } FILE_QUOTA_INFORMATION, * PFILE_QUOTA_INFORMATION;

    typedef enum _FSINFOCLASS
    {
        FileFsVolumeInformation = 1, // q: FILE_FS_VOLUME_INFORMATION
        FileFsLabelInformation, // s: FILE_FS_LABEL_INFORMATION (requires FILE_WRITE_DATA to volume)
        FileFsSizeInformation, // q: FILE_FS_SIZE_INFORMATION
        FileFsDeviceInformation, // q: FILE_FS_DEVICE_INFORMATION
        FileFsAttributeInformation, // q: FILE_FS_ATTRIBUTE_INFORMATION
        FileFsControlInformation, // q, s: FILE_FS_CONTROL_INFORMATION  (q: requires FILE_READ_DATA; s: requires FILE_WRITE_DATA to volume)
        FileFsFullSizeInformation, // q: FILE_FS_FULL_SIZE_INFORMATION
        FileFsObjectIdInformation, // q; s: FILE_FS_OBJECTID_INFORMATION (s: requires FILE_WRITE_DATA to volume)
        FileFsDriverPathInformation, // q: FILE_FS_DRIVER_PATH_INFORMATION
        FileFsVolumeFlagsInformation, // q; s: FILE_FS_VOLUME_FLAGS_INFORMATION (q: requires FILE_READ_ATTRIBUTES; s: requires FILE_WRITE_ATTRIBUTES to volume) // 10
        FileFsSectorSizeInformation, // q: FILE_FS_SECTOR_SIZE_INFORMATION // since WIN8
        FileFsDataCopyInformation, // q: FILE_FS_DATA_COPY_INFORMATION
        FileFsMetadataSizeInformation, // q: FILE_FS_METADATA_SIZE_INFORMATION // since THRESHOLD
        FileFsFullSizeInformationEx, // q: FILE_FS_FULL_SIZE_INFORMATION_EX // since REDSTONE5
        FileFsMaximumInformation
    } FSINFOCLASS, * PFSINFOCLASS;
    typedef enum _FSINFOCLASS FS_INFORMATION_CLASS;

    // NtQueryVolumeInformation/NtSetVolumeInformation types

    typedef struct _FILE_FS_VOLUME_INFORMATION
    {
        LARGE_INTEGER VolumeCreationTime;
        ULONG VolumeSerialNumber;
        ULONG VolumeLabelLength;
        BOOLEAN SupportsObjects;
        _Field_size_bytes_(VolumeLabelLength) WCHAR VolumeLabel[1];
    } FILE_FS_VOLUME_INFORMATION, * PFILE_FS_VOLUME_INFORMATION;

    typedef struct _FILE_FS_LABEL_INFORMATION
    {
        ULONG VolumeLabelLength;
        _Field_size_bytes_(VolumeLabelLength) WCHAR VolumeLabel[1];
    } FILE_FS_LABEL_INFORMATION, * PFILE_FS_LABEL_INFORMATION;

    typedef struct _FILE_FS_SIZE_INFORMATION
    {
        LARGE_INTEGER TotalAllocationUnits;
        LARGE_INTEGER AvailableAllocationUnits;
        ULONG SectorsPerAllocationUnit;
        ULONG BytesPerSector;
    } FILE_FS_SIZE_INFORMATION, * PFILE_FS_SIZE_INFORMATION;

    // FileSystemControlFlags
#define FILE_VC_QUOTA_NONE 0x00000000
#define FILE_VC_QUOTA_TRACK 0x00000001
#define FILE_VC_QUOTA_ENFORCE 0x00000002
#define FILE_VC_QUOTA_MASK 0x00000003
#define FILE_VC_CONTENT_INDEX_DISABLED 0x00000008
#define FILE_VC_LOG_QUOTA_THRESHOLD 0x00000010
#define FILE_VC_LOG_QUOTA_LIMIT 0x00000020
#define FILE_VC_LOG_VOLUME_THRESHOLD 0x00000040
#define FILE_VC_LOG_VOLUME_LIMIT 0x00000080
#define FILE_VC_QUOTAS_INCOMPLETE 0x00000100
#define FILE_VC_QUOTAS_REBUILDING 0x00000200
#define FILE_VC_VALID_MASK 0x000003ff

    typedef struct _FILE_FS_CONTROL_INFORMATION
    {
        LARGE_INTEGER FreeSpaceStartFiltering;
        LARGE_INTEGER FreeSpaceThreshold;
        LARGE_INTEGER FreeSpaceStopFiltering;
        LARGE_INTEGER DefaultQuotaThreshold;
        LARGE_INTEGER DefaultQuotaLimit;
        ULONG FileSystemControlFlags; // FILE_VC_*
    } FILE_FS_CONTROL_INFORMATION, * PFILE_FS_CONTROL_INFORMATION;

    typedef struct _FILE_FS_FULL_SIZE_INFORMATION
    {
        LARGE_INTEGER TotalAllocationUnits;
        LARGE_INTEGER CallerAvailableAllocationUnits;
        LARGE_INTEGER ActualAvailableAllocationUnits;
        ULONG SectorsPerAllocationUnit;
        ULONG BytesPerSector;
    } FILE_FS_FULL_SIZE_INFORMATION, * PFILE_FS_FULL_SIZE_INFORMATION;

    typedef struct _FILE_FS_OBJECTID_INFORMATION
    {
        UCHAR ObjectId[16];
        union
        {
            struct
            {
                UCHAR BirthVolumeId[16];
                UCHAR BirthObjectId[16];
                UCHAR DomainId[16];
            };
            UCHAR ExtendedInfo[48];
        };
    } FILE_FS_OBJECTID_INFORMATION, * PFILE_FS_OBJECTID_INFORMATION;

    typedef struct _FILE_FS_DEVICE_INFORMATION
    {
        DEVICE_TYPE DeviceType;
        ULONG Characteristics;
    } FILE_FS_DEVICE_INFORMATION, * PFILE_FS_DEVICE_INFORMATION;

    typedef struct _FILE_FS_ATTRIBUTE_INFORMATION
    {
        ULONG FileSystemAttributes;
        LONG MaximumComponentNameLength;
        ULONG FileSystemNameLength;
        _Field_size_bytes_(FileSystemNameLength) WCHAR FileSystemName[1];
    } FILE_FS_ATTRIBUTE_INFORMATION, * PFILE_FS_ATTRIBUTE_INFORMATION;

    typedef struct _FILE_FS_DRIVER_PATH_INFORMATION
    {
        BOOLEAN DriverInPath;
        ULONG DriverNameLength;
        _Field_size_bytes_(DriverNameLength) WCHAR DriverName[1];
    } FILE_FS_DRIVER_PATH_INFORMATION, * PFILE_FS_DRIVER_PATH_INFORMATION;

    typedef struct _FILE_FS_VOLUME_FLAGS_INFORMATION
    {
        ULONG Flags;
    } FILE_FS_VOLUME_FLAGS_INFORMATION, * PFILE_FS_VOLUME_FLAGS_INFORMATION;

#define SSINFO_FLAGS_ALIGNED_DEVICE 0x00000001
#define SSINFO_FLAGS_PARTITION_ALIGNED_ON_DEVICE 0x00000002
#define SSINFO_FLAGS_NO_SEEK_PENALTY 0x00000004
#define SSINFO_FLAGS_TRIM_ENABLED 0x00000008
#define SSINFO_FLAGS_BYTE_ADDRESSABLE 0x00000010 // since REDSTONE

    // If set for Sector and Partition fields, alignment is not known.
#define SSINFO_OFFSET_UNKNOWN 0xffffffff

    typedef struct _FILE_FS_SECTOR_SIZE_INFORMATION
    {
        ULONG LogicalBytesPerSector;
        ULONG PhysicalBytesPerSectorForAtomicity;
        ULONG PhysicalBytesPerSectorForPerformance;
        ULONG FileSystemEffectivePhysicalBytesPerSectorForAtomicity;
        ULONG Flags; // SSINFO_FLAGS_*
        ULONG ByteOffsetForSectorAlignment;
        ULONG ByteOffsetForPartitionAlignment;
    } FILE_FS_SECTOR_SIZE_INFORMATION, * PFILE_FS_SECTOR_SIZE_INFORMATION;

    typedef struct _FILE_FS_DATA_COPY_INFORMATION
    {
        ULONG NumberOfCopies;
    } FILE_FS_DATA_COPY_INFORMATION, * PFILE_FS_DATA_COPY_INFORMATION;

    typedef struct _FILE_FS_METADATA_SIZE_INFORMATION
    {
        LARGE_INTEGER TotalMetadataAllocationUnits;
        ULONG SectorsPerAllocationUnit;
        ULONG BytesPerSector;
    } FILE_FS_METADATA_SIZE_INFORMATION, * PFILE_FS_METADATA_SIZE_INFORMATION;

    typedef struct _FILE_FS_FULL_SIZE_INFORMATION_EX
    {
        ULONGLONG ActualTotalAllocationUnits;
        ULONGLONG ActualAvailableAllocationUnits;
        ULONGLONG ActualPoolUnavailableAllocationUnits;
        ULONGLONG CallerTotalAllocationUnits;
        ULONGLONG CallerAvailableAllocationUnits;
        ULONGLONG CallerPoolUnavailableAllocationUnits;
        ULONGLONG UsedAllocationUnits;
        ULONGLONG TotalReservedAllocationUnits;
        ULONGLONG VolumeStorageReserveAllocationUnits;
        ULONGLONG AvailableCommittedAllocationUnits;
        ULONGLONG PoolAvailableAllocationUnits;
        ULONG SectorsPerAllocationUnit;
        ULONG BytesPerSector;
    } FILE_FS_FULL_SIZE_INFORMATION_EX, * PFILE_FS_FULL_SIZE_INFORMATION_EX;

    // System calls

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtCreateFile(
            _Out_ PHANDLE FileHandle,
            _In_ ACCESS_MASK DesiredAccess,
            _In_ POBJECT_ATTRIBUTES ObjectAttributes,
            _Out_ PIO_STATUS_BLOCK IoStatusBlock,
            _In_opt_ PLARGE_INTEGER AllocationSize,
            _In_ ULONG FileAttributes,
            _In_ ULONG ShareAccess,
            _In_ ULONG CreateDisposition,
            _In_ ULONG CreateOptions,
            _In_reads_bytes_opt_(EaLength) PVOID EaBuffer,
            _In_ ULONG EaLength
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtCreateNamedPipeFile(
            _Out_ PHANDLE FileHandle,
            _In_ ULONG DesiredAccess,
            _In_ POBJECT_ATTRIBUTES ObjectAttributes,
            _Out_ PIO_STATUS_BLOCK IoStatusBlock,
            _In_ ULONG ShareAccess,
            _In_ ULONG CreateDisposition,
            _In_ ULONG CreateOptions,
            _In_ ULONG NamedPipeType,
            _In_ ULONG ReadMode,
            _In_ ULONG CompletionMode,
            _In_ ULONG MaximumInstances,
            _In_ ULONG InboundQuota,
            _In_ ULONG OutboundQuota,
            _In_ PLARGE_INTEGER DefaultTimeout
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtCreateMailslotFile(
            _Out_ PHANDLE FileHandle,
            _In_ ULONG DesiredAccess,
            _In_ POBJECT_ATTRIBUTES ObjectAttributes,
            _Out_ PIO_STATUS_BLOCK IoStatusBlock,
            _In_ ULONG CreateOptions,
            _In_ ULONG MailslotQuota,
            _In_ ULONG MaximumMessageSize,
            _In_ PLARGE_INTEGER ReadTimeout
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtOpenFile(
            _Out_ PHANDLE FileHandle,
            _In_ ACCESS_MASK DesiredAccess,
            _In_ POBJECT_ATTRIBUTES ObjectAttributes,
            _Out_ PIO_STATUS_BLOCK IoStatusBlock,
            _In_ ULONG ShareAccess,
            _In_ ULONG OpenOptions
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtDeleteFile(
            _In_ POBJECT_ATTRIBUTES ObjectAttributes
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtFlushBuffersFile(
            _In_ HANDLE FileHandle,
            _Out_ PIO_STATUS_BLOCK IoStatusBlock
        );

#define FLUSH_FLAGS_FILE_DATA_ONLY 0x00000001
#define FLUSH_FLAGS_NO_SYNC 0x00000002
#define FLUSH_FLAGS_FILE_DATA_SYNC_ONLY 0x00000004 // REDSTONE1

#if (PHNT_VERSION >= PHNT_WIN8)
    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtFlushBuffersFileEx(
            _In_ HANDLE FileHandle,
            _In_ ULONG Flags,
            _In_reads_bytes_(ParametersSize) PVOID Parameters,
            _In_ ULONG ParametersSize,
            _Out_ PIO_STATUS_BLOCK IoStatusBlock
        );
#endif

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtQueryInformationFile(
            _In_ HANDLE FileHandle,
            _Out_ PIO_STATUS_BLOCK IoStatusBlock,
            _Out_writes_bytes_(Length) PVOID FileInformation,
            _In_ ULONG Length,
            _In_ FILE_INFORMATION_CLASS FileInformationClass
        );

#if (PHNT_VERSION >= PHNT_REDSTONE2)
    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtQueryInformationByName(
            _In_ POBJECT_ATTRIBUTES ObjectAttributes,
            _Out_ PIO_STATUS_BLOCK IoStatusBlock,
            _Out_writes_bytes_(Length) PVOID FileInformation,
            _In_ ULONG Length,
            _In_ FILE_INFORMATION_CLASS FileInformationClass
        );
#endif

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtSetInformationFile(
            _In_ HANDLE FileHandle,
            _Out_ PIO_STATUS_BLOCK IoStatusBlock,
            _In_reads_bytes_(Length) PVOID FileInformation,
            _In_ ULONG Length,
            _In_ FILE_INFORMATION_CLASS FileInformationClass
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtQueryDirectoryFile(
            _In_ HANDLE FileHandle,
            _In_opt_ HANDLE Event,
            _In_opt_ PIO_APC_ROUTINE ApcRoutine,
            _In_opt_ PVOID ApcContext,
            _Out_ PIO_STATUS_BLOCK IoStatusBlock,
            _Out_writes_bytes_(Length) PVOID FileInformation,
            _In_ ULONG Length,
            _In_ FILE_INFORMATION_CLASS FileInformationClass,
            _In_ BOOLEAN ReturnSingleEntry,
            _In_opt_ PUNICODE_STRING FileName,
            _In_ BOOLEAN RestartScan
        );

#if (PHNT_VERSION >= PHNT_REDSTONE3)
    // QueryFlags values for NtQueryDirectoryFileEx
#define FILE_QUERY_RESTART_SCAN 0x00000001
#define FILE_QUERY_RETURN_SINGLE_ENTRY 0x00000002
#define FILE_QUERY_INDEX_SPECIFIED 0x00000004
#define FILE_QUERY_RETURN_ON_DISK_ENTRIES_ONLY 0x00000008
#if (PHNT_VERSION >= PHNT_REDSTONE5)
#define FILE_QUERY_NO_CURSOR_UPDATE 0x00000010
#endif

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtQueryDirectoryFileEx(
            _In_ HANDLE FileHandle,
            _In_opt_ HANDLE Event,
            _In_opt_ PIO_APC_ROUTINE ApcRoutine,
            _In_opt_ PVOID ApcContext,
            _Out_ PIO_STATUS_BLOCK IoStatusBlock,
            _Out_writes_bytes_(Length) PVOID FileInformation,
            _In_ ULONG Length,
            _In_ FILE_INFORMATION_CLASS FileInformationClass,
            _In_ ULONG QueryFlags,
            _In_opt_ PUNICODE_STRING FileName
        );
#endif

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtQueryEaFile(
            _In_ HANDLE FileHandle,
            _Out_ PIO_STATUS_BLOCK IoStatusBlock,
            _Out_writes_bytes_(Length) PVOID Buffer,
            _In_ ULONG Length,
            _In_ BOOLEAN ReturnSingleEntry,
            _In_reads_bytes_opt_(EaListLength) PVOID EaList,
            _In_ ULONG EaListLength,
            _In_opt_ PULONG EaIndex,
            _In_ BOOLEAN RestartScan
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtSetEaFile(
            _In_ HANDLE FileHandle,
            _Out_ PIO_STATUS_BLOCK IoStatusBlock,
            _In_reads_bytes_(Length) PVOID Buffer,
            _In_ ULONG Length
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtQueryQuotaInformationFile(
            _In_ HANDLE FileHandle,
            _Out_ PIO_STATUS_BLOCK IoStatusBlock,
            _Out_writes_bytes_(Length) PVOID Buffer,
            _In_ ULONG Length,
            _In_ BOOLEAN ReturnSingleEntry,
            _In_reads_bytes_opt_(SidListLength) PVOID SidList,
            _In_ ULONG SidListLength,
            _In_opt_ PSID StartSid,
            _In_ BOOLEAN RestartScan
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtSetQuotaInformationFile(
            _In_ HANDLE FileHandle,
            _Out_ PIO_STATUS_BLOCK IoStatusBlock,
            _In_reads_bytes_(Length) PVOID Buffer,
            _In_ ULONG Length
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtQueryVolumeInformationFile(
            _In_ HANDLE FileHandle,
            _Out_ PIO_STATUS_BLOCK IoStatusBlock,
            _Out_writes_bytes_(Length) PVOID FsInformation,
            _In_ ULONG Length,
            _In_ FSINFOCLASS FsInformationClass
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtSetVolumeInformationFile(
            _In_ HANDLE FileHandle,
            _Out_ PIO_STATUS_BLOCK IoStatusBlock,
            _In_reads_bytes_(Length) PVOID FsInformation,
            _In_ ULONG Length,
            _In_ FSINFOCLASS FsInformationClass
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtCancelIoFile(
            _In_ HANDLE FileHandle,
            _Out_ PIO_STATUS_BLOCK IoStatusBlock
        );

#if (PHNT_VERSION >= PHNT_VISTA)
    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtCancelIoFileEx(
            _In_ HANDLE FileHandle,
            _In_opt_ PIO_STATUS_BLOCK IoRequestToCancel,
            _Out_ PIO_STATUS_BLOCK IoStatusBlock
        );
#endif

#if (PHNT_VERSION >= PHNT_VISTA)
    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtCancelSynchronousIoFile(
            _In_ HANDLE ThreadHandle,
            _In_opt_ PIO_STATUS_BLOCK IoRequestToCancel,
            _Out_ PIO_STATUS_BLOCK IoStatusBlock
        );
#endif

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtDeviceIoControlFile(
            _In_ HANDLE FileHandle,
            _In_opt_ HANDLE Event,
            _In_opt_ PIO_APC_ROUTINE ApcRoutine,
            _In_opt_ PVOID ApcContext,
            _Out_ PIO_STATUS_BLOCK IoStatusBlock,
            _In_ ULONG IoControlCode,
            _In_reads_bytes_opt_(InputBufferLength) PVOID InputBuffer,
            _In_ ULONG InputBufferLength,
            _Out_writes_bytes_opt_(OutputBufferLength) PVOID OutputBuffer,
            _In_ ULONG OutputBufferLength
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtFsControlFile(
            _In_ HANDLE FileHandle,
            _In_opt_ HANDLE Event,
            _In_opt_ PIO_APC_ROUTINE ApcRoutine,
            _In_opt_ PVOID ApcContext,
            _Out_ PIO_STATUS_BLOCK IoStatusBlock,
            _In_ ULONG FsControlCode,
            _In_reads_bytes_opt_(InputBufferLength) PVOID InputBuffer,
            _In_ ULONG InputBufferLength,
            _Out_writes_bytes_opt_(OutputBufferLength) PVOID OutputBuffer,
            _In_ ULONG OutputBufferLength
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtReadFile(
            _In_ HANDLE FileHandle,
            _In_opt_ HANDLE Event,
            _In_opt_ PIO_APC_ROUTINE ApcRoutine,
            _In_opt_ PVOID ApcContext,
            _Out_ PIO_STATUS_BLOCK IoStatusBlock,
            _Out_writes_bytes_(Length) PVOID Buffer,
            _In_ ULONG Length,
            _In_opt_ PLARGE_INTEGER ByteOffset,
            _In_opt_ PULONG Key
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtWriteFile(
            _In_ HANDLE FileHandle,
            _In_opt_ HANDLE Event,
            _In_opt_ PIO_APC_ROUTINE ApcRoutine,
            _In_opt_ PVOID ApcContext,
            _Out_ PIO_STATUS_BLOCK IoStatusBlock,
            _In_reads_bytes_(Length) PVOID Buffer,
            _In_ ULONG Length,
            _In_opt_ PLARGE_INTEGER ByteOffset,
            _In_opt_ PULONG Key
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtReadFileScatter(
            _In_ HANDLE FileHandle,
            _In_opt_ HANDLE Event,
            _In_opt_ PIO_APC_ROUTINE ApcRoutine,
            _In_opt_ PVOID ApcContext,
            _Out_ PIO_STATUS_BLOCK IoStatusBlock,
            _In_ PFILE_SEGMENT_ELEMENT SegmentArray,
            _In_ ULONG Length,
            _In_opt_ PLARGE_INTEGER ByteOffset,
            _In_opt_ PULONG Key
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtWriteFileGather(
            _In_ HANDLE FileHandle,
            _In_opt_ HANDLE Event,
            _In_opt_ PIO_APC_ROUTINE ApcRoutine,
            _In_opt_ PVOID ApcContext,
            _Out_ PIO_STATUS_BLOCK IoStatusBlock,
            _In_ PFILE_SEGMENT_ELEMENT SegmentArray,
            _In_ ULONG Length,
            _In_opt_ PLARGE_INTEGER ByteOffset,
            _In_opt_ PULONG Key
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtLockFile(
            _In_ HANDLE FileHandle,
            _In_opt_ HANDLE Event,
            _In_opt_ PIO_APC_ROUTINE ApcRoutine,
            _In_opt_ PVOID ApcContext,
            _Out_ PIO_STATUS_BLOCK IoStatusBlock,
            _In_ PLARGE_INTEGER ByteOffset,
            _In_ PLARGE_INTEGER Length,
            _In_ ULONG Key,
            _In_ BOOLEAN FailImmediately,
            _In_ BOOLEAN ExclusiveLock
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtUnlockFile(
            _In_ HANDLE FileHandle,
            _Out_ PIO_STATUS_BLOCK IoStatusBlock,
            _In_ PLARGE_INTEGER ByteOffset,
            _In_ PLARGE_INTEGER Length,
            _In_ ULONG Key
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtQueryAttributesFile(
            _In_ POBJECT_ATTRIBUTES ObjectAttributes,
            _Out_ PFILE_BASIC_INFORMATION FileInformation
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtQueryFullAttributesFile(
            _In_ POBJECT_ATTRIBUTES ObjectAttributes,
            _Out_ PFILE_NETWORK_OPEN_INFORMATION FileInformation
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtNotifyChangeDirectoryFile(
            _In_ HANDLE FileHandle,
            _In_opt_ HANDLE Event,
            _In_opt_ PIO_APC_ROUTINE ApcRoutine,
            _In_opt_ PVOID ApcContext,
            _Out_ PIO_STATUS_BLOCK IoStatusBlock,
            _Out_writes_bytes_(Length) PVOID Buffer, // FILE_NOTIFY_INFORMATION
            _In_ ULONG Length,
            _In_ ULONG CompletionFilter,
            _In_ BOOLEAN WatchTree
        );

    // private
    typedef enum _DIRECTORY_NOTIFY_INFORMATION_CLASS
    {
        DirectoryNotifyInformation = 1, // FILE_NOTIFY_INFORMATION
        DirectoryNotifyExtendedInformation, // FILE_NOTIFY_EXTENDED_INFORMATION
        DirectoryNotifyFullInformation, // since 22H2
        DirectoryNotifyMaximumInformation
    } DIRECTORY_NOTIFY_INFORMATION_CLASS, * PDIRECTORY_NOTIFY_INFORMATION_CLASS;

#if (PHNT_VERSION >= PHNT_REDSTONE3)
    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtNotifyChangeDirectoryFileEx(
            _In_ HANDLE FileHandle,
            _In_opt_ HANDLE Event,
            _In_opt_ PIO_APC_ROUTINE ApcRoutine,
            _In_opt_ PVOID ApcContext,
            _Out_ PIO_STATUS_BLOCK IoStatusBlock,
            _Out_writes_bytes_(Length) PVOID Buffer,
            _In_ ULONG Length,
            _In_ ULONG CompletionFilter,
            _In_ BOOLEAN WatchTree,
            _In_opt_ DIRECTORY_NOTIFY_INFORMATION_CLASS DirectoryNotifyInformationClass
        );
#endif

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtLoadDriver(
            _In_ PUNICODE_STRING DriverServiceName
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtUnloadDriver(
            _In_ PUNICODE_STRING DriverServiceName
        );

    // I/O completion port

#ifndef IO_COMPLETION_QUERY_STATE
#define IO_COMPLETION_QUERY_STATE 0x0001
#endif

#ifndef IO_COMPLETION_MODIFY_STATE
#define IO_COMPLETION_MODIFY_STATE 0x0002
#endif

#ifndef IO_COMPLETION_ALL_ACCESS
#define IO_COMPLETION_ALL_ACCESS (IO_COMPLETION_QUERY_STATE|IO_COMPLETION_MODIFY_STATE|STANDARD_RIGHTS_REQUIRED|SYNCHRONIZE)
#endif

    typedef enum _IO_COMPLETION_INFORMATION_CLASS
    {
        IoCompletionBasicInformation
    } IO_COMPLETION_INFORMATION_CLASS;

    typedef struct _IO_COMPLETION_BASIC_INFORMATION
    {
        LONG Depth;
    } IO_COMPLETION_BASIC_INFORMATION, * PIO_COMPLETION_BASIC_INFORMATION;

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtCreateIoCompletion(
            _Out_ PHANDLE IoCompletionHandle,
            _In_ ACCESS_MASK DesiredAccess,
            _In_opt_ POBJECT_ATTRIBUTES ObjectAttributes,
            _In_opt_ ULONG Count
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtOpenIoCompletion(
            _Out_ PHANDLE IoCompletionHandle,
            _In_ ACCESS_MASK DesiredAccess,
            _In_ POBJECT_ATTRIBUTES ObjectAttributes
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtQueryIoCompletion(
            _In_ HANDLE IoCompletionHandle,
            _In_ IO_COMPLETION_INFORMATION_CLASS IoCompletionInformationClass,
            _Out_writes_bytes_(IoCompletionInformationLength) PVOID IoCompletionInformation,
            _In_ ULONG IoCompletionInformationLength,
            _Out_opt_ PULONG ReturnLength
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtSetIoCompletion(
            _In_ HANDLE IoCompletionHandle,
            _In_opt_ PVOID KeyContext,
            _In_opt_ PVOID ApcContext,
            _In_ NTSTATUS IoStatus,
            _In_ ULONG_PTR IoStatusInformation
        );

#if (PHNT_VERSION >= PHNT_WIN7)
    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtSetIoCompletionEx(
            _In_ HANDLE IoCompletionHandle,
            _In_ HANDLE IoCompletionPacketHandle,
            _In_opt_ PVOID KeyContext,
            _In_opt_ PVOID ApcContext,
            _In_ NTSTATUS IoStatus,
            _In_ ULONG_PTR IoStatusInformation
        );
#endif

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtRemoveIoCompletion(
            _In_ HANDLE IoCompletionHandle,
            _Out_ PVOID* KeyContext,
            _Out_ PVOID* ApcContext,
            _Out_ PIO_STATUS_BLOCK IoStatusBlock,
            _In_opt_ PLARGE_INTEGER Timeout
        );

#if (PHNT_VERSION >= PHNT_VISTA)
    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtRemoveIoCompletionEx(
            _In_ HANDLE IoCompletionHandle,
            _Out_writes_to_(Count, *NumEntriesRemoved) PFILE_IO_COMPLETION_INFORMATION IoCompletionInformation,
            _In_ ULONG Count,
            _Out_ PULONG NumEntriesRemoved,
            _In_opt_ PLARGE_INTEGER Timeout,
            _In_ BOOLEAN Alertable
        );
#endif

    // Wait completion packet

#if (PHNT_VERSION >= PHNT_WIN8)

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtCreateWaitCompletionPacket(
            _Out_ PHANDLE WaitCompletionPacketHandle,
            _In_ ACCESS_MASK DesiredAccess,
            _In_opt_ POBJECT_ATTRIBUTES ObjectAttributes
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtAssociateWaitCompletionPacket(
            _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 AlreadySignaled
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtCancelWaitCompletionPacket(
            _In_ HANDLE WaitCompletionPacketHandle,
            _In_ BOOLEAN RemoveSignaledPacket
        );

#endif

    // Sessions

    typedef enum _IO_SESSION_EVENT
    {
        IoSessionEventIgnore,
        IoSessionEventCreated,
        IoSessionEventTerminated,
        IoSessionEventConnected,
        IoSessionEventDisconnected,
        IoSessionEventLogon,
        IoSessionEventLogoff,
        IoSessionEventMax
    } IO_SESSION_EVENT;

    typedef enum _IO_SESSION_STATE
    {
        IoSessionStateCreated = 1,
        IoSessionStateInitialized = 2,
        IoSessionStateConnected = 3,
        IoSessionStateDisconnected = 4,
        IoSessionStateDisconnectedLoggedOn = 5,
        IoSessionStateLoggedOn = 6,
        IoSessionStateLoggedOff = 7,
        IoSessionStateTerminated = 8,
        IoSessionStateMax
    } IO_SESSION_STATE;

    // Sessions

#if (PHNT_MODE != PHNT_MODE_KERNEL)

#if (PHNT_VERSION >= PHNT_VISTA)
    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtOpenSession(
            _Out_ PHANDLE SessionHandle,
            _In_ ACCESS_MASK DesiredAccess,
            _In_ POBJECT_ATTRIBUTES ObjectAttributes
        );
#endif

#endif

#if (PHNT_VERSION >= PHNT_WIN7)
    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtNotifyChangeSession(
            _In_ HANDLE SessionHandle,
            _In_ ULONG ChangeSequenceNumber,
            _In_ PLARGE_INTEGER ChangeTimeStamp,
            _In_ IO_SESSION_EVENT Event,
            _In_ IO_SESSION_STATE NewState,
            _In_ IO_SESSION_STATE PreviousState,
            _In_reads_bytes_opt_(PayloadSize) PVOID Payload,
            _In_ ULONG PayloadSize
        );
#endif

    // I/O Ring

#if (PHNT_VERSION >= PHNT_WIN11)
    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtCreateIoRing(
            _Out_ PHANDLE IoRingHandle,
            _In_ ULONG CreateParametersLength,
            _In_ PVOID CreateParameters,
            _In_ ULONG OutputParametersLength,
            _Out_ PVOID OutputParameters
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtSubmitIoRing(
            _In_ HANDLE IoRingHandle,
            _In_ ULONG Flags,
            _In_opt_ ULONG WaitOperations,
            _In_opt_ PLARGE_INTEGER Timeout
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtQueryIoRingCapabilities(
            _In_ SIZE_T IoRingCapabilitiesLength,
            _Out_ PVOID IoRingCapabilities
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtSetInformationIoRing(
            _In_ HANDLE IoRingHandle,
            _In_ ULONG IoRingInformationClass,
            _In_ ULONG IoRingInformationLength,
            _In_ PVOID IoRingInformation
        );
#endif

    // Other types

    typedef enum _INTERFACE_TYPE
    {
        InterfaceTypeUndefined = -1,
        Internal = 0,
        Isa = 1,
        Eisa = 2,
        MicroChannel = 3,
        TurboChannel = 4,
        PCIBus = 5,
        VMEBus = 6,
        NuBus = 7,
        PCMCIABus = 8,
        CBus = 9,
        MPIBus = 10,
        MPSABus = 11,
        ProcessorInternal = 12,
        InternalPowerBus = 13,
        PNPISABus = 14,
        PNPBus = 15,
        Vmcs = 16,
        ACPIBus = 17,
        MaximumInterfaceType
    } INTERFACE_TYPE, * PINTERFACE_TYPE;

    typedef enum _DMA_WIDTH
    {
        Width8Bits,
        Width16Bits,
        Width32Bits,
        Width64Bits,
        WidthNoWrap,
        MaximumDmaWidth
    } DMA_WIDTH, * PDMA_WIDTH;

    typedef enum _DMA_SPEED
    {
        Compatible,
        TypeA,
        TypeB,
        TypeC,
        TypeF,
        MaximumDmaSpeed
    } DMA_SPEED, * PDMA_SPEED;

    typedef enum _BUS_DATA_TYPE
    {
        ConfigurationSpaceUndefined = -1,
        Cmos,
        EisaConfiguration,
        Pos,
        CbusConfiguration,
        PCIConfiguration,
        VMEConfiguration,
        NuBusConfiguration,
        PCMCIAConfiguration,
        MPIConfiguration,
        MPSAConfiguration,
        PNPISAConfiguration,
        SgiInternalConfiguration,
        MaximumBusDataType
    } BUS_DATA_TYPE, * PBUS_DATA_TYPE;

    // Control structures

    // Reparse structure for FSCTL_SET_REPARSE_POINT, FSCTL_GET_REPARSE_POINT, FSCTL_DELETE_REPARSE_POINT

#define SYMLINK_FLAG_RELATIVE 0x00000001

#if (PHNT_VERSION >= PHNT_REDSTONE4)
#define SYMLINK_DIRECTORY 0x80000000 // If set then this is a directory symlink
#define SYMLINK_FILE 0x40000000 // If set then this is a file symlink
#endif

    typedef struct _REPARSE_DATA_BUFFER
    {
        ULONG ReparseTag;
        USHORT ReparseDataLength;
        USHORT Reserved;

        _Field_size_bytes_(ReparseDataLength)
            union
        {
            struct
            {
                USHORT SubstituteNameOffset;
                USHORT SubstituteNameLength;
                USHORT PrintNameOffset;
                USHORT PrintNameLength;
                ULONG Flags;
                WCHAR PathBuffer[1];
            } SymbolicLinkReparseBuffer;
            struct
            {
                USHORT SubstituteNameOffset;
                USHORT SubstituteNameLength;
                USHORT PrintNameOffset;
                USHORT PrintNameLength;
                WCHAR PathBuffer[1];
            } MountPointReparseBuffer;
            struct
            {
                ULONG StringCount;
                WCHAR StringList[1];
            } AppExecLinkReparseBuffer;
            struct
            {
                UCHAR DataBuffer[1];
            } GenericReparseBuffer;
        };
    } REPARSE_DATA_BUFFER, * PREPARSE_DATA_BUFFER;

#define REPARSE_DATA_BUFFER_HEADER_SIZE UFIELD_OFFSET(REPARSE_DATA_BUFFER, GenericReparseBuffer)

#if (PHNT_VERSION >= PHNT_REDSTONE)
    // Reparse structure for FSCTL_SET_REPARSE_POINT_EX

    typedef struct _REPARSE_DATA_BUFFER_EX
    {
        ULONG Flags;

        //
        //  This is the existing reparse tag on the file if any,  if the
        //  caller wants to replace the reparse tag too.
        //
        //    - To set the reparse data  along with the reparse tag that
        //      could be different,  pass the current reparse tag of the
        //      file.
        //
        //    - To update the reparse data while having the same reparse
        //      tag,  the caller should give the existing reparse tag in
        //      this ExistingReparseTag field.
        //
        //    - To set the reparse tag along with reparse data on a file
        //      that doesn't have a reparse tag yet, set this to zero.
        //
        //  If the ExistingReparseTag  does not match the reparse tag on
        //  the file,  the FSCTL_SET_REPARSE_POINT_EX  would  fail  with
        //  STATUS_IO_REPARSE_TAG_MISMATCH. NOTE: If a file doesn't have
        //  a reparse tag, ExistingReparseTag should be 0.
        //

        ULONG ExistingReparseTag;

        //  For non-Microsoft reparse tags, this is the existing reparse
        //  guid on the file if any,  if the caller wants to replace the
        //  reparse tag and / or guid along with the data.
        //
        //  If ExistingReparseTag is 0, the file is not expected to have
        //  any reparse tags, so ExistingReparseGuid is ignored. And for
        //  non-Microsoft tags ExistingReparseGuid should match the guid
        //  in the file if ExistingReparseTag is non zero.

        GUID ExistingReparseGuid;

        //
        //  Reserved
        //
        ULONGLONG Reserved;

        //
        //  Reparse data to set
        //
        union
        {
            REPARSE_DATA_BUFFER ReparseDataBuffer;
            REPARSE_GUID_DATA_BUFFER ReparseGuidDataBuffer;
        };
    } REPARSE_DATA_BUFFER_EX, * PREPARSE_DATA_BUFFER_EX;

    //  REPARSE_DATA_BUFFER_EX Flags
    //
    //  REPARSE_DATA_EX_FLAG_GIVEN_TAG_OR_NONE - Forces the FSCTL to set the
    //  reparse tag if the file has no tag or the tag on the file is same as
    //  the one in  ExistingReparseTag.   NOTE: If the ExistingReparseTag is
    //  not a Microsoft tag then the ExistingReparseGuid should match if the
    //  file has the ExistingReparseTag.
    //
#define REPARSE_DATA_EX_FLAG_GIVEN_TAG_OR_NONE              (0x00000001)

#define REPARSE_GUID_DATA_BUFFER_EX_HEADER_SIZE \
    UFIELD_OFFSET(REPARSE_DATA_BUFFER_EX, ReparseGuidDataBuffer.GenericReparseBuffer)

#define REPARSE_DATA_BUFFER_EX_HEADER_SIZE \
    UFIELD_OFFSET(REPARSE_DATA_BUFFER_EX, ReparseDataBuffer.GenericReparseBuffer)

#endif // PHNT_REDSTONE

// Named pipe FS control definitions

#define DEVICE_NAMED_PIPE L"\\Device\\NamedPipe\\"

#define FSCTL_PIPE_ASSIGN_EVENT             CTL_CODE(FILE_DEVICE_NAMED_PIPE, 0, METHOD_BUFFERED, FILE_ANY_ACCESS)
#define FSCTL_PIPE_DISCONNECT               CTL_CODE(FILE_DEVICE_NAMED_PIPE, 1, METHOD_BUFFERED, FILE_ANY_ACCESS)
#define FSCTL_PIPE_LISTEN                   CTL_CODE(FILE_DEVICE_NAMED_PIPE, 2, METHOD_BUFFERED, FILE_ANY_ACCESS)
#define FSCTL_PIPE_PEEK                     CTL_CODE(FILE_DEVICE_NAMED_PIPE, 3, METHOD_BUFFERED, FILE_READ_DATA)
#define FSCTL_PIPE_QUERY_EVENT              CTL_CODE(FILE_DEVICE_NAMED_PIPE, 4, METHOD_BUFFERED, FILE_ANY_ACCESS)
#define FSCTL_PIPE_TRANSCEIVE               CTL_CODE(FILE_DEVICE_NAMED_PIPE, 5, METHOD_NEITHER,  FILE_READ_DATA | FILE_WRITE_DATA)
#define FSCTL_PIPE_WAIT                     CTL_CODE(FILE_DEVICE_NAMED_PIPE, 6, METHOD_BUFFERED, FILE_ANY_ACCESS)
#define FSCTL_PIPE_IMPERSONATE              CTL_CODE(FILE_DEVICE_NAMED_PIPE, 7, METHOD_BUFFERED, FILE_ANY_ACCESS)
#define FSCTL_PIPE_SET_CLIENT_PROCESS       CTL_CODE(FILE_DEVICE_NAMED_PIPE, 8, METHOD_BUFFERED, FILE_ANY_ACCESS)
#define FSCTL_PIPE_QUERY_CLIENT_PROCESS     CTL_CODE(FILE_DEVICE_NAMED_PIPE, 9, METHOD_BUFFERED, FILE_ANY_ACCESS)
#define FSCTL_PIPE_GET_PIPE_ATTRIBUTE       CTL_CODE(FILE_DEVICE_NAMED_PIPE, 10, METHOD_BUFFERED, FILE_ANY_ACCESS)
#define FSCTL_PIPE_SET_PIPE_ATTRIBUTE       CTL_CODE(FILE_DEVICE_NAMED_PIPE, 11, METHOD_BUFFERED, FILE_ANY_ACCESS)
#define FSCTL_PIPE_GET_CONNECTION_ATTRIBUTE CTL_CODE(FILE_DEVICE_NAMED_PIPE, 12, METHOD_BUFFERED, FILE_ANY_ACCESS)
#define FSCTL_PIPE_SET_CONNECTION_ATTRIBUTE CTL_CODE(FILE_DEVICE_NAMED_PIPE, 13, METHOD_BUFFERED, FILE_ANY_ACCESS)
#define FSCTL_PIPE_GET_HANDLE_ATTRIBUTE     CTL_CODE(FILE_DEVICE_NAMED_PIPE, 14, METHOD_BUFFERED, FILE_ANY_ACCESS)
#define FSCTL_PIPE_SET_HANDLE_ATTRIBUTE     CTL_CODE(FILE_DEVICE_NAMED_PIPE, 15, METHOD_BUFFERED, FILE_ANY_ACCESS)
#define FSCTL_PIPE_FLUSH                    CTL_CODE(FILE_DEVICE_NAMED_PIPE, 16, METHOD_BUFFERED, FILE_WRITE_DATA)
#define FSCTL_PIPE_DISABLE_IMPERSONATE      CTL_CODE(FILE_DEVICE_NAMED_PIPE, 17, METHOD_BUFFERED, FILE_ANY_ACCESS) // since REDSTONE
#define FSCTL_PIPE_SILO_ARRIVAL             CTL_CODE(FILE_DEVICE_NAMED_PIPE, 18, METHOD_BUFFERED, FILE_WRITE_DATA) // since REDSTONE3
#define FSCTL_PIPE_CREATE_SYMLINK           CTL_CODE(FILE_DEVICE_NAMED_PIPE, 19, METHOD_BUFFERED, FILE_SPECIAL_ACCESS) // requires SeTcbPrivilege
#define FSCTL_PIPE_DELETE_SYMLINK           CTL_CODE(FILE_DEVICE_NAMED_PIPE, 20, METHOD_BUFFERED, FILE_SPECIAL_ACCESS)
#define FSCTL_PIPE_QUERY_CLIENT_PROCESS_V2  CTL_CODE(FILE_DEVICE_NAMED_PIPE, 21, METHOD_BUFFERED, FILE_ANY_ACCESS) // since 19H1

#define FSCTL_PIPE_INTERNAL_READ            CTL_CODE(FILE_DEVICE_NAMED_PIPE, 2045, METHOD_BUFFERED, FILE_READ_DATA)
#define FSCTL_PIPE_INTERNAL_WRITE           CTL_CODE(FILE_DEVICE_NAMED_PIPE, 2046, METHOD_BUFFERED, FILE_WRITE_DATA)
#define FSCTL_PIPE_INTERNAL_TRANSCEIVE      CTL_CODE(FILE_DEVICE_NAMED_PIPE, 2047, METHOD_NEITHER, FILE_READ_DATA | FILE_WRITE_DATA)
#define FSCTL_PIPE_INTERNAL_READ_OVFLOW     CTL_CODE(FILE_DEVICE_NAMED_PIPE, 2048, METHOD_BUFFERED, FILE_READ_DATA)

// Flags for query event

#define FILE_PIPE_READ_DATA 0x00000000
#define FILE_PIPE_WRITE_SPACE 0x00000001

// Input for FSCTL_PIPE_ASSIGN_EVENT
    typedef struct _FILE_PIPE_ASSIGN_EVENT_BUFFER
    {
        HANDLE EventHandle;
        ULONG KeyValue;
    } FILE_PIPE_ASSIGN_EVENT_BUFFER, * PFILE_PIPE_ASSIGN_EVENT_BUFFER;

    // Output for FILE_PIPE_PEEK_BUFFER
    typedef struct _FILE_PIPE_PEEK_BUFFER
    {
        ULONG NamedPipeState;
        ULONG ReadDataAvailable;
        ULONG NumberOfMessages;
        ULONG MessageLength;
        _Field_size_bytes_(MessageLength) CHAR Data[1];
    } FILE_PIPE_PEEK_BUFFER, * PFILE_PIPE_PEEK_BUFFER;

    // Output for FSCTL_PIPE_QUERY_EVENT
    typedef struct _FILE_PIPE_EVENT_BUFFER
    {
        ULONG NamedPipeState;
        ULONG EntryType;
        ULONG ByteCount;
        ULONG KeyValue;
        ULONG NumberRequests;
    } FILE_PIPE_EVENT_BUFFER, * PFILE_PIPE_EVENT_BUFFER;

    // Input for FSCTL_PIPE_WAIT
    typedef struct _FILE_PIPE_WAIT_FOR_BUFFER
    {
        LARGE_INTEGER Timeout;
        ULONG NameLength;
        BOOLEAN TimeoutSpecified;
        _Field_size_bytes_(NameLength) WCHAR Name[1];
    } FILE_PIPE_WAIT_FOR_BUFFER, * PFILE_PIPE_WAIT_FOR_BUFFER;

    // Input for FSCTL_PIPE_SET_CLIENT_PROCESS, Output for FSCTL_PIPE_QUERY_CLIENT_PROCESS
    typedef struct _FILE_PIPE_CLIENT_PROCESS_BUFFER
    {
#if !defined(BUILD_WOW6432)
        PVOID ClientSession;
        PVOID ClientProcess;
#else
        ULONGLONG ClientSession;
        ULONGLONG ClientProcess;
#endif
    } FILE_PIPE_CLIENT_PROCESS_BUFFER, * PFILE_PIPE_CLIENT_PROCESS_BUFFER;

    // Control structure for FSCTL_PIPE_QUERY_CLIENT_PROCESS_V2

    typedef struct _FILE_PIPE_CLIENT_PROCESS_BUFFER_V2
    {
        ULONGLONG ClientSession;
#if !defined(BUILD_WOW6432)
        PVOID ClientProcess;
#else
        ULONGLONG ClientProcess;
#endif
    } FILE_PIPE_CLIENT_PROCESS_BUFFER_V2, * PFILE_PIPE_CLIENT_PROCESS_BUFFER_V2;

#define FILE_PIPE_COMPUTER_NAME_LENGTH 15

    // Input for FSCTL_PIPE_SET_CLIENT_PROCESS, Output for FSCTL_PIPE_QUERY_CLIENT_PROCESS
    typedef struct _FILE_PIPE_CLIENT_PROCESS_BUFFER_EX
    {
#if !defined(BUILD_WOW6432)
        PVOID ClientSession;
        PVOID ClientProcess;
#else
        ULONGLONG ClientSession;
        ULONGLONG ClientProcess;
#endif
        USHORT ClientComputerNameLength; // in bytes
        WCHAR ClientComputerBuffer[FILE_PIPE_COMPUTER_NAME_LENGTH + 1]; // null-terminated
    } FILE_PIPE_CLIENT_PROCESS_BUFFER_EX, * PFILE_PIPE_CLIENT_PROCESS_BUFFER_EX;

    // Control structure for FSCTL_PIPE_SILO_ARRIVAL

    typedef struct _FILE_PIPE_SILO_ARRIVAL_INPUT
    {
        HANDLE JobHandle;
    } FILE_PIPE_SILO_ARRIVAL_INPUT, * PFILE_PIPE_SILO_ARRIVAL_INPUT;

    //
    // Flags for create symlink
    //

    //
    // A global symlink will cause resolution of the symlink's target to occur in
    // the host silo (i.e. not in any current silo).  For example, if there is a
    // symlink at \Device\Silos\37\Device\NamedPipe\symlink then the target will be
    // resolved as \Device\NamedPipe\target instead of \Device\Silos\37\Device\NamedPipe\target
    //
#define FILE_PIPE_SYMLINK_FLAG_GLOBAL   0x1

//
// A relative symlink will cause resolution of the symlink's target to occur relative
// to the root of the named pipe file system.  For example, if there is a symlink at
// \Device\NamedPipe\symlink that has a target called "target", then the target will
// be resolved as \Device\NamedPipe\target
//
#define FILE_PIPE_SYMLINK_FLAG_RELATIVE 0x2

#define FILE_PIPE_SYMLINK_VALID_FLAGS \
    (FILE_PIPE_SYMLINK_FLAG_GLOBAL | FILE_PIPE_SYMLINK_FLAG_RELATIVE)

// Control structure for FSCTL_PIPE_CREATE_SYMLINK

    typedef struct _FILE_PIPE_CREATE_SYMLINK_INPUT
    {
        USHORT NameOffset;
        USHORT NameLength;
        USHORT SubstituteNameOffset;
        USHORT SubstituteNameLength;
        ULONG Flags;
    } FILE_PIPE_CREATE_SYMLINK_INPUT, * PFILE_PIPE_CREATE_SYMLINK_INPUT;

    // Control structure for FSCTL_PIPE_DELETE_SYMLINK

    typedef struct _FILE_PIPE_DELETE_SYMLINK_INPUT
    {
        USHORT NameOffset;
        USHORT NameLength;
    } FILE_PIPE_DELETE_SYMLINK_INPUT, * PFILE_PIPE_DELETE_SYMLINK_INPUT;

    // Mailslot FS control definitions

#define MAILSLOT_CLASS_FIRSTCLASS 1
#define MAILSLOT_CLASS_SECONDCLASS 2

#define FSCTL_MAILSLOT_PEEK             CTL_CODE(FILE_DEVICE_MAILSLOT, 0, METHOD_NEITHER, FILE_READ_DATA)

// Output for FSCTL_MAILSLOT_PEEK
    typedef struct _FILE_MAILSLOT_PEEK_BUFFER
    {
        ULONG ReadDataAvailable;
        ULONG NumberOfMessages;
        ULONG MessageLength;
    } FILE_MAILSLOT_PEEK_BUFFER, * PFILE_MAILSLOT_PEEK_BUFFER;

    // Mount manager FS control definitions

#define MOUNTMGR_DEVICE_NAME L"\\Device\\MountPointManager"
#define MOUNTMGRCONTROLTYPE 0x0000006D // 'm'
#define MOUNTDEVCONTROLTYPE 0x0000004D // 'M'

#define IOCTL_MOUNTMGR_CREATE_POINT                 CTL_CODE(MOUNTMGRCONTROLTYPE, 0, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS)
#define IOCTL_MOUNTMGR_DELETE_POINTS                CTL_CODE(MOUNTMGRCONTROLTYPE, 1, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS)
#define IOCTL_MOUNTMGR_QUERY_POINTS                 CTL_CODE(MOUNTMGRCONTROLTYPE, 2, METHOD_BUFFERED, FILE_ANY_ACCESS)
#define IOCTL_MOUNTMGR_DELETE_POINTS_DBONLY         CTL_CODE(MOUNTMGRCONTROLTYPE, 3, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS)
#define IOCTL_MOUNTMGR_NEXT_DRIVE_LETTER            CTL_CODE(MOUNTMGRCONTROLTYPE, 4, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS)
#define IOCTL_MOUNTMGR_AUTO_DL_ASSIGNMENTS          CTL_CODE(MOUNTMGRCONTROLTYPE, 5, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS)
#define IOCTL_MOUNTMGR_VOLUME_MOUNT_POINT_CREATED   CTL_CODE(MOUNTMGRCONTROLTYPE, 6, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS)
#define IOCTL_MOUNTMGR_VOLUME_MOUNT_POINT_DELETED   CTL_CODE(MOUNTMGRCONTROLTYPE, 7, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS)
#define IOCTL_MOUNTMGR_CHANGE_NOTIFY                CTL_CODE(MOUNTMGRCONTROLTYPE, 8, METHOD_BUFFERED, FILE_READ_ACCESS)
#define IOCTL_MOUNTMGR_KEEP_LINKS_WHEN_OFFLINE      CTL_CODE(MOUNTMGRCONTROLTYPE, 9, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS)
#define IOCTL_MOUNTMGR_CHECK_UNPROCESSED_VOLUMES    CTL_CODE(MOUNTMGRCONTROLTYPE, 10, METHOD_BUFFERED, FILE_READ_ACCESS)
#define IOCTL_MOUNTMGR_VOLUME_ARRIVAL_NOTIFICATION  CTL_CODE(MOUNTMGRCONTROLTYPE, 11, METHOD_BUFFERED, FILE_READ_ACCESS)
#define IOCTL_MOUNTMGR_QUERY_DOS_VOLUME_PATH        CTL_CODE(MOUNTMGRCONTROLTYPE, 12, METHOD_BUFFERED, FILE_ANY_ACCESS)
#define IOCTL_MOUNTMGR_QUERY_DOS_VOLUME_PATHS       CTL_CODE(MOUNTMGRCONTROLTYPE, 13, METHOD_BUFFERED, FILE_ANY_ACCESS)
#define IOCTL_MOUNTMGR_SCRUB_REGISTRY               CTL_CODE(MOUNTMGRCONTROLTYPE, 14, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS)
#define IOCTL_MOUNTMGR_QUERY_AUTO_MOUNT             CTL_CODE(MOUNTMGRCONTROLTYPE, 15, METHOD_BUFFERED, FILE_ANY_ACCESS)
#define IOCTL_MOUNTMGR_SET_AUTO_MOUNT               CTL_CODE(MOUNTMGRCONTROLTYPE, 16, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS)
#define IOCTL_MOUNTMGR_BOOT_DL_ASSIGNMENT           CTL_CODE(MOUNTMGRCONTROLTYPE, 17, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS) // since WIN7
#define IOCTL_MOUNTMGR_TRACELOG_CACHE               CTL_CODE(MOUNTMGRCONTROLTYPE, 18, METHOD_BUFFERED, FILE_READ_ACCESS)
#define IOCTL_MOUNTMGR_PREPARE_VOLUME_DELETE        CTL_CODE(MOUNTMGRCONTROLTYPE, 19, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS)
#define IOCTL_MOUNTMGR_CANCEL_VOLUME_DELETE         CTL_CODE(MOUNTMGRCONTROLTYPE, 20, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS) // since WIN8
#define IOCTL_MOUNTMGR_SILO_ARRIVAL                 CTL_CODE(MOUNTMGRCONTROLTYPE, 21, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS) // since RS1

#define IOCTL_MOUNTDEV_QUERY_DEVICE_NAME            CTL_CODE(MOUNTDEVCONTROLTYPE, 2, METHOD_BUFFERED, FILE_ANY_ACCESS)

// Input structure for IOCTL_MOUNTMGR_CREATE_POINT.
    typedef struct _MOUNTMGR_CREATE_POINT_INPUT
    {
        USHORT SymbolicLinkNameOffset;
        USHORT SymbolicLinkNameLength;
        USHORT DeviceNameOffset;
        USHORT DeviceNameLength;
    } MOUNTMGR_CREATE_POINT_INPUT, * PMOUNTMGR_CREATE_POINT_INPUT;

    // Input structure for IOCTL_MOUNTMGR_DELETE_POINTS, IOCTL_MOUNTMGR_QUERY_POINTS, and IOCTL_MOUNTMGR_DELETE_POINTS_DBONLY.
    typedef struct _MOUNTMGR_MOUNT_POINT
    {
        ULONG SymbolicLinkNameOffset;
        USHORT SymbolicLinkNameLength;
        USHORT Reserved1;
        ULONG UniqueIdOffset;
        USHORT UniqueIdLength;
        USHORT Reserved2;
        ULONG DeviceNameOffset;
        USHORT DeviceNameLength;
        USHORT Reserved3;
    } MOUNTMGR_MOUNT_POINT, * PMOUNTMGR_MOUNT_POINT;

    // Output structure for IOCTL_MOUNTMGR_DELETE_POINTS, IOCTL_MOUNTMGR_QUERY_POINTS, and IOCTL_MOUNTMGR_DELETE_POINTS_DBONLY.
    typedef struct _MOUNTMGR_MOUNT_POINTS
    {
        ULONG Size;
        ULONG NumberOfMountPoints;
        _Field_size_(NumberOfMountPoints) MOUNTMGR_MOUNT_POINT MountPoints[1];
    } MOUNTMGR_MOUNT_POINTS, * PMOUNTMGR_MOUNT_POINTS;

    // Input structure for IOCTL_MOUNTMGR_NEXT_DRIVE_LETTER.
    typedef struct _MOUNTMGR_DRIVE_LETTER_TARGET
    {
        USHORT DeviceNameLength;
        _Field_size_bytes_(DeviceNameLength) WCHAR DeviceName[1];
    } MOUNTMGR_DRIVE_LETTER_TARGET, * PMOUNTMGR_DRIVE_LETTER_TARGET;

    // Output structure for IOCTL_MOUNTMGR_NEXT_DRIVE_LETTER.
    typedef struct _MOUNTMGR_DRIVE_LETTER_INFORMATION
    {
        BOOLEAN DriveLetterWasAssigned;
        UCHAR CurrentDriveLetter;
    } MOUNTMGR_DRIVE_LETTER_INFORMATION, * PMOUNTMGR_DRIVE_LETTER_INFORMATION;

    // Input structure for IOCTL_MOUNTMGR_VOLUME_MOUNT_POINT_CREATED and
    // IOCTL_MOUNTMGR_VOLUME_MOUNT_POINT_DELETED.
    typedef struct _MOUNTMGR_VOLUME_MOUNT_POINT
    {
        USHORT SourceVolumeNameOffset;
        USHORT SourceVolumeNameLength;
        USHORT TargetVolumeNameOffset;
        USHORT TargetVolumeNameLength;
    } MOUNTMGR_VOLUME_MOUNT_POINT, * PMOUNTMGR_VOLUME_MOUNT_POINT;

    // Input structure for IOCTL_MOUNTMGR_CHANGE_NOTIFY.
    // Output structure for IOCTL_MOUNTMGR_CHANGE_NOTIFY.
    typedef struct _MOUNTMGR_CHANGE_NOTIFY_INFO
    {
        ULONG EpicNumber;
    } MOUNTMGR_CHANGE_NOTIFY_INFO, * PMOUNTMGR_CHANGE_NOTIFY_INFO;

    // Input structure for IOCTL_MOUNTMGR_KEEP_LINKS_WHEN_OFFLINE,
    // IOCTL_MOUNTMGR_VOLUME_ARRIVAL_NOTIFICATION,
    // IOCTL_MOUNTMGR_QUERY_DOS_VOLUME_PATH, and
    // IOCTL_MOUNTMGR_QUERY_DOS_VOLUME_PATHS.
    // IOCTL_MOUNTMGR_PREPARE_VOLUME_DELETE
    // IOCTL_MOUNTMGR_CANCEL_VOLUME_DELETE
    typedef struct _MOUNTMGR_TARGET_NAME
    {
        USHORT DeviceNameLength;
        _Field_size_bytes_(DeviceNameLength) WCHAR DeviceName[1];
    } MOUNTMGR_TARGET_NAME, * PMOUNTMGR_TARGET_NAME;

    // Input / Output structure for querying / setting the auto-mount setting
    typedef enum _MOUNTMGR_AUTO_MOUNT_STATE
    {
        Disabled = 0,
        Enabled
    } MOUNTMGR_AUTO_MOUNT_STATE;

    // IOCTL_MOUNTMGR_QUERY_AUTO_MOUNT
    typedef struct _MOUNTMGR_QUERY_AUTO_MOUNT
    {
        MOUNTMGR_AUTO_MOUNT_STATE CurrentState;
    } MOUNTMGR_QUERY_AUTO_MOUNT, * PMOUNTMGR_QUERY_AUTO_MOUNT;

    // IOCTL_MOUNTMGR_SET_AUTO_MOUNT
    typedef struct _MOUNTMGR_SET_AUTO_MOUNT
    {
        MOUNTMGR_AUTO_MOUNT_STATE NewState;
    } MOUNTMGR_SET_AUTO_MOUNT, * PMOUNTMGR_SET_AUTO_MOUNT;

    // Input structure for IOCTL_MOUNTMGR_SILO_ARRIVAL.
    typedef struct _MOUNTMGR_SILO_ARRIVAL_INPUT
    {
        HANDLE JobHandle;
    } MOUNTMGR_SILO_ARRIVAL_INPUT, * PMOUNTMGR_SILO_ARRIVAL_INPUT;

    // Macro that defines what a "drive letter" mount point is.  This macro can
    // be used to scan the result from QUERY_POINTS to discover which mount points
    // are find "drive letter" mount points.
#define MOUNTMGR_IS_DRIVE_LETTER(s) ( \
    (s)->Length == 28 && \
    (s)->Buffer[0] == '\\' && \
    (s)->Buffer[1] == 'D' && \
    (s)->Buffer[2] == 'o' && \
    (s)->Buffer[3] == 's' && \
    (s)->Buffer[4] == 'D' && \
    (s)->Buffer[5] == 'e' && \
    (s)->Buffer[6] == 'v' && \
    (s)->Buffer[7] == 'i' && \
    (s)->Buffer[8] == 'c' && \
    (s)->Buffer[9] == 'e' && \
    (s)->Buffer[10] == 's' && \
    (s)->Buffer[11] == '\\' && \
    (s)->Buffer[12] >= 'A' && \
    (s)->Buffer[12] <= 'Z' && \
    (s)->Buffer[13] == ':')

// Macro that defines what a "volume name" mount point is.  This macro can
// be used to scan the result from QUERY_POINTS to discover which mount points
// are "volume name" mount points.
#define MOUNTMGR_IS_VOLUME_NAME(s) ( \
     ((s)->Length == 96 || ((s)->Length == 98 && (s)->Buffer[48] == '\\')) && \
     (s)->Buffer[0] == '\\' && \
     ((s)->Buffer[1] == '?' || (s)->Buffer[1] == '\\') && \
     (s)->Buffer[2] == '?' && \
     (s)->Buffer[3] == '\\' && \
     (s)->Buffer[4] == 'V' && \
     (s)->Buffer[5] == 'o' && \
     (s)->Buffer[6] == 'l' && \
     (s)->Buffer[7] == 'u' && \
     (s)->Buffer[8] == 'm' && \
     (s)->Buffer[9] == 'e' && \
     (s)->Buffer[10] == '{' && \
     (s)->Buffer[19] == '-' && \
     (s)->Buffer[24] == '-' && \
     (s)->Buffer[29] == '-' && \
     (s)->Buffer[34] == '-' && \
     (s)->Buffer[47] == '}')

// Output structure for IOCTL_MOUNTDEV_QUERY_DEVICE_NAME.
    typedef struct _MOUNTDEV_NAME
    {
        USHORT NameLength;
        _Field_size_bytes_(NameLength) WCHAR Name[1];
    } MOUNTDEV_NAME, * PMOUNTDEV_NAME;

    // Output structure for IOCTL_MOUNTMGR_QUERY_DOS_VOLUME_PATH and IOCTL_MOUNTMGR_QUERY_DOS_VOLUME_PATHS.
    typedef struct _MOUNTMGR_VOLUME_PATHS
    {
        ULONG MultiSzLength;
        _Field_size_bytes_(MultiSzLength) WCHAR MultiSz[1];
    } MOUNTMGR_VOLUME_PATHS, * PMOUNTMGR_VOLUME_PATHS;

#define MOUNTMGR_IS_DOS_VOLUME_NAME(s) ( \
     MOUNTMGR_IS_VOLUME_NAME(s) && \
     (s)->Length == 96 && \
     (s)->Buffer[1] == '\\')

#define MOUNTMGR_IS_DOS_VOLUME_NAME_WB(s) ( \
     MOUNTMGR_IS_VOLUME_NAME(s) && \
     (s)->Length == 98 && \
     (s)->Buffer[1] == '\\')

#define MOUNTMGR_IS_NT_VOLUME_NAME(s) ( \
     MOUNTMGR_IS_VOLUME_NAME(s) && \
     (s)->Length == 96 && \
     (s)->Buffer[1] == '?')

#define MOUNTMGR_IS_NT_VOLUME_NAME_WB(s) ( \
     MOUNTMGR_IS_VOLUME_NAME(s) && \
     (s)->Length == 98 && \
     (s)->Buffer[1] == '?')

#if (PHNT_MODE != PHNT_MODE_KERNEL)
    // File Object
#define FO_FILE_OPEN                    0x00000001
#define FO_SYNCHRONOUS_IO               0x00000002
#define FO_ALERTABLE_IO                 0x00000004
#define FO_NO_INTERMEDIATE_BUFFERING    0x00000008
#define FO_WRITE_THROUGH                0x00000010
#define FO_SEQUENTIAL_ONLY              0x00000020
#define FO_CACHE_SUPPORTED              0x00000040
#define FO_NAMED_PIPE                   0x00000080
#define FO_STREAM_FILE                  0x00000100
#define FO_MAILSLOT                     0x00000200
#define FO_GENERATE_AUDIT_ON_CLOSE      0x00000400
#define FO_QUEUE_IRP_TO_THREAD          FO_GENERATE_AUDIT_ON_CLOSE
#define FO_DIRECT_DEVICE_OPEN           0x00000800
#define FO_FILE_MODIFIED                0x00001000
#define FO_FILE_SIZE_CHANGED            0x00002000
#define FO_CLEANUP_COMPLETE             0x00004000
#define FO_TEMPORARY_FILE               0x00008000
#define FO_DELETE_ON_CLOSE              0x00010000
#define FO_OPENED_CASE_SENSITIVE        0x00020000
#define FO_HANDLE_CREATED               0x00040000
#define FO_FILE_FAST_IO_READ            0x00080000
#define FO_RANDOM_ACCESS                0x00100000
#define FO_FILE_OPEN_CANCELLED          0x00200000
#define FO_VOLUME_OPEN                  0x00400000
#define FO_BYPASS_IO_ENABLED            0x00800000  //when set BYPASS IO is enabled on this handle
#define FO_REMOTE_ORIGIN                0x01000000
#define FO_DISALLOW_EXCLUSIVE           0x02000000
#define FO_SKIP_COMPLETION_PORT         FO_DISALLOW_EXCLUSIVE
#define FO_SKIP_SET_EVENT               0x04000000
#define FO_SKIP_SET_FAST_IO             0x08000000
#define FO_INDIRECT_WAIT_OBJECT         0x10000000
#define FO_SECTION_MINSTORE_TREATMENT   0x20000000

//
// Define Device Object (DO) flags
//
// DO_DAX_VOLUME - If set, this is a DAX volume i.e. the volume supports mapping a file directly
// on the persistent memory device.  The cached and memory mapped IO to user files wouldn't
// generate paging IO.
//
#define DO_VERIFY_VOLUME                    0x00000002
#define DO_BUFFERED_IO                      0x00000004
#define DO_EXCLUSIVE                        0x00000008
#define DO_DIRECT_IO                        0x00000010
#define DO_MAP_IO_BUFFER                    0x00000020
#define DO_DEVICE_INITIALIZING              0x00000080
#define DO_SHUTDOWN_REGISTERED              0x00000800
#define DO_BUS_ENUMERATED_DEVICE            0x00001000
#define DO_POWER_PAGABLE                    0x00002000
#define DO_POWER_INRUSH                     0x00004000
#define DO_DEVICE_TO_BE_RESET               0x04000000
#define DO_DAX_VOLUME                       0x10000000
#endif // (PHNT_MODE != PHNT_MODE_KERNEL)

// KSecDD FS control definitions

#define KSEC_DEVICE_NAME L"\\Device\\KSecDD"

#define IOCTL_KSEC_CONNECT_LSA                      CTL_CODE(FILE_DEVICE_KSEC,  0, METHOD_BUFFERED,     FILE_WRITE_ACCESS )
#define IOCTL_KSEC_RNG                              CTL_CODE(FILE_DEVICE_KSEC,  1, METHOD_BUFFERED,     FILE_ANY_ACCESS )
#define IOCTL_KSEC_RNG_REKEY                        CTL_CODE(FILE_DEVICE_KSEC,  2, METHOD_BUFFERED,     FILE_ANY_ACCESS )
#define IOCTL_KSEC_ENCRYPT_MEMORY                   CTL_CODE(FILE_DEVICE_KSEC,  3, METHOD_OUT_DIRECT,   FILE_ANY_ACCESS )
#define IOCTL_KSEC_DECRYPT_MEMORY                   CTL_CODE(FILE_DEVICE_KSEC,  4, METHOD_OUT_DIRECT,   FILE_ANY_ACCESS )
#define IOCTL_KSEC_ENCRYPT_MEMORY_CROSS_PROC        CTL_CODE(FILE_DEVICE_KSEC,  5, METHOD_OUT_DIRECT,   FILE_ANY_ACCESS )
#define IOCTL_KSEC_DECRYPT_MEMORY_CROSS_PROC        CTL_CODE(FILE_DEVICE_KSEC,  6, METHOD_OUT_DIRECT,   FILE_ANY_ACCESS )
#define IOCTL_KSEC_ENCRYPT_MEMORY_SAME_LOGON        CTL_CODE(FILE_DEVICE_KSEC,  7, METHOD_OUT_DIRECT,   FILE_ANY_ACCESS )
#define IOCTL_KSEC_DECRYPT_MEMORY_SAME_LOGON        CTL_CODE(FILE_DEVICE_KSEC,  8, METHOD_OUT_DIRECT,   FILE_ANY_ACCESS )
#define IOCTL_KSEC_FIPS_GET_FUNCTION_TABLE          CTL_CODE(FILE_DEVICE_KSEC,  9, METHOD_BUFFERED,     FILE_ANY_ACCESS )
#define IOCTL_KSEC_ALLOC_POOL                       CTL_CODE(FILE_DEVICE_KSEC, 10, METHOD_BUFFERED,     FILE_ANY_ACCESS )
#define IOCTL_KSEC_FREE_POOL                        CTL_CODE(FILE_DEVICE_KSEC, 11, METHOD_BUFFERED,     FILE_ANY_ACCESS )
#define IOCTL_KSEC_COPY_POOL                        CTL_CODE(FILE_DEVICE_KSEC, 12, METHOD_BUFFERED,     FILE_ANY_ACCESS )
#define IOCTL_KSEC_DUPLICATE_HANDLE                 CTL_CODE(FILE_DEVICE_KSEC, 13, METHOD_BUFFERED,     FILE_ANY_ACCESS )
#define IOCTL_KSEC_REGISTER_EXTENSION               CTL_CODE(FILE_DEVICE_KSEC, 14, METHOD_BUFFERED,     FILE_ANY_ACCESS )
#define IOCTL_KSEC_CLIENT_CALLBACK                  CTL_CODE(FILE_DEVICE_KSEC, 15, METHOD_BUFFERED,     FILE_ANY_ACCESS )
#define IOCTL_KSEC_GET_BCRYPT_EXTENSION             CTL_CODE(FILE_DEVICE_KSEC, 16, METHOD_BUFFERED,     FILE_ANY_ACCESS )
#define IOCTL_KSEC_GET_SSL_EXTENSION                CTL_CODE(FILE_DEVICE_KSEC, 17, METHOD_BUFFERED,     FILE_ANY_ACCESS )
#define IOCTL_KSEC_GET_DEVICECONTROL_EXTENSION      CTL_CODE(FILE_DEVICE_KSEC, 18, METHOD_BUFFERED,     FILE_ANY_ACCESS )
#define IOCTL_KSEC_ALLOC_VM                         CTL_CODE(FILE_DEVICE_KSEC, 19, METHOD_BUFFERED,     FILE_ANY_ACCESS )
#define IOCTL_KSEC_FREE_VM                          CTL_CODE(FILE_DEVICE_KSEC, 20, METHOD_BUFFERED,     FILE_ANY_ACCESS )
#define IOCTL_KSEC_COPY_VM                          CTL_CODE(FILE_DEVICE_KSEC, 21, METHOD_BUFFERED,     FILE_ANY_ACCESS )
#define IOCTL_KSEC_CLIENT_FREE_VM                   CTL_CODE(FILE_DEVICE_KSEC, 22, METHOD_BUFFERED,     FILE_ANY_ACCESS )
#define IOCTL_KSEC_INSERT_PROTECTED_PROCESS_ADDRESS CTL_CODE(FILE_DEVICE_KSEC, 23, METHOD_BUFFERED,     FILE_ANY_ACCESS )
#define IOCTL_KSEC_REMOVE_PROTECTED_PROCESS_ADDRESS CTL_CODE(FILE_DEVICE_KSEC, 24, METHOD_BUFFERED,     FILE_ANY_ACCESS )
#define IOCTL_KSEC_GET_BCRYPT_EXTENSION2            CTL_CODE(FILE_DEVICE_KSEC, 25, METHOD_BUFFERED,     FILE_ANY_ACCESS )
#define IOCTL_KSEC_IPC_GET_QUEUED_FUNCTION_CALLS    CTL_CODE(FILE_DEVICE_KSEC, 26, METHOD_OUT_DIRECT,   FILE_ANY_ACCESS)
#define IOCTL_KSEC_IPC_SET_FUNCTION_RETURN          CTL_CODE(FILE_DEVICE_KSEC, 27, METHOD_NEITHER,      FILE_ANY_ACCESS)

#endif
/*
 * Local Inter-process Communication support functions
 *
 * This file is part of System Informer.
 */

#ifndef _NTLPCAPI_H
#define _NTLPCAPI_H

#define PORT_CONNECT 0x0001
#define PORT_ALL_ACCESS (STANDARD_RIGHTS_REQUIRED | SYNCHRONIZE | 0x1)

    typedef struct _PORT_MESSAGE
    {
        union
        {
            struct
            {
                CSHORT DataLength;
                CSHORT TotalLength;
            } s1;
            ULONG Length;
        } u1;
        union
        {
            struct
            {
                CSHORT Type;
                CSHORT DataInfoOffset;
            } s2;
            ULONG ZeroInit;
        } u2;
        union
        {
            CLIENT_ID ClientId;
            double DoNotUseThisField;
        };
        ULONG MessageId;
        union
        {
            SIZE_T ClientViewSize; // only valid for LPC_CONNECTION_REQUEST messages
            ULONG CallbackId; // only valid for LPC_REQUEST messages
        };
    } PORT_MESSAGE, * PPORT_MESSAGE;

    typedef struct _PORT_DATA_ENTRY
    {
        PVOID Base;
        ULONG Size;
    } PORT_DATA_ENTRY, * PPORT_DATA_ENTRY;

    typedef struct _PORT_DATA_INFORMATION
    {
        ULONG CountDataEntries;
        _Field_size_(CountDataEntries) PORT_DATA_ENTRY DataEntries[1];
    } PORT_DATA_INFORMATION, * PPORT_DATA_INFORMATION;

#define LPC_REQUEST 1
#define LPC_REPLY 2
#define LPC_DATAGRAM 3
#define LPC_LOST_REPLY 4
#define LPC_PORT_CLOSED 5
#define LPC_CLIENT_DIED 6
#define LPC_EXCEPTION 7
#define LPC_DEBUG_EVENT 8
#define LPC_ERROR_EVENT 9
#define LPC_CONNECTION_REQUEST 10

#define LPC_KERNELMODE_MESSAGE (CSHORT)0x8000
#define LPC_NO_IMPERSONATE (CSHORT)0x4000

#define PORT_VALID_OBJECT_ATTRIBUTES OBJ_CASE_INSENSITIVE

#ifdef _WIN64
#define PORT_MAXIMUM_MESSAGE_LENGTH 512
#else
#define PORT_MAXIMUM_MESSAGE_LENGTH 256
#endif

#define LPC_MAX_CONNECTION_INFO_SIZE (16 * sizeof(ULONG_PTR))

#define PORT_TOTAL_MAXIMUM_MESSAGE_LENGTH \
    ((PORT_MAXIMUM_MESSAGE_LENGTH + sizeof(PORT_MESSAGE) + LPC_MAX_CONNECTION_INFO_SIZE + 0xf) & ~0xf)

    typedef struct _LPC_CLIENT_DIED_MSG
    {
        PORT_MESSAGE PortMsg;
        LARGE_INTEGER CreateTime;
    } LPC_CLIENT_DIED_MSG, * PLPC_CLIENT_DIED_MSG;

    typedef struct _PORT_VIEW
    {
        ULONG Length;
        HANDLE SectionHandle;
        ULONG SectionOffset;
        SIZE_T ViewSize;
        PVOID ViewBase;
        PVOID ViewRemoteBase;
    } PORT_VIEW, * PPORT_VIEW;

    typedef struct _REMOTE_PORT_VIEW
    {
        ULONG Length;
        SIZE_T ViewSize;
        PVOID ViewBase;
    } REMOTE_PORT_VIEW, * PREMOTE_PORT_VIEW;

    // WOW64 definitions

    // Except in a small number of special cases, WOW64 programs using the LPC APIs must use the 64-bit versions of the
    // PORT_MESSAGE, PORT_VIEW and REMOTE_PORT_VIEW data structures. Note that we take a different approach than the
    // official NT headers, which produce 64-bit versions in a 32-bit environment when USE_LPC6432 is defined.

    typedef struct _PORT_MESSAGE64
    {
        union
        {
            struct
            {
                CSHORT DataLength;
                CSHORT TotalLength;
            } s1;
            ULONG Length;
        } u1;
        union
        {
            struct
            {
                CSHORT Type;
                CSHORT DataInfoOffset;
            } s2;
            ULONG ZeroInit;
        } u2;
        union
        {
            CLIENT_ID64 ClientId;
            double DoNotUseThisField;
        };
        ULONG MessageId;
        union
        {
            ULONGLONG ClientViewSize; // only valid for LPC_CONNECTION_REQUEST messages
            ULONG CallbackId; // only valid for LPC_REQUEST messages
        };
    } PORT_MESSAGE64, * PPORT_MESSAGE64;

    typedef struct _LPC_CLIENT_DIED_MSG64
    {
        PORT_MESSAGE64 PortMsg;
        LARGE_INTEGER CreateTime;
    } LPC_CLIENT_DIED_MSG64, * PLPC_CLIENT_DIED_MSG64;

    typedef struct _PORT_VIEW64
    {
        ULONG Length;
        ULONGLONG SectionHandle;
        ULONG SectionOffset;
        ULONGLONG ViewSize;
        ULONGLONG ViewBase;
        ULONGLONG ViewRemoteBase;
    } PORT_VIEW64, * PPORT_VIEW64;

    typedef struct _REMOTE_PORT_VIEW64
    {
        ULONG Length;
        ULONGLONG ViewSize;
        ULONGLONG ViewBase;
    } REMOTE_PORT_VIEW64, * PREMOTE_PORT_VIEW64;

    // Port creation

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtCreatePort(
            _Out_ PHANDLE PortHandle,
            _In_opt_ POBJECT_ATTRIBUTES ObjectAttributes,
            _In_ ULONG MaxConnectionInfoLength,
            _In_ ULONG MaxMessageLength,
            _In_opt_ ULONG MaxPoolUsage
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtCreateWaitablePort(
            _Out_ PHANDLE PortHandle,
            _In_opt_ POBJECT_ATTRIBUTES ObjectAttributes,
            _In_ ULONG MaxConnectionInfoLength,
            _In_ ULONG MaxMessageLength,
            _In_opt_ ULONG MaxPoolUsage
        );

    // Port connection (client)

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtConnectPort(
            _Out_ PHANDLE PortHandle,
            _In_ PUNICODE_STRING PortName,
            _In_ PSECURITY_QUALITY_OF_SERVICE SecurityQos,
            _Inout_opt_ PPORT_VIEW ClientView,
            _Inout_opt_ PREMOTE_PORT_VIEW ServerView,
            _Out_opt_ PULONG MaxMessageLength,
            _Inout_updates_bytes_to_opt_(*ConnectionInformationLength, *ConnectionInformationLength) PVOID ConnectionInformation,
            _Inout_opt_ PULONG ConnectionInformationLength
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtSecureConnectPort(
            _Out_ PHANDLE PortHandle,
            _In_ PUNICODE_STRING PortName,
            _In_ PSECURITY_QUALITY_OF_SERVICE SecurityQos,
            _Inout_opt_ PPORT_VIEW ClientView,
            _In_opt_ PSID RequiredServerSid,
            _Inout_opt_ PREMOTE_PORT_VIEW ServerView,
            _Out_opt_ PULONG MaxMessageLength,
            _Inout_updates_bytes_to_opt_(*ConnectionInformationLength, *ConnectionInformationLength) PVOID ConnectionInformation,
            _Inout_opt_ PULONG ConnectionInformationLength
        );

    // Port connection (server)

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtListenPort(
            _In_ HANDLE PortHandle,
            _Out_ PPORT_MESSAGE ConnectionRequest
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtAcceptConnectPort(
            _Out_ PHANDLE PortHandle,
            _In_opt_ PVOID PortContext,
            _In_ PPORT_MESSAGE ConnectionRequest,
            _In_ BOOLEAN AcceptConnection,
            _Inout_opt_ PPORT_VIEW ServerView,
            _Out_opt_ PREMOTE_PORT_VIEW ClientView
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtCompleteConnectPort(
            _In_ HANDLE PortHandle
        );

    // General

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtRequestPort(
            _In_ HANDLE PortHandle,
            _In_reads_bytes_(RequestMessage->u1.s1.TotalLength) PPORT_MESSAGE RequestMessage
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtRequestWaitReplyPort(
            _In_ HANDLE PortHandle,
            _In_reads_bytes_(RequestMessage->u1.s1.TotalLength) PPORT_MESSAGE RequestMessage,
            _Out_ PPORT_MESSAGE ReplyMessage
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtReplyPort(
            _In_ HANDLE PortHandle,
            _In_reads_bytes_(ReplyMessage->u1.s1.TotalLength) PPORT_MESSAGE ReplyMessage
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtReplyWaitReplyPort(
            _In_ HANDLE PortHandle,
            _Inout_ PPORT_MESSAGE ReplyMessage
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtReplyWaitReceivePort(
            _In_ HANDLE PortHandle,
            _Out_opt_ PVOID* PortContext,
            _In_reads_bytes_opt_(ReplyMessage->u1.s1.TotalLength) PPORT_MESSAGE ReplyMessage,
            _Out_ PPORT_MESSAGE ReceiveMessage
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtReplyWaitReceivePortEx(
            _In_ HANDLE PortHandle,
            _Out_opt_ PVOID* PortContext,
            _In_reads_bytes_opt_(ReplyMessage->u1.s1.TotalLength) PPORT_MESSAGE ReplyMessage,
            _Out_ PPORT_MESSAGE ReceiveMessage,
            _In_opt_ PLARGE_INTEGER Timeout
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtImpersonateClientOfPort(
            _In_ HANDLE PortHandle,
            _In_ PPORT_MESSAGE Message
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtReadRequestData(
            _In_ HANDLE PortHandle,
            _In_ PPORT_MESSAGE Message,
            _In_ ULONG DataEntryIndex,
            _Out_writes_bytes_to_(BufferSize, *NumberOfBytesRead) PVOID Buffer,
            _In_ SIZE_T BufferSize,
            _Out_opt_ PSIZE_T NumberOfBytesRead
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtWriteRequestData(
            _In_ HANDLE PortHandle,
            _In_ PPORT_MESSAGE Message,
            _In_ ULONG DataEntryIndex,
            _In_reads_bytes_(BufferSize) PVOID Buffer,
            _In_ SIZE_T BufferSize,
            _Out_opt_ PSIZE_T NumberOfBytesWritten
        );

    typedef enum _PORT_INFORMATION_CLASS
    {
        PortBasicInformation,
        PortDumpInformation
    } PORT_INFORMATION_CLASS;

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtQueryInformationPort(
            _In_ HANDLE PortHandle,
            _In_ PORT_INFORMATION_CLASS PortInformationClass,
            _Out_writes_bytes_to_(Length, *ReturnLength) PVOID PortInformation,
            _In_ ULONG Length,
            _Out_opt_ PULONG ReturnLength
        );

    // Asynchronous Local Inter-process Communication

    // rev
    typedef HANDLE ALPC_HANDLE, * PALPC_HANDLE;

#define ALPC_PORFLG_LPC_MODE 0x1000 // kernel only
#define ALPC_PORFLG_ALLOW_IMPERSONATION 0x10000
#define ALPC_PORFLG_ALLOW_LPC_REQUESTS 0x20000 // rev
#define ALPC_PORFLG_WAITABLE_PORT 0x40000 // dbg
#define ALPC_PORFLG_ALLOW_DUP_OBJECT 0x80000
#define ALPC_PORFLG_SYSTEM_PROCESS 0x100000 // dbg
#define ALPC_PORFLG_WAKE_POLICY1 0x200000
#define ALPC_PORFLG_WAKE_POLICY2 0x400000
#define ALPC_PORFLG_WAKE_POLICY3 0x800000
#define ALPC_PORFLG_DIRECT_MESSAGE 0x1000000
#define ALPC_PORFLG_ALLOW_MULTIHANDLE_ATTRIBUTE 0x2000000

#define ALPC_PORFLG_OBJECT_TYPE_FILE 0x0001
#define ALPC_PORFLG_OBJECT_TYPE_INVALID 0x0002
#define ALPC_PORFLG_OBJECT_TYPE_THREAD 0x0004
#define ALPC_PORFLG_OBJECT_TYPE_SEMAPHORE 0x0008
#define ALPC_PORFLG_OBJECT_TYPE_EVENT 0x0010
#define ALPC_PORFLG_OBJECT_TYPE_PROCESS 0X0020
#define ALPC_PORFLG_OBJECT_TYPE_MUTEX 0x0040
#define ALPC_PORFLG_OBJECT_TYPE_SECTION 0x0080
#define ALPC_PORFLG_OBJECT_TYPE_REGKEY 0x0100
#define ALPC_PORFLG_OBJECT_TYPE_TOKEN 0x0200
#define ALPC_PORFLG_OBJECT_TYPE_COMPOSITION 0x0400
#define ALPC_PORFLG_OBJECT_TYPE_JOB 0x0800
#define ALPC_PORFLG_OBJECT_TYPE_ALL \
    (ALPC_PORFLG_OBJECT_TYPE_FILE | ALPC_PORFLG_OBJECT_TYPE_THREAD | \
     ALPC_PORFLG_OBJECT_TYPE_SEMAPHORE | ALPC_PORFLG_OBJECT_TYPE_EVENT | \
     ALPC_PORFLG_OBJECT_TYPE_PROCESS | ALPC_PORFLG_OBJECT_TYPE_MUTEX | \
     ALPC_PORFLG_OBJECT_TYPE_SECTION | ALPC_PORFLG_OBJECT_TYPE_REGKEY | \
     ALPC_PORFLG_OBJECT_TYPE_TOKEN | ALPC_PORFLG_OBJECT_TYPE_COMPOSITION | \
     ALPC_PORFLG_OBJECT_TYPE_JOB)

    // symbols
    typedef struct _ALPC_PORT_ATTRIBUTES
    {
        ULONG Flags;
        SECURITY_QUALITY_OF_SERVICE SecurityQos;
        SIZE_T MaxMessageLength;
        SIZE_T MemoryBandwidth;
        SIZE_T MaxPoolUsage;
        SIZE_T MaxSectionSize;
        SIZE_T MaxViewSize;
        SIZE_T MaxTotalSectionSize;
        ULONG DupObjectTypes;
#ifdef _WIN64
        ULONG Reserved;
#endif
    } ALPC_PORT_ATTRIBUTES, * PALPC_PORT_ATTRIBUTES;

    // begin_rev
#define ALPC_MESSAGE_SECURITY_ATTRIBUTE 0x80000000
#define ALPC_MESSAGE_VIEW_ATTRIBUTE 0x40000000
#define ALPC_MESSAGE_CONTEXT_ATTRIBUTE 0x20000000
#define ALPC_MESSAGE_HANDLE_ATTRIBUTE 0x10000000
// end_rev

// symbols
    typedef struct _ALPC_MESSAGE_ATTRIBUTES
    {
        ULONG AllocatedAttributes;
        ULONG ValidAttributes;
    } ALPC_MESSAGE_ATTRIBUTES, * PALPC_MESSAGE_ATTRIBUTES;

    // symbols
    typedef struct _ALPC_COMPLETION_LIST_STATE
    {
        union
        {
            struct
            {
                ULONG64 Head : 24;
                ULONG64 Tail : 24;
                ULONG64 ActiveThreadCount : 16;
            } s1;
            ULONG64 Value;
        } u1;
    } ALPC_COMPLETION_LIST_STATE, * PALPC_COMPLETION_LIST_STATE;

#define ALPC_COMPLETION_LIST_BUFFER_GRANULARITY_MASK 0x3f // dbg

    // symbols
    typedef struct DECLSPEC_ALIGN(128) _ALPC_COMPLETION_LIST_HEADER
    {
        ULONG64 StartMagic;

        ULONG TotalSize;
        ULONG ListOffset;
        ULONG ListSize;
        ULONG BitmapOffset;
        ULONG BitmapSize;
        ULONG DataOffset;
        ULONG DataSize;
        ULONG AttributeFlags;
        ULONG AttributeSize;

        DECLSPEC_ALIGN(128) ALPC_COMPLETION_LIST_STATE State;
        ULONG LastMessageId;
        ULONG LastCallbackId;
        DECLSPEC_ALIGN(128) ULONG PostCount;
        DECLSPEC_ALIGN(128) ULONG ReturnCount;
        DECLSPEC_ALIGN(128) ULONG LogSequenceNumber;
        DECLSPEC_ALIGN(128) RTL_SRWLOCK UserLock;

        ULONG64 EndMagic;
    } ALPC_COMPLETION_LIST_HEADER, * PALPC_COMPLETION_LIST_HEADER;

    // private
    typedef struct _ALPC_CONTEXT_ATTR
    {
        PVOID PortContext;
        PVOID MessageContext;
        ULONG Sequence;
        ULONG MessageId;
        ULONG CallbackId;
    } ALPC_CONTEXT_ATTR, * PALPC_CONTEXT_ATTR;

    // begin_rev
#define ALPC_HANDLEFLG_DUPLICATE_SAME_ACCESS 0x10000
#define ALPC_HANDLEFLG_DUPLICATE_SAME_ATTRIBUTES 0x20000
#define ALPC_HANDLEFLG_DUPLICATE_INHERIT 0x80000
// end_rev

// private
    typedef struct _ALPC_HANDLE_ATTR32
    {
        ULONG Flags;
        ULONG Reserved0;
        ULONG SameAccess;
        ULONG SameAttributes;
        ULONG Indirect;
        ULONG Inherit;
        ULONG Reserved1;
        ULONG Handle;
        ULONG ObjectType; // ObjectTypeCode, not ObjectTypeIndex
        ULONG DesiredAccess;
        ULONG GrantedAccess;
    } ALPC_HANDLE_ATTR32, * PALPC_HANDLE_ATTR32;

    // private
    typedef struct _ALPC_HANDLE_ATTR
    {
        ULONG Flags;
        ULONG Reserved0;
        ULONG SameAccess;
        ULONG SameAttributes;
        ULONG Indirect;
        ULONG Inherit;
        ULONG Reserved1;
        HANDLE Handle;
        PALPC_HANDLE_ATTR32 HandleAttrArray;
        ULONG ObjectType; // ObjectTypeCode, not ObjectTypeIndex
        ULONG HandleCount;
        ACCESS_MASK DesiredAccess;
        ACCESS_MASK GrantedAccess;
    } ALPC_HANDLE_ATTR, * PALPC_HANDLE_ATTR;

#define ALPC_SECFLG_CREATE_HANDLE 0x20000 // dbg
#define ALPC_SECFLG_NOSECTIONHANDLE 0x40000

    // private
    typedef struct _ALPC_SECURITY_ATTR
    {
        ULONG Flags;
        PSECURITY_QUALITY_OF_SERVICE QoS;
        ALPC_HANDLE ContextHandle; // dbg
    } ALPC_SECURITY_ATTR, * PALPC_SECURITY_ATTR;

    // begin_rev
#define ALPC_VIEWFLG_NOT_SECURE 0x40000
// end_rev

// private
    typedef struct _ALPC_DATA_VIEW_ATTR
    {
        ULONG Flags;
        ALPC_HANDLE SectionHandle;
        PVOID ViewBase; // must be zero on input
        SIZE_T ViewSize;
    } ALPC_DATA_VIEW_ATTR, * PALPC_DATA_VIEW_ATTR;

    // private
    typedef enum _ALPC_PORT_INFORMATION_CLASS
    {
        AlpcBasicInformation, // q: out ALPC_BASIC_INFORMATION
        AlpcPortInformation, // s: in ALPC_PORT_ATTRIBUTES
        AlpcAssociateCompletionPortInformation, // s: in ALPC_PORT_ASSOCIATE_COMPLETION_PORT
        AlpcConnectedSIDInformation, // q: in SID
        AlpcServerInformation, // q: inout ALPC_SERVER_INFORMATION
        AlpcMessageZoneInformation, // s: in ALPC_PORT_MESSAGE_ZONE_INFORMATION
        AlpcRegisterCompletionListInformation, // s: in ALPC_PORT_COMPLETION_LIST_INFORMATION
        AlpcUnregisterCompletionListInformation, // s: VOID
        AlpcAdjustCompletionListConcurrencyCountInformation, // s: in ULONG
        AlpcRegisterCallbackInformation, // s: ALPC_REGISTER_CALLBACK // kernel-mode only
        AlpcCompletionListRundownInformation, // s: VOID // 10
        AlpcWaitForPortReferences,
        AlpcServerSessionInformation // q: ALPC_SERVER_SESSION_INFORMATION // since 19H2
    } ALPC_PORT_INFORMATION_CLASS;

    // private
    typedef struct _ALPC_BASIC_INFORMATION
    {
        ULONG Flags;
        ULONG SequenceNo;
        PVOID PortContext;
    } ALPC_BASIC_INFORMATION, * PALPC_BASIC_INFORMATION;

    // private
    typedef struct _ALPC_PORT_ASSOCIATE_COMPLETION_PORT
    {
        PVOID CompletionKey;
        HANDLE CompletionPort;
    } ALPC_PORT_ASSOCIATE_COMPLETION_PORT, * PALPC_PORT_ASSOCIATE_COMPLETION_PORT;

    // private
    typedef struct _ALPC_SERVER_INFORMATION
    {
        union
        {
            struct
            {
                HANDLE ThreadHandle;
            } In;
            struct
            {
                BOOLEAN ThreadBlocked;
                HANDLE ConnectedProcessId;
                UNICODE_STRING ConnectionPortName;
            } Out;
        };
    } ALPC_SERVER_INFORMATION, * PALPC_SERVER_INFORMATION;

    // private
    typedef struct _ALPC_PORT_MESSAGE_ZONE_INFORMATION
    {
        PVOID Buffer;
        ULONG Size;
    } ALPC_PORT_MESSAGE_ZONE_INFORMATION, * PALPC_PORT_MESSAGE_ZONE_INFORMATION;

    // private
    typedef struct _ALPC_PORT_COMPLETION_LIST_INFORMATION
    {
        PVOID Buffer; // PALPC_COMPLETION_LIST_HEADER
        ULONG Size;
        ULONG ConcurrencyCount;
        ULONG AttributeFlags;
    } ALPC_PORT_COMPLETION_LIST_INFORMATION, * PALPC_PORT_COMPLETION_LIST_INFORMATION;

    // private
    typedef struct _ALPC_REGISTER_CALLBACK
    {
        PVOID CallbackObject; // PCALLBACK_OBJECT
        PVOID CallbackContext;
    } ALPC_REGISTER_CALLBACK, * PALPC_REGISTER_CALLBACK;

    // private
    typedef struct _ALPC_SERVER_SESSION_INFORMATION
    {
        ULONG SessionId;
        ULONG ProcessId;
    } ALPC_SERVER_SESSION_INFORMATION, * PALPC_SERVER_SESSION_INFORMATION;

    // private
    typedef enum _ALPC_MESSAGE_INFORMATION_CLASS
    {
        AlpcMessageSidInformation, // q: out SID
        AlpcMessageTokenModifiedIdInformation,  // q: out LUID
        AlpcMessageDirectStatusInformation,
        AlpcMessageHandleInformation, // ALPC_MESSAGE_HANDLE_INFORMATION
        MaxAlpcMessageInfoClass
    } ALPC_MESSAGE_INFORMATION_CLASS, * PALPC_MESSAGE_INFORMATION_CLASS;

    typedef struct _ALPC_MESSAGE_HANDLE_INFORMATION
    {
        ULONG Index;
        ULONG Flags;
        ULONG Handle;
        ULONG ObjectType;
        ACCESS_MASK GrantedAccess;
    } ALPC_MESSAGE_HANDLE_INFORMATION, * PALPC_MESSAGE_HANDLE_INFORMATION;

    // begin_private

#if (PHNT_VERSION >= PHNT_VISTA)

// System calls

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtAlpcCreatePort(
            _Out_ PHANDLE PortHandle,
            _In_opt_ POBJECT_ATTRIBUTES ObjectAttributes,
            _In_opt_ PALPC_PORT_ATTRIBUTES PortAttributes
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtAlpcDisconnectPort(
            _In_ HANDLE PortHandle,
            _In_ ULONG Flags
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtAlpcQueryInformation(
            _In_opt_ HANDLE PortHandle,
            _In_ ALPC_PORT_INFORMATION_CLASS PortInformationClass,
            _Inout_updates_bytes_to_(Length, *ReturnLength) PVOID PortInformation,
            _In_ ULONG Length,
            _Out_opt_ PULONG ReturnLength
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtAlpcSetInformation(
            _In_ HANDLE PortHandle,
            _In_ ALPC_PORT_INFORMATION_CLASS PortInformationClass,
            _In_reads_bytes_opt_(Length) PVOID PortInformation,
            _In_ ULONG Length
        );

#define ALPC_CREATEPORTSECTIONFLG_SECURE 0x40000 // rev

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtAlpcCreatePortSection(
            _In_ HANDLE PortHandle,
            _In_ ULONG Flags,
            _In_opt_ HANDLE SectionHandle,
            _In_ SIZE_T SectionSize,
            _Out_ PALPC_HANDLE AlpcSectionHandle,
            _Out_ PSIZE_T ActualSectionSize
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtAlpcDeletePortSection(
            _In_ HANDLE PortHandle,
            _Reserved_ ULONG Flags,
            _In_ ALPC_HANDLE SectionHandle
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtAlpcCreateResourceReserve(
            _In_ HANDLE PortHandle,
            _Reserved_ ULONG Flags,
            _In_ SIZE_T MessageSize,
            _Out_ PALPC_HANDLE ResourceId
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtAlpcDeleteResourceReserve(
            _In_ HANDLE PortHandle,
            _Reserved_ ULONG Flags,
            _In_ ALPC_HANDLE ResourceId
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtAlpcCreateSectionView(
            _In_ HANDLE PortHandle,
            _Reserved_ ULONG Flags,
            _Inout_ PALPC_DATA_VIEW_ATTR ViewAttributes
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtAlpcDeleteSectionView(
            _In_ HANDLE PortHandle,
            _Reserved_ ULONG Flags,
            _In_ PVOID ViewBase
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtAlpcCreateSecurityContext(
            _In_ HANDLE PortHandle,
            _Reserved_ ULONG Flags,
            _Inout_ PALPC_SECURITY_ATTR SecurityAttribute
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtAlpcDeleteSecurityContext(
            _In_ HANDLE PortHandle,
            _Reserved_ ULONG Flags,
            _In_ ALPC_HANDLE ContextHandle
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtAlpcRevokeSecurityContext(
            _In_ HANDLE PortHandle,
            _Reserved_ ULONG Flags,
            _In_ ALPC_HANDLE ContextHandle
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtAlpcQueryInformationMessage(
            _In_ HANDLE PortHandle,
            _In_ PPORT_MESSAGE PortMessage,
            _In_ ALPC_MESSAGE_INFORMATION_CLASS MessageInformationClass,
            _Out_writes_bytes_to_opt_(Length, *ReturnLength) PVOID MessageInformation,
            _In_ ULONG Length,
            _Out_opt_ PULONG ReturnLength
        );

#define ALPC_MSGFLG_REPLY_MESSAGE 0x1
#define ALPC_MSGFLG_LPC_MODE 0x2
#define ALPC_MSGFLG_RELEASE_MESSAGE 0x10000 // dbg
#define ALPC_MSGFLG_SYNC_REQUEST 0x20000 // dbg
#define ALPC_MSGFLG_TRACK_PORT_REFERENCES 0x40000
#define ALPC_MSGFLG_WAIT_USER_MODE 0x100000
#define ALPC_MSGFLG_WAIT_ALERTABLE 0x200000
#define ALPC_MSGFLG_WOW64_CALL 0x80000000 // dbg

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtAlpcConnectPort(
            _Out_ PHANDLE PortHandle,
            _In_ PUNICODE_STRING PortName,
            _In_opt_ POBJECT_ATTRIBUTES ObjectAttributes,
            _In_opt_ PALPC_PORT_ATTRIBUTES PortAttributes,
            _In_ ULONG Flags,
            _In_opt_ PSID RequiredServerSid,
            _Inout_updates_bytes_to_opt_(*BufferLength, *BufferLength) PPORT_MESSAGE ConnectionMessage,
            _Inout_opt_ PULONG BufferLength,
            _Inout_opt_ PALPC_MESSAGE_ATTRIBUTES OutMessageAttributes,
            _Inout_opt_ PALPC_MESSAGE_ATTRIBUTES InMessageAttributes,
            _In_opt_ PLARGE_INTEGER Timeout
        );

#if (PHNT_VERSION >= PHNT_WIN8)
    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtAlpcConnectPortEx(
            _Out_ PHANDLE PortHandle,
            _In_ POBJECT_ATTRIBUTES ConnectionPortObjectAttributes,
            _In_opt_ POBJECT_ATTRIBUTES ClientPortObjectAttributes,
            _In_opt_ PALPC_PORT_ATTRIBUTES PortAttributes,
            _In_ ULONG Flags,
            _In_opt_ PSECURITY_DESCRIPTOR ServerSecurityRequirements,
            _Inout_updates_bytes_to_opt_(*BufferLength, *BufferLength) PPORT_MESSAGE ConnectionMessage,
            _Inout_opt_ PSIZE_T BufferLength,
            _Inout_opt_ PALPC_MESSAGE_ATTRIBUTES OutMessageAttributes,
            _Inout_opt_ PALPC_MESSAGE_ATTRIBUTES InMessageAttributes,
            _In_opt_ PLARGE_INTEGER Timeout
        );
#endif

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtAlpcAcceptConnectPort(
            _Out_ PHANDLE PortHandle,
            _In_ HANDLE ConnectionPortHandle,
            _In_ ULONG Flags,
            _In_opt_ POBJECT_ATTRIBUTES ObjectAttributes,
            _In_opt_ PALPC_PORT_ATTRIBUTES PortAttributes,
            _In_opt_ PVOID PortContext,
            _In_reads_bytes_(ConnectionRequest->u1.s1.TotalLength) PPORT_MESSAGE ConnectionRequest,
            _Inout_opt_ PALPC_MESSAGE_ATTRIBUTES ConnectionMessageAttributes,
            _In_ BOOLEAN AcceptConnection
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtAlpcSendWaitReceivePort(
            _In_ HANDLE PortHandle,
            _In_ ULONG Flags,
            _In_reads_bytes_opt_(SendMessage->u1.s1.TotalLength) PPORT_MESSAGE SendMessage,
            _Inout_opt_ PALPC_MESSAGE_ATTRIBUTES SendMessageAttributes,
            _Out_writes_bytes_to_opt_(*BufferLength, *BufferLength) PPORT_MESSAGE ReceiveMessage,
            _Inout_opt_ PSIZE_T BufferLength,
            _Inout_opt_ PALPC_MESSAGE_ATTRIBUTES ReceiveMessageAttributes,
            _In_opt_ PLARGE_INTEGER Timeout
        );

#define ALPC_CANCELFLG_TRY_CANCEL 0x1 // dbg
#define ALPC_CANCELFLG_NO_CONTEXT_CHECK 0x8
#define ALPC_CANCELFLGP_FLUSH 0x10000 // dbg

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtAlpcCancelMessage(
            _In_ HANDLE PortHandle,
            _In_ ULONG Flags,
            _In_ PALPC_CONTEXT_ATTR MessageContext
        );

#define ALPC_IMPERSONATEFLG_ANONYMOUS 0x1
#define ALPC_IMPERSONATEFLG_REQUIRE_IMPERSONATE 0x2
    //ALPC_IMPERSONATEFLG 0x3-0x10 (SECURITY_IMPERSONATION_LEVEL)

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtAlpcImpersonateClientOfPort(
            _In_ HANDLE PortHandle,
            _In_ PPORT_MESSAGE Message,
            _In_ PVOID Flags
        );

#if (PHNT_VERSION >= PHNT_THRESHOLD)
    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtAlpcImpersonateClientContainerOfPort(
            _In_ HANDLE PortHandle,
            _In_ PPORT_MESSAGE Message,
            _Reserved_ ULONG Flags
        );
#endif

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtAlpcOpenSenderProcess(
            _Out_ PHANDLE ProcessHandle,
            _In_ HANDLE PortHandle,
            _In_ PPORT_MESSAGE PortMessage,
            _Reserved_ ULONG Flags,
            _In_ ACCESS_MASK DesiredAccess,
            _In_ POBJECT_ATTRIBUTES ObjectAttributes
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtAlpcOpenSenderThread(
            _Out_ PHANDLE ThreadHandle,
            _In_ HANDLE PortHandle,
            _In_ PPORT_MESSAGE PortMessage,
            _Reserved_ ULONG Flags,
            _In_ ACCESS_MASK DesiredAccess,
            _In_ POBJECT_ATTRIBUTES ObjectAttributes
        );

    // Support functions

    NTSYSAPI
        ULONG
        NTAPI
        AlpcMaxAllowedMessageLength(
            VOID
        );

    NTSYSAPI
        ULONG
        NTAPI
        AlpcGetHeaderSize(
            _In_ ULONG Flags
        );

#define ALPC_ATTRFLG_ALLOCATEDATTR 0x20000000
#define ALPC_ATTRFLG_VALIDATTR 0x40000000
#define ALPC_ATTRFLG_KEEPRUNNINGATTR 0x60000000

    NTSYSAPI
        NTSTATUS
        NTAPI
        AlpcInitializeMessageAttribute(
            _In_ ULONG AttributeFlags,
            _Out_opt_ PALPC_MESSAGE_ATTRIBUTES Buffer,
            _In_ ULONG BufferSize,
            _Out_ PULONG RequiredBufferSize
        );

    NTSYSAPI
        PVOID
        NTAPI
        AlpcGetMessageAttribute(
            _In_ PALPC_MESSAGE_ATTRIBUTES Buffer,
            _In_ ULONG AttributeFlag
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        AlpcRegisterCompletionList(
            _In_ HANDLE PortHandle,
            _Out_ PALPC_COMPLETION_LIST_HEADER Buffer,
            _In_ ULONG Size,
            _In_ ULONG ConcurrencyCount,
            _In_ ULONG AttributeFlags
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        AlpcUnregisterCompletionList(
            _In_ HANDLE PortHandle
        );

#if (PHNT_VERSION >= PHNT_WIN7)
    // rev
    NTSYSAPI
        NTSTATUS
        NTAPI
        AlpcRundownCompletionList(
            _In_ HANDLE PortHandle
        );
#endif

    NTSYSAPI
        NTSTATUS
        NTAPI
        AlpcAdjustCompletionListConcurrencyCount(
            _In_ HANDLE PortHandle,
            _In_ ULONG ConcurrencyCount
        );

    NTSYSAPI
        BOOLEAN
        NTAPI
        AlpcRegisterCompletionListWorkerThread(
            _Inout_ PVOID CompletionList
        );

    NTSYSAPI
        BOOLEAN
        NTAPI
        AlpcUnregisterCompletionListWorkerThread(
            _Inout_ PVOID CompletionList
        );

    NTSYSAPI
        VOID
        NTAPI
        AlpcGetCompletionListLastMessageInformation(
            _In_ PVOID CompletionList,
            _Out_ PULONG LastMessageId,
            _Out_ PULONG LastCallbackId
        );

    NTSYSAPI
        ULONG
        NTAPI
        AlpcGetOutstandingCompletionListMessageCount(
            _In_ PVOID CompletionList
        );

    NTSYSAPI
        PPORT_MESSAGE
        NTAPI
        AlpcGetMessageFromCompletionList(
            _In_ PVOID CompletionList,
            _Out_opt_ PALPC_MESSAGE_ATTRIBUTES* MessageAttributes
        );

    NTSYSAPI
        VOID
        NTAPI
        AlpcFreeCompletionListMessage(
            _Inout_ PVOID CompletionList,
            _In_ PPORT_MESSAGE Message
        );

    NTSYSAPI
        PALPC_MESSAGE_ATTRIBUTES
        NTAPI
        AlpcGetCompletionListMessageAttributes(
            _In_ PVOID CompletionList,
            _In_ PPORT_MESSAGE Message
        );

#endif

    // end_private

#endif
/*
 * Prefetcher (Superfetch) support functions
 *
 * This file is part of System Informer.
 */

#ifndef _NTPFAPI_H
#define _NTPFAPI_H

 // begin_private

 // Prefetch

    typedef enum _PF_BOOT_PHASE_ID
    {
        PfKernelInitPhase = 0,
        PfBootDriverInitPhase = 90,
        PfSystemDriverInitPhase = 120,
        PfSessionManagerInitPhase = 150,
        PfSMRegistryInitPhase = 180,
        PfVideoInitPhase = 210,
        PfPostVideoInitPhase = 240,
        PfBootAcceptedRegistryInitPhase = 270,
        PfUserShellReadyPhase = 300,
        PfMaxBootPhaseId = 900
    } PF_BOOT_PHASE_ID;

    typedef enum _PF_ENABLE_STATUS
    {
        PfSvNotSpecified,
        PfSvEnabled,
        PfSvDisabled,
        PfSvMaxEnableStatus
    } PF_ENABLE_STATUS;

    typedef struct _PF_TRACE_LIMITS
    {
        ULONG MaxNumPages;
        ULONG MaxNumSections;
        LONGLONG TimerPeriod;
    } PF_TRACE_LIMITS, * PPF_TRACE_LIMITS;

    typedef struct _PF_SYSTEM_PREFETCH_PARAMETERS
    {
        PF_ENABLE_STATUS EnableStatus[2];
        PF_TRACE_LIMITS TraceLimits[2];
        ULONG MaxNumActiveTraces;
        ULONG MaxNumSavedTraces;
        WCHAR RootDirPath[32];
        WCHAR HostingApplicationList[128];
    } PF_SYSTEM_PREFETCH_PARAMETERS, * PPF_SYSTEM_PREFETCH_PARAMETERS;

#define PF_BOOT_CONTROL_VERSION 1

    typedef struct _PF_BOOT_CONTROL
    {
        ULONG Version;
        ULONG DisableBootPrefetching;
    } PF_BOOT_CONTROL, * PPF_BOOT_CONTROL;

    typedef enum _PREFETCHER_INFORMATION_CLASS
    {
        PrefetcherRetrieveTrace = 1, // q: CHAR[]
        PrefetcherSystemParameters, // q: PF_SYSTEM_PREFETCH_PARAMETERS
        PrefetcherBootPhase, // s: PF_BOOT_PHASE_ID
        PrefetcherSpare1, // PrefetcherRetrieveBootLoaderTrace // q: CHAR[]
        PrefetcherBootControl, // s: PF_BOOT_CONTROL
        PrefetcherScenarioPolicyControl,
        PrefetcherSpare2,
        PrefetcherAppLaunchScenarioControl,
        PrefetcherInformationMax
    } PREFETCHER_INFORMATION_CLASS;

#define PREFETCHER_INFORMATION_VERSION 23 // rev
#define PREFETCHER_INFORMATION_MAGIC ('kuhC') // rev

    typedef struct _PREFETCHER_INFORMATION
    {
        _In_ ULONG Version;
        _In_ ULONG Magic;
        _In_ PREFETCHER_INFORMATION_CLASS PrefetcherInformationClass;
        _Inout_ PVOID PrefetcherInformation;
        _Inout_ ULONG PrefetcherInformationLength;
    } PREFETCHER_INFORMATION, * PPREFETCHER_INFORMATION;

    // Superfetch

    typedef struct _PF_SYSTEM_SUPERFETCH_PARAMETERS
    {
        ULONG EnabledComponents;
        ULONG BootID;
        ULONG SavedSectInfoTracesMax;
        ULONG SavedPageAccessTracesMax;
        ULONG ScenarioPrefetchTimeoutStandby;
        ULONG ScenarioPrefetchTimeoutHibernate;
        ULONG ScenarioPrefetchTimeoutHiberBoot;
    } PF_SYSTEM_SUPERFETCH_PARAMETERS, * PPF_SYSTEM_SUPERFETCH_PARAMETERS;

    // rev
    typedef enum _PF_EVENT_TYPE
    {
        PfEventTypeImageLoad = 0,
        PfEventTypeAppLaunch = 1,
        PfEventTypeStartTrace = 2,
        PfEventTypeEndTrace = 3,
        PfEventTypeTimestamp = 4,
        PfEventTypeOperation = 5,
        PfEventTypeRepurpose = 6,
        PfEventTypeForegroundProcess = 7,
        PfEventTypeTimeRange = 8,
        PfEventTypeUserInput = 9,
        PfEventTypeFileAccess = 10,
        PfEventTypeUnmap = 11,
        PfEventTypeUtilization = 11,
        PfEventTypeMemInfo = 12,
        PfEventTypeFileDelete = 13,
        PfEventTypeAppExit = 14,
        PfEventTypeSystemTime = 15,
        PfEventTypePower = 16,
        PfEventTypeSessionChange = 17,
        PfEventTypeHardFaultTimeStamp = 18,
        PfEventTypeVirtualFree = 19,
        PfEventTypePerfInfo = 20,
        PfEventTypeProcessSnapshot = 21,
        PfEventTypeUserSnapshot = 22,
        PfEventTypeStreamSequenceNumber = 23,
        PfEventTypeFileTruncate = 24,
        PfEventTypeFileRename = 25,
        PfEventTypeFileCreate = 26,
        PfEventTypeAgCxContext = 27,
        PfEventTypePowerAction = 28,
        PfEventTypeHardFaultTS = 29,
        PfEventTypeRobustInfo = 30,
        PfEventTypeFileDefrag = 31,
        PfEventTypeMax = 32
    } PF_EVENT_TYPE;

    // rev
    typedef struct _PF_LOG_EVENT_DATA
    {
        ULONG EventType : 5; // PF_EVENT_TYPE
        ULONG Flags : 2;
        ULONG DataSize : 25;
        PVOID EventData;
    } PF_LOG_EVENT_DATA, * PPF_LOG_EVENT_DATA;

#define PF_PFN_PRIO_REQUEST_VERSION 1
#define PF_PFN_PRIO_REQUEST_QUERY_MEMORY_LIST 0x1
#define PF_PFN_PRIO_REQUEST_VALID_FLAGS 0x1

    typedef struct _PF_PFN_PRIO_REQUEST
    {
        ULONG Version;
        ULONG RequestFlags;
        ULONG_PTR PfnCount;
        SYSTEM_MEMORY_LIST_INFORMATION MemInfo;
        MMPFN_IDENTITY PageData[256];
    } PF_PFN_PRIO_REQUEST, * PPF_PFN_PRIO_REQUEST;

    typedef enum _PFS_PRIVATE_PAGE_SOURCE_TYPE
    {
        PfsPrivateSourceKernel,
        PfsPrivateSourceSession,
        PfsPrivateSourceProcess,
        PfsPrivateSourceMax
    } PFS_PRIVATE_PAGE_SOURCE_TYPE;

    typedef struct _PFS_PRIVATE_PAGE_SOURCE
    {
        PFS_PRIVATE_PAGE_SOURCE_TYPE Type;
        union
        {
            ULONG SessionId;
            ULONG ProcessId;
        };
        ULONG ImagePathHash;
        ULONG_PTR UniqueProcessHash;
    } PFS_PRIVATE_PAGE_SOURCE, * PPFS_PRIVATE_PAGE_SOURCE;

    typedef struct _PF_PRIVSOURCE_INFO
    {
        PFS_PRIVATE_PAGE_SOURCE DbInfo;
        PVOID EProcess;
        SIZE_T WsPrivatePages;
        SIZE_T TotalPrivatePages;
        ULONG SessionID;
        CHAR ImageName[16];
        union {
            ULONG_PTR WsSwapPages;                 // process only PF_PRIVSOURCE_QUERY_WS_SWAP_PAGES.
            ULONG_PTR SessionPagedPoolPages;       // session only.
            ULONG_PTR StoreSizePages;              // process only PF_PRIVSOURCE_QUERY_STORE_INFO.
        };
        ULONG_PTR WsTotalPages;         // process/session only.
        ULONG DeepFreezeTimeMs;         // process only.
        ULONG ModernApp : 1;            // process only.
        ULONG DeepFrozen : 1;           // process only. If set, DeepFreezeTimeMs contains the time at which the freeze occurred
        ULONG Foreground : 1;           // process only.
        ULONG PerProcessStore : 1;      // process only.
        ULONG Spare : 28;
    } PF_PRIVSOURCE_INFO, * PPF_PRIVSOURCE_INFO;

    // rev
#define PF_PRIVSOURCE_QUERY_REQUEST_VERSION 8
#define PF_PRIVSOURCE_QUERY_REQUEST_FLAGS_QUERYWSPAGES 0x1
#define PF_PRIVSOURCE_QUERY_REQUEST_FLAGS_QUERYCOMPRESSEDPAGES 0x2
#define PF_PRIVSOURCE_QUERY_REQUEST_FLAGS_QUERYSKIPPAGES 0x4 // ??

// rev
    typedef struct _PF_PRIVSOURCE_QUERY_REQUEST
    {
        ULONG Version;
        ULONG Flags;
        ULONG InfoCount;
        PF_PRIVSOURCE_INFO InfoArray[1];
    } PF_PRIVSOURCE_QUERY_REQUEST, * PPF_PRIVSOURCE_QUERY_REQUEST;

    // rev
    typedef enum _PF_PHASED_SCENARIO_TYPE
    {
        PfScenarioTypeNone,
        PfScenarioTypeStandby,
        PfScenarioTypeHibernate,
        PfScenarioTypeFUS,
        PfScenarioTypeMax
    } PF_PHASED_SCENARIO_TYPE;

    // rev
#define PF_SCENARIO_PHASE_INFO_VERSION 4

// rev
    typedef struct _PF_SCENARIO_PHASE_INFO
    {
        ULONG Version;
        PF_PHASED_SCENARIO_TYPE ScenType;
        ULONG PhaseId;
        ULONG SequenceNumber;
        ULONG Flags;
        ULONG FUSUserId;
    } PF_SCENARIO_PHASE_INFO, * PPF_SCENARIO_PHASE_INFO;

    // rev
    typedef struct _PF_MEMORY_LIST_NODE
    {
        ULONGLONG Node : 8;
        ULONGLONG Spare : 56;
        ULONGLONG StandbyLowPageCount;
        ULONGLONG StandbyMediumPageCount;
        ULONGLONG StandbyHighPageCount;
        ULONGLONG FreePageCount;
        ULONGLONG ModifiedPageCount;
    } PF_MEMORY_LIST_NODE, * PPF_MEMORY_LIST_NODE;

    // rev
    typedef struct _PF_ROBUST_PROCESS_ENTRY
    {
        ULONG ImagePathHash;
        ULONG Pid;
        ULONG Alignment;
    } PF_ROBUST_PROCESS_ENTRY, * PPF_ROBUST_PROCESS_ENTRY;

    // rev
    typedef struct _PF_ROBUST_FILE_ENTRY
    {
        ULONG FilePathHash;
    } PF_ROBUST_FILE_ENTRY, * PPF_ROBUST_FILE_ENTRY;

    // rev
    typedef enum _PF_ROBUSTNESS_CONTROL_COMMAND
    {
        PfRpControlUpdate = 0,
        PfRpControlReset = 1,
        PfRpControlRobustAllStart = 2,
        PfRpControlRobustAllStop = 3,
        PfRpControlCommandMax = 4
    } PF_ROBUSTNESS_CONTROL_COMMAND;

    // rev
#define PF_ROBUSTNESS_CONTROL_VERSION 1

// rev
    typedef struct _PF_ROBUSTNESS_CONTROL
    {
        ULONG Version;
        PF_ROBUSTNESS_CONTROL_COMMAND Command;
        ULONG DeprioProcessCount;
        ULONG ExemptProcessCount;
        ULONG DeprioFileCount;
        ULONG ExemptFileCount;
        PF_ROBUST_PROCESS_ENTRY ProcessEntries[1];
        PF_ROBUST_FILE_ENTRY FileEntries[1];
    } PF_ROBUSTNESS_CONTROL, * PPF_ROBUSTNESS_CONTROL;

    // rev
    typedef struct _PF_TIME_CONTROL
    {
        LONG TimeAdjustment;
    } PF_TIME_CONTROL, * PPF_TIME_CONTROL;

#define PF_MEMORY_LIST_INFO_VERSION 1

    typedef struct _PF_MEMORY_LIST_INFO
    {
        ULONG Version;
        ULONG Size;
        ULONG NodeCount;
        PF_MEMORY_LIST_NODE Nodes[1];
    } PF_MEMORY_LIST_INFO, * PPF_MEMORY_LIST_INFO;

    typedef struct _PF_PHYSICAL_MEMORY_RANGE
    {
        ULONG_PTR BasePfn;
        ULONG_PTR PageCount;
    } PF_PHYSICAL_MEMORY_RANGE, * PPF_PHYSICAL_MEMORY_RANGE;

#define PF_PHYSICAL_MEMORY_RANGE_INFO_V1_VERSION 1

    typedef struct _PF_PHYSICAL_MEMORY_RANGE_INFO_V1
    {
        ULONG Version;
        ULONG RangeCount;
        PF_PHYSICAL_MEMORY_RANGE Ranges[1];
    } PF_PHYSICAL_MEMORY_RANGE_INFO_V1, * PPF_PHYSICAL_MEMORY_RANGE_INFO_V1;

#define PF_PHYSICAL_MEMORY_RANGE_INFO_V2_VERSION 2

    typedef struct _PF_PHYSICAL_MEMORY_RANGE_INFO_V2
    {
        ULONG Version;
        ULONG Flags;
        ULONG RangeCount;
        PF_PHYSICAL_MEMORY_RANGE Ranges[ANYSIZE_ARRAY];
    } PF_PHYSICAL_MEMORY_RANGE_INFO_V2, * PPF_PHYSICAL_MEMORY_RANGE_INFO_V2;

    // rev
#define PF_REPURPOSED_BY_PREFETCH_INFO_VERSION 1

// rev
    typedef struct _PF_REPURPOSED_BY_PREFETCH_INFO
    {
        ULONG Version;
        SIZE_T RepurposedByPrefetch;
    } PF_REPURPOSED_BY_PREFETCH_INFO, * PPF_REPURPOSED_BY_PREFETCH_INFO;

    // rev
#define PF_VIRTUAL_QUERY_VERSION 1

// rev
    typedef struct _PF_VIRTUAL_QUERY
    {
        ULONG Version;
        union
        {
            ULONG Flags;
            struct
            {
                ULONG FaultInPageTables : 1;
                ULONG ReportPageTables : 1;
                ULONG Spare : 30;
            };
        };
        PVOID QueryBuffer; // MEMORY_WORKING_SET_EX_INFORMATION[NumberOfPages] (input: VirtualAddress[], output: VirtualAttributes[])
        SIZE_T QueryBufferSize; // NumberOfPages * sizeof(MEMORY_WORKING_SET_EX_INFORMATION)
        HANDLE ProcessHandle;
    } PF_VIRTUAL_QUERY, * PPF_VIRTUAL_QUERY;

    // rev
#define PF_MIN_WS_AGE_RATE_CONTROL_VERSION 1

// rev
    typedef struct _PF_MIN_WS_AGE_RATE_CONTROL
    {
        ULONG Version;
        ULONG SecondsToOldestAge;
    } PF_MIN_WS_AGE_RATE_CONTROL, * PPF_MIN_WS_AGE_RATE_CONTROL;

    // rev
#define PF_DEPRIORITIZE_OLD_PAGES_VERSION 3

// rev
    typedef struct _PF_DEPRIORITIZE_OLD_PAGES
    {
        ULONG Version;
        HANDLE ProcessHandle;
        union
        {
            ULONG Flags;
            struct
            {
                ULONG TargetPriority : 4;
                ULONG TrimPages : 2;
                ULONG Spare : 26;
            };
        };
    } PF_DEPRIORITIZE_OLD_PAGES, * PPF_DEPRIORITIZE_OLD_PAGES;

    // rev
#define PF_GPU_UTILIZATION_INFO_VERSION 1

// rev
    typedef struct _PF_GPU_UTILIZATION_INFO
    {
        ULONG Version;
        ULONG SessionId;
        ULONGLONG GpuTime;
    } PF_GPU_UTILIZATION_INFO, * PPF_GPU_UTILIZATION_INFO;

    // rev
    typedef enum _SUPERFETCH_INFORMATION_CLASS
    {
        SuperfetchRetrieveTrace = 1, // q: CHAR[]
        SuperfetchSystemParameters, // q: PF_SYSTEM_SUPERFETCH_PARAMETERS
        SuperfetchLogEvent, // s: PF_LOG_EVENT_DATA
        SuperfetchGenerateTrace, // s: NULL
        SuperfetchPrefetch,
        SuperfetchPfnQuery, // q: PF_PFN_PRIO_REQUEST
        SuperfetchPfnSetPriority,
        SuperfetchPrivSourceQuery, // q: PF_PRIVSOURCE_QUERY_REQUEST
        SuperfetchSequenceNumberQuery, // q: ULONG
        SuperfetchScenarioPhase, // 10
        SuperfetchWorkerPriority, // s: KPRIORITY
        SuperfetchScenarioQuery, // q: PF_SCENARIO_PHASE_INFO
        SuperfetchScenarioPrefetch,
        SuperfetchRobustnessControl, // s: PF_ROBUSTNESS_CONTROL
        SuperfetchTimeControl, // s: PF_TIME_CONTROL
        SuperfetchMemoryListQuery, // q: PF_MEMORY_LIST_INFO
        SuperfetchMemoryRangesQuery, // q: PF_PHYSICAL_MEMORY_RANGE_INFO
        SuperfetchTracingControl,
        SuperfetchTrimWhileAgingControl,
        SuperfetchRepurposedByPrefetch, // q: PF_REPURPOSED_BY_PREFETCH_INFO // 20
        SuperfetchChannelPowerRequest,
        SuperfetchMovePages,
        SuperfetchVirtualQuery, // q: PF_VIRTUAL_QUERY
        SuperfetchCombineStatsQuery,
        SuperfetchSetMinWsAgeRate, // s: PF_MIN_WS_AGE_RATE_CONTROL
        SuperfetchDeprioritizeOldPagesInWs, // s: PF_DEPRIORITIZE_OLD_PAGES
        SuperfetchFileExtentsQuery, // q: PF_FILE_EXTENTS_INFO
        SuperfetchGpuUtilizationQuery, // q: PF_GPU_UTILIZATION_INFO
        SuperfetchPfnSet, // s: PF_PFN_PRIO_REQUEST // since WIN11
        SuperfetchInformationMax
    } SUPERFETCH_INFORMATION_CLASS;

#define SUPERFETCH_INFORMATION_VERSION 45 // rev
#define SUPERFETCH_INFORMATION_MAGIC ('kuhC') // rev

    typedef struct _SUPERFETCH_INFORMATION
    {
        _In_ ULONG Version;
        _In_ ULONG Magic;
        _In_ SUPERFETCH_INFORMATION_CLASS SuperfetchInformationClass;
        _Inout_ PVOID SuperfetchInformation;
        _Inout_ ULONG SuperfetchInformationLength;
    } SUPERFETCH_INFORMATION, * PSUPERFETCH_INFORMATION;

    // end_private

#endif
/*
 * Plug and Play support functions
 *
 * This file is part of System Informer.
 */

#ifndef _NTPNPAPI_H
#define _NTPNPAPI_H

    typedef enum _PLUGPLAY_EVENT_CATEGORY
    {
        HardwareProfileChangeEvent,
        TargetDeviceChangeEvent,
        DeviceClassChangeEvent,
        CustomDeviceEvent,
        DeviceInstallEvent,
        DeviceArrivalEvent,
        PowerEvent,
        VetoEvent,
        BlockedDriverEvent,
        InvalidIDEvent,
        MaxPlugEventCategory
    } PLUGPLAY_EVENT_CATEGORY, * PPLUGPLAY_EVENT_CATEGORY;

    typedef struct _PLUGPLAY_EVENT_BLOCK
    {
        GUID EventGuid;
        PLUGPLAY_EVENT_CATEGORY EventCategory;
        PULONG Result;
        ULONG Flags;
        ULONG TotalSize;
        PVOID DeviceObject;

        union
        {
            struct
            {
                GUID ClassGuid;
                WCHAR SymbolicLinkName[1];
            } DeviceClass;
            struct
            {
                WCHAR DeviceIds[1];
            } TargetDevice;
            struct
            {
                WCHAR DeviceId[1];
            } InstallDevice;
            struct
            {
                PVOID NotificationStructure;
                WCHAR DeviceIds[1];
            } CustomNotification;
            struct
            {
                PVOID Notification;
            } ProfileNotification;
            struct
            {
                ULONG NotificationCode;
                ULONG NotificationData;
            } PowerNotification;
            struct
            {
                PNP_VETO_TYPE VetoType;
                WCHAR DeviceIdVetoNameBuffer[1]; // DeviceId<null>VetoName<null><null>
            } VetoNotification;
            struct
            {
                GUID BlockedDriverGuid;
            } BlockedDriverNotification;
            struct
            {
                WCHAR ParentId[1];
            } InvalidIDNotification;
        } u;
    } PLUGPLAY_EVENT_BLOCK, * PPLUGPLAY_EVENT_BLOCK;

    typedef enum _PLUGPLAY_CONTROL_CLASS
    {
        PlugPlayControlEnumerateDevice, // PLUGPLAY_CONTROL_ENUMERATE_DEVICE_DATA
        PlugPlayControlRegisterNewDevice, // PLUGPLAY_CONTROL_DEVICE_CONTROL_DATA
        PlugPlayControlDeregisterDevice, // PLUGPLAY_CONTROL_DEVICE_CONTROL_DATA
        PlugPlayControlInitializeDevice, // PLUGPLAY_CONTROL_DEVICE_CONTROL_DATA
        PlugPlayControlStartDevice, // PLUGPLAY_CONTROL_DEVICE_CONTROL_DATA
        PlugPlayControlUnlockDevice, // PLUGPLAY_CONTROL_DEVICE_CONTROL_DATA
        PlugPlayControlQueryAndRemoveDevice, // PLUGPLAY_CONTROL_QUERY_AND_REMOVE_DATA
        PlugPlayControlUserResponse, // PLUGPLAY_CONTROL_USER_RESPONSE_DATA
        PlugPlayControlGenerateLegacyDevice, // PLUGPLAY_CONTROL_LEGACY_DEVGEN_DATA
        PlugPlayControlGetInterfaceDeviceList, // PLUGPLAY_CONTROL_INTERFACE_LIST_DATA
        PlugPlayControlProperty, // PLUGPLAY_CONTROL_PROPERTY_DATA
        PlugPlayControlDeviceClassAssociation, // PLUGPLAY_CONTROL_CLASS_ASSOCIATION_DATA
        PlugPlayControlGetRelatedDevice, // PLUGPLAY_CONTROL_RELATED_DEVICE_DATA
        PlugPlayControlGetInterfaceDeviceAlias, // PLUGPLAY_CONTROL_INTERFACE_ALIAS_DATA
        PlugPlayControlDeviceStatus, // PLUGPLAY_CONTROL_STATUS_DATA
        PlugPlayControlGetDeviceDepth, // PLUGPLAY_CONTROL_DEPTH_DATA
        PlugPlayControlQueryDeviceRelations, // PLUGPLAY_CONTROL_DEVICE_RELATIONS_DATA
        PlugPlayControlTargetDeviceRelation, // PLUGPLAY_CONTROL_TARGET_RELATION_DATA
        PlugPlayControlQueryConflictList, // PLUGPLAY_CONTROL_CONFLICT_LIST
        PlugPlayControlRetrieveDock, // PLUGPLAY_CONTROL_RETRIEVE_DOCK_DATA
        PlugPlayControlResetDevice, // PLUGPLAY_CONTROL_DEVICE_CONTROL_DATA
        PlugPlayControlHaltDevice, // PLUGPLAY_CONTROL_DEVICE_CONTROL_DATA
        PlugPlayControlGetBlockedDriverList, // PLUGPLAY_CONTROL_BLOCKED_DRIVER_DATA
        PlugPlayControlGetDeviceInterfaceEnabled, // PLUGPLAY_CONTROL_DEVICE_INTERFACE_ENABLED
        MaxPlugPlayControl
    } PLUGPLAY_CONTROL_CLASS, * PPLUGPLAY_CONTROL_CLASS;

#if (PHNT_VERSION < PHNT_WIN8)
    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtGetPlugPlayEvent(
            _In_ HANDLE EventHandle,
            _In_opt_ PVOID Context,
            _Out_writes_bytes_(EventBufferSize) PPLUGPLAY_EVENT_BLOCK EventBlock,
            _In_ ULONG EventBufferSize
        );
#endif

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtPlugPlayControl(
            _In_ PLUGPLAY_CONTROL_CLASS PnPControlClass,
            _Inout_updates_bytes_(PnPControlDataLength) PVOID PnPControlData,
            _In_ ULONG PnPControlDataLength
        );

#if (PHNT_VERSION >= PHNT_WIN7)

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtSerializeBoot(
            VOID
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtEnableLastKnownGood(
            VOID
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtDisableLastKnownGood(
            VOID
        );

#endif

#if (PHNT_VERSION >= PHNT_VISTA)
    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtReplacePartitionUnit(
            _In_ PUNICODE_STRING TargetInstancePath,
            _In_ PUNICODE_STRING SpareInstancePath,
            _In_ ULONG Flags
        );
#endif

#endif
    /*
     * Power Management support functions
     *
     * This file is part of System Informer.
     */

#ifndef _NTPOAPI_H
#define _NTPOAPI_H

#if (PHNT_MODE != PHNT_MODE_KERNEL)
     // POWER_INFORMATION_LEVEL
     // Note: We don't use an enum for these values to minimize conflicts with the Windows SDK. (dmex)
#define SystemPowerPolicyAc 0 // SYSTEM_POWER_POLICY // GET: InputBuffer NULL. SET: InputBuffer not NULL.
#define SystemPowerPolicyDc 1 // SYSTEM_POWER_POLICY
#define VerifySystemPolicyAc 2 // SYSTEM_POWER_POLICY
#define VerifySystemPolicyDc 3 // SYSTEM_POWER_POLICY
#define SystemPowerCapabilities 4 // SYSTEM_POWER_CAPABILITIES
#define SystemBatteryState 5 // SYSTEM_BATTERY_STATE
#define SystemPowerStateHandler 6 // POWER_STATE_HANDLER // (kernel-mode only)
#define ProcessorStateHandler 7 // PROCESSOR_STATE_HANDLER // (kernel-mode only)
#define SystemPowerPolicyCurrent 8 // SYSTEM_POWER_POLICY
#define AdministratorPowerPolicy 9 // ADMINISTRATOR_POWER_POLICY
#define SystemReserveHiberFile 10 // BOOLEAN // (requires SeCreatePagefilePrivilege) // TRUE: hibernation file created. FALSE: hibernation file deleted.
#define ProcessorInformation 11 // PROCESSOR_POWER_INFORMATION
#define SystemPowerInformation 12 // SYSTEM_POWER_INFORMATION
#define ProcessorStateHandler2 13 // PROCESSOR_STATE_HANDLER2 // not implemented
#define LastWakeTime 14 // ULONGLONG // InterruptTime
#define LastSleepTime 15 // ULONGLONG // InterruptTime
#define SystemExecutionState 16 // EXECUTION_STATE // NtSetThreadExecutionState
#define SystemPowerStateNotifyHandler 17 // POWER_STATE_NOTIFY_HANDLER // (kernel-mode only)
#define ProcessorPowerPolicyAc 18 // PROCESSOR_POWER_POLICY // not implemented
#define ProcessorPowerPolicyDc 19 // PROCESSOR_POWER_POLICY // not implemented
#define VerifyProcessorPowerPolicyAc 20 // PROCESSOR_POWER_POLICY // not implemented
#define VerifyProcessorPowerPolicyDc 21 // PROCESSOR_POWER_POLICY // not implemented
#define ProcessorPowerPolicyCurrent 22 // PROCESSOR_POWER_POLICY // not implemented
#define SystemPowerStateLogging 23 // SYSTEM_POWER_STATE_DISABLE_REASON[]
#define SystemPowerLoggingEntry 24 // SYSTEM_POWER_LOGGING_ENTRY[] // (kernel-mode only)
#define SetPowerSettingValue 25 // (kernel-mode only)
#define NotifyUserPowerSetting 26 // not implemented
#define PowerInformationLevelUnused0 27 // not implemented
#define SystemMonitorHiberBootPowerOff 28 // NULL (PowerMonitorOff)
#define SystemVideoState 29 // MONITOR_DISPLAY_STATE
#define TraceApplicationPowerMessage 30 // (kernel-mode only)
#define TraceApplicationPowerMessageEnd 31 // (kernel-mode only)
#define ProcessorPerfStates 32 // (kernel-mode only)
#define ProcessorIdleStates 33 // PROCESSOR_IDLE_STATES // (kernel-mode only)
#define ProcessorCap 34 // PROCESSOR_CAP // (kernel-mode only)
#define SystemWakeSource 35 // out: POWER_WAKE_SOURCE_INFO
#define SystemHiberFileInformation 36 // out: SYSTEM_HIBERFILE_INFORMATION
#define TraceServicePowerMessage 37
#define ProcessorLoad 38 // in: PROCESSOR_LOAD (sets), in: PPROCESSOR_NUMBER (clears)
#define PowerShutdownNotification 39 // (kernel-mode only)
#define MonitorCapabilities 40 // (kernel-mode only)
#define SessionPowerInit 41 // (kernel-mode only)
#define SessionDisplayState 42 // (kernel-mode only)
#define PowerRequestCreate 43 // in: COUNTED_REASON_CONTEXT, out: HANDLE
#define PowerRequestAction 44 // in: POWER_REQUEST_ACTION
#define GetPowerRequestList 45 // out: POWER_REQUEST_LIST
#define ProcessorInformationEx 46 // in: USHORT ProcessorGroup, out: PROCESSOR_POWER_INFORMATION
#define NotifyUserModeLegacyPowerEvent 47 // (kernel-mode only)
#define GroupPark 48 // (debug-mode boot only)
#define ProcessorIdleDomains 49 // (kernel-mode only)
#define WakeTimerList 50 // out: WAKE_TIMER_INFO[]
#define SystemHiberFileSize 51 // ULONG
#define ProcessorIdleStatesHv 52 // (kernel-mode only)
#define ProcessorPerfStatesHv 53 // (kernel-mode only)
#define ProcessorPerfCapHv 54 // PROCESSOR_PERF_CAP_HV // (kernel-mode only)
#define ProcessorSetIdle 55 // (debug-mode boot only)
#define LogicalProcessorIdling 56 // (kernel-mode only)
#define UserPresence 57 // POWER_USER_PRESENCE // not implemented
#define PowerSettingNotificationName 58
#define GetPowerSettingValue 59 // GUID
#define IdleResiliency 60 // POWER_IDLE_RESILIENCY
#define SessionRITState 61 // POWER_SESSION_RIT_STATE
#define SessionConnectNotification 62 // POWER_SESSION_WINLOGON
#define SessionPowerCleanup 63
#define SessionLockState 64 // POWER_SESSION_WINLOGON
#define SystemHiberbootState 65 // BOOLEAN // fast startup supported
#define PlatformInformation 66 // BOOLEAN // connected standby supported
#define PdcInvocation 67 // (kernel-mode only)
#define MonitorInvocation 68 // (kernel-mode only)
#define FirmwareTableInformationRegistered 69 // (kernel-mode only)
#define SetShutdownSelectedTime 70 // NULL
#define SuspendResumeInvocation 71 // (kernel-mode only)
#define PlmPowerRequestCreate 72 // in: COUNTED_REASON_CONTEXT, out: HANDLE
#define ScreenOff 73 // NULL (PowerMonitorOff)
#define CsDeviceNotification 74 // (kernel-mode only)
#define PlatformRole 75 // POWER_PLATFORM_ROLE
#define LastResumePerformance 76 // RESUME_PERFORMANCE
#define DisplayBurst 77 // NULL (PowerMonitorOn)
#define ExitLatencySamplingPercentage 78
#define RegisterSpmPowerSettings 79 // (kernel-mode only)
#define PlatformIdleStates 80 // (kernel-mode only)
#define ProcessorIdleVeto 81 // (kernel-mode only) // deprecated
#define PlatformIdleVeto 82 // (kernel-mode only) // deprecated
#define SystemBatteryStatePrecise 83 // SYSTEM_BATTERY_STATE
#define ThermalEvent 84  // THERMAL_EVENT // PowerReportThermalEvent
#define PowerRequestActionInternal 85 // POWER_REQUEST_ACTION_INTERNAL
#define BatteryDeviceState 86
#define PowerInformationInternal 87 // POWER_INFORMATION_LEVEL_INTERNAL // PopPowerInformationInternal
#define ThermalStandby 88 // NULL // shutdown with thermal standby as reason.
#define SystemHiberFileType 89 // ULONG // zero ? reduced : full // powercfg.exe /h /type
#define PhysicalPowerButtonPress 90 // BOOLEAN
#define QueryPotentialDripsConstraint 91 // (kernel-mode only)
#define EnergyTrackerCreate 92
#define EnergyTrackerQuery 93
#define UpdateBlackBoxRecorder 94
#define SessionAllowExternalDmaDevices 95
#define SendSuspendResumeNotification 96 // since WIN11
#define BlackBoxRecorderDirectAccessBuffer 97
#define PowerInformationLevelMaximum 98
#endif

    typedef struct _PROCESSOR_POWER_INFORMATION
    {
        ULONG Number;
        ULONG MaxMhz;
        ULONG CurrentMhz;
        ULONG MhzLimit;
        ULONG MaxIdleState;
        ULONG CurrentIdleState;
    } PROCESSOR_POWER_INFORMATION, * PPROCESSOR_POWER_INFORMATION;

    typedef struct _SYSTEM_POWER_INFORMATION
    {
        ULONG MaxIdlenessAllowed;
        ULONG Idleness;
        ULONG TimeRemaining;
        UCHAR CoolingMode;
    } SYSTEM_POWER_INFORMATION, * PSYSTEM_POWER_INFORMATION;

    typedef struct _SYSTEM_HIBERFILE_INFORMATION
    {
        ULONG NumberOfMcbPairs;
        LARGE_INTEGER Mcb[1];
    } SYSTEM_HIBERFILE_INFORMATION, * PSYSTEM_HIBERFILE_INFORMATION;

#define POWER_REQUEST_CONTEXT_NOT_SPECIFIED DIAGNOSTIC_REASON_NOT_SPECIFIED

    // wdm
    typedef struct _COUNTED_REASON_CONTEXT
    {
        ULONG Version;
        ULONG Flags;
        union
        {
            struct
            {
                UNICODE_STRING ResourceFileName;
                USHORT ResourceReasonId;
                ULONG StringCount;
                _Field_size_(StringCount) PUNICODE_STRING ReasonStrings;
            };
            UNICODE_STRING SimpleString;
        };
    } COUNTED_REASON_CONTEXT, * PCOUNTED_REASON_CONTEXT;

    typedef enum _POWER_REQUEST_TYPE_INTERNAL // POWER_REQUEST_TYPE
    {
        PowerRequestDisplayRequiredInternal,
        PowerRequestSystemRequiredInternal,
        PowerRequestAwayModeRequiredInternal,
        PowerRequestExecutionRequiredInternal, // Windows 8+
        PowerRequestPerfBoostRequiredInternal, // Windows 8+
        PowerRequestActiveLockScreenInternal, // Windows 10 RS1+ (reserved on Windows 8)
        // Values 6 and 7 are reserved for Windows 8 only
        PowerRequestInternalInvalid,
        PowerRequestInternalUnknown,
        PowerRequestFullScreenVideoRequired  // Windows 8 only
    } POWER_REQUEST_TYPE_INTERNAL;

    typedef struct _POWER_REQUEST_ACTION
    {
        HANDLE PowerRequestHandle;
        POWER_REQUEST_TYPE_INTERNAL RequestType;
        BOOLEAN SetAction;
        HANDLE ProcessHandle; // Windows 8+ and only for requests created via PlmPowerRequestCreate
    } POWER_REQUEST_ACTION, * PPOWER_REQUEST_ACTION;

    typedef union _POWER_STATE
    {
        SYSTEM_POWER_STATE SystemState;
        DEVICE_POWER_STATE DeviceState;
    } POWER_STATE, * PPOWER_STATE;

    typedef enum _POWER_STATE_TYPE
    {
        SystemPowerState = 0,
        DevicePowerState
    } POWER_STATE_TYPE, * PPOWER_STATE_TYPE;

    // wdm
    typedef struct _SYSTEM_POWER_STATE_CONTEXT
    {
        union
        {
            struct
            {
                ULONG Reserved1 : 8;
                ULONG TargetSystemState : 4;
                ULONG EffectiveSystemState : 4;
                ULONG CurrentSystemState : 4;
                ULONG IgnoreHibernationPath : 1;
                ULONG PseudoTransition : 1;
                ULONG Reserved2 : 10;
            };
            ULONG ContextAsUlong;
        };
    } SYSTEM_POWER_STATE_CONTEXT, * PSYSTEM_POWER_STATE_CONTEXT;

    typedef enum _REQUESTER_TYPE
    {
        KernelRequester = 0,
        UserProcessRequester = 1,
        UserSharedServiceRequester = 2
    } REQUESTER_TYPE;

    typedef struct _COUNTED_REASON_CONTEXT_RELATIVE
    {
        ULONG Flags;
        union
        {
            struct
            {
                SIZE_T ResourceFileNameOffset;
                USHORT ResourceReasonId;
                ULONG StringCount;
                SIZE_T SubstitutionStringsOffset;
            } DUMMYSTRUCTNAME;
            SIZE_T SimpleStringOffset;
        } DUMMYUNIONNAME;
    } COUNTED_REASON_CONTEXT_RELATIVE, * PCOUNTED_REASON_CONTEXT_RELATIVE;

    typedef struct _DIAGNOSTIC_BUFFER
    {
        SIZE_T Size;
        REQUESTER_TYPE CallerType;
        union
        {
            struct
            {
                SIZE_T ProcessImageNameOffset; // PWSTR
                ULONG ProcessId;
                ULONG ServiceTag;
            } DUMMYSTRUCTNAME;
            struct
            {
                SIZE_T DeviceDescriptionOffset; // PWSTR
                SIZE_T DevicePathOffset; // PWSTR
            } DUMMYSTRUCTNAME;
        } DUMMYUNIONNAME;
        SIZE_T ReasonOffset; // PCOUNTED_REASON_CONTEXT_RELATIVE
    } DIAGNOSTIC_BUFFER, * PDIAGNOSTIC_BUFFER;

    typedef struct _WAKE_TIMER_INFO
    {
        SIZE_T OffsetToNext;
        ULARGE_INTEGER DueTime;
        ULONG Period;
        DIAGNOSTIC_BUFFER ReasonContext;
    } WAKE_TIMER_INFO, * PWAKE_TIMER_INFO;

    // rev
    typedef struct _PROCESSOR_PERF_CAP_HV
    {
        ULONG Version;
        ULONG InitialApicId;
        ULONG Ppc;
        ULONG Tpc;
        ULONG ThermalCap;
    } PROCESSOR_PERF_CAP_HV, * PPROCESSOR_PERF_CAP_HV;

    typedef struct PROCESSOR_IDLE_TIMES
    {
        ULONG64 StartTime;
        ULONG64 EndTime;
        ULONG Reserved[4];
    } PROCESSOR_IDLE_TIMES, * PPROCESSOR_IDLE_TIMES;

    _Function_class_(PROCESSOR_IDLE_HANDLER)
        typedef NTSTATUS(FASTCALL PROCESSOR_IDLE_HANDLER)(
            _In_ ULONG_PTR Context,
            _Inout_ PPROCESSOR_IDLE_TIMES IdleTimes
            );

    typedef PROCESSOR_IDLE_HANDLER* PPROCESSOR_IDLE_HANDLER;

#define PROCESSOR_STATE_TYPE_PERFORMANCE    0x1
#define PROCESSOR_STATE_TYPE_THROTTLE       0x2

#define IDLE_STATE_FLAGS_C1_HLT     0x01        // describes C1 only
#define IDLE_STATE_FLAGS_C1_IO_HLT  0x02        // describes C1 only
#define IDLE_STATE_FLAGS_IO         0x04        // describes C2 and C3 only
#define IDLE_STATE_FLAGS_MWAIT      0x08        // describes C1, C2, C3, C4, ...

    typedef struct _PROCESSOR_IDLE_STATE
    {
        UCHAR StateType;
        ULONG StateFlags;
        ULONG HardwareLatency;
        ULONG Power;
        ULONG_PTR Context;
        PPROCESSOR_IDLE_HANDLER Handler;
    } PROCESSOR_IDLE_STATE, * PPROCESSOR_IDLE_STATE;

    typedef struct _PROCESSOR_IDLE_STATES
    {
        ULONG Size;
        ULONG Revision;
        ULONG Count;
        ULONG Type;
        KAFFINITY TargetProcessors;
        PROCESSOR_IDLE_STATE State[ANYSIZE_ARRAY];
    } PROCESSOR_IDLE_STATES, * PPROCESSOR_IDLE_STATES;

    // rev
    typedef struct _PROCESSOR_LOAD
    {
        PROCESSOR_NUMBER ProcessorNumber;
        UCHAR BusyPercentage;
        UCHAR FrequencyPercentage;
        USHORT Padding;
    } PROCESSOR_LOAD, * PPROCESSOR_LOAD;

    // rev
    typedef struct _PROCESSOR_CAP
    {
        ULONG Version;
        PROCESSOR_NUMBER ProcessorNumber;
        ULONG PlatformCap;
        ULONG ThermalCap;
        ULONG LimitReasons;
    } PROCESSOR_CAP, * PPROCESSOR_CAP;

    typedef struct _PO_WAKE_SOURCE_INFO
    {
        ULONG Count;
        ULONG Offsets[ANYSIZE_ARRAY]; // POWER_WAKE_SOURCE_HEADER, POWER_WAKE_SOURCE_INTERNAL, POWER_WAKE_SOURCE_TIMER, POWER_WAKE_SOURCE_FIXED
    } PO_WAKE_SOURCE_INFO, * PPO_WAKE_SOURCE_INFO;

    typedef struct _PO_WAKE_SOURCE_HISTORY
    {
        ULONG Count;
        ULONG Offsets[ANYSIZE_ARRAY]; // POWER_WAKE_SOURCE_HEADER, POWER_WAKE_SOURCE_INTERNAL, POWER_WAKE_SOURCE_TIMER, POWER_WAKE_SOURCE_FIXED
    } PO_WAKE_SOURCE_HISTORY, * PPO_WAKE_SOURCE_HISTORY;

    typedef enum _PO_WAKE_SOURCE_TYPE
    {
        DeviceWakeSourceType = 0,
        FixedWakeSourceType = 1,
        TimerWakeSourceType = 2,
        TimerPresumedWakeSourceType = 3,
        InternalWakeSourceType = 4
    } PO_WAKE_SOURCE_TYPE, * PPO_WAKE_SOURCE_TYPE;

    typedef enum _PO_INTERNAL_WAKE_SOURCE_TYPE
    {
        InternalWakeSourceDozeToHibernate = 0,
        InternalWakeSourcePredictedUserPresence = 1
    } PO_INTERNAL_WAKE_SOURCE_TYPE;

    typedef enum _PO_FIXED_WAKE_SOURCE_TYPE
    {
        FixedWakeSourcePowerButton = 0,
        FixedWakeSourceSleepButton = 1,
        FixedWakeSourceRtc = 2,
        FixedWakeSourceDozeToHibernate = 3
    } PO_FIXED_WAKE_SOURCE_TYPE, * PPO_FIXED_WAKE_SOURCE_TYPE;

    typedef struct _PO_WAKE_SOURCE_HEADER
    {
        PO_WAKE_SOURCE_TYPE Type;
        ULONG Size;
    } PO_WAKE_SOURCE_HEADER, * PPO_WAKE_SOURCE_HEADER;

    typedef struct _PO_WAKE_SOURCE_DEVICE
    {
        PO_WAKE_SOURCE_HEADER Header;
        WCHAR InstancePath[ANYSIZE_ARRAY];
    } PO_WAKE_SOURCE_DEVICE, * PPO_WAKE_SOURCE_DEVICE;

    typedef struct _PO_WAKE_SOURCE_FIXED
    {
        PO_WAKE_SOURCE_HEADER Header;
        PO_FIXED_WAKE_SOURCE_TYPE FixedWakeSourceType;
    } PO_WAKE_SOURCE_FIXED, * PPO_WAKE_SOURCE_FIXED;

    typedef struct _PO_WAKE_SOURCE_INTERNAL
    {
        PO_WAKE_SOURCE_HEADER Header;
        PO_INTERNAL_WAKE_SOURCE_TYPE InternalWakeSourceType;
    } PO_WAKE_SOURCE_INTERNAL, * PPO_WAKE_SOURCE_INTERNAL;

    typedef struct _PO_WAKE_SOURCE_TIMER
    {
        PO_WAKE_SOURCE_HEADER Header;
        DIAGNOSTIC_BUFFER Reason;
    } PO_WAKE_SOURCE_TIMER, * PPO_WAKE_SOURCE_TIMER;

    // The number of supported request types per version
#define POWER_REQUEST_SUPPORTED_TYPES_V1 3 // Windows 7
#define POWER_REQUEST_SUPPORTED_TYPES_V2 9 // Windows 8
#define POWER_REQUEST_SUPPORTED_TYPES_V3 5 // Windows 8.1 and Windows 10 TH1-TH2
#define POWER_REQUEST_SUPPORTED_TYPES_V4 6 // Windows 10 RS1+

    typedef struct _POWER_REQUEST
    {
        union
        {
            struct
            {
                ULONG SupportedRequestMask;
                ULONG PowerRequestCount[POWER_REQUEST_SUPPORTED_TYPES_V1];
                DIAGNOSTIC_BUFFER DiagnosticBuffer;
            } V1;
#if (PHNT_VERSION >= PHNT_WIN8)
            struct
            {
                ULONG SupportedRequestMask;
                ULONG PowerRequestCount[POWER_REQUEST_SUPPORTED_TYPES_V2];
                DIAGNOSTIC_BUFFER DiagnosticBuffer;
            } V2;
#endif
#if (PHNT_VERSION >= PHNT_WINBLUE)
            struct
            {
                ULONG SupportedRequestMask;
                ULONG PowerRequestCount[POWER_REQUEST_SUPPORTED_TYPES_V3];
                DIAGNOSTIC_BUFFER DiagnosticBuffer;
            } V3;
#endif
#if (PHNT_VERSION >= PHNT_REDSTONE)
            struct
            {
                ULONG SupportedRequestMask;
                ULONG PowerRequestCount[POWER_REQUEST_SUPPORTED_TYPES_V4];
                DIAGNOSTIC_BUFFER DiagnosticBuffer;
            } V4;
#endif
        };
    } POWER_REQUEST, * PPOWER_REQUEST;

    typedef struct _POWER_REQUEST_LIST
    {
        ULONG_PTR Count;
        ULONG_PTR PowerRequestOffsets[ANYSIZE_ARRAY]; // PPOWER_REQUEST
    } POWER_REQUEST_LIST, * PPOWER_REQUEST_LIST;

    typedef enum _POWER_STATE_HANDLER_TYPE
    {
        PowerStateSleeping1 = 0,
        PowerStateSleeping2 = 1,
        PowerStateSleeping3 = 2,
        PowerStateSleeping4 = 3,
        PowerStateShutdownOff = 4,
        PowerStateShutdownReset = 5,
        PowerStateSleeping4Firmware = 6,
        PowerStateMaximum = 7
    } POWER_STATE_HANDLER_TYPE, * PPOWER_STATE_HANDLER_TYPE;

    typedef NTSTATUS(NTAPI* PENTER_STATE_SYSTEM_HANDLER)(
        _In_ PVOID SystemContext
        );

    typedef NTSTATUS(NTAPI* PENTER_STATE_HANDLER)(
        _In_ PVOID Context,
        _In_opt_ PENTER_STATE_SYSTEM_HANDLER SystemHandler,
        _In_ PVOID SystemContext,
        _In_ LONG NumberProcessors,
        _In_ LONG volatile* Number
        );

    typedef struct _POWER_STATE_HANDLER
    {
        POWER_STATE_HANDLER_TYPE Type;
        BOOLEAN RtcWake;
        UCHAR Spare[3];
        PENTER_STATE_HANDLER Handler;
        PVOID Context;
    } POWER_STATE_HANDLER, * PPOWER_STATE_HANDLER;

    typedef NTSTATUS(NTAPI* PENTER_STATE_NOTIFY_HANDLER)(
        _In_ POWER_STATE_HANDLER_TYPE State,
        _In_ PVOID Context,
        _In_ BOOLEAN Entering
        );

    typedef struct _POWER_STATE_NOTIFY_HANDLER
    {
        PENTER_STATE_NOTIFY_HANDLER Handler;
        PVOID Context;
    } POWER_STATE_NOTIFY_HANDLER, * PPOWER_STATE_NOTIFY_HANDLER;

    typedef struct _POWER_REQUEST_ACTION_INTERNAL
    {
        PVOID PowerRequestPointer;
        POWER_REQUEST_TYPE_INTERNAL RequestType;
        BOOLEAN SetAction;
    } POWER_REQUEST_ACTION_INTERNAL, * PPOWER_REQUEST_ACTION_INTERNAL;

    typedef enum _POWER_INFORMATION_LEVEL_INTERNAL
    {
        PowerInternalAcpiInterfaceRegister,
        PowerInternalS0LowPowerIdleInfo, // POWER_S0_LOW_POWER_IDLE_INFO
        PowerInternalReapplyBrightnessSettings,
        PowerInternalUserAbsencePrediction, // POWER_USER_ABSENCE_PREDICTION
        PowerInternalUserAbsencePredictionCapability, // POWER_USER_ABSENCE_PREDICTION_CAPABILITY
        PowerInternalPoProcessorLatencyHint, // POWER_PROCESSOR_LATENCY_HINT
        PowerInternalStandbyNetworkRequest, // POWER_STANDBY_NETWORK_REQUEST (requires PopNetBIServiceSid)
        PowerInternalDirtyTransitionInformation, // out: BOOLEAN
        PowerInternalSetBackgroundTaskState, // POWER_SET_BACKGROUND_TASK_STATE
        PowerInternalTtmOpenTerminal,
        PowerInternalTtmCreateTerminal, // 10
        PowerInternalTtmEvacuateDevices,
        PowerInternalTtmCreateTerminalEventQueue,
        PowerInternalTtmGetTerminalEvent,
        PowerInternalTtmSetDefaultDeviceAssignment,
        PowerInternalTtmAssignDevice,
        PowerInternalTtmSetDisplayState,
        PowerInternalTtmSetDisplayTimeouts,
        PowerInternalBootSessionStandbyActivationInformation, // out: POWER_BOOT_SESSION_STANDBY_ACTIVATION_INFO
        PowerInternalSessionPowerState, // in: POWER_SESSION_POWER_STATE
        PowerInternalSessionTerminalInput, // 20
        PowerInternalSetWatchdog,
        PowerInternalPhysicalPowerButtonPressInfoAtBoot,
        PowerInternalExternalMonitorConnected,
        PowerInternalHighPrecisionBrightnessSettings,
        PowerInternalWinrtScreenToggle,
        PowerInternalPpmQosDisable,
        PowerInternalTransitionCheckpoint,
        PowerInternalInputControllerState,
        PowerInternalFirmwareResetReason,
        PowerInternalPpmSchedulerQosSupport, // out: POWER_INTERNAL_PROCESSOR_QOS_SUPPORT // 30
        PowerInternalBootStatGet,
        PowerInternalBootStatSet,
        PowerInternalCallHasNotReturnedWatchdog,
        PowerInternalBootStatCheckIntegrity,
        PowerInternalBootStatRestoreDefaults, // in: void
        PowerInternalHostEsStateUpdate, // in: POWER_INTERNAL_HOST_ENERGY_SAVER_STATE
        PowerInternalGetPowerActionState, // out: ULONG
        PowerInternalBootStatUnlock,
        PowerInternalWakeOnVoiceState,
        PowerInternalDeepSleepBlock, // 40
        PowerInternalIsPoFxDevice,
        PowerInternalPowerTransitionExtensionAtBoot,
        PowerInternalProcessorBrandedFrequency, // in: POWER_INTERNAL_PROCESSOR_BRANDED_FREQENCY_INPUT, out: POWER_INTERNAL_PROCESSOR_BRANDED_FREQENCY_OUTPUT
        PowerInternalTimeBrokerExpirationReason,
        PowerInternalNotifyUserShutdownStatus,
        PowerInternalPowerRequestTerminalCoreWindow,
        PowerInternalProcessorIdleVeto,
        PowerInternalPlatformIdleVeto,
        PowerInternalIsLongPowerButtonBugcheckEnabled,
        PowerInternalAutoChkCausedReboot, // 50
        PowerInternalSetWakeAlarmOverride,

        PowerInternalDirectedFxAddTestDevice = 53,
        PowerInternalDirectedFxRemoveTestDevice,

        PowerInternalDirectedFxSetMode = 56,
        PowerInternalRegisterPowerPlane,
        PowerInternalSetDirectedDripsFlags,
        PowerInternalClearDirectedDripsFlags,
        PowerInternalRetrieveHiberFileResumeContext, // 60
        PowerInternalReadHiberFilePage,
        PowerInternalLastBootSucceeded, // out: BOOLEAN
        PowerInternalQuerySleepStudyHelperRoutineBlock,
        PowerInternalDirectedDripsQueryCapabilities,
        PowerInternalClearConstraints,
        PowerInternalSoftParkVelocityEnabled,
        PowerInternalQueryIntelPepCapabilities,
        PowerInternalGetSystemIdleLoopEnablement, // since WIN11
        PowerInternalGetVmPerfControlSupport,
        PowerInternalGetVmPerfControlConfig, // 70
        PowerInternalSleepDetailedDiagUpdate,
        PowerInternalProcessorClassFrequencyBandsStats,
        PowerInternalHostGlobalUserPresenceStateUpdate,
        PowerInternalCpuNodeIdleIntervalStats,
        PowerInternalClassIdleIntervalStats,
        PowerInternalCpuNodeConcurrencyStats,
        PowerInternalClassConcurrencyStats,
        PowerInternalQueryProcMeasurementCapabilities,
        PowerInternalQueryProcMeasurementValues,
        PowerInternalPrepareForSystemInitiatedReboot, // 80
        PowerInternalGetAdaptiveSessionState,
        PowerInternalSetConsoleLockedState,
        PowerInternalOverrideSystemInitiatedRebootState,
        PowerInternalFanImpactStats,
        PowerInternalFanRpmBuckets,
        PowerInternalPowerBootAppDiagInfo, // out: POWER_INTERNAL_BOOTAPP_DIAGNOSTIC
        PowerInternalUnregisterShutdownNotification, // since 22H1
        PowerInternalManageTransitionStateRecord,
        PowerInternalGetAcpiTimeAndAlarmCapabilities, // since 22H2
        PowerInternalSuspendResumeRequest,
        PowerInformationInternalMaximum
    } POWER_INFORMATION_LEVEL_INTERNAL;

    typedef enum _POWER_S0_DISCONNECTED_REASON
    {
        PoS0DisconnectedReasonNone,
        PoS0DisconnectedReasonNonCompliantNic,
        PoS0DisconnectedReasonSettingPolicy,
        PoS0DisconnectedReasonEnforceDsPolicy,
        PoS0DisconnectedReasonCsChecksFailed,
        PoS0DisconnectedReasonSmartStandby,
        PoS0DisconnectedReasonMaximum
    } POWER_S0_DISCONNECTED_REASON;

    typedef struct _POWER_S0_LOW_POWER_IDLE_INFO
    {
        POWER_S0_DISCONNECTED_REASON DisconnectedReason;
        union
        {
            BOOLEAN Storage : 1;
            BOOLEAN WiFi : 1;
            BOOLEAN Mbn : 1;
            BOOLEAN Ethernet : 1;
            BOOLEAN Reserved : 4;
            UCHAR AsUCHAR;
        } CsDeviceCompliance;
        union
        {
            BOOLEAN DisconnectInStandby : 1;
            BOOLEAN EnforceDs : 1;
            BOOLEAN Reserved : 6;
            UCHAR AsUCHAR;
        } Policy;
    } POWER_S0_LOW_POWER_IDLE_INFO, * PPOWER_S0_LOW_POWER_IDLE_INFO;

    typedef struct _POWER_INFORMATION_INTERNAL_HEADER
    {
        POWER_INFORMATION_LEVEL_INTERNAL InternalType;
        ULONG Version;
    } POWER_INFORMATION_INTERNAL_HEADER, * PPOWER_INFORMATION_INTERNAL_HEADER;

    typedef struct _POWER_USER_ABSENCE_PREDICTION
    {
        POWER_INFORMATION_INTERNAL_HEADER Header;
        LARGE_INTEGER ReturnTime;
    } POWER_USER_ABSENCE_PREDICTION, * PPOWER_USER_ABSENCE_PREDICTION;

    typedef struct _POWER_USER_ABSENCE_PREDICTION_CAPABILITY
    {
        BOOLEAN AbsencePredictionCapability;
    } POWER_USER_ABSENCE_PREDICTION_CAPABILITY, * PPOWER_USER_ABSENCE_PREDICTION_CAPABILITY;

    // rev
    typedef struct _POWER_PROCESSOR_LATENCY_HINT
    {
        POWER_INFORMATION_INTERNAL_HEADER PowerInformationInternalHeader;
        ULONG Type;
    } POWER_PROCESSOR_LATENCY_HINT, * PPO_PROCESSOR_LATENCY_HINT;

    // rev
    typedef struct _POWER_STANDBY_NETWORK_REQUEST
    {
        POWER_INFORMATION_INTERNAL_HEADER PowerInformationInternalHeader;
        BOOLEAN Active;
    } POWER_STANDBY_NETWORK_REQUEST, * PPOWER_STANDBY_NETWORK_REQUEST;

    // rev
    typedef struct _POWER_SET_BACKGROUND_TASK_STATE
    {
        POWER_INFORMATION_INTERNAL_HEADER PowerInformationInternalHeader;
        BOOLEAN Engaged;
    } POWER_SET_BACKGROUND_TASK_STATE, * PPOWER_SET_BACKGROUND_TASK_STATE;

    // rev
    typedef struct _POWER_BOOT_SESSION_STANDBY_ACTIVATION_INFO
    {
        ULONG StandbyTotalTime;
        ULONG DripsTotalTime;
        ULONG ActivatorClientTotalActiveTime;
        ULONG PerActivatorClientTotalActiveTime[98];
    } POWER_BOOT_SESSION_STANDBY_ACTIVATION_INFO, * PPOWER_BOOT_SESSION_STANDBY_ACTIVATION_INFO;

    // rev
    typedef struct _POWER_SESSION_POWER_STATE
    {
        POWER_INFORMATION_INTERNAL_HEADER Header;
        ULONG SessionId;
        BOOLEAN On;
        BOOLEAN IsConsole;
        POWER_MONITOR_REQUEST_REASON RequestReason;
    } POWER_SESSION_POWER_STATE, * PPOWER_SESSION_POWER_STATE;

    // rev
    typedef struct _POWER_INTERNAL_PROCESSOR_QOS_SUPPORT
    {
        BOOLEAN QosSupportedAndConfigured;
        BOOLEAN SchedulerDirectedPerfStatesSupported;
        BOOLEAN QosGroupPolicyDisable;
    } POWER_INTERNAL_PROCESSOR_QOS_SUPPORT, * PPOWER_INTERNAL_PROCESSOR_QOS_SUPPORT;

    // rev
    typedef struct _POWER_INTERNAL_HOST_ENERGY_SAVER_STATE
    {
        POWER_INFORMATION_INTERNAL_HEADER Header;
        BOOLEAN EsEnabledOnHost;
    } POWER_INTERNAL_HOST_ENERGY_SAVER_STATE, * PPOWER_INTERNAL_HOST_ENERGY_SAVER_STATE;

    // rev
    typedef struct _POWER_INTERNAL_PROCESSOR_BRANDED_FREQENCY_INPUT
    {
        POWER_INFORMATION_LEVEL_INTERNAL InternalType;
        PROCESSOR_NUMBER ProcessorNumber; // ULONG_MAX
    } POWER_INTERNAL_PROCESSOR_BRANDED_FREQENCY_INPUT, * PPOWER_INTERNAL_PROCESSOR_BRANDED_FREQENCY_INPUT;

    // rev
    typedef struct _POWER_INTERNAL_PROCESSOR_BRANDED_FREQENCY_OUTPUT
    {
        ULONG Version;
        ULONG NominalFrequency; // if (Domain) Prcb->PowerState.CheckContext.Domain.NominalFrequency else Prcb->MHz
    } POWER_INTERNAL_PROCESSOR_BRANDED_FREQENCY_OUTPUT, * PPOWER_INTERNAL_PROCESSOR_BRANDED_FREQENCY_OUTPUT;

    // rev
    typedef struct _POWER_INTERNAL_BOOTAPP_DIAGNOSTIC
    {
        ULONG BootAppErrorDiagCode; // bcdedit last status
        ULONG BootAppFailureStatus; // bcdedit last status
    } POWER_INTERNAL_BOOTAPP_DIAGNOSTIC, * PPOWER_INTERNAL_BOOTAPP_DIAGNOSTIC;

#if (PHNT_MODE != PHNT_MODE_KERNEL)

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtPowerInformation(
            _In_ POWER_INFORMATION_LEVEL InformationLevel,
            _In_reads_bytes_opt_(InputBufferLength) PVOID InputBuffer,
            _In_ ULONG InputBufferLength,
            _Out_writes_bytes_opt_(OutputBufferLength) PVOID OutputBuffer,
            _In_ ULONG OutputBufferLength
        );

#endif

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtSetThreadExecutionState(
            _In_ EXECUTION_STATE NewFlags, // ES_* flags
            _Out_ EXECUTION_STATE* PreviousFlags
        );

#if (PHNT_VERSION < PHNT_WIN7)
    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtRequestWakeupLatency(
            _In_ LATENCY_TIME latency
        );
#endif

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtInitiatePowerAction(
            _In_ POWER_ACTION SystemAction,
            _In_ SYSTEM_POWER_STATE LightestSystemState,
            _In_ ULONG Flags, // POWER_ACTION_* flags
            _In_ BOOLEAN Asynchronous
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtSetSystemPowerState(
            _In_ POWER_ACTION SystemAction,
            _In_ SYSTEM_POWER_STATE LightestSystemState,
            _In_ ULONG Flags // POWER_ACTION_* flags
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtGetDevicePowerState(
            _In_ HANDLE Device,
            _Out_ PDEVICE_POWER_STATE State
        );

    NTSYSCALLAPI
        BOOLEAN
        NTAPI
        NtIsSystemResumeAutomatic(
            VOID
        );

#endif
    /*
     * Registry support functions
     *
     * This file is part of System Informer.
     */

#ifndef _NTREGAPI_H
#define _NTREGAPI_H

     // Boot condition flags (NtInitializeRegistry)

#define REG_INIT_BOOT_SM 0x0000
#define REG_INIT_BOOT_SETUP 0x0001
#define REG_INIT_BOOT_ACCEPTED_BASE 0x0002
#define REG_INIT_BOOT_ACCEPTED_MAX REG_INIT_BOOT_ACCEPTED_BASE + 999

#define REG_MAX_KEY_VALUE_NAME_LENGTH 32767
#define REG_MAX_KEY_NAME_LENGTH 512

    typedef enum _KEY_INFORMATION_CLASS
    {
        KeyBasicInformation, // KEY_BASIC_INFORMATION
        KeyNodeInformation, // KEY_NODE_INFORMATION
        KeyFullInformation, // KEY_FULL_INFORMATION
        KeyNameInformation, // KEY_NAME_INFORMATION
        KeyCachedInformation, // KEY_CACHED_INFORMATION
        KeyFlagsInformation, // KEY_FLAGS_INFORMATION
        KeyVirtualizationInformation, // KEY_VIRTUALIZATION_INFORMATION
        KeyHandleTagsInformation, // KEY_HANDLE_TAGS_INFORMATION
        KeyTrustInformation, // KEY_TRUST_INFORMATION
        KeyLayerInformation, // KEY_LAYER_INFORMATION
        MaxKeyInfoClass
    } KEY_INFORMATION_CLASS;

    typedef struct _KEY_BASIC_INFORMATION
    {
        LARGE_INTEGER LastWriteTime;
        ULONG TitleIndex;
        ULONG NameLength;
        _Field_size_bytes_(NameLength) WCHAR Name[1];
    } KEY_BASIC_INFORMATION, * PKEY_BASIC_INFORMATION;

    typedef struct _KEY_NODE_INFORMATION
    {
        LARGE_INTEGER LastWriteTime;
        ULONG TitleIndex;
        ULONG ClassOffset;
        ULONG ClassLength;
        ULONG NameLength;
        _Field_size_bytes_(NameLength) WCHAR Name[1];
        // ...
        // WCHAR Class[1];
    } KEY_NODE_INFORMATION, * PKEY_NODE_INFORMATION;

    typedef struct _KEY_FULL_INFORMATION
    {
        LARGE_INTEGER LastWriteTime;
        ULONG TitleIndex;
        ULONG ClassOffset;
        ULONG ClassLength;
        ULONG SubKeys;
        ULONG MaxNameLength;
        ULONG MaxClassLength;
        ULONG Values;
        ULONG MaxValueNameLength;
        ULONG MaxValueDataLength;
        WCHAR Class[1];
    } KEY_FULL_INFORMATION, * PKEY_FULL_INFORMATION;

    typedef struct _KEY_NAME_INFORMATION
    {
        ULONG NameLength;
        _Field_size_bytes_(NameLength) WCHAR Name[1];
    } KEY_NAME_INFORMATION, * PKEY_NAME_INFORMATION;

    typedef struct _KEY_CACHED_INFORMATION
    {
        LARGE_INTEGER LastWriteTime;
        ULONG TitleIndex;
        ULONG SubKeys;
        ULONG MaxNameLength;
        ULONG Values;
        ULONG MaxValueNameLength;
        ULONG MaxValueDataLength;
        ULONG NameLength;
        _Field_size_bytes_(NameLength) WCHAR Name[1];
    } KEY_CACHED_INFORMATION, * PKEY_CACHED_INFORMATION;

    // rev
#define REG_FLAG_VOLATILE 0x0001
#define REG_FLAG_LINK 0x0002

// msdn
#define REG_KEY_DONT_VIRTUALIZE 0x0002
#define REG_KEY_DONT_SILENT_FAIL 0x0004
#define REG_KEY_RECURSE_FLAG 0x0008

// private
    typedef struct _KEY_FLAGS_INFORMATION
    {
        ULONG Wow64Flags;
        ULONG KeyFlags; // REG_FLAG_*
        ULONG ControlFlags; // REG_KEY_*
    } KEY_FLAGS_INFORMATION, * PKEY_FLAGS_INFORMATION;

    typedef struct _KEY_VIRTUALIZATION_INFORMATION
    {
        ULONG VirtualizationCandidate : 1; // Tells whether the key is part of the virtualization namespace scope (only HKLM\Software for now).
        ULONG VirtualizationEnabled : 1; // Tells whether virtualization is enabled on this key. Can be 1 only if above flag is 1.
        ULONG VirtualTarget : 1; // Tells if the key is a virtual key. Can be 1 only if above 2 are 0. Valid only on the virtual store key handles.
        ULONG VirtualStore : 1; // Tells if the key is a part of the virtual store path. Valid only on the virtual store key handles.
        ULONG VirtualSource : 1; // Tells if the key has ever been virtualized, can be 1 only if VirtualizationCandidate is 1.
        ULONG Reserved : 27;
    } KEY_VIRTUALIZATION_INFORMATION, * PKEY_VIRTUALIZATION_INFORMATION;

    // private
    typedef struct _KEY_TRUST_INFORMATION
    {
        ULONG TrustedKey : 1;
        ULONG Reserved : 31;
    } KEY_TRUST_INFORMATION, * PKEY_TRUST_INFORMATION;

    // private
    typedef struct _KEY_LAYER_INFORMATION
    {
        ULONG IsTombstone : 1;
        ULONG IsSupersedeLocal : 1;
        ULONG IsSupersedeTree : 1;
        ULONG ClassIsInherited : 1;
        ULONG Reserved : 28;
    } KEY_LAYER_INFORMATION, * PKEY_LAYER_INFORMATION;

    typedef enum _KEY_SET_INFORMATION_CLASS
    {
        KeyWriteTimeInformation, // KEY_WRITE_TIME_INFORMATION
        KeyWow64FlagsInformation, // KEY_WOW64_FLAGS_INFORMATION
        KeyControlFlagsInformation, // KEY_CONTROL_FLAGS_INFORMATION
        KeySetVirtualizationInformation, // KEY_SET_VIRTUALIZATION_INFORMATION
        KeySetDebugInformation,
        KeySetHandleTagsInformation, // KEY_HANDLE_TAGS_INFORMATION
        KeySetLayerInformation, // KEY_SET_LAYER_INFORMATION
        MaxKeySetInfoClass
    } KEY_SET_INFORMATION_CLASS;

    typedef struct _KEY_WRITE_TIME_INFORMATION
    {
        LARGE_INTEGER LastWriteTime;
    } KEY_WRITE_TIME_INFORMATION, * PKEY_WRITE_TIME_INFORMATION;

    typedef struct _KEY_WOW64_FLAGS_INFORMATION
    {
        ULONG UserFlags;
    } KEY_WOW64_FLAGS_INFORMATION, * PKEY_WOW64_FLAGS_INFORMATION;

    typedef struct _KEY_HANDLE_TAGS_INFORMATION
    {
        ULONG HandleTags;
    } KEY_HANDLE_TAGS_INFORMATION, * PKEY_HANDLE_TAGS_INFORMATION;

    typedef struct _KEY_SET_LAYER_INFORMATION
    {
        ULONG IsTombstone : 1;
        ULONG IsSupersedeLocal : 1;
        ULONG IsSupersedeTree : 1;
        ULONG ClassIsInherited : 1;
        ULONG Reserved : 28;
    } KEY_SET_LAYER_INFORMATION, * PKEY_SET_LAYER_INFORMATION;

    typedef struct _KEY_CONTROL_FLAGS_INFORMATION
    {
        ULONG ControlFlags;
    } KEY_CONTROL_FLAGS_INFORMATION, * PKEY_CONTROL_FLAGS_INFORMATION;

    typedef struct _KEY_SET_VIRTUALIZATION_INFORMATION
    {
        ULONG VirtualTarget : 1;
        ULONG VirtualStore : 1;
        ULONG VirtualSource : 1; // true if key has been virtualized at least once
        ULONG Reserved : 29;
    } KEY_SET_VIRTUALIZATION_INFORMATION, * PKEY_SET_VIRTUALIZATION_INFORMATION;

    typedef enum _KEY_VALUE_INFORMATION_CLASS
    {
        KeyValueBasicInformation, // KEY_VALUE_BASIC_INFORMATION
        KeyValueFullInformation, // KEY_VALUE_FULL_INFORMATION
        KeyValuePartialInformation, // KEY_VALUE_PARTIAL_INFORMATION
        KeyValueFullInformationAlign64,
        KeyValuePartialInformationAlign64,  // KEY_VALUE_PARTIAL_INFORMATION_ALIGN64
        KeyValueLayerInformation, // KEY_VALUE_LAYER_INFORMATION
        MaxKeyValueInfoClass
    } KEY_VALUE_INFORMATION_CLASS;

    typedef struct _KEY_VALUE_BASIC_INFORMATION
    {
        ULONG TitleIndex;
        ULONG Type;
        ULONG NameLength;
        _Field_size_bytes_(NameLength) WCHAR Name[1];
    } KEY_VALUE_BASIC_INFORMATION, * PKEY_VALUE_BASIC_INFORMATION;

    typedef struct _KEY_VALUE_FULL_INFORMATION
    {
        ULONG TitleIndex;
        ULONG Type;
        ULONG DataOffset;
        ULONG DataLength;
        ULONG NameLength;
        _Field_size_bytes_(NameLength) WCHAR Name[1];
        // ...
        // UCHAR Data[1];
    } KEY_VALUE_FULL_INFORMATION, * PKEY_VALUE_FULL_INFORMATION;

    typedef struct _KEY_VALUE_PARTIAL_INFORMATION
    {
        ULONG TitleIndex;
        ULONG Type;
        ULONG DataLength;
        _Field_size_bytes_(DataLength) UCHAR Data[1];
    } KEY_VALUE_PARTIAL_INFORMATION, * PKEY_VALUE_PARTIAL_INFORMATION;

    typedef struct _KEY_VALUE_PARTIAL_INFORMATION_ALIGN64
    {
        ULONG Type;
        ULONG DataLength;
        _Field_size_bytes_(DataLength) UCHAR Data[1];
    } KEY_VALUE_PARTIAL_INFORMATION_ALIGN64, * PKEY_VALUE_PARTIAL_INFORMATION_ALIGN64;

    // private
    typedef struct _KEY_VALUE_LAYER_INFORMATION
    {
        ULONG IsTombstone : 1;
        ULONG Reserved : 31;
    } KEY_VALUE_LAYER_INFORMATION, * PKEY_VALUE_LAYER_INFORMATION;

    // private
    typedef enum _CM_EXTENDED_PARAMETER_TYPE
    {
        CmExtendedParameterInvalidType,
        CmExtendedParameterTrustClassKey,
        CmExtendedParameterEvent,
        CmExtendedParameterFileAccessToken,
        CmExtendedParameterMax,
    } CM_EXTENDED_PARAMETER_TYPE;

#define CM_EXTENDED_PARAMETER_TYPE_BITS 8

    // private
    typedef struct DECLSPEC_ALIGN(8) _CM_EXTENDED_PARAMETER
    {
        struct
        {
            ULONG64 Type : CM_EXTENDED_PARAMETER_TYPE_BITS;
            ULONG64 Reserved : 64 - CM_EXTENDED_PARAMETER_TYPE_BITS;
        };

        union
        {
            ULONG64 ULong64;
            PVOID Pointer;
            SIZE_T Size;
            HANDLE Handle;
            ULONG ULong;
            ACCESS_MASK AccessMask;
        };
    } CM_EXTENDED_PARAMETER, * PCM_EXTENDED_PARAMETER;

    typedef struct _KEY_VALUE_ENTRY
    {
        PUNICODE_STRING ValueName;
        ULONG DataLength;
        ULONG DataOffset;
        ULONG Type;
    } KEY_VALUE_ENTRY, * PKEY_VALUE_ENTRY;

    typedef enum _REG_ACTION
    {
        KeyAdded,
        KeyRemoved,
        KeyModified
    } REG_ACTION;

    typedef struct _REG_NOTIFY_INFORMATION
    {
        ULONG NextEntryOffset;
        REG_ACTION Action;
        ULONG KeyLength;
        _Field_size_bytes_(KeyLength) WCHAR Key[1];
    } REG_NOTIFY_INFORMATION, * PREG_NOTIFY_INFORMATION;

    typedef struct _KEY_PID_ARRAY
    {
        HANDLE ProcessId;
        UNICODE_STRING KeyName;
    } KEY_PID_ARRAY, * PKEY_PID_ARRAY;

    typedef struct _KEY_OPEN_SUBKEYS_INFORMATION
    {
        ULONG Count;
        KEY_PID_ARRAY KeyArray[1];
    } KEY_OPEN_SUBKEYS_INFORMATION, * PKEY_OPEN_SUBKEYS_INFORMATION;

    // Differencing registry & virtualization // since REDSTONE

    // rev
#define VR_DEVICE_NAME L"\\Device\\VRegDriver"

// rev
#define IOCTL_VR_INITIALIZE_JOB_FOR_VREG            CTL_CODE(FILE_DEVICE_UNKNOWN, 1, METHOD_BUFFERED, FILE_ANY_ACCESS) // in: VR_INITIALIZE_JOB_FOR_VREG
#define IOCTL_VR_LOAD_DIFFERENCING_HIVE             CTL_CODE(FILE_DEVICE_UNKNOWN, 2, METHOD_BUFFERED, FILE_ANY_ACCESS) // in: VR_LOAD_DIFFERENCING_HIVE
#define IOCTL_VR_CREATE_NAMESPACE_NODE              CTL_CODE(FILE_DEVICE_UNKNOWN, 3, METHOD_BUFFERED, FILE_ANY_ACCESS) // in: VR_CREATE_NAMESPACE_NODE
#define IOCTL_VR_MODIFY_FLAGS                       CTL_CODE(FILE_DEVICE_UNKNOWN, 4, METHOD_BUFFERED, FILE_ANY_ACCESS) // in: VR_MODIFY_FLAGS
#define IOCTL_VR_CREATE_MULTIPLE_NAMESPACE_NODES    CTL_CODE(FILE_DEVICE_UNKNOWN, 5, METHOD_BUFFERED, FILE_ANY_ACCESS) // in: VR_CREATE_MULTIPLE_NAMESPACE_NODES
#define IOCTL_VR_UNLOAD_DYNAMICALLY_LOADED_HIVES    CTL_CODE(FILE_DEVICE_UNKNOWN, 6, METHOD_BUFFERED, FILE_ANY_ACCESS) // in: VR_UNLOAD_DYNAMICALLY_LOADED_HIVES
#define IOCTL_VR_GET_VIRTUAL_ROOT_KEY               CTL_CODE(FILE_DEVICE_UNKNOWN, 7, METHOD_BUFFERED, FILE_ANY_ACCESS) // in: VR_GET_VIRTUAL_ROOT; out: VR_GET_VIRTUAL_ROOT_RESULT
#define IOCTL_VR_LOAD_DIFFERENCING_HIVE_FOR_HOST    CTL_CODE(FILE_DEVICE_UNKNOWN, 8, METHOD_BUFFERED, FILE_ANY_ACCESS) // in: VR_LOAD_DIFFERENCING_HIVE_FOR_HOST
#define IOCTL_VR_UNLOAD_DIFFERENCING_HIVE_FOR_HOST  CTL_CODE(FILE_DEVICE_UNKNOWN, 9, METHOD_BUFFERED, FILE_ANY_ACCESS) // in: VR_UNLOAD_DIFFERENCING_HIVE_FOR_HOST

// private
    typedef struct _VR_INITIALIZE_JOB_FOR_VREG
    {
        HANDLE Job;
    } VR_INITIALIZE_JOB_FOR_VREG, * PVR_INITIALIZE_JOB_FOR_VREG;

    // rev
#define VR_FLAG_INHERIT_TRUST_CLASS 0x00000001
#define VR_FLAG_WRITE_THROUGH_HIVE 0x00000002 // since REDSTONE2
#define VR_FLAG_LOCAL_MACHINE_TRUST_CLASS 0x00000004 // since 21H1

// rev + private
    typedef struct _VR_LOAD_DIFFERENCING_HIVE
    {
        HANDLE Job;
        ULONG NextLayerIsHost;
        ULONG Flags; // VR_FLAG_*
        ULONG LoadFlags; // NtLoadKeyEx flags
        WORD KeyPathLength;
        WORD HivePathLength;
        WORD NextLayerKeyPathLength;
        HANDLE FileAccessToken; // since 20H1
        WCHAR Strings[ANYSIZE_ARRAY];
        // ...
        // WCHAR KeyPath[1];
        // WCHAR HivePath[1];
        // WCHAR NextLayerKeyPath[1];
    } VR_LOAD_DIFFERENCING_HIVE, * PVR_LOAD_DIFFERENCING_HIVE;

    // rev + private
    typedef struct _VR_CREATE_NAMESPACE_NODE
    {
        HANDLE Job;
        WORD ContainerPathLength;
        WORD HostPathLength;
        ULONG Flags;
        ACCESS_MASK AccessMask; // since 20H1
        WCHAR Strings[ANYSIZE_ARRAY];
        // ...
        // WCHAR ContainerPath[1];
        // WCHAR HostPath[1];
    } VR_CREATE_NAMESPACE_NODE, * PVR_CREATE_NAMESPACE_NODE;

    // private
    typedef struct _VR_MODIFY_FLAGS
    {
        HANDLE Job;
        ULONG AddFlags;
        ULONG RemoveFlags;
    } VR_MODIFY_FLAGS, * PVR_MODIFY_FLAGS;

    // private
    typedef struct _NAMESPACE_NODE_DATA
    {
        ACCESS_MASK AccessMask;
        WORD ContainerPathLength;
        WORD HostPathLength;
        ULONG Flags;
        WCHAR Strings[ANYSIZE_ARRAY];
        // ...
        // WCHAR ContainerPath[1];
        // WCHAR HostPath[1];
    } NAMESPACE_NODE_DATA, * PNAMESPACE_NODE_DATA;

    // private
    typedef struct _VR_CREATE_MULTIPLE_NAMESPACE_NODES
    {
        HANDLE Job;
        ULONG NumNewKeys;
        NAMESPACE_NODE_DATA Keys[1];
    } VR_CREATE_MULTIPLE_NAMESPACE_NODES, * PVR_CREATE_MULTIPLE_NAMESPACE_NODES;

    // private
    typedef struct _VR_UNLOAD_DYNAMICALLY_LOADED_HIVES
    {
        HANDLE Job;
    } VR_UNLOAD_DYNAMICALLY_LOADED_HIVES, * PVR_UNLOAD_DYNAMICALLY_LOADED_HIVES;

    // rev
#define VR_KEY_COMROOT 0          // \Registry\ComRoot\Classes
#define VR_KEY_MACHINE_SOFTWARE 1 // \Registry\Machine\Software // since REDSTONE2
#define VR_KEY_CONTROL_SET 2      // \Registry\Machine\System\ControlSet001 // since REDSTONE2

// rev
    typedef struct _VR_GET_VIRTUAL_ROOT
    {
        HANDLE Job;
        ULONG Index; // VR_KEY_* // since REDSTONE2
    } VR_GET_VIRTUAL_ROOT, * PVR_GET_VIRTUAL_ROOT;

    // rev
    typedef struct _VR_GET_VIRTUAL_ROOT_RESULT
    {
        HANDLE Key;
    } VR_GET_VIRTUAL_ROOT_RESULT, * PVR_GET_VIRTUAL_ROOT_RESULT;

    // rev
    typedef struct _VR_LOAD_DIFFERENCING_HIVE_FOR_HOST
    {
        ULONG LoadFlags; // NtLoadKeyEx flags
        ULONG Flags; // VR_FLAG_* // since REDSTONE2
        WORD KeyPathLength;
        WORD HivePathLength;
        WORD NextLayerKeyPathLength;
        HANDLE FileAccessToken; // since 20H1
        WCHAR Strings[ANYSIZE_ARRAY];
        // ...
        // WCHAR KeyPath[1];
        // WCHAR HivePath[1];
        // WCHAR NextLayerKeyPath[1];
    } VR_LOAD_DIFFERENCING_HIVE_FOR_HOST, * PVR_LOAD_DIFFERENCING_HIVE_FOR_HOST;

    // rev
    typedef struct _VR_UNLOAD_DIFFERENCING_HIVE_FOR_HOST
    {
        ULONG Reserved;
        WORD TargetKeyPathLength;
        WCHAR TargetKeyPath[ANYSIZE_ARRAY];
    } VR_UNLOAD_DIFFERENCING_HIVE_FOR_HOST, * PVR_UNLOAD_DIFFERENCING_HIVE_FOR_HOST;

    // System calls

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtCreateKey(
            _Out_ PHANDLE KeyHandle,
            _In_ ACCESS_MASK DesiredAccess,
            _In_ POBJECT_ATTRIBUTES ObjectAttributes,
            _Reserved_ ULONG TitleIndex,
            _In_opt_ PUNICODE_STRING Class,
            _In_ ULONG CreateOptions,
            _Out_opt_ PULONG Disposition
        );

#if (PHNT_VERSION >= PHNT_VISTA)
    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtCreateKeyTransacted(
            _Out_ PHANDLE KeyHandle,
            _In_ ACCESS_MASK DesiredAccess,
            _In_ POBJECT_ATTRIBUTES ObjectAttributes,
            _Reserved_ ULONG TitleIndex,
            _In_opt_ PUNICODE_STRING Class,
            _In_ ULONG CreateOptions,
            _In_ HANDLE TransactionHandle,
            _Out_opt_ PULONG Disposition
        );
#endif

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtOpenKey(
            _Out_ PHANDLE KeyHandle,
            _In_ ACCESS_MASK DesiredAccess,
            _In_ POBJECT_ATTRIBUTES ObjectAttributes
        );

#if (PHNT_VERSION >= PHNT_VISTA)
    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtOpenKeyTransacted(
            _Out_ PHANDLE KeyHandle,
            _In_ ACCESS_MASK DesiredAccess,
            _In_ POBJECT_ATTRIBUTES ObjectAttributes,
            _In_ HANDLE TransactionHandle
        );
#endif

#if (PHNT_VERSION >= PHNT_WIN7)
    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtOpenKeyEx(
            _Out_ PHANDLE KeyHandle,
            _In_ ACCESS_MASK DesiredAccess,
            _In_ POBJECT_ATTRIBUTES ObjectAttributes,
            _In_ ULONG OpenOptions
        );
#endif

#if (PHNT_VERSION >= PHNT_WIN7)
    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtOpenKeyTransactedEx(
            _Out_ PHANDLE KeyHandle,
            _In_ ACCESS_MASK DesiredAccess,
            _In_ POBJECT_ATTRIBUTES ObjectAttributes,
            _In_ ULONG OpenOptions,
            _In_ HANDLE TransactionHandle
        );
#endif

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtDeleteKey(
            _In_ HANDLE KeyHandle
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtRenameKey(
            _In_ HANDLE KeyHandle,
            _In_ PUNICODE_STRING NewName
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtDeleteValueKey(
            _In_ HANDLE KeyHandle,
            _In_ PUNICODE_STRING ValueName
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtQueryKey(
            _In_ HANDLE KeyHandle,
            _In_ KEY_INFORMATION_CLASS KeyInformationClass,
            _Out_writes_bytes_opt_(Length) PVOID KeyInformation,
            _In_ ULONG Length,
            _Out_ PULONG ResultLength
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtSetInformationKey(
            _In_ HANDLE KeyHandle,
            _In_ KEY_SET_INFORMATION_CLASS KeySetInformationClass,
            _In_reads_bytes_(KeySetInformationLength) PVOID KeySetInformation,
            _In_ ULONG KeySetInformationLength
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtQueryValueKey(
            _In_ HANDLE KeyHandle,
            _In_ PUNICODE_STRING ValueName,
            _In_ KEY_VALUE_INFORMATION_CLASS KeyValueInformationClass,
            _Out_writes_bytes_opt_(Length) PVOID KeyValueInformation,
            _In_ ULONG Length,
            _Out_ PULONG ResultLength
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtSetValueKey(
            _In_ HANDLE KeyHandle,
            _In_ PUNICODE_STRING ValueName,
            _In_opt_ ULONG TitleIndex,
            _In_ ULONG Type,
            _In_reads_bytes_opt_(DataSize) PVOID Data,
            _In_ ULONG DataSize
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtQueryMultipleValueKey(
            _In_ HANDLE KeyHandle,
            _Inout_updates_(EntryCount) PKEY_VALUE_ENTRY ValueEntries,
            _In_ ULONG EntryCount,
            _Out_writes_bytes_(*BufferLength) PVOID ValueBuffer,
            _Inout_ PULONG BufferLength,
            _Out_opt_ PULONG RequiredBufferLength
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtEnumerateKey(
            _In_ HANDLE KeyHandle,
            _In_ ULONG Index,
            _In_ KEY_INFORMATION_CLASS KeyInformationClass,
            _Out_writes_bytes_opt_(Length) PVOID KeyInformation,
            _In_ ULONG Length,
            _Out_ PULONG ResultLength
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtEnumerateValueKey(
            _In_ HANDLE KeyHandle,
            _In_ ULONG Index,
            _In_ KEY_VALUE_INFORMATION_CLASS KeyValueInformationClass,
            _Out_writes_bytes_opt_(Length) PVOID KeyValueInformation,
            _In_ ULONG Length,
            _Out_ PULONG ResultLength
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtFlushKey(
            _In_ HANDLE KeyHandle
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtCompactKeys(
            _In_ ULONG Count,
            _In_reads_(Count) HANDLE KeyArray[]
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtCompressKey(
            _In_ HANDLE KeyHandle
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtLoadKey(
            _In_ POBJECT_ATTRIBUTES TargetKey,
            _In_ POBJECT_ATTRIBUTES SourceFile
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtLoadKey2(
            _In_ POBJECT_ATTRIBUTES TargetKey,
            _In_ POBJECT_ATTRIBUTES SourceFile,
            _In_ ULONG Flags
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtLoadKeyEx(
            _In_ POBJECT_ATTRIBUTES TargetKey,
            _In_ POBJECT_ATTRIBUTES SourceFile,
            _In_ ULONG Flags,
            _In_opt_ HANDLE TrustClassKey, // this and below were added on Win10
            _In_opt_ HANDLE Event,
            _In_opt_ ACCESS_MASK DesiredAccess,
            _Out_opt_ PHANDLE RootHandle,
            _Reserved_ PVOID Reserved // previously PIO_STATUS_BLOCK
        );

    // rev by tyranid
#if (PHNT_VERSION >= PHNT_20H1)
    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtLoadKey3(
            _In_ POBJECT_ATTRIBUTES TargetKey,
            _In_ POBJECT_ATTRIBUTES SourceFile,
            _In_ ULONG Flags,
            _In_reads_(ExtendedParameterCount) PCM_EXTENDED_PARAMETER ExtendedParameters,
            _In_ ULONG ExtendedParameterCount,
            _In_opt_ ACCESS_MASK DesiredAccess,
            _Out_opt_ PHANDLE RootHandle,
            _Reserved_ PVOID Reserved
        );
#endif

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtReplaceKey(
            _In_ POBJECT_ATTRIBUTES NewFile,
            _In_ HANDLE TargetHandle,
            _In_ POBJECT_ATTRIBUTES OldFile
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtSaveKey(
            _In_ HANDLE KeyHandle,
            _In_ HANDLE FileHandle
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtSaveKeyEx(
            _In_ HANDLE KeyHandle,
            _In_ HANDLE FileHandle,
            _In_ ULONG Format
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtSaveMergedKeys(
            _In_ HANDLE HighPrecedenceKeyHandle,
            _In_ HANDLE LowPrecedenceKeyHandle,
            _In_ HANDLE FileHandle
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtRestoreKey(
            _In_ HANDLE KeyHandle,
            _In_ HANDLE FileHandle,
            _In_ ULONG Flags
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtUnloadKey(
            _In_ POBJECT_ATTRIBUTES TargetKey
        );

    //
    // NtUnloadKey2 Flags (from winnt.h)
    //
    //#define REG_FORCE_UNLOAD            1
    //#define REG_UNLOAD_LEGAL_FLAGS      (REG_FORCE_UNLOAD)

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtUnloadKey2(
            _In_ POBJECT_ATTRIBUTES TargetKey,
            _In_ ULONG Flags
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtUnloadKeyEx(
            _In_ POBJECT_ATTRIBUTES TargetKey,
            _In_opt_ HANDLE Event
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtNotifyChangeKey(
            _In_ HANDLE KeyHandle,
            _In_opt_ HANDLE Event,
            _In_opt_ PIO_APC_ROUTINE ApcRoutine,
            _In_opt_ PVOID ApcContext,
            _Out_ PIO_STATUS_BLOCK IoStatusBlock,
            _In_ ULONG CompletionFilter,
            _In_ BOOLEAN WatchTree,
            _Out_writes_bytes_opt_(BufferSize) PVOID Buffer,
            _In_ ULONG BufferSize,
            _In_ BOOLEAN Asynchronous
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtNotifyChangeMultipleKeys(
            _In_ HANDLE MasterKeyHandle,
            _In_opt_ ULONG Count,
            _In_reads_opt_(Count) OBJECT_ATTRIBUTES SubordinateObjects[],
            _In_opt_ HANDLE Event,
            _In_opt_ PIO_APC_ROUTINE ApcRoutine,
            _In_opt_ PVOID ApcContext,
            _Out_ PIO_STATUS_BLOCK IoStatusBlock,
            _In_ ULONG CompletionFilter,
            _In_ BOOLEAN WatchTree,
            _Out_writes_bytes_opt_(BufferSize) PVOID Buffer,
            _In_ ULONG BufferSize,
            _In_ BOOLEAN Asynchronous
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtQueryOpenSubKeys(
            _In_ POBJECT_ATTRIBUTES TargetKey,
            _Out_ PULONG HandleCount
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtQueryOpenSubKeysEx(
            _In_ POBJECT_ATTRIBUTES TargetKey,
            _In_ ULONG BufferLength,
            _Out_writes_bytes_opt_(BufferLength) PVOID Buffer,
            _Out_ PULONG RequiredSize
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtInitializeRegistry(
            _In_ USHORT BootCondition
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtLockRegistryKey(
            _In_ HANDLE KeyHandle
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtLockProductActivationKeys(
            _Inout_opt_ ULONG* pPrivateVer,
            _Out_opt_ ULONG* pSafeMode
        );

#if (PHNT_VERSION >= PHNT_VISTA)
    // private
    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtFreezeRegistry(
            _In_ ULONG TimeOutInSeconds
        );
#endif

#if (PHNT_VERSION >= PHNT_VISTA)
    // private
    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtThawRegistry(
            VOID
        );
#endif

#if (PHNT_VERSION >= PHNT_REDSTONE)
    NTSTATUS NtCreateRegistryTransaction(
        _Out_ HANDLE* RegistryTransactionHandle,
        _In_ ACCESS_MASK DesiredAccess,
        _In_opt_ POBJECT_ATTRIBUTES ObjAttributes,
        _Reserved_ ULONG CreateOptions
    );
#endif

#if (PHNT_VERSION >= PHNT_REDSTONE)
    NTSTATUS NtOpenRegistryTransaction(
        _Out_ HANDLE* RegistryTransactionHandle,
        _In_ ACCESS_MASK DesiredAccess,
        _In_ POBJECT_ATTRIBUTES ObjAttributes
    );
#endif

#if (PHNT_VERSION >= PHNT_REDSTONE)
    NTSTATUS NtCommitRegistryTransaction(
        _In_ HANDLE RegistryTransactionHandle,
        _Reserved_ ULONG Flags
    );
#endif

#if (PHNT_VERSION >= PHNT_REDSTONE)
    NTSTATUS NtRollbackRegistryTransaction(
        _In_ HANDLE RegistryTransactionHandle,
        _Reserved_ ULONG Flags
    );
#endif

#endif
    /*
     * RTL support functions
     *
     * This file is part of System Informer.
     */

#ifndef _NTRTL_H
#define _NTRTL_H

#define RtlOffsetToPointer(Base, Offset) ((PCHAR)(((PCHAR)(Base)) + ((ULONG_PTR)(Offset))))
#define RtlPointerToOffset(Base, Pointer) ((ULONG)(((PCHAR)(Pointer)) - ((PCHAR)(Base))))

#define RTL_PTR_ADD(Pointer, Value) ((PVOID)((ULONG_PTR)(Pointer) + (ULONG_PTR)(Value)))
#define RTL_PTR_SUBTRACT(Pointer, Value) ((PVOID)((ULONG_PTR)(Pointer) - (ULONG_PTR)(Value)))

#define RTL_MILLISEC_TO_100NANOSEC(m) ((m) * 10000ui64)
#define RTL_SEC_TO_100NANOSEC(s) ((s) * 10000000ui64)
#define RTL_SEC_TO_MILLISEC(s) ((s) * 1000ui64)

#define RTL_MEG (1024UL * 1024UL)
#define RTL_IMAGE_MAX_DOS_HEADER (256UL * RTL_MEG)

     // Linked lists

    FORCEINLINE VOID InitializeListHead(
        _Out_ PLIST_ENTRY ListHead
    )
    {
        ListHead->Flink = ListHead->Blink = ListHead;
    }

    _Check_return_ FORCEINLINE BOOLEAN IsListEmpty(
        _In_ PLIST_ENTRY ListHead
    )
    {
        return ListHead->Flink == ListHead;
    }

    FORCEINLINE BOOLEAN RemoveEntryList(
        _In_ PLIST_ENTRY Entry
    )
    {
        PLIST_ENTRY Blink;
        PLIST_ENTRY Flink;

        Flink = Entry->Flink;
        Blink = Entry->Blink;
        Blink->Flink = Flink;
        Flink->Blink = Blink;

        return Flink == Blink;
    }

    FORCEINLINE PLIST_ENTRY RemoveHeadList(
        _Inout_ PLIST_ENTRY ListHead
    )
    {
        PLIST_ENTRY Flink;
        PLIST_ENTRY Entry;

        Entry = ListHead->Flink;
        Flink = Entry->Flink;
        ListHead->Flink = Flink;
        Flink->Blink = ListHead;

        return Entry;
    }

    FORCEINLINE PLIST_ENTRY RemoveTailList(
        _Inout_ PLIST_ENTRY ListHead
    )
    {
        PLIST_ENTRY Blink;
        PLIST_ENTRY Entry;

        Entry = ListHead->Blink;
        Blink = Entry->Blink;
        ListHead->Blink = Blink;
        Blink->Flink = ListHead;

        return Entry;
    }

    FORCEINLINE VOID InsertTailList(
        _Inout_ PLIST_ENTRY ListHead,
        _Inout_ PLIST_ENTRY Entry
    )
    {
        PLIST_ENTRY Blink;

        Blink = ListHead->Blink;
        Entry->Flink = ListHead;
        Entry->Blink = Blink;
        Blink->Flink = Entry;
        ListHead->Blink = Entry;
    }

    FORCEINLINE VOID InsertHeadList(
        _Inout_ PLIST_ENTRY ListHead,
        _Inout_ PLIST_ENTRY Entry
    )
    {
        PLIST_ENTRY Flink;

        Flink = ListHead->Flink;
        Entry->Flink = Flink;
        Entry->Blink = ListHead;
        Flink->Blink = Entry;
        ListHead->Flink = Entry;
    }

    FORCEINLINE VOID AppendTailList(
        _Inout_ PLIST_ENTRY ListHead,
        _Inout_ PLIST_ENTRY ListToAppend
    )
    {
        PLIST_ENTRY ListEnd = ListHead->Blink;

        ListHead->Blink->Flink = ListToAppend;
        ListHead->Blink = ListToAppend->Blink;
        ListToAppend->Blink->Flink = ListHead;
        ListToAppend->Blink = ListEnd;
    }

    FORCEINLINE PSINGLE_LIST_ENTRY PopEntryList(
        _Inout_ PSINGLE_LIST_ENTRY ListHead
    )
    {
        PSINGLE_LIST_ENTRY FirstEntry;

        FirstEntry = ListHead->Next;

        if (FirstEntry)
            ListHead->Next = FirstEntry->Next;

        return FirstEntry;
    }

    FORCEINLINE VOID PushEntryList(
        _Inout_ PSINGLE_LIST_ENTRY ListHead,
        _Inout_ PSINGLE_LIST_ENTRY Entry
    )
    {
        Entry->Next = ListHead->Next;
        ListHead->Next = Entry;
    }

    // AVL and splay trees

    typedef enum _TABLE_SEARCH_RESULT
    {
        TableEmptyTree,
        TableFoundNode,
        TableInsertAsLeft,
        TableInsertAsRight
    } TABLE_SEARCH_RESULT;

    typedef enum _RTL_GENERIC_COMPARE_RESULTS
    {
        GenericLessThan,
        GenericGreaterThan,
        GenericEqual
    } RTL_GENERIC_COMPARE_RESULTS;

    typedef RTL_GENERIC_COMPARE_RESULTS(NTAPI* PRTL_AVL_COMPARE_ROUTINE)(
        _In_ struct _RTL_AVL_TABLE* Table,
        _In_ PVOID FirstStruct,
        _In_ PVOID SecondStruct
        );

    typedef PVOID(NTAPI* PRTL_AVL_ALLOCATE_ROUTINE)(
        _In_ struct _RTL_AVL_TABLE* Table,
        _In_ CLONG ByteSize
        );

    typedef VOID(NTAPI* PRTL_AVL_FREE_ROUTINE)(
        _In_ struct _RTL_AVL_TABLE* Table,
        _In_ _Post_invalid_ PVOID Buffer
        );

    typedef NTSTATUS(NTAPI* PRTL_AVL_MATCH_FUNCTION)(
        _In_ struct _RTL_AVL_TABLE* Table,
        _In_ PVOID UserData,
        _In_ PVOID MatchData
        );

    typedef struct _RTL_BALANCED_LINKS
    {
        struct _RTL_BALANCED_LINKS* Parent;
        struct _RTL_BALANCED_LINKS* LeftChild;
        struct _RTL_BALANCED_LINKS* RightChild;
        CHAR Balance;
        UCHAR Reserved[3];
    } RTL_BALANCED_LINKS, * PRTL_BALANCED_LINKS;

    typedef struct _RTL_AVL_TABLE
    {
        RTL_BALANCED_LINKS BalancedRoot;
        PVOID OrderedPointer;
        ULONG WhichOrderedElement;
        ULONG NumberGenericTableElements;
        ULONG DepthOfTree;
        PRTL_BALANCED_LINKS RestartKey;
        ULONG DeleteCount;
        PRTL_AVL_COMPARE_ROUTINE CompareRoutine;
        PRTL_AVL_ALLOCATE_ROUTINE AllocateRoutine;
        PRTL_AVL_FREE_ROUTINE FreeRoutine;
        PVOID TableContext;
    } RTL_AVL_TABLE, * PRTL_AVL_TABLE;

    NTSYSAPI
        VOID
        NTAPI
        RtlInitializeGenericTableAvl(
            _Out_ PRTL_AVL_TABLE Table,
            _In_ PRTL_AVL_COMPARE_ROUTINE CompareRoutine,
            _In_ PRTL_AVL_ALLOCATE_ROUTINE AllocateRoutine,
            _In_ PRTL_AVL_FREE_ROUTINE FreeRoutine,
            _In_opt_ PVOID TableContext
        );

    NTSYSAPI
        PVOID
        NTAPI
        RtlInsertElementGenericTableAvl(
            _In_ PRTL_AVL_TABLE Table,
            _In_reads_bytes_(BufferSize) PVOID Buffer,
            _In_ CLONG BufferSize,
            _Out_opt_ PBOOLEAN NewElement
        );

    NTSYSAPI
        PVOID
        NTAPI
        RtlInsertElementGenericTableFullAvl(
            _In_ PRTL_AVL_TABLE Table,
            _In_reads_bytes_(BufferSize) PVOID Buffer,
            _In_ CLONG BufferSize,
            _Out_opt_ PBOOLEAN NewElement,
            _In_ PVOID NodeOrParent,
            _In_ TABLE_SEARCH_RESULT SearchResult
        );

    NTSYSAPI
        BOOLEAN
        NTAPI
        RtlDeleteElementGenericTableAvl(
            _In_ PRTL_AVL_TABLE Table,
            _In_ PVOID Buffer
        );

    _Check_return_
        NTSYSAPI
        PVOID
        NTAPI
        RtlLookupElementGenericTableAvl(
            _In_ PRTL_AVL_TABLE Table,
            _In_ PVOID Buffer
        );

    NTSYSAPI
        PVOID
        NTAPI
        RtlLookupElementGenericTableFullAvl(
            _In_ PRTL_AVL_TABLE Table,
            _In_ PVOID Buffer,
            _Out_ PVOID* NodeOrParent,
            _Out_ TABLE_SEARCH_RESULT* SearchResult
        );

    _Check_return_
        NTSYSAPI
        PVOID
        NTAPI
        RtlEnumerateGenericTableAvl(
            _In_ PRTL_AVL_TABLE Table,
            _In_ BOOLEAN Restart
        );

    _Check_return_
        NTSYSAPI
        PVOID
        NTAPI
        RtlEnumerateGenericTableWithoutSplayingAvl(
            _In_ PRTL_AVL_TABLE Table,
            _Inout_ PVOID* RestartKey
        );

    _Check_return_
        NTSYSAPI
        PVOID
        NTAPI
        RtlLookupFirstMatchingElementGenericTableAvl(
            _In_ PRTL_AVL_TABLE Table,
            _In_ PVOID Buffer,
            _Out_ PVOID* RestartKey
        );

    _Check_return_
        NTSYSAPI
        PVOID
        NTAPI
        RtlEnumerateGenericTableLikeADirectory(
            _In_ PRTL_AVL_TABLE Table,
            _In_opt_ PRTL_AVL_MATCH_FUNCTION MatchFunction,
            _In_opt_ PVOID MatchData,
            _In_ ULONG NextFlag,
            _Inout_ PVOID* RestartKey,
            _Inout_ PULONG DeleteCount,
            _In_ PVOID Buffer
        );

    _Check_return_
        NTSYSAPI
        PVOID
        NTAPI
        RtlGetElementGenericTableAvl(
            _In_ PRTL_AVL_TABLE Table,
            _In_ ULONG I
        );

    NTSYSAPI
        ULONG
        NTAPI
        RtlNumberGenericTableElementsAvl(
            _In_ PRTL_AVL_TABLE Table
        );

    _Check_return_
        NTSYSAPI
        BOOLEAN
        NTAPI
        RtlIsGenericTableEmptyAvl(
            _In_ PRTL_AVL_TABLE Table
        );

    typedef struct _RTL_SPLAY_LINKS
    {
        struct _RTL_SPLAY_LINKS* Parent;
        struct _RTL_SPLAY_LINKS* LeftChild;
        struct _RTL_SPLAY_LINKS* RightChild;
    } RTL_SPLAY_LINKS, * PRTL_SPLAY_LINKS;

#define RtlInitializeSplayLinks(Links) \
{ \
    PRTL_SPLAY_LINKS _SplayLinks; \
    _SplayLinks = (PRTL_SPLAY_LINKS)(Links); \
    _SplayLinks->Parent = _SplayLinks; \
    _SplayLinks->LeftChild = NULL; \
    _SplayLinks->RightChild = NULL; \
}

#define RtlParent(Links) ((PRTL_SPLAY_LINKS)(Links)->Parent)
#define RtlLeftChild(Links) ((PRTL_SPLAY_LINKS)(Links)->LeftChild)
#define RtlRightChild(Links) ((PRTL_SPLAY_LINKS)(Links)->RightChild)
#define RtlIsRoot(Links) ((RtlParent(Links) == (PRTL_SPLAY_LINKS)(Links)))
#define RtlIsLeftChild(Links) ((RtlLeftChild(RtlParent(Links)) == (PRTL_SPLAY_LINKS)(Links)))
#define RtlIsRightChild(Links) ((RtlRightChild(RtlParent(Links)) == (PRTL_SPLAY_LINKS)(Links)))

#define RtlInsertAsLeftChild(ParentLinks, ChildLinks) \
{ \
    PRTL_SPLAY_LINKS _SplayParent; \
    PRTL_SPLAY_LINKS _SplayChild; \
    _SplayParent = (PRTL_SPLAY_LINKS)(ParentLinks); \
    _SplayChild = (PRTL_SPLAY_LINKS)(ChildLinks); \
    _SplayParent->LeftChild = _SplayChild; \
    _SplayChild->Parent = _SplayParent; \
}

#define RtlInsertAsRightChild(ParentLinks, ChildLinks) \
{ \
    PRTL_SPLAY_LINKS _SplayParent; \
    PRTL_SPLAY_LINKS _SplayChild; \
    _SplayParent = (PRTL_SPLAY_LINKS)(ParentLinks); \
    _SplayChild = (PRTL_SPLAY_LINKS)(ChildLinks); \
    _SplayParent->RightChild = _SplayChild; \
    _SplayChild->Parent = _SplayParent; \
}

    NTSYSAPI
        PRTL_SPLAY_LINKS
        NTAPI
        RtlSplay(
            _Inout_ PRTL_SPLAY_LINKS Links
        );

    NTSYSAPI
        PRTL_SPLAY_LINKS
        NTAPI
        RtlDelete(
            _In_ PRTL_SPLAY_LINKS Links
        );

    NTSYSAPI
        VOID
        NTAPI
        RtlDeleteNoSplay(
            _In_ PRTL_SPLAY_LINKS Links,
            _Inout_ PRTL_SPLAY_LINKS* Root
        );

    _Check_return_
        NTSYSAPI
        PRTL_SPLAY_LINKS
        NTAPI
        RtlSubtreeSuccessor(
            _In_ PRTL_SPLAY_LINKS Links
        );

    _Check_return_
        NTSYSAPI
        PRTL_SPLAY_LINKS
        NTAPI
        RtlSubtreePredecessor(
            _In_ PRTL_SPLAY_LINKS Links
        );

    _Check_return_
        NTSYSAPI
        PRTL_SPLAY_LINKS
        NTAPI
        RtlRealSuccessor(
            _In_ PRTL_SPLAY_LINKS Links
        );

    _Check_return_
        NTSYSAPI
        PRTL_SPLAY_LINKS
        NTAPI
        RtlRealPredecessor(
            _In_ PRTL_SPLAY_LINKS Links
        );

    struct _RTL_GENERIC_TABLE;

    typedef RTL_GENERIC_COMPARE_RESULTS(NTAPI* PRTL_GENERIC_COMPARE_ROUTINE)(
        _In_ struct _RTL_GENERIC_TABLE* Table,
        _In_ PVOID FirstStruct,
        _In_ PVOID SecondStruct
        );

    typedef PVOID(NTAPI* PRTL_GENERIC_ALLOCATE_ROUTINE)(
        _In_ struct _RTL_GENERIC_TABLE* Table,
        _In_ CLONG ByteSize
        );

    typedef VOID(NTAPI* PRTL_GENERIC_FREE_ROUTINE)(
        _In_ struct _RTL_GENERIC_TABLE* Table,
        _In_ _Post_invalid_ PVOID Buffer
        );

    typedef struct _RTL_GENERIC_TABLE
    {
        PRTL_SPLAY_LINKS TableRoot;
        LIST_ENTRY InsertOrderList;
        PLIST_ENTRY OrderedPointer;
        ULONG WhichOrderedElement;
        ULONG NumberGenericTableElements;
        PRTL_GENERIC_COMPARE_ROUTINE CompareRoutine;
        PRTL_GENERIC_ALLOCATE_ROUTINE AllocateRoutine;
        PRTL_GENERIC_FREE_ROUTINE FreeRoutine;
        PVOID TableContext;
    } RTL_GENERIC_TABLE, * PRTL_GENERIC_TABLE;

    NTSYSAPI
        VOID
        NTAPI
        RtlInitializeGenericTable(
            _Out_ PRTL_GENERIC_TABLE Table,
            _In_ PRTL_GENERIC_COMPARE_ROUTINE CompareRoutine,
            _In_ PRTL_GENERIC_ALLOCATE_ROUTINE AllocateRoutine,
            _In_ PRTL_GENERIC_FREE_ROUTINE FreeRoutine,
            _In_opt_ PVOID TableContext
        );

    NTSYSAPI
        PVOID
        NTAPI
        RtlInsertElementGenericTable(
            _In_ PRTL_GENERIC_TABLE Table,
            _In_reads_bytes_(BufferSize) PVOID Buffer,
            _In_ CLONG BufferSize,
            _Out_opt_ PBOOLEAN NewElement
        );

    NTSYSAPI
        PVOID
        NTAPI
        RtlInsertElementGenericTableFull(
            _In_ PRTL_GENERIC_TABLE Table,
            _In_reads_bytes_(BufferSize) PVOID Buffer,
            _In_ CLONG BufferSize,
            _Out_opt_ PBOOLEAN NewElement,
            _In_ PVOID NodeOrParent,
            _In_ TABLE_SEARCH_RESULT SearchResult
        );

    NTSYSAPI
        BOOLEAN
        NTAPI
        RtlDeleteElementGenericTable(
            _In_ PRTL_GENERIC_TABLE Table,
            _In_ PVOID Buffer
        );

    _Check_return_
        NTSYSAPI
        PVOID
        NTAPI
        RtlLookupElementGenericTable(
            _In_ PRTL_GENERIC_TABLE Table,
            _In_ PVOID Buffer
        );

    NTSYSAPI
        PVOID
        NTAPI
        RtlLookupElementGenericTableFull(
            _In_ PRTL_GENERIC_TABLE Table,
            _In_ PVOID Buffer,
            _Out_ PVOID* NodeOrParent,
            _Out_ TABLE_SEARCH_RESULT* SearchResult
        );

    _Check_return_
        NTSYSAPI
        PVOID
        NTAPI
        RtlEnumerateGenericTable(
            _In_ PRTL_GENERIC_TABLE Table,
            _In_ BOOLEAN Restart
        );

    _Check_return_
        NTSYSAPI
        PVOID
        NTAPI
        RtlEnumerateGenericTableWithoutSplaying(
            _In_ PRTL_GENERIC_TABLE Table,
            _Inout_ PVOID* RestartKey
        );

    _Check_return_
        NTSYSAPI
        PVOID
        NTAPI
        RtlGetElementGenericTable(
            _In_ PRTL_GENERIC_TABLE Table,
            _In_ ULONG I
        );

    NTSYSAPI
        ULONG
        NTAPI
        RtlNumberGenericTableElements(
            _In_ PRTL_GENERIC_TABLE Table
        );

    _Check_return_
        NTSYSAPI
        BOOLEAN
        NTAPI
        RtlIsGenericTableEmpty(
            _In_ PRTL_GENERIC_TABLE Table
        );

    // RB trees

    typedef struct _RTL_RB_TREE
    {
        PRTL_BALANCED_NODE Root;
        PRTL_BALANCED_NODE Min;
    } RTL_RB_TREE, * PRTL_RB_TREE;

#if (PHNT_VERSION >= PHNT_WIN8)

    // rev
    NTSYSAPI
        BOOLEAN
        NTAPI
        RtlRbInsertNodeEx(
            _In_ PRTL_RB_TREE Tree,
            _In_opt_ PRTL_BALANCED_NODE Parent,
            _In_ BOOLEAN Right,
            _Out_ PRTL_BALANCED_NODE Node
        );

    // rev
    NTSYSAPI
        BOOLEAN
        NTAPI
        RtlRbRemoveNode(
            _In_ PRTL_RB_TREE Tree,
            _In_ PRTL_BALANCED_NODE Node
        );

#endif

    // Hash tables

    // begin_ntddk

#define RTL_HASH_ALLOCATED_HEADER 0x00000001
#define RTL_HASH_RESERVED_SIGNATURE 0

    typedef struct _RTL_DYNAMIC_HASH_TABLE_ENTRY
    {
        LIST_ENTRY Linkage;
        ULONG_PTR Signature;
    } RTL_DYNAMIC_HASH_TABLE_ENTRY, * PRTL_DYNAMIC_HASH_TABLE_ENTRY;

#define HASH_ENTRY_KEY(x) ((x)->Signature)

    typedef struct _RTL_DYNAMIC_HASH_TABLE_CONTEXT
    {
        PLIST_ENTRY ChainHead;
        PLIST_ENTRY PrevLinkage;
        ULONG_PTR Signature;
    } RTL_DYNAMIC_HASH_TABLE_CONTEXT, * PRTL_DYNAMIC_HASH_TABLE_CONTEXT;

    typedef struct _RTL_DYNAMIC_HASH_TABLE_ENUMERATOR
    {
        RTL_DYNAMIC_HASH_TABLE_ENTRY HashEntry;
        PLIST_ENTRY ChainHead;
        ULONG BucketIndex;
    } RTL_DYNAMIC_HASH_TABLE_ENUMERATOR, * PRTL_DYNAMIC_HASH_TABLE_ENUMERATOR;

    typedef struct _RTL_DYNAMIC_HASH_TABLE
    {
        // Entries initialized at creation.
        ULONG Flags;
        ULONG Shift;

        // Entries used in bucket computation.
        ULONG TableSize;
        ULONG Pivot;
        ULONG DivisorMask;

        // Counters.
        ULONG NumEntries;
        ULONG NonEmptyBuckets;
        ULONG NumEnumerators;

        // The directory. This field is for internal use only.
        PVOID Directory;
    } RTL_DYNAMIC_HASH_TABLE, * PRTL_DYNAMIC_HASH_TABLE;

#if (PHNT_VERSION >= PHNT_WIN7)

    FORCEINLINE
        VOID
        RtlInitHashTableContext(
            _Inout_ PRTL_DYNAMIC_HASH_TABLE_CONTEXT Context
        )
    {
        Context->ChainHead = NULL;
        Context->PrevLinkage = NULL;
    }

    FORCEINLINE
        VOID
        RtlInitHashTableContextFromEnumerator(
            _Inout_ PRTL_DYNAMIC_HASH_TABLE_CONTEXT Context,
            _In_ PRTL_DYNAMIC_HASH_TABLE_ENUMERATOR Enumerator
        )
    {
        Context->ChainHead = Enumerator->ChainHead;
        Context->PrevLinkage = Enumerator->HashEntry.Linkage.Blink;
    }

    FORCEINLINE
        VOID
        RtlReleaseHashTableContext(
            _Inout_ PRTL_DYNAMIC_HASH_TABLE_CONTEXT Context
        )
    {
        UNREFERENCED_PARAMETER(Context);
        return;
    }

    FORCEINLINE
        ULONG
        RtlTotalBucketsHashTable(
            _In_ PRTL_DYNAMIC_HASH_TABLE HashTable
        )
    {
        return HashTable->TableSize;
    }

    FORCEINLINE
        ULONG
        RtlNonEmptyBucketsHashTable(
            _In_ PRTL_DYNAMIC_HASH_TABLE HashTable
        )
    {
        return HashTable->NonEmptyBuckets;
    }

    FORCEINLINE
        ULONG
        RtlEmptyBucketsHashTable(
            _In_ PRTL_DYNAMIC_HASH_TABLE HashTable
        )
    {
        return HashTable->TableSize - HashTable->NonEmptyBuckets;
    }

    FORCEINLINE
        ULONG
        RtlTotalEntriesHashTable(
            _In_ PRTL_DYNAMIC_HASH_TABLE HashTable
        )
    {
        return HashTable->NumEntries;
    }

    FORCEINLINE
        ULONG
        RtlActiveEnumeratorsHashTable(
            _In_ PRTL_DYNAMIC_HASH_TABLE HashTable
        )
    {
        return HashTable->NumEnumerators;
    }

    _Must_inspect_result_
        NTSYSAPI
        BOOLEAN
        NTAPI
        RtlCreateHashTable(
            _Inout_ _When_(*HashTable == NULL, __drv_allocatesMem(Mem)) PRTL_DYNAMIC_HASH_TABLE* HashTable,
            _In_ ULONG Shift,
            _In_ _Reserved_ ULONG Flags
        );

    NTSYSAPI
        LOGICAL
        NTAPI
        RtlDeleteHashTable(
            _In_ PRTL_DYNAMIC_HASH_TABLE HashTable
        );

    NTSYSAPI
        BOOLEAN
        NTAPI
        RtlInsertEntryHashTable(
            _In_ PRTL_DYNAMIC_HASH_TABLE HashTable,
            _In_ PRTL_DYNAMIC_HASH_TABLE_ENTRY Entry,
            _In_ ULONG_PTR Signature,
            _Inout_opt_ PRTL_DYNAMIC_HASH_TABLE_CONTEXT Context
        );

    NTSYSAPI
        BOOLEAN
        NTAPI
        RtlRemoveEntryHashTable(
            _In_ PRTL_DYNAMIC_HASH_TABLE HashTable,
            _In_ PRTL_DYNAMIC_HASH_TABLE_ENTRY Entry,
            _Inout_opt_ PRTL_DYNAMIC_HASH_TABLE_CONTEXT Context
        );

    _Must_inspect_result_
        NTSYSAPI
        PRTL_DYNAMIC_HASH_TABLE_ENTRY
        NTAPI
        RtlLookupEntryHashTable(
            _In_ PRTL_DYNAMIC_HASH_TABLE HashTable,
            _In_ ULONG_PTR Signature,
            _Out_opt_ PRTL_DYNAMIC_HASH_TABLE_CONTEXT Context
        );

    _Must_inspect_result_
        NTSYSAPI
        PRTL_DYNAMIC_HASH_TABLE_ENTRY
        NTAPI
        RtlGetNextEntryHashTable(
            _In_ PRTL_DYNAMIC_HASH_TABLE HashTable,
            _In_ PRTL_DYNAMIC_HASH_TABLE_CONTEXT Context
        );

    NTSYSAPI
        BOOLEAN
        NTAPI
        RtlInitEnumerationHashTable(
            _In_ PRTL_DYNAMIC_HASH_TABLE HashTable,
            _Out_ PRTL_DYNAMIC_HASH_TABLE_ENUMERATOR Enumerator
        );

    _Must_inspect_result_
        NTSYSAPI
        PRTL_DYNAMIC_HASH_TABLE_ENTRY
        NTAPI
        RtlEnumerateEntryHashTable(
            _In_ PRTL_DYNAMIC_HASH_TABLE HashTable,
            _Inout_ PRTL_DYNAMIC_HASH_TABLE_ENUMERATOR Enumerator
        );

    NTSYSAPI
        VOID
        NTAPI
        RtlEndEnumerationHashTable(
            _In_ PRTL_DYNAMIC_HASH_TABLE HashTable,
            _Inout_ PRTL_DYNAMIC_HASH_TABLE_ENUMERATOR Enumerator
        );

    NTSYSAPI
        BOOLEAN
        NTAPI
        RtlInitWeakEnumerationHashTable(
            _In_ PRTL_DYNAMIC_HASH_TABLE HashTable,
            _Out_ PRTL_DYNAMIC_HASH_TABLE_ENUMERATOR Enumerator
        );

    _Must_inspect_result_
        NTSYSAPI
        PRTL_DYNAMIC_HASH_TABLE_ENTRY
        NTAPI
        RtlWeaklyEnumerateEntryHashTable(
            _In_ PRTL_DYNAMIC_HASH_TABLE HashTable,
            _Inout_ PRTL_DYNAMIC_HASH_TABLE_ENUMERATOR Enumerator
        );

    NTSYSAPI
        VOID
        NTAPI
        RtlEndWeakEnumerationHashTable(
            _In_ PRTL_DYNAMIC_HASH_TABLE HashTable,
            _Inout_ PRTL_DYNAMIC_HASH_TABLE_ENUMERATOR Enumerator
        );

    NTSYSAPI
        BOOLEAN
        NTAPI
        RtlExpandHashTable(
            _In_ PRTL_DYNAMIC_HASH_TABLE HashTable
        );

    NTSYSAPI
        BOOLEAN
        NTAPI
        RtlContractHashTable(
            _In_ PRTL_DYNAMIC_HASH_TABLE HashTable
        );

#endif

#if (PHNT_VERSION >= PHNT_THRESHOLD)

    NTSYSAPI
        BOOLEAN
        NTAPI
        RtlInitStrongEnumerationHashTable(
            _In_ PRTL_DYNAMIC_HASH_TABLE HashTable,
            _Out_ PRTL_DYNAMIC_HASH_TABLE_ENUMERATOR Enumerator
        );

    _Must_inspect_result_
        NTSYSAPI
        PRTL_DYNAMIC_HASH_TABLE_ENTRY
        NTAPI
        RtlStronglyEnumerateEntryHashTable(
            _In_ PRTL_DYNAMIC_HASH_TABLE HashTable,
            _Inout_ PRTL_DYNAMIC_HASH_TABLE_ENUMERATOR Enumerator
        );

    NTSYSAPI
        VOID
        NTAPI
        RtlEndStrongEnumerationHashTable(
            _In_ PRTL_DYNAMIC_HASH_TABLE HashTable,
            _Inout_ PRTL_DYNAMIC_HASH_TABLE_ENUMERATOR Enumerator
        );

#endif

    // end_ntddk

    // Critical sections

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlInitializeCriticalSection(
            _Out_ PRTL_CRITICAL_SECTION CriticalSection
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlInitializeCriticalSectionAndSpinCount(
            _Inout_ PRTL_CRITICAL_SECTION CriticalSection,
            _In_ ULONG SpinCount
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlInitializeCriticalSectionEx(
            _Out_ PRTL_CRITICAL_SECTION CriticalSection,
            _In_ ULONG SpinCount,
            _In_ ULONG Flags
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlDeleteCriticalSection(
            _Inout_ PRTL_CRITICAL_SECTION CriticalSection
        );

    _Acquires_exclusive_lock_(*CriticalSection)
        NTSYSAPI
        NTSTATUS
        NTAPI
        RtlEnterCriticalSection(
            _Inout_ PRTL_CRITICAL_SECTION CriticalSection
        );

    _Releases_exclusive_lock_(*CriticalSection)
        NTSYSAPI
        NTSTATUS
        NTAPI
        RtlLeaveCriticalSection(
            _Inout_ PRTL_CRITICAL_SECTION CriticalSection
        );

    _When_(return != 0, _Acquires_exclusive_lock_(*CriticalSection))
        NTSYSAPI
        LOGICAL
        NTAPI
        RtlTryEnterCriticalSection(
            _Inout_ PRTL_CRITICAL_SECTION CriticalSection
        );

    NTSYSAPI
        LOGICAL
        NTAPI
        RtlIsCriticalSectionLocked(
            _In_ PRTL_CRITICAL_SECTION CriticalSection
        );

    NTSYSAPI
        LOGICAL
        NTAPI
        RtlIsCriticalSectionLockedByThread(
            _In_ PRTL_CRITICAL_SECTION CriticalSection
        );

    NTSYSAPI
        ULONG
        NTAPI
        RtlGetCriticalSectionRecursionCount(
            _In_ PRTL_CRITICAL_SECTION CriticalSection
        );

    NTSYSAPI
        ULONG
        NTAPI
        RtlSetCriticalSectionSpinCount(
            _Inout_ PRTL_CRITICAL_SECTION CriticalSection,
            _In_ ULONG SpinCount
        );

#if (PHNT_VERSION >= PHNT_VISTA)
    // private
    NTSYSAPI
        HANDLE
        NTAPI
        RtlQueryCriticalSectionOwner(
            _In_ HANDLE EventHandle
        );
#endif

    NTSYSAPI
        VOID
        NTAPI
        RtlCheckForOrphanedCriticalSections(
            _In_ HANDLE ThreadHandle
        );

    // Resources

    typedef struct _RTL_RESOURCE
    {
        RTL_CRITICAL_SECTION CriticalSection;

        HANDLE SharedSemaphore;
        volatile ULONG NumberOfWaitingShared;
        HANDLE ExclusiveSemaphore;
        volatile ULONG NumberOfWaitingExclusive;

        volatile LONG NumberOfActive; // negative: exclusive acquire; zero: not acquired; positive: shared acquire(s)
        HANDLE ExclusiveOwnerThread;

        ULONG Flags; // RTL_RESOURCE_FLAG_*

        PRTL_RESOURCE_DEBUG DebugInfo;
    } RTL_RESOURCE, * PRTL_RESOURCE;

#define RTL_RESOURCE_FLAG_LONG_TERM ((ULONG)0x00000001)

    NTSYSAPI
        VOID
        NTAPI
        RtlInitializeResource(
            _Out_ PRTL_RESOURCE Resource
        );

    NTSYSAPI
        VOID
        NTAPI
        RtlDeleteResource(
            _Inout_ PRTL_RESOURCE Resource
        );

    NTSYSAPI
        BOOLEAN
        NTAPI
        RtlAcquireResourceShared(
            _Inout_ PRTL_RESOURCE Resource,
            _In_ BOOLEAN Wait
        );

    NTSYSAPI
        BOOLEAN
        NTAPI
        RtlAcquireResourceExclusive(
            _Inout_ PRTL_RESOURCE Resource,
            _In_ BOOLEAN Wait
        );

    NTSYSAPI
        VOID
        NTAPI
        RtlReleaseResource(
            _Inout_ PRTL_RESOURCE Resource
        );

    NTSYSAPI
        VOID
        NTAPI
        RtlConvertSharedToExclusive(
            _Inout_ PRTL_RESOURCE Resource
        );

    NTSYSAPI
        VOID
        NTAPI
        RtlConvertExclusiveToShared(
            _Inout_ PRTL_RESOURCE Resource
        );

    // Slim reader-writer locks, condition variables, and barriers

#if (PHNT_VERSION >= PHNT_VISTA)

// winbase:InitializeSRWLock
    NTSYSAPI
        VOID
        NTAPI
        RtlInitializeSRWLock(
            _Out_ PRTL_SRWLOCK SRWLock
        );

    // winbase:AcquireSRWLockExclusive
    _Acquires_exclusive_lock_(*SRWLock)
        NTSYSAPI
        VOID
        NTAPI
        RtlAcquireSRWLockExclusive(
            _Inout_ PRTL_SRWLOCK SRWLock
        );

    // winbase:AcquireSRWLockShared
    _Acquires_shared_lock_(*SRWLock)
        NTSYSAPI
        VOID
        NTAPI
        RtlAcquireSRWLockShared(
            _Inout_ PRTL_SRWLOCK SRWLock
        );

    // winbase:ReleaseSRWLockExclusive
    _Releases_exclusive_lock_(*SRWLock)
        NTSYSAPI
        VOID
        NTAPI
        RtlReleaseSRWLockExclusive(
            _Inout_ PRTL_SRWLOCK SRWLock
        );

    // winbase:ReleaseSRWLockShared
    _Releases_shared_lock_(*SRWLock)
        NTSYSAPI
        VOID
        NTAPI
        RtlReleaseSRWLockShared(
            _Inout_ PRTL_SRWLOCK SRWLock
        );

    // winbase:TryAcquireSRWLockExclusive
    _When_(return != 0, _Acquires_exclusive_lock_(*SRWLock))
        NTSYSAPI
        BOOLEAN
        NTAPI
        RtlTryAcquireSRWLockExclusive(
            _Inout_ PRTL_SRWLOCK SRWLock
        );

    // winbase:TryAcquireSRWLockShared
    _When_(return != 0, _Acquires_shared_lock_(*SRWLock))
        NTSYSAPI
        BOOLEAN
        NTAPI
        RtlTryAcquireSRWLockShared(
            _Inout_ PRTL_SRWLOCK SRWLock
        );

#if (PHNT_VERSION >= PHNT_WIN7)
    // rev
    NTSYSAPI
        VOID
        NTAPI
        RtlAcquireReleaseSRWLockExclusive(
            _Inout_ PRTL_SRWLOCK SRWLock
        );
#endif

#endif

#if (PHNT_VERSION >= PHNT_VISTA)

    // winbase:InitializeConditionVariable
    NTSYSAPI
        VOID
        NTAPI
        RtlInitializeConditionVariable(
            _Out_ PRTL_CONDITION_VARIABLE ConditionVariable
        );

    // private
    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlSleepConditionVariableCS(
            _Inout_ PRTL_CONDITION_VARIABLE ConditionVariable,
            _Inout_ PRTL_CRITICAL_SECTION CriticalSection,
            _In_opt_ PLARGE_INTEGER Timeout
        );

    // private
    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlSleepConditionVariableSRW(
            _Inout_ PRTL_CONDITION_VARIABLE ConditionVariable,
            _Inout_ PRTL_SRWLOCK SRWLock,
            _In_opt_ PLARGE_INTEGER Timeout,
            _In_ ULONG Flags
        );

    // winbase:WakeConditionVariable
    NTSYSAPI
        VOID
        NTAPI
        RtlWakeConditionVariable(
            _Inout_ PRTL_CONDITION_VARIABLE ConditionVariable
        );

    // winbase:WakeAllConditionVariable
    NTSYSAPI
        VOID
        NTAPI
        RtlWakeAllConditionVariable(
            _Inout_ PRTL_CONDITION_VARIABLE ConditionVariable
        );

#endif

    // begin_rev
#define RTL_BARRIER_FLAGS_SPIN_ONLY 0x00000001 // never block on event - always spin
#define RTL_BARRIER_FLAGS_BLOCK_ONLY 0x00000002 // always block on event - never spin
#define RTL_BARRIER_FLAGS_NO_DELETE 0x00000004 // use if barrier will never be deleted
// end_rev

// begin_private

#if (PHNT_VERSION >= PHNT_VISTA)

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlInitBarrier(
            _Out_ PRTL_BARRIER Barrier,
            _In_ ULONG TotalThreads,
            _In_ ULONG SpinCount
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlDeleteBarrier(
            _In_ PRTL_BARRIER Barrier
        );

    NTSYSAPI
        BOOLEAN
        NTAPI
        RtlBarrier(
            _Inout_ PRTL_BARRIER Barrier,
            _In_ ULONG Flags
        );

    NTSYSAPI
        BOOLEAN
        NTAPI
        RtlBarrierForDelete(
            _Inout_ PRTL_BARRIER Barrier,
            _In_ ULONG Flags
        );

#endif

    // end_private

    // Wait on address

    // begin_rev

#if (PHNT_VERSION >= PHNT_WIN8)

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlWaitOnAddress(
            _In_reads_bytes_(AddressSize) volatile VOID* Address,
            _In_reads_bytes_(AddressSize) PVOID CompareAddress,
            _In_ SIZE_T AddressSize,
            _In_opt_ PLARGE_INTEGER Timeout
        );

    NTSYSAPI
        VOID
        NTAPI
        RtlWakeAddressAll(
            _In_ PVOID Address
        );

    NTSYSAPI
        VOID
        NTAPI
        RtlWakeAddressSingle(
            _In_ PVOID Address
        );

#endif

    // end_rev

#if (PHNT_VERSION >= PHNT_WIN11_22H2)
    FORCEINLINE
        VOID
        RtlCopyVolatileMemory(
            _Out_writes_bytes_(Size) VOID* Destination,
            _In_reads_bytes_(Size) volatile const VOID* Source,
            _In_ SIZE_T Size
        )
    {
        RtlCopyMemory(Destination, (const VOID*)Source, Size);
        BarrierAfterRead();
    }
#endif

    FORCEINLINE
        HANDLE
        RtlReadHandleNoFence(
            _In_reads_bytes_(sizeof(HANDLE)) volatile CONST HANDLE* Address
        )
    {
        return (HANDLE)ReadPointerNoFence((PVOID*)Address);
    }

    // Strings

    FORCEINLINE
        VOID
        NTAPI
        RtlInitEmptyAnsiString(
            _Out_ PANSI_STRING AnsiString,
            _Pre_maybenull_ _Pre_readable_size_(MaximumLength) PCHAR Buffer,
            _In_ USHORT MaximumLength
        )
    {
        memset(AnsiString, 0, sizeof(ANSI_STRING));
        AnsiString->MaximumLength = MaximumLength;
        AnsiString->Buffer = Buffer;
    }

#ifndef PHNT_NO_INLINE_INIT_STRING
    FORCEINLINE VOID RtlInitString(
        _Out_ PSTRING DestinationString,
        _In_opt_ PCSTR SourceString
    )
    {
        if (SourceString)
            DestinationString->MaximumLength = (DestinationString->Length = (USHORT)strlen(SourceString)) + sizeof(ANSI_NULL);
        else
            DestinationString->MaximumLength = DestinationString->Length = 0;

        DestinationString->Buffer = (PCHAR)SourceString;
    }
#else
    NTSYSAPI
        VOID
        NTAPI
        RtlInitString(
            _Out_ PSTRING DestinationString,
            _In_opt_ PCSTR SourceString
        );
#endif

#if (PHNT_VERSION >= PHNT_THRESHOLD)
    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlInitStringEx(
            _Out_ PSTRING DestinationString,
            _In_opt_z_ PCSZ SourceString
        );
#endif

#ifndef PHNT_NO_INLINE_INIT_STRING
    FORCEINLINE VOID RtlInitAnsiString(
        _Out_ PANSI_STRING DestinationString,
        _In_opt_ PCSTR SourceString
    )
    {
        if (SourceString)
            DestinationString->MaximumLength = (DestinationString->Length = (USHORT)strlen(SourceString)) + sizeof(ANSI_NULL);
        else
            DestinationString->MaximumLength = DestinationString->Length = 0;

        DestinationString->Buffer = (PCHAR)SourceString;
    }
#else
    NTSYSAPI
        VOID
        NTAPI
        RtlInitAnsiString(
            _Out_ PANSI_STRING DestinationString,
            _In_opt_ PCSTR SourceString
        );
#endif

#if (PHNT_VERSION >= PHNT_WS03)
    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlInitAnsiStringEx(
            _Out_ PANSI_STRING DestinationString,
            _In_opt_z_ PCSZ SourceString
        );
#endif

    NTSYSAPI
        VOID
        NTAPI
        RtlFreeAnsiString(
            _Inout_ _At_(AnsiString->Buffer, _Frees_ptr_opt_) PANSI_STRING AnsiString
        );

#if (PHNT_VERSION >= PHNT_20H1)
    NTSYSAPI
        VOID
        NTAPI
        RtlInitUTF8String(
            _Out_ PUTF8_STRING DestinationString,
            _In_opt_z_ PCSZ SourceString
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlInitUTF8StringEx(
            _Out_ PUTF8_STRING DestinationString,
            _In_opt_z_ PCSZ SourceString
        );

    NTSYSAPI
        VOID
        NTAPI
        RtlFreeUTF8String(
            _Inout_ _At_(Utf8String->Buffer, _Frees_ptr_opt_) PUTF8_STRING Utf8String
        );
#endif

    NTSYSAPI
        VOID
        NTAPI
        RtlFreeOemString(
            _Inout_ POEM_STRING OemString
        );

    NTSYSAPI
        VOID
        NTAPI
        RtlCopyString(
            _In_ PSTRING DestinationString,
            _In_opt_ PSTRING SourceString
        );

    NTSYSAPI
        CHAR
        NTAPI
        RtlUpperChar(
            _In_ CHAR Character
        );

    _Must_inspect_result_
        NTSYSAPI
        LONG
        NTAPI
        RtlCompareString(
            _In_ PSTRING String1,
            _In_ PSTRING String2,
            _In_ BOOLEAN CaseInSensitive
        );

    _Must_inspect_result_
        NTSYSAPI
        BOOLEAN
        NTAPI
        RtlEqualString(
            _In_ PSTRING String1,
            _In_ PSTRING String2,
            _In_ BOOLEAN CaseInSensitive
        );

    _Must_inspect_result_
        NTSYSAPI
        BOOLEAN
        NTAPI
        RtlPrefixString(
            _In_ PSTRING String1,
            _In_ PSTRING String2,
            _In_ BOOLEAN CaseInSensitive
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlAppendStringToString(
            _Inout_ PSTRING Destination,
            _In_ PSTRING Source
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlAppendAsciizToString(
            _In_ PSTRING Destination,
            _In_opt_ PCSTR Source
        );

    NTSYSAPI
        VOID
        NTAPI
        RtlUpperString(
            _Inout_ PSTRING DestinationString,
            _In_ const STRING* SourceString
        );

    FORCEINLINE
        BOOLEAN
        RtlIsNullOrEmptyUnicodeString(
            _In_opt_ PUNICODE_STRING String
        )
    {
        return !String || String->Length == 0;
    }

    FORCEINLINE
        VOID
        NTAPI
        RtlInitEmptyUnicodeString(
            _Out_ PUNICODE_STRING DestinationString,
            _Writable_bytes_(MaximumLength) _When_(MaximumLength != 0, _Notnull_) PWCHAR Buffer,
            _In_ USHORT MaximumLength
        )
    {
        memset(DestinationString, 0, sizeof(UNICODE_STRING));
        DestinationString->MaximumLength = MaximumLength;
        DestinationString->Buffer = Buffer;
    }

#ifndef PHNT_NO_INLINE_INIT_STRING
    FORCEINLINE VOID RtlInitUnicodeString(
        _Out_ PUNICODE_STRING DestinationString,
        _In_opt_z_ PCWSTR SourceString
    )
    {
        if (SourceString)
            DestinationString->MaximumLength = (DestinationString->Length = (USHORT)(wcslen(SourceString) * sizeof(WCHAR))) + sizeof(UNICODE_NULL);
        else
            DestinationString->MaximumLength = DestinationString->Length = 0;

        DestinationString->Buffer = (PWCH)SourceString;
    }
#else
    NTSYSAPI
        VOID
        NTAPI
        RtlInitUnicodeString(
            _Out_ PUNICODE_STRING DestinationString,
            _In_opt_z_ PCWSTR SourceString
        );
#endif

#ifndef PHNT_NO_INLINE_INIT_STRING
    FORCEINLINE NTSTATUS RtlInitUnicodeStringEx(
        _Out_ PUNICODE_STRING DestinationString,
        _In_opt_z_ PCWSTR SourceString
    )
    {
        size_t stringLength;

        DestinationString->Length = 0;
        DestinationString->Buffer = (PWCH)SourceString;

        if (!SourceString)
            return STATUS_SUCCESS;

        stringLength = wcslen(SourceString);

        if (stringLength <= UNICODE_STRING_MAX_CHARS - 1)
        {
            DestinationString->Length = (USHORT)stringLength * sizeof(WCHAR);
            DestinationString->MaximumLength = DestinationString->Length + sizeof(UNICODE_NULL);
            return STATUS_SUCCESS;
        }

        return STATUS_NAME_TOO_LONG;
    }
#else
    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlInitUnicodeStringEx(
            _Out_ PUNICODE_STRING DestinationString,
            _In_opt_z_ PCWSTR SourceString
        );
#endif

    _Success_(return != 0)
        _Must_inspect_result_
        NTSYSAPI
        BOOLEAN
        NTAPI
        RtlCreateUnicodeString(
            _Out_ PUNICODE_STRING DestinationString,
            _In_z_ PCWSTR SourceString
        );

    NTSYSAPI
        BOOLEAN
        NTAPI
        RtlCreateUnicodeStringFromAsciiz(
            _Out_ PUNICODE_STRING DestinationString,
            _In_ PCSTR SourceString
        );

    NTSYSAPI
        VOID
        NTAPI
        RtlFreeUnicodeString(
            _Inout_ _At_(UnicodeString->Buffer, _Frees_ptr_opt_) PUNICODE_STRING UnicodeString
        );

#define RTL_DUPLICATE_UNICODE_STRING_NULL_TERMINATE (0x00000001)
#define RTL_DUPLICATE_UNICODE_STRING_ALLOCATE_NULL_STRING (0x00000002)

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlDuplicateUnicodeString(
            _In_ ULONG Flags,
            _In_ PUNICODE_STRING StringIn,
            _Out_ PUNICODE_STRING StringOut
        );

    NTSYSAPI
        VOID
        NTAPI
        RtlCopyUnicodeString(
            _In_ PUNICODE_STRING DestinationString,
            _In_opt_ PCUNICODE_STRING SourceString
        );

    NTSYSAPI
        WCHAR
        NTAPI
        RtlUpcaseUnicodeChar(
            _In_ WCHAR SourceCharacter
        );

    NTSYSAPI
        WCHAR
        NTAPI
        RtlDowncaseUnicodeChar(
            _In_ WCHAR SourceCharacter
        );

    _Must_inspect_result_
        NTSYSAPI
        LONG
        NTAPI
        RtlCompareUnicodeString(
            _In_ PUNICODE_STRING String1,
            _In_ PUNICODE_STRING String2,
            _In_ BOOLEAN CaseInSensitive
        );

#if (PHNT_VERSION >= PHNT_VISTA)
    _Must_inspect_result_
        NTSYSAPI
        LONG
        NTAPI
        RtlCompareUnicodeStrings(
            _In_reads_(String1Length) PCWCH String1,
            _In_ SIZE_T String1Length,
            _In_reads_(String2Length) PCWCH String2,
            _In_ SIZE_T String2Length,
            _In_ BOOLEAN CaseInSensitive
        );
#endif

    _Must_inspect_result_
        NTSYSAPI
        BOOLEAN
        NTAPI
        RtlEqualUnicodeString(
            _In_ PUNICODE_STRING String1,
            _In_ PUNICODE_STRING String2,
            _In_ BOOLEAN CaseInSensitive
        );

#define HASH_STRING_ALGORITHM_DEFAULT 0
#define HASH_STRING_ALGORITHM_X65599 1
#define HASH_STRING_ALGORITHM_INVALID 0xffffffff

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlHashUnicodeString(
            _In_ PUNICODE_STRING String,
            _In_ BOOLEAN CaseInSensitive,
            _In_ ULONG HashAlgorithm,
            _Out_ PULONG HashValue
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlValidateUnicodeString(
            _In_ ULONG Flags,
            _In_ PUNICODE_STRING String
        );

    _Must_inspect_result_
        NTSYSAPI
        BOOLEAN
        NTAPI
        RtlPrefixUnicodeString(
            _In_ PUNICODE_STRING String1,
            _In_ PUNICODE_STRING String2,
            _In_ BOOLEAN CaseInSensitive
        );

#if (PHNT_MODE == PHNT_MODE_KERNEL && PHNT_VERSION >= PHNT_THRESHOLD)
    _Must_inspect_result_
        NTSYSAPI
        BOOLEAN
        NTAPI
        RtlSuffixUnicodeString(
            _In_ PUNICODE_STRING String1,
            _In_ PUNICODE_STRING String2,
            _In_ BOOLEAN CaseInSensitive
        );
#endif

#if (PHNT_VERSION >= PHNT_THRESHOLD)
    _Must_inspect_result_
        NTSYSAPI
        PWCHAR
        NTAPI
        RtlFindUnicodeSubstring(
            _In_ PUNICODE_STRING FullString,
            _In_ PUNICODE_STRING SearchString,
            _In_ BOOLEAN CaseInSensitive
        );
#endif

#define RTL_FIND_CHAR_IN_UNICODE_STRING_START_AT_END 0x00000001
#define RTL_FIND_CHAR_IN_UNICODE_STRING_COMPLEMENT_CHAR_SET 0x00000002
#define RTL_FIND_CHAR_IN_UNICODE_STRING_CASE_INSENSITIVE 0x00000004

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlFindCharInUnicodeString(
            _In_ ULONG Flags,
            _In_ PUNICODE_STRING StringToSearch,
            _In_ PUNICODE_STRING CharSet,
            _Out_ PUSHORT NonInclusivePrefixLength
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlAppendUnicodeStringToString(
            _In_ PUNICODE_STRING Destination,
            _In_ PCUNICODE_STRING Source
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlAppendUnicodeToString(
            _In_ PUNICODE_STRING Destination,
            _In_opt_ PCWSTR Source
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlUpcaseUnicodeString(
            _Inout_ PUNICODE_STRING DestinationString,
            _In_ PUNICODE_STRING SourceString,
            _In_ BOOLEAN AllocateDestinationString
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlDowncaseUnicodeString(
            _Inout_ PUNICODE_STRING DestinationString,
            _In_ PUNICODE_STRING SourceString,
            _In_ BOOLEAN AllocateDestinationString
        );

    NTSYSAPI
        VOID
        NTAPI
        RtlEraseUnicodeString(
            _Inout_ PUNICODE_STRING String
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlAnsiStringToUnicodeString(
            _Inout_ PUNICODE_STRING DestinationString,
            _In_ PANSI_STRING SourceString,
            _In_ BOOLEAN AllocateDestinationString
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlUnicodeStringToAnsiString(
            _Inout_ PANSI_STRING DestinationString,
            _In_ PUNICODE_STRING SourceString,
            _In_ BOOLEAN AllocateDestinationString
        );

    // rev
    NTSYSAPI
        ULONG
        NTAPI
        RtlUnicodeStringToAnsiSize(
            _In_ PUNICODE_STRING SourceString
        );

#if (PHNT_VERSION >= PHNT_20H1)
    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlUnicodeStringToUTF8String(
            _Inout_ PUTF8_STRING DestinationString,
            _In_ PCUNICODE_STRING SourceString,
            _In_ BOOLEAN AllocateDestinationString
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlUTF8StringToUnicodeString(
            _Inout_ PUNICODE_STRING DestinationString,
            _In_ PUTF8_STRING SourceString,
            _In_ BOOLEAN AllocateDestinationString
        );
#endif

    NTSYSAPI
        WCHAR
        NTAPI
        RtlAnsiCharToUnicodeChar(
            _Inout_ PUCHAR* SourceCharacter
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlUpcaseUnicodeStringToAnsiString(
            _Inout_ PANSI_STRING DestinationString,
            _In_ PUNICODE_STRING SourceString,
            _In_ BOOLEAN AllocateDestinationString
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlOemStringToUnicodeString(
            _Inout_ PUNICODE_STRING DestinationString,
            _In_ POEM_STRING SourceString,
            _In_ BOOLEAN AllocateDestinationString
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlUnicodeStringToOemString(
            _Inout_ POEM_STRING DestinationString,
            _In_ PUNICODE_STRING SourceString,
            _In_ BOOLEAN AllocateDestinationString
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlUpcaseUnicodeStringToOemString(
            _Inout_ POEM_STRING DestinationString,
            _In_ PUNICODE_STRING SourceString,
            _In_ BOOLEAN AllocateDestinationString
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlOemStringToCountedUnicodeString(
            _Inout_ PUNICODE_STRING DestinationString,
            _In_ PCOEM_STRING SourceString,
            _In_ BOOLEAN AllocateDestinationString
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlUnicodeStringToCountedOemString(
            _Inout_ POEM_STRING DestinationString,
            _In_ PUNICODE_STRING SourceString,
            _In_ BOOLEAN AllocateDestinationString
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlUpcaseUnicodeStringToCountedOemString(
            _Inout_ POEM_STRING DestinationString,
            _In_ PUNICODE_STRING SourceString,
            _In_ BOOLEAN AllocateDestinationString
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlMultiByteToUnicodeN(
            _Out_writes_bytes_to_(MaxBytesInUnicodeString, *BytesInUnicodeString) PWCH UnicodeString,
            _In_ ULONG MaxBytesInUnicodeString,
            _Out_opt_ PULONG BytesInUnicodeString,
            _In_reads_bytes_(BytesInMultiByteString) PCSTR MultiByteString,
            _In_ ULONG BytesInMultiByteString
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlMultiByteToUnicodeSize(
            _Out_ PULONG BytesInUnicodeString,
            _In_reads_bytes_(BytesInMultiByteString) PCSTR MultiByteString,
            _In_ ULONG BytesInMultiByteString
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlUnicodeToMultiByteN(
            _Out_writes_bytes_to_(MaxBytesInMultiByteString, *BytesInMultiByteString) PCHAR MultiByteString,
            _In_ ULONG MaxBytesInMultiByteString,
            _Out_opt_ PULONG BytesInMultiByteString,
            _In_reads_bytes_(BytesInUnicodeString) PCWCH UnicodeString,
            _In_ ULONG BytesInUnicodeString
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlUnicodeToMultiByteSize(
            _Out_ PULONG BytesInMultiByteString,
            _In_reads_bytes_(BytesInUnicodeString) PCWCH UnicodeString,
            _In_ ULONG BytesInUnicodeString
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlUpcaseUnicodeToMultiByteN(
            _Out_writes_bytes_to_(MaxBytesInMultiByteString, *BytesInMultiByteString) PCHAR MultiByteString,
            _In_ ULONG MaxBytesInMultiByteString,
            _Out_opt_ PULONG BytesInMultiByteString,
            _In_reads_bytes_(BytesInUnicodeString) PCWCH UnicodeString,
            _In_ ULONG BytesInUnicodeString
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlOemToUnicodeN(
            _Out_writes_bytes_to_(MaxBytesInUnicodeString, *BytesInUnicodeString) PWSTR UnicodeString,
            _In_ ULONG MaxBytesInUnicodeString,
            _Out_opt_ PULONG BytesInUnicodeString,
            _In_reads_bytes_(BytesInOemString) PCCH OemString,
            _In_ ULONG BytesInOemString
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlUnicodeToOemN(
            _Out_writes_bytes_to_(MaxBytesInOemString, *BytesInOemString) PCHAR OemString,
            _In_ ULONG MaxBytesInOemString,
            _Out_opt_ PULONG BytesInOemString,
            _In_reads_bytes_(BytesInUnicodeString) PCWCH UnicodeString,
            _In_ ULONG BytesInUnicodeString
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlUpcaseUnicodeToOemN(
            _Out_writes_bytes_to_(MaxBytesInOemString, *BytesInOemString) PCHAR OemString,
            _In_ ULONG MaxBytesInOemString,
            _Out_opt_ PULONG BytesInOemString,
            _In_reads_bytes_(BytesInUnicodeString) PCWCH UnicodeString,
            _In_ ULONG BytesInUnicodeString
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlConsoleMultiByteToUnicodeN(
            _Out_writes_bytes_to_(MaxBytesInUnicodeString, *BytesInUnicodeString) PWCH UnicodeString,
            _In_ ULONG MaxBytesInUnicodeString,
            _Out_opt_ PULONG BytesInUnicodeString,
            _In_reads_bytes_(BytesInMultiByteString) PCCH MultiByteString,
            _In_ ULONG BytesInMultiByteString,
            _Out_ PULONG pdwSpecialChar
        );

#if (PHNT_VERSION >= PHNT_WIN7)
    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlUTF8ToUnicodeN(
            _Out_writes_bytes_to_(UnicodeStringMaxByteCount, *UnicodeStringActualByteCount) PWSTR UnicodeStringDestination,
            _In_ ULONG UnicodeStringMaxByteCount,
            _Out_opt_ PULONG UnicodeStringActualByteCount,
            _In_reads_bytes_(UTF8StringByteCount) PCCH UTF8StringSource,
            _In_ ULONG UTF8StringByteCount
        );
#endif

#if (PHNT_VERSION >= PHNT_WIN7)
    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlUnicodeToUTF8N(
            _Out_writes_bytes_to_(UTF8StringMaxByteCount, *UTF8StringActualByteCount) PCHAR UTF8StringDestination,
            _In_ ULONG UTF8StringMaxByteCount,
            _Out_opt_ PULONG UTF8StringActualByteCount,
            _In_reads_bytes_(UnicodeStringByteCount) PCWCH UnicodeStringSource,
            _In_ ULONG UnicodeStringByteCount
        );
#endif

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlCustomCPToUnicodeN(
            _In_ PCPTABLEINFO CustomCP,
            _Out_writes_bytes_to_(MaxBytesInUnicodeString, *BytesInUnicodeString) PWCH UnicodeString,
            _In_ ULONG MaxBytesInUnicodeString,
            _Out_opt_ PULONG BytesInUnicodeString,
            _In_reads_bytes_(BytesInCustomCPString) PCH CustomCPString,
            _In_ ULONG BytesInCustomCPString
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlUnicodeToCustomCPN(
            _In_ PCPTABLEINFO CustomCP,
            _Out_writes_bytes_to_(MaxBytesInCustomCPString, *BytesInCustomCPString) PCH CustomCPString,
            _In_ ULONG MaxBytesInCustomCPString,
            _Out_opt_ PULONG BytesInCustomCPString,
            _In_reads_bytes_(BytesInUnicodeString) PWCH UnicodeString,
            _In_ ULONG BytesInUnicodeString
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlUpcaseUnicodeToCustomCPN(
            _In_ PCPTABLEINFO CustomCP,
            _Out_writes_bytes_to_(MaxBytesInCustomCPString, *BytesInCustomCPString) PCH CustomCPString,
            _In_ ULONG MaxBytesInCustomCPString,
            _Out_opt_ PULONG BytesInCustomCPString,
            _In_reads_bytes_(BytesInUnicodeString) PWCH UnicodeString,
            _In_ ULONG BytesInUnicodeString
        );

    NTSYSAPI
        VOID
        NTAPI
        RtlInitCodePageTable(
            _In_reads_z_(2) PUSHORT TableBase,
            _Inout_ PCPTABLEINFO CodePageTable
        );

    NTSYSAPI
        VOID
        NTAPI
        RtlInitNlsTables(
            _In_ PUSHORT AnsiNlsBase,
            _In_ PUSHORT OemNlsBase,
            _In_ PUSHORT LanguageNlsBase,
            _Out_ PNLSTABLEINFO TableInfo // PCPTABLEINFO?
        );

    NTSYSAPI
        VOID
        NTAPI
        RtlResetRtlTranslations(
            _In_ PNLSTABLEINFO TableInfo
        );

    NTSYSAPI
        BOOLEAN
        NTAPI
        RtlIsTextUnicode(
            _In_ PVOID Buffer,
            _In_ ULONG Size,
            _Inout_opt_ PULONG Result
        );

    typedef enum _RTL_NORM_FORM
    {
        NormOther = 0x0,
        NormC = 0x1,
        NormD = 0x2,
        NormKC = 0x5,
        NormKD = 0x6,
        NormIdna = 0xd,
        DisallowUnassigned = 0x100,
        NormCDisallowUnassigned = 0x101,
        NormDDisallowUnassigned = 0x102,
        NormKCDisallowUnassigned = 0x105,
        NormKDDisallowUnassigned = 0x106,
        NormIdnaDisallowUnassigned = 0x10d
    } RTL_NORM_FORM;

#if (PHNT_VERSION >= PHNT_VISTA)
    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlNormalizeString(
            _In_ ULONG NormForm, // RTL_NORM_FORM
            _In_ PCWSTR SourceString,
            _In_ LONG SourceStringLength,
            _Out_writes_to_(*DestinationStringLength, *DestinationStringLength) PWSTR DestinationString,
            _Inout_ PLONG DestinationStringLength
        );
#endif

#if (PHNT_VERSION >= PHNT_VISTA)
    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlIsNormalizedString(
            _In_ ULONG NormForm, // RTL_NORM_FORM
            _In_ PCWSTR SourceString,
            _In_ LONG SourceStringLength,
            _Out_ PBOOLEAN Normalized
        );
#endif

#if (PHNT_VERSION >= PHNT_WIN7)
    // ntifs:FsRtlIsNameInExpression
    NTSYSAPI
        BOOLEAN
        NTAPI
        RtlIsNameInExpression(
            _In_ PUNICODE_STRING Expression,
            _In_ PUNICODE_STRING Name,
            _In_ BOOLEAN IgnoreCase,
            _In_opt_ PWCH UpcaseTable
        );
#endif

#if (PHNT_VERSION >= PHNT_REDSTONE4)
    // rev
    NTSYSAPI
        BOOLEAN
        NTAPI
        RtlIsNameInUnUpcasedExpression(
            _In_ PUNICODE_STRING Expression,
            _In_ PUNICODE_STRING Name,
            _In_ BOOLEAN IgnoreCase,
            _In_opt_ PWCH UpcaseTable
        );
#endif

#if (PHNT_VERSION >= PHNT_19H1)
    NTSYSAPI
        BOOLEAN
        NTAPI
        RtlDoesNameContainWildCards(
            _In_ PUNICODE_STRING Expression
        );
#endif

    NTSYSAPI
        BOOLEAN
        NTAPI
        RtlEqualDomainName(
            _In_ PUNICODE_STRING String1,
            _In_ PUNICODE_STRING String2
        );

    NTSYSAPI
        BOOLEAN
        NTAPI
        RtlEqualComputerName(
            _In_ PUNICODE_STRING String1,
            _In_ PUNICODE_STRING String2
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlDnsHostNameToComputerName(
            _Out_ PUNICODE_STRING ComputerNameString,
            _In_ PUNICODE_STRING DnsHostNameString,
            _In_ BOOLEAN AllocateComputerNameString
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlStringFromGUID(
            _In_ PGUID Guid,
            _Out_ PUNICODE_STRING GuidString
        );

#if (PHNT_VERSION >= PHNT_WINBLUE)

    // rev
    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlStringFromGUIDEx(
            _In_ PGUID Guid,
            _Inout_ PUNICODE_STRING GuidString,
            _In_ BOOLEAN AllocateGuidString
        );

#endif

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlGUIDFromString(
            _In_ PUNICODE_STRING GuidString,
            _Out_ PGUID Guid
        );

#if (PHNT_VERSION >= PHNT_VISTA)

    NTSYSAPI
        LONG
        NTAPI
        RtlCompareAltitudes(
            _In_ PUNICODE_STRING Altitude1,
            _In_ PUNICODE_STRING Altitude2
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlIdnToAscii(
            _In_ ULONG Flags,
            _In_ PCWSTR SourceString,
            _In_ LONG SourceStringLength,
            _Out_writes_to_(*DestinationStringLength, *DestinationStringLength) PWSTR DestinationString,
            _Inout_ PLONG DestinationStringLength
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlIdnToUnicode(
            _In_ ULONG Flags,
            _In_ PCWSTR SourceString,
            _In_ LONG SourceStringLength,
            _Out_writes_to_(*DestinationStringLength, *DestinationStringLength) PWSTR DestinationString,
            _Inout_ PLONG DestinationStringLength
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlIdnToNameprepUnicode(
            _In_ ULONG Flags,
            _In_ PCWSTR SourceString,
            _In_ LONG SourceStringLength,
            _Out_writes_to_(*DestinationStringLength, *DestinationStringLength) PWSTR DestinationString,
            _Inout_ PLONG DestinationStringLength
        );

#endif

    // Prefix

    typedef struct _PREFIX_TABLE_ENTRY
    {
        CSHORT NodeTypeCode;
        CSHORT NameLength;
        struct _PREFIX_TABLE_ENTRY* NextPrefixTree;
        RTL_SPLAY_LINKS Links;
        PSTRING Prefix;
    } PREFIX_TABLE_ENTRY, * PPREFIX_TABLE_ENTRY;

    typedef struct _PREFIX_TABLE
    {
        CSHORT NodeTypeCode;
        CSHORT NameLength;
        PPREFIX_TABLE_ENTRY NextPrefixTree;
    } PREFIX_TABLE, * PPREFIX_TABLE;

    NTSYSAPI
        VOID
        NTAPI
        PfxInitialize(
            _Out_ PPREFIX_TABLE PrefixTable
        );

    NTSYSAPI
        BOOLEAN
        NTAPI
        PfxInsertPrefix(
            _In_ PPREFIX_TABLE PrefixTable,
            _In_ PSTRING Prefix,
            _Out_ PPREFIX_TABLE_ENTRY PrefixTableEntry
        );

    NTSYSAPI
        VOID
        NTAPI
        PfxRemovePrefix(
            _In_ PPREFIX_TABLE PrefixTable,
            _In_ PPREFIX_TABLE_ENTRY PrefixTableEntry
        );

    NTSYSAPI
        PPREFIX_TABLE_ENTRY
        NTAPI
        PfxFindPrefix(
            _In_ PPREFIX_TABLE PrefixTable,
            _In_ PSTRING FullName
        );

    typedef struct _UNICODE_PREFIX_TABLE_ENTRY
    {
        CSHORT NodeTypeCode;
        CSHORT NameLength;
        struct _UNICODE_PREFIX_TABLE_ENTRY* NextPrefixTree;
        struct _UNICODE_PREFIX_TABLE_ENTRY* CaseMatch;
        RTL_SPLAY_LINKS Links;
        PUNICODE_STRING Prefix;
    } UNICODE_PREFIX_TABLE_ENTRY, * PUNICODE_PREFIX_TABLE_ENTRY;

    typedef struct _UNICODE_PREFIX_TABLE
    {
        CSHORT NodeTypeCode;
        CSHORT NameLength;
        PUNICODE_PREFIX_TABLE_ENTRY NextPrefixTree;
        PUNICODE_PREFIX_TABLE_ENTRY LastNextEntry;
    } UNICODE_PREFIX_TABLE, * PUNICODE_PREFIX_TABLE;

    NTSYSAPI
        VOID
        NTAPI
        RtlInitializeUnicodePrefix(
            _Out_ PUNICODE_PREFIX_TABLE PrefixTable
        );

    NTSYSAPI
        BOOLEAN
        NTAPI
        RtlInsertUnicodePrefix(
            _In_ PUNICODE_PREFIX_TABLE PrefixTable,
            _In_ PUNICODE_STRING Prefix,
            _Out_ PUNICODE_PREFIX_TABLE_ENTRY PrefixTableEntry
        );

    NTSYSAPI
        VOID
        NTAPI
        RtlRemoveUnicodePrefix(
            _In_ PUNICODE_PREFIX_TABLE PrefixTable,
            _In_ PUNICODE_PREFIX_TABLE_ENTRY PrefixTableEntry
        );

    NTSYSAPI
        PUNICODE_PREFIX_TABLE_ENTRY
        NTAPI
        RtlFindUnicodePrefix(
            _In_ PUNICODE_PREFIX_TABLE PrefixTable,
            _In_ PUNICODE_STRING FullName,
            _In_ ULONG CaseInsensitiveIndex
        );

    NTSYSAPI
        PUNICODE_PREFIX_TABLE_ENTRY
        NTAPI
        RtlNextUnicodePrefix(
            _In_ PUNICODE_PREFIX_TABLE PrefixTable,
            _In_ BOOLEAN Restart
        );

    // Compression

    typedef struct _COMPRESSED_DATA_INFO
    {
        USHORT CompressionFormatAndEngine; // COMPRESSION_FORMAT_* and COMPRESSION_ENGINE_*

        UCHAR CompressionUnitShift;
        UCHAR ChunkShift;
        UCHAR ClusterShift;
        UCHAR Reserved;

        USHORT NumberOfChunks;

        ULONG CompressedChunkSizes[1];
    } COMPRESSED_DATA_INFO, * PCOMPRESSED_DATA_INFO;

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlGetCompressionWorkSpaceSize(
            _In_ USHORT CompressionFormatAndEngine,
            _Out_ PULONG CompressBufferWorkSpaceSize,
            _Out_ PULONG CompressFragmentWorkSpaceSize
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlCompressBuffer(
            _In_ USHORT CompressionFormatAndEngine,
            _In_reads_bytes_(UncompressedBufferSize) PUCHAR UncompressedBuffer,
            _In_ ULONG UncompressedBufferSize,
            _Out_writes_bytes_to_(CompressedBufferSize, *FinalCompressedSize) PUCHAR CompressedBuffer,
            _In_ ULONG CompressedBufferSize,
            _In_ ULONG UncompressedChunkSize,
            _Out_ PULONG FinalCompressedSize,
            _In_ PVOID WorkSpace
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlDecompressBuffer(
            _In_ USHORT CompressionFormat,
            _Out_writes_bytes_to_(UncompressedBufferSize, *FinalUncompressedSize) PUCHAR UncompressedBuffer,
            _In_ ULONG UncompressedBufferSize,
            _In_reads_bytes_(CompressedBufferSize) PUCHAR CompressedBuffer,
            _In_ ULONG CompressedBufferSize,
            _Out_ PULONG FinalUncompressedSize
        );

#if (PHNT_VERSION >= PHNT_WIN8)
    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlDecompressBufferEx(
            _In_ USHORT CompressionFormat,
            _Out_writes_bytes_to_(UncompressedBufferSize, *FinalUncompressedSize) PUCHAR UncompressedBuffer,
            _In_ ULONG UncompressedBufferSize,
            _In_reads_bytes_(CompressedBufferSize) PUCHAR CompressedBuffer,
            _In_ ULONG CompressedBufferSize,
            _Out_ PULONG FinalUncompressedSize,
            _In_opt_ PVOID WorkSpace
        );
#endif

#if (PHNT_VERSION >= PHNT_WINBLUE)
    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlDecompressBufferEx2(
            _In_ USHORT CompressionFormat,
            _Out_writes_bytes_to_(UncompressedBufferSize, *FinalUncompressedSize) PUCHAR UncompressedBuffer,
            _In_ ULONG UncompressedBufferSize,
            _In_reads_bytes_(CompressedBufferSize) PUCHAR CompressedBuffer,
            _In_ ULONG CompressedBufferSize,
            _In_ ULONG UncompressedChunkSize,
            _Out_ PULONG FinalUncompressedSize,
            _In_opt_ PVOID WorkSpace
        );
#endif

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlDecompressFragment(
            _In_ USHORT CompressionFormat,
            _Out_writes_bytes_to_(UncompressedFragmentSize, *FinalUncompressedSize) PUCHAR UncompressedFragment,
            _In_ ULONG UncompressedFragmentSize,
            _In_reads_bytes_(CompressedBufferSize) PUCHAR CompressedBuffer,
            _In_ ULONG CompressedBufferSize,
            _In_range_(< , CompressedBufferSize) ULONG FragmentOffset,
            _Out_ PULONG FinalUncompressedSize,
            _In_ PVOID WorkSpace
        );

#if (PHNT_VERSION >= PHNT_WINBLUE)
    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlDecompressFragmentEx(
            _In_ USHORT CompressionFormat,
            _Out_writes_bytes_to_(UncompressedFragmentSize, *FinalUncompressedSize) PUCHAR UncompressedFragment,
            _In_ ULONG UncompressedFragmentSize,
            _In_reads_bytes_(CompressedBufferSize) PUCHAR CompressedBuffer,
            _In_ ULONG CompressedBufferSize,
            _In_range_(< , CompressedBufferSize) ULONG FragmentOffset,
            _In_ ULONG UncompressedChunkSize,
            _Out_ PULONG FinalUncompressedSize,
            _In_ PVOID WorkSpace
        );
#endif

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlDescribeChunk(
            _In_ USHORT CompressionFormat,
            _Inout_ PUCHAR* CompressedBuffer,
            _In_ PUCHAR EndOfCompressedBufferPlus1,
            _Out_ PUCHAR* ChunkBuffer,
            _Out_ PULONG ChunkSize
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlReserveChunk(
            _In_ USHORT CompressionFormat,
            _Inout_ PUCHAR* CompressedBuffer,
            _In_ PUCHAR EndOfCompressedBufferPlus1,
            _Out_ PUCHAR* ChunkBuffer,
            _In_ ULONG ChunkSize
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlDecompressChunks(
            _Out_writes_bytes_(UncompressedBufferSize) PUCHAR UncompressedBuffer,
            _In_ ULONG UncompressedBufferSize,
            _In_reads_bytes_(CompressedBufferSize) PUCHAR CompressedBuffer,
            _In_ ULONG CompressedBufferSize,
            _In_reads_bytes_(CompressedTailSize) PUCHAR CompressedTail,
            _In_ ULONG CompressedTailSize,
            _In_ PCOMPRESSED_DATA_INFO CompressedDataInfo
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlCompressChunks(
            _In_reads_bytes_(UncompressedBufferSize) PUCHAR UncompressedBuffer,
            _In_ ULONG UncompressedBufferSize,
            _Out_writes_bytes_(CompressedBufferSize) PUCHAR CompressedBuffer,
            _In_range_(>= , (UncompressedBufferSize - (UncompressedBufferSize / 16))) ULONG CompressedBufferSize,
            _Inout_updates_bytes_(CompressedDataInfoLength) PCOMPRESSED_DATA_INFO CompressedDataInfo,
            _In_range_(> , sizeof(COMPRESSED_DATA_INFO)) ULONG CompressedDataInfoLength,
            _In_ PVOID WorkSpace
        );

    // Locale

#if (PHNT_VERSION >= PHNT_VISTA)

// private
    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlConvertLCIDToString(
            _In_ LCID LcidValue,
            _In_ ULONG Base,
            _In_ ULONG Padding, // string is padded to this width
            _Out_writes_(Size) PWSTR pResultBuf,
            _In_ ULONG Size
        );

    // private
    NTSYSAPI
        BOOLEAN
        NTAPI
        RtlIsValidLocaleName(
            _In_ PCWSTR LocaleName,
            _In_ ULONG Flags
        );

    // private
    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlGetParentLocaleName(
            _In_ PCWSTR LocaleName,
            _Inout_ PUNICODE_STRING ParentLocaleName,
            _In_ ULONG Flags,
            _In_ BOOLEAN AllocateDestinationString
        );

    // private
    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlLcidToLocaleName(
            _In_ LCID lcid, // sic
            _Inout_ PUNICODE_STRING LocaleName,
            _In_ ULONG Flags,
            _In_ BOOLEAN AllocateDestinationString
        );

    // private
    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlLocaleNameToLcid(
            _In_ PCWSTR LocaleName,
            _Out_ PLCID lcid,
            _In_ ULONG Flags
        );

    // private
    NTSYSAPI
        BOOLEAN
        NTAPI
        RtlLCIDToCultureName(
            _In_ LCID Lcid,
            _Inout_ PUNICODE_STRING String
        );

    // private
    NTSYSAPI
        BOOLEAN
        NTAPI
        RtlCultureNameToLCID(
            _In_ PUNICODE_STRING String,
            _Out_ PLCID Lcid
        );

    // private
    NTSYSAPI
        VOID
        NTAPI
        RtlCleanUpTEBLangLists(
            VOID
        );

#endif

#if (PHNT_VERSION >= PHNT_WIN7)

    // rev from GetThreadPreferredUILanguages
    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlGetThreadPreferredUILanguages(
            _In_ ULONG Flags, // MUI_LANGUAGE_NAME
            _Out_ PULONG NumberOfLanguages,
            _Out_writes_opt_(*ReturnLength) PZZWSTR Languages,
            _Inout_ PULONG ReturnLength
        );

    // rev from GetProcessPreferredUILanguages
    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlGetProcessPreferredUILanguages(
            _In_ ULONG Flags, // MUI_LANGUAGE_NAME
            _Out_ PULONG NumberOfLanguages,
            _Out_writes_opt_(*ReturnLength) PZZWSTR Languages,
            _Inout_ PULONG ReturnLength
        );

    // rev from GetSystemPreferredUILanguages
    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlGetSystemPreferredUILanguages(
            _In_ ULONG Flags, // MUI_LANGUAGE_NAME
            _In_ PCWSTR LocaleName,
            _Out_ PULONG NumberOfLanguages,
            _Out_writes_opt_(*ReturnLength) PZZWSTR Languages,
            _Inout_ PULONG ReturnLength
        );

    // rev from GetSystemDefaultUILanguage
    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlpGetSystemDefaultUILanguage(
            _Out_ LANGID DefaultUILanguageId,
            _Inout_ PLCID Lcid
        );

    // rev from GetUserPreferredUILanguages
    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlGetUserPreferredUILanguages(
            _In_ ULONG Flags, // MUI_LANGUAGE_NAME
            _In_ PCWSTR LocaleName,
            _Out_ PULONG NumberOfLanguages,
            _Out_writes_opt_(*ReturnLength) PZZWSTR Languages,
            _Inout_ PULONG ReturnLength
        );

    // rev from GetUILanguageInfo
    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlGetUILanguageInfo(
            _In_ ULONG Flags,
            _In_ PCZZWSTR Languages,
            _Out_writes_opt_(*NumberOfFallbackLanguages) PZZWSTR FallbackLanguages,
            _Inout_opt_ PULONG NumberOfFallbackLanguages,
            _Out_ PULONG Attributes
        );

    // rev
    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlGetLocaleFileMappingAddress(
            _Out_ PVOID* BaseAddress,
            _Out_ PLCID DefaultLocaleId,
            _Out_ PLARGE_INTEGER DefaultCasingTableSize,
            _Out_opt_ PULONG CurrentNLSVersion
        );

#endif

    // PEB

    NTSYSAPI
        PPEB
        NTAPI
        RtlGetCurrentPeb(
            VOID
        );

#ifndef PHNT_INLINE_PEB_LOCK
    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlAcquirePebLock(
            VOID
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlReleasePebLock(
            VOID
        );
#else
    FORCEINLINE
        NTSTATUS
        NTAPI
        RtlAcquirePebLock(
            VOID
        )
    {
        return RtlEnterCriticalSection(NtCurrentPeb()->FastPebLock)
    }

    FORCEINLINE
        NTSTATUS
        NTAPI
        RtlReleasePebLock(
            VOID
        )
    {
        return RtlLeaveCriticalSection(NtCurrentPeb()->FastPebLock)
    }
#endif

#if (PHNT_VERSION >= PHNT_VISTA)
    // private
    NTSYSAPI
        LOGICAL
        NTAPI
        RtlTryAcquirePebLock(
            VOID
        );
#endif

#if (PHNT_VERSION < PHNT_VISTA)
    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlAllocateFromPeb(
            _In_ ULONG Size,
            _Out_ PVOID* Block
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlFreeToPeb(
            _In_ PVOID Block,
            _In_ ULONG Size
        );
#endif

    // Processes

    typedef struct _CURDIR
    {
        UNICODE_STRING DosPath;
        HANDLE Handle;
    } CURDIR, * PCURDIR;

#define RTL_USER_PROC_CURDIR_CLOSE 0x00000002
#define RTL_USER_PROC_CURDIR_INHERIT 0x00000003

    typedef struct _RTL_DRIVE_LETTER_CURDIR
    {
        USHORT Flags;
        USHORT Length;
        ULONG TimeStamp;
        STRING DosPath;
    } RTL_DRIVE_LETTER_CURDIR, * PRTL_DRIVE_LETTER_CURDIR;

#define RTL_MAX_DRIVE_LETTERS 32
#define RTL_DRIVE_LETTER_VALID (USHORT)0x0001

    typedef struct _RTL_USER_PROCESS_PARAMETERS
    {
        ULONG MaximumLength;
        ULONG Length;

        ULONG Flags;
        ULONG DebugFlags;

        HANDLE ConsoleHandle;
        ULONG ConsoleFlags;
        HANDLE StandardInput;
        HANDLE StandardOutput;
        HANDLE StandardError;

        CURDIR CurrentDirectory;
        UNICODE_STRING DllPath;
        UNICODE_STRING ImagePathName;
        UNICODE_STRING CommandLine;
        PVOID Environment;

        ULONG StartingX;
        ULONG StartingY;
        ULONG CountX;
        ULONG CountY;
        ULONG CountCharsX;
        ULONG CountCharsY;
        ULONG FillAttribute;

        ULONG WindowFlags;
        ULONG ShowWindowFlags;
        UNICODE_STRING WindowTitle;
        UNICODE_STRING DesktopInfo;
        UNICODE_STRING ShellInfo;
        UNICODE_STRING RuntimeData;
        RTL_DRIVE_LETTER_CURDIR CurrentDirectories[RTL_MAX_DRIVE_LETTERS];

        ULONG_PTR EnvironmentSize;
        ULONG_PTR EnvironmentVersion;

        PVOID PackageDependencyData;
        ULONG ProcessGroupId;
        ULONG LoaderThreads;

        UNICODE_STRING RedirectionDllName; // REDSTONE4
        UNICODE_STRING HeapPartitionName; // 19H1
        ULONG_PTR DefaultThreadpoolCpuSetMasks;
        ULONG DefaultThreadpoolCpuSetMaskCount;
        ULONG DefaultThreadpoolThreadMaximum;
        ULONG HeapMemoryTypeMask; // WIN11
    } RTL_USER_PROCESS_PARAMETERS, * PRTL_USER_PROCESS_PARAMETERS;

#define RTL_USER_PROC_PARAMS_NORMALIZED 0x00000001
#define RTL_USER_PROC_PROFILE_USER 0x00000002
#define RTL_USER_PROC_PROFILE_KERNEL 0x00000004
#define RTL_USER_PROC_PROFILE_SERVER 0x00000008
#define RTL_USER_PROC_RESERVE_1MB 0x00000020
#define RTL_USER_PROC_RESERVE_16MB 0x00000040
#define RTL_USER_PROC_CASE_SENSITIVE 0x00000080
#define RTL_USER_PROC_DISABLE_HEAP_DECOMMIT 0x00000100
#define RTL_USER_PROC_DLL_REDIRECTION_LOCAL 0x00001000
#define RTL_USER_PROC_APP_MANIFEST_PRESENT 0x00002000
#define RTL_USER_PROC_IMAGE_KEY_MISSING 0x00004000
#define RTL_USER_PROC_OPTIN_PROCESS 0x00020000

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlCreateProcessParameters(
            _Out_ PRTL_USER_PROCESS_PARAMETERS* pProcessParameters,
            _In_ PUNICODE_STRING ImagePathName,
            _In_opt_ PUNICODE_STRING DllPath,
            _In_opt_ PUNICODE_STRING CurrentDirectory,
            _In_opt_ PUNICODE_STRING CommandLine,
            _In_opt_ PVOID Environment,
            _In_opt_ PUNICODE_STRING WindowTitle,
            _In_opt_ PUNICODE_STRING DesktopInfo,
            _In_opt_ PUNICODE_STRING ShellInfo,
            _In_opt_ PUNICODE_STRING RuntimeData
        );

#if (PHNT_VERSION >= PHNT_VISTA)
    // private
    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlCreateProcessParametersEx(
            _Out_ PRTL_USER_PROCESS_PARAMETERS* pProcessParameters,
            _In_ PUNICODE_STRING ImagePathName,
            _In_opt_ PUNICODE_STRING DllPath,
            _In_opt_ PUNICODE_STRING CurrentDirectory,
            _In_opt_ PUNICODE_STRING CommandLine,
            _In_opt_ PVOID Environment,
            _In_opt_ PUNICODE_STRING WindowTitle,
            _In_opt_ PUNICODE_STRING DesktopInfo,
            _In_opt_ PUNICODE_STRING ShellInfo,
            _In_opt_ PUNICODE_STRING RuntimeData,
            _In_ ULONG Flags // pass RTL_USER_PROC_PARAMS_NORMALIZED to keep parameters normalized
        );
#endif

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlDestroyProcessParameters(
            _In_ _Post_invalid_ PRTL_USER_PROCESS_PARAMETERS ProcessParameters
        );

    NTSYSAPI
        PRTL_USER_PROCESS_PARAMETERS
        NTAPI
        RtlNormalizeProcessParams(
            _Inout_ PRTL_USER_PROCESS_PARAMETERS ProcessParameters
        );

    NTSYSAPI
        PRTL_USER_PROCESS_PARAMETERS
        NTAPI
        RtlDeNormalizeProcessParams(
            _Inout_ PRTL_USER_PROCESS_PARAMETERS ProcessParameters
        );

    typedef struct _RTL_USER_PROCESS_INFORMATION
    {
        ULONG Length;
        HANDLE ProcessHandle;
        HANDLE ThreadHandle;
        CLIENT_ID ClientId;
        SECTION_IMAGE_INFORMATION ImageInformation;
    } RTL_USER_PROCESS_INFORMATION, * PRTL_USER_PROCESS_INFORMATION;

    // private
    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlCreateUserProcess(
            _In_ PUNICODE_STRING NtImagePathName,
            _In_ ULONG AttributesDeprecated,
            _In_ PRTL_USER_PROCESS_PARAMETERS ProcessParameters,
            _In_opt_ PSECURITY_DESCRIPTOR ProcessSecurityDescriptor,
            _In_opt_ PSECURITY_DESCRIPTOR ThreadSecurityDescriptor,
            _In_opt_ HANDLE ParentProcess,
            _In_ BOOLEAN InheritHandles,
            _In_opt_ HANDLE DebugPort,
            _In_opt_ HANDLE TokenHandle, // used to be ExceptionPort
            _Out_ PRTL_USER_PROCESS_INFORMATION ProcessInformation
        );

#if (PHNT_VERSION >= PHNT_REDSTONE2)

#define RTL_USER_PROCESS_EXTENDED_PARAMETERS_VERSION 1

    // private
    typedef struct _RTL_USER_PROCESS_EXTENDED_PARAMETERS
    {
        USHORT Version;
        USHORT NodeNumber;
        PSECURITY_DESCRIPTOR ProcessSecurityDescriptor;
        PSECURITY_DESCRIPTOR ThreadSecurityDescriptor;
        HANDLE ParentProcess;
        HANDLE DebugPort;
        HANDLE TokenHandle;
        HANDLE JobHandle;
    } RTL_USER_PROCESS_EXTENDED_PARAMETERS, * PRTL_USER_PROCESS_EXTENDED_PARAMETERS;

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlCreateUserProcessEx(
            _In_ PUNICODE_STRING NtImagePathName,
            _In_ PRTL_USER_PROCESS_PARAMETERS ProcessParameters,
            _In_ BOOLEAN InheritHandles,
            _In_opt_ PRTL_USER_PROCESS_EXTENDED_PARAMETERS ProcessExtendedParameters,
            _Out_ PRTL_USER_PROCESS_INFORMATION ProcessInformation
        );

#endif

#if (PHNT_VERSION >= PHNT_VISTA)
    DECLSPEC_NORETURN
        NTSYSAPI
        VOID
        NTAPI
        RtlExitUserProcess(
            _In_ NTSTATUS ExitStatus
        );
#else

#define RtlExitUserProcess RtlExitUserProcess_R

    DECLSPEC_NORETURN
        FORCEINLINE VOID RtlExitUserProcess_R(
            _In_ NTSTATUS ExitStatus
        )
    {
        ExitProcess(ExitStatus);
    }

#endif

#if (PHNT_VERSION >= PHNT_VISTA)

    // begin_rev
#define RTL_CLONE_PROCESS_FLAGS_CREATE_SUSPENDED 0x00000001
#define RTL_CLONE_PROCESS_FLAGS_INHERIT_HANDLES 0x00000002
#define RTL_CLONE_PROCESS_FLAGS_NO_SYNCHRONIZE 0x00000004 // don't update synchronization objects
// end_rev

// private
    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlCloneUserProcess(
            _In_ ULONG ProcessFlags,
            _In_opt_ PSECURITY_DESCRIPTOR ProcessSecurityDescriptor,
            _In_opt_ PSECURITY_DESCRIPTOR ThreadSecurityDescriptor,
            _In_opt_ HANDLE DebugPort,
            _Out_ PRTL_USER_PROCESS_INFORMATION ProcessInformation
        );

    // private
    NTSYSAPI
        VOID
        NTAPI
        RtlUpdateClonedCriticalSection(
            _Inout_ PRTL_CRITICAL_SECTION CriticalSection
        );

    // private
    NTSYSAPI
        VOID
        NTAPI
        RtlUpdateClonedSRWLock(
            _Inout_ PRTL_SRWLOCK SRWLock,
            _In_ LOGICAL Shared // TRUE to set to shared acquire
        );

    // rev
#define RTL_PROCESS_REFLECTION_FLAGS_INHERIT_HANDLES 0x2
#define RTL_PROCESS_REFLECTION_FLAGS_NO_SUSPEND 0x4
#define RTL_PROCESS_REFLECTION_FLAGS_NO_SYNCHRONIZE 0x8
#define RTL_PROCESS_REFLECTION_FLAGS_NO_CLOSE_EVENT 0x10

// private
    typedef struct _RTLP_PROCESS_REFLECTION_REFLECTION_INFORMATION
    {
        HANDLE ReflectionProcessHandle;
        HANDLE ReflectionThreadHandle;
        CLIENT_ID ReflectionClientId;
    } RTLP_PROCESS_REFLECTION_REFLECTION_INFORMATION, * PRTLP_PROCESS_REFLECTION_REFLECTION_INFORMATION;

    typedef RTLP_PROCESS_REFLECTION_REFLECTION_INFORMATION PROCESS_REFLECTION_INFORMATION, * PPROCESS_REFLECTION_INFORMATION;

#if (PHNT_VERSION >= PHNT_WIN7)
    // rev
    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlCreateProcessReflection(
            _In_ HANDLE ProcessHandle,
            _In_ ULONG Flags, // RTL_PROCESS_REFLECTION_FLAGS_*
            _In_opt_ PVOID StartRoutine,
            _In_opt_ PVOID StartContext,
            _In_opt_ HANDLE EventHandle,
            _Out_opt_ PRTLP_PROCESS_REFLECTION_REFLECTION_INFORMATION ReflectionInformation
        );
#endif

#endif

    NTSYSAPI
        NTSTATUS
        STDAPIVCALLTYPE
        RtlSetProcessIsCritical(
            _In_ BOOLEAN NewValue,
            _Out_opt_ PBOOLEAN OldValue,
            _In_ BOOLEAN CheckFlag
        );

    NTSYSAPI
        NTSTATUS
        STDAPIVCALLTYPE
        RtlSetThreadIsCritical(
            _In_ BOOLEAN NewValue,
            _Out_opt_ PBOOLEAN OldValue,
            _In_ BOOLEAN CheckFlag
        );

    // rev
    NTSYSAPI
        PVOID
        NTAPI
        RtlSetThreadSubProcessTag(
            _In_ PVOID SubProcessTag
        );

    // rev
    NTSYSAPI
        BOOLEAN
        NTAPI
        RtlValidProcessProtection(
            _In_ PS_PROTECTION ProcessProtection
        );

    // rev
    NTSYSAPI
        BOOLEAN
        NTAPI
        RtlTestProtectedAccess(
            _In_ PS_PROTECTION Source,
            _In_ PS_PROTECTION Target
        );

#if (PHNT_VERSION >= PHNT_REDSTONE3)
    // rev
    NTSYSAPI
        BOOLEAN
        NTAPI
        RtlIsCurrentProcess( // NtCompareObjects(NtCurrentProcess(), ProcessHandle)
            _In_ HANDLE ProcessHandle
        );

    // rev
    NTSYSAPI
        BOOLEAN
        NTAPI
        RtlIsCurrentThread( // NtCompareObjects(NtCurrentThread(), ThreadHandle)
            _In_ HANDLE ThreadHandle
        );
#endif

    // Threads

    typedef NTSTATUS(NTAPI* PUSER_THREAD_START_ROUTINE)(
        _In_ PVOID ThreadParameter
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlCreateUserThread(
            _In_ HANDLE ProcessHandle,
            _In_opt_ PSECURITY_DESCRIPTOR ThreadSecurityDescriptor,
            _In_ BOOLEAN CreateSuspended,
            _In_opt_ ULONG ZeroBits,
            _In_opt_ SIZE_T MaximumStackSize,
            _In_opt_ SIZE_T CommittedStackSize,
            _In_ PUSER_THREAD_START_ROUTINE StartAddress,
            _In_opt_ PVOID Parameter,
            _Out_opt_ PHANDLE ThreadHandle,
            _Out_opt_ PCLIENT_ID ClientId
        );

#if (PHNT_VERSION >= PHNT_VISTA) // should be PHNT_WINXP, but is PHNT_VISTA for consistency with RtlExitUserProcess
    DECLSPEC_NORETURN
        NTSYSAPI
        VOID
        NTAPI
        RtlExitUserThread(
            _In_ NTSTATUS ExitStatus
        );
#else

#define RtlExitUserThread RtlExitUserThread_R

    DECLSPEC_NORETURN
        FORCEINLINE VOID RtlExitUserThread_R(
            _In_ NTSTATUS ExitStatus
        )
    {
        ExitThread(ExitStatus);
    }

#endif

#if (PHNT_VERSION >= PHNT_VISTA)

    // rev
    NTSYSAPI
        BOOLEAN
        NTAPI
        RtlIsCurrentThreadAttachExempt(
            VOID
        );

#endif

#if (PHNT_VERSION >= PHNT_VISTA)

    // private
    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlCreateUserStack(
            _In_opt_ SIZE_T CommittedStackSize,
            _In_opt_ SIZE_T MaximumStackSize,
            _In_opt_ ULONG_PTR ZeroBits,
            _In_ SIZE_T PageSize,
            _In_ ULONG_PTR ReserveAlignment,
            _Out_ PINITIAL_TEB InitialTeb
        );

    // private
    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlFreeUserStack(
            _In_ PVOID AllocationBase
        );

#endif

    // Extended thread context

    typedef struct _CONTEXT_CHUNK
    {
        LONG Offset; // Offset may be negative.
        ULONG Length;
    } CONTEXT_CHUNK, * PCONTEXT_CHUNK;

    typedef struct _CONTEXT_EX
    {
        CONTEXT_CHUNK All;
        CONTEXT_CHUNK Legacy;
        CONTEXT_CHUNK XState;
        CONTEXT_CHUNK KernelCet;
    } CONTEXT_EX, * PCONTEXT_EX;

#if defined(_AMD64_) || defined(_ARM64_) || defined(_ARM64EC_)
#define CONTEXT_ALIGN 0x10
#else
#define CONTEXT_ALIGN 0x8
#endif

#if defined(_AMD64_)
#define CONTEXT_FRAME_LENGTH 0x4D0
#define CONTEXT_EX_PADDING   0x10
#elif defined(_ARM64_) || defined(_ARM64EC_)
#define CONTEXT_FRAME_LENGTH 0x390
#define CONTEXT_EX_PADDING   0x10
#elif defined(_M_ARM)
#define CONTEXT_FRAME_LENGTH 0x1a0
#define CONTEXT_EX_PADDING   0x8
#else
#define CONTEXT_FRAME_LENGTH 0x2CC
#define CONTEXT_EX_PADDING   0x4
#endif

#define CONTEXT_ALIGNMENT(Size, Align) \
    (((ULONG_PTR)(Size) + (Align) - 1) & ~((Align) - 1))

#define CONTEXT_EX_LENGTH \
    CONTEXT_ALIGNMENT(sizeof(CONTEXT_EX), CONTEXT_ALIGN)

    C_ASSERT(CONTEXT_FRAME_LENGTH == sizeof(CONTEXT));
    C_ASSERT(CONTEXT_EX_LENGTH == 0x20);

#define RTL_CONTEXT_EX_OFFSET(ContextEx, Chunk) ((ContextEx)->Chunk.Offset)
#define RTL_CONTEXT_EX_LENGTH(ContextEx, Chunk) ((ContextEx)->Chunk.Length)
#define RTL_CONTEXT_EX_CHUNK(Base, Layout, Chunk) ((PVOID)((PCHAR)(Base) + RTL_CONTEXT_EX_OFFSET(Layout, Chunk)))
#define RTL_CONTEXT_OFFSET(Context, Chunk) RTL_CONTEXT_EX_OFFSET((PCONTEXT_EX)(Context + 1), Chunk)
#define RTL_CONTEXT_LENGTH(Context, Chunk) RTL_CONTEXT_EX_LENGTH((PCONTEXT_EX)(Context + 1), Chunk)
#define RTL_CONTEXT_CHUNK(Context, Chunk) RTL_CONTEXT_EX_CHUNK((PCONTEXT_EX)(Context + 1), (PCONTEXT_EX)(Context + 1), Chunk)

#if defined(_M_AMD64)
    // returns constant 0xf0e0d0c0a0908070 (dmex)
    NTSYSAPI
        ULONG64
        NTAPI
        RtlInitializeContext(
            _Reserved_ HANDLE Reserved,
            _Out_ PCONTEXT Context,
            _In_opt_ PVOID Parameter,
            _In_opt_ PVOID InitialPc,
            _In_opt_ PVOID InitialSp
        );
#else
    // returns status of NtWriteVirtualMemory (dmex)
    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlInitializeContext(
            _In_ HANDLE ProcessHandle,
            _Out_ PCONTEXT Context,
            _In_opt_ PVOID Parameter,
            _In_opt_ PVOID InitialPc,
            _In_opt_ PVOID InitialSp
        );
#endif

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlInitializeExtendedContext(
            _Out_ PCONTEXT Context,
            _In_ ULONG ContextFlags,
            _Out_ PCONTEXT_EX* ContextEx
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlInitializeExtendedContext2(
            _Out_ PCONTEXT Context,
            _In_ ULONG ContextFlags,
            _Out_ PCONTEXT_EX* ContextEx,
            _In_ ULONG64 EnabledExtendedFeatures // RtlGetEnabledExtendedFeatures(-1)
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlCopyContext(
            _Inout_ PCONTEXT Context,
            _In_ ULONG ContextFlags,
            _Out_ PCONTEXT Source
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlCopyExtendedContext(
            _Out_ PCONTEXT_EX Destination,
            _In_ ULONG ContextFlags,
            _In_ PCONTEXT_EX Source
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlGetExtendedContextLength(
            _In_ ULONG ContextFlags,
            _Out_ PULONG ContextLength
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlGetExtendedContextLength2(
            _In_ ULONG ContextFlags,
            _Out_ PULONG ContextLength,
            _In_ ULONG64 EnabledExtendedFeatures // RtlGetEnabledExtendedFeatures(-1)
        );

    NTSYSAPI
        ULONG64
        NTAPI
        RtlGetExtendedFeaturesMask(
            _In_ PCONTEXT_EX ContextEx
        );

    NTSYSAPI
        PVOID
        NTAPI
        RtlLocateExtendedFeature(
            _In_ PCONTEXT_EX ContextEx,
            _In_ ULONG FeatureId,
            _Out_opt_ PULONG Length
        );

    NTSYSAPI
        PCONTEXT
        NTAPI
        RtlLocateLegacyContext(
            _In_ PCONTEXT_EX ContextEx,
            _Out_opt_ PULONG Length
        );

    NTSYSAPI
        VOID
        NTAPI
        RtlSetExtendedFeaturesMask(
            _In_ PCONTEXT_EX ContextEx,
            _In_ ULONG64 FeatureMask
        );

#ifdef _WIN64
    // rev
    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlWow64GetThreadContext(
            _In_ HANDLE ThreadHandle,
            _Inout_ PWOW64_CONTEXT ThreadContext
        );
#endif

#ifdef _WIN64
    // rev
    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlWow64SetThreadContext(
            _In_ HANDLE ThreadHandle,
            _In_ PWOW64_CONTEXT ThreadContext
        );
#endif

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlRemoteCall(
            _In_ HANDLE ProcessHandle,
            _In_ HANDLE ThreadHandle,
            _In_ PVOID CallSite,
            _In_ ULONG ArgumentCount,
            _In_opt_ PULONG_PTR Arguments,
            _In_ BOOLEAN PassContext,
            _In_ BOOLEAN AlreadySuspended
        );

    // Vectored Exception Handlers

    NTSYSAPI
        PVOID
        NTAPI
        RtlAddVectoredExceptionHandler(
            _In_ ULONG First,
            _In_ PVECTORED_EXCEPTION_HANDLER Handler
        );

    NTSYSAPI
        ULONG
        NTAPI
        RtlRemoveVectoredExceptionHandler(
            _In_ PVOID Handle
        );

    NTSYSAPI
        PVOID
        NTAPI
        RtlAddVectoredContinueHandler(
            _In_ ULONG First,
            _In_ PVECTORED_EXCEPTION_HANDLER Handler
        );

    NTSYSAPI
        ULONG
        NTAPI
        RtlRemoveVectoredContinueHandler(
            _In_ PVOID Handle
        );

    // Runtime exception handling

    typedef ULONG(NTAPI* PRTLP_UNHANDLED_EXCEPTION_FILTER)(
        _In_ PEXCEPTION_POINTERS ExceptionInfo
        );

    NTSYSAPI
        VOID
        NTAPI
        RtlSetUnhandledExceptionFilter(
            _In_ PRTLP_UNHANDLED_EXCEPTION_FILTER UnhandledExceptionFilter
        );

    // rev
    NTSYSAPI
        LONG
        NTAPI
        RtlUnhandledExceptionFilter(
            _In_ PEXCEPTION_POINTERS ExceptionPointers
        );

    // rev
    NTSYSAPI
        LONG
        NTAPI
        RtlUnhandledExceptionFilter2(
            _In_ PEXCEPTION_POINTERS ExceptionPointers,
            _In_ ULONG Flags
        );

    // rev
    NTSYSAPI
        LONG
        NTAPI
        RtlKnownExceptionFilter(
            _In_ PEXCEPTION_POINTERS ExceptionPointers
        );

#ifdef _WIN64

    // private
    typedef enum _FUNCTION_TABLE_TYPE
    {
        RF_SORTED,
        RF_UNSORTED,
        RF_CALLBACK,
        RF_KERNEL_DYNAMIC
    } FUNCTION_TABLE_TYPE;

    // private
    typedef struct _DYNAMIC_FUNCTION_TABLE
    {
        LIST_ENTRY ListEntry;
        PRUNTIME_FUNCTION FunctionTable;
        LARGE_INTEGER TimeStamp;
        ULONG64 MinimumAddress;
        ULONG64 MaximumAddress;
        ULONG64 BaseAddress;
        PGET_RUNTIME_FUNCTION_CALLBACK Callback;
        PVOID Context;
        PWSTR OutOfProcessCallbackDll;
        FUNCTION_TABLE_TYPE Type;
        ULONG EntryCount;
        RTL_BALANCED_NODE TreeNodeMin;
        RTL_BALANCED_NODE TreeNodeMax;
    } DYNAMIC_FUNCTION_TABLE, * PDYNAMIC_FUNCTION_TABLE;

    // rev
    NTSYSAPI
        PLIST_ENTRY
        NTAPI
        RtlGetFunctionTableListHead(
            VOID
        );

#endif

    // Activation Contexts

#define INVALID_ACTIVATION_CONTEXT ((HANDLE)(LONG_PTR)-1)
#define ACTCTX_PROCESS_DEFAULT ((HANDLE)(LONG_PTR)0)
#define ACTCTX_EMPTY ((HANDLE)(LONG_PTR)-3)
#define ACTCTX_SYSTEM_DEFAULT ((HANDLE)(LONG_PTR)-4)
#define IS_SPECIAL_ACTCTX(x) (((((LONG_PTR)(x)) - 1) | 7) == -1)

// private
    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlGetActiveActivationContext(
            _Out_ PACTIVATION_CONTEXT ActivationContext
        );

    // private
    NTSYSAPI
        VOID
        NTAPI
        RtlAddRefActivationContext(
            _In_ PACTIVATION_CONTEXT ActivationContext
        );

    // private
    NTSYSAPI
        VOID
        NTAPI
        RtlReleaseActivationContext(
            _In_ PACTIVATION_CONTEXT ActivationContext
        );

    // private
    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlZombifyActivationContext(
            _In_ PACTIVATION_CONTEXT ActivationContext
        );

    // private
    NTSYSAPI
        BOOLEAN
        NTAPI
        RtlIsActivationContextActive(
            _In_ PACTIVATION_CONTEXT ActivationContext
        );

    // private
    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlActivateActivationContext(
            _Reserved_ ULONG Flags,
            _In_ PACTIVATION_CONTEXT ActivationContext,
            _Out_ PULONG_PTR Cookie
        );

#define RTL_ACTIVATE_ACTIVATION_CONTEXT_EX_FLAG_RELEASE_ON_STACK_DEALLOCATION 0x00000001

    // private
    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlActivateActivationContextEx(
            _In_ ULONG Flags,
            _In_ PTEB Teb,
            _In_ PACTIVATION_CONTEXT ActivationContext,
            _Out_ PULONG_PTR Cookie
        );

#define RTL_DEACTIVATE_ACTIVATION_CONTEXT_FLAG_FORCE_EARLY_DEACTIVATION 0x00000001

    // private
    NTSYSAPI
        VOID
        NTAPI
        RtlDeactivateActivationContext(
            _In_ ULONG Flags,
            _In_ ULONG_PTR Cookie
        );

    // private
    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlCreateActivationContext(
            _Reserved_ ULONG Flags,
            _In_ PACTIVATION_CONTEXT_DATA ActivationContextData,
            _In_opt_ ULONG ExtraBytes,
            _In_opt_ PACTIVATION_CONTEXT_NOTIFY_ROUTINE NotificationRoutine,
            _In_opt_ PVOID NotificationContext,
            _Out_ PACTIVATION_CONTEXT* ActivationContext
        );

#define FIND_ACTIVATION_CONTEXT_SECTION_KEY_RETURN_ACTIVATION_CONTEXT 0x00000001
#define FIND_ACTIVATION_CONTEXT_SECTION_KEY_RETURN_FLAGS 0x00000002
#define FIND_ACTIVATION_CONTEXT_SECTION_KEY_RETURN_ASSEMBLY_METADATA 0x00000004

    // private
    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlFindActivationContextSectionString(
            _In_ ULONG Flags,
            _In_opt_ PGUID ExtensionGuid,
            _In_ ULONG SectionId, // ACTIVATION_CONTEXT_SECTION_*
            _In_ PUNICODE_STRING StringToFind,
            _Inout_ PACTCTX_SECTION_KEYED_DATA ReturnedData
        );

    // private
    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlFindActivationContextSectionGuid(
            _In_ ULONG Flags,
            _In_opt_ PGUID ExtensionGuid,
            _In_ ULONG SectionId, // ACTIVATION_CONTEXT_SECTION_*
            _In_ PGUID GuidToFind,
            _Inout_ PACTCTX_SECTION_KEYED_DATA ReturnedData
        );

    // rev
    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlQueryActivationContextApplicationSettings(
            _Reserved_ ULONG Flags,
            _In_ PACTIVATION_CONTEXT ActivationContext,
            _In_ PWSTR SettingsNameSpace,
            _In_ PWSTR SettingName,
            _Out_writes_bytes_(BufferLength) PWSTR Buffer,
            _In_ SIZE_T BufferLength,
            _Out_opt_ PSIZE_T RequiredLength
        );

    // ACTIVATION_CONTEXT_INFO_CLASS
    //   ActivationContextBasicInformation                      // q: ACTIVATION_CONTEXT_BASIC_INFORMATION
    //   ActivationContextDetailedInformation                   // q: ACTIVATION_CONTEXT_DETAILED_INFORMATION
    //   AssemblyDetailedInformationInActivationContext         // q: ACTIVATION_CONTEXT_ASSEMBLY_DETAILED_INFORMATION
    //   FileInformationInAssemblyOfAssemblyInActivationContext // q: ASSEMBLY_FILE_DETAILED_INFORMATION
    //   RunlevelInformationInActivationContext                 // q: ACTIVATION_CONTEXT_RUN_LEVEL_INFORMATION
    //   CompatibilityInformationInActivationContext            // q: ACTIVATION_CONTEXT_COMPATIBILITY_INFORMATION[_LEGACY]
    //   ActivationContextManifestResourceName                  // q: ULONG

#define RTL_QUERY_INFORMATION_ACTIVATION_CONTEXT_FLAG_USE_ACTIVE_ACTIVATION_CONTEXT 0x00000001
#define RTL_QUERY_INFORMATION_ACTIVATION_CONTEXT_FLAG_ACTIVATION_CONTEXT_IS_MODULE 0x00000002
#define RTL_QUERY_INFORMATION_ACTIVATION_CONTEXT_FLAG_ACTIVATION_CONTEXT_IS_ADDRESS 0x00000004
#define RTL_QUERY_INFORMATION_ACTIVATION_CONTEXT_FLAG_NO_ADDREF 0x80000000

// private
    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlQueryInformationActivationContext(
            _In_ ULONG Flags,
            _In_opt_ PACTIVATION_CONTEXT ActivationContext,
            _In_opt_ PACTIVATION_CONTEXT_QUERY_INDEX SubInstanceIndex,
            _In_ ACTIVATION_CONTEXT_INFO_CLASS ActivationContextInformationClass,
            _Out_writes_bytes_(ActivationContextInformationLength) PVOID ActivationContextInformation,
            _In_ SIZE_T ActivationContextInformationLength,
            _Out_opt_ PSIZE_T ReturnLength
        );

#ifdef PHNT_INLINE_ACTIVE_ACTIVATION_CONTEXT
    // private
    FORCEINLINE
        NTSTATUS
        NTAPI
        RtlQueryInformationActiveActivationContext(
            _In_ ACTIVATION_CONTEXT_INFO_CLASS ActivationContextInformationClass,
            _Out_writes_bytes_(ActivationContextInformationLength) PVOID ActivationContextInformation,
            _In_ SIZE_T ActivationContextInformationLength,
            _Out_opt_ PSIZE_T ReturnLength
        )
    {
        return RtlQueryInformationActivationContext(
            RTL_QUERY_INFORMATION_ACTIVATION_CONTEXT_FLAG_USE_ACTIVE_ACTIVATION_CONTEXT,
            NULL,
            0,
            ActivationContextInformationClass,
            ActivationContextInformation,
            ActivationContextInformationLength,
            ReturnLength
        );
    }
#else
    // private
    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlQueryInformationActiveActivationContext(
            _In_ ACTIVATION_CONTEXT_INFO_CLASS ActivationContextInformationClass,
            _Out_writes_bytes_(ActivationContextInformationLength) PVOID ActivationContextInformation,
            _In_ SIZE_T ActivationContextInformationLength,
            _Out_opt_ PSIZE_T ReturnLength
        );
#endif

    // Images

    NTSYSAPI
        PIMAGE_NT_HEADERS
        NTAPI
        RtlImageNtHeader(
            _In_ PVOID BaseOfImage
        );

#define RTL_IMAGE_NT_HEADER_EX_FLAG_NO_RANGE_CHECK 0x00000001

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlImageNtHeaderEx(
            _In_ ULONG Flags,
            _In_ PVOID BaseOfImage,
            _In_ ULONG64 Size,
            _Out_ PIMAGE_NT_HEADERS* OutHeaders
        );

    NTSYSAPI
        PVOID
        NTAPI
        RtlAddressInSectionTable(
            _In_ PIMAGE_NT_HEADERS NtHeaders,
            _In_ PVOID BaseOfImage,
            _In_ ULONG VirtualAddress
        );

    NTSYSAPI
        PIMAGE_SECTION_HEADER
        NTAPI
        RtlSectionTableFromVirtualAddress(
            _In_ PIMAGE_NT_HEADERS NtHeaders,
            _In_ PVOID BaseOfImage,
            _In_ ULONG VirtualAddress
        );

    NTSYSAPI
        PVOID
        NTAPI
        RtlImageDirectoryEntryToData(
            _In_ PVOID BaseOfImage,
            _In_ BOOLEAN MappedAsImage,
            _In_ USHORT DirectoryEntry,
            _Out_ PULONG Size
        );

    NTSYSAPI
        PIMAGE_SECTION_HEADER
        NTAPI
        RtlImageRvaToSection(
            _In_ PIMAGE_NT_HEADERS NtHeaders,
            _In_ PVOID BaseOfImage,
            _In_ ULONG Rva
        );

    NTSYSAPI
        PVOID
        NTAPI
        RtlImageRvaToVa(
            _In_ PIMAGE_NT_HEADERS NtHeaders,
            _In_ PVOID BaseOfImage,
            _In_ ULONG Rva,
            _Out_opt_ PIMAGE_SECTION_HEADER* LastRvaSection
        );

#if (PHNT_VERSION >= PHNT_REDSTONE)

    // rev
    NTSYSAPI
        PVOID
        NTAPI
        RtlFindExportedRoutineByName(
            _In_ PVOID BaseOfImage,
            _In_ PCSTR RoutineName
        );

    // rev
    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlGuardCheckLongJumpTarget(
            _In_ PVOID PcValue,
            _In_ BOOL IsFastFail,
            _Out_ PBOOL IsLongJumpTarget
        );

#endif

#if (PHNT_VERSION >= PHNT_WIN11_22H2)
    NTSYSAPI
        VOID
        NTAPI
        RtlValidateUserCallTarget(
            _In_ PVOID Address,
            _Out_ PULONG Flags
        );
#endif

    // Memory

    _Must_inspect_result_
        NTSYSAPI
        SIZE_T
        NTAPI
        RtlCompareMemoryUlong(
            _In_reads_bytes_(Length) PVOID Source,
            _In_ SIZE_T Length,
            _In_ ULONG Pattern
        );

#if defined(_M_AMD64)
    FORCEINLINE
        VOID
        RtlFillMemoryUlong(
            _Out_writes_bytes_all_(Length) PVOID Destination,
            _In_ SIZE_T Length,
            _In_ ULONG Pattern
        )
    {
        PULONG Address = (PULONG)Destination;

        //
        // If the number of DWORDs is not zero, then fill the specified buffer
        // with the specified pattern.
        //

        if ((Length /= 4) != 0) {

            //
            // If the destination is not quadword aligned (ignoring low bits),
            // then align the destination by storing one DWORD.
            //

            if (((ULONG64)Address & 4) != 0) {
                *Address = Pattern;
                if ((Length -= 1) == 0) {
                    return;
                }

                Address += 1;
            }

            //
            // If the number of QWORDs is not zero, then fill the destination
            // buffer a QWORD at a time.
            //

            __stosq((PULONG64)(Address),
                Pattern | ((ULONG64)Pattern << 32),
                Length / 2);

            if ((Length & 1) != 0) {
                Address[Length - 1] = Pattern;
            }
        }

        return;
    }
#else
    NTSYSAPI
        VOID
        NTAPI
        RtlFillMemoryUlong(
            _Out_writes_bytes_all_(Length) PVOID Destination,
            _In_ SIZE_T Length,
            _In_ ULONG Pattern
        );
#endif

#if defined(_M_AMD64)

#define RtlFillMemoryUlonglong(Destination, Length, Pattern) \
    __stosq((PULONG64)(Destination), Pattern, (Length) / 8)

#else
    NTSYSAPI
        VOID
        NTAPI
        RtlFillMemoryUlonglong(
            _Out_writes_bytes_all_(Length) PVOID Destination,
            _In_ SIZE_T Length,
            _In_ ULONGLONG Pattern
        );
#endif

#if (PHNT_VERSION >= PHNT_19H2)
    NTSYSAPI
        BOOLEAN
        NTAPI
        RtlIsZeroMemory(
            _In_ PVOID Buffer,
            _In_ SIZE_T Length
        );
#endif

    // Environment

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlCreateEnvironment(
            _In_ BOOLEAN CloneCurrentEnvironment,
            _Out_ PVOID* Environment
        );

    // begin_rev
#define RTL_CREATE_ENVIRONMENT_TRANSLATE 0x1 // translate from multi-byte to Unicode
#define RTL_CREATE_ENVIRONMENT_TRANSLATE_FROM_OEM 0x2 // translate from OEM to Unicode (Translate flag must also be set)
#define RTL_CREATE_ENVIRONMENT_EMPTY 0x4 // create empty environment block
// end_rev

#if (PHNT_VERSION >= PHNT_VISTA)
// private
    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlCreateEnvironmentEx(
            _In_ PVOID SourceEnv,
            _Out_ PVOID* Environment,
            _In_ ULONG Flags
        );
#endif

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlDestroyEnvironment(
            _In_ _Post_invalid_ PVOID Environment
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlSetCurrentEnvironment(
            _In_ PVOID Environment,
            _Out_opt_ PVOID* PreviousEnvironment
        );

#if (PHNT_VERSION >= PHNT_VISTA)
    // private
    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlSetEnvironmentVar(
            _Inout_opt_ PVOID* Environment,
            _In_reads_(NameLength) PCWSTR Name,
            _In_ SIZE_T NameLength,
            _In_reads_(ValueLength) PCWSTR Value,
            _In_ SIZE_T ValueLength
        );
#endif

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlSetEnvironmentVariable(
            _Inout_opt_ PVOID* Environment,
            _In_ PUNICODE_STRING Name,
            _In_opt_ PUNICODE_STRING Value
        );

#if (PHNT_VERSION >= PHNT_VISTA)
    // private
    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlQueryEnvironmentVariable(
            _In_opt_ PVOID Environment,
            _In_reads_(NameLength) PCWSTR Name,
            _In_ SIZE_T NameLength,
            _Out_writes_opt_(ValueLength) PWSTR Value,
            _In_opt_ SIZE_T ValueLength,
            _Out_ PSIZE_T ReturnLength
        );
#endif

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlQueryEnvironmentVariable_U(
            _In_opt_ PVOID Environment,
            _In_ PUNICODE_STRING Name,
            _Inout_ PUNICODE_STRING Value
        );

#if (PHNT_VERSION >= PHNT_VISTA)
    // private
    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlExpandEnvironmentStrings(
            _In_opt_ PVOID Environment,
            _In_reads_(SourceLength) PCWSTR Source,
            _In_ SIZE_T SourceLength,
            _Out_writes_(DestinationLength) PWSTR Destination,
            _In_ SIZE_T DestinationLength,
            _Out_opt_ PSIZE_T ReturnLength
        );
#endif

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlExpandEnvironmentStrings_U(
            _In_opt_ PVOID Environment,
            _In_ PUNICODE_STRING Source,
            _Inout_ PUNICODE_STRING Destination,
            _Out_opt_ PULONG ReturnedLength
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlSetEnvironmentStrings(
            _In_ PCWCHAR NewEnvironment,
            _In_ SIZE_T NewEnvironmentSize
        );

    // Directory and path support

    typedef struct _RTLP_CURDIR_REF
    {
        LONG ReferenceCount;
        HANDLE DirectoryHandle;
    } RTLP_CURDIR_REF, * PRTLP_CURDIR_REF;

    typedef struct _RTL_RELATIVE_NAME_U
    {
        UNICODE_STRING RelativeName;
        HANDLE ContainingDirectory;
        PRTLP_CURDIR_REF CurDirRef;
    } RTL_RELATIVE_NAME_U, * PRTL_RELATIVE_NAME_U;

    typedef enum _RTL_PATH_TYPE
    {
        RtlPathTypeUnknown,
        RtlPathTypeUncAbsolute,
        RtlPathTypeDriveAbsolute,
        RtlPathTypeDriveRelative,
        RtlPathTypeRooted,
        RtlPathTypeRelative,
        RtlPathTypeLocalDevice,
        RtlPathTypeRootLocalDevice
    } RTL_PATH_TYPE;

    // Data exports (ntdll.lib/ntdllp.lib)

    NTSYSAPI PWSTR RtlNtdllName;
    NTSYSAPI UNICODE_STRING RtlDosPathSeperatorsString;
    NTSYSAPI UNICODE_STRING RtlAlternateDosPathSeperatorString;
    NTSYSAPI UNICODE_STRING RtlNtPathSeperatorString;

#ifndef PHNT_INLINE_SEPERATOR_STRINGS
#define RtlNtdllName L"ntdll.dll"
#define RtlDosPathSeperatorsString ((UNICODE_STRING)RTL_CONSTANT_STRING(L"\\/"))
#define RtlAlternateDosPathSeperatorString ((UNICODE_STRING)RTL_CONSTANT_STRING(L"/"))
#define RtlNtPathSeperatorString ((UNICODE_STRING)RTL_CONSTANT_STRING(L"\\"))

#define RtlDosDevicesPrefix ((UNICODE_STRING)RTL_CONSTANT_STRING(L"\\??\\"))
#define RtlDosDevicesUncPrefix ((UNICODE_STRING)RTL_CONSTANT_STRING(L"\\??\\UNC\\"))
#define RtlSlashSlashDot ((UNICODE_STRING)RTL_CONSTANT_STRING(L"\\\\.\\"))
#define RtlNullString ((UNICODE_STRING)RTL_CONSTANT_STRING(L""))
#define RtlWin32NtRootSlash ((UNICODE_STRING)RTL_CONSTANT_STRING(L"\\\\?\\"))
#define RtlWin32NtRoot ((UNICODE_STRING)RTL_CONSTANT_STRING(L"\\\\?"))
#define RtlWin32NtUncRoot ((UNICODE_STRING)RTL_CONSTANT_STRING(L"\\\\?\\UNC"))
#define RtlWin32NtUncRootSlash ((UNICODE_STRING)RTL_CONSTANT_STRING(L"\\\\?\\UNC\\"))
#define RtlDefaultExtension ((UNICODE_STRING)RTL_CONSTANT_STRING(L".DLL"))
#endif

    // Path functions

    NTSYSAPI
        RTL_PATH_TYPE
        NTAPI
        RtlDetermineDosPathNameType_U(
            _In_ PCWSTR DosFileName
        );

    NTSYSAPI
        ULONG
        NTAPI
        RtlIsDosDeviceName_U(
            _In_ PCWSTR DosFileName
        );

    NTSYSAPI
        ULONG
        NTAPI
        RtlGetFullPathName_U(
            _In_ PCWSTR FileName,
            _In_ ULONG BufferLength,
            _Out_writes_bytes_(BufferLength) PWSTR Buffer,
            _Out_opt_ PWSTR* FilePart
        );

#if (PHNT_VERSION >= PHNT_WIN7)
    // rev
    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlGetFullPathName_UEx(
            _In_ PCWSTR FileName,
            _In_ ULONG BufferLength,
            _Out_writes_bytes_(BufferLength) PWSTR Buffer,
            _Out_opt_ PWSTR* FilePart,
            _Out_opt_ ULONG* BytesRequired
        );
#endif

#if (PHNT_VERSION >= PHNT_WS03)
    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlGetFullPathName_UstrEx(
            _In_ PUNICODE_STRING FileName,
            _Inout_ PUNICODE_STRING StaticString,
            _Out_opt_ PUNICODE_STRING DynamicString,
            _Out_opt_ PUNICODE_STRING* StringUsed,
            _Out_opt_ SIZE_T* FilePartPrefixCch,
            _Out_opt_ PBOOLEAN NameInvalid,
            _Out_ RTL_PATH_TYPE* InputPathType,
            _Out_opt_ SIZE_T* BytesRequired
        );
#endif

    NTSYSAPI
        ULONG
        NTAPI
        RtlGetCurrentDirectory_U(
            _In_ ULONG BufferLength,
            _Out_writes_bytes_(BufferLength) PWSTR Buffer
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlSetCurrentDirectory_U(
            _In_ PUNICODE_STRING PathName
        );

    NTSYSAPI
        ULONG
        NTAPI
        RtlGetLongestNtPathLength(
            VOID
        );

    // rev
    typedef struct _RTL_BUFFER
    {
        PUCHAR Buffer;
        PUCHAR StaticBuffer;
        SIZE_T Size;
        SIZE_T StaticSize;
    } RTL_BUFFER, * PRTL_BUFFER;

    // rev
    typedef struct _RTL_UNICODE_STRING_BUFFER
    {
        UNICODE_STRING String;
        RTL_BUFFER ByteBuffer;
        UCHAR MinimumStaticBufferForTerminalNul[2];
    } RTL_UNICODE_STRING_BUFFER, * PRTL_UNICODE_STRING_BUFFER;

    // rev
    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlNtPathNameToDosPathName(
            _Reserved_ ULONG Flags,
            _Inout_ PRTL_UNICODE_STRING_BUFFER Path,
            _Out_opt_ PULONG Disposition, // RtlDetermineDosPathNameType_U
            _Out_opt_ PWSTR* FilePart
        );

    NTSYSAPI
        BOOLEAN
        NTAPI
        RtlDosPathNameToNtPathName_U(
            _In_ PCWSTR DosFileName,
            _Out_ PUNICODE_STRING NtFileName,
            _Out_opt_ PWSTR* FilePart,
            _Out_opt_ PRTL_RELATIVE_NAME_U RelativeName
        );

#if (PHNT_VERSION >= PHNT_WS03)
    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlDosPathNameToNtPathName_U_WithStatus(
            _In_ PCWSTR DosFileName,
            _Out_ PUNICODE_STRING NtFileName,
            _Out_opt_ PWSTR* FilePart,
            _Out_opt_ PRTL_RELATIVE_NAME_U RelativeName
        );
#endif

#if (PHNT_VERSION >= PHNT_REDSTONE3)
    // rev
    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlDosLongPathNameToNtPathName_U_WithStatus(
            _In_ PCWSTR DosFileName,
            _Out_ PUNICODE_STRING NtFileName,
            _Out_opt_ PWSTR* FilePart,
            _Out_opt_ PRTL_RELATIVE_NAME_U RelativeName
        );
#endif

#if (PHNT_VERSION >= PHNT_WS03)
    NTSYSAPI
        BOOLEAN
        NTAPI
        RtlDosPathNameToRelativeNtPathName_U(
            _In_ PCWSTR DosFileName,
            _Out_ PUNICODE_STRING NtFileName,
            _Out_opt_ PWSTR* FilePart,
            _Out_opt_ PRTL_RELATIVE_NAME_U RelativeName
        );
#endif

#if (PHNT_VERSION >= PHNT_WS03)
    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlDosPathNameToRelativeNtPathName_U_WithStatus(
            _In_ PCWSTR DosFileName,
            _Out_ PUNICODE_STRING NtFileName,
            _Out_opt_ PWSTR* FilePart,
            _Out_opt_ PRTL_RELATIVE_NAME_U RelativeName
        );
#endif

#if (PHNT_VERSION >= PHNT_REDSTONE3)
    // rev
    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlDosLongPathNameToRelativeNtPathName_U_WithStatus(
            _In_ PCWSTR DosFileName,
            _Out_ PUNICODE_STRING NtFileName,
            _Out_opt_ PWSTR* FilePart,
            _Out_opt_ PRTL_RELATIVE_NAME_U RelativeName
        );
#endif

#if (PHNT_VERSION >= PHNT_WS03)
    NTSYSAPI
        VOID
        NTAPI
        RtlReleaseRelativeName(
            _Inout_ PRTL_RELATIVE_NAME_U RelativeName
        );
#endif

    NTSYSAPI
        ULONG
        NTAPI
        RtlDosSearchPath_U(
            _In_ PCWSTR Path,
            _In_ PCWSTR FileName,
            _In_opt_ PCWSTR Extension,
            _In_ ULONG BufferLength,
            _Out_writes_bytes_(BufferLength) PWSTR Buffer,
            _Out_opt_ PWSTR* FilePart
        );

#define RTL_DOS_SEARCH_PATH_FLAG_APPLY_ISOLATION_REDIRECTION 0x00000001
#define RTL_DOS_SEARCH_PATH_FLAG_DISALLOW_DOT_RELATIVE_PATH_SEARCH 0x00000002
#define RTL_DOS_SEARCH_PATH_FLAG_APPLY_DEFAULT_EXTENSION_WHEN_NOT_RELATIVE_PATH_EVEN_IF_FILE_HAS_EXTENSION 0x00000004

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlDosSearchPath_Ustr(
            _In_ ULONG Flags,
            _In_ PUNICODE_STRING Path,
            _In_ PUNICODE_STRING FileName,
            _In_opt_ PUNICODE_STRING DefaultExtension,
            _Out_opt_ PUNICODE_STRING StaticString,
            _Out_opt_ PUNICODE_STRING DynamicString,
            _Out_opt_ PCUNICODE_STRING* FullFileNameOut,
            _Out_opt_ SIZE_T* FilePartPrefixCch,
            _Out_opt_ SIZE_T* BytesRequired
        );

    NTSYSAPI
        BOOLEAN
        NTAPI
        RtlDoesFileExists_U(
            _In_ PCWSTR FileName
        );

    // ros
    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlDosApplyFileIsolationRedirection_Ustr(
            _In_ ULONG                  Flags,
            _In_ PUNICODE_STRING        OriginalName,
            _In_ PUNICODE_STRING        Extension,
            _In_opt_ PUNICODE_STRING    StaticString,
            _In_opt_ PUNICODE_STRING    DynamicString,
            _In_opt_ PUNICODE_STRING* NewName,
            _In_ PULONG                 NewFlags,
            _In_ PSIZE_T                FileNameSize,
            _In_ PSIZE_T                RequiredLength
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlGetLengthWithoutLastFullDosOrNtPathElement(
            _Reserved_ ULONG Flags,
            _In_ PUNICODE_STRING PathString,
            _Out_ PULONG Length
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlGetLengthWithoutTrailingPathSeperators(
            _Reserved_ ULONG Flags,
            _In_ PUNICODE_STRING PathString,
            _Out_ PULONG Length
        );

    typedef struct _GENERATE_NAME_CONTEXT
    {
        USHORT Checksum;
        BOOLEAN CheckSumInserted;
        UCHAR NameLength;
        WCHAR NameBuffer[8];
        ULONG ExtensionLength;
        WCHAR ExtensionBuffer[4];
        ULONG LastIndexValue;
    } GENERATE_NAME_CONTEXT, * PGENERATE_NAME_CONTEXT;

    // private
    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlGenerate8dot3Name(
            _In_ PUNICODE_STRING Name,
            _In_ BOOLEAN AllowExtendedCharacters,
            _Inout_ PGENERATE_NAME_CONTEXT Context,
            _Inout_ PUNICODE_STRING Name8dot3
        );

#if (PHNT_VERSION >= PHNT_WIN8)

    // private
    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlComputePrivatizedDllName_U(
            _In_ PUNICODE_STRING DllName,
            _Out_ PUNICODE_STRING RealName,
            _Out_ PUNICODE_STRING LocalName
        );

    // rev
    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlGetSearchPath(
            _Out_ PWSTR* SearchPath
        );

    // rev
    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlSetSearchPathMode(
            _In_ ULONG Flags
        );

    // rev
    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlGetExePath(
            _In_ PCWSTR DosPathName,
            _Out_ PWSTR* SearchPath
        );

    // rev
    NTSYSAPI
        VOID
        NTAPI
        RtlReleasePath(
            _In_ PWSTR Path
        );

#endif

#if (PHNT_VERSION >= PHNT_REDSTONE)
    // rev
    NTSYSAPI
        ULONG
        NTAPI
        RtlReplaceSystemDirectoryInPath(
            _Inout_ PUNICODE_STRING Destination,
            _In_ USHORT Machine, // IMAGE_FILE_MACHINE_I386
            _In_ USHORT TargetMachine, // IMAGE_FILE_MACHINE_TARGET_HOST
            _In_ BOOLEAN IncludePathSeperator
        );
#endif

#if (PHNT_VERSION >= PHNT_WIN10_21H2)
    // rev
    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlWow64GetProcessMachines(
            _In_ HANDLE ProcessHandle,
            _Out_ PUSHORT ProcessMachine,
            _Out_ PUSHORT NativeMachine
        );
#endif

#if (PHNT_VERSION >= PHNT_WIN11)
    // rev
#define IMAGE_FILE_NATIVE_MACHINE_I386  0x1
#define IMAGE_FILE_NATIVE_MACHINE_AMD64 0x2
#define IMAGE_FILE_NATIVE_MACHINE_ARMNT 0x4
#define IMAGE_FILE_NATIVE_MACHINE_ARM64 0x8

// rev
    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlGetImageFileMachines(
            _In_ PCWSTR FileName,
            _Out_ PUSHORT FileMachines
        );
#endif

#if (PHNT_VERSION >= PHNT_REDSTONE2)

#ifdef PHNT_INLINE_SYSTEMROOT
    // rev
    FORCEINLINE
        PWSTR
        NTAPI
        RtlGetNtSystemRoot(
            VOID
        )
    {
        if (NtCurrentPeb()->SharedData && NtCurrentPeb()->SharedData->ServiceSessionId) // RtlGetCurrentServiceSessionId
            return NtCurrentPeb()->SharedData->NtSystemRoot;
        else
            return USER_SHARED_DATA->NtSystemRoot;
    }
#else
    // private
    NTSYSAPI
        PWSTR
        NTAPI
        RtlGetNtSystemRoot(
            VOID
        );
#endif

#ifdef PHNT_INLINE_LONGPATH
    // rev
    FORCEINLINE
        BOOLEAN
        NTAPI
        RtlAreLongPathsEnabled(
            VOID
        )
    {
        return NtCurrentPeb()->IsLongPathAwareProcess;
    }
#else
    // rev
    NTSYSAPI
        BOOLEAN
        NTAPI
        RtlAreLongPathsEnabled(
            VOID
        );
#endif

#endif

    NTSYSAPI
        BOOLEAN
        NTAPI
        RtlIsThreadWithinLoaderCallout(
            VOID
        );

    NTSYSAPI
        BOOLEAN
        NTAPI
        RtlDllShutdownInProgress(
            VOID
        );

    // Heaps

    typedef struct _RTL_HEAP_ENTRY
    {
        SIZE_T Size;
        USHORT Flags;
        USHORT AllocatorBackTraceIndex;
        union
        {
            struct
            {
                SIZE_T Settable;
                ULONG Tag;
            } s1;
            struct
            {
                SIZE_T CommittedSize;
                PVOID FirstBlock;
            } s2;
        } u;
    } RTL_HEAP_ENTRY, * PRTL_HEAP_ENTRY;

#define RTL_HEAP_BUSY (USHORT)0x0001
#define RTL_HEAP_SEGMENT (USHORT)0x0002
#define RTL_HEAP_SETTABLE_VALUE (USHORT)0x0010
#define RTL_HEAP_SETTABLE_FLAG1 (USHORT)0x0020
#define RTL_HEAP_SETTABLE_FLAG2 (USHORT)0x0040
#define RTL_HEAP_SETTABLE_FLAG3 (USHORT)0x0080
#define RTL_HEAP_SETTABLE_FLAGS (USHORT)0x00e0
#define RTL_HEAP_UNCOMMITTED_RANGE (USHORT)0x1000
#define RTL_HEAP_PROTECTED_ENTRY (USHORT)0x2000
#define RTL_HEAP_LARGE_ALLOC (USHORT)0x4000
#define RTL_HEAP_LFH_ALLOC (USHORT)0x8000

    typedef struct _RTL_HEAP_TAG
    {
        ULONG NumberOfAllocations;
        ULONG NumberOfFrees;
        SIZE_T BytesAllocated;
        USHORT TagIndex;
        USHORT CreatorBackTraceIndex;
        WCHAR TagName[24];
    } RTL_HEAP_TAG, * PRTL_HEAP_TAG;

    // Windows 7/8/10
    typedef struct _RTL_HEAP_INFORMATION_V1
    {
        PVOID BaseAddress;
        ULONG Flags;
        USHORT EntryOverhead;
        USHORT CreatorBackTraceIndex;
        SIZE_T BytesAllocated;
        SIZE_T BytesCommitted;
        ULONG NumberOfTags;
        ULONG NumberOfEntries;
        ULONG NumberOfPseudoTags;
        ULONG PseudoTagGranularity;
        ULONG Reserved[5];
        PRTL_HEAP_TAG Tags;
        PRTL_HEAP_ENTRY Entries;
    } RTL_HEAP_INFORMATION_V1, * PRTL_HEAP_INFORMATION_V1;

    // Windows 11 > 22000
    typedef struct _RTL_HEAP_INFORMATION_V2
    {
        PVOID BaseAddress;
        ULONG Flags;
        USHORT EntryOverhead;
        USHORT CreatorBackTraceIndex;
        SIZE_T BytesAllocated;
        SIZE_T BytesCommitted;
        ULONG NumberOfTags;
        ULONG NumberOfEntries;
        ULONG NumberOfPseudoTags;
        ULONG PseudoTagGranularity;
        ULONG Reserved[5];
        PRTL_HEAP_TAG Tags;
        PRTL_HEAP_ENTRY Entries;
        ULONG64 HeapTag;
    } RTL_HEAP_INFORMATION_V2, * PRTL_HEAP_INFORMATION_V2;

#define RTL_HEAP_SIGNATURE 0xFFEEFFEEUL
#define RTL_HEAP_SEGMENT_SIGNATURE 0xDDEEDDEEUL

    typedef struct _RTL_PROCESS_HEAPS_V1
    {
        ULONG NumberOfHeaps;
        _Field_size_(NumberOfHeaps) RTL_HEAP_INFORMATION_V1 Heaps[1];
    } RTL_PROCESS_HEAPS_V1, * PRTL_PROCESS_HEAPS_V1;

    typedef struct _RTL_PROCESS_HEAPS_V2
    {
        ULONG NumberOfHeaps;
        _Field_size_(NumberOfHeaps) RTL_HEAP_INFORMATION_V2 Heaps[1];
    } RTL_PROCESS_HEAPS_V2, * PRTL_PROCESS_HEAPS_V2;

    // Segment heap parameters.

    typedef enum _RTL_MEMORY_TYPE
    {
        MemoryTypePaged,
        MemoryTypeNonPaged,
        MemoryType64KPage,
        MemoryTypeLargePage,
        MemoryTypeHugePage,
        MemoryTypeCustom,
        MemoryTypeMax
    } RTL_MEMORY_TYPE, * PRTL_MEMORY_TYPE;

    typedef enum _HEAP_MEMORY_INFO_CLASS
    {
        HeapMemoryBasicInformation
    } HEAP_MEMORY_INFO_CLASS;

    typedef NTSTATUS ALLOCATE_VIRTUAL_MEMORY_EX_CALLBACK(
        _Inout_ HANDLE CallbackContext,
        _In_ HANDLE ProcessHandle,
        _Inout_ _At_(*BaseAddress, _Readable_bytes_(*RegionSize) _Writable_bytes_(*RegionSize) _Post_readable_byte_size_(*RegionSize)) PVOID* BaseAddress,
        _Inout_ PSIZE_T RegionSize,
        _In_ ULONG AllocationType,
        _In_ ULONG PageProtection,
        _Inout_updates_opt_(ExtendedParameterCount) PMEM_EXTENDED_PARAMETER ExtendedParameters,
        _In_ ULONG ExtendedParameterCount
    );

    typedef ALLOCATE_VIRTUAL_MEMORY_EX_CALLBACK* PALLOCATE_VIRTUAL_MEMORY_EX_CALLBACK;

    typedef NTSTATUS FREE_VIRTUAL_MEMORY_EX_CALLBACK(
        _Inout_ HANDLE CallbackContext,
        _In_ HANDLE ProcessHandle,
        _Inout_ __drv_freesMem(Mem) PVOID* BaseAddress,
        _Inout_ PSIZE_T RegionSize,
        _In_ ULONG FreeType
    );

    typedef FREE_VIRTUAL_MEMORY_EX_CALLBACK* PFREE_VIRTUAL_MEMORY_EX_CALLBACK;

    typedef NTSTATUS QUERY_VIRTUAL_MEMORY_CALLBACK(
        _Inout_ HANDLE CallbackContext,
        _In_ HANDLE ProcessHandle,
        _In_opt_ PVOID BaseAddress,
        _In_ HEAP_MEMORY_INFO_CLASS MemoryInformationClass,
        _Out_writes_bytes_(MemoryInformationLength) PVOID MemoryInformation,
        _In_ SIZE_T MemoryInformationLength,
        _Out_opt_ PSIZE_T ReturnLength
    );

    typedef QUERY_VIRTUAL_MEMORY_CALLBACK* PQUERY_VIRTUAL_MEMORY_CALLBACK;

    typedef struct _RTL_SEGMENT_HEAP_VA_CALLBACKS
    {
        HANDLE CallbackContext;
        PALLOCATE_VIRTUAL_MEMORY_EX_CALLBACK AllocateVirtualMemory;
        PFREE_VIRTUAL_MEMORY_EX_CALLBACK FreeVirtualMemory;
        PQUERY_VIRTUAL_MEMORY_CALLBACK QueryVirtualMemory;
    } RTL_SEGMENT_HEAP_VA_CALLBACKS, * PRTL_SEGMENT_HEAP_VA_CALLBACKS;

#define RTL_SEGHEAP_MEM_SOURCE_ANY_NODE ((ULONG)-1)

    typedef struct _RTL_SEGMENT_HEAP_MEMORY_SOURCE
    {
        ULONG Flags;
        ULONG MemoryTypeMask; // Mask of RTL_MEMORY_TYPE members.
        ULONG NumaNode;
        union
        {
            HANDLE PartitionHandle;
            RTL_SEGMENT_HEAP_VA_CALLBACKS* Callbacks;
        };
        SIZE_T Reserved[2];
    } RTL_SEGMENT_HEAP_MEMORY_SOURCE, * PRTL_SEGMENT_HEAP_MEMORY_SOURCE;

#define SEGMENT_HEAP_PARAMETERS_VERSION         3
#define SEGMENT_HEAP_FLG_USE_PAGE_HEAP          0x1
#define SEGMENT_HEAP_PARAMS_VALID_FLAGS         SEGMENT_HEAP_FLG_USE_PAGE_HEAP

    typedef struct _RTL_SEGMENT_HEAP_PARAMETERS
    {
        USHORT Version;
        USHORT Size;
        ULONG Flags;
        RTL_SEGMENT_HEAP_MEMORY_SOURCE MemorySource;
        SIZE_T Reserved[4];
    } RTL_SEGMENT_HEAP_PARAMETERS, * PRTL_SEGMENT_HEAP_PARAMETERS;

    // Heap parameters.

    typedef
        _Function_class_(RTL_HEAP_COMMIT_ROUTINE)
        NTSTATUS
        NTAPI
        RTL_HEAP_COMMIT_ROUTINE(
            _In_ PVOID Base,
            _Inout_ PVOID* CommitAddress,
            _Inout_ PSIZE_T CommitSize
        );

    typedef RTL_HEAP_COMMIT_ROUTINE* PRTL_HEAP_COMMIT_ROUTINE;

    typedef struct _RTL_HEAP_PARAMETERS
    {
        ULONG Length;
        SIZE_T SegmentReserve;
        SIZE_T SegmentCommit;
        SIZE_T DeCommitFreeBlockThreshold;
        SIZE_T DeCommitTotalFreeThreshold;
        SIZE_T MaximumAllocationSize;
        SIZE_T VirtualMemoryThreshold;
        SIZE_T InitialCommit;
        SIZE_T InitialReserve;
        PRTL_HEAP_COMMIT_ROUTINE CommitRoutine;
        SIZE_T Reserved[2];
    } RTL_HEAP_PARAMETERS, * PRTL_HEAP_PARAMETERS;

#define HEAP_SETTABLE_USER_VALUE 0x00000100
#define HEAP_SETTABLE_USER_FLAG1 0x00000200
#define HEAP_SETTABLE_USER_FLAG2 0x00000400
#define HEAP_SETTABLE_USER_FLAG3 0x00000800
#define HEAP_SETTABLE_USER_FLAGS 0x00000e00

#define HEAP_CLASS_0 0x00000000 // Process heap
#define HEAP_CLASS_1 0x00001000 // Private heap
#define HEAP_CLASS_2 0x00002000 // Kernel heap
#define HEAP_CLASS_3 0x00003000 // GDI heap
#define HEAP_CLASS_4 0x00004000 // User heap
#define HEAP_CLASS_5 0x00005000 // Console heap
#define HEAP_CLASS_6 0x00006000 // User desktop heap
#define HEAP_CLASS_7 0x00007000 // CSR shared heap
#define HEAP_CLASS_8 0x00008000 // CSR port heap
#define HEAP_CLASS_MASK 0x0000f000

    _Must_inspect_result_
        NTSYSAPI
        PVOID
        NTAPI
        RtlCreateHeap(
            _In_ ULONG Flags,
            _In_opt_ PVOID HeapBase,
            _In_opt_ SIZE_T ReserveSize,
            _In_opt_ SIZE_T CommitSize,
            _In_opt_ PVOID Lock,
            _When_((Flags& HEAP_CREATE_SEGMENT_HEAP) != 0, _In_reads_bytes_opt_(sizeof(RTL_SEGMENT_HEAP_PARAMETERS)))
            _When_((Flags& HEAP_CREATE_SEGMENT_HEAP) == 0, _In_reads_bytes_opt_(sizeof(RTL_HEAP_PARAMETERS)))
            _In_opt_ PVOID Parameters
        );

    NTSYSAPI
        PVOID
        NTAPI
        RtlDestroyHeap(
            _In_ _Post_invalid_ PVOID HeapHandle
        );

    NTSYSAPI
        _Success_(return != 0)
        _Must_inspect_result_
        _Ret_maybenull_
        _Post_writable_byte_size_(Size)
        __drv_allocatesMem(Mem)
        DECLSPEC_ALLOCATOR
        PVOID
        NTAPI
        RtlAllocateHeap(
            _In_ PVOID HeapHandle,
            _In_opt_ ULONG Flags,
            _In_ SIZE_T Size
        );

#if (PHNT_VERSION >= PHNT_WIN8)
    _Success_(return != 0)
        NTSYSAPI
        LOGICAL
        NTAPI
        RtlFreeHeap(
            _In_ PVOID HeapHandle,
            _In_opt_ ULONG Flags,
            _Frees_ptr_opt_ PVOID BaseAddress
        );
#else
    _Success_(return)
        NTSYSAPI
        BOOLEAN
        NTAPI
        RtlFreeHeap(
            _In_ PVOID HeapHandle,
            _In_opt_ ULONG Flags,
            _Frees_ptr_opt_ PVOID BaseAddress
        );
#endif

    NTSYSAPI
        SIZE_T
        NTAPI
        RtlSizeHeap(
            _In_ PVOID HeapHandle,
            _In_ ULONG Flags,
            _In_ PVOID BaseAddress
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlZeroHeap(
            _In_ PVOID HeapHandle,
            _In_ ULONG Flags
        );

    NTSYSAPI
        VOID
        NTAPI
        RtlProtectHeap(
            _In_ PVOID HeapHandle,
            _In_ BOOLEAN MakeReadOnly
        );

#define RtlProcessHeap() (NtCurrentPeb()->ProcessHeap)

    NTSYSAPI
        BOOLEAN
        NTAPI
        RtlLockHeap(
            _In_ PVOID HeapHandle
        );

    NTSYSAPI
        BOOLEAN
        NTAPI
        RtlUnlockHeap(
            _In_ PVOID HeapHandle
        );

    NTSYSAPI
        _Success_(return != 0)
        _Must_inspect_result_
        _Ret_maybenull_
        _Post_writable_byte_size_(Size)
        _When_(Size > 0, __drv_allocatesMem(Mem))
        DECLSPEC_ALLOCATOR
        PVOID
        NTAPI
        RtlReAllocateHeap(
            _In_ PVOID HeapHandle,
            _In_ ULONG Flags,
            _Frees_ptr_opt_ PVOID BaseAddress,
            _In_ SIZE_T Size
        );

    NTSYSAPI
        BOOLEAN
        NTAPI
        RtlGetUserInfoHeap(
            _In_ PVOID HeapHandle,
            _In_ ULONG Flags,
            _In_ PVOID BaseAddress,
            _Out_opt_ PVOID* UserValue,
            _Out_opt_ PULONG UserFlags
        );

    NTSYSAPI
        BOOLEAN
        NTAPI
        RtlSetUserValueHeap(
            _In_ PVOID HeapHandle,
            _In_ ULONG Flags,
            _In_ PVOID BaseAddress,
            _In_ PVOID UserValue
        );

    NTSYSAPI
        BOOLEAN
        NTAPI
        RtlSetUserFlagsHeap(
            _In_ PVOID HeapHandle,
            _In_ ULONG Flags,
            _In_ PVOID BaseAddress,
            _In_ ULONG UserFlagsReset,
            _In_ ULONG UserFlagsSet
        );

    typedef struct _RTL_HEAP_TAG_INFO
    {
        ULONG NumberOfAllocations;
        ULONG NumberOfFrees;
        SIZE_T BytesAllocated;
    } RTL_HEAP_TAG_INFO, * PRTL_HEAP_TAG_INFO;

#define RTL_HEAP_MAKE_TAG HEAP_MAKE_TAG_FLAGS

    NTSYSAPI
        ULONG
        NTAPI
        RtlCreateTagHeap(
            _In_ PVOID HeapHandle,
            _In_ ULONG Flags,
            _In_opt_ PWSTR TagPrefix,
            _In_ PWSTR TagNames
        );

    NTSYSAPI
        PWSTR
        NTAPI
        RtlQueryTagHeap(
            _In_ PVOID HeapHandle,
            _In_ ULONG Flags,
            _In_ USHORT TagIndex,
            _In_ BOOLEAN ResetCounters,
            _Out_opt_ PRTL_HEAP_TAG_INFO TagInfo
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlExtendHeap(
            _In_ PVOID HeapHandle,
            _In_ ULONG Flags,
            _In_ PVOID Base,
            _In_ SIZE_T Size
        );

    NTSYSAPI
        SIZE_T
        NTAPI
        RtlCompactHeap(
            _In_ PVOID HeapHandle,
            _In_ ULONG Flags
        );

    NTSYSAPI
        BOOLEAN
        NTAPI
        RtlValidateHeap(
            _In_opt_ PVOID HeapHandle,
            _In_ ULONG Flags,
            _In_opt_ PVOID BaseAddress
        );

    NTSYSAPI
        BOOLEAN
        NTAPI
        RtlValidateProcessHeaps(
            VOID
        );

    NTSYSAPI
        ULONG
        NTAPI
        RtlGetProcessHeaps(
            _In_ ULONG NumberOfHeaps,
            _Out_ PVOID* ProcessHeaps
        );

    _Function_class_(RTL_ENUM_HEAPS_ROUTINE)
        typedef NTSTATUS(NTAPI RTL_ENUM_HEAPS_ROUTINE)(
            _In_ PVOID HeapHandle,
            _In_ PVOID Parameter
            );
    typedef RTL_ENUM_HEAPS_ROUTINE* PRTL_ENUM_HEAPS_ROUTINE;

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlEnumProcessHeaps(
            _In_ PRTL_ENUM_HEAPS_ROUTINE EnumRoutine,
            _In_ PVOID Parameter
        );

    typedef struct _RTL_HEAP_USAGE_ENTRY
    {
        struct _RTL_HEAP_USAGE_ENTRY* Next;
        PVOID Address;
        SIZE_T Size;
        USHORT AllocatorBackTraceIndex;
        USHORT TagIndex;
    } RTL_HEAP_USAGE_ENTRY, * PRTL_HEAP_USAGE_ENTRY;

    typedef struct _RTL_HEAP_USAGE
    {
        ULONG Length;
        SIZE_T BytesAllocated;
        SIZE_T BytesCommitted;
        SIZE_T BytesReserved;
        SIZE_T BytesReservedMaximum;
        PRTL_HEAP_USAGE_ENTRY Entries;
        PRTL_HEAP_USAGE_ENTRY AddedEntries;
        PRTL_HEAP_USAGE_ENTRY RemovedEntries;
        ULONG_PTR Reserved[8];
    } RTL_HEAP_USAGE, * PRTL_HEAP_USAGE;

#define HEAP_USAGE_ALLOCATED_BLOCKS HEAP_REALLOC_IN_PLACE_ONLY
#define HEAP_USAGE_FREE_BUFFER HEAP_ZERO_MEMORY

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlUsageHeap(
            _In_ PVOID HeapHandle,
            _In_ ULONG Flags,
            _Inout_ PRTL_HEAP_USAGE Usage
        );

    typedef struct _RTL_HEAP_WALK_ENTRY
    {
        PVOID DataAddress;
        SIZE_T DataSize;
        UCHAR OverheadBytes;
        UCHAR SegmentIndex;
        USHORT Flags;
        union
        {
            struct
            {
                SIZE_T Settable;
                USHORT TagIndex;
                USHORT AllocatorBackTraceIndex;
                ULONG Reserved[2];
            } Block;
            struct
            {
                ULONG CommittedSize;
                ULONG UnCommittedSize;
                PVOID FirstEntry;
                PVOID LastEntry;
            } Segment;
        };
    } RTL_HEAP_WALK_ENTRY, * PRTL_HEAP_WALK_ENTRY;

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlWalkHeap(
            _In_ PVOID HeapHandle,
            _Inout_ PRTL_HEAP_WALK_ENTRY Entry
        );

    // HEAP_INFORMATION_CLASS
#define HeapCompatibilityInformation 0x0 // q; s: ULONG
#define HeapEnableTerminationOnCorruption 0x1 // q; s: NULL
#define HeapExtendedInformation 0x2 // q; s: HEAP_EXTENDED_INFORMATION
#define HeapOptimizeResources 0x3 // q; s: HEAP_OPTIMIZE_RESOURCES_INFORMATION
#define HeapTaggingInformation 0x4
#define HeapStackDatabase 0x5 // q: RTL_HEAP_STACK_QUERY; s: RTL_HEAP_STACK_CONTROL
#define HeapMemoryLimit 0x6 // since 19H2
#define HeapTag 0x7 // since 20H1
#define HeapDetailedFailureInformation 0x80000001
#define HeapSetDebuggingInformation 0x80000002 // q; s: HEAP_DEBUGGING_INFORMATION

    typedef enum _HEAP_COMPATIBILITY_MODE
    {
        HEAP_COMPATIBILITY_STANDARD = 0UL,
        HEAP_COMPATIBILITY_LAL = 1UL,
        HEAP_COMPATIBILITY_LFH = 2UL,
    } HEAP_COMPATIBILITY_MODE;

    typedef struct _RTLP_TAG_INFO
    {
        GUID Id;
        ULONG_PTR CurrentAllocatedBytes;
    } RTLP_TAG_INFO, * PRTLP_TAG_INFO;

    typedef struct _RTLP_HEAP_TAGGING_INFO
    {
        USHORT Version;
        USHORT Flags;
        PVOID ProcessHandle;
        ULONG_PTR EntriesCount;
        RTLP_TAG_INFO Entries[1];
    } RTLP_HEAP_TAGGING_INFO, * PRTLP_HEAP_TAGGING_INFO;

    typedef struct _PROCESS_HEAP_INFORMATION
    {
        SIZE_T ReserveSize;
        SIZE_T CommitSize;
        ULONG NumberOfHeaps;
        ULONG_PTR FirstHeapInformationOffset;
    } PROCESS_HEAP_INFORMATION, * PPROCESS_HEAP_INFORMATION;

    typedef struct _HEAP_REGION_INFORMATION
    {
        PVOID Address;
        SIZE_T ReserveSize;
        SIZE_T CommitSize;
        ULONG_PTR FirstRangeInformationOffset;
        ULONG_PTR NextRegionInformationOffset;
    } HEAP_REGION_INFORMATION, * PHEAP_REGION_INFORMATION;

    typedef struct _HEAP_RANGE_INFORMATION
    {
        PVOID Address;
        SIZE_T Size;
        ULONG Type;
        ULONG Protection;
        ULONG_PTR FirstBlockInformationOffset;
        ULONG_PTR NextRangeInformationOffset;
    } HEAP_RANGE_INFORMATION, * PHEAP_RANGE_INFORMATION;

    typedef struct _HEAP_BLOCK_INFORMATION
    {
        PVOID Address;
        ULONG Flags;
        SIZE_T DataSize;
        ULONG_PTR OverheadSize;
        ULONG_PTR NextBlockInformationOffset;
    } HEAP_BLOCK_INFORMATION, * PHEAP_BLOCK_INFORMATION;

    typedef struct _HEAP_INFORMATION
    {
        PVOID Address;
        ULONG Mode;
        SIZE_T ReserveSize;
        SIZE_T CommitSize;
        ULONG_PTR FirstRegionInformationOffset;
        ULONG_PTR NextHeapInformationOffset;
    } HEAP_INFORMATION, * PHEAP_INFORMATION;

    typedef struct _SEGMENT_HEAP_PERFORMANCE_COUNTER_INFORMATION
    {
        SIZE_T SegmentReserveSize;
        SIZE_T SegmentCommitSize;
        ULONG_PTR SegmentCount;
        SIZE_T AllocatedSize;
        SIZE_T LargeAllocReserveSize;
        SIZE_T LargeAllocCommitSize;
    } SEGMENT_HEAP_PERFORMANCE_COUNTER_INFORMATION, * PSEGMENT_HEAP_PERFORMANCE_COUNTER_INFORMATION;

#define HeapPerformanceCountersInformationStandardHeapVersion 0x1
#define HeapPerformanceCountersInformationSegmentHeapVersion 0x2

    typedef struct _HEAP_PERFORMANCE_COUNTERS_INFORMATION
    {
        ULONG Size;
        ULONG Version;
        ULONG HeapIndex;
        ULONG LastHeapIndex;
        PVOID BaseAddress;
        SIZE_T ReserveSize;
        SIZE_T CommitSize;
        ULONG SegmentCount;
        SIZE_T LargeUCRMemory;
        ULONG UCRLength;
        SIZE_T AllocatedSpace;
        SIZE_T FreeSpace;
        ULONG FreeListLength;
        ULONG Contention;
        ULONG VirtualBlocks;
        ULONG CommitRate;
        ULONG DecommitRate;
        SEGMENT_HEAP_PERFORMANCE_COUNTER_INFORMATION SegmentHeapPerfInformation; // since WIN8
    } HEAP_PERFORMANCE_COUNTERS_INFORMATION, * PHEAP_PERFORMANCE_COUNTERS_INFORMATION;

    typedef struct _HEAP_INFORMATION_ITEM
    {
        ULONG Level;
        SIZE_T Size;
        union
        {
            PROCESS_HEAP_INFORMATION ProcessHeapInformation;
            HEAP_INFORMATION HeapInformation;
            HEAP_REGION_INFORMATION HeapRegionInformation;
            HEAP_RANGE_INFORMATION HeapRangeInformation;
            HEAP_BLOCK_INFORMATION HeapBlockInformation;
            HEAP_PERFORMANCE_COUNTERS_INFORMATION HeapPerfInformation;
            ULONG_PTR DynamicStart;
        };
    } HEAP_INFORMATION_ITEM, * PHEAP_INFORMATION_ITEM;

    _Function_class_(RTL_HEAP_EXTENDED_ENUMERATION_ROUTINE)
        typedef NTSTATUS(NTAPI RTL_HEAP_EXTENDED_ENUMERATION_ROUTINE)(
            _In_ PHEAP_INFORMATION_ITEM Information,
            _In_opt_ PVOID Context
            );
    typedef RTL_HEAP_EXTENDED_ENUMERATION_ROUTINE* PRTL_HEAP_EXTENDED_ENUMERATION_ROUTINE;

    // HEAP_EXTENDED_INFORMATION Level
#define HeapExtendedProcessHeapInformationLevel 0x1
#define HeapExtendedHeapInformationLevel 0x2
#define HeapExtendedHeapRegionInformationLevel 0x3
#define HeapExtendedHeapRangeInformationLevel 0x4
#define HeapExtendedHeapBlockInformationLevel 0x5
#define HeapExtendedHeapHeapPerfInformationLevel 0x80000000

    typedef struct _HEAP_EXTENDED_INFORMATION
    {
        HANDLE ProcessHandle;
        PVOID HeapHandle;
        ULONG Level;
        PRTL_HEAP_EXTENDED_ENUMERATION_ROUTINE CallbackRoutine;
        PVOID CallbackContext;
        union
        {
            PROCESS_HEAP_INFORMATION ProcessHeapInformation;
            HEAP_INFORMATION HeapInformation;
        };
    } HEAP_EXTENDED_INFORMATION, * PHEAP_EXTENDED_INFORMATION;

    // rev
    typedef NTSTATUS(NTAPI* RTL_HEAP_STACK_WRITE_ROUTINE)(
        _In_ PVOID Information, // TODO: 3 missing structures (dmex)
        _In_ ULONG Size,
        _In_opt_ PVOID Context
        );

    // rev
    typedef struct _RTLP_HEAP_STACK_TRACE_SERIALIZATION_INIT
    {
        ULONG Count;
        ULONG Total;
        ULONG Flags;
    } RTLP_HEAP_STACK_TRACE_SERIALIZATION_INIT, * PRTLP_HEAP_STACK_TRACE_SERIALIZATION_INIT;

    // rev
    typedef struct _RTLP_HEAP_STACK_TRACE_SERIALIZATION_HEADER
    {
        USHORT Version;
        USHORT PointerSize;
        PVOID Heap;
        SIZE_T TotalCommit;
        SIZE_T TotalReserve;
    } RTLP_HEAP_STACK_TRACE_SERIALIZATION_HEADER, * PRTLP_HEAP_STACK_TRACE_SERIALIZATION_HEADER;

    // rev
    typedef struct _RTLP_HEAP_STACK_TRACE_SERIALIZATION_ALLOCATION
    {
        PVOID Address;
        ULONG Flags;
        SIZE_T DataSize;
    } RTLP_HEAP_STACK_TRACE_SERIALIZATION_ALLOCATION, * PRTLP_HEAP_STACK_TRACE_SERIALIZATION_ALLOCATION;

    // rev
    typedef struct _RTLP_HEAP_STACK_TRACE_SERIALIZATION_STACKFRAME
    {
        PVOID StackFrame[8];
    } RTLP_HEAP_STACK_TRACE_SERIALIZATION_STACKFRAME, * PRTLP_HEAP_STACK_TRACE_SERIALIZATION_STACKFRAME;

#define HEAP_STACK_QUERY_VERSION 0x2

    typedef struct _RTL_HEAP_STACK_QUERY
    {
        ULONG Version;
        HANDLE ProcessHandle;
        RTL_HEAP_STACK_WRITE_ROUTINE WriteRoutine;
        PVOID SerializationContext;
        UCHAR QueryLevel;
        UCHAR Flags;
    } RTL_HEAP_STACK_QUERY, * PRTL_HEAP_STACK_QUERY;

#define HEAP_STACK_CONTROL_VERSION 0x1
#define HEAP_STACK_CONTROL_FLAGS_STACKTRACE_ENABLE 0x1
#define HEAP_STACK_CONTROL_FLAGS_STACKTRACE_DISABLE 0x2

    typedef struct _RTL_HEAP_STACK_CONTROL
    {
        USHORT Version;
        USHORT Flags;
        HANDLE ProcessHandle;
    } RTL_HEAP_STACK_CONTROL, * PRTL_HEAP_STACK_CONTROL;

    // rev
    typedef NTSTATUS(NTAPI* PRTL_HEAP_DEBUGGING_INTERCEPTOR_ROUTINE)(
        _In_ PVOID HeapHandle,
        _In_ ULONG Action,
        _In_ ULONG StackFramesToCapture,
        _In_ PVOID* StackTrace
        );

    // rev
    typedef NTSTATUS(NTAPI* PRTL_HEAP_LEAK_ENUMERATION_ROUTINE)(
        _In_ LONG Reserved,
        _In_ PVOID HeapHandle,
        _In_ PVOID BaseAddress,
        _In_ SIZE_T BlockSize,
        _In_ ULONG StackTraceDepth,
        _In_ PVOID* StackTrace
        );

    // symbols
    typedef struct _HEAP_DEBUGGING_INFORMATION
    {
        PRTL_HEAP_DEBUGGING_INTERCEPTOR_ROUTINE InterceptorFunction;
        USHORT InterceptorValue;
        ULONG ExtendedOptions;
        ULONG StackTraceDepth;
        SIZE_T MinTotalBlockSize;
        SIZE_T MaxTotalBlockSize;
        PRTL_HEAP_LEAK_ENUMERATION_ROUTINE HeapLeakEnumerationRoutine;
    } HEAP_DEBUGGING_INFORMATION, * PHEAP_DEBUGGING_INFORMATION;

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlQueryHeapInformation(
            _In_opt_ PVOID HeapHandle,
            _In_ HEAP_INFORMATION_CLASS HeapInformationClass,
            _Out_opt_ PVOID HeapInformation,
            _In_opt_ SIZE_T HeapInformationLength,
            _Out_opt_ PSIZE_T ReturnLength
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlSetHeapInformation(
            _In_opt_ PVOID HeapHandle,
            _In_ HEAP_INFORMATION_CLASS HeapInformationClass,
            _In_opt_ PVOID HeapInformation,
            _In_opt_ SIZE_T HeapInformationLength
        );

    NTSYSAPI
        ULONG
        NTAPI
        RtlMultipleAllocateHeap(
            _In_ PVOID HeapHandle,
            _In_ ULONG Flags,
            _In_ SIZE_T Size,
            _In_ ULONG Count,
            _Out_ PVOID* Array
        );

    NTSYSAPI
        ULONG
        NTAPI
        RtlMultipleFreeHeap(
            _In_ PVOID HeapHandle,
            _In_ ULONG Flags,
            _In_ ULONG Count,
            _In_ PVOID* Array
        );

#if (PHNT_VERSION >= PHNT_WIN7)
    NTSYSAPI
        VOID
        NTAPI
        RtlDetectHeapLeaks(
            VOID
        );
#endif

    NTSYSAPI
        VOID
        NTAPI
        RtlFlushHeaps(
            VOID
        );

    // Memory zones

    // begin_private

    typedef struct _RTL_MEMORY_ZONE_SEGMENT
    {
        struct _RTL_MEMORY_ZONE_SEGMENT* NextSegment;
        SIZE_T Size;
        PVOID Next;
        PVOID Limit;
    } RTL_MEMORY_ZONE_SEGMENT, * PRTL_MEMORY_ZONE_SEGMENT;

    typedef struct _RTL_MEMORY_ZONE
    {
        RTL_MEMORY_ZONE_SEGMENT Segment;
        RTL_SRWLOCK Lock;
        ULONG LockCount;
        PRTL_MEMORY_ZONE_SEGMENT FirstSegment;
    } RTL_MEMORY_ZONE, * PRTL_MEMORY_ZONE;

#if (PHNT_VERSION >= PHNT_VISTA)

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlCreateMemoryZone(
            _Out_ PVOID* MemoryZone,
            _In_ SIZE_T InitialSize,
            _Reserved_ ULONG Flags
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlDestroyMemoryZone(
            _In_ _Post_invalid_ PVOID MemoryZone
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlAllocateMemoryZone(
            _In_ PVOID MemoryZone,
            _In_ SIZE_T BlockSize,
            _Out_ PVOID* Block
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlResetMemoryZone(
            _In_ PVOID MemoryZone
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlLockMemoryZone(
            _In_ PVOID MemoryZone
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlUnlockMemoryZone(
            _In_ PVOID MemoryZone
        );

#endif

    // Memory block lookaside lists

#if (PHNT_VERSION >= PHNT_VISTA)

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlCreateMemoryBlockLookaside(
            _Out_ PVOID* MemoryBlockLookaside,
            _Reserved_ ULONG Flags,
            _In_ ULONG InitialSize,
            _In_ ULONG MinimumBlockSize,
            _In_ ULONG MaximumBlockSize
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlDestroyMemoryBlockLookaside(
            _In_ PVOID MemoryBlockLookaside
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlAllocateMemoryBlockLookaside(
            _In_ PVOID MemoryBlockLookaside,
            _In_ ULONG BlockSize,
            _Out_ PVOID* Block
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlFreeMemoryBlockLookaside(
            _In_ PVOID MemoryBlockLookaside,
            _In_ PVOID Block
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlExtendMemoryBlockLookaside(
            _In_ PVOID MemoryBlockLookaside,
            _In_ ULONG Increment
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlResetMemoryBlockLookaside(
            _In_ PVOID MemoryBlockLookaside
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlLockMemoryBlockLookaside(
            _In_ PVOID MemoryBlockLookaside
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlUnlockMemoryBlockLookaside(
            _In_ PVOID MemoryBlockLookaside
        );

#endif

    // end_private

    // Transactions

#if (PHNT_VERSION >= PHNT_VISTA)
// private
    NTSYSAPI
        HANDLE
        NTAPI
        RtlGetCurrentTransaction(
            VOID
        );
#endif

#if (PHNT_VERSION >= PHNT_VISTA)
    // private
    NTSYSAPI
        LOGICAL
        NTAPI
        RtlSetCurrentTransaction(
            _In_opt_ HANDLE TransactionHandle
        );
#endif

    // LUIDs

    FORCEINLINE BOOLEAN RtlIsEqualLuid( // RtlEqualLuid
        _In_ PLUID L1,
        _In_ PLUID L2
    )
    {
        return L1->LowPart == L2->LowPart &&
            L1->HighPart == L2->HighPart;
    }

    FORCEINLINE BOOLEAN RtlIsZeroLuid(
        _In_ PLUID L1
    )
    {
        return (L1->LowPart | L1->HighPart) == 0;
    }

    FORCEINLINE
        LUID
        NTAPI_INLINE
        RtlConvertLongToLuid(
            _In_ LONG Long
        )
    {
        LUID tempLuid;
        LARGE_INTEGER tempLi;

        tempLi.QuadPart = Long;
        tempLuid.LowPart = tempLi.LowPart;
        tempLuid.HighPart = tempLi.HighPart;

        return tempLuid;
    }

    FORCEINLINE
        LUID
        NTAPI_INLINE
        RtlConvertUlongToLuid(
            _In_ ULONG Ulong
        )
    {
        LUID tempLuid;

        tempLuid.LowPart = Ulong;
        tempLuid.HighPart = 0;

        return tempLuid;
    }

    NTSYSAPI
        VOID
        NTAPI
        RtlCopyLuid(
            _Out_ PLUID DestinationLuid,
            _In_ PLUID SourceLuid
        );

    // ros
    NTSYSAPI
        VOID
        NTAPI
        RtlCopyLuidAndAttributesArray(
            _In_ ULONG Count,
            _In_ PLUID_AND_ATTRIBUTES Src,
            _In_ PLUID_AND_ATTRIBUTES Dest
        );

    // Byte swap routines.

#ifndef PHNT_RTL_BYTESWAP
#define RtlUshortByteSwap(_x) _byteswap_ushort((USHORT)(_x))
#define RtlUlongByteSwap(_x) _byteswap_ulong((_x))
#define RtlUlonglongByteSwap(_x) _byteswap_uint64((_x))
#else
    NTSYSAPI
        USHORT
        FASTCALL
        RtlUshortByteSwap(
            _In_ USHORT Source
        );

    NTSYSAPI
        ULONG
        FASTCALL
        RtlUlongByteSwap(
            _In_ ULONG Source
        );

    NTSYSAPI
        ULONGLONG
        FASTCALL
        RtlUlonglongByteSwap(
            _In_ ULONGLONG Source
        );
#endif

    // Debugging

    // private
    typedef struct _RTL_PROCESS_MODULES* PRTL_PROCESS_MODULES;
    typedef struct _RTL_PROCESS_MODULE_INFORMATION_EX* PRTL_PROCESS_MODULE_INFORMATION_EX;
    typedef struct _RTL_PROCESS_BACKTRACES* PRTL_PROCESS_BACKTRACES;
    typedef struct _RTL_PROCESS_LOCKS* PRTL_PROCESS_LOCKS;

    typedef struct _RTL_PROCESS_VERIFIER_OPTIONS
    {
        ULONG SizeStruct;
        ULONG Option;
        UCHAR OptionData[1];
    } RTL_PROCESS_VERIFIER_OPTIONS, * PRTL_PROCESS_VERIFIER_OPTIONS;

    // private
    typedef struct _RTL_DEBUG_INFORMATION
    {
        HANDLE SectionHandleClient;
        PVOID ViewBaseClient;
        PVOID ViewBaseTarget;
        ULONG_PTR ViewBaseDelta;
        HANDLE EventPairClient;
        HANDLE EventPairTarget;
        HANDLE TargetProcessId;
        HANDLE TargetThreadHandle;
        ULONG Flags;
        SIZE_T OffsetFree;
        SIZE_T CommitSize;
        SIZE_T ViewSize;
        union
        {
            PRTL_PROCESS_MODULES Modules;
            PRTL_PROCESS_MODULE_INFORMATION_EX ModulesEx;
        };
        PRTL_PROCESS_BACKTRACES BackTraces;
        PVOID Heaps;
        PRTL_PROCESS_LOCKS Locks;
        PVOID SpecificHeap;
        HANDLE TargetProcessHandle;
        PRTL_PROCESS_VERIFIER_OPTIONS VerifierOptions;
        PVOID ProcessHeap;
        HANDLE CriticalSectionHandle;
        HANDLE CriticalSectionOwnerThread;
        PVOID Reserved[4];
    } RTL_DEBUG_INFORMATION, * PRTL_DEBUG_INFORMATION;

    NTSYSAPI
        PRTL_DEBUG_INFORMATION
        NTAPI
        RtlCreateQueryDebugBuffer(
            _In_opt_ ULONG MaximumCommit,
            _In_ BOOLEAN UseEventPair
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlDestroyQueryDebugBuffer(
            _In_ PRTL_DEBUG_INFORMATION Buffer
        );

#if (PHNT_VERSION >= PHNT_VISTA)

    // private
    NTSYSAPI
        PVOID
        NTAPI
        RtlCommitDebugInfo(
            _Inout_ PRTL_DEBUG_INFORMATION Buffer,
            _In_ SIZE_T Size
        );

    // private
    NTSYSAPI
        VOID
        NTAPI
        RtlDeCommitDebugInfo(
            _Inout_ PRTL_DEBUG_INFORMATION Buffer,
            _In_ PVOID p,
            _In_ SIZE_T Size
        );

#endif

#define RTL_QUERY_PROCESS_MODULES 0x00000001
#define RTL_QUERY_PROCESS_BACKTRACES 0x00000002
#define RTL_QUERY_PROCESS_HEAP_SUMMARY 0x00000004
#define RTL_QUERY_PROCESS_HEAP_TAGS 0x00000008
#define RTL_QUERY_PROCESS_HEAP_ENTRIES 0x00000010
#define RTL_QUERY_PROCESS_LOCKS 0x00000020
#define RTL_QUERY_PROCESS_MODULES32 0x00000040
#define RTL_QUERY_PROCESS_VERIFIER_OPTIONS 0x00000080 // rev
#define RTL_QUERY_PROCESS_MODULESEX 0x00000100 // rev
#define RTL_QUERY_PROCESS_HEAP_SEGMENTS 0x00000200
#define RTL_QUERY_PROCESS_CS_OWNER 0x00000400 // rev
#define RTL_QUERY_PROCESS_NONINVASIVE 0x80000000
#define RTL_QUERY_PROCESS_NONINVASIVE_CS_OWNER 0x80000800 // WIN11

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlQueryProcessDebugInformation(
            _In_ HANDLE UniqueProcessId,
            _In_ ULONG Flags,
            _Inout_ PRTL_DEBUG_INFORMATION Buffer
        );

    // rev
    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlSetProcessDebugInformation(
            _In_ HANDLE UniqueProcessId,
            _In_ ULONG Flags,
            _Inout_ PRTL_DEBUG_INFORMATION Buffer
        );

    // rev
    FORCEINLINE
        BOOLEAN
        NTAPI
        RtlIsAnyDebuggerPresent(
            VOID
        )
    {
        BOOLEAN result;

        result = NtCurrentPeb()->BeingDebugged;

        if (!result)
            return USER_SHARED_DATA->KdDebuggerEnabled;

        return result;
    }

    // Messages

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlFindMessage(
            _In_ PVOID DllHandle,
            _In_ ULONG MessageTableId,
            _In_ ULONG MessageLanguageId,
            _In_ ULONG MessageId,
            _Out_ PMESSAGE_RESOURCE_ENTRY* MessageEntry
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlFormatMessage(
            _In_ PWSTR MessageFormat,
            _In_ ULONG MaximumWidth,
            _In_ BOOLEAN IgnoreInserts,
            _In_ BOOLEAN ArgumentsAreAnsi,
            _In_ BOOLEAN ArgumentsAreAnArray,
            _In_ va_list* Arguments,
            _Out_writes_bytes_to_(Length, *ReturnLength) PWSTR Buffer,
            _In_ ULONG Length,
            _Out_opt_ PULONG ReturnLength
        );

    typedef struct _PARSE_MESSAGE_CONTEXT
    {
        ULONG fFlags;
        ULONG cwSavColumn;
        SIZE_T iwSrc;
        SIZE_T iwDst;
        SIZE_T iwDstSpace;
        va_list lpvArgStart;
    } PARSE_MESSAGE_CONTEXT, * PPARSE_MESSAGE_CONTEXT;

#define INIT_PARSE_MESSAGE_CONTEXT(ctx) { (ctx)->fFlags = 0; }
#define TEST_PARSE_MESSAGE_CONTEXT_FLAG(ctx, flag) ((ctx)->fFlags & (flag))
#define SET_PARSE_MESSAGE_CONTEXT_FLAG(ctx, flag) ((ctx)->fFlags |= (flag))
#define CLEAR_PARSE_MESSAGE_CONTEXT_FLAG(ctx, flag) ((ctx)->fFlags &= ~(flag))

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlFormatMessageEx(
            _In_ PWSTR MessageFormat,
            _In_ ULONG MaximumWidth,
            _In_ BOOLEAN IgnoreInserts,
            _In_ BOOLEAN ArgumentsAreAnsi,
            _In_ BOOLEAN ArgumentsAreAnArray,
            _In_ va_list* Arguments,
            _Out_writes_bytes_to_(Length, *ReturnLength) PWSTR Buffer,
            _In_ ULONG Length,
            _Out_opt_ PULONG ReturnLength,
            _Out_opt_ PPARSE_MESSAGE_CONTEXT ParseContext
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlGetFileMUIPath(
            _In_ ULONG Flags,
            _In_ PCWSTR FilePath,
            _Inout_opt_ PWSTR Language,
            _Inout_ PULONG LanguageLength,
            _Out_opt_ PWSTR FileMUIPath,
            _Inout_ PULONG FileMUIPathLength,
            _Inout_ PULONGLONG Enumerator
        );

    // private
    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlLoadString(
            _In_ PVOID DllHandle,
            _In_ ULONG StringId,
            _In_opt_ PCWSTR StringLanguage,
            _In_ ULONG Flags,
            _Out_ PCWSTR* ReturnString,
            _Out_opt_ PUSHORT ReturnStringLen,
            _Out_writes_(ReturnLanguageLen) PWSTR ReturnLanguageName,
            _Inout_opt_ PULONG ReturnLanguageLen
        );

    // Errors

    NTSYSAPI
        ULONG
        NTAPI
        RtlNtStatusToDosError(
            _In_ NTSTATUS Status
        );

    NTSYSAPI
        ULONG
        NTAPI
        RtlNtStatusToDosErrorNoTeb(
            _In_ NTSTATUS Status
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlGetLastNtStatus(
            VOID
        );

    NTSYSAPI
        LONG
        NTAPI
        RtlGetLastWin32Error(
            VOID
        );

    NTSYSAPI
        VOID
        NTAPI
        RtlSetLastWin32ErrorAndNtStatusFromNtStatus(
            _In_ NTSTATUS Status
        );

    NTSYSAPI
        VOID
        NTAPI
        RtlSetLastWin32Error(
            _In_ LONG Win32Error
        );

    NTSYSAPI
        VOID
        NTAPI
        RtlRestoreLastWin32Error(
            _In_ LONG Win32Error
        );

#define RTL_ERRORMODE_FAILCRITICALERRORS 0x0010
#define RTL_ERRORMODE_NOGPFAULTERRORBOX 0x0020
#define RTL_ERRORMODE_NOOPENFILEERRORBOX 0x0040

    NTSYSAPI
        ULONG
        NTAPI
        RtlGetThreadErrorMode(
            VOID
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlSetThreadErrorMode(
            _In_ ULONG NewMode,
            _Out_opt_ PULONG OldMode
        );

    // Windows Error Reporting

#if (PHNT_VERSION >= PHNT_VISTA)
// private
    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlReportException(
            _In_ PEXCEPTION_RECORD ExceptionRecord,
            _In_ PCONTEXT ContextRecord,
            _In_ ULONG Flags
        );
#endif

#if (PHNT_VERSION >= PHNT_REDSTONE)
    // rev
    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlReportExceptionEx(
            _In_ PEXCEPTION_RECORD ExceptionRecord,
            _In_ PCONTEXT ContextRecord,
            _In_ ULONG Flags,
            _In_ PLARGE_INTEGER Timeout
        );
#endif

#if (PHNT_VERSION >= PHNT_VISTA)
    // private
    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlWerpReportException(
            _In_ ULONG ProcessId,
            _In_ HANDLE CrashReportSharedMem,
            _In_ ULONG Flags,
            _Out_ PHANDLE CrashVerticalProcessHandle
        );
#endif

#if (PHNT_VERSION >= PHNT_WIN7)
    // rev
    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlReportSilentProcessExit(
            _In_ HANDLE ProcessHandle,
            _In_ NTSTATUS ExitStatus
        );
#endif

    // Random

    NTSYSAPI
        ULONG
        NTAPI
        RtlUniform(
            _Inout_ PULONG Seed
        );

    _Ret_range_(<= , MAXLONG)
        NTSYSAPI
        ULONG
        NTAPI
        RtlRandom(
            _Inout_ PULONG Seed
        );

    _Ret_range_(<= , MAXLONG)
        NTSYSAPI
        ULONG
        NTAPI
        RtlRandomEx(
            _Inout_ PULONG Seed
        );

#define RTL_IMPORT_TABLE_HASH_REVISION 1

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlComputeImportTableHash(
            _In_ HANDLE FileHandle,
            _Out_writes_bytes_(16) PCHAR Hash,
            _In_ ULONG ImportTableHashRevision // must be 1
        );

    // Integer conversion

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlIntegerToChar(
            _In_ ULONG Value,
            _In_opt_ ULONG Base,
            _In_ LONG OutputLength, // negative to pad to width
            _Out_ PSTR String
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlCharToInteger(
            _In_ PCSTR String,
            _In_opt_ ULONG Base,
            _Out_ PULONG Value
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlLargeIntegerToChar(
            _In_ PLARGE_INTEGER Value,
            _In_opt_ ULONG Base,
            _In_ LONG OutputLength,
            _Out_ PSTR String
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlIntegerToUnicodeString(
            _In_ ULONG Value,
            _In_opt_ ULONG Base,
            _Inout_ PUNICODE_STRING String
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlInt64ToUnicodeString(
            _In_ ULONGLONG Value,
            _In_opt_ ULONG Base,
            _Inout_ PUNICODE_STRING String
        );

#ifdef _WIN64
#define RtlIntPtrToUnicodeString(Value, Base, String) RtlInt64ToUnicodeString(Value, Base, String)
#else
#define RtlIntPtrToUnicodeString(Value, Base, String) RtlIntegerToUnicodeString(Value, Base, String)
#endif

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlUnicodeStringToInteger(
            _In_ PUNICODE_STRING String,
            _In_opt_ ULONG Base,
            _Out_ PULONG Value
        );

    // IPv4/6 conversion

    typedef struct in_addr IN_ADDR, * PIN_ADDR;
    typedef struct in6_addr IN6_ADDR, * PIN6_ADDR;
    typedef IN_ADDR const* PCIN_ADDR;
    typedef IN6_ADDR const* PCIN6_ADDR;

    NTSYSAPI
        PWSTR
        NTAPI
        RtlIpv4AddressToStringW(
            _In_ PCIN_ADDR Address,
            _Out_writes_(16) PWSTR AddressString
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlIpv4AddressToStringExW(
            _In_ PCIN_ADDR Address,
            _In_ USHORT Port,
            _Out_writes_to_(*AddressStringLength, *AddressStringLength) PWSTR AddressString,
            _Inout_ PULONG AddressStringLength
        );

    NTSYSAPI
        PWSTR
        NTAPI
        RtlIpv6AddressToStringW(
            _In_ PCIN6_ADDR Address,
            _Out_writes_(46) PWSTR AddressString
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlIpv6AddressToStringExW(
            _In_ PCIN6_ADDR Address,
            _In_ ULONG ScopeId,
            _In_ USHORT Port,
            _Out_writes_to_(*AddressStringLength, *AddressStringLength) PWSTR AddressString,
            _Inout_ PULONG AddressStringLength
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlIpv4StringToAddressW(
            _In_ PCWSTR AddressString,
            _In_ BOOLEAN Strict,
            _Out_ LPCWSTR* Terminator,
            _Out_ PIN_ADDR Address
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlIpv4StringToAddressExW(
            _In_ PCWSTR AddressString,
            _In_ BOOLEAN Strict,
            _Out_ PIN_ADDR Address,
            _Out_ PUSHORT Port
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlIpv6StringToAddressW(
            _In_ PCWSTR AddressString,
            _Out_ PCWSTR* Terminator,
            _Out_ PIN6_ADDR Address
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlIpv6StringToAddressExW(
            _In_ PCWSTR AddressString,
            _Out_ PIN6_ADDR Address,
            _Out_ PULONG ScopeId,
            _Out_ PUSHORT Port
        );

#define RtlIpv4AddressToString RtlIpv4AddressToStringW
#define RtlIpv4AddressToStringEx RtlIpv4AddressToStringExW
#define RtlIpv6AddressToString RtlIpv6AddressToStringW
#define RtlIpv6AddressToStringEx RtlIpv6AddressToStringExW
#define RtlIpv4StringToAddress RtlIpv4StringToAddressW
#define RtlIpv4StringToAddressEx RtlIpv4StringToAddressExW
#define RtlIpv6StringToAddress RtlIpv6StringToAddressW
#define RtlIpv6StringToAddressEx RtlIpv6StringToAddressExW

    // Time

    typedef struct _TIME_FIELDS
    {
        CSHORT Year; // 1601...
        CSHORT Month; // 1..12
        CSHORT Day; // 1..31
        CSHORT Hour; // 0..23
        CSHORT Minute; // 0..59
        CSHORT Second; // 0..59
        CSHORT Milliseconds; // 0..999
        CSHORT Weekday; // 0..6 = Sunday..Saturday
    } TIME_FIELDS, * PTIME_FIELDS;

    NTSYSAPI
        BOOLEAN
        NTAPI
        RtlCutoverTimeToSystemTime(
            _In_ PTIME_FIELDS CutoverTime,
            _Out_ PLARGE_INTEGER SystemTime,
            _In_ PLARGE_INTEGER CurrentSystemTime,
            _In_ BOOLEAN ThisYear
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlSystemTimeToLocalTime(
            _In_ PLARGE_INTEGER SystemTime,
            _Out_ PLARGE_INTEGER LocalTime
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlLocalTimeToSystemTime(
            _In_ PLARGE_INTEGER LocalTime,
            _Out_ PLARGE_INTEGER SystemTime
        );

    NTSYSAPI
        VOID
        NTAPI
        RtlTimeToElapsedTimeFields(
            _In_ PLARGE_INTEGER Time,
            _Out_ PTIME_FIELDS TimeFields
        );

    NTSYSAPI
        VOID
        NTAPI
        RtlTimeToTimeFields(
            _In_ PLARGE_INTEGER Time,
            _Out_ PTIME_FIELDS TimeFields
        );

    NTSYSAPI
        BOOLEAN
        NTAPI
        RtlTimeFieldsToTime(
            _In_ PTIME_FIELDS TimeFields, // Weekday is ignored
            _Out_ PLARGE_INTEGER Time
        );

#define SecondsToStartOf1980 11960006400
#define SecondsToStartOf1970 11644473600

    NTSYSAPI
        BOOLEAN
        NTAPI
        RtlTimeToSecondsSince1980(
            _In_ PLARGE_INTEGER Time,
            _Out_ PULONG ElapsedSeconds
        );

    NTSYSAPI
        VOID
        NTAPI
        RtlSecondsSince1980ToTime(
            _In_ ULONG ElapsedSeconds,
            _Out_ PLARGE_INTEGER Time
        );

    NTSYSAPI
        BOOLEAN
        NTAPI
        RtlTimeToSecondsSince1970(
            _In_ PLARGE_INTEGER Time,
            _Out_ PULONG ElapsedSeconds
        );

    NTSYSAPI
        VOID
        NTAPI
        RtlSecondsSince1970ToTime(
            _In_ ULONG ElapsedSeconds,
            _Out_ PLARGE_INTEGER Time
        );

#if (PHNT_VERSION >= PHNT_WIN8)
    NTSYSAPI
        LARGE_INTEGER
        NTAPI
        RtlGetSystemTimePrecise(
            VOID
        );
#endif

#if (PHNT_VERSION >= PHNT_WIN10_21H2)
    NTSYSAPI
        KSYSTEM_TIME
        NTAPI
        RtlGetSystemTimeAndBias(
            _Out_ KSYSTEM_TIME TimeZoneBias,
            _Out_opt_ PLARGE_INTEGER TimeZoneBiasEffectiveStart,
            _Out_opt_ PLARGE_INTEGER TimeZoneBiasEffectiveEnd
        );
#endif

#if (PHNT_VERSION >= PHNT_THRESHOLD)
    NTSYSAPI
        LARGE_INTEGER
        NTAPI
        RtlGetInterruptTimePrecise(
            _Out_ PLARGE_INTEGER PerformanceCounter
        );
#endif

#if (PHNT_VERSION >= PHNT_WIN8)
    NTSYSAPI
        BOOLEAN
        NTAPI
        RtlQueryUnbiasedInterruptTime(
            _Out_ PLARGE_INTEGER InterruptTime
        );
#endif

    // Time zones

    typedef struct _RTL_TIME_ZONE_INFORMATION
    {
        LONG Bias;
        WCHAR StandardName[32];
        TIME_FIELDS StandardStart;
        LONG StandardBias;
        WCHAR DaylightName[32];
        TIME_FIELDS DaylightStart;
        LONG DaylightBias;
    } RTL_TIME_ZONE_INFORMATION, * PRTL_TIME_ZONE_INFORMATION;

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlQueryTimeZoneInformation(
            _Out_ PRTL_TIME_ZONE_INFORMATION TimeZoneInformation
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlSetTimeZoneInformation(
            _In_ PRTL_TIME_ZONE_INFORMATION TimeZoneInformation
        );

    // Interlocked bit manipulation interfaces

#define RtlInterlockedSetBits(Flags, Flag) \
    InterlockedOr((PLONG)(Flags), Flag)

#define RtlInterlockedAndBits(Flags, Flag) \
    InterlockedAnd((PLONG)(Flags), Flag)

#define RtlInterlockedClearBits(Flags, Flag) \
    RtlInterlockedAndBits(Flags, ~(Flag))

#define RtlInterlockedXorBits(Flags, Flag) \
    InterlockedXor(Flags, Flag)

#define RtlInterlockedSetBitsDiscardReturn(Flags, Flag) \
    (VOID) RtlInterlockedSetBits(Flags, Flag)

#define RtlInterlockedAndBitsDiscardReturn(Flags, Flag) \
    (VOID) RtlInterlockedAndBits(Flags, Flag)

#define RtlInterlockedClearBitsDiscardReturn(Flags, Flag) \
    RtlInterlockedAndBitsDiscardReturn(Flags, ~(Flag))

// Bitmaps

    typedef struct _RTL_BITMAP
    {
        ULONG SizeOfBitMap;
        PULONG Buffer;
    } RTL_BITMAP, * PRTL_BITMAP;

    NTSYSAPI
        VOID
        NTAPI
        RtlInitializeBitMap(
            _Out_ PRTL_BITMAP BitMapHeader,
            _In_ PULONG BitMapBuffer,
            _In_ ULONG SizeOfBitMap
        );

#if (PHNT_MODE == PHNT_MODE_KERNEL || PHNT_VERSION >= PHNT_WIN8)
    NTSYSAPI
        VOID
        NTAPI
        RtlClearBit(
            _In_ PRTL_BITMAP BitMapHeader,
            _In_range_(< , BitMapHeader->SizeOfBitMap) ULONG BitNumber
        );
#endif

#if (PHNT_MODE == PHNT_MODE_KERNEL || PHNT_VERSION >= PHNT_WIN8)
    NTSYSAPI
        VOID
        NTAPI
        RtlSetBit(
            _In_ PRTL_BITMAP BitMapHeader,
            _In_range_(< , BitMapHeader->SizeOfBitMap) ULONG BitNumber
        );
#endif

    _Check_return_
        NTSYSAPI
        BOOLEAN
        NTAPI
        RtlTestBit(
            _In_ PRTL_BITMAP BitMapHeader,
            _In_range_(< , BitMapHeader->SizeOfBitMap) ULONG BitNumber
        );

    NTSYSAPI
        VOID
        NTAPI
        RtlClearAllBits(
            _In_ PRTL_BITMAP BitMapHeader
        );

    NTSYSAPI
        VOID
        NTAPI
        RtlSetAllBits(
            _In_ PRTL_BITMAP BitMapHeader
        );

    _Success_(return != -1)
        _Check_return_
        NTSYSAPI
        ULONG
        NTAPI
        RtlFindClearBits(
            _In_ PRTL_BITMAP BitMapHeader,
            _In_ ULONG NumberToFind,
            _In_ ULONG HintIndex
        );

    _Success_(return != -1)
        _Check_return_
        NTSYSAPI
        ULONG
        NTAPI
        RtlFindSetBits(
            _In_ PRTL_BITMAP BitMapHeader,
            _In_ ULONG NumberToFind,
            _In_ ULONG HintIndex
        );

    _Success_(return != -1)
        NTSYSAPI
        ULONG
        NTAPI
        RtlFindClearBitsAndSet(
            _In_ PRTL_BITMAP BitMapHeader,
            _In_ ULONG NumberToFind,
            _In_ ULONG HintIndex
        );

    _Success_(return != -1)
        NTSYSAPI
        ULONG
        NTAPI
        RtlFindSetBitsAndClear(
            _In_ PRTL_BITMAP BitMapHeader,
            _In_ ULONG NumberToFind,
            _In_ ULONG HintIndex
        );

    NTSYSAPI
        VOID
        NTAPI
        RtlClearBits(
            _In_ PRTL_BITMAP BitMapHeader,
            _In_range_(0, BitMapHeader->SizeOfBitMap - NumberToClear) ULONG StartingIndex,
            _In_range_(0, BitMapHeader->SizeOfBitMap - StartingIndex) ULONG NumberToClear
        );

    NTSYSAPI
        VOID
        NTAPI
        RtlSetBits(
            _In_ PRTL_BITMAP BitMapHeader,
            _In_range_(0, BitMapHeader->SizeOfBitMap - NumberToSet) ULONG StartingIndex,
            _In_range_(0, BitMapHeader->SizeOfBitMap - StartingIndex) ULONG NumberToSet
        );

    NTSYSAPI
        CCHAR
        NTAPI
        RtlFindMostSignificantBit(
            _In_ ULONGLONG Set
        );

    NTSYSAPI
        CCHAR
        NTAPI
        RtlFindLeastSignificantBit(
            _In_ ULONGLONG Set
        );

    typedef struct _RTL_BITMAP_RUN
    {
        ULONG StartingIndex;
        ULONG NumberOfBits;
    } RTL_BITMAP_RUN, * PRTL_BITMAP_RUN;

    NTSYSAPI
        ULONG
        NTAPI
        RtlFindClearRuns(
            _In_ PRTL_BITMAP BitMapHeader,
            _Out_writes_to_(SizeOfRunArray, return) PRTL_BITMAP_RUN RunArray,
            _In_range_(> , 0) ULONG SizeOfRunArray,
            _In_ BOOLEAN LocateLongestRuns
        );

    NTSYSAPI
        ULONG
        NTAPI
        RtlFindLongestRunClear(
            _In_ PRTL_BITMAP BitMapHeader,
            _Out_ PULONG StartingIndex
        );

    NTSYSAPI
        ULONG
        NTAPI
        RtlFindFirstRunClear(
            _In_ PRTL_BITMAP BitMapHeader,
            _Out_ PULONG StartingIndex
        );

    _Check_return_
        FORCEINLINE
        BOOLEAN
        RtlCheckBit(
            _In_ PRTL_BITMAP BitMapHeader,
            _In_range_(< , BitMapHeader->SizeOfBitMap) ULONG BitPosition
        )
    {
#ifdef _WIN64
        return BitTest64((LONG64 const*)BitMapHeader->Buffer, (LONG64)BitPosition);
#else
        return (((PLONG)BitMapHeader->Buffer)[BitPosition / 32] >> (BitPosition % 32)) & 0x1;
#endif
    }

    NTSYSAPI
        ULONG
        NTAPI
        RtlNumberOfClearBits(
            _In_ PRTL_BITMAP BitMapHeader
        );

    NTSYSAPI
        ULONG
        NTAPI
        RtlNumberOfSetBits(
            _In_ PRTL_BITMAP BitMapHeader
        );

    _Check_return_
        NTSYSAPI
        BOOLEAN
        NTAPI
        RtlAreBitsClear(
            _In_ PRTL_BITMAP BitMapHeader,
            _In_ ULONG StartingIndex,
            _In_ ULONG Length
        );

    _Check_return_
        NTSYSAPI
        BOOLEAN
        NTAPI
        RtlAreBitsSet(
            _In_ PRTL_BITMAP BitMapHeader,
            _In_ ULONG StartingIndex,
            _In_ ULONG Length
        );

    NTSYSAPI
        ULONG
        NTAPI
        RtlFindNextForwardRunClear(
            _In_ PRTL_BITMAP BitMapHeader,
            _In_ ULONG FromIndex,
            _Out_ PULONG StartingRunIndex
        );

    NTSYSAPI
        ULONG
        NTAPI
        RtlFindLastBackwardRunClear(
            _In_ PRTL_BITMAP BitMapHeader,
            _In_ ULONG FromIndex,
            _Out_ PULONG StartingRunIndex
        );

#if (PHNT_VERSION >= PHNT_VISTA)

    NTSYSAPI
        ULONG
        NTAPI
        RtlNumberOfSetBitsUlongPtr(
            _In_ ULONG_PTR Target
        );

#endif

#if (PHNT_VERSION >= PHNT_WIN7)

    // rev
    NTSYSAPI
        VOID
        NTAPI
        RtlInterlockedClearBitRun(
            _In_ PRTL_BITMAP BitMapHeader,
            _In_range_(0, BitMapHeader->SizeOfBitMap - NumberToClear) ULONG StartingIndex,
            _In_range_(0, BitMapHeader->SizeOfBitMap - StartingIndex) ULONG NumberToClear
        );

    // rev
    NTSYSAPI
        VOID
        NTAPI
        RtlInterlockedSetBitRun(
            _In_ PRTL_BITMAP BitMapHeader,
            _In_range_(0, BitMapHeader->SizeOfBitMap - NumberToSet) ULONG StartingIndex,
            _In_range_(0, BitMapHeader->SizeOfBitMap - StartingIndex) ULONG NumberToSet
        );

#endif

#if (PHNT_VERSION >= PHNT_WIN8)

    NTSYSAPI
        VOID
        NTAPI
        RtlCopyBitMap(
            _In_ PRTL_BITMAP Source,
            _In_ PRTL_BITMAP Destination,
            _In_range_(0, Destination->SizeOfBitMap - 1) ULONG TargetBit
        );

    NTSYSAPI
        VOID
        NTAPI
        RtlExtractBitMap(
            _In_ PRTL_BITMAP Source,
            _In_ PRTL_BITMAP Destination,
            _In_range_(0, Source->SizeOfBitMap - 1) ULONG TargetBit,
            _In_range_(0, Source->SizeOfBitMap) ULONG NumberOfBits
        );

    NTSYSAPI
        ULONG
        NTAPI
        RtlNumberOfClearBitsInRange(
            _In_ PRTL_BITMAP BitMapHeader,
            _In_ ULONG StartingIndex,
            _In_ ULONG Length
        );

    NTSYSAPI
        ULONG
        NTAPI
        RtlNumberOfSetBitsInRange(
            _In_ PRTL_BITMAP BitMapHeader,
            _In_ ULONG StartingIndex,
            _In_ ULONG Length
        );

#endif

#if (PHNT_VERSION >= PHNT_THRESHOLD)

    // private
    typedef struct _RTL_BITMAP_EX
    {
        ULONG64 SizeOfBitMap;
        PULONG64 Buffer;
    } RTL_BITMAP_EX, * PRTL_BITMAP_EX;

    // rev
    NTSYSAPI
        VOID
        NTAPI
        RtlInitializeBitMapEx(
            _Out_ PRTL_BITMAP_EX BitMapHeader,
            _In_ PULONG64 BitMapBuffer,
            _In_ ULONG64 SizeOfBitMap
        );

    // rev
    _Check_return_
        NTSYSAPI
        BOOLEAN
        NTAPI
        RtlTestBitEx(
            _In_ PRTL_BITMAP_EX BitMapHeader,
            _In_range_(< , BitMapHeader->SizeOfBitMap) ULONG64 BitNumber
        );

    // rev
    NTSYSAPI
        VOID
        NTAPI
        RtlClearAllBitsEx(
            _In_ PRTL_BITMAP_EX BitMapHeader
        );

    // rev
    NTSYSAPI
        VOID
        NTAPI
        RtlClearBitEx(
            _In_ PRTL_BITMAP_EX BitMapHeader,
            _In_range_(< , BitMapHeader->SizeOfBitMap) ULONG64 BitNumber
        );

    // rev
    NTSYSAPI
        VOID
        NTAPI
        RtlSetBitEx(
            _In_ PRTL_BITMAP_EX BitMapHeader,
            _In_range_(< , BitMapHeader->SizeOfBitMap) ULONG64 BitNumber
        );

    // rev
    NTSYSAPI
        ULONG64
        NTAPI
        RtlFindSetBitsEx(
            _In_ PRTL_BITMAP_EX BitMapHeader,
            _In_ ULONG64 NumberToFind,
            _In_ ULONG64 HintIndex
        );

    NTSYSAPI
        ULONG64
        NTAPI
        RtlFindSetBitsAndClearEx(
            _In_ PRTL_BITMAP_EX BitMapHeader,
            _In_ ULONG64 NumberToFind,
            _In_ ULONG64 HintIndex
        );

#endif

    // Handle tables

    typedef struct _RTL_HANDLE_TABLE_ENTRY
    {
        union
        {
            ULONG Flags; // allocated entries have the low bit set
            struct _RTL_HANDLE_TABLE_ENTRY* NextFree;
        };
    } RTL_HANDLE_TABLE_ENTRY, * PRTL_HANDLE_TABLE_ENTRY;

#define RTL_HANDLE_ALLOCATED (USHORT)0x0001

    typedef struct _RTL_HANDLE_TABLE
    {
        ULONG MaximumNumberOfHandles;
        ULONG SizeOfHandleTableEntry;
        ULONG Reserved[2];
        PRTL_HANDLE_TABLE_ENTRY FreeHandles;
        PRTL_HANDLE_TABLE_ENTRY CommittedHandles;
        PRTL_HANDLE_TABLE_ENTRY UnCommittedHandles;
        PRTL_HANDLE_TABLE_ENTRY MaxReservedHandles;
    } RTL_HANDLE_TABLE, * PRTL_HANDLE_TABLE;

    NTSYSAPI
        VOID
        NTAPI
        RtlInitializeHandleTable(
            _In_ ULONG MaximumNumberOfHandles,
            _In_ ULONG SizeOfHandleTableEntry,
            _Out_ PRTL_HANDLE_TABLE HandleTable
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlDestroyHandleTable(
            _Inout_ PRTL_HANDLE_TABLE HandleTable
        );

    NTSYSAPI
        PRTL_HANDLE_TABLE_ENTRY
        NTAPI
        RtlAllocateHandle(
            _In_ PRTL_HANDLE_TABLE HandleTable,
            _Out_opt_ PULONG HandleIndex
        );

    NTSYSAPI
        BOOLEAN
        NTAPI
        RtlFreeHandle(
            _In_ PRTL_HANDLE_TABLE HandleTable,
            _In_ PRTL_HANDLE_TABLE_ENTRY Handle
        );

    NTSYSAPI
        BOOLEAN
        NTAPI
        RtlIsValidHandle(
            _In_ PRTL_HANDLE_TABLE HandleTable,
            _In_ PRTL_HANDLE_TABLE_ENTRY Handle
        );

    NTSYSAPI
        BOOLEAN
        NTAPI
        RtlIsValidIndexHandle(
            _In_ PRTL_HANDLE_TABLE HandleTable,
            _In_ ULONG HandleIndex,
            _Out_ PRTL_HANDLE_TABLE_ENTRY* Handle
        );

    // Atom tables

#define RTL_ATOM_MAXIMUM_INTEGER_ATOM (RTL_ATOM)0xc000
#define RTL_ATOM_INVALID_ATOM (RTL_ATOM)0x0000
#define RTL_ATOM_TABLE_DEFAULT_NUMBER_OF_BUCKETS 37
#define RTL_ATOM_MAXIMUM_NAME_LENGTH 255
#define RTL_ATOM_PINNED 0x01

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlCreateAtomTable(
            _In_ ULONG NumberOfBuckets,
            _Out_ PVOID* AtomTableHandle
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlDestroyAtomTable(
            _In_ _Post_invalid_ PVOID AtomTableHandle
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlEmptyAtomTable(
            _In_ PVOID AtomTableHandle,
            _In_ BOOLEAN IncludePinnedAtoms
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlAddAtomToAtomTable(
            _In_ PVOID AtomTableHandle,
            _In_ PWSTR AtomName,
            _Inout_opt_ PRTL_ATOM Atom
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlLookupAtomInAtomTable(
            _In_ PVOID AtomTableHandle,
            _In_ PWSTR AtomName,
            _Out_opt_ PRTL_ATOM Atom
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlDeleteAtomFromAtomTable(
            _In_ PVOID AtomTableHandle,
            _In_ RTL_ATOM Atom
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlPinAtomInAtomTable(
            _In_ PVOID AtomTableHandle,
            _In_ RTL_ATOM Atom
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlQueryAtomInAtomTable(
            _In_ PVOID AtomTableHandle,
            _In_ RTL_ATOM Atom,
            _Out_opt_ PULONG AtomUsage,
            _Out_opt_ PULONG AtomFlags,
            _Inout_updates_bytes_to_opt_(*AtomNameLength, *AtomNameLength) PWSTR AtomName,
            _Inout_opt_ PULONG AtomNameLength
        );

#if (PHNT_VERSION >= PHNT_VISTA)
    // rev
    NTSYSAPI
        BOOLEAN
        NTAPI
        RtlGetIntegerAtom(
            _In_ PWSTR AtomName,
            _Out_opt_ PUSHORT IntegerAtom
        );
#endif

    // SIDs

    _Must_inspect_result_
        NTSYSAPI
        BOOLEAN
        NTAPI
        RtlValidSid(
            _In_ PSID Sid
        );

    _Must_inspect_result_
        NTSYSAPI
        BOOLEAN
        NTAPI
        RtlEqualSid(
            _In_ PSID Sid1,
            _In_ PSID Sid2
        );

    _Must_inspect_result_
        NTSYSAPI
        BOOLEAN
        NTAPI
        RtlEqualPrefixSid(
            _In_ PSID Sid1,
            _In_ PSID Sid2
        );

    NTSYSAPI
        ULONG
        NTAPI
        RtlLengthRequiredSid(
            _In_ ULONG SubAuthorityCount
        );

    NTSYSAPI
        PVOID
        NTAPI
        RtlFreeSid(
            _In_ _Post_invalid_ PSID Sid
        );

    _Must_inspect_result_
        NTSYSAPI
        NTSTATUS
        NTAPI
        RtlAllocateAndInitializeSid(
            _In_ PSID_IDENTIFIER_AUTHORITY IdentifierAuthority,
            _In_ UCHAR SubAuthorityCount,
            _In_ ULONG SubAuthority0,
            _In_ ULONG SubAuthority1,
            _In_ ULONG SubAuthority2,
            _In_ ULONG SubAuthority3,
            _In_ ULONG SubAuthority4,
            _In_ ULONG SubAuthority5,
            _In_ ULONG SubAuthority6,
            _In_ ULONG SubAuthority7,
            _Outptr_ PSID* Sid
        );

#if (PHNT_VERSION >= PHNT_WINBLUE)
    _Must_inspect_result_
        NTSYSAPI
        NTSTATUS
        NTAPI
        RtlAllocateAndInitializeSidEx(
            _In_ PSID_IDENTIFIER_AUTHORITY IdentifierAuthority,
            _In_ UCHAR SubAuthorityCount,
            _In_reads_(SubAuthorityCount) PULONG SubAuthorities,
            _Outptr_ PSID* Sid
        );
#endif

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlInitializeSid(
            _Out_ PSID Sid,
            _In_ PSID_IDENTIFIER_AUTHORITY IdentifierAuthority,
            _In_ UCHAR SubAuthorityCount
        );

#if (PHNT_VERSION >= PHNT_THRESHOLD)
    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlInitializeSidEx(
            _Out_writes_bytes_(SECURITY_SID_SIZE(SubAuthorityCount)) PSID Sid,
            _In_ PSID_IDENTIFIER_AUTHORITY IdentifierAuthority,
            _In_ UCHAR SubAuthorityCount,
            ...
        );
#endif

    NTSYSAPI
        PSID_IDENTIFIER_AUTHORITY
        NTAPI
        RtlIdentifierAuthoritySid(
            _In_ PSID Sid
        );

    NTSYSAPI
        PULONG
        NTAPI
        RtlSubAuthoritySid(
            _In_ PSID Sid,
            _In_ ULONG SubAuthority
        );

    NTSYSAPI
        PUCHAR
        NTAPI
        RtlSubAuthorityCountSid(
            _In_ PSID Sid
        );

    NTSYSAPI
        ULONG
        NTAPI
        RtlLengthSid(
            _In_ PSID Sid
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlCopySid(
            _In_ ULONG DestinationSidLength,
            _Out_writes_bytes_(DestinationSidLength) PSID DestinationSid,
            _In_ PSID SourceSid
        );

    // ros
    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlCopySidAndAttributesArray(
            _In_ ULONG Count,
            _In_ PSID_AND_ATTRIBUTES Src,
            _In_ ULONG SidAreaSize,
            _In_ PSID_AND_ATTRIBUTES Dest,
            _In_ PSID SidArea,
            _Out_ PSID* RemainingSidArea,
            _Out_ PULONG RemainingSidAreaSize
        );

#if (PHNT_VERSION >= PHNT_VISTA)

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlCreateServiceSid(
            _In_ PUNICODE_STRING ServiceName,
            _Out_writes_bytes_opt_(*ServiceSidLength) PSID ServiceSid,
            _Inout_ PULONG ServiceSidLength
        );

#endif

#if (PHNT_VERSION >= PHNT_VISTA)

    // private
    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlSidDominates(
            _In_ PSID Sid1,
            _In_ PSID Sid2,
            _Out_ PBOOLEAN Dominates
        );

#endif

#if (PHNT_VERSION >= PHNT_WINBLUE)

    // rev
    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlSidDominatesForTrust(
            _In_ PSID Sid1,
            _In_ PSID Sid2,
            _Out_ PBOOLEAN DominatesTrust // TokenProcessTrustLevel
        );

#endif

#if (PHNT_VERSION >= PHNT_VISTA)
    // private
    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlSidEqualLevel(
            _In_ PSID Sid1,
            _In_ PSID Sid2,
            _Out_ PBOOLEAN EqualLevel
        );

    // private
    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlSidIsHigherLevel(
            _In_ PSID Sid1,
            _In_ PSID Sid2,
            _Out_ PBOOLEAN HigherLevel
        );
#endif

#if (PHNT_VERSION >= PHNT_WIN7)
    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlCreateVirtualAccountSid(
            _In_ PUNICODE_STRING Name,
            _In_ ULONG BaseSubAuthority,
            _Out_writes_bytes_(*SidLength) PSID Sid,
            _Inout_ PULONG SidLength
        );
#endif

#if (PHNT_VERSION >= PHNT_WIN7)
    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlReplaceSidInSd(
            _Inout_ PSECURITY_DESCRIPTOR SecurityDescriptor,
            _In_ PSID OldSid,
            _In_ PSID NewSid,
            _Out_ ULONG* NumChanges
        );
#endif

#define MAX_UNICODE_STACK_BUFFER_LENGTH 256

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlLengthSidAsUnicodeString(
            _In_ PSID Sid,
            _Out_ PULONG StringLength
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlConvertSidToUnicodeString(
            _Inout_ PUNICODE_STRING UnicodeString,
            _In_ PSID Sid,
            _In_ BOOLEAN AllocateDestinationString
        );

#if (PHNT_VERSION >= PHNT_VISTA)
    // private
    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlSidHashInitialize(
            _In_reads_(SidCount) PSID_AND_ATTRIBUTES SidAttr,
            _In_ ULONG SidCount,
            _Out_ PSID_AND_ATTRIBUTES_HASH SidAttrHash
        );
#endif

#if (PHNT_VERSION >= PHNT_VISTA)
    // private
    NTSYSAPI
        PSID_AND_ATTRIBUTES
        NTAPI
        RtlSidHashLookup(
            _In_ PSID_AND_ATTRIBUTES_HASH SidAttrHash,
            _In_ PSID Sid
        );
#endif

#if (PHNT_VERSION >= PHNT_VISTA)
    // rev
    NTSYSAPI
        BOOLEAN
        NTAPI
        RtlIsElevatedRid(
            _In_ PSID_AND_ATTRIBUTES SidAttr
        );
#endif

#if (PHNT_VERSION >= PHNT_THRESHOLD)
    // rev
    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlDeriveCapabilitySidsFromName(
            _Inout_ PUNICODE_STRING UnicodeString,
            _Out_ PSID CapabilityGroupSid,
            _Out_ PSID CapabilitySid
        );
#endif

    // Security Descriptors

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlCreateSecurityDescriptor(
            _Out_ PSECURITY_DESCRIPTOR SecurityDescriptor,
            _In_ ULONG Revision
        );

    _Check_return_
        NTSYSAPI
        BOOLEAN
        NTAPI
        RtlValidSecurityDescriptor(
            _In_ PSECURITY_DESCRIPTOR SecurityDescriptor
        );

    NTSYSAPI
        ULONG
        NTAPI
        RtlLengthSecurityDescriptor(
            _In_ PSECURITY_DESCRIPTOR SecurityDescriptor
        );

    _Check_return_
        NTSYSAPI
        BOOLEAN
        NTAPI
        RtlValidRelativeSecurityDescriptor(
            _In_reads_bytes_(SecurityDescriptorLength) PSECURITY_DESCRIPTOR SecurityDescriptorInput,
            _In_ ULONG SecurityDescriptorLength,
            _In_ SECURITY_INFORMATION RequiredInformation
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlGetControlSecurityDescriptor(
            _In_ PSECURITY_DESCRIPTOR SecurityDescriptor,
            _Out_ PSECURITY_DESCRIPTOR_CONTROL Control,
            _Out_ PULONG Revision
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlSetControlSecurityDescriptor(
            _Inout_ PSECURITY_DESCRIPTOR SecurityDescriptor,
            _In_ SECURITY_DESCRIPTOR_CONTROL ControlBitsOfInterest,
            _In_ SECURITY_DESCRIPTOR_CONTROL ControlBitsToSet
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlSetAttributesSecurityDescriptor(
            _Inout_ PSECURITY_DESCRIPTOR SecurityDescriptor,
            _In_ SECURITY_DESCRIPTOR_CONTROL Control,
            _Out_ PULONG Revision
        );

    NTSYSAPI
        BOOLEAN
        NTAPI
        RtlGetSecurityDescriptorRMControl(
            _In_ PSECURITY_DESCRIPTOR SecurityDescriptor,
            _Out_ PUCHAR RMControl
        );

    NTSYSAPI
        VOID
        NTAPI
        RtlSetSecurityDescriptorRMControl(
            _Inout_ PSECURITY_DESCRIPTOR SecurityDescriptor,
            _In_opt_ PUCHAR RMControl
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlSetDaclSecurityDescriptor(
            _Inout_ PSECURITY_DESCRIPTOR SecurityDescriptor,
            _In_ BOOLEAN DaclPresent,
            _In_opt_ PACL Dacl,
            _In_ BOOLEAN DaclDefaulted
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlGetDaclSecurityDescriptor(
            _In_ PSECURITY_DESCRIPTOR SecurityDescriptor,
            _Out_ PBOOLEAN DaclPresent,
            _Outptr_result_maybenull_ PACL* Dacl,
            _Out_ PBOOLEAN DaclDefaulted
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlSetSaclSecurityDescriptor(
            _Inout_ PSECURITY_DESCRIPTOR SecurityDescriptor,
            _In_ BOOLEAN SaclPresent,
            _In_opt_ PACL Sacl,
            _In_ BOOLEAN SaclDefaulted
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlGetSaclSecurityDescriptor(
            _In_ PSECURITY_DESCRIPTOR SecurityDescriptor,
            _Out_ PBOOLEAN SaclPresent,
            _Out_ PACL* Sacl,
            _Out_ PBOOLEAN SaclDefaulted
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlSetOwnerSecurityDescriptor(
            _Inout_ PSECURITY_DESCRIPTOR SecurityDescriptor,
            _In_opt_ PSID Owner,
            _In_ BOOLEAN OwnerDefaulted
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlGetOwnerSecurityDescriptor(
            _In_ PSECURITY_DESCRIPTOR SecurityDescriptor,
            _Outptr_result_maybenull_ PSID* Owner,
            _Out_ PBOOLEAN OwnerDefaulted
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlSetGroupSecurityDescriptor(
            _Inout_ PSECURITY_DESCRIPTOR SecurityDescriptor,
            _In_opt_ PSID Group,
            _In_ BOOLEAN GroupDefaulted
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlGetGroupSecurityDescriptor(
            _In_ PSECURITY_DESCRIPTOR SecurityDescriptor,
            _Outptr_result_maybenull_ PSID* Group,
            _Out_ PBOOLEAN GroupDefaulted
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlMakeSelfRelativeSD(
            _In_ PSECURITY_DESCRIPTOR AbsoluteSecurityDescriptor,
            _Out_writes_bytes_(*BufferLength) PSECURITY_DESCRIPTOR SelfRelativeSecurityDescriptor,
            _Inout_ PULONG BufferLength
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlAbsoluteToSelfRelativeSD(
            _In_ PSECURITY_DESCRIPTOR AbsoluteSecurityDescriptor,
            _Out_writes_bytes_to_opt_(*BufferLength, *BufferLength) PSECURITY_DESCRIPTOR SelfRelativeSecurityDescriptor,
            _Inout_ PULONG BufferLength
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlSelfRelativeToAbsoluteSD(
            _In_ PSECURITY_DESCRIPTOR SelfRelativeSecurityDescriptor,
            _Out_writes_bytes_to_opt_(*AbsoluteSecurityDescriptorSize, *AbsoluteSecurityDescriptorSize) PSECURITY_DESCRIPTOR AbsoluteSecurityDescriptor,
            _Inout_ PULONG AbsoluteSecurityDescriptorSize,
            _Out_writes_bytes_to_opt_(*DaclSize, *DaclSize) PACL Dacl,
            _Inout_ PULONG DaclSize,
            _Out_writes_bytes_to_opt_(*SaclSize, *SaclSize) PACL Sacl,
            _Inout_ PULONG SaclSize,
            _Out_writes_bytes_to_opt_(*OwnerSize, *OwnerSize) PSID Owner,
            _Inout_ PULONG OwnerSize,
            _Out_writes_bytes_to_opt_(*PrimaryGroupSize, *PrimaryGroupSize) PSID PrimaryGroup,
            _Inout_ PULONG PrimaryGroupSize
        );

    // private
    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlSelfRelativeToAbsoluteSD2(
            _Inout_ PSECURITY_DESCRIPTOR SelfRelativeSecurityDescriptor,
            _Inout_ PULONG BufferSize
        );

#if (PHNT_VERSION >= PHNT_19H2)
    __drv_maxIRQL(APC_LEVEL)
        NTSYSAPI
        BOOLEAN
        NTAPI
        RtlNormalizeSecurityDescriptor(
            _Inout_ PSECURITY_DESCRIPTOR* SecurityDescriptor,
            _In_ ULONG SecurityDescriptorLength,
            _Out_opt_ PSECURITY_DESCRIPTOR* NewSecurityDescriptor,
            _Out_opt_ PULONG NewSecurityDescriptorLength,
            _In_ BOOLEAN CheckOnly
        );
#endif

    // Access masks

#ifndef PHNT_NO_INLINE_ACCESSES_GRANTED
    FORCEINLINE
        BOOLEAN
        NTAPI
        RtlAreAllAccessesGranted(
            _In_ ACCESS_MASK GrantedAccess,
            _In_ ACCESS_MASK DesiredAccess
        )
    {
        return (~GrantedAccess & DesiredAccess) == 0;
    }

    FORCEINLINE
        BOOLEAN
        NTAPI
        RtlAreAnyAccessesGranted(
            _In_ ACCESS_MASK GrantedAccess,
            _In_ ACCESS_MASK DesiredAccess
        )
    {
        return (GrantedAccess & DesiredAccess) != 0;
    }
#else
    NTSYSAPI
        BOOLEAN
        NTAPI
        RtlAreAllAccessesGranted(
            _In_ ACCESS_MASK GrantedAccess,
            _In_ ACCESS_MASK DesiredAccess
        );

    NTSYSAPI
        BOOLEAN
        NTAPI
        RtlAreAnyAccessesGranted(
            _In_ ACCESS_MASK GrantedAccess,
            _In_ ACCESS_MASK DesiredAccess
        );
#endif

    NTSYSAPI
        VOID
        NTAPI
        RtlMapGenericMask(
            _Inout_ PACCESS_MASK AccessMask,
            _In_ PGENERIC_MAPPING GenericMapping
        );

    // ACLs

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlCreateAcl(
            _Out_writes_bytes_(AclLength) PACL Acl,
            _In_ ULONG AclLength,
            _In_ ULONG AclRevision
        );

    NTSYSAPI
        BOOLEAN
        NTAPI
        RtlValidAcl(
            _In_ PACL Acl
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlQueryInformationAcl(
            _In_ PACL Acl,
            _Out_writes_bytes_(AclInformationLength) PVOID AclInformation,
            _In_ ULONG AclInformationLength,
            _In_ ACL_INFORMATION_CLASS AclInformationClass
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlSetInformationAcl(
            _Inout_ PACL Acl,
            _In_reads_bytes_(AclInformationLength) PVOID AclInformation,
            _In_ ULONG AclInformationLength,
            _In_ ACL_INFORMATION_CLASS AclInformationClass
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlAddAce(
            _Inout_ PACL Acl,
            _In_ ULONG AceRevision,
            _In_ ULONG StartingAceIndex,
            _In_reads_bytes_(AceListLength) PVOID AceList,
            _In_ ULONG AceListLength
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlDeleteAce(
            _Inout_ PACL Acl,
            _In_ ULONG AceIndex
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlGetAce(
            _In_ PACL Acl,
            _In_ ULONG AceIndex,
            _Outptr_ PVOID* Ace
        );

    NTSYSAPI
        BOOLEAN
        NTAPI
        RtlFirstFreeAce(
            _In_ PACL Acl,
            _Out_ PVOID* FirstFree
        );

#if (PHNT_VERSION >= PHNT_VISTA)
    // private
    NTSYSAPI
        PVOID
        NTAPI
        RtlFindAceByType(
            _In_ PACL Acl,
            _In_ UCHAR AceType,
            _Out_opt_ PULONG Index
        );
#endif

#if (PHNT_VERSION >= PHNT_VISTA)
    // private
    NTSYSAPI
        BOOLEAN
        NTAPI
        RtlOwnerAcesPresent(
            _In_ PACL pAcl
        );
#endif

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlAddAccessAllowedAce(
            _Inout_ PACL Acl,
            _In_ ULONG AceRevision,
            _In_ ACCESS_MASK AccessMask,
            _In_ PSID Sid
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlAddAccessAllowedAceEx(
            _Inout_ PACL Acl,
            _In_ ULONG AceRevision,
            _In_ ULONG AceFlags,
            _In_ ACCESS_MASK AccessMask,
            _In_ PSID Sid
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlAddAccessDeniedAce(
            _Inout_ PACL Acl,
            _In_ ULONG AceRevision,
            _In_ ACCESS_MASK AccessMask,
            _In_ PSID Sid
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlAddAccessDeniedAceEx(
            _Inout_ PACL Acl,
            _In_ ULONG AceRevision,
            _In_ ULONG AceFlags,
            _In_ ACCESS_MASK AccessMask,
            _In_ PSID Sid
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlAddAuditAccessAce(
            _Inout_ PACL Acl,
            _In_ ULONG AceRevision,
            _In_ ACCESS_MASK AccessMask,
            _In_ PSID Sid,
            _In_ BOOLEAN AuditSuccess,
            _In_ BOOLEAN AuditFailure
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlAddAuditAccessAceEx(
            _Inout_ PACL Acl,
            _In_ ULONG AceRevision,
            _In_ ULONG AceFlags,
            _In_ ACCESS_MASK AccessMask,
            _In_ PSID Sid,
            _In_ BOOLEAN AuditSuccess,
            _In_ BOOLEAN AuditFailure
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlAddAccessAllowedObjectAce(
            _Inout_ PACL Acl,
            _In_ ULONG AceRevision,
            _In_ ULONG AceFlags,
            _In_ ACCESS_MASK AccessMask,
            _In_opt_ PGUID ObjectTypeGuid,
            _In_opt_ PGUID InheritedObjectTypeGuid,
            _In_ PSID Sid
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlAddAccessDeniedObjectAce(
            _Inout_ PACL Acl,
            _In_ ULONG AceRevision,
            _In_ ULONG AceFlags,
            _In_ ACCESS_MASK AccessMask,
            _In_opt_ PGUID ObjectTypeGuid,
            _In_opt_ PGUID InheritedObjectTypeGuid,
            _In_ PSID Sid
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlAddAuditAccessObjectAce(
            _Inout_ PACL Acl,
            _In_ ULONG AceRevision,
            _In_ ULONG AceFlags,
            _In_ ACCESS_MASK AccessMask,
            _In_opt_ PGUID ObjectTypeGuid,
            _In_opt_ PGUID InheritedObjectTypeGuid,
            _In_ PSID Sid,
            _In_ BOOLEAN AuditSuccess,
            _In_ BOOLEAN AuditFailure
        );

    // private
#define COMPOUND_ACE_IMPERSONATION 1

// private
    typedef struct _COMPOUND_ACCESS_ALLOWED_ACE
    {
        ACE_HEADER Header;
        ACCESS_MASK Mask;
        USHORT CompoundAceType; // COMPOUND_ACE_*
        USHORT Reserved;
        ULONG SidStart; // Server SID
        // Client SID follows
    } COMPOUND_ACCESS_ALLOWED_ACE, * PCOMPOUND_ACCESS_ALLOWED_ACE;

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlAddCompoundAce(
            _Inout_ PACL Acl,
            _In_ ULONG AceRevision,
            _In_ UCHAR AceType, // COMPOUND_ACE_*
            _In_ ACCESS_MASK AccessMask,
            _In_ PSID ServerSid,
            _In_ PSID ClientSid
        );

#if (PHNT_VERSION >= PHNT_VISTA)
    // private
    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlAddMandatoryAce(
            _Inout_ PACL Acl,
            _In_ ULONG AceRevision,
            _In_ ULONG AceFlags,
            _In_ PSID Sid,
            _In_ UCHAR AceType,
            _In_ ACCESS_MASK AccessMask
        );
#endif

#if (PHNT_VERSION >= PHNT_WIN8)
    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlAddResourceAttributeAce(
            _Inout_ PACL Acl,
            _In_ ULONG AceRevision,
            _In_ ULONG AceFlags,
            _In_ ULONG AccessMask,
            _In_ PSID Sid,
            _In_ PCLAIM_SECURITY_ATTRIBUTES_INFORMATION AttributeInfo,
            _Out_ PULONG ReturnLength
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlAddScopedPolicyIDAce(
            _Inout_ PACL Acl,
            _In_ ULONG AceRevision,
            _In_ ULONG AceFlags,
            _In_ ULONG AccessMask,
            _In_ PSID Sid
        );

    // rev
    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlAddProcessTrustLabelAce(
            _Inout_ PACL Acl,
            _In_ ULONG AceRevision,
            _In_ ULONG AceFlags,
            _In_ PSID ProcessTrustLabelSid,
            _In_ UCHAR AceType, // SYSTEM_PROCESS_TRUST_LABEL_ACE_TYPE
            _In_ ACCESS_MASK AccessMask
        );
#endif

    // Named pipes

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlDefaultNpAcl(
            _Out_ PACL* Acl
        );

    // Security objects

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlNewSecurityObject(
            _In_opt_ PSECURITY_DESCRIPTOR ParentDescriptor,
            _In_opt_ PSECURITY_DESCRIPTOR CreatorDescriptor,
            _Out_ PSECURITY_DESCRIPTOR* NewDescriptor,
            _In_ BOOLEAN IsDirectoryObject,
            _In_opt_ HANDLE Token,
            _In_ PGENERIC_MAPPING GenericMapping
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlNewSecurityObjectEx(
            _In_opt_ PSECURITY_DESCRIPTOR ParentDescriptor,
            _In_opt_ PSECURITY_DESCRIPTOR CreatorDescriptor,
            _Out_ PSECURITY_DESCRIPTOR* NewDescriptor,
            _In_opt_ GUID* ObjectType,
            _In_ BOOLEAN IsDirectoryObject,
            _In_ ULONG AutoInheritFlags, // SEF_*
            _In_opt_ HANDLE Token,
            _In_ PGENERIC_MAPPING GenericMapping
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlNewSecurityObjectWithMultipleInheritance(
            _In_opt_ PSECURITY_DESCRIPTOR ParentDescriptor,
            _In_opt_ PSECURITY_DESCRIPTOR CreatorDescriptor,
            _Out_ PSECURITY_DESCRIPTOR* NewDescriptor,
            _In_opt_ GUID** ObjectType,
            _In_ ULONG GuidCount,
            _In_ BOOLEAN IsDirectoryObject,
            _In_ ULONG AutoInheritFlags, // SEF_*
            _In_opt_ HANDLE Token,
            _In_ PGENERIC_MAPPING GenericMapping
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlDeleteSecurityObject(
            _Inout_ PSECURITY_DESCRIPTOR* ObjectDescriptor
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlQuerySecurityObject(
            _In_ PSECURITY_DESCRIPTOR ObjectDescriptor,
            _In_ SECURITY_INFORMATION SecurityInformation,
            _Out_opt_ PSECURITY_DESCRIPTOR ResultantDescriptor,
            _In_ ULONG DescriptorLength,
            _Out_ PULONG ReturnLength
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlSetSecurityObject(
            _In_ SECURITY_INFORMATION SecurityInformation,
            _In_ PSECURITY_DESCRIPTOR ModificationDescriptor,
            _Inout_ PSECURITY_DESCRIPTOR* ObjectsSecurityDescriptor,
            _In_ PGENERIC_MAPPING GenericMapping,
            _In_opt_ HANDLE TokenHandle
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlSetSecurityObjectEx(
            _In_ SECURITY_INFORMATION SecurityInformation,
            _In_ PSECURITY_DESCRIPTOR ModificationDescriptor,
            _Inout_ PSECURITY_DESCRIPTOR* ObjectsSecurityDescriptor,
            _In_ ULONG AutoInheritFlags, // SEF_*
            _In_ PGENERIC_MAPPING GenericMapping,
            _In_opt_ HANDLE TokenHandle
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlConvertToAutoInheritSecurityObject(
            _In_opt_ PSECURITY_DESCRIPTOR ParentDescriptor,
            _In_ PSECURITY_DESCRIPTOR CurrentSecurityDescriptor,
            _Out_ PSECURITY_DESCRIPTOR* NewSecurityDescriptor,
            _In_opt_ GUID* ObjectType,
            _In_ BOOLEAN IsDirectoryObject,
            _In_ PGENERIC_MAPPING GenericMapping
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlNewInstanceSecurityObject(
            _In_ BOOLEAN ParentDescriptorChanged,
            _In_ BOOLEAN CreatorDescriptorChanged,
            _In_ PLUID OldClientTokenModifiedId,
            _Out_ PLUID NewClientTokenModifiedId,
            _In_opt_ PSECURITY_DESCRIPTOR ParentDescriptor,
            _In_opt_ PSECURITY_DESCRIPTOR CreatorDescriptor,
            _Out_ PSECURITY_DESCRIPTOR* NewDescriptor,
            _In_ BOOLEAN IsDirectoryObject,
            _In_ HANDLE TokenHandle,
            _In_ PGENERIC_MAPPING GenericMapping
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlCopySecurityDescriptor(
            _In_ PSECURITY_DESCRIPTOR InputSecurityDescriptor,
            _Out_ PSECURITY_DESCRIPTOR* OutputSecurityDescriptor
        );

    // private
    typedef struct _RTL_ACE_DATA
    {
        UCHAR AceType;
        UCHAR InheritFlags;
        UCHAR AceFlags;
        ACCESS_MASK AccessMask;
        PSID* Sid;
    } RTL_ACE_DATA, * PRTL_ACE_DATA;

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlCreateUserSecurityObject(
            _In_ PRTL_ACE_DATA AceData,
            _In_ ULONG AceCount,
            _In_ PSID OwnerSid,
            _In_ PSID GroupSid,
            _In_ BOOLEAN IsDirectoryObject,
            _In_ PGENERIC_MAPPING GenericMapping,
            _Out_ PSECURITY_DESCRIPTOR* NewSecurityDescriptor
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlCreateAndSetSD(
            _In_ PRTL_ACE_DATA AceData,
            _In_ ULONG AceCount,
            _In_opt_ PSID OwnerSid,
            _In_opt_ PSID GroupSid,
            _Out_ PSECURITY_DESCRIPTOR* NewSecurityDescriptor
        );

    // Misc. security

    NTSYSAPI
        VOID
        NTAPI
        RtlRunEncodeUnicodeString(
            _Inout_ PUCHAR Seed,
            _Inout_ PUNICODE_STRING String
        );

    NTSYSAPI
        VOID
        NTAPI
        RtlRunDecodeUnicodeString(
            _In_ UCHAR Seed,
            _Inout_ PUNICODE_STRING String
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlImpersonateSelf(
            _In_ SECURITY_IMPERSONATION_LEVEL ImpersonationLevel
        );

#if (PHNT_VERSION >= PHNT_VISTA)
    // private
    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlImpersonateSelfEx(
            _In_ SECURITY_IMPERSONATION_LEVEL ImpersonationLevel,
            _In_opt_ ACCESS_MASK AdditionalAccess,
            _Out_opt_ PHANDLE ThreadToken
        );
#endif

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlAdjustPrivilege(
            _In_ ULONG Privilege,
            _In_ BOOLEAN Enable,
            _In_ BOOLEAN Client,
            _Out_ PBOOLEAN WasEnabled
        );

#define RTL_ACQUIRE_PRIVILEGE_REVERT 0x00000001
#define RTL_ACQUIRE_PRIVILEGE_PROCESS 0x00000002

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlAcquirePrivilege(
            _In_ PULONG Privilege,
            _In_ ULONG NumPriv,
            _In_ ULONG Flags,
            _Out_ PVOID* ReturnedState
        );

    NTSYSAPI
        VOID
        NTAPI
        RtlReleasePrivilege(
            _In_ PVOID StatePointer
        );

#if (PHNT_VERSION >= PHNT_VISTA)
    // private
    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlRemovePrivileges(
            _In_ HANDLE TokenHandle,
            _In_ PULONG PrivilegesToKeep,
            _In_ ULONG PrivilegeCount
        );
#endif

#if (PHNT_VERSION >= PHNT_WIN8)

    // rev
    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlIsUntrustedObject(
            _In_opt_ HANDLE Handle,
            _In_opt_ PVOID Object,
            _Out_ PBOOLEAN IsUntrustedObject
        );

    NTSYSAPI
        ULONG
        NTAPI
        RtlQueryValidationRunlevel(
            _In_opt_ PUNICODE_STRING ComponentName
        );

#endif

    // Private namespaces

#if (PHNT_VERSION >= PHNT_VISTA)

// rev
#define BOUNDARY_DESCRIPTOR_ADD_APPCONTAINER_SID 0x0001

// begin_private

    _Ret_maybenull_
        _Success_(return != NULL)
        NTSYSAPI
        POBJECT_BOUNDARY_DESCRIPTOR
        NTAPI
        RtlCreateBoundaryDescriptor(
            _In_ PUNICODE_STRING Name,
            _In_ ULONG Flags
        );

    NTSYSAPI
        VOID
        NTAPI
        RtlDeleteBoundaryDescriptor(
            _In_ _Post_invalid_ POBJECT_BOUNDARY_DESCRIPTOR BoundaryDescriptor
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlAddSIDToBoundaryDescriptor(
            _Inout_ POBJECT_BOUNDARY_DESCRIPTOR* BoundaryDescriptor,
            _In_ PSID RequiredSid
        );

#if (PHNT_VERSION >= PHNT_WIN7)
    // rev
    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlAddIntegrityLabelToBoundaryDescriptor(
            _Inout_ POBJECT_BOUNDARY_DESCRIPTOR* BoundaryDescriptor,
            _In_ PSID IntegrityLabel
        );
#endif

    // end_private

#endif

// Version

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlGetVersion(
            _Out_ PRTL_OSVERSIONINFOEXW VersionInformation // PRTL_OSVERSIONINFOW
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlVerifyVersionInfo(
            _In_ PRTL_OSVERSIONINFOEXW VersionInformation, // PRTL_OSVERSIONINFOW
            _In_ ULONG TypeMask,
            _In_ ULONGLONG ConditionMask
        );

    // rev
    NTSYSAPI
        VOID
        NTAPI
        RtlGetNtVersionNumbers(
            _Out_opt_ PULONG NtMajorVersion,
            _Out_opt_ PULONG NtMinorVersion,
            _Out_opt_ PULONG NtBuildNumber
        );

    // System information

    // rev
    NTSYSAPI
        ULONG
        NTAPI
        RtlGetNtGlobalFlags(
            VOID
        );

    // rev
    NTSYSAPI
        BOOLEAN
        NTAPI
        RtlGetNtProductType(
            _Out_ PNT_PRODUCT_TYPE NtProductType
        );

#if (PHNT_VERSION >= PHNT_REDSTONE)
    // private
    NTSYSAPI
        ULONG
        NTAPI
        RtlGetSuiteMask(
            VOID
        );
#endif

    // Thread pool (old)

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlRegisterWait(
            _Out_ PHANDLE WaitHandle,
            _In_ HANDLE Handle,
            _In_ WAITORTIMERCALLBACKFUNC Function,
            _In_opt_ PVOID Context,
            _In_ ULONG Milliseconds,
            _In_ ULONG Flags
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlDeregisterWait(
            _In_ HANDLE WaitHandle
        );

#define RTL_WAITER_DEREGISTER_WAIT_FOR_COMPLETION ((HANDLE)(LONG_PTR)-1)

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlDeregisterWaitEx(
            _In_ HANDLE WaitHandle,
            _In_opt_ HANDLE CompletionEvent // optional: RTL_WAITER_DEREGISTER_WAIT_FOR_COMPLETION
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlQueueWorkItem(
            _In_ WORKERCALLBACKFUNC Function,
            _In_opt_ PVOID Context,
            _In_ ULONG Flags
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlSetIoCompletionCallback(
            _In_ HANDLE FileHandle,
            _In_ APC_CALLBACK_FUNCTION CompletionProc,
            _In_ ULONG Flags
        );

    _Function_class_(RTL_START_POOL_THREAD)
        typedef NTSTATUS(NTAPI RTL_START_POOL_THREAD)(
            _In_ PTHREAD_START_ROUTINE Function,
            _In_ PVOID Parameter,
            _Out_ PHANDLE ThreadHandle
            );
    typedef RTL_START_POOL_THREAD* PRTL_START_POOL_THREAD;

    _Function_class_(RTL_EXIT_POOL_THREAD)
        typedef NTSTATUS(NTAPI RTL_EXIT_POOL_THREAD)(
            _In_ NTSTATUS ExitStatus
            );
    typedef RTL_EXIT_POOL_THREAD* PRTL_EXIT_POOL_THREAD;

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlSetThreadPoolStartFunc(
            _In_ PRTL_START_POOL_THREAD StartPoolThread,
            _In_ PRTL_EXIT_POOL_THREAD ExitPoolThread
        );

    NTSYSAPI
        VOID
        NTAPI
        RtlUserThreadStart(
            _In_ PTHREAD_START_ROUTINE Function,
            _In_ PVOID Parameter
        );

    NTSYSAPI
        VOID
        NTAPI
        LdrInitializeThunk(
            _In_ PCONTEXT ContextRecord,
            _In_ PVOID Parameter
        );

    // Thread execution

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        RtlDelayExecution(
            _In_ BOOLEAN Alertable,
            _In_opt_ PLARGE_INTEGER DelayInterval
        );

    // Timer support

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlCreateTimerQueue(
            _Out_ PHANDLE TimerQueueHandle
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlCreateTimer(
            _In_ HANDLE TimerQueueHandle,
            _Out_ PHANDLE Handle,
            _In_ WAITORTIMERCALLBACKFUNC Function,
            _In_opt_ PVOID Context,
            _In_ ULONG DueTime,
            _In_ ULONG Period,
            _In_ ULONG Flags
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlSetTimer(
            _In_ HANDLE TimerQueueHandle,
            _Out_ PHANDLE Handle,
            _In_ WAITORTIMERCALLBACKFUNC Function,
            _In_opt_ PVOID Context,
            _In_ ULONG DueTime,
            _In_ ULONG Period,
            _In_ ULONG Flags
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlUpdateTimer(
            _In_ HANDLE TimerQueueHandle,
            _In_ HANDLE TimerHandle,
            _In_ ULONG DueTime,
            _In_ ULONG Period
        );

#define RTL_TIMER_DELETE_WAIT_FOR_COMPLETION ((HANDLE)(LONG_PTR)-1)

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlDeleteTimer(
            _In_ HANDLE TimerQueueHandle,
            _In_ HANDLE TimerToCancel,
            _In_opt_ HANDLE Event // optional: RTL_TIMER_DELETE_WAIT_FOR_COMPLETION
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlDeleteTimerQueue(
            _In_ HANDLE TimerQueueHandle
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlDeleteTimerQueueEx(
            _In_ HANDLE TimerQueueHandle,
            _In_opt_ HANDLE Event
        );

    // Registry access

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlFormatCurrentUserKeyPath(
            _Out_ PUNICODE_STRING CurrentUserKeyPath
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlOpenCurrentUser(
            _In_ ACCESS_MASK DesiredAccess,
            _Out_ PHANDLE CurrentUserKey
        );

#define RTL_REGISTRY_ABSOLUTE 0
#define RTL_REGISTRY_SERVICES 1 // \Registry\Machine\System\CurrentControlSet\Services
#define RTL_REGISTRY_CONTROL 2 // \Registry\Machine\System\CurrentControlSet\Control
#define RTL_REGISTRY_WINDOWS_NT 3 // \Registry\Machine\Software\Microsoft\Windows NT\CurrentVersion
#define RTL_REGISTRY_DEVICEMAP 4 // \Registry\Machine\Hardware\DeviceMap
#define RTL_REGISTRY_USER 5 // \Registry\User\CurrentUser
#define RTL_REGISTRY_MAXIMUM 6
#define RTL_REGISTRY_HANDLE 0x40000000
#define RTL_REGISTRY_OPTIONAL 0x80000000

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlCreateRegistryKey(
            _In_ ULONG RelativeTo,
            _In_ PWSTR Path
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlCheckRegistryKey(
            _In_ ULONG RelativeTo,
            _In_ PWSTR Path
        );

    _Function_class_(RTL_QUERY_REGISTRY_ROUTINE)
        typedef NTSTATUS(NTAPI RTL_QUERY_REGISTRY_ROUTINE)(
            _In_ PWSTR ValueName,
            _In_ ULONG ValueType,
            _In_ PVOID ValueData,
            _In_ ULONG ValueLength,
            _In_opt_ PVOID Context,
            _In_opt_ PVOID EntryContext
            );
    typedef RTL_QUERY_REGISTRY_ROUTINE* PRTL_QUERY_REGISTRY_ROUTINE;

    typedef struct _RTL_QUERY_REGISTRY_TABLE
    {
        PRTL_QUERY_REGISTRY_ROUTINE QueryRoutine;
        ULONG Flags;
        PWSTR Name;
        PVOID EntryContext;
        ULONG DefaultType;
        PVOID DefaultData;
        ULONG DefaultLength;
    } RTL_QUERY_REGISTRY_TABLE, * PRTL_QUERY_REGISTRY_TABLE;

#define RTL_QUERY_REGISTRY_SUBKEY 0x00000001
#define RTL_QUERY_REGISTRY_TOPKEY 0x00000002
#define RTL_QUERY_REGISTRY_REQUIRED 0x00000004
#define RTL_QUERY_REGISTRY_NOVALUE 0x00000008
#define RTL_QUERY_REGISTRY_NOEXPAND 0x00000010
#define RTL_QUERY_REGISTRY_DIRECT 0x00000020
#define RTL_QUERY_REGISTRY_DELETE 0x00000040

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlQueryRegistryValues(
            _In_ ULONG RelativeTo,
            _In_ PCWSTR Path,
            _Inout_ _At_(*(*QueryTable).EntryContext, _Pre_unknown_) PRTL_QUERY_REGISTRY_TABLE QueryTable,
            _In_opt_ PVOID Context,
            _In_opt_ PVOID Environment
        );

#if (PHNT_VERSION >= PHNT_WIN8)
    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlQueryRegistryValuesEx(
            _In_ ULONG RelativeTo,
            _In_ PCWSTR Path,
            _Inout_ _At_(*(*QueryTable).EntryContext, _Pre_unknown_) PRTL_QUERY_REGISTRY_TABLE QueryTable,
            _In_opt_ PVOID Context,
            _In_opt_ PVOID Environment
        );
#endif

#if (PHNT_VERSION >= PHNT_REDSTONE4)
    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlQueryRegistryValueWithFallback(
            _In_opt_ HANDLE PrimaryHandle,
            _In_opt_ HANDLE FallbackHandle,
            _In_ PUNICODE_STRING ValueName,
            _In_ ULONG ValueLength,
            _Out_opt_ PULONG ValueType,
            _Out_writes_bytes_to_(ValueLength, *ResultLength) PVOID ValueData,
            _Out_range_(<= , ValueLength) PULONG ResultLength
        );
#endif

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlWriteRegistryValue(
            _In_ ULONG RelativeTo,
            _In_ PCWSTR Path,
            _In_ PCWSTR ValueName,
            _In_ ULONG ValueType,
            _In_ PVOID ValueData,
            _In_ ULONG ValueLength
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlDeleteRegistryValue(
            _In_ ULONG RelativeTo,
            _In_ PCWSTR Path,
            _In_ PCWSTR ValueName
        );

    // Thread profiling

#if (PHNT_VERSION >= PHNT_WIN7)

// rev
    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlEnableThreadProfiling(
            _In_ HANDLE ThreadHandle,
            _In_ ULONG Flags,
            _In_ ULONG64 HardwareCounters,
            _Out_ PVOID* PerformanceDataHandle
        );

    // rev
    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlDisableThreadProfiling(
            _In_ PVOID PerformanceDataHandle
        );

    // rev
    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlQueryThreadProfiling(
            _In_ HANDLE ThreadHandle,
            _Out_ PBOOLEAN Enabled
        );

    // rev
    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlReadThreadProfilingData(
            _In_ HANDLE PerformanceDataHandle,
            _In_ ULONG Flags,
            _Out_ PPERFORMANCE_DATA PerformanceData
        );

#endif

    // WOW64

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlGetNativeSystemInformation(
            _In_ ULONG SystemInformationClass,
            _In_ PVOID NativeSystemInformation,
            _In_ ULONG InformationLength,
            _Out_opt_ PULONG ReturnLength
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlQueueApcWow64Thread(
            _In_ HANDLE ThreadHandle,
            _In_ PPS_APC_ROUTINE ApcRoutine,
            _In_opt_ PVOID ApcArgument1,
            _In_opt_ PVOID ApcArgument2,
            _In_opt_ PVOID ApcArgument3
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlWow64EnableFsRedirection(
            _In_ BOOLEAN Wow64FsEnableRedirection
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlWow64EnableFsRedirectionEx(
            _In_ PVOID Wow64FsEnableRedirection,
            _Out_ PVOID* OldFsRedirectionLevel
        );

    // Misc.

    NTSYSAPI
        ULONG32
        NTAPI
        RtlComputeCrc32(
            _In_ ULONG32 PartialCrc,
            _In_ PVOID Buffer,
            _In_ ULONG Length
        );

    NTSYSAPI
        PVOID
        NTAPI
        RtlEncodePointer(
            _In_ PVOID Ptr
        );

    NTSYSAPI
        PVOID
        NTAPI
        RtlDecodePointer(
            _In_ PVOID Ptr
        );

    NTSYSAPI
        PVOID
        NTAPI
        RtlEncodeSystemPointer(
            _In_ PVOID Ptr
        );

    NTSYSAPI
        PVOID
        NTAPI
        RtlDecodeSystemPointer(
            _In_ PVOID Ptr
        );

#if (PHNT_VERSION >= PHNT_THRESHOLD)
    // rev
    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlEncodeRemotePointer(
            _In_ HANDLE ProcessHandle,
            _In_ PVOID Pointer,
            _Out_ PVOID* EncodedPointer
        );

    // rev
    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlDecodeRemotePointer(
            _In_ HANDLE ProcessHandle,
            _In_ PVOID Pointer,
            _Out_ PVOID* DecodedPointer
        );
#endif

#if (PHNT_VERSION >= PHNT_THRESHOLD)

    // rev
    NTSYSAPI
        BOOLEAN
        NTAPI
        RtlIsProcessorFeaturePresent(
            _In_ ULONG ProcessorFeature
        );

#endif

    // rev
    NTSYSAPI
        ULONG
        NTAPI
        RtlGetCurrentProcessorNumber(
            VOID
        );

#if (PHNT_VERSION >= PHNT_WIN7)

    // rev
    NTSYSAPI
        VOID
        NTAPI
        RtlGetCurrentProcessorNumberEx(
            _Out_ PPROCESSOR_NUMBER ProcessorNumber
        );

#endif

    // Stack support

    NTSYSAPI
        VOID
        NTAPI
        RtlPushFrame(
            _In_ PTEB_ACTIVE_FRAME Frame
        );

    NTSYSAPI
        VOID
        NTAPI
        RtlPopFrame(
            _In_ PTEB_ACTIVE_FRAME Frame
        );

    NTSYSAPI
        PTEB_ACTIVE_FRAME
        NTAPI
        RtlGetFrame(
            VOID
        );

#define RTL_WALK_USER_MODE_STACK 0x00000001
#define RTL_WALK_VALID_FLAGS 0x00000001
#define RTL_STACK_WALKING_MODE_FRAMES_TO_SKIP_SHIFT 0x00000008

    // private
    NTSYSAPI
        ULONG
        NTAPI
        RtlWalkFrameChain(
            _Out_writes_(Count - (Flags >> RTL_STACK_WALKING_MODE_FRAMES_TO_SKIP_SHIFT)) PVOID* Callers,
            _In_ ULONG Count,
            _In_ ULONG Flags
        );

    // rev
    NTSYSAPI
        VOID
        NTAPI
        RtlGetCallersAddress( // Use the intrinsic _ReturnAddress instead.
            _Out_ PVOID* CallersAddress,
            _Out_ PVOID* CallersCaller
        );

#if (PHNT_VERSION >= PHNT_WIN7)

    NTSYSAPI
        ULONG64
        NTAPI
        RtlGetEnabledExtendedFeatures(
            _In_ ULONG64 FeatureMask
        );

#endif

#if (PHNT_VERSION >= PHNT_REDSTONE4)

    // msdn
    NTSYSAPI
        ULONG64
        NTAPI
        RtlGetEnabledExtendedAndSupervisorFeatures(
            _In_ ULONG64 FeatureMask
        );

    // msdn
    _Ret_maybenull_
        _Success_(return != NULL)
        NTSYSAPI
        PVOID
        NTAPI
        RtlLocateSupervisorFeature(
            _In_ PXSAVE_AREA_HEADER XStateHeader,
            _In_range_(XSTATE_AVX, MAXIMUM_XSTATE_FEATURES - 1) ULONG FeatureId,
            _Out_opt_ PULONG Length
        );

#endif

    // private
    typedef union _RTL_ELEVATION_FLAGS
    {
        ULONG Flags;
        struct
        {
            ULONG ElevationEnabled : 1;
            ULONG VirtualizationEnabled : 1;
            ULONG InstallerDetectEnabled : 1;
            ULONG ReservedBits : 29;
        };
    } RTL_ELEVATION_FLAGS, * PRTL_ELEVATION_FLAGS;

#if (PHNT_VERSION >= PHNT_VISTA)

    // private
    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlQueryElevationFlags(
            _Out_ PRTL_ELEVATION_FLAGS Flags
        );

#endif

#if (PHNT_VERSION >= PHNT_VISTA)

    // private
    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlRegisterThreadWithCsrss(
            VOID
        );

#endif

#if (PHNT_VERSION >= PHNT_VISTA)

    // private
    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlLockCurrentThread(
            VOID
        );

#endif

#if (PHNT_VERSION >= PHNT_VISTA)

    // private
    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlUnlockCurrentThread(
            VOID
        );

#endif

#if (PHNT_VERSION >= PHNT_VISTA)

    // private
    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlLockModuleSection(
            _In_ PVOID Address
        );

#endif

#if (PHNT_VERSION >= PHNT_VISTA)

    // private
    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlUnlockModuleSection(
            _In_ PVOID Address
        );

#endif

    // begin_msdn:"Winternl"

#define RTL_UNLOAD_EVENT_TRACE_NUMBER 64

// private
    typedef struct _RTL_UNLOAD_EVENT_TRACE
    {
        PVOID BaseAddress;
        SIZE_T SizeOfImage;
        ULONG Sequence;
        ULONG TimeDateStamp;
        ULONG CheckSum;
        WCHAR ImageName[32];
        ULONG Version[2];
    } RTL_UNLOAD_EVENT_TRACE, * PRTL_UNLOAD_EVENT_TRACE;

    typedef struct _RTL_UNLOAD_EVENT_TRACE32
    {
        ULONG BaseAddress;
        ULONG SizeOfImage;
        ULONG Sequence;
        ULONG TimeDateStamp;
        ULONG CheckSum;
        WCHAR ImageName[32];
        ULONG Version[2];
    } RTL_UNLOAD_EVENT_TRACE32, * PRTL_UNLOAD_EVENT_TRACE32;

    NTSYSAPI
        PRTL_UNLOAD_EVENT_TRACE
        NTAPI
        RtlGetUnloadEventTrace(
            VOID
        );

#if (PHNT_VERSION >= PHNT_VISTA)
    NTSYSAPI
        VOID
        NTAPI
        RtlGetUnloadEventTraceEx(
            _Out_ PULONG* ElementSize,
            _Out_ PULONG* ElementCount,
            _Out_ PVOID* EventTrace // works across all processes
        );
#endif

    // end_msdn

#if (PHNT_VERSION >= PHNT_WIN7)
// rev
    NTSYSAPI
        LOGICAL
        NTAPI
        RtlQueryPerformanceCounter(
            _Out_ PLARGE_INTEGER PerformanceCounter
        );

    // rev
    NTSYSAPI
        LOGICAL
        NTAPI
        RtlQueryPerformanceFrequency(
            _Out_ PLARGE_INTEGER PerformanceFrequency
        );
#endif

    // Image Mitigation

    // rev
    typedef enum _IMAGE_MITIGATION_POLICY
    {
        ImageDepPolicy, // RTL_IMAGE_MITIGATION_DEP_POLICY
        ImageAslrPolicy, // RTL_IMAGE_MITIGATION_ASLR_POLICY
        ImageDynamicCodePolicy, // RTL_IMAGE_MITIGATION_DYNAMIC_CODE_POLICY
        ImageStrictHandleCheckPolicy, // RTL_IMAGE_MITIGATION_STRICT_HANDLE_CHECK_POLICY
        ImageSystemCallDisablePolicy, // RTL_IMAGE_MITIGATION_SYSTEM_CALL_DISABLE_POLICY
        ImageMitigationOptionsMask,
        ImageExtensionPointDisablePolicy, // RTL_IMAGE_MITIGATION_EXTENSION_POINT_DISABLE_POLICY
        ImageControlFlowGuardPolicy, // RTL_IMAGE_MITIGATION_CONTROL_FLOW_GUARD_POLICY
        ImageSignaturePolicy, // RTL_IMAGE_MITIGATION_BINARY_SIGNATURE_POLICY
        ImageFontDisablePolicy, // RTL_IMAGE_MITIGATION_FONT_DISABLE_POLICY
        ImageImageLoadPolicy, // RTL_IMAGE_MITIGATION_IMAGE_LOAD_POLICY
        ImagePayloadRestrictionPolicy, // RTL_IMAGE_MITIGATION_PAYLOAD_RESTRICTION_POLICY
        ImageChildProcessPolicy, // RTL_IMAGE_MITIGATION_CHILD_PROCESS_POLICY
        ImageSehopPolicy, // RTL_IMAGE_MITIGATION_SEHOP_POLICY
        ImageHeapPolicy, // RTL_IMAGE_MITIGATION_HEAP_POLICY
        ImageUserShadowStackPolicy, // RTL_IMAGE_MITIGATION_USER_SHADOW_STACK_POLICY
        ImageRedirectionTrustPolicy, // RTL_IMAGE_MITIGATION_REDIRECTION_TRUST_POLICY
        ImageUserPointerAuthPolicy, // RTL_IMAGE_MITIGATION_USER_POINTER_AUTH_POLICY
        MaxImageMitigationPolicy
    } IMAGE_MITIGATION_POLICY;

    // rev
    typedef union _RTL_IMAGE_MITIGATION_POLICY
    {
        struct
        {
            ULONG64 AuditState : 2;
            ULONG64 AuditFlag : 1;
            ULONG64 EnableAdditionalAuditingOption : 1;
            ULONG64 Reserved : 60;
        };
        struct
        {
            ULONG64 PolicyState : 2;
            ULONG64 AlwaysInherit : 1;
            ULONG64 EnableAdditionalPolicyOption : 1;
            ULONG64 AuditReserved : 60;
        };
    } RTL_IMAGE_MITIGATION_POLICY, * PRTL_IMAGE_MITIGATION_POLICY;

    // rev
    typedef struct _RTL_IMAGE_MITIGATION_DEP_POLICY
    {
        RTL_IMAGE_MITIGATION_POLICY Dep;
    } RTL_IMAGE_MITIGATION_DEP_POLICY, * PRTL_IMAGE_MITIGATION_DEP_POLICY;

    // rev
    typedef struct _RTL_IMAGE_MITIGATION_ASLR_POLICY
    {
        RTL_IMAGE_MITIGATION_POLICY ForceRelocateImages;
        RTL_IMAGE_MITIGATION_POLICY BottomUpRandomization;
        RTL_IMAGE_MITIGATION_POLICY HighEntropyRandomization;
    } RTL_IMAGE_MITIGATION_ASLR_POLICY, * PRTL_IMAGE_MITIGATION_ASLR_POLICY;

    // rev
    typedef struct _RTL_IMAGE_MITIGATION_DYNAMIC_CODE_POLICY
    {
        RTL_IMAGE_MITIGATION_POLICY BlockDynamicCode;
    } RTL_IMAGE_MITIGATION_DYNAMIC_CODE_POLICY, * PRTL_IMAGE_MITIGATION_DYNAMIC_CODE_POLICY;

    // rev
    typedef struct _RTL_IMAGE_MITIGATION_STRICT_HANDLE_CHECK_POLICY
    {
        RTL_IMAGE_MITIGATION_POLICY StrictHandleChecks;
    } RTL_IMAGE_MITIGATION_STRICT_HANDLE_CHECK_POLICY, * PRTL_IMAGE_MITIGATION_STRICT_HANDLE_CHECK_POLICY;

    // rev
    typedef struct _RTL_IMAGE_MITIGATION_SYSTEM_CALL_DISABLE_POLICY
    {
        RTL_IMAGE_MITIGATION_POLICY BlockWin32kSystemCalls;
    } RTL_IMAGE_MITIGATION_SYSTEM_CALL_DISABLE_POLICY, * PRTL_IMAGE_MITIGATION_SYSTEM_CALL_DISABLE_POLICY;

    // rev
    typedef struct _RTL_IMAGE_MITIGATION_EXTENSION_POINT_DISABLE_POLICY
    {
        RTL_IMAGE_MITIGATION_POLICY DisableExtensionPoints;
    } RTL_IMAGE_MITIGATION_EXTENSION_POINT_DISABLE_POLICY, * PRTL_IMAGE_MITIGATION_EXTENSION_POINT_DISABLE_POLICY;

    // rev
    typedef struct _RTL_IMAGE_MITIGATION_CONTROL_FLOW_GUARD_POLICY
    {
        RTL_IMAGE_MITIGATION_POLICY ControlFlowGuard;
        RTL_IMAGE_MITIGATION_POLICY StrictControlFlowGuard;
    } RTL_IMAGE_MITIGATION_CONTROL_FLOW_GUARD_POLICY, * PRTL_IMAGE_MITIGATION_CONTROL_FLOW_GUARD_POLICY;

    // rev
    typedef struct _RTL_IMAGE_MITIGATION_BINARY_SIGNATURE_POLICY
    {
        RTL_IMAGE_MITIGATION_POLICY BlockNonMicrosoftSignedBinaries;
        RTL_IMAGE_MITIGATION_POLICY EnforceSigningOnModuleDependencies;
    } RTL_IMAGE_MITIGATION_BINARY_SIGNATURE_POLICY, * PRTL_IMAGE_MITIGATION_BINARY_SIGNATURE_POLICY;

    // rev
    typedef struct _RTL_IMAGE_MITIGATION_FONT_DISABLE_POLICY
    {
        RTL_IMAGE_MITIGATION_POLICY DisableNonSystemFonts;
    } RTL_IMAGE_MITIGATION_FONT_DISABLE_POLICY, * PRTL_IMAGE_MITIGATION_FONT_DISABLE_POLICY;

    // rev
    typedef struct _RTL_IMAGE_MITIGATION_IMAGE_LOAD_POLICY
    {
        RTL_IMAGE_MITIGATION_POLICY BlockRemoteImageLoads;
        RTL_IMAGE_MITIGATION_POLICY BlockLowLabelImageLoads;
        RTL_IMAGE_MITIGATION_POLICY PreferSystem32;
    } RTL_IMAGE_MITIGATION_IMAGE_LOAD_POLICY, * PRTL_IMAGE_MITIGATION_IMAGE_LOAD_POLICY;

    // rev
    typedef struct _RTL_IMAGE_MITIGATION_PAYLOAD_RESTRICTION_POLICY
    {
        RTL_IMAGE_MITIGATION_POLICY EnableExportAddressFilter;
        RTL_IMAGE_MITIGATION_POLICY EnableExportAddressFilterPlus;
        RTL_IMAGE_MITIGATION_POLICY EnableImportAddressFilter;
        RTL_IMAGE_MITIGATION_POLICY EnableRopStackPivot;
        RTL_IMAGE_MITIGATION_POLICY EnableRopCallerCheck;
        RTL_IMAGE_MITIGATION_POLICY EnableRopSimExec;
        WCHAR EafPlusModuleList[512]; // 19H1
    } RTL_IMAGE_MITIGATION_PAYLOAD_RESTRICTION_POLICY, * PRTL_IMAGE_MITIGATION_PAYLOAD_RESTRICTION_POLICY;

    // rev
    typedef struct _RTL_IMAGE_MITIGATION_CHILD_PROCESS_POLICY
    {
        RTL_IMAGE_MITIGATION_POLICY DisallowChildProcessCreation;
    } RTL_IMAGE_MITIGATION_CHILD_PROCESS_POLICY, * PRTL_IMAGE_MITIGATION_CHILD_PROCESS_POLICY;

    // rev
    typedef struct _RTL_IMAGE_MITIGATION_SEHOP_POLICY
    {
        RTL_IMAGE_MITIGATION_POLICY Sehop;
    } RTL_IMAGE_MITIGATION_SEHOP_POLICY, * PRTL_IMAGE_MITIGATION_SEHOP_POLICY;

    // rev
    typedef struct _RTL_IMAGE_MITIGATION_HEAP_POLICY
    {
        RTL_IMAGE_MITIGATION_POLICY TerminateOnHeapErrors;
    } RTL_IMAGE_MITIGATION_HEAP_POLICY, * PRTL_IMAGE_MITIGATION_HEAP_POLICY;

    // rev
    typedef struct _RTL_IMAGE_MITIGATION_USER_SHADOW_STACK_POLICY
    {
        RTL_IMAGE_MITIGATION_POLICY UserShadowStack;
        RTL_IMAGE_MITIGATION_POLICY SetContextIpValidation;
        RTL_IMAGE_MITIGATION_POLICY BlockNonCetBinaries;
    } RTL_IMAGE_MITIGATION_USER_SHADOW_STACK_POLICY, * PRTL_IMAGE_MITIGATION_USER_SHADOW_STACK_POLICY;

    // rev
    typedef struct _RTL_IMAGE_MITIGATION_REDIRECTION_TRUST_POLICY
    {
        RTL_IMAGE_MITIGATION_POLICY BlockUntrustedRedirections;
    } RTL_IMAGE_MITIGATION_REDIRECTION_TRUST_POLICY, * PRTL_IMAGE_MITIGATION_REDIRECTION_TRUST_POLICY;

    // rev
    typedef struct _RTL_IMAGE_MITIGATION_USER_POINTER_AUTH_POLICY
    {
        RTL_IMAGE_MITIGATION_POLICY PointerAuthUserIp;
    } RTL_IMAGE_MITIGATION_USER_POINTER_AUTH_POLICY, * PRTL_IMAGE_MITIGATION_USER_POINTER_AUTH_POLICY;

    // rev
    typedef enum _RTL_IMAGE_MITIGATION_OPTION_STATE
    {
        RtlMitigationOptionStateNotConfigured,
        RtlMitigationOptionStateOn,
        RtlMitigationOptionStateOff,
        RtlMitigationOptionStateForce,
        RtlMitigationOptionStateOption
    } RTL_IMAGE_MITIGATION_OPTION_STATE;

#define RTL_IMAGE_MITIGATION_OPTION_STATEMASK 3UL
#define RTL_IMAGE_MITIGATION_OPTION_FORCEMASK 4UL
#define RTL_IMAGE_MITIGATION_OPTION_OPTIONMASK 8UL

    // rev from PROCESS_MITIGATION_FLAGS
#define RTL_IMAGE_MITIGATION_FLAG_RESET 0x1
#define RTL_IMAGE_MITIGATION_FLAG_REMOVE 0x2
#define RTL_IMAGE_MITIGATION_FLAG_OSDEFAULT 0x4
#define RTL_IMAGE_MITIGATION_FLAG_AUDIT 0x8

#if (PHNT_VERSION >= PHNT_REDSTONE3)

// rev
    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlQueryImageMitigationPolicy(
            _In_opt_ PWSTR ImagePath, // NULL for system-wide defaults
            _In_ IMAGE_MITIGATION_POLICY Policy,
            _In_ ULONG Flags,
            _Inout_ PVOID Buffer,
            _In_ ULONG BufferSize
        );

    // rev
    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlSetImageMitigationPolicy(
            _In_opt_ PWSTR ImagePath, // NULL for system-wide defaults
            _In_ IMAGE_MITIGATION_POLICY Policy,
            _In_ ULONG Flags,
            _Inout_ PVOID Buffer,
            _In_ ULONG BufferSize
        );

#endif

    // session

    // rev
    NTSYSAPI
        ULONG
        NTAPI
        RtlGetCurrentServiceSessionId(
            VOID
        );

    // private
    NTSYSAPI
        ULONG
        NTAPI
        RtlGetActiveConsoleId(
            VOID
        );

#if (PHNT_VERSION >= PHNT_REDSTONE)
    // private
    NTSYSAPI
        ULONGLONG
        NTAPI
        RtlGetConsoleSessionForegroundProcessId(
            VOID
        );
#endif

    // Appcontainer

#if (PHNT_VERSION >= PHNT_REDSTONE2)
// rev
    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlGetTokenNamedObjectPath(
            _In_ HANDLE TokenHandle,
            _In_opt_ PSID Sid,
            _Out_ PUNICODE_STRING ObjectPath // RtlFreeUnicodeString
        );
#endif

#if (PHNT_VERSION >= PHNT_WIN8)
    // rev
    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlGetAppContainerNamedObjectPath(
            _In_opt_ HANDLE TokenHandle,
            _In_opt_ PSID AppContainerSid,
            _In_ BOOLEAN RelativePath,
            _Out_ PUNICODE_STRING ObjectPath // RtlFreeUnicodeString
        );
#endif

#if (PHNT_VERSION >= PHNT_WINBLUE)
    // rev
    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlGetAppContainerParent(
            _In_ PSID AppContainerSid,
            _Out_ PSID* AppContainerSidParent // RtlFreeSid
        );
#endif

#if (PHNT_VERSION >= PHNT_THRESHOLD)
    // rev
    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlCheckSandboxedToken(
            _In_opt_ HANDLE TokenHandle,
            _Out_ PBOOLEAN IsSandboxed
        );
#endif

#if (PHNT_VERSION >= PHNT_WIN8)
    // rev
    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlCheckTokenCapability(
            _In_opt_ HANDLE TokenHandle,
            _In_ PSID CapabilitySidToCheck,
            _Out_ PBOOLEAN HasCapability
        );
#endif

#if (PHNT_VERSION >= PHNT_THRESHOLD)
    // rev
    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlCapabilityCheck(
            _In_opt_ HANDLE TokenHandle,
            _In_ PUNICODE_STRING CapabilityName,
            _Out_ PBOOLEAN HasCapability
        );
#endif

#if (PHNT_VERSION >= PHNT_WIN8)
    // rev
    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlCheckTokenMembership(
            _In_opt_ HANDLE TokenHandle,
            _In_ PSID SidToCheck,
            _Out_ PBOOLEAN IsMember
        );

    // rev
    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlCheckTokenMembershipEx(
            _In_opt_ HANDLE TokenHandle,
            _In_ PSID SidToCheck,
            _In_ ULONG Flags, // CTMF_VALID_FLAGS
            _Out_ PBOOLEAN IsMember
        );
#endif

#if (PHNT_VERSION >= PHNT_REDSTONE4)
    // rev
    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlQueryTokenHostIdAsUlong64(
            _In_ HANDLE TokenHandle,
            _Out_ PULONG64 HostId // (WIN://PKGHOSTID)
        );
#endif

#if (PHNT_VERSION >= PHNT_WINBLUE)
    // rev
    NTSYSAPI
        BOOLEAN
        NTAPI
        RtlIsParentOfChildAppContainer(
            _In_ PSID ParentAppContainerSid,
            _In_ PSID ChildAppContainerSid
        );
#endif

#if (PHNT_VERSION >= PHNT_WIN11)
    // rev
    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlIsApiSetImplemented(
            _In_ PCSTR ApiSetName
        );
#endif

#if (PHNT_VERSION >= PHNT_WIN8)
    // rev
    NTSYSAPI
        BOOLEAN
        NTAPI
        RtlIsCapabilitySid(
            _In_ PSID Sid
        );

    // rev
    NTSYSAPI
        BOOLEAN
        NTAPI
        RtlIsPackageSid(
            _In_ PSID Sid
        );
#endif

#if (PHNT_VERSION >= PHNT_WINBLUE)
    // rev
    NTSYSAPI
        BOOLEAN
        NTAPI
        RtlIsValidProcessTrustLabelSid(
            _In_ PSID Sid
        );
#endif

    typedef enum _APPCONTAINER_SID_TYPE
    {
        NotAppContainerSidType,
        ChildAppContainerSidType,
        ParentAppContainerSidType,
        InvalidAppContainerSidType,
        MaxAppContainerSidType
    } APPCONTAINER_SID_TYPE, * PAPPCONTAINER_SID_TYPE;

#if (PHNT_VERSION >= PHNT_WINBLUE)
    // rev
    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlGetAppContainerSidType(
            _In_ PSID AppContainerSid,
            _Out_ PAPPCONTAINER_SID_TYPE AppContainerSidType
        );
#endif

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlFlsAlloc(
            _In_ PFLS_CALLBACK_FUNCTION Callback,
            _Out_ PULONG FlsIndex
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlFlsFree(
            _In_ ULONG FlsIndex
        );

#if (PHNT_VERSION >= PHNT_20H1)
    NTSYSAPI
        NTSTATUS
        WINAPI
        RtlFlsGetValue(
            _In_ ULONG FlsIndex,
            _Out_ PVOID* FlsData
        );

    NTSYSAPI
        NTSTATUS
        WINAPI
        RtlFlsSetValue(
            _In_ ULONG FlsIndex,
            _In_ PVOID FlsData
        );
#endif

    // State isolation

    typedef enum _STATE_LOCATION_TYPE
    {
        LocationTypeRegistry,
        LocationTypeFileSystem,
        LocationTypeMaximum
    } STATE_LOCATION_TYPE;

#if (PHNT_VERSION >= PHNT_REDSTONE3)
    // private
    NTSYSAPI
        BOOLEAN
        NTAPI
        RtlIsStateSeparationEnabled(
            VOID
        );

    // private
    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlGetPersistedStateLocation(
            _In_ PCWSTR SourceID,
            _In_opt_ PCWSTR CustomValue,
            _In_opt_ PCWSTR DefaultPath,
            _In_ STATE_LOCATION_TYPE StateLocationType,
            _Out_writes_bytes_to_opt_(BufferLengthIn, *BufferLengthOut) PWCHAR TargetPath,
            _In_ ULONG BufferLengthIn,
            _Out_opt_ PULONG BufferLengthOut
        );
#endif

    // Cloud Filters

#if (PHNT_VERSION >= PHNT_REDSTONE3)
// msdn
    NTSYSAPI
        BOOLEAN
        NTAPI
        RtlIsCloudFilesPlaceholder(
            _In_ ULONG FileAttributes,
            _In_ ULONG ReparseTag
        );

    // msdn
    NTSYSAPI
        BOOLEAN
        NTAPI
        RtlIsPartialPlaceholder(
            _In_ ULONG FileAttributes,
            _In_ ULONG ReparseTag
        );

    // msdn
    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlIsPartialPlaceholderFileHandle(
            _In_ HANDLE FileHandle,
            _Out_ PBOOLEAN IsPartialPlaceholder
        );

    // msdn
    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlIsPartialPlaceholderFileInfo(
            _In_ PVOID InfoBuffer,
            _In_ FILE_INFORMATION_CLASS InfoClass,
            _Out_ PBOOLEAN IsPartialPlaceholder
        );

#undef PHCM_MAX
#define PHCM_APPLICATION_DEFAULT ((CHAR)0)
#define PHCM_DISGUISE_PLACEHOLDERS ((CHAR)1)
#define PHCM_EXPOSE_PLACEHOLDERS ((CHAR)2)
#define PHCM_MAX ((CHAR)2)

#define PHCM_ERROR_INVALID_PARAMETER ((CHAR)-1)
#define PHCM_ERROR_NO_TEB ((CHAR)-2)

    NTSYSAPI
        CHAR
        NTAPI
        RtlQueryThreadPlaceholderCompatibilityMode(
            VOID
        );

    NTSYSAPI
        CHAR
        NTAPI
        RtlSetThreadPlaceholderCompatibilityMode(
            _In_ CHAR Mode
        );
#endif

#if (PHNT_VERSION >= PHNT_REDSTONE4)

#undef PHCM_MAX
#define PHCM_DISGUISE_FULL_PLACEHOLDERS ((CHAR)3)
#define PHCM_MAX ((CHAR)3)
#define PHCM_ERROR_NO_PEB ((CHAR)-3)

    NTSYSAPI
        CHAR
        NTAPI
        RtlQueryProcessPlaceholderCompatibilityMode(
            VOID
        );

    NTSYSAPI
        CHAR
        NTAPI
        RtlSetProcessPlaceholderCompatibilityMode(
            _In_ CHAR Mode
        );

#endif

#if (PHNT_VERSION >= PHNT_REDSTONE2)
    // rev
    NTSYSAPI
        BOOLEAN
        NTAPI
        RtlIsNonEmptyDirectoryReparsePointAllowed(
            _In_ ULONG ReparseTag
        );
#endif

#if (PHNT_VERSION >= PHNT_WIN8)
    // rev
    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlAppxIsFileOwnedByTrustedInstaller(
            _In_ HANDLE FileHandle,
            _Out_ PBOOLEAN IsFileOwnedByTrustedInstaller
        );
#endif

    // Windows Internals book
#define PSM_ACTIVATION_TOKEN_PACKAGED_APPLICATION 0x1
#define PSM_ACTIVATION_TOKEN_SHARED_ENTITY 0x2
#define PSM_ACTIVATION_TOKEN_FULL_TRUST 0x4
#define PSM_ACTIVATION_TOKEN_NATIVE_SERVICE 0x8
#define PSM_ACTIVATION_TOKEN_DEVELOPMENT_APP 0x10
#define PSM_ACTIVATION_TOKEN_BREAKAWAY_INHIBITED 0x20
#define PSM_ACTIVATION_TOKEN_RUNTIME_BROKER 0x40 // rev
#define PSM_ACTIVATION_TOKEN_UNIVERSAL_CONSOLE 0x200 // rev
#define PSM_ACTIVATION_TOKEN_WIN32ALACARTE_PROCESS 0x10000 // rev

// PackageOrigin appmodel.h
//#define PackageOrigin_Unknown 0
//#define PackageOrigin_Unsigned 1
//#define PackageOrigin_Inbox 2
//#define PackageOrigin_Store 3
//#define PackageOrigin_DeveloperUnsigned 4
//#define PackageOrigin_DeveloperSigned 5
//#define PackageOrigin_LineOfBusiness 6

#define PSMP_MINIMUM_SYSAPP_CLAIM_VALUES 2
#define PSMP_MAXIMUM_SYSAPP_CLAIM_VALUES 4

// private
    typedef struct _PS_PKG_CLAIM
    {
        ULONG Flags;  // PSM_ACTIVATION_TOKEN_*
        ULONG Origin; // PackageOrigin
    } PS_PKG_CLAIM, * PPS_PKG_CLAIM;

#if (PHNT_VERSION >= PHNT_THRESHOLD)
    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlQueryPackageClaims(
            _In_ HANDLE TokenHandle,
            _Out_writes_bytes_to_opt_(*PackageSize, *PackageSize) PWSTR PackageFullName,
            _Inout_opt_ PSIZE_T PackageSize,
            _Out_writes_bytes_to_opt_(*AppIdSize, *AppIdSize) PWSTR AppId,
            _Inout_opt_ PSIZE_T AppIdSize,
            _Out_opt_ PGUID DynamicId,
            _Out_opt_ PPS_PKG_CLAIM PkgClaim,
            _Out_opt_ PULONG64 AttributesPresent
        );
#endif

#if (PHNT_VERSION >= PHNT_WIN8)
    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlQueryPackageIdentity(
            _In_ HANDLE TokenHandle,
            _Out_writes_bytes_to_(*PackageSize, *PackageSize) PWSTR PackageFullName,
            _Inout_ PSIZE_T PackageSize,
            _Out_writes_bytes_to_opt_(*AppIdSize, *AppIdSize) PWSTR AppId,
            _Inout_opt_ PSIZE_T AppIdSize,
            _Out_opt_ PBOOLEAN Packaged
        );
#endif

#if (PHNT_VERSION >= PHNT_WINBLUE)
    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlQueryPackageIdentityEx(
            _In_ HANDLE TokenHandle,
            _Out_writes_bytes_to_(*PackageSize, *PackageSize) PWSTR PackageFullName,
            _Inout_ PSIZE_T PackageSize,
            _Out_writes_bytes_to_opt_(*AppIdSize, *AppIdSize) PWSTR AppId,
            _Inout_opt_ PSIZE_T AppIdSize,
            _Out_opt_ PGUID DynamicId,
            _Out_opt_ PULONG64 Flags
        );
#endif

    // Protected policies

#if (PHNT_VERSION >= PHNT_WINBLUE)
// rev
    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlQueryProtectedPolicy(
            _In_ PGUID PolicyGuid,
            _Out_ PULONG_PTR PolicyValue
        );

    // rev
    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlSetProtectedPolicy(
            _In_ PGUID PolicyGuid,
            _In_ ULONG_PTR PolicyValue,
            _Out_ PULONG_PTR OldPolicyValue
        );
#endif

#if (PHNT_VERSION >= PHNT_REDSTONE)
    // rev
    NTSYSAPI
        BOOLEAN
        NTAPI
        RtlIsEnclaveFeaturePresent(
            _In_ ULONG FeatureMask
        );
#endif

#if (PHNT_VERSION >= PHNT_THRESHOLD)
    // private
    NTSYSAPI
        BOOLEAN
        NTAPI
        RtlIsMultiSessionSku(
            VOID
        );
#endif

#if (PHNT_VERSION >= PHNT_REDSTONE)
    // private
    NTSYSAPI
        BOOLEAN
        NTAPI
        RtlIsMultiUsersInSessionSku(
            VOID
        );
#endif

#if (PHNT_VERSION >= PHNT_WIN11)
    // rev
    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlGetSessionProperties(
            _In_ ULONG SessionId,
            _Out_ PULONG SharedUserSessionId
        );
#endif

    // private
    typedef enum _RTL_BSD_ITEM_TYPE
    {
        RtlBsdItemVersionNumber, // q; s: ULONG
        RtlBsdItemProductType, // q; s: NT_PRODUCT_TYPE (ULONG)
        RtlBsdItemAabEnabled, // q: s: BOOLEAN // AutoAdvancedBoot
        RtlBsdItemAabTimeout, // q: s: UCHAR // AdvancedBootMenuTimeout
        RtlBsdItemBootGood, // q: s: BOOLEAN // LastBootSucceeded
        RtlBsdItemBootShutdown, // q: s: BOOLEAN // LastBootShutdown
        RtlBsdSleepInProgress, // q: s: BOOLEAN // SleepInProgress
        RtlBsdPowerTransition, // q: s: RTL_BSD_DATA_POWER_TRANSITION
        RtlBsdItemBootAttemptCount, // q: s: UCHAR // BootAttemptCount
        RtlBsdItemBootCheckpoint, // q: s: UCHAR // LastBootCheckpoint
        RtlBsdItemBootId, // q; s: ULONG (USER_SHARED_DATA->BootId)
        RtlBsdItemShutdownBootId, // q; s: ULONG
        RtlBsdItemReportedAbnormalShutdownBootId, // q; s: ULONG
        RtlBsdItemErrorInfo, // RTL_BSD_DATA_ERROR_INFO
        RtlBsdItemPowerButtonPressInfo, // RTL_BSD_POWER_BUTTON_PRESS_INFO
        RtlBsdItemChecksum, // q: s: UCHAR
        RtlBsdPowerTransitionExtension,
        RtlBsdItemFeatureConfigurationState, // q; s: ULONG
        RtlBsdItemMax
    } RTL_BSD_ITEM_TYPE;

    // ros
    typedef struct _RTL_BSD_DATA_POWER_TRANSITION
    {
        LARGE_INTEGER PowerButtonTimestamp;
        struct
        {
            BOOLEAN SystemRunning : 1;
            BOOLEAN ConnectedStandbyInProgress : 1;
            BOOLEAN UserShutdownInProgress : 1;
            BOOLEAN SystemShutdownInProgress : 1;
            BOOLEAN SleepInProgress : 4;
        } Flags;
        UCHAR ConnectedStandbyScenarioInstanceId;
        UCHAR ConnectedStandbyEntryReason;
        UCHAR ConnectedStandbyExitReason;
        USHORT SystemSleepTransitionCount;
        LARGE_INTEGER LastReferenceTime;
        ULONG LastReferenceTimeChecksum;
        ULONG LastUpdateBootId;
    } RTL_BSD_DATA_POWER_TRANSITION, * PRTL_BSD_DATA_POWER_TRANSITION;

    // ros
    typedef struct _RTL_BSD_DATA_ERROR_INFO
    {
        ULONG BootId;
        ULONG RepeatCount;
        ULONG OtherErrorCount;
        ULONG Code;
        ULONG OtherErrorCount2;
    } RTL_BSD_DATA_ERROR_INFO, * PRTL_BSD_DATA_ERROR_INFO;

    // ros
    typedef struct _RTL_BSD_POWER_BUTTON_PRESS_INFO
    {
        LARGE_INTEGER LastPressTime;
        ULONG CumulativePressCount;
        USHORT LastPressBootId;
        UCHAR LastPowerWatchdogStage;
        struct
        {
            UCHAR WatchdogArmed : 1;
            UCHAR ShutdownInProgress : 1;
        } Flags;
        LARGE_INTEGER LastReleaseTime;
        ULONG CumulativeReleaseCount;
        USHORT LastReleaseBootId;
        USHORT ErrorCount;
        UCHAR CurrentConnectedStandbyPhase;
        ULONG TransitionLatestCheckpointId;
        ULONG TransitionLatestCheckpointType;
        ULONG TransitionLatestCheckpointSequenceNumber;
    } RTL_BSD_POWER_BUTTON_PRESS_INFO, * PRTL_BSD_POWER_BUTTON_PRESS_INFO;

    // private
    typedef struct _RTL_BSD_ITEM
    {
        RTL_BSD_ITEM_TYPE Type;
        PVOID DataBuffer;
        ULONG DataLength;
    } RTL_BSD_ITEM, * PRTL_BSD_ITEM;

    // ros
    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlCreateBootStatusDataFile(
            VOID
        );

    // ros
    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlLockBootStatusData(
            _Out_ PHANDLE FileHandle
        );

    // ros
    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlUnlockBootStatusData(
            _In_ HANDLE FileHandle
        );

    // ros
    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlGetSetBootStatusData(
            _In_ HANDLE FileHandle,
            _In_ BOOLEAN Read,
            _In_ RTL_BSD_ITEM_TYPE DataClass,
            _In_ PVOID Buffer,
            _In_ ULONG BufferSize,
            _Out_opt_ PULONG ReturnLength
        );

#if (PHNT_VERSION >= PHNT_REDSTONE)
    // rev
    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlCheckBootStatusIntegrity(
            _In_ HANDLE FileHandle,
            _Out_ PBOOLEAN Verified
        );

    // rev
    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlRestoreBootStatusDefaults(
            _In_ HANDLE FileHandle
        );
#endif

#if (PHNT_VERSION >= PHNT_REDSTONE3)
    // rev
    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlRestoreSystemBootStatusDefaults(
            VOID
        );

    // rev
    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlGetSystemBootStatus(
            _In_ RTL_BSD_ITEM_TYPE BootStatusInformationClass,
            _Out_ PVOID DataBuffer,
            _In_ ULONG DataLength,
            _Out_opt_ PULONG ReturnLength
        );

    // rev
    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlSetSystemBootStatus(
            _In_ RTL_BSD_ITEM_TYPE BootStatusInformationClass,
            _In_ PVOID DataBuffer,
            _In_ ULONG DataLength,
            _Out_opt_ PULONG ReturnLength
        );
#endif

#if (PHNT_VERSION >= PHNT_WIN8)
    // rev
    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlCheckPortableOperatingSystem(
            _Out_ PBOOLEAN IsPortable // VOID
        );

    // rev
    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlSetPortableOperatingSystem(
            _In_ BOOLEAN IsPortable
        );

    // rev
    NTSYSAPI
        ULONG
        NTAPI
        RtlSetProxiedProcessId(
            _In_ ULONG ProxiedProcessId
        );
#endif

#if (PHNT_VERSION >= PHNT_VISTA)

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlFindClosestEncodableLength(
            _In_ ULONGLONG SourceLength,
            _Out_ PULONGLONG TargetLength
        );

#endif

    // Memory cache

    _Function_class_(RTL_SECURE_MEMORY_CACHE_CALLBACK)
        typedef NTSTATUS(NTAPI RTL_SECURE_MEMORY_CACHE_CALLBACK)(
            _In_ PVOID Address,
            _In_ SIZE_T Length
            );
    typedef RTL_SECURE_MEMORY_CACHE_CALLBACK* PRTL_SECURE_MEMORY_CACHE_CALLBACK;

    // ros
    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlRegisterSecureMemoryCacheCallback(
            _In_ PRTL_SECURE_MEMORY_CACHE_CALLBACK Callback
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlDeregisterSecureMemoryCacheCallback(
            _In_ PRTL_SECURE_MEMORY_CACHE_CALLBACK Callback
        );

    // ros
    NTSYSAPI
        BOOLEAN
        NTAPI
        RtlFlushSecureMemoryCache(
            _In_ PVOID MemoryCache,
            _In_opt_ SIZE_T MemoryLength
        );

#if (PHNT_VERSION >= PHNT_20H1)

    // Feature configuration

    typedef struct __RTL_FEATURE_USAGE_REPORT
    {
        ULONG FeatureId;
        USHORT ReportingKind;
        USHORT ReportingOptions;
    } RTL_FEATURE_USAGE_REPORT, * PRTL_FEATURE_USAGE_REPORT;

    // rev
    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlNotifyFeatureUsage(
            _In_ PRTL_FEATURE_USAGE_REPORT FeatureUsageReport
        );

    typedef enum _RTL_FEATURE_CONFIGURATION_TYPE
    {
        RtlFeatureConfigurationBoot,
        RtlFeatureConfigurationRuntime,
        RtlFeatureConfigurationCount
    } RTL_FEATURE_CONFIGURATION_TYPE;

    // rev
    typedef struct _RTL_FEATURE_CONFIGURATION
    {
        ULONG FeatureId;
        union
        {
            ULONG Flags;
            struct
            {
                ULONG Priority : 4;
                ULONG EnabledState : 2;
                ULONG IsWexpConfiguration : 1;
                ULONG HasSubscriptions : 1;
                ULONG Variant : 6;
                ULONG VariantPayloadKind : 2;
                ULONG Reserved : 16;
            };
        };
        ULONG VariantPayload;
    } RTL_FEATURE_CONFIGURATION, * PRTL_FEATURE_CONFIGURATION;

    // rev
    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlQueryFeatureConfiguration(
            _In_ ULONG FeatureId,
            _In_ RTL_FEATURE_CONFIGURATION_TYPE FeatureType,
            _Inout_ PULONGLONG ChangeStamp,
            _In_ PRTL_FEATURE_CONFIGURATION FeatureConfiguration
        );

    // rev
    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlSetFeatureConfigurations(
            _Inout_ PULONGLONG ChangeStamp,
            _In_ RTL_FEATURE_CONFIGURATION_TYPE FeatureType,
            _In_ PRTL_FEATURE_CONFIGURATION FeatureConfiguration,
            _In_ ULONG FeatureConfigurationCount
        );

    // rev
    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlQueryAllFeatureConfigurations(
            _In_ RTL_FEATURE_CONFIGURATION_TYPE FeatureType,
            _Inout_ PULONGLONG ChangeStamp,
            _Out_ PRTL_FEATURE_CONFIGURATION FeatureConfigurations,
            _Inout_ PULONG FeatureConfigurationCount
        );

    // rev
    NTSYSAPI
        ULONGLONG
        NTAPI
        RtlQueryFeatureConfigurationChangeStamp(
            VOID
        );

    // rev
    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlQueryFeatureUsageNotificationSubscriptions(
            _Out_ PRTL_FEATURE_CONFIGURATION FeatureConfiguration,
            _Inout_ PULONG FeatureConfigurationCount
        );

    _Function_class_(RTL_FEATURE_CONFIGURATION_CHANGE_NOTIFICATION)
        typedef VOID(NTAPI RTL_FEATURE_CONFIGURATION_CHANGE_NOTIFICATION)(
            _In_opt_ PVOID Context
            );
    typedef RTL_FEATURE_CONFIGURATION_CHANGE_NOTIFICATION* PRTL_FEATURE_CONFIGURATION_CHANGE_NOTIFICATION;

    // rev
    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlRegisterFeatureConfigurationChangeNotification(
            _In_ PRTL_FEATURE_CONFIGURATION_CHANGE_NOTIFICATION Callback,
            _In_opt_ PVOID Context,
            _Inout_opt_ PULONGLONG ChangeStamp,
            _Out_ PHANDLE NotificationHandle
        );

    // rev
    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlUnregisterFeatureConfigurationChangeNotification(
            _In_ HANDLE NotificationHandle
        );

    // rev
    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlSubscribeForFeatureUsageNotification(
            _In_ PRTL_FEATURE_CONFIGURATION FeatureConfiguration,
            _In_ ULONG FeatureConfigurationCount
        );

    // rev
    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlUnsubscribeFromFeatureUsageNotifications(
            _In_ PRTL_FEATURE_CONFIGURATION FeatureConfiguration,
            _In_ ULONG FeatureConfigurationCount
        );
#endif

#if (PHNT_VERSION >= PHNT_VISTA)

#ifndef _RTL_RUN_ONCE_DEF
#define _RTL_RUN_ONCE_DEF
    //
    // Run once initializer
    //
#define RTL_RUN_ONCE_INIT {0}
//
// Run once flags
//
#define RTL_RUN_ONCE_CHECK_ONLY     0x00000001UL
#define RTL_RUN_ONCE_ASYNC          0x00000002UL
#define RTL_RUN_ONCE_INIT_FAILED    0x00000004UL
//
// The context stored in the run once structure must
// leave the following number of low order bits unused.
//
#define RTL_RUN_ONCE_CTX_RESERVED_BITS 2

    typedef union _RTL_RUN_ONCE
    {
        PVOID Ptr;
    } RTL_RUN_ONCE, * PRTL_RUN_ONCE;
#endif

    NTSYSAPI
        VOID
        NTAPI
        RtlRunOnceInitialize(
            _Out_ PRTL_RUN_ONCE RunOnce
        );

    typedef _Function_class_(RTL_RUN_ONCE_INIT_FN)
        LOGICAL NTAPI RTL_RUN_ONCE_INIT_FN(
            _Inout_ PRTL_RUN_ONCE RunOnce,
            _Inout_opt_ PVOID Parameter,
            _Inout_opt_ PVOID* Context
        );
    typedef RTL_RUN_ONCE_INIT_FN* PRTL_RUN_ONCE_INIT_FN;

    _Maybe_raises_SEH_exception_
        NTSYSAPI
        NTSTATUS
        NTAPI
        RtlRunOnceExecuteOnce(
            _Inout_ PRTL_RUN_ONCE RunOnce,
            _In_ __callback PRTL_RUN_ONCE_INIT_FN InitFn,
            _Inout_opt_ PVOID Parameter,
            _Outptr_opt_result_maybenull_ PVOID* Context
        );

    _Must_inspect_result_
        NTSYSAPI
        NTSTATUS
        NTAPI
        RtlRunOnceBeginInitialize(
            _Inout_ PRTL_RUN_ONCE RunOnce,
            _In_ ULONG Flags,
            _Outptr_opt_result_maybenull_ PVOID* Context
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlRunOnceComplete(
            _Inout_ PRTL_RUN_ONCE RunOnce,
            _In_ ULONG Flags,
            _In_opt_ PVOID Context
        );

#endif

#if (PHNT_VERSION >= PHNT_THRESHOLD)

#define WNF_STATE_KEY 0x41C64E6DA3BC0074

    _Must_inspect_result_
        NTSYSAPI
        BOOLEAN
        NTAPI
        RtlEqualWnfChangeStamps(
            _In_ WNF_CHANGE_STAMP ChangeStamp1,
            _In_ WNF_CHANGE_STAMP ChangeStamp2
        );

    _Always_(_Post_satisfies_(return == STATUS_NO_MEMORY || return == STATUS_RETRY || return == STATUS_SUCCESS))
        typedef _Function_class_(WNF_USER_CALLBACK)
        NTSTATUS NTAPI WNF_USER_CALLBACK(
            _In_ WNF_STATE_NAME StateName,
            _In_ WNF_CHANGE_STAMP ChangeStamp,
            _In_opt_ PWNF_TYPE_ID TypeId,
            _In_opt_ PVOID CallbackContext,
            _In_reads_bytes_opt_(Length) const VOID* Buffer,
            _In_ ULONG Length
        );
    typedef WNF_USER_CALLBACK* PWNF_USER_CALLBACK;

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlQueryWnfStateData(
            _Out_ PWNF_CHANGE_STAMP ChangeStamp,
            _In_ WNF_STATE_NAME StateName,
            _In_ PWNF_USER_CALLBACK Callback,
            _In_opt_ PVOID CallbackContext,
            _In_opt_ PWNF_TYPE_ID TypeId
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlPublishWnfStateData(
            _In_ WNF_STATE_NAME StateName,
            _In_opt_ PCWNF_TYPE_ID TypeId,
            _In_reads_bytes_opt_(Length) const VOID* Buffer,
            _In_opt_ ULONG Length,
            _In_opt_ const VOID* ExplicitScope
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlSubscribeWnfStateChangeNotification(
            _Outptr_ PVOID* SubscriptionHandle, // PWNF_USER_SUBSCRIPTION
            _In_ WNF_STATE_NAME StateName,
            _In_ WNF_CHANGE_STAMP ChangeStamp,
            _In_ PWNF_USER_CALLBACK Callback,
            _In_opt_ PVOID CallbackContext,
            _In_opt_ PCWNF_TYPE_ID TypeId,
            _In_opt_ ULONG SerializationGroup,
            _Reserved_ ULONG Flags
        );

    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlUnsubscribeWnfStateChangeNotification(
            _In_ PWNF_USER_CALLBACK Callback
        );

#endif

#if (PHNT_VERSION >= PHNT_WIN11)

    NTSYSAPI
        NTSTATUS
        NTAPI
        NtCopyFileChunk(
            _In_ HANDLE SourceHandle,
            _In_ HANDLE DestinationHandle,
            _In_opt_ HANDLE EventHandle,
            _Out_ PIO_STATUS_BLOCK IoStatusBlock,
            _In_ ULONG Length,
            _In_ PLARGE_INTEGER SourceOffset,
            _In_ PLARGE_INTEGER DestOffset,
            _In_opt_ PGUID SourceKey,
            _In_opt_ PGUID DestKey,
            _In_ ULONG Flags
        );

#endif

#if (PHNT_VERSION >= PHNT_WIN11)
    // rev
    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlQueryPropertyStore(
            _In_ ULONG_PTR Key,
            _Out_ PULONG_PTR Context
        );

    // rev
    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlRemovePropertyStore(
            _In_ ULONG_PTR Key,
            _Out_ PULONG_PTR Context
        );

    // rev
    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlCompareExchangePropertyStore(
            _In_ ULONG_PTR Key,
            _In_ PULONG_PTR Comperand,
            _In_opt_ PULONG_PTR Exchange,
            _Out_ PULONG_PTR Context
        );
#endif

#if (PHNT_VERSION >= PHNT_WIN11)
    typedef enum _THREAD_STATE_CHANGE_TYPE THREAD_STATE_CHANGE_TYPE, * PTHREAD_STATE_CHANGE_TYPE;

    // rev
    NTSYSAPI
        NTSTATUS
        NTAPI
        RtlWow64ChangeThreadState(
            _In_ HANDLE ThreadStateChangeHandle,
            _In_ HANDLE ThreadHandle,
            _In_ THREAD_STATE_CHANGE_TYPE StateChangeType,
            _In_opt_ PVOID ExtendedInformation,
            _In_opt_ SIZE_T ExtendedInformationLength,
            _In_opt_ ULONG64 Reserved
        );
#endif

#endif // _NTRTL_H

    /*
     * RTL forward symbol typedefs
     *
     * This file is part of System Informer.
     */
#ifndef _NTRTL_FWD_H
#define _NTRTL_FWD_H

     // begin_forwarders
#ifndef PHNT_INLINE_NAME_FORWARDERS
#define RtlGetNativeSystemInformation NtQuerySystemInformation
#define RtlGetTickCount NtGetTickCount
#define RtlGuardRestoreContext RtlRestoreContext
#define RtlRandom RtlRandomEx
#define RtlOpenImageFileOptionsKey LdrOpenImageFileOptionsKey
#define RtlQueryImageFileExecutionOptions LdrQueryImageFileExecutionOptionsEx
#define RtlQueryImageFileKeyOption LdrQueryImageFileKeyOption
#define RtlSetTimer RtlCreateTimer
#define RtlRestoreLastWin32Error RtlSetLastWin32Error
#endif

#ifndef PHNT_INLINE_FREE_FORWARDERS
//#define RtlFreeUnicodeString(UnicodeString) {if ((UnicodeString)->Buffer) RtlFreeHeap(RtlProcessHeap(), 0, (UnicodeString)->Buffer); memset(UnicodeString, 0, sizeof(UNICODE_STRING));}
    FORCEINLINE
        VOID
        RtlFreeUnicodeString(
            _Inout_ _At_(UnicodeString->Buffer, _Frees_ptr_opt_) PUNICODE_STRING UnicodeString
        )
    {
        if (UnicodeString->Buffer)
        {
            RtlFreeHeap(RtlProcessHeap(), 0, UnicodeString->Buffer);
            memset(UnicodeString, 0, sizeof(UNICODE_STRING));
        }
    }

    //#define RtlFreeAnsiString(UnicodeString) {if ((AnsiString)->Buffer) RtlFreeHeap(RtlProcessHeap(), 0, (AnsiString)->Buffer); memset(AnsiString, 0, sizeof(ANSI_STRING));}
    FORCEINLINE
        VOID
        RtlFreeAnsiString(
            _Inout_ _At_(AnsiString->Buffer, _Frees_ptr_opt_) PANSI_STRING AnsiString
        )
    {
        if (AnsiString->Buffer)
        {
            RtlFreeHeap(RtlProcessHeap(), 0, AnsiString->Buffer);
            memset(AnsiString, 0, sizeof(ANSI_STRING));
        }
    }

    //#define RtlFreeUTF8String(Utf8String) {if ((Utf8String)->Buffer) RtlFreeHeap(RtlProcessHeap(), 0, (Utf8String)->Buffer); memset(Utf8String, 0, sizeof(UTF8_STRING));}
    FORCEINLINE
        VOID
        RtlFreeUTF8String(
            _Inout_ _At_(Utf8String->Buffer, _Frees_ptr_opt_) PUTF8_STRING Utf8String
        )
    {
        if (Utf8String->Buffer)
        {
            RtlFreeHeap(RtlProcessHeap(), 0, Utf8String->Buffer);
            memset(Utf8String, 0, sizeof(UTF8_STRING));
        }
    }

    //#define RtlFreeSid(Sid) RtlFreeHeap(RtlProcessHeap(), 0, (Sid))
    FORCEINLINE
        PVOID
        RtlFreeSid(
            _In_ _Post_invalid_ PSID Sid
        )
    {
        RtlFreeHeap(RtlProcessHeap(), 0, Sid);
        return NULL;
    }

    //#define RtlDeleteBoundaryDescriptor(BoundaryDescriptor) RtlFreeHeap(RtlProcessHeap(), 0, (BoundaryDescriptor))
    FORCEINLINE
        VOID
        RtlDeleteBoundaryDescriptor(
            _In_ _Post_invalid_ POBJECT_BOUNDARY_DESCRIPTOR BoundaryDescriptor
        )
    {
        RtlFreeHeap(RtlProcessHeap(), 0, BoundaryDescriptor);
    }

    //#define RtlDeleteSecurityObject(ObjectDescriptor) RtlFreeHeap(RtlProcessHeap(), 0, *(ObjectDescriptor))
    //FORCEINLINE
    //NTSTATUS
    //RtlDeleteSecurityObject(
    //    _Inout_ PSECURITY_DESCRIPTOR *ObjectDescriptor
    //    )
    //{
    //    RtlFreeHeap(RtlProcessHeap(), 0, *ObjectDescriptor);
    //    return STATUS_SUCCESS;
    //}

    //#define RtlDestroyEnvironment(Environment) RtlFreeHeap(RtlProcessHeap(), 0, (Environment))
    FORCEINLINE
        NTSTATUS
        RtlDestroyEnvironment(
            _In_ _Post_invalid_ PVOID Environment
        )
    {
        RtlFreeHeap(RtlProcessHeap(), 0, Environment);
        return STATUS_SUCCESS;
    }

    //#define RtlDestroyProcessParameters(ProcessParameters) RtlFreeHeap(RtlProcessHeap(), 0, (ProcessParameters))
    FORCEINLINE
        NTSTATUS
        RtlDestroyProcessParameters(
            _In_ _Post_invalid_ PRTL_USER_PROCESS_PARAMETERS ProcessParameters
        )
    {
        RtlFreeHeap(RtlProcessHeap(), 0, ProcessParameters);
        return STATUS_SUCCESS;
    }
#endif
    // end_forwarders

#endif // _NTRTL_FWD_H
/*
 * PE format support
 *
 * This file is part of System Informer.
 */

#ifndef _NTIMAGE_H
#define _NTIMAGE_H

#include <pshpack4.h>

#ifndef IMAGE_FILE_MACHINE_CHPE_X86
#define IMAGE_FILE_MACHINE_CHPE_X86 0x3A64
#endif

    typedef struct _IMAGE_DEBUG_POGO_ENTRY
    {
        ULONG Rva;
        ULONG Size;
        CHAR Name[1];
    } IMAGE_DEBUG_POGO_ENTRY, * PIMAGE_DEBUG_POGO_ENTRY;

    typedef struct _IMAGE_DEBUG_POGO_SIGNATURE
    {
        ULONG Signature;
    } IMAGE_DEBUG_POGO_SIGNATURE, * PIMAGE_DEBUG_POGO_SIGNATURE;

#define IMAGE_DEBUG_POGO_SIGNATURE_LTCG 'LTCG' // coffgrp LTCG (0x4C544347)
#define IMAGE_DEBUG_POGO_SIGNATURE_PGU 'PGU\0' // coffgrp PGU (0x50475500)

    typedef struct _IMAGE_RELOCATION_RECORD
    {
        USHORT Offset : 12;
        USHORT Type : 4;
    } IMAGE_RELOCATION_RECORD, * PIMAGE_RELOCATION_RECORD;

    typedef struct _IMAGE_CHPE_METADATA_X86
    {
        ULONG Version;
        ULONG CHPECodeAddressRangeOffset;
        ULONG CHPECodeAddressRangeCount;
        ULONG WowA64ExceptionHandlerFunctionPointer;
        ULONG WowA64DispatchCallFunctionPointer;
        ULONG WowA64DispatchIndirectCallFunctionPointer;
        ULONG WowA64DispatchIndirectCallCfgFunctionPointer;
        ULONG WowA64DispatchRetFunctionPointer;
        ULONG WowA64DispatchRetLeafFunctionPointer;
        ULONG WowA64DispatchJumpFunctionPointer;
        ULONG CompilerIATPointer;         // Present if Version >= 2
        ULONG WowA64RdtscFunctionPointer; // Present if Version >= 3
    } IMAGE_CHPE_METADATA_X86, * PIMAGE_CHPE_METADATA_X86;

    typedef struct _IMAGE_CHPE_RANGE_ENTRY
    {
        union
        {
            ULONG StartOffset;
            struct
            {
                ULONG NativeCode : 1;
                ULONG AddressBits : 31;
            } DUMMYSTRUCTNAME;
        } DUMMYUNIONNAME;

        ULONG Length;
    } IMAGE_CHPE_RANGE_ENTRY, * PIMAGE_CHPE_RANGE_ENTRY;

    typedef struct _IMAGE_ARM64EC_METADATA
    {
        ULONG Version;
        ULONG CodeMap;
        ULONG CodeMapCount;
        ULONG CodeRangesToEntryPoints;
        ULONG RedirectionMetadata;
        ULONG tbd__os_arm64x_dispatch_call_no_redirect;
        ULONG tbd__os_arm64x_dispatch_ret;
        ULONG tbd__os_arm64x_dispatch_call;
        ULONG tbd__os_arm64x_dispatch_icall;
        ULONG tbd__os_arm64x_dispatch_icall_cfg;
        ULONG AlternateEntryPoint;
        ULONG AuxiliaryIAT;
        ULONG CodeRangesToEntryPointsCount;
        ULONG RedirectionMetadataCount;
        ULONG GetX64InformationFunctionPointer;
        ULONG SetX64InformationFunctionPointer;
        ULONG ExtraRFETable;
        ULONG ExtraRFETableSize;
        ULONG __os_arm64x_dispatch_fptr;
        ULONG AuxiliaryIATCopy;
    } IMAGE_ARM64EC_METADATA, * PIMAGE_ARM64EC_METADATA;

    typedef struct _IMAGE_ARM64EC_REDIRECTION_ENTRY
    {
        ULONG Source;
        ULONG Destination;
    } IMAGE_ARM64EC_REDIRECTION_ENTRY, * PIMAGE_ARM64EC_REDIRECTION_ENTRY;

    typedef struct _IMAGE_ARM64EC_CODE_RANGE_ENTRY_POINT
    {
        ULONG StartRva;
        ULONG EndRva;
        ULONG EntryPoint;
    } IMAGE_ARM64EC_CODE_RANGE_ENTRY_POINT, * PIMAGE_ARM64EC_CODE_RANGE_ENTRY_POINT;

#define IMAGE_DVRT_ARM64X_FIXUP_TYPE_ZEROFILL   0
#define IMAGE_DVRT_ARM64X_FIXUP_TYPE_VALUE      1
#define IMAGE_DVRT_ARM64X_FIXUP_TYPE_DELTA      2

#define IMAGE_DVRT_ARM64X_FIXUP_SIZE_2BYTES     1
#define IMAGE_DVRT_ARM64X_FIXUP_SIZE_4BYTES     2
#define IMAGE_DVRT_ARM64X_FIXUP_SIZE_8BYTES     3

    typedef struct _IMAGE_DVRT_ARM64X_FIXUP_RECORD
    {
        USHORT Offset : 12;
        USHORT Type : 2;
        USHORT Size : 2;
        // Value of variable Size when IMAGE_DVRT_ARM64X_FIXUP_TYPE_VALUE
    } IMAGE_DVRT_ARM64X_FIXUP_RECORD, * PIMAGE_DVRT_ARM64X_FIXUP_RECORD;

    typedef struct _IMAGE_DVRT_ARM64X_DELTA_FIXUP_RECORD
    {
        USHORT Offset : 12;
        USHORT Type : 2; // IMAGE_DVRT_ARM64X_FIXUP_TYPE_DELTA
        USHORT Sign : 1; // 1 = -, 0 = +
        USHORT Scale : 1; // 1 = 8, 0 = 4
        // USHORT Value; // Delta = Value * Scale * Sign
    } IMAGE_DVRT_ARM64X_DELTA_FIXUP_RECORD, * PIMAGE_DVRT_ARM64X_DELTA_FIXUP_RECORD;

#include <poppack.h>

#define IMAGE_DYNAMIC_RELOCATION_ARM64X                         0x00000006
#define IMAGE_DYNAMIC_RELOCATION_MM_SHARED_USER_DATA_VA         0x7FFE0000
#define IMAGE_DYNAMIC_RELOCATION_KI_USER_SHARED_DATA64          0xFFFFF78000000000UI64

    // Note: The Windows SDK defines UNALIGNED for PIMAGE_IMPORT_DESCRIPTOR but
    // doesn't include UNALIGNED for PIMAGE_THUNK_DATA (See GH#1694) (dmex)
    typedef IMAGE_THUNK_DATA32 UNALIGNED* UNALIGNED_PIMAGE_THUNK_DATA32;
    typedef IMAGE_THUNK_DATA64 UNALIGNED* UNALIGNED_PIMAGE_THUNK_DATA64;

    // Note: Required for legacy SDK support (dmex)
#if !defined(NTDDI_WIN10_NI) || (NTDDI_VERSION < NTDDI_WIN10_NI)
#define IMAGE_DYNAMIC_RELOCATION_GUARD_RF_PROLOGUE   0x00000001
#define IMAGE_DYNAMIC_RELOCATION_GUARD_RF_EPILOGUE   0x00000002
#define IMAGE_DYNAMIC_RELOCATION_GUARD_IMPORT_CONTROL_TRANSFER  0x00000003
#define IMAGE_DYNAMIC_RELOCATION_GUARD_INDIR_CONTROL_TRANSFER   0x00000004
#define IMAGE_DYNAMIC_RELOCATION_GUARD_SWITCHTABLE_BRANCH       0x00000005
#define IMAGE_DYNAMIC_RELOCATION_FUNCTION_OVERRIDE              0x00000007

    typedef struct _IMAGE_FUNCTION_OVERRIDE_HEADER {
        ULONG FuncOverrideSize;
        // IMAGE_FUNCTION_OVERRIDE_DYNAMIC_RELOCATION  FuncOverrideInfo[ANYSIZE_ARRAY]; // FuncOverrideSize bytes in size
        // IMAGE_BDD_INFO BDDInfo; // BDD region, size in bytes: DVRTEntrySize - sizeof(IMAGE_FUNCTION_OVERRIDE_HEADER) - FuncOverrideSize
    } IMAGE_FUNCTION_OVERRIDE_HEADER;
    typedef IMAGE_FUNCTION_OVERRIDE_HEADER UNALIGNED* PIMAGE_FUNCTION_OVERRIDE_HEADER;

    typedef struct _IMAGE_BDD_INFO {
        ULONG Version; // decides the semantics of serialized BDD
        ULONG BDDSize;
        // IMAGE_BDD_DYNAMIC_RELOCATION BDDNodes[ANYSIZE_ARRAY]; // BDDSize size in bytes.
    } IMAGE_BDD_INFO, * PIMAGE_BDD_INFO;

    typedef struct _IMAGE_FUNCTION_OVERRIDE_DYNAMIC_RELOCATION {
        ULONG OriginalRva;          // RVA of original function
        ULONG BDDOffset;            // Offset into the BDD region
        ULONG RvaSize;              // Size in bytes taken by RVAs. Must be multiple of sizeof(DWORD).
        ULONG BaseRelocSize;        // Size in bytes taken by BaseRelocs
        // DWORD RVAs[RvaSize / sizeof(DWORD)];     // Array containing overriding func RVAs.
        // IMAGE_BASE_RELOCATION  BaseRelocs[ANYSIZE_ARRAY];
        // ^Base relocations (RVA + Size + TO)
        // ^Padded with extra TOs for 4B alignment
        // ^BaseRelocSize size in bytes
    } IMAGE_FUNCTION_OVERRIDE_DYNAMIC_RELOCATION, * PIMAGE_FUNCTION_OVERRIDE_DYNAMIC_RELOCATION;

    typedef struct _IMAGE_BDD_DYNAMIC_RELOCATION {
        USHORT Left;  // Index of FALSE edge in BDD array
        USHORT Right; // Index of TRUE edge in BDD array
        ULONG  Value; // Either FeatureNumber or Index into RVAs array
    } IMAGE_BDD_DYNAMIC_RELOCATION, * PIMAGE_BDD_DYNAMIC_RELOCATION;

    // Function override relocation types in DVRT records.
#define IMAGE_FUNCTION_OVERRIDE_INVALID         0
#define IMAGE_FUNCTION_OVERRIDE_X64_REL32       1  // 32-bit relative address from byte following reloc
#define IMAGE_FUNCTION_OVERRIDE_ARM64_BRANCH26  2  // 26 bit offset << 2 & sign ext. for B & BL
#define IMAGE_FUNCTION_OVERRIDE_ARM64_THUNK     3
#endif

#endif
#endif

#if (PHNT_MODE != PHNT_MODE_KERNEL)

/*
 * Authorization functions
 *
 * This file is part of System Informer.
 */

#ifndef _NTSEAPI_H
#define _NTSEAPI_H

 // Privileges

#define SE_MIN_WELL_KNOWN_PRIVILEGE (2L)
#define SE_CREATE_TOKEN_PRIVILEGE (2L)
#define SE_ASSIGNPRIMARYTOKEN_PRIVILEGE (3L)
#define SE_LOCK_MEMORY_PRIVILEGE (4L)
#define SE_INCREASE_QUOTA_PRIVILEGE (5L)

#define SE_MACHINE_ACCOUNT_PRIVILEGE (6L)
#define SE_TCB_PRIVILEGE (7L)
#define SE_SECURITY_PRIVILEGE (8L)
#define SE_TAKE_OWNERSHIP_PRIVILEGE (9L)
#define SE_LOAD_DRIVER_PRIVILEGE (10L)
#define SE_SYSTEM_PROFILE_PRIVILEGE (11L)
#define SE_SYSTEMTIME_PRIVILEGE (12L)
#define SE_PROF_SINGLE_PROCESS_PRIVILEGE (13L)
#define SE_INC_BASE_PRIORITY_PRIVILEGE (14L)
#define SE_CREATE_PAGEFILE_PRIVILEGE (15L)
#define SE_CREATE_PERMANENT_PRIVILEGE (16L)
#define SE_BACKUP_PRIVILEGE (17L)
#define SE_RESTORE_PRIVILEGE (18L)
#define SE_SHUTDOWN_PRIVILEGE (19L)
#define SE_DEBUG_PRIVILEGE (20L)
#define SE_AUDIT_PRIVILEGE (21L)
#define SE_SYSTEM_ENVIRONMENT_PRIVILEGE (22L)
#define SE_CHANGE_NOTIFY_PRIVILEGE (23L)
#define SE_REMOTE_SHUTDOWN_PRIVILEGE (24L)
#define SE_UNDOCK_PRIVILEGE (25L)
#define SE_SYNC_AGENT_PRIVILEGE (26L)
#define SE_ENABLE_DELEGATION_PRIVILEGE (27L)
#define SE_MANAGE_VOLUME_PRIVILEGE (28L)
#define SE_IMPERSONATE_PRIVILEGE (29L)
#define SE_CREATE_GLOBAL_PRIVILEGE (30L)
#define SE_TRUSTED_CREDMAN_ACCESS_PRIVILEGE (31L)
#define SE_RELABEL_PRIVILEGE (32L)
#define SE_INC_WORKING_SET_PRIVILEGE (33L)
#define SE_TIME_ZONE_PRIVILEGE (34L)
#define SE_CREATE_SYMBOLIC_LINK_PRIVILEGE (35L)
#define SE_DELEGATE_SESSION_USER_IMPERSONATE_PRIVILEGE (36L)
#define SE_MAX_WELL_KNOWN_PRIVILEGE SE_DELEGATE_SESSION_USER_IMPERSONATE_PRIVILEGE

// Authz

// begin_rev

#if (PHNT_MODE == PHNT_MODE_KERNEL)
    typedef enum _TOKEN_INFORMATION_CLASS
    {
        TokenUser = 1, // q: TOKEN_USER, SE_TOKEN_USER
        TokenGroups, // q: TOKEN_GROUPS
        TokenPrivileges, // q: TOKEN_PRIVILEGES
        TokenOwner, // q; s: TOKEN_OWNER
        TokenPrimaryGroup, // q; s: TOKEN_PRIMARY_GROUP
        TokenDefaultDacl, // q; s: TOKEN_DEFAULT_DACL
        TokenSource, // q: TOKEN_SOURCE
        TokenType, // q: TOKEN_TYPE
        TokenImpersonationLevel, // q: SECURITY_IMPERSONATION_LEVEL
        TokenStatistics, // q: TOKEN_STATISTICS // 10
        TokenRestrictedSids, // q: TOKEN_GROUPS
        TokenSessionId, // q; s: ULONG (requires SeTcbPrivilege)
        TokenGroupsAndPrivileges, // q: TOKEN_GROUPS_AND_PRIVILEGES
        TokenSessionReference, // s: ULONG (requires SeTcbPrivilege)
        TokenSandBoxInert, // q: ULONG
        TokenAuditPolicy, // q; s: TOKEN_AUDIT_POLICY (requires SeSecurityPrivilege/SeTcbPrivilege)
        TokenOrigin, // q; s: TOKEN_ORIGIN (requires SeTcbPrivilege)
        TokenElevationType, // q: TOKEN_ELEVATION_TYPE
        TokenLinkedToken, // q; s: TOKEN_LINKED_TOKEN (requires SeCreateTokenPrivilege)
        TokenElevation, // q: TOKEN_ELEVATION // 20
        TokenHasRestrictions, // q: ULONG
        TokenAccessInformation, // q: TOKEN_ACCESS_INFORMATION
        TokenVirtualizationAllowed, // q; s: ULONG (requires SeCreateTokenPrivilege)
        TokenVirtualizationEnabled, // q; s: ULONG
        TokenIntegrityLevel, // q; s: TOKEN_MANDATORY_LABEL
        TokenUIAccess, // q; s: ULONG (requires SeTcbPrivilege)
        TokenMandatoryPolicy, // q; s: TOKEN_MANDATORY_POLICY (requires SeTcbPrivilege)
        TokenLogonSid, // q: TOKEN_GROUPS
        TokenIsAppContainer, // q: ULONG // since WIN8
        TokenCapabilities, // q: TOKEN_GROUPS // 30
        TokenAppContainerSid, // q: TOKEN_APPCONTAINER_INFORMATION
        TokenAppContainerNumber, // q: ULONG
        TokenUserClaimAttributes, // q: CLAIM_SECURITY_ATTRIBUTES_INFORMATION
        TokenDeviceClaimAttributes, // q: CLAIM_SECURITY_ATTRIBUTES_INFORMATION
        TokenRestrictedUserClaimAttributes, // q: CLAIM_SECURITY_ATTRIBUTES_INFORMATION
        TokenRestrictedDeviceClaimAttributes, // q: CLAIM_SECURITY_ATTRIBUTES_INFORMATION
        TokenDeviceGroups, // q: TOKEN_GROUPS
        TokenRestrictedDeviceGroups, // q: TOKEN_GROUPS
        TokenSecurityAttributes, // q; s: TOKEN_SECURITY_ATTRIBUTES_[AND_OPERATION_]INFORMATION (requires SeTcbPrivilege)
        TokenIsRestricted, // q: ULONG // 40
        TokenProcessTrustLevel, // q: TOKEN_PROCESS_TRUST_LEVEL // since WINBLUE
        TokenPrivateNameSpace, // q; s: ULONG  (requires SeTcbPrivilege) // since THRESHOLD
        TokenSingletonAttributes, // q: TOKEN_SECURITY_ATTRIBUTES_INFORMATION // since REDSTONE
        TokenBnoIsolation, // q: TOKEN_BNO_ISOLATION_INFORMATION // since REDSTONE2
        TokenChildProcessFlags, // s: ULONG  (requires SeTcbPrivilege) // since REDSTONE3
        TokenIsLessPrivilegedAppContainer, // q: ULONG // since REDSTONE5
        TokenIsSandboxed, // q: ULONG // since 19H1
        TokenIsAppSilo, // q: ULONG // since WIN11 22H2 // previously TokenOriginatingProcessTrustLevel // q: TOKEN_PROCESS_TRUST_LEVEL
        MaxTokenInfoClass
    } TOKEN_INFORMATION_CLASS, * PTOKEN_INFORMATION_CLASS;
#endif

    // Types

#define TOKEN_SECURITY_ATTRIBUTE_TYPE_INVALID 0x00
#define TOKEN_SECURITY_ATTRIBUTE_TYPE_INT64 0x01
#define TOKEN_SECURITY_ATTRIBUTE_TYPE_UINT64 0x02
#define TOKEN_SECURITY_ATTRIBUTE_TYPE_STRING 0x03
#define TOKEN_SECURITY_ATTRIBUTE_TYPE_FQBN 0x04
#define TOKEN_SECURITY_ATTRIBUTE_TYPE_SID 0x05
#define TOKEN_SECURITY_ATTRIBUTE_TYPE_BOOLEAN 0x06
#define TOKEN_SECURITY_ATTRIBUTE_TYPE_OCTET_STRING 0x10

// Flags

#define TOKEN_SECURITY_ATTRIBUTE_NON_INHERITABLE 0x0001
#define TOKEN_SECURITY_ATTRIBUTE_VALUE_CASE_SENSITIVE 0x0002
#define TOKEN_SECURITY_ATTRIBUTE_USE_FOR_DENY_ONLY 0x0004
#define TOKEN_SECURITY_ATTRIBUTE_DISABLED_BY_DEFAULT 0x0008
#define TOKEN_SECURITY_ATTRIBUTE_DISABLED 0x0010
#define TOKEN_SECURITY_ATTRIBUTE_MANDATORY 0x0020
#define TOKEN_SECURITY_ATTRIBUTE_COMPARE_IGNORE 0x0040

#define TOKEN_SECURITY_ATTRIBUTE_VALID_FLAGS ( \
    TOKEN_SECURITY_ATTRIBUTE_NON_INHERITABLE | \
    TOKEN_SECURITY_ATTRIBUTE_VALUE_CASE_SENSITIVE | \
    TOKEN_SECURITY_ATTRIBUTE_USE_FOR_DENY_ONLY | \
    TOKEN_SECURITY_ATTRIBUTE_DISABLED_BY_DEFAULT | \
    TOKEN_SECURITY_ATTRIBUTE_DISABLED | \
    TOKEN_SECURITY_ATTRIBUTE_MANDATORY)

#define TOKEN_SECURITY_ATTRIBUTE_CUSTOM_FLAGS 0xffff0000

// end_rev

// private
    typedef struct _TOKEN_SECURITY_ATTRIBUTE_FQBN_VALUE
    {
        ULONG64 Version;
        UNICODE_STRING Name;
    } TOKEN_SECURITY_ATTRIBUTE_FQBN_VALUE, * PTOKEN_SECURITY_ATTRIBUTE_FQBN_VALUE;

    // private
    typedef struct _TOKEN_SECURITY_ATTRIBUTE_OCTET_STRING_VALUE
    {
        PVOID pValue;
        ULONG ValueLength;
    } TOKEN_SECURITY_ATTRIBUTE_OCTET_STRING_VALUE, * PTOKEN_SECURITY_ATTRIBUTE_OCTET_STRING_VALUE;

    // private
    typedef struct _TOKEN_SECURITY_ATTRIBUTE_V1
    {
        UNICODE_STRING Name;
        USHORT ValueType;
        USHORT Reserved;
        ULONG Flags;
        ULONG ValueCount;
        union
        {
            PLONG64 pInt64;
            PULONG64 pUint64;
            PUNICODE_STRING pString;
            PTOKEN_SECURITY_ATTRIBUTE_FQBN_VALUE pFqbn;
            PTOKEN_SECURITY_ATTRIBUTE_OCTET_STRING_VALUE pOctetString;
        } Values;
    } TOKEN_SECURITY_ATTRIBUTE_V1, * PTOKEN_SECURITY_ATTRIBUTE_V1;

    // rev
#define TOKEN_SECURITY_ATTRIBUTES_INFORMATION_VERSION_V1 1
// rev
#define TOKEN_SECURITY_ATTRIBUTES_INFORMATION_VERSION TOKEN_SECURITY_ATTRIBUTES_INFORMATION_VERSION_V1

// private
    typedef struct _TOKEN_SECURITY_ATTRIBUTES_INFORMATION
    {
        USHORT Version;
        USHORT Reserved;
        ULONG AttributeCount;
        union
        {
            PTOKEN_SECURITY_ATTRIBUTE_V1 pAttributeV1;
        } Attribute;
    } TOKEN_SECURITY_ATTRIBUTES_INFORMATION, * PTOKEN_SECURITY_ATTRIBUTES_INFORMATION;

    // private
    typedef enum _TOKEN_SECURITY_ATTRIBUTE_OPERATION
    {
        TOKEN_SECURITY_ATTRIBUTE_OPERATION_NONE,
        TOKEN_SECURITY_ATTRIBUTE_OPERATION_REPLACE_ALL,
        TOKEN_SECURITY_ATTRIBUTE_OPERATION_ADD,
        TOKEN_SECURITY_ATTRIBUTE_OPERATION_DELETE,
        TOKEN_SECURITY_ATTRIBUTE_OPERATION_REPLACE
    } TOKEN_SECURITY_ATTRIBUTE_OPERATION, * PTOKEN_SECURITY_ATTRIBUTE_OPERATION;

    // private
    typedef struct _TOKEN_SECURITY_ATTRIBUTES_AND_OPERATION_INFORMATION
    {
        PTOKEN_SECURITY_ATTRIBUTES_INFORMATION Attributes;
        PTOKEN_SECURITY_ATTRIBUTE_OPERATION Operations;
    } TOKEN_SECURITY_ATTRIBUTES_AND_OPERATION_INFORMATION, * PTOKEN_SECURITY_ATTRIBUTES_AND_OPERATION_INFORMATION;

    // rev
    typedef struct _TOKEN_PROCESS_TRUST_LEVEL
    {
        PSID TrustLevelSid;
    } TOKEN_PROCESS_TRUST_LEVEL, * PTOKEN_PROCESS_TRUST_LEVEL;

    // Tokens

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtCreateToken(
            _Out_ PHANDLE TokenHandle,
            _In_ ACCESS_MASK DesiredAccess,
            _In_opt_ POBJECT_ATTRIBUTES ObjectAttributes,
            _In_ TOKEN_TYPE Type,
            _In_ PLUID AuthenticationId,
            _In_ PLARGE_INTEGER ExpirationTime,
            _In_ PTOKEN_USER User,
            _In_ PTOKEN_GROUPS Groups,
            _In_ PTOKEN_PRIVILEGES Privileges,
            _In_opt_ PTOKEN_OWNER Owner,
            _In_ PTOKEN_PRIMARY_GROUP PrimaryGroup,
            _In_opt_ PTOKEN_DEFAULT_DACL DefaultDacl,
            _In_ PTOKEN_SOURCE Source
        );

#if (PHNT_VERSION >= PHNT_WIN8)
    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtCreateLowBoxToken(
            _Out_ PHANDLE TokenHandle,
            _In_ HANDLE ExistingTokenHandle,
            _In_ ACCESS_MASK DesiredAccess,
            _In_opt_ POBJECT_ATTRIBUTES ObjectAttributes,
            _In_ PSID PackageSid,
            _In_ ULONG CapabilityCount,
            _In_reads_opt_(CapabilityCount) PSID_AND_ATTRIBUTES Capabilities,
            _In_ ULONG HandleCount,
            _In_reads_opt_(HandleCount) HANDLE* Handles
        );
#endif

#if (PHNT_VERSION >= PHNT_WIN8)
    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtCreateTokenEx(
            _Out_ PHANDLE TokenHandle,
            _In_ ACCESS_MASK DesiredAccess,
            _In_opt_ POBJECT_ATTRIBUTES ObjectAttributes,
            _In_ TOKEN_TYPE Type,
            _In_ PLUID AuthenticationId,
            _In_ PLARGE_INTEGER ExpirationTime,
            _In_ PTOKEN_USER User,
            _In_ PTOKEN_GROUPS Groups,
            _In_ PTOKEN_PRIVILEGES Privileges,
            _In_opt_ PTOKEN_SECURITY_ATTRIBUTES_INFORMATION UserAttributes,
            _In_opt_ PTOKEN_SECURITY_ATTRIBUTES_INFORMATION DeviceAttributes,
            _In_opt_ PTOKEN_GROUPS DeviceGroups,
            _In_opt_ PTOKEN_MANDATORY_POLICY MandatoryPolicy,
            _In_opt_ PTOKEN_OWNER Owner,
            _In_ PTOKEN_PRIMARY_GROUP PrimaryGroup,
            _In_opt_ PTOKEN_DEFAULT_DACL DefaultDacl,
            _In_ PTOKEN_SOURCE Source
        );
#endif

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtOpenProcessToken(
            _In_ HANDLE ProcessHandle,
            _In_ ACCESS_MASK DesiredAccess,
            _Out_ PHANDLE TokenHandle
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtOpenProcessTokenEx(
            _In_ HANDLE ProcessHandle,
            _In_ ACCESS_MASK DesiredAccess,
            _In_ ULONG HandleAttributes,
            _Out_ PHANDLE TokenHandle
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtOpenThreadToken(
            _In_ HANDLE ThreadHandle,
            _In_ ACCESS_MASK DesiredAccess,
            _In_ BOOLEAN OpenAsSelf,
            _Out_ PHANDLE TokenHandle
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtOpenThreadTokenEx(
            _In_ HANDLE ThreadHandle,
            _In_ ACCESS_MASK DesiredAccess,
            _In_ BOOLEAN OpenAsSelf,
            _In_ ULONG HandleAttributes,
            _Out_ PHANDLE TokenHandle
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtDuplicateToken(
            _In_ HANDLE ExistingTokenHandle,
            _In_ ACCESS_MASK DesiredAccess,
            _In_opt_ POBJECT_ATTRIBUTES ObjectAttributes,
            _In_ BOOLEAN EffectiveOnly,
            _In_ TOKEN_TYPE Type,
            _Out_ PHANDLE NewTokenHandle
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtQueryInformationToken(
            _In_ HANDLE TokenHandle,
            _In_ TOKEN_INFORMATION_CLASS TokenInformationClass,
            _Out_writes_bytes_to_opt_(TokenInformationLength, *ReturnLength) PVOID TokenInformation,
            _In_ ULONG TokenInformationLength,
            _Out_ PULONG ReturnLength
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtSetInformationToken(
            _In_ HANDLE TokenHandle,
            _In_ TOKEN_INFORMATION_CLASS TokenInformationClass,
            _In_reads_bytes_(TokenInformationLength) PVOID TokenInformation,
            _In_ ULONG TokenInformationLength
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtAdjustPrivilegesToken(
            _In_ HANDLE TokenHandle,
            _In_ BOOLEAN DisableAllPrivileges,
            _In_opt_ PTOKEN_PRIVILEGES NewState,
            _In_ ULONG BufferLength,
            _Out_writes_bytes_to_opt_(BufferLength, *ReturnLength) PTOKEN_PRIVILEGES PreviousState,
            _Out_opt_ PULONG ReturnLength
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtAdjustGroupsToken(
            _In_ HANDLE TokenHandle,
            _In_ BOOLEAN ResetToDefault,
            _In_opt_ PTOKEN_GROUPS NewState,
            _In_opt_ ULONG BufferLength,
            _Out_writes_bytes_to_opt_(BufferLength, *ReturnLength) PTOKEN_GROUPS PreviousState,
            _Out_opt_ PULONG ReturnLength
        );

#if (PHNT_VERSION >= PHNT_WIN8)
    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtAdjustTokenClaimsAndDeviceGroups(
            _In_ HANDLE TokenHandle,
            _In_ BOOLEAN UserResetToDefault,
            _In_ BOOLEAN DeviceResetToDefault,
            _In_ BOOLEAN DeviceGroupsResetToDefault,
            _In_opt_ PTOKEN_SECURITY_ATTRIBUTES_INFORMATION NewUserState,
            _In_opt_ PTOKEN_SECURITY_ATTRIBUTES_INFORMATION NewDeviceState,
            _In_opt_ PTOKEN_GROUPS NewDeviceGroupsState,
            _In_ ULONG UserBufferLength,
            _Out_writes_bytes_to_opt_(UserBufferLength, *UserReturnLength) PTOKEN_SECURITY_ATTRIBUTES_INFORMATION PreviousUserState,
            _In_ ULONG DeviceBufferLength,
            _Out_writes_bytes_to_opt_(DeviceBufferLength, *DeviceReturnLength) PTOKEN_SECURITY_ATTRIBUTES_INFORMATION PreviousDeviceState,
            _In_ ULONG DeviceGroupsBufferLength,
            _Out_writes_bytes_to_opt_(DeviceGroupsBufferLength, *DeviceGroupsReturnBufferLength) PTOKEN_GROUPS PreviousDeviceGroups,
            _Out_opt_ PULONG UserReturnLength,
            _Out_opt_ PULONG DeviceReturnLength,
            _Out_opt_ PULONG DeviceGroupsReturnBufferLength
        );
#endif

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtFilterToken(
            _In_ HANDLE ExistingTokenHandle,
            _In_ ULONG Flags,
            _In_opt_ PTOKEN_GROUPS SidsToDisable,
            _In_opt_ PTOKEN_PRIVILEGES PrivilegesToDelete,
            _In_opt_ PTOKEN_GROUPS RestrictedSids,
            _Out_ PHANDLE NewTokenHandle
        );

#if (PHNT_VERSION >= PHNT_WIN8)
    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtFilterTokenEx(
            _In_ HANDLE ExistingTokenHandle,
            _In_ ULONG Flags,
            _In_opt_ PTOKEN_GROUPS SidsToDisable,
            _In_opt_ PTOKEN_PRIVILEGES PrivilegesToDelete,
            _In_opt_ PTOKEN_GROUPS RestrictedSids,
            _In_ ULONG DisableUserClaimsCount,
            _In_opt_ PUNICODE_STRING UserClaimsToDisable,
            _In_ ULONG DisableDeviceClaimsCount,
            _In_opt_ PUNICODE_STRING DeviceClaimsToDisable,
            _In_opt_ PTOKEN_GROUPS DeviceGroupsToDisable,
            _In_opt_ PTOKEN_SECURITY_ATTRIBUTES_INFORMATION RestrictedUserAttributes,
            _In_opt_ PTOKEN_SECURITY_ATTRIBUTES_INFORMATION RestrictedDeviceAttributes,
            _In_opt_ PTOKEN_GROUPS RestrictedDeviceGroups,
            _Out_ PHANDLE NewTokenHandle
        );
#endif

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtCompareTokens(
            _In_ HANDLE FirstTokenHandle,
            _In_ HANDLE SecondTokenHandle,
            _Out_ PBOOLEAN Equal
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtPrivilegeCheck(
            _In_ HANDLE ClientToken,
            _Inout_ PPRIVILEGE_SET RequiredPrivileges,
            _Out_ PBOOLEAN Result
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtImpersonateAnonymousToken(
            _In_ HANDLE ThreadHandle
        );

#if (PHNT_VERSION >= PHNT_WIN7)
    // rev
    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtQuerySecurityAttributesToken(
            _In_ HANDLE TokenHandle,
            _In_reads_opt_(NumberOfAttributes) PUNICODE_STRING Attributes,
            _In_ ULONG NumberOfAttributes,
            _Out_writes_bytes_(Length) PVOID Buffer, // PTOKEN_SECURITY_ATTRIBUTES_INFORMATION
            _In_ ULONG Length,
            _Out_ PULONG ReturnLength
        );
#endif

    // Access checking

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtAccessCheck(
            _In_ PSECURITY_DESCRIPTOR SecurityDescriptor,
            _In_ HANDLE ClientToken,
            _In_ ACCESS_MASK DesiredAccess,
            _In_ PGENERIC_MAPPING GenericMapping,
            _Out_writes_bytes_(*PrivilegeSetLength) PPRIVILEGE_SET PrivilegeSet,
            _Inout_ PULONG PrivilegeSetLength,
            _Out_ PACCESS_MASK GrantedAccess,
            _Out_ PNTSTATUS AccessStatus
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtAccessCheckByType(
            _In_ PSECURITY_DESCRIPTOR SecurityDescriptor,
            _In_opt_ PSID PrincipalSelfSid,
            _In_ HANDLE ClientToken,
            _In_ ACCESS_MASK DesiredAccess,
            _In_reads_(ObjectTypeListLength) POBJECT_TYPE_LIST ObjectTypeList,
            _In_ ULONG ObjectTypeListLength,
            _In_ PGENERIC_MAPPING GenericMapping,
            _Out_writes_bytes_(*PrivilegeSetLength) PPRIVILEGE_SET PrivilegeSet,
            _Inout_ PULONG PrivilegeSetLength,
            _Out_ PACCESS_MASK GrantedAccess,
            _Out_ PNTSTATUS AccessStatus
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtAccessCheckByTypeResultList(
            _In_ PSECURITY_DESCRIPTOR SecurityDescriptor,
            _In_opt_ PSID PrincipalSelfSid,
            _In_ HANDLE ClientToken,
            _In_ ACCESS_MASK DesiredAccess,
            _In_reads_(ObjectTypeListLength) POBJECT_TYPE_LIST ObjectTypeList,
            _In_ ULONG ObjectTypeListLength,
            _In_ PGENERIC_MAPPING GenericMapping,
            _Out_writes_bytes_(*PrivilegeSetLength) PPRIVILEGE_SET PrivilegeSet,
            _Inout_ PULONG PrivilegeSetLength,
            _Out_writes_(ObjectTypeListLength) PACCESS_MASK GrantedAccess,
            _Out_writes_(ObjectTypeListLength) PNTSTATUS AccessStatus
        );

    // Signing

#if (PHNT_VERSION >= PHNT_WIN8)

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtSetCachedSigningLevel(
            _In_ ULONG Flags,
            _In_ SE_SIGNING_LEVEL InputSigningLevel,
            _In_reads_(SourceFileCount) PHANDLE SourceFiles,
            _In_ ULONG SourceFileCount,
            _In_opt_ HANDLE TargetFile
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtGetCachedSigningLevel(
            _In_ HANDLE File,
            _Out_ PULONG Flags,
            _Out_ PSE_SIGNING_LEVEL SigningLevel,
            _Out_writes_bytes_to_opt_(*ThumbprintSize, *ThumbprintSize) PUCHAR Thumbprint,
            _Inout_opt_ PULONG ThumbprintSize,
            _Out_opt_ PULONG ThumbprintAlgorithm
        );

#endif

#if (PHNT_VERSION >= PHNT_REDSTONE2)

    // rev
    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtCompareSigningLevels(
            _In_ SE_SIGNING_LEVEL FirstSigningLevel,
            _In_ SE_SIGNING_LEVEL SecondSigningLevel
        );

#endif

    // Audit alarm

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtAccessCheckAndAuditAlarm(
            _In_ PUNICODE_STRING SubsystemName,
            _In_opt_ PVOID HandleId,
            _In_ PUNICODE_STRING ObjectTypeName,
            _In_ PUNICODE_STRING ObjectName,
            _In_ PSECURITY_DESCRIPTOR SecurityDescriptor,
            _In_ ACCESS_MASK DesiredAccess,
            _In_ PGENERIC_MAPPING GenericMapping,
            _In_ BOOLEAN ObjectCreation,
            _Out_ PACCESS_MASK GrantedAccess,
            _Out_ PNTSTATUS AccessStatus,
            _Out_ PBOOLEAN GenerateOnClose
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtAccessCheckByTypeAndAuditAlarm(
            _In_ PUNICODE_STRING SubsystemName,
            _In_opt_ PVOID HandleId,
            _In_ PUNICODE_STRING ObjectTypeName,
            _In_ PUNICODE_STRING ObjectName,
            _In_ PSECURITY_DESCRIPTOR SecurityDescriptor,
            _In_opt_ PSID PrincipalSelfSid,
            _In_ ACCESS_MASK DesiredAccess,
            _In_ AUDIT_EVENT_TYPE AuditType,
            _In_ ULONG Flags,
            _In_reads_opt_(ObjectTypeListLength) POBJECT_TYPE_LIST ObjectTypeList,
            _In_ ULONG ObjectTypeListLength,
            _In_ PGENERIC_MAPPING GenericMapping,
            _In_ BOOLEAN ObjectCreation,
            _Out_ PACCESS_MASK GrantedAccess,
            _Out_ PNTSTATUS AccessStatus,
            _Out_ PBOOLEAN GenerateOnClose
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtAccessCheckByTypeResultListAndAuditAlarm(
            _In_ PUNICODE_STRING SubsystemName,
            _In_opt_ PVOID HandleId,
            _In_ PUNICODE_STRING ObjectTypeName,
            _In_ PUNICODE_STRING ObjectName,
            _In_ PSECURITY_DESCRIPTOR SecurityDescriptor,
            _In_opt_ PSID PrincipalSelfSid,
            _In_ ACCESS_MASK DesiredAccess,
            _In_ AUDIT_EVENT_TYPE AuditType,
            _In_ ULONG Flags,
            _In_reads_opt_(ObjectTypeListLength) POBJECT_TYPE_LIST ObjectTypeList,
            _In_ ULONG ObjectTypeListLength,
            _In_ PGENERIC_MAPPING GenericMapping,
            _In_ BOOLEAN ObjectCreation,
            _Out_writes_(ObjectTypeListLength) PACCESS_MASK GrantedAccess,
            _Out_writes_(ObjectTypeListLength) PNTSTATUS AccessStatus,
            _Out_ PBOOLEAN GenerateOnClose
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtAccessCheckByTypeResultListAndAuditAlarmByHandle(
            _In_ PUNICODE_STRING SubsystemName,
            _In_opt_ PVOID HandleId,
            _In_ HANDLE ClientToken,
            _In_ PUNICODE_STRING ObjectTypeName,
            _In_ PUNICODE_STRING ObjectName,
            _In_ PSECURITY_DESCRIPTOR SecurityDescriptor,
            _In_opt_ PSID PrincipalSelfSid,
            _In_ ACCESS_MASK DesiredAccess,
            _In_ AUDIT_EVENT_TYPE AuditType,
            _In_ ULONG Flags,
            _In_reads_opt_(ObjectTypeListLength) POBJECT_TYPE_LIST ObjectTypeList,
            _In_ ULONG ObjectTypeListLength,
            _In_ PGENERIC_MAPPING GenericMapping,
            _In_ BOOLEAN ObjectCreation,
            _Out_writes_(ObjectTypeListLength) PACCESS_MASK GrantedAccess,
            _Out_writes_(ObjectTypeListLength) PNTSTATUS AccessStatus,
            _Out_ PBOOLEAN GenerateOnClose
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtOpenObjectAuditAlarm(
            _In_ PUNICODE_STRING SubsystemName,
            _In_opt_ PVOID HandleId,
            _In_ PUNICODE_STRING ObjectTypeName,
            _In_ PUNICODE_STRING ObjectName,
            _In_opt_ PSECURITY_DESCRIPTOR SecurityDescriptor,
            _In_ HANDLE ClientToken,
            _In_ ACCESS_MASK DesiredAccess,
            _In_ ACCESS_MASK GrantedAccess,
            _In_opt_ PPRIVILEGE_SET Privileges,
            _In_ BOOLEAN ObjectCreation,
            _In_ BOOLEAN AccessGranted,
            _Out_ PBOOLEAN GenerateOnClose
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtPrivilegeObjectAuditAlarm(
            _In_ PUNICODE_STRING SubsystemName,
            _In_opt_ PVOID HandleId,
            _In_ HANDLE ClientToken,
            _In_ ACCESS_MASK DesiredAccess,
            _In_ PPRIVILEGE_SET Privileges,
            _In_ BOOLEAN AccessGranted
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtCloseObjectAuditAlarm(
            _In_ PUNICODE_STRING SubsystemName,
            _In_opt_ PVOID HandleId,
            _In_ BOOLEAN GenerateOnClose
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtDeleteObjectAuditAlarm(
            _In_ PUNICODE_STRING SubsystemName,
            _In_opt_ PVOID HandleId,
            _In_ BOOLEAN GenerateOnClose
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtPrivilegedServiceAuditAlarm(
            _In_ PUNICODE_STRING SubsystemName,
            _In_ PUNICODE_STRING ServiceName,
            _In_ HANDLE ClientToken,
            _In_ PPRIVILEGE_SET Privileges,
            _In_ BOOLEAN AccessGranted
        );

#endif
    /*
     * Transaction Manager support functions
     *
     * This file is part of System Informer.
     */

#ifndef _NTTMAPI_H
#define _NTTMAPI_H

#if (PHNT_VERSION >= PHNT_VISTA)
    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtCreateTransactionManager(
            _Out_ PHANDLE TmHandle,
            _In_ ACCESS_MASK DesiredAccess,
            _In_opt_ POBJECT_ATTRIBUTES ObjectAttributes,
            _In_opt_ PUNICODE_STRING LogFileName,
            _In_opt_ ULONG CreateOptions,
            _In_opt_ ULONG CommitStrength
        );
#endif

#if (PHNT_VERSION >= PHNT_VISTA)
    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtOpenTransactionManager(
            _Out_ PHANDLE TmHandle,
            _In_ ACCESS_MASK DesiredAccess,
            _In_opt_ POBJECT_ATTRIBUTES ObjectAttributes,
            _In_opt_ PUNICODE_STRING LogFileName,
            _In_opt_ LPGUID TmIdentity,
            _In_opt_ ULONG OpenOptions
        );
#endif

#if (PHNT_VERSION >= PHNT_VISTA)
    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtRenameTransactionManager(
            _In_ PUNICODE_STRING LogFileName,
            _In_ LPGUID ExistingTransactionManagerGuid
        );
#endif

#if (PHNT_VERSION >= PHNT_VISTA)
    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtRollforwardTransactionManager(
            _In_ HANDLE TransactionManagerHandle,
            _In_opt_ PLARGE_INTEGER TmVirtualClock
        );
#endif

#if (PHNT_VERSION >= PHNT_VISTA)
    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtRecoverTransactionManager(
            _In_ HANDLE TransactionManagerHandle
        );
#endif

#if (PHNT_VERSION >= PHNT_VISTA)
    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtQueryInformationTransactionManager(
            _In_ HANDLE TransactionManagerHandle,
            _In_ TRANSACTIONMANAGER_INFORMATION_CLASS TransactionManagerInformationClass,
            _Out_writes_bytes_(TransactionManagerInformationLength) PVOID TransactionManagerInformation,
            _In_ ULONG TransactionManagerInformationLength,
            _Out_opt_ PULONG ReturnLength
        );
#endif

#if (PHNT_VERSION >= PHNT_VISTA)
    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtSetInformationTransactionManager(
            _In_opt_ HANDLE TmHandle,
            _In_ TRANSACTIONMANAGER_INFORMATION_CLASS TransactionManagerInformationClass,
            _In_reads_bytes_(TransactionManagerInformationLength) PVOID TransactionManagerInformation,
            _In_ ULONG TransactionManagerInformationLength
        );
#endif

#if (PHNT_VERSION >= PHNT_VISTA)
    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtEnumerateTransactionObject(
            _In_opt_ HANDLE RootObjectHandle,
            _In_ KTMOBJECT_TYPE QueryType,
            _Inout_updates_bytes_(ObjectCursorLength) PKTMOBJECT_CURSOR ObjectCursor,
            _In_ ULONG ObjectCursorLength,
            _Out_ PULONG ReturnLength
        );
#endif

#if (PHNT_VERSION >= PHNT_VISTA)
    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtCreateTransaction(
            _Out_ PHANDLE TransactionHandle,
            _In_ ACCESS_MASK DesiredAccess,
            _In_opt_ POBJECT_ATTRIBUTES ObjectAttributes,
            _In_opt_ LPGUID Uow,
            _In_opt_ HANDLE TmHandle,
            _In_opt_ ULONG CreateOptions,
            _In_opt_ ULONG IsolationLevel,
            _In_opt_ ULONG IsolationFlags,
            _In_opt_ PLARGE_INTEGER Timeout,
            _In_opt_ PUNICODE_STRING Description
        );
#endif

#if (PHNT_VERSION >= PHNT_VISTA)
    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtOpenTransaction(
            _Out_ PHANDLE TransactionHandle,
            _In_ ACCESS_MASK DesiredAccess,
            _In_opt_ POBJECT_ATTRIBUTES ObjectAttributes,
            _In_ LPGUID Uow,
            _In_opt_ HANDLE TmHandle
        );
#endif

#if (PHNT_VERSION >= PHNT_VISTA)
    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtQueryInformationTransaction(
            _In_ HANDLE TransactionHandle,
            _In_ TRANSACTION_INFORMATION_CLASS TransactionInformationClass,
            _Out_writes_bytes_(TransactionInformationLength) PVOID TransactionInformation,
            _In_ ULONG TransactionInformationLength,
            _Out_opt_ PULONG ReturnLength
        );
#endif

#if (PHNT_VERSION >= PHNT_VISTA)
    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtSetInformationTransaction(
            _In_ HANDLE TransactionHandle,
            _In_ TRANSACTION_INFORMATION_CLASS TransactionInformationClass,
            _In_reads_bytes_(TransactionInformationLength) PVOID TransactionInformation,
            _In_ ULONG TransactionInformationLength
        );
#endif

#if (PHNT_VERSION >= PHNT_VISTA)
    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtCommitTransaction(
            _In_ HANDLE TransactionHandle,
            _In_ BOOLEAN Wait
        );
#endif

#if (PHNT_VERSION >= PHNT_VISTA)
    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtRollbackTransaction(
            _In_ HANDLE TransactionHandle,
            _In_ BOOLEAN Wait
        );
#endif

#if (PHNT_VERSION >= PHNT_VISTA)
    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtCreateEnlistment(
            _Out_ PHANDLE EnlistmentHandle,
            _In_ ACCESS_MASK DesiredAccess,
            _In_ HANDLE ResourceManagerHandle,
            _In_ HANDLE TransactionHandle,
            _In_opt_ POBJECT_ATTRIBUTES ObjectAttributes,
            _In_opt_ ULONG CreateOptions,
            _In_ NOTIFICATION_MASK NotificationMask,
            _In_opt_ PVOID EnlistmentKey
        );
#endif

#if (PHNT_VERSION >= PHNT_VISTA)
    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtOpenEnlistment(
            _Out_ PHANDLE EnlistmentHandle,
            _In_ ACCESS_MASK DesiredAccess,
            _In_ HANDLE ResourceManagerHandle,
            _In_ LPGUID EnlistmentGuid,
            _In_opt_ POBJECT_ATTRIBUTES ObjectAttributes
        );
#endif

#if (PHNT_VERSION >= PHNT_VISTA)
    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtQueryInformationEnlistment(
            _In_ HANDLE EnlistmentHandle,
            _In_ ENLISTMENT_INFORMATION_CLASS EnlistmentInformationClass,
            _Out_writes_bytes_(EnlistmentInformationLength) PVOID EnlistmentInformation,
            _In_ ULONG EnlistmentInformationLength,
            _Out_opt_ PULONG ReturnLength
        );
#endif

#if (PHNT_VERSION >= PHNT_VISTA)
    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtSetInformationEnlistment(
            _In_opt_ HANDLE EnlistmentHandle,
            _In_ ENLISTMENT_INFORMATION_CLASS EnlistmentInformationClass,
            _In_reads_bytes_(EnlistmentInformationLength) PVOID EnlistmentInformation,
            _In_ ULONG EnlistmentInformationLength
        );
#endif

#if (PHNT_VERSION >= PHNT_VISTA)
    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtRecoverEnlistment(
            _In_ HANDLE EnlistmentHandle,
            _In_opt_ PVOID EnlistmentKey
        );
#endif

#if (PHNT_VERSION >= PHNT_VISTA)
    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtPrePrepareEnlistment(
            _In_ HANDLE EnlistmentHandle,
            _In_opt_ PLARGE_INTEGER TmVirtualClock
        );
#endif

#if (PHNT_VERSION >= PHNT_VISTA)
    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtPrepareEnlistment(
            _In_ HANDLE EnlistmentHandle,
            _In_opt_ PLARGE_INTEGER TmVirtualClock
        );
#endif

#if (PHNT_VERSION >= PHNT_VISTA)
    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtCommitEnlistment(
            _In_ HANDLE EnlistmentHandle,
            _In_opt_ PLARGE_INTEGER TmVirtualClock
        );
#endif

#if (PHNT_VERSION >= PHNT_VISTA)
    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtRollbackEnlistment(
            _In_ HANDLE EnlistmentHandle,
            _In_opt_ PLARGE_INTEGER TmVirtualClock
        );
#endif

#if (PHNT_VERSION >= PHNT_VISTA)
    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtPrePrepareComplete(
            _In_ HANDLE EnlistmentHandle,
            _In_opt_ PLARGE_INTEGER TmVirtualClock
        );
#endif

#if (PHNT_VERSION >= PHNT_VISTA)
    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtPrepareComplete(
            _In_ HANDLE EnlistmentHandle,
            _In_opt_ PLARGE_INTEGER TmVirtualClock
        );
#endif

#if (PHNT_VERSION >= PHNT_VISTA)
    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtCommitComplete(
            _In_ HANDLE EnlistmentHandle,
            _In_opt_ PLARGE_INTEGER TmVirtualClock
        );
#endif

#if (PHNT_VERSION >= PHNT_VISTA)
    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtReadOnlyEnlistment(
            _In_ HANDLE EnlistmentHandle,
            _In_opt_ PLARGE_INTEGER TmVirtualClock
        );
#endif

#if (PHNT_VERSION >= PHNT_VISTA)
    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtRollbackComplete(
            _In_ HANDLE EnlistmentHandle,
            _In_opt_ PLARGE_INTEGER TmVirtualClock
        );
#endif

#if (PHNT_VERSION >= PHNT_VISTA)
    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtSinglePhaseReject(
            _In_ HANDLE EnlistmentHandle,
            _In_opt_ PLARGE_INTEGER TmVirtualClock
        );
#endif

#if (PHNT_VERSION >= PHNT_VISTA)
    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtCreateResourceManager(
            _Out_ PHANDLE ResourceManagerHandle,
            _In_ ACCESS_MASK DesiredAccess,
            _In_ HANDLE TmHandle,
            _In_ LPGUID RmGuid,
            _In_opt_ POBJECT_ATTRIBUTES ObjectAttributes,
            _In_opt_ ULONG CreateOptions,
            _In_opt_ PUNICODE_STRING Description
        );
#endif

#if (PHNT_VERSION >= PHNT_VISTA)
    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtOpenResourceManager(
            _Out_ PHANDLE ResourceManagerHandle,
            _In_ ACCESS_MASK DesiredAccess,
            _In_ HANDLE TmHandle,
            _In_opt_ LPGUID ResourceManagerGuid,
            _In_opt_ POBJECT_ATTRIBUTES ObjectAttributes
        );
#endif

#if (PHNT_VERSION >= PHNT_VISTA)
    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtRecoverResourceManager(
            _In_ HANDLE ResourceManagerHandle
        );
#endif

#if (PHNT_VERSION >= PHNT_VISTA)
    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtGetNotificationResourceManager(
            _In_ HANDLE ResourceManagerHandle,
            _Out_ PTRANSACTION_NOTIFICATION TransactionNotification,
            _In_ ULONG NotificationLength,
            _In_opt_ PLARGE_INTEGER Timeout,
            _Out_opt_ PULONG ReturnLength,
            _In_ ULONG Asynchronous,
            _In_opt_ ULONG_PTR AsynchronousContext
        );
#endif

#if (PHNT_VERSION >= PHNT_VISTA)
    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtQueryInformationResourceManager(
            _In_ HANDLE ResourceManagerHandle,
            _In_ RESOURCEMANAGER_INFORMATION_CLASS ResourceManagerInformationClass,
            _Out_writes_bytes_(ResourceManagerInformationLength) PVOID ResourceManagerInformation,
            _In_ ULONG ResourceManagerInformationLength,
            _Out_opt_ PULONG ReturnLength
        );
#endif

#if (PHNT_VERSION >= PHNT_VISTA)
    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtSetInformationResourceManager(
            _In_ HANDLE ResourceManagerHandle,
            _In_ RESOURCEMANAGER_INFORMATION_CLASS ResourceManagerInformationClass,
            _In_reads_bytes_(ResourceManagerInformationLength) PVOID ResourceManagerInformation,
            _In_ ULONG ResourceManagerInformationLength
        );
#endif

#if (PHNT_VERSION >= PHNT_VISTA)
    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtRegisterProtocolAddressInformation(
            _In_ HANDLE ResourceManager,
            _In_ PCRM_PROTOCOL_ID ProtocolId,
            _In_ ULONG ProtocolInformationSize,
            _In_ PVOID ProtocolInformation,
            _In_opt_ ULONG CreateOptions
        );
#endif

#if (PHNT_VERSION >= PHNT_VISTA)
    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtPropagationComplete(
            _In_ HANDLE ResourceManagerHandle,
            _In_ ULONG RequestCookie,
            _In_ ULONG BufferLength,
            _In_ PVOID Buffer
        );
#endif

#if (PHNT_VERSION >= PHNT_VISTA)
    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtPropagationFailed(
            _In_ HANDLE ResourceManagerHandle,
            _In_ ULONG RequestCookie,
            _In_ NTSTATUS PropStatus
        );
#endif

#if (PHNT_VERSION >= PHNT_VISTA)
    // private
    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtFreezeTransactions(
            _In_ PLARGE_INTEGER FreezeTimeout,
            _In_ PLARGE_INTEGER ThawTimeout
        );
#endif

#if (PHNT_VERSION >= PHNT_VISTA)
    // private
    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtThawTransactions(
            VOID
        );
#endif

#endif
    /*
     * Thread Pool support functions
     *
     * This file is part of System Informer.
     */

#ifndef _NTTP_H
#define _NTTP_H

     // Some types are already defined in winnt.h.

    typedef struct _TP_ALPC TP_ALPC, * PTP_ALPC;

    // private
    typedef VOID(NTAPI* PTP_ALPC_CALLBACK)(
        _Inout_ PTP_CALLBACK_INSTANCE Instance,
        _Inout_opt_ PVOID Context,
        _In_ PTP_ALPC Alpc
        );

    // rev
    typedef VOID(NTAPI* PTP_ALPC_CALLBACK_EX)(
        _Inout_ PTP_CALLBACK_INSTANCE Instance,
        _Inout_opt_ PVOID Context,
        _In_ PTP_ALPC Alpc,
        _In_ PVOID ApcContext
        );

#if (PHNT_VERSION >= PHNT_VISTA)

    // winbase:CreateThreadpool
    NTSYSAPI
        NTSTATUS
        NTAPI
        TpAllocPool(
            _Out_ PTP_POOL* PoolReturn,
            _Reserved_ PVOID Reserved
        );

    // winbase:CloseThreadpool
    NTSYSAPI
        VOID
        NTAPI
        TpReleasePool(
            _Inout_ PTP_POOL Pool
        );

    // winbase:SetThreadpoolThreadMaximum
    NTSYSAPI
        VOID
        NTAPI
        TpSetPoolMaxThreads(
            _Inout_ PTP_POOL Pool,
            _In_ ULONG MaxThreads
        );

    // winbase:SetThreadpoolThreadMinimum
    NTSYSAPI
        NTSTATUS
        NTAPI
        TpSetPoolMinThreads(
            _Inout_ PTP_POOL Pool,
            _In_ ULONG MinThreads
        );

#if (PHNT_VERSION >= PHNT_WIN7)
    // winbase:QueryThreadpoolStackInformation
    NTSYSAPI
        NTSTATUS
        NTAPI
        TpQueryPoolStackInformation(
            _In_ PTP_POOL Pool,
            _Out_ PTP_POOL_STACK_INFORMATION PoolStackInformation
        );

    // winbase:SetThreadpoolStackInformation
    NTSYSAPI
        NTSTATUS
        NTAPI
        TpSetPoolStackInformation(
            _Inout_ PTP_POOL Pool,
            _In_ PTP_POOL_STACK_INFORMATION PoolStackInformation
        );

    // rev
    NTSYSAPI
        NTSTATUS
        NTAPI
        TpSetPoolThreadBasePriority(
            _Inout_ PTP_POOL Pool,
            _In_ ULONG BasePriority
        );
#endif

    // winbase:CreateThreadpoolCleanupGroup
    NTSYSAPI
        NTSTATUS
        NTAPI
        TpAllocCleanupGroup(
            _Out_ PTP_CLEANUP_GROUP* CleanupGroupReturn
        );

    // winbase:CloseThreadpoolCleanupGroup
    NTSYSAPI
        VOID
        NTAPI
        TpReleaseCleanupGroup(
            _Inout_ PTP_CLEANUP_GROUP CleanupGroup
        );

    // winbase:CloseThreadpoolCleanupGroupMembers
    NTSYSAPI
        VOID
        NTAPI
        TpReleaseCleanupGroupMembers(
            _Inout_ PTP_CLEANUP_GROUP CleanupGroup,
            _In_ LOGICAL CancelPendingCallbacks,
            _Inout_opt_ PVOID CleanupParameter
        );

    // winbase:SetEventWhenCallbackReturns
    NTSYSAPI
        VOID
        NTAPI
        TpCallbackSetEventOnCompletion(
            _Inout_ PTP_CALLBACK_INSTANCE Instance,
            _In_ HANDLE Event
        );

    // winbase:ReleaseSemaphoreWhenCallbackReturns
    NTSYSAPI
        VOID
        NTAPI
        TpCallbackReleaseSemaphoreOnCompletion(
            _Inout_ PTP_CALLBACK_INSTANCE Instance,
            _In_ HANDLE Semaphore,
            _In_ ULONG ReleaseCount
        );

    // winbase:ReleaseMutexWhenCallbackReturns
    NTSYSAPI
        VOID
        NTAPI
        TpCallbackReleaseMutexOnCompletion(
            _Inout_ PTP_CALLBACK_INSTANCE Instance,
            _In_ HANDLE Mutex
        );

    // winbase:LeaveCriticalSectionWhenCallbackReturns
    NTSYSAPI
        VOID
        NTAPI
        TpCallbackLeaveCriticalSectionOnCompletion(
            _Inout_ PTP_CALLBACK_INSTANCE Instance,
            _Inout_ PRTL_CRITICAL_SECTION CriticalSection
        );

    // winbase:FreeLibraryWhenCallbackReturns
    NTSYSAPI
        VOID
        NTAPI
        TpCallbackUnloadDllOnCompletion(
            _Inout_ PTP_CALLBACK_INSTANCE Instance,
            _In_ PVOID DllHandle
        );

    // winbase:CallbackMayRunLong
    NTSYSAPI
        NTSTATUS
        NTAPI
        TpCallbackMayRunLong(
            _Inout_ PTP_CALLBACK_INSTANCE Instance
        );

    // winbase:DisassociateCurrentThreadFromCallback
    NTSYSAPI
        VOID
        NTAPI
        TpDisassociateCallback(
            _Inout_ PTP_CALLBACK_INSTANCE Instance
        );

    // winbase:TrySubmitThreadpoolCallback
    NTSYSAPI
        NTSTATUS
        NTAPI
        TpSimpleTryPost(
            _In_ PTP_SIMPLE_CALLBACK Callback,
            _Inout_opt_ PVOID Context,
            _In_opt_ PTP_CALLBACK_ENVIRON CallbackEnviron
        );

    // winbase:CreateThreadpoolWork
    NTSYSAPI
        NTSTATUS
        NTAPI
        TpAllocWork(
            _Out_ PTP_WORK* WorkReturn,
            _In_ PTP_WORK_CALLBACK Callback,
            _Inout_opt_ PVOID Context,
            _In_opt_ PTP_CALLBACK_ENVIRON CallbackEnviron
        );

    // winbase:CloseThreadpoolWork
    NTSYSAPI
        VOID
        NTAPI
        TpReleaseWork(
            _Inout_ PTP_WORK Work
        );

    // winbase:SubmitThreadpoolWork
    NTSYSAPI
        VOID
        NTAPI
        TpPostWork(
            _Inout_ PTP_WORK Work
        );

    // winbase:WaitForThreadpoolWorkCallbacks
    NTSYSAPI
        VOID
        NTAPI
        TpWaitForWork(
            _Inout_ PTP_WORK Work,
            _In_ LOGICAL CancelPendingCallbacks
        );

    // winbase:CreateThreadpoolTimer
    NTSYSAPI
        NTSTATUS
        NTAPI
        TpAllocTimer(
            _Out_ PTP_TIMER* Timer,
            _In_ PTP_TIMER_CALLBACK Callback,
            _Inout_opt_ PVOID Context,
            _In_opt_ PTP_CALLBACK_ENVIRON CallbackEnviron
        );

    // winbase:CloseThreadpoolTimer
    NTSYSAPI
        VOID
        NTAPI
        TpReleaseTimer(
            _Inout_ PTP_TIMER Timer
        );

    // winbase:SetThreadpoolTimer
    NTSYSAPI
        VOID
        NTAPI
        TpSetTimer(
            _Inout_ PTP_TIMER Timer,
            _In_opt_ PLARGE_INTEGER DueTime,
            _In_ ULONG Period,
            _In_opt_ ULONG WindowLength
        );

#if (PHNT_VERSION >= PHNT_WIN8)
    // winbase:SetThreadpoolTimerEx
    NTSYSAPI
        NTSTATUS
        NTAPI
        TpSetTimerEx(
            _Inout_ PTP_TIMER Timer,
            _In_opt_ PLARGE_INTEGER DueTime,
            _In_ ULONG Period,
            _In_opt_ ULONG WindowLength
        );
#endif

    // winbase:IsThreadpoolTimerSet
    NTSYSAPI
        LOGICAL
        NTAPI
        TpIsTimerSet(
            _In_ PTP_TIMER Timer
        );

    // winbase:WaitForThreadpoolTimerCallbacks
    NTSYSAPI
        VOID
        NTAPI
        TpWaitForTimer(
            _Inout_ PTP_TIMER Timer,
            _In_ LOGICAL CancelPendingCallbacks
        );

    // winbase:CreateThreadpoolWait
    NTSYSAPI
        NTSTATUS
        NTAPI
        TpAllocWait(
            _Out_ PTP_WAIT* WaitReturn,
            _In_ PTP_WAIT_CALLBACK Callback,
            _Inout_opt_ PVOID Context,
            _In_opt_ PTP_CALLBACK_ENVIRON CallbackEnviron
        );

    // winbase:CloseThreadpoolWait
    NTSYSAPI
        VOID
        NTAPI
        TpReleaseWait(
            _Inout_ PTP_WAIT Wait
        );

    // winbase:SetThreadpoolWait
    NTSYSAPI
        VOID
        NTAPI
        TpSetWait(
            _Inout_ PTP_WAIT Wait,
            _In_opt_ HANDLE Handle,
            _In_opt_ PLARGE_INTEGER Timeout
        );

#if (PHNT_VERSION >= PHNT_WIN8)
    // winbase:SetThreadpoolWaitEx
    NTSYSAPI
        NTSTATUS
        NTAPI
        TpSetWaitEx(
            _Inout_ PTP_WAIT Wait,
            _In_opt_ HANDLE Handle,
            _In_opt_ PLARGE_INTEGER Timeout,
            _In_opt_ PVOID Reserved
        );
#endif

    // winbase:WaitForThreadpoolWaitCallbacks
    NTSYSAPI
        VOID
        NTAPI
        TpWaitForWait(
            _Inout_ PTP_WAIT Wait,
            _In_ LOGICAL CancelPendingCallbacks
        );

    // private
    typedef VOID(NTAPI* PTP_IO_CALLBACK)(
        _Inout_ PTP_CALLBACK_INSTANCE Instance,
        _Inout_opt_ PVOID Context,
        _In_ PVOID ApcContext,
        _In_ PIO_STATUS_BLOCK IoSB,
        _In_ PTP_IO Io
        );

    // winbase:CreateThreadpoolIo
    NTSYSAPI
        NTSTATUS
        NTAPI
        TpAllocIoCompletion(
            _Out_ PTP_IO* IoReturn,
            _In_ HANDLE File,
            _In_ PTP_IO_CALLBACK Callback,
            _Inout_opt_ PVOID Context,
            _In_opt_ PTP_CALLBACK_ENVIRON CallbackEnviron
        );

    // winbase:CloseThreadpoolIo
    NTSYSAPI
        VOID
        NTAPI
        TpReleaseIoCompletion(
            _Inout_ PTP_IO Io
        );

    // winbase:StartThreadpoolIo
    NTSYSAPI
        VOID
        NTAPI
        TpStartAsyncIoOperation(
            _Inout_ PTP_IO Io
        );

    // winbase:CancelThreadpoolIo
    NTSYSAPI
        VOID
        NTAPI
        TpCancelAsyncIoOperation(
            _Inout_ PTP_IO Io
        );

    // winbase:WaitForThreadpoolIoCallbacks
    NTSYSAPI
        VOID
        NTAPI
        TpWaitForIoCompletion(
            _Inout_ PTP_IO Io,
            _In_ LOGICAL CancelPendingCallbacks
        );

    // private
    NTSYSAPI
        NTSTATUS
        NTAPI
        TpAllocAlpcCompletion(
            _Out_ PTP_ALPC* AlpcReturn,
            _In_ HANDLE AlpcPort,
            _In_ PTP_ALPC_CALLBACK Callback,
            _Inout_opt_ PVOID Context,
            _In_opt_ PTP_CALLBACK_ENVIRON CallbackEnviron
        );

#if (PHNT_VERSION >= PHNT_WIN7)
    // rev
    NTSYSAPI
        NTSTATUS
        NTAPI
        TpAllocAlpcCompletionEx(
            _Out_ PTP_ALPC* AlpcReturn,
            _In_ HANDLE AlpcPort,
            _In_ PTP_ALPC_CALLBACK_EX Callback,
            _Inout_opt_ PVOID Context,
            _In_opt_ PTP_CALLBACK_ENVIRON CallbackEnviron
        );
#endif

    // private
    NTSYSAPI
        VOID
        NTAPI
        TpReleaseAlpcCompletion(
            _Inout_ PTP_ALPC Alpc
        );

    // private
    NTSYSAPI
        VOID
        NTAPI
        TpWaitForAlpcCompletion(
            _Inout_ PTP_ALPC Alpc
        );

    // private
    typedef enum _TP_TRACE_TYPE
    {
        TpTraceThreadPriority = 1,
        TpTraceThreadAffinity,
        MaxTpTraceType
    } TP_TRACE_TYPE;

    // private
    NTSYSAPI
        VOID
        NTAPI
        TpCaptureCaller(
            _In_ TP_TRACE_TYPE Type
        );

    // private
    NTSYSAPI
        VOID
        NTAPI
        TpCheckTerminateWorker(
            _In_ HANDLE Thread
        );

#endif

#endif
    /*
     * Exception support functions
     *
     * This file is part of System Informer.
     */

#ifndef _NTXCAPI_H
#define _NTXCAPI_H

    NTSYSAPI
        BOOLEAN
        NTAPI
        RtlDispatchException(
            _In_ PEXCEPTION_RECORD ExceptionRecord,
            _In_ PCONTEXT ContextRecord
        );

    NTSYSAPI
        DECLSPEC_NORETURN
        VOID
        NTAPI
        RtlRaiseStatus(
            _In_ NTSTATUS Status
        );

    NTSYSAPI
        VOID
        NTAPI
        RtlRaiseException(
            _In_ PEXCEPTION_RECORD ExceptionRecord
        );

#if (PHNT_VERSION >= PHNT_20H1)
    // rev
    NTSYSAPI
        VOID
        NTAPI
        RtlRaiseExceptionForReturnAddressHijack(
            VOID
        );

    // rev
    NTSYSAPI
        DECLSPEC_NORETURN
        VOID
        NTAPI
        RtlRaiseNoncontinuableException(
            _In_ PEXCEPTION_RECORD ExceptionRecord,
            _In_ PCONTEXT ContextRecord
        );
#endif

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtContinue(
            _In_ PCONTEXT ContextRecord,
            _In_ BOOLEAN TestAlert
        );

#if (PHNT_VERSION >= PHNT_THRESHOLD)
    typedef enum _KCONTINUE_TYPE
    {
        KCONTINUE_UNWIND,
        KCONTINUE_RESUME,
        KCONTINUE_LONGJUMP,
        KCONTINUE_SET,
        KCONTINUE_LAST,
    } KCONTINUE_TYPE;

    typedef struct _KCONTINUE_ARGUMENT
    {
        KCONTINUE_TYPE ContinueType;
        ULONG ContinueFlags;
        ULONGLONG Reserved[2];
    } KCONTINUE_ARGUMENT, * PKCONTINUE_ARGUMENT;

#define KCONTINUE_FLAG_TEST_ALERT 0x00000001 // wbenny
#define KCONTINUE_FLAG_DELIVER_APC 0x00000002 // wbenny

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtContinueEx(
            _In_ PCONTEXT ContextRecord,
            _In_ PVOID ContinueArgument // PKCONTINUE_ARGUMENT and BOOLEAN are valid
        );

    //FORCEINLINE
    //NTSTATUS
    //NtContinue(
    //    _In_ PCONTEXT ContextRecord,
    //    _In_ BOOLEAN TestAlert
    //    )
    //{
    //    return NtContinueEx(ContextRecord, (PCONTINUE_ARGUMENT)TestAlert);
    //}
#endif

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtRaiseException(
            _In_ PEXCEPTION_RECORD ExceptionRecord,
            _In_ PCONTEXT ContextRecord,
            _In_ BOOLEAN FirstChance
        );

    NTSYSCALLAPI
        DECLSPEC_NORETURN
        VOID
        NTAPI
        RtlAssert(
            _In_ PVOID VoidFailedAssertion,
            _In_ PVOID VoidFileName,
            _In_ ULONG LineNumber,
            _In_opt_ PSTR MutableMessage
        );

#define RTL_ASSERT(exp) \
    ((!(exp)) ? (RtlAssert((PVOID)#exp, (PVOID)__FILE__, __LINE__, NULL), FALSE) : TRUE)
#define RTL_ASSERTMSG(msg, exp) \
    ((!(exp)) ? (RtlAssert((PVOID)#exp, (PVOID)__FILE__, __LINE__, msg), FALSE) : TRUE)
#define RTL_SOFT_ASSERT(_exp) \
    ((!(_exp)) ? (DbgPrint("%s(%d): Soft assertion failed\n   Expression: %s\n", __FILE__, __LINE__, #_exp), FALSE) : TRUE)
#define RTL_SOFT_ASSERTMSG(_msg, _exp) \
    ((!(_exp)) ? (DbgPrint("%s(%d): Soft assertion failed\n   Expression: %s\n   Message: %s\n", __FILE__, __LINE__, #_exp, (_msg)), FALSE) : TRUE)

#endif

    /*
     * Windows on Windows support functions
     *
     * This file is part of System Informer.
     */

#ifndef _NTWOW64_H
#define _NTWOW64_H

#define WOW64_SYSTEM_DIRECTORY "SysWOW64"
#define WOW64_SYSTEM_DIRECTORY_U L"SysWOW64"
#define WOW64_X86_TAG " (x86)"
#define WOW64_X86_TAG_U L" (x86)"

     // In USER_SHARED_DATA
    typedef enum _WOW64_SHARED_INFORMATION
    {
        SharedNtdll32LdrInitializeThunk,
        SharedNtdll32KiUserExceptionDispatcher,
        SharedNtdll32KiUserApcDispatcher,
        SharedNtdll32KiUserCallbackDispatcher,
        SharedNtdll32ExpInterlockedPopEntrySListFault,
        SharedNtdll32ExpInterlockedPopEntrySListResume,
        SharedNtdll32ExpInterlockedPopEntrySListEnd,
        SharedNtdll32RtlUserThreadStart,
        SharedNtdll32pQueryProcessDebugInformationRemote,
        SharedNtdll32BaseAddress,
        SharedNtdll32LdrSystemDllInitBlock,
        Wow64SharedPageEntriesCount
    } WOW64_SHARED_INFORMATION;

    // 32-bit definitions

#define WOW64_POINTER(Type) ULONG

    typedef struct _RTL_BALANCED_NODE32
    {
        union
        {
            WOW64_POINTER(struct _RTL_BALANCED_NODE*) Children[2];
            struct
            {
                WOW64_POINTER(struct _RTL_BALANCED_NODE*) Left;
                WOW64_POINTER(struct _RTL_BALANCED_NODE*) Right;
            };
        };
        union
        {
            WOW64_POINTER(UCHAR) Red : 1;
            WOW64_POINTER(UCHAR) Balance : 2;
            WOW64_POINTER(ULONG_PTR) ParentValue;
        };
    } RTL_BALANCED_NODE32, * PRTL_BALANCED_NODE32;

    typedef struct _RTL_RB_TREE32
    {
        WOW64_POINTER(PRTL_BALANCED_NODE) Root;
        WOW64_POINTER(PRTL_BALANCED_NODE) Min;
    } RTL_RB_TREE32, * PRTL_RB_TREE32;

    typedef struct _PEB_LDR_DATA32
    {
        ULONG Length;
        BOOLEAN Initialized;
        WOW64_POINTER(HANDLE) SsHandle;
        LIST_ENTRY32 InLoadOrderModuleList;
        LIST_ENTRY32 InMemoryOrderModuleList;
        LIST_ENTRY32 InInitializationOrderModuleList;
        WOW64_POINTER(PVOID) EntryInProgress;
        BOOLEAN ShutdownInProgress;
        WOW64_POINTER(HANDLE) ShutdownThreadId;
    } PEB_LDR_DATA32, * PPEB_LDR_DATA32;

    typedef struct _LDR_SERVICE_TAG_RECORD32
    {
        WOW64_POINTER(struct _LDR_SERVICE_TAG_RECORD*) Next;
        ULONG ServiceTag;
    } LDR_SERVICE_TAG_RECORD32, * PLDR_SERVICE_TAG_RECORD32;

    typedef struct _LDRP_CSLIST32
    {
        WOW64_POINTER(PSINGLE_LIST_ENTRY) Tail;
    } LDRP_CSLIST32, * PLDRP_CSLIST32;

    typedef struct _LDR_DDAG_NODE32
    {
        LIST_ENTRY32 Modules;
        WOW64_POINTER(PLDR_SERVICE_TAG_RECORD) ServiceTagList;
        ULONG LoadCount;
        ULONG LoadWhileUnloadingCount;
        ULONG LowestLink;
        union
        {
            LDRP_CSLIST32 Dependencies;
            SINGLE_LIST_ENTRY32 RemovalLink;
        };
        LDRP_CSLIST32 IncomingDependencies;
        LDR_DDAG_STATE State;
        SINGLE_LIST_ENTRY32 CondenseLink;
        ULONG PreorderNumber;
    } LDR_DDAG_NODE32, * PLDR_DDAG_NODE32;

#define LDR_DATA_TABLE_ENTRY_SIZE_WINXP_32 FIELD_OFFSET(LDR_DATA_TABLE_ENTRY32, DdagNode)
#define LDR_DATA_TABLE_ENTRY_SIZE_WIN7_32 FIELD_OFFSET(LDR_DATA_TABLE_ENTRY32, BaseNameHashValue)
#define LDR_DATA_TABLE_ENTRY_SIZE_WIN8_32 FIELD_OFFSET(LDR_DATA_TABLE_ENTRY32, ImplicitPathOptions)
#define LDR_DATA_TABLE_ENTRY_SIZE_WIN10_32 FIELD_OFFSET(LDR_DATA_TABLE_ENTRY32, SigningLevel)
#define LDR_DATA_TABLE_ENTRY_SIZE_WIN11_32 sizeof(LDR_DATA_TABLE_ENTRY32)

    typedef struct _LDR_DATA_TABLE_ENTRY32
    {
        LIST_ENTRY32 InLoadOrderLinks;
        LIST_ENTRY32 InMemoryOrderLinks;
        union
        {
            LIST_ENTRY32 InInitializationOrderLinks;
            LIST_ENTRY32 InProgressLinks;
        };
        WOW64_POINTER(PVOID) DllBase;
        WOW64_POINTER(PVOID) EntryPoint;
        ULONG SizeOfImage;
        UNICODE_STRING32 FullDllName;
        UNICODE_STRING32 BaseDllName;
        union
        {
            UCHAR FlagGroup[4];
            ULONG Flags;
            struct
            {
                ULONG PackagedBinary : 1;
                ULONG MarkedForRemoval : 1;
                ULONG ImageDll : 1;
                ULONG LoadNotificationsSent : 1;
                ULONG TelemetryEntryProcessed : 1;
                ULONG ProcessStaticImport : 1;
                ULONG InLegacyLists : 1;
                ULONG InIndexes : 1;
                ULONG ShimDll : 1;
                ULONG InExceptionTable : 1;
                ULONG ReservedFlags1 : 2;
                ULONG LoadInProgress : 1;
                ULONG LoadConfigProcessed : 1;
                ULONG EntryProcessed : 1;
                ULONG ProtectDelayLoad : 1;
                ULONG ReservedFlags3 : 2;
                ULONG DontCallForThreads : 1;
                ULONG ProcessAttachCalled : 1;
                ULONG ProcessAttachFailed : 1;
                ULONG CorDeferredValidate : 1;
                ULONG CorImage : 1;
                ULONG DontRelocate : 1;
                ULONG CorILOnly : 1;
                ULONG ChpeImage : 1;
                ULONG ReservedFlags5 : 2;
                ULONG Redirected : 1;
                ULONG ReservedFlags6 : 2;
                ULONG CompatDatabaseProcessed : 1;
            };
        };
        USHORT ObsoleteLoadCount;
        USHORT TlsIndex;
        LIST_ENTRY32 HashLinks;
        ULONG TimeDateStamp;
        WOW64_POINTER(struct _ACTIVATION_CONTEXT*) EntryPointActivationContext;
        WOW64_POINTER(PVOID) Lock;
        WOW64_POINTER(PLDR_DDAG_NODE) DdagNode;
        LIST_ENTRY32 NodeModuleLink;
        WOW64_POINTER(struct _LDRP_LOAD_CONTEXT*) LoadContext;
        WOW64_POINTER(PVOID) ParentDllBase;
        WOW64_POINTER(PVOID) SwitchBackContext;
        RTL_BALANCED_NODE32 BaseAddressIndexNode;
        RTL_BALANCED_NODE32 MappingInfoIndexNode;
        WOW64_POINTER(ULONG_PTR) OriginalBase;
        LARGE_INTEGER LoadTime;
        ULONG BaseNameHashValue;
        LDR_DLL_LOAD_REASON LoadReason;
        ULONG ImplicitPathOptions;
        ULONG ReferenceCount;
        ULONG DependentLoadFlags;
        UCHAR SigningLevel; // since REDSTONE2
        ULONG CheckSum; // since 22H1
        WOW64_POINTER(PVOID) ActivePatchImageBase;
        LDR_HOT_PATCH_STATE HotPatchState;
    } LDR_DATA_TABLE_ENTRY32, * PLDR_DATA_TABLE_ENTRY32;

    typedef struct _CURDIR32
    {
        UNICODE_STRING32 DosPath;
        WOW64_POINTER(HANDLE) Handle;
    } CURDIR32, * PCURDIR32;

    typedef struct _RTL_DRIVE_LETTER_CURDIR32
    {
        USHORT Flags;
        USHORT Length;
        ULONG TimeStamp;
        STRING32 DosPath;
    } RTL_DRIVE_LETTER_CURDIR32, * PRTL_DRIVE_LETTER_CURDIR32;

    typedef struct _RTL_USER_PROCESS_PARAMETERS32
    {
        ULONG MaximumLength;
        ULONG Length;

        ULONG Flags;
        ULONG DebugFlags;

        WOW64_POINTER(HANDLE) ConsoleHandle;
        ULONG ConsoleFlags;
        WOW64_POINTER(HANDLE) StandardInput;
        WOW64_POINTER(HANDLE) StandardOutput;
        WOW64_POINTER(HANDLE) StandardError;

        CURDIR32 CurrentDirectory;
        UNICODE_STRING32 DllPath;
        UNICODE_STRING32 ImagePathName;
        UNICODE_STRING32 CommandLine;
        WOW64_POINTER(PVOID) Environment;

        ULONG StartingX;
        ULONG StartingY;
        ULONG CountX;
        ULONG CountY;
        ULONG CountCharsX;
        ULONG CountCharsY;
        ULONG FillAttribute;

        ULONG WindowFlags;
        ULONG ShowWindowFlags;
        UNICODE_STRING32 WindowTitle;
        UNICODE_STRING32 DesktopInfo;
        UNICODE_STRING32 ShellInfo;
        UNICODE_STRING32 RuntimeData;
        RTL_DRIVE_LETTER_CURDIR32 CurrentDirectories[RTL_MAX_DRIVE_LETTERS];

        WOW64_POINTER(ULONG_PTR) EnvironmentSize;
        WOW64_POINTER(ULONG_PTR) EnvironmentVersion;
        WOW64_POINTER(PVOID) PackageDependencyData;
        ULONG ProcessGroupId;
        ULONG LoaderThreads;

        UNICODE_STRING32 RedirectionDllName; // REDSTONE4
        UNICODE_STRING32 HeapPartitionName; // 19H1
        WOW64_POINTER(ULONG_PTR) DefaultThreadpoolCpuSetMasks;
        ULONG DefaultThreadpoolCpuSetMaskCount;
        ULONG DefaultThreadpoolThreadMaximum;
    } RTL_USER_PROCESS_PARAMETERS32, * PRTL_USER_PROCESS_PARAMETERS32;

    typedef struct _LEAP_SECOND_DATA* PLEAP_SECOND_DATA;

    typedef struct _PEB32
    {
        BOOLEAN InheritedAddressSpace;
        BOOLEAN ReadImageFileExecOptions;
        BOOLEAN BeingDebugged;
        union
        {
            BOOLEAN BitField;
            struct
            {
                BOOLEAN ImageUsesLargePages : 1;
                BOOLEAN IsProtectedProcess : 1;
                BOOLEAN IsImageDynamicallyRelocated : 1;
                BOOLEAN SkipPatchingUser32Forwarders : 1;
                BOOLEAN IsPackagedProcess : 1;
                BOOLEAN IsAppContainer : 1;
                BOOLEAN IsProtectedProcessLight : 1;
                BOOLEAN IsLongPathAwareProcess : 1;
            };
        };
        WOW64_POINTER(HANDLE) Mutant;

        WOW64_POINTER(PVOID) ImageBaseAddress;
        WOW64_POINTER(PPEB_LDR_DATA) Ldr;
        WOW64_POINTER(PRTL_USER_PROCESS_PARAMETERS) ProcessParameters;
        WOW64_POINTER(PVOID) SubSystemData;
        WOW64_POINTER(PVOID) ProcessHeap;
        WOW64_POINTER(PRTL_CRITICAL_SECTION) FastPebLock;
        WOW64_POINTER(PVOID) AtlThunkSListPtr;
        WOW64_POINTER(PVOID) IFEOKey;
        union
        {
            ULONG CrossProcessFlags;
            struct
            {
                ULONG ProcessInJob : 1;
                ULONG ProcessInitializing : 1;
                ULONG ProcessUsingVEH : 1;
                ULONG ProcessUsingVCH : 1;
                ULONG ProcessUsingFTH : 1;
                ULONG ReservedBits0 : 27;
            };
        };
        union
        {
            WOW64_POINTER(PVOID) KernelCallbackTable;
            WOW64_POINTER(PVOID) UserSharedInfoPtr;
        };
        ULONG SystemReserved;
        ULONG AtlThunkSListPtr32;
        WOW64_POINTER(PVOID) ApiSetMap;
        ULONG TlsExpansionCounter;
        WOW64_POINTER(PVOID) TlsBitmap;
        ULONG TlsBitmapBits[2];
        WOW64_POINTER(PVOID) ReadOnlySharedMemoryBase;
        WOW64_POINTER(PVOID) HotpatchInformation;
        WOW64_POINTER(PVOID*) ReadOnlyStaticServerData;
        WOW64_POINTER(PVOID) AnsiCodePageData;
        WOW64_POINTER(PVOID) OemCodePageData;
        WOW64_POINTER(PVOID) UnicodeCaseTableData;

        ULONG NumberOfProcessors;
        ULONG NtGlobalFlag;

        LARGE_INTEGER CriticalSectionTimeout;
        WOW64_POINTER(SIZE_T) HeapSegmentReserve;
        WOW64_POINTER(SIZE_T) HeapSegmentCommit;
        WOW64_POINTER(SIZE_T) HeapDeCommitTotalFreeThreshold;
        WOW64_POINTER(SIZE_T) HeapDeCommitFreeBlockThreshold;

        ULONG NumberOfHeaps;
        ULONG MaximumNumberOfHeaps;
        WOW64_POINTER(PVOID*) ProcessHeaps;

        WOW64_POINTER(PVOID) GdiSharedHandleTable;
        WOW64_POINTER(PVOID) ProcessStarterHelper;
        ULONG GdiDCAttributeList;

        WOW64_POINTER(PRTL_CRITICAL_SECTION) LoaderLock;

        ULONG OSMajorVersion;
        ULONG OSMinorVersion;
        USHORT OSBuildNumber;
        USHORT OSCSDVersion;
        ULONG OSPlatformId;
        ULONG ImageSubsystem;
        ULONG ImageSubsystemMajorVersion;
        ULONG ImageSubsystemMinorVersion;
        WOW64_POINTER(ULONG_PTR) ActiveProcessAffinityMask;
        GDI_HANDLE_BUFFER32 GdiHandleBuffer;
        WOW64_POINTER(PVOID) PostProcessInitRoutine;

        WOW64_POINTER(PVOID) TlsExpansionBitmap;
        ULONG TlsExpansionBitmapBits[32];

        ULONG SessionId;

        ULARGE_INTEGER AppCompatFlags;
        ULARGE_INTEGER AppCompatFlagsUser;
        WOW64_POINTER(PVOID) pShimData;
        WOW64_POINTER(PVOID) AppCompatInfo;

        UNICODE_STRING32 CSDVersion;

        WOW64_POINTER(PACTIVATION_CONTEXT_DATA) ActivationContextData;
        WOW64_POINTER(PVOID) ProcessAssemblyStorageMap;
        WOW64_POINTER(PACTIVATION_CONTEXT_DATA) SystemDefaultActivationContextData;
        WOW64_POINTER(PVOID) SystemAssemblyStorageMap;

        WOW64_POINTER(SIZE_T) MinimumStackCommit;

        WOW64_POINTER(PVOID) SparePointers[2]; // 19H1 (previously FlsCallback to FlsHighIndex)
        WOW64_POINTER(PVOID) PatchLoaderData;
        WOW64_POINTER(PVOID) ChpeV2ProcessInfo; // _CHPEV2_PROCESS_INFO

        ULONG AppModelFeatureState;
        ULONG SpareUlongs[2];

        USHORT ActiveCodePage;
        USHORT OemCodePage;
        USHORT UseCaseMapping;
        USHORT UnusedNlsField;

        WOW64_POINTER(PVOID) WerRegistrationData;
        WOW64_POINTER(PVOID) WerShipAssertPtr;

        union
        {
            WOW64_POINTER(PVOID) pContextData; // WIN7
            WOW64_POINTER(PVOID) pUnused; // WIN10
            WOW64_POINTER(PVOID) EcCodeBitMap; // WIN11
        };

        WOW64_POINTER(PVOID) pImageHeaderHash;
        union
        {
            ULONG TracingFlags;
            struct
            {
                ULONG HeapTracingEnabled : 1;
                ULONG CritSecTracingEnabled : 1;
                ULONG LibLoaderTracingEnabled : 1;
                ULONG SpareTracingBits : 29;
            };
        };
        ULONGLONG CsrServerReadOnlySharedMemoryBase;
        WOW64_POINTER(PVOID) TppWorkerpListLock;
        LIST_ENTRY32 TppWorkerpList;
        WOW64_POINTER(PVOID) WaitOnAddressHashTable[128];
        WOW64_POINTER(PVOID) TelemetryCoverageHeader; // REDSTONE3
        ULONG CloudFileFlags;
        ULONG CloudFileDiagFlags; // REDSTONE4
        CHAR PlaceholderCompatibilityMode;
        CHAR PlaceholderCompatibilityModeReserved[7];
        WOW64_POINTER(PLEAP_SECOND_DATA) LeapSecondData; // REDSTONE5
        union
        {
            ULONG LeapSecondFlags;
            struct
            {
                ULONG SixtySecondEnabled : 1;
                ULONG Reserved : 31;
            };
        };
        ULONG NtGlobalFlag2;
        ULONGLONG ExtendedFeatureDisableMask; // since WIN11
    } PEB32, * PPEB32;

    //C_ASSERT(sizeof(PEB32) == 0x460); // REDSTONE3
    //C_ASSERT(sizeof(PEB32) == 0x470); // REDSTONE5
    C_ASSERT(sizeof(PEB32) == 0x488); // WIN11

    // Note: Use PhGetProcessPeb32 instead. (dmex)
    //#define WOW64_GET_PEB32(peb64) ((PPEB32)PTR_ADD_OFFSET((peb64), ALIGN_UP_BY(sizeof(PEB), PAGE_SIZE)))

#define GDI_BATCH_BUFFER_SIZE 310

    typedef struct _GDI_TEB_BATCH32
    {
        ULONG Offset;
        WOW64_POINTER(ULONG_PTR) HDC;
        ULONG Buffer[GDI_BATCH_BUFFER_SIZE];
    } GDI_TEB_BATCH32, * PGDI_TEB_BATCH32;

    typedef struct _TEB32
    {
        NT_TIB32 NtTib;

        WOW64_POINTER(PVOID) EnvironmentPointer;
        CLIENT_ID32 ClientId;
        WOW64_POINTER(PVOID) ActiveRpcHandle;
        WOW64_POINTER(PVOID) ThreadLocalStoragePointer;
        WOW64_POINTER(PPEB) ProcessEnvironmentBlock;

        ULONG LastErrorValue;
        ULONG CountOfOwnedCriticalSections;
        WOW64_POINTER(PVOID) CsrClientThread;
        WOW64_POINTER(PVOID) Win32ThreadInfo;
        ULONG User32Reserved[26];
        ULONG UserReserved[5];
        WOW64_POINTER(PVOID) WOW32Reserved;
        LCID CurrentLocale;
        ULONG FpSoftwareStatusRegister;
        WOW64_POINTER(PVOID) ReservedForDebuggerInstrumentation[16];
        WOW64_POINTER(PVOID) SystemReserved1[36];
        UCHAR WorkingOnBehalfTicket[8];
        NTSTATUS ExceptionCode;

        WOW64_POINTER(PVOID) ActivationContextStackPointer;
        WOW64_POINTER(ULONG_PTR) InstrumentationCallbackSp;
        WOW64_POINTER(ULONG_PTR) InstrumentationCallbackPreviousPc;
        WOW64_POINTER(ULONG_PTR) InstrumentationCallbackPreviousSp;
        BOOLEAN InstrumentationCallbackDisabled;
        UCHAR SpareBytes[23];
        ULONG TxFsContext;

        GDI_TEB_BATCH32 GdiTebBatch;
        CLIENT_ID32 RealClientId;
        WOW64_POINTER(HANDLE) GdiCachedProcessHandle;
        ULONG GdiClientPID;
        ULONG GdiClientTID;
        WOW64_POINTER(PVOID) GdiThreadLocalInfo;
        WOW64_POINTER(ULONG_PTR) Win32ClientInfo[62];
        WOW64_POINTER(PVOID) glDispatchTable[233];
        WOW64_POINTER(ULONG_PTR) glReserved1[29];
        WOW64_POINTER(PVOID) glReserved2;
        WOW64_POINTER(PVOID) glSectionInfo;
        WOW64_POINTER(PVOID) glSection;
        WOW64_POINTER(PVOID) glTable;
        WOW64_POINTER(PVOID) glCurrentRC;
        WOW64_POINTER(PVOID) glContext;

        NTSTATUS LastStatusValue;
        UNICODE_STRING32 StaticUnicodeString;
        WCHAR StaticUnicodeBuffer[261];

        WOW64_POINTER(PVOID) DeallocationStack;
        WOW64_POINTER(PVOID) TlsSlots[64];
        LIST_ENTRY32 TlsLinks;

        WOW64_POINTER(PVOID) Vdm;
        WOW64_POINTER(PVOID) ReservedForNtRpc;
        WOW64_POINTER(PVOID) DbgSsReserved[2];

        ULONG HardErrorMode;
        WOW64_POINTER(PVOID) Instrumentation[9];
        GUID ActivityId;

        WOW64_POINTER(PVOID) SubProcessTag;
        WOW64_POINTER(PVOID) PerflibData;
        WOW64_POINTER(PVOID) EtwTraceData;
        WOW64_POINTER(PVOID) WinSockData;
        ULONG GdiBatchCount;

        union
        {
            PROCESSOR_NUMBER CurrentIdealProcessor;
            ULONG IdealProcessorValue;
            struct
            {
                UCHAR ReservedPad0;
                UCHAR ReservedPad1;
                UCHAR ReservedPad2;
                UCHAR IdealProcessor;
            };
        };

        ULONG GuaranteedStackBytes;
        WOW64_POINTER(PVOID) ReservedForPerf;
        WOW64_POINTER(PVOID) ReservedForOle;
        ULONG WaitingOnLoaderLock;
        WOW64_POINTER(PVOID) SavedPriorityState;
        WOW64_POINTER(ULONG_PTR) ReservedForCodeCoverage;
        WOW64_POINTER(PVOID) ThreadPoolData;
        WOW64_POINTER(PVOID*) TlsExpansionSlots;

        ULONG MuiGeneration;
        ULONG IsImpersonating;
        WOW64_POINTER(PVOID) NlsCache;
        WOW64_POINTER(PVOID) pShimData;
        USHORT HeapVirtualAffinity;
        USHORT LowFragHeapDataSlot;
        WOW64_POINTER(HANDLE) CurrentTransactionHandle;
        WOW64_POINTER(PTEB_ACTIVE_FRAME) ActiveFrame;
        WOW64_POINTER(PVOID) FlsData;

        WOW64_POINTER(PVOID) PreferredLanguages;
        WOW64_POINTER(PVOID) UserPrefLanguages;
        WOW64_POINTER(PVOID) MergedPrefLanguages;
        ULONG MuiImpersonation;

        union
        {
            USHORT CrossTebFlags;
            USHORT SpareCrossTebBits : 16;
        };
        union
        {
            USHORT SameTebFlags;
            struct
            {
                USHORT SafeThunkCall : 1;
                USHORT InDebugPrint : 1;
                USHORT HasFiberData : 1;
                USHORT SkipThreadAttach : 1;
                USHORT WerInShipAssertCode : 1;
                USHORT RanProcessInit : 1;
                USHORT ClonedThread : 1;
                USHORT SuppressDebugMsg : 1;
                USHORT DisableUserStackWalk : 1;
                USHORT RtlExceptionAttached : 1;
                USHORT InitialThread : 1;
                USHORT SessionAware : 1;
                USHORT LoadOwner : 1;
                USHORT LoaderWorker : 1;
                USHORT SpareSameTebBits : 2;
            };
        };

        WOW64_POINTER(PVOID) TxnScopeEnterCallback;
        WOW64_POINTER(PVOID) TxnScopeExitCallback;
        WOW64_POINTER(PVOID) TxnScopeContext;
        ULONG LockCount;
        LONG WowTebOffset;
        WOW64_POINTER(PVOID) ResourceRetValue;
        WOW64_POINTER(PVOID) ReservedForWdf;
        ULONGLONG ReservedForCrt;
        GUID EffectiveContainerId;
    } TEB32, * PTEB32;

    C_ASSERT(FIELD_OFFSET(TEB32, ProcessEnvironmentBlock) == 0x030);
    C_ASSERT(FIELD_OFFSET(TEB32, ExceptionCode) == 0x1a4);
    C_ASSERT(FIELD_OFFSET(TEB32, TxFsContext) == 0x1d0);
    C_ASSERT(FIELD_OFFSET(TEB32, glContext) == 0xbf0);
    C_ASSERT(FIELD_OFFSET(TEB32, StaticUnicodeBuffer) == 0xc00);
    C_ASSERT(FIELD_OFFSET(TEB32, TlsLinks) == 0xf10);
    C_ASSERT(FIELD_OFFSET(TEB32, DbgSsReserved) == 0xf20);
    C_ASSERT(FIELD_OFFSET(TEB32, ActivityId) == 0xf50);
    C_ASSERT(FIELD_OFFSET(TEB32, GdiBatchCount) == 0xf70);
    C_ASSERT(FIELD_OFFSET(TEB32, TlsExpansionSlots) == 0xf94);
    C_ASSERT(FIELD_OFFSET(TEB32, FlsData) == 0xfb4);
    C_ASSERT(FIELD_OFFSET(TEB32, MuiImpersonation) == 0xfc4);
    C_ASSERT(FIELD_OFFSET(TEB32, ReservedForCrt) == 0xfe8);
    C_ASSERT(FIELD_OFFSET(TEB32, EffectiveContainerId) == 0xff0);
    C_ASSERT(sizeof(TEB32) == 0x1000);

    // Conversion

    FORCEINLINE VOID UStr32ToUStr(
        _Out_ PUNICODE_STRING Destination,
        _In_ PUNICODE_STRING32 Source
    )
    {
        Destination->Length = Source->Length;
        Destination->MaximumLength = Source->MaximumLength;
        Destination->Buffer = (PWCH)UlongToPtr(Source->Buffer);
    }

    FORCEINLINE VOID UStrToUStr32(
        _Out_ PUNICODE_STRING32 Destination,
        _In_ PUNICODE_STRING Source
    )
    {
        Destination->Length = Source->Length;
        Destination->MaximumLength = Source->MaximumLength;
        Destination->Buffer = PtrToUlong(Source->Buffer);
    }

    // The Wow64Info structure follows the PEB32/TEB32 structures and is shared between 32-bit and 64-bit modules inside a Wow64 process.
    // from SDK/10.0.10240.0/um/minwin/wow64t.h (dmex)
    //
    // Page size on x86 NT
    //
#define PAGE_SIZE_X86NT 0x1000
#define PAGE_SHIFT_X86NT 12L
#define WOW64_SPLITS_PER_PAGE (PAGE_SIZE_X86NT / PAGE_SIZE_X86NT)

//
// Convert the number of native pages to sub x86-pages
//
#define Wow64GetNumberOfX86Pages(NativePages) \
    (NativePages * (PAGE_SIZE_X86NT >> PAGE_SHIFT_X86NT))

//
// Macro to round to the nearest page size
//
#define WOW64_ROUND_TO_PAGES(Size) \
    (((ULONG_PTR)(Size) + PAGE_SIZE_X86NT - 1) & ~(PAGE_SIZE_X86NT - 1))

//
// Get number of native pages
//
#define WOW64_BYTES_TO_PAGES(Size) \
    (((ULONG)(Size) >> WOW64_ROUND_TO_PAGES) + (((ULONG)(Size) & (PAGE_SIZE_X86NT - 1)) != 0))

//
// Get the 32-bit TEB without doing a memory reference.
//
#define WOW64_GET_TEB32(teb64) ((PTEB32)(PVOID)RtlOffsetToPointer((teb64), WOW64_ROUND_TO_PAGES(sizeof(TEB))))
#define WOW64_TEB32_POINTER_ADDRESS(teb64) (PVOID)&((teb64)->NtTib.ExceptionList)

    typedef union _WOW64_EXECUTE_OPTIONS
    {
        ULONG Flags;
        struct
        {
            ULONG StackReserveSize : 8;
            ULONG StackCommitSize : 4;
            ULONG Deprecated0 : 1;
            ULONG DisableWowAssert : 1;
            ULONG DisableTurboDispatch : 1;
            ULONG Unused : 13;
            ULONG Reserved0 : 1;
            ULONG Reserved1 : 1;
            ULONG Reserved2 : 1;
            ULONG Reserved3 : 1;
        };
    } WOW64_EXECUTE_OPTIONS, * PWOW64_EXECUTE_OPTIONS;

#define WOW64_CPUFLAGS_MSFT64           0x00000001
#define WOW64_CPUFLAGS_SOFTWARE         0x00000002
#define WOW64_CPUFLAGS_IA64             0x00000004

    typedef struct _WOW64INFO
    {
        ULONG NativeSystemPageSize;
        ULONG CpuFlags;
        WOW64_EXECUTE_OPTIONS Wow64ExecuteFlags;
        ULONG InstrumentationCallback;
    } WOW64INFO, * PWOW64INFO;

    typedef struct _PEB32_WITH_WOW64INFO
    {
        PEB32 Peb32;
        WOW64INFO Wow64Info;
    } PEB32_WITH_WOW64INFO, * PPEB32_WITH_WOW64INFO;

#if (PHNT_MODE != PHNT_MODE_KERNEL)
#ifdef _M_X64

    FORCEINLINE
        TEB32*
        POINTER_UNSIGNED
        Wow64CurrentGuestTeb(
            VOID
        )
    {
        TEB* POINTER_UNSIGNED Teb;
        TEB32* POINTER_UNSIGNED Teb32;

        Teb = NtCurrentTeb();

        if (Teb->WowTebOffset == 0)
        {
            //
            // Not running under or over WoW, so there is no "guest teb"
            //

            return NULL;
        }

        if (Teb->WowTebOffset < 0)
        {
            //
            // Was called while running under WoW. The current teb is the guest
            // teb.
            //

            Teb32 = (PTEB32)Teb;

            RTL_ASSERT(&Teb32->WowTebOffset == &Teb->WowTebOffset);
        }
        else
        {
            //
            // Called by the WoW Host, so calculate the position of the guest teb
            // relative to the current (host) teb.
            //

            Teb32 = (PTEB32)RtlOffsetToPointer(Teb, Teb->WowTebOffset);
        }

        RTL_ASSERT(Teb32->NtTib.Self == PtrToUlong(Teb32));

        return Teb32;
    }

    FORCEINLINE
        VOID*
        POINTER_UNSIGNED
        Wow64CurrentNativeTeb(
            VOID
        )
    {
        TEB* POINTER_UNSIGNED Teb;
        VOID* POINTER_UNSIGNED HostTeb;

        Teb = NtCurrentTeb();

        if (Teb->WowTebOffset >= 0)
        {
            //
            // Not running under WoW, so it it either not running on WoW at all, or
            // it is the host. Return the current teb as native teb.
            //

            HostTeb = (PVOID)Teb;
        }
        else
        {
            //
            // Called while runnign under WoW Host, so calculate the position of the
            // host teb relative to the current (guest) teb.
            //

            HostTeb = (PVOID)RtlOffsetToPointer(Teb, Teb->WowTebOffset);
        }

        RTL_ASSERT((((PTEB32)HostTeb)->NtTib.Self == PtrToUlong(HostTeb)) || ((ULONG_PTR)((PTEB)HostTeb)->NtTib.Self == (ULONG_PTR)HostTeb));

        return HostTeb;
    }

#define NtCurrentTeb32() (Wow64CurrentGuestTeb())
#define NtCurrentPeb32()  ((PPEB32)(UlongToPtr((NtCurrentTeb32()->ProcessEnvironmentBlock))))

#define Wow64GetNativeTebField(teb, field) (((ULONG)(teb) == ((PTEB32)(teb))->NtTib.Self) ? (((PTEB32)(teb))->##field) : (((PTEB)(teb))->##field) )
#define Wow64SetNativeTebField(teb, field, value) { if ((ULONG)(teb) == ((PTEB32)(teb))->NtTib.Self) {(((PTEB32)(teb))->##field) = (value);} else {(((PTEB)(teb))->##field) = (value);} }

#endif
#endif

#endif

#include <ntlsa.h>
    /*
     * Security Account Manager support functions
     *
     * This file is part of System Informer.
     */

#ifndef _NTSAM_H
#define _NTSAM_H

#define SAM_MAXIMUM_LOOKUP_COUNT (1000)
#define SAM_MAXIMUM_LOOKUP_LENGTH (32000)
#define SAM_MAX_PASSWORD_LENGTH (256)
#define SAM_PASSWORD_ENCRYPTION_SALT_LEN (16)

    typedef PVOID SAM_HANDLE, * PSAM_HANDLE;
    typedef ULONG SAM_ENUMERATE_HANDLE, * PSAM_ENUMERATE_HANDLE;

    typedef struct _SAM_RID_ENUMERATION
    {
        ULONG RelativeId;
        UNICODE_STRING Name;
    } SAM_RID_ENUMERATION, * PSAM_RID_ENUMERATION;

    typedef struct _SAM_SID_ENUMERATION
    {
        PSID Sid;
        UNICODE_STRING Name;
    } SAM_SID_ENUMERATION, * PSAM_SID_ENUMERATION;

    typedef struct _SAM_BYTE_ARRAY
    {
        ULONG Size;
        _Field_size_bytes_(Size) PUCHAR Data;
    } SAM_BYTE_ARRAY, * PSAM_BYTE_ARRAY;

    typedef struct _SAM_BYTE_ARRAY_32K
    {
        ULONG Size;
        _Field_size_bytes_(Size) PUCHAR Data;
    } SAM_BYTE_ARRAY_32K, * PSAM_BYTE_ARRAY_32K;

    typedef SAM_BYTE_ARRAY_32K SAM_SHELL_OBJECT_PROPERTIES, * PSAM_SHELL_OBJECT_PROPERTIES;

    // Basic

    NTSTATUS
        NTAPI
        SamFreeMemory(
            _In_ PVOID Buffer
        );

    NTSTATUS
        NTAPI
        SamCloseHandle(
            _In_ SAM_HANDLE SamHandle
        );

    _Check_return_
        NTSTATUS
        NTAPI
        SamSetSecurityObject(
            _In_ SAM_HANDLE ObjectHandle,
            _In_ SECURITY_INFORMATION SecurityInformation,
            _In_ PSECURITY_DESCRIPTOR SecurityDescriptor
        );

    _Check_return_
        NTSTATUS
        NTAPI
        SamQuerySecurityObject(
            _In_ SAM_HANDLE ObjectHandle,
            _In_ SECURITY_INFORMATION SecurityInformation,
            _Outptr_ PSECURITY_DESCRIPTOR* SecurityDescriptor
        );

    _Check_return_
        NTSTATUS
        NTAPI
        SamRidToSid(
            _In_ SAM_HANDLE ObjectHandle,
            _In_ ULONG Rid,
            _Outptr_ PSID* Sid
        );

    // Server

#define SAM_SERVER_CONNECT 0x0001
#define SAM_SERVER_SHUTDOWN 0x0002
#define SAM_SERVER_INITIALIZE 0x0004
#define SAM_SERVER_CREATE_DOMAIN 0x0008
#define SAM_SERVER_ENUMERATE_DOMAINS 0x0010
#define SAM_SERVER_LOOKUP_DOMAIN 0x0020

#define SAM_SERVER_ALL_ACCESS (STANDARD_RIGHTS_REQUIRED     | \
    SAM_SERVER_CONNECT | \
    SAM_SERVER_INITIALIZE | \
    SAM_SERVER_CREATE_DOMAIN | \
    SAM_SERVER_SHUTDOWN | \
    SAM_SERVER_ENUMERATE_DOMAINS | \
    SAM_SERVER_LOOKUP_DOMAIN)

#define SAM_SERVER_READ (STANDARD_RIGHTS_READ | \
    SAM_SERVER_ENUMERATE_DOMAINS)

#define SAM_SERVER_WRITE (STANDARD_RIGHTS_WRITE | \
    SAM_SERVER_INITIALIZE | \
    SAM_SERVER_CREATE_DOMAIN | \
    SAM_SERVER_SHUTDOWN)

#define SAM_SERVER_EXECUTE (STANDARD_RIGHTS_EXECUTE | \
    SAM_SERVER_CONNECT | \
    SAM_SERVER_LOOKUP_DOMAIN)

    typedef struct _RPC_AUTH_IDENTITY_HANDLE* PRPC_AUTH_IDENTITY_HANDLE;

    // Functions

    _Check_return_
        NTSTATUS
        NTAPI
        SamConnect(
            _In_opt_ PUNICODE_STRING ServerName,
            _Out_ PSAM_HANDLE ServerHandle,
            _In_ ACCESS_MASK DesiredAccess,
            _In_ POBJECT_ATTRIBUTES ObjectAttributes
        );

    _Check_return_
        NTSTATUS
        NTAPI
        SamConnectWithCreds(
            _In_ PUNICODE_STRING ServerName,
            _Out_ PSAM_HANDLE ServerHandle,
            _In_ ACCESS_MASK DesiredAccess,
            _In_ POBJECT_ATTRIBUTES ObjectAttributes,
            _In_ PRPC_AUTH_IDENTITY_HANDLE Creds,
            _In_ PWCHAR Spn,
            _Out_ BOOL* pfDstIsW2K
        );

    _Check_return_
        NTSTATUS
        NTAPI
        SamShutdownSamServer(
            _In_ SAM_HANDLE ServerHandle
        );

    // Domain

#define DOMAIN_READ_PASSWORD_PARAMETERS 0x0001
#define DOMAIN_WRITE_PASSWORD_PARAMS 0x0002
#define DOMAIN_READ_OTHER_PARAMETERS 0x0004
#define DOMAIN_WRITE_OTHER_PARAMETERS 0x0008
#define DOMAIN_CREATE_USER 0x0010
#define DOMAIN_CREATE_GROUP 0x0020
#define DOMAIN_CREATE_ALIAS 0x0040
#define DOMAIN_GET_ALIAS_MEMBERSHIP 0x0080
#define DOMAIN_LIST_ACCOUNTS 0x0100
#define DOMAIN_LOOKUP 0x0200
#define DOMAIN_ADMINISTER_SERVER 0x0400

#define DOMAIN_ALL_ACCESS (STANDARD_RIGHTS_REQUIRED | \
    DOMAIN_READ_OTHER_PARAMETERS | \
    DOMAIN_WRITE_OTHER_PARAMETERS | \
    DOMAIN_WRITE_PASSWORD_PARAMS | \
    DOMAIN_CREATE_USER | \
    DOMAIN_CREATE_GROUP | \
    DOMAIN_CREATE_ALIAS | \
    DOMAIN_GET_ALIAS_MEMBERSHIP | \
    DOMAIN_LIST_ACCOUNTS | \
    DOMAIN_READ_PASSWORD_PARAMETERS | \
    DOMAIN_LOOKUP | \
    DOMAIN_ADMINISTER_SERVER)

#define DOMAIN_READ (STANDARD_RIGHTS_READ | \
    DOMAIN_GET_ALIAS_MEMBERSHIP | \
    DOMAIN_READ_OTHER_PARAMETERS)

#define DOMAIN_WRITE (STANDARD_RIGHTS_WRITE | \
    DOMAIN_WRITE_OTHER_PARAMETERS | \
    DOMAIN_WRITE_PASSWORD_PARAMS | \
    DOMAIN_CREATE_USER | \
    DOMAIN_CREATE_GROUP | \
    DOMAIN_CREATE_ALIAS | \
    DOMAIN_ADMINISTER_SERVER)

#define DOMAIN_EXECUTE (STANDARD_RIGHTS_EXECUTE | \
    DOMAIN_READ_PASSWORD_PARAMETERS | \
    DOMAIN_LIST_ACCOUNTS | \
    DOMAIN_LOOKUP)

#define DOMAIN_PROMOTION_INCREMENT { 0x0, 0x10 }
#define DOMAIN_PROMOTION_MASK { 0x0, 0xfffffff0 }

// SamQueryInformationDomain/SamSetInformationDomain types

    typedef enum _DOMAIN_INFORMATION_CLASS
    {
        DomainPasswordInformation = 1, // q; s: DOMAIN_PASSWORD_INFORMATION
        DomainGeneralInformation, // q: DOMAIN_GENERAL_INFORMATION
        DomainLogoffInformation, // q; s: DOMAIN_LOGOFF_INFORMATION
        DomainOemInformation, // q; s: DOMAIN_OEM_INFORMATION
        DomainNameInformation, // q: DOMAIN_NAME_INFORMATION
        DomainReplicationInformation, // q; s: DOMAIN_REPLICATION_INFORMATION
        DomainServerRoleInformation, // q; s: DOMAIN_SERVER_ROLE_INFORMATION
        DomainModifiedInformation, // q: DOMAIN_MODIFIED_INFORMATION
        DomainStateInformation, // q; s: DOMAIN_STATE_INFORMATION
        DomainUasInformation, // q; s: DOMAIN_UAS_INFORMATION
        DomainGeneralInformation2, // q: DOMAIN_GENERAL_INFORMATION2
        DomainLockoutInformation, // q; s: DOMAIN_LOCKOUT_INFORMATION
        DomainModifiedInformation2 // q: DOMAIN_MODIFIED_INFORMATION2
    } DOMAIN_INFORMATION_CLASS;

    typedef enum _DOMAIN_SERVER_ENABLE_STATE
    {
        DomainServerEnabled = 1,
        DomainServerDisabled
    } DOMAIN_SERVER_ENABLE_STATE, * PDOMAIN_SERVER_ENABLE_STATE;

    typedef enum _DOMAIN_SERVER_ROLE
    {
        DomainServerRoleBackup = 2,
        DomainServerRolePrimary
    } DOMAIN_SERVER_ROLE, * PDOMAIN_SERVER_ROLE;

#include <pshpack4.h>
    typedef struct _DOMAIN_GENERAL_INFORMATION
    {
        LARGE_INTEGER ForceLogoff;
        UNICODE_STRING OemInformation;
        UNICODE_STRING DomainName;
        UNICODE_STRING ReplicaSourceNodeName;
        LARGE_INTEGER DomainModifiedCount;
        DOMAIN_SERVER_ENABLE_STATE DomainServerState;
        DOMAIN_SERVER_ROLE DomainServerRole;
        BOOLEAN UasCompatibilityRequired;
        ULONG UserCount;
        ULONG GroupCount;
        ULONG AliasCount;
    } DOMAIN_GENERAL_INFORMATION, * PDOMAIN_GENERAL_INFORMATION;
#include <poppack.h>

#include <pshpack4.h>
    typedef struct _DOMAIN_GENERAL_INFORMATION2
    {
        DOMAIN_GENERAL_INFORMATION I1;
        LARGE_INTEGER LockoutDuration; // delta time
        LARGE_INTEGER LockoutObservationWindow; // delta time
        USHORT LockoutThreshold;
    } DOMAIN_GENERAL_INFORMATION2, * PDOMAIN_GENERAL_INFORMATION2;
#include <poppack.h>

    typedef struct _DOMAIN_UAS_INFORMATION
    {
        BOOLEAN UasCompatibilityRequired;
    } DOMAIN_UAS_INFORMATION;

#ifndef _DOMAIN_PASSWORD_INFORMATION_DEFINED // defined in ntsecapi.h
#define _DOMAIN_PASSWORD_INFORMATION_DEFINED

    typedef struct _DOMAIN_PASSWORD_INFORMATION
    {
        USHORT MinPasswordLength;
        USHORT PasswordHistoryLength;
        ULONG PasswordProperties;
        LARGE_INTEGER MaxPasswordAge;
        LARGE_INTEGER MinPasswordAge;
    } DOMAIN_PASSWORD_INFORMATION, * PDOMAIN_PASSWORD_INFORMATION;

    // PasswordProperties flags

#define DOMAIN_PASSWORD_COMPLEX 0x00000001L
#define DOMAIN_PASSWORD_NO_ANON_CHANGE 0x00000002L
#define DOMAIN_PASSWORD_NO_CLEAR_CHANGE 0x00000004L
#define DOMAIN_LOCKOUT_ADMINS 0x00000008L
#define DOMAIN_PASSWORD_STORE_CLEARTEXT 0x00000010L
#define DOMAIN_REFUSE_PASSWORD_CHANGE 0x00000020L
#define DOMAIN_NO_LM_OWF_CHANGE 0x00000040L

#endif

    typedef enum _DOMAIN_PASSWORD_CONSTRUCTION
    {
        DomainPasswordSimple = 1,
        DomainPasswordComplex
    } DOMAIN_PASSWORD_CONSTRUCTION;

    typedef struct _DOMAIN_LOGOFF_INFORMATION
    {
        LARGE_INTEGER ForceLogoff;
    } DOMAIN_LOGOFF_INFORMATION, * PDOMAIN_LOGOFF_INFORMATION;

    typedef struct _DOMAIN_OEM_INFORMATION
    {
        UNICODE_STRING OemInformation;
    } DOMAIN_OEM_INFORMATION, * PDOMAIN_OEM_INFORMATION;

    typedef struct _DOMAIN_NAME_INFORMATION
    {
        UNICODE_STRING DomainName;
    } DOMAIN_NAME_INFORMATION, * PDOMAIN_NAME_INFORMATION;

    typedef struct _DOMAIN_SERVER_ROLE_INFORMATION
    {
        DOMAIN_SERVER_ROLE DomainServerRole;
    } DOMAIN_SERVER_ROLE_INFORMATION, * PDOMAIN_SERVER_ROLE_INFORMATION;

    typedef struct _DOMAIN_REPLICATION_INFORMATION
    {
        UNICODE_STRING ReplicaSourceNodeName;
    } DOMAIN_REPLICATION_INFORMATION, * PDOMAIN_REPLICATION_INFORMATION;

    typedef struct _DOMAIN_MODIFIED_INFORMATION
    {
        LARGE_INTEGER DomainModifiedCount;
        LARGE_INTEGER CreationTime;
    } DOMAIN_MODIFIED_INFORMATION, * PDOMAIN_MODIFIED_INFORMATION;

    typedef struct _DOMAIN_MODIFIED_INFORMATION2
    {
        LARGE_INTEGER DomainModifiedCount;
        LARGE_INTEGER CreationTime;
        LARGE_INTEGER ModifiedCountAtLastPromotion;
    } DOMAIN_MODIFIED_INFORMATION2, * PDOMAIN_MODIFIED_INFORMATION2;

    typedef struct _DOMAIN_STATE_INFORMATION
    {
        DOMAIN_SERVER_ENABLE_STATE DomainServerState;
    } DOMAIN_STATE_INFORMATION, * PDOMAIN_STATE_INFORMATION;

    typedef struct _DOMAIN_LOCKOUT_INFORMATION
    {
        LARGE_INTEGER LockoutDuration; // delta time
        LARGE_INTEGER LockoutObservationWindow; // delta time
        USHORT LockoutThreshold; // zero means no lockout
    } DOMAIN_LOCKOUT_INFORMATION, * PDOMAIN_LOCKOUT_INFORMATION;

    // SamQueryDisplayInformation types

    typedef enum _DOMAIN_DISPLAY_INFORMATION
    {
        DomainDisplayUser = 1, // DOMAIN_DISPLAY_USER
        DomainDisplayMachine, // DOMAIN_DISPLAY_MACHINE
        DomainDisplayGroup, // DOMAIN_DISPLAY_GROUP
        DomainDisplayOemUser, // DOMAIN_DISPLAY_OEM_USER
        DomainDisplayOemGroup, // DOMAIN_DISPLAY_OEM_GROUP
        DomainDisplayServer
    } DOMAIN_DISPLAY_INFORMATION, * PDOMAIN_DISPLAY_INFORMATION;

    typedef struct _DOMAIN_DISPLAY_USER
    {
        ULONG Index;
        ULONG Rid;
        ULONG AccountControl;
        UNICODE_STRING LogonName;
        UNICODE_STRING AdminComment;
        UNICODE_STRING FullName;
    } DOMAIN_DISPLAY_USER, * PDOMAIN_DISPLAY_USER;

    typedef struct _DOMAIN_DISPLAY_MACHINE
    {
        ULONG Index;
        ULONG Rid;
        ULONG AccountControl;
        UNICODE_STRING Machine;
        UNICODE_STRING Comment;
    } DOMAIN_DISPLAY_MACHINE, * PDOMAIN_DISPLAY_MACHINE;

    typedef struct _DOMAIN_DISPLAY_GROUP
    {
        ULONG Index;
        ULONG Rid;
        ULONG Attributes;
        UNICODE_STRING Group;
        UNICODE_STRING Comment;
    } DOMAIN_DISPLAY_GROUP, * PDOMAIN_DISPLAY_GROUP;

    typedef struct _DOMAIN_DISPLAY_OEM_USER
    {
        ULONG Index;
        OEM_STRING User;
    } DOMAIN_DISPLAY_OEM_USER, * PDOMAIN_DISPLAY_OEM_USER;

    typedef struct _DOMAIN_DISPLAY_OEM_GROUP
    {
        ULONG Index;
        OEM_STRING Group;
    } DOMAIN_DISPLAY_OEM_GROUP, * PDOMAIN_DISPLAY_OEM_GROUP;

    // SamQueryLocalizableAccountsInDomain types

    typedef enum _DOMAIN_LOCALIZABLE_ACCOUNTS_INFORMATION
    {
        DomainLocalizableAccountsBasic = 1,
    } DOMAIN_LOCALIZABLE_ACCOUNTS_INFORMATION, * PDOMAIN_LOCALIZABLE_ACCOUNTS_INFORMATION;

    typedef struct _DOMAIN_LOCALIZABLE_ACCOUNTS_ENTRY
    {
        ULONG Rid;
        SID_NAME_USE Use;
        UNICODE_STRING Name;
        UNICODE_STRING AdminComment;
    } DOMAIN_LOCALIZABLE_ACCOUNT_ENTRY, * PDOMAIN_LOCALIZABLE_ACCOUNT_ENTRY;

    typedef struct _DOMAIN_LOCALIZABLE_ACCOUNTS
    {
        ULONG Count;
        _Field_size_(Count) DOMAIN_LOCALIZABLE_ACCOUNT_ENTRY* Entries;
    } DOMAIN_LOCALIZABLE_ACCOUNTS_BASIC, * PDOMAIN_LOCALIZABLE_ACCOUNTS_BASIC;

    typedef union _DOMAIN_LOCALIZABLE_INFO_BUFFER
    {
        DOMAIN_LOCALIZABLE_ACCOUNTS_BASIC Basic;
    } DOMAIN_LOCALIZABLE_ACCOUNTS_INFO_BUFFER, * PDOMAIN_LOCALIZABLE_ACCOUNTS_INFO_BUFFER;

    // Functions

    _Check_return_
        NTSTATUS
        NTAPI
        SamLookupDomainInSamServer(
            _In_ SAM_HANDLE ServerHandle,
            _In_ PUNICODE_STRING Name,
            _Outptr_ PSID* DomainId
        );

    _Check_return_
        NTSTATUS
        NTAPI
        SamEnumerateDomainsInSamServer(
            _In_ SAM_HANDLE ServerHandle,
            _Inout_ PSAM_ENUMERATE_HANDLE EnumerationContext,
            _Outptr_ PVOID* Buffer, // PSAM_SID_ENUMERATION *Buffer
            _In_ ULONG PreferedMaximumLength,
            _Out_ PULONG CountReturned
        );

    _Check_return_
        NTSTATUS
        NTAPI
        SamOpenDomain(
            _In_ SAM_HANDLE ServerHandle,
            _In_ ACCESS_MASK DesiredAccess,
            _In_ PSID DomainId,
            _Out_ PSAM_HANDLE DomainHandle
        );

    _Check_return_
        NTSTATUS
        NTAPI
        SamQueryInformationDomain(
            _In_ SAM_HANDLE DomainHandle,
            _In_ DOMAIN_INFORMATION_CLASS DomainInformationClass,
            _Outptr_ PVOID* Buffer
        );

    _Check_return_
        NTSTATUS
        NTAPI
        SamSetInformationDomain(
            _In_ SAM_HANDLE DomainHandle,
            _In_ DOMAIN_INFORMATION_CLASS DomainInformationClass,
            _In_ PVOID DomainInformation
        );

    _Check_return_
        NTSTATUS
        NTAPI
        SamLookupNamesInDomain(
            _In_ SAM_HANDLE DomainHandle,
            _In_ ULONG Count,
            _In_reads_(Count) PUNICODE_STRING Names,
            _Out_ _Deref_post_count_(Count) PULONG* RelativeIds,
            _Out_ _Deref_post_count_(Count) PSID_NAME_USE* Use
        );

    _Check_return_
        NTSTATUS
        NTAPI
        SamLookupNamesInDomain2(
            _In_ SAM_HANDLE DomainHandle,
            _In_ ULONG Count,
            _In_reads_(Count) PUNICODE_STRING Names,
            _Out_ _Deref_post_count_(Count) PSID* Sids,
            _Out_ _Deref_post_count_(Count) PSID_NAME_USE* Use
        );

    _Check_return_
        NTSTATUS
        NTAPI
        SamLookupIdsInDomain(
            _In_ SAM_HANDLE DomainHandle,
            _In_ ULONG Count,
            _In_reads_(Count) PULONG RelativeIds,
            _Out_ _Deref_post_count_(Count) PUNICODE_STRING* Names,
            _Out_ _Deref_post_opt_count_(Count) PSID_NAME_USE* Use
        );

    _Check_return_
        NTSTATUS
        NTAPI
        SamRemoveMemberFromForeignDomain(
            _In_ SAM_HANDLE DomainHandle,
            _In_ PSID MemberId
        );

    _Check_return_
        NTSTATUS
        NTAPI
        SamQueryLocalizableAccountsInDomain(
            _In_ SAM_HANDLE Domain,
            _In_ ULONG Flags,
            _In_ ULONG LanguageId,
            _In_ DOMAIN_LOCALIZABLE_ACCOUNTS_INFORMATION Class,
            _Outptr_ PVOID* Buffer
        );

    // Group

#define GROUP_READ_INFORMATION 0x0001
#define GROUP_WRITE_ACCOUNT 0x0002
#define GROUP_ADD_MEMBER 0x0004
#define GROUP_REMOVE_MEMBER 0x0008
#define GROUP_LIST_MEMBERS 0x0010

#define GROUP_ALL_ACCESS (STANDARD_RIGHTS_REQUIRED | \
    GROUP_LIST_MEMBERS | \
    GROUP_WRITE_ACCOUNT | \
    GROUP_ADD_MEMBER | \
    GROUP_REMOVE_MEMBER | \
    GROUP_READ_INFORMATION)

#define GROUP_READ (STANDARD_RIGHTS_READ | \
    GROUP_LIST_MEMBERS)

#define GROUP_WRITE (STANDARD_RIGHTS_WRITE | \
    GROUP_WRITE_ACCOUNT | \
    GROUP_ADD_MEMBER | \
    GROUP_REMOVE_MEMBER)

#define GROUP_EXECUTE (STANDARD_RIGHTS_EXECUTE | \
    GROUP_READ_INFORMATION)

    typedef struct _GROUP_MEMBERSHIP
    {
        ULONG RelativeId;
        ULONG Attributes;
    } GROUP_MEMBERSHIP, * PGROUP_MEMBERSHIP;

    // SamQueryInformationGroup/SamSetInformationGroup types

    typedef enum _GROUP_INFORMATION_CLASS
    {
        GroupGeneralInformation = 1, // q: GROUP_GENERAL_INFORMATION
        GroupNameInformation, // q; s: GROUP_NAME_INFORMATION
        GroupAttributeInformation, // q; s: GROUP_ATTRIBUTE_INFORMATION
        GroupAdminCommentInformation, // q; s: GROUP_ADM_COMMENT_INFORMATION
        GroupReplicationInformation
    } GROUP_INFORMATION_CLASS;

    typedef struct _GROUP_GENERAL_INFORMATION
    {
        UNICODE_STRING Name;
        ULONG Attributes;
        ULONG MemberCount;
        UNICODE_STRING AdminComment;
    } GROUP_GENERAL_INFORMATION, * PGROUP_GENERAL_INFORMATION;

    typedef struct _GROUP_NAME_INFORMATION
    {
        UNICODE_STRING Name;
    } GROUP_NAME_INFORMATION, * PGROUP_NAME_INFORMATION;

    typedef struct _GROUP_ATTRIBUTE_INFORMATION
    {
        ULONG Attributes;
    } GROUP_ATTRIBUTE_INFORMATION, * PGROUP_ATTRIBUTE_INFORMATION;

    typedef struct _GROUP_ADM_COMMENT_INFORMATION
    {
        UNICODE_STRING AdminComment;
    } GROUP_ADM_COMMENT_INFORMATION, * PGROUP_ADM_COMMENT_INFORMATION;

    // Functions

    _Check_return_
        NTSTATUS
        NTAPI
        SamEnumerateGroupsInDomain(
            _In_ SAM_HANDLE DomainHandle,
            _Inout_ PSAM_ENUMERATE_HANDLE EnumerationContext,
            _Outptr_ PVOID* Buffer, // PSAM_RID_ENUMERATION *
            _In_ ULONG PreferedMaximumLength,
            _Out_ PULONG CountReturned
        );

    _Check_return_
        NTSTATUS
        NTAPI
        SamCreateGroupInDomain(
            _In_ SAM_HANDLE DomainHandle,
            _In_ PUNICODE_STRING AccountName,
            _In_ ACCESS_MASK DesiredAccess,
            _Out_ PSAM_HANDLE GroupHandle,
            _Out_ PULONG RelativeId
        );

    _Check_return_
        NTSTATUS
        NTAPI
        SamOpenGroup(
            _In_ SAM_HANDLE DomainHandle,
            _In_ ACCESS_MASK DesiredAccess,
            _In_ ULONG GroupId,
            _Out_ PSAM_HANDLE GroupHandle
        );

    _Check_return_
        NTSTATUS
        NTAPI
        SamDeleteGroup(
            _In_ SAM_HANDLE GroupHandle
        );

    _Check_return_
        NTSTATUS
        NTAPI
        SamQueryInformationGroup(
            _In_ SAM_HANDLE GroupHandle,
            _In_ GROUP_INFORMATION_CLASS GroupInformationClass,
            _Outptr_ PVOID* Buffer
        );

    _Check_return_
        NTSTATUS
        NTAPI
        SamSetInformationGroup(
            _In_ SAM_HANDLE GroupHandle,
            _In_ GROUP_INFORMATION_CLASS GroupInformationClass,
            _In_ PVOID Buffer
        );

    _Check_return_
        NTSTATUS
        NTAPI
        SamAddMemberToGroup(
            _In_ SAM_HANDLE GroupHandle,
            _In_ ULONG MemberId,
            _In_ ULONG Attributes
        );

    _Check_return_
        NTSTATUS
        NTAPI
        SamRemoveMemberFromGroup(
            _In_ SAM_HANDLE GroupHandle,
            _In_ ULONG MemberId
        );

    _Check_return_
        NTSTATUS
        NTAPI
        SamGetMembersInGroup(
            _In_ SAM_HANDLE GroupHandle,
            _Out_ _Deref_post_count_(*MemberCount) PULONG* MemberIds,
            _Out_ _Deref_post_count_(*MemberCount) PULONG* Attributes,
            _Out_ PULONG MemberCount
        );

    _Check_return_
        NTSTATUS
        NTAPI
        SamSetMemberAttributesOfGroup(
            _In_ SAM_HANDLE GroupHandle,
            _In_ ULONG MemberId,
            _In_ ULONG Attributes
        );

    // Alias

#define ALIAS_ADD_MEMBER 0x0001
#define ALIAS_REMOVE_MEMBER 0x0002
#define ALIAS_LIST_MEMBERS 0x0004
#define ALIAS_READ_INFORMATION 0x0008
#define ALIAS_WRITE_ACCOUNT 0x0010

#define ALIAS_ALL_ACCESS (STANDARD_RIGHTS_REQUIRED | \
    ALIAS_READ_INFORMATION | \
    ALIAS_WRITE_ACCOUNT | \
    ALIAS_LIST_MEMBERS | \
    ALIAS_ADD_MEMBER | \
    ALIAS_REMOVE_MEMBER)

#define ALIAS_READ (STANDARD_RIGHTS_READ | \
    ALIAS_LIST_MEMBERS)

#define ALIAS_WRITE (STANDARD_RIGHTS_WRITE | \
    ALIAS_WRITE_ACCOUNT | \
    ALIAS_ADD_MEMBER | \
    ALIAS_REMOVE_MEMBER)

#define ALIAS_EXECUTE (STANDARD_RIGHTS_EXECUTE | \
    ALIAS_READ_INFORMATION)

// SamQueryInformationAlias/SamSetInformationAlias types

    typedef enum _ALIAS_INFORMATION_CLASS
    {
        AliasGeneralInformation = 1, // q: ALIAS_GENERAL_INFORMATION
        AliasNameInformation, // q; s: ALIAS_NAME_INFORMATION
        AliasAdminCommentInformation, // q; s: ALIAS_ADM_COMMENT_INFORMATION
        AliasReplicationInformation,
        AliasExtendedInformation,
    } ALIAS_INFORMATION_CLASS;

    typedef struct _ALIAS_GENERAL_INFORMATION
    {
        UNICODE_STRING Name;
        ULONG MemberCount;
        UNICODE_STRING AdminComment;
    } ALIAS_GENERAL_INFORMATION, * PALIAS_GENERAL_INFORMATION;

    typedef struct _ALIAS_NAME_INFORMATION
    {
        UNICODE_STRING Name;
    } ALIAS_NAME_INFORMATION, * PALIAS_NAME_INFORMATION;

    typedef struct _ALIAS_ADM_COMMENT_INFORMATION
    {
        UNICODE_STRING AdminComment;
    } ALIAS_ADM_COMMENT_INFORMATION, * PALIAS_ADM_COMMENT_INFORMATION;

#define ALIAS_ALL_NAME (0x00000001L)
#define ALIAS_ALL_MEMBER_COUNT (0x00000002L)
#define ALIAS_ALL_ADMIN_COMMENT (0x00000004L)
#define ALIAS_ALL_SHELL_ADMIN_OBJECT_PROPERTIES (0x00000008L)

    typedef struct _ALIAS_EXTENDED_INFORMATION
    {
        ULONG WhichFields;
        SAM_SHELL_OBJECT_PROPERTIES ShellAdminObjectProperties;
    } ALIAS_EXTENDED_INFORMATION, * PALIAS_EXTENDED_INFORMATION;

    // Functions

    _Check_return_
        NTSTATUS
        NTAPI
        SamEnumerateAliasesInDomain(
            _In_ SAM_HANDLE DomainHandle,
            _Inout_ PSAM_ENUMERATE_HANDLE EnumerationContext,
            _Outptr_ PVOID* Buffer, // PSAM_RID_ENUMERATION *Buffer
            _In_ ULONG PreferedMaximumLength,
            _Out_ PULONG CountReturned
        );

    _Check_return_
        NTSTATUS
        NTAPI
        SamCreateAliasInDomain(
            _In_ SAM_HANDLE DomainHandle,
            _In_ PUNICODE_STRING AccountName,
            _In_ ACCESS_MASK DesiredAccess,
            _Out_ PSAM_HANDLE AliasHandle,
            _Out_ PULONG RelativeId
        );

    _Check_return_
        NTSTATUS
        NTAPI
        SamOpenAlias(
            _In_ SAM_HANDLE DomainHandle,
            _In_ ACCESS_MASK DesiredAccess,
            _In_ ULONG AliasId,
            _Out_ PSAM_HANDLE AliasHandle
        );

    _Check_return_
        NTSTATUS
        NTAPI
        SamDeleteAlias(
            _In_ SAM_HANDLE AliasHandle
        );

    _Check_return_
        NTSTATUS
        NTAPI
        SamQueryInformationAlias(
            _In_ SAM_HANDLE AliasHandle,
            _In_ ALIAS_INFORMATION_CLASS AliasInformationClass,
            _Outptr_ PVOID* Buffer
        );

    _Check_return_
        NTSTATUS
        NTAPI
        SamSetInformationAlias(
            _In_ SAM_HANDLE AliasHandle,
            _In_ ALIAS_INFORMATION_CLASS AliasInformationClass,
            _In_ PVOID Buffer
        );

    _Check_return_
        NTSTATUS
        NTAPI
        SamAddMemberToAlias(
            _In_ SAM_HANDLE AliasHandle,
            _In_ PSID MemberId
        );

    _Check_return_
        NTSTATUS
        NTAPI
        SamAddMultipleMembersToAlias(
            _In_ SAM_HANDLE AliasHandle,
            _In_reads_(MemberCount) PSID* MemberIds,
            _In_ ULONG MemberCount
        );

    _Check_return_
        NTSTATUS
        NTAPI
        SamRemoveMemberFromAlias(
            _In_ SAM_HANDLE AliasHandle,
            _In_ PSID MemberId
        );

    _Check_return_
        NTSTATUS
        NTAPI
        SamRemoveMultipleMembersFromAlias(
            _In_ SAM_HANDLE AliasHandle,
            _In_reads_(MemberCount) PSID* MemberIds,
            _In_ ULONG MemberCount
        );

    _Check_return_
        NTSTATUS
        NTAPI
        SamGetMembersInAlias(
            _In_ SAM_HANDLE AliasHandle,
            _Out_ _Deref_post_count_(*MemberCount) PSID** MemberIds,
            _Out_ PULONG MemberCount
        );

    _Check_return_
        NTSTATUS
        NTAPI
        SamGetAliasMembership(
            _In_ SAM_HANDLE DomainHandle,
            _In_ ULONG PassedCount,
            _In_reads_(PassedCount) PSID* Sids,
            _Out_ PULONG MembershipCount,
            _Out_ _Deref_post_count_(*MembershipCount) PULONG* Aliases
        );

    // Group types

#define GROUP_TYPE_BUILTIN_LOCAL_GROUP 0x00000001
#define GROUP_TYPE_ACCOUNT_GROUP 0x00000002
#define GROUP_TYPE_RESOURCE_GROUP 0x00000004
#define GROUP_TYPE_UNIVERSAL_GROUP 0x00000008
#define GROUP_TYPE_APP_BASIC_GROUP 0x00000010
#define GROUP_TYPE_APP_QUERY_GROUP 0x00000020
#define GROUP_TYPE_SECURITY_ENABLED 0x80000000

#define GROUP_TYPE_RESOURCE_BEHAVOIR (GROUP_TYPE_RESOURCE_GROUP | \
    GROUP_TYPE_APP_BASIC_GROUP | \
    GROUP_TYPE_APP_QUERY_GROUP)

// User

#define USER_READ_GENERAL 0x0001
#define USER_READ_PREFERENCES 0x0002
#define USER_WRITE_PREFERENCES 0x0004
#define USER_READ_LOGON 0x0008
#define USER_READ_ACCOUNT 0x0010
#define USER_WRITE_ACCOUNT 0x0020
#define USER_CHANGE_PASSWORD 0x0040
#define USER_FORCE_PASSWORD_CHANGE 0x0080
#define USER_LIST_GROUPS 0x0100
#define USER_READ_GROUP_INFORMATION 0x0200
#define USER_WRITE_GROUP_INFORMATION 0x0400

#define USER_ALL_ACCESS (STANDARD_RIGHTS_REQUIRED | \
    USER_READ_PREFERENCES | \
    USER_READ_LOGON | \
    USER_LIST_GROUPS | \
    USER_READ_GROUP_INFORMATION | \
    USER_WRITE_PREFERENCES | \
    USER_CHANGE_PASSWORD | \
    USER_FORCE_PASSWORD_CHANGE | \
    USER_READ_GENERAL | \
    USER_READ_ACCOUNT | \
    USER_WRITE_ACCOUNT | \
    USER_WRITE_GROUP_INFORMATION)

#define USER_READ (STANDARD_RIGHTS_READ | \
    USER_READ_PREFERENCES | \
    USER_READ_LOGON | \
    USER_READ_ACCOUNT | \
    USER_LIST_GROUPS | \
    USER_READ_GROUP_INFORMATION)

#define USER_WRITE (STANDARD_RIGHTS_WRITE | \
    USER_WRITE_PREFERENCES | \
    USER_CHANGE_PASSWORD)

#define USER_EXECUTE (STANDARD_RIGHTS_EXECUTE | \
    USER_READ_GENERAL | \
    USER_CHANGE_PASSWORD)

// User account control flags

#define USER_ACCOUNT_DISABLED (0x00000001)
#define USER_HOME_DIRECTORY_REQUIRED (0x00000002)
#define USER_PASSWORD_NOT_REQUIRED (0x00000004)
#define USER_TEMP_DUPLICATE_ACCOUNT (0x00000008)
#define USER_NORMAL_ACCOUNT (0x00000010)
#define USER_MNS_LOGON_ACCOUNT (0x00000020)
#define USER_INTERDOMAIN_TRUST_ACCOUNT (0x00000040)
#define USER_WORKSTATION_TRUST_ACCOUNT (0x00000080)
#define USER_SERVER_TRUST_ACCOUNT (0x00000100)
#define USER_DONT_EXPIRE_PASSWORD (0x00000200)
#define USER_ACCOUNT_AUTO_LOCKED (0x00000400)
#define USER_ENCRYPTED_TEXT_PASSWORD_ALLOWED (0x00000800)
#define USER_SMARTCARD_REQUIRED (0x00001000)
#define USER_TRUSTED_FOR_DELEGATION (0x00002000)
#define USER_NOT_DELEGATED (0x00004000)
#define USER_USE_DES_KEY_ONLY (0x00008000)
#define USER_DONT_REQUIRE_PREAUTH (0x00010000)
#define USER_PASSWORD_EXPIRED (0x00020000)
#define USER_TRUSTED_TO_AUTHENTICATE_FOR_DELEGATION (0x00040000)
#define USER_NO_AUTH_DATA_REQUIRED (0x00080000)
#define USER_PARTIAL_SECRETS_ACCOUNT (0x00100000)
#define USER_USE_AES_KEYS (0x00200000)

#define NEXT_FREE_ACCOUNT_CONTROL_BIT (USER_USE_AES_KEYS << 1)

#define USER_MACHINE_ACCOUNT_MASK ( \
    USER_INTERDOMAIN_TRUST_ACCOUNT | \
    USER_WORKSTATION_TRUST_ACCOUNT | \
    USER_SERVER_TRUST_ACCOUNT \
    )

#define USER_ACCOUNT_TYPE_MASK ( \
    USER_TEMP_DUPLICATE_ACCOUNT | \
    USER_NORMAL_ACCOUNT | \
    USER_MACHINE_ACCOUNT_MASK \
    )

#define USER_COMPUTED_ACCOUNT_CONTROL_BITS ( \
    USER_ACCOUNT_AUTO_LOCKED | \
    USER_PASSWORD_EXPIRED \
    )

// Logon times may be expressed in day, hour, or minute granularity.

#define SAM_DAYS_PER_WEEK (7)
#define SAM_HOURS_PER_WEEK (24 * SAM_DAYS_PER_WEEK)
#define SAM_MINUTES_PER_WEEK (60 * SAM_HOURS_PER_WEEK)

    typedef struct _LOGON_HOURS
    {
        USHORT UnitsPerWeek;

        // UnitsPerWeek is the number of equal length time units the week is
        // divided into. This value is used to compute the length of the bit
        // string in logon_hours. Must be less than or equal to
        // SAM_UNITS_PER_WEEK (10080) for this release.
        //
        // LogonHours is a bit map of valid logon times. Each bit represents
        // a unique division in a week. The largest bit map supported is 1260
        // bytes (10080 bits), which represents minutes per week. In this case
        // the first bit (bit 0, byte 0) is Sunday, 00:00:00 - 00-00:59; bit 1,
        // byte 0 is Sunday, 00:01:00 - 00:01:59, etc. A NULL pointer means
        // DONT_CHANGE for SamSetInformationUser() calls.

        PUCHAR LogonHours;
    } LOGON_HOURS, * PLOGON_HOURS;

    typedef struct _SR_SECURITY_DESCRIPTOR
    {
        ULONG Length;
        PUCHAR SecurityDescriptor;
    } SR_SECURITY_DESCRIPTOR, * PSR_SECURITY_DESCRIPTOR;

    // SamQueryInformationUser/SamSetInformationUser types

    typedef enum _USER_INFORMATION_CLASS
    {
        UserGeneralInformation = 1, // q: USER_GENERAL_INFORMATION
        UserPreferencesInformation, // q; s: USER_PREFERENCES_INFORMATION
        UserLogonInformation, // q: USER_LOGON_INFORMATION
        UserLogonHoursInformation, // q; s: USER_LOGON_HOURS_INFORMATION
        UserAccountInformation, // q: USER_ACCOUNT_INFORMATION
        UserNameInformation, // q; s: USER_NAME_INFORMATION
        UserAccountNameInformation, // q; s: USER_ACCOUNT_NAME_INFORMATION
        UserFullNameInformation, // q; s: USER_FULL_NAME_INFORMATION
        UserPrimaryGroupInformation, // q; s: USER_PRIMARY_GROUP_INFORMATION
        UserHomeInformation, // q; s: USER_HOME_INFORMATION // 10
        UserScriptInformation, // q; s: USER_SCRIPT_INFORMATION
        UserProfileInformation, // q; s: USER_PROFILE_INFORMATION
        UserAdminCommentInformation, // q; s: USER_ADMIN_COMMENT_INFORMATION
        UserWorkStationsInformation, // q; s: USER_WORKSTATIONS_INFORMATION
        UserSetPasswordInformation, // s: USER_SET_PASSWORD_INFORMATION
        UserControlInformation, // q; s: USER_CONTROL_INFORMATION
        UserExpiresInformation, // q; s: USER_EXPIRES_INFORMATION
        UserInternal1Information, // USER_INTERNAL1_INFORMATION
        UserInternal2Information, // USER_INTERNAL2_INFORMATION
        UserParametersInformation, // q; s: USER_PARAMETERS_INFORMATION // 20
        UserAllInformation, // USER_ALL_INFORMATION
        UserInternal3Information, // USER_INTERNAL3_INFORMATION
        UserInternal4Information, // USER_INTERNAL4_INFORMATION
        UserInternal5Information, // USER_INTERNAL5_INFORMATION
        UserInternal4InformationNew, // USER_INTERNAL4_INFORMATION_NEW
        UserInternal5InformationNew, // USER_INTERNAL5_INFORMATION_NEW
        UserInternal6Information, // USER_INTERNAL6_INFORMATION
        UserExtendedInformation, // USER_EXTENDED_INFORMATION
        UserLogonUIInformation, // USER_LOGON_UI_INFORMATION
        UserUnknownTodoInformation,
        UserInternal7Information, // USER_INTERNAL7_INFORMATION
        UserInternal8Information, // USER_INTERNAL8_INFORMATION
    } USER_INFORMATION_CLASS, * PUSER_INFORMATION_CLASS;

    typedef struct _USER_GENERAL_INFORMATION
    {
        UNICODE_STRING UserName;
        UNICODE_STRING FullName;
        ULONG PrimaryGroupId;
        UNICODE_STRING AdminComment;
        UNICODE_STRING UserComment;
    } USER_GENERAL_INFORMATION, * PUSER_GENERAL_INFORMATION;

    typedef struct _USER_PREFERENCES_INFORMATION
    {
        UNICODE_STRING UserComment;
        UNICODE_STRING Reserved1;
        USHORT CountryCode;
        USHORT CodePage;
    } USER_PREFERENCES_INFORMATION, * PUSER_PREFERENCES_INFORMATION;

#include <pshpack4.h>
    typedef struct _USER_LOGON_INFORMATION
    {
        UNICODE_STRING UserName;
        UNICODE_STRING FullName;
        ULONG UserId;
        ULONG PrimaryGroupId;
        UNICODE_STRING HomeDirectory;
        UNICODE_STRING HomeDirectoryDrive;
        UNICODE_STRING ScriptPath;
        UNICODE_STRING ProfilePath;
        UNICODE_STRING WorkStations;
        LARGE_INTEGER LastLogon;
        LARGE_INTEGER LastLogoff;
        LARGE_INTEGER PasswordLastSet;
        LARGE_INTEGER PasswordCanChange;
        LARGE_INTEGER PasswordMustChange;
        LOGON_HOURS LogonHours;
        USHORT BadPasswordCount;
        USHORT LogonCount;
        ULONG UserAccountControl;
    } USER_LOGON_INFORMATION, * PUSER_LOGON_INFORMATION;
#include <poppack.h>

    typedef struct _USER_LOGON_HOURS_INFORMATION
    {
        LOGON_HOURS LogonHours;
    } USER_LOGON_HOURS_INFORMATION, * PUSER_LOGON_HOURS_INFORMATION;

#include <pshpack4.h>
    typedef struct _USER_ACCOUNT_INFORMATION
    {
        UNICODE_STRING UserName;
        UNICODE_STRING FullName;
        ULONG UserId;
        ULONG PrimaryGroupId;
        UNICODE_STRING HomeDirectory;
        UNICODE_STRING HomeDirectoryDrive;
        UNICODE_STRING ScriptPath;
        UNICODE_STRING ProfilePath;
        UNICODE_STRING AdminComment;
        UNICODE_STRING WorkStations;
        LARGE_INTEGER LastLogon;
        LARGE_INTEGER LastLogoff;
        LOGON_HOURS LogonHours;
        USHORT BadPasswordCount;
        USHORT LogonCount;
        LARGE_INTEGER PasswordLastSet;
        LARGE_INTEGER AccountExpires;
        ULONG UserAccountControl;
    } USER_ACCOUNT_INFORMATION, * PUSER_ACCOUNT_INFORMATION;
#include <poppack.h>

    typedef struct _USER_NAME_INFORMATION
    {
        UNICODE_STRING UserName;
        UNICODE_STRING FullName;
    } USER_NAME_INFORMATION, * PUSER_NAME_INFORMATION;

    typedef struct _USER_ACCOUNT_NAME_INFORMATION
    {
        UNICODE_STRING UserName;
    } USER_ACCOUNT_NAME_INFORMATION, * PUSER_ACCOUNT_NAME_INFORMATION;

    typedef struct _USER_FULL_NAME_INFORMATION
    {
        UNICODE_STRING FullName;
    } USER_FULL_NAME_INFORMATION, * PUSER_FULL_NAME_INFORMATION;

    typedef struct _USER_PRIMARY_GROUP_INFORMATION
    {
        ULONG PrimaryGroupId;
    } USER_PRIMARY_GROUP_INFORMATION, * PUSER_PRIMARY_GROUP_INFORMATION;

    typedef struct _USER_HOME_INFORMATION
    {
        UNICODE_STRING HomeDirectory;
        UNICODE_STRING HomeDirectoryDrive;
    } USER_HOME_INFORMATION, * PUSER_HOME_INFORMATION;

    typedef struct _USER_SCRIPT_INFORMATION
    {
        UNICODE_STRING ScriptPath;
    } USER_SCRIPT_INFORMATION, * PUSER_SCRIPT_INFORMATION;

    typedef struct _USER_PROFILE_INFORMATION
    {
        UNICODE_STRING ProfilePath;
    } USER_PROFILE_INFORMATION, * PUSER_PROFILE_INFORMATION;

    typedef struct _USER_ADMIN_COMMENT_INFORMATION
    {
        UNICODE_STRING AdminComment;
    } USER_ADMIN_COMMENT_INFORMATION, * PUSER_ADMIN_COMMENT_INFORMATION;

    typedef struct _USER_WORKSTATIONS_INFORMATION
    {
        UNICODE_STRING WorkStations;
    } USER_WORKSTATIONS_INFORMATION, * PUSER_WORKSTATIONS_INFORMATION;

    typedef struct _USER_SET_PASSWORD_INFORMATION
    {
        UNICODE_STRING Password;
        BOOLEAN PasswordExpired;
    } USER_SET_PASSWORD_INFORMATION, * PUSER_SET_PASSWORD_INFORMATION;

    typedef struct _USER_CONTROL_INFORMATION
    {
        ULONG UserAccountControl;
    } USER_CONTROL_INFORMATION, * PUSER_CONTROL_INFORMATION;

    typedef struct _USER_EXPIRES_INFORMATION
    {
        LARGE_INTEGER AccountExpires;
    } USER_EXPIRES_INFORMATION, * PUSER_EXPIRES_INFORMATION;

#define CYPHER_BLOCK_LENGTH 8

    typedef struct _CYPHER_BLOCK
    {
        CHAR data[CYPHER_BLOCK_LENGTH];
    } CYPHER_BLOCK, * PCYPHER_BLOCK;

    typedef struct _ENCRYPTED_NT_OWF_PASSWORD
    {
        CYPHER_BLOCK data[2];
    } ENCRYPTED_NT_OWF_PASSWORD, * PENCRYPTED_NT_OWF_PASSWORD;

    typedef struct _ENCRYPTED_LM_OWF_PASSWORD
    {
        CYPHER_BLOCK data[2];
    } ENCRYPTED_LM_OWF_PASSWORD, * PENCRYPTED_LM_OWF_PASSWORD;

    typedef struct _USER_INTERNAL1_INFORMATION
    {
        ENCRYPTED_NT_OWF_PASSWORD EncryptedNtOwfPassword;
        ENCRYPTED_LM_OWF_PASSWORD EncryptedLmOwfPassword;
        BOOLEAN NtPasswordPresent;
        BOOLEAN LmPasswordPresent;
        BOOLEAN PasswordExpired;
    } USER_INTERNAL1_INFORMATION, * PUSER_INTERNAL1_INFORMATION;

    typedef struct _USER_INTERNAL2_INFORMATION
    {
        ULONG StatisticsToApply;
        LARGE_INTEGER LastLogon;
        LARGE_INTEGER LastLogoff;
        USHORT BadPasswordCount;
        USHORT LogonCount;
    } USER_INTERNAL2_INFORMATION, * PUSER_INTERNAL2_INFORMATION;

    typedef struct _USER_PARAMETERS_INFORMATION
    {
        UNICODE_STRING Parameters;
    } USER_PARAMETERS_INFORMATION, * PUSER_PARAMETERS_INFORMATION;

    // Flags for WhichFields in USER_ALL_INFORMATION

#define USER_ALL_USERNAME 0x00000001
#define USER_ALL_FULLNAME 0x00000002
#define USER_ALL_USERID 0x00000004
#define USER_ALL_PRIMARYGROUPID 0x00000008
#define USER_ALL_ADMINCOMMENT 0x00000010
#define USER_ALL_USERCOMMENT 0x00000020
#define USER_ALL_HOMEDIRECTORY 0x00000040
#define USER_ALL_HOMEDIRECTORYDRIVE 0x00000080
#define USER_ALL_SCRIPTPATH 0x00000100
#define USER_ALL_PROFILEPATH 0x00000200
#define USER_ALL_WORKSTATIONS 0x00000400
#define USER_ALL_LASTLOGON 0x00000800
#define USER_ALL_LASTLOGOFF 0x00001000
#define USER_ALL_LOGONHOURS 0x00002000
#define USER_ALL_BADPASSWORDCOUNT 0x00004000
#define USER_ALL_LOGONCOUNT 0x00008000
#define USER_ALL_PASSWORDCANCHANGE 0x00010000
#define USER_ALL_PASSWORDMUSTCHANGE 0x00020000
#define USER_ALL_PASSWORDLASTSET 0x00040000
#define USER_ALL_ACCOUNTEXPIRES 0x00080000
#define USER_ALL_USERACCOUNTCONTROL 0x00100000
#define USER_ALL_PARAMETERS 0x00200000
#define USER_ALL_COUNTRYCODE 0x00400000
#define USER_ALL_CODEPAGE 0x00800000
#define USER_ALL_NTPASSWORDPRESENT 0x01000000 // field AND boolean
#define USER_ALL_LMPASSWORDPRESENT 0x02000000 // field AND boolean
#define USER_ALL_PRIVATEDATA 0x04000000 // field AND boolean
#define USER_ALL_PASSWORDEXPIRED 0x08000000
#define USER_ALL_SECURITYDESCRIPTOR 0x10000000
#define USER_ALL_OWFPASSWORD 0x20000000 // boolean

#define USER_ALL_UNDEFINED_MASK 0xc0000000

// Fields that require USER_READ_GENERAL access to read.

#define USER_ALL_READ_GENERAL_MASK \
    (USER_ALL_USERNAME | \
    USER_ALL_FULLNAME | \
    USER_ALL_USERID | \
    USER_ALL_PRIMARYGROUPID | \
    USER_ALL_ADMINCOMMENT | \
    USER_ALL_USERCOMMENT)

// Fields that require USER_READ_LOGON access to read.

#define USER_ALL_READ_LOGON_MASK \
   (USER_ALL_HOMEDIRECTORY | \
    USER_ALL_HOMEDIRECTORYDRIVE | \
    USER_ALL_SCRIPTPATH | \
    USER_ALL_PROFILEPATH | \
    USER_ALL_WORKSTATIONS | \
    USER_ALL_LASTLOGON | \
    USER_ALL_LASTLOGOFF | \
    USER_ALL_LOGONHOURS | \
    USER_ALL_BADPASSWORDCOUNT | \
    USER_ALL_LOGONCOUNT | \
    USER_ALL_PASSWORDCANCHANGE | \
    USER_ALL_PASSWORDMUSTCHANGE)

// Fields that require USER_READ_ACCOUNT access to read.

#define USER_ALL_READ_ACCOUNT_MASK \
    (USER_ALL_PASSWORDLASTSET | \
    USER_ALL_ACCOUNTEXPIRES | \
    USER_ALL_USERACCOUNTCONTROL | \
    USER_ALL_PARAMETERS)

// Fields that require USER_READ_PREFERENCES access to read.

#define USER_ALL_READ_PREFERENCES_MASK \
    (USER_ALL_COUNTRYCODE | USER_ALL_CODEPAGE)

// Fields that can only be read by trusted clients.

#define USER_ALL_READ_TRUSTED_MASK \
    (USER_ALL_NTPASSWORDPRESENT | \
    USER_ALL_LMPASSWORDPRESENT | \
    USER_ALL_PASSWORDEXPIRED | \
    USER_ALL_SECURITYDESCRIPTOR | \
    USER_ALL_PRIVATEDATA)

// Fields that can't be read.

#define USER_ALL_READ_CANT_MASK USER_ALL_UNDEFINED_MASK

// Fields that require USER_WRITE_ACCOUNT access to write.

#define USER_ALL_WRITE_ACCOUNT_MASK \
    (USER_ALL_USERNAME | \
    USER_ALL_FULLNAME | \
    USER_ALL_PRIMARYGROUPID | \
    USER_ALL_HOMEDIRECTORY | \
    USER_ALL_HOMEDIRECTORYDRIVE | \
    USER_ALL_SCRIPTPATH | \
    USER_ALL_PROFILEPATH | \
    USER_ALL_ADMINCOMMENT | \
    USER_ALL_WORKSTATIONS | \
    USER_ALL_LOGONHOURS | \
    USER_ALL_ACCOUNTEXPIRES | \
    USER_ALL_USERACCOUNTCONTROL | \
    USER_ALL_PARAMETERS)

// Fields that require USER_WRITE_PREFERENCES access to write.

#define USER_ALL_WRITE_PREFERENCES_MASK \
    (USER_ALL_USERCOMMENT | USER_ALL_COUNTRYCODE | USER_ALL_CODEPAGE)

// Fields that require USER_FORCE_PASSWORD_CHANGE access to write.
//
// Note that non-trusted clients only set the NT password as a
// UNICODE string. The wrapper will convert it to an LM password,
// OWF and encrypt both versions. Trusted clients can pass in OWF
// versions of either or both.

#define USER_ALL_WRITE_FORCE_PASSWORD_CHANGE_MASK \
    (USER_ALL_NTPASSWORDPRESENT | \
    USER_ALL_LMPASSWORDPRESENT | \
    USER_ALL_PASSWORDEXPIRED)

// Fields that can only be written by trusted clients.

#define USER_ALL_WRITE_TRUSTED_MASK \
    (USER_ALL_LASTLOGON | \
    USER_ALL_LASTLOGOFF | \
    USER_ALL_BADPASSWORDCOUNT | \
    USER_ALL_LOGONCOUNT | \
    USER_ALL_PASSWORDLASTSET | \
    USER_ALL_SECURITYDESCRIPTOR | \
    USER_ALL_PRIVATEDATA)

// Fields that can't be written.

#define USER_ALL_WRITE_CANT_MASK \
    (USER_ALL_USERID | \
    USER_ALL_PASSWORDCANCHANGE | \
    USER_ALL_PASSWORDMUSTCHANGE | \
    USER_ALL_UNDEFINED_MASK)

#include <pshpack4.h>
    typedef struct _USER_ALL_INFORMATION
    {
        LARGE_INTEGER LastLogon;
        LARGE_INTEGER LastLogoff;
        LARGE_INTEGER PasswordLastSet;
        LARGE_INTEGER AccountExpires;
        LARGE_INTEGER PasswordCanChange;
        LARGE_INTEGER PasswordMustChange;
        UNICODE_STRING UserName;
        UNICODE_STRING FullName;
        UNICODE_STRING HomeDirectory;
        UNICODE_STRING HomeDirectoryDrive;
        UNICODE_STRING ScriptPath;
        UNICODE_STRING ProfilePath;
        UNICODE_STRING AdminComment;
        UNICODE_STRING WorkStations;
        UNICODE_STRING UserComment;
        UNICODE_STRING Parameters;
        UNICODE_STRING LmPassword;
        UNICODE_STRING NtPassword;
        UNICODE_STRING PrivateData;
        SR_SECURITY_DESCRIPTOR SecurityDescriptor;
        ULONG UserId;
        ULONG PrimaryGroupId;
        ULONG UserAccountControl;
        ULONG WhichFields;
        LOGON_HOURS LogonHours;
        USHORT BadPasswordCount;
        USHORT LogonCount;
        USHORT CountryCode;
        USHORT CodePage;
        BOOLEAN LmPasswordPresent;
        BOOLEAN NtPasswordPresent;
        BOOLEAN PasswordExpired;
        BOOLEAN PrivateDataSensitive;
    } USER_ALL_INFORMATION, * PUSER_ALL_INFORMATION;
#include <poppack.h>

#include <pshpack4.h>
    typedef struct _USER_INTERNAL3_INFORMATION
    {
        USER_ALL_INFORMATION I1;
        LARGE_INTEGER LastBadPasswordTime;
    } USER_INTERNAL3_INFORMATION, * PUSER_INTERNAL3_INFORMATION;
#include <poppack.h>

    typedef struct _ENCRYPTED_USER_PASSWORD
    {
        UCHAR Buffer[(SAM_MAX_PASSWORD_LENGTH * 2) + 4];
    } ENCRYPTED_USER_PASSWORD, * PENCRYPTED_USER_PASSWORD;

    typedef struct _USER_INTERNAL4_INFORMATION
    {
        USER_ALL_INFORMATION I1;
        ENCRYPTED_USER_PASSWORD UserPassword;
    } USER_INTERNAL4_INFORMATION, * PUSER_INTERNAL4_INFORMATION;

    typedef struct _USER_INTERNAL5_INFORMATION
    {
        ENCRYPTED_USER_PASSWORD UserPassword;
        BOOLEAN PasswordExpired;
    } USER_INTERNAL5_INFORMATION, * PUSER_INTERNAL5_INFORMATION;

    typedef struct _ENCRYPTED_USER_PASSWORD_NEW
    {
        UCHAR Buffer[(SAM_MAX_PASSWORD_LENGTH * 2) + 4 + SAM_PASSWORD_ENCRYPTION_SALT_LEN];
    } ENCRYPTED_USER_PASSWORD_NEW, * PENCRYPTED_USER_PASSWORD_NEW;

    typedef struct _USER_INTERNAL4_INFORMATION_NEW
    {
        USER_ALL_INFORMATION I1;
        ENCRYPTED_USER_PASSWORD_NEW UserPassword;
    } USER_INTERNAL4_INFORMATION_NEW, * PUSER_INTERNAL4_INFORMATION_NEW;

    typedef struct _USER_INTERNAL5_INFORMATION_NEW
    {
        ENCRYPTED_USER_PASSWORD_NEW UserPassword;
        BOOLEAN PasswordExpired;
    } USER_INTERNAL5_INFORMATION_NEW, * PUSER_INTERNAL5_INFORMATION_NEW;

    typedef struct _USER_ALLOWED_TO_DELEGATE_TO_LIST
    {
        ULONG Size;
        ULONG NumSPNs;
        UNICODE_STRING SPNList[ANYSIZE_ARRAY];
    } USER_ALLOWED_TO_DELEGATE_TO_LIST, * PUSER_ALLOWED_TO_DELEGATE_TO_LIST;

#define USER_EXTENDED_FIELD_UPN 0x00000001L
#define USER_EXTENDED_FIELD_A2D2 0x00000002L

    typedef struct _USER_INTERNAL6_INFORMATION
    {
        USER_ALL_INFORMATION I1;
        LARGE_INTEGER LastBadPasswordTime;
        ULONG ExtendedFields;
        BOOLEAN UPNDefaulted;
        UNICODE_STRING UPN;
        PUSER_ALLOWED_TO_DELEGATE_TO_LIST A2D2List;
    } USER_INTERNAL6_INFORMATION, * PUSER_INTERNAL6_INFORMATION;

    typedef SAM_BYTE_ARRAY_32K SAM_USER_TILE, * PSAM_USER_TILE;

    // 0xff000fff is reserved for internal callers and implementation.

#define USER_EXTENDED_FIELD_USER_TILE (0x00001000L)
#define USER_EXTENDED_FIELD_PASSWORD_HINT (0x00002000L)
#define USER_EXTENDED_FIELD_DONT_SHOW_IN_LOGON_UI (0x00004000L)
#define USER_EXTENDED_FIELD_SHELL_ADMIN_OBJECT_PROPERTIES (0x00008000L)

    typedef struct _USER_EXTENDED_INFORMATION
    {
        ULONG ExtendedWhichFields;
        SAM_USER_TILE UserTile;
        UNICODE_STRING PasswordHint;
        BOOLEAN DontShowInLogonUI;
        SAM_SHELL_OBJECT_PROPERTIES ShellAdminObjectProperties;
    } USER_EXTENDED_INFORMATION, * PUSER_EXTENDED_INFORMATION;

    // For local callers only.
    typedef struct _USER_LOGON_UI_INFORMATION
    {
        BOOLEAN PasswordIsBlank;
        BOOLEAN AccountIsDisabled;
    } USER_LOGON_UI_INFORMATION, * PUSER_LOGON_UI_INFORMATION;

    typedef struct _ENCRYPTED_PASSWORD_AES
    {
        UCHAR AuthData[64];
        UCHAR Salt[SAM_PASSWORD_ENCRYPTION_SALT_LEN];
        ULONG cbCipher;
        PUCHAR Cipher;
        ULONGLONG PBKDF2Iterations;
    } ENCRYPTED_PASSWORD_AES, * PENCRYPTED_PASSWORD_AES;

    typedef struct _USER_INTERNAL7_INFORMATION
    {
        ENCRYPTED_PASSWORD_AES UserPassword;
        BOOLEAN PasswordExpired;
    } USER_INTERNAL7_INFORMATION, * PUSER_INTERNAL7_INFORMATION;

    typedef struct _USER_INTERNAL8_INFORMATION
    {
        USER_ALL_INFORMATION I1;
        ENCRYPTED_PASSWORD_AES UserPassword;
    } USER_INTERNAL8_INFORMATION, * PUSER_INTERNAL8_INFORMATION;

    // SamChangePasswordUser3 types

    // Error values:
    // * SAM_PWD_CHANGE_NO_ERROR
    // * SAM_PWD_CHANGE_PASSWORD_TOO_SHORT
    // * SAM_PWD_CHANGE_PWD_IN_HISTORY
    // * SAM_PWD_CHANGE_USERNAME_IN_PASSWORD
    // * SAM_PWD_CHANGE_FULLNAME_IN_PASSWORD
    // * SAM_PWD_CHANGE_MACHINE_PASSWORD_NOT_DEFAULT
    // * SAM_PWD_CHANGE_FAILED_BY_FILTER

    typedef struct _USER_PWD_CHANGE_FAILURE_INFORMATION
    {
        ULONG ExtendedFailureReason;
        UNICODE_STRING FilterModuleName;
    } USER_PWD_CHANGE_FAILURE_INFORMATION, * PUSER_PWD_CHANGE_FAILURE_INFORMATION;

    // ExtendedFailureReason values

#define SAM_PWD_CHANGE_NO_ERROR 0
#define SAM_PWD_CHANGE_PASSWORD_TOO_SHORT 1
#define SAM_PWD_CHANGE_PWD_IN_HISTORY 2
#define SAM_PWD_CHANGE_USERNAME_IN_PASSWORD 3
#define SAM_PWD_CHANGE_FULLNAME_IN_PASSWORD 4
#define SAM_PWD_CHANGE_NOT_COMPLEX 5
#define SAM_PWD_CHANGE_MACHINE_PASSWORD_NOT_DEFAULT 6
#define SAM_PWD_CHANGE_FAILED_BY_FILTER 7
#define SAM_PWD_CHANGE_PASSWORD_TOO_LONG 8
#define SAM_PWD_CHANGE_FAILURE_REASON_MAX 8

// Functions

    _Check_return_
        NTSTATUS
        NTAPI
        SamEnumerateUsersInDomain(
            _In_ SAM_HANDLE DomainHandle,
            _Inout_ PSAM_ENUMERATE_HANDLE EnumerationContext,
            _In_ ULONG UserAccountControl,
            _Outptr_ PVOID* Buffer, // PSAM_RID_ENUMERATION *
            _In_ ULONG PreferedMaximumLength,
            _Out_ PULONG CountReturned
        );

    _Check_return_
        NTSTATUS
        NTAPI
        SamCreateUserInDomain(
            _In_ SAM_HANDLE DomainHandle,
            _In_ PUNICODE_STRING AccountName,
            _In_ ACCESS_MASK DesiredAccess,
            _Out_ PSAM_HANDLE UserHandle,
            _Out_ PULONG RelativeId
        );

    _Check_return_
        NTSTATUS
        NTAPI
        SamCreateUser2InDomain(
            _In_ SAM_HANDLE DomainHandle,
            _In_ PUNICODE_STRING AccountName,
            _In_ ULONG AccountType,
            _In_ ACCESS_MASK DesiredAccess,
            _Out_ PSAM_HANDLE UserHandle,
            _Out_ PULONG GrantedAccess,
            _Out_ PULONG RelativeId
        );

    _Check_return_
        NTSTATUS
        NTAPI
        SamOpenUser(
            _In_ SAM_HANDLE DomainHandle,
            _In_ ACCESS_MASK DesiredAccess,
            _In_ ULONG UserId,
            _Out_ PSAM_HANDLE UserHandle
        );

    _Check_return_
        NTSTATUS
        NTAPI
        SamDeleteUser(
            _In_ SAM_HANDLE UserHandle
        );

    _Check_return_
        NTSTATUS
        NTAPI
        SamQueryInformationUser(
            _In_ SAM_HANDLE UserHandle,
            _In_ USER_INFORMATION_CLASS UserInformationClass,
            _Outptr_ PVOID* Buffer
        );

    _Check_return_
        NTSTATUS
        NTAPI
        SamSetInformationUser(
            _In_ SAM_HANDLE UserHandle,
            _In_ USER_INFORMATION_CLASS UserInformationClass,
            _In_ PVOID Buffer
        );

    _Check_return_
        NTSTATUS
        NTAPI
        SamGetGroupsForUser(
            _In_ SAM_HANDLE UserHandle,
            _Out_ _Deref_post_count_(*MembershipCount) PGROUP_MEMBERSHIP* Groups,
            _Out_ PULONG MembershipCount
        );

    _Check_return_
        NTSTATUS
        NTAPI
        SamChangePasswordUser(
            _In_ SAM_HANDLE UserHandle,
            _In_ PUNICODE_STRING OldPassword,
            _In_ PUNICODE_STRING NewPassword
        );

    _Check_return_
        NTSTATUS
        NTAPI
        SamChangePasswordUser2(
            _In_ PUNICODE_STRING ServerName,
            _In_ PUNICODE_STRING UserName,
            _In_ PUNICODE_STRING OldPassword,
            _In_ PUNICODE_STRING NewPassword
        );

    _Check_return_
        NTSTATUS
        NTAPI
        SamChangePasswordUser3(
            _In_ PUNICODE_STRING ServerName,
            _In_ PUNICODE_STRING UserName,
            _In_ PUNICODE_STRING OldPassword,
            _In_ PUNICODE_STRING NewPassword,
            _Outptr_ PDOMAIN_PASSWORD_INFORMATION* EffectivePasswordPolicy,
            _Outptr_ PUSER_PWD_CHANGE_FAILURE_INFORMATION* PasswordChangeFailureInfo
        );

    _Check_return_
        NTSTATUS
        NTAPI
        SamQueryDisplayInformation(
            _In_ SAM_HANDLE DomainHandle,
            _In_ DOMAIN_DISPLAY_INFORMATION DisplayInformation,
            _In_ ULONG Index,
            _In_ ULONG EntryCount,
            _In_ ULONG PreferredMaximumLength,
            _Out_ PULONG TotalAvailable,
            _Out_ PULONG TotalReturned,
            _Out_ PULONG ReturnedEntryCount,
            _Outptr_ PVOID* SortedBuffer
        );

    _Check_return_
        NTSTATUS
        NTAPI
        SamGetDisplayEnumerationIndex(
            _In_ SAM_HANDLE DomainHandle,
            _In_ DOMAIN_DISPLAY_INFORMATION DisplayInformation,
            _In_ PUNICODE_STRING Prefix,
            _Out_ PULONG Index
        );

    // Database replication

    typedef enum _SECURITY_DB_DELTA_TYPE
    {
        SecurityDbNew = 1,
        SecurityDbRename,
        SecurityDbDelete,
        SecurityDbChangeMemberAdd,
        SecurityDbChangeMemberSet,
        SecurityDbChangeMemberDel,
        SecurityDbChange,
        SecurityDbChangePassword
    } SECURITY_DB_DELTA_TYPE, * PSECURITY_DB_DELTA_TYPE;

    typedef enum _SECURITY_DB_OBJECT_TYPE
    {
        SecurityDbObjectSamDomain = 1,
        SecurityDbObjectSamUser,
        SecurityDbObjectSamGroup,
        SecurityDbObjectSamAlias,
        SecurityDbObjectLsaPolicy,
        SecurityDbObjectLsaTDomain,
        SecurityDbObjectLsaAccount,
        SecurityDbObjectLsaSecret
    } SECURITY_DB_OBJECT_TYPE, * PSECURITY_DB_OBJECT_TYPE;

    typedef enum _SAM_ACCOUNT_TYPE
    {
        SamObjectUser = 1,
        SamObjectGroup,
        SamObjectAlias
    } SAM_ACCOUNT_TYPE, * PSAM_ACCOUNT_TYPE;

#define SAM_USER_ACCOUNT (0x00000001)
#define SAM_GLOBAL_GROUP_ACCOUNT (0x00000002)
#define SAM_LOCAL_GROUP_ACCOUNT (0x00000004)

    typedef struct _SAM_GROUP_MEMBER_ID
    {
        ULONG MemberRid;
    } SAM_GROUP_MEMBER_ID, * PSAM_GROUP_MEMBER_ID;

    typedef struct _SAM_ALIAS_MEMBER_ID
    {
        PSID MemberSid;
    } SAM_ALIAS_MEMBER_ID, * PSAM_ALIAS_MEMBER_ID;

    typedef union _SAM_DELTA_DATA
    {
        SAM_GROUP_MEMBER_ID GroupMemberId;
        SAM_ALIAS_MEMBER_ID AliasMemberId;
        ULONG AccountControl;
    } SAM_DELTA_DATA, * PSAM_DELTA_DATA;

    typedef NTSTATUS(NTAPI* PSAM_DELTA_NOTIFICATION_ROUTINE)(
        _In_ PSID DomainSid,
        _In_ SECURITY_DB_DELTA_TYPE DeltaType,
        _In_ SECURITY_DB_OBJECT_TYPE ObjectType,
        _In_ ULONG ObjectRid,
        _In_opt_ PUNICODE_STRING ObjectName,
        _In_ PLARGE_INTEGER ModifiedCount,
        _In_opt_ PSAM_DELTA_DATA DeltaData
        );

#define SAM_DELTA_NOTIFY_ROUTINE "DeltaNotify"

    _Check_return_
        NTSTATUS
        NTAPI
        SamRegisterObjectChangeNotification(
            _In_ SECURITY_DB_OBJECT_TYPE ObjectType,
            _In_ HANDLE NotificationEventHandle
        );

    NTSTATUS
        NTAPI
        SamUnregisterObjectChangeNotification(
            _In_ SECURITY_DB_OBJECT_TYPE ObjectType,
            _In_ HANDLE NotificationEventHandle
        );

    // Compatibility mode

#define SAM_SID_COMPATIBILITY_ALL 0
#define SAM_SID_COMPATIBILITY_LAX 1
#define SAM_SID_COMPATIBILITY_STRICT 2

    _Check_return_
        NTSTATUS
        NTAPI
        SamGetCompatibilityMode(
            _In_ SAM_HANDLE ObjectHandle,
            _Out_ ULONG* Mode
        );

    // Password validation

    typedef enum _PASSWORD_POLICY_VALIDATION_TYPE
    {
        SamValidateAuthentication = 1,
        SamValidatePasswordChange,
        SamValidatePasswordReset
    } PASSWORD_POLICY_VALIDATION_TYPE;

    typedef struct _SAM_VALIDATE_PASSWORD_HASH
    {
        ULONG Length;
        _Field_size_bytes_(Length) PUCHAR Hash;
    } SAM_VALIDATE_PASSWORD_HASH, * PSAM_VALIDATE_PASSWORD_HASH;

    // Flags for PresentFields in SAM_VALIDATE_PERSISTED_FIELDS

#define SAM_VALIDATE_PASSWORD_LAST_SET 0x00000001
#define SAM_VALIDATE_BAD_PASSWORD_TIME 0x00000002
#define SAM_VALIDATE_LOCKOUT_TIME 0x00000004
#define SAM_VALIDATE_BAD_PASSWORD_COUNT 0x00000008
#define SAM_VALIDATE_PASSWORD_HISTORY_LENGTH 0x00000010
#define SAM_VALIDATE_PASSWORD_HISTORY 0x00000020

    typedef struct _SAM_VALIDATE_PERSISTED_FIELDS
    {
        ULONG PresentFields;
        LARGE_INTEGER PasswordLastSet;
        LARGE_INTEGER BadPasswordTime;
        LARGE_INTEGER LockoutTime;
        ULONG BadPasswordCount;
        ULONG PasswordHistoryLength;
        _Field_size_bytes_(PasswordHistoryLength) PSAM_VALIDATE_PASSWORD_HASH PasswordHistory;
    } SAM_VALIDATE_PERSISTED_FIELDS, * PSAM_VALIDATE_PERSISTED_FIELDS;

    typedef enum _SAM_VALIDATE_VALIDATION_STATUS
    {
        SamValidateSuccess = 0,
        SamValidatePasswordMustChange,
        SamValidateAccountLockedOut,
        SamValidatePasswordExpired,
        SamValidatePasswordIncorrect,
        SamValidatePasswordIsInHistory,
        SamValidatePasswordTooShort,
        SamValidatePasswordTooLong,
        SamValidatePasswordNotComplexEnough,
        SamValidatePasswordTooRecent,
        SamValidatePasswordFilterError
    } SAM_VALIDATE_VALIDATION_STATUS, * PSAM_VALIDATE_VALIDATION_STATUS;

    typedef struct _SAM_VALIDATE_STANDARD_OUTPUT_ARG
    {
        SAM_VALIDATE_PERSISTED_FIELDS ChangedPersistedFields;
        SAM_VALIDATE_VALIDATION_STATUS ValidationStatus;
    } SAM_VALIDATE_STANDARD_OUTPUT_ARG, * PSAM_VALIDATE_STANDARD_OUTPUT_ARG;

    typedef struct _SAM_VALIDATE_AUTHENTICATION_INPUT_ARG
    {
        SAM_VALIDATE_PERSISTED_FIELDS InputPersistedFields;
        BOOLEAN PasswordMatched;
    } SAM_VALIDATE_AUTHENTICATION_INPUT_ARG, * PSAM_VALIDATE_AUTHENTICATION_INPUT_ARG;

    typedef struct _SAM_VALIDATE_PASSWORD_CHANGE_INPUT_ARG
    {
        SAM_VALIDATE_PERSISTED_FIELDS InputPersistedFields;
        UNICODE_STRING ClearPassword;
        UNICODE_STRING UserAccountName;
        SAM_VALIDATE_PASSWORD_HASH HashedPassword;
        BOOLEAN PasswordMatch; // denotes if the old password supplied by user matched or not
    } SAM_VALIDATE_PASSWORD_CHANGE_INPUT_ARG, * PSAM_VALIDATE_PASSWORD_CHANGE_INPUT_ARG;

    typedef struct _SAM_VALIDATE_PASSWORD_RESET_INPUT_ARG
    {
        SAM_VALIDATE_PERSISTED_FIELDS InputPersistedFields;
        UNICODE_STRING ClearPassword;
        UNICODE_STRING UserAccountName;
        SAM_VALIDATE_PASSWORD_HASH HashedPassword;
        BOOLEAN PasswordMustChangeAtNextLogon; // looked at only for password reset
        BOOLEAN ClearLockout; // can be used clear user account lockout
    }SAM_VALIDATE_PASSWORD_RESET_INPUT_ARG, * PSAM_VALIDATE_PASSWORD_RESET_INPUT_ARG;

    typedef union _SAM_VALIDATE_INPUT_ARG
    {
        SAM_VALIDATE_AUTHENTICATION_INPUT_ARG ValidateAuthenticationInput;
        SAM_VALIDATE_PASSWORD_CHANGE_INPUT_ARG ValidatePasswordChangeInput;
        SAM_VALIDATE_PASSWORD_RESET_INPUT_ARG ValidatePasswordResetInput;
    } SAM_VALIDATE_INPUT_ARG, * PSAM_VALIDATE_INPUT_ARG;

    typedef union _SAM_VALIDATE_OUTPUT_ARG
    {
        SAM_VALIDATE_STANDARD_OUTPUT_ARG ValidateAuthenticationOutput;
        SAM_VALIDATE_STANDARD_OUTPUT_ARG ValidatePasswordChangeOutput;
        SAM_VALIDATE_STANDARD_OUTPUT_ARG ValidatePasswordResetOutput;
    } SAM_VALIDATE_OUTPUT_ARG, * PSAM_VALIDATE_OUTPUT_ARG;

    _Check_return_
        NTSTATUS
        NTAPI
        SamValidatePassword(
            _In_opt_ PUNICODE_STRING ServerName,
            _In_ PASSWORD_POLICY_VALIDATION_TYPE ValidationType,
            _In_ PSAM_VALIDATE_INPUT_ARG InputArg,
            _Out_ PSAM_VALIDATE_OUTPUT_ARG* OutputArg
        );

    // Generic operation

    typedef enum _SAM_GENERIC_OPERATION_TYPE
    {
        SamObjectChangeNotificationOperation
    } SAM_GENERIC_OPERATION_TYPE, * PSAM_GENERIC_OPERATION_TYPE;

    typedef struct _SAM_OPERATION_OBJCHG_INPUT
    {
        BOOLEAN Register;
        ULONG64 EventHandle;
        SECURITY_DB_OBJECT_TYPE ObjectType;
        ULONG ProcessID;
    } SAM_OPERATION_OBJCHG_INPUT, * PSAM_OPERATION_OBJCHG_INPUT;

    typedef struct _SAM_OPERATION_OBJCHG_OUTPUT
    {
        ULONG Reserved;
    } SAM_OPERATION_OBJCHG_OUTPUT, * PSAM_OPERATION_OBJCHG_OUTPUT;

    typedef union _SAM_GENERIC_OPERATION_INPUT
    {
        SAM_OPERATION_OBJCHG_INPUT ObjChangeIn;
    } SAM_GENERIC_OPERATION_INPUT, * PSAM_GENERIC_OPERATION_INPUT;

    typedef union _SAM_GENERIC_OPERATION_OUTPUT
    {
        SAM_OPERATION_OBJCHG_OUTPUT ObjChangeOut;
    } SAM_GENERIC_OPERATION_OUTPUT, * PSAM_GENERIC_OPERATION_OUTPUT;

    _Check_return_
        NTSTATUS
        NTAPI
        SamPerformGenericOperation(
            _In_opt_ PWSTR ServerName,
            _In_ SAM_GENERIC_OPERATION_TYPE OperationType,
            _In_ PSAM_GENERIC_OPERATION_INPUT OperationIn,
            _Out_ PSAM_GENERIC_OPERATION_OUTPUT* OperationOut
        );

#endif

    /*
     * Trace Control support functions
     *
     * This file is part of System Informer.
     */

#ifndef _NTMISC_H
#define _NTMISC_H

     // Filter manager

#define FLT_PORT_CONNECT 0x0001
#define FLT_PORT_ALL_ACCESS (FLT_PORT_CONNECT | STANDARD_RIGHTS_ALL)

// VDM

    typedef enum _VDMSERVICECLASS
    {
        VdmStartExecution,
        VdmQueueInterrupt,
        VdmDelayInterrupt,
        VdmInitialize,
        VdmFeatures,
        VdmSetInt21Handler,
        VdmQueryDir,
        VdmPrinterDirectIoOpen,
        VdmPrinterDirectIoClose,
        VdmPrinterInitialize,
        VdmSetLdtEntries,
        VdmSetProcessLdtInfo,
        VdmAdlibEmulation,
        VdmPMCliControl,
        VdmQueryVdmProcess,
        VdmPreInitialize
    } VDMSERVICECLASS, * PVDMSERVICECLASS;

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtVdmControl(
            _In_ VDMSERVICECLASS Service,
            _Inout_ PVOID ServiceData
        );

    // WMI/ETW

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtTraceEvent(
            _In_ HANDLE TraceHandle,
            _In_ ULONG Flags,
            _In_ ULONG FieldSize,
            _In_ PVOID Fields
        );

    // rev
    typedef enum _ETWTRACECONTROLCODE
    {
        EtwStartLoggerCode = 1, // inout WMI_LOGGER_INFORMATION
        EtwStopLoggerCode = 2, // inout WMI_LOGGER_INFORMATION
        EtwQueryLoggerCode = 3, // inout WMI_LOGGER_INFORMATION
        EtwUpdateLoggerCode = 4, // inout WMI_LOGGER_INFORMATION
        EtwFlushLoggerCode = 5, // inout WMI_LOGGER_INFORMATION
        EtwIncrementLoggerFile = 6, // inout WMI_LOGGER_INFORMATION
        EtwRealtimeTransition = 7, // inout WMI_LOGGER_INFORMATION
        // reserved
        EtwRealtimeConnectCode = 11,
        EtwActivityIdCreate = 12,
        EtwWdiScenarioCode = 13,
        EtwRealtimeDisconnectCode = 14, // in HANDLE
        EtwRegisterGuidsCode = 15,
        EtwReceiveNotification = 16,
        EtwSendDataBlock = 17, // ETW_ENABLE_NOTIFICATION_PACKET
        EtwSendReplyDataBlock = 18,
        EtwReceiveReplyDataBlock = 19,
        EtwWdiSemUpdate = 20,
        EtwEnumTraceGuidList = 21, // out GUID[]
        EtwGetTraceGuidInfo = 22, // in GUID, out ETW_TRACE_GUID_INFO
        EtwEnumerateTraceGuids = 23,
        EtwRegisterSecurityProv = 24,
        EtwReferenceTimeCode = 25, // in ULONG LoggerId, out ETW_REF_CLOCK
        EtwTrackBinaryCode = 26, // in HANDLE
        EtwAddNotificationEvent = 27,
        EtwUpdateDisallowList = 28,
        EtwSetEnableAllKeywordsCode = 29,
        EtwSetProviderTraitsCode = 30,
        EtwUseDescriptorTypeCode = 31,
        EtwEnumTraceGroupList = 32,
        EtwGetTraceGroupInfo = 33,
        EtwGetDisallowList = 34,
        EtwSetCompressionSettings = 35,
        EtwGetCompressionSettings = 36,
        EtwUpdatePeriodicCaptureState = 37,
        EtwGetPrivateSessionTraceHandle = 38,
        EtwRegisterPrivateSession = 39,
        EtwQuerySessionDemuxObject = 40,
        EtwSetProviderBinaryTracking = 41,
        EtwMaxLoggers = 42, // out ULONG
        EtwMaxPmcCounter = 43, // out ULONG
        EtwQueryUsedProcessorCount = 44, // ULONG // since WIN11
        EtwGetPmcOwnership = 45,
        EtwGetPmcSessions = 46,
    } ETWTRACECONTROLCODE;

    // public TRACE_PROVIDER_INSTANCE_INFO
    typedef struct _ETW_TRACE_PROVIDER_INSTANCE_INFO
    {
        ULONG NextOffset;
        ULONG EnableCount;
        ULONG Pid;
        ULONG Flags;
    } ETW_TRACE_PROVIDER_INSTANCE_INFO, * PETW_TRACE_PROVIDER_INSTANCE_INFO;

    // public TRACE_GUID_INFO
    typedef struct _ETW_TRACE_GUID_INFO
    {
        ULONG InstanceCount;
        ULONG Reserved;
        //ETW_TRACE_PROVIDER_INSTANCE_INFO Instances[1];
    } ETW_TRACE_GUID_INFO, * PETW_TRACE_GUID_INFO;

    typedef struct _ETW_REF_CLOCK
    {
        LARGE_INTEGER StartTime;
        LARGE_INTEGER StartPerfClock;
    } ETW_REF_CLOCK, * PETW_REF_CLOCK;

#if (PHNT_VERSION >= PHNT_VISTA)

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        NtTraceControl(
            _In_ ETWTRACECONTROLCODE TraceControlCode,
            _In_reads_bytes_opt_(InputBufferLength) PVOID InputBuffer,
            _In_ ULONG InputBufferLength,
            _Out_writes_bytes_opt_(OutputBufferLength) PVOID OutputBuffer,
            _In_ ULONG OutputBufferLength,
            _Out_ PULONG ReturnLength
        );

#endif

    //
    // Maximum supported buffer size in KB - Win8 (16MB)
    //
    // N.B. Prior to Win8 the value was 1MB (1024KB).
#define MIN_ETW_BUFFER_SIZE      1             // in KBytes
#define MAX_ETW_BUFFER_SIZE      (16 * 1024)   // in KBytes
#define MAX_ETW_BUFFER_SIZE_WIN7 (1 * 1024)    // in KBytes
#define MAX_ETW_EVENT_SIZE       0xFFFF        // MAX_USHORT

#define ETW_KERNEL_RUNDOWN_START 0x00000001
#define ETW_KERNEL_RUNDOWN_STOP  0x00000002
#define ETW_CKCL_RUNDOWN_START   0x00000004
#define ETW_CKCL_RUNDOWN_STOP    0x00000008
#define ETW_FILENAME_RUNDOWN     0x00000010

//
// Constants for UMGL (User Mode Global Logging).
//
// N.B. There is enough space reserved in UserSharedData
//      to support up to 16 providers, but to avoid needless
//      scanning MAX_PROVIDERS constant is currently set to 8.
//
// N.B. Heap and CritSec providers can be controlled with IFEO
//      making the indexes fixed.
#define ETW_UMGL_INDEX_HEAP             0
#define ETW_UMGL_INDEX_CRITSEC          1
#define ETW_UMGL_INDEX_LDR              2
#define ETW_UMGL_INDEX_THREAD_POOL      3
#define ETW_UMGL_INDEX_HEAPRANGE        4
#define ETW_UMGL_INDEX_HEAPSUMMARY      5
#define ETW_UMGL_INDEX_UMS              6
#define ETW_UMGL_INDEX_WNF              7
#define ETW_UMGL_INDEX_THREAD           8
#define ETW_UMGL_INDEX_SPARE2           9
#define ETW_UMGL_INDEX_SPARE3           10
#define ETW_UMGL_INDEX_SPARE4           11
#define ETW_UMGL_INDEX_SPARE5           12
#define ETW_UMGL_INDEX_SPARE6           13
#define ETW_UMGL_INDEX_SPARE7           14
#define ETW_UMGL_INDEX_SPARE8           15

#define ETW_UMGL_MAX_PROVIDERS          9

    typedef struct _ETW_UMGL_KEY
    {
        UCHAR LoggerId;
        UCHAR Flags;
    } ETW_UMGL_KEY, * PETW_UMGL_KEY;

#define UMGL_LOGGER_ID(Index)               (((PETW_UMGL_KEY)(&USER_SHARED_DATA->UserModeGlobalLogger[Index]))->LoggerId)
#define UMGL_LOGGER_FLAGS(Index)            (((PETW_UMGL_KEY)(&USER_SHARED_DATA->UserModeGlobalLogger[Index]))->Flags)
#define IS_UMGL_LOGGING_ENABLED(Index)      (UMGL_LOGGER_ID(Index) != 0)
#define IS_UMGL_FLAG_ENABLED(Index, Flag)   ((UMGL_LOGGER_FLAGS(Index) & Flag) != 0)

#define IS_HEAP_LOGGING_ENABLED()           (IS_UMGL_LOGGING_ENABLED(ETW_UMGL_INDEX_HEAP) && (NtCurrentPeb()->HeapTracingEnabled != FALSE))
#define IS_HEAP_RANGE_LOGGING_ENABLED()     (IS_UMGL_LOGGING_ENABLED(ETW_UMGL_INDEX_HEAPRANGE))
#define HEAP_LOGGER_ID                      (UMGL_LOGGER_ID(ETW_UMGL_INDEX_HEAP))

#define IS_CRITSEC_LOGGING_ENABLED()        (IS_UMGL_LOGGING_ENABLED(ETW_UMGL_INDEX_CRITSEC) && (NtCurrentPeb()->CritSecTracingEnabled != FALSE))
#define CRITSEC_LOGGER_ID                   (UMGL_LOGGER_ID(ETW_UMGL_INDEX_CRITSEC))
#define IS_LOADER_LOGGING_ENABLED_FLAG(Flag) (IS_UMGL_LOGGING_ENABLED(ETW_UMGL_INDEX_LDR) && ((UMGL_LOGGER_FLAGS(ETW_UMGL_INDEX_LDR) & Flag) != 0) )
#define IS_PER_PROCESS_LOADER_LOGGING_ENABLED_FLAG(Flag) (IS_UMGL_LOGGING_ENABLED(ETW_UMGL_INDEX_LDR) && (NtCurrentPeb()->LibLoaderTracingEnabled != FALSE) && ((UMGL_LOGGER_FLAGS(ETW_UMGL_INDEX_LDR) & Flag) != 0) )
#define IS_GLOBAL_LOADER_LOGGING_ENABLED()  (IS_UMGL_LOGGING_ENABLED(ETW_UMGL_INDEX_LDR))
#define LOADER_LOGGER_ID                    (UMGL_LOGGER_ID(ETW_UMGL_INDEX_LDR))
#define HEAPRANGE_LOGGER_ID                 (UMGL_LOGGER_ID(ETW_UMGL_INDEX_HEAPRANGE))
#define IS_THREAD_POOL_LOGGING_ENABLED()    (IS_UMGL_LOGGING_ENABLED(ETW_UMGL_INDEX_THREAD_POOL))
#define THREAD_POOL_LOGGER_ID               (UMGL_LOGGER_ID(ETW_UMGL_INDEX_THREAD_POOL))
#define IS_UMS_LOGGING_ENABLED()            (IS_UMGL_LOGGING_ENABLED(ETW_UMGL_INDEX_UMS))
#define UMS_LOGGER_ID                       (UMGL_LOGGER_ID(ETW_UMGL_INDEX_UMS))
#define HEAPSUMMARY_LOGGER_ID               (UMGL_LOGGER_ID(ETW_UMGL_INDEX_HEAPSUMMARY))
#define IS_HEAPSUMMARY_LOGGING_ENABLED()    (IS_UMGL_LOGGING_ENABLED(ETW_UMGL_INDEX_HEAPSUMMARY))
#define WNF_LOGGER_ID                       (UMGL_LOGGER_ID(ETW_UMGL_INDEX_WNF))
#define IS_WNF_LOGGING_ENABLED()            (IS_UMGL_LOGGING_ENABLED(ETW_UMGL_INDEX_WNF))
#define UMGL_THREAD_LOGGER_ID               (UMGL_LOGGER_ID(ETW_UMGL_INDEX_THREAD))
#define IS_UMGL_THREAD_LOGGING_ENABLED()    (IS_UMGL_LOGGING_ENABLED(ETW_UMGL_INDEX_THREAD))

    //
    // Flags used by user mode loader logging to UMGL.
    //
#define ETW_UMGL_LDR_MUI_VERBOSE_FLAG 0x0001
#define ETW_UMGL_LDR_MUI_TEST_FLAG    0x0002
#define ETW_UMGL_LDR_RELOCATION_FLAG  0x0004
#define ETW_UMGL_LDR_NEW_DLL_FLAG   0x0010
#define ETW_UMGL_LDR_TEST_FLAG      0x0020
#define ETW_UMGL_LDR_SECURITY_FLAG  0x0040

//
// Constants for heap log
//
#define MEMORY_FROM_LOOKASIDE                   1       //Activity from LookAside
#define MEMORY_FROM_LOWFRAG                     2       //Activity from Low Frag Heap
#define MEMORY_FROM_MAINPATH                    3       //Activity from Main Code Path
#define MEMORY_FROM_SLOWPATH                    4       //Activity from Slow C
#define MEMORY_FROM_INVALID                     5
#define MEMORY_FROM_SEGMENT_HEAP                6       //Activity from segment heap.

//
// Header preparation macro for UMGL
//
#define TRACE_HEADER_TYPE_SYSTEM32          1
#define TRACE_HEADER_TYPE_SYSTEM64          2
#define TRACE_HEADER_TYPE_COMPACT32         3
#define TRACE_HEADER_TYPE_COMPACT64         4
#define TRACE_HEADER_TYPE_FULL_HEADER32     10
#define TRACE_HEADER_TYPE_INSTANCE32        11
#define TRACE_HEADER_TYPE_TIMED             12  // Not used
#define TRACE_HEADER_TYPE_ERROR             13  // Error while logging event
#define TRACE_HEADER_TYPE_WNODE_HEADER      14  // Not used
#define TRACE_HEADER_TYPE_MESSAGE           15
#define TRACE_HEADER_TYPE_PERFINFO32        16
#define TRACE_HEADER_TYPE_PERFINFO64        17
#define TRACE_HEADER_TYPE_EVENT_HEADER32    18
#define TRACE_HEADER_TYPE_EVENT_HEADER64    19
#define TRACE_HEADER_TYPE_FULL_HEADER64     20
#define TRACE_HEADER_TYPE_INSTANCE64        21

#define EVENT_HEADER_SIZE_MASK              0x0000FFFF

#define SYSTEM_TRACE_VERSION                 2

#define TRACE_HEADER_FLAG                   0x80000000

#define EVENT_HEADER_EVENT64      ((USHORT)(((TRACE_HEADER_FLAG | TRACE_HEADER_EVENT_TRACE) >> 16) | TRACE_HEADER_TYPE_EVENT_HEADER64))
#define EVENT_HEADER_EVENT32      ((USHORT)(((TRACE_HEADER_FLAG | TRACE_HEADER_EVENT_TRACE) >> 16) | TRACE_HEADER_TYPE_EVENT_HEADER32))
#define EVENT_HEADER_ERROR        ((USHORT)(((TRACE_HEADER_FLAG | TRACE_HEADER_EVENT_TRACE) >> 16) | TRACE_HEADER_TYPE_ERROR))
#define TRACE_HEADER_FULL32       (TRACE_HEADER_FLAG | TRACE_HEADER_EVENT_TRACE | (TRACE_HEADER_TYPE_FULL_HEADER32 << 16))
#define TRACE_HEADER_FULL64       (TRACE_HEADER_FLAG | TRACE_HEADER_EVENT_TRACE | (TRACE_HEADER_TYPE_FULL_HEADER64 << 16))
#define TRACE_HEADER_INSTANCE32   (TRACE_HEADER_FLAG | TRACE_HEADER_EVENT_TRACE | (TRACE_HEADER_TYPE_INSTANCE32 << 16))
#define TRACE_HEADER_INSTANCE64   (TRACE_HEADER_FLAG | TRACE_HEADER_EVENT_TRACE | (TRACE_HEADER_TYPE_INSTANCE64 << 16))

#ifdef _WIN64
#define EVENT_HEADER_EVENT      EVENT_HEADER_EVENT64
#define TRACE_HEADER_FULL       TRACE_HEADER_FULL64
#define TRACE_HEADER_INSTANCE   TRACE_HEADER_INSTANCE64
#else
#define EVENT_HEADER_EVENT      EVENT_HEADER_EVENT32
#define TRACE_HEADER_FULL       TRACE_HEADER_FULL32
#define TRACE_HEADER_INSTANCE   TRACE_HEADER_INSTANCE32
#endif

#define PREPARE_ETW_TRACE_HEADER_GUID(Header, EventStruct, EventType, EventGuid, LoggerId) \
    (Header)->Size = sizeof(EventStruct); \
    (Header)->Class.Type = (EventType); \
    RtlCopyMemory(&((Header)->Guid), (EventGuid), sizeof(*(EventGuid))); \

// Used with OpenTrace(), prevents conversion of TimeStamps to UTC
#define EVENT_TRACE_USE_RAWTIMESTAMP 0x00000002
// Used with OpenTrace(), retrieves event from file as is.
#define EVENT_TRACE_GET_RAWEVENT 0x00000100
// Used with OpenTrace() to ReadBehind  a live logger session
#define EVENT_TRACE_READ_BEHIND 0x00000200
// Used in EventCallbacks to indicate that the InstanceId field is a sequence number.
#define EVENT_TRACE_USE_SEQUENCE  0x0004
// Kernel Event Version is used to indicate if any kernel event has changed.
#define ETW_KERNEL_EVENT_VERSION 60

    typedef struct _ETW_KERNEL_HEADER_EXTENSION
    {
        PERFINFO_GROUPMASK GroupMasks;
        ULONG Version;
    } ETW_KERNEL_HEADER_EXTENSION, * PETW_KERNEL_HEADER_EXTENSION;

#define ETW_SET_MARK_WITH_FLUSH 0x00000001

    typedef struct _ETW_SET_MARK_INFORMATION
    {
        ULONG Flag;
        WCHAR Mark[1];
    } ETW_SET_MARK_INFORMATION, * PETW_SET_MARK_INFORMATION;

    //
    // Data Block structure for ETW notification
    //
    typedef enum _ETW_NOTIFICATION_TYPE
    {
        EtwNotificationTypeNoReply = 1,     // No data block reply
        EtwNotificationTypeLegacyEnable,    // Enable notification for RegisterTraceGuids
        EtwNotificationTypeEnable,          // Enable notification for EventRegister
        EtwNotificationTypePrivateLogger,   // Private logger notification for ETW
        EtwNotificationTypePerflib,         // PERFLIB V2 counter data request/delivery block
        EtwNotificationTypeAudio,           // Private notification for audio policy
        EtwNotificationTypeSession,         // Session related ETW notifications
        EtwNotificationTypeReserved,        // For internal use (test)
        EtwNotificationTypeCredentialUI,    // Private notification for media center elevation detection
        EtwNotificationTypeInProcSession,   // Private in-proc session related ETW notifications
        EtwNotificationTypeMax
    } ETW_NOTIFICATION_TYPE;

#define ETW_MAX_DATA_BLOCK_BUFFER_SIZE (65536)

    typedef struct _ETW_NOTIFICATION_HEADER
    {
        ETW_NOTIFICATION_TYPE NotificationType; // Notification type
        ULONG                 NotificationSize; // Notification size in bytes
        ULONG                 Offset;           // Offset to the next notification
        BOOLEAN               ReplyRequested;   // Reply Requested
        ULONG                 Timeout;          // Timeout in milliseconds when requesting reply
        union
        {
            ULONG             ReplyCount;       // Out to sender: the number of notifications sent
            ULONG             NotifyeeCount;    // Out to notifyee: the order during notification
        };
        ULONGLONG             Reserved2;
        ULONG                 TargetPID;
        ULONG                 SourcePID;
        GUID                  DestinationGuid;  // Desctination GUID
        GUID                  SourceGuid;       // Source GUID
    } ETW_NOTIFICATION_HEADER, * PETW_NOTIFICATION_HEADER;

    typedef ULONG(NTAPI* PETW_NOTIFICATION_CALLBACK)(
        _In_ PETW_NOTIFICATION_HEADER NotificationHeader,
        _In_ PVOID Context
        );

    typedef enum _ETW_SESSION_NOTIFICATION_TYPE
    {
        EtwSessionNotificationMediaChanged = 1,
        EtwSessionNotificationSessionTerminated,
        EtwSessionNotificationLogfileError,
        EtwSessionNotificationRealtimeError,
        EtwSessionNotificationSessionStarted,
        EtwSessionNotificationMax
    } ETW_SESSION_NOTIFICATION_TYPE;

    typedef struct _ETW_SESSION_NOTIFICATION_PACKET
    {
        ETW_NOTIFICATION_HEADER NotificationHeader;
        ETW_SESSION_NOTIFICATION_TYPE Type;
        NTSTATUS Status;
        TRACEHANDLE TraceHandle;
        ULONG Reserved[2];
    } ETW_SESSION_NOTIFICATION_PACKET, * PETW_SESSION_NOTIFICATION_PACKET;

#if (PHNT_MODE != PHNT_MODE_KERNEL)

#ifndef EVENT_DESCRIPTOR_DEF
#define EVENT_DESCRIPTOR_DEF
    typedef struct _EVENT_DESCRIPTOR
    {
        USHORT Id;
        UCHAR Version;
        UCHAR Channel;
        UCHAR Level;
        UCHAR Opcode;
        USHORT Task;
        ULONGLONG Keyword;
    } EVENT_DESCRIPTOR, * PEVENT_DESCRIPTOR;
    typedef const EVENT_DESCRIPTOR* PCEVENT_DESCRIPTOR;
#endif

    NTSYSAPI
        ULONG
        NTAPI
        EtwSetMark(
            _In_opt_ TRACEHANDLE TraceHandle,
            _In_ PETW_SET_MARK_INFORMATION MarkInfo,
            _In_ ULONG Size
        );

    typedef struct _EVENT_DATA_DESCRIPTOR EVENT_DATA_DESCRIPTOR, * PEVENT_DATA_DESCRIPTOR;

    NTSYSAPI
        ULONG
        NTAPI
        EtwEventWriteFull(
            _In_ REGHANDLE RegHandle,
            _In_ PCEVENT_DESCRIPTOR EventDescriptor,
            _In_ USHORT EventProperty,
            _In_opt_ LPCGUID ActivityId,
            _In_opt_ LPCGUID RelatedActivityId,
            _In_ ULONG UserDataCount,
            _In_reads_opt_(UserDataCount) PEVENT_DATA_DESCRIPTOR UserData
        );

    //NTSYSAPI
    //ULONG
    //NTAPI
    //EtwEventRegister(
    //    _In_ LPCGUID ProviderId,
    //    _In_opt_ PENABLECALLBACK EnableCallback,
    //    _In_opt_ PVOID CallbackContext,
    //    _Out_ PREGHANDLE RegHandle
    //    );

    NTSYSAPI
        ULONG
        NTAPI
        EtwEventUnregister(
            _In_ REGHANDLE RegHandle
        );

    typedef enum _EVENT_INFO_CLASS EVENT_INFO_CLASS;

    NTSYSAPI
        ULONG
        NTAPI
        EtwEventSetInformation(
            _In_ REGHANDLE RegHandle,
            _In_ EVENT_INFO_CLASS InformationClass,
            _In_reads_bytes_(InformationLength) PVOID EventInformation,
            _In_ ULONG InformationLength
        );

    NTSYSAPI
        ULONG
        NTAPI
        EtwRegisterSecurityProvider(
            VOID
        );

    NTSYSAPI
        BOOLEAN
        NTAPI
        EtwEventProviderEnabled(
            _In_ REGHANDLE RegHandle,
            _In_ UCHAR Level,
            _In_ ULONGLONG Keyword
        );

    NTSYSAPI
        BOOLEAN
        NTAPI
        EtwEventEnabled(
            _In_ REGHANDLE RegHandle,
            _In_ PCEVENT_DESCRIPTOR EventDescriptor
        );

    NTSYSAPI
        ULONG
        NTAPI
        EtwEventWrite(
            _In_ REGHANDLE RegHandle,
            _In_ PCEVENT_DESCRIPTOR EventDescriptor,
            _In_ ULONG UserDataCount,
            _In_reads_opt_(UserDataCount) PEVENT_DATA_DESCRIPTOR UserData
        );

    NTSYSAPI
        ULONG
        NTAPI
        EtwEventWriteTransfer(
            _In_ REGHANDLE RegHandle,
            _In_ PCEVENT_DESCRIPTOR EventDescriptor,
            _In_opt_ LPCGUID ActivityId,
            _In_opt_ LPCGUID RelatedActivityId,
            _In_ ULONG UserDataCount,
            _In_reads_opt_(UserDataCount) PEVENT_DATA_DESCRIPTOR UserData
        );

    NTSYSAPI
        ULONG
        NTAPI
        EtwEventWriteString(
            _In_ REGHANDLE RegHandle,
            _In_ UCHAR Level,
            _In_ ULONGLONG Keyword,
            _In_ PCWSTR String
        );

    ULONG
        NTAPI
        EtwEventWriteEx(
            _In_ REGHANDLE RegHandle,
            _In_ PCEVENT_DESCRIPTOR EventDescriptor,
            _In_ ULONG64 Filter,
            _In_ ULONG Flags,
            _In_opt_ LPCGUID ActivityId,
            _In_opt_ LPCGUID RelatedActivityId,
            _In_ ULONG UserDataCount,
            _In_reads_opt_(UserDataCount) PEVENT_DATA_DESCRIPTOR UserData
        );

    NTSYSAPI
        ULONG
        NTAPI
        EtwEventWriteStartScenario(
            _In_ REGHANDLE RegHandle,
            _In_ PCEVENT_DESCRIPTOR EventDescriptor,
            _In_ ULONG UserDataCount,
            _In_reads_opt_(UserDataCount) PEVENT_DATA_DESCRIPTOR UserData
        );

    NTSYSAPI
        ULONG
        NTAPI
        EtwEventWriteEndScenario(
            _In_ REGHANDLE RegHandle,
            _In_ PCEVENT_DESCRIPTOR EventDescriptor,
            _In_ ULONG UserDataCount,
            _In_reads_opt_(UserDataCount) PEVENT_DATA_DESCRIPTOR UserData
        );

    NTSYSAPI
        ULONG
        NTAPI
        EtwWriteUMSecurityEvent(
            _In_ PCEVENT_DESCRIPTOR EventDescriptor,
            _In_ USHORT EventProperty,
            _In_ ULONG UserDataCount,
            _In_opt_ PEVENT_DATA_DESCRIPTOR UserData
        );

    ULONG
        NTAPI
        EtwEventWriteNoRegistration(
            _In_ LPCGUID ProviderId,
            _In_ PCEVENT_DESCRIPTOR EventDescriptor,
            _In_ ULONG UserDataCount,
            _In_reads_opt_(UserDataCount) PEVENT_DATA_DESCRIPTOR UserData
        );

    NTSYSAPI
        ULONG
        NTAPI
        EtwEventActivityIdControl(
            _In_ ULONG ControlCode,
            _Inout_ LPGUID ActivityId
        );

    NTSYSAPI
        ULONG
        NTAPI
        EtwNotificationRegister(
            _In_ LPCGUID Guid,
            _In_ ULONG Type,
            _In_ PETW_NOTIFICATION_CALLBACK Callback,
            _In_opt_ PVOID Context,
            _Out_ PREGHANDLE RegHandle
        );

    NTSYSAPI
        ULONG
        NTAPI
        EtwNotificationUnregister(
            _In_ REGHANDLE RegHandle,
            _Out_opt_ PVOID* Context
        );

    NTSYSAPI
        ULONG
        NTAPI
        EtwSendNotification(
            _In_ PETW_NOTIFICATION_HEADER DataBlock,
            _In_ ULONG ReceiveDataBlockSize,
            _Inout_ PVOID ReceiveDataBlock,
            _Out_ PULONG ReplyReceived,
            _Out_ PULONG ReplySizeNeeded
        );

    NTSYSAPI
        ULONG
        NTAPI
        EtwReplyNotification(
            _In_ PETW_NOTIFICATION_HEADER Notification
        );

    NTSYSAPI
        ULONG
        NTAPI
        EtwEnumerateProcessRegGuids(
            _Out_writes_bytes_opt_(OutBufferSize) PVOID OutBuffer,
            _In_ ULONG OutBufferSize,
            _Out_ PULONG ReturnLength
        );

    NTSYSAPI
        ULONG
        NTAPI
        EtwQueryRealtimeConsumer(
            _In_ TRACEHANDLE TraceHandle,
            _Out_ PULONG EventsLostCount,
            _Out_ PULONG BuffersLostCount
        );

#endif

#endif

#ifndef _NTZWAPI_H
#define _NTZWAPI_H

    // This file was automatically generated. Do not edit.

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwAcceptConnectPort(
            _Out_ PHANDLE PortHandle,
            _In_opt_ PVOID PortContext,
            _In_ PPORT_MESSAGE ConnectionRequest,
            _In_ BOOLEAN AcceptConnection,
            _Inout_opt_ PPORT_VIEW ServerView,
            _Out_opt_ PREMOTE_PORT_VIEW ClientView
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwAccessCheck(
            _In_ PSECURITY_DESCRIPTOR SecurityDescriptor,
            _In_ HANDLE ClientToken,
            _In_ ACCESS_MASK DesiredAccess,
            _In_ PGENERIC_MAPPING GenericMapping,
            _Out_writes_bytes_(*PrivilegeSetLength) PPRIVILEGE_SET PrivilegeSet,
            _Inout_ PULONG PrivilegeSetLength,
            _Out_ PACCESS_MASK GrantedAccess,
            _Out_ PNTSTATUS AccessStatus
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwAccessCheckAndAuditAlarm(
            _In_ PUNICODE_STRING SubsystemName,
            _In_opt_ PVOID HandleId,
            _In_ PUNICODE_STRING ObjectTypeName,
            _In_ PUNICODE_STRING ObjectName,
            _In_ PSECURITY_DESCRIPTOR SecurityDescriptor,
            _In_ ACCESS_MASK DesiredAccess,
            _In_ PGENERIC_MAPPING GenericMapping,
            _In_ BOOLEAN ObjectCreation,
            _Out_ PACCESS_MASK GrantedAccess,
            _Out_ PNTSTATUS AccessStatus,
            _Out_ PBOOLEAN GenerateOnClose
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwAccessCheckByType(
            _In_ PSECURITY_DESCRIPTOR SecurityDescriptor,
            _In_opt_ PSID PrincipalSelfSid,
            _In_ HANDLE ClientToken,
            _In_ ACCESS_MASK DesiredAccess,
            _In_reads_(ObjectTypeListLength) POBJECT_TYPE_LIST ObjectTypeList,
            _In_ ULONG ObjectTypeListLength,
            _In_ PGENERIC_MAPPING GenericMapping,
            _Out_writes_bytes_(*PrivilegeSetLength) PPRIVILEGE_SET PrivilegeSet,
            _Inout_ PULONG PrivilegeSetLength,
            _Out_ PACCESS_MASK GrantedAccess,
            _Out_ PNTSTATUS AccessStatus
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwAccessCheckByTypeAndAuditAlarm(
            _In_ PUNICODE_STRING SubsystemName,
            _In_opt_ PVOID HandleId,
            _In_ PUNICODE_STRING ObjectTypeName,
            _In_ PUNICODE_STRING ObjectName,
            _In_ PSECURITY_DESCRIPTOR SecurityDescriptor,
            _In_opt_ PSID PrincipalSelfSid,
            _In_ ACCESS_MASK DesiredAccess,
            _In_ AUDIT_EVENT_TYPE AuditType,
            _In_ ULONG Flags,
            _In_reads_opt_(ObjectTypeListLength) POBJECT_TYPE_LIST ObjectTypeList,
            _In_ ULONG ObjectTypeListLength,
            _In_ PGENERIC_MAPPING GenericMapping,
            _In_ BOOLEAN ObjectCreation,
            _Out_ PACCESS_MASK GrantedAccess,
            _Out_ PNTSTATUS AccessStatus,
            _Out_ PBOOLEAN GenerateOnClose
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwAccessCheckByTypeResultList(
            _In_ PSECURITY_DESCRIPTOR SecurityDescriptor,
            _In_opt_ PSID PrincipalSelfSid,
            _In_ HANDLE ClientToken,
            _In_ ACCESS_MASK DesiredAccess,
            _In_reads_(ObjectTypeListLength) POBJECT_TYPE_LIST ObjectTypeList,
            _In_ ULONG ObjectTypeListLength,
            _In_ PGENERIC_MAPPING GenericMapping,
            _Out_writes_bytes_(*PrivilegeSetLength) PPRIVILEGE_SET PrivilegeSet,
            _Inout_ PULONG PrivilegeSetLength,
            _Out_writes_(ObjectTypeListLength) PACCESS_MASK GrantedAccess,
            _Out_writes_(ObjectTypeListLength) PNTSTATUS AccessStatus
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwAccessCheckByTypeResultListAndAuditAlarm(
            _In_ PUNICODE_STRING SubsystemName,
            _In_opt_ PVOID HandleId,
            _In_ PUNICODE_STRING ObjectTypeName,
            _In_ PUNICODE_STRING ObjectName,
            _In_ PSECURITY_DESCRIPTOR SecurityDescriptor,
            _In_opt_ PSID PrincipalSelfSid,
            _In_ ACCESS_MASK DesiredAccess,
            _In_ AUDIT_EVENT_TYPE AuditType,
            _In_ ULONG Flags,
            _In_reads_opt_(ObjectTypeListLength) POBJECT_TYPE_LIST ObjectTypeList,
            _In_ ULONG ObjectTypeListLength,
            _In_ PGENERIC_MAPPING GenericMapping,
            _In_ BOOLEAN ObjectCreation,
            _Out_writes_(ObjectTypeListLength) PACCESS_MASK GrantedAccess,
            _Out_writes_(ObjectTypeListLength) PNTSTATUS AccessStatus,
            _Out_ PBOOLEAN GenerateOnClose
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwAccessCheckByTypeResultListAndAuditAlarmByHandle(
            _In_ PUNICODE_STRING SubsystemName,
            _In_opt_ PVOID HandleId,
            _In_ HANDLE ClientToken,
            _In_ PUNICODE_STRING ObjectTypeName,
            _In_ PUNICODE_STRING ObjectName,
            _In_ PSECURITY_DESCRIPTOR SecurityDescriptor,
            _In_opt_ PSID PrincipalSelfSid,
            _In_ ACCESS_MASK DesiredAccess,
            _In_ AUDIT_EVENT_TYPE AuditType,
            _In_ ULONG Flags,
            _In_reads_opt_(ObjectTypeListLength) POBJECT_TYPE_LIST ObjectTypeList,
            _In_ ULONG ObjectTypeListLength,
            _In_ PGENERIC_MAPPING GenericMapping,
            _In_ BOOLEAN ObjectCreation,
            _Out_writes_(ObjectTypeListLength) PACCESS_MASK GrantedAccess,
            _Out_writes_(ObjectTypeListLength) PNTSTATUS AccessStatus,
            _Out_ PBOOLEAN GenerateOnClose
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwAcquireCMFViewOwnership(
            _Out_ PULONGLONG TimeStamp,
            _Out_ PBOOLEAN tokenTaken,
            _In_ BOOLEAN replaceExisting
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwAddAtom(
            _In_reads_bytes_opt_(Length) PWSTR AtomName,
            _In_ ULONG Length,
            _Out_opt_ PRTL_ATOM Atom
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwAddAtomEx(
            _In_reads_bytes_opt_(Length) PWSTR AtomName,
            _In_ ULONG Length,
            _Out_opt_ PRTL_ATOM Atom,
            _In_ ULONG Flags
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwAddBootEntry(
            _In_ PBOOT_ENTRY BootEntry,
            _Out_opt_ PULONG Id
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwAddDriverEntry(
            _In_ PEFI_DRIVER_ENTRY DriverEntry,
            _Out_opt_ PULONG Id
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwAdjustGroupsToken(
            _In_ HANDLE TokenHandle,
            _In_ BOOLEAN ResetToDefault,
            _In_opt_ PTOKEN_GROUPS NewState,
            _In_opt_ ULONG BufferLength,
            _Out_writes_bytes_to_opt_(BufferLength, *ReturnLength) PTOKEN_GROUPS PreviousState,
            _Out_opt_ PULONG ReturnLength
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwAdjustPrivilegesToken(
            _In_ HANDLE TokenHandle,
            _In_ BOOLEAN DisableAllPrivileges,
            _In_opt_ PTOKEN_PRIVILEGES NewState,
            _In_ ULONG BufferLength,
            _Out_writes_bytes_to_opt_(BufferLength, *ReturnLength) PTOKEN_PRIVILEGES PreviousState,
            _Out_opt_ PULONG ReturnLength
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwAdjustTokenClaimsAndDeviceGroups(
            _In_ HANDLE TokenHandle,
            _In_ BOOLEAN UserResetToDefault,
            _In_ BOOLEAN DeviceResetToDefault,
            _In_ BOOLEAN DeviceGroupsResetToDefault,
            _In_opt_ PTOKEN_SECURITY_ATTRIBUTES_INFORMATION NewUserState,
            _In_opt_ PTOKEN_SECURITY_ATTRIBUTES_INFORMATION NewDeviceState,
            _In_opt_ PTOKEN_GROUPS NewDeviceGroupsState,
            _In_ ULONG UserBufferLength,
            _Out_writes_bytes_to_opt_(UserBufferLength, *UserReturnLength) PTOKEN_SECURITY_ATTRIBUTES_INFORMATION PreviousUserState,
            _In_ ULONG DeviceBufferLength,
            _Out_writes_bytes_to_opt_(DeviceBufferLength, *DeviceReturnLength) PTOKEN_SECURITY_ATTRIBUTES_INFORMATION PreviousDeviceState,
            _In_ ULONG DeviceGroupsBufferLength,
            _Out_writes_bytes_to_opt_(DeviceGroupsBufferLength, *DeviceGroupsReturnBufferLength) PTOKEN_GROUPS PreviousDeviceGroups,
            _Out_opt_ PULONG UserReturnLength,
            _Out_opt_ PULONG DeviceReturnLength,
            _Out_opt_ PULONG DeviceGroupsReturnBufferLength
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwAlertResumeThread(
            _In_ HANDLE ThreadHandle,
            _Out_opt_ PULONG PreviousSuspendCount
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwAlertThread(
            _In_ HANDLE ThreadHandle
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwAlertThreadByThreadId(
            _In_ HANDLE ThreadId
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwAllocateLocallyUniqueId(
            _Out_ PLUID Luid
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwAllocateReserveObject(
            _Out_ PHANDLE MemoryReserveHandle,
            _In_ POBJECT_ATTRIBUTES ObjectAttributes,
            _In_ MEMORY_RESERVE_TYPE Type
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwAllocateUserPhysicalPages(
            _In_ HANDLE ProcessHandle,
            _Inout_ PULONG_PTR NumberOfPages,
            _Out_writes_(*NumberOfPages) PULONG_PTR UserPfnArray
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwAllocateUserPhysicalPagesEx(
            _In_ HANDLE ProcessHandle,
            _Inout_ PULONG_PTR NumberOfPages,
            _Out_writes_(*NumberOfPages) PULONG_PTR UserPfnArray,
            _Inout_updates_opt_(ParameterCount) PMEM_EXTENDED_PARAMETER ExtendedParameters,
            _In_ ULONG ExtendedParameterCount
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwAllocateUuids(
            _Out_ PULARGE_INTEGER Time,
            _Out_ PULONG Range,
            _Out_ PULONG Sequence,
            _Out_ PCHAR Seed
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwAllocateVirtualMemory(
            _In_ HANDLE ProcessHandle,
            _Inout_ _At_(*BaseAddress, _Readable_bytes_(*RegionSize) _Writable_bytes_(*RegionSize) _Post_readable_byte_size_(*RegionSize)) PVOID* BaseAddress,
            _In_ ULONG_PTR ZeroBits,
            _Inout_ PSIZE_T RegionSize,
            _In_ ULONG AllocationType,
            _In_ ULONG Protect
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwAllocateVirtualMemoryEx(
            _In_ HANDLE ProcessHandle,
            _Inout_ _At_(*BaseAddress, _Readable_bytes_(*RegionSize) _Writable_bytes_(*RegionSize) _Post_readable_byte_size_(*RegionSize)) PVOID* BaseAddress,
            _Inout_ PSIZE_T RegionSize,
            _In_ ULONG AllocationType,
            _In_ ULONG PageProtection,
            _Inout_updates_opt_(ExtendedParameterCount) PMEM_EXTENDED_PARAMETER ExtendedParameters,
            _In_ ULONG ExtendedParameterCount
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwAlpcAcceptConnectPort(
            _Out_ PHANDLE PortHandle,
            _In_ HANDLE ConnectionPortHandle,
            _In_ ULONG Flags,
            _In_opt_ POBJECT_ATTRIBUTES ObjectAttributes,
            _In_opt_ PALPC_PORT_ATTRIBUTES PortAttributes,
            _In_opt_ PVOID PortContext,
            _In_reads_bytes_(ConnectionRequest->u1.s1.TotalLength) PPORT_MESSAGE ConnectionRequest,
            _Inout_opt_ PALPC_MESSAGE_ATTRIBUTES ConnectionMessageAttributes,
            _In_ BOOLEAN AcceptConnection
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwAlpcCancelMessage(
            _In_ HANDLE PortHandle,
            _In_ ULONG Flags,
            _In_ PALPC_CONTEXT_ATTR MessageContext
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwAlpcConnectPort(
            _Out_ PHANDLE PortHandle,
            _In_ PUNICODE_STRING PortName,
            _In_opt_ POBJECT_ATTRIBUTES ObjectAttributes,
            _In_opt_ PALPC_PORT_ATTRIBUTES PortAttributes,
            _In_ ULONG Flags,
            _In_opt_ PSID RequiredServerSid,
            _Inout_updates_bytes_to_opt_(*BufferLength, *BufferLength) PPORT_MESSAGE ConnectionMessage,
            _Inout_opt_ PULONG BufferLength,
            _Inout_opt_ PALPC_MESSAGE_ATTRIBUTES OutMessageAttributes,
            _Inout_opt_ PALPC_MESSAGE_ATTRIBUTES InMessageAttributes,
            _In_opt_ PLARGE_INTEGER Timeout
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwAlpcConnectPortEx(
            _Out_ PHANDLE PortHandle,
            _In_ POBJECT_ATTRIBUTES ConnectionPortObjectAttributes,
            _In_opt_ POBJECT_ATTRIBUTES ClientPortObjectAttributes,
            _In_opt_ PALPC_PORT_ATTRIBUTES PortAttributes,
            _In_ ULONG Flags,
            _In_opt_ PSECURITY_DESCRIPTOR ServerSecurityRequirements,
            _Inout_updates_bytes_to_opt_(*BufferLength, *BufferLength) PPORT_MESSAGE ConnectionMessage,
            _Inout_opt_ PSIZE_T BufferLength,
            _Inout_opt_ PALPC_MESSAGE_ATTRIBUTES OutMessageAttributes,
            _Inout_opt_ PALPC_MESSAGE_ATTRIBUTES InMessageAttributes,
            _In_opt_ PLARGE_INTEGER Timeout
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwAlpcCreatePort(
            _Out_ PHANDLE PortHandle,
            _In_opt_ POBJECT_ATTRIBUTES ObjectAttributes,
            _In_opt_ PALPC_PORT_ATTRIBUTES PortAttributes
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwAlpcCreatePortSection(
            _In_ HANDLE PortHandle,
            _In_ ULONG Flags,
            _In_opt_ HANDLE SectionHandle,
            _In_ SIZE_T SectionSize,
            _Out_ PALPC_HANDLE AlpcSectionHandle,
            _Out_ PSIZE_T ActualSectionSize
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwAlpcCreateResourceReserve(
            _In_ HANDLE PortHandle,
            _Reserved_ ULONG Flags,
            _In_ SIZE_T MessageSize,
            _Out_ PALPC_HANDLE ResourceId
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwAlpcCreateSectionView(
            _In_ HANDLE PortHandle,
            _Reserved_ ULONG Flags,
            _Inout_ PALPC_DATA_VIEW_ATTR ViewAttributes
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwAlpcCreateSecurityContext(
            _In_ HANDLE PortHandle,
            _Reserved_ ULONG Flags,
            _Inout_ PALPC_SECURITY_ATTR SecurityAttribute
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwAlpcDeletePortSection(
            _In_ HANDLE PortHandle,
            _Reserved_ ULONG Flags,
            _In_ ALPC_HANDLE SectionHandle
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwAlpcDeleteResourceReserve(
            _In_ HANDLE PortHandle,
            _Reserved_ ULONG Flags,
            _In_ ALPC_HANDLE ResourceId
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwAlpcDeleteSectionView(
            _In_ HANDLE PortHandle,
            _Reserved_ ULONG Flags,
            _In_ PVOID ViewBase
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwAlpcDeleteSecurityContext(
            _In_ HANDLE PortHandle,
            _Reserved_ ULONG Flags,
            _In_ ALPC_HANDLE ContextHandle
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwAlpcDisconnectPort(
            _In_ HANDLE PortHandle,
            _In_ ULONG Flags
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwAlpcImpersonateClientContainerOfPort(
            _In_ HANDLE PortHandle,
            _In_ PPORT_MESSAGE Message,
            _Reserved_ ULONG Flags
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwAlpcImpersonateClientOfPort(
            _In_ HANDLE PortHandle,
            _In_ PPORT_MESSAGE Message,
            _In_ PVOID Flags
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwAlpcOpenSenderProcess(
            _Out_ PHANDLE ProcessHandle,
            _In_ HANDLE PortHandle,
            _In_ PPORT_MESSAGE PortMessage,
            _Reserved_ ULONG Flags,
            _In_ ACCESS_MASK DesiredAccess,
            _In_ POBJECT_ATTRIBUTES ObjectAttributes
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwAlpcOpenSenderThread(
            _Out_ PHANDLE ThreadHandle,
            _In_ HANDLE PortHandle,
            _In_ PPORT_MESSAGE PortMessage,
            _Reserved_ ULONG Flags,
            _In_ ACCESS_MASK DesiredAccess,
            _In_ POBJECT_ATTRIBUTES ObjectAttributes
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwAlpcQueryInformation(
            _In_opt_ HANDLE PortHandle,
            _In_ ALPC_PORT_INFORMATION_CLASS PortInformationClass,
            _Inout_updates_bytes_to_(Length, *ReturnLength) PVOID PortInformation,
            _In_ ULONG Length,
            _Out_opt_ PULONG ReturnLength
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwAlpcQueryInformationMessage(
            _In_ HANDLE PortHandle,
            _In_ PPORT_MESSAGE PortMessage,
            _In_ ALPC_MESSAGE_INFORMATION_CLASS MessageInformationClass,
            _Out_writes_bytes_to_opt_(Length, *ReturnLength) PVOID MessageInformation,
            _In_ ULONG Length,
            _Out_opt_ PULONG ReturnLength
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwAlpcRevokeSecurityContext(
            _In_ HANDLE PortHandle,
            _Reserved_ ULONG Flags,
            _In_ ALPC_HANDLE ContextHandle
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwAlpcSendWaitReceivePort(
            _In_ HANDLE PortHandle,
            _In_ ULONG Flags,
            _In_reads_bytes_opt_(SendMessage->u1.s1.TotalLength) PPORT_MESSAGE SendMessage,
            _Inout_opt_ PALPC_MESSAGE_ATTRIBUTES SendMessageAttributes,
            _Out_writes_bytes_to_opt_(*BufferLength, *BufferLength) PPORT_MESSAGE ReceiveMessage,
            _Inout_opt_ PSIZE_T BufferLength,
            _Inout_opt_ PALPC_MESSAGE_ATTRIBUTES ReceiveMessageAttributes,
            _In_opt_ PLARGE_INTEGER Timeout
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwAlpcSetInformation(
            _In_ HANDLE PortHandle,
            _In_ ALPC_PORT_INFORMATION_CLASS PortInformationClass,
            _In_reads_bytes_opt_(Length) PVOID PortInformation,
            _In_ ULONG Length
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwAreMappedFilesTheSame(
            _In_ PVOID File1MappedAsAnImage,
            _In_ PVOID File2MappedAsFile
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwAssignProcessToJobObject(
            _In_ HANDLE JobHandle,
            _In_ HANDLE ProcessHandle
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwAssociateWaitCompletionPacket(
            _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 AlreadySignaled
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwCallbackReturn(
            _In_reads_bytes_opt_(OutputLength) PVOID OutputBuffer,
            _In_ ULONG OutputLength,
            _In_ NTSTATUS Status
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwCallEnclave(
            _In_ PENCLAVE_ROUTINE Routine,
            _In_ PVOID Reserved,              // reserved for dispatch (RtlEnclaveCallDispatch)
            _In_ ULONG Flags,                 // ENCLAVE_CALL_FLAG_*
            _Inout_ PVOID* RoutineParamReturn // input routine parameter, output routine return value
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwCancelIoFile(
            _In_ HANDLE FileHandle,
            _Out_ PIO_STATUS_BLOCK IoStatusBlock
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwCancelIoFileEx(
            _In_ HANDLE FileHandle,
            _In_opt_ PIO_STATUS_BLOCK IoRequestToCancel,
            _Out_ PIO_STATUS_BLOCK IoStatusBlock
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwCancelSynchronousIoFile(
            _In_ HANDLE ThreadHandle,
            _In_opt_ PIO_STATUS_BLOCK IoRequestToCancel,
            _Out_ PIO_STATUS_BLOCK IoStatusBlock
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwCancelTimer(
            _In_ HANDLE TimerHandle,
            _Out_opt_ PBOOLEAN CurrentState
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwCancelTimer2(
            _In_ HANDLE TimerHandle,
            _In_ PT2_CANCEL_PARAMETERS Parameters
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwCancelWaitCompletionPacket(
            _In_ HANDLE WaitCompletionPacketHandle,
            _In_ BOOLEAN RemoveSignaledPacket
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwChangeProcessState(
            _In_ HANDLE ProcessStateChangeHandle,
            _In_ HANDLE ProcessHandle,
            _In_ PROCESS_STATE_CHANGE_TYPE StateChangeType,
            _In_opt_ PVOID ExtendedInformation,
            _In_opt_ SIZE_T ExtendedInformationLength,
            _In_opt_ ULONG64 Reserved
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwChangeThreadState(
            _In_ HANDLE ThreadStateChangeHandle,
            _In_ HANDLE ThreadHandle,
            _In_ THREAD_STATE_CHANGE_TYPE StateChangeType,
            _In_opt_ PVOID ExtendedInformation,
            _In_opt_ SIZE_T ExtendedInformationLength,
            _In_opt_ ULONG64 Reserved
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwClearEvent(
            _In_ HANDLE EventHandle
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwClose(
            _In_ _Post_ptr_invalid_ HANDLE Handle
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwCloseObjectAuditAlarm(
            _In_ PUNICODE_STRING SubsystemName,
            _In_opt_ PVOID HandleId,
            _In_ BOOLEAN GenerateOnClose
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwCommitComplete(
            _In_ HANDLE EnlistmentHandle,
            _In_opt_ PLARGE_INTEGER TmVirtualClock
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwCommitEnlistment(
            _In_ HANDLE EnlistmentHandle,
            _In_opt_ PLARGE_INTEGER TmVirtualClock
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwCommitTransaction(
            _In_ HANDLE TransactionHandle,
            _In_ BOOLEAN Wait
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwCompactKeys(
            _In_ ULONG Count,
            _In_reads_(Count) HANDLE KeyArray[]
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwCompareObjects(
            _In_ HANDLE FirstObjectHandle,
            _In_ HANDLE SecondObjectHandle
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwCompareSigningLevels(
            _In_ SE_SIGNING_LEVEL FirstSigningLevel,
            _In_ SE_SIGNING_LEVEL SecondSigningLevel
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwCompareTokens(
            _In_ HANDLE FirstTokenHandle,
            _In_ HANDLE SecondTokenHandle,
            _Out_ PBOOLEAN Equal
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwCompleteConnectPort(
            _In_ HANDLE PortHandle
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwCompressKey(
            _In_ HANDLE KeyHandle
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwConnectPort(
            _Out_ PHANDLE PortHandle,
            _In_ PUNICODE_STRING PortName,
            _In_ PSECURITY_QUALITY_OF_SERVICE SecurityQos,
            _Inout_opt_ PPORT_VIEW ClientView,
            _Inout_opt_ PREMOTE_PORT_VIEW ServerView,
            _Out_opt_ PULONG MaxMessageLength,
            _Inout_updates_bytes_to_opt_(*ConnectionInformationLength, *ConnectionInformationLength) PVOID ConnectionInformation,
            _Inout_opt_ PULONG ConnectionInformationLength
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwContinue(
            _In_ PCONTEXT ContextRecord,
            _In_ BOOLEAN TestAlert
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwContinueEx(
            _In_ PCONTEXT ContextRecord,
            _In_ PVOID ContinueArgument // PKCONTINUE_ARGUMENT and BOOLEAN are valid
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwConvertBetweenAuxiliaryCounterAndPerformanceCounter(
            _In_opt_ PLARGE_INTEGER AuxiliaryCounterValue,
            _Inout_ PLARGE_INTEGER PerformanceCounterValue,
            _Out_ PLARGE_INTEGER PerformanceOrAuxiliaryCounterValue,
            _Out_ PLARGE_INTEGER ConversionError
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwCreateDebugObject(
            _Out_ PHANDLE DebugObjectHandle,
            _In_ ACCESS_MASK DesiredAccess,
            _In_opt_ POBJECT_ATTRIBUTES ObjectAttributes,
            _In_ ULONG Flags
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwCreateDirectoryObject(
            _Out_ PHANDLE DirectoryHandle,
            _In_ ACCESS_MASK DesiredAccess,
            _In_ POBJECT_ATTRIBUTES ObjectAttributes
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwCreateDirectoryObjectEx(
            _Out_ PHANDLE DirectoryHandle,
            _In_ ACCESS_MASK DesiredAccess,
            _In_ POBJECT_ATTRIBUTES ObjectAttributes,
            _In_ HANDLE ShadowDirectoryHandle,
            _In_ ULONG Flags
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwCreateEnclave(
            _In_ HANDLE ProcessHandle,
            _Inout_ PVOID* BaseAddress,
            _In_ ULONG_PTR ZeroBits,
            _In_ SIZE_T Size,
            _In_ SIZE_T InitialCommitment,
            _In_ ULONG EnclaveType,
            _In_reads_bytes_(EnclaveInformationLength) PVOID EnclaveInformation,
            _In_ ULONG EnclaveInformationLength,
            _Out_opt_ PULONG EnclaveError
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwCreateEnlistment(
            _Out_ PHANDLE EnlistmentHandle,
            _In_ ACCESS_MASK DesiredAccess,
            _In_ HANDLE ResourceManagerHandle,
            _In_ HANDLE TransactionHandle,
            _In_opt_ POBJECT_ATTRIBUTES ObjectAttributes,
            _In_opt_ ULONG CreateOptions,
            _In_ NOTIFICATION_MASK NotificationMask,
            _In_opt_ PVOID EnlistmentKey
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwCreateEvent(
            _Out_ PHANDLE EventHandle,
            _In_ ACCESS_MASK DesiredAccess,
            _In_opt_ POBJECT_ATTRIBUTES ObjectAttributes,
            _In_ EVENT_TYPE EventType,
            _In_ BOOLEAN InitialState
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwCreateEventPair(
            _Out_ PHANDLE EventPairHandle,
            _In_ ACCESS_MASK DesiredAccess,
            _In_opt_ POBJECT_ATTRIBUTES ObjectAttributes
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwCreateFile(
            _Out_ PHANDLE FileHandle,
            _In_ ACCESS_MASK DesiredAccess,
            _In_ POBJECT_ATTRIBUTES ObjectAttributes,
            _Out_ PIO_STATUS_BLOCK IoStatusBlock,
            _In_opt_ PLARGE_INTEGER AllocationSize,
            _In_ ULONG FileAttributes,
            _In_ ULONG ShareAccess,
            _In_ ULONG CreateDisposition,
            _In_ ULONG CreateOptions,
            _In_reads_bytes_opt_(EaLength) PVOID EaBuffer,
            _In_ ULONG EaLength
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwCreateIoCompletion(
            _Out_ PHANDLE IoCompletionHandle,
            _In_ ACCESS_MASK DesiredAccess,
            _In_opt_ POBJECT_ATTRIBUTES ObjectAttributes,
            _In_opt_ ULONG Count
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwCreateIRTimer(
            _Out_ PHANDLE TimerHandle,
            _In_ ACCESS_MASK DesiredAccess
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwCreateJobObject(
            _Out_ PHANDLE JobHandle,
            _In_ ACCESS_MASK DesiredAccess,
            _In_opt_ POBJECT_ATTRIBUTES ObjectAttributes
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwCreateJobSet(
            _In_ ULONG NumJob,
            _In_reads_(NumJob) PJOB_SET_ARRAY UserJobSet,
            _In_ ULONG Flags
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwCreateKey(
            _Out_ PHANDLE KeyHandle,
            _In_ ACCESS_MASK DesiredAccess,
            _In_ POBJECT_ATTRIBUTES ObjectAttributes,
            _Reserved_ ULONG TitleIndex,
            _In_opt_ PUNICODE_STRING Class,
            _In_ ULONG CreateOptions,
            _Out_opt_ PULONG Disposition
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwCreateKeyedEvent(
            _Out_ PHANDLE KeyedEventHandle,
            _In_ ACCESS_MASK DesiredAccess,
            _In_opt_ POBJECT_ATTRIBUTES ObjectAttributes,
            _Reserved_ ULONG Flags
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwCreateKeyTransacted(
            _Out_ PHANDLE KeyHandle,
            _In_ ACCESS_MASK DesiredAccess,
            _In_ POBJECT_ATTRIBUTES ObjectAttributes,
            _Reserved_ ULONG TitleIndex,
            _In_opt_ PUNICODE_STRING Class,
            _In_ ULONG CreateOptions,
            _In_ HANDLE TransactionHandle,
            _Out_opt_ PULONG Disposition
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwCreateLowBoxToken(
            _Out_ PHANDLE TokenHandle,
            _In_ HANDLE ExistingTokenHandle,
            _In_ ACCESS_MASK DesiredAccess,
            _In_opt_ POBJECT_ATTRIBUTES ObjectAttributes,
            _In_ PSID PackageSid,
            _In_ ULONG CapabilityCount,
            _In_reads_opt_(CapabilityCount) PSID_AND_ATTRIBUTES Capabilities,
            _In_ ULONG HandleCount,
            _In_reads_opt_(HandleCount) HANDLE* Handles
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwCreateMailslotFile(
            _Out_ PHANDLE FileHandle,
            _In_ ULONG DesiredAccess,
            _In_ POBJECT_ATTRIBUTES ObjectAttributes,
            _Out_ PIO_STATUS_BLOCK IoStatusBlock,
            _In_ ULONG CreateOptions,
            _In_ ULONG MailslotQuota,
            _In_ ULONG MaximumMessageSize,
            _In_ PLARGE_INTEGER ReadTimeout
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwCreateMutant(
            _Out_ PHANDLE MutantHandle,
            _In_ ACCESS_MASK DesiredAccess,
            _In_opt_ POBJECT_ATTRIBUTES ObjectAttributes,
            _In_ BOOLEAN InitialOwner
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwCreateNamedPipeFile(
            _Out_ PHANDLE FileHandle,
            _In_ ULONG DesiredAccess,
            _In_ POBJECT_ATTRIBUTES ObjectAttributes,
            _Out_ PIO_STATUS_BLOCK IoStatusBlock,
            _In_ ULONG ShareAccess,
            _In_ ULONG CreateDisposition,
            _In_ ULONG CreateOptions,
            _In_ ULONG NamedPipeType,
            _In_ ULONG ReadMode,
            _In_ ULONG CompletionMode,
            _In_ ULONG MaximumInstances,
            _In_ ULONG InboundQuota,
            _In_ ULONG OutboundQuota,
            _In_ PLARGE_INTEGER DefaultTimeout
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwCreatePagingFile(
            _In_ PUNICODE_STRING PageFileName,
            _In_ PLARGE_INTEGER MinimumSize,
            _In_ PLARGE_INTEGER MaximumSize,
            _In_ ULONG Priority
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwCreatePartition(
            _In_opt_ HANDLE ParentPartitionHandle,
            _Out_ PHANDLE PartitionHandle,
            _In_ ACCESS_MASK DesiredAccess,
            _In_opt_ POBJECT_ATTRIBUTES ObjectAttributes,
            _In_ ULONG PreferredNode
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwCreatePort(
            _Out_ PHANDLE PortHandle,
            _In_opt_ POBJECT_ATTRIBUTES ObjectAttributes,
            _In_ ULONG MaxConnectionInfoLength,
            _In_ ULONG MaxMessageLength,
            _In_opt_ ULONG MaxPoolUsage
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwCreatePrivateNamespace(
            _Out_ PHANDLE NamespaceHandle,
            _In_ ACCESS_MASK DesiredAccess,
            _In_opt_ POBJECT_ATTRIBUTES ObjectAttributes,
            _In_ POBJECT_BOUNDARY_DESCRIPTOR BoundaryDescriptor
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwCreateProcess(
            _Out_ PHANDLE ProcessHandle,
            _In_ ACCESS_MASK DesiredAccess,
            _In_opt_ POBJECT_ATTRIBUTES ObjectAttributes,
            _In_ HANDLE ParentProcess,
            _In_ BOOLEAN InheritObjectTable,
            _In_opt_ HANDLE SectionHandle,
            _In_opt_ HANDLE DebugPort,
            _In_opt_ HANDLE TokenHandle
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwCreateProcessEx(
            _Out_ PHANDLE ProcessHandle,
            _In_ ACCESS_MASK DesiredAccess,
            _In_opt_ POBJECT_ATTRIBUTES ObjectAttributes,
            _In_ HANDLE ParentProcess,
            _In_ ULONG Flags, // PROCESS_CREATE_FLAGS_*
            _In_opt_ HANDLE SectionHandle,
            _In_opt_ HANDLE DebugPort,
            _In_opt_ HANDLE TokenHandle,
            _Reserved_ ULONG Reserved // JobMemberLevel
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwCreateProcessStateChange(
            _Out_ PHANDLE ProcessStateChangeHandle,
            _In_ ACCESS_MASK DesiredAccess,
            _In_opt_ POBJECT_ATTRIBUTES ObjectAttributes,
            _In_ HANDLE ProcessHandle,
            _In_opt_ ULONG64 Reserved
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwCreateProfile(
            _Out_ PHANDLE ProfileHandle,
            _In_opt_ HANDLE Process,
            _In_ PVOID ProfileBase,
            _In_ SIZE_T ProfileSize,
            _In_ ULONG BucketSize,
            _In_reads_bytes_(BufferSize) PULONG Buffer,
            _In_ ULONG BufferSize,
            _In_ KPROFILE_SOURCE ProfileSource,
            _In_ KAFFINITY Affinity
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwCreateProfileEx(
            _Out_ PHANDLE ProfileHandle,
            _In_opt_ HANDLE Process,
            _In_ PVOID ProfileBase,
            _In_ SIZE_T ProfileSize,
            _In_ ULONG BucketSize,
            _In_reads_bytes_(BufferSize) PULONG Buffer,
            _In_ ULONG BufferSize,
            _In_ KPROFILE_SOURCE ProfileSource,
            _In_ USHORT GroupCount,
            _In_reads_(GroupCount) PGROUP_AFFINITY GroupAffinity
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwCreateResourceManager(
            _Out_ PHANDLE ResourceManagerHandle,
            _In_ ACCESS_MASK DesiredAccess,
            _In_ HANDLE TmHandle,
            _In_ LPGUID RmGuid,
            _In_opt_ POBJECT_ATTRIBUTES ObjectAttributes,
            _In_opt_ ULONG CreateOptions,
            _In_opt_ PUNICODE_STRING Description
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwCreateSection(
            _Out_ PHANDLE SectionHandle,
            _In_ ACCESS_MASK DesiredAccess,
            _In_opt_ POBJECT_ATTRIBUTES ObjectAttributes,
            _In_opt_ PLARGE_INTEGER MaximumSize,
            _In_ ULONG SectionPageProtection,
            _In_ ULONG AllocationAttributes,
            _In_opt_ HANDLE FileHandle
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwCreateSectionEx(
            _Out_ PHANDLE SectionHandle,
            _In_ ACCESS_MASK DesiredAccess,
            _In_opt_ POBJECT_ATTRIBUTES ObjectAttributes,
            _In_opt_ PLARGE_INTEGER MaximumSize,
            _In_ ULONG SectionPageProtection,
            _In_ ULONG AllocationAttributes,
            _In_opt_ HANDLE FileHandle,
            _Inout_updates_opt_(ExtendedParameterCount) PMEM_EXTENDED_PARAMETER ExtendedParameters,
            _In_ ULONG ExtendedParameterCount
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwCreateSemaphore(
            _Out_ PHANDLE SemaphoreHandle,
            _In_ ACCESS_MASK DesiredAccess,
            _In_opt_ POBJECT_ATTRIBUTES ObjectAttributes,
            _In_ LONG InitialCount,
            _In_ LONG MaximumCount
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwCreateSymbolicLinkObject(
            _Out_ PHANDLE LinkHandle,
            _In_ ACCESS_MASK DesiredAccess,
            _In_ POBJECT_ATTRIBUTES ObjectAttributes,
            _In_ PUNICODE_STRING LinkTarget
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwCreateThread(
            _Out_ PHANDLE ThreadHandle,
            _In_ ACCESS_MASK DesiredAccess,
            _In_opt_ POBJECT_ATTRIBUTES ObjectAttributes,
            _In_ HANDLE ProcessHandle,
            _Out_ PCLIENT_ID ClientId,
            _In_ PCONTEXT ThreadContext,
            _In_ PINITIAL_TEB InitialTeb,
            _In_ BOOLEAN CreateSuspended
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwCreateThreadEx(
            _Out_ PHANDLE ThreadHandle,
            _In_ ACCESS_MASK DesiredAccess,
            _In_opt_ POBJECT_ATTRIBUTES ObjectAttributes,
            _In_ HANDLE ProcessHandle,
            _In_ PUSER_THREAD_START_ROUTINE StartRoutine,
            _In_opt_ PVOID Argument,
            _In_ ULONG CreateFlags, // THREAD_CREATE_FLAGS_*
            _In_ SIZE_T ZeroBits,
            _In_ SIZE_T StackSize,
            _In_ SIZE_T MaximumStackSize,
            _In_opt_ PPS_ATTRIBUTE_LIST AttributeList
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwCreateThreadStateChange(
            _Out_ PHANDLE ThreadStateChangeHandle,
            _In_ ACCESS_MASK DesiredAccess,
            _In_opt_ POBJECT_ATTRIBUTES ObjectAttributes,
            _In_ HANDLE ThreadHandle,
            _In_opt_ ULONG64 Reserved
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwCreateTimer(
            _Out_ PHANDLE TimerHandle,
            _In_ ACCESS_MASK DesiredAccess,
            _In_opt_ POBJECT_ATTRIBUTES ObjectAttributes,
            _In_ TIMER_TYPE TimerType
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwCreateTimer2(
            _Out_ PHANDLE TimerHandle,
            _In_opt_ PVOID Reserved1,
            _In_opt_ POBJECT_ATTRIBUTES ObjectAttributes,
            _In_ ULONG Attributes,
            _In_ ACCESS_MASK DesiredAccess
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwCreateToken(
            _Out_ PHANDLE TokenHandle,
            _In_ ACCESS_MASK DesiredAccess,
            _In_opt_ POBJECT_ATTRIBUTES ObjectAttributes,
            _In_ TOKEN_TYPE Type,
            _In_ PLUID AuthenticationId,
            _In_ PLARGE_INTEGER ExpirationTime,
            _In_ PTOKEN_USER User,
            _In_ PTOKEN_GROUPS Groups,
            _In_ PTOKEN_PRIVILEGES Privileges,
            _In_opt_ PTOKEN_OWNER Owner,
            _In_ PTOKEN_PRIMARY_GROUP PrimaryGroup,
            _In_opt_ PTOKEN_DEFAULT_DACL DefaultDacl,
            _In_ PTOKEN_SOURCE Source
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwCreateTokenEx(
            _Out_ PHANDLE TokenHandle,
            _In_ ACCESS_MASK DesiredAccess,
            _In_opt_ POBJECT_ATTRIBUTES ObjectAttributes,
            _In_ TOKEN_TYPE Type,
            _In_ PLUID AuthenticationId,
            _In_ PLARGE_INTEGER ExpirationTime,
            _In_ PTOKEN_USER User,
            _In_ PTOKEN_GROUPS Groups,
            _In_ PTOKEN_PRIVILEGES Privileges,
            _In_opt_ PTOKEN_SECURITY_ATTRIBUTES_INFORMATION UserAttributes,
            _In_opt_ PTOKEN_SECURITY_ATTRIBUTES_INFORMATION DeviceAttributes,
            _In_opt_ PTOKEN_GROUPS DeviceGroups,
            _In_opt_ PTOKEN_MANDATORY_POLICY MandatoryPolicy,
            _In_opt_ PTOKEN_OWNER Owner,
            _In_ PTOKEN_PRIMARY_GROUP PrimaryGroup,
            _In_opt_ PTOKEN_DEFAULT_DACL DefaultDacl,
            _In_ PTOKEN_SOURCE Source
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwCreateTransaction(
            _Out_ PHANDLE TransactionHandle,
            _In_ ACCESS_MASK DesiredAccess,
            _In_opt_ POBJECT_ATTRIBUTES ObjectAttributes,
            _In_opt_ LPGUID Uow,
            _In_opt_ HANDLE TmHandle,
            _In_opt_ ULONG CreateOptions,
            _In_opt_ ULONG IsolationLevel,
            _In_opt_ ULONG IsolationFlags,
            _In_opt_ PLARGE_INTEGER Timeout,
            _In_opt_ PUNICODE_STRING Description
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwCreateTransactionManager(
            _Out_ PHANDLE TmHandle,
            _In_ ACCESS_MASK DesiredAccess,
            _In_opt_ POBJECT_ATTRIBUTES ObjectAttributes,
            _In_opt_ PUNICODE_STRING LogFileName,
            _In_opt_ ULONG CreateOptions,
            _In_opt_ ULONG CommitStrength
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwCreateUserProcess(
            _Out_ PHANDLE ProcessHandle,
            _Out_ PHANDLE ThreadHandle,
            _In_ ACCESS_MASK ProcessDesiredAccess,
            _In_ ACCESS_MASK ThreadDesiredAccess,
            _In_opt_ POBJECT_ATTRIBUTES ProcessObjectAttributes,
            _In_opt_ POBJECT_ATTRIBUTES ThreadObjectAttributes,
            _In_ ULONG ProcessFlags, // PROCESS_CREATE_FLAGS_*
            _In_ ULONG ThreadFlags, // THREAD_CREATE_FLAGS_*
            _In_opt_ PVOID ProcessParameters, // PRTL_USER_PROCESS_PARAMETERS
            _Inout_ PPS_CREATE_INFO CreateInfo,
            _In_opt_ PPS_ATTRIBUTE_LIST AttributeList
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwCreateWaitablePort(
            _Out_ PHANDLE PortHandle,
            _In_opt_ POBJECT_ATTRIBUTES ObjectAttributes,
            _In_ ULONG MaxConnectionInfoLength,
            _In_ ULONG MaxMessageLength,
            _In_opt_ ULONG MaxPoolUsage
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwCreateWaitCompletionPacket(
            _Out_ PHANDLE WaitCompletionPacketHandle,
            _In_ ACCESS_MASK DesiredAccess,
            _In_opt_ POBJECT_ATTRIBUTES ObjectAttributes
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwCreateWnfStateName(
            _Out_ PWNF_STATE_NAME StateName,
            _In_ WNF_STATE_NAME_LIFETIME NameLifetime,
            _In_ WNF_DATA_SCOPE DataScope,
            _In_ BOOLEAN PersistData,
            _In_opt_ PCWNF_TYPE_ID TypeId,
            _In_ ULONG MaximumStateSize,
            _In_ PSECURITY_DESCRIPTOR SecurityDescriptor
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwCreateWorkerFactory(
            _Out_ PHANDLE WorkerFactoryHandleReturn,
            _In_ ACCESS_MASK DesiredAccess,
            _In_opt_ POBJECT_ATTRIBUTES ObjectAttributes,
            _In_ HANDLE CompletionPortHandle,
            _In_ HANDLE WorkerProcessHandle,
            _In_ PVOID StartRoutine,
            _In_opt_ PVOID StartParameter,
            _In_opt_ ULONG MaxThreadCount,
            _In_opt_ SIZE_T StackReserve,
            _In_opt_ SIZE_T StackCommit
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwDebugActiveProcess(
            _In_ HANDLE ProcessHandle,
            _In_ HANDLE DebugObjectHandle
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwDebugContinue(
            _In_ HANDLE DebugObjectHandle,
            _In_ PCLIENT_ID ClientId,
            _In_ NTSTATUS ContinueStatus
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwDelayExecution(
            _In_ BOOLEAN Alertable,
            _In_ PLARGE_INTEGER DelayInterval
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwDeleteAtom(
            _In_ RTL_ATOM Atom
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwDeleteBootEntry(
            _In_ ULONG Id
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwDeleteDriverEntry(
            _In_ ULONG Id
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwDeleteFile(
            _In_ POBJECT_ATTRIBUTES ObjectAttributes
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwDeleteKey(
            _In_ HANDLE KeyHandle
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwDeleteObjectAuditAlarm(
            _In_ PUNICODE_STRING SubsystemName,
            _In_opt_ PVOID HandleId,
            _In_ BOOLEAN GenerateOnClose
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwDeletePrivateNamespace(
            _In_ HANDLE NamespaceHandle
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwDeleteValueKey(
            _In_ HANDLE KeyHandle,
            _In_ PUNICODE_STRING ValueName
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwDeleteWnfStateData(
            _In_ PCWNF_STATE_NAME StateName,
            _In_opt_ const VOID* ExplicitScope
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwDeleteWnfStateName(
            _In_ PCWNF_STATE_NAME StateName
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwDeviceIoControlFile(
            _In_ HANDLE FileHandle,
            _In_opt_ HANDLE Event,
            _In_opt_ PIO_APC_ROUTINE ApcRoutine,
            _In_opt_ PVOID ApcContext,
            _Out_ PIO_STATUS_BLOCK IoStatusBlock,
            _In_ ULONG IoControlCode,
            _In_reads_bytes_opt_(InputBufferLength) PVOID InputBuffer,
            _In_ ULONG InputBufferLength,
            _Out_writes_bytes_opt_(OutputBufferLength) PVOID OutputBuffer,
            _In_ ULONG OutputBufferLength
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwDisableLastKnownGood(
            VOID
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwDisplayString(
            _In_ PUNICODE_STRING String
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwDrawText(
            _In_ PUNICODE_STRING Text
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwDuplicateObject(
            _In_ HANDLE SourceProcessHandle,
            _In_ HANDLE SourceHandle,
            _In_opt_ HANDLE TargetProcessHandle,
            _Out_opt_ PHANDLE TargetHandle,
            _In_ ACCESS_MASK DesiredAccess,
            _In_ ULONG HandleAttributes,
            _In_ ULONG Options
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwDuplicateToken(
            _In_ HANDLE ExistingTokenHandle,
            _In_ ACCESS_MASK DesiredAccess,
            _In_opt_ POBJECT_ATTRIBUTES ObjectAttributes,
            _In_ BOOLEAN EffectiveOnly,
            _In_ TOKEN_TYPE Type,
            _Out_ PHANDLE NewTokenHandle
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwEnableLastKnownGood(
            VOID
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwEnumerateBootEntries(
            _Out_writes_bytes_opt_(*BufferLength) PVOID Buffer,
            _Inout_ PULONG BufferLength
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwEnumerateDriverEntries(
            _Out_writes_bytes_opt_(*BufferLength) PVOID Buffer,
            _Inout_ PULONG BufferLength
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwEnumerateKey(
            _In_ HANDLE KeyHandle,
            _In_ ULONG Index,
            _In_ KEY_INFORMATION_CLASS KeyInformationClass,
            _Out_writes_bytes_opt_(Length) PVOID KeyInformation,
            _In_ ULONG Length,
            _Out_ PULONG ResultLength
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwEnumerateSystemEnvironmentValuesEx(
            _In_ ULONG InformationClass, // SYSTEM_ENVIRONMENT_INFORMATION_CLASS
            _Out_ PVOID Buffer,
            _Inout_ PULONG BufferLength
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwEnumerateTransactionObject(
            _In_opt_ HANDLE RootObjectHandle,
            _In_ KTMOBJECT_TYPE QueryType,
            _Inout_updates_bytes_(ObjectCursorLength) PKTMOBJECT_CURSOR ObjectCursor,
            _In_ ULONG ObjectCursorLength,
            _Out_ PULONG ReturnLength
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwEnumerateValueKey(
            _In_ HANDLE KeyHandle,
            _In_ ULONG Index,
            _In_ KEY_VALUE_INFORMATION_CLASS KeyValueInformationClass,
            _Out_writes_bytes_opt_(Length) PVOID KeyValueInformation,
            _In_ ULONG Length,
            _Out_ PULONG ResultLength
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwExtendSection(
            _In_ HANDLE SectionHandle,
            _Inout_ PLARGE_INTEGER NewSectionSize
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwFilterBootOption(
            _In_ FILTER_BOOT_OPTION_OPERATION FilterOperation,
            _In_ ULONG ObjectType,
            _In_ ULONG ElementType,
            _In_reads_bytes_opt_(DataSize) PVOID Data,
            _In_ ULONG DataSize
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwFilterToken(
            _In_ HANDLE ExistingTokenHandle,
            _In_ ULONG Flags,
            _In_opt_ PTOKEN_GROUPS SidsToDisable,
            _In_opt_ PTOKEN_PRIVILEGES PrivilegesToDelete,
            _In_opt_ PTOKEN_GROUPS RestrictedSids,
            _Out_ PHANDLE NewTokenHandle
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwFilterTokenEx(
            _In_ HANDLE ExistingTokenHandle,
            _In_ ULONG Flags,
            _In_opt_ PTOKEN_GROUPS SidsToDisable,
            _In_opt_ PTOKEN_PRIVILEGES PrivilegesToDelete,
            _In_opt_ PTOKEN_GROUPS RestrictedSids,
            _In_ ULONG DisableUserClaimsCount,
            _In_opt_ PUNICODE_STRING UserClaimsToDisable,
            _In_ ULONG DisableDeviceClaimsCount,
            _In_opt_ PUNICODE_STRING DeviceClaimsToDisable,
            _In_opt_ PTOKEN_GROUPS DeviceGroupsToDisable,
            _In_opt_ PTOKEN_SECURITY_ATTRIBUTES_INFORMATION RestrictedUserAttributes,
            _In_opt_ PTOKEN_SECURITY_ATTRIBUTES_INFORMATION RestrictedDeviceAttributes,
            _In_opt_ PTOKEN_GROUPS RestrictedDeviceGroups,
            _Out_ PHANDLE NewTokenHandle
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwFindAtom(
            _In_reads_bytes_opt_(Length) PWSTR AtomName,
            _In_ ULONG Length,
            _Out_opt_ PRTL_ATOM Atom
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwFlushBuffersFile(
            _In_ HANDLE FileHandle,
            _Out_ PIO_STATUS_BLOCK IoStatusBlock
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwFlushBuffersFileEx(
            _In_ HANDLE FileHandle,
            _In_ ULONG Flags,
            _In_reads_bytes_(ParametersSize) PVOID Parameters,
            _In_ ULONG ParametersSize,
            _Out_ PIO_STATUS_BLOCK IoStatusBlock
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwFlushInstallUILanguage(
            _In_ LANGID InstallUILanguage,
            _In_ ULONG SetComittedFlag
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwFlushInstructionCache(
            _In_ HANDLE ProcessHandle,
            _In_opt_ PVOID BaseAddress,
            _In_ SIZE_T Length
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwFlushKey(
            _In_ HANDLE KeyHandle
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwFlushProcessWriteBuffers(
            VOID
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwFlushVirtualMemory(
            _In_ HANDLE ProcessHandle,
            _Inout_ PVOID* BaseAddress,
            _Inout_ PSIZE_T RegionSize,
            _Out_ PIO_STATUS_BLOCK IoStatus
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwFlushWriteBuffer(
            VOID
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwFreeUserPhysicalPages(
            _In_ HANDLE ProcessHandle,
            _Inout_ PULONG_PTR NumberOfPages,
            _In_reads_(*NumberOfPages) PULONG_PTR UserPfnArray
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwFreeVirtualMemory(
            _In_ HANDLE ProcessHandle,
            _Inout_ PVOID* BaseAddress,
            _Inout_ PSIZE_T RegionSize,
            _In_ ULONG FreeType
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwFreezeRegistry(
            _In_ ULONG TimeOutInSeconds
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwFreezeTransactions(
            _In_ PLARGE_INTEGER FreezeTimeout,
            _In_ PLARGE_INTEGER ThawTimeout
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwFsControlFile(
            _In_ HANDLE FileHandle,
            _In_opt_ HANDLE Event,
            _In_opt_ PIO_APC_ROUTINE ApcRoutine,
            _In_opt_ PVOID ApcContext,
            _Out_ PIO_STATUS_BLOCK IoStatusBlock,
            _In_ ULONG FsControlCode,
            _In_reads_bytes_opt_(InputBufferLength) PVOID InputBuffer,
            _In_ ULONG InputBufferLength,
            _Out_writes_bytes_opt_(OutputBufferLength) PVOID OutputBuffer,
            _In_ ULONG OutputBufferLength
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwGetCachedSigningLevel(
            _In_ HANDLE File,
            _Out_ PULONG Flags,
            _Out_ PSE_SIGNING_LEVEL SigningLevel,
            _Out_writes_bytes_to_opt_(*ThumbprintSize, *ThumbprintSize) PUCHAR Thumbprint,
            _Inout_opt_ PULONG ThumbprintSize,
            _Out_opt_ PULONG ThumbprintAlgorithm
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwGetCompleteWnfStateSubscription(
            _In_opt_ PWNF_STATE_NAME OldDescriptorStateName,
            _In_opt_ ULONG64* OldSubscriptionId,
            _In_opt_ ULONG OldDescriptorEventMask,
            _In_opt_ ULONG OldDescriptorStatus,
            _Out_writes_bytes_(DescriptorSize) PWNF_DELIVERY_DESCRIPTOR NewDeliveryDescriptor,
            _In_ ULONG DescriptorSize
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwGetContextThread(
            _In_ HANDLE ThreadHandle,
            _Inout_ PCONTEXT ThreadContext
        );

    NTSYSCALLAPI
        ULONG
        NTAPI
        ZwGetCurrentProcessorNumber(
            VOID
        );

    NTSYSCALLAPI
        ULONG
        NTAPI
        ZwGetCurrentProcessorNumberEx(
            _Out_opt_ PPROCESSOR_NUMBER ProcessorNumber
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwGetDevicePowerState(
            _In_ HANDLE Device,
            _Out_ PDEVICE_POWER_STATE State
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwGetMUIRegistryInfo(
            _In_ ULONG Flags,
            _Inout_ PULONG DataSize,
            _Out_ PVOID Data
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwGetNextProcess(
            _In_opt_ HANDLE ProcessHandle,
            _In_ ACCESS_MASK DesiredAccess,
            _In_ ULONG HandleAttributes,
            _In_ ULONG Flags,
            _Out_ PHANDLE NewProcessHandle
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwGetNextThread(
            _In_ HANDLE ProcessHandle,
            _In_opt_ HANDLE ThreadHandle,
            _In_ ACCESS_MASK DesiredAccess,
            _In_ ULONG HandleAttributes,
            _In_ ULONG Flags,
            _Out_ PHANDLE NewThreadHandle
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwGetNlsSectionPtr(
            _In_ ULONG SectionType,
            _In_ ULONG SectionData,
            _In_ PVOID ContextData,
            _Out_ PVOID* SectionPointer,
            _Out_ PULONG SectionSize
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwGetNotificationResourceManager(
            _In_ HANDLE ResourceManagerHandle,
            _Out_ PTRANSACTION_NOTIFICATION TransactionNotification,
            _In_ ULONG NotificationLength,
            _In_opt_ PLARGE_INTEGER Timeout,
            _Out_opt_ PULONG ReturnLength,
            _In_ ULONG Asynchronous,
            _In_opt_ ULONG_PTR AsynchronousContext
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwGetPlugPlayEvent(
            _In_ HANDLE EventHandle,
            _In_opt_ PVOID Context,
            _Out_writes_bytes_(EventBufferSize) PPLUGPLAY_EVENT_BLOCK EventBlock,
            _In_ ULONG EventBufferSize
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwGetWriteWatch(
            _In_ HANDLE ProcessHandle,
            _In_ ULONG Flags,
            _In_ PVOID BaseAddress,
            _In_ SIZE_T RegionSize,
            _Out_writes_(*EntriesInUserAddressArray) PVOID* UserAddressArray,
            _Inout_ PULONG_PTR EntriesInUserAddressArray,
            _Out_ PULONG Granularity
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwImpersonateAnonymousToken(
            _In_ HANDLE ThreadHandle
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwImpersonateClientOfPort(
            _In_ HANDLE PortHandle,
            _In_ PPORT_MESSAGE Message
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwImpersonateThread(
            _In_ HANDLE ServerThreadHandle,
            _In_ HANDLE ClientThreadHandle,
            _In_ PSECURITY_QUALITY_OF_SERVICE SecurityQos
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwInitializeEnclave(
            _In_ HANDLE ProcessHandle,
            _In_ PVOID BaseAddress,
            _In_reads_bytes_(EnclaveInformationLength) PVOID EnclaveInformation,
            _In_ ULONG EnclaveInformationLength,
            _Out_opt_ PULONG EnclaveError
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwInitializeNlsFiles(
            _Out_ PVOID* BaseAddress,
            _Out_ PLCID DefaultLocaleId,
            _Out_ PLARGE_INTEGER DefaultCasingTableSize
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwInitializeRegistry(
            _In_ USHORT BootCondition
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwInitiatePowerAction(
            _In_ POWER_ACTION SystemAction,
            _In_ SYSTEM_POWER_STATE LightestSystemState,
            _In_ ULONG Flags, // POWER_ACTION_* flags
            _In_ BOOLEAN Asynchronous
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwIsProcessInJob(
            _In_ HANDLE ProcessHandle,
            _In_opt_ HANDLE JobHandle
        );

    NTSYSCALLAPI
        BOOLEAN
        NTAPI
        ZwIsSystemResumeAutomatic(
            VOID
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwIsUILanguageComitted(
            VOID
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwListenPort(
            _In_ HANDLE PortHandle,
            _Out_ PPORT_MESSAGE ConnectionRequest
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwLoadDriver(
            _In_ PUNICODE_STRING DriverServiceName
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwLoadEnclaveData(
            _In_ HANDLE ProcessHandle,
            _In_ PVOID BaseAddress,
            _In_reads_bytes_(BufferSize) PVOID Buffer,
            _In_ SIZE_T BufferSize,
            _In_ ULONG Protect,
            _In_reads_bytes_(PageInformationLength) PVOID PageInformation,
            _In_ ULONG PageInformationLength,
            _Out_opt_ PSIZE_T NumberOfBytesWritten,
            _Out_opt_ PULONG EnclaveError
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwLoadKey(
            _In_ POBJECT_ATTRIBUTES TargetKey,
            _In_ POBJECT_ATTRIBUTES SourceFile
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwLoadKey2(
            _In_ POBJECT_ATTRIBUTES TargetKey,
            _In_ POBJECT_ATTRIBUTES SourceFile,
            _In_ ULONG Flags
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwLoadKey3(
            _In_ POBJECT_ATTRIBUTES TargetKey,
            _In_ POBJECT_ATTRIBUTES SourceFile,
            _In_ ULONG Flags,
            _In_reads_(ExtendedParameterCount) PCM_EXTENDED_PARAMETER ExtendedParameters,
            _In_ ULONG ExtendedParameterCount,
            _In_opt_ ACCESS_MASK DesiredAccess,
            _Out_opt_ PHANDLE RootHandle,
            _Reserved_ PVOID Reserved
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwLoadKeyEx(
            _In_ POBJECT_ATTRIBUTES TargetKey,
            _In_ POBJECT_ATTRIBUTES SourceFile,
            _In_ ULONG Flags,
            _In_opt_ HANDLE TrustClassKey, // this and below were added on Win10
            _In_opt_ HANDLE Event,
            _In_opt_ ACCESS_MASK DesiredAccess,
            _Out_opt_ PHANDLE RootHandle,
            _Reserved_ PVOID Reserved // previously PIO_STATUS_BLOCK
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwLockFile(
            _In_ HANDLE FileHandle,
            _In_opt_ HANDLE Event,
            _In_opt_ PIO_APC_ROUTINE ApcRoutine,
            _In_opt_ PVOID ApcContext,
            _Out_ PIO_STATUS_BLOCK IoStatusBlock,
            _In_ PLARGE_INTEGER ByteOffset,
            _In_ PLARGE_INTEGER Length,
            _In_ ULONG Key,
            _In_ BOOLEAN FailImmediately,
            _In_ BOOLEAN ExclusiveLock
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwLockProductActivationKeys(
            _Inout_opt_ ULONG* pPrivateVer,
            _Out_opt_ ULONG* pSafeMode
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwLockRegistryKey(
            _In_ HANDLE KeyHandle
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwLockVirtualMemory(
            _In_ HANDLE ProcessHandle,
            _Inout_ PVOID* BaseAddress,
            _Inout_ PSIZE_T RegionSize,
            _In_ ULONG MapType
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwMakePermanentObject(
            _In_ HANDLE Handle
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwMakeTemporaryObject(
            _In_ HANDLE Handle
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwManagePartition(
            _In_ HANDLE TargetHandle,
            _In_opt_ HANDLE SourceHandle,
            _In_ PARTITION_INFORMATION_CLASS PartitionInformationClass,
            _Inout_updates_bytes_(PartitionInformationLength) PVOID PartitionInformation,
            _In_ ULONG PartitionInformationLength
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwMapCMFModule(
            _In_ ULONG What,
            _In_ ULONG Index,
            _Out_opt_ PULONG CacheIndexOut,
            _Out_opt_ PULONG CacheFlagsOut,
            _Out_opt_ PULONG ViewSizeOut,
            _Out_opt_ PVOID* BaseAddress
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwMapUserPhysicalPages(
            _In_ PVOID VirtualAddress,
            _In_ ULONG_PTR NumberOfPages,
            _In_reads_opt_(NumberOfPages) PULONG_PTR UserPfnArray
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwMapUserPhysicalPagesScatter(
            _In_reads_(NumberOfPages) PVOID* VirtualAddresses,
            _In_ ULONG_PTR NumberOfPages,
            _In_reads_opt_(NumberOfPages) PULONG_PTR UserPfnArray
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwMapViewOfSection(
            _In_ HANDLE SectionHandle,
            _In_ HANDLE ProcessHandle,
            _Inout_ _At_(*BaseAddress, _Readable_bytes_(*ViewSize) _Writable_bytes_(*ViewSize) _Post_readable_byte_size_(*ViewSize)) PVOID* BaseAddress,
            _In_ ULONG_PTR ZeroBits,
            _In_ SIZE_T CommitSize,
            _Inout_opt_ PLARGE_INTEGER SectionOffset,
            _Inout_ PSIZE_T ViewSize,
            _In_ SECTION_INHERIT InheritDisposition,
            _In_ ULONG AllocationType,
            _In_ ULONG Win32Protect
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwMapViewOfSectionEx(
            _In_ HANDLE SectionHandle,
            _In_ HANDLE ProcessHandle,
            _Inout_ _At_(*BaseAddress, _Readable_bytes_(*ViewSize) _Writable_bytes_(*ViewSize) _Post_readable_byte_size_(*ViewSize)) PVOID* BaseAddress,
            _Inout_opt_ PLARGE_INTEGER SectionOffset,
            _Inout_ PSIZE_T ViewSize,
            _In_ ULONG AllocationType,
            _In_ ULONG Win32Protect,
            _Inout_updates_opt_(ExtendedParameterCount) PMEM_EXTENDED_PARAMETER ExtendedParameters,
            _In_ ULONG ExtendedParameterCount
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwModifyBootEntry(
            _In_ PBOOT_ENTRY BootEntry
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwModifyDriverEntry(
            _In_ PEFI_DRIVER_ENTRY DriverEntry
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwNotifyChangeDirectoryFile(
            _In_ HANDLE FileHandle,
            _In_opt_ HANDLE Event,
            _In_opt_ PIO_APC_ROUTINE ApcRoutine,
            _In_opt_ PVOID ApcContext,
            _Out_ PIO_STATUS_BLOCK IoStatusBlock,
            _Out_writes_bytes_(Length) PVOID Buffer, // FILE_NOTIFY_INFORMATION
            _In_ ULONG Length,
            _In_ ULONG CompletionFilter,
            _In_ BOOLEAN WatchTree
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwNotifyChangeDirectoryFileEx(
            _In_ HANDLE FileHandle,
            _In_opt_ HANDLE Event,
            _In_opt_ PIO_APC_ROUTINE ApcRoutine,
            _In_opt_ PVOID ApcContext,
            _Out_ PIO_STATUS_BLOCK IoStatusBlock,
            _Out_writes_bytes_(Length) PVOID Buffer,
            _In_ ULONG Length,
            _In_ ULONG CompletionFilter,
            _In_ BOOLEAN WatchTree,
            _In_opt_ DIRECTORY_NOTIFY_INFORMATION_CLASS DirectoryNotifyInformationClass
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwNotifyChangeKey(
            _In_ HANDLE KeyHandle,
            _In_opt_ HANDLE Event,
            _In_opt_ PIO_APC_ROUTINE ApcRoutine,
            _In_opt_ PVOID ApcContext,
            _Out_ PIO_STATUS_BLOCK IoStatusBlock,
            _In_ ULONG CompletionFilter,
            _In_ BOOLEAN WatchTree,
            _Out_writes_bytes_opt_(BufferSize) PVOID Buffer,
            _In_ ULONG BufferSize,
            _In_ BOOLEAN Asynchronous
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwNotifyChangeMultipleKeys(
            _In_ HANDLE MasterKeyHandle,
            _In_opt_ ULONG Count,
            _In_reads_opt_(Count) OBJECT_ATTRIBUTES SubordinateObjects[],
            _In_opt_ HANDLE Event,
            _In_opt_ PIO_APC_ROUTINE ApcRoutine,
            _In_opt_ PVOID ApcContext,
            _Out_ PIO_STATUS_BLOCK IoStatusBlock,
            _In_ ULONG CompletionFilter,
            _In_ BOOLEAN WatchTree,
            _Out_writes_bytes_opt_(BufferSize) PVOID Buffer,
            _In_ ULONG BufferSize,
            _In_ BOOLEAN Asynchronous
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwNotifyChangeSession(
            _In_ HANDLE SessionHandle,
            _In_ ULONG ChangeSequenceNumber,
            _In_ PLARGE_INTEGER ChangeTimeStamp,
            _In_ IO_SESSION_EVENT Event,
            _In_ IO_SESSION_STATE NewState,
            _In_ IO_SESSION_STATE PreviousState,
            _In_reads_bytes_opt_(PayloadSize) PVOID Payload,
            _In_ ULONG PayloadSize
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwOpenDirectoryObject(
            _Out_ PHANDLE DirectoryHandle,
            _In_ ACCESS_MASK DesiredAccess,
            _In_ POBJECT_ATTRIBUTES ObjectAttributes
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwOpenEnlistment(
            _Out_ PHANDLE EnlistmentHandle,
            _In_ ACCESS_MASK DesiredAccess,
            _In_ HANDLE ResourceManagerHandle,
            _In_ LPGUID EnlistmentGuid,
            _In_opt_ POBJECT_ATTRIBUTES ObjectAttributes
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwOpenEvent(
            _Out_ PHANDLE EventHandle,
            _In_ ACCESS_MASK DesiredAccess,
            _In_ POBJECT_ATTRIBUTES ObjectAttributes
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwOpenEventPair(
            _Out_ PHANDLE EventPairHandle,
            _In_ ACCESS_MASK DesiredAccess,
            _In_ POBJECT_ATTRIBUTES ObjectAttributes
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwOpenFile(
            _Out_ PHANDLE FileHandle,
            _In_ ACCESS_MASK DesiredAccess,
            _In_ POBJECT_ATTRIBUTES ObjectAttributes,
            _Out_ PIO_STATUS_BLOCK IoStatusBlock,
            _In_ ULONG ShareAccess,
            _In_ ULONG OpenOptions
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwOpenIoCompletion(
            _Out_ PHANDLE IoCompletionHandle,
            _In_ ACCESS_MASK DesiredAccess,
            _In_ POBJECT_ATTRIBUTES ObjectAttributes
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwOpenJobObject(
            _Out_ PHANDLE JobHandle,
            _In_ ACCESS_MASK DesiredAccess,
            _In_ POBJECT_ATTRIBUTES ObjectAttributes
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwOpenKey(
            _Out_ PHANDLE KeyHandle,
            _In_ ACCESS_MASK DesiredAccess,
            _In_ POBJECT_ATTRIBUTES ObjectAttributes
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwOpenKeyedEvent(
            _Out_ PHANDLE KeyedEventHandle,
            _In_ ACCESS_MASK DesiredAccess,
            _In_ POBJECT_ATTRIBUTES ObjectAttributes
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwOpenKeyEx(
            _Out_ PHANDLE KeyHandle,
            _In_ ACCESS_MASK DesiredAccess,
            _In_ POBJECT_ATTRIBUTES ObjectAttributes,
            _In_ ULONG OpenOptions
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwOpenKeyTransacted(
            _Out_ PHANDLE KeyHandle,
            _In_ ACCESS_MASK DesiredAccess,
            _In_ POBJECT_ATTRIBUTES ObjectAttributes,
            _In_ HANDLE TransactionHandle
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwOpenKeyTransactedEx(
            _Out_ PHANDLE KeyHandle,
            _In_ ACCESS_MASK DesiredAccess,
            _In_ POBJECT_ATTRIBUTES ObjectAttributes,
            _In_ ULONG OpenOptions,
            _In_ HANDLE TransactionHandle
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwOpenMutant(
            _Out_ PHANDLE MutantHandle,
            _In_ ACCESS_MASK DesiredAccess,
            _In_ POBJECT_ATTRIBUTES ObjectAttributes
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwOpenObjectAuditAlarm(
            _In_ PUNICODE_STRING SubsystemName,
            _In_opt_ PVOID HandleId,
            _In_ PUNICODE_STRING ObjectTypeName,
            _In_ PUNICODE_STRING ObjectName,
            _In_opt_ PSECURITY_DESCRIPTOR SecurityDescriptor,
            _In_ HANDLE ClientToken,
            _In_ ACCESS_MASK DesiredAccess,
            _In_ ACCESS_MASK GrantedAccess,
            _In_opt_ PPRIVILEGE_SET Privileges,
            _In_ BOOLEAN ObjectCreation,
            _In_ BOOLEAN AccessGranted,
            _Out_ PBOOLEAN GenerateOnClose
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwOpenPartition(
            _Out_ PHANDLE PartitionHandle,
            _In_ ACCESS_MASK DesiredAccess,
            _In_ POBJECT_ATTRIBUTES ObjectAttributes
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwOpenPrivateNamespace(
            _Out_ PHANDLE NamespaceHandle,
            _In_ ACCESS_MASK DesiredAccess,
            _In_opt_ POBJECT_ATTRIBUTES ObjectAttributes,
            _In_ POBJECT_BOUNDARY_DESCRIPTOR BoundaryDescriptor
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwOpenProcess(
            _Out_ PHANDLE ProcessHandle,
            _In_ ACCESS_MASK DesiredAccess,
            _In_ POBJECT_ATTRIBUTES ObjectAttributes,
            _In_opt_ PCLIENT_ID ClientId
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwOpenProcessToken(
            _In_ HANDLE ProcessHandle,
            _In_ ACCESS_MASK DesiredAccess,
            _Out_ PHANDLE TokenHandle
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwOpenProcessTokenEx(
            _In_ HANDLE ProcessHandle,
            _In_ ACCESS_MASK DesiredAccess,
            _In_ ULONG HandleAttributes,
            _Out_ PHANDLE TokenHandle
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwOpenResourceManager(
            _Out_ PHANDLE ResourceManagerHandle,
            _In_ ACCESS_MASK DesiredAccess,
            _In_ HANDLE TmHandle,
            _In_opt_ LPGUID ResourceManagerGuid,
            _In_opt_ POBJECT_ATTRIBUTES ObjectAttributes
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwOpenSection(
            _Out_ PHANDLE SectionHandle,
            _In_ ACCESS_MASK DesiredAccess,
            _In_ POBJECT_ATTRIBUTES ObjectAttributes
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwOpenSemaphore(
            _Out_ PHANDLE SemaphoreHandle,
            _In_ ACCESS_MASK DesiredAccess,
            _In_ POBJECT_ATTRIBUTES ObjectAttributes
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwOpenSession(
            _Out_ PHANDLE SessionHandle,
            _In_ ACCESS_MASK DesiredAccess,
            _In_ POBJECT_ATTRIBUTES ObjectAttributes
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwOpenSymbolicLinkObject(
            _Out_ PHANDLE LinkHandle,
            _In_ ACCESS_MASK DesiredAccess,
            _In_ POBJECT_ATTRIBUTES ObjectAttributes
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwOpenThread(
            _Out_ PHANDLE ThreadHandle,
            _In_ ACCESS_MASK DesiredAccess,
            _In_ POBJECT_ATTRIBUTES ObjectAttributes,
            _In_opt_ PCLIENT_ID ClientId
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwOpenThreadToken(
            _In_ HANDLE ThreadHandle,
            _In_ ACCESS_MASK DesiredAccess,
            _In_ BOOLEAN OpenAsSelf,
            _Out_ PHANDLE TokenHandle
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwOpenThreadTokenEx(
            _In_ HANDLE ThreadHandle,
            _In_ ACCESS_MASK DesiredAccess,
            _In_ BOOLEAN OpenAsSelf,
            _In_ ULONG HandleAttributes,
            _Out_ PHANDLE TokenHandle
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwOpenTimer(
            _Out_ PHANDLE TimerHandle,
            _In_ ACCESS_MASK DesiredAccess,
            _In_ POBJECT_ATTRIBUTES ObjectAttributes
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwOpenTransaction(
            _Out_ PHANDLE TransactionHandle,
            _In_ ACCESS_MASK DesiredAccess,
            _In_opt_ POBJECT_ATTRIBUTES ObjectAttributes,
            _In_ LPGUID Uow,
            _In_opt_ HANDLE TmHandle
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwOpenTransactionManager(
            _Out_ PHANDLE TmHandle,
            _In_ ACCESS_MASK DesiredAccess,
            _In_opt_ POBJECT_ATTRIBUTES ObjectAttributes,
            _In_opt_ PUNICODE_STRING LogFileName,
            _In_opt_ LPGUID TmIdentity,
            _In_opt_ ULONG OpenOptions
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwPlugPlayControl(
            _In_ PLUGPLAY_CONTROL_CLASS PnPControlClass,
            _Inout_updates_bytes_(PnPControlDataLength) PVOID PnPControlData,
            _In_ ULONG PnPControlDataLength
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwPowerInformation(
            _In_ POWER_INFORMATION_LEVEL InformationLevel,
            _In_reads_bytes_opt_(InputBufferLength) PVOID InputBuffer,
            _In_ ULONG InputBufferLength,
            _Out_writes_bytes_opt_(OutputBufferLength) PVOID OutputBuffer,
            _In_ ULONG OutputBufferLength
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwPrepareComplete(
            _In_ HANDLE EnlistmentHandle,
            _In_opt_ PLARGE_INTEGER TmVirtualClock
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwPrepareEnlistment(
            _In_ HANDLE EnlistmentHandle,
            _In_opt_ PLARGE_INTEGER TmVirtualClock
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwPrePrepareComplete(
            _In_ HANDLE EnlistmentHandle,
            _In_opt_ PLARGE_INTEGER TmVirtualClock
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwPrePrepareEnlistment(
            _In_ HANDLE EnlistmentHandle,
            _In_opt_ PLARGE_INTEGER TmVirtualClock
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwPrivilegeCheck(
            _In_ HANDLE ClientToken,
            _Inout_ PPRIVILEGE_SET RequiredPrivileges,
            _Out_ PBOOLEAN Result
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwPrivilegedServiceAuditAlarm(
            _In_ PUNICODE_STRING SubsystemName,
            _In_ PUNICODE_STRING ServiceName,
            _In_ HANDLE ClientToken,
            _In_ PPRIVILEGE_SET Privileges,
            _In_ BOOLEAN AccessGranted
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwPrivilegeObjectAuditAlarm(
            _In_ PUNICODE_STRING SubsystemName,
            _In_opt_ PVOID HandleId,
            _In_ HANDLE ClientToken,
            _In_ ACCESS_MASK DesiredAccess,
            _In_ PPRIVILEGE_SET Privileges,
            _In_ BOOLEAN AccessGranted
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwPropagationComplete(
            _In_ HANDLE ResourceManagerHandle,
            _In_ ULONG RequestCookie,
            _In_ ULONG BufferLength,
            _In_ PVOID Buffer
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwPropagationFailed(
            _In_ HANDLE ResourceManagerHandle,
            _In_ ULONG RequestCookie,
            _In_ NTSTATUS PropStatus
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwProtectVirtualMemory(
            _In_ HANDLE ProcessHandle,
            _Inout_ PVOID* BaseAddress,
            _Inout_ PSIZE_T RegionSize,
            _In_ ULONG NewProtect,
            _Out_ PULONG OldProtect
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwPssCaptureVaSpaceBulk(
            _In_ HANDLE ProcessHandle,
            _In_opt_ PVOID BaseAddress,
            _In_ PNTPSS_MEMORY_BULK_INFORMATION BulkInformation,
            _In_ SIZE_T BulkInformationLength,
            _Out_opt_ PSIZE_T ReturnLength
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwPulseEvent(
            _In_ HANDLE EventHandle,
            _Out_opt_ PLONG PreviousState
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwQueryAttributesFile(
            _In_ POBJECT_ATTRIBUTES ObjectAttributes,
            _Out_ PFILE_BASIC_INFORMATION FileInformation
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwQueryAuxiliaryCounterFrequency(
            _Out_ PLARGE_INTEGER AuxiliaryCounterFrequency
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwQueryBootEntryOrder(
            _Out_writes_opt_(*Count) PULONG Ids,
            _Inout_ PULONG Count
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwQueryBootOptions(
            _Out_writes_bytes_opt_(*BootOptionsLength) PBOOT_OPTIONS BootOptions,
            _Inout_ PULONG BootOptionsLength
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwQueryDebugFilterState(
            _In_ ULONG ComponentId,
            _In_ ULONG Level
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwQueryDefaultLocale(
            _In_ BOOLEAN UserProfile,
            _Out_ PLCID DefaultLocaleId
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwQueryDefaultUILanguage(
            _Out_ LANGID* DefaultUILanguageId
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwQueryDirectoryFile(
            _In_ HANDLE FileHandle,
            _In_opt_ HANDLE Event,
            _In_opt_ PIO_APC_ROUTINE ApcRoutine,
            _In_opt_ PVOID ApcContext,
            _Out_ PIO_STATUS_BLOCK IoStatusBlock,
            _Out_writes_bytes_(Length) PVOID FileInformation,
            _In_ ULONG Length,
            _In_ FILE_INFORMATION_CLASS FileInformationClass,
            _In_ BOOLEAN ReturnSingleEntry,
            _In_opt_ PUNICODE_STRING FileName,
            _In_ BOOLEAN RestartScan
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwQueryDirectoryFileEx(
            _In_ HANDLE FileHandle,
            _In_opt_ HANDLE Event,
            _In_opt_ PIO_APC_ROUTINE ApcRoutine,
            _In_opt_ PVOID ApcContext,
            _Out_ PIO_STATUS_BLOCK IoStatusBlock,
            _Out_writes_bytes_(Length) PVOID FileInformation,
            _In_ ULONG Length,
            _In_ FILE_INFORMATION_CLASS FileInformationClass,
            _In_ ULONG QueryFlags,
            _In_opt_ PUNICODE_STRING FileName
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwQueryDirectoryObject(
            _In_ HANDLE DirectoryHandle,
            _Out_writes_bytes_opt_(Length) PVOID Buffer,
            _In_ ULONG Length,
            _In_ BOOLEAN ReturnSingleEntry,
            _In_ BOOLEAN RestartScan,
            _Inout_ PULONG Context,
            _Out_opt_ PULONG ReturnLength
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwQueryDriverEntryOrder(
            _Out_writes_opt_(*Count) PULONG Ids,
            _Inout_ PULONG Count
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwQueryEaFile(
            _In_ HANDLE FileHandle,
            _Out_ PIO_STATUS_BLOCK IoStatusBlock,
            _Out_writes_bytes_(Length) PVOID Buffer,
            _In_ ULONG Length,
            _In_ BOOLEAN ReturnSingleEntry,
            _In_reads_bytes_opt_(EaListLength) PVOID EaList,
            _In_ ULONG EaListLength,
            _In_opt_ PULONG EaIndex,
            _In_ BOOLEAN RestartScan
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwQueryEvent(
            _In_ HANDLE EventHandle,
            _In_ EVENT_INFORMATION_CLASS EventInformationClass,
            _Out_writes_bytes_(EventInformationLength) PVOID EventInformation,
            _In_ ULONG EventInformationLength,
            _Out_opt_ PULONG ReturnLength
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwQueryFullAttributesFile(
            _In_ POBJECT_ATTRIBUTES ObjectAttributes,
            _Out_ PFILE_NETWORK_OPEN_INFORMATION FileInformation
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwQueryInformationAtom(
            _In_ RTL_ATOM Atom,
            _In_ ATOM_INFORMATION_CLASS AtomInformationClass,
            _Out_writes_bytes_(AtomInformationLength) PVOID AtomInformation,
            _In_ ULONG AtomInformationLength,
            _Out_opt_ PULONG ReturnLength
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwQueryInformationByName(
            _In_ POBJECT_ATTRIBUTES ObjectAttributes,
            _Out_ PIO_STATUS_BLOCK IoStatusBlock,
            _Out_writes_bytes_(Length) PVOID FileInformation,
            _In_ ULONG Length,
            _In_ FILE_INFORMATION_CLASS FileInformationClass
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwQueryInformationEnlistment(
            _In_ HANDLE EnlistmentHandle,
            _In_ ENLISTMENT_INFORMATION_CLASS EnlistmentInformationClass,
            _Out_writes_bytes_(EnlistmentInformationLength) PVOID EnlistmentInformation,
            _In_ ULONG EnlistmentInformationLength,
            _Out_opt_ PULONG ReturnLength
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwQueryInformationFile(
            _In_ HANDLE FileHandle,
            _Out_ PIO_STATUS_BLOCK IoStatusBlock,
            _Out_writes_bytes_(Length) PVOID FileInformation,
            _In_ ULONG Length,
            _In_ FILE_INFORMATION_CLASS FileInformationClass
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwQueryInformationJobObject(
            _In_opt_ HANDLE JobHandle,
            _In_ JOBOBJECTINFOCLASS JobObjectInformationClass,
            _Out_writes_bytes_(JobObjectInformationLength) PVOID JobObjectInformation,
            _In_ ULONG JobObjectInformationLength,
            _Out_opt_ PULONG ReturnLength
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwQueryInformationPort(
            _In_ HANDLE PortHandle,
            _In_ PORT_INFORMATION_CLASS PortInformationClass,
            _Out_writes_bytes_to_(Length, *ReturnLength) PVOID PortInformation,
            _In_ ULONG Length,
            _Out_opt_ PULONG ReturnLength
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwQueryInformationProcess(
            _In_ HANDLE ProcessHandle,
            _In_ PROCESSINFOCLASS ProcessInformationClass,
            _Out_writes_bytes_(ProcessInformationLength) PVOID ProcessInformation,
            _In_ ULONG ProcessInformationLength,
            _Out_opt_ PULONG ReturnLength
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwQueryInformationResourceManager(
            _In_ HANDLE ResourceManagerHandle,
            _In_ RESOURCEMANAGER_INFORMATION_CLASS ResourceManagerInformationClass,
            _Out_writes_bytes_(ResourceManagerInformationLength) PVOID ResourceManagerInformation,
            _In_ ULONG ResourceManagerInformationLength,
            _Out_opt_ PULONG ReturnLength
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwQueryInformationThread(
            _In_ HANDLE ThreadHandle,
            _In_ THREADINFOCLASS ThreadInformationClass,
            _Out_writes_bytes_(ThreadInformationLength) PVOID ThreadInformation,
            _In_ ULONG ThreadInformationLength,
            _Out_opt_ PULONG ReturnLength
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwQueryInformationToken(
            _In_ HANDLE TokenHandle,
            _In_ TOKEN_INFORMATION_CLASS TokenInformationClass,
            _Out_writes_bytes_to_opt_(TokenInformationLength, *ReturnLength) PVOID TokenInformation,
            _In_ ULONG TokenInformationLength,
            _Out_ PULONG ReturnLength
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwQueryInformationTransaction(
            _In_ HANDLE TransactionHandle,
            _In_ TRANSACTION_INFORMATION_CLASS TransactionInformationClass,
            _Out_writes_bytes_(TransactionInformationLength) PVOID TransactionInformation,
            _In_ ULONG TransactionInformationLength,
            _Out_opt_ PULONG ReturnLength
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwQueryInformationTransactionManager(
            _In_ HANDLE TransactionManagerHandle,
            _In_ TRANSACTIONMANAGER_INFORMATION_CLASS TransactionManagerInformationClass,
            _Out_writes_bytes_(TransactionManagerInformationLength) PVOID TransactionManagerInformation,
            _In_ ULONG TransactionManagerInformationLength,
            _Out_opt_ PULONG ReturnLength
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwQueryInformationWorkerFactory(
            _In_ HANDLE WorkerFactoryHandle,
            _In_ WORKERFACTORYINFOCLASS WorkerFactoryInformationClass,
            _Out_writes_bytes_(WorkerFactoryInformationLength) PVOID WorkerFactoryInformation,
            _In_ ULONG WorkerFactoryInformationLength,
            _Out_opt_ PULONG ReturnLength
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwQueryInstallUILanguage(
            _Out_ LANGID* InstallUILanguageId
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwQueryIntervalProfile(
            _In_ KPROFILE_SOURCE ProfileSource,
            _Out_ PULONG Interval
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwQueryIoCompletion(
            _In_ HANDLE IoCompletionHandle,
            _In_ IO_COMPLETION_INFORMATION_CLASS IoCompletionInformationClass,
            _Out_writes_bytes_(IoCompletionInformationLength) PVOID IoCompletionInformation,
            _In_ ULONG IoCompletionInformationLength,
            _Out_opt_ PULONG ReturnLength
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwQueryKey(
            _In_ HANDLE KeyHandle,
            _In_ KEY_INFORMATION_CLASS KeyInformationClass,
            _Out_writes_bytes_opt_(Length) PVOID KeyInformation,
            _In_ ULONG Length,
            _Out_ PULONG ResultLength
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwQueryLicenseValue(
            _In_ PUNICODE_STRING ValueName,
            _Out_opt_ PULONG Type,
            _Out_writes_bytes_to_opt_(DataSize, *ResultDataSize) PVOID Data,
            _In_ ULONG DataSize,
            _Out_ PULONG ResultDataSize
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwQueryMultipleValueKey(
            _In_ HANDLE KeyHandle,
            _Inout_updates_(EntryCount) PKEY_VALUE_ENTRY ValueEntries,
            _In_ ULONG EntryCount,
            _Out_writes_bytes_(*BufferLength) PVOID ValueBuffer,
            _Inout_ PULONG BufferLength,
            _Out_opt_ PULONG RequiredBufferLength
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwQueryMutant(
            _In_ HANDLE MutantHandle,
            _In_ MUTANT_INFORMATION_CLASS MutantInformationClass,
            _Out_writes_bytes_(MutantInformationLength) PVOID MutantInformation,
            _In_ ULONG MutantInformationLength,
            _Out_opt_ PULONG ReturnLength
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwQueryObject(
            _In_opt_ HANDLE Handle,
            _In_ OBJECT_INFORMATION_CLASS ObjectInformationClass,
            _Out_writes_bytes_opt_(ObjectInformationLength) PVOID ObjectInformation,
            _In_ ULONG ObjectInformationLength,
            _Out_opt_ PULONG ReturnLength
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwQueryOpenSubKeys(
            _In_ POBJECT_ATTRIBUTES TargetKey,
            _Out_ PULONG HandleCount
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwQueryOpenSubKeysEx(
            _In_ POBJECT_ATTRIBUTES TargetKey,
            _In_ ULONG BufferLength,
            _Out_writes_bytes_opt_(BufferLength) PVOID Buffer,
            _Out_ PULONG RequiredSize
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwQueryPerformanceCounter(
            _Out_ PLARGE_INTEGER PerformanceCounter,
            _Out_opt_ PLARGE_INTEGER PerformanceFrequency
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwQueryPortInformationProcess(
            VOID
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwQueryQuotaInformationFile(
            _In_ HANDLE FileHandle,
            _Out_ PIO_STATUS_BLOCK IoStatusBlock,
            _Out_writes_bytes_(Length) PVOID Buffer,
            _In_ ULONG Length,
            _In_ BOOLEAN ReturnSingleEntry,
            _In_reads_bytes_opt_(SidListLength) PVOID SidList,
            _In_ ULONG SidListLength,
            _In_opt_ PSID StartSid,
            _In_ BOOLEAN RestartScan
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwQuerySection(
            _In_ HANDLE SectionHandle,
            _In_ SECTION_INFORMATION_CLASS SectionInformationClass,
            _Out_writes_bytes_(SectionInformationLength) PVOID SectionInformation,
            _In_ SIZE_T SectionInformationLength,
            _Out_opt_ PSIZE_T ReturnLength
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwQuerySecurityAttributesToken(
            _In_ HANDLE TokenHandle,
            _In_reads_opt_(NumberOfAttributes) PUNICODE_STRING Attributes,
            _In_ ULONG NumberOfAttributes,
            _Out_writes_bytes_(Length) PVOID Buffer, // PTOKEN_SECURITY_ATTRIBUTES_INFORMATION
            _In_ ULONG Length,
            _Out_ PULONG ReturnLength
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwQuerySecurityObject(
            _In_ HANDLE Handle,
            _In_ SECURITY_INFORMATION SecurityInformation,
            _Out_writes_bytes_opt_(Length) PSECURITY_DESCRIPTOR SecurityDescriptor,
            _In_ ULONG Length,
            _Out_ PULONG LengthNeeded
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwQuerySemaphore(
            _In_ HANDLE SemaphoreHandle,
            _In_ SEMAPHORE_INFORMATION_CLASS SemaphoreInformationClass,
            _Out_writes_bytes_(SemaphoreInformationLength) PVOID SemaphoreInformation,
            _In_ ULONG SemaphoreInformationLength,
            _Out_opt_ PULONG ReturnLength
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwQuerySymbolicLinkObject(
            _In_ HANDLE LinkHandle,
            _Inout_ PUNICODE_STRING LinkTarget,
            _Out_opt_ PULONG ReturnedLength
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwQuerySystemEnvironmentValue(
            _In_ PUNICODE_STRING VariableName,
            _Out_writes_bytes_(ValueLength) PWSTR VariableValue,
            _In_ USHORT ValueLength,
            _Out_opt_ PUSHORT ReturnLength
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwQuerySystemEnvironmentValueEx(
            _In_ PUNICODE_STRING VariableName,
            _In_ PCGUID VendorGuid,
            _Out_writes_bytes_opt_(*ValueLength) PVOID Value,
            _Inout_ PULONG ValueLength,
            _Out_opt_ PULONG Attributes // EFI_VARIABLE_*
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwQuerySystemInformation(
            _In_ SYSTEM_INFORMATION_CLASS SystemInformationClass,
            _Out_writes_bytes_opt_(SystemInformationLength) PVOID SystemInformation,
            _In_ ULONG SystemInformationLength,
            _Out_opt_ PULONG ReturnLength
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwQuerySystemInformationEx(
            _In_ SYSTEM_INFORMATION_CLASS SystemInformationClass,
            _In_reads_bytes_(InputBufferLength) PVOID InputBuffer,
            _In_ ULONG InputBufferLength,
            _Out_writes_bytes_opt_(SystemInformationLength) PVOID SystemInformation,
            _In_ ULONG SystemInformationLength,
            _Out_opt_ PULONG ReturnLength
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwQuerySystemTime(
            _Out_ PLARGE_INTEGER SystemTime
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwQueryTimer(
            _In_ HANDLE TimerHandle,
            _In_ TIMER_INFORMATION_CLASS TimerInformationClass,
            _Out_writes_bytes_(TimerInformationLength) PVOID TimerInformation,
            _In_ ULONG TimerInformationLength,
            _Out_opt_ PULONG ReturnLength
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwQueryTimerResolution(
            _Out_ PULONG MaximumTime,
            _Out_ PULONG MinimumTime,
            _Out_ PULONG CurrentTime
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwQueryValueKey(
            _In_ HANDLE KeyHandle,
            _In_ PUNICODE_STRING ValueName,
            _In_ KEY_VALUE_INFORMATION_CLASS KeyValueInformationClass,
            _Out_writes_bytes_opt_(Length) PVOID KeyValueInformation,
            _In_ ULONG Length,
            _Out_ PULONG ResultLength
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwQueryVirtualMemory(
            _In_ HANDLE ProcessHandle,
            _In_opt_ PVOID BaseAddress,
            _In_ MEMORY_INFORMATION_CLASS MemoryInformationClass,
            _Out_writes_bytes_(MemoryInformationLength) PVOID MemoryInformation,
            _In_ SIZE_T MemoryInformationLength,
            _Out_opt_ PSIZE_T ReturnLength
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwQueryVolumeInformationFile(
            _In_ HANDLE FileHandle,
            _Out_ PIO_STATUS_BLOCK IoStatusBlock,
            _Out_writes_bytes_(Length) PVOID FsInformation,
            _In_ ULONG Length,
            _In_ FSINFOCLASS FsInformationClass
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwQueryWnfStateData(
            _In_ PCWNF_STATE_NAME StateName,
            _In_opt_ PCWNF_TYPE_ID TypeId,
            _In_opt_ const VOID* ExplicitScope,
            _Out_ PWNF_CHANGE_STAMP ChangeStamp,
            _Out_writes_bytes_opt_(*BufferSize) PVOID Buffer,
            _Inout_ PULONG BufferSize
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwQueryWnfStateNameInformation(
            _In_ PCWNF_STATE_NAME StateName,
            _In_ WNF_STATE_NAME_INFORMATION NameInfoClass,
            _In_opt_ const VOID* ExplicitScope,
            _Out_writes_bytes_(InfoBufferSize) PVOID InfoBuffer,
            _In_ ULONG InfoBufferSize
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwQueueApcThread(
            _In_ HANDLE ThreadHandle,
            _In_ PPS_APC_ROUTINE ApcRoutine,
            _In_opt_ PVOID ApcArgument1,
            _In_opt_ PVOID ApcArgument2,
            _In_opt_ PVOID ApcArgument3
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwQueueApcThreadEx(
            _In_ HANDLE ThreadHandle,
            _In_opt_ HANDLE ReserveHandle, // NtAllocateReserveObject // SPECIAL_USER_APC
            _In_ PPS_APC_ROUTINE ApcRoutine,
            _In_opt_ PVOID ApcArgument1,
            _In_opt_ PVOID ApcArgument2,
            _In_opt_ PVOID ApcArgument3
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwQueueApcThreadEx2(
            _In_ HANDLE ThreadHandle,
            _In_opt_ HANDLE ReserveHandle, // NtAllocateReserveObject
            _In_ ULONG ApcFlags, // QUEUE_USER_APC_FLAGS
            _In_ PPS_APC_ROUTINE ApcRoutine,
            _In_opt_ PVOID ApcArgument1,
            _In_opt_ PVOID ApcArgument2,
            _In_opt_ PVOID ApcArgument3
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwRaiseException(
            _In_ PEXCEPTION_RECORD ExceptionRecord,
            _In_ PCONTEXT ContextRecord,
            _In_ BOOLEAN FirstChance
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwRaiseHardError(
            _In_ NTSTATUS ErrorStatus,
            _In_ ULONG NumberOfParameters,
            _In_ ULONG UnicodeStringParameterMask,
            _In_reads_(NumberOfParameters) PULONG_PTR Parameters,
            _In_ ULONG ValidResponseOptions,
            _Out_ PULONG Response
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwReadFile(
            _In_ HANDLE FileHandle,
            _In_opt_ HANDLE Event,
            _In_opt_ PIO_APC_ROUTINE ApcRoutine,
            _In_opt_ PVOID ApcContext,
            _Out_ PIO_STATUS_BLOCK IoStatusBlock,
            _Out_writes_bytes_(Length) PVOID Buffer,
            _In_ ULONG Length,
            _In_opt_ PLARGE_INTEGER ByteOffset,
            _In_opt_ PULONG Key
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwReadFileScatter(
            _In_ HANDLE FileHandle,
            _In_opt_ HANDLE Event,
            _In_opt_ PIO_APC_ROUTINE ApcRoutine,
            _In_opt_ PVOID ApcContext,
            _Out_ PIO_STATUS_BLOCK IoStatusBlock,
            _In_ PFILE_SEGMENT_ELEMENT SegmentArray,
            _In_ ULONG Length,
            _In_opt_ PLARGE_INTEGER ByteOffset,
            _In_opt_ PULONG Key
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwReadOnlyEnlistment(
            _In_ HANDLE EnlistmentHandle,
            _In_opt_ PLARGE_INTEGER TmVirtualClock
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwReadRequestData(
            _In_ HANDLE PortHandle,
            _In_ PPORT_MESSAGE Message,
            _In_ ULONG DataEntryIndex,
            _Out_writes_bytes_to_(BufferSize, *NumberOfBytesRead) PVOID Buffer,
            _In_ SIZE_T BufferSize,
            _Out_opt_ PSIZE_T NumberOfBytesRead
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwReadVirtualMemory(
            _In_ HANDLE ProcessHandle,
            _In_opt_ PVOID BaseAddress,
            _Out_writes_bytes_(BufferSize) PVOID Buffer,
            _In_ SIZE_T BufferSize,
            _Out_opt_ PSIZE_T NumberOfBytesRead
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwReadVirtualMemoryEx(
            _In_ HANDLE ProcessHandle,
            _In_opt_ PVOID BaseAddress,
            _Out_writes_bytes_(BufferSize) PVOID Buffer,
            _In_ SIZE_T BufferSize,
            _Out_opt_ PSIZE_T NumberOfBytesRead,
            _In_ ULONG Flags
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwRecoverEnlistment(
            _In_ HANDLE EnlistmentHandle,
            _In_opt_ PVOID EnlistmentKey
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwRecoverResourceManager(
            _In_ HANDLE ResourceManagerHandle
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwRecoverTransactionManager(
            _In_ HANDLE TransactionManagerHandle
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwRegisterProtocolAddressInformation(
            _In_ HANDLE ResourceManager,
            _In_ PCRM_PROTOCOL_ID ProtocolId,
            _In_ ULONG ProtocolInformationSize,
            _In_ PVOID ProtocolInformation,
            _In_opt_ ULONG CreateOptions
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwRegisterThreadTerminatePort(
            _In_ HANDLE PortHandle
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwReleaseCMFViewOwnership(
            VOID
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwReleaseKeyedEvent(
            _In_opt_ HANDLE KeyedEventHandle,
            _In_ PVOID KeyValue,
            _In_ BOOLEAN Alertable,
            _In_opt_ PLARGE_INTEGER Timeout
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwReleaseMutant(
            _In_ HANDLE MutantHandle,
            _Out_opt_ PLONG PreviousCount
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwReleaseSemaphore(
            _In_ HANDLE SemaphoreHandle,
            _In_ LONG ReleaseCount,
            _Out_opt_ PLONG PreviousCount
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwReleaseWorkerFactoryWorker(
            _In_ HANDLE WorkerFactoryHandle
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwRemoveIoCompletion(
            _In_ HANDLE IoCompletionHandle,
            _Out_ PVOID* KeyContext,
            _Out_ PVOID* ApcContext,
            _Out_ PIO_STATUS_BLOCK IoStatusBlock,
            _In_opt_ PLARGE_INTEGER Timeout
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwRemoveIoCompletionEx(
            _In_ HANDLE IoCompletionHandle,
            _Out_writes_to_(Count, *NumEntriesRemoved) PFILE_IO_COMPLETION_INFORMATION IoCompletionInformation,
            _In_ ULONG Count,
            _Out_ PULONG NumEntriesRemoved,
            _In_opt_ PLARGE_INTEGER Timeout,
            _In_ BOOLEAN Alertable
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwRemoveProcessDebug(
            _In_ HANDLE ProcessHandle,
            _In_ HANDLE DebugObjectHandle
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwRenameKey(
            _In_ HANDLE KeyHandle,
            _In_ PUNICODE_STRING NewName
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwRenameTransactionManager(
            _In_ PUNICODE_STRING LogFileName,
            _In_ LPGUID ExistingTransactionManagerGuid
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwReplaceKey(
            _In_ POBJECT_ATTRIBUTES NewFile,
            _In_ HANDLE TargetHandle,
            _In_ POBJECT_ATTRIBUTES OldFile
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwReplacePartitionUnit(
            _In_ PUNICODE_STRING TargetInstancePath,
            _In_ PUNICODE_STRING SpareInstancePath,
            _In_ ULONG Flags
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwReplyPort(
            _In_ HANDLE PortHandle,
            _In_reads_bytes_(ReplyMessage->u1.s1.TotalLength) PPORT_MESSAGE ReplyMessage
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwReplyWaitReceivePort(
            _In_ HANDLE PortHandle,
            _Out_opt_ PVOID* PortContext,
            _In_reads_bytes_opt_(ReplyMessage->u1.s1.TotalLength) PPORT_MESSAGE ReplyMessage,
            _Out_ PPORT_MESSAGE ReceiveMessage
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwReplyWaitReceivePortEx(
            _In_ HANDLE PortHandle,
            _Out_opt_ PVOID* PortContext,
            _In_reads_bytes_opt_(ReplyMessage->u1.s1.TotalLength) PPORT_MESSAGE ReplyMessage,
            _Out_ PPORT_MESSAGE ReceiveMessage,
            _In_opt_ PLARGE_INTEGER Timeout
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwReplyWaitReplyPort(
            _In_ HANDLE PortHandle,
            _Inout_ PPORT_MESSAGE ReplyMessage
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwRequestPort(
            _In_ HANDLE PortHandle,
            _In_reads_bytes_(RequestMessage->u1.s1.TotalLength) PPORT_MESSAGE RequestMessage
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwRequestWaitReplyPort(
            _In_ HANDLE PortHandle,
            _In_reads_bytes_(RequestMessage->u1.s1.TotalLength) PPORT_MESSAGE RequestMessage,
            _Out_ PPORT_MESSAGE ReplyMessage
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwRequestWakeupLatency(
            _In_ LATENCY_TIME latency
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwResetEvent(
            _In_ HANDLE EventHandle,
            _Out_opt_ PLONG PreviousState
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwResetWriteWatch(
            _In_ HANDLE ProcessHandle,
            _In_ PVOID BaseAddress,
            _In_ SIZE_T RegionSize
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwRestoreKey(
            _In_ HANDLE KeyHandle,
            _In_ HANDLE FileHandle,
            _In_ ULONG Flags
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwResumeProcess(
            _In_ HANDLE ProcessHandle
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwResumeThread(
            _In_ HANDLE ThreadHandle,
            _Out_opt_ PULONG PreviousSuspendCount
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwRevertContainerImpersonation(
            VOID
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwRollbackComplete(
            _In_ HANDLE EnlistmentHandle,
            _In_opt_ PLARGE_INTEGER TmVirtualClock
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwRollbackEnlistment(
            _In_ HANDLE EnlistmentHandle,
            _In_opt_ PLARGE_INTEGER TmVirtualClock
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwRollbackTransaction(
            _In_ HANDLE TransactionHandle,
            _In_ BOOLEAN Wait
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwRollforwardTransactionManager(
            _In_ HANDLE TransactionManagerHandle,
            _In_opt_ PLARGE_INTEGER TmVirtualClock
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwSaveKey(
            _In_ HANDLE KeyHandle,
            _In_ HANDLE FileHandle
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwSaveKeyEx(
            _In_ HANDLE KeyHandle,
            _In_ HANDLE FileHandle,
            _In_ ULONG Format
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwSaveMergedKeys(
            _In_ HANDLE HighPrecedenceKeyHandle,
            _In_ HANDLE LowPrecedenceKeyHandle,
            _In_ HANDLE FileHandle
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwSecureConnectPort(
            _Out_ PHANDLE PortHandle,
            _In_ PUNICODE_STRING PortName,
            _In_ PSECURITY_QUALITY_OF_SERVICE SecurityQos,
            _Inout_opt_ PPORT_VIEW ClientView,
            _In_opt_ PSID RequiredServerSid,
            _Inout_opt_ PREMOTE_PORT_VIEW ServerView,
            _Out_opt_ PULONG MaxMessageLength,
            _Inout_updates_bytes_to_opt_(*ConnectionInformationLength, *ConnectionInformationLength) PVOID ConnectionInformation,
            _Inout_opt_ PULONG ConnectionInformationLength
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwSerializeBoot(
            VOID
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwSetBootEntryOrder(
            _In_reads_(Count) PULONG Ids,
            _In_ ULONG Count
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwSetBootOptions(
            _In_ PBOOT_OPTIONS BootOptions,
            _In_ ULONG FieldsToChange
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwSetCachedSigningLevel(
            _In_ ULONG Flags,
            _In_ SE_SIGNING_LEVEL InputSigningLevel,
            _In_reads_(SourceFileCount) PHANDLE SourceFiles,
            _In_ ULONG SourceFileCount,
            _In_opt_ HANDLE TargetFile
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwSetContextThread(
            _In_ HANDLE ThreadHandle,
            _In_ PCONTEXT ThreadContext
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwSetDebugFilterState(
            _In_ ULONG ComponentId,
            _In_ ULONG Level,
            _In_ BOOLEAN State
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwSetDefaultHardErrorPort(
            _In_ HANDLE DefaultHardErrorPort
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwSetDefaultLocale(
            _In_ BOOLEAN UserProfile,
            _In_ LCID DefaultLocaleId
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwSetDefaultUILanguage(
            _In_ LANGID DefaultUILanguageId
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwSetDriverEntryOrder(
            _In_reads_(Count) PULONG Ids,
            _In_ ULONG Count
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwSetEaFile(
            _In_ HANDLE FileHandle,
            _Out_ PIO_STATUS_BLOCK IoStatusBlock,
            _In_reads_bytes_(Length) PVOID Buffer,
            _In_ ULONG Length
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwSetEvent(
            _In_ HANDLE EventHandle,
            _Out_opt_ PLONG PreviousState
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwSetEventBoostPriority(
            _In_ HANDLE EventHandle
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwSetHighEventPair(
            _In_ HANDLE EventPairHandle
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwSetHighWaitLowEventPair(
            _In_ HANDLE EventPairHandle
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwSetInformationDebugObject(
            _In_ HANDLE DebugObjectHandle,
            _In_ DEBUGOBJECTINFOCLASS DebugObjectInformationClass,
            _In_ PVOID DebugInformation,
            _In_ ULONG DebugInformationLength,
            _Out_opt_ PULONG ReturnLength
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwSetInformationEnlistment(
            _In_opt_ HANDLE EnlistmentHandle,
            _In_ ENLISTMENT_INFORMATION_CLASS EnlistmentInformationClass,
            _In_reads_bytes_(EnlistmentInformationLength) PVOID EnlistmentInformation,
            _In_ ULONG EnlistmentInformationLength
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwSetInformationFile(
            _In_ HANDLE FileHandle,
            _Out_ PIO_STATUS_BLOCK IoStatusBlock,
            _In_reads_bytes_(Length) PVOID FileInformation,
            _In_ ULONG Length,
            _In_ FILE_INFORMATION_CLASS FileInformationClass
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwSetInformationJobObject(
            _In_ HANDLE JobHandle,
            _In_ JOBOBJECTINFOCLASS JobObjectInformationClass,
            _In_reads_bytes_(JobObjectInformationLength) PVOID JobObjectInformation,
            _In_ ULONG JobObjectInformationLength
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwSetInformationKey(
            _In_ HANDLE KeyHandle,
            _In_ KEY_SET_INFORMATION_CLASS KeySetInformationClass,
            _In_reads_bytes_(KeySetInformationLength) PVOID KeySetInformation,
            _In_ ULONG KeySetInformationLength
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwSetInformationObject(
            _In_ HANDLE Handle,
            _In_ OBJECT_INFORMATION_CLASS ObjectInformationClass,
            _In_reads_bytes_(ObjectInformationLength) PVOID ObjectInformation,
            _In_ ULONG ObjectInformationLength
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwSetInformationProcess(
            _In_ HANDLE ProcessHandle,
            _In_ PROCESSINFOCLASS ProcessInformationClass,
            _In_reads_bytes_(ProcessInformationLength) PVOID ProcessInformation,
            _In_ ULONG ProcessInformationLength
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwSetInformationResourceManager(
            _In_ HANDLE ResourceManagerHandle,
            _In_ RESOURCEMANAGER_INFORMATION_CLASS ResourceManagerInformationClass,
            _In_reads_bytes_(ResourceManagerInformationLength) PVOID ResourceManagerInformation,
            _In_ ULONG ResourceManagerInformationLength
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwSetInformationSymbolicLink(
            _In_ HANDLE LinkHandle,
            _In_ SYMBOLIC_LINK_INFO_CLASS SymbolicLinkInformationClass,
            _In_reads_bytes_(SymbolicLinkInformationLength) PVOID SymbolicLinkInformation,
            _In_ ULONG SymbolicLinkInformationLength
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwSetInformationThread(
            _In_ HANDLE ThreadHandle,
            _In_ THREADINFOCLASS ThreadInformationClass,
            _In_reads_bytes_(ThreadInformationLength) PVOID ThreadInformation,
            _In_ ULONG ThreadInformationLength
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwSetInformationToken(
            _In_ HANDLE TokenHandle,
            _In_ TOKEN_INFORMATION_CLASS TokenInformationClass,
            _In_reads_bytes_(TokenInformationLength) PVOID TokenInformation,
            _In_ ULONG TokenInformationLength
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwSetInformationTransaction(
            _In_ HANDLE TransactionHandle,
            _In_ TRANSACTION_INFORMATION_CLASS TransactionInformationClass,
            _In_reads_bytes_(TransactionInformationLength) PVOID TransactionInformation,
            _In_ ULONG TransactionInformationLength
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwSetInformationTransactionManager(
            _In_opt_ HANDLE TmHandle,
            _In_ TRANSACTIONMANAGER_INFORMATION_CLASS TransactionManagerInformationClass,
            _In_reads_bytes_(TransactionManagerInformationLength) PVOID TransactionManagerInformation,
            _In_ ULONG TransactionManagerInformationLength
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwSetInformationVirtualMemory(
            _In_ HANDLE ProcessHandle,
            _In_ VIRTUAL_MEMORY_INFORMATION_CLASS VmInformationClass,
            _In_ ULONG_PTR NumberOfEntries,
            _In_reads_(NumberOfEntries) PMEMORY_RANGE_ENTRY VirtualAddresses,
            _In_reads_bytes_(VmInformationLength) PVOID VmInformation,
            _In_ ULONG VmInformationLength
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwSetInformationWorkerFactory(
            _In_ HANDLE WorkerFactoryHandle,
            _In_ WORKERFACTORYINFOCLASS WorkerFactoryInformationClass,
            _In_reads_bytes_(WorkerFactoryInformationLength) PVOID WorkerFactoryInformation,
            _In_ ULONG WorkerFactoryInformationLength
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwSetIntervalProfile(
            _In_ ULONG Interval,
            _In_ KPROFILE_SOURCE Source
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwSetIoCompletion(
            _In_ HANDLE IoCompletionHandle,
            _In_opt_ PVOID KeyContext,
            _In_opt_ PVOID ApcContext,
            _In_ NTSTATUS IoStatus,
            _In_ ULONG_PTR IoStatusInformation
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwSetIoCompletionEx(
            _In_ HANDLE IoCompletionHandle,
            _In_ HANDLE IoCompletionPacketHandle,
            _In_opt_ PVOID KeyContext,
            _In_opt_ PVOID ApcContext,
            _In_ NTSTATUS IoStatus,
            _In_ ULONG_PTR IoStatusInformation
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwSetIRTimer(
            _In_ HANDLE TimerHandle,
            _In_opt_ PLARGE_INTEGER DueTime
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwSetLdtEntries(
            _In_ ULONG Selector0,
            _In_ ULONG Entry0Low,
            _In_ ULONG Entry0Hi,
            _In_ ULONG Selector1,
            _In_ ULONG Entry1Low,
            _In_ ULONG Entry1Hi
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwSetLowEventPair(
            _In_ HANDLE EventPairHandle
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwSetLowWaitHighEventPair(
            _In_ HANDLE EventPairHandle
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwSetQuotaInformationFile(
            _In_ HANDLE FileHandle,
            _Out_ PIO_STATUS_BLOCK IoStatusBlock,
            _In_reads_bytes_(Length) PVOID Buffer,
            _In_ ULONG Length
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwSetSecurityObject(
            _In_ HANDLE Handle,
            _In_ SECURITY_INFORMATION SecurityInformation,
            _In_ PSECURITY_DESCRIPTOR SecurityDescriptor
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwSetSystemEnvironmentValue(
            _In_ PUNICODE_STRING VariableName,
            _In_ PUNICODE_STRING VariableValue
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwSetSystemEnvironmentValueEx(
            _In_ PUNICODE_STRING VariableName,
            _In_ PCGUID VendorGuid,
            _In_reads_bytes_opt_(ValueLength) PVOID Value,
            _In_ ULONG ValueLength, // 0 = delete variable
            _In_ ULONG Attributes // EFI_VARIABLE_*
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwSetSystemInformation(
            _In_ SYSTEM_INFORMATION_CLASS SystemInformationClass,
            _In_reads_bytes_opt_(SystemInformationLength) PVOID SystemInformation,
            _In_ ULONG SystemInformationLength
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwSetSystemPowerState(
            _In_ POWER_ACTION SystemAction,
            _In_ SYSTEM_POWER_STATE LightestSystemState,
            _In_ ULONG Flags // POWER_ACTION_* flags
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwSetSystemTime(
            _In_opt_ PLARGE_INTEGER SystemTime,
            _Out_opt_ PLARGE_INTEGER PreviousTime
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwSetThreadExecutionState(
            _In_ EXECUTION_STATE NewFlags, // ES_* flags
            _Out_ EXECUTION_STATE* PreviousFlags
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwSetTimer(
            _In_ HANDLE TimerHandle,
            _In_ PLARGE_INTEGER DueTime,
            _In_opt_ PTIMER_APC_ROUTINE TimerApcRoutine,
            _In_opt_ PVOID TimerContext,
            _In_ BOOLEAN ResumeTimer,
            _In_opt_ LONG Period,
            _Out_opt_ PBOOLEAN PreviousState
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwSetTimer2(
            _In_ HANDLE TimerHandle,
            _In_ PLARGE_INTEGER DueTime,
            _In_opt_ PLARGE_INTEGER Period,
            _In_ PT2_SET_PARAMETERS Parameters
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwSetTimerEx(
            _In_ HANDLE TimerHandle,
            _In_ TIMER_SET_INFORMATION_CLASS TimerSetInformationClass,
            _Inout_updates_bytes_opt_(TimerSetInformationLength) PVOID TimerSetInformation,
            _In_ ULONG TimerSetInformationLength
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwSetTimerResolution(
            _In_ ULONG DesiredTime,
            _In_ BOOLEAN SetResolution,
            _Out_ PULONG ActualTime
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwSetUuidSeed(
            _In_ PCHAR Seed
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwSetValueKey(
            _In_ HANDLE KeyHandle,
            _In_ PUNICODE_STRING ValueName,
            _In_opt_ ULONG TitleIndex,
            _In_ ULONG Type,
            _In_reads_bytes_opt_(DataSize) PVOID Data,
            _In_ ULONG DataSize
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwSetVolumeInformationFile(
            _In_ HANDLE FileHandle,
            _Out_ PIO_STATUS_BLOCK IoStatusBlock,
            _In_reads_bytes_(Length) PVOID FsInformation,
            _In_ ULONG Length,
            _In_ FSINFOCLASS FsInformationClass
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwSetWnfProcessNotificationEvent(
            _In_ HANDLE NotificationEvent
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwShutdownSystem(
            _In_ SHUTDOWN_ACTION Action
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwShutdownWorkerFactory(
            _In_ HANDLE WorkerFactoryHandle,
            _Inout_ volatile LONG* PendingWorkerCount
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwSignalAndWaitForSingleObject(
            _In_ HANDLE SignalHandle,
            _In_ HANDLE WaitHandle,
            _In_ BOOLEAN Alertable,
            _In_opt_ PLARGE_INTEGER Timeout
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwSinglePhaseReject(
            _In_ HANDLE EnlistmentHandle,
            _In_opt_ PLARGE_INTEGER TmVirtualClock
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwStartProfile(
            _In_ HANDLE ProfileHandle
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwStopProfile(
            _In_ HANDLE ProfileHandle
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwSubscribeWnfStateChange(
            _In_ PCWNF_STATE_NAME StateName,
            _In_opt_ WNF_CHANGE_STAMP ChangeStamp,
            _In_ ULONG EventMask,
            _Out_opt_ PULONG64 SubscriptionId
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwSuspendProcess(
            _In_ HANDLE ProcessHandle
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwSuspendThread(
            _In_ HANDLE ThreadHandle,
            _Out_opt_ PULONG PreviousSuspendCount
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwSystemDebugControl(
            _In_ SYSDBG_COMMAND Command,
            _Inout_updates_bytes_opt_(InputBufferLength) PVOID InputBuffer,
            _In_ ULONG InputBufferLength,
            _Out_writes_bytes_opt_(OutputBufferLength) PVOID OutputBuffer,
            _In_ ULONG OutputBufferLength,
            _Out_opt_ PULONG ReturnLength
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwTerminateEnclave(
            _In_ PVOID BaseAddress,
            _In_ ULONG Flags // TERMINATE_ENCLAVE_FLAG_*
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwTerminateJobObject(
            _In_ HANDLE JobHandle,
            _In_ NTSTATUS ExitStatus
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwTerminateProcess(
            _In_opt_ HANDLE ProcessHandle,
            _In_ NTSTATUS ExitStatus
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwTerminateThread(
            _In_opt_ HANDLE ThreadHandle,
            _In_ NTSTATUS ExitStatus
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwTestAlert(
            VOID
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwThawRegistry(
            VOID
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwThawTransactions(
            VOID
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwTraceControl(
            _In_ ETWTRACECONTROLCODE TraceControlCode,
            _In_reads_bytes_opt_(InputBufferLength) PVOID InputBuffer,
            _In_ ULONG InputBufferLength,
            _Out_writes_bytes_opt_(OutputBufferLength) PVOID OutputBuffer,
            _In_ ULONG OutputBufferLength,
            _Out_ PULONG ReturnLength
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwTraceEvent(
            _In_ HANDLE TraceHandle,
            _In_ ULONG Flags,
            _In_ ULONG FieldSize,
            _In_ PVOID Fields
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwTranslateFilePath(
            _In_ PFILE_PATH InputFilePath,
            _In_ ULONG OutputType,
            _Out_writes_bytes_opt_(*OutputFilePathLength) PFILE_PATH OutputFilePath,
            _Inout_opt_ PULONG OutputFilePathLength
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwUmsThreadYield(
            _In_ PVOID SchedulerParam
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwUnloadDriver(
            _In_ PUNICODE_STRING DriverServiceName
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwUnloadKey(
            _In_ POBJECT_ATTRIBUTES TargetKey
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwUnloadKey2(
            _In_ POBJECT_ATTRIBUTES TargetKey,
            _In_ ULONG Flags
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwUnloadKeyEx(
            _In_ POBJECT_ATTRIBUTES TargetKey,
            _In_opt_ HANDLE Event
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwUnlockFile(
            _In_ HANDLE FileHandle,
            _Out_ PIO_STATUS_BLOCK IoStatusBlock,
            _In_ PLARGE_INTEGER ByteOffset,
            _In_ PLARGE_INTEGER Length,
            _In_ ULONG Key
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwUnlockVirtualMemory(
            _In_ HANDLE ProcessHandle,
            _Inout_ PVOID* BaseAddress,
            _Inout_ PSIZE_T RegionSize,
            _In_ ULONG MapType
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwUnmapViewOfSection(
            _In_ HANDLE ProcessHandle,
            _In_opt_ PVOID BaseAddress
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwUnmapViewOfSectionEx(
            _In_ HANDLE ProcessHandle,
            _In_opt_ PVOID BaseAddress,
            _In_ ULONG Flags
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwUnsubscribeWnfStateChange(
            _In_ PCWNF_STATE_NAME StateName
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwUpdateWnfStateData(
            _In_ PCWNF_STATE_NAME StateName,
            _In_reads_bytes_opt_(Length) const VOID* Buffer,
            _In_opt_ ULONG Length,
            _In_opt_ PCWNF_TYPE_ID TypeId,
            _In_opt_ const VOID* ExplicitScope,
            _In_ WNF_CHANGE_STAMP MatchingChangeStamp,
            _In_ LOGICAL CheckStamp
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwVdmControl(
            _In_ VDMSERVICECLASS Service,
            _Inout_ PVOID ServiceData
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwWaitForAlertByThreadId(
            _In_ PVOID Address,
            _In_opt_ PLARGE_INTEGER Timeout
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwWaitForDebugEvent(
            _In_ HANDLE DebugObjectHandle,
            _In_ BOOLEAN Alertable,
            _In_opt_ PLARGE_INTEGER Timeout,
            _Out_ PDBGUI_WAIT_STATE_CHANGE WaitStateChange
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwWaitForKeyedEvent(
            _In_opt_ HANDLE KeyedEventHandle,
            _In_ PVOID KeyValue,
            _In_ BOOLEAN Alertable,
            _In_opt_ PLARGE_INTEGER Timeout
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwWaitForMultipleObjects(
            _In_ ULONG Count,
            _In_reads_(Count) HANDLE Handles[],
            _In_ WAIT_TYPE WaitType,
            _In_ BOOLEAN Alertable,
            _In_opt_ PLARGE_INTEGER Timeout
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwWaitForMultipleObjects32(
            _In_ ULONG Count,
            _In_reads_(Count) LONG Handles[],
            _In_ WAIT_TYPE WaitType,
            _In_ BOOLEAN Alertable,
            _In_opt_ PLARGE_INTEGER Timeout
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwWaitForSingleObject(
            _In_ HANDLE Handle,
            _In_ BOOLEAN Alertable,
            _In_opt_ PLARGE_INTEGER Timeout
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwWaitForWorkViaWorkerFactory(
            _In_ HANDLE WorkerFactoryHandle,
            _Out_writes_to_(Count, *PacketsReturned) PFILE_IO_COMPLETION_INFORMATION MiniPackets,
            _In_ ULONG Count,
            _Out_ PULONG PacketsReturned,
            _In_ PWORKER_FACTORY_DEFERRED_WORK DeferredWork
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwWaitHighEventPair(
            _In_ HANDLE EventPairHandle
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwWaitLowEventPair(
            _In_ HANDLE EventPairHandle
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwWorkerFactoryWorkerReady(
            _In_ HANDLE WorkerFactoryHandle
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwWriteFile(
            _In_ HANDLE FileHandle,
            _In_opt_ HANDLE Event,
            _In_opt_ PIO_APC_ROUTINE ApcRoutine,
            _In_opt_ PVOID ApcContext,
            _Out_ PIO_STATUS_BLOCK IoStatusBlock,
            _In_reads_bytes_(Length) PVOID Buffer,
            _In_ ULONG Length,
            _In_opt_ PLARGE_INTEGER ByteOffset,
            _In_opt_ PULONG Key
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwWriteFileGather(
            _In_ HANDLE FileHandle,
            _In_opt_ HANDLE Event,
            _In_opt_ PIO_APC_ROUTINE ApcRoutine,
            _In_opt_ PVOID ApcContext,
            _Out_ PIO_STATUS_BLOCK IoStatusBlock,
            _In_ PFILE_SEGMENT_ELEMENT SegmentArray,
            _In_ ULONG Length,
            _In_opt_ PLARGE_INTEGER ByteOffset,
            _In_opt_ PULONG Key
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwWriteRequestData(
            _In_ HANDLE PortHandle,
            _In_ PPORT_MESSAGE Message,
            _In_ ULONG DataEntryIndex,
            _In_reads_bytes_(BufferSize) PVOID Buffer,
            _In_ SIZE_T BufferSize,
            _Out_opt_ PSIZE_T NumberOfBytesWritten
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwWriteVirtualMemory(
            _In_ HANDLE ProcessHandle,
            _In_opt_ PVOID BaseAddress,
            _In_reads_bytes_(BufferSize) PVOID Buffer,
            _In_ SIZE_T BufferSize,
            _Out_opt_ PSIZE_T NumberOfBytesWritten
        );

    NTSYSCALLAPI
        NTSTATUS
        NTAPI
        ZwYieldExecution(
            VOID
        );

#endif

#endif

#ifdef __cplusplus
}
#endif

#endif

#endif // _PHNT_AMALGAMATE_H
