From 53fbbdc5b5d2b08761db1c7b26bfa8c820924356 Mon Sep 17 00:00:00 2001 From: Johnny Shaw Date: Wed, 25 Mar 2026 18:14:46 -0600 Subject: [PATCH] sync latest --- ntafd.h | 1169 ++++++++++++ ntbcd.h | 1054 ++++++++--- ntd3dkmt.h | 107 ++ ntdbg.h | 254 ++- ntexapi.h | 4911 +++++++++++++++++++++++++++++++++++++----------- ntgdi.h | 6 +- ntimage.h | 122 +- ntintsafe.h | 5 +- ntioapi.h | 949 +++++++--- ntkeapi.h | 37 +- ntldr.h | 1130 +++++++---- ntlpcapi.h | 74 +- ntmisc.h | 601 +++++- ntmmapi.h | 1151 ++++++++---- ntnls.h | 50 +- ntobapi.h | 302 ++- ntpebteb.h | 541 ++++-- ntpfapi.h | 480 +++-- ntpnpapi.h | 22 +- ntpoapi.h | 1447 +++++++++++--- ntpsapi.h | 2096 +++++++++++++-------- ntregapi.h | 667 ++++--- ntrtl.h | 3823 ++++++++++++++++++++++++++----------- ntsam.h | 552 ++++-- ntseapi.h | 949 +++++++--- ntsmss.h | 10 +- ntstrsafe.h | 1 + ntsxs.h | 74 +- nttmapi.h | 94 +- nttp.h | 411 +++- nttypesafe.h | 566 ++++++ ntuser.h | 2330 ++++++++++++++++++++--- ntwmi.h | 535 ++++-- ntwow64.h | 64 +- ntxcapi.h | 20 +- ntzwapi.h | 277 +-- phnt.h | 19 +- phnt_ntdef.h | 757 +++++++- phnt_windows.h | 13 +- smbios.h | 2 +- usermgr.h | 44 +- winsta.h | 506 +++-- 42 files changed, 21779 insertions(+), 6443 deletions(-) create mode 100644 ntafd.h create mode 100644 ntd3dkmt.h create mode 100644 nttypesafe.h diff --git a/ntafd.h b/ntafd.h new file mode 100644 index 0000000..7f21421 --- /dev/null +++ b/ntafd.h @@ -0,0 +1,1169 @@ +/* + * Ancillary Function Driver definitions + * + * This file is part of System Informer. + */ + +#ifndef _NTAFD_H +#define _NTAFD_H + +#include +#include +#include + +// private +#define AFD_DEVICE_NAME L"\\Device\\Afd" + +// private // Extended Attributes +#define AfdOpenPacket "AfdOpenPacketXX" // AFD_OPEN_PACKET +#define AfdSwOpenPacket "AfdSwOpenPacket" // AFD_SWITCH_OPEN_PACKET // rev +#define AfdRioRDOpenPacket "AfdRioRDOpenPacket" // void // rev + +// private +typedef struct _AFD_ENDPOINT_FLAGS +{ + union + { + struct + { + UCHAR ConnectionLess : 1; + UCHAR : 3; + UCHAR MessageMode : 1; + UCHAR : 3; + UCHAR Raw : 1; + UCHAR : 3; + UCHAR Multipoint : 1; + UCHAR : 3; + UCHAR C_Root : 1; + UCHAR : 3; + UCHAR D_Root : 1; + UCHAR : 3; + UCHAR IgnoreTDI : 1; + UCHAR : 3; + UCHAR RioSocket : 1; + UCHAR : 3; + }; + ULONG EndpointFlags; + }; +} AFD_ENDPOINT_FLAGS, *PAFD_ENDPOINT_FLAGS; + +// private // Transport device names +#define DD_TCP_DEVICE_NAME L"\\Device\\Tcp" +#define DD_TCPV6_DEVICE_NAME L"\\Device\\Tcp6" +#define DD_UDP_DEVICE_NAME L"\\Device\\Udp" +#define DD_UDPV6_DEVICE_NAME L"\\Device\\Udp6" +#define DD_RAW_IP_DEVICE_NAME L"\\Device\\RawIp" +#define DD_RAW_IPV6_DEVICE_NAME L"\\Device\\RawIp6" + +// private +typedef struct _AFD_OPEN_PACKET +{ + _In_ AFD_ENDPOINT_FLAGS __f; + _In_opt_ GROUP GroupID; + _In_ LONG AddressFamily; // AF_* + _In_ LONG SocketType; // SOCK_* + _In_ LONG Protocol; // IPPROTO_*, BTHPROTO_*, HV_PROTOCOL_*, etc. + _In_opt_ ULONG TransportDeviceNameLength; // Note: specifying a device changes the transport mode + _Field_size_bytes_opt_(TransportDeviceNameLength) WCHAR TransportDeviceName[ANYSIZE_ARRAY]; +} AFD_OPEN_PACKET, *PAFD_OPEN_PACKET; + +// rev (FILE_FULL_EA_INFORMATION + AfdOpenPacket + AFD_OPEN_PACKET) +_Struct_size_bytes_(NextEntryOffset) +typedef struct _AFD_OPEN_PACKET_FULL_EA +{ + ULONG NextEntryOffset; + UCHAR Flags; + UCHAR EaNameLength; // sizeof(AfdOpenPacket) - sizeof(ANSI_NULL); + USHORT EaValueLength; // sizeof(AFD_OPEN_PACKET) + CHAR EaName[sizeof(AfdOpenPacket)]; + AFD_OPEN_PACKET OpenPacket; +} AFD_OPEN_PACKET_FULL_EA, *PAFD_OPEN_PACKET_FULL_EA; + +// private +typedef struct _AFD_SWITCH_OPEN_PACKET +{ + HANDLE CompletionPort; + HANDLE CompletionEvent; +} AFD_SWITCH_OPEN_PACKET, *PAFD_SWITCH_OPEN_PACKET; + +// +// Since Vista, sockets can use different modes of transport: TLI, TDI, and hybrid. The mode is selected +// based on whether the caller specifies the transport device at socket creation and whether this device +// is suitable for hybrid operation. No device means TLI, which is the most common choice. +// +// The transport mode affects which structures AFD uses for IOCTLs on the socket: +// - TLI sockets use *_TL structures (where applicable) and SOCKADDR for addresses. +// - TDI and hybrid sockets use non-TL structures and TDI_ADDRESS_INFO for addresses. +// + +// private // IOCTL function numbers +#define AFD_BIND 0 // in: AFD_BIND_INFO_TL; out: SOCKADDR /or/ in: AFD_BIND_INFO; out: TDI_ADDRESS_INFO (depending on transport mode) +#define AFD_CONNECT 1 // in: AFD_CONNECT_JOIN_INFO_TL or AFD_CONNECT_JOIN_INFO (depending on transport mode); out (opt): IO_STATUS_BLOCK +#define AFD_START_LISTEN 2 // in: AFD_LISTEN_INFO +#define AFD_WAIT_FOR_LISTEN 3 // out: AFD_LISTEN_RESPONSE_INFO_TL or AFD_LISTEN_RESPONSE_INFO (depending on transport mode) +#define AFD_ACCEPT 4 // in: AFD_ACCEPT_INFO +#define AFD_RECEIVE 5 // in: AFD_RECV_INFO +#define AFD_RECEIVE_DATAGRAM 6 // in: AFD_DATAGRAM_INFO +#define AFD_SEND 7 // in: AFD_SEND_INFO +#define AFD_SEND_DATAGRAM 8 // in: AFD_SEND_DATAGRAM_INFO +#define AFD_POLL 9 // in, out: AFD_POLL_INFO +#define AFD_PARTIAL_DISCONNECT 10 // in: AFD_PARTIAL_DISCONNECT_INFO +#define AFD_GET_ADDRESS 11 // out: AFD_ADDRESS (SOCKADDR or TDI_ADDRESS_INFO, depending on transport mode) +#define AFD_QUERY_RECEIVE_INFO 12 // out: AFD_RECEIVE_INFORMATION +#define AFD_QUERY_HANDLES 13 // in: ULONG (AFD_QUERY_*); out: AFD_HANDLE_INFO +#define AFD_SET_INFORMATION 14 // in: AFD_INFORMATION +#define AFD_GET_REMOTE_ADDRESS 15 // out: AFD_ADDRESS (SOCKADDR or TDI_ADDRESS_INFO, depending on transport mode) +#define AFD_GET_CONTEXT 16 // out: SOCK_SHARED_INFO (on Win32 level) or custom data +#define AFD_SET_CONTEXT 17 // in: SOCK_SHARED_INFO (on Win32 level) or custom data; out: AFD_ADDRESS (SOCKADDR or TDI_ADDRESS_INFO, depending on transport mode; output buffer must be inside the input buffer) +#define AFD_SET_CONNECT_DATA 18 // in: AFD_UNACCEPTED_CONNECT_DATA_INFO; out: payload +#define AFD_SET_CONNECT_OPTIONS 19 // in: AFD_UNACCEPTED_CONNECT_DATA_INFO; out: payload +#define AFD_SET_DISCONNECT_DATA 20 // in: AFD_UNACCEPTED_CONNECT_DATA_INFO; out: payload +#define AFD_SET_DISCONNECT_OPTIONS 21 // in: AFD_UNACCEPTED_CONNECT_DATA_INFO; out: payload +#define AFD_GET_CONNECT_DATA 22 // in: AFD_UNACCEPTED_CONNECT_DATA_INFO; out: payload +#define AFD_GET_CONNECT_OPTIONS 23 // in: AFD_UNACCEPTED_CONNECT_DATA_INFO; out: payload +#define AFD_GET_DISCONNECT_DATA 24 // in: AFD_UNACCEPTED_CONNECT_DATA_INFO; out: payload +#define AFD_GET_DISCONNECT_OPTIONS 25 // in: AFD_UNACCEPTED_CONNECT_DATA_INFO; out: payload +#define AFD_SIZE_CONNECT_DATA 26 // in: AFD_UNACCEPTED_CONNECT_DATA_INFO; out: payload +#define AFD_SIZE_CONNECT_OPTIONS 27 // in: AFD_UNACCEPTED_CONNECT_DATA_INFO; out: payload +#define AFD_SIZE_DISCONNECT_DATA 28 // in: AFD_UNACCEPTED_CONNECT_DATA_INFO; out: payload +#define AFD_SIZE_DISCONNECT_OPTIONS 29 // in: AFD_UNACCEPTED_CONNECT_DATA_INFO; out: payload +#define AFD_GET_INFORMATION 30 // in, out: AFD_INFORMATION +#define AFD_TRANSMIT_FILE 31 // in: AFD_TRANSMIT_FILE_INFO; out (opt): BOOLEAN +#define AFD_SUPER_ACCEPT 32 // in: AFD_SUPER_ACCEPT_INFO; out: received data + local address + remote address (at offsets according to the input) +#define AFD_EVENT_SELECT 33 // in: AFD_EVENT_SELECT_INFO +#define AFD_ENUM_NETWORK_EVENTS 34 // in (opt): HANDLE; out: AFD_ENUM_NETWORK_EVENTS_INFO +#define AFD_DEFER_ACCEPT 35 // in: AFD_DEFER_ACCEPT_INFO +#define AFD_WAIT_FOR_LISTEN_LIFO 36 // out: AFD_LISTEN_RESPONSE_INFO_TL or AFD_LISTEN_RESPONSE_INFO (depending on transport mode) +#define AFD_SET_QOS 37 // in: AFD_QOS_INFO +#define AFD_GET_QOS 38 // out: AFD_QOS_INFO +#define AFD_NO_OPERATION 39 // in (opt): IO_STATUS_BLOCK +#define AFD_VALIDATE_GROUP 40 // in: AFD_VALIDATE_GROUP_INFO +#define AFD_GET_UNACCEPTED_CONNECT_DATA 41 // in: AFD_UNACCEPTED_CONNECT_DATA_INFO; out: AFD_UNACCEPTED_CONNECT_DATA_INFO (when LengthOnly is set) or received data +#define AFD_ROUTING_INTERFACE_QUERY 42 // in: TRANSPORT_ADDRESS; out: SOCKADDR +#define AFD_ROUTING_INTERFACE_CHANGE 43 // in: AFD_TRANSPORT_IOCTL_INFO +#define AFD_ADDRESS_LIST_QUERY 44 // in: USHORT (TDI_ADDRESS_TYPE_*/AF_*); out: TRANSPORT_ADDRESS +#define AFD_ADDRESS_LIST_CHANGE 45 // in: AFD_TRANSPORT_IOCTL_INFO +#define AFD_JOIN_LEAF 46 // in: AFD_CONNECT_JOIN_INFO_TL or AFD_CONNECT_JOIN_INFO (depending on transport mode); out (opt): IO_STATUS_BLOCK +#define AFD_TRANSPORT_IOCTL 47 // in: AFD_TL_IO_CONTROL_INFO; out: variable +#define AFD_TRANSMIT_PACKETS 48 // in: AFD_TPACKETS_INFO; out (opt): BOOLEAN +#define AFD_SUPER_CONNECT 49 // in: AFD_SUPER_CONNECT_INFO_TL or AFD_SUPER_CONNECT_INFO (depending on transport mode); out: payload +#define AFD_SUPER_DISCONNECT 50 // in: AFD_SUPER_DISCONNECT_INFO +#define AFD_RECEIVE_MESSAGE 51 // in: AFD_MESSAGE_INFO +#define AFD_SEND_MESSAGE 52 // in: AFD_MESSAGE_INFO // rev // since VISTA // breaks layout; values below are different on XP +#define AFD_SWITCH_CEMENT_SAN 53 // in: AFD_SWITCH_CONTEXT_INFO +#define AFD_SWITCH_SET_EVENTS 54 // in: AFD_SWITCH_EVENT_INFO +#define AFD_SWITCH_RESET_EVENTS 55 // in: AFD_SWITCH_EVENT_INFO +#define AFD_SWITCH_CONNECT_IND 56 // in: AFD_SWITCH_CONNECT_INFO; out: AFD_SWITCH_ACCEPT_INFO +#define AFD_SWITCH_CMPL_ACCEPT 57 // in: AFD_SWITCH_CONTEXT_INFO; out: payload +#define AFD_SWITCH_CMPL_REQUEST 58 // in: AFD_SWITCH_REQUEST_INFO; out: payload +#define AFD_SWITCH_CMPL_IO 59 // in: IO_STATUS_BLOCK +#define AFD_SWITCH_REFRESH_ENDP 60 // in: AFD_SWITCH_CONTEXT_INFO +#define AFD_SWITCH_GET_PHYSICAL_ADDR 61 // deprecated +#define AFD_SWITCH_ACQUIRE_CTX 62 // in: AFD_SWITCH_ACQUIRE_CTX_INFO; out: payload +#define AFD_SWITCH_TRANSFER_CTX 63 // in: AFD_SWITCH_TRANSFER_CTX_INFO +#define AFD_SWITCH_GET_SERVICE_PID 64 // in/out: void; returns PID in IO_STATUS_BLOCK.Information +#define AFD_SWITCH_SET_SERVICE_PROCESS 65 // in/out: void +#define AFD_SWITCH_PROVIDER_CHANGE 66 // in/out: void +#define AFD_SWITCH_ADDRLIST_CHANGE 67 // in: AFD_TRANSPORT_IOCTL_INFO +#define AFD_UNBIND 68 // in: AFD_UNBIND_INFO // rev // since VISTA +#define AFD_SQM 69 // in: AFD_SQM_INFO // rev // since WIN7 +#define AFD_RIO 70 // in/out: AFD_RIO_COMMAND_HEADER // rev // since WIN8 +#define AFD_TRANSFER_BEGIN 71 // in/out: void // rev // since TH1 +#define AFD_TRANSFER_END 72 // in/out: void // rev // since TH1 +#define AFD_NOTIFY 73 // rev // since 22H2 + +// private // Note: different bit layout from CTL_CODE +#define FSCTL_AFD_BASE FILE_DEVICE_NETWORK +#define _AFD_CONTROL_CODE(Request, Method) (FSCTL_AFD_BASE << 12 | (Request) << 2 | (Method)) + +// private // IOCTLs +#define IOCTL_AFD_BIND _AFD_CONTROL_CODE(AFD_BIND, METHOD_NEITHER) // 0x12003 +#define IOCTL_AFD_CONNECT _AFD_CONTROL_CODE(AFD_CONNECT, METHOD_NEITHER) // 0x12007 +#define IOCTL_AFD_START_LISTEN _AFD_CONTROL_CODE(AFD_START_LISTEN, METHOD_NEITHER) // 0x1200B +#define IOCTL_AFD_WAIT_FOR_LISTEN _AFD_CONTROL_CODE(AFD_WAIT_FOR_LISTEN, METHOD_BUFFERED) // 0x1200C +#define IOCTL_AFD_ACCEPT _AFD_CONTROL_CODE(AFD_ACCEPT, METHOD_BUFFERED) // 0x12010 +#define IOCTL_AFD_RECEIVE _AFD_CONTROL_CODE(AFD_RECEIVE, METHOD_NEITHER) // 0x12017 +#define IOCTL_AFD_RECEIVE_DATAGRAM _AFD_CONTROL_CODE(AFD_RECEIVE_DATAGRAM, METHOD_NEITHER) // 0x1201B +#define IOCTL_AFD_SEND _AFD_CONTROL_CODE(AFD_SEND, METHOD_NEITHER) // 0x1201F +#define IOCTL_AFD_SEND_DATAGRAM _AFD_CONTROL_CODE(AFD_SEND_DATAGRAM, METHOD_NEITHER) // 0x12023 +#define IOCTL_AFD_POLL _AFD_CONTROL_CODE(AFD_POLL, METHOD_BUFFERED) // 0x12024 +#define IOCTL_AFD_PARTIAL_DISCONNECT _AFD_CONTROL_CODE(AFD_PARTIAL_DISCONNECT, METHOD_NEITHER) // 0x1202B +#define IOCTL_AFD_GET_ADDRESS _AFD_CONTROL_CODE(AFD_GET_ADDRESS, METHOD_NEITHER) // 0x1202F +#define IOCTL_AFD_QUERY_RECEIVE_INFO _AFD_CONTROL_CODE(AFD_QUERY_RECEIVE_INFO, METHOD_NEITHER) // 0x12033 +#define IOCTL_AFD_QUERY_HANDLES _AFD_CONTROL_CODE(AFD_QUERY_HANDLES, METHOD_NEITHER) // 0x12037 +#define IOCTL_AFD_SET_INFORMATION _AFD_CONTROL_CODE(AFD_SET_INFORMATION, METHOD_NEITHER) // 0x1203B +#define IOCTL_AFD_GET_REMOTE_ADDRESS _AFD_CONTROL_CODE(AFD_GET_REMOTE_ADDRESS, METHOD_NEITHER) // 0x1203F +#define IOCTL_AFD_GET_CONTEXT _AFD_CONTROL_CODE(AFD_GET_CONTEXT, METHOD_NEITHER) // 0x12043 +#define IOCTL_AFD_SET_CONTEXT _AFD_CONTROL_CODE(AFD_SET_CONTEXT, METHOD_NEITHER) // 0x12047 +#define IOCTL_AFD_SET_CONNECT_DATA _AFD_CONTROL_CODE(AFD_SET_CONNECT_DATA, METHOD_NEITHER) // 0x1204B +#define IOCTL_AFD_SET_CONNECT_OPTIONS _AFD_CONTROL_CODE(AFD_SET_CONNECT_OPTIONS, METHOD_NEITHER) // 0x1204F +#define IOCTL_AFD_SET_DISCONNECT_DATA _AFD_CONTROL_CODE(AFD_SET_DISCONNECT_DATA, METHOD_NEITHER) // 0x12053 +#define IOCTL_AFD_SET_DISCONNECT_OPTIONS _AFD_CONTROL_CODE(AFD_SET_DISCONNECT_OPTIONS, METHOD_NEITHER) // 0x12057 +#define IOCTL_AFD_GET_CONNECT_DATA _AFD_CONTROL_CODE(AFD_GET_CONNECT_DATA, METHOD_NEITHER) // 0x1205B +#define IOCTL_AFD_GET_CONNECT_OPTIONS _AFD_CONTROL_CODE(AFD_GET_CONNECT_OPTIONS, METHOD_NEITHER) // 0x1205F +#define IOCTL_AFD_GET_DISCONNECT_DATA _AFD_CONTROL_CODE(AFD_GET_DISCONNECT_DATA, METHOD_NEITHER) // 0x12063 +#define IOCTL_AFD_GET_DISCONNECT_OPTIONS _AFD_CONTROL_CODE(AFD_GET_DISCONNECT_OPTIONS, METHOD_NEITHER) // 0x12067 +#define IOCTL_AFD_SIZE_CONNECT_DATA _AFD_CONTROL_CODE(AFD_SIZE_CONNECT_DATA, METHOD_NEITHER) // 0x1206B +#define IOCTL_AFD_SIZE_CONNECT_OPTIONS _AFD_CONTROL_CODE(AFD_SIZE_CONNECT_OPTIONS, METHOD_NEITHER) // 0x1206F +#define IOCTL_AFD_SIZE_DISCONNECT_DATA _AFD_CONTROL_CODE(AFD_SIZE_DISCONNECT_DATA, METHOD_NEITHER) // 0x12073 +#define IOCTL_AFD_SIZE_DISCONNECT_OPTIONS _AFD_CONTROL_CODE(AFD_SIZE_DISCONNECT_OPTIONS, METHOD_NEITHER) // 0x12077 +#define IOCTL_AFD_GET_INFORMATION _AFD_CONTROL_CODE(AFD_GET_INFORMATION, METHOD_NEITHER) // 0x1207B +#define IOCTL_AFD_TRANSMIT_FILE _AFD_CONTROL_CODE(AFD_TRANSMIT_FILE, METHOD_NEITHER) // 0x1207F +#define IOCTL_AFD_SUPER_ACCEPT _AFD_CONTROL_CODE(AFD_SUPER_ACCEPT, METHOD_NEITHER) // 0x12083 +#define IOCTL_AFD_EVENT_SELECT _AFD_CONTROL_CODE(AFD_EVENT_SELECT, METHOD_NEITHER) // 0x12087 +#define IOCTL_AFD_ENUM_NETWORK_EVENTS _AFD_CONTROL_CODE(AFD_ENUM_NETWORK_EVENTS, METHOD_NEITHER) // 0x1208B +#define IOCTL_AFD_DEFER_ACCEPT _AFD_CONTROL_CODE(AFD_DEFER_ACCEPT, METHOD_BUFFERED) // 0x1208C +#define IOCTL_AFD_WAIT_FOR_LISTEN_LIFO _AFD_CONTROL_CODE(AFD_WAIT_FOR_LISTEN_LIFO, METHOD_BUFFERED) // 0x12090 +#define IOCTL_AFD_SET_QOS _AFD_CONTROL_CODE(AFD_SET_QOS, METHOD_BUFFERED) // 0x12094 +#define IOCTL_AFD_GET_QOS _AFD_CONTROL_CODE(AFD_GET_QOS, METHOD_BUFFERED) // 0x12098 +#define IOCTL_AFD_NO_OPERATION _AFD_CONTROL_CODE(AFD_NO_OPERATION, METHOD_NEITHER) // 0x1209F +#define IOCTL_AFD_VALIDATE_GROUP _AFD_CONTROL_CODE(AFD_VALIDATE_GROUP, METHOD_BUFFERED) // 0x120A0 +#define IOCTL_AFD_GET_UNACCEPTED_CONNECT_DATA _AFD_CONTROL_CODE(AFD_GET_UNACCEPTED_CONNECT_DATA, METHOD_NEITHER) // 0x120A7 +#define IOCTL_AFD_ROUTING_INTERFACE_QUERY _AFD_CONTROL_CODE(AFD_ROUTING_INTERFACE_QUERY, METHOD_NEITHER) // 0x120AB +#define IOCTL_AFD_ROUTING_INTERFACE_CHANGE _AFD_CONTROL_CODE(AFD_ROUTING_INTERFACE_CHANGE, METHOD_BUFFERED) // 0x120AC +#define IOCTL_AFD_ADDRESS_LIST_QUERY _AFD_CONTROL_CODE(AFD_ADDRESS_LIST_QUERY, METHOD_NEITHER) // 0x120B3 +#define IOCTL_AFD_ADDRESS_LIST_CHANGE _AFD_CONTROL_CODE(AFD_ADDRESS_LIST_CHANGE, METHOD_BUFFERED) // 0x120B4 +#define IOCTL_AFD_JOIN_LEAF _AFD_CONTROL_CODE(AFD_JOIN_LEAF, METHOD_NEITHER) // 0x120BB +#define IOCTL_AFD_TRANSPORT_IOCTL _AFD_CONTROL_CODE(AFD_TRANSPORT_IOCTL, METHOD_NEITHER) // 0x120BF +#define IOCTL_AFD_TRANSMIT_PACKETS _AFD_CONTROL_CODE(AFD_TRANSMIT_PACKETS, METHOD_NEITHER) // 0x120C3 +#define IOCTL_AFD_SUPER_CONNECT _AFD_CONTROL_CODE(AFD_SUPER_CONNECT, METHOD_NEITHER) // 0x120C7 +#define IOCTL_AFD_SUPER_DISCONNECT _AFD_CONTROL_CODE(AFD_SUPER_DISCONNECT, METHOD_NEITHER) // 0x120CB +#define IOCTL_AFD_RECEIVE_MESSAGE _AFD_CONTROL_CODE(AFD_RECEIVE_MESSAGE, METHOD_NEITHER) // 0x120CF +#define IOCTL_AFD_SEND_MESSAGE _AFD_CONTROL_CODE(AFD_SEND_MESSAGE, METHOD_NEITHER) // 0x120D3 // rev // since VISTA +#define IOCTL_AFD_SWITCH_CEMENT_SAN _AFD_CONTROL_CODE(AFD_SWITCH_CEMENT_SAN, METHOD_NEITHER) // 0x120D7 +#define IOCTL_AFD_SWITCH_SET_EVENTS _AFD_CONTROL_CODE(AFD_SWITCH_SET_EVENTS, METHOD_NEITHER) // 0x120DB +#define IOCTL_AFD_SWITCH_RESET_EVENTS _AFD_CONTROL_CODE(AFD_SWITCH_RESET_EVENTS, METHOD_NEITHER) // 0x120DF +#define IOCTL_AFD_SWITCH_CONNECT_IND _AFD_CONTROL_CODE(AFD_SWITCH_CONNECT_IND, METHOD_OUT_DIRECT) // 0x120E2 +#define IOCTL_AFD_SWITCH_CMPL_ACCEPT _AFD_CONTROL_CODE(AFD_SWITCH_CMPL_ACCEPT, METHOD_NEITHER) // 0x120E7 +#define IOCTL_AFD_SWITCH_CMPL_REQUEST _AFD_CONTROL_CODE(AFD_SWITCH_CMPL_REQUEST, METHOD_NEITHER) // 0x120EB +#define IOCTL_AFD_SWITCH_CMPL_IO _AFD_CONTROL_CODE(AFD_SWITCH_CMPL_IO, METHOD_NEITHER) // 0x120EF +#define IOCTL_AFD_SWITCH_REFRESH_ENDP _AFD_CONTROL_CODE(AFD_SWITCH_REFRESH_ENDP, METHOD_NEITHER) // 0x120F3 +#define IOCTL_AFD_SWITCH_GET_PHYSICAL_ADDR _AFD_CONTROL_CODE(AFD_SWITCH_GET_PHYSICAL_ADDR, METHOD_NEITHER) // 0x120F7 +#define IOCTL_AFD_SWITCH_ACQUIRE_CTX _AFD_CONTROL_CODE(AFD_SWITCH_ACQUIRE_CTX, METHOD_NEITHER) // 0x120FB +#define IOCTL_AFD_SWITCH_TRANSFER_CTX _AFD_CONTROL_CODE(AFD_SWITCH_TRANSFER_CTX, METHOD_NEITHER) // 0x120FF +#define IOCTL_AFD_SWITCH_GET_SERVICE_PID _AFD_CONTROL_CODE(AFD_SWITCH_GET_SERVICE_PID, METHOD_NEITHER) // 0x12103 +#define IOCTL_AFD_SWITCH_SET_SERVICE_PROCESS _AFD_CONTROL_CODE(AFD_SWITCH_SET_SERVICE_PROCESS, METHOD_NEITHER) // 0x12107 +#define IOCTL_AFD_SWITCH_PROVIDER_CHANGE _AFD_CONTROL_CODE(AFD_SWITCH_PROVIDER_CHANGE, METHOD_NEITHER) // 0x1210B +#define IOCTL_AFD_SWITCH_ADDRLIST_CHANGE _AFD_CONTROL_CODE(AFD_SWITCH_ADDRLIST_CHANGE, METHOD_BUFFERED) // 0x1210C +#define IOCTL_AFD_UNBIND _AFD_CONTROL_CODE(AFD_UNBIND, METHOD_NEITHER) // 0x12113 // rev +#define IOCTL_AFD_SQM _AFD_CONTROL_CODE(AFD_SQM, METHOD_NEITHER) // 0x12117 // rev // since WIN7 +#define IOCTL_AFD_RIO _AFD_CONTROL_CODE(AFD_RIO, METHOD_NEITHER) // 0x1211B // rev // since WIN8 +#define IOCTL_AFD_TRANSFER_BEGIN _AFD_CONTROL_CODE(AFD_TRANSFER_BEGIN, METHOD_NEITHER) // 0x1211F // rev // since TH1 +#define IOCTL_AFD_TRANSFER_END _AFD_CONTROL_CODE(AFD_TRANSFER_END, METHOD_NEITHER) // 0x12123 // rev +#define IOCTL_AFD_NOTIFY _AFD_CONTROL_CODE(AFD_NOTIFY, METHOD_NEITHER) // 0x12127 // rev // since 22H2 + +#include + +// rev - a union for TLI/TDI socket addresses +typedef union _AFD_ADDRESS +{ + SOCKADDR_STORAGE TliAddress; + TDI_ADDRESS_INFO TdiAddress; + + struct + { + // + // TDI_ADDRESS_INFO includes an embedded socket address that starts at AddressType (which corresponds to sa_family). + // + // ---------------- | ------------------------- | + // | ULONG ActivityCount | + // | ------------------------- | --------------------- | + // | | ULONG TAAddressCount | + // | | --------------------- | ---------------------------- | + // | | | USHORT AddressLength | + // TDI_ADDRESS_INFO | TRANSPORT_ADDRESS Address | | ---------------------------- | ---------- | ---------------- | + // | | TA_ADDRESS Address[1] | USHORT AddressType | | USHORT sa_family | + // | | | ---------------------------- | SOCKADDR | ---------------- | + // | | | UCHAR Address[AddressLength] | (embedded) | ... | + // | | | ... | | | + // ---------------- | ------------------------- | --------------------- | ---------------------------- | ---------- | ---------------- | + // + + UCHAR Padding[10]; // RTL_SIZEOF_THROUGH_FIELD(TDI_ADDRESS_INFO, Address.Address[0].AddressLength) + SOCKADDR_STORAGE EmbeddedAddress; + } TdiAddressUnpacked; +} AFD_ADDRESS, *PAFD_ADDRESS; + +#include + +// private // Bind share access +#define AFD_NORMALADDRUSE 0 +#define AFD_REUSEADDRESS 1 +#define AFD_WILDCARDADDRESS 2 +#define AFD_EXCLUSIVEADDRUSE 3 + +// private +typedef struct _AFD_BIND_INFO +{ + ULONG ShareAccess; + TRANSPORT_ADDRESS Address; +} AFD_BIND_INFO, *PAFD_BIND_INFO; + +// private +typedef struct _AFD_BIND_INFO_TL +{ + ULONG ShareAccess; + SOCKADDR Address; +} AFD_BIND_INFO_TL, *PAFD_BIND_INFO_TL; + +// private +typedef struct _AFD_CONNECT_JOIN_INFO +{ + BOOLEAN SanActive; + HANDLE RootEndpoint; + HANDLE ConnectEndpoint; + TRANSPORT_ADDRESS RemoteAddress; +} AFD_CONNECT_JOIN_INFO, *PAFD_CONNECT_JOIN_INFO; + +// private +typedef struct _AFD_CONNECT_JOIN_INFO_TL +{ + BOOLEAN SanActive; + HANDLE RootEndpoint; + HANDLE ConnectEndpoint; + SOCKADDR RemoteAddress; +} AFD_CONNECT_JOIN_INFO_TL, *PAFD_CONNECT_JOIN_INFO_TL; + +// private +typedef struct _AFD_LISTEN_INFO +{ + BOOLEAN SanActive; + ULONG MaximumConnectionQueue; + BOOLEAN UseDelayedAcceptance; +} AFD_LISTEN_INFO, *PAFD_LISTEN_INFO; + +// private +typedef struct _AFD_LISTEN_RESPONSE_INFO +{ + LONG Sequence; + TRANSPORT_ADDRESS RemoteAddress; +} AFD_LISTEN_RESPONSE_INFO, *PAFD_LISTEN_RESPONSE_INFO; + +// private +typedef struct _AFD_LISTEN_RESPONSE_INFO_TL +{ + LONG Sequence; + SOCKADDR RemoteAddress; +} AFD_LISTEN_RESPONSE_INFO_TL, *PAFD_LISTEN_RESPONSE_INFO_TL; + +// private +typedef struct _AFD_ACCEPT_INFO +{ + BOOLEAN SanActive; + LONG Sequence; + HANDLE AcceptHandle; +} AFD_ACCEPT_INFO, *PAFD_ACCEPT_INFO; + +// private // AfdFlags +#define AFD_NO_FAST_IO 0x0001 +#define AFD_OVERLAPPED 0x0002 + +// private +typedef struct _AFD_RECV_INFO +{ + _Field_size_(BufferCount) LPWSABUF BufferArray; + ULONG BufferCount; + ULONG AfdFlags; + ULONG TdiFlags; // TDI_RECEIVE_* +} AFD_RECV_INFO, *PAFD_RECV_INFO; + +// private +typedef struct _AFD_DATAGRAM_INFO +{ + _Field_size_(BufferCount) LPWSABUF BufferArray; + ULONG BufferCount; + ULONG AfdFlags; + ULONG TdiFlags; // TDI_RECEIVE_* + PVOID Address; + PULONG AddressLength; +} AFD_DATAGRAM_INFO, *PAFD_DATAGRAM_INFO; + +// private +typedef struct _AFD_SEND_INFO +{ + _Field_size_(BufferCount) LPWSABUF BufferArray; + ULONG BufferCount; + ULONG AfdFlags; + ULONG TdiFlags; // TDI_RECEIVE_* +} AFD_SEND_INFO, *PAFD_SEND_INFO; + +// private +typedef struct _AFD_SEND_DATAGRAM_INFO +{ + _Field_size_(BufferCount) LPWSABUF BufferArray; + ULONG BufferCount; + ULONG AfdFlags; + TDI_REQUEST_SEND_DATAGRAM TdiRequest; + TDI_CONNECTION_INFORMATION TdiConnInfo; +} AFD_SEND_DATAGRAM_INFO, *PAFD_SEND_DATAGRAM_INFO; + +// private // Poll event bit numbers +#define AFD_POLL_RECEIVE_BIT 0 +#define AFD_POLL_RECEIVE_EXPEDITED_BIT 1 +#define AFD_POLL_SEND_BIT 2 +#define AFD_POLL_DISCONNECT_BIT 3 +#define AFD_POLL_ABORT_BIT 4 +#define AFD_POLL_LOCAL_CLOSE_BIT 5 +#define AFD_POLL_CONNECT_BIT 6 +#define AFD_POLL_ACCEPT_BIT 7 +#define AFD_POLL_CONNECT_FAIL_BIT 8 +#define AFD_POLL_QOS_BIT 9 +#define AFD_POLL_GROUP_QOS_BIT 10 +#define AFD_POLL_ROUTING_IF_CHANGE_BIT 11 +#define AFD_POLL_ADDRESS_LIST_CHANGE_BIT 12 +#define AFD_NUM_POLL_EVENTS 13 + +// private // Poll event flags +#define AFD_POLL_RECEIVE (1 << AFD_POLL_RECEIVE_BIT) // 0x0001 +#define AFD_POLL_RECEIVE_EXPEDITED (1 << AFD_POLL_RECEIVE_EXPEDITED_BIT) // 0x0002 +#define AFD_POLL_SEND (1 << AFD_POLL_SEND_BIT) // 0x0004 +#define AFD_POLL_DISCONNECT (1 << AFD_POLL_DISCONNECT_BIT) // 0x0008 +#define AFD_POLL_ABORT (1 << AFD_POLL_ABORT_BIT) // 0x0010 +#define AFD_POLL_LOCAL_CLOSE (1 << AFD_POLL_LOCAL_CLOSE_BIT) // 0x0020 +#define AFD_POLL_CONNECT (1 << AFD_POLL_CONNECT_BIT) // 0x0040 +#define AFD_POLL_ACCEPT (1 << AFD_POLL_ACCEPT_BIT) // 0x0080 +#define AFD_POLL_CONNECT_FAIL (1 << AFD_POLL_CONNECT_FAIL_BIT) // 0x0100 +#define AFD_POLL_QOS (1 << AFD_POLL_QOS_BIT) // 0x0200 +#define AFD_POLL_GROUP_QOS (1 << AFD_POLL_GROUP_QOS_BIT) // 0x0400 +#define AFD_POLL_ROUTING_IF_CHANGE (1 << AFD_POLL_ROUTING_IF_CHANGE_BIT) // 0x0800 +#define AFD_POLL_ADDRESS_LIST_CHANGE (1 << AFD_POLL_ADDRESS_LIST_CHANGE_BIT) // 0x1000 +#define AFD_POLL_ALL ((1 << AFD_NUM_POLL_EVENTS) - 1) // 0x1FFF +#define AFD_POLL_SANCOUNTS_UPDATED 0x80000000 + +// private +typedef struct _AFD_POLL_HANDLE_INFO +{ + HANDLE Handle; + ULONG PollEvents; // AFD_POLL_* + NTSTATUS Status; +} AFD_POLL_HANDLE_INFO, *PAFD_POLL_HANDLE_INFO; + +// private +typedef struct _AFD_POLL_INFO +{ + LARGE_INTEGER Timeout; + ULONG NumberOfHandles; + BOOLEAN Unique; + _Field_size_(NumberOfHandles) AFD_POLL_HANDLE_INFO Handles[ANYSIZE_ARRAY]; +} AFD_POLL_INFO, *PAFD_POLL_INFO; + +// private // Disconnect flags +#define AFD_PARTIAL_DISCONNECT_SEND 0x01 +#define AFD_PARTIAL_DISCONNECT_RECEIVE 0x02 +#define AFD_ABORTIVE_DISCONNECT 0x04 +#define AFD_UNCONNECT_DATAGRAM 0x08 + +// private +typedef struct _AFD_PARTIAL_DISCONNECT_INFO +{ + ULONG DisconnectMode; + LARGE_INTEGER Timeout; +} AFD_PARTIAL_DISCONNECT_INFO, *PAFD_PARTIAL_DISCONNECT_INFO; + +// private +typedef struct _AFD_RECEIVE_INFORMATION +{ + ULONG BytesAvailable; + ULONG ExpeditedBytesAvailable; +} AFD_RECEIVE_INFORMATION, *PAFD_RECEIVE_INFORMATION; + +// private // Handle query flags +#define AFD_QUERY_ADDRESS_HANDLE 0x01 +#define AFD_QUERY_CONNECTION_HANDLE 0x02 + +// private +typedef struct _AFD_HANDLE_INFO +{ + HANDLE TdiAddressHandle; + HANDLE TdiConnectionHandle; +} AFD_HANDLE_INFO, *PAFD_HANDLE_INFO; + +// private // InformationType +#define AFD_INLINE_MODE 1 // s: BOOLEAN +#define AFD_NONBLOCKING_MODE 2 // s: BOOLEAN +#define AFD_MAX_SEND_SIZE 3 // q: ULONG +#define AFD_SENDS_PENDING 4 // q: ULONG +#define AFD_MAX_PATH_SEND_SIZE 5 // q: ULONG +#define AFD_RECEIVE_WINDOW_SIZE 6 // q; s: ULONG +#define AFD_SEND_WINDOW_SIZE 7 // q; s: ULONG +#define AFD_CONNECT_TIME 8 // q: ULONG (in seconds) +#define AFD_CIRCULAR_QUEUEING 9 // s: BOOLEAN +#define AFD_GROUP_ID_AND_TYPE 10 // q: AFD_GROUP_INFO +#define AFD_REPORT_PORT_UNREACHABLE 11 // s: BOOLEAN +#define AFD_REPORT_NETWORK_UNREACHABLE 12 // s: BOOLEAN // rev +#define AFD_DELIVERY_STATUS 14 // q: SIO_DELIVERY_STATUS // rev +#define AFD_CANCEL_TL 15 // s: void // rev + +// private +typedef enum _AFD_GROUP_TYPE +{ + GroupTypeNeither = 0, + GroupTypeUnconstrained = SG_UNCONSTRAINED_GROUP, + GroupTypeConstrained = SG_CONSTRAINED_GROUP, +} AFD_GROUP_TYPE, *PAFD_GROUP_TYPE; + +// private +typedef struct _AFD_GROUP_INFO +{ + GROUP GroupID; + AFD_GROUP_TYPE GroupType; +} AFD_GROUP_INFO, *PAFD_GROUP_INFO; + +// private +typedef struct _SIO_DELIVERY_STATUS +{ + BOOLEAN DeliveryAvailable; + ULONG PendedReceiveRequests; +} SIO_DELIVERY_STATUS, *PSIO_DELIVERY_STATUS; + +// private +typedef struct _AFD_INFORMATION +{ + ULONG InformationType; + union + { + BOOLEAN Boolean; + ULONG Ulong; + LARGE_INTEGER LargeInteger; + AFD_GROUP_INFO GroupInfo; // rev + SIO_DELIVERY_STATUS DeliveryStatus; // rev + } Information; +} AFD_INFORMATION, *PAFD_INFORMATION; + +// private +typedef enum _SOCKET_STATE +{ + SocketStateInitializing = -1, + SocketStateOpen = 0, + SocketStateBound = 1, + SocketStateBoundSpecific = 2, + SocketStateConnected = 3, + SocketStateClosing = 4, +} SOCKET_STATE, *PSOCKET_STATE; + +// private +typedef struct _SOCK_SHARED_INFO +{ + SOCKET_STATE State; + LONG AddressFamily; // AF_* + LONG SocketType; // SOCK_* + LONG Protocol; // IPPROTO_*, BTHPROTO_*, HV_PROTOCOL_*, etc. + LONG LocalAddressLength; + LONG RemoteAddressLength; + LINGER LingerInfo; + ULONG SendTimeout; // in milliseconds + ULONG ReceiveTimeout; // in milliseconds + ULONG ReceiveBufferSize; + ULONG SendBufferSize; + union + { + USHORT Flags; + struct + { + USHORT Listening : 1; + USHORT Broadcast : 1; + USHORT Debug : 1; + USHORT OobInline : 1; + USHORT ReuseAddresses : 1; + USHORT ExclusiveAddressUse : 1; + USHORT NonBlocking : 1; + USHORT DontUseWildcard : 1; + USHORT ReceiveShutdown : 1; + USHORT SendShutdown : 1; + USHORT ConditionalAccept : 1; + USHORT IsSANSocket : 1; + USHORT fIsTLI : 1; + USHORT Rio : 1; + USHORT ReceiveBufferSizeSet : 1; + USHORT SendBufferSizeSet : 1; + }; + }; + ULONG CreationFlags; // WSA_FLAG_* + ULONG CatalogEntryId; + ULONG ServiceFlags1; // XP1_* + ULONG ProviderFlags; // PFL_* + GROUP GroupID; + AFD_GROUP_TYPE GroupType; + LONG GroupPriority; + LONG LastError; + union + { + HWND AsyncSelecthWnd; + ULONGLONG AsyncSelectWnd64; + }; + ULONG AsyncSelectSerialNumber; + ULONG AsyncSelectwMsg; + LONG AsyncSelectlEvent; + LONG DisabledAsyncSelectEvents; + GUID ProviderId; +} SOCK_SHARED_INFO, *PSOCK_SHARED_INFO; + +// private +typedef struct _AFD_UNACCEPTED_CONNECT_DATA_INFO +{ + LONG Sequence; + ULONG ConnectDataLength; + BOOLEAN LengthOnly; +} AFD_UNACCEPTED_CONNECT_DATA_INFO, *PAFD_UNACCEPTED_CONNECT_DATA_INFO; + +// private // Transmit flags +#define AFD_TF_DISCONNECT 0x01 +#define AFD_TF_REUSE_SOCKET 0x02 +#define AFD_TF_WRITE_BEHIND 0x04 +#define AFD_TF_USE_DEFAULT_WORKER 0x00 +#define AFD_TF_USE_SYSTEM_THREAD 0x10 +#define AFD_TF_USE_KERNEL_APC 0x20 +#define AFD_TF_WORKER_KIND_MASK 0x30 + +// private +typedef struct _AFD_TRANSMIT_FILE_INFO +{ + LARGE_INTEGER Offset; + LARGE_INTEGER WriteLength; + ULONG SendPacketLength; + HANDLE FileHandle; + PVOID Head; + ULONG HeadLength; + PVOID Tail; + ULONG TailLength; + ULONG Flags; // AFD_TF_* +} AFD_TRANSMIT_FILE_INFO, *PAFD_TRANSMIT_FILE_INFO; + +// private +typedef struct _AFD_SUPER_ACCEPT_INFO +{ + BOOLEAN SanActive; + BOOLEAN FixAddressAlignment; + HANDLE AcceptHandle; + ULONG ReceiveDataLength; + ULONG LocalAddressLength; + ULONG RemoteAddressLength; +} AFD_SUPER_ACCEPT_INFO, *PAFD_SUPER_ACCEPT_INFO; + +// private +typedef struct _AFD_EVENT_SELECT_INFO +{ + HANDLE Event; + ULONG PollEvents; // AFD_POLL_* +} AFD_EVENT_SELECT_INFO, *PAFD_EVENT_SELECT_INFO; + +// private +typedef struct _AFD_ENUM_NETWORK_EVENTS_INFO +{ + ULONG PollEvents; // AFD_POLL_* + NTSTATUS EventStatus[AFD_NUM_POLL_EVENTS]; +} AFD_ENUM_NETWORK_EVENTS_INFO, *PAFD_ENUM_NETWORK_EVENTS_INFO; + +// private +typedef struct _AFD_DEFER_ACCEPT_INFO +{ + LONG Sequence; + BOOLEAN Reject; +} AFD_DEFER_ACCEPT_INFO, *PAFD_DEFER_ACCEPT_INFO; + +// private +typedef struct _AFD_QOS_INFO +{ + QOS Qos; + BOOLEAN GroupQos; +} AFD_QOS_INFO, *PAFD_QOS_INFO; + +// private +typedef struct _AFD_VALIDATE_GROUP_INFO +{ + GROUP GroupID; + TRANSPORT_ADDRESS RemoteAddress; +} AFD_VALIDATE_GROUP_INFO, *PAFD_VALIDATE_GROUP_INFO; + +// private +typedef struct _AFD_TRANSPORT_IOCTL_INFO +{ + HANDLE Handle; + _Field_size_bytes_(InputBufferLength) PVOID InputBuffer; + ULONG InputBufferLength; + ULONG IoControlCode; + ULONG AfdFlags; + ULONG PollEvent; +} AFD_TRANSPORT_IOCTL_INFO, *PAFD_TRANSPORT_IOCTL_INFO; + +// rev - HV_PROTOCOL_RAW-level option in addition to ones in hvsocket.h +#define HVSOCKET_CONTAINER_PASSTHRU 0x02 // q: ULONG + +// private +typedef enum TL_IO_CONTROL_TYPE +{ + TlEndpointIoControlType = 0, // not supported + TlSetSockOptIoControlType = 1, // setsockopt + TlGetSockOptIoControlType = 2, // getsockopt + TlSocketIoControlType = 3, // ioctlsocket // Level must be 0 +} TL_IO_CONTROL_TYPE, *PTL_IO_CONTROL_TYPE; + +// private +typedef struct _AFD_TL_IO_CONTROL_INFO +{ + TL_IO_CONTROL_TYPE Type; + ULONG Level; // SOL_* or IPPROTO_* or HV_PROTOCOL_RAW + ULONG IoControlCode; // SIO_*, SO_*, IP_*, IPV6_*, TCP_*, UDP_*, HVSOCKET_*, etc. (depending on type and level) + BOOLEAN EndpointIoctl; // must be TRUE + _Field_size_bytes_(InputBufferLength) PVOID InputBuffer; + SIZE_T InputBufferLength; +} AFD_TL_IO_CONTROL_INFO, *PAFD_TL_IO_CONTROL_INFO; + +// private +typedef struct _AFD_TPACKETS_INFO +{ + _Field_size_(ElementCount) PTRANSMIT_PACKETS_ELEMENT ElementArray; + ULONG ElementCount; + ULONG SendSize; + ULONG Flags; +} AFD_TPACKETS_INFO, *PAFD_TPACKETS_INFO; + +// private +typedef struct _AFD_SUPER_CONNECT_INFO +{ + BOOLEAN SanActive; + TRANSPORT_ADDRESS RemoteAddress; +} AFD_SUPER_CONNECT_INFO, *PAFD_SUPER_CONNECT_INFO; + +// rev +typedef struct _AFD_SUPER_CONNECT_INFO_TL +{ + BOOLEAN SanActive; + SOCKADDR RemoteAddress; +} AFD_SUPER_CONNECT_INFO_TL, *PAFD_SUPER_CONNECT_INFO_TL; + +// private +typedef struct _AFD_SUPER_DISCONNECT_INFO +{ + ULONG Flags; // same as partial disconnect +} AFD_SUPER_DISCONNECT_INFO, *PAFD_SUPER_DISCONNECT_INFO; + +// private +typedef struct _AFD_MESSAGE_INFO +{ + AFD_DATAGRAM_INFO dgi; + _Field_size_bytes_(ControlLength) PVOID ControlBuffer; + PULONG ControlLength; + PULONG MsgFlags; +} AFD_MESSAGE_INFO, *PAFD_MESSAGE_INFO; + +// private +typedef struct _AFD_SWITCH_CONTEXT +{ + LONG EventsActive; + LONG RcvCount; + LONG ExpCount; + LONG SndCount; + BOOLEAN SelectFlag; +} AFD_SWITCH_CONTEXT, *PAFD_SWITCH_CONTEXT; + +// private +typedef struct _AFD_SWITCH_CONTEXT_INFO +{ + HANDLE SocketHandle; + PAFD_SWITCH_CONTEXT SwitchContext; +} AFD_SWITCH_CONTEXT_INFO, *PAFD_SWITCH_CONTEXT_INFO; + +// private +typedef struct _AFD_SWITCH_EVENT_INFO +{ + HANDLE SocketHandle; + PAFD_SWITCH_CONTEXT SwitchContext; + ULONG EventBit; // AFD_POLL_*_BIT + NTSTATUS Status; +} AFD_SWITCH_EVENT_INFO, *PAFD_SWITCH_EVENT_INFO; + +// private +typedef struct _AFD_SWITCH_CONNECT_INFO +{ + HANDLE ListenHandle; + PAFD_SWITCH_CONTEXT SwitchContext; + TRANSPORT_ADDRESS RemoteAddress; +} AFD_SWITCH_CONNECT_INFO, *PAFD_SWITCH_CONNECT_INFO; + +// private +typedef struct _AFD_SWITCH_ACCEPT_INFO +{ + HANDLE AcceptHandle; + ULONG ReceiveLength; +} AFD_SWITCH_ACCEPT_INFO, *PAFD_SWITCH_ACCEPT_INFO; + +// private +typedef struct _AFD_SWITCH_REQUEST_INFO +{ + HANDLE SocketHandle; + PAFD_SWITCH_CONTEXT SwitchContext; + PVOID RequestContext; + NTSTATUS RequestStatus; + ULONG DataOffset; +} AFD_SWITCH_REQUEST_INFO, *PAFD_SWITCH_REQUEST_INFO; + +// private +typedef struct _AFD_SWITCH_ACQUIRE_CTX_INFO +{ + HANDLE SocketHandle; + PAFD_SWITCH_CONTEXT SwitchContext; + PVOID SocketCtxBuf; + ULONG SocketCtxBufSize; +} AFD_SWITCH_ACQUIRE_CTX_INFO, *PAFD_SWITCH_ACQUIRE_CTX_INFO; + +// private +typedef struct _AFD_SWITCH_TRANSFER_CTX_INFO +{ + HANDLE SocketHandle; + PAFD_SWITCH_CONTEXT SwitchContext; + PVOID RequestContext; + PVOID SocketCtxBuf; + ULONG SocketCtxBufSize; + _Field_size_(RcvBufferCount) LPWSABUF RcvBufferArray; + ULONG RcvBufferCount; + NTSTATUS Status; +} AFD_SWITCH_TRANSFER_CTX_INFO, *PAFD_SWITCH_TRANSFER_CTX_INFO; + +// private +typedef struct _AFD_UNBIND_INFO +{ + LONG AddressFamily; // AF_* + LONG Protocol; // IPPROTO_*, BTHPROTO_*, HV_PROTOCOL_*, etc. +} AFD_UNBIND_INFO, *PAFD_UNBIND_INFO; + +// rev // SQM Control Codes +#define AFD_SQM_CONTROL_CODE_STORE 1 +#define AFD_SQM_CONTROL_CODE_SWEEP -1 + +// private +typedef struct _AFD_SQM_CONTROL +{ + ULONG Code; // AFD_SQM_CONTROL_CODE_* +} AFD_SQM_CONTROL, *PAFD_SQM_CONTROL; + +// private +typedef struct _WINSOCK_SQM_SOCKTYPE_DESC +{ + ULONG StreamTCP : 1; + ULONG StreamOther : 1; + ULONG DatagramUDP : 1; + ULONG DatagramUDPMulticast : 1; + ULONG DatagramOther : 1; + ULONG RawTCP : 1; + ULONG RawUDP : 1; + ULONG RawOther : 1; + ULONG OtherSocketTypes : 1; + ULONG IPv6Socket : 1; + ULONG ProviderLoadedWSD : 1; + ULONG ProviderLoadedLSP : 1; + ULONG ProviderLoadedMultiLSP : 1; + ULONG NonMswsockBSP : 1; +} WINSOCK_SQM_SOCKTYPE_DESC, *PWINSOCK_SQM_SOCKTYPE_DESC; + +// private +typedef struct _WINSOCK_SQM_SOCKTYPE_COUNTS +{ + ULONG MaxStreamSocketsConn; + ULONG MaxStreamSocketsListen; + ULONG MaxDatagramSockets; + ULONG MaxRawSockets; + ULONG MaxOtherSockets; +} WINSOCK_SQM_SOCKTYPE_COUNTS, *PWINSOCK_SQM_SOCKTYPE_COUNTS; + +// private +typedef struct _WINSOCK_SQM_NONCORE_FUNC +{ + ULONG Select : 1; + ULONG WSAPoll : 1; + ULONG StreamWSAEventSelect : 1; + ULONG StreamWSAAsyncSelect : 1; + ULONG TransmitFile : 1; + ULONG StreamTransmitPackets : 1; + ULONG DisconnectEx : 1; + ULONG SocketReuse : 1; + ULONG StreamDuplicateSocket : 1; + ULONG ReadWriteFile : 1; + ULONG OOBSendRecv : 1; + ULONG StreamSoSndTimeO : 1; + ULONG StreamSoRcvTimeO : 1; + ULONG MsgWaitAll : 1; + ULONG StreamNonCoreSOLOptions : 1; + ULONG StreamNonCoreTCPOptions : 1; + ULONG StreamNonCoreIPOptions : 1; + ULONG StreamNonCoreOtherOptions : 1; + ULONG StreamNonCoreIOCTLs : 1; + ULONG StreamNonCoreWSASocket : 1; + ULONG NonCoreRecv : 1; + ULONG NonCoreSend : 1; + ULONG StreamNonCoreWSAIoctl : 1; + ULONG NonCoreWSAAccept : 1; + ULONG StreamNonCoreWSAConnect : 1; + ULONG StreamWSAJoinLeaf : 1; + ULONG StreamWSAGetQoSByName : 1; + ULONG WSASendDisconnect : 1; + ULONG WSARecvDisconnect : 1; +} WINSOCK_SQM_NONCORE_FUNC, *PWINSOCK_SQM_NONCORE_FUNC; + +// private +typedef struct _WINSOCK_SQM_DEPRECATION_LIST +{ + ULONG bEnumProtocols : 1; + ULONG bGetNameByType : 1; + ULONG bGetService : 1; + ULONG bGetTypeByName : 1; + ULONG bSetService : 1; + ULONG bWSACancelBlockingCall : 1; + ULONG bWSAIsBlocking : 1; + ULONG bWSASetBlockingHook : 1; + ULONG bWSAUnhookBlockingHook : 1; + ULONG bGetAddressByName : 1; + ULONG bGetHostByAddr : 1; + ULONG bGetHostByName : 1; + ULONG bGetHostName : 1; + ULONG bGetProtoByName : 1; + ULONG bGetProtoByNumber : 1; + ULONG bGetServByName : 1; + ULONG bGetServByPort : 1; + ULONG bInetAddr : 1; + ULONG bInetNtoa : 1; + ULONG bWSAAsyncGetHostByAddr : 1; + ULONG bWSAAsyncGetHostByName : 1; + ULONG bWSAAsyncGetProtoByName : 1; + ULONG bWSAAsyncGetProtoByNumber : 1; + ULONG bWSAAsyncGetServByName : 1; + ULONG bWSAAsyncGetServByPort : 1; + ULONG bWSACancelAsyncRequest : 1; + ULONG bWSARecvEx : 1; +} WINSOCK_SQM_DEPRECATION_LIST, *PWINSOCK_SQM_DEPRECATION_LIST; + +// private +typedef struct _WINSOCK_SQM_SOCK_OPTIONS +{ + ULONG SoSndBuf : 1; + ULONG SoRcvBuf : 1; + ULONG SoSndBuf0 : 1; + ULONG SoRcvBuf0 : 1; + ULONG SoKeepAliveOn : 1; + ULONG SoReuseAddrOn : 1; + ULONG SoExclusiveAddrUseOn : 1; + ULONG SoLingerOn : 1; + ULONG SoLingerOn0 : 1; + ULONG SoRandomizePortOn : 1; + ULONG SoPortScaleOn : 1; + ULONG SoCondAcceptOn : 1; + ULONG SoOobInlineOn : 1; + ULONG SoOther : 1; + ULONG TCPNoDelayOn : 1; + ULONG TCPOther : 1; + ULONG IPV6V6OnlyOff : 1; + ULONG IPV6ProtectLevel : 1; + ULONG IPOther : 1; + ULONG LevelOther : 1; + ULONG ISBQuery : 1; + ULONG ISBNotify : 1; + ULONG AddressQuery : 1; + ULONG AddressNotify : 1; + ULONG RouteQuery : 1; + ULONG RouteNotify : 1; + ULONG FionbioOn : 1; + ULONG Fionread : 1; + ULONG Siocatmark : 1; + ULONG Siokeepalivevals : 1; + ULONG Siosetcompatmode : 1; + ULONG Sioportreserve : 1; +} WINSOCK_SQM_SOCK_OPTIONS, *PWINSOCK_SQM_SOCK_OPTIONS; + +// private +typedef struct _WINSOCK_SQM_MISC_BEHAVIOR +{ + ULONG SendEverPended : 1; + ULONG RecvEverPended : 1; + ULONG ShutdownSend : 1; + ULONG ShutdownRecv : 1; + ULONG WSASocketProtocol : 1; +} WINSOCK_SQM_MISC_BEHAVIOR, *PWINSOCK_SQM_MISC_BEHAVIOR; + +// private +typedef struct _AFD_SQM_INFO +{ + AFD_SQM_CONTROL Control; + WCHAR AppName[16]; + WCHAR LSPName[16]; + ULONG AppVersion; + WINSOCK_SQM_SOCKTYPE_DESC SocketTypeDescriptor; + WINSOCK_SQM_SOCKTYPE_COUNTS SocketTypeCounts; + WINSOCK_SQM_NONCORE_FUNC NonCoreFunctions; + WINSOCK_SQM_DEPRECATION_LIST DeprecationList; + WINSOCK_SQM_SOCK_OPTIONS SocketOptions; + WINSOCK_SQM_MISC_BEHAVIOR MiscBehavior; +} AFD_SQM_INFO, *PAFD_SQM_INFO; + +// private +typedef enum _AFD_RIO_COMMAND +{ + AfdRioCommandIdCreateCq = 0, // in: AFD_RIO_COMMAND_CREATE_CQ; out: AFD_RIO_COMMAND_CREATE_CQ_RESULT + AfdRioCommandIdDestroyCq = 1, // in: AFD_RIO_COMMAND_DESTROY_CQ + AfdRioCommandIdNotifyCq = 2, // in: AFD_RIO_COMMAND_NOTIFY_CQ + AfdRioCommandIdCreateRqPair = 3, // in: AFD_RIO_COMMAND_CREATE_RQ_PAIR + AfdRioCommandIdRegisterBuffer = 4, // in: AFD_RIO_COMMAND_REGISTER_BUFFER; out: AFD_RIO_COMMAND_REGISTER_BUFFER_RESULT + AfdRioCommandIdDeregisterBuffer = 5, // in: AFD_RIO_COMMAND_DEREGISTER_BUFFER + AfdRioCommandIdPokeSend = 6, // in: AFD_RIO_COMMAND_POKE_SEND + AfdRioCommandIdPokeReceive = 7, // in: AFD_RIO_COMMAND_POKE_RECEIVE + AfdRioCommandIdResizeCq = 8, // in: AFD_RIO_COMMAND_RESIZE_CQ + AfdRioCommandIdResizeRqPair = 9, // in: AFD_RIO_COMMAND_RESIZE_RQ_PAIR + AfdRioCommandIdMaximum = 10, +} AFD_RIO_COMMAND, *PAFD_RIO_COMMAND; + +// private +typedef struct _AFD_RIO_COMMAND_HEADER +{ + AFD_RIO_COMMAND Command; +} AFD_RIO_COMMAND_HEADER, *PAFD_RIO_COMMAND_HEADER; + +// private +typedef enum _AFD_RIO_NOTIFICATION_COMPLETION_TYPE +{ + AfdRioNoCompletion = 0, + AfdRioEventCompletion = 1, + AfdRioIocpCompletion = 2, +} AFD_RIO_NOTIFICATION_COMPLETION_TYPE, *PAFD_RIO_NOTIFICATION_COMPLETION_TYPE; + +// private +typedef struct _AFD_RIO_COMPLETION_QUEUE +{ + ULONG QHead; + ULONG QTail; + BOOLEAN Corrupted; + RIORESULT QEntry[ANYSIZE_ARRAY]; +} AFD_RIO_COMPLETION_QUEUE, *PAFD_RIO_COMPLETION_QUEUE; + +// private +typedef struct _AFD_RIO_COMMAND_CREATE_CQ +{ + AFD_RIO_COMMAND_HEADER Header; + ULONG QSize; + AFD_RIO_NOTIFICATION_COMPLETION_TYPE NotificationType; + ULONGLONG NotificationHandle; + ULONGLONG NotificationContext; + ULONGLONG NotificationContext2; + ULONG BufferSize; + ULONGLONG Buffer; // PAFD_RIO_COMPLETION_QUEUE +} AFD_RIO_COMMAND_CREATE_CQ, *PAFD_RIO_COMMAND_CREATE_CQ; + +// private +typedef struct _AFD_RIO_COMMAND_CREATE_CQ_RESULT +{ + ULONG CqId; +} AFD_RIO_COMMAND_CREATE_CQ_RESULT, *PAFD_RIO_COMMAND_CREATE_CQ_RESULT; + +// private +typedef struct _AFD_RIO_COMMAND_DESTROY_CQ +{ + AFD_RIO_COMMAND_HEADER Header; + ULONG CqId; +} AFD_RIO_COMMAND_DESTROY_CQ, *PAFD_RIO_COMMAND_DESTROY_CQ; + +// private +typedef struct _AFD_RIO_COMMAND_NOTIFY_CQ +{ + AFD_RIO_COMMAND_HEADER Header; + ULONG Index; +} AFD_RIO_COMMAND_NOTIFY_CQ, *PAFD_RIO_COMMAND_NOTIFY_CQ; + +// private +typedef struct _AFD_RIO_BUF +{ + ULONG BufferId; + ULONG Offset; + ULONG Length; +} AFD_RIO_BUF, *PAFD_RIO_BUF; + +// private +typedef struct _AFD_RIO_REQUEST_QUEUE_ENTRY +{ + AFD_RIO_BUF Data; + AFD_RIO_BUF SourceAddress; + AFD_RIO_BUF DestinationAddress; + AFD_RIO_BUF Control; + AFD_RIO_BUF FlagsBuffer; + ULONG Flags; + ULONGLONG Context; +} AFD_RIO_REQUEST_QUEUE_ENTRY, *PAFD_RIO_REQUEST_QUEUE_ENTRY; + +// private +typedef struct _AFD_RIO_REQUEST_QUEUE +{ + ULONG Start; + ULONG End; + BOOLEAN PokeRequired; + AFD_RIO_REQUEST_QUEUE_ENTRY Entries[ANYSIZE_ARRAY]; +} AFD_RIO_REQUEST_QUEUE, *PAFD_RIO_REQUEST_QUEUE; + +// private +typedef struct _AFD_RIO_COMMAND_CREATE_RQ_PAIR +{ + AFD_RIO_COMMAND_HEADER Header; + ULONG SendCompletionQueue; + ULONG ReceiveCompletionQueue; + ULONG SendQueueEntryCount; + ULONG SendQueueBufferSize; + ULONGLONG SendQueueBuffer; // PAFD_RIO_REQUEST_QUEUE + ULONG ReceiveQueueEntryCount; + ULONG ReceiveQueueBufferSize; + ULONGLONG ReceiveQueueBuffer; // PAFD_RIO_REQUEST_QUEUE + ULONGLONG EndpointHandle; + ULONGLONG SocketContext; +} AFD_RIO_COMMAND_CREATE_RQ_PAIR, *PAFD_RIO_COMMAND_CREATE_RQ_PAIR; + +// private +typedef struct _AFD_RIO_COMMAND_REGISTER_BUFFER +{ + AFD_RIO_COMMAND_HEADER Header; + ULONGLONG Buffer; + ULONG BufferLength; +} AFD_RIO_COMMAND_REGISTER_BUFFER, *PAFD_RIO_COMMAND_REGISTER_BUFFER; + +// private +typedef struct _AFD_RIO_COMMAND_REGISTER_BUFFER_RESULT +{ + ULONG BufferId; +} AFD_RIO_COMMAND_REGISTER_BUFFER_RESULT, *PAFD_RIO_COMMAND_REGISTER_BUFFER_RESULT; + +// private +typedef struct _AFD_RIO_COMMAND_DEREGISTER_BUFFER +{ + AFD_RIO_COMMAND_HEADER Header; + ULONG BufferId; +} AFD_RIO_COMMAND_DEREGISTER_BUFFER, *PAFD_RIO_COMMAND_DEREGISTER_BUFFER; + +// private +typedef struct _AFD_RIO_COMMAND_POKE_SEND +{ + AFD_RIO_COMMAND_HEADER Header; +} AFD_RIO_COMMAND_POKE_SEND, *PAFD_RIO_COMMAND_POKE_SEND; + +// private +typedef struct _AFD_RIO_COMMAND_POKE_RECEIVE +{ + AFD_RIO_COMMAND_HEADER Header; +} AFD_RIO_COMMAND_POKE_RECEIVE, *PAFD_RIO_COMMAND_POKE_RECEIVE; + +// private +typedef struct _AFD_RIO_COMMAND_RESIZE_CQ +{ + AFD_RIO_COMMAND_HEADER Header; + ULONG CqId; + ULONG QSize; + ULONG BufferSize; + ULONGLONG Buffer; +} AFD_RIO_COMMAND_RESIZE_CQ, *PAFD_RIO_COMMAND_RESIZE_CQ; + +// private +typedef struct _AFD_RIO_COMMAND_RESIZE_RQ_PAIR +{ + AFD_RIO_COMMAND_HEADER Header; + ULONG SendQueueEntryCount; + ULONG SendQueueBufferSize; + ULONGLONG SendQueueBuffer; + ULONG ReceiveQueueEntryCount; + ULONG ReceiveQueueBufferSize; + ULONGLONG ReceiveQueueBuffer; +} AFD_RIO_COMMAND_RESIZE_RQ_PAIR, *PAFD_RIO_COMMAND_RESIZE_RQ_PAIR; + +#endif diff --git a/ntbcd.h b/ntbcd.h index 1327e22..0c4e4a4 100644 --- a/ntbcd.h +++ b/ntbcd.h @@ -7,6 +7,10 @@ #ifndef _NTBCD_H #define _NTBCD_H +// +// BCD.dll Exported Types +// + #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); @@ -40,9 +44,9 @@ DEFINE_GUID(GUID_WINDOWS_MEMORY_TESTER, 0xB2721D73, 0x1DB4, 0x4C62, 0xBF, 0x78, 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} +// 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} +// 98B02A23-0674-4CE7-BDAD-E0A15A8FF97B DEFINE_GUID(GUID_WINDOWS_RESUME_TARGET_TEMPLATE_PCAT, 0x98B02A23, 0x0674, 0x4CE7, 0xBD, 0xAD, 0xE0, 0xA1, 0x5A, 0x8F, 0xF9, 0x7B); // 7254a080-1510-4e85-ac0f-e7fb3d444736 DEFINE_GUID(GUID_WINDOWS_SETUP_EFI, 0x7254A080, 0x1510, 0x4E85, 0xAC, 0x0F, 0xE7, 0xFB, 0x3D, 0x44, 0x47, 0x36); @@ -50,29 +54,31 @@ DEFINE_GUID(GUID_WINDOWS_SETUP_EFI, 0x7254A080, 0x1510, 0x4E85, 0xAC, 0x0F, 0xE7 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} +// 7619dcc9-fafe-11d9-b411-000476eba25f DEFINE_GUID(GUID_WINDOWS_SETUP_BOOT_ENTRY, 0x7619dcc9, 0xfafe, 0x11d9, 0xb4, 0x11, 0x00, 0x04, 0x76, 0xeb, 0xa2, 0x5f); -// {a62c8016-ca4e-4687-8032-d666c51a280c} +// A62C8016-CA4E-4687-8032-D666C51A280C DEFINE_GUID(GUID_VHD_BOOT_OPTIONS, 0xa62c8016, 0xca4e, 0x4687, 0x80, 0x32, 0xd6, 0x66, 0xc5, 0x1a, 0x28, 0x0c); -// ebd0a0a2-b9e5-4433-87c0-68b6b72699c7 +// C63C9BDF-5FA5-4208-B03F-6B458B365592 +DEFINE_GUID(GUID_VMBFS_BOOT_INSTANCE, 0xc63c9bdf, 0x5fa5, 0x4208, 0xb0, 0x3f, 0x6b, 0x45, 0x8b, 0x36, 0x55, 0x92); +// EBD0A0A2-B9E5-4433-87C0-68B6B72699C7 DEFINE_GUID(PARTITION_BASIC_DATA_GUID, 0xebd0a0a2, 0xb9e5, 0x4433, 0x87, 0xc0, 0x68, 0xb6, 0xb7, 0x26, 0x99, 0xc7); -// db97dba9-0840-4bae-97f0-ffb9a327c7e1 +// DB97DBA9-0840-4BAE-97F0-FFB9A327C7E1 DEFINE_GUID(PARTITION_CLUSTER_GUID, 0xdb97dba9, 0x0840, 0x4bae, 0x97, 0xf0, 0xff, 0xb9, 0xa3, 0x27, 0xc7, 0xe1); // 00000000-0000-0000-0000-000000000000 DEFINE_GUID(PARTITION_ENTRY_UNUSED_GUID, 0x00000000, 0x0000, 0x0000, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00); -// af9b60a0-1431-4f62-bc68-3311714a69ad +// AF9B60A0-1431-4F62-BC68-3311714A69AD DEFINE_GUID(PARTITION_LDM_DATA_GUID, 0xaf9b60a0, 0x1431, 0x4f62, 0xbc, 0x68, 0x33, 0x11, 0x71, 0x4a, 0x69, 0xad); -// 5808c8aa-7e8f-42e0-85d2-e1e90434cfb3 +// 5808C8AA-7E8F-42E0-85D2-E1E90434CFB3 DEFINE_GUID(PARTITION_LDM_METADATA_GUID, 0x5808c8aa, 0x7e8f, 0x42e0, 0x85, 0xd2, 0xe1, 0xe9, 0x04, 0x34, 0xcf, 0xb3); -// de94bba4-06d1-4d40-a16a-bfd50179d6ac +// DE94BBA4-06D1-4D40-A16A-BFD50179D6AC DEFINE_GUID(PARTITION_MSFT_RECOVERY_GUID, 0xde94bba4, 0x06d1, 0x4d40, 0xa1, 0x6a, 0xbf, 0xd5, 0x01, 0x79, 0xd6, 0xac); -// e3c9e316-0b5c-4db8-817d-f92df00215ae +// E3C9E316-0B5C-4DB8-817D-F92DF00215AE DEFINE_GUID(PARTITION_MSFT_RESERVED_GUID, 0xe3c9e316, 0x0b5c, 0x4db8, 0x81, 0x7d, 0xf9, 0x2d, 0xf0, 0x02, 0x15, 0xae); -// caddebf1-4400-4de8-b103-12117dcf3cc +// CADDEBF1-4400-4DE8-B103-12117DCF3CC DEFINE_GUID(PARTITION_MSFT_SNAPSHOT_GUID, 0xcaddebf1, 0x4400, 0x4de8, 0xb1, 0x03, 0x12, 0x11, 0x7d, 0xcf, 0x3c, 0xcf); -// e75caf8f-f680-4cee-afa3-b001e56efc2d +// E75CAF8F-F680-4CEE-AFA3-B001E56EFC2D DEFINE_GUID(PARTITION_SPACES_GUID, 0xe75caf8f, 0xf680, 0x4cee, 0xaf, 0xa3, 0xb0, 0x01, 0xe5, 0x6e, 0xfc, 0x2d); -// c12a7328-f81f-11d2-ba4b-00a0c93ec93b +// C12A7328-F81F-11D2-BA4B-00A0C93EC93B DEFINE_GUID(PARTITION_SYSTEM_GUID, 0xc12a7328, 0xf81f, 0x11d2, 0xba, 0x4b, 0x00, 0xa0, 0xc9, 0x3e, 0xc9, 0x3b); #else NTSYSAPI GUID GUID_BAD_MEMORY_GROUP; // {badmemory} @@ -107,8 +113,11 @@ NTSYSAPI GUID PARTITION_MSFT_RESERVED_GUID; NTSYSAPI GUID PARTITION_MSFT_SNAPSHOT_GUID; NTSYSAPI GUID PARTITION_SPACES_GUID; NTSYSAPI GUID PARTITION_SYSTEM_GUID; -#endif +#endif // PHNT_INLINE_BCD_GUIDS +/** + * The BCD_MESSAGE_TYPE enumeration represents the types of messages for BCD operations. + */ typedef enum _BCD_MESSAGE_TYPE { BCD_MESSAGE_TYPE_NONE, @@ -119,28 +128,30 @@ typedef enum _BCD_MESSAGE_TYPE BCD_MESSAGE_TYPE_MAXIMUM } BCD_MESSAGE_TYPE; -typedef VOID (NTAPI* BCD_MESSAGE_CALLBACK)( +typedef _Function_class_(BCD_MESSAGE_CALLBACK) +VOID NTAPI BCD_MESSAGE_CALLBACK( _In_ BCD_MESSAGE_TYPE type, _In_ PCWSTR Message ); +typedef BCD_MESSAGE_CALLBACK* PBCD_MESSAGE_CALLBACK; /** - * Sets the logging level and callback routine for BCD messages. + * Sets the logging level and callback function for BCD messages. * - * @param BcdLoggingLevel The logging level to set. - * @param BcdMessageCallbackRoutine The callback routine for BCD messages. - * @return NTSTATUS Successful or errant status. + * \param BcdLoggingLevel The logging level to set. + * \param BcdMessageCallbackRoutine The callback routine for BCD messages. + * \return NTSTATUS Successful or errant status. */ NTSYSAPI NTSTATUS NTAPI BcdSetLogging( _In_ BCD_MESSAGE_TYPE BcdLoggingLevel, - _In_ BCD_MESSAGE_CALLBACK BcdMessageCallbackRoutine + _In_ PBCD_MESSAGE_CALLBACK BcdMessageCallbackRoutine ); /** - * Initializes the BCD synchronization mutant. + * The BcdInitializeBcdSyncMutant function initializes the BCD synchronization mutant. */ NTSYSAPI VOID @@ -150,10 +161,10 @@ BcdInitializeBcdSyncMutant( ); /** - * Retrieves the file name for the BCD. + * The BcdGetSystemStorePath function retrieves the file name for the BCD. * - * @param BcdSystemStorePath The pointer to receive the system store path. - * @return NTSTATUS Successful or errant status. + * \param BcdSystemStorePath The pointer to receive the system store path. + * \return NTSTATUS Successful or errant status. */ NTSYSAPI NTSTATUS @@ -163,10 +174,10 @@ BcdGetSystemStorePath( ); /** - * Sets the device for the system BCD store. + * The BcdSetSystemStoreDevice function sets the device for the system BCD store. * - * @param SystemPartition The system partition to set. - * @return NTSTATUS Successful or errant status. + * \param SystemPartition The system partition to set. + * \return NTSTATUS Successful or errant status. */ NTSYSAPI NTSTATUS @@ -176,10 +187,10 @@ BcdSetSystemStoreDevice( ); /** - * Opens the BCD system store. + * The BcdOpenSystemStore function opens the BCD system store. * - * @param BcdStoreHandle The handle to receive the system store. - * @return NTSTATUS Successful or errant status. + * \param BcdStoreHandle The handle to receive the system store. + * \return NTSTATUS Successful or errant status. */ NTSYSAPI NTSTATUS @@ -189,11 +200,11 @@ BcdOpenSystemStore( ); /** - * Opens a BCD store from a file. + * The BcdOpenStoreFromFile function opens a BCD store from a file. * - * @param BcdFilePath The file path of the BCD store. - * @param BcdStoreHandle The handle to receive the BCD store. - * @return NTSTATUS Successful or errant status. + * \param BcdFilePath The file path of the BCD store. + * \param BcdStoreHandle The handle to receive the BCD store. + * \return NTSTATUS Successful or errant status. */ NTSYSAPI NTSTATUS @@ -204,11 +215,11 @@ BcdOpenStoreFromFile( ); /** - * Creates a BCD store. + * The BcdCreateStore function creates a BCD store. * - * @param BcdFilePath The file path to create the BCD store. - * @param BcdStoreHandle The handle to receive the BCD store. - * @return NTSTATUS Successful or errant status. + * \param BcdFilePath The file path to create the BCD store. + * \param BcdStoreHandle The handle to receive the BCD store. + * \return NTSTATUS Successful or errant status. */ NTSYSAPI NTSTATUS @@ -219,10 +230,10 @@ BcdCreateStore( ); /** - * Exports the BCD store to a file. + * The BcdExportStore function exports the BCD store to a file. * - * @param BcdFilePath The file path to export the BCD store. - * @return NTSTATUS Successful or errant status. + * \param BcdFilePath The file path to export the BCD store. + * \return NTSTATUS Successful or errant status. */ NTSYSAPI NTSTATUS @@ -233,12 +244,12 @@ BcdExportStore( #if (PHNT_VERSION > PHNT_WINDOWS_11) /** - * Exports the BCD store to a file with additional flags. + * The BcdExportStoreEx function exports the BCD store to a file with additional flags. * - * @param BcdStoreHandle The handle to the BCD store. - * @param Flags The flags for exporting the store. - * @param BcdFilePath The file path to export the BCD store. - * @return NTSTATUS Successful or errant status. + * \param BcdStoreHandle The handle to the BCD store. + * \param Flags The flags for exporting the store. + * \param BcdFilePath The file path to export the BCD store. + * \return NTSTATUS Successful or errant status. */ NTSYSAPI NTSTATUS @@ -248,13 +259,13 @@ BcdExportStoreEx( _In_ ULONG Flags, _In_ PCUNICODE_STRING BcdFilePath ); -#endif +#endif // PHNT_VERSION > PHNT_WINDOWS_11 /** - * Imports a BCD store from a file. + * The BcdImportStore function imports a BCD store from a file. * - * @param BcdFilePath The file path to import the BCD store. - * @return NTSTATUS Successful or errant status. + * \param BcdFilePath The file path to import the BCD store. + * \return NTSTATUS Successful or errant status. */ NTSYSAPI NTSTATUS @@ -270,11 +281,11 @@ typedef enum _BCD_IMPORT_FLAGS } BCD_IMPORT_FLAGS; /** - * Imports a BCD store from a file with additional flags. + * The BcdImportStoreWithFlags function imports a BCD store from a file with additional flags. * - * @param BcdFilePath The file path to import the BCD store. - * @param BcdImportFlags The flags for importing the store. - * @return NTSTATUS Successful or errant status. + * \param BcdFilePath The file path to import the BCD store. + * \param BcdImportFlags The flags for importing the store. + * \return NTSTATUS Successful or errant status. */ NTSYSAPI NTSTATUS @@ -285,24 +296,24 @@ BcdImportStoreWithFlags( ); /** - * Deletes object references in the BCD store. + * The BcdDeleteObjectReferences function deletes object references in the BCD store. * - * @param BcdStoreHandle The handle to the BCD store. - * @param Identifier The identifier of the object to delete references for. - * @return NTSTATUS Successful or errant status. + * \param BcdStoreHandle The handle to the BCD store. + * \param Identifier The identifier of the object to delete references for. + * \return NTSTATUS Successful or errant status. */ NTSYSAPI NTSTATUS NTAPI BcdDeleteObjectReferences( _In_ HANDLE BcdStoreHandle, - _In_ PGUID Identifier + _In_ PCGUID Identifier ); /** - * Deletes the system store for BCD. + * The BcdDeleteSystemStore function deletes the system store for BCD. * - * @return NTSTATUS Successful or errant status. + * \return NTSTATUS Successful or errant status. */ NTSYSAPI NTSTATUS @@ -319,12 +330,12 @@ typedef enum _BCD_OPEN_FLAGS } BCD_OPEN_FLAGS; /** - * Opens a BCD store with additional flags. + * The BcdOpenStore function opens a BCD store with additional flags. * - * @param BcdFilePath The file path of the BCD store. - * @param BcdOpenFlags The flags for opening the store. - * @param BcdStoreHandle The handle to receive the BCD store. - * @return NTSTATUS Successful or errant status. + * \param BcdFilePath The file path of the BCD store. + * \param BcdOpenFlags The flags for opening the store. + * \param BcdStoreHandle The handle to receive the BCD store. + * \return NTSTATUS Successful or errant status. */ NTSYSAPI NTSTATUS @@ -336,10 +347,10 @@ BcdOpenStore( ); /** - * Closes a BCD store. + * The BcdCloseStore function closes a BCD store. * - * @param BcdStoreHandle The handle to the BCD store. - * @return NTSTATUS Successful or errant status. + * \param BcdStoreHandle The handle to the BCD store. + * \return NTSTATUS Successful or errant status. */ NTSYSAPI NTSTATUS @@ -349,10 +360,10 @@ BcdCloseStore( ); /** - * Flushes a BCD store. + * The BcdFlushStore function flushes a BCD store. * - * @param BcdStoreHandle The handle to the BCD store. - * @return NTSTATUS Successful or errant status. + * \param BcdStoreHandle The handle to the BCD store. + * \return NTSTATUS Successful or errant status. */ NTSYSAPI NTSTATUS @@ -362,10 +373,10 @@ BcdFlushStore( ); /** - * Forcibly unloads a BCD store. + * The BcdForciblyUnloadStore function forcibly unloads a BCD store. * - * @param BcdStoreHandle The handle to the BCD store. - * @return NTSTATUS Successful or errant status. + * \param BcdStoreHandle The handle to the BCD store. + * \return NTSTATUS Successful or errant status. */ NTSYSAPI NTSTATUS @@ -374,6 +385,13 @@ BcdForciblyUnloadStore( _In_ HANDLE BcdStoreHandle ); +/** + * The BcdMarkAsSystemStore function marks the specified BCD store as the system store + * and used by the boot manager and other boot components as the primary source of boot configuration data. + * + * \param BcdStoreHandle Handle to the BCD store to be marked as the system store. + * \return NTSTATUS Successful or errant status. + */ NTSYSAPI NTSTATUS NTAPI @@ -381,6 +399,9 @@ BcdMarkAsSystemStore( _In_ HANDLE BcdStoreHandle ); +/** + * The BCD_OBJECT_TYPE enumeration represents the types of BCD (Boot Configuration Data) objects. + */ typedef enum _BCD_OBJECT_TYPE { BCD_OBJECT_TYPE_NONE, @@ -389,6 +410,10 @@ typedef enum _BCD_OBJECT_TYPE BCD_OBJECT_TYPE_DEVICE, // 0x30000000 } BCD_OBJECT_TYPE; +/** + * The BCD_APPLICATION_OBJECT_TYPE enumeration represents the various types + * of application objects in the Boot Configuration Data (BCD). + */ typedef enum _BCD_APPLICATION_OBJECT_TYPE { BCD_APPLICATION_OBJECT_NONE = 0, @@ -405,6 +430,9 @@ typedef enum _BCD_APPLICATION_OBJECT_TYPE BCD_APPLICATION_OBJECT_RESERVED = 0xFFFFF // 0x000fffff } BCD_APPLICATION_OBJECT_TYPE; +/** + * The BCD_APPLICATION_IMAGE_TYPE enumeration represents the types of images for BCD applications. + */ typedef enum _BCD_APPLICATION_IMAGE_TYPE { BCD_APPLICATION_IMAGE_NONE, @@ -414,6 +442,9 @@ typedef enum _BCD_APPLICATION_IMAGE_TYPE BCD_APPLICATION_IMAGE_REALMODE_CODE, // 0x00400000 } BCD_APPLICATION_IMAGE_TYPE; +/** + * The BCD_INHERITED_CLASS_TYPE enumeration represents the classes of inherited BCD objects. + */ typedef enum _BCD_INHERITED_CLASS_TYPE { BCD_INHERITED_CLASS_NONE, @@ -422,24 +453,68 @@ typedef enum _BCD_INHERITED_CLASS_TYPE BCD_INHERITED_CLASS_DEVICE } BCD_INHERITED_CLASS_TYPE; +/** + * Constructs a BCD (Boot Configuration Data) object identifier with the specified + * object type, image type, and application type into a single ULONG value. + * \param ObjectType The type of the BCD object (placed in the highest 4 bits). + * \param ImageType The type of the image (placed in the next 4 bits). + * \param ApplicationType The type of the application (placed in the lowest 20 bits). + * \returns A ULONG value representing the combined BCD object identifier. + * \remarks Bit Layout: + * | 31 ... 28 | 27 ... 24 | 23 ... 20 | 19 .......... 0 | + * | ObjectType| Reserved | ImageType | ApplicationType | + */ #define MAKE_BCD_OBJECT(ObjectType, ImageType, ApplicationType) \ (((ULONG)(ObjectType) << 28) | \ (((ULONG)(ImageType) & 0xF) << 20) | \ ((ULONG)(ApplicationType) & 0xFFFFF)) +/** + * Constructs a BCD (Boot Configuration Data) application object identifier. + * This macro creates a BCD object identifier for an application by combining the object type, + * image type, and application type into a single value using the MAKE_BCD_OBJECT macro. + * \param ImageType The type of the image (e.g., Windows Boot Loader, Windows Resume Application). + * \param ApplicationType The specific application type within the image type. + * \return A value representing the BCD application object identifier. + */ #define MAKE_BCD_APPLICATION_OBJECT(ImageType, ApplicationType) \ MAKE_BCD_OBJECT(BCD_OBJECT_TYPE_APPLICATION, (ULONG)(ImageType), (ULONG)(ApplicationType)) +/** + * Macro to extract the BCD (Boot Configuration Data) object type from a given DataType value. + * The macro shifts the input DataType 28 bits to the right and masks the result with 0xF, + * effectively extracting the upper 4 bits, which represent the BCD object type. + * \param DataType The value containing the BCD object type in its upper 4 bits. + * \return The extracted BCD_OBJECT_TYPE value. + */ #define GET_BCD_OBJECT_TYPE(DataType) \ - ((BCD_OBJECT_TYPE)(((((ULONG)DataType)) >> 28) & 0xF)) + ((BCD_OBJECT_TYPE)(((((ULONG)(DataType))) >> 28) & 0xF)) + +/** + * Extracts the BCD (Boot Configuration Data) application image type from a given data type value. + * This macro shifts the input value 20 bits to the right and masks the result with 0xF (4 bits), + * effectively extracting bits 20-23, which represent the BCD application image type. + * \param DataType The value containing the BCD application image type encoded in bits 20-23. + * \return The extracted BCD_APPLICATION_IMAGE_TYPE value. + */ #define GET_BCD_APPLICATION_IMAGE(DataType) \ - ((BCD_APPLICATION_IMAGE_TYPE)(((((ULONG)DataType)) >> 20) & 0xF)) + ((BCD_APPLICATION_IMAGE_TYPE)(((((ULONG)(DataType))) >> 20) & 0xF)) + +/** + * Macro to extract the BCD application object type from a given data type value. + * \param DataType The value containing the BCD application object type information. + * \return The extracted BCD_APPLICATION_OBJECT_TYPE, obtained by masking the lower 20 bits of DataType. + */ #define GET_BCD_APPLICATION_OBJECT(DataType) \ - ((BCD_APPLICATION_OBJECT_TYPE)((((ULONG)DataType)) & 0xFFFFF)) + ((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) +/** + * The BCD_OBJECT_DATATYPE provides multiple views of the packed value for different BCD (Boot Configuration Data) objects. + * \remarks This union allows for flexible interpretation of BCD object data depending on the context in which it is used. + */ typedef union _BCD_OBJECT_DATATYPE { ULONG PackedValue; @@ -476,18 +551,34 @@ static_assert(sizeof(BCD_OBJECT_DATATYPE) == sizeof(ULONG), "sizeof(BCD_OBJECT_D #define BCD_OBJECT_DESCRIPTION_VERSION 0x1 +/** + * The BCD_OBJECT_DESCRIPTION structure contains metadata about a BCD object, including its version and type. + */ typedef struct _BCD_OBJECT_DESCRIPTION { ULONG Version; // BCD_OBJECT_DESCRIPTION_VERSION ULONG Type; // BCD_OBJECT_DATATYPE } BCD_OBJECT_DESCRIPTION, *PBCD_OBJECT_DESCRIPTION; +/** + * The BCD_OBJECT structure contains the identifier and description of a BCD object. + */ typedef struct _BCD_OBJECT { - GUID Identifer; + GUID Identifier; PBCD_OBJECT_DESCRIPTION Description; } BCD_OBJECT, *PBCD_OBJECT; +/** + * The BcdEnumerateObjects function enumerates BCD objects in the specified BCD store. + * + * \param BcdStoreHandle Handle to the BCD store. + * \param BcdEnumDescriptor Pointer to a BCD_OBJECT_DESCRIPTION structure that specifies the type of objects to enumerate. + * \param Buffer Optional pointer to a buffer that receives an array of BCD_OBJECT structures. + * \param BufferSize On input, the size of the buffer in bytes. On output, the required or actual size. + * \param ObjectCount Receives the number of objects returned. + * \return NTSTATUS Successful or errant status. + */ NTSYSAPI NTSTATUS NTAPI @@ -499,25 +590,48 @@ BcdEnumerateObjects( _Out_ PULONG ObjectCount ); +/** + * The BcdOpenObject function opens a BCD object by its identifier. + * + * \param BcdStoreHandle Handle to the BCD store. + * \param Identifier Pointer to the GUID of the object to open. + * \param BcdObjectHandle Receives the handle to the opened BCD object. + * \return NTSTATUS Successful or errant status. + */ NTSYSAPI NTSTATUS NTAPI BcdOpenObject( _In_ HANDLE BcdStoreHandle, - _In_ const GUID* Identifier, + _In_ PCGUID Identifier, _Out_ PHANDLE BcdObjectHandle ); +/** + * The BcdCreateObject function creates a new BCD object in the specified store. + * + * \param BcdStoreHandle Handle to the BCD store. + * \param Identifier Pointer to the GUID for the new object. + * \param Description Pointer to a BCD_OBJECT_DESCRIPTION structure describing the object. + * \param BcdObjectHandle Receives the handle to the created BCD object. + * \return NTSTATUS Successful or errant status. + */ NTSYSAPI NTSTATUS NTAPI BcdCreateObject( _In_ HANDLE BcdStoreHandle, - _In_ PGUID Identifier, + _In_ PCGUID Identifier, _In_ PBCD_OBJECT_DESCRIPTION Description, _Out_ PHANDLE BcdObjectHandle ); +/** + * The BcdDeleteObject function deletes a BCD object. + * + * \param BcdObjectHandle Handle to the BCD object to delete. + * \return NTSTATUS Successful or errant status. + */ NTSYSAPI NTSTATUS NTAPI @@ -525,6 +639,12 @@ BcdDeleteObject( _In_ HANDLE BcdObjectHandle ); +/** + * The BcdCloseObject function closes a handle to a BCD object. + * + * \param BcdObjectHandle Handle to the BCD object to close. + * \return NTSTATUS Successful or errant status. + */ NTSYSAPI NTSTATUS NTAPI @@ -532,6 +652,11 @@ BcdCloseObject( _In_ HANDLE BcdObjectHandle ); +/** + * The BCD_COPY_FLAGS specify the behavior of Boot Configuration Data (BCD) copy operations, + * controlling how objects and elements are handled during BCD copy procedures. + */ +_Enum_is_bitflag_ typedef enum _BCD_COPY_FLAGS { BCD_COPY_NONE = 0x0, @@ -542,7 +667,18 @@ typedef enum _BCD_COPY_FLAGS BCD_COPY_RETAIN_ELEMENT_DATA = 0x10, BCD_COPY_MIGRATE_ELEMENT_DATA = 0x20 } BCD_COPY_FLAGS; +DEFINE_ENUM_FLAG_OPERATORS(BCD_COPY_FLAGS); +/** + * The BcdCopyObject function copies a BCD object from one store to another. + * + * \param BcdStoreHandle Handle to the source BCD store. + * \param BcdObjectHandle Handle to the BCD object to copy. + * \param BcdCopyFlags Flags that control the copy operation. + * \param TargetStoreHandle Handle to the target BCD store. + * \param TargetObjectHandle Receives the handle to the copied BCD object in the target store. + * \return NTSTATUS Successful or errant status. + */ NTSYSAPI NTSTATUS NTAPI @@ -554,6 +690,17 @@ BcdCopyObject( _Out_ PHANDLE TargetObjectHandle ); +/** + * The BcdCopyObjectEx function copies a BCD object from one store to another, specifying the target object identifier. + * + * \param BcdStoreHandle Handle to the source BCD store. + * \param BcdObjectHandle Handle to the BCD object to copy. + * \param BcdCopyFlags Flags that control the copy operation. + * \param TargetStoreHandle Handle to the target BCD store. + * \param TargetObjectId Pointer to the GUID for the new object in the target store. + * \param TargetObjectHandle Receives the handle to the copied BCD object in the target store. + * \return NTSTATUS Successful or errant status. + */ NTSYSAPI NTSTATUS NTAPI @@ -562,10 +709,19 @@ BcdCopyObjectEx( _In_ HANDLE BcdObjectHandle, _In_ BCD_COPY_FLAGS BcdCopyFlags, _In_ HANDLE TargetStoreHandle, - _In_ PGUID TargetObjectId, + _In_ PCGUID TargetObjectId, _Out_ PHANDLE TargetObjectHandle ); +/** + * The BcdCopyObjects function copies multiple BCD objects from one store to another based on specified characteristics. + * + * \param BcdStoreHandle Handle to the source BCD store. + * \param Characteristics Pointer to a BCD_OBJECT_DESCRIPTION structure specifying the objects to copy. + * \param BcdCopyFlags Flags that control the copy operation. + * \param TargetStoreHandle Handle to the target BCD store. + * \return NTSTATUS Successful or errant status. + */ NTSYSAPI NTSTATUS NTAPI @@ -576,6 +732,14 @@ BcdCopyObjects( _In_ HANDLE TargetStoreHandle ); +/** + * The BcdMigrateObjectElementValues function migrates element values from a source BCD object to a target BCD object using a template. + * + * \param TemplateObjectHandle Handle to the template BCD object. + * \param SourceObjectHandle Handle to the source BCD object. + * \param TargetObjectHandle Handle to the target BCD object. + * \return NTSTATUS Successful or errant status. + */ NTSYSAPI NTSTATUS NTAPI @@ -585,6 +749,15 @@ BcdMigrateObjectElementValues( _In_ HANDLE TargetObjectHandle ); +/** + * The BcdQueryObject function queries a BCD object for its description and identifier. + * + * \param BcdObjectHandle Handle to the BCD object to query. + * \param BcdVersion The version of the BCD object description structure (use BCD_OBJECT_DESCRIPTION_VERSION). + * \param Description Receives the BCD_OBJECT_DESCRIPTION structure for the object. + * \param Identifier Receives the GUID identifier of the object. + * \return NTSTATUS Successful or errant status. + */ NTSYSAPI NTSTATUS NTAPI @@ -595,6 +768,9 @@ BcdQueryObject( _Out_ PGUID Identifier ); +/** + * The BCD_ELEMENT_DATATYPE_FORMAT enumeration represents the data formats for BCD elements. + */ typedef enum _BCD_ELEMENT_DATATYPE_FORMAT { BCD_ELEMENT_DATATYPE_FORMAT_UNKNOWN, @@ -608,6 +784,9 @@ typedef enum _BCD_ELEMENT_DATATYPE_FORMAT BCD_ELEMENT_DATATYPE_FORMAT_BINARY // 0x08000000 } BCD_ELEMENT_DATATYPE_FORMAT; +/** + * The BCD_ELEMENT_DATATYPE_CLASS enumeration represents the classes for BCD elements. + */ typedef enum _BCD_ELEMENT_DATATYPE_CLASS { BCD_ELEMENT_DATATYPE_CLASS_NONE, @@ -618,6 +797,9 @@ typedef enum _BCD_ELEMENT_DATATYPE_CLASS BCD_ELEMENT_DATATYPE_CLASS_OEM // 0x50000000 } BCD_ELEMENT_DATATYPE_CLASS; +/** + * The BCD_ELEMENT_DEVICE_TYPE enumeration represents the types of devices for BCD elements. + */ typedef enum _BCD_ELEMENT_DEVICE_TYPE { BCD_ELEMENT_DEVICE_TYPE_NONE, @@ -633,16 +815,47 @@ typedef enum _BCD_ELEMENT_DEVICE_TYPE BCD_ELEMENT_DEVICE_TYPE_COMPOSITE } BCD_ELEMENT_DEVICE_TYPE; +/** + * Macro to construct a BCD element data type value from its class, format, and subtype. + * + * \param Class The class of the BCD element. + * \param Format The format of the BCD element data. + * \param Subtype The subtype identifier for the element. + * \return A ULONG value representing the combined BCD element data type. + */ #define MAKE_BCDE_DATA_TYPE(Class, Format, Subtype) \ - (((((ULONG)Class) & 0xF) << 28) | ((((ULONG)Format) & 0xF) << 24) | (((ULONG)Subtype) & 0x00FFFFFF)) + (((((ULONG)(Class)) & 0xF) << 28) | ((((ULONG)(Format)) & 0xF) << 24) | (((ULONG)(Subtype)) & 0x00FFFFFF)) +/** + * Macro to extract the BCD element class from a given data type value. + * + * \param DataType The value containing the BCD element information. + * \return The extracted BCD_ELEMENT_DATATYPE_CLASS. + */ #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)) + ((BCD_ELEMENT_DATATYPE_CLASS)(((((ULONG)(DataType))) >> 28) & 0xF)) +/** + * Macro to extract the BCD element data format from a given data type value. + * + * \param DataType The value containing the BCD element information. + * \return The extracted BCD_ELEMENT_DATATYPE_FORMAT. + */ +#define GET_BCDE_DATA_FORMAT(DataType) \ + ((BCD_ELEMENT_DATATYPE_FORMAT)(((((ULONG)(DataType))) >> 24) & 0xF)) + +/** + * Macro to extract the BCD element subtype identifier from a given data type value. + * + * \param DataType The value containing the BCD element information. + * \return The extracted subtype identifier as a ULONG value. + */ +#define GET_BCDE_DATA_SUBTYPE(DataType) \ + ((ULONG)((((ULONG)(DataType))) & 0x00FFFFFF)) + +/** + * The BCD_ELEMENT_DATATYPE union represents the data type for a BCD element. + */ typedef union _BCD_ELEMENT_DATATYPE { ULONG PackedValue; @@ -656,6 +869,16 @@ typedef union _BCD_ELEMENT_DATATYPE static_assert(sizeof(BCD_ELEMENT_DATATYPE) == sizeof(ULONG), "sizeof(BCD_ELEMENT_DATATYPE) is invalid."); +/** + * The BcdEnumerateElementTypes function enumerates the element types present in a specified BCD object. + * + * \param BcdObjectHandle Handle to the BCD object whose element types are to be enumerated. + * \param Buffer Optional pointer to a buffer that receives an array of BCD_ELEMENT_DATATYPE values. + * If this parameter is NULL, the function will return the required buffer size in BufferSize. + * \param BufferSize On input, specifies the size of the buffer in bytes. On output, receives the required or actual size of the buffer. + * \param ElementCount Receives the number of element types returned in the buffer. + * \return NTSTATUS Successful or errant status. + */ NTSYSAPI NTSTATUS NTAPI @@ -666,6 +889,9 @@ BcdEnumerateElementTypes( _Out_ PULONG ElementCount ); +/** + * The BCD_ELEMENT_DEVICE_QUALIFIED_PARTITION structure contains information about a qualified partition. + */ typedef struct _BCD_ELEMENT_DEVICE_QUALIFIED_PARTITION { ULONG PartitionStyle; @@ -685,6 +911,9 @@ typedef struct _BCD_ELEMENT_DEVICE_QUALIFIED_PARTITION }; } BCD_ELEMENT_DEVICE_QUALIFIED_PARTITION, *PBCD_ELEMENT_DEVICE_QUALIFIED_PARTITION; +/** + * The BCD_ELEMENT_DEVICE structure contains information about a BCD device element. + */ typedef struct _BCD_ELEMENT_DEVICE { ULONG DeviceType; @@ -719,31 +948,49 @@ typedef struct _BCD_ELEMENT_DEVICE }; } BCD_ELEMENT_DEVICE, *PBCD_ELEMENT_DEVICE; +/** + * The BCD_ELEMENT_STRING structure contains a string value for a BCD element. + */ typedef struct _BCD_ELEMENT_STRING { WCHAR Value[ANYSIZE_ARRAY]; } BCD_ELEMENT_STRING, *PBCD_ELEMENT_STRING; +/** + * The BCD_ELEMENT_OBJECT structure contains a GUID value for a BCD object element. + */ typedef struct _BCD_ELEMENT_OBJECT { GUID Object; } BCD_ELEMENT_OBJECT, *PBCD_ELEMENT_OBJECT; +/** + * The BCD_ELEMENT_OBJECT_LIST structure contains a list of GUIDs for a BCD object list element. + */ typedef struct _BCD_ELEMENT_OBJECT_LIST { GUID ObjectList[ANYSIZE_ARRAY]; } BCD_ELEMENT_OBJECT_LIST, *PBCD_ELEMENT_OBJECT_LIST; +/** + * The BCD_ELEMENT_INTEGER structure contains a 64-bit integer value for a BCD element. + */ typedef struct _BCD_ELEMENT_INTEGER { ULONG64 Value; } BCD_ELEMENT_INTEGER, *PBCD_ELEMENT_INTEGER; +/** + * The BCD_ELEMENT_INTEGER_LIST structure contains a list of 64-bit integers for a BCD element. + */ typedef struct _BCD_ELEMENT_INTEGER_LIST { ULONG64 Value[ANYSIZE_ARRAY]; } BCD_ELEMENT_INTEGER_LIST, *PBCD_ELEMENT_INTEGER_LIST; +/** + * The BCD_ELEMENT_BOOLEAN structure contains a boolean value for a BCD element. + */ typedef struct _BCD_ELEMENT_BOOLEAN { BOOLEAN Value; @@ -752,6 +999,9 @@ typedef struct _BCD_ELEMENT_BOOLEAN #define BCD_ELEMENT_DESCRIPTION_VERSION 0x1 +/** + * The BCD_ELEMENT_DESCRIPTION structure contains information about a BCD element. + */ typedef struct BCD_ELEMENT_DESCRIPTION { ULONG Version; // BCD_ELEMENT_DESCRIPTION_VERSION @@ -759,12 +1009,25 @@ typedef struct BCD_ELEMENT_DESCRIPTION ULONG DataSize; } BCD_ELEMENT_DESCRIPTION, *PBCD_ELEMENT_DESCRIPTION; +/** + * The BCD_ELEMENT structure contains information about a BCD element. + */ typedef struct _BCD_ELEMENT { PBCD_ELEMENT_DESCRIPTION Description; PVOID Data; } BCD_ELEMENT, *PBCD_ELEMENT; +/** + * The BcdEnumerateElements function enumerates the elements present in a specified BCD object. + * + * \param BcdObjectHandle Handle to the BCD object whose elements are to be enumerated. + * \param Buffer Optional pointer to a buffer that receives an array of BCD_ELEMENT structures. + * If this parameter is NULL, the function will return the required buffer size in BufferSize. + * \param BufferSize On input, specifies the size of the buffer in bytes. On output, receives the required or actual size of the buffer. + * \param ElementCount Receives the number of elements returned in the buffer. + * \return NTSTATUS Successful or errant status. + */ NTSYSAPI NTSTATUS NTAPI @@ -775,6 +1038,10 @@ BcdEnumerateElements( _Out_ PULONG ElementCount ); +/** + * The BCD_FLAGS enumeration defines flags that control the behavior of BCD object enumeration, + * device translation, and policy checks in the context of system boot configuration. + */ typedef enum _BCD_FLAGS { BCD_FLAG_NONE = 0x0, @@ -788,6 +1055,17 @@ typedef enum _BCD_FLAGS BCD_FLAG_DISABLE_POLICY_CHECKS = 0x80 } BCD_FLAGS; +/** + * The BcdEnumerateElementsWithFlags function enumerates the elements present in a specified BCD object, using additional flags to control enumeration behavior. + * + * \param BcdObjectHandle Handle to the BCD object whose elements are to be enumerated. + * \param BcdFlags Flags that control the enumeration behavior (see BCD_FLAGS). + * \param Buffer Optional pointer to a buffer that receives an array of BCD_ELEMENT structures. + * If this parameter is NULL, the function will return the required buffer size in BufferSize. + * \param BufferSize On input, specifies the size of the buffer in bytes. On output, receives the required or actual size of the buffer. + * \param ElementCount Receives the number of elements returned in the buffer. + * \return NTSTATUS Successful or errant status. + */ NTSYSAPI NTSTATUS NTAPI @@ -799,6 +1077,18 @@ BcdEnumerateElementsWithFlags( _Out_ PULONG ElementCount ); +/** + * The BcdEnumerateAndUnpackElements function enumerates and unpacks the elements of a specified BCD object from a BCD store, using additional flags. + * + * \param BcdStoreHandle Handle to the BCD store. + * \param BcdObjectHandle Handle to the BCD object whose elements are to be enumerated and unpacked. + * \param BcdFlags Flags that control the enumeration and unpacking behavior. + * \param Buffer Optional pointer to a buffer that receives an array of BCD_ELEMENT structures. + * If this parameter is NULL, the function will return the required buffer size in BufferSize. + * \param BufferSize On input, specifies the size of the buffer in bytes. On output, receives the required or actual size of the buffer. + * \param ElementCount Receives the number of elements returned in the buffer. + * \return NTSTATUS Successful or errant status. + */ NTSYSAPI NTSTATUS NTAPI @@ -811,6 +1101,16 @@ BcdEnumerateAndUnpackElements( _Out_ PULONG ElementCount ); +/** + * The BcdGetElementData function retrieves the data for a specified element in a BCD object. + * + * \param BcdObjectHandle Handle to the BCD object. + * \param BcdElement The element type to retrieve (BCD_ELEMENT_DATATYPE). + * \param Buffer Optional pointer to a buffer that receives the element data. + * If this parameter is NULL, the function will return the required buffer size in BufferSize. + * \param BufferSize On input, specifies the size of the buffer in bytes. On output, receives the required or actual size of the buffer. + * \return NTSTATUS Successful or errant status. + */ NTSYSAPI NTSTATUS NTAPI @@ -821,6 +1121,17 @@ BcdGetElementData( _Inout_ PULONG BufferSize ); +/** + * The BcdGetElementDataWithFlags function retrieves the data for a specified element in a BCD object, using additional flags. + * + * \param BcdObjectHandle Handle to the BCD object. + * \param BcdElement The element type to retrieve (BCD_ELEMENT_DATATYPE). + * \param BcdFlags Flags that control the retrieval behavior. + * \param Buffer Optional pointer to a buffer that receives the element data. + * If this parameter is NULL, the function will return the required buffer size in BufferSize. + * \param BufferSize On input, specifies the size of the buffer in bytes. On output, receives the required or actual size of the buffer. + * \return NTSTATUS Successful or errant status. + */ NTSYSAPI NTSTATUS NTAPI @@ -832,6 +1143,15 @@ BcdGetElementDataWithFlags( _Inout_ PULONG BufferSize ); +/** + * The BcdSetElementData function sets the data for a specified element in a BCD object. + * + * \param BcdObjectHandle Handle to the BCD object. + * \param BcdElement The element type to set (BCD_ELEMENT_DATATYPE). + * \param Buffer Pointer to the buffer containing the data to set. + * \param BufferSize The size of the buffer in bytes. + * \return NTSTATUS Successful or errant status. + */ NTSYSAPI NTSTATUS NTAPI @@ -842,6 +1162,16 @@ BcdSetElementData( _In_ ULONG BufferSize ); +/** + * The BcdSetElementDataWithFlags function sets the data for a specified element in a BCD object, using additional flags. + * + * \param BcdObjectHandle Handle to the BCD object. + * \param BcdElement The element type to set (BCD_ELEMENT_DATATYPE). + * \param BcdFlags Flags that control the set operation. + * \param Buffer Pointer to the buffer containing the data to set. + * \param BufferSize The size of the buffer in bytes. + * \return NTSTATUS Successful or errant status. + */ NTSYSAPI NTSTATUS NTAPI @@ -853,6 +1183,13 @@ BcdSetElementDataWithFlags( _In_ ULONG BufferSize ); +/** + * The BcdDeleteElement function deletes a specified element from a BCD object. + * + * \param BcdObjectHandle Handle to the BCD object. + * \param BcdElement The element type to delete (BCD_ELEMENT_DATATYPE). + * \return NTSTATUS Successful or errant status. + */ NTSYSAPI NTSTATUS NTAPI @@ -865,95 +1202,145 @@ BcdDeleteElement( // Element types // +/** + * Specifies the device object element types. + * \sa https://learn.microsoft.com/en-us/previous-versions/windows/desktop/bcd/bcddeviceobjectelementtypes + */ +typedef enum BcdDeviceObjectElementTypes +{ + // The RAM disk image offset. The element data format is BcdIntegerElement. + BcdDeviceInteger_RamdiskImageOffset = 0x35000001, + // The IP port number to be used for Trivial File Transfer Protocol (TFTP) reads. The element data format is BcdIntegerElement. + BcdDeviceInteger_TftpClientPort = 0x35000002, + // The device that contains the SDI object. The element data format is BcdDeviceElement. + BcdDeviceInteger_SdiDevice = 0x31000003, + // The path from the root of the SDI device to the RAM disk file. The element data format is BcdStringElement. + BcdDeviceInteger_SdiPath = 0x32000004, + // The length of the image for the RAM disk. The element data format is BcdIntegerElement. + BcdDeviceInteger_RamdiskImageLength = 0x35000005, + // Enables exporting the RAM disk as a CD. The element data format is BcdBooleanElement. + BcdDeviceBoolean_RamdiskExportAsCd = 0x36000006, + // Defines the TFTP block size for the RAM disk Windows Imaging (WIM) file. The element data format is BcdIntegerElement. + BcdDeviceInteger_RamdiskTftpBlockSize = 0x36000007, + // Defines the TFTP window size for the RAM disk WIM file. The element data format is BcdIntegerElement. + BcdDeviceInteger_RamdiskTftpWindowSize = 0x36000008, + // Enables or disables multicast for the RAM disk WIM file. The element data format is BcdBooleanElement. + BcdDeviceBoolean_RamdiskMulticastEnabled = 0x36000009, + // Enables fallback to TFTP if multicast fails. The element data format is BcdBooleanElement. + BcdDeviceBoolean_RamdiskMulticastTftpFallback = 0x3600000A, + // Enables or disables the TFTP variable window size extension. The element data format is BcdBooleanElement. + BcdDeviceBoolean_RamdiskTftpVarWindow = 0x3600000B +} BcdDeviceObjectElementTypes; + /** * BCD configuration elements for the Boot Manager types. */ typedef enum _BcdBootMgrElementTypes { - /** - * The order in which BCD objects should be displayed. [0x24000001] - * Objects are displayed using the string specified by the BcdLibraryString_Description element. - */ + /// + /// The order in which BCD objects should be displayed. + /// Objects are displayed using the string specified by the BcdLibraryString_Description element. + /// + /// 0x24000001 - BCDE_BOOTMGR_TYPE_DISPLAY_ORDER BcdBootMgrObjectList_DisplayOrder = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_OBJECTLIST, 1), - /** - * List of boot environment applications the boot manager should execute. [0x24000002] - * 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. - */ + /// + /// 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. + /// + /// 0x24000002 - BCDE_BOOTMGR_TYPE_BOOT_SEQUENCE BcdBootMgrObjectList_BootSequence = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_OBJECTLIST, 2), - /** - * The default boot environment application to load if the user does not select one. [0x23000003] - */ + /// + /// The default boot environment application to load if the user does not select one. + /// + /// 0x23000003 - BCDE_BOOTMGR_TYPE_DEFAULT_OBJECT BcdBootMgrObject_DefaultObject = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_OBJECT, 3), - /** - * The maximum number of seconds a boot selection menu is to be displayed to the user. [0x25000004] - * 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. - */ + /// + /// 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. + /// + /// 0x25000004 - BCDE_BOOTMGR_TYPE_TIMEOUT BcdBootMgrInteger_Timeout = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_INTEGER, 4), - /** - * Indicates that a resume operation should be attempted during a system restart. [0x26000005] - */ + /// + /// Indicates that a resume operation should be attempted during a system restart. + /// + /// 0x26000005 - BCDE_BOOTMGR_TYPE_ATTEMPT_RESUME BcdBootMgrBoolean_AttemptResume = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_BOOLEAN, 5), - /** - * The resume application object. [0x23000006] - */ + /// + /// The resume application object. + /// + /// 0x23000006 - BCDE_BOOTMGR_TYPE_RESUME_OBJECT BcdBootMgrObject_ResumeObject = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_OBJECT, 6), - /** - * The startup sequence. [0x24000007] - */ + /// + /// The startup sequence. + /// + /// 0x24000007 - BCDE_BOOTMGR_TYPE_STARTUP_SEQUENCE BcdBootMgrObjectList_StartupSequence = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_OBJECTLIST, 7), - /** - * The boot manager tools display order list. [0x24000010] - */ + /// + /// The boot manager tools display order list. + /// + /// 0x24000010 - BCDE_BOOTMGR_TYPE_TOOLS_DISPLAY_ORDER BcdBootMgrObjectList_ToolsDisplayOrder = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_OBJECTLIST, 16), - /** - * Forces the display of the legacy boot menu, regardless of the number of OS entries in the BCD store and their BcdOSLoaderInteger_BootMenuPolicy. [0x26000020] - */ + /// + /// Forces the display of the legacy boot menu, regardless of the number of OS entries in the BCD store and their BcdOSLoaderInteger_BootMenuPolicy. + /// + /// 0x26000020 - BCDE_BOOTMGR_TYPE_DISPLAY_BOOT_MENU BcdBootMgrBoolean_DisplayBootMenu = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_BOOLEAN, 32), - /** - * 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. [0x26000021] - */ + /// + /// 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. + /// + /// 0x26000021 - BCDE_BOOTMGR_TYPE_NO_ERROR_DISPLAY BcdBootMgrBoolean_NoErrorDisplay = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_BOOLEAN, 33), - /** - * The device on which the boot application resides. [0x21000022] - */ + /// + /// The device on which the boot application resides. + /// + /// 0x21000022 - BCDE_BOOTMGR_TYPE_BCD_DEVICE BcdBootMgrDevice_BcdDevice = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_DEVICE, 34), - /** - * The boot application. [0x22000023] (BCDE_BOOTMGR_TYPE_BCD_FILEPATH) - */ + /// + /// The boot application. + /// + /// 0x22000023 - BCDE_BOOTMGR_TYPE_BCD_FILEPATH BcdBootMgrString_BcdFilePath = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_STRING, 35), - /** - * Indicates whether HORM (Hibernate Once/Resume Many) is enabled. [0x26000024] - */ + /// + /// Indicates whether HORM (Hibernate Once/Resume Many) is enabled. + /// + /// 0x26000024 - BCDE_BOOTMGR_TYPE_HIBERBOOT BcdBootMgrBoolean_HormEnabled = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_BOOLEAN, 36), - /** - * Indicates whether the system is in hibernation root mode. [0x26000025] - */ + /// + /// Indicates whether the system is in hibernation root mode. + /// + /// 0x26000025 - BCDE_BOOTMGR_TYPE_NEXT_ENTRY_ON_FAILURE BcdBootMgrBoolean_HiberRoot = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_BOOLEAN, 37), - /** - * The password override string. [0x22000026] - */ + /// + /// The password override string. + /// + /// 0x22000026 - BCDE_BOOTMGR_TYPE_FVE_RECOVERY_MESSAGE BcdBootMgrString_PasswordOverride = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_STRING, 38), - /** - * The PIN/passphrase override string. [0x22000027] - */ + /// + /// The PIN/passphrase override string. + /// + /// 0x22000027 - BCDE_BOOTMGR_TYPE_FVE_RECOVERY_URL BcdBootMgrString_PinpassPhraseOverride = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_STRING, 39), - /** - * Controls whether custom actions are processed before a boot sequence. Note This value is supported starting in Windows 8 and Windows Server 2012. [0x26000028] - */ + /// + /// Controls whether custom actions are processed before a boot sequence. Note This value is supported starting in Windows 8 and Windows Server 2012. + /// + /// 0x26000028 - BCDE_BOOTMGR_TYPE_PROCESS_CUSTOM_ACTIONS_FIRST BcdBootMgrBoolean_ProcessCustomActionsFirst = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_BOOLEAN, 40), - /** - * Custom Bootstrap Actions. [0x27000030] (BCDE_BOOTMGR_TYPE_CUSTOM_ACTIONS_LIST) - */ + /// + /// Custom Bootstrap Actions. + /// + /// 0x27000030 - BCDE_BOOTMGR_TYPE_CUSTOM_ACTIONS_LIST BcdBootMgrIntegerList_CustomActionsList = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_INTEGERLIST, 48), - /** - * Controls whether a boot sequence persists across multiple boots. Note This value is supported starting in Windows 8 and Windows Server 2012. [0x26000031] - */ + /// + /// Controls whether a boot sequence persists across multiple boots. Note This value is supported starting in Windows 8 and Windows Server 2012. + /// + /// 0x26000031 - BCDE_BOOTMGR_TYPE_PERSIST_BOOT_SEQUENCE BcdBootMgrBoolean_PersistBootSequence = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_BOOLEAN, 49), - /** - * Indicates whether to skip the startup sequence. [0x26000032] - */ + /// + /// Indicates whether to skip the startup sequence. + /// + /// 0x26000032 - BCDE_BOOTMGR_TYPE_SKIP_STARTUP_SEQUENCE BcdBootMgrBoolean_SkipStartupSequence = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_BOOLEAN, 50), } BcdBootMgrElementTypes; @@ -1026,15 +1413,15 @@ typedef enum _BcdLibrary_ConfigAccessPolicy */ typedef enum _BcdLibrary_UxDisplayMessageType { - DisplayMessageTypeDefault = 0, /**< Default display message type. */ - DisplayMessageTypeResume = 1, /**< Display message type for resume. */ - DisplayMessageTypeHyperV = 2, /**< Display message type for Hyper-V. */ - DisplayMessageTypeRecovery = 3, /**< Display message type for recovery. */ - DisplayMessageTypeStartupRepair = 4, /**< Display message type for startup repair. */ - DisplayMessageTypeSystemImageRecovery = 5, /**< Display message type for system image recovery. */ - DisplayMessageTypeCommandPrompt = 6, /**< Display message type for command prompt. */ - DisplayMessageTypeSystemRestore = 7, /**< Display message type for system restore. */ - DisplayMessageTypePushButtonReset = 8 /**< Display message type for push button reset. */ + DisplayMessageTypeDefault = 0, // Default display message type. + DisplayMessageTypeResume = 1, // Display message type for resume. + DisplayMessageTypeHyperV = 2, // Display message type for Hyper-V. + DisplayMessageTypeRecovery = 3, // Display message type for recovery. + DisplayMessageTypeStartupRepair = 4, // Display message type for startup repair. + DisplayMessageTypeSystemImageRecovery = 5, // Display message type for system image recovery. + DisplayMessageTypeCommandPrompt = 6, // Display message type for command prompt. + DisplayMessageTypeSystemRestore = 7, // Display message type for system restore. + DisplayMessageTypePushButtonReset = 8 // Display message type for push button reset. } BcdLibrary_UxDisplayMessageType; /** @@ -1141,7 +1528,10 @@ typedef enum _BcdLibraryElementTypes /// 0x1500000E BcdLibraryInteger_AvoidLowPhysicalMemory = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_LIBRARY, BCD_ELEMENT_DATATYPE_FORMAT_INTEGER, 14), /// - /// + /// Indicates whether traditional KSEG mappings are to be used. + /// KSEG refers to the kernel segment address space in Windows NT-based systems, typically mapping physical memory into a fixed virtual address range for the kernel (e.g., KSEG0/KSEG1 in MIPS, or the equivalent region in x86/x64). + /// Traditional KSEG mappings use a static, direct mapping of physical memory for kernel access, as opposed to dynamic or flexible mappings introduced in newer Windows versions. + /// Enabling this option forces the kernel to use legacy, fixed mappings for physical memory, which may be required for compatibility with certain drivers or hardware. /// /// 0x1600000F // alternate name: BCDE_LIBRARY_TYPE_TRADITIONAL_KSEG_MAPPINGS @@ -1220,12 +1610,12 @@ typedef enum _BcdLibraryElementTypes /// 0x1200001D BcdLibraryString_DebuggerNetKey = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_LIBRARY, BCD_ELEMENT_DATATYPE_FORMAT_STRING, 29), /// - /// + /// Indicates whether the network debugger is connected through a virtual machine (VM). /// /// 0x1600001E BcdLibraryBoolean_DebuggerNetVM = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_LIBRARY, BCD_ELEMENT_DATATYPE_FORMAT_BOOLEAN, 30), /// - /// + /// Defines the host IPv6 address for the network debugger. /// /// 0x1200001F BcdLibraryString_DebuggerNetHostIpv6 = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_LIBRARY, BCD_ELEMENT_DATATYPE_FORMAT_STRING, 31), @@ -1251,7 +1641,7 @@ typedef enum _BcdLibraryElementTypes /// 0x12000030 BcdLibraryString_LoadOptionsString = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_LIBRARY, BCD_ELEMENT_DATATYPE_FORMAT_STRING, 48), /// - /// + /// Indicates whether an attempt should be made to start a non-BCD-aware boot application. /// /// 0x16000031 BcdLibraryBoolean_AttemptNonBcdStart = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_LIBRARY, BCD_ELEMENT_DATATYPE_FORMAT_BOOLEAN, 49), @@ -1266,10 +1656,9 @@ typedef enum _BcdLibraryElementTypes /// 0x16000041 BcdLibraryBoolean_DisplayOptionsEdit = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_LIBRARY, BCD_ELEMENT_DATATYPE_FORMAT_BOOLEAN, 65), /// - /// + /// Represents a reference to the address of the FVE (Full Volume Encryption) Key Ring as an integer. /// /// 0x15000042 - // BCDE_LIBRARY_TYPE_FVE_KEYRING_ADDRESS BcdLibraryInteger_FVEKeyRingAddress = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_LIBRARY, BCD_ELEMENT_DATATYPE_FORMAT_INTEGER, 66), /// /// Allows a device override for the bootstat.dat log in the boot manager and winload.exe. @@ -1287,10 +1676,9 @@ typedef enum _BcdLibraryElementTypes /// 0x16000045 BcdLibraryBoolean_BsdPreserveLog = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_LIBRARY, BCD_ELEMENT_DATATYPE_FORMAT_BOOLEAN, 69), /// - /// + /// Indicates whether graphics mode is disabled, requiring boot applications to use text mode display. /// - /// 0x16000046 - // BCDE_LIBRARY_TYPE_GRAPHICS_MODE_DISABLED + /// 0x16000046 - BCDE_LIBRARY_TYPE_GRAPHICS_MODE_DISABLED BcdLibraryBoolean_GraphicsModeDisabled = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_LIBRARY, BCD_ELEMENT_DATATYPE_FORMAT_BOOLEAN, 70), /// /// Indicates the access policy for PCI configuration space. @@ -1312,11 +1700,10 @@ typedef enum _BcdLibraryElementTypes /// /// Overrides the default location of the boot fonts. /// - /// 0x1200004A - // BCDE_LIBRARY_TYPE_FONT_PATH + /// 0x1200004A - BCDE_LIBRARY_TYPE_FONT_PATH BcdLibraryString_FontPath = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_LIBRARY, BCD_ELEMENT_DATATYPE_FORMAT_STRING, 74), /// - /// + /// Specifies the System Integrity Policy (SIP) version. /// /// 0x1500004B BcdLibraryInteger_SiPolicy = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_LIBRARY, BCD_ELEMENT_DATATYPE_FORMAT_INTEGER, 75), @@ -1331,7 +1718,7 @@ typedef enum _BcdLibraryElementTypes /// 0x16000050 BcdLibraryBoolean_ConsoleExtendedInput = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_LIBRARY, BCD_ELEMENT_DATATYPE_FORMAT_BOOLEAN, 80), /// - /// + /// Specifies the initial device for console input. /// /// 0x15000051 BcdLibraryInteger_InitialConsoleInput = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_LIBRARY, BCD_ELEMENT_DATATYPE_FORMAT_INTEGER, 81), @@ -1368,7 +1755,7 @@ typedef enum _BcdLibraryElementTypes /// 0x15000065 BcdLibraryInteger_BootUxDisplayMessage = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_LIBRARY, BCD_ELEMENT_DATATYPE_FORMAT_INTEGER, 101), /// - /// + /// This setting allows setting an integer representing a custom message that will be shown during the boot user experience (Boot UX). /// /// 0x15000066 BcdLibraryInteger_BootUxDisplayMessageOverride = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_LIBRARY, BCD_ELEMENT_DATATYPE_FORMAT_INTEGER, 102), @@ -1393,42 +1780,42 @@ typedef enum _BcdLibraryElementTypes /// 0x1600006A BcdLibraryBoolean_BootUxFadeDisable = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_LIBRARY, BCD_ELEMENT_DATATYPE_FORMAT_BOOLEAN, 106), /// - /// + /// Enables pool reservation debugging for the Boot UX (User Experience) subsystem. /// /// 0x1600006B BcdLibraryBoolean_BootUxReservePoolDebug = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_LIBRARY, BCD_ELEMENT_DATATYPE_FORMAT_BOOLEAN, 107), /// - /// + /// Disables the Boot UX (User Experience) animation subsystem. /// /// 0x1600006C BcdLibraryBoolean_BootUxDisable = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_LIBRARY, BCD_ELEMENT_DATATYPE_FORMAT_BOOLEAN, 108), /// - /// + /// Specifies the number of frames used for the Boot UX fade animation. /// /// 0x1500006D BcdLibraryInteger_BootUxFadeFrames = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_LIBRARY, BCD_ELEMENT_DATATYPE_FORMAT_INTEGER, 109), /// - /// + /// Enables dumping of Boot UX performance statistics. /// /// 0x1600006E BcdLibraryBoolean_BootUxDumpStats = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_LIBRARY, BCD_ELEMENT_DATATYPE_FORMAT_BOOLEAN, 110), /// - /// + /// Enables display of Boot UX performance statistics on screen. /// /// 0x1600006F BcdLibraryBoolean_BootUxShowStats = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_LIBRARY, BCD_ELEMENT_DATATYPE_FORMAT_BOOLEAN, 111), /// - /// + /// Indicates whether the system is configured as a multi-boot system. /// /// 0x16000071 BcdLibraryBoolean_MultiBootSystem = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_LIBRARY, BCD_ELEMENT_DATATYPE_FORMAT_BOOLEAN, 113), /// - /// + /// Disables keyboard input during the boot process. /// /// 0x16000072 BcdLibraryBoolean_ForceNoKeyboard = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_LIBRARY, BCD_ELEMENT_DATATYPE_FORMAT_BOOLEAN, 114), /// - /// + /// Remaps the Windows keyboard key from the standard scan code to the extended scan code. /// /// 0x15000073 BcdLibraryInteger_AliasWindowsKey = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_LIBRARY, BCD_ELEMENT_DATATYPE_FORMAT_INTEGER, 115), @@ -1438,12 +1825,12 @@ typedef enum _BcdLibraryElementTypes /// 0x16000074 BcdLibraryBoolean_BootShutdownDisabled = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_LIBRARY, BCD_ELEMENT_DATATYPE_FORMAT_BOOLEAN, 116), /// - /// + /// Represents the performance counter frequency, in hertz. /// /// 0x15000075 BcdLibraryInteger_PerformanceFrequency = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_LIBRARY, BCD_ELEMENT_DATATYPE_FORMAT_INTEGER, 117), /// - /// + /// This setting is used to configure Secure Boot policies at a low level. /// /// 0x15000076 BcdLibraryInteger_SecurebootRawPolicy = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_LIBRARY, BCD_ELEMENT_DATATYPE_FORMAT_INTEGER, 118), @@ -1454,12 +1841,12 @@ typedef enum _BcdLibraryElementTypes /// 0x17000077 BcdLibraryIntegerList_AllowedInMemorySettings = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_LIBRARY, BCD_ELEMENT_DATATYPE_FORMAT_INTEGER, 119), /// - /// + /// Specifies the duration in milliseconds for the Boot UX bitmap transition effect. /// /// 0x15000079 BcdLibraryInteger_BootUxBitmapTransitionTime = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_LIBRARY, BCD_ELEMENT_DATATYPE_FORMAT_INTEGER, 121), /// - /// + /// Indicates whether two boot images are used during the Boot UX transition animation. /// /// 0x1600007A BcdLibraryBoolean_TwoBootImages = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_LIBRARY, BCD_ELEMENT_DATATYPE_FORMAT_BOOLEAN, 122), @@ -1470,47 +1857,47 @@ typedef enum _BcdLibraryElementTypes /// 0x1600007B BcdLibraryBoolean_ForceFipsCrypto = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_LIBRARY, BCD_ELEMENT_DATATYPE_FORMAT_BOOLEAN, 123), /// - /// + /// Specifies the Boot UX mode for displaying boot errors. /// /// 0x1500007D BcdLibraryInteger_BootErrorUx = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_LIBRARY, BCD_ELEMENT_DATATYPE_FORMAT_INTEGER, 125), /// - /// + /// Allows flight-signed (canary) binaries to be loaded during boot. /// /// 0x1600007E BcdLibraryBoolean_AllowFlightSignatures = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_LIBRARY, BCD_ELEMENT_DATATYPE_FORMAT_BOOLEAN, 126), /// - /// + /// Specifies the format of the boot measurement log for security auditing. /// /// 0x1500007F BcdLibraryInteger_BootMeasurementLogFormat = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_LIBRARY, BCD_ELEMENT_DATATYPE_FORMAT_INTEGER, 127), /// - /// + /// Specifies the display rotation angle (in degrees) to apply during boot. /// /// 0x15000080 BcdLibraryInteger_DisplayRotation = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_LIBRARY, BCD_ELEMENT_DATATYPE_FORMAT_INTEGER, 128), /// - /// + /// Specifies the level of logging for boot measurement. /// /// 0x15000081 BcdLibraryInteger_LogControl = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_LIBRARY, BCD_ELEMENT_DATATYPE_FORMAT_INTEGER, 129), /// - /// + /// Disables BCD (Boot Configuration Data) synchronization with UEFI firmware during boot. /// /// 0x16000082 BcdLibraryBoolean_NoFirmwareSync = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_LIBRARY, BCD_ELEMENT_DATATYPE_FORMAT_BOOLEAN, 130), /// - /// + /// Specifies the Windows system device used for boot. /// /// 0x11000084 BcdLibraryDevice_WindowsSystemDevice = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_LIBRARY, BCD_ELEMENT_DATATYPE_FORMAT_DEVICE, 132), /// - /// + /// Enables the NumLock key during boot. /// /// 0x16000087 BcdLibraryBoolean_NumLockOn = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_LIBRARY, BCD_ELEMENT_DATATYPE_FORMAT_BOOLEAN, 135), /// - /// + /// Additional Code Integrity (CI) policies to be applied during boot. /// /// 0x12000088 BcdLibraryString_AdditionalCiPolicy = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_LIBRARY, BCD_ELEMENT_DATATYPE_FORMAT_STRING, 136), @@ -1524,118 +1911,118 @@ typedef enum _BcdLibraryElementTypes typedef enum _BcdTemplateElementTypes { /// - /// + /// Specifies the device type for the setup boot template. /// /// 0x45000001 BcdSetupInteger_DeviceType = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_SETUPTEMPLATE, BCD_ELEMENT_DATATYPE_FORMAT_INTEGER, 1), /// - /// + /// Specifies the relative path to the boot application for the setup template. /// /// 0x42000002 BcdSetupString_ApplicationRelativePath = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_SETUPTEMPLATE, BCD_ELEMENT_DATATYPE_FORMAT_STRING, 2), /// - /// + /// Specifies the relative path to the RAM disk device for the setup template. /// /// 0x42000003 BcdSetupString_RamdiskDeviceRelativePath = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_SETUPTEMPLATE, BCD_ELEMENT_DATATYPE_FORMAT_STRING, 3), /// - /// + /// Indicates whether to omit OS loader elements when copying objects to the setup template. /// /// 0x46000004 BcdSetupBoolean_OmitOsLoaderElements = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_SETUPTEMPLATE, BCD_ELEMENT_DATATYPE_FORMAT_BOOLEAN, 4), /// - /// + /// Specifies the list of element types to migrate from the setup template. /// /// 0x47000006 BcdSetupIntegerList_ElementsToMigrateList = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_SETUPTEMPLATE, BCD_ELEMENT_DATATYPE_FORMAT_INTEGERLIST, 6), /// - /// + /// Indicates whether the setup template targets the recovery operating system. /// /// 0x46000010 BcdSetupBoolean_RecoveryOs = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_SETUPTEMPLATE, BCD_ELEMENT_DATATYPE_FORMAT_BOOLEAN, 16), } BcdTemplateElementTypes; /** - * @brief Specifies the no-execute page protection policies. + * Specifies the no-execute page protection policies. */ typedef enum _BcdOSLoader_NxPolicy { /** - * @brief The no-execute page protection is off by default. + * The no-execute page protection is off by default. */ NxPolicyOptIn = 0, /** - * @brief The no-execute page protection is on by default. + * The no-execute page protection is on by default. */ NxPolicyOptOut = 1, /** - * @brief The no-execute page protection is always off. + * The no-execute page protection is always off. */ NxPolicyAlwaysOff = 2, /** - * @brief The no-execute page protection is always on. + * The no-execute page protection is always on. */ NxPolicyAlwaysOn = 3 } BcdOSLoader_NxPolicy; /** - * @brief Specifies the Physical Address Extension (PAE) policies. + * Specifies the Physical Address Extension (PAE) policies. */ typedef enum _BcdOSLoader_PAEPolicy { /** - * @brief Enable PAE if hot-pluggable memory is defined above 4GB. + * Enable PAE if hot-pluggable memory is defined above 4GB. */ PaePolicyDefault = 0, /** - * @brief PAE is enabled. + * PAE is enabled. */ PaePolicyForceEnable = 1, /** - * @brief PAE is disabled. + * PAE is disabled. */ PaePolicyForceDisable = 2 } BcdOSLoader_PAEPolicy; /** - * @brief Specifies the boot status policies. + * Specifies the boot status policies. */ typedef enum _BcdOSLoader_BootStatusPolicy { /** - * @brief Display all boot failures. + * Display all boot failures. */ BootStatusPolicyDisplayAllFailures = 0, /** - * @brief Ignore all boot failures. + * Ignore all boot failures. */ BootStatusPolicyIgnoreAllFailures = 1, /** - * @brief Ignore all shutdown failures. + * Ignore all shutdown failures. */ BootStatusPolicyIgnoreShutdownFailures = 2, /** - * @brief Ignore all boot failures. + * Ignore all boot failures. */ BootStatusPolicyIgnoreBootFailures = 3, /** - * @brief Ignore checkpoint failures. + * Ignore checkpoint failures. */ BootStatusPolicyIgnoreCheckpointFailures = 4, /** - * @brief Display shutdown failures. + * Display shutdown failures. */ BootStatusPolicyDisplayShutdownFailures = 5, /** - * @brief Display boot failures. + * Display boot failures. */ BootStatusPolicyDisplayBootFailures = 6, /** - * @brief Display checkpoint failures. + * Display checkpoint failures. */ BootStatusPolicyDisplayCheckpointFailures = 7, /** - * @brief Always display startup failures. + * Always display startup failures. */ BootStatusPolicyAlwaysDisplayStartupFailures = 8 } BcdOSLoaderBootStatusPolicy; @@ -1659,7 +2046,10 @@ typedef enum _BcdOSLoaderElementTypes /// 0x23000003 BcdOSLoaderObject_AssociatedResumeObject = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_OBJECT, 3), /// - /// + /// Indicates whether the OS loader should stamp disks during the boot process. + /// The OS loader writes a stamp or marker to disk(s) during boot for identifying boot disks, tracking boot status, + /// or supporting features like BitLocker or recovery. The marker helps the boot environment recognize which disk + /// was used to boot, and used for diagnostics or recovery. /// /// 0x26000004 BcdOSLoaderBoolean_StampDisks = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_BOOLEAN, 4), @@ -1709,7 +2099,7 @@ typedef enum _BcdOSLoaderElementTypes /// 0x26000025 BcdOSLoaderBoolean_UseLastGoodSettings = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_BOOLEAN, 37), /// - /// + /// Indicates that the system should disable code integrity checks during boot. /// /// 0x26000026 BcdOSLoaderBoolean_DisableCodeIntegrityChecks = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_BOOLEAN, 38), @@ -1737,9 +2127,9 @@ typedef enum _BcdOSLoaderElementTypes /// 0x25000032 BcdOSLoaderInteger_IncreaseUserVa = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_INTEGER, 50), /// - /// BCDE_OSLOADER_TYPE_PERFORMANCE_DATA_MEMORY + /// The amount of memory that should be reserved for performance data. /// - /// 0x25000033 + /// 0x25000033 - BCDE_OSLOADER_TYPE_PERFORMANCE_DATA_MEMORY BcdOSLoaderInteger_PerformaceDataMemory = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_INTEGER, 51), /// /// Indicates whether the system should use the standard VGA display driver instead of a high-performance display driver. @@ -1779,7 +2169,10 @@ typedef enum _BcdOSLoaderElementTypes /// 0x25000052 BcdOSLoaderInteger_RestrictApicCluster = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_INTEGER, 82), /// - /// + /// Represents the OS Loader Type EV Store string element for the BCD (Boot Configuration Data) OS Loader. + /// The "EV Store" refers to the Event Log Store, which is a boot-time log or storage area used by Windows + /// typically used in scenarios involving secure boot, measured boot, or advanced diagnostics to record + /// boot-related events, diagnostics, or measurements for security, reliability, or troubleshooting. /// /// 0x22000053 BcdOSLoaderString_OSLoaderTypeEVStore = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_STRING, 83), @@ -1879,7 +2272,7 @@ typedef enum _BcdOSLoaderElementTypes /// /// Forces the use of the platform clock as the system's performance counter. /// - /// 0x260000A2 + /// 0x260000A2 - BCDE_OSLOADER_TYPE_USE_PLATFORM_CLOCK BcdOSLoaderBoolean_UsePlatformClock = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_BOOLEAN, 162), /// /// Forces the OS to assume the presence of legacy PC devices like CMOS and keyboard controllers. @@ -1888,12 +2281,21 @@ typedef enum _BcdOSLoaderElementTypes /// 0x260000A3 BcdOSLoaderBoolean_ForceLegacyPlatform = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_BOOLEAN, 163), /// - /// + /// Forces the kernel to use the platform legacy periodic timer interrupt (platform tick) + /// instead of newer tick suppression mechanisms (high-resolution timer, TSC deadline, or dynamic tick). + /// This corresponds to the BCDEdit boot option 'useplatformtick'. + /// Use this option when diagnosing timekeeping, scheduler, or idle state issues on systems with + /// problematic TSC/HPET implementations, or when consistent periodic interrupts are required for debugging. + /// Value TRUE enables the behavior; absence or FALSE uses default adaptive clock tick behavior. /// /// 0x260000A4 BcdOSLoaderBoolean_UsePlatformTick = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_BOOLEAN, 164), /// - /// + /// Disables dynamic tick (tickless kernel) so the system continues generating periodic clock interrupts. + /// Dynamic tick allows the kernel to stop the periodic timer when all CPUs are idle to reduce power usage; + /// disabling this feature helps improve performance with older hardware, high-resolution latency measurements, certain debuggers, + /// or troubleshooting missed timer events. + /// Value TRUE disables tick suppression; absence or FALSE leaves dynamic tick enabled (default). /// /// 0x260000A5 BcdOSLoaderBoolean_DisableDynamicTick = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_BOOLEAN, 165), @@ -1909,7 +2311,7 @@ typedef enum _BcdOSLoaderElementTypes /// 0x260000B0 BcdOSLoaderBoolean_EmsEnabled = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_BOOLEAN, 176), /// - /// + /// Represents the BCDE data type for forcing the OS loader to fail during the boot process. /// /// 0x250000C0 BcdOSLoaderInteger_ForceFailure = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_INTEGER, 192), @@ -1932,7 +2334,7 @@ typedef enum _BcdOSLoaderElementTypes /// 0x260000C3 BcdOSLoaderBoolean_AdvancedOptionsOneTime = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_BOOLEAN, 195), /// - /// + /// Allows for a one-time system boot using the specified boot options before returning to the original boot behavior. /// /// 0x260000C4 BcdOSLoaderBoolean_OptionsEditOneTime = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_BOOLEAN, 196), @@ -1953,7 +2355,9 @@ typedef enum _BcdOSLoaderElementTypes /// 0x250000F0 BcdOSLoaderInteger_HypervisorLaunchType = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_INTEGER, 240), /// - /// + /// Specifies the path to the hypervisor binary used for launching virtualization features. + /// This string value typically points to the location of the hypervisor image (e.g., hvloader.efi or hvloader.exe). + /// Used when configuring custom hypervisor binaries or alternate launch paths. /// /// 0x250000F1 BcdOSLoaderString_HypervisorPath = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_INTEGER, 241), @@ -1988,7 +2392,8 @@ typedef enum _BcdOSLoaderElementTypes /// 0x250000F7 BcdOSLoaderInteger_BootUxPolicy = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_INTEGER, 247), /// - /// + /// Indicates whether Second Level Address Translation (SLAT) is disabled for the hypervisor. + /// SLAT is a hardware virtualization feature; disabling it may impact performance or compatibility. /// /// 0x220000F8 BcdOSLoaderInteger_HypervisorSlatDisabled = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_STRING, 248), @@ -1999,300 +2404,361 @@ typedef enum _BcdOSLoaderElementTypes /// 0x220000F9 BcdOSLoaderString_HypervisorDebuggerBusParams = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_STRING, 249), /// - /// + /// Specifies the number of processors to be used by the hypervisor. + /// Used to limit or configure processor usage for virtualization. /// /// 0x250000FA BcdOSLoaderInteger_HypervisorNumProc = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_INTEGER, 250), /// - /// + /// Specifies the number of root processors per NUMA node for the hypervisor. + /// Used for advanced NUMA and processor topology configuration. /// /// 0x250000FB BcdOSLoaderInteger_HypervisorRootProcPerNode = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_INTEGER, 251), /// - /// + /// Indicates whether the hypervisor should use large virtual TLBs (Translation Lookaside Buffers). + /// May improve performance for certain workloads. /// /// 0x260000FC BcdOSLoaderBoolean_HypervisorUseLargeVTlb = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_BOOLEAN, 252), /// - /// + /// Specifies the IPv4 address for the hypervisor debugger network host. + /// Used for remote debugging over the network. /// /// 0x250000FD BcdOSLoaderInteger_HypervisorDebuggerNetHostIp = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_INTEGER, 253), /// - /// + /// Specifies the network port for the hypervisor debugger. + /// Used for remote debugging over the network. /// /// 0x250000FE BcdOSLoaderInteger_HypervisorDebuggerNetHostPort = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_INTEGER, 254), /// - /// + /// Specifies the number of memory pages allocated for the hypervisor debugger. + /// Used to control debugger memory usage. /// /// 0x250000FF BcdOSLoaderInteger_HypervisorDebuggerPages = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_INTEGER, 255), /// - /// + /// Specifies the TPM boot entropy policy for the hypervisor. + /// Used to configure Trusted Platform Module entropy usage during boot. /// /// 0x25000100 BcdOSLoaderInteger_TpmBootEntropyPolicy = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_INTEGER, 256), /// - /// + /// Specifies the encryption key for the hypervisor debugger network connection. + /// Used to secure remote debugging sessions. /// /// 0x22000110 BcdOSLoaderString_HypervisorDebuggerNetKey = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_STRING, 272), /// - /// + /// Specifies the product SKU type for the hypervisor. + /// Used for licensing and feature differentiation. /// /// 0x22000112 BcdOSLoaderString_HypervisorProductSkuType = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_STRING, 274), /// - /// + /// Specifies the root processor configuration for the hypervisor. + /// Used for advanced processor topology settings. /// /// 0x22000113 BcdOSLoaderInteger_HypervisorRootProc = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_STRING, 275), /// - /// + /// Indicates whether DHCP should be used for the hypervisor debugger network connection. + /// TRUE enables DHCP; FALSE requires manual configuration. /// /// 0x26000114 BcdOSLoaderBoolean_HypervisorDebuggerNetDhcp = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_BOOLEAN, 276), /// - /// + /// Specifies the IOMMU policy for the hypervisor. + /// Used to configure Input-Output Memory Management Unit behavior. /// /// 0x25000115 BcdOSLoaderInteger_HypervisorIommuPolicy = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_INTEGER, 277), /// - /// + /// Indicates whether the hypervisor should use virtual APICs. + /// May affect interrupt handling and virtualization performance. /// /// 0x26000116 BcdOSLoaderBoolean_HypervisorUseVApic = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_BOOLEAN, 278), /// - /// + /// Specifies additional load options for the hypervisor. + /// Used to pass custom command-line or configuration parameters. /// /// 0x22000117 BcdOSLoaderString_HypervisorLoadOptions = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_STRING, 279), /// - /// BCDE_POLICY_OSLOADER_TYPE_HYPERVISOR_MSR_FILTER_POLICY + /// Specifies the MSR filter policy for the hypervisor. + /// Used to control Model-Specific Register access filtering. /// /// 0x25000118 BcdOSLoaderInteger_HypervisorMsrFilterPolicy = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_INTEGER, 280), /// - /// + /// Specifies the MMIO NX policy for the hypervisor. + /// Used to configure No-Execute protection for memory-mapped I/O regions. /// /// 0x25000119 BcdOSLoaderInteger_HypervisorMmioNxPolicy = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_INTEGER, 281), /// - /// + /// Specifies the scheduler type for the hypervisor. + /// Used to select between different scheduling algorithms. /// /// 0x2500011A BcdOSLoaderInteger_HypervisorSchedulerType = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_INTEGER, 282), /// - /// + /// Specifies the NUMA node configuration for root processors in the hypervisor. + /// Used for advanced NUMA topology settings. /// /// 0x2200011B BcdOSLoaderString_HypervisorRootProcNumaNodes = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_STRING, 283), /// - /// BCDE_POLICY_OSLOADER_TYPE_HYPERVISOR_PERFMON + /// Enables or configures performance monitoring for the hypervisor. + /// Used for diagnostics and performance analysis. /// /// 0x2500011C BcdOSLoaderInteger_HypervisorPerfmon = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_INTEGER, 284), /// - /// + /// Specifies the number of root processors per core for the hypervisor. + /// Used for advanced processor topology configuration. /// /// 0x2500011D BcdOSLoaderInteger_HypervisorRootProcPerCore = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_INTEGER, 285), /// - /// + /// Specifies NUMA node logical processor settings for root processors in the hypervisor. + /// Used for advanced NUMA topology configuration. /// /// 0x2200011E BcdOSLoaderString_HypervisorRootProcNumaNodeLps = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_STRING, 286), /// - /// + /// Specifies the xsave policy for processor state saving in the hypervisor. + /// Used to configure processor feature usage. /// /// 0x25000120 BcdOSLoaderInteger_XSavePolicy = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_INTEGER, 288), /// - /// + /// Adds processor features to the xsave mask for processor state saving (feature 0). + /// Used for advanced processor feature configuration. /// /// 0x25000121 BcdOSLoaderInteger_XSaveAddFeature0 = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_INTEGER, 289), /// - /// + /// Adds processor features to the xsave mask for processor state saving (feature 1). + /// Used for advanced processor feature configuration. /// /// 0x25000122 BcdOSLoaderInteger_XSaveAddFeature1 = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_INTEGER, 290), /// - /// + /// Adds processor features to the xsave mask for processor state saving (feature 2). + /// Used for advanced processor feature configuration. /// /// 0x25000123 BcdOSLoaderInteger_XSaveAddFeature2 = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_INTEGER, 291), /// - /// + /// Adds processor features to the xsave mask for processor state saving (feature 3). + /// Used for advanced processor feature configuration. /// /// 0x25000124 BcdOSLoaderInteger_XSaveAddFeature3 = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_INTEGER, 292), /// - /// + /// Adds processor features to the xsave mask for processor state saving (feature 4). + /// Used for advanced processor feature configuration. /// /// 0x25000125 BcdOSLoaderInteger_XSaveAddFeature4 = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_INTEGER, 293), /// - /// + /// Adds processor features to the xsave mask for processor state saving (feature 5). + /// Used for advanced processor feature configuration. /// /// 0x25000126 BcdOSLoaderInteger_XSaveAddFeature5 = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_INTEGER, 294), /// - /// + /// Adds processor features to the xsave mask for processor state saving (feature 6). + /// Used for advanced processor feature configuration. /// /// 0x25000127 BcdOSLoaderInteger_XSaveAddFeature6 = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_INTEGER, 295), /// - /// + /// Adds processor features to the xsave mask for processor state saving (feature 7). + /// Used for advanced processor feature configuration. /// /// 0x25000128 BcdOSLoaderInteger_XSaveAddFeature7 = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_INTEGER, 296), /// - /// + /// Removes processor features from the xsave mask for processor state saving. + /// Used for advanced processor feature configuration. /// /// 0x25000129 BcdOSLoaderInteger_XSaveRemoveFeature = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_INTEGER, 297), /// - /// + /// Specifies the processor mask for xsave operations. + /// Used to configure which processors participate in state saving. /// /// 0x2500012A BcdOSLoaderInteger_XSaveProcessorsMask = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_INTEGER, 298), /// - /// + /// Disables xsave processor state saving. + /// Used for compatibility or troubleshooting. /// /// 0x2500012B BcdOSLoaderInteger_XSaveDisable = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_INTEGER, 299), /// - /// + /// Specifies the kernel debugger type for the OS loader. + /// Used to select between serial, 1394, USB, or network debugging. /// /// 0x2500012C BcdOSLoaderInteger_KernelDebuggerType = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_INTEGER, 300), /// - /// + /// PCI bus parameters for the kernel debugger device. + /// Format: "bus.device.function" (e.g., "1.5.0"). + /// Used to specify the hardware location for debugging. /// /// 0x2200012D BcdOSLoaderString_KernelDebuggerBusParameters = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_STRING, 301), /// - /// + /// Specifies the port address for the kernel debugger. + /// Used for configuring hardware debugging. /// /// 0x2500012E BcdOSLoaderInteger_KernelDebuggerPortAddress = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_INTEGER, 302), /// - /// + /// Specifies the port number for the kernel debugger. + /// Used for configuring hardware debugging. /// /// 0x2500012F BcdOSLoaderInteger_KernelDebuggerPortNumber = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_INTEGER, 303), /// - /// + /// Specifies the claimed TPM counter value for the OS loader. + /// Used for advanced TPM and security configuration. /// /// 0x25000130 BcdOSLoaderInteger_ClaimedTpmCounter = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_INTEGER, 304), /// - /// + /// Specifies the channel number for 1394 kernel debugging. + /// Used for configuring FireWire debugging. /// /// 0x25000131 BcdOSLoaderInteger_KernelDebugger1394Channel = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_INTEGER, 305), /// - /// + /// Specifies the USB target name for kernel debugging. + /// Used for configuring USB debugging. /// /// 0x22000132 BcdOSLoaderString_KernelDebuggerUsbTargetname = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_STRING, 306), /// - /// + /// Specifies the IPv4 address for the kernel debugger network host. + /// Used for remote debugging over the network. /// /// 0x25000133 BcdOSLoaderInteger_KernelDebuggerNetHostIp = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_INTEGER, 307), /// - /// + /// Specifies the network port for the kernel debugger. + /// Used for remote debugging over the network. /// /// 0x25000134 BcdOSLoaderInteger_KernelDebuggerNetHostPort = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_INTEGER, 308), /// - /// + /// Indicates whether DHCP should be used for the kernel debugger network connection. + /// TRUE enables DHCP; FALSE requires manual configuration. /// /// 0x26000135 BcdOSLoaderBoolean_KernelDebuggerNetDhcp = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_BOOLEAN, 309), /// - /// + /// Specifies the encryption key for the kernel debugger network connection. + /// Used to secure remote debugging sessions. /// /// 0x22000136 BcdOSLoaderString_KernelDebuggerNetKey = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_STRING, 310), /// - /// + /// Specifies the IMC hive name for the OS loader. + /// Used for advanced configuration or diagnostics. /// /// 0x22000137 BcdOSLoaderString_IMCHiveName = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_STRING, 311), /// - /// + /// Specifies the IMC device for the OS loader. + /// Used for advanced configuration or diagnostics. /// /// 0x21000138 BcdOSLoaderDevice_IMCDevice = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_DEVICE, 312), /// - /// + /// Specifies the baud rate for kernel debugging. + /// Used for configuring hardware debugging. /// /// 0x25000139 BcdOSLoaderInteger_KernelDebuggerBaudrate = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_INTEGER, 313), /// - /// + /// Specifies the manufacturing mode string for the OS loader. + /// Used for OEM or factory configuration. /// /// 0x22000140 BcdOSLoaderString_ManufacturingMode = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_STRING, 320), /// - /// + /// Indicates whether event logging is enabled for the OS loader. + /// Used for diagnostics and troubleshooting. /// /// 0x26000141 BcdOSLoaderBoolean_EventLoggingEnabled = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_BOOLEAN, 321), /// - /// + /// Specifies the launch type for Virtual Secure Mode (VSM). + /// Used for configuring virtualization-based security. /// /// 0x25000142 BcdOSLoaderInteger_VsmLaunchType = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_INTEGER, 322), /// - /// Zero (0) indicates Disabled, one (1) indicates that Enabled and two (2) indicates strict mode. + /// Specifies the code integrity enforcement policy for the hypervisor. + /// 0 = Disabled, 1 = Enabled, 2 = Strict. + /// Used for security and compliance. /// /// 0x25000144 BcdOSLoaderInteger_HypervisorEnforcedCodeIntegrity = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_INTEGER, 324), /// - /// + /// Indicates whether DTrace is enabled for the OS loader. + /// Used for advanced diagnostics and tracing. /// /// 0x26000145 BcdOSLoaderBoolean_DtraceEnabled = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_BOOLEAN, 325), /// - /// + /// Specifies the system data device for the OS loader. + /// Used for advanced configuration or diagnostics. /// /// 0x21000150 BcdOSLoaderDevice_SystemDataDevice = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_DEVICE, 336), /// - /// + /// Specifies the OS ARC device for the OS loader. + /// Used for advanced configuration or diagnostics. /// /// 0x21000151 BcdOSLoaderDevice_OsArcDevice = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_DEVICE, 337), /// - /// + /// Specifies the OS data device for the OS loader. + /// Used for advanced configuration or diagnostics. /// /// 0x21000153 BcdOSLoaderDevice_OsDataDevice = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_DEVICE, 339), /// - /// + /// Specifies the BSP device for the OS loader. + /// Used for advanced configuration or diagnostics. /// /// 0x21000154 BcdOSLoaderDevice_BspDevice = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_DEVICE, 340), /// - /// + /// Specifies the BSP file path for the OS loader. + /// Used for advanced configuration or diagnostics. /// /// 0x21000155 BcdOSLoaderDevice_BspFilepath = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_DEVICE, 341), /// - /// + /// Specifies the IPv6 address for the kernel debugger network host. + /// Used for remote debugging over IPv6. /// /// 0x22000156 BcdOSLoaderString_KernelDebuggerNetHostIpv6 = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_STRING, 342), /// - /// + /// Specifies the IPv6 address for the hypervisor debugger network host. + /// Used for remote debugging over IPv6. /// /// 0x22000161 BcdOSLoaderString_HypervisorDebuggerNetHostIpv6 = MAKE_BCDE_DATA_TYPE(BCD_ELEMENT_DATATYPE_CLASS_APPLICATION, BCD_ELEMENT_DATATYPE_FORMAT_STRING, 353), } BcdOSLoaderElementTypes; -#endif +#endif // _NTBCD_H diff --git a/ntd3dkmt.h b/ntd3dkmt.h new file mode 100644 index 0000000..6800dd4 --- /dev/null +++ b/ntd3dkmt.h @@ -0,0 +1,107 @@ +/* + * Direct3D Kernel Mode Thunk (D3DKMT) + * + * This file is part of System Informer. + */ + +#ifndef _NTD3DKMT_H +#define _NTD3DKMT_H + +#include +//#include +#include +#include + +DEFINE_DEVPROPKEY(DEVPKEY_Gpu_Luid, 0x60b193cb, 0x5276, 0x4d0f, 0x96, 0xfc, 0xf1, 0x73, 0xab, 0xad, 0x3e, 0xc6, 2); // DEVPROP_TYPE_UINT64 +DEFINE_DEVPROPKEY(DEVPKEY_Gpu_PhysicalAdapterIndex, 0x60b193cb, 0x5276, 0x4d0f, 0x96, 0xfc, 0xf1, 0x73, 0xab, 0xad, 0x3e, 0xc6, 3); // DEVPROP_TYPE_UINT32 +DEFINE_GUID(GUID_COMPUTE_DEVICE_ARRIVAL, 0x1024e4c9, 0x47c9, 0x48d3, 0xb4, 0xa8, 0xf9, 0xdf, 0x78, 0x52, 0x3b, 0x53); + +typedef D3DKMT_HANDLE* PD3DKMT_HANDLE; + +typedef struct _D3DKMT_QUERYSTATISTICS_SEGMENT_INFORMATION_V1 +{ + ULONG CommitLimit; + ULONG BytesCommitted; + ULONG BytesResident; + D3DKMT_QUERYSTATISTICS_MEMORY Memory; + ULONG Aperture; // boolean + ULONGLONG TotalBytesEvictedByPriority[D3DKMT_MaxAllocationPriorityClass]; + ULONG64 SystemMemoryEndAddress; + struct + { + ULONG64 PreservedDuringStandby : 1; + ULONG64 PreservedDuringHibernate : 1; + ULONG64 PartiallyPreservedDuringHibernate : 1; + ULONG64 Reserved : 61; + } PowerFlags; + ULONG64 Reserved[7]; +} D3DKMT_QUERYSTATISTICS_SEGMENT_INFORMATION_V1, *PD3DKMT_QUERYSTATISTICS_SEGMENT_INFORMATION_V1; + +/** + * The D3DKMT_GET_PROCESS_LIST structure is used for retrieving a list of process handles using a graphics adapter. + * \remarks The caller is responsible for closing the returned process handles. + */ +// rev +typedef struct _D3DKMT_GET_PROCESS_LIST +{ + LUID AdapterLuid; // [in] The locally unique identifier (LUID) for the graphics adapter. + ULONG DesiredAccess; // [in] The access rights to request for the process handles. This must be `PROCESS_QUERY_INFORMATION` (0x400). + ULONG ProcessHandleCount; // [in, out] On input, specifies the number of handles the `ProcessHandle` member can hold. On output, receives the number of handles returned. + HANDLE ProcessHandle; // [out] The first element of an array that receives the process handles. +} D3DKMT_GET_PROCESS_LIST, *PD3DKMT_GET_PROCESS_LIST; + +// rev +/** + * The D3DKMTGetProcessList function retrieves a list of processes that are using a specific graphics adapter. + * + * \param[in,out] GetProcessList A pointer to a \ref D3DKMT_GET_PROCESS_LIST structure that contains the processes using the graphics adapter. + * \return NTSTATUS Successful or errant status. + */ +EXTERN_C +NTSTATUS +NTAPI +D3DKMTGetProcessList( + _Inout_ PD3DKMT_GET_PROCESS_LIST GetProcessList + ); + +// rev +/** + * The D3DKMT_ENUM_PROCESS_LIST structure is used for retrieving a list of process identifiers using a graphics adapter. + */ +typedef struct _D3DKMT_ENUM_PROCESS_LIST +{ + LUID AdapterLuid; // [in] The locally unique identifier (LUID) for the graphics adapter. + PULONG ProcessIdBuffer; // [out] A pointer to a buffer that receives the list of process identifiers (PIDs). + SIZE_T ProcessIdCount; // [in, out] On input, specifies the number of elements the `ProcessIdBuffer` can hold. On output, receives the number of process IDs returned. +} D3DKMT_ENUM_PROCESS_LIST, *PD3DKMT_ENUM_PROCESS_LIST; + +// rev +/** + * The D3DKMTEnumProcesses function provides a list of process IDs (PIDs) rather than handles that are using a specific graphics adapter, + * which can be more efficient for monitoring purposes. + * + * \param[in,out] EnumProcessList A pointer to a \ref D3DKMT_ENUM_PROCESS_LIST structure that contains the processes using the graphics adapter. + * \return NTSTATUS Successful or errant status. + */ +EXTERN_C +NTSTATUS +NTAPI +D3DKMTEnumProcesses( + _Inout_ PD3DKMT_ENUM_PROCESS_LIST EnumProcessList + ); + +#if (PHNT_VERSION >= PHNT_WINDOWS_10_20H1) +// rev +NTSYSCALLAPI +NTSTATUS +NTAPI +NtDirectGraphicsCall( + _In_ ULONG InputBufferLength, + _In_reads_bytes_opt_(InputBufferLength) PVOID InputBuffer, + _In_ ULONG OutputBufferLength, + _Out_writes_bytes_opt_(OutputBufferLength) PVOID OutputBuffer, + _Out_ PULONG ReturnLength + ); +#endif // (PHNT_VERSION >= PHNT_WINDOWS_10_20H1) + +#endif // _NTD3DKMT_H diff --git a/ntdbg.h b/ntdbg.h index 7bec3f2..60f9c7e 100644 --- a/ntdbg.h +++ b/ntdbg.h @@ -7,8 +7,13 @@ #ifndef _NTDBG_H #define _NTDBG_H +// // Debugging +// +/** + * Causes a user-mode breakpoint to occur. + */ NTSYSAPI VOID NTAPI @@ -16,6 +21,9 @@ DbgUserBreakPoint( VOID ); +/** + * Causes a breakpoint to occur. + */ NTSYSAPI VOID NTAPI @@ -23,6 +31,11 @@ DbgBreakPoint( VOID ); +/** + * Causes a breakpoint to occur with a specific status. + * + * \param Status The status code to be associated with the breakpoint. + */ NTSYSAPI VOID NTAPI @@ -38,6 +51,13 @@ DbgBreakPointWithStatus( #define DBG_STATUS_DEBUG_CONTROL 6 #define DBG_STATUS_WORKER 7 +/** + * Sends a message to the kernel debugger. + * + * \param Format A pointer to a printf-style format string. + * \param ... Arguments for the format string. + * \return ULONG The number of characters printed. + */ NTSYSAPI ULONG STDAPIVCALLTYPE @@ -46,6 +66,15 @@ DbgPrint( ... ); +/** + * Sends a message to the kernel debugger with a component ID and level. + * + * \param ComponentId The ID of the component that is sending the message. + * \param Level The importance level of the message. + * \param Format A pointer to a printf-style format string. + * \param ... Arguments for the format string. + * \return ULONG The number of characters printed. + */ NTSYSAPI ULONG STDAPIVCALLTYPE @@ -56,6 +85,15 @@ DbgPrintEx( ... ); +/** + * Sends a message to the kernel debugger with a component ID and level (va_list version). + * + * \param ComponentId The ID of the component that is sending the message. + * \param Level The importance level of the message. + * \param Format A pointer to a printf-style format string. + * \param arglist A list of arguments for the format string. + * \return ULONG The number of characters printed. + */ NTSYSAPI ULONG NTAPI @@ -66,6 +104,16 @@ vDbgPrintEx( _In_ va_list arglist ); +/** + * Sends a message to the kernel debugger with a prefix, component ID, and level. + * + * \param Prefix A pointer to a string to be prefixed to the message. + * \param ComponentId The ID of the component that is sending the message. + * \param Level The importance level of the message. + * \param Format A pointer to a printf-style format string. + * \param arglist A list of arguments for the format string. + * \return ULONG The number of characters printed. + */ NTSYSAPI ULONG NTAPI @@ -77,6 +125,13 @@ vDbgPrintExWithPrefix( _In_ va_list arglist ); +/** + * Sends a message to the kernel debugger and returns Control-C status. + * + * \param Format A pointer to a printf-style format string. + * \param ... Arguments for the format string. + * \return ULONG The number of characters printed. + */ NTSYSAPI ULONG STDAPIVCALLTYPE @@ -85,6 +140,13 @@ DbgPrintReturnControlC( ... ); +/** + * Queries the debug filter state for a component. + * + * \param ComponentId The ID of the component. + * \param Level The importance level. + * \return NTSTATUS Successful or errant status. + */ NTSYSAPI NTSTATUS NTAPI @@ -93,6 +155,14 @@ DbgQueryDebugFilterState( _In_ ULONG Level ); +/** + * Sets the debug filter state for a component. + * + * \param ComponentId The ID of the component. + * \param Level The importance level. + * \param State The new state for the filter. + * \return NTSTATUS Successful or errant status. + */ NTSYSAPI NTSTATUS NTAPI @@ -102,6 +172,14 @@ DbgSetDebugFilterState( _In_ BOOLEAN State ); +/** + * Prompts the user for input. + * + * \param Prompt A pointer to the prompt string. + * \param Response A pointer to the buffer that receives the user response. + * \param Length The length of the response buffer, in bytes. + * \return ULONG The number of characters in the response. + */ NTSYSAPI ULONG NTAPI @@ -111,20 +189,31 @@ DbgPrompt( _In_ ULONG Length ); +// // Definitions +// +/** + * The DBGKM_EXCEPTION structure contains exception information for a debug event. + */ typedef struct _DBGKM_EXCEPTION { EXCEPTION_RECORD ExceptionRecord; ULONG FirstChance; } DBGKM_EXCEPTION, *PDBGKM_EXCEPTION; +/** + * The DBGKM_CREATE_THREAD structure contains information about a newly created thread. + */ typedef struct _DBGKM_CREATE_THREAD { ULONG SubSystemKey; PVOID StartAddress; } DBGKM_CREATE_THREAD, *PDBGKM_CREATE_THREAD; +/** + * The DBGKM_CREATE_PROCESS structure contains information about a newly created process. + */ typedef struct _DBGKM_CREATE_PROCESS { ULONG SubSystemKey; @@ -135,16 +224,25 @@ typedef struct _DBGKM_CREATE_PROCESS DBGKM_CREATE_THREAD InitialThread; } DBGKM_CREATE_PROCESS, *PDBGKM_CREATE_PROCESS; +/** + * The DBGKM_EXIT_THREAD structure contains the exit status of a thread. + */ typedef struct _DBGKM_EXIT_THREAD { NTSTATUS ExitStatus; } DBGKM_EXIT_THREAD, *PDBGKM_EXIT_THREAD; +/** + * The DBGKM_EXIT_PROCESS structure contains the exit status of a process. + */ typedef struct _DBGKM_EXIT_PROCESS { NTSTATUS ExitStatus; } DBGKM_EXIT_PROCESS, *PDBGKM_EXIT_PROCESS; +/** + * The DBGKM_LOAD_DLL structure contains information about a loaded DLL. + */ typedef struct _DBGKM_LOAD_DLL { HANDLE FileHandle; @@ -154,11 +252,17 @@ typedef struct _DBGKM_LOAD_DLL PVOID NamePointer; } DBGKM_LOAD_DLL, *PDBGKM_LOAD_DLL; +/** + * The DBGKM_UNLOAD_DLL structure contains the base address of an unloaded DLL. + */ typedef struct _DBGKM_UNLOAD_DLL { PVOID BaseAddress; } DBGKM_UNLOAD_DLL, *PDBGKM_UNLOAD_DLL; +/** + * The DBG_STATE enumeration defines the state of a debug object. + */ typedef enum _DBG_STATE { DbgIdle, @@ -174,12 +278,18 @@ typedef enum _DBG_STATE DbgUnloadDllStateChange } DBG_STATE, *PDBG_STATE; +/** + * The DBGUI_CREATE_THREAD structure contains UI-level information about a newly created thread. + */ typedef struct _DBGUI_CREATE_THREAD { HANDLE HandleToThread; DBGKM_CREATE_THREAD NewThread; } DBGUI_CREATE_THREAD, *PDBGUI_CREATE_THREAD; +/** + * The DBGUI_CREATE_PROCESS structure contains UI-level information about a newly created process. + */ typedef struct _DBGUI_CREATE_PROCESS { HANDLE HandleToProcess; @@ -187,6 +297,9 @@ typedef struct _DBGUI_CREATE_PROCESS DBGKM_CREATE_PROCESS NewProcess; } DBGUI_CREATE_PROCESS, *PDBGUI_CREATE_PROCESS; +/** + * The DBGUI_WAIT_STATE_CHANGE structure contains information about a debug state change. + */ typedef struct _DBGUI_WAIT_STATE_CHANGE { DBG_STATE NewState; @@ -213,6 +326,9 @@ typedef struct _DBGUI_WAIT_STATE_CHANGE #define DEBUG_KILL_ON_CLOSE 0x1 +/** + * The DEBUGOBJECTINFOCLASS enumeration defines the information classes for debug objects. + */ typedef enum _DEBUGOBJECTINFOCLASS { DebugObjectUnusedInformation, @@ -220,8 +336,19 @@ typedef enum _DEBUGOBJECTINFOCLASS MaxDebugObjectInfoClass } DEBUGOBJECTINFOCLASS, *PDEBUGOBJECTINFOCLASS; +// // System calls +// +/** + * Creates a debug object. + * + * \param DebugObjectHandle A pointer to a variable that receives the debug object handle. + * \param DesiredAccess The access rights desired for the debug object. + * \param ObjectAttributes Optional. A pointer to an OBJECT_ATTRIBUTES structure that specifies the attributes of the debug object. + * \param Flags Flags for the debug object creation. (DEBUG_KILL_ON_CLOSE) + * \return NTSTATUS Successful or errant status. + */ NTSYSCALLAPI NTSTATUS NTAPI @@ -232,6 +359,13 @@ NtCreateDebugObject( _In_ ULONG Flags ); +/** + * Attaches a debugger to an active process. + * + * \param ProcessHandle A handle to the process to be debugged. + * \param DebugObjectHandle A handle to the debug object. + * \return NTSTATUS Successful or errant status. + */ NTSYSCALLAPI NTSTATUS NTAPI @@ -240,6 +374,14 @@ NtDebugActiveProcess( _In_ HANDLE DebugObjectHandle ); +/** + * Continues a thread that was stopped by a debug event. + * + * \param DebugObjectHandle A handle to the debug object. + * \param ClientId A pointer to a CLIENT_ID structure that identifies the thread to be continued. + * \param ContinueStatus The status code to use when continuing the thread. + * \return NTSTATUS Successful or errant status. + */ NTSYSCALLAPI NTSTATUS NTAPI @@ -249,6 +391,13 @@ NtDebugContinue( _In_ NTSTATUS ContinueStatus ); +/** + * Stops debugging a process. + * + * \param ProcessHandle A handle to the process. + * \param DebugObjectHandle A handle to the debug object. + * \return NTSTATUS Successful or errant status. + */ NTSYSCALLAPI NTSTATUS NTAPI @@ -257,6 +406,16 @@ NtRemoveProcessDebug( _In_ HANDLE DebugObjectHandle ); +/** + * Sets information for a debug object. + * + * \param DebugObjectHandle A handle to the debug object. + * \param DebugObjectInformationClass The information class to be set. + * \param DebugInformation A pointer to the buffer that contains the information. + * \param DebugInformationLength The length of the information buffer, in bytes. + * \param ReturnLength Optional. A pointer to a variable that receives the number of bytes returned. + * \return NTSTATUS Successful or errant status. + */ NTSYSCALLAPI NTSTATUS NTAPI @@ -268,6 +427,15 @@ NtSetInformationDebugObject( _Out_opt_ PULONG ReturnLength ); +/** + * Waits for a debug event to occur. + * + * \param DebugObjectHandle A handle to the debug object. + * \param Alertable Specifies whether the wait is alertable. + * \param Timeout Optional. A pointer to a LARGE_INTEGER structure that specifies the timeout. + * \param WaitStateChange A pointer to a DBGUI_WAIT_STATE_CHANGE structure that receives information about the debug event. + * \return NTSTATUS Successful or errant status. + */ NTSYSCALLAPI NTSTATUS NTAPI @@ -278,8 +446,15 @@ NtWaitForDebugEvent( _Out_ PDBGUI_WAIT_STATE_CHANGE WaitStateChange ); +// // Debugging UI +// +/** + * Connects the current thread to the debugger. + * + * \return NTSTATUS Successful or errant status. + */ NTSYSAPI NTSTATUS NTAPI @@ -287,6 +462,11 @@ DbgUiConnectToDbg( VOID ); +/** + * Retrieves the debug object handle for the current thread. + * + * \return HANDLE The debug object handle. + */ NTSYSAPI HANDLE NTAPI @@ -294,6 +474,11 @@ DbgUiGetThreadDebugObject( VOID ); +/** + * Sets the debug object handle for the current thread. + * + * \param DebugObject The debug object handle. + */ NTSYSAPI VOID NTAPI @@ -301,6 +486,13 @@ DbgUiSetThreadDebugObject( _In_ HANDLE DebugObject ); +/** + * Waits for a debug state change. + * + * \param StateChange A pointer to a DBGUI_WAIT_STATE_CHANGE structure that receives the state change information. + * \param Timeout Optional. A pointer to a LARGE_INTEGER structure that specifies the timeout. + * \return NTSTATUS Successful or errant status. + */ NTSYSAPI NTSTATUS NTAPI @@ -309,6 +501,13 @@ DbgUiWaitStateChange( _In_opt_ PLARGE_INTEGER Timeout ); +/** + * Continues a debug state change. + * + * \param AppClientId A pointer to a CLIENT_ID structure that identifies the thread to be continued. + * \param ContinueStatus The status code to use when continuing the thread. + * \return NTSTATUS Successful or errant status. + */ NTSYSAPI NTSTATUS NTAPI @@ -317,6 +516,12 @@ DbgUiContinue( _In_ NTSTATUS ContinueStatus ); +/** + * Stops debugging a process. + * + * \param Process A handle to the process. + * \return NTSTATUS Successful or errant status. + */ NTSYSAPI NTSTATUS NTAPI @@ -324,6 +529,12 @@ DbgUiStopDebugging( _In_ HANDLE Process ); +/** + * Attaches a debugger to an active process. + * + * \param Process A handle to the process. + * \return NTSTATUS Successful or errant status. + */ NTSYSAPI NTSTATUS NTAPI @@ -331,6 +542,11 @@ DbgUiDebugActiveProcess( _In_ HANDLE Process ); +/** + * Remotely triggers a breakpoint in a process. + * + * \param Context A pointer to the context for the breakpoint. + */ NTSYSAPI VOID NTAPI @@ -338,6 +554,12 @@ DbgUiRemoteBreakin( _In_ PVOID Context ); +/** + * Issues a remote breakpoint in a process. + * + * \param Process A handle to the process. + * \return NTSTATUS Successful or errant status. + */ NTSYSAPI NTSTATUS NTAPI @@ -345,6 +567,13 @@ DbgUiIssueRemoteBreakin( _In_ HANDLE Process ); +/** + * Converts a state change structure to a debug event structure. + * + * \param StateChange A pointer to a DBGUI_WAIT_STATE_CHANGE structure. + * \param DebugEvent A pointer to a DEBUG_EVENT structure that receives the converted information. + * \return NTSTATUS Successful or errant status. + */ NTSYSAPI NTSTATUS NTAPI @@ -353,6 +582,13 @@ DbgUiConvertStateChangeStructure( _Out_ LPDEBUG_EVENT DebugEvent ); +/** + * Converts a state change structure to a debug event structure (extended). + * + * \param StateChange A pointer to a DBGUI_WAIT_STATE_CHANGE structure. + * \param DebugEvent A pointer to a DEBUG_EVENT structure that receives the converted information. + * \return NTSTATUS Successful or errant status. + */ NTSYSAPI NTSTATUS NTAPI @@ -363,7 +599,11 @@ DbgUiConvertStateChangeStructureEx( typedef struct _EVENT_FILTER_DESCRIPTOR *PEVENT_FILTER_DESCRIPTOR; -typedef VOID (NTAPI *PENABLECALLBACK)( +/** + * A callback function that receives event enabled notifications. + */ +typedef _Function_class_(ENABLECALLBACK) +VOID NTAPI ENABLECALLBACK( _In_ LPCGUID SourceId, _In_ ULONG IsEnabled, _In_ UCHAR Level, @@ -372,9 +612,19 @@ typedef VOID (NTAPI *PENABLECALLBACK)( _In_opt_ PEVENT_FILTER_DESCRIPTOR FilterData, _Inout_opt_ PVOID CallbackContext ); +typedef ENABLECALLBACK* PENABLECALLBACK; typedef ULONGLONG REGHANDLE, *PREGHANDLE; +/** + * Registers an ETW event provider. + * + * \param ProviderId A pointer to the provider ID. + * \param EnableCallback Optional. A pointer to the enable callback function. + * \param CallbackContext Optional. A pointer to the callback context. + * \param RegHandle A pointer to a variable that receives the registration handle. + * \return NTSTATUS Successful or errant status. + */ NTSYSAPI NTSTATUS NTAPI @@ -385,4 +635,4 @@ EtwEventRegister( _Out_ PREGHANDLE RegHandle ); -#endif +#endif // _NTDBG_H diff --git a/ntexapi.h b/ntexapi.h index 0ffe98f..bea2519 100644 --- a/ntexapi.h +++ b/ntexapi.h @@ -7,8 +7,6 @@ #ifndef _NTEXAPI_H #define _NTEXAPI_H -#include - typedef struct _TEB* PTEB; typedef struct _COUNTED_REASON_CONTEXT* PCOUNTED_REASON_CONTEXT; typedef struct _FILE_IO_COMPLETION_INFORMATION* PFILE_IO_COMPLETION_INFORMATION; @@ -28,15 +26,15 @@ typedef struct _RTL_BITMAP* PRTL_BITMAP; /** * The NtDelayExecution routine suspends the current thread until the specified condition is met. * - * @param Alertable The function returns when either the time-out period has elapsed or when the APC function is called. - * @param DelayInterval The time interval for which execution is to be suspended, in milliseconds. + * \param Alertable The function returns when either the time-out period has elapsed or when the APC function is called. + * \param DelayInterval The time interval for which execution is to be suspended, in milliseconds. * - A value of zero causes the thread to relinquish the remainder of its time slice to any other thread that is ready to run. * - If there are no other threads ready to run, the function returns immediately, and the thread continues execution. * - A value of INFINITE indicates that the suspension should not time out. - * @return NTSTATUS Successful or errant status. The return value is STATUS_USER_APC when Alertable is TRUE, and the function returned due to one or more I/O completion callback functions. - * @remarks Note that a ready thread is not guaranteed to run immediately. Consequently, the thread will not run until some arbitrary time after the sleep interval elapses, + * \return NTSTATUS Successful or errant status. The return value is STATUS_USER_APC when Alertable is TRUE, and the function returned due to one or more I/O completion callback functions. + * \remarks Note that a ready thread is not guaranteed to run immediately. Consequently, the thread will not run until some arbitrary time after the sleep interval elapses, * based upon the system "tick" frequency and the load factor from other processes. - * @see https://learn.microsoft.com/en-us/windows/win32/api/synchapi/nf-synchapi-sleepex + * \see https://learn.microsoft.com/en-us/windows/win32/api/synchapi/nf-synchapi-sleepex */ NTSYSCALLAPI NTSTATUS @@ -54,17 +52,17 @@ NtDelayExecution( * Retrieves the value of the specified firmware environment variable. * The user account that the app is running under must have the SE_SYSTEM_ENVIRONMENT_NAME privilege. * - * @param VariableName The name of the firmware environment variable. The pointer must not be NULL. - * @param VariableValue A pointer to a buffer that receives the value of the specified firmware environment variable. - * @param ValueLength The size of the \c VariableValue buffer, in bytes. - * @param ReturnLength If the function succeeds, the return length is the number of bytes stored in the \c VariableValue buffer. - * @return NTSTATUS Successful or errant status. + * \param VariableName The name of the firmware environment variable. The pointer must not be NULL. + * \param VariableValue A pointer to a buffer that receives the value of the specified firmware environment variable. + * \param ValueLength The size of the \c VariableValue buffer, in bytes. + * \param ReturnLength If the function succeeds, the return length is the number of bytes stored in the \c VariableValue buffer. + * \return NTSTATUS Successful or errant status. */ NTSYSCALLAPI NTSTATUS NTAPI NtQuerySystemEnvironmentValue( - _In_ PUNICODE_STRING VariableName, + _In_ PCUNICODE_STRING VariableName, _Out_writes_bytes_(ValueLength) PWSTR VariableValue, _In_ USHORT ValueLength, _Out_opt_ PUSHORT ReturnLength @@ -92,12 +90,12 @@ NtQuerySystemEnvironmentValue( * Retrieves the value of the specified firmware environment variable and its attributes. * The user account that the app is running under must have the SE_SYSTEM_ENVIRONMENT_NAME privilege. * - * @param VariableName The name of the firmware environment variable. The pointer must not be NULL. - * @param VendorGuid The GUID that represents the namespace of the firmware environment variable. - * @param Buffer A pointer to a buffer that receives the value of the specified firmware environment variable. - * @param BufferLength The size of the \c Buffer, in bytes. - * @param Attributes Bitmask identifying UEFI variable attributes associated with the variable. - * @return NTSTATUS Successful or errant status. + * \param VariableName The name of the firmware environment variable. The pointer must not be NULL. + * \param VendorGuid The GUID that represents the namespace of the firmware environment variable. + * \param Buffer A pointer to a buffer that receives the value of the specified firmware environment variable. + * \param BufferLength The size of the \c Buffer, in bytes. + * \param Attributes Bitmask identifying UEFI variable attributes associated with the variable. + * \return NTSTATUS Successful or errant status. */ NTSYSCALLAPI NTSTATUS @@ -114,10 +112,10 @@ NtQuerySystemEnvironmentValueEx( * Sets the value of the specified firmware environment variable. * The user account that the app is running under must have the SE_SYSTEM_ENVIRONMENT_NAME privilege. * - * @param VariableName The name of the firmware environment variable. The pointer must not be NULL. - * @param VariableValue A pointer to the new value for the firmware environment variable. + * \param VariableName The name of the firmware environment variable. The pointer must not be NULL. + * \param VariableValue A pointer to the new value for the firmware environment variable. * If this parameter is zero, the firmware environment variable is deleted. - * @return NTSTATUS Successful or errant status. + * \return NTSTATUS Successful or errant status. */ NTSYSCALLAPI NTSTATUS @@ -131,15 +129,15 @@ NtSetSystemEnvironmentValue( * Sets the value of the specified firmware environment variable and the attributes that indicate how this variable is stored and maintained. * The user account that the app is running under must have the SE_SYSTEM_ENVIRONMENT_NAME privilege. * - * @param VariableName The name of the firmware environment variable. The pointer must not be NULL. - * @param VendorGuid The GUID that represents the namespace of the firmware environment variable. - * @param Buffer A pointer to the new value for the firmware environment variable. - * @param BufferLength The size of the pValue buffer, in bytes. + * \param VariableName The name of the firmware environment variable. The pointer must not be NULL. + * \param VendorGuid The GUID that represents the namespace of the firmware environment variable. + * \param Buffer A pointer to the new value for the firmware environment variable. + * \param BufferLength The size of the pValue buffer, in bytes. * Unless the VARIABLE_ATTRIBUTE_APPEND_WRITE, VARIABLE_ATTRIBUTE_AUTHENTICATED_WRITE_ACCESS, * or VARIABLE_ATTRIBUTE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS variable attribute is set via dwAttributes, * setting this value to zero will result in the deletion of this variable. - * @param Attributes Bitmask to set UEFI variable attributes associated with the variable. - * @return NTSTATUS Successful or errant status. + * \param Attributes Bitmask to set UEFI variable attributes associated with the variable. + * \return NTSTATUS Successful or errant status. */ NTSYSCALLAPI NTSTATUS @@ -159,6 +157,7 @@ typedef enum _SYSTEM_ENVIRONMENT_INFORMATION_CLASS MaxSystemEnvironmentInfoClass } SYSTEM_ENVIRONMENT_INFORMATION_CLASS; +_Struct_size_bytes_(NextEntryOffset) typedef struct _VARIABLE_NAME { ULONG NextEntryOffset; @@ -166,6 +165,7 @@ typedef struct _VARIABLE_NAME WCHAR Name[ANYSIZE_ARRAY]; } VARIABLE_NAME, *PVARIABLE_NAME; +_Struct_size_bytes_(NextEntryOffset) typedef struct _VARIABLE_NAME_AND_VALUE { ULONG NextEntryOffset; @@ -177,6 +177,14 @@ typedef struct _VARIABLE_NAME_AND_VALUE //BYTE Value[ANYSIZE_ARRAY]; } VARIABLE_NAME_AND_VALUE, *PVARIABLE_NAME_AND_VALUE; +/** + * The NtEnumerateSystemEnvironmentValuesEx routine enumerates system environment values with extended information. + * + * \param InformationClass The class of system environment information to retrieve. + * \param Buffer Pointer to a buffer that receives the system environment values data. + * \param BufferLength Pointer to a ULONG variable that specifies the size of the Buffer on input. + * \return NTSTATUS Successful or errant status. + */ NTSYSCALLAPI NTSTATUS NTAPI @@ -186,7 +194,9 @@ NtEnumerateSystemEnvironmentValuesEx( _Inout_ PULONG BufferLength ); +// // EFI +// // private typedef struct _BOOT_ENTRY @@ -202,6 +212,7 @@ typedef struct _BOOT_ENTRY } BOOT_ENTRY, *PBOOT_ENTRY; // private +_Struct_size_bytes_(NextEntryOffset) typedef struct _BOOT_ENTRY_LIST { ULONG NextEntryOffset; @@ -216,7 +227,7 @@ typedef struct _BOOT_OPTIONS ULONG Timeout; ULONG CurrentBootEntryId; ULONG NextBootEntryId; - WCHAR HeadlessRedirection[1]; + _Field_size_bytes_(Length) WCHAR HeadlessRedirection[1]; } BOOT_OPTIONS, *PBOOT_OPTIONS; // private @@ -239,19 +250,19 @@ typedef struct _EFI_DRIVER_ENTRY } EFI_DRIVER_ENTRY, *PEFI_DRIVER_ENTRY; // private +_Struct_size_bytes_(NextEntryOffset) typedef struct _EFI_DRIVER_ENTRY_LIST { ULONG NextEntryOffset; EFI_DRIVER_ENTRY DriverEntry; } EFI_DRIVER_ENTRY_LIST, *PEFI_DRIVER_ENTRY_LIST; -#if (PHNT_VERSION >= PHNT_WINDOWS_XP) /** * The NtAddBootEntry routine adds a new boot entry to the system boot configuration. * - * @param BootEntry A pointer to a BOOT_ENTRY structure that specifies the boot entry to be added. - * @param Id A pointer to a variable that receives the identifier of the new boot entry. - * @return NTSTATUS Successful or errant status. + * \param BootEntry A pointer to a BOOT_ENTRY structure that specifies the boot entry to be added. + * \param Id A pointer to a variable that receives the identifier of the new boot entry. + * \return NTSTATUS Successful or errant status. */ NTSYSCALLAPI NTSTATUS @@ -264,8 +275,8 @@ NtAddBootEntry( /** * The NtDeleteBootEntry routine deletes an existing boot entry from the system boot configuration. * - * @param Id The identifier of the boot entry to be deleted. - * @return NTSTATUS Successful or errant status. + * \param Id The identifier of the boot entry to be deleted. + * \return NTSTATUS Successful or errant status. */ NTSYSCALLAPI NTSTATUS @@ -277,8 +288,8 @@ NtDeleteBootEntry( /** * The NtModifyBootEntry routine modifies an existing boot entry in the system boot configuration. * - * @param BootEntry A pointer to a BOOT_ENTRY structure that specifies the new boot entry information. - * @return NTSTATUS Successful or errant status. + * \param BootEntry A pointer to a BOOT_ENTRY structure that specifies the new boot entry information. + * \return NTSTATUS Successful or errant status. */ NTSYSCALLAPI NTSTATUS @@ -290,9 +301,9 @@ NtModifyBootEntry( /** * The NtEnumerateBootEntries routine retrieves information about all boot entries in the system boot configuration. * - * @param Buffer A pointer to a buffer that receives the boot entries information. - * @param BufferLength A pointer to a variable that specifies the size of the buffer. On return, it contains the size of the data returned. - * @return NTSTATUS Successful or errant status. + * \param Buffer A pointer to a buffer that receives the boot entries information. + * \param BufferLength A pointer to a variable that specifies the size of the buffer. On return, it contains the size of the data returned. + * \return NTSTATUS Successful or errant status. */ NTSYSCALLAPI NTSTATUS @@ -305,9 +316,9 @@ NtEnumerateBootEntries( /** * The NtQueryBootEntryOrder routine retrieves the current boot entry order. * - * @param Ids A pointer to a buffer that receives the identifiers of the boot entries in the current boot order. - * @param Count A pointer to a variable that specifies the number of entries in the buffer. On return, it contains the number of entries returned. - * @return NTSTATUS Successful or errant status. + * \param Ids A pointer to a buffer that receives the identifiers of the boot entries in the current boot order. + * \param Count A pointer to a variable that specifies the number of entries in the buffer. On return, it contains the number of entries returned. + * \return NTSTATUS Successful or errant status. */ NTSYSCALLAPI NTSTATUS @@ -320,9 +331,9 @@ NtQueryBootEntryOrder( /** * The NtSetBootEntryOrder routine sets the boot entry order. * - * @param Ids A pointer to a buffer that specifies the identifiers of the boot entries in the desired boot order. - * @param Count The number of entries in the buffer. - * @return NTSTATUS Successful or errant status. + * \param Ids A pointer to a buffer that specifies the identifiers of the boot entries in the desired boot order. + * \param Count The number of entries in the buffer. + * \return NTSTATUS Successful or errant status. */ NTSYSCALLAPI NTSTATUS @@ -335,9 +346,9 @@ NtSetBootEntryOrder( /** * The NtQueryBootOptions routine retrieves the current boot options. * - * @param BootOptions A pointer to a buffer that receives the boot options. - * @param BootOptionsLength A pointer to a variable that specifies the size of the buffer. On return, it contains the size of the data returned. - * @return NTSTATUS Successful or errant status. + * \param BootOptions A pointer to a buffer that receives the boot options. + * \param BootOptionsLength A pointer to a variable that specifies the size of the buffer. On return, it contains the size of the data returned. + * \return NTSTATUS Successful or errant status. */ NTSYSCALLAPI NTSTATUS @@ -350,9 +361,9 @@ NtQueryBootOptions( /** * The NtSetBootOptions routine sets the boot options. * - * @param BootOptions A pointer to a BOOT_OPTIONS structure that specifies the new boot options. - * @param FieldsToChange A bitmask that specifies which fields in the BOOT_OPTIONS structure are to be changed. - * @return NTSTATUS Successful or errant status. + * \param BootOptions A pointer to a BOOT_OPTIONS structure that specifies the new boot options. + * \param FieldsToChange A bitmask that specifies which fields in the BOOT_OPTIONS structure are to be changed. + * \return NTSTATUS Successful or errant status. */ NTSYSCALLAPI NTSTATUS @@ -365,11 +376,11 @@ NtSetBootOptions( /** * The NtTranslateFilePath routine translates a file path from one format to another. * - * @param InputFilePath A pointer to a FILE_PATH structure that specifies the input file path. - * @param OutputType The type of the output file path. - * @param OutputFilePath A pointer to a buffer that receives the translated file path. - * @param OutputFilePathLength A pointer to a variable that specifies the size of the buffer. On return, it contains the size of the data returned. - * @return NTSTATUS Successful or errant status. + * \param InputFilePath A pointer to a FILE_PATH structure that specifies the input file path. + * \param OutputType The type of the output file path. + * \param OutputFilePath A pointer to a buffer that receives the translated file path. + * \param OutputFilePathLength A pointer to a variable that specifies the size of the buffer. On return, it contains the size of the data returned. + * \return NTSTATUS Successful or errant status. */ NTSYSCALLAPI NTSTATUS @@ -380,15 +391,13 @@ NtTranslateFilePath( _Out_writes_bytes_opt_(*OutputFilePathLength) PFILE_PATH OutputFilePath, _Inout_opt_ PULONG OutputFilePathLength ); -#endif // (PHNT_VERSION >= PHNT_WINDOWS_XP) -#if (PHNT_VERSION >= PHNT_WINDOWS_SERVER_2003) /** * The NtAddDriverEntry routine adds a new driver entry to the system boot configuration. * - * @param DriverEntry A pointer to an EFI_DRIVER_ENTRY structure that specifies the driver entry to be added. - * @param Id A pointer to a variable that receives the identifier of the new driver entry. - * @return NTSTATUS Successful or errant status. + * \param DriverEntry A pointer to an EFI_DRIVER_ENTRY structure that specifies the driver entry to be added. + * \param Id A pointer to a variable that receives the identifier of the new driver entry. + * \return NTSTATUS Successful or errant status. */ NTSYSCALLAPI NTSTATUS @@ -401,8 +410,8 @@ NtAddDriverEntry( /** * The NtDeleteDriverEntry routine deletes an existing driver entry from the system boot configuration. * - * @param Id The identifier of the driver entry to be deleted. - * @return NTSTATUS Successful or errant status. + * \param Id The identifier of the driver entry to be deleted. + * \return NTSTATUS Successful or errant status. */ NTSYSCALLAPI NTSTATUS @@ -414,8 +423,8 @@ NtDeleteDriverEntry( /** * The NtModifyDriverEntry routine modifies an existing driver entry in the system boot configuration. * - * @param DriverEntry A pointer to an EFI_DRIVER_ENTRY structure that specifies the new driver entry information. - * @return NTSTATUS Successful or errant status. + * \param DriverEntry A pointer to an EFI_DRIVER_ENTRY structure that specifies the new driver entry information. + * \return NTSTATUS Successful or errant status. */ NTSYSCALLAPI NTSTATUS @@ -427,9 +436,9 @@ NtModifyDriverEntry( /** * The NtEnumerateDriverEntries routine retrieves information about all driver entries in the system boot configuration. * - * @param Buffer A pointer to a buffer that receives the driver entries information. - * @param BufferLength A pointer to a variable that specifies the size of the buffer. On return, it contains the size of the data returned. - * @return NTSTATUS Successful or errant status. + * \param Buffer A pointer to a buffer that receives the driver entries information. + * \param BufferLength A pointer to a variable that specifies the size of the buffer. On return, it contains the size of the data returned. + * \return NTSTATUS Successful or errant status. */ NTSYSCALLAPI NTSTATUS @@ -442,9 +451,9 @@ NtEnumerateDriverEntries( /** * The NtQueryDriverEntryOrder routine retrieves the current driver entry order. * - * @param Ids A pointer to a buffer that receives the identifiers of the driver entries in the current driver order. - * @param Count A pointer to a variable that specifies the number of entries in the buffer. On return, it contains the number of entries returned. - * @return NTSTATUS Successful or errant status. + * \param Ids A pointer to a buffer that receives the identifiers of the driver entries in the current driver order. + * \param Count A pointer to a variable that specifies the number of entries in the buffer. On return, it contains the number of entries returned. + * \return NTSTATUS Successful or errant status. */ NTSYSCALLAPI NTSTATUS @@ -457,9 +466,9 @@ NtQueryDriverEntryOrder( /** * The NtSetDriverEntryOrder routine sets the driver entry order. * - * @param Ids A pointer to a buffer that specifies the identifiers of the driver entries in the desired driver order. - * @param Count The number of entries in the buffer. - * @return NTSTATUS Successful or errant status. + * \param Ids A pointer to a buffer that specifies the identifiers of the driver entries in the desired driver order. + * \param Count The number of entries in the buffer. + * \return NTSTATUS Successful or errant status. */ NTSYSCALLAPI NTSTATUS @@ -468,7 +477,6 @@ NtSetDriverEntryOrder( _In_reads_(Count) PULONG Ids, _In_ ULONG Count ); -#endif // (PHNT_VERSION >= PHNT_WINDOWS_SERVER_2003) typedef enum _FILTER_BOOT_OPTION_OPERATION { @@ -482,12 +490,12 @@ typedef enum _FILTER_BOOT_OPTION_OPERATION /** * The NtFilterBootOption routine filters boot options based on the specified operation, object type, and element type. * - * @param FilterOperation The operation to be performed on the boot option. This can be one of the values from the FILTER_BOOT_OPTION_OPERATION enumeration. - * @param ObjectType The type of the object to be filtered. - * @param ElementType The type of the element within the object to be filtered. - * @param Data A pointer to a buffer that contains the data to be used in the filter operation. This parameter is optional and can be NULL. - * @param DataSize The size, in bytes, of the data buffer pointed to by the Data parameter. - * @return NTSTATUS Successful or errant status. + * \param FilterOperation The operation to be performed on the boot option. This can be one of the values from the FILTER_BOOT_OPTION_OPERATION enumeration. + * \param ObjectType The type of the object to be filtered. + * \param ElementType The type of the element within the object to be filtered. + * \param Data A pointer to a buffer that contains the data to be used in the filter operation. This parameter is optional and can be NULL. + * \param DataSize The size, in bytes, of the data buffer pointed to by the Data parameter. + * \return NTSTATUS Successful or errant status. */ NTSYSCALLAPI NTSTATUS @@ -517,28 +525,34 @@ NtFilterBootOption( #define EVENT_ALL_ACCESS (EVENT_QUERY_STATE|EVENT_MODIFY_STATE|STANDARD_RIGHTS_REQUIRED|SYNCHRONIZE) #endif +/** + * The EVENT_INFORMATION_CLASS specifies the type of information to be retrieved about an event object. + */ typedef enum _EVENT_INFORMATION_CLASS { EventBasicInformation } EVENT_INFORMATION_CLASS; +/** + * The EVENT_BASIC_INFORMATION structure contains basic information about an event object. + */ typedef struct _EVENT_BASIC_INFORMATION { - EVENT_TYPE EventType; - LONG EventState; + EVENT_TYPE EventType; // The type of the event object (NotificationEvent or SynchronizationEvent). + LONG EventState; // The current state of the event object. Nonzero if the event is signaled; zero if not signaled. } EVENT_BASIC_INFORMATION, *PEVENT_BASIC_INFORMATION; /** * The NtCreateEvent routine creates an event object, sets the initial state of the event to the specified value, * and opens a handle to the object with the specified desired access. * - * @param EventHandle A pointer to a variable that receives the event object handle. - * @param DesiredAccess The access mask that specifies the requested access to the event object. - * @param ObjectAttributes A pointer to an OBJECT_ATTRIBUTES structure that specifies the object attributes. - * @param EventType The type of the event, which can be SynchronizationEvent or a NotificationEvent. - * @param InitialState The initial state of the event object. - * @return NTSTATUS Successful or errant status. - * @see https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/ntifs/nf-ntifs-zwcreateevent + * \param EventHandle A pointer to a variable that receives the event object handle. + * \param DesiredAccess The access mask that specifies the requested access to the event object. + * \param ObjectAttributes A pointer to an OBJECT_ATTRIBUTES structure that specifies the object attributes. + * \param EventType The type of the event, which can be SynchronizationEvent or a NotificationEvent. + * \param InitialState The initial state of the event object. + * \return NTSTATUS Successful or errant status. + * \see https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/ntifs/nf-ntifs-zwcreateevent */ NTSYSCALLAPI NTSTATUS @@ -554,10 +568,10 @@ NtCreateEvent( /** * The NtOpenEvent routine opens a handle to an existing event object. * - * @param EventHandle A pointer to a variable that receives the event object handle. - * @param DesiredAccess The access mask that specifies the requested access to the event object. - * @param ObjectAttributes A pointer to an OBJECT_ATTRIBUTES structure that specifies the object attributes. - * @return NTSTATUS Successful or errant status. + * \param EventHandle A pointer to a variable that receives the event object handle. + * \param DesiredAccess The access mask that specifies the requested access to the event object. + * \param ObjectAttributes A pointer to an OBJECT_ATTRIBUTES structure that specifies the object attributes. + * \return NTSTATUS Successful or errant status. */ NTSYSCALLAPI NTSTATUS @@ -571,9 +585,9 @@ NtOpenEvent( /** * The NtSetEvent routine sets an event object to the signaled state. * - * @param EventHandle A handle to the event object. - * @param PreviousState A pointer to a variable that receives the previous state of the event object. - * @return NTSTATUS Successful or errant status. + * \param EventHandle A handle to the event object. + * \param PreviousState A pointer to a variable that receives the previous state of the event object. + * \return NTSTATUS Successful or errant status. */ NTSYSCALLAPI NTSTATUS @@ -587,9 +601,9 @@ NtSetEvent( /** * The NtSetEventEx routine sets an event object to the signaled state and optionally acquires a lock. * - * @param ThreadId A handle to the thread. - * @param Lock A pointer to an RTL_SRWLOCK structure that specifies the lock to acquire. - * @return NTSTATUS Successful or errant status. + * \param ThreadId A handle to the thread. + * \param Lock A pointer to an RTL_SRWLOCK structure that specifies the lock to acquire. + * \return NTSTATUS Successful or errant status. */ NTSYSCALLAPI NTSTATUS @@ -603,8 +617,8 @@ NtSetEventEx( /** * The NtSetEventBoostPriority routine sets an event object to the signaled state and boosts the priority of threads waiting on the event. * - * @param EventHandle A handle to the event object. - * @return NTSTATUS Successful or errant status. + * \param EventHandle A handle to the event object. + * \return NTSTATUS Successful or errant status. */ NTSYSCALLAPI NTSTATUS @@ -616,8 +630,8 @@ NtSetEventBoostPriority( /** * The NtClearEvent routine sets an event object to the not-signaled state. * - * @param EventHandle A handle to the event object. - * @return NTSTATUS Successful or errant status. + * \param EventHandle A handle to the event object. + * \return NTSTATUS Successful or errant status. */ NTSYSCALLAPI NTSTATUS @@ -629,10 +643,10 @@ NtClearEvent( /** * The NtResetEvent routine sets an event object to the not-signaled state and optionally returns the previous state. * - * @param EventHandle A handle to the event object. - * @param PreviousState A pointer to a variable that receives the previous state of the event object. - * @return NTSTATUS Successful or errant status. - * @see https://learn.microsoft.com/en-us/windows/win32/api/synchapi/nf-synchapi-resetevent + * \param EventHandle A handle to the event object. + * \param PreviousState A pointer to a variable that receives the previous state of the event object. + * \return NTSTATUS Successful or errant status. + * \see https://learn.microsoft.com/en-us/windows/win32/api/synchapi/nf-synchapi-resetevent */ NTSYSCALLAPI NTSTATUS @@ -645,10 +659,10 @@ NtResetEvent( /** * The NtPulseEvent routine sets an event object to the signaled state and then resets it to the not-signaled state after releasing the appropriate number of waiting threads. * - * @param EventHandle A handle to the event object. - * @param PreviousState A pointer to a variable that receives the previous state of the event object. - * @return NTSTATUS Successful or errant status. - * @see https://learn.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-pulseevent + * \param EventHandle A handle to the event object. + * \param PreviousState A pointer to a variable that receives the previous state of the event object. + * \return NTSTATUS Successful or errant status. + * \see https://learn.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-pulseevent */ NTSYSCALLAPI NTSTATUS @@ -661,12 +675,12 @@ NtPulseEvent( /** * The NtQueryEvent routine retrieves information about an event object. * - * @param EventHandle A handle to the event object. - * @param EventInformationClass The type of information to be retrieved. - * @param EventInformation A pointer to a buffer that receives the requested information. - * @param EventInformationLength The size of the buffer pointed to by EventInformation. - * @param ReturnLength A pointer to a variable that receives the size of the data returned in the buffer. - * @return NTSTATUS Successful or errant status. + * \param EventHandle A handle to the event object. + * \param EventInformationClass The type of information to be retrieved. + * \param EventInformation A pointer to a buffer that receives the requested information. + * \param EventInformationLength The size of the buffer pointed to by EventInformation. + * \param ReturnLength A pointer to a variable that receives the size of the data returned in the buffer. + * \return NTSTATUS Successful or errant status. */ NTSYSCALLAPI NTSTATUS @@ -688,10 +702,11 @@ NtQueryEvent( /** * The NtCreateEventPair routine creates an event pair object and opens a handle to the object with the specified desired access. * - * @param EventPairHandle A pointer to a variable that receives the event pair object handle. - * @param DesiredAccess The access mask that specifies the requested access to the event pair object. - * @param ObjectAttributes A pointer to an OBJECT_ATTRIBUTES structure that specifies the object attributes. - * @return NTSTATUS Successful or errant status. + * \remark Event Pairs are used to communicate with protected subsystems (see Context Switches). + * \param EventPairHandle A pointer to a variable that receives the event pair object handle. + * \param DesiredAccess The access mask that specifies the requested access to the event pair object. + * \param ObjectAttributes A pointer to an OBJECT_ATTRIBUTES structure that specifies the object attributes. + * \return NTSTATUS Successful or errant status. */ NTSYSCALLAPI NTSTATUS @@ -705,10 +720,10 @@ NtCreateEventPair( /** * The NtOpenEventPair routine opens a handle to an existing event pair object. * - * @param EventPairHandle A pointer to a variable that receives the event pair object handle. - * @param DesiredAccess The access mask that specifies the requested access to the event pair object. - * @param ObjectAttributes A pointer to an OBJECT_ATTRIBUTES structure that specifies the object attributes. - * @return NTSTATUS Successful or errant status. + * \param EventPairHandle A pointer to a variable that receives the event pair object handle. + * \param DesiredAccess The access mask that specifies the requested access to the event pair object. + * \param ObjectAttributes A pointer to an OBJECT_ATTRIBUTES structure that specifies the object attributes. + * \return NTSTATUS Successful or errant status. */ NTSYSCALLAPI NTSTATUS @@ -722,8 +737,8 @@ NtOpenEventPair( /** * The NtSetLowEventPair routine sets the low event in an event pair to the signaled state. * - * @param EventPairHandle A handle to the event pair object. - * @return NTSTATUS Successful or errant status. + * \param EventPairHandle A handle to the event pair object. + * \return NTSTATUS Successful or errant status. */ NTSYSCALLAPI NTSTATUS @@ -735,8 +750,8 @@ NtSetLowEventPair( /** * The NtSetHighEventPair routine sets the high event in an event pair to the signaled state. * - * @param EventPairHandle A handle to the event pair object. - * @return NTSTATUS Successful or errant status. + * \param EventPairHandle A handle to the event pair object. + * \return NTSTATUS Successful or errant status. */ NTSYSCALLAPI NTSTATUS @@ -748,8 +763,8 @@ NtSetHighEventPair( /** * The NtWaitLowEventPair routine waits for the low event in an event pair to be set to the signaled state. * - * @param EventPairHandle A handle to the event pair object. - * @return NTSTATUS Successful or errant status. + * \param EventPairHandle A handle to the event pair object. + * \return NTSTATUS Successful or errant status. */ NTSYSCALLAPI NTSTATUS @@ -761,8 +776,8 @@ NtWaitLowEventPair( /** * The NtWaitHighEventPair routine waits for the high event in an event pair to be set to the signaled state. * - * @param EventPairHandle A handle to the event pair object. - * @return NTSTATUS Successful or errant status. + * \param EventPairHandle A handle to the event pair object. + * \return NTSTATUS Successful or errant status. */ NTSYSCALLAPI NTSTATUS @@ -774,8 +789,8 @@ NtWaitHighEventPair( /** * The NtSetLowWaitHighEventPair routine sets the low event in an event pair to the signaled state and waits for the high event to be set to the signaled state. * - * @param EventPairHandle A handle to the event pair object. - * @return NTSTATUS Successful or errant status. + * \param EventPairHandle A handle to the event pair object. + * \return NTSTATUS Successful or errant status. */ NTSYSCALLAPI NTSTATUS @@ -787,8 +802,8 @@ NtSetLowWaitHighEventPair( /** * The NtSetHighWaitLowEventPair routine sets the high event in an event pair to the signaled state and waits for the low event to be set to the signaled state. * - * @param EventPairHandle A handle to the event pair object. - * @return NTSTATUS Successful or errant status. + * \param EventPairHandle A handle to the event pair object. + * \return NTSTATUS Successful or errant status. */ NTSYSCALLAPI NTSTATUS @@ -837,11 +852,11 @@ typedef struct _MUTANT_OWNER_INFORMATION * The NtCreateMutant routine creates a mutant object, sets the initial state of the mutant to the specified value, * and opens a handle to the object with the specified desired access. * - * @param MutantHandle A pointer to a variable that receives the mutant object handle. - * @param DesiredAccess The access mask that specifies the requested access to the mutant object. - * @param ObjectAttributes A pointer to an OBJECT_ATTRIBUTES structure that specifies the object attributes. - * @param InitialOwner If TRUE, the calling thread is the initial owner of the mutant object. - * @return NTSTATUS Successful or errant status. + * \param MutantHandle A pointer to a variable that receives the mutant object handle. + * \param DesiredAccess The access mask that specifies the requested access to the mutant object. + * \param ObjectAttributes A pointer to an OBJECT_ATTRIBUTES structure that specifies the object attributes. + * \param InitialOwner If TRUE, the calling thread is the initial owner of the mutant object. + * \return NTSTATUS Successful or errant status. */ NTSYSCALLAPI NTSTATUS @@ -856,10 +871,10 @@ NtCreateMutant( /** * The NtOpenMutant routine opens a handle to an existing mutant object. * - * @param MutantHandle A pointer to a variable that receives the mutant object handle. - * @param DesiredAccess The access mask that specifies the requested access to the mutant object. - * @param ObjectAttributes A pointer to an OBJECT_ATTRIBUTES structure that specifies the object attributes. - * @return NTSTATUS Successful or errant status. + * \param MutantHandle A pointer to a variable that receives the mutant object handle. + * \param DesiredAccess The access mask that specifies the requested access to the mutant object. + * \param ObjectAttributes A pointer to an OBJECT_ATTRIBUTES structure that specifies the object attributes. + * \return NTSTATUS Successful or errant status. */ NTSYSCALLAPI NTSTATUS @@ -873,9 +888,9 @@ NtOpenMutant( /** * The NtReleaseMutant routine releases ownership of a mutant object. * - * @param MutantHandle A handle to the mutant object. - * @param PreviousCount A pointer to a variable that receives the previous count of the mutant object. - * @return NTSTATUS Successful or errant status. + * \param MutantHandle A handle to the mutant object. + * \param PreviousCount A pointer to a variable that receives the previous count of the mutant object. + * \return NTSTATUS Successful or errant status. */ NTSYSCALLAPI NTSTATUS @@ -888,12 +903,12 @@ NtReleaseMutant( /** * The NtQueryMutant routine retrieves information about a mutant object. * - * @param MutantHandle A handle to the mutant object. - * @param MutantInformationClass The type of information to be retrieved. - * @param MutantInformation A pointer to a buffer that receives the requested information. - * @param MutantInformationLength The size of the buffer pointed to by MutantInformation. - * @param ReturnLength A pointer to a variable that receives the size of the data returned in the buffer. - * @return NTSTATUS Successful or errant status. + * \param MutantHandle A handle to the mutant object. + * \param MutantInformationClass The type of information to be retrieved. + * \param MutantInformation A pointer to a buffer that receives the requested information. + * \param MutantInformationLength The size of the buffer pointed to by MutantInformation. + * \param ReturnLength A pointer to a variable that receives the size of the data returned in the buffer. + * \return NTSTATUS Successful or errant status. */ NTSYSCALLAPI NTSTATUS @@ -940,12 +955,12 @@ typedef struct _SEMAPHORE_BASIC_INFORMATION * The NtCreateSemaphore routine creates a semaphore object, sets the initial count of the semaphore to the specified value, * and opens a handle to the object with the specified desired access. * - * @param SemaphoreHandle A pointer to a variable that receives the semaphore object handle. - * @param DesiredAccess The access mask that specifies the requested access to the semaphore object. - * @param ObjectAttributes A pointer to an OBJECT_ATTRIBUTES structure that specifies the object attributes. - * @param InitialCount The initial count of the semaphore object. - * @param MaximumCount The maximum count of the semaphore object. - * @return NTSTATUS Successful or errant status. + * \param SemaphoreHandle A pointer to a variable that receives the semaphore object handle. + * \param DesiredAccess The access mask that specifies the requested access to the semaphore object. + * \param ObjectAttributes A pointer to an OBJECT_ATTRIBUTES structure that specifies the object attributes. + * \param InitialCount The initial count of the semaphore object. + * \param MaximumCount The maximum count of the semaphore object. + * \return NTSTATUS Successful or errant status. */ NTSYSCALLAPI NTSTATUS @@ -961,10 +976,10 @@ NtCreateSemaphore( /** * The NtOpenSemaphore routine opens a handle to an existing semaphore object. * - * @param SemaphoreHandle A pointer to a variable that receives the semaphore object handle. - * @param DesiredAccess The access mask that specifies the requested access to the semaphore object. - * @param ObjectAttributes A pointer to an OBJECT_ATTRIBUTES structure that specifies the object attributes. - * @return NTSTATUS Successful or errant status. + * \param SemaphoreHandle A pointer to a variable that receives the semaphore object handle. + * \param DesiredAccess The access mask that specifies the requested access to the semaphore object. + * \param ObjectAttributes A pointer to an OBJECT_ATTRIBUTES structure that specifies the object attributes. + * \return NTSTATUS Successful or errant status. */ NTSYSCALLAPI NTSTATUS @@ -978,10 +993,10 @@ NtOpenSemaphore( /** * The NtReleaseSemaphore routine increases the count of the specified semaphore object by a specified amount. * - * @param SemaphoreHandle A handle to the semaphore object. - * @param ReleaseCount The amount by which the semaphore object's count is to be increased. - * @param PreviousCount A pointer to a variable that receives the previous count of the semaphore object. - * @return NTSTATUS Successful or errant status. + * \param SemaphoreHandle A handle to the semaphore object. + * \param ReleaseCount The amount by which the semaphore object's count is to be increased. + * \param PreviousCount A pointer to a variable that receives the previous count of the semaphore object. + * \return NTSTATUS Successful or errant status. */ NTSYSCALLAPI NTSTATUS @@ -995,12 +1010,12 @@ NtReleaseSemaphore( /** * The NtQuerySemaphore routine retrieves information about a semaphore object. * - * @param SemaphoreHandle A handle to the semaphore object. - * @param SemaphoreInformationClass The type of information to be retrieved. - * @param SemaphoreInformation A pointer to a buffer that receives the requested information. - * @param SemaphoreInformationLength The size of the buffer pointed to by SemaphoreInformation. - * @param ReturnLength A pointer to a variable that receives the size of the data returned in the buffer. - * @return NTSTATUS Successful or errant status. + * \param SemaphoreHandle A handle to the semaphore object. + * \param SemaphoreInformationClass The type of information to be retrieved. + * \param SemaphoreInformation A pointer to a buffer that receives the requested information. + * \param SemaphoreInformationLength The size of the buffer pointed to by SemaphoreInformation. + * \param ReturnLength A pointer to a variable that receives the size of the data returned in the buffer. + * \return NTSTATUS Successful or errant status. */ NTSYSCALLAPI NTSTATUS @@ -1034,6 +1049,15 @@ typedef enum _TIMER_INFORMATION_CLASS TimerBasicInformation // TIMER_BASIC_INFORMATION } TIMER_INFORMATION_CLASS; +typedef enum _TIMER_SET_INFORMATION_CLASS +{ + TimerSetCoalescableTimer, // TIMER_SET_COALESCABLE_TIMER_INFO + MaxTimerInfoClass +} TIMER_SET_INFORMATION_CLASS; + +/** + * The TIMER_BASIC_INFORMATION structure contains basic information about a timer object. + */ typedef struct _TIMER_BASIC_INFORMATION { LARGE_INTEGER RemainingTime; @@ -1048,12 +1072,6 @@ VOID NTAPI TIMER_APC_ROUTINE( ); typedef TIMER_APC_ROUTINE* PTIMER_APC_ROUTINE; -typedef enum _TIMER_SET_INFORMATION_CLASS -{ - TimerSetCoalescableTimer, // TIMER_SET_COALESCABLE_TIMER_INFO - MaxTimerInfoClass -} TIMER_SET_INFORMATION_CLASS; - typedef struct _TIMER_SET_COALESCABLE_TIMER_INFO { _In_ LARGE_INTEGER DueTime; @@ -1065,6 +1083,15 @@ typedef struct _TIMER_SET_COALESCABLE_TIMER_INFO _Out_opt_ PBOOLEAN PreviousState; } TIMER_SET_COALESCABLE_TIMER_INFO, *PTIMER_SET_COALESCABLE_TIMER_INFO; +/** + * The NtCreateTimer routine creates a timer object. + * + * \param TimerHandle A pointer to a variable that receives the handle to the timer object. + * \param DesiredAccess The access mask that specifies the requested access to the timer object. + * \param ObjectAttributes A pointer to an OBJECT_ATTRIBUTES structure that specifies the object attributes. + * \param TimerType The type of the timer object. + * \return NTSTATUS Successful or errant status. + */ NTSYSCALLAPI NTSTATUS NTAPI @@ -1075,6 +1102,14 @@ NtCreateTimer( _In_ TIMER_TYPE TimerType ); +/** + * The NtOpenTimer routine opens a handle to an existing timer object. + * + * \param TimerHandle A pointer to a variable that receives the handle to the timer object. + * \param DesiredAccess The access mask that specifies the requested access to the timer object. + * \param ObjectAttributes A pointer to an OBJECT_ATTRIBUTES structure that specifies the object attributes. + * \return NTSTATUS Successful or errant status. + */ NTSYSCALLAPI NTSTATUS NTAPI @@ -1084,6 +1119,18 @@ NtOpenTimer( _In_ PCOBJECT_ATTRIBUTES ObjectAttributes ); +/** + * The NtSetTimer routine sets a timer object to the signaled state after a specified interval. + * + * \param TimerHandle A handle to the timer object. + * \param DueTime A pointer to a LARGE_INTEGER that specifies the absolute or relative time at which the timer is to be set to the signaled state. + * \param TimerApcRoutine An optional pointer to a function to be called when the timer is signaled. + * \param TimerContext An optional pointer to a context to be passed to the APC routine. + * \param ResumeTimer If TRUE, resumes the timer; otherwise, sets a new timer. + * \param Period The period of the timer, in milliseconds. If zero, the timer is signaled once. + * \param PreviousState A pointer to a variable that receives the previous state of the timer. + * \return NTSTATUS Successful or errant status. + */ NTSYSCALLAPI NTSTATUS NTAPI @@ -1097,7 +1144,15 @@ NtSetTimer( _Out_opt_ PBOOLEAN PreviousState ); -#if (PHNT_VERSION >= PHNT_WINDOWS_7) +/** + * The NtSetTimerEx routine sets extended information for a timer object. + * + * \param TimerHandle A handle to the timer object. + * \param TimerSetInformationClass The class of information to set. + * \param TimerSetInformation A pointer to a buffer that contains the information to set. + * \param TimerSetInformationLength The size of the buffer, in bytes. + * \return NTSTATUS Successful or errant status. + */ NTSYSCALLAPI NTSTATUS NTAPI @@ -1107,8 +1162,14 @@ NtSetTimerEx( _Inout_updates_bytes_opt_(TimerSetInformationLength) PVOID TimerSetInformation, _In_ ULONG TimerSetInformationLength ); -#endif // (PHNT_VERSION >= PHNT_WINDOWS_7) +/** + * The NtCancelTimer routine Cancels a timer object. + * + * \param TimerHandle A handle to the timer object. + * \param CurrentState A pointer to a variable that receives the current state of the timer object. + * \return NTSTATUS Successful or errant status. + */ NTSYSCALLAPI NTSTATUS NTAPI @@ -1117,6 +1178,16 @@ NtCancelTimer( _Out_opt_ PBOOLEAN CurrentState ); +/** + * The NtQueryTimer routine retrieves information about a timer object. + * + * \param TimerHandle A handle to the timer object. + * \param TimerInformationClass The class of information to retrieve. + * \param TimerInformation A pointer to a buffer that receives the requested information. + * \param TimerInformationLength The size of the buffer, in bytes. + * \param ReturnLength A pointer to a variable that receives the size of the data returned. + * \return NTSTATUS Successful or errant status. + */ NTSYSCALLAPI NTSTATUS NTAPI @@ -1130,15 +1201,88 @@ NtQueryTimer( #if (PHNT_VERSION >= PHNT_WINDOWS_8) +// ExCheckValidIRTimerId +typedef enum _IR_TIMER_PROVIDER_INDEX +{ + IR_TIMER_PROVIDER_TESTIDENTIFIER, // Token(Service SID) + IR_TIMER_PROVIDER_BROKERINFRASTRUCTURE, // Token(Service SID) + IR_TIMER_PROVIDER_TIMEBROKERSVC, // Token(Service SID) + IR_TIMER_PROVIDER_LFSVC, + IR_TIMER_PROVIDER_WINLOGON, + IR_TIMER_PROVIDER_POWER, + IR_TIMER_PROVIDER_SENSORSERVICE, + IR_TIMER_PROVIDER_NTOSPO, + IR_TIMER_PROVIDER_ACPI, + IR_TIMER_PROVIDER_BUTTON, + IR_TIMER_PROVIDER_MSGPIOCLX, + IR_TIMER_PROVIDER_BUTTONCONVERTER, + IR_TIMER_PROVIDER_MSGPIOWIN32, + IR_TIMER_PROVIDER_KNETPWRDEPBROKER, + IR_TIMER_PROVIDER_CMBATT, + IR_TIMER_PROVIDER_BTHPORT, + IR_TIMER_PROVIDER_AUDIOSRV, // TOKEN(SERVICE SID) + IR_TIMER_PROVIDER_ARTESTIDENTIFIER, // TOKEN(SERVICE SID) + IR_TIMER_PROVIDER_BATTC, + IR_TIMER_PROVIDER_MAXINDEX +} IR_TIMER_PROVIDER_INDEX; + +//CONST USHORT IR_TIMER_PROVIDER_ID_MAX[] = +//{ +// 1, // IR_TIMER_PROVIDER_TESTIDENTIFIER +// 1, // IR_TIMER_PROVIDER_BROKERINFRASTRUCTURE +// 1, // IR_TIMER_PROVIDER_TIMEBROKERSVC +// 11, // IR_TIMER_PROVIDER_LFSVC (0x0B) +// 1, // IR_TIMER_PROVIDER_WINLOGON +// 2, // IR_TIMER_PROVIDER_POWER +// 1, // IR_TIMER_PROVIDER_SENSORSERVICE +// 6, // IR_TIMER_PROVIDER_NTOSPO +// 1, // IR_TIMER_PROVIDER_ACPI +// 1, // IR_TIMER_PROVIDER_BUTTON +// 2, // MsGpioClx +// 1, // ButtonConverter +// 2, // MsGpioWin32 +// 2, // KNetPwrDepBroker +// 1, // Cmbatt +// 2, // Bthport +// 1, // AudioSrv +// 1, // ArTestIdentifier +// 1 // Battc +//}; + +// rev +#define IR_TIMERID_PROVIDER(TimerId) ((USHORT)LOWORD((ULONG)(TimerId))) +#define IR_TIMERID_ID(TimerId) ((USHORT)HIWORD((ULONG)(TimerId))) +#define IR_TIMERID_IS_NONZERO(TimerId) (IR_TIMERID_PROVIDER(TimerId) != 0) +#define IR_TIMERID_ATTRIBUTES(ProviderIndex, ProviderId) \ + ((ULONG)MAKELONG((USHORT)(ProviderIndex), (USHORT)(ProviderId))) + +/** + * The NtCreateIRTimer routine creates an IR timer object. + * IR timers are interruptdriven and designed for high-resolution timing in system components. + * + * \param TimerHandle A pointer to a variable that receives the handle to the IR timer object. + * \param TimerId A pointer to a timer identifier that specifies the provider. + * \param DesiredAccess The access mask that specifies the requested access to the timer object. + * \return NTSTATUS Successful or errant status. + * \remarks The TimerId must be non-NULL and point to a valid timer identifier. + */ NTSYSCALLAPI NTSTATUS NTAPI NtCreateIRTimer( _Out_ PHANDLE TimerHandle, - _In_ PVOID Reserved, + _In_ PULONG TimerId, _In_ ACCESS_MASK DesiredAccess ); +/** + * The NtSetIRTimer routine sets an IR timer object. + * + * \param TimerHandle A handle to the IR timer object. + * \param DueTime An optional pointer to a LARGE_INTEGER that specifies + * the time at which the timer is to be set to the signaled state. + * \return NTSTATUS Successful or errant status. + */ NTSYSCALLAPI NTSTATUS NTAPI @@ -1150,31 +1294,118 @@ NtSetIRTimer( #endif // (PHNT_VERSION >= PHNT_WINDOWS_8) #if (PHNT_VERSION >= PHNT_WINDOWS_10) +// +// NtCreateTimer2 Attributes +// +#define TIMER2_ATTRIBUTE_IR_TIMER 0x00000002UL +#define TIMER2_ATTRIBUTE_HIGH_RESOLUTION 0x00000004UL +#define TIMER2_ATTRIBUTE_NO_WAKE 0x00000008UL +#define TIMER2_ATTRIBUTE_NOTIFICATION 0x80000000UL +// rev +#define TIMER2_ATTRIBUTE_KNOWN_MASK (TIMER2_ATTRIBUTE_IR_TIMER | TIMER2_ATTRIBUTE_HIGH_RESOLUTION | TIMER2_ATTRIBUTE_NO_WAKE | TIMER2_ATTRIBUTE_NOTIFICATION) +#define TIMER2_ATTRIBUTE_RESERVED_MASK (~TIMER2_ATTRIBUTE_KNOWN_MASK) +#define TIMER2_ATTRIBUTE_FOR_TYPE(T) \ + (((T) == NotificationTimer) ? TIMER2_ATTRIBUTE_NOTIFICATION : 0) + +// Build attributes for a *non-IR* timer +// - T: TIMER_TYPE (NotificationTimer/SynchronizationTimer) +// - R: bool for HighResolution +// +#define TIMER2_BUILD_ATTRIBUTES(T, R) \ + (TIMER2_ATTRIBUTE_FOR_TYPE(T) | ((R) ? TIMER2_ATTRIBUTE_HIGH_RESOLUTION : 0)) + +// Build attributes for an *IR* timer +// - R: bool for HighResolution +// +#define TIMER2_BUILD_IR_ATTRIBUTES(R) \ + (TIMER2_ATTRIBUTE_IR_TIMER | ((R) ? TIMER2_ATTRIBUTE_HIGH_RESOLUTION : 0)) + +// rev +typedef union _TIMER2_ATTRIBUTES +{ + ULONG Value; + struct + { + ULONG Reserved0 : 1; // bit 0 (reserved) + ULONG IrTimer : 1; // bit 1 == TIMER2_ATTRIBUTE_IR_TIMER + ULONG HighResolution : 1; // bit 2 == TIMER2_ATTRIBUTE_HIGH_RESOLUTION + ULONG NoWake : 1; // bit 3 == TIMER2_ATTRIBUTE_NO_WAKE + ULONG Reserved1 : 27; // bits [4..30] (reserved) + TIMER_TYPE NotificationType : 1; // bit 31 == TIMER2_ATTRIBUTE_NOTIFICATION + }; +} TIMER2_ATTRIBUTES; + +/** + * The NtCreateTimer2 routine creates a timer object. + * + * \param TimerHandle A pointer to a variable that receives the handle to the timer object. + * \param TimerId For IR timers: A pointer to ULONG TIMERID (non-NULL). For non-IR timers: must be NULL. + * \param ObjectAttributes A pointer to an OBJECT_ATTRIBUTES structure that specifies the object attributes. + * \param Attributes Timer attributes (TIMER_TYPE). + * \param DesiredAccess The access mask that specifies the requested access to the timer object. + * \return NTSTATUS Successful or errant status. + * \sa https://learn.microsoft.com/en-us/windows/win32/api/synchapi/nf-synchapi-createwaitabletimerexw + */ NTSYSCALLAPI NTSTATUS NTAPI NtCreateTimer2( _Out_ PHANDLE TimerHandle, - _In_opt_ PVOID Reserved1, + _In_opt_ PULONG TimerId, _In_opt_ PCOBJECT_ATTRIBUTES ObjectAttributes, - _In_ ULONG Attributes, // TIMER_TYPE + _In_ ULONG Attributes, _In_ ACCESS_MASK DesiredAccess ); - #endif // (PHNT_VERSION >= PHNT_WINDOWS_10) +// rev +#define TIMER2_SET_PARAMETERS_CURRENT_VERSION 0 + +// rev +/** + * The T2_SET_PARAMETERS structure configures the high-resolution or coalescable timers, + * and specify a "no-wake tolerance" value, which controls how much the kernel + * may delay the timers for coalescing or power efficiency. + * \remarks Setting NoWakeTolerance to 0 requests **no coalescing** and the most precise + * wake-up behavior the system can provide. + */ typedef struct _T2_SET_PARAMETERS_V0 { + /** + * Structure version. Must be set to zero. + */ ULONG Version; + /** + * Reserved. + */ ULONG Reserved; + /** + * Maximum tolerable delay (in 100-ns units) for timer coalescing. + * - Set to 0 for **no coalescing** (strict wake-up). + * - Set to a positive value to allow the kernel to delay the timer + * by up to this amount for power efficiency. + * Example: + * If NoWakeTolerance = 0 --> High-resolution, best precision, min jitter, zero coalescing, low power savings. + * If NoWakeTolerance > 0 --> Normal-resolution, allow up to this value of coalescing, normal power savings. + * If NoWakeTolerance = -1 --> Low-resolution, worst precision, max jitter, max coalescing, max power savings. + */ LONGLONG NoWakeTolerance; } T2_SET_PARAMETERS, *PT2_SET_PARAMETERS; typedef PVOID PT2_CANCEL_PARAMETERS; #if (PHNT_VERSION >= PHNT_WINDOWS_10) - +/** + * The NtSetTimer2 routine activates the timer object for a specified interval with optional periodic behavior. + * + * \param TimerHandle A handle to the timer object to set. + * \param DueTime A pointer to a LARGE_INTEGER specifying the absolute or relative time when the timer should expire. + * \param Period An optional pointer to a LARGE_INTEGER specifying the period for periodic timer notifications, in 100-nanosecond intervals. If NULL, the timer is non-periodic. + * \param Parameters A pointer to a T2_SET_PARAMETERS structure containing additional timer configuration parameters. + * \return NTSTATUS Successful or errant status. + * \sa https://learn.microsoft.com/en-us/windows/win32/api/synchapi/nf-synchapi-setwaitabletimer + */ NTSYSCALLAPI NTSTATUS NTAPI @@ -1182,9 +1413,17 @@ NtSetTimer2( _In_ HANDLE TimerHandle, _In_ PLARGE_INTEGER DueTime, _In_opt_ PLARGE_INTEGER Period, - _In_ PT2_SET_PARAMETERS Parameters + _In_opt_ PT2_SET_PARAMETERS Parameters ); +/** + * The NtCancelTimer2 routine sets the specified waitable timer to the inactive state. + * + * \param TimerHandle A handle to the timer object to set. + * \param Parameters A pointer to a PT2_CANCEL_PARAMETERS structure containing additional parameters. + * \return NTSTATUS Successful or errant status. + * \sa https://learn.microsoft.com/en-us/windows/win32/api/synchapi/nf-synchapi-cancelwaitabletimer + */ NTSYSCALLAPI NTSTATUS NTAPI @@ -1192,7 +1431,6 @@ NtCancelTimer2( _In_ HANDLE TimerHandle, _In_ PT2_CANCEL_PARAMETERS Parameters ); - #endif // (PHNT_VERSION >= PHNT_WINDOWS_10) // @@ -1202,6 +1440,20 @@ NtCancelTimer2( #define PROFILE_CONTROL 0x0001 #define PROFILE_ALL_ACCESS (STANDARD_RIGHTS_REQUIRED | PROFILE_CONTROL) +/** + * The NtCreateProfile routine creates a profile object for performance monitoring. + * + * \param ProfileHandle A pointer to a variable that receives the handle to the profile object. + * \param Process Optional handle to the process to be profiled. If NULL, the current process is used. + * \param ProfileBase The base address of the region to be profiled. + * \param ProfileSize The size, in bytes, of the region to be profiled. + * \param BucketSize The size, in bytes, of each bucket in the profile buffer. + * \param Buffer A pointer to a buffer that receives the profile data. + * \param BufferSize The size, in bytes, of the buffer. + * \param ProfileSource The source of the profiling data (KPROFILE_SOURCE). + * \param Affinity The processor affinity mask indicating which processors to profile. + * \return NTSTATUS Successful or errant status. + */ NTSYSCALLAPI NTSTATUS NTAPI @@ -1217,7 +1469,21 @@ NtCreateProfile( _In_ KAFFINITY Affinity ); -#if (PHNT_VERSION >= PHNT_WINDOWS_7) +/** + * The NtCreateProfileEx routine creates a profile object for performance monitoring with group affinity. + * + * \param ProfileHandle A pointer to a variable that receives the handle to the profile object. + * \param Process Optional handle to the process to be profiled. If NULL, the current process is used. + * \param ProfileBase The base address of the region to be profiled. + * \param ProfileSize The size, in bytes, of the region to be profiled. + * \param BucketSize The size, in bytes, of each bucket in the profile buffer. + * \param Buffer A pointer to a buffer that receives the profile data. + * \param BufferSize The size, in bytes, of the buffer. + * \param ProfileSource The source of the profiling data (KPROFILE_SOURCE). + * \param GroupCount The number of group affinities provided. + * \param GroupAffinity A pointer to an array of GROUP_AFFINITY structures specifying processor groups to profile. + * \return NTSTATUS Successful or errant status. + */ NTSYSCALLAPI NTSTATUS NTAPI @@ -1233,8 +1499,13 @@ NtCreateProfileEx( _In_ USHORT GroupCount, _In_reads_(GroupCount) PGROUP_AFFINITY GroupAffinity ); -#endif // (PHNT_VERSION >= PHNT_WINDOWS_7) +/** + * The NtStartProfile routine starts the specified profile object. + * + * \param ProfileHandle A handle to the profile object. + * \return NTSTATUS Successful or errant status. + */ NTSYSCALLAPI NTSTATUS NTAPI @@ -1242,6 +1513,12 @@ NtStartProfile( _In_ HANDLE ProfileHandle ); +/** + * The NtStopProfile routine stops the specified profile object. + * + * \param ProfileHandle A handle to the profile object. + * \return NTSTATUS Successful or errant status. + */ NTSYSCALLAPI NTSTATUS NTAPI @@ -1249,6 +1526,13 @@ NtStopProfile( _In_ HANDLE ProfileHandle ); +/** + * The NtQueryIntervalProfile routine retrieves the interval for the specified profile source. + * + * \param ProfileSource The profile source (KPROFILE_SOURCE) to query. + * \param Interval A pointer to a variable that receives the interval, in 100-nanosecond units. + * \return NTSTATUS Successful or errant status. + */ NTSYSCALLAPI NTSTATUS NTAPI @@ -1257,6 +1541,13 @@ NtQueryIntervalProfile( _Out_ PULONG Interval ); +/** + * The NtSetIntervalProfile routine sets the interval for the specified profile source. + * + * \param Interval The interval, in 100-nanosecond units, to set. + * \param Source The profile source (KPROFILE_SOURCE) to set the interval for. + * \return NTSTATUS Successful or errant status. + */ NTSYSCALLAPI NTSTATUS NTAPI @@ -1265,13 +1556,24 @@ NtSetIntervalProfile( _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) +/** + * The NtCreateKeyedEvent routine creates a keyed event object and returns a handle to it. + * + * \param KeyedEventHandle A pointer to a variable that receives the handle to the keyed event object. + * \param DesiredAccess The access mask that specifies the requested access to the keyed event object. + * \param ObjectAttributes A pointer to an OBJECT_ATTRIBUTES structure that specifies the object attributes. + * \param Flags Reserved. Must be zero. + * \return NTSTATUS Successful or errant status. + */ NTSYSCALLAPI NTSTATUS NTAPI @@ -1282,6 +1584,14 @@ NtCreateKeyedEvent( _Reserved_ ULONG Flags ); +/** + * The NtOpenKeyedEvent routine opens a handle to an existing keyed event object. + * + * \param KeyedEventHandle A pointer to a variable that receives the handle to the keyed event object. + * \param DesiredAccess The access mask that specifies the requested access to the keyed event object. + * \param ObjectAttributes A pointer to an OBJECT_ATTRIBUTES structure that specifies the object attributes. + * \return NTSTATUS Successful or errant status. + */ NTSYSCALLAPI NTSTATUS NTAPI @@ -1291,6 +1601,15 @@ NtOpenKeyedEvent( _In_ PCOBJECT_ATTRIBUTES ObjectAttributes ); +/** + * The NtReleaseKeyedEvent routine releases a thread that is waiting on a keyed event with the specified key value. + * + * \param KeyedEventHandle Optional handle to the keyed event object. If NULL, the default keyed event is used. + * \param KeyValue The key value that identifies the waiting thread to release. + * \param Alertable Specifies whether the call is alertable (can be interrupted by APCs). + * \param Timeout Optional pointer to a timeout value (in 100-nanosecond intervals). If NULL, waits indefinitely. + * \return NTSTATUS Successful or errant status. + */ NTSYSCALLAPI NTSTATUS NTAPI @@ -1301,6 +1620,15 @@ NtReleaseKeyedEvent( _In_opt_ PLARGE_INTEGER Timeout ); +/** + * The NtWaitForKeyedEvent routine waits for a keyed event to be released with the specified key value. + * + * \param KeyedEventHandle Optional handle to the keyed event object. If NULL, the default keyed event is used. + * \param KeyValue The key value to wait for. + * \param Alertable Specifies whether the call is alertable (can be interrupted by APCs). + * \param Timeout Optional pointer to a timeout value (in 100-nanosecond intervals). If NULL, waits indefinitely. + * \return NTSTATUS Successful or errant status. + */ NTSYSCALLAPI NTSTATUS NTAPI @@ -1315,14 +1643,20 @@ NtWaitForKeyedEvent( // UMS // -#if (PHNT_VERSION >= PHNT_WINDOWS_7) +/** + * The NtUmsThreadYield routine yields control to the user-mode scheduling (UMS) scheduler thread on which the calling UMS worker thread is running. + * Note: As of Windows 11, user-mode scheduling is not supported. All calls fail with the error STATUS_NOT_SUPPORTED. + * + * \param SchedulerParam Optional handle to the keyed event object. If NULL, the default keyed event is used. + * \return NTSTATUS Successful or errant status. + * \sa https://learn.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-umsthreadyield + */ NTSYSCALLAPI NTSTATUS NTAPI NtUmsThreadYield( _In_ PVOID SchedulerParam ); -#endif // (PHNT_VERSION >= PHNT_WINDOWS_7) // // WNF @@ -1332,7 +1666,19 @@ NtUmsThreadYield( typedef struct _WNF_STATE_NAME { - ULONG Data[2]; + union + { + ULONGLONG Value; + ULONG Data[2]; + struct + { + ULONG64 Version : 4; + ULONG64 NameLifetime : 2; + ULONG64 DataScope : 4; + ULONG64 PermanentData : 1; + ULONG64 Unique : 53; + }; + }; } WNF_STATE_NAME, *PWNF_STATE_NAME; typedef const WNF_STATE_NAME *PCWNF_STATE_NAME; @@ -1386,7 +1732,18 @@ typedef struct _WNF_DELIVERY_DESCRIPTOR // end_private #if (PHNT_VERSION >= PHNT_WINDOWS_8) - +/** + * The NtCreateWnfStateName routine creates a new WNF (Windows Notification Facility) state name. + * + * \param StateName Pointer to a WNF_STATE_NAME structure that receives the created state name. + * \param NameLifetime The lifetime of the state name (see WNF_STATE_NAME_LIFETIME). + * \param DataScope The data scope for the state name (see WNF_DATA_SCOPE). + * \param PersistData If TRUE, the state data is persistent. + * \param TypeId Optional pointer to a WNF_TYPE_ID structure specifying the type of the state data. + * \param MaximumStateSize The maximum size, in bytes, of the state data. + * \param SecurityDescriptor Pointer to a security descriptor for the state name. + * \return NTSTATUS Successful or errant status. + */ NTSYSCALLAPI NTSTATUS NTAPI @@ -1400,6 +1757,12 @@ NtCreateWnfStateName( _In_ PSECURITY_DESCRIPTOR SecurityDescriptor ); +/** + * The NtDeleteWnfStateName routine deletes an existing WNF state name. + * + * \param StateName Pointer to the WNF_STATE_NAME to delete. + * \return NTSTATUS Successful or errant status. + */ NTSYSCALLAPI NTSTATUS NTAPI @@ -1407,6 +1770,18 @@ NtDeleteWnfStateName( _In_ PCWNF_STATE_NAME StateName ); +/** + * The NtUpdateWnfStateData routine updates the data associated with a WNF state name. + * + * \param StateName Pointer to the WNF_STATE_NAME to update. + * \param Buffer Pointer to the data buffer to write. + * \param Length Length, in bytes, of the data buffer. + * \param TypeId Optional pointer to a WNF_TYPE_ID structure specifying the type of the state data. + * \param ExplicitScope Optional pointer to a security identifier (SID) for explicit scope. + * \param MatchingChangeStamp The change stamp to match for update. + * \param CheckStamp If TRUE, the change stamp is checked before updating. + * \return NTSTATUS Successful or errant status. + */ NTSYSCALLAPI NTSTATUS NTAPI @@ -1415,42 +1790,79 @@ NtUpdateWnfStateData( _In_reads_bytes_opt_(Length) const VOID* Buffer, _In_opt_ ULONG Length, _In_opt_ PCWNF_TYPE_ID TypeId, - _In_opt_ const VOID* ExplicitScope, + _In_opt_ PCSID ExplicitScope, _In_ WNF_CHANGE_STAMP MatchingChangeStamp, _In_ LOGICAL CheckStamp ); +/** + * The NtDeleteWnfStateData routine deletes the data associated with a WNF state name. + * + * \param StateName Pointer to the WNF_STATE_NAME whose data is to be deleted. + * \param ExplicitScope Optional pointer to a security identifier (SID) for explicit scope. + * \return NTSTATUS Successful or errant status. + */ NTSYSCALLAPI NTSTATUS NTAPI NtDeleteWnfStateData( _In_ PCWNF_STATE_NAME StateName, - _In_opt_ const VOID* ExplicitScope + _In_opt_ PCSID ExplicitScope ); +/** + * The NtQueryWnfStateData routine queries the data associated with a WNF state name. + * + * \param StateName Pointer to the WNF_STATE_NAME to query. + * \param TypeId Optional pointer to a WNF_TYPE_ID structure specifying the type of the state data. + * \param ExplicitScope Optional pointer to a security identifier (SID) for explicit scope. + * \param ChangeStamp Pointer to a variable that receives the change stamp. + * \param Buffer Pointer to a buffer that receives the state data. + * \param BufferLength On input, the size of the buffer in bytes; on output, the number of bytes written. + * \return NTSTATUS Successful or errant status. + */ NTSYSCALLAPI NTSTATUS NTAPI NtQueryWnfStateData( _In_ PCWNF_STATE_NAME StateName, _In_opt_ PCWNF_TYPE_ID TypeId, - _In_opt_ const VOID* ExplicitScope, + _In_opt_ PCSID ExplicitScope, _Out_ PWNF_CHANGE_STAMP ChangeStamp, - _Out_writes_bytes_opt_(*BufferSize) PVOID Buffer, - _Inout_ PULONG BufferSize + _Out_writes_bytes_opt_(*BufferLength) PVOID Buffer, + _Inout_ PULONG BufferLength ); +/** + * The NtQueryWnfStateNameInformation routine queries information about a WNF state name. + * + * \param StateName Pointer to the WNF_STATE_NAME to query. + * \param NameInfoClass The information class to query (see WNF_STATE_NAME_INFORMATION). + * \param ExplicitScope Optional pointer to a security identifier (SID) for explicit scope. + * \param Buffer Pointer to a buffer that receives the requested information. + * \param BufferLength The size, in bytes, of the buffer. + * \return NTSTATUS Successful or errant status. + */ 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 + _In_opt_ PCSID ExplicitScope, + _Out_writes_bytes_(BufferLength) PVOID Buffer, + _In_ ULONG BufferLength ); +/** + * The NtSubscribeWnfStateChange routine subscribes to state change notifications for a WNF state name. + * + * \param StateName Pointer to the WNF_STATE_NAME to subscribe to. + * \param ChangeStamp Optional change stamp to start receiving notifications from. + * \param EventMask Bitmask specifying which events to subscribe to. + * \param SubscriptionId Optional pointer to a variable that receives the subscription ID. + * \return NTSTATUS Successful or errant status. + */ NTSYSCALLAPI NTSTATUS NTAPI @@ -1461,6 +1873,12 @@ NtSubscribeWnfStateChange( _Out_opt_ PULONG64 SubscriptionId ); +/** + * The NtUnsubscribeWnfStateChange routine unsubscribes from state change notifications for a WNF state name. + * + * \param StateName Pointer to the WNF_STATE_NAME to unsubscribe from. + * \return NTSTATUS Successful or errant status. + */ NTSYSCALLAPI NTSTATUS NTAPI @@ -1472,6 +1890,17 @@ NtUnsubscribeWnfStateChange( #if (PHNT_VERSION >= PHNT_WINDOWS_10) +/** + * The NtGetCompleteWnfStateSubscription routine retrieves the complete WNF state subscription information. + * + * \param OldDescriptorStateName Optional pointer to the previous state name. + * \param OldSubscriptionId Optional pointer to the previous subscription ID. + * \param OldDescriptorEventMask Optional previous event mask. + * \param OldDescriptorStatus Optional previous descriptor status. + * \param NewDeliveryDescriptor Pointer to a buffer that receives the new delivery descriptor. + * \param DescriptorSize The size, in bytes, of the delivery descriptor buffer. + * \return NTSTATUS code indicating success or failure. + */ NTSYSCALLAPI NTSTATUS NTAPI @@ -1484,6 +1913,12 @@ NtGetCompleteWnfStateSubscription( _In_ ULONG DescriptorSize ); +/** + * The NtSetWnfProcessNotificationEvent routine sets a process notification event for WNF state changes. + * + * \param NotificationEvent Handle to the event object to be signaled on state change. + * \return NTSTATUS code indicating success or failure. + */ NTSYSCALLAPI NTSTATUS NTAPI @@ -1571,8 +2006,6 @@ typedef struct _WORKER_FACTORY_BASIC_INFORMATION // end_private -#if (PHNT_VERSION >= PHNT_WINDOWS_VISTA) - NTSYSCALLAPI NTSTATUS NTAPI @@ -1650,7 +2083,7 @@ NtWaitForWorkViaWorkerFactory( _Out_writes_to_(Count, *PacketsReturned) PFILE_IO_COMPLETION_INFORMATION MiniPackets, _In_ ULONG Count, _Out_ PULONG PacketsReturned, - _In_ PWORKER_FACTORY_DEFERRED_WORK DeferredWork + _In_ PVOID DeferredWork // PWORKER_FACTORY_DEFERRED_WORK ); #else @@ -1665,8 +2098,6 @@ NtWaitForWorkViaWorkerFactory( #endif // (PHNT_VERSION >= PHNT_WINDOWS_8) -#endif // (PHNT_VERSION >= PHNT_WINDOWS_VISTA) - // // Time // @@ -1674,9 +2105,9 @@ NtWaitForWorkViaWorkerFactory( /** * The NtQuerySystemTime routine obtains the current system time. * - * @param SystemTime A pointer to a LARGE_INTEGER structure that receives the system time. This is a 64-bit value representing the number of 100-nanosecond intervals since January 1, 1601 (UTC). - * @return NTSTATUS Successful or errant status. - * @see https://learn.microsoft.com/en-us/windows/win32/api/winternl/nf-winternl-ntquerysystemtime + * \param SystemTime A pointer to a LARGE_INTEGER structure that receives the system time. This is a 64-bit value representing the number of 100-nanosecond intervals since January 1, 1601 (UTC). + * \return NTSTATUS Successful or errant status. + * \see https://learn.microsoft.com/en-us/windows/win32/api/winternl/nf-winternl-ntquerysystemtime */ NTSYSCALLAPI NTSTATUS @@ -1688,11 +2119,11 @@ NtQuerySystemTime( /** * The NtSetSystemTime routine sets the current system time and date. The system time is expressed in Coordinated Universal Time (UTC). * - * @param SystemTime A pointer to a LARGE_INTEGER structure that that contains the new system date and time. - * @param PreviousTime A pointer to a LARGE_INTEGER structure that that contains the previous system time. - * @return NTSTATUS Successful or errant status. - * @remarks The calling process must have the SE_SYSTEMTIME_NAME privilege. - * @see https://learn.microsoft.com/en-us/windows/win32/api/sysinfoapi/nf-sysinfoapi-setsystemtime + * \param SystemTime A pointer to a LARGE_INTEGER structure that that contains the new system date and time. + * \param PreviousTime A pointer to a LARGE_INTEGER structure that that contains the previous system time. + * \return NTSTATUS Successful or errant status. + * \remarks The calling process must have the SE_SYSTEMTIME_NAME privilege. + * \see https://learn.microsoft.com/en-us/windows/win32/api/sysinfoapi/nf-sysinfoapi-setsystemtime */ NTSYSCALLAPI NTSTATUS @@ -1705,10 +2136,10 @@ NtSetSystemTime( /** * The NtQueryTimerResolution routine retrieves the range and current value of the system interrupt timer. * - * @param MaximumTime The maximum timer resolution, in 100-nanosecond units. - * @param MinimumTime The minimum timer resolution, in 100-nanosecond units. - * @param CurrentTime The current timer resolution, in 100-nanosecond units. - * @return NTSTATUS Successful or errant status. + * \param MaximumTime The maximum timer resolution, in 100-nanosecond units. + * \param MinimumTime The minimum timer resolution, in 100-nanosecond units. + * \param CurrentTime The current timer resolution, in 100-nanosecond units. + * \return NTSTATUS Successful or errant status. */ NTSYSCALLAPI NTSTATUS @@ -1722,10 +2153,10 @@ NtQueryTimerResolution( /** * The NtSetTimerResolution routine sets the system interrupt timer resolution to the specified value. * - * @param DesiredTime The desired timer resolution, in 100-nanosecond units. - * @param SetResolution If TRUE, the timer resolution is set to the value specified by DesiredTime. If FALSE, the timer resolution is reset to the default value. - * @param ActualTime The actual timer resolution, in 100-nanosecond units. - * @return NTSTATUS Successful or errant status. + * \param DesiredTime The desired timer resolution, in 100-nanosecond units. + * \param SetResolution If TRUE, the timer resolution is set to the value specified by DesiredTime. If FALSE, the timer resolution is reset to the default value. + * \param ActualTime The actual timer resolution, in 100-nanosecond units. + * \return NTSTATUS Successful or errant status. */ NTSYSCALLAPI NTSTATUS @@ -1740,6 +2171,16 @@ NtSetTimerResolution( // Performance Counters // +/** + * The NtQueryPerformanceCounter routine retrieves the current value of the performance counter, + * which is a high resolution (<1us) time stamp that can be used for time-interval measurements. + * + * \param PerformanceCounter A pointer to a variable that receives the current performance-counter value, in 100-nanosecond units. + * \param PerformanceFrequency A pointer to a variable that receives the current performance-frequency value, in 100-nanosecond units. + * \return NTSTATUS Successful or errant status. + * \remarks On systems that run Windows XP or later, the function will always succeed and will thus never return zero. Use RtlQueryPerformanceCounter instead since no system calls are required. + * \sa https://learn.microsoft.com/en-us/windows/win32/api/profileapi/nf-profileapi-queryperformancecounter + */ NTSYSCALLAPI NTSTATUS NTAPI @@ -1753,9 +2194,9 @@ NtQueryPerformanceCounter( /** * The NtQueryAuxiliaryCounterFrequency routine queries the auxiliary counter frequency. (The auxiliary counter is generally the HPET hardware timer). * - * @param AuxiliaryCounterFrequency A pointer to an output buffer that contains the specified auxiliary counter frequency. If the auxiliary counter is not supported, the value in the output buffer will be undefined. - * @return NTSTATUS Successful or errant status. - * @see https://learn.microsoft.com/en-us/windows/win32/api/realtimeapiset/nf-realtimeapiset-queryauxiliarycounterfrequency + * \param AuxiliaryCounterFrequency A pointer to an output buffer that contains the specified auxiliary counter frequency. If the auxiliary counter is not supported, the value in the output buffer will be undefined. + * \return NTSTATUS Successful or errant status. + * \see https://learn.microsoft.com/en-us/windows/win32/api/realtimeapiset/nf-realtimeapiset-queryauxiliarycounterfrequency */ NTSYSCALLAPI NTSTATUS @@ -1769,12 +2210,12 @@ NtQueryAuxiliaryCounterFrequency( * The NtConvertBetweenAuxiliaryCounterAndPerformanceCounter routine converts the specified performance counter value to the corresponding auxiliary counter value; * optionally provides the estimated conversion error in nanoseconds due to latencies and maximum possible drift. * - * @param ConvertAuxiliaryToPerformanceCounter If TRUE, the value will be converted from AUX to QPC. If FALSE, the value will be converted from QPC to AUX. - * @param PerformanceOrAuxiliaryCounterValue The performance counter value to convert. - * @param ConvertedValue On success, contains the converted auxiliary counter value. Will be undefined if the function fails. - * @param ConversionError On success, contains the estimated conversion error, in nanoseconds. Will be undefined if the function fails. - * @return NTSTATUS Successful or errant status. - * @see https://learn.microsoft.com/en-us/windows/win32/api/realtimeapiset/nf-realtimeapiset-convertperformancecountertoauxiliarycounter + * \param ConvertAuxiliaryToPerformanceCounter If TRUE, the value will be converted from AUX to QPC. If FALSE, the value will be converted from QPC to AUX. + * \param PerformanceOrAuxiliaryCounterValue The performance counter value to convert. + * \param ConvertedValue On success, contains the converted auxiliary counter value. Will be undefined if the function fails. + * \param ConversionError On success, contains the estimated conversion error, in nanoseconds. Will be undefined if the function fails. + * \return NTSTATUS Successful or errant status. + * \see https://learn.microsoft.com/en-us/windows/win32/api/realtimeapiset/nf-realtimeapiset-convertperformancecountertoauxiliarycounter */ NTSYSCALLAPI NTSTATUS @@ -1829,298 +2270,322 @@ NtAllocateUuids( // 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 - SystemPrioritySeparation, // s (requires SeTcbPrivilege) - SystemVerifierAddDriverInformation, // s: UNICODE_STRING (requires SeDebugPrivilege) // 40 - SystemVerifierRemoveDriverInformation, // s: UNICODE_STRING (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_EXTENDED_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 // NtQuerySystemInformationEx // (kernel-mode only) - SystemLogicalProcessorInformation, // q: SYSTEM_LOGICAL_PROCESSOR_INFORMATION (EX in: USHORT ProcessorGroup) // NtQuerySystemInformationEx - SystemWow64SharedInformationObsolete, // not implemented - SystemRegisterFirmwareTableInformationHandler, // s: SYSTEM_FIRMWARE_TABLE_HANDLER // (kernel-mode only) - SystemFirmwareTableInformation, // SYSTEM_FIRMWARE_TABLE_INFORMATION - SystemModuleInformationEx, // q: RTL_PROCESS_MODULE_INFORMATION_EX // since VISTA - 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) // NtQuerySystemInformationEx - SystemProcessorIdleCycleTimeInformation, // q: SYSTEM_PROCESSOR_IDLE_CYCLE_TIME_INFORMATION[] (EX in: USHORT ProcessorGroup) // NtQuerySystemInformationEx - 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) // NtQuerySystemInformationEx // 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 // NtQuerySystemInformationEx // KeQueryLogicalProcessorRelationship - SystemProcessorCycleTimeInformation, // q: SYSTEM_PROCESSOR_CYCLE_TIME_INFORMATION[] (EX in: USHORT ProcessorGroup) // NtQuerySystemInformationEx - 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: BOOT_ENTROPY_NT_RESULT // ExQueryBootEntropyInformation - 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) // NtQuerySystemInformationEx - 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, // SYSTEM_BAD_PAGE_INFORMATION - 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) // NtQuerySystemInformationEx // since WINBLUE - SystemCriticalProcessErrorLogInformation, // CRITICAL_PROCESS_EXCEPTION_DATA - SystemSecureBootPolicyInformation, // q: SYSTEM_SECUREBOOT_POLICY_INFORMATION - SystemPageFileInformationEx, // q: SYSTEM_PAGEFILE_INFORMATION_EX - SystemSecureBootInformation, // q: SYSTEM_SECUREBOOT_INFORMATION - SystemEntropyInterruptTimingRawInformation, // q; s: SYSTEM_ENTROPY_TIMING_INFORMATION - SystemPortableWorkspaceEfiLauncherInformation, // q: SYSTEM_PORTABLE_WORKSPACE_EFI_LAUNCHER_INFORMATION - SystemFullProcessInformation, // q: SYSTEM_EXTENDED_PROCESS_INFORMATION with SYSTEM_PROCESS_INFORMATION_EXTENSION (requires admin) - SystemKernelDebuggerInformationEx, // q: SYSTEM_KERNEL_DEBUGGER_INFORMATION_EX - SystemBootMetadataInformation, // 150 // (requires SeTcbPrivilege) - 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) // NtQuerySystemInformationEx // 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, // q: KAFFINITY_EX // (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 // NtQuerySystemInformationEx // 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, // NtQuerySystemInformationEx - SystemCodeIntegrityUnlockInformation, // SYSTEM_CODEINTEGRITY_UNLOCK_INFORMATION // 190 - SystemIntegrityQuotaInformation, - SystemFlushInformation, // q: SYSTEM_FLUSH_INFORMATION - SystemProcessorIdleMaskInformation, // q: ULONG_PTR[ActiveGroupCount] // since REDSTONE3 - SystemSecureDumpEncryptionInformation, // NtQuerySystemInformationEx - 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, // NtQuerySystemInformationEx - SystemFeatureConfigurationInformation, // q: in: SYSTEM_FEATURE_CONFIGURATION_QUERY, out: SYSTEM_FEATURE_CONFIGURATION_INFORMATION; s: SYSTEM_FEATURE_CONFIGURATION_UPDATE // NtQuerySystemInformationEx // since 20H1 // 210 - SystemFeatureConfigurationSectionInformation, // q: in: SYSTEM_FEATURE_CONFIGURATION_SECTIONS_REQUEST, out: SYSTEM_FEATURE_CONFIGURATION_SECTIONS_INFORMATION // NtQuerySystemInformationEx - SystemFeatureUsageSubscriptionInformation, // q: SYSTEM_FEATURE_USAGE_SUBSCRIPTION_DETAILS; s: SYSTEM_FEATURE_USAGE_SUBSCRIPTION_UPDATE - 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) // NtQuerySystemInformationEx - 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) // NtQuerySystemInformationEx - 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, // NtQuerySystemInformationEx - SystemOriginalImageFeatureInformation, // q: in: SYSTEM_ORIGINAL_IMAGE_FEATURE_INFORMATION_INPUT, out: SYSTEM_ORIGINAL_IMAGE_FEATURE_INFORMATION_OUTPUT // NtQuerySystemInformationEx - SystemMemoryNumaInformation, // SYSTEM_MEMORY_NUMA_INFORMATION_INPUT, SYSTEM_MEMORY_NUMA_INFORMATION_OUTPUT // NtQuerySystemInformationEx - SystemMemoryNumaPerformanceInformation, // SYSTEM_MEMORY_NUMA_PERFORMANCE_INFORMATION_INPUTSYSTEM_MEMORY_NUMA_PERFORMANCE_INFORMATION_INPUT, SYSTEM_MEMORY_NUMA_PERFORMANCE_INFORMATION_OUTPUT // since 24H2 // 240 - SystemCodeIntegritySignedPoliciesFullInformation, - SystemSecureCoreInformation, // SystemSecureSecretsInformation - SystemTrustedAppsRuntimeInformation, // SYSTEM_TRUSTEDAPPS_RUNTIME_INFORMATION - SystemBadPageInformationEx, // SYSTEM_BAD_PAGE_INFORMATION - SystemResourceDeadlockTimeout, // ULONG - SystemBreakOnContextUnwindFailureInformation, // ULONG (requires SeDebugPrivilege) - SystemOslRamdiskInformation, // SYSTEM_OSL_RAMDISK_INFORMATION - SystemCodeIntegrityPolicyManagementInformation, // since 25H2 - SystemMemoryNumaCacheInformation, - SystemProcessorFeaturesBitMapInformation, + SystemBasicInformation, // q: SYSTEM_BASIC_INFORMATION + SystemProcessorInformation, // q: SYSTEM_PROCESSOR_INFORMATION + SystemPerformanceInformation, // q: SYSTEM_PERFORMANCE_INFORMATION + SystemTimeOfDayInformation, // q: SYSTEM_TIMEOFDAY_INFORMATION + SystemPathInformation, // q: 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, // qs: SYSTEM_FLAGS_INFORMATION + SystemCallTimeInformation, // q: SYSTEM_CALL_TIME_INFORMATION // not implemented // 10 + SystemModuleInformation, // q: RTL_PROCESS_MODULES + SystemLocksInformation, // q: RTL_PROCESS_LOCKS + SystemStackTraceInformation, // q: RTL_PROCESS_BACKTRACES + SystemPagedPoolInformation, // q: not implemented + SystemNonPagedPoolInformation, // q: 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, // q: not implemented // 20 + SystemFileCacheInformation, // qs: SYSTEM_FILECACHE_INFORMATION; s (requires SeIncreaseQuotaPrivilege) (info for WorkingSetTypeSystemCache) + SystemPoolTagInformation, // q: SYSTEM_POOLTAG_INFORMATION + SystemInterruptInformation, // q: SYSTEM_INTERRUPT_INFORMATION (EX in: USHORT ProcessorGroup) + SystemDpcBehaviorInformation, // qs: SYSTEM_DPC_BEHAVIOR_INFORMATION; s: SYSTEM_DPC_BEHAVIOR_INFORMATION (requires SeLoadDriverPrivilege) + SystemFullMemoryInformation, // q: SYSTEM_MEMORY_USAGE_INFORMATION // not implemented + SystemLoadGdiDriverInformation, // s: (kernel-mode only) + SystemUnloadGdiDriverInformation, // s: (kernel-mode only) + SystemTimeAdjustmentInformation, // qs: SYSTEM_QUERY_TIME_ADJUST_INFORMATION; s: SYSTEM_SET_TIME_ADJUST_INFORMATION (requires SeSystemtimePrivilege) + SystemSummaryMemoryInformation, // q: SYSTEM_MEMORY_USAGE_INFORMATION // not implemented + SystemMirrorMemoryInformation, // qs: (requires license value "Kernel-MemoryMirroringSupported") (requires SeShutdownPrivilege) // 30 + SystemPerformanceTraceInformation, // qs: (type depends on EVENT_TRACE_INFORMATION_CLASS) + SystemObsolete0, // q: 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, // qs: SYSTEM_REGISTRY_QUOTA_INFORMATION; s (requires SeIncreaseQuotaPrivilege) + SystemExtendServiceTableInformation, // s: (requires SeLoadDriverPrivilege) // loads win32k only + SystemPrioritySeparation, // s: (requires SeTcbPrivilege) + SystemVerifierAddDriverInformation, // s: UNICODE_STRING (requires SeDebugPrivilege) // 40 + SystemVerifierRemoveDriverInformation, // s: UNICODE_STRING (requires SeDebugPrivilege) + SystemProcessorIdleInformation, // q: SYSTEM_PROCESSOR_IDLE_INFORMATION (EX in: USHORT ProcessorGroup) + SystemLegacyDriverInformation, // q: SYSTEM_LEGACY_DRIVER_INFORMATION + SystemCurrentTimeZoneInformation, // qs: RTL_TIME_ZONE_INFORMATION + SystemLookasideInformation, // q: SYSTEM_LOOKASIDE_INFORMATION + SystemTimeSlipNotification, // s: HANDLE (NtCreateEvent) (requires SeSystemtimePrivilege) + SystemSessionCreate, // q: not implemented + SystemSessionDetach, // q: not implemented + SystemSessionInformation, // q: not implemented (SYSTEM_SESSION_INFORMATION) + SystemRangeStartInformation, // q: SYSTEM_RANGE_START_INFORMATION // 50 + SystemVerifierInformation, // qs: SYSTEM_VERIFIER_INFORMATION; s (requires SeDebugPrivilege) + SystemVerifierThunkExtend, // qs: (kernel-mode only) + SystemSessionProcessInformation, // q: SYSTEM_SESSION_PROCESS_INFORMATION + SystemLoadGdiDriverInSystemSpace, // qs: SYSTEM_GDI_DRIVER_INFORMATION (kernel-mode only) (same as SystemLoadGdiDriverInformation) + SystemNumaProcessorMap, // q: SYSTEM_NUMA_INFORMATION + SystemPrefetcherInformation, // qs: PREFETCHER_INFORMATION // PfSnQueryPrefetcherInformation + SystemExtendedProcessInformation, // q: SYSTEM_EXTENDED_PROCESS_INFORMATION + SystemRecommendedSharedDataAlignment, // q: ULONG // KeGetRecommendedSharedDataAlignment + SystemComPlusPackage, // qs: 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, // qs: SYSTEM_HOTPATCH_CODE_INFORMATION + SystemObjectSecurityMode, // q: ULONG // 70 + SystemWatchdogTimerHandler, // s: SYSTEM_WATCHDOG_HANDLER_INFORMATION // (kernel-mode only) + SystemWatchdogTimerInformation, // qs: out: SYSTEM_WATCHDOG_TIMER_INFORMATION (EX in: ULONG WATCHDOG_INFORMATION_CLASS) // NtQuerySystemInformationEx + SystemLogicalProcessorInformation, // q: SYSTEM_LOGICAL_PROCESSOR_INFORMATION (EX in: USHORT ProcessorGroup) // NtQuerySystemInformationEx + SystemWow64SharedInformationObsolete, // q: not implemented + SystemRegisterFirmwareTableInformationHandler, // s: SYSTEM_FIRMWARE_TABLE_HANDLER // (kernel-mode only) + SystemFirmwareTableInformation, // q: SYSTEM_FIRMWARE_TABLE_INFORMATION + SystemModuleInformationEx, // q: RTL_PROCESS_MODULE_INFORMATION_EX // since VISTA + SystemVerifierTriageInformation, // q: not implemented + SystemSuperfetchInformation, // qs: 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) // NtQuerySystemInformationEx + SystemProcessorIdleCycleTimeInformation, // q: SYSTEM_PROCESSOR_IDLE_CYCLE_TIME_INFORMATION[] (EX in: USHORT ProcessorGroup) // NtQuerySystemInformationEx + SystemVerifierCancellationInformation, // q: SYSTEM_VERIFIER_CANCELLATION_INFORMATION // name:wow64:whNT32QuerySystemVerifierCancellationInformation + SystemProcessorPowerInformationEx, // q: not implemented + SystemRefTraceInformation, // qs: SYSTEM_REF_TRACE_INFORMATION // ObQueryRefTraceInformation + SystemSpecialPoolInformation, // qs: SYSTEM_SPECIAL_POOL_INFORMATION (requires SeDebugPrivilege) // MmSpecialPoolTag, then MmSpecialPoolCatchOverruns != 0 + SystemProcessIdInformation, // q: SYSTEM_PROCESS_ID_INFORMATION + SystemErrorPortInformation, // s: HANDLE (requires SeTcbPrivilege) + SystemBootEnvironmentInformation, // q: SYSTEM_BOOT_ENVIRONMENT_INFORMATION // 90 + SystemHypervisorInformation, // q: SYSTEM_HYPERVISOR_QUERY_INFORMATION + SystemVerifierInformationEx, // qs: SYSTEM_VERIFIER_INFORMATION_EX + SystemTimeZoneInformation, // qs: 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, // q: 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) // NtQuerySystemInformationEx // 100 + SystemNumaProximityNodeInformation, // qs: SYSTEM_NUMA_PROXIMITY_MAP + SystemDynamicTimeZoneInformation, // qs: RTL_DYNAMIC_TIME_ZONE_INFORMATION (requires SeTimeZonePrivilege) + SystemCodeIntegrityInformation, // q: SYSTEM_CODEINTEGRITY_INFORMATION // SeCodeIntegrityQueryInformation + SystemProcessorMicrocodeUpdateInformation, // s: SYSTEM_PROCESSOR_MICROCODE_UPDATE_INFORMATION (requires SeLoadDriverPrivilege) + 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 // NtQuerySystemInformationEx // KeQueryLogicalProcessorRelationship + SystemProcessorCycleTimeInformation, // q: SYSTEM_PROCESSOR_CYCLE_TIME_INFORMATION[] (EX in: USHORT ProcessorGroup) // NtQuerySystemInformationEx + SystemStoreInformation, // qs: 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, // qs: PS_CPU_QUOTA_QUERY_INFORMATION + SystemNativeBasicInformation, // q: SYSTEM_BASIC_INFORMATION + SystemErrorPortTimeouts, // q: SYSTEM_ERROR_PORT_TIMEOUTS + SystemLowPriorityIoInformation, // q: SYSTEM_LOW_PRIORITY_IO_INFORMATION + SystemTpmBootEntropyInformation, // q: BOOT_ENTROPY_NT_RESULT // ExQueryBootEntropyInformation + 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) // NtQuerySystemInformationEx + 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, // qs: SYSTEM_BOOT_GRAPHICS_INFORMATION (kernel-mode only) + SystemScrubPhysicalMemoryInformation, // qs: MEMORY_SCRUB_INFORMATION + SystemBadPageInformation, // q: SYSTEM_BAD_PAGE_INFORMATION + SystemProcessorProfileControlArea, // qs: SYSTEM_PROCESSOR_PROFILE_CONTROL_AREA + SystemCombinePhysicalMemoryInformation, // s: MEMORY_COMBINE_INFORMATION, MEMORY_COMBINE_INFORMATION_EX, MEMORY_COMBINE_INFORMATION_EX2 // 130 + SystemEntropyInterruptTimingInformation, // qs: SYSTEM_ENTROPY_TIMING_INFORMATION + SystemConsoleInformation, // qs: SYSTEM_CONSOLE_INFORMATION // (requires SeLoadDriverPrivilege) + 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) // NtQuerySystemInformationEx // since WINBLUE + SystemCriticalProcessErrorLogInformation, // q: CRITICAL_PROCESS_EXCEPTION_DATA + SystemSecureBootPolicyInformation, // q: SYSTEM_SECUREBOOT_POLICY_INFORMATION + SystemPageFileInformationEx, // q: SYSTEM_PAGEFILE_INFORMATION_EX + SystemSecureBootInformation, // q: SYSTEM_SECUREBOOT_INFORMATION + SystemEntropyInterruptTimingRawInformation, // qs: SYSTEM_ENTROPY_TIMING_INFORMATION + SystemPortableWorkspaceEfiLauncherInformation, // q: SYSTEM_PORTABLE_WORKSPACE_EFI_LAUNCHER_INFORMATION + SystemFullProcessInformation, // q: SYSTEM_EXTENDED_PROCESS_INFORMATION with SYSTEM_PROCESS_INFORMATION_EXTENSION (requires admin) + SystemKernelDebuggerInformationEx, // q: SYSTEM_KERNEL_DEBUGGER_INFORMATION_EX + SystemBootMetadataInformation, // q: SYSTEM_BOOT_METADATA_INFORMATION // (requires SeTcbPrivilege) // 150 + SystemSoftRebootInformation, // q: SYSTEM_SOFT_REBOOT_INFORMATION + 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) // NtQuerySystemInformationEx // 160 + SystemVmGenerationCountInformation, // s: PHYSICAL_ADDRESS (kernel-mode only) (vmgencounter.sys) + SystemTrustedPlatformModuleInformation, // q: SYSTEM_TPM_INFORMATION + SystemKernelDebuggerFlags, // q: SYSTEM_KERNEL_DEBUGGER_FLAGS + SystemCodeIntegrityPolicyInformation, // qs: SYSTEM_CODEINTEGRITYPOLICY_INFORMATION + SystemIsolatedUserModeInformation, // q: SYSTEM_ISOLATED_USER_MODE_INFORMATION + SystemHardwareSecurityTestInterfaceResultsInformation, // q: SYSTEM_HARDWARE_SECURITY_TEST_INTERFACE_RESULTS_INFORMATION + 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, // q: + SystemAffinitizedInterruptProcessorInformation, // q: KAFFINITY_EX // (requires SeIncreaseBasePriorityPrivilege) + SystemRootSiloInformation, // q: SYSTEM_ROOT_SILO_INFORMATION + SystemCpuSetInformation, // q: SYSTEM_CPU_SET_INFORMATION // since THRESHOLD2 + SystemCpuSetTagInformation, // q: SYSTEM_CPU_SET_TAG_INFORMATION + SystemWin32WerStartCallout, // s: + SystemSecureKernelProfileInformation, // q: SYSTEM_SECURE_KERNEL_HYPERGUARD_PROFILE_INFORMATION + SystemCodeIntegrityPlatformManifestInformation, // q: SYSTEM_SECUREBOOT_PLATFORM_MANIFEST_INFORMATION // NtQuerySystemInformationEx // since REDSTONE + SystemInterruptSteeringInformation, // q: in: SYSTEM_INTERRUPT_STEERING_INFORMATION_INPUT, out: SYSTEM_INTERRUPT_STEERING_INFORMATION_OUTPUT // NtQuerySystemInformationEx + SystemSupportedProcessorArchitectures, // p: in opt: HANDLE, out: SYSTEM_SUPPORTED_PROCESSOR_ARCHITECTURES_INFORMATION[] // NtQuerySystemInformationEx // 180 + SystemMemoryUsageInformation, // q: SYSTEM_MEMORY_USAGE_INFORMATION + SystemCodeIntegrityCertificateInformation, // q: SYSTEM_CODEINTEGRITY_CERTIFICATE_INFORMATION + SystemPhysicalMemoryInformation, // q: SYSTEM_PHYSICAL_MEMORY_INFORMATION // since REDSTONE2 + SystemControlFlowTransition, // qs: (Warbird/Encrypt/Decrypt/Execute) + SystemKernelDebuggingAllowed, // s: ULONG + SystemActivityModerationExeState, // s: SYSTEM_ACTIVITY_MODERATION_EXE_STATE + SystemActivityModerationUserSettings, // q: SYSTEM_ACTIVITY_MODERATION_USER_SETTINGS + SystemCodeIntegrityPoliciesFullInformation, // qs: NtQuerySystemInformationEx + SystemCodeIntegrityUnlockInformation, // q: SYSTEM_CODEINTEGRITY_UNLOCK_INFORMATION // 190 + SystemIntegrityQuotaInformation, // s: SYSTEM_INTEGRITY_QUOTA_INFORMATION (requires SeDebugPrivilege) + SystemFlushInformation, // q: SYSTEM_FLUSH_INFORMATION + SystemProcessorIdleMaskInformation, // q: ULONG_PTR[ActiveGroupCount] // since REDSTONE3 + SystemSecureDumpEncryptionInformation, // qs: NtQuerySystemInformationEx // (q: requires SeDebugPrivilege) (s: requires SeTcbPrivilege) + SystemWriteConstraintInformation, // q: SYSTEM_WRITE_CONSTRAINT_INFORMATION + SystemKernelVaShadowInformation, // q: SYSTEM_KERNEL_VA_SHADOW_INFORMATION + SystemHypervisorSharedPageInformation, // q: SYSTEM_HYPERVISOR_SHARED_PAGE_INFORMATION // since REDSTONE4 + SystemFirmwareBootPerformanceInformation, // q: + SystemCodeIntegrityVerificationInformation, // q: SYSTEM_CODEINTEGRITYVERIFICATION_INFORMATION + SystemFirmwarePartitionInformation, // q: SYSTEM_FIRMWARE_PARTITION_INFORMATION // 200 + SystemSpeculationControlInformation, // q: SYSTEM_SPECULATION_CONTROL_INFORMATION // (CVE-2017-5715) REDSTONE3 and above. + SystemDmaGuardPolicyInformation, // q: SYSTEM_DMA_GUARD_POLICY_INFORMATION + SystemEnclaveLaunchControlInformation, // q: SYSTEM_ENCLAVE_LAUNCH_CONTROL_INFORMATION + SystemWorkloadAllowedCpuSetsInformation, // q: SYSTEM_WORKLOAD_ALLOWED_CPU_SET_INFORMATION // since REDSTONE5 + SystemCodeIntegrityUnlockModeInformation, // q: SYSTEM_CODEINTEGRITY_UNLOCK_INFORMATION + SystemLeapSecondInformation, // qs: SYSTEM_LEAP_SECOND_INFORMATION // (s: requires SeSystemtimePrivilege) + SystemFlags2Information, // q: SYSTEM_FLAGS_INFORMATION // (s: requires SeDebugPrivilege) + SystemSecurityModelInformation, // q: SYSTEM_SECURITY_MODEL_INFORMATION // since 19H1 + SystemCodeIntegritySyntheticCacheInformation, // qs: NtQuerySystemInformationEx + SystemFeatureConfigurationInformation, // q: in: SYSTEM_FEATURE_CONFIGURATION_QUERY, out: SYSTEM_FEATURE_CONFIGURATION_INFORMATION; s: SYSTEM_FEATURE_CONFIGURATION_UPDATE // NtQuerySystemInformationEx // since 20H1 // 210 + SystemFeatureConfigurationSectionInformation, // q: in: SYSTEM_FEATURE_CONFIGURATION_SECTIONS_REQUEST, out: SYSTEM_FEATURE_CONFIGURATION_SECTIONS_INFORMATION // NtQuerySystemInformationEx + SystemFeatureUsageSubscriptionInformation, // q: SYSTEM_FEATURE_USAGE_SUBSCRIPTION_DETAILS; s: SYSTEM_FEATURE_USAGE_SUBSCRIPTION_UPDATE + SystemSecureSpeculationControlInformation, // q: SECURE_SPECULATION_CONTROL_INFORMATION + SystemSpacesBootInformation, // qs: // since 20H2 + SystemFwRamdiskInformation, // q: SYSTEM_FIRMWARE_RAMDISK_INFORMATION + SystemWheaIpmiHardwareInformation, // q: SYSTEM_WHEA_IPMI_HARDWARE_INFORMATION + SystemDifSetRuleClassInformation, // s: SYSTEM_DIF_VOLATILE_INFORMATION (requires SeDebugPrivilege) + SystemDifClearRuleClassInformation, // s: NULL (requires SeDebugPrivilege) + SystemDifApplyPluginVerificationOnDriver, // q: SYSTEM_DIF_PLUGIN_DRIVER_INFORMATION (requires SeDebugPrivilege) + SystemDifRemovePluginVerificationOnDriver, // q: SYSTEM_DIF_PLUGIN_DRIVER_INFORMATION (requires SeDebugPrivilege) // 220 + SystemShadowStackInformation, // q: SYSTEM_SHADOW_STACK_INFORMATION + SystemBuildVersionInformation, // q: in: ULONG (LayerNumber), out: SYSTEM_BUILD_VERSION_INFORMATION // NtQuerySystemInformationEx + SystemPoolLimitInformation, // q: SYSTEM_POOL_LIMIT_INFORMATION (requires SeIncreaseQuotaPrivilege) // NtQuerySystemInformationEx + SystemCodeIntegrityAddDynamicStore, // q: CodeIntegrity-AllowConfigurablePolicy-CustomKernelSigners + SystemCodeIntegrityClearDynamicStores, // q: CodeIntegrity-AllowConfigurablePolicy-CustomKernelSigners + SystemDifPoolTrackingInformation, // s: SYSTEM_DIF_POOL_TRACKING_INFORMATION (requires SeDebugPrivilege) + SystemPoolZeroingInformation, // q: SYSTEM_POOL_ZEROING_INFORMATION + SystemDpcWatchdogInformation, // qs: SYSTEM_DPC_WATCHDOG_CONFIGURATION_INFORMATION + SystemDpcWatchdogInformation2, // qs: 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) // NtQuerySystemInformationEx + SystemXfgCheckFailureInformation, // q: SYSTEM_XFG_FAILURE_INFORMATION + SystemIommuStateInformation, // q: SYSTEM_IOMMU_STATE_INFORMATION // since 22H1 + SystemHypervisorMinrootInformation, // q: SYSTEM_HYPERVISOR_MINROOT_INFORMATION + SystemHypervisorBootPagesInformation, // q: SYSTEM_HYPERVISOR_BOOT_PAGES_INFORMATION + SystemPointerAuthInformation, // q: SYSTEM_POINTER_AUTH_INFORMATION + SystemSecureKernelDebuggerInformation, // qs: NtQuerySystemInformationEx + SystemOriginalImageFeatureInformation, // q: in: SYSTEM_ORIGINAL_IMAGE_FEATURE_INFORMATION_INPUT, out: SYSTEM_ORIGINAL_IMAGE_FEATURE_INFORMATION_OUTPUT // NtQuerySystemInformationEx + SystemMemoryNumaInformation, // q: SYSTEM_MEMORY_NUMA_INFORMATION_INPUT, SYSTEM_MEMORY_NUMA_INFORMATION_OUTPUT // NtQuerySystemInformationEx + SystemMemoryNumaPerformanceInformation, // q: SYSTEM_MEMORY_NUMA_PERFORMANCE_INFORMATION_INPUT, SYSTEM_MEMORY_NUMA_PERFORMANCE_INFORMATION_OUTPUT // since 24H2 // 240 + SystemCodeIntegritySignedPoliciesFullInformation, // qs: NtQuerySystemInformationEx + SystemSecureCoreInformation, // qs: SystemSecureSecretsInformation + SystemTrustedAppsRuntimeInformation, // q: SYSTEM_TRUSTEDAPPS_RUNTIME_INFORMATION + SystemBadPageInformationEx, // q: SYSTEM_BAD_PAGE_INFORMATION + SystemResourceDeadlockTimeout, // q: ULONG + SystemBreakOnContextUnwindFailureInformation, // q: ULONG (requires SeDebugPrivilege) + SystemOslRamdiskInformation, // q: SYSTEM_OSL_RAMDISK_INFORMATION + SystemCodeIntegrityPolicyManagementInformation, // q: SYSTEM_CODEINTEGRITYPOLICY_MANAGEMENT // since 25H2 + SystemMemoryNumaCacheInformation, // q: SYSTEM_MEMORY_NUMA_CACHE_INFORMATION + SystemProcessorFeaturesBitMapInformation, // q: ULONG64[2] // RTL_BITMAP_EX // RtlInitializeBitMapEx // 250 + SystemRefTraceInformationEx, // q: SYSTEM_REF_TRACE_INFORMATION_EX + SystemBasicProcessInformation, // q: SYSTEM_BASICPROCESS_INFORMATION + SystemHandleCountInformation, // q: SYSTEM_HANDLECOUNT_INFORMATION + SystemRuntimeAttestationReport, // q: SYSTEM_RUNTIME_REPORT_INPUT + SystemPoolTagInformation2, // q: SYSTEM_POOLTAG_INFORMATION2 // since 26H1 MaxSystemInfoClass } SYSTEM_INFORMATION_CLASS; +/** + * The SYSTEM_BASIC_INFORMATION structure contains basic information about the current system. + */ 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; + ULONG Reserved; // Reserved + ULONG TimerResolution; // The resolution of the timer, in milliseconds. // NtQueryTimerResolution + ULONG PageSize; // The page size and the granularity of page protection and commitment. + ULONG NumberOfPhysicalPages; // The number of physical pages in the system. // KUSER_SHARED_DATA->NumberOfPhysicalPages + ULONG LowestPhysicalPageNumber; // The lowest memory page accessible to applications and dynamic-link libraries (DLLs). + ULONG HighestPhysicalPageNumber; // The highest memory page accessible to applications and dynamic-link libraries (DLLs). + ULONG AllocationGranularity; // The granularity for the starting address at which virtual memory can be allocated. + ULONG_PTR MinimumUserModeAddress; // A pointer to the lowest memory address accessible to applications and dynamic-link libraries (DLLs). + ULONG_PTR MaximumUserModeAddress; // A pointer to the highest memory address accessible to applications and dynamic-link libraries (DLLs). + KAFFINITY ActiveProcessorsAffinityMask; // A mask representing the set of processors configured in the current processor group. // deprecated + UCHAR NumberOfProcessors; // The number of logical processors in the current processor group. // deprecated } SYSTEM_BASIC_INFORMATION, *PSYSTEM_BASIC_INFORMATION; // SYSTEM_PROCESSOR_INFORMATION // ProcessorFeatureBits (see also SYSTEM_PROCESSOR_FEATURES_INFORMATION) -#define KF_V86_VIS 0x00000001 -#define KF_RDTSC 0x00000002 // Indicates support for the RDTSC instruction. -#define KF_CR4 0x00000004 // Indicates support for the CR4 register. -#define KF_CMOV 0x00000008 -#define KF_GLOBAL_PAGE 0x00000010 // Indicates support for global pages. -#define KF_LARGE_PAGE 0x00000020 // Indicates support for large pages. -#define KF_MTRR 0x00000040 -#define KF_CMPXCHG8B 0x00000080 // Indicates support for the CMPXCHG8B instruction. -#define KF_MMX 0x00000100 -#define KF_WORKING_PTE 0x00000200 -#define KF_PAT 0x00000400 -#define KF_FXSR 0x00000800 -#define KF_FAST_SYSCALL 0x00001000 // Indicates support for fast system calls. -#define KF_XMMI 0x00002000 -#define KF_3DNOW 0x00004000 -#define KF_AMDK6MTRR 0x00008000 -#define KF_XMMI64 0x00010000 -#define KF_DTS 0x00020000 -#define KF_NOEXECUTE 0x20000000 -#define KF_GLOBAL_32BIT_EXECUTE 0x40000000 -#define KF_GLOBAL_32BIT_NOEXECUTE 0x80000000 +#define KF32_V86_VIS 0x00000001 // Virtual 8086 mode. +#define KF32_RDTSC 0x00000002 // RDTSC (Read Time-Stamp Counter) instruction. +#define KF32_CR4 0x00000004 // CR4 (Control Register 4) register. +#define KF32_CMOV 0x00000008 // CMOV (Conditional Move) instruction. +#define KF32_GLOBAL_PAGE 0x00000010 // Global memory pages. +#define KF32_LARGE_PAGE 0x00000020 // Large memory pages. +#define KF32_MTRR 0x00000040 // MTRR (Memory Type Range Registers). +#define KF32_CMPXCHG8B 0x00000080 // CMPXCHG8B (CompareExchange) instruction. +#define KF32_MMX 0x00000100 // MMX (MultiMedia eXtensions). +#define KF32_WORKING_PTE 0x00000200 // PTE (Page Table Entries). +#define KF32_PAT 0x00000400 // PAT (Page Attribute Table). +#define KF32_FXSR 0x00000800 // FXSR (Floating Point Extended Save and Restore). +#define KF32_FAST_SYSCALL 0x00001000 // Fast system calls. +#define KF32_XMMI 0x00002000 // XMMI (Streaming SIMD Extensions - 32-bit). +#define KF32_3DNOW 0x00004000 // AMD 3DNow! technology. +#define KF32_AMDK6MTRR 0x00008000 // AMD K6 MTRR. +#define KF32_XMMI64 0x00010000 // XMMI (Streaming SIMD Extensions - 64-bit). +#define KF32_DTS 0x00020000 // DTS (Digital Thermal Sensor). +#define KF32_TM2 0x00040000 // TM2 (Thermal Monitor 2). +#define KF32_EST 0x00080000 // EST (Enhanced SpeedStep Technology). +#define KF32_IA64 0x00100000 // Intel Itanium architecture. +#define KF32_3DNOW2 0x00200000 // AMD 3DNow! technology, version 2. +#define KF32_VMX 0x00400000 // VMX (Virtual Machine Extensions). +#define KF32_SMX 0x00800000 // SMX (Safer Mode Extensions). +#define KF32_EST2 0x01000000 // EST (Enhanced SpeedStep Technology), version 2. +#define KF32_SSSE3 0x02000000 // SSSE3 (Supplemental Streaming SIMD Extensions 3). +#define KF32_CX16 0x04000000 // CMPXCHG16B instruction. +#define KF32_ETPRD 0x08000000 // ETPRD (Enhanced Time-Stamp Counter Priority Rotation Disable). +#define KF32_PDCM 0x10000000 // PDCM (Performance and Debug Capability MSR). +#define KF32_NOEXECUTE 0x20000000 // No-Execute (NX) bit. +#define KF32_GLOBAL_32BIT_EXECUTE 0x40000000 +#define KF32_GLOBAL_32BIT_NOEXECUTE 0x80000000 +/** + * The SYSTEM_PROCESSOR_INFORMATION structure contains information about the current processor. + * + * \sa https://learn.microsoft.com/en-us/windows/win32/api/sysinfoapi/ns-sysinfoapi-system_info + */ typedef struct _SYSTEM_PROCESSOR_INFORMATION { USHORT ProcessorArchitecture; @@ -2130,101 +2595,107 @@ typedef struct _SYSTEM_PROCESSOR_INFORMATION ULONG ProcessorFeatureBits; } SYSTEM_PROCESSOR_INFORMATION, *PSYSTEM_PROCESSOR_INFORMATION; +/** + * The SYSTEM_PERFORMANCE_INFORMATION structure contains detailed system-wide performance statistics. + */ 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; - LONGLONG ResidentAvailablePages; - ULONGLONG SharedCommittedPages; - ULONGLONG MdlPagesAllocated; // since 24H2 - ULONGLONG PfnDatabaseCommittedPages; - ULONGLONG SystemPageTableCommittedPages; - ULONGLONG ContiguousPagesAllocated; + LARGE_INTEGER IdleProcessTime; // Total time spent by the idle process (in 100ns units). Used to calculate overall CPU idle percentage; combine with per-processor stats for system CPU usage. + LARGE_INTEGER IoReadTransferCount; // Total bytes read by all I/O operations system-wide. Combine with IoWriteTransferCount and IoOtherTransferCount for total I/O throughput. + LARGE_INTEGER IoWriteTransferCount; // Total bytes written by all I/O operations system-wide. Use with IoReadTransferCount for disk throughput analysis. + LARGE_INTEGER IoOtherTransferCount; // Total bytes transferred by non-read/write I/O operations (e.g., device control). Add to above for total I/O. + ULONG IoReadOperationCount; // Number of read I/O operations. Use with IoReadTransferCount to get average read size per operation. + ULONG IoWriteOperationCount; // Number of write I/O operations. Use with IoWriteTransferCount for average write size per operation. + ULONG IoOtherOperationCount; // Number of non-read/write I/O operations. Combine with above for total I/O operation count. */ + ULONG AvailablePages; // Number of free physical memory pages available for immediate allocation to processes. (Display: Value * PageSize for bytes). Indicates instantly available RAM. + ULONG CommittedPages; // Number of committed virtual memory pages (backed by RAM or pagefile). Use with CommitLimit to assess memory pressure and overcommit risk. + ULONG CommitLimit; // Maximum number of pages that can be committed (RAM + pagefile). Compare with CommittedPages to determine available commit space. + ULONG PeakCommitment; // Highest number of committed pages since boot. Tracks historical maximum memory commitment. + ULONG PageFaultCount; // Total number of page faults (both soft and hard) since boot. Includes all types of faults. + ULONG CopyOnWriteCount; // Number of page faults due to copy-on-write events. Subset of PageFaultCount. Indicates process memory sharing and forking activity. + ULONG TransitionCount; // Number of page faults due to transition from standby to active. Subset of PageFaultCount. Indicates memory reactivation from standby lists. + ULONG CacheTransitionCount; // Number of page faults due to cache transitions. Subset of TransitionCount. Indicates faults resolved from the system cache. + ULONG DemandZeroCount; // Number of page faults resolved by zeroing a page (demand-zero). Subset of PageFaultCount. Indicates new memory allocations. + ULONG PageReadCount; // Number of pages read from disk to resolve faults. Use with PageReadIoCount for read efficiency (pages per I/O). + ULONG PageReadIoCount; // Number of I/O operations for page reads. Compare with PageReadCount for average pages per I/O. + ULONG CacheReadCount; // Number of pages read from the system cache. Use with CacheIoCount for cache hit/miss analysis. + ULONG CacheIoCount; // Number of I/O operations for cache reads. Compare with CacheReadCount for average pages per cache I/O. + ULONG DirtyPagesWriteCount; // Number of dirty pages written to disk (writeback). Use with DirtyWriteIoCount for write efficiency. + ULONG DirtyWriteIoCount; // Number of I/O operations for dirty page writes. Compare with DirtyPagesWriteCount for average pages per write I/O. + ULONG MappedPagesWriteCount; // Number of mapped pages written (e.g., memory-mapped files). Use with MappedWriteIoCount for mapped file activity. + ULONG MappedWriteIoCount; // Number of I/O operations for mapped page writes. Compare with MappedPagesWriteCount for average mapped write size. + ULONG PagedPoolPages; // Number of pages used by the paged pool (kernel memory that can be paged out). Combine with NonPagedPoolPages for total pool usage. + ULONG NonPagedPoolPages; // Number of pages used by the nonpaged pool (kernel memory that must remain resident). Combine with PagedPoolPages for total pool usage. + ULONG PagedPoolAllocs; // Number of paged pool allocations. Use with PagedPoolFrees for leak detection and pool usage trends. + ULONG PagedPoolFrees; // Number of paged pool frees. Compare with PagedPoolAllocs to detect leaks or fragmentation. + ULONG NonPagedPoolAllocs; // Number of nonpaged pool allocations. Use with NonPagedPoolFrees for leak detection. + ULONG NonPagedPoolFrees; // Number of nonpaged pool frees. Compare with NonPagedPoolAllocs for pool usage. + ULONG FreeSystemPtes; // Number of free system page table entries (PTEs). Low values may indicate kernel memory exhaustion or fragmentation. + ULONG ResidentSystemCodePage; // Number of resident pages for system code (kernel and drivers). Use with TotalSystemCodePages for residency ratio. + ULONG TotalSystemDriverPages; // Total pages used by system drivers. Combine with TotalSystemCodePages for total kernel code usage. + ULONG TotalSystemCodePages; // Total pages used by system code (kernel + drivers). Use with ResidentSystemCodePage for residency analysis. + ULONG NonPagedPoolLookasideHits; // Hits in nonpaged pool lookaside lists. Higher values indicate efficient small nonpaged allocations. + ULONG PagedPoolLookasideHits; // Hits in paged pool lookaside lists. Higher values indicate efficient small paged allocations. + ULONG AvailablePagedPoolPages; // Number of free pages in the paged pool. Monitor for pool exhaustion or fragmentation. + ULONG ResidentSystemCachePage; // Resident pages in the system cache. Use with ResidentPagedPoolPage for cache residency analysis. + ULONG ResidentPagedPoolPage; // Resident pages in the paged pool. Indicates how much of the paged pool is currently resident in RAM. + ULONG ResidentSystemDriverPage; // Resident pages for system drivers. Use with TotalSystemDriverPages for residency ratio. + ULONG CcFastReadNoWait; // Fast cache reads completed without waiting. Use with CcFastReadWait for cache performance analysis. + ULONG CcFastReadWait; // Fast cache reads that required waiting. Compare with CcFastReadNoWait to assess cache latency. + ULONG CcFastReadResourceMiss; // Fast cache read misses due to resource contention. Indicates cache bottlenecks. + ULONG CcFastReadNotPossible; // Fast cache reads not possible (e.g., file not cached). Indicates cache limitations or bypasses. + ULONG CcFastMdlReadNoWait; // Fast MDL (Memory Descriptor List) reads completed without waiting. Use with CcFastMdlReadWait. + ULONG CcFastMdlReadWait; // Fast MDL reads that required waiting. Compare with CcFastMdlReadNoWait. + ULONG CcFastMdlReadResourceMiss; // Fast MDL read misses due to resource contention. Indicates MDL bottlenecks. + ULONG CcFastMdlReadNotPossible; // Fast MDL reads not possible. Indicates MDL limitations or cache bypass. + ULONG CcMapDataNoWait; // Cache map data operations completed without waiting. Use with CcMapDataWait for mapping efficiency. + ULONG CcMapDataWait; // Cache map data operations that required waiting. Compare with CcMapDataNoWait. + ULONG CcMapDataNoWaitMiss; // Cache map data misses without waiting. Indicates mapping bottlenecks. + ULONG CcMapDataWaitMiss; // Cache map data misses with waiting. Indicates mapping bottlenecks under contention. + ULONG CcPinMappedDataCount; // Number of pinned mapped data pages. Indicates how much data is locked in cache for I/O. + ULONG CcPinReadNoWait; // Pin reads completed without waiting. Use with CcPinReadWait for pinning efficiency. + ULONG CcPinReadWait; // Pin reads that required waiting. Compare with CcPinReadNoWait. + ULONG CcPinReadNoWaitMiss; // Pin read misses without waiting. Indicates pinning bottlenecks. + ULONG CcPinReadWaitMiss; // Pin read misses with waiting. Indicates pinning bottlenecks under contention. + ULONG CcCopyReadNoWait; // Copy reads completed without waiting. Use with CcCopyReadWait for copy efficiency. + ULONG CcCopyReadWait; // Copy reads that required waiting. Compare with CcCopyReadNoWait. + ULONG CcCopyReadNoWaitMiss; // Copy read misses without waiting. Indicates copy bottlenecks. + ULONG CcCopyReadWaitMiss; // Copy read misses with waiting. Indicates copy bottlenecks under contention. + ULONG CcMdlReadNoWait; // MDL reads completed without waiting. Use with CcMdlReadWait for MDL efficiency. + ULONG CcMdlReadWait; // MDL reads that required waiting. Compare with CcMdlReadNoWait. + ULONG CcMdlReadNoWaitMiss; // MDL read misses without waiting. Indicates MDL bottlenecks. + ULONG CcMdlReadWaitMiss; // MDL read misses with waiting. Indicates MDL bottlenecks under contention. + ULONG CcReadAheadIos; // Number of read-ahead I/O operations. Indicates cache prefetching activity. + ULONG CcLazyWriteIos; // Number of lazy write I/O operations. Indicates deferred write activity by the cache manager. + ULONG CcLazyWritePages; // Number of pages written by the lazy writer. Use with CcLazyWriteIos for writeback efficiency. + ULONG CcDataFlushes; // Number of cache data flushes. Indicates cache consistency operations (e.g., file close). + ULONG CcDataPages; // Number of pages flushed from cache. Use with CcDataFlushes for average flush size. + ULONG ContextSwitches; // Number of context switches system-wide. Use for CPU scheduling and multitasking analysis. + ULONG FirstLevelTbFills; // First-level translation buffer (TLB) fills. Indicates TLB efficiency and memory access patterns. + ULONG SecondLevelTbFills; // Second-level TLB fills. Indicates deeper TLB misses and memory access patterns. + ULONG SystemCalls; // Number of system calls made. Use for syscall activity and system workload analysis. + ULONGLONG CcTotalDirtyPages; // Total number of dirty pages in the cache (since Windows 10/Threshold). Use with CcDirtyPageThreshold for writeback policy. // since THRESHOLD + ULONGLONG CcDirtyPageThreshold; // Dirty page threshold for the cache. Compare with CcTotalDirtyPages to determine if writeback is needed. + LONGLONG ResidentAvailablePages; // Number of available pages that are resident in memory. Combine with AvailablePages for residency analysis. + ULONGLONG SharedCommittedPages; // Number of committed pages that are shared (e.g., mapped by multiple processes). Useful for shared memory analysis. + ULONGLONG MdlPagesAllocated; // Number of pages allocated for MDLs (since Windows 11 24H2). Indicates MDL resource usage. // since 24H2 + ULONGLONG PfnDatabaseCommittedPages; // Number of pages committed for the PFN (Page Frame Number) database. Kernel memory usage for tracking physical pages. + ULONGLONG SystemPageTableCommittedPages; // Number of pages committed for system page tables. Kernel memory usage for virtual-to-physical mapping structures. + ULONGLONG ContiguousPagesAllocated; // Number of contiguous pages allocated. Indicates large memory allocations (e.g., for DMA or drivers). } SYSTEM_PERFORMANCE_INFORMATION, *PSYSTEM_PERFORMANCE_INFORMATION; +/** + * The SYSTEM_TIMEOFDAY_INFORMATION structure contains information about the system uptime. + */ typedef struct _SYSTEM_TIMEOFDAY_INFORMATION { - LARGE_INTEGER BootTime; - LARGE_INTEGER CurrentTime; - LARGE_INTEGER TimeZoneBias; - ULONG TimeZoneId; - ULONG Reserved; - ULONGLONG BootTimeBias; - ULONGLONG SleepTimeBias; + LARGE_INTEGER BootTime; // Number of 100-nanosecond intervals since the system was started. + LARGE_INTEGER CurrentTime; // The current system date and time. + LARGE_INTEGER TimeZoneBias; // Number of 100-nanosecond intervals between local time and Coordinated Universal Time (UTC). + ULONG TimeZoneId; // The current system time zone identifier. + ULONG Reserved; // Reserved + ULONGLONG BootTimeBias; // Number of 100-nanosecond intervals between the boot time and Coordinated Universal Time (UTC). + ULONGLONG SleepTimeBias; // Number of 100-nanosecond intervals between the sleep time and Coordinated Universal Time (UTC). } SYSTEM_TIMEOFDAY_INFORMATION, *PSYSTEM_TIMEOFDAY_INFORMATION; /** @@ -2233,66 +2704,62 @@ typedef struct _SYSTEM_TIMEOFDAY_INFORMATION */ typedef struct _SYSTEM_THREAD_INFORMATION { - LARGE_INTEGER KernelTime; // Number of 100-nanosecond intervals spent executing kernel code. - LARGE_INTEGER UserTime; // Number of 100-nanosecond intervals spent executing user code. - LARGE_INTEGER CreateTime; // System time when the thread was created. - ULONG WaitTime; // Time spent in ready queue or waiting (depending on the thread state). - PVOID StartAddress; // Start address of the thread. - CLIENT_ID ClientId; // ID of the thread and the process owning the thread. - KPRIORITY Priority; // Dynamic thread priority. - KPRIORITY BasePriority; // Base thread priority. - ULONG ContextSwitches; // Total context switches. - KTHREAD_STATE ThreadState; // Current thread state. - KWAIT_REASON WaitReason; // The reason the thread is waiting. + LARGE_INTEGER KernelTime; // Number of 100-nanosecond intervals spent executing kernel code. + LARGE_INTEGER UserTime; // Number of 100-nanosecond intervals spent executing user code. + LARGE_INTEGER CreateTime; // The date and time when the thread was created. + ULONG WaitTime; // The current time spent in ready queue or waiting (depending on the thread state). + PVOID StartAddress; // The initial start address of the thread. + CLIENT_ID ClientId; // The identifier of the thread and the process owning the thread. + KPRIORITY Priority; // The dynamic priority of the thread. + KPRIORITY BasePriority; // The starting priority of the thread. + ULONG ContextSwitches; // The total number of context switches performed. + KTHREAD_STATE ThreadState; // The current state of the thread. + KWAIT_REASON WaitReason; // The current reason the thread is waiting. } SYSTEM_THREAD_INFORMATION, *PSYSTEM_THREAD_INFORMATION; +/** + * The SYSTEM_PROCESS_INFORMATION structure contains information about a process running on a system. + */ +_Struct_size_bytes_(NextEntryOffset) typedef struct _SYSTEM_PROCESS_INFORMATION { - ULONG NextEntryOffset; // The address of the previous item plus the value in the NextEntryOffset member. For the last item in the array, NextEntryOffset is 0. - ULONG NumberOfThreads; // The NumberOfThreads member contains the number of threads in the process. - ULONGLONG WorkingSetPrivateSize; // since VISTA - ULONG HardFaultCount; // since WIN7 - ULONG NumberOfThreadsHighWatermark; // The peak number of threads that were running at any given point in time, indicative of potential performance bottlenecks related to thread management. - ULONGLONG CycleTime; // The sum of the cycle time of all threads in the process. - LARGE_INTEGER CreateTime; // Number of 100-nanosecond intervals since the creation time of the process. Not updated during system timezone changes resullting in an incorrect value. - LARGE_INTEGER UserTime; - LARGE_INTEGER KernelTime; - UNICODE_STRING ImageName; // The file name of the executable image. - KPRIORITY BasePriority; - HANDLE UniqueProcessId; - HANDLE InheritedFromUniqueProcessId; - ULONG HandleCount; - ULONG SessionId; - ULONG_PTR UniqueProcessKey; // since VISTA (requires SystemExtendedProcessInformation) - SIZE_T PeakVirtualSize; // The peak size, in bytes, of the virtual memory used by the process. - SIZE_T VirtualSize; // The current size, in bytes, of virtual memory used by the process. - ULONG PageFaultCount; // The member of page faults for data that is not currently in memory. - SIZE_T PeakWorkingSetSize; // The peak size, in kilobytes, of the working set of the process. - SIZE_T WorkingSetSize; // The number of pages visible to the process in physical memory. These pages are resident and available for use without triggering a page fault. - SIZE_T QuotaPeakPagedPoolUsage; // The peak quota charged to the process for pool usage, in bytes. - SIZE_T QuotaPagedPoolUsage; // The quota charged to the process for paged pool usage, in bytes. - SIZE_T QuotaPeakNonPagedPoolUsage; // The peak quota charged to the process for nonpaged pool usage, in bytes. - SIZE_T QuotaNonPagedPoolUsage; // The current quota charged to the process for nonpaged pool usage. - SIZE_T PagefileUsage; // The PagefileUsage member contains the number of bytes of page file storage in use by the process. - SIZE_T PeakPagefileUsage; // The maximum number of bytes of page-file storage used by the process. - SIZE_T PrivatePageCount; // The number of memory pages allocated for the use by the process. - LARGE_INTEGER ReadOperationCount; // The total number of read operations performed. - LARGE_INTEGER WriteOperationCount; // The total number of write operations performed. - LARGE_INTEGER OtherOperationCount; // The total number of I/O operations performed other than read and write operations. - LARGE_INTEGER ReadTransferCount; // The total number of bytes read during a read operation. - LARGE_INTEGER WriteTransferCount; // The total number of bytes written during a write operation. - LARGE_INTEGER OtherTransferCount; // The total number of bytes transferred during operations other than read and write operations. - SYSTEM_THREAD_INFORMATION Threads[1]; // This type is not defined in the structure but was added for convenience. + ULONG NextEntryOffset; // The address of the previous item plus the value in the NextEntryOffset member. For the last item in the array, NextEntryOffset is 0. + ULONG NumberOfThreads; // The NumberOfThreads member contains the number of threads in the process. + ULONGLONG WorkingSetPrivateSize; // The total private memory that a process currently has allocated and is physically resident in memory. // since VISTA + ULONG HardFaultCount; // The total number of hard faults for data from disk rather than from in-memory pages. // since WIN7 + ULONG NumberOfThreadsHighWatermark; // The peak number of threads that were running at any given point in time, indicative of potential performance bottlenecks related to thread management. + ULONGLONG CycleTime; // The sum of the cycle time of all threads in the process. + LARGE_INTEGER CreateTime; // Number of 100-nanosecond intervals since the creation time of the process. Not updated during system timezone changes. + LARGE_INTEGER UserTime; // Number of 100-nanosecond intervals the process has executed in user mode. + LARGE_INTEGER KernelTime; // Number of 100-nanosecond intervals the process has executed in kernel mode. + UNICODE_STRING ImageName; // The file name of the executable image. + KPRIORITY BasePriority; // The starting priority of the process. + HANDLE UniqueProcessId; // The identifier of the process. + HANDLE InheritedFromUniqueProcessId; // The identifier of the process that created this process. Not updated and incorrectly refers to processes with recycled identifiers. + ULONG HandleCount; // The current number of open handles used by the process. + ULONG SessionId; // The identifier of the Remote Desktop Services session under which the specified process is running. + ULONG_PTR UniqueProcessKey; // since VISTA (requires SystemExtendedProcessInformation) + SIZE_T PeakVirtualSize; // The peak size, in bytes, of the virtual memory used by the process. + SIZE_T VirtualSize; // The current size, in bytes, of virtual memory used by the process. + ULONG PageFaultCount; // The total number of page faults for data that is not currently in memory. The value wraps around to zero on average 24 hours. + SIZE_T PeakWorkingSetSize; // The peak size, in kilobytes, of the working set of the process. + SIZE_T WorkingSetSize; // The number of pages visible to the process in physical memory. These pages are resident and available for use without triggering a page fault. + SIZE_T QuotaPeakPagedPoolUsage; // The peak quota charged to the process for pool usage, in bytes. + SIZE_T QuotaPagedPoolUsage; // The quota charged to the process for paged pool usage, in bytes. + SIZE_T QuotaPeakNonPagedPoolUsage; // The peak quota charged to the process for nonpaged pool usage, in bytes. + SIZE_T QuotaNonPagedPoolUsage; // The current quota charged to the process for nonpaged pool usage. + SIZE_T PagefileUsage; // The total number of bytes of page file storage in use by the process. + SIZE_T PeakPagefileUsage; // The maximum number of bytes of page-file storage used by the process. + SIZE_T PrivatePageCount; // The number of memory pages allocated for the use by the process. + LARGE_INTEGER ReadOperationCount; // The total number of read operations performed. + LARGE_INTEGER WriteOperationCount; // The total number of write operations performed. + LARGE_INTEGER OtherOperationCount; // The total number of I/O operations performed other than read and write operations. + LARGE_INTEGER ReadTransferCount; // The total number of bytes read during a read operation. + LARGE_INTEGER WriteTransferCount; // The total number of bytes written during a write operation. + LARGE_INTEGER OtherTransferCount; // The total number of bytes transferred during operations other than read and write operations. + SYSTEM_THREAD_INFORMATION Threads[1]; // This type is not defined in the structure but was added for convenience. } SYSTEM_PROCESS_INFORMATION, *PSYSTEM_PROCESS_INFORMATION; -#define SYSTEM_PROCESS_INFORMATION_SIZE RTL_SIZEOF_THROUGH_FIELD(SYSTEM_PROCESS_INFORMATION, OtherTransferCount) - -#ifdef _WIN64 -static_assert(SYSTEM_PROCESS_INFORMATION_SIZE == 0x100, "SYSTEM_PROCESS_INFORMATION_SIZE must equal SIZEOF_THROUGH_FIELD(OtherTransferCount)"); -#else -static_assert(SYSTEM_PROCESS_INFORMATION_SIZE == 0xB8, "SYSTEM_PROCESS_INFORMATION_SIZE must equal SIZEOF_THROUGH_FIELD(OtherTransferCount)"); -#endif - // private typedef struct _SYSTEM_EXTENDED_THREAD_INFORMATION { @@ -2301,76 +2768,73 @@ typedef struct _SYSTEM_EXTENDED_THREAD_INFORMATION SYSTEM_THREAD_INFORMATION ThreadInfo; struct { - ULONGLONG KernelTime; - ULONGLONG UserTime; - ULONGLONG CreateTime; - ULONG WaitTime; - PVOID StartAddress; - CLIENT_ID ClientId; - KPRIORITY Priority; - KPRIORITY BasePriority; - ULONG ContextSwitches; - KTHREAD_STATE ThreadState; - KWAIT_REASON WaitReason; + ULONGLONG KernelTime; // Number of 100-nanosecond intervals spent executing kernel code. + ULONGLONG UserTime; // Number of 100-nanosecond intervals spent executing user code. + ULONGLONG CreateTime; // The date and time when the thread was created. + ULONG WaitTime; // The current time spent in ready queue or waiting (depending on the thread state). + PVOID StartAddress; // The initial start address of the thread. + CLIENT_ID ClientId; // The identifier of the thread and the process owning the thread. + KPRIORITY Priority; // The dynamic priority of the thread. + KPRIORITY BasePriority; // The starting priority of the thread. + ULONG ContextSwitches; // The total number of context switches performed. + KTHREAD_STATE ThreadState; // The current state of the thread. + KWAIT_REASON WaitReason; // The current reason the thread is waiting. } DUMMYSTRUCTNAME; } DUMMYUNIONNAME; - ULONG_PTR StackBase; - ULONG_PTR StackLimit; - PVOID Win32StartAddress; - PVOID TebBase; // since VISTA + PVOID StackBase; // The lower boundary of the current thread stack. + PVOID StackLimit; // The upper boundary of the current thread stack. + PVOID Win32StartAddress; // The thread's Win32 start address. + PVOID TebBaseAddress; // The base address of the memory region containing the TEB structure. // since VISTA ULONG_PTR Reserved2; ULONG_PTR Reserved3; ULONG_PTR Reserved4; } SYSTEM_EXTENDED_THREAD_INFORMATION, *PSYSTEM_EXTENDED_THREAD_INFORMATION; +/** + * The SYSTEM_EXTENDED_PROCESS_INFORMATION structure contains extended information about a process running on a system. + * https://learn.microsoft.com/en-us/windows/win32/api/winternl/ns-winternl-system_extended_process_information + */ +_Struct_size_bytes_(NextEntryOffset) typedef struct _SYSTEM_EXTENDED_PROCESS_INFORMATION { - ULONG NextEntryOffset; - ULONG NumberOfThreads; - ULONGLONG WorkingSetPrivateSize; // since VISTA - ULONG HardFaultCount; // since WIN7 - ULONG NumberOfThreadsHighWatermark; - ULONGLONG CycleTime; - ULONGLONG CreateTime; - ULONGLONG UserTime; - ULONGLONG KernelTime; - UNICODE_STRING ImageName; - KPRIORITY BasePriority; - HANDLE UniqueProcessId; - HANDLE InheritedFromUniqueProcessId; - ULONG HandleCount; - ULONG SessionId; - HANDLE UniqueProcessKey; // since VISTA - 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; - ULONGLONG ReadOperationCount; - ULONGLONG WriteOperationCount; - ULONGLONG OtherOperationCount; - ULONGLONG ReadTransferCount; - ULONGLONG WriteTransferCount; - ULONGLONG OtherTransferCount; - SYSTEM_EXTENDED_THREAD_INFORMATION Threads[1]; + ULONG NextEntryOffset; // The address of the previous item plus the value in the NextEntryOffset member. For the last item in the array, NextEntryOffset is 0. + ULONG NumberOfThreads; // The NumberOfThreads member contains the number of threads in the process. + ULONGLONG WorkingSetPrivateSize; // The total private memory that a process currently has allocated and is physically resident in memory. // since VISTA + ULONG HardFaultCount; // The total number of hard faults for data from disk rather than from in-memory pages. // since WIN7 + ULONG NumberOfThreadsHighWatermark; // The peak number of threads that were running at any given point in time, indicative of potential performance bottlenecks related to thread management. + ULONGLONG CycleTime; // The sum of the cycle time of all threads in the process. + ULONGLONG CreateTime; // Number of 100-nanosecond intervals since the creation time of the process. Not updated during system timezone changes. + ULONGLONG UserTime; // Number of 100-nanosecond intervals the process has executed in user mode. + ULONGLONG KernelTime; // Number of 100-nanosecond intervals the process has executed in kernel mode. + UNICODE_STRING ImageName; // The file name of the executable image. + KPRIORITY BasePriority; // The starting priority of the process. + HANDLE UniqueProcessId; // The identifier of the process. + HANDLE InheritedFromUniqueProcessId; // The identifier of the process that created this process. Not updated and incorrectly refers to processes with recycled identifiers. + ULONG HandleCount; // The current number of open handles used by the process. + ULONG SessionId; // The identifier of the Remote Desktop Services session under which the specified process is running. + HANDLE UniqueProcessKey; // since VISTA (requires SystemExtendedProcessInformation) + SIZE_T PeakVirtualSize; // The peak size, in bytes, of the virtual memory used by the process. + SIZE_T VirtualSize; // The current size, in bytes, of virtual memory used by the process. + ULONG PageFaultCount; // The total number of page faults for data that is not currently in memory. The value wraps around to zero on average 24 hours. + SIZE_T PeakWorkingSetSize; // The peak size, in kilobytes, of the working set of the process. + SIZE_T WorkingSetSize; // The number of pages visible to the process in physical memory. These pages are resident and available for use without triggering a page fault. + SIZE_T QuotaPeakPagedPoolUsage; // The peak quota charged to the process for pool usage, in bytes. + SIZE_T QuotaPagedPoolUsage; // The quota charged to the process for paged pool usage, in bytes. + SIZE_T QuotaPeakNonPagedPoolUsage; // The peak quota charged to the process for nonpaged pool usage, in bytes. + SIZE_T QuotaNonPagedPoolUsage; // The current quota charged to the process for nonpaged pool usage. + SIZE_T PagefileUsage; // The total number of bytes of page file storage in use by the process. + SIZE_T PeakPagefileUsage; // The maximum number of bytes of page-file storage used by the process. + SIZE_T PrivatePageCount; // The number of memory pages allocated for the use by the process. + ULONGLONG ReadOperationCount; // The total number of read operations performed. + ULONGLONG WriteOperationCount; // The total number of write operations performed. + ULONGLONG OtherOperationCount; // The total number of I/O operations performed other than read and write operations. + ULONGLONG ReadTransferCount; // The total number of bytes read during a read operation. + ULONGLONG WriteTransferCount; // The total number of bytes written during a write operation. + ULONGLONG OtherTransferCount; // The total number of bytes transferred during operations other than read and write operations. + SYSTEM_THREAD_INFORMATION Threads[1]; // This type is not defined in the structure but was added for convenience. // SYSTEM_PROCESS_INFORMATION_EXTENSION // SystemFullProcessInformation } SYSTEM_EXTENDED_PROCESS_INFORMATION, *PSYSTEM_EXTENDED_PROCESS_INFORMATION; -#define SYSTEM_EXTENDED_PROCESS_INFORMATION_SIZE RTL_SIZEOF_THROUGH_FIELD(SYSTEM_EXTENDED_PROCESS_INFORMATION, OtherTransferCount) - -#ifdef _WIN64 -static_assert(SYSTEM_EXTENDED_PROCESS_INFORMATION_SIZE == 0x100, "SYSTEM_EXTENDED_PROCESS_INFORMATION_SIZE must equal SIZEOF_THROUGH_FIELD(OtherTransferCount)"); -#else -static_assert(SYSTEM_EXTENDED_PROCESS_INFORMATION_SIZE == 0xB8, "SYSTEM_EXTENDED_PROCESS_INFORMATION_SIZE must equal SIZEOF_THROUGH_FIELD(OtherTransferCount)"); -#endif - typedef struct _SYSTEM_CALL_COUNT_INFORMATION { ULONG Length; @@ -2387,14 +2851,19 @@ typedef struct _SYSTEM_DEVICE_INFORMATION ULONG NumberOfParallelPorts; } SYSTEM_DEVICE_INFORMATION, *PSYSTEM_DEVICE_INFORMATION; +/** + * The SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION structure contains information about the performance of each processor installed in the system. + * https://learn.microsoft.com/en-us/windows/win32/api/winternl/nf-winternl-ntquerysysteminformation#system_processor_performance_information + */ typedef struct _SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION { - LARGE_INTEGER IdleTime; - LARGE_INTEGER KernelTime; - LARGE_INTEGER UserTime; - LARGE_INTEGER DpcTime; - LARGE_INTEGER InterruptTime; - ULONG InterruptCount; + LARGE_INTEGER IdleTime; // The IdleTime member contains the amount of time that the system has been idle, in 100-nanosecond intervals. + LARGE_INTEGER KernelTime; // The KernelTime member contains the amount of time that the system has spent executing in Kernel mode (including all threads in all processes, on all processors), in 100-nanosecond intervals. + LARGE_INTEGER UserTime; // The UserTime member contains the amount of time that the system has spent executing in User mode (including all threads in all processes, on all processors), in 100-nanosecond intervals. + LARGE_INTEGER DpcTime; // The DpcTime member contains the amount of time that the system has spent processing deferred procedure calls (DPCs), in 100-nanosecond intervals. + LARGE_INTEGER InterruptTime; // The InterruptTime member contains the amount of time that the system has spent processing hardware interrupts, in 100-nanosecond intervals. + ULONG InterruptCount; // The InterruptCount member contains the number of interrupts that have occurred, as counted by the system. + ULONG Spare0; } SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION, *PSYSTEM_PROCESSOR_PERFORMANCE_INFORMATION; typedef struct _SYSTEM_FLAGS_INFORMATION @@ -2448,6 +2917,10 @@ typedef struct _SYSTEM_CALL_TIME_INFORMATION LARGE_INTEGER TimeOfCalls[1]; } SYSTEM_CALL_TIME_INFORMATION, *PSYSTEM_CALL_TIME_INFORMATION; +// RTL_PROCESS_LOCK_INFORMATION Type +#define RTL_CRITSECT_TYPE 0 +#define RTL_RESOURCE_TYPE 1 + // private typedef struct _RTL_PROCESS_LOCK_INFORMATION { @@ -2483,13 +2956,14 @@ typedef struct _RTL_PROCESS_BACKTRACE_INFORMATION // private typedef struct _RTL_PROCESS_BACKTRACES { - ULONG CommittedMemory; - ULONG ReservedMemory; + SIZE_T CommittedMemory; + SIZE_T ReservedMemory; ULONG NumberOfBackTraceLookups; ULONG NumberOfBackTraces; _Field_size_(NumberOfBackTraces) RTL_PROCESS_BACKTRACE_INFORMATION BackTraces[1]; } RTL_PROCESS_BACKTRACES, *PRTL_PROCESS_BACKTRACES; +// Note: This information class is deprecated since values are limited to 65535. Use SystemExtendedHandleInformation instead. typedef struct _SYSTEM_HANDLE_TABLE_ENTRY_INFO { USHORT UniqueProcessId; @@ -2507,6 +2981,7 @@ typedef struct _SYSTEM_HANDLE_INFORMATION _Field_size_(NumberOfHandles) SYSTEM_HANDLE_TABLE_ENTRY_INFO Handles[1]; } SYSTEM_HANDLE_INFORMATION, *PSYSTEM_HANDLE_INFORMATION; +_Struct_size_bytes_(NextEntryOffset) typedef struct _SYSTEM_OBJECTTYPE_INFORMATION { ULONG NextEntryOffset; @@ -2522,6 +2997,7 @@ typedef struct _SYSTEM_OBJECTTYPE_INFORMATION UNICODE_STRING TypeName; } SYSTEM_OBJECTTYPE_INFORMATION, *PSYSTEM_OBJECTTYPE_INFORMATION; +_Struct_size_bytes_(NextEntryOffset) typedef struct _SYSTEM_OBJECT_INFORMATION { ULONG NextEntryOffset; @@ -2534,10 +3010,11 @@ typedef struct _SYSTEM_OBJECT_INFORMATION ULONG PagedPoolCharge; ULONG NonPagedPoolCharge; HANDLE ExclusiveProcessId; - PVOID SecurityDescriptor; + PSECURITY_DESCRIPTOR SecurityDescriptor; UNICODE_STRING NameInfo; } SYSTEM_OBJECT_INFORMATION, *PSYSTEM_OBJECT_INFORMATION; +_Struct_size_bytes_(NextEntryOffset) typedef struct _SYSTEM_PAGEFILE_INFORMATION { ULONG NextEntryOffset; @@ -2720,7 +3197,7 @@ typedef struct _EVENT_TRACE_GROUPMASK_INFORMATION { EVENT_TRACE_INFORMATION_CLASS EventTraceInformationClass; TRACEHANDLE TraceHandle; - ULONG EventTraceGroupMasks[8]; // PERFINFO_GROUPMASK + ULONG Masks[8]; // PERFINFO_GROUPMASK } EVENT_TRACE_GROUPMASK_INFORMATION, *PEVENT_TRACE_GROUPMASK_INFORMATION; typedef struct _EVENT_TRACE_PERFORMANCE_INFORMATION @@ -2801,6 +3278,7 @@ typedef struct _EVENT_TRACE_PROFILE_COUNTER_INFORMATION typedef EVENT_TRACE_PROFILE_COUNTER_INFORMATION EVENT_TRACE_PROFILE_CONFIG_INFORMATION, *PEVENT_TRACE_PROFILE_CONFIG_INFORMATION; +//_Struct_size_bytes_(NextEntryOffset) //typedef struct _PROFILE_SOURCE_INFO //{ // ULONG NextEntryOffset; @@ -3021,41 +3499,37 @@ typedef struct _SYSTEM_RANGE_START_INFORMATION ULONG_PTR SystemRangeStart; } SYSTEM_RANGE_START_INFORMATION, *PSYSTEM_RANGE_START_INFORMATION; +_Struct_size_bytes_(NextEntryOffset) 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; +_Struct_size_bytes_(NextEntryOffset) typedef struct _SYSTEM_VERIFIER_INFORMATION { ULONG NextEntryOffset; @@ -3063,32 +3537,25 @@ typedef struct _SYSTEM_VERIFIER_INFORMATION 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; @@ -3099,7 +3566,7 @@ typedef struct _SYSTEM_VERIFIER_INFORMATION typedef struct _SYSTEM_SESSION_PROCESS_INFORMATION { ULONG SessionId; - ULONG SizeOfBuf; + ULONG BufferSize; PVOID Buffer; } SYSTEM_SESSION_PROCESS_INFORMATION, *PSYSTEM_SESSION_PROCESS_INFORMATION; @@ -3226,6 +3693,7 @@ typedef struct _SYSTEM_POOL_INFORMATION _Field_size_(NumberOfEntries) SYSTEM_POOL_ENTRY Entries[1]; } SYSTEM_POOL_INFORMATION, *PSYSTEM_POOL_INFORMATION; +_Struct_size_bytes_(NextEntryOffset) typedef struct _SYSTEM_SESSION_POOLTAG_INFORMATION { SIZE_T NextEntryOffset; @@ -3234,6 +3702,7 @@ typedef struct _SYSTEM_SESSION_POOLTAG_INFORMATION _Field_size_(Count) SYSTEM_POOLTAG TagInfo[1]; } SYSTEM_SESSION_POOLTAG_INFORMATION, *PSYSTEM_SESSION_POOLTAG_INFORMATION; +_Struct_size_bytes_(NextEntryOffset) typedef struct _SYSTEM_SESSION_MAPPED_VIEW_INFORMATION { SIZE_T NextEntryOffset; @@ -3314,9 +3783,11 @@ typedef struct _SYSTEM_FIRMWARE_TABLE_INFORMATION #if (PHNT_MODE != PHNT_MODE_KERNEL) // private -typedef NTSTATUS (__cdecl* PFNFTH)( +typedef _Function_class_(FNFTH) +NTSTATUS STDAPIVCALLTYPE FNFTH( _Inout_ PSYSTEM_FIRMWARE_TABLE_INFORMATION SystemFirmwareTableInfo ); +typedef FNFTH* PFNFTH; // private typedef struct _SYSTEM_FIRMWARE_TABLE_HANDLER @@ -3353,14 +3824,26 @@ typedef enum _SYSTEM_MEMORY_LIST_COMMAND MemoryCommandMax } SYSTEM_MEMORY_LIST_COMMAND; -// private +/** + * The SYSTEM_THREAD_CID_PRIORITY_INFORMATION structure is used with NtSetSystemInformation + * to set the priority of a thread by its client ID (process ID and thread ID) without + * requiring a thread handle. + * + * \remarks This structure is used with the SystemThreadPriorityClientIdInformation + * information class (0x52). The caller must have SeIncreaseBasePriorityPrivilege + * to raise a thread's priority above normal. + */ typedef struct _SYSTEM_THREAD_CID_PRIORITY_INFORMATION { - CLIENT_ID ClientId; - KPRIORITY Priority; + CLIENT_ID ClientId; // The process and thread identifiers of the target thread. + KPRIORITY Priority; // The new priority value to assign to the thread. } SYSTEM_THREAD_CID_PRIORITY_INFORMATION, *PSYSTEM_THREAD_CID_PRIORITY_INFORMATION; -// private +/** + * The SYSTEM_PROCESSOR_IDLE_CYCLE_TIME_INFORMATION structure contains the cumulative number of clock cycles a logical processor + * has spent running its idle thread, deferred procedure calls (DPCs) and interrupt service routines (ISRs) since it became active. + * \see https://learn.microsoft.com/en-us/windows/win32/api/realtimeapiset/nf-realtimeapiset-queryidleprocessorcycletimeex + */ typedef struct _SYSTEM_PROCESSOR_IDLE_CYCLE_TIME_INFORMATION { ULONGLONG CycleTime; @@ -3401,7 +3884,11 @@ typedef struct _SYSTEM_SPECIAL_POOL_INFORMATION ULONG Flags; } SYSTEM_SPECIAL_POOL_INFORMATION, *PSYSTEM_SPECIAL_POOL_INFORMATION; -// private +/** + * The SYSTEM_PROCESS_ID_INFORMATION structure retrieves the executable image + * name associated with a specific process ID. The caller supplies a process ID, + * and on return the system fills the UNICODE_STRING with the corresponding image path. + */ typedef struct _SYSTEM_PROCESS_ID_INFORMATION { HANDLE ProcessId; @@ -3600,27 +4087,34 @@ typedef struct _SYSTEM_CODEINTEGRITY_INFORMATION ULONG CodeIntegrityOptions; struct { - ULONG Enabled : 1; - ULONG TestSign : 1; - ULONG UmciEnabled : 1; - ULONG UmciAuditModeEnabled : 1; - ULONG UmciExclusionPathsEnabled : 1; - ULONG TestBuild : 1; - ULONG PreproductionBuild : 1; - ULONG DebugModeEnabled : 1; - ULONG FlightBuild : 1; - ULONG FlightingEnabled : 1; - ULONG HvciKmciEnabled : 1; - ULONG HvciKmciAuditModeEnabled : 1; - ULONG HvciKmciStrictModeEnabled : 1; - ULONG HvciIumEnabled : 1; - ULONG WhqlEnforcementEnabled : 1; - ULONG WhqlAuditModeEnabled : 1; + ULONG Enabled : 1; // CODEINTEGRITY_OPTION_ENABLED + ULONG TestSign : 1; // CODEINTEGRITY_OPTION_TESTSIGN + ULONG UmciEnabled : 1; // CODEINTEGRITY_OPTION_UMCI_ENABLED + ULONG UmciAuditModeEnabled : 1; // CODEINTEGRITY_OPTION_UMCI_AUDITMODE_ENABLED + ULONG UmciExclusionPathsEnabled : 1; // CODEINTEGRITY_OPTION_UMCI_EXCLUSIONPATHS_ENABLED + ULONG TestBuild : 1; // CODEINTEGRITY_OPTION_TEST_BUILD + ULONG PreproductionBuild : 1; // CODEINTEGRITY_OPTION_PREPRODUCTION_BUILD + ULONG DebugModeEnabled : 1; // CODEINTEGRITY_OPTION_DEBUGMODE_ENABLE + ULONG FlightBuild : 1; // CODEINTEGRITY_OPTION_FLIGHT_BUILD + ULONG FlightingEnabled : 1; // CODEINTEGRITY_OPTION_FLIGHTING_ENABLED + ULONG HvciKmciEnabled : 1; // CODEINTEGRITY_OPTION_HVCI_KMCI_ENABLED + ULONG HvciKmciAuditModeEnabled : 1; // CODEINTEGRITY_OPTION_HVCI_KMCI_AUDITMODE_ENABLED + ULONG HvciKmciStrictModeEnabled : 1; // CODEINTEGRITY_OPTION_HVCI_KMCI_STRICTMODE_ENABLED + ULONG HvciIumEnabled : 1; // CODEINTEGRITY_OPTION_HVCI_IUM_ENABLED + ULONG WhqlEnforcementEnabled : 1; // CODEINTEGRITY_OPTION_WHQL_ENFORCEMENT_ENABLED + ULONG WhqlAuditModeEnabled : 1; // CODEINTEGRITY_OPTION_WHQL_AUDITMODE_ENABLED ULONG Spare : 16; }; }; } SYSTEM_CODEINTEGRITY_INFORMATION, *PSYSTEM_CODEINTEGRITY_INFORMATION; +// rev +// Loads mcupdate.dll via ntosext.sys to perform microcode updates. +#define PROCESSOR_MICROCODE_OPERATION_LOAD 0x01 +// rev +// Unloads mcupdate.dll via ntosext.sys to preform microcode updates. +#define PROCESSOR_MICROCODE_OPERATION_UNLOAD 0x02 + // private typedef struct _SYSTEM_PROCESSOR_MICROCODE_UPDATE_INFORMATION { @@ -3648,32 +4142,140 @@ typedef struct _SYSTEM_VA_LIST_INFORMATION SIZE_T AllocationFailures; } SYSTEM_VA_LIST_INFORMATION, *PSYSTEM_VA_LIST_INFORMATION; +// private +//typedef enum _LOGICAL_PROCESSOR_RELATIONSHIP +//{ +// RelationProcessorCore, +// RelationNumaNode, +// RelationCache, +// RelationProcessorPackage, +// RelationGroup, +// RelationProcessorDie, +// RelationNumaNodeEx, +// RelationProcessorModule, +// RelationAll = 0xffff +//} LOGICAL_PROCESSOR_RELATIONSHIP; +// +// private +//typedef struct _SYSTEM_LOGICAL_PROCESSOR_INFORMATION +//{ +// ULONG_PTR ProcessorMask; +// LOGICAL_PROCESSOR_RELATIONSHIP Relationship; +// union +// { +// struct +// { +// UCHAR Flags; +// } ProcessorCore; +// struct +// { +// ULONG NodeNumber; +// } NumaNode; +// CACHE_DESCRIPTOR Cache; +// ULONGLONG Reserved[2]; +// }; +//} SYSTEM_LOGICAL_PROCESSOR_INFORMATION, *PSYSTEM_LOGICAL_PROCESSOR_INFORMATION; +// +// private +//typedef struct _PROCESSOR_RELATIONSHIP +//{ +// UCHAR Flags; +// UCHAR EfficiencyClass; +// UCHAR Reserved[20]; +// USHORT GroupCount; +// _Field_size_(GroupCount) GROUP_AFFINITY GroupMask[ANYSIZE_ARRAY]; +//} PROCESSOR_RELATIONSHIP, *PPROCESSOR_RELATIONSHIP; +// +// private +//typedef struct _NUMA_NODE_RELATIONSHIP +//{ +// ULONG NodeNumber; +// UCHAR Reserved[18]; +// USHORT GroupCount; +// union +// { +// GROUP_AFFINITY GroupMask; +// _Field_size_(GroupCount) GROUP_AFFINITY GroupMasks[ANYSIZE_ARRAY]; +// }; +//} NUMA_NODE_RELATIONSHIP, *PNUMA_NODE_RELATIONSHIP; +// +// private +//typedef struct _CACHE_RELATIONSHIP +//{ +// UCHAR Level; +// UCHAR Associativity; +// USHORT LineSize; +// ULONG CacheSize; +// PROCESSOR_CACHE_TYPE Type; +// UCHAR Reserved[18]; +// USHORT GroupCount; +// union +// { +// GROUP_AFFINITY GroupMask; +// _Field_size_(GroupCount) GROUP_AFFINITY GroupMasks[ANYSIZE_ARRAY]; +// }; +//} CACHE_RELATIONSHIP, *PCACHE_RELATIONSHIP; +// +// private +//typedef struct _PROCESSOR_GROUP_INFO +//{ +// UCHAR MaximumProcessorCount; +// UCHAR ActiveProcessorCount; +// UCHAR Reserved[38]; +// KAFFINITY ActiveProcessorMask; +//} PROCESSOR_GROUP_INFO, *PPROCESSOR_GROUP_INFO; +// +// private +//typedef struct _GROUP_RELATIONSHIP +//{ +// USHORT MaximumGroupCount; +// USHORT ActiveGroupCount; +// UCHAR Reserved[20]; +// _Field_size_(ActiveGroupCount) PROCESSOR_GROUP_INFO GroupInfo[ANYSIZE_ARRAY]; +//} GROUP_RELATIONSHIP, *PGROUP_RELATIONSHIP; +// +// private +//typedef _Struct_size_bytes_(Size) struct _SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX +//{ +// LOGICAL_PROCESSOR_RELATIONSHIP Relationship; +// ULONG Size; +// _Field_size_bytes_(Size - (sizeof(LOGICAL_PROCESSOR_RELATIONSHIP) + sizeof(ULONG))) union +// { +// PROCESSOR_RELATIONSHIP Processor; +// NUMA_NODE_RELATIONSHIP NumaNode; +// CACHE_RELATIONSHIP Cache; +// GROUP_RELATIONSHIP Group; +// }; +//} SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX, *PSYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX; + // 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: SM_STORE_CACHE_RESIZE_REQUEST (requires SeProfileSingleProcessPrivilege) - SmConfigRequest = 19, // s: SM_CONFIG_REQUEST (requires SeProfileSingleProcessPrivilege) - StoreHighMemoryPriorityRequest = 20, // s: SM_STORE_HIGH_MEMORY_PRIORITY_REQUEST (requires SeProfileSingleProcessPrivilege) - SystemStoreTrimRequest = 21, // s: SM_SYSTEM_STORE_TRIM_REQUEST (requires SeProfileSingleProcessPrivilege) // SmProcessSystemStoreTrimRequest - MemCompressionInfoRequest = 22, // q: SM_STORE_COMPRESSION_INFORMATION_REQUEST // SmProcessCompressionInfoRequest - ProcessStoreInfoRequest = 23, // SmProcessProcessStoreInfoRequest + StorePageRequest = 1, // q: Not implemented + 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 + + StoreEmptyRequest = 7, // q: Not implemented + CacheListRequest = 8, // q: SMC_CACHE_LIST_REQUEST // SmcProcessListRequest + CacheCreateRequest = 9, // s: SMC_CACHE_CREATE_REQUEST (requires SeProfileSingleProcessPrivilege) // SmcProcessCreateRequest + CacheDeleteRequest = 10, // s: SMC_CACHE_DELETE_REQUEST (requires SeProfileSingleProcessPrivilege) // SmcProcessDeleteRequest + CacheStoreCreateRequest = 11, // s: SMC_STORE_CREATE_REQUEST (requires SeProfileSingleProcessPrivilege) // SmcProcessStoreCreateRequest + CacheStoreDeleteRequest = 12, // s: SMC_STORE_DELETE_REQUEST (requires SeProfileSingleProcessPrivilege) // SmcProcessStoreDeleteRequest + CacheStatsRequest = 13, // q: SMC_CACHE_STATS_REQUEST // SmcProcessStatsRequest + + RegistrationRequest = 15, // q: SM_REGISTRATION_REQUEST (requires SeProfileSingleProcessPrivilege) // SmProcessRegistrationRequest + GlobalCacheStatsRequest = 16, // q: Not implemented + StoreResizeRequest = 17, // s: SM_STORE_RESIZE_REQUEST (requires SeProfileSingleProcessPrivilege) // SmProcessResizeRequest + CacheStoreResizeRequest = 18, // s: SM_STORE_CACHE_RESIZE_REQUEST (requires SeProfileSingleProcessPrivilege) // SmcProcessResizeRequest + SmConfigRequest = 19, // s: SM_CONFIG_REQUEST (requires SeProfileSingleProcessPrivilege) + StoreHighMemoryPriorityRequest = 20, // s: SM_STORE_HIGH_MEMORY_PRIORITY_REQUEST (requires SeProfileSingleProcessPrivilege) + SystemStoreTrimRequest = 21, // s: SM_SYSTEM_STORE_TRIM_REQUEST (requires SeProfileSingleProcessPrivilege) // SmProcessSystemStoreTrimRequest + MemCompressionInfoRequest = 22, // q: SM_STORE_COMPRESSION_INFORMATION_REQUEST // SmProcessCompressionInfoRequest + StoreExistsForProcess = 23, // q: SM_SYSTEM_STORE_EXISTS_FOR_PROCESS // SmProcessProcessStoreInfoRequest // 25H2 + CompressionReadStatsRequest = 24, // q: SM_COMPRESSION_READ_STATS_REQUEST // SmProcessCompressionReadStatsRequest + CompressionAcceleratorRequest = 25, // q: SM_COMPRESSION_ACCELERATOR_REQUEST // SmProcessCompressionAcceleratorRequest StoreInformationMax } STORE_INFORMATION_CLASS; @@ -3952,9 +4554,9 @@ typedef struct _SMC_CACHE_DELETE_REQUEST typedef enum _SM_STORE_MANAGER_TYPE { - SmStoreManagerTypePhysical=0, - SmStoreManagerTypeVirtual=1, - SmStoreManagerTypeMax=2 + SmStoreManagerTypePhysical = 0, + SmStoreManagerTypeVirtual = 1, + SmStoreManagerTypeMax = 2 } SM_STORE_MANAGER_TYPE; typedef struct _SMC_STORE_CREATE_REQUEST @@ -3998,9 +4600,9 @@ typedef struct _SMC_CACHE_STATS typedef struct _SMC_CACHE_STATS_REQUEST { ULONG Version : 8; // SYSTEM_CACHE_STATS_INFORMATION_VERSION - ULONG NoFilePath : 1; + ULONG NoFilePath : 1; // Skip TemplateFilePath when set ULONG Spare : 23; - ULONG CacheId; + ULONG CacheId; // cache to query for statistics SMC_CACHE_STATS CacheStats; } SMC_CACHE_STATS_REQUEST, *PSMC_CACHE_STATS_REQUEST; @@ -4053,6 +4655,7 @@ typedef enum _SM_CONFIG_TYPE SmConfigTypeMax = 3 } SM_CONFIG_TYPE; +// rev typedef struct _SM_CONFIG_REQUEST { ULONG Version : 8; // SYSTEM_STORE_CONFIG_INFORMATION_VERSION @@ -4061,23 +4664,26 @@ typedef struct _SM_CONFIG_REQUEST ULONG ConfigValue; } SM_CONFIG_REQUEST, *PSM_CONFIG_REQUEST; -#define SYSTEM_STORE_HIGH_MEM_PRIORITY_INFORMATION_VERSION 1 +// rev +#define SYSTEM_STORE_PRIORITY_REQUEST_VERSION 1 +// rev +#define SYSTEM_STORE_PRIORITY_FLAG_REQUIRE_HANDLE 0x00000100u // required +#define SYSTEM_STORE_PRIORITY_FLAG_SET_PRIORITY 0x00000200u // rev -typedef struct _SM_STORE_HIGH_MEMORY_PRIORITY_REQUEST +typedef struct _SM_STORE_MEMORY_PRIORITY_REQUEST { - ULONG Version : 8; // SYSTEM_STORE_HIGH_MEMORY_PRIORITY_INFORMATION_VERSION - ULONG SetHighMemoryPriority : 1; - ULONG Spare : 23; - HANDLE ProcessHandle; -} SM_STORE_HIGH_MEMORY_PRIORITY_REQUEST, *PSM_STORE_HIGH_MEMORY_PRIORITY_REQUEST; + ULONG Version : 8; // SYSTEM_STORE_PRIORITY_REQUEST_VERSION + ULONG Flags : 24; + HANDLE ProcessHandle; // in // PROCESS_SET_INFORMATION access required +} SM_STORE_MEMORY_PRIORITY_REQUEST, *PSM_STORE_MEMORY_PRIORITY_REQUEST; // rev typedef struct _SM_SYSTEM_STORE_TRIM_REQUEST { ULONG Version : 8; // SYSTEM_STORE_TRIM_INFORMATION_VERSION ULONG Spare : 24; - SIZE_T PagesToTrim; + SIZE_T PagesToTrim; // TrimFlags // must be non-zero HANDLE PartitionHandle; // since 24H2 } SM_SYSTEM_STORE_TRIM_REQUEST, *PSM_SYSTEM_STORE_TRIM_REQUEST; @@ -4130,6 +4736,51 @@ static_assert(SYSTEM_STORE_COMPRESSION_INFORMATION_SIZE_V1 == 24, "SM_STORE_COMP static_assert(SYSTEM_STORE_COMPRESSION_INFORMATION_SIZE_V2 == 28, "SM_STORE_COMPRESSION_INFORMATION_REQUEST_V2 must equal 28"); #endif +// rev +#define SYSTEM_STORE_EXISTS_FOR_PROCESS_VERSION 1 + +// rev +typedef struct _SM_SYSTEM_STORE_EXISTS_FOR_PROCESS +{ + ULONG Version : 8; + ULONG Spare : 24; + HANDLE ProcessHandle; // in // PROCESS_QUERY_INFORMATION access required + BOOLEAN StoreExists; // out +} SM_SYSTEM_STORE_EXISTS_FOR_PROCESS, *PSM_SYSTEM_STORE_EXISTS_FOR_PROCESS; + +// rev +typedef struct _SM_COMPRESSION_READ_STATS +{ + ULONGLONG Counters[17]; + ULONGLONG TailValue; +} SM_COMPRESSION_READ_STATS, * PSM_COMPRESSION_READ_STATS; + +// rev +#define SYSTEM_STORE_COMPRESSION_READ_STATS_VERSION 1 + +// rev +typedef struct _SM_COMPRESSION_READ_STATS_REQUEST +{ + ULONG Version : 8; // SYSTEM_STORE_COMPRESSION_READ_STATS_VERSION + ULONG Spare : 24; + ULONG Flags; // must be zero + HANDLE PartitionHandle; // optional + SM_COMPRESSION_READ_STATS Stats; // output +} SM_COMPRESSION_READ_STATS_REQUEST, *PSM_COMPRESSION_READ_STATS_REQUEST; + +// rev +#define SYSTEM_STORE_ACCELERATOR_REQUEST_VERSION 1 + +// rev +typedef struct _SM_COMPRESSION_ACCELERATOR_REQUEST +{ + ULONG Version : 8; // SYSTEM_STORE_ACCELERATOR_REQUEST_VERSION + ULONG Spare : 24; + ULONG Flags; // must be zero + HANDLE PartitionHandle; // optional + ULONG AcceleratorValue; // output +} SM_COMPRESSION_ACCELERATOR_REQUEST, *PSM_COMPRESSION_ACCELERATOR_REQUEST; + // private typedef struct _SYSTEM_REGISTRY_APPEND_STRING_PARAMETERS { @@ -4177,14 +4828,14 @@ typedef struct _SYSTEM_ERROR_PORT_TIMEOUTS // private typedef struct _SYSTEM_LOW_PRIORITY_IO_INFORMATION { - ULONG LowPriReadOperations; - ULONG LowPriWriteOperations; + ULONG LowPriorityReadOperationCount; + ULONG LowPriorityWriteOperationCount; ULONG KernelBumpedToNormalOperations; - ULONG LowPriPagingReadOperations; + ULONG LowPriorityPagingReadOperations; ULONG KernelPagingReadsBumpedToNormal; - ULONG LowPriPagingWriteOperations; + ULONG LowPriorityPagingWriteOperations; ULONG KernelPagingWritesBumpedToNormal; - ULONG BoostedIrpCount; + ULONG BoostedThreadedIrpCount; ULONG BoostedPagingIrpCount; ULONG BlanketBoostCount; } SYSTEM_LOW_PRIORITY_IO_INFORMATION, *PSYSTEM_LOW_PRIORITY_IO_INFORMATION; @@ -4562,9 +5213,10 @@ typedef struct _SYSTEM_SECUREBOOT_POLICY_INFORMATION } SYSTEM_SECUREBOOT_POLICY_INFORMATION, *PSYSTEM_SECUREBOOT_POLICY_INFORMATION; // private +_Struct_size_bytes_(NextEntryOffset) typedef struct _SYSTEM_PAGEFILE_INFORMATION_EX { - union // HACK union declaration for convenience (dmex) + union // union declaration for convenience (dmex) { SYSTEM_PAGEFILE_INFORMATION Info; struct @@ -4610,80 +5262,263 @@ typedef union _ENERGY_STATE_DURATION } DUMMYSTRUCTNAME; } ENERGY_STATE_DURATION, *PENERGY_STATE_DURATION; +/** + * The PROCESS_ENERGY_VALUES_QOS_INDEX type represents the QoS (Quality of Service) / + * thread-context bucket used as the first index of the Cycles, AttributedCycles, and + * WorkOnBehalfCycles arrays in PROCESS_ENERGY_VALUES. + */ +typedef enum _PROCESS_ENERGY_VALUES_QOS_INDEX +{ + // Foreground / High QoS — threads running at foreground or high quality-of-service priority. + ProcessEnergyValuesQoSHighForeground = 0, + // Above-normal — threads running at above-normal priority. + ProcessEnergyValuesQoSAboveNormal = 1, + // Normal — threads running at normal priority. + ProcessEnergyValuesQoSNormal = 2, + // Background / Low QoS — threads running at background or low quality-of-service priority. + ProcessEnergyValuesQoSLowBackground = 3, + // The maximum number of QoS buckets. + ProcessEnergyValuesQoSMax = 4 +} PROCESS_ENERGY_VALUES_QOS_INDEX, *PPROCESS_ENERGY_VALUES_QOS_INDEX; + +/** + * The PROCESS_ENERGY_VALUES_CYCLE_TYPE_INDEX type represents the cycle type (user vs. kernel) + * used as the second index of the Cycles, AttributedCycles, and WorkOnBehalfCycles. + */ +typedef enum _PROCESS_ENERGY_VALUES_CYCLE_TYPE_INDEX +{ + // User-mode cycles accumulated by threads in this QoS bucket. + ProcessEnergyValuesCycleTypeUser = 0, + // Kernel-mode cycles accumulated by threads in this QoS bucket. + ProcessEnergyValuesCycleTypeKernel = 1, + // The maximum number of cycle types. + ProcessEnergyValuesCycleTypeMax = 2 +} PROCESS_ENERGY_VALUES_CYCLE_TYPE_INDEX, *PPROCESS_ENERGY_VALUES_CYCLE_TYPE_INDEX; + +/** + * \brief Energy accounting values for a process, broken down by QoS bucket and cycle type. + * + * \details Contains CPU cycle counts, energy estimates, network/MBB byte counts, + * activity durations, and DWM composition statistics accumulated for a process. + * CPU cycles are indexed by QoS bucket (see PROCESS_ENERGY_VALUES_QOS_INDEX) and + * cycle type (see PROCESS_ENERGY_VALUES_CYCLE_TYPE_INDEX). + */ typedef struct _PROCESS_ENERGY_VALUES { - ULONGLONG Cycles[4][2]; + /** + * CPU cycles accumulated per QoS bucket and cycle type. + * First index: QoS bucket (PROCESS_ENERGY_VALUES_QOS_INDEX). + * Second index: cycle type — user [0] or kernel [1] (PROCESS_ENERGY_VALUES_CYCLE_TYPE_INDEX). + */ + ULONGLONG Cycles[ProcessEnergyValuesQoSMax][ProcessEnergyValuesCycleTypeMax]; + /** + * Energy consumed by disk I/O, in arbitrary energy units. + */ ULONGLONG DiskEnergy; + /** + * Tail energy attributed to network activity. + */ ULONGLONG NetworkTailEnergy; + /** + * Tail energy attributed to Mobile Broadband (MBB) activity. + */ ULONGLONG MBBTailEnergy; + /** + * Total bytes transmitted and received over network interfaces. + */ ULONGLONG NetworkTxRxBytes; + /** + * Total bytes transmitted and received over Mobile Broadband (MBB) interfaces. + */ ULONGLONG MBBTxRxBytes; union { + /** + * Activity state durations: [0] foreground, [1] desktop visible, [2] PSM foreground. + */ ENERGY_STATE_DURATION Durations[3]; struct { + /** + * Duration the process was in the foreground. + */ ENERGY_STATE_DURATION ForegroundDuration; + /** + * Duration the process was visible on the desktop. + */ ENERGY_STATE_DURATION DesktopVisibleDuration; + /** + * Duration the process was in the PSM (Process State Manager) foreground state. + */ ENERGY_STATE_DURATION PSMForegroundDuration; } DUMMYSTRUCTNAME; } DUMMYUNIONNAME; + /** + * Number of frames rendered by the DWM compositor on behalf of this process. + */ ULONG CompositionRendered; + /** + * Number of dirty regions generated by this process during DWM composition. + */ ULONG CompositionDirtyGenerated; + /** + * Number of dirty regions propagated from this process to other windows during DWM composition. + */ ULONG CompositionDirtyPropagated; ULONG Reserved1; - ULONGLONG AttributedCycles[4][2]; - ULONGLONG WorkOnBehalfCycles[4][2]; + /** + * CPU cycles attributed to this process (e.g. from work performed on its behalf). + * Indexed identically to Cycles: [QoS bucket][cycle type]. + */ + ULONGLONG AttributedCycles[ProcessEnergyValuesQoSMax][ProcessEnergyValuesCycleTypeMax]; + /** + * CPU cycles consumed while performing work on behalf of another process. + * Indexed identically to Cycles: [QoS bucket][cycle type]. + */ + ULONGLONG WorkOnBehalfCycles[ProcessEnergyValuesQoSMax][ProcessEnergyValuesCycleTypeMax]; } PROCESS_ENERGY_VALUES, *PPROCESS_ENERGY_VALUES; +/** + * \brief A compact activity timeline encoded as a bitmap with an end-time anchor. + * + * \details Each bit in the Bitmap field represents a fixed-size time slot. + * A set bit indicates the process was active during that slot. + * Each slot is 4096 milliseconds (≈4.1 seconds) in duration. + * The 32-bit bitmap covers approximately 131 seconds of recent history. + * EndTime is a slot index (not wall-clock seconds); multiply by 4096 to get elapsed milliseconds. + */ typedef union _TIMELINE_BITMAP { + /** Raw 64-bit value combining EndTime and Bitmap. */ ULONGLONG Value; struct { + /** + * The slot index of the most recent time slot represented by the bitmap. + * Real time ≈ EndTime * 4096 milliseconds. + */ ULONG EndTime; + /** + * Bit-mask of activity slots; bit 0 is the most recent slot. + * One set bit represents approximately 4.096 seconds of activity. + * popcount(Bitmap) * 4096 ms ≈ total active duration within window. + */ ULONG Bitmap; }; } TIMELINE_BITMAP, *PTIMELINE_BITMAP; +/** + * \brief Extended energy accounting values for a process, providing activity timelines + * and additional duration/input statistics not present in PROCESS_ENERGY_VALUES. + * + * \details Added in REDSTONE2; the Timelines array grew from 9 to 14 entries in REDSTONE3. + * The Durations union and the input/audio fields are REDSTONE3+. + */ typedef struct _PROCESS_ENERGY_VALUES_EXTENSION { union { + /** Activity timelines indexed by resource type (9 entries pre-RS3, 14 entries RS3+). */ TIMELINE_BITMAP Timelines[14]; // 9 for REDSTONE2, 14 for REDSTONE3/4/5 struct { + /** + * CPU activity timeline. + */ TIMELINE_BITMAP CpuTimeline; + /** + * Disk I/O activity timeline. + */ TIMELINE_BITMAP DiskTimeline; + /** + * Network activity timeline. + */ TIMELINE_BITMAP NetworkTimeline; + /** + * Mobile Broadband (MBB) activity timeline. + */ TIMELINE_BITMAP MBBTimeline; + /** + * Foreground visibility timeline. + */ TIMELINE_BITMAP ForegroundTimeline; + /** + * Desktop visible timeline. + */ TIMELINE_BITMAP DesktopVisibleTimeline; + /** + * DWM composition rendered timeline. + */ TIMELINE_BITMAP CompositionRenderedTimeline; + /** + * DWM composition dirty-generated timeline. + */ TIMELINE_BITMAP CompositionDirtyGeneratedTimeline; + /** + * DWM composition dirty-propagated timeline. + */ TIMELINE_BITMAP CompositionDirtyPropagatedTimeline; + /** + * Input activity timeline (REDSTONE3+). + */ TIMELINE_BITMAP InputTimeline; // REDSTONE3 + /** + * Audio input (microphone) activity timeline (REDSTONE3+). + */ TIMELINE_BITMAP AudioInTimeline; + /** + * Audio output (speaker/headphone) activity timeline (REDSTONE3+). + */ TIMELINE_BITMAP AudioOutTimeline; + /** + * Display-required (screen-on prevention) timeline (REDSTONE3+). + */ TIMELINE_BITMAP DisplayRequiredTimeline; + /** + * Keyboard input activity timeline (REDSTONE3+). + */ TIMELINE_BITMAP KeyboardInputTimeline; } DUMMYSTRUCTNAME; } DUMMYUNIONNAME; union // REDSTONE3 { + /** + * Activity state durations for extended resource types (REDSTONE3+). + */ ENERGY_STATE_DURATION Durations[5]; struct { + /** + * Duration the process received user input (REDSTONE3+). + */ ENERGY_STATE_DURATION InputDuration; + /** + * Duration the process used audio input (REDSTONE3+). + */ ENERGY_STATE_DURATION AudioInDuration; + /** + * Duration the process used audio output (REDSTONE3+). + */ ENERGY_STATE_DURATION AudioOutDuration; + /** + * Duration the process prevented display power-off (REDSTONE3+). + */ ENERGY_STATE_DURATION DisplayRequiredDuration; + /** + * Duration the process ran in PSM background state (REDSTONE3+). + */ ENERGY_STATE_DURATION PSMBackgroundDuration; } DUMMYSTRUCTNAME; } DUMMYUNIONNAME; + /** + * Number of keyboard input events attributed to the process (REDSTONE3+). + */ ULONG KeyboardInput; + /** + * Number of mouse input events attributed to the process (REDSTONE3+). + */ ULONG MouseInput; } PROCESS_ENERGY_VALUES_EXTENSION, *PPROCESS_ENERGY_VALUES_EXTENSION; @@ -4693,6 +5528,13 @@ typedef struct _PROCESS_EXTENDED_ENERGY_VALUES PROCESS_ENERGY_VALUES_EXTENSION Extension; } PROCESS_EXTENDED_ENERGY_VALUES, *PPROCESS_EXTENDED_ENERGY_VALUES; +typedef struct _PROCESS_EXTENDED_ENERGY_VALUES_V1 +{ + PROCESS_ENERGY_VALUES Base; + PROCESS_ENERGY_VALUES_EXTENSION Extension; + ULONG64 NpuWorkUnits; +} PROCESS_EXTENDED_ENERGY_VALUES_V1, *PPROCESS_EXTENDED_ENERGY_VALUES_V1; + // private typedef enum _SYSTEM_PROCESS_CLASSIFICATION { @@ -4704,29 +5546,139 @@ typedef enum _SYSTEM_PROCESS_CLASSIFICATION SystemProcessClassificationMaximum } SYSTEM_PROCESS_CLASSIFICATION; -// private +/** + * Extended process information appended to SYSTEM_PROCESS_INFORMATION in full process enumeration queries. + * + * \details This structure provides additional process accounting, classification, and energy metrics + * not present in the base SYSTEM_PROCESS_INFORMATION structure. It is returned when querying + * SystemFullProcessInformation (information class 148) or SystemExtendedProcessInformation (information class 57) + * via NtQuerySystemInformation. + * + * The structure is appended immediately after the SYSTEM_THREAD_INFORMATION array in + * SYSTEM_EXTENDED_PROCESS_INFORMATION, and the offsets are relative to the start of this extension structure. + * + * \since Windows 10 Threshold (version 1507, build 10240) + * + * \remarks This structure contains variable-length data. The UserSidOffset, PackageFullNameOffset, + * and AppIdOffset fields point to data stored immediately after this structure in memory. + * Callers must use these offsets to locate the actual strings and SID data. + */ typedef struct _SYSTEM_PROCESS_INFORMATION_EXTENSION { + /** + * Cumulative disk I/O counters for the process (reads, writes, flushes). + * Includes total bytes transferred and operation counts for read, write, and flush operations. + */ PROCESS_DISK_COUNTERS DiskCounters; + + /** + * Total number of context switches performed by all threads in the process since creation. + * Use this to measure scheduling overhead and CPU time-sharing behavior. + */ ULONGLONG ContextSwitches; + + /** + * Process classification flags and security attributes. + */ union { + /** + * Raw flags value containing all classification bits. + */ ULONG Flags; + struct { + /** + * If set, the process has a strong identity (e.g., packaged app with cryptographic signing). + * Strong identities are used for security policy enforcement and resource isolation. + */ ULONG HasStrongId : 1; + + /** + * Process classification type (SYSTEM_PROCESS_CLASSIFICATION). + * Indicates whether this is a normal user process, system process, secure system process, + * memory compression process, or registry process. Used by the kernel for resource + * management, security policy, and scheduling decisions. + */ ULONG Classification : 4; // SYSTEM_PROCESS_CLASSIFICATION + + /** + * If set, the process has had background activity moderation applied to it. + * The system may throttle CPU, I/O, or network resources when the process is not in the foreground. + * \since Windows 10 Redstone 2 (version 1703) + */ ULONG BackgroundActivityModerated : 1; + + /** + * Reserved for future use. + */ ULONG Spare : 26; } DUMMYSTRUCTNAME; } DUMMYUNIONNAME; + + /** + * Offset, in bytes, from the start of this structure to the user SID (Security Identifier). + * If zero, no user SID is available. The SID data is stored in standard binary format. + * Use this offset to locate the process owner's security identifier for access control + * and auditing purposes. + */ ULONG UserSidOffset; + + /** + * Offset, in bytes, from the start of this structure to a null-terminated WCHAR string + * containing the full package name (e.g., "Contoso.App_1.0.0.0_x64__8wekyb3d8bbwe"). + * If zero, the process is not packaged (classic Win32 application). + * \since Windows 10 Threshold (version 1507) + */ ULONG PackageFullNameOffset; // since THRESHOLD + + /** + * Detailed energy accounting values for the process, including CPU cycles, disk energy, + * network/MBB tail energy, DWM composition metrics, and activity state durations. + * Provides per-QoS-bucket breakdowns of energy consumption for foreground/background + * resource usage analysis. + * \since Windows 10 Threshold (version 1507) + */ PROCESS_ENERGY_VALUES EnergyValues; // since THRESHOLD + + /** + * Offset, in bytes, from the start of this structure to a null-terminated WCHAR string + * containing the Application User Model ID (AUMID) for packaged applications. + * If zero, the process does not have an AppId (either not packaged or not a UWP app). + * \since Windows 10 Threshold (version 1507) + */ ULONG AppIdOffset; // since THRESHOLD + + /** + * Number of bytes of committed memory shared between this process and other processes + * (e.g., memory-mapped sections, shared DLLs, or copy-on-write pages). + * Use this to measure memory overhead due to sharing and to calculate true private bytes. + * SharedCommitCharge + PrivatePageCount gives a more accurate picture of process memory usage. + * \since Windows 10 Threshold 2 (version 1511) + */ SIZE_T SharedCommitCharge; // since THRESHOLD2 + + /** + * Identifier of the job object to which the process belongs, if any. + * If zero, the process is not assigned to a job object. Job objects are used to group + * processes and apply resource limits, accounting, and management policies. + * \since Windows 10 Redstone (version 1607) + */ ULONG JobObjectId; // since REDSTONE + + /** + * Reserved for future use. + * \since Windows 10 Redstone (version 1607) + */ ULONG SpareUlong; // since REDSTONE + + /** + * Unique monotonically-increasing sequence number assigned when the process was created. + * Unlike ProcessId (which can be recycled), this value is never reused and provides + * a stable identifier for correlation across logs and telemetry even after process termination. + * \since Windows 10 Redstone (version 1607) + */ ULONGLONG ProcessSequenceNumber; } SYSTEM_PROCESS_INFORMATION_EXTENSION, *PSYSTEM_PROCESS_INFORMATION_EXTENSION; @@ -4744,6 +5696,19 @@ typedef struct _SYSTEM_KERNEL_DEBUGGER_INFORMATION_EX BOOLEAN DebuggerPresent; } SYSTEM_KERNEL_DEBUGGER_INFORMATION_EX, *PSYSTEM_KERNEL_DEBUGGER_INFORMATION_EX; +// rev +typedef struct _SYSTEM_BOOT_METADATA_INFORMATION +{ + ULONG Size; + UCHAR Data[1]; +} SYSTEM_BOOT_METADATA_INFORMATION, *PSYSTEM_BOOT_METADATA_INFORMATION; + +// rev +typedef struct _SYSTEM_SOFT_REBOOT_INFORMATION +{ + ULONG Flags; +} SYSTEM_SOFT_REBOOT_INFORMATION, *PSYSTEM_SOFT_REBOOT_INFORMATION; + // private typedef struct _SYSTEM_ELAM_CERTIFICATE_INFORMATION { @@ -4769,11 +5734,50 @@ typedef struct _OFFLINE_CRASHDUMP_CONFIGURATION_TABLE_V1 } OFFLINE_CRASHDUMP_CONFIGURATION_TABLE_V1, *POFFLINE_CRASHDUMP_CONFIGURATION_TABLE_V1; // SYSTEM_PROCESSOR_FEATURES_INFORMATION // ProcessorFeatureBits -#define KF_BRANCH 0x0000000000020000 -#define KF_XSTATE 0x0000000000800000 -#define KF_RDTSCP 0x0000000400000000 -#define KF_CET_SS 0x0000400000000000 -#define KF_XFD 0x0080000000000000 +// Processor feature bits (31 flags spanning bits 0-55 with documented gaps at bits 18-22) +// These flags indicate CPU capabilities detected by the kernel via CPUID and other detection mechanisms. +// Allocated bit ranges: +// Bits 0-17 : Base CPU features (MMX, SSE, branch prediction, etc.) - 18 flags +// Bits 18-22 : Reserved/unused (5 bit gap) +// Bits 23-31 : Extended states and additional features (1 flag) +// Bits 32-34 : Advanced features (RDRAND, SMAP, RDTSCP) - 3 flags +// Bits 35-44 : Reserved/unused (10 bit gap) +// Bits 45-46 : Huge pages and extended saves - 2 flags +// Bits 47-51 : Reserved/unused (5 bit gap) +// Bits 52-58 : Security and extended features (FPU_LEAKAGE, CAT, CET_SS, SSSE3, SSE4.x) - 7 flags +// Bits 59-62 : Reserved/unused (4 bit gap) +// Bit 63 : XFD (extended FPU data) - 1 flag +#define KF64_SMEP 0x0000000000000001ULL // Supervisor Mode Execution Protection +#define KF64_RDTSC 0x0000000000000002ULL // Read Time-Stamp Counter +#define KF64_CR4 0x0000000000000004ULL // CR4 Register Features +#define KF64_CMOV 0x0000000000000008ULL // Conditional Move Instructions +#define KF64_GLOBAL_PAGE 0x0000000000000010ULL // Global Pages Support +#define KF64_LARGE_PAGE 0x0000000000000020ULL // Large Page Support +#define KF64_MTRR 0x0000000000000040ULL // Memory Type Range Registers +#define KF64_CMPXCHG8B 0x0000000000000080ULL // CMPXCHG8B Instruction +#define KF64_MMX 0x0000000000000100ULL // MMX Instructions +#define KF64_DTS 0x0000000000000200ULL // Debug Store +#define KF64_PAT 0x0000000000000400ULL // Page Attribute Table +#define KF64_FXSR 0x0000000000000800ULL // FXSAVE and FXRSTOR Instructions +#define KF64_FAST_SYSCALL 0x0000000000001000ULL // Fast System Call +#define KF64_XMMI 0x0000000000002000ULL // Streaming SIMD Extensions +#define KF64_3DNOW 0x0000000000004000ULL // 3DNow! Instructions +#define KF64_AMDK6MTRR 0x0000000000008000ULL // AMD K6 Memory Type Range Registers +#define KF64_XMMI64 0x0000000000010000ULL // Streaming SIMD Extensions 2 +#define KF64_BRANCH 0x0000000000020000ULL // Branch Prediction +#define KF64_XSTATE 0x0000000000800000ULL // Extended States +#define KF64_RDRAND 0x0000000100000000ULL // RDRAND Instruction +#define KF64_SMAP 0x0000000200000000ULL // Supervisor Mode Access Prevention +#define KF64_RDTSCP 0x0000000400000000ULL // RDTSCP Instruction +#define KF64_HUGEPAGE 0x0000002000000000ULL // Huge Page Support +#define KF64_XSAVES 0x0000004000000000ULL // XSAVES and XRSTORS Instructions +#define KF64_FPU_LEAKAGE 0x0000020000000000ULL // FPU Data Leakage Mitigations +#define KF64_CAT 0x0000100000000000ULL // Cache Allocation Technology +#define KF64_CET_SS 0x0000400000000000ULL // Control-flow Enforcement Technology - Shadow Stack +#define KF64_SSSE3 0x0000800000000000ULL // Supplemental Streaming SIMD Extensions 3 +#define KF64_SSE4_1 0x0001000000000000ULL // Streaming SIMD Extensions 4.1 +#define KF64_SSE4_2 0x0002000000000000ULL // Streaming SIMD Extensions 4.2 +#define KF64_XFD 0x0080000000000000ULL // eXtended FPU Data // private typedef struct _SYSTEM_PROCESSOR_FEATURES_INFORMATION @@ -4782,10 +5786,57 @@ typedef struct _SYSTEM_PROCESSOR_FEATURES_INFORMATION ULONGLONG Reserved[3]; } SYSTEM_PROCESSOR_FEATURES_INFORMATION, *PSYSTEM_PROCESSOR_FEATURES_INFORMATION; +// EDID v1.4 detailed timing descriptor (18 bytes) +typedef struct _SYSTEM_EDID_DETAILED_TIMING_DESCRIPTOR +{ + USHORT PixelClock; // Pixel clock in 10 kHz units + UCHAR HorizontalActiveLo; // Horizontal active pixels (low 8 bits) + UCHAR HorizontalBlankLo; // Horizontal blanking pixels (low 8 bits) + UCHAR HorizontalActiveBlankHi; // High bits for horizontal active/blanking + UCHAR VerticalActiveLo; // Vertical active lines (low 8 bits) + UCHAR VerticalBlankLo; // Vertical blanking lines (low 8 bits) + UCHAR VerticalActiveBlankHi; // High bits for vertical active/blanking + UCHAR HorizontalSyncOffsetLo;// Horizontal sync offset (low 8 bits) + UCHAR HorizontalSyncPulseWidthLo; // Horizontal sync pulse width (low 8 bits) + UCHAR VerticalSyncOffsetPulseWidthLo; // Vertical sync offset/pulse width (low 4 bits each) + UCHAR SyncOffsetPulseWidthHi; // High bits for sync offset/pulse width + UCHAR HorizontalImageSizeLo; // Horizontal image size in mm (low 8 bits) + UCHAR VerticalImageSizeLo; // Vertical image size in mm (low 8 bits) + UCHAR ImageSizeHi; // High bits for image size + UCHAR HorizontalBorder; // Horizontal border in pixels + UCHAR VerticalBorder; // Vertical border in lines + UCHAR Flags; // Flags (interlaced, stereo, sync, etc.) +} SYSTEM_EDID_DETAILED_TIMING_DESCRIPTOR, *PSYSTEM_EDID_DETAILED_TIMING_DESCRIPTOR; + // EDID v1.4 standard data format typedef struct _SYSTEM_EDID_INFORMATION { - UCHAR Edid[128]; + union + { + UCHAR Edid[128]; + struct + { + UCHAR Header[8]; // 00h: EDID header (00 FF FF FF FF FF FF 00) + UCHAR ManufacturerId[2]; // 08h: Manufacturer ID (big endian) + UCHAR ProductCode[2]; // 0Ah: Product code (little endian) + UCHAR SerialNumber[4]; // 0Ch: Serial number + UCHAR WeekOfManufacture; // 10h: Week of manufacture + UCHAR YearOfManufacture; // 11h: Year of manufacture (offset from 1990) + UCHAR EdidVersion; // 12h: EDID version (should be 1) + UCHAR EdidRevision; // 13h: EDID revision (should be 4) + UCHAR VideoInputDefinition; // 14h: Video input parameters + UCHAR MaxHorizontalImageSize; // 15h: Max horizontal image size (cm) + UCHAR MaxVerticalImageSize; // 16h: Max vertical image size (cm) + UCHAR DisplayGamma; // 17h: Display gamma (gamma*100 - 100) + UCHAR FeatureSupport; // 18h: DPMS features, color encoding, etc. + UCHAR Chromaticity[10]; // 19h: Chromaticity coordinates + UCHAR EstablishedTimings[3]; // 23h: Established timings + UCHAR StandardTimings[16]; // 26h: Standard timings (8x2 bytes) + SYSTEM_EDID_DETAILED_TIMING_DESCRIPTOR DetailedTiming[4]; // 36h: 4 detailed timing descriptors (18 bytes each) + UCHAR ExtensionFlag; // 7Eh: Number of (optional) 128-byte extension blocks + UCHAR Checksum; // 7Fh: Checksum (sum of all 128 bytes = 0) + }; + }; } SYSTEM_EDID_INFORMATION, *PSYSTEM_EDID_INFORMATION; // private @@ -4819,6 +5870,44 @@ typedef struct _SYSTEM_HYPERVISOR_DETAIL_INFORMATION HV_DETAILS ImplementationLimits; } SYSTEM_HYPERVISOR_DETAIL_INFORMATION, *PSYSTEM_HYPERVISOR_DETAIL_INFORMATION; +/** + * The SYSTEM_PROCESSOR_CYCLE_STATS_BUCKET_INDEX type represents a frequency bucket + * for processor cycle statistics, selected by PoGetFrequencyBucket based on the current + * processor frequency relative to thresholds in _KPRCB.PowerState.FrequencyBucketThresholds. + */ +typedef enum _SYSTEM_PROCESSOR_CYCLE_STATS_BUCKET_INDEX +{ + // Lowest frequency bucket — processor running at or below the first frequency threshold. + SystemProcessorCycleStatsBucketLowestFrequency = 0, + // Low frequency bucket — processor running between the first and second frequency thresholds. + SystemProcessorCycleStatsBucketLowFrequency = 1, + // High frequency bucket — processor running between the second and third frequency thresholds. + SystemProcessorCycleStatsBucketHighFrequency = 2, + // Highest frequency bucket — processor running above the third frequency threshold. + SystemProcessorCycleStatsBucketHighestFrequency = 3, + // The maximum number of frequency buckets. + SystemProcessorCycleStatsBucketMax = 4 +} SYSTEM_PROCESSOR_CYCLE_STATS_BUCKET_INDEX, *PSYSTEM_PROCESSOR_CYCLE_STATS_BUCKET_INDEX; + +/** + * The SYSTEM_PROCESSOR_CYCLE_STATS_EFFICIENCY_CLASS_INDEX type represents the baseline architectural-efficiency group. + * + * \note In current kernel accounting this is effectively binary grouping (0/1), not an open-ended N-class index. + * So think of it as Group A vs Group B for heterogeneity tracking. + * It is not guaranteed to mean exactly “P-core vs E-core” on every platform, even though that may often correlate. + */ +typedef enum _SYSTEM_PROCESSOR_CYCLE_STATS_EFFICIENCY_CLASS_INDEX +{ + // Represents the baseline architectural-efficiency group (the group with the minimum class value in current kernel logic) + // Baseline efficiency-class group (minimum architectural efficiency class). + SystemProcessorCycleStatsEfficiencyClassPrimary = 0, + // Represents processors not in that baseline group (all non-min class values are folded into this second bucket) + // Non-baseline efficiency-class group (all other architectural efficiency classes). + SystemProcessorCycleStatsEfficiencyClassSecondary = 1, + // The current maximum number of architectural-efficiency classes (subject to change). + SystemProcessorCycleStatsEfficiencyClassMax = 2 +} SYSTEM_PROCESSOR_CYCLE_STATS_EFFICIENCY_CLASS_INDEX, *PSYSTEM_PROCESSOR_CYCLE_STATS_EFFICIENCY_CLASS_INDEX; + // private typedef struct _SYSTEM_PROCESSOR_CYCLE_STATS_INFORMATION { @@ -4830,7 +5919,7 @@ typedef struct _SYSTEM_PROCESSOR_CYCLE_STATS_INFORMATION // dependent KeHeteroSystem and using _KPRCB.PowerState.EarlyBootArchitecturalEfficiencyClass // instead, when appropriate. // - ULONGLONG Cycles[4][2]; + ULONGLONG Cycles[SystemProcessorCycleStatsBucketMax][SystemProcessorCycleStatsEfficiencyClassMax]; } SYSTEM_PROCESSOR_CYCLE_STATS_INFORMATION, *PSYSTEM_PROCESSOR_CYCLE_STATS_INFORMATION; // private @@ -4875,66 +5964,137 @@ typedef struct _SYSTEM_KERNEL_DEBUGGER_FLAGS #define CODEINTEGRITYPOLICY_HVCIOPTION_DEBUG 0x04 // private +/** + * \brief Code Integrity Policy configuration and HVCI (Hypervisor-enforced Code Integrity) settings. + * + * Contains the kernel's code integrity policy enforcement options and Hardware-enforced Code Integrity (HVCI) + * configuration state. Enables applications to query the security posture of code integrity enforcement and + * virtualization-based security features. Available via NtQuerySystemInformation(SystemCodeIntegrityInformation). + * + * \since Windows 10 + */ typedef struct _SYSTEM_CODEINTEGRITYPOLICY_INFORMATION { + /** + * \brief Code integrity policy options (Options union). + * + * Union providing both raw 32-bit access and bitfield access to policy flags: + * - Enabled: Code integrity enforcement is active + * - Audit: Code integrity operates in audit mode (violations logged, not blocked) + * - RequireWHQL: Windows Hardware Quality Labs certification required for drivers + * - DisabledFlightSigning: Flight-signed binaries are blocked from loading + * - EnabledUMCI: User-mode Code Integrity enforcement enabled (signed DLL requirement) + * - EnabledUpdatePolicyNoReboot: Code integrity policy updates without system reboot + * - EnabledSecureSettingPolicy: Secure settings policy enforcement enabled + * - EnabledUnsignedSystemIntegrityPolicy: Unsigned system integrity policies allowed + * - DynamicCodePolicyEnabled: Dynamic code generation and modification is restricted + * - Spare: 19 reserved bits for future expansion + * - ReloadPolicyNoReboot: Policy reloaded without reboot (bit 28) + * - ConditionalLockdown: Conditional code integrity lockdown mode (bit 29) + * - NoLockdown: Code integrity lockdown is not active (bit 30) + * - Lockdown: Code integrity lockdown mode is enforced (bit 31) + */ union { ULONG Options; struct { - ULONG Enabled : 1; - ULONG Audit : 1; - ULONG RequireWHQL : 1; - ULONG DisabledFlightSigning : 1; - ULONG EnabledUMCI : 1; - ULONG EnabledUpdatePolicyNoReboot : 1; - ULONG EnabledSecureSettingPolicy : 1; - ULONG EnabledUnsignedSystemIntegrityPolicy : 1; - ULONG DynamicCodePolicyEnabled : 1; - ULONG Spare : 19; - ULONG ReloadPolicyNoReboot : 1; - ULONG ConditionalLockdown : 1; - ULONG NoLockdown : 1; - ULONG Lockdown : 1; + ULONG Enabled : 1; ///< Code integrity enforcement enabled + ULONG Audit : 1; ///< Audit mode (log violations, don't block) + ULONG RequireWHQL : 1; ///< Require WHQL certification + ULONG DisabledFlightSigning : 1; ///< Block flight-signed binaries + ULONG EnabledUMCI : 1; ///< User-mode code integrity enabled + ULONG EnabledUpdatePolicyNoReboot : 1; ///< Update policy without reboot + ULONG EnabledSecureSettingPolicy : 1; ///< Secure settings policy active + ULONG EnabledUnsignedSystemIntegrityPolicy : 1; ///< Allow unsigned system integrity policies + ULONG DynamicCodePolicyEnabled : 1; ///< Restrict dynamic code/JIT + ULONG Spare : 19; ///< Reserved for future use + ULONG ReloadPolicyNoReboot : 1; ///< Policy reloaded without reboot + ULONG ConditionalLockdown : 1; ///< Conditional lockdown mode + ULONG NoLockdown : 1; ///< Lockdown not enforced + ULONG Lockdown : 1; ///< Lockdown mode enforced } DUMMYSTRUCTNAME; } DUMMYUNIONNAME; + /** + * \brief Hardware-enforced Code Integrity (HVCI) options. + * + * Union providing both raw access and bitfield access to HVCI/VBS configuration: + * - HVCIEnabled: HVCI is active (code integrity enforcement via hypervisor) + * - HVCIStrict: Strict mode enforcement (higher security, lower performance) + * - HVCIDebug: Debug mode enabled (diagnostic/troubleshooting) + * - HVCISpare: 29 reserved bits for future HVCI expansion + */ union { ULONG HVCIOptions; struct { - ULONG HVCIEnabled : 1; - ULONG HVCIStrict : 1; - ULONG HVCIDebug : 1; - ULONG HVCISpare : 29; + ULONG HVCIEnabled : 1; ///< HVCI enforced by hypervisor + ULONG HVCIStrict : 1; ///< Strict HVCI mode enforcement + ULONG HVCIDebug : 1; ///< HVCI debug mode active + ULONG HVCISpare : 29; ///< Reserved for future use } DUMMYSTRUCTNAME; } DUMMYUNIONNAME; + /** + * \brief Code integrity policy version. + * + * Version number incremented when the kernel reloads/updates the code integrity policy. + * Used to detect policy changes without requiring system restart. + */ ULONGLONG Version; + /** + * \brief Code integrity policy GUID. + * + * Uniquely identifies the loaded code integrity policy file. Changes when a different + * policy becomes active; can be used to correlate policy audit logs. + */ GUID PolicyGuid; } SYSTEM_CODEINTEGRITYPOLICY_INFORMATION, *PSYSTEM_CODEINTEGRITYPOLICY_INFORMATION; // private +/** + * \brief Isolated User Mode (IUM) and virtualization-based security (VBS) status. + * + * Queries the state of Virtualization-Based Security (VBS) infrastructure, including Hyper-V Code Integrity (HVCI), + * Secure Kernel, trustlets, and hardware-enforced security features. Enables applications to detect when running + * in a hardened security posture and to determine available cryptographic protections. + * Available via NtQuerySystemInformation(SystemIsolatedUserModeInformation). + * + * \since Windows 10 (RS2+) + */ 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 HardwareEnforcedVbs : 1; - BOOLEAN NoSecrets : 1; - BOOLEAN EncryptionKeyPersistent : 1; - BOOLEAN HardwareEnforcedHvpt : 1; - BOOLEAN HardwareHvptAvailable : 1; - BOOLEAN SpareFlags2 : 1; - BOOLEAN Spare0[6]; - ULONGLONG Spare1; + ///< \brief Virtualization-based Security core status (byte 0): + BOOLEAN SecureKernelRunning : 1; ///< Secure Kernel (hypervisor-based isolation) is active + BOOLEAN HvciEnabled : 1; ///< Hypervisor-enforced Code Integrity enabled + BOOLEAN HvciStrictMode : 1; ///< HVCI in strict enforcement mode + BOOLEAN DebugEnabled : 1; ///< Kernel debugger enabled (may weaken security) + BOOLEAN FirmwarePageProtection : 1; ///< UEFI Secure Boot firmware page protection active + BOOLEAN EncryptionKeyAvailable : 1; ///< Isolation-backed encryption key available from Secure Kernel + BOOLEAN SpareFlags : 2; ///< Reserved for future VBS flags (bits 6-7) + + ///< \brief Isolated execution and security features (byte 1): + BOOLEAN TrustletRunning : 1; ///< Trustlet (isolated edge function) is running + BOOLEAN HvciDisableAllowed : 1; ///< HVCI can be disabled without reboot (policy-driven) + BOOLEAN HardwareEnforcedVbs : 1; ///< VBS enforced by processor/platform (e.g., AMD SME, Intel TXT) + BOOLEAN NoSecrets : 1; ///< No cryptographic secrets loaded in isolated user mode + BOOLEAN EncryptionKeyPersistent : 1; ///< Encryption key persists across reboots + BOOLEAN HardwareEnforcedHvpt : 1; ///< Hardware enforces Hypervisor Page Table (HVPT) isolation + BOOLEAN HardwareHvptAvailable : 1; ///< CPU supports hardware-enforced HVPT (architectural feature) + BOOLEAN SpareFlags2 : 1; ///< Reserved for future feature flag (bit 15) + BOOLEAN EncryptionKeyTpmBound : 1; ///< Encryption key bound to TPM (Trusted Platform Module) + + ///< \brief Reserved for future expansion (binary compatibility): + BOOLEAN Spare0[5]; ///< Reserved bytes for future isolated user mode flags + ULONGLONG Spare1; ///< Reserved 8 bytes for future isolated user mode expansion } SYSTEM_ISOLATED_USER_MODE_INFORMATION, *PSYSTEM_ISOLATED_USER_MODE_INFORMATION; +// private +typedef struct _SYSTEM_HARDWARE_SECURITY_TEST_INTERFACE_RESULTS_INFORMATION +{ + UCHAR Results[1]; +} SYSTEM_HARDWARE_SECURITY_TEST_INTERFACE_RESULTS_INFORMATION, *PSYSTEM_HARDWARE_SECURITY_TEST_INTERFACE_RESULTS_INFORMATION; + // private typedef struct _SYSTEM_SINGLE_MODULE_INFORMATION { @@ -5057,6 +6217,9 @@ typedef struct _SYSTEM_SUPPORTED_PROCESSOR_ARCHITECTURES_INFORMATION #endif // NTDDI_WIN10_FE // private +/** + * The SYSTEM_MEMORY_USAGE_INFORMATION structure contains information about the memory usage of the system. + */ typedef struct _SYSTEM_MEMORY_USAGE_INFORMATION { ULONGLONG TotalPhysicalBytes; @@ -5068,28 +6231,80 @@ typedef struct _SYSTEM_MEMORY_USAGE_INFORMATION ULONGLONG PeakCommitmentBytes; } SYSTEM_MEMORY_USAGE_INFORMATION, *PSYSTEM_MEMORY_USAGE_INFORMATION; -// private +// rev +/** + * The SYSTEM_CODEINTEGRITY_IMAGE_TYPE constant is used for validating user-mode images (EXE/DLL). + */ +typedef enum _SYSTEM_CODEINTEGRITY_IMAGE_TYPE +{ + SystemCodeIntegrityImageTypeUser, + SystemCodeIntegrityImageTypeKernel, + SystemCodeIntegrityImageTypeBoot +} SYSTEM_CODEINTEGRITY_IMAGE_TYPE; + +/** + * The SYSTEM_CODEINTEGRITY_IMAGE_TYPE_USER constant is used for validating user-mode images (EXE/DLL). + * + * Validation includes: + * - Digital signature + * - User-mode certificate chain validity. + * - Compliance policies for user-mode binaries. + */ +#define SYSTEM_CODEINTEGRITY_IMAGE_TYPE_USER 0 + +/** + * The SYSTEM_CODEINTEGRITY_IMAGE_TYPE_KERNEL constant is used for validating kernel-mode images (SYS/Native). + * + * Validation includes: + * - Signed by a trusted certificate authority (or cross-signed). + * - Compliance policies for kernel-mode binaries. + */ +#define SYSTEM_CODEINTEGRITY_IMAGE_TYPE_KERNEL 1 + +/** + * The SYSTEM_CODEINTEGRITY_IMAGE_TYPE_BOOT constant is used for validating boot-critical images (SYS/Native). + * + * Validation includes: + * - Signed only by Microsoft. + * - Compliance policies for boot-critical binaries (Strict WHQL, Secure Boot requirements). + */ +#define SYSTEM_CODEINTEGRITY_IMAGE_TYPE_BOOT 2 + +/** + * The SYSTEM_CODEINTEGRITY_CERTIFICATE_INFORMATION structure contains information to validate the integrity of an image. + * + * \note The return status of NtQuerySystemInformation indicates the result of the code integrity validation as determined by the type specified. + */ typedef struct _SYSTEM_CODEINTEGRITY_CERTIFICATE_INFORMATION { - HANDLE ImageFile; - ULONG Type; // REDSTONE4 + HANDLE ImageFile; // in: Handle to a file or image to validate. + ULONG Type; // in: The type of code integrity policy. // REDSTONE4 } SYSTEM_CODEINTEGRITY_CERTIFICATE_INFORMATION, *PSYSTEM_CODEINTEGRITY_CERTIFICATE_INFORMATION; -// private +/** + * The SYSTEM_PHYSICAL_MEMORY_INFORMATION structure retrieves the physical memory layout of the system. + * + * \remarks The addresses are physical, not virtual. + */ typedef struct _SYSTEM_PHYSICAL_MEMORY_INFORMATION { - ULONGLONG TotalPhysicalBytes; - ULONGLONG LowestPhysicalAddress; - ULONGLONG HighestPhysicalAddress; + ULONGLONG TotalPhysicalBytes; // Total amount of physical RAM present, in bytes. + ULONGLONG LowestPhysicalAddress; // Lowest accessible physical address (byte address). + ULONGLONG HighestPhysicalAddress; // Highest accessible physical address (byte address, inclusive). } SYSTEM_PHYSICAL_MEMORY_INFORMATION, *PSYSTEM_PHYSICAL_MEMORY_INFORMATION; -// private +/** + * The SYSTEM_ACTIVITY_MODERATION_STATE type contains the moderation state applied to an application, + * with respect to background throttling, resource reduction, and related heuristics. + * + * \remarks The state may be assigned automatically by the system or explicitly overridden by the user. + */ typedef enum _SYSTEM_ACTIVITY_MODERATION_STATE { - SystemActivityModerationStateSystemManaged, - SystemActivityModerationStateUserManagedAllowThrottling, - SystemActivityModerationStateUserManagedDisableThrottling, - MaxSystemActivityModerationState + SystemActivityModerationStateSystemManaged, // The system applies heuristics based on the appropriate moderation behavior. + SystemActivityModerationStateUserManagedAllowThrottling, // User allows the system to throttle the application. + SystemActivityModerationStateUserManagedDisableThrottling, // User disables throttling for the application. + MaxSystemActivityModerationState // Upper bound for validation; not a real state. } SYSTEM_ACTIVITY_MODERATION_STATE; // private - REDSTONE2 @@ -5115,23 +6330,80 @@ typedef struct _SYSTEM_ACTIVITY_MODERATION_INFO } SYSTEM_ACTIVITY_MODERATION_INFO, *PSYSTEM_ACTIVITY_MODERATION_INFO; // rev -#include +/** + * The SYSTEM_ACTIVITY_MODERATION_APP_SETTINGS structure describes the moderation state + * and classification of an application as used by the system's activity moderation framework. + * These settings influence how aggressively the system may throttle, defer, or + * suppress certain background activities for the application. + * + * The structure maintains a stable binary layout because it is stored in + * serialized policy blobs and consumed by system components that expect + * fixed field offsets. + */ typedef struct _SYSTEM_ACTIVITY_MODERATION_APP_SETTINGS { - LARGE_INTEGER LastUpdatedTime; // QuerySystemTime - SYSTEM_ACTIVITY_MODERATION_STATE ModerationState; - UCHAR Reserved[4]; - SYSTEM_ACTIVITY_MODERATION_APP_TYPE AppType; - UCHAR Flags[4]; + LARGE_INTEGER LastUpdatedTime; // Timestamp of the last update to this settings block. + SYSTEM_ACTIVITY_MODERATION_STATE ModerationState; // Current moderation state assigned to the application. + UCHAR Reserved[4]; // Reserved for future expansion + SYSTEM_ACTIVITY_MODERATION_APP_TYPE AppType; // Current application type for moderation purposes. + ULONG Flags; // Additional moderation flags. } SYSTEM_ACTIVITY_MODERATION_APP_SETTINGS, *PSYSTEM_ACTIVITY_MODERATION_APP_SETTINGS; -#include -// private +/** + * The SYSTEM_ACTIVITY_MODERATION_USER_SETTINGS structure provides the activity-moderation + * registry location where moderation policies or overrides may be stored. + */ typedef struct _SYSTEM_ACTIVITY_MODERATION_USER_SETTINGS { - HANDLE UserKeyHandle; + HANDLE UserKeyHandle; // Handle to the user registry key for activity moderation settings. } SYSTEM_ACTIVITY_MODERATION_USER_SETTINGS, *PSYSTEM_ACTIVITY_MODERATION_USER_SETTINGS; +/** + * The SYSTEM_CODEINTEGRITY_UNLOCK_INFORMATION structure contains Code Integrity unlock state and validation token. + * + * **Purpose:** + * + * The UnlockId field is a 32-byte cryptographic validation token used to authenticate requests to temporarily + * disable Code Integrity (CI) enforcement. It works in conjunction with the three flag bits (Locked, UnlockApplied, UnlockIdValid) + * to control the application of code integrity bypass authorization. + * + * **Mechanism:** + * + * \b Token \b Generation: When needing to disable CI, a component (bootloader, recovery environment, or factory process) + * computes a 32-byte UnlockId using: + * - HMAC-SHA256 or similar cryptographic hash function + * - A kernel-embedded or TPM-stored secret key + * - Machine-specific data (boot state, firmware version, hardware configuration, etc.) + * + * \b Validation: The kernel validates the UnlockId by: + * - Recomputing the expected HMAC-SHA256 using its stored secret and machine state + * - Comparing against the provided UnlockId (32-byte comparison) + * - Setting the UnlockIdValid flag if the cryptographic match succeeds + * - Rejecting any token that fails validation + * + * \b Application: Once validated: + * - UnlockApplied flag is set (unlock request accepted by the kernel) + * - Locked flag may be cleared (CI enforcement disabled for this session) + * - Temporary bypass of code integrity checks is granted for authorized operations + * + * **Security Properties:** + * + * - \b 256-bit \b Token: The 32-byte (256-bit) size is standard for HMAC-SHA256 output, providing strong cryptographic security + * - \b Microsoft-Controlled \b Secret: UnlockId tokens are derived from a Microsoft-controlled secret key, preventing unauthorized bypasses + * - \b Machine \b Binding: Machine-specific data ensures tokens are valid only for the intended system + * - \b Temporal \b Scope: Unlock is session-scoped and typically used during controlled recovery or factory processes + * + * **Use Cases:** + * + * - \b Factory \b Reset (OOBE): Allow boot in non-secure mode during device initial setup and provisioning + * - \b Recovery \b Environment: Enable recovery tools to bypass CI during authorized system repairs + * - \b Secure \b Boot \b Bypass: Controlled disabling of code verification during authorized recovery scenarios + * - \b Development/Debugging: Microsoft-signed tokens for internal kernel validation and testing on development systems + * + * \note The UnlockId prevents unauthorized bypasses of code integrity protection and is only trusted after cryptographic validation succeeds. + * \note This structure is private to the kernel and not part of the public API. + * \note Available since Windows Redstone 4 (Windows 10 version 1803). + */ // private typedef struct _SYSTEM_CODEINTEGRITY_UNLOCK_INFORMATION { @@ -5140,21 +6412,87 @@ typedef struct _SYSTEM_CODEINTEGRITY_UNLOCK_INFORMATION ULONG Flags; struct { + /** \brief Code Integrity is currently locked (enforced). + * + * When set (1), Code Integrity enforcement is active and code execution restrictions are applied. + * When clear (0), Code Integrity may be disabled if UnlockApplied is set and a valid token was provided. + */ ULONG Locked : 1; - ULONG UnlockApplied : 1; // Unlockable field removed 19H1 + + /** \brief Unlock request has been validated and applied. + * + * Set by the kernel when the provided UnlockId passes cryptographic validation and the unlock is authorized. + * When set, this flag indicates that CI enforcement has been temporarily disabled for this session. + * Field removed after Windows 10 v1909 (19H1) in newer releases. + */ + ULONG UnlockApplied : 1; + + /** \brief UnlockId contains a valid, authenticated cryptographic token. + * + * Set by the kernel when the provided UnlockId passes HMAC-SHA256 validation against the kernel's stored secret. + * This flag indicates that the token is cryptographically valid and can authorize CI bypass. + */ ULONG UnlockIdValid : 1; + + /** \brief Reserved flag bits for future use. */ ULONG Reserved : 29; }; }; - UCHAR UnlockId[32]; // REDSTONE4 + + /** \brief 32-byte cryptographic validation token for Code Integrity unlock requests. + * + * This HMAC-SHA256 token authorizes temporary disabling of Code Integrity enforcement. + * The token is computed using a kernel-embedded secret key, machine-specific data, and cryptographic derivation. + * + * **Format:** + * - Size: 32 bytes (256 bits) + * - Algorithm: HMAC-SHA256 + * - Derivation: Microsoft-controlled secret key + machine state + * - Validation: Kernel verifies token before granting CI bypass + * + * **Validation Process:** + * 1. Kernel recomputes expected HMAC-SHA256 from stored secret and current machine state + * 2. Compares computed HMAC against the provided UnlockId (byte-for-byte) + * 3. Sets UnlockIdValid flag if match succeeds; fails otherwise + * 4. If validation succeeds, kernel sets UnlockApplied and may clear Locked flag + * + * **Authorization Scenarios:** + * - Factory Reset (OOBE): Token allows non-secure boot during device provisioning + * - Recovery Mode: Token allows recovery environment to bypass code verification checks + * - Development/Debug: Microsoft-signed tokens for test systems and kernel development + * + * \note Available since Windows 10 Redstone 4 (version 1803, NTDDI_WIN10_RS4). + */ + UCHAR UnlockId[32]; } SYSTEM_CODEINTEGRITY_UNLOCK_INFORMATION, *PSYSTEM_CODEINTEGRITY_UNLOCK_INFORMATION; // private typedef struct _SYSTEM_FLUSH_INFORMATION { - ULONG SupportedFlushMethods; + union + { + ULONG SupportedFlushMethods; + struct + { + ULONG MethodAlwaysPresent : 1; // 0x1 + ULONG MethodProcessorFeatureBit35 : 1; // 0x2 + ULONG MethodProcessorFeatureBit36 : 1; // 0x4 + ULONG ReservedMethods : 29; + } DUMMYSTRUCTNAME; + } DUMMYUNIONNAME; + ULONG ProcessorCacheFlushSize; - ULONGLONG SystemFlushCapabilities; + + union + { + ULONGLONG SystemFlushCapabilities; + struct + { + ULONGLONG NfitType7FlushCapable : 1; // 0x1 + ULONGLONG ReservedCapabilities : 63; + } DUMMYSTRUCTNAME; + } DUMMYUNIONNAME; + ULONGLONG Reserved[2]; } SYSTEM_FLUSH_INFORMATION, *PSYSTEM_FLUSH_INFORMATION; @@ -5188,24 +6526,86 @@ typedef struct _SYSTEM_KERNEL_VA_SHADOW_INFORMATION } SYSTEM_KERNEL_VA_SHADOW_INFORMATION, *PSYSTEM_KERNEL_VA_SHADOW_INFORMATION; // private +/** + * The SYSTEM_CODEINTEGRITYVERIFICATION_INFORMATION structure contains information + * required for code integrity verification of an image. + * + * Two verification modes are supported: + * - File-backed: supply a non-null FileHandle (handle to an open file); Image and ImageSize are ignored. + * - Memory-backed: supply a null FileHandle, set Image to the base address of a mapped/loaded PE image + * in memory, and ImageSize to its size in bytes. The kernel reads image content directly from the buffer. + */ typedef struct _SYSTEM_CODEINTEGRITYVERIFICATION_INFORMATION { - HANDLE FileHandle; - ULONG ImageSize; - PVOID Image; + HANDLE FileHandle; // Handle to an open file for file-backed verification, or NULL for memory-backed verification. + ULONG ImageSize; // Size in bytes of the image buffer; used only when FileHandle is NULL. + PVOID Image; // Base address of the PE image buffer for memory-backed verification; ignored when FileHandle is non-null. } SYSTEM_CODEINTEGRITYVERIFICATION_INFORMATION, *PSYSTEM_CODEINTEGRITYVERIFICATION_INFORMATION; // rev +/** + * The SYSTEM_HYPERVISOR_USER_SHARED_DATA structure contains information shared with the hypervisor and user-mode. + * + * This structure is populated by the hypervisor (when present) to allow user-mode components to perform + * high-resolution time calculations without requiring a hypercall or kernel transition. + */ typedef struct _SYSTEM_HYPERVISOR_USER_SHARED_DATA { - ULONGLONG TimeUpdateLock; // QpcSystemTimeIncrement? - volatile ULONGLONG QpcMultiplier; - volatile ULONGLONG QpcBias; // HvlGetQpcBias + /** + * Lock used to synchronize updates to the timing fields. + * + * The hypervisor increments this value before and after updating the + * QPC multiplier and bias. User-mode callers can sample this value + * before and after reading the timing fields to detect whether an + * update occurred mid-read and retry if necessary. + */ + volatile ULONG TimeUpdateLock; + + /** + * Reserved field - The hypervisor does not assign this field. + */ + ULONG Reserved0; + + /** + * Multiplier used to convert hypervisor QPC ticks to host time. + * + * This value is applied to the hypervisor's virtualized performance + * counter to compute a stable, high-resolution timebase. The multiplier + * is chosen by the hypervisor based on the underlying hardware timer + * source and virtualization mode. + */ + ULONGLONG QpcMultiplier; + + /** + * Bias applied after QPC multiplication to produce final time. + * + * The hypervisor uses this bias to align the virtualized QPC value with + * the host's notion of system time. Combined with QpcMultiplier, this + * allows user-mode components to compute consistent time values even + * under virtualization. + */ + ULONGLONG QpcBias; } SYSTEM_HYPERVISOR_USER_SHARED_DATA, *PSYSTEM_HYPERVISOR_USER_SHARED_DATA; -// private +/** + * The SYSTEM_HYPERVISOR_SHARED_PAGE_INFORMATION structure describes + * the user-mode mapping of the hypervisor shared page. + * + * This structure provides the virtual address at which the hypervisor's + * user-accessible shared data page is mapped. When a hypervisor is present, + * the kernel maps a read-only page into user mode containing timing and + * virtualization-related information (see SYSTEM_HYPERVISOR_USER_SHARED_DATA). + * + * User-mode components can read this page directly to obtain high-resolution + * time conversion parameters or other hypervisor-provided data without + * requiring a hypercall or kernel transition. + */ typedef struct _SYSTEM_HYPERVISOR_SHARED_PAGE_INFORMATION { + /** + * User-mode virtual address of the hypervisor shared data page. + * If no hypervisor is present, this pointer is NULL. + */ PSYSTEM_HYPERVISOR_USER_SHARED_DATA HypervisorSharedUserVa; } SYSTEM_HYPERVISOR_SHARED_PAGE_INFORMATION, *PSYSTEM_HYPERVISOR_SHARED_PAGE_INFORMATION; @@ -5348,6 +6748,18 @@ typedef struct _SYSTEM_FIRMWARE_RAMDISK_INFORMATION SIZE_T Size; } SYSTEM_FIRMWARE_RAMDISK_INFORMATION, *PSYSTEM_FIRMWARE_RAMDISK_INFORMATION; +// rev +typedef struct _SYSTEM_WHEA_IPMI_HARDWARE_INFORMATION +{ + ULONGLONG RecordId; + UCHAR EventType; + UCHAR SensorType; + USHORT GeneratorId; + UCHAR EvmRevision; + UCHAR RecordType; + UCHAR Data[4]; +} SYSTEM_WHEA_IPMI_HARDWARE_INFORMATION, *PSYSTEM_WHEA_IPMI_HARDWARE_INFORMATION; + // private typedef struct _SYSTEM_SHADOW_STACK_INFORMATION { @@ -5505,19 +6917,32 @@ typedef struct _SYSTEM_POINTER_AUTH_INFORMATION }; } SYSTEM_POINTER_AUTH_INFORMATION, *PSYSTEM_POINTER_AUTH_INFORMATION; -// private +// rev +#define SYSTEM_ORIGINAL_IMAGE_FEATURE_INFORMATION_VERSION 1 // Current protocol version for input/output structures. + +/** + * Query interface for checking whether a named Windows feature flag is enabled for an image's + * "born-on" Windows version — the OS version the image was originally built or linked against. + * In observed logic, the decision is based on OriginalImageVersion for the image context plus the + * caller-provided BornOnVersion. This is image-compat metadata, not simply current OS version. + * A plain OS upgrade does not automatically guarantee the result flips to enabled for an existing + * old image. It can become enabled if the relevant image/component is updated or replaced so its + * original-image version context is newer and passes the threshold. The code path only reports + * eligibility in FeatureIsEnabled and does not directly enable a feature system-wide. + * So think of it as compatibility gating tied to image provenance, not a global switch that turns on when Windows version increases. + */ typedef struct _SYSTEM_ORIGINAL_IMAGE_FEATURE_INFORMATION_INPUT { - ULONG Version; - PWSTR FeatureName; - ULONG BornOnVersion; + ULONG Version; // Must be set to SYSTEM_ORIGINAL_IMAGE_FEATURE_INFORMATION_VERSION (1). + PWSTR FeatureName; // Wide string naming the feature to query. Not consulted by the kernel in observed builds; reserved for future use. + ULONG BornOnVersion; // Windows version number the image was originally targeted at; compared against OriginalImageVersion. } 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; + ULONG Version; // Echoes back the protocol version. + BOOLEAN FeatureIsEnabled; // Eligibility result only; TRUE/FALSE does not directly toggle a system-wide feature state. } SYSTEM_ORIGINAL_IMAGE_FEATURE_INFORMATION_OUTPUT, *PSYSTEM_ORIGINAL_IMAGE_FEATURE_INFORMATION_OUTPUT; // private @@ -5596,7 +7021,10 @@ typedef struct _SYSTEM_MEMORY_NUMA_PERFORMANCE_INFORMATION_OUTPUT SYSTEM_MEMORY_NUMA_PERFORMANCE_ENTRY PerformanceEntries[1]; } SYSTEM_MEMORY_NUMA_PERFORMANCE_INFORMATION_OUTPUT, *PSYSTEM_MEMORY_NUMA_PERFORMANCE_INFORMATION_OUTPUT; -// private +/** + * The SYSTEM_OSL_RAMDISK_ENTRY structure describes a single RAM disk region + * used by the operating system loader. + */ typedef struct _SYSTEM_OSL_RAMDISK_ENTRY { ULONG BlockSize; @@ -5604,7 +7032,10 @@ typedef struct _SYSTEM_OSL_RAMDISK_ENTRY SIZE_T Size; } SYSTEM_OSL_RAMDISK_ENTRY, *PSYSTEM_OSL_RAMDISK_ENTRY; -// private +/** + * The SYSTEM_TRUSTEDAPPS_RUNTIME_INFORMATION structure describes runtime + * information related to Trusted Apps support. + */ typedef struct _SYSTEM_TRUSTEDAPPS_RUNTIME_INFORMATION { union @@ -5619,7 +7050,10 @@ typedef struct _SYSTEM_TRUSTEDAPPS_RUNTIME_INFORMATION PVOID RemoteBreakingRoutine; } SYSTEM_TRUSTEDAPPS_RUNTIME_INFORMATION, *PSYSTEM_TRUSTEDAPPS_RUNTIME_INFORMATION; -// private +/** + * The SYSTEM_OSL_RAMDISK_INFORMATION structure describes a variable-length + * array of RAM disk entries used by the operating system loader. + */ typedef struct _SYSTEM_OSL_RAMDISK_INFORMATION { ULONG Version; @@ -5627,8 +7061,612 @@ typedef struct _SYSTEM_OSL_RAMDISK_INFORMATION SYSTEM_OSL_RAMDISK_ENTRY Entries[1]; } SYSTEM_OSL_RAMDISK_INFORMATION, *PSYSTEM_OSL_RAMDISK_INFORMATION; +/** + * The CI_POLICY_MGMT_OPERATION enumeration specifies the type of Code Integrity + * policy management operation requested. + */ +typedef enum _CI_POLICY_MGMT_OPERATION +{ + CI_POLICY_MGMT_OPERATION_NONE = 0, + CI_POLICY_MGMT_OPERATION_OPEN_TX = 1, + CI_POLICY_MGMT_OPERATION_COMMIT_TX = 2, + CI_POLICY_MGMT_OPERATION_CLOSE_TX = 3, + CI_POLICY_MGMT_OPERATION_ADD_POLICY = 4, + CI_POLICY_MGMT_OPERATION_REMOVE_POLICY = 5, + CI_POLICY_MGMT_OPERATION_GET_POLICY = 6, + CI_POLICY_MGMT_OPERATION_GET_POLICY_IDS = 7, + CI_POLICY_MGMT_OPERATION_MAX = 8 +} CI_POLICY_MGMT_OPERATION; + +/** + * The SYSTEM_CODEINTEGRITYPOLICY_MANAGEMENT structure describes parameters + * used to manage Code Integrity policies through the system information + * interface. + */ +typedef struct _SYSTEM_CODEINTEGRITYPOLICY_MANAGEMENT +{ + CI_POLICY_MGMT_OPERATION Operation; + UCHAR UseInProgressState; + ULONG Arg1Len; + PUCHAR Arg1; + ULONG Arg2Len; + PUCHAR Arg2; +} SYSTEM_CODEINTEGRITYPOLICY_MANAGEMENT, *PSYSTEM_CODEINTEGRITYPOLICY_MANAGEMENT; + +// rev +typedef struct _SYSTEM_MEMORY_NUMA_CACHE_ENTRY +{ + ULONG CacheNode; + ULONG CacheLevel; + ULONG CacheSize; + ULONG CacheLineSize; + ULONG CacheType; + ULONG CacheAttributes; + ULONG CacheFlags; + UCHAR Present; + UCHAR Reserved[3]; +} SYSTEM_MEMORY_NUMA_CACHE_ENTRY, *PSYSTEM_MEMORY_NUMA_CACHE_ENTRY; + +// rev +typedef struct _SYSTEM_MEMORY_NUMA_CACHE_INFORMATION +{ + ULONG Version; // always 1 + ULONG Size; // total bytes written, aligned to 0x20 + ULONG EntryCount; // number of cache entries + ULONG Reserved; // appears to stay zero + SYSTEM_MEMORY_NUMA_CACHE_ENTRY Entries[1]; // Followed by EntryCount records, each 0x20 bytes +} SYSTEM_MEMORY_NUMA_CACHE_INFORMATION, *PSYSTEM_MEMORY_NUMA_CACHE_INFORMATION; + +/** + * The SYSTEM_REF_TRACE_INFORMATION_EX structure describes configuration + * parameters for object reference tracing. + */ +typedef struct _SYSTEM_REF_TRACE_INFORMATION_EX +{ + ULONG Version; + ULONGLONG MemoryLimits; + union + { + ULONG Flags; + struct + { + ULONG TraceEnable : 1; + ULONG TracePermanent : 1; + ULONG UseTracePoolTags : 1; + ULONG TraceByStacksOnly : 1; + ULONG ReservedFlags : 28; + }; + }; + UNICODE_STRING TraceProcessName; + UNICODE_STRING TracePoolTags; + ULONG MaxObjectRefTraces; + ULONG TracedObjectLimit; +} SYSTEM_REF_TRACE_INFORMATION_EX, *PSYSTEM_REF_TRACE_INFORMATION_EX; + +/** + * The SYSTEM_BASICPROCESS_INFORMATION structure describes basic process + * information returned when enumerating processes. + */ +_Struct_size_bytes_(NextEntryOffset) +typedef struct _SYSTEM_BASICPROCESS_INFORMATION +{ + ULONG NextEntryOffset; + HANDLE UniqueProcessId; + HANDLE InheritedFromUniqueProcessId; + ULONG64 SequenceNumber; + UNICODE_STRING ImageName; +} SYSTEM_BASICPROCESS_INFORMATION, *PSYSTEM_BASICPROCESS_INFORMATION; + +/** + * The SYSTEM_HANDLECOUNT_INFORMATION structure provides global counts of + * processes, threads, and handles in the system. + */ +typedef struct _SYSTEM_HANDLECOUNT_INFORMATION +{ + ULONG ProcessCount; + ULONG ThreadCount; + ULONG HandleCount; +} SYSTEM_HANDLECOUNT_INFORMATION, *PSYSTEM_HANDLECOUNT_INFORMATION; + +// +// Runtime Report Definitions +// + +#define SYSTEM_RUNTIME_REPORT_INPUT_VERSION_1 1 +#define SYSTEM_RUNTIME_REPORT_INPUT_PACKAGE_VERSION_1 1 + +// private +typedef struct _SYSTEM_RUNTIME_REPORT_INPUT +{ + USHORT InputVersion; + USHORT PackageVersion; + ULONG Reserved; + ULONG_PTR ReportTypesBitmap; + UCHAR Nonce[32]; +} SYSTEM_RUNTIME_REPORT_INPUT, *PSYSTEM_RUNTIME_REPORT_INPUT; + +#if !defined(NTDDI_WIN11_GE) || (NTDDI_VERSION < NTDDI_WIN11_GE) +// +// =============================================== +// Runtime Report Package Format: +// +// ------------------------------------- Signed part Begin +// +// RUNTIME_REPORT_PACKAGE_HEADER +// +// BYTE Nonce[RUNTIME_REPORT_NONCE_SIZE] +// +// RUNTIME_REPORT_DIGEST_HEADER_A +// +// RUNTIME_REPORT_DIGEST_HEADER_B +// ... +// ... +// +// ------------------------------------- Signed part End +// +// Signature Blob +// +// ------------------------------------- Authenticated part Begin +// +// RUNTIME_REPORT_HEADER +// REPORT_A +// +// RUNTIME_REPORT_HEADER +// REPORT_B +// +// ------------------------------------- Authenticated part End +// +// =============================================== +// + +#define RUNTIME_REPORT_PACKAGE_MAGIC 0x52545250 // = "RTRP" +#define RUNTIME_REPORT_PACKAGE_VERSION_CURRENT (1) +#define RUNTIME_REPORT_NONCE_SIZE 32 +#define RUNTIME_REPORT_DIGEST_MAX_SIZE 64 +#define RUNTIME_REPORT_SIGNATURE_SCHEME_SHA512_RSA_PSS_SHA512 (1) + +// +// Runtime Report Type Enumeration +// + +typedef enum _RUNTIME_REPORT_TYPE +{ + RuntimeReportTypeDriver = 0, + RuntimeReportTypeCodeIntegrity = 1, + RuntimeReportTypeMax +} RUNTIME_REPORT_TYPE; + +// +// Macro to convert a report type enum value to a bitmap mask +// + +#define RUNTIME_REPORT_TYPE_TO_MASK(type) (1ULL << (type)) + +// +// Bitmap mask containing all valid report types +// + +#define RUNTIME_REPORT_TYPE_MASK_ALL ((1ULL << RuntimeReportTypeMax) - 1) + +typedef struct _RUNTIME_REPORT_PACKAGE_HEADER +{ + // + // Set to RUNTIME_REPORT_PACKAGE_MAGIC = 0x52545250 ("RTRP") + // + + ULONG Magic; + + // + // The version of the package format + // + + USHORT PackageVersion; + + // + // Number of different report types contained in the package. + // + + USHORT NumberOfReports; + + // + // A bitmap of all the report types in the package. + // + // Use RUNTIME_REPORT_TYPE_TO_MASK macro to convert enum values to bitmap masks. + // Current valid report types: + // RuntimeReportTypeDriver = 0 + // RuntimeReportTypeCodeIntegrity = 1 + // + + ULONG_PTR ReportTypesBitmap; + + // + // The size of the total package including the package header, + // various runtime reports, their digests, and the signature blob. + // + + ULONG PackageSize; + + // + // The type of digest contained in the report digest headers. + // + // Current valid values: + // CALG_SHA_512 (see wincrypt.h) + // + + USHORT ReportDigestType; + + // + // Total size of the signed runtime report digest headers + // following the package header. + // + + USHORT TotalReportDigestsSize; + + // + // Reserved field. Must be set to zero. + // + + USHORT Reserved; + + // + // The signature scheme used to sign the runtime reports. + // + // Current valid values: + // RUNTIME_REPORT_SIGNATURE_SCHEME_SHA512_RSA_PSS_SHA512 = 1 + // + + USHORT SignatureScheme; + + // + // Size of the signature blob following the runtime report digests. + // + + ULONG SignatureSize; + + // + // Total size of the authenticated (but unsigned) runtime reports + // following the signature blob. + // + + ULONG TotalAuthenticatedReportsSize; + +} RUNTIME_REPORT_PACKAGE_HEADER, *PRUNTIME_REPORT_PACKAGE_HEADER; + +typedef struct _RUNTIME_REPORT_DIGEST_HEADER +{ + // + // Indicates the type of report that was hashed. + // + // Current valid values: + // RuntimeReportTypeDriver = 0 + // RuntimeReportTypeCodeIntegrity = 1 + // + + USHORT ReportType; + + // + // Reserved field. + // + + USHORT Reserved; + + // + // Digest of the report including the report header. + // This is a SHA-512 digest. + // + + UCHAR ReportDigest[RUNTIME_REPORT_DIGEST_MAX_SIZE]; + +} RUNTIME_REPORT_DIGEST_HEADER, *PRUNTIME_REPORT_DIGEST_HEADER; + +typedef struct _RUNTIME_REPORT_HEADER +{ + // + // Indicates the type of report. + // + // Current valid values: + // RuntimeReportTypeDriver = 0 + // RuntimeReportTypeCodeIntegrity = 1 + // + + USHORT ReportType; + + // + // Reserved field. + // + + USHORT Reserved; + + // + // The number of bytes consumed by this report, including the header. + // + + ULONG ReportSize; + +} RUNTIME_REPORT_HEADER, *PRUNTIME_REPORT_HEADER; + +// +// Driver Report Definitions +// + +#define DRIVER_REPORT_DIGEST_MAX_SIZE RUNTIME_REPORT_DIGEST_MAX_SIZE +#define DRIVER_REPORT_NAME_MAX_LENGTH 32 + +typedef struct _DRIVER_INFO_ENTRY +{ + // + // Internal name of the driver from the resource section. + // + + CHAR InternalName[DRIVER_REPORT_NAME_MAX_LENGTH]; + + // + // Hash algorithm used to calculate the image digest. + // + + USHORT ImageHashAlgorithm; + + // + // Hash algorithm used to calculate the thumbprint of the leaf certificate + // that validates the entire image. + // + + USHORT PublisherThumbprintHashAlgorithm; + + // + // Offset from the start of the driver report to a buffer containing the + // digest of the driver image on disk. + // + + ULONG ImageHashOffset; + + // + // Offset from the start of the driver report to a buffer containing the + // thumbprint of the leaf certificate validating the entire image + // + + ULONG PublisherThumbprintOffset; + + // + // Number of times that this driver image has been loaded into the system. + // + + USHORT NumberOfLoadingTimes; + + // + // Size and Offset of a string indicating the OEM name stored in the + // authenticated OPUS block of the image digital signature. + // There is no OEM name for inbox Windows signed drivers. The size does *NOT* + // include the NULL terminator (even though the string is NULL-terminated). + // + + USHORT OemNameSize; + ULONG OemNameOffset; + + // + // Flags indicating various properties of the current driver image: + // - Unloaded - Set to 1 in case the driver is current unloaded. + // + // - BootDriver - Set to 1 in case the image is a Boot Driver; + // 0 otherwise (the image is a Runtime driver). + // + // - HotPatch - Set to 1 in case the image can be also loaded as Hotpatch; + // + // - Reserved - Reserved flags bits. + // + + union + { + struct + { + USHORT Unloaded : 1; + USHORT BootDriver : 1; + USHORT HotPatch : 1; + USHORT Reserved : 13; + }; + USHORT AsUInt16; + } Flags; + + USHORT Padding; +} DRIVER_INFO_ENTRY, *PDRIVER_INFO_ENTRY; + +typedef struct _DRIVER_RUNTIME_REPORT +{ + // + // The driver runtime report header. + // + + RUNTIME_REPORT_HEADER Header; + + // + // The current number of unique drivers in the report. + // + + USHORT NumberOfDrivers; + + // + // Flags indicating various properties of the report: + // - ReportOverflowed - Secure Kernel places a limit on the number of + // drivers it can list in the report. If this is set, it indicates + // that some loaded drivers might be missing from the report. + // + // - PartialReport - Indicates whether the report contains only a + // subset of NT loaded drivers. + // + // - IncludeBootDrivers - Set to 1 in case the report includes + // boot-loaded drivers; 0 otherwise (in that case the information + // is stored in the TCG Log). + // + // - Reserved - Reserved flags bits. + // + + union + { + struct + { + USHORT ReportOverflowed : 1; + USHORT PartialReport : 1; + USHORT IncludeBootDrivers : 1; + USHORT Reserved : 13; + }; + USHORT AsUInt16; + } Flags; + + // + // A list, of size zero up to MaximumDriversRecorded, containing driver entries. + // Unloaded drivers are not removed from the list. + // + + DRIVER_INFO_ENTRY DriverEntries[ANYSIZE_ARRAY]; + + // + // After the driver info array the driver runtime report store hashes, + // strings and information that are dynamic in size. + // + // BYTE DynamicBuffer[ANYSIZE_ARRAY]; + // + // The dynamic buffer, for each driver is composed off: + // ImageHash - PublisherHash - OemName. + // + +} DRIVER_RUNTIME_REPORT, *PDRIVER_RUNTIME_REPORT; + +// +// Code Integrity Report Definitions. +// + +typedef struct _CODE_INTEGRITY_RUNTIME_REPORT +{ + // + // The Code Integrity runtime report header. + // + + RUNTIME_REPORT_HEADER Header; + + // + // The number of generations (updates) of policy there have been since boot. + // The initial generation at boot is 1. + // + + UINT64 CurrentGeneration; + + // + // The number of generations of policy that are in this report. This is + // non-zero with the current generation reported first, followed by prior + // generations in order of ascending age. + // + + ULONG NumberOfGenerations; + +} CODE_INTEGRITY_RUNTIME_REPORT; + +#define CODE_INTEGRITY_REPORT_GENERATION_VERSION_CURRENT (1) + +typedef struct _CODE_INTEGRITY_REPORT_GENERATION_HEADER +{ + // + // Version of this structure. + // + + USHORT Version; + + // + // Reserved Field. + // + + USHORT Reserved; + + // + // The number of bytes consumed by this generation, including this header + // and all CODE_INTEGRITY_REPORT_RECORD_HEADER structures and payloads. + // + + ULONG RecordSize; + + // + // Secure Kernel / Hypervisor secure time reference when this policy was + // commited. + // + + ULONG64 CommitTime; + +} CODE_INTEGRITY_REPORT_GENERATION_HEADER; + +#define CODE_INTEGRITY_REPORT_RECORD_VERSION_CURRENT (1) + +typedef struct _CODE_INTEGRITY_REPORT_RECORD_HEADER +{ + // + // Version of this structure. + // + + USHORT Version; + + // + // Reserved Field. + // + + USHORT Reserved; + + // + // The number of bytes consumed by this record, including this header. + // + + ULONG RecordSize; + + // + // The event code (type) of this record. The same codes as the Measured + // Boot TCG Log are used, for example SIPAEVENT_OS_REVOCATION_LIST, and + // indicate the structure type of the payload that immediately follows + // this header. + // + + ULONG SipaEventCode; + +} CODE_INTEGRITY_REPORT_RECORD_HEADER; +#endif // #if !defined(NTDDI_WIN11_GE) || (NTDDI_VERSION < NTDDI_WIN11_GE) + +/** + * The SYSTEM_POOLTAG2 structure describes allocation statistics for a single + * pool tag, including paged and nonpaged usage. + */ +typedef struct _SYSTEM_POOLTAG2 +{ + union + { + UCHAR Tag[4]; + ULONG TagUlong; + } DUMMYUNIONNAME; + SIZE_T PagedAllocs; + SIZE_T PagedFrees; + SIZE_T PagedUsed; + SIZE_T NonPagedAllocs; + SIZE_T NonPagedFrees; + SIZE_T NonPagedUsed; +} SYSTEM_POOLTAG2, *PSYSTEM_POOLTAG2; + +/** + * The SYSTEM_POOLTAG_INFORMATION2 structure describes a variable-length array + * of SYSTEM_POOLTAG2 entries representing pool tag usage statistics. + */ +typedef struct _SYSTEM_POOLTAG_INFORMATION2 +{ + ULONG Count; + _Field_size_(Count) SYSTEM_POOLTAG2 TagInfo[1]; +} SYSTEM_POOLTAG_INFORMATION2, *PSYSTEM_POOLTAG_INFORMATION2; + #if (PHNT_MODE != PHNT_MODE_KERNEL) +/** + * The NtQuerySystemInformation routine queries information about the system. + * + * \param SystemInformationClass The type of information to be retrieved. + * \param SystemInformation A pointer to a buffer that receives the requested information. + * \param SystemInformationLength The size of the buffer pointed to by SystemInformation. + * \param ReturnLength A pointer to a variable that receives the size of the data returned in the buffer. + * \return NTSTATUS Successful or errant status. + * \see https://learn.microsoft.com/en-us/windows/win32/sysinfo/zwquerysysteminformation + */ NTSYSCALLAPI NTSTATUS NTAPI @@ -5639,7 +7677,18 @@ NtQuerySystemInformation( _Out_opt_ PULONG ReturnLength ); -#if (PHNT_VERSION >= PHNT_WINDOWS_7) +/** + * The NtQuerySystemInformationEx routine queries information about the system. + * + * \param SystemInformationClass The type of information to be retrieved. + * \param InputBuffer Pointer to a caller-allocated input buffer that contains class-specific information. + * \param InputBufferLength The size of the buffer pointed to by InputBuffer. + * \param SystemInformation A pointer to a buffer that receives the requested information. + * \param SystemInformationLength The size of the buffer pointed to by SystemInformation. + * \param ReturnLength A pointer to a variable that receives the size of the data returned in the buffer. + * \return NTSTATUS Successful or errant status. + * \see https://learn.microsoft.com/en-us/windows/win32/sysinfo/zwquerysysteminformation + */ NTSYSCALLAPI NTSTATUS NTAPI @@ -5651,8 +7700,15 @@ NtQuerySystemInformationEx( _In_ ULONG SystemInformationLength, _Out_opt_ PULONG ReturnLength ); -#endif // (PHNT_VERSION >= PHNT_WINDOWS_7) +/** + * The NtSetSystemInformation routine sets information about the system. + * + * \param SystemInformationClass The type of information to be set. + * \param SystemInformation A pointer to a buffer that receives the requested information. + * \param SystemInformationLength The size of the buffer pointed to by SystemInformation. + * \return NTSTATUS Successful or errant status. + */ NTSYSCALLAPI NTSTATUS NTAPI @@ -5662,53 +7718,62 @@ NtSetSystemInformation( _In_ ULONG SystemInformationLength ); +// // SysDbg APIs +// -// private +/** + * The SYSDBG_COMMAND enumeration specifies the type of system debugger + * operation requested through NtSystemDebugControl. + */ 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 + SysDbgQueryModuleInformation, // q: DBGKD_DEBUG_DATA_HEADER64 + SysDbgQueryTraceInformation, // q: DBGKD_TRACE_DATA + SysDbgSetTracepoint, // s: PVOID + SysDbgSetSpecialCall, // s: PVOID + SysDbgClearSpecialCalls, // s: void + SysDbgQuerySpecialCalls, // q: PVOID[] + SysDbgBreakPoint, // s: void + SysDbgQueryVersion, // q: DBGKD_GET_VERSION64 + SysDbgReadVirtual, // q: SYSDBG_VIRTUAL + SysDbgWriteVirtual, // s: SYSDBG_VIRTUAL + SysDbgReadPhysical, // q: SYSDBG_PHYSICAL // 10 + SysDbgWritePhysical, // s: SYSDBG_PHYSICAL + SysDbgReadControlSpace, // q: SYSDBG_CONTROL_SPACE + SysDbgWriteControlSpace, // s: SYSDBG_CONTROL_SPACE + SysDbgReadIoSpace, // q: SYSDBG_IO_SPACE + SysDbgWriteIoSpace, // s: SYSDBG_IO_SPACE + SysDbgReadMsr, // q: SYSDBG_MSR + SysDbgWriteMsr, // s: SYSDBG_MSR + SysDbgReadBusData, // q: SYSDBG_BUS_DATA + SysDbgWriteBusData, // s: SYSDBG_BUS_DATA + SysDbgCheckLowMemory, // q: ULONG // 20 + SysDbgEnableKernelDebugger, // s: void + SysDbgDisableKernelDebugger, // s: void + SysDbgGetAutoKdEnable, // q: ULONG + SysDbgSetAutoKdEnable, // s: ULONG + SysDbgGetPrintBufferSize, // q: ULONG + SysDbgSetPrintBufferSize, // s: ULONG + SysDbgGetKdUmExceptionEnable, // q: ULONG + SysDbgSetKdUmExceptionEnable, // s: ULONG + SysDbgGetTriageDump, // q: SYSDBG_TRIAGE_DUMP + SysDbgGetKdBlockEnable, // q: ULONG // 30 + SysDbgSetKdBlockEnable, // s: ULONG + SysDbgRegisterForUmBreakInfo, // s: HANDLE + SysDbgGetUmBreakPid, // q: ULONG + SysDbgClearUmBreakPid, // s: void + SysDbgGetUmAttachPid, // q: ULONG + SysDbgClearUmAttachPid, // s: void + SysDbgGetLiveKernelDump, // q: SYSDBG_LIVEDUMP_CONTROL + SysDbgKdPullRemoteFile, // q: SYSDBG_KD_PULL_REMOTE_FILE SysDbgMaxInfoClass } SYSDBG_COMMAND, *PSYSDBG_COMMAND; +/** + * The SYSDBG_VIRTUAL structure describes a request to read or write virtual + * memory through the system debugger interface. + */ typedef struct _SYSDBG_VIRTUAL { PVOID Address; @@ -5716,6 +7781,10 @@ typedef struct _SYSDBG_VIRTUAL ULONG Request; } SYSDBG_VIRTUAL, *PSYSDBG_VIRTUAL; +/** + * The SYSDBG_PHYSICAL structure describes a request to read or write physical + * memory through the system debugger interface. + */ typedef struct _SYSDBG_PHYSICAL { PHYSICAL_ADDRESS Address; @@ -5723,6 +7792,10 @@ typedef struct _SYSDBG_PHYSICAL ULONG Request; } SYSDBG_PHYSICAL, *PSYSDBG_PHYSICAL; +/** + * The SYSDBG_CONTROL_SPACE structure describes a request to access processor + * control space through the system debugger interface. + */ typedef struct _SYSDBG_CONTROL_SPACE { ULONG64 Address; @@ -5731,37 +7804,52 @@ typedef struct _SYSDBG_CONTROL_SPACE ULONG Processor; } SYSDBG_CONTROL_SPACE, *PSYSDBG_CONTROL_SPACE; -enum _INTERFACE_TYPE; +typedef enum _INTERFACE_TYPE INTERFACE_TYPE; +/** + * The SYSDBG_IO_SPACE structure describes a request to access I/O space + * through the system debugger interface. + */ typedef struct _SYSDBG_IO_SPACE { ULONG64 Address; PVOID Buffer; ULONG Request; - enum _INTERFACE_TYPE InterfaceType; + INTERFACE_TYPE InterfaceType; ULONG BusNumber; ULONG AddressSpace; } SYSDBG_IO_SPACE, *PSYSDBG_IO_SPACE; +/** + * The SYSDBG_MSR structure describes a request to read or write a model-specific + * register (MSR) through the system debugger interface. + */ typedef struct _SYSDBG_MSR { ULONG Msr; ULONG64 Data; } SYSDBG_MSR, *PSYSDBG_MSR; -enum _BUS_DATA_TYPE; +typedef enum _BUS_DATA_TYPE BUS_DATA_TYPE; +/** + * The SYSDBG_BUS_DATA structure describes a request to access bus-specific + * configuration data through the system debugger interface. + */ typedef struct _SYSDBG_BUS_DATA { ULONG Address; PVOID Buffer; ULONG Request; - enum _BUS_DATA_TYPE BusDataType; + BUS_DATA_TYPE BusDataType; ULONG BusNumber; ULONG SlotNumber; } SYSDBG_BUS_DATA, *PSYSDBG_BUS_DATA; -// private +/** + * The SYSDBG_TRIAGE_DUMP structure describes parameters used when generating + * a triage dump through the system debugger interface. + */ typedef struct _SYSDBG_TRIAGE_DUMP { ULONG Flags; @@ -5775,7 +7863,10 @@ typedef struct _SYSDBG_TRIAGE_DUMP PHANDLE Handles; } SYSDBG_TRIAGE_DUMP, *PSYSDBG_TRIAGE_DUMP; -// private +/** + * The SYSDBG_LIVEDUMP_CONTROL_FLAGS union specifies control flags used when + * generating a live kernel dump. + */ typedef union _SYSDBG_LIVEDUMP_CONTROL_FLAGS { struct @@ -5790,7 +7881,10 @@ typedef union _SYSDBG_LIVEDUMP_CONTROL_FLAGS ULONG AsUlong; } SYSDBG_LIVEDUMP_CONTROL_FLAGS, *PSYSDBG_LIVEDUMP_CONTROL_FLAGS; -// private +/** + * The SYSDBG_LIVEDUMP_CONTROL_ADDPAGES union specifies additional page + * categories to include when generating a live kernel dump. + */ typedef union _SYSDBG_LIVEDUMP_CONTROL_ADDPAGES { struct @@ -5805,6 +7899,10 @@ typedef union _SYSDBG_LIVEDUMP_CONTROL_ADDPAGES #define SYSDBG_LIVEDUMP_SELECTIVE_CONTROL_VERSION 1 // rev +/** + * The SYSDBG_LIVEDUMP_SELECTIVE_CONTROL structure specifies selective dump + * options for live kernel dump generation. + */ typedef struct _SYSDBG_LIVEDUMP_SELECTIVE_CONTROL { ULONG Version; @@ -5825,7 +7923,10 @@ typedef struct _SYSDBG_LIVEDUMP_SELECTIVE_CONTROL #define SYSDBG_LIVEDUMP_CONTROL_VERSION_2 2 #define SYSDBG_LIVEDUMP_CONTROL_VERSION SYSDBG_LIVEDUMP_CONTROL_VERSION_2 -// private +/** + * The SYSDBG_LIVEDUMP_CONTROL_V1 structure describes parameters used when + * generating a live kernel dump (version 1). + */ typedef struct _SYSDBG_LIVEDUMP_CONTROL_V1 { ULONG Version; @@ -5840,7 +7941,10 @@ typedef struct _SYSDBG_LIVEDUMP_CONTROL_V1 SYSDBG_LIVEDUMP_CONTROL_ADDPAGES AddPagesControl; } SYSDBG_LIVEDUMP_CONTROL_V1, *PSYSDBG_LIVEDUMP_CONTROL_V1; -// private +/** + * The SYSDBG_LIVEDUMP_CONTROL structure describes parameters used when + * generating a live kernel dump (current version). + */ typedef struct _SYSDBG_LIVEDUMP_CONTROL { ULONG Version; @@ -5856,12 +7960,26 @@ typedef struct _SYSDBG_LIVEDUMP_CONTROL PSYSDBG_LIVEDUMP_SELECTIVE_CONTROL SelectiveControl; // since WIN11 } SYSDBG_LIVEDUMP_CONTROL, *PSYSDBG_LIVEDUMP_CONTROL; -// private +/** + * The SYSDBG_KD_PULL_REMOTE_FILE structure describes a request to retrieve + * a remote file through the kernel debugger transport. + */ typedef struct _SYSDBG_KD_PULL_REMOTE_FILE { UNICODE_STRING ImageFileName; } SYSDBG_KD_PULL_REMOTE_FILE, *PSYSDBG_KD_PULL_REMOTE_FILE; +/** + * The NtSystemDebugControl routine provides system debugging and diagnostic control of the system. + * + * \param[in] Command The debug control command to execute (of type SYSDBG_COMMAND). + * \param[in] InputBuffer Optional pointer to a buffer containing input data for the command. + * \param[in] InputBufferLength Length, in bytes, of the input buffer. + * \param[out] OutputBuffer Optional pointer to a buffer that receives output data from the command. + * \param[in] OutputBufferLength Length, in bytes, of the output buffer. + * \param[out] ReturnLength Optional pointer to a variable that receives the number of bytes returned in the output buffer. + * \return NTSTATUS Successful or errant status. + */ NTSYSCALLAPI NTSTATUS NTAPI @@ -5874,8 +7992,14 @@ NtSystemDebugControl( _Out_opt_ PULONG ReturnLength ); +// // Hard errors +// +/** + * The HARDERROR_RESPONSE_OPTION enumeration specifies the type of user + * interface prompt that may be displayed when a hard error occurs. + */ typedef enum _HARDERROR_RESPONSE_OPTION { OptionAbortRetryIgnore, @@ -5889,6 +8013,10 @@ typedef enum _HARDERROR_RESPONSE_OPTION OptionCancelTryContinue } HARDERROR_RESPONSE_OPTION; +/** + * The HARDERROR_RESPONSE enumeration specifies the response returned by the + * caller or user when handling a hard error condition. + */ typedef enum _HARDERROR_RESPONSE { ResponseReturnToCaller, @@ -5904,8 +8032,25 @@ typedef enum _HARDERROR_RESPONSE ResponseContinue } HARDERROR_RESPONSE; +/** + * HARDERROR_OVERRIDE_ERRORMODE indicates that the system should ignore the + * calling process's error mode when processing a hard error. + */ #define HARDERROR_OVERRIDE_ERRORMODE 0x10000000 +/** + * The NtRaiseHardError routine raises a hard error or serious error dialog box being displayed to the user. + * + * \param[in] ErrorStatus The NTSTATUS code that describes the error condition. + * \param[in] NumberOfParameters The number of parameters in the Parameters array. + * \param[in] UnicodeStringParameterMask A bitmask indicating which entries in the Parameters array are Unicode strings. + * \param[in] Parameters An array of parameters to be used in the error message. + * \param[in] ValidResponseOptions Specifies the valid responses that the user can select in the error dialog. + * \param[out] Response Receives the user's response to the error dialog. + * \return NTSTATUS Successful or errant status. + */ +_Analysis_noreturn_ +DECLSPEC_NORETURN NTSYSCALLAPI NTSTATUS NTAPI @@ -5922,6 +8067,13 @@ NtRaiseHardError( // Kernel-user shared data // +/** + * The ALTERNATIVE_ARCHITECTURE_TYPE enumeration specifies the hardware + * architecture variant used by the system. + * + * \remarks NEC98x86 represents the NEC PC-98 architecture, + * supported only on very early Windows releases. + */ typedef enum _ALTERNATIVE_ARCHITECTURE_TYPE { StandardDesign, @@ -5929,8 +8081,16 @@ typedef enum _ALTERNATIVE_ARCHITECTURE_TYPE EndAlternatives } ALTERNATIVE_ARCHITECTURE_TYPE; +/** + * PROCESSOR_FEATURE_MAX defines the maximum number of processor feature flags + * that may be reported by the system. + */ #define PROCESSOR_FEATURE_MAX 64 +/** + * MAX_WOW64_SHARED_ENTRIES defines the number of shared entries available to + * the WOW64 (Windows-on-Windows 64-bit) subsystem. + */ #define MAX_WOW64_SHARED_ENTRIES 16 // @@ -6023,7 +8183,11 @@ typedef enum _ALTERNATIVE_ARCHITECTURE_TYPE #define SHARED_GLOBAL_FLAGS_QPC_BYPASS_A73_ERRATA (0x40) #define SHARED_GLOBAL_FLAGS_QPC_BYPASS_USE_RDTSCP (0x80) - +/** + * The KUSER_SHARED_DATA structure contains information shared with user-mode. + * + * \sa https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/ntddk/ns-ntddk-kuser_shared_data + */ typedef struct _KUSER_SHARED_DATA { // @@ -6089,19 +8253,44 @@ typedef struct _KUSER_SHARED_DATA ULONG TimeZoneId; + // + // Minimum size of a large page on the system, in bytes. + // + // N.B. Returned by GetLargePageMinimum() function. + // + ULONG LargePageMinimum; // - // This value controls the AIT Sampling rate. + // This value controls the Application Impact Telemetry (AIT) Sampling rate. + // + // This value determines how frequently the system records AIT events, + // which are used by the Application Experience and compatibility + // subsystems to evaluate application behavior, performance, and + // potential compatibility issues. + // + // Lower values increase sampling frequency, while higher values reduce it. + // The kernel updates this field as part of its internal telemetry and + // heuristics logic. // ULONG AitSamplingValue; // - // This value controls switchback processing. + // This value controls Application Compatibility (AppCompat) switchback processing. // - ULONG AppCompatFlag; + union + { + ULONG AppCompatFlag; + struct + { + ULONG SwitchbackEnabled : 1; // Basic switchback processing + ULONG ExtendedHeuristics : 1; // Extended switchback heuristics + ULONG TelemetryFallback : 1; // Telemetry-driven fallback + ULONG Reserved : 29; + } AppCompatFlags; + }; // // Current Kernel Root RNG state seed version @@ -6112,9 +8301,28 @@ typedef struct _KUSER_SHARED_DATA // // This value controls assertion failure handling. // + // Historically (prior to Windows 10), this value was also used by + // Code Integrity (CI), AppLocker, and related security components to + // determine the minimum validation requirements for executable images, + // drivers, and privileged operations. + // + // In modern Windows versions, this field is used primarily by the kernel's + // diagnostic and validation infrastructure to decide how assertion failures + // should be handled (e.g., logging, debugger break-in, or bugcheck). ULONG GlobalValidationRunlevel; + // + // Monotonic stamp incremented by the kernel whenever the system's + // time zone bias value changes. + // + // N.B. This field must be accessed via the RtlGetSystemTimeAndBias API for + // an accurate result. + // This value is read before and after accessing the bias fields to determine + // whether the time zone data changed during the read. If the stamp differs, + // the caller must re-read the bias values to ensure consistency. + // + volatile LONG TimeZoneBiasStamp; // @@ -6134,6 +8342,15 @@ typedef struct _KUSER_SHARED_DATA NT_PRODUCT_TYPE NtProductType; BOOLEAN ProductTypeIsValid; BOOLEAN Reserved0[1]; + + // + // Native hardware processor architecture of the running system. + // + // N.B. User-mode components read this field to determine the true system + // architecture, especially in WOW64 scenarios where the process architecture + // differs from the native one. + // + USHORT NativeProcessorArchitecture; // @@ -6158,8 +8375,8 @@ typedef struct _KUSER_SHARED_DATA // Reserved fields - do not use. // - ULONG Reserved1; - ULONG Reserved3; + ULONG MaximumUserModeAddressDeprecated; // Deprecated, use SystemBasicInformation instead. + ULONG SystemRangeStartDeprecated; // Deprecated, use SystemRangeStartInformation instead. // // Time slippage while in debugger. @@ -6343,6 +8560,10 @@ typedef struct _KUSER_SHARED_DATA } DUMMYSTRUCTNAME2; } DUMMYUNIONNAME2; + // + // Reserved padding field to preserve structure alignment and compatibility. + // + ULONG DataFlagsPad[1]; // @@ -6354,6 +8575,16 @@ typedef struct _KUSER_SHARED_DATA ULONGLONG TestRetInstruction; + // + // Query-performance counter (QPC) frequency, in counts per second. + // + // N.B. This value represents the fixed frequency of the system's high-resolution + // performance counter. It is used by user-mode time routines to convert QPC + // ticks into elapsed time without requiring a system call. The frequency is + // constant for the lifetime of the system and reflects the hardware or + // virtualized timer source selected by the kernel. + // + LONGLONG QpcFrequency; // @@ -6526,10 +8757,19 @@ typedef struct _KUSER_SHARED_DATA volatile ULONGLONG QpcBias; // - // Number of active processors and groups. + // Number of active logical processors. // ULONG ActiveProcessorCount; + + // + // Number of active processor groups. + // + // N.B. This value is volatile because group membership and processor + // availability may change dynamically due to hot-add, hot-remove, + // or power management events. + // + volatile UCHAR ActiveGroupCount; // @@ -6548,7 +8788,49 @@ typedef struct _KUSER_SHARED_DATA // read the counter directly (bypassing the system call) and flags. // - volatile UCHAR QpcBypassEnabled; + union + { + + volatile UCHAR QpcBypassEnabled; + + struct + { + // + // QPC may bypass the syscall and use a fast user-mode path. + // + volatile UCHAR BypassAllowed : 1; + + // + // Hypervisor-assisted QPC conversion. + // + volatile UCHAR HypervisorAssist : 1; + + // + // Reserved/unused + // + volatile UCHAR Reserved_2_3 : 2; + + // + // MFENCE before RDTSC in relevant paths. + // + volatile UCHAR UseMfence : 1; + + // + // LFENCE before RDTSC in relevant paths. + // + volatile UCHAR UseLfence : 1; + + // + // Reserved/unused + // + volatile UCHAR Reserved_6 : 1; + + // + // RDTSCP instead of RDTSC in the fast path. + // + volatile UCHAR UseRdtscp : 1; + }; + }; // // Reserved, leave as zero for backward compatibility. Was shift @@ -6559,6 +8841,10 @@ typedef struct _KUSER_SHARED_DATA }; }; + // + // Reserved for future use. + // + LARGE_INTEGER TimeZoneBiasEffectiveStart; LARGE_INTEGER TimeZoneBiasEffectiveEnd; @@ -6568,9 +8854,23 @@ typedef struct _KUSER_SHARED_DATA XSTATE_CONFIGURATION XState; + // + // RtlQueryFeatureConfigurationChangeStamp + // + KSYSTEM_TIME FeatureConfigurationChangeStamp; + + // + // Spare (available for re-use). + // + ULONG Spare; + // + // This field holds a mask that is used in the process of authenticating pointers in user mode. + // It helps in determining which bits of the pointer are used for authentication in user mode. + // + ULONG64 UserPointerAuthMask; // @@ -6585,113 +8885,132 @@ typedef struct _KUSER_SHARED_DATA #endif } 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); +static_assert(FIELD_OFFSET(KUSER_SHARED_DATA, TickCountLowDeprecated) == 0x000, "KUSER_SHARED_DATA.TickCountLowDeprecated offset is incorrect"); +static_assert(FIELD_OFFSET(KUSER_SHARED_DATA, TickCountMultiplier) == 0x004, "KUSER_SHARED_DATA.TickCountMultiplier offset is incorrect"); +static_assert(__alignof(KSYSTEM_TIME) == 0X004, "KSYSTEM_TIME alignment is incorrect"); +static_assert(FIELD_OFFSET(KUSER_SHARED_DATA, InterruptTime) == 0x008, "KUSER_SHARED_DATA.InterruptTime offset is incorrect"); +static_assert(FIELD_OFFSET(KUSER_SHARED_DATA, SystemTime) == 0x014, "KUSER_SHARED_DATA.SystemTime offset is incorrect"); +static_assert(FIELD_OFFSET(KUSER_SHARED_DATA, TimeZoneBias) == 0x020, "KUSER_SHARED_DATA.TimeZoneBias offset is incorrect"); +static_assert(FIELD_OFFSET(KUSER_SHARED_DATA, ImageNumberLow) == 0x02c, "KUSER_SHARED_DATA.ImageNumberLow offset is incorrect"); +static_assert(FIELD_OFFSET(KUSER_SHARED_DATA, ImageNumberHigh) == 0x02e, "KUSER_SHARED_DATA.ImageNumberHigh offset is incorrect"); +static_assert(FIELD_OFFSET(KUSER_SHARED_DATA, NtSystemRoot) == 0x030, "KUSER_SHARED_DATA.NtSystemRoot offset is incorrect"); +static_assert(FIELD_OFFSET(KUSER_SHARED_DATA, MaxStackTraceDepth) == 0x238, "KUSER_SHARED_DATA.MaxStackTraceDepth offset is incorrect"); +static_assert(FIELD_OFFSET(KUSER_SHARED_DATA, CryptoExponent) == 0x23c, "KUSER_SHARED_DATA.CryptoExponent offset is incorrect"); +static_assert(FIELD_OFFSET(KUSER_SHARED_DATA, TimeZoneId) == 0x240, "KUSER_SHARED_DATA.TimeZoneId offset is incorrect"); +static_assert(FIELD_OFFSET(KUSER_SHARED_DATA, LargePageMinimum) == 0x244, "KUSER_SHARED_DATA.LargePageMinimum offset is incorrect"); +static_assert(FIELD_OFFSET(KUSER_SHARED_DATA, AitSamplingValue) == 0x248, "KUSER_SHARED_DATA.AitSamplingValue offset is incorrect"); +static_assert(FIELD_OFFSET(KUSER_SHARED_DATA, AppCompatFlag) == 0x24c, "KUSER_SHARED_DATA.AppCompatFlag offset is incorrect"); +static_assert(FIELD_OFFSET(KUSER_SHARED_DATA, RNGSeedVersion) == 0x250, "KUSER_SHARED_DATA.RNGSeedVersion offset is incorrect"); +static_assert(FIELD_OFFSET(KUSER_SHARED_DATA, GlobalValidationRunlevel) == 0x258, "KUSER_SHARED_DATA.GlobalValidationRunlevel offset is incorrect"); +static_assert(FIELD_OFFSET(KUSER_SHARED_DATA, TimeZoneBiasStamp) == 0x25c, "KUSER_SHARED_DATA.TimeZoneBiasStamp offset is incorrect"); +static_assert(FIELD_OFFSET(KUSER_SHARED_DATA, NtBuildNumber) == 0x260, "KUSER_SHARED_DATA.NtBuildNumber offset is incorrect"); +static_assert(FIELD_OFFSET(KUSER_SHARED_DATA, NtProductType) == 0x264, "KUSER_SHARED_DATA.NtProductType offset is incorrect"); +static_assert(FIELD_OFFSET(KUSER_SHARED_DATA, ProductTypeIsValid) == 0x268, "KUSER_SHARED_DATA.ProductTypeIsValid offset is incorrect"); +static_assert(FIELD_OFFSET(KUSER_SHARED_DATA, NativeProcessorArchitecture) == 0x26a, "KUSER_SHARED_DATA.NativeProcessorArchitecture offset is incorrect"); +static_assert(FIELD_OFFSET(KUSER_SHARED_DATA, NtMajorVersion) == 0x26c, "KUSER_SHARED_DATA.NtMajorVersion offset is incorrect"); +static_assert(FIELD_OFFSET(KUSER_SHARED_DATA, NtMinorVersion) == 0x270, "KUSER_SHARED_DATA.NtMinorVersion offset is incorrect"); +static_assert(FIELD_OFFSET(KUSER_SHARED_DATA, ProcessorFeatures) == 0x274, "KUSER_SHARED_DATA.ProcessorFeatures offset is incorrect"); +static_assert(FIELD_OFFSET(KUSER_SHARED_DATA, MaximumUserModeAddressDeprecated) == 0x2b4, "KUSER_SHARED_DATA.MaximumUserModeAddressDeprecated offset is incorrect"); +static_assert(FIELD_OFFSET(KUSER_SHARED_DATA, SystemRangeStartDeprecated) == 0x2b8, "KUSER_SHARED_DATA.SystemRangeStartDeprecated offset is incorrect"); +static_assert(FIELD_OFFSET(KUSER_SHARED_DATA, TimeSlip) == 0x2bc, "KUSER_SHARED_DATA.TimeSlip offset is incorrect"); +static_assert(FIELD_OFFSET(KUSER_SHARED_DATA, AlternativeArchitecture) == 0x2c0, "KUSER_SHARED_DATA.AlternativeArchitecture offset is incorrect"); +static_assert(FIELD_OFFSET(KUSER_SHARED_DATA, SystemExpirationDate) == 0x2c8, "KUSER_SHARED_DATA.SystemExpirationDate offset is incorrect"); +static_assert(FIELD_OFFSET(KUSER_SHARED_DATA, SuiteMask) == 0x2d0, "KUSER_SHARED_DATA.SuiteMask offset is incorrect"); +static_assert(FIELD_OFFSET(KUSER_SHARED_DATA, KdDebuggerEnabled) == 0x2d4, "KUSER_SHARED_DATA.KdDebuggerEnabled offset is incorrect"); +static_assert(FIELD_OFFSET(KUSER_SHARED_DATA, MitigationPolicies) == 0x2d5, "KUSER_SHARED_DATA.MitigationPolicies offset is incorrect"); +static_assert(FIELD_OFFSET(KUSER_SHARED_DATA, CyclesPerYield) == 0x2d6, "KUSER_SHARED_DATA.CyclesPerYield offset is incorrect"); +static_assert(FIELD_OFFSET(KUSER_SHARED_DATA, ActiveConsoleId) == 0x2d8, "KUSER_SHARED_DATA.ActiveConsoleId offset is incorrect"); +static_assert(FIELD_OFFSET(KUSER_SHARED_DATA, DismountCount) == 0x2dc, "KUSER_SHARED_DATA.DismountCount offset is incorrect"); +static_assert(FIELD_OFFSET(KUSER_SHARED_DATA, ComPlusPackage) == 0x2e0, "KUSER_SHARED_DATA.ComPlusPackage offset is incorrect"); +static_assert(FIELD_OFFSET(KUSER_SHARED_DATA, LastSystemRITEventTickCount) == 0x2e4, "KUSER_SHARED_DATA.LastSystemRITEventTickCount offset is incorrect"); +static_assert(FIELD_OFFSET(KUSER_SHARED_DATA, NumberOfPhysicalPages) == 0x2e8, "KUSER_SHARED_DATA.NumberOfPhysicalPages offset is incorrect"); +static_assert(FIELD_OFFSET(KUSER_SHARED_DATA, SafeBootMode) == 0x2ec, "KUSER_SHARED_DATA.SafeBootMode offset is incorrect"); +static_assert(FIELD_OFFSET(KUSER_SHARED_DATA, VirtualizationFlags) == 0x2ed, "KUSER_SHARED_DATA.VirtualizationFlags offset is incorrect"); +static_assert(FIELD_OFFSET(KUSER_SHARED_DATA, Reserved12) == 0x2ee, "KUSER_SHARED_DATA.Reserved12 offset is incorrect"); #if defined(_MSC_EXTENSIONS) -C_ASSERT(FIELD_OFFSET(KUSER_SHARED_DATA, SharedDataFlags) == 0x2f0); +static_assert(FIELD_OFFSET(KUSER_SHARED_DATA, SharedDataFlags) == 0x2f0, "KUSER_SHARED_DATA.SharedDataFlags offset is incorrect"); #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) == 0x318); // previously 0x310 +static_assert(FIELD_OFFSET(KUSER_SHARED_DATA, TestRetInstruction) == 0x2f8, "KUSER_SHARED_DATA.TestRetInstruction offset is incorrect"); +static_assert(FIELD_OFFSET(KUSER_SHARED_DATA, QpcFrequency) == 0x300, "KUSER_SHARED_DATA.QpcFrequency offset is incorrect"); +static_assert(FIELD_OFFSET(KUSER_SHARED_DATA, SystemCall) == 0x308, "KUSER_SHARED_DATA.SystemCall offset is incorrect"); +static_assert(FIELD_OFFSET(KUSER_SHARED_DATA, Reserved2) == 0x30c, "KUSER_SHARED_DATA.Reserved2 offset is incorrect"); +static_assert(FIELD_OFFSET(KUSER_SHARED_DATA, SystemCallPad) == 0x318, "KUSER_SHARED_DATA.SystemCallPad offset is incorrect (previously 0x310)"); #if defined(_MSC_EXTENSIONS) -C_ASSERT(FIELD_OFFSET(KUSER_SHARED_DATA, TickCount) == 0x320); -C_ASSERT(FIELD_OFFSET(KUSER_SHARED_DATA, TickCountQuad) == 0x320); +static_assert(FIELD_OFFSET(KUSER_SHARED_DATA, TickCount) == 0x320, "KUSER_SHARED_DATA.TickCount offset is incorrect"); +static_assert(FIELD_OFFSET(KUSER_SHARED_DATA, TickCountQuad) == 0x320, "KUSER_SHARED_DATA.TickCountQuad offset is incorrect"); #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, QpcReserved) == 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); +static_assert(FIELD_OFFSET(KUSER_SHARED_DATA, Cookie) == 0x330, "KUSER_SHARED_DATA.Cookie offset is incorrect"); +static_assert(FIELD_OFFSET(KUSER_SHARED_DATA, ConsoleSessionForegroundProcessId) == 0x338, "KUSER_SHARED_DATA.ConsoleSessionForegroundProcessId offset is incorrect"); +static_assert(FIELD_OFFSET(KUSER_SHARED_DATA, TimeUpdateLock) == 0x340, "KUSER_SHARED_DATA.TimeUpdateLock offset is incorrect"); +static_assert(FIELD_OFFSET(KUSER_SHARED_DATA, BaselineSystemTimeQpc) == 0x348, "KUSER_SHARED_DATA.BaselineSystemTimeQpc offset is incorrect"); +static_assert(FIELD_OFFSET(KUSER_SHARED_DATA, BaselineInterruptTimeQpc) == 0x350, "KUSER_SHARED_DATA.BaselineInterruptTimeQpc offset is incorrect"); +static_assert(FIELD_OFFSET(KUSER_SHARED_DATA, QpcSystemTimeIncrement) == 0x358, "KUSER_SHARED_DATA.QpcSystemTimeIncrement offset is incorrect"); +static_assert(FIELD_OFFSET(KUSER_SHARED_DATA, QpcInterruptTimeIncrement) == 0x360, "KUSER_SHARED_DATA.QpcInterruptTimeIncrement offset is incorrect"); +static_assert(FIELD_OFFSET(KUSER_SHARED_DATA, QpcSystemTimeIncrementShift) == 0x368, "KUSER_SHARED_DATA.QpcSystemTimeIncrementShift offset is incorrect"); +static_assert(FIELD_OFFSET(KUSER_SHARED_DATA, QpcInterruptTimeIncrementShift) == 0x369, "KUSER_SHARED_DATA.QpcInterruptTimeIncrementShift offset is incorrect"); +static_assert(FIELD_OFFSET(KUSER_SHARED_DATA, UnparkedProcessorCount) == 0x36a, "KUSER_SHARED_DATA.UnparkedProcessorCount offset is incorrect"); +static_assert(FIELD_OFFSET(KUSER_SHARED_DATA, EnclaveFeatureMask) == 0x36c, "KUSER_SHARED_DATA.EnclaveFeatureMask offset is incorrect"); +static_assert(FIELD_OFFSET(KUSER_SHARED_DATA, TelemetryCoverageRound) == 0x37c, "KUSER_SHARED_DATA.TelemetryCoverageRound offset is incorrect"); +static_assert(FIELD_OFFSET(KUSER_SHARED_DATA, UserModeGlobalLogger) == 0x380, "KUSER_SHARED_DATA.UserModeGlobalLogger offset is incorrect"); +static_assert(FIELD_OFFSET(KUSER_SHARED_DATA, ImageFileExecutionOptions) == 0x3a0, "KUSER_SHARED_DATA.ImageFileExecutionOptions offset is incorrect"); +static_assert(FIELD_OFFSET(KUSER_SHARED_DATA, LangGenerationCount) == 0x3a4, "KUSER_SHARED_DATA.LangGenerationCount offset is incorrect"); +static_assert(FIELD_OFFSET(KUSER_SHARED_DATA, Reserved4) == 0x3a8, "KUSER_SHARED_DATA.Reserved4 offset is incorrect"); +static_assert(FIELD_OFFSET(KUSER_SHARED_DATA, InterruptTimeBias) == 0x3b0, "KUSER_SHARED_DATA.InterruptTimeBias offset is incorrect"); +static_assert(FIELD_OFFSET(KUSER_SHARED_DATA, QpcBias) == 0x3b8, "KUSER_SHARED_DATA.QpcBias offset is incorrect"); +static_assert(FIELD_OFFSET(KUSER_SHARED_DATA, ActiveProcessorCount) == 0x3c0, "KUSER_SHARED_DATA.ActiveProcessorCount offset is incorrect"); +static_assert(FIELD_OFFSET(KUSER_SHARED_DATA, ActiveGroupCount) == 0x3c4, "KUSER_SHARED_DATA.ActiveGroupCount offset is incorrect"); +static_assert(FIELD_OFFSET(KUSER_SHARED_DATA, Reserved9) == 0x3c5, "KUSER_SHARED_DATA.Reserved9 offset is incorrect"); +static_assert(FIELD_OFFSET(KUSER_SHARED_DATA, QpcData) == 0x3c6, "KUSER_SHARED_DATA.QpcData offset is incorrect"); +static_assert(FIELD_OFFSET(KUSER_SHARED_DATA, QpcBypassEnabled) == 0x3c6, "KUSER_SHARED_DATA.QpcBypassEnabled offset is incorrect"); +static_assert(FIELD_OFFSET(KUSER_SHARED_DATA, QpcReserved) == 0x3c7, "KUSER_SHARED_DATA.QpcReserved offset is incorrect"); +static_assert(FIELD_OFFSET(KUSER_SHARED_DATA, TimeZoneBiasEffectiveStart) == 0x3c8, "KUSER_SHARED_DATA.TimeZoneBiasEffectiveStart offset is incorrect"); +static_assert(FIELD_OFFSET(KUSER_SHARED_DATA, TimeZoneBiasEffectiveEnd) == 0x3d0, "KUSER_SHARED_DATA.TimeZoneBiasEffectiveEnd offset is incorrect"); +static_assert(FIELD_OFFSET(KUSER_SHARED_DATA, XState) == 0x3d8, "KUSER_SHARED_DATA.XState offset is incorrect"); #if !defined(NTDDI_WIN10_FE) || (NTDDI_VERSION < NTDDI_WIN10_FE) -C_ASSERT(FIELD_OFFSET(KUSER_SHARED_DATA, FeatureConfigurationChangeStamp) == 0x710); -C_ASSERT(FIELD_OFFSET(KUSER_SHARED_DATA, UserPointerAuthMask) == 0x720); +static_assert(FIELD_OFFSET(KUSER_SHARED_DATA, FeatureConfigurationChangeStamp) == 0x710, "KUSER_SHARED_DATA.FeatureConfigurationChangeStamp offset is incorrect"); +static_assert(FIELD_OFFSET(KUSER_SHARED_DATA, UserPointerAuthMask) == 0x720, "KUSER_SHARED_DATA.UserPointerAuthMask offset is incorrect"); #if defined(_ARM64_) -C_ASSERT(FIELD_OFFSET(KUSER_SHARED_DATA, XStateArm64) == 0x728); +static_assert(FIELD_OFFSET(KUSER_SHARED_DATA, XStateArm64) == 0x728, "KUSER_SHARED_DATA.XStateArm64 offset is incorrect"); #else -C_ASSERT(FIELD_OFFSET(KUSER_SHARED_DATA, Reserved10) == 0x728); +static_assert(FIELD_OFFSET(KUSER_SHARED_DATA, Reserved10) == 0x728, "KUSER_SHARED_DATA.Reserved10 offset is incorrect"); #endif #if !defined(WINDOWS_IGNORE_PACKING_MISMATCH) -C_ASSERT(sizeof(KUSER_SHARED_DATA) == 0xa70); +static_assert(sizeof(KUSER_SHARED_DATA) == 0xa70, "KUSER_SHARED_DATA size is incorrect (expected 0xa70)"); #endif #else -C_ASSERT(FIELD_OFFSET(KUSER_SHARED_DATA, FeatureConfigurationChangeStamp) == 0x720); -C_ASSERT(FIELD_OFFSET(KUSER_SHARED_DATA, UserPointerAuthMask) == 0x730); +static_assert(FIELD_OFFSET(KUSER_SHARED_DATA, FeatureConfigurationChangeStamp) == 0x720, "KUSER_SHARED_DATA.FeatureConfigurationChangeStamp offset is incorrect"); +static_assert(FIELD_OFFSET(KUSER_SHARED_DATA, UserPointerAuthMask) == 0x730, "KUSER_SHARED_DATA.UserPointerAuthMask offset is incorrect"); #if defined(_ARM64_) -C_ASSERT(FIELD_OFFSET(KUSER_SHARED_DATA, XStateArm64) == 0x738); +static_assert(FIELD_OFFSET(KUSER_SHARED_DATA, XStateArm64) == 0x738, "KUSER_SHARED_DATA.XStateArm64 offset is incorrect"); #else -C_ASSERT(FIELD_OFFSET(KUSER_SHARED_DATA, Reserved10) == 0x738); +static_assert(FIELD_OFFSET(KUSER_SHARED_DATA, Reserved10) == 0x738, "KUSER_SHARED_DATA.Reserved10 offset is incorrect"); #endif #if !defined(WINDOWS_IGNORE_PACKING_MISMATCH) -C_ASSERT(sizeof(KUSER_SHARED_DATA) == 0xa80); +static_assert(sizeof(KUSER_SHARED_DATA) == 0xa80, "KUSER_SHARED_DATA size is incorrect (expected 0xa80)"); #endif #endif +/** + * USER_SHARED_DATA pointer to the Windows KUSER_SHARED_DATA structure at its fixed + * user-mode mapping address (0x7FFE0000). + * + * The Windows kernel exposes a read-only data structure, mapped into every user-mode + * process at the fixed virtual address `0x7FFE0000`. This region contains frequently + * accessed system information and avoids the overhead of system calls for data that + * the kernel updates frequently. The mapping is always present and identical across + * all user processes, it provides a fast and efficient way to retrieve system state. + */ #define USER_SHARED_DATA ((KUSER_SHARED_DATA * const)0x7ffe0000) +/** + * The NtGetTickCount64 routine retrieves the number of milliseconds that have elapsed since the system was started. + * + * \return ULONGLONG The return value is the number of milliseconds that have elapsed since the system was started. + * \remarks The resolution of the NtGetTickCount64 function is limited to the resolution of the system timer, + * which is typically in the range of 10 milliseconds to 16 milliseconds. The resolution of the NtGetTickCount64 + * function is not affected by adjustments made by the GetSystemTimeAdjustment function. + * \see https://learn.microsoft.com/en-us/windows/win32/api/sysinfoapi/nf-sysinfoapi-gettickcount64 + */ FORCEINLINE ULONGLONG NtGetTickCount64( @@ -6723,6 +9042,17 @@ NtGetTickCount64( (UInt32x32To64(tickCount.HighPart, USER_SHARED_DATA->TickCountMultiplier) << 8); } +/** + * The NtGetTickCount routine retrieves the number of milliseconds that have elapsed since the system was started, up to 49.7 days. + * + * \return ULONG The return value is the number of milliseconds that have elapsed since the system was started. + * \remarks The elapsed time is stored as a ULONG value. Therefore, the time will wrap around to zero if the system + * is run continuously for 49.7 days. To avoid this problem, use the NtGetTickCount64 function. Otherwise, check + * for an overflow condition when comparing times. The resolution of the NtGetTickCount function is limited to + * the resolution of the system timer, which is typically in the range of 10 milliseconds to 16 milliseconds. + * The resolution of the NtGetTickCount function is not affected by adjustments made by the GetSystemTimeAdjustment function. + * \see https://learn.microsoft.com/en-us/windows/win32/api/sysinfoapi/nf-sysinfoapi-gettickcount + */ FORCEINLINE ULONG NtGetTickCount( @@ -6758,6 +9088,15 @@ NtGetTickCount( // Locale // +/** + * The NtQueryDefaultLocale routine retrieves the default locale identifier for either the user profile or the system. + * + * \param UserProfile If TRUE, retrieves the user default locale; otherwise, retrieves the system default locale. + * \param DefaultLocaleId A pointer that receives the resulting locale identifier (LCID). + * \return NTSTATUS Successful or errant status. + * \see https://learn.microsoft.com/en-us/windows/win32/api/winnls/nf-winnls-getsystemdefaultlocale + * \sa https://learn.microsoft.com/en-us/windows/win32/api/winnls/nf-winnls-getuserdefaultlocale + */ NTSYSCALLAPI NTSTATUS NTAPI @@ -6766,6 +9105,15 @@ NtQueryDefaultLocale( _Out_ PLCID DefaultLocaleId ); +/** + * The NtSetDefaultLocale routine sets the default locale identifier for either + * the user profile or the system. + * + * \param UserProfile If TRUE, sets the user default locale; otherwise, sets the system default locale. + * \param DefaultLocaleId The locale identifier (LCID) to set. + * \return NTSTATUS Successful or errant status. + * \see https://learn.microsoft.com/en-us/windows/win32/api/winnls/nf-winnls-setthreadlocale + */ NTSYSCALLAPI NTSTATUS NTAPI @@ -6774,6 +9122,13 @@ NtSetDefaultLocale( _In_ LCID DefaultLocaleId ); +/** + * The NtQueryInstallUILanguage routine retrieves the system's installed UI language identifier. + * + * \param InstallUILanguageId A pointer that receives the installed UI language identifier (LANGID). + * \return NTSTATUS Successful or errant status. + * \see https://learn.microsoft.com/en-us/windows/win32/api/winnls/nf-winnls-getsystemdefaultuilanguage + */ NTSYSCALLAPI NTSTATUS NTAPI @@ -6781,8 +9136,14 @@ NtQueryInstallUILanguage( _Out_ LANGID *InstallUILanguageId ); -#if (PHNT_VERSION >= PHNT_WINDOWS_VISTA) -// private +/** + * The NtFlushInstallUILanguage routine updates the system's installed UI + * language and optionally commits the change. + * + * \param InstallUILanguage The UI language identifier (LANGID) to set. + * \param SetComittedFlag If nonzero, commits the language change. + * \return NTSTATUS Successful or errant status. + */ NTSYSCALLAPI NTSTATUS NTAPI @@ -6790,8 +9151,14 @@ NtFlushInstallUILanguage( _In_ LANGID InstallUILanguage, _In_ ULONG SetComittedFlag ); -#endif // PHNT_VERSION >= PHNT_WINDOWS_VISTA +/** + * The NtQueryDefaultUILanguage routine retrieves the system's default UI language identifier. + * + * \param DefaultUILanguageId A pointer that receives the default UI language identifier (LANGID). + * \return NTSTATUS Successful or errant status. + * \see https://learn.microsoft.com/en-us/windows/win32/api/winnls/nf-winnls-getsystemdefaultuilanguage + */ NTSYSCALLAPI NTSTATUS NTAPI @@ -6799,6 +9166,12 @@ NtQueryDefaultUILanguage( _Out_ LANGID *DefaultUILanguageId ); +/** + * The NtSetDefaultUILanguage routine sets the system's default UI language identifier. + * + * \param DefaultUILanguageId The UI language identifier (LANGID) to set. + * \return NTSTATUS Successful or errant status. + */ NTSYSCALLAPI NTSTATUS NTAPI @@ -6806,22 +9179,23 @@ NtSetDefaultUILanguage( _In_ LANGID DefaultUILanguageId ); -#if (PHNT_VERSION >= PHNT_WINDOWS_VISTA) -// private +/** + * The NtIsUILanguageComitted routine determines whether the system UI language has been committed. + * \return NTSTATUS Successful or errant status. + */ NTSYSCALLAPI NTSTATUS NTAPI NtIsUILanguageComitted( VOID ); -#endif // PHNT_VERSION >= PHNT_WINDOWS_VISTA +// // NLS +// // begin_private -#if (PHNT_VERSION >= PHNT_WINDOWS_VISTA) - NTSYSCALLAPI NTSTATUS NTAPI @@ -6844,7 +9218,17 @@ NtGetNlsSectionPtr( ); #if (PHNT_VERSION < PHNT_WINDOWS_7) - +/** + * The NtAcquireCMFViewOwnership routine acquires ownership of the Code Map + * File (CMF) view and optionally replaces an existing ownership token. + * + * \param TimeStamp A pointer that receives the timestamp associated with the + * CMF view ownership. + * \param tokenTaken A pointer that receives TRUE if the caller successfully + * acquired the ownership token, or FALSE if another owner already held it. + * \param replaceExisting If TRUE, replaces any existing ownership token. + * \return NTSTATUS Successful or errant status. + */ NTSYSCALLAPI NTSTATUS NTAPI @@ -6854,15 +9238,101 @@ NtAcquireCMFViewOwnership( _In_ BOOLEAN replaceExisting ); +/** + * The NtReleaseCMFViewOwnership routine releases ownership of the Code Map + * File (CMF) view previously acquired by NtAcquireCMFViewOwnership. + * \return NTSTATUS Successful or errant status. + */ NTSYSCALLAPI NTSTATUS NTAPI NtReleaseCMFViewOwnership( VOID ); - #endif // PHNT_VERSION < PHNT_WINDOWS_7 +/** + * The `What` flags for NtMapCMFModule. + * The `What` parameter is a bitfield controlling: + * - Which CMF section to map + * - Access rights for CMFCheckAccess() + * - Whether to update CMF global flags + * - Page protection mode + * - CMF cache mode bits (propagate into CMFFlagsCache) + * + * These determine what access rights are checked and influence whether the mapping is allowed. + */ +#define CMF_ACCESS_DIRECTORY 0x00000002 // Access check for directory section. +#define CMF_ACCESS_SEGMENT 0x00000004 // Access check for segment section. +#define CMF_ACCESS_HITS 0x00000008 // Access check for hits section. +/** + * The `What` flags for NtMapCMFModule. + * These determine which CMF section is mapped and directly control the BaseAddress and ViewSizeOut outputs. + */ +#define CMF_OP_DIRECTORY 0x00000010 // Map directory section (Index ignored) // Affects: BaseAddress, ViewSizeOut +#define CMF_OP_SEGMENT 0x00000020 // Map segment section at Index // Affects: BaseAddress, ViewSizeOut +#define CMF_OP_HITS 0x00000100 // Map hits section (Index ignored) // Affects: BaseAddress, ViewSizeOut +/** + * The `What` flags for NtMapCMFModule. + * This affects the protection flags passed to MmMapViewOfSection, + * which ultimately influences the memory protections of the BaseAddress parameter. + */ +#define CMF_PROTECT_SPECIAL 0x00000040 // Changes protection from PAGE_READONLY to PAGE_WRITECOPY +/** + * The `What` flags for NtMapCMFModule. + * When this bit is set, the function does not map anything. + * Instead, it updates CMFFlagsCache and optionally modifies the directory header. + */ +#define CMF_UPDATE_FLAGS 0x00020000 // Enter flag-update mode // CacheFlagsOut parameter +/** + * The `What` flags for NtMapCMFModule. + * These bits are extracted from What and written into CMFFlagsCache. + * They determine global CMF behavior, including which modules are valid. + */ +#define CMF_FLAG_A 0x00040000 // May trigger directory header update +#define CMF_FLAG_B 0x00080000 // Enables directory update path +#define CMF_FLAG_C 0x00100000 // Enables segment unmap path +/** + * Flags for NtMapCMFModule. + * These bits strip all bits outside this mask: + */ +#define CMF_ALLOWED_MASK 0xFFFFFECF // All valid bits for What +/** + * Flags for NtMapCMFModule. + */ +typedef enum _CMF_WHAT_FLAGS +{ + // ---- Access rights (used by CMFCheckAccess) ---- + CmfAccessDirectory = 0x00000002, // Access check for directory + CmfAccessSegment = 0x00000004, // Access check for segment[Index] + CmfAccessHits = 0x00000008, // Access check for hits + // ---- Operation selection (controls BaseAddress + ViewSizeOut) ---- + CmfDirectoryOp = 0x00000010, // Map directory section + CmfSegmentOp = 0x00000020, // Map segment section at Index + CmfHitsOp = 0x00000100, // Map hits section + // ---- Memory protection modifier ---- + CmfSpecialProtect = 0x00000040, // Changes protection for MmMapViewOfSection + // ---- Flag update mode (affects CacheFlagsOut only) ---- + CmfUpdateFlags = 0x00020000, // Update CMFFlagsCache instead of mapping + // ---- CMF cache mode bits (propagate into CMFFlagsCache) ---- + CmfFlagA = 0x00040000, // May trigger directory header update + CmfFlagB = 0x00080000, // Enables directory update path + CmfFlagC = 0x00100000, // Enables segment unmap path +} CMF_WHAT_FLAGS; +DEFINE_ENUM_FLAG_OPERATORS(CMF_WHAT_FLAGS); + +/** + * The NtMapCMFModule routine maps a Code Map File (CMF) module into memory + * and returns information about the cached view. + * + * \param What Specifies the CMF operation to perform. + * \param Index The module index to map. Only valid for CmfSegmentOp operations. + * \param CacheIndexOut Optional pointer that receives the cache index. + * \param CacheFlagsOut Optional pointer that receives cache flags. + * \param ViewSizeOut Optional pointer that receives the size of the mapped view. + * \param BaseAddress Optional pointer that receives the base address of the mapped module. + * \return NTSTATUS Successful or errant status. + */ NTSYSCALLAPI NTSTATUS NTAPI @@ -6875,6 +9345,37 @@ NtMapCMFModule( _Out_opt_ PVOID *BaseAddress ); +/** + * Flags for NtGetMUIRegistryInfo. + * Only the values below are supported. Any other bit results in STATUS_INVALID_PARAMETER. + */ +typedef enum _MUI_REGISTRY_INFO_FLAGS +{ + MUIRegInfoQuery = 0x1, // Query or load the MUI registry info. + MUIRegInfoClear = 0x2, // Clear the cached MUI registry info. + MUIRegInfoCommit = 0x8 // Commit/update state (increments counter). +} MUI_REGISTRY_INFO_FLAGS; +DEFINE_ENUM_FLAG_OPERATORS(MUI_REGISTRY_INFO_FLAGS); + +/** + * Flags for NtGetMUIRegistryInfo. + * Only the values below are supported. Any other bit results in STATUS_INVALID_PARAMETER. + */ +#define MUI_REGINFO_QUERY 0x1 // Query or load the MUI registry info. +#define MUI_REGINFO_CLEAR 0x2 // Clear the cached MUI registry info. +#define MUI_REGINFO_COMMIT 0x8 // Commit/update state (increments counter). + +/** + * The NtGetMUIRegistryInfo routine retrieves Multilingual User Interface (MUI) + * configuration data from the system registry. + * + * \param Flags Flags that control the type of MUI information returned. + * \param DataSize On input, the size of the buffer pointed to by Data. + * On output, the required or actual size of the data returned. + * \param Data A pointer to the MUI registry information. + * \return NTSTATUS Successful or errant status. + * \remarks This routine is private and subject to change. + */ NTSYSCALLAPI NTSTATUS NTAPI @@ -6884,14 +9385,24 @@ NtGetMUIRegistryInfo( _Out_ PVOID Data ); -#endif // PHNT_VERSION >= PHNT_WINDOWS_VISTA - // end_private // // Global atoms // +/** + * The NtAddAtom routine adds a Unicode string to the system atom table and + * returns the corresponding atom identifier. + * + * \param AtomName A pointer to a Unicode string containing the atom name. + * \param Length The length, in bytes, of the string pointed to by AtomName. + * \param Atom An optional pointer that receives the resulting atom identifier. + * \return NTSTATUS Successful or errant status. + * \remarks If the atom already exists, its reference count is incremented and + * the existing atom identifier is returned. + * \see https://learn.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-addatomw + */ NTSYSCALLAPI NTSTATUS NTAPI @@ -6903,9 +9414,33 @@ NtAddAtom( #if (PHNT_VERSION >= PHNT_WINDOWS_8) +/** + * ATOM_FLAG_NONE indicates that the atom being created should be placed in + * the session-local atom table rather than the global atom table. + */ +#define ATOM_FLAG_NONE 0x0 +/** + * ATOM_FLAG_GLOBAL indicates that the atom being created should be placed in + * the global atom table rather than the session-local table. + * \remarks This flag is only valid starting with Windows 8 and later. + */ #define ATOM_FLAG_GLOBAL 0x2 // rev +/** + * The NtAddAtomEx routine adds a Unicode string to the system atom table with + * additional creation flags. + * + * \param AtomName A pointer to a Unicode string containing the atom name. + * \param Length The length, in bytes, of the string pointed to by AtomName. + * \param Atom An optional pointer that receives the resulting atom identifier. + * \param Flags A set of flags that control atom creation behavior. + * \return NTSTATUS Successful or errant status. + * \remarks ATOM_FLAG_GLOBAL may be used to create a global atom. + * Only ATOM_FLAG_GLOBAL and ATOM_FLAG_NONE are currently supported. + * Any other flag value results in STATUS_INVALID_PARAMETER. + * \see https://learn.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-addatomw + */ NTSYSCALLAPI NTSTATUS NTAPI @@ -6918,6 +9453,16 @@ NtAddAtomEx( #endif // PHNT_VERSION >= PHNT_WINDOWS_8 +/** + * The NtFindAtom routine retrieves the atom identifier associated with a + * Unicode string in the system atom table. + * + * \param AtomName A pointer to a Unicode string containing the atom name. + * \param Length The length, in bytes, of the string pointed to by AtomName. + * \param Atom An optional pointer that receives the atom identifier if found. + * \return NTSTATUS Successful or errant status. + * \see https://learn.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-findatomw + */ NTSYSCALLAPI NTSTATUS NTAPI @@ -6927,6 +9472,16 @@ NtFindAtom( _Out_opt_ PRTL_ATOM Atom ); +/** + * The NtDeleteAtom routine decrements the reference count of an atom and + * removes it from the system atom table when the count reaches zero. + * + * \param Atom The atom identifier to delete. + * \return NTSTATUS Successful or errant status. + * \remarks If the atom is still referenced elsewhere, it is not removed until + * its reference count reaches zero. + * \see https://learn.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-deleteatom + */ NTSYSCALLAPI NTSTATUS NTAPI @@ -6934,26 +9489,46 @@ NtDeleteAtom( _In_ RTL_ATOM Atom ); +/** + * The ATOM_INFORMATION_CLASS enumeration specifies the type of information + * returned when querying atom table data. + */ typedef enum _ATOM_INFORMATION_CLASS { AtomBasicInformation, AtomTableInformation } ATOM_INFORMATION_CLASS; +/** + * The ATOM_BASIC_INFORMATION structure contains basic information about an Atom. + */ typedef struct _ATOM_BASIC_INFORMATION { - USHORT UsageCount; - USHORT Flags; - USHORT NameLength; - _Field_size_bytes_(NameLength) WCHAR Name[1]; + USHORT UsageCount; // The number of times the atom is referenced. + USHORT Flags; // Flags associated with the atom. */ + USHORT NameLength; // Length, in bytes, of the atom's name. + _Field_size_bytes_(NameLength) WCHAR Name[1]; // The atom's name (not null-terminated). } ATOM_BASIC_INFORMATION, *PATOM_BASIC_INFORMATION; +/** + * The ATOM_TABLE_INFORMATION structure contains information about all Atoms from the system atom table. + */ typedef struct _ATOM_TABLE_INFORMATION { - ULONG NumberOfAtoms; - _Field_size_(NumberOfAtoms) RTL_ATOM Atoms[1]; + ULONG NumberOfAtoms; // The number of atoms in the atom table. + _Field_size_(NumberOfAtoms) RTL_ATOM Atoms[1]; // Array of atom identifiers. } ATOM_TABLE_INFORMATION, *PATOM_TABLE_INFORMATION; +/** + * The NtQueryInformationAtom routine retrieves information about a specified atom in the system atom table. + * + * \param Atom The atom identifier for which information is being queried. + * \param AtomInformationClass Specifies the type of information to retrieve. This is an ATOM_INFORMATION_CLASS value. + * \param AtomInformation A pointer to a buffer that receives the requested information. + * \param AtomInformationLength The size, in bytes, of the AtomInformation buffer. + * \param ReturnLength Optional pointer to a variable that receives the number of bytes written to the AtomInformation buffer. + * \return NTSTATUS Successful or errant status. + */ NTSYSCALLAPI NTSTATUS NTAPI @@ -6973,42 +9548,34 @@ NtQueryInformationAtom( #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_LDR_TOP_DOWN 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 | \ @@ -7047,24 +9614,46 @@ NtQueryInformationAtom( FLG_DISABLE_DBGPRINT | \ FLG_ENABLE_HANDLE_EXCEPTIONS) +// // Licensing -#if (PHNT_VERSION >= PHNT_WINDOWS_VISTA) +// + +/** + * The NtQueryLicenseValue routine retrieves a licensing-related value from the + * system licensing database. + * + * \param ValueName A pointer to a UNICODE_STRING structure that contains the name of the license value to query. + * \param Type An optional pointer that receives the type of the returned data. + * \param Data An optional buffer that receives the value data. + * \param DataSize The size, in bytes, of the buffer pointed to by Data. + * \param ResultDataSize A pointer that receives the number of bytes required to store the complete value data. + * \return NTSTATUS Successful or errant status. + * \see https://learn.microsoft.com/en-us/windows/win32/api/slpublic/nf-slpublic-slquerylicensevaluefromapp + */ NTSYSCALLAPI NTSTATUS NTAPI NtQueryLicenseValue( - _In_ PUNICODE_STRING ValueName, + _In_ PCUNICODE_STRING ValueName, _Out_opt_ PULONG Type, _Out_writes_bytes_to_opt_(DataSize, *ResultDataSize) PVOID Data, _In_ ULONG DataSize, _Out_ PULONG ResultDataSize ); -#endif // // Misc. // +/** + * The NtSetDefaultHardErrorPort routine sets the system's default hard error + * port, which is used by the kernel to deliver hard error notifications to a + * user-mode process. + * + * \param DefaultHardErrorPort A handle to a port object that will receive + * hard error messages generated by the system. + * \return NTSTATUS Successful or errant status. + */ NTSYSCALLAPI NTSTATUS NTAPI @@ -7072,6 +9661,9 @@ NtSetDefaultHardErrorPort( _In_ HANDLE DefaultHardErrorPort ); +/** + * The SHUTDOWN_ACTION enumeration specifies the type of system shutdown to perform. + */ typedef enum _SHUTDOWN_ACTION { ShutdownNoReboot, @@ -7080,6 +9672,15 @@ typedef enum _SHUTDOWN_ACTION ShutdownRebootForRecovery // since WIN11 } SHUTDOWN_ACTION; +/** + * The NtShutdownSystem routine initiates a system shutdown using the specified + * shutdown action. + * + * \param Action A SHUTDOWN_ACTION value that specifies whether the system + * should halt, reboot, power off, or reboot for recovery. + * \return NTSTATUS Successful or errant status. + * \remarks The calling process must have the SE_SHUTDOWN_NAME privilege. + */ NTSYSCALLAPI NTSTATUS NTAPI @@ -7087,24 +9688,38 @@ NtShutdownSystem( _In_ SHUTDOWN_ACTION Action ); +/** + * The NtDisplayString routine displays a Unicode string on the system display + * during early boot or in environments where a console is not yet available. + * + * \param String A pointer to a UNICODE_STRING structure that contains the text to display. + * \return NTSTATUS Successful or errant status. + */ NTSYSCALLAPI NTSTATUS NTAPI NtDisplayString( - _In_ PUNICODE_STRING String + _In_ PCUNICODE_STRING String ); +// // Boot graphics +// -#if (PHNT_VERSION >= PHNT_WINDOWS_7) // rev +/** + * The NtDrawText routine displays a Unicode string on the system display during + * early boot or in environments where a standard console is not yet available. + * + * \param Text A pointer to a UNICODE_STRING structure that contains the text to draw on the screen. + * \return NTSTATUS Successful or errant status. + */ NTSYSCALLAPI NTSTATUS NTAPI NtDrawText( - _In_ PUNICODE_STRING Text + _In_ PCUNICODE_STRING Text ); -#endif // // Hot patching @@ -7126,103 +9741,146 @@ typedef enum _HOT_PATCH_INFORMATION_CLASS ManageHotPatchMax } HOT_PATCH_INFORMATION_CLASS; +/** + * The HOT_PATCH_IMAGE_INFO structure contains identifying information about a hot patch image. + */ typedef struct _HOT_PATCH_IMAGE_INFO { - ULONG CheckSum; - ULONG TimeDateStamp; + ULONG CheckSum; // The checksum of the hot patch image. + ULONG TimeDateStamp; // The time/date stamp of the hot patch image. } HOT_PATCH_IMAGE_INFO, *PHOT_PATCH_IMAGE_INFO; +#define MANAGE_HOT_PATCH_LOAD_PATCH_VERSION 1 + +/** + * The MANAGE_HOT_PATCH_LOAD_PATCH structure describes parameters for loading a hot patch. + */ typedef struct _MANAGE_HOT_PATCH_LOAD_PATCH { - ULONG Version; - UNICODE_STRING PatchPath; + ULONG Version; // Structure version. Must be MANAGE_HOT_PATCH_LOAD_PATCH_VERSION. + UNICODE_STRING PatchPath; // The path to the hot patch file. union { - SID Sid; - UCHAR Buffer[SECURITY_MAX_SID_SIZE]; + SID Sid; // The SID of the user for whom the patch is being loaded. + UCHAR Buffer[SECURITY_MAX_SID_SIZE]; // Buffer for the SID. } UserSid; - HOT_PATCH_IMAGE_INFO BaseInfo; + HOT_PATCH_IMAGE_INFO BaseInfo; // Identifying information about the base image to patch. } MANAGE_HOT_PATCH_LOAD_PATCH, *PMANAGE_HOT_PATCH_LOAD_PATCH; +#define MANAGE_HOT_PATCH_UNLOAD_PATCH_VERSION 1 + +/** + * The MANAGE_HOT_PATCH_UNLOAD_PATCH structure describes parameters for unloading a hot patch. + */ typedef struct _MANAGE_HOT_PATCH_UNLOAD_PATCH { - ULONG Version; - HOT_PATCH_IMAGE_INFO BaseInfo; + ULONG Version; // Structure version. Must be MANAGE_HOT_PATCH_UNLOAD_PATCH_VERSION. + HOT_PATCH_IMAGE_INFO BaseInfo; // Identifying information about the base image to unpatch. union { - SID Sid; - UCHAR Buffer[SECURITY_MAX_SID_SIZE]; + SID Sid; // The SID of the user for whom the patch is being unloaded. + UCHAR Buffer[SECURITY_MAX_SID_SIZE]; // Buffer for the SID. } UserSid; } MANAGE_HOT_PATCH_UNLOAD_PATCH, *PMANAGE_HOT_PATCH_UNLOAD_PATCH; +#define MANAGE_HOT_PATCH_QUERY_PATCHES_VERSION 1 + +/** + * The MANAGE_HOT_PATCH_QUERY_PATCHES structure is used to query information about loaded hot patches. + */ typedef struct _MANAGE_HOT_PATCH_QUERY_PATCHES { - ULONG Version; + ULONG Version; // Structure version. Must be MANAGE_HOT_PATCH_QUERY_PATCHES_VERSION. union { - SID Sid; - UCHAR Buffer[SECURITY_MAX_SID_SIZE]; + SID Sid; // The SID of the user whose patches are being queried. + UCHAR Buffer[SECURITY_MAX_SID_SIZE]; // Buffer for the SID. } UserSid; - ULONG PatchCount; - PUNICODE_STRING PatchPathStrings; - PHOT_PATCH_IMAGE_INFO BaseInfos; + ULONG PatchCount; // The number of patches found. + PUNICODE_STRING PatchPathStrings; // Pointer to an array of patch path strings. + PHOT_PATCH_IMAGE_INFO BaseInfos; // Pointer to an array of patch image info structures. } MANAGE_HOT_PATCH_QUERY_PATCHES, *PMANAGE_HOT_PATCH_QUERY_PATCHES; +#define MANAGE_HOT_PATCH_QUERY_ACTIVE_PATCHES_VERSION 1 + +/** + * The MANAGE_HOT_PATCH_QUERY_ACTIVE_PATCHES structure is used to query active hot patches for a process. + */ typedef struct _MANAGE_HOT_PATCH_QUERY_ACTIVE_PATCHES { - ULONG Version; - HANDLE ProcessHandle; - ULONG PatchCount; - PUNICODE_STRING PatchPathStrings; - PHOT_PATCH_IMAGE_INFO BaseInfos; - PULONG PatchSequenceNumbers; + ULONG Version; // Structure version. Must be MANAGE_HOT_PATCH_QUERY_ACTIVE_PATCHES_VERSION. + HANDLE ProcessHandle; // Handle to the process being queried. + ULONG PatchCount; // The number of active patches. + PUNICODE_STRING PatchPathStrings; // Pointer to an array of patch path strings. + PHOT_PATCH_IMAGE_INFO BaseInfos; // Pointer to an array of patch image info structures. + PULONG PatchSequenceNumbers; // Pointer to an array of patch sequence numbers. } MANAGE_HOT_PATCH_QUERY_ACTIVE_PATCHES, *PMANAGE_HOT_PATCH_QUERY_ACTIVE_PATCHES; +#define MANAGE_HOT_PATCH_APPLY_IMAGE_PATCH_VERSION 1 + +/** + * The MANAGE_HOT_PATCH_APPLY_IMAGE_PATCH structure describes parameters for applying a hot patch to an image. + */ typedef struct _MANAGE_HOT_PATCH_APPLY_IMAGE_PATCH { - ULONG Version; + ULONG Version; // Structure version. Must be MANAGE_HOT_PATCH_APPLY_IMAGE_PATCH_VERSION. union { + ULONG AllFlags; // All flags as a ULONG. struct { - ULONG ApplyReversePatches : 1; - ULONG ApplyForwardPatches : 1; + ULONG ApplyReversePatches : 1; // If set, apply reverse patches. + ULONG ApplyForwardPatches : 1; // If set, apply forward patches. ULONG Spare : 29; }; - ULONG AllFlags; }; - HANDLE ProcessHandle; - PVOID BaseImageAddress; - PVOID PatchImageAddress; + HANDLE ProcessHandle; // Handle to the process to patch. + PVOID BaseImageAddress; // Base address of the image to patch. + PVOID PatchImageAddress; // Address of the patch image. } MANAGE_HOT_PATCH_APPLY_IMAGE_PATCH, *PMANAGE_HOT_PATCH_APPLY_IMAGE_PATCH; +#define MANAGE_HOT_PATCH_QUERY_SINGLE_PATCH_VERSION 1 + +/** + * The MANAGE_HOT_PATCH_QUERY_SINGLE_PATCH structure is used to query a single hot patch. + */ typedef struct _MANAGE_HOT_PATCH_QUERY_SINGLE_PATCH { - ULONG Version; - HANDLE ProcessHandle; - PVOID BaseAddress; - ULONG Flags; - UNICODE_STRING PatchPathString; + ULONG Version; // Structure version. Must be MANAGE_HOT_PATCH_QUERY_SINGLE_PATCH_VERSION. + HANDLE ProcessHandle; // Handle to the process being queried. + PVOID BaseAddress; // Base address of the image being queried. + ULONG Flags; // Query flags. + UNICODE_STRING PatchPathString; // The path to the patch being queried. } MANAGE_HOT_PATCH_QUERY_SINGLE_PATCH, *PMANAGE_HOT_PATCH_QUERY_SINGLE_PATCH; +#define MANAGE_HOT_PATCH_CHECK_ENABLED_VERSION 1 + +/** + * The MANAGE_HOT_PATCH_CHECK_ENABLED structure is used to check if hot patching is enabled. + */ typedef struct _MANAGE_HOT_PATCH_CHECK_ENABLED { - ULONG Version; - ULONG Flags; + ULONG Version; // Structure version. Must be MANAGE_HOT_PATCH_CHECK_ENABLED_VERSION. + ULONG Flags; // Flags for the check operation. } MANAGE_HOT_PATCH_CHECK_ENABLED, *PMANAGE_HOT_PATCH_CHECK_ENABLED; +#define MANAGE_HOT_PATCH_CREATE_PATCH_SECTION_VERSION 1 + +/** + * The MANAGE_HOT_PATCH_CREATE_PATCH_SECTION structure describes parameters for creating a hot patch section. + */ typedef struct _MANAGE_HOT_PATCH_CREATE_PATCH_SECTION { - ULONG Version; - ULONG Flags; - ACCESS_MASK DesiredAccess; - ULONG PageProtection; - ULONG AllocationAttributes; - PVOID BaseImageAddress; - HANDLE SectionHandle; + ULONG Version; // Structure version. Must be MANAGE_HOT_PATCH_CREATE_PATCH_SECTION_VERSION. + ULONG Flags; // Creation flags. + ACCESS_MASK DesiredAccess; // Desired access mask for the section. + ULONG PageProtection; // Page protection flags. + ULONG AllocationAttributes; // Allocation attributes. + PVOID BaseImageAddress; // Base address of the image for the patch section. + HANDLE SectionHandle; // Handle to the created section. } MANAGE_HOT_PATCH_CREATE_PATCH_SECTION, *PMANAGE_HOT_PATCH_CREATE_PATCH_SECTION; -#ifdef WIN64 +#if defined(_WIN64) static_assert(sizeof(MANAGE_HOT_PATCH_LOAD_PATCH) == 0x68, "Size of MANAGE_HOT_PATCH_LOAD_PATCH is incorrect"); static_assert(sizeof(MANAGE_HOT_PATCH_UNLOAD_PATCH) == 0x50, "Size of MANAGE_HOT_PATCH_UNLOAD_PATCH is incorrect"); static_assert(sizeof(MANAGE_HOT_PATCH_QUERY_PATCHES) == 0x60, "Size of MANAGE_HOT_PATCH_QUERY_PATCHES is incorrect"); @@ -7231,10 +9889,19 @@ static_assert(sizeof(MANAGE_HOT_PATCH_APPLY_IMAGE_PATCH) == 0x20, "Size of MANAG static_assert(sizeof(MANAGE_HOT_PATCH_QUERY_SINGLE_PATCH) == 0x30, "Size of MANAGE_HOT_PATCH_QUERY_SINGLE_PATCH is incorrect"); static_assert(sizeof(MANAGE_HOT_PATCH_CHECK_ENABLED) == 0x8, "Size of MANAGE_HOT_PATCH_CHECK_ENABLED is incorrect"); static_assert(sizeof(MANAGE_HOT_PATCH_CREATE_PATCH_SECTION) == 0x28, "Size of MANAGE_HOT_PATCH_CREATE_PATCH_SECTION is incorrect"); -#endif +#endif // WIN64 #if (PHNT_VERSION >= PHNT_WINDOWS_11) // rev +/** + * The NtManageHotPatch routine manages hot patching operations in the system. + * + * \param[in] HotPatchInformationClass Specifies the type of hot patch information being queried or set. + * \param[out] HotPatchInformation A pointer to a buffer that receives or contains the hot patch information, depending on the operation. + * \param[in] HotPatchInformationLength The size, in bytes, of the HotPatchInformation buffer. + * \param[out] ReturnLength Optional pointer to a variable that receives the number of bytes written to the HotPatchInformation buffer. + * \return NTSTATUS Successful or errant status. + */ NTSYSCALLAPI NTSTATUS NTAPI @@ -7248,4 +9915,4 @@ NtManageHotPatch( #endif // (PHNT_MODE != PHNT_MODE_KERNEL) -#endif +#endif // _NTEXAPI_H diff --git a/ntgdi.h b/ntgdi.h index bf70b71..08e08ef 100644 --- a/ntgdi.h +++ b/ntgdi.h @@ -36,7 +36,9 @@ #define GDI_MAKE_HANDLE(Index, Unique) ((ULONG)(((ULONG)(Unique) << GDI_HANDLE_INDEX_BITS) | (ULONG)(Index))) +// // GDI server-side types +// #define GDI_DEF_TYPE 0 // invalid handle #define GDI_DC_TYPE 1 @@ -70,7 +72,9 @@ #define GDI_DCIOBJ_TYPE 29 // unused #define GDI_SPOOL_TYPE 30 +// // GDI client-side types +// #define GDI_CLIENT_TYPE_FROM_HANDLE(Handle) ((ULONG)(Handle) & ((GDI_HANDLE_ALTTYPE_MASK << GDI_HANDLE_ALTTYPE_SHIFT) | \ (GDI_HANDLE_TYPE_MASK << GDI_HANDLE_TYPE_SHIFT))) @@ -124,4 +128,4 @@ typedef struct _GDI_SHARED_MEMORY GDI_HANDLE_ENTRY Handles[GDI_MAX_HANDLE_COUNT]; } GDI_SHARED_MEMORY, *PGDI_SHARED_MEMORY; -#endif +#endif // _NTGDI_H diff --git a/ntimage.h b/ntimage.h index f73e69d..2527ee0 100644 --- a/ntimage.h +++ b/ntimage.h @@ -7,14 +7,15 @@ #ifndef _NTIMAGE_H #define _NTIMAGE_H -#include - #if (PHNT_MODE != PHNT_MODE_KERNEL) #define IMAGE_FILE_MACHINE_CHPE_X86 0x3A64 #define IMAGE_FILE_MACHINE_ARM64EC 0xA641 #define IMAGE_FILE_MACHINE_ARM64X 0xA64E -#endif +#endif // (PHNT_MODE != PHNT_MODE_KERNEL) +/** + * The IMAGE_DEBUG_POGO_ENTRY structure represents a POGO (Profile Guided Optimization) entry. + */ typedef struct _IMAGE_DEBUG_POGO_ENTRY { ULONG Rva; @@ -22,20 +23,32 @@ typedef struct _IMAGE_DEBUG_POGO_ENTRY CHAR Name[1]; } IMAGE_DEBUG_POGO_ENTRY, *PIMAGE_DEBUG_POGO_ENTRY; +/** + * The IMAGE_DEBUG_POGO_SIGNATURE structure represents a POGO signature. + */ 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_PGI 'PGI\0' // coffgrp PGI (0x50474900) +#define IMAGE_DEBUG_POGO_SIGNATURE_PGO 'PGO\0' // coffgrp PGO (0x50474F00) #define IMAGE_DEBUG_POGO_SIGNATURE_PGU 'PGU\0' // coffgrp PGU (0x50475500) +#define IMAGE_DEBUG_POGO_SIGNATURE_SPGO 'SPGO' // coffgrp SPGO (0x5350474F) +/** + * The IMAGE_RELOCATION_RECORD structure represents a relocation record. + */ typedef struct _IMAGE_RELOCATION_RECORD { USHORT Offset : 12; USHORT Type : 4; } IMAGE_RELOCATION_RECORD, *PIMAGE_RELOCATION_RECORD; +/** + * The IMAGE_CHPE_METADATA_X86 structure represents CHPE (Compiled Hybrid Portable Executable) metadata for x86. + */ typedef struct _IMAGE_CHPE_METADATA_X86 { ULONG Version; @@ -52,6 +65,9 @@ typedef struct _IMAGE_CHPE_METADATA_X86 ULONG WowA64RdtscFunctionPointer; // Present if Version >= 3 } IMAGE_CHPE_METADATA_X86, *PIMAGE_CHPE_METADATA_X86; +/** + * The IMAGE_CHPE_RANGE_ENTRY structure represents a CHPE range entry. + */ typedef struct _IMAGE_CHPE_RANGE_ENTRY { union @@ -67,6 +83,9 @@ typedef struct _IMAGE_CHPE_RANGE_ENTRY ULONG Length; } IMAGE_CHPE_RANGE_ENTRY, *PIMAGE_CHPE_RANGE_ENTRY; +/** + * The IMAGE_ARM64EC_METADATA structure represents ARM64EC metadata. + */ typedef struct _IMAGE_ARM64EC_METADATA { ULONG Version; @@ -97,6 +116,9 @@ typedef struct _IMAGE_ARM64EC_METADATA #define IMAGE_ARM64EC_CODE_MAP_TYPE_AMD64 2 // rev +/** + * The IMAGE_ARM64EC_CODE_MAP_ENTRY structure represents an ARM64EC code map entry. + */ typedef struct _IMAGE_ARM64EC_CODE_MAP_ENTRY { union @@ -112,12 +134,18 @@ typedef struct _IMAGE_ARM64EC_CODE_MAP_ENTRY ULONG Length; } IMAGE_ARM64EC_CODE_MAP_ENTRY, *PIMAGE_ARM64EC_CODE_MAP_ENTRY; +/** + * The IMAGE_ARM64EC_REDIRECTION_ENTRY structure represents an ARM64EC redirection entry. + */ typedef struct _IMAGE_ARM64EC_REDIRECTION_ENTRY { ULONG Source; ULONG Destination; } IMAGE_ARM64EC_REDIRECTION_ENTRY, *PIMAGE_ARM64EC_REDIRECTION_ENTRY; +/** + * The IMAGE_ARM64EC_CODE_RANGE_ENTRY_POINT structure represents an ARM64EC code range entry point. + */ typedef struct _IMAGE_ARM64EC_CODE_RANGE_ENTRY_POINT { ULONG StartRva; @@ -133,6 +161,9 @@ typedef struct _IMAGE_ARM64EC_CODE_RANGE_ENTRY_POINT #define IMAGE_DVRT_ARM64X_FIXUP_SIZE_4BYTES 2 #define IMAGE_DVRT_ARM64X_FIXUP_SIZE_8BYTES 3 +/** + * The IMAGE_DVRT_ARM64X_FIXUP_RECORD structure represents an ARM64X fixup record. + */ typedef struct _IMAGE_DVRT_ARM64X_FIXUP_RECORD { USHORT Offset : 12; @@ -141,6 +172,9 @@ typedef struct _IMAGE_DVRT_ARM64X_FIXUP_RECORD // Value of variable Size when IMAGE_DVRT_ARM64X_FIXUP_TYPE_VALUE } IMAGE_DVRT_ARM64X_FIXUP_RECORD, *PIMAGE_DVRT_ARM64X_FIXUP_RECORD; +/** + * The IMAGE_DVRT_ARM64X_DELTA_FIXUP_RECORD structure represents an ARM64X delta fixup record. + */ typedef struct _IMAGE_DVRT_ARM64X_DELTA_FIXUP_RECORD { USHORT Offset : 12; @@ -150,9 +184,55 @@ typedef struct _IMAGE_DVRT_ARM64X_DELTA_FIXUP_RECORD // USHORT Value; // Delta = Value * Scale * Sign } IMAGE_DVRT_ARM64X_DELTA_FIXUP_RECORD, *PIMAGE_DVRT_ARM64X_DELTA_FIXUP_RECORD; -#include +/** + * The IMAGE_IMPORT_CONTROL_TRANSFER_ARM64_RELOCATION structure represents an ARM64 import control transfer relocation. + * + * \remarks On ARM64, optimized imported functions use this structure for import control transfer relocations. + * This is used with IMAGE_DYNAMIC_RELOCATION_ARM64_KERNEL_IMPORT_CALL_TRANSFER. + */ +//typedef struct _IMAGE_IMPORT_CONTROL_TRANSFER_ARM64_RELOCATION +//{ +// ULONG PageRelativeOffset : 10; ///< Offset to the call instruction shifted right by 2 (4-byte aligned instruction) +// ULONG IndirectCall : 1; ///< 0 if target instruction is a BR, 1 if BLR +// ULONG RegisterIndex : 5; ///< Register index used for the indirect call/jump +// ULONG ImportType : 1; ///< 0 if this refers to a static import, 1 for delayload import +// ULONG IATIndex : 15; ///< IAT index of the corresponding import (0x7FFF indicates no index) +//} IMAGE_IMPORT_CONTROL_TRANSFER_ARM64_RELOCATION, *PIMAGE_IMPORT_CONTROL_TRANSFER_ARM64_RELOCATION; + +/** + * The IMAGE_PROLOGUE_DYNAMIC_RELOCATION_HEADER structure represents a prologue dynamic relocation header. + * + * \remarks This structure is followed by PrologueByteCount bytes containing the prologue code. + * Used with IMAGE_DYNAMIC_RELOCATION_GUARD_RF_PROLOGUE. + */ +//#include +//typedef struct _IMAGE_PROLOGUE_DYNAMIC_RELOCATION_HEADER +//{ +// UCHAR PrologueByteCount; +// // UCHAR PrologueBytes[PrologueByteCount]; +//} IMAGE_PROLOGUE_DYNAMIC_RELOCATION_HEADER, UNALIGNED *PIMAGE_PROLOGUE_DYNAMIC_RELOCATION_HEADER; +//#include + +/** + * The IMAGE_EPILOGUE_DYNAMIC_RELOCATION_HEADER structure represents an epilogue dynamic relocation header. + * + * \remarks This structure is followed by variable-length branch descriptor data. + * Used with IMAGE_DYNAMIC_RELOCATION_GUARD_RF_EPILOGUE. + */ +//#include +//typedef struct _IMAGE_EPILOGUE_DYNAMIC_RELOCATION_HEADER +//{ +// ULONG EpilogueCount; +// UCHAR EpilogueByteCount; +// UCHAR BranchDescriptorElementSize; +// USHORT BranchDescriptorCount; +// // UCHAR BranchDescriptors[...]; +// // UCHAR BranchDescriptorBitMap[...]; +//} IMAGE_EPILOGUE_DYNAMIC_RELOCATION_HEADER, UNALIGNED *PIMAGE_EPILOGUE_DYNAMIC_RELOCATION_HEADER; +//#include #define IMAGE_DYNAMIC_RELOCATION_ARM64X 0x00000006 +#define IMAGE_DYNAMIC_RELOCATION_ARM64_KERNEL_IMPORT_CALL_TRANSFER 0x00000008 #define IMAGE_DYNAMIC_RELOCATION_MM_SHARED_USER_DATA_VA 0x7FFE0000 #define IMAGE_DYNAMIC_RELOCATION_KI_USER_SHARED_DATA64 0xFFFFF78000000000UI64 @@ -172,32 +252,48 @@ typedef IMAGE_THUNK_DATA64 UNALIGNED* UNALIGNED_PIMAGE_THUNK_DATA64; #define IMAGE_DYNAMIC_RELOCATION_GUARD_SWITCHTABLE_BRANCH 0x00000005 #define IMAGE_DYNAMIC_RELOCATION_FUNCTION_OVERRIDE 0x00000007 -typedef struct _IMAGE_FUNCTION_OVERRIDE_HEADER { +/** + * The IMAGE_FUNCTION_OVERRIDE_HEADER structure represents a function override header. + */ +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 { +/** + * The IMAGE_BDD_INFO structure represents BDD (Binary Decision Diagram) information. + */ +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 { +/** + * The IMAGE_FUNCTION_OVERRIDE_DYNAMIC_RELOCATION structure represents a function override dynamic relocation. + */ +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 RvaSize; // Size in bytes taken by RVAs. Must be multiple of sizeof(ULONG). ULONG BaseRelocSize; // Size in bytes taken by BaseRelocs - // DWORD RVAs[RvaSize / sizeof(DWORD)]; // Array containing overriding func RVAs. + // ULONG RVAs[RvaSize / sizeof(ULONG)]; // 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 { +/** + * The IMAGE_BDD_DYNAMIC_RELOCATION structure represents a BDD 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 @@ -208,11 +304,11 @@ typedef struct _IMAGE_BDD_DYNAMIC_RELOCATION { #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 // !defined(NTDDI_WIN10_NI) || (NTDDI_VERSION < NTDDI_WIN10_NI) #if !defined(NTDDI_WIN11_GE) || (NTDDI_VERSION < NTDDI_WIN11_GE) #define IMAGE_DLLCHARACTERISTICS_EX_FORWARD_CFI_COMPAT 0x40 #define IMAGE_DLLCHARACTERISTICS_EX_HOTPATCH_COMPATIBLE 0x80 -#endif +#endif // !defined(NTDDI_WIN11_GE) || (NTDDI_VERSION < NTDDI_WIN11_GE) -#endif +#endif // _NTIMAGE_H diff --git a/ntintsafe.h b/ntintsafe.h index c0a49b8..8d0ac61 100644 --- a/ntintsafe.h +++ b/ntintsafe.h @@ -7,6 +7,7 @@ * Copyright (c) Microsoft Corp. All rights reserved. * * * ******************************************************************/ + #ifndef _NTINTSAFE_H_INCLUDED_ #define _NTINTSAFE_H_INCLUDED_ @@ -120,7 +121,7 @@ ULONG64 UnsignedMultiply128( _In_ ULONGLONG ullMultiplicand, _In_ ULONGLONG ullMultiplier, - _Out_ _Deref_out_range_(==, ullMultiplicand * ullMultiplier) ULONGLONG* pullResultHigh); + _Out_ ULONGLONG* pullResultHigh); // _Deref_out_range_(==, ullMultiplicand * ullMultiplier) #if !defined(_ARM64EC_) #pragma intrinsic(_umul128) @@ -6914,7 +6915,7 @@ RtlUShortAdd( #define RtlUInt16Add RtlUShortAdd // -// WORD addtition +// WORD addition // #define RtlWordAdd RtlUShortAdd diff --git a/ntioapi.h b/ntioapi.h index cfcbe76..5de7c51 100644 --- a/ntioapi.h +++ b/ntioapi.h @@ -7,14 +7,18 @@ #ifndef _NTIOAPI_H #define _NTIOAPI_H +// // Sharing mode +// #define FILE_SHARE_NONE 0x00000000 #define FILE_SHARE_READ 0x00000001 #define FILE_SHARE_WRITE 0x00000002 #define FILE_SHARE_DELETE 0x00000004 +// // Create disposition +// #define FILE_SUPERSEDE 0x00000000 #define FILE_OPEN 0x00000001 @@ -24,7 +28,9 @@ #define FILE_OVERWRITE_IF 0x00000005 #define FILE_MAXIMUM_DISPOSITION 0x00000005 +// // Create/open flags +// #define FILE_DIRECTORY_FILE 0x00000001 #define FILE_WRITE_THROUGH 0x00000002 @@ -58,12 +64,14 @@ #define TREE_CONNECT_WRITE_THROUGH 0x00000002 #define TREE_CONNECT_NO_CLIENT_BUFFERING 0x00000008 +// // Extended create/open flags +// #define FILE_CONTAINS_EXTENDED_CREATE_INFORMATION 0x10000000 #define FILE_VALID_EXTENDED_OPTION_FLAGS 0x10000000 -typedef struct _EXTENDED_CREATE_DUAL_OPLOCK_KEYS +typedef struct _EXTENDED_CREATE_DUAL_OPLOCK_KEYS { // // Parent oplock key. @@ -138,7 +146,9 @@ typedef struct _EXTENDED_CREATE_INFORMATION_32 #define MAXIMUM_FILENAME_LENGTH 256 +// // Extended attributes +// #define FILE_NEED_EA 0x00000080 @@ -153,7 +163,9 @@ typedef struct _EXTENDED_CREATE_INFORMATION_32 #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 @@ -173,7 +185,9 @@ typedef struct _EXTENDED_CREATE_INFORMATION_32 #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 @@ -208,7 +222,9 @@ typedef struct _EXTENDED_CREATE_INFORMATION_32 // Win32 pipe instance limit (0xff) #define FILE_PIPE_UNLIMITED_INSTANCES 0xffffffff +// // Mailslot values +// #define MAILSLOT_SIZE_AUTO 0 @@ -230,104 +246,105 @@ VOID NTAPI IO_APC_ROUTINE( ); typedef IO_APC_ROUTINE* PIO_APC_ROUTINE; -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 - FileStatBasicInformation, // since 23H2 - FileId64ExtdDirectoryInformation, // FILE_ID_64_EXTD_DIR_INFORMATION - FileId64ExtdBothDirectoryInformation, // FILE_ID_64_EXTD_BOTH_DIR_INFORMATION - FileIdAllExtdDirectoryInformation, // FILE_ID_ALL_EXTD_DIR_INFORMATION - FileIdAllExtdBothDirectoryInformation, // FILE_ID_ALL_EXTD_BOTH_DIR_INFORMATION - FileStreamReservationInformation, // FILE_STREAM_RESERVATION_INFORMATION // since 24H2 - FileMupProviderInfo, // MUP_PROVIDER_INFORMATION - FileMaximumInformation -} FILE_INFORMATION_CLASS, *PFILE_INFORMATION_CLASS; - // // NtQueryInformationFile/NtSetInformationFile types // +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, // qs: 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 (requires FILE_READ_EA) + 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, // qs: FILE_POSITION_INFORMATION (q: requires FILE_READ_ATTRIBUTES; s: requires FILE_WRITE_ATTRIBUTES) + FileFullEaInformation, // q: FILE_FULL_EA_INFORMATION (requires FILE_READ_EA) + FileModeInformation, // qs: FILE_MODE_INFORMATION (q: requires FILE_READ_ATTRIBUTES; s: requires FILE_WRITE_ATTRIBUTES) + FileAlignmentInformation, // q: FILE_ALIGNMENT_INFORMATION + FileAllInformation, // q: FILE_ALL_INFORMATION + 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, // qs: FILE_PIPE_INFORMATION (q: requires FILE_READ_ATTRIBUTES; s: requires FILE_WRITE_ATTRIBUTES) + FilePipeLocalInformation, // q: FILE_PIPE_LOCAL_INFORMATION + FilePipeRemoteInformation, // qs: 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 + FileAttributeTagInformation, // q: FILE_ATTRIBUTE_TAG_INFORMATION + 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, // qs: FILE_IO_COMPLETION_NOTIFICATION_INFORMATION (q: requires FILE_READ_ATTRIBUTES; s: requires FILE_WRITE_ATTRIBUTES) // since VISTA + FileIoStatusBlockRangeInformation, // s: FILE_IOSTATUSBLOCK_RANGE_INFORMATION (requires SeLockMemoryPrivilege) + FileIoPriorityHintInformation, // qs: FILE_IO_PRIORITY_HINT_INFORMATION, FILE_IO_PRIORITY_HINT_INFORMATION_EX (q: requires FILE_READ_DATA) + FileSfioReserveInformation, // qs: FILE_SFIO_RESERVE_INFORMATION (q: requires FILE_READ_DATA) + FileSfioVolumeInformation, // q: FILE_SFIO_VOLUME_INFORMATION + FileHardLinkInformation, // q: FILE_LINKS_INFORMATION + FileProcessIdsUsingFileInformation, // q: FILE_PROCESS_IDS_USING_FILE_INFORMATION + 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 + FileUnusedInformation, // q: + FileNumaNodeInformation, // q: FILE_NUMA_NODE_INFORMATION + FileStandardLinkInformation, // q: FILE_STANDARD_LINK_INFORMATION + FileRemoteProtocolInformation, // q: FILE_REMOTE_PROTOCOL_INFORMATION + FileRenameInformationBypassAccessCheck, // s: FILE_RENAME_INFORMATION // (kernel-mode only) // since WIN8 + FileLinkInformationBypassAccessCheck, // s: FILE_LINK_INFORMATION // (kernel-mode only) + 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, // s: FILE_RENAME_INFORMATION_EX // (kernel-mode only) + FileDesiredStorageClassInformation, // qs: FILE_DESIRED_STORAGE_CLASS_INFORMATION // since REDSTONE2 + FileStatInformation, // q: FILE_STAT_INFORMATION + 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, // qs: FILE_CASE_SENSITIVE_INFORMATION + FileLinkInformationEx, // s: FILE_LINK_INFORMATION_EX // since REDSTONE5 + FileLinkInformationExBypassAccessCheck, // s: FILE_LINK_INFORMATION_EX // (kernel-mode only) + FileStorageReserveIdInformation, // qs: FILE_STORAGE_RESERVE_ID_INFORMATION + FileCaseSensitiveInformationForceAccessCheck, // qs: FILE_CASE_SENSITIVE_INFORMATION + FileKnownFolderInformation, // qs: FILE_KNOWN_FOLDER_INFORMATION // since WIN11 + FileStatBasicInformation, // qs: FILE_STAT_BASIC_INFORMATION // since 23H2 + FileId64ExtdDirectoryInformation, // q: FILE_ID_64_EXTD_DIR_INFORMATION + FileId64ExtdBothDirectoryInformation, // q: FILE_ID_64_EXTD_BOTH_DIR_INFORMATION + FileIdAllExtdDirectoryInformation, // q: FILE_ID_ALL_EXTD_DIR_INFORMATION + FileIdAllExtdBothDirectoryInformation, // q: FILE_ID_ALL_EXTD_BOTH_DIR_INFORMATION + FileStreamReservationInformation, // q: FILE_STREAM_RESERVATION_INFORMATION // since 24H2 + FileMupProviderInfo, // qs: MUP_PROVIDER_INFORMATION + FileMaximumInformation +} FILE_INFORMATION_CLASS, *PFILE_INFORMATION_CLASS; + /** * The FILE_BASIC_INFORMATION structure contains timestamps and basic attributes of a file. * \li If you specify a value of zero for any of the XxxTime members, the file system keeps a file's current value for that time. - * \li If you specify a value of -1 for any of the XxxTime members, time stamp updates are disabled for I/O operations preformed on the file handle. - * \li If you specify a value of -2 for any of the XxxTime members, time stamp updates are enabled for I/O operations preformed on the file handle. + * \li If you specify a value of -1 for any of the XxxTime members, time stamp updates are disabled for I/O operations performed on the file handle. + * \li If you specify a value of -2 for any of the XxxTime members, time stamp updates are enabled for I/O operations performed on the file handle. * \remarks To set the members of this structure, the caller must have FILE_WRITE_ATTRIBUTES access to the file. + * \sa https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/wdm/ns-wdm-_file_basic_information */ typedef struct _FILE_BASIC_INFORMATION { @@ -342,6 +359,7 @@ typedef struct _FILE_BASIC_INFORMATION * The FILE_STANDARD_INFORMATION structure contains standard information of a file. * \remarks EndOfFile specifies the byte offset to the end of the file. * Because this value is zero-based, it actually refers to the first free byte in the file; that is, it is the offset to the byte immediately following the last valid byte in the file. + * \sa https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/wdm/ns-wdm-_file_standard_information */ typedef struct _FILE_STANDARD_INFORMATION { @@ -352,6 +370,10 @@ typedef struct _FILE_STANDARD_INFORMATION BOOLEAN Directory; // The file directory status. TRUE indicates the file object represents a directory. } FILE_STANDARD_INFORMATION, *PFILE_STANDARD_INFORMATION; +/** + * The FILE_STANDARD_INFORMATION_EX structure is used as an argument to routines that query or set file information + * \sa https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/wdm/ns-wdm-_file_standard_information_ex + */ typedef struct _FILE_STANDARD_INFORMATION_EX { LARGE_INTEGER AllocationSize; @@ -363,6 +385,11 @@ typedef struct _FILE_STANDARD_INFORMATION_EX BOOLEAN MetadataAttribute; } FILE_STANDARD_INFORMATION_EX, *PFILE_STANDARD_INFORMATION_EX; +/** + * The FILE_INTERNAL_INFORMATION structure is used to query for the file system's 8-byte file reference number for a file. + * \sa https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/ntifs/ns-ntifs-_file_internal_information + * \remark The IndexNumber member is the same as the FileId member of the FILE_ID_BOTH_DIR_INFORMATION and FILE_ID_FULL_DIR_INFORMATION structures. + */ typedef struct _FILE_INTERNAL_INFORMATION { union @@ -376,37 +403,65 @@ typedef struct _FILE_INTERNAL_INFORMATION }; } FILE_INTERNAL_INFORMATION, *PFILE_INTERNAL_INFORMATION; +/** + * The FILE_EA_INFORMATION structure is used to query for the size of the extended attributes (EA) for a file. + * \sa https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/ntifs/ns-ntifs-_file_ea_information + */ typedef struct _FILE_EA_INFORMATION { ULONG EaSize; } FILE_EA_INFORMATION, *PFILE_EA_INFORMATION; +/** + * The FILE_ACCESS_INFORMATION structure is used to query for or set the access rights of a file. + * \sa https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/ntifs/ns-ntifs-_file_access_information + */ typedef struct _FILE_ACCESS_INFORMATION { ACCESS_MASK AccessFlags; } FILE_ACCESS_INFORMATION, *PFILE_ACCESS_INFORMATION; +/** + * The FILE_POSITION_INFORMATION structure is used as an argument to routines that query or set file information. + * \sa https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/wdm/ns-wdm-_file_position_information + */ typedef struct _FILE_POSITION_INFORMATION { LARGE_INTEGER CurrentByteOffset; } FILE_POSITION_INFORMATION, *PFILE_POSITION_INFORMATION; +/** + * The FILE_MODE_INFORMATION structure is used to query or set the access mode of a file. + * \sa https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/ntifs/ns-ntifs-_file_mode_information + */ typedef struct _FILE_MODE_INFORMATION { ULONG Mode; } FILE_MODE_INFORMATION, *PFILE_MODE_INFORMATION; +/** + * The FILE_ALIGNMENT_INFORMATION structure is used to query or set the buffer alignment required by the underlying device. + * \sa https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/ntddk/ns-ntddk-_file_alignment_information + */ typedef struct _FILE_ALIGNMENT_INFORMATION { ULONG AlignmentRequirement; } FILE_ALIGNMENT_INFORMATION, *PFILE_ALIGNMENT_INFORMATION; +/** + * The FILE_NAME_INFORMATION structure is used to query or set the file name and/or new short name for a file. + * \sa https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/ntddk/ns-ntddk-_file_name_information + */ typedef struct _FILE_NAME_INFORMATION { ULONG FileNameLength; _Field_size_bytes_(FileNameLength) WCHAR FileName[1]; } FILE_NAME_INFORMATION, *PFILE_NAME_INFORMATION; +/** + * The FILE_ALL_INFORMATION structure is used as a container for several FILE_XXX_INFORMATION structures. + * \sa https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/ntifs/ns-ntifs-_file_all_information + */ typedef struct _FILE_ALL_INFORMATION { FILE_BASIC_INFORMATION BasicInformation; @@ -420,6 +475,10 @@ typedef struct _FILE_ALL_INFORMATION FILE_NAME_INFORMATION NameInformation; } FILE_ALL_INFORMATION, *PFILE_ALL_INFORMATION; +/** + * The FILE_NETWORK_OPEN_INFORMATION structure is used to query for information that is commonly needed when a file is opened across a network. + * \sa https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/wdm/ns-wdm-_file_network_open_information + */ typedef struct _FILE_NETWORK_OPEN_INFORMATION { LARGE_INTEGER CreationTime; @@ -431,17 +490,29 @@ typedef struct _FILE_NETWORK_OPEN_INFORMATION ULONG FileAttributes; } FILE_NETWORK_OPEN_INFORMATION, *PFILE_NETWORK_OPEN_INFORMATION; +/** + * The FILE_ATTRIBUTE_TAG_INFORMATION structure is used to query for attribute and reparse tag information for a file. + * \sa https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/ntddk/ns-ntddk-_file_attribute_tag_information + */ typedef struct _FILE_ATTRIBUTE_TAG_INFORMATION { ULONG FileAttributes; ULONG ReparseTag; } FILE_ATTRIBUTE_TAG_INFORMATION, *PFILE_ATTRIBUTE_TAG_INFORMATION; +/** + * The FILE_ALLOCATION_INFORMATION structure is used to set the allocation size for a file. + * \sa https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/ntifs/ns-ntifs-_file_allocation_information + */ typedef struct _FILE_ALLOCATION_INFORMATION { LARGE_INTEGER AllocationSize; } FILE_ALLOCATION_INFORMATION, *PFILE_ALLOCATION_INFORMATION; +/** + * The FILE_COMPRESSION_INFORMATION structure describes the state of a compressed data buffer. + * \sa https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/ntifs/ns-ntifs-_file_compression_information + */ typedef struct _FILE_COMPRESSION_INFORMATION { LARGE_INTEGER CompressedFileSize; @@ -452,17 +523,24 @@ typedef struct _FILE_COMPRESSION_INFORMATION UCHAR Reserved[3]; } FILE_COMPRESSION_INFORMATION, *PFILE_COMPRESSION_INFORMATION; +/** + * The FILE_DISPOSITION_INFORMATION structure is used to mark a file for deletion. + * \sa https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/ntddk/ns-ntddk-_file_disposition_information + */ typedef struct _FILE_DISPOSITION_INFORMATION { BOOLEAN DeleteFile; } FILE_DISPOSITION_INFORMATION, *PFILE_DISPOSITION_INFORMATION; +/** + * The FILE_END_OF_FILE_INFORMATION structure is used to set end-of-file information for a file. + * \sa https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/ntddk/ns-ntddk-_file_end_of_file_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_WINDOWS_10_RS5) #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 @@ -476,8 +554,11 @@ typedef struct _FILE_END_OF_FILE_INFORMATION_EX LARGE_INTEGER PagingFileMaxSize; ULONG Flags; } FILE_END_OF_FILE_INFORMATION_EX, *PFILE_END_OF_FILE_INFORMATION_EX; -//#endif +/** + * The FILE_VALID_DATA_LENGTH_INFORMATION structure is used to set the valid data length information for a file. + * \sa https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/ntddk/ns-ntddk-_file_valid_data_length_information + */ typedef struct _FILE_VALID_DATA_LENGTH_INFORMATION { LARGE_INTEGER ValidDataLength; @@ -495,6 +576,10 @@ typedef struct _FILE_VALID_DATA_LENGTH_INFORMATION #define FILE_LINK_FORCE_RESIZE_SOURCE_SR 0x00000100 #define FILE_LINK_FORCE_RESIZE_SR 0x00000180 +/** + * The FILE_LINK_INFORMATION structure is used to create an NTFS hard link to an existing file. + * \sa https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/ntifs/ns-ntifs-_file_link_information + */ typedef struct _FILE_LINK_INFORMATION { BOOLEAN ReplaceIfExists; @@ -519,6 +604,10 @@ typedef struct _FILE_MOVE_CLUSTER_INFORMATION _Field_size_bytes_(FileNameLength) WCHAR FileName[1]; } FILE_MOVE_CLUSTER_INFORMATION, *PFILE_MOVE_CLUSTER_INFORMATION; +/** + * The FILE_RENAME_INFORMATION structure is used to rename a file. + * \sa https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/ntifs/ns-ntifs-_file_rename_information + */ typedef struct _FILE_RENAME_INFORMATION { BOOLEAN ReplaceIfExists; @@ -539,6 +628,10 @@ typedef struct _FILE_RENAME_INFORMATION #define FILE_RENAME_FORCE_RESIZE_SOURCE_SR 0x00000100 #define FILE_RENAME_FORCE_RESIZE_SR 0x00000180 +/** + * The FILE_RENAME_INFORMATION_EX structure is used to rename a file. + * \sa https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/ntifs/ns-ntifs-_file_rename_information + */ typedef struct _FILE_RENAME_INFORMATION_EX { ULONG Flags; @@ -549,7 +642,9 @@ typedef struct _FILE_RENAME_INFORMATION_EX /** * The FILE_STREAM_INFORMATION structure contains information about a file stream. + * \sa https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/ntifs/ns-ntifs-_file_stream_information */ +_Struct_size_bytes_(NextEntryOffset) typedef struct _FILE_STREAM_INFORMATION { ULONG NextEntryOffset; @@ -575,8 +670,7 @@ typedef struct _FILE_TRACKING_INFORMATION * \remarks he FILE_COMPLETION_INFORMATION structure is used to replace the completion information for a port handle set in Port. * Completion information is replaced with the ZwSetInformationFile routine with the FileInformationClass parameter set to FileReplaceCompletionInformation. * The Port and Key members of FILE_COMPLETION_INFORMATION are set to their new values. To remove an existing completion port for a file handle, Port is set to NULL. - * - * https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/ntifs/ns-ntifs-_file_completion_information + * \sa https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/ntifs/ns-ntifs-_file_completion_information */ typedef struct _FILE_COMPLETION_INFORMATION { @@ -591,8 +685,7 @@ typedef struct _FILE_COMPLETION_INFORMATION * When CompletionMode is set to FILE_PIPE_QUEUE_OPERATION, if the pipe is connected to, read to, or written from, * the operation is not completed until there is data to read, all data is written, or a client is connected. * When CompletionMode is set to FILE_PIPE_COMPLETE_OPERATION, if the pipe is being connected to, read to, or written from, the operation is completed immediately. - * - * https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/ntifs/ns-ntifs-_file_pipe_information + * \sa https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/ntifs/ns-ntifs-_file_pipe_information */ typedef struct _FILE_PIPE_INFORMATION { @@ -602,8 +695,7 @@ typedef struct _FILE_PIPE_INFORMATION /** * The FILE_PIPE_LOCAL_INFORMATION structure contains information about the local end of a named pipe. - * - * \remarks https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/ntifs/ns-ntifs-_file_pipe_local_information + * \sa https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/ntifs/ns-ntifs-_file_pipe_local_information */ typedef struct _FILE_PIPE_LOCAL_INFORMATION { @@ -623,7 +715,7 @@ typedef struct _FILE_PIPE_LOCAL_INFORMATION * The FILE_PIPE_REMOTE_INFORMATION structure contains information about the remote end of a named pipe. * * \remarks Remote information is not available for local pipes or for the server end of a remote pipe. - * https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/ntifs/ns-ntifs-_file_pipe_remote_information + * \sa https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/ntifs/ns-ntifs-_file_pipe_remote_information */ typedef struct _FILE_PIPE_REMOTE_INFORMATION { @@ -633,8 +725,7 @@ typedef struct _FILE_PIPE_REMOTE_INFORMATION /** * The FILE_MAILSLOT_QUERY_INFORMATION structure contains information about a mailslot. - * - * \remarks https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/ntifs/ns-ntifs-_file_mailslot_query_information + * \sa https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/ntifs/ns-ntifs-_file_mailslot_query_information */ typedef struct _FILE_MAILSLOT_QUERY_INFORMATION { @@ -647,8 +738,7 @@ typedef struct _FILE_MAILSLOT_QUERY_INFORMATION /** * The FILE_MAILSLOT_SET_INFORMATION structure is used to set a value on a mailslot. - * - * \remarks https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/ntifs/ns-ntifs-_file_mailslot_set_information + * \sa https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/ntifs/ns-ntifs-_file_mailslot_set_information */ typedef struct _FILE_MAILSLOT_SET_INFORMATION { @@ -657,6 +747,7 @@ typedef struct _FILE_MAILSLOT_SET_INFORMATION /** * The FILE_REPARSE_POINT_INFORMATION structure contains information about a reparse point. + * \sa https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/ntifs/ns-ntifs-_file_reparse_point_information */ typedef struct _FILE_REPARSE_POINT_INFORMATION { @@ -667,6 +758,7 @@ typedef struct _FILE_REPARSE_POINT_INFORMATION /** * The FILE_LINK_ENTRY_INFORMATION structure contains information about a file link entry. */ +_Struct_size_bytes_(NextEntryOffset) typedef struct _FILE_LINK_ENTRY_INFORMATION { ULONG NextEntryOffset; @@ -687,6 +779,7 @@ typedef struct _FILE_LINKS_INFORMATION /** * The FILE_NETWORK_PHYSICAL_NAME_INFORMATION structure contains information about the network physical name of a file. + * \sa https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/ntifs/ns-ntifs-_file_network_physical_name_information */ typedef struct _FILE_NETWORK_PHYSICAL_NAME_INFORMATION { @@ -696,6 +789,7 @@ typedef struct _FILE_NETWORK_PHYSICAL_NAME_INFORMATION /** * The FILE_STANDARD_LINK_INFORMATION structure contains standard information about a file link. + * \sa https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/ntifs/ns-ntifs-file_standard_link_information */ typedef struct _FILE_STANDARD_LINK_INFORMATION { @@ -722,29 +816,55 @@ typedef struct _FILE_SFIO_VOLUME_INFORMATION ULONG MinimumTransferSize; } FILE_SFIO_VOLUME_INFORMATION, *PFILE_SFIO_VOLUME_INFORMATION; +/** + * The IO_PRIORITY_HINT enumeration type specifies the priority hint for an IRP. + * \sa https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/wdm/ne-wdm-_io_priority_hint + */ 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. + IoPriorityVeryLow, // 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; +/** + * The FILE_IO_PRIORITY_HINT_INFORMATION structure is used to query and set the default IRP priority hint for requests on the specified file handle. + * \sa https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/wdm/ns-wdm-_file_io_priority_hint_information + */ typedef struct DECLSPEC_ALIGN(8) _FILE_IO_PRIORITY_HINT_INFORMATION { IO_PRIORITY_HINT PriorityHint; } FILE_IO_PRIORITY_HINT_INFORMATION, *PFILE_IO_PRIORITY_HINT_INFORMATION; +/** + * The FILE_IO_PRIORITY_HINT_INFORMATION_EX structure is used to query and set the default IRP priority hint for requests on the specified file handle. + * \sa https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/wdm/ns-wdm-_file_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; +/** + * FILE_SKIP_COMPLETION_PORT_ON_SUCCESS + * Skip posting a completion packet to the I/O completion port if the operation completes successfully. + */ #define FILE_SKIP_COMPLETION_PORT_ON_SUCCESS 0x1 + +/** + * FILE_SKIP_SET_EVENT_ON_HANDLE + * Skip setting the event on the file handle when the operation completes. + */ #define FILE_SKIP_SET_EVENT_ON_HANDLE 0x2 + +/** + * FILE_SKIP_SET_USER_EVENT_ON_FAST_IO + * Skip setting the user event when a fast I/O operation completes. + */ #define FILE_SKIP_SET_USER_EVENT_ON_FAST_IO 0x4 typedef struct _FILE_IO_COMPLETION_NOTIFICATION_INFORMATION @@ -755,11 +875,12 @@ typedef struct _FILE_IO_COMPLETION_NOTIFICATION_INFORMATION typedef struct _FILE_PROCESS_IDS_USING_FILE_INFORMATION { ULONG NumberOfProcessIdsInList; - _Field_size_(NumberOfProcessIdsInList) ULONG_PTR ProcessIdList[1]; + _Field_size_(NumberOfProcessIdsInList) HANDLE ProcessIdList[1]; } FILE_PROCESS_IDS_USING_FILE_INFORMATION, *PFILE_PROCESS_IDS_USING_FILE_INFORMATION; /** * The FILE_IS_REMOTE_DEVICE_INFORMATION structure indicates whether the file system that contains the file is a remote file system. + * \sa https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/wdm/ns-wdm-_file_is_remote_device_information */ typedef struct _FILE_IS_REMOTE_DEVICE_INFORMATION { @@ -883,6 +1004,10 @@ typedef struct _FILE_VOLUME_NAME_INFORMATION ((FID128).Identifier[15] = (UCHAR)-1); \ } +/** + * The FILE_ID_INFORMATION structure is used to query file identification information. + * \sa https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/ntifs/ns-ntifs-file_id_information + */ typedef struct _FILE_ID_INFORMATION { ULONGLONG VolumeSerialNumber; @@ -891,12 +1016,21 @@ typedef struct _FILE_ID_INFORMATION FILE_ID_128 FileId; struct { - LONGLONG FileIdLowPart : 64; // rev - LONGLONG FileIdHighPart : 64; // rev + union + { + FILE_INTERNAL_INFORMATION FileInternal; // rev + LONGLONG FileIdLowPart; // rev + }; + LONGLONG FileIdHighPart; // rev }; }; } FILE_ID_INFORMATION, *PFILE_ID_INFORMATION; +/** + * The FILE_ID_EXTD_DIR_INFORMATION structure is used to query 128-bit file reference number information for the files in a directory. + * \sa https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/ntifs/ns-ntifs-file_id_extd_dir_information + */ +_Struct_size_bytes_(NextEntryOffset) typedef struct _FILE_ID_EXTD_DIR_INFORMATION { ULONG NextEntryOffset; @@ -922,6 +1056,7 @@ typedef struct _FILE_ID_EXTD_DIR_INFORMATION FIELD_OFFSET(FILE_ID_EXTD_DIR_INFORMATION, FileNameLength) \ } +_Struct_size_bytes_(NextEntryOffset) typedef struct _FILE_LINK_ENTRY_FULL_ID_INFORMATION { ULONG NextEntryOffset; @@ -937,6 +1072,7 @@ typedef struct _FILE_LINKS_FULL_ID_INFORMATION FILE_LINK_ENTRY_FULL_ID_INFORMATION Entry; } FILE_LINKS_FULL_ID_INFORMATION, *PFILE_LINKS_FULL_ID_INFORMATION; +_Struct_size_bytes_(NextEntryOffset) typedef struct _FILE_ID_EXTD_BOTH_DIR_INFORMATION { ULONG NextEntryOffset; @@ -964,6 +1100,7 @@ typedef struct _FILE_ID_EXTD_BOTH_DIR_INFORMATION FIELD_OFFSET(FILE_ID_EXTD_BOTH_DIR_INFORMATION, FileNameLength) \ } +_Struct_size_bytes_(NextEntryOffset) typedef struct _FILE_ID_64_EXTD_DIR_INFORMATION { ULONG NextEntryOffset; @@ -978,7 +1115,11 @@ typedef struct _FILE_ID_64_EXTD_DIR_INFORMATION ULONG FileNameLength; ULONG EaSize; ULONG ReparsePointTag; - LARGE_INTEGER FileId; + union + { + LARGE_INTEGER FileId; + FILE_INTERNAL_INFORMATION FileInternal; // rev + }; _Field_size_bytes_(FileNameLength) WCHAR FileName[1]; } FILE_ID_64_EXTD_DIR_INFORMATION, *PFILE_ID_64_EXTD_DIR_INFORMATION; @@ -989,6 +1130,7 @@ typedef struct _FILE_ID_64_EXTD_DIR_INFORMATION FIELD_OFFSET(FILE_ID_64_EXTD_DIR_INFORMATION, FileNameLength) \ } +_Struct_size_bytes_(NextEntryOffset) typedef struct _FILE_ID_64_EXTD_BOTH_DIR_INFORMATION { ULONG NextEntryOffset; @@ -1003,7 +1145,11 @@ typedef struct _FILE_ID_64_EXTD_BOTH_DIR_INFORMATION ULONG FileNameLength; ULONG EaSize; ULONG ReparsePointTag; - LARGE_INTEGER FileId; + union + { + LARGE_INTEGER FileId; + FILE_INTERNAL_INFORMATION FileInternal; // rev + }; CCHAR ShortNameLength; WCHAR ShortName[12]; _Field_size_bytes_(FileNameLength) WCHAR FileName[1]; @@ -1016,6 +1162,7 @@ typedef struct _FILE_ID_64_EXTD_BOTH_DIR_INFORMATION FIELD_OFFSET(FILE_ID_64_EXTD_BOTH_DIR_INFORMATION, FileNameLength) \ } +_Struct_size_bytes_(NextEntryOffset) typedef struct _FILE_ID_ALL_EXTD_DIR_INFORMATION { ULONG NextEntryOffset; @@ -1030,7 +1177,11 @@ typedef struct _FILE_ID_ALL_EXTD_DIR_INFORMATION ULONG FileNameLength; ULONG EaSize; ULONG ReparsePointTag; - LARGE_INTEGER FileId; + union + { + LARGE_INTEGER FileId; + FILE_INTERNAL_INFORMATION FileInternal; // rev + }; FILE_ID_128 FileId128; _Field_size_bytes_(FileNameLength) WCHAR FileName[1]; } FILE_ID_ALL_EXTD_DIR_INFORMATION, *PFILE_ID_ALL_EXTD_DIR_INFORMATION; @@ -1042,6 +1193,7 @@ typedef struct _FILE_ID_ALL_EXTD_DIR_INFORMATION FIELD_OFFSET(FILE_ID_ALL_EXTD_DIR_INFORMATION, FileNameLength) \ } +_Struct_size_bytes_(NextEntryOffset) typedef struct _FILE_ID_ALL_EXTD_BOTH_DIR_INFORMATION { ULONG NextEntryOffset; @@ -1056,7 +1208,11 @@ typedef struct _FILE_ID_ALL_EXTD_BOTH_DIR_INFORMATION ULONG FileNameLength; ULONG EaSize; ULONG ReparsePointTag; - LARGE_INTEGER FileId; + union + { + LARGE_INTEGER FileId; + FILE_INTERNAL_INFORMATION FileInternal; // rev + }; FILE_ID_128 FileId128; CCHAR ShortNameLength; WCHAR ShortName[12]; @@ -1106,6 +1262,10 @@ typedef struct _FILE_STAT_BASIC_INFORMATION } FILE_STAT_BASIC_INFORMATION, *PFILE_STAT_BASIC_INFORMATION; #endif // NTDDI_WIN11_GE +/** + * The FILE_MEMORY_PARTITION_INFORMATION structure is used to query information about a memory partition. + * \sa https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/wdm/ns-wdm-_file_memory_partition_information + */ typedef struct _FILE_MEMORY_PARTITION_INFORMATION { HANDLE OwnerPartitionHandle; @@ -1130,7 +1290,7 @@ typedef struct _FILE_MEMORY_PARTITION_INFORMATION #if !defined(NTDDI_WIN11_GE) || (NTDDI_VERSION < NTDDI_WIN11_GE) typedef struct _FILE_STAT_LX_INFORMATION { - LARGE_INTEGER FileId; + FILE_INTERNAL_INFORMATION FileId; LARGE_INTEGER CreationTime; LARGE_INTEGER LastAccessTime; LARGE_INTEGER LastWriteTime; @@ -1197,8 +1357,11 @@ typedef struct _MUP_PROVIDER_INFORMATION PULONG BufferSize; } MUP_PROVIDER_INFORMATION, *PMUP_PROVIDER_INFORMATION; +// // NtQueryDirectoryFile types +// +_Struct_size_bytes_(NextEntryOffset) typedef struct _FILE_INFORMATION_DEFINITION { FILE_INFORMATION_CLASS Class; @@ -1207,6 +1370,7 @@ typedef struct _FILE_INFORMATION_DEFINITION ULONG FileNameLengthOffset; } FILE_INFORMATION_DEFINITION, *PFILE_INFORMATION_DEFINITION; +_Struct_size_bytes_(NextEntryOffset) typedef struct _FILE_DIRECTORY_INFORMATION { ULONG NextEntryOffset; @@ -1229,6 +1393,7 @@ typedef struct _FILE_DIRECTORY_INFORMATION FIELD_OFFSET(FILE_DIRECTORY_INFORMATION, FileNameLength) \ } +_Struct_size_bytes_(NextEntryOffset) typedef struct _FILE_FULL_DIR_INFORMATION { ULONG NextEntryOffset; @@ -1252,6 +1417,7 @@ typedef struct _FILE_FULL_DIR_INFORMATION FIELD_OFFSET(FILE_FULL_DIR_INFORMATION, FileNameLength) \ } +_Struct_size_bytes_(NextEntryOffset) typedef struct _FILE_ID_FULL_DIR_INFORMATION { ULONG NextEntryOffset; @@ -1265,7 +1431,11 @@ typedef struct _FILE_ID_FULL_DIR_INFORMATION ULONG FileAttributes; ULONG FileNameLength; ULONG EaSize; - LARGE_INTEGER FileId; + union + { + LARGE_INTEGER FileId; + FILE_INTERNAL_INFORMATION FileInternal; // rev + }; _Field_size_bytes_(FileNameLength) WCHAR FileName[1]; } FILE_ID_FULL_DIR_INFORMATION, *PFILE_ID_FULL_DIR_INFORMATION; @@ -1276,6 +1446,7 @@ typedef struct _FILE_ID_FULL_DIR_INFORMATION FIELD_OFFSET(FILE_ID_FULL_DIR_INFORMATION, FileNameLength) \ } +_Struct_size_bytes_(NextEntryOffset) typedef struct _FILE_BOTH_DIR_INFORMATION { ULONG NextEntryOffset; @@ -1301,6 +1472,7 @@ typedef struct _FILE_BOTH_DIR_INFORMATION FIELD_OFFSET(FILE_BOTH_DIR_INFORMATION, FileNameLength) \ } +_Struct_size_bytes_(NextEntryOffset) typedef struct _FILE_ID_BOTH_DIR_INFORMATION { ULONG NextEntryOffset; @@ -1316,7 +1488,11 @@ typedef struct _FILE_ID_BOTH_DIR_INFORMATION ULONG EaSize; CCHAR ShortNameLength; WCHAR ShortName[12]; - LARGE_INTEGER FileId; + union + { + LARGE_INTEGER FileId; + FILE_INTERNAL_INFORMATION FileInternal; // rev + }; _Field_size_bytes_(FileNameLength) WCHAR FileName[1]; } FILE_ID_BOTH_DIR_INFORMATION, *PFILE_ID_BOTH_DIR_INFORMATION; @@ -1327,6 +1503,7 @@ typedef struct _FILE_ID_BOTH_DIR_INFORMATION FIELD_OFFSET(FILE_ID_BOTH_DIR_INFORMATION, FileNameLength) \ } +_Struct_size_bytes_(NextEntryOffset) typedef struct _FILE_NAMES_INFORMATION { ULONG NextEntryOffset; @@ -1342,6 +1519,7 @@ typedef struct _FILE_NAMES_INFORMATION FIELD_OFFSET(FILE_NAMES_INFORMATION, FileNameLength) \ } +_Struct_size_bytes_(NextEntryOffset) typedef struct _FILE_ID_GLOBAL_TX_DIR_INFORMATION { ULONG NextEntryOffset; @@ -1354,7 +1532,11 @@ typedef struct _FILE_ID_GLOBAL_TX_DIR_INFORMATION LARGE_INTEGER AllocationSize; ULONG FileAttributes; ULONG FileNameLength; - LARGE_INTEGER FileId; + union + { + LARGE_INTEGER FileId; + FILE_INTERNAL_INFORMATION FileInternal; // rev + }; GUID LockingTransactionId; ULONG TxInfoFlags; _Field_size_bytes_(FileNameLength) WCHAR FileName[1]; @@ -1392,8 +1574,11 @@ typedef struct _FILE_DIRECTORY_NEXT_INFORMATION ULONG NextEntryOffset; } FILE_DIRECTORY_NEXT_INFORMATION, *PFILE_DIRECTORY_NEXT_INFORMATION; +// // NtQueryEaFile/NtSetEaFile types +// +_Struct_size_bytes_(NextEntryOffset) typedef struct _FILE_FULL_EA_INFORMATION { ULONG NextEntryOffset; @@ -1405,6 +1590,7 @@ typedef struct _FILE_FULL_EA_INFORMATION // UCHAR EaValue[1] } FILE_FULL_EA_INFORMATION, *PFILE_FULL_EA_INFORMATION; +_Struct_size_bytes_(NextEntryOffset) typedef struct _FILE_GET_EA_INFORMATION { ULONG NextEntryOffset; @@ -1412,8 +1598,11 @@ typedef struct _FILE_GET_EA_INFORMATION _Field_size_bytes_(EaNameLength) CHAR EaName[1]; } FILE_GET_EA_INFORMATION, *PFILE_GET_EA_INFORMATION; +// // NtQueryQuotaInformationFile/NtSetQuotaInformationFile types +// +_Struct_size_bytes_(NextEntryOffset) typedef struct _FILE_GET_QUOTA_INFORMATION { ULONG NextEntryOffset; @@ -1421,6 +1610,7 @@ typedef struct _FILE_GET_QUOTA_INFORMATION _Field_size_bytes_(SidLength) SID Sid; } FILE_GET_QUOTA_INFORMATION, *PFILE_GET_QUOTA_INFORMATION; +_Struct_size_bytes_(NextEntryOffset) typedef struct _FILE_QUOTA_INFORMATION { ULONG NextEntryOffset; @@ -1434,26 +1624,28 @@ typedef struct _FILE_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 - FileFsGuidInformation, // q: FILE_FS_GUID_INFORMATION // since 23H2 + FileFsVolumeInformation = 1, // q: FILE_FS_VOLUME_INFORMATION + FileFsLabelInformation, // s: FILE_FS_LABEL_INFORMATION // SeManageVolumePrivilege + FileFsSizeInformation, // q: FILE_FS_SIZE_INFORMATION + FileFsDeviceInformation, // q: FILE_FS_DEVICE_INFORMATION + FileFsAttributeInformation, // q: FILE_FS_ATTRIBUTE_INFORMATION + FileFsControlInformation, // qs: FILE_FS_CONTROL_INFORMATION // SeManageVolumePrivilege + FileFsFullSizeInformation, // q: FILE_FS_FULL_SIZE_INFORMATION + FileFsObjectIdInformation, // qs: FILE_FS_OBJECTID_INFORMATION // SeRestorePrivilege + FileFsDriverPathInformation, // q: FILE_FS_DRIVER_PATH_INFORMATION + FileFsVolumeFlagsInformation, // qs: FILE_FS_VOLUME_FLAGS_INFORMATION // SeManageVolumePrivilege // 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 + FileFsGuidInformation, // q: FILE_FS_GUID_INFORMATION // since 23H2 FileFsMaximumInformation } FSINFOCLASS, *PFSINFOCLASS; typedef enum _FSINFOCLASS FS_INFORMATION_CLASS; +// // NtQueryVolumeInformation/NtSetVolumeInformation types +// typedef struct _FILE_FS_VOLUME_INFORMATION { @@ -1606,15 +1798,34 @@ typedef struct _FILE_FS_GUID_INFORMATION GUID FsGuid; } FILE_FS_GUID_INFORMATION, *PFILE_FS_GUID_INFORMATION; +// // System calls +// +/** + * The NtCreateFile routine creates a new file or directory, or opens an existing file, device, directory, or volume. + * + * \param[out] FileHandle Pointer to a variable that receives a handle to the pipe. + * \param[in] DesiredAccess The requested access to the object. + * \param[in] ObjectAttributes Pointer to an OBJECT_ATTRIBUTES structure that contains the object attributes, including pipe name. + * \param[out] IoStatusBlock Pointer to an IO_STATUS_BLOCK structure that receives the final completion status and information about the operation. + * \param[in] AllocationSize The initial allocation size in bytes for the file. Specify a non-zero value to eliminate disk fragmentation, since the file system pre-allocates the file using a contiguous block. + * \param[in] FileAttributes The file attributes. Explicitly specified attributes are applied only when the file is created, superseded, or, in some cases, overwritten. + * \param[in] ShareAccess The type of share access that the caller would like to use in the file. + * \param[in] CreateDisposition Specifies how the file should be handled when the file already exists. + * \param[in] CreateOptions Specifies the options to be applied when creating or opening the file. + * \param[in] EaBuffer Pointer to an EA buffer used to pass extended attributes. + * \param[in] EaLength Length of the EA buffer. + * \return NTSTATUS Successful or errant status. + * \sa https://learn.microsoft.com/en-us/windows/win32/api/Winternl/nf-winternl-ntcreatefile + */ NTSYSCALLAPI NTSTATUS NTAPI NtCreateFile( _Out_ PHANDLE FileHandle, _In_ ACCESS_MASK DesiredAccess, - _In_ POBJECT_ATTRIBUTES ObjectAttributes, + _In_ PCOBJECT_ATTRIBUTES ObjectAttributes, _Out_ PIO_STATUS_BLOCK IoStatusBlock, _In_opt_ PLARGE_INTEGER AllocationSize, _In_ ULONG FileAttributes, @@ -1625,13 +1836,33 @@ NtCreateFile( _In_ ULONG EaLength ); +/** + * The NtCreateNamedPipeFile routine deletes the specified file. + * + * \param[out] FileHandle Pointer to a variable that receives a handle to the pipe. + * \param[in] DesiredAccess The requested access to the object. + * \param[in] ObjectAttributes Pointer to an OBJECT_ATTRIBUTES structure that contains the object attributes, including pipe name. + * \param[out] IoStatusBlock Pointer to an IO_STATUS_BLOCK structure that receives the final completion status and information about the operation. + * \param[in] ShareAccess Specifies the type of share access for the file. + * \param[in] CreateDisposition Specifies how the file should be handled when the file already exists. + * \param[in] CreateOptions Specifies the options to be applied when creating or opening the file. + * \param[in] NamedPipeType Type of named pipe to create (byte-type or message-type). + * \param[in] ReadMode Mode in which to read the pipe (byte-type or message-type). + * \param[in] CompletionMode Specifies blocking or non-blocking mode of the pipe. + * \param[in] MaximumInstances Maximum number of simultaneous instances of the named pipe. + * \param[in] InboundQuota Specifies the pool quota that is reserved for writes to the inbound side of the named pipe. + * \param[in] OutboundQuota Specifies the pool quota that is reserved for writes to the inbound side of the named pipe. + * \param[in] DefaultTimeout An optional pointer to a timeout value that is used if a timeout value is not specified when waiting for an instance of a named pipe. + * \return NTSTATUS Successful or errant status. + * \sa https://learn.microsoft.com/en-us/windows/win32/devnotes/nt-create-named-pipe-file + */ NTSYSCALLAPI NTSTATUS NTAPI NtCreateNamedPipeFile( _Out_ PHANDLE FileHandle, _In_ ACCESS_MASK DesiredAccess, - _In_ POBJECT_ATTRIBUTES ObjectAttributes, + _In_ PCOBJECT_ATTRIBUTES ObjectAttributes, _Out_ PIO_STATUS_BLOCK IoStatusBlock, _In_ ULONG ShareAccess, _In_ ULONG CreateDisposition, @@ -1651,7 +1882,7 @@ NTAPI NtCreateMailslotFile( _Out_ PHANDLE FileHandle, _In_ ACCESS_MASK DesiredAccess, - _In_ POBJECT_ATTRIBUTES ObjectAttributes, + _In_ PCOBJECT_ATTRIBUTES ObjectAttributes, _Out_ PIO_STATUS_BLOCK IoStatusBlock, _In_ ULONG CreateOptions, _In_ ULONG MailslotQuota, @@ -1659,25 +1890,52 @@ NtCreateMailslotFile( _In_ PLARGE_INTEGER ReadTimeout ); +/** + * The NtOpenFile routine opens an existing file, device, directory, or volume, and returns a handle for the file object. + * + * \param[out] FileHandle Pointer to a variable that receives a handle to the file. + * \param[in] DesiredAccess The requested access to the object. + * \param[in] ObjectAttributes Pointer to an OBJECT_ATTRIBUTES structure that contains the file's attributes, including file name. + * \param[out] IoStatusBlock Pointer to an IO_STATUS_BLOCK structure that receives the final completion status and information about the operation. + * \param[in] ShareAccess Specifies the type of share access for the file. + * \param[in] OpenOptions Specifies the options to apply when opening the file. + * \return NTSTATUS Successful or errant status. + * \sa https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/ntifs/nf-ntifs-ntopenfile + */ NTSYSCALLAPI NTSTATUS NTAPI NtOpenFile( _Out_ PHANDLE FileHandle, _In_ ACCESS_MASK DesiredAccess, - _In_ POBJECT_ATTRIBUTES ObjectAttributes, + _In_ PCOBJECT_ATTRIBUTES ObjectAttributes, _Out_ PIO_STATUS_BLOCK IoStatusBlock, _In_ ULONG ShareAccess, _In_ ULONG OpenOptions ); +/** + * The NtDeleteFile routine deletes the specified file. + * + * \param[in] ObjectAttributes Pointer to an OBJECT_ATTRIBUTES structure that contains the file's attributes, including file name. + * \return NTSTATUS Successful or errant status. + * \sa https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/ntifs/nf-ntifs-zwdeletefile + */ NTSYSCALLAPI NTSTATUS NTAPI NtDeleteFile( - _In_ POBJECT_ATTRIBUTES ObjectAttributes + _In_ PCOBJECT_ATTRIBUTES ObjectAttributes ); +/** + * The NtFlushBuffersFile routine sends a flush request for the specified file to the file system. + * + * \param[in] FileHandle A handle to the file whose buffers will be flushed. + * \param[out] IoStatusBlock Pointer to an IO_STATUS_BLOCK structure that receives the final completion status and information about the operation. + * \return NTSTATUS Successful or errant status. + * \sa https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/ntifs/nf-ntifs-zwflushbuffersfile + */ NTSYSCALLAPI NTSTATUS NTAPI @@ -1706,8 +1964,13 @@ NtFlushBuffersFile( // written data in the devices cache to persistent storage. // // This is equivalent to how NtFlushBuffersFile has always worked. -// + +// If set, File data and metadata in the file cache will be written, and the +// underlying storage is synchronized to flush its cache. +// Windows file systems supported: NTFS, ReFS, FAT, exFAT. +// +#define FLUSH_FLAGS_FILE_NORMAL 0x00000000 // If set, this operation will write the data for the given file from the // Windows in-memory cache. This will NOT commit any associated metadata // changes. This will NOT send a SYNC to the storage device to flush its @@ -1735,8 +1998,19 @@ NtFlushBuffersFile( // #define FLUSH_FLAGS_FLUSH_AND_PURGE 0x00000008 // 24H2 - #if (PHNT_VERSION >= PHNT_WINDOWS_8) + +/** + * The NtFlushBuffersFileEx routine sends a flush request for a given file to the file system. An optional flush operation flag can be set to control how file data is written to storage. + * + * \param FileHandle A handle to the file object representing the file, directory, device or volume. + * \param Flags Flush operation flags. + * \param Parameters Pointer to a block with additional parameters. This parameter must currently be set to NULL. + * \param ParametersSize The size, in bytes, of the block that Parameters point to. This parameter must currently be set to 0. + * \param IoStatusBlock Address of the caller's I/O status block. This parameter is required and cannot be NULL. + * \return NTSTATUS Successful or errant status. + * \sa https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/ntifs/nf-ntifs-ntflushbuffersfileex + */ NTSYSCALLAPI NTSTATUS NTAPI @@ -1747,8 +2021,19 @@ NtFlushBuffersFileEx( _In_ ULONG ParametersSize, _Out_ PIO_STATUS_BLOCK IoStatusBlock ); -#endif +#endif // PHNT_VERSION >= PHNT_WINDOWS_8 +/** + * The NtQueryInformationFile routine returns various kinds of information about a file object. + * + * \param FileHandle A handle to the file object representing the file or directory. + * \param IoStatusBlock A pointer to an IO_STATUS_BLOCK structure that receives the final completion status, and the number of bytes written to the buffer pointed to by FileInformation. + * \param FileInformation Pointer to a caller-allocated buffer into which the routine writes the requested information about the file object. + * \param Length The size, in bytes, of the buffer pointed to by FileInformation. + * \param FileInformationClass Specifies the type of information to be returned about the file, in the buffer that FileInformation points to. + * \return NTSTATUS Successful or errant status. + * \sa https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/ntifs/nf-ntifs-ntqueryinformationfile + */ NTSYSCALLAPI NTSTATUS NTAPI @@ -1761,18 +2046,42 @@ NtQueryInformationFile( ); #if (PHNT_VERSION >= PHNT_WINDOWS_10_RS2) +/** + * The NtQueryInformationByName routine returns various kinds of information about a file object by file name. + * + * \param ObjectAttributes Pointer to an OBJECT_ATTRIBUTES structure that contains the file's attributes, including file name. + * \param IoStatusBlock A pointer to an IO_STATUS_BLOCK structure that receives the final completion status, and the number of bytes written to the buffer pointed to by FileInformation. + * \param FileInformation Pointer to a caller-allocated buffer into which the routine writes the requested information about the file object. + * \param Length The size, in bytes, of the buffer pointed to by FileInformation. + * \param FileInformationClass Specifies the type of information to be returned about the file, in the buffer that FileInformation points to. + * \return NTSTATUS Successful or errant status. + * \sa https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/ntifs/nf-ntifs-ntqueryinformationbyname + * \remarks NtQueryInformationByName queries and returns the requested information without opening the actual file, + * making it more efficient than NtQueryInformationFile, which requires a file open and subsequent file close. + */ NTSYSCALLAPI NTSTATUS NTAPI NtQueryInformationByName( - _In_ POBJECT_ATTRIBUTES ObjectAttributes, + _In_ PCOBJECT_ATTRIBUTES ObjectAttributes, _Out_ PIO_STATUS_BLOCK IoStatusBlock, _Out_writes_bytes_(Length) PVOID FileInformation, _In_ ULONG Length, _In_ FILE_INFORMATION_CLASS FileInformationClass ); -#endif +#endif // PHNT_VERSION >= PHNT_WINDOWS_10_RS2 +/** + * The NtSetInformationFile routine changes various kinds of information about a file object. + * + * \param FileHandle A handle to the file object representing the file or directory. + * \param IoStatusBlock A pointer to an IO_STATUS_BLOCK structure that receives the final completion status, and the number of bytes written to the buffer pointed to by FileInformation. + * \param FileInformation Pointer to a buffer that contains the information to set for the file. + * \param Length The size, in bytes, of the buffer pointed to by FileInformation. + * \param FileInformationClass The type of information, supplied in the buffer pointed to by FileInformation, to set for the file. + * \return NTSTATUS Successful or errant status. + * \sa https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/ntifs/nf-ntifs-ntsetinformationfile + */ NTSYSCALLAPI NTSTATUS NTAPI @@ -1784,6 +2093,23 @@ NtSetInformationFile( _In_ FILE_INFORMATION_CLASS FileInformationClass ); +/** + * The NtQueryDirectoryFile routine returns various kinds of information about files in the directory specified by a given file handle. + * + * \param[in] FileHandle A handle for the file object that represents the directory for which information is being requested. + * \param[in] Event An optional handle for a caller-created event. The event is set to the Signaled state the requested operation is completed. + * \param[in] ApcRoutine An address of an optional, caller-supplied APC routine to be called when the requested operation completes. + * \param[in] ApcContext An address of an optional, caller-supplied APC or I/O completion object associated with the file object. + * \param[out] IoStatusBlock A pointer to an IO_STATUS_BLOCK structure that receives the final completion status, and the number of bytes written to the buffer pointed to by FileInformation. + * \param[out] FileInformation A pointer to a buffer that receives the desired information about the file. + * \param[in] Length The size, in bytes, of the buffer pointed to by FileInformation. + * \param[in] FileInformationClass The type of information to be returned about files in the directory. + * \param[in] ReturnSingleEntry Set to TRUE if only a single entry should be returned, FALSE otherwise. + * \param[in] FileName An optional pointer to a Unicode string search expression containing the name of a file (or multiple files, if wildcards are used) within the directory. + * \param[in] RestartScan Set to TRUE if the scan is to start at the first entry in the directory. Set to FALSE if resuming the scan from a previous call. + * \return NTSTATUS Successful or errant status. + * \sa https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/ntifs/nf-ntifs-ntquerydirectoryfile + */ NTSYSCALLAPI NTSTATUS NTAPI @@ -1797,18 +2123,59 @@ NtQueryDirectoryFile( _In_ ULONG Length, _In_ FILE_INFORMATION_CLASS FileInformationClass, _In_ BOOLEAN ReturnSingleEntry, - _In_opt_ PUNICODE_STRING FileName, + _In_opt_ PCUNICODE_STRING FileName, _In_ BOOLEAN RestartScan ); // QueryFlags values for NtQueryDirectoryFileEx +/** + * The scan will start at the first entry in the directory. If this flag is not set, the scan will resume from where the last query ended. + */ #define FILE_QUERY_RESTART_SCAN 0x00000001 +/** + * Normally the return buffer is packed with as many matching directory entries that fit. + * If this flag is set, the file system will return only one directory entry at a time. + * This does make the operation less efficient. + */ #define FILE_QUERY_RETURN_SINGLE_ENTRY 0x00000002 +/** + * The scan should start at a specified indexed position in the directory. + * This flag can only be set if you generate your own IRP_MJ_DIRECTORY_CONTROL IRP; the index is specified in the IRP. + * How the position is specified varies from file system to file system. + */ #define FILE_QUERY_INDEX_SPECIFIED 0x00000004 +/** + * Any file system filters that perform directory virtualization or just-in-time expansion should simply pass the request + * through to the file system and return entries that are currently on disk. Not all file systems support this flag. + */ #define FILE_QUERY_RETURN_ON_DISK_ENTRIES_ONLY 0x00000008 +/** + * File systems maintain per-FileObject directory cursor information. When multiple threads do queries using the same FileObject, + * access to the per-FileObject structure is single threaded to prevent corruption of the cursor state. + * This flag tells the file system to not update per-FileObject cursor state information thus allowing multiple threads + * to query in parallel using the same handle. It behaves as if SL_RESTART_SCAN is specified on each call. If a wild card pattern + * is given on the next call, the operation will not pick up where the last query ended. + * This allows for true asynchronous directory query support. Not all file systems support this flag. + */ #define FILE_QUERY_NO_CURSOR_UPDATE 0x00000010 // RS5 #if (PHNT_VERSION >= PHNT_WINDOWS_10_RS3) +/** + * The NtQueryDirectoryFileEx routine returns various kinds of information about files in the directory specified by a given file handle. + * + * \param[in] FileHandle A handle for the file object that represents the directory for which information is being requested. + * \param[in] Event An optional handle for a caller-created event. The event is set to the Signaled state the requested operation is completed. + * \param[in] ApcRoutine An address of an optional, caller-supplied APC routine to be called when the requested operation completes. + * \param[in] ApcContext An address of an optional, caller-supplied APC or I/O completion object associated with the file object. + * \param[out] IoStatusBlock A pointer to an IO_STATUS_BLOCK structure that receives the final completion status, and the number of bytes written to the buffer pointed to by FileInformation. + * \param[out] FileInformation A pointer to a buffer that receives the desired information about the file. + * \param[in] Length The size, in bytes, of the buffer pointed to by FileInformation. + * \param[in] FileInformationClass The type of information to be returned about files in the directory. + * \param[in] QueryFlags One or more of the flags contained in SL_QUERY_DIRECTORY_MASK + * \param[in] FileName An optional pointer to a Unicode string search expression containing the name of a file (or multiple files, if wildcards are used) within the directory. + * \return NTSTATUS Successful or errant status. + * \sa https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/ntifs/nf-ntifs-ntquerydirectoryfileex + */ NTSYSCALLAPI NTSTATUS NTAPI @@ -1822,9 +2189,9 @@ NtQueryDirectoryFileEx( _In_ ULONG Length, _In_ FILE_INFORMATION_CLASS FileInformationClass, _In_ ULONG QueryFlags, - _In_opt_ PUNICODE_STRING FileName + _In_opt_ PCUNICODE_STRING FileName ); -#endif +#endif // PHNT_VERSION >= PHNT_WINDOWS_10_RS3 NTSYSCALLAPI NTSTATUS @@ -1876,6 +2243,17 @@ NtSetQuotaInformationFile( _In_ ULONG Length ); +/** + * The NtQueryVolumeInformationFile routine retrieves information about the volume associated with a given file, directory, storage device, or volume. + * + * \param[in] FileHandle A handle to the file, directory, storage device, or volume for which volume information is being requested. + * \param[out] IoStatusBlock A pointer to an IO_STATUS_BLOCK structure that receives the final completion status, and the number of bytes written to the buffer pointed to by FsInformation. + * \param[out] FsInformation A pointer to a caller-allocated buffer that receives the desired information about the volume. + * \param[in] Length The size, in bytes, of the buffer pointed to by FsInformation. + * \param[in] FsInformationClass The type of information to be returned about the volume. + * \return NTSTATUS Successful or errant status. + * \sa https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/ntifs/nf-ntifs-ntqueryvolumeinformationfile + */ NTSYSCALLAPI NTSTATUS NTAPI @@ -1887,6 +2265,17 @@ NtQueryVolumeInformationFile( _In_ FSINFOCLASS FsInformationClass ); +/** + * The NtSetVolumeInformationFile routine modifies information about the volume associated with a given file, directory, storage device, or volume. + * + * \param[in] FileHandle A handle to the file, directory, storage device, or volume for which volume information is being requested. + * \param[out] IoStatusBlock A pointer to an IO_STATUS_BLOCK structure that receives the final completion status, and the number of bytes written to the buffer pointed to by FsInformation. + * \param[in] FsInformation A pointer to a caller-allocated buffer containing the volume information to be modified. + * \param[in] Length The size, in bytes, of the buffer pointed to by FsInformation. + * \param[in] FsInformationClass The type of information to set about the volume. + * \return NTSTATUS Successful or errant status. + * \sa https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/ntifs/nf-ntifs-zwsetvolumeinformationfile + */ NTSYSCALLAPI NTSTATUS NTAPI @@ -1906,7 +2295,6 @@ NtCancelIoFile( _Out_ PIO_STATUS_BLOCK IoStatusBlock ); -#if (PHNT_VERSION >= PHNT_WINDOWS_VISTA) NTSYSCALLAPI NTSTATUS NTAPI @@ -1915,9 +2303,7 @@ NtCancelIoFileEx( _In_opt_ PIO_STATUS_BLOCK IoRequestToCancel, _Out_ PIO_STATUS_BLOCK IoStatusBlock ); -#endif -#if (PHNT_VERSION >= PHNT_WINDOWS_VISTA) NTSYSCALLAPI NTSTATUS NTAPI @@ -1926,8 +2312,23 @@ NtCancelSynchronousIoFile( _In_opt_ PIO_STATUS_BLOCK IoRequestToCancel, _Out_ PIO_STATUS_BLOCK IoStatusBlock ); -#endif +/** + * The NtDeviceIoControlFile function sends a control code directly to a specified device driver, causing the corresponding driver to perform the specified operation. + * + * \param[in] FileHandle A handle to the file object representing the file or directory on which the specified action is to be performed. + * \param[in] Event A handle for a caller-created event. This parameter is optional and can be NULL. It must be NULL if the caller will wait for the FileHandle to be set to the Signaled state. + * \param[in] ApcRoutine Address of a caller-supplied APC routine to be called when the requested operation completes. This parameter is optional and can be NULL. + * \param[in] ApcContext Pointer to a caller-determined context area. This parameter value is used as the APC context if the caller supplies an APC, or is used as the completion context if an I/O completion object has been associated with the file object. + * \param[out] IoStatusBlock Pointer to an IO_STATUS_BLOCK structure that receives the final completion status and information about the operation. + * \param[in] IoControlCode IOCTL_XXX code that indicates which device I/O control operation is to be carried out on, usually by the underlying device driver. + * \param[in] InputBuffer Pointer to a caller-allocated input buffer that contains device-specific information to be given to the target driver. + * \param[in] InputBufferLength Size, in bytes, of the buffer at InputBuffer. This value is ignored if InputBuffer is NULL. + * \param[out] OutputBuffer Pointer to a caller-allocated output buffer in which information is returned from the target driver. + * \param[in] OutputBufferLength Size, in bytes, of the buffer at OutputBuffer. This value is ignored if OutputBuffer is NULL. + * \return NTSTATUS Successful or errant status. + * \sa https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/ntifs/nf-ntifs-zwdeviceiocontrolfile + */ NTSYSCALLAPI NTSTATUS NTAPI @@ -1944,6 +2345,22 @@ NtDeviceIoControlFile( _In_ ULONG OutputBufferLength ); +/** + * The NtFsControlFile function sends a control code directly to a file system or filter driver, causing the corresponding driver to perform the specified action. + * + * \param[in] FileHandle A handle to the file object representing the file or directory on which the specified action is to be performed. + * \param[in] Event A handle for a caller-created event. This parameter is optional and can be NULL. It must be NULL if the caller will wait for the FileHandle to be set to the Signaled state. + * \param[in] ApcRoutine Address of a caller-supplied APC routine to be called when the requested operation completes. This parameter is optional and can be NULL. + * \param[in] ApcContext Pointer to a caller-determined context area. This parameter value is used as the APC context if the caller supplies an APC, or is used as the completion context if an I/O completion object has been associated with the file object. + * \param[out] IoStatusBlock Pointer to an IO_STATUS_BLOCK structure that receives the final completion status and information about the operation. + * \param[in] FsControlCode FSCTL_XXX code that indicates which file system control operation is to be carried out. + * \param[in] InputBuffer Pointer to a caller-allocated input buffer that contains device-specific information to be given to the target driver. + * \param[in] InputBufferLength Size, in bytes, of the buffer at InputBuffer. This value is ignored if InputBuffer is NULL. + * \param[out] OutputBuffer Pointer to a caller-allocated output buffer in which information is returned from the target driver. + * \param[in] OutputBufferLength Size, in bytes, of the buffer at OutputBuffer. This value is ignored if OutputBuffer is NULL. + * \return NTSTATUS Successful or errant status. + * \sa https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/ntifs/nf-ntifs-zwfscontrolfile + */ NTSYSCALLAPI NTSTATUS NTAPI @@ -1960,6 +2377,21 @@ NtFsControlFile( _In_ ULONG OutputBufferLength ); +/** + * The NtReadFile function reads data from an open file. + * + * \param[in] FileHandle A handle to the file object representing the file or directory on which the specified action is to be performed. + * \param[in] Event A handle for a caller-created event. This parameter is optional and can be NULL. It must be NULL if the caller will wait for the FileHandle to be set to the Signaled state. + * \param[in] ApcRoutine Address of a caller-supplied APC routine to be called when the requested operation completes. This parameter is optional and can be NULL. + * \param[in] ApcContext Pointer to a caller-determined context area. This parameter value is used as the APC context if the caller supplies an APC, or is used as the completion context if an I/O completion object has been associated with the file object. + * \param[out] IoStatusBlock Pointer to an IO_STATUS_BLOCK structure that receives the final completion status and information about the operation. + * \param[out] Buffer Pointer to a caller-allocated buffer that receives the data read from the file. + * \param[in] Length The size, in bytes, of the buffer pointed to by Buffer. + * \param[in] ByteOffset Pointer to a variable that specifies the starting byte offset in the file where the read operation will begin. + * \param[in] Key Device and intermediate drivers should set this pointer to NULL. + * \return NTSTATUS Successful or errant status. + * \sa https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/wdm/nf-wdm-zwreadfile + */ NTSYSCALLAPI NTSTATUS NTAPI @@ -1975,6 +2407,21 @@ NtReadFile( _In_opt_ PULONG Key ); +/** + * The NtWriteFile function writes data to an open file. + * + * \param[in] FileHandle A handle to the file object representing the file or directory on which the specified action is to be performed. + * \param[in] Event A handle for a caller-created event. This parameter is optional and can be NULL. It must be NULL if the caller will wait for the FileHandle to be set to the Signaled state. + * \param[in] ApcRoutine Address of a caller-supplied APC routine to be called when the requested operation completes. This parameter is optional and can be NULL. + * \param[in] ApcContext Pointer to a caller-determined context area. This parameter value is used as the APC context if the caller supplies an APC, or is used as the completion context if an I/O completion object has been associated with the file object. + * \param[out] IoStatusBlock Pointer to an IO_STATUS_BLOCK structure that receives the final completion status and information about the operation. + * \param[in] Buffer Pointer to a caller-allocated buffer that contains the data to write to the file. + * \param[in] Length The size, in bytes, of the buffer pointed to by Buffer. + * \param[in] ByteOffset Pointer to a variable that specifies the starting byte offset in the file for beginning the write operation. + * \param[in] Key Device and intermediate drivers should set this pointer to NULL. + * \return NTSTATUS Successful or errant status. + * \sa https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/wdm/nf-wdm-zwwritefile + */ NTSYSCALLAPI NTSTATUS NTAPI @@ -2047,22 +2494,42 @@ NtUnlockFile( _In_ ULONG Key ); +/** + * The NtQueryAttributesFile function retrieves basic attributes for the specified file. + * + * \param ObjectAttributes A pointer to an OBJECT_ATTRIBUTES structure that supplies the attributes to be used for the file object. + * \param FileInformation A pointer to a FILE_BASIC_INFORMATION structure to receive the returned file attribute information. + * \return NTSTATUS Successful or errant status. + * \sa https://learn.microsoft.com/en-us/windows/win32/devnotes/ntqueryattributesfile + */ NTSYSCALLAPI NTSTATUS NTAPI NtQueryAttributesFile( - _In_ POBJECT_ATTRIBUTES ObjectAttributes, + _In_ PCOBJECT_ATTRIBUTES ObjectAttributes, _Out_ PFILE_BASIC_INFORMATION FileInformation ); +/** + * The NtQueryFullAttributesFile function retrieves network open information for the specified file. + * + * \param ObjectAttributes A pointer to an OBJECT_ATTRIBUTES structure that supplies the attributes to be used for the file object. + * \param FileInformation A pointer to a FILE_NETWORK_OPEN_INFORMATION structure that receives the returned file attributes information. + * \return NTSTATUS Successful or errant status. + * \sa https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/wdm/nf-wdm-zwqueryfullattributesfile + */ NTSYSCALLAPI NTSTATUS NTAPI NtQueryFullAttributesFile( - _In_ POBJECT_ATTRIBUTES ObjectAttributes, + _In_ PCOBJECT_ATTRIBUTES ObjectAttributes, _Out_ PFILE_NETWORK_OPEN_INFORMATION FileInformation ); +// +// NtNotifyChangeDirectoryFile information +// + #define FILE_NOTIFY_CHANGE_FILE_NAME 0x00000001 // winnt #define FILE_NOTIFY_CHANGE_DIR_NAME 0x00000002 // winnt #define FILE_NOTIFY_CHANGE_NAME 0x00000003 @@ -2115,6 +2582,7 @@ typedef enum _DIRECTORY_NOTIFY_INFORMATION_CLASS } DIRECTORY_NOTIFY_INFORMATION_CLASS, *PDIRECTORY_NOTIFY_INFORMATION_CLASS; #if !defined(NTDDI_WIN10_RS5) || (NTDDI_VERSION < NTDDI_WIN10_RS5) +_Struct_size_bytes_(NextEntryOffset) typedef struct _FILE_NOTIFY_INFORMATION { ULONG NextEntryOffset; @@ -2123,6 +2591,7 @@ typedef struct _FILE_NOTIFY_INFORMATION WCHAR FileName[1]; } FILE_NOTIFY_INFORMATION, *PFILE_NOTIFY_INFORMATION; +_Struct_size_bytes_(NextEntryOffset) typedef struct _FILE_NOTIFY_EXTENDED_INFORMATION { ULONG NextEntryOffset; @@ -2139,8 +2608,8 @@ typedef struct _FILE_NOTIFY_EXTENDED_INFORMATION ULONG ReparsePointTag; ULONG EaSize; }; - LARGE_INTEGER FileId; - LARGE_INTEGER ParentFileId; + FILE_INTERNAL_INFORMATION FileId; + FILE_INTERNAL_INFORMATION ParentFileId; ULONG FileNameLength; WCHAR FileName[1]; } FILE_NOTIFY_EXTENDED_INFORMATION, *PFILE_NOTIFY_EXTENDED_INFORMATION; @@ -2153,6 +2622,7 @@ typedef struct _FILE_NOTIFY_EXTENDED_INFORMATION #define FILE_NAME_FLAGS_UNSPECIFIED 0x80 // not specified by file system (do not combine with other flags) #if !defined(NTDDI_WIN10_NI) || (NTDDI_VERSION < NTDDI_WIN10_NI) +_Struct_size_bytes_(NextEntryOffset) typedef struct _FILE_NOTIFY_FULL_INFORMATION { ULONG NextEntryOffset; @@ -2169,14 +2639,14 @@ typedef struct _FILE_NOTIFY_FULL_INFORMATION ULONG ReparsePointTag; ULONG EaSize; }; - LARGE_INTEGER FileId; - LARGE_INTEGER ParentFileId; + FILE_INTERNAL_INFORMATION FileId; + FILE_INTERNAL_INFORMATION ParentFileId; USHORT FileNameLength; BYTE FileNameFlags; BYTE Reserved; WCHAR FileName[1]; } FILE_NOTIFY_FULL_INFORMATION, *PFILE_NOTIFY_FULL_INFORMATION; -#endif +#endif // NTDDI_WIN10_NI #if (PHNT_VERSION >= PHNT_WINDOWS_10_RS3) NTSYSCALLAPI @@ -2194,44 +2664,37 @@ NtNotifyChangeDirectoryFileEx( _In_ BOOLEAN WatchTree, _In_opt_ DIRECTORY_NOTIFY_INFORMATION_CLASS DirectoryNotifyInformationClass ); -#endif +#endif // PHNT_VERSION >= PHNT_WINDOWS_10_RS3 /** - * \brief The NtLoadDriver function loads a driver specified by the DriverServiceName parameter. + * The NtLoadDriver function loads a driver specified by the DriverServiceName parameter. + * * \param DriverServiceName A pointer to a UNICODE_STRING structure that specifies the name of the driver service to load. - * \return NTSTATUS The status code returned by the function. Possible values include, but are not limited to: - * - STATUS_SUCCESS: The driver was successfully loaded. - * - STATUS_INVALID_PARAMETER: The DriverServiceName parameter is invalid. - * - STATUS_INSUFFICIENT_RESOURCES: There are insufficient resources to load the driver. - * - STATUS_OBJECT_NAME_NOT_FOUND: The specified driver service name was not found. - * - STATUS_OBJECT_PATH_NOT_FOUND: The path to the driver service was not found. - * - STATUS_OBJECT_NAME_COLLISION: A driver with the same name already exists. + * \return NTSTATUS Successful or errant status. */ NTSYSCALLAPI NTSTATUS NTAPI NtLoadDriver( - _In_ PUNICODE_STRING DriverServiceName + _In_ PCUNICODE_STRING DriverServiceName ); /** - * \brief The NtUnloadDriver function unloads a driver specified by the DriverServiceName parameter. + * The NtUnloadDriver function unloads a driver specified by the DriverServiceName parameter. + * * \param DriverServiceName A pointer to a UNICODE_STRING structure that specifies the name of the driver service to unload. - * \return NTSTATUS The status code returned by the function. Possible values include, but are not limited to: - * - STATUS_SUCCESS: The driver was successfully unloaded. - * - STATUS_INVALID_PARAMETER: The DriverServiceName parameter is invalid. - * - STATUS_OBJECT_NAME_NOT_FOUND: The specified driver service name was not found. - * - STATUS_OBJECT_PATH_NOT_FOUND: The path to the driver service was not found. - * - STATUS_OBJECT_NAME_COLLISION: A driver with the same name already exists. + * \return NTSTATUS Successful or errant status. */ NTSYSCALLAPI NTSTATUS NTAPI NtUnloadDriver( - _In_ PUNICODE_STRING DriverServiceName + _In_ PCUNICODE_STRING DriverServiceName ); +// // I/O completion port +// #ifndef IO_COMPLETION_QUERY_STATE #define IO_COMPLETION_QUERY_STATE 0x0001 @@ -2261,7 +2724,7 @@ NTAPI NtCreateIoCompletion( _Out_ PHANDLE IoCompletionHandle, _In_ ACCESS_MASK DesiredAccess, - _In_opt_ POBJECT_ATTRIBUTES ObjectAttributes, + _In_opt_ PCOBJECT_ATTRIBUTES ObjectAttributes, _In_opt_ ULONG NumberOfConcurrentThreads ); @@ -2271,7 +2734,7 @@ NTAPI NtOpenIoCompletion( _Out_ PHANDLE IoCompletionHandle, _In_ ACCESS_MASK DesiredAccess, - _In_ POBJECT_ATTRIBUTES ObjectAttributes + _In_ PCOBJECT_ATTRIBUTES ObjectAttributes ); NTSYSCALLAPI @@ -2296,7 +2759,6 @@ NtSetIoCompletion( _In_ ULONG_PTR IoStatusInformation ); -#if (PHNT_VERSION >= PHNT_WINDOWS_7) NTSYSCALLAPI NTSTATUS NTAPI @@ -2308,7 +2770,6 @@ NtSetIoCompletionEx( _In_ NTSTATUS IoStatus, _In_ ULONG_PTR IoStatusInformation ); -#endif NTSYSCALLAPI NTSTATUS @@ -2321,7 +2782,6 @@ NtRemoveIoCompletion( _In_opt_ PLARGE_INTEGER Timeout ); -#if (PHNT_VERSION >= PHNT_WINDOWS_VISTA) // private typedef struct _FILE_IO_COMPLETION_INFORMATION { @@ -2341,7 +2801,6 @@ NtRemoveIoCompletionEx( _In_opt_ PLARGE_INTEGER Timeout, _In_ BOOLEAN Alertable ); -#endif // (PHNT_VERSION >= PHNT_WINDOWS_VISTA) // // Wait completion packet @@ -2349,15 +2808,58 @@ NtRemoveIoCompletionEx( #if (PHNT_VERSION >= PHNT_WINDOWS_8) +/** + * The NtCreateWaitCompletionPacket routine creates a wait completion packet object. + * + * A wait completion packet is a kernel object that can be associated with wait + * or I/O completion sources and later queried via I/O completion mechanisms. + * + * \param WaitCompletionPacketHandle Pointer to a variable that receives a handle + * to the newly created wait completion packet object. + * \param DesiredAccess The access mask that specifies the requested access to + * the wait completion packet object. + * \param ObjectAttributes Optional pointer to an OBJECT_ATTRIBUTES structure that + * supplies the object name and other attributes. May be NULL. + * \return NTSTATUS Successful or errant status. + */ NTSYSCALLAPI NTSTATUS NTAPI NtCreateWaitCompletionPacket( _Out_ PHANDLE WaitCompletionPacketHandle, _In_ ACCESS_MASK DesiredAccess, - _In_opt_ POBJECT_ATTRIBUTES ObjectAttributes + _In_opt_ PCOBJECT_ATTRIBUTES ObjectAttributes ); +/** + * The NtAssociateWaitCompletionPacket routine associates a wait completion packet + * with an I/O completion port or other target object so that a completion packet + * will be queued when the target object becomes signaled or an I/O completes. + * + * This routine links the specified wait completion packet with the target + * completion object so the packet will carry the supplied context and status + * information when it is delivered. + * + * \param[in] WaitCompletionPacketHandle Handle to the wait completion packet object. + * \param[in] IoCompletionHandle Handle to an I/O completion port (or compatible object) + * with which the wait completion packet should be associated. + * \param[in] TargetObjectHandle Handle to the object to watch for completion or + * signalling (for example, a waitable kernel object). + * \param[in] KeyContext Optional pointer to caller-specified context that will be + * stored in the completion packet and returned to the consumer. + * \param[in] ApcContext Optional pointer to caller-specified APC/context value that + * will be stored in the completion packet and returned to the consumer. + * \param[in] IoStatus The NTSTATUS value to be placed in the completion packet. + * \param[in] IoStatusInformation Additional information ( ULONG_PTR ) to be placed + * in the completion packet (commonly used for number of bytes transferred). + * \param[out] AlreadySignaled Optional pointer to a BOOLEAN that, on return, is set + * to TRUE if the packet was already signaled at the time of association; + * otherwise FALSE. May be NULL. + * \return NTSTATUS Successful or errant status. + * \remarks Use this routine to arrange for notification of a target object's + * completion by queuing a wait completion packet containing the + * supplied context and status. + */ NTSYSCALLAPI NTSTATUS NTAPI @@ -2372,6 +2874,18 @@ NtAssociateWaitCompletionPacket( _Out_opt_ PBOOLEAN AlreadySignaled ); +/** + * The NtCancelWaitCompletionPacket routine cancels a previously associated wait + * completion packet or removes a signaled packet from its queue. + * + * \param[in] WaitCompletionPacketHandle Handle to the wait completion packet object to cancel. + * \param[in] RemoveSignaledPacket If TRUE and the packet is already signaled, remove + * the signaled packet from the target queue; if FALSE, cancellation will + * prevent future signaling but will not remove an already queued packet. + * \return NTSTATUS Successful or errant status. + * \remarks After successful cancellation, the wait completion packet will no + * longer be delivered as a result of the previously associated target. + */ NTSYSCALLAPI NTSTATUS NTAPI @@ -2383,6 +2897,32 @@ NtCancelWaitCompletionPacket( #endif // (PHNT_VERSION >= PHNT_WINDOWS_8) #if (PHNT_VERSION >= PHNT_WINDOWS_11) +/** + * The NtCopyFileChunk routine copies a contiguous range of bytes (a chunk) + * from a source file to a destination file. The operation may be performed + * synchronously or asynchronously depending on the file handles and flags. + * + * \param[in] SourceHandle Handle to the source file. The handle must be opened + * with access that allows reading the specified range. + * \param[in] DestinationHandle Handle to the destination file. The handle must + * be opened with access that allows writing to the specified range. + * \param[in] EventHandle Optional handle to an event object. If provided, + * the event is set when the operation completes. May be NULL. + * \param[out] IoStatusBlock Pointer to an IO_STATUS_BLOCK structure that + * receives the final completion status and information about the operation. + * \param[in] Length The number of bytes to copy. + * \param[in] SourceOffset Pointer to a LARGE_INTEGER specifying the byte + * offset in the source file at which copying begins. + * \param[in] DestOffset Pointer to a LARGE_INTEGER specifying the byte + * offset in the destination file at which copying begins. + * \param[in] SourceKey Optional pointer to a source file key. May be NULL. + * \param[in] DestKey Optional pointer to a destination file key. May be NULL. + * \param[in] Flags Additional flags controlling copy semantics. + * \return NTSTATUS Successful or errant status. + * \remarks The exact meaning and required privileges for `Flags` and keys may + * depend on the Windows version and file system. Consumers should + * verify handle access rights and the platform's support for this call. + */ NTSYSCALLAPI NTSTATUS NTAPI @@ -2629,8 +3169,9 @@ typedef struct _REPARSE_DATA_BUFFER_EX #define REPARSE_DATA_BUFFER_EX_HEADER_SIZE \ UFIELD_OFFSET(REPARSE_DATA_BUFFER_EX, ReparseDataBuffer.GenericReparseBuffer) - +// // Named pipe FS control definitions +// #define DEVICE_NAMED_PIPE L"\\Device\\NamedPipe\\" @@ -2864,6 +3405,7 @@ typedef struct _MOUNTMGR_MOUNT_POINT } MOUNTMGR_MOUNT_POINT, *PMOUNTMGR_MOUNT_POINT; // Output structure for IOCTL_MOUNTMGR_DELETE_POINTS, IOCTL_MOUNTMGR_QUERY_POINTS, and IOCTL_MOUNTMGR_DELETE_POINTS_DBONLY. +_Struct_size_bytes_(Size) typedef struct _MOUNTMGR_MOUNT_POINTS { ULONG Size; @@ -3161,7 +3703,9 @@ typedef struct _FLT_ATTACH USHORT AltitudeOffset; // to WCHAR[] from this struct } FLT_ATTACH, *PFLT_ATTACH; +// // Multiple UNC Provider +// // rev // FSCTLs for \Device\Mup #define FSCTL_MUP_GET_UNC_CACHE_INFO CTL_CODE(FILE_DEVICE_MULTI_UNC_PROVIDER, 11, METHOD_BUFFERED, FILE_ANY_ACCESS) // out: MUP_FSCTL_UNC_CACHE_INFORMATION @@ -3515,39 +4059,6 @@ typedef struct _MUP_FSCTL_QUERY_UNC_HARDENING_CONFIGURATION_OUT #define DO_DEVICE_TO_BE_RESET 0x04000000 #define DO_DAX_VOLUME 0x10000000 -// -// 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) - // pub typedef enum _FS_FILTER_SECTION_SYNC_TYPE { @@ -3631,4 +4142,4 @@ typedef struct _OPLOCK_KEY_CONTEXT #endif // (PHNT_MODE != PHNT_MODE_KERNEL) -#endif +#endif // _NTIOAPI_H diff --git a/ntkeapi.h b/ntkeapi.h index 9b06855..fa96dcc 100644 --- a/ntkeapi.h +++ b/ntkeapi.h @@ -12,7 +12,7 @@ #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 +#endif // (PHNT_MODE != PHNT_MODE_KERNEL) typedef enum _KTHREAD_STATE { @@ -61,17 +61,17 @@ typedef enum _KWAIT_REASON WrExecutive, // Waiting for an executive event. WrFreePage, // Waiting for a free page. WrPageIn, // Waiting for a page to be read in. - WrPoolAllocation, // Waiting for a pool allocation. + WrPoolAllocation, // Waiting for a pool allocation. // 10 WrDelayExecution, // Waiting due to a delay execution. WrSuspended, // Waiting because the thread is suspended. WrUserRequest, // Waiting due to a user request. WrEventPair, // Waiting for an event pair. // NtCreateEventPair WrQueue, // Waiting for a queue. // NtRemoveIoCompletion - WrLpcReceive, // Waiting for an LPC receive. - WrLpcReply, // Waiting for an LPC reply. + WrLpcReceive, // Waiting for an LPC receive. // NtReplyWaitReceivePort + WrLpcReply, // Waiting for an LPC reply. // NtRequestWaitReplyPort WrVirtualMemory, // Waiting for virtual memory. - WrPageOut, // Waiting for a page to be written out. - WrRendezvous, // Waiting for a rendezvous. + WrPageOut, // Waiting for a page to be written out. // NtFlushVirtualMemory + WrRendezvous, // Waiting for a rendezvous. // 20 WrKeyedEvent, // Waiting for a keyed event. // NtCreateKeyedEvent WrTerminated, // Waiting for thread termination. WrProcessInSwap, // Waiting for a process to be swapped in. @@ -81,7 +81,7 @@ typedef enum _KWAIT_REASON WrResource, // Waiting for a resource. WrPushLock, // Waiting for a push lock. WrMutex, // Waiting for a mutex. - WrQuantumEnd, // Waiting for the end of a quantum. + WrQuantumEnd, // Waiting for the end of a quantum. // 30 WrDispatchInt, // Waiting for a dispatch interrupt. WrPreempted, // Waiting because the thread was preempted. WrYieldExecution, // Waiting to yield execution. @@ -91,7 +91,7 @@ typedef enum _KWAIT_REASON WrAlertByThreadId, // Waiting for an alert by thread ID. WrDeferredPreempt, // Waiting for a deferred preemption. WrPhysicalFault, // Waiting for a physical fault. - WrIoRing, // Waiting for an I/O ring. + WrIoRing, // Waiting for an I/O ring. // 40 WrMdlCache, // Waiting for an MDL cache. WrRcu, // Waiting for read-copy-update (RCU) synchronization. MaximumWaitReason @@ -126,7 +126,7 @@ typedef enum _KPROFILE_SOURCE ProfileMaximum } KPROFILE_SOURCE; -#endif +#endif // (PHNT_MODE != PHNT_MODE_KERNEL) #if (PHNT_MODE != PHNT_MODE_KERNEL) @@ -139,21 +139,6 @@ NtCallbackReturn( _In_ NTSTATUS Status ); -#if (PHNT_VERSION >= PHNT_WINDOWS_VISTA) -/** - * The NtFlushProcessWriteBuffers routine flushes the write queue of each processor that is running a thread of the current process. - * - * @return NTSTATUS Successful or errant status. - * @see https://learn.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-flushprocesswritebuffers - */ -NTSYSCALLAPI -NTSTATUS -NTAPI -NtFlushProcessWriteBuffers( - VOID - ); -#endif - NTSYSCALLAPI NTSTATUS NTAPI @@ -178,6 +163,6 @@ NtYieldExecution( VOID ); -#endif +#endif // (PHNT_MODE != PHNT_MODE_KERNEL) -#endif +#endif // _NTKEAPI_H diff --git a/ntldr.h b/ntldr.h index fde2770..dd334f8 100644 --- a/ntldr.h +++ b/ntldr.h @@ -14,25 +14,28 @@ typedef struct _LDRP_LOAD_CONTEXT *PLDRP_LOAD_CONTEXT; // DLLs // -typedef _Function_class_(LDR_INIT_ROUTINE) -BOOLEAN NTAPI LDR_INIT_ROUTINE( +typedef _Function_class_(DLL_INIT_ROUTINE) +BOOLEAN NTAPI DLL_INIT_ROUTINE( _In_ PVOID DllHandle, _In_ ULONG Reason, _In_opt_ PVOID Context ); -typedef LDR_INIT_ROUTINE* PLDR_INIT_ROUTINE; +typedef DLL_INIT_ROUTINE* PDLL_INIT_ROUTINE; +// private typedef struct _LDR_SERVICE_TAG_RECORD { struct _LDR_SERVICE_TAG_RECORD *Next; ULONG ServiceTag; } LDR_SERVICE_TAG_RECORD, *PLDR_SERVICE_TAG_RECORD; +// private typedef struct _LDRP_CSLIST { PSINGLE_LIST_ENTRY Tail; } LDRP_CSLIST, *PLDRP_CSLIST; +// private typedef enum _LDR_DDAG_STATE { LdrModulesMerged = -5, @@ -52,13 +55,14 @@ typedef enum _LDR_DDAG_STATE LdrModulesReadyToRun = 9 } LDR_DDAG_STATE; +// private typedef struct _LDR_DDAG_NODE { LIST_ENTRY Modules; PLDR_SERVICE_TAG_RECORD ServiceTagList; ULONG LoadCount; - ULONG LoadWhileUnloadingCount; - ULONG LowestLink; + ULONG LoadWhileUnloadingCount; // ReferenceCount before WIN10 + ULONG LowestLink; // DependencyCount before WIN10 union { LDRP_CSLIST Dependencies; @@ -70,30 +74,40 @@ typedef struct _LDR_DDAG_NODE ULONG PreorderNumber; } LDR_DDAG_NODE, *PLDR_DDAG_NODE; -// rev -typedef struct _LDR_DEPENDENCY_RECORD +// private +typedef struct _LDRP_DEPENDENCY { - SINGLE_LIST_ENTRY DependencyLink; - PLDR_DDAG_NODE DependencyNode; - SINGLE_LIST_ENTRY IncomingDependencyLink; - PLDR_DDAG_NODE IncomingDependencyNode; -} LDR_DEPENDENCY_RECORD, *PLDR_DEPENDENCY_RECORD; + SINGLE_LIST_ENTRY Link; + PLDR_DDAG_NODE ChildNode; + SINGLE_LIST_ENTRY BackLink; + union + { + PLDR_DDAG_NODE ParentNode; + struct + { + ULONG ForwarderLink : 1; + ULONG SpareFlags : 2; + }; + }; +} LDRP_DEPENDENCY, *PLDRP_DEPENDENCY; +// LoadReason typedef enum _LDR_DLL_LOAD_REASON { - LoadReasonStaticDependency, - LoadReasonStaticForwarderDependency, - LoadReasonDynamicForwarderDependency, - LoadReasonDelayloadDependency, - LoadReasonDynamicLoad, - LoadReasonAsImageLoad, - LoadReasonAsDataLoad, - LoadReasonEnclavePrimary, // since REDSTONE3 - LoadReasonEnclaveDependency, - LoadReasonPatchImage, // since WIN11 - LoadReasonUnknown = -1 + LoadReasonUnknown = -1, + LoadReasonStaticDependency = 0, + LoadReasonStaticForwarderDependency = 1, + LoadReasonDynamicForwarderDependency = 2, + LoadReasonDelayloadDependency = 3, + LoadReasonDynamicLoad = 4, + LoadReasonAsImageLoad = 5, + LoadReasonAsDataLoad = 6, + LoadReasonEnclavePrimary = 7, // since REDSTONE3 + LoadReasonEnclaveDependency = 8, + LoadReasonPatchImage = 9, // since WIN11 } LDR_DLL_LOAD_REASON, *PLDR_DLL_LOAD_REASON; +// HotPatchState typedef enum _LDR_HOT_PATCH_STATE { LdrHotPatchBaseImage, @@ -115,19 +129,22 @@ typedef enum _LDR_HOT_PATCH_STATE #define LDRP_IN_INDEXES 0x00000080 #define LDRP_SHIM_DLL 0x00000100 #define LDRP_IN_EXCEPTION_TABLE 0x00000200 +#define LDRP_VERIFIER_PROVIDER 0x00000400 // reserved before WIN11 24H2 +#define LDRP_SHIM_ENGINE_CALLOUT_SENT 0x00000800 // reserved before WIN11 24H2 #define LDRP_LOAD_IN_PROGRESS 0x00001000 -#define LDRP_LOAD_CONFIG_PROCESSED 0x00002000 +#define LDRP_LOAD_CONFIG_PROCESSED 0x00002000 // reserved before WIN10 #define LDRP_ENTRY_PROCESSED 0x00004000 -#define LDRP_PROTECT_DELAY_LOAD 0x00008000 +#define LDRP_PROTECT_DELAY_LOAD 0x00008000 // reserved before WINBLUE +#define LDRP_AUX_IAT_COPY_PRIVATE 0x00010000 // reserved before WIN11 24H2 #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_SCP_IN_EXCEPTION_TABLE 0x00200000 // LDRP_COR_DEFERRED_VALIDATE before WIN11 24H2 #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_CHPE_IMAGE 0x02000000 // reserved before REDSTONE4 +#define LDRP_CHPE_EMULATOR_IMAGE 0x04000000 // reserved before WIN11 #define LDRP_REDIRECTED 0x10000000 #define LDRP_COMPAT_DATABASE_PROCESSED 0x80000000 @@ -144,7 +161,7 @@ typedef struct _LDR_DATA_TABLE_ENTRY LIST_ENTRY InMemoryOrderLinks; LIST_ENTRY InInitializationOrderLinks; PVOID DllBase; - PLDR_INIT_ROUTINE EntryPoint; + PVOID EntryPoint; // PDLL_INIT_ROUTINE ULONG SizeOfImage; UNICODE_STRING FullDllName; UNICODE_STRING BaseDllName; @@ -164,21 +181,23 @@ typedef struct _LDR_DATA_TABLE_ENTRY ULONG InIndexes : 1; ULONG ShimDll : 1; ULONG InExceptionTable : 1; - ULONG ReservedFlags1 : 2; + ULONG VerifierProvider : 1; // 24H2 + ULONG ShimEngineCalloutSent : 1; // 24H2 ULONG LoadInProgress : 1; - ULONG LoadConfigProcessed : 1; + ULONG LoadConfigProcessed : 1; // WIN10 ULONG EntryProcessed : 1; - ULONG ProtectDelayLoad : 1; - ULONG ReservedFlags3 : 2; + ULONG ProtectDelayLoad : 1; // WINBLUE + ULONG AuxIatCopyPrivate : 1; // 24H2 + ULONG ReservedFlags3 : 1; ULONG DontCallForThreads : 1; ULONG ProcessAttachCalled : 1; ULONG ProcessAttachFailed : 1; - ULONG CorDeferredValidate : 1; + ULONG ScpInExceptionTable : 1; // CorDeferredValidate before 24H2 ULONG CorImage : 1; ULONG DontRelocate : 1; ULONG CorILOnly : 1; - ULONG ChpeImage : 1; - ULONG ChpeEmulatorImage : 1; + ULONG ChpeImage : 1; // RS4 + ULONG ChpeEmulatorImage : 1; // WIN11 ULONG ReservedFlags5 : 1; ULONG Redirected : 1; ULONG ReservedFlags6 : 2; @@ -201,16 +220,18 @@ typedef struct _LDR_DATA_TABLE_ENTRY PVOID OriginalBase; LARGE_INTEGER LoadTime; ULONG BaseNameHashValue; - LDR_DLL_LOAD_REASON LoadReason; // since WIN8 - ULONG ImplicitPathOptions; + LDR_DLL_LOAD_REASON LoadReason; + ULONG ImplicitPathOptions; // since WINBLUE ULONG ReferenceCount; // since WIN10 - ULONG DependentLoadFlags; - UCHAR SigningLevel; // since REDSTONE2 - ULONG CheckSum; // since 22H1 + ULONG DependentLoadFlags; // since RS1 + UCHAR SigningLevel; // since RS2 + ULONG CheckSum; // since WIN11 PVOID ActivePatchImageBase; LDR_HOT_PATCH_STATE HotPatchState; } LDR_DATA_TABLE_ENTRY, *PLDR_DATA_TABLE_ENTRY; +typedef const LDR_DATA_TABLE_ENTRY* PCLDR_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)) @@ -221,16 +242,50 @@ typedef struct _LDR_DATA_TABLE_ENTRY #if (PHNT_MODE != PHNT_MODE_KERNEL) +// rev LdrLoadDll DllCharacteristics +#define LDR_DONT_RESOLVE_DLL_REFERENCES 0x00000002 // IMAGE_FILE_EXECUTABLE_IMAGE maps to DONT_RESOLVE_DLL_REFERENCES +#define LDR_PACKAGED_LIBRARY 0x00000004 // LOAD_PACKAGED_LIBRARY +#define LDR_REQUIRE_SIGNED_TARGET 0x00800000 // maps to LOAD_LIBRARY_REQUIRE_SIGNED_TARGET (requires /INTEGRITYCHECK) +#define LDR_OS_INTEGRITY_CONTINUITY 0x80000000 // maps to LOAD_LIBRARY_OS_INTEGRITY_CONTINUITY // since REDSTONE2 +// rev LdrLoadDll DllPath +#define LDR_PATH_IS_FLAGS 0x00000001 +#define LDR_PATH_VALID_FLAGS 0x00007F08 +#define LDR_PATH_WITH_ALTERED_SEARCH_PATH 0x00000008 // LOAD_WITH_ALTERED_SEARCH_PATH +#define LDR_PATH_SEARCH_DLL_LOAD_DIR 0x00000100 // LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR +#define LDR_PATH_SEARCH_APPLICATION_DIR 0x00000200 // LOAD_LIBRARY_SEARCH_APPLICATION_DIR +#define LDR_PATH_SEARCH_USER_DIRS 0x00000400 // LOAD_LIBRARY_SEARCH_USER_DIRS +#define LDR_PATH_SEARCH_SYSTEM32 0x00000800 // LOAD_LIBRARY_SEARCH_SYSTEM32 +#define LDR_PATH_SEARCH_DEFAULT_DIRS 0x00001000 // LOAD_LIBRARY_SEARCH_DEFAULT_DIRS +#define LDR_PATH_SAFE_CURRENT_DIRS 0x00002000 // LOAD_LIBRARY_SAFE_CURRENT_DIRS // since REDSTONE1 +#define LDR_PATH_SEARCH_SYSTEM32_NO_FORWARDER 0x00004000 // LOAD_LIBRARY_SEARCH_SYSTEM32_NO_FORWARDER // since REDSTONE1 + +/** + * The LdrLoadDll routine loads the specified DLL into the address space of the calling process. + * + * \param DllPath A pointer to a Unicode string specifying the search path for the DLL or a combination of LDR_PATH_* flags. If NULL, the default search order is used. + * \param DllCharacteristics A pointer to a variable specifying DLL characteristics. + * \param DllName A pointer to a UNICODE_STRING structure containing the name of the DLL to load. + * \param DllHandle A pointer that receives the handle to module on success. + * \return NTSTATUS Successful or errant status. + * \sa https://learn.microsoft.com/en-us/windows/win32/api/libloaderapi/nf-libloaderapi-loadlibraryexw + */ NTSYSAPI NTSTATUS NTAPI LdrLoadDll( _In_opt_ PCWSTR DllPath, _In_opt_ PULONG DllCharacteristics, - _In_ PUNICODE_STRING DllName, + _In_ PCUNICODE_STRING DllName, _Out_ PVOID *DllHandle ); +/** + * The LdrUnloadDll routine unloads the specified DLL from the address space of the calling process. + * + * \param DllHandle A handle to the DLL module to unload, as returned by LdrLoadDll. + * \return NTSTATUS Successful or errant status. + * \sa https://learn.microsoft.com/en-us/windows/win32/api/libloaderapi/nf-libloaderapi-freelibrary + */ NTSYSAPI NTSTATUS NTAPI @@ -238,19 +293,42 @@ LdrUnloadDll( _In_ PVOID DllHandle ); +/** + * The LdrGetDllHandle routine retrieves a handle to a module that is already loaded in the calling process. + * + * \param DllPath A pointer to a Unicode string specifying the search path for the DLL or a combination of LDR_PATH_* flags. If NULL, the default search order is used. + * \param DllCharacteristics A pointer to a variable specifying DLL characteristics. Can be NULL. + * \param DllName A pointer to a UNICODE_STRING structure containing the name of the DLL to find. + * \param DllHandle A pointer that receives the handle to the loaded DLL module on success. + * \return NTSTATUS Successful or errant status. + * \sa https://learn.microsoft.com/en-us/windows/win32/api/libloaderapi/nf-libloaderapi-getmodulehandleexw + */ NTSYSAPI NTSTATUS NTAPI LdrGetDllHandle( _In_opt_ PCWSTR DllPath, _In_opt_ PULONG DllCharacteristics, - _In_ PUNICODE_STRING DllName, + _In_ PCUNICODE_STRING DllName, _Out_ PVOID *DllHandle ); +// LdrGetDllHandleEx Flags #define LDR_GET_DLL_HANDLE_EX_UNCHANGED_REFCOUNT 0x00000001 #define LDR_GET_DLL_HANDLE_EX_PIN 0x00000002 +/** + * The LdrGetDllHandleEx routine retrieves a handle to a module that is already loaded in the calling process, with extended control over reference counting. + * + * \param Flags A combination of flags that control behavior: + * - LDR_GET_DLL_HANDLE_EX_UNCHANGED_REFCOUNT: Do not modify the module's reference count. + * - LDR_GET_DLL_HANDLE_EX_PIN: Pin the module so it cannot be unloaded for the lifetime of the process. + * \param DllPath An optional semicolon-separated search path used to resolve DllName if needed. If NULL, the default module lookup is used. + * \param DllCharacteristics Optional pointer to the DLL characteristics (same values accepted by LdrLoadDll). Typically NULL for lookups. + * \param DllName The Unicode name of the module to find. Can be a base name (e.g., "ntdll.dll") or a fully-qualified path. + * \param DllHandle Receives the module handle on success. + * \return NTSTATUS Successful or errant status. + */ NTSYSAPI NTSTATUS NTAPI @@ -258,12 +336,18 @@ LdrGetDllHandleEx( _In_ ULONG Flags, _In_opt_ PCWSTR DllPath, _In_opt_ PULONG DllCharacteristics, - _In_ PUNICODE_STRING DllName, + _In_ PCUNICODE_STRING DllName, _Out_ PVOID *DllHandle ); -#if (PHNT_VERSION >= PHNT_WINDOWS_7) // rev +/** + * The LdrGetDllHandleByMapping routine retrieves a module handle for an image that is already loaded in the calling process, identified by base address. + * + * \param BaseAddress The base address of a mapped image (image or datafile view). + * \param DllHandle Receives the module handle corresponding to the base address. + * \return NTSTATUS Successful or errant status. + */ NTSYSAPI NTSTATUS NTAPI @@ -271,19 +355,25 @@ LdrGetDllHandleByMapping( _In_ PVOID BaseAddress, _Out_ PVOID *DllHandle ); -#endif -#if (PHNT_VERSION >= PHNT_WINDOWS_7) // rev +/** + * The LdrGetDllHandleByName routine retrieves a module handle by base name and/or full path for a DLL already loaded in the calling process. + * + * \param BaseDllName Optional base file name (e.g., "kernel32.dll"). Note: Matching is case-insensitive. + * \param FullDllName Optional fully-qualified path of the module. Note: Matching is case-insensitive. + * \param DllHandle Receives the module handle on success. + * \return NTSTATUS Successful or errant status. + * \remarks At least one of BaseDllName or FullDllName must be supplied. If both are supplied, they must refer to the same module. + */ NTSYSAPI NTSTATUS NTAPI LdrGetDllHandleByName( - _In_opt_ PUNICODE_STRING BaseDllName, - _In_opt_ PUNICODE_STRING FullDllName, + _In_opt_ PCUNICODE_STRING BaseDllName, + _In_opt_ PCUNICODE_STRING FullDllName, _Out_ PVOID *DllHandle ); -#endif #if (PHNT_VERSION >= PHNT_WINDOWS_8) // rev @@ -291,7 +381,7 @@ NTSYSAPI NTSTATUS NTAPI LdrGetDllFullName( - _In_ PVOID DllHandle, + _In_opt_ PVOID DllHandle, _Out_ PUNICODE_STRING FullDllName ); @@ -307,21 +397,35 @@ LdrGetDllPath( ); // rev +/** + * The LdrGetDllDirectory routine retrieves the application-specific portion of the search path used to locate DLLs for the application. + * + * \param PathName A pointer to a buffer that receives the application-specific portion of the search path. + * \return NTSTATUS Successful or errant status. + * \sa https://learn.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-getdlldirectoryw + */ NTSYSAPI NTSTATUS NTAPI LdrGetDllDirectory( - _Out_ PUNICODE_STRING DllDirectory + _Out_ PUNICODE_STRING PathName ); // rev +/** + * The LdrSetDllDirectory routine adds a directory to the search path used to locate DLLs for the application. + * + * \param PathName The directory to be added to the search path. If this parameter is NULL, the function restores the default search order. + * \return NTSTATUS Successful or errant status. + * \sa https://learn.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-setdlldirectoryw + */ NTSYSAPI NTSTATUS NTAPI LdrSetDllDirectory( - _In_ PUNICODE_STRING DllDirectory + _In_ PCUNICODE_STRING PathName ); -#endif +#endif // (PHNT_VERSION >= PHNT_WINDOWS_8) #define LDR_ADDREF_DLL_PIN 0x00000001 @@ -338,7 +442,7 @@ NTSTATUS NTAPI LdrGetProcedureAddress( _In_ PVOID DllHandle, - _In_opt_ PANSI_STRING ProcedureName, + _In_opt_ PCANSI_STRING ProcedureName, _In_opt_ ULONG ProcedureNumber, _Out_ PVOID *ProcedureAddress ); @@ -346,19 +450,17 @@ LdrGetProcedureAddress( // rev #define LDR_GET_PROCEDURE_ADDRESS_DONT_RECORD_FORWARDER 0x00000001 -#if (PHNT_VERSION >= PHNT_WINDOWS_VISTA) // private NTSYSAPI NTSTATUS NTAPI LdrGetProcedureAddressEx( _In_ PVOID DllHandle, - _In_opt_ PANSI_STRING ProcedureName, + _In_opt_ PCANSI_STRING ProcedureName, _In_opt_ ULONG ProcedureNumber, _Out_ PVOID *ProcedureAddress, - _In_ ULONG Flags + _In_ ULONG Flags // LDR_GET_PROCEDURE_ADDRESS_* ); -#endif NTSYSAPI NTSTATUS @@ -366,7 +468,7 @@ NTAPI LdrGetKnownDllSectionHandle( _In_ PCWSTR DllName, _In_ BOOLEAN KnownDlls32, - _Out_ PHANDLE Section + _Out_ PHANDLE SectionHandle ); #if (PHNT_VERSION >= PHNT_WINDOWS_10) @@ -376,13 +478,13 @@ NTSTATUS NTAPI LdrGetProcedureAddressForCaller( _In_ PVOID DllHandle, - _In_opt_ PANSI_STRING ProcedureName, + _In_opt_ PCANSI_STRING ProcedureName, _In_opt_ ULONG ProcedureNumber, _Out_ PVOID *ProcedureAddress, - _In_ ULONG Flags, - _In_ PVOID *Callback + _In_ ULONG Flags, // LDR_GET_PROCEDURE_ADDRESS_* + _In_ PVOID CallerAddress ); -#endif +#endif // (PHNT_VERSION >= PHNT_WINDOWS_10) #define LDR_LOCK_LOADER_LOCK_FLAG_RAISE_ON_ERRORS 0x00000001 #define LDR_LOCK_LOADER_LOCK_FLAG_TRY_ONLY 0x00000002 @@ -396,8 +498,8 @@ NTSTATUS NTAPI LdrLockLoaderLock( _In_ ULONG Flags, - _Out_opt_ ULONG *Disposition, - _Out_opt_ PVOID *Cookie + _Out_opt_ PULONG Disposition, + _Out_ PVOID *Cookie ); #define LDR_UNLOCK_LOADER_LOCK_FLAG_RAISE_ON_ERRORS 0x00000001 @@ -407,32 +509,12 @@ 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 + _In_ PVOID Cookie ); +// private +_Must_inspect_result_ +_Maybenull_ NTSYSAPI PIMAGE_BASE_RELOCATION NTAPI @@ -444,6 +526,9 @@ LdrProcessRelocationBlock( ); #if (PHNT_VERSION >= PHNT_WINDOWS_8) +// private +_Must_inspect_result_ +_Maybenull_ NTSYSAPI PIMAGE_BASE_RELOCATION NTAPI @@ -454,24 +539,16 @@ LdrProcessRelocationBlockEx( _In_ PUSHORT NextOffset, _In_ LONG_PTR Diff ); -#endif - -NTSYSAPI -BOOLEAN -NTAPI -LdrVerifyMappedImageMatchesChecksum( - _In_ PVOID BaseAddress, - _In_ SIZE_T NumberOfBytes, - _In_ ULONG FileLength - ); +#endif // (PHNT_VERSION >= PHNT_WINDOWS_8) typedef _Function_class_(LDR_IMPORT_MODULE_CALLBACK) VOID NTAPI LDR_IMPORT_MODULE_CALLBACK( _In_ PVOID Parameter, - _In_ PSTR ModuleName + _In_ PCSTR ModuleName ); typedef LDR_IMPORT_MODULE_CALLBACK* PLDR_IMPORT_MODULE_CALLBACK; +// private NTSYSAPI NTSTATUS NTAPI @@ -499,17 +576,21 @@ typedef struct _LDR_SECTION_INFO ULONG AllocationAttributes; } LDR_SECTION_INFO, *PLDR_SECTION_INFO; +// rev +#define LDR_VERIFY_IMAGE_FLAG_USE_CALLBACK 0x01 +#define LDR_VERIFY_IMAGE_FLAG_USE_SECTION_INFO 0x02 +#define LDR_VERIFY_IMAGE_FLAG_RETURN_IMAGE_CHARACTERISTICS 0x04 + // private typedef struct _LDR_VERIFY_IMAGE_INFO { ULONG Size; - ULONG Flags; + ULONG Flags; // LDR_VERIFY_IMAGE_FLAG_* LDR_IMPORT_CALLBACK_INFO CallbackInfo; LDR_SECTION_INFO SectionInfo; USHORT ImageCharacteristics; } LDR_VERIFY_IMAGE_INFO, *PLDR_VERIFY_IMAGE_INFO; -#if (PHNT_VERSION >= PHNT_WINDOWS_VISTA) // private NTSYSAPI NTSTATUS @@ -518,9 +599,7 @@ LdrVerifyImageMatchesChecksumEx( _In_ HANDLE ImageFileHandle, _Inout_ PLDR_VERIFY_IMAGE_INFO VerifyInfo ); -#endif -#if (PHNT_VERSION >= PHNT_WINDOWS_VISTA) // private NTSYSAPI NTSTATUS @@ -530,7 +609,6 @@ LdrQueryModuleServiceTags( _Out_writes_(*BufferSize) PULONG ServiceTagBuffer, _Inout_ PULONG BufferSize ); -#endif // begin_msdn:"DLL Load Notification" @@ -561,24 +639,25 @@ typedef union _LDR_DLL_NOTIFICATION_DATA LDR_DLL_UNLOADED_NOTIFICATION_DATA Unloaded; } LDR_DLL_NOTIFICATION_DATA, *PLDR_DLL_NOTIFICATION_DATA; +typedef const LDR_DLL_NOTIFICATION_DATA *PCLDR_DLL_NOTIFICATION_DATA; + typedef _Function_class_(LDR_DLL_NOTIFICATION_FUNCTION) VOID NTAPI LDR_DLL_NOTIFICATION_FUNCTION( _In_ ULONG NotificationReason, - _In_ PLDR_DLL_NOTIFICATION_DATA NotificationData, + _In_ PCLDR_DLL_NOTIFICATION_DATA NotificationData, _In_opt_ PVOID Context ); typedef LDR_DLL_NOTIFICATION_FUNCTION* PLDR_DLL_NOTIFICATION_FUNCTION; -#if (PHNT_VERSION >= PHNT_WINDOWS_VISTA) /** * Registers for notification when a DLL is first loaded. This notification occurs before dynamic linking takes place. * - * @param Flags This parameter must be zero. - * @param NotificationFunction A pointer to an LdrDllNotification notification callback function to call when the DLL is loaded. - * @param Context A pointer to context data for the callback function. - * @param Cookie A pointer to a variable to receive an identifier for the callback function. This identifier is used to unregister the notification callback function. - * @return NTSTATUS Successful or errant status. - * @remarks https://learn.microsoft.com/en-us/windows/win32/devnotes/ldrregisterdllnotification + * \param Flags This parameter must be zero. + * \param NotificationFunction A pointer to an LdrDllNotification notification callback function to call when the DLL is loaded. + * \param Context A pointer to context data for the callback function. + * \param Cookie A pointer to a variable to receive an identifier for the callback function. This identifier is used to unregister the notification callback function. + * \return NTSTATUS Successful or errant status. + * \remarks https://learn.microsoft.com/en-us/windows/win32/devnotes/ldrregisterdllnotification */ NTSYSAPI NTSTATUS @@ -593,9 +672,9 @@ LdrRegisterDllNotification( /** * Cancels DLL load notification previously registered by calling the LdrRegisterDllNotification function. * - * @param Cookie A pointer to the callback identifier received from the LdrRegisterDllNotification call that registered for notification. - * @return NTSTATUS Successful or errant status. - * @remarks https://learn.microsoft.com/en-us/windows/win32/devnotes/ldrunregisterdllnotification + * \param Cookie A pointer to the callback identifier received from the LdrRegisterDllNotification call that registered for notification. + * \return NTSTATUS Successful or errant status. + * \remarks https://learn.microsoft.com/en-us/windows/win32/devnotes/ldrunregisterdllnotification */ NTSYSAPI NTSTATUS @@ -603,17 +682,18 @@ NTAPI LdrUnregisterDllNotification( _In_ PVOID Cookie ); -#endif // end_msdn -// rev +#if (PHNT_VERSION >= PHNT_WINDOWS_10) +// deprecated NTSYSAPI PUNICODE_STRING NTAPI LdrStandardizeSystemPath( - _In_ PUNICODE_STRING SystemPath + _In_ PCUNICODE_STRING SystemPath ); +#endif typedef struct _LDR_FAILURE_DATA { @@ -622,34 +702,82 @@ typedef struct _LDR_FAILURE_DATA WCHAR AdditionalInfo[0x20]; } LDR_FAILURE_DATA, *PLDR_FAILURE_DATA; -#if (PHNT_VERSION >= PHNT_WINDOWS_8_1) +#if (PHNT_VERSION >= PHNT_WINDOWS_VISTA) NTSYSAPI PLDR_FAILURE_DATA NTAPI LdrGetFailureData( VOID ); -#endif +#endif // (PHNT_VERSION >= PHNT_WINDOWS_VISTA) -// private -typedef struct _PS_MITIGATION_OPTIONS_MAP +// WIN8 to REDSTONE +typedef struct _PS_MITIGATION_OPTIONS_MAP_V1 { - ULONG_PTR Map[3]; // 2 < 20H1 -} PS_MITIGATION_OPTIONS_MAP, *PPS_MITIGATION_OPTIONS_MAP; + ULONG64 Map[1]; +} PS_MITIGATION_OPTIONS_MAP_V1, *PPS_MITIGATION_OPTIONS_MAP_V1; -// private -typedef struct _PS_MITIGATION_AUDIT_OPTIONS_MAP +// private // REDSTONE2 to 19H2 +typedef struct _PS_MITIGATION_OPTIONS_MAP_V2 { - ULONG_PTR Map[3]; // 2 < 20H1 -} PS_MITIGATION_AUDIT_OPTIONS_MAP, *PPS_MITIGATION_AUDIT_OPTIONS_MAP; + ULONG64 Map[2]; +} PS_MITIGATION_OPTIONS_MAP_V2, *PPS_MITIGATION_OPTIONS_MAP_V2; -// private -typedef struct _PS_SYSTEM_DLL_INIT_BLOCK +// private // since 20H1 +typedef struct _PS_MITIGATION_OPTIONS_MAP_V3 +{ + ULONG64 Map[3]; +} PS_MITIGATION_OPTIONS_MAP_V3, *PPS_MITIGATION_OPTIONS_MAP_V3; + +typedef PS_MITIGATION_OPTIONS_MAP_V3 + PS_MITIGATION_OPTIONS_MAP, *PPS_MITIGATION_OPTIONS_MAP; + +// private // REDSTONE3 to 19H2 +typedef struct _PS_MITIGATION_AUDIT_OPTIONS_MAP_V2 +{ + ULONG64 Map[2]; +} PS_MITIGATION_AUDIT_OPTIONS_MAP_V2, *PPS_MITIGATION_AUDIT_OPTIONS_MAP_V2; + +// private // since 20H1 +typedef struct _PS_MITIGATION_AUDIT_OPTIONS_MAP_V3 +{ + ULONG64 Map[3]; +} PS_MITIGATION_AUDIT_OPTIONS_MAP_V3, *PPS_MITIGATION_AUDIT_OPTIONS_MAP_V3, + PS_MITIGATION_AUDIT_OPTIONS_MAP, *PPS_MITIGATION_AUDIT_OPTIONS_MAP; + +// private // WIN8 to REDSTONE +_Struct_size_bytes_(Size) +typedef struct _PS_SYSTEM_DLL_INIT_BLOCK_V1 { ULONG Size; - ULONG_PTR SystemDllWowRelocation; - ULONG_PTR SystemDllNativeRelocation; - ULONG_PTR Wow64SharedInformation[16]; // use WOW64_SHARED_INFORMATION as index + ULONG SystemDllWowRelocation; + ULONG64 SystemDllNativeRelocation; + ULONG Wow64SharedInformation[16]; // use WOW64_SHARED_INFORMATION as index + ULONG RngData; + union + { + ULONG Flags; + struct + { + ULONG CfgOverride : 1; // since REDSTONE + ULONG Reserved : 31; + }; + }; + ULONG64 MitigationOptions; + ULONG64 CfgBitMap; // since WINBLUE + ULONG64 CfgBitMapSize; + ULONG64 Wow64CfgBitMap; // since THRESHOLD + ULONG64 Wow64CfgBitMapSize; +} PS_SYSTEM_DLL_INIT_BLOCK_V1, *PPS_SYSTEM_DLL_INIT_BLOCK_V1; + +// RS2 - 19H2 +_Struct_size_bytes_(Size) +typedef struct _PS_SYSTEM_DLL_INIT_BLOCK_V2 +{ + ULONG Size; + ULONG64 SystemDllWowRelocation; + ULONG64 SystemDllNativeRelocation; + ULONG64 Wow64SharedInformation[16]; // use WOW64_SHARED_INFORMATION as index ULONG RngData; union { @@ -660,34 +788,53 @@ typedef struct _PS_SYSTEM_DLL_INIT_BLOCK 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 - ULONG_PTR ScpCfgCheckFunction; // since 24H2 - ULONG_PTR ScpCfgCheckESFunction; - ULONG_PTR ScpCfgDispatchFunction; - ULONG_PTR ScpCfgDispatchESFunction; - ULONG_PTR ScpArm64EcCallCheck; - ULONG_PTR ScpArm64EcCfgCheckFunction; - ULONG_PTR ScpArm64EcCfgCheckESFunction; -} PS_SYSTEM_DLL_INIT_BLOCK, *PPS_SYSTEM_DLL_INIT_BLOCK; + PS_MITIGATION_OPTIONS_MAP_V2 MitigationOptionsMap; + ULONG64 CfgBitMap; + ULONG64 CfgBitMapSize; + ULONG64 Wow64CfgBitMap; + ULONG64 Wow64CfgBitMapSize; + PS_MITIGATION_AUDIT_OPTIONS_MAP_V2 MitigationAuditOptionsMap; // since REDSTONE3 +} PS_SYSTEM_DLL_INIT_BLOCK_V2, *PPS_SYSTEM_DLL_INIT_BLOCK_V2; -// rev -#if (PHNT_VERSION >= PHNT_WINDOWS_10) +// private // since 20H1 +_Struct_size_bytes_(Size) +typedef struct _PS_SYSTEM_DLL_INIT_BLOCK_V3 +{ + ULONG Size; + ULONG64 SystemDllWowRelocation; // effectively since WIN8 + ULONG64 SystemDllNativeRelocation; + ULONG64 Wow64SharedInformation[16]; // use WOW64_SHARED_INFORMATION as index + ULONG RngData; + union + { + ULONG Flags; + struct + { + ULONG CfgOverride : 1; // effectively since REDSTONE + ULONG Reserved : 31; + }; + }; + PS_MITIGATION_OPTIONS_MAP_V3 MitigationOptionsMap; + ULONG64 CfgBitMap; // effectively since WINBLUE + ULONG64 CfgBitMapSize; + ULONG64 Wow64CfgBitMap; // effectively since THRESHOLD + ULONG64 Wow64CfgBitMapSize; + PS_MITIGATION_AUDIT_OPTIONS_MAP_V3 MitigationAuditOptionsMap; // effectively since REDSTONE3 + ULONG64 ScpCfgCheckFunction; // since 24H2 + ULONG64 ScpCfgCheckESFunction; + ULONG64 ScpCfgDispatchFunction; + ULONG64 ScpCfgDispatchESFunction; + ULONG64 ScpArm64EcCallCheck; + ULONG64 ScpArm64EcCfgCheckFunction; + ULONG64 ScpArm64EcCfgCheckESFunction; +} PS_SYSTEM_DLL_INIT_BLOCK_V3, *PPS_SYSTEM_DLL_INIT_BLOCK_V3, + PS_SYSTEM_DLL_INIT_BLOCK, *PPS_SYSTEM_DLL_INIT_BLOCK; + +// private +#if (PHNT_VERSION >= PHNT_WINDOWS_8) NTSYSAPI PS_SYSTEM_DLL_INIT_BLOCK LdrSystemDllInitBlock; #endif -#define PS_SYSTEM_DLL_INIT_BLOCK_SIZE_V1 \ - RTL_SIZEOF_THROUGH_FIELD(PS_SYSTEM_DLL_INIT_BLOCK, MitigationAuditOptionsMap) -#define PS_SYSTEM_DLL_INIT_BLOCK_SIZE_V2 \ - RTL_SIZEOF_THROUGH_FIELD(PS_SYSTEM_DLL_INIT_BLOCK, ScpArm64EcCfgCheckESFunction) - -//static_assert(PS_SYSTEM_DLL_INIT_BLOCK_SIZE_V1 == 240, "PS_SYSTEM_DLL_INIT_BLOCK_SIZE_V1 must equal 240"); -//static_assert(PS_SYSTEM_DLL_INIT_BLOCK_SIZE_V2 == 296, "PS_SYSTEM_DLL_INIT_BLOCK_SIZE_V2 must equal 296"); - // rev see also MEMORY_IMAGE_EXTENSION_INFORMATION typedef struct _RTL_SCPCFG_NTDLL_EXPORTS { @@ -723,17 +870,15 @@ NTSYSAPI RTL_SCPCFG_NTDLL_EXPORTS RtlpScpCfgNtdllExports; // Load as data table // -#if (PHNT_VERSION >= PHNT_WINDOWS_VISTA) - // private NTSYSAPI NTSTATUS NTAPI LdrAddLoadAsDataTable( - _In_ PVOID Module, - _In_ PCWSTR FilePath, - _In_ SIZE_T Size, - _In_ HANDLE Handle, + _In_ PVOID DllHandle, + _In_opt_ PCWSTR FilePath, + _In_ SIZE_T FileSize, + _In_ HANDLE FileHandle, _In_opt_ PACTIVATION_CONTEXT ActCtx ); @@ -742,9 +887,9 @@ NTSYSAPI NTSTATUS NTAPI LdrRemoveLoadAsDataTable( - _In_ PVOID InitModule, - _Out_opt_ PVOID *BaseModule, - _Out_opt_ PSIZE_T Size, + _In_ PVOID DllHandle, + _Out_ PVOID *BaseModule, + _Out_opt_ PSIZE_T FileSize, _In_ ULONG Flags ); @@ -753,23 +898,40 @@ NTSYSAPI NTSTATUS NTAPI LdrGetFileNameFromLoadAsDataTable( - _In_ PVOID Module, - _Out_ PVOID *pFileNamePrt + _In_ PVOID DllHandle, + _Out_ PWSTR *FileName ); -#endif - NTSYSAPI NTSTATUS NTAPI LdrDisableThreadCalloutsForDll( - _In_ PVOID DllImageBase + _In_ PVOID DllHandle ); // // Resources // +// NtCurrentTeb()->ResourceRetValue +// LdrFindResource* and LdrAccessResource +typedef struct _LDR_RESLOADER_RET +{ + PVOID Module; + PVOID DataEntry; + PVOID TargetModule; +} LDR_RESLOADER_RET, *PLDR_RESLOADER_RET; + +/** + * The LdrAccessResource function returns a pointer to the first byte of the specified resource in memory. + * + * \param DllHandle A handle to the DLL. + * \param ResourceDataEntry The resource information block. + * \param ResourceBuffer The pointer to the specified resource in memory. + * \param ResourceLength The size, in bytes, of the specified resource. + * \return NTSTATUS Successful or errant status. + * \sa https://learn.microsoft.com/en-us/windows/win32/api/libloaderapi/nf-libloaderapi-loadresource + */ NTSYSAPI NTSTATUS NTAPI @@ -780,36 +942,45 @@ LdrAccessResource( _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 - +/** + * The LdrFindResource_U function determines the location of a resource in a DLL. + * + * \param DllHandle A handle to the DLL. + * \param ResourcePath A pointer to an array of Type/Name/Language/(optional)AlternateType. + * \param Count The number of elements in the ResourcePath array. + * \param ResourceDataEntry The resource information block. + * \return NTSTATUS Successful or errant status. + * \sa https://learn.microsoft.com/en-us/windows/win32/api/libloaderapi/nf-libloaderapi-findresourceexw + */ NTSYSAPI NTSTATUS NTAPI LdrFindResource_U( _In_ PVOID DllHandle, - _In_ PLDR_RESOURCE_INFO ResourceInfo, - _In_ ULONG Level, + _In_reads_(Count) PULONG_PTR ResourcePath, + _In_ ULONG Count, _Out_ PIMAGE_RESOURCE_DATA_ENTRY *ResourceDataEntry ); +/** + * The LdrFindResourceEx_U function determines the location of a resource in a DLL. + * + * \param Flags A handle to the DLL. + * \param DllHandle A handle to the DLL. + * \param ResourcePath A pointer to an array of Type/Name/Language/(optional)AlternateType. + * \param Count The number of elements in the ResourcePath array. + * \param ResourceDataEntry The resource information block. + * \return NTSTATUS Successful or errant status. + * \sa https://learn.microsoft.com/en-us/windows/win32/api/libloaderapi/nf-libloaderapi-findresourceexw + */ NTSYSAPI NTSTATUS NTAPI LdrFindResourceEx_U( _In_ ULONG Flags, _In_ PVOID DllHandle, - _In_ PLDR_RESOURCE_INFO ResourceInfo, - _In_ ULONG Level, + _In_reads_(Count) PULONG_PTR ResourcePath, + _In_ ULONG Count, _Out_ PIMAGE_RESOURCE_DATA_ENTRY *ResourceDataEntry ); @@ -818,66 +989,121 @@ NTSTATUS NTAPI LdrFindResourceDirectory_U( _In_ PVOID DllHandle, - _In_ PLDR_RESOURCE_INFO ResourceInfo, - _In_ ULONG Level, + _In_reads_(Count) PULONG_PTR ResourcePath, + _In_ ULONG Count, _Out_ PIMAGE_RESOURCE_DIRECTORY *ResourceDirectory ); #if (PHNT_VERSION >= PHNT_WINDOWS_8) + +// rev // Flags for LdrResFindResource, LdrpResGetResourceDirectory, LdrResSearchResource +#define LDR_RES_REQUIRE_FOUR_KEYS_A 0x00000001u // Enables 4-key mode (variant A) (requires Count==4) +#define LDR_RES_ALLOW_ANY 0x00000002u // Permit Count < 3 (else Count must be 3 or 4) +#define LDR_RES_OPTIMIZE_SMALL_A 0x00000008u // Cannot combine with LDR_RES_OPTIMIZE_SMALL_B +#define LDR_RES_OPTIMIZE_SMALL_B 0x00000010u // Required when using LDR_RES_SPECIAL_DEPENDENCY with LDR_RES_MODE_D_SEARCH +//#define LDR_RES_ALT_RETRY 0x00000030u +#define LDR_RES_REQUIRE_FOUR_KEYS_B 0x00000040u // Enables 4-key mode (Enable alternate module message) (requires Count==4) + +// Search mode flags (if not specified, LDR_RES_MODE_A_SEARCH is the default) +#define LDR_RES_MODE_A_SEARCH 0x00000100u // Default mode for typical resource lookup. // Exclusive with B/C/D // LdrResRelease +#define LDR_RES_MODE_B_SEARCH 0x00000200u // When the resource is loaded as a datafile // LDR_IS_DATAFILE(DllHandle) // Exclusive with A/C/D // LdrResRelease +#define LDR_RES_MODE_C_SEARCH 0x00000400u // When precise control over mapping size is needed. // Exclusive with A/B/D // LdrResRelease +#define LDR_RES_MODE_D_SEARCH 0x00000800u // When dependency resolution or alternate resources are needed. // Used with LDR_RES_SPECIAL_DEPENDENCY // Exclusive with A/B/C // LdrResRelease + +// Mapping behavior flags (only valid with LDR_RES_MODE_C or LDR_RES_MODE_D) +#define LDR_RES_MAPPING_STRICT 0x00001000u // Default; Fail if mapping size query fails // LdrResRelease +#define LDR_RES_MAPPING_LENIENT 0x00002000u // Allow fallback if mapping size query fails // LdrResRelease +#define LDR_RES_MAPPING_ALT_RESOURCE 0x00004000u // When the primary resource search fails, try load and search the alternate resource // LdrResRelease + +// Small/fast lookup optimizations (only valid with LDR_RES_MODE_A or LDR_RES_MODE_B) +#define LDR_RES_SPECIAL_DEPENDENCY 0x00008000u // Only valid with (LDR_RES_MODE_D_SEARCH | LDR_RES_OPTIMIZE_SMALL_B) + +#define LDR_RES_SIZE_FROM_LENGTH_C 0x00020000u // Use *ResourceLength as mapping size; requires LDR_RES_MODE_C +#define LDR_RES_SIZE_FROM_LENGTH_AB 0x00080000u // Use *ResourceLength as mapping size; requires LDR_RES_MODE_A or LDR_RES_MODE_B + +// Internal-only (set by loader on alternate resource retry; callers must not set) +#define LDR_RES_INTERNAL_ALT_RETRY 0x01000000u + +// Group masks +#define LDR_RES_MODE_MASK 0x00000F00u // LDR_RES_MODE_A|LDR_RES_MODE_B|LDR_RES_MODE_C|LDR_RES_MODE_D +#define LDR_RES_BEHAVIOR_MASK 0x00003000u // LDR_RES_MAPPING_STRICT/LDR_RES_MAPPING_LENIENT +#define LDR_RES_SIZEOVERRIDE_MASK 0x000A0000u // LDR_RES_SIZE_FROM_LENGTH_* (0x20000|0x80000) +#define LDR_RES_KEY4_MASK (LDR_RES_REQUIRE_FOUR_KEYS_A | LDR_RES_REQUIRE_FOUR_KEYS_B) + +// Public/caller-visible bit mask (high bits must be zero for callers) +#define LDR_RES_PUBLIC_MASK 0x000FFFFFu + +// Common invalid combinations (useful for validation) +#define LDR_RES_INVALID_SMALL_OPT_PAIR 0x00000018u // LDR_RES_OPTIMIZE_SMALL_A|LDR_RES_OPTIMIZE_SMALL_B +#define LDR_RES_INVALID_MAPPING_BEHAVIOR_PAIR 0x00003000u // LDR_RES_MAPPING_STRICT|LDR_RES_MAPPING_LENIENT? + +// rev /** * The LdrResFindResource function finds a resource in a DLL. * - * @param DllHandle A handle to the DLL. - * @param Type The type of the resource. - * @param Name The name of the resource. - * @param Language The language of the resource. - * @param ResourceBuffer An optional pointer to receive the resource buffer. - * @param ResourceLength An optional pointer to receive the resource length. - * @param CultureName An optional buffer to receive the culture name. - * @param CultureNameLength An optional pointer to receive the length of the culture name. - * @param Flags Flags for the resource search. - * @return NTSTATUS Successful or errant status. + * \param DllHandle A handle to the DLL. + * \param Type The type of the resource. This parameter can also be MAKEINTRESOURCE(ID), where ID is the integer identifier of the resource. + * \param Name The name of the resource. This parameter can also be MAKEINTRESOURCE(ID), where ID is the integer identifier of the resource. + * \param Language The language of the resource. This parameter can also be MAKEINTRESOURCE(ID), where ID is the integer identifier of the resource. + * \param ResourceBuffer An optional pointer to receive the resource buffer. + * \param ResourceLength An optional pointer to receive the resource length. + * \param CultureName An optional buffer to receive the culture name. + * \param CultureNameLength An optional pointer to receive the length of the culture name. + * \param Flags Flags to modify the resource search. + * \return NTSTATUS Successful or errant status. */ NTSYSAPI NTSTATUS NTAPI LdrResFindResource( _In_ PVOID DllHandle, - _In_ ULONG_PTR Type, - _In_ ULONG_PTR Name, - _In_ ULONG_PTR Language, + _In_ PCWSTR Type, + _In_ PCWSTR Name, + _In_ PCWSTR Language, _Out_opt_ PVOID* ResourceBuffer, - _Out_opt_ PULONG ResourceLength, + _Out_opt_ PSIZE_T ResourceLength, _Out_writes_bytes_opt_(CultureNameLength) PVOID CultureName, // WCHAR buffer[6] _Out_opt_ PULONG CultureNameLength, - _In_ ULONG Flags + _In_opt_ ULONG Flags ); +// rev /** - * The LdrResFindResourceDirectory function finds a resource directory in a DLL. + * The LdrResFindResourceDirectory function finds the resource directory containing the specified resource. * - * @param DllHandle A handle to the DLL. - * @param Type The type of the resource. - * @param Name The name of the resource. - * @param ResourceDirectory An optional pointer to receive the resource directory. - * @param CultureName An optional buffer to receive the culture name. - * @param CultureNameLength An optional pointer to receive the length of the culture name. - * @param Flags Flags for the resource search. - * @return NTSTATUS Successful or errant status. + * \param DllHandle A handle to the DLL. + * \param Type The type of the resource. This parameter can also be MAKEINTRESOURCE(ID), where ID is the integer identifier of the resource. + * \param Name The name of the resource. This parameter can also be MAKEINTRESOURCE(ID), where ID is the integer identifier of the resource. + * \param ResourceDirectory An optional pointer to receive the resource directory. + * \param CultureName An optional buffer to receive the culture name. + * \param CultureNameLength An optional pointer to receive the length of the culture name. + * \param Flags Flags for the resource search. + * \return NTSTATUS Successful or errant status. */ NTSYSAPI NTSTATUS NTAPI LdrResFindResourceDirectory( _In_ PVOID DllHandle, - _In_ ULONG_PTR Type, - _In_ ULONG_PTR Name, + _In_ PCWSTR Type, + _In_ PCWSTR Name, _Out_opt_ PIMAGE_RESOURCE_DIRECTORY* ResourceDirectory, _Out_writes_bytes_opt_(CultureNameLength) PVOID CultureName, // WCHAR buffer[6] _Out_opt_ PULONG CultureNameLength, - _In_ ULONG Flags + _In_opt_ ULONG Flags ); +// rev +/** + * The LdrpResGetResourceDirectory function returns the resource directory for a DLL. + * + * \param DllHandle A handle to the DLL. + * \param Size The size of the image mapping. + * \param Flags Flags for the resource search. + * \param ResourceDirectory An optional pointer to receive the resource directory. + * \param OutHeaders The NT headers of the image. + * \return NTSTATUS Successful or errant status. + */ NTSYSAPI NTSTATUS NTAPI @@ -889,42 +1115,93 @@ LdrpResGetResourceDirectory( _Out_ PIMAGE_NT_HEADERS* OutHeaders ); +// rev /** -* The LdrResSearchResource function searches for a resource in a DLL. -* -* @param DllHandle A handle to the DLL. -* @param ResourceInfo A pointer to the resource information. -* @param Level The level of the resource. -* @param Flags Flags for the resource search. -* @param ResourceBuffer An optional pointer to receive the resource buffer. -* @param ResourceLength An optional pointer to receive the resource length. -* @param CultureName An optional buffer to receive the culture name. -* @param CultureNameLength An optional pointer to receive the length of the culture name. -* @return NTSTATUS Successful or errant status. -*/ + * The LdrResSearchResource function searches for a resource in a DLL. + * + * \param DllHandle A handle to the DLL. + * \param ResourcePath A pointer to an array of Type/Name/Language/(optional)AlternateType. + * \param ResourcePathCount The number of elements in the ResourcePath array. + * \param Flags Flags for the resource search. + * \param ResourceBuffer An optional pointer to receive the resource buffer. + * \param ResourceLength An optional pointer to receive the resource length. + * \param CultureName An optional buffer to receive the culture name. + * \param CultureNameLength An optional pointer to receive the length of the culture name. + * \return NTSTATUS Successful or errant status. + */ NTSYSAPI NTSTATUS NTAPI LdrResSearchResource( _In_ PVOID DllHandle, - _In_ PLDR_RESOURCE_INFO ResourceInfo, - _In_ ULONG Level, + _In_ PULONG_PTR ResourcePath, + _In_ ULONG ResourcePathCount, _In_ ULONG Flags, _Out_opt_ PVOID* ResourceBuffer, _Out_opt_ PSIZE_T ResourceLength, - _Out_writes_bytes_opt_(CultureNameLength) PVOID CultureName, // WCHAR buffer[6] + _Out_writes_bytes_opt_(*CultureNameLength) PWSTR CultureName, // WCHAR buffer[6] _Out_opt_ PULONG CultureNameLength ); +// rev +typedef struct _MUI_RC_CONFIG +{ + ULONG Signature; // Magic signature 0xFEEDFACE (-20054323 signed) + ULONG Size; // Total size of this structure + ULONG Version; // Version (0x10000 = 1.0) + ULONG Flags1; // Primary flags field (validated with & 0xFFFFFFF8) + ULONG Flags2; // Secondary flags field (validated with & 0xFFFFFFCC) + ULONG ValidationField; // Additional validation field + ULONG Flags3; // Tertiary flags field (validated with & 0xFFFFFFFC) + ULONG Reserved1; // Reserved field + ULONG Reserved2; // Reserved field + ULONG Reserved3; // Reserved field + ULONG Reserved4; // Reserved field + ULONG Reserved5; // Reserved field + ULONG Reserved6; // Reserved field + ULONG Reserved7; // Reserved field + ULONG Reserved8; // Reserved field + ULONG Reserved9; // Reserved field + ULONG Reserved10; // Reserved field + + // Data section offset/size pairs (validated for bounds checking) + ULONG Section1Offset; // First data section offset + ULONG Section1Size; // First data section size + ULONG Section2Offset; // Second data section offset + ULONG Section2Size; // Second data section size + ULONG Section3Offset; // Third data section offset + ULONG Section3Size; // Third data section size + ULONG Section4Offset; // Fourth data section offset + ULONG Section4Size; // Fourth data section size + ULONG Section5Offset; // Fifth data section offset + ULONG Section5Size; // Fifth data section size + ULONG Section6Offset; // Sixth data section offset + ULONG Section6Size; // Sixth data section size + ULONG Section7Offset; // Seventh data section offset + ULONG Section7Size; // Seventh data section size + ULONG Section8Offset; // Eighth data section offset + ULONG Section8Size; // Eighth data section size + // Variable length data follows... + // The actual data sections referenced by the offset/size pairs above +} MUI_RC_CONFIG, *PMUI_RC_CONFIG; + +// Magic signature constant +#define MUI_RC_CONFIG_SIGNATURE 0xFEEDFACE +#define MUI_RC_CONFIG_VERSION_1_0 0x10000 +// Flag validation masks +#define MUI_FLAGS1_VALID_MASK 0xFFFFFFF8 // Only lower 3 bits allowed +#define MUI_FLAGS2_VALID_MASK 0xFFFFFFCC // Specific bit pattern +#define MUI_FLAGS3_VALID_MASK 0xFFFFFFFC // Only lower 2 bits allowed + /** - * The LdrResGetRCConfig function retrieves the RC configuration for a DLL. + * The LdrResGetRCConfig function retrieves the MUI configuration (resource type 3) for a DLL. * - * @param DllHandle A handle to the DLL. - * @param Length The length of the configuration buffer. - * @param Config A buffer to receive the configuration. - * @param Flags Flags for the operation. - * @param AlternateResource Indicates if an alternate resource should be loaded. - * @return NTSTATUS Successful or errant status. + * \param DllHandle A handle to the DLL. + * \param Length The length of the configuration buffer. + * \param Config A buffer to receive the configuration. + * \param Flags Flags for the operation. + * \param AlternateResource Indicates if an alternate resource should be loaded. + * \return NTSTATUS Successful or errant status. */ NTSYSAPI NTSTATUS @@ -932,28 +1209,39 @@ NTAPI LdrResGetRCConfig( _In_ PVOID DllHandle, _In_opt_ SIZE_T Length, - _Out_writes_bytes_opt_(Length) PVOID Config, + _Out_writes_bytes_opt_(Length) PMUI_RC_CONFIG* Config, _In_ ULONG Flags, _In_ BOOLEAN AlternateResource // LdrLoadAlternateResourceModule ); /** - * The LdrResRelease function releases a resource in a DLL. + * The LdrResRelease function releases the alternate resource module or section of an associated DLL. * - * @param DllHandle A handle to the DLL. - * @param CultureNameOrId An optional culture name or ID. - * @param Flags Flags for the operation. - * @return NTSTATUS Successful or errant status. + * \param DllHandle A handle to the DLL. + * \param CultureNameOrId An optional culture name or ID. + * \param Flags Flags for the operation. + * \return NTSTATUS Successful or errant status. */ NTSYSAPI NTSTATUS NTAPI LdrResRelease( _In_ PVOID DllHandle, - _In_opt_ ULONG_PTR CultureNameOrId, // MAKEINTRESOURCE + _In_opt_ PCWSTR CultureNameOrId, // MAKEINTRESOURCE _In_ ULONG Flags ); -#endif + +// rev +NTSYSAPI +VOID +NTAPI +LdrpResGetMappingSize( + _In_ PVOID BaseAddress, + _Out_ PSIZE_T Size, + _In_ ULONG Flags, + _In_ BOOLEAN GetFileSizeFromLoadAsDataTable + ); +#endif // (PHNT_VERSION >= PHNT_WINDOWS_8) // private typedef struct _LDR_ENUM_RESOURCE_ENTRY @@ -974,19 +1262,49 @@ typedef struct _LDR_ENUM_RESOURCE_ENTRY } LDR_ENUM_RESOURCE_ENTRY, *PLDR_ENUM_RESOURCE_ENTRY; #define NAME_FROM_RESOURCE_ENTRY(RootDirectory, Entry) \ - ((Entry)->NameIsString ? (ULONG_PTR)((ULONG_PTR)(RootDirectory) + (ULONG_PTR)((Entry)->NameOffset)) : (Entry)->Id) + ((Entry)->NameIsString ? (ULONG_PTR)((PUCHAR)(RootDirectory) + (ULONG_PTR)((Entry)->NameOffset)) : (Entry)->Id) +FORCEINLINE +ULONG_PTR +NTAPI +LdrNameOrIdFromResourceEntry( + _In_ PIMAGE_RESOURCE_DIRECTORY ResourceDirectory, + _In_ PIMAGE_RESOURCE_DIRECTORY_ENTRY Entry) +{ + if (Entry->NameIsString) + return (ULONG_PTR)((PUCHAR)(ResourceDirectory) + (ULONG_PTR)(Entry->NameOffset)); + else + return (ULONG_PTR)(Entry->Id); +} + +/** + * The LdrEnumResources routine enumerates resources of a specified DLL module. + * + * \param DllHandle Handle to the loaded DLL module whose resources are to be enumerated. + * \param ResourceId A pointer to an array of Type/Name/Language/(optional)AlternateType. + * \param Count Specifies the number of elements in the ResourceId array. + * \param ResourceCount On input, specifies the maximum number of resources to enumerate. On output, receives the actual number of resources enumerated. + * \param Resources Pointer to a buffer that receives an array of LDR_ENUM_RESOURCE_ENTRY structures describing the resources. + * \return NTSTATUS Successful or errant status. + */ NTSYSAPI NTSTATUS NTAPI LdrEnumResources( _In_ PVOID DllHandle, - _In_ PLDR_RESOURCE_INFO ResourceInfo, - _In_ ULONG Level, + _In_reads_(Count) PULONG_PTR ResourceId, + _In_ ULONG Count, _Inout_ ULONG *ResourceCount, _Out_writes_to_opt_(*ResourceCount, *ResourceCount) PLDR_ENUM_RESOURCE_ENTRY Resources ); +/** + * The LdrFindEntryForAddress routine retrieves the loader data table entry for a given address within a loaded module. + * + * \param DllHandle A pointer to an address within the loaded module (such as the base address of the DLL or any address inside the module). + * \param Entry On success, receives a pointer to the LDR_DATA_TABLE_ENTRY structure corresponding to the module containing the specified address. + * \return NTSTATUS Successful or errant status. + */ NTSYSAPI NTSTATUS NTAPI @@ -996,16 +1314,30 @@ LdrFindEntryForAddress( ); // rev +/** + * The LdrLoadAlternateResourceModule routine returns a handle to the language-specific dynamic-link library (DLL) + * resource module associated with a DLL that is already loaded for the calling process. + * + * \param DllHandle A handle to the DLL module to search for a MUI resource. If the language-specific DLL for the MUI is available, + * loads the specified module into the address space of the calling process and returns a handle to the module. + * \param BaseAddress The base address of the mapped view. + * \param Size The size of the mapped view. + * \param Flags Reserved + * \return NTSTATUS Successful or errant status. + */ NTSYSAPI NTSTATUS NTAPI LdrLoadAlternateResourceModule( _In_ PVOID DllHandle, - _Out_ PVOID *ResourceDllBase, - _Out_opt_ ULONG_PTR *ResourceOffset, + _Out_ PVOID *BaseAddress, + _Out_opt_ SIZE_T *Size, _In_ ULONG Flags ); +// Flags for LdrLoadAlternateResourceModuleEx +#define LDR_LOAD_ALT_RESOURCE_MUN_MODE 0x01000000u // Use .mun files instead of .mui files + // rev NTSYSAPI NTSTATUS @@ -1013,8 +1345,8 @@ NTAPI LdrLoadAlternateResourceModuleEx( _In_ PVOID DllHandle, _In_ LANGID LanguageId, - _Out_ PVOID *ResourceDllBase, - _Out_opt_ ULONG_PTR *ResourceOffset, + _Out_ PVOID *BaseAddress, + _Out_opt_ SIZE_T *Size, _In_ ULONG Flags ); @@ -1095,31 +1427,39 @@ NTAPI LdrQueryProcessModuleInformation( _In_opt_ PRTL_PROCESS_MODULES ModuleInformation, _In_opt_ ULONG Size, - _Out_ PULONG ReturnedSize + _Out_opt_ PULONG ReturnedSize ); typedef _Function_class_(LDR_ENUM_CALLBACK) VOID NTAPI LDR_ENUM_CALLBACK( _In_ PLDR_DATA_TABLE_ENTRY ModuleInformation, _In_ PVOID Parameter, - _Out_ BOOLEAN* Stop + _Out_ PBOOLEAN Stop ); typedef LDR_ENUM_CALLBACK* PLDR_ENUM_CALLBACK; +typedef _Function_class_(LDR_LOADED_MODULE_ENUMERATION_CALLBACK_FUNCTION) +VOID NTAPI LDR_LOADED_MODULE_ENUMERATION_CALLBACK_FUNCTION( + _In_ PCLDR_DATA_TABLE_ENTRY DataTableEntry, + _In_opt_ PVOID Context, + _Inout_ BOOLEAN *StopEnumeration + ); +typedef LDR_LOADED_MODULE_ENUMERATION_CALLBACK_FUNCTION* PLDR_LOADED_MODULE_ENUMERATION_CALLBACK_FUNCTION; + NTSYSAPI NTSTATUS NTAPI LdrEnumerateLoadedModules( _In_ BOOLEAN ReservedFlag, - _In_ PLDR_ENUM_CALLBACK EnumProc, - _In_ PVOID Context + _In_ PLDR_LOADED_MODULE_ENUMERATION_CALLBACK_FUNCTION EnumProc, + _In_opt_ PVOID Context ); NTSYSAPI NTSTATUS NTAPI LdrOpenImageFileOptionsKey( - _In_ PUNICODE_STRING SubKey, + _In_ PCUNICODE_STRING SubKey, _In_ BOOLEAN Wow64, _Out_ PHANDLE NewKeyHandle ); @@ -1140,7 +1480,7 @@ NTSYSAPI NTSTATUS NTAPI LdrQueryImageFileExecutionOptions( - _In_ PUNICODE_STRING SubKey, + _In_ PCUNICODE_STRING SubKey, _In_ PCWSTR ValueName, _In_ ULONG ValueSize, _Out_ PVOID Buffer, @@ -1152,7 +1492,7 @@ NTSYSAPI NTSTATUS NTAPI LdrQueryImageFileExecutionOptionsEx( - _In_ PUNICODE_STRING SubKey, + _In_ PCUNICODE_STRING SubKey, _In_ PCWSTR ValueName, _In_ ULONG Type, _Out_ PVOID Buffer, @@ -1204,14 +1544,14 @@ typedef DELAYLOAD_FAILURE_SYSTEM_ROUTINE* PDELAYLOAD_FAILURE_SYSTEM_ROUTINE; #if (PHNT_VERSION >= PHNT_WINDOWS_10) // rev from QueryOptionalDelayLoadedAPI /** - * Determines whether the specified function in a delay-loaded DLL is available on the system. + * The LdrQueryOptionalDelayLoadedAPI routine determines whether the specified function in a delay-loaded DLL is available on the system. * - * @param ParentModuleBase A handle to the calling module. (NtCurrentImageBase) - * @param DllName The file name of the delay-loaded DLL that exports the specified function. This parameter is case-insensitive. - * @param ProcedureName The address of a delay-load failure callback function for the specified DLL and process. - * @param Flags Reserved; must be 0. - * @return NTSTATUS Successful or errant status. - * @remarks https://learn.microsoft.com/en-us/windows/win32/api/libloaderapi2/nf-libloaderapi2-queryoptionaldelayloadedapi + * \param ParentModuleBase A handle to the calling module. (NtCurrentImageBase) + * \param DllName The file name of the delay-loaded DLL that exports the specified function. This parameter is case-insensitive. + * \param ProcedureName The address of a delay-load failure callback function for the specified DLL and process. + * \param Flags Reserved; must be 0. + * \return NTSTATUS Successful or errant status. + * \remarks https://learn.microsoft.com/en-us/windows/win32/api/libloaderapi2/nf-libloaderapi2-queryoptionaldelayloadedapi */ NTSYSAPI NTSTATUS @@ -1222,21 +1562,21 @@ LdrQueryOptionalDelayLoadedAPI( _In_ PCSTR ProcedureName, _Reserved_ ULONG Flags ); -#endif +#endif // (PHNT_VERSION >= PHNT_WINDOWS_10) #if (PHNT_VERSION >= PHNT_WINDOWS_8) // rev from ResolveDelayLoadedAPI /** - * Locates the target function of the specified import and replaces the function pointer in the import thunk with the target of the function implementation. + * The LdrResolveDelayLoadedAPI routine locates the target function of the specified import and replaces the function pointer in the import thunk with the target of the function implementation. * - * @param ParentModuleBase The address of the base of the module importing a delay-loaded function. (NtCurrentImageBase) - * @param DelayloadDescriptor The address of the image delay import directory for the module to be loaded. - * @param FailureDllHook The address of a delay-load failure callback function for the specified DLL and process. - * @param FailureSystemHook The address of a delay-load failure callback function for the specified DLL and process. - * @param ThunkAddress The thunk data for the target function. Used to find the specific name table entry of the function. - * @param Flags Reserved; must be 0. - * @return The address of the import, or the failure stub for it. - * @remarks https://learn.microsoft.com/en-us/windows/win32/devnotes/resolvedelayloadedapi + * \param ParentModuleBase The address of the base of the module importing a delay-loaded function. (NtCurrentImageBase) + * \param DelayloadDescriptor The address of the image delay import directory for the module to be loaded. + * \param FailureDllHook The address of a delay-load failure callback function for the specified DLL and process. + * \param FailureSystemHook The address of a delay-load failure callback function for the specified DLL and process. + * \param ThunkAddress The thunk data for the target function. Used to find the specific name table entry of the function. + * \param Flags Reserved; must be 0. + * \return The address of the import, or the failure stub for it. + * \remarks https://learn.microsoft.com/en-us/windows/win32/devnotes/resolvedelayloadedapi */ NTSYSAPI PVOID @@ -1252,13 +1592,13 @@ LdrResolveDelayLoadedAPI( // rev from ResolveDelayLoadsFromDll /** - * Forwards the work in resolving delay-loaded imports from the parent binary to a target binary. + * The LdrResolveDelayLoadsFromDll routine forwards the work in resolving delay-loaded imports from the parent binary to a target binary. * - * @param [in] ParentModuleBase The base address of the module that delay loads another binary. - * @param [in] TargetDllName The name of the target DLL. - * @param [in] Flags Reserved; must be 0. - * @return NTSTATUS Successful or errant status. - * @remarks https://learn.microsoft.com/en-us/windows/win32/devnotes/resolvedelayloadsfromdll + * \param [in] ParentModuleBase The base address of the module that delay loads another binary. + * \param [in] TargetDllName The name of the target DLL. + * \param [in] Flags Reserved; must be 0. + * \return NTSTATUS Successful or errant status. + * \remarks https://learn.microsoft.com/en-us/windows/win32/devnotes/resolvedelayloadsfromdll */ NTSYSAPI NTSTATUS @@ -1271,11 +1611,11 @@ LdrResolveDelayLoadsFromDll( // rev from SetDefaultDllDirectories /** - * Specifies a default set of directories to search when the calling process loads a DLL. + * The LdrSetDefaultDllDirectories routine specifies a default set of directories to search when the calling process loads a DLL. * - * @param [in] DirectoryFlags The directories to search. - * @return NTSTATUS Successful or errant status. - * @remarks https://learn.microsoft.com/en-us/windows/win32/api/libloaderapi/nf-libloaderapi-setdefaultdlldirectories + * \param [in] DirectoryFlags The directories to search. + * \return NTSTATUS Successful or errant status. + * \remarks https://learn.microsoft.com/en-us/windows/win32/api/libloaderapi/nf-libloaderapi-setdefaultdlldirectories */ NTSYSAPI NTSTATUS @@ -1286,28 +1626,28 @@ LdrSetDefaultDllDirectories( // rev from AddDllDirectory /** - * Adds a directory to the process DLL search path. + * The LdrAddDllDirectory routine adds a directory to the process DLL search path. * - * @param [in] NewDirectory An absolute path to the directory to add to the search path. For example, to add the directory Dir2 to the process DLL search path, specify \Dir2. - * @param [out] Cookie An opaque pointer that can be passed to RemoveDllDirectory to remove the DLL from the process DLL search path. - * @return NTSTATUS Successful or errant status. - * @remarks https://learn.microsoft.com/en-us/windows/win32/api/libloaderapi/nf-libloaderapi-adddlldirectory + * \param [in] NewDirectory An absolute path to the directory to add to the search path. For example, to add the directory Dir2 to the process DLL search path, specify \Dir2. + * \param [out] Cookie An opaque pointer that can be passed to RemoveDllDirectory to remove the DLL from the process DLL search path. + * \return NTSTATUS Successful or errant status. + * \remarks https://learn.microsoft.com/en-us/windows/win32/api/libloaderapi/nf-libloaderapi-adddlldirectory */ NTSYSAPI NTSTATUS NTAPI LdrAddDllDirectory( - _In_ PUNICODE_STRING NewDirectory, + _In_ PCUNICODE_STRING NewDirectory, _Out_ PDLL_DIRECTORY_COOKIE Cookie ); // rev from RemoveDllDirectory /** - * Removes a directory that was added to the process DLL search path by using LdrAddDllDirectory. + * The LdrRemoveDllDirectory routine removes a directory that was added to the process DLL search path by using LdrAddDllDirectory. * - * @param [in] Cookie The cookie returned by LdrAddDllDirectory when the directory was added to the search path. - * @return NTSTATUS Successful or errant status. - * @remarks https://learn.microsoft.com/en-us/windows/win32/api/libloaderapi/nf-libloaderapi-removedlldirectory + * \param [in] Cookie The cookie returned by LdrAddDllDirectory when the directory was added to the search path. + * \return NTSTATUS Successful or errant status. + * \remarks https://learn.microsoft.com/en-us/windows/win32/api/libloaderapi/nf-libloaderapi-removedlldirectory */ NTSYSAPI NTSTATUS @@ -1315,9 +1655,12 @@ NTAPI LdrRemoveDllDirectory( _In_ DLL_DIRECTORY_COOKIE Cookie ); -#endif +#endif // (PHNT_VERSION >= PHNT_WINDOWS_8) // rev +/** + * The LdrShutdownProcess routine forcefully terminates the calling program if it is invoked inside a loader callout. Otherwise, it has no effect. + */ _Analysis_noreturn_ DECLSPEC_NORETURN NTSYSAPI @@ -1328,6 +1671,9 @@ LdrShutdownProcess( ); // rev +/** + * The LdrShutdownThread routine forcefully terminates the calling thread if it is invoked inside a loader callout. Otherwise, it has no effect. + */ _Analysis_noreturn_ DECLSPEC_NORETURN NTSYSAPI @@ -1339,6 +1685,11 @@ LdrShutdownThread( #if (PHNT_VERSION >= PHNT_WINDOWS_8_1) // rev +/** + * The LdrSetImplicitPathOptions routine sets implicit path options. + * + * \param [in] ImplicitPathOptions The implicit path options to set. + */ NTSYSAPI NTSTATUS NTAPI @@ -1347,60 +1698,28 @@ LdrSetImplicitPathOptions( ); #endif -#if (PHNT_VERSION >= PHNT_WINDOWS_10) -#ifdef PHNT_INLINE_TYPEDEFS +#if (PHNT_VERSION >= PHNT_WINDOWS_10RS3) +// private /** - * The LdrControlFlowGuardEnforced function checks if Control Flow Guard is enforced. + * The LdrControlFlowGuardEnforced routine checks if Control Flow Guard is enforced. * - * @return BOOLEAN TRUE if Control Flow Guard is enforced, FALSE otherwise. - */ -FORCEINLINE -BOOLEAN -NTAPI -LdrControlFlowGuardEnforced( - VOID - ) -{ - return LdrSystemDllInitBlock.CfgBitMap && (LdrSystemDllInitBlock.Flags & 1) == 0; -} -#else -// rev -/** - * The LdrControlFlowGuardEnforced function checks if Control Flow Guard is enforced. - * - * @return BOOLEAN TRUE if Control Flow Guard is enforced, FALSE otherwise. + * \return TRUE if Control Flow Guard is enforced, FALSE otherwise. */ NTSYSAPI -BOOLEAN +ULONG NTAPI LdrControlFlowGuardEnforced( VOID ); #endif -#endif - -#if (PHNT_VERSION >= PHNT_WINDOWS_10) -/** - * The LdrControlFlowGuardEnforcedWithExportSuppression function checks if Control Flow Guard is - * enforced with export suppression. - * - * @return BOOLEAN TRUE if Control Flow Guard is enforced, FALSE otherwise. - */ -FORCEINLINE -BOOLEAN -NTAPI -LdrControlFlowGuardEnforcedWithExportSuppression( - VOID - ) -{ - return LdrSystemDllInitBlock.CfgBitMap - && (LdrSystemDllInitBlock.Flags & 1) == 0 - && (LdrSystemDllInitBlock.MitigationOptionsMap.Map[0] & 3) == 3; // PROCESS_CREATION_MITIGATION_POLICY_CONTROL_FLOW_GUARD_EXPORT_SUPPRESSION -} -#endif #if (PHNT_VERSION >= PHNT_WINDOWS_10_19H1) // rev +/** + * The LdrIsModuleSxsRedirected routine determines whether the specified module is SxS-redirected. + * + * \param [in] DllHandle A handle to the DLL + */ NTSYSAPI BOOLEAN NTAPI @@ -1411,6 +1730,11 @@ LdrIsModuleSxsRedirected( #if (PHNT_VERSION >= PHNT_WINDOWS_10) // rev +/** + * The LdrUpdatePackageSearchPath routine updates the package search path used by the loader. + * + * \param [in] SearchPath The new search path. + */ NTSYSAPI NTSTATUS NTAPI @@ -1445,20 +1769,20 @@ typedef struct _LDR_SOFTWARE_ENCLAVE // rev from CreateEnclave /** - * Creates a new uninitialized enclave. An enclave is an isolated region of code and data within the address space for an application. Only code that runs within the enclave can access data within the same enclave. + * The LdrCreateEnclave routine creates a new uninitialized enclave. An enclave is an isolated region of code and data within the address space for an application. Only code that runs within the enclave can access data within the same enclave. * - * @param ProcessHandle A handle to the process for which you want to create an enclave. - * @param BaseAddress The preferred base address of the enclave. Specify NULL to have the operating system assign the base address. - * @param Reserved Reserved. - * @param Size The size of the enclave that you want to create, including the size of the code that you will load into the enclave, in bytes. - * @param InitialCommitment The amount of memory to commit for the enclave, in bytes. This parameter is not used for virtualization-based security (VBS) enclaves. - * @param EnclaveType The architecture type of the enclave that you want to create. To verify that an enclave type is supported, call IsEnclaveTypeSupported. - * @param EnclaveInformation A pointer to the architecture-specific information to use to create the enclave. - * @param EnclaveInformationLength The length of the structure that the EnclaveInformation parameter points to, in bytes. + * \param ProcessHandle A handle to the process for which you want to create an enclave. + * \param BaseAddress The preferred base address of the enclave. Specify NULL to have the operating system assign the base address. + * \param Reserved Reserved. + * \param Size The size of the enclave that you want to create, including the size of the code that you will load into the enclave, in bytes. + * \param InitialCommitment The amount of memory to commit for the enclave, in bytes. This parameter is not used for virtualization-based security (VBS) enclaves. + * \param EnclaveType The architecture type of the enclave that you want to create. To verify that an enclave type is supported, call IsEnclaveTypeSupported. + * \param EnclaveInformation A pointer to the architecture-specific information to use to create the enclave. + * \param EnclaveInformationLength The length of the structure that the EnclaveInformation parameter points to, in bytes. * For the ENCLAVE_TYPE_SGX and ENCLAVE_TYPE_SGX2 enclave types, this value must be 4096. For the ENCLAVE_TYPE_VBS enclave type, this value must be sizeof(ENCLAVE_CREATE_INFO_VBS), which is 36 bytes. - * @param EnclaveError An optional pointer to a variable that receives an enclave error code that is architecture-specific. - * @return NTSTATUS Successful or errant status. - * @remarks https://learn.microsoft.com/en-us/windows/win32/api/enclaveapi/nf-enclaveapi-createenclave + * \param EnclaveError An optional pointer to a variable that receives an enclave error code that is architecture-specific. + * \return NTSTATUS Successful or errant status. + * \remarks https://learn.microsoft.com/en-us/windows/win32/api/enclaveapi/nf-enclaveapi-createenclave */ NTSYSAPI NTSTATUS @@ -1477,16 +1801,16 @@ LdrCreateEnclave( // rev from InitializeEnclave /** - * Initializes an enclave that you created and loaded with data. + * The LdrInitializeEnclave routine initializes an enclave that you created and loaded with data. * - * @param ProcessHandle A handle to the process for which the enclave was created. - * @param BaseAddress Any address within the enclave. - * @param EnclaveInformation A pointer to the architecture-specific information to use to initialize the enclave. - * @param EnclaveInformationLength The length of the structure that the EnclaveInformation parameter points to, in bytes. + * \param ProcessHandle A handle to the process for which the enclave was created. + * \param BaseAddress Any address within the enclave. + * \param EnclaveInformation A pointer to the architecture-specific information to use to initialize the enclave. + * \param EnclaveInformationLength The length of the structure that the EnclaveInformation parameter points to, in bytes. * For the ENCLAVE_TYPE_SGX and ENCLAVE_TYPE_SGX2 enclave types, this value must be 4096. For the ENCLAVE_TYPE_VBS enclave type, this value must be sizeof(ENCLAVE_CREATE_INFO_VBS), which is 36 bytes. - * @param EnclaveError An optional pointer to a variable that receives an enclave error code that is architecture-specific. - * @return NTSTATUS Successful or errant status. - * @remarks https://learn.microsoft.com/en-us/windows/win32/api/enclaveapi/nf-enclaveapi-initializeenclave + * \param EnclaveError An optional pointer to a variable that receives an enclave error code that is architecture-specific. + * \return NTSTATUS Successful or errant status. + * \remarks https://learn.microsoft.com/en-us/windows/win32/api/enclaveapi/nf-enclaveapi-initializeenclave */ NTSYSAPI NTSTATUS @@ -1501,11 +1825,11 @@ LdrInitializeEnclave( // rev from DeleteEnclave /** - * Deletes the specified enclave. + * The LdrDeleteEnclave routine deletes the specified enclave. * - * @param BaseAddress The base address of the enclave that you want to delete. - * @return NTSTATUS Successful or errant status. - * @remarks https://learn.microsoft.com/en-us/windows/win32/api/enclaveapi/nf-enclaveapi-deleteenclave + * \param BaseAddress The base address of the enclave that you want to delete. + * \return NTSTATUS Successful or errant status. + * \remarks https://learn.microsoft.com/en-us/windows/win32/api/enclaveapi/nf-enclaveapi-deleteenclave */ NTSYSAPI NTSTATUS @@ -1516,13 +1840,13 @@ LdrDeleteEnclave( // rev from CallEnclave /** - * Calls a function within an enclave. LdrCallEnclave can also be called within an enclave to call a function outside of the enclave. + * The LdrCallEnclave routine calls a function within an enclave. LdrCallEnclave can also be called within an enclave to call a function outside of the enclave. * - * @param Routine The address of the function that you want to call. - * @param Flags The flags to modify the call function. - * @param RoutineParamReturn The parameter than you want to pass to the function. - * @return NTSTATUS Successful or errant status. - * @remarks https://learn.microsoft.com/en-us/windows/win32/api/enclaveapi/nf-enclaveapi-callenclave + * \param Routine The address of the function that you want to call. + * \param Flags The flags to modify the call function. + * \param RoutineParamReturn The parameter than you want to pass to the function. + * \return NTSTATUS Successful or errant status. + * \remarks https://learn.microsoft.com/en-us/windows/win32/api/enclaveapi/nf-enclaveapi-callenclave */ NTSYSAPI NTSTATUS @@ -1535,13 +1859,14 @@ LdrCallEnclave( // rev from LoadEnclaveImage /** - * Loads an image and all of its imports into an enclave. + * The LdrLoadEnclaveModule routine loads an image and all of its imports into an enclave. * - * @param BaseAddress The base address of the image into which to load the image. - * @param DllPath A NULL-terminated string that contains the path of the image to load. - * @param DllName A NULL-terminated string that contains the name of the image to load. - * @return NTSTATUS Successful or errant status. - * @remarks https://learn.microsoft.com/en-us/windows/win32/api/enclaveapi/nf-enclaveapi-loadenclaveimagew + * \param BaseAddress The base address of the enclave in which the module will be loaded. + * This address must correspond to an enclave previously created by using LdrCreateEnclave. + * \param DllPath A NULL-terminated string that contains the path of the image to load. + * \param DllName A NULL-terminated string that contains the name of the image to load. + * \return NTSTATUS Successful or errant status. + * \remarks https://learn.microsoft.com/en-us/windows/win32/api/enclaveapi/nf-enclaveapi-loadenclaveimagew */ NTSYSAPI NTSTATUS @@ -1549,15 +1874,15 @@ NTAPI LdrLoadEnclaveModule( _In_ PVOID BaseAddress, _In_opt_ PCWSTR DllPath, - _In_ PUNICODE_STRING DllName + _In_ PCUNICODE_STRING DllName ); -#endif +#endif // (PHNT_VERSION >= PHNT_WINDOWS_10) /** - * This function forcefully terminates the calling program if it is invoked inside a loader callout. Otherwise, it has no effect. + * The LdrFastFailInLoaderCallout routine forcefully terminates the calling program if it is invoked inside a loader callout. Otherwise, it has no effect. * - * @remarks This routine does not catch all potential deadlock cases; it is possible for a thread inside a loader callout + * \remarks This routine does not catch all potential deadlock cases; it is possible for a thread inside a loader callout * to acquire a lock while some thread outside a loader callout holds the same lock and makes a call into the loader. * In other words, there can be a lock order inversion between the loader lock and a client lock. * https://learn.microsoft.com/en-us/windows/win32/devnotes/ldrfastfailinloadercallout @@ -1603,15 +1928,44 @@ NTSYSAPI BOOLEAN LdrpChildNtdll; // DATA export // rev NTSYSAPI -VOID +NTSTATUS NTAPI -LdrpResGetMappingSize( - _In_ PVOID BaseAddress, - _Out_ PSIZE_T Size, - _In_ ULONG Flags, - _In_ BOOLEAN GetFileSizeFromLoadAsDataTable +LdrAppxHandleIntegrityFailure( + _In_ NTSTATUS Status ); #endif // (PHNT_MODE != PHNT_MODE_KERNEL) +// Note: Keep the static asserts below at the end of the file to ensure the structure is correct. + +#if defined(_WIN64) +static_assert(UFIELD_OFFSET(LDR_DATA_TABLE_ENTRY, InMemoryOrderLinks) == 0x10, "LDR_DATA_TABLE_ENTRY.InMemoryOrderLinks offset incorrect"); +static_assert(UFIELD_OFFSET(LDR_DATA_TABLE_ENTRY, InInitializationOrderLinks) == 0x20, "LDR_DATA_TABLE_ENTRY.InInitializationOrderLinks offset incorrect"); +static_assert(UFIELD_OFFSET(LDR_DATA_TABLE_ENTRY, DllBase) == 0x30, "LDR_DATA_TABLE_ENTRY.DllBase offset incorrect"); +static_assert(UFIELD_OFFSET(LDR_DATA_TABLE_ENTRY, EntryPoint) == 0x38, "LDR_DATA_TABLE_ENTRY.EntryPoint offset incorrect"); +static_assert(UFIELD_OFFSET(LDR_DATA_TABLE_ENTRY, SizeOfImage) == 0x40, "LDR_DATA_TABLE_ENTRY.SizeOfImage offset incorrect"); +static_assert(UFIELD_OFFSET(LDR_DATA_TABLE_ENTRY, ObsoleteLoadCount) == 0x6c, "LDR_DATA_TABLE_ENTRY.ObsoleteLoadCount offset incorrect"); +static_assert(UFIELD_OFFSET(LDR_DATA_TABLE_ENTRY, TimeDateStamp) == 0x80, "LDR_DATA_TABLE_ENTRY.TimeDateStamp offset incorrect"); +static_assert(UFIELD_OFFSET(LDR_DATA_TABLE_ENTRY, DdagNode) == 0x98, "LDR_DATA_TABLE_ENTRY.DdagNode offset incorrect"); +static_assert(UFIELD_OFFSET(LDR_DATA_TABLE_ENTRY, ParentDllBase) == 0xb8, "LDR_DATA_TABLE_ENTRY.ParentDllBase offset incorrect"); +static_assert(UFIELD_OFFSET(LDR_DATA_TABLE_ENTRY, OriginalBase) == 0xf8, "LDR_DATA_TABLE_ENTRY.OriginalBase offset incorrect"); +static_assert(UFIELD_OFFSET(LDR_DATA_TABLE_ENTRY, BaseNameHashValue) == 0x108, "LDR_DATA_TABLE_ENTRY.BaseNameHashValue offset incorrect"); +static_assert(UFIELD_OFFSET(LDR_DATA_TABLE_ENTRY, LoadReason) == 0x10c, "LDR_DATA_TABLE_ENTRY.LoadReason offset incorrect"); +static_assert(sizeof(LDR_DATA_TABLE_ENTRY) == 0x138, "LDR_DATA_TABLE_ENTRY incorrect size"); +#else +static_assert(UFIELD_OFFSET(LDR_DATA_TABLE_ENTRY, InMemoryOrderLinks) == 0x8, "LDR_DATA_TABLE_ENTRY.InMemoryOrderLinks offset incorrect"); +static_assert(UFIELD_OFFSET(LDR_DATA_TABLE_ENTRY, InInitializationOrderLinks) == 0x10, "LDR_DATA_TABLE_ENTRY.InInitializationOrderLinks offset incorrect"); +static_assert(UFIELD_OFFSET(LDR_DATA_TABLE_ENTRY, DllBase) == 0x18, "LDR_DATA_TABLE_ENTRY.DllBase offset incorrect"); +static_assert(UFIELD_OFFSET(LDR_DATA_TABLE_ENTRY, EntryPoint) == 0x1c, "LDR_DATA_TABLE_ENTRY.EntryPoint offset incorrect"); +static_assert(UFIELD_OFFSET(LDR_DATA_TABLE_ENTRY, SizeOfImage) == 0x20, "LDR_DATA_TABLE_ENTRY.SizeOfImage offset incorrect"); +static_assert(UFIELD_OFFSET(LDR_DATA_TABLE_ENTRY, ObsoleteLoadCount) == 0x38, "LDR_DATA_TABLE_ENTRY.ObsoleteLoadCount offset incorrect"); +static_assert(UFIELD_OFFSET(LDR_DATA_TABLE_ENTRY, TimeDateStamp) == 0x44, "LDR_DATA_TABLE_ENTRY.TimeDateStamp offset incorrect"); +static_assert(UFIELD_OFFSET(LDR_DATA_TABLE_ENTRY, DdagNode) == 0x50, "LDR_DATA_TABLE_ENTRY.DdagNode offset incorrect"); +static_assert(UFIELD_OFFSET(LDR_DATA_TABLE_ENTRY, ParentDllBase) == 0x60, "LDR_DATA_TABLE_ENTRY.ParentDllBase offset incorrect"); +static_assert(UFIELD_OFFSET(LDR_DATA_TABLE_ENTRY, OriginalBase) == 0x80, "LDR_DATA_TABLE_ENTRY.OriginalBase offset incorrect"); +static_assert(UFIELD_OFFSET(LDR_DATA_TABLE_ENTRY, BaseNameHashValue) == 0x90, "LDR_DATA_TABLE_ENTRY.BaseNameHashValue offset incorrect"); +static_assert(UFIELD_OFFSET(LDR_DATA_TABLE_ENTRY, LoadReason) == 0x94, "LDR_DATA_TABLE_ENTRY.LoadReason offset incorrect"); +static_assert(sizeof(LDR_DATA_TABLE_ENTRY) == 0xB8, "LDR_DATA_TABLE_ENTRY incorrect size"); #endif + +#endif // _NTLDR_H diff --git a/ntlpcapi.h b/ntlpcapi.h index 290eae5..adddea3 100644 --- a/ntlpcapi.h +++ b/ntlpcapi.h @@ -7,9 +7,17 @@ #ifndef _NTLPCAPI_H #define _NTLPCAPI_H + // + // ALPC Object Specific Access Rights + // + #define PORT_CONNECT 0x0001 #define PORT_ALL_ACCESS (STANDARD_RIGHTS_REQUIRED | SYNCHRONIZE | 0x1) +// +// ALPC information structures +// + typedef struct _PORT_MESSAGE { union @@ -70,6 +78,17 @@ typedef struct _PORT_DATA_INFORMATION #define LPC_NO_IMPERSONATE 0x4000 #define LPC_KERNELMODE_MESSAGE 0x8000 +#define ALPC_REQUEST (LPC_CONTINUATION_REQUIRED | LPC_REQUEST) +#define ALPC_REPLY (LPC_CONTINUATION_REQUIRED | LPC_REPLY) +#define ALPC_DATAGRAM (LPC_CONTINUATION_REQUIRED | LPC_DATAGRAM) +#define ALPC_LOST_REPLY (LPC_CONTINUATION_REQUIRED | LPC_LOST_REPLY) +#define ALPC_PORT_CLOSED (LPC_CONTINUATION_REQUIRED | LPC_PORT_CLOSED) +#define ALPC_CLIENT_DIED (LPC_CONTINUATION_REQUIRED | LPC_CLIENT_DIED) +#define ALPC_EXCEPTION (LPC_CONTINUATION_REQUIRED | LPC_EXCEPTION) +#define ALPC_DEBUG_EVENT (LPC_CONTINUATION_REQUIRED | LPC_DEBUG_EVENT) +#define ALPC_ERROR_EVENT (LPC_CONTINUATION_REQUIRED | LPC_ERROR_EVENT) +#define ALPC_CONNECTION_REQUEST (LPC_CONTINUATION_REQUIRED | LPC_CONNECTION_REQUEST) + #define PORT_VALID_OBJECT_ATTRIBUTES OBJ_CASE_INSENSITIVE #ifdef _WIN64 @@ -203,7 +222,7 @@ NTSTATUS NTAPI NtConnectPort( _Out_ PHANDLE PortHandle, - _In_ PUNICODE_STRING PortName, + _In_ PCUNICODE_STRING PortName, _In_ PSECURITY_QUALITY_OF_SERVICE SecurityQos, _Inout_opt_ PPORT_VIEW ClientView, _Inout_opt_ PREMOTE_PORT_VIEW ServerView, @@ -217,7 +236,7 @@ NTSTATUS NTAPI NtSecureConnectPort( _Out_ PHANDLE PortHandle, - _In_ PUNICODE_STRING PortName, + _In_ PCUNICODE_STRING PortName, _In_ PSECURITY_QUALITY_OF_SERVICE SecurityQos, _Inout_opt_ PPORT_VIEW ClientView, _In_opt_ PSID RequiredServerSid, @@ -365,22 +384,25 @@ NtQueryInformationPort( _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_NONE 0x0 +#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 @@ -424,6 +446,13 @@ typedef struct _ALPC_PORT_ATTRIBUTES #define ALPC_MESSAGE_CONTEXT_ATTRIBUTE 0x20000000 #define ALPC_MESSAGE_VIEW_ATTRIBUTE 0x40000000 #define ALPC_MESSAGE_SECURITY_ATTRIBUTE 0x80000000 + +// Convenience macro for all message attributes +#define ALPC_MESSAGE_ATTRIBUTES_ALL \ + (ALPC_MESSAGE_HANDLE_ATTRIBUTE | \ + ALPC_MESSAGE_CONTEXT_ATTRIBUTE | \ + ALPC_MESSAGE_VIEW_ATTRIBUTE | \ + ALPC_MESSAGE_SECURITY_ATTRIBUTE) // end_rev // symbols @@ -654,8 +683,6 @@ typedef struct _ALPC_MESSAGE_HANDLE_INFORMATION // begin_private -#if (PHNT_VERSION >= PHNT_WINDOWS_VISTA) - // // System calls // @@ -728,7 +755,7 @@ NtAlpcCreateResourceReserve( _In_ HANDLE PortHandle, _Reserved_ ULONG Flags, _In_ SIZE_T MessageSize, - _Out_ PALPC_HANDLE ResourceId + _Out_ PULONG ResourceId ); NTSYSCALLAPI @@ -737,7 +764,7 @@ NTAPI NtAlpcDeleteResourceReserve( _In_ HANDLE PortHandle, _Reserved_ ULONG Flags, - _In_ ALPC_HANDLE ResourceId + _In_ ULONG ResourceId ); NTSYSCALLAPI @@ -811,7 +838,7 @@ NTSTATUS NTAPI NtAlpcConnectPort( _Out_ PHANDLE PortHandle, - _In_ PUNICODE_STRING PortName, + _In_ PCUNICODE_STRING PortName, _In_opt_ POBJECT_ATTRIBUTES ObjectAttributes, _In_opt_ PALPC_PORT_ATTRIBUTES PortAttributes, _In_ ULONG Flags, @@ -943,9 +970,10 @@ AlpcMaxAllowedMessageLength( VOID ); -#define ALPC_ATTRFLG_ALLOCATEDATTR 0x20000000 -#define ALPC_ATTRFLG_VALIDATTR 0x40000000 -#define ALPC_ATTRFLG_KEEPRUNNINGATTR 0x60000000 +// ALPC message attribute flags (internal state) +#define ALPC_ATTRFLG_ALLOCATEDATTR 0x20000000 // Attribute buffer was allocated +#define ALPC_ATTRFLG_VALIDATTR 0x40000000 // Attribute buffer is valid +#define ALPC_ATTRFLG_KEEPRUNNINGATTR 0x60000000 // Keep running attribute NTSYSAPI ULONG @@ -990,7 +1018,6 @@ AlpcUnregisterCompletionList( _In_ HANDLE PortHandle ); -#if (PHNT_VERSION >= PHNT_WINDOWS_7) // rev NTSYSAPI NTSTATUS @@ -998,7 +1025,6 @@ NTAPI AlpcRundownCompletionList( _In_ HANDLE PortHandle ); -#endif NTSYSAPI NTSTATUS @@ -1062,8 +1088,6 @@ AlpcGetCompletionListMessageAttributes( _In_ PPORT_MESSAGE Message ); -#endif - // end_private #endif diff --git a/ntmisc.h b/ntmisc.h index d6d7c7b..cf3471f 100644 --- a/ntmisc.h +++ b/ntmisc.h @@ -7,6 +7,258 @@ #ifndef _NTMISC_H #define _NTMISC_H +// +// Apphelp +// + +_Enum_is_bitflag_ +typedef enum _AHC_INFO_CLASS +{ + AhcInfoClassSdbQueryResult = 0x00000001, + AhcInfoClassSdbSxsOverrideManifest = 0x00000002, + AhcInfoClassSdbRunlevelFlags = 0x00000004, + AhcInfoClassSdbFusionFlags = 0x00000008, + AhcInfoClassSdbInstallerFlags = 0x00000010, + AhcInfoClassFusionFlags = 0x00000020, + AhcInfoClassTelemetryFlags = 0x00000040, + AhcInfoClassInstallDetect = 0x00000080, + AhcInfoClassRacEventSent = 0x00000100, + AhcInfoClassIsSystemFile = 0x00000200, + AhcInfoClassMonitoringFlags = 0x00000400, + AhcInfoClassExeType = 0x00000800, +} AHC_INFO_CLASS, *PAHC_INFO_CLASS; + +#define AHC_INFO_CLASS_FILTER_ON_FILETIME_CHANGE \ + (AHC_INFO_CLASS)(AhcInfoClassSdbQueryResult | \ + AhcInfoClassSdbSxsOverrideManifest | \ + AhcInfoClassSdbRunlevelFlags | \ + AhcInfoClassSdbFusionFlags | \ + AhcInfoClassSdbInstallerFlags | \ + AhcInfoClassFusionFlags | \ + AhcInfoClassRacEventSent) + +#define AHC_INFO_CLASS_FILTER_ON_SDB_CHANGE \ + (AHC_INFO_CLASS)(AhcInfoClassSdbQueryResult | \ + AhcInfoClassSdbSxsOverrideManifest | \ + AhcInfoClassSdbRunlevelFlags | \ + AhcInfoClassSdbFusionFlags | \ + AhcInfoClassSdbInstallerFlags | \ + AhcInfoClassInstallDetect) + +#define AHC_INFO_CLASS_ALL \ + (AHC_INFO_CLASS)(AhcInfoClassSdbQueryResult | \ + AhcInfoClassSdbSxsOverrideManifest | \ + AhcInfoClassSdbRunlevelFlags | \ + AhcInfoClassSdbFusionFlags | \ + AhcInfoClassSdbInstallerFlags | \ + AhcInfoClassFusionFlags | \ + AhcInfoClassTelemetryFlags | \ + AhcInfoClassInstallDetect | \ + AhcInfoClassRacEventSent | \ + AhcInfoClassIsSystemFile | \ + AhcInfoClassMonitoringFlags | \ + AhcInfoClassExeType) + +#define AHC_INFO_CLASS_INTERNALLY_COMPUTED \ + (AHC_INFO_CLASS)(AhcInfoClassSdbQueryResult | \ + AhcInfoClassSdbSxsOverrideManifest | \ + AhcInfoClassSdbRunlevelFlags | \ + AhcInfoClassSdbFusionFlags | \ + AhcInfoClassSdbInstallerFlags | \ + AhcInfoClassTelemetryFlags | \ + AhcInfoClassIsSystemFile | \ + AhcInfoClassMonitoringFlags | \ + AhcInfoClassExeType) + +#define AHC_INFO_CLASS_SAFE_FOR_UNPRIVILEGED_UPDATE \ + (AHC_INFO_CLASS)(AhcInfoClassInstallDetect | \ + AhcInfoClassRacEventSent | \ + AhcInfoClassTelemetryFlags | \ + AhcInfoClassMonitoringFlags) + +// +// Cache structures and APIs. +// + +typedef enum _AHC_SERVICE_CLASS +{ + ApphelpCacheServiceLookup = 0, + ApphelpCacheServiceRemove = 1, + ApphelpCacheServiceUpdate = 2, + ApphelpCacheServiceClear = 3, + ApphelpCacheServiceSnapStatistics = 4, + ApphelpCacheServiceSnapCache = 5, + ApphelpCacheServiceLookupCdb = 6, + ApphelpCacheServiceRefreshCdb = 7, + ApphelpCacheServiceMapQuirks = 8, + ApphelpCacheServiceHwIdQuery = 9, + ApphelpCacheServiceInitProcessData = 10, + ApphelpCacheServiceLookupAndWriteToProcess = 11, + ApphelpCacheServiceMax +} AHC_SERVICE_CLASS; + +typedef struct _AHC_SERVICE_LOOKUP +{ + AHC_INFO_CLASS InfoClass; // Information to lookup. + UINT HintFlags; // Hint flags about cache query. + UNICODE_STRING PackageAlias; // Aliased package moniker in a packed string. + HANDLE FileHandle; // User space handle to file. + HANDLE ProcessHandle; // User space process handle. + USHORT ExeType; // Executable bitness. + USHORT Padding; // Padding to even USHORTs. + UNICODE_STRING ExeSignature; // Executable file signature. + PCZZWSTR Environment; // Environment block. + UINT EnvironmentSize; // Size of environment block in bytes. +} AHC_SERVICE_LOOKUP, *PAHC_SERVICE_LOOKUP; + +typedef struct _AHC_SERVICE_REMOVE +{ + AHC_INFO_CLASS InfoClass; + UNICODE_STRING PackageAlias; + HANDLE FileHandle; + UNICODE_STRING ExeSignature; +} AHC_SERVICE_REMOVE, *PAHC_SERVICE_REMOVE; + +typedef struct _AHC_SERVICE_UPDATE +{ + AHC_INFO_CLASS InfoClass; + UNICODE_STRING PackageAlias; + HANDLE FileHandle; + UNICODE_STRING ExeSignature; + PVOID Data; + ULONG DataSize; +} AHC_SERVICE_UPDATE, *PAHC_SERVICE_UPDATE; + +typedef struct _AHC_SERVICE_CLEAR +{ + AHC_INFO_CLASS InfoClass; +} AHC_SERVICE_CLEAR, *PAHC_SERVICE_CLEAR; + +typedef struct _AHC_SERVICE_LOOKUP_CDB +{ + UNICODE_STRING Name; +} AHC_SERVICE_LOOKUP_CDB, *PAHC_SERVICE_LOOKUP_CDB; + +// +// AHC_HINT_* flags are used in the HintFlags variable. +// + +#define AHC_HINT_FORCE_BYPASS 0x00000001 +#define AHC_HINT_REMOVABLE_MEDIA 0x00000002 +#define AHC_HINT_TEMPORARY_DIRECTORY 0x00000004 +#define AHC_HINT_USER_PERM_LAYER 0x00000008 +#define AHC_HINT_CREATE_PROCESS 0x00000010 +#define AHC_HINT_NATIVE_EXE 0x00000020 + +#define SHIM_CACHE_MAIN_DATABASE_PATH32 L"\\AppPatch\\sysmain.sdb" +#define SHIM_CACHE_MAIN_DATABASE_PATH64 L"\\AppPatch\\AppPatch64\\sysmain.sdb" + +// +// Flag definitions for various flag-type information in cache. +// + +#define AHC_CACHE_FLAG_MONITORING_IS_CANDIDATE 0x00000001 // Candidate for monitoring. +#define AHC_CACHE_FLAG_MONITORING_IS_COMPLETE 0x00000002 // Monitoring has completed. +#define AHC_CACHE_FLAG_MONITORING_VALID_MASK (AHC_CACHE_FLAG_MONITORING_IS_CANDIDATE | \ + AHC_CACHE_FLAG_MONITORING_IS_COMPLETE) + +#define AHC_CACHE_FLAG_TELEMETRY_IS_CANDIDATE 0x00000001 // Candidate for telemetry. +#define AHC_CACHE_FLAG_TELEMETRY_HAS_SAMPLED 0x00000002 // Telemetry has run. +#define AHC_CACHE_FLAG_TELEMETRY_VALID_MASK (AHC_CACHE_FLAG_TELEMETRY_IS_CANDIDATE | \ + AHC_CACHE_FLAG_TELEMETRY_HAS_SAMPLED) + +#define AHC_CACHE_FLAG_FUSION_HASDOTLOCAL 0x00000001 // Dot local file exists. +#define AHC_CACHE_FLAG_FUSION_HASMANIFESTFILE 0x00000002 // Fusion manifest exists. +#define AHC_CACHE_FLAG_FUSION_HASMANIFESTRESOURCE 0x00000004 // Fusion manifest resource exists. +#define AHC_CACHE_FLAG_FUSION_VALID_MASK (AHC_CACHE_FLAG_FUSION_HASDOTLOCAL | \ + AHC_CACHE_FLAG_FUSION_HASMANIFESTFILE | \ + AHC_CACHE_FLAG_FUSION_HASMANIFESTRESOURCE) + +#define AHC_CACHE_FLAG_RAC_EVENTSENT 0x00000001 // Rac event has been sent. +#define AHC_CACHE_FLAG_RAC_VALID_MASK (AHC_CACHE_FLAG_RAC_EVENTSENT) + +#define AHC_CACHE_FLAG_INSTALLDETECT_CLAIMED 0x00000001 // InstallDetect claimed. +#define AHC_CACHE_FLAG_INSTALLDETECT_VALID_MASK (AHC_CACHE_FLAG_RAC_EVENTSENT) + +// +// Statistics. +// + +typedef struct _AHC_MAIN_STATISTICS +{ + ULONG Lookup; // Count of lookup calls. + ULONG Remove; // Count of remove calls. + ULONG Update; // Count of update calls. + ULONG Clear; // Count of clear calls. + ULONG SnapStatistics; // Count of snap statistics calls. + ULONG SnapCache; // Count of snap store calls. +} AHC_MAIN_STATISTICS, *PAHC_MAIN_STATISTICS; + +typedef struct _AHC_STORE_STATISTICS +{ + ULONG LookupHits; // Count of lookup hits. + ULONG LookupMisses; // Count of lookup misses. + ULONG Inserted; // Count of inserted. + ULONG Replaced; // Count of replaced. + ULONG Updated; // Count of updates. +} AHC_STORE_STATISTICS, *PAHC_STORE_STATISTICS; + +typedef struct _AHC_STATISTICS +{ + ULONG Size; // Size of the structure. + AHC_MAIN_STATISTICS Main; // Main statistics. + AHC_STORE_STATISTICS Store; // Store statistics. +} AHC_STATISTICS, *PAHC_STATISTICS; + +typedef struct _AHC_SERVICE_DATAQUERY +{ + AHC_STATISTICS Stats; // Statistics. + ULONG DataSize; // Size of data. + PBYTE Data; // Data. +} AHC_SERVICE_DATAQUERY, *PAHC_SERVICE_DATAQUERY; + +typedef struct _AHC_SERVICE_DATACACHE +{ + HANDLE FileHandle; // User space handle to file. + USHORT ExeType; // Executable bitness. + USHORT Padding; // Padding to even USHORTs. + UINT HintFlags; // Metadata flags about cache query. + HANDLE ProcessHandle; // User space process handle. + UNICODE_STRING FileName; // Executable file name. + UNICODE_STRING Environment; // Environment block. + UNICODE_STRING PackageAlias; // Aliased package moniker in a packed string. + ULONG CustomDataSize; // Size of the custom data to cache. + PBYTE CustomData; // Pointer to the custom data. +} AHC_SERVICE_DATACACHE, *PAHC_SERVICE_DATACACHE; + +typedef struct _AHC_SERVICE_HWID_QUERY +{ + BOOLEAN QueryResult; // Query result + UNICODE_STRING HwId; // Query HwId; can contain wildcards +} AHC_SERVICE_HWID_QUERY, *PAHC_SERVICE_HWID_QUERY; + +typedef struct _AHC_SERVICE_DATA +{ + AHC_SERVICE_LOOKUP Lookup; // Lookup EXE/Package. + AHC_SERVICE_UPDATE Update; // Updating flags for a given exe/package. + AHC_SERVICE_DATACACHE Cache; // For cache operations. + AHC_SERVICE_LOOKUP_CDB LookupCdb; // Lookup cdb. + AHC_SERVICE_CLEAR Clear; // Clear flags for all exes/packages. + AHC_SERVICE_REMOVE Remove; // Remove EXE/Package. + AHC_SERVICE_HWID_QUERY HwIdQuery; // For HWID cache queries. + NTSTATUS DriverStatus; // Receive the status from the cache driver. Set error code in IoStatus block causes driver verifier violation. + PVOID ParamsOut; // Parameters out data. + ULONG ParamsOutSize; // Parameters out size. +} AHC_SERVICE_DATA, *PAHC_SERVICE_DATA; + +NTSYSCALLAPI +NTSTATUS +NTAPI +NtApphelpCacheControl( + _In_ AHC_SERVICE_CLASS ServiceClass, + _Inout_opt_ PVOID ServiceContext // AHC_SERVICE_DATA + ); + // // VDM // @@ -70,7 +322,6 @@ typedef enum _IO_SESSION_STATE #if (PHNT_MODE != PHNT_MODE_KERNEL) -#if (PHNT_VERSION >= PHNT_WINDOWS_VISTA) NTSYSCALLAPI NTSTATUS NTAPI @@ -79,11 +330,7 @@ NtOpenSession( _In_ ACCESS_MASK DesiredAccess, _In_ POBJECT_ATTRIBUTES ObjectAttributes ); -#endif // (PHNT_VERSION >= PHNT_WINDOWS_VISTA) -#endif // (PHNT_MODE != PHNT_MODE_KERNEL) - -#if (PHNT_VERSION >= PHNT_WINDOWS_7) NTSYSCALLAPI NTSTATUS NTAPI @@ -97,7 +344,8 @@ NtNotifyChangeSession( _In_reads_bytes_opt_(PayloadSize) PVOID Payload, _In_ ULONG PayloadSize ); -#endif // (PHNT_VERSION >= PHNT_WINDOWS_7) + +#endif // (PHNT_MODE != PHNT_MODE_KERNEL) // // ApiSet @@ -142,7 +390,7 @@ NtQuerySecurityPolicy( _Out_writes_bytes_opt_(*ValueSize) PVOID Value, _Inout_ PULONG ValueSize ); -#endif +#endif // (PHNT_VERSION >= PHNT_WINDOWS_10_RS1) #if (PHNT_VERSION >= PHNT_WINDOWS_10_20H1) // rev @@ -179,7 +427,9 @@ NtAcquireCrossVmMutant( _In_ HANDLE CrossVmMutant, _In_ PLARGE_INTEGER Timeout ); +#endif // (PHNT_VERSION >= PHNT_WINDOWS_10_20H1) +#if (PHNT_VERSION >= PHNT_WINDOWS_10_20H1) // rev NTSYSCALLAPI NTSTATUS @@ -227,7 +477,20 @@ NtSetInformationCpuPartition( _Reserved_ ULONG, _Reserved_ ULONG ); -#endif + +// rev +NTSYSCALLAPI +NTSTATUS +NTAPI +NtQueryInformationCpuPartition( + _In_ HANDLE CpuPartitionHandle, + _In_ ULONG CpuPartitionInformationClass, + _Out_writes_bytes_opt_(CpuPartitionInformationLength) PVOID CpuPartitionInformation, + _In_ ULONG CpuPartitionInformationLength, + _Out_opt_ PULONG ReturnLength + ); + +#endif // (PHNT_VERSION >= PHNT_WINDOWS_11_22H2) #if (PHNT_VERSION >= PHNT_WINDOWS_10_RS2) // @@ -247,9 +510,8 @@ NTAPI NtAcquireProcessActivityReference( _Out_ PHANDLE ActivityReferenceHandle, _In_ HANDLE ParentProcessHandle, - _Reserved_ PROCESS_ACTIVITY_TYPE Reserved + _In_ ULONG ProcessActivityType // PROCESS_ACTIVITY_TYPE ); - #endif // (PHNT_VERSION >= PHNT_WINDOWS_10_RS2) // @@ -501,7 +763,7 @@ WINAPI GetCurrentPackageApplicationResourcesContext( _In_ ULONG Index, _Reserved_ ULONG_PTR Unused, - _Out_ PACKAGE_APPLICATION_CONTEXT_REFERENCE *PackageResourcesContext + _Out_ PACKAGE_RESOURCES_CONTEXT_REFERENCE *PackageResourcesContext ); // rev @@ -512,7 +774,7 @@ GetPackageApplicationResourcesContext( _In_ PVOID PackageInfoReference, // PACKAGE_INFO_REFERENCE _In_ ULONG Index, _Reserved_ ULONG_PTR Unused, - _Out_ PACKAGE_APPLICATION_CONTEXT_REFERENCE *PackageResourcesContext + _Out_ PACKAGE_RESOURCES_CONTEXT_REFERENCE *PackageResourcesContext ); // rev @@ -520,10 +782,11 @@ WINBASEAPI LONG WINAPI GetPackageResourcesProperty( - _In_ PACKAGE_APPLICATION_CONTEXT_REFERENCE PackageResourcesContext, + _In_ PACKAGE_RESOURCES_CONTEXT_REFERENCE PackageResourcesContext, _In_ PackageResourcesProperty PropertyId, _Inout_ PULONG BufferSize, - _Out_writes_bytes_(BufferSize) PVOID Buffer + _Out_writes_bytes_(BufferSize) PVOID Buffer, + _Out_opt_ PULONG Flags ); // @@ -606,11 +869,11 @@ WINBASEAPI HRESULT WINAPI GetCurrentPackageInfo3( - _In_ ULONG flags, - _In_ ULONG packagePathType, // PackagePathType - _Inout_ PULONG bufferLength, - _Out_writes_bytes_opt_(*bufferLength) PVOID buffer, - _Out_opt_ PULONG count + _In_ ULONG Flags, + _In_ ULONG PackagePathType, // PackagePathType + _Inout_ PULONG BufferLength, + _Out_writes_bytes_opt_(*BufferLength) PVOID Buffer, + _Out_opt_ PULONG ReturnLength ); // @@ -651,4 +914,304 @@ GetPackageGlobalizationProperty( #endif // PHNT_VERSION >= PHNT_WINDOWS_10_20H1 +// +// COM +// + +// private +_Enum_is_bitflag_ +typedef enum _MTA_HOST_USAGE_FLAGS +{ + MTA_HOST_USAGE_NONE = 0x0, + MTA_HOST_USAGE_MTAINITIALIZED = 0x1, + MTA_HOST_USAGE_ACTIVATORINITIALIZED = 0x2, + MTA_HOST_USAGE_UNLOADCALLED = 0x4, +} MTA_HOST_USAGE_FLAGS, *PMTA_HOST_USAGE_FLAGS; +DEFINE_ENUM_FLAG_OPERATORS(MTA_HOST_USAGE_FLAGS); + +// private +typedef struct _MTA_USAGE_GLOBALS +{ + _Reserved_ ULONG StackCapture; + PULONG MTAInits; // A pointer to the total number of MTA inits + PULONG MTAIncInits; // A pointer to the number of MTA inits from CoIncrementMTAUsage + PULONG MTAWaiters; // A pointer to the number of callers waiting inside CoWaitMTACompletion + PULONG MTAIncrementorSize; // A pointer to the size of the cookie returned by CoIncrementMTAUsage + ULONG CompletionTimeOut; // A timeout for CoWaitMTACompletion in milliseconds + _Reserved_ PLIST_ENTRY ListEntryHeadMTAUsageIncrementor; + _Reserved_ PULONG MTAIncrementorCompleted; + _Reserved_ PVOID* MTAUsageCompletedIncrementorHead; + PMTA_HOST_USAGE_FLAGS MTAHostUsageFlags; // A pointer to the MTA usage flags // since THRESHOLD +} MTA_USAGE_GLOBALS, *PMTA_USAGE_GLOBALS; + +#if (PHNT_VERSION >= PHNT_WINDOWS_8) +// private // combase.dll, ordinal 70 +_Success_(return != 0) +_Must_inspect_result_ +WINBASEAPI +PMTA_USAGE_GLOBALS +WINAPI +CoGetMTAUsageInfo( + VOID + ); #endif + +// +// COM/OLE +// + +// OLETLSFLAGS +#define OLETLS_LOCALTID 0x01 // This TID is in the current process. +#define OLETLS_UUIDINITIALIZED 0x02 // This Logical thread is init'd. +#define OLETLS_INTHREADDETACH 0x04 // This is in thread detach. +#define OLETLS_CHANNELTHREADINITIALZED 0x08// This channel has been init'd +#define OLETLS_WOWTHREAD 0x10 // This thread is a 16-bit WOW thread. +#define OLETLS_THREADUNINITIALIZING 0x20 // This thread is in CoUninitialize. +#define OLETLS_DISABLE_OLE1DDE 0x40 // This thread can't use a DDE window. +#define OLETLS_APARTMENTTHREADED 0x80 // This is an STA apartment thread +#define OLETLS_MULTITHREADED 0x100 // This is an MTA apartment thread +#define OLETLS_IMPERSONATING 0x200 // This thread is impersonating +#define OLETLS_DISABLE_EVENTLOGGER 0x400 // Prevent recursion in event logger +#define OLETLS_INNEUTRALAPT 0x800 // This thread is in the NTA +#define OLETLS_DISPATCHTHREAD 0x1000 // This is a dispatch thread +#define OLETLS_HOSTTHREAD 0x2000 // This is a host thread +#define OLETLS_ALLOWCOINIT 0x4000 // This thread allows inits +#define OLETLS_PENDINGUNINIT 0x8000 // This thread has pending uninit +#define OLETLS_FIRSTMTAINIT 0x10000// First thread to attempt an MTA init +#define OLETLS_FIRSTNTAINIT 0x20000// First thread to attempt an NTA init +#define OLETLS_APTINITIALIZING 0x40000 // Apartment Object is initializing +#define OLETLS_UIMSGSINMODALLOOP 0x80000 +#define OLETLS_MARSHALING_ERROR_OBJECT 0x100000 // since WIN8 +#define OLETLS_WINRT_INITIALIZE 0x200000 // This thread called RoInitialize +#define OLETLS_APPLICATION_STA 0x400000 +#define OLETLS_IN_SHUTDOWN_CALLBACKS 0x800000 +#define OLETLS_POINTER_INPUT_BLOCKED 0x1000000 +#define OLETLS_IN_ACTIVATION_FILTER 0x2000000 // since WINBLUE +#define OLETLS_ASTATOASTAEXEMPT_QUIRK 0x4000000 +#define OLETLS_ASTATOASTAEXEMPT_PROXY 0x8000000 +#define OLETLS_ASTATOASTAEXEMPT_INDOUBT 0x10000000 +#define OLETLS_DETECTED_USER_INITIALIZED 0x20000000 // since RS3 +#define OLETLS_BRIDGE_STA 0x40000000 // since RS5 +#define OLETLS_NAINITIALIZING 0x80000000UL // since 19H1 + +// private +typedef struct tagSOleTlsData +{ + PVOID ThreadBase; + PVOID SmAllocator; + ULONG ApartmentID; + ULONG Flags; // OLETLSFLAGS + LONG TlsMapIndex; + PVOID *TlsSlot; + ULONG ComInits; + ULONG OleInits; + ULONG Calls; + PVOID ServerCall; // previously CallInfo (before TH1) + PVOID CallObjectCache; // previously FreeAsyncCall (before TH1) + PVOID ContextStack; // previously FreeClientCall (before TH1) + PVOID ObjServer; + ULONG TIDCaller; + // ... (other fields are version-dependant) +} SOleTlsData, *PSOleTlsData; + +// private // ole32.dll +WINBASEAPI +VOID +WINAPI +UpdateDCOMSettings( + VOID + ); + +// +// AppCompat +// + +typedef struct tagSDBQUERYRESULT +{ + ULONG Exes[16]; + ULONG ExeFlags[16]; + ULONG Layers[8]; + ULONG LayerFlags; + ULONG AppHelp; + ULONG ExeCount; + ULONG LayerCount; + GUID ID; + ULONG ExtraFlags; + ULONG CustomSDBMap; + GUID DB[16]; +} SDBQUERYRESULT, *PSDBQUERYRESULT; + +static_assert(sizeof(SDBQUERYRESULT) == 0x1c8, "SDBQUERYRESULT size mismatch"); + +typedef struct tagSWITCH_CONTEXT_ATTRIBUTE +{ + ULONG_PTR ContextUpdateCounter; + BOOL AllowContextUpdate; + BOOL EnableTrace; + HANDLE EtwHandle; +} SWITCH_CONTEXT_ATTRIBUTE, *PSWITCH_CONTEXT_ATTRIBUTE; + +#ifdef _WIN64 +static_assert(sizeof(SWITCH_CONTEXT_ATTRIBUTE) == 0x18, "SWITCH_CONTEXT_ATTRIBUTE size mismatch"); +#else +static_assert(sizeof(SWITCH_CONTEXT_ATTRIBUTE) == 0x10, "SWITCH_CONTEXT_ATTRIBUTE size mismatch"); +#endif + +typedef struct tagSWITCH_CONTEXT_DATA +{ + ULONGLONG OsMaxVersionTested; + ULONG TargetPlatform; + ULONGLONG ContextMinimum; + GUID Platform; + GUID MinPlatform; + ULONG ContextSource; + ULONG ElementCount; + GUID Elements[48]; +} SWITCH_CONTEXT_DATA, * PSWITCH_CONTEXT_DATA; + +static_assert(sizeof(SWITCH_CONTEXT_DATA) == 0x340, "SWITCH_CONTEXT_DATA size mismatch"); + +typedef struct tagSWITCH_CONTEXT +{ + SWITCH_CONTEXT_ATTRIBUTE Attribute; + SWITCH_CONTEXT_DATA Data; +} SWITCH_CONTEXT, *PSWITCH_CONTEXT; + +#ifdef _WIN64 +static_assert(sizeof(SWITCH_CONTEXT) == 0x358, "SWITCH_CONTEXT size mismatch"); +#else +static_assert(sizeof(SWITCH_CONTEXT) == 0x350, "SWITCH_CONTEXT size mismatch"); +#endif + +typedef struct _SDB_CSTRUCT_COBALT_PROCFLAG +{ + KAFFINITY AffinityMask; + ULONG CPUIDEcxOverride; + ULONG CPUIDEdxOverride; + USHORT ProcessorGroup; + USHORT FastSelfModThreshold; + USHORT Reserved1; + UCHAR Reserved2; + UCHAR BackgroundWork : 5; + UCHAR CPUIDBrand : 4; + UCHAR Reserved3 : 4; + UCHAR RdtscScaling : 3; + UCHAR Reserved4 : 2; + UCHAR UnalignedAtomicApproach : 2; + UCHAR Win11Atomics : 2; + UCHAR RunOnSingleCore : 1; + UCHAR X64CPUID : 1; + UCHAR PatchUnaligned : 1; + UCHAR InterpreterOrJitter : 1; + UCHAR ForceSegmentHeap : 1; + UCHAR Reserved5 : 1; + UCHAR Reserved6 : 1; + union + { + ULONGLONG Group1AsUINT64; + struct _SDB_CSTRUCT_COBALT_PROCFLAG* Specified; + }; +} SDB_CSTRUCT_COBALT_PROCFLAG, *PSDB_CSTRUCT_COBALT_PROCFLAG; + +#ifdef _WIN64 +static_assert(sizeof(SDB_CSTRUCT_COBALT_PROCFLAG) == 0x28, "SDB_CSTRUCT_COBALT_PROCFLAG size mismatch"); +#else +static_assert(sizeof(SDB_CSTRUCT_COBALT_PROCFLAG) == 0x20, "SDB_CSTRUCT_COBALT_PROCFLAG size mismatch"); +#endif + +typedef struct _APPCOMPAT_EXE_DATA +{ + ULONG_PTR Reserved[65]; + ULONG Size; + ULONG Magic; + BOOL LoadShimEngine; + USHORT ExeType; + SDBQUERYRESULT SdbQueryResult; + ULONG_PTR DbgLogChannels[128]; + SWITCH_CONTEXT SwitchContext; + ULONG ParentProcessId; + WCHAR ParentImageName[260]; + WCHAR ParentCompatLayers[256]; + WCHAR ActiveCompatLayers[256]; + ULONG ImageFileSize; + ULONG ImageCheckSum; + BOOL LatestOs; + BOOL PackageId; + BOOL SwitchBackManifest; + BOOL UacManifest; + BOOL LegacyInstaller; + ULONG RunLevel; + ULONG_PTR WinRTFlags; + PVOID HookCOM; + PVOID ComponentOnDemandEvent; + PVOID Quirks; + ULONG QuirksSize; + SDB_CSTRUCT_COBALT_PROCFLAG CobaltProcFlags; + ULONG FullMatchDbSizeCb; + ULONG FullMatchDbOffset; +} APPCOMPAT_EXE_DATA; + +#ifdef _WIN64 +static_assert(sizeof(APPCOMPAT_EXE_DATA) == 0x11C0, "APPCOMPAT_EXE_DATA size mismatch"); +#else +static_assert(sizeof(APPCOMPAT_EXE_DATA) == 0xE98, "APPCOMPAT_EXE_DATA size mismatch"); +#endif + +// +// Direct3D Kernel Mode Thunk (D3DKMT) +// + +/** + * The D3DKMT_GET_PROCESS_LIST structure is used for retrieving a list of process handles using a graphics adapter. + * \remarks The caller is responsible for closing the returned process handles. + */ +// rev +typedef struct _D3DKMT_GET_PROCESS_LIST +{ + LUID AdapterLuid; // [in] The locally unique identifier (LUID) for the graphics adapter. + ULONG DesiredAccess; // [in] The access rights to request for the process handles. This must be `PROCESS_QUERY_INFORMATION` (0x400). + ULONG ProcessHandleCount; // [in, out] On input, specifies the number of handles the `ProcessHandle` member can hold. On output, receives the number of handles returned. + HANDLE ProcessHandle; // [out] The first element of an array that receives the process handles. +} D3DKMT_GET_PROCESS_LIST, *PD3DKMT_GET_PROCESS_LIST; + +// rev +/** + * The D3DKMTGetProcessList function retrieves a list of processes that are using a specific graphics adapter. + * + * \param[in,out] GetProcessList A pointer to a \ref D3DKMT_GET_PROCESS_LIST structure that contains the processes using the graphics adapter. + * \return NTSTATUS Successful or errant status. + */ +EXTERN_C +NTSTATUS +NTAPI +D3DKMTGetProcessList( + _Inout_ PD3DKMT_GET_PROCESS_LIST GetProcessList + ); + +// rev +/** + * The D3DKMT_ENUM_PROCESS_LIST structure is used for retrieving a list of process identifiers using a graphics adapter. + */ +typedef struct _D3DKMT_ENUM_PROCESS_LIST +{ + LUID AdapterLuid; // [in] The locally unique identifier (LUID) for the graphics adapter. + PULONG ProcessIdBuffer; // [out] A pointer to a buffer that receives the list of process identifiers (PIDs). + SIZE_T ProcessIdCount; // [in, out] On input, specifies the number of elements the `ProcessIdBuffer` can hold. On output, receives the number of process IDs returned. +} D3DKMT_ENUM_PROCESS_LIST, *PD3DKMT_ENUM_PROCESS_LIST; + +// rev +/** + * The D3DKMTEnumProcesses function provides a list of process IDs (PIDs) rather than handles that are using a specific graphics adapter, + * which can be more efficient for monitoring purposes. + * + * \param[in,out] EnumProcessList A pointer to a \ref D3DKMT_ENUM_PROCESS_LIST structure that contains the processes using the graphics adapter. + * \return NTSTATUS Successful or errant status. + */ +EXTERN_C +NTSTATUS +NTAPI +D3DKMTEnumProcesses( + _Inout_ PD3DKMT_ENUM_PROCESS_LIST EnumProcessList + ); + +#endif // _NTMISC_H diff --git a/ntmmapi.h b/ntmmapi.h index 25469be..45d6487 100644 --- a/ntmmapi.h +++ b/ntmmapi.h @@ -7,6 +7,8 @@ #ifndef _NTMMAPI_H #define _NTMMAPI_H +typedef struct _IO_STATUS_BLOCK* PIO_STATUS_BLOCK; + // // Memory Protection Constants // @@ -86,21 +88,21 @@ #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 - MemoryImageExtensionInformation, // MEMORY_IMAGE_EXTENSION_INFORMATION // since 24H2 + MemoryBasicInformation, // q: MEMORY_BASIC_INFORMATION + MemoryWorkingSetInformation, // q: MEMORY_WORKING_SET_INFORMATION + MemoryMappedFilenameInformation, // q: UNICODE_STRING + MemoryRegionInformation, // q: MEMORY_REGION_INFORMATION/MEMORY_REGION_INFORMATION_EX + MemoryWorkingSetExInformation, // q: MEMORY_WORKING_SET_EX_INFORMATION // since VISTA + MemorySharedCommitInformation, // q: MEMORY_SHARED_COMMIT_INFORMATION // since WIN8 + MemoryImageInformation, // q: MEMORY_IMAGE_INFORMATION + MemoryRegionInformationEx, // q: MEMORY_REGION_INFORMATION/MEMORY_REGION_INFORMATION_EX + MemoryPrivilegedBasicInformation, // q: MEMORY_BASIC_INFORMATION + MemoryEnclaveImageInformation, // q: MEMORY_ENCLAVE_IMAGE_INFORMATION // since REDSTONE3 + MemoryBasicInformationCapped, // q: 10 + MemoryPhysicalContiguityInformation, // q: MEMORY_PHYSICAL_CONTIGUITY_INFORMATION // since 20H1 + MemoryBadInformation, // q: MEMORY_BAD_INFORMATION // since WIN11 + MemoryBadInformationAllProcesses, // qs: not implemented // since 22H1 + MemoryImageExtensionInformation, // q: MEMORY_IMAGE_EXTENSION_INFORMATION // since 24H2 MaxMemoryInfoClass } MEMORY_INFORMATION_CLASS; #else @@ -119,7 +121,7 @@ typedef enum _MEMORY_INFORMATION_CLASS #define MemoryBadInformation 0xC #define MemoryBadInformationAllProcesses 0xD #define MemoryImageExtensionInformation 0xE -#endif +#endif // (PHNT_MODE != PHNT_MODE_KERNEL) // MEMORY_WORKING_SET_BLOCK->Protection #define MEMORY_BLOCK_NOT_ACCESSED 0 @@ -157,8 +159,7 @@ typedef enum _MEMORY_INFORMATION_CLASS /** * The MEMORY_WORKING_SET_BLOCK structure contains working set information for a page. - * - * \ref https://learn.microsoft.com/en-us/windows/win32/api/psapi/ns-psapi-psapi_working_set_block + * \sa https://learn.microsoft.com/en-us/windows/win32/api/psapi/ns-psapi-psapi_working_set_block */ typedef struct _MEMORY_WORKING_SET_BLOCK { @@ -175,8 +176,7 @@ typedef struct _MEMORY_WORKING_SET_BLOCK /** * The MEMORY_WORKING_SET_INFORMATION structure contains working set information for a process. - * - * \ref https://learn.microsoft.com/en-us/windows/win32/api/psapi/ns-psapi-psapi_working_set_information + * \sa https://learn.microsoft.com/en-us/windows/win32/api/psapi/ns-psapi-psapi_working_set_information */ typedef struct _MEMORY_WORKING_SET_INFORMATION { @@ -184,38 +184,50 @@ typedef struct _MEMORY_WORKING_SET_INFORMATION _Field_size_(NumberOfEntries) MEMORY_WORKING_SET_BLOCK WorkingSetInfo[ANYSIZE_ARRAY]; } MEMORY_WORKING_SET_INFORMATION, *PMEMORY_WORKING_SET_INFORMATION; +typedef union _MEMORY_REGION_INFORMATION_TYPE +{ + ULONG RegionType; + struct + { + ULONG Private : 1; // Region is private to the process (not shared). + ULONG MappedDataFile : 1; // Region is a mapped view of a data file (read/write data mapping). + ULONG MappedImage : 1; // Region is a mapped view of an image file (executable/DLL mapping). + ULONG MappedPageFile : 1; // Region is a mapped view of a pagefile-backed section. + ULONG MappedPhysical : 1; // Region is a mapped view of the \Device\PhysicalMemory section. + ULONG DirectMapped : 1; // Region is a mapped view of a direct-mapped file. + ULONG SoftwareEnclave : 1; // Region is a mapped view of a software enclave. // since REDSTONE3 + ULONG PageSize64K : 1; // Region uses 64 KB page size. + ULONG PlaceholderReservation : 1; // Region uses placeholder reservations. // since REDSTONE4 + ULONG MappedAwe : 1; // Region uses Address Windowing Extensions (AWE). // 21H1 + ULONG MappedWriteWatch : 1; // Region uses write-watch protection. + ULONG PageSizeLarge : 1; // Region uses large page size. + ULONG PageSizeHuge : 1; // Region uses huge page size. + ULONG Reserved : 19; + }; +} MEMORY_REGION_INFORMATION_TYPE, *PMEMORY_REGION_INFORMATION_TYPE; + // 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 + PVOID AllocationBase; // Base address of the allocation. + ULONG AllocationProtect; // Page protection when the allocation was created (individual pages can be different from this value). + ULONG RegionType; // Region type flags. + SIZE_T RegionSize; // The combined size of pages in the region. + SIZE_T CommitSize; // The commit charge associated with the allocation. } MEMORY_REGION_INFORMATION, *PMEMORY_REGION_INFORMATION; +// private +typedef struct _MEMORY_REGION_INFORMATION_EX +{ + PVOID AllocationBase; // Base address of the allocation. + ULONG AllocationProtect; // Page protection when the allocation was created (individual pages can be different from this value). + ULONG RegionType; // Region type flags. + SIZE_T RegionSize; // The combined size of pages in the region. + SIZE_T CommitSize; // The commit charge associated with the allocation. + ULONG_PTR PartitionId; // 19H1 + ULONG_PTR NodePreference; // 20H1 +} MEMORY_REGION_INFORMATION_EX, *PMEMORY_REGION_INFORMATION_EX; + // private typedef enum _MEMORY_WORKING_SET_EX_LOCATION { @@ -227,8 +239,7 @@ typedef enum _MEMORY_WORKING_SET_EX_LOCATION /** * The MEMORY_WORKING_SET_EX_BLOCK structure contains extended working set information for a page. - * - * \ref https://learn.microsoft.com/en-us/windows/win32/api/psapi/ns-psapi-psapi_working_set_ex_block + * \sa https://learn.microsoft.com/en-us/windows/win32/api/psapi/ns-psapi-psapi_working_set_ex_block */ typedef union _MEMORY_WORKING_SET_EX_BLOCK { @@ -259,10 +270,10 @@ typedef union _MEMORY_WORKING_SET_EX_BLOCK ULONG_PTR Reserved0 : 14; ULONG_PTR Shared : 1; // If this bit is 1, the page can be shared. ULONG_PTR Reserved1 : 5; - ULONG_PTR PageTable : 1; + ULONG_PTR PageTable : 1; // If this bit is 1, the page is a page table entry. ULONG_PTR Location : 2; // The memory location of the page. MEMORY_WORKING_SET_EX_LOCATION ULONG_PTR Priority : 3; // The memory priority of the page. - ULONG_PTR ModifiedList : 1; + ULONG_PTR ModifiedList : 1; // If this bit is 1, the page is on the modified standby list. ULONG_PTR Reserved2 : 2; ULONG_PTR SharedOriginal : 1; // If this bit is 1, the page was not modified. ULONG_PTR Bad : 1; // If this bit is 1, the page is has been reported as bad. @@ -275,8 +286,7 @@ typedef union _MEMORY_WORKING_SET_EX_BLOCK /** * The MEMORY_WORKING_SET_EX_INFORMATION structure contains extended working set information for a process. - * - * \ref https://learn.microsoft.com/en-us/windows/win32/api/psapi/ns-psapi-psapi_working_set_ex_information + * \sa https://learn.microsoft.com/en-us/windows/win32/api/psapi/ns-psapi-psapi_working_set_ex_information */ typedef struct _MEMORY_WORKING_SET_EX_INFORMATION { @@ -284,7 +294,10 @@ typedef struct _MEMORY_WORKING_SET_EX_INFORMATION MEMORY_WORKING_SET_EX_BLOCK VirtualAttributes; // The attributes of the page at VirtualAddress. } MEMORY_WORKING_SET_EX_INFORMATION, *PMEMORY_WORKING_SET_EX_INFORMATION; -// private +/** + * The MEMORY_SHARED_COMMIT_INFORMATION structure contains the total commit size + * for a region of memory that is shared between processes. + */ typedef struct _MEMORY_SHARED_COMMIT_INFORMATION { SIZE_T CommitSize; @@ -313,11 +326,13 @@ typedef struct _MEMORY_IMAGE_INFORMATION typedef struct _MEMORY_ENCLAVE_IMAGE_INFORMATION { MEMORY_IMAGE_INFORMATION ImageInfo; - UCHAR UniqueID[32]; - UCHAR AuthorID[32]; + UCHAR UniqueID[32]; // 32-byte unique identifier for the enclave image. + UCHAR AuthorID[32]; // 32-byte identifier for the author/creator of the enclave image. } MEMORY_ENCLAVE_IMAGE_INFORMATION, *PMEMORY_ENCLAVE_IMAGE_INFORMATION; -// private +/** + * The MEMORY_PHYSICAL_CONTIGUITY_UNIT_STATE structure describes the eligibility state or contiguity unit. + */ typedef enum _MEMORY_PHYSICAL_CONTIGUITY_UNIT_STATE { MemoryNotContiguous, @@ -327,21 +342,25 @@ typedef enum _MEMORY_PHYSICAL_CONTIGUITY_UNIT_STATE MemoryContiguityStateMax, } MEMORY_PHYSICAL_CONTIGUITY_UNIT_STATE; -// private +/** + * The MEMORY_PHYSICAL_CONTIGUITY_UNIT_INFORMATION structure describes the per-unit contiguity state. + */ typedef struct _MEMORY_PHYSICAL_CONTIGUITY_UNIT_INFORMATION { union { + ULONG AllInformation; struct { ULONG State : 2; ULONG Reserved : 30; }; - ULONG AllInformation; }; } MEMORY_PHYSICAL_CONTIGUITY_UNIT_INFORMATION, *PMEMORY_PHYSICAL_CONTIGUITY_UNIT_INFORMATION; -// private +/** + * The MEMORY_PHYSICAL_CONTIGUITY_INFORMATION structure describes a virtual range and contiguity unit characteristics for physical contiguity queries. + */ typedef struct _MEMORY_PHYSICAL_CONTIGUITY_INFORMATION { PVOID VirtualAddress; @@ -351,106 +370,145 @@ typedef struct _MEMORY_PHYSICAL_CONTIGUITY_INFORMATION PMEMORY_PHYSICAL_CONTIGUITY_UNIT_INFORMATION ContiguityUnitInformation; } MEMORY_PHYSICAL_CONTIGUITY_INFORMATION, *PMEMORY_PHYSICAL_CONTIGUITY_INFORMATION; -// private +// rev +/** + * The MEMORY_BAD_INFORMATION structure reports a range of memory that has been marked bad or otherwise problematic. + */ +typedef struct _MEMORY_BAD_INFORMATION +{ + PVOID BadAddress; // Starting address of the bad memory range. + ULONG_PTR Length; // Length in bytes of the bad range. + ULONG Flags; // Flags describing the nature of the bad memory. + ULONG Reserved; +} MEMORY_BAD_INFORMATION, *PMEMORY_BAD_INFORMATION; + +/** + * The RTL_SCP_CFG_ARM64_HEADER structure contains ARM64 SCP/CFG descriptors; RVAs to handlers + * and helper routines used when configuring CFG/SCP emulation on ARM64. + */ typedef struct _RTL_SCP_CFG_ARM64_HEADER { - ULONG EcInvalidCallHandlerRva; - ULONG EcCfgCheckRva; - ULONG EcCfgCheckESRva; - ULONG EcCallCheckRva; - ULONG CpuInitializationCompleteLoadRva; - ULONG LdrpValidateEcCallTargetInitRva; - ULONG SyscallFfsSizeRva; - ULONG SyscallFfsBaseRva; + ULONG EcInvalidCallHandlerRva; // RVA to invalid EC call handler. + ULONG EcCfgCheckRva; // RVA to EC CFG check routine. + ULONG EcCfgCheckESRva; // RVA to EC CFG check exception stub RVA. + ULONG EcCallCheckRva; // RVA to EC call-check routine. + ULONG CpuInitializationCompleteLoadRva; // RVA related to CPU init completion load. + ULONG LdrpValidateEcCallTargetInitRva; // RVA used by loader validation init. + ULONG SyscallFfsSizeRva; // RVA describing syscall FFS size. + ULONG SyscallFfsBaseRva; // RVA describing syscall FFS base. } RTL_SCP_CFG_ARM64_HEADER, *PRTL_SCP_CFG_ARM64_HEADER; -// private +/** + * The RTL_SCP_CFG_PAGE_TYPE enumeration describes page types used by SCP/CFG image extensions. + */ typedef enum _RTL_SCP_CFG_PAGE_TYPE { - RtlScpCfgPageTypeNop, - RtlScpCfgPageTypeDefault, - RtlScpCfgPageTypeExportSuppression, - RtlScpCfgPageTypeFptr, - RtlScpCfgPageTypeMax, - RtlScpCfgPageTypeNone + RtlScpCfgPageTypeNop, // No-op / placeholder page. + RtlScpCfgPageTypeDefault, // Default handling page. + RtlScpCfgPageTypeExportSuppression, // Export-suppression descriptor page. + RtlScpCfgPageTypeFptr, // Page that contains function pointers. + RtlScpCfgPageTypeMax, // Upper bound for the enum. + RtlScpCfgPageTypeNone // Explicit 'none' value. } RTL_SCP_CFG_PAGE_TYPE; -// private +/** + * The RTL_SCP_CFG_COMMON_HEADER structure contains RVAs to dispatch and check + * routines used by SCP/CFG configuration blocks. + */ typedef struct _RTL_SCP_CFG_COMMON_HEADER { - ULONG CfgDispatchRva; - ULONG CfgDispatchESRva; - ULONG CfgCheckRva; - ULONG CfgCheckESRva; - ULONG InvalidCallHandlerRva; - ULONG FnTableRva; + ULONG CfgDispatchRva; // RVA to CFG dispatch routine. + ULONG CfgDispatchESRva; // RVA to CFG dispatch exception stub. + ULONG CfgCheckRva; // RVA to CFG checking routine. + ULONG CfgCheckESRva; // RVA to CFG checking exception stub. + ULONG InvalidCallHandlerRva; // RVA to invalid-call handler. + ULONG FnTableRva; // RVA to function-pointer table. } RTL_SCP_CFG_COMMON_HEADER, *PRTL_SCP_CFG_COMMON_HEADER; -// private +/** + * The RTL_SCP_CFG_HEADER structure contains the common SCP/CFG configuration header. + */ typedef struct _RTL_SCP_CFG_HEADER { RTL_SCP_CFG_COMMON_HEADER Common; } RTL_SCP_CFG_HEADER, *PRTL_SCP_CFG_HEADER; -// private +/** + * The RTL_SCP_CFG_REGION_BOUNDS structure describes inclusive start/end + * addresses of an SCP/CFG-protected region. + */ typedef struct _RTL_SCP_CFG_REGION_BOUNDS { - PVOID StartAddress; - PVOID EndAddress; + PVOID StartAddress; // Inclusive start address of the region. + PVOID EndAddress; // Inclusive end address of the region. } RTL_SCP_CFG_REGION_BOUNDS, *PRTL_SCP_CFG_REGION_BOUNDS; -// private +/** + * The RTL_SCP_CFG_NTDLL_EXPORTS structure contains ntdll export descriptors and + * region bounds used to implement or validate CFG/SCP behavior at runtime. + */ typedef struct _RTL_SCP_CFG_NTDLL_EXPORTS { - RTL_SCP_CFG_REGION_BOUNDS ScpRegions[4]; - PVOID CfgDispatchFptr; - PVOID CfgDispatchESFptr; - PVOID CfgCheckFptr; - PVOID CfgCheckESFptr; - PVOID IllegalCallHandler; + RTL_SCP_CFG_REGION_BOUNDS ScpRegions[4]; // Array of SCP region bounds (max 4). + PVOID CfgDispatchFptr; // Pointer to CFG dispatch function. + PVOID CfgDispatchESFptr; // Pointer to CFG dispatch exception stub. + PVOID CfgCheckFptr; // Pointer to CFG check function. + PVOID CfgCheckESFptr; // Pointer to CFG check exception stub. + PVOID IllegalCallHandler; // Pointer to handler invoked for illegal calls. } RTL_SCP_CFG_NTDLL_EXPORTS, *PRTL_SCP_CFG_NTDLL_EXPORTS; -// private +/** + * The RTL_SCP_CFG_NTDLL_EXPORTS_ARM64EC structure contains ARM64-specific ntdll + * export descriptors used for EC / ARM64EC handling. + */ typedef struct _RTL_SCP_CFG_NTDLL_EXPORTS_ARM64EC { - PVOID EcInvalidCallHandler; - PVOID EcCfgCheckFptr; - PVOID EcCfgCheckESFptr; - PVOID EcCallCheckFptr; - PVOID CpuInitializationComplete; - PVOID LdrpValidateEcCallTargetInit; + PVOID EcInvalidCallHandler; // Pointer to invalid EC call handler. + PVOID EcCfgCheckFptr; // Pointer to EC CFG check function. + PVOID EcCfgCheckESFptr; // Pointer to EC CFG check exception stub. + PVOID EcCallCheckFptr; // Pointer to EC call-check routine. + PVOID CpuInitializationComplete; // Pointer to CPU initialization completion routine. + PVOID LdrpValidateEcCallTargetInit; // Pointer to loader validation init routine. struct { - PVOID SyscallFfsSize; + PVOID SyscallFfsSize; // Pointer to syscall FFS size descriptor. union { - PVOID Ptr; - ULONG Value; + PVOID Ptr; // Pointer form of FFS size descriptor. + ULONG Value; // Value form of FFS size descriptor. }; }; - PVOID SyscallFfsBase; + PVOID SyscallFfsBase; // Pointer to syscall FFS base. } RTL_SCP_CFG_NTDLL_EXPORTS_ARM64EC, *PRTL_SCP_CFG_NTDLL_EXPORTS_ARM64EC; -// private +/** + * The RTL_RETPOLINE_ROUTINES structure contains indices/offsets and jump-table + * descriptors used for retpoline/runtime patching. + */ typedef struct _RTL_RETPOLINE_ROUTINES { - ULONG SwitchtableJump[16]; - ULONG CfgIndirectRax; - ULONG NonCfgIndirectRax; - ULONG ImportR10; - ULONG JumpHpat; + ULONG SwitchtableJump[16]; // Jump offsets for switchtable entries. + ULONG CfgIndirectRax; // Index/offset for indirect calls using RAX under CFG. + ULONG NonCfgIndirectRax; // Index/offset for indirect calls not under CFG. + ULONG ImportR10; // Import slot/index for R10-based imports. + ULONG JumpHpat; // Hot-spot jump table offset. } RTL_RETPOLINE_ROUTINES, *PRTL_RETPOLINE_ROUTINES; -// private +/** + * The RTL_KSCP_ROUTINES structure contains the kernel-side + * SCP-related routine descriptors used for XFG/CFG/retpoline support. + */ typedef struct _RTL_KSCP_ROUTINES { - ULONG UnwindDataOffset; + ULONG UnwindDataOffset; // Offset to unwind data for the routines. RTL_RETPOLINE_ROUTINES RetpolineRoutines; - ULONG CfgDispatchSmep; - ULONG CfgDispatchNoSmep; + ULONG CfgDispatchSmep; // CFG dispatch variant when SMEP is enabled. + ULONG CfgDispatchNoSmep; // CFG dispatch variant when SMEP is not enabled. } RTL_KSCP_ROUTINES, *PRTL_KSCP_ROUTINES; -// private +/** + * The MEMORY_IMAGE_EXTENSION_TYPE enumeration specifies the supported image extension types. + */ typedef enum _MEMORY_IMAGE_EXTENSION_TYPE { MemoryImageExtensionCfgScp, @@ -458,13 +516,16 @@ typedef enum _MEMORY_IMAGE_EXTENSION_TYPE MemoryImageExtensionTypeMax, } MEMORY_IMAGE_EXTENSION_TYPE; -// private +/** + * The MEMORY_IMAGE_EXTENSION_INFORMATION structure describes an optional image extension + * containing additional metadata or features (for example, CFG/SCP related extensions). + */ typedef struct _MEMORY_IMAGE_EXTENSION_INFORMATION { - MEMORY_IMAGE_EXTENSION_TYPE ExtensionType; - ULONG Flags; - PVOID ExtensionImageBaseRva; - SIZE_T ExtensionSize; + MEMORY_IMAGE_EXTENSION_TYPE ExtensionType; // Type of the image extension (MEMORY_IMAGE_EXTENSION_TYPE). + ULONG Flags; // Extension-specific flags. + PVOID ExtensionImageBaseRva; // Relative virtual address of the extension image base. + SIZE_T ExtensionSize; // Size, in bytes, of the extension region. } MEMORY_IMAGE_EXTENSION_INFORMATION, *PMEMORY_IMAGE_EXTENSION_INFORMATION; #define MMPFNLIST_ZERO 0 @@ -589,111 +650,16 @@ typedef struct _MMPFN_MEMSNAP_INFORMATION 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 ImageExportSuppressionInfoPresent : 1; - ULONG ImageCfgEnabled : 1; - ULONG Reserved : 22; - }; - }; -} 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_DISABLE_EXCEPTION_CHAIN_VALIDATION 0x40 +// Flags directly correspond to KPROCESS.Flags, of type KEXECUTE_OPTIONS (named bitfields available). +// Flags adjust OS behavior for 32-bit processes only. They are effectively ignored for ARM64 and x64 processes. +// [nt!Mi]canGrantExecute = KF_GLOBAL_32BIT_EXECUTE || MEM_EXECUTE_OPTION_ENABLE || (!KF_GLOBAL_32BIT_NOEXECUTE && !MEM_EXECUTE_OPTION_DISABLE) +#define MEM_EXECUTE_OPTION_DISABLE 0x1 // respect the NX bit: DEP on, only run code from executable pages +#define MEM_EXECUTE_OPTION_ENABLE 0x2 // ignore the NX bit: DEP off, enable executing most of ro/rw memory; trumps over the _DISABLE option +#define MEM_EXECUTE_OPTION_DISABLE_THUNK_EMULATION 0x4 // do not emulate NX code sequences which look like ATL thunks +#define MEM_EXECUTE_OPTION_PERMANENT 0x8 // changing any MEM_EXECUTE_* option for the process is not allowed [anymore] +#define MEM_EXECUTE_OPTION_EXECUTE_DISPATCH_ENABLE 0x10 // allow non-executable exception handlers (ntdll!RtlIsValidHandler) +#define MEM_EXECUTE_OPTION_IMAGE_DISPATCH_ENABLE 0x20 // allow non-MEM_IMAGE exception handlers (ntdll!RtlIsValidHandler) +#define MEM_EXECUTE_OPTION_DISABLE_EXCEPTION_CHAIN_VALIDATION 0x40 // don't invoke ntdll!RtlpIsValidExceptionChain to check SEH chain #define MEM_EXECUTE_OPTION_VALID_FLAGS 0x7f // @@ -702,6 +668,20 @@ typedef enum _SECTION_INHERIT #if (PHNT_MODE != PHNT_MODE_KERNEL) +/** + * The NtAllocateVirtualMemory routine reserves, commits, or both, a region of pages within the user-mode virtual address space of a specified process. + * + * \param ProcessHandle A handle for the process for which the mapping should be done. + * \param BaseAddress A pointer to a variable that will receive the base address of the allocated region of pages. + * If the initial value is not zero, the region is allocated at the specified virtual address. + * \param ZeroBits The number of high-order address bits that must be zero in the base address of the section view. + * This value must be less than 21 and the initial value of BaseAddress must be zero. + * \param RegionSize A pointer to a variable that will receive the actual size, in bytes, of the allocated region of pages. + * \param AllocationType A bitmask containing flags that specify the type of allocation to be performed. + * \param PageProtection A bitmask containing page protection flags that specify the protection desired for the committed region of pages. + * \return NTSTATUS Successful or errant status. + * \sa https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/ntifs/nf-ntifs-zwallocatevirtualmemory + */ _Must_inspect_result_ _When_(return == 0, __drv_allocatesMem(mem)) NTSYSCALLAPI @@ -717,8 +697,21 @@ NtAllocateVirtualMemory( ); #if (PHNT_VERSION >= PHNT_WINDOWS_10_RS5) +/** + * The NtAllocateVirtualMemoryEx routine reserves, commits, or both, a region of pages within the user-mode virtual address space of a specified process. + * + * \param ProcessHandle A handle for the process for which the mapping should be done. + * \param BaseAddress A pointer to a variable that will receive the base address of the allocated region of pages. If the initial value is not zero, the region is allocated at the specified virtual address. + * \param RegionSize A pointer to a variable that will receive the actual size, in bytes, of the allocated region of pages. + * \param AllocationType A bitmask containing flags that specify the type of allocation to be performed. + * \param PageProtection A bitmask containing page protection flags that specify the protection desired for the committed region of pages. + * \param ExtendedParameters An optional pointer to one or more extended parameters of type MEM_EXTENDED_PARAMETER. + * \param ExtendedParameterCount Specifies the number of elements in the ExtendedParameters array. + * \return NTSTATUS Successful or errant status. + * \sa https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/ntifs/nf-ntifs-zwallocatevirtualmemory + */ _Must_inspect_result_ -_When_(return == 0, __drv_allocatesMem(mem)) +_When_(return == 0, __drv_allocatesMem(Mem)) NTSYSCALLAPI NTSTATUS NTAPI @@ -731,36 +724,36 @@ NtAllocateVirtualMemoryEx( _Inout_updates_opt_(ExtendedParameterCount) PMEM_EXTENDED_PARAMETER ExtendedParameters, _In_ ULONG ExtendedParameterCount ); -#endif +#endif // (PHNT_VERSION >= PHNT_WINDOWS_10_RS5) /** - * Frees virtual memory allocated for a process. + * The NtFreeVirtualMemory routine frees virtual memory allocated for a process. * - * @param ProcessHandle A handle to the process whose virtual memory is to be freed. - * @param BaseAddress A pointer to the base address of the region of pages to be freed. - * @param RegionSize A pointer to a variable that specifies the size of the region of memory to be freed. - * @param FreeType The type of free operation. This parameter can be MEM_DECOMMIT or MEM_RELEASE. - * @return NTSTATUS Successful or errant status. + * \param ProcessHandle A handle to the process whose virtual memory is to be freed. + * \param BaseAddress A pointer to the base address of the region of pages to be freed. + * \param RegionSize A pointer to a variable that specifies the size of the region of memory to be freed. + * \param FreeType The type of free operation. This parameter can be MEM_DECOMMIT or MEM_RELEASE. + * \return NTSTATUS Successful or errant status. */ NTSYSCALLAPI NTSTATUS NTAPI NtFreeVirtualMemory( _In_ HANDLE ProcessHandle, - _Inout_ PVOID *BaseAddress, + _Inout_ __drv_freesMem(Mem) PVOID *BaseAddress, _Inout_ PSIZE_T RegionSize, _In_ ULONG FreeType ); -/** - * Reads virtual memory from a process. + /** + * The NtReadVirtualMemory routine reads virtual memory from a process. * - * @param ProcessHandle A handle to the process whose memory is to be read. - * @param BaseAddress A pointer to the base address in the specified process from which to read. - * @param Buffer A pointer to a buffer that receives the contents from the address space of the specified process. - * @param NumberOfBytesToRead The number of bytes to be read from the specified process. - * @param NumberOfBytesRead A pointer to a variable that receives the number of bytes transferred into the specified buffer. - * @return NTSTATUS Successful or errant status. + * \param ProcessHandle A handle to the process whose memory is to be read. + * \param BaseAddress A pointer to the base address in the specified process from which to read. + * \param Buffer A pointer to a buffer that receives the contents from the address space of the specified process. + * \param NumberOfBytesToRead The number of bytes to be read from the specified process. + * \param NumberOfBytesRead A pointer to a variable that receives the number of bytes transferred into the specified buffer. + * \return NTSTATUS Successful or errant status. */ NTSYSCALLAPI NTSTATUS @@ -774,7 +767,17 @@ NtReadVirtualMemory( ); // rev -NTSYSCALLAPI +/** + * The NtWow64ReadVirtualMemory64 routine reads virtual memory of a 64-bit process from a 32-bit process. + * + * \param ProcessHandle A handle to the process whose memory is to be read. + * \param BaseAddress A pointer to the base address in the specified process from which to read. + * \param Buffer A pointer to a buffer that receives the contents from the address space of the specified process. + * \param NumberOfBytesToRead The number of bytes to be read from the specified process. + * \param NumberOfBytesRead A pointer to a variable that receives the number of bytes transferred into the specified buffer. + * \return NTSTATUS Successful or errant status. + */ +NTSYSAPI NTSTATUS NTAPI NtWow64ReadVirtualMemory64( @@ -787,15 +790,15 @@ NtWow64ReadVirtualMemory64( #if (PHNT_VERSION >= PHNT_WINDOWS_11) /** - * Reads virtual memory from a process with extended options. + * The NtReadVirtualMemoryEx routine reads virtual memory from a process with extended options. * - * @param ProcessHandle A handle to the process whose memory is to be read. - * @param BaseAddress A pointer to the base address in the specified process from which to read. - * @param Buffer A pointer to a buffer that receives the contents from the address space of the specified process. - * @param NumberOfBytesToRead The number of bytes to be read from the specified process. - * @param NumberOfBytesRead A pointer to a variable that receives the number of bytes transferred into the specified buffer. - * @param Flags Additional flags for the read operation. - * @return NTSTATUS Successful or errant status. + * \param ProcessHandle A handle to the process whose memory is to be read. + * \param BaseAddress A pointer to the base address in the specified process from which to read. + * \param Buffer A pointer to a buffer that receives the contents from the address space of the specified process. + * \param NumberOfBytesToRead The number of bytes to be read from the specified process. + * \param NumberOfBytesRead A pointer to a variable that receives the number of bytes transferred into the specified buffer. + * \param Flags Additional flags for the read operation. + * \return NTSTATUS Successful or errant status. */ NTSYSCALLAPI NTSTATUS @@ -808,17 +811,17 @@ NtReadVirtualMemoryEx( _Out_opt_ PSIZE_T NumberOfBytesRead, _In_ ULONG Flags ); -#endif +#endif // (PHNT_VERSION >= PHNT_WINDOWS_11) /** - * Writes virtual memory to a process. + * The NtWriteVirtualMemory routine writes virtual memory to a process. * - * @param ProcessHandle A handle to the process whose memory is to be written. - * @param BaseAddress A pointer to the base address in the specified process to which to write. - * @param Buffer A pointer to the buffer that contains the data to be written to the address space of the specified process. - * @param NumberOfBytesToWrite The number of bytes to be written to the specified process. - * @param NumberOfBytesWritten A pointer to a variable that receives the number of bytes transferred into the specified buffer. - * @return NTSTATUS Successful or errant status. + * \param ProcessHandle A handle to the process whose memory is to be written. + * \param BaseAddress A pointer to the base address in the specified process to which to write. + * \param Buffer A pointer to the buffer that contains the data to be written to the address space of the specified process. + * \param NumberOfBytesToWrite The number of bytes to be written to the specified process. + * \param NumberOfBytesWritten A pointer to a variable that receives the number of bytes transferred into the specified buffer. + * \return NTSTATUS Successful or errant status. */ NTSYSCALLAPI NTSTATUS @@ -833,16 +836,16 @@ NtWriteVirtualMemory( // rev /** - * Writes virtual memory to a 64-bit process from a 32-bit process. + * The NtWow64WriteVirtualMemory64 routine writes virtual memory to a 64-bit process from a 32-bit process. * - * @param ProcessHandle A handle to the process whose memory is to be written. - * @param BaseAddress A pointer to the base address in the specified process to which to write. - * @param Buffer A pointer to the buffer that contains the data to be written to the address space of the specified process. - * @param NumberOfBytesToWrite The number of bytes to be written to the specified process. - * @param NumberOfBytesWritten A pointer to a variable that receives the number of bytes transferred into the specified buffer. - * @return NTSTATUS Successful or errant status. + * \param ProcessHandle A handle to the process whose memory is to be written. + * \param BaseAddress A pointer to the base address in the specified process to which to write. + * \param Buffer A pointer to the buffer that contains the data to be written to the address space of the specified process. + * \param NumberOfBytesToWrite The number of bytes to be written to the specified process. + * \param NumberOfBytesWritten A pointer to a variable that receives the number of bytes transferred into the specified buffer. + * \return NTSTATUS Successful or errant status. */ -NTSYSCALLAPI +NTSYSAPI NTSTATUS NTAPI NtWow64WriteVirtualMemory64( @@ -854,14 +857,14 @@ NtWow64WriteVirtualMemory64( ); /** - * Changes the protection on a region of virtual memory. + * The NtProtectVirtualMemory routine changes the protection on a region of virtual memory. * - * @param ProcessHandle A handle to the process whose memory protection is to be changed. - * @param BaseAddress A pointer to the base address of the region of pages whose access protection attributes are to be changed. - * @param RegionSize A pointer to a variable that specifies the size of the region whose access protection attributes are to be changed. - * @param NewProtection The memory protection option. This parameter can be one of the memory protection constants. - * @param OldProtection A pointer to a variable that receives the previous access protection of the first page in the specified region of pages. - * @return NTSTATUS Successful or errant status. + * \param ProcessHandle A handle to the process whose memory protection is to be changed. + * \param BaseAddress A pointer to the base address of the region of pages whose access protection attributes are to be changed. + * \param RegionSize A pointer to a variable that specifies the size of the region whose access protection attributes are to be changed. + * \param NewProtection The memory protection option. This parameter can be one of the memory protection constants. + * \param OldProtection A pointer to a variable that receives the previous access protection of the first page in the specified region of pages. + * \return NTSTATUS Successful or errant status. */ NTSYSCALLAPI NTSTATUS @@ -875,15 +878,15 @@ NtProtectVirtualMemory( ); /** - * Queries information about a region of virtual memory in a process. + * The NtQueryVirtualMemory routine queries information about a region of virtual memory in a process. * - * @param ProcessHandle A handle to the process whose memory information is to be queried. - * @param BaseAddress A pointer to the base address of the region of pages to be queried. - * @param MemoryInformationClass The type of information to be queried. - * @param MemoryInformation A pointer to a buffer that receives the memory information. - * @param MemoryInformationLength The size of the buffer pointed to by the MemoryInformation parameter. - * @param ReturnLength A pointer to a variable that receives the number of bytes returned in the MemoryInformation buffer. - * @return NTSTATUS Successful or errant status. + * \param ProcessHandle A handle to the process whose memory information is to be queried. + * \param BaseAddress A pointer to the base address of the region of pages to be queried. + * \param MemoryInformationClass The type of information to be queried. + * \param MemoryInformation A pointer to a buffer that receives the memory information. + * \param MemoryInformationLength The size of the buffer pointed to by the MemoryInformation parameter. + * \param ReturnLength A pointer to a variable that receives the number of bytes returned in the MemoryInformation buffer. + * \return NTSTATUS Successful or errant status. */ NTSYSCALLAPI NTSTATUS @@ -899,17 +902,17 @@ NtQueryVirtualMemory( // rev /** - * Queries information about a region of virtual memory in a 64-bit process from a 32-bit process. + * The NtWow64QueryVirtualMemory64 routine queries information about a region of virtual memory in a 64-bit process from a 32-bit process. * - * @param ProcessHandle A handle to the process whose memory information is to be queried. - * @param BaseAddress A pointer to the base address of the region of pages to be queried. - * @param MemoryInformationClass The type of information to be queried. - * @param MemoryInformation A pointer to a buffer that receives the memory information. - * @param MemoryInformationLength The size of the buffer pointed to by the MemoryInformation parameter. - * @param ReturnLength A pointer to a variable that receives the number of bytes returned in the MemoryInformation buffer. - * @return NTSTATUS Successful or errant status. + * \param ProcessHandle A handle to the process whose memory information is to be queried. + * \param BaseAddress A pointer to the base address of the region of pages to be queried. + * \param MemoryInformationClass The type of information to be queried. + * \param MemoryInformation A pointer to a buffer that receives the memory information. + * \param MemoryInformationLength The size of the buffer pointed to by the MemoryInformation parameter. + * \param ReturnLength A pointer to a variable that receives the number of bytes returned in the MemoryInformation buffer. + * \return NTSTATUS Successful or errant status. */ -NTSYSCALLAPI +NTSYSAPI NTSTATUS NTAPI NtWow64QueryVirtualMemory64( @@ -921,16 +924,14 @@ NtWow64QueryVirtualMemory64( _Out_opt_ PULONGLONG ReturnLength ); -typedef struct _IO_STATUS_BLOCK* PIO_STATUS_BLOCK; - /** - * Flushes the instruction cache for a specified process. + * The NtFlushVirtualMemory routine flushes the instruction cache for a specified process. * - * @param ProcessHandle A handle to the process whose instruction cache is to be flushed. - * @param BaseAddress A pointer to the base address of the region of memory to be flushed. - * @param RegionSize A pointer to a variable that specifies the size of the region to be flushed. - * @param IoStatus A pointer to an IO_STATUS_BLOCK structure that receives the status of the flush operation. - * @return NTSTATUS Successful or errant status. + * \param ProcessHandle A handle to the process whose instruction cache is to be flushed. + * \param BaseAddress A pointer to the base address of the memory region to be flushed. + * \param RegionSize A pointer to a variable that specifies the size of the region to be flushed. + * \param IoStatus A pointer to an IO_STATUS_BLOCK structure that receives the status of the flush operation. + * \return NTSTATUS Successful or errant status. */ NTSYSCALLAPI NTSTATUS @@ -942,22 +943,23 @@ NtFlushVirtualMemory( _Out_ PIO_STATUS_BLOCK IoStatus ); -#endif +#endif // (PHNT_MODE != PHNT_MODE_KERNEL) -// begin_private #if (PHNT_MODE != PHNT_MODE_KERNEL) +// begin_private typedef enum _VIRTUAL_MEMORY_INFORMATION_CLASS { - VmPrefetchInformation, // MEMORY_PREFETCH_INFORMATION - VmPagePriorityInformation, // MEMORY_PAGE_PRIORITY_INFORMATION - VmCfgCallTargetInformation, // CFG_CALL_TARGET_LIST_INFORMATION // REDSTONE2 - VmPageDirtyStateInformation, // REDSTONE3 - VmImageHotPatchInformation, // 19H1 - VmPhysicalContiguityInformation, // 20H1 + VmPrefetchInformation, // s: MEMORY_PREFETCH_INFORMATION + VmPagePriorityInformation, // s: MEMORY_PAGE_PRIORITY_INFORMATION + VmCfgCallTargetInformation, // s: CFG_CALL_TARGET_LIST_INFORMATION // REDSTONE2 + VmPageDirtyStateInformation, // s: MEMORY_PAGE_DIRTY_STATE_INFORMATION // REDSTONE3 + VmImageHotPatchInformation, // s: 19H1 + VmPhysicalContiguityInformation, // s: MEMORY_PHYSICAL_CONTIGUITY_INFORMATION // 20H1 // (requires SeLockMemoryPrivilege) VmVirtualMachinePrepopulateInformation, - VmRemoveFromWorkingSetInformation, + VmRemoveFromWorkingSetInformation, // s: MEMORY_REMOVE_WORKING_SET_INFORMATION MaxVmInfoClass } VIRTUAL_MEMORY_INFORMATION_CLASS; +// end_private #else #define VmPrefetchInformation 0x0 #define VmPagePriorityInformation 0x1 @@ -968,17 +970,25 @@ typedef enum _VIRTUAL_MEMORY_INFORMATION_CLASS #define VmVirtualMachinePrepopulateInformation 0x6 #define VmRemoveFromWorkingSetInformation 0x7 #define MaxVmInfoClass 0x8 -#endif +#endif // (PHNT_MODE != PHNT_MODE_KERNEL) #if (PHNT_MODE != PHNT_MODE_KERNEL) -typedef struct _MEMORY_RANGE_ENTRY -{ - PVOID VirtualAddress; - SIZE_T NumberOfBytes; -} MEMORY_RANGE_ENTRY, *PMEMORY_RANGE_ENTRY; +/** + * Attempt to populate specified single or multiple address ranges + * into the process working set (bring pages into physical memory). + */ #define VM_PREFETCH_TO_WORKING_SET 0x1 // since 24H4 +// rev +/** + * The MEMORY_PREFETCH_INFORMATION structure defines prefetch-control flags that + * determine how prefetch operations are executed on the supplied address ranges. + * + * \remarks The behavior and success of prefetch operations depend on OS policy, + * working set limits, privileges, and presence of backing storage. + * \sa NtSetInformationVirtualMemory, VIRTUAL_MEMORY_INFORMATION_CLASS, VmPrefetchInformation + */ typedef struct _MEMORY_PREFETCH_INFORMATION { ULONG Flags; @@ -1013,13 +1023,45 @@ typedef struct _CFG_CALL_TARGET_LIST_INFORMATION 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) +// rev +// VmPageDirtyStateInformation +typedef struct _MEMORY_PAGE_DIRTY_STATE_INFORMATION +{ + ULONG Flags; +} MEMORY_PAGE_DIRTY_STATE_INFORMATION, *PMEMORY_PAGE_DIRTY_STATE_INFORMATION; + +// rev +typedef struct _MEMORY_REMOVE_WORKING_SET_INFORMATION +{ + ULONG Flags; +} MEMORY_REMOVE_WORKING_SET_INFORMATION, *PMEMORY_REMOVE_WORKING_SET_INFORMATION; #if (PHNT_VERSION >= PHNT_WINDOWS_8) +/** + * The MEMORY_RANGE_ENTRY structure describes a contiguous region of virtual address space. + */ +typedef struct _MEMORY_RANGE_ENTRY +{ + PVOID VirtualAddress; // A pointer to the starting virtual address of the region. + SIZE_T NumberOfBytes; // The size, in bytes, of the region. +} MEMORY_RANGE_ENTRY, *PMEMORY_RANGE_ENTRY; +/** + * The NtSetInformationVirtualMemory routine performs an operation on a specified list of address ranges in the user address space of a process. + * + * \param ProcessHandle Specifies an open handle for the process in the context of which the operation is to be performed. This handle cannot be invalid. + * \param VmInformationClass Specifies the type of operation to perform. + * \param NumberOfEntries Number of entries in the array pointed to by the VirtualAddresses parameter. This parameter cannot be 0. + * \param VirtualAddresses Pointer to an array of MEMORY_RANGE_ENTRY structures in which each entry specifies a virtual address range to be processed. + * The virtual address ranges may cover any part of the process address space accessible by the target process. + * \param VmInformation A pointer to a buffer that contains memory information. + * Note: If VmInformationClass is VmPrefetchInformation, this parameter cannot be this parameter cannot be NULL and must point to a ULONG variable that is set to 0. + * \param VmInformationLength The size of the buffer pointed to by VmInformation. + * If VmInformationClass is VmPrefetchInformation, this must be sizeof (ULONG). + * \return NTSTATUS Successful or errant status. + * \sa https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/ntifs/nf-ntifs-zwsetinformationvirtualmemory + */ NTSYSCALLAPI NTSTATUS NTAPI @@ -1032,11 +1074,22 @@ NtSetInformationVirtualMemory( _In_ ULONG VmInformationLength ); -#endif +#endif // (PHNT_VERSION >= PHNT_WINDOWS_8) -#define MAP_PROCESS 1 -#define MAP_SYSTEM 2 +#define MAP_PROCESS 1 // Process WorkingSet +#define MAP_SYSTEM 2 // Physical Memory // (requires SeLockMemoryPrivilege) +/** + * The NtLockVirtualMemory routine locks the specified region of the process's virtual address space into physical memory, + * ensuring that subsequent access to the region will not incur a page fault. + * + * \param ProcessHandle A handle to the process whose virtual address space is to be locked. + * \param BaseAddress A pointer to the base address of the region of pages to be locked. + * \param RegionSize The size of the region to be locked, in bytes. The size is rounded up to the nearest multiple of PAGE_SIZE. + * \param MapType A bitmask containing one or more flags that specify the type of operations to be performed. + * \return NTSTATUS Successful or errant status. + * \sa https://learn.microsoft.com/en-us/windows/win32/api/memoryapi/nf-memoryapi-virtuallock + */ NTSYSCALLAPI NTSTATUS NTAPI @@ -1047,6 +1100,17 @@ NtLockVirtualMemory( _In_ ULONG MapType ); +/** + * The NtUnlockVirtualMemory routine unlocks a specified range of pages in the virtual address space of a process, + * enabling the system to swap the pages out to the paging file if necessary. + * + * \param ProcessHandle A handle to the process whose virtual address space is to be unlocked. + * \param BaseAddress A pointer to the base address of the region of pages to be unlocked. + * \param RegionSize The size of the region to be unlocked, in bytes. The size is rounded up to the nearest multiple of PAGE_SIZE. + * \param MapType A bitmask containing one or more flags that specify the type of operations to be performed. + * \return NTSTATUS Successful or errant status. + * \sa https://learn.microsoft.com/en-us/windows/win32/api/memoryapi/nf-memoryapi-virtualunlock + */ NTSYSCALLAPI NTSTATUS NTAPI @@ -1057,12 +1121,137 @@ NtUnlockVirtualMemory( _In_ ULONG MapType ); -#endif +#endif // (PHNT_MODE != PHNT_MODE_KERNEL) +// // Sections +// + +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, // q; SECTION_INTERNAL_IMAGE_INFORMATION // since REDSTONE2 + MaxSectionInfoClass +} SECTION_INFORMATION_CLASS; + +/** + * The SECTION_BASIC_INFORMATION structure contains basic information about an image section. + * \sa https://learn.microsoft.com/en-us/windows/win32/devnotes/ntquerysection + */ +typedef struct _SECTION_BASIC_INFORMATION +{ + PVOID BaseAddress; // The base virtual address of the section if the section is based. + ULONG AllocationAttributes; // The allocation attributes flags. + LARGE_INTEGER MaximumSize; // The maximum size of the section in bytes. +} SECTION_BASIC_INFORMATION, *PSECTION_BASIC_INFORMATION; + +/** + * The SECTION_IMAGE_INFORMATION structure contains detailed information about an image section. + */ +typedef struct _SECTION_IMAGE_INFORMATION +{ + PVOID TransferAddress; // The address of the image entry point function. + ULONG ZeroBits; // The number of high-order address bits that must be zero in the image base address. + SIZE_T MaximumStackSize; // The maximum stack size of threads from the PE file header. + SIZE_T CommittedStackSize; // The initial stack size of threads from the PE file header. + ULONG SubSystemType; // The image subsystem from the PE file header (e.g., Windows GUI, Windows CUI, POSIX). + union + { + struct + { + USHORT SubSystemMinorVersion; + USHORT SubSystemMajorVersion; + }; + ULONG SubSystemVersion; + }; + union + { + struct + { + USHORT MajorOperatingSystemVersion; + USHORT MinorOperatingSystemVersion; + }; + ULONG OperatingSystemVersion; + }; + USHORT ImageCharacteristics; // The image characteristics from the PE file header. + USHORT DllCharacteristics; // The DLL characteristics flags (e.g., ASLR, NX compatibility). + USHORT Machine; // The image architecture (e.g., x86, x64, ARM). + BOOLEAN ImageContainsCode; // The image contains native executable code. + union + { + UCHAR ImageFlags; + struct + { + UCHAR ComPlusNativeReady : 1; // The image contains precompiled .NET assembly generated by NGEN (Native Image Generator). + UCHAR ComPlusILOnly : 1; // the image contains only Microsoft Intermediate Language (IL) assembly. + UCHAR ImageDynamicallyRelocated : 1; // The image was mapped using a random base address rather than the preferred base address. + UCHAR ImageMappedFlat : 1; // The image was mapped using a single contiguous region, rather than separate regions for each section. + UCHAR BaseBelow4gb : 1; // The image was mapped using a base address below the 4 GB boundary. + UCHAR ComPlusPrefer32bit : 1; // The image prefers to run as a 32-bit process, even on a 64-bit system. + UCHAR Reserved : 2; + }; + }; + ULONG LoaderFlags; // Reserved by ntdll.dll for the Windows loader. + ULONG ImageFileSize; // The size of the image, in bytes, including all headers. + ULONG CheckSum; // The image file checksum, from the PE optional header. +} SECTION_IMAGE_INFORMATION, *PSECTION_IMAGE_INFORMATION; + +/** + * The SECTION_INTERNAL_IMAGE_INFORMATION structure contains information about Control Flow Guard (CFG) features required by the image section. + */ +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 ImageExportSuppressionInfoPresent : 1; + ULONG ImageCfgEnabled : 1; + ULONG Reserved : 22; + }; + }; +} SECTION_INTERNAL_IMAGE_INFORMATION, *PSECTION_INTERNAL_IMAGE_INFORMATION; #if (PHNT_MODE != PHNT_MODE_KERNEL) +/** + * The SECTION_INHERIT structure specifies how the mapped view of the section is to be shared with child processes. + */ +typedef enum _SECTION_INHERIT +{ + ViewShare = 1, // The mapped view of the section will be mapped into any child processes created by the process. + ViewUnmap = 2 // The mapped view of the section will not be mapped into any child processes created by the process. +} SECTION_INHERIT; +#endif // (PHNT_MODE != PHNT_MODE_KERNEL) +#if (PHNT_MODE != PHNT_MODE_KERNEL) +/** + * The NtCreateSection routine creates a section object. + * + * \param SectionHandle Pointer to a variable that receives a handle to the section object. + * \param DesiredAccess The access mask that specifies the requested access to the section object. + * \param ObjectAttributes Pointer to the base virtual address of the view to unmap. This value can be any virtual address within the view. + * \param MaximumSize The maximum size, in bytes, of the section. The actual size when backed by the paging file, + * or the maximum the file can be extended or mapped when backed by an ordinary file. + * \param SectionPageProtection Specifies the protection to place on each page in the section. + * \param AllocationAttributes A bitmask of SEC_XXX flags that determines the allocation attributes of the section. + * \param FileHandle Optionally specifies a handle for an open file object. If the value of FileHandle is NULL, + * the section is backed by the paging file. Otherwise, the section is backed by the specified file. + * \return NTSTATUS Successful or errant status. + * \sa https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/wdm/nf-wdm-zwcreatesection + */ NTSYSCALLAPI NTSTATUS NTAPI @@ -1077,6 +1266,23 @@ NtCreateSection( ); #if (PHNT_VERSION >= PHNT_WINDOWS_10_RS5) +/** + * The NtCreateSectionEx routine creates a section object. + * + * \param SectionHandle Pointer to a variable that receives a handle to the section object. + * \param DesiredAccess The access mask that specifies the requested access to the section object. + * \param ObjectAttributes Pointer to the base virtual address of the view to unmap. This value can be any virtual address within the view. + * \param MaximumSize The maximum size, in bytes, of the section. The actual size when backed by the paging file, + * or the maximum the file can be extended or mapped when backed by an ordinary file. + * \param SectionPageProtection Specifies the protection to place on each page in the section. + * \param AllocationAttributes A bitmask of SEC_XXX flags that determines the allocation attributes of the section. + * \param FileHandle Optionally specifies a handle for an open file object. If the value of FileHandle is NULL, + * the section is backed by the paging file. Otherwise, the section is backed by the specified file. + * \param ExtendedParameters An optional pointer to one or more extended parameters of type MEM_EXTENDED_PARAMETER. + * \param ExtendedParameterCount Specifies the number of elements in the ExtendedParameters array. + * \return NTSTATUS Successful or errant status. + * \sa https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/wdm/nf-wdm-zwcreatesection + */ NTSYSCALLAPI NTSTATUS NTAPI @@ -1091,8 +1297,17 @@ NtCreateSectionEx( _Inout_updates_opt_(ExtendedParameterCount) PMEM_EXTENDED_PARAMETER ExtendedParameters, _In_ ULONG ExtendedParameterCount ); -#endif +#endif // (PHNT_VERSION >= PHNT_WINDOWS_10_RS5) +/** + * The NtOpenSection routine opens a handle for an existing section object. + * + * \param SectionHandle Handle to a process object that was previously passed to NtMapViewOfSection. + * \param DesiredAccess The access mask that specifies the requested access to the section object. + * \param ObjectAttributes Pointer to an OBJECT_ATTRIBUTES structure that specifies the object name and other attributes. + * \return NTSTATUS Successful or errant status. + * \sa https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/wdm/nf-wdm-zwopensection + */ NTSYSCALLAPI NTSTATUS NTAPI @@ -1102,6 +1317,22 @@ NtOpenSection( _In_ PCOBJECT_ATTRIBUTES ObjectAttributes ); +/** + * The NtMapViewOfSection routine maps a view of a section into the virtual address space of a subject process. + * + * \param SectionHandle A handle to an existing section object. + * \param ProcessHandle A handle to the object that represents the process that the view should be mapped into. The handle must have been opened with PROCESS_VM_OPERATION access. + * \param BaseAddress A pointer to a variable that receives the base address of the view. If the value is not NULL, the view is allocated starting at the specified virtual address rounded down to the next 64-kilobyte address boundary. + * \param ZeroBits The number of high-order address bits that must be zero in the base address of the section view. The value of this parameter must be less than 21 and is used only if BaseAddress is NULL. + * \param CommitSize Specifies the size, in bytes, of the initially committed region of the view. CommitSize is meaningful only for page-file backed sections and is rounded up to the nearest multiple of PAGE_SIZE. + * \param SectionOffset A pointer to a variable that receives the offset, in bytes, from the beginning of the section to the view. + * \param ViewSize A pointer to a variable that specifies the size of the view in bytes. If the initial value is zero, NtMapViewOfSection maps a view of the section that starts at SectionOffset and continues to the end of the section. + * \param InheritDisposition A value that specifies how the view is to be shared with child processes. + * \param AllocationType Specifies the type of allocation to be performed for the specified region of pages. The valid flags are MEM_RESERVE, MEM_TOP_DOWN, MEM_LARGE_PAGES, MEM_DIFFERENT_IMAGE_BASE_OK and MEM_REPLACE_PLACEHOLDER. Although MEM_COMMIT is not allowed, it is implied unless MEM_RESERVE is specified. + * \param PageProtection Specifies the page protection to be applied to the mapped view. Not used with SEC_IMAGE, must be set to PAGE_READONLY for SEC_IMAGE_NO_EXECUTE. For non-image sections, the value must be compatible with the section's page protection from NtCreateSection. + * \return NTSTATUS Successful or errant status. + * \sa https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/wdm/nf-wdm-zwmapviewofsection + */ NTSYSCALLAPI NTSTATUS NTAPI @@ -1119,6 +1350,21 @@ NtMapViewOfSection( ); #if (PHNT_VERSION >= PHNT_WINDOWS_10_RS5) +/** + * The NtMapViewOfSectionEx routine maps a view of a section into the virtual address space of a subject process. + * + * \param SectionHandle A handle to an existing section object. + * \param ProcessHandle A handle to the object that represents the process that the view should be mapped into. The handle must have been opened with PROCESS_VM_OPERATION access. + * \param BaseAddress A pointer to a variable that receives the base address of the view. If the value is not NULL, the view is allocated starting at the specified virtual address rounded down to the next 64-kilobyte address boundary. + * \param SectionOffset A pointer to a variable that receives the offset, in bytes, from the beginning of the section to the view. + * \param ViewSize A pointer to a variable that specifies the size of the view in bytes. If the initial value is zero, NtMapViewOfSection maps a view of the section that starts at SectionOffset and continues to the end of the section. + * \param AllocationType Specifies the type of allocation to be performed for the specified region of pages. The valid flags are MEM_RESERVE, MEM_TOP_DOWN, MEM_LARGE_PAGES, MEM_DIFFERENT_IMAGE_BASE_OK and MEM_REPLACE_PLACEHOLDER. Although MEM_COMMIT is not allowed, it is implied unless MEM_RESERVE is specified. + * \param PageProtection Specifies the page protection to be applied to the mapped view. Not used with SEC_IMAGE, must be set to PAGE_READONLY for SEC_IMAGE_NO_EXECUTE. For non-image sections, the value must be compatible with the section's page protection from NtCreateSection. + * \param ExtendedParameters An optional pointer to one or more extended parameters of type MEM_EXTENDED_PARAMETER. + * \param ExtendedParameterCount Specifies the number of elements in the ExtendedParameters array. + * \return NTSTATUS Successful or errant status. + * \sa https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/wdm/nf-wdm-zwmapviewofsectionex + */ NTSYSCALLAPI NTSTATUS NTAPI @@ -1133,8 +1379,16 @@ NtMapViewOfSectionEx( _Inout_updates_opt_(ExtendedParameterCount) PMEM_EXTENDED_PARAMETER ExtendedParameters, _In_ ULONG ExtendedParameterCount ); -#endif +#endif // (PHNT_VERSION >= PHNT_WINDOWS_10_RS5) +/** + * The NtUnmapViewOfSection routine unmaps a view of a section from the virtual address space of a subject process. + * + * \param ProcessHandle Handle to a process object that was previously passed to NtMapViewOfSection. + * \param BaseAddress Pointer to the base virtual address of the view to unmap. This value can be any virtual address within the view. + * \return NTSTATUS Successful or errant status. + * \sa https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/wdm/nf-wdm-zwunmapviewofsection + */ NTSYSCALLAPI NTSTATUS NTAPI @@ -1144,6 +1398,15 @@ NtUnmapViewOfSection( ); #if (PHNT_VERSION >= PHNT_WINDOWS_8) +/** + * The NtUnmapViewOfSectionEx routine unmaps a view of a section from the virtual address space of a subject process. + * + * \param ProcessHandle Handle to a process object that was previously passed to NtMapViewOfSection. + * \param BaseAddress Pointer to the base virtual address of the view to unmap. This value can be any virtual address within the view. + * \param Flags Additional flags for the unmap operation. + * \return NTSTATUS Successful or errant status. + * \sa https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/wdm/nf-wdm-zwunmapviewofsection + */ NTSYSCALLAPI NTSTATUS NTAPI @@ -1152,7 +1415,7 @@ NtUnmapViewOfSectionEx( _In_opt_ PVOID BaseAddress, _In_ ULONG Flags ); -#endif +#endif // (PHNT_VERSION >= PHNT_WINDOWS_8) NTSYSCALLAPI NTSTATUS @@ -1162,6 +1425,17 @@ NtExtendSection( _Inout_ PLARGE_INTEGER NewSectionSize ); +/** + * The NtQuerySection routine provides the capability to determine the base address, size, granted access, and allocation of an opened section object. + * + * \param SectionHandle An open handle to a section object. + * \param SectionInformationClass The section information class about which to retrieve information. + * \param SectionInformation A pointer to a buffer that receives the specified information. The format and content of the buffer depend on the specified section class. + * \param SectionInformationLength Specifies the length in bytes of the section information buffer. + * \param ReturnLength An optional pointer which, if specified, receives the number of bytes placed in the section information buffer. + * \return NTSTATUS Successful or errant status. + * \sa https://learn.microsoft.com/en-us/windows/win32/devnotes/ntquerysection + */ NTSYSCALLAPI NTSTATUS NTAPI @@ -1173,6 +1447,13 @@ NtQuerySection( _Out_opt_ PSIZE_T ReturnLength ); +/** + * The NtAreMappedFilesTheSame routine determines whether two mapped files are the same. + * + * \param File1MappedAsAnImage A pointer to the base address of the first file mapped as an image. + * \param File2MappedAsFile A pointer to the base address of the second file mapped as a file. + * \return NTSTATUS Returns STATUS_SUCCESS if the files are the same; otherwise, an appropriate NTSTATUS error code. + */ NTSYSCALLAPI NTSTATUS NTAPI @@ -1181,7 +1462,7 @@ NtAreMappedFilesTheSame( _In_ PVOID File2MappedAsFile ); -#endif +#endif // (PHNT_MODE != PHNT_MODE_KERNEL) // // Memory Partitions @@ -1189,22 +1470,22 @@ NtAreMappedFilesTheSame( #ifndef MEMORY_CURRENT_PARTITION_HANDLE #define MEMORY_CURRENT_PARTITION_HANDLE ((HANDLE)(LONG_PTR)-1) -#endif +#endif // MEMORY_CURRENT_PARTITION_HANDLE #ifndef MEMORY_SYSTEM_PARTITION_HANDLE #define MEMORY_SYSTEM_PARTITION_HANDLE ((HANDLE)(LONG_PTR)-2) -#endif +#endif // MEMORY_SYSTEM_PARTITION_HANDLE #ifndef MEMORY_EXISTING_VAD_PARTITION_HANDLE #define MEMORY_EXISTING_VAD_PARTITION_HANDLE ((HANDLE)(LONG_PTR)-3) -#endif +#endif // MEMORY_EXISTING_VAD_PARTITION_HANDLE #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 +#endif // MEMORY_PARTITION_QUERY_ACCESS #if (PHNT_MODE != PHNT_MODE_KERNEL) // private @@ -1244,7 +1525,7 @@ typedef enum _PARTITION_INFORMATION_CLASS #define SystemMemoryPartitionSetMemoryThresholds 0xD #define SystemMemoryPartitionMemoryListCommand 0xE #define SystemMemoryPartitionMax 0xF -#endif +#endif // (PHNT_MODE != PHNT_MODE_KERNEL) // private typedef struct _MEMORY_PARTITION_CONFIGURATION_INFORMATION @@ -1331,7 +1612,6 @@ typedef struct _MEMORY_PARTITION_MEMORY_EVENTS_INFORMATION } MEMORY_PARTITION_MEMORY_EVENTS_INFORMATION, *PMEMORY_PARTITION_MEMORY_EVENTS_INFORMATION; #if (PHNT_MODE != PHNT_MODE_KERNEL) - #if (PHNT_VERSION >= PHNT_WINDOWS_10) NTSYSCALLAPI @@ -1341,8 +1621,7 @@ NtCreatePartition( _In_opt_ HANDLE ParentPartitionHandle, _Out_ PHANDLE PartitionHandle, _In_ ACCESS_MASK DesiredAccess, - _In_opt_ PCOBJECT_ATTRIBUTES ObjectAttributes, - _In_ ULONG PreferredNode + _In_opt_ PCOBJECT_ATTRIBUTES ObjectAttributes ); NTSYSCALLAPI @@ -1365,14 +1644,21 @@ NtManagePartition( _In_ ULONG PartitionInformationLength ); -#endif - -#endif +#endif // (PHNT_VERSION >= PHNT_WINDOWS_10) +// // User physical pages +// -#if (PHNT_MODE != PHNT_MODE_KERNEL) - +/** + * Maps previously allocated physical memory pages at a specified address in an Address Windowing Extensions (AWE) region. + * + * \param VirtualAddress A pointer to the starting address of the region of memory to remap. The value of VirtualAddress must be within the address range that the VirtualAlloc function returns when the Address Windowing Extensions (AWE) region is allocated. + * \param NumberOfPages The size of the physical memory and virtual address space for which to establish translations, in pages. + * \param UserPfnArray A pointer to an array of physical page frame numbers. + * \return NTSTATUS Successful or errant status. + * \sa https://learn.microsoft.com/en-us/windows/win32/api/memoryapi/nf-memoryapi-mapuserphysicalpages + */ NTSYSCALLAPI NTSTATUS NTAPI @@ -1382,6 +1668,15 @@ NtMapUserPhysicalPages( _In_reads_opt_(NumberOfPages) PULONG_PTR UserPfnArray ); +/** + * Maps previously allocated physical memory pages at a specified address in an Address Windowing Extensions (AWE) region. + * + * \param VirtualAddresses A pointer to an array of starting addresses of the regions of memory to remap. The value of VirtualAddress must be within the address range that the VirtualAlloc function returns when the Address Windowing Extensions (AWE) region is allocated. + * \param NumberOfPages The size of the physical memory and virtual address space for which to establish translations, in pages. + * \param UserPfnArray A pointer to an array of values that indicates how each corresponding page in VirtualAddresses should be treated. A 0 (zero) indicates the entry should be unmapped, and any nonzero value should be mapped. + * \return NTSTATUS Successful or errant status. + * \sa https://learn.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-mapuserphysicalpagesscatter + */ NTSYSCALLAPI NTSTATUS NTAPI @@ -1391,6 +1686,15 @@ NtMapUserPhysicalPagesScatter( _In_reads_opt_(NumberOfPages) PULONG_PTR UserPfnArray ); +/** + * Allocates physical memory pages to be mapped and unmapped within any Address Windowing Extensions (AWE) region of a specified process. + * + * \param ProcessHandle A handle to the process whose physical memory pages are to be allocated within the virtual address space of this process. + * \param NumberOfPages The size of the physical memory to allocate, in pages. + * \param UserPfnArray A pointer to an array to store the page frame numbers of the allocated memory. Do not attempt to modify this buffer. It contains operating system data, and corruption could be catastrophic. The information in the buffer is not useful to an application. + * \return NTSTATUS Successful or errant status. + * \sa https://learn.microsoft.com/en-us/windows/win32/api/memoryapi/nf-memoryapi-allocateuserphysicalpages + */ NTSYSCALLAPI NTSTATUS NTAPI @@ -1401,6 +1705,17 @@ NtAllocateUserPhysicalPages( ); #if (PHNT_VERSION >= PHNT_WINDOWS_10) +/** + * Allocates physical memory pages to be mapped and unmapped within any Address Windowing Extensions (AWE) region of a specified process, with extended parameters. + * + * \param ProcessHandle A handle to the process whose physical memory pages are to be allocated within the virtual address space of this process. + * \param NumberOfPages The size of the physical memory to allocate, in pages. + * \param UserPfnArray A pointer to an array to store the page frame numbers of the allocated memory. Do not attempt to modify this buffer. It contains operating system data, and corruption could be catastrophic. The information in the buffer is not useful to an application. + * \param ExtendedParameters Pointer to an array of MEM_EXTENDED_PARAMETER structures. + * \param ExtendedParameterCount The number of MEM_EXTENDED_PARAMETER in the ExtendedParameters array. + * \return NTSTATUS Successful or errant status. + * \sa https://learn.microsoft.com/en-us/windows/win32/api/memoryapi/nf-memoryapi-allocateuserphysicalpages + */ NTSYSCALLAPI NTSTATUS NTAPI @@ -1411,8 +1726,17 @@ NtAllocateUserPhysicalPagesEx( _Inout_updates_opt_(ExtendedParameterCount) PMEM_EXTENDED_PARAMETER ExtendedParameters, _In_ ULONG ExtendedParameterCount ); -#endif +#endif // (PHNT_VERSION >= PHNT_WINDOWS_10) +/** + * Frees physical memory pages that are allocated previously by using NtAllocateUserPhysicalPages. + * + * \param ProcessHandle A handle to the process. The function frees memory within the virtual address space of this process. + * \param NumberOfPages The size of the physical memory to free, in pages. On return, if the function fails, this parameter indicates the number of pages that are freed. + * \param UserPfnArray A pointer to an array of page frame numbers of the allocated memory to be freed. + * \return NTSTATUS Successful or errant status. + * \sa https://learn.microsoft.com/en-us/windows/win32/api/memoryapi/nf-memoryapi-freeuserphysicalpages + */ NTSYSCALLAPI NTSTATUS NTAPI @@ -1422,26 +1746,22 @@ NtFreeUserPhysicalPages( _In_reads_(*NumberOfPages) PULONG_PTR UserPfnArray ); -#endif - // // Misc. // -#if (PHNT_MODE != PHNT_MODE_KERNEL) - /** * Retrieves the addresses of the pages that are written to in a region of virtual memory. * - * @param ProcessHandle A handle to the process whose watch information is to be queried. - * @param Flags Additional flags for the operation. To reset the write-tracking state, set this parameter to WRITE_WATCH_FLAG_RESET. Otherwise, set this parameter to zero. - * @param BaseAddress The base address of the memory region for which to retrieve write-tracking information. This address must a region that is allocated using MEM_WRITE_WATCH. - * @param RegionSize The size of the memory region for which to retrieve write-tracking information, in bytes. - * @param UserAddressArray A pointer to a buffer that receives an array of page addresses that have been written to since the region has been allocated or the write-tracking state has been reset. - * @param EntriesInUserAddressArray On input, this variable indicates the size of the UserAddressArray array. On output, the variable receives the number of page addresses that are returned in the array. - * @param Granularity A pointer to a variable that receives the page size, in bytes. - * @return NTSTATUS Successful or errant status. - * @see https://learn.microsoft.com/en-us/windows/win32/api/memoryapi/nf-memoryapi-getwritewatch + * \param ProcessHandle A handle to the process whose watch information is to be queried. + * \param Flags Additional flags for the operation. To reset the write-tracking state, set this parameter to WRITE_WATCH_FLAG_RESET. Otherwise, set this parameter to zero. + * \param BaseAddress The base address of the memory region for which to retrieve write-tracking information. This address must a region that is allocated using MEM_WRITE_WATCH. + * \param RegionSize The size of the memory region for which to retrieve write-tracking information, in bytes. + * \param UserAddressArray A pointer to a buffer that receives an array of page addresses that have been written to since the region has been allocated or the write-tracking state has been reset. + * \param EntriesInUserAddressArray On input, this variable indicates the size of the UserAddressArray array. On output, the variable receives the number of page addresses that are returned in the array. + * \param Granularity A pointer to a variable that receives the page size, in bytes. + * \return NTSTATUS Successful or errant status. + * \see https://learn.microsoft.com/en-us/windows/win32/api/memoryapi/nf-memoryapi-getwritewatch */ NTSYSCALLAPI NTSTATUS @@ -1459,11 +1779,11 @@ NtGetWriteWatch( /** * Resets the write-tracking state for a region of virtual memory. * - * @param ProcessHandle A handle to the process whose watch information is to be reset. - * @param BaseAddress A pointer to the base address of the memory region for which to reset the write-tracking state. - * @param RegionSize The size of the memory region for which to reset the write-tracking information, in bytes. - * @return NTSTATUS Successful or errant status. - * @see https://learn.microsoft.com/en-us/windows/win32/api/memoryapi/nf-memoryapi-resetwritewatch + * \param ProcessHandle A handle to the process whose watch information is to be reset. + * \param BaseAddress A pointer to the base address of the memory region for which to reset the write-tracking state. + * \param RegionSize The size of the memory region for which to reset the write-tracking information, in bytes. + * \return NTSTATUS Successful or errant status. + * \see https://learn.microsoft.com/en-us/windows/win32/api/memoryapi/nf-memoryapi-resetwritewatch */ NTSYSCALLAPI NTSTATUS @@ -1474,25 +1794,50 @@ NtResetWriteWatch( _In_ SIZE_T RegionSize ); +/** + * Creates or extends a paging file. + * + * \param PageFileName The NT path of the paging file to create or extend. + * \param MinimumSize A pointer to the minimum size of the paging file, in bytes. + * \param MaximumSize A pointer to the maximum size of the paging file, in bytes. + * \param Priority The paging file priority. + * \return NTSTATUS Successful or errant status. + * \remarks The caller must have the SeCreatePagefilePrivilege privilege. + */ NTSYSCALLAPI NTSTATUS NTAPI NtCreatePagingFile( - _In_ PUNICODE_STRING PageFileName, + _In_ PCUNICODE_STRING PageFileName, _In_ PLARGE_INTEGER MinimumSize, _In_ PLARGE_INTEGER MaximumSize, _In_ ULONG Priority ); +/** + * Flushes the instruction cache for the specified process. + * + * \param ProcessHandle A handle to the process whose instruction cache is to be flushed. + * \param BaseAddress A pointer to the base address of the memory region to be flushed. This parameter can be NULL. + * \param RegionSize The size of the memory region to be flushed, in bytes. + * \return NTSTATUS Successful or errant status. + * \remarks Applications should call NtFlushInstructionCache if they generate or modify code in memory. The CPU cannot detect the change, and may execute the old code it cached. + * \see https://learn.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-flushinstructioncache + */ NTSYSCALLAPI NTSTATUS NTAPI NtFlushInstructionCache( _In_ HANDLE ProcessHandle, _In_opt_ PVOID BaseAddress, - _In_ SIZE_T Length + _In_ SIZE_T RegionSize ); +/** + * The NtFlushWriteBuffer routine flushes the write queue of the current processor that is running a thread of the current process. + * + * \return NTSTATUS Successful or errant status. + */ NTSYSCALLAPI NTSTATUS NTAPI @@ -1500,7 +1845,20 @@ NtFlushWriteBuffer( VOID ); -#endif +/** + * The NtFlushProcessWriteBuffers routine flushes the write queue of each processor that is running a thread of the current process. + * + * \return NTSTATUS Successful or errant status. + * \see https://learn.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-flushprocesswritebuffers + */ +NTSYSCALLAPI +NTSTATUS +NTAPI +NtFlushProcessWriteBuffers( + VOID + ); + +#endif // (PHNT_MODE != PHNT_MODE_KERNEL) // // Enclave support @@ -1508,6 +1866,24 @@ NtFlushWriteBuffer( #if (PHNT_VERSION >= PHNT_WINDOWS_10) +/** + * Creates a new uninitialized enclave. An enclave is an isolated region of code and data within the address space for an application. + * Only code that runs within the enclave can access data within the same enclave. + * + * \param ProcessHandle A handle to the process for which you want to create an enclave. + * \param BaseAddress The preferred base address of the enclave. Specify NULL to have the operating system assign the base address. + * \param ZeroBits The number of high-order address bits that must be zero in the base address of the section view. This value must be less than 21 and the initial value of BaseAddress must be zero. + * \param Size The size of the enclave that you want to create, including the size of the code that you will load into the enclave, in bytes. VBS enclaves must be a multiple of 2 MB in size. + * SGX enclaves must be a power of 2 in size and must have their base aligned to the same power of 2 as the size, with a minimum alignment of 2 MB. As an example, if the enclave is 128 MB, then its base must be aligned to a 128 MB boundary. + * \param InitialCommitment The amount of memory to commit for the enclave, in bytes. + * \param EnclaveType The architecture type of the enclave that you want to create. To verify that an enclave type is supported, call IsEnclaveTypeSupported. + * \param EnclaveInformation A pointer to the architecture-specific information to use to create the enclave. + * \param EnclaveInformationLength The length of the structure that the EnclaveInformation parameter points to, in bytes. + * For the ENCLAVE_TYPE_SGX and ENCLAVE_TYPE_SGX2 enclave types, this value must be 4096. For the ENCLAVE_TYPE_VBS enclave type, this value must be sizeof(ENCLAVE_CREATE_INFO_VBS), which is 36 bytes. + * \param EnclaveError An optional pointer to a variable that receives an enclave error code that is architecture-specific. + * \return NTSTATUS Successful or errant status. + * \see https://learn.microsoft.com/en-us/windows/win32/api/enclaveapi/nf-enclaveapi-createenclave + */ NTSYSCALLAPI NTSTATUS NTAPI @@ -1523,6 +1899,21 @@ NtCreateEnclave( _Out_opt_ PULONG EnclaveError ); +/** + * Loads data into an uninitialized enclave that you created by calling NtCreateEnclave. + * + * \param ProcessHandle A handle to the process for which the enclave was created. + * \param BaseAddress The address in the enclave where you want to load the data. + * \param Buffer A pointer to the data the you want to load into the enclave. + * \param BufferSize The size of the data that you want to load into the enclave, in bytes. This value must be a whole-number multiple of the page size. + * \param Protect The memory protection to use for the pages that you want to add to the enclave. + * \param PageInformation A pointer to information that describes the pages that you want to add to the enclave. + * \param PageInformationLength The length of the structure that the PageInformation parameter points to, in bytes. + * \param NumberOfBytesWritten A pointer to a variable that receives the number of bytes that NtLoadEnclaveData copied into the enclave. + * \param EnclaveError An optional pointer to a variable that receives an enclave error code that is architecture-specific. + * \return NTSTATUS Successful or errant status. + * \see https://learn.microsoft.com/en-us/windows/win32/api/enclaveapi/nf-enclaveapi-loadenclavedata + */ NTSYSCALLAPI NTSTATUS NTAPI @@ -1538,6 +1929,17 @@ NtLoadEnclaveData( _Out_opt_ PULONG EnclaveError ); +/** + * Initializes an enclave that you created and loaded with data. + * + * \param ProcessHandle A handle to the process for which the enclave was created. + * \param BaseAddress Any address within the enclave. + * \param EnclaveInformation A pointer to architecture-specific information to use to initialize the enclave. + * \param EnclaveInformationLength The length of the structure that the EnclaveInformation parameter points to, in bytes. + * \param EnclaveError An optional pointer to a variable that receives an enclave error code that is architecture-specific. + * \return NTSTATUS Successful or errant status. + * \see https://learn.microsoft.com/en-us/windows/win32/api/enclaveapi/nf-enclaveapi-initializeenclave + */ NTSYSCALLAPI NTSTATUS NTAPI @@ -1555,6 +1957,14 @@ NtInitializeEnclave( #define TERMINATE_ENCLAVE_FLAG_WAIT_ERROR 0x00000004ul // STATUS_PENDING -> STATUS_ENCLAVE_NOT_TERMINATED // rev +/** + * Ends the execution of the threads that are running within an enclave. + * + * \param BaseAddress The base address of the enclave in which to end the execution of the threads. + * \param Flags Additional flags for the termination operation. + * \return NTSTATUS Successful or errant status. + * \see https://learn.microsoft.com/en-us/windows/win32/api/enclaveapi/nf-enclaveapi-terminateenclave + */ NTSYSCALLAPI NTSTATUS NTAPI @@ -1564,23 +1974,32 @@ NtTerminateEnclave( ); #if (PHNT_MODE != PHNT_MODE_KERNEL) - // rev #define ENCLAVE_CALL_VALID_FLAGS 0x00000001ul #define ENCLAVE_CALL_FLAG_NO_WAIT 0x00000001ul // rev +/** + * Calls a function within an enclave. NtCallEnclave can also be called within an enclave to call a function outside of the enclave. + * + * \param Routine The address of the function that you want to call. + * \param Reserved Reserved for dispatch (RtlEnclaveCallDispatch) + * \param Flags Additional flags for the call operation. + * \param RoutineParamReturn The parameter than you want to pass to the function and return value of the function. + * \return NTSTATUS Successful or errant status. + * \see https://learn.microsoft.com/en-us/windows/win32/api/enclaveapi/nf-enclaveapi-callenclave + */ NTSYSCALLAPI NTSTATUS NTAPI NtCallEnclave( _In_ PENCLAVE_ROUTINE Routine, - _In_ PVOID Reserved, // reserved for dispatch (RtlEnclaveCallDispatch) + _In_ PVOID Reserved, // SelectVsmEnclaveByNumber > 0 // reserved for dispatch (RtlEnclaveCallDispatch) _In_ ULONG Flags, // ENCLAVE_CALL_FLAG_* _Inout_ PVOID* RoutineParamReturn // input routine parameter, output routine return value ); -#endif +#endif // (PHNT_MODE != PHNT_MODE_KERNEL) -#endif +#endif // (PHNT_VERSION >= PHNT_WINDOWS_10) -#endif +#endif // _NTMMAPI_H diff --git a/ntnls.h b/ntnls.h index 6babac8..065a64f 100644 --- a/ntnls.h +++ b/ntnls.h @@ -9,34 +9,48 @@ #define MAXIMUM_LEADBYTES 12 +/** + * Stores the NLS file formats. + * + * \sa https://learn.microsoft.com/en-us/previous-versions/mt791523(v=vs.85) + */ 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; + USHORT CodePage; // Specifies the code page number. + USHORT MaximumCharacterSize; // Specifies the maximum length in bytes of a character. + USHORT DefaultChar; // Specifies the default character (MB). + USHORT UniDefaultChar; // Specifies the default character (Unicode). + USHORT TransDefaultChar; // Specifies the translation of the default character (Unicode). + USHORT TransUniDefaultChar; // Specifies the translation of the Unicode default character (MB). + USHORT DBCSCodePage; // Specifies non-zero for DBCS code pages. + UCHAR LeadByte[MAXIMUM_LEADBYTES]; // Specifies the lead byte ranges. + PUSHORT MultiByteTable; // Specifies a pointer to a MB translation table. + PVOID WideCharTable; // Specifies a pointer to a WC translation table. + PUSHORT DBCSRanges; // Specifies a pointer to DBCS ranges. + PUSHORT DBCSOffsets; // Specifies a pointer to DBCS offsets. } CPTABLEINFO, *PCPTABLEINFO; +/** + * Stores the NLS file formats. + * + * \sa https://learn.microsoft.com/en-us/previous-versions/mt791531(v=vs.85) + */ typedef struct _NLSTABLEINFO { - CPTABLEINFO OemTableInfo; - CPTABLEINFO AnsiTableInfo; - PUSHORT UpperCaseTable; - PUSHORT LowerCaseTable; + CPTABLEINFO OemTableInfo; // Specifies OEM table. + CPTABLEINFO AnsiTableInfo; // Specifies an ANSI table. + PUSHORT UpperCaseTable; // Specifies an 844 format uppercase table. + PUSHORT LowerCaseTable; // Specifies an 844 format lowercase table. } NLSTABLEINFO, *PNLSTABLEINFO; +// +// Data exports (ntdll.lib/ntdllp.lib) +// + #if (PHNT_MODE != PHNT_MODE_KERNEL) NTSYSAPI USHORT NlsAnsiCodePage; NTSYSAPI BOOLEAN NlsMbCodePageTag; NTSYSAPI BOOLEAN NlsMbOemCodePageTag; -#endif +#endif // (PHNT_MODE != PHNT_MODE_KERNEL) -#endif +#endif // _NTNLS_H diff --git a/ntobapi.h b/ntobapi.h index 18a8d50..d26e66a 100644 --- a/ntobapi.h +++ b/ntobapi.h @@ -7,36 +7,82 @@ #ifndef _NTOBAPI_H #define _NTOBAPI_H -#if (PHNT_MODE != PHNT_MODE_KERNEL) +// +// Object Specific Access Rights +// + +#ifndef OBJECT_TYPE_CREATE #define OBJECT_TYPE_CREATE 0x0001 +#endif + +#ifndef OBJECT_TYPE_ALL_ACCESS #define OBJECT_TYPE_ALL_ACCESS (STANDARD_RIGHTS_REQUIRED | OBJECT_TYPE_CREATE) #endif -#if (PHNT_MODE != PHNT_MODE_KERNEL) +// +// Directory Object Specific Access Rights +// + +#ifndef DIRECTORY_QUERY #define DIRECTORY_QUERY 0x0001 +#endif + +#ifndef DIRECTORY_TRAVERSE #define DIRECTORY_TRAVERSE 0x0002 +#endif + +#ifndef DIRECTORY_CREATE_OBJECT #define DIRECTORY_CREATE_OBJECT 0x0004 +#endif + +#ifndef DIRECTORY_CREATE_SUBDIRECTORY #define DIRECTORY_CREATE_SUBDIRECTORY 0x0008 +#endif + +#ifndef DIRECTORY_ALL_ACCESS #define DIRECTORY_ALL_ACCESS (STANDARD_RIGHTS_REQUIRED | DIRECTORY_QUERY | DIRECTORY_TRAVERSE | DIRECTORY_CREATE_OBJECT | DIRECTORY_CREATE_SUBDIRECTORY) #endif -#if (PHNT_MODE != PHNT_MODE_KERNEL) +// +// Symbolic Link Specific Access Rights +// + +#ifndef SYMBOLIC_LINK_QUERY #define SYMBOLIC_LINK_QUERY 0x0001 +#endif + +#ifndef SYMBOLIC_LINK_SET #define SYMBOLIC_LINK_SET 0x0002 +#endif + +#ifndef SYMBOLIC_LINK_ALL_ACCESS #define SYMBOLIC_LINK_ALL_ACCESS (STANDARD_RIGHTS_REQUIRED | SYMBOLIC_LINK_QUERY) +#endif + +#ifndef SYMBOLIC_LINK_ALL_ACCESS_EX #define SYMBOLIC_LINK_ALL_ACCESS_EX (STANDARD_RIGHTS_REQUIRED | SPECIFIC_RIGHTS_ALL) #endif +// +// Object Attribute Flags +// + #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 +// +// Object Information +// + #if (PHNT_MODE != PHNT_MODE_KERNEL) typedef enum _OBJECT_INFORMATION_CLASS { @@ -47,6 +93,7 @@ typedef enum _OBJECT_INFORMATION_CLASS ObjectHandleFlagInformation, // qs: OBJECT_HANDLE_FLAG_INFORMATION ObjectSessionInformation, // s: void // change object session // (requires SeTcbPrivilege) ObjectSessionObjectInformation, // s: void // change object session // (requires SeTcbPrivilege) + ObjectSetRefTraceInformation, // since 25H2 MaxObjectInfoClass } OBJECT_INFORMATION_CLASS; #else @@ -57,7 +104,9 @@ typedef enum _OBJECT_INFORMATION_CLASS #define ObjectHandleFlagInformation 4 #define ObjectSessionInformation 5 #define ObjectSessionObjectInformation 6 -#endif +#define ObjectSetRefTraceInformation 7 +#define MaxObjectInfoClass 8 +#endif // (PHNT_MODE != PHNT_MODE_KERNEL) /** * The OBJECT_BASIC_INFORMATION structure contains basic information about an object. @@ -85,7 +134,7 @@ typedef struct _OBJECT_NAME_INFORMATION { UNICODE_STRING Name; // The object name (when present) includes a NULL-terminator and all path separators "\" in the name. } OBJECT_NAME_INFORMATION, *POBJECT_NAME_INFORMATION; -#endif +#endif // (PHNT_MODE != PHNT_MODE_KERNEL) /** * The OBJECT_NAME_INFORMATION structure contains various statistics and properties about an object type. @@ -128,10 +177,23 @@ typedef struct _OBJECT_HANDLE_FLAG_INFORMATION BOOLEAN ProtectFromClose; } OBJECT_HANDLE_FLAG_INFORMATION, *POBJECT_HANDLE_FLAG_INFORMATION; +// // Objects, handles +// #if (PHNT_MODE != PHNT_MODE_KERNEL) +/** + * The NtQueryObject routine retrieves various kinds of object information. + * + * \param Handle The handle of the object for which information is being queried. + * \param ObjectInformationClass The information class indicating the kind of object information to be retrieved. + * \param ObjectInformation An optional pointer to a buffer where the requested information is to be returned. + * \param ObjectInformationLength The size of the buffer pointed to by the ObjectInformation parameter, in bytes. + * \param ReturnLength An optional pointer to a location where the function writes the actual size of the information requested. + * \return NTSTATUS Successful or errant status. + * \sa https://learn.microsoft.com/en-us/windows/win32/api/winternl/nf-winternl-ntqueryobject + */ NTSYSCALLAPI NTSTATUS NTAPI @@ -143,6 +205,15 @@ NtQueryObject( _Out_opt_ PULONG ReturnLength ); +/** + * The NtSetInformationObject routine changes various kinds of information about a object. + * + * \param Handle The handle of the object for which information is being changed. + * \param ObjectInformationClass The type of information, supplied in the buffer pointed to by ObjectInformation, to set for the object. + * \param ObjectInformation Pointer to a buffer that contains the information to set for the object. + * \param ObjectInformationLength The size of the buffer pointed to by the ObjectInformation parameter, in bytes. + * \return NTSTATUS Successful or errant status. + */ NTSYSCALLAPI NTSTATUS NTAPI @@ -153,10 +224,23 @@ NtSetInformationObject( _In_ ULONG ObjectInformationLength ); -#define DUPLICATE_CLOSE_SOURCE 0x00000001 -#define DUPLICATE_SAME_ACCESS 0x00000002 -#define DUPLICATE_SAME_ATTRIBUTES 0x00000004 +#define DUPLICATE_CLOSE_SOURCE 0x00000001 // Close the source handle. +#define DUPLICATE_SAME_ACCESS 0x00000002 // Instead of using the DesiredAccess parameter, copy the access rights from the source handle to the target handle. +#define DUPLICATE_SAME_ATTRIBUTES 0x00000004 // Instead of using the HandleAttributes parameter, copy the attributes from the source handle to the target handle. +/** + * The NtDuplicateObject routine creates a handle that is a duplicate of the specified source handle. + * + * \param SourceProcessHandle A handle to the source process for the handle being duplicated. + * \param SourceHandle The handle to duplicate. + * \param TargetProcessHandle A handle to the target process that is to receive the new handle. This parameter is optional and can be specified as NULL if the DUPLICATE_CLOSE_SOURCE flag is set in Options. + * \param TargetHandle A pointer to a HANDLE variable into which the routine writes the new duplicated handle. The duplicated handle is valid in the specified target process. This parameter is optional and can be specified as NULL if no duplicate handle is to be created. + * \param DesiredAccess An ACCESS_MASK value that specifies the desired access for the new handle. + * \param HandleAttributes A ULONG that specifies the desired attributes for the new handle. + * \param Options A set of flags to control the behavior of the duplication operation. + * \return NTSTATUS Successful or errant status. + * \sa https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/ntifs/nf-ntifs-zwduplicateobject + */ NTSYSCALLAPI NTSTATUS NTAPI @@ -170,6 +254,13 @@ NtDuplicateObject( _In_ ULONG Options ); +/** + * The NtMakeTemporaryObject routine changes the attributes of an object to make it temporary. + * + * \param Handle Handle to an object of any type. + * \return NTSTATUS Successful or errant status. + * \sa https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/wdm/nf-wdm-zwmaketemporaryobject + */ NTSYSCALLAPI NTSTATUS NTAPI @@ -177,6 +268,13 @@ NtMakeTemporaryObject( _In_ HANDLE Handle ); +/** + * The NtMakePermanentObject routine changes the attributes of an object to make it permanent. + * + * \param Handle Handle to an object of any type. + * \return NTSTATUS Successful or errant status. + * \sa https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/wdm/nf-wdm-zwmaketemporaryobject + */ NTSYSCALLAPI NTSTATUS NTAPI @@ -184,6 +282,17 @@ NtMakePermanentObject( _In_ HANDLE Handle ); +/** + * The NtSignalAndWaitForSingleObject routine signals one object and waits on another object as a single operation. + * + * \param SignalHandle A handle to the object to be signaled. + * \param WaitHandle A handle to the object to wait on. The SYNCHRONIZE access right is required. + * \param Alertable If this parameter is TRUE, the function returns when the system queues an I/O completion routine or APC function, and the thread calls the function. + * \param Timeout The time-out interval. The function returns if the interval elapses, even if the object's state is nonsignaled and no completion or APC objects are queued. + * If zero, the function tests the object's state, checks for queued completion routines or APCs, and returns immediately. + * \return NTSTATUS Successful or errant status. + * \sa https://learn.microsoft.com/en-us/windows/win32/api/synchapi/nf-synchapi-signalobjectandwait + */ NTSYSCALLAPI NTSTATUS NTAPI @@ -194,6 +303,17 @@ NtSignalAndWaitForSingleObject( _In_opt_ PLARGE_INTEGER Timeout ); +/** + * The NtWaitForSingleObject routine waits until the specified object is in the signaled state or the time-out interval elapses. + * + * \param Handle The handle to the wait object. + * \param Alertable The function returns when either the time-out period has elapsed or when the APC function is called. + * \param Timeout A pointer to an absolute or relative time over which the wait is to occur. Can be null. If a timeout is specified, + * and the object has not attained a state of signaled when the timeout expires, then the wait is automatically satisfied. + * If an explicit timeout value of zero is specified, then no wait occurs if the wait cannot be satisfied immediately. + * \return NTSTATUS Successful or errant status. + * \sa https://learn.microsoft.com/en-us/windows/win32/api/winternl/nf-winternl-ntwaitforsingleobject + */ NTSYSCALLAPI NTSTATUS NTAPI @@ -203,6 +323,19 @@ NtWaitForSingleObject( _In_opt_ PLARGE_INTEGER Timeout ); +/** + * The NtWaitForMultipleObjects routine waits until one or all of the specified objects are in the signaled state, an I/O completion routine or asynchronous procedure call (APC) is queued to the thread, or the time-out interval elapses. + * + * \param Count The number of object handles to wait for in the array pointed to by lpHandles. The maximum number of object handles is MAXIMUM_WAIT_OBJECTS. This parameter cannot be zero. + * \param Handles An array of object handles. The array can contain handles of objects of different types. It may not contain multiple copies of the same handle. + * \param WaitType If this parameter is WaitAll, the function returns when the state of all objects in the Handles array is set to signaled. + * \param Alertable f this parameter is TRUE and the thread is in the waiting state, the function returns when the system queues an I/O completion routine or APC, and the thread runs the routine or function. + * \param Timeout A pointer to an absolute or relative time over which the wait is to occur. Can be null. If a timeout is specified, + * and the object has not attained a state of signaled when the timeout expires, then the wait is automatically satisfied. + * If an explicit timeout value of zero is specified, then no wait occurs if the wait cannot be satisfied immediately. + * \return NTSTATUS Successful or errant status. + * \sa https://learn.microsoft.com/en-us/windows/win32/api/synchapi/nf-synchapi-waitformultipleobjectsex + */ NTSYSCALLAPI NTSTATUS NTAPI @@ -214,7 +347,6 @@ NtWaitForMultipleObjects( _In_opt_ PLARGE_INTEGER Timeout ); -#if (PHNT_VERSION >= PHNT_WINDOWS_SERVER_2003) NTSYSCALLAPI NTSTATUS NTAPI @@ -225,8 +357,16 @@ NtWaitForMultipleObjects32( _In_ BOOLEAN Alertable, _In_opt_ PLARGE_INTEGER Timeout ); -#endif +/** + * The NtSetSecurityObject routine sets an object's security state. + * + * \param Handle Handle for the object whose security state is to be set. + * \param SecurityInformation A SECURITY_INFORMATION value specifying the information to be set. + * \param SecurityDescriptor Pointer to the security descriptor to be set for the object. + * \return NTSTATUS Successful or errant status. + * \sa https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/ntifs/nf-ntifs-zwsetsecurityobject + */ NTSYSCALLAPI NTSTATUS NTAPI @@ -236,6 +376,17 @@ NtSetSecurityObject( _In_ PSECURITY_DESCRIPTOR SecurityDescriptor ); +/** + * The NtQuerySecurityObject routine retrieves a copy of an object's security descriptor. + * + * \param Handle Handle for the object whose security descriptor is to be queried. + * \param SecurityInformation A SECURITY_INFORMATION value specifying the information to be queried. + * \param SecurityDescriptor Caller-allocated buffer that NtQuerySecurityObject fills with a copy of the specified security descriptor. + * \param Length Size, in bytes, of the buffer pointed to by SecurityDescriptor. + * \param LengthNeeded Pointer to a caller-allocated variable that receives the number of bytes required to store the copied security descriptor. + * \return NTSTATUS Successful or errant status. + * \sa https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/ntifs/nf-ntifs-ntquerysecurityobject + */ NTSYSCALLAPI NTSTATUS NTAPI @@ -247,6 +398,13 @@ NtQuerySecurityObject( _Out_ PULONG LengthNeeded ); +/** + * The NtClose routine closes the specified handle. + * + * \param Handle The handle being closed. + * \return NTSTATUS Successful or errant status. + * \sa https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/wdm/nf-wdm-zwclose + */ NTSYSCALLAPI NTSTATUS NTAPI @@ -255,6 +413,14 @@ NtClose( ); #if (PHNT_VERSION >= PHNT_WINDOWS_10) +/** + * Compares two object handles to determine if they refer to the same underlying kernel object. + * + * \param FirstObjectHandle The first object handle to compare. + * \param SecondObjectHandle The second object handle to compare. + * \return NTSTATUS Successful or errant status. + * \sa https://learn.microsoft.com/en-us/windows/win32/api/handleapi/nf-handleapi-compareobjecthandles + */ NTSYSCALLAPI NTSTATUS NTAPI @@ -262,14 +428,25 @@ NtCompareObjects( _In_ HANDLE FirstObjectHandle, _In_ HANDLE SecondObjectHandle ); -#endif +#endif // (PHNT_VERSION >= PHNT_WINDOWS_10) -#endif +#endif // (PHNT_MODE != PHNT_MODE_KERNEL) +// // Directory objects +// #if (PHNT_MODE != PHNT_MODE_KERNEL) +/** + * The NtCreateDirectoryObject routine creates or opens an object-directory object. + * + * \param DirectoryHandle Pointer to a HANDLE variable that receives a handle to the object directory. + * \param DesiredAccess An ACCESS_MASK that specifies the requested access to the directory object. + * \param ObjectAttributes The attributes for the directory object. + * \return NTSTATUS Successful or errant status. + * \sa https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/wdm/nf-wdm-zwcreatedirectoryobject + */ NTSYSCALLAPI NTSTATUS NTAPI @@ -290,8 +467,17 @@ NtCreateDirectoryObjectEx( _In_ HANDLE ShadowDirectoryHandle, _In_ ULONG Flags ); -#endif +#endif // (PHNT_VERSION >= PHNT_WINDOWS_8) +/** + * Opens an existing directory object. + * + * \param DirectoryHandle A handle to the newly opened directory object. + * \param DesiredAccess An ACCESS_MASK that specifies the requested access to the directory object. + * \param ObjectAttributes The attributes for the directory object. + * \return NTSTATUS Successful or errant status. + * \sa https://learn.microsoft.com/en-us/windows/win32/devnotes/ntopendirectoryobject + */ NTSYSCALLAPI NTSTATUS NTAPI @@ -301,12 +487,28 @@ NtOpenDirectoryObject( _In_ POBJECT_ATTRIBUTES ObjectAttributes ); +/** + * The OBJECT_DIRECTORY_INFORMATION structure contains information about the directory object. + */ typedef struct _OBJECT_DIRECTORY_INFORMATION { UNICODE_STRING Name; UNICODE_STRING TypeName; } OBJECT_DIRECTORY_INFORMATION, *POBJECT_DIRECTORY_INFORMATION; +/** + * Retrieves information about the specified directory object. + * + * \param DirectoryHandle A handle to the directory object. This handle must have been opened with the appropriate access rights. + * \param Buffer A pointer to a buffer that receives the directory information. + * \param Length The size, in bytes, of the buffer pointed to by the Buffer parameter. + * \param ReturnSingleEntry A BOOLEAN value that specifies whether to return a single entry or multiple entries. + * \param RestartScan A BOOLEAN value that specifies whether to restart the scan from the beginning of the directory. + * \param Context A pointer to a variable that maintains the context of the directory enumeration. + * \param ReturnLength An optional pointer to a variable that receives the number of bytes returned in the buffer. + * \return NTSTATUS Successful or errant status. + * \sa https://learn.microsoft.com/en-us/windows/win32/devnotes/ntquerydirectoryobject + */ NTSYSCALLAPI NTSTATUS NTAPI @@ -320,32 +522,37 @@ NtQueryDirectoryObject( _Out_opt_ PULONG ReturnLength ); -#endif +#endif // (PHNT_MODE != PHNT_MODE_KERNEL) +// // Private namespaces +// #if (PHNT_MODE != PHNT_MODE_KERNEL) // private typedef enum _BOUNDARY_ENTRY_TYPE { - OBNS_Invalid, - OBNS_Name, - OBNS_SID, - OBNS_IL + BOUNDARY_ENTRY_TYPE_INVALID, + BOUNDARY_ENTRY_TYPE_NAME, + BOUNDARY_ENTRY_TYPE_SID, + BOUNDARY_ENTRY_TYPE_IL } BOUNDARY_ENTRY_TYPE; +// private +typedef union _OBJECT_BOUNDARY_VALUE +{ + WCHAR Name[1]; + PSID Sid; + PSID IntegrityLabel; +} OBJECT_BOUNDARY_VALUE, *POBJECT_BOUNDARY_VALUE; + // private typedef struct _OBJECT_BOUNDARY_ENTRY { - BOUNDARY_ENTRY_TYPE EntryType; - ULONG EntrySize; - //union - //{ - // WCHAR Name[1]; - // PSID Sid; - // PSID IntegrityLabel; - //}; + BOUNDARY_ENTRY_TYPE Type; + ULONG Size; + // OBJECT_BOUNDARY_VALUE Value; } OBJECT_BOUNDARY_ENTRY, *POBJECT_BOUNDARY_ENTRY; // rev @@ -369,8 +576,16 @@ typedef struct _OBJECT_BOUNDARY_DESCRIPTOR //OBJECT_BOUNDARY_ENTRY Entries[1]; } OBJECT_BOUNDARY_DESCRIPTOR, *POBJECT_BOUNDARY_DESCRIPTOR; -#if (PHNT_VERSION >= PHNT_WINDOWS_VISTA) - +/** + * Creates a private namespace. + * + * \param NamespaceHandle A handle to the newly created private namespace. + * \param DesiredAccess An ACCESS_MASK that specifies the requested access to the private namespace. + * \param ObjectAttributes The attributes for the private namespace. + * \param BoundaryDescriptor A descriptor that defines how the namespace is to be isolated. The RtlCreateBoundaryDescriptor function creates a boundary descriptor. + * \return NTSTATUS Successful or errant status. + * \sa https://learn.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-createprivatenamespacea + */ NTSYSCALLAPI NTSTATUS NTAPI @@ -381,6 +596,16 @@ NtCreatePrivateNamespace( _In_ POBJECT_BOUNDARY_DESCRIPTOR BoundaryDescriptor ); +/** + * Opens a private namespace. + * + * \param NamespaceHandle A handle to the newly opened private namespace. + * \param DesiredAccess An ACCESS_MASK that specifies the requested access to the private namespace. + * \param ObjectAttributes The attributes for the private namespace. + * \param BoundaryDescriptor A descriptor that defines how the namespace is to be isolated. The RtlCreateBoundaryDescriptor function creates a boundary descriptor. + * \return NTSTATUS Successful or errant status. + * \sa https://learn.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-openprivatenamespacea + */ NTSYSCALLAPI NTSTATUS NTAPI @@ -391,6 +616,13 @@ NtOpenPrivateNamespace( _In_ POBJECT_BOUNDARY_DESCRIPTOR BoundaryDescriptor ); +/** + * Deletes an open namespace handle. + * + * \param NamespaceHandle A handle to the private namespace. + * \return NTSTATUS Successful or errant status. + * \sa https://learn.microsoft.com/en-us/windows/win32/api/namespaceapi/nf-namespaceapi-closeprivatenamespace + */ NTSYSCALLAPI NTSTATUS NTAPI @@ -398,11 +630,11 @@ NtDeletePrivateNamespace( _In_ HANDLE NamespaceHandle ); -#endif - -#endif +#endif // (PHNT_MODE != PHNT_MODE_KERNEL) +// // Symbolic links +// #if (PHNT_MODE != PHNT_MODE_KERNEL) @@ -413,7 +645,7 @@ NtCreateSymbolicLinkObject( _Out_ PHANDLE LinkHandle, _In_ ACCESS_MASK DesiredAccess, _In_ POBJECT_ATTRIBUTES ObjectAttributes, - _In_ PUNICODE_STRING LinkTarget + _In_ PCUNICODE_STRING LinkTarget ); NTSYSCALLAPI @@ -451,8 +683,8 @@ NtSetInformationSymbolicLink( _In_reads_bytes_(SymbolicLinkInformationLength) PVOID SymbolicLinkInformation, _In_ ULONG SymbolicLinkInformationLength ); -#endif +#endif // (PHNT_VERSION >= PHNT_WINDOWS_10) -#endif +#endif // (PHNT_MODE != PHNT_MODE_KERNEL) -#endif +#endif // _NTOBAPI_H diff --git a/ntpebteb.h b/ntpebteb.h index 1836c4f..696ac7a 100644 --- a/ntpebteb.h +++ b/ntpebteb.h @@ -7,51 +7,179 @@ #ifndef _NTPEBTEB_H #define _NTPEBTEB_H +#ifdef __has_include +#if __has_include () +#include +#endif // __has_include +#if __has_include () #include +#endif // __has_include +#endif // __has_include +typedef struct _APPCOMPAT_EXE_DATA APPCOMPAT_EXE_DATA, *PAPPCOMPAT_EXE_DATA; 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 _LDR_RESLOADER_RET LDR_RESLOADER_RET, *PLDR_RESLOADER_RET; typedef struct _LEAP_SECOND_DATA *PLEAP_SECOND_DATA; typedef struct _PEB_LDR_DATA PEB_LDR_DATA, *PPEB_LDR_DATA; +typedef struct tagSOleTlsData SOleTlsData, *PSOleTlsData; +typedef struct _KERNEL_CALLBACK_TABLE KERNEL_CALLBACK_TABLE, *PKERNEL_CALLBACK_TABLE; +typedef struct _GDI_HANDLE_ENTRY GDI_HANDLE_ENTRY, *PGDI_HANDLE_ENTRY; +typedef struct _SHIM_PROCESS_CONTEXT SHIM_PROCESS_CONTEXT, *PSHIM_PROCESS_CONTEXT; +typedef struct _HEAP HEAP, *PHEAP; // PEB->AppCompatFlags -#define KACF_OLDGETSHORTPATHNAME 0x00000001 -#define KACF_VERSIONLIE_NOT_USED 0x00000002 -#define KACF_GETTEMPPATH_NOT_USED 0x00000004 -#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 +#define KACF_OLDGETSHORTPATHNAME 0x00000001 +#define KACF_VERSIONLIE_NOT_USED 0x00000002 +#define KACF_GETTEMPPATH_NOT_USED 0x00000004 +#define KACF_GETDISKFREESPACE 0x00000008 +#define KACF_APPCOMPATFLAG_BIT4 0x00000010 +#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_APPCOMPATFLAG_BIT19 0x00080000 +#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 +#define KACF_DISABLEPOSIXDELETEFILE 0x100000000 // rev KernelBase!InternalDeleteFileW +#define KACF_ENABLE_PROCESS_SYSTEMDPIAWARENESS 0x20000000000000 // rev // Enable Per-Process System DPI Awareness and Opt-in to Per-Process System DPI mode. +#define KACF_DISABLE_PROCESS_SYSTEMDPIAWARENESS 0x40000000000000 // rev // Disable Per-Process System DPI Awareness and force legacy DPI behavior. +#define KACF_ENABLE_GDI_DPI_SCALING 0x800000000000000 +#define KACF_FORCE_DISABLE_GDI_SCALING 0x4000000000000000 -// PEB->ApiSetMap -typedef struct _API_SET_NAMESPACE +// PEB->CrossProcessFlags +#define PEB_FLAG_PROCESS_IN_JOB 0x00000001 // Process is part of a job +#define PEB_FLAG_PROCESS_INITIALIZING 0x00000002 // Process is initializing +#define PEB_FLAG_PROCESS_USING_VEH 0x00000004 // Process is using VEH +#define PEB_FLAG_PROCESS_USING_VCH 0x00000008 // Process is using VCH +#define PEB_FLAG_PROCESS_USING_FTH 0x00000010 // Process is using FTH +#define PEB_FLAG_PROCESS_PREVIOUSLY_THROTTLED 0x00000020 // Process was previously throttled +#define PEB_FLAG_PROCESS_CURRENTLY_THROTTLED 0x00000040 // Process is currently throttled +#define PEB_FLAG_PROCESS_IMAGES_HOT_PATCHED 0x00000080 // Process images are hot patched (RS5+) + +// private +#define API_SET_SECTION_NAME ".apiset" + +// private +#define API_SET_SCHEMA_VERSION_V2 0x00000002 // WIN7, WIN8 +#define API_SET_SCHEMA_VERSION_V4 0x00000004 // WINBLUE +#define API_SET_SCHEMA_VERSION_V6 0x00000006 // since THRESHOLD +#define API_SET_SCHEMA_VERSION API_SET_SCHEMA_VERSION_V6 + +// private +#define API_SET_SCHEMA_FLAGS_SEALED 0x00000001 +#define API_SET_SCHEMA_FLAGS_HOST_EXTENSION 0x00000002 + +// private +#define API_SET_SCHEMA_ENTRY_FLAGS_SEALED 0x00000001 +#define API_SET_SCHEMA_ENTRY_FLAGS_EXTENSION 0x00000002 + +// private +typedef struct _API_SET_VALUE_ENTRY_V2 +{ + ULONG NameOffset; // to WCHAR[NameLength / sizeof(WCHAR)], from schema base + ULONG NameLength; + ULONG ValueOffset; // to WCHAR[ValueLength / sizeof(WCHAR)], from schema base + ULONG ValueLength; +} API_SET_VALUE_ENTRY_V2, *PAPI_SET_VALUE_ENTRY_V2; + +// private +typedef struct _API_SET_VALUE_ARRAY_V2 +{ + ULONG Count; + _Field_size_full_(Count) API_SET_VALUE_ENTRY_V2 Array[ANYSIZE_ARRAY]; +} API_SET_VALUE_ARRAY_V2, *PAPI_SET_VALUE_ARRAY_V2; + +// private +typedef struct _API_SET_NAMESPACE_ENTRY_V2 +{ + ULONG NameOffset; // to WCHAR[NameLength / sizeof(WCHAR)], from schema base + ULONG NameLength; + ULONG DataOffset; // to API_SET_VALUE_ARRAY_V2, from schema base +} API_SET_NAMESPACE_ENTRY_V2, *PAPI_SET_NAMESPACE_ENTRY_V2; + +// private // PEB->ApiSetMap on WIN7, WIN8 +typedef struct _API_SET_NAMESPACE_ARRAY_V2 +{ + ULONG Version; // API_SET_SCHEMA_VERSION_V2 + ULONG Count; + _Field_size_full_(Count) API_SET_NAMESPACE_ENTRY_V2 Array[ANYSIZE_ARRAY]; +} API_SET_NAMESPACE_ARRAY_V2, *PAPI_SET_NAMESPACE_ARRAY_V2; + +// private +typedef struct _API_SET_VALUE_ENTRY_V4 +{ + ULONG Flags; + ULONG NameOffset; // to WCHAR[NameLength / sizeof(WCHAR)], from schema base + ULONG NameLength; + ULONG ValueOffset; // to WCHAR[ValueLength / sizeof(WCHAR)], from schema base + ULONG ValueLength; +} API_SET_VALUE_ENTRY_V4, *PAPI_SET_VALUE_ENTRY_V4; + +// private +typedef struct _API_SET_VALUE_ARRAY_V4 { - ULONG Version; - ULONG Size; ULONG Flags; ULONG Count; - ULONG EntryOffset; - ULONG HashOffset; - ULONG HashFactor; -} API_SET_NAMESPACE, *PAPI_SET_NAMESPACE; + _Field_size_full_(Count) API_SET_VALUE_ENTRY_V4 Array[ANYSIZE_ARRAY]; +} API_SET_VALUE_ARRAY_V4, *PAPI_SET_VALUE_ARRAY_V4; + +// private +typedef struct _API_SET_NAMESPACE_ENTRY_V4 +{ + ULONG Flags; // API_SET_SCHEMA_ENTRY_FLAGS_* + ULONG NameOffset; // to WCHAR[NameLength / sizeof(WCHAR)], from schema base + ULONG NameLength; + ULONG AliasOffset; // to WCHAR[AliasLength / sizeof(WCHAR)], from schema base + ULONG AliasLength; + ULONG DataOffset; // to API_SET_VALUE_ARRAY_V4, from schema base +} API_SET_NAMESPACE_ENTRY_V4, *PAPI_SET_NAMESPACE_ENTRY_V4; + +// private // PEB->ApiSetMap on WINBLUE +typedef struct _API_SET_NAMESPACE_ARRAY_V4 +{ + ULONG Version; // API_SET_SCHEMA_VERSION_V4 + ULONG Size; + ULONG Flags; // API_SET_SCHEMA_FLAGS_* + ULONG Count; + _Field_size_full_(Count) API_SET_NAMESPACE_ENTRY_V4 Array[ANYSIZE_ARRAY]; +} API_SET_NAMESPACE_ARRAY_V4, *PAPI_SET_NAMESPACE_ARRAY_V4; + +// private +typedef struct _API_SET_VALUE_ENTRY +{ + ULONG Flags; + ULONG NameOffset; // to WCHAR[NameLength / sizeof(WCHAR)], from schema base + ULONG NameLength; + ULONG ValueOffset; // to WCHAR[ValueLength / sizeof(WCHAR)], from schema base + ULONG ValueLength; +} API_SET_VALUE_ENTRY, *PAPI_SET_VALUE_ENTRY; + +// private +typedef struct _API_SET_NAMESPACE_ENTRY +{ + ULONG Flags; // API_SET_SCHEMA_ENTRY_FLAGS_* + ULONG NameOffset; // to WCHAR[NameLength / sizeof(WCHAR)], from schema base + ULONG NameLength; + ULONG HashedLength; + ULONG ValueOffset; // to API_SET_VALUE_ENTRY[ValueCount], from schema base + ULONG ValueCount; +} API_SET_NAMESPACE_ENTRY, *PAPI_SET_NAMESPACE_ENTRY; // private typedef struct _API_SET_HASH_ENTRY @@ -60,26 +188,17 @@ typedef struct _API_SET_HASH_ENTRY ULONG Index; } API_SET_HASH_ENTRY, *PAPI_SET_HASH_ENTRY; -// private -typedef struct _API_SET_NAMESPACE_ENTRY +// private // PEB->ApiSetMap since THRESHOLD +typedef struct _API_SET_NAMESPACE { - 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; + ULONG Version; // API_SET_SCHEMA_VERSION_V6 + ULONG Size; + ULONG Flags; // API_SET_SCHEMA_FLAGS_* + ULONG Count; + ULONG EntryOffset; // to API_SET_NAMESPACE_ENTRY[Count], from this struct base + ULONG HashOffset; // to API_SET_HASH_ENTRY[Count], from this struct base + ULONG HashFactor; +} API_SET_NAMESPACE, *PAPI_SET_NAMESPACE; // PEB->TelemetryCoverageHeader typedef struct _TELEMETRY_COVERAGE_HEADER @@ -208,12 +327,17 @@ 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]; -typedef VOID (NTAPI* PPS_POST_PROCESS_INIT_ROUTINE)( +typedef _Function_class_(PS_POST_PROCESS_INIT_ROUTINE) +VOID NTAPI PS_POST_PROCESS_INIT_ROUTINE( VOID ); +typedef PS_POST_PROCESS_INIT_ROUTINE* PPS_POST_PROCESS_INIT_ROUTINE; +#ifndef RTL_FLS_MAXIMUM_AVAILABLE +#define RTL_FLS_MAXIMUM_AVAILABLE 128 +#endif #ifndef FLS_MAXIMUM_AVAILABLE -#define FLS_MAXIMUM_AVAILABLE 128 +#define FLS_MAXIMUM_AVAILABLE 4080 #endif #ifndef TLS_MINIMUM_AVAILABLE #define TLS_MINIMUM_AVAILABLE 64 @@ -225,7 +349,7 @@ typedef VOID (NTAPI* PPS_POST_PROCESS_INIT_ROUTINE)( /** * Process Environment Block (PEB) structure. * - * \remarks https://learn.microsoft.com/en-us/windows/win32/api/winternl/ns-winternl-peb + * \sa https://learn.microsoft.com/en-us/windows/win32/api/winternl/ns-winternl-peb */ typedef struct _PEB { @@ -254,7 +378,7 @@ typedef struct _PEB BOOLEAN IsImageDynamicallyRelocated : 1; // The process image base address was relocated. BOOLEAN SkipPatchingUser32Forwarders : 1; // The process skipped forwarders for User32.dll functions. 1 for 64-bit, 0 for 32-bit. BOOLEAN IsPackagedProcess : 1; // The process is a packaged store process (APPX/MSIX). - BOOLEAN IsAppContainer : 1; // The process has an AppContainer token. + BOOLEAN IsAppContainerProcess : 1; // The process has an AppContainer token. BOOLEAN IsProtectedProcessLight : 1; // The process is a protected process (light). BOOLEAN IsLongPathAwareProcess : 1; // The process is long path aware. }; @@ -288,7 +412,7 @@ typedef struct _PEB // // Pointer to the process default heap. // - PVOID ProcessHeap; + PHEAP ProcessHeap; // // Pointer to a critical section used to synchronize access to the PEB. @@ -301,9 +425,9 @@ typedef struct _PEB PSLIST_HEADER AtlThunkSListPtr; // - // Pointer to the Image File Execution Options key. + // Handle to the Image File Execution Options key. // - PVOID IFEOKey; + HANDLE IFEOKey; // // Cross process flags. @@ -330,7 +454,7 @@ typedef struct _PEB // union { - PVOID KernelCallbackTable; + PKERNEL_CALLBACK_TABLE KernelCallbackTable; PVOID UserSharedInfoPtr; }; @@ -380,19 +504,19 @@ typedef struct _PEB PVOID* ReadOnlyStaticServerData; // - // Pointer to the ANSI code page data. (PCPTABLEINFO) + // Pointer to the ANSI code page data. // - PVOID AnsiCodePageData; + PCPTABLEINFO AnsiCodePageData; // - // Pointer to the OEM code page data. (PCPTABLEINFO) + // Pointer to the OEM code page data. // - PVOID OemCodePageData; + PCPTABLEINFO OemCodePageData; // - // Pointer to the Unicode case table data. (PNLSTABLEINFO) + // Pointer to the Unicode case table data. // - PVOID UnicodeCaseTableData; + PNLSTABLEINFO UnicodeCaseTableData; // // The total number of system processors. @@ -488,7 +612,7 @@ typedef struct _PEB // // Pointer to the system GDI shared handle table. // - PVOID GdiSharedHandleTable; + PGDI_HANDLE_ENTRY GdiSharedHandleTable; // // Pointer to the process starter helper. @@ -588,12 +712,12 @@ typedef struct _PEB // // Pointer to the Application SwitchBack Compatibility Engine. // - PVOID pShimData; + PSHIM_PROCESS_CONTEXT pShimData; // - // Pointer to the Application Compatibility Engine. // APPCOMPAT_EXE_DATA + // Pointer to the Application Compatibility Engine. // - PVOID AppCompatInfo; + PAPPCOMPAT_EXE_DATA AppCompatInfo; // // CSD version string of the operating system. @@ -643,15 +767,7 @@ typedef struct _PEB // // Packaged process feature state. // - union - { - ULONG AppModelFeatureState; - struct - { - ULONG ForegroundBoostProcesses : 1; - ULONG AppModelFeatureStateReserved : 31; - }; - }; + ULONG AppModelFeatureState; // // SpareUlongs @@ -700,7 +816,7 @@ typedef struct _PEB // // Reserved. // - PVOID pImageHeaderHash; + PVOID ImageHeaderHash; // // ETW tracing flags. @@ -789,19 +905,13 @@ typedef struct _PEB // Extended feature disable mask (AVX). // since WIN11 // ULONGLONG ExtendedFeatureDisableMask; -} PEB, * PPEB; +} PEB, *PPEB; #ifdef _WIN64 static_assert(FIELD_OFFSET(PEB, SessionId) == 0x2C0, "FIELD_OFFSET(PEB, SessionId) is incorrect"); -//static_assert(sizeof(PEB) == 0x7B0, "Size of PEB is incorrect"); // REDSTONE3 -//static_assert(sizeof(PEB) == 0x7B8, "Size of PEB is incorrect"); // REDSTONE4 -//static_assert(sizeof(PEB) == 0x7C8, "Size of PEB is incorrect"); // REDSTONE5 // 19H1 static_assert(sizeof(PEB) == 0x7d0, "Size of PEB is incorrect"); // WIN11 #else static_assert(FIELD_OFFSET(PEB, SessionId) == 0x1D4, "FIELD_OFFSET(PEB, SessionId) is incorrect"); -//static_assert(sizeof(PEB) == 0x468, "Size of PEB is incorrect"); // REDSTONE3 -//static_assert(sizeof(PEB) == 0x470, "Size of PEB is incorrect"); // REDSTONE4 -//static_assert(sizeof(PEB) == 0x480, "Size of PEB is incorrect"); // REDSTONE5 // 19H1 static_assert(sizeof(PEB) == 0x488, "Size of PEB is incorrect"); // WIN11 #endif @@ -861,10 +971,68 @@ typedef struct _TEB_ACTIVE_FRAME_EX #define STATIC_UNICODE_BUFFER_LENGTH 261 #define WIN32_CLIENT_INFO_LENGTH 62 +#if (PHNT_MODE != PHNT_MODE_KERNEL) +// private +typedef struct _CALLBACKWND +{ + HWND hwnd; + ULONG_PTR pwnd; + PACTIVATION_CONTEXT ActCtx; +} CALLBACKWND, *PCALLBACKWND; + +// private +typedef struct tagDPICONTEXTINFO +{ + ULONG dpiContext; + LOGICAL Dirty; +} DPICONTEXTINFO, *PDPICONTEXTINFO; + +// private + rev +typedef struct tagCLIENTINFO +{ + ULONG_PTR CI_flags; + ULONG_PTR Spins; + ULONG ExpWinVer; + ULONG CompatFlags; + ULONG CompatFlags2; + ULONG TIFlags; + struct tagDESKTOPINFO* DeskInfo; + PVOID DesktopBase; // ClientDelta before RS2 + HHOOK hkCurrent; + ULONG Hooks; + CALLBACKWND CallbackWnd; + ULONG HookCurrent; + LONG InDDEMLCallback; + struct tagCLIENTTHREADINFO* ClientThreadInfo; + ULONG_PTR HookData; + ULONG KeyCache; + UCHAR KeyState[8]; + ULONG AsyncKeyCache; + UCHAR AsyncKeyState[8]; + UCHAR AsyncKeyStateRecentDown[8]; + HKL hKL; + USHORT CodePage; + UCHAR DbcsCFOld[2]; + UCHAR DbcsCFNew[2]; + MSG msgDbcsCB; + PULONG RegisteredClasses; + HANDLE mmcssHandle; + ULONG_PTR CI_exflags; + DPICONTEXTINFO dci; +} CLIENTINFO, *PCLIENTINFO; +#endif // (PHNT_MODE != PHNT_MODE_KERNEL) + +// rev - xor key for ReservedForNtRpc +#ifdef _WIN64 +#define RPC_THREAD_POINTER_KEY 0xABABABABDEDEDEDEui64 +#else +#define RPC_THREAD_POINTER_KEY 0xABABABAB +#endif + /** * Thread Environment Block (TEB) structure. * - * \remarks https://learn.microsoft.com/en-us/windows/win32/api/winternl/ns-winternl-teb + * \sa https://learn.microsoft.com/en-us/windows/win32/api/winternl/ns-winternl-teb */ typedef struct _TEB { @@ -914,17 +1082,17 @@ typedef struct _TEB PVOID CsrClientThread; // - // Reserved. + // Reserved for win32k.sys // PVOID Win32ThreadInfo; // - // Reserved. + // Reserved for user32.dll // ULONG User32Reserved[26]; // - // Reserved. + // Reserved for winsrv.dll // ULONG UserReserved[5]; @@ -950,7 +1118,7 @@ typedef struct _TEB #ifdef _WIN64 // - // Reserved. + // Reserved for floating-point emulation. // PVOID SystemReserved1[25]; @@ -981,7 +1149,7 @@ typedef struct _TEB BOOLEAN PlaceholderHydrationAlwaysExplicit; // - // Reserved. + // ProjFs and Cloud Files (reparse point) file virtualization. // CHAR PlaceholderReserved[10]; @@ -1057,7 +1225,7 @@ typedef struct _TEB #endif // - // Reserved for GDI. + // Reserved for GDI (Win32k). // GDI_TEB_BATCH GdiTebBatch; CLIENT_ID RealClientId; @@ -1066,10 +1234,18 @@ typedef struct _TEB ULONG GdiClientTID; PVOID GdiThreadLocalInfo; - // - // Reserved for User32. - // +#if (PHNT_MODE != PHNT_MODE_KERNEL) + union + { + // + // User32 (Win32k) thread information. + // + CLIENTINFO Win32ClientInfo; + ULONG_PTR Win32ClientInfoArea[WIN32_CLIENT_INFO_LENGTH]; + }; +#else ULONG_PTR Win32ClientInfo[WIN32_CLIENT_INFO_LENGTH]; +#endif // // Reserved for opengl32.dll @@ -1109,7 +1285,7 @@ typedef struct _TEB PVOID TlsSlots[TLS_MINIMUM_AVAILABLE]; // - // Reserved. + // Reserved for TLS. // LIST_ENTRY TlsLinks; @@ -1119,12 +1295,12 @@ typedef struct _TEB PVOID Vdm; // - // Reserved. + // Reserved for RPC. The pointer is XOR'ed with RPC_THREAD_POINTER_KEY. // PVOID ReservedForNtRpc; // - // Reserved. + // Reserved for Debugging (DebugActiveProcess). // PVOID DbgSsReserved[2]; @@ -1148,7 +1324,7 @@ typedef struct _TEB GUID ActivityId; // - // The service creating the thread (svchost). + // The identifier of the service that created the thread. (svchost) // PVOID SubProcessTag; @@ -1173,7 +1349,7 @@ typedef struct _TEB ULONG GdiBatchCount; // - // The preferred processor for the curremt thread. (SetThreadIdealProcessor/SetThreadIdealProcessorEx) + // The preferred processor for the current thread. (SetThreadIdealProcessor/SetThreadIdealProcessorEx) // union { @@ -1199,25 +1375,73 @@ typedef struct _TEB PVOID ReservedForPerf; // - // tagSOleTlsData. + // Reserved for Object Linking and Embedding (OLE) // - PVOID ReservedForOle; + PSOleTlsData ReservedForOle; + // + // Indicates whether the thread is waiting on the loader lock. + // ULONG WaitingOnLoaderLock; + + // + // The saved priority state for the thread. + // PVOID SavedPriorityState; + + // + // Reserved. + // ULONG_PTR ReservedForCodeCoverage; + + // + // Reserved. + // PVOID ThreadPoolData; + + // + // Pointer to the TLS (Thread Local Storage) expansion slots for the thread. + // PVOID *TlsExpansionSlots; + #ifdef _WIN64 PVOID ChpeV2CpuAreaInfo; // CHPEV2_CPUAREA_INFO // previously DeallocationBStore PVOID Unused; // previously BStoreLimit #endif + + // + // The generation of the MUI (Multilingual User Interface) data. + // ULONG MuiGeneration; + + // + // Indicates whether the thread is impersonating another security context. + // ULONG IsImpersonating; + + // + // Pointer to the NLS (National Language Support) cache. + // PVOID NlsCache; + + // + // Pointer to the AppCompat/Shim Engine data. + // PVOID pShimData; + + // + // Reserved. + // ULONG HeapData; + + // + // Handle to the current transaction associated with the thread. + // HANDLE CurrentTransactionHandle; + + // + // Pointer to the active frame for the thread. + // PTEB_ACTIVE_FRAME ActiveFrame; // @@ -1225,63 +1449,148 @@ typedef struct _TEB // PVOID FlsData; + // + // Pointer to the preferred languages for the current thread. (GetThreadPreferredUILanguages) + // PVOID PreferredLanguages; + + // + // Pointer to the user-preferred languages for the current thread. (GetUserPreferredUILanguages) + // PVOID UserPrefLanguages; + + // + // Pointer to the merged preferred languages for the current thread. (MUI_MERGE_USER_FALLBACK) + // PVOID MergedPrefLanguages; + + // + // Indicates whether the thread is impersonating another user's language settings. + // ULONG MuiImpersonation; + // + // Reserved. + // union { USHORT CrossTebFlags; USHORT SpareCrossTebBits : 16; }; + + // + // SameTebFlags modify the state and behavior of the current thread. + // union { USHORT SameTebFlags; struct { USHORT SafeThunkCall : 1; - USHORT InDebugPrint : 1; - USHORT HasFiberData : 1; - USHORT SkipThreadAttach : 1; + USHORT InDebugPrint : 1; // Indicates if the thread is currently in a debug print routine. + USHORT HasFiberData : 1; // Indicates if the thread has local fiber-local storage (FLS). + USHORT SkipThreadAttach : 1; // Indicates if the thread should suppress DLL_THREAD_ATTACH notifications. USHORT WerInShipAssertCode : 1; - USHORT RanProcessInit : 1; - USHORT ClonedThread : 1; - USHORT SuppressDebugMsg : 1; + USHORT RanProcessInit : 1; // Indicates if the thread has run process initialization code. + USHORT ClonedThread : 1; // Indicates if the thread is a clone of a different thread. + USHORT SuppressDebugMsg : 1; // Indicates if the thread should suppress LOAD_DLL_DEBUG_INFO notifications. USHORT DisableUserStackWalk : 1; USHORT RtlExceptionAttached : 1; - USHORT InitialThread : 1; + USHORT InitialThread : 1; // Indicates if the thread is the initial thread of the process. USHORT SessionAware : 1; - USHORT LoadOwner : 1; + USHORT LoadOwner : 1; // Indicates if the thread is the owner of the process loader lock. USHORT LoaderWorker : 1; USHORT SkipLoaderInit : 1; USHORT SkipFileAPIBrokering : 1; }; }; + // + // Pointer to the callback function that is called when a KTM transaction scope is entered. + // PVOID TxnScopeEnterCallback; + + // + // Pointer to the callback function that is called when a KTM transaction scope is exited. + /// PVOID TxnScopeExitCallback; + + // + // Pointer to optional context data for use by the application when a KTM transaction scope callback is called. + // PVOID TxnScopeContext; + + // + // The lock count of critical sections for the current thread. + // ULONG LockCount; + + // + // The offset to the WOW64 (Windows on Windows) TEB for the current thread. + // LONG WowTebOffset; - PVOID ResourceRetValue; + + // + // Pointer to the DLL containing the resource (valid after LdrFindResource_U/LdrResFindResource/etc... returns). + // + PLDR_RESLOADER_RET ResourceRetValue; + + // + // Reserved for Windows Driver Framework (WDF). + // PVOID ReservedForWdf; + + // + // Reserved for the Microsoft C runtime (CRT). + // ULONGLONG ReservedForCrt; + + // + // The Host Compute Service (HCS) container identifier. + // GUID EffectiveContainerId; - ULONGLONG LastSleepCounter; // Win11 + + // + // Reserved for Kernel32!Sleep (SpinWait). + // + ULONGLONG LastSleepCounter; // since Win11 + + // + // Reserved for Kernel32!Sleep (SpinWait). + // ULONG SpinCallCount; + + // + // Extended feature disable mask (AVX). + // ULONGLONG ExtendedFeatureDisableMask; - PVOID SchedulerSharedDataSlot; // 24H2 + + // + // Reserved. + // + PVOID SchedulerSharedDataSlot; // since 24H2 + + // + // Reserved. + // PVOID HeapWalkContext; + + // + // The primary processor group affinity of the thread. + // GROUP_AFFINITY PrimaryGroupAffinity; + + // + // Read-copy-update (RCU) synchronization context. + // ULONG Rcu[2]; } TEB, *PTEB; #ifdef _WIN64 -//static_assert(sizeof(TEB) == 0x1850, "Size of TEB is incorrect"); // WIN11 +static_assert(FIELD_OFFSET(TEB, SchedulerSharedDataSlot) == 0x1850, "Size of TEB is incorrect"); // WIN11 static_assert(sizeof(TEB) == 0x1878, "Size of TEB is incorrect"); // 24H2 #else -//static_assert(sizeof(TEB) == 0x1018, "Size of TEB is incorrect"); // WIN11 +static_assert(FIELD_OFFSET(TEB, SchedulerSharedDataSlot) == 0x1018, "Size of TEB is incorrect"); // WIN11 static_assert(sizeof(TEB) == 0x1038, "Size of TEB is incorrect"); // 24H2 #endif diff --git a/ntpfapi.h b/ntpfapi.h index dc7354f..173df35 100644 --- a/ntpfapi.h +++ b/ntpfapi.h @@ -9,65 +9,20 @@ // 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, + PrefetcherRetrieveTrace = 1, // q: PF_RETRIEVE_TRACE + PrefetcherSystemParameters, // q: PF_SYSTEM_PREFETCH_PARAMETERS + PrefetcherBootPhase, // s: PF_BOOT_PHASE_ID + PrefetcherSpare1, // q: PrefetcherRetrieveBootLoaderTrace + PrefetcherOperationProcess, // s: PF_OPERATION_PROCESS + PrefetcherCacheEntryUpdate, // s: PF_CACHE_ENTRY_UPDATE PrefetcherSpare2, - PrefetcherAppLaunchScenarioControl, + PrefetcherAppLaunchScenarioControl, // s: PF_APP_LAUNCH_SCENARIO_CONTROL PrefetcherInformationMax } PREFETCHER_INFORMATION_CLASS; @@ -83,8 +38,174 @@ typedef struct _PREFETCHER_INFORMATION _Inout_ ULONG PrefetcherInformationLength; } PREFETCHER_INFORMATION, *PPREFETCHER_INFORMATION; -// Superfetch +// rev +typedef struct _PF_RETRIEVE_TRACE +{ + UCHAR Buffer[1]; +} PF_RETRIEVE_TRACE, *PPF_RETRIEVE_TRACE; +typedef enum _PF_ENABLE_STATUS +{ + PfSvNotSpecified, + PfSvEnabled, + PfSvDisabled, + PfSvMaxEnableStatus +} PF_ENABLE_STATUS; + +// rev +typedef struct _PF_TRACE_LIMITS +{ + ULONG MaxNumPages; + ULONG MaxNumSections; + LONGLONG TimerPeriod; +} PF_TRACE_LIMITS, *PPF_TRACE_LIMITS; + +// rev +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; + +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; + +#define PF_SN_OPERATION_PROCESS_VERSION 1 + +typedef enum _PF_OPERATION_PROCESS_ACTION +{ + PfSnOpProcessBegin = 0, + PfSnOpProcessEnd = 1, + PfSnOpProcessMax = 2 +} PF_OPERATION_PROCESS_ACTION; + +typedef struct _PF_OPERATION_PROCESS +{ + UCHAR Version; + UCHAR Action; // PF_SYSTEM_OPERATION_PROCESS_ACTION + USHORT Reserved; + ULONG OpFlags; + ULONG Value; +} PF_OPERATION_PROCESS, *PPF_OPERATION_PROCESS; + +#define PF_BOOT_CONTROL_VERSION 1 + +typedef struct _PF_BOOT_CONTROL +{ + ULONG Version; + ULONG DisableBootPrefetching; +} PF_BOOT_CONTROL, *PPF_BOOT_CONTROL; + +#define PF_CACHE_ENTRY_UPDATE_VERSION 2 + +typedef struct _PF_CACHE_ENTRY_UPDATE +{ + ULONG Version; + UCHAR Name[64]; + ULONG NewValue; +} PF_CACHE_ENTRY_UPDATE, *PPF_CACHE_ENTRY_UPDATE; + +#define PF_APP_LAUNCH_SCENARIO_CONTROL_VERSION 1 + +typedef struct _PF_APP_LAUNCH_SCENARIO_CONTROL +{ + ULONG Version; + ULONG Enable; // must be non-zero + HANDLE ProcessHandle; +} PF_APP_LAUNCH_SCENARIO_CONTROL, *PPF_APP_LAUNCH_SCENARIO_CONTROL; + +// +// Superfetch +// + +// rev +typedef enum _SUPERFETCH_INFORMATION_CLASS +{ + SuperfetchRetrieveTrace = 1, // q: PF_SYSTEM_SUPERFETCH_RETRIEVE_TRACE // PfGetCompletedTrace + SuperfetchSystemParameters, // q: PF_SYSTEM_SUPERFETCH_PARAMETERS + SuperfetchLogEvent, // s: PF_LOG_EVENT_DATA + SuperfetchGenerateTrace, // s: PF_GENERATE_TRACE_CONTROL + SuperfetchPrefetch, + SuperfetchPfnQuery, // q: PF_PFN_PRIO_REQUEST + SuperfetchPfnSetPriority, // s: PF_PFN_PRIO_REQUEST // MmSetPfnListInfo + SuperfetchPrivSourceQuery, // q: PF_PRIVSOURCE_QUERY_REQUEST + SuperfetchSequenceNumberQuery, // q: ULONG + SuperfetchScenarioPhase, // s: PF_SCENARIO_PHASE_INFO // 10 + SuperfetchWorkerPriority, // s: PF_WORKER_PRIORITY_CONTROL + SuperfetchScenarioQuery, // q: PF_SCENARIO_QUERY_INFO + SuperfetchScenarioPrefetch, // s: PF_SCENARIO_PREFETCH_INFO + SuperfetchRobustnessControl, // s: PF_ROBUSTNESS_CONTROL + SuperfetchTimeControl, // s: PF_TIME_CONTROL + SuperfetchMemoryListQuery, // q: PF_MEMORY_LIST_INFO + SuperfetchMemoryRangesQuery, // q: PF_PHYSICAL_MEMORY_RANGE_INFO_V1/V2 + SuperfetchTracingControl, // s: PF_ACCESS_TRACING_CONTROL + SuperfetchTrimWhileAgingControl, // s: PF_TRIM_WHILE_AGING_CONTROL + SuperfetchRepurposedByPrefetch, // q: PF_REPURPOSED_BY_PREFETCH_INFO // 20 + SuperfetchChannelPowerRequest, + SuperfetchMovePages, // s: PF_PFN_PRIO_REQUEST // MmRelocatePfnList + SuperfetchVirtualQuery, // q: PF_VIRTUAL_QUERY + SuperfetchCombineStatsQuery, // q: PF_PAGECOMBINE_AGGREGATE_STAT + 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; + +// rev +typedef struct _PF_SYSTEM_SUPERFETCH_RETRIEVE_TRACE +{ + union + { + struct + { + ULONGLONG RequestType; // Must be 2 for "get completed trace" + ULONGLONG Reserved; // Ignored on input + HANDLE PartitionHandle; + } Input; + struct + { + ULONGLONG TypeFlags; // 0x0000000000180002 on success + ULONGLONG Timestamp; // Scaled TSC value + HANDLE PartitionHandle; + } Output; + + // + // Raw view of the buffer for opaque access + // + UCHAR Buffer[ANYSIZE_ARRAY]; + }; +} PF_SYSTEM_SUPERFETCH_RETRIEVE_TRACE, *PPF_SYSTEM_SUPERFETCH_RETRIEVE_TRACE; + +// rev typedef struct _PF_SYSTEM_SUPERFETCH_PARAMETERS { ULONG EnabledComponents; @@ -135,14 +256,31 @@ typedef enum _PF_EVENT_TYPE PfEventTypeMax = 32 } PF_EVENT_TYPE; -// rev +#define PF_LOG_EVENT_DATA_VERSION 1 + typedef struct _PF_LOG_EVENT_DATA { - ULONG EventType : 5; // PF_EVENT_TYPE - ULONG Flags : 2; - ULONG DataSize : 25; + ULONG Version; // PF_LOG_EVENT_DATA_VERSION + union + { + ULONG Packed; // [31:7]=DataSize, [6:5]=Flags, [4:0]=EventType (PF_EVENT_TYPE) + struct + { + ULONG DataSize : 25; // in bytes + ULONG Flags : 2; + ULONG EventType: 5; // 2,3,5,27 accepted by the handler // PF_EVENT_TYPE + }; + }; PVOID EventData; -} PF_LOG_EVENT_DATA, *PPF_LOG_EVENT_DATA; + HANDLE PartitionHandle; +} PF_LOG_EVENT_DATA , *PPF_LOG_EVENT_DATA ; + +typedef struct _PFN_TRIPLET +{ + ULONGLONG MaskOrKey; // Compared against identity with 0x1FFFFFFFFFFFE00 mask + ULONGLONG Pfn; // Page frame number + ULONGLONG Flags; // Request/result flags +} PFN_TRIPLET, *PPFN_TRIPLET; #define PF_PFN_PRIO_REQUEST_VERSION 1 #define PF_PFN_PRIO_REQUEST_QUERY_MEMORY_LIST 0x1 @@ -152,9 +290,15 @@ typedef struct _PF_PFN_PRIO_REQUEST { ULONG Version; ULONG RequestFlags; - ULONG_PTR PfnCount; + SIZE_T PfnCount; SYSTEM_MEMORY_LIST_INFORMATION MemInfo; - MMPFN_IDENTITY PageData[256]; + union + { + // Input: (class 6/16) MmQueryPfnList fills identities here + MMPFN_IDENTITY PageIdentities[256]; // ANYSIZE_ARRAY + // Output: (class 7/29/1D) caller supplies PFN_TRIPLETs here + PFN_TRIPLET Entries[256]; // ANYSIZE_ARRAY + }; } PF_PFN_PRIO_REQUEST, *PPF_PFN_PRIO_REQUEST; typedef enum _PFS_PRIVATE_PAGE_SOURCE_TYPE @@ -184,13 +328,14 @@ typedef struct _PF_PRIVSOURCE_INFO 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. + UCHAR ImageName[16]; + union + { + SIZE_T WsSwapPages; // process only PF_PRIVSOURCE_QUERY_WS_SWAP_PAGES. + SIZE_T SessionPagedPoolPages; // session only. + SIZE_T StoreSizePages; // process only PF_PRIVSOURCE_QUERY_STORE_INFO. }; - ULONG_PTR WsTotalPages; // process/session only. + SIZE_T 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 @@ -236,8 +381,30 @@ typedef struct _PF_SCENARIO_PHASE_INFO ULONG SequenceNumber; ULONG Flags; ULONG FUSUserId; + ULONG Reserved0; // pad to 32 bytes (handler expects 32) + ULONG Reserved1; } PF_SCENARIO_PHASE_INFO, *PPF_SCENARIO_PHASE_INFO; +// rev +typedef struct _PF_WORKER_PRIORITY_CONTROL +{ + ULONG Version; + KPRIORITY Priority; // 0..31 (STATUS_INVALID_PARAMETER if >31) + HANDLE PartitionHandle; +} PF_WORKER_PRIORITY_CONTROL, *PPF_WORKER_PRIORITY_CONTROL; + +// rev +#define PF_SCENARIO_QUERY_INFO_VERSION 4 + +// rev +typedef struct _PF_SCENARIO_QUERY_INFO +{ + ULONG_PTR Version; + ULONG_PTR Field1; + ULONG_PTR Field2; + ULONG_PTR Field3; +} PF_SCENARIO_QUERY_INFO , *PPF_SCENARIO_QUERY_INFO; + // rev typedef struct _PF_MEMORY_LIST_NODE { @@ -290,6 +457,49 @@ typedef struct _PF_ROBUSTNESS_CONTROL PF_ROBUST_FILE_ENTRY FileEntries[1]; } PF_ROBUSTNESS_CONTROL, *PPF_ROBUSTNESS_CONTROL; +// rev +typedef struct _PF_SCENARIO_PREFETCH_INFO +{ + ULONG Version; + ULONG State; +} PF_SCENARIO_PREFETCH_INFO, *PPF_SCENARIO_PREFETCH_INFO; + +// rev +#define PF_TRIM_WHILE_AGING_CONTROL_VERSION_1 1 + +// rev +typedef enum _PF_TRIM_WHILE_AGING_STATE +{ + PfTrimWhileAgingOff = 0, + PfTrimWhileAgingLowPriority = 1, + PfTrimWhileAgingPassive = 2, + PfTrimWhileAgingNormal = 3, + PfTrimWhileAgingAggressive = 4, + PfTrimWhileAgingMax = 5, +} PF_TRIM_WHILE_AGING_STATE, *PPF_TRIM_WHILE_AGING_STATE; + +// rev +typedef struct _PF_TRIM_WHILE_AGING_CONTROL_1 +{ + ULONG Version; + PF_TRIM_WHILE_AGING_STATE TrimWhileAgingState; + BOOLEAN PrivatePageTrimAge; + BOOLEAN SharedPageTrimAge; + USHORT Spare; +} PF_TRIM_WHILE_AGING_CONTROL_1, *PPF_TRIM_WHILE_AGING_CONTROL_1; + +#define PF_TRIM_WHILE_AGING_CONTROL_VERSION_2 2 + +// rev +typedef struct _PF_TRIM_WHILE_AGING_CONTROL_2 +{ + ULONG Version; + PF_TRIM_WHILE_AGING_STATE TrimWhileAgingState; + UCHAR PrivatePageTrimAge; // 0..7 + UCHAR SharedPageTrimAge; // 0..7 + USHORT Spare; // must be 0 +} PF_TRIM_WHILE_AGING_CONTROL_2, *PPF_TRIM_WHILE_AGING_CONTROL_2; + // rev typedef struct _PF_TIME_CONTROL { @@ -327,17 +537,46 @@ typedef struct _PF_PHYSICAL_MEMORY_RANGE_INFO_V2 { ULONG Version; ULONG Flags; - ULONG RangeCount; - PF_PHYSICAL_MEMORY_RANGE Ranges[ANYSIZE_ARRAY]; + SIZE_T RangeCount; + PF_PHYSICAL_MEMORY_RANGE Ranges[1]; } PF_PHYSICAL_MEMORY_RANGE_INFO_V2, *PPF_PHYSICAL_MEMORY_RANGE_INFO_V2; +// rev +typedef struct _PF_START_TRACE_CONTROL +{ + struct + { + ULONG Type; + ULONG Mode; + ULONG Flags; + ULONG Restart; + }; + struct + { + HANDLE PartitionHandle; // in + HANDLE TraceHandleOut; // out when Restart == 0 + }; +} PF_START_TRACE_CONTROL, *PPF_START_TRACE_CONTROL; + +// rev +#define PF_ACCESS_TRACING_CONTROL_VERSION 1 + +// rev +typedef struct _PF_ACCESS_TRACING_CONTROL +{ + ULONG Version; + ULONG Command; + ULONG ComponentMask; +} PF_ACCESS_TRACING_CONTROL, *PPF_ACCESS_TRACING_CONTROL; + // rev #define PF_REPURPOSED_BY_PREFETCH_INFO_VERSION 1 // rev typedef struct _PF_REPURPOSED_BY_PREFETCH_INFO { - ULONG Version; + ULONG Version; // PF_REPURPOSED_BY_PREFETCH_INFO_VERSION + ULONG Reserved; SIZE_T RepurposedByPrefetch; } PF_REPURPOSED_BY_PREFETCH_INFO, *PPF_REPURPOSED_BY_PREFETCH_INFO; @@ -363,6 +602,18 @@ typedef struct _PF_VIRTUAL_QUERY HANDLE ProcessHandle; } PF_VIRTUAL_QUERY, *PPF_VIRTUAL_QUERY; +// rev +#define PF_PAGECOMBINE_AGGREGATE_STAT_VERSION 1 + +// rev +typedef struct _PF_PAGECOMBINE_AGGREGATE_STAT +{ + ULONG Version; + ULONG CombineScanCount; + ULONG CombinedBlocksInUse; + ULONG SumCombinedBlocksReferenceCount; +} PF_PAGECOMBINE_AGGREGATE_STAT, *PPF_PAGECOMBINE_AGGREGATE_STAT; + // rev #define PF_MIN_WS_AGE_RATE_CONTROL_VERSION 1 @@ -370,7 +621,7 @@ typedef struct _PF_VIRTUAL_QUERY typedef struct _PF_MIN_WS_AGE_RATE_CONTROL { ULONG Version; - ULONG SecondsToOldestAge; + ULONG SecondsToOldestAgeRate; } PF_MIN_WS_AGE_RATE_CONTROL, *PPF_MIN_WS_AGE_RATE_CONTROL; // rev @@ -393,6 +644,42 @@ typedef struct _PF_DEPRIORITIZE_OLD_PAGES }; } PF_DEPRIORITIZE_OLD_PAGES, *PPF_DEPRIORITIZE_OLD_PAGES; +// rev +#define PF_FILE_EXTENTS_INFO_VERSION 1 + +// rev +typedef struct _PF_FILE_EXTENTS_INFO +{ + ULONG Version; + PWSTR FilePath; + ULONG FilePathSize; + ULONG VolumePathSize; + LARGE_INTEGER FileIndexNumber; + ULONG VolumeSerialNumber; + RETRIEVAL_POINTERS_BUFFER ExtentsBuffer; + ULONGLONG ExtentsBufferSize; +} PF_FILE_EXTENTS_INFO, *PPF_FILE_EXTENTS_INFO; + +// rev +#define PF_FILE_EXTENTS_INFO_VERSION2 2 + +typedef struct _PF_FILE_EXTENTS_INFO_V2 +{ + ULONG Version; // must be 2 + ULONG Reserved0; + PWSTR PathUtf16; + + ULONG PathBytes; // must be even, within bounds + ULONG PathMeta; // used to compute an index (>>1) tested for '\\' + ULONG ParamA; // must be nonzero and < PathBytes (per checks) + ULONG Reserved1; + + PVOID OutMeta0; + PVOID OutBuffer; + ULONG OutBufferBytesRequested; + ULONG Reserved2; +} PF_FILE_EXTENTS_INFO_V2, *PPF_FILE_EXTENTS_INFO_V2; + // rev #define PF_GPU_UTILIZATION_INFO_VERSION 1 @@ -404,53 +691,6 @@ typedef struct _PF_GPU_UTILIZATION_INFO 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 +#endif // _NTPFAPI_H diff --git a/ntpnpapi.h b/ntpnpapi.h index 6b49034..4ce07a4 100644 --- a/ntpnpapi.h +++ b/ntpnpapi.h @@ -107,7 +107,7 @@ typedef enum _PLUGPLAY_CONTROL_CLASS MaxPlugPlayControl } PLUGPLAY_CONTROL_CLASS, *PPLUGPLAY_CONTROL_CLASS; -// pub +// private typedef enum _DEVICE_RELATION_TYPE { BusRelations, @@ -119,7 +119,7 @@ typedef enum _DEVICE_RELATION_TYPE TransportRelations } DEVICE_RELATION_TYPE, *PDEVICE_RELATION_TYPE; -// pub +// private typedef enum _BUS_QUERY_ID_TYPE { BusQueryDeviceID = 0, // \ @@ -130,14 +130,14 @@ typedef enum _BUS_QUERY_ID_TYPE BusQueryContainerID = 5 // unique id of the device's physical container } BUS_QUERY_ID_TYPE, *PBUS_QUERY_ID_TYPE; -// pub +// private typedef enum _DEVICE_TEXT_TYPE { DeviceTextDescription = 0, // DeviceDesc property DeviceTextLocationInformation = 1 // DeviceLocation property } DEVICE_TEXT_TYPE, *PDEVICE_TEXT_TYPE; -// pub +// private typedef enum _DEVICE_USAGE_NOTIFICATION_TYPE { DeviceUsageTypeUndefined, @@ -159,7 +159,7 @@ NtGetPlugPlayEvent( _Out_writes_bytes_(EventBufferSize) PPLUGPLAY_EVENT_BLOCK EventBlock, _In_ ULONG EventBufferSize ); -#endif +#endif // (PHNT_VERSION < PHNT_WINDOWS_8) NTSYSCALLAPI NTSTATUS @@ -170,8 +170,6 @@ NtPlugPlayControl( _In_ ULONG PnPControlDataLength ); -#if (PHNT_VERSION >= PHNT_WINDOWS_7) - NTSYSCALLAPI NTSTATUS NTAPI @@ -193,17 +191,13 @@ NtDisableLastKnownGood( VOID ); -#endif - -#if (PHNT_VERSION >= PHNT_WINDOWS_VISTA) NTSYSCALLAPI NTSTATUS NTAPI NtReplacePartitionUnit( - _In_ PUNICODE_STRING TargetInstancePath, - _In_ PUNICODE_STRING SpareInstancePath, + _In_ PCUNICODE_STRING TargetInstancePath, + _In_ PCUNICODE_STRING SpareInstancePath, _In_ ULONG Flags ); -#endif -#endif +#endif // _NTPNPAPI_H diff --git a/ntpoapi.h b/ntpoapi.h index 44ff100..b684802 100644 --- a/ntpoapi.h +++ b/ntpoapi.h @@ -10,108 +10,113 @@ #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 // in: ? (optional) // out: PWNF_STATE_NAME (RtlSubscribeWnfStateChangeNotification) -#define GetPowerSettingValue 59 // GUID -#define IdleResiliency 60 // POWER_IDLE_RESILIENCY -#define SessionRITState 61 // POWER_SESSION_RIT_STATE -#define SessionConnectNotification 62 // POWER_SESSION_WINLOGON +#define POWER_INFORMATION_LEVEL ULONG +#define SystemPowerPolicyAc 0 // in: SYSTEM_POWER_POLICY, out: SYSTEM_POWER_POLICY // GET: InputBuffer NULL. SET: InputBuffer not NULL. +#define SystemPowerPolicyDc 1 // in: SYSTEM_POWER_POLICY, out: SYSTEM_POWER_POLICY +#define VerifySystemPolicyAc 2 // in: SYSTEM_POWER_POLICY, out: SYSTEM_POWER_POLICY +#define VerifySystemPolicyDc 3 // in: SYSTEM_POWER_POLICY, out: SYSTEM_POWER_POLICY +#define SystemPowerCapabilities 4 // out: SYSTEM_POWER_CAPABILITIES +#define SystemBatteryState 5 // out: SYSTEM_BATTERY_STATE +#define SystemPowerStateHandler 6 // in: POWER_STATE_HANDLER // (kernel-mode only) +#define ProcessorStateHandler 7 // in: PROCESSOR_STATE_HANDLER // (kernel-mode only) +#define SystemPowerPolicyCurrent 8 // in: SYSTEM_POWER_POLICY +#define AdministratorPowerPolicy 9 // in: ADMINISTRATOR_POWER_POLICY +#define SystemReserveHiberFile 10 // in: BOOLEAN // (requires SeCreatePagefilePrivilege) // TRUE: hibernation file created. FALSE: hibernation file deleted. +#define ProcessorInformation 11 // out: PROCESSOR_POWER_INFORMATION +#define SystemPowerInformation 12 // out: SYSTEM_POWER_INFORMATION +#define ProcessorStateHandler2 13 // in: PROCESSOR_STATE_HANDLER2 // not implemented +#define LastWakeTime 14 // out: ULONGLONG // InterruptTime +#define LastSleepTime 15 // out: ULONGLONG // InterruptTime +#define SystemExecutionState 16 // out: EXECUTION_STATE // NtSetThreadExecutionState +#define SystemPowerStateNotifyHandler 17 // in: POWER_STATE_NOTIFY_HANDLER // (kernel-mode only) +#define ProcessorPowerPolicyAc 18 // in: PROCESSOR_POWER_POLICY // not implemented +#define ProcessorPowerPolicyDc 19 // in: PROCESSOR_POWER_POLICY // not implemented +#define VerifyProcessorPowerPolicyAc 20 // in: PROCESSOR_POWER_POLICY // not implemented +#define VerifyProcessorPowerPolicyDc 21 // in: PROCESSOR_POWER_POLICY // not implemented +#define ProcessorPowerPolicyCurrent 22 // in: PROCESSOR_POWER_POLICY // not implemented +#define SystemPowerStateLogging 23 // in: SYSTEM_POWER_STATE_DISABLE_REASON[] +#define SystemPowerLoggingEntry 24 // in: SYSTEM_POWER_LOGGING_ENTRY[] // (kernel-mode only) +#define SetPowerSettingValue 25 // in: SYSTEM_POWER_SETTING_VALUE // (kernel-mode only) +#define NotifyUserPowerSetting 26 // not implemented +#define PowerInformationLevelUnused0 27 // not implemented +#define SystemMonitorHiberBootPowerOff 28 // in: NULL (PowerMonitorOff) +#define SystemVideoState 29 // out: MONITOR_DISPLAY_STATE +#define TraceApplicationPowerMessage 30 // in: (kernel-mode only) +#define TraceApplicationPowerMessageEnd 31 // in: (kernel-mode only) +#define ProcessorPerfStates 32 // not implemented +#define ProcessorIdleStates 33 // out: PROCESSOR_IDLE_STATES // (kernel-mode only) +#define ProcessorCap 34 // out: PROCESSOR_CAP // (kernel-mode only) +#define SystemWakeSource 35 // out: POWER_WAKE_SOURCE_INFO +#define SystemHiberFileInformation 36 // out: SYSTEM_HIBERFILE_INFORMATION +#define TraceServicePowerMessage 37 // in: SYSTEM_SERVICE_POWER_MESSAGE // (kernel-mode only) +#define ProcessorLoad 38 // in: PROCESSOR_LOAD (sets), in: PPROCESSOR_NUMBER (clears) +#define PowerShutdownNotification 39 // in: POWER_SHUTDOWN_NOTIFICATION +#define MonitorCapabilities 40 // in: POWER_MONITOR_CAPABILITIES +#define SessionPowerInit 41 // in: POWER_SESSION_POWER_INIT +#define SessionDisplayState 42 // in: POWER_SESSION_DISPLAY_STATE +#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 // in: (kernel-mode only) +#define GroupPark 48 // in: (debug-mode boot only) +#define ProcessorIdleDomains 49 // in: (kernel-mode only) +#define WakeTimerList 50 // out: WAKE_TIMER_INFO[] +#define SystemHiberFileSize 51 // out: ULONG +#define ProcessorIdleStatesHv 52 // in: (kernel-mode only) +#define ProcessorPerfStatesHv 53 // in: (kernel-mode only) +#define ProcessorPerfCapHv 54 // int: PROCESSOR_PERF_CAP_HV // (kernel-mode only) +#define ProcessorSetIdle 55 // in: (debug-mode boot only) +#define LogicalProcessorIdling 56 // in: (kernel-mode only) +#define UserPresence 57 // out: POWER_USER_PRESENCE // not implemented +#define PowerSettingNotificationName 58 // in: ? (optional) // out: PWNF_STATE_NAME (RtlSubscribeWnfStateChangeNotification) +#define GetPowerSettingValue 59 // in: GUID +#define IdleResiliency 60 // out: POWER_IDLE_RESILIENCY +#define SessionRITState 61 // out: POWER_SESSION_RIT_STATE +#define SessionConnectNotification 62 // out: 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 // in: NULL -#define SuspendResumeInvocation 71 // (kernel-mode only) // not implemented -#define PlmPowerRequestCreate 72 // in: COUNTED_REASON_CONTEXT, out: HANDLE -#define ScreenOff 73 // in: NULL (PowerMonitorOff) -#define CsDeviceNotification 74 // (kernel-mode only) -#define PlatformRole 75 // POWER_PLATFORM_ROLE -#define LastResumePerformance 76 // RESUME_PERFORMANCE -#define DisplayBurst 77 // in: NULL (PowerMonitorOn) -#define ExitLatencySamplingPercentage 78 // in: NULL (ClearExitLatencySamplingPercentage), in: ULONG (SetExitLatencySamplingPercentage) (max 100) -#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 SessionLockState 64 // out: POWER_SESSION_WINLOGON +#define SystemHiberbootState 65 // out: BOOLEAN // fast startup supported +#define PlatformInformation 66 // out: BOOLEAN // connected standby supported +#define PdcInvocation 67 // in: (kernel-mode only) +#define MonitorInvocation 68 // in: (kernel-mode only) +#define FirmwareTableInformationRegistered 69 // in: (kernel-mode only) +#define SetShutdownSelectedTime 70 // in: NULL +#define SuspendResumeInvocation 71 // in: (kernel-mode only) // not implemented +#define PlmPowerRequestCreate 72 // in: COUNTED_REASON_CONTEXT, out: HANDLE +#define ScreenOff 73 // in: NULL (PowerMonitorOff) +#define CsDeviceNotification 74 // in: (kernel-mode only) +#define PlatformRole 75 // out: POWER_PLATFORM_ROLE +#define LastResumePerformance 76 // out: RESUME_PERFORMANCE +#define DisplayBurst 77 // in: NULL (PowerMonitorOn) +#define ExitLatencySamplingPercentage 78 // in: NULL (ClearExitLatencySamplingPercentage), in: ULONG (SetExitLatencySamplingPercentage) (max 100) +#define RegisterSpmPowerSettings 79 // in: (kernel-mode only) +#define PlatformIdleStates 80 // in: (kernel-mode only) +#define ProcessorIdleVeto 81 // in: (kernel-mode only) // deprecated +#define PlatformIdleVeto 82 // in: (kernel-mode only) // deprecated +#define SystemBatteryStatePrecise 83 // out: SYSTEM_BATTERY_STATE +#define ThermalEvent 84 // in: THERMAL_EVENT // PowerReportThermalEvent +#define PowerRequestActionInternal 85 // in: 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 // POWER_SESSION_ALLOW_EXTERNAL_DMA_DEVICES -#define SendSuspendResumeNotification 96 // since WIN11 -#define BlackBoxRecorderDirectAccessBuffer 97 -#define SystemPowerSourceState 98 // since 25H2 +#define PowerInformationInternal 87 // in: POWER_INFORMATION_LEVEL_INTERNAL // PopPowerInformationInternal +#define ThermalStandby 88 // in: NULL // shutdown with thermal standby as reason. +#define SystemHiberFileType 89 // in: ULONG // zero ? reduced : full // powercfg.exe /h /type +#define PhysicalPowerButtonPress 90 // in: BOOLEAN +#define QueryPotentialDripsConstraint 91 // in: (kernel-mode only) +#define EnergyTrackerCreate 92 // in: POWER_INFORMATION_ENERGY_TRACKER_CREATE_INPUT, out: POWER_INFORMATION_ENERGY_TRACKER_CREATE_OUTPUT +#define EnergyTrackerQuery 93 // in: POWER_INFORMATION_ENERGY_TRACKER_QUERY_INPUT, out: POWER_INFORMATION_ENERGY_TRACKER_QUERY_OUTPUT +#define UpdateBlackBoxRecorder 94 // in: POWER_INFORMATION_BBR_UPDATE_REQUEST_INPUT +#define SessionAllowExternalDmaDevices 95 // in: POWER_SESSION_ALLOW_EXTERNAL_DMA_DEVICES +#define SendSuspendResumeNotification 96 // in: since WIN11 +#define BlackBoxRecorderDirectAccessBuffer 97 // in: POWER_INFORMATION_BBR_DIRECT_ACCESS_REQUEST_INPUT, out: POWER_INFORMATION_BBR_DIRECT_ACCESS_REQUEST_OUTPUT // since WIN11 +#define SystemPowerSourceState 98 // in: since 25H2 #define PowerInformationLevelMaximum 99 -#endif +#endif // (PHNT_MODE != PHNT_MODE_KERNEL) +/** + * The PROCESSOR_POWER_INFORMATION structure contains information about the power characteristics of a processor. + * \sa https://learn.microsoft.com/en-us/windows/win32/power/processor-power-information-str + */ typedef struct _PROCESSOR_POWER_INFORMATION { ULONG Number; @@ -122,6 +127,15 @@ typedef struct _PROCESSOR_POWER_INFORMATION ULONG CurrentIdleState; } PROCESSOR_POWER_INFORMATION, *PPROCESSOR_POWER_INFORMATION; +// CoolingMode flags +#define PO_TZ_ACTIVE 0 // The system is currently in Active cooling mode. +#define PO_TZ_PASSIVE 1 // The system does not support CPU throttling, or there is no thermal zone defined in the system. +#define PO_TZ_INVALID_MODE 2 //The system is currently in Passive cooling mode. + +/** + * The SYSTEM_POWER_INFORMATION structure contains information about the idleness of the system. + * \sa https://learn.microsoft.com/en-us/windows/win32/power/system-power-information-str + */ typedef struct _SYSTEM_POWER_INFORMATION { ULONG MaxIdlenessAllowed; @@ -136,6 +150,13 @@ typedef struct _SYSTEM_HIBERFILE_INFORMATION LARGE_INTEGER Mcb[1]; } SYSTEM_HIBERFILE_INFORMATION, *PSYSTEM_HIBERFILE_INFORMATION; +typedef struct _SYSTEM_SERVICE_POWER_MESSAGE +{ + ULONG MessageId; + ULONG SessionId; + ULONG Flags; +} SYSTEM_SERVICE_POWER_MESSAGE, *PSYSTEM_SERVICE_POWER_MESSAGE; + //typedef enum POWER_USER_PRESENCE_TYPE //{ // UserNotPresent = 0, @@ -213,6 +234,13 @@ typedef struct _SYSTEM_POWER_LOGGING_ENTRY ULONG States; } SYSTEM_POWER_LOGGING_ENTRY, *PSYSTEM_POWER_LOGGING_ENTRY; +typedef struct _SYSTEM_POWER_SETTING_VALUE +{ + GUID SettingGuid; + ULONG ValueLength; + UCHAR Value[1]; +} SYSTEM_POWER_SETTING_VALUE, *PSYSTEM_POWER_SETTING_VALUE; + typedef enum _POWER_STATE_DISABLED_TYPE { PoDisabledStateSleeping1 = 0, @@ -381,12 +409,11 @@ typedef struct PROCESSOR_IDLE_TIMES ULONG Reserved[4]; } PROCESSOR_IDLE_TIMES, *PPROCESSOR_IDLE_TIMES; -_Function_class_(PROCESSOR_IDLE_HANDLER) -typedef NTSTATUS (FASTCALL PROCESSOR_IDLE_HANDLER)( +typedef _Function_class_(PROCESSOR_IDLE_HANDLER) +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 @@ -454,6 +481,36 @@ typedef struct _PROCESSOR_LOAD USHORT Padding; } PROCESSOR_LOAD, *PPROCESSOR_LOAD; +// rev +typedef struct _POWER_SHUTDOWN_NOTIFICATION +{ + PVOID CallbackRoutine; + PVOID Context; +} POWER_SHUTDOWN_NOTIFICATION, *PPOWER_SHUTDOWN_NOTIFICATION; + +// rev +typedef struct _POWER_MONITOR_CAPABILITIES +{ + ULONG Size; + ULONG Flags; // e.g. brightness, color control + ULONG Reserved; +} POWER_MONITOR_CAPABILITIES, *PPOWER_MONITOR_CAPABILITIES; + +// rev +typedef struct _POWER_SESSION_POWER_INIT +{ + ULONG SessionId; + ULONG Flags; + ULONG Reserved; +} POWER_SESSION_POWER_INIT, *PPOWER_SESSION_POWER_INIT; + +// rev +typedef struct _POWER_SESSION_DISPLAY_STATE +{ + ULONG SessionId; + ULONG DisplayState; // e.g. on, off, dimmed +} POWER_SESSION_DISPLAY_STATE, *PPOWER_SESSION_DISPLAY_STATE; + // rev typedef struct _PROCESSOR_CAP { @@ -552,7 +609,7 @@ typedef struct _POWER_REQUEST ULONG PowerRequestCount[POWER_REQUEST_SUPPORTED_TYPES_V2]; DIAGNOSTIC_BUFFER DiagnosticBuffer; } V2; -#endif +#endif // (PHNT_VERSION >= PHNT_WINDOWS_8) #if (PHNT_VERSION >= PHNT_WINDOWS_8_1) struct { @@ -560,7 +617,7 @@ typedef struct _POWER_REQUEST ULONG PowerRequestCount[POWER_REQUEST_SUPPORTED_TYPES_V3]; DIAGNOSTIC_BUFFER DiagnosticBuffer; } V3; -#endif +#endif // (PHNT_VERSION >= PHNT_WINDOWS_8_1) #if (PHNT_VERSION >= PHNT_WINDOWS_10_RS1) struct { @@ -568,7 +625,7 @@ typedef struct _POWER_REQUEST ULONG PowerRequestCount[POWER_REQUEST_SUPPORTED_TYPES_V4]; DIAGNOSTIC_BUFFER DiagnosticBuffer; } V4; -#endif +#endif // (PHNT_VERSION >= PHNT_WINDOWS_10_RS1) }; } POWER_REQUEST, *PPOWER_REQUEST; @@ -590,17 +647,21 @@ typedef enum _POWER_STATE_HANDLER_TYPE PowerStateMaximum = 7 } POWER_STATE_HANDLER_TYPE, *PPOWER_STATE_HANDLER_TYPE; -typedef NTSTATUS (NTAPI *PENTER_STATE_SYSTEM_HANDLER)( +typedef _Function_class_(ENTER_STATE_SYSTEM_HANDLER) +NTSTATUS NTAPI ENTER_STATE_SYSTEM_HANDLER( _In_ PVOID SystemContext ); +typedef ENTER_STATE_SYSTEM_HANDLER* PENTER_STATE_SYSTEM_HANDLER; -typedef NTSTATUS (NTAPI *PENTER_STATE_HANDLER)( +typedef _Function_class_(ENTER_STATE_HANDLER) +NTSTATUS NTAPI ENTER_STATE_HANDLER( _In_ PVOID Context, _In_opt_ PENTER_STATE_SYSTEM_HANDLER SystemHandler, _In_ PVOID SystemContext, _In_ LONG NumberProcessors, - _In_ LONG volatile *Number + _In_ LONG volatile* Number ); +typedef ENTER_STATE_HANDLER* PENTER_STATE_HANDLER; typedef struct _POWER_STATE_HANDLER { @@ -611,11 +672,13 @@ typedef struct _POWER_STATE_HANDLER PVOID Context; } POWER_STATE_HANDLER, *PPOWER_STATE_HANDLER; -typedef NTSTATUS (NTAPI *PENTER_STATE_NOTIFY_HANDLER)( +typedef _Function_class_(ENTER_STATE_NOTIFY_HANDLER) +NTSTATUS NTAPI ENTER_STATE_NOTIFY_HANDLER( _In_ POWER_STATE_HANDLER_TYPE State, _In_ PVOID Context, _In_ BOOLEAN Entering ); +typedef ENTER_STATE_NOTIFY_HANDLER* PENTER_STATE_NOTIFY_HANDLER; typedef struct _POWER_STATE_NOTIFY_HANDLER { @@ -632,103 +695,105 @@ typedef struct _POWER_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, // (requires SeShutdownPrivilege and terminalPowerManagement capability) - PowerInternalTtmCreateTerminal, // (requires SeShutdownPrivilege and terminalPowerManagement capability) // 10 - PowerInternalTtmEvacuateDevices, // (requires SeShutdownPrivilege and terminalPowerManagement capability) - PowerInternalTtmCreateTerminalEventQueue, // (requires SeShutdownPrivilege and terminalPowerManagement capability) - PowerInternalTtmGetTerminalEvent, // (requires SeShutdownPrivilege and terminalPowerManagement capability) - PowerInternalTtmSetDefaultDeviceAssignment, // (requires SeShutdownPrivilege and terminalPowerManagement capability) - PowerInternalTtmAssignDevice, // (requires SeShutdownPrivilege and terminalPowerManagement capability) - PowerInternalTtmSetDisplayState, // (requires SeShutdownPrivilege and terminalPowerManagement capability) - PowerInternalTtmSetDisplayTimeouts, // (requires SeShutdownPrivilege and terminalPowerManagement capability) - 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, // PROCESSOR_IDLE_VETO - PowerInternalPlatformIdleVeto, // PLATFORM_IDLE_VETO - PowerInternalIsLongPowerButtonBugcheckEnabled, - PowerInternalAutoChkCausedReboot, // 50 - PowerInternalSetWakeAlarmOverride, + PowerInternalAcpiInterfaceRegister, // in: POWER_INTERNAL_ACPI_INTERFACE_REGISTER_INPUT, out: POWER_INTERNAL_ACPI_INTERFACE_REGISTER_OUTPUT + PowerInternalS0LowPowerIdleInfo, // out: POWER_S0_LOW_POWER_IDLE_INFO + PowerInternalReapplyBrightnessSettings, // in: void + PowerInternalUserAbsencePrediction, // out: POWER_USER_ABSENCE_PREDICTION + PowerInternalUserAbsencePredictionCapability, // out: POWER_USER_ABSENCE_PREDICTION_CAPABILITY + PowerInternalPoProcessorLatencyHint, // out: POWER_PROCESSOR_LATENCY_HINT + PowerInternalStandbyNetworkRequest, // out: POWER_STANDBY_NETWORK_REQUEST (requires PopNetBIServiceSid) + PowerInternalDirtyTransitionInformation, // out: BOOLEAN + PowerInternalSetBackgroundTaskState, // out: POWER_SET_BACKGROUND_TASK_STATE + PowerInternalTtmOpenTerminal, // in: (requires SeShutdownPrivilege and terminalPowerManagement capability) + PowerInternalTtmCreateTerminal, // in: (requires SeShutdownPrivilege and terminalPowerManagement capability) // 10 + PowerInternalTtmEvacuateDevices, // in: (requires SeShutdownPrivilege and terminalPowerManagement capability) + PowerInternalTtmCreateTerminalEventQueue, // in: (requires SeShutdownPrivilege and terminalPowerManagement capability) + PowerInternalTtmGetTerminalEvent, // in: (requires SeShutdownPrivilege and terminalPowerManagement capability) + PowerInternalTtmSetDefaultDeviceAssignment, // in: (requires SeShutdownPrivilege and terminalPowerManagement capability) + PowerInternalTtmAssignDevice, // in: (requires SeShutdownPrivilege and terminalPowerManagement capability) + PowerInternalTtmSetDisplayState, // in: (requires SeShutdownPrivilege and terminalPowerManagement capability) + PowerInternalTtmSetDisplayTimeouts, // in: (requires SeShutdownPrivilege and terminalPowerManagement capability) + PowerInternalBootSessionStandbyActivationInformation, // out: POWER_BOOT_SESSION_STANDBY_ACTIVATION_INFO + PowerInternalSessionPowerState, // in: POWER_SESSION_POWER_STATE + PowerInternalSessionTerminalInput, // in: POWER_INTERNAL_TERMINAL_CORE_WINDOW_INPUT // 20 + PowerInternalSetWatchdog, // in: POWER_INTERNAL_SET_WATCHDOG, out: (optional) HANDLE + PowerInternalPhysicalPowerButtonPressInfoAtBoot, // in: POWER_INTERNAL_PHYSICAL_POWER_BUTTON_AT_BOOT_INPUT, out: POWER_INTERNAL_PHYSICAL_POWER_BUTTON_AT_BOOT_OUTPUT + PowerInternalExternalMonitorConnected, // in: POWER_INTERNAL_EXTERNAL_MONITOR_CONNECTED_INPUT + PowerInternalHighPrecisionBrightnessSettings, // in: POWER_INTERNAL_HIGH_PRECISION_BRIGHTNESS_SETTINGS_INPUT + PowerInternalWinrtScreenToggle, // in: POWER_INTERNAL_WINRT_SCREEN_TOGGLE_INPUT + PowerInternalPpmQosDisable, // in: POWER_INTERNAL_PPM_QOS_DISABLE_INPUT + PowerInternalTransitionCheckpoint, // in: POWER_INTERNAL_TRANSITION_CHECKPOINT_INPUT + PowerInternalInputControllerState, // in: POWER_INTERNAL_INPUT_CONTROLLER_STATE + PowerInternalFirmwareResetReason, // in: POWER_INTERNAL_FIRMWARE_RESET_REASON_INPUT, out: POWER_INTERNAL_FIRMWARE_RESET_REASON_OUTPUT + PowerInternalPpmSchedulerQosSupport, // out: POWER_INTERNAL_PROCESSOR_QOS_SUPPORT // 30 + PowerInternalBootStatGet, // in: POWER_INTERNAL_BOOTSTAT_GET_INPUT, out: (optional) POWER_INTERNAL_BOOTSTAT_GET_OUTPUT[EntryCount] or ULONG[EntryCount] + PowerInternalBootStatSet, // in: POWER_INTERNAL_BOOTSTAT_GET_INPUT + PowerInternalCallHasNotReturnedWatchdog, // not implemented + PowerInternalBootStatCheckIntegrity, // in: POWER_INTERNAL_BOOTSTAT_CHECK_INTEGRITY_INPUT, out: POWER_INTERNAL_BOOTSTAT_CHECK_INTEGRITY_OUTPUT + PowerInternalBootStatRestoreDefaults, // in: void + PowerInternalHostEsStateUpdate, // in: POWER_INTERNAL_HOST_ENERGY_SAVER_STATE + PowerInternalGetPowerActionState, // out: ULONG + PowerInternalBootStatUnlock, // in: POWER_INTERNAL_BOOTSTAT_GET_INPUT + PowerInternalWakeOnVoiceState, // in: POWER_INTERNAL_WAKE_ON_VOICE_STATE_INPUT + PowerInternalDeepSleepBlock, // in: POWER_INTERNAL_DEEP_SLEEP_BLOCK_INPUT // 40 + PowerInternalIsPoFxDevice, // in: POWER_INTERNAL_IS_POFX_DEVICE_INPUT, out: BOOLEAN + PowerInternalPowerTransitionExtensionAtBoot, // out: POWER_INTERNAL_POWER_TRANSITION_EXTENSION_AT_BOOT_OUTPUT + PowerInternalProcessorBrandedFrequency, // in: POWER_INTERNAL_PROCESSOR_BRANDED_FREQUENCY_INPUT, out: POWER_INTERNAL_PROCESSOR_BRANDED_FREQUENCY_OUTPUT + PowerInternalTimeBrokerExpirationReason, // in: POWER_INTERNAL_TIME_BROKER_EXPIRATION_REASON_INPUT + PowerInternalNotifyUserShutdownStatus, // in: POWER_INTERNAL_NOTIFY_USER_SHUTDOWN_STATUS_INPUT + PowerInternalPowerRequestTerminalCoreWindow, // in: POWER_INTERNAL_POWER_REQUEST_TERMINAL_CORE_WINDOW_INPUT + PowerInternalProcessorIdleVeto, // out: PROCESSOR_IDLE_VETO + PowerInternalPlatformIdleVeto, // out: PLATFORM_IDLE_VETO + PowerInternalIsLongPowerButtonBugcheckEnabled, // out: BOOLEAN + PowerInternalAutoChkCausedReboot, // in: POWER_INTERNAL_AUTOCHK_CAUASED_REBOOT_INPUT, out: POWER_INTERNAL_AUTOCHK_CAUASED_REBOOT_OUTPUT // 50 + PowerInternalSetWakeAlarmOverride, // in: POWER_INTERNAL_SET_WAKE_ALARM_OVERRIDE_INPUT - PowerInternalDirectedFxAddTestDevice = 53, - PowerInternalDirectedFxRemoveTestDevice, + PowerInternalDirectedFxAddTestDevice = 53, // in: POWER_INTERNAL_DIRECTED_FX_ADD_TEST_DEVICE_INPUT + PowerInternalDirectedFxRemoveTestDevice, // in: POWER_INTERNAL_DIRECTED_FX_REMOVE_TEST_DEVICE_INPUT - 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, // PPROCESSOR_QUERY_MEASUREMENT_CAPABILITIES - PowerInternalQueryProcMeasurementValues, // PROCESSOR_QUERY_MEASUREMENT_VALUES - PowerInternalPrepareForSystemInitiatedReboot, // 80 - PowerInternalGetAdaptiveSessionState, - PowerInternalSetConsoleLockedState, - PowerInternalOverrideSystemInitiatedRebootState, - PowerInternalFanImpactStats, - PowerInternalFanRpmBuckets, - PowerInternalPowerBootAppDiagInfo, // out: POWER_INTERNAL_BOOTAPP_DIAGNOSTIC - PowerInternalUnregisterShutdownNotification, // since 22H1 - PowerInternalManageTransitionStateRecord, - PowerInternalGetAcpiTimeAndAlarmCapabilities, // since 22H2 - PowerInternalSuspendResumeRequest, - PowerInternalEnergyEstimationInfo, // since 23H2 - PowerInternalProvSocIdentifierOperation, // since 24H2 - PowerInternalGetVmPerfPrioritySupport, - PowerInternalGetVmPerfPriorityConfig, - PowerInternalNotifyWin32kPowerRequestQueued, - PowerInternalNotifyWin32kPowerRequestCompleted, + PowerInternalDirectedFxSetMode = 56, // in: POWER_INTERNAL_DIRECTED_FX_SET_MODE_INPUT + PowerInternalRegisterPowerPlane, // in: POWER_INTERNAL_REGISTER_POWER_PLANE_INPUT + PowerInternalSetDirectedDripsFlags, // in: POWER_INTERNAL_DIRECTED_DRIPS_DEVICE_FLAGS_INPUT + PowerInternalClearDirectedDripsFlags, // in: POWER_INTERNAL_DIRECTED_DRIPS_DEVICE_FLAGS_INPUT + PowerInternalRetrieveHiberFileResumeContext, // out: POWER_INTERNAL_RETRIEVE_HIBERFILE_RESUME_CONTEXT_OUTPUT // 60 + PowerInternalReadHiberFilePage, // in: POWER_INTERNAL_READ_HIBERFILE_PAGE_INPUT, out: POWER_INTERNAL_READ_HIBERFILE_PAGE_OUTPUT + PowerInternalLastBootSucceeded, // out: BOOLEAN + PowerInternalQuerySleepStudyHelperRoutineBlock, // out: POWER_INTERNAL_QUERY_SLEEPSTUDY_HELPER_ROUTINE_BLOCK_OUTPUT + PowerInternalDirectedDripsQueryCapabilities, // out: POWER_INTERNAL_DIRECTED_DRIPS_QUERY_CAPABILITIES_OUTPUT + PowerInternalClearConstraints, // in: POWER_INTERNAL_CLEAR_CONSTRAINTS_INPUT + PowerInternalSoftParkVelocityEnabled, // not implemented + PowerInternalQueryIntelPepCapabilities, // in: POWER_INTERNAL_QUERY_INTEL_PEP_CAPABILITIES_INPUT, out: POWER_INTERNAL_QUERY_INTEL_PEP_CAPABILITIES_OUTPUT + PowerInternalGetSystemIdleLoopEnablement, // in: POWER_INTERNAL_SYSTEM_IDLE_LOOP_ENABLEMENT_INPUT, out: POWER_INTERNAL_SYSTEM_IDLE_LOOP_ENABLEMENT_OUTPUT // since WIN11 + PowerInternalGetVmPerfControlSupport, // in: POWER_INTERNAL_VM_PERF_CONTROL_SUPPORT_INPUT, out: POWER_INTERNAL_VM_PERF_CONTROL_SUPPORT_OUTPUT + PowerInternalGetVmPerfControlConfig, // in: POWER_INTERNAL_VM_PERF_CONTROL_CONFIG_INPUT, out: POWER_INTERNAL_VM_PERF_CONTROL_CONFIG_OUTPUT // 70 + PowerInternalSleepDetailedDiagUpdate, // in: POWER_INTERNAL_SLEEP_DETAILED_DIAG_UPDATE_INPUT + PowerInternalProcessorClassFrequencyBandsStats, // in: POWER_INTERNAL_PROCESSOR_CLASS_BAND_STATS_INPUT, out: POWER_INTERNAL_PROCESSOR_CLASS_BAND_STATS_OUTPUT[] * NumberOfProcessors + PowerInternalHostGlobalUserPresenceStateUpdate, // in: POWER_INTERNAL_HOST_GLOBAL_USER_PRESENCE_STATE_UPDATE_INPUT + PowerInternalCpuNodeIdleIntervalStats, // in: POWER_INTERNAL_IDLE_INTERVAL_STATS_INPUT, out: POWER_INTERNAL_IDLE_INTERVAL_PACKAGE + PowerInternalClassIdleIntervalStats, // in: POWER_INTERNAL_IDLE_INTERVAL_STATS_INPUT, out: POWER_INTERNAL_IDLE_INTERVAL_STATS_OUTPUT + PowerInternalCpuNodeConcurrencyStats, // in: POWER_INTERNAL_IDLE_INTERVAL_STATS_INPUT, out: POWER_INTERNAL_CONCURRENCY_STATS_OUTPUT + PowerInternalClassConcurrencyStats, // in: POWER_INTERNAL_IDLE_INTERVAL_STATS_INPUT, out: POWER_INTERNAL_CONCURRENCY_STATS_OUTPUT + PowerInternalQueryProcMeasurementCapabilities, // in: PROCESSOR_INTERNAL_QUERY_MEASUREMENT_CAPABILITIES, out: PROCESSOR_INTERNAL_QUERY_MEASUREMENT_CAPABILITIES_OUTPUT // (in optional) + PowerInternalQueryProcMeasurementValues, // in: PROCESSOR_INTERNAL_QUERY_MEASUREMENT_VALUES, out: PROCESSOR_INTERNAL_QUERY_MEASUREMENT_VALUES_OUTPUT + PowerInternalPrepareForSystemInitiatedReboot, // in: POWER_INTERNAL_PREPARE_FOR_SYSTEM_INITIATED_REBOOT_INPUT // 80 + PowerInternalGetAdaptiveSessionState, // in: POWER_INTERNAL_GET_ADAPTIVE_SESSION_STATE_INPUT, out: POWER_INTERNAL_GET_ADAPTIVE_SESSION_STATE_OUTPUT + PowerInternalSetConsoleLockedState, // in: POWER_INTERNAL_SET_CONSOLE_LOCKED_STATE_INPUT + PowerInternalOverrideSystemInitiatedRebootState, // in: POWER_INTERNAL_OVERRIDE_SYSTEM_INITIATED_REBOOT_STATE_INPUT + PowerInternalFanImpactStats, // in: POWER_INTERNAL_FAN_IMPACT_STATS_INPUT, out: POWER_INTERNAL_FAN_IMPACT_STATS_OUTPUT + PowerInternalFanRpmBuckets, // in: POWER_INTERNAL_FAN_RPM_BUCKETS_INPUT, out: POWER_INTERNAL_FAN_RPM_OUTPUT + PowerInternalPowerBootAppDiagInfo, // out: POWER_INTERNAL_BOOTAPP_DIAGNOSTIC + PowerInternalUnregisterShutdownNotification, // in: POWER_INTERNAL_UNREGISTER_SHUTDOWN_NOTIFICATION_INPUT // since 22H1 + PowerInternalManageTransitionStateRecord, // in: POWER_INTERNAL_MANAGE_TRANSITION_STATE_RECORD_INPUT + PowerInternalGetAcpiTimeAndAlarmCapabilities, // in: POWER_INTERNAL_GET_ACPI_TIME_AND_ALARM_CAPABILITIES_INPUT, out: POWER_INTERNAL_GET_ACPI_TIME_AND_ALARM_CAPABILITIES_OUTPUT // since 22H2 + PowerInternalSuspendResumeRequest, // in: POWER_INTERNAL_SUSPEND_RESUME_REQUEST_INPUT // 90 + PowerInternalEnergyEstimationInfo, // out: POWER_INTERNAL_ENERGY_ESTIMATION_INFO_OUTPUT // since 23H2 + PowerInternalProvSocIdentifierOperation, // in: POWER_INTERNAL_SOC_IDENTIFIER_OPERATION_INPUT, out: POWER_INTERNAL_SOC_IDENTIFIER_OPERATION_OUTPUT // since 24H2 + PowerInternalGetVmPerfPrioritySupport, // in: POWER_INTERNAL_VMPERF_PRIORITY_SUPPORT_INPUT, out: POWER_INTERNAL_VMPERF_PRIORITY_SUPPORT_OUTPUT + PowerInternalGetVmPerfPriorityConfig, // in: POWER_INTERNAL_VMPERF_PRIORITY_CONFIG_INPUT, out: POWER_INTERNAL_VMPERF_PRIORITY_CONFIG_OUTPUT + PowerInternalNotifyWin32kPowerRequestQueued, // in: POWER_INTERNAL_NOTIFY_WIN32K_POWER_REQUEST_INPUT + PowerInternalNotifyWin32kPowerRequestCompleted, // in: POWER_INTERNAL_NOTIFY_WIN32K_POWER_REQUEST_INPUT + PowerInternalPdcAgentSessionQuery, // in: POWER_INTERNAL_PDC_AGENT_SESSION_QUERY_INPUT, out: BOOLEAN // (feature-gated) + PowerInternalSessionConnectionChangeV2, // in: POWER_INTERNAL_SESSION_CONNECTION_CHANGE_V2_INPUT, out: POWER_INTERNAL_GET_ADAPTIVE_SESSION_STATE_OUTPUT // (feature-gated) PowerInformationInternalMaximum } POWER_INFORMATION_LEVEL_INTERNAL; @@ -770,6 +835,22 @@ typedef struct _POWER_INFORMATION_INTERNAL_HEADER ULONG Version; } POWER_INFORMATION_INTERNAL_HEADER, *PPOWER_INFORMATION_INTERNAL_HEADER; +// rev +typedef struct _POWER_INTERNAL_ACPI_INTERFACE_REGISTER_INPUT +{ + POWER_INFORMATION_INTERNAL_HEADER Header; + UCHAR Data[24]; +} POWER_INTERNAL_ACPI_INTERFACE_REGISTER_INPUT, *PPOWER_INTERNAL_ACPI_INTERFACE_REGISTER_INPUT; + +C_ASSERT(sizeof(POWER_INTERNAL_ACPI_INTERFACE_REGISTER_INPUT) == 0x20); + +// rev +typedef struct _POWER_INTERNAL_ACPI_INTERFACE_REGISTER_OUTPUT +{ + ULONG_PTR RegistrationHandle; + ULONG_PTR Reserved; +} POWER_INTERNAL_ACPI_INTERFACE_REGISTER_OUTPUT, *PPOWER_INTERNAL_ACPI_INTERFACE_REGISTER_OUTPUT; + typedef struct _POWER_USER_ABSENCE_PREDICTION { POWER_INFORMATION_INTERNAL_HEADER Header; @@ -821,6 +902,108 @@ typedef struct _POWER_SESSION_POWER_STATE POWER_MONITOR_REQUEST_REASON RequestReason; } POWER_SESSION_POWER_STATE, *PPOWER_SESSION_POWER_STATE; +// rev +typedef struct _POWER_INTERNAL_SET_WATCHDOG +{ + POWER_INFORMATION_INTERNAL_HEADER Header; + PVOID WatchdogHandle; + UCHAR Parameters[0x48]; + BOOLEAN DeleteWatchdog; + UCHAR Reserved[7]; +} POWER_INTERNAL_SET_WATCHDOG, *PPOWER_INTERNAL_SET_WATCHDOG; + +//C_ASSERT(sizeof(POWER_INTERNAL_SET_WATCHDOG) == 0x60); + +// rev +typedef struct _POWER_INTERNAL_TERMINAL_CORE_WINDOW_INPUT +{ + POWER_INFORMATION_LEVEL_INTERNAL InternalType; + ULONG Version; + ULONG SessionId; + ULONG TerminalId; + UCHAR InputType; +} POWER_INTERNAL_TERMINAL_CORE_WINDOW_INPUT, *PPOWER_INTERNAL_TERMINAL_CORE_WINDOW_INPUT; + +// rev +typedef struct _POWER_INTERNAL_PHYSICAL_POWER_BUTTON_AT_BOOT_INPUT +{ + POWER_INFORMATION_LEVEL_INTERNAL InternalType; + ULONG Version; +} POWER_INTERNAL_PHYSICAL_POWER_BUTTON_AT_BOOT_INPUT, *PPOWER_INTERNAL_PHYSICAL_POWER_BUTTON_AT_BOOT_INPUT; + +// rev +typedef struct _POWER_INTERNAL_PHYSICAL_POWER_BUTTON_AT_BOOT_OUTPUT +{ + UCHAR Buffer[64]; +} POWER_INTERNAL_PHYSICAL_POWER_BUTTON_AT_BOOT_OUTPUT, *PPOWER_INTERNAL_PHYSICAL_POWER_BUTTON_AT_BOOT_OUTPUT; + +// rev +typedef struct _POWER_INTERNAL_EXTERNAL_MONITOR_CONNECTED_INPUT +{ + POWER_INFORMATION_LEVEL_INTERNAL InternalType; + ULONG Version; + BOOLEAN Connected; // 1 = connected, 0 = disconnected +} POWER_INTERNAL_EXTERNAL_MONITOR_CONNECTED_INPUT, *PPOWER_INTERNAL_EXTERNAL_MONITOR_CONNECTED_INPUT; + +// rev +typedef struct _POWER_INTERNAL_HIGH_PRECISION_BRIGHTNESS_SETTINGS_INPUT +{ + POWER_INFORMATION_LEVEL_INTERNAL InternalType; + ULONG Version; + ULONG SessionId; + ULONG BrightnessLevel; + ULONG Flags; + ULONG Reserved[5]; +} POWER_INTERNAL_HIGH_PRECISION_BRIGHTNESS_SETTINGS_INPUT, *PPOWER_INTERNAL_HIGH_PRECISION_BRIGHTNESS_SETTINGS_INPUT; + +// rev +typedef struct _POWER_INTERNAL_WINRT_SCREEN_TOGGLE_INPUT +{ + POWER_INFORMATION_LEVEL_INTERNAL InternalType; + ULONG Version; + BOOLEAN Toggle; // 1 = turn screen on, 0 = turn screen off +} POWER_INTERNAL_WINRT_SCREEN_TOGGLE_INPUT, *PPOWER_INTERNAL_WINRT_SCREEN_TOGGLE_INPUT; + +// rev +typedef struct _POWER_INTERNAL_PPM_QOS_DISABLE_INPUT +{ + POWER_INFORMATION_LEVEL_INTERNAL InternalType; + ULONG Version; + BOOLEAN EnableDisable; // Non-zero to enable QoS disable, zero to disable +} POWER_INTERNAL_PPM_QOS_DISABLE_INPUT, *PPOWER_INTERNAL_PPM_QOS_DISABLE_INPUT; + +// rev +typedef struct _POWER_INTERNAL_TRANSITION_CHECKPOINT_INPUT +{ + POWER_INFORMATION_LEVEL_INTERNAL InternalType; + ULONG Version; + ULONG CheckpointId; + ULONG CheckpointType; +} POWER_INTERNAL_TRANSITION_CHECKPOINT_INPUT, *PPOWER_INTERNAL_TRANSITION_CHECKPOINT_INPUT; + +// rev +typedef struct _POWER_INTERNAL_INPUT_CONTROLLER_STATE +{ + POWER_INFORMATION_INTERNAL_HEADER Header; + ULONG InputControllerState; +} POWER_INTERNAL_INPUT_CONTROLLER_STATE, *PPOWER_INTERNAL_INPUT_CONTROLLER_STATE; + +// rev +typedef struct _POWER_INTERNAL_FIRMWARE_RESET_REASON_INPUT +{ + POWER_INFORMATION_LEVEL_INTERNAL InternalType; + ULONG Version; +} POWER_INTERNAL_FIRMWARE_RESET_REASON_INPUT, *PPOWER_INTERNAL_FIRMWARE_RESET_REASON_INPUT; + +// rev +typedef struct _POWER_INTERNAL_FIRMWARE_RESET_REASON_OUTPUT +{ + ULONG ResetReasonCode; + UCHAR DiagnosticData1[16]; + UCHAR DiagnosticData2[16]; + UCHAR Reserved[12]; +} POWER_INTERNAL_FIRMWARE_RESET_REASON_OUTPUT, *PPOWER_INTERNAL_FIRMWARE_RESET_REASON_OUTPUT; + // rev typedef struct _POWER_INTERNAL_PROCESSOR_QOS_SUPPORT { @@ -829,6 +1012,43 @@ typedef struct _POWER_INTERNAL_PROCESSOR_QOS_SUPPORT BOOLEAN QosGroupPolicyDisable; } POWER_INTERNAL_PROCESSOR_QOS_SUPPORT, *PPOWER_INTERNAL_PROCESSOR_QOS_SUPPORT; +typedef struct _RTL_BSD_ITEM RTL_BSD_ITEM, *PRTL_BSD_ITEM; + +// rev +typedef struct _POWER_INTERNAL_BOOTSTAT_GET_INPUT +{ + POWER_INFORMATION_LEVEL_INTERNAL InternalType; + ULONG Version; + ULONG EntryCount; + ULONG Reserved; + PRTL_BSD_ITEM Entries; +} POWER_INTERNAL_BOOTSTAT_GET_INPUT, *PPOWER_INTERNAL_BOOTSTAT_GET_INPUT; + +// rev +typedef struct _POWER_INTERNAL_BOOTSTAT_GET_OUTPUT +{ + // If present, it receives the actual sizes of the data copied into each DataBuffer. + ULONG Sizes[ANYSIZE_ARRAY]; // Array of sizes, one per entry +} POWER_INTERNAL_BOOTSTAT_GET_OUTPUT, *PPOWER_INTERNAL_BOOTSTAT_GET_OUTPUT; + +// rev +typedef struct _POWER_INTERNAL_BOOTSTAT_CHECK_INTEGRITY_INPUT +{ + POWER_INFORMATION_LEVEL_INTERNAL InternalType; + ULONG Version; + ULONG EntryCount; + ULONG Reserved; + PRTL_BSD_ITEM Entries; +} POWER_INTERNAL_BOOTSTAT_CHECK_INTEGRITY_INPUT, *PPOWER_INTERNAL_BOOTSTAT_CHECK_INTEGRITY_INPUT; + +C_ASSERT(sizeof(POWER_INTERNAL_BOOTSTAT_CHECK_INTEGRITY_INPUT) == sizeof(POWER_INTERNAL_BOOTSTAT_GET_INPUT)); + +// rev +typedef struct _POWER_INTERNAL_BOOTSTAT_CHECK_INTEGRITY_OUTPUT +{ + BOOLEAN IntegrityOk; +} POWER_INTERNAL_BOOTSTAT_CHECK_INTEGRITY_OUTPUT, *PPOWER_INTERNAL_BOOTSTAT_CHECK_INTEGRITY_OUTPUT; + // rev typedef struct _POWER_INTERNAL_HOST_ENERGY_SAVER_STATE { @@ -836,22 +1056,132 @@ typedef struct _POWER_INTERNAL_HOST_ENERGY_SAVER_STATE BOOLEAN EsEnabledOnHost; } POWER_INTERNAL_HOST_ENERGY_SAVER_STATE, *PPOWER_INTERNAL_HOST_ENERGY_SAVER_STATE; +// rev +typedef struct _POWER_INTERNAL_IS_POFX_DEVICE_INPUT +{ + POWER_INFORMATION_INTERNAL_HEADER Header; + PVOID DeviceObject; +} POWER_INTERNAL_IS_POFX_DEVICE_INPUT, *PPOWER_INTERNAL_IS_POFX_DEVICE_INPUT; + +// rev +typedef struct _POWER_INTERNAL_POWER_TRANSITION_EXTENSION_AT_BOOT_OUTPUT +{ + UCHAR Data[32]; +} POWER_INTERNAL_POWER_TRANSITION_EXTENSION_AT_BOOT_OUTPUT, *PPOWER_INTERNAL_POWER_TRANSITION_EXTENSION_AT_BOOT_OUTPUT; + +// rev +typedef struct _POWER_INTERNAL_NOTIFY_USER_SHUTDOWN_STATUS_INPUT +{ + POWER_INFORMATION_LEVEL_INTERNAL InternalType; + ULONG Version; + BOOLEAN ShutdownInitiated; // 1 = initiated, 0 = cancelled +} POWER_INTERNAL_NOTIFY_USER_SHUTDOWN_STATUS_INPUT, *PPOWER_INTERNAL_NOTIFY_USER_SHUTDOWN_STATUS_INPUT; + +// rev +typedef struct _POWER_INTERNAL_AUTOCHK_CAUASED_REBOOT_INPUT +{ + POWER_INFORMATION_LEVEL_INTERNAL InternalType; + ULONG Version; +} POWER_INTERNAL_AUTOCHK_CAUASED_REBOOT_INPUT, *PPOWER_INTERNAL_AUTOCHK_CAUASED_REBOOT_INPUT; + +// rev +typedef struct _POWER_INTERNAL_READ_HIBERFILE_PAGE_INPUT +{ + POWER_INFORMATION_LEVEL_INTERNAL InternalType; + ULONG Version; + ULONG PageNumber; +} POWER_INTERNAL_READ_HIBERFILE_PAGE_INPUT, *PPOWER_INTERNAL_READ_HIBERFILE_PAGE_INPUT; + +// rev +typedef struct _POWER_INTERNAL_READ_HIBERFILE_PAGE_OUTPUT +{ + UCHAR PageData[PAGE_SIZE]; +} POWER_INTERNAL_READ_HIBERFILE_PAGE_OUTPUT, *PPOWER_INTERNAL_READ_HIBERFILE_PAGE_OUTPUT; + +// rev +typedef struct _POWER_INTERNAL_QUERY_INTEL_PEP_CAPABILITIES_INPUT +{ + POWER_INFORMATION_LEVEL_INTERNAL InternalType; + ULONG Version; +} POWER_INTERNAL_QUERY_INTEL_PEP_CAPABILITIES_INPUT, *PPOWER_INTERNAL_QUERY_INTEL_PEP_CAPABILITIES_INPUT; + +// rev +typedef struct _POWER_INTERNAL_QUERY_INTEL_PEP_CAPABILITIES_OUTPUT +{ + ULONG Capabilities[4]; +} POWER_INTERNAL_QUERY_INTEL_PEP_CAPABILITIES_OUTPUT, *PPOWER_INTERNAL_QUERY_INTEL_PEP_CAPABILITIES_OUTPUT; + +// rev +typedef struct _POWER_INTERNAL_AUTOCHK_CAUASED_REBOOT_OUTPUT +{ + BOOLEAN CausedReboot; +} POWER_INTERNAL_AUTOCHK_CAUASED_REBOOT_OUTPUT, *PPOWER_INTERNAL_AUTOCHK_CAUASED_REBOOT_OUTPUT; + +// rev +typedef struct _POWER_INTERNAL_TIME_BROKER_EXPIRATION_REASON_INPUT +{ + POWER_INFORMATION_INTERNAL_HEADER Header; + WCHAR Reason[64]; + ULONGLONG DueTime; +} POWER_INTERNAL_TIME_BROKER_EXPIRATION_REASON_INPUT, *PPOWER_INTERNAL_TIME_BROKER_EXPIRATION_REASON_INPUT; + +C_ASSERT(sizeof(POWER_INTERNAL_TIME_BROKER_EXPIRATION_REASON_INPUT) == 0x90); + +// rev +typedef struct _POWER_INTERNAL_POWER_REQUEST_TERMINAL_CORE_WINDOW_INPUT +{ + POWER_INFORMATION_INTERNAL_HEADER Header; + PVOID ProcessHandle; + PVOID PowerRequestPointer; + ULONG ReasonCode; + ULONG Reserved; +} POWER_INTERNAL_POWER_REQUEST_TERMINAL_CORE_WINDOW_INPUT, *PPOWER_INTERNAL_POWER_REQUEST_TERMINAL_CORE_WINDOW_INPUT; + +// rev +typedef struct _POWER_INTERNAL_WAKE_ON_VOICE_STATE_INPUT +{ + POWER_INFORMATION_LEVEL_INTERNAL InternalType; + ULONG Version; + BOOLEAN Enabled; // 1 = enable Wake on Voice, 0 = disable +} POWER_INTERNAL_WAKE_ON_VOICE_STATE_INPUT, *PPOWER_INTERNAL_WAKE_ON_VOICE_STATE_INPUT; + +// rev +typedef struct _POWER_INTERNAL_DEEP_SLEEP_BLOCK_INPUT +{ + POWER_INFORMATION_LEVEL_INTERNAL InternalType; + ULONG Version; + BOOLEAN Block; // 1 = block deep sleep, 0 = unblock +} POWER_INTERNAL_DEEP_SLEEP_BLOCK_INPUT, *PPOWER_INTERNAL_DEEP_SLEEP_BLOCK_INPUT; + // rev typedef struct _POWER_INTERNAL_PROCESSOR_BRANDED_FREQUENCY_INPUT { POWER_INFORMATION_LEVEL_INTERNAL InternalType; - PROCESSOR_NUMBER ProcessorNumber; // ULONG_MAX + ULONG Version; + PROCESSOR_NUMBER ProcessorNumber; // Optional: provide only when InputBufferLength == sizeof(POWER_INTERNAL_PROCESSOR_BRANDED_FREQUENCY_INPUT) (0x0C). Reserved must be 0. } POWER_INTERNAL_PROCESSOR_BRANDED_FREQUENCY_INPUT, *PPOWER_INTERNAL_PROCESSOR_BRANDED_FREQUENCY_INPUT; #define POWER_INTERNAL_PROCESSOR_BRANDED_FREQUENCY_VERSION 1 +C_ASSERT(sizeof(POWER_INTERNAL_PROCESSOR_BRANDED_FREQUENCY_INPUT) == 0x0C); + // rev typedef struct _POWER_INTERNAL_PROCESSOR_BRANDED_FREQUENCY_OUTPUT { - ULONG Version; + ULONG Version; // POWER_INTERNAL_PROCESSOR_BRANDED_FREQUENCY_VERSION ULONG NominalFrequency; // if (Domain) Prcb->PowerState.CheckContext.Domain.NominalFrequency else Prcb->MHz } POWER_INTERNAL_PROCESSOR_BRANDED_FREQUENCY_OUTPUT, *PPOWER_INTERNAL_PROCESSOR_BRANDED_FREQUENCY_OUTPUT; +C_ASSERT(sizeof(POWER_INTERNAL_PROCESSOR_BRANDED_FREQUENCY_OUTPUT) == 0x08); + +// rev +typedef struct _POWER_INTERNAL_SET_WAKE_ALARM_OVERRIDE_INPUT +{ + POWER_INFORMATION_INTERNAL_HEADER Header; + ULONGLONG WakeAlarmOverrideAc; + ULONGLONG WakeAlarmOverrideDc; +} POWER_INTERNAL_SET_WAKE_ALARM_OVERRIDE_INPUT, *PPOWER_INTERNAL_SET_WAKE_ALARM_OVERRIDE_INPUT; + // rev typedef struct _PROCESSOR_IDLE_VETO { @@ -871,6 +1201,204 @@ typedef struct _PLATFORM_IDLE_VETO UCHAR Increment; } PLATFORM_IDLE_VETO, *PPLATFORM_IDLE_VETO; +// rev +typedef struct _POWER_INTERNAL_SYSTEM_IDLE_LOOP_ENABLEMENT_INPUT +{ + POWER_INFORMATION_LEVEL_INTERNAL InternalType; + ULONG Version; +} POWER_INTERNAL_SYSTEM_IDLE_LOOP_ENABLEMENT_INPUT, *PPOWER_INTERNAL_SYSTEM_IDLE_LOOP_ENABLEMENT_INPUT; + +// rev +typedef struct _POWER_INTERNAL_SYSTEM_IDLE_LOOP_ENABLEMENT_OUTPUT +{ + ULONG IdleLoopEnabled; +} POWER_INTERNAL_SYSTEM_IDLE_LOOP_ENABLEMENT_OUTPUT, *PPOWER_INTERNAL_SYSTEM_IDLE_LOOP_ENABLEMENT_OUTPUT; + +// rev +typedef struct _POWER_INTERNAL_VM_PERF_CONTROL_SUPPORT_INPUT +{ + POWER_INFORMATION_LEVEL_INTERNAL InternalType; + ULONG Version; + ULONG Reserved1; +} POWER_INTERNAL_VM_PERF_CONTROL_SUPPORT_INPUT, *PPOWER_INTERNAL_VM_PERF_CONTROL_SUPPORT_INPUT; + +// rev +#define PPM_VMPCS_SUPPORTS_PERF_SET 0x00000001 // Can set explicit performance levels +#define PPM_VMPCS_SUPPORTS_AUTONOMOUS 0x00000002 // Supports autonomous (hardware-managed) mode +#define PPM_VMPCS_SUPPORTS_EPP 0x00000004 // Supports Energy Performance Preference (EPP) +#define PPM_VMPCS_SUPPORTS_BOOST 0x00000008 // Supports boost performance modes +#define PPM_VMPCS_SUPPORTS_TIME_WINDOW 0x00000010 // Supports time-window based control + +// rev +typedef struct _POWER_INTERNAL_VM_PERF_CONTROL_SUPPORT_OUTPUT +{ + // If OutputBuffer only 1 byte, just this flag returned for "VM perf-control supported". + UCHAR Supported; + // Reserved values (returned when OutputBuffer > 1 bytes). + UCHAR Reserved0; + UCHAR Reserved1; + UCHAR Reserved2; + // Extended details (returned when OutputBuffer >= 20 bytes). + ULONG MinPerfPercent; // Minimum performance percentage (0..100) + ULONG MaxPerfPercent; // Maximum performance percentage (0..100) + ULONG StepPerfPercent; // Step size for performance percentage (>=1) + ULONG Capabilities; // Bitmask of PPM_VMPCS_SUPPORTS_* flags +} POWER_INTERNAL_VM_PERF_CONTROL_SUPPORT_OUTPUT, *PPOWER_INTERNAL_VM_PERF_CONTROL_SUPPORT_OUTPUT; + +// rev +typedef struct _POWER_INTERNAL_SLEEP_DETAILED_DIAG_UPDATE_INPUT +{ + POWER_INFORMATION_LEVEL_INTERNAL InternalType; + ULONG Version; + BOOLEAN Enable; +} POWER_INTERNAL_SLEEP_DETAILED_DIAG_UPDATE_INPUT, *PPOWER_INTERNAL_SLEEP_DETAILED_DIAG_UPDATE_INPUT; + +// rev +typedef struct _POWER_INTERNAL_PROCESSOR_CLASS_BAND_STATS_INPUT +{ + POWER_INFORMATION_LEVEL_INTERNAL InternalType; + ULONG Version; +} POWER_INTERNAL_PROCESSOR_CLASS_BAND_STATS_INPUT, *PPOWER_INTERNAL_PROCESSOR_CLASS_BAND_STATS_INPUT; + +// rev +typedef struct _POWER_INTERNAL_HOST_GLOBAL_USER_PRESENCE_STATE_UPDATE_INPUT +{ + POWER_INFORMATION_LEVEL_INTERNAL InternalType; + ULONG Version; + BOOLEAN UserPresent; // 1 if user is present, 0 otherwise +} POWER_INTERNAL_HOST_GLOBAL_USER_PRESENCE_STATE_UPDATE_INPUT, *PPOWER_INTERNAL_HOST_GLOBAL_USER_PRESENCE_STATE_UPDATE_INPUT; + +// rev +/** + * The POWER_INTERNAL_IDLE_INTERVAL_STATS_INPUT structure is passed to internal power management routines + * to request idle interval statistics for a given processor package or node. + */ +typedef struct _POWER_INTERNAL_IDLE_INTERVAL_STATS_INPUT +{ + POWER_INFORMATION_LEVEL_INTERNAL InternalType; + ULONG Version; + ULONG Node; +} POWER_INTERNAL_IDLE_INTERVAL_STATS_INPUT, *PPOWER_INTERNAL_IDLE_INTERVAL_STATS_INPUT; + +// rev +/** + * The POWER_INTERNAL_IDLE_INTERVAL_PACKAGE structure contains a histogram of idle intervals, + * each entry representing the total time spent in a given duration bucket. + * The 37 buckets are logarithmically spaced to capture idle durations from ms up to seconds. + * Approximate bucket ranges: + * - Indices [0-2] = Very long idle (10-50 seconds) + * - Indices [3-5] = Long idle (2-10 seconds) + * - Indices [6-10] = Medium idle (100 ms-1 second) + * - Indices [11-15] = Short idle (10-100 ms) + * - Indices [16-36] = Very short idle (<10 ms, down to microseconds) + */ +typedef struct _POWER_INTERNAL_IDLE_INTERVAL_PACKAGE +{ + /** + * Idle interval histogram buckets. + * Each entry is a ULONGLONG value in 100-nanosecond units. + * There are 37 buckets, covering idle durations from microseconds + * up to tens of seconds. + */ + ULONGLONG IdleIntervals[37]; +} POWER_INTERNAL_IDLE_INTERVAL_PACKAGE, *PPOWER_INTERNAL_IDLE_INTERVAL_PACKAGE; + +// rev +/** + * The POWER_INTERNAL_IDLE_INTERVAL_STATS_OUTPUT structure contains the idle interval statistics. + */ +typedef struct _POWER_INTERNAL_IDLE_INTERVAL_STATS_OUTPUT +{ + POWER_INTERNAL_IDLE_INTERVAL_PACKAGE Package[2]; +} POWER_INTERNAL_IDLE_INTERVAL_STATS_OUTPUT, *PPOWER_INTERNAL_IDLE_INTERVAL_STATS_OUTPUT; + +// rev +#define PPM_PERF_BANKS_COUNT 2 +#define PPM_PERF_BANDS_COUNT 48 +#define PPM_PERF_METRICS_COUNT 3 +#define PPM_PERF_BANDS_SIZE sizeof(PPM_PERF_BAND_ENTRY) +#define PPM_PERF_STATS_SIZE (PPM_PERF_BANDS_COUNT * PPM_PERF_BANDS_SIZE) +#define PPM_PERF_DELTA_OFFSET 0xF8 // 248 bytes + +// rev +typedef struct _POWER_INTERNAL_PPM_PERF_FREQUENCY_BAND_STATS_BANK +{ + // Metric[0][0..47], Metric[1][0..47], Metric[2][0..47] + ULONGLONG Metric[PPM_PERF_METRICS_COUNT][PPM_PERF_BANDS_COUNT]; +} POWER_INTERNAL_PPM_PERF_FREQUENCY_BAND_STATS_BANK, PPOWER_INTERNAL_PM_PERF_FREQUENCY_BAND_STATS_BANK; + +// rev +typedef struct _POWER_INTERNAL_PPM_PERF_FREQUENCY_BAND_STATS_OUT +{ + POWER_INTERNAL_PPM_PERF_FREQUENCY_BAND_STATS_BANK Bank[PPM_PERF_BANKS_COUNT]; +} POWER_INTERNAL_PPM_PERF_FREQUENCY_BAND_STATS_OUT; + +// rev +typedef struct _POWER_INTERNAL_PROCESSOR_CLASS_BAND_STATS +{ + ULONGLONG Counter[PPM_PERF_METRICS_COUNT]; +} POWER_INTERNAL_PROCESSOR_CLASS_BAND_STATS, *PPOWER_INTERNAL_PROCESSOR_CLASS_BAND_STATS; + +// rev +typedef struct _POWER_INTERNAL_PROCESSOR_CLASS_BAND_STATS_OUTPUT +{ + POWER_INTERNAL_PROCESSOR_CLASS_BAND_STATS Band[PPM_PERF_BANDS_COUNT]; +} POWER_INTERNAL_PROCESSOR_CLASS_BAND_STATS_OUTPUT, *PPOWER_INTERNAL_PROCESSOR_CLASS_BAND_STATS_OUTPUT; + +// rev +typedef struct _POWER_INTERNAL_GET_ADAPTIVE_SESSION_STATE_INPUT +{ + POWER_INFORMATION_LEVEL_INTERNAL InternalType; + ULONG Version; + ULONG SessionStateId; + UCHAR Reserved[28]; +} POWER_INTERNAL_GET_ADAPTIVE_SESSION_STATE_INPUT, *PPOWER_INTERNAL_GET_ADAPTIVE_SESSION_STATE_INPUT; + +// rev +typedef struct _POWER_INTERNAL_GET_ADAPTIVE_SESSION_STATE_OUTPUT +{ + UCHAR Reserved[16]; +} POWER_INTERNAL_GET_ADAPTIVE_SESSION_STATE_OUTPUT, *PPOWER_INTERNAL_GET_ADAPTIVE_SESSION_STATE_OUTPUT; + +// rev +typedef struct _POWER_INTERNAL_SET_CONSOLE_LOCKED_STATE_INPUT +{ + POWER_INFORMATION_LEVEL_INTERNAL InternalType; + ULONG Version; + BOOLEAN Locked; // 1 if console is locked, 0 if unlocked +} POWER_INTERNAL_SET_CONSOLE_LOCKED_STATE_INPUT, *PPOWER_INTERNAL_SET_CONSOLE_LOCKED_STATE_INPUT; + +// rev +typedef struct _POWER_INTERNAL_FAN_IMPACT_STATS_INPUT +{ + POWER_INFORMATION_LEVEL_INTERNAL InternalType; + ULONG Version; +} POWER_INTERNAL_FAN_IMPACT_STATS_INPUT, *PPOWER_INTERNAL_FAN_IMPACT_STATS_INPUT; + +// rev +typedef struct _POWER_INTERNAL_FAN_IMPACT_STATS_OUTPUT +{ + ULONG BucketCountPlusTwo; + ULONGLONG Buckets[19]; +} POWER_INTERNAL_FAN_IMPACT_STATS_OUTPUT, *PPOWER_INTERNAL_FAN_IMPACT_STATS_OUTPUT; + +// rev +typedef struct _POWER_INTERNAL_FAN_RPM_BUCKETS_INPUT +{ + POWER_INFORMATION_LEVEL_INTERNAL InternalType; + ULONG Version; +} POWER_INTERNAL_FAN_RPM_BUCKETS_INPUT, *PPOWER_INTERNAL_FAN_RPM_BUCKETS_INPUT; + +// rev +typedef struct _POWER_INTERNAL_FAN_RPM_OUTPUT +{ + ULONG NumberOfFanRpmBuckets; + ULONG BucketMaxRpm[17]; + ULONG NoiseZoneMaxRpm[4]; +} POWER_INTERNAL_FAN_RPM_OUTPUT, *PPOWER_INTERNAL_FAN_RPM_OUTPUT; + +C_ASSERT(sizeof(POWER_INTERNAL_FAN_RPM_OUTPUT) == 0x58); + // rev typedef struct _POWER_INTERNAL_BOOTAPP_DIAGNOSTIC { @@ -878,16 +1406,449 @@ typedef struct _POWER_INTERNAL_BOOTAPP_DIAGNOSTIC ULONG BootAppFailureStatus; // bcdedit last status } POWER_INTERNAL_BOOTAPP_DIAGNOSTIC, *PPOWER_INTERNAL_BOOTAPP_DIAGNOSTIC; +// rev +typedef struct _POWER_INTERNAL_GET_ACPI_TIME_AND_ALARM_CAPABILITIES_INPUT +{ + POWER_INFORMATION_LEVEL_INTERNAL InternalType; + ULONG Version; + UCHAR Reserved[12]; +} POWER_INTERNAL_GET_ACPI_TIME_AND_ALARM_CAPABILITIES_INPUT, *PPOWER_INTERNAL_GET_ACPI_TIME_AND_ALARM_CAPABILITIES_INPUT; + +// rev +typedef struct _POWER_INTERNAL_GET_ACPI_TIME_AND_ALARM_CAPABILITIES_OUTPUT +{ + UCHAR Capabilities[20]; +} POWER_INTERNAL_GET_ACPI_TIME_AND_ALARM_CAPABILITIES_OUTPUT, *PPOWER_INTERNAL_GET_ACPI_TIME_AND_ALARM_CAPABILITIES_OUTPUT; + +// rev +typedef struct _POWER_INTERNAL_SOC_IDENTIFIER_OPERATION_INPUT +{ + POWER_INFORMATION_LEVEL_INTERNAL InternalType; + ULONG Version; + ULONG Action; + ULONG Domain; + ULONG Reserved[2]; +} POWER_INTERNAL_SOC_IDENTIFIER_OPERATION_INPUT, *PPOWER_INTERNAL_SOC_IDENTIFIER_OPERATION_INPUT; + +// rev +typedef struct _POWER_INTERNAL_SOC_IDENTIFIER_OPERATION_OUTPUT +{ + // Action 0 returns a USHORT maximum-length value. + // Action 1 returns a UTF-16 identifier blob. + UCHAR Data[ANYSIZE_ARRAY]; +} POWER_INTERNAL_SOC_IDENTIFIER_OPERATION_OUTPUT, *PPOWER_INTERNAL_SOC_IDENTIFIER_OPERATION_OUTPUT; + +// rev +typedef struct _POWER_INTERNAL_VMPERF_PRIORITY_SUPPORT_INPUT +{ + POWER_INFORMATION_LEVEL_INTERNAL InternalType; + ULONG Version; +} POWER_INTERNAL_VMPERF_PRIORITY_SUPPORT_INPUT, *PPOWER_INTERNAL_VMPERF_PRIORITY_SUPPORT_INPUT; + +// rev +typedef struct _POWER_INTERNAL_VMPERF_PRIORITY_SUPPORT_OUTPUT +{ + BOOLEAN VmThrottleSupportedAndConfigured; + ULONG VmThrottlePriorityCount; +} POWER_INTERNAL_VMPERF_PRIORITY_SUPPORT_OUTPUT, *PPOWER_INTERNAL_VMPERF_PRIORITY_SUPPORT_OUTPUT; + +// rev +typedef struct _POWER_INTERNAL_VMPERF_PRIORITY_CONFIG_INPUT +{ + POWER_INFORMATION_LEVEL_INTERNAL InternalType; + ULONG Version; + ULONG Action; + ULONG Domain; +} POWER_INTERNAL_VMPERF_PRIORITY_CONFIG_INPUT, *PPOWER_INTERNAL_VMPERF_PRIORITY_CONFIG_INPUT; + +// rev +typedef struct _POWER_INTERNAL_VMPERF_PRIORITY_CONFIG_OUTPUT +{ + BOOLEAN VmThrottleSupportedAndConfigured; + ULONG VmThrottlePriorityCount; +} POWER_INTERNAL_VMPERF_PRIORITY_CONFIG_OUTPUT, *PPOWER_INTERNAL_VMPERF_PRIORITY_CONFIG_OUTPUT; + +// rev +typedef struct _POWER_INTERNAL_DIRECTED_FX_ADD_TEST_DEVICE_INPUT +{ + POWER_INFORMATION_INTERNAL_HEADER Header; + ULONG Flags; + ULONG DeviceNameLength; + WCHAR DeviceName[ANYSIZE_ARRAY]; +} POWER_INTERNAL_DIRECTED_FX_ADD_TEST_DEVICE_INPUT, *PPOWER_INTERNAL_DIRECTED_FX_ADD_TEST_DEVICE_INPUT; + +// rev +typedef struct _POWER_INTERNAL_DIRECTED_FX_REMOVE_TEST_DEVICE_INPUT +{ + POWER_INFORMATION_INTERNAL_HEADER Header; + ULONG DeviceNameLength; + WCHAR DeviceName[ANYSIZE_ARRAY]; +} POWER_INTERNAL_DIRECTED_FX_REMOVE_TEST_DEVICE_INPUT, *PPOWER_INTERNAL_DIRECTED_FX_REMOVE_TEST_DEVICE_INPUT; + +// rev +typedef struct _POWER_INTERNAL_DIRECTED_FX_SET_MODE_INPUT +{ + POWER_INFORMATION_INTERNAL_HEADER Header; + BOOLEAN PermissiveMode; +} POWER_INTERNAL_DIRECTED_FX_SET_MODE_INPUT, *PPOWER_INTERNAL_DIRECTED_FX_SET_MODE_INPUT; + +// rev +typedef struct _POWER_INTERNAL_DIRECTED_DRIPS_QUERY_CAPABILITIES_OUTPUT +{ + BOOLEAN SupportsDirectedFxTestDevice; + BOOLEAN SupportsDirectedFxModeControl; +} POWER_INTERNAL_DIRECTED_DRIPS_QUERY_CAPABILITIES_OUTPUT, *PPOWER_INTERNAL_DIRECTED_DRIPS_QUERY_CAPABILITIES_OUTPUT; + +// rev +typedef struct _POWER_INTERNAL_REGISTER_POWER_PLANE_INPUT +{ + POWER_INFORMATION_INTERNAL_HEADER Header; + ULONG_PTR ClientHandle; + ULONG_PTR DataSize; + UCHAR Data[ANYSIZE_ARRAY]; +} POWER_INTERNAL_REGISTER_POWER_PLANE_INPUT, *PPOWER_INTERNAL_REGISTER_POWER_PLANE_INPUT; + +// rev +typedef struct _POWER_INTERNAL_DIRECTED_DRIPS_DEVICE_FLAGS_INPUT +{ + POWER_INFORMATION_INTERNAL_HEADER Header; + PVOID DeviceObject; + ULONG Flags; + ULONG Reserved; +} POWER_INTERNAL_DIRECTED_DRIPS_DEVICE_FLAGS_INPUT, *PPOWER_INTERNAL_DIRECTED_DRIPS_DEVICE_FLAGS_INPUT; + +// rev +typedef struct _POWER_INTERNAL_RETRIEVE_HIBERFILE_RESUME_CONTEXT_OUTPUT +{ + ULONG Version; + ULONG DataSize; + ULONG EntryCount; + UCHAR Data[ANYSIZE_ARRAY]; +} POWER_INTERNAL_RETRIEVE_HIBERFILE_RESUME_CONTEXT_OUTPUT, *PPOWER_INTERNAL_RETRIEVE_HIBERFILE_RESUME_CONTEXT_OUTPUT; + +// rev +typedef struct _POWER_INTERNAL_QUERY_SLEEPSTUDY_HELPER_ROUTINE_BLOCK_OUTPUT +{ + PVOID HelperRoutineBlock; +} POWER_INTERNAL_QUERY_SLEEPSTUDY_HELPER_ROUTINE_BLOCK_OUTPUT, *PPOWER_INTERNAL_QUERY_SLEEPSTUDY_HELPER_ROUTINE_BLOCK_OUTPUT; + +// rev +typedef struct _POWER_INTERNAL_CLEAR_CONSTRAINTS_INPUT +{ + POWER_INFORMATION_INTERNAL_HEADER Header; + PVOID DeviceObject; +} POWER_INTERNAL_CLEAR_CONSTRAINTS_INPUT, *PPOWER_INTERNAL_CLEAR_CONSTRAINTS_INPUT; + +// rev +typedef struct _POWER_INTERNAL_VM_PERF_CONTROL_CONFIG_INPUT +{ + POWER_INFORMATION_INTERNAL_HEADER Header; + ULONG Parameter0; + ULONG Parameter1; + ULONG Parameter2; + ULONG Parameter3; + ULONG Parameter4; + BOOLEAN Parameter5; + UCHAR Reserved[3]; +} POWER_INTERNAL_VM_PERF_CONTROL_CONFIG_INPUT, *PPOWER_INTERNAL_VM_PERF_CONTROL_CONFIG_INPUT; + +// rev +typedef struct _POWER_INTERNAL_VM_PERF_CONTROL_CONFIG_OUTPUT +{ + ULONG Value0; + ULONG Value1; +} POWER_INTERNAL_VM_PERF_CONTROL_CONFIG_OUTPUT, *PPOWER_INTERNAL_VM_PERF_CONTROL_CONFIG_OUTPUT; + +// rev +typedef struct _POWER_INTERNAL_CONCURRENCY_STATS_OUTPUT +{ + ULONG Data[ANYSIZE_ARRAY]; +} POWER_INTERNAL_CONCURRENCY_STATS_OUTPUT, *PPOWER_INTERNAL_CONCURRENCY_STATS_OUTPUT; + +// rev +typedef struct _PROCESSOR_INTERNAL_QUERY_MEASUREMENT_CAPABILITIES +{ + POWER_INFORMATION_INTERNAL_HEADER Header; +} PROCESSOR_INTERNAL_QUERY_MEASUREMENT_CAPABILITIES, *PPROCESSOR_INTERNAL_QUERY_MEASUREMENT_CAPABILITIES; + +// rev +typedef struct _PROCESSOR_INTERNAL_QUERY_MEASUREMENT_CAPABILITIES_OUTPUT +{ + ULONG Capabilities; +} PROCESSOR_INTERNAL_QUERY_MEASUREMENT_CAPABILITIES_OUTPUT, *PPROCESSOR_INTERNAL_QUERY_MEASUREMENT_CAPABILITIES_OUTPUT; + +// rev +typedef struct _PROCESSOR_INTERNAL_QUERY_MEASUREMENT_VALUES +{ + POWER_INFORMATION_INTERNAL_HEADER Header; + ULONG Processor; +} PROCESSOR_INTERNAL_QUERY_MEASUREMENT_VALUES, *PPROCESSOR_INTERNAL_QUERY_MEASUREMENT_VALUES; + +// rev +typedef struct _PROCESSOR_INTERNAL_QUERY_MEASUREMENT_VALUE_ENTRY +{ + ULONGLONG Value[3]; +} PROCESSOR_INTERNAL_QUERY_MEASUREMENT_VALUE_ENTRY, *PPROCESSOR_INTERNAL_QUERY_MEASUREMENT_VALUE_ENTRY; + +// rev +typedef struct _PROCESSOR_INTERNAL_QUERY_MEASUREMENT_VALUES_OUTPUT +{ + ULONG EntryCount; + ULONG Reserved; + PROCESSOR_INTERNAL_QUERY_MEASUREMENT_VALUE_ENTRY Entries[ANYSIZE_ARRAY]; +} PROCESSOR_INTERNAL_QUERY_MEASUREMENT_VALUES_OUTPUT, *PPROCESSOR_INTERNAL_QUERY_MEASUREMENT_VALUES_OUTPUT; + +// rev +typedef struct _POWER_INTERNAL_PREPARE_FOR_SYSTEM_INITIATED_REBOOT_INPUT +{ + POWER_INFORMATION_INTERNAL_HEADER Header; +} POWER_INTERNAL_PREPARE_FOR_SYSTEM_INITIATED_REBOOT_INPUT, *PPOWER_INTERNAL_PREPARE_FOR_SYSTEM_INITIATED_REBOOT_INPUT; + +// rev +typedef struct _POWER_INTERNAL_OVERRIDE_SYSTEM_INITIATED_REBOOT_STATE_INPUT +{ + POWER_INFORMATION_INTERNAL_HEADER Header; + ULONG State; + ULONG Reserved; +} POWER_INTERNAL_OVERRIDE_SYSTEM_INITIATED_REBOOT_STATE_INPUT, *PPOWER_INTERNAL_OVERRIDE_SYSTEM_INITIATED_REBOOT_STATE_INPUT; + +// rev +typedef struct _POWER_INTERNAL_UNREGISTER_SHUTDOWN_NOTIFICATION_INPUT +{ + POWER_INFORMATION_INTERNAL_HEADER Header; + HANDLE ProcessId; + HANDLE ThreadId; +} POWER_INTERNAL_UNREGISTER_SHUTDOWN_NOTIFICATION_INPUT, *PPOWER_INTERNAL_UNREGISTER_SHUTDOWN_NOTIFICATION_INPUT; + +// rev +typedef struct _POWER_INTERNAL_MANAGE_TRANSITION_STATE_RECORD_INPUT +{ + POWER_INFORMATION_INTERNAL_HEADER Header; + ULONG Action; + ULONG Reserved0; + HANDLE ProcessId; + HANDLE ThreadId; + ULONG Reason; + ULONG CallbackType; + PVOID CallbackContext; +} POWER_INTERNAL_MANAGE_TRANSITION_STATE_RECORD_INPUT, *PPOWER_INTERNAL_MANAGE_TRANSITION_STATE_RECORD_INPUT; + +// rev +typedef struct _POWER_INTERNAL_SUSPEND_RESUME_REQUEST_INPUT +{ + POWER_INFORMATION_INTERNAL_HEADER Header; + UCHAR Data[12]; +} POWER_INTERNAL_SUSPEND_RESUME_REQUEST_INPUT, *PPOWER_INTERNAL_SUSPEND_RESUME_REQUEST_INPUT; + +// rev +typedef struct _POWER_INTERNAL_ENERGY_ESTIMATION_ENTRY +{ + ULONG Data[4]; +} POWER_INTERNAL_ENERGY_ESTIMATION_ENTRY, *PPOWER_INTERNAL_ENERGY_ESTIMATION_ENTRY; + +// rev +typedef struct _POWER_INTERNAL_ENERGY_ESTIMATION_INFO_OUTPUT +{ + ULONG EntryCount; + POWER_INTERNAL_ENERGY_ESTIMATION_ENTRY Entries[2]; +} POWER_INTERNAL_ENERGY_ESTIMATION_INFO_OUTPUT, *PPOWER_INTERNAL_ENERGY_ESTIMATION_INFO_OUTPUT; + +// rev +typedef struct _POWER_INTERNAL_NOTIFY_WIN32K_POWER_REQUEST_INPUT +{ + POWER_INFORMATION_INTERNAL_HEADER Header; + ULONG RequestIndex; +} POWER_INTERNAL_NOTIFY_WIN32K_POWER_REQUEST_INPUT, *PPOWER_INTERNAL_NOTIFY_WIN32K_POWER_REQUEST_INPUT; + +C_ASSERT(sizeof(POWER_INTERNAL_NOTIFY_WIN32K_POWER_REQUEST_INPUT) == 0x0C); + +// rev +typedef struct _POWER_INTERNAL_PDC_AGENT_SESSION_QUERY_INPUT +{ + POWER_INFORMATION_INTERNAL_HEADER Header; + ULONG QueryKey; +} POWER_INTERNAL_PDC_AGENT_SESSION_QUERY_INPUT, *PPOWER_INTERNAL_PDC_AGENT_SESSION_QUERY_INPUT; + +C_ASSERT(sizeof(POWER_INTERNAL_PDC_AGENT_SESSION_QUERY_INPUT) == 0x0C); + +// rev +typedef struct _POWER_INTERNAL_SESSION_CONNECTION_INFO_V2 +{ + BOOLEAN Connected; + UCHAR Reserved0[3]; + ULONG ConnectionType; +} POWER_INTERNAL_SESSION_CONNECTION_INFO_V2, *PPOWER_INTERNAL_SESSION_CONNECTION_INFO_V2; + +// rev +typedef struct _POWER_INTERNAL_ADAPTIVE_SESSION_STATE_REQUEST +{ + ULONGLONG Field0; + ULONGLONG Field1; + ULONGLONG Field2; + ULONG Field3; + ULONG Reserved; +} POWER_INTERNAL_ADAPTIVE_SESSION_STATE_REQUEST, *PPOWER_INTERNAL_ADAPTIVE_SESSION_STATE_REQUEST; + +// rev +typedef struct _POWER_INTERNAL_SESSION_CONNECTION_CHANGE_V2_INPUT +{ + POWER_INFORMATION_INTERNAL_HEADER Header; + POWER_INTERNAL_SESSION_CONNECTION_INFO_V2 ConnectionInfo; + POWER_INTERNAL_ADAPTIVE_SESSION_STATE_REQUEST SessionStateRequest; +} POWER_INTERNAL_SESSION_CONNECTION_CHANGE_V2_INPUT, *PPOWER_INTERNAL_SESSION_CONNECTION_CHANGE_V2_INPUT; + +C_ASSERT(sizeof(POWER_INTERNAL_SESSION_CONNECTION_CHANGE_V2_INPUT) == 0x30); + +// rev +typedef struct _POWER_INFORMATION_ENERGY_TRACKER_CREATE_INPUT +{ + ULONG Version; + ULONG Flags; + ULONG Reserved; +} POWER_INFORMATION_ENERGY_TRACKER_CREATE_INPUT, *PPOWER_INFORMATION_ENERGY_TRACKER_CREATE_INPUT; + +// rev +typedef struct _POWER_INFORMATION_ENERGY_TRACKER_CREATE_OUTPUT +{ + HANDLE QueryHandle; +} POWER_INFORMATION_ENERGY_TRACKER_CREATE_OUTPUT, *PPOWER_INFORMATION_ENERGY_TRACKER_CREATE_OUTPUT; + +// rev +typedef struct _POWER_INFORMATION_ENERGY_TRACKER_QUERY_INPUT +{ + HANDLE QueryHandle; +} POWER_INFORMATION_ENERGY_TRACKER_QUERY_INPUT, *PPOWER_INFORMATION_ENERGY_TRACKER_QUERY_INPUT; + +// rev +typedef struct _POWER_INFORMATION_ENERGY_TRACKER_QUERY_OUTPUT +{ + ULONG Version; + ULONG DataType; + ULONG DataSize; + // BYTE Data[...]; // optional payload follows +} POWER_INFORMATION_ENERGY_TRACKER_QUERY_OUTPUT, *PPOWER_INFORMATION_ENERGY_TRACKER_QUERY_OUTPUT; + +// rev +DEFINE_GUID(PopBlackBoxScmGuid, 0x45F9D5A3, 0xE1D0, 0x8891, 0x07, 0x26, 0xFB, 0x1D, 0x71, 0xAD, 0x11, 0xB8); +DEFINE_GUID(PopBlackBoxBsdGuid, 0x4E01CC45, 0xF573, 0x08DF, 0x0E, 0xC1, 0x0B, 0x0E, 0xBA, 0x42, 0x97, 0x6A); +DEFINE_GUID(PopBlackBoxPnpGuid, 0x4CD6532A, 0xB763, 0x1941, 0x57, 0x45, 0x7D, 0x91, 0xB5, 0xED, 0xB1, 0xB1); +DEFINE_GUID(PopBlackBoxAcpiGuid, 0x429FF755, 0x3B2E, 0xA98B, 0x8C, 0x52, 0x06, 0x81, 0xA1, 0x31, 0xC1, 0x80); +DEFINE_GUID(PopBlackBoxPoIrpGuid, 0x4A654DDB, 0x2523, 0xDB46, 0x0C, 0x65, 0xC9, 0x83, 0xF0, 0xE9, 0x13, 0x9A); +DEFINE_GUID(PopBlackBoxWinLogonNotifyGuid, 0x4E3EAA07, 0x6B2D, 0x3E93, 0x3B, 0xC6, 0x3C, 0x0E, 0x6D, 0x91, 0x1A, 0xA4); +DEFINE_GUID(PopBlackBoxPdcLockGuid, 0x4E912A6E, 0x33DB, 0xDDBB, 0x84, 0x8A, 0x7B, 0x99, 0xE1, 0x5D, 0x42, 0x9E); +DEFINE_GUID(PopBlackBoxPoPepWorkOrderGuid, 0x42750E88, 0xE0E8, 0x5A55, 0x0D, 0x03, 0x45, 0xAF, 0xB3, 0xF1, 0x33, 0xF9); +DEFINE_GUID(PopBlackBoxPoPowerWatchdogGuid, 0x44675326, 0x5545, 0xF79E, 0x55, 0x31, 0xE3, 0x3A, 0x63, 0x81, 0x69, 0xAE); +DEFINE_GUID(PopBlackBoxPnpEventWorkerGuid, 0x4131386C, 0x8BEF, 0xF310, 0x4A, 0x68, 0x1E, 0xFA, 0x44, 0x0A, 0xB1, 0xB1); +DEFINE_GUID(PopBlackBoxPnpDeviceCompletionQueueGuid, 0x452E8590, 0xC129, 0x4D5E, 0x68, 0xCA, 0x00, 0xF7, 0x45, 0x7F, 0x71, 0xBC); +DEFINE_GUID(PopBlackBoxPnpDelayedRemoveWorkerGuid, 0x4D9CFF3A, 0x7392, 0xA43B, 0x08, 0xED, 0xCD, 0x65, 0xAA, 0x50, 0x31, 0xBA); +DEFINE_GUID(PopBlackBoxDxgDisplayGuid, 0x44D6ED00, 0xB3BE, 0xB7EE, 0x1C, 0x0F, 0xF8, 0x2D, 0xA9, 0xC1, 0x60, 0xAD); +DEFINE_GUID(PopBlackBoxCrashedProcessGuid, 0x4367A550, 0xBE84, 0xD651, 0x94, 0x1F, 0x63, 0x2B, 0x79, 0xAB, 0x63, 0x8E); +DEFINE_GUID(PopBlackBoxUsoCommitGuid, 0x4CDA57F3, 0x6DE4, 0xC85A, 0x0E, 0x4F, 0x85, 0x85, 0xA8, 0x5C, 0x8F, 0xE8); +DEFINE_GUID(PopBlackBoxWheaGuid, 0x457D912A, 0x32D3, 0xEA49, 0x0F, 0xC5, 0x3E, 0xF2, 0x92, 0x9D, 0xDE, 0x6B); +DEFINE_GUID(PopBlackBoxNtfsGuid, 0x4213940D, 0x00AF, 0xE9C4, 0x20, 0xBC, 0xB5, 0x19, 0x37, 0xCD, 0x16, 0x80); +DEFINE_GUID(PopBlackBoxWinLogonGuid, 0x4AF1A719, 0x80CC, 0x79CF, 0x0C, 0x1E, 0xB7, 0x6F, 0xF2, 0x9F, 0xE9, 0x7B); +DEFINE_GUID(PopBlackBoxExplorerLogonTasksGuid, 0x4D93B9AC, 0xAA9A, 0x6517, 0x0A, 0x03, 0x93, 0x6E, 0x66, 0x62, 0x6D, 0x08); +DEFINE_GUID(PopBlackBoxExplorerCoreStartupGuid, 0x4E121623, 0xF5A6, 0xB2E1, 0x0F, 0xA8, 0x08, 0x29, 0xBA, 0x84, 0x83, 0x98); +DEFINE_GUID(PopBlackBoxUserModeLKDReasonGuid, 0x44BEB1A5, 0xC1B9, 0x41DF, 0x22, 0x5E, 0xBC, 0x66, 0xF1, 0xDA, 0x5C, 0x9D); +DEFINE_GUID(PopBlackBoxCodeIntegrityGuid, 0x44A03CF4, 0x4EE7, 0x6BD8, 0x0A, 0x33, 0x73, 0xE6, 0x43, 0x73, 0x9A, 0x0C); +DEFINE_GUID(PoBlackBoxIdCsrGuid, 0x470BC061, 0x42C1, 0xADD0, 0x0C, 0xB1, 0x8E, 0x99, 0xF2, 0xEF, 0x68, 0xFB); +DEFINE_GUID(PoBlackBoxIdSmGuid, 0x42D2AC4A, 0xD368, 0xF58F, 0x25, 0xA7, 0x6A, 0xC2, 0xDB, 0x76, 0x97, 0x8F); + +// rev +typedef struct _POWER_INFORMATION_BBR_DIRECT_ACCESS_REQUEST_CATEGORY +{ + ULONG Index; + PCSTR Name; + GUID Guid; +} POWER_INFORMATION_BBR_DIRECT_ACCESS_REQUEST_CATEGORY, *PPOWER_INFORMATION_BBR_DIRECT_ACCESS_REQUEST_CATEGORY; + +// rev +//CONST POWER_INFORMATION_BBR_DIRECT_ACCESS_REQUEST_CATEGORY BlackBoxCategories[24] = +//{ +// { 0, "SCM", PopBlackBoxScmGuid }, +// { 1, "BSD", PopBlackBoxBsdGuid }, +// { 2, "PNP", PopBlackBoxPnpGuid }, +// { 3, "ACPI", PopBlackBoxAcpiGuid }, +// { 4, "POIRP", PopBlackBoxPoIrpGuid }, +// { 5, "WINLOGON-NOTIFY", PopBlackBoxWinLogonNotifyGuid }, +// { 6, "PDCLOCK", PopBlackBoxPdcLockGuid }, +// { 7, "PEPWORKORDER", PopBlackBoxPoPepWorkOrderGuid }, +// { 8, "POWERWATCHDOG", PopBlackBoxPoPowerWatchdogGuid }, +// { 9, "PNPEVENTWORKER", PopBlackBoxPnpEventWorkerGuid }, +// { 10, "DEVICECOMPLETIONQUEUE", PopBlackBoxPnpDeviceCompletionQueueGuid }, +// { 11, "PNPDELAYEDREMOVEWORKER", PopBlackBoxPnpDelayedRemoveWorkerGuid }, +// { 12, "DXG-DISPLAY", PopBlackBoxDxgDisplayGuid }, +// { 13, "CrashedProcess", PopBlackBoxCrashedProcessGuid }, +// { 14, "UsoCommit", PopBlackBoxUsoCommitGuid }, +// { 15, "WHEA", PopBlackBoxWheaGuid }, +// { 16, "NTFS", PopBlackBoxNtfsGuid }, +// { 17, "Winlogon", PopBlackBoxWinLogonGuid }, +// { 18, "Explorer logon tasks", PopBlackBoxExplorerLogonTasksGuid }, +// { 19, "Explorer core startup", PopBlackBoxExplorerCoreStartupGuid }, +// { 20, "User mode LKD API caller data", PopBlackBoxUserModeLKDReasonGuid }, +// { 21, "CI", PopBlackBoxCodeIntegrityGuid }, +// { 22, "CSR", PoBlackBoxIdCsrGuid }, +// { 23, "SM", PoBlackBoxIdSmGuid }, +//}; + +// rev +typedef struct _POWER_INFORMATION_BBR_UPDATE_REQUEST_INPUT +{ + ULONG Version; + ULONG Flags; + ULONG_PTR Reserved0; // must be zero + ULONG_PTR Reserved1; // must be zero + ULONG_PTR Reserved2; // must be zero +} POWER_INFORMATION_BBR_UPDATE_REQUEST_INPUT, *PPOWER_INFORMATION_BBR_UPDATE_REQUEST_INPUT; + +// rev +#define POWER_INFORMATION_BBR_DIRECT_ACCESS_REQUEST_MAX_CATEGORY RTL_NUMBER_OF(BlackBoxCategories) +#define POWER_INFORMATION_BBR_DIRECT_ACCESS_REQUEST_CATEGORY_SHIFT 0 +#define POWER_INFORMATION_BBR_DIRECT_ACCESS_REQUEST_CATEGORY_MASK_RAW 0x0000FFFF +#define POWER_INFORMATION_BBR_DIRECT_ACCESS_REQUEST_CATEGORY_MASK_DIRECT 0x0000001F +#define POWER_INFORMATION_BBR_DIRECT_ACCESS_REQUEST_MODIFIERS_MASK 0xFFFF0000 + +// rev +#define POWER_INFORMATION_BBR_DIRECT_ACCESS_REQUEST_FLAGS(category, modifiers) \ + ((ULONG)(((category) & POWER_INFORMATION_BBR_DIRECT_ACCESS_REQUEST_CATEGORY_MASK_RAW << POWER_INFORMATION_BBR_DIRECT_ACCESS_REQUEST_CATEGORY_SHIFT) | \ + ((ULONG)(modifiers) & POWER_INFORMATION_BBR_DIRECT_ACCESS_REQUEST_MODIFIERS_MASK))) + +// rev +typedef struct _POWER_INFORMATION_BBR_DIRECT_ACCESS_REQUEST_INPUT +{ + ULONG Version; + union + { + ULONG Flags; + struct + { + ULONG Category : 5; // Index from POWER_INFORMATION_BBR_DIRECT_ACCESS_REQUEST_CATEGORY + ULONG Reserved : 11; + ULONG Modifiers : 16; + }; + }; + ULONG_PTR Offset; + ULONG_PTR Length; +} POWER_INFORMATION_BBR_DIRECT_ACCESS_REQUEST_INPUT, *PPOWER_INFORMATION_BBR_DIRECT_ACCESS_REQUEST_INPUT; + +// rev +typedef struct _POWER_INFORMATION_BBR_DIRECT_ACCESS_RESPONSE_OUTPUT +{ + PVOID UserMappingBase; + SIZE_T UserMappingSize; +} POWER_INFORMATION_BBR_DIRECT_ACCESS_RESPONSE_OUTPUT, *PPOWER_INFORMATION_BBR_DIRECT_ACCESS_RESPONSE_OUTPUT; + #if (PHNT_MODE != PHNT_MODE_KERNEL) /** * The NtPowerInformation routine sets or retrieves system power information. * - * @param InformationLevel Specifies the requested information level, which indicates the specific power information to be set or retrieved. - * @param InputBuffer Optional pointer to a caller-allocated input buffer. - * @param InputBufferLength Size, in bytes, of the buffer at InputBuffer. - * @param OutputBuffer Optional pointer to an output buffer. The type depends on the InformationLevel requested. - * @param OutputBufferLength Size, in bytes, of the output buffer. - * @return Successful or errant status. + * \param InformationLevel Specifies the requested information level, which indicates the specific power information to be set or retrieved. + * \param InputBuffer Optional pointer to a caller-allocated input buffer. + * \param InputBufferLength Size, in bytes, of the buffer at InputBuffer. + * \param OutputBuffer Optional pointer to an output buffer. The type depends on the InformationLevel requested. + * \param OutputBufferLength Size, in bytes, of the output buffer. + * \return Successful or errant status. + * \sa https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/wdm/nf-wdm-ntpowerinformation */ NTSYSCALLAPI NTSTATUS @@ -899,15 +1860,15 @@ NtPowerInformation( _Out_writes_bytes_opt_(OutputBufferLength) PVOID OutputBuffer, _In_ ULONG OutputBufferLength ); -#endif /** - * Enables an application to inform the system that it is in use, - * thereby preventing the system from entering sleep or turning off the display while the application is running. + * The NtSetThreadExecutionState routine informs the system of execution requirements, * - * @param NewFlags New execution state flags. - * @param PreviousFlags Pointer to receive the previous execution state flags. - * @return Successful or errant status. + * in order to prevent the system from entering sleep or turning off the display while the application is running. + * \param NewFlags New execution state flags. + * \param PreviousFlags Pointer to receive the previous execution state flags. + * \return Successful or errant status. + * \sa https://learn.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-setthreadexecutionstate */ NTSYSCALLAPI NTSTATUS @@ -916,13 +1877,14 @@ NtSetThreadExecutionState( _In_ EXECUTION_STATE NewFlags, // ES_* flags _Out_ EXECUTION_STATE *PreviousFlags ); +#endif // (PHNT_MODE != PHNT_MODE_KERNEL) #if (PHNT_VERSION < PHNT_WINDOWS_7) /** - * Requests the system resume latency. + * The NtRequestWakeupLatency routine requests the system resume latency. * - * @param latency The desired latency time. - * @return Successful or errant status. + * \param latency The desired latency time. + * \return Successful or errant status. */ NTSYSCALLAPI NTSTATUS @@ -930,16 +1892,17 @@ NTAPI NtRequestWakeupLatency( _In_ LATENCY_TIME latency ); -#endif +#endif // (PHNT_VERSION < PHNT_WINDOWS_7) /** - * Initiates a power action of the current system. + * The NtInitiatePowerAction routine initiates a shutdown and optional restart of the specified computer. * - * @param SystemAction The system power action. - * @param LightestSystemState The lightest system power state. - * @param Flags Flags for the power action. - * @param Asynchronous Whether the action is asynchronous. - * @return Successful or errant status. + * \param SystemAction The system power action. + * \param LightestSystemState The lightest system power state. + * \param Flags Flags for the power action. + * \param Asynchronous Whether the action is asynchronous. + * \return Successful or errant status. + * \sa https://learn.microsoft.com/en-us/windows/win32/api/winreg/nf-winreg-initiatesystemshutdownw */ NTSYSCALLAPI NTSTATUS @@ -952,13 +1915,13 @@ NtInitiatePowerAction( ); /** - * Initiates a power action of the current system. Depending on the Flags parameter, the function either - * suspends operation immediately or requests permission from all applications and device drivers before doing so. + * The NtSetSystemPowerState routine initiates a suspension and optional forced shutdown of the specified computer. * - * @param SystemAction The system power action. - * @param LightestSystemState The lightest system power state. - * @param Flags Flags for the power action. - * @return Successful or errant status. + * \param SystemAction The system power action. + * \param LightestSystemState The lightest system power state. + * \param Flags Flags for the power action. + * \return Successful or errant status. + * \sa https://learn.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-setsystempowerstate */ NTSYSCALLAPI NTSTATUS @@ -970,12 +1933,12 @@ NtSetSystemPowerState( ); /** - * Retrieves the current power state of the specified device. This function cannot be used to query the power state of a display device. + * The NtGetDevicePowerState routine retrieves the current power state of the specified device. * - * @param Device A handle to an object on the device, such as a file or socket, or a handle to the device itself. - * @param State A pointer to the variable that receives the power state. - * @return Successful or errant status. - * @remarks An application can use NtGetDevicePowerState to determine whether a device is in the working state or a low-power state. + * \param Device A handle to an object on the device, such as a file or socket, or a handle to the device itself. + * \param State A pointer to the variable that receives the power state. + * \return Successful or errant status. + * \remarks An application can use NtGetDevicePowerState to determine whether a device is in the working state or a low-power state. * If the device is in a low-power state, accessing the device may cause it to either queue or fail any I/O requests, or transition the device into the working state. * The exact behavior depends on the implementation of the device. */ @@ -988,9 +1951,9 @@ NtGetDevicePowerState( ); /** - * Checks if the system resume is automatic. - * - * @return BOOLEAN TRUE if the system resume is automatic, FALSE otherwise. + * The NtIsSystemResumeAutomatic routine checks if the system resume is automatic. + + * \return BOOLEAN TRUE if the system resume is automatic, FALSE otherwise. */ NTSYSCALLAPI BOOLEAN @@ -999,4 +1962,4 @@ NtIsSystemResumeAutomatic( VOID ); -#endif +#endif // _NTPOAPI_H diff --git a/ntpsapi.h b/ntpsapi.h index 2e6e04a..eabcfdf 100644 --- a/ntpsapi.h +++ b/ntpsapi.h @@ -148,6 +148,10 @@ // Process information structures // +/** + * The PEB_LDR_DATA structure contains information about the loaded modules for the process. + * \sa https://learn.microsoft.com/en-us/windows/win32/api/winternl/ns-winternl-peb_ldr_data + */ typedef struct _PEB_LDR_DATA { ULONG Length; @@ -161,209 +165,222 @@ typedef struct _PEB_LDR_DATA HANDLE ShutdownThreadId; } PEB_LDR_DATA, *PPEB_LDR_DATA; +/** + * The INITIAL_TEB structure contains information about the initial stack for a thread. + * This structure is used when creating a new thread to specify the stack boundaries and allocation base. + * It also contains information about the previous stack if the thread is being recreated. + */ typedef struct _INITIAL_TEB { struct { - PVOID OldStackBase; - PVOID OldStackLimit; + PVOID OldStackBase; // Pointer to the base address of the previous stack. + PVOID OldStackLimit; // Pointer to the limit address of the previous stack. } OldInitialTeb; - PVOID StackBase; - PVOID StackLimit; - PVOID StackAllocationBase; + PVOID StackBase; // Pointer to the base address of the new stack. + PVOID StackLimit; // Pointer to the limit address of the new stack. + PVOID StackAllocationBase; // Pointer to the base address where the stack was allocated. } INITIAL_TEB, *PINITIAL_TEB; +// +// NtQueryInformationProcess/NtSetInformationProcess types +// + #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) // s: 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: PROCESS_HANDLE_TRACING_ENABLE[_EX] or void to disable - ProcessIoPriority, // qs: IO_PRIORITY_HINT - ProcessExecuteFlags, // qs: ULONG (MEM_EXECUTE_OPTION_*) - 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[]; s: void - 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, // s: PROCESS_DYNAMIC_FUNCTION_TABLE_INFORMATION - 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 - ProcessHandleTable, // q: ULONG[] // since WINBLUE - ProcessCheckStackExtentsMode, // qs: ULONG // KPROCESS->CheckStackExtents (CFG) - ProcessCommandLineInformation, // q: UNICODE_STRING // 60 - ProcessProtectionInformation, // q: PS_PROTECTION - ProcessMemoryExhaustion, // s: PROCESS_MEMORY_EXHAUSTION_INFO // since THRESHOLD - ProcessFaultInformation, // s: PROCESS_FAULT_INFORMATION - ProcessTelemetryIdInformation, // q: PROCESS_TELEMETRY_ID_INFORMATION - ProcessCommitReleaseInformation, // qs: PROCESS_COMMIT_RELEASE_INFORMATION - ProcessDefaultCpuSetsInformation, // qs: SYSTEM_CPU_SET_INFORMATION[5] - ProcessAllowedCpuSetsInformation, // qs: SYSTEM_CPU_SET_INFORMATION[5] - ProcessSubsystemProcess, - ProcessJobMemoryInformation, // q: PROCESS_JOB_MEMORY_INFO - ProcessInPrivate, // q: BOOLEAN; 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, // s: BOOLEAN // 80 - ProcessWakeInformation, // q: PROCESS_WAKE_INFORMATION - ProcessEnergyTrackingState, // qs: PROCESS_ENERGY_TRACKING_STATE - ProcessManageWritesToExecutableMemory, // MANAGE_WRITES_TO_EXECUTABLE_MEMORY // since REDSTONE3 - ProcessCaptureTrustletLiveDump, - ProcessTelemetryCoverage, // q: TELEMETRY_COVERAGE_HEADER; s: TELEMETRY_COVERAGE_POINT + 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, // s: PROCESS_IO_PORT_HANDLER_INFORMATION // (kernel-mode only) + 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, // qs: 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: PROCESS_HANDLE_TRACING_ENABLE[_EX] or void to disable + ProcessIoPriority, // qs: IO_PRIORITY_HINT + ProcessExecuteFlags, // qs: ULONG (MEM_EXECUTE_OPTION_*) + ProcessTlsInformation, // qs: 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[]; s: void + 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, // qs: PROCESS_MITIGATION_POLICY_INFORMATION + ProcessDynamicFunctionTableInformation, // s: PROCESS_DYNAMIC_FUNCTION_TABLE_INFORMATION + 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 + ProcessHandleTable, // q: ULONG[] // since WINBLUE + ProcessCheckStackExtentsMode, // qs: ULONG // KPROCESS->CheckStackExtents (CFG) + ProcessCommandLineInformation, // q: UNICODE_STRING // 60 + ProcessProtectionInformation, // q: PS_PROTECTION + ProcessMemoryExhaustion, // s: PROCESS_MEMORY_EXHAUSTION_INFO // since THRESHOLD + ProcessFaultInformation, // s: PROCESS_FAULT_INFORMATION + ProcessTelemetryIdInformation, // q: PROCESS_TELEMETRY_ID_INFORMATION + ProcessCommitReleaseInformation, // qs: PROCESS_COMMIT_RELEASE_INFORMATION + ProcessDefaultCpuSetsInformation, // qs: SYSTEM_CPU_SET_INFORMATION[5] // ProcessReserved1Information + ProcessAllowedCpuSetsInformation, // qs: SYSTEM_CPU_SET_INFORMATION[5] // ProcessReserved2Information + ProcessSubsystemProcess, // s: void // EPROCESS->SubsystemProcess + ProcessJobMemoryInformation, // q: PROCESS_JOB_MEMORY_INFO + ProcessInPrivate, // q: BOOLEAN; s: void // ETW // since THRESHOLD2 // 70 + ProcessRaiseUMExceptionOnInvalidHandleClose, // qs: ULONG; s: 0 disables, otherwise enables + ProcessIumChallengeResponse, // q: PROCESS_IUM_CHALLENGE_RESPONSE + ProcessChildProcessInformation, // q: PROCESS_CHILD_PROCESS_INFORMATION + ProcessHighGraphicsPriorityInformation, // q: BOOLEAN; s: BOOLEAN (requires SeTcbPrivilege) + ProcessSubsystemInformation, // q: SUBSYSTEM_INFORMATION_TYPE // since REDSTONE2 + ProcessEnergyValues, // q: PROCESS_ENERGY_VALUES, PROCESS_EXTENDED_ENERGY_VALUES, PROCESS_EXTENDED_ENERGY_VALUES_V1 + ProcessPowerThrottlingState, // qs: POWER_THROTTLING_PROCESS_STATE + ProcessActivityThrottlePolicy, // qs: PROCESS_ACTIVITY_THROTTLE_POLICY // ProcessReserved3Information + ProcessWin32kSyscallFilterInformation, // q: WIN32K_SYSCALL_FILTER + ProcessDisableSystemAllowedCpuSets, // s: BOOLEAN // 80 + ProcessWakeInformation, // q: PROCESS_WAKE_INFORMATION // (kernel-mode only) + ProcessEnergyTrackingState, // qs: PROCESS_ENERGY_TRACKING_STATE + ProcessManageWritesToExecutableMemory, // s: MANAGE_WRITES_TO_EXECUTABLE_MEMORY // since REDSTONE3 + ProcessCaptureTrustletLiveDump, // q: ULONG + ProcessTelemetryCoverage, // q: TELEMETRY_COVERAGE_HEADER; s: TELEMETRY_COVERAGE_POINT ProcessEnclaveInformation, - ProcessEnableReadWriteVmLogging, // qs: PROCESS_READWRITEVM_LOGGING_INFORMATION - ProcessUptimeInformation, // q: PROCESS_UPTIME_INFORMATION - ProcessImageSection, // q: HANDLE - ProcessDebugAuthInformation, // since REDSTONE4 // 90 - ProcessSystemResourceManagement, // s: PROCESS_SYSTEM_RESOURCE_MANAGEMENT - ProcessSequenceNumber, // q: ULONGLONG - ProcessLoaderDetour, // since REDSTONE5 - ProcessSecurityDomainInformation, // q: PROCESS_SECURITY_DOMAIN_INFORMATION - ProcessCombineSecurityDomainsInformation, // s: PROCESS_COMBINE_SECURITY_DOMAINS_INFORMATION - ProcessEnableLogging, // qs: PROCESS_LOGGING_INFORMATION - ProcessLeapSecondInformation, // qs: PROCESS_LEAP_SECOND_INFORMATION - ProcessFiberShadowStackAllocation, // s: PROCESS_FIBER_SHADOW_STACK_ALLOCATION_INFORMATION // since 19H1 - ProcessFreeFiberShadowStackAllocation, // s: PROCESS_FREE_FIBER_SHADOW_STACK_ALLOCATION_INFORMATION - ProcessAltSystemCallInformation, // s: PROCESS_SYSCALL_PROVIDER_INFORMATION // since 20H1 // 100 - ProcessDynamicEHContinuationTargets, // s: PROCESS_DYNAMIC_EH_CONTINUATION_TARGETS_INFORMATION - ProcessDynamicEnforcedCetCompatibleRanges, // s: PROCESS_DYNAMIC_ENFORCED_ADDRESS_RANGE_INFORMATION // since 20H2 - ProcessCreateStateChange, // since WIN11 - ProcessApplyStateChange, - ProcessEnableOptionalXStateFeatures, // s: ULONG64 // optional XState feature bitmask - ProcessAltPrefetchParam, // qs: OVERRIDE_PREFETCH_PARAMETER // App Launch Prefetch (ALPF) // since 22H1 - ProcessAssignCpuPartitions, // HANDLE - ProcessPriorityClassEx, // s: PROCESS_PRIORITY_CLASS_EX - ProcessMembershipInformation, // q: PROCESS_MEMBERSHIP_INFORMATION - ProcessEffectiveIoPriority, // q: IO_PRIORITY_HINT // 110 - ProcessEffectivePagePriority, // q: ULONG - ProcessSchedulerSharedData, // SCHEDULER_SHARED_DATA_SLOT_INFORMATION // since 24H2 + ProcessEnableReadWriteVmLogging, // qs: PROCESS_READWRITEVM_LOGGING_INFORMATION + ProcessUptimeInformation, // q: PROCESS_UPTIME_INFORMATION + ProcessImageSection, // q: HANDLE + ProcessDebugAuthInformation, // s: CiTool.exe --device-id // PplDebugAuthorization // since RS4 // 90 + ProcessSystemResourceManagement, // s: PROCESS_SYSTEM_RESOURCE_MANAGEMENT + ProcessSequenceNumber, // q: ULONGLONG + ProcessLoaderDetour, // qs: Obsolete // since RS5 + ProcessSecurityDomainInformation, // q: PROCESS_SECURITY_DOMAIN_INFORMATION + ProcessCombineSecurityDomainsInformation, // s: PROCESS_COMBINE_SECURITY_DOMAINS_INFORMATION + ProcessEnableLogging, // qs: PROCESS_LOGGING_INFORMATION + ProcessLeapSecondInformation, // qs: PROCESS_LEAP_SECOND_INFORMATION + ProcessFiberShadowStackAllocation, // s: PROCESS_FIBER_SHADOW_STACK_ALLOCATION_INFORMATION // since 19H1 + ProcessFreeFiberShadowStackAllocation, // s: PROCESS_FREE_FIBER_SHADOW_STACK_ALLOCATION_INFORMATION + ProcessAltSystemCallInformation, // s: PROCESS_SYSCALL_PROVIDER_INFORMATION // since 20H1 // 100 + ProcessDynamicEHContinuationTargets, // s: PROCESS_DYNAMIC_EH_CONTINUATION_TARGETS_INFORMATION + ProcessDynamicEnforcedCetCompatibleRanges, // s: PROCESS_DYNAMIC_ENFORCED_ADDRESS_RANGE_INFORMATION // since 20H2 + ProcessCreateStateChange, // s: Obsolete // since WIN11 + ProcessApplyStateChange, // s: Obsolete + ProcessEnableOptionalXStateFeatures, // s: ULONG64 // EnableProcessOptionalXStateFeatures + ProcessAltPrefetchParam, // qs: OVERRIDE_PREFETCH_PARAMETER // App Launch Prefetch (ALPF) // since 22H1 + ProcessAssignCpuPartitions, // s: HANDLE + ProcessPriorityClassEx, // s: PROCESS_PRIORITY_CLASS_EX + ProcessMembershipInformation, // q: PROCESS_MEMBERSHIP_INFORMATION + ProcessEffectiveIoPriority, // q: IO_PRIORITY_HINT // 110 + ProcessEffectivePagePriority, // q: ULONG + ProcessSchedulerSharedData, // q: SCHEDULER_SHARED_DATA_SLOT_INFORMATION // since 24H2 ProcessSlistRollbackInformation, - ProcessNetworkIoCounters, // q: PROCESS_NETWORK_COUNTERS - ProcessFindFirstThreadByTebValue, // PROCESS_TEB_VALUE_INFORMATION - ProcessEnclaveAddressSpaceRestriction, // since 25H2 - ProcessAvailableCpus, + ProcessNetworkIoCounters, // q: PROCESS_NETWORK_COUNTERS + ProcessFindFirstThreadByTebValue, // q: PROCESS_TEB_VALUE_INFORMATION // NtCurrentProcess + ProcessEnclaveAddressSpaceRestriction, // qs: // since 25H2 + ProcessAvailableCpus, // q: PROCESS_AVAILABLE_CPUS_INFORMATION MaxProcessInfoClass } PROCESSINFOCLASS; -#endif +#endif // (PHNT_MODE != PHNT_MODE_KERNEL) + +// +// NtQueryInformationThread/NtSetInformationThread types +// #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, // Obsolete - 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 (requires THREAD_QUERY_LIMITED_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, // Obsolete - 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 (requires THREAD_SET_LIMITED_INFORMATION) - ThreadSelectedCpuSets, // q: ULONG[] - 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 // (requires SeDebugPrivilege and PsProtectedSignerAntimalware) - 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, // qs: POWER_THROTTLING_THREAD_STATE // since REDSTONE3 (set), WIN11 22H2 (query) - ThreadWorkloadClass, // THREAD_WORKLOAD_CLASS // since REDSTONE5 // 50 - ThreadCreateStateChange, // since WIN11 - ThreadApplyStateChange, - ThreadStrongerBadHandleChecks, // s: ULONG // NtCurrentThread // since 22H1 - ThreadEffectiveIoPriority, // q: IO_PRIORITY_HINT - ThreadEffectivePagePriority, // q: ULONG - ThreadUpdateLockOwnership, // THREAD_LOCK_OWNERSHIP // since 24H2 - ThreadSchedulerSharedDataSlot, // SCHEDULER_SHARED_DATA_SLOT_INFORMATION - ThreadTebInformationAtomic, // q: THREAD_TEB_INFORMATION (requires THREAD_GET_CONTEXT + THREAD_QUERY_INFORMATION) - ThreadIndexInformation, // THREAD_INDEX_INFORMATION + 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, // q: Obsolete + ThreadQuerySetWin32StartAddress, // q: PVOID + ThreadZeroTlsCell, // s: ULONG // TlsIndex // 10 + ThreadPerformanceCount, // q: LARGE_INTEGER + ThreadAmILastThread, // q: ULONG + ThreadIdealProcessor, // s: ULONG + ThreadPriorityBoost, // qs: ULONG + ThreadSetTlsArrayAddress, // s: ULONG_PTR + 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 (requires THREAD_QUERY_LIMITED_INFORMATION) + ThreadPagePriority, // qs: PAGE_PRIORITY_INFORMATION + ThreadActualBasePriority, // s: LONG (requires SeIncreaseBasePriorityPrivilege) + ThreadTebInformation, // q: THREAD_TEB_INFORMATION (requires THREAD_GET_CONTEXT + THREAD_SET_CONTEXT) + ThreadCSwitchMon, // q: Obsolete + ThreadCSwitchPmu, // q: Obsolete + 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 (requires THREAD_SET_LIMITED_INFORMATION) + ThreadSelectedCpuSets, // q: ULONG[] + 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 // (requires SeDebugPrivilege and PsProtectedSignerAntimalware) + ThreadWorkOnBehalfTicket, // q: ALPC_WORK_ON_BEHALF_TICKET // RTL_WORK_ON_BEHALF_TICKET_EX // NtCurrentThread + ThreadSubsystemInformation, // q: SUBSYSTEM_INFORMATION_TYPE // since REDSTONE2 + ThreadDbgkWerReportActive, // s: ULONG; s: 0 disables, otherwise enables + ThreadAttachContainer, // s: HANDLE (job object) // NtCurrentThread + ThreadManageWritesToExecutableMemory, // s: MANAGE_WRITES_TO_EXECUTABLE_MEMORY // since REDSTONE3 + ThreadPowerThrottlingState, // qs: POWER_THROTTLING_THREAD_STATE // since REDSTONE3 (set), WIN11 22H2 (query) + ThreadWorkloadClass, // q: THREAD_WORKLOAD_CLASS // since REDSTONE5 // 50 + ThreadCreateStateChange, // s: Obsolete // since WIN11 + ThreadApplyStateChange, // s: Obsolete + ThreadStrongerBadHandleChecks, // s: ULONG // NtCurrentThread // since 22H1 + ThreadEffectiveIoPriority, // q: IO_PRIORITY_HINT + ThreadEffectivePagePriority, // q: ULONG + ThreadUpdateLockOwnership, // s: THREAD_LOCK_OWNERSHIP // since 24H2 + ThreadSchedulerSharedDataSlot, // q: SCHEDULER_SHARED_DATA_SLOT_INFORMATION + ThreadTebInformationAtomic, // q: THREAD_TEB_INFORMATION (requires THREAD_GET_CONTEXT + THREAD_QUERY_INFORMATION) + ThreadIndexInformation, // q: THREAD_INDEX_INFORMATION MaxThreadInfoClass } THREADINFOCLASS; -#endif +#endif // (PHNT_MODE != PHNT_MODE_KERNEL) #if (PHNT_MODE != PHNT_MODE_KERNEL) @@ -395,6 +412,7 @@ typedef struct _PROCESS_BASIC_INFORMATION /** * The PROCESS_EXTENDED_BASIC_INFORMATION structure contains extended basic information about a process. */ +_Struct_size_bytes_(Size) typedef struct _PROCESS_EXTENDED_BASIC_INFORMATION { _In_ SIZE_T Size; // The size of the structure, in bytes. This member must be set to sizeof(PROCESS_EXTENDED_BASIC_INFORMATION). @@ -403,12 +421,12 @@ typedef struct _PROCESS_EXTENDED_BASIC_INFORMATION PROCESS_BASIC_INFORMATION BasicInfo; struct { - NTSTATUS ExitStatus; // The exit status of the process. (GetExitCodeProcess) - PPEB PebBaseAddress; // A pointer to the process environment block (PEB) of the process. - KAFFINITY AffinityMask; // The affinity mask of the process. (GetProcessAffinityMask) (deprecated) - KPRIORITY BasePriority; // The base priority of the process. (GetPriorityClass) - HANDLE UniqueProcessId; // The unique identifier of the process. (GetProcessId) - HANDLE InheritedFromUniqueProcessId; // The unique identifier of the parent process. + NTSTATUS ExitStatus; // The exit status of the process. (GetExitCodeProcess) + PPEB PebBaseAddress; // A pointer to the process environment block (PEB) of the process. + KAFFINITY AffinityMask; // The affinity mask of the process. (GetProcessAffinityMask) (deprecated) + KPRIORITY BasePriority; // The base priority of the process. (GetPriorityClass) + HANDLE UniqueProcessId; // The unique identifier of the process. (GetProcessId) + HANDLE InheritedFromUniqueProcessId; // The unique identifier of the parent process. }; }; union @@ -605,7 +623,7 @@ typedef struct _LDT_ENTRY } Bits; } HighWord; } LDT_ENTRY, *PLDT_ENTRY; -#endif +#endif // _LDT_ENTRY_DEFINED /** * The PROCESS_LDT_INFORMATION structure is used to manage Local Descriptor Table (LDT) entries for a process. @@ -636,7 +654,7 @@ typedef struct _PROCESS_WS_WATCH_INFORMATION PVOID FaultingVa; // A pointer to the page that was added to the working set. } PROCESS_WS_WATCH_INFORMATION, *PPROCESS_WS_WATCH_INFORMATION; -#endif +#endif // (PHNT_MODE != PHNT_MODE_KERNEL) /** * The PROCESS_WS_WATCH_INFORMATION_EX structure contains extended information about a page added to a process working set. @@ -694,7 +712,7 @@ typedef struct _PROCESS_PRIORITY_CLASS_EX } PROCESS_PRIORITY_CLASS_EX, *PPROCESS_PRIORITY_CLASS_EX; /** - * The PROCESS_FOREGROUND_BACKGROUND structure is used to manage the the priority class of a process, specifically whether it runs in the foreground or background. + * The PROCESS_FOREGROUND_BACKGROUND structure is used to manage the priority class of a process, specifically whether it runs in the foreground or background. */ typedef struct _PROCESS_FOREGROUND_BACKGROUND { @@ -731,10 +749,13 @@ typedef struct _PROCESS_DEVICEMAP_INFORMATION }; } PROCESS_DEVICEMAP_INFORMATION, *PPROCESS_DEVICEMAP_INFORMATION; +/** + * The PROCESS_LUID_DOSDEVICES_ONLY flag limits the device map to only devices from the current process or logon session. + */ #define PROCESS_LUID_DOSDEVICES_ONLY 0x00000001 /** - * The _PROCESS_DEVICEMAP_INFORMATION_EX structure contains information about a process's device map. + * The PROCESS_DEVICEMAP_INFORMATION_EX structure contains information about a process's device map. */ typedef struct _PROCESS_DEVICEMAP_INFORMATION_EX { @@ -770,9 +791,12 @@ typedef struct _PROCESS_SESSION_INFORMATION */ typedef struct _PROCESS_HANDLE_TRACING_ENABLE { - ULONG Flags; // Flags that control handle tracing. + ULONG Flags; // Flags that control handle tracing. } PROCESS_HANDLE_TRACING_ENABLE, *PPROCESS_HANDLE_TRACING_ENABLE; +/** + * The PROCESS_HANDLE_TRACING_MAX_SLOTS macro specifies the maximum number of slots. + */ #define PROCESS_HANDLE_TRACING_MAX_SLOTS 0x20000 /** @@ -784,20 +808,24 @@ typedef struct _PROCESS_HANDLE_TRACING_ENABLE_EX ULONG TotalSlots; // Total number of handle tracing slots. } 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 +/** + * The PROCESS_HANDLE_TRACING_ENTRY structure contains information about the handle operation associated with the event. + */ typedef struct _PROCESS_HANDLE_TRACING_ENTRY { - HANDLE Handle; - CLIENT_ID ClientId; - ULONG Type; - PVOID Stacks[PROCESS_HANDLE_TRACING_MAX_STACKS]; + HANDLE Handle; // The handle associated with the event. + CLIENT_ID ClientId; // The process and thread associated with the event. + ULONG Type; // The type of handle operation associated with the event. + PVOID Stacks[16]; } PROCESS_HANDLE_TRACING_ENTRY, *PPROCESS_HANDLE_TRACING_ENTRY; +/** + * The PROCESS_HANDLE_TRACING_QUERY structure is used to query all handle events or a specific handle event for a process. + */ typedef struct _PROCESS_HANDLE_TRACING_QUERY { _In_opt_ HANDLE Handle; @@ -805,7 +833,7 @@ typedef struct _PROCESS_HANDLE_TRACING_QUERY _Out_ _Field_size_(TotalTraces) PROCESS_HANDLE_TRACING_ENTRY HandleTrace[1]; } PROCESS_HANDLE_TRACING_QUERY, *PPROCESS_HANDLE_TRACING_QUERY; -#endif +#endif // (PHNT_MODE != PHNT_MODE_KERNEL) /** * The THREAD_TLS_INFORMATION structure contains information about the Thread Local Storage (TLS) data for a thread. @@ -872,30 +900,37 @@ typedef struct _PROCESS_STACK_ALLOCATION_INFORMATION_EX ULONG Reserved2; // Reserved for future use. PROCESS_STACK_ALLOCATION_INFORMATION AllocInfo; // The stack allocation information. } PROCESS_STACK_ALLOCATION_INFORMATION_EX, *PPROCESS_STACK_ALLOCATION_INFORMATION_EX; + /** * The PROCESS_AFFINITY_UPDATE_MODE union is used to specify the affinity update mode for a process. */ -typedef union _PROCESS_AFFINITY_UPDATE_MODE +typedef struct _PROCESS_AFFINITY_UPDATE_MODE { - ULONG Flags; - struct + union { - ULONG EnableAutoUpdate : 1; // Indicates whether auto-update of affinity is enabled. - ULONG Permanent : 1; // Indicates whether the affinity update is permanent. - ULONG Reserved : 30; // Reserved for future use. + ULONG Flags; + struct + { + ULONG EnableAutoUpdate : 1; // Indicates whether auto-update of affinity is enabled. + ULONG Permanent : 1; // Indicates whether the affinity update is permanent. + ULONG Reserved : 30; // Reserved for future use. + }; }; } PROCESS_AFFINITY_UPDATE_MODE, *PPROCESS_AFFINITY_UPDATE_MODE; /** * The PROCESS_MEMORY_ALLOCATION_MODE union is used to specify the memory allocation mode for a process. */ -typedef union _PROCESS_MEMORY_ALLOCATION_MODE +typedef struct _PROCESS_MEMORY_ALLOCATION_MODE { - ULONG Flags; - struct + union { - ULONG TopDown : 1; // Indicates whether memory allocation should be top-down. - ULONG Reserved : 31; // Reserved for future use. + ULONG Flags; + struct + { + ULONG TopDown : 1; // Indicates whether memory allocation should be top-down. + ULONG Reserved : 31; // Reserved for future use. + }; }; } PROCESS_MEMORY_ALLOCATION_MODE, *PPROCESS_MEMORY_ALLOCATION_MODE; @@ -965,7 +1000,7 @@ typedef struct _PROCESS_MITIGATION_REDIRECTION_TRUST_POLICY }; }; } PROCESS_MITIGATION_REDIRECTION_TRUST_POLICY, *PPROCESS_MITIGATION_REDIRECTION_TRUST_POLICY; -#endif +#endif // NTDDI_WIN10_FE #if !defined(NTDDI_WIN10_NI) || (NTDDI_VERSION < NTDDI_WIN10_NI) typedef struct _PROCESS_MITIGATION_USER_POINTER_AUTH_POLICY { @@ -987,7 +1022,7 @@ typedef struct _PROCESS_MITIGATION_SEHOP_POLICY { }; }; } PROCESS_MITIGATION_SEHOP_POLICY, *PPROCESS_MITIGATION_SEHOP_POLICY; -#endif +#endif // NTDDI_WIN10_NI typedef struct _PROCESS_MITIGATION_ACTIVATION_CONTEXT_TRUST_POLICY2 { @@ -1005,29 +1040,34 @@ typedef struct _PROCESS_MITIGATION_ACTIVATION_CONTEXT_TRUST_POLICY2 #if defined(_PHLIB_) // enum PROCESS_MITIGATION_POLICY #define PROCESS_MITIGATION_POLICY ULONG -#define ProcessDEPPolicy 0 -#define ProcessASLRPolicy 1 -#define ProcessDynamicCodePolicy 2 -#define ProcessStrictHandleCheckPolicy 3 -#define ProcessSystemCallDisablePolicy 4 -#define ProcessMitigationOptionsMask 5 -#define ProcessExtensionPointDisablePolicy 6 +#define ProcessDEPPolicy 0 // The data execution prevention (DEP) policy of the process. +#define ProcessASLRPolicy 1 // The Address Space Layout Randomization (ASLR) policy of the process. +#define ProcessDynamicCodePolicy 2 // Disables the ability to generate dynamic code or modify existing executable code. +#define ProcessStrictHandleCheckPolicy 3 // Enables the ability to generate a fatal error if the process manipulates an invalid handle. +#define ProcessSystemCallDisablePolicy 4 // Disables the ability of the process to use NTUser/GDI functions at the lowest layer. +#define ProcessMitigationOptionsMask 5 // Returns the mask of valid bits for all the mitigation options on the system. +#define ProcessExtensionPointDisablePolicy 6 // Disables the ability of the process to load legacy extension point DLLs. #define ProcessControlFlowGuardPolicy 7 -#define ProcessSignaturePolicy 8 -#define ProcessFontDisablePolicy 9 -#define ProcessImageLoadPolicy 10 +#define ProcessSignaturePolicy 8 // Disables the ability of the process to load images not signed by Microsoft, the Windows Store and the Windows Hardware Quality Labs (WHQL). +#define ProcessFontDisablePolicy 9 // Disables the ability of the process to load non-system fonts. +#define ProcessImageLoadPolicy 10 // Disables the ability of the process to load images from some locations, such a remote devices or files that have the low mandatory label. #define ProcessSystemCallFilterPolicy 11 #define ProcessPayloadRestrictionPolicy 12 -#define ProcessChildProcessPolicy 13 +#define ProcessChildProcessPolicy 13 // Disables the ability to create child processes. #define ProcessSideChannelIsolationPolicy 14 -#define ProcessUserShadowStackPolicy 15 +#define ProcessUserShadowStackPolicy 15 // since 20H1 #define ProcessRedirectionTrustPolicy 16 #define ProcessUserPointerAuthPolicy 17 #define ProcessSEHOPPolicy 18 #define ProcessActivationContextTrustPolicy 19 #define MaxProcessMitigationPolicy 20 -#endif +#endif // _PHLIB_ +/** + * The PROCESS_MITIGATION_POLICY_INFORMATION structure represents the different process mitigation policies. + * + * \remarks https://learn.microsoft.com/en-us/windows/win32/api/winnt/ne-winnt-process_mitigation_policy + */ typedef struct _PROCESS_MITIGATION_POLICY_INFORMATION { PROCESS_MITIGATION_POLICY Policy; @@ -1050,22 +1090,34 @@ typedef struct _PROCESS_MITIGATION_POLICY_INFORMATION PROCESS_MITIGATION_REDIRECTION_TRUST_POLICY RedirectionTrustPolicy; PROCESS_MITIGATION_USER_POINTER_AUTH_POLICY UserPointerAuthPolicy; PROCESS_MITIGATION_SEHOP_POLICY SEHOPPolicy; + PROCESS_MITIGATION_ACTIVATION_CONTEXT_TRUST_POLICY2 ActivationContextTrustPolicy; }; } PROCESS_MITIGATION_POLICY_INFORMATION, *PPROCESS_MITIGATION_POLICY_INFORMATION; // private +typedef struct _DYNAMIC_FUNCTION_TABLE DYNAMIC_FUNCTION_TABLE, *PDYNAMIC_FUNCTION_TABLE; + +/** + * The PROCESS_DYNAMIC_FUNCTION_TABLE_INFORMATION structure is used to manage dynamic function tables for a process. + */ typedef struct _PROCESS_DYNAMIC_FUNCTION_TABLE_INFORMATION { - struct _DYNAMIC_FUNCTION_TABLE* DynamicFunctionTable; - BOOLEAN Remove; + PDYNAMIC_FUNCTION_TABLE DynamicFunctionTable; // Pointer to the dynamic function table. + BOOLEAN Remove; // Indicates whether to remove (TRUE) or add (FALSE) the dynamic function table. } PROCESS_DYNAMIC_FUNCTION_TABLE_INFORMATION, *PPROCESS_DYNAMIC_FUNCTION_TABLE_INFORMATION; +/** + * The PROCESS_KEEPALIVE_COUNT_INFORMATION structure contains information about the wake and no-wake counts for a process. + */ typedef struct _PROCESS_KEEPALIVE_COUNT_INFORMATION { - ULONG WakeCount; - ULONG NoWakeCount; + ULONG WakeCount; // The number of times the process has been awakened. + ULONG NoWakeCount; // The number of times the process was not awakened when expected. } PROCESS_KEEPALIVE_COUNT_INFORMATION, *PPROCESS_KEEPALIVE_COUNT_INFORMATION; +/** + * The PROCESS_REVOKE_FILE_HANDLES_INFORMATION structure revokes handles to the specified device from a process. + */ typedef struct _PROCESS_REVOKE_FILE_HANDLES_INFORMATION { UNICODE_STRING TargetDevicePath; @@ -1095,6 +1147,10 @@ typedef enum _PROCESS_WORKING_SET_OPERATION * Shared pages are those that are shared between multiple processes. */ #define PROCESS_WORKING_SET_FLAG_EMPTY_SHARED_PAGES 0x02 + /** + * The PROCESS_WORKING_SET_FLAG_EMPTY_PAGES flag indicates that the operation should target pages in the working set. + */ +#define PROCESS_WORKING_SET_FLAG_EMPTY_PAGES 0x04 /** * The PROCESS_WORKING_SET_FLAG_COMPRESS flag indicates that the operation should compress the pages before they are removed from the working set. * Compression is typically used in conjunction with other flags to specify that the pages should be compressed as part of the operation. @@ -1180,28 +1236,73 @@ typedef struct _PS_PROTECTION }; } PS_PROTECTION, *PPS_PROTECTION; +/** + * The PROCESS_MEMORY_EXHAUSTION_TYPE enumeration defines the different memory exhaustion types. + * + * \sa https://learn.microsoft.com/en-us/windows/win32/api/processthreadsapi/ne-processthreadsapi-process_memory_exhaustion_type + */ +//typedef enum _PROCESS_MEMORY_EXHAUSTION_TYPE +//{ +// // Anytime memory management fails an allocation due to an inability to commit memory, +// // it will cause the process to trigger a Windows Error Reporting report and then terminate immediately with STATUS_COMMITMENT_LIMIT. +// // The failure cannot be caught and handled by the app. +// PMETypeFailFastOnCommitFailure, +// PMETypeMax +//} PROCESS_MEMORY_EXHAUSTION_TYPE, *PPROCESS_MEMORY_EXHAUSTION_TYPE; + +/** + * The PROCESS_MEMORY_EXHAUSTION_INFO structure allows applications to configure + * termination if an allocation fails to commit memory. + * \sa https://learn.microsoft.com/en-us/windows/win32/api/processthreadsapi/ns-processthreadsapi-process_memory_exhaustion_info + */ +//typedef struct _PROCESS_MEMORY_EXHAUSTION_INFO +//{ +// USHORT Version; // Version should be set to PME_CURRENT_VERSION. +// USHORT Reserved; // Reserved +// PROCESS_MEMORY_EXHAUSTION_TYPE Type; // Type of failure. +// ULONG_PTR Value; // Used to turn the feature on or off. +//} PROCESS_MEMORY_EXHAUSTION_INFO, *PPROCESS_MEMORY_EXHAUSTION_INFO; + +// rev PROCESS_FAULT_INFORMATION->FaultFlags +#define PROCESS_FAULT_FLAG_MARK_CRASHED 0x00000001 // sets Flags3.Crashed (bit 2) via atomic OR +#define PROCESS_FAULT_FLAG_SET_STATE_CRASHED 0x00000002 // sets HangCount to 0x7 +#define PROCESS_FAULT_FLAG_ESCALATE_SEVERITY 0x00000004 // sets GhostCount to 0x7 (mask 0x38) +#define PROCESS_FAULT_FLAG_SET_TERMINAL_BIT 0x00000008 // sets PrefilterException (bit 6) + /** * The PROCESS_FAULT_INFORMATION structure contains information about process faults. */ typedef struct _PROCESS_FAULT_INFORMATION { - ULONG FaultFlags; // Flags that provide additional information about the fault. - ULONG AdditionalInfo; // Additional information about the fault. + union + { + ULONG FaultFlags; + struct + { + ULONG MarkCrashed : 1; // PROCESS_FAULT_FLAG_MARK_CRASHED (0x00000001) + ULONG SetStateCrashed : 1; // PROCESS_FAULT_FLAG_SET_STATE_CRASHED (0x00000002) + ULONG EscalateSeverity : 1; // PROCESS_FAULT_FLAG_ESCALATE_SEVERITY (0x00000004) + ULONG SetTerminalBit : 1; // PROCESS_FAULT_FLAG_SET_TERMINAL_BIT (0x00000008) + ULONG Reserved : 28; + }; + }; + ULONG AdditionalInfo; // Reserved for future use. } PROCESS_FAULT_INFORMATION, *PPROCESS_FAULT_INFORMATION; /** * The PROCESS_TELEMETRY_ID_INFORMATION structure contains telemetry information about a process. */ +_Struct_size_bytes_(HeaderSize) typedef struct _PROCESS_TELEMETRY_ID_INFORMATION { ULONG HeaderSize; // The size of the structure, in bytes. ULONG ProcessId; // The ID of the process. - ULONGLONG ProcessStartKey; // The start key of the process. - ULONGLONG CreateTime; // The creation time of the process. - ULONGLONG CreateInterruptTime; // The interrupt time at creation. - ULONGLONG CreateUnbiasedInterruptTime; // The unbiased interrupt time at creation. - ULONGLONG ProcessSequenceNumber; // The monotonic sequence number of the process. - ULONGLONG SessionCreateTime; // The session creation time. + ULONG64 ProcessStartKey; // The start key of the process. + ULONG64 CreateTime; // The creation time of the process. + ULONG64 CreateInterruptTime; // The interrupt time at creation. + ULONG64 CreateUnbiasedInterruptTime; // The unbiased interrupt time at creation. + ULONG64 ProcessSequenceNumber; // The monotonic sequence number of the process. + ULONG64 SessionCreateTime; // The session creation time. ULONG SessionId; // The ID of the session. ULONG BootId; // The boot ID. ULONG ImageChecksum; // The checksum of the process image. @@ -1232,19 +1333,25 @@ typedef struct _PROCESS_COMMIT_RELEASE_INFORMATION } PROCESS_COMMIT_RELEASE_INFORMATION, *PPROCESS_COMMIT_RELEASE_INFORMATION; /** - * The PROCESS_JOB_MEMORY_INFO structure contains Represents app memory usage at a single point in time. + * The PROCESS_JOB_MEMORY_INFO structure represents app memory usage at a single point in time. * * \remarks https://learn.microsoft.com/en-us/windows/win32/api/processthreadsapi/ns-processthreadsapi-app_memory_information */ typedef struct _PROCESS_JOB_MEMORY_INFO { - ULONGLONG SharedCommitUsage; // The current shared commit usage, in bytes. - ULONGLONG PrivateCommitUsage; // The current private commit usage, in bytes. - ULONGLONG PeakPrivateCommitUsage; // The peak private commit usage, in bytes. - ULONGLONG PrivateCommitLimit; // The private commit limit, in bytes. - ULONGLONG TotalCommitLimit; // The total commit limit, in bytes. + ULONG64 SharedCommitUsage; // The current shared commit usage, in bytes. + ULONG64 PrivateCommitUsage; // The current private commit usage, in bytes. + ULONG64 PeakPrivateCommitUsage; // The peak private commit usage, in bytes. + ULONG64 PrivateCommitLimit; // The private commit limit, in bytes. + ULONG64 TotalCommitLimit; // The total commit limit, in bytes. } PROCESS_JOB_MEMORY_INFO, *PPROCESS_JOB_MEMORY_INFO; +// rev +typedef struct _PROCESS_IUM_CHALLENGE_RESPONSE +{ + BYTE Buffer[0x1000]; // Challenge response buffer. +} PROCESS_IUM_CHALLENGE_RESPONSE, *PPROCESS_IUM_CHALLENGE_RESPONSE; + /** * The PROCESS_CHILD_PROCESS_INFORMATION structure contains information about child process policies. */ @@ -1255,12 +1362,38 @@ typedef struct _PROCESS_CHILD_PROCESS_INFORMATION BOOLEAN AuditProhibitChildProcesses; // Child processes are audited. } PROCESS_CHILD_PROCESS_INFORMATION, *PPROCESS_CHILD_PROCESS_INFORMATION; +/** + * Defines the current version of the power throttling structure. + */ #define POWER_THROTTLING_PROCESS_CURRENT_VERSION 1 - +/** + * Limits the CPU execution speed of the process to reduce power consumption. + */ #define POWER_THROTTLING_PROCESS_EXECUTION_SPEED 0x1 +/** + * The POWER_THROTTLING_PROCESS_DELAYTIMERS flag delays the expiration of waits and timers for the process. + * When this flag is set, the process's wait and timer expiration events may be postponed, + * which can help reduce power consumption by allowing the system to remain in low-power states longer. + */ #define POWER_THROTTLING_PROCESS_DELAYTIMERS 0x2 +/** + * The POWER_THROTTLING_PROCESS_IGNORE_TIMER_RESOLUTION flag controls whether calls made by the + * process to adjust the system timer resolution (such as timeBeginPeriod or NtSetTimerResolution) + * are honored. When this flag is enabled, such requests are ignored. + * + * This behavior is part of Windows power-throttling mechanism introduced in Windows 11 and is + * enabled by default for all processes. Changes to the system timer resolution can alter the + * behavior of system timers, wait timeouts, and sleep durations, often causing unintended + * side effects in applications. Higher-precision timer resolutions also negatively impact + * battery life and overall system performance. + * + * \note Enabled by default since Windows 11. This may cause performance issues for legacy + * applications and games that rely on modifying the system tick resolution. + */ #define POWER_THROTTLING_PROCESS_IGNORE_TIMER_RESOLUTION 0x4 // since WIN11 - +/** + * Valid flags for power throttling process control and state masks. + */ #define POWER_THROTTLING_PROCESS_VALID_FLAGS \ ((POWER_THROTTLING_PROCESS_EXECUTION_SPEED | POWER_THROTTLING_PROCESS_DELAYTIMERS | POWER_THROTTLING_PROCESS_IGNORE_TIMER_RESOLUTION)) @@ -1274,23 +1407,91 @@ typedef struct _POWER_THROTTLING_PROCESS_STATE ULONG StateMask; // A mask that specifies the current state of power throttling. } POWER_THROTTLING_PROCESS_STATE, *PPOWER_THROTTLING_PROCESS_STATE; +// private +#ifndef PROCESS_POWER_THROTTLING_CURRENT_VERSION +#define PROCESS_POWER_THROTTLING_CURRENT_VERSION 1 +#endif +#ifndef PROCESS_POWER_THROTTLING_EXECUTION_SPEED +#define PROCESS_POWER_THROTTLING_EXECUTION_SPEED 0x1 +#endif +#ifndef PROCESS_POWER_THROTTLING_IGNORE_TIMER_RESOLUTION +#define PROCESS_POWER_THROTTLING_IGNORE_TIMER_RESOLUTION 0x4 +#endif +#ifndef PROCESS_POWER_THROTTLING_VALID_FLAGS +#define PROCESS_POWER_THROTTLING_VALID_FLAGS \ + ((PROCESS_POWER_THROTTLING_EXECUTION_SPEED | PROCESS_POWER_THROTTLING_IGNORE_TIMER_RESOLUTION)) +#endif + +// private +//typedef struct _PROCESS_POWER_THROTTLING_STATE +//{ +// ULONG Version; +// ULONG ControlMask; +// ULONG StateMask; +//} PROCESS_POWER_THROTTLING_STATE, *PPROCESS_POWER_THROTTLING_STATE; + +// private +typedef enum _PROCESS_ACTIVITY_THROTTLE_POLICY_OP +{ + ProcessActivityThrottlePolicyDisable = 0, + ProcessActivityThrottlePolicyEnable = 1, + ProcessActivityThrottlePolicyDefault = 2, + MaxProcessActivityThrottlePolicy +} PROCESS_ACTIVITY_THROTTLE_POLICY_OP; + +// PROCESS_ACTIVITY_THROTTLE_POLICY PolicyFlags +#define PROCESS_ACTIVITY_THROTTLE_EXECUTIONSPEED 0x1 +#define PROCESS_ACTIVITY_THROTTLE_DELAYTIMERS 0x2 +#define PROCESS_ACTIVITY_THROTTLE_ALL \ + ((PROCESS_ACTIVITY_THROTTLE_EXECUTIONSPEED | PROCESS_ACTIVITY_THROTTLE_DELAYTIMERS)) + +/** + * The PROCESS_ACTIVITY_THROTTLE_POLICY structure is used to manage the activity throttle of a process. + */ +typedef struct _PROCESS_ACTIVITY_THROTTLE_POLICY +{ + PROCESS_ACTIVITY_THROTTLE_POLICY_OP Operation; + ULONG PolicyFlags; +} PROCESS_ACTIVITY_THROTTLE_POLICY, *PPROCESS_ACTIVITY_THROTTLE_POLICY; + // rev (tyranid) #define WIN32K_SYSCALL_FILTER_STATE_ENABLE 0x1 #define WIN32K_SYSCALL_FILTER_STATE_AUDIT 0x2 +/** + * The WIN32K_SYSCALL_FILTER structure is used to specify filtering options for Win32k system calls. + */ typedef struct _WIN32K_SYSCALL_FILTER { - ULONG FilterState; - ULONG FilterSet; + ULONG FilterState; // The state of the Win32k syscall filter (e.g., enable, audit). + ULONG FilterSet; // The set of Win32k syscalls to be filtered. } WIN32K_SYSCALL_FILTER, *PWIN32K_SYSCALL_FILTER; -typedef struct _JOBOBJECT_WAKE_FILTER *PJOBOBJECT_WAKE_FILTER; // from ntpsapi.h +// private +typedef struct _JOBOBJECT_WAKE_FILTER +{ + ULONG HighEdgeFilter; + ULONG LowEdgeFilter; +} JOBOBJECT_WAKE_FILTER, *PJOBOBJECT_WAKE_FILTER; + +// private +typedef enum _PS_WAKE_REASON +{ + PsWakeReasonUser = 0, + PsWakeReasonExecutionRequired = 1, + PsWakeReasonKernel = 2, + PsWakeReasonInstrumentation = 3, + PsWakeReasonPreserveProcess = 4, + PsWakeReasonActivityReference = 5, + PsWakeReasonWorkOnBehalf = 6, + PsMaxWakeReasons = 7, +} PS_WAKE_REASON, *PPS_WAKE_REASON; typedef struct _PROCESS_WAKE_INFORMATION { - ULONGLONG NotificationChannel; - ULONG WakeCounters[7]; - PJOBOBJECT_WAKE_FILTER WakeFilter; + ULONG64 NotificationChannel; + ULONG WakeCounters[PsMaxWakeReasons]; + JOBOBJECT_WAKE_FILTER WakeFilter; } PROCESS_WAKE_INFORMATION, *PPROCESS_WAKE_INFORMATION; typedef struct _PROCESS_ENERGY_TRACKING_STATE @@ -1302,24 +1503,33 @@ typedef struct _PROCESS_ENERGY_TRACKING_STATE WCHAR Tag[64]; } PROCESS_ENERGY_TRACKING_STATE, *PPROCESS_ENERGY_TRACKING_STATE; +/** + * The MANAGE_WRITES_TO_EXECUTABLE_MEMORY structure controls write permissions to executable memory + * for processes and threads, and provides a signal for kernel write events. + */ typedef struct _MANAGE_WRITES_TO_EXECUTABLE_MEMORY { - ULONG Version : 8; - ULONG ProcessEnableWriteExceptions : 1; - ULONG ThreadAllowWrites : 1; - ULONG Spare : 22; - PVOID KernelWriteToExecutableSignal; // 19H1 + ULONG Version : 8; // The version of the structure. + ULONG ProcessEnableWriteExceptions : 1; // Enables write exceptions for the process. + ULONG ThreadAllowWrites : 1; // Allows the thread to write to executable memory. + ULONG Spare : 22; // Reserved for future use. + HANDLE KernelWriteToExecutableSignal; // Pointer to kernel signal for write-to-executable events (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) +/** + * The POWER_THROTTLING_THREAD_STATE structure contains the throttling policies of a thread subject to power management. + * + * \remarks https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/ntddk/ns-ntddk-_power_throttling_thread_state + */ typedef struct _POWER_THROTTLING_THREAD_STATE { - ULONG Version; - ULONG ControlMask; - ULONG StateMask; + ULONG Version; // The version of this structure. Set to THREAD_POWER_THROTTLING_CURRENT_VERSION. + ULONG ControlMask; // Flags that enable the caller to take control of the power throttling mechanism. + ULONG StateMask; // Flags that manage the power throttling mechanism on/off state. } POWER_THROTTLING_THREAD_STATE, *PPOWER_THROTTLING_THREAD_STATE; #define PROCESS_READWRITEVM_LOGGING_ENABLE_READVM 1 @@ -1327,70 +1537,123 @@ typedef struct _POWER_THROTTLING_THREAD_STATE #define PROCESS_READWRITEVM_LOGGING_ENABLE_READVM_V 1UL #define PROCESS_READWRITEVM_LOGGING_ENABLE_WRITEVM_V 2UL -typedef union _PROCESS_READWRITEVM_LOGGING_INFORMATION +/** + * The PROCESS_READWRITEVM_LOGGING_INFORMATION structure provides flags to enable logging + * of read and write operations to a process's virtual memory. + */ +typedef struct _PROCESS_READWRITEVM_LOGGING_INFORMATION { - UCHAR Flags; - struct + union { - UCHAR EnableReadVmLogging : 1; - UCHAR EnableWriteVmLogging : 1; - UCHAR Unused : 6; + UCHAR Flags; + struct + { + UCHAR EnableReadVmLogging : 1; // Enable logging of read operations to virtual memory. + UCHAR EnableWriteVmLogging : 1; // Enable logging of write operations to virtual memory. + UCHAR Unused : 6; + }; }; } PROCESS_READWRITEVM_LOGGING_INFORMATION, *PPROCESS_READWRITEVM_LOGGING_INFORMATION; +/** + * The PROCESS_UPTIME_INFORMATION structure contains information about the uptime of a process and diagnostic information. + */ typedef struct _PROCESS_UPTIME_INFORMATION { - ULONGLONG QueryInterruptTime; - ULONGLONG QueryUnbiasedTime; - ULONGLONG EndInterruptTime; - ULONGLONG TimeSinceCreation; - ULONGLONG Uptime; - ULONGLONG SuspendedTime; + ULONGLONG QueryInterruptTime; // The interrupt time when the query was made. + ULONGLONG QueryUnbiasedTime; // The unbiased time when the query was made. + ULONGLONG EndInterruptTime; // The interrupt time when the process ended. + ULONGLONG TimeSinceCreation; // The total time elapsed since the process was created. + ULONGLONG Uptime; // The total uptime of the process. + ULONGLONG SuspendedTime; // The total time the process was in a suspended state. struct { - ULONG HangCount : 4; - ULONG GhostCount : 4; - ULONG Crashed : 1; - ULONG Terminated : 1; + ULONG HangCount : 4; // The number of times the process was detected as hanging. + ULONG GhostCount : 4; // The number of times the process was detected as a ghost process. + ULONG Crashed : 1; // Indicates whether the process has crashed (1 if true, 0 otherwise). + ULONG Terminated : 1; // Indicates whether the process has been terminated (1 if true, 0 otherwise). }; } PROCESS_UPTIME_INFORMATION, *PPROCESS_UPTIME_INFORMATION; -typedef union _PROCESS_SYSTEM_RESOURCE_MANAGEMENT +/** + * The PROCESS_SYSTEM_RESOURCE_MANAGEMENT union is used to specify system resource management flags for a process. + */ +typedef struct _PROCESS_SYSTEM_RESOURCE_MANAGEMENT { - ULONG Flags; - struct + union { - ULONG Foreground : 1; - ULONG Reserved : 31; + ULONG Flags; + struct + { + ULONG Foreground : 1; // Indicates if the process is a foreground process (1 = foreground, 0 = background). + ULONG Reserved : 31; + }; }; } PROCESS_SYSTEM_RESOURCE_MANAGEMENT, *PPROCESS_SYSTEM_RESOURCE_MANAGEMENT; +/** + * The PROCESS_SECURITY_DOMAIN_INFORMATION structure contains the security domain identifier for a process. + * + * This structure is used to query or set the security domain of a process, which can be used for isolation + * and security boundary purposes in Windows. The SecurityDomain field is a 64-bit value that uniquely + * identifies the security domain associated with the process. + */ typedef struct _PROCESS_SECURITY_DOMAIN_INFORMATION { - ULONGLONG SecurityDomain; + ULONGLONG SecurityDomain; // The unique identifier of the process's security domain. } PROCESS_SECURITY_DOMAIN_INFORMATION, *PPROCESS_SECURITY_DOMAIN_INFORMATION; +/** + * The PROCESS_COMBINE_SECURITY_DOMAINS_INFORMATION structure combines the security domain of a process. + * + * This structure contains information required to combine the security domains + * of a specified process. It is typically used in system-level or security-related + * operations where process security contexts need to be merged or managed. + */ typedef struct _PROCESS_COMBINE_SECURITY_DOMAINS_INFORMATION { - HANDLE ProcessHandle; + HANDLE ProcessHandle; // The Handle to the process whose security domains are to be combined. } PROCESS_COMBINE_SECURITY_DOMAINS_INFORMATION, *PPROCESS_COMBINE_SECURITY_DOMAINS_INFORMATION; -typedef union _PROCESS_LOGGING_INFORMATION +/** + * The PROCESS_LOGGING_INFORMATION structure provides flags to enable or disable logging + * for specific process and thread events, such as virtual memory access, suspend/resume, + * execution protection, and impersonation. + */ +typedef struct _PROCESS_LOGGING_INFORMATION { - ULONG Flags; - struct + union { - ULONG EnableReadVmLogging : 1; - ULONG EnableWriteVmLogging : 1; - ULONG EnableProcessSuspendResumeLogging : 1; - ULONG EnableThreadSuspendResumeLogging : 1; - ULONG EnableLocalExecProtectVmLogging : 1; - ULONG EnableRemoteExecProtectVmLogging : 1; - ULONG EnableImpersonationLogging : 1; - ULONG Reserved : 25; + ULONG Flags; + struct + { + ULONG EnableReadVmLogging : 1; // Enables logging of read operations to process virtual memory. + ULONG EnableWriteVmLogging : 1; // Enables logging of write operations to process virtual memory. + ULONG EnableProcessSuspendResumeLogging : 1; // Enables logging of process suspend and resume events. + ULONG EnableThreadSuspendResumeLogging : 1; // Enables logging of thread suspend and resume events. + ULONG EnableLocalExecProtectVmLogging : 1; // Enables logging of local execution protection for virtual memory. + ULONG EnableRemoteExecProtectVmLogging : 1; // Enables logging of remote execution protection for virtual memory. + ULONG EnableImpersonationLogging : 1; // Enables logging of impersonation events. + ULONG Reserved : 25; + }; }; } PROCESS_LOGGING_INFORMATION, *PPROCESS_LOGGING_INFORMATION; +/** + * This value changes the seconds field during a positive leap second adjustment by the system. + * If enabled, then the seconds field returns any positive leap second (For example: 23:59:59 -> 23:59:60 -> 00:00:00). + * If not enabled, then the 59th second preceding a positive leap second will be shown for 2 seconds with the milliseconds + * value ticking twice as slow. (For example: 23:59:59 -> 23:59:59.500 -> 00:00:00, which takes 2 seconds in wall clock time). + * Note: Leap second adjustments are disabled by default for each process, this flag also does not persist if the process is restarted. + */ +#define PROCESS_LEAP_SECOND_FLAG_ENABLE_SIXTY_SECOND 0x1 +#define PROCESS_LEAP_SECOND_VALID_FLAGS (PROCESS_LEAP_SECOND_INFO_FLAG_ENABLE_SIXTY_SECOND) + +/** + * The PROCESS_LEAP_SECOND_INFORMATION structure contains information about leap second adjustments for a process. + * + * \remarks https://learn.microsoft.com/en-us/windows/win32/api/processthreadsapi/ns-processthreadsapi-process_leap_second_info + */ typedef struct _PROCESS_LEAP_SECOND_INFORMATION { ULONG Flags; @@ -1411,12 +1674,20 @@ 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; +/** + * The PROCESS_SYSCALL_PROVIDER_INFORMATION structure contains information about a system call provider + * and level for system call filtering or instrumentation. + */ typedef struct _PROCESS_SYSCALL_PROVIDER_INFORMATION { - GUID ProviderId; - UCHAR Level; + GUID ProviderId; // The unique identifier of the system call provider. + UCHAR Level; // The level or mode of the provider. } PROCESS_SYSCALL_PROVIDER_INFORMATION, *PPROCESS_SYSCALL_PROVIDER_INFORMATION; +/** + * Contains dynamic enforced address ranges used by various features related to user-mode Hardware-enforced Stack Protection (HSP). + * \remarks https://learn.microsoft.com/en-us/windows/win32/api/winnt/ns-winnt-process_dynamic_enforced_address_range + */ //typedef struct _PROCESS_DYNAMIC_ENFORCED_ADDRESS_RANGE //{ // ULONG_PTR BaseAddress; @@ -1432,30 +1703,50 @@ typedef struct _PROCESS_SYSCALL_PROVIDER_INFORMATION // PPROCESS_DYNAMIC_ENFORCED_ADDRESS_RANGE Ranges; //} PROCESS_DYNAMIC_ENFORCED_ADDRESS_RANGES_INFORMATION, *PPROCESS_DYNAMIC_ENFORCED_ADDRESS_RANGES_INFORMATION; +/** + * The PROCESS_MEMBERSHIP_INFORMATION structure contains the Silo identifier of the process. + * + * \remarks https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/ntddk/ns-ntddk-process_membership_information + */ typedef struct _PROCESS_MEMBERSHIP_INFORMATION { ULONG ServerSiloId; } PROCESS_MEMBERSHIP_INFORMATION, *PPROCESS_MEMBERSHIP_INFORMATION; #if !defined(NTDDI_WIN11_GE) || (NTDDI_VERSION < NTDDI_WIN11_GE) +/** + * The PROCESS_NETWORK_COUNTERS structure contains network usage statistics for a process. + */ typedef struct _PROCESS_NETWORK_COUNTERS { - ULONG64 BytesIn; - ULONG64 BytesOut; + ULONG64 BytesIn; // The total number of bytes received by the process. + ULONG64 BytesOut; // The total number of bytes sent by the process. } PROCESS_NETWORK_COUNTERS, *PPROCESS_NETWORK_COUNTERS; #endif +/** + * The PROCESS_TEB_VALUE_INFORMATION structure contains information from the Thread Environment Block (TEB) for a specific thread. + */ typedef struct _PROCESS_TEB_VALUE_INFORMATION { - ULONG ThreadId; - ULONG TebOffset; - ULONG_PTR Value; + ULONG ThreadId; // The identifier of the thread whose TEB is being queried or modified. + ULONG TebOffset; // The offset within the TEB where the value is located. + ULONG_PTR Value; // The value at the specified offset in the TEB. } PROCESS_TEB_VALUE_INFORMATION, *PPROCESS_TEB_VALUE_INFORMATION; +// rev +typedef struct _PROCESS_AVAILABLE_CPUS_INFORMATION +{ + ULONG64 ObservedSequenceNumber; + ULONG64 SequenceNumber; + ULONG AvailableCpusCount; + PKAFFINITY_EX Affinity; +} PROCESS_AVAILABLE_CPUS_INFORMATION, *PPROCESS_AVAILABLE_CPUS_INFORMATION; + /** * The NtQueryPortInformationProcess function retrieves the status of the current process exception port. * - * @return LOGICAL If TRUE, the process exception port is valid. + * \return LOGICAL If TRUE, the process exception port is valid. */ NTSYSCALLAPI LOGICAL @@ -1464,32 +1755,33 @@ NtQueryPortInformationProcess( VOID ); -#endif // PHNT_MODE != PHNT_MODE_KERNEL +#endif // (PHNT_MODE != PHNT_MODE_KERNEL) // // Thread information structures // +/** + * The THREAD_BASIC_INFORMATION structure contains basic information about the thread. + */ typedef struct _THREAD_BASIC_INFORMATION { - NTSTATUS ExitStatus; - PTEB TebBaseAddress; - CLIENT_ID ClientId; - KAFFINITY AffinityMask; - KPRIORITY Priority; - KPRIORITY BasePriority; + NTSTATUS ExitStatus; // The exit status of the thread or STATUS_PENDING when the thread has not terminated. (GetExitCodeThread) + PTEB TebBaseAddress; // The base address of the memory region containing the TEB structure. (NtCurrentTeb) + CLIENT_ID ClientId; // The process and thread identifier of the thread. + KAFFINITY AffinityMask; // The affinity mask of the thread. (deprecated) (SetThreadAffinityMask) + KPRIORITY Priority; // The current priority of the thread. (GetThreadPriority) + KPRIORITY BasePriority; // The current base priority of the thread determined by the thread priority and process priority class. } THREAD_BASIC_INFORMATION, *PTHREAD_BASIC_INFORMATION; +/** + * The THREAD_LAST_SYSCALL_INFORMATION structure contains information about the last system call made by a thread. + */ 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; + PVOID FirstArgument; // Pointer to the first argument of the last system call. + USHORT SystemCallNumber; // The system call number of the last system call made by the thread. + ULONG64 WaitTime; // The time spent waiting for the system call to complete, in milliseconds. } THREAD_LAST_SYSCALL_INFORMATION, *PTHREAD_LAST_SYSCALL_INFORMATION; /** @@ -1497,8 +1789,8 @@ typedef struct _THREAD_LAST_SYSCALL_INFORMATION */ typedef struct _THREAD_CYCLE_TIME_INFORMATION { - ULONGLONG AccumulatedCycles; // The total number of cycles accumulated by the thread. - ULONGLONG CurrentCycleCount; // The current cycle count of the thread. + ULONG64 AccumulatedCycles; // The total number of cycles accumulated by the thread. + ULONG64 CurrentCycleCount; // The current cycle count of the thread. } THREAD_CYCLE_TIME_INFORMATION, *PTHREAD_CYCLE_TIME_INFORMATION; // RtlAbPostRelease / ReleaseAllUserModeAutoBoostLockHandles @@ -1550,6 +1842,7 @@ typedef struct _COUNTER_READING * * \remarks https://learn.microsoft.com/en-us/windows/win32/api/winnt/ns-winnt-performance_data */ +_Struct_size_bytes_(Size) typedef struct _THREAD_PERFORMANCE_DATA { USHORT Size; // The size of the structure. @@ -1688,7 +1981,7 @@ typedef enum _SUBSYSTEM_INFORMATION_TYPE SubsystemInformationTypeWSL, MaxSubsystemInformationType } SUBSYSTEM_INFORMATION_TYPE; -#endif +#endif // (PHNT_MODE != PHNT_MODE_KERNEL) typedef enum _THREAD_WORKLOAD_CLASS { @@ -1705,9 +1998,7 @@ typedef enum _THREAD_WORKLOAD_CLASS #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 @@ -1724,61 +2015,61 @@ typedef struct DECLSPEC_ALIGN(8) DECLSPEC_NOINITALL _ARM_NT_CONTEXT { // Control flags. // - DWORD ContextFlags; + ULONG 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; + ULONG R0; + ULONG R1; + ULONG R2; + ULONG R3; + ULONG R4; + ULONG R5; + ULONG R6; + ULONG R7; + ULONG R8; + ULONG R9; + ULONG R10; + ULONG R11; + ULONG R12; // // Control Registers // - DWORD Sp; - DWORD Lr; - DWORD Pc; - DWORD Cpsr; + ULONG Sp; + ULONG Lr; + ULONG Pc; + ULONG Cpsr; // // Floating Point/NEON Registers // - DWORD Fpscr; - DWORD Padding; + ULONG Fpscr; + ULONG Padding; union { ARM_NT_NEON128 Q[16]; ULONGLONG D[32]; - DWORD S[32]; + ULONG 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]; + ULONG Bvr[ARM_MAX_BREAKPOINTS]; + ULONG Bcr[ARM_MAX_BREAKPOINTS]; + ULONG Wvr[ARM_MAX_WATCHPOINTS]; + ULONG Wcr[ARM_MAX_WATCHPOINTS]; - DWORD Padding2[2]; + ULONG Padding2[2]; } ARM_NT_CONTEXT, *PARM_NT_CONTEXT; -#endif +#endif // _ARM64_ // private typedef struct _THREAD_INDEX_INFORMATION @@ -1796,15 +2087,15 @@ typedef struct _THREAD_INDEX_INFORMATION /** * Creates a new process. * - * @param ProcessHandle A pointer to a handle that receives the process object handle. - * @param DesiredAccess The access rights desired for the process object. - * @param ObjectAttributes Optional. A pointer to an OBJECT_ATTRIBUTES structure that specifies the attributes of the new process. - * @param ParentProcess A handle to the parent process. - * @param InheritObjectTable If TRUE, the new process inherits the object table of the parent process. - * @param SectionHandle Optional. A handle to a section object to be used for the new process. - * @param DebugPort Optional. A handle to a debug port to be used for the new process. - * @param TokenHandle Optional. A handle to an access token to be used for the new process. - * @return NTSTATUS Successful or errant status. + * \param ProcessHandle A pointer to a handle that receives the process object handle. + * \param DesiredAccess The access rights desired for the process object. + * \param ObjectAttributes Optional. A pointer to an OBJECT_ATTRIBUTES structure that specifies the attributes of the new process. + * \param ParentProcess A handle to the parent process. + * \param InheritObjectTable If TRUE, the new process inherits the object table of the parent process. + * \param SectionHandle Optional. A handle to a section object to be used for the new process. + * \param DebugPort Optional. A handle to a debug port to be used for the new process. + * \param TokenHandle Optional. A handle to an access token to be used for the new process. + * \return NTSTATUS Successful or errant status. */ NTSYSCALLAPI NTSTATUS @@ -1822,41 +2113,41 @@ NtCreateProcess( // begin_rev #define PROCESS_CREATE_FLAGS_NONE 0x00000000 -#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 SeLockMemoryPrivilege) -#define PROCESS_CREATE_FLAGS_LARGE_PAGE_SYSTEM_DLL 0x00000020 // NtCreateProcessEx only (requires SeLockMemoryPrivilege) -#define PROCESS_CREATE_FLAGS_PROTECTED_PROCESS 0x00000040 // NtCreateUserProcess only -#define PROCESS_CREATE_FLAGS_CREATE_SESSION 0x00000080 // NtCreateProcessEx & NtCreateUserProcess (requires SeLoadDriverPrivilege) -#define PROCESS_CREATE_FLAGS_INHERIT_FROM_PARENT 0x00000100 // NtCreateProcessEx & NtCreateUserProcess -#define PROCESS_CREATE_FLAGS_CREATE_SUSPENDED 0x00000200 // NtCreateProcessEx & NtCreateUserProcess -#define PROCESS_CREATE_FLAGS_FORCE_BREAKAWAY 0x00000400 // NtCreateProcessEx & NtCreateUserProcess (requires SeTcbPrivilege) -#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_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 SeLockMemoryPrivilege) +#define PROCESS_CREATE_FLAGS_LARGE_PAGE_SYSTEM_DLL 0x00000020 // NtCreateProcessEx only (requires SeLockMemoryPrivilege) +#define PROCESS_CREATE_FLAGS_PROTECTED_PROCESS 0x00000040 // NtCreateUserProcess only +#define PROCESS_CREATE_FLAGS_CREATE_SESSION 0x00000080 // NtCreateProcessEx & NtCreateUserProcess (requires SeLoadDriverPrivilege) +#define PROCESS_CREATE_FLAGS_INHERIT_FROM_PARENT 0x00000100 // NtCreateProcessEx & NtCreateUserProcess +#define PROCESS_CREATE_FLAGS_CREATE_SUSPENDED 0x00000200 // NtCreateProcessEx & NtCreateUserProcess +#define PROCESS_CREATE_FLAGS_FORCE_BREAKAWAY 0x00000400 // NtCreateProcessEx & NtCreateUserProcess (requires SeTcbPrivilege) +#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 SeTcbPrivilege) -#define PROCESS_CREATE_FLAGS_CREATE_STORE 0x00020000 // NtCreateProcessEx & NtCreateUserProcess -#define PROCESS_CREATE_FLAGS_USE_PROTECTED_ENVIRONMENT 0x00040000 // NtCreateProcessEx & NtCreateUserProcess +#define PROCESS_CREATE_FLAGS_AUXILIARY_PROCESS 0x00008000 // NtCreateProcessEx & NtCreateUserProcess (requires SeTcbPrivilege) +#define PROCESS_CREATE_FLAGS_CREATE_STORE 0x00020000 // NtCreateProcessEx & NtCreateUserProcess +#define PROCESS_CREATE_FLAGS_USE_PROTECTED_ENVIRONMENT 0x00040000 // NtCreateProcessEx & NtCreateUserProcess #define PROCESS_CREATE_FLAGS_IMAGE_EXPANSION_MITIGATION_DISABLE 0x00080000 -#define PROCESS_CREATE_FLAGS_PARTITION_CREATE_SLAB_IDENTITY 0x00400000 // NtCreateProcessEx & NtCreateUserProcess (requires SeLockMemoryPrivilege) +#define PROCESS_CREATE_FLAGS_PARTITION_CREATE_SLAB_IDENTITY 0x00400000 // NtCreateProcessEx & NtCreateUserProcess (requires SeLockMemoryPrivilege) // end_rev /** * Creates a new process with extended options. * - * @param ProcessHandle A pointer to a handle that receives the process object handle. - * @param DesiredAccess The access rights desired for the process object. - * @param ObjectAttributes Optional. A pointer to an OBJECT_ATTRIBUTES structure that specifies the attributes of the new process. - * @param ParentProcess A handle to the parent process. - * @param Flags Flags that control the creation of the process. These flags are defined as PROCESS_CREATE_FLAGS_*. - * @param SectionHandle Optional. A handle to a section object to be used for the new process. - * @param DebugPort Optional. A handle to a debug port to be used for the new process. - * @param TokenHandle Optional. A handle to an access token to be used for the new process. - * @param Reserved Reserved for future use. Must be zero. - * @return NTSTATUS Successful or errant status. + * \param ProcessHandle A pointer to a handle that receives the process object handle. + * \param DesiredAccess The access rights desired for the process object. + * \param ObjectAttributes Optional. A pointer to an OBJECT_ATTRIBUTES structure that specifies the attributes of the new process. + * \param ParentProcess A handle to the parent process. + * \param Flags Flags that control the creation of the process. These flags are defined as PROCESS_CREATE_FLAGS_*. + * \param SectionHandle Optional. A handle to a section object to be used for the new process. + * \param DebugPort Optional. A handle to a debug port to be used for the new process. + * \param TokenHandle Optional. A handle to an access token to be used for the new process. + * \param Reserved Reserved for future use. Must be zero. + * \return NTSTATUS Successful or errant status. */ NTSYSCALLAPI NTSTATUS @@ -1876,11 +2167,12 @@ NtCreateProcessEx( /** * Opens an existing process object. * - * @param ProcessHandle A pointer to a handle that receives the process object handle. - * @param DesiredAccess The access rights desired for the process object. - * @param ObjectAttributes A pointer to an OBJECT_ATTRIBUTES structure that specifies the attributes of the new process. - * @param ClientId Optional. A pointer to a CLIENT_ID structure that specifies the client ID of the process to be opened. - * @return NTSTATUS Successful or errant status. + * \param ProcessHandle A pointer to a handle that receives the process object handle. + * \param DesiredAccess The access rights desired for the process object. + * \param ObjectAttributes A pointer to an OBJECT_ATTRIBUTES structure that specifies the attributes of the new process. + * \param ClientId Optional. A pointer to a CLIENT_ID structure that specifies the client ID of the process to be opened. + * \return NTSTATUS Successful or errant status. + * \sa https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/ntddk/nf-ntddk-ntopenprocess */ NTSYSCALLAPI NTSTATUS @@ -1895,9 +2187,10 @@ NtOpenProcess( /** * Terminates the specified process. * - * @param ProcessHandle Optional. A handle to the process to be terminated. If this parameter is NULL, the calling process is terminated. - * @param ExitStatus The exit status to be used by the process and the process's termination status. - * @return NTSTATUS Successful or errant status. + * \param ProcessHandle Optional. A handle to the process to be terminated. If this parameter is NULL, the calling process is terminated. + * \param ExitStatus The exit status to be used by the process and the process's termination status. + * \return NTSTATUS Successful or errant status. + * \sa https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/ntddk/nf-ntddk-zwterminateprocess */ NTSYSCALLAPI NTSTATUS @@ -1910,8 +2203,9 @@ NtTerminateProcess( /** * Suspends the specified process. * - * @param ProcessHandle A handle to the process to be suspended. - * @return NTSTATUS Successful or errant status. + * \param ProcessHandle A handle to the process to be suspended. + * \return NTSTATUS Successful or errant status. + * \remarks Use NtCreateProcessStateChange instead. */ NTSYSCALLAPI NTSTATUS @@ -1923,8 +2217,9 @@ NtSuspendProcess( /** * Resumes the specified process. * - * @param ProcessHandle A handle to the process to be resumed. - * @return NTSTATUS Successful or errant status. + * \param ProcessHandle A handle to the process to be resumed. + * \return NTSTATUS Successful or errant status. + * \remarks Use NtCreateProcessStateChange instead. */ NTSYSCALLAPI NTSTATUS @@ -1955,21 +2250,21 @@ NtResumeProcess( #define NtCurrentThreadEffectiveToken() ((HANDLE)(LONG_PTR)-6) // NtOpenThreadToken(NtCurrentThread()) + NtOpenProcessToken(NtCurrentProcess()) #define NtCurrentSilo() ((HANDLE)(LONG_PTR)-1) -EXTERN_C CONST IMAGE_DOS_HEADER __ImageBase; -#define NtCurrentImageBase() ((PIMAGE_DOS_HEADER)&__ImageBase) +EXTERN_C IMAGE_DOS_HEADER __ImageBase; +#define NtCurrentImageBase() ((PVOID)((PIMAGE_DOS_HEADER)&__ImageBase)) #define NtCurrentSessionId() (RtlGetActiveConsoleId()) // USER_SHARED_DATA->ActiveConsoleId -#define NtCurrentLogonId() (NtCurrentPeb()->LogonId) +//#define NtCurrentLogonId() (NtCurrentPeb()->LogonId) /** - * Retrieves information about the specified process. + * The NtQueryInformationProcess routine retrieves information about the specified process. * - * @param ProcessHandle A handle to the process. - * @param ProcessInformationClass The type of process information to be retrieved. - * @param ProcessInformation A pointer to a buffer that receives the process information. - * @param ProcessInformationLength The size of the buffer pointed to by the ProcessInformation parameter. - * @param ReturnLength An optional pointer to a variable that receives the size of the data returned. - * @return NTSTATUS Successful or errant status. + * \param ProcessHandle A handle to the process. + * \param ProcessInformationClass The type of process information to be retrieved. + * \param ProcessInformation A pointer to a buffer that receives the process information. + * \param ProcessInformationLength The size of the buffer pointed to by the ProcessInformation parameter. + * \param ReturnLength An optional pointer to a variable that receives the size of the data returned. + * \return NTSTATUS Successful or errant status. */ NTSYSCALLAPI NTSTATUS @@ -1983,7 +2278,17 @@ NtQueryInformationProcess( ); // rev -NTSYSCALLAPI +/** + * The NtWow64QueryInformationProcess64 routine retrieves information about the specified process. + * + * \param ProcessHandle A handle to the process. + * \param ProcessInformationClass The type of process information to be retrieved. + * \param ProcessInformation A pointer to a buffer that receives the process information. + * \param ProcessInformationLength The size of the buffer pointed to by the ProcessInformation parameter. + * \param ReturnLength An optional pointer to a variable that receives the size of the data returned. + * \return NTSTATUS Successful or errant status. + */ +NTSYSAPI NTSTATUS NTAPI NtWow64QueryInformationProcess64( @@ -1995,13 +2300,13 @@ NtWow64QueryInformationProcess64( ); /** - * Sets information for the specified process. + * The NtSetInformationProcess routine sets information for the specified process. * - * @param ProcessHandle A handle to the process. - * @param ProcessInformationClass The type of process information to be set. - * @param ProcessInformation A pointer to a buffer that contains the process information. - * @param ProcessInformationLength The size of the buffer pointed to by the ProcessInformation parameter. - * @return NTSTATUS Successful or errant status. + * \param ProcessHandle A handle to the process. + * \param ProcessInformationClass The type of process information to be set. + * \param ProcessInformation A pointer to a buffer that contains the process information. + * \param ProcessInformationLength The size of the buffer pointed to by the ProcessInformation parameter. + * \return NTSTATUS Successful or errant status. */ NTSYSCALLAPI NTSTATUS @@ -2013,19 +2318,27 @@ NtSetInformationProcess( _In_ ULONG ProcessInformationLength ); +/** + * The PROCESS_GET_NEXT_FLAGS_PREVIOUS_PROCESS flag retrieves the previous process in the system. + * + * When calling NtGetNextProcess, this flag can be specified in the Flags parameter to indicate + * that the function should return the previous process in the system enumeration order, + * rather than the next process. This can be useful for iterating through processes in reverse order. + */ +#ifndef PROCESS_GET_NEXT_FLAGS_PREVIOUS_PROCESS #define PROCESS_GET_NEXT_FLAGS_PREVIOUS_PROCESS 0x00000001 +#endif -#if (PHNT_VERSION >= PHNT_WINDOWS_SERVER_2003) /** * Retrieves a handle to the next process in the system. * - * @param ProcessHandle An optional handle to a process. If this parameter is NULL, the function retrieves the first process in the system. - * @param DesiredAccess The access rights desired for the new process handle. - * @param HandleAttributes The attributes for the new process handle. - * @param Flags Flags that modify the behavior of the function. This can be a combination of the following flags: + * \param ProcessHandle An optional handle to a process. If this parameter is NULL, the function retrieves the first process in the system. + * \param DesiredAccess The access rights desired for the new process handle. + * \param HandleAttributes The attributes for the new process handle. + * \param Flags Flags that modify the behavior of the function. This can be a combination of the following flags: * - \ref PROCESS_GET_NEXT_FLAGS_PREVIOUS_PROCESS (0x00000001): Retrieve the previous process in the system. - * @param NewProcessHandle A pointer to a variable that receives the handle to the next process. - * @return NTSTATUS Successful or errant status. + * \param NewProcessHandle A pointer to a variable that receives the handle to the next process. + * \return NTSTATUS Successful or errant status. */ NTSYSCALLAPI NTSTATUS @@ -2041,14 +2354,13 @@ NtGetNextProcess( /** * Retrieves a handle to the next thread in the system. * - * @param ProcessHandle A handle to the process for enumerateration of threads. - * @param ThreadHandle An optional handle to a thread. If this parameter is NULL, the function retrieves the first thread in the process. - * @param DesiredAccess The access rights desired for the new thread handle. - * @param HandleAttributes The attributes for the new thread handle. - * @param Flags Flags that modify the behavior of the function. This can be a combination of the following flags: - * - \ref THREAD_GET_NEXT_FLAGS_PREVIOUS_THREAD (0x00000001): Retrieve the previous thread in the process. - * @param NewThreadHandle A pointer to a variable that receives the handle to the next thread. - * @return NTSTATUS Successful or errant status. + * \param ProcessHandle A handle to the process for enumeration of threads. + * \param ThreadHandle An optional handle to a thread. If this parameter is NULL, the function retrieves the first thread in the process. + * \param DesiredAccess The access rights desired for the new thread handle. + * \param HandleAttributes The attributes for the new thread handle. + * \param Flags Flags that modify the behavior of the function. Unused and should be zero. + * \param NewThreadHandle A pointer to a variable that receives the handle to the next thread. + * \return NTSTATUS Successful or errant status. */ NTSYSCALLAPI NTSTATUS @@ -2058,12 +2370,11 @@ NtGetNextThread( _In_opt_ HANDLE ThreadHandle, _In_ ACCESS_MASK DesiredAccess, _In_ ULONG HandleAttributes, - _In_ ULONG Flags, + _In_opt_ _Reserved_ ULONG Flags, _Out_ PHANDLE NewThreadHandle ); -#endif -#endif +#endif // PHNT_MODE != PHNT_MODE_KERNEL #define STATECHANGE_SET_ATTRIBUTES 0x0001 @@ -2078,12 +2389,12 @@ typedef enum _PROCESS_STATE_CHANGE_TYPE /** * Creates a state change handle for changing the suspension state of a process. * - * @param ProcessStateChangeHandle A pointer to a variable that receives the handle. - * @param DesiredAccess The access rights desired for the handle. - * @param ObjectAttributes Optional attributes for the handle. - * @param ProcessHandle A handle to the process. - * @param Reserved Reserved for future use. - * @return NTSTATUS Successful or errant status. + * \param ProcessStateChangeHandle A pointer to a variable that receives the handle. + * \param DesiredAccess The access rights desired for the handle. + * \param ObjectAttributes Optional attributes for the handle. + * \param ProcessHandle A handle to the process. + * \param Reserved Reserved for future use. + * \return NTSTATUS Successful or errant status. */ NTSYSCALLAPI NTSTATUS @@ -2093,19 +2404,19 @@ NtCreateProcessStateChange( _In_ ACCESS_MASK DesiredAccess, _In_opt_ PCOBJECT_ATTRIBUTES ObjectAttributes, _In_ HANDLE ProcessHandle, - _In_opt_ _Reserved_ ULONG64 Reserved + _In_opt_ _Reserved_ ULONG Reserved ); /** * Changes the suspension state of a process. * - * @param ProcessStateChangeHandle A handle to the process state change object. - * @param ProcessHandle A handle to the process. - * @param StateChangeType The type of state change. - * @param ExtendedInformation Optional extended information. - * @param ExtendedInformationLength The length of the extended information. - * @param Reserved Reserved for future use. - * @return NTSTATUS Successful or errant status. + * \param ProcessStateChangeHandle A handle to the process state change object. + * \param ProcessHandle A handle to the process. + * \param StateChangeType The type of state change. + * \param ExtendedInformation Optional extended information. + * \param ExtendedInformationLength The length of the extended information. + * \param Reserved Reserved for future use. + * \return NTSTATUS Successful or errant status. */ NTSYSCALLAPI NTSTATUS @@ -2116,27 +2427,20 @@ NtChangeProcessState( _In_ PROCESS_STATE_CHANGE_TYPE StateChangeType, _In_opt_ _Reserved_ PVOID ExtendedInformation, _In_opt_ _Reserved_ SIZE_T ExtendedInformationLength, - _In_opt_ _Reserved_ ULONG64 Reserved + _In_opt_ _Reserved_ ULONG Reserved ); -#endif - -typedef enum _THREAD_STATE_CHANGE_TYPE -{ - ThreadStateChangeSuspend, - ThreadStateChangeResume, - ThreadStateChangeMax, -} THREAD_STATE_CHANGE_TYPE, *PTHREAD_STATE_CHANGE_TYPE; +#endif // PHNT_VERSION >= PHNT_WINDOWS_11 #if (PHNT_VERSION >= PHNT_WINDOWS_11) /** * Creates a state change handle for changing the suspension state of a thread. * - * @param ThreadStateChangeHandle A pointer to a variable that receives the handle. - * @param DesiredAccess The access rights desired for the handle. - * @param ObjectAttributes Optional attributes for the handle. - * @param ThreadHandle A handle to the thread. - * @param Reserved Reserved for future use. - * @return NTSTATUS Successful or errant status. + * \param ThreadStateChangeHandle A pointer to a variable that receives the handle. + * \param DesiredAccess The access rights desired for the handle. + * \param ObjectAttributes Optional attributes for the handle. + * \param ThreadHandle A handle to the thread. + * \param Reserved Reserved for future use. + * \return NTSTATUS Successful or errant status. */ NTSYSCALLAPI NTSTATUS @@ -2146,19 +2450,26 @@ NtCreateThreadStateChange( _In_ ACCESS_MASK DesiredAccess, _In_opt_ PCOBJECT_ATTRIBUTES ObjectAttributes, _In_ HANDLE ThreadHandle, - _In_opt_ ULONG64 Reserved + _In_opt_ _Reserved_ ULONG Reserved ); +typedef enum _THREAD_STATE_CHANGE_TYPE +{ + ThreadStateChangeSuspend, + ThreadStateChangeResume, + ThreadStateChangeMax, +} THREAD_STATE_CHANGE_TYPE, *PTHREAD_STATE_CHANGE_TYPE; + /** * Changes the suspension state of a thread. * - * @param ThreadStateChangeHandle A handle to the thread state change object. - * @param ThreadHandle A handle to the thread. - * @param StateChangeType The type of state change. - * @param ExtendedInformation Optional extended information. - * @param ExtendedInformationLength The length of the extended information. - * @param Reserved Reserved for future use. - * @return NTSTATUS Successful or errant status. + * \param ThreadStateChangeHandle A handle to the thread state change object. + * \param ThreadHandle A handle to the thread. + * \param StateChangeType The type of state change. + * \param ExtendedInformation Optional extended information. + * \param ExtendedInformationLength The length of the extended information. + * \param Reserved Reserved for future use. + * \return NTSTATUS Successful or errant status. */ NTSYSCALLAPI NTSTATUS @@ -2169,9 +2480,9 @@ NtChangeThreadState( _In_ THREAD_STATE_CHANGE_TYPE StateChangeType, _In_opt_ PVOID ExtendedInformation, _In_opt_ SIZE_T ExtendedInformationLength, - _In_opt_ ULONG64 Reserved + _In_opt_ ULONG Reserved ); -#endif +#endif // PHNT_VERSION >= PHNT_WINDOWS_11 // // Threads @@ -2181,15 +2492,15 @@ NtChangeThreadState( /** * Creates a new thread in the specified process. * - * @param ThreadHandle A pointer to a handle that receives the thread object handle. - * @param DesiredAccess The access rights desired for the thread object. - * @param ObjectAttributes Optional. A pointer to an OBJECT_ATTRIBUTES structure that specifies the attributes of the new thread. - * @param ProcessHandle A handle to the process in which the thread is to be created. - * @param ClientId A pointer to a CLIENT_ID structure that receives the client ID of the new thread. - * @param ThreadContext A pointer to a CONTEXT structure that specifies the initial context of the new thread. - * @param InitialTeb A pointer to an INITIAL_TEB structure that specifies the initial stack limits of the new thread. - * @param CreateSuspended If TRUE, the thread is created in a suspended state. - * @return NTSTATUS Successful or errant status. + * \param ThreadHandle A pointer to a handle that receives the thread object handle. + * \param DesiredAccess The access rights desired for the thread object. + * \param ObjectAttributes Optional. A pointer to an OBJECT_ATTRIBUTES structure that specifies the attributes of the new thread. + * \param ProcessHandle A handle to the process in which the thread is to be created. + * \param ClientId A pointer to a CLIENT_ID structure that receives the client ID of the new thread. + * \param ThreadContext A pointer to a CONTEXT structure that specifies the initial context of the new thread. + * \param InitialTeb A pointer to an INITIAL_TEB structure that specifies the initial stack limits of the new thread. + * \param CreateSuspended If TRUE, the thread is created in a suspended state. + * \return NTSTATUS Successful or errant status. */ NTSYSCALLAPI NTSTATUS @@ -2208,11 +2519,11 @@ NtCreateThread( /** * Opens an existing thread object. * - * @param ThreadHandle A pointer to a handle that receives the thread object handle. - * @param DesiredAccess The access rights desired for the thread object. - * @param ObjectAttributes Optional. A pointer to an OBJECT_ATTRIBUTES structure that specifies the attributes of the new thread. - * @param ClientId Optional. A pointer to a CLIENT_ID structure that specifies the client ID of the thread to be opened. - * @return NTSTATUS Successful or errant status. + * \param ThreadHandle A pointer to a handle that receives the thread object handle. + * \param DesiredAccess The access rights desired for the thread object. + * \param ObjectAttributes Optional. A pointer to an OBJECT_ATTRIBUTES structure that specifies the attributes of the new thread. + * \param ClientId Optional. A pointer to a CLIENT_ID structure that specifies the client ID of the thread to be opened. + * \return NTSTATUS Successful or errant status. */ NTSYSCALLAPI NTSTATUS @@ -2227,9 +2538,9 @@ NtOpenThread( /** * Terminates the specified thread. * - * @param ThreadHandle Optional. A handle to the thread to be terminated. If this parameter is NULL, the calling thread is terminated. - * @param ExitStatus The exit status to be used by the thread and the thread's termination status. - * @return NTSTATUS Successful or errant status. + * \param ThreadHandle Optional. A handle to the thread to be terminated. If this parameter is NULL, the calling thread is terminated. + * \param ExitStatus The exit status to be used by the thread and the thread's termination status. + * \return NTSTATUS Successful or errant status. */ NTSYSCALLAPI NTSTATUS @@ -2242,9 +2553,9 @@ NtTerminateThread( /** * Suspends the specified thread. * - * @param ThreadHandle A handle to the thread to be suspended. - * @param PreviousSuspendCount Optional. A pointer to a variable that receives the thread's previous suspend count. - * @return NTSTATUS Successful or errant status. + * \param ThreadHandle A handle to the thread to be suspended. + * \param PreviousSuspendCount Optional. A pointer to a variable that receives the thread's previous suspend count. + * \return NTSTATUS Successful or errant status. */ NTSYSCALLAPI NTSTATUS @@ -2257,9 +2568,9 @@ NtSuspendThread( /** * Resumes the specified thread. * - * @param ThreadHandle A handle to the thread to be resumed. - * @param PreviousSuspendCount Optional. A pointer to a variable that receives the thread's previous suspend count. - * @return NTSTATUS Successful or errant status. + * \param ThreadHandle A handle to the thread to be resumed. + * \param PreviousSuspendCount Optional. A pointer to a variable that receives the thread's previous suspend count. + * \return NTSTATUS Successful or errant status. */ NTSYSCALLAPI NTSTATUS @@ -2269,11 +2580,11 @@ NtResumeThread( _Out_opt_ PULONG PreviousSuspendCount ); -#if (PHNT_VERSION >= PHNT_WINDOWS_SERVER_2003) /** * Retrieves the number of the current processor. * - * @return ULONG The number of the current processor. + * \return ULONG The number of the current processor. + * \sa https://learn.microsoft.com/en-us/windows/win32/procthread/ntgetcurrentprocessornumber */ NTSYSCALLAPI ULONG @@ -2281,14 +2592,13 @@ NTAPI NtGetCurrentProcessorNumber( VOID ); -#endif -#if (PHNT_VERSION >= PHNT_WINDOWS_7) /** * Retrieves the number of the current processor. * - * @param ProcessorNumber An optional pointer to a PROCESSOR_NUMBER structure that receives the processor number. - * @return ULONG The number of the current processor. + * \param ProcessorNumber An optional pointer to a PROCESSOR_NUMBER structure that receives the processor number. + * \return ULONG The number of the current processor. + * \sa https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/ntddk/nf-ntddk-kegetcurrentprocessornumberex */ NTSYSCALLAPI ULONG @@ -2296,14 +2606,13 @@ NTAPI NtGetCurrentProcessorNumberEx( _Out_opt_ PPROCESSOR_NUMBER ProcessorNumber ); -#endif /** * Retrieves the context of the specified thread. * - * @param ThreadHandle A handle to the thread. - * @param ThreadContext A pointer to a CONTEXT structure that receives the thread context. - * @return NTSTATUS Successful or errant status. + * \param ThreadHandle A handle to the thread. + * \param ThreadContext A pointer to a CONTEXT structure that receives the thread context. + * \return NTSTATUS Successful or errant status. */ NTSYSCALLAPI NTSTATUS @@ -2316,9 +2625,9 @@ NtGetContextThread( /** * Sets the context of the specified thread. * - * @param ThreadHandle A handle to the thread. - * @param ThreadContext A pointer to a CONTEXT structure that specifies the thread context. - * @return NTSTATUS Successful or errant status. + * \param ThreadHandle A handle to the thread. + * \param ThreadContext A pointer to a CONTEXT structure that specifies the thread context. + * \return NTSTATUS Successful or errant status. */ NTSYSCALLAPI NTSTATUS @@ -2327,15 +2636,16 @@ NtSetContextThread( _In_ HANDLE ThreadHandle, _In_ PCONTEXT ThreadContext ); + /** * Retrieves information about the specified thread. * - * @param ThreadHandle A handle to the thread. - * @param ThreadInformationClass The type of thread information to be retrieved. - * @param ThreadInformation A pointer to a buffer that receives the thread information. - * @param ThreadInformationLength The size of the buffer pointed to by the ThreadInformation parameter. - * @param ReturnLength An optional pointer to a variable that receives the size of the data returned. - * @return NTSTATUS Successful or errant status. + * \param ThreadHandle A handle to the thread. + * \param ThreadInformationClass The type of thread information to be retrieved. + * \param ThreadInformation A pointer to a buffer that receives the thread information. + * \param ThreadInformationLength The size of the buffer pointed to by the ThreadInformation parameter. + * \param ReturnLength An optional pointer to a variable that receives the size of the data returned. + * \return NTSTATUS Successful or errant status. */ NTSYSCALLAPI NTSTATUS @@ -2351,11 +2661,11 @@ NtQueryInformationThread( /** * Sets information for the specified thread. * - * @param ThreadHandle A handle to the thread. - * @param ThreadInformationClass The type of thread information to be set. - * @param ThreadInformation A pointer to a buffer that contains the thread information. - * @param ThreadInformationLength The size of the buffer pointed to by the ThreadInformation parameter. - * @return NTSTATUS Successful or errant status. + * \param ThreadHandle A handle to the thread. + * \param ThreadInformationClass The type of thread information to be set. + * \param ThreadInformation A pointer to a buffer that contains the thread information. + * \param ThreadInformationLength The size of the buffer pointed to by the ThreadInformation parameter. + * \return NTSTATUS Successful or errant status. */ NTSYSCALLAPI NTSTATUS @@ -2368,10 +2678,10 @@ NtSetInformationThread( ); /** - * Sends an alert to the specified thread. + * The NtAlertThread routine alerts the specified thread. * - * @param ThreadHandle A handle to the thread to be alerted. - * @return NTSTATUS Successful or errant status. + * \param[in] ThreadHandle A handle to the thread to be alerted. + * \return NTSTATUS Successful or errant status. */ NTSYSCALLAPI NTSTATUS @@ -2381,11 +2691,11 @@ NtAlertThread( ); /** - * Resumes a thread that was previously suspended and sends an alert to it. + * The NtAlertResumeThread routine resumes a specified thread that was previously suspended and alerts the thread. * - * @param ThreadHandle A handle to the thread to be resumed and alerted. - * @param PreviousSuspendCount An optional pointer to a variable that receives the thread's previous suspend count. - * @return NTSTATUS Successful or errant status. + * \param[in] ThreadHandle A handle to the thread to be resumed and alerted. + * \param[out, optional] PreviousSuspendCount An optional pointer to a variable that receives the thread's previous suspend count. + * \return NTSTATUS Successful or errant status. */ NTSYSCALLAPI NTSTATUS @@ -2396,9 +2706,10 @@ NtAlertResumeThread( ); /** - * Tests whether the current thread has an alert pending. + * The NtTestAlert routine indicates whether the current thread has an alert pending + * and executes asynchronous procedure calls (APCs) queued to the current thread. * - * @return NTSTATUS Successful or errant status. + * \return NTSTATUS Successful or errant status. */ NTSYSCALLAPI NTSTATUS @@ -2410,10 +2721,10 @@ NtTestAlert( #if (PHNT_VERSION >= PHNT_WINDOWS_8) // rev /** - * Sends an alert to the specified thread. + * The NtAlertThreadByThreadId routine sends an alert to the specified thread. * - * @param ThreadId The thread ID of the thread to be alerted. - * @return NTSTATUS Successful or errant status. + * \param ThreadId The thread ID of the thread to be alerted. + * \return NTSTATUS Successful or errant status. */ NTSYSCALLAPI NTSTATUS @@ -2421,15 +2732,15 @@ NTAPI NtAlertThreadByThreadId( _In_ HANDLE ThreadId ); -#endif +#endif // PHNT_VERSION >= PHNT_WINDOWS_8 #if (PHNT_VERSION >= PHNT_WINDOWS_11) /** - * Sends an alert to the specified thread by its thread ID, with an optional lock. + * The NtAlertThreadByThreadIdEx routine sends an alert to the specified thread by its thread ID, with an optional lock. * - * @param ThreadId The thread ID of the thread to be alerted. - * @param Lock An optional pointer to an SRW lock to be used during the alert. - * @return NTSTATUS Successful or errant status. + * \param ThreadId The thread ID of the thread to be alerted. + * \param Lock An optional pointer to an SRW lock to be used during the alert. + * \return NTSTATUS Successful or errant status. */ NTSYSCALLAPI NTSTATUS @@ -2440,13 +2751,75 @@ NtAlertThreadByThreadIdEx( ); /** - * Sends an alert to multiple threads by their thread IDs. + * Identifies the interpretation of a PS_ALERT_THREAD_EXTENDED_PARAMETER record. * - * @param MultipleThreadId A pointer to an array of thread IDs to be alerted. - * @param Count The number of thread IDs in the array. - * @param Boost A pointer to a boost value to be applied to the threads. - * @param BoostCount The number of boost values in the array. - * @return NTSTATUS Successful or errant status. + * The current kernel implementation for NtAlertMultipleThreadByThreadId accepts only + * PsAlertMultipleExtendedParameterAutoBoostContext (0). Other values are rejected with + * STATUS_INVALID_PARAMETER. + */ +typedef enum _PS_ALERT_THREAD_EXTENDED_PARAMETER_TYPE +{ + /** + * AutoBoost context token passed into the kernel's AutoBoost (Ab) bookkeeping. + * + * The payload (ULong64/Pointer/etc.) is forwarded to internal routines and may be used to + * associate the wakeup with a particular synchronization/ownership handoff context. + */ + PsAlertMultipleExtendedParameterAutoBoostContext = 0, + /** + * Sentinel / upper bound (not a usable type). + */ + PsAlertMultipleExtendedParameterMax = 1, +} PS_ALERT_THREAD_EXTENDED_PARAMETER_TYPE, *PPS_ALERT_THREAD_EXTENDED_PARAMETER_TYPE; + +/** + * Extended parameter record for NtAlertMultipleThreadByThreadId. + * + * In the analyzed NtAlertMultipleThreadByThreadId implementation: + * - Type must be 0 (PsAlertMultipleExtendedParameterAutoBoostContext). + * - The union payload at offset +0x8 is forwarded as an opaque 64-bit context value. + */ +typedef struct _PS_ALERT_THREAD_EXTENDED_PARAMETER +{ + /** + * Parameter type (8-bit) + */ + ULONGLONG Type : 8; + /** + * Reserved bits; should be zero. + */ + ULONGLONG Reserved : 56; + /** + * Payload value whose meaning depends on Type. + * + * For Type == PsAlertMultipleExtendedParameterAutoBoostContext, this is treated as an + * opaque "AutoBoostContext" token. It may be pointer-like and may use low-bit tagging. + */ + union + { + ULONGLONG ULong64; + PVOID Pointer; + SIZE_T Size; + HANDLE Handle; + ULONG ULong; + UCHAR Boolean; + }; +} PS_ALERT_THREAD_EXTENDED_PARAMETER, *PPS_ALERT_THREAD_EXTENDED_PARAMETER; + +/** + * The NtAlertMultipleThreadByThreadId routine alerts each target thread specified by thread ID. + * Target threads must belong to the caller's current process (cross-process targets fail STATUS_ACCESS_DENIED). + * + * \param MultipleThreadId A pointer to an array of thread IDs to be alerted. + * \param Count The number of thread IDs in the array. + * \param ExtendedParameters An optional pointer to one or more extended parameters of type PS_ALERT_THREAD_EXTENDED_PARAMETER. + * \param ExtendedParameterCount Specifies the number of elements in the ExtendedParameters array. + * \return NTSTATUS Successful or errant status. + * \remarks STATUS_ACCESS_DENIED may be returned when the thread belongs to another process. + * \note + * - Only PS_ALERT_THREAD_EXTENDED_PARAMETER.Type == 0 is currently accepted. + * - If multiple extended parameters are provided, the implementation consumes them in order and + * the *last* parameter's payload is the one forwarded to the internal alert logic. */ NTSYSCALLAPI NTSTATUS @@ -2454,19 +2827,25 @@ NTAPI NtAlertMultipleThreadByThreadId( _In_ PHANDLE MultipleThreadId, _In_ ULONG Count, - _In_ PVOID Boost, - _In_ ULONG BoostCount + _Inout_updates_opt_(ExtendedParameterCount) PPS_ALERT_THREAD_EXTENDED_PARAMETER ExtendedParameters, + _In_ ULONG ExtendedParameterCount ); -#endif +#endif // PHNT_VERSION >= PHNT_WINDOWS_11 #if (PHNT_VERSION >= PHNT_WINDOWS_8) // rev /** - * Waits for an alert to be delivered to the specified thread. + * The NtWaitForAlertByThreadId routine blocks the calling thread until another thread calls NtAlertThreadByThreadId + * with a matching address, or until the timeout expires. * - * @param Address The address to wait for an alert on. - * @param Timeout The timeout value for waiting, or NULL for no timeout. - * @return NTSTATUS Successful or errant status. + * \param Address A unique address used to identify this wait operation. Other threads call + * NtAlertThreadByThreadId with this same address to wake the waiting thread. + * Can be NULL to wait on the thread ID itself. + * \param Timeout Optional timeout value. If NULL, waits indefinitely. If present, specifies + * the absolute or relative time to wait before returning STATUS_TIMEOUT. + * \return STATUS_SUCCESS if alerted successfully. + * \return STATUS_TIMEOUT if the timeout expired before being alerted. + * \return STATUS_ALERTED if woken by NtAlertThreadByThreadId. */ NTSYSCALLAPI NTSTATUS @@ -2475,15 +2854,15 @@ NtWaitForAlertByThreadId( _In_opt_ PVOID Address, _In_opt_ PLARGE_INTEGER Timeout ); -#endif +#endif // PHNT_VERSION >= PHNT_WINDOWS_8 /** * Impersonates a client thread. * - * @param ServerThreadHandle A handle to the server thread. - * @param ClientThreadHandle A handle to the client thread. - * @param SecurityQos A pointer to a SECURITY_QUALITY_OF_SERVICE structure that specifies the impersonation level and context tracking mode. - * @return NTSTATUS Successful or errant status. + * \param ServerThreadHandle A handle to the server thread. + * \param ClientThreadHandle A handle to the client thread. + * \param SecurityQos A pointer to a SECURITY_QUALITY_OF_SERVICE structure that specifies the impersonation level and context tracking mode. + * \return NTSTATUS Successful or errant status. */ NTSYSCALLAPI NTSTATUS @@ -2497,8 +2876,8 @@ NtImpersonateThread( /** * Registers a thread termination port. * - * @param PortHandle A handle to the port to be registered. - * @return NTSTATUS Successful or errant status. + * \param PortHandle A handle to the port to be registered. + * \return NTSTATUS Successful or errant status. */ NTSYSCALLAPI NTSTATUS @@ -2510,13 +2889,13 @@ NtRegisterThreadTerminatePort( /** * Sets LDT (Local Descriptor Table) entries. * - * @param Selector0 The first selector. - * @param Entry0Low The low part of the first entry. - * @param Entry0Hi The high part of the first entry. - * @param Selector1 The second selector. - * @param Entry1Low The low part of the second entry. - * @param Entry1Hi The high part of the second entry. - * @return NTSTATUS Successful or errant status. + * \param Selector0 The first selector. + * \param Entry0Low The low part of the first entry. + * \param Entry0Hi The high part of the first entry. + * \param Selector1 The second selector. + * \param Entry1Low The low part of the second entry. + * \param Entry1Hi The high part of the second entry. + * \return NTSTATUS Successful or errant status. */ NTSYSCALLAPI NTSTATUS @@ -2533,9 +2912,9 @@ NtSetLdtEntries( /** * Dispatches the Asynchronous Procedure Call (APC) from the NtQueueApc* functions to the specified routine. * - * @param ApcRoutine A pointer to the APC routine to be executed. - * @param Parameter Optional. A pointer to a parameter to be passed to the APC routine. - * @param ActxContext Optional. A handle to an activation context. + * \param ApcRoutine A pointer to the APC routine to be executed. + * \param Parameter Optional. A pointer to a parameter to be passed to the APC routine. + * \param ActxContext Optional. A handle to an activation context. */ NTSYSAPI VOID @@ -2549,21 +2928,23 @@ RtlDispatchAPC( /** * A pointer to a function that serves as an APC routine. * - * @param ApcArgument1 Optional. A pointer to the first argument to be passed to the APC routine. - * @param ApcArgument2 Optional. A pointer to the second argument to be passed to the APC routine. - * @param ApcArgument3 Optional. A pointer to the third argument to be passed to the APC routine. + * \param ApcArgument1 Optional. A pointer to the first argument to be passed to the APC routine. + * \param ApcArgument2 Optional. A pointer to the second argument to be passed to the APC routine. + * \param ApcArgument3 Optional. A pointer to the third argument to be passed to the APC routine. */ -typedef VOID (NTAPI* PPS_APC_ROUTINE)( +typedef _Function_class_(PS_APC_ROUTINE) +VOID NTAPI PS_APC_ROUTINE( _In_opt_ PVOID ApcArgument1, _In_opt_ PVOID ApcArgument2, _In_opt_ PVOID ApcArgument3 ); +typedef PS_APC_ROUTINE* PPS_APC_ROUTINE; /** * Encodes an APC routine pointer for use in a WOW64 environment. * - * @param ApcRoutine The APC routine pointer to be encoded. - * @return PVOID The encoded APC routine pointer. + * \param ApcRoutine The APC routine pointer to be encoded. + * \return PVOID The encoded APC routine pointer. */ #define Wow64EncodeApcRoutine(ApcRoutine) \ ((PVOID)((0 - ((LONG_PTR)(ApcRoutine))) << 2)) @@ -2571,8 +2952,8 @@ typedef VOID (NTAPI* PPS_APC_ROUTINE)( /** * Decodes an APC routine pointer that was encoded for use in a WOW64 environment. * - * @param ApcRoutine The encoded APC routine pointer to be decoded. - * @return PVOID The decoded APC routine pointer. + * \param ApcRoutine The encoded APC routine pointer to be decoded. + * \return PVOID The decoded APC routine pointer. */ #define Wow64DecodeApcRoutine(ApcRoutine) \ ((PVOID)(0 - (((LONG_PTR)(ApcRoutine)) >> 2))) @@ -2580,13 +2961,13 @@ typedef VOID (NTAPI* PPS_APC_ROUTINE)( /** * Queues an APC (Asynchronous Procedure Call) to a thread. * - * @param ThreadHandle Handle to the thread to which the APC is to be queued. - * @param ApcRoutine A pointer to the RtlDispatchAPC function or custom APC routine to be executed. - * @param ApcArgument1 Optional first argument to be passed to the APC routine. - * @param ApcArgument2 Optional second argument to be passed to the APC routine. - * @param ApcArgument3 Optional third argument to be passed to the APC routine. - * @return NTSTATUS Successful or errant status. - * @remarks The APC will be executed in the context of the specified thread when the thread enters an alertable wait state or when any + * \param ThreadHandle Handle to the thread to which the APC is to be queued. + * \param ApcRoutine A pointer to the RtlDispatchAPC function or custom APC routine to be executed. + * \param ApcArgument1 Optional first argument to be passed to the APC routine. + * \param ApcArgument2 Optional second argument to be passed to the APC routine. + * \param ApcArgument3 Optional third argument to be passed to the APC routine. + * \return NTSTATUS Successful or errant status. + * \remarks The APC will be executed in the context of the specified thread when the thread enters an alertable wait state or when any * process calls the NtTestAlert, NtAlertThread, NtAlertResumeThread or NtAlertThreadByThreadId functions. */ NTSYSCALLAPI @@ -2605,18 +2986,17 @@ NtQueueApcThread( */ #define QUEUE_USER_APC_SPECIAL_USER_APC ((HANDLE)0x1) -#if (PHNT_VERSION >= PHNT_WINDOWS_7) /** * Queues an APC (Asynchronous Procedure Call) to a thread. * - * @param ThreadHandle Handle to the thread to which the APC is to be queued. - * @param ReserveHandle Optional handle to a reserve object. This can be QUEUE_USER_APC_SPECIAL_USER_APC or a handle returned by NtAllocateReserveObject. - * @param ApcRoutine A pointer to the RtlDispatchAPC function or custom APC routine to be executed. - * @param ApcArgument1 Optional first argument to be passed to the APC routine. - * @param ApcArgument2 Optional second argument to be passed to the APC routine. - * @param ApcArgument3 Optional third argument to be passed to the APC routine. - * @return NTSTATUS Successful or errant status. - * @remarks The APC will be executed in the context of the specified thread after the thread enters an alertable wait state or immediately + * \param ThreadHandle Handle to the thread to which the APC is to be queued. + * \param ReserveHandle Optional handle to a reserve object. This can be QUEUE_USER_APC_SPECIAL_USER_APC or a handle returned by NtAllocateReserveObject. + * \param ApcRoutine A pointer to the RtlDispatchAPC function or custom APC routine to be executed. + * \param ApcArgument1 Optional first argument to be passed to the APC routine. + * \param ApcArgument2 Optional second argument to be passed to the APC routine. + * \param ApcArgument3 Optional third argument to be passed to the APC routine. + * \return NTSTATUS Successful or errant status. + * \remarks The APC will be executed in the context of the specified thread after the thread enters an alertable wait state or immediately * when QUEUE_USER_APC_SPECIAL_USER_APC is used or NtTestAlert, NtAlertThread, NtAlertResumeThread or NtAlertThreadByThreadId are called. */ NTSYSCALLAPI @@ -2630,7 +3010,6 @@ NtQueueApcThreadEx( _In_opt_ PVOID ApcArgument2, _In_opt_ PVOID ApcArgument3 ); -#endif /** * The APC_CALLBACK_DATA_CONTEXT structure is used to pass information to the APC callback routine. @@ -2651,15 +3030,15 @@ typedef struct _APC_CALLBACK_DATA_CONTEXT /** * Queues an Asynchronous Procedure Call (APC) to a specified thread. * - * @param ThreadHandle A handle to the thread to which the APC is to be queued. - * @param ReserveHandle An optional handle to a reserve object. This can be obtained using NtAllocateReserveObject. - * @param ApcFlags Flags that control the behavior of the APC. These flags are defined in QUEUE_USER_APC_FLAGS. - * @param ApcRoutine A pointer to the RtlDispatchAPC function or custom APC routine to be executed. - * @param ApcArgument1 An optional argument to be passed to the APC routine. - * @param ApcArgument2 An optional argument to be passed to the APC routine. - * @param ApcArgument3 An optional argument to be passed to the APC routine. - * @return NTSTATUS Successful or errant status. - * @remarks The APC will be executed in the context of the specified thread when the thread enters an alertable wait state or immediately + * \param ThreadHandle A handle to the thread to which the APC is to be queued. + * \param ReserveHandle An optional handle to a reserve object. This can be obtained using NtAllocateReserveObject. + * \param ApcFlags Flags that control the behavior of the APC. These flags are defined in QUEUE_USER_APC_FLAGS. + * \param ApcRoutine A pointer to the RtlDispatchAPC function or custom APC routine to be executed. + * \param ApcArgument1 An optional argument to be passed to the APC routine. + * \param ApcArgument2 An optional argument to be passed to the APC routine. + * \param ApcArgument3 An optional argument to be passed to the APC routine. + * \return NTSTATUS Successful or errant status. + * \remarks The APC will be executed in the context of the specified thread when the thread enters an alertable wait state or immediately * when QUEUE_USER_APC_SPECIAL_USER_APC is used or any process calls the NtTestAlert, NtAlertThread, * NtAlertResumeThread or NtAlertThreadByThreadId functions. */ @@ -2676,9 +3055,9 @@ NtQueueApcThreadEx2( _In_opt_ PVOID ApcArgument3 ); -#endif +#endif // PHNT_VERSION >= PHNT_WINDOWS_11 -#endif +#endif // PHNT_MODE != PHNT_MODE_KERNEL // // User processes and threads @@ -2689,35 +3068,36 @@ NtQueueApcThreadEx2( // 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 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 #define ProcThreadAttributeSveVectorLength 30 +#define ProcThreadAttributeSmeVectorLength 31 // since 25H2 #ifndef PROC_THREAD_ATTRIBUTE_EXTENDED_FLAGS #define PROC_THREAD_ATTRIBUTE_EXTENDED_FLAGS \ @@ -2832,7 +3212,9 @@ typedef struct _ISOLATION_MANIFEST_PROPERTIES ULONG_PTR Level; } ISOLATION_MANIFEST_PROPERTIES, *PISOLATION_MANIFEST_PROPERTIES; +// // Attributes (Native) +// // private typedef enum _PS_ATTRIBUTE_NUM @@ -2847,17 +3229,17 @@ typedef enum _PS_ATTRIBUTE_NUM PsAttributeMemoryReserve, // in PPS_MEMORY_RESERVE PsAttributePriorityClass, // in UCHAR PsAttributeErrorMode, // in ULONG - PsAttributeStdHandleInfo, // 10, in PPS_STD_HANDLE_INFO + PsAttributeStdHandleInfo, // in PPS_STD_HANDLE_INFO // 10 PsAttributeHandleList, // in HANDLE[] PsAttributeGroupAffinity, // in PGROUP_AFFINITY PsAttributePreferredNode, // in PUSHORT PsAttributeIdealProcessor, // in PPROCESSOR_NUMBER - PsAttributeUmsThread, // ? in PUMS_CREATE_THREAD_ATTRIBUTES + 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 + PsAttributeChildProcessPolicy, // in PULONG (PROCESS_CREATION_CHILD_PROCESS_*) // since THRESHOLD2 // 20 PsAttributeAllApplicationPackagesPolicy, // in PULONG (PROCESS_CREATION_ALL_APPLICATION_PACKAGES_*) // since REDSTONE PsAttributeWin32kFilter, // in PWIN32K_SYSCALL_FILTER PsAttributeSafeOpenPromptOriginClaim, // in SE_SAFE_OPEN_PROMPT_RESULTS @@ -2866,9 +3248,9 @@ typedef enum _PS_ATTRIBUTE_NUM 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 - PsAttributeSupportedMachines, // since 24H2 + PsAttributeComponentFilter, // in COMPONENT_FILTER + PsAttributeEnableOptionalXStateFeatures, // in ULONG64 // since WIN11 // 30 + PsAttributeSupportedMachines, // in ULONG // since 24H2 PsAttributeSveVectorLength, // PPS_PROCESS_CREATION_SVE_VECTOR_LENGTH PsAttributeMax } PS_ATTRIBUTE_NUM; @@ -2966,6 +3348,7 @@ typedef struct _PS_ATTRIBUTE PSIZE_T ReturnLength; } PS_ATTRIBUTE, *PPS_ATTRIBUTE; +_Struct_size_bytes_(TotalLength) typedef struct _PS_ATTRIBUTE_LIST { SIZE_T TotalLength; @@ -3016,19 +3399,16 @@ typedef union _PS_TRUSTLET_ATTRIBUTE_ACCESSRIGHTS UCHAR AccessRights; } PS_TRUSTLET_ATTRIBUTE_ACCESSRIGHTS, *PPS_TRUSTLET_ATTRIBUTE_ACCESSRIGHTS; -typedef struct _PS_TRUSTLET_ATTRIBUTE_TYPE +typedef union _PS_TRUSTLET_ATTRIBUTE_TYPE { - union + ULONG AttributeType; + struct { - struct - { - UCHAR Version; - UCHAR DataCount; - UCHAR SemanticType; - PS_TRUSTLET_ATTRIBUTE_ACCESSRIGHTS AccessRights; - }; - ULONG AttributeType; - }; + UCHAR Version; + UCHAR DataCount; + UCHAR SemanticType; + PS_TRUSTLET_ATTRIBUTE_ACCESSRIGHTS AccessRights; + } DUMMYSTRUCTNAME; } PS_TRUSTLET_ATTRIBUTE_TYPE, *PPS_TRUSTLET_ATTRIBUTE_TYPE; typedef struct _PS_TRUSTLET_ATTRIBUTE_HEADER @@ -3122,6 +3502,7 @@ typedef enum _PS_CREATE_STATE PsCreateMaximumStates } PS_CREATE_STATE; +_Struct_size_bytes_(Size) typedef struct _PS_CREATE_INFO { SIZE_T Size; @@ -3199,22 +3580,21 @@ typedef struct _PS_CREATE_INFO // end_private -#if (PHNT_VERSION >= PHNT_WINDOWS_VISTA) /** * Creates a new process and primary thread. * - * @param ProcessHandle A pointer to a handle that receives the process object handle. - * @param ThreadHandle A pointer to a handle that receives the thread object handle. - * @param ProcessDesiredAccess The access rights desired for the process object. - * @param ThreadDesiredAccess The access rights desired for the thread object. - * @param ProcessObjectAttributes Optional. A pointer to an OBJECT_ATTRIBUTES structure that specifies the attributes of the new process. - * @param ThreadObjectAttributes Optional. A pointer to an OBJECT_ATTRIBUTES structure that specifies the attributes of the new thread. - * @param ProcessFlags Flags that control the creation of the process. These flags are defined as PROCESS_CREATE_FLAGS_*. - * @param ThreadFlags Flags that control the creation of the thread. These flags are defined as THREAD_CREATE_FLAGS_*. - * @param ProcessParameters Optional. A pointer to a RTL_USER_PROCESS_PARAMETERS structure that specifies the parameters for the new process. - * @param CreateInfo A pointer to a PS_CREATE_INFO structure that specifies additional information for the process creation. - * @param AttributeList Optional. A pointer to a list of attributes for the process and thread. - * @return NTSTATUS Successful or errant status. + * \param ProcessHandle A pointer to a handle that receives the process object handle. + * \param ThreadHandle A pointer to a handle that receives the thread object handle. + * \param ProcessDesiredAccess The access rights desired for the process object. + * \param ThreadDesiredAccess The access rights desired for the thread object. + * \param ProcessObjectAttributes Optional. A pointer to an OBJECT_ATTRIBUTES structure that specifies the attributes of the new process. + * \param ThreadObjectAttributes Optional. A pointer to an OBJECT_ATTRIBUTES structure that specifies the attributes of the new thread. + * \param ProcessFlags Flags that control the creation of the process. These flags are defined as PROCESS_CREATE_FLAGS_*. + * \param ThreadFlags Flags that control the creation of the thread. These flags are defined as THREAD_CREATE_FLAGS_*. + * \param ProcessParameters Optional. A pointer to a RTL_USER_PROCESS_PARAMETERS structure that specifies the parameters for the new process. + * \param CreateInfo A pointer to a PS_CREATE_INFO structure that specifies additional information for the process creation. + * \param AttributeList Optional. A pointer to a list of attributes for the process and thread. + * \return NTSTATUS Successful or errant status. */ NTSYSCALLAPI NTSTATUS @@ -3246,28 +3626,30 @@ NtCreateUserProcess( /** * A pointer to a user-defined function that serves as the starting routine for a new thread. * - * @param ThreadParameter A pointer to a variable to be passed to the thread. - * @return NTSTATUS Successful or errant status. + * \param ThreadParameter A pointer to a variable that is passed to the thread. + * \return NTSTATUS Successful or errant status. */ -typedef NTSTATUS (NTAPI *PUSER_THREAD_START_ROUTINE)( +typedef _Function_class_(USER_THREAD_START_ROUTINE) +NTSTATUS NTAPI USER_THREAD_START_ROUTINE( _In_ PVOID ThreadParameter ); +typedef USER_THREAD_START_ROUTINE* PUSER_THREAD_START_ROUTINE; /** * Creates a new thread in the specified process. * - * @param ThreadHandle A pointer to a handle that receives the thread object handle. - * @param DesiredAccess The access rights desired for the thread object. - * @param ObjectAttributes Optional. A pointer to an OBJECT_ATTRIBUTES structure that specifies the attributes of the new thread. - * @param ProcessHandle A handle to the process in which the thread is to be created. - * @param StartRoutine A pointer to the application-defined function to be executed by the thread. - * @param Argument Optional. A pointer to a variable to be passed to the thread. - * @param CreateFlags Flags that control the creation of the thread. These flags are defined as THREAD_CREATE_FLAGS_*. - * @param ZeroBits The number of zero bits in the starting address of the thread's stack. - * @param StackSize The initial size of the thread's stack, in bytes. - * @param MaximumStackSize The maximum size of the thread's stack, in bytes. - * @param AttributeList Optional. A pointer to a list of attributes for the thread. - * @return NTSTATUS Successful or errant status. + * \param ThreadHandle A pointer to a handle that receives the thread object handle. + * \param DesiredAccess The access rights desired for the thread object. + * \param ObjectAttributes Optional. A pointer to an OBJECT_ATTRIBUTES structure that specifies the attributes of the new thread. + * \param ProcessHandle A handle to the process in which the thread is to be created. + * \param StartRoutine A pointer to the application-defined function to be executed by the thread. + * \param Argument Optional. A pointer to a variable that is passed to the thread. + * \param CreateFlags Flags that control the creation of the thread. These flags are defined as THREAD_CREATE_FLAGS_*. + * \param ZeroBits The number of zero bits in the starting address of the thread's stack. + * \param StackSize The initial size of the thread's stack, in bytes. + * \param MaximumStackSize The maximum size of the thread's stack, in bytes. + * \param AttributeList Optional. A pointer to a list of attributes for the thread. + * \return NTSTATUS Successful or errant status. */ NTSYSCALLAPI NTSTATUS @@ -3285,9 +3667,8 @@ NtCreateThreadEx( _In_ SIZE_T MaximumStackSize, _In_opt_ PPS_ATTRIBUTE_LIST AttributeList ); -#endif -#endif +#endif // PHNT_MODE != PHNT_MODE_KERNEL // // Job objects @@ -3297,63 +3678,69 @@ NtCreateThreadEx( // 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 // GUID // NtSetInformationJobObject(_In_ PGUID, 44, _In_ PGUID, sizeof(GUID)); // daxexec -#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 JobObjectServerSiloDiagnosticInformation 50 // SERVERSILO_DIAGNOSTIC_INFORMATION // since 24H2 -#define JobObjectNetworkAccountingInformation 51 // JOBOBJECT_NETWORK_ACCOUNTING_INFORMATION -#define MaxJobObjectInfoClass 52 +#define JOBOBJECTINFOCLASS ULONG +#define JobObjectBasicAccountingInformation 1 // q: JOBOBJECT_BASIC_ACCOUNTING_INFORMATION +#define JobObjectBasicLimitInformation 2 // qs: JOBOBJECT_BASIC_LIMIT_INFORMATION +#define JobObjectBasicProcessIdList 3 // q: JOBOBJECT_BASIC_PROCESS_ID_LIST +#define JobObjectBasicUIRestrictions 4 // qs: JOBOBJECT_BASIC_UI_RESTRICTIONS +#define JobObjectSecurityLimitInformation 5 // qs: JOBOBJECT_SECURITY_LIMIT_INFORMATION +#define JobObjectEndOfJobTimeInformation 6 // qs: 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 // qs: JOBOBJECT_EXTENDED_LIMIT_INFORMATION[V2] +#define JobObjectJobSetInformation 10 // q: JOBOBJECT_JOBSET_INFORMATION +#define JobObjectGroupInformation 11 // q: USHORT +#define JobObjectNotificationLimitInformation 12 // q: JOBOBJECT_NOTIFICATION_LIMIT_INFORMATION +#define JobObjectLimitViolationInformation 13 // q: JOBOBJECT_LIMIT_VIOLATION_INFORMATION +#define JobObjectGroupInformationEx 14 // qs: GROUP_AFFINITY (ARRAY) +#define JobObjectCpuRateControlInformation 15 // qs: JOBOBJECT_CPU_RATE_CONTROL_INFORMATION +#define JobObjectCompletionFilter 16 // qs: ULONG +#define JobObjectCompletionCounter 17 // qs: ULONG +#define JobObjectFreezeInformation 18 // qs: JOBOBJECT_FREEZE_INFORMATION +#define JobObjectExtendedAccountingInformation 19 // qs: JOBOBJECT_EXTENDED_ACCOUNTING_INFORMATION +#define JobObjectWakeInformation 20 // qs: JOBOBJECT_WAKE_INFORMATION +#define JobObjectBackgroundInformation 21 // s: BOOLEAN +#define JobObjectSchedulingRankBiasInformation 22 // s: JOBOBJECT_SCHEDULING_RANK_BIAS_INFORMATION +#define JobObjectTimerVirtualizationInformation 23 // s: JOBOBJECT_TIMER_VIRTUALIZATION_INFORMATION +#define JobObjectCycleTimeNotification 24 // s: JOBOBJECT_CYCLE_TIME_NOTIFICATION +#define JobObjectClearEvent 25 // s: HANDLE +#define JobObjectInterferenceInformation 26 // q: JOBOBJECT_INTERFERENCE_INFORMATION +#define JobObjectClearPeakJobMemoryUsed 27 // s: NULL +#define JobObjectMemoryUsageInformation 28 // q: JOBOBJECT_MEMORY_USAGE_INFORMATION // JOBOBJECT_MEMORY_USAGE_INFORMATION_V2 +#define JobObjectSharedCommit 29 // q: JOBOBJECT_SHARED_COMMIT +#define JobObjectContainerId 30 // q: JOBOBJECT_CONTAINER_IDENTIFIER_V2 +#define JobObjectIoRateControlInformation 31 // qs: JOBOBJECT_IO_RATE_CONTROL_INFORMATION_NATIVE, JOBOBJECT_IO_RATE_CONTROL_INFORMATION_NATIVE_V2, JOBOBJECT_IO_RATE_CONTROL_INFORMATION_NATIVE_V3 +#define JobObjectNetRateControlInformation 32 // qs: JOBOBJECT_NET_RATE_CONTROL_INFORMATION +#define JobObjectNotificationLimitInformation2 33 // qs: JOBOBJECT_NOTIFICATION_LIMIT_INFORMATION_2 +#define JobObjectLimitViolationInformation2 34 // qs: JOBOBJECT_LIMIT_VIOLATION_INFORMATION_2 +#define JobObjectCreateSilo 35 // s: NULL +#define JobObjectSiloBasicInformation 36 // q: SILOOBJECT_BASIC_INFORMATION +#define JobObjectSiloRootDirectory 37 // q: SILOOBJECT_ROOT_DIRECTORY +#define JobObjectServerSiloBasicInformation 38 // q: SERVERSILO_BASIC_INFORMATION +#define JobObjectServerSiloUserSharedData 39 // q: SILO_USER_SHARED_DATA // NtQueryInformationJobObject(NULL, 39, Buffer, sizeof(SILO_USER_SHARED_DATA), 0); +#define JobObjectServerSiloInitialize 40 // qs: SERVERSILO_INIT_INFORMATION +#define JobObjectServerSiloRunningState 41 // s: BOOLEAN +#define JobObjectIoAttribution 42 // q: JOBOBJECT_IO_ATTRIBUTION_INFORMATION +#define JobObjectMemoryPartitionInformation 43 // qs: JOBOBJECT_MEMORY_PARTITION_INFORMATION +#define JobObjectContainerTelemetryId 44 // s: GUID // NtSetInformationJobObject(_In_ PGUID, 44, _In_ PGUID, sizeof(GUID)); // daxexec +#define JobObjectSiloSystemRoot 45 // s: UNICODE_STRING +#define JobObjectEnergyTrackingState 46 // q: JOBOBJECT_ENERGY_TRACKING_STATE +#define JobObjectThreadImpersonationInformation 47 // qs: BOOLEAN +#define JobObjectIoPriorityLimit 48 // qs: JOBOBJECT_IO_PRIORITY_LIMIT +#define JobObjectPagePriorityLimit 49 // qs: JOBOBJECT_PAGE_PRIORITY_LIMIT +#define JobObjectServerSiloDiagnosticInformation 50 // q: SERVERSILO_DIAGNOSTIC_INFORMATION // since 24H2 +#define JobObjectNetworkAccountingInformation 51 // q: JOBOBJECT_NETWORK_ACCOUNTING_INFORMATION +#define JobObjectCpuPartition 52 // qs: JOBOBJECT_CPU_PARTITION_INFORMATION // since 25H2 +#define MaxJobObjectInfoClass 53 // rev // extended limit v2 #define JOB_OBJECT_LIMIT_SILO_READY 0x00400000 -// private +/** + * The JOBOBJECT_EXTENDED_LIMIT_INFORMATION_V2 structure contains basic and extended limit information for a job object. + * + * \sa https://learn.microsoft.com/en-us/windows/win32/api/winnt/ns-winnt-jobobject_extended_limit_information + */ typedef struct _JOBOBJECT_EXTENDED_LIMIT_INFORMATION_V2 { JOBOBJECT_BASIC_LIMIT_INFORMATION BasicLimitInformation; @@ -3365,6 +3752,43 @@ typedef struct _JOBOBJECT_EXTENDED_LIMIT_INFORMATION_V2 SIZE_T JobTotalMemoryLimit; } JOBOBJECT_EXTENDED_LIMIT_INFORMATION_V2, *PJOBOBJECT_EXTENDED_LIMIT_INFORMATION_V2; +// private +typedef struct _JOBOBJECT_SCHEDULING_RANK_BIAS_INFORMATION +{ + ULONG SchedulingRankBias; +} JOBOBJECT_SCHEDULING_RANK_BIAS_INFORMATION, *PJOBOBJECT_SCHEDULING_RANK_BIAS_INFORMATION; + +// private +typedef struct _JOBOBJECT_TIMER_VIRTUALIZATION_INFORMATION +{ + ULONG TimerVirtualizationEnabled; +} JOBOBJECT_TIMER_VIRTUALIZATION_INFORMATION, *PJOBOBJECT_TIMER_VIRTUALIZATION_INFORMATION; + +// private +typedef struct _JOBOBJECT_CYCLE_TIME_NOTIFICATION +{ + HANDLE NotificationChannel; + ULONG64 CycleTime; +} JOBOBJECT_CYCLE_TIME_NOTIFICATION, *PJOBOBJECT_CYCLE_TIME_NOTIFICATION; + +// private +typedef struct _JOBOBJECT_SHARED_COMMIT +{ + ULONG64 SharedCommit; +} JOBOBJECT_SHARED_COMMIT, *PJOBOBJECT_SHARED_COMMIT; + +// private +typedef struct _JOBOBJECT_MEMORY_PARTITION_INFORMATION +{ + ULONG_PTR PartitionId; +} JOBOBJECT_MEMORY_PARTITION_INFORMATION, *PJOBOBJECT_MEMORY_PARTITION_INFORMATION; + +// private +typedef struct _JOBOBJECT_CPU_PARTITION_INFORMATION +{ + ULONG_PTR PartitionId; +} JOBOBJECT_CPU_PARTITION_INFORMATION, *PJOBOBJECT_CPU_PARTITION_INFORMATION; + // private typedef struct _JOBOBJECT_EXTENDED_ACCOUNTING_INFORMATION { @@ -3381,7 +3805,7 @@ typedef struct _JOBOBJECT_EXTENDED_ACCOUNTING_INFORMATION typedef struct _JOBOBJECT_WAKE_INFORMATION { HANDLE NotificationChannel; - ULONG64 WakeCounters[7]; + ULONG64 WakeCounters[PsMaxWakeReasons]; } JOBOBJECT_WAKE_INFORMATION, *PJOBOBJECT_WAKE_INFORMATION; // private @@ -3397,13 +3821,6 @@ 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 { @@ -3498,11 +3915,13 @@ typedef struct _JOBOBJECT_ENERGY_TRACKING_STATE } JOBOBJECT_ENERGY_TRACKING_STATE, *PJOBOBJECT_ENERGY_TRACKING_STATE; // private +_Enum_is_bitflag_ 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; +DEFINE_ENUM_FLAG_OPERATORS(JOBOBJECT_IO_PRIORITY_LIMIT_FLAGS); // private typedef struct _JOBOBJECT_IO_PRIORITY_LIMIT @@ -3512,11 +3931,13 @@ typedef struct _JOBOBJECT_IO_PRIORITY_LIMIT } JOBOBJECT_IO_PRIORITY_LIMIT, *PJOBOBJECT_IO_PRIORITY_LIMIT; // private +_Enum_is_bitflag_ 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; +DEFINE_ENUM_FLAG_OPERATORS(JOBOBJECT_PAGE_PRIORITY_LIMIT_FLAGS); // private typedef struct _JOBOBJECT_PAGE_PRIORITY_LIMIT @@ -3539,15 +3960,15 @@ typedef struct _JOBOBJECT_NETWORK_ACCOUNTING_INFORMATION ULONG64 DataBytesIn; ULONG64 DataBytesOut; } JOBOBJECT_NETWORK_ACCOUNTING_INFORMATION, *PJOBOBJECT_NETWORK_ACCOUNTING_INFORMATION; -#endif +#endif // !defined(NTDDI_WIN11_GE) || (NTDDI_VERSION < NTDDI_WIN11_GE) /** * Creates or opens a job object. * - * @param JobHandle A handle to the job object. - * @param DesiredAccess The access rights desired for the thread object. - * @param ObjectAttributes Optional. A pointer to an OBJECT_ATTRIBUTES structure that specifies the attributes of the new thread. - * @return NTSTATUS Successful or errant status. + * \param JobHandle A handle to the job object. + * \param DesiredAccess The access rights desired for the thread object. + * \param ObjectAttributes Optional. A pointer to an OBJECT_ATTRIBUTES structure that specifies the attributes of the new thread. + * \return NTSTATUS Successful or errant status. */ NTSYSCALLAPI NTSTATUS @@ -3561,10 +3982,10 @@ NtCreateJobObject( /** * Opens an existing job object. * - * @param JobHandle A handle to the job object. - * @param DesiredAccess The access rights desired for the thread object. - * @param ObjectAttributes Optional. A pointer to an OBJECT_ATTRIBUTES structure that specifies the attributes of the new thread. - * @return NTSTATUS Successful or errant status. + * \param JobHandle A handle to the job object. + * \param DesiredAccess The access rights desired for the thread object. + * \param ObjectAttributes Optional. A pointer to an OBJECT_ATTRIBUTES structure that specifies the attributes of the new thread. + * \return NTSTATUS Successful or errant status. */ NTSYSCALLAPI NTSTATUS @@ -3578,9 +3999,9 @@ NtOpenJobObject( /** * Assigns a process to an existing job object. * - * @param JobHandle A handle to the job object to which the process will be associated. The handle must have the JOB_OBJECT_ASSIGN_PROCESS access right. - * @param ProcessHandle A handle to the process to associate with the job object. The handle must have the PROCESS_SET_QUOTA and PROCESS_TERMINATE access rights. - * @return NTSTATUS Successful or errant status. + * \param JobHandle A handle to the job object to which the process will be associated. The handle must have the JOB_OBJECT_ASSIGN_PROCESS access right. + * \param ProcessHandle A handle to the process to associate with the job object. The handle must have the PROCESS_SET_QUOTA and PROCESS_TERMINATE access rights. + * \return NTSTATUS Successful or errant status. */ NTSYSCALLAPI NTSTATUS @@ -3593,9 +4014,9 @@ NtAssignProcessToJobObject( /** * Terminates all processes associated with the job object. If the job is nested, all processes currently associated with the job and all child jobs in the hierarchy are terminated. * - * @param JobHandle A handle to the job whose processes will be terminated. The handle must have the JOB_OBJECT_TERMINATE access right. - * @param ExitStatus The exit status to be used by all processes and threads in the job object. - * @return NTSTATUS Successful or errant status. + * \param JobHandle A handle to the job whose processes will be terminated. The handle must have the JOB_OBJECT_TERMINATE access right. + * \param ExitStatus The exit status to be used by all processes and threads in the job object. + * \return NTSTATUS Successful or errant status. */ NTSYSCALLAPI NTSTATUS @@ -3608,10 +4029,10 @@ NtTerminateJobObject( /** * Checks if a process is associated with a job object. * - * @param ProcessHandle A handle to the process to be checked. - * @param JobHandle An optional handle to the job object. If this parameter is NULL, the function checks if the process is associated with any job object. - * @return NTSTATUS Successful or errant status. - * @remarks This function can be used to determine if a process is running within a job object, which can be useful for managing process resources and constraints. + * \param ProcessHandle A handle to the process to be checked. + * \param JobHandle An optional handle to the job object. If this parameter is NULL, the function checks if the process is associated with any job object. + * \return NTSTATUS Successful or errant status. + * \remarks This function can be used to determine if a process is running within a job object, which can be useful for managing process resources and constraints. */ NTSYSCALLAPI NTSTATUS @@ -3624,13 +4045,13 @@ NtIsProcessInJob( /** * Retrieves information about a job object. * - * @param JobHandle An optional handle to the job object. If this parameter is NULL, the function retrieves information about the job object associated with the calling process. - * @param JobObjectInformationClass The type of job object information to be retrieved. - * @param JobObjectInformation A pointer to a buffer that receives the job object information. - * @param JobObjectInformationLength The size of the buffer pointed to by the JobObjectInformation parameter. - * @param ReturnLength An optional pointer to a variable that receives the size of the data returned. - * @return NTSTATUS Successful or errant status. - * @remarks This function can be used to query various types of information about a job object, such as accounting information, limit information, and process ID list. + * \param JobHandle An optional handle to the job object. If this parameter is NULL, the function retrieves information about the job object associated with the calling process. + * \param JobObjectInformationClass The type of job object information to be retrieved. + * \param JobObjectInformation A pointer to a buffer that receives the job object information. + * \param JobObjectInformationLength The size of the buffer pointed to by the JobObjectInformation parameter. + * \param ReturnLength An optional pointer to a variable that receives the size of the data returned. + * \return NTSTATUS Successful or errant status. + * \remarks This function can be used to query various types of information about a job object, such as accounting information, limit information, and process ID list. */ NTSYSCALLAPI NTSTATUS @@ -3646,12 +4067,12 @@ NtQueryInformationJobObject( /** * Sets information for a job object. * - * @param JobHandle A handle to the job object. - * @param JobObjectInformationClass The type of job object information to be set. - * @param JobObjectInformation A pointer to a buffer that contains the job object information. - * @param JobObjectInformationLength The size of the buffer pointed to by the JobObjectInformation parameter. - * @return NTSTATUS Successful or errant status. - * @remarks This function can be used to set various types of information for a job object, such as limit information, UI restrictions, and security limit information. + * \param JobHandle A handle to the job object. + * \param JobObjectInformationClass The type of job object information to be set. + * \param JobObjectInformation A pointer to a buffer that contains the job object information. + * \param JobObjectInformationLength The size of the buffer pointed to by the JobObjectInformation parameter. + * \return NTSTATUS Successful or errant status. + * \remarks This function can be used to set various types of information for a job object, such as limit information, UI restrictions, and security limit information. */ NTSYSCALLAPI NTSTATUS @@ -3666,11 +4087,11 @@ NtSetInformationJobObject( /** * Creates a set of job objects. * - * @param NumJob The number of job objects in the set. - * @param UserJobSet A pointer to an array of JOB_SET_ARRAY structures that specify the job objects in the set. - * @param Flags Reserved for future use. Must be zero. - * @return NTSTATUS Successful or errant status. - * @remarks This function can be used to create a set of job objects, which can be useful for managing groups of related processes. + * \param NumJob The number of job objects in the set. + * \param UserJobSet A pointer to an array of JOB_SET_ARRAY structures that specify the job objects in the set. + * \param Flags Reserved for future use. Must be zero. + * \return NTSTATUS Successful or errant status. + * \remarks This function can be used to create a set of job objects, which can be useful for managing groups of related processes. */ NTSYSCALLAPI NTSTATUS @@ -3688,9 +4109,9 @@ NTAPI NtRevertContainerImpersonation( VOID ); -#endif +#endif // (PHNT_VERSION >= PHNT_WINDOWS_10) -#endif +#endif // (PHNT_MODE != PHNT_MODE_KERNEL) // // Reserve objects @@ -3706,14 +4127,13 @@ typedef enum _MEMORY_RESERVE_TYPE MemoryReserveTypeMax } MEMORY_RESERVE_TYPE; -#if (PHNT_VERSION >= PHNT_WINDOWS_7) /** * Allocates a memory reserve object. * - * @param MemoryReserveHandle Pointer to a variable that receives the memory reserve object handle. - * @param ObjectAttributes Pointer to an object attributes structure. - * @param Type The type of memory reserve. - * @return NTSTATUS Successful or errant status. + * \param MemoryReserveHandle Pointer to a variable that receives the memory reserve object handle. + * \param ObjectAttributes Pointer to an object attributes structure. + * \param Type The type of memory reserve. + * \return NTSTATUS Successful or errant status. */ NTSYSCALLAPI NTSTATUS @@ -3723,13 +4143,13 @@ NtAllocateReserveObject( _In_ PCOBJECT_ATTRIBUTES ObjectAttributes, _In_ MEMORY_RESERVE_TYPE Type ); -#endif // // Process snapshotting // // Capture/creation flags. +_Enum_is_bitflag_ typedef enum _PSSNT_CAPTURE_FLAGS { PSSNT_CAPTURE_NONE = 0x00000000, @@ -3758,6 +4178,7 @@ typedef enum _PSSNT_CAPTURE_FLAGS } PSSNT_CAPTURE_FLAGS; DEFINE_ENUM_FLAG_OPERATORS(PSSNT_CAPTURE_FLAGS); +_Enum_is_bitflag_ typedef enum _PSSNT_DUPLICATE_FLAGS { PSSNT_DUPLICATE_NONE = 0x00, @@ -3782,13 +4203,13 @@ typedef enum _PSSNT_QUERY_INFORMATION_CLASS #if (PHNT_VERSION >= PHNT_WINDOWS_8_1) // rev /** - * Captures a snapshot of the specified process. + * The PssNtCaptureSnapshot routine captures a snapshot of the specified process. * - * @param SnapshotHandle Pointer to a variable that receives the snapshot handle. - * @param ProcessHandle Handle to the process. - * @param CaptureFlags Flags indicating what to capture. - * @param ThreadContextFlags Optional flags for capturing thread context. - * @return NTSTATUS Successful or errant status. + * \param SnapshotHandle Pointer to a variable that receives the snapshot handle. + * \param ProcessHandle Handle to the process. + * \param CaptureFlags Flags indicating what to capture. + * \param ThreadContextFlags Optional flags for capturing thread context. + * \return NTSTATUS Successful or errant status. */ NTSYSAPI NTSTATUS @@ -3802,14 +4223,14 @@ PssNtCaptureSnapshot( // rev /** - * Duplicates a process snapshot from one process to another. + * The PssNtDuplicateSnapshot routine duplicates a process snapshot from one process to another. * - * @param SourceProcessHandle Handle to the source process. - * @param SnapshotHandle Handle to the snapshot to duplicate. - * @param TargetProcessHandle Handle to the target process. - * @param TargetSnapshotHandle Pointer to a variable that receives the duplicated snapshot handle. - * @param Flags Optional flags for duplication. - * @return NTSTATUS Successful or errant status. + * \param SourceProcessHandle Handle to the source process. + * \param SnapshotHandle Handle to the snapshot to duplicate. + * \param TargetProcessHandle Handle to the target process. + * \param TargetSnapshotHandle Pointer to a variable that receives the duplicated snapshot handle. + * \param Flags Optional flags for duplication. + * \return NTSTATUS Successful or errant status. */ NTSYSAPI NTSTATUS @@ -3824,11 +4245,10 @@ PssNtDuplicateSnapshot( // rev /** - * Frees a remote process snapshot. + * The PssNtFreeSnapshot routine frees a snapshot. * - * @param ProcessHandle A handle to the process that contains the snapshot. The handle must have PROCESS_VM_READ, PROCESS_VM_OPERATION, and PROCESS_DUP_HANDLE rights. - * @param SnapshotHandle Handle to the snapshot to free. - * @return NTSTATUS Successful or errant status. + * \param SnapshotHandle Handle to the snapshot to free. + * \return NTSTATUS Successful or errant status. */ NTSYSAPI NTSTATUS @@ -3839,10 +4259,11 @@ PssNtFreeSnapshot( // rev /** - * Frees a snapshot. + * The PssNtFreeRemoteSnapshot routine frees a remote process snapshot. * - * @param SnapshotHandle Handle to the snapshot to free. - * @return NTSTATUS Successful or errant status. + * \param ProcessHandle A handle to the process that contains the snapshot. The handle must have PROCESS_VM_READ, PROCESS_VM_OPERATION, and PROCESS_DUP_HANDLE rights. + * \param SnapshotHandle Handle to the snapshot to free. + * \return NTSTATUS Successful or errant status. */ NTSYSAPI NTSTATUS @@ -3854,13 +4275,13 @@ PssNtFreeRemoteSnapshot( // rev /** - * Queries information from a the specified snapshot. + * The PssNtQuerySnapshot routine queries information from the specified snapshot. * - * @param SnapshotHandle Handle to the snapshot. - * @param InformationClass The information class to query. - * @param Buffer Pointer to a buffer that receives the queried information. - * @param BufferLength Length of the buffer. - * @return NTSTATUS Successful or errant status. + * \param SnapshotHandle Handle to the snapshot. + * \param InformationClass The information class to query. + * \param Buffer Pointer to a buffer that receives the queried information. + * \param BufferLength Length of the buffer. + * \return NTSTATUS Successful or errant status. */ NTSYSAPI NTSTATUS @@ -3871,7 +4292,44 @@ PssNtQuerySnapshot( _Out_writes_bytes_(BufferLength) PVOID Buffer, _In_ ULONG BufferLength ); -#endif + +// rev +typedef struct _PSSNT_WALK_MARKER_INFO +{ + ULONG Signature; // Win32: 0x4D575350 // 'PSSM' + HANDLE SectionHandle; +} PSSNT_WALK_MARKER_INFO, *PPSSNT_WALK_MARKER_INFO; + +// rev +NTSYSAPI +NTSTATUS +NTAPI +PssNtWalkSnapshot( + _In_ HANDLE SnapshotHandle, + _In_ ULONG InformationClass, + _In_ HANDLE WalkMarkerHandle, + _Out_writes_bytes_(BufferLength) PVOID Buffer, + _In_ ULONG BufferLength + ); + +// rev +NTSYSAPI +NTSTATUS +NTAPI +PssNtFreeWalkMarker( + _Inout_ PHANDLE WalkMarkerHandle + ); + +// rev +NTSYSAPI +NTSTATUS +NTAPI +PssNtValidateDescriptor( + _In_ HANDLE SnapshotHandle, + _In_opt_ PVOID ExceptionAddress + ); + +#endif // (PHNT_VERSION >= PHNT_WINDOWS_8_1) // rev /** @@ -3895,12 +4353,12 @@ typedef struct _NTPSS_MEMORY_BULK_INFORMATION /** * Captures virtual address space bulk information for a process. * - * @param ProcessHandle Handle to the process. - * @param BaseAddress Optional base address to start the capture. - * @param BulkInformation Pointer to the memory bulk information structure. - * @param BulkInformationLength Length of the memory bulk information structure. - * @param ReturnLength Optional pointer to a variable that receives the length of the captured information. - * @return NTSTATUS Successful or errant status. + * \param ProcessHandle Handle to the process. + * \param BaseAddress Optional base address to start the capture. + * \param BulkInformation Pointer to the memory bulk information structure. + * \param BulkInformationLength Length of the memory bulk information structure. + * \param ReturnLength Optional pointer to a variable that receives the length of the captured information. + * \return NTSTATUS Successful or errant status. */ NTSYSCALLAPI NTSTATUS @@ -3912,8 +4370,8 @@ NtPssCaptureVaSpaceBulk( _In_ SIZE_T BulkInformationLength, _Out_opt_ PSIZE_T ReturnLength ); -#endif +#endif // (PHNT_VERSION >= PHNT_WINDOWS_10_20H1) -#endif +#endif // (PHNT_MODE != PHNT_MODE_KERNEL) -#endif +#endif // _NTPSAPI_H diff --git a/ntregapi.h b/ntregapi.h index 261f841..6d73090 100644 --- a/ntregapi.h +++ b/ntregapi.h @@ -7,16 +7,17 @@ #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 +// +// Registry +// #define REG_MAX_KEY_VALUE_NAME_LENGTH 32767 #define REG_MAX_KEY_NAME_LENGTH 512 +/** + * The KEY_INFORMATION_CLASS structure represents the type of information to supply about a registry key. + * \sa https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/wdm/ne-wdm-_key_information_class + */ typedef enum _KEY_INFORMATION_CLASS { KeyBasicInformation, // KEY_BASIC_INFORMATION @@ -32,26 +33,38 @@ typedef enum _KEY_INFORMATION_CLASS MaxKeyInfoClass } KEY_INFORMATION_CLASS; +/** + * The KEY_BASIC_INFORMATION structure defines a subset of the full information that is available for a registry key. + * \sa https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/wdm/ns-wdm-_key_basic_information + */ typedef struct _KEY_BASIC_INFORMATION { - LARGE_INTEGER LastWriteTime; - ULONG TitleIndex; - ULONG NameLength; - _Field_size_bytes_(NameLength) WCHAR Name[1]; + LARGE_INTEGER LastWriteTime; // Number of 100-nanosecond intervals since this key or any of its values changed. + ULONG TitleIndex; // Reserved // A legacy field originally intended for use with localization such as an index of a resource table. + ULONG NameLength; // The size, in bytes, of the key name string in the Name array. + _Field_size_bytes_(NameLength) WCHAR Name[1]; // The name of the registry key. This string is not null-terminated. } KEY_BASIC_INFORMATION, *PKEY_BASIC_INFORMATION; +/** + * The KEY_NODE_INFORMATION structure defines the basic information available for a registry (sub)key. + * \sa https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/wdm/ns-wdm-_key_node_information + */ typedef struct _KEY_NODE_INFORMATION { - LARGE_INTEGER LastWriteTime; - ULONG TitleIndex; - ULONG ClassOffset; - ULONG ClassLength; - ULONG NameLength; - _Field_size_bytes_(NameLength) WCHAR Name[1]; + LARGE_INTEGER LastWriteTime; // Number of 100-nanosecond intervals since this key or any of its values changed. + ULONG TitleIndex; // Reserved // A legacy field originally intended for use with localization such as an index of a resource table. + ULONG ClassOffset; // The byte offset from the start of this structure to the class name string. This string is not null-terminated. + ULONG ClassLength; // The size, in bytes, in the class name string. + ULONG NameLength; // The size, in bytes, of the key name string contained in the Name array. + _Field_size_bytes_(NameLength) WCHAR Name[1]; // The name of the registry key. This string is not null-terminated. // ... // WCHAR Class[1]; } KEY_NODE_INFORMATION, *PKEY_NODE_INFORMATION; +/** + * The KEY_FULL_INFORMATION structure defines information available for a registry key, including subkeys, names and value entries. + * \sa https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/wdm/ns-wdm-_key_full_information + */ typedef struct _KEY_FULL_INFORMATION { LARGE_INTEGER LastWriteTime; @@ -67,12 +80,20 @@ typedef struct _KEY_FULL_INFORMATION WCHAR Class[1]; } KEY_FULL_INFORMATION, *PKEY_FULL_INFORMATION; +/** + * The KEY_NAME_INFORMATION structure holds the name and name length of the key. + * \sa https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/ntddk/ns-ntddk-_key_name_information + */ typedef struct _KEY_NAME_INFORMATION { - ULONG NameLength; - _Field_size_bytes_(NameLength) WCHAR Name[1]; + ULONG NameLength; // The size, in bytes, of the key name string in the Name array. + _Field_size_bytes_(NameLength) WCHAR Name[1]; // The name of the registry key. This string is not null-terminated. } KEY_NAME_INFORMATION, *PKEY_NAME_INFORMATION; +/** + * The KEY_CACHED_INFORMATION structure holds the cached information available for a registry key or subkey. + * \sa https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/ntddk/ns-ntddk-_key_cached_information + */ typedef struct _KEY_CACHED_INFORMATION { LARGE_INTEGER LastWriteTime; @@ -86,16 +107,69 @@ typedef struct _KEY_CACHED_INFORMATION _Field_size_bytes_(NameLength) WCHAR Name[1]; } KEY_CACHED_INFORMATION, *PKEY_CACHED_INFORMATION; +// +// REG_FLAG_* +// + // rev +/** + * \def REG_FLAG_VOLATILE + * \brief The registry key is volatile. + * + * When this flag is set, the key is not preserved when the system is rebooted. + * Volatile keys exist only in memory and are lost when the system shuts down. + */ #define REG_FLAG_VOLATILE 0x0001 +// rev +/** + * \def REG_FLAG_LINK + * \brief The registry key is a symbolic link. + * + * When this flag is set, the key acts as a symbolic link to another registry key. + * This allows redirection of registry operations to a different key location. + */ #define REG_FLAG_LINK 0x0002 +// +// REG_KEY_* +// + +// rev +#define REG_KEY_RESERVED_FLAG 0x0001 // msdn +/** + * \def REG_KEY_DONT_VIRTUALIZE + * \brief The REG_KEY_DONT_VIRTUALIZE flag disables write registry virtualization. + * + * If this flag is set and a create key or set value operation fails because the caller + * does not have sufficient access right to the parent key, the registry fails the operation. + * If this flag is clear, the registry attempts to write the key or value in the virtual store. + * The caller must have the KEY_READ right on the parent key. + */ #define REG_KEY_DONT_VIRTUALIZE 0x0002 +/** + * \def REG_KEY_DONT_SILENT_FAIL + * \brief The REG_KEY_DONT_SILENT_FAIL flag disables open registry virtualization. + * + * If this flag is set and an open operation fails on a key that has virtualization enabled, + * the registry does not attempt to reopen the key. If this flag is clear, the registry attempts + * to reopen the key with MAXIMUM_ALLOWED access instead of the requested access. + */ #define REG_KEY_DONT_SILENT_FAIL 0x0004 +/** + * \def REG_KEY_RECURSE_FLAG + * \brief If REG_KEY_RECURSE_FLAG is set, registry virtualization flags are propagated from the parent key. + * + * If this flag is clear, registry virtualization flags are not propagated. + * Changing this flag affects only new descendent keys created after the flag is changed. + * It does not set or clear these flags for existing descendent keys. + */ #define REG_KEY_RECURSE_FLAG 0x0008 // private +/** + * The KEY_FLAGS_INFORMATION structure contains various flags about a registry key or subkey. + */ typedef struct _KEY_FLAGS_INFORMATION { ULONG Wow64Flags; @@ -167,6 +241,10 @@ typedef struct _KEY_LAYER_INFORMATION ULONG Reserved : 28; } KEY_LAYER_INFORMATION, *PKEY_LAYER_INFORMATION; +/** + * The KEY_SET_INFORMATION_CLASS enumeration type represents the type of information to set for a registry key. + * \sa https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/wdm/ne-wdm-_key_set_information_class + */ typedef enum _KEY_SET_INFORMATION_CLASS { KeyWriteTimeInformation, // KEY_WRITE_TIME_INFORMATION @@ -180,14 +258,12 @@ typedef enum _KEY_SET_INFORMATION_CLASS } KEY_SET_INFORMATION_CLASS; /** - * Structure representing the last write time of a registry key. - * - * The values include: - * - LastWriteTime: Contains the timestamp of the last write operation performed on a registry key. + * The KEY_WRITE_TIME_INFORMATION structure is used by the system to set the last write time for a registry key. + * \sa https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/wdm/ns-wdm-_key_write_time_information */ typedef struct _KEY_WRITE_TIME_INFORMATION { - LARGE_INTEGER LastWriteTime; + LARGE_INTEGER LastWriteTime; // Number of 100-nanosecond intervals since this key or any of its values changed. } KEY_WRITE_TIME_INFORMATION, *PKEY_WRITE_TIME_INFORMATION; /** @@ -261,17 +337,25 @@ typedef struct _KEY_SET_VIRTUALIZATION_INFORMATION ULONG Reserved : 29; } KEY_SET_VIRTUALIZATION_INFORMATION, *PKEY_SET_VIRTUALIZATION_INFORMATION; +/** + * The KEY_VALUE_INFORMATION_CLASS enumeration type specifies the type of information to supply about the value of a registry key. + * \sa https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/wdm/ne-wdm-_key_value_information_class + */ typedef enum _KEY_VALUE_INFORMATION_CLASS { KeyValueBasicInformation, // KEY_VALUE_BASIC_INFORMATION KeyValueFullInformation, // KEY_VALUE_FULL_INFORMATION KeyValuePartialInformation, // KEY_VALUE_PARTIAL_INFORMATION - KeyValueFullInformationAlign64, + KeyValueFullInformationAlign64, // KEY_VALUE_FULL_INFORMATION_ALIGN64 KeyValuePartialInformationAlign64, // KEY_VALUE_PARTIAL_INFORMATION_ALIGN64 KeyValueLayerInformation, // KEY_VALUE_LAYER_INFORMATION MaxKeyValueInfoClass } KEY_VALUE_INFORMATION_CLASS; +/** + * The KEY_VALUE_BASIC_INFORMATION structure defines a subset of the full information available for a value entry of a registry key. + * \sa https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/wdm/ns-wdm-_key_value_basic_information + */ typedef struct _KEY_VALUE_BASIC_INFORMATION { ULONG TitleIndex; @@ -280,6 +364,10 @@ typedef struct _KEY_VALUE_BASIC_INFORMATION _Field_size_bytes_(NameLength) WCHAR Name[1]; } KEY_VALUE_BASIC_INFORMATION, *PKEY_VALUE_BASIC_INFORMATION; +/** + * The KEY_VALUE_FULL_INFORMATION structure defines information available for a value entry of a registry key. + * \sa https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/wdm/ns-wdm-_key_value_full_information + */ typedef struct _KEY_VALUE_FULL_INFORMATION { ULONG TitleIndex; @@ -292,6 +380,25 @@ typedef struct _KEY_VALUE_FULL_INFORMATION // UCHAR Data[1]; } KEY_VALUE_FULL_INFORMATION, *PKEY_VALUE_FULL_INFORMATION; +/** + * The KEY_VALUE_FULL_INFORMATION_ALIGN64 structure defines information available for a value entry of a registry key. + */ +typedef DECLSPEC_ALIGN(8) struct _KEY_VALUE_FULL_INFORMATION_ALIGN64 +{ + ULONG TitleIndex; + ULONG Type; + ULONG DataOffset; + ULONG DataLength; + ULONG NameLength; + _Field_size_bytes_(NameLength) WCHAR Name[1]; + // ... + // UCHAR Data[1]; +} KEY_VALUE_FULL_INFORMATION_ALIGN64, *PKEY_VALUE_FULL_INFORMATION_ALIGN64; + +/** + * The KEY_VALUE_PARTIAL_INFORMATION structure defines a subset of the value information available for a value entry of a registry key. + * \sa https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/wdm/ns-wdm-_key_value_partial_information + */ typedef struct _KEY_VALUE_PARTIAL_INFORMATION { ULONG TitleIndex; @@ -300,7 +407,10 @@ typedef struct _KEY_VALUE_PARTIAL_INFORMATION _Field_size_bytes_(DataLength) UCHAR Data[1]; } KEY_VALUE_PARTIAL_INFORMATION, *PKEY_VALUE_PARTIAL_INFORMATION; -typedef struct _KEY_VALUE_PARTIAL_INFORMATION_ALIGN64 +/** + * The KEY_VALUE_PARTIAL_INFORMATION_ALIGN64 structure defines a subset of the value information available for a value entry of a registry key. + */ +typedef DECLSPEC_ALIGN(8) struct _KEY_VALUE_PARTIAL_INFORMATION_ALIGN64 { ULONG Type; ULONG DataLength; @@ -308,6 +418,9 @@ typedef struct _KEY_VALUE_PARTIAL_INFORMATION_ALIGN64 } KEY_VALUE_PARTIAL_INFORMATION_ALIGN64, *PKEY_VALUE_PARTIAL_INFORMATION_ALIGN64; // private +/** + * The KEY_VALUE_LAYER_INFORMATION structure defines the flags for a value entry of a registry key. + */ typedef struct _KEY_VALUE_LAYER_INFORMATION { ULONG IsTombstone : 1; @@ -361,6 +474,7 @@ typedef enum _REG_ACTION KeyModified } REG_ACTION; +_Struct_size_bytes_(NextEntryOffset) typedef struct _REG_NOTIFY_INFORMATION { ULONG NextEntryOffset; @@ -369,18 +483,6 @@ typedef struct _REG_NOTIFY_INFORMATION _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; - // // Virtualization // since REDSTONE // @@ -587,14 +689,14 @@ typedef struct _VR_UNLOAD_DIFFERENCING_HIVE_FOR_HOST /** * Creates a new registry key routine or opens an existing one. * - * @param[out] KeyHandle A pointer to a handle that receives the key handle. - * @param[in] DesiredAccess The access mask that specifies the desired access rights. - * @param[in] ObjectAttributes A pointer to an OBJECT_ATTRIBUTES structure that specifies the object attributes. - * @param[in] TitleIndex Reserved. - * @param[in, optional] Class A pointer to a UNICODE_STRING structure that specifies the class of the key. - * @param[in] CreateOptions The options to use when creating the key. - * @param[out, optional] Disposition A pointer to a variable that receives the disposition value. - * @return NTSTATUS Successful or errant status. + * \param[out] KeyHandle A pointer to a handle that receives the key handle. + * \param[in] DesiredAccess The access mask that specifies the desired access rights. + * \param[in] ObjectAttributes A pointer to an OBJECT_ATTRIBUTES structure that specifies the object attributes. + * \param[in] TitleIndex Reserved. + * \param[in, optional] Class A pointer to a UNICODE_STRING structure that specifies the class of the key. + * \param[in] CreateOptions The options to use when creating the key. + * \param[out, optional] Disposition A pointer to a variable that receives the disposition value. + * \return NTSTATUS Successful or errant status. */ NTSYSCALLAPI NTSTATUS @@ -604,24 +706,23 @@ NtCreateKey( _In_ ACCESS_MASK DesiredAccess, _In_ POBJECT_ATTRIBUTES ObjectAttributes, _Reserved_ ULONG TitleIndex, - _In_opt_ PUNICODE_STRING Class, + _In_opt_ PCUNICODE_STRING Class, _In_ ULONG CreateOptions, _Out_opt_ PULONG Disposition ); -#if (PHNT_VERSION >= PHNT_WINDOWS_VISTA) /** * Creates a new registry key or opens an existing one, and it associates the key with a transaction. * - * @param[out] KeyHandle A pointer to a handle that receives the key handle. - * @param[in] DesiredAccess The access mask that specifies the desired access rights. - * @param[in] ObjectAttributes A pointer to an OBJECT_ATTRIBUTES structure that specifies the object attributes. - * @param[in] TitleIndex Reserved. - * @param[in, optional] Class A pointer to a UNICODE_STRING structure that specifies the class of the key. - * @param[in] CreateOptions The options to use when creating the key. - * @param[in] TransactionHandle A handle to the transaction. - * @param[out, optional] Disposition A pointer to a variable that receives the disposition value. - * @return NTSTATUS Successful or errant status. + * \param[out] KeyHandle A pointer to a handle that receives the key handle. + * \param[in] DesiredAccess The access mask that specifies the desired access rights. + * \param[in] ObjectAttributes A pointer to an OBJECT_ATTRIBUTES structure that specifies the object attributes. + * \param[in] TitleIndex Reserved. + * \param[in, optional] Class A pointer to a UNICODE_STRING structure that specifies the class of the key. + * \param[in] CreateOptions The options to use when creating the key. + * \param[in] TransactionHandle A handle to the transaction. + * \param[out, optional] Disposition A pointer to a variable that receives the disposition value. + * \return NTSTATUS Successful or errant status. */ NTSYSCALLAPI NTSTATUS @@ -631,21 +732,20 @@ NtCreateKeyTransacted( _In_ ACCESS_MASK DesiredAccess, _In_ POBJECT_ATTRIBUTES ObjectAttributes, _Reserved_ ULONG TitleIndex, - _In_opt_ PUNICODE_STRING Class, + _In_opt_ PCUNICODE_STRING Class, _In_ ULONG CreateOptions, _In_ HANDLE TransactionHandle, _Out_opt_ PULONG Disposition ); -#endif /** * Opens an existing registry key. * - * @param[out] KeyHandle A pointer to a handle that receives the key handle. - * @param[in] DesiredAccess The access mask that specifies the desired access rights. - * @param[in] ObjectAttributes A pointer to an OBJECT_ATTRIBUTES structure that specifies the object attributes. - * @return NTSTATUS Successful or errant status. - * @remarks NtOpenKey ignores the security information in the ObjectAttributes structure. + * \param[out] KeyHandle A pointer to a handle that receives the key handle. + * \param[in] DesiredAccess The access mask that specifies the desired access rights. + * \param[in] ObjectAttributes A pointer to an OBJECT_ATTRIBUTES structure that specifies the object attributes. + * \return NTSTATUS Successful or errant status. + * \remarks NtOpenKey ignores the security information in the ObjectAttributes structure. */ NTSYSCALLAPI NTSTATUS @@ -656,15 +756,14 @@ NtOpenKey( _In_ POBJECT_ATTRIBUTES ObjectAttributes ); -#if (PHNT_VERSION >= PHNT_WINDOWS_VISTA) /** * Opens an existing registry key and associates the key with a transaction. * - * @param[out] KeyHandle A pointer to a handle that receives the key handle. - * @param[in] DesiredAccess The access mask that specifies the desired access rights. - * @param[in] ObjectAttributes A pointer to an OBJECT_ATTRIBUTES structure that specifies the object attributes. - * @param[in] TransactionHandle A handle to the transaction. - * @return NTSTATUS Successful or errant status. + * \param[out] KeyHandle A pointer to a handle that receives the key handle. + * \param[in] DesiredAccess The access mask that specifies the desired access rights. + * \param[in] ObjectAttributes A pointer to an OBJECT_ATTRIBUTES structure that specifies the object attributes. + * \param[in] TransactionHandle A handle to the transaction. + * \return NTSTATUS Successful or errant status. */ NTSYSCALLAPI NTSTATUS @@ -675,17 +774,15 @@ NtOpenKeyTransacted( _In_ POBJECT_ATTRIBUTES ObjectAttributes, _In_ HANDLE TransactionHandle ); -#endif -#if (PHNT_VERSION >= PHNT_WINDOWS_7) /** * Opens an existing registry key with extended options. * - * @param[out] KeyHandle A pointer to a handle that receives the key handle. - * @param[in] DesiredAccess The access mask that specifies the desired access rights. - * @param[in] ObjectAttributes A pointer to an OBJECT_ATTRIBUTES structure that specifies the object attributes. - * @param[in] OpenOptions The options to use when opening the key. - * @return NTSTATUS Successful or errant status. + * \param[out] KeyHandle A pointer to a handle that receives the key handle. + * \param[in] DesiredAccess The access mask that specifies the desired access rights. + * \param[in] ObjectAttributes A pointer to an OBJECT_ATTRIBUTES structure that specifies the object attributes. + * \param[in] OpenOptions The options to use when opening the key. + * \return NTSTATUS Successful or errant status. */ NTSYSCALLAPI NTSTATUS @@ -700,12 +797,12 @@ NtOpenKeyEx( /** * Opens an existing registry key in a transaction with extended options. * - * @param[out] KeyHandle A pointer to a handle that receives the key handle. - * @param[in] DesiredAccess The access mask that specifies the desired access rights. - * @param[in] ObjectAttributes A pointer to an OBJECT_ATTRIBUTES structure that specifies the object attributes. - * @param[in] OpenOptions The options to use when opening the key. - * @param[in] TransactionHandle A handle to the transaction. - * @return NTSTATUS Successful or errant status. + * \param[out] KeyHandle A pointer to a handle that receives the key handle. + * \param[in] DesiredAccess The access mask that specifies the desired access rights. + * \param[in] ObjectAttributes A pointer to an OBJECT_ATTRIBUTES structure that specifies the object attributes. + * \param[in] OpenOptions The options to use when opening the key. + * \param[in] TransactionHandle A handle to the transaction. + * \return NTSTATUS Successful or errant status. */ NTSYSCALLAPI NTSTATUS @@ -717,13 +814,12 @@ NtOpenKeyTransactedEx( _In_ ULONG OpenOptions, _In_ HANDLE TransactionHandle ); -#endif /** * Deletes a registry key. * - * @param[in] KeyHandle A handle to the key to be deleted. - * @return NTSTATUS Successful or errant status. + * \param[in] KeyHandle A handle to the key to be deleted. + * \return NTSTATUS Successful or errant status. */ NTSYSCALLAPI NTSTATUS @@ -735,42 +831,42 @@ NtDeleteKey( /** * Renames a registry key. * - * @param[in] KeyHandle A handle to the key to be renamed. - * @param[in] NewName A pointer to a UNICODE_STRING structure that specifies the new name of the key. - * @return NTSTATUS Successful or errant status. + * \param[in] KeyHandle A handle to the key to be renamed. + * \param[in] NewName A pointer to a UNICODE_STRING structure that specifies the new name of the key. + * \return NTSTATUS Successful or errant status. */ NTSYSCALLAPI NTSTATUS NTAPI NtRenameKey( _In_ HANDLE KeyHandle, - _In_ PUNICODE_STRING NewName + _In_ PCUNICODE_STRING NewName ); /** * Deletes a value from a registry key. * - * @param[in] KeyHandle A handle to the key that contains the value to be deleted. - * @param[in] ValueName A pointer to a UNICODE_STRING structure that specifies the name of the value to be deleted. - * @return NTSTATUS Successful or errant status. + * \param[in] KeyHandle A handle to the key that contains the value to be deleted. + * \param[in] ValueName A pointer to a UNICODE_STRING structure that specifies the name of the value to be deleted. + * \return NTSTATUS Successful or errant status. */ NTSYSCALLAPI NTSTATUS NTAPI NtDeleteValueKey( _In_ HANDLE KeyHandle, - _In_ PUNICODE_STRING ValueName + _In_ PCUNICODE_STRING ValueName ); /** * Queries information about a registry key. * - * @param[in] KeyHandle A handle to the key to be queried. - * @param[in] KeyInformationClass The type of information to be queried. - * @param[out] KeyInformation A pointer to a buffer that receives the key information. - * @param[in] Length The size of the buffer. - * @param[out] ResultLength A pointer to a variable that receives the size of the data returned. - * @return NTSTATUS Successful or errant status. + * \param[in] KeyHandle A handle to the key to be queried. + * \param[in] KeyInformationClass The type of information to be queried. + * \param[out] KeyInformation A pointer to a buffer that receives the key information. + * \param[in] Length The size of the buffer. + * \param[out] ResultLength A pointer to a variable that receives the size of the data returned. + * \return NTSTATUS Successful or errant status. */ NTSYSCALLAPI NTSTATUS @@ -786,11 +882,11 @@ NtQueryKey( /** * Sets information for a registry key. * - * @param[in] KeyHandle A handle to the key to be modified. - * @param[in] KeySetInformationClass The type of information to be set. - * @param[in] KeySetInformation A pointer to a buffer that contains the key information. - * @param[in] KeySetInformationLength The size of the buffer. - * @return NTSTATUS Successful or errant status. + * \param[in] KeyHandle A handle to the key to be modified. + * \param[in] KeySetInformationClass The type of information to be set. + * \param[in] KeySetInformation A pointer to a buffer that contains the key information. + * \param[in] KeySetInformationLength The size of the buffer. + * \return NTSTATUS Successful or errant status. */ NTSYSCALLAPI NTSTATUS @@ -805,20 +901,20 @@ NtSetInformationKey( /** * Queries the value of a registry key. * - * @param[in] KeyHandle A handle to the key to be queried. - * @param[in] ValueName A pointer to a UNICODE_STRING structure that specifies the name of the value to be queried. - * @param[in] KeyValueInformationClass The type of information to be queried. - * @param[out] KeyValueInformation A pointer to a buffer that receives the value information. - * @param[in] Length The size of the buffer. - * @param[out] ResultLength A pointer to a variable that receives the size of the data returned. - * @return NTSTATUS Successful or errant status. + * \param[in] KeyHandle A handle to the key to be queried. + * \param[in] ValueName A pointer to a UNICODE_STRING structure that specifies the name of the value to be queried. + * \param[in] KeyValueInformationClass The type of information to be queried. + * \param[out] KeyValueInformation A pointer to a buffer that receives the value information. + * \param[in] Length The size of the buffer. + * \param[out] ResultLength A pointer to a variable that receives the size of the data returned. + * \return NTSTATUS Successful or errant status. */ NTSYSCALLAPI NTSTATUS NTAPI NtQueryValueKey( _In_ HANDLE KeyHandle, - _In_ PUNICODE_STRING ValueName, + _In_ PCUNICODE_STRING ValueName, _In_ KEY_VALUE_INFORMATION_CLASS KeyValueInformationClass, _Out_writes_bytes_to_opt_(Length, *ResultLength) PVOID KeyValueInformation, _In_ ULONG Length, @@ -828,20 +924,20 @@ NtQueryValueKey( /** * Sets the value of a registry key. * - * @param[in] KeyHandle A handle to the key to be modified. - * @param[in] ValueName A pointer to a UNICODE_STRING structure that specifies the name of the value to be set. - * @param[in, optional] TitleIndex Reserved. - * @param[in] Type The type of the value. - * @param[in] Data A pointer to a buffer that contains the value data. - * @param[in] DataSize The size of the buffer. - * @return NTSTATUS Successful or errant status. + * \param[in] KeyHandle A handle to the key to be modified. + * \param[in] ValueName A pointer to a UNICODE_STRING structure that specifies the name of the value to be set. + * \param[in, optional] TitleIndex Reserved. + * \param[in] Type The type of the value. + * \param[in] Data A pointer to a buffer that contains the value data. + * \param[in] DataSize The size of the buffer. + * \return NTSTATUS Successful or errant status. */ NTSYSCALLAPI NTSTATUS NTAPI NtSetValueKey( _In_ HANDLE KeyHandle, - _In_ PUNICODE_STRING ValueName, + _In_ PCUNICODE_STRING ValueName, _In_opt_ ULONG TitleIndex, _In_ ULONG Type, _In_reads_bytes_opt_(DataSize) PVOID Data, @@ -851,13 +947,13 @@ NtSetValueKey( /** * Queries multiple values of a registry key. * - * @param[in] KeyHandle A handle to the key to be queried. - * @param[in, out] ValueEntries A pointer to an array of KEY_VALUE_ENTRY structures that specify the values to be queried. - * @param[in] EntryCount The number of entries in the array. - * @param[out] ValueBuffer A pointer to a buffer that receives the value data. - * @param[in, out] BufferLength A pointer to a variable that specifies the size of the buffer and receives the size of the data returned. - * @param[out, optional] RequiredBufferLength A pointer to a variable that receives the size of the buffer required to hold the data. - * @return NTSTATUS Successful or errant status. + * \param[in] KeyHandle A handle to the key to be queried. + * \param[in, out] ValueEntries A pointer to an array of KEY_VALUE_ENTRY structures that specify the values to be queried. + * \param[in] EntryCount The number of entries in the array. + * \param[out] ValueBuffer A pointer to a buffer that receives the value data. + * \param[in, out] BufferLength A pointer to a variable that specifies the size of the buffer and receives the size of the data returned. + * \param[out, optional] RequiredBufferLength A pointer to a variable that receives the size of the buffer required to hold the data. + * \return NTSTATUS Successful or errant status. */ NTSYSCALLAPI NTSTATUS @@ -874,13 +970,13 @@ NtQueryMultipleValueKey( /** * Enumerates the subkeys of a registry key. * - * @param[in] KeyHandle A handle to the key to be enumerated. - * @param[in] Index The index of the subkey to be enumerated. - * @param[in] KeyInformationClass The type of information to be queried. - * @param[out] KeyInformation A pointer to a buffer that receives the key information. - * @param[in] Length The size of the buffer. - * @param[out] ResultLength A pointer to a variable that receives the size of the data returned. - * @return NTSTATUS Successful or errant status. + * \param[in] KeyHandle A handle to the key to be enumerated. + * \param[in] Index The index of the subkey to be enumerated. + * \param[in] KeyInformationClass The type of information to be queried. + * \param[out] KeyInformation A pointer to a buffer that receives the key information. + * \param[in] Length The size of the buffer. + * \param[out] ResultLength A pointer to a variable that receives the size of the data returned. + * \return NTSTATUS Successful or errant status. */ NTSYSCALLAPI NTSTATUS @@ -897,13 +993,13 @@ NtEnumerateKey( /** * Enumerates the values of a registry key. * - * @param[in] KeyHandle A handle to the key to be enumerated. - * @param[in] Index The index of the value to be enumerated. - * @param[in] KeyValueInformationClass The type of information to be queried. - * @param[out] KeyValueInformation A pointer to a buffer that receives the value information. - * @param[in] Length The size of the buffer. - * @param[out] ResultLength A pointer to a variable that receives the size of the data returned. - * @return NTSTATUS Successful or errant status. + * \param[in] KeyHandle A handle to the key to be enumerated. + * \param[in] Index The index of the value to be enumerated. + * \param[in] KeyValueInformationClass The type of information to be queried. + * \param[out] KeyValueInformation A pointer to a buffer that receives the value information. + * \param[in] Length The size of the buffer. + * \param[out] ResultLength A pointer to a variable that receives the size of the data returned. + * \return NTSTATUS Successful or errant status. */ NTSYSCALLAPI NTSTATUS @@ -920,8 +1016,8 @@ NtEnumerateValueKey( /** * Flushes the changes to a registry key. * - * @param[in] KeyHandle A handle to the key to be flushed. - * @return NTSTATUS Successful or errant status. + * \param[in] KeyHandle A handle to the key to be flushed. + * \return NTSTATUS Successful or errant status. */ NTSYSCALLAPI NTSTATUS @@ -933,9 +1029,9 @@ NtFlushKey( /** * Compacts the specified registry keys. * - * @param[in] Count The number of keys to be compacted. - * @param[in] KeyArray An array of handles to the keys to be compacted. - * @return NTSTATUS Successful or errant status. + * \param[in] Count The number of keys to be compacted. + * \param[in] KeyArray An array of handles to the keys to be compacted. + * \return NTSTATUS Successful or errant status. */ NTSYSCALLAPI NTSTATUS @@ -948,8 +1044,8 @@ NtCompactKeys( /** * Compresses a registry key. * - * @param[in] KeyHandle A handle to the key to be compressed. - * @return NTSTATUS Successful or errant status. + * \param[in] KeyHandle A handle to the key to be compressed. + * \return NTSTATUS Successful or errant status. */ NTSYSCALLAPI NTSTATUS @@ -961,9 +1057,9 @@ NtCompressKey( /** * Loads a registry key from a file. * - * @param[in] TargetKey A pointer to an OBJECT_ATTRIBUTES structure that specifies the target key. - * @param[in] SourceFile A pointer to an OBJECT_ATTRIBUTES structure that specifies the source file. - * @return NTSTATUS Successful or errant status. + * \param[in] TargetKey A pointer to an OBJECT_ATTRIBUTES structure that specifies the target key. + * \param[in] SourceFile A pointer to an OBJECT_ATTRIBUTES structure that specifies the source file. + * \return NTSTATUS Successful or errant status. */ NTSYSCALLAPI NTSTATUS @@ -976,10 +1072,10 @@ NtLoadKey( /** * Loads a registry key from a file with additional options. * - * @param[in] TargetKey A pointer to an OBJECT_ATTRIBUTES structure that specifies the target key. - * @param[in] SourceFile A pointer to an OBJECT_ATTRIBUTES structure that specifies the source file. - * @param[in] Flags The options to use when loading the key. - * @return NTSTATUS Successful or errant status. + * \param[in] TargetKey A pointer to an OBJECT_ATTRIBUTES structure that specifies the target key. + * \param[in] SourceFile A pointer to an OBJECT_ATTRIBUTES structure that specifies the source file. + * \param[in] Flags The options to use when loading the key. + * \return NTSTATUS Successful or errant status. */ NTSYSCALLAPI NTSTATUS @@ -990,19 +1086,18 @@ NtLoadKey2( _In_ ULONG Flags ); -#if (PHNT_VERSION >= PHNT_WINDOWS_SERVER_2003) /** * Loads a registry key from a file with extended options. * - * @param[in] TargetKey A pointer to an OBJECT_ATTRIBUTES structure that specifies the target key. - * @param[in] SourceFile A pointer to an OBJECT_ATTRIBUTES structure that specifies the source file. - * @param[in] Flags The options to use when loading the key. - * @param[in, optional] TrustClassKey A handle to the trust class key. - * @param[in, optional] Event A handle to an event. - * @param[in, optional] DesiredAccess The access mask that specifies the desired access rights. - * @param[out, optional] RootHandle A pointer to a handle that receives the root handle. - * @param[in, reserved] Reserved Reserved. - * @return NTSTATUS Successful or errant status. + * \param[in] TargetKey A pointer to an OBJECT_ATTRIBUTES structure that specifies the target key. + * \param[in] SourceFile A pointer to an OBJECT_ATTRIBUTES structure that specifies the source file. + * \param[in] Flags The options to use when loading the key. + * \param[in, optional] TrustClassKey A handle to the trust class key. + * \param[in, optional] Event A handle to an event. + * \param[in, optional] DesiredAccess The access mask that specifies the desired access rights. + * \param[out, optional] RootHandle A pointer to a handle that receives the root handle. + * \param[in, reserved] Reserved Reserved. + * \return NTSTATUS Successful or errant status. */ NTSYSCALLAPI NTSTATUS @@ -1017,22 +1112,21 @@ NtLoadKeyEx( _Out_opt_ PHANDLE RootHandle, _Reserved_ PVOID Reserved // previously PIO_STATUS_BLOCK ); -#endif #if (PHNT_VERSION >= PHNT_WINDOWS_10_20H1) // rev by tyranid /** * Loads a registry key from a file with extended parameters. * - * @param[in] TargetKey A pointer to an OBJECT_ATTRIBUTES structure that specifies the target key. - * @param[in] SourceFile A pointer to an OBJECT_ATTRIBUTES structure that specifies the source file. - * @param[in] Flags The options to use when loading the key. - * @param[in] ExtendedParameters A pointer to an array of extended parameters. - * @param[in] ExtendedParameterCount The number of extended parameters. - * @param[in, optional] DesiredAccess The access mask that specifies the desired access rights. - * @param[out, optional] RootHandle A pointer to a handle that receives the root handle. - * @param[in, reserved] Reserved Reserved. - * @return NTSTATUS Successful or errant status. + * \param[in] TargetKey A pointer to an OBJECT_ATTRIBUTES structure that specifies the target key. + * \param[in] SourceFile A pointer to an OBJECT_ATTRIBUTES structure that specifies the source file. + * \param[in] Flags The options to use when loading the key. + * \param[in] ExtendedParameters A pointer to an array of extended parameters. + * \param[in] ExtendedParameterCount The number of extended parameters. + * \param[in, optional] DesiredAccess The access mask that specifies the desired access rights. + * \param[out, optional] RootHandle A pointer to a handle that receives the root handle. + * \param[in, reserved] Reserved Reserved. + * \return NTSTATUS Successful or errant status. */ NTSYSCALLAPI NTSTATUS @@ -1052,10 +1146,10 @@ NtLoadKey3( /** * Replaces a registry key. * - * @param[in] NewFile A pointer to an OBJECT_ATTRIBUTES structure that specifies the new file. - * @param[in] TargetHandle A handle to the target key. - * @param[in] OldFile A pointer to an OBJECT_ATTRIBUTES structure that specifies the old file. - * @return NTSTATUS Successful or errant status. + * \param[in] NewFile A pointer to an OBJECT_ATTRIBUTES structure that specifies the new file. + * \param[in] TargetHandle A handle to the target key. + * \param[in] OldFile A pointer to an OBJECT_ATTRIBUTES structure that specifies the old file. + * \return NTSTATUS Successful or errant status. */ NTSYSCALLAPI NTSTATUS @@ -1069,9 +1163,9 @@ NtReplaceKey( /** * Saves the specified registry key to a file. * - * @param KeyHandle Handle to the registry key. - * @param FileHandle Handle to the file where the key will be saved. - * @return NTSTATUS Successful or errant status. + * \param KeyHandle Handle to the registry key. + * \param FileHandle Handle to the file where the key will be saved. + * \return NTSTATUS Successful or errant status. */ NTSYSCALLAPI NTSTATUS @@ -1084,10 +1178,10 @@ NtSaveKey( /** * Saves the specified registry key to a file with a specified format. * - * @param KeyHandle Handle to the registry key. - * @param FileHandle Handle to the file where the key will be saved. - * @param Format Format in which the key will be saved. - * @return NTSTATUS Successful or errant status. + * \param KeyHandle Handle to the registry key. + * \param FileHandle Handle to the file where the key will be saved. + * \param Format Format in which the key will be saved. + * \return NTSTATUS Successful or errant status. */ NTSYSCALLAPI NTSTATUS @@ -1101,10 +1195,10 @@ NtSaveKeyEx( /** * Merges two registry keys and saves the result to a file. * - * @param HighPrecedenceKeyHandle Handle to the high precedence registry key. - * @param LowPrecedenceKeyHandle Handle to the low precedence registry key. - * @param FileHandle Handle to the file where the merged key will be saved. - * @return NTSTATUS Successful or errant status. + * \param HighPrecedenceKeyHandle Handle to the high precedence registry key. + * \param LowPrecedenceKeyHandle Handle to the low precedence registry key. + * \param FileHandle Handle to the file where the merged key will be saved. + * \return NTSTATUS Successful or errant status. */ NTSYSCALLAPI NTSTATUS @@ -1118,10 +1212,10 @@ NtSaveMergedKeys( /** * Restores a registry key from a file. * - * @param KeyHandle Handle to the registry key. - * @param FileHandle Handle to the file from which the key will be restored. - * @param Flags Flags for the restore operation. - * @return NTSTATUS Successful or errant status. + * \param KeyHandle Handle to the registry key. + * \param FileHandle Handle to the file from which the key will be restored. + * \param Flags Flags for the restore operation. + * \return NTSTATUS Successful or errant status. */ NTSYSCALLAPI NTSTATUS @@ -1135,8 +1229,8 @@ NtRestoreKey( /** * Unloads a registry key. * - * @param TargetKey Pointer to the object attributes of the target key. - * @return NTSTATUS Successful or errant status. + * \param TargetKey Pointer to the object attributes of the target key. + * \return NTSTATUS Successful or errant status. */ NTSYSCALLAPI NTSTATUS @@ -1145,14 +1239,13 @@ NtUnloadKey( _In_ POBJECT_ATTRIBUTES TargetKey ); -#if PHNT_VERSION >= PHNT_WINDOWS_SERVER_2003 /** * Unloads a registry key with additional flags. * - * @param TargetKey Pointer to the object attributes of the target key. - * @param Flags Flags for the unload operation. - * @return NTSTATUS Successful or errant status. - * @remarks Valid flags are REG_FORCE_UNLOAD and REG_UNLOAD_LEGAL_FLAGS. + * \param TargetKey Pointer to the object attributes of the target key. + * \param Flags Flags for the unload operation. + * \return NTSTATUS Successful or errant status. + * \remarks Valid flags are REG_FORCE_UNLOAD and REG_UNLOAD_LEGAL_FLAGS. */ NTSYSCALLAPI NTSTATUS @@ -1161,14 +1254,13 @@ NtUnloadKey2( _In_ POBJECT_ATTRIBUTES TargetKey, _In_ ULONG Flags ); -#endif /** * Unloads a registry key and optionally signals an event. * - * @param TargetKey Pointer to the object attributes of the target key. - * @param Event Optional handle to an event to be signaled. - * @return NTSTATUS Successful or errant status. + * \param TargetKey Pointer to the object attributes of the target key. + * \param Event Optional handle to an event to be signaled. + * \return NTSTATUS Successful or errant status. */ NTSYSCALLAPI NTSTATUS @@ -1181,17 +1273,17 @@ NtUnloadKeyEx( /** * Notifies of changes to a registry key. * - * @param KeyHandle Handle to the registry key. - * @param Event Optional handle to an event to be signaled. - * @param ApcRoutine Optional APC routine to be called. - * @param ApcContext Optional context for the APC routine. - * @param IoStatusBlock Pointer to an IO status block. - * @param CompletionFilter Filter for the types of changes to notify. - * @param WatchTree Whether to watch the entire tree. - * @param Buffer Optional buffer for change data. - * @param BufferSize Size of the buffer. - * @param Asynchronous Whether the operation is asynchronous. - * @return NTSTATUS Successful or errant status. + * \param KeyHandle Handle to the registry key. + * \param Event Optional handle to an event to be signaled. + * \param ApcRoutine Optional APC routine to be called. + * \param ApcContext Optional context for the APC routine. + * \param IoStatusBlock Pointer to an IO status block. + * \param CompletionFilter Filter for the types of changes to notify. + * \param WatchTree Whether to watch the entire tree. + * \param Buffer Optional buffer for change data. + * \param BufferSize Size of the buffer. + * \param Asynchronous Whether the operation is asynchronous. + * \return NTSTATUS Successful or errant status. */ NTSYSCALLAPI NTSTATUS @@ -1212,19 +1304,19 @@ NtNotifyChangeKey( /** * Requests notification when a registry key or any of its subkeys changes. * - * @param MasterKeyHandle A handle to an open key. The handle must be opened with the KEY_NOTIFY access right. - * @param Count The number of subkeys under the key specified by the MasterKeyHandle parameter. - * @param SubordinateObjects Pointer to an array of OBJECT_ATTRIBUTES structures, one for each subkey. This array can contain one OBJECT_ATTRIBUTES structure. - * @param Event A handle to an event created by the caller. If Event is not NULL, the caller waits until the operation succeeds, at which time the event is signaled. - * @param ApcRoutine A pointer to an asynchronous procedure call (APC) function supplied by the caller. If ApcRoutine is not NULL, the specified APC function executes after the operation completes. - * @param ApcContext A pointer to a context supplied by the caller for its APC function. This value is passed to the APC function when it is executed. The Asynchronous parameter must be TRUE. If ApcContext is specified, the Event parameter must be NULL. - * @param IoStatusBlock A pointer to an IO_STATUS_BLOCK structure that contains the final status and information about the operation. For successful calls that return data, the number of bytes written to the Buffer parameter is supplied in the Information member of the IO_STATUS_BLOCK structure. - * @param CompletionFilter A bitmap of operations that trigger notification. This parameter can be one or more of the following flags. REG_NOTIFY_CHANGE_NAME, REG_NOTIFY_CHANGE_ATTRIBUTES, REG_NOTIFY_CHANGE_LAST_SET, REG_NOTIFY_CHANGE_SECURITY. - * @param WatchTree If this parameter is TRUE, the caller is notified about changes to all subkeys of the specified key. If this parameter is FALSE, the caller is notified only about changes to the specified key. - * @param Buffer Reserved for system use. This parameter must be NULL. - * @param BufferSize Reserved for system use. This parameter must be zero. - * @param Asynchronous Whether the operation is asynchronous. - * @return NTSTATUS Successful or errant status. + * \param MasterKeyHandle A handle to an open key. The handle must be opened with the KEY_NOTIFY access right. + * \param Count The number of subkeys under the key specified by the MasterKeyHandle parameter. + * \param SubordinateObjects Pointer to an array of OBJECT_ATTRIBUTES structures, one for each subkey. This array can contain one OBJECT_ATTRIBUTES structure. + * \param Event A handle to an event created by the caller. If Event is not NULL, the caller waits until the operation succeeds, at which time the event is signaled. + * \param ApcRoutine A pointer to an asynchronous procedure call (APC) function supplied by the caller. If ApcRoutine is not NULL, the specified APC function executes after the operation completes. + * \param ApcContext A pointer to a context supplied by the caller for its APC function. This value is passed to the APC function when it is executed. The Asynchronous parameter must be TRUE. If ApcContext is specified, the Event parameter must be NULL. + * \param IoStatusBlock A pointer to an IO_STATUS_BLOCK structure that contains the final status and information about the operation. For successful calls that return data, the number of bytes written to the Buffer parameter is supplied in the Information member of the IO_STATUS_BLOCK structure. + * \param CompletionFilter A bitmap of operations that trigger notification. This parameter can be one or more of the following flags. REG_NOTIFY_CHANGE_NAME, REG_NOTIFY_CHANGE_ATTRIBUTES, REG_NOTIFY_CHANGE_LAST_SET, REG_NOTIFY_CHANGE_SECURITY. + * \param WatchTree If this parameter is TRUE, the caller is notified about changes to all subkeys of the specified key. If this parameter is FALSE, the caller is notified only about changes to the specified key. + * \param Buffer Reserved for system use. This parameter must be NULL. + * \param BufferSize Reserved for system use. This parameter must be zero. + * \param Asynchronous Whether the operation is asynchronous. + * \return NTSTATUS Successful or errant status. */ NTSYSCALLAPI NTSTATUS @@ -1247,9 +1339,9 @@ NtNotifyChangeMultipleKeys( /** * Queries the number of open subkeys of a registry key. * - * @param TargetKey Pointer to the object attributes of the target key. - * @param HandleCount Pointer to a variable to receive the handle count. - * @return NTSTATUS Successful or errant status. + * \param TargetKey Pointer to the object attributes of the target key. + * \param HandleCount Pointer to a variable to receive the handle count. + * \return NTSTATUS Successful or errant status. */ NTSYSCALLAPI NTSTATUS @@ -1259,16 +1351,27 @@ NtQueryOpenSubKeys( _Out_ PULONG HandleCount ); -#if (PHNT_VERSION >= PHNT_WINDOWS_SERVER_2003) +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; + /** * Queries the open subkeys of a registry key with additional information. * - * @param TargetKey Pointer to the object attributes of the target key. - * @param BufferLength Length of the buffer. - * @param Buffer Optional buffer to receive the subkey information. - * @param RequiredSize Pointer to a variable to receive the required size. - * @return NTSTATUS Successful or errant status. - * @remarks Returns an array of KEY_OPEN_SUBKEYS_INFORMATION structures. + * \param TargetKey Pointer to the object attributes of the target key. + * \param BufferLength Length of the buffer. + * \param Buffer Optional buffer to receive the subkey information. + * \param RequiredSize Pointer to a variable to receive the required size. + * \return NTSTATUS Successful or errant status. + * \remarks Returns an array of KEY_OPEN_SUBKEYS_INFORMATION structures. */ NTSYSCALLAPI NTSTATUS @@ -1279,13 +1382,21 @@ NtQueryOpenSubKeysEx( _Out_writes_bytes_opt_(BufferLength) PVOID Buffer, _Out_ PULONG RequiredSize ); -#endif + +// +// 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) /** * Initializes the registry. * - * @param BootCondition Condition for the boot. - * @return NTSTATUS Successful or errant status. + * \param BootCondition Condition for the boot. + * \return NTSTATUS Successful or errant status. */ NTSYSCALLAPI NTSTATUS @@ -1297,8 +1408,8 @@ NtInitializeRegistry( /** * Locks the registry key and prevents changes from being written to disk. * - * @param KeyHandle Handle to the registry key. - * @return NTSTATUS Successful or errant status. + * \param KeyHandle Handle to the registry key. + * \return NTSTATUS Successful or errant status. */ NTSYSCALLAPI NTSTATUS @@ -1310,9 +1421,9 @@ NtLockRegistryKey( /** * Locks the product activation keys. * - * @param pPrivateVer Optional pointer to a private version variable. - * @param pSafeMode Optional pointer to a safe mode variable. - * @return NTSTATUS Successful or errant status. + * \param pPrivateVer Optional pointer to a private version variable. + * \param pSafeMode Optional pointer to a safe mode variable. + * \return NTSTATUS Successful or errant status. */ NTSYSCALLAPI NTSTATUS @@ -1322,12 +1433,11 @@ NtLockProductActivationKeys( _Out_opt_ ULONG *pSafeMode ); -#if (PHNT_VERSION >= PHNT_WINDOWS_VISTA) /** * Freezes the registry and prevents changes from being flushed to disk. * - * @param TimeOutInSeconds Timeout in seconds. - * @return NTSTATUS Successful or errant status. + * \param TimeOutInSeconds Timeout in seconds. + * \return NTSTATUS Successful or errant status. */ NTSYSCALLAPI NTSTATUS @@ -1335,13 +1445,11 @@ NTAPI NtFreezeRegistry( _In_ ULONG TimeOutInSeconds ); -#endif -#if (PHNT_VERSION >= PHNT_WINDOWS_VISTA) /** * Thaws the registry and enables flushing changes to disk. * - * @return NTSTATUS Successful or errant status. + * \return NTSTATUS Successful or errant status. */ NTSYSCALLAPI NTSTATUS @@ -1349,19 +1457,21 @@ NTAPI NtThawRegistry( VOID ); -#endif #if (PHNT_VERSION >= PHNT_WINDOWS_10_RS1) /** * Creates a registry transaction. * - * @param RegistryTransactionHandle Pointer to a variable to receive the handle. - * @param DesiredAccess Desired access mask. - * @param ObjAttributes Optional pointer to object attributes. - * @param CreateOptions Reserved for future use. - * @return NTSTATUS Successful or errant status. + * \param RegistryTransactionHandle Pointer to a variable to receive the handle. + * \param DesiredAccess Desired access mask. + * \param ObjAttributes Optional pointer to object attributes. + * \param CreateOptions Reserved for future use. + * \return NTSTATUS Successful or errant status. */ -NTSTATUS NtCreateRegistryTransaction( +NTSYSCALLAPI +NTSTATUS +NTAPI +NtCreateRegistryTransaction( _Out_ HANDLE *RegistryTransactionHandle, _In_ ACCESS_MASK DesiredAccess, _In_opt_ POBJECT_ATTRIBUTES ObjAttributes, @@ -1373,12 +1483,15 @@ NTSTATUS NtCreateRegistryTransaction( /** * Opens a registry transaction. * - * @param RegistryTransactionHandle Pointer to a variable to receive the handle. - * @param DesiredAccess Desired access mask. - * @param ObjAttributes Pointer to object attributes. - * @return NTSTATUS Successful or errant status. + * \param RegistryTransactionHandle Pointer to a variable to receive the handle. + * \param DesiredAccess Desired access mask. + * \param ObjAttributes Pointer to object attributes. + * \return NTSTATUS Successful or errant status. */ -NTSTATUS NtOpenRegistryTransaction( +NTSYSCALLAPI +NTSTATUS +NTAPI +NtOpenRegistryTransaction( _Out_ HANDLE *RegistryTransactionHandle, _In_ ACCESS_MASK DesiredAccess, _In_ POBJECT_ATTRIBUTES ObjAttributes @@ -1389,11 +1502,14 @@ NTSTATUS NtOpenRegistryTransaction( /** * Commits a registry transaction. * - * @param RegistryTransactionHandle Handle to the registry transaction. - * @param Flags Reserved for future use. - * @return NTSTATUS Successful or errant status. + * \param RegistryTransactionHandle Handle to the registry transaction. + * \param Flags Reserved for future use. + * \return NTSTATUS Successful or errant status. */ -NTSTATUS NtCommitRegistryTransaction( +NTSYSCALLAPI +NTSTATUS +NTAPI +NtCommitRegistryTransaction( _In_ HANDLE RegistryTransactionHandle, _Reserved_ ULONG Flags ); @@ -1403,14 +1519,17 @@ NTSTATUS NtCommitRegistryTransaction( /** * Rolls back a registry transaction. * - * @param RegistryTransactionHandle Handle to the registry transaction. - * @param Flags Reserved for future use. - * @return NTSTATUS Successful or errant status. + * \param RegistryTransactionHandle Handle to the registry transaction. + * \param Flags Reserved for future use. + * \return NTSTATUS Successful or errant status. */ -NTSTATUS NtRollbackRegistryTransaction( +NTSYSCALLAPI +NTSTATUS +NTAPI +NtRollbackRegistryTransaction( _In_ HANDLE RegistryTransactionHandle, _Reserved_ ULONG Flags ); #endif -#endif +#endif // _NTREGAPI_H diff --git a/ntrtl.h b/ntrtl.h index e8cee3a..afe8c43 100644 --- a/ntrtl.h +++ b/ntrtl.h @@ -7,20 +7,186 @@ #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)))) +typedef struct _CPTABLEINFO CPTABLEINFO, *PCPTABLEINFO; +typedef enum _FILE_INFORMATION_CLASS FILE_INFORMATION_CLASS, *PFILE_INFORMATION_CLASS; -#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))) +// +// Pointer arithmetic macros (type safe) +// -#define RTL_MILLISEC_TO_100NANOSEC(m) ((m) * 10000ULL) -#define RTL_SEC_TO_100NANOSEC(s) ((s) * 10000000ULL) -#define RTL_SEC_TO_MILLISEC(s) ((s) * 1000ULL) +#define RtlOffsetToPointer(Base, Offset) ((PUCHAR)(((PUCHAR)(Base)) + ((ULONG_PTR)(Offset)))) +#define RtlPointerToOffset(Base, Pointer) ((ULONG)(((PUCHAR)(Pointer)) - ((PUCHAR)(Base)))) -#define RTL_MEG (1024UL * 1024UL) -#define RTL_IMAGE_MAX_DOS_HEADER (256UL * RTL_MEG) +#if defined(__cplusplus) +EXTERN_C_END + +template +FORCEINLINE +T* +RTL_PTR_ADD(T* Pointer, ULONG_PTR Value) noexcept { + return reinterpret_cast(reinterpret_cast(Pointer) + Value); +} + +template +FORCEINLINE +T* +RTL_PTR_SUBTRACT(T* Pointer, ULONG_PTR Value) noexcept { + return reinterpret_cast(reinterpret_cast(Pointer) - Value); +} + +EXTERN_C_START + +#else + +#ifndef RTL_PTR_ADD +#define RTL_PTR_ADD(Pointer, Value) ((PVOID)(((PUCHAR)(Pointer)) + ((ULONG_PTR)(Value)))) +#endif + +#ifndef RTL_PTR_SUBTRACT +#define RTL_PTR_SUBTRACT(Pointer, Value) ((PVOID)(((PUCHAR)(Pointer)) - ((ULONG_PTR)(Value)))) +#endif + +#endif + +#ifndef RTL_IS_POWER_OF_TWO +#define RTL_IS_POWER_OF_TWO(Value) ((Value != 0) && !((Value) & ((Value) - 1))) +#endif + +#ifndef RTL_IS_CLEAR_OR_SINGLE_FLAG +#define RTL_IS_CLEAR_OR_SINGLE_FLAG(Flags, Mask) (((Flags) & (Mask)) == 0 || !(((Flags) & (Mask)) & (((Flags) & (Mask)) - 1))) +#endif + +#ifndef RTL_NUM_ALIGN_DOWN +#define RTL_NUM_ALIGN_DOWN(Number, Alignment) ((Number) - ((Number) & ((Alignment) - 1))) +#endif + +#ifndef RTL_NUM_ALIGN_UP +#define RTL_NUM_ALIGN_UP(Number, Alignment) RTL_NUM_ALIGN_DOWN((Number) + (Alignment) - 1, (Alignment)) +#endif + +// +// Time unit constants (ordered by magnitude) +// + +#define RTL_NANOSEC_PER_TICK 100 +#define RTL_TICKS_PER_MICROSEC 10 +#define RTL_TICKS_PER_MILLISEC (RTL_TICKS_PER_MICROSEC * 1000) // 10,000 +#define RTL_TICKS_PER_SEC (RTL_TICKS_PER_MILLISEC * 1000) // 10,000,000 +#define RTL_TICKS_PER_MIN (RTL_TICKS_PER_SEC * 60) // 600,000,000 +#define RTL_TICKS_PER_HOUR (RTL_TICKS_PER_MIN * 60) // 36,000,000,000 +#define RTL_TICKS_PER_DAY (RTL_TICKS_PER_HOUR * 24) // 864,000,000,000 +#define RTL_TICKS_PER_WEEK (RTL_TICKS_PER_DAY * 7) // 6,048,000,000,000 +#define RTL_TICKS_PER_MONTH (RTL_TICKS_PER_DAY * 30) // 25,920,000,000,000 +#define RTL_TICKS_PER_YEAR (RTL_TICKS_PER_DAY * 365) // 31,536,000,000,000 +#define RTL_TICKS_PER_LEAP_YEAR (RTL_TICKS_PER_DAY * 366) // 31,622,400,000,000 + +#define RTL_NANOSEC_PER_SEC 1000000000ull +#define RTL_NANOSEC_PER_MILLISEC 1000000ull +#define RTL_100NANOSEC_PER_SEC 10000000ull +#define RTL_100NANOSEC_PER_MILLISEC 10000ull +#define RTL_MILLISEC_PER_SEC 1000ull + +#define RTL_SEC_PER_HOUR 3600ull // 1 hour // 3,600 seconds +#define RTL_SEC_PER_DAY 86400ull // 1 day // 86,400 seconds +#define RTL_SEC_PER_WEEK 604800ull // 1 week // 604,800 seconds +#define RTL_SEC_PER_MONTH 2592000ull // 1 month // 2,592,000 seconds (30 days) +#define RTL_SEC_PER_YEAR 31536000ull // 1 year // 31,536,000 seconds (365 days) + +// +// Time conversion macros (ordered by unit) +// + +// Nanoseconds +#define RTL_SEC_TO_NANOSEC(s) ((s) * RTL_NANOSEC_PER_SEC) +#define RTL_NANOSEC_TO_SEC(ns) ((ns) / RTL_NANOSEC_PER_SEC) +#define RTL_MILLISEC_TO_NANOSEC(m) ((m) * RTL_NANOSEC_PER_MILLISEC) +#define RTL_NANOSEC_TO_MILLISEC(ns) ((ns) / RTL_NANOSEC_PER_MILLISEC) +#define RTL_NANOSEC_TO_100NANOSEC(ns) ((ns) / 100) +#define RTL_100NANOSEC_TO_NANOSEC(ns) ((ns) * 100) + +// 100-Nanoseconds +#define RTL_SEC_TO_100NANOSEC(s) ((s) * RTL_100NANOSEC_PER_SEC) +#define RTL_100NANOSEC_TO_SEC(ns) ((ns) / RTL_100NANOSEC_PER_SEC) +#define RTL_MILLISEC_TO_100NANOSEC(m) ((m) * RTL_100NANOSEC_PER_MILLISEC) +#define RTL_100NANOSEC_TO_MILLISEC(ns) ((ns) / RTL_100NANOSEC_PER_MILLISEC) + +// Milliseconds +#define RTL_SEC_TO_MILLISEC(s) ((s) * RTL_MILLISEC_PER_SEC) +#define RTL_MILLISEC_TO_SEC(m) ((m) / RTL_MILLISEC_PER_SEC) + +/** + * The maximum value of the e_lfanew field in the IMAGE_DOS_HEADER structure for validation. + */ +#define RTL_IMAGE_MAX_DOS_HEADER (256UL * (1024UL * 1024UL)) // 256 MB + +/** + * Meta characters for wildcard processing. + * \remarks NtQueryDirectoryFile(Ex), RtlDoesNameContainWildCards and file system drivers (FAT, NTFS, REFS). + */ +#define ANSI_DOS_STAR ((CHAR)'<') +#define ANSI_DOS_STAR_W ((WCHAR)L'<') +#define ANSI_DOS_QM ((CHAR)'>') +#define ANSI_DOS_QM_W ((WCHAR)L'>') +#define ANSI_DOS_DOT ((CHAR)'"') +#define ANSI_DOS_DOT_W ((WCHAR)L'"') + +// +// Errors +// + +/** + * The RtlFailFast routine brings down the caller immediately in the event that critical corruption has been detected. No exception handlers are invoked. + * + * \param Code A FAST_FAIL_ symbolic constant from winnt.h or wdm.h that indicates the reason for process termination. + * \return None. There is no return from this routine. + * \remarks The routine is shared with user mode and kernel mode. In user mode, the process is terminated, whereas in kernel mode, a KERNEL_SECURITY_CHECK_FAILURE bug check is raised. + */ +DECLSPEC_NORETURN +FORCEINLINE +VOID +NTAPI_INLINE +RtlFailFast( + _In_ ULONG Code + ) +{ + __fastfail(Code); +} + +/** + * The RtlFatalListEntryError routine reports a fatal list entry error. + * + * \param p1 The first parameter passed to `RtlFailFast`. + * \param p2 The second parameter passed to `RtlFailFast`. + * \param p3 The third parameter passed to `RtlFailFast`. + * \remarks This routine is a wrapper around `RtlFailFast` that can be used to provide alternative reporting mechanisms, such as logging and trying to continue. + */ +DECLSPEC_NORETURN +FORCEINLINE +VOID +NTAPI_INLINE +RtlFatalListEntryError( + _In_ PVOID p1, + _In_ PVOID p2, + _In_ PVOID p3 + ) +{ + //++ + // This routine reports a fatal list entry error. It is implemented here as a + // wrapper around RtlFailFast so that alternative reporting mechanisms (such + // as simply logging and trying to continue) can be easily switched in. + //-- + + UNREFERENCED_PARAMETER(p1); + UNREFERENCED_PARAMETER(p2); + UNREFERENCED_PARAMETER(p3); + + RtlFailFast(FAST_FAIL_CORRUPT_LIST_ENTRY); +} + +// // Linked lists +// typedef struct _LIST_ENTRY LIST_ENTRY, *PLIST_ENTRY; @@ -28,10 +194,44 @@ typedef struct _LIST_ENTRY LIST_ENTRY, *PLIST_ENTRY; LIST_ENTRY (x) = { &(x), &(x) } #define RTL_LIST_FOREACH(Entry, ListHead) \ - for ((Entry) = &(ListHead); (Entry) != &(ListHead); (Entry) = (Entry)->Flink) + for ((Entry) = (&(ListHead))->Flink; (Entry) != &(ListHead); (Entry) = (Entry)->Flink) +// #ifndef NO_LIST_ENTRY_CHECKS +// #define NO_LIST_ENTRY_CHECKS +// #endif + +/** + * The RtlCheckListEntry routine checks the integrity of a doubly linked list entry. + * + * \param Entry A pointer to the list entry to check. + * \remarks This function calls `RtlFatalListEntryError` if the list entry is corrupted. + */ FORCEINLINE VOID +NTAPI_INLINE +RtlCheckListEntry( + _In_ PLIST_ENTRY Entry + ) +{ + if ((((Entry->Flink)->Blink) != Entry) || (((Entry->Blink)->Flink) != Entry)) + { + RtlFatalListEntryError( + (PVOID)(Entry), + (PVOID)((Entry->Flink)->Blink), + (PVOID)((Entry->Blink)->Flink) + ); + } +} + +/** + * The InitializeListHead routine initializes a doubly linked list head. + * + * \param ListHead A pointer to the `LIST_ENTRY` structure to be initialized as a list head. + * \sa https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/wdm/nf-wdm-initializelisthead + */ +FORCEINLINE +VOID +NTAPI_INLINE InitializeListHead( _Out_ PLIST_ENTRY ListHead ) @@ -39,18 +239,33 @@ InitializeListHead( ListHead->Flink = ListHead->Blink = ListHead; } +/** + * The InitializeListHead32 routine initializes a 32-bit doubly linked list head. + * + * \param ListHead A pointer to the `LIST_ENTRY32` structure to be initialized as a list head. + */ FORCEINLINE VOID +NTAPI_INLINE InitializeListHead32( _Out_ PLIST_ENTRY32 ListHead ) { - ListHead->Flink = ListHead->Blink = ((ULONG)(ULONG_PTR)ListHead); + ListHead->Flink = ListHead->Blink = PtrToUlong(ListHead); } +/** + * The IsListEmpty routine determines whether a doubly linked list is empty. + * + * \param ListHead A pointer to the list head. + * + * \return `TRUE` if the list is empty, otherwise `FALSE`. + * \sa https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/wdm/nf-wdm-islistempty + */ _Must_inspect_result_ FORCEINLINE BOOLEAN +NTAPI_INLINE IsListEmpty( _In_ PLIST_ENTRY ListHead ) @@ -58,7 +273,16 @@ IsListEmpty( return ListHead->Flink == ListHead; } -FORCEINLINE BOOLEAN RemoveEntryList( +/** + * The RemoveEntryListUnsafe routine removes an entry from a doubly linked list without checking for integrity. + * + * \param Entry A pointer to the list entry to be removed. + * \return `TRUE` if the list becomes empty after the entry is removed, otherwise `FALSE`. + */ +FORCEINLINE +BOOLEAN +NTAPI_INLINE +RemoveEntryListUnsafe( _In_ PLIST_ENTRY Entry ) { @@ -69,82 +293,212 @@ FORCEINLINE BOOLEAN RemoveEntryList( Blink = Entry->Blink; Blink->Flink = Flink; Flink->Blink = Blink; - - return Flink == Blink; + return (BOOLEAN)(Flink == Blink); } -FORCEINLINE PLIST_ENTRY RemoveHeadList( +/** + * The RemoveEntryList routine removes an entry from a doubly linked list. + * + * \param Entry A pointer to the list entry to be removed. + * \return `TRUE` if the list becomes empty after the entry is removed, otherwise `FALSE`. + * \sa https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/wdm/nf-wdm-removeentrylist + */ +FORCEINLINE +BOOLEAN +NTAPI_INLINE +RemoveEntryList( + _In_ PLIST_ENTRY Entry + ) +{ + PLIST_ENTRY PrevEntry; + PLIST_ENTRY NextEntry; + + NextEntry = Entry->Flink; + PrevEntry = Entry->Blink; + +#if !defined(NO_LIST_ENTRY_CHECKS) + if ((NextEntry->Blink != Entry) || (PrevEntry->Flink != Entry)) + { + RtlFatalListEntryError((PVOID)PrevEntry, (PVOID)Entry, (PVOID)NextEntry); + } +#endif + + PrevEntry->Flink = NextEntry; + NextEntry->Blink = PrevEntry; + + return NextEntry == PrevEntry; +} + +/** + * The RemoveHeadList routine removes the entry from the head of a doubly linked list. + * + * \param ListHead A pointer to the list head. + * \return A pointer to the entry removed from the head of the list. + * \sa https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/wdm/nf-wdm-removeheadlist + */ +FORCEINLINE +PLIST_ENTRY +NTAPI_INLINE +RemoveHeadList( _Inout_ PLIST_ENTRY ListHead ) { - PLIST_ENTRY Flink; PLIST_ENTRY Entry; + PLIST_ENTRY NextEntry; Entry = ListHead->Flink; - Flink = Entry->Flink; - ListHead->Flink = Flink; - Flink->Blink = ListHead; + NextEntry = Entry->Flink; + +#if !defined(NO_LIST_ENTRY_CHECKS) + if ((Entry->Blink != ListHead) || (NextEntry->Blink != Entry)) + { + RtlFatalListEntryError((PVOID)ListHead, (PVOID)Entry, (PVOID)NextEntry); + } +#endif + + ListHead->Flink = NextEntry; + NextEntry->Blink = ListHead; return Entry; } -FORCEINLINE PLIST_ENTRY RemoveTailList( +/** + * The RemoveTailList routine removes the entry from the tail of a doubly linked list. + * + * \param ListHead A pointer to the list head. + * \return A pointer to the entry removed from the tail of the list. + * \sa https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/wdm/nf-wdm-removetaillist + */ +FORCEINLINE +PLIST_ENTRY +NTAPI_INLINE +RemoveTailList( _Inout_ PLIST_ENTRY ListHead ) { - PLIST_ENTRY Blink; PLIST_ENTRY Entry; + PLIST_ENTRY PrevEntry; Entry = ListHead->Blink; - Blink = Entry->Blink; - ListHead->Blink = Blink; - Blink->Flink = ListHead; + PrevEntry = Entry->Blink; + +#if !defined(NO_LIST_ENTRY_CHECKS) + if ((Entry->Flink != ListHead) || (PrevEntry->Flink != Entry)) + { + RtlFatalListEntryError((PVOID)PrevEntry, (PVOID)Entry, (PVOID)ListHead); + } +#endif + + ListHead->Blink = PrevEntry; + PrevEntry->Flink = ListHead; return Entry; } -FORCEINLINE VOID InsertTailList( +/** + * The InsertTailList routine inserts an entry at the tail of a doubly linked list. + * + * \param ListHead A pointer to the list head. + * \param Entry A pointer to the list entry to be inserted. + * \sa https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/wdm/nf-wdm-inserttaillist + */ +FORCEINLINE +VOID +NTAPI_INLINE +InsertTailList( _Inout_ PLIST_ENTRY ListHead, - _Inout_ PLIST_ENTRY Entry + _Inout_ __drv_aliasesMem PLIST_ENTRY Entry ) { - PLIST_ENTRY Blink; + PLIST_ENTRY PrevEntry; + + PrevEntry = ListHead->Blink; + +#if !defined(NO_LIST_ENTRY_CHECKS) + if (PrevEntry->Flink != ListHead) + { + RtlFatalListEntryError((PVOID)PrevEntry, (PVOID)ListHead, (PVOID)PrevEntry->Flink); + } +#endif - Blink = ListHead->Blink; Entry->Flink = ListHead; - Entry->Blink = Blink; - Blink->Flink = Entry; + Entry->Blink = PrevEntry; + PrevEntry->Flink = Entry; ListHead->Blink = Entry; } -FORCEINLINE VOID InsertHeadList( +/** + * The InsertHeadList routine inserts an entry at the head of a doubly linked list. + * + * \param ListHead A pointer to the list head. + * \param Entry A pointer to the list entry to be inserted. + * \sa https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/wdm/nf-wdm-insertheadlist + */ +FORCEINLINE +VOID +NTAPI_INLINE +InsertHeadList( _Inout_ PLIST_ENTRY ListHead, - _Inout_ PLIST_ENTRY Entry + _Inout_ __drv_aliasesMem PLIST_ENTRY Entry ) { - PLIST_ENTRY Flink; + PLIST_ENTRY NextEntry; - Flink = ListHead->Flink; - Entry->Flink = Flink; + NextEntry = ListHead->Flink; + +#if !defined(NO_LIST_ENTRY_CHECKS) + RtlCheckListEntry(ListHead); + + if (NextEntry->Blink != ListHead) + { + RtlFatalListEntryError((PVOID)ListHead, (PVOID)NextEntry, (PVOID)NextEntry->Blink); + } +#endif + + Entry->Flink = NextEntry; Entry->Blink = ListHead; - Flink->Blink = Entry; + NextEntry->Blink = Entry; ListHead->Flink = Entry; } -FORCEINLINE VOID AppendTailList( +/** + * The AppendTailList routine appends a doubly linked list to the tail of another doubly linked list. + * + * \param ListHead A pointer to the head of the list to which to append. + * \param ListToAppend A pointer to the list to be appended. + */ +FORCEINLINE +VOID +NTAPI_INLINE +AppendTailList( _Inout_ PLIST_ENTRY ListHead, _Inout_ PLIST_ENTRY ListToAppend ) { PLIST_ENTRY ListEnd = ListHead->Blink; +#if !defined(NO_LIST_ENTRY_CHECKS) + RtlCheckListEntry(ListHead); + RtlCheckListEntry(ListToAppend); +#endif + ListHead->Blink->Flink = ListToAppend; ListHead->Blink = ListToAppend->Blink; ListToAppend->Blink->Flink = ListHead; ListToAppend->Blink = ListEnd; } -FORCEINLINE PSINGLE_LIST_ENTRY PopEntryList( +/** + * The PopEntryList routine removes the first entry from a singly linked list. + * + * \param ListHead A pointer to the list head. + * \return A pointer to the entry removed from the head of the list, or `NULL` if the list is empty. + * \sa https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/wdm/nf-wdm-popentrylist + */ +FORCEINLINE +PSINGLE_LIST_ENTRY +NTAPI_INLINE +PopEntryList( _Inout_ PSINGLE_LIST_ENTRY ListHead ) { @@ -158,16 +512,28 @@ FORCEINLINE PSINGLE_LIST_ENTRY PopEntryList( return FirstEntry; } -FORCEINLINE VOID PushEntryList( +/** + * The PushEntryList routine inserts an entry at the head of a singly linked list. + * + * \param ListHead A pointer to the list head. + * \param Entry A pointer to the list entry to be inserted. + * \sa https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/wdm/nf-wdm-pushentrylist + */ +FORCEINLINE +VOID +NTAPI_INLINE +PushEntryList( _Inout_ PSINGLE_LIST_ENTRY ListHead, - _Inout_ PSINGLE_LIST_ENTRY Entry + _Inout_ __drv_aliasesMem PSINGLE_LIST_ENTRY Entry ) { Entry->Next = ListHead->Next; ListHead->Next = Entry; } +// // AVL and splay trees +// typedef enum _TABLE_SEARCH_RESULT { @@ -184,27 +550,37 @@ typedef enum _RTL_GENERIC_COMPARE_RESULTS GenericEqual } RTL_GENERIC_COMPARE_RESULTS; -typedef RTL_GENERIC_COMPARE_RESULTS (NTAPI *PRTL_AVL_COMPARE_ROUTINE)( - _In_ struct _RTL_AVL_TABLE *Table, +typedef struct _RTL_AVL_TABLE RTL_AVL_TABLE, *PRTL_AVL_TABLE; + +typedef _Function_class_(RTL_AVL_COMPARE_ROUTINE) +RTL_GENERIC_COMPARE_RESULTS NTAPI RTL_AVL_COMPARE_ROUTINE( + _In_ PRTL_AVL_TABLE Table, _In_ PVOID FirstStruct, _In_ PVOID SecondStruct ); +typedef RTL_AVL_COMPARE_ROUTINE* PRTL_AVL_COMPARE_ROUTINE; -typedef PVOID (NTAPI *PRTL_AVL_ALLOCATE_ROUTINE)( - _In_ struct _RTL_AVL_TABLE *Table, +typedef _Function_class_(RTL_AVL_ALLOCATE_ROUTINE) +PVOID NTAPI RTL_AVL_ALLOCATE_ROUTINE( + _In_ PRTL_AVL_TABLE Table, _In_ CLONG ByteSize ); +typedef RTL_AVL_ALLOCATE_ROUTINE* PRTL_AVL_ALLOCATE_ROUTINE; -typedef VOID (NTAPI *PRTL_AVL_FREE_ROUTINE)( - _In_ struct _RTL_AVL_TABLE *Table, +typedef _Function_class_(RTL_AVL_FREE_ROUTINE) +VOID NTAPI RTL_AVL_FREE_ROUTINE( + _In_ PRTL_AVL_TABLE Table, _In_ _Post_invalid_ PVOID Buffer ); +typedef RTL_AVL_FREE_ROUTINE* PRTL_AVL_FREE_ROUTINE; -typedef NTSTATUS (NTAPI *PRTL_AVL_MATCH_FUNCTION)( - _In_ struct _RTL_AVL_TABLE *Table, +typedef _Function_class_(RTL_AVL_MATCH_FUNCTION) +NTSTATUS NTAPI RTL_AVL_MATCH_FUNCTION( + _In_ PRTL_AVL_TABLE Table, _In_ PVOID UserData, _In_ PVOID MatchData ); +typedef RTL_AVL_MATCH_FUNCTION* PRTL_AVL_MATCH_FUNCTION; typedef struct _RTL_BALANCED_LINKS { @@ -230,6 +606,16 @@ typedef struct _RTL_AVL_TABLE PVOID TableContext; } RTL_AVL_TABLE, *PRTL_AVL_TABLE; +/** + * The RtlInitializeGenericTableAvl routine initializes a generic AVL table. + * + * \param Table A pointer to the `RTL_AVL_TABLE` structure to be initialized. + * \param CompareRoutine A comparison routine to be used for comparing elements. + * \param AllocateRoutine An allocation routine to be used for allocating memory for the table. + * \param FreeRoutine A free routine to be used for freeing memory allocated for the table. + * \param TableContext A context to be passed to the comparison, allocation, and free routines. + * \sa https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/ntddk/nf-ntddk-rtlinitializegenerictableavl + */ NTSYSAPI VOID NTAPI @@ -241,6 +627,16 @@ RtlInitializeGenericTableAvl( _In_opt_ PVOID TableContext ); +/** + * The RtlInsertElementGenericTableAvl routine inserts an element into a generic AVL table. + * + * \param Table A pointer to the generic table. + * \param Buffer A pointer to the buffer containing the element to be inserted. + * \param BufferSize The size of the buffer. + * \param NewElement A pointer to a boolean that receives `TRUE` if the element was newly inserted, or `FALSE` if the element already existed. + * \return A pointer to the newly inserted or existing element. + * \sa https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/ntddk/nf-ntddk-rtlinsertelementgenerictableavl + */ NTSYSAPI PVOID NTAPI @@ -251,6 +647,18 @@ RtlInsertElementGenericTableAvl( _Out_opt_ PBOOLEAN NewElement ); +/** + * The RtlInsertElementGenericTableFullAvl routine inserts an element into a generic AVL table. + * + * \param Table A pointer to the generic table. + * \param Buffer A pointer to the buffer containing the element to be inserted. + * \param BufferSize The size of the buffer. + * \param NewElement A pointer to a boolean that receives `TRUE` if the element was newly inserted, or `FALSE` if the element already existed. + * \param NodeOrParent A pointer to the node or parent for the insertion. + * \param SearchResult The result of the search for the insertion point. + * \return A pointer to the newly inserted or existing element. + * \sa https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/ntddk/nf-ntddk-rtlinsertelementgenerictablefullavl + */ NTSYSAPI PVOID NTAPI @@ -263,6 +671,14 @@ RtlInsertElementGenericTableFullAvl( _In_ TABLE_SEARCH_RESULT SearchResult ); +/** + * The RtlDeleteElementGenericTableAvl routine deletes an element from a generic AVL table. + * + * \param Table A pointer to the generic table. + * \param Buffer A pointer to the buffer containing the element to be deleted. + * \return `TRUE` if the element was deleted, otherwise `FALSE`. + * \sa https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/ntddk/nf-ntddk-rtldeleteelementgenerictableavl + */ NTSYSAPI BOOLEAN NTAPI @@ -271,6 +687,14 @@ RtlDeleteElementGenericTableAvl( _In_ PVOID Buffer ); +/** + * The RtlLookupElementGenericTableAvl routine looks up an element in a generic AVL table. + * + * \param Table A pointer to the generic table. + * \param Buffer A pointer to the buffer containing the element to look up. + * \return A pointer to the found element, or `NULL` if the element was not found. + * \sa https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/ntddk/nf-ntddk-rtllookupelementgenerictableavl + */ _Check_return_ NTSYSAPI PVOID @@ -280,6 +704,16 @@ RtlLookupElementGenericTableAvl( _In_ PVOID Buffer ); +/** + * The RtlLookupElementGenericTableFullAvl routine looks up an element in a generic AVL table. + * + * \param Table A pointer to the generic table. + * \param Buffer A pointer to the buffer containing the element to look up. + * \param NodeOrParent A pointer that receives the node or parent of the element. + * \param SearchResult A pointer that receives the result of the search. + * \return A pointer to the found element, or `NULL` if the element was not found. + * \sa https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/ntddk/nf-ntddk-rtllookupelementgenerictablefullavl + */ NTSYSAPI PVOID NTAPI @@ -290,6 +724,14 @@ RtlLookupElementGenericTableFullAvl( _Out_ TABLE_SEARCH_RESULT *SearchResult ); +/** + * The RtlEnumerateGenericTableAvl routine enumerates the elements in a generic AVL table. + * + * \param Table A pointer to the generic table. + * \param Restart `TRUE` to restart the enumeration, `FALSE` to continue. + * \return A pointer to the next element in the table, or `NULL` if there are no more elements. + * \sa https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/ntddk/nf-ntddk-rtlenumerategenerictableavl + */ _Check_return_ NTSYSAPI PVOID @@ -299,6 +741,14 @@ RtlEnumerateGenericTableAvl( _In_ BOOLEAN Restart ); +/** + * The RtlEnumerateGenericTableWithoutSplayingAvl routine enumerates the elements in a generic AVL table without splaying. + * + * \param Table A pointer to the generic table. + * \param RestartKey A pointer to a restart key. + * \return A pointer to the next element in the table, or `NULL` if there are no more elements. + * \sa https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/ntddk/nf-ntddk-rtlenumerategenerictablewithoutsplayingavl + */ _Check_return_ NTSYSAPI PVOID @@ -308,6 +758,15 @@ RtlEnumerateGenericTableWithoutSplayingAvl( _Inout_ PVOID *RestartKey ); +/** + * The RtlLookupFirstMatchingElementGenericTableAvl routine looks up the first matching element in a generic AVL table. + * + * \param Table A pointer to the generic table. + * \param Buffer A pointer to the buffer containing the element to look up. + * \param RestartKey A pointer to a restart key. + * \return A pointer to the first matching element, or `NULL` if no matching element was found. + * \sa https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/ntddk/nf-ntddk-rtllookupfirstmatchingelementgenerictableavl + */ _Check_return_ NTSYSAPI PVOID @@ -318,6 +777,18 @@ RtlLookupFirstMatchingElementGenericTableAvl( _Out_ PVOID *RestartKey ); +/** + * The RtlEnumerateGenericTableLikeADirectory routine enumerates the elements in a generic AVL table like a directory. + * + * \param Table A pointer to the generic table. + * \param MatchFunction A match function to be used for comparing elements. + * \param MatchData A context to be passed to the match function. + * \param NextFlag A flag indicating whether to move to the next element. + * \param RestartKey A pointer to a restart key. + * \param DeleteCount A pointer to a counter for deleted elements. + * \param Buffer A pointer to the buffer containing the element to look up. + * \return A pointer to the next element in the table, or `NULL` if there are no more elements. + */ _Check_return_ NTSYSAPI PVOID @@ -332,6 +803,14 @@ RtlEnumerateGenericTableLikeADirectory( _In_ PVOID Buffer ); +/** + * The RtlGetElementGenericTableAvl routine gets an element from a generic AVL table by its index. + * + * \param Table A pointer to the generic table. + * \param I The index of the element to get. + * \return A pointer to the element, or `NULL` if the index is out of range. + * \sa https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/ntddk/nf-ntddk-rtlgetelementgenerictableavl + */ _Check_return_ NTSYSAPI PVOID @@ -341,6 +820,13 @@ RtlGetElementGenericTableAvl( _In_ ULONG I ); +/** + * The RtlNumberGenericTableElementsAvl routine gets the number of elements in a generic AVL table. + * + * \param Table A pointer to the generic table. + * \return The number of elements in the table. + * \sa https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/ntddk/nf-ntddk-rtlnumbergenerictableelementsavl + */ NTSYSAPI ULONG NTAPI @@ -348,6 +834,13 @@ RtlNumberGenericTableElementsAvl( _In_ PRTL_AVL_TABLE Table ); +/** + * The RtlIsGenericTableEmptyAvl routine determines whether a generic AVL table is empty. + * + * \param Table A pointer to the generic table. + * \return `TRUE` if the table is empty, otherwise `FALSE`. + * \sa https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/ntddk/nf-ntddk-rtlisgenerictableemptyavl + */ _Check_return_ NTSYSAPI BOOLEAN @@ -399,6 +892,13 @@ typedef struct _RTL_SPLAY_LINKS _SplayChild->Parent = _SplayParent; \ } +/** + * The RtlSplay routine performs a splay operation on a splay tree. + * + * \param Links A pointer to the splay links of the node to splay. + * \return A pointer to the new root of the splay tree. + * \sa https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/ntddk/nf-ntddk-rtlsplay + */ NTSYSAPI PRTL_SPLAY_LINKS NTAPI @@ -406,6 +906,13 @@ RtlSplay( _Inout_ PRTL_SPLAY_LINKS Links ); +/** + * The RtlDelete routine deletes a node from a splay tree. + * + * \param Links A pointer to the splay links of the node to delete. + * \return A pointer to the new root of the splay tree. + * \sa https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/ntddk/nf-ntddk-rtldelete + */ NTSYSAPI PRTL_SPLAY_LINKS NTAPI @@ -413,6 +920,12 @@ RtlDelete( _In_ PRTL_SPLAY_LINKS Links ); +/** + * The RtlDeleteNoSplay routine deletes a node from a splay tree without splaying. + * + * \param Links A pointer to the splay links of the node to delete. + * \param Root A pointer to the root of the splay tree. + */ NTSYSAPI VOID NTAPI @@ -421,6 +934,13 @@ RtlDeleteNoSplay( _Inout_ PRTL_SPLAY_LINKS *Root ); +/** + * The RtlSubtreeSuccessor routine finds the successor of a node in a splay tree. + * + * \param Links A pointer to the splay links of the node. + * \return A pointer to the splay links of the successor node. + * \sa https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/ntddk/nf-ntddk-rtlsubtreesuccessor + */ _Check_return_ NTSYSAPI PRTL_SPLAY_LINKS @@ -429,6 +949,13 @@ RtlSubtreeSuccessor( _In_ PRTL_SPLAY_LINKS Links ); +/** + * The RtlSubtreePredecessor routine finds the predecessor of a node in a splay tree. + * + * \param Links A pointer to the splay links of the node. + * \return A pointer to the splay links of the predecessor node. + * \sa https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/ntddk/nf-ntddk-rtlsubtreepredecessor + */ _Check_return_ NTSYSAPI PRTL_SPLAY_LINKS @@ -437,6 +964,13 @@ RtlSubtreePredecessor( _In_ PRTL_SPLAY_LINKS Links ); +/** + * The RtlRealSuccessor routine finds the real successor of a node in a splay tree. + * + * \param Links A pointer to the splay links of the node. + * \return A pointer to the splay links of the real successor node. + * \sa https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/ntddk/nf-ntddk-rtlrealsuccessor + */ _Check_return_ NTSYSAPI PRTL_SPLAY_LINKS @@ -445,6 +979,13 @@ RtlRealSuccessor( _In_ PRTL_SPLAY_LINKS Links ); +/** + * The RtlRealPredecessor routine finds the real predecessor of a node in a splay tree. + * + * \param Links A pointer to the splay links of the node. + * \return A pointer to the splay links of the real predecessor node. + * \sa https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/ntddk/nf-ntddk-rtlrealpredecessor + */ _Check_return_ NTSYSAPI PRTL_SPLAY_LINKS @@ -453,23 +994,29 @@ RtlRealPredecessor( _In_ PRTL_SPLAY_LINKS Links ); -struct _RTL_GENERIC_TABLE; +typedef struct _RTL_GENERIC_TABLE RTL_GENERIC_TABLE, *PRTL_GENERIC_TABLE; -typedef RTL_GENERIC_COMPARE_RESULTS (NTAPI *PRTL_GENERIC_COMPARE_ROUTINE)( - _In_ struct _RTL_GENERIC_TABLE *Table, +typedef _Function_class_(RTL_GENERIC_COMPARE_ROUTINE) +RTL_GENERIC_COMPARE_RESULTS NTAPI RTL_GENERIC_COMPARE_ROUTINE( + _In_ PRTL_GENERIC_TABLE Table, _In_ PVOID FirstStruct, _In_ PVOID SecondStruct ); +typedef RTL_GENERIC_COMPARE_ROUTINE* PRTL_GENERIC_COMPARE_ROUTINE; -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, +typedef _Function_class_(RTL_GENERIC_FREE_ROUTINE) +VOID NTAPI RTL_GENERIC_FREE_ROUTINE( + _In_ PRTL_GENERIC_TABLE Table, _In_ _Post_invalid_ PVOID Buffer ); +typedef RTL_GENERIC_FREE_ROUTINE* PRTL_GENERIC_FREE_ROUTINE; + +typedef _Function_class_(RTL_GENERIC_ALLOCATE_ROUTINE) +PVOID NTAPI RTL_GENERIC_ALLOCATE_ROUTINE( + _In_ PRTL_GENERIC_TABLE Table, + _In_ CLONG ByteSize + ); +typedef RTL_GENERIC_ALLOCATE_ROUTINE* PRTL_GENERIC_ALLOCATE_ROUTINE; typedef struct _RTL_GENERIC_TABLE { @@ -484,6 +1031,16 @@ typedef struct _RTL_GENERIC_TABLE PVOID TableContext; } RTL_GENERIC_TABLE, *PRTL_GENERIC_TABLE; +/** + * The RtlInitializeGenericTable routine initializes a generic table. + * + * \param Table A pointer to the `RTL_GENERIC_TABLE` structure to be initialized. + * \param CompareRoutine A comparison routine to be used for comparing elements. + * \param AllocateRoutine An allocation routine to be used for allocating memory for the table. + * \param FreeRoutine A free routine to be used for freeing memory allocated for the table. + * \param TableContext A context to be passed to the comparison, allocation, and free routines. + * \sa https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/ntddk/nf-ntddk-rtlinitializegenerictable + */ NTSYSAPI VOID NTAPI @@ -495,6 +1052,16 @@ RtlInitializeGenericTable( _In_opt_ PVOID TableContext ); +/** + * The RtlInsertElementGenericTable routine inserts an element into a generic table. + * + * \param Table A pointer to the generic table. + * \param Buffer A pointer to the buffer containing the element to be inserted. + * \param BufferSize The size of the buffer. + * \param NewElement A pointer to a boolean that receives `TRUE` if the element was newly inserted, or `FALSE` if the element already existed. + * \return A pointer to the newly inserted or existing element. + * \sa https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/ntddk/nf-ntddk-rtlinsertelementgenerictable + */ NTSYSAPI PVOID NTAPI @@ -505,6 +1072,18 @@ RtlInsertElementGenericTable( _Out_opt_ PBOOLEAN NewElement ); +/** + * The RtlInsertElementGenericTableFull routine inserts an element into a generic table. + * + * \param Table A pointer to the generic table. + * \param Buffer A pointer to the buffer containing the element to be inserted. + * \param BufferSize The size of the buffer. + * \param NewElement A pointer to a boolean that receives `TRUE` if the element was newly inserted, or `FALSE` if the element already existed. + * \param NodeOrParent A pointer to the node or parent for the insertion. + * \param SearchResult The result of the search for the insertion point. + * \return A pointer to the newly inserted or existing element. + * \sa https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/ntddk/nf-ntddk-rtlinsertelementgenerictablefull + */ NTSYSAPI PVOID NTAPI @@ -586,16 +1165,21 @@ RtlIsGenericTableEmpty( _In_ PRTL_GENERIC_TABLE Table ); +// // RB trees +// typedef struct _RTL_RB_TREE { PRTL_BALANCED_NODE Root; - PRTL_BALANCED_NODE Min; + union + { + UCHAR Encoded : 1; + PRTL_BALANCED_NODE Min; + }; } RTL_RB_TREE, *PRTL_RB_TREE; #if (PHNT_VERSION >= PHNT_WINDOWS_8) - // rev NTSYSAPI BOOLEAN @@ -674,7 +1258,11 @@ typedef struct _RTL_DYNAMIC_HASH_TABLE_CONTEXT typedef struct _RTL_DYNAMIC_HASH_TABLE_ENUMERATOR { - RTL_DYNAMIC_HASH_TABLE_ENTRY HashEntry; + union + { + RTL_DYNAMIC_HASH_TABLE_ENTRY HashEntry; + PLIST_ENTRY CurEntry; + }; PLIST_ENTRY ChainHead; ULONG BucketIndex; } RTL_DYNAMIC_HASH_TABLE_ENUMERATOR, *PRTL_DYNAMIC_HASH_TABLE_ENUMERATOR; @@ -699,10 +1287,9 @@ typedef struct _RTL_DYNAMIC_HASH_TABLE PVOID Directory; } RTL_DYNAMIC_HASH_TABLE, *PRTL_DYNAMIC_HASH_TABLE; -#if (PHNT_VERSION >= PHNT_WINDOWS_7) - FORCEINLINE VOID +NTAPI_INLINE RtlInitHashTableContext( _Inout_ PRTL_DYNAMIC_HASH_TABLE_CONTEXT Context ) @@ -713,6 +1300,7 @@ RtlInitHashTableContext( FORCEINLINE VOID +NTAPI_INLINE RtlInitHashTableContextFromEnumerator( _Inout_ PRTL_DYNAMIC_HASH_TABLE_CONTEXT Context, _In_ PRTL_DYNAMIC_HASH_TABLE_ENUMERATOR Enumerator @@ -724,6 +1312,7 @@ RtlInitHashTableContextFromEnumerator( FORCEINLINE VOID +NTAPI_INLINE RtlReleaseHashTableContext( _Inout_ PRTL_DYNAMIC_HASH_TABLE_CONTEXT Context ) @@ -734,6 +1323,7 @@ RtlReleaseHashTableContext( FORCEINLINE ULONG +NTAPI_INLINE RtlTotalBucketsHashTable( _In_ PRTL_DYNAMIC_HASH_TABLE HashTable ) @@ -743,6 +1333,7 @@ RtlTotalBucketsHashTable( FORCEINLINE ULONG +NTAPI_INLINE RtlNonEmptyBucketsHashTable( _In_ PRTL_DYNAMIC_HASH_TABLE HashTable ) @@ -752,6 +1343,7 @@ RtlNonEmptyBucketsHashTable( FORCEINLINE ULONG +NTAPI_INLINE RtlEmptyBucketsHashTable( _In_ PRTL_DYNAMIC_HASH_TABLE HashTable ) @@ -761,6 +1353,7 @@ RtlEmptyBucketsHashTable( FORCEINLINE ULONG +NTAPI_INLINE RtlTotalEntriesHashTable( _In_ PRTL_DYNAMIC_HASH_TABLE HashTable ) @@ -770,6 +1363,7 @@ RtlTotalEntriesHashTable( FORCEINLINE ULONG +NTAPI_INLINE RtlActiveEnumeratorsHashTable( _In_ PRTL_DYNAMIC_HASH_TABLE HashTable ) @@ -908,8 +1502,6 @@ RtlContractHashTable( _In_ PRTL_DYNAMIC_HASH_TABLE HashTable ); -#endif // PHNT_VERSION >= PHNT_WINDOWS_7 - #if (PHNT_VERSION >= PHNT_WINDOWS_10) NTSYSAPI @@ -981,6 +1573,12 @@ RtlEndStrongEnumerationHashTable( // } RTL_CRITICAL_SECTION, *PRTL_CRITICAL_SECTION; // #pragma pack(pop) +/** + * The RtlInitializeCriticalSection routine initializes a critical section object. + * + * \param CriticalSection A pointer to the critical section object. + * \sa https://learn.microsoft.com/en-us/windows/win32/api/synchapi/nf-synchapi-initializecriticalsection + */ NTSYSAPI NTSTATUS NTAPI @@ -988,14 +1586,29 @@ RtlInitializeCriticalSection( _Out_ PRTL_CRITICAL_SECTION CriticalSection ); +/** + * The RtlInitializeCriticalSectionAndSpinCount routine initializes a critical section object and sets the spin count for the critical section. + * + * \param CriticalSection A pointer to the critical section object. + * \param SpinCount The spin count for the critical section object. On single-processor systems, the spin count is ignored. + * \sa https://learn.microsoft.com/en-us/windows/win32/api/synchapi/nf-synchapi-initializecriticalsectionandspincount + */ NTSYSAPI NTSTATUS NTAPI RtlInitializeCriticalSectionAndSpinCount( - _Inout_ PRTL_CRITICAL_SECTION CriticalSection, + _Out_ PRTL_CRITICAL_SECTION CriticalSection, _In_ ULONG SpinCount ); +/** + * The RtlInitializeCriticalSectionEx routine initializes a critical section object and sets the spin count for the critical section with flags. + * + * \param CriticalSection A pointer to the critical section object. + * \param SpinCount The spin count for the critical section object. On single-processor systems, the spin count is ignored. + * \param Flags This parameter can be 0 or the CRITICAL_SECTION_NO_DEBUG_INFO flag. + * \sa https://learn.microsoft.com/en-us/windows/win32/api/synchapi/nf-synchapi-initializecriticalsectionex + */ NTSYSAPI NTSTATUS NTAPI @@ -1065,15 +1678,13 @@ RtlSetCriticalSectionSpinCount( _In_ ULONG SpinCount ); -#if (PHNT_VERSION >= PHNT_WINDOWS_VISTA) -// private NTSYSAPI HANDLE NTAPI RtlQueryCriticalSectionOwner( - _In_ HANDLE EventHandle + _In_ HANDLE EventHandle, + _In_ BOOLEAN ExactMatchOwnerAddress ); -#endif // PHNT_VERSION >= PHNT_WINDOWS_VISTA NTSYSAPI VOID @@ -1088,8 +1699,8 @@ RtlCheckForOrphanedCriticalSections( * This function allows the system to create critical section events early in the process * initialization. It is typically used to ensure that critical sections are properly * initialized and can be used safely during the early stages of process startup. - * @remarks This function sets the FLG_CRITSEC_EVENT_CREATION flag in the PEB flags field. - * @return A pointer to the Process Environment Block (PEB). + * \remarks This function sets the FLG_CRITSEC_EVENT_CREATION flag in the PEB flags field. + * \return A pointer to the Process Environment Block (PEB). */ NTSYSAPI PPEB @@ -1098,7 +1709,9 @@ RtlEnableEarlyCriticalSectionEventCreation( VOID ); +// // Resources +// typedef struct _RTL_RESOURCE { @@ -1177,11 +1790,21 @@ RtlDumpResource( _Inout_ PRTL_RESOURCE Resource ); +// // Slim reader-writer locks, condition variables, and barriers +// -#if (PHNT_VERSION >= PHNT_WINDOWS_VISTA) +#ifndef RTL_SRWLOCK_INIT +#define RTL_SRWLOCK_INIT {0} +#endif // winbase:InitializeSRWLock +/** + * The RtlInitializeSRWLock routine initializes a slim reader/writer (SRW) lock. + * + * \param SRWLock A pointer to the SRW lock. + * \sa https://learn.microsoft.com/en-us/windows/win32/api/synchapi/nf-synchapi-initializesrwlock + */ NTSYSAPI VOID NTAPI @@ -1243,9 +1866,6 @@ RtlTryAcquireSRWLockShared( _Inout_ PRTL_SRWLOCK SRWLock ); -#endif // PHNT_VERSION >= PHNT_WINDOWS_VISTA - -#if (PHNT_VERSION >= PHNT_WINDOWS_7) // rev NTSYSAPI VOID @@ -1253,7 +1873,6 @@ NTAPI RtlAcquireReleaseSRWLockExclusive( _Inout_ PRTL_SRWLOCK SRWLock ); -#endif // PHNT_VERSION >= PHNT_WINDOWS_7 #if (PHNT_VERSION >= PHNT_WINDOWS_10) // rev @@ -1266,56 +1885,148 @@ RtlConvertSRWLockExclusiveToShared( #endif // PHNT_VERSION >= PHNT_WINDOWS_10 #if (PHNT_VERSION >= PHNT_WINDOWS_11) + // -// Read-Copy Update. +// Read-Copy-Update (RCU). // // RCU synchronization allows concurrent access to shared data structures, // such as linked lists, trees, or hash tables, without using traditional locking methods // in scenarios where read operations are frequent and need to be fast. +// It is particularly useful in multi-threaded environments where multiple threads +// may read from the same data structure while one or more threads may modify it. // @remarks RCU synchronization is not for general-purpose synchronization. // Teb->Rcu is used to store the RCU state. +#if defined(PHNT_NATIVE_RCU) +// rev +typedef struct _RTL_RCU_SEGMENT +{ + ULONG Count; + ULONG Reserved; // padding/unused + PVOID Slots[ANYSIZE_ARRAY]; + // + // Interpretation (x64): + // Slots[0 .. Count-1] = RTL_RCU_THREAD_ENTRY* (or NULL) + // Slots[Count] = RTL_RCU_SEGMENT* link to next segment (or NULL) + // +} RTL_RCU_SEGMENT, *PRTL_RCU_SEGMENT; + +// Helper for the address of link slot (the "next segment pointer") +#define RTL_RCU_SEGMENT_NEXT_PTR(S) ((PRTL_RCU_SEGMENT*)&((S)->Slots[(S)->Count])) + +// rev +typedef struct _RTL_RCU_THREAD_ENTRY +{ + volatile ULONGLONG ReadDepth; + ULONG ThreadCookie; // compared with TEB cached cookie + ULONG ThreadIdLike; // compared with TEB cached id + volatile ULONGLONG SeenEpoch; // WaitOnAddress/WakeAddressAll target + struct _RTL_RCU_THREAD_ENTRY* Next; // linked via State->ThreadList +} RTL_RCU_THREAD_ENTRY, *PRTL_RCU_THREAD_ENTRY; + +C_ASSERT(sizeof(RTL_RCU_THREAD_ENTRY) == 0x20); +C_ASSERT(FIELD_OFFSET(RTL_RCU_THREAD_ENTRY, SeenEpoch) == 0x10); + +//typedef struct _RTL_RCU_THREAD_ENTRY RTL_RCU_THREAD_ENTRY, *PRTL_RCU_THREAD_ENTRY; +//typedef struct _RTL_RCU_SEGMENT RTL_RCU_SEGMENT, *PRTL_RCU_SEGMENT; + +// rev +typedef struct _RTL_RCU_STATE +{ + // + // Global list links (inserted by RtlRcuAllocate under a global SRW lock). + // + struct _RTL_RCU_STATE *GlobalNext; + struct _RTL_RCU_STATE *GlobalPrev; + + // + // Global epoch/state. + // + volatile ULONGLONG Epoch; + + // + // Segmented array root used by RtlpRcuCurrentThreadData() + // to map "thread-id-like" (ebx) -> RTL_RCU_THREAD_ENTRY*. + // + PRTL_RCU_SEGMENT SegmentRoot; + + // + // Singly-linked list of all per-thread entries for this state. + // synchronize walks this list and waits on each entry->SeenEpoch. + // + PRTL_RCU_THREAD_ENTRY ThreadList; + + // + // Small cache indexed by (ebx % 10) (the 0xCCCCCCCD multiply trick). + // + PRTL_RCU_THREAD_ENTRY Cache[10]; + + // + // Slow-path SRW lock used when RtlpRcuCurrentThreadData() returns NULL. + // - ReadLock uses AcquireSRWLockShared(&state+0x78) + // - Synchronize uses Acquire/Release Exclusive on &state+0x78 (via helper) + // + RTL_SRWLOCK SlowPathLock; + + // + // Stored from RtlRcuAllocate(ecx) + // + ULONG TagOrFlags; + + ULONG Padding; // (to make sizeof == 0x88 on x64) +} RTL_RCU_STATE, *PRTL_RCU_STATE; + +// Sanity checks (x64) +C_ASSERT(sizeof(RTL_RCU_STATE) == 0x88); + +typedef struct _RTL_RCU_COOKIE +{ + ULONG_PTR ThreadEntryOrNull; // NULL => slow-path SRW shared lock was used +} RTL_RCU_COOKIE, *PRTL_RCU_COOKIE; +#else +typedef struct _RTL_RCU_STATE RTL_RCU_STATE, *PRTL_RCU_STATE; +typedef ULONG_PTR RTL_RCU_COOKIE, *PRTL_RCU_COOKIE; +#endif // #if defined(PHNT_NATIVE_RCU) + NTSYSAPI -PVOID +PRTL_RCU_STATE NTAPI RtlRcuAllocate( - _In_ SIZE_T Size + _In_ ULONG Flags ); NTSYSAPI LOGICAL NTAPI RtlRcuFree( - _In_ PULONG Rcu + _In_ PRTL_RCU_STATE State ); NTSYSAPI VOID NTAPI RtlRcuReadLock( - _Inout_ PRTL_SRWLOCK SRWLock, - _Out_ PULONG Rcu + _Inout_ PRTL_RCU_STATE State, + _Out_ PRTL_RCU_COOKIE Cookie ); NTSYSAPI VOID NTAPI RtlRcuReadUnlock( - _Inout_ PRTL_SRWLOCK SRWLock, - _Inout_ PULONG* Rcu + _Inout_ PRTL_RCU_STATE State, + _Inout_ PRTL_RCU_COOKIE Cookie ); NTSYSAPI LONG NTAPI RtlRcuSynchronize( - _Inout_ PRTL_SRWLOCK SRWLock + _Inout_ PRTL_RCU_STATE State ); #endif // PHNT_VERSION >= PHNT_WINDOWS_11 -#if (PHNT_VERSION >= PHNT_WINDOWS_VISTA) - #define RTL_CONDITION_VARIABLE_INIT {0} #define RTL_CONDITION_VARIABLE_LOCKMODE_SHARED 0x1 @@ -1364,8 +2075,6 @@ RtlWakeAllConditionVariable( _Inout_ PRTL_CONDITION_VARIABLE ConditionVariable ); -#endif // PHNT_VERSION >= PHNT_WINDOWS_VISTA - // 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 @@ -1374,8 +2083,6 @@ RtlWakeAllConditionVariable( // begin_private -#if (PHNT_VERSION >= PHNT_WINDOWS_VISTA) - NTSYSAPI NTSTATUS NTAPI @@ -1408,8 +2115,6 @@ RtlBarrierForDelete( _In_ ULONG Flags ); -#endif // PHNT_VERSION >= PHNT_WINDOWS_VISTA - // end_private // @@ -1420,6 +2125,17 @@ RtlBarrierForDelete( #if (PHNT_VERSION >= PHNT_WINDOWS_8) +/** + * The RtlWaitOnAddress routine waits for the value at the specified address to change. + * + * \param Address The address on which to wait. + * \param CompareAddress A pointer to the location of the previously observed value at Address. + * \param AddressSize The size of the value, in bytes. This parameter can be 1, 2, 4, or 8. + * \param Timeout The number of milliseconds to wait before the operation times out. If this parameter is NULL (INFINITE), the thread waits indefinitely. + * \remarks WaitOnAddress is guaranteed to return when the address is signaled, but it is also allowed to return for other reasons. + * For this reason, the caller should compare the new value with the original undesired value to confirm that the value has actually changed. + * \sa https://learn.microsoft.com/en-us/windows/win32/api/synchapi/nf-synchapi-waitonaddress + */ NTSYSAPI NTSTATUS NTAPI @@ -1430,6 +2146,12 @@ RtlWaitOnAddress( _In_opt_ PLARGE_INTEGER Timeout ); +/** + * The RtlWakeAddressAll routine wakes all threads that are waiting for the value of an address to change. + * + * \param Address The address to signal. If any threads have previously called RtlWaitOnAddress for this address, the system wakes all of the waiting threads. + * \sa https://learn.microsoft.com/en-us/windows/win32/api/synchapi/nf-synchapi-wakebyaddressall + */ NTSYSAPI VOID NTAPI @@ -1437,6 +2159,12 @@ RtlWakeAddressAll( _In_ PVOID Address ); +/** + * The RtlWakeAddressAllNoFence routine wakes all threads that are waiting for the value of an address to change. + * + * \param Address The address to signal. If any threads have previously called RtlWaitOnAddress for this address, the system wakes all of the waiting threads. + * \sa https://learn.microsoft.com/en-us/windows/win32/api/synchapi/nf-synchapi-wakebyaddressall + */ NTSYSAPI VOID NTAPI @@ -1444,6 +2172,12 @@ RtlWakeAddressAllNoFence( _In_ PVOID Address ); +/** + * The RtlWakeAddressSingle routine wakes one thread that is waiting for the value of an address to change. + * + * \param Address The address to signal. + * \sa https://learn.microsoft.com/en-us/windows/win32/api/synchapi/nf-synchapi-wakebyaddresssingle + */ NTSYSAPI VOID NTAPI @@ -1451,6 +2185,12 @@ RtlWakeAddressSingle( _In_ PVOID Address ); +/** + * The RtlWakeAddressSingleNoFence routine wakes one thread that is waiting for the value of an address to change. + * + * \param Address The address to signal. + * \sa https://learn.microsoft.com/en-us/windows/win32/api/synchapi/nf-synchapi-wakebyaddresssingle + */ NTSYSAPI VOID NTAPI @@ -1462,14 +2202,19 @@ RtlWakeAddressSingleNoFence( // end_rev +// // Strings +// +_At_(AnsiString->Buffer, _Post_equal_to_(Buffer)) +_At_(AnsiString->Length, _Post_equal_to_(0)) +_At_(AnsiString->MaximumLength, _Post_equal_to_(MaximumLength)) FORCEINLINE VOID -NTAPI +NTAPI_INLINE RtlInitEmptyAnsiString( _Out_ PANSI_STRING AnsiString, - _Pre_maybenull_ _Pre_readable_size_(MaximumLength) PCHAR Buffer, + _Pre_maybenull_ _Pre_readable_size_(MaximumLength) __drv_aliasesMem PCHAR Buffer, _In_ USHORT MaximumLength ) { @@ -1479,7 +2224,10 @@ RtlInitEmptyAnsiString( } #ifndef PHNT_NO_INLINE_INIT_STRING -FORCEINLINE VOID RtlInitString( +FORCEINLINE +VOID +NTAPI_INLINE +RtlInitString( _Out_ PSTRING DestinationString, _In_opt_z_ PCSTR SourceString ) @@ -1507,12 +2255,15 @@ NTSTATUS NTAPI RtlInitStringEx( _Out_ PSTRING DestinationString, - _In_opt_z_ PCSZ SourceString + _In_opt_z_ __drv_aliasesMem PCSZ SourceString ); #endif // PHNT_VERSION >= PHNT_WINDOWS_10 #ifndef PHNT_NO_INLINE_INIT_STRING -FORCEINLINE VOID RtlInitAnsiString( +FORCEINLINE +VOID +NTAPI_INLINE +RtlInitAnsiString( _Out_ PANSI_STRING DestinationString, _In_opt_z_ PCSTR SourceString ) @@ -1534,15 +2285,13 @@ RtlInitAnsiString( ); #endif // PHNT_NO_INLINE_INIT_STRING -#if (PHNT_VERSION >= PHNT_WINDOWS_SERVER_2003) NTSYSAPI NTSTATUS NTAPI RtlInitAnsiStringEx( _Out_ PANSI_STRING DestinationString, - _In_opt_z_ PCSZ SourceString + _In_opt_z_ __drv_aliasesMem PCSZ SourceString ); -#endif // PHNT_VERSION >= PHNT_WINDOWS_SERVER_2003 NTSYSAPI VOID @@ -1565,7 +2314,7 @@ NTSTATUS NTAPI RtlInitUTF8StringEx( _Out_ PUTF8_STRING DestinationString, - _In_opt_z_ PCSZ SourceString + _In_opt_z_ __drv_aliasesMem PCSZ SourceString ); NTSYSAPI @@ -1654,19 +2403,23 @@ RtlUpperString( FORCEINLINE BOOLEAN +NTAPI_INLINE RtlIsNullOrEmptyUnicodeString( - _In_opt_ PUNICODE_STRING String + _In_opt_ PCUNICODE_STRING String ) { return !String || String->Length == 0; } +_At_(DestinationString->Buffer, _Post_equal_to_(Buffer)) +_At_(DestinationString->Length, _Post_equal_to_(0)) +_At_(DestinationString->MaximumLength, _Post_equal_to_(MaximumLength)) FORCEINLINE VOID -NTAPI +NTAPI_INLINE RtlInitEmptyUnicodeString( _Out_ PUNICODE_STRING DestinationString, - _Writable_bytes_(MaximumLength) _When_(MaximumLength != 0, _Notnull_) PWCHAR Buffer, + _Writable_bytes_(MaximumLength) _When_(MaximumLength != 0, _Notnull_) __drv_aliasesMem PWCHAR Buffer, _In_ USHORT MaximumLength ) { @@ -1676,7 +2429,10 @@ RtlInitEmptyUnicodeString( } #ifndef PHNT_NO_INLINE_INIT_STRING -FORCEINLINE VOID RtlInitUnicodeString( +FORCEINLINE +VOID +NTAPI_INLINE +RtlInitUnicodeString( _Out_ PUNICODE_STRING DestinationString, _In_opt_z_ PCWSTR SourceString ) @@ -1699,7 +2455,10 @@ RtlInitUnicodeString( #endif // PHNT_NO_INLINE_INIT_STRING #ifndef PHNT_NO_INLINE_INIT_STRING -FORCEINLINE NTSTATUS RtlInitUnicodeStringEx( +FORCEINLINE +NTSTATUS +NTAPI_INLINE +RtlInitUnicodeStringEx( _Out_ PUNICODE_STRING DestinationString, _In_opt_z_ PCWSTR SourceString ) @@ -1733,6 +2492,14 @@ RtlInitUnicodeStringEx( ); #endif // PHNT_NO_INLINE_INIT_STRING +/** + * The RtlCreateUnicodeString routine creates a new counted Unicode string. + * + * \param DestinationString Pointer to the newly allocated and initialized Unicode string. + * \param SourceString Pointer to a null-terminated Unicode string with which to initialize the new string. + * \return TRUE if the Unicode string was successfully created, FALSE otherwise. + * \sa https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/ntifs/nf-ntifs-rtlcreateunicodestring + */ _Success_(return != 0) _Must_inspect_result_ NTSYSAPI @@ -1751,6 +2518,12 @@ RtlCreateUnicodeStringFromAsciiz( _In_z_ PCSTR SourceString ); +/** + * The RtlFreeUnicodeString routine releases storage that was allocated by RtlAnsiStringToUnicodeString or RtlUpcaseUnicodeString. + * + * \param UnicodeString A pointer to the string buffer. + * \sa https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/wdm/nf-wdm-rtlfreeunicodestring + */ NTSYSAPI VOID NTAPI @@ -1766,18 +2539,32 @@ NTSTATUS NTAPI RtlDuplicateUnicodeString( _In_ ULONG Flags, - _In_ PUNICODE_STRING StringIn, + _In_ PCUNICODE_STRING StringIn, _Out_ PUNICODE_STRING StringOut ); +/** + * The RtlCopyUnicodeString routine copies a source string to a destination string. + * + * \param[in] DestinationString A pointer to the destination string buffer. + * \param[in] SourceString A pointer to the source string buffer. + * \sa https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/wdm/nf-wdm-rtlcopyunicodestring + */ NTSYSAPI VOID NTAPI RtlCopyUnicodeString( - _In_ PUNICODE_STRING DestinationString, + _In_ PCUNICODE_STRING DestinationString, _In_opt_ PCUNICODE_STRING SourceString ); +/** + * The RtlUpcaseUnicodeChar routine converts the specified Unicode character to uppercase. + * + * \param[in] SourceCharacter Specifies the character to convert. + * \return The uppercase version of the specified Unicode character. + * \sa https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/wdm/nf-wdm-rtlupcaseunicodechar + */ NTSYSAPI WCHAR NTAPI @@ -1785,6 +2572,13 @@ RtlUpcaseUnicodeChar( _In_ WCHAR SourceCharacter ); +/** + * The RtlDowncaseUnicodeChar routine converts the specified Unicode character to lowercase. + * + * \param[in] SourceCharacter Specifies the character to convert. + * \return The lowercase version of the specified Unicode character. + * \sa https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/wdm/nf-wdm-rtldowncaseunicodechar + */ NTSYSAPI WCHAR NTAPI @@ -1792,17 +2586,35 @@ RtlDowncaseUnicodeChar( _In_ WCHAR SourceCharacter ); +/** + * The RtlCompareUnicodeString routine compares two Unicode strings. + * + * \param[in] String1 Pointer to the first string. + * \param[in] String2 Pointer to the second string. + * \param[in] CaseInSensitive If TRUE, case should be ignored when doing the comparison. + * \return A signed value that gives the results of the comparison. + * \sa https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/wdm/nf-wdm-rtlcompareunicodestring + */ _Must_inspect_result_ NTSYSAPI LONG NTAPI RtlCompareUnicodeString( - _In_ PUNICODE_STRING String1, - _In_ PUNICODE_STRING String2, + _In_ PCUNICODE_STRING String1, + _In_ PCUNICODE_STRING String2, _In_ BOOLEAN CaseInSensitive ); -#if (PHNT_VERSION >= PHNT_WINDOWS_VISTA) +/** + * The RtlCompareUnicodeStrings routine compares two Unicode strings. + * + * \param[in] String1 Pointer to the first string. + * \param[in] String1Length The length, in bytes, of the first string. + * \param[in] String2 Pointer to the second string. + * \param[in] String2Length The length, in bytes, of the second string. + * \param[in] CaseInSensitive If TRUE, case should be ignored when doing the comparison. + * \return A signed value that gives the results of the comparison. + */ _Must_inspect_result_ NTSYSAPI LONG @@ -1814,15 +2626,23 @@ RtlCompareUnicodeStrings( _In_ SIZE_T String2Length, _In_ BOOLEAN CaseInSensitive ); -#endif // PHNT_VERSION >= PHNT_WINDOWS_VISTA +/** + * The RtlEqualUnicodeString routine compares two Unicode strings to determine whether they are equal. + * + * \param[in] String1 Pointer to the first Unicode string. + * \param[in] String2 Pointer to the second Unicode string. + * \param[in] CaseInSensitive If TRUE, case should be ignored when doing the comparison. + * \return TRUE if the two Unicode strings are equal; otherwise, it returns FALSE. + * \sa https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/wdm/nf-wdm-rtlequalunicodestring + */ _Must_inspect_result_ NTSYSAPI BOOLEAN NTAPI RtlEqualUnicodeString( - _In_ PUNICODE_STRING String1, - _In_ PUNICODE_STRING String2, + _In_ PCUNICODE_STRING String1, + _In_ PCUNICODE_STRING String2, _In_ BOOLEAN CaseInSensitive ); @@ -1830,11 +2650,21 @@ RtlEqualUnicodeString( #define HASH_STRING_ALGORITHM_X65599 1 #define HASH_STRING_ALGORITHM_INVALID 0xffffffff +/** + * The RtlHashUnicodeString routine creates a hash value from a given Unicode string and hash algorithm. + * + * \param[in] String A pointer to a UNICODE_STRING structure that contains the Unicode string to be converted to a hash value. + * \param[in] CaseInSensitive Specifies whether to treat the Unicode string as case sensitive when computing the hash value. If CaseInSensitive is TRUE, a lowercase and uppercase string hash to the same value. + * \param[in] HashAlgorithm The hash algorithm to use. + * \param[out] HashValue A pointer to a ULONG variable that receives the hash value. + * \return NTSTATUS Successful or errant status. + * \sa https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/wdm/nf-wdm-rtlhashunicodestring + */ NTSYSAPI NTSTATUS NTAPI RtlHashUnicodeString( - _In_ PUNICODE_STRING String, + _In_ PCUNICODE_STRING String, _In_ BOOLEAN CaseInSensitive, _In_ ULONG HashAlgorithm, _Out_ PULONG HashValue @@ -1845,16 +2675,25 @@ NTSTATUS NTAPI RtlValidateUnicodeString( _In_ ULONG Flags, - _In_ PUNICODE_STRING String + _In_ PCUNICODE_STRING String ); +/** + * The RtlPrefixUnicodeString routine compares two Unicode strings to determine whether one string is a prefix of the other. + * + * \param[in] String1 Pointer to the first string, which might be a prefix of the buffered Unicode string at String2. + * \param[in] String2 Pointer to the second string. + * \param[in] CaseInSensitive TRUE, case should be ignored when doing the comparison. + * \return TRUE if String1 is a prefix of String2. + * \sa https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/ntddk/nf-ntddk-rtlprefixunicodestring + */ _Must_inspect_result_ NTSYSAPI BOOLEAN NTAPI RtlPrefixUnicodeString( - _In_ PUNICODE_STRING String1, - _In_ PUNICODE_STRING String2, + _In_ PCUNICODE_STRING String1, + _In_ PCUNICODE_STRING String2, _In_ BOOLEAN CaseInSensitive ); @@ -1864,20 +2703,43 @@ NTSYSAPI BOOLEAN NTAPI RtlSuffixUnicodeString( - _In_ PUNICODE_STRING String1, - _In_ PUNICODE_STRING String2, + _In_ PCUNICODE_STRING String1, + _In_ PCUNICODE_STRING String2, _In_ BOOLEAN CaseInSensitive ); #endif // PHNT_MODE == PHNT_MODE_KERNEL && PHNT_VERSION >= PHNT_WINDOWS_10 +#pragma prefast(push) +#pragma prefast(disable : 6101, "Out parameter is not written fully or at all.") +FORCEINLINE +VOID +NTAPI_INLINE +RtlSanitizeUnicodeStringPadding( + _Out_ PUNICODE_STRING String + ) +{ +#if defined(_WIN64) + ULONG PaddingSize; + ULONG PaddingStart; + + PaddingStart = FIELD_OFFSET(UNICODE_STRING, MaximumLength) + sizeof(String->MaximumLength); + PaddingSize = FIELD_OFFSET(UNICODE_STRING, Buffer) - PaddingStart; + + memset((PCH)String + PaddingStart, 0, PaddingSize); +#else + UNREFERENCED_PARAMETER(String); +#endif +} +#pragma prefast(pop) + #if (PHNT_VERSION >= PHNT_WINDOWS_10) _Must_inspect_result_ NTSYSAPI PWCHAR NTAPI RtlFindUnicodeSubstring( - _In_ PUNICODE_STRING FullString, - _In_ PUNICODE_STRING SearchString, + _In_ PCUNICODE_STRING FullString, + _In_ PCUNICODE_STRING SearchString, _In_ BOOLEAN CaseInSensitive ); #endif // PHNT_VERSION >= PHNT_WINDOWS_10 @@ -1891,11 +2753,31 @@ NTSTATUS NTAPI RtlFindCharInUnicodeString( _In_ ULONG Flags, - _In_ PUNICODE_STRING StringToSearch, - _In_ PUNICODE_STRING CharSet, + _In_ PCUNICODE_STRING StringToSearch, + _In_ PCUNICODE_STRING CharSet, _Out_ PUSHORT NonInclusivePrefixLength ); +typedef struct _RTL_UNICODE_STRING_BUFFER RTL_UNICODE_STRING_BUFFER, *PRTL_UNICODE_STRING_BUFFER; + +NTSYSAPI +NTSTATUS +NTAPI +RtlMultiAppendUnicodeStringBuffer( + _Inout_ PRTL_UNICODE_STRING_BUFFER Buffer, + _In_ ULONG BufferCount, + _In_ PCUNICODE_STRING Source + ); + +NTSYSAPI +NTSTATUS +NTAPI +RtlAppendPathElement( + _In_ ULONG Flags, + _Inout_ PRTL_UNICODE_STRING_BUFFER Buffer, + _In_ PCUNICODE_STRING Source + ); + NTSYSAPI NTSTATUS NTAPI @@ -1917,7 +2799,7 @@ NTSTATUS NTAPI RtlUpcaseUnicodeString( _Inout_ PUNICODE_STRING DestinationString, - _In_ PUNICODE_STRING SourceString, + _In_ PCUNICODE_STRING SourceString, _In_ BOOLEAN AllocateDestinationString ); @@ -1926,7 +2808,7 @@ NTSTATUS NTAPI RtlDowncaseUnicodeString( _Inout_ PUNICODE_STRING DestinationString, - _In_ PUNICODE_STRING SourceString, + _In_ PCUNICODE_STRING SourceString, _In_ BOOLEAN AllocateDestinationString ); @@ -1968,7 +2850,7 @@ NTSTATUS NTAPI RtlUnicodeStringToAnsiString( _Inout_ PANSI_STRING DestinationString, - _In_ PUNICODE_STRING SourceString, + _In_ PCUNICODE_STRING SourceString, _In_ BOOLEAN AllocateDestinationString ); @@ -1977,7 +2859,7 @@ NTSYSAPI ULONG NTAPI RtlUnicodeStringToAnsiSize( - _In_ PUNICODE_STRING SourceString + _In_ PCUNICODE_STRING SourceString ); #if (PHNT_VERSION >= PHNT_WINDOWS_10_20H1) @@ -1995,7 +2877,7 @@ NTSTATUS NTAPI RtlUTF8StringToUnicodeString( _Inout_ PUNICODE_STRING DestinationString, - _In_ PUTF8_STRING SourceString, + _In_ PCUTF8_STRING SourceString, _In_ BOOLEAN AllocateDestinationString ); #endif // PHNT_VERSION >= PHNT_WINDOWS_10_20H1 @@ -2012,7 +2894,7 @@ NTSTATUS NTAPI RtlUpcaseUnicodeStringToAnsiString( _Inout_ PANSI_STRING DestinationString, - _In_ PUNICODE_STRING SourceString, + _In_ PCUNICODE_STRING SourceString, _In_ BOOLEAN AllocateDestinationString ); @@ -2030,7 +2912,7 @@ NTSTATUS NTAPI RtlUnicodeStringToOemString( _Inout_ POEM_STRING DestinationString, - _In_ PUNICODE_STRING SourceString, + _In_ PCUNICODE_STRING SourceString, _In_ BOOLEAN AllocateDestinationString ); @@ -2039,7 +2921,7 @@ NTSTATUS NTAPI RtlUpcaseUnicodeStringToOemString( _Inout_ POEM_STRING DestinationString, - _In_ PUNICODE_STRING SourceString, + _In_ PCUNICODE_STRING SourceString, _In_ BOOLEAN AllocateDestinationString ); @@ -2057,7 +2939,7 @@ NTSTATUS NTAPI RtlUnicodeStringToCountedOemString( _Inout_ POEM_STRING DestinationString, - _In_ PUNICODE_STRING SourceString, + _In_ PCUNICODE_STRING SourceString, _In_ BOOLEAN AllocateDestinationString ); @@ -2066,10 +2948,22 @@ NTSTATUS NTAPI RtlUpcaseUnicodeStringToCountedOemString( _Inout_ POEM_STRING DestinationString, - _In_ PUNICODE_STRING SourceString, + _In_ PCUNICODE_STRING SourceString, _In_ BOOLEAN AllocateDestinationString ); +/** + * The RtlMultiByteToUnicodeN routine translates the specified source string into a Unicode string, using the current system ANSI code page (ACP). + * The source string is not necessarily from a multibyte character set. + * + * \param UnicodeString Pointer to a caller-allocated buffer that receives the translated string. UnicodeString buffer must not overlap with MultiByteString buffer. + * \param MaxBytesInUnicodeString Maximum number of bytes to be written at UnicodeString. If this value causes the translated string to be truncated, RtlMultiByteToUnicodeN does not return an error status. + * \param BytesInUnicodeString Pointer to a caller-allocated variable that receives the length, in bytes, of the translated string. This parameter can be NULL. + * \param MultiByteString Pointer to the string to be translated. + * \param BytesInMultiByteString Size, in bytes, of the string at MultiByteString. + * \return NTSTATUS Successful or errant status. + * \sa https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/ntifs/nf-ntifs-rtlmultibytetounicoden + */ NTSYSAPI NTSTATUS NTAPI @@ -2081,6 +2975,16 @@ RtlMultiByteToUnicodeN( _In_ ULONG BytesInMultiByteString ); +/** + * The RtlMultiByteToUnicodeSize routine determines the number of bytes that are required to store the Unicode translation for the specified source string. + * The translation is assumed to use the current system ANSI code page (ACP). The source string is not necessarily from a multibyte character set. + * + * \param BytesInUnicodeString Pointer to a caller-allocated variable that receives the number of bytes that are required to store the translated string. + * \param MultiByteString Pointer to the source string for which the Unicode length is to be calculated. + * \param BytesInMultiByteString Length, in bytes, of the source string. + * \return NTSTATUS Successful or errant status. + * \sa https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/ntifs/nf-ntifs-rtlmultibytetounicodesize + */ NTSYSAPI NTSTATUS NTAPI @@ -2090,6 +2994,18 @@ RtlMultiByteToUnicodeSize( _In_ ULONG BytesInMultiByteString ); +/** + * The RtlUnicodeToMultiByteN routine translates the specified Unicode string into a new character string, using the current system ANSI code page (ACP). + * The source string is not necessarily from a multibyte character set. + * + * \param MultiByteString Pointer to a caller-allocated buffer to receive the translated string. MultiByteString buffer must not overlap with UnicodeString buffer. + * \param MaxBytesInMultiByteString Maximum number of bytes to be written to MultiByteString. If this value causes the translated string to be truncated, RtlUnicodeToMultiByteN does not return an error status. + * \param BytesInMultiByteString Pointer to a caller-allocated variable that receives the length, in bytes, of the translated string. This parameter is optional and can be NULL. + * \param UnicodeString Pointer to the Unicode source string to be translated. + * \param BytesInUnicodeString Size, in bytes, of the string at UnicodeString. + * \return NTSTATUS Successful or errant status. + * \sa https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/ntifs/nf-ntifs-rtlunicodetomultibyten + */ NTSYSAPI NTSTATUS NTAPI @@ -2101,6 +3017,16 @@ RtlUnicodeToMultiByteN( _In_ ULONG BytesInUnicodeString ); +/** + * The RtlUnicodeToMultiByteSize routine determines the number of bytes that are required to store the multibyte translation for the specified Unicode string. + * The translation is assumed to use the current system ANSI code page (ACP). The source string is not necessarily from a multibyte character set. + * + * \param BytesInMultiByteString Pointer to a caller-allocated variable that receives the number of bytes required to store the translated string. + * \param UnicodeString Pointer to the Unicode string for which the multibyte length is to be calculated. + * \param BytesInUnicodeString Length, in bytes, of the source string. + * \return NTSTATUS Successful or errant status. + * \sa https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/ntifs/nf-ntifs-rtlunicodetomultibytesize + */ NTSYSAPI NTSTATUS NTAPI @@ -2110,6 +3036,18 @@ RtlUnicodeToMultiByteSize( _In_ ULONG BytesInUnicodeString ); +/** + * The RtlUpcaseUnicodeToMultiByteN routine translates the specified Unicode string into a new uppercase character string, using the current system ANSI code page (ACP). + * The translated string is not necessarily from a multibyte character set. + * + * \param MultiByteString Pointer to a caller-allocated buffer to receive the translated string. + * \param MaxBytesInMultiByteString Maximum number of bytes to be written at MultiByteString. If this value causes the translated string to be truncated, RtlUpcaseUnicodeToMultiByteN does not return an error status. + * \param BytesInMultiByteString Pointer to a caller-allocated variable that receives the length, in bytes, of the translated string. This parameter can be NULL. + * \param UnicodeString Pointer to the Unicode source string to be translated. + * \param BytesInUnicodeString Size, in bytes, of the string at UnicodeString. + * \return NTSTATUS Successful or errant status. + * \sa https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/ntifs/nf-ntifs-rtlupcaseunicodetomultibyten + */ NTSYSAPI NTSTATUS NTAPI @@ -2166,7 +3104,17 @@ RtlConsoleMultiByteToUnicodeN( _Out_ PULONG pdwSpecialChar ); -#if (PHNT_VERSION >= PHNT_WINDOWS_7) +/** + * The RtlUTF8ToUnicodeN routine translates the specified source string into a Unicode string, using the 8-bit Unicode Transformation Format (UTF-8) code page. + * + * \param UnicodeStringDestination Pointer to a caller-allocated buffer to receive the translated string. + * \param UnicodeStringMaxByteCount Maximum number of bytes to be written at MultiByteString. If this value causes the translated string to be truncated, RtlUpcaseUnicodeToMultiByteN does not return an error status. + * \param UnicodeStringActualByteCount Pointer to a caller-allocated variable that receives the length, in bytes, of the translated string. This parameter can be NULL. + * \param UTF8StringSource Pointer to the Unicode source string to be translated. + * \param UTF8StringByteCount Size, in bytes, of the string at UnicodeString. + * \return NTSTATUS Successful or errant status. + * \sa https://learn.microsoft.com/en-us/windows/win32/devnotes/rtlutf8tounicoden + */ NTSYSAPI NTSTATUS NTAPI @@ -2177,9 +3125,18 @@ RtlUTF8ToUnicodeN( _In_reads_bytes_(UTF8StringByteCount) PCCH UTF8StringSource, _In_ ULONG UTF8StringByteCount ); -#endif // PHNT_VERSION >= PHNT_WINDOWS_7 -#if (PHNT_VERSION >= PHNT_WINDOWS_7) +/** + * The RtlUnicodeToUTF8N routine translates the specified Unicode string into a new character string, using the 8-bit Unicode Transformation Format (UTF-8) code page. + * + * \param UTF8StringDestination Pointer to a caller-allocated buffer to receive the translated string. + * \param UTF8StringMaxByteCount Maximum number of bytes to be written to UTF8StringDestination. If this value causes the translated string to be truncated, RtlUnicodeToUTF8N returns an error status. + * \param UTF8StringActualByteCount A pointer to a caller-allocated variable that receives the length, in bytes, of the translated string. This parameter is optional and can be NULL. If the string is truncated then the returned number counts the actual truncated string count. + * \param UnicodeStringSource A pointer to the Unicode source string to be translated. + * \param UnicodeStringByteCount Specifies the number of bytes in the Unicode source string that the UnicodeStringSource parameter points to. + * \return NTSTATUS Successful or errant status. + * \sa https://learn.microsoft.com/en-us/windows/win32/devnotes/rtlunicodetoutf8n + */ NTSYSAPI NTSTATUS NTAPI @@ -2190,7 +3147,6 @@ RtlUnicodeToUTF8N( _In_reads_bytes_(UnicodeStringByteCount) PCWCH UnicodeStringSource, _In_ ULONG UnicodeStringByteCount ); -#endif // PHNT_VERSION >= PHNT_WINDOWS_7 NTSYSAPI NTSTATUS @@ -2232,10 +3188,11 @@ NTSYSAPI VOID NTAPI RtlInitCodePageTable( - _In_reads_z_(2) PUSHORT TableBase, + _In_reads_opt_(2) PUSHORT TableBase, _Inout_ PCPTABLEINFO CodePageTable ); +#if (PHNT_VERSION < PHNT_WINDOWS_11) NTSYSAPI VOID NTAPI @@ -2245,6 +3202,7 @@ RtlInitNlsTables( _In_ PUSHORT LanguageNlsBase, _Out_ PNLSTABLEINFO TableInfo // PCPTABLEINFO? ); +#endif NTSYSAPI VOID @@ -2278,7 +3236,6 @@ typedef enum _RTL_NORM_FORM NormIdnaDisallowUnassigned = 0x10d } RTL_NORM_FORM; -#if (PHNT_VERSION >= PHNT_WINDOWS_VISTA) NTSYSAPI NTSTATUS NTAPI @@ -2289,9 +3246,7 @@ RtlNormalizeString( _Out_writes_to_(*DestinationStringLength, *DestinationStringLength) PWSTR DestinationString, _Inout_ PLONG DestinationStringLength ); -#endif // PHNT_VERSION >= PHNT_WINDOWS_VISTA -#if (PHNT_VERSION >= PHNT_WINDOWS_VISTA) NTSYSAPI NTSTATUS NTAPI @@ -2301,20 +3256,27 @@ RtlIsNormalizedString( _In_ LONG SourceStringLength, _Out_ PBOOLEAN Normalized ); -#endif // PHNT_VERSION >= PHNT_WINDOWS_VISTA -#if (PHNT_VERSION >= PHNT_WINDOWS_7) // ntifs:FsRtlIsNameInExpression +/** + * The RtlIsNameInExpression routine determines whether a Unicode string matches the specified pattern. + * + * \param Expression A pointer to the pattern string. This string can contain wildcard characters. If the IgnoreCase parameter is TRUE, the string must contain only uppercase characters. + * \param Name Maximum number of bytes to be written to UTF8StringDestination. If this value causes the translated string to be truncated, RtlUnicodeToUTF8N returns an error status. + * \param IgnoreCase TRUE for case-insensitive matching, or FALSE for case-sensitive matching. + * \param UpcaseTable An optional pointer to an uppercase character table to use for case-insensitive matching. If this parameter is NULL, the default system uppercase character table is used. + * \return TRUE if the string matches the pattern. If the string does not match the pattern, this function returns FALSE. + * \sa https://learn.microsoft.com/en-us/windows/win32/devnotes/rtlisnameinexpression + */ NTSYSAPI BOOLEAN NTAPI RtlIsNameInExpression( - _In_ PUNICODE_STRING Expression, - _In_ PUNICODE_STRING Name, + _In_ PCUNICODE_STRING Expression, + _In_ PCUNICODE_STRING Name, _In_ BOOLEAN IgnoreCase, _In_opt_ PWCH UpcaseTable ); -#endif // PHNT_VERSION >= PHNT_WINDOWS_7 #if (PHNT_VERSION >= PHNT_WINDOWS_10_RS4) // rev @@ -2322,36 +3284,45 @@ NTSYSAPI BOOLEAN NTAPI RtlIsNameInUnUpcasedExpression( - _In_ PUNICODE_STRING Expression, - _In_ PUNICODE_STRING Name, + _In_ PCUNICODE_STRING Expression, + _In_ PCUNICODE_STRING Name, _In_ BOOLEAN IgnoreCase, _In_opt_ PWCH UpcaseTable ); #endif // PHNT_VERSION >= PHNT_WINDOWS_10_RS4 #if (PHNT_VERSION >= PHNT_WINDOWS_10_19H1) +/** + * The RtlDoesNameContainWildCards routine determines whether a Unicode string contains wildcard characters. + * + * \param Name A pointer to the string to be checked. + * \return TRUE if one or more wildcard characters were found, FALSE otherwise. + * \remarks The following are wildcard characters: *, ?, ANSI_DOS_STAR, ANSI_DOS_DOT, and ANSI_DOS_QM. + * \sa https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/ntifs/nf-ntifs-_fsrtl_advanced_fcb_header-fsrtldoesnamecontainwildcards + */ NTSYSAPI BOOLEAN NTAPI RtlDoesNameContainWildCards( - _In_ PUNICODE_STRING Expression + _In_ PCUNICODE_STRING Expression ); + #endif // PHNT_VERSION >= PHNT_WINDOWS_10_19H1 NTSYSAPI BOOLEAN NTAPI RtlEqualDomainName( - _In_ PUNICODE_STRING String1, - _In_ PUNICODE_STRING String2 + _In_ PCUNICODE_STRING String1, + _In_ PCUNICODE_STRING String2 ); NTSYSAPI BOOLEAN NTAPI RtlEqualComputerName( - _In_ PUNICODE_STRING String1, - _In_ PUNICODE_STRING String2 + _In_ PCUNICODE_STRING String1, + _In_ PCUNICODE_STRING String2 ); NTSYSAPI @@ -2359,10 +3330,18 @@ NTSTATUS NTAPI RtlDnsHostNameToComputerName( _Out_ PUNICODE_STRING ComputerNameString, - _In_ PUNICODE_STRING DnsHostNameString, + _In_ PCUNICODE_STRING DnsHostNameString, _In_ BOOLEAN AllocateComputerNameString ); +/** + * The RtlStringFromGUID routine converts a given GUID from binary format into a Unicode string. + * + * \param[in] Guid Specifies the binary-format GUID to convert. + * \param[out] GuidString Pointer to a caller-supplied variable in which a pointer to the converted GUID string is returned and must free by calling RtlFreeUnicodeString. + * \return NTSTATUS Successful or errant status. + * \sa https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/wdm/nf-wdm-rtlstringfromguid + */ NTSYSAPI NTSTATUS NTAPI @@ -2373,6 +3352,9 @@ RtlStringFromGUID( #if (PHNT_VERSION >= PHNT_WINDOWS_8_1) +#define RTL_GUID_STRING_SIZE 38 +#define MAX_UNICODE_GUID_STRING_LENGTH (36 + sizeof(UNICODE_NULL)) + // rev NTSYSAPI NTSTATUS @@ -2389,18 +3371,16 @@ NTSYSAPI NTSTATUS NTAPI RtlGUIDFromString( - _In_ PUNICODE_STRING GuidString, + _In_ PCUNICODE_STRING GuidString, _Out_ PGUID Guid ); -#if (PHNT_VERSION >= PHNT_WINDOWS_VISTA) - NTSYSAPI LONG NTAPI RtlCompareAltitudes( - _In_ PUNICODE_STRING Altitude1, - _In_ PUNICODE_STRING Altitude2 + _In_ PCUNICODE_STRING Altitude1, + _In_ PCUNICODE_STRING Altitude2 ); NTSYSAPI @@ -2436,8 +3416,6 @@ RtlIdnToNameprepUnicode( _Inout_ PLONG DestinationStringLength ); -#endif // PHNT_VERSION >= PHNT_WINDOWS_VISTA - // // Prefix // @@ -2470,7 +3448,7 @@ BOOLEAN NTAPI PfxInsertPrefix( _In_ PPREFIX_TABLE PrefixTable, - _In_ PSTRING Prefix, + _In_ __drv_aliasesMem PSTRING Prefix, _Out_ PPREFIX_TABLE_ENTRY PrefixTableEntry ); @@ -2520,7 +3498,7 @@ BOOLEAN NTAPI RtlInsertUnicodePrefix( _In_ PUNICODE_PREFIX_TABLE PrefixTable, - _In_ PUNICODE_STRING Prefix, + _In_ __drv_aliasesMem PCUNICODE_STRING Prefix, _Out_ PUNICODE_PREFIX_TABLE_ENTRY PrefixTableEntry ); @@ -2537,7 +3515,7 @@ PUNICODE_PREFIX_TABLE_ENTRY NTAPI RtlFindUnicodePrefix( _In_ PUNICODE_PREFIX_TABLE PrefixTable, - _In_ PUNICODE_STRING FullName, + _In_ PCUNICODE_STRING FullName, _In_ ULONG CaseInsensitiveIndex ); @@ -2549,7 +3527,9 @@ RtlNextUnicodePrefix( _In_ BOOLEAN Restart ); +// // Compression +// #define COMPRESSION_FORMAT_NONE (0x0000) #define COMPRESSION_FORMAT_DEFAULT (0x0001) @@ -2669,7 +3649,7 @@ RtlDecompressBufferEx( _Out_ PULONG FinalUncompressedSize, _In_opt_ PVOID WorkSpace ); -#endif +#endif // PHNT_VERSION >= PHNT_WINDOWS_8 #if (PHNT_VERSION >= PHNT_WINDOWS_8_1) NTSYSAPI @@ -2685,7 +3665,7 @@ RtlDecompressBufferEx2( _Out_ PULONG FinalUncompressedSize, _In_opt_ PVOID WorkSpace ); -#endif +#endif // PHNT_VERSION >= PHNT_WINDOWS_8_1 NTSYSAPI NTSTATUS @@ -2766,9 +3746,9 @@ RtlCompressChunks( _In_ PVOID WorkSpace ); +// // Locale - -#if (PHNT_VERSION >= PHNT_WINDOWS_VISTA) +// // private NTSYSAPI @@ -2837,10 +3817,28 @@ NTSYSAPI BOOLEAN NTAPI RtlCultureNameToLCID( - _In_ PUNICODE_STRING String, + _In_ PCUNICODE_STRING String, _Out_ PLCID Lcid ); +// rev +NTSYSAPI +BOOLEAN +NTAPI +RtlpConvertLCIDsToCultureNames( + _In_ PCWSTR Lcids, // array + _Out_ PCWSTR* CultureNames + ); + +// rev +NTSYSAPI +BOOLEAN +NTAPI +RtlpConvertCultureNamesToLCIDs( + _In_ PCWSTR CultureNames, // array + _Out_ PCWSTR* Lcids + ); + // private NTSYSAPI VOID @@ -2849,10 +3847,6 @@ RtlCleanUpTEBLangLists( VOID ); -#endif // PHNT_VERSION >= PHNT_WINDOWS_VISTA - -#if (PHNT_VERSION >= PHNT_WINDOWS_7) - // rev from GetThreadPreferredUILanguages NTSYSAPI NTSTATUS @@ -2931,8 +3925,6 @@ RtlGetLocaleFileMappingAddress( _Out_opt_ PULONG CurrentNLSVersion ); -#endif // PHNT_VERSION >= PHNT_WINDOWS_7 - // // PEB // @@ -2958,7 +3950,6 @@ RtlReleasePebLock( VOID ); -#if (PHNT_VERSION >= PHNT_WINDOWS_VISTA) // private NTSYSAPI LOGICAL @@ -2966,9 +3957,7 @@ NTAPI RtlTryAcquirePebLock( VOID ); -#endif // PHNT_VERSION >= PHNT_WINDOWS_VISTA -#if (PHNT_VERSION < PHNT_WINDOWS_VISTA) NTSYSAPI NTSTATUS NTAPI @@ -2984,7 +3973,6 @@ RtlFreeToPeb( _In_ PVOID Block, _In_ ULONG Size ); -#endif // PHNT_VERSION < PHNT_WINDOWS_VISTA // // Processes @@ -3057,13 +4045,13 @@ typedef struct _RTL_USER_PROCESS_PARAMETERS PVOID PackageDependencyData; ULONG ProcessGroupId; - ULONG LoaderThreads; - UNICODE_STRING RedirectionDllName; // REDSTONE4 + ULONG LoaderThreads; // THRESHOLD + UNICODE_STRING RedirectionDllName; // REDSTONE5 UNICODE_STRING HeapPartitionName; // 19H1 PULONGLONG DefaultThreadpoolCpuSetMasks; ULONG DefaultThreadpoolCpuSetMaskCount; - ULONG DefaultThreadpoolThreadMaximum; - ULONG HeapMemoryTypeMask; // WIN11 + ULONG DefaultThreadpoolThreadMaximum; // 20H1 + ULONG HeapMemoryTypeMask; // WIN11 22H2 } RTL_USER_PROCESS_PARAMETERS, *PRTL_USER_PROCESS_PARAMETERS; // RTL_USER_PROCESS_PARAMETERS Flags @@ -3071,6 +4059,7 @@ typedef struct _RTL_USER_PROCESS_PARAMETERS #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_64K 0x00000010 #define RTL_USER_PROC_RESERVE_1MB 0x00000020 #define RTL_USER_PROC_RESERVE_16MB 0x00000040 #define RTL_USER_PROC_CASE_SENSITIVE 0x00000080 @@ -3080,7 +4069,6 @@ typedef struct _RTL_USER_PROCESS_PARAMETERS #define RTL_USER_PROC_IMAGE_KEY_MISSING 0x00004000 #define RTL_USER_PROC_DEV_OVERRIDE_ENABLED 0x00008000 #define RTL_USER_PROC_OPTIN_PROCESS 0x00020000 -#define RTL_USER_PROC_OPTIN_PROCESS 0x00020000 #define RTL_USER_PROC_SESSION_OWNER 0x00040000 #define RTL_USER_PROC_HANDLE_USER_CALLBACK_EXCEPTIONS 0x00080000 #define RTL_USER_PROC_PROTECTED_PROCESS 0x00400000 @@ -3091,36 +4079,34 @@ NTSTATUS NTAPI RtlCreateProcessParameters( _Out_ PRTL_USER_PROCESS_PARAMETERS *ProcessParameters, - _In_ PUNICODE_STRING ImagePathName, - _In_opt_ PUNICODE_STRING DllPath, - _In_opt_ PUNICODE_STRING CurrentDirectory, - _In_opt_ PUNICODE_STRING CommandLine, + _In_ PCUNICODE_STRING ImagePathName, + _In_opt_ PCUNICODE_STRING DllPath, + _In_opt_ PCUNICODE_STRING CurrentDirectory, + _In_opt_ PCUNICODE_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_opt_ PCUNICODE_STRING WindowTitle, + _In_opt_ PCUNICODE_STRING DesktopInfo, + _In_opt_ PCUNICODE_STRING ShellInfo, + _In_opt_ PCUNICODE_STRING RuntimeData ); -#if (PHNT_VERSION >= PHNT_WINDOWS_VISTA) // private NTSYSAPI NTSTATUS NTAPI RtlCreateProcessParametersEx( _Out_ PRTL_USER_PROCESS_PARAMETERS *ProcessParameters, - _In_ PUNICODE_STRING ImagePathName, - _In_opt_ PUNICODE_STRING DllPath, - _In_opt_ PUNICODE_STRING CurrentDirectory, - _In_opt_ PUNICODE_STRING CommandLine, + _In_ PCUNICODE_STRING ImagePathName, + _In_opt_ PCUNICODE_STRING DllPath, + _In_opt_ PCUNICODE_STRING CurrentDirectory, + _In_opt_ PCUNICODE_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_opt_ PCUNICODE_STRING WindowTitle, + _In_opt_ PCUNICODE_STRING DesktopInfo, + _In_opt_ PCUNICODE_STRING ShellInfo, + _In_opt_ PCUNICODE_STRING RuntimeData, _In_ ULONG Flags // pass RTL_USER_PROC_PARAMS_NORMALIZED to keep parameters normalized ); -#endif // PHNT_VERSION >= PHNT_WINDOWS_VISTA #if (PHNT_VERSION >= PHNT_WINDOWS_10_RS4) // private @@ -3129,16 +4115,16 @@ NTSTATUS NTAPI RtlCreateProcessParametersWithTemplate( _Out_ PRTL_USER_PROCESS_PARAMETERS *ProcessParameters, - _In_ PUNICODE_STRING ImagePathName, - _In_opt_ PUNICODE_STRING DllPath, - _In_opt_ PUNICODE_STRING CurrentDirectory, - _In_opt_ PUNICODE_STRING CommandLine, + _In_ PCUNICODE_STRING ImagePathName, + _In_opt_ PCUNICODE_STRING DllPath, + _In_opt_ PCUNICODE_STRING CurrentDirectory, + _In_opt_ PCUNICODE_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_opt_ PUNICODE_STRING RedirectionDllName, + _In_opt_ PCUNICODE_STRING WindowTitle, + _In_opt_ PCUNICODE_STRING DesktopInfo, + _In_opt_ PCUNICODE_STRING ShellInfo, + _In_opt_ PCUNICODE_STRING RuntimeData, + _In_opt_ PCUNICODE_STRING RedirectionDllName, _In_ ULONG Flags // pass RTL_USER_PROC_PARAMS_NORMALIZED to keep parameters normalized ); #endif // PHNT_VERSION >= PHNT_WINDOWS_10_RS4 @@ -3174,11 +4160,27 @@ typedef struct _RTL_USER_PROCESS_INFORMATION } RTL_USER_PROCESS_INFORMATION, *PRTL_USER_PROCESS_INFORMATION; // private +/** + * Creates a new process and its primary thread. The new process runs in the security context of the calling process. + * + * \param NtImagePathName The path of the image to be executed. + * \param ExtendedParameters Reserved + * \param ProcessParameters The process parameter information. + * \param ProcessSecurityDescriptor The security descriptor for the new process. If NULL, the process gets a default security descriptor. + * \param ThreadSecurityDescriptor The security descriptor for the initial thread. If NULL, the thread gets a default security descriptor. + * \param ParentProcess The handle of a process to use (instead of the calling process) as the parent for the process being created. + * \param InheritHandles If this parameter is TRUE, each inheritable handle in the calling process is inherited by the new process. + * \param DebugPort The handle of an ALPC port for debug messages. If NULL, the process gets a default port. (WindowsErrorReportingServicePort) + * \param TokenHandle The handle of a Token to use as the security context. + * \param ProcessInformation The user process information. + * \return NTSTATUS Successful or errant status. + * \sa https://learn.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-createprocessw + */ NTSYSAPI NTSTATUS NTAPI RtlCreateUserProcess( - _In_ PUNICODE_STRING NtImagePathName, + _In_ PCUNICODE_STRING NtImagePathName, _In_ ULONG ExtendedParameters, // HIWORD(NumaNodeNumber), LOWORD(Reserved) _In_ PRTL_USER_PROCESS_PARAMETERS ProcessParameters, _In_opt_ PSECURITY_DESCRIPTOR ProcessSecurityDescriptor, @@ -3206,11 +4208,23 @@ typedef struct _RTL_USER_PROCESS_EXTENDED_PARAMETERS } RTL_USER_PROCESS_EXTENDED_PARAMETERS, *PRTL_USER_PROCESS_EXTENDED_PARAMETERS; #if (PHNT_VERSION >= PHNT_WINDOWS_10_RS2) +/** + * The RtlCreateUserProcessEx routine creates a new process and its primary thread, with extended parameters. + * + * \param NtImagePathName Pointer to a UNICODE_STRING that specifies the path of the image to be executed. + * \param ProcessParameters Pointer to a RTL_USER_PROCESS_PARAMETERS structure that contains process parameter information. + * \param InheritHandles If TRUE, each inheritable handle in the calling process is inherited by the new process. + * \param ProcessExtendedParameters Optional pointer to a RTL_USER_PROCESS_EXTENDED_PARAMETERS structure for additional process creation options. Can be NULL. + * \param ProcessInformation Pointer to a RTL_USER_PROCESS_INFORMATION structure that receives information about the new process and its primary thread. + * \return NTSTATUS Successful or errant status. + * \remarks This function is available on Windows 10 RS2 and later. It allows for more advanced process creation scenarios than RtlCreateUserProcess. + * \sa https://learn.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-createprocessw + */ NTSYSAPI NTSTATUS NTAPI RtlCreateUserProcessEx( - _In_ PUNICODE_STRING NtImagePathName, + _In_ PCUNICODE_STRING NtImagePathName, _In_ PRTL_USER_PROCESS_PARAMETERS ProcessParameters, _In_ BOOLEAN InheritHandles, _In_opt_ PRTL_USER_PROCESS_EXTENDED_PARAMETERS ProcessExtendedParameters, @@ -3218,7 +4232,13 @@ RtlCreateUserProcessEx( ); #endif // PHNT_VERSION >= PHNT_WINDOWS_10_RS2 -#if (PHNT_VERSION >= PHNT_WINDOWS_VISTA) +/** + * The RtlExitUserProcess routine ends the calling process and all its threads. + * + * \param ExitStatus The exit status for the process and all threads. + * \sa https://learn.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-exitprocess + * \remarks This function does not return to the caller. It terminates the process and all threads immediately. + */ _Analysis_noreturn_ DECLSPEC_NORETURN NTSYSAPI @@ -3227,9 +4247,6 @@ NTAPI RtlExitUserProcess( _In_ NTSTATUS ExitStatus ); -#endif // PHNT_VERSION >= PHNT_WINDOWS_VISTA - -#if (PHNT_VERSION >= PHNT_WINDOWS_VISTA) // begin_rev #define RTL_CLONE_PROCESS_FLAGS_CREATE_SUSPENDED 0x00000001 @@ -3238,6 +4255,16 @@ RtlExitUserProcess( // end_rev // private +/** + * The RtlCloneUserProcess routine creates a new process from the current process. + * + * \param ProcessFlags The path of the image to be executed. + * \param ProcessSecurityDescriptor The security descriptor for the new process. If NULL, the process gets a default security descriptor. + * \param ThreadSecurityDescriptor The security descriptor for the initial thread. If NULL, the thread gets a default security descriptor. + * \param DebugPort The handle of an ALPC port for debug messages. If NULL, the process gets a default port. (WindowsErrorReportingServicePort) + * \param ProcessInformation The new process information. + * \return NTSTATUS Successful or errant status. + */ NTSYSAPI NTSTATUS NTAPI @@ -3282,13 +4309,12 @@ RtlUpdateClonedSRWLock( _In_ LOGICAL Shared // TRUE to set to shared acquire ); -#endif // PHNT_VERSION >= PHNT_WINDOWS_VISTA - -// 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 +// rev RtlCloneUserProcess Flags +#define RTL_PROCESS_REFLECTION_FLAGS_CREATE_SUSPENDED 0x00000001 +#define RTL_PROCESS_REFLECTION_FLAGS_INHERIT_HANDLES 0x00000002 +#define RTL_PROCESS_REFLECTION_FLAGS_NO_SUSPEND 0x00000004 +#define RTL_PROCESS_REFLECTION_FLAGS_NO_SYNCHRONIZE 0x00000008 +#define RTL_PROCESS_REFLECTION_FLAGS_NO_CLOSE_EVENT 0x00000010 // private typedef struct _RTLP_PROCESS_REFLECTION_REFLECTION_INFORMATION @@ -3300,8 +4326,18 @@ typedef struct _RTLP_PROCESS_REFLECTION_REFLECTION_INFORMATION typedef RTLP_PROCESS_REFLECTION_REFLECTION_INFORMATION PROCESS_REFLECTION_INFORMATION, *PPROCESS_REFLECTION_INFORMATION; -#if (PHNT_VERSION >= PHNT_WINDOWS_7) // rev +/** + * The RtlCreateProcessReflection function creates a lightweight copy of a process for debugging or snapshot purposes. + * + * \param ProcessHandle Handle to the process to reflect. + * \param Flags Flags that control the behavior of the reflection. See RTL_PROCESS_REFLECTION_FLAGS_*. + * \param StartRoutine Optional pointer to a routine to execute in the reflected process. + * \param StartContext Optional pointer to context to pass to the start routine. + * \param EventHandle Optional handle to an event to signal when the reflection is complete. + * \param ReflectionInformation Optional pointer to a structure that receives information about the reflected process. + * \return NTSTATUS Successful or errant status. + */ NTSYSAPI NTSTATUS NTAPI @@ -3311,22 +4347,39 @@ RtlCreateProcessReflection( _In_opt_ PVOID StartRoutine, _In_opt_ PVOID StartContext, _In_opt_ HANDLE EventHandle, - _Out_opt_ PRTLP_PROCESS_REFLECTION_REFLECTION_INFORMATION ReflectionInformation + _Out_opt_ PPROCESS_REFLECTION_INFORMATION ReflectionInformation ); -#endif // PHNT_VERSION >= PHNT_WINDOWS_7 +/** + * The RtlSetProcessIsCritical function sets or clears the critical status of the current process. + * + * \param NewValue TRUE to mark the process as critical, FALSE to clear. + * \param OldValue Optional pointer to receive the previous critical status. + * \param CheckFlag If TRUE, checks for certain conditions before setting. + * \return NTSTATUS Successful or errant status. + * \remarks A critical process will cause a system bugcheck if terminated. + */ NTSYSAPI NTSTATUS -STDAPIVCALLTYPE +NTAPI RtlSetProcessIsCritical( _In_ BOOLEAN NewValue, _Out_opt_ PBOOLEAN OldValue, _In_ BOOLEAN CheckFlag ); +/** + * The RtlSetThreadIsCritical function sets or clears the critical status of the current thread. + * + * \param NewValue TRUE to mark the thread as critical, FALSE to clear. + * \param OldValue Optional pointer to receive the previous critical status. + * \param CheckFlag If TRUE, checks for certain conditions before setting. + * \return NTSTATUS Successful or errant status. + * \remarks A critical thread will cause a system bugcheck if terminated. + */ NTSYSAPI NTSTATUS -STDAPIVCALLTYPE +NTAPI RtlSetThreadIsCritical( _In_ BOOLEAN NewValue, _Out_opt_ PBOOLEAN OldValue, @@ -3334,6 +4387,12 @@ RtlSetThreadIsCritical( ); // rev +/** + * The RtlSetThreadSubProcessTag function sets the sub-process tag for the current thread. + * + * \param SubProcessTag Pointer to the tag value to set. + * \return The previous sub-process tag value. + */ NTSYSAPI PVOID NTAPI @@ -3342,6 +4401,12 @@ RtlSetThreadSubProcessTag( ); // rev +/** + * The RtlValidProcessProtection function validates the process protection level. + * + * \param ProcessProtection Pointer to a PS_PROTECTION structure describing the protection. + * \return TRUE if the protection level is valid, FALSE otherwise. + */ NTSYSAPI BOOLEAN NTAPI @@ -3350,6 +4415,13 @@ RtlValidProcessProtection( ); // rev +/** + * The RtlTestProtectedAccess function tests whether a source protection level can access a target protection level. + * + * \param Source Pointer to a PS_PROTECTION structure for the source. + * \param Target Pointer to a PS_PROTECTION structure for the target. + * \return TRUE if access is allowed, FALSE otherwise. + */ NTSYSAPI BOOLEAN NTAPI @@ -3359,7 +4431,13 @@ RtlTestProtectedAccess( ); #if (PHNT_VERSION >= PHNT_WINDOWS_10_RS3) -// rev +/** + * The RtlIsCurrentProcess function determines whether the specified process handle refers to the current process. + * + * \param ProcessHandle Handle to the process to compare with the current process. + * \return TRUE if the handle refers to the current process; otherwise, FALSE. + * \remarks Internally compares the specified handle with the current process handle using NtCompareObjects. + */ NTSYSAPI BOOLEAN NTAPI @@ -3367,7 +4445,13 @@ RtlIsCurrentProcess( // NtCompareObjects(NtCurrentProcess(), ProcessHandle) _In_ HANDLE ProcessHandle ); -// rev +/** + * The RtlIsCurrentThread function determines whether the specified thread handle refers to the current thread. + * + * \param ThreadHandle Handle to the thread to compare with the current thread. + * \return TRUE if the handle refers to the current thread; otherwise, FALSE. + * \remarks Internally compares the specified handle with the current thread handle using NtCompareObjects. + */ NTSYSAPI BOOLEAN NTAPI @@ -3376,12 +4460,31 @@ RtlIsCurrentThread( // NtCompareObjects(NtCurrentThread(), ThreadHandle) ); #endif // PHNT_VERSION >= PHNT_WINDOWS_10_RS3 +// // Threads +// -typedef NTSTATUS (NTAPI *PUSER_THREAD_START_ROUTINE)( +typedef _Function_class_(USER_THREAD_START_ROUTINE) +NTSTATUS NTAPI USER_THREAD_START_ROUTINE( _In_ PVOID ThreadParameter ); +typedef USER_THREAD_START_ROUTINE* PUSER_THREAD_START_ROUTINE; +/** + * The RtlCreateUserThread routine creates a thread in the specified process. + * + * \param ProcessHandle Handle to the process in which the thread is to be created. + * \param ThreadSecurityDescriptor Optional pointer to a security descriptor for the new thread. If NULL, the thread gets a default security descriptor. + * \param CreateSuspended If TRUE, the thread is created in a suspended state and must be resumed explicitly. If FALSE, the thread starts running immediately. + * \param ZeroBits Optional number of high-order address bits that must be zero in the stack's base address. Usually set to 0. + * \param MaximumStackSize Optional maximum size, in bytes, of the stack for the new thread. If 0, the default size is used. + * \param CommittedStackSize Optional initial size, in bytes, of committed stack for the new thread. If 0, the default size is used. + * \param StartAddress Pointer to the application-defined function to be executed by the thread. + * \param Parameter Optional pointer to a variable to be passed to the thread function. + * \param ThreadHandle Optional pointer to a variable that receives the handle of the new thread. + * \param ClientId Optional pointer to a CLIENT_ID structure that receives the thread and process identifiers. + * \return NTSTATUS Successful or errant status. + */ NTSYSAPI NTSTATUS NTAPI @@ -3398,7 +4501,13 @@ RtlCreateUserThread( _Out_opt_ PCLIENT_ID ClientId ); -#if (PHNT_VERSION >= PHNT_WINDOWS_XP) +/** + * The RtlExitUserThread routine ends the calling thread and returns the specified exit status. + * + * \param ExitStatus The exit status for the thread. + * \remarks This function does not return to the caller. It terminates the thread immediately. + * \sa https://learn.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-exitthread + */ _Analysis_noreturn_ DECLSPEC_NORETURN NTSYSAPI @@ -3407,20 +4516,32 @@ NTAPI RtlExitUserThread( _In_ NTSTATUS ExitStatus ); -#endif // PHNT_VERSION >= PHNT_WINDOWS_XP -#if (PHNT_VERSION >= PHNT_WINDOWS_VISTA) // rev +/** + * The RtlIsCurrentThreadAttachExempt routine determines whether the current thread is exempt from attach notifications. + * + * \return TRUE if the current thread is attach-exempt; otherwise, FALSE. + * \remarks Attach-exempt threads do not receive DLL_THREAD_ATTACH and DLL_THREAD_DETACH notifications. + */ NTSYSAPI BOOLEAN NTAPI RtlIsCurrentThreadAttachExempt( VOID ); -#endif // PHNT_VERSION >= PHNT_WINDOWS_VISTA -#if (PHNT_VERSION >= PHNT_WINDOWS_VISTA) -// private +/** + * The RtlCreateUserStack routine allocates and initializes a user-mode stack for a new thread. + * + * \param CommittedStackSize The initial size, in bytes, of committed stack. If 0, the default is used. + * \param MaximumStackSize The maximum size, in bytes, of the stack. If 0, the default is used. + * \param ZeroBits The number of high-order address bits that must be zero in the stack's base address. Usually set to 0. + * \param PageSize The system page size, in bytes. + * \param ReserveAlignment The alignment for the reserved stack region. + * \param InitialTeb Pointer to an INITIAL_TEB structure that receives the stack information. + * \return NTSTATUS Successful or errant status. + */ NTSYSAPI NTSTATUS NTAPI @@ -3433,14 +4554,18 @@ RtlCreateUserStack( _Out_ PINITIAL_TEB InitialTeb ); -// private +/** + * The RtlFreeUserStack routine frees a user-mode stack previously allocated for a thread. + * + * \param AllocationBase The base address of the stack allocation to free. + * \return NTSTATUS Successful or errant status. + */ NTSYSAPI NTSTATUS NTAPI RtlFreeUserStack( _In_ PVOID AllocationBase ); -#endif // PHNT_VERSION >= PHNT_WINDOWS_VISTA // // Extended thread context @@ -3464,7 +4589,7 @@ typedef struct _CONTEXT_EX #define CONTEXT_ALIGN 0x10 #else #define CONTEXT_ALIGN 0x8 -#endif +#endif // _AMD64_ || _ARM64_ || _ARM64EC_ #if defined(_AMD64_) #define CONTEXT_FRAME_LENGTH 0x4D0 @@ -3478,7 +4603,7 @@ typedef struct _CONTEXT_EX #else #define CONTEXT_FRAME_LENGTH 0x2CC #define CONTEXT_EX_PADDING 0x4 -#endif +#endif // _AMD64_ #define CONTEXT_ALIGNMENT(Size, Align) \ (((ULONG_PTR)(Size) + (Align) - 1) & ~((Align) - 1)) @@ -3486,30 +4611,28 @@ typedef struct _CONTEXT_EX #define CONTEXT_EX_LENGTH \ CONTEXT_ALIGNMENT(sizeof(CONTEXT_EX), CONTEXT_ALIGN) -C_ASSERT(CONTEXT_FRAME_LENGTH == sizeof(CONTEXT)); -C_ASSERT(CONTEXT_EX_LENGTH == 0x20); +static_assert(CONTEXT_FRAME_LENGTH == sizeof(CONTEXT)); +static_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) +#define RTL_CONTEXT_EX_CHUNK(Base, Layout, Chunk) ((PVOID)((PUCHAR)(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) +/** + * The RtlInitializeContext function initializes a CONTEXT structure. + * + * \param ProcessHandle Handle to the process to write the CONTEXT. (32bit only) + * \param Context A pointer to a buffer within which to initialize a CONTEXT structure. + * \param Parameter Optional parameter passed to the thread start routine. + * \param InitialPc Initial instruction pointer (thread start routine). + * \param InitialSp Initial stack pointer. + * \return On 32bit, returns the status of NtWriteVirtualMemory. On 64bit, returns a constant value (0xf0e0d0c0a0908070). + * \remarks The return value on 64bit systems is not an NTSTATUS; callers should ignore it. + * \sa https://learn.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-initializecontext + */ NTSYSAPI NTSTATUS NTAPI @@ -3520,7 +4643,6 @@ RtlInitializeContext( _In_opt_ PVOID InitialPc, _In_opt_ PVOID InitialSp ); -#endif // _M_AMD64 NTSYSAPI NTSTATUS @@ -3592,6 +4714,16 @@ RtlLocateExtendedFeature( _Out_opt_ PULONG Length ); +NTSYSAPI +PVOID +NTAPI +RtlLocateExtendedFeature2( + _In_ PCONTEXT_EX ContextEx, + _In_ ULONG FeatureId, + _In_ XSTATE_CONFIGURATION XState, + _Out_opt_ PULONG Length + ); + NTSYSAPI PCONTEXT NTAPI @@ -3608,11 +4740,11 @@ RtlSetExtendedFeaturesMask( _In_ ULONG64 FeatureMask ); -#ifdef _WIN64 -#ifdef PHNT_INLINE_TYPEDEFS +#if defined(_WIN64) +#if defined(_PHLIB_) FORCEINLINE NTSTATUS -NTAPI +NTAPI_INLINE RtlWow64GetThreadContext( _In_ HANDLE ThreadHandle, _Inout_ PWOW64_CONTEXT ThreadContext @@ -3635,14 +4767,14 @@ RtlWow64GetThreadContext( _In_ HANDLE ThreadHandle, _Inout_ PWOW64_CONTEXT ThreadContext ); -#endif // PHNT_INLINE_TYPEDEFS +#endif // _PHLIB_ #endif // _WIN64 -#ifdef _WIN64 -#ifdef PHNT_INLINE_TYPEDEFS +#if defined(_WIN64) +#if defined(_PHLIB_) FORCEINLINE NTSTATUS -NTAPI +NTAPI_INLINE RtlWow64SetThreadContext( _In_ HANDLE ThreadHandle, _In_ PWOW64_CONTEXT ThreadContext @@ -3664,9 +4796,21 @@ RtlWow64SetThreadContext( _In_ HANDLE ThreadHandle, _In_ PWOW64_CONTEXT ThreadContext ); -#endif // PHNT_INLINE_TYPEDEFS +#endif // _PHLIB_ #endif // _WIN64 +/** + * The RtlRemoteCall routine calls a function in the context of a specified thread in a remote process. + * + * \param ProcessHandle Handle to the process in which the thread resides. + * \param ThreadHandle Handle to the thread in which the function is to be called. + * \param CallSite Address of the function to call in the remote process. + * \param ArgumentCount Number of arguments to pass to the function. + * \param Arguments Pointer to an array of arguments to pass to the function. Can be NULL if no arguments are needed. + * \param PassContext If TRUE, the thread context is passed to the function. + * \param AlreadySuspended If TRUE, the thread is already suspended and does not need to be suspended by this routine. + * \return NTSTATUS Successful or errant status. + */ NTSYSAPI NTSTATUS NTAPI @@ -3687,10 +4831,10 @@ RtlRemoteCall( /** * Registers a vectored exception handler. * - * @param First If this parameter is TRUE, the handler is the first handler in the list. - * @param Handler A pointer to the vectored exception handler to be called. - * @return A handle to the vectored exception handler. - * @see https://docs.microsoft.com/en-us/windows/win32/api/errhandlingapi/nf-errhandlingapi-addvectoredexceptionhandler + * \param First If this parameter is TRUE, the handler is the first handler in the list. + * \param Handler A pointer to the vectored exception handler to be called. + * \return A handle to the vectored exception handler. + * \see https://docs.microsoft.com/en-us/windows/win32/api/errhandlingapi/nf-errhandlingapi-addvectoredexceptionhandler */ NTSYSAPI PVOID @@ -3703,9 +4847,9 @@ RtlAddVectoredExceptionHandler( /** * Removes a vectored exception handler. * - * @param Handle A handle to the vectored exception handler to remove. - * @return The function returns 0 if the handler is removed, or -1 if the handler is not found. - * @see https://docs.microsoft.com/en-us/windows/win32/api/errhandlingapi/nf-errhandlingapi-removevectoredexceptionhandler + * \param Handle A handle to the vectored exception handler to remove. + * \return The function returns 0 if the handler is removed, or -1 if the handler is not found. + * \see https://docs.microsoft.com/en-us/windows/win32/api/errhandlingapi/nf-errhandlingapi-removevectoredexceptionhandler */ NTSYSAPI ULONG @@ -3717,10 +4861,10 @@ RtlRemoveVectoredExceptionHandler( /** * Registers a vectored continue handler. * - * @param First If this parameter is TRUE, the handler is the first handler in the list. - * @param Handler A pointer to the vectored exception handler to be called. - * @return A handle to the vectored continue handler. - * @see https://docs.microsoft.com/en-us/windows/win32/api/errhandlingapi/nf-errhandlingapi-addvectoredcontinuehandler + * \param First If this parameter is TRUE, the handler is the first handler in the list. + * \param Handler A pointer to the vectored exception handler to be called. + * \return A handle to the vectored continue handler. + * \see https://docs.microsoft.com/en-us/windows/win32/api/errhandlingapi/nf-errhandlingapi-addvectoredcontinuehandler */ NTSYSAPI PVOID @@ -3733,9 +4877,9 @@ RtlAddVectoredContinueHandler( /** * Removes a vectored continue handler. * - * @param Handle A handle to the vectored continue handler to remove. - * @return The function returns 0 if the handler is removed, or -1 if the handler is not found. - * @see https://docs.microsoft.com/en-us/windows/win32/api/errhandlingapi/nf-errhandlingapi-removevectoredcontinuehandler + * \param Handle A handle to the vectored continue handler to remove. + * \return The function returns 0 if the handler is removed, or -1 if the handler is not found. + * \see https://docs.microsoft.com/en-us/windows/win32/api/errhandlingapi/nf-errhandlingapi-removevectoredcontinuehandler */ NTSYSAPI ULONG @@ -3744,17 +4888,21 @@ RtlRemoveVectoredContinueHandler( _In_ PVOID Handle ); +// // Runtime exception handling +// -typedef ULONG (NTAPI *PRTLP_UNHANDLED_EXCEPTION_FILTER)( +typedef _Function_class_(RTLP_UNHANDLED_EXCEPTION_FILTER) +LONG NTAPI RTLP_UNHANDLED_EXCEPTION_FILTER( _In_ PEXCEPTION_POINTERS ExceptionInfo ); +typedef RTLP_UNHANDLED_EXCEPTION_FILTER* PRTLP_UNHANDLED_EXCEPTION_FILTER; NTSYSAPI VOID NTAPI RtlSetUnhandledExceptionFilter( - _In_ PRTLP_UNHANDLED_EXCEPTION_FILTER UnhandledExceptionFilter + _In_opt_ PRTLP_UNHANDLED_EXCEPTION_FILTER UnhandledExceptionFilter ); // rev @@ -3832,6 +4980,7 @@ RtlInitializeSListHead( _Out_ PSLIST_HEADER ListHead ); +_Must_inspect_result_ NTSYSAPI PSLIST_ENTRY NTAPI @@ -3861,7 +5010,7 @@ RtlInterlockedPushListSListEx( _Inout_ PSLIST_HEADER ListHead, _Inout_ __drv_aliasesMem PSLIST_ENTRY List, _Inout_ PSLIST_ENTRY ListEnd, - _In_ DWORD Count + _In_ ULONG Count ); NTSYSAPI @@ -3872,7 +5021,7 @@ RtlInterlockedFlushSList( ); NTSYSAPI -WORD +USHORT NTAPI RtlQueryDepthSList( _In_ PSLIST_HEADER ListHead @@ -3987,7 +5136,7 @@ RtlFindActivationContextSectionString( _In_ ULONG Flags, _In_opt_ PGUID ExtensionGuid, _In_ ULONG SectionId, // ACTIVATION_CONTEXT_SECTION_* - _In_ PUNICODE_STRING StringToFind, + _In_ PCUNICODE_STRING StringToFind, _Inout_ PACTCTX_SECTION_KEYED_DATA ReturnedData ); @@ -4045,11 +5194,11 @@ RtlQueryInformationActivationContext( _Out_opt_ PSIZE_T ReturnLength ); -#ifdef PHNT_INLINE_TYPEDEFS +#if defined(_PHLIB_) // private FORCEINLINE NTSTATUS -NTAPI +NTAPI_INLINE RtlQueryInformationActiveActivationContext( _In_ ACTIVATION_CONTEXT_INFO_CLASS ActivationContextInformationClass, _Out_writes_bytes_(ActivationContextInformationLength) PVOID ActivationContextInformation, @@ -4060,7 +5209,7 @@ RtlQueryInformationActiveActivationContext( return RtlQueryInformationActivationContext( RTL_QUERY_INFORMATION_ACTIVATION_CONTEXT_FLAG_USE_ACTIVE_ACTIVATION_CONTEXT, NULL, - 0, + NULL, ActivationContextInformationClass, ActivationContextInformation, ActivationContextInformationLength, @@ -4078,7 +5227,7 @@ RtlQueryInformationActiveActivationContext( _In_ SIZE_T ActivationContextInformationLength, _Out_opt_ PSIZE_T ReturnLength ); -#endif // PHNT_INLINE_TYPEDEFS +#endif // _PHLIB_ // // Images @@ -4091,6 +5240,9 @@ RtlImageNtHeader( _In_ PVOID BaseOfImage ); +/** + * Flag to disable range checking in RtlImageNtHeaderEx. + */ #define RTL_IMAGE_NT_HEADER_EX_FLAG_NO_RANGE_CHECK 0x00000001 NTSYSAPI @@ -4170,7 +5322,6 @@ RtlGuardCheckLongJumpTarget( _In_ BOOL IsFastFail, _Out_ PBOOL IsLongJumpTarget ); - #endif // PHNT_VERSION >= PHNT_WINDOWS_10_RS1 #if (PHNT_VERSION >= PHNT_WINDOWS_11_22H2) @@ -4207,9 +5358,42 @@ RtlCompareMemoryUlong( _In_ ULONG Pattern ); +NTSYSAPI +NTSTATUS +NTAPI +RtlCopyMappedMemory( + _Out_writes_bytes_all_(Length) PVOID Destination, + _In_reads_bytes_(Length) PVOID Source, + _In_ SIZE_T Length + ); + +#if defined(_M_AMD64) || defined(_M_ARM64) +NTSYSAPI +VOID +NTAPI +RtlCopyMemoryNonTemporal( + _Out_writes_bytes_all_(Length) VOID UNALIGNED *Destination, + _In_reads_bytes_(Length) CONST VOID UNALIGNED *Source, + _In_ SIZE_T Length + ); + +NTSYSAPI +VOID +NTAPI +RtlFillMemoryNonTemporal( + _Out_writes_bytes_all_(Length) VOID UNALIGNED *Destination, + _In_ SIZE_T Length, + _In_ CONST UCHAR Value + ); +#else +#define RtlCopyMemoryNonTemporal RtlCopyMemory +#define RtlFillMemoryNonTemporal RtlFillMemory +#endif + #if defined(_M_AMD64) FORCEINLINE VOID +NTAPI_INLINE RtlFillMemoryUlong( _Out_writes_bytes_all_(Length) PVOID Destination, _In_ SIZE_T Length, @@ -4312,28 +5496,28 @@ RtlCrc64( // RTL_SYSTEM_GLOBAL_DATA_ID #define GlobalDataIdUnknown 0 -#define GlobalDataIdRngSeedVersion 1 -#define GlobalDataIdInterruptTime 2 -#define GlobalDataIdTimeZoneBias 3 -#define GlobalDataIdImageNumberLow 4 -#define GlobalDataIdImageNumberHigh 5 -#define GlobalDataIdTimeZoneId 6 -#define GlobalDataIdNtMajorVersion 7 -#define GlobalDataIdNtMinorVersion 8 -#define GlobalDataIdSystemExpirationDate 9 -#define GlobalDataIdKdDebuggerEnabled 10 -#define GlobalDataIdCyclesPerYield 11 -#define GlobalDataIdSafeBootMode 12 -#define GlobalDataIdLastSystemRITEventTickCount 13 -#define GlobalDataIdConsoleSharedDataFlags 14 -#define GlobalDataIdNtSystemRootDrive 15 -#define GlobalDataIdQpcBypassEnabled 16 -#define GlobalDataIdQpcData 17 -#define GlobalDataIdQpcBias 18 +#define GlobalDataIdRngSeedVersion 1 // KUSER_SHARED_DATA->RngSeedVersion +#define GlobalDataIdInterruptTime 2 // KUSER_SHARED_DATA->InterruptTime +#define GlobalDataIdTimeZoneBias 3 // KUSER_SHARED_DATA->TimeZoneBias +#define GlobalDataIdImageNumberLow 4 // KUSER_SHARED_DATA->ImageNumberLow +#define GlobalDataIdImageNumberHigh 5 // KUSER_SHARED_DATA->ImageNumberHigh +#define GlobalDataIdTimeZoneId 6 // KUSER_SHARED_DATA->TimeZoneId +#define GlobalDataIdNtMajorVersion 7 // KUSER_SHARED_DATA->NtMajorVersion +#define GlobalDataIdNtMinorVersion 8 // KUSER_SHARED_DATA->NtMinorVersion +#define GlobalDataIdSystemExpirationDate 9 // KUSER_SHARED_DATA->SystemExpirationDate +#define GlobalDataIdKdDebuggerEnabled 10 // KUSER_SHARED_DATA->KdDebuggerEnabled +#define GlobalDataIdCyclesPerYield 11 // KUSER_SHARED_DATA->CyclesPerYield +#define GlobalDataIdSafeBootMode 12 // KUSER_SHARED_DATA->SafeBootMode +#define GlobalDataIdLastSystemRITEventTickCount 13 // KUSER_SHARED_DATA->LastSystemRITEventTickCount +#define GlobalDataIdConsoleSharedDataFlags 14 // KUSER_SHARED_DATA->ConsoleSharedDataFlags +#define GlobalDataIdNtSystemRootDrive 15 // KUSER_SHARED_DATA->NtSystemRoot // RtlGetNtSystemRoot +#define GlobalDataIdQpcBypassEnabled 16 // KUSER_SHARED_DATA->QpcBypassEnabled +#define GlobalDataIdQpcData 17 // KUSER_SHARED_DATA->QpcData +#define GlobalDataIdQpcBias 18 // KUSER_SHARED_DATA->QpcBias #if !defined(NTDDI_WIN10_FE) || (NTDDI_VERSION < NTDDI_WIN10_FE) typedef ULONG RTL_SYSTEM_GLOBAL_DATA_ID; -#endif +#endif // !defined(NTDDI_WIN10_FE) || (NTDDI_VERSION < NTDDI_WIN10_FE) NTSYSAPI ULONG @@ -4371,7 +5555,6 @@ RtlCreateEnvironment( #define RTL_CREATE_ENVIRONMENT_EMPTY 0x4 // create empty environment block // end_rev -#if (PHNT_VERSION >= PHNT_WINDOWS_VISTA) // private NTSYSAPI NTSTATUS @@ -4381,7 +5564,6 @@ RtlCreateEnvironmentEx( _Out_ PVOID *Environment, _In_ ULONG Flags ); -#endif // PHNT_VERSION >= PHNT_WINDOWS_VISTA NTSYSAPI NTSTATUS @@ -4398,7 +5580,6 @@ RtlSetCurrentEnvironment( _Out_opt_ PVOID *PreviousEnvironment ); -#if (PHNT_VERSION >= PHNT_WINDOWS_VISTA) // private NTSYSAPI NTSTATUS @@ -4410,18 +5591,16 @@ RtlSetEnvironmentVar( _In_reads_(ValueLength) PCWSTR Value, _In_opt_ SIZE_T ValueLength ); -#endif // PHNT_VERSION >= PHNT_WINDOWS_VISTA NTSYSAPI NTSTATUS NTAPI RtlSetEnvironmentVariable( _Inout_opt_ PVOID *Environment, - _In_ PUNICODE_STRING Name, - _In_opt_ PUNICODE_STRING Value + _In_ PCUNICODE_STRING Name, + _In_opt_ PCUNICODE_STRING Value ); -#if (PHNT_VERSION >= PHNT_WINDOWS_VISTA) // private NTSYSAPI NTSTATUS @@ -4434,18 +5613,16 @@ RtlQueryEnvironmentVariable( _In_opt_ SIZE_T ValueLength, _Out_ PSIZE_T ReturnLength ); -#endif // PHNT_VERSION >= PHNT_WINDOWS_VISTA NTSYSAPI NTSTATUS NTAPI RtlQueryEnvironmentVariable_U( _In_opt_ PVOID Environment, - _In_ PUNICODE_STRING Name, + _In_ PCUNICODE_STRING Name, _Inout_ PUNICODE_STRING Value ); -#if (PHNT_VERSION >= PHNT_WINDOWS_VISTA) // private NTSYSAPI NTSTATUS @@ -4458,14 +5635,13 @@ RtlExpandEnvironmentStrings( _In_ SIZE_T DestinationLength, _Out_opt_ PSIZE_T ReturnLength ); -#endif // PHNT_VERSION >= PHNT_WINDOWS_VISTA NTSYSAPI NTSTATUS NTAPI RtlExpandEnvironmentStrings_U( _In_opt_ PVOID Environment, - _In_ PUNICODE_STRING Source, + _In_ PCUNICODE_STRING Source, _Inout_ PUNICODE_STRING Destination, _Out_opt_ PULONG ReturnedLength ); @@ -4507,6 +5683,25 @@ typedef enum _RTL_PATH_TYPE RtlPathTypeRootLocalDevice // "\\\\?\\C:\\folder\\file.txt" } RTL_PATH_TYPE; +#if !defined(PHNT_INLINE_SEPERATOR_STRINGS) + +#define RtlNtdllName L"ntdll.dll" +#define RtlDosPathSeperatorsString ((CONST UNICODE_STRING)RTL_CONSTANT_STRING(L"\\/")) +#define RtlAlternateDosPathSeperatorString ((CONST UNICODE_STRING)RTL_CONSTANT_STRING(L"/")) +#define RtlNtPathSeperatorString ((CONST UNICODE_STRING)RTL_CONSTANT_STRING(L"\\")) + +#define RtlDosDevicesPrefix ((CONST UNICODE_STRING)RTL_CONSTANT_STRING(L"\\??\\")) +#define RtlDosDevicesUncPrefix ((CONST UNICODE_STRING)RTL_CONSTANT_STRING(L"\\??\\UNC\\")) +#define RtlSlashSlashDot ((CONST UNICODE_STRING)RTL_CONSTANT_STRING(L"\\\\.\\")) +#define RtlNullString ((CONST UNICODE_STRING)RTL_CONSTANT_STRING(L"")) +#define RtlWin32NtRootSlash ((CONST UNICODE_STRING)RTL_CONSTANT_STRING(L"\\\\?\\")) +#define RtlWin32NtRoot ((CONST UNICODE_STRING)RTL_CONSTANT_STRING(L"\\\\?")) +#define RtlWin32NtUncRoot ((CONST UNICODE_STRING)RTL_CONSTANT_STRING(L"\\\\?\\UNC")) +#define RtlWin32NtUncRootSlash ((CONST UNICODE_STRING)RTL_CONSTANT_STRING(L"\\\\?\\UNC\\")) +#define RtlDefaultExtension ((CONST UNICODE_STRING)RTL_CONSTANT_STRING(L".DLL")) + +#else + // Data exports (ntdll.lib/ntdllp.lib) NTSYSAPI PCWSTR RtlNtdllName; @@ -4514,27 +5709,18 @@ 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 // PHNT_INLINE_SEPERATOR_STRINGS // // Path functions // +/** + * The RtlDetermineDosPathNameType_U routine determines the type of Dos or Win32 path type for the specified filename. + * + * \param DosFileName A pointer to the buffer that contains the Dos or Win32 filename. + * \return The return value specifies the path type for the specified file. + */ NTSYSAPI RTL_PATH_TYPE NTAPI @@ -4542,6 +5728,15 @@ RtlDetermineDosPathNameType_U( _In_ PCWSTR DosFileName ); +/** + * The RtlIsDosDeviceName_U routine examines the Dos format file name and determines if it is a Dos device name. + * + * \param DosFileName A pointer to the buffer that contains the DOS or Win32 filename. + * \return A nonzero value when the Dos file name is the name of a Dos device. The high order 16 bits is the offset + * in the input buffer where the dos device name beings and the low order 16 bits is the length of the device name (excluding any optional trailing colon). + * Otherwise, A zero value when the Dos file name is not the name of a Dos device. + * \sa https://learn.microsoft.com/en-us/windows/win32/devnotes/rtlisdosdevicename_u + */ NTSYSAPI ULONG NTAPI @@ -4549,6 +5744,16 @@ RtlIsDosDeviceName_U( _In_ PCWSTR DosFileName ); +/** + * The RtlGetFullPathName_U routine retrieves the full path and file name of the specified file. + * + * \param FileName A pointer to the buffer that contains the relative filename. + * \param BufferLength The length of the buffer for the file path string, in WCHARs. The buffer length must include room for a terminating null character. + * \param Buffer A pointer to the buffer that receives the file path string. + * \param FilePart A pointer to a buffer that receives the address (within Buffer) of the final file name component in the path. + * \return If the function succeeds, the return value specifies the number of characters that are written to the buffer, not including the terminating null character. + * \sa https://learn.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-getfullpathnamea + */ NTSYSAPI ULONG NTAPI @@ -4559,8 +5764,18 @@ RtlGetFullPathName_U( _Out_opt_ PWSTR *FilePart ); -#if (PHNT_VERSION >= PHNT_WINDOWS_7) // rev +/** + * The RtlGetFullPathName_UEx routine retrieves the full path and file name of the specified file. + * + * \param FileName A pointer to the buffer that contains the relative filename. + * \param BufferLength The length of the buffer for the file path string, in WCHARs. The buffer length must include room for a terminating null character. + * \param Buffer A pointer to the buffer that receives the file path string. + * \param FilePart A pointer to a buffer that receives the address (within Buffer) of the final file name component in the path. + * \param BytesRequired If the function succeeds, the return value specifies the number of characters that are written to the buffer, not including the terminating null character. + * \return NTSTATUS Successful or errant status. + * \sa https://learn.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-getfullpathnamea + */ NTSYSAPI NTSTATUS NTAPI @@ -4571,14 +5786,12 @@ RtlGetFullPathName_UEx( _Out_opt_ PWSTR *FilePart, _Out_opt_ ULONG *BytesRequired ); -#endif // PHNT_VERSION >= PHNT_WINDOWS_7 -#if (PHNT_VERSION >= PHNT_WINDOWS_SERVER_2003) NTSYSAPI NTSTATUS NTAPI RtlGetFullPathName_UstrEx( - _In_ PUNICODE_STRING FileName, + _In_ PCUNICODE_STRING FileName, _Inout_ PUNICODE_STRING StaticString, _Out_opt_ PUNICODE_STRING DynamicString, _Out_opt_ PUNICODE_STRING *StringUsed, @@ -4587,8 +5800,15 @@ RtlGetFullPathName_UstrEx( _Out_ RTL_PATH_TYPE *InputPathType, _Out_opt_ SIZE_T *BytesRequired ); -#endif // PHNT_VERSION >= PHNT_WINDOWS_SERVER_2003 +/** + * The RtlGetCurrentDirectory_U routine retrieves the current directory for the current process. + * + * \param BufferLength The length of the buffer for the current directory string, in WCHARs. The buffer length must include room for a terminating null character. + * \param Buffer A pointer to the buffer that receives the current directory string. + * \return If the function succeeds, the return value specifies the number of characters that are written to the buffer, not including the terminating null character. + * \sa https://learn.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-getcurrentdirectory + */ NTSYSAPI ULONG NTAPI @@ -4597,11 +5817,19 @@ RtlGetCurrentDirectory_U( _Out_writes_bytes_(BufferLength) PWSTR Buffer ); +/** + * The RtlSetCurrentDirectory_U routine changes the current directory for the current process. + * + * \param PathName The path to the new current directory. + * This parameter may specify a relative path or a full path. In either case, the full path of the specified directory is calculated and stored as the current directory. + * \return If the function succeeds, the return value specifies the number of characters that are written to the buffer, not including the terminating null character. + * \sa https://learn.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-getcurrentdirectory + */ NTSYSAPI NTSTATUS NTAPI RtlSetCurrentDirectory_U( - _In_ PUNICODE_STRING PathName + _In_ PCUNICODE_STRING PathName ); NTSYSAPI @@ -4660,7 +5888,7 @@ RtlNtPathNameToDosPathName( _Reserved_ ULONG Flags, _Inout_ PRTL_UNICODE_STRING_BUFFER Path, _Out_opt_ PULONG Disposition, // RtlDetermineDosPathNameType_U - _Out_opt_ PWSTR* FilePart + _Inout_opt_ PWSTR* FilePart ); NTSYSAPI @@ -4673,7 +5901,6 @@ RtlDosPathNameToNtPathName_U( _Out_opt_ PRTL_RELATIVE_NAME_U RelativeName ); -#if (PHNT_VERSION >= PHNT_WINDOWS_SERVER_2003) NTSYSAPI NTSTATUS NTAPI @@ -4683,7 +5910,6 @@ RtlDosPathNameToNtPathName_U_WithStatus( _Out_opt_ PWSTR *FilePart, _Out_opt_ PRTL_RELATIVE_NAME_U RelativeName ); -#endif #if (PHNT_VERSION >= PHNT_WINDOWS_10_RS3) // rev @@ -4696,9 +5922,8 @@ RtlDosLongPathNameToNtPathName_U_WithStatus( _Out_opt_ PWSTR *FilePart, _Out_opt_ PRTL_RELATIVE_NAME_U RelativeName ); -#endif +#endif // PHNT_VERSION >= PHNT_WINDOWS_10_RS3 -#if (PHNT_VERSION >= PHNT_WINDOWS_SERVER_2003) NTSYSAPI BOOLEAN NTAPI @@ -4708,9 +5933,7 @@ RtlDosPathNameToRelativeNtPathName_U( _Out_opt_ PWSTR *FilePart, _Out_opt_ PRTL_RELATIVE_NAME_U RelativeName ); -#endif -#if (PHNT_VERSION >= PHNT_WINDOWS_SERVER_2003) NTSYSAPI NTSTATUS NTAPI @@ -4720,7 +5943,6 @@ RtlDosPathNameToRelativeNtPathName_U_WithStatus( _Out_opt_ PWSTR *FilePart, _Out_opt_ PRTL_RELATIVE_NAME_U RelativeName ); -#endif #if (PHNT_VERSION >= PHNT_WINDOWS_10_RS3) // rev @@ -4733,16 +5955,14 @@ RtlDosLongPathNameToRelativeNtPathName_U_WithStatus( _Out_opt_ PWSTR *FilePart, _Out_opt_ PRTL_RELATIVE_NAME_U RelativeName ); -#endif +#endif // PHNT_VERSION >= PHNT_WINDOWS_10_RS3 -#if (PHNT_VERSION >= PHNT_WINDOWS_SERVER_2003) NTSYSAPI VOID NTAPI RtlReleaseRelativeName( _Inout_ PRTL_RELATIVE_NAME_U RelativeName ); -#endif NTSYSAPI ULONG @@ -4765,9 +5985,9 @@ NTSTATUS NTAPI RtlDosSearchPath_Ustr( _In_ ULONG Flags, - _In_ PUNICODE_STRING Path, - _In_ PUNICODE_STRING FileName, - _In_opt_ PUNICODE_STRING DefaultExtension, + _In_ PCUNICODE_STRING Path, + _In_ PCUNICODE_STRING FileName, + _In_opt_ PCUNICODE_STRING DefaultExtension, _Out_opt_ PUNICODE_STRING StaticString, _Out_opt_ PUNICODE_STRING DynamicString, _Out_opt_ PCUNICODE_STRING *FullFileNameOut, @@ -4787,15 +6007,15 @@ 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 + _In_ ULONG Flags, + _In_ PCUNICODE_STRING OriginalName, + _In_ PCUNICODE_STRING Extension, + _In_opt_ PCUNICODE_STRING StaticString, + _In_opt_ PCUNICODE_STRING DynamicString, + _In_opt_ PCUNICODE_STRING* NewName, + _In_ PULONG NewFlags, + _In_ PSIZE_T FileNameSize, + _In_ PSIZE_T RequiredLength ); NTSYSAPI @@ -4803,7 +6023,7 @@ NTSTATUS NTAPI RtlGetLengthWithoutLastFullDosOrNtPathElement( _Reserved_ ULONG Flags, - _In_ PUNICODE_STRING PathString, + _In_ PCUNICODE_STRING PathString, _Out_ PULONG Length ); @@ -4812,7 +6032,7 @@ NTSTATUS NTAPI RtlGetLengthWithoutTrailingPathSeperators( _Reserved_ ULONG Flags, - _In_ PUNICODE_STRING PathString, + _In_ PCUNICODE_STRING PathString, _Out_ PULONG Length ); @@ -4832,7 +6052,7 @@ NTSYSAPI NTSTATUS NTAPI RtlGenerate8dot3Name( - _In_ PUNICODE_STRING Name, + _In_ PCUNICODE_STRING Name, _In_ BOOLEAN AllowExtendedCharacters, _Inout_ PGENERATE_NAME_CONTEXT Context, _Inout_ PUNICODE_STRING Name8dot3 @@ -4845,7 +6065,7 @@ NTSYSAPI NTSTATUS NTAPI RtlComputePrivatizedDllName_U( - _In_ PUNICODE_STRING DllName, + _In_ PCUNICODE_STRING DllName, _Out_ PUNICODE_STRING RealName, _Out_ PUNICODE_STRING LocalName ); @@ -4855,7 +6075,7 @@ NTSYSAPI NTSTATUS NTAPI RtlGetSearchPath( - _Out_ PWSTR *SearchPath + _Out_ PCWSTR* Path // RtlReleasePath ); // rev @@ -4872,7 +6092,7 @@ NTSTATUS NTAPI RtlGetExePath( _In_ PCWSTR DosPathName, - _Out_ PWSTR* SearchPath + _Out_ PCWSTR* Path ); // rev @@ -4935,6 +6155,25 @@ RtlWow64GetProcessMachines( #define IMAGE_FILE_NATIVE_MACHINE_AMD64 0x2 #define IMAGE_FILE_NATIVE_MACHINE_ARMNT 0x4 #define IMAGE_FILE_NATIVE_MACHINE_ARM64 0x8 +#define IMAGE_FILE_NATIVE_MACHINE_ARM64EC 0x10 + +#if !defined(NTDDI_WIN11_BR) || (NTDDI_VERSION < NTDDI_WIN11_BR) +// private +typedef struct _IMAGE_FILE_MACHINES +{ + union + { + ULONG Value; + struct + { + ULONG MachineX86 : 1; + ULONG MachineAmd64 : 1; + ULONG MachineArm : 1; + ULONG MachineArm64 : 1; + ULONG MachineArm64EC : 1; + } DUMMYSTRUCTNAME; + } DUMMYUNIONNAME; +} IMAGE_FILE_MACHINES; // rev NTSYSAPI @@ -4942,48 +6181,20 @@ NTSTATUS NTAPI RtlGetImageFileMachines( _In_ PCWSTR FileName, - _Out_ PUSHORT FileMachines + _Out_ IMAGE_FILE_MACHINES *MachineTypeFlags ); +#endif // #if !defined(NTDDI_WIN11_BR) || (NTDDI_VERSION < NTDDI_WIN11_BR) #endif // PHNT_VERSION >= PHNT_WINDOWS_11 #if (PHNT_VERSION >= PHNT_WINDOWS_10_RS2) - -#ifdef PHNT_INLINE_TYPEDEFS // 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 // PHNT_INLINE_TYPEDEFS -#ifdef PHNT_INLINE_TYPEDEFS -// rev -FORCEINLINE -BOOLEAN -NTAPI -RtlAreLongPathsEnabled( - VOID - ) -{ - return NtCurrentPeb()->IsLongPathAwareProcess; -} -#else // rev NTSYSAPI BOOLEAN @@ -4991,8 +6202,6 @@ NTAPI RtlAreLongPathsEnabled( VOID ); -#endif // PHNT_INLINE_TYPEDEFS - #endif // PHNT_VERSION >= PHNT_WINDOWS_10_RS2 NTSYSAPI @@ -5005,7 +6214,7 @@ RtlIsThreadWithinLoaderCallout( /** * Gets a value indicating whether the process is currently in the shutdown phase. * - * @return TRUE if a shutdown of the current dll process is in progress; otherwise, FALSE. + * \return TRUE if a shutdown of the current dll process is in progress; otherwise, FALSE. */ NTSYSAPI BOOLEAN @@ -5014,7 +6223,9 @@ RtlDllShutdownInProgress( VOID ); +// // Heaps +// typedef struct _RTL_HEAP_ENTRY { @@ -5110,7 +6321,9 @@ typedef struct _RTL_PROCESS_HEAPS_V2 _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 { @@ -5128,7 +6341,8 @@ typedef enum _HEAP_MEMORY_INFO_CLASS HeapMemoryBasicInformation } HEAP_MEMORY_INFO_CLASS; -typedef NTSTATUS ALLOCATE_VIRTUAL_MEMORY_EX_CALLBACK( +typedef _Function_class_(ALLOCATE_VIRTUAL_MEMORY_EX_CALLBACK) +NTSTATUS NTAPI 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, @@ -5138,20 +6352,20 @@ typedef NTSTATUS ALLOCATE_VIRTUAL_MEMORY_EX_CALLBACK( _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( +typedef _Function_class_(FREE_VIRTUAL_MEMORY_EX_CALLBACK) +NTSTATUS NTAPI 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( +typedef _Function_class_(QUERY_VIRTUAL_MEMORY_CALLBACK) +NTSTATUS NTAPI QUERY_VIRTUAL_MEMORY_CALLBACK( _Inout_ HANDLE CallbackContext, _In_ HANDLE ProcessHandle, _In_opt_ PVOID BaseAddress, @@ -5160,7 +6374,6 @@ typedef NTSTATUS QUERY_VIRTUAL_MEMORY_CALLBACK( _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 @@ -5200,18 +6413,16 @@ typedef struct _RTL_SEGMENT_HEAP_PARAMETERS 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( +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 @@ -5268,20 +6479,20 @@ typedef struct _RTL_HEAP_PARAMETERS * The RtlCreateHeap routine creates a heap object that can be used by the calling process. This routine reserves * space in the virtual address space of the process and allocates physical storage for a specified initial portion of this block. * - * @param Flags Flags specifying optional attributes of the heap. - * @param HeapBase If HeapBase is a non-NULL value, it specifies the base address for a block of caller-allocated memory to use for the heap. - * @param ReserveSize If ReserveSize is a nonzero value, it specifies the initial amount of memory, in bytes, to reserve for the heap. - * @param CommitSize If CommitSize is a nonzero value, it specifies the initial amount of memory, in bytes, to commit for the heap. - * @param Lock Pointer to an opaque structure to be used as the heap lock. - * @param Parameters Pointer to a RTL_HEAP_PARAMETERS structure that contains parameters to be applied when creating the heap. - * @return RtlCreateHeap returns a handle to be used in accessing the created heap. + * \param Flags Flags specifying optional attributes of the heap. + * \param HeapBase If HeapBase is a non-NULL value, it specifies the base address for a block of caller-allocated memory to use for the heap. + * \param ReserveSize If ReserveSize is a nonzero value, it specifies the initial amount of memory, in bytes, to reserve for the heap. + * \param CommitSize If CommitSize is a nonzero value, it specifies the initial amount of memory, in bytes, to commit for the heap. + * \param Lock Pointer to an opaque structure to be used as the heap lock. + * \param Parameters Pointer to a RTL_HEAP_PARAMETERS structure that contains parameters to be applied when creating the heap. + * \return RtlCreateHeap returns a handle to be used in accessing the created heap. * \remarks https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/ntifs/nf-ntifs-rtlcreateheap */ _Success_(return != 0) _Must_inspect_result_ _Ret_maybenull_ NTSYSAPI -PVOID +HANDLE NTAPI RtlCreateHeap( _In_ ULONG Flags, @@ -5298,8 +6509,8 @@ RtlCreateHeap( * The RtlDestroyHeap routine destroys the specified heap object. RtlDestroyHeap decommits and releases all the pages of a private heap object, * and it invalidates the handle to the heap. * - * @param HeapHandle Handle for the heap to be destroyed. This parameter is a heap handle returned by RtlCreateHeap. - * @return If the call to RtlDestroyHeap succeeds, the return value is a NULL pointer. If the call to RtlDestroyHeap fails, the return value is a handle for the heap. + * \param HeapHandle Handle for the heap to be destroyed. This parameter is a heap handle returned by RtlCreateHeap. + * \return If the call to RtlDestroyHeap succeeds, the return value is a NULL pointer. If the call to RtlDestroyHeap fails, the return value is a handle for the heap. * \remarks https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/ntifs/nf-ntifs-rtldestroyheap */ _Success_(return == 0) @@ -5307,31 +6518,31 @@ NTSYSAPI PVOID NTAPI RtlDestroyHeap( - _In_ _Post_invalid_ PVOID HeapHandle + _In_ _Post_invalid_ HANDLE HeapHandle ); /** * The RtlAllocateHeap routine allocates a block of memory from a heap. * - * @param HeapHandle Handle for a private heap from which the memory will be allocated. - * @param Flags Controllable aspects of heap allocation. Specifying any flags will override the corresponding value specified when the heap was created with RtlCreateHeap. - * @param Size Number of bytes to be allocated. If the heap, specified by the HeapHandle parameter, is a nongrowable heap, Size must be less than or equal to the heap's virtual memory threshold. - * @return If the call to RtlAllocateHeap succeeds, the return value is a pointer to the newly-allocated block. The return value is NULL if the allocation failed. + * \param HeapHandle Handle for a private heap from which the memory will be allocated. + * \param Flags Controllable aspects of heap allocation. Specifying any flags will override the corresponding value specified when the heap was created with RtlCreateHeap. + * \param Size Number of bytes to be allocated. If the heap, specified by the HeapHandle parameter, is a nongrowable heap, Size must be less than or equal to the heap's virtual memory threshold. + * \return If the call to RtlAllocateHeap succeeds, the return value is a pointer to the newly-allocated block. The return value is NULL if the allocation failed. * \remarks https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/ntifs/nf-ntifs-rtlallocateheap */ -NTSYSAPI _Success_(return != 0) _Must_inspect_result_ _Ret_maybenull_ _Post_writable_byte_size_(Size) __drv_allocatesMem(Mem) +NTSYSAPI DECLSPEC_ALLOCATOR DECLSPEC_NOALIAS DECLSPEC_RESTRICT PVOID NTAPI RtlAllocateHeap( - _In_ PVOID HeapHandle, + _In_ HANDLE HeapHandle, _In_opt_ ULONG Flags, _In_ SIZE_T Size ); @@ -5342,7 +6553,7 @@ NTSYSAPI LOGICAL NTAPI RtlFreeHeap( - _In_ PVOID HeapHandle, + _In_ HANDLE HeapHandle, _In_opt_ ULONG Flags, _Frees_ptr_opt_ _Post_invalid_ PVOID BaseAddress ); @@ -5352,7 +6563,7 @@ NTSYSAPI BOOLEAN NTAPI RtlFreeHeap( - _In_ PVOID HeapHandle, + _In_ HANDLE HeapHandle, _In_opt_ ULONG Flags, _Frees_ptr_opt_ PVOID BaseAddress ); @@ -5362,16 +6573,16 @@ NTSYSAPI SIZE_T NTAPI RtlSizeHeap( - _In_ PVOID HeapHandle, + _In_ HANDLE HeapHandle, _In_ ULONG Flags, - _In_ PVOID BaseAddress + _In_ PCVOID BaseAddress ); NTSYSAPI NTSTATUS NTAPI RtlZeroHeap( - _In_ PVOID HeapHandle, + _In_ HANDLE HeapHandle, _In_ ULONG Flags ); @@ -5379,7 +6590,7 @@ NTSYSAPI VOID NTAPI RtlProtectHeap( - _In_ PVOID HeapHandle, + _In_ HANDLE HeapHandle, _In_ BOOLEAN MakeReadOnly ); @@ -5389,29 +6600,29 @@ NTSYSAPI BOOLEAN NTAPI RtlLockHeap( - _In_ PVOID HeapHandle + _In_ HANDLE HeapHandle ); NTSYSAPI BOOLEAN NTAPI RtlUnlockHeap( - _In_ PVOID HeapHandle + _In_ HANDLE HeapHandle ); -NTSYSAPI _Success_(return != 0) _Must_inspect_result_ _Ret_maybenull_ _Post_writable_byte_size_(Size) _When_(Size > 0, __drv_allocatesMem(Mem)) +NTSYSAPI DECLSPEC_ALLOCATOR DECLSPEC_NOALIAS DECLSPEC_RESTRICT PVOID NTAPI RtlReAllocateHeap( - _In_ PVOID HeapHandle, + _In_ HANDLE HeapHandle, _In_ ULONG Flags, _Frees_ptr_opt_ PVOID BaseAddress, _In_ SIZE_T Size @@ -5421,7 +6632,7 @@ NTSYSAPI BOOLEAN NTAPI RtlGetUserInfoHeap( - _In_ PVOID HeapHandle, + _In_ HANDLE HeapHandle, _In_ ULONG Flags, _In_ PVOID BaseAddress, _Out_opt_ PVOID *UserValue, @@ -5432,7 +6643,7 @@ NTSYSAPI BOOLEAN NTAPI RtlSetUserValueHeap( - _In_ PVOID HeapHandle, + _In_ HANDLE HeapHandle, _In_ ULONG Flags, _In_ PVOID BaseAddress, _In_ PVOID UserValue @@ -5442,7 +6653,7 @@ NTSYSAPI BOOLEAN NTAPI RtlSetUserFlagsHeap( - _In_ PVOID HeapHandle, + _In_ HANDLE HeapHandle, _In_ ULONG Flags, _In_ PVOID BaseAddress, _In_ ULONG UserFlagsReset, @@ -5462,7 +6673,7 @@ NTSYSAPI ULONG NTAPI RtlCreateTagHeap( - _In_ PVOID HeapHandle, + _In_ HANDLE HeapHandle, _In_ ULONG Flags, _In_opt_ PCWSTR TagPrefix, _In_ PCWSTR TagNames @@ -5472,7 +6683,7 @@ NTSYSAPI PWSTR NTAPI RtlQueryTagHeap( - _In_ PVOID HeapHandle, + _In_ HANDLE HeapHandle, _In_ ULONG Flags, _In_ USHORT TagIndex, _In_ BOOLEAN ResetCounters, @@ -5483,7 +6694,7 @@ NTSYSAPI NTSTATUS NTAPI RtlExtendHeap( - _In_ PVOID HeapHandle, + _In_ HANDLE HeapHandle, _In_ ULONG Flags, _In_ PVOID Base, _In_ SIZE_T Size @@ -5493,7 +6704,7 @@ NTSYSAPI SIZE_T NTAPI RtlCompactHeap( - _In_ PVOID HeapHandle, + _In_ HANDLE HeapHandle, _In_ ULONG Flags ); @@ -5501,7 +6712,7 @@ NTSYSAPI BOOLEAN NTAPI RtlValidateHeap( - _In_opt_ PVOID HeapHandle, + _In_opt_ HANDLE HeapHandle, _In_ ULONG Flags, _In_opt_ PVOID BaseAddress ); @@ -5521,9 +6732,9 @@ RtlGetProcessHeaps( _Out_ PVOID *ProcessHeaps ); -_Function_class_(RTL_ENUM_HEAPS_ROUTINE) -typedef NTSTATUS (NTAPI RTL_ENUM_HEAPS_ROUTINE)( - _In_ PVOID HeapHandle, +typedef _Function_class_(RTL_ENUM_HEAPS_ROUTINE) +NTSTATUS NTAPI RTL_ENUM_HEAPS_ROUTINE( + _In_ HANDLE HeapHandle, _In_ PVOID Parameter ); typedef RTL_ENUM_HEAPS_ROUTINE *PRTL_ENUM_HEAPS_ROUTINE; @@ -5565,7 +6776,7 @@ NTSYSAPI NTSTATUS NTAPI RtlUsageHeap( - _In_ PVOID HeapHandle, + _In_ HANDLE HeapHandle, _In_ ULONG Flags, _Inout_ PRTL_HEAP_USAGE Usage ); @@ -5600,7 +6811,7 @@ NTSYSAPI NTSTATUS NTAPI RtlWalkHeap( - _In_ PVOID HeapHandle, + _In_ HANDLE HeapHandle, _Inout_ PRTL_HEAP_WALK_ENTRY Entry ); @@ -5609,7 +6820,7 @@ RtlWalkHeap( #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 HeapTaggingInformation 0x4 // q: RTLP_HEAP_TAGGING_INFO #define HeapStackDatabase 0x5 // q: RTL_HEAP_STACK_QUERY; s: RTL_HEAP_STACK_CONTROL #define HeapMemoryLimit 0x6 // since 19H2 #define HeapTag 0x7 // since 20H1 @@ -5618,23 +6829,25 @@ RtlWalkHeap( typedef enum _HEAP_COMPATIBILITY_MODE { - HEAP_COMPATIBILITY_STANDARD = 0UL, - HEAP_COMPATIBILITY_LAL = 1UL, - HEAP_COMPATIBILITY_LFH = 2UL, + HEAP_COMPATIBILITY_MODE_STANDARD = 0UL, + HEAP_COMPATIBILITY_MODE_LAL = 1UL, // Lookaside list heap (LAL) compatibility mode. + HEAP_COMPATIBILITY_MODE_LFH = 2UL, // Low-fragmentation heap (LFH) compatibility mode. } HEAP_COMPATIBILITY_MODE; typedef struct _RTLP_TAG_INFO { GUID Id; - ULONG_PTR CurrentAllocatedBytes; + SIZE_T CurrentAllocatedBytes; } RTLP_TAG_INFO, *PRTLP_TAG_INFO; +#define RTLP_HEAP_TAGGING_INFO_VERSION 0x1 + typedef struct _RTLP_HEAP_TAGGING_INFO { USHORT Version; - USHORT Flags; - PVOID ProcessHandle; - ULONG_PTR EntriesCount; + USHORT Flags; // 1: Multiple Tags, 2: Single Tag + Hash + HANDLE ProcessHandle; + SIZE_T EntriesCount; RTLP_TAG_INFO Entries[1]; } RTLP_HEAP_TAGGING_INFO, *PRTLP_HEAP_TAGGING_INFO; @@ -5688,7 +6901,7 @@ typedef struct _SEGMENT_HEAP_PERFORMANCE_COUNTER_INFORMATION { SIZE_T SegmentReserveSize; SIZE_T SegmentCommitSize; - ULONG_PTR SegmentCount; + SIZE_T SegmentCount; SIZE_T AllocatedSize; SIZE_T LargeAllocReserveSize; SIZE_T LargeAllocCommitSize; @@ -5735,10 +6948,12 @@ typedef struct _HEAP_INFORMATION_ITEM }; } HEAP_INFORMATION_ITEM, *PHEAP_INFORMATION_ITEM; -typedef NTSTATUS (NTAPI *PRTL_HEAP_EXTENDED_ENUMERATION_ROUTINE)( +typedef _Function_class_(RTL_HEAP_EXTENDED_ENUMERATION_ROUTINE) +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 @@ -5751,7 +6966,7 @@ typedef NTSTATUS (NTAPI *PRTL_HEAP_EXTENDED_ENUMERATION_ROUTINE)( typedef struct _HEAP_EXTENDED_INFORMATION { HANDLE ProcessHandle; - PVOID HeapHandle; + HANDLE HeapHandle; ULONG Level; PRTL_HEAP_EXTENDED_ENUMERATION_ROUTINE CallbackRoutine; PVOID CallbackContext; @@ -5763,11 +6978,13 @@ typedef struct _HEAP_EXTENDED_INFORMATION } HEAP_EXTENDED_INFORMATION, *PHEAP_EXTENDED_INFORMATION; // rev -typedef NTSTATUS (NTAPI *RTL_HEAP_STACK_WRITE_ROUTINE)( +typedef _Function_class_(RTL_HEAP_STACK_WRITE_ROUTINE) +NTSTATUS NTAPI RTL_HEAP_STACK_WRITE_ROUTINE( _In_ PVOID Information, // TODO: 3 missing structures (dmex) _In_ ULONG Size, _In_opt_ PVOID Context ); +typedef RTL_HEAP_STACK_WRITE_ROUTINE* PRTL_HEAP_STACK_WRITE_ROUTINE; // rev typedef struct _RTLP_HEAP_STACK_TRACE_SERIALIZATION_INIT @@ -5807,7 +7024,7 @@ typedef struct _RTL_HEAP_STACK_QUERY { ULONG Version; HANDLE ProcessHandle; - RTL_HEAP_STACK_WRITE_ROUTINE WriteRoutine; + PRTL_HEAP_STACK_WRITE_ROUTINE WriteRoutine; PVOID SerializationContext; UCHAR QueryLevel; UCHAR Flags; @@ -5825,22 +7042,26 @@ typedef struct _RTL_HEAP_STACK_CONTROL } RTL_HEAP_STACK_CONTROL, *PRTL_HEAP_STACK_CONTROL; // rev -typedef NTSTATUS (NTAPI *PRTL_HEAP_DEBUGGING_INTERCEPTOR_ROUTINE)( - _In_ PVOID HeapHandle, +typedef _Function_class_(RTL_HEAP_DEBUGGING_INTERCEPTOR_ROUTINE) +NTSTATUS NTAPI RTL_HEAP_DEBUGGING_INTERCEPTOR_ROUTINE( + _In_ HANDLE HeapHandle, _In_ ULONG Action, _In_ ULONG StackFramesToCapture, _In_ PVOID *StackTrace ); +typedef RTL_HEAP_DEBUGGING_INTERCEPTOR_ROUTINE* PRTL_HEAP_DEBUGGING_INTERCEPTOR_ROUTINE; // rev -typedef NTSTATUS (NTAPI *PRTL_HEAP_LEAK_ENUMERATION_ROUTINE)( +typedef _Function_class_(RTL_HEAP_LEAK_ENUMERATION_ROUTINE) +NTSTATUS NTAPI RTL_HEAP_LEAK_ENUMERATION_ROUTINE( _In_ LONG Reserved, - _In_ PVOID HeapHandle, + _In_ HANDLE HeapHandle, _In_ PVOID BaseAddress, _In_ SIZE_T BlockSize, _In_ ULONG StackTraceDepth, _In_ PVOID *StackTrace ); +typedef RTL_HEAP_LEAK_ENUMERATION_ROUTINE* PRTL_HEAP_LEAK_ENUMERATION_ROUTINE; // symbols typedef struct _HEAP_DEBUGGING_INFORMATION @@ -5858,7 +7079,7 @@ NTSYSAPI NTSTATUS NTAPI RtlQueryHeapInformation( - _In_opt_ PVOID HeapHandle, + _In_opt_ HANDLE HeapHandle, _In_ HEAP_INFORMATION_CLASS HeapInformationClass, _Out_opt_ PVOID HeapInformation, _In_opt_ SIZE_T HeapInformationLength, @@ -5869,7 +7090,7 @@ NTSYSAPI NTSTATUS NTAPI RtlSetHeapInformation( - _In_opt_ PCVOID HeapHandle, + _In_opt_ HANDLE HeapHandle, _In_ HEAP_INFORMATION_CLASS HeapInformationClass, _In_opt_ PCVOID HeapInformation, _In_opt_ SIZE_T HeapInformationLength @@ -5879,7 +7100,7 @@ NTSYSAPI ULONG NTAPI RtlMultipleAllocateHeap( - _In_ PCVOID HeapHandle, + _In_ HANDLE HeapHandle, _In_ ULONG Flags, _In_ SIZE_T Size, _In_ ULONG Count, @@ -5890,20 +7111,18 @@ NTSYSAPI ULONG NTAPI RtlMultipleFreeHeap( - _In_ PCVOID HeapHandle, + _In_ HANDLE HeapHandle, _In_ ULONG Flags, _In_ ULONG Count, _In_ PVOID *Array ); -#if (PHNT_VERSION >= PHNT_WINDOWS_7) NTSYSAPI VOID NTAPI RtlDetectHeapLeaks( VOID ); -#endif // PHNT_VERSION >= PHNT_WINDOWS_7 NTSYSAPI VOID @@ -5912,7 +7131,9 @@ RtlFlushHeaps( VOID ); +// // Memory zones +// // begin_private @@ -5932,8 +7153,6 @@ typedef struct _RTL_MEMORY_ZONE PRTL_MEMORY_ZONE_SEGMENT FirstSegment; } RTL_MEMORY_ZONE, *PRTL_MEMORY_ZONE; -#if (PHNT_VERSION >= PHNT_WINDOWS_VISTA) - NTSYSAPI NTSTATUS NTAPI @@ -5980,14 +7199,10 @@ RtlUnlockMemoryZone( _In_ PVOID MemoryZone ); -#endif // PHNT_VERSION >= PHNT_WINDOWS_VISTA - // // Memory block lookaside lists // -#if (PHNT_VERSION >= PHNT_WINDOWS_VISTA) - NTSYSAPI NTSTATUS NTAPI @@ -6052,15 +7267,12 @@ RtlUnlockMemoryBlockLookaside( _In_ PVOID MemoryBlockLookaside ); -#endif // PHNT_VERSION >= PHNT_WINDOWS_VISTA - // end_private // // Transactions // -#if (PHNT_VERSION >= PHNT_WINDOWS_VISTA) // private NTSYSAPI HANDLE @@ -6069,9 +7281,7 @@ RtlGetCurrentTransaction( _In_opt_ PCWSTR ExistingFileName, _In_opt_ PCWSTR NewFileName ); -#endif -#if (PHNT_VERSION >= PHNT_WINDOWS_VISTA) // private NTSYSAPI LOGICAL @@ -6079,13 +7289,15 @@ NTAPI RtlSetCurrentTransaction( _In_opt_ HANDLE TransactionHandle ); -#endif // // LUIDs // -FORCEINLINE BOOLEAN RtlIsEqualLuid( // RtlEqualLuid +FORCEINLINE +BOOLEAN +NTAPI_INLINE +RtlIsEqualLuid( // RtlEqualLuid _In_ PLUID L1, _In_ PLUID L2 ) @@ -6094,7 +7306,10 @@ FORCEINLINE BOOLEAN RtlIsEqualLuid( // RtlEqualLuid L1->HighPart == L2->HighPart; } -FORCEINLINE BOOLEAN RtlIsZeroLuid( +FORCEINLINE +BOOLEAN +NTAPI_INLINE +RtlIsZeroLuid( _In_ PLUID L1 ) { @@ -6179,7 +7394,9 @@ RtlCopyLuidAndAttributesArray( _In_ PLUID_AND_ATTRIBUTES Dest ); +// // Byte swap routines. +// #ifndef PHNT_RTL_BYTESWAP #define RtlUshortByteSwap(_x) _byteswap_ushort((USHORT)(_x)) @@ -6242,7 +7459,9 @@ RtlEnlargedUnsignedMultiply( _In_ ULONG Multiplier ); +// // Debugging +// // private typedef struct _RTL_PROCESS_MODULES *PRTL_PROCESS_MODULES; @@ -6304,8 +7523,6 @@ RtlDestroyQueryDebugBuffer( _In_ PRTL_DEBUG_INFORMATION Buffer ); -#if (PHNT_VERSION >= PHNT_WINDOWS_VISTA) - // private NTSYSAPI PVOID @@ -6325,8 +7542,6 @@ RtlDeCommitDebugInfo( _In_ SIZE_T Size ); -#endif // PHNT_VERSION >= PHNT_WINDOWS_VISTA - #define RTL_QUERY_PROCESS_MODULES 0x00000001 #define RTL_QUERY_PROCESS_BACKTRACES 0x00000002 #define RTL_QUERY_PROCESS_HEAP_SUMMARY 0x00000004 @@ -6363,7 +7578,7 @@ RtlSetProcessDebugInformation( // rev FORCEINLINE BOOLEAN -NTAPI +NTAPI_INLINE RtlIsAnyDebuggerPresent( VOID ) @@ -6475,7 +7690,9 @@ RtlLoadString( _Inout_opt_ PULONG ReturnLanguageLen ); +// // Errors +// _When_(Status < 0, _Out_range_(>, 0)) _When_(Status >= 0, _Out_range_(==, 0)) @@ -6502,6 +7719,8 @@ RtlGetLastNtStatus( VOID ); +_Check_return_ +_Post_equals_last_error_ NTSYSAPI LONG NTAPI @@ -6549,10 +7768,10 @@ RtlSetThreadErrorMode( _Out_opt_ PULONG OldMode ); +// // Windows Error Reporting +// -#if (PHNT_VERSION >= PHNT_WINDOWS_VISTA) -// private NTSYSAPI NTSTATUS NTAPI @@ -6561,7 +7780,6 @@ RtlReportException( _In_ PCONTEXT ContextRecord, _In_ ULONG Flags ); -#endif // PHNT_VERSION >= PHNT_WINDOWS_VISTA #if (PHNT_VERSION >= PHNT_WINDOWS_10_RS1) // rev @@ -6576,8 +7794,6 @@ RtlReportExceptionEx( ); #endif // PHNT_VERSION >= PHNT_WINDOWS_10_RS1 -#if (PHNT_VERSION >= PHNT_WINDOWS_VISTA) -// private NTSYSAPI NTSTATUS NTAPI @@ -6587,9 +7803,7 @@ RtlWerpReportException( _In_ ULONG Flags, _Out_ PHANDLE CrashVerticalProcessHandle ); -#endif // PHNT_VERSION >= PHNT_WINDOWS_VISTA -#if (PHNT_VERSION >= PHNT_WINDOWS_7) // rev NTSYSAPI NTSTATUS @@ -6598,7 +7812,6 @@ RtlReportSilentProcessExit( _In_ HANDLE ProcessHandle, _In_ NTSTATUS ExitStatus ); -#endif // PHNT_VERSION >= PHNT_WINDOWS_7 // // Random @@ -6634,7 +7847,7 @@ NTSTATUS NTAPI RtlComputeImportTableHash( _In_ HANDLE FileHandle, - _Out_writes_bytes_(16) PCHAR Hash, + _Out_writes_bytes_(16) PUCHAR Hash, _In_ ULONG ImportTableHashRevision // must be 1 ); @@ -6706,13 +7919,13 @@ RtlInt64ToUnicodeString( #define RtlIntPtrToUnicodeString(Value, Base, String) RtlInt64ToUnicodeString(Value, Base, String) #else #define RtlIntPtrToUnicodeString(Value, Base, String) RtlIntegerToUnicodeString(Value, Base, String) -#endif +#endif // _WIN64 NTSYSAPI NTSTATUS NTAPI RtlUnicodeStringToInteger( - _In_ PUNICODE_STRING String, + _In_ PCUNICODE_STRING String, _In_opt_ ULONG Base, _Out_ PULONG Value ); @@ -6741,7 +7954,7 @@ typedef struct in_addr #define s_impno S_un.S_un_b.s_b4 // imp # #define s_lh S_un.S_un_b.s_b3 // logical host } IN_ADDR, * PIN_ADDR, FAR* LPIN_ADDR; -#endif +#endif // s_addr #ifndef s6_addr // @@ -6762,13 +7975,21 @@ typedef struct in6_addr #define s6_bytes u.Byte #define s6_words u.Word } IN6_ADDR, *PIN6_ADDR, FAR *LPIN6_ADDR; -#endif +#endif // s6_addr 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 +PSTR +NTAPI +RtlIpv4AddressToStringA( + _In_ PCIN_ADDR Address, + _Out_writes_(16) PSTR AddressString + ); + NTSYSAPI PWSTR NTAPI @@ -6777,6 +7998,16 @@ RtlIpv4AddressToStringW( _Out_writes_(16) PWSTR AddressString ); +NTSYSAPI +NTSTATUS +NTAPI +RtlIpv4AddressToStringExA( + _In_ PCIN_ADDR Address, + _In_ USHORT Port, + _Out_writes_to_(*AddressStringLength, *AddressStringLength) PSTR AddressString, + _Inout_ PULONG AddressStringLength + ); + NTSYSAPI NTSTATUS NTAPI @@ -6787,6 +8018,14 @@ RtlIpv4AddressToStringExW( _Inout_ PULONG AddressStringLength ); +NTSYSAPI +PSTR +NTAPI +RtlIpv6AddressToStringA( + _In_ PCIN6_ADDR Address, + _Out_writes_(46) PSTR AddressString + ); + NTSYSAPI PWSTR NTAPI @@ -6795,6 +8034,17 @@ RtlIpv6AddressToStringW( _Out_writes_(46) PWSTR AddressString ); +NTSYSAPI +NTSTATUS +NTAPI +RtlIpv6AddressToStringExA( + _In_ PCIN6_ADDR Address, + _In_ ULONG ScopeId, + _In_ USHORT Port, + _Out_writes_to_(*AddressStringLength, *AddressStringLength) PSTR AddressString, + _Inout_ PULONG AddressStringLength + ); + NTSYSAPI NTSTATUS NTAPI @@ -6806,16 +8056,36 @@ RtlIpv6AddressToStringExW( _Inout_ PULONG AddressStringLength ); +NTSYSAPI +NTSTATUS +NTAPI +RtlIpv4StringToAddressA( + _In_ PCSTR AddressString, + _In_ BOOLEAN Strict, + _Out_ PCSTR *Terminator, + _Out_ PIN_ADDR Address + ); + NTSYSAPI NTSTATUS NTAPI RtlIpv4StringToAddressW( _In_ PCWSTR AddressString, _In_ BOOLEAN Strict, - _Out_ LPCWSTR *Terminator, + _Out_ PCWSTR *Terminator, _Out_ PIN_ADDR Address ); +NTSYSAPI +NTSTATUS +NTAPI +RtlIpv4StringToAddressExA( + _In_ PCSTR AddressString, + _In_ BOOLEAN Strict, + _Out_ PIN_ADDR Address, + _Out_ PUSHORT Port + ); + NTSYSAPI NTSTATUS NTAPI @@ -6826,6 +8096,15 @@ RtlIpv4StringToAddressExW( _Out_ PUSHORT Port ); +NTSYSAPI +NTSTATUS +NTAPI +RtlIpv6StringToAddressA( + _In_ PCSTR AddressString, + _Out_ PCSTR *Terminator, + _Out_ PIN6_ADDR Address + ); + NTSYSAPI NTSTATUS NTAPI @@ -6835,6 +8114,16 @@ RtlIpv6StringToAddressW( _Out_ PIN6_ADDR Address ); +NTSYSAPI +NTSTATUS +NTAPI +RtlIpv6StringToAddressExA( + _In_ PCSTR AddressString, + _Out_ PIN6_ADDR Address, + _Out_ PULONG ScopeId, + _Out_ PUSHORT Port + ); + NTSYSAPI NTSTATUS NTAPI @@ -6854,7 +8143,9 @@ RtlIpv6StringToAddressExW( #define RtlIpv6StringToAddress RtlIpv6StringToAddressW #define RtlIpv6StringToAddressEx RtlIpv6StringToAddressExW +// // Time +// typedef struct _TIME_FIELDS { @@ -6984,16 +8275,27 @@ RtlGetInterruptTimePrecise( #if (PHNT_VERSION >= PHNT_WINDOWS_8) NTSYSAPI -BOOLEAN +ULONGLONG NTAPI RtlQueryUnbiasedInterruptTime( _Out_ PLARGE_INTEGER InterruptTime ); #endif // PHNT_VERSION >= PHNT_WINDOWS_8 -FORCEINLINE +#if (PHNT_VERSION >= PHNT_WINDOWS_11_24H2) +// rev +NTSYSAPI ULONGLONG NTAPI +RtlQueryUnbiasedInterruptTimePrecise( + _Out_ PLARGE_INTEGER InterruptTime + ); +#endif // PHNT_VERSION >= PHNT_WINDOWS_11_24H2 + +#if (PHNT_VERSION >= PHNT_WINDOWS_11) +FORCEINLINE +ULONGLONG +NTAPI_INLINE RtlBeginReadTickLock( _In_ PULONGLONG TimeUpdateLock // USER_SHARED_DATA->TimeUpdateLock ) @@ -7007,6 +8309,7 @@ RtlBeginReadTickLock( return result; } +#endif // PHNT_VERSION >= PHNT_WINDOWS_11 // // Time zones @@ -7092,7 +8395,7 @@ RtlClearBit( _In_ PRTL_BITMAP BitMapHeader, _In_range_(<, BitMapHeader->SizeOfBitMap) ULONG BitNumber ); -#endif +#endif // PHNT_MODE == PHNT_MODE_KERNEL || PHNT_VERSION >= PHNT_WINDOWS_8 #if (PHNT_MODE == PHNT_MODE_KERNEL || PHNT_VERSION >= PHNT_WINDOWS_8) NTSYSAPI @@ -7102,7 +8405,7 @@ RtlSetBit( _In_ PRTL_BITMAP BitMapHeader, _In_range_(<, BitMapHeader->SizeOfBitMap) ULONG BitNumber ); -#endif +#endif // PHNT_MODE == PHNT_MODE_KERNEL || PHNT_VERSION >= PHNT_WINDOWS_8 _Check_return_ NTSYSAPI @@ -7236,6 +8539,7 @@ RtlFindFirstRunClear( _Check_return_ FORCEINLINE BOOLEAN +NTAPI_INLINE RtlCheckBit( _In_ PRTL_BITMAP BitMapHeader, _In_range_(<, BitMapHeader->SizeOfBitMap) ULONG BitPosition @@ -7245,7 +8549,7 @@ RtlCheckBit( return BitTest64((LONG64 const *)BitMapHeader->Buffer, (LONG64)BitPosition); #else return (((PLONG)BitMapHeader->Buffer)[BitPosition / 32] >> (BitPosition % 32)) & 0x1; -#endif +#endif // _WIN64 } NTSYSAPI @@ -7300,8 +8604,6 @@ RtlFindLastBackwardRunClear( _Out_ PULONG StartingRunIndex ); -#if (PHNT_VERSION >= PHNT_WINDOWS_VISTA) - NTSYSAPI ULONG NTAPI @@ -7309,10 +8611,6 @@ RtlNumberOfSetBitsUlongPtr( _In_ ULONG_PTR Target ); -#endif // PHNT_VERSION >= PHNT_WINDOWS_VISTA - -#if (PHNT_VERSION >= PHNT_WINDOWS_7) - // rev NTSYSAPI VOID @@ -7333,8 +8631,6 @@ RtlInterlockedSetBitRun( _In_range_(0, BitMapHeader->SizeOfBitMap - StartingIndex) ULONG NumberToSet ); -#endif // PHNT_VERSION >= PHNT_WINDOWS_7 - #if (PHNT_VERSION >= PHNT_WINDOWS_8) NTSYSAPI @@ -7542,7 +8838,7 @@ NTSTATUS NTAPI RtlCreateAtomTable( _In_ ULONG NumberOfBuckets, - _Out_ PVOID *AtomTableHandle + _Inout_ PVOID *AtomTableHandle ); NTSYSAPI @@ -7606,7 +8902,6 @@ RtlQueryAtomInAtomTable( _Inout_opt_ PULONG AtomNameLength ); -#if (PHNT_VERSION >= PHNT_WINDOWS_VISTA) // rev NTSYSAPI BOOLEAN @@ -7615,7 +8910,6 @@ RtlGetIntegerAtom( _In_ PCWSTR AtomName, _Out_opt_ PUSHORT IntegerAtom ); -#endif // PHNT_VERSION >= PHNT_WINDOWS_VISTA // // SIDs @@ -7765,21 +9059,15 @@ RtlCopySidAndAttributesArray( _Out_ PULONG RemainingSidAreaSize ); -#if (PHNT_VERSION >= PHNT_WINDOWS_VISTA) - NTSYSAPI NTSTATUS NTAPI RtlCreateServiceSid( - _In_ PUNICODE_STRING ServiceName, + _In_ PCUNICODE_STRING ServiceName, _Out_writes_bytes_opt_(*ServiceSidLength) PSID ServiceSid, _Inout_ PULONG ServiceSidLength ); -#endif // PHNT_VERSION >= PHNT_WINDOWS_VISTA - -#if (PHNT_VERSION >= PHNT_WINDOWS_VISTA) - // private NTSYSAPI NTSTATUS @@ -7790,10 +9078,7 @@ RtlSidDominates( _Out_ PBOOLEAN Dominates ); -#endif // PHNT_VERSION >= PHNT_WINDOWS_VISTA - #if (PHNT_VERSION >= PHNT_WINDOWS_8_1) - // rev NTSYSAPI NTSTATUS @@ -7803,10 +9088,8 @@ RtlSidDominatesForTrust( _In_ PSID Sid2, _Out_ PBOOLEAN DominatesTrust // TokenProcessTrustLevel ); - #endif // PHNT_VERSION >= PHNT_WINDOWS_8_1 -#if (PHNT_VERSION >= PHNT_WINDOWS_VISTA) // private NTSYSAPI NTSTATUS @@ -7826,21 +9109,17 @@ RtlSidIsHigherLevel( _In_ PSID Sid2, _Out_ PBOOLEAN HigherLevel ); -#endif // PHNT_VERSION >= PHNT_WINDOWS_VISTA -#if (PHNT_VERSION >= PHNT_WINDOWS_7) NTSYSAPI NTSTATUS NTAPI RtlCreateVirtualAccountSid( - _In_ PUNICODE_STRING Name, + _In_ PCUNICODE_STRING Name, _In_ ULONG BaseSubAuthority, _Out_writes_bytes_(*SidLength) PSID Sid, _Inout_ PULONG SidLength ); -#endif -#if (PHNT_VERSION >= PHNT_WINDOWS_7) NTSYSAPI NTSTATUS NTAPI @@ -7850,7 +9129,6 @@ RtlReplaceSidInSd( _In_ PSID NewSid, _Out_ ULONG *NumChanges ); -#endif #define MAX_UNICODE_STACK_BUFFER_LENGTH 256 @@ -7871,7 +9149,6 @@ RtlConvertSidToUnicodeString( _In_ BOOLEAN AllocateDestinationString ); -#if (PHNT_VERSION >= PHNT_WINDOWS_VISTA) // private NTSYSAPI NTSTATUS @@ -7881,9 +9158,7 @@ RtlSidHashInitialize( _In_ ULONG SidCount, _Out_ PSID_AND_ATTRIBUTES_HASH SidAttrHash ); -#endif -#if (PHNT_VERSION >= PHNT_WINDOWS_VISTA) // private NTSYSAPI PSID_AND_ATTRIBUTES @@ -7892,9 +9167,7 @@ RtlSidHashLookup( _In_ PSID_AND_ATTRIBUTES_HASH SidAttrHash, _In_ PSID Sid ); -#endif -#if (PHNT_VERSION >= PHNT_WINDOWS_VISTA) // rev NTSYSAPI BOOLEAN @@ -7902,7 +9175,6 @@ NTAPI RtlIsElevatedRid( _In_ PSID_AND_ATTRIBUTES SidAttr ); -#endif #if (PHNT_VERSION >= PHNT_WINDOWS_10) // rev @@ -7914,7 +9186,7 @@ RtlDeriveCapabilitySidsFromName( _Out_ PSID CapabilityGroupSid, _Out_ PSID CapabilitySid ); -#endif +#endif // PHNT_VERSION >= PHNT_WINDOWS_10 // // Security Descriptors @@ -7926,8 +9198,8 @@ RtlDeriveCapabilitySidsFromName( * * \param SecurityDescriptor Pointer to the buffer for the \ref SECURITY_DESCRIPTOR to be initialized. * \param Revision Specifies the revision level to assign to the security descriptor. Set this parameter to SECURITY_DESCRIPTOR_REVISION. - * @return NTSTATUS Successful or errant status. - * @see https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/wdm/nf-wdm-rtlcreatesecuritydescriptor + * \return NTSTATUS Successful or errant status. + * \see https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/wdm/nf-wdm-rtlcreatesecuritydescriptor */ NTSYSAPI NTSTATUS @@ -7941,9 +9213,9 @@ RtlCreateSecurityDescriptor( * The RtlValidSecurityDescriptor routine checks a given security descriptor's validity. * * \param SecurityDescriptor Pointer to the \ref SECURITY_DESCRIPTOR to be checked. - * @return Returns TRUE if the security descriptor is valid, or FALSE otherwise. - * @remarks The routine checks the validity of an absolute-format security descriptor. To check the validity of a self-relative security descriptor, use the \ref RtlValidRelativeSecurityDescriptor routine instead. - * @see https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/wdm/nf-wdm-rtlvalidsecuritydescriptor + * \return Returns TRUE if the security descriptor is valid, or FALSE otherwise. + * \remarks The routine checks the validity of an absolute-format security descriptor. To check the validity of a self-relative security descriptor, use the \ref RtlValidRelativeSecurityDescriptor routine instead. + * \see https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/wdm/nf-wdm-rtlvalidsecuritydescriptor */ _Check_return_ NTSYSAPI @@ -7957,8 +9229,8 @@ RtlValidSecurityDescriptor( * The RtlLengthSecurityDescriptor routine returns the size of a given security descriptor. * * \param SecurityDescriptor A pointer to a \ref SECURITY_DESCRIPTOR structure whose length the function retrieves. - * @return Returns the length, in bytes, of the SECURITY_DESCRIPTOR structure. - * @see https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/wdm/nf-wdm-rtllengthsecuritydescriptor + * \return Returns the length, in bytes, of the SECURITY_DESCRIPTOR structure. + * \see https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/wdm/nf-wdm-rtllengthsecuritydescriptor */ NTSYSAPI ULONG @@ -7974,8 +9246,8 @@ RtlLengthSecurityDescriptor( * The buffer must begin with a SECURITY_DESCRIPTOR structure, which is followed by the rest of the security descriptor data. * \param SecurityDescriptorLength The size of the SecurityDescriptorInput structure. * \param RequiredInformation A SECURITY_INFORMATION value that specifies the information that is required to be contained in the security descriptor. - * @return RtlValidRelativeSecurityDescriptor returns TRUE if the security descriptor is valid and includes the information that the RequiredInformation parameter specifies. Otherwise, this routine returns FALSE. - * @see https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/wdm/nf-wdm-rtlvalidrelativesecuritydescriptor + * \return RtlValidRelativeSecurityDescriptor returns TRUE if the security descriptor is valid and includes the information that the RequiredInformation parameter specifies. Otherwise, this routine returns FALSE. + * \see https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/wdm/nf-wdm-rtlvalidrelativesecuritydescriptor */ _Check_return_ NTSYSAPI @@ -8080,8 +9352,8 @@ RtlGetSaclSecurityDescriptor( * \param OwnerDefaulted Set to TRUE if the owner information is derived from a default mechanism. * \li \c If this value is TRUE, it is default information. RtlSetOwnerSecurityDescriptor sets the SE_OWNER_DEFAULTED flag in the security descriptor's SECURITY_DESCRIPTOR_CONTROL field. * \li \c If this parameter is FALSE, the SE_OWNER_DEFAULTED flag is cleared. - * @return NTSTATUS Successful or errant status. - * @see https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/ntifs/nf-ntifs-rtlsetownersecuritydescriptor + * \return NTSTATUS Successful or errant status. + * \see https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/ntifs/nf-ntifs-rtlsetownersecuritydescriptor */ NTSYSAPI NTSTATUS @@ -8098,8 +9370,8 @@ RtlSetOwnerSecurityDescriptor( * \param SecurityDescriptor Pointer to the SECURITY_DESCRIPTOR structure. * \param Owner Pointer to an address to receive a pointer to the owner security identifier (SID). If the security descriptor does not currently contain an owner SID, Owner receives NULL. * \param OwnerDefaulted Pointer to a Boolean variable that receives TRUE if the owner information is derived from a default mechanism, FALSE otherwise. Valid only if Owner receives a non-NULL value. - * @return NTSTATUS Successful or errant status. - * @see https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/ntifs/nf-ntifs-rtlgetownersecuritydescriptor + * \return NTSTATUS Successful or errant status. + * \see https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/ntifs/nf-ntifs-rtlgetownersecuritydescriptor */ NTSYSAPI NTSTATUS @@ -8120,8 +9392,8 @@ RtlGetOwnerSecurityDescriptor( * \param GroupDefaulted Set this Boolean variable to TRUE if the primary group information is derived from a default mechanism. * \li \c If this parameter is TRUE, RtlSetGroupSecurityDescriptor sets the SE_GROUP_DEFAULTED flag in the security descriptor's SECURITY_DESCRIPTOR_CONTROL field. * \li \c If this parameter is FALSE, RtlSetGroupSecurityDescriptor clears the SE_GROUP_DEFAULTED flag. - * @return NTSTATUS Successful or errant status. - * @see https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/ntifs/nf-ntifs-rtlsetgroupsecuritydescriptor + * \return NTSTATUS Successful or errant status. + * \see https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/ntifs/nf-ntifs-rtlsetgroupsecuritydescriptor */ NTSYSAPI NTSTATUS @@ -8132,6 +9404,15 @@ RtlSetGroupSecurityDescriptor( _In_ BOOLEAN GroupDefaulted ); +/** + * The RtlGetGroupSecurityDescriptor routine returns the primary group information for a given security descriptor. + * + * \param SecurityDescriptor Pointer to the security descriptor whose primary group information is to be returned. + * \param Group Pointer to a variable that receives a pointer to the security identifier (SID) for the primary group. + * \param GroupDefaulted Pointer to a Boolean variable that receives the value of the SE_GROUP_DEFAULTED flag. + * \return NTSTATUS Successful or errant status. + * \see https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/ntifs/nf-ntifs-rtlgetgroupsecuritydescriptor + */ NTSYSAPI NTSTATUS NTAPI @@ -8197,9 +9478,11 @@ RtlNormalizeSecurityDescriptor( _Out_opt_ PULONG NewSecurityDescriptorLength, _In_ BOOLEAN CheckOnly ); -#endif +#endif // PHNT_VERSION >= PHNT_WINDOWS_10_19H2 +// // Access masks +// #ifndef PHNT_NO_INLINE_ACCESSES_GRANTED /** @@ -8210,11 +9493,11 @@ RtlNormalizeSecurityDescriptor( * * \param GrantedAccess The access mask that specifies the granted accesses. * \param DesiredAccess The access mask that specifies the desired accesses. - * @return Returns TRUE if all desired accesses are granted, otherwise FALSE. + * \return Returns TRUE if all desired accesses are granted, otherwise FALSE. */ FORCEINLINE BOOLEAN -NTAPI +NTAPI_INLINE RtlAreAllAccessesGranted( _In_ ACCESS_MASK GrantedAccess, _In_ ACCESS_MASK DesiredAccess @@ -8231,11 +9514,11 @@ RtlAreAllAccessesGranted( * * \param GrantedAccess The access mask that specifies the granted access rights. * \param DesiredAccess The access mask that specifies the desired access rights. - * @return Returns TRUE if any of the desired access rights are granted, otherwise FALSE. + * \return Returns TRUE if any of the desired access rights are granted, otherwise FALSE. */ FORCEINLINE BOOLEAN -NTAPI +NTAPI_INLINE RtlAreAnyAccessesGranted( _In_ ACCESS_MASK GrantedAccess, _In_ ACCESS_MASK DesiredAccess @@ -8252,7 +9535,7 @@ RtlAreAnyAccessesGranted( * * \param GrantedAccess The access mask that specifies the granted accesses. * \param DesiredAccess The access mask that specifies the desired accesses. - * @return Returns TRUE if all desired accesses are granted, otherwise FALSE. + * \return Returns TRUE if all desired accesses are granted, otherwise FALSE. */ NTSYSAPI BOOLEAN @@ -8270,7 +9553,7 @@ RtlAreAllAccessesGranted( * * \param GrantedAccess The access mask that specifies the granted access rights. * \param DesiredAccess The access mask that specifies the desired access rights. - * @return Returns TRUE if any of the desired access rights are granted, otherwise FALSE. + * \return Returns TRUE if any of the desired access rights are granted, otherwise FALSE. */ NTSYSAPI BOOLEAN @@ -8365,7 +9648,7 @@ RtlGetAcesBufferSize( _In_ PACL Acl, _Out_ PULONG AcesBufferSize ); -#endif +#endif // PHNT_VERSION >= PHNT_WINDOWS_11_24H2 NTSYSAPI BOOLEAN @@ -8375,7 +9658,6 @@ RtlFirstFreeAce( _Out_ PVOID *FirstFree ); -#if (PHNT_VERSION >= PHNT_WINDOWS_VISTA) // private NTSYSAPI PVOID @@ -8385,9 +9667,7 @@ RtlFindAceByType( _In_ UCHAR AceType, _Out_opt_ PULONG Index ); -#endif -#if (PHNT_VERSION >= PHNT_WINDOWS_VISTA) // private NTSYSAPI BOOLEAN @@ -8395,7 +9675,6 @@ NTAPI RtlOwnerAcesPresent( _In_ PACL pAcl ); -#endif NTSYSAPI NTSTATUS @@ -8531,7 +9810,6 @@ RtlAddCompoundAce( _In_ PSID ClientSid ); -#if (PHNT_VERSION >= PHNT_WINDOWS_VISTA) // private NTSYSAPI NTSTATUS @@ -8544,7 +9822,6 @@ RtlAddMandatoryAce( _In_ UCHAR AceType, _In_ ACCESS_MASK AccessMask ); -#endif #if (PHNT_VERSION >= PHNT_WINDOWS_8) NTSYSAPI @@ -8585,6 +9862,21 @@ RtlAddProcessTrustLabelAce( ); #endif // PHNT_VERSION >= PHNT_WINDOWS_8 +// rev +NTSYSAPI +NTSTATUS +NTAPI +RtlAddAccessFilterAce( + _Inout_ PACL Acl, + _In_ ULONG AceRevision, + _In_ ULONG AceFlags, // TRUST_PROTECTED_FILTER_ACE_FLAG + _In_ PSID AccessFilterSid, + _In_ UCHAR AceType, // SYSTEM_FILTERING_ACE_TYPE + _In_ ACCESS_MASK AccessMask, + _In_ PVOID Buffer, // SYSTEM_ACCESS_FILTER_ACE + _In_ USHORT BufferLength + ); + // // Named pipes // @@ -8752,7 +10044,9 @@ RtlCreateAndSetSD( _Out_ PSECURITY_DESCRIPTOR* NewSecurityDescriptor ); +// // Misc. security +// NTSYSAPI VOID @@ -8777,7 +10071,6 @@ RtlImpersonateSelf( _In_ SECURITY_IMPERSONATION_LEVEL ImpersonationLevel ); -#if (PHNT_VERSION >= PHNT_WINDOWS_VISTA) // private NTSYSAPI NTSTATUS @@ -8787,7 +10080,6 @@ RtlImpersonateSelfEx( _In_opt_ ACCESS_MASK AdditionalAccess, _Out_opt_ PHANDLE ThreadToken ); -#endif NTSYSAPI NTSTATUS @@ -8819,7 +10111,6 @@ RtlReleasePrivilege( _In_ PVOID StatePointer ); -#if (PHNT_VERSION >= PHNT_WINDOWS_VISTA) // private NTSYSAPI NTSTATUS @@ -8829,7 +10120,6 @@ RtlRemovePrivileges( _In_ PULONG PrivilegesToKeep, _In_ ULONG PrivilegeCount ); -#endif #if (PHNT_VERSION >= PHNT_WINDOWS_8) @@ -8847,20 +10137,29 @@ NTSYSAPI ULONG NTAPI RtlQueryValidationRunlevel( - _In_opt_ PUNICODE_STRING ComponentName + _In_opt_ PCUNICODE_STRING ComponentName ); #endif // PHNT_VERSION >= PHNT_WINDOWS_8 +NTSYSAPI +NTSTATUS +NTAPI +RtlNewSecurityGrantedAccess( + _In_ ACCESS_MASK DesiredAccess, + _Out_ PPRIVILEGE_SET NewPrivileges, + _Inout_ PULONG Length, + _In_opt_ HANDLE TokenHandle, + _In_ PGENERIC_MAPPING GenericMapping, + _Out_ PACCESS_MASK RemainingDesiredAccess + ); + // // Private namespaces // -// begin_private - -#if (PHNT_VERSION >= PHNT_WINDOWS_VISTA) - // rev +#define BOUNDARY_DESCRIPTOR_FLAG_NONE 0x0 #define BOUNDARY_DESCRIPTOR_ADD_APPCONTAINER_SID 0x0001 _Ret_maybenull_ @@ -8869,7 +10168,7 @@ NTSYSAPI POBJECT_BOUNDARY_DESCRIPTOR NTAPI RtlCreateBoundaryDescriptor( - _In_ PUNICODE_STRING Name, + _In_ PCUNICODE_STRING Name, _In_ ULONG Flags ); @@ -8885,40 +10184,113 @@ NTSTATUS NTAPI RtlAddSIDToBoundaryDescriptor( _Inout_ POBJECT_BOUNDARY_DESCRIPTOR *BoundaryDescriptor, - _In_ PSID RequiredSid + _In_ PCSID RequiredSid ); -#endif // PHNT_VERSION >= PHNT_WINDOWS_VISTA - -#if (PHNT_VERSION >= PHNT_WINDOWS_7) // rev NTSYSAPI NTSTATUS NTAPI RtlAddIntegrityLabelToBoundaryDescriptor( _Inout_ POBJECT_BOUNDARY_DESCRIPTOR *BoundaryDescriptor, - _In_ PSID IntegrityLabel + _In_ PCSID IntegrityLabel ); -#endif // PHNT_VERSION >= PHNT_WINDOWS_7 - -// end_private // // Version // +// rev +typedef struct _RTL_OSVERSIONINFO +{ + ULONG OSVersionInfoSize; + ULONG MajorVersion; + ULONG MinorVersion; + ULONG BuildNumber; + ULONG PlatformId; + WCHAR CSDVersion[128]; +} RTL_OSVERSIONINFO, *PRTL_OSVERSIONINFO; + +// rev +typedef struct _RTL_OSVERSIONINFOEX +{ + ULONG OSVersionInfoSize; + ULONG MajorVersion; + ULONG MinorVersion; + ULONG BuildNumber; + ULONG PlatformId; + WCHAR CSDVersion[128]; + USHORT ServicePackMajor; + USHORT ServicePackMinor; + USHORT SuiteMask; + UCHAR ProductType; + UCHAR Reserved; +} RTL_OSVERSIONINFOEX, *PRTL_OSVERSIONINFOEX; + +// rev +typedef struct _RTL_OSVERSIONINFOEX2 +{ + ULONG OSVersionInfoSize; + ULONG MajorVersion; + ULONG MinorVersion; + ULONG BuildNumber; + ULONG PlatformId; + WCHAR CSDVersion[128]; + USHORT ServicePackMajor; + USHORT ServicePackMinor; + USHORT SuiteMask; + UCHAR ProductType; + UCHAR Reserved; + ULONG SuiteMaskEx; + ULONG Reserved2; +} RTL_OSVERSIONINFOEX2, *PRTL_OSVERSIONINFOEX2; + +// rev +typedef struct _RTL_OSVERSIONINFOEX3 +{ + ULONG OSVersionInfoSize; + ULONG MajorVersion; + ULONG MinorVersion; + ULONG BuildNumber; + union + { + ULONG PlatformId; + ULONG QfeNumber; + }; + union + { + WCHAR CSDVersion[128]; + WCHAR LayerAttrib[128]; + }; + USHORT ServicePackMajor; + USHORT ServicePackMinor; + USHORT SuiteMask; + UCHAR ProductType; + UCHAR Reserved; + ULONG SuiteMaskEx; + ULONG Reserved2; + union + { + USHORT RawInput16; + USHORT LayerNumber : 12; + USHORT AttribSelector : 4; + } Input; + USHORT LayerCount; + ULONG LayerFlags; +} RTL_OSVERSIONINFOEX3, *PRTL_OSVERSIONINFOEX3; + NTSYSAPI NTSTATUS NTAPI RtlGetVersion( - _Out_ PRTL_OSVERSIONINFOEXW VersionInformation // PRTL_OSVERSIONINFOW + _Out_ PVOID VersionInformation ); NTSYSAPI NTSTATUS NTAPI RtlVerifyVersionInfo( - _In_ PRTL_OSVERSIONINFOEXW VersionInformation, // PRTL_OSVERSIONINFOW + _In_ PVOID VersionInformation, _In_ ULONG TypeMask, _In_ ULONGLONG ConditionMask ); @@ -8953,6 +10325,18 @@ RtlGetNtProductType( _Out_ PNT_PRODUCT_TYPE NtProductType ); +// private +NTSYSAPI +BOOLEAN +NTAPI +RtlGetProductInfo( + _In_ ULONG OSMajorVersion, + _In_ ULONG OSMinorVersion, + _In_ ULONG SpMajorVersion, + _In_ ULONG SpMinorVersion, + _Out_ PULONG ReturnedProductType + ); + #if (PHNT_VERSION >= PHNT_WINDOWS_10_RS1) // private NTSYSAPI @@ -8961,19 +10345,37 @@ NTAPI RtlGetSuiteMask( VOID ); -#endif +#endif // PHNT_VERSION >= PHNT_WINDOWS_10_RS1 // // Thread pool (old) // +typedef _Function_class_(WAIT_CALLBACK_ROUTINE) +VOID NTAPI WAIT_CALLBACK_ROUTINE( + _In_ PVOID Parameter, + _In_ BOOLEAN TimerOrWaitFired + ); +typedef WAIT_CALLBACK_ROUTINE* PWAIT_CALLBACK_ROUTINE; + +#define WT_EXECUTEDEFAULT 0x00000000 +#define WT_EXECUTEINIOTHREAD 0x00000001 +#define WT_EXECUTEINUITHREAD 0x00000002 +#define WT_EXECUTEINWAITTHREAD 0x00000004 +#define WT_EXECUTEONLYONCE 0x00000008 +#define WT_EXECUTELONGFUNCTION 0x00000010 +#define WT_EXECUTEINTIMERTHREAD 0x00000020 +#define WT_EXECUTEINPERSISTENTIOTHREAD 0x00000040 +#define WT_EXECUTEINPERSISTENTTHREAD 0x00000080 +#define WT_TRANSFER_IMPERSONATION 0x00000100 + NTSYSAPI NTSTATUS NTAPI RtlRegisterWait( _Out_ PHANDLE WaitHandle, _In_ HANDLE Handle, - _In_ WAITORTIMERCALLBACKFUNC Function, + _In_ PWAIT_CALLBACK_ROUTINE Function, _In_opt_ PVOID Context, _In_ ULONG Milliseconds, _In_ ULONG Flags @@ -8988,6 +10390,16 @@ RtlDeregisterWait( #define RTL_WAITER_DEREGISTER_WAIT_FOR_COMPLETION ((HANDLE)(LONG_PTR)-1) +/** + * Releases all resources used by a wait object. + * + * \param WaitHandle The access mask that specifies the granted access rights. + * \param CompletionEvent Optional completion event for wait callback completion. + * \remarks RTL_WAITER_DEREGISTER_WAIT_FOR_COMPLETION: blocking wait for wait callback completion. + * NULL: non-blocking wait for wait callback completion. + * EventHandle: caller wait for wait callback completion. + * \return NTSTATUS Successful or errant status. + */ NTSYSAPI NTSTATUS NTAPI @@ -8996,34 +10408,58 @@ RtlDeregisterWaitEx( _In_opt_ HANDLE CompletionEvent // optional: RTL_WAITER_DEREGISTER_WAIT_FOR_COMPLETION ); +typedef _Function_class_(RTL_WORK_CALLBACK) +VOID NTAPI RTL_WORK_CALLBACK( + _In_ PVOID ThreadParameter + ); +typedef RTL_WORK_CALLBACK* PRTL_WORK_CALLBACK; + NTSYSAPI NTSTATUS NTAPI RtlQueueWorkItem( - _In_ WORKERCALLBACKFUNC Function, + _In_ PRTL_WORK_CALLBACK Function, _In_opt_ PVOID Context, _In_ ULONG Flags ); +typedef _Function_class_(RTL_OVERLAPPED_COMPLETION_ROUTINE) +VOID NTAPI RTL_OVERLAPPED_COMPLETION_ROUTINE( + _In_ NTSTATUS StatusCode, + _In_ PVOID Context1, + _In_ PVOID Context2 + ); +typedef RTL_OVERLAPPED_COMPLETION_ROUTINE* PRTL_OVERLAPPED_COMPLETION_ROUTINE; + +/** + * Associates the I/O completion port owned by the thread pool with the specified file handle. + * On completion of an I/O request involving this file, a non-I/O worker thread will execute the specified callback function. + * + * \param FileHandle A handle to the file or device for which to set the I/O completion callback. + * \param Function A pointer to the callback function to be executed when an I/O operation completes. + * \param Flags Reserved; must be zero. + * \return NTSTATUS Successful or errant status. + * \sa https://learn.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-bindiocompletioncallback + */ NTSYSAPI NTSTATUS NTAPI RtlSetIoCompletionCallback( _In_ HANDLE FileHandle, - _In_ APC_CALLBACK_FUNCTION CompletionProc, + _In_ PRTL_OVERLAPPED_COMPLETION_ROUTINE Function, _In_ ULONG Flags ); -_Function_class_(RTL_START_POOL_THREAD) -typedef NTSTATUS (NTAPI RTL_START_POOL_THREAD)( - _In_ PTHREAD_START_ROUTINE Function, +typedef _Function_class_(RTL_START_POOL_THREAD) +NTSTATUS NTAPI RTL_START_POOL_THREAD( + _In_ PUSER_THREAD_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)( +typedef _Function_class_(RTL_EXIT_POOL_THREAD) +NTSTATUS NTAPI RTL_EXIT_POOL_THREAD( _In_ NTSTATUS ExitStatus ); typedef RTL_EXIT_POOL_THREAD *PRTL_EXIT_POOL_THREAD; @@ -9040,7 +10476,7 @@ NTSYSAPI VOID NTAPI RtlUserThreadStart( - _In_ PTHREAD_START_ROUTINE Function, + _In_ PUSER_THREAD_START_ROUTINE Function, _In_ PVOID Parameter ); @@ -9052,6 +10488,13 @@ LdrInitializeThunk( _In_ PVOID Parameter ); +NTSYSAPI +NTSTATUS +NTAPI +LdrProcessInitializationComplete( + VOID + ); + // // Thread execution // @@ -9068,6 +10511,14 @@ RtlDelayExecution( // Timer support // +/** + * Creates a queue for timers. + * + * \param TimerQueueHandle A pointer to a variable that receives the handle to the newly created timer queue. + * \return NTSTATUS Successful or errant status. + * \remarks Timer-queue timers are lightweight objects that enable you to specify a callback function to be called at a specified time. + * \sa https://learn.microsoft.com/en-us/windows/win32/api/threadpoollegacyapiset/nf-threadpoollegacyapiset-createtimerqueue + */ NTSYSAPI NTSTATUS NTAPI @@ -9075,13 +10526,34 @@ RtlCreateTimerQueue( _Out_ PHANDLE TimerQueueHandle ); +typedef _Function_class_(RTL_TIMER_CALLBACK) +VOID NTAPI RTL_TIMER_CALLBACK( + _In_ PVOID Parameter, + _In_ BOOLEAN TimerOrWaitFired + ); +typedef RTL_TIMER_CALLBACK *PRTL_TIMER_CALLBACK; + +/** + * Creates a timer-queue timer. + * + * \param TimerQueueHandle A handle to the timer queue. This handle is returned by a previous call to RtlCreateTimerQueue. + * \param Handle A pointer to a variable that receives the handle to the newly created timer-queue timer. + * \param Function A pointer to the callback function to be executed when the timer expires. + * \param Context A pointer to a variable to be passed to the callback function. + * \param DueTime The amount of time in milliseconds relative to the current time that must elapse before the timer is signaled for the first time. + * \param Period The period of the timer in milliseconds. If this value is zero, the timer is signaled once; otherwise, it is signaled periodically. + * \param Flags The flags that control the behavior of the timer. This parameter can be zero or one of the following values: + * WT_EXECUTEDEFAULT, WT_EXECUTEONLYONCE, WT_EXECUTELONGFUNCTION, WT_EXECUTEINTIMERTHREAD, WT_EXECUTEINPERSISTENTTHREAD, WT_TRANSFER_IMPERSONATION. + * \return NTSTATUS Successful or errant status. + * \sa https://learn.microsoft.com/en-us/windows/win32/api/threadpoollegacyapiset/nf-threadpoollegacyapiset-createtimerqueuetimer + */ NTSYSAPI NTSTATUS NTAPI RtlCreateTimer( _In_ HANDLE TimerQueueHandle, _Out_ PHANDLE Handle, - _In_ WAITORTIMERCALLBACKFUNC Function, + _In_ PRTL_TIMER_CALLBACK Function, _In_opt_ PVOID Context, _In_ ULONG DueTime, _In_ ULONG Period, @@ -9094,7 +10566,7 @@ NTAPI RtlSetTimer( _In_ HANDLE TimerQueueHandle, _Out_ PHANDLE Handle, - _In_ WAITORTIMERCALLBACKFUNC Function, + _In_ PRTL_TIMER_CALLBACK Function, _In_opt_ PVOID Context, _In_ ULONG DueTime, _In_ ULONG Period, @@ -9182,9 +10654,9 @@ RtlCheckRegistryKey( _In_ PCWSTR Path ); -_Function_class_(RTL_QUERY_REGISTRY_ROUTINE) -typedef NTSTATUS (NTAPI RTL_QUERY_REGISTRY_ROUTINE)( - _In_ PCWSTR ValueName, +typedef _Function_class_(RTL_QUERY_REGISTRY_ROUTINE) +NTSTATUS NTAPI RTL_QUERY_REGISTRY_ROUTINE( + _In_z_ PCWSTR ValueName, _In_ ULONG ValueType, _In_ PVOID ValueData, _In_ ULONG ValueLength, @@ -9211,6 +10683,11 @@ typedef struct _RTL_QUERY_REGISTRY_TABLE #define RTL_QUERY_REGISTRY_NOEXPAND 0x00000010 #define RTL_QUERY_REGISTRY_DIRECT 0x00000020 #define RTL_QUERY_REGISTRY_DELETE 0x00000040 +#define RTL_QUERY_REGISTRY_NOSTRING 0x00000080 // deprecated +#define RTL_QUERY_REGISTRY_TYPECHECK 0x00000100 + +#define RTL_QUERY_REGISTRY_TYPECHECK_SHIFT 24 +#define RTL_QUERY_REGISTRY_TYPECHECK_MASK (0xff << RTL_QUERY_REGISTRY_TYPECHECK_SHIFT) NTSYSAPI NTSTATUS @@ -9234,7 +10711,7 @@ RtlQueryRegistryValuesEx( _In_opt_ PVOID Context, _In_opt_ PVOID Environment ); -#endif +#endif // PHNT_VERSION >= PHNT_WINDOWS_8 #if (PHNT_VERSION >= PHNT_WINDOWS_10_RS4) NTSYSAPI @@ -9243,13 +10720,13 @@ NTAPI RtlQueryRegistryValueWithFallback( _In_opt_ HANDLE PrimaryHandle, _In_opt_ HANDLE FallbackHandle, - _In_ PUNICODE_STRING ValueName, + _In_ PCUNICODE_STRING ValueName, _In_ ULONG ValueLength, _Out_opt_ PULONG ValueType, _Out_writes_bytes_to_(ValueLength, *ResultLength) PVOID ValueData, _Out_range_(<= , ValueLength) PULONG ResultLength ); -#endif +#endif // PHNT_VERSION >= PHNT_WINDOWS_10_RS4 NTSYSAPI NTSTATUS @@ -9257,7 +10734,7 @@ NTAPI RtlWriteRegistryValue( _In_ ULONG RelativeTo, _In_ PCWSTR Path, - _In_ PCWSTR ValueName, + _In_z_ PCWSTR ValueName, _In_ ULONG ValueType, _In_ PVOID ValueData, _In_ ULONG ValueLength @@ -9269,16 +10746,24 @@ NTAPI RtlDeleteRegistryValue( _In_ ULONG RelativeTo, _In_ PCWSTR Path, - _In_ PCWSTR ValueName + _In_z_ PCWSTR ValueName ); // // Thread profiling // -#if (PHNT_VERSION >= PHNT_WINDOWS_7) - // rev +/** + * The RtlEnableThreadProfiling routine enables thread profiling on the specified thread. + * + * \param ThreadHandle The handle to the thread on which you want to enable profiling. This must be the current thread. + * \param Flags To receive thread profiling data such as context switch count, set this parameter to THREAD_PROFILING_FLAG_DISPATCH; otherwise, set to 0. + * \param HardwareCounters To receive hardware performance counter data, set this parameter to a bitmask that identifies the hardware counters to collect. + * \param PerformanceDataHandle An opaque handle that you use when calling the RtlReadThreadProfilingData and RtlDisableThreadProfiling functions. + * \return NTSTATUS Successful or errant status. + * \sa https://learn.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-enablethreadprofiling + */ NTSYSAPI NTSTATUS NTAPI @@ -9290,6 +10775,13 @@ RtlEnableThreadProfiling( ); // rev +/** + * The RtlDisableThreadProfiling routine disables thread profiling. + * + * \param PerformanceDataHandle The handle that the RtlEnableThreadProfiling function returned. + * \return NTSTATUS Successful or errant status. + * \sa https://learn.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-querythreadprofiling + */ NTSYSAPI NTSTATUS NTAPI @@ -9298,6 +10790,14 @@ RtlDisableThreadProfiling( ); // rev +/** + * The RtlQueryThreadProfiling routine determines whether thread profiling is enabled for the specified thread. + * + * \param ThreadHandle The handle to the thread on which you want to enable profiling. This must be the current thread. + * \param Enabled Is TRUE if thread profiling is enabled for the specified thread; otherwise, FALSE. + * \return NTSTATUS Successful or errant status. + * \sa https://learn.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-querythreadprofiling + */ NTSYSAPI NTSTATUS NTAPI @@ -9307,6 +10807,15 @@ RtlQueryThreadProfiling( ); // rev +/** + * The RtlReadThreadProfilingData routine reads the specified profiling data associated with the thread. + * + * \param PerformanceDataHandle The handle that the RtlEnableThreadProfiling function returned. + * \param Flags One or more flags set when you called the RtlEnableThreadProfiling function that specify the counter data to read. + * \param PerformanceData A PERFORMANCE_DATA structure that contains the thread profiling and hardware counter data. + * \return NTSTATUS Successful or errant status. + * \sa https://learn.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-readthreadprofilingdata + */ NTSYSAPI NTSTATUS NTAPI @@ -9316,8 +10825,6 @@ RtlReadThreadProfilingData( _Out_ PPERFORMANCE_DATA PerformanceData ); -#endif // PHNT_VERSION >= PHNT_WINDOWS_7 - // // WOW64 // @@ -9354,6 +10861,13 @@ RtlQueueApcWow64Thread( _In_opt_ PVOID ApcArgument3 ); +/** + * The RtlWow64EnableFsRedirection routine enables or disables file system redirection for the calling thread. + * + * \param Wow64FsEnableRedirection If TRUE, requests redirection be enabled; if FALSE, requests redirection be disabled. + * \return NTSTATUS Successful or errant status. + * \sa https://learn.microsoft.com/en-us/windows/win32/api/wow64apiset/nf-wow64apiset-wow64enablewow64fsredirection + */ NTSYSAPI NTSTATUS NTAPI @@ -9361,6 +10875,15 @@ RtlWow64EnableFsRedirection( _In_ BOOLEAN Wow64FsEnableRedirection ); +/** + * The RtlWow64EnableFsRedirectionEx routine enables or disables file system redirection for the calling thread. + * + * \param Wow64FsEnableRedirection If TRUE, requests redirection be enabled; if FALSE, requests redirection be disabled. + * \param OldFsRedirectionLevel The WOW64 file system redirection value. The system uses this parameter to store information + * necessary to revert (re-enable) file system redirection. + * \return NTSTATUS Successful or errant status. + * \sa https://learn.microsoft.com/en-us/windows/win32/api/wow64apiset/nf-wow64apiset-wow64disablewow64fsredirection + */ NTSYSAPI NTSTATUS NTAPI @@ -9373,6 +10896,14 @@ RtlWow64EnableFsRedirectionEx( // Misc. // +/** + * The RtlComputeCrc32 routine computes the CRC32 checksum for a buffer, allowing for incremental computation by providing a partial CRC value. + * + * \param PartialCrc The initial CRC32 value. Use 0 for a new computation, or the result of a previous call to continue CRC calculation over additional data. + * \param Buffer Pointer to the buffer containing the data to compute the CRC32 for. + * \param Length The length, in bytes, of the buffer. + * \return The computed CRC32 value. + */ NTSYSAPI ULONG32 NTAPI @@ -9382,69 +10913,134 @@ RtlComputeCrc32( _In_ ULONG Length ); +/** + * The RtlEncodePointer routine encodes the specified pointer. Encoded pointers can be used to provide another layer of protection for pointer values. + * + * \param Ptr The system pointer to be encoded. + * \return The function returns the encoded pointer. + * \sa https://learn.microsoft.com/en-us/previous-versions/bb432254(v=vs.85) + */ +_Ret_maybenull_ NTSYSAPI PVOID NTAPI RtlEncodePointer( - _In_ PVOID Ptr + _In_opt_ PVOID Ptr ); +/** + * The RtlDecodePointer routine decodes a pointer that was previously encoded with RtlEncodePointer. + * + * \param Ptr The system pointer to be decoded. + * \return The function returns the decoded pointer. + * \sa https://learn.microsoft.com/en-us/previous-versions/bb432242(v=vs.85) + */ +_Ret_maybenull_ NTSYSAPI PVOID NTAPI RtlDecodePointer( - _In_ PVOID Ptr + _In_opt_ PVOID Ptr ); +/** + * The RtlEncodeSystemPointer routine encodes the specified pointer with a system-specific value. + * Encoded pointers can be used to provide another layer of protection for pointer values. + * + * \param Ptr The system pointer to be encoded. + * \return The function returns the encoded pointer. + * \sa https://learn.microsoft.com/en-us/previous-versions/bb432255(v=vs.85) + */ +_Ret_maybenull_ NTSYSAPI PVOID NTAPI RtlEncodeSystemPointer( - _In_ PVOID Ptr + _In_opt_ PVOID Ptr ); +/** + * The RtlDecodeSystemPointer routine decodes a pointer that was previously encoded with RtlEncodeSystemPointer. + * + * \param Ptr The pointer to be decoded. + * \return The function returns the decoded pointer. + * \sa https://learn.microsoft.com/en-us/previous-versions/bb432243(v=vs.85) + */ +_Ret_maybenull_ NTSYSAPI PVOID NTAPI RtlDecodeSystemPointer( - _In_ PVOID Ptr + _In_opt_ PVOID Ptr ); #if (PHNT_VERSION >= PHNT_WINDOWS_10) // rev +/** + * The RtlEncodeRemotePointer routine encodes the specified pointer of the specified process. + * Encoded pointers can be used to provide another layer of protection for pointer values. + * + * \param ProcessHandle Handle to the remote process that owns the pointer. + * \param Pointer The pointer to be encoded. + * \param EncodedPointer The encoded pointer. + * \return HRESULT Successful or errant status. + * \sa https://learn.microsoft.com/en-us/previous-versions/dn877135(v=vs.85) + */ NTSYSAPI -NTSTATUS +HRESULT NTAPI RtlEncodeRemotePointer( _In_ HANDLE ProcessHandle, - _In_ PVOID Pointer, + _In_opt_ PVOID Pointer, _Out_ PVOID *EncodedPointer ); // rev +/** + * The RtlDecodeRemotePointer routine decodes a pointer in a specified process that was previously + * encoded with RtlEncodePointer or RtlEncodeRemotePointer. + * + * \param ProcessHandle Handle to the remote process that owns the pointer. + * \param Pointer The pointer to be decoded. + * \param DecodedPointer The decoded pointer. + * \return HRESULT Successful or errant status. + * \sa https://learn.microsoft.com/en-us/previous-versions/dn877133(v=vs.85) + */ NTSYSAPI -NTSTATUS +HRESULT NTAPI RtlDecodeRemotePointer( _In_ HANDLE ProcessHandle, - _In_ PVOID Pointer, + _In_opt_ PVOID Pointer, _Out_ PVOID *DecodedPointer ); #endif // PHNT_VERSION >= PHNT_WINDOWS_10 #if (PHNT_VERSION >= PHNT_WINDOWS_10) - // rev +/** + * The RtlIsProcessorFeaturePresent routine determines whether the specified processor feature is supported by the current computer. + * + * \param ProcessorFeature The processor feature to be tested. + * \return If the feature is supported, the return value is a nonzero value. + * \sa https://learn.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-isprocessorfeaturepresent + */ NTSYSAPI BOOLEAN NTAPI RtlIsProcessorFeaturePresent( _In_ ULONG ProcessorFeature ); - -#endif +#endif // PHNT_VERSION >= PHNT_WINDOWS_10 // rev +/** + * The RtlGetCurrentProcessorNumber routine retrieves the number of the processor the current thread was running + * on during the call to this function. + * + * \return The function returns the current processor number. + * \sa https://learn.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-getcurrentprocessornumber + */ NTSYSAPI ULONG NTAPI @@ -9452,9 +11048,16 @@ RtlGetCurrentProcessorNumber( VOID ); -#if (PHNT_VERSION >= PHNT_WINDOWS_7) - // rev +/** + * The RtlGetCurrentProcessorNumberEx routine retrieves the processor group and number of the logical processor + * in which the calling thread is running. + * + * \param ProcessorNumber A pointer to a PROCESSOR_NUMBER structure that receives the processor group and number + * of the logical processor the calling thread is running. + * \return This function does not return a value. + * \sa https://learn.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-getcurrentprocessornumberex + */ NTSYSAPI VOID NTAPI @@ -9462,8 +11065,6 @@ RtlGetCurrentProcessorNumberEx( _Out_ PPROCESSOR_NUMBER ProcessorNumber ); -#endif - // // Stack support // @@ -9490,7 +11091,9 @@ RtlGetFrame( ); #define RTL_WALK_USER_MODE_STACK 0x00000001 -#define RTL_WALK_VALID_FLAGS 0x00000001 +#define RTL_WALK_KERNEL_STACK 0x00000002 +#define RTL_WALK_USER_KERNEL_STACK 0x00000003 +#define RTL_WALK_VALID_FLAGS 0x00000006 #define RTL_STACK_WALKING_MODE_FRAMES_TO_SKIP_SHIFT 0x00000008 // private @@ -9504,6 +11107,7 @@ RtlWalkFrameChain( ); // rev +DECLSPEC_DEPRECATED NTSYSAPI VOID NTAPI @@ -9512,8 +11116,15 @@ RtlGetCallersAddress( // Use the intrinsic _ReturnAddress instead. _Out_ PVOID *CallersCaller ); -#if (PHNT_VERSION >= PHNT_WINDOWS_7) - +/** + * The RtlGetEnabledExtendedFeatures routine returns a mask of extended processor features that are enabled by the system. + * + * \param FeatureMask A 64-bit feature mask. This parameter indicates a set of extended processor features for which the caller + * requests information about whether the features are enabled. + * \return A 64-bitmask of enabled extended processor features. The routine calculates this mask as the intersection (bitwise AND) + * between all enabled features and the value of the FeatureMask parameter. + * \sa https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/ntddk/nf-ntddk-rtlgetenabledextendedfeatures + */ NTSYSAPI ULONG64 NTAPI @@ -9521,8 +11132,6 @@ RtlGetEnabledExtendedFeatures( _In_ ULONG64 FeatureMask ); -#endif - #if (PHNT_VERSION >= PHNT_WINDOWS_10_RS4) // msdn @@ -9545,7 +11154,7 @@ RtlLocateSupervisorFeature( _Out_opt_ PULONG Length ); -#endif +#endif // PHNT_VERSION >= PHNT_WINDOWS_10_RS4 #define ELEVATION_FLAG_TOKEN_CHECKS 0x00000001 #define ELEVATION_FLAG_VIRTUALIZATION 0x00000002 @@ -9553,21 +11162,22 @@ RtlLocateSupervisorFeature( #define ELEVATION_FLAG_NO_SIGNATURE_CHECK 0x00000008 // private -typedef union _RTL_ELEVATION_FLAGS +typedef struct _RTL_ELEVATION_FLAGS { - ULONG Flags; - struct + union { - ULONG ElevationEnabled : 1; - ULONG VirtualizationEnabled : 1; - ULONG InstallerDetectEnabled : 1; - ULONG AdminApprovalModeType : 2; - ULONG ReservedBits : 27; + ULONG Flags; + struct + { + ULONG ElevationEnabled : 1; + ULONG VirtualizationEnabled : 1; + ULONG InstallerDetectEnabled : 1; + ULONG AdminApprovalModeType : 2; + ULONG ReservedBits : 27; + }; }; } RTL_ELEVATION_FLAGS, *PRTL_ELEVATION_FLAGS; -#if (PHNT_VERSION >= PHNT_WINDOWS_VISTA) - // private NTSYSAPI NTSTATUS @@ -9576,10 +11186,6 @@ RtlQueryElevationFlags( _Out_ PRTL_ELEVATION_FLAGS Flags ); -#endif - -#if (PHNT_VERSION >= PHNT_WINDOWS_VISTA) - // private NTSYSAPI NTSTATUS @@ -9588,10 +11194,6 @@ RtlRegisterThreadWithCsrss( VOID ); -#endif - -#if (PHNT_VERSION >= PHNT_WINDOWS_VISTA) - // private NTSYSAPI NTSTATUS @@ -9600,10 +11202,6 @@ RtlLockCurrentThread( VOID ); -#endif - -#if (PHNT_VERSION >= PHNT_WINDOWS_VISTA) - // private NTSYSAPI NTSTATUS @@ -9612,10 +11210,6 @@ RtlUnlockCurrentThread( VOID ); -#endif - -#if (PHNT_VERSION >= PHNT_WINDOWS_VISTA) - // private NTSYSAPI NTSTATUS @@ -9624,10 +11218,6 @@ RtlLockModuleSection( _In_ PVOID Address ); -#endif - -#if (PHNT_VERSION >= PHNT_WINDOWS_VISTA) - // private NTSYSAPI NTSTATUS @@ -9636,35 +11226,42 @@ RtlUnlockModuleSection( _In_ PVOID Address ); -#endif - -// begin_msdn:"Winternl" - #define RTL_UNLOAD_EVENT_TRACE_NUMBER 64 // private +/** + * The RTL_UNLOAD_EVENT_TRACE structure contains information about modules unloaded by the current process. + * + * \sa https://learn.microsoft.com/en-us/windows/win32/devnotes/rtlgetunloadeventtrace + */ typedef struct _RTL_UNLOAD_EVENT_TRACE { - PVOID BaseAddress; - SIZE_T SizeOfImage; - ULONG Sequence; - ULONG TimeDateStamp; - ULONG CheckSum; - WCHAR ImageName[32]; + PVOID BaseAddress; // Base address of dll + SIZE_T SizeOfImage; // Size of image + ULONG Sequence; // Sequence number for this event + ULONG TimeDateStamp; // Time and date of image + ULONG CheckSum; // Image checksum + WCHAR ImageName[32]; // Image name 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 BaseAddress; // Base address of dll + ULONG SizeOfImage; // Size of image + ULONG Sequence; // Sequence number for this event + ULONG TimeDateStamp; // Time and date of image + ULONG CheckSum; // Image checksum + WCHAR ImageName[32]; // Image name ULONG Version[2]; } RTL_UNLOAD_EVENT_TRACE32, *PRTL_UNLOAD_EVENT_TRACE32; +/** + * The RtlGetUnloadEventTrace routine enables the dump code to get the unloaded module information from Ntdll.dll for storage in the minidump. + * + * \return A pointer to an array of unload events. + * \sa https://learn.microsoft.com/en-us/windows/win32/devnotes/rtlgetunloadeventtrace + */ NTSYSAPI PRTL_UNLOAD_EVENT_TRACE NTAPI @@ -9672,7 +11269,15 @@ RtlGetUnloadEventTrace( VOID ); -#if (PHNT_VERSION >= PHNT_WINDOWS_VISTA) +/** + * The RtlGetUnloadEventTraceEx routine retrieves the size and location of the dynamically unloaded module list for the current process. + * + * \param ElementSize A pointer to a variable that contains the size of an element in the list. + * \param ElementCount A pointer to a variable that contains the number of elements in the list. + * \param EventTrace A pointer to an array of RTL_UNLOAD_EVENT_TRACE structures. + * \return A pointer to an array of unload events. + * \sa https://learn.microsoft.com/en-us/windows/win32/devnotes/rtlgetunloadeventtraceex + */ NTSYSAPI PRTL_UNLOAD_EVENT_TRACE NTAPI @@ -9681,11 +11286,19 @@ RtlGetUnloadEventTraceEx( _Out_ PULONG *ElementCount, _Out_ PVOID *EventTrace // works across all processes ); -#endif - -NTSYSAPI +/** + * The RtlCaptureStackBackTrace routine captures a stack trace by walking the stack and recording the information for each frame. + * + * \param FramesToSkip Number of frames to skip from the start (current call point) of the back trace. + * \param FramesToCapture Number of frames to be captured. + * \param BackTrace Caller-allocated array in which pointers to the return addresses captured from the current stack trace are returned. + * \param BackTraceHash Optional value that can be used to organize hash tables. This hash value is calculated based on the values of the pointers returned in the BackTrace array. Two identical stack traces will generate identical hash values. + * \return The number of captured frames. + * \sa https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/ntifs/nf-ntifs-rtlcapturestackbacktrace + */ _Success_(return != 0) +NTSYSAPI USHORT NTAPI RtlCaptureStackBackTrace( @@ -9695,6 +11308,13 @@ RtlCaptureStackBackTrace( _Out_opt_ PULONG BackTraceHash ); +/** + * The RtlCaptureContext routine retrieves a context record in the context of the caller. + * + * \param ContextRecord A pointer to a CONTEXT structure. + * \return This function does not return a value. + * \sa https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/ntifs/nf-ntifs-rtlcapturecontext + */ NTSYSAPI VOID NTAPI @@ -9709,18 +11329,17 @@ NTAPI RtlCaptureContext2( _Inout_ PCONTEXT ContextRecord ); -#endif +#endif // PHNT_VERSION >= PHNT_WINDOWS_10_20H1 #if (PHNT_VERSION >= PHNT_WINDOWS_11) NTSYSAPI VOID -__cdecl +STDAPIVCALLTYPE RtlRestoreContext( _In_ PCONTEXT ContextRecord, _In_opt_ struct _EXCEPTION_RECORD* ExceptionRecord ); -#endif - +#endif // PHNT_VERSION >= PHNT_WINDOWS_11 NTSYSAPI VOID @@ -9735,27 +11354,27 @@ RtlUnwind( #if defined(_M_AMD64) && defined(_M_ARM64EC) NTSYSAPI BOOLEAN -__cdecl +STDAPIVCALLTYPE RtlAddFunctionTable( _In_reads_(EntryCount) PRUNTIME_FUNCTION FunctionTable, - _In_ DWORD EntryCount, - _In_ DWORD64 BaseAddress + _In_ ULONG EntryCount, + _In_ ULONG64 BaseAddress ); NTSYSAPI BOOLEAN -__cdecl +STDAPIVCALLTYPE RtlDeleteFunctionTable( _In_ PRUNTIME_FUNCTION FunctionTable ); NTSYSAPI BOOLEAN -__cdecl +STDAPIVCALLTYPE RtlInstallFunctionTableCallback( - _In_ DWORD64 TableIdentifier, - _In_ DWORD64 BaseAddress, - _In_ DWORD Length, + _In_ ULONG64 TableIdentifier, + _In_ ULONG64 BaseAddress, + _In_ ULONG Length, _In_ PGET_RUNTIME_FUNCTION_CALLBACK Callback, _In_opt_ PVOID Context, _In_opt_ PCWSTR OutOfProcessCallbackDll @@ -9763,13 +11382,13 @@ RtlInstallFunctionTableCallback( #if (PHNT_VERSION >= PHNT_WINDOWS_8) NTSYSAPI -DWORD +ULONG NTAPI RtlAddGrowableFunctionTable( _Out_ PVOID* DynamicTable, _In_reads_(MaximumEntryCount) PRUNTIME_FUNCTION FunctionTable, - _In_ DWORD EntryCount, - _In_ DWORD MaximumEntryCount, + _In_ ULONG EntryCount, + _In_ ULONG MaximumEntryCount, _In_ ULONG_PTR RangeBase, _In_ ULONG_PTR RangeEnd ); @@ -9779,7 +11398,7 @@ VOID NTAPI RtlGrowFunctionTable( _Inout_ PVOID DynamicTable, - _In_ DWORD NewEntryCount + _In_ ULONG NewEntryCount ); NTSYSAPI @@ -9800,6 +11419,31 @@ RtlIsEcCode( ); #endif // _M_ARM64EC +/** + * The RtlLookupFunctionEntry routine searches the active function tables for an entry that corresponds to the specified PC value. + * + * \param ControlPc The virtual address of an instruction bundle within the function. + * \param ImageBase The base address of module to which the function belongs. + * \return The entry in the function table for the specified PC. + * \sa https://learn.microsoft.com/en-us/windows/win32/api/winnt/nf-winnt-rtllookupfunctionentry + */ +// NTSYSAPI +// PRUNTIME_FUNCTION +// NTAPI +// RtlLookupFunctionEntry( +// _In_ ULONG_PTR ControlPc, +// _Out_ PULONG_PTR ImageBase, +// _Inout_opt_ PUNWIND_HISTORY_TABLE HistoryTable +// ); + +/** + * The RtlPcToFileHeader routine retrieves the base address of the image that contains the specified PC value. + * + * \param PcValue The PC value. The function searches all modules mapped into the address space of the calling process for a module that contains this value. + * \param BaseOfImage The base address of the image containing the PC value. This value must be added to any relative addresses in the headers to locate the image. + * \return If the PC value is found, returns the base address of the image that contains the PC value. If no image contains the PC value, the function returns NULL. + * \sa https://learn.microsoft.com/en-us/windows/win32/api/winnt/nf-winnt-rtlpctofileheader + */ NTSYSAPI PVOID NTAPI @@ -9808,10 +11452,14 @@ RtlPcToFileHeader( _Out_ PVOID* BaseOfImage ); -// end_msdn - -#if (PHNT_VERSION >= PHNT_WINDOWS_7) // rev +/** + * The RtlQueryPerformanceCounter routine retrieves the current value of the performance counter, which is a high resolution (<1us) time stamp that can be used for time-interval measurements. + * + * \param PerformanceCounter A pointer to a variable that receives the current performance-counter value, in counts. + * \return Returns TRUE if the function succeeds, otherwise FALSE. On systems that run Windows XP or later, the function will always succeed and will thus never return zero. + * \sa https://learn.microsoft.com/en-us/windows/win32/api/profileapi/nf-profileapi-queryperformancecounter + */ NTSYSAPI LOGICAL NTAPI @@ -9820,13 +11468,20 @@ RtlQueryPerformanceCounter( ); // rev +/** + * The RtlQueryPerformanceFrequency routine retrieves the frequency of the performance counter. The frequency of the performance counter is fixed at system boot and is consistent across all processors. + * Therefore, the frequency need only be queried upon application initialization, and the result can be cached. + * + * \param PerformanceFrequency A pointer to a variable that receives the current performance-counter frequency, in counts per second. + * \return Returns TRUE if the function succeeds, otherwise FALSE. On systems that run Windows XP or later, the function will always succeed and will thus never return zero. + * \sa https://learn.microsoft.com/en-us/windows/win32/api/profileapi/nf-profileapi-queryperformancefrequency + */ NTSYSAPI LOGICAL NTAPI RtlQueryPerformanceFrequency( _Out_ PLARGE_INTEGER PerformanceFrequency ); -#endif // PHNT_VERSION >= PHNT_WINDOWS_7 // // Image Mitigation @@ -10037,27 +11692,12 @@ RtlSetImageMitigationPolicy( _In_ ULONG BufferSize ); -#endif +#endif // PHNT_VERSION >= PHNT_WINDOWS_10_RS3 // -// session +// Session // -#ifdef PHNT_INLINE_TYPEDEFS -// rev -FORCEINLINE -ULONG -NTAPI -RtlGetCurrentServiceSessionId( - VOID - ) -{ - if (NtCurrentPeb()->SharedData && NtCurrentPeb()->SharedData->ServiceSessionId) - return NtCurrentPeb()->SharedData->ServiceSessionId; - else - return 0; -} -#else // rev NTSYSAPI ULONG @@ -10065,23 +11705,7 @@ NTAPI RtlGetCurrentServiceSessionId( VOID ); -#endif -#ifdef PHNT_INLINE_TYPEDEFS -// rev -FORCEINLINE -ULONG -NTAPI -RtlGetActiveConsoleId( - VOID - ) -{ - if (NtCurrentPeb()->SharedData && NtCurrentPeb()->SharedData->ServiceSessionId) - return NtCurrentPeb()->SharedData->ActiveConsoleId; - else - return USER_SHARED_DATA->ActiveConsoleId; -} -#else // private NTSYSAPI ULONG @@ -10089,25 +11713,7 @@ NTAPI RtlGetActiveConsoleId( VOID ); -#endif -#ifdef PHNT_INLINE_TYPEDEFS -#if (PHNT_VERSION >= PHNT_WINDOWS_10_RS1) -// private -FORCEINLINE -LONGLONG -NTAPI -RtlGetConsoleSessionForegroundProcessId( - VOID - ) -{ - if (NtCurrentPeb()->SharedData && NtCurrentPeb()->SharedData->ServiceSessionId) - return NtCurrentPeb()->SharedData->ConsoleSessionForegroundProcessId; - else - return USER_SHARED_DATA->ConsoleSessionForegroundProcessId; -} -#endif -#else #if (PHNT_VERSION >= PHNT_WINDOWS_10_RS1) // private NTSYSAPI @@ -10116,8 +11722,7 @@ NTAPI RtlGetConsoleSessionForegroundProcessId( VOID ); -#endif -#endif +#endif // PHNT_VERSION >= PHNT_WINDOWS_10_RS1 // // Appcontainer @@ -10133,7 +11738,7 @@ RtlGetTokenNamedObjectPath( _In_opt_ PSID Sid, _Out_ PUNICODE_STRING ObjectPath // RtlFreeUnicodeString ); -#endif +#endif // PHNT_VERSION >= PHNT_WINDOWS_10_RS2 #if (PHNT_VERSION >= PHNT_WINDOWS_8) // rev @@ -10146,7 +11751,7 @@ RtlGetAppContainerNamedObjectPath( _In_ BOOLEAN RelativePath, _Out_ PUNICODE_STRING ObjectPath // RtlFreeUnicodeString ); -#endif +#endif // PHNT_VERSION >= PHNT_WINDOWS_8 #if (PHNT_VERSION >= PHNT_WINDOWS_8_1) // rev @@ -10157,7 +11762,7 @@ RtlGetAppContainerParent( _In_ PSID AppContainerSid, _Out_ PSID* AppContainerSidParent // RtlFreeSid ); -#endif +#endif // PHNT_VERSION >= PHNT_WINDOWS_8_1 #if (PHNT_VERSION >= PHNT_WINDOWS_10) // rev @@ -10168,7 +11773,7 @@ RtlCheckSandboxedToken( _In_opt_ HANDLE TokenHandle, _Out_ PBOOLEAN IsSandboxed ); -#endif +#endif // PHNT_VERSION >= PHNT_WINDOWS_10 #if (PHNT_VERSION >= PHNT_WINDOWS_8) // rev @@ -10180,7 +11785,7 @@ RtlCheckTokenCapability( _In_ PSID CapabilitySidToCheck, _Out_ PBOOLEAN HasCapability ); -#endif +#endif // PHNT_VERSION >= PHNT_WINDOWS_8 #if (PHNT_VERSION >= PHNT_WINDOWS_10) // rev @@ -10189,10 +11794,10 @@ NTSTATUS NTAPI RtlCapabilityCheck( _In_opt_ HANDLE TokenHandle, - _In_ PUNICODE_STRING CapabilityName, + _In_ PCUNICODE_STRING CapabilityName, _Out_ PBOOLEAN HasCapability ); -#endif +#endif // PHNT_VERSION >= PHNT_WINDOWS_10 #if (PHNT_VERSION >= PHNT_WINDOWS_8) // rev @@ -10231,7 +11836,7 @@ RtlQueryTokenHostIdAsUlong64( _In_ HANDLE TokenHandle, _Out_ PULONG64 HostId // (WIN://PKGHOSTID) ); -#endif +#endif // PHNT_VERSION >= PHNT_WINDOWS_10_RS4 #if (PHNT_VERSION >= PHNT_WINDOWS_8_1) // rev @@ -10242,7 +11847,7 @@ RtlIsParentOfChildAppContainer( _In_ PSID ParentAppContainerSid, _In_ PSID ChildAppContainerSid ); -#endif +#endif // PHNT_VERSION >= PHNT_WINDOWS_8_1 #if (PHNT_VERSION >= PHNT_WINDOWS_11) // rev @@ -10252,7 +11857,7 @@ NTAPI RtlIsApiSetImplemented( _In_z_ PCSTR ApiSetName ); -#endif +#endif // PHNT_VERSION >= PHNT_WINDOWS_11 #if (PHNT_VERSION >= PHNT_WINDOWS_8) // rev @@ -10270,7 +11875,7 @@ NTAPI RtlIsPackageSid( _In_ PSID Sid ); -#endif +#endif // PHNT_VERSION >= PHNT_WINDOWS_8 #if (PHNT_VERSION >= PHNT_WINDOWS_8_1) // rev @@ -10280,7 +11885,7 @@ NTAPI RtlIsValidProcessTrustLabelSid( _In_ PSID Sid ); -#endif +#endif // PHNT_VERSION >= PHNT_WINDOWS_8_1 typedef enum _APPCONTAINER_SID_TYPE { @@ -10300,13 +11905,13 @@ RtlGetAppContainerSidType( _In_ PSID AppContainerSid, _Out_ PAPPCONTAINER_SID_TYPE AppContainerSidType ); -#endif +#endif // PHNT_VERSION >= PHNT_WINDOWS_8_1 NTSYSAPI NTSTATUS NTAPI RtlFlsAlloc( - _In_ PFLS_CALLBACK_FUNCTION Callback, + _In_opt_ PFLS_CALLBACK_FUNCTION Callback, _Out_ PULONG FlsIndex ); @@ -10315,7 +11920,7 @@ NTSYSAPI NTSTATUS NTAPI RtlFlsAllocEx( - _In_ PFLS_CALLBACK_FUNCTION Callback, + _In_opt_ PFLS_CALLBACK_FUNCTION Callback, _Out_ PULONG, _Out_ PULONG FlsIndex ); @@ -10327,7 +11932,6 @@ RtlFlsFree( _In_ ULONG FlsIndex ); -#if (PHNT_VERSION >= PHNT_WINDOWS_10_20H1) NTSYSAPI NTSTATUS NTAPI @@ -10336,29 +11940,33 @@ RtlFlsGetValue( _Out_ PVOID* FlsData ); +#if (PHNT_VERSION >= PHNT_WINDOWS_10_20H1) NTSYSAPI PVOID -WINAPI +NTAPI RtlFlsGetValue2( _In_ ULONG FlsIndex ); +#endif // PHNT_VERSION >= PHNT_WINDOWS_10_20H1 NTSYSAPI NTSTATUS NTAPI RtlFlsSetValue( _In_ ULONG FlsIndex, - _In_ PVOID FlsData + _In_opt_ PVOID FlsData ); +#define RTL_FLS_DATA_CLEANUP_PER_SLOT 1 +#define RTL_FLS_DATA_CLEANUP_DEALLOCATE 2 + NTSYSAPI -NTSTATUS +VOID NTAPI RtlProcessFlsData( - _In_ HANDLE ProcessHandle, - _Out_ PVOID* FlsData + _In_ PVOID FlsData, + _In_ ULONG Flags ); -#endif #if (PHNT_VERSION >= PHNT_WINDOWS_11) // rev @@ -10383,9 +11991,9 @@ NTSTATUS NTAPI RtlTlsSetValue( _In_ ULONG TlsIndex, - _In_ PVOID TlsData + _In_opt_ PVOID TlsData ); -#endif +#endif // PHNT_VERSION >= PHNT_WINDOWS_11 // // State isolation @@ -10420,9 +12028,11 @@ RtlGetPersistedStateLocation( _In_ ULONG BufferLengthIn, _Out_opt_ PULONG BufferLengthOut ); -#endif +#endif // PHNT_VERSION >= PHNT_WINDOWS_10_RS3 +// // Cloud Filters +// #if (PHNT_VERSION >= PHNT_WINDOWS_10_RS3) // msdn @@ -10492,7 +12102,6 @@ RtlSetThreadPlaceholderCompatibilityMode( #define PHCM_ERROR_NO_PEB ((CHAR)-3) #if (PHNT_VERSION >= PHNT_WINDOWS_10_RS4) - NTSYSAPI CHAR NTAPI @@ -10506,7 +12115,6 @@ NTAPI RtlSetProcessPlaceholderCompatibilityMode( _In_ CHAR Mode ); - #endif // PHNT_VERSION >= PHNT_WINDOWS_10_RS4 #if (PHNT_VERSION >= PHNT_WINDOWS_10_RS2) @@ -10561,6 +12169,16 @@ typedef struct _PS_PKG_CLAIM ULONG Origin; // PackageOrigin } PS_PKG_CLAIM, *PPS_PKG_CLAIM; +// private // WIN://BGKD +typedef enum _PSM_ACTIVATE_BACKGROUND_TYPE +{ + PsmActNotBackground = 0, + PsmActMixedHost = 1, + PsmActPureHost = 2, + PsmActSystemHost = 3, + PsmActInvalidType = 4, +} PSM_ACTIVATE_BACKGROUND_TYPE; + #if (PHNT_VERSION >= PHNT_WINDOWS_10) NTSYSAPI NTSTATUS @@ -10575,7 +12193,7 @@ RtlQueryPackageClaims( _Out_opt_ PPS_PKG_CLAIM PkgClaim, _Out_opt_ PULONG64 AttributesPresent ); -#endif +#endif // PHNT_VERSION >= PHNT_WINDOWS_10 #if (PHNT_VERSION >= PHNT_WINDOWS_8) NTSYSAPI @@ -10589,7 +12207,7 @@ RtlQueryPackageIdentity( _Inout_opt_ PSIZE_T AppIdSize, _Out_opt_ PBOOLEAN Packaged ); -#endif +#endif // PHNT_VERSION >= PHNT_WINDOWS_8 #if (PHNT_VERSION >= PHNT_WINDOWS_8_1) NTSYSAPI @@ -10604,9 +12222,11 @@ RtlQueryPackageIdentityEx( _Out_opt_ PGUID DynamicId, _Out_opt_ PULONG64 Flags ); -#endif +#endif // PHNT_VERSION >= PHNT_WINDOWS_8_1 +// // Protected policies +// #if (PHNT_VERSION >= PHNT_WINDOWS_8_1) // rev @@ -10627,7 +12247,7 @@ RtlSetProtectedPolicy( _In_ ULONG_PTR PolicyValue, _Out_ PULONG_PTR OldPolicyValue ); -#endif +#endif // PHNT_VERSION >= PHNT_WINDOWS_8_1 #if (PHNT_VERSION >= PHNT_WINDOWS_10_RS1) // rev @@ -10637,7 +12257,7 @@ NTAPI RtlIsEnclaveFeaturePresent( _In_ ULONG FeatureMask ); -#endif +#endif // PHNT_VERSION >= PHNT_WINDOWS_10_RS1 #if (PHNT_VERSION >= PHNT_WINDOWS_10) // private @@ -10647,7 +12267,7 @@ NTAPI RtlIsMultiSessionSku( VOID ); -#endif +#endif // PHNT_VERSION >= PHNT_WINDOWS_10 #if (PHNT_VERSION >= PHNT_WINDOWS_10_RS1) // private @@ -10657,7 +12277,7 @@ NTAPI RtlIsMultiUsersInSessionSku( VOID ); -#endif +#endif // PHNT_VERSION >= PHNT_WINDOWS_10_RS1 #if (PHNT_VERSION >= PHNT_WINDOWS_11) // rev @@ -10668,86 +12288,69 @@ RtlGetSessionProperties( _In_ ULONG SessionId, _Out_ PULONG SharedUserSessionId ); -#endif +#endif // PHNT_VERSION >= PHNT_WINDOWS_11 // 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 - RtlBsdItemRevocationListInfo, // 24H2 + RtlBsdItemVersionNumber, // qs: ULONG + RtlBsdItemProductType, // qs: NT_PRODUCT_TYPE (ULONG) + RtlBsdItemAabEnabled, // qs: BOOLEAN // AutoAdvancedBoot + RtlBsdItemAabTimeout, // qs: UCHAR // AdvancedBootMenuTimeout + RtlBsdItemBootGood, // qs: BOOLEAN // LastBootSucceeded + RtlBsdItemBootShutdown, // qs: BOOLEAN // LastBootShutdown + RtlBsdSleepInProgress, // qs: BOOLEAN // SleepInProgress + RtlBsdPowerTransition, // qs: RTL_BSD_DATA_POWER_TRANSITION + RtlBsdItemBootAttemptCount, // qs: UCHAR // BootAttemptCount + RtlBsdItemBootCheckpoint, // qs: UCHAR // LastBootCheckpoint + RtlBsdItemBootId, // qs: ULONG (USER_SHARED_DATA->BootId) // 10 + RtlBsdItemShutdownBootId, // qs: ULONG + RtlBsdItemReportedAbnormalShutdownBootId, // qs: ULONG + RtlBsdItemErrorInfo, // qs: RTL_BSD_DATA_ERROR_INFO + RtlBsdItemPowerButtonPressInfo, // qs: RTL_BSD_POWER_BUTTON_PRESS_INFO + RtlBsdItemChecksum, // q: UCHAR + RtlBsdPowerTransitionExtension, // qs: RTL_BSD_DATA_POWER_TRANSITION_EXTENSION + RtlBsdItemFeatureConfigurationState, // qs: ULONG + RtlBsdItemRevocationListInfo, // qs: RTL_BSD_ITEM_REVOCATION_LIST // 24H2 RtlBsdItemMax } RTL_BSD_ITEM_TYPE; -// ros -typedef struct _RTL_BSD_DATA_POWER_TRANSITION +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; + UCHAR PowerButton : 1; + UCHAR SleepButton : 1; + UCHAR LidClose : 1; + UCHAR SystemIdle : 1; + UCHAR UserPresent : 1; // Power setting "Keep Alive" + UCHAR ApmBattery : 1; + UCHAR Reserved : 2; } RTL_BSD_DATA_POWER_TRANSITION, *PRTL_BSD_DATA_POWER_TRANSITION; -// ros -typedef struct _RTL_BSD_DATA_ERROR_INFO +typedef struct _RTL_BSD_DATA_ERROR_INFO { - ULONG BootId; - ULONG RepeatCount; - ULONG OtherErrorCount; - ULONG Code; - ULONG OtherErrorCount2; + ULONG BootId; // The Boot ID where the error occurred + ULONG RepeatCount; // How many times this specific error happened + ULONG OtherErrorCount; // Count of other errors } RTL_BSD_DATA_ERROR_INFO, *PRTL_BSD_DATA_ERROR_INFO; -// ros -typedef struct _RTL_BSD_POWER_BUTTON_PRESS_INFO +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; + ULONG LastPressBootId; + ULONG LastPressTime; // Time in seconds since boot + ULONG LastReleaseTime; + ULONG ButtonPressCount; + ULONG CoalescedPressTime; // Total time pressed across recent boots + ULONG CoalescedPressCount; } RTL_BSD_POWER_BUTTON_PRESS_INFO, *PRTL_BSD_POWER_BUTTON_PRESS_INFO; +typedef struct _RTL_BSD_DATA_POWER_TRANSITION_EXTENSION +{ + UCHAR SystemIdleTransition : 1; + UCHAR FanError : 1; + UCHAR ThermalShutdown : 1; + UCHAR Reserved : 5; +} RTL_BSD_DATA_POWER_TRANSITION_EXTENSION, *PRTL_BSD_DATA_POWER_TRANSITION_EXTENSION; + // private typedef struct _RTL_BSD_ITEM { @@ -10810,7 +12413,7 @@ NTAPI RtlRestoreBootStatusDefaults( _In_ HANDLE FileHandle ); -#endif +#endif // PHNT_VERSION >= PHNT_WINDOWS_10_RS1 #if (PHNT_VERSION >= PHNT_WINDOWS_10_RS3) // rev @@ -10828,8 +12431,8 @@ NTAPI RtlGetSystemBootStatus( _In_ RTL_BSD_ITEM_TYPE BootStatusInformationClass, _Out_ PVOID DataBuffer, - _In_ ULONG DataLength, - _Out_opt_ PULONG ReturnLength + _In_ ULONG DataLength + //_Out_opt_ PULONG ReturnLength ); // rev @@ -10839,8 +12442,8 @@ NTAPI RtlSetSystemBootStatus( _In_ RTL_BSD_ITEM_TYPE BootStatusInformationClass, _In_ PVOID DataBuffer, - _In_ ULONG DataLength, - _Out_opt_ PULONG ReturnLength + _In_ ULONG DataLength + //_Out_opt_ PULONG ReturnLength ); #endif // PHNT_VERSION >= PHNT_WINDOWS_10_RS3 @@ -10870,8 +12473,6 @@ RtlSetProxiedProcessId( ); #endif // PHNT_VERSION >= PHNT_WINDOWS_8 -#if (PHNT_VERSION >= PHNT_WINDOWS_VISTA) - NTSYSAPI NTSTATUS NTAPI @@ -10880,14 +12481,12 @@ RtlFindClosestEncodableLength( _Out_ PULONGLONG TargetLength ); -#endif // PHNT_VERSION >= PHNT_WINDOWS_VISTA - // // Memory cache // -_Function_class_(RTL_SECURE_MEMORY_CACHE_CALLBACK) -typedef NTSTATUS (NTAPI RTL_SECURE_MEMORY_CACHE_CALLBACK)( +typedef _Function_class_(RTL_SECURE_MEMORY_CACHE_CALLBACK) +NTSTATUS NTAPI RTL_SECURE_MEMORY_CACHE_CALLBACK( _In_ PVOID Address, _In_ SIZE_T Length ); @@ -10917,7 +12516,9 @@ RtlFlushSecureMemoryCache( _In_opt_ SIZE_T MemoryLength ); +// // Feature configuration +// // private typedef ULONG RTL_FEATURE_ID; @@ -10945,7 +12546,7 @@ typedef enum _RTL_FEATURE_CONFIGURATION_TYPE // private typedef struct _RTL_FEATURE_CONFIGURATION { - RTL_FEATURE_ID FeatureId; + ULONG FeatureId; union { ULONG Flags; @@ -10960,14 +12561,82 @@ typedef struct _RTL_FEATURE_CONFIGURATION ULONG Reserved : 16; }; }; - RTL_FEATURE_VARIANT_PAYLOAD VariantPayload; + ULONG VariantPayload; } RTL_FEATURE_CONFIGURATION, *PRTL_FEATURE_CONFIGURATION; +// private +typedef struct _RTL_FEATURE_CONFIGURATION_INTERNAL +{ + ULONG FeatureId; + union + { + struct + { + ULONG Priority : 4; + ULONG EnabledState : 2; + ULONG IsWexpConfiguration : 1; + ULONG HasSubscriptions : 1; + ULONG Variant : 6; + ULONG VariantPayloadKind : 2; + ULONG Reserved : 16; + }; + ULONG Flags; + }; + ULONG VariantPayload; + union + { + struct + { + ULONG ChangeTimeUpgrade : 1; + ULONG HasGroupBypass : 1; + ULONG Reserved2 : 30; + }; + ULONG Flags2; + }; +} RTL_FEATURE_CONFIGURATION_INTERNAL, *PRTL_FEATURE_CONFIGURATION_INTERNAL; + +// private +typedef struct _SYSTEM_FEATURE_CONFIGURATION_SECTIONS_INFORMATION_ENTRY +{ + RTL_FEATURE_CHANGE_STAMP ChangeStamp; + HANDLE SectionHandle; + SIZE_T Size; +} SYSTEM_FEATURE_CONFIGURATION_SECTIONS_INFORMATION_ENTRY, *PSYSTEM_FEATURE_CONFIGURATION_SECTIONS_INFORMATION_ENTRY; + +// private +typedef enum _SYSTEM_FEATURE_CONFIGURATION_SECTION_TYPE +{ + SystemFeatureConfigurationSectionTypeBoot = 0, + SystemFeatureConfigurationSectionTypeRuntime = 1, + SystemFeatureConfigurationSectionTypeUsageTriggers = 2, + SystemFeatureConfigurationSectionTypeGoverned = 3, + SystemFeatureConfigurationSectionTypeCount +} SYSTEM_FEATURE_CONFIGURATION_SECTION_TYPE; + +// private +typedef struct _SYSTEM_FEATURE_CONFIGURATION_SECTIONS_REQUEST +{ + RTL_FEATURE_CHANGE_STAMP PreviousChangeStamps[SystemFeatureConfigurationSectionTypeCount]; +} SYSTEM_FEATURE_CONFIGURATION_SECTIONS_REQUEST, *PSYSTEM_FEATURE_CONFIGURATION_SECTIONS_REQUEST; + +// private +typedef struct _SYSTEM_FEATURE_CONFIGURATION_SECTIONS_INFORMATION +{ + RTL_FEATURE_CHANGE_STAMP OverallChangeStamp; + SYSTEM_FEATURE_CONFIGURATION_SECTIONS_INFORMATION_ENTRY Descriptors[SystemFeatureConfigurationSectionTypeCount]; +} SYSTEM_FEATURE_CONFIGURATION_SECTIONS_INFORMATION, *PSYSTEM_FEATURE_CONFIGURATION_SECTIONS_INFORMATION; + +//typedef struct _SYSTEM_FEATURE_USAGE_SUBSCRIPTION_UPDATE +//{ +// ULONG UpdateCount; +// _Field_size_(UpdateCount) SYSTEM_FEATURE_USAGE_SUBSCRIPTION_UPDATE_ENTRY Updates[ANYSIZE_ARRAY]; +//} SYSTEM_FEATURE_USAGE_SUBSCRIPTION_UPDATE, *PSYSTEM_FEATURE_USAGE_SUBSCRIPTION_UPDATE; + // private typedef struct _RTL_FEATURE_CONFIGURATION_TABLE { ULONG FeatureCount; - _Field_size_(FeatureCount) RTL_FEATURE_CONFIGURATION Features[ANYSIZE_ARRAY]; + _Field_size_(FeatureCount) RTL_FEATURE_CONFIGURATION_INTERNAL Features[ANYSIZE_ARRAY]; } RTL_FEATURE_CONFIGURATION_TABLE, *PRTL_FEATURE_CONFIGURATION_TABLE; // private @@ -11032,7 +12701,19 @@ typedef struct _RTL_FEATURE_CONFIGURATION_UPDATE RTL_FEATURE_CONFIGURATION_PRIORITY Priority; RTL_FEATURE_ENABLED_STATE EnabledState; RTL_FEATURE_ENABLED_STATE_OPTIONS EnabledStateOptions; - RTL_FEATURE_VARIANT Variant; + + union + { + ULONG VariantFlags; + struct + { + ULONG Variant : 8; + ULONG ChangeTimeUpgrade : 1; + ULONG HasGroupBypass : 1; + ULONG ReservedFlags : 22; + } DUMMYSTRUCTNAME; + } DUMMYUNIONNAME; + UCHAR Reserved[3]; RTL_FEATURE_VARIANT_PAYLOAD_KIND VariantPayloadKind; RTL_FEATURE_VARIANT_PAYLOAD VariantPayload; @@ -11045,12 +12726,21 @@ 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 +{ + RTL_FEATURE_ID FeatureId; + USHORT ReportingKind; + USHORT ReportingOptions; + RTL_FEATURE_USAGE_SUBSCRIPTION_TARGET ReportingTarget; +} SYSTEM_FEATURE_USAGE_SUBSCRIPTION_DETAILS, *PSYSTEM_FEATURE_USAGE_SUBSCRIPTION_DETAILS; + // private typedef struct _RTL_FEATURE_USAGE_DATA { RTL_FEATURE_ID FeatureId; USHORT ReportingKind; - USHORT Reserved; + USHORT UsageCount; } RTL_FEATURE_USAGE_DATA, *PRTL_FEATURE_USAGE_DATA; // private @@ -11070,8 +12760,15 @@ typedef struct _RTL_FEATURE_USAGE_SUBSCRIPTION_TABLE } RTL_FEATURE_USAGE_SUBSCRIPTION_TABLE, *PRTL_FEATURE_USAGE_SUBSCRIPTION_TABLE; // private -_Function_class_(RTL_FEATURE_CONFIGURATION_CHANGE_CALLBACK) -typedef VOID (NTAPI RTL_FEATURE_CONFIGURATION_CHANGE_CALLBACK)( +typedef struct _SYSTEM_FEATURE_USAGE_SUBSCRIPTION_UPDATE_ENTRY +{ + ULONG Remove; + RTL_FEATURE_USAGE_SUBSCRIPTION_DETAILS Details; +} SYSTEM_FEATURE_USAGE_SUBSCRIPTION_UPDATE_ENTRY, *PSYSTEM_FEATURE_USAGE_SUBSCRIPTION_UPDATE_ENTRY; + +// private +typedef _Function_class_(RTL_FEATURE_CONFIGURATION_CHANGE_CALLBACK) +VOID NTAPI RTL_FEATURE_CONFIGURATION_CHANGE_CALLBACK( _In_opt_ PVOID Context ); typedef RTL_FEATURE_CONFIGURATION_CHANGE_CALLBACK *PRTL_FEATURE_CONFIGURATION_CHANGE_CALLBACK; @@ -11093,9 +12790,9 @@ typedef struct _SYSTEM_FEATURE_CONFIGURATION_INFORMATION // private typedef enum _SYSTEM_FEATURE_CONFIGURATION_UPDATE_TYPE { - SystemFeatureConfigurationUpdateTypeUpdate = 0, - SystemFeatureConfigurationUpdateTypeOverwrite = 1, - SystemFeatureConfigurationUpdateTypeCount = 2, + SystemFeatureConfigurationUpdateTypeUpdate = 0, + SystemFeatureConfigurationUpdateTypeOverwrite = 1, + SystemFeatureConfigurationUpdateTypeCount = 2, } SYSTEM_FEATURE_CONFIGURATION_UPDATE_TYPE, *PSYSTEM_FEATURE_CONFIGURATION_UPDATE_TYPE; // private @@ -11123,55 +12820,25 @@ typedef struct _SYSTEM_FEATURE_CONFIGURATION_UPDATE } SYSTEM_FEATURE_CONFIGURATION_UPDATE, *PSYSTEM_FEATURE_CONFIGURATION_UPDATE; // private -typedef struct _SYSTEM_FEATURE_CONFIGURATION_SECTIONS_INFORMATION_ENTRY -{ - RTL_FEATURE_CHANGE_STAMP ChangeStamp; - PVOID Section; - SIZE_T Size; -} SYSTEM_FEATURE_CONFIGURATION_SECTIONS_INFORMATION_ENTRY, *PSYSTEM_FEATURE_CONFIGURATION_SECTIONS_INFORMATION_ENTRY; +//typedef struct _SYSTEM_FEATURE_USAGE_SUBSCRIPTION_DETAILS +//{ +// RTL_FEATURE_ID FeatureId; +// USHORT ReportingKind; +// USHORT ReportingOptions; +// RTL_FEATURE_USAGE_SUBSCRIPTION_TARGET ReportingTarget; +//} SYSTEM_FEATURE_USAGE_SUBSCRIPTION_DETAILS, *PSYSTEM_FEATURE_USAGE_SUBSCRIPTION_DETAILS; -// private -typedef enum _SYSTEM_FEATURE_CONFIGURATION_SECTION_TYPE -{ - SystemFeatureConfigurationSectionTypeBoot = 0, - SystemFeatureConfigurationSectionTypeRuntime = 1, - SystemFeatureConfigurationSectionTypeUsageTriggers = 2, - SystemFeatureConfigurationSectionTypeCount = 3, -} SYSTEM_FEATURE_CONFIGURATION_SECTION_TYPE; - -// private -typedef struct _SYSTEM_FEATURE_CONFIGURATION_SECTIONS_REQUEST -{ - RTL_FEATURE_CHANGE_STAMP PreviousChangeStamps[SystemFeatureConfigurationSectionTypeCount]; -} SYSTEM_FEATURE_CONFIGURATION_SECTIONS_REQUEST, *PSYSTEM_FEATURE_CONFIGURATION_SECTIONS_REQUEST; - -// private -typedef struct _SYSTEM_FEATURE_CONFIGURATION_SECTIONS_INFORMATION -{ - RTL_FEATURE_CHANGE_STAMP OverallChangeStamp; - SYSTEM_FEATURE_CONFIGURATION_SECTIONS_INFORMATION_ENTRY Descriptors[SystemFeatureConfigurationSectionTypeCount]; -} SYSTEM_FEATURE_CONFIGURATION_SECTIONS_INFORMATION, *PSYSTEM_FEATURE_CONFIGURATION_SECTIONS_INFORMATION; - -// private -typedef struct _SYSTEM_FEATURE_USAGE_SUBSCRIPTION_DETAILS -{ - RTL_FEATURE_ID FeatureId; - USHORT ReportingKind; - USHORT ReportingOptions; - RTL_FEATURE_USAGE_SUBSCRIPTION_TARGET ReportingTarget; -} SYSTEM_FEATURE_USAGE_SUBSCRIPTION_DETAILS, *PSYSTEM_FEATURE_USAGE_SUBSCRIPTION_DETAILS; - -typedef struct _SYSTEM_FEATURE_USAGE_SUBSCRIPTION_UPDATE_ENTRY -{ - ULONG Remove; - RTL_FEATURE_USAGE_SUBSCRIPTION_DETAILS Details; -} SYSTEM_FEATURE_USAGE_SUBSCRIPTION_UPDATE_ENTRY, *PSYSTEM_FEATURE_USAGE_SUBSCRIPTION_UPDATE_ENTRY; - -typedef struct _SYSTEM_FEATURE_USAGE_SUBSCRIPTION_UPDATE -{ - ULONG UpdateCount; - _Field_size_(UpdateCount) SYSTEM_FEATURE_USAGE_SUBSCRIPTION_UPDATE_ENTRY Updates[ANYSIZE_ARRAY]; -} SYSTEM_FEATURE_USAGE_SUBSCRIPTION_UPDATE, *PSYSTEM_FEATURE_USAGE_SUBSCRIPTION_UPDATE; +//typedef struct _SYSTEM_FEATURE_USAGE_SUBSCRIPTION_UPDATE_ENTRY +//{ +// ULONG Remove; +// RTL_FEATURE_USAGE_SUBSCRIPTION_DETAILS Details; +//} SYSTEM_FEATURE_USAGE_SUBSCRIPTION_UPDATE_ENTRY, *PSYSTEM_FEATURE_USAGE_SUBSCRIPTION_UPDATE_ENTRY; +// +//typedef struct _SYSTEM_FEATURE_USAGE_SUBSCRIPTION_UPDATE +//{ +// ULONG UpdateCount; +// _Field_size_(UpdateCount) SYSTEM_FEATURE_USAGE_SUBSCRIPTION_UPDATE_ENTRY Updates[ANYSIZE_ARRAY]; +//} SYSTEM_FEATURE_USAGE_SUBSCRIPTION_UPDATE, *PSYSTEM_FEATURE_USAGE_SUBSCRIPTION_UPDATE; #if (PHNT_VERSION >= PHNT_WINDOWS_10_20H1) @@ -11216,6 +12883,29 @@ RtlQueryAllFeatureConfigurations( _Inout_ PSIZE_T ConfigurationCount ); +// private +NTSYSAPI +NTSTATUS +NTAPI +RtlQueryAllInternalFeatureConfigurations( + _In_ RTL_FEATURE_CONFIGURATION_TYPE ConfigurationType, + _Out_opt_ PRTL_FEATURE_CHANGE_STAMP ChangeStamp, + _Out_writes_(*ConfigurationCount) PRTL_FEATURE_CONFIGURATION Configurations, + _Inout_ PSIZE_T ConfigurationCount + ); + +// private +NTSYSAPI +NTSTATUS +NTAPI +RtlQueryAllInternalRuntimeFeatureConfigurations( + _In_ RTL_FEATURE_ID FeatureId, + _In_ RTL_FEATURE_CONFIGURATION_TYPE ConfigurationType, + _Out_opt_ PRTL_FEATURE_CHANGE_STAMP ChangeStamp, + _Out_writes_(*ConfigurationCount) PRTL_FEATURE_CONFIGURATION Configurations, + _Inout_ PSIZE_T ConfigurationCount + ); + // private NTSYSAPI RTL_FEATURE_CHANGE_STAMP @@ -11269,7 +12959,7 @@ RtlUnsubscribeFromFeatureUsageNotifications( _In_reads_(SubscriptionCount) PRTL_FEATURE_USAGE_SUBSCRIPTION_DETAILS SubscriptionDetails, _In_ SIZE_T SubscriptionCount ); -#endif +#endif // PHNT_VERSION >= PHNT_WINDOWS_10_20H1 // private #if (PHNT_VERSION >= PHNT_WINDOWS_11) @@ -11282,7 +12972,7 @@ RtlOverwriteFeatureConfigurationBuffer( _In_reads_bytes_opt_(ConfigurationBufferSize) PVOID ConfigurationBuffer, _In_ ULONG ConfigurationBufferSize ); -#endif +#endif // PHNT_VERSION >= PHNT_WINDOWS_11 // rev NTSYSAPI @@ -11294,6 +12984,18 @@ RtlNotifyFeatureToggleUsage( _In_ ULONG Flags ); +// rev +NTSYSAPI +ULONG +NTAPI +RtlGetFeatureTogglesChangeToken( + VOID + ); + +// +// Run Once +// + #ifndef _RTL_RUN_ONCE_DEF #define _RTL_RUN_ONCE_DEF // @@ -11318,8 +13020,6 @@ typedef union _RTL_RUN_ONCE } RTL_RUN_ONCE, *PRTL_RUN_ONCE; #endif // _RTL_RUN_ONCE_DEF -#if (PHNT_VERSION >= PHNT_WINDOWS_VISTA) - NTSYSAPI VOID NTAPI @@ -11328,9 +13028,7 @@ RtlRunOnceInitialize( ); typedef _Function_class_(RTL_RUN_ONCE_INIT_FN) -LOGICAL -NTAPI -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 @@ -11367,7 +13065,9 @@ RtlRunOnceComplete( _In_opt_ PVOID Context ); -#endif // PHNT_VERSION >= PHNT_WINDOWS_VISTA +// +// WNF (Windows Notification Facility) +// #if (PHNT_VERSION >= PHNT_WINDOWS_10) @@ -11384,9 +13084,7 @@ RtlEqualWnfChangeStamps( _Always_(_Post_satisfies_(return == STATUS_NO_MEMORY || return == STATUS_RETRY || return == STATUS_SUCCESS)) typedef _Function_class_(WNF_USER_CALLBACK) -NTSTATUS -NTAPI -WNF_USER_CALLBACK( +NTSTATUS NTAPI WNF_USER_CALLBACK( _In_ WNF_STATE_NAME StateName, _In_ WNF_CHANGE_STAMP ChangeStamp, _In_opt_ PWNF_TYPE_ID TypeId, @@ -11418,25 +13116,29 @@ RtlPublishWnfStateData( _In_opt_ const VOID* ExplicitScope ); +typedef struct WNF_USER_SUBSCRIPTION *PWNF_USER_SUBSCRIPTION; + +#define WNF_CREATE_SERIALIZATION_GROUP_FLAG 0x00000001L + NTSYSAPI NTSTATUS NTAPI RtlSubscribeWnfStateChangeNotification( - _Outptr_ PVOID* SubscriptionHandle, // PWNF_USER_SUBSCRIPTION + _Out_ PWNF_USER_SUBSCRIPTION* SubscriptionHandle, _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 + _In_ ULONG Flags ); NTSYSAPI NTSTATUS NTAPI RtlUnsubscribeWnfStateChangeNotification( - _In_ PWNF_USER_CALLBACK Callback + _In_ PWNF_USER_SUBSCRIPTION SubscriptionHandle ); NTSYSAPI @@ -11448,9 +13150,22 @@ RtlWnfDllUnloadCallback( #endif // PHNT_VERSION >= PHNT_WINDOWS_10 +#if (PHNT_VERSION >= PHNT_WINDOWS_10_20H1) +NTSYSAPI +ULONG_PTR +NTAPI +RtlGetReturnAddressHijackTarget( + VOID + ); +#endif + #define COPY_FILE_CHUNK_DUPLICATE_EXTENTS 0x00000001L // 24H2 #define VALID_COPY_FILE_CHUNK_FLAGS (COPY_FILE_CHUNK_DUPLICATE_EXTENTS) +// +// Property Store +// + #if (PHNT_VERSION >= PHNT_WINDOWS_11) // rev NTSYSAPI @@ -11483,7 +13198,15 @@ RtlCompareExchangePropertyStore( #endif // PHNT_VERSION >= PHNT_WINDOWS_11 #if (PHNT_VERSION >= PHNT_WINDOWS_11) -typedef enum _THREAD_STATE_CHANGE_TYPE THREAD_STATE_CHANGE_TYPE, *PTHREAD_STATE_CHANGE_TYPE; +// rev +NTSYSAPI +NTSTATUS +NTAPI +RtlWow64ChangeProcessState( + _In_ HANDLE ProcessStateChangeHandle, + _In_ HANDLE ProcessHandle, + _In_ PROCESS_STATE_CHANGE_TYPE StateChangeType + ); // rev NTSYSAPI @@ -11492,27 +13215,10 @@ 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 + _In_ THREAD_STATE_CHANGE_TYPE StateChangeType ); #endif // PHNT_VERSION >= PHNT_WINDOWS_11 -#ifdef PHNT_INLINE_TYPEDEFS -#if (PHNT_VERSION >= PHNT_WINDOWS_11) -// rev -FORCEINLINE -USHORT -NTAPI -RtlGetCurrentThreadPrimaryGroup( - VOID - ) -{ - return NtCurrentTeb()->PrimaryGroupAffinity.Group; -} -#endif // PHNT_VERSION >= PHNT_WINDOWS_11 -#else #if (PHNT_VERSION >= PHNT_WINDOWS_10_RS1) // rev NTSYSAPI @@ -11522,7 +13228,29 @@ RtlGetCurrentThreadPrimaryGroup( VOID ); #endif // PHNT_VERSION >= PHNT_WINDOWS_10_RS1 -#endif // PHNT_INLINE_TYPEDEFS + +#if (PHNT_VERSION >= PHNT_WINDOWS_11_24H2) +// rev +NTSYSAPI +NTSTATUS +NTAPI +RtlQueryProcessAvailableCpus( + _In_ HANDLE ProcessHandle, + _In_ PKAFFINITY_EX Affinity, + _In_ ULONG64 ObservedSequenceNumber, + _Out_opt_ PULONG64 SequenceNumber + ); + +// rev +NTSYSAPI +NTSTATUS +NTAPI +RtlQueryProcessAvailableCpusCount( + _In_ HANDLE ProcessHandle, + _Out_ PULONG AvailableCpusCount, + _Out_opt_ PULONG64 SequenceNumber + ); +#endif // PHNT_VERSION >= PHNT_WINDOWS_11_24H2 #endif // _NTRTL_H @@ -11548,143 +13276,6 @@ RtlGetCurrentThreadPrimaryGroup( #define RtlSetTimer RtlCreateTimer #define RtlRestoreLastWin32Error RtlSetLastWin32Error #endif // PHNT_INLINE_NAME_FORWARDERS - -#ifndef PHNT_INLINE_PEB_FORWARDERS -FORCEINLINE -PPEB -NTAPI -RtlGetCurrentPeb( - VOID - ) -{ - return NtCurrentPeb(); -} - -FORCEINLINE -NTSTATUS -NTAPI -RtlAcquirePebLock( - VOID - ) -{ - return RtlEnterCriticalSection(NtCurrentPeb()->FastPebLock); -} - -FORCEINLINE -NTSTATUS -NTAPI -RtlReleasePebLock( - VOID - ) -{ - return RtlLeaveCriticalSection(NtCurrentPeb()->FastPebLock); -} -#endif // PHNT_INLINE_PEB_FORWARDERS - -#ifndef PHNT_INLINE_FREE_FORWARDERS -//#define RtlFreeUnicodeString(UnicodeString) {if ((UnicodeString)->Buffer) RtlFreeHeap(RtlProcessHeap(), 0, (UnicodeString)->Buffer); memset(UnicodeString, 0, sizeof(UNICODE_STRING));} -FORCEINLINE -VOID -NTAPI -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 -NTAPI -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 -NTAPI -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 -NTAPI -RtlFreeSid( - _In_ _Post_invalid_ PSID Sid - ) -{ - RtlFreeHeap(RtlProcessHeap(), 0, Sid); - return NULL; -} - -//#define RtlDeleteBoundaryDescriptor(BoundaryDescriptor) RtlFreeHeap(RtlProcessHeap(), 0, (BoundaryDescriptor)) -FORCEINLINE -VOID -NTAPI -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 -NTAPI -RtlDestroyEnvironment( - _In_ _Post_invalid_ PVOID Environment - ) -{ - RtlFreeHeap(RtlProcessHeap(), 0, Environment); - return STATUS_SUCCESS; -} - -//#define RtlDestroyProcessParameters(ProcessParameters) RtlFreeHeap(RtlProcessHeap(), 0, (ProcessParameters)) -FORCEINLINE -NTSTATUS -NTAPI -RtlDestroyProcessParameters( - _In_ _Post_invalid_ PRTL_USER_PROCESS_PARAMETERS ProcessParameters - ) -{ - RtlFreeHeap(RtlProcessHeap(), 0, ProcessParameters); - return STATUS_SUCCESS; -} -#endif // PHNT_INLINE_FREE_FORWARDERS // end_forwarders #endif // _NTRTL_FWD_H diff --git a/ntsam.h b/ntsam.h index 6c6dcbf..940c441 100644 --- a/ntsam.h +++ b/ntsam.h @@ -7,6 +7,10 @@ #ifndef _NTSAM_H #define _NTSAM_H +// +// Types +// + #define SAM_MAXIMUM_LOOKUP_COUNT (1000) #define SAM_MAXIMUM_LOOKUP_LENGTH (32000) #define SAM_MAX_PASSWORD_LENGTH (256) @@ -41,21 +45,32 @@ typedef struct _SAM_BYTE_ARRAY_32K typedef SAM_BYTE_ARRAY_32K SAM_SHELL_OBJECT_PROPERTIES, *PSAM_SHELL_OBJECT_PROPERTIES; +// // Basic +// +NTSYSAPI NTSTATUS NTAPI SamFreeMemory( _In_ PVOID Buffer ); +/** + * The SamCloseHandle method closes (that is, releases server-side resources used by) any handle. + * + * \param SamHandle The object handle. + * \return NTSTATUS Successful or errant status. + * \sa https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-samr/55d134df-e257-48ad-8afa-cb2ca45cd3cc + */ +NTSYSAPI NTSTATUS NTAPI SamCloseHandle( _In_ SAM_HANDLE SamHandle ); -_Check_return_ +NTSYSAPI NTSTATUS NTAPI SamSetSecurityObject( @@ -64,7 +79,16 @@ SamSetSecurityObject( _In_ PSECURITY_DESCRIPTOR SecurityDescriptor ); -_Check_return_ +/** + * The SamQuerySecurityObject method queries the access control on a server, domain, user, group, or alias object. + * + * \param ObjectHandle The "Domain", "User", "Group", or "Alias" object handle. + * \param SecurityInformation A bit field that specifies which fields of SecurityDescriptor the client is requesting to be returned. + * \param SecurityDescriptor A security descriptor expressing accesses that are specific to the ObjectHandle and the owner and group of the object. + * \return NTSTATUS Successful or errant status. + * \sa https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-samr/0ecf8fec-d17e-4a88-b7f1-e0f0f66790db + */ +NTSYSAPI NTSTATUS NTAPI SamQuerySecurityObject( @@ -73,7 +97,16 @@ SamQuerySecurityObject( _Outptr_ PSECURITY_DESCRIPTOR *SecurityDescriptor ); -_Check_return_ +/** + * The SamRidToSid method obtains the SID of an account, given a RID. + * + * \param ObjectHandle The "Domain", "User", "Group", or "Alias" object handle. + * \param Rid The RID of the object. + * \param Sid The SID of the object referenced by Rid. + * \return NTSTATUS Successful or errant status. + * \sa https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-samr/00ff8192-a4f6-45ba-9f65-917e46b6a693 + */ +NTSYSAPI NTSTATUS NTAPI SamRidToSid( @@ -82,7 +115,17 @@ SamRidToSid( _Outptr_ PSID *Sid ); +NTSYSAPI +NTSTATUS +NTAPI +SamQueryLapsManagedAccount( + _In_ SAM_HANDLE ObjectHandle, + _Outptr_ PSID *AccountSid + ); + +// // Server +// #define SAM_SERVER_CONNECT 0x0001 #define SAM_SERVER_SHUTDOWN 0x0002 @@ -113,39 +156,53 @@ SamRidToSid( typedef struct _RPC_AUTH_IDENTITY_HANDLE *PRPC_AUTH_IDENTITY_HANDLE; +// // Functions +// -_Check_return_ +/** + * The SamConnect method returns a handle to a server. + * + * \param ServerName The NETBIOS name of the server; this parameter MAY be ignored on receipt. + * \param ServerHandle A handle representing a server. + * \param DesiredAccess The access requested for ServerHandle upon output. + * \param ObjectAttributes The OBJECT_ATTRIBUTES structure that specifies the properties of the server handle to be opened. + * \return NTSTATUS Successful or errant status. + * \sa https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-samr/47492d59-e095-4398-b03e-8a062b989123 + */ +NTSYSAPI NTSTATUS NTAPI SamConnect( - _In_opt_ PUNICODE_STRING ServerName, + _In_opt_ PCUNICODE_STRING ServerName, _Out_ PSAM_HANDLE ServerHandle, _In_ ACCESS_MASK DesiredAccess, - _In_ POBJECT_ATTRIBUTES ObjectAttributes + _In_ PCOBJECT_ATTRIBUTES ObjectAttributes ); -_Check_return_ +NTSYSAPI NTSTATUS NTAPI SamConnectWithCreds( - _In_ PUNICODE_STRING ServerName, + _In_ PCUNICODE_STRING ServerName, _Out_ PSAM_HANDLE ServerHandle, _In_ ACCESS_MASK DesiredAccess, - _In_ POBJECT_ATTRIBUTES ObjectAttributes, + _In_ PCOBJECT_ATTRIBUTES ObjectAttributes, _In_ PRPC_AUTH_IDENTITY_HANDLE Creds, _In_ PWCHAR Spn, - _Out_ BOOL* pfDstIsW2K + _Out_ PBOOL DestinationIsWindows2K ); -_Check_return_ +NTSYSAPI NTSTATUS NTAPI SamShutdownSamServer( _In_ SAM_HANDLE ServerHandle ); +// // Domain +// #define DOMAIN_READ_PASSWORD_PARAMETERS 0x0001 #define DOMAIN_WRITE_PASSWORD_PARAMS 0x0002 @@ -192,23 +249,26 @@ SamShutdownSamServer( #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 + DomainPasswordInformation = 1, // qs: DOMAIN_PASSWORD_INFORMATION + DomainGeneralInformation, // q: DOMAIN_GENERAL_INFORMATION + DomainLogoffInformation, // qs: DOMAIN_LOGOFF_INFORMATION + DomainOemInformation, // qs: DOMAIN_OEM_INFORMATION + DomainNameInformation, // q: DOMAIN_NAME_INFORMATION + DomainReplicationInformation, // qs: DOMAIN_REPLICATION_INFORMATION + DomainServerRoleInformation, // qs: DOMAIN_SERVER_ROLE_INFORMATION + DomainModifiedInformation, // q: DOMAIN_MODIFIED_INFORMATION + DomainStateInformation, // qs: DOMAIN_STATE_INFORMATION + DomainUasInformation, // qs: DOMAIN_UAS_INFORMATION + DomainGeneralInformation2, // q: DOMAIN_GENERAL_INFORMATION2 + DomainLockoutInformation, // qs: DOMAIN_LOCKOUT_INFORMATION + DomainModifiedInformation2, // q: DOMAIN_MODIFIED_INFORMATION2 + DomainMaxInformation } DOMAIN_INFORMATION_CLASS; typedef enum _DOMAIN_SERVER_ENABLE_STATE @@ -223,7 +283,6 @@ typedef enum _DOMAIN_SERVER_ROLE DomainServerRolePrimary } DOMAIN_SERVER_ROLE, *PDOMAIN_SERVER_ROLE; -#include typedef struct _DOMAIN_GENERAL_INFORMATION { LARGE_INTEGER ForceLogoff; @@ -238,9 +297,7 @@ typedef struct _DOMAIN_GENERAL_INFORMATION ULONG GroupCount; ULONG AliasCount; } DOMAIN_GENERAL_INFORMATION, *PDOMAIN_GENERAL_INFORMATION; -#include -#include typedef struct _DOMAIN_GENERAL_INFORMATION2 { DOMAIN_GENERAL_INFORMATION I1; @@ -248,7 +305,6 @@ typedef struct _DOMAIN_GENERAL_INFORMATION2 LARGE_INTEGER LockoutObservationWindow; // delta time USHORT LockoutThreshold; } DOMAIN_GENERAL_INFORMATION2, *PDOMAIN_GENERAL_INFORMATION2; -#include typedef struct _DOMAIN_UAS_INFORMATION { @@ -267,7 +323,9 @@ typedef struct _DOMAIN_PASSWORD_INFORMATION LARGE_INTEGER MinPasswordAge; } DOMAIN_PASSWORD_INFORMATION, *PDOMAIN_PASSWORD_INFORMATION; +// // PasswordProperties flags +// #define DOMAIN_PASSWORD_COMPLEX 0x00000001L #define DOMAIN_PASSWORD_NO_ANON_CHANGE 0x00000002L @@ -277,7 +335,7 @@ typedef struct _DOMAIN_PASSWORD_INFORMATION #define DOMAIN_REFUSE_PASSWORD_CHANGE 0x00000020L #define DOMAIN_NO_LM_OWF_CHANGE 0x00000040L -#endif +#endif // _DOMAIN_PASSWORD_INFORMATION_DEFINED typedef enum _DOMAIN_PASSWORD_CONSTRUCTION { @@ -335,16 +393,19 @@ typedef struct _DOMAIN_LOCKOUT_INFORMATION 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 + 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_MACHINE + DomainDisplayMax } DOMAIN_DISPLAY_INFORMATION, *PDOMAIN_DISPLAY_INFORMATION; typedef struct _DOMAIN_DISPLAY_USER @@ -387,7 +448,9 @@ typedef struct _DOMAIN_DISPLAY_OEM_GROUP OEM_STRING Group; } DOMAIN_DISPLAY_OEM_GROUP, *PDOMAIN_DISPLAY_OEM_GROUP; +// // SamQueryLocalizableAccountsInDomain types +// typedef enum _DOMAIN_LOCALIZABLE_ACCOUNTS_INFORMATION { @@ -413,18 +476,40 @@ typedef union _DOMAIN_LOCALIZABLE_INFO_BUFFER DOMAIN_LOCALIZABLE_ACCOUNTS_BASIC Basic; } DOMAIN_LOCALIZABLE_ACCOUNTS_INFO_BUFFER, *PDOMAIN_LOCALIZABLE_ACCOUNTS_INFO_BUFFER; +// // Functions +// -_Check_return_ +/** + * The SamLookupDomainInSamServer method obtains the SID of a domain, given the object's name. + * + * \param ServerHandle A handle representing a server. + * \param Name A UTF-16 encoded string. + * \param DomainId A SID value of a domain that corresponds to the Name. + * \return NTSTATUS Successful or errant status. + * \sa https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-samr/47492d59-e095-4398-b03e-8a062b989123 + */ +NTSYSAPI NTSTATUS NTAPI SamLookupDomainInSamServer( _In_ SAM_HANDLE ServerHandle, - _In_ PUNICODE_STRING Name, + _In_ PCUNICODE_STRING Name, _Outptr_ PSID *DomainId ); -_Check_return_ +/** + * The SamEnumerateDomainsInSamServer method obtains a listing of all domains hosted by the server side of this protocol. + * + * \param ServerHandle A handle representing a server. + * \param EnumerationContext An opaque value that the server can use to continue an enumeration on a subsequent call. + * \param Buffer A listing of domain information. + * \param PreferedMaximumLength The requested maximum number of bytes to return in Buffer. + * \param CountReturned The count of domain elements returned in Buffer. + * \return NTSTATUS Successful or errant status. + * \sa https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-samr/2142fd2d-0854-42c1-a9fb-2fe964e381ce + */ +NTSYSAPI NTSTATUS NTAPI SamEnumerateDomainsInSamServer( @@ -435,7 +520,17 @@ SamEnumerateDomainsInSamServer( _Out_ PULONG CountReturned ); -_Check_return_ +/** + * The SamOpenDomain method obtains a handle to a domain, given a SID. + * + * \param ServerHandle A handle representing a server. + * \param DesiredAccess The desired access to the domain. + * \param DomainId A SID value of a domain hosted by the server. + * \param DomainHandle A handle to the requested domain. + * \return NTSTATUS Successful or errant status. + * \sa https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-samr/ba710c90-5b12-42f8-9e5a-d4aacc1329fa + */ +NTSYSAPI NTSTATUS NTAPI SamOpenDomain( @@ -445,7 +540,16 @@ SamOpenDomain( _Out_ PSAM_HANDLE DomainHandle ); -_Check_return_ +/** + * The SamQueryInformationDomain method obtains attributes from a domain object. + * + * \param DomainHandle A handle representing a domain. + * \param DomainInformationClass An enumeration indicating which attributes to return. + * \param Buffer The requested attributes on output. + * \return NTSTATUS Successful or errant status. + * \sa https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-samr/5d6a2817-caa9-41ca-a269-fd13ecbb4fa8 + */ +NTSYSAPI NTSTATUS NTAPI SamQueryInformationDomain( @@ -454,38 +558,68 @@ SamQueryInformationDomain( _Outptr_ PVOID *Buffer ); -_Check_return_ +/** + * The SamSetInformationDomain method updates attributes of a domain object. + * + * \param DomainHandle A handle representing a domain. + * \param DomainInformationClass An enumeration indicating which attributes to update. + * \param Buffer The provided attributes on output. + * \return NTSTATUS Successful or errant status. + */ +NTSYSAPI NTSTATUS NTAPI SamSetInformationDomain( _In_ SAM_HANDLE DomainHandle, _In_ DOMAIN_INFORMATION_CLASS DomainInformationClass, - _In_ PVOID DomainInformation + _In_ PVOID Buffer ); -_Check_return_ +/** + * The SamLookupNamesInDomain method translates a set of account names into a set of RIDs. + * + * \param DomainHandle A handle representing a domain. + * \param Count The number of elements in Names. + * \param Names An array of strings that are to be mapped to RIDs. + * \param RelativeIds An array of RIDs of accounts that correspond to the elements in Names. + * \param Use An array of SID_NAME_USE enumeration values that describe the type of account for each entry in RelativeIds. + * \return NTSTATUS Successful or errant status. + * \sa https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-samr/d91271c6-7b2e-4194-9927-8fabfa429f90 + */ +NTSYSAPI NTSTATUS NTAPI SamLookupNamesInDomain( _In_ SAM_HANDLE DomainHandle, _In_ ULONG Count, - _In_reads_(Count) PUNICODE_STRING Names, + _In_reads_(Count) PCUNICODE_STRING Names, _Out_ _Deref_post_count_(Count) PULONG *RelativeIds, _Out_ _Deref_post_count_(Count) PSID_NAME_USE *Use ); -_Check_return_ +NTSYSAPI NTSTATUS NTAPI SamLookupNamesInDomain2( _In_ SAM_HANDLE DomainHandle, _In_ ULONG Count, - _In_reads_(Count) PUNICODE_STRING Names, + _In_reads_(Count) PCUNICODE_STRING Names, _Out_ _Deref_post_count_(Count) PSID* Sids, _Out_ _Deref_post_count_(Count) PSID_NAME_USE* Use ); -_Check_return_ +/** + * The SamLookupIdsInDomain method translates a set of RIDs into account names. + * + * \param DomainHandle A handle representing a domain. + * \param Count The number of elements in RelativeIds. + * \param RelativeIds An array of RIDs that are to be mapped to account names. + * \param Names An array of account names that correspond to the elements in RelativeIds. + * \param Use An array of SID_NAME_USE enumeration values that describe the type of account for each entry in RelativeIds. + * \return NTSTATUS Successful or errant status. + * \sa https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-samr/c870951c-74b3-4714-9857-224595ffc61a + */ +NTSYSAPI NTSTATUS NTAPI SamLookupIdsInDomain( @@ -496,7 +630,15 @@ SamLookupIdsInDomain( _Out_ _Deref_post_opt_count_(Count) PSID_NAME_USE *Use ); -_Check_return_ +/** + * The SamRemoveMemberFromForeignDomain method removes a member from all aliases. + * + * \param DomainHandle A handle representing a domain. + * \param MemberId The SID to remove from the membership. + * \return NTSTATUS Successful or errant status. + * \sa https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-samr/03afc843-584d-473b-834a-3f5a1ac86cce + */ +NTSYSAPI NTSTATUS NTAPI SamRemoveMemberFromForeignDomain( @@ -504,7 +646,7 @@ SamRemoveMemberFromForeignDomain( _In_ PSID MemberId ); -_Check_return_ +NTSYSAPI NTSTATUS NTAPI SamQueryLocalizableAccountsInDomain( @@ -515,7 +657,9 @@ SamQueryLocalizableAccountsInDomain( _Outptr_ PVOID *Buffer ); +// // Group +// #define GROUP_READ_INFORMATION 0x0001 #define GROUP_WRITE_ACCOUNT 0x0002 @@ -547,15 +691,18 @@ typedef struct _GROUP_MEMBERSHIP 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 + GroupGeneralInformation = 1, // q: GROUP_GENERAL_INFORMATION + GroupNameInformation, // qs: GROUP_NAME_INFORMATION + GroupAttributeInformation, // qs: GROUP_ATTRIBUTE_INFORMATION + GroupAdminCommentInformation, // qs: GROUP_ADM_COMMENT_INFORMATION + GroupReplicationInformation, // q: GROUP_REPLICATION_INFORMATION + GroupMaxInformation } GROUP_INFORMATION_CLASS; typedef struct _GROUP_GENERAL_INFORMATION @@ -581,9 +728,27 @@ typedef struct _GROUP_ADM_COMMENT_INFORMATION UNICODE_STRING AdminComment; } GROUP_ADM_COMMENT_INFORMATION, *PGROUP_ADM_COMMENT_INFORMATION; -// Functions +typedef struct _GROUP_REPLICATION_INFORMATION +{ + LARGE_INTEGER LastWriteTime; +} GROUP_REPLICATION_INFORMATION, *PGROUP_REPLICATION_INFORMATION; -_Check_return_ +// +// Functions +// + +/** + * The SamEnumerateGroupsInDomain method enumerates all groups. + * + * \param DomainHandle A handle representing a domain. + * \param EnumerationContext An opaque value that the server can use to continue an enumeration on a subsequent call. + * \param Buffer A listing of group information. + * \param PreferedMaximumLength The requested maximum number of bytes to return in Buffer. + * \param CountReturned The count of domain elements returned in Buffer. + * \return NTSTATUS Successful or errant status. + * \sa https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-samr/e0b7a4b7-ecfc-405f-9d7d-32b3cd2cd6c8 + */ +NTSYSAPI NTSTATUS NTAPI SamEnumerateGroupsInDomain( @@ -594,18 +759,18 @@ SamEnumerateGroupsInDomain( _Out_ PULONG CountReturned ); -_Check_return_ +NTSYSAPI NTSTATUS NTAPI SamCreateGroupInDomain( _In_ SAM_HANDLE DomainHandle, - _In_ PUNICODE_STRING AccountName, + _In_ PCUNICODE_STRING AccountName, _In_ ACCESS_MASK DesiredAccess, _Out_ PSAM_HANDLE GroupHandle, _Out_ PULONG RelativeId ); -_Check_return_ +NTSYSAPI NTSTATUS NTAPI SamOpenGroup( @@ -615,14 +780,14 @@ SamOpenGroup( _Out_ PSAM_HANDLE GroupHandle ); -_Check_return_ +NTSYSAPI NTSTATUS NTAPI SamDeleteGroup( _In_ SAM_HANDLE GroupHandle ); -_Check_return_ +NTSYSAPI NTSTATUS NTAPI SamQueryInformationGroup( @@ -631,7 +796,7 @@ SamQueryInformationGroup( _Outptr_ PVOID *Buffer ); -_Check_return_ +NTSYSAPI NTSTATUS NTAPI SamSetInformationGroup( @@ -640,7 +805,7 @@ SamSetInformationGroup( _In_ PVOID Buffer ); -_Check_return_ +NTSYSAPI NTSTATUS NTAPI SamAddMemberToGroup( @@ -649,7 +814,7 @@ SamAddMemberToGroup( _In_ ULONG Attributes ); -_Check_return_ +NTSYSAPI NTSTATUS NTAPI SamRemoveMemberFromGroup( @@ -657,7 +822,7 @@ SamRemoveMemberFromGroup( _In_ ULONG MemberId ); -_Check_return_ +NTSYSAPI NTSTATUS NTAPI SamGetMembersInGroup( @@ -667,7 +832,7 @@ SamGetMembersInGroup( _Out_ PULONG MemberCount ); -_Check_return_ +NTSYSAPI NTSTATUS NTAPI SamSetMemberAttributesOfGroup( @@ -676,7 +841,9 @@ SamSetMemberAttributesOfGroup( _In_ ULONG Attributes ); +// // Alias +// #define ALIAS_ADD_MEMBER 0x0001 #define ALIAS_REMOVE_MEMBER 0x0002 @@ -702,15 +869,18 @@ SamSetMemberAttributesOfGroup( #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, + AliasGeneralInformation = 1, // q: ALIAS_GENERAL_INFORMATION + AliasNameInformation, // qs: ALIAS_NAME_INFORMATION + AliasAdminCommentInformation, // qs: ALIAS_ADM_COMMENT_INFORMATION + AliasReplicationInformation, // q: ALIAS_REPLICATION_INFORMATION + AliasExtendedInformation, // q: ALIAS_EXTENDED_INFORMATION + AliasMaxInformation } ALIAS_INFORMATION_CLASS; typedef struct _ALIAS_GENERAL_INFORMATION @@ -730,6 +900,11 @@ typedef struct _ALIAS_ADM_COMMENT_INFORMATION UNICODE_STRING AdminComment; } ALIAS_ADM_COMMENT_INFORMATION, *PALIAS_ADM_COMMENT_INFORMATION; +typedef struct _ALIAS_REPLICATION_INFORMATION +{ + LARGE_INTEGER LastWriteTime; +} ALIAS_REPLICATION_INFORMATION, *PALIAS_REPLICATION_INFORMATION; + #define ALIAS_ALL_NAME (0x00000001L) #define ALIAS_ALL_MEMBER_COUNT (0x00000002L) #define ALIAS_ALL_ADMIN_COMMENT (0x00000004L) @@ -741,9 +916,11 @@ typedef struct _ALIAS_EXTENDED_INFORMATION SAM_SHELL_OBJECT_PROPERTIES ShellAdminObjectProperties; } ALIAS_EXTENDED_INFORMATION, *PALIAS_EXTENDED_INFORMATION; +// // Functions +// -_Check_return_ +NTSYSAPI NTSTATUS NTAPI SamEnumerateAliasesInDomain( @@ -754,18 +931,18 @@ SamEnumerateAliasesInDomain( _Out_ PULONG CountReturned ); -_Check_return_ +NTSYSAPI NTSTATUS NTAPI SamCreateAliasInDomain( _In_ SAM_HANDLE DomainHandle, - _In_ PUNICODE_STRING AccountName, + _In_ PCUNICODE_STRING AccountName, _In_ ACCESS_MASK DesiredAccess, _Out_ PSAM_HANDLE AliasHandle, _Out_ PULONG RelativeId ); -_Check_return_ +NTSYSAPI NTSTATUS NTAPI SamOpenAlias( @@ -775,14 +952,14 @@ SamOpenAlias( _Out_ PSAM_HANDLE AliasHandle ); -_Check_return_ +NTSYSAPI NTSTATUS NTAPI SamDeleteAlias( _In_ SAM_HANDLE AliasHandle ); -_Check_return_ +NTSYSAPI NTSTATUS NTAPI SamQueryInformationAlias( @@ -791,7 +968,7 @@ SamQueryInformationAlias( _Outptr_ PVOID *Buffer ); -_Check_return_ +NTSYSAPI NTSTATUS NTAPI SamSetInformationAlias( @@ -800,7 +977,7 @@ SamSetInformationAlias( _In_ PVOID Buffer ); -_Check_return_ +NTSYSAPI NTSTATUS NTAPI SamAddMemberToAlias( @@ -808,7 +985,7 @@ SamAddMemberToAlias( _In_ PSID MemberId ); -_Check_return_ +NTSYSAPI NTSTATUS NTAPI SamAddMultipleMembersToAlias( @@ -817,7 +994,7 @@ SamAddMultipleMembersToAlias( _In_ ULONG MemberCount ); -_Check_return_ +NTSYSAPI NTSTATUS NTAPI SamRemoveMemberFromAlias( @@ -825,7 +1002,7 @@ SamRemoveMemberFromAlias( _In_ PSID MemberId ); -_Check_return_ +NTSYSAPI NTSTATUS NTAPI SamRemoveMultipleMembersFromAlias( @@ -834,7 +1011,7 @@ SamRemoveMultipleMembersFromAlias( _In_ ULONG MemberCount ); -_Check_return_ +NTSYSAPI NTSTATUS NTAPI SamGetMembersInAlias( @@ -843,7 +1020,7 @@ SamGetMembersInAlias( _Out_ PULONG MemberCount ); -_Check_return_ +NTSYSAPI NTSTATUS NTAPI SamGetAliasMembership( @@ -853,8 +1030,9 @@ SamGetAliasMembership( _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 @@ -868,7 +1046,9 @@ SamGetAliasMembership( GROUP_TYPE_APP_BASIC_GROUP | \ GROUP_TYPE_APP_QUERY_GROUP) +// // User +// #define USER_READ_GENERAL 0x0001 #define USER_READ_PREFERENCES 0x0002 @@ -910,7 +1090,9 @@ SamGetAliasMembership( USER_READ_GENERAL | \ USER_CHANGE_PASSWORD) +// // User account control flags +// #define USER_ACCOUNT_DISABLED (0x00000001) #define USER_HOME_DIRECTORY_REQUIRED (0x00000002) @@ -979,48 +1161,56 @@ typedef struct _LOGON_HOURS PUCHAR LogonHours; } LOGON_HOURS, *PLOGON_HOURS; +/** + * The SR_SECURITY_DESCRIPTOR structure contains information about the security privileges of the user. + * + * \sa https://learn.microsoft.com/en-us/windows/win32/api/subauth/ns-subauth-sr_security_descriptor + */ typedef struct _SR_SECURITY_DESCRIPTOR { - ULONG Length; - PUCHAR SecurityDescriptor; + ULONG Length; // Indicates the size in bytes of the structure. + PUCHAR SecurityDescriptor; // Indicates the user's security privileges. } 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 + UserGeneralInformation = 1, // q: USER_GENERAL_INFORMATION + UserPreferencesInformation, // qs: USER_PREFERENCES_INFORMATION + UserLogonInformation, // q: USER_LOGON_INFORMATION + UserLogonHoursInformation, // qs: USER_LOGON_HOURS_INFORMATION + UserAccountInformation, // q: USER_ACCOUNT_INFORMATION + UserNameInformation, // qs: USER_NAME_INFORMATION + UserAccountNameInformation, // qs: USER_ACCOUNT_NAME_INFORMATION + UserFullNameInformation, // qs: USER_FULL_NAME_INFORMATION + UserPrimaryGroupInformation, // qs: USER_PRIMARY_GROUP_INFORMATION + UserHomeInformation, // qs: USER_HOME_INFORMATION // 10 + UserScriptInformation, // qs: USER_SCRIPT_INFORMATION + UserProfileInformation, // qs: USER_PROFILE_INFORMATION + UserAdminCommentInformation, // qs: USER_ADMIN_COMMENT_INFORMATION + UserWorkStationsInformation, // qs: USER_WORKSTATIONS_INFORMATION + UserSetPasswordInformation, // s: USER_SET_PASSWORD_INFORMATION + UserControlInformation, // qs: USER_CONTROL_INFORMATION + UserExpiresInformation, // qs: USER_EXPIRES_INFORMATION + UserInternal1Information, // qs: USER_INTERNAL1_INFORMATION + UserInternal2Information, // qs: USER_INTERNAL2_INFORMATION + UserParametersInformation, // qs: USER_PARAMETERS_INFORMATION // 20 + UserAllInformation, // qs: USER_ALL_INFORMATION + UserInternal3Information, // qs: USER_INTERNAL3_INFORMATION + UserInternal4Information, // qs: USER_INTERNAL4_INFORMATION + UserInternal5Information, // qs: USER_INTERNAL5_INFORMATION + UserInternal4InformationNew, // qs: USER_INTERNAL4_INFORMATION_NEW + UserInternal5InformationNew, // qs: USER_INTERNAL5_INFORMATION_NEW + UserInternal6Information, // qs: USER_INTERNAL6_INFORMATION + UserExtendedInformation, // qs: USER_EXTENDED_INFORMATION + UserLogonUIInformation, // q: USER_LOGON_UI_INFORMATION // since VISTA + UserAuthInformation, // qs: USER_AUTH_INFORMATION // since WIN10 // 30 + UserInternal7Information, // qs: USER_INTERNAL7_INFORMATION // since 20H1 + UserInternal8Information, // qs: USER_INTERNAL8_INFORMATION + UserMaxInformation } USER_INFORMATION_CLASS, *PUSER_INFORMATION_CLASS; typedef struct _USER_GENERAL_INFORMATION @@ -1040,7 +1230,6 @@ typedef struct _USER_PREFERENCES_INFORMATION USHORT CodePage; } USER_PREFERENCES_INFORMATION, *PUSER_PREFERENCES_INFORMATION; -#include typedef struct _USER_LOGON_INFORMATION { UNICODE_STRING UserName; @@ -1062,14 +1251,12 @@ typedef struct _USER_LOGON_INFORMATION USHORT LogonCount; ULONG UserAccountControl; } USER_LOGON_INFORMATION, *PUSER_LOGON_INFORMATION; -#include typedef struct _USER_LOGON_HOURS_INFORMATION { LOGON_HOURS LogonHours; } USER_LOGON_HOURS_INFORMATION, *PUSER_LOGON_HOURS_INFORMATION; -#include typedef struct _USER_ACCOUNT_INFORMATION { UNICODE_STRING UserName; @@ -1091,7 +1278,6 @@ typedef struct _USER_ACCOUNT_INFORMATION LARGE_INTEGER AccountExpires; ULONG UserAccountControl; } USER_ACCOUNT_INFORMATION, *PUSER_ACCOUNT_INFORMATION; -#include typedef struct _USER_NAME_INFORMATION { @@ -1196,7 +1382,9 @@ 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 @@ -1336,7 +1524,6 @@ typedef struct _USER_PARAMETERS_INFORMATION USER_ALL_PASSWORDMUSTCHANGE | \ USER_ALL_UNDEFINED_MASK) -#include typedef struct _USER_ALL_INFORMATION { LARGE_INTEGER LastLogon; @@ -1373,15 +1560,12 @@ typedef struct _USER_ALL_INFORMATION BOOLEAN PasswordExpired; BOOLEAN PrivateDataSensitive; } USER_ALL_INFORMATION, *PUSER_ALL_INFORMATION; -#include -#include typedef struct _USER_INTERNAL3_INFORMATION { USER_ALL_INFORMATION I1; LARGE_INTEGER LastBadPasswordTime; } USER_INTERNAL3_INFORMATION, *PUSER_INTERNAL3_INFORMATION; -#include typedef struct _ENCRYPTED_USER_PASSWORD { @@ -1462,6 +1646,11 @@ typedef struct _USER_LOGON_UI_INFORMATION BOOLEAN AccountIsDisabled; } USER_LOGON_UI_INFORMATION, *PUSER_LOGON_UI_INFORMATION; +typedef struct _USER_AUTH_INFORMATION +{ + SAM_BYTE_ARRAY_32K AuthData; +} USER_AUTH_INFORMATION, *PUSER_AUTH_INFORMATION; + typedef struct _ENCRYPTED_PASSWORD_AES { UCHAR AuthData[64]; @@ -1500,7 +1689,9 @@ typedef struct _USER_PWD_CHANGE_FAILURE_INFORMATION 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 @@ -1513,9 +1704,11 @@ typedef struct _USER_PWD_CHANGE_FAILURE_INFORMATION #define SAM_PWD_CHANGE_PASSWORD_TOO_LONG 8 #define SAM_PWD_CHANGE_FAILURE_REASON_MAX 8 +// // Functions +// -_Check_return_ +NTSYSAPI NTSTATUS NTAPI SamEnumerateUsersInDomain( @@ -1527,23 +1720,37 @@ SamEnumerateUsersInDomain( _Out_ PULONG CountReturned ); -_Check_return_ +// rev +NTSYSAPI +NTSTATUS +NTAPI +SamEnumerateUsersInDomain2( + _In_ SAM_HANDLE DomainHandle, + _Inout_ PSAM_ENUMERATE_HANDLE EnumerationContext, + _In_ ULONG UserAccountControl, + _In_ ULONG Flags, + _Outptr_ PVOID *Buffer, // PSAM_RID_ENUMERATION * + _In_ ULONG PreferedMaximumLength, + _Out_ PULONG CountReturned + ); + +NTSYSAPI NTSTATUS NTAPI SamCreateUserInDomain( _In_ SAM_HANDLE DomainHandle, - _In_ PUNICODE_STRING AccountName, + _In_ PCUNICODE_STRING AccountName, _In_ ACCESS_MASK DesiredAccess, _Out_ PSAM_HANDLE UserHandle, _Out_ PULONG RelativeId ); -_Check_return_ +NTSYSAPI NTSTATUS NTAPI SamCreateUser2InDomain( _In_ SAM_HANDLE DomainHandle, - _In_ PUNICODE_STRING AccountName, + _In_ PCUNICODE_STRING AccountName, _In_ ULONG AccountType, _In_ ACCESS_MASK DesiredAccess, _Out_ PSAM_HANDLE UserHandle, @@ -1551,7 +1758,7 @@ SamCreateUser2InDomain( _Out_ PULONG RelativeId ); -_Check_return_ +NTSYSAPI NTSTATUS NTAPI SamOpenUser( @@ -1561,14 +1768,14 @@ SamOpenUser( _Out_ PSAM_HANDLE UserHandle ); -_Check_return_ +NTSYSAPI NTSTATUS NTAPI SamDeleteUser( _In_ SAM_HANDLE UserHandle ); -_Check_return_ +NTSYSAPI NTSTATUS NTAPI SamQueryInformationUser( @@ -1577,7 +1784,7 @@ SamQueryInformationUser( _Outptr_ PVOID *Buffer ); -_Check_return_ +NTSYSAPI NTSTATUS NTAPI SamSetInformationUser( @@ -1586,7 +1793,7 @@ SamSetInformationUser( _In_ PVOID Buffer ); -_Check_return_ +NTSYSAPI NTSTATUS NTAPI SamGetGroupsForUser( @@ -1595,38 +1802,38 @@ SamGetGroupsForUser( _Out_ PULONG MembershipCount ); -_Check_return_ +NTSYSAPI NTSTATUS NTAPI SamChangePasswordUser( _In_ SAM_HANDLE UserHandle, - _In_ PUNICODE_STRING OldPassword, - _In_ PUNICODE_STRING NewPassword + _In_ PCUNICODE_STRING OldPassword, + _In_ PCUNICODE_STRING NewPassword ); -_Check_return_ +NTSYSAPI NTSTATUS NTAPI SamChangePasswordUser2( - _In_ PUNICODE_STRING ServerName, - _In_ PUNICODE_STRING UserName, - _In_ PUNICODE_STRING OldPassword, - _In_ PUNICODE_STRING NewPassword + _In_ PCUNICODE_STRING ServerName, + _In_ PCUNICODE_STRING UserName, + _In_ PCUNICODE_STRING OldPassword, + _In_ PCUNICODE_STRING NewPassword ); -_Check_return_ +NTSYSAPI NTSTATUS NTAPI SamChangePasswordUser3( - _In_ PUNICODE_STRING ServerName, - _In_ PUNICODE_STRING UserName, - _In_ PUNICODE_STRING OldPassword, - _In_ PUNICODE_STRING NewPassword, + _In_ PCUNICODE_STRING ServerName, + _In_ PCUNICODE_STRING UserName, + _In_ PCUNICODE_STRING OldPassword, + _In_ PCUNICODE_STRING NewPassword, _Outptr_ PDOMAIN_PASSWORD_INFORMATION *EffectivePasswordPolicy, _Outptr_ PUSER_PWD_CHANGE_FAILURE_INFORMATION *PasswordChangeFailureInfo ); -_Check_return_ +NTSYSAPI NTSTATUS NTAPI SamQueryDisplayInformation( @@ -1641,17 +1848,29 @@ SamQueryDisplayInformation( _Outptr_ PVOID *SortedBuffer ); -_Check_return_ +/** + * The SamGetDisplayEnumerationIndex method obtains an index into an ascending account-name–sorted list of accounts. + * + * \param DomainHandle A handle representing a domain. + * \param DisplayInformation An enumeration indicating which set of objects to return an index. + * \param Prefix A string matched against the account name to find a starting point for an enumeration. + * \param Index A value to use as input to SamQueryDisplayInformation in order to control the accounts that are returned from that method. + * \return NTSTATUS Successful or errant status. + * \sa https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-samr/bd429624-f2d5-4717-8aa2-659952c3e209 + */ +NTSYSAPI NTSTATUS NTAPI SamGetDisplayEnumerationIndex( _In_ SAM_HANDLE DomainHandle, _In_ DOMAIN_DISPLAY_INFORMATION DisplayInformation, - _In_ PUNICODE_STRING Prefix, + _In_ PCUNICODE_STRING Prefix, _Out_ PULONG Index ); +// // Database replication +// typedef enum _SECURITY_DB_DELTA_TYPE { @@ -1705,19 +1924,21 @@ typedef union _SAM_DELTA_DATA ULONG AccountControl; } SAM_DELTA_DATA, *PSAM_DELTA_DATA; -typedef NTSTATUS (NTAPI *PSAM_DELTA_NOTIFICATION_ROUTINE)( +typedef _Function_class_(SAM_DELTA_NOTIFICATION_ROUTINE) +NTSTATUS NTAPI SAM_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_opt_ PCUNICODE_STRING ObjectName, _In_ PLARGE_INTEGER ModifiedCount, _In_opt_ PSAM_DELTA_DATA DeltaData ); +typedef SAM_DELTA_NOTIFICATION_ROUTINE* PSAM_DELTA_NOTIFICATION_ROUTINE; #define SAM_DELTA_NOTIFY_ROUTINE "DeltaNotify" -_Check_return_ +NTSYSAPI NTSTATUS NTAPI SamRegisterObjectChangeNotification( @@ -1725,6 +1946,7 @@ SamRegisterObjectChangeNotification( _In_ HANDLE NotificationEventHandle ); +NTSYSAPI NTSTATUS NTAPI SamUnregisterObjectChangeNotification( @@ -1732,13 +1954,15 @@ SamUnregisterObjectChangeNotification( _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_ +NTSYSAPI NTSTATUS NTAPI SamGetCompatibilityMode( @@ -1746,7 +1970,9 @@ SamGetCompatibilityMode( _Out_ ULONG *Mode ); +// // Password validation +// typedef enum _PASSWORD_POLICY_VALIDATION_TYPE { @@ -1841,17 +2067,19 @@ typedef union _SAM_VALIDATE_OUTPUT_ARG SAM_VALIDATE_STANDARD_OUTPUT_ARG ValidatePasswordResetOutput; } SAM_VALIDATE_OUTPUT_ARG, *PSAM_VALIDATE_OUTPUT_ARG; -_Check_return_ +NTSYSAPI NTSTATUS NTAPI SamValidatePassword( - _In_opt_ PUNICODE_STRING ServerName, + _In_opt_ PCUNICODE_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 { @@ -1881,14 +2109,14 @@ typedef union _SAM_GENERIC_OPERATION_OUTPUT SAM_OPERATION_OBJCHG_OUTPUT ObjChangeOut; } SAM_GENERIC_OPERATION_OUTPUT, *PSAM_GENERIC_OPERATION_OUTPUT; -_Check_return_ +NTSYSAPI NTSTATUS NTAPI SamPerformGenericOperation( - _In_opt_ PWSTR ServerName, + _In_opt_ PCWSTR ServerName, _In_ SAM_GENERIC_OPERATION_TYPE OperationType, _In_ PSAM_GENERIC_OPERATION_INPUT OperationIn, _Out_ PSAM_GENERIC_OPERATION_OUTPUT *OperationOut ); -#endif +#endif // _NTSAM_H diff --git a/ntseapi.h b/ntseapi.h index f56df2c..e017316 100644 --- a/ntseapi.h +++ b/ntseapi.h @@ -19,7 +19,7 @@ #define SE_MACHINE_ACCOUNT_PRIVILEGE (6L) // Required to create a computer account. #define SE_TCB_PRIVILEGE (7L) // Required to act as part of the Trusted Computer Base. #define SE_SECURITY_PRIVILEGE (8L) // Required to perform a number of security-related functions, such as controlling and viewing audit messages. // Security operator. -#define SE_TAKE_OWNERSHIP_PRIVILEGE (9L) // Required to take ownership of an object without being granted discretionary access. +#define SE_TAKE_OWNERSHIP_PRIVILEGE (9L) // Required to take ownership of an object without being granted discretionary access. #define SE_LOAD_DRIVER_PRIVILEGE (10L) // Required to load or unload a device driver. #define SE_SYSTEM_PROFILE_PRIVILEGE (11L) // Required to gather profiling information for the entire system. #define SE_SYSTEMTIME_PRIVILEGE (12L) // Required to modify the system time. @@ -36,7 +36,7 @@ #define SE_CHANGE_NOTIFY_PRIVILEGE (23L) // Required to receive notifications of changes to files or directories and skip all traversal access checks. It is enabled by default for all users. #define SE_REMOTE_SHUTDOWN_PRIVILEGE (24L) // Required to shut down a system using a network request. #define SE_UNDOCK_PRIVILEGE (25L) // Required to undock a laptop. -#define SE_SYNC_AGENT_PRIVILEGE (26L) // Required for a domain controller to use the Lightweight Directory Access Protocol (LDAP) directory synchronization services. +#define SE_SYNC_AGENT_PRIVILEGE (26L) // Required for a domain controller to use the Lightweight Directory Access Protocol (LDAP) directory synchronization services. #define SE_ENABLE_DELEGATION_PRIVILEGE (27L) // Required to mark user and computer accounts as trusted for delegation. #define SE_MANAGE_VOLUME_PRIVILEGE (28L) // Required to enable volume management privileges. #define SE_IMPERSONATE_PRIVILEGE (29L) // Required to impersonate a client after authentication. @@ -56,112 +56,261 @@ // begin_rev #if (PHNT_MODE == PHNT_MODE_KERNEL) +/** + * The TOKEN_INFORMATION_CLASS enumeration contains values that specify the type of information + * being assigned to or retrieved from an access token. + * + * \sa https://learn.microsoft.com/en-us/windows/win32/api/winnt/ne-winnt-token_information_class + */ 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 + TokenUser = 1, // q: TOKEN_USER, SE_TOKEN_USER + TokenGroups, // q: TOKEN_GROUPS + TokenPrivileges, // q: TOKEN_PRIVILEGES + TokenOwner, // qs: TOKEN_OWNER + TokenPrimaryGroup, // qs: TOKEN_PRIMARY_GROUP + TokenDefaultDacl, // qs: 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, // qs: ULONG (requires SeTcbPrivilege) + TokenGroupsAndPrivileges, // q: TOKEN_GROUPS_AND_PRIVILEGES + TokenSessionReference, // s: ULONG (requires SeTcbPrivilege) + TokenSandBoxInert, // q: ULONG + TokenAuditPolicy, // qs: TOKEN_AUDIT_POLICY (requires SeSecurityPrivilege/SeTcbPrivilege) + TokenOrigin, // qs: TOKEN_ORIGIN (requires SeTcbPrivilege) + TokenElevationType, // q: TOKEN_ELEVATION_TYPE + TokenLinkedToken, // qs: TOKEN_LINKED_TOKEN (requires SeCreateTokenPrivilege) + TokenElevation, // q: TOKEN_ELEVATION // 20 + TokenHasRestrictions, // q: ULONG + TokenAccessInformation, // q: TOKEN_ACCESS_INFORMATION + TokenVirtualizationAllowed, // qs: ULONG (requires SeCreateTokenPrivilege) + TokenVirtualizationEnabled, // qs: ULONG + TokenIntegrityLevel, // qs: TOKEN_MANDATORY_LABEL + TokenUIAccess, // qs: ULONG (requires SeTcbPrivilege) + TokenMandatoryPolicy, // qs: 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 - TokenLoggingInformation, // TOKEN_LOGGING_INFORMATION // since 24H2 + TokenDeviceGroups, // q: TOKEN_GROUPS + TokenRestrictedDeviceGroups, // q: TOKEN_GROUPS + TokenSecurityAttributes, // qs: TOKEN_SECURITY_ATTRIBUTES_[AND_OPERATION_]INFORMATION (requires SeTcbPrivilege) + TokenIsRestricted, // q: ULONG // 40 + TokenProcessTrustLevel, // q: TOKEN_PROCESS_TRUST_LEVEL // since WINBLUE + TokenPrivateNameSpace, // qs: 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 + TokenLoggingInformation, // q: TOKEN_LOGGING_INFORMATION // since 24H2 + TokenLearningMode, // q: // since 25H2 MaxTokenInfoClass } TOKEN_INFORMATION_CLASS, *PTOKEN_INFORMATION_CLASS; -#else -#define TOKEN_INFORMATION_CLASS ULONG -//#define TokenUser 1 // q: TOKEN_USER, SE_TOKEN_USER -//#define TokenGroups 2 // q: TOKEN_GROUPS -//#define TokenPrivileges 3 // q: TOKEN_PRIVILEGES -//#define TokenOwner 4 // q; s: TOKEN_OWNER -#define TokenPrimaryGroup 5 // q; s: TOKEN_PRIMARY_GROUP -#define TokenDefaultDacl 6 // q; s: TOKEN_DEFAULT_DACL -#define TokenSource 7 // q: TOKEN_SOURCE -//#define TokenType 8 // q: TOKEN_TYPE -#define TokenImpersonationLevel 9 // q: SECURITY_IMPERSONATION_LEVEL -#define TokenStatistics 10 // q: TOKEN_STATISTICS // 10 -#define TokenRestrictedSids 11 // q: TOKEN_GROUPS -#define TokenSessionId 12 // q; s: ULONG (requires SeTcbPrivilege) -#define TokenGroupsAndPrivileges 13 // q: TOKEN_GROUPS_AND_PRIVILEGES -#define TokenSessionReference 14 // s: ULONG (requires SeTcbPrivilege) -#define TokenSandBoxInert 15 // q: ULONG -#define TokenAuditPolicy 16 // q; s: TOKEN_AUDIT_POLICY (requires SeSecurityPrivilege/SeTcbPrivilege) -#define TokenOrigin 17 // q; s: TOKEN_ORIGIN (requires SeTcbPrivilege) -//#define TokenElevationType 18 // q: TOKEN_ELEVATION_TYPE -#define TokenLinkedToken 19 // q; s: TOKEN_LINKED_TOKEN (requires SeCreateTokenPrivilege) -//#define TokenElevation 20 // q: TOKEN_ELEVATION // 20 -#define TokenHasRestrictions 21 // q: ULONG -#define TokenAccessInformation 22 // q: TOKEN_ACCESS_INFORMATION -#define TokenVirtualizationAllowed 23 // q; s: ULONG (requires SeCreateTokenPrivilege) -#define TokenVirtualizationEnabled 24 // q; s: ULONG -#define TokenIntegrityLevel 25 // q; s: TOKEN_MANDATORY_LABEL -#define TokenUIAccess 26 // q; s: ULONG (requires SeTcbPrivilege) -#define TokenMandatoryPolicy 27 // q; s: TOKEN_MANDATORY_POLICY (requires SeTcbPrivilege) -#define TokenLogonSid 28 // q: TOKEN_GROUPS -#define TokenIsAppContainer 29 // q: ULONG // since WIN8 -#define TokenCapabilities 30 // q: TOKEN_GROUPS // 30 -//#define TokenAppContainerSid 31 // q: TOKEN_APPCONTAINER_INFORMATION -#define TokenAppContainerNumber 32 // q: ULONG -#define TokenUserClaimAttributes 33 // q: CLAIM_SECURITY_ATTRIBUTES_INFORMATION -#define TokenDeviceClaimAttributes 34 // q: CLAIM_SECURITY_ATTRIBUTES_INFORMATION -#define TokenRestrictedUserClaimAttributes 35 // q: CLAIM_SECURITY_ATTRIBUTES_INFORMATION -#define TokenRestrictedDeviceClaimAttributes 36 // q: CLAIM_SECURITY_ATTRIBUTES_INFORMATION -#define TokenDeviceGroups 37 // q: TOKEN_GROUPS -#define TokenRestrictedDeviceGroups 38 // q: TOKEN_GROUPS -#define TokenSecurityAttributes 39 // q; s: TOKEN_SECURITY_ATTRIBUTES_[AND_OPERATION_]INFORMATION (requires SeTcbPrivilege) -#define TokenIsRestricted 40 // q: ULONG // 40 -#define TokenProcessTrustLevel 41 // q: TOKEN_PROCESS_TRUST_LEVEL // since WINBLUE -#define TokenPrivateNameSpace 42// q; s: ULONG (requires SeTcbPrivilege) // since THRESHOLD -#define TokenSingletonAttributes 43 // q: TOKEN_SECURITY_ATTRIBUTES_INFORMATION // since REDSTONE -#define TokenBnoIsolation 44 // q: TOKEN_BNO_ISOLATION_INFORMATION // since REDSTONE2 -#define TokenChildProcessFlags 45 // s: ULONG (requires SeTcbPrivilege) // since REDSTONE3 -#define TokenIsLessPrivilegedAppContainer 46 // q: ULONG // since REDSTONE5 -#define TokenIsSandboxed 47 // q: ULONG // since 19H1 -#define TokenIsAppSilo 48 // q: ULONG // since 22H2 // previously TokenOriginatingProcessTrustLevel // q: TOKEN_PROCESS_TRUST_LEVEL -#define TokenLoggingInformation 49 // TOKEN_LOGGING_INFORMATION // since 24H2 -#define MaxTokenInfoClass 50 -#endif + +// +// Token information structures +// + +/** + * The TOKEN_USER structure identifies the user associated with an access token. + * \sa https://learn.microsoft.com/en-us/windows/win32/api/winnt/ns-winnt-token_user + */ +typedef struct _TOKEN_USER +{ + SID_AND_ATTRIBUTES User; +} TOKEN_USER, *PTOKEN_USER; + +typedef struct _SE_TOKEN_USER +{ + union + { + TOKEN_USER TokenUser; + SID_AND_ATTRIBUTES User; + } DUMMYUNIONNAME; + union + { + SID Sid; + BYTE Buffer[SECURITY_MAX_SID_SIZE]; + } DUMMYUNIONNAME2; +} SE_TOKEN_USER, PSE_TOKEN_USER; + +#define TOKEN_USER_MAX_SIZE (sizeof(TOKEN_USER) + SECURITY_MAX_SID_SIZE) + +/** + * The TOKEN_GROUPS structure contains information about the group security identifiers (SIDs) in an access token. + * \sa https://learn.microsoft.com/en-us/windows/win32/api/winnt/ns-winnt-token_groups + */ +typedef struct _TOKEN_GROUPS +{ + ULONG GroupCount; + SID_AND_ATTRIBUTES Groups[ANYSIZE_ARRAY]; +} TOKEN_GROUPS, *PTOKEN_GROUPS; + +/** + * The TOKEN_PRIVILEGES structure contains information about a set of privileges for an access token. + * \sa https://learn.microsoft.com/en-us/windows/win32/api/winnt/ns-winnt-token_privileges + */ +typedef struct _TOKEN_PRIVILEGES +{ + ULONG PrivilegeCount; + LUID_AND_ATTRIBUTES Privileges[ANYSIZE_ARRAY]; +} TOKEN_PRIVILEGES, *PTOKEN_PRIVILEGES; + +/** + * The TOKEN_OWNER structure contains the default owner security identifier (SID) that will be applied to newly created objects. + * \sa https://learn.microsoft.com/en-us/windows/win32/api/winnt/ns-winnt-token_owner + */ +typedef struct _TOKEN_OWNER +{ + PSID Owner; +} TOKEN_OWNER, *PTOKEN_OWNER; + +#define TOKEN_OWNER_MAX_SIZE (sizeof(TOKEN_OWNER) + SECURITY_MAX_SID_SIZE) + +/** + * The TOKEN_PRIMARY_GROUP structure specifies a group security identifier (SID) for an access token. + * \sa https://learn.microsoft.com/en-us/windows/win32/api/winnt/ns-winnt-token_primary_group + */ +typedef struct _TOKEN_PRIMARY_GROUP +{ + PSID PrimaryGroup; +} TOKEN_PRIMARY_GROUP, *PTOKEN_PRIMARY_GROUP; + +/** + * The TOKEN_DEFAULT_DACL structure specifies a discretionary access control list (DACL). + * \sa https://learn.microsoft.com/en-us/windows/win32/api/winnt/ns-winnt-token_default_dacl + */ +typedef struct _TOKEN_DEFAULT_DACL +{ + PACL DefaultDacl; +} TOKEN_DEFAULT_DACL, *PTOKEN_DEFAULT_DACL; + +#define TOKEN_SOURCE_LENGTH 8 + +/** + * The TOKEN_SOURCE structure identifies the source of an access token. + * \sa https://learn.microsoft.com/en-us/windows/win32/api/winnt/ns-winnt-token_source + */ +typedef struct _TOKEN_SOURCE +{ + CHAR SourceName[TOKEN_SOURCE_LENGTH]; + LUID SourceIdentifier; +} TOKEN_SOURCE, *PTOKEN_SOURCE; + +/** + * The TOKEN_TYPE enumeration contains values that differentiate between a primary token and an impersonation token. + * \sa https://learn.microsoft.com/en-us/windows/win32/api/winnt/ne-winnt-token_type + */ +typedef enum _TOKEN_TYPE +{ + TokenPrimary = 1, + TokenImpersonation +} TOKEN_TYPE; + +typedef struct _TOKEN_USER_CLAIMS +{ + PCLAIMS_BLOB UserClaims; +} TOKEN_USER_CLAIMS, *PTOKEN_USER_CLAIMS; + +typedef struct _TOKEN_DEVICE_CLAIMS +{ + PCLAIMS_BLOB DeviceClaims; +} TOKEN_DEVICE_CLAIMS, *PTOKEN_DEVICE_CLAIMS; + +typedef struct _TOKEN_GROUPS_AND_PRIVILEGES +{ + ULONG SidCount; + ULONG SidLength; + PSID_AND_ATTRIBUTES Sids; + ULONG RestrictedSidCount; + ULONG RestrictedSidLength; + PSID_AND_ATTRIBUTES RestrictedSids; + ULONG PrivilegeCount; + ULONG PrivilegeLength; + PLUID_AND_ATTRIBUTES Privileges; + LUID AuthenticationId; +} TOKEN_GROUPS_AND_PRIVILEGES, *PTOKEN_GROUPS_AND_PRIVILEGES; + +typedef struct _TOKEN_LINKED_TOKEN +{ + HANDLE LinkedToken; +} TOKEN_LINKED_TOKEN, *PTOKEN_LINKED_TOKEN; + +typedef struct _TOKEN_ELEVATION +{ + ULONG TokenIsElevated; +} TOKEN_ELEVATION, *PTOKEN_ELEVATION; + +/** + * The TOKEN_MANDATORY_POLICY structure specifies the mandatory integrity policy for a token. + * \sa https://learn.microsoft.com/en-us/windows/win32/api/winnt/ns-winnt-token_mandatory_policy + */ +typedef struct _TOKEN_MANDATORY_LABEL +{ + SID_AND_ATTRIBUTES Label; +} TOKEN_MANDATORY_LABEL, *PTOKEN_MANDATORY_LABEL; + +#define TOKEN_MANDATORY_POLICY_OFF 0x0 +#define TOKEN_MANDATORY_POLICY_NO_WRITE_UP 0x1 +#define TOKEN_MANDATORY_POLICY_NEW_PROCESS_MIN 0x2 +#define TOKEN_MANDATORY_POLICY_VALID_MASK (TOKEN_MANDATORY_POLICY_NO_WRITE_UP | \ + TOKEN_MANDATORY_POLICY_NEW_PROCESS_MIN) + +#define TOKEN_INTEGRITY_LEVEL_MAX_SIZE \ + ((((ULONG)(sizeof(TOKEN_MANDATORY_LABEL)) + sizeof(PVOID) - 1) & ~(sizeof(PVOID)-1)) + SECURITY_MAX_SID_SIZE) + +typedef struct _TOKEN_MANDATORY_POLICY +{ + ULONG Policy; +} TOKEN_MANDATORY_POLICY, *PTOKEN_MANDATORY_POLICY; + +typedef PVOID PSECURITY_ATTRIBUTES_OPAQUE; + +typedef struct _TOKEN_ACCESS_INFORMATION +{ + PSID_AND_ATTRIBUTES_HASH SidHash; + PSID_AND_ATTRIBUTES_HASH RestrictedSidHash; + PTOKEN_PRIVILEGES Privileges; + LUID AuthenticationId; + TOKEN_TYPE TokenType; + SECURITY_IMPERSONATION_LEVEL ImpersonationLevel; + TOKEN_MANDATORY_POLICY MandatoryPolicy; + ULONG Flags; + ULONG AppContainerNumber; + PSID PackageSid; + PSID_AND_ATTRIBUTES_HASH CapabilitiesHash; + PSID TrustLevelSid; + PSECURITY_ATTRIBUTES_OPAQUE SecurityAttributes; +} TOKEN_ACCESS_INFORMATION, *PTOKEN_ACCESS_INFORMATION; + +typedef struct _TOKEN_LOGGING_INFORMATION +{ + TOKEN_TYPE TokenType; + TOKEN_ELEVATION TokenElevation; + TOKEN_ELEVATION_TYPE TokenElevationType; + SECURITY_IMPERSONATION_LEVEL ImpersonationLevel; + ULONG IntegrityLevel; + SID_AND_ATTRIBUTES User; + PSID TrustLevelSid; + ULONG SessionId; + ULONG AppContainerNumber; + LUID AuthenticationId; + ULONG GroupCount; + ULONG GroupsLength; + PSID_AND_ATTRIBUTES Groups; +} TOKEN_LOGGING_INFORMATION, *PTOKEN_LOGGING_INFORMATION; + +#endif // (PHNT_MODE == PHNT_MODE_KERNEL) // // Types @@ -292,6 +441,11 @@ typedef struct _TOKEN_SECURITY_ATTRIBUTES_AND_OPERATION_INFORMATION } TOKEN_SECURITY_ATTRIBUTES_AND_OPERATION_INFORMATION, *PTOKEN_SECURITY_ATTRIBUTES_AND_OPERATION_INFORMATION; // rev +/** + * The TOKEN_PROCESS_TRUST_LEVEL structure contains information about + * the trust level assigned to a process token. The trust level is + * represented by a SID (Security Identifier) pointed to by TrustLevelSid. + */ typedef struct _TOKEN_PROCESS_TRUST_LEVEL { PSID TrustLevelSid; @@ -304,22 +458,39 @@ typedef struct _TOKEN_LOGGING_INFORMATION TOKEN_ELEVATION TokenElevation; TOKEN_ELEVATION_TYPE TokenElevationType; SECURITY_IMPERSONATION_LEVEL ImpersonationLevel; - DWORD IntegrityLevel; + ULONG IntegrityLevel; SID_AND_ATTRIBUTES User; PSID TrustLevelSid; - DWORD SessionId; - DWORD AppContainerNumber; + ULONG SessionId; + ULONG AppContainerNumber; LUID AuthenticationId; - DWORD GroupCount; - DWORD GroupsLength; + ULONG GroupCount; + ULONG GroupsLength; PSID_AND_ATTRIBUTES Groups; } TOKEN_LOGGING_INFORMATION, *PTOKEN_LOGGING_INFORMATION; -#endif +#endif // !defined(NTDDI_WIN11_GE) || (NTDDI_VERSION < NTDDI_WIN11_GE) // // Tokens // - +/** + * The NtCreateToken routine creates a new access token. + * + * \param TokenHandle Pointer to a variable that receives the handle to the newly created token. + * \param DesiredAccess Specifies the requested access rights for the new token. + * \param ObjectAttributes Optional pointer to an OBJECT_ATTRIBUTES structure specifying object attributes. + * \param Type Specifies the type of token to be created (primary or impersonation). + * \param AuthenticationId Pointer to a locally unique identifier (LUID) for the token. + * \param ExpirationTime Pointer to a LARGE_INTEGER specifying the expiration time of the token. + * \param User Pointer to a TOKEN_USER structure specifying the user account for the token. + * \param Groups Pointer to a TOKEN_GROUPS structure specifying the group accounts for the token. + * \param Privileges Pointer to a TOKEN_PRIVILEGES structure specifying the privileges for the token. + * \param Owner Optional pointer to a TOKEN_OWNER structure specifying the owner SID for the token. + * \param PrimaryGroup Pointer to a TOKEN_PRIMARY_GROUP structure specifying the primary group SID for the token. + * \param DefaultDacl Optional pointer to a TOKEN_DEFAULT_DACL structure specifying the default DACL for the token. + * \param Source Pointer to a TOKEN_SOURCE structure specifying the source of the token. + * \return NTSTATUS code indicating success or failure. + */ NTSYSCALLAPI NTSTATUS NTAPI @@ -340,6 +511,21 @@ NtCreateToken( ); #if (PHNT_VERSION >= PHNT_WINDOWS_8) +/** + * The NtCreateLowBoxToken routine creates a new lowbox access token based on an existing token. + * + * \param TokenHandle Pointer to a variable that receives the handle to the newly created lowbox token. + * \param ExistingTokenHandle Handle to an existing token to base the new token on. + * \param DesiredAccess Specifies the requested access rights for the new token. + * \param ObjectAttributes Optional pointer to an OBJECT_ATTRIBUTES structure specifying object attributes. + * \param PackageSid Pointer to a SID structure specifying the package SID for the lowbox token. + * \param CapabilityCount Number of capabilities in the Capabilities array. + * \param Capabilities Optional pointer to an array of SID_AND_ATTRIBUTES structures specifying capabilities. + * \param HandleCount Number of handles in the Handles array. + * \param Handles Optional pointer to an array of handles to be associated with the token. + * \return NTSTATUS code indicating success or failure. + * \sa https://learn.microsoft.com/en-us/windows/win32/secauthz/ntcreatelowboxtoken + */ NTSYSCALLAPI NTSTATUS NTAPI @@ -354,9 +540,31 @@ NtCreateLowBoxToken( _In_ ULONG HandleCount, _In_reads_opt_(HandleCount) HANDLE *Handles ); -#endif +#endif // (PHNT_VERSION >= PHNT_WINDOWS_8) #if (PHNT_VERSION >= PHNT_WINDOWS_8) +/** + * The NtCreateTokenEx routine creates a new access token with extended attributes. + * + * \param TokenHandle Pointer to a variable that receives the handle to the newly created token. + * \param DesiredAccess Specifies the requested access rights for the new token. + * \param ObjectAttributes Optional pointer to an OBJECT_ATTRIBUTES structure specifying object attributes. + * \param Type Specifies the type of token to be created (primary or impersonation). + * \param AuthenticationId Pointer to a locally unique identifier (LUID) for the token. + * \param ExpirationTime Pointer to a LARGE_INTEGER specifying the expiration time of the token. + * \param User Pointer to a TOKEN_USER structure specifying the user account for the token. + * \param Groups Pointer to a TOKEN_GROUPS structure specifying the group accounts for the token. + * \param Privileges Pointer to a TOKEN_PRIVILEGES structure specifying the privileges for the token. + * \param UserAttributes Optional pointer to a TOKEN_SECURITY_ATTRIBUTES_INFORMATION structure specifying user claims. + * \param DeviceAttributes Optional pointer to a TOKEN_SECURITY_ATTRIBUTES_INFORMATION structure specifying device claims. + * \param DeviceGroups Optional pointer to a TOKEN_GROUPS structure specifying device groups. + * \param MandatoryPolicy Optional pointer to a TOKEN_MANDATORY_POLICY structure specifying the mandatory policy. + * \param Owner Optional pointer to a TOKEN_OWNER structure specifying the owner SID for the token. + * \param PrimaryGroup Pointer to a TOKEN_PRIMARY_GROUP structure specifying the primary group SID for the token. + * \param DefaultDacl Optional pointer to a TOKEN_DEFAULT_DACL structure specifying the default DACL for the token. + * \param Source Pointer to a TOKEN_SOURCE structure specifying the source of the token. + * \return NTSTATUS code indicating success or failure. + */ NTSYSCALLAPI NTSTATUS NTAPI @@ -379,16 +587,16 @@ NtCreateTokenEx( _In_opt_ PTOKEN_DEFAULT_DACL DefaultDacl, _In_ PTOKEN_SOURCE Source ); -#endif +#endif // (PHNT_VERSION >= PHNT_WINDOWS_8) /** * The NtOpenProcessToken routine opens the access token associated with a process, and returns a handle that can be used to access that token. * - * @param ProcessHandle Handle to the process whose access token is to be opened. The handle must have PROCESS_QUERY_INFORMATION access. - * @param DesiredAccess ACCESS_MASK structure specifying the requested types of access to the access token. - * @param TokenHandle Pointer to a caller-allocated variable that receives a handle to the newly opened access token. - * @return NTSTATUS Successful or errant status. - * @remarks https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/ntifs/nf-ntifs-ntopenprocesstoken + * \param ProcessHandle Handle to the process whose access token is to be opened. The handle must have PROCESS_QUERY_INFORMATION access. + * \param DesiredAccess ACCESS_MASK structure specifying the requested types of access to the access token. + * \param TokenHandle Pointer to a caller-allocated variable that receives a handle to the newly opened access token. + * \return NTSTATUS Successful or errant status. + * \sa https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/ntifs/nf-ntifs-ntopenprocesstoken */ NTSYSCALLAPI NTSTATUS @@ -402,12 +610,12 @@ NtOpenProcessToken( /** * The NtOpenProcessTokenEx routine opens the access token associated with a process, and returns a handle that can be used to access that token. * - * @param ProcessHandle Handle to the process whose access token is to be opened. The handle must have PROCESS_QUERY_INFORMATION access. - * @param DesiredAccess ACCESS_MASK structure specifying the requested types of access to the access token. - * @param HandleAttributes Attributes for the created handle. Only OBJ_KERNEL_HANDLE is currently supported. - * @param TokenHandle Pointer to a caller-allocated variable that receives a handle to the newly opened access token. - * @return NTSTATUS Successful or errant status. - * @remarks https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/ntifs/nf-ntifs-ntopenprocesstokenex + * \param ProcessHandle Handle to the process whose access token is to be opened. The handle must have PROCESS_QUERY_INFORMATION access. + * \param DesiredAccess ACCESS_MASK structure specifying the requested types of access to the access token. + * \param HandleAttributes Attributes for the created handle. Only OBJ_KERNEL_HANDLE is currently supported. + * \param TokenHandle Pointer to a caller-allocated variable that receives a handle to the newly opened access token. + * \return NTSTATUS Successful or errant status. + * \sa https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/ntifs/nf-ntifs-ntopenprocesstokenex */ NTSYSCALLAPI NTSTATUS @@ -422,12 +630,12 @@ NtOpenProcessTokenEx( /** * The NtOpenThreadToken routine opens the access token associated with a thread, and returns a handle that can be used to access that token. * - * @param ThreadHandle Handle to the thread whose access token is to be opened. The handle must have THREAD_QUERY_INFORMATION access. - * @param DesiredAccess ACCESS_MASK structure specifying the requested types of access to the access token. - * @param OpenAsSelf Boolean value specifying whether the access check is to be made against the security context of the thread calling NtOpenThreadToken or against the security context of the process for the calling thread. - * @param TokenHandle Pointer to a caller-allocated variable that receives a handle to the newly opened access token. - * @return NTSTATUS Successful or errant status. - * @remarks https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/ntifs/nf-ntifs-ntopenthreadtoken + * \param ThreadHandle Handle to the thread whose access token is to be opened. The handle must have THREAD_QUERY_INFORMATION access. + * \param DesiredAccess ACCESS_MASK structure specifying the requested types of access to the access token. + * \param OpenAsSelf Boolean value specifying whether the access check is to be made against the security context of the thread calling NtOpenThreadToken or against the security context of the process for the calling thread. + * \param TokenHandle Pointer to a caller-allocated variable that receives a handle to the newly opened access token. + * \return NTSTATUS Successful or errant status. + * \sa https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/ntifs/nf-ntifs-ntopenthreadtoken */ NTSYSCALLAPI NTSTATUS @@ -442,13 +650,13 @@ NtOpenThreadToken( /** * The NtOpenThreadTokenEx routine opens the access token associated with a thread, and returns a handle that can be used to access that token. * - * @param ThreadHandle Handle to the thread whose access token is to be opened. The handle must have THREAD_QUERY_INFORMATION access. - * @param DesiredAccess ACCESS_MASK structure specifying the requested types of access to the access token. - * @param OpenAsSelf Boolean value specifying whether the access check is to be made against the security context of the thread calling NtOpenThreadToken or against the security context of the process for the calling thread. - * @param HandleAttributes Attributes for the created handle. Only OBJ_KERNEL_HANDLE is currently supported. - * @param TokenHandle Pointer to a caller-allocated variable that receives a handle to the newly opened access token. - * @return NTSTATUS Successful or errant status. - * @remarks https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/ntifs/nf-ntifs-ntopenthreadtokenex + * \param ThreadHandle Handle to the thread whose access token is to be opened. The handle must have THREAD_QUERY_INFORMATION access. + * \param DesiredAccess ACCESS_MASK structure specifying the requested types of access to the access token. + * \param OpenAsSelf Boolean value specifying whether the access check is to be made against the security context of the thread calling NtOpenThreadToken or against the security context of the process for the calling thread. + * \param HandleAttributes Attributes for the created handle. Only OBJ_KERNEL_HANDLE is currently supported. + * \param TokenHandle Pointer to a caller-allocated variable that receives a handle to the newly opened access token. + * \return NTSTATUS Successful or errant status. + * \sa https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/ntifs/nf-ntifs-ntopenthreadtokenex */ NTSYSCALLAPI NTSTATUS @@ -464,14 +672,14 @@ NtOpenThreadTokenEx( /** * The NtDuplicateToken function creates a handle to a new access token that duplicates an existing token. * - * @param ExistingTokenHandle A handle to an existing access token that was opened with the TOKEN_DUPLICATE access right. - * @param DesiredAccess ACCESS_MASK structure specifying the requested types of access to the access token. - * @param ObjectAttributes Pointer to an OBJECT_ATTRIBUTES structure that describes the requested properties for the new token. - * @param EffectiveOnly A Boolean value that indicates whether the entire existing token should be duplicated into the new token or just the effective (currently enabled) part of the token. - * @param Type Specifies the type of token to create either a primary token or an impersonation token. - * @param NewTokenHandle Pointer to a caller-allocated variable that receives a handle to the newly duplicated token. - * @return NTSTATUS Successful or errant status. - * @remarks https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/ntifs/nf-ntifs-ntduplicatetoken + * \param ExistingTokenHandle A handle to an existing access token that was opened with the TOKEN_DUPLICATE access right. + * \param DesiredAccess ACCESS_MASK structure specifying the requested types of access to the access token. + * \param ObjectAttributes Pointer to an OBJECT_ATTRIBUTES structure that describes the requested properties for the new token. + * \param EffectiveOnly A Boolean value that indicates whether the entire existing token should be duplicated into the new token or just the effective (currently enabled) part of the token. + * \param Type Specifies the type of token to create either a primary token or an impersonation token. + * \param NewTokenHandle Pointer to a caller-allocated variable that receives a handle to the newly duplicated token. + * \return NTSTATUS Successful or errant status. + * \sa https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/ntifs/nf-ntifs-ntduplicatetoken */ NTSYSCALLAPI NTSTATUS @@ -488,14 +696,14 @@ NtDuplicateToken( /** * The NtQueryInformationToken routine retrieves a specified type of information about an access token. The calling process must have appropriate access rights to obtain the information. * - * @param TokenHandle A handle to an existing access token from which information is to be retrieved. If TokenInformationClass is set to TokenSource, the handle must have TOKEN_QUERY_SOURCE access. - * For all other TokenInformationClass values, the handle must have TOKEN_QUERY access. - * @param TokenInformationClass A value from the TOKEN_INFORMATION_CLASS enumerated type identifying the type of information to be retrieved. - * @param TokenInformation Pointer to a caller-allocated buffer that receives the requested information about the token. - * @param TokenInformationLength Length, in bytes, of the caller-allocated TokenInformation buffer. - * @param ReturnLength Pointer to a caller-allocated variable that receives the actual length, in bytes, of the information returned in the TokenInformation buffer. - * @return NTSTATUS Successful or errant status. - * @remarks https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/ntifs/nf-ntifs-ntqueryinformationtoken + * \param TokenHandle A handle to an existing access token from which information is to be retrieved. If TokenInformationClass is set to TokenSource, the handle must have TOKEN_QUERY_SOURCE access. + * For all other TokenInformationClass values, the handle must have TOKEN_QUERY access. + * \param TokenInformationClass A value from the TOKEN_INFORMATION_CLASS enumerated type identifying the type of information to be retrieved. + * \param TokenInformation Pointer to a caller-allocated buffer that receives the requested information about the token. + * \param TokenInformationLength Length, in bytes, of the caller-allocated TokenInformation buffer. + * \param ReturnLength Pointer to a caller-allocated variable that receives the actual length, in bytes, of the information returned in the TokenInformation buffer. + * \return NTSTATUS Successful or errant status. + * \sa https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/ntifs/nf-ntifs-ntqueryinformationtoken */ NTSYSCALLAPI NTSTATUS @@ -511,12 +719,12 @@ NtQueryInformationToken( /** * The NtSetInformationToken routine modifies information in a specified token. The calling process must have appropriate access rights to set the information. * - * @param TokenHandle A handle to an existing access token which information is to be modified. - * @param TokenInformationClass A value from the TOKEN_INFORMATION_CLASS enumerated type identifying the type of information to be modified. - * @param TokenInformation Pointer to a caller-allocated buffer containing the information to be modified in the token. - * @param TokenInformationLength Length, in bytes, of the caller-allocated TokenInformation buffer. - * @return NTSTATUS Successful or errant status. - * @remarks https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/ntifs/nf-ntifs-ntsetinformationtoken + * \param TokenHandle A handle to an existing access token which information is to be modified. + * \param TokenInformationClass A value from the TOKEN_INFORMATION_CLASS enumerated type identifying the type of information to be modified. + * \param TokenInformation Pointer to a caller-allocated buffer containing the information to be modified in the token. + * \param TokenInformationLength Length, in bytes, of the caller-allocated TokenInformation buffer. + * \return NTSTATUS Successful or errant status. + * \sa https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/ntifs/nf-ntifs-ntsetinformationtoken */ NTSYSCALLAPI NTSTATUS @@ -531,15 +739,15 @@ NtSetInformationToken( /** * The NtAdjustPrivilegesToken routine enables or disables privileges in the specified access token. * - * @param TokenHandle Handle to the token that contains the privileges to be modified. The handle must have TOKEN_ADJUST_PRIVILEGES access. - * @param DisableAllPrivileges Specifies whether the function disables all of the token's privileges. If this value is TRUE, the function disables all privileges and ignores the NewState parameter. + * \param TokenHandle Handle to the token that contains the privileges to be modified. The handle must have TOKEN_ADJUST_PRIVILEGES access. + * \param DisableAllPrivileges Specifies whether the function disables all of the token's privileges. If this value is TRUE, the function disables all privileges and ignores the NewState parameter. * If it is FALSE, the function modifies privileges based on the information pointed to by the NewState parameter. - * @param NewState A pointer to a TOKEN_PRIVILEGES structure that specifies an array of privileges and their attributes. If DisableAllPrivileges is TRUE, the function ignores this parameter. - * @param BufferLength Specifies the size, in bytes, of the buffer pointed to by the PreviousState parameter. This parameter can be zero if the PreviousState parameter is NULL. - * @param PreviousState A pointer to a buffer that the function fills with a TOKEN_PRIVILEGES structure that contains the previous state of any privileges that the function modifies. - * @param ReturnLength A pointer to a variable that receives the required size, in bytes, of the buffer pointed to by the PreviousState parameter. This parameter can be NULL if PreviousState is NULL. - * @return NTSTATUS Successful or errant status. - * @remarks https://learn.microsoft.com/en-us/windows/win32/api/securitybaseapi/nf-securitybaseapi-adjusttokenprivileges + * \param NewState A pointer to a TOKEN_PRIVILEGES structure that specifies an array of privileges and their attributes. If DisableAllPrivileges is TRUE, the function ignores this parameter. + * \param BufferLength Specifies the size, in bytes, of the buffer pointed to by the PreviousState parameter. This parameter can be zero if the PreviousState parameter is NULL. + * \param PreviousState A pointer to a buffer that the function fills with a TOKEN_PRIVILEGES structure that contains the previous state of any privileges that the function modifies. + * \param ReturnLength A pointer to a variable that receives the required size, in bytes, of the buffer pointed to by the PreviousState parameter. This parameter can be NULL if PreviousState is NULL. + * \return NTSTATUS Successful or errant status. + * \sa https://learn.microsoft.com/en-us/windows/win32/api/securitybaseapi/nf-securitybaseapi-adjusttokenprivileges */ NTSYSCALLAPI NTSTATUS @@ -553,6 +761,18 @@ NtAdjustPrivilegesToken( _Out_opt_ PULONG ReturnLength ); +/** + * The NtAdjustGroupsToken routine enables or disables groups in the specified access token. + * + * \param TokenHandle Handle to the token that contains the groups to be modified. The handle must have TOKEN_ADJUST_GROUPS access. + * \param ResetToDefault Specifies whether the function resets the groups to the default state. If this value is TRUE, the function resets all groups to their default state and ignores the NewState parameter. + * \param NewState A pointer to a TOKEN_GROUPS structure that specifies an array of groups and their attributes. If ResetToDefault is TRUE, the function ignores this parameter. + * \param BufferLength Specifies the size, in bytes, of the buffer pointed to by the PreviousState parameter. This parameter can be zero if the PreviousState parameter is NULL. + * \param PreviousState A pointer to a buffer that the function fills with a TOKEN_GROUPS structure that contains the previous state of any groups that the function modifies. + * \param ReturnLength A pointer to a variable that receives the required size, in bytes, of the buffer pointed to by the PreviousState parameter. This parameter can be NULL if PreviousState is NULL. + * \return NTSTATUS Successful or errant status. + * \sa https://learn.microsoft.com/en-us/windows/win32/api/securitybaseapi/nf-securitybaseapi-adjusttokengroups + */ NTSYSCALLAPI NTSTATUS NTAPI @@ -587,8 +807,26 @@ NtAdjustTokenClaimsAndDeviceGroups( _Out_opt_ PULONG DeviceReturnLength, _Out_opt_ PULONG DeviceGroupsReturnBufferLength ); -#endif +#endif // (PHNT_VERSION >= PHNT_WINDOWS_8) +// NtFilterToken Flags +#define DISABLE_MAX_PRIVILEGE 0x1 // Disables all privileges in the new token except SE_CHANGE_NOTIFY_PRIVILEGE. +#define SANDBOX_INERT 0x2 // Stores the TOKEN_SANDBOX_INERT flag in the token. +#define LUA_TOKEN 0x4 +#define WRITE_RESTRICTED 0x8 + +/** + * The NtFilterToken routine creates a new access token that is a restricted version of an existing access token. + * + * \param ExistingTokenHandle Handle to a primary or impersonation token. The token can also be a restricted token. This token must already be open for TOKEN_DUPLICATE access. + * \param Flags Specifies additional privilege options. + * \param SidsToDisable The deny-only SIDs to include in the restricted token. The system uses a deny-only SID to deny access to a securable object. The absence of a deny-only SID does not allow access. + * \param PrivilegesToDelete The privileges to delete in the restricted token. This parameter is optional and can be NULL. + * \param RestrictedSids The list of restricting SIDs for the new token. This parameter is optional and can be NULL. + * \param NewTokenHandle The new restricted token. The new token is the same type, primary or impersonation, as the existing token. + * \return NTSTATUS Successful or errant status. + * \sa https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/ntifs/nf-ntifs-sefiltertoken + */ NTSYSCALLAPI NTSTATUS NTAPI @@ -612,17 +850,26 @@ NtFilterTokenEx( _In_opt_ PTOKEN_PRIVILEGES PrivilegesToDelete, _In_opt_ PTOKEN_GROUPS RestrictedSids, _In_ ULONG DisableUserClaimsCount, - _In_opt_ PUNICODE_STRING UserClaimsToDisable, + _In_opt_ PCUNICODE_STRING UserClaimsToDisable, _In_ ULONG DisableDeviceClaimsCount, - _In_opt_ PUNICODE_STRING DeviceClaimsToDisable, + _In_opt_ PCUNICODE_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 +#endif // (PHNT_VERSION >= PHNT_WINDOWS_8) +/** + * The NtCompareTokens routine compares two access tokens to determine whether they are equivalent. + * + * \param FirstTokenHandle Handle to the first access token to compare. The handle must have TOKEN_QUERY access. + * \param SecondTokenHandle Handle to the second access token to compare. The handle must have TOKEN_QUERY access. + * \param Equal Pointer to a BOOLEAN variable that receives TRUE if the tokens are equivalent, or FALSE otherwise. + * \return NTSTATUS Successful or errant status. + * \sa https://learn.microsoft.com/en-us/windows/win32/secauthz/ntcomparetokens + */ NTSYSCALLAPI NTSTATUS NTAPI @@ -632,6 +879,15 @@ NtCompareTokens( _Out_ PBOOLEAN Equal ); +/** + * The NtPrivilegeCheck routine determines whether a specified set of privileges are enabled in the access token of a client. + * + * \param ClientToken Handle to the access token of the client whose privileges are to be checked. The handle must have TOKEN_QUERY access. + * \param RequiredPrivileges Pointer to a PRIVILEGE_SET structure that specifies the set of privileges to be checked. On input, this structure contains the privileges to check. + * \param Result Pointer to a BOOLEAN variable that receives TRUE if all specified privileges are enabled, or FALSE otherwise. + * \return NTSTATUS Successful or errant status. + * \sa https://learn.microsoft.com/en-us/windows/win32/api/securitybaseapi/nf-securitybaseapi-privilegecheck + */ NTSYSCALLAPI NTSTATUS NTAPI @@ -641,6 +897,12 @@ NtPrivilegeCheck( _Out_ PBOOLEAN Result ); +/** + * The NtImpersonateAnonymousToken routine causes a thread to impersonate the anonymous token. + * + * \param ThreadHandle Handle to the thread that will impersonate the anonymous token. The handle must have THREAD_DIRECT_IMPERSONATION access. + * \return NTSTATUS Successful or errant status. + */ NTSYSCALLAPI NTSTATUS NTAPI @@ -648,23 +910,46 @@ NtImpersonateAnonymousToken( _In_ HANDLE ThreadHandle ); -#if (PHNT_VERSION >= PHNT_WINDOWS_7) -// rev +/** + * The NtQuerySecurityAttributesToken routine retrieves security attribute information from an access token. + * + * \param TokenHandle Handle to the access token from which to retrieve security attributes. The handle must have TOKEN_QUERY access. + * \param Attributes Pointer to an array of UNICODE_STRING structures specifying the names of the attributes to query. This parameter can be NULL if NumberOfAttributes is zero. + * \param NumberOfAttributes The number of attributes specified in the Attributes array. + * \param Buffer Pointer to a buffer that receives the security attribute information. The buffer receives a TOKEN_SECURITY_ATTRIBUTES_INFORMATION structure. + * \param Length The size, in bytes, of the Buffer parameter. + * \param ReturnLength Pointer to a variable that receives the number of bytes required to store the complete security attribute information. + * \return NTSTATUS Successful or errant status. + */ NTSYSCALLAPI NTSTATUS NTAPI NtQuerySecurityAttributesToken( _In_ HANDLE TokenHandle, - _In_reads_opt_(NumberOfAttributes) PUNICODE_STRING Attributes, + _In_reads_opt_(NumberOfAttributes) PCUNICODE_STRING Attributes, _In_ ULONG NumberOfAttributes, _Out_writes_bytes_(Length) PVOID Buffer, // PTOKEN_SECURITY_ATTRIBUTES_INFORMATION _In_ ULONG Length, _Out_ PULONG ReturnLength ); -#endif +// // Access checking - +// +/** + * The NtAccessCheck routine determines whether a security descriptor grants a specified set of access rights to the client represented by an access token. + * + * \param SecurityDescriptor Pointer to the SECURITY_DESCRIPTOR structure against which access is checked. + * \param ClientToken Handle to the access token representing the client. The handle must have TOKEN_QUERY access. + * \param DesiredAccess Access mask that specifies the access rights to check. + * \param GenericMapping Pointer to the GENERIC_MAPPING structure associated with the object for which access is being checked. + * \param PrivilegeSet Pointer to a PRIVILEGE_SET structure that receives the privileges required to access the object. The buffer must be large enough to hold the privilege set. + * \param PrivilegeSetLength Pointer to a variable that specifies the size, in bytes, of the PrivilegeSet buffer. On input, this is the size of the buffer; on output, it receives the number of bytes required. + * \param GrantedAccess Pointer to an access mask that receives the granted access rights. + * \param AccessStatus Pointer to a variable that receives the results of the access check. + * \return NTSTATUS code indicating success or failure. + * \sa https://learn.microsoft.com/en-us/windows/win32/api/securitybaseapi/nf-securitybaseapi-accesscheck + */ NTSYSCALLAPI NTSTATUS NTAPI @@ -679,6 +964,23 @@ NtAccessCheck( _Out_ PNTSTATUS AccessStatus ); +/** + * The NtAccessCheckByType routine determines whether a security descriptor grants a specified set of access rights to the client represented by an access token, taking into account object type information. + * + * \param SecurityDescriptor Pointer to the SECURITY_DESCRIPTOR structure against which access is checked. + * \param PrincipalSelfSid Optional pointer to a SID structure representing the principal self SID, or NULL. + * \param ClientToken Handle to the access token representing the client. The handle must have TOKEN_QUERY access. + * \param DesiredAccess Access mask that specifies the access rights to check. + * \param ObjectTypeList Pointer to an array of OBJECT_TYPE_LIST structures that specify the hierarchy of object types for the object being accessed. + * \param ObjectTypeListLength The number of elements in the ObjectTypeList array. + * \param GenericMapping Pointer to the GENERIC_MAPPING structure associated with the object for which access is being checked. + * \param PrivilegeSet Pointer to a PRIVILEGE_SET structure that receives the privileges required to access the object. The buffer must be large enough to hold the privilege set. + * \param PrivilegeSetLength Pointer to a variable that specifies the size, in bytes, of the PrivilegeSet buffer. On input, this is the size of the buffer; on output, it receives the number of bytes required. + * \param GrantedAccess Pointer to an access mask that receives the granted access rights. + * \param AccessStatus Pointer to a variable that receives the results of the access check. + * \return NTSTATUS code indicating success or failure. + * \sa https://learn.microsoft.com/en-us/windows/win32/api/securitybaseapi/nf-securitybaseapi-accesscheckbytype + */ NTSYSCALLAPI NTSTATUS NTAPI @@ -696,6 +998,23 @@ NtAccessCheckByType( _Out_ PNTSTATUS AccessStatus ); +/** + * The NtAccessCheckByTypeResultList routine determines whether a security descriptor grants a specified set of access rights to the client represented by an access token, and returns the results for each object type in a list. + * + * \param SecurityDescriptor Pointer to the SECURITY_DESCRIPTOR structure against which access is checked. + * \param PrincipalSelfSid Optional pointer to a SID structure representing the principal self SID, or NULL. + * \param ClientToken Handle to the access token representing the client. The handle must have TOKEN_QUERY access. + * \param DesiredAccess Access mask that specifies the access rights to check. + * \param ObjectTypeList Pointer to an array of OBJECT_TYPE_LIST structures that specify the hierarchy of object types for the object being accessed. + * \param ObjectTypeListLength The number of elements in the ObjectTypeList array. + * \param GenericMapping Pointer to the GENERIC_MAPPING structure associated with the object for which access is being checked. + * \param PrivilegeSet Pointer to a PRIVILEGE_SET structure that receives the privileges required to access the object. The buffer must be large enough to hold the privilege set. + * \param PrivilegeSetLength Pointer to a variable that specifies the size, in bytes, of the PrivilegeSet buffer. On input, this is the size of the buffer; on output, it receives the number of bytes required. + * \param GrantedAccess Pointer to an array of access masks that receive the granted access rights for each object type. + * \param AccessStatus Pointer to an array of NTSTATUS values that receive the results of the access check for each object type. + * \return NTSTATUS code indicating success or failure. + * \sa https://learn.microsoft.com/en-us/windows/win32/api/securitybaseapi/nf-securitybaseapi-accesscheckbytyperesultlist + */ NTSYSCALLAPI NTSTATUS NTAPI @@ -713,21 +1032,26 @@ NtAccessCheckByTypeResultList( _Out_writes_(ObjectTypeListLength) PNTSTATUS AccessStatus ); +// // Signing +// + +#define SIGNING_LEVEL_FILE_CACHE_FLAG_NOT_VALIDATED 0x01 +#define SIGNING_LEVEL_FILE_CACHE_FLAG_VALIDATE_ONLY 0x04 #if (PHNT_VERSION >= PHNT_WINDOWS_8) - -NTSYSCALLAPI -NTSTATUS -NTAPI -NtSetCachedSigningLevel( - _In_ ULONG Flags, - _In_ SE_SIGNING_LEVEL InputSigningLevel, - _In_reads_(SourceFileCount) PHANDLE SourceFiles, - _In_ ULONG SourceFileCount, - _In_opt_ HANDLE TargetFile - ); - +/** + * The NtGetCachedSigningLevel routine retrieves the cached signing level of a file. + * + * \param File Handle to a file. + * \param Flags Pointer to the flags set on the file. + * \param SigningLevel Pointer to the signing level. + * \param Thumbprint Pointer to the thumbprint. + * \param ThumbprintSize Pointer to the thumbprint size. + * \param ThumbprintAlgorithm Pointer to the thumbprint algorithm. + * \return NTSTATUS Successful or errant status. + * \sa https://learn.microsoft.com/en-us/windows/win32/api/securitybaseapi/nf-securitybaseapi-getcachedsigninglevel + */ NTSYSCALLAPI NTSTATUS NTAPI @@ -740,7 +1064,28 @@ NtGetCachedSigningLevel( _Out_opt_ PULONG ThumbprintAlgorithm ); -#endif +/** + * The NtSetCachedSigningLevel routine sets the cached signing level of a file. + * + * \param Flags Pointer to the flags set on the file. + * \param InputSigningLevel Pointer to the signing level. + * \param SourceFiles Pointer to a set of source file handles. + * \param SourceFileCount The source file count. + * \param TargetFile The target file. + * \return NTSTATUS Successful or errant status. + * \sa https://learn.microsoft.com/en-us/windows/win32/api/securitybaseapi/nf-securitybaseapi-setcachedsigninglevel + */ +NTSYSCALLAPI +NTSTATUS +NTAPI +NtSetCachedSigningLevel( + _In_ ULONG Flags, + _In_ SE_SIGNING_LEVEL InputSigningLevel, + _In_reads_(SourceFileCount) PHANDLE SourceFiles, + _In_ ULONG SourceFileCount, + _In_opt_ HANDLE TargetFile + ); +#endif // (PHNT_VERSION >= PHNT_WINDOWS_8) // rev typedef struct _SE_FILE_CACHE_CLAIM_INFORMATION @@ -758,7 +1103,6 @@ typedef struct _SE_SET_FILE_CACHE_INFORMATION } SE_SET_FILE_CACHE_INFORMATION, *PSE_SET_FILE_CACHE_INFORMATION; #if (PHNT_VERSION >= PHNT_WINDOWS_10_RS1) - // rev NTSYSCALLAPI NTSTATUS @@ -771,11 +1115,9 @@ NtSetCachedSigningLevel2( _In_opt_ HANDLE TargetFile, _In_opt_ SE_SET_FILE_CACHE_INFORMATION* CacheInformation ); - -#endif +#endif // (PHNT_VERSION >= PHNT_WINDOWS_10_RS1) #if (PHNT_VERSION >= PHNT_WINDOWS_10_RS2) - // rev NTSYSCALLAPI NTSTATUS @@ -784,19 +1126,38 @@ NtCompareSigningLevels( _In_ SE_SIGNING_LEVEL FirstSigningLevel, _In_ SE_SIGNING_LEVEL SecondSigningLevel ); +#endif // (PHNT_VERSION >= PHNT_WINDOWS_10_RS2) -#endif - +// // Audit alarm +// +/** + * The NtAccessCheckAndAuditAlarm routine determines whether a security descriptor grants a specified set of access rights to the client being impersonated by the calling thread. + * If the security descriptor has a SACL with ACEs that apply to the client, the function generates any necessary audit messages in the security event log. + * + * \param SubsystemName A pointer to a null-terminated string specifying the name of the subsystem calling the function. + * \param HandleId A pointer to a unique value representing the client's handle to the object. + * \param ObjectTypeName A pointer to a null-terminated string specifying the type of object being created or accessed. + * \param ObjectName A pointer to a null-terminated string specifying the name of the object being created or accessed. + * \param SecurityDescriptor A pointer to the SECURITY_DESCRIPTOR structure against which access is checked. + * \param DesiredAccess Access mask that specifies the access rights to check. This mask must have been mapped by the MapGenericMask function to contain no generic access rights. + * \param GenericMapping A pointer to the GENERIC_MAPPING structure associated with the object for which access is being checked. + * \param ObjectCreation Specifies a flag that determines whether the calling application will create a new object when access is granted. + * \param GrantedAccess A pointer to an access mask that receives the granted access rights. + * \param AccessStatus A pointer to a variable that receives the results of the access check. + * \param GenerateOnClose A pointer to a flag set by the audit-generation routine when the function returns. + * \return NTSTATUS Successful or errant status. + * \sa https://learn.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-accesscheckandauditalarma + */ NTSYSCALLAPI NTSTATUS NTAPI NtAccessCheckAndAuditAlarm( - _In_ PUNICODE_STRING SubsystemName, + _In_ PCUNICODE_STRING SubsystemName, _In_opt_ PVOID HandleId, - _In_ PUNICODE_STRING ObjectTypeName, - _In_ PUNICODE_STRING ObjectName, + _In_ PCUNICODE_STRING ObjectTypeName, + _In_ PCUNICODE_STRING ObjectName, _In_ PSECURITY_DESCRIPTOR SecurityDescriptor, _In_ ACCESS_MASK DesiredAccess, _In_ PGENERIC_MAPPING GenericMapping, @@ -806,14 +1167,37 @@ NtAccessCheckAndAuditAlarm( _Out_ PBOOLEAN GenerateOnClose ); +/** + * The NtAccessCheckByTypeAndAuditAlarm routine determines whether a security descriptor grants a specified set of access rights to the client being impersonated by the calling thread. + * If the security descriptor has a SACL with ACEs that apply to the client, the function generates any necessary audit messages in the security event log. + * + * \param SubsystemName A pointer to a UNICODE_STRING specifying the name of the subsystem calling the function. + * \param HandleId A pointer to a unique value representing the client's handle to the object. + * \param ObjectTypeName A pointer to a UNICODE_STRING specifying the type of object being created or accessed. + * \param ObjectName A pointer to a UNICODE_STRING specifying the name of the object being created or accessed. + * \param SecurityDescriptor A pointer to the SECURITY_DESCRIPTOR structure against which access is checked. + * \param PrincipalSelfSid A pointer to a SID structure representing the principal self SID, or NULL. + * \param DesiredAccess Access mask that specifies the access rights to check. This mask must have been mapped by the MapGenericMask function to contain no generic access rights. + * \param AuditType Specifies the type of audit event to be generated. + * \param Flags Audit event flags. + * \param ObjectTypeList A pointer to an array of OBJECT_TYPE_LIST structures that specify the hierarchy of object types for the object being accessed. + * \param ObjectTypeListLength The number of elements in the ObjectTypeList array. + * \param GenericMapping A pointer to the GENERIC_MAPPING structure associated with the object for which access is being checked. + * \param ObjectCreation Specifies a flag that determines whether the calling application will create a new object when access is granted. + * \param GrantedAccess A pointer to an access mask that receives the granted access rights. + * \param AccessStatus A pointer to a variable that receives the results of the access check. + * \param GenerateOnClose A pointer to a flag set by the audit-generation routine when the function returns. + * \return NTSTATUS Successful or errant status. + * \sa https://learn.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-accesscheckbytypeandauditalarma + */ NTSYSCALLAPI NTSTATUS NTAPI NtAccessCheckByTypeAndAuditAlarm( - _In_ PUNICODE_STRING SubsystemName, + _In_ PCUNICODE_STRING SubsystemName, _In_opt_ PVOID HandleId, - _In_ PUNICODE_STRING ObjectTypeName, - _In_ PUNICODE_STRING ObjectName, + _In_ PCUNICODE_STRING ObjectTypeName, + _In_ PCUNICODE_STRING ObjectName, _In_ PSECURITY_DESCRIPTOR SecurityDescriptor, _In_opt_ PSID PrincipalSelfSid, _In_ ACCESS_MASK DesiredAccess, @@ -828,14 +1212,37 @@ NtAccessCheckByTypeAndAuditAlarm( _Out_ PBOOLEAN GenerateOnClose ); +/** + * The NtAccessCheckByTypeResultListAndAuditAlarm routine determines whether a security descriptor grants a specified set of access rights to the client being impersonated by the calling thread. + * It also generates audit messages for each object type in the hierarchy, and returns the results for each object type in a list. + * + * \param SubsystemName A pointer to a UNICODE_STRING specifying the name of the subsystem calling the function. + * \param HandleId A pointer to a unique value representing the client's handle to the object. + * \param ObjectTypeName A pointer to a UNICODE_STRING specifying the type of object being created or accessed. + * \param ObjectName A pointer to a UNICODE_STRING specifying the name of the object being created or accessed. + * \param SecurityDescriptor A pointer to the SECURITY_DESCRIPTOR structure against which access is checked. + * \param PrincipalSelfSid A pointer to a SID structure representing the principal self SID, or NULL. + * \param DesiredAccess Access mask that specifies the access rights to check. + * \param AuditType Specifies the type of audit event to be generated. + * \param Flags Audit event flags. + * \param ObjectTypeList A pointer to an array of OBJECT_TYPE_LIST structures that specify the hierarchy of object types for the object being accessed. + * \param ObjectTypeListLength The number of elements in the ObjectTypeList array. + * \param GenericMapping A pointer to the GENERIC_MAPPING structure associated with the object for which access is being checked. + * \param ObjectCreation Specifies a flag that determines whether the calling application will create a new object when access is granted. + * \param GrantedAccess A pointer to an array of access masks that receive the granted access rights for each object type. + * \param AccessStatus A pointer to an array of NTSTATUS values that receive the results of the access check for each object type. + * \param GenerateOnClose A pointer to a flag set by the audit-generation routine when the function returns. + * \return NTSTATUS Successful or errant status. + * \sa https://learn.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-accesscheckbytyperesultlistandauditalarma + */ NTSYSCALLAPI NTSTATUS NTAPI NtAccessCheckByTypeResultListAndAuditAlarm( - _In_ PUNICODE_STRING SubsystemName, + _In_ PCUNICODE_STRING SubsystemName, _In_opt_ PVOID HandleId, - _In_ PUNICODE_STRING ObjectTypeName, - _In_ PUNICODE_STRING ObjectName, + _In_ PCUNICODE_STRING ObjectTypeName, + _In_ PCUNICODE_STRING ObjectName, _In_ PSECURITY_DESCRIPTOR SecurityDescriptor, _In_opt_ PSID PrincipalSelfSid, _In_ ACCESS_MASK DesiredAccess, @@ -850,15 +1257,39 @@ NtAccessCheckByTypeResultListAndAuditAlarm( _Out_ PBOOLEAN GenerateOnClose ); +/** + * The NtAccessCheckByTypeResultListAndAuditAlarmByHandle routine determines whether a security descriptor grants a specified set of access rights to the client represented by a specified access token. + * It also generates audit messages for each object type in the hierarchy, and returns the results for each object type in a list. + * + * \param SubsystemName A pointer to a UNICODE_STRING specifying the name of the subsystem calling the function. + * \param HandleId A pointer to a unique value representing the client's handle to the object. + * \param ClientToken Handle to the access token representing the client. + * \param ObjectTypeName A pointer to a UNICODE_STRING specifying the type of object being created or accessed. + * \param ObjectName A pointer to a UNICODE_STRING specifying the name of the object being created or accessed. + * \param SecurityDescriptor A pointer to the SECURITY_DESCRIPTOR structure against which access is checked. + * \param PrincipalSelfSid A pointer to a SID structure representing the principal self SID, or NULL. + * \param DesiredAccess Access mask that specifies the access rights to check. + * \param AuditType Specifies the type of audit event to be generated. + * \param Flags Audit event flags. + * \param ObjectTypeList A pointer to an array of OBJECT_TYPE_LIST structures that specify the hierarchy of object types for the object being accessed. + * \param ObjectTypeListLength The number of elements in the ObjectTypeList array. + * \param GenericMapping A pointer to the GENERIC_MAPPING structure associated with the object for which access is being checked. + * \param ObjectCreation Specifies a flag that determines whether the calling application will create a new object when access is granted. + * \param GrantedAccess A pointer to an array of access masks that receive the granted access rights for each object type. + * \param AccessStatus A pointer to an array of NTSTATUS values that receive the results of the access check for each object type. + * \param GenerateOnClose A pointer to a flag set by the audit-generation routine when the function returns. + * \return NTSTATUS Successful or errant status. + * \sa https://learn.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-accesscheckbytyperesultlistandauditalarmbyhandlea + */ NTSYSCALLAPI NTSTATUS NTAPI NtAccessCheckByTypeResultListAndAuditAlarmByHandle( - _In_ PUNICODE_STRING SubsystemName, + _In_ PCUNICODE_STRING SubsystemName, _In_opt_ PVOID HandleId, _In_ HANDLE ClientToken, - _In_ PUNICODE_STRING ObjectTypeName, - _In_ PUNICODE_STRING ObjectName, + _In_ PCUNICODE_STRING ObjectTypeName, + _In_ PCUNICODE_STRING ObjectName, _In_ PSECURITY_DESCRIPTOR SecurityDescriptor, _In_opt_ PSID PrincipalSelfSid, _In_ ACCESS_MASK DesiredAccess, @@ -873,14 +1304,31 @@ NtAccessCheckByTypeResultListAndAuditAlarmByHandle( _Out_ PBOOLEAN GenerateOnClose ); +/** + * The NtOpenObjectAuditAlarm routine generates an audit message in the security event log when an object is opened. + * + * \param SubsystemName A pointer to a UNICODE_STRING specifying the name of the subsystem calling the function. + * \param HandleId A pointer to a unique value representing the client's handle to the object. + * \param ObjectTypeName A pointer to a UNICODE_STRING specifying the type of object being opened. + * \param ObjectName A pointer to a UNICODE_STRING specifying the name of the object being opened. + * \param SecurityDescriptor A pointer to the SECURITY_DESCRIPTOR structure for the object. + * \param ClientToken Handle to the access token representing the client. + * \param DesiredAccess Access mask that specifies the access rights requested. + * \param GrantedAccess Access mask that specifies the access rights granted. + * \param Privileges A pointer to a PRIVILEGE_SET structure that specifies the privileges used to gain access, or NULL. + * \param ObjectCreation Specifies a flag that determines whether the object is being created. + * \param AccessGranted Specifies a flag that determines whether access was granted. + * \param GenerateOnClose A pointer to a flag set by the audit-generation routine when the function returns. + * \return NTSTATUS Successful or errant status. + */ NTSYSCALLAPI NTSTATUS NTAPI NtOpenObjectAuditAlarm( - _In_ PUNICODE_STRING SubsystemName, + _In_ PCUNICODE_STRING SubsystemName, _In_opt_ PVOID HandleId, - _In_ PUNICODE_STRING ObjectTypeName, - _In_ PUNICODE_STRING ObjectName, + _In_ PCUNICODE_STRING ObjectTypeName, + _In_ PCUNICODE_STRING ObjectName, _In_opt_ PSECURITY_DESCRIPTOR SecurityDescriptor, _In_ HANDLE ClientToken, _In_ ACCESS_MASK DesiredAccess, @@ -891,11 +1339,22 @@ NtOpenObjectAuditAlarm( _Out_ PBOOLEAN GenerateOnClose ); +/** + * The NtPrivilegeObjectAuditAlarm routine generates an audit message in the security event log when a privilege is used to access an object. + * + * \param SubsystemName A pointer to a UNICODE_STRING specifying the name of the subsystem calling the function. + * \param HandleId A pointer to a unique value representing the client's handle to the object. + * \param ClientToken Handle to the access token representing the client. + * \param DesiredAccess Access mask that specifies the access rights requested. + * \param Privileges A pointer to a PRIVILEGE_SET structure that specifies the privileges used to gain access. + * \param AccessGranted Specifies a flag that determines whether access was granted. + * \return NTSTATUS Successful or errant status. + */ NTSYSCALLAPI NTSTATUS NTAPI NtPrivilegeObjectAuditAlarm( - _In_ PUNICODE_STRING SubsystemName, + _In_ PCUNICODE_STRING SubsystemName, _In_opt_ PVOID HandleId, _In_ HANDLE ClientToken, _In_ ACCESS_MASK DesiredAccess, @@ -903,33 +1362,93 @@ NtPrivilegeObjectAuditAlarm( _In_ BOOLEAN AccessGranted ); +/** + * The NtCloseObjectAuditAlarm routine generates an audit message in the security event log when an object handle is closed. + * + * \param SubsystemName A pointer to a UNICODE_STRING specifying the name of the subsystem calling the function. + * \param HandleId A pointer to a unique value representing the client's handle to the object. + * \param GenerateOnClose Specifies a flag that determines whether to generate an audit on close. + * \return NTSTATUS Successful or errant status. + */ NTSYSCALLAPI NTSTATUS NTAPI NtCloseObjectAuditAlarm( - _In_ PUNICODE_STRING SubsystemName, + _In_ PCUNICODE_STRING SubsystemName, _In_opt_ PVOID HandleId, _In_ BOOLEAN GenerateOnClose ); +/** + * The NtDeleteObjectAuditAlarm routine generates an audit message in the security event log when an object is deleted. + * + * \param SubsystemName A pointer to a UNICODE_STRING specifying the name of the subsystem calling the function. + * \param HandleId A pointer to a unique value representing the client's handle to the object. + * \param GenerateOnClose Specifies a flag that determines whether to generate an audit on close. + * \return NTSTATUS Successful or errant status. + */ NTSYSCALLAPI NTSTATUS NTAPI NtDeleteObjectAuditAlarm( - _In_ PUNICODE_STRING SubsystemName, + _In_ PCUNICODE_STRING SubsystemName, _In_opt_ PVOID HandleId, _In_ BOOLEAN GenerateOnClose ); +/** + * The NtPrivilegedServiceAuditAlarm routine generates an audit message in the security event log when a privileged service is accessed. + * + * \param SubsystemName A pointer to a UNICODE_STRING specifying the name of the subsystem calling the function. + * \param ServiceName A pointer to a UNICODE_STRING specifying the name of the service being accessed. + * \param ClientToken Handle to the access token representing the client. + * \param Privileges A pointer to a PRIVILEGE_SET structure that specifies the privileges used to access the service. + * \param AccessGranted Specifies a flag that determines whether access was granted. + * \return NTSTATUS Successful or errant status. + * \sa https://learn.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-privilegedserviceauditalarma + */ NTSYSCALLAPI NTSTATUS NTAPI NtPrivilegedServiceAuditAlarm( - _In_ PUNICODE_STRING SubsystemName, - _In_ PUNICODE_STRING ServiceName, + _In_ PCUNICODE_STRING SubsystemName, + _In_ PCUNICODE_STRING ServiceName, _In_ HANDLE ClientToken, _In_ PPRIVILEGE_SET Privileges, _In_ BOOLEAN AccessGranted ); -#endif +// +// 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 // _NTSEAPI_H diff --git a/ntsmss.h b/ntsmss.h index b2aea96..2a71f7c 100644 --- a/ntsmss.h +++ b/ntsmss.h @@ -138,10 +138,10 @@ typedef struct _SBFOREIGNSESSIONCOMPLETE // private typedef struct _SBCREATEPROCESSIN { - _In_ PUNICODE_STRING ImageFileName; - _In_ PUNICODE_STRING CurrentDirectory; - _In_ PUNICODE_STRING CommandLine; - _In_opt_ PUNICODE_STRING DefaultLibPath; + _In_ PCUNICODE_STRING ImageFileName; + _In_ PCUNICODE_STRING CurrentDirectory; + _In_ PCUNICODE_STRING CommandLine; + _In_opt_ PCUNICODE_STRING DefaultLibPath; _In_ ULONG Flags; // SMP_* _In_ ULONG DefaultDebugFlags; } SBCREATEPROCESSIN, *PSBCREATEPROCESSIN; @@ -193,7 +193,7 @@ NTSYSAPI NTSTATUS NTAPI RtlConnectToSm( - _In_opt_ PUNICODE_STRING ApiPortName, + _In_opt_ PCUNICODE_STRING ApiPortName, _In_opt_ HANDLE ApiPortHandle, _In_ ULONG ProcessImageType, _Out_ PHANDLE SmssConnection diff --git a/ntstrsafe.h b/ntstrsafe.h index 86b9054..e1dee9c 100644 --- a/ntstrsafe.h +++ b/ntstrsafe.h @@ -9,6 +9,7 @@ * Copyright (c) Microsoft Corp. All rights reserved. * * * ******************************************************************/ + #ifndef _NTSTRSAFE_H_INCLUDED_ #define _NTSTRSAFE_H_INCLUDED_ #if (_MSC_VER > 1000) diff --git a/ntsxs.h b/ntsxs.h index ca9a37a..48136ba 100644 --- a/ntsxs.h +++ b/ntsxs.h @@ -29,9 +29,7 @@ typedef enum _ACTCTX_COMPATIBILITY_ELEMENT_TYPE ACTCTX_COMPATIBILITY_ELEMENT_TYPE_MITIGATION, ACTCTX_COMPATIBILITY_ELEMENT_TYPE_MAXVERSIONTESTED } ACTCTX_COMPATIBILITY_ELEMENT_TYPE; -#endif - -#include +#endif // (PHNT_MODE == PHNT_MODE_KERNEL) typedef struct _ACTIVATION_CONTEXT_DATA { @@ -93,7 +91,7 @@ typedef struct _ACTIVATION_CONTEXT_DATA_ASSEMBLY_ROSTER_HEADER typedef struct _ACTIVATION_CONTEXT_DATA_ASSEMBLY_ROSTER_ENTRY { - ULONG Flags; + ULONG Flags; // ACTIVATION_CONTEXT_DATA_ASSEMBLY_ROSTER_ENTRY_* ULONG PseudoKey; ULONG AssemblyNameOffset; // to WCHAR[], from ACTIVATION_CONTEXT_DATA base ULONG AssemblyNameLength; @@ -178,7 +176,7 @@ typedef struct _ACTIVATION_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 + 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 @@ -188,7 +186,7 @@ typedef struct _ACTIVATION_CONTEXT_GUID_SECTION_HASH_BUCKET } 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_ASSEMBLY_INFORMATION (1) // ACTIVATION_CONTEXT_DATA_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 @@ -218,11 +216,19 @@ typedef struct _ACTIVATION_CONTEXT_DATA_ASSEMBLY_INFORMATION ULONG ManifestPathType; // ACTIVATION_CONTEXT_PATH_TYPE_* ULONG ManifestPathLength; ULONG ManifestPathOffset; // to WCHAR[], from section header - LARGE_INTEGER ManifestLastWriteTime; + struct + { + ULONG LowPart; + LONG HighPart; + } ManifestLastWriteTime; ULONG PolicyPathType; // ACTIVATION_CONTEXT_PATH_TYPE_* ULONG PolicyPathLength; ULONG PolicyPathOffset; // to WCHAR[], from section header - LARGE_INTEGER PolicyLastWriteTime; + struct + { + ULONG LowPart; + LONG HighPart; + } PolicyLastWriteTime; ULONG MetadataSatelliteRosterIndex; ULONG Unused2; ULONG ManifestVersionMajor; @@ -280,7 +286,7 @@ typedef struct _ACTIVATION_CONTEXT_DATA_WINDOW_CLASS_REDIRECTION ULONG Size; ULONG Flags; ULONG VersionSpecificClassNameLength; - ULONG VersionSpecificClassNameOffset; // to WHCAR[], from this struct base + ULONG VersionSpecificClassNameOffset; // to WCHAR[], 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; @@ -304,7 +310,7 @@ typedef struct _ACTIVATION_CONTEXT_DATA_WINDOW_CLASS_REDIRECTION typedef struct _ACTIVATION_CONTEXT_DATA_COM_SERVER_REDIRECTION { ULONG Size; - ULONG Flags; + ULONG Flags; // ACTIVATION_CONTEXT_DATA_COM_SERVER_MISCSTATUS_HAS_* ULONG ThreadingModel; // ACTIVATION_CONTEXT_DATA_COM_SERVER_REDIRECTION_THREADING_MODEL_* GUID ReferenceClsid; GUID ConfiguredClsid; @@ -316,11 +322,11 @@ typedef struct _ACTIVATION_CONTEXT_DATA_COM_SERVER_REDIRECTION 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; + ULONG MiscStatusDefault; // OLEMISC_* oleidl.h + ULONG MiscStatusContent; // OLEMISC_* oleidl.h + ULONG MiscStatusThumbnail; // OLEMISC_* oleidl.h + ULONG MiscStatusIcon; // OLEMISC_* oleidl.h + ULONG MiscStatusDocPrint; // OLEMISC_* oleidl.h } ACTIVATION_CONTEXT_DATA_COM_SERVER_REDIRECTION, *PACTIVATION_CONTEXT_DATA_COM_SERVER_REDIRECTION; #define ACTIVATION_CONTEXT_DATA_COM_SERVER_REDIRECTION_SHIM_TYPE_OTHER 1 @@ -368,14 +374,14 @@ typedef struct _ACTIVATION_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 + 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; @@ -392,13 +398,13 @@ typedef struct _ACTIVATION_CONTEXT_DATA_COM_PROGID_REDIRECTION 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 + ULONG Size; + ULONG Flags; + GUID SurrogateIdent; + ULONG VersionOffset; // to WCHAR[], from this struct base + ULONG VersionLength; + ULONG TypeNameOffset; // to WCHAR[], from this struct base + ULONG TypeNameLength; } ACTIVATION_CONTEXT_DATA_CLR_SURROGATE, *PACTIVATION_CONTEXT_DATA_CLR_SURROGATE; #define ACTIVATION_CONTEXT_DATA_APPLICATION_SETTINGS_FORMAT_LONGHORN 1 @@ -438,8 +444,6 @@ typedef struct _ACTIVATION_CONTEXT_COMPATIBILITY_INFORMATION_LEGACY COMPATIBILITY_CONTEXT_ELEMENT_LEGACY Elements[ANYSIZE_ARRAY]; } ACTIVATION_CONTEXT_COMPATIBILITY_INFORMATION_LEGACY, *PACTIVATION_CONTEXT_COMPATIBILITY_INFORMATION_LEGACY; -#include - // begin_private typedef struct _ASSEMBLY_STORAGE_MAP_ENTRY @@ -464,7 +468,8 @@ typedef struct _ACTIVATION_CONTEXT *PACTIVATION_CONTEXT; #define ACTIVATION_CONTEXT_NOTIFICATION_ZOMBIFY 2 #define ACTIVATION_CONTEXT_NOTIFICATION_USED 3 -typedef VOID (NTAPI *PACTIVATION_CONTEXT_NOTIFY_ROUTINE)( +typedef _Function_class_(ACTIVATION_CONTEXT_NOTIFY_ROUTINE) +VOID NTAPI ACTIVATION_CONTEXT_NOTIFY_ROUTINE( _In_ ULONG NotificationType, // ACTIVATION_CONTEXT_NOTIFICATION_* _In_ PACTIVATION_CONTEXT ActivationContext, _In_ PACTIVATION_CONTEXT_DATA ActivationContextData, @@ -472,6 +477,7 @@ typedef VOID (NTAPI *PACTIVATION_CONTEXT_NOTIFY_ROUTINE)( _In_opt_ PVOID NotificationData, _Inout_ PBOOLEAN DisableThisNotification ); +typedef ACTIVATION_CONTEXT_NOTIFY_ROUTINE* PACTIVATION_CONTEXT_NOTIFY_ROUTINE; typedef struct _ACTIVATION_CONTEXT { @@ -512,4 +518,4 @@ typedef struct _ACTIVATION_CONTEXT_STACK // end_private -#endif +#endif // _NTSXS_H diff --git a/nttmapi.h b/nttmapi.h index 43b8c09..1a0524f 100644 --- a/nttmapi.h +++ b/nttmapi.h @@ -7,7 +7,6 @@ #ifndef _NTTMAPI_H #define _NTTMAPI_H -#if (PHNT_VERSION >= PHNT_WINDOWS_VISTA) NTSYSCALLAPI NTSTATUS NTAPI @@ -15,13 +14,11 @@ NtCreateTransactionManager( _Out_ PHANDLE TmHandle, _In_ ACCESS_MASK DesiredAccess, _In_opt_ POBJECT_ATTRIBUTES ObjectAttributes, - _In_opt_ PUNICODE_STRING LogFileName, + _In_opt_ PCUNICODE_STRING LogFileName, _In_opt_ ULONG CreateOptions, _In_opt_ ULONG CommitStrength ); -#endif -#if (PHNT_VERSION >= PHNT_WINDOWS_VISTA) NTSYSCALLAPI NTSTATUS NTAPI @@ -29,23 +26,19 @@ NtOpenTransactionManager( _Out_ PHANDLE TmHandle, _In_ ACCESS_MASK DesiredAccess, _In_opt_ POBJECT_ATTRIBUTES ObjectAttributes, - _In_opt_ PUNICODE_STRING LogFileName, + _In_opt_ PCUNICODE_STRING LogFileName, _In_opt_ LPGUID TmIdentity, _In_opt_ ULONG OpenOptions ); -#endif -#if (PHNT_VERSION >= PHNT_WINDOWS_VISTA) NTSYSCALLAPI NTSTATUS NTAPI NtRenameTransactionManager( - _In_ PUNICODE_STRING LogFileName, + _In_ PCUNICODE_STRING LogFileName, _In_ LPGUID ExistingTransactionManagerGuid ); -#endif -#if (PHNT_VERSION >= PHNT_WINDOWS_VISTA) NTSYSCALLAPI NTSTATUS NTAPI @@ -53,18 +46,14 @@ NtRollforwardTransactionManager( _In_ HANDLE TransactionManagerHandle, _In_opt_ PLARGE_INTEGER TmVirtualClock ); -#endif -#if (PHNT_VERSION >= PHNT_WINDOWS_VISTA) NTSYSCALLAPI NTSTATUS NTAPI NtRecoverTransactionManager( _In_ HANDLE TransactionManagerHandle ); -#endif -#if (PHNT_VERSION >= PHNT_WINDOWS_VISTA) NTSYSCALLAPI NTSTATUS NTAPI @@ -75,9 +64,7 @@ NtQueryInformationTransactionManager( _In_ ULONG TransactionManagerInformationLength, _Out_opt_ PULONG ReturnLength ); -#endif -#if (PHNT_VERSION >= PHNT_WINDOWS_VISTA) NTSYSCALLAPI NTSTATUS NTAPI @@ -87,9 +74,7 @@ NtSetInformationTransactionManager( _In_reads_bytes_(TransactionManagerInformationLength) PVOID TransactionManagerInformation, _In_ ULONG TransactionManagerInformationLength ); -#endif -#if (PHNT_VERSION >= PHNT_WINDOWS_VISTA) NTSYSCALLAPI NTSTATUS NTAPI @@ -100,9 +85,7 @@ NtEnumerateTransactionObject( _In_ ULONG ObjectCursorLength, _Out_ PULONG ReturnLength ); -#endif -#if (PHNT_VERSION >= PHNT_WINDOWS_VISTA) NTSYSCALLAPI NTSTATUS NTAPI @@ -116,11 +99,9 @@ NtCreateTransaction( _In_opt_ ULONG IsolationLevel, _In_opt_ ULONG IsolationFlags, _In_opt_ PLARGE_INTEGER Timeout, - _In_opt_ PUNICODE_STRING Description + _In_opt_ PCUNICODE_STRING Description ); -#endif -#if (PHNT_VERSION >= PHNT_WINDOWS_VISTA) NTSYSCALLAPI NTSTATUS NTAPI @@ -131,9 +112,7 @@ NtOpenTransaction( _In_ LPGUID Uow, _In_opt_ HANDLE TmHandle ); -#endif -#if (PHNT_VERSION >= PHNT_WINDOWS_VISTA) NTSYSCALLAPI NTSTATUS NTAPI @@ -144,9 +123,7 @@ NtQueryInformationTransaction( _In_ ULONG TransactionInformationLength, _Out_opt_ PULONG ReturnLength ); -#endif -#if (PHNT_VERSION >= PHNT_WINDOWS_VISTA) NTSYSCALLAPI NTSTATUS NTAPI @@ -156,9 +133,7 @@ NtSetInformationTransaction( _In_reads_bytes_(TransactionInformationLength) PVOID TransactionInformation, _In_ ULONG TransactionInformationLength ); -#endif -#if (PHNT_VERSION >= PHNT_WINDOWS_VISTA) NTSYSCALLAPI NTSTATUS NTAPI @@ -166,9 +141,7 @@ NtCommitTransaction( _In_ HANDLE TransactionHandle, _In_ BOOLEAN Wait ); -#endif -#if (PHNT_VERSION >= PHNT_WINDOWS_VISTA) NTSYSCALLAPI NTSTATUS NTAPI @@ -176,9 +149,7 @@ NtRollbackTransaction( _In_ HANDLE TransactionHandle, _In_ BOOLEAN Wait ); -#endif -#if (PHNT_VERSION >= PHNT_WINDOWS_VISTA) NTSYSCALLAPI NTSTATUS NTAPI @@ -192,9 +163,7 @@ NtCreateEnlistment( _In_ NOTIFICATION_MASK NotificationMask, _In_opt_ PVOID EnlistmentKey ); -#endif -#if (PHNT_VERSION >= PHNT_WINDOWS_VISTA) NTSYSCALLAPI NTSTATUS NTAPI @@ -205,9 +174,7 @@ NtOpenEnlistment( _In_ LPGUID EnlistmentGuid, _In_opt_ POBJECT_ATTRIBUTES ObjectAttributes ); -#endif -#if (PHNT_VERSION >= PHNT_WINDOWS_VISTA) NTSYSCALLAPI NTSTATUS NTAPI @@ -218,9 +185,7 @@ NtQueryInformationEnlistment( _In_ ULONG EnlistmentInformationLength, _Out_opt_ PULONG ReturnLength ); -#endif -#if (PHNT_VERSION >= PHNT_WINDOWS_VISTA) NTSYSCALLAPI NTSTATUS NTAPI @@ -230,9 +195,7 @@ NtSetInformationEnlistment( _In_reads_bytes_(EnlistmentInformationLength) PVOID EnlistmentInformation, _In_ ULONG EnlistmentInformationLength ); -#endif -#if (PHNT_VERSION >= PHNT_WINDOWS_VISTA) NTSYSCALLAPI NTSTATUS NTAPI @@ -240,9 +203,7 @@ NtRecoverEnlistment( _In_ HANDLE EnlistmentHandle, _In_opt_ PVOID EnlistmentKey ); -#endif -#if (PHNT_VERSION >= PHNT_WINDOWS_VISTA) NTSYSCALLAPI NTSTATUS NTAPI @@ -250,9 +211,7 @@ NtPrePrepareEnlistment( _In_ HANDLE EnlistmentHandle, _In_opt_ PLARGE_INTEGER TmVirtualClock ); -#endif -#if (PHNT_VERSION >= PHNT_WINDOWS_VISTA) NTSYSCALLAPI NTSTATUS NTAPI @@ -260,9 +219,7 @@ NtPrepareEnlistment( _In_ HANDLE EnlistmentHandle, _In_opt_ PLARGE_INTEGER TmVirtualClock ); -#endif -#if (PHNT_VERSION >= PHNT_WINDOWS_VISTA) NTSYSCALLAPI NTSTATUS NTAPI @@ -270,9 +227,7 @@ NtCommitEnlistment( _In_ HANDLE EnlistmentHandle, _In_opt_ PLARGE_INTEGER TmVirtualClock ); -#endif -#if (PHNT_VERSION >= PHNT_WINDOWS_VISTA) NTSYSCALLAPI NTSTATUS NTAPI @@ -280,9 +235,7 @@ NtRollbackEnlistment( _In_ HANDLE EnlistmentHandle, _In_opt_ PLARGE_INTEGER TmVirtualClock ); -#endif -#if (PHNT_VERSION >= PHNT_WINDOWS_VISTA) NTSYSCALLAPI NTSTATUS NTAPI @@ -290,9 +243,7 @@ NtPrePrepareComplete( _In_ HANDLE EnlistmentHandle, _In_opt_ PLARGE_INTEGER TmVirtualClock ); -#endif -#if (PHNT_VERSION >= PHNT_WINDOWS_VISTA) NTSYSCALLAPI NTSTATUS NTAPI @@ -300,9 +251,7 @@ NtPrepareComplete( _In_ HANDLE EnlistmentHandle, _In_opt_ PLARGE_INTEGER TmVirtualClock ); -#endif -#if (PHNT_VERSION >= PHNT_WINDOWS_VISTA) NTSYSCALLAPI NTSTATUS NTAPI @@ -310,9 +259,7 @@ NtCommitComplete( _In_ HANDLE EnlistmentHandle, _In_opt_ PLARGE_INTEGER TmVirtualClock ); -#endif -#if (PHNT_VERSION >= PHNT_WINDOWS_VISTA) NTSYSCALLAPI NTSTATUS NTAPI @@ -320,9 +267,7 @@ NtReadOnlyEnlistment( _In_ HANDLE EnlistmentHandle, _In_opt_ PLARGE_INTEGER TmVirtualClock ); -#endif -#if (PHNT_VERSION >= PHNT_WINDOWS_VISTA) NTSYSCALLAPI NTSTATUS NTAPI @@ -330,9 +275,7 @@ NtRollbackComplete( _In_ HANDLE EnlistmentHandle, _In_opt_ PLARGE_INTEGER TmVirtualClock ); -#endif -#if (PHNT_VERSION >= PHNT_WINDOWS_VISTA) NTSYSCALLAPI NTSTATUS NTAPI @@ -340,9 +283,7 @@ NtSinglePhaseReject( _In_ HANDLE EnlistmentHandle, _In_opt_ PLARGE_INTEGER TmVirtualClock ); -#endif -#if (PHNT_VERSION >= PHNT_WINDOWS_VISTA) NTSYSCALLAPI NTSTATUS NTAPI @@ -353,11 +294,9 @@ NtCreateResourceManager( _In_ LPGUID RmGuid, _In_opt_ POBJECT_ATTRIBUTES ObjectAttributes, _In_opt_ ULONG CreateOptions, - _In_opt_ PUNICODE_STRING Description + _In_opt_ PCUNICODE_STRING Description ); -#endif -#if (PHNT_VERSION >= PHNT_WINDOWS_VISTA) NTSYSCALLAPI NTSTATUS NTAPI @@ -368,18 +307,14 @@ NtOpenResourceManager( _In_opt_ LPGUID ResourceManagerGuid, _In_opt_ POBJECT_ATTRIBUTES ObjectAttributes ); -#endif -#if (PHNT_VERSION >= PHNT_WINDOWS_VISTA) NTSYSCALLAPI NTSTATUS NTAPI NtRecoverResourceManager( _In_ HANDLE ResourceManagerHandle ); -#endif -#if (PHNT_VERSION >= PHNT_WINDOWS_VISTA) NTSYSCALLAPI NTSTATUS NTAPI @@ -392,9 +327,7 @@ NtGetNotificationResourceManager( _In_ ULONG Asynchronous, _In_opt_ ULONG_PTR AsynchronousContext ); -#endif -#if (PHNT_VERSION >= PHNT_WINDOWS_VISTA) NTSYSCALLAPI NTSTATUS NTAPI @@ -405,9 +338,7 @@ NtQueryInformationResourceManager( _In_ ULONG ResourceManagerInformationLength, _Out_opt_ PULONG ReturnLength ); -#endif -#if (PHNT_VERSION >= PHNT_WINDOWS_VISTA) NTSYSCALLAPI NTSTATUS NTAPI @@ -417,9 +348,7 @@ NtSetInformationResourceManager( _In_reads_bytes_(ResourceManagerInformationLength) PVOID ResourceManagerInformation, _In_ ULONG ResourceManagerInformationLength ); -#endif -#if (PHNT_VERSION >= PHNT_WINDOWS_VISTA) NTSYSCALLAPI NTSTATUS NTAPI @@ -430,9 +359,7 @@ NtRegisterProtocolAddressInformation( _In_ PVOID ProtocolInformation, _In_opt_ ULONG CreateOptions ); -#endif -#if (PHNT_VERSION >= PHNT_WINDOWS_VISTA) NTSYSCALLAPI NTSTATUS NTAPI @@ -442,9 +369,7 @@ NtPropagationComplete( _In_ ULONG BufferLength, _In_ PVOID Buffer ); -#endif -#if (PHNT_VERSION >= PHNT_WINDOWS_VISTA) NTSYSCALLAPI NTSTATUS NTAPI @@ -453,10 +378,7 @@ NtPropagationFailed( _In_ ULONG RequestCookie, _In_ NTSTATUS PropStatus ); -#endif -#if (PHNT_VERSION >= PHNT_WINDOWS_VISTA) -// private NTSYSCALLAPI NTSTATUS NTAPI @@ -464,16 +386,12 @@ NtFreezeTransactions( _In_ PLARGE_INTEGER FreezeTimeout, _In_ PLARGE_INTEGER ThawTimeout ); -#endif -#if (PHNT_VERSION >= PHNT_WINDOWS_VISTA) -// private NTSYSCALLAPI NTSTATUS NTAPI NtThawTransactions( VOID ); -#endif -#endif +#endif // _NTTMAPI_H diff --git a/nttp.h b/nttp.h index ad99d3c..7d99d45 100644 --- a/nttp.h +++ b/nttp.h @@ -12,23 +12,48 @@ typedef struct _TP_ALPC TP_ALPC, *PTP_ALPC; // private -typedef VOID (NTAPI *PTP_ALPC_CALLBACK)( +/** + * Defines the callback function for ALPC completion notifications. + * + * \param[in,out] Instance A pointer to a TP_CALLBACK_INSTANCE structure that defines the callback instance. + * \param[in,out] Context Optional application-defined data specified when the ALPC completion object was created. + * \param[in] Alpc A pointer to the ALPC completion object. + */ +typedef _Function_class_(TP_ALPC_CALLBACK) +VOID NTAPI TP_ALPC_CALLBACK( _Inout_ PTP_CALLBACK_INSTANCE Instance, _Inout_opt_ PVOID Context, _In_ PTP_ALPC Alpc ); +typedef TP_ALPC_CALLBACK *PTP_ALPC_CALLBACK; // rev -typedef VOID (NTAPI *PTP_ALPC_CALLBACK_EX)( +/** + * Defines the extended callback function for ALPC completion notifications. + * + * \param[in,out] Instance A pointer to a TP_CALLBACK_INSTANCE structure that defines the callback instance. + * \param[in,out] Context Optional application-defined data specified when the ALPC completion object was created. + * \param[in] Alpc A pointer to the ALPC completion object. + * \param[in] ApcContext A pointer to additional APC context data for the completion callback. + */ +typedef _Function_class_(TP_ALPC_CALLBACK_EX) +VOID NTAPI TP_ALPC_CALLBACK_EX( _Inout_ PTP_CALLBACK_INSTANCE Instance, _Inout_opt_ PVOID Context, _In_ PTP_ALPC Alpc, _In_ PVOID ApcContext ); - -#if (PHNT_VERSION >= PHNT_WINDOWS_VISTA) +typedef TP_ALPC_CALLBACK_EX *PTP_ALPC_CALLBACK_EX; // winbase:CreateThreadpool +/** + * Allocates a new pool of threads to execute callbacks. + * + * \param[out] PoolReturn Pointer to a variable that receives the address of the newly allocated thread pool. + * \param[in] Reserved Reserved for future use. Must be NULL. + * \return NTSTATUS Successful or errant status. + * \sa https://learn.microsoft.com/en-us/windows/win32/api/threadpoolapiset/nf-threadpoolapiset-createthreadpool + */ NTSYSAPI NTSTATUS NTAPI @@ -38,6 +63,13 @@ TpAllocPool( ); // winbase:CloseThreadpool +/** + * Closes the specified thread pool. + * + * \param[in,out] Pool A pointer to a TP_POOL structure that defines the thread pool. + * \return NTSTATUS Successful or errant status. + * \sa https://learn.microsoft.com/en-us/windows/win32/api/threadpoolapiset/nf-threadpoolapiset-closethreadpool + */ NTSYSAPI VOID NTAPI @@ -46,6 +78,14 @@ TpReleasePool( ); // winbase:SetThreadpoolThreadMaximum +/** + * Sets the maximum number of threads that the specified thread pool can allocate to process callbacks. + * + * \param[in,out] Pool A pointer to a TP_POOL structure that defines the thread pool. + * \param[in] MaxThreads The maximum number of threads. + * \return NTSTATUS Successful or errant status. + * \sa https://learn.microsoft.com/en-us/windows/win32/api/threadpoolapiset/nf-threadpoolapiset-setthreadpoolthreadmaximum + */ NTSYSAPI VOID NTAPI @@ -55,6 +95,14 @@ TpSetPoolMaxThreads( ); // winbase:SetThreadpoolThreadMinimum +/** + * Sets the minimum number of threads that the specified thread pool must make available to process callbacks. + * + * \param[in,out] Pool A pointer to a TP_POOL structure that defines the thread pool. + * \param[in] MinThreads The minimum number of threads. + * \return NTSTATUS Successful or errant status. + * \sa https://learn.microsoft.com/en-us/windows/win32/api/threadpoolapiset/nf-threadpoolapiset-setthreadpoolthreadminimum + */ NTSYSAPI NTSTATUS NTAPI @@ -63,8 +111,15 @@ TpSetPoolMinThreads( _In_ ULONG MinThreads ); -#if (PHNT_VERSION >= PHNT_WINDOWS_7) // winbase:QueryThreadpoolStackInformation +/** + * Retrieves the stack reserve and commit sizes for threads in the specified thread pool. + * + * \param[in] Pool A pointer to a TP_POOL structure that defines the thread pool. + * \param[out] PoolStackInformation A pointer to a TP_POOL_STACK_INFORMATION structure that receives the stack reserve and commit size. + * \return NTSTATUS Successful or errant status. + * \sa https://learn.microsoft.com/en-us/windows/win32/api/threadpoolapiset/nf-threadpoolapiset-querythreadpoolstackinformation + */ NTSYSAPI NTSTATUS NTAPI @@ -74,6 +129,14 @@ TpQueryPoolStackInformation( ); // winbase:SetThreadpoolStackInformation +/** + * Sets the stack reserve and commit sizes for threads in the specified thread pool. + * + * \param[in,out] Pool A pointer to a TP_POOL structure that defines the thread pool. + * \param[in] PoolStackInformation A pointer to a TP_POOL_STACK_INFORMATION structure that specifies stack reserve and commit sizes. + * \return NTSTATUS Successful or errant status. + * \sa https://learn.microsoft.com/en-us/windows/win32/api/threadpoolapiset/nf-threadpoolapiset-setthreadpoolstackinformation + */ NTSYSAPI NTSTATUS NTAPI @@ -83,6 +146,13 @@ TpSetPoolStackInformation( ); // rev +/** + * Sets the base priority for worker threads in the specified thread pool. + * + * \param[in,out] Pool A pointer to a TP_POOL structure that defines the thread pool. + * \param[in] BasePriority The new base priority value for worker threads. + * \return NTSTATUS Successful or errant status. + */ NTSYSAPI NTSTATUS NTAPI @@ -90,17 +160,29 @@ TpSetPoolThreadBasePriority( _Inout_ PTP_POOL Pool, _In_ ULONG BasePriority ); -#endif // winbase:CreateThreadpoolCleanupGroup +/** + * Creates a cleanup group that applications can use to track one or more thread pool callbacks. + * + * \param[out] CleanupGroup A pointer to a TP_CLEANUP_GROUP structure of the newly allocated cleanup group. + * \return NTSTATUS Successful or errant status. + * \sa https://learn.microsoft.com/en-us/windows/win32/api/threadpoolapiset/nf-threadpoolapiset-createthreadpoolcleanupgroup + */ NTSYSAPI NTSTATUS NTAPI TpAllocCleanupGroup( - _Out_ PTP_CLEANUP_GROUP *CleanupGroupReturn + _Out_ PTP_CLEANUP_GROUP *CleanupGroup ); // winbase:CloseThreadpoolCleanupGroup +/** + * Closes the specified cleanup group. + * + * \param[in,out] CleanupGroup A pointer to a TP_CLEANUP_GROUP structure that defines the cleanup group. + * \sa https://learn.microsoft.com/en-us/windows/win32/api/threadpoolapiset/nf-threadpoolapiset-closethreadpoolcleanupgroup + */ NTSYSAPI VOID NTAPI @@ -109,6 +191,14 @@ TpReleaseCleanupGroup( ); // winbase:CloseThreadpoolCleanupGroupMembers +/** + * Releases the members of the specified cleanup group. + * + * \param[in,out] CleanupGroup A pointer to a TP_CLEANUP_GROUP structure that defines the cleanup group. + * \param[in] CancelPendingCallbacks If TRUE, pending callbacks that have not started are canceled. + * \param[in,out] CleanupParameter Optional application-defined context to pass to cleanup callbacks. + * \sa https://learn.microsoft.com/en-us/windows/win32/api/threadpoolapiset/nf-threadpoolapiset-closethreadpoolcleanupgroupmembers + */ NTSYSAPI VOID NTAPI @@ -119,6 +209,13 @@ TpReleaseCleanupGroupMembers( ); // winbase:SetEventWhenCallbackReturns +/** + * Sets an event object when the current callback function returns. + * + * \param[in,out] Instance A pointer to a TP_CALLBACK_INSTANCE structure that defines the callback instance. + * \param[in] Event A handle to an event object. + * \sa https://learn.microsoft.com/en-us/windows/win32/api/threadpoolapiset/nf-threadpoolapiset-seteventwhencallbackreturns + */ NTSYSAPI VOID NTAPI @@ -128,6 +225,14 @@ TpCallbackSetEventOnCompletion( ); // winbase:ReleaseSemaphoreWhenCallbackReturns +/** + * Releases a semaphore when the current callback function returns. + * + * \param[in,out] Instance A pointer to a TP_CALLBACK_INSTANCE structure that defines the callback instance. + * \param[in] Semaphore A handle to a semaphore object. + * \param[in] ReleaseCount The amount by which to increment the semaphore's current count. + * \sa https://learn.microsoft.com/en-us/windows/win32/api/threadpoolapiset/nf-threadpoolapiset-releasesemaphorewhencallbackreturns + */ NTSYSAPI VOID NTAPI @@ -138,6 +243,13 @@ TpCallbackReleaseSemaphoreOnCompletion( ); // winbase:ReleaseMutexWhenCallbackReturns +/** + * Releases a mutex when the current callback function returns. + * + * \param[in,out] Instance A pointer to a TP_CALLBACK_INSTANCE structure that defines the callback instance. + * \param[in] Mutex A handle to a mutex object. + * \sa https://learn.microsoft.com/en-us/windows/win32/api/threadpoolapiset/nf-threadpoolapiset-releasemutexwhencallbackreturns + */ NTSYSAPI VOID NTAPI @@ -147,6 +259,13 @@ TpCallbackReleaseMutexOnCompletion( ); // winbase:LeaveCriticalSectionWhenCallbackReturns +/** + * Leaves a critical section when the current callback function returns. + * + * \param[in,out] Instance A pointer to a TP_CALLBACK_INSTANCE structure that defines the callback instance. + * \param[in,out] CriticalSection A pointer to a critical section object. + * \sa https://learn.microsoft.com/en-us/windows/win32/api/threadpoolapiset/nf-threadpoolapiset-leavecriticalsectionwhencallbackreturns + */ NTSYSAPI VOID NTAPI @@ -156,6 +275,13 @@ TpCallbackLeaveCriticalSectionOnCompletion( ); // winbase:FreeLibraryWhenCallbackReturns +/** + * Frees the specified DLL when the current callback function returns. + * + * \param[in,out] Instance A pointer to a TP_CALLBACK_INSTANCE structure that defines the callback instance. + * \param[in] DllHandle A module handle for the DLL to unload. + * \sa https://learn.microsoft.com/en-us/windows/win32/api/threadpoolapiset/nf-threadpoolapiset-freelibrarywhencallbackreturns + */ NTSYSAPI VOID NTAPI @@ -165,6 +291,13 @@ TpCallbackUnloadDllOnCompletion( ); // winbase:CallbackMayRunLong +/** + * Indicates that the callback may not return quickly. + * + * \param[in,out] Instance A pointer to a TP_CALLBACK_INSTANCE structure that defines the callback instance. + * \return NTSTATUS Successful or errant status. + * \sa https://learn.microsoft.com/en-us/windows/win32/api/threadpoolapiset/nf-threadpoolapiset-callbackmayrunlong + */ NTSYSAPI NTSTATUS NTAPI @@ -173,6 +306,12 @@ TpCallbackMayRunLong( ); // winbase:DisassociateCurrentThreadFromCallback +/** + * Removes the association between the current thread and the callback instance. + * + * \param[in,out] Instance A pointer to a TP_CALLBACK_INSTANCE structure that defines the callback instance. + * \sa https://learn.microsoft.com/en-us/windows/win32/api/threadpoolapiset/nf-threadpoolapiset-disassociatecurrentthreadfromcallback + */ NTSYSAPI VOID NTAPI @@ -180,17 +319,51 @@ TpDisassociateCallback( _Inout_ PTP_CALLBACK_INSTANCE Instance ); +/** + * Defines the callback function that is executed by a thread pool worker thread. + * + * \param[in,out] Instance A pointer to a TP_CALLBACK_INSTANCE structure that defines the callback instance. + * \param[in,out] Context Optional application-defined data passed to the callback. + * \return None. + * \sa https://learn.microsoft.com/en-us/windows/win32/api/threadpoolapiset/nc-threadpoolapiset-ptp_simple_callback + */ +typedef _Function_class_(TP_CALLBACK_ROUTINE) +VOID NTAPI TP_CALLBACK_ROUTINE( + _Inout_ PTP_CALLBACK_INSTANCE Instance, + _Inout_opt_ PVOID Context + ); +typedef TP_CALLBACK_ROUTINE* PTP_CALLBACK_ROUTINE; + // winbase:TrySubmitThreadpoolCallback +/** + * Requests that a thread pool worker thread call the specified callback function. + * + * \param[in] Callback The callback function. + * \param[in,out] Context Optional application-defined data to pass to the callback function. + * \param[in] CallbackEnviron A pointer to a TP_CALLBACK_ENVIRON structure that defines the environment in which to execute the callback function. + * \return NTSTATUS Successful or errant status. + * \sa https://learn.microsoft.com/en-us/windows/win32/api/threadpoolapiset/nf-threadpoolapiset-trysubmitthreadpoolcallback + */ NTSYSAPI NTSTATUS NTAPI TpSimpleTryPost( - _In_ PTP_SIMPLE_CALLBACK Callback, + _In_ PTP_CALLBACK_ROUTINE Callback, _Inout_opt_ PVOID Context, _In_opt_ PTP_CALLBACK_ENVIRON CallbackEnviron ); // winbase:CreateThreadpoolWork +/** + * Allocates a work object. + * + * \param[out] WorkReturn A pointer to a variable that receives the new work object. + * \param[in] Callback The callback function to execute. + * \param[in,out] Context Optional application-defined data to pass to the callback function. + * \param[in] CallbackEnviron Optional callback environment for the callback. + * \return NTSTATUS Successful or errant status. + * \sa https://learn.microsoft.com/en-us/windows/win32/api/threadpoolapiset/nf-threadpoolapiset-createthreadpoolwork + */ NTSYSAPI NTSTATUS NTAPI @@ -202,6 +375,13 @@ TpAllocWork( ); // winbase:CloseThreadpoolWork +/** + * Closes the specified work object. + * + * \param[in,out] Work A pointer to a TP_WORK structure that defines the work object. + * \return None. + * \sa https://learn.microsoft.com/en-us/windows/win32/api/threadpoolapiset/nf-threadpoolapiset-closethreadpoolwork + */ NTSYSAPI VOID NTAPI @@ -210,6 +390,13 @@ TpReleaseWork( ); // winbase:SubmitThreadpoolWork +/** + * Submits a work object to the thread pool. + * + * \param[in,out] Work A pointer to a TP_WORK structure that defines the work object. + * \return None. + * \sa https://learn.microsoft.com/en-us/windows/win32/api/threadpoolapiset/nf-threadpoolapiset-submitthreadpoolwork + */ NTSYSAPI VOID NTAPI @@ -218,6 +405,14 @@ TpPostWork( ); // winbase:WaitForThreadpoolWorkCallbacks +/** + * Waits for outstanding work callbacks to complete and optionally cancels pending callbacks. + * + * \param[in,out] Work A pointer to a TP_WORK structure that defines the work object. + * \param[in] CancelPendingCallbacks If TRUE, pending callbacks that have not started are canceled. + * \return None. + * \sa https://learn.microsoft.com/en-us/windows/win32/api/threadpoolapiset/nf-threadpoolapiset-waitforthreadpoolworkcallbacks + */ NTSYSAPI VOID NTAPI @@ -227,6 +422,16 @@ TpWaitForWork( ); // winbase:CreateThreadpoolTimer +/** + * Allocates a timer object. + * + * \param[out] Timer A pointer to a variable that receives the new timer object. + * \param[in] Callback The callback function to execute when the timer expires. + * \param[in,out] Context Optional application-defined data to pass to the callback function. + * \param[in] CallbackEnviron Optional callback environment for the callback. + * \return NTSTATUS Successful or errant status. + * \sa https://learn.microsoft.com/en-us/windows/win32/api/threadpoolapiset/nf-threadpoolapiset-createthreadpooltimer + */ NTSYSAPI NTSTATUS NTAPI @@ -238,6 +443,12 @@ TpAllocTimer( ); // winbase:CloseThreadpoolTimer +/** + * Closes the specified timer object. + * + * \param[in,out] Timer A pointer to a TP_TIMER structure that defines the timer object. + * \sa https://learn.microsoft.com/en-us/windows/win32/api/threadpoolapiset/nf-threadpoolapiset-closethreadpooltimer + */ NTSYSAPI VOID NTAPI @@ -246,6 +457,16 @@ TpReleaseTimer( ); // winbase:SetThreadpoolTimer +/** + * Sets the due time and periodic interval for the specified timer object. + * + * \param[in,out] Timer A pointer to a TP_TIMER structure that defines the timer object. + * \param[in] DueTime A pointer to a FILETIME-based value that specifies when the timer expires. + * \param[in] Period The period, in milliseconds, for periodic timer callbacks. + * \param[in] WindowLength The maximum amount of time, in milliseconds, that can elapse before the timer callback is invoked. + * \return None. + * \sa https://learn.microsoft.com/en-us/windows/win32/api/threadpoolapiset/nf-threadpoolapiset-setthreadpooltimer + */ NTSYSAPI VOID NTAPI @@ -258,6 +479,16 @@ TpSetTimer( #if (PHNT_VERSION >= PHNT_WINDOWS_8) // winbase:SetThreadpoolTimerEx +/** + * Sets the due time and periodic interval for the specified timer object and returns status. + * + * \param[in,out] Timer A pointer to a TP_TIMER structure that defines the timer object. + * \param[in] DueTime A pointer to a FILETIME-based value that specifies when the timer expires. + * \param[in] Period The period, in milliseconds, for periodic timer callbacks. + * \param[in] WindowLength The maximum amount of time, in milliseconds, that can elapse before the timer callback is invoked. + * \return NTSTATUS Successful or errant status. + * \sa https://learn.microsoft.com/en-us/windows/win32/api/threadpoolapiset/nf-threadpoolapiset-setthreadpooltimerex + */ NTSYSAPI NTSTATUS NTAPI @@ -270,6 +501,13 @@ TpSetTimerEx( #endif // winbase:IsThreadpoolTimerSet +/** + * Determines whether a timer object is currently set. + * + * \param[in] Timer A pointer to a TP_TIMER structure that defines the timer object. + * \return LOGICAL TRUE if the timer is set; otherwise FALSE. + * \sa https://learn.microsoft.com/en-us/windows/win32/api/threadpoolapiset/nf-threadpoolapiset-isthreadpooltimerset + */ NTSYSAPI LOGICAL NTAPI @@ -278,6 +516,13 @@ TpIsTimerSet( ); // winbase:WaitForThreadpoolTimerCallbacks +/** + * Waits for outstanding timer callbacks to complete and optionally cancels pending callbacks. + * + * \param[in,out] Timer A pointer to a TP_TIMER structure that defines the timer object. + * \param[in] CancelPendingCallbacks If TRUE, pending callbacks that have not started are canceled. + * \sa https://learn.microsoft.com/en-us/windows/win32/api/threadpoolapiset/nf-threadpoolapiset-waitforthreadpooltimercallbacks + */ NTSYSAPI VOID NTAPI @@ -287,6 +532,16 @@ TpWaitForTimer( ); // winbase:CreateThreadpoolWait +/** + * Allocates a wait object. + * + * \param[out] WaitReturn A pointer to a variable that receives the new wait object. + * \param[in] Callback The callback function to execute when the wait is satisfied or times out. + * \param[in,out] Context Optional application-defined data to pass to the callback function. + * \param[in] CallbackEnviron Optional callback environment for the callback. + * \return NTSTATUS Successful or errant status. + * \sa https://learn.microsoft.com/en-us/windows/win32/api/threadpoolapiset/nf-threadpoolapiset-createthreadpoolwait + */ NTSYSAPI NTSTATUS NTAPI @@ -298,6 +553,12 @@ TpAllocWait( ); // winbase:CloseThreadpoolWait +/** + * Closes the specified wait object. + * + * \param[in,out] Wait A pointer to a TP_WAIT structure that defines the wait object. + * \sa https://learn.microsoft.com/en-us/windows/win32/api/threadpoolapiset/nf-threadpoolapiset-closethreadpoolwait + */ NTSYSAPI VOID NTAPI @@ -306,6 +567,14 @@ TpReleaseWait( ); // winbase:SetThreadpoolWait +/** + * Sets the object to wait on and optional timeout for a wait object. + * + * \param[in,out] Wait A pointer to a TP_WAIT structure that defines the wait object. + * \param[in] Handle A handle to the object to wait on. + * \param[in] Timeout A pointer to a FILETIME-based timeout value. + * \sa https://learn.microsoft.com/en-us/windows/win32/api/threadpoolapiset/nf-threadpoolapiset-setthreadpoolwait + */ NTSYSAPI VOID NTAPI @@ -317,6 +586,16 @@ TpSetWait( #if (PHNT_VERSION >= PHNT_WINDOWS_8) // winbase:SetThreadpoolWaitEx +/** + * Sets the object to wait on and optional timeout for a wait object and returns status. + * + * \param[in,out] Wait A pointer to a TP_WAIT structure that defines the wait object. + * \param[in] Handle A handle to the object to wait on. + * \param[in] Timeout A pointer to a FILETIME-based timeout value. + * \param[in] Reserved Reserved for future use. + * \return NTSTATUS Successful or errant status. + * \sa https://learn.microsoft.com/en-us/windows/win32/api/threadpoolapiset/nf-threadpoolapiset-setthreadpoolwaitex + */ NTSYSAPI NTSTATUS NTAPI @@ -329,6 +608,13 @@ TpSetWaitEx( #endif // winbase:WaitForThreadpoolWaitCallbacks +/** + * Waits for outstanding wait callbacks to complete and optionally cancels pending callbacks. + * + * \param[in,out] Wait A pointer to a TP_WAIT structure that defines the wait object. + * \param[in] CancelPendingCallbacks If TRUE, pending callbacks that have not started are canceled. + * \sa https://learn.microsoft.com/en-us/windows/win32/api/threadpoolapiset/nf-threadpoolapiset-waitforthreadpoolwaitcallbacks + */ NTSYSAPI VOID NTAPI @@ -338,15 +624,38 @@ TpWaitForWait( ); // private -typedef VOID (NTAPI *PTP_IO_CALLBACK)( +/** + * Defines the callback function for asynchronous I/O completion callbacks. + * + * \param[in,out] Instance A pointer to a TP_CALLBACK_INSTANCE structure that defines the callback instance. + * \param[in,out] Context Optional application-defined data passed to the callback. + * \param[in] ApcContext A pointer to the asynchronous procedure call (APC) context. + * \param[in] IoSB A pointer to an IO_STATUS_BLOCK structure that contains the final I/O status. + * \param[in] Io A pointer to the I/O completion object. + * \sa https://learn.microsoft.com/en-us/windows/win32/api/threadpoolapiset/nc-threadpoolapiset-ptp_win32_io_callback + */ +typedef _Function_class_(TP_IO_CALLBACK) +VOID NTAPI TP_IO_CALLBACK( _Inout_ PTP_CALLBACK_INSTANCE Instance, _Inout_opt_ PVOID Context, _In_ PVOID ApcContext, _In_ PIO_STATUS_BLOCK IoSB, _In_ PTP_IO Io ); +typedef TP_IO_CALLBACK *PTP_IO_CALLBACK; // winbase:CreateThreadpoolIo +/** + * Allocates an I/O completion object associated with a file handle. + * + * \param[out] IoReturn A pointer to a variable that receives the new I/O completion object. + * \param[in] File A file handle associated with an I/O completion port. + * \param[in] Callback The callback function to execute when asynchronous I/O completes. + * \param[in,out] Context Optional application-defined data to pass to the callback function. + * \param[in] CallbackEnviron Optional callback environment for the callback. + * \return NTSTATUS Successful or errant status. + * \sa https://learn.microsoft.com/en-us/windows/win32/api/threadpoolapiset/nf-threadpoolapiset-createthreadpoolio + */ NTSYSAPI NTSTATUS NTAPI @@ -359,6 +668,12 @@ TpAllocIoCompletion( ); // winbase:CloseThreadpoolIo +/** + * Closes the specified I/O completion object. + * + * \param[in,out] Io A pointer to a TP_IO structure that defines the I/O completion object. + * \sa https://learn.microsoft.com/en-us/windows/win32/api/threadpoolapiset/nf-threadpoolapiset-closethreadpoolio + */ NTSYSAPI VOID NTAPI @@ -367,6 +682,12 @@ TpReleaseIoCompletion( ); // winbase:StartThreadpoolIo +/** + * Marks the start of one or more asynchronous I/O operations on the I/O completion object. + * + * \param[in,out] Io A pointer to a TP_IO structure that defines the I/O completion object. + * \sa https://learn.microsoft.com/en-us/windows/win32/api/threadpoolapiset/nf-threadpoolapiset-startthreadpoolio + */ NTSYSAPI VOID NTAPI @@ -375,6 +696,12 @@ TpStartAsyncIoOperation( ); // winbase:CancelThreadpoolIo +/** + * Cancels callbacks for outstanding asynchronous I/O operations. + * + * \param[in,out] Io A pointer to a TP_IO structure that defines the I/O completion object. + * \sa https://learn.microsoft.com/en-us/windows/win32/api/threadpoolapiset/nf-threadpoolapiset-cancelthreadpoolio + */ NTSYSAPI VOID NTAPI @@ -383,6 +710,13 @@ TpCancelAsyncIoOperation( ); // winbase:WaitForThreadpoolIoCallbacks +/** + * Waits for outstanding I/O callbacks to complete and optionally cancels pending callbacks. + * + * \param[in,out] Io A pointer to a TP_IO structure that defines the I/O completion object. + * \param[in] CancelPendingCallbacks If TRUE, pending callbacks that have not started are canceled. + * \sa https://learn.microsoft.com/en-us/windows/win32/api/threadpoolapiset/nf-threadpoolapiset-waitforthreadpooliocallbacks + */ NTSYSAPI VOID NTAPI @@ -392,6 +726,16 @@ TpWaitForIoCompletion( ); // private +/** + * Allocates an ALPC completion object. + * + * \param[out] AlpcReturn A pointer to a variable that receives the new ALPC completion object. + * \param[in] AlpcPort A handle to an ALPC port. + * \param[in] Callback The callback function to execute for ALPC completions. + * \param[in,out] Context Optional application-defined data to pass to the callback function. + * \param[in] CallbackEnviron Optional callback environment for the callback. + * \return NTSTATUS Successful or errant status. + */ NTSYSAPI NTSTATUS NTAPI @@ -403,8 +747,17 @@ TpAllocAlpcCompletion( _In_opt_ PTP_CALLBACK_ENVIRON CallbackEnviron ); -#if (PHNT_VERSION >= PHNT_WINDOWS_7) // rev +/** + * Allocates an ALPC completion object with extended callback context. + * + * \param[out] AlpcReturn A pointer to a variable that receives the new ALPC completion object. + * \param[in] AlpcPort A handle to an ALPC port. + * \param[in] Callback The extended callback function to execute for ALPC completions. + * \param[in,out] Context Optional application-defined data to pass to the callback function. + * \param[in] CallbackEnviron Optional callback environment for the callback. + * \return NTSTATUS Successful or errant status. + */ NTSYSAPI NTSTATUS NTAPI @@ -415,9 +768,13 @@ TpAllocAlpcCompletionEx( _Inout_opt_ PVOID Context, _In_opt_ PTP_CALLBACK_ENVIRON CallbackEnviron ); -#endif // private +/** + * Releases an ALPC completion object. + * + * \param[in,out] Alpc A pointer to a TP_ALPC structure that defines the ALPC completion object. + */ NTSYSAPI VOID NTAPI @@ -426,6 +783,11 @@ TpReleaseAlpcCompletion( ); // private +/** + * Waits for ALPC completion processing to finish. + * + * \param[in,out] Alpc A pointer to a TP_ALPC structure that defines the ALPC completion object. + */ NTSYSAPI VOID NTAPI @@ -434,6 +796,11 @@ TpWaitForAlpcCompletion( ); // rev +/** + * Registers the ALPC completion list for the specified ALPC completion object. + * + * \param[in,out] Alpc A pointer to a TP_ALPC structure that defines the ALPC completion object. + */ NTSYSAPI VOID NTAPI @@ -442,6 +809,12 @@ TpAlpcRegisterCompletionList( ); // rev +/** + * Unregisters the ALPC completion list for the specified ALPC completion object. + * + * \param[in,out] Alpc A pointer to a TP_ALPC structure that defines the ALPC completion object. + * \return None. + */ NTSYSAPI VOID NTAPI @@ -458,6 +831,12 @@ typedef enum _TP_TRACE_TYPE } TP_TRACE_TYPE; // private +/** + * Captures caller context for thread pool tracing. + * + * \param[in] Type The trace operation type. + * \return None. + */ NTSYSAPI VOID NTAPI @@ -466,6 +845,12 @@ TpCaptureCaller( ); // private +/** + * Checks whether a worker thread should terminate. + * + * \param[in] Thread A handle to the worker thread. + * \return None. + */ NTSYSAPI VOID NTAPI @@ -473,6 +858,4 @@ TpCheckTerminateWorker( _In_ HANDLE Thread ); -#endif - -#endif +#endif // _NTTP_H diff --git a/nttypesafe.h b/nttypesafe.h new file mode 100644 index 0000000..0c66374 --- /dev/null +++ b/nttypesafe.h @@ -0,0 +1,566 @@ +/* + * Integer literal/constant support macros for typesafe integer types. + * + * This file is part of System Informer. + */ + +// +// Typed integer literal macros with MSVC compiler extensions and C99 portable fallbacks. +// +// MSVC: Employs Microsoft integer literal suffixes (i8/ui8, i16/ui16, i32/ui32, +// i64/ui64, i128/ui128) to enforce type correctness at compile time. +// Example: UINT16_C(42) produces a uint16_t constant. +// +// Non-MSVC: Standard typed literal syntax unavailable. Macros are pass-through for +// smaller types (relying on type inference) or use standard C suffixes +// (U, ULL, LL) for larger types. Trade-off: reduced type checking; casts +// may suppress compile-time diagnostics for overflow/truncation. +// +// Naming: "_C" suffix conforms to C99 conventions (INT32_C, UINT64_C, etc.) +// +// Organization (sorted by size, then logical grouping): +// +// 1. Boolean type - (1 byte) (C89/C99) +// 2. Character types - (1-2 bytes) (C89/C99) +// 3. Short types - (2 bytes) (C89/C99) +// 4. Half-pointer types - (2-4 bytes) (Windows-specific) +// 5. Int types - (4 bytes) (C89/C99) +// 6. Long types - (4-8 bytes) (C89/C99) +// 7. Floating-point types - (4-8 bytes) (C89/C99) +// 8. NT cardinal types - (2-4 bytes) (Windows NT-specific) +// 9. Pointer-sized types - (4-8 bytes) (C99 + platform-dependent) +// 10. Standard C99 fixed-width types - (1-8 bytes) (C99 core) +// 11. Windows-specific types - (1-8 bytes) (Windows API) +// 12. 128-bit integer types - (16 bytes) (MSVC extension) + +#ifndef _NTTYPESAFE_H_INCLUDED_ +#define _NTTYPESAFE_H_INCLUDED_ + +#include + +// +// Boolean type - (1 byte) (C89/C99) +// + +#ifndef BOOLEAN_C +#if defined(_MSC_VER) +#define BOOLEAN_C(x) (x##ui8) +#else +#define BOOLEAN_C(x) (x) +#endif +#endif + +// +// Character types - (1-2 bytes) (C89/C99) +// + +#ifndef CHAR_C +#if defined(_MSC_VER) +#define CHAR_C(x) (x##i8) +#else +#define CHAR_C(x) (x) +#endif +#endif + +#ifndef CCHAR_C +#if defined(_MSC_VER) +#define CCHAR_C(x) (x##i8) +#else +#define CCHAR_C(x) (x) +#endif +#endif + +#ifndef UCHAR_C +#if defined(_MSC_VER) +#define UCHAR_C(x) (x##ui8) +#else +#define UCHAR_C(x) (x) +#endif +#endif + +#ifndef WCHAR_C +#if defined(_MSC_VER) +#define WCHAR_C(x) (x##ui16) +#else +#define WCHAR_C(x) (x) +#endif +#endif + +// +// Short types - (2 bytes) (C89/C99) +// + +#ifndef SHORT_C +#if defined(_MSC_VER) +#define SHORT_C(x) (x##i16) +#else +#define SHORT_C(x) (x) +#endif +#endif + +#ifndef USHORT_C +#if defined(_MSC_VER) +#define USHORT_C(x) (x##ui16) +#else +#define USHORT_C(x) (x) +#endif +#endif + +#ifndef WORD_C +#if defined(_MSC_VER) +#define WORD_C(x) (x##ui16) +#else +#define WORD_C(x) (x) +#endif +#endif + +// +// Half-pointer types - (2-4 bytes) (Windows-specific) +// 32-bit on 64-bit platforms, 16-bit on 32-bit platforms +// + +#ifndef HALF_PTR_C +#ifdef _WIN64 +#if defined(_MSC_VER) +#define HALF_PTR_C(x) (x##i32) +#else +#define HALF_PTR_C(x) (x) +#endif +#else +#if defined(_MSC_VER) +#define HALF_PTR_C(x) (x##i16) +#else +#define HALF_PTR_C(x) (x) +#endif +#endif +#endif + +#ifndef UHALF_PTR_C +#ifdef _WIN64 +#if defined(_MSC_VER) +#define UHALF_PTR_C(x) (x##ui32) +#else +#define UHALF_PTR_C(x) (x##U) +#endif +#else +#if defined(_MSC_VER) +#define UHALF_PTR_C(x) (x##ui16) +#else +#define UHALF_PTR_C(x) (x) +#endif +#endif +#endif + +#ifndef PHALF_PTR_C +#ifdef _WIN64 +#if defined(_MSC_VER) +#define PHALF_PTR_C(x) (x##i32) +#else +#define PHALF_PTR_C(x) (x) +#endif +#else +#if defined(_MSC_VER) +#define PHALF_PTR_C(x) (x##i16) +#else +#define PHALF_PTR_C(x) (x) +#endif +#endif +#endif + +#ifndef PUHALF_PTR_C +#ifdef _WIN64 +#if defined(_MSC_VER) +#define PUHALF_PTR_C(x) (x##ui32) +#else +#define PUHALF_PTR_C(x) (x##U) +#endif +#else +#if defined(_MSC_VER) +#define PUHALF_PTR_C(x) (x##ui16) +#else +#define PUHALF_PTR_C(x) (x) +#endif +#endif +#endif + +// +// Int types - (4 bytes) (C89/C99) +// + +#ifndef INT_C +#if defined(_MSC_VER) +#define INT_C(x) (x##i32) +#else +#define INT_C(x) (x) +#endif +#endif + +#ifndef UINT_C +#if defined(_MSC_VER) +#define UINT_C(x) (x##ui32) +#else +#define UINT_C(x) (x##U) +#endif +#endif + +// +// Long types - (4-8 bytes) (C89/C99) +// + +#ifndef LONG_C +#if defined(_MSC_VER) +#define LONG_C(x) (x##i32) +#else +#define LONG_C(x) (x) +#endif +#endif + +#ifndef LONG32_C +#if defined(_MSC_VER) +#define LONG32_C(x) (x##i32) +#else +#define LONG32_C(x) (x) +#endif +#endif + +#ifndef LONG64_C +#if defined(_MSC_VER) +#define LONG64_C(x) (x##i64) +#else +#define LONG64_C(x) (x##LL) +#endif +#endif + +#ifndef LONGLONG_C +#if defined(_MSC_VER) +#define LONGLONG_C(x) (x##i64) +#else +#define LONGLONG_C(x) (x##LL) +#endif +#endif + +#ifndef ULONG_C +#if defined(_MSC_VER) +#define ULONG_C(x) (x##ui32) +#else +#define ULONG_C(x) (x##U) +#endif +#endif + +#ifndef ULONG32_C +#if defined(_MSC_VER) +#define ULONG32_C(x) (x##ui32) +#else +#define ULONG32_C(x) (x##U) +#endif +#endif + +#ifndef ULONG64_C +#if defined(_MSC_VER) +#define ULONG64_C(x) (x##ui64) +#else +#define ULONG64_C(x) (x##ULL) +#endif +#endif + +#ifndef ULONGLONG_C +#if defined(_MSC_VER) +#define ULONGLONG_C(x) (x##ui64) +#else +#define ULONGLONG_C(x) (x##ULL) +#endif +#endif + +// +// Floating-point types - (4-8 bytes) (C89/C99) +// + +#ifndef FLOAT_C +#define FLOAT_C(x) (x##f) +#endif + +#ifndef DOUBLE_C +#if defined(_MSC_VER) +#define DOUBLE_C(x) (x##.0) +#else +#define DOUBLE_C(x) (x) +#endif +#endif + +// +// NT cardinal types - (2-4 bytes) (Windows NT-specific) +// Counted/cardinal types from NT native subsystem with 'C' prefix +// + +#ifndef CSHORT_C +#if defined(_MSC_VER) +#define CSHORT_C(x) (x##i16) +#else +#define CSHORT_C(x) (x) +#endif +#endif + +#ifndef CLONG_C +#if defined(_MSC_VER) +#define CLONG_C(x) (x##ui32) +#else +#define CLONG_C(x) (x##U) +#endif +#endif + +#ifndef LOGICAL_C +#if defined(_MSC_VER) +#define LOGICAL_C(x) (x##ui32) +#else +#define LOGICAL_C(x) (x##U) +#endif +#endif + +// +// Pointer-sized types - (4-8 bytes) (C99 + platform-dependent) +// Vary between 32-bit and 64-bit platforms +// + +#ifndef INT_PTR_C +#ifdef _WIN64 +#if defined(_MSC_VER) +#define INT_PTR_C(x) (x##i64) +#else +#define INT_PTR_C(x) (x##LL) +#endif +#else +#if defined(_MSC_VER) +#define INT_PTR_C(x) (x##i32) +#else +#define INT_PTR_C(x) (x) +#endif +#endif +#endif + +#ifndef UINT_PTR_C +#ifdef _WIN64 +#if defined(_MSC_VER) +#define UINT_PTR_C(x) (x##ui64) +#else +#define UINT_PTR_C(x) (x##ULL) +#endif +#else +#if defined(_MSC_VER) +#define UINT_PTR_C(x) (x##ui32) +#else +#define UINT_PTR_C(x) (x##U) +#endif +#endif +#endif + +#ifndef LONG_PTR_C +#ifdef _WIN64 +#if defined(_MSC_VER) +#define LONG_PTR_C(x) (x##i64) +#else +#define LONG_PTR_C(x) (x##LL) +#endif +#else +#if defined(_MSC_VER) +#define LONG_PTR_C(x) (x##i32) +#else +#define LONG_PTR_C(x) (x) +#endif +#endif +#endif + +#ifndef ULONG_PTR_C +#ifdef _WIN64 +#if defined(_MSC_VER) +#define ULONG_PTR_C(x) (x##ui64) +#else +#define ULONG_PTR_C(x) (x##ULL) +#endif +#else +#if defined(_MSC_VER) +#define ULONG_PTR_C(x) (x##ui32) +#else +#define ULONG_PTR_C(x) (x##U) +#endif +#endif +#endif + +#ifndef SIZE_T_C +#ifdef _WIN64 +#if defined(_MSC_VER) +#define SIZE_T_C(x) (x##ui64) +#else +#define SIZE_T_C(x) (x##ULL) +#endif +#else +#if defined(_MSC_VER) +#define SIZE_T_C(x) (x##ui32) +#else +#define SIZE_T_C(x) (x##U) +#endif +#endif +#endif + +#ifndef SSIZE_T_C +#ifdef _WIN64 +#if defined(_MSC_VER) +#define SSIZE_T_C(x) (x##i64) +#else +#define SSIZE_T_C(x) (x##LL) +#endif +#else +#if defined(_MSC_VER) +#define SSIZE_T_C(x) (x##i32) +#else +#define SSIZE_T_C(x) (x) +#endif +#endif +#endif + +#ifndef PTRDIFF_T_C +#ifdef _WIN64 +#if defined(_MSC_VER) +#define PTRDIFF_T_C(x) (x##i64) +#else +#define PTRDIFF_T_C(x) (x##LL) +#endif +#else +#if defined(_MSC_VER) +#define PTRDIFF_T_C(x) (x##i32) +#else +#define PTRDIFF_T_C(x) (x) +#endif +#endif +#endif + +// +// Standard C99 fixed-width integer types - (1-8 bytes) (C99 core) +// Redefine with MSVC extensions for better type safety +// + +#undef INT8_C +#undef UINT8_C +#undef INT16_C +#undef UINT16_C +#undef INT32_C +#undef UINT32_C +#undef INT64_C +#undef UINT64_C +#undef INTMAX_C +#undef UINTMAX_C + +#if defined(_MSC_VER) +#define INT8_C(x) (x##i8) +#define UINT8_C(x) (x##ui8) +#define INT16_C(x) (x##i16) +#define UINT16_C(x) (x##ui16) +#define INT32_C(x) (x##i32) +#define UINT32_C(x) (x##ui32) +#define INT64_C(x) (x##i64) +#define UINT64_C(x) (x##ui64) +#define INTMAX_C(x) (x##i64) +#define UINTMAX_C(x) (x##ui64) +#else +#define INT8_C(x) (x) +#define UINT8_C(x) (x) +#define INT16_C(x) (x) +#define UINT16_C(x) (x) +#define INT32_C(x) (x) +#define UINT32_C(x) (x##U) +#define INT64_C(x) (x##LL) +#define UINT64_C(x) (x##ULL) +#define INTMAX_C(x) (x##LL) +#define UINTMAX_C(x) (x##ULL) +#endif + +// +// Windows-specific types - (1-8 bytes) (Windows API) +// + +#ifndef BYTE_C +#if defined(_MSC_VER) +#define BYTE_C(x) (x##ui8) +#else +#define BYTE_C(x) (x) +#endif +#endif + +#ifndef DWORD_C +#if defined(_MSC_VER) +#define DWORD_C(x) (x##ui32) +#else +#define DWORD_C(x) (x##U) +#endif +#endif + +#ifndef DWORD32_C +#if defined(_MSC_VER) +#define DWORD32_C(x) (x##ui32) +#else +#define DWORD32_C(x) (x##U) +#endif +#endif + +#ifndef DWORD64_C +#if defined(_MSC_VER) +#define DWORD64_C(x) (x##ui64) +#else +#define DWORD64_C(x) (x##ULL) +#endif +#endif + +#ifndef DWORDLONG_C +#if defined(_MSC_VER) +#define DWORDLONG_C(x) (x##ui64) +#else +#define DWORDLONG_C(x) (x##ULL) +#endif +#endif + +#ifndef DWORD_PTR_C +#ifdef _WIN64 +#if defined(_MSC_VER) +#define DWORD_PTR_C(x) (x##ui64) +#else +#define DWORD_PTR_C(x) (x##ULL) +#endif +#else +#if defined(_MSC_VER) +#define DWORD_PTR_C(x) (x##ui32) +#else +#define DWORD_PTR_C(x) (x##U) +#endif +#endif +#endif + +#ifndef QWORD_C +#if defined(_MSC_VER) +#define QWORD_C(x) (x##ui64) +#else +#define QWORD_C(x) (x##ULL) +#endif +#endif + +// +// 128-bit integer types - (16 bytes) (MSVC extension) +// + +#ifndef INT128_C +#if defined(_MSC_VER) +#define INT128_C(x) (x##i128) +#else +// 128-bit literals not supported on non-MSVC, use cast as fallback +#define INT128_C(x) ((__int128)(x##LL)) +#endif +#endif + +#ifndef UINT128_C +#if defined(_MSC_VER) +#define UINT128_C(x) (x##ui128) +#else +// 128-bit literals not supported on non-MSVC, use cast as fallback +#define UINT128_C(x) ((unsigned __int128)(x##ULL)) +#endif +#endif + +#endif /* _NTTYPESAFE_H_INCLUDED_ */ diff --git a/ntuser.h b/ntuser.h index 5105fc5..a5c8e1f 100644 --- a/ntuser.h +++ b/ntuser.h @@ -33,14 +33,29 @@ NtUserBlockInput( _In_ BOOL BlockInput ); +#define FW_BOTH 0 +#define FW_16BIT 1 +#define FW_32BIT 2 + +NTSYSCALLAPI +HWND +NTAPI +NtUserFindWindowEx( + _In_opt_ HWND hwndParent, + _In_opt_ HWND hwndChild, + _In_ PCUNICODE_STRING ClassName, + _In_ PCUNICODE_STRING WindowName, + _In_ ULONG Type // FW_* + ); + NTSYSCALLAPI NTSTATUS NTAPI NtUserBuildHwndList( _In_opt_ HANDLE DesktopHandle, - _In_opt_ HWND StartWindowHandle, - _In_opt_ LOGICAL IncludeChildren, - _In_opt_ LOGICAL ExcludeImmersive, + _In_opt_ HWND ParentWindowHandle, + _In_opt_ BOOL IncludeChildren, + _In_opt_ BOOL ExcludeImmersive, _In_opt_ ULONG ThreadId, _In_ ULONG HwndListInformationLength, _Out_writes_bytes_(HwndListInformationLength) PVOID HwndListInformation, @@ -68,7 +83,7 @@ NtUserBuildPropList( ); NTSYSCALLAPI -LOGICAL +BOOL NTAPI NtUserCanCurrentThreadChangeForeground( VOID @@ -103,12 +118,58 @@ NtUserCheckProcessForClipboardAccess( ); NTSYSCALLAPI -LOGICAL +BOOL NTAPI NtUserCloseWindowStation( _In_ HWINSTA WindowStationHandle ); +#if (PHNT_VERSION >= PHNT_WINDOWS_8) +/** + * The NtUserDisableProcessWindowFiltering routine disables window filtering + * so you can enumerate immersive windows from the desktop. + * + * \return Successful or errant status. + * \sa https://learn.microsoft.com/en-us/windows/win32/sbscs/application-manifests#disableWindowFiltering + */ +NTSYSCALLAPI +BOOL +NTAPI +NtUserDisableProcessWindowFiltering( + VOID + ); +#endif + +NTSYSCALLAPI +HANDLE +NTAPI +NtUserGetProp( + _In_ HWND WindowHandle, + _In_ PCWSTR String + ); + +NTSYSCALLAPI +HANDLE +NTAPI +NtUserGetProp2( + _In_ HWND WindowHandle, + _In_ PCUNICODE_STRING String + ); + +NTSYSCALLAPI +NTSTATUS +NTAPI +NtUserCreateWindowStation( + _In_ POBJECT_ATTRIBUTES ObjectAttributes, + _In_ ACCESS_MASK DesiredAccess, + _In_opt_ HANDLE KeyboardLayoutHandle, + _In_opt_ PVOID KeyboardLayoutOffset, + _In_opt_ PVOID NlsTableOffset, + _In_opt_ PVOID KeyboardDescriptor, + _In_opt_ PCUNICODE_STRING LanguageIdString, + _In_opt_ ULONG KeyboardLocale + ); + typedef enum _CONSOLECONTROL { ConsoleSetVDMCursorBounds = 0, // RECT @@ -162,10 +223,10 @@ typedef struct _CONSOLEENDTASK * This includes reparenting the console window, allowing the console to pass foreground rights * on to launched console subsystem applications and terminating attached processes. * - * @param Command One of the CONSOLECONTROL values indicating which console control function should be executed. - * @param ConsoleInformation A pointer to one of the structures specifying additional data for the requested console control function. - * @param ConsoleInformationLength The size of the structure pointed to by the ConsoleInformation parameter. - * @return Successful or errant status. + * \param Command One of the CONSOLECONTROL values indicating which console control function should be executed. + * \param ConsoleInformation A pointer to one of the structures specifying additional data for the requested console control function. + * \param ConsoleInformationLength The size of the structure pointed to by the ConsoleInformation parameter. + * \return Successful or errant status. */ NTSYSCALLAPI NTSTATUS @@ -176,30 +237,16 @@ NtUserConsoleControl( _In_ ULONG ConsoleInformationLength ); -NTSYSCALLAPI -NTSTATUS -NTAPI -NtUserCreateWindowStation( - _In_ POBJECT_ATTRIBUTES ObjectAttributes, - _In_ ACCESS_MASK DesiredAccess, - _In_opt_ HANDLE KeyboardLayoutHandle, - _In_opt_ PVOID KeyboardLayoutOffset, - _In_opt_ PVOID NlsTableOffset, - _In_opt_ PVOID KeyboardDescriptor, - _In_opt_ PUNICODE_STRING LanguageIdString, - _In_opt_ ULONG KeyboardLocale - ); - /** * Performs special kernel operations for console host applications. (user32.dll) * * This includes reparenting the console window, allowing the console to pass foreground rights * on to launched console subsystem applications and terminating attached processes. * - * @param Command One of the CONSOLECONTROL values indicating which console control function should be executed. - * @param ConsoleInformation A pointer to one of the structures specifying additional data for the requested console control function. - * @param ConsoleInformationLength The size of the structure pointed to by the ConsoleInformation parameter. - * @return Successful or errant status. + * \param Command One of the CONSOLECONTROL values indicating which console control function should be executed. + * \param ConsoleInformation A pointer to one of the structures specifying additional data for the requested console control function. + * \param ConsoleInformationLength The size of the structure pointed to by the ConsoleInformation parameter. + * \return Successful or errant status. */ NTSYSAPI NTSTATUS @@ -210,15 +257,30 @@ ConsoleControl( _In_ ULONG ConsoleInformationLength ); +/** + * The NtUserGetClassName routine retrieves a string that specifies the window type. + * + * \param WindowHandle A handle to the window and, indirectly, the class to which the window belongs. + * \param RealClassName Return the superclass or baseclass name when the window is a superclass. + * \param ClassName A pointer to a string that receives the window type. + * \return A handle to the foreground window, or NULL if no foreground window exists. + * \sa https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-realgetwindowclassw + */ NTSYSCALLAPI -HWND +ULONG NTAPI NtUserGetClassName( _In_ HWND WindowHandle, - _In_ BOOL Real, + _In_ BOOL RealClassName, _Out_ PUNICODE_STRING ClassName ); +/** + * The NtUserGetForegroundWindow routine retrieves a handle to the foreground window. + * + * \return A handle to the foreground window, or NULL if no foreground window exists. + * \sa https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-getforegroundwindow + */ NTSYSCALLAPI HWND NTAPI @@ -227,7 +289,7 @@ NtUserGetForegroundWindow( ); NTSYSCALLAPI -LOGICAL +BOOL NTAPI NtUserGetIconInfo( _In_ HICON IconOrCursorHandle, @@ -239,7 +301,7 @@ NtUserGetIconInfo( ); NTSYSCALLAPI -LOGICAL +BOOL NTAPI NtUserGetIconSize( _In_ HGDIOBJ IconOrCursorHandle, @@ -248,13 +310,57 @@ NtUserGetIconSize( _Out_ PULONG YY ); +/** + * The NtUserGetProcessWindowStation routine retrieves the window station handle associated with the current process. + * + * \return A handle to the window station, or NULL if the operation fails. + * \sa https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-getprocesswindowstation + */ NTSYSCALLAPI -HWND +HWINSTA NTAPI NtUserGetProcessWindowStation( VOID ); +typedef enum _PROCESS_UICONTEXT +{ + PROCESS_UICONTEXT_DESKTOP, + PROCESS_UICONTEXT_IMMERSIVE, + PROCESS_UICONTEXT_IMMERSIVE_BROKER, + PROCESS_UICONTEXT_IMMERSIVE_BROWSER +} PROCESS_UICONTEXT; + +typedef enum _PROCESS_UI_FLAGS +{ + PROCESS_UIF_NONE, + PROCESS_UIF_AUTHORING_MODE, + PROCESS_UIF_RESTRICTIONS_DISABLED +} PROCESS_UI_FLAGS; +DEFINE_ENUM_FLAG_OPERATORS(PROCESS_UI_FLAGS); + +typedef struct _PROCESS_UICONTEXT_INFORMATION +{ + PROCESS_UICONTEXT ProcessUIContext; + PROCESS_UI_FLAGS Flags; +} PROCESS_UICONTEXT_INFORMATION, *PPROCESS_UICONTEXT_INFORMATION; + +NTSYSCALLAPI +NTSTATUS +NTAPI +NtUserGetProcessUIContextInformation( + _In_ HANDLE ProcessHandle, + _Out_ PPROCESS_UICONTEXT_INFORMATION UIContext + ); + +NTSYSCALLAPI +BOOL +NTAPI +GetProcessUIContextInformation( + _In_ HANDLE ProcessHandle, + _Out_ PPROCESS_UICONTEXT_INFORMATION UIContext + ); + NTSYSCALLAPI ULONG_PTR NTAPI @@ -319,9 +425,9 @@ NtUserOpenDesktop( /** * Opens the specified window station. * - * @param ObjectAttributes The name of the window station to be opened. Window station names are case-insensitive. This window station must belong to the current session. - * @param DesiredAccess The access to the window station. - * @return Successful or errant status. + * \param ObjectAttributes The name of the window station to be opened. Window station names are case-insensitive. This window station must belong to the current session. + * \param DesiredAccess The access to the window station. + * \return Successful or errant status. */ NTSYSCALLAPI HWINSTA @@ -376,7 +482,7 @@ NtUserSetFocus( // User32 ordinal 2005 NTSYSAPI -LOGICAL +BOOL NTAPI SetChildWindowNoActivate( _In_ HWND WindowHandle @@ -393,12 +499,92 @@ NtUserSetInformationThread( ); NTSYSCALLAPI -LOGICAL +BOOL NTAPI NtUserSetProcessWindowStation( _In_ HWINSTA WindowStationHandle ); +// rev // Valid bit masks enforced by NtUserSetProcessWin32Capabilities +#define PROC_CAP_FLAGS1_VALID_MASK 0x00000007u // bits 0-2 +#define PROC_CAP_FLAGS2_VALID_MASK 0x00000007u // bits 0-2 +#define PROC_CAP_ENABLE_VALID_MASK 0x00000001u // bit 0 +#define PROC_CAP_DISABLE_VALID_MASK 0x00000001u // bit 0 + +#define PROC_CAP_FLAGS1_BIT0 0x00000001u +#define PROC_CAP_FLAGS1_BIT1 0x00000002u +#define PROC_CAP_FLAGS1_BIT2 0x00000004u + +#define PROC_CAP_FLAGS2_BIT0 0x00000001u +#define PROC_CAP_FLAGS2_BIT1 0x00000002u +#define PROC_CAP_FLAGS2_BIT2 0x00000004u + +#define PROC_CAP_ENABLE_BIT0 0x00000001u +#define PROC_CAP_DISABLE_BIT0 0x00000001u + +#define PROC_CAP_FLAGS1_INVALID(x) (((x) & ~PROC_CAP_FLAGS1_VALID_MASK) != 0) +#define PROC_CAP_FLAGS2_INVALID(x) (((x) & ~PROC_CAP_FLAGS2_VALID_MASK) != 0) +#define PROC_CAP_ENABLE_INVALID(x) (((x) & ~PROC_CAP_ENABLE_VALID_MASK) != 0) +#define PROC_CAP_DISABLE_INVALID(x) (((x) & ~PROC_CAP_DISABLE_VALID_MASK) != 0) + +// rev +typedef struct _USER_PROCESS_CAP_ENTRY +{ + HANDLE ProcessHandle; + ULONG Flags1; + ULONG Flags2; + ULONG EnableMask; + ULONG DisableMask; +} USER_PROCESS_CAP_ENTRY, *PUSER_PROCESS_CAP_ENTRY; + +// rev +typedef struct _USER_PROCESS_CAP_INTERNAL +{ + PVOID ProcessObject; + ULONG SessionId; + ULONG Reserved; + ULONGLONG FlagsPacked; + ULONGLONG CapabilityPacked; +} USER_PROCESS_CAP_INTERNAL, *PUSER_PROCESS_CAP_INTERNAL; + +// rev +NTSYSCALLAPI +NTSTATUS +NTAPI +NtUserSetProcessWin32Capabilities( + _In_reads_(Count) const USER_PROCESS_CAP_ENTRY* Capabilities, + _In_ ULONG Count + ); + +// rev +/** + * The NtUserSetProcessRestrictionExemption routine marks the current process as exempt from certain win32k/user restrictions. + * Note: This requires a developer mode/license check. + * + * \param Enable Indicates whether to enable or disable the exemption. + * \return Successful or errant status. + */ +NTSYSCALLAPI +NTSTATUS +NTAPI +NtUserSetProcessRestrictionExemption( + _In_ BOOL EnableExemption + ); + +// rev +/** + * The NtUserSetProcessUIAccessZorder routine tweaks window z-order behavior for UIAccess scenarios. + * Note: Set only when the process is not elevated. + * + * \return Successful or errant status. + */ +NTSYSCALLAPI +NTSTATUS +NTAPI +NtUserSetProcessUIAccessZorder( + VOID + ); + NTSYSCALLAPI BOOL NTAPI @@ -408,7 +594,7 @@ NtUserSetWindowPlacement( ); NTSYSCALLAPI -LOGICAL +BOOL NTAPI NtUserSetWindowStationUser( _In_ HWINSTA WindowStationHandle, @@ -418,7 +604,7 @@ NtUserSetWindowStationUser( ); NTSYSAPI -LOGICAL +BOOL NTAPI SetWindowStationUser( _In_ HWINSTA WindowStationHandle, @@ -435,7 +621,7 @@ NtUserTestForInteractiveUser( ); NTSYSCALLAPI -LOGICAL +BOOL NTAPI NtUserSwitchDesktop( _In_ HDESK DesktopHandle, @@ -444,7 +630,7 @@ NtUserSwitchDesktop( ); NTSYSCALLAPI -LOGICAL +BOOL NTAPI NtUserSetThreadDesktop( _In_ HDESK DesktopHandle @@ -697,7 +883,7 @@ ULONG NTAPI NtUserGetGuiResources( _In_ HANDLE ProcessHandle, - _In_ ULONG uiFlags + _In_ ULONG Flags ); NTSYSCALLAPI @@ -705,9 +891,9 @@ BOOL NTAPI NtUserGetLayeredWindowAttributes( _In_ HWND WindowHandle, - _In_ COLORREF* pcrKey, - _In_ BYTE* pbAlpha, - _In_ ULONG pdwFlags + _Out_opt_ COLORREF* Key, + _Out_opt_ PBYTE Alpha, + _Out_opt_ PULONG Flags ); NTSYSCALLAPI @@ -777,13 +963,6 @@ NtUserGetRegisteredRawInputDevices( _In_ ULONG RawInputDeviceSize ); -NTSYSCALLAPI -HMENU -NTAPI -NtUserGetSendMessageReceiver( - _In_ HANDLE ThreadId - ); - NTSYSAPI HWND NTAPI @@ -840,6 +1019,22 @@ NtUserGetWindowPlacement( _Inout_ PWINDOWPLACEMENT WindowPlacement ); +NTSYSCALLAPI +HANDLE +NTAPI +GetWindowProcessHandle( + _In_ HWND WindowHandle, + _In_ ACCESS_MASK DesiredAccess + ); + +NTSYSCALLAPI +HANDLE +NTAPI +NtUserGetWindowProcessHandle( + _In_ HWND WindowHandle, + _In_ ACCESS_MASK DesiredAccess + ); + NTSYSCALLAPI BOOL NTAPI @@ -864,7 +1059,7 @@ BOOL NTAPI NtUserInvalidateRgn( _In_ HWND WindowHandle, - _In_ HRGN hRgn, + _In_ HRGN RgnHandle, _In_ BOOL Erase ); @@ -934,7 +1129,7 @@ BOOL NTAPI NtUserPhysicalToLogicalPoint( _In_ HWND WindowHandle, - _In_ LPPOINT lpPoint + _In_ LPPOINT Point ); NTSYSCALLAPI @@ -942,8 +1137,8 @@ BOOL NTAPI NtUserPrintWindow( _In_ HWND WindowHandle, - _In_ HDC hdcBlt, - _In_ ULONG nFlags + _In_ HDC Hdc, + _In_ ULONG Flags ); NTSYSCALLAPI @@ -952,7 +1147,7 @@ NTAPI NtUserQueryInformationThread( _In_ HANDLE ThreadHandle, _In_ USERTHREADINFOCLASS ThreadInformationClass, - _Out_writes_bytes_(ThreadInformationLength) PVOID ThreadInformation, + _Out_writes_bytes_(*ReturnLength) PVOID ThreadInformation, _Out_opt_ PULONG ReturnLength ); @@ -969,8 +1164,8 @@ NtUserSetInformationThread( NTSYSAPI BOOL NTAPI -QuerySendMessage( - _Inout_ MSG* pMsg +NtUserQuerySendMessage( + _Inout_ PMSG Message ); NTSYSCALLAPI @@ -988,7 +1183,7 @@ NtUserRedrawWindow( _In_ HWND WindowHandle, _In_ const PRECT lprcUpdate, _In_ HRGN hrgnUpdate, - _In_ ULONG flags + _In_ ULONG Flags ); NTSYSCALLAPI @@ -1004,7 +1199,7 @@ BOOL NTAPI NtUserRegisterHotKey( _In_ HWND WindowHandle, - _In_ LONG id, + _In_ LONG Id, _In_ ULONG fsModifiers, _In_ ULONG vk ); @@ -1014,17 +1209,17 @@ BOOL NTAPI NtUserRemoveMenu( _In_ HMENU MenuHandle, - _In_ ULONG uPosition, - _In_ ULONG uFlags + _In_ ULONG Position, + _In_ ULONG Flags ); NTSYSCALLAPI ULONG NTAPI NtUserSendInput( - _In_ ULONG cInputs, - _In_ LPINPUT pInputs, - _In_ LONG cbSize + _In_ ULONG Count, + _In_ LPINPUT Inputs, + _In_ LONG Size ); NTSYSCALLAPI @@ -1046,19 +1241,19 @@ ULONG_PTR NTAPI NtUserSetTimer( _In_ HWND WindowHandle, - _In_ ULONG_PTR nIDEvent, - _In_ ULONG uElapse, - _In_ TIMERPROC lpTimerFunc, - _In_ ULONG uToleranceDelay + _In_ ULONG_PTR IDEvent, + _In_ ULONG Elapse, + _In_ TIMERPROC TimerFunc, + _In_ ULONG ToleranceDelay ); NTSYSCALLAPI -WORD +USHORT NTAPI NtUserSetClassWord( _In_ HWND WindowHandle, - _In_ LONG nIndex, - _In_ WORD wNewWord + _In_ LONG Index, + _In_ USHORT NewWord ); NTSYSCALLAPI @@ -1081,16 +1276,9 @@ BOOL NTAPI NtUserSetLayeredWindowAttributes( _In_ HWND WindowHandle, - _In_ COLORREF crKey, - _In_ BYTE bAlpha, - _In_ DWORD dwFlags - ); - -NTSYSCALLAPI -BOOL -NTAPI -NtUserSetProcessRestrictionExemption( - _In_ BOOL EnableExemption + _In_ COLORREF Key, + _In_ BYTE Alpha, + _In_ ULONG Flags ); NTSYSCALLAPI @@ -1098,21 +1286,56 @@ BOOL NTAPI NtUserSetWindowPos( _In_ HWND WindowHandle, - _In_ HWND WindowHandleInsertAfter, + _In_opt_ HWND WindowHandleInsertAfter, _In_ LONG X, _In_ LONG Y, _In_ LONG cx, _In_ LONG cy, - _In_ ULONG uFlags + _In_ ULONG Flags + ); + +FORCEINLINE +BOOL +NTAPI +NtUserBringWindowToTop( + _In_ HWND WindowHandle + ) +{ + return NtUserSetWindowPos( + WindowHandle, + NULL, + 0, 0, 0, 0, + 3 + ); +} + +// Send to the window registered with NtUserRegisterCloakedNotification +// when cloak state of the window has changed +// wParam - if window cloak state changed contains cloaking value +// which can be one/all of the below +// DWM_CLOAKED_APP(0x0000001).The window was cloaked by its owner application. +// DWM_CLOAKED_SHELL(0x0000002).The window was cloaked by the Shell. +// 0 - window is not cloaked +// +// lParam - 0 (unused) +// +#define WM_CLOAKED_STATE_CHANGED 0x0347 + +NTSYSCALLAPI +BOOL +NTAPI +NtUserRegisterCloakedNotification( + _In_ HWND WindowHandle, + _In_ BOOL Register ); NTSYSCALLAPI -WORD +USHORT NTAPI NtUserSetWindowWord( _In_ HWND WindowHandle, - _In_ LONG nIndex, - _In_ WORD wNewWord + _In_ LONG Index, + _In_ USHORT NewWord ); NTSYSCALLAPI @@ -1137,18 +1360,21 @@ NtUserSetAdditionalForegroundBoostProcesses( _In_ HWND WindowHandle ); +// rev NTSYSCALLAPI ULONG NTAPI NtUserSetAdditionalPowerThrottlingProcess( - _In_ HWND WindowHandle + _In_ HWND WindowHandle, + _In_ ULONG ProcessHandlesCount, + _In_reads_(ProcessHandlesCount) PHANDLE ProcessHandles ); NTSYSCALLAPI LONG NTAPI NtUserShowCursor( - _In_ BOOL bShow + _In_ BOOL Show ); NTSYSCALLAPI @@ -1156,7 +1382,7 @@ BOOL NTAPI NtUserShowWindow( _In_ HWND WindowHandle, - _In_ LONG nCmdShow + _In_ LONG CmdShow ); NTSYSCALLAPI @@ -1164,7 +1390,7 @@ BOOL NTAPI NtUserShowWindowAsync( _In_ HWND WindowHandle, - _In_ LONG nCmdShow + _In_ LONG CmdShow ); NTSYSCALLAPI @@ -1172,8 +1398,8 @@ BOOL NTAPI NtUserShutdownBlockReasonQuery( _In_ HWND WindowHandle, - _Out_ LPWSTR pwszBuff, - _Inout_ PULONG pcchBuff + _Out_ PWSTR Buffer, + _Inout_ PULONG BufferCount ); NTSYSCALLAPI @@ -1187,7 +1413,7 @@ NTSYSCALLAPI BOOL NTAPI NtUserTrackMouseEvent( - _In_ LPTRACKMOUSEEVENT lpEventTrack + _In_ LPTRACKMOUSEEVENT EventTrack ); NTSYSCALLAPI @@ -1195,7 +1421,7 @@ BOOL NTAPI NtUserTrackPopupMenuEx( _In_ HMENU MenuHandle, - _In_ ULONG uFlags, + _In_ ULONG Flags, _In_ LONG x, _In_ LONG y, _In_ HWND WindowHandle, @@ -1206,7 +1432,7 @@ NTSYSCALLAPI BOOL NTAPI NtUserUnhookWinEvent( - _In_ HWINEVENTHOOK hWinEventHook + _In_ HWINEVENTHOOK WinEventHookHandle ); NTSYSCALLAPI @@ -1214,7 +1440,7 @@ BOOL NTAPI NtUserUnregisterHotKey( _In_ HWND WindowHandle, - _In_ LONG id + _In_ LONG Id ); NTSYSCALLAPI @@ -1238,7 +1464,7 @@ NTSYSCALLAPI HWND NTAPI NtUserWindowFromDC( - _In_ HDC hDC + _In_ HDC Hdc ); NTSYSCALLAPI @@ -1255,149 +1481,1773 @@ NtUserWindowFromPoint( _In_ POINT Point ); +// rev // valid since 20H1 +#define SFI_CREATEMENU 0 // NtUserCallNoParam +#define SFI_CREATEPOPUPMENU 1 // NtUserCallNoParam +#define SFI_ALLOWFOREGROUNDACTIVATION 2 // NtUserCallNoParam +#define SFI_CANCELQUEUEEVENTCOMPLETIONPACKET 3 // NtUserCallNoParam +#define SFI_CLEARWAKEMASK 4 // NtUserCallNoParam +#define SFI_CREATESYSTEMTHREADS 5 // NtUserCallNoParam +#define SFI_DESTROYCARET 6 // NtUserCallNoParam +#define SFI_DISABLEPROCESSWINDOWSGHOSTING 7 // NtUserCallNoParam +#define SFI_DRAINTHREADCOREMESSAGINGCOMPLETIONS 8 // NtUserCallNoParam +#define SFI_GETDEVICECHANGEINFO 9 // NtUserCallNoParam +#define SFI_GETIMESHOWSTATUS 10 // NtUserCallNoParam +#define SFI_GETINPUTDESKTOP 11 // NtUserCallNoParam +#define SFI_GETMESSAGEPOS 12 // NtUserCallNoParam +#define SFI_GETQUEUEIOCP 13 // NtUserCallNoParam +#define SFI_GETUNPREDICTEDMESSAGEPOS 14 // NtUserCallNoParam +#define SFI_HANDLESYSTEMTHREADCREATIONFAILURE 15 // NtUserCallNoParam +#define SFI_HIDECURSORNOCAPTURE 16 // NtUserCallNoParam +#define SFI_ISQUEUEATTACHED 17 // NtUserCallNoParam +#define SFI_LOADCURSORSANDICONS 18 // NtUserCallNoParam +#define SFI_LOADUSERAPIHOOK 19 // NtUserCallNoParam +#define SFI_PREPAREFORLOGOFF 20 // NtUserCallNoParam +#define SFI_REASSOCIATEQUEUEEVENTCOMPLETIONPACKET 21 // NtUserCallNoParam +#define SFI_RELEASECAPTURE 22 // NtUserCallNoParam +#define SFI_REMOVEQUEUECOMPLETION 23 // NtUserCallNoParam +#define SFI_RESETDBLCLK 24 // NtUserCallNoParam +#define SFI_ZAPACTIVEANDFOCUS 25 // NtUserCallNoParam +#define SFI_REMOTECONSOLESHADOWSTOP 26 // NtUserCallNoParam +#define SFI_REMOTEDISCONNECT 27 // NtUserCallNoParam +#define SFI_REMOTESHADOWSETUP 30 // NtUserCallNoParam +#define SFI_REMOTESHADOWSTOP 31 // NtUserCallNoParam +#define SFI_REMOTEPASSTHRUENABLE 32 // NtUserCallNoParam +#define SFI_REMOTEPASSTHRUDISABLE 33 // NtUserCallNoParam +#define SFI_REMOTECONNECTSTATE 34 // NtUserCallNoParam +#define SFI_UPDATEPERUSERIMMENABLING 36 // NtUserCallNoParam +#define SFI_USERPOWERCALLOUTWORKER 37 // NtUserCallNoParam +#define SFI_WAKERITFORSHUTDOWN 38 // NtUserCallNoParam +#define SFI_DOINITMESSAGEPUMPHOOK 39 // NtUserCallNoParam +#define SFI_DOUNINITMESSAGEPUMPHOOK 40 // NtUserCallNoParam +#define SFI_ENABLEMOUSEINPOINTERFORTHREAD 41 // NtUserCallNoParam +#define SFI_DEFERREDDESKTOPROTATION 42 // NtUserCallNoParam +#define SFI_ENABLEPERMONITORMENUSCALING 43 // NtUserCallNoParam +#define SFI_BEGINDEFERWINDOWPOS 44 // NtUserCallOneParam +#define SFI_GETSENDMESSAGERECEIVER 45 // NtUserCallOneParam +#define SFI_ALLOWSETFOREGROUNDWINDOW 46 // NtUserCallOneParam +#define SFI_CSDDEUNINITIALIZE 47 // NtUserCallOneParam +#define SFI_ENUMCLIPBOARDFORMATS 49 // NtUserCallOneParam +#define SFI_GETINPUTEVENT 50 // NtUserCallOneParam +#define SFI_GETKEYBOARDTYPE 51 // NtUserCallOneParam +#define SFI_GETPROCESSDEFAULTLAYOUT 52 // NtUserCallOneParam +#define SFI_GETWINSTATIONINFO 53 // NtUserCallOneParam +#define SFI_LOCKSETFOREGROUNDWINDOW 54 // NtUserCallOneParam +#define SFI_LW_LOADFONTS 55 // NtUserCallOneParam +#define SFI_MAPDESKTOPOBJECT 56 // NtUserCallOneParam +#define SFI_MESSAGEBEEP 57 // NtUserCallOneParam +#define SFI_PLAYEVENTSOUND 58 // NtUserCallOneParam +#define SFI_POSTQUITMESSAGE 59 // NtUserCallOneParam +#define SFI_REALIZEPALETTE 60 // NtUserCallOneParam +#define SFI_REGISTERLPK 61 // NtUserCallOneParam +#define SFI_REGISTERSYSTEMTHREAD 62 // NtUserCallOneParam +#define SFI_REMOTERECONNECT 63 // NtUserCallOneParam +#define SFI_REMOTETHINWIRESTATS 64 // NtUserCallOneParam +#define SFI_REMOTENOTIFY 65 // NtUserCallOneParam +#define SFI_REPLYMESSAGE 66 // NtUserCallOneParam +#define SFI_SETCARETBLINKTIME 67 // NtUserCallOneParam +#define SFI_SETDOUBLECLICKTIME 68 // NtUserCallOneParam +#define SFI_SETMESSAGEEXTRAINFO 69 // NtUserCallOneParam +#define SFI_SETPROCESSDEFAULTLAYOUT 70 // NtUserCallOneParam +#define SFI_SETWATERMARKSTRINGS 71 // NtUserCallOneParam +#define SFI_SHOWSTARTGLASS 72 // NtUserCallOneParam +#define SFI_SWAPMOUSEBUTTON 73 // NtUserCallOneParam +#define SFI_WOWMODULEUNLOAD 74 // NtUserCallOneParam +#define SFI_DWMLOCKSCREENUPDATES 75 // NtUserCallOneParam +#define SFI_ENABLESESSIONFORMMCSS 76 // NtUserCallOneParam +#define SFI_SETWAITFORQUEUEATTACH 77 // NtUserCallOneParam +#define SFI_THREADMESSAGEQUEUEATTACHED 78 // NtUserCallOneParam +#define SFI_ENSUREDPIDEPSYSMETCACHEFORPLATEAU 80 // NtUserCallOneParam +#define SFI_FORCEENABLENUMPADTRANSLATION 81 // NtUserCallOneParam +#define SFI_SETTSFEVENTSTATE 82 // NtUserCallOneParam +#define SFI_SETSHELLCHANGENOTIFYHWND 83 // NtUserCallOneParam +#define SFI_DEREGISTERSHELLHOOKWINDOW 84 // NtUserCallHwnd +#define SFI_DWP_GETENABLEDPOPUPOFFSET 85 // NtUserCallHwnd +#define SFI_GETMODERNAPPWINDOW 86 // NtUserCallHwnd +#define SFI_GETWINDOWCONTEXTHELPID 87 // NtUserCallHwnd +#define SFI_REGISTERSHELLHOOKWINDOW 88 // NtUserCallHwnd +#define SFI_SETMSGBOX 89 // NtUserCallHwnd +#define SFI_INITTHREADCOREMESSAGINGIOCP 90 // NtUserCallHwnd, NtUserCallHwndSafe +#define SFI_SCHEDULEDISPATCHNOTIFICATION 91 // NtUserCallHwnd, NtUserCallHwndSafe +#define SFI_SETPROGMANWINDOW 92 // NtUserCallHwndOpt +#define SFI_SETTASKMANWINDOW 93 // NtUserCallHwndOpt +#define SFI_GETCLASSICOCUR 94 // NtUserCallHwndParam +#define SFI_CLEARWINDOWSTATE 95 // NtUserCallHwndParam +#define SFI_KILLSYSTEMTIMER 96 // NtUserCallHwndParam +#define SFI_NOTIFYOVERLAYWINDOW 97 // NtUserCallHwndParam +#define SFI_SETDIALOGPOINTER 99 // NtUserCallHwndParam +#define SFI_SETVISIBLE 100 // NtUserCallHwndParam +#define SFI_SETWINDOWCONTEXTHELPID 101 // NtUserCallHwndParam +#define SFI_SETWINDOWSTATE 102 // NtUserCallHwndParam +#define SFI_REGISTERWINDOWARRANGEMENTCALLOUT 103 // NtUserCallHwndParam +#define SFI_ENABLEMODERNAPPWINDOWKEYBOARDINTERCEPT 104 // NtUserCallHwndParam +#define SFI_ARRANGEICONICWINDOWS 105 // NtUserCallHwndLock +#define SFI_DRAWMENUBAR 106 // NtUserCallHwndLock +#define SFI_CHECKIMESHOWSTATUSINTHREAD 107 // NtUserCallHwndLock, NtUserCallHwndLockSafe +#define SFI_GETSYSMENUOFFSET 108 // NtUserCallHwndLock +#define SFI_REDRAWFRAME 109 // NtUserCallHwndLock +#define SFI_REDRAWFRAMEANDHOOK 110 // NtUserCallHwndLock +#define SFI_SETDIALOGSYSTEMMENU 111 // NtUserCallHwndLock +#define SFI_SETFOREGROUNDWINDOW 112 // NtUserCallHwndLock +#define SFI_SETSYSMENU 113 // NtUserCallHwndLock +#define SFI_UPDATECLIENTRECT 114 // NtUserCallHwndLock +#define SFI_UPDATEWINDOW 115 // NtUserCallHwndLock +#define SFI_SETCANCELROTATIONDELAYHINTWINDOW 116 // NtUserCallHwndLock +#define SFI_GETWINDOWTRACKINFOASYNC 117 // NtUserCallHwndLock +#define SFI_BROADCASTIMESHOWSTATUSCHANGE 118 // NtUserCallHwndParamLock +#define SFI_SETMODERNAPPWINDOW 119 // NtUserCallHwndParamLock +#define SFI_REDRAWTITLE 120 // NtUserCallHwndParamLock +#define SFI_SHOWOWNEDPOPUPS 121 // NtUserCallHwndParamLock +#define SFI_SWITCHTOTHISWINDOW 122 // NtUserCallHwndParamLock +#define SFI_UPDATEWINDOWS 123 // NtUserCallHwndParamLock +#define SFI_VALIDATERGN 124 // NtUserCallHwndParamLock +#define SFI_ENABLEWINDOW 125 // NtUserCallHwndParamLock, NtUserCallHwndParamLockSafe +#define SFI_CHANGEWINDOWMESSAGEFILTER 126 // NtUserCallTwoParam +#define SFI_GETCURSORPOS 127 // NtUserCallTwoParam +#define SFI_INITANSIOEM 128 // NtUserCallTwoParam +#define SFI_NLSKBDSENDIMENOTIFICATION 129 // NtUserCallTwoParam +#define SFI_REGISTERGHOSTWINDOW 130 // NtUserCallTwoParam +#define SFI_REGISTERLOGONPROCESS 131 // NtUserCallTwoParam +#define SFI_REGISTERSIBLINGFROSTWINDOW 132 // NtUserCallTwoParam +#define SFI_REGISTERUSERHUNGAPPHANDLERS 133 // NtUserCallTwoParam +#define SFI_REMOTESHADOWCLEANUP 134 // NtUserCallTwoParam +#define SFI_REMOTESHADOWSTART 135 // NtUserCallTwoParam +#define SFI_SETCARETPOS 136 // NtUserCallTwoParam +#define SFI_SETTHREADQUEUEMERGESETTING 137 // NtUserCallTwoParam +#define SFI_UNHOOKWINDOWSHOOK 138 // NtUserCallTwoParam +#define SFI_ENABLESHELLWINDOWMANAGEMENTBEHAVIOR 139 // NtUserCallTwoParam +#define SFI_CITSETINFO 140 // NtUserCallTwoParam +#define SFI_SCALESYSTEMMETRICFORDPIWITHOUTCACHE 141 // NtUserCallTwoParam + +// N.B. +// Windows 10 uses NtUserCall* dispatch routines to invoke ~140 functions +// by index (note that our index table is valid only since 20H1). +// Windows 11 uses the newly introduced syscalls for each function instead. + +// private // before WIN11 +NTSYSCALLAPI +ULONG_PTR +NTAPI +NtUserCallNoParam( + _In_ ULONG xpfnProc + ); + +// private // before WIN11 +NTSYSCALLAPI +ULONG_PTR +NTAPI +NtUserCallOneParam( + _In_ ULONG_PTR Param, + _In_ ULONG xpfnProc + ); + +// private // before WIN11 +NTSYSCALLAPI +ULONG_PTR +NTAPI +NtUserCallHwnd( + _In_ HWND hwnd, + _In_ ULONG xpfnProc + ); + +// private // before WIN11 +#if (PHNT_VERSION >= PHNT_WINDOWS_10_RS5) +NTSYSCALLAPI +ULONG_PTR +NTAPI +NtUserCallHwndSafe( + _In_ HWND hwnd, + _In_ ULONG xpfnProc + ); +#endif + +// private // before WIN11 +NTSYSCALLAPI +ULONG_PTR +NTAPI +NtUserCallHwndOpt( + _In_opt_ HWND hwnd, + _In_ ULONG xpfnProc + ); + +// private // before WIN11 +NTSYSCALLAPI +ULONG_PTR +NTAPI +NtUserCallHwndParam( + _In_ HWND hwnd, + _In_ ULONG_PTR Param, + _In_ ULONG xpfnProc + ); + +// private // before WIN11 +NTSYSCALLAPI +ULONG_PTR +NTAPI +NtUserCallHwndLock( + _In_ HWND hwnd, + _In_ ULONG xpfnProc + ); + +// private // before WIN11 +#if (PHNT_VERSION >= PHNT_WINDOWS_10_RS5) +NTSYSCALLAPI +ULONG_PTR +NTAPI +NtUserCallHwndLockSafe( + _In_ HWND hwnd, + _In_ ULONG xpfnProc + ); +#endif + +// private // before WIN11 +NTSYSCALLAPI +ULONG_PTR +NTAPI +NtUserCallHwndParamLock( + _In_ HWND hwnd, + _In_ ULONG_PTR Param, + _In_ ULONG xpfnProc + ); + +// private // before WIN11 +#if (PHNT_VERSION >= PHNT_WINDOWS_10_RS5) +NTSYSCALLAPI +ULONG_PTR +NTAPI +NtUserCallHwndParamLockSafe( + _In_ HWND hwnd, + _In_ ULONG_PTR Param, + _In_ ULONG xpfnProc + ); +#endif + +// private // before WIN11 +NTSYSCALLAPI +ULONG_PTR +NTAPI +NtUserCallTwoParam( + _In_ ULONG_PTR Param1, + _In_ ULONG_PTR Param2, + _In_ ULONG xpfnProc + ); + +#if (PHNT_VERSION >= PHNT_WINDOWS_11) + +// private // NtUserCallNoParam(SFI_CREATEMENU) before WIN11 +_Success_(return != NULL) +_Must_inspect_result_ +NTSYSCALLAPI +HMENU +NTAPI +NtUserCreateMenu( + VOID + ); + +// private // NtUserCallNoParam(SFI_CREATEPOPUPMENU) before WIN11 +_Success_(return != NULL) +_Must_inspect_result_ +NTSYSCALLAPI +HMENU +NTAPI +NtUserCreatePopupMenu( + VOID + ); + +// private // NtUserCallNoParam(SFI_ALLOWFOREGROUNDACTIVATION) before WIN11 +_Success_(return != 0) +NTSYSCALLAPI +LOGICAL +NTAPI +NtUserAllowForegroundActivation( + VOID + ); + +// rev // NtUserCallNoParam(SFI_CANCELQUEUEEVENTCOMPLETIONPACKET) before WIN11 +_Success_(return != 0) +NTSYSCALLAPI +LOGICAL +NTAPI +NtUserCancelQueueEventCompletionPacket( + VOID + ); + +// private // NtUserCallNoParam(SFI_CLEARWAKEMASK) before WIN11 +_Success_(return != 0) +NTSYSCALLAPI +LOGICAL +NTAPI +NtUserClearWakeMask( + VOID + ); + +// private // NtUserCallNoParam(SFI_CREATESYSTEMTHREADS) before WIN11 +_Success_(return != 0) +NTSYSCALLAPI +LOGICAL +NTAPI +NtUserCreateSystemThreads( + VOID + ); + +// private // NtUserCallNoParam(SFI_DESTROYCARET) before WIN11 +_Success_(return != 0) +NTSYSCALLAPI +LOGICAL +NTAPI +NtUserDestroyCaret( + VOID + ); + +// private // NtUserCallNoParam(SFI_DISABLEPROCESSWINDOWSGHOSTING) before WIN11 +_Success_(return != 0) +NTSYSCALLAPI +LOGICAL +NTAPI +NtUserDisableProcessWindowsGhosting( + VOID + ); + +// rev // NtUserCallNoParam(SFI_DRAINTHREADCOREMESSAGINGCOMPLETIONS) before WIN11 +_Success_(return != 0) +NTSYSCALLAPI +LOGICAL +NTAPI +NtUserDrainThreadCoreMessagingCompletions( + VOID + ); + +// private // NtUserCallNoParam(SFI_GETDEVICECHANGEINFO) before WIN11 +_Success_(return != 0) +_Must_inspect_result_ +NTSYSCALLAPI +ULONG +NTAPI +NtUserGetDeviceChangeInfo( + VOID + ); + +// private // NtUserCallNoParam(SFI_GETIMESHOWSTATUS) before WIN11 +_Success_(return != 0) +_Must_inspect_result_ +NTSYSCALLAPI +LOGICAL +NTAPI +NtUserGetIMEShowStatus( + VOID + ); + +// private // NtUserCallNoParam(SFI_GETINPUTDESKTOP) before WIN11 +_Success_(return != NULL) +_Must_inspect_result_ +NTSYSCALLAPI +HDESK +NTAPI +NtUserGetInputDesktop( + VOID + ); + +// private // NtUserCallNoParam(SFI_GETMESSAGEPOS) before WIN11 +_Must_inspect_result_ +NTSYSCALLAPI +ULONG +NTAPI +NtUserGetMessagePos( + VOID + ); + +// rev // NtUserCallNoParam(SFI_GETQUEUEIOCP) before WIN11 +_Must_inspect_result_ +NTSYSCALLAPI +ULONG_PTR +NTAPI +NtUserGetQueueIocp( + VOID + ); + +// private // NtUserCallNoParam(SFI_GETUNPREDICTEDMESSAGEPOS) before WIN11 +_Must_inspect_result_ +NTSYSCALLAPI +ULONG +NTAPI +NtUserGetUnpredictedMessagePos( + VOID + ); + +// private // NtUserCallNoParam(SFI_HANDLESYSTEMTHREADCREATIONFAILURE) before WIN11 +_Success_(return != 0) +NTSYSCALLAPI +LOGICAL +NTAPI +NtUserHandleSystemThreadCreationFailure( + VOID + ); + +// private // NtUserCallNoParam(SFI_HIDECURSORNOCAPTURE) before WIN11 +NTSYSCALLAPI +ULONG_PTR +NTAPI +NtUserHideCursorNoCapture( + VOID + ); + +// private // NtUserCallNoParam(SFI_ISQUEUEATTACHED) before WIN11 +_Must_inspect_result_ +NTSYSCALLAPI +LOGICAL +NTAPI +NtUserIsQueueAttached( + VOID + ); + +// private // NtUserCallNoParam(SFI_LOADCURSORSANDICONS) before WIN11 +_Success_(return != 0) +NTSYSCALLAPI +LOGICAL +NTAPI +NtUserLoadCursorsAndIcons( + VOID + ); + +// private // NtUserCallNoParam(SFI_LOADUSERAPIHOOK) before WIN11 +_Success_(return != 0) +NTSYSCALLAPI +LOGICAL +NTAPI +NtUserLoadUserApiHook( + VOID + ); + +// private // NtUserCallNoParam(SFI_PREPAREFORLOGOFF) before WIN11 +_Success_(return != 0) +NTSYSCALLAPI +LOGICAL +NTAPI +NtUserPrepareForLogoff( + VOID + ); + +// rev // NtUserCallNoParam(SFI_REASSOCIATEQUEUEEVENTCOMPLETIONPACKET) before WIN11 +_Success_(return != 0) +NTSYSCALLAPI +LOGICAL +NTAPI +NtUserReassociateQueueEventCompletionPacket( + VOID + ); + +// private // NtUserCallNoParam(SFI_RELEASECAPTURE) before WIN11 +_Success_(return != 0) +NTSYSCALLAPI +LOGICAL +NTAPI +NtUserReleaseCapture( + VOID + ); + +// rev // NtUserCallNoParam(SFI_REMOVEQUEUECOMPLETION) before WIN11 +_Success_(return != 0) +NTSYSCALLAPI +LOGICAL +NTAPI +NtUserRemoveQueueCompletion( + VOID + ); + +// private // NtUserCallNoParam(SFI_RESETDBLCLK) before WIN11 +_Success_(return != 0) +NTSYSCALLAPI +LOGICAL +NTAPI +NtUserResetDblClk( + VOID + ); + +// private // NtUserCallNoParam(SFI_ZAPACTIVEANDFOCUS) before WIN11 +_Success_(return != 0) +NTSYSCALLAPI +LOGICAL +NTAPI +NtUserZapActiveAndFocus( + VOID + ); + +// private // NtUserCallNoParam(SFI_REMOTECONSOLESHADOWSTOP) before WIN11 +NTSYSCALLAPI +NTSTATUS +NTAPI +NtUserRemoteConsoleShadowStop( + VOID + ); + +// private // NtUserCallNoParam(SFI_REMOTEDISCONNECT) before WIN11 +NTSYSCALLAPI +NTSTATUS +NTAPI +NtUserRemoteDisconnect( + VOID + ); + +// private // NtUserCallNoParam(SFI_REMOTESHADOWSETUP) before WIN11 +NTSYSCALLAPI +NTSTATUS +NTAPI +NtUserRemoteShadowSetup( + VOID + ); + +// private // NtUserCallNoParam(SFI_REMOTESHADOWSTOP) before WIN11 +NTSYSCALLAPI +NTSTATUS +NTAPI +NtUserRemoteShadowStop( + VOID + ); + +// private // NtUserCallNoParam(SFI_REMOTEPASSTHRUENABLE) before WIN11 +NTSYSCALLAPI +NTSTATUS +NTAPI +NtUserRemotePassthruEnable( + VOID + ); + +// private // NtUserCallNoParam(SFI_REMOTEPASSTHRUDISABLE) before WIN11 +NTSYSCALLAPI +NTSTATUS +NTAPI +NtUserRemotePassthruDisable( + VOID + ); + +// private +#define CTX_W32_CONNECT_STATE_CONSOLE 0 +#define CTX_W32_CONNECT_STATE_IDLE 1 +#define CTX_W32_CONNECT_STATE_EXIT_IN_PROGRESS 2 +#define CTX_W32_CONNECT_STATE_CONNECTED 3 +#define CTX_W32_CONNECT_STATE_DISCONNECTED 4 + +// private // NtUserCallNoParam(SFI_REMOTECONNECTSTATE) before WIN11 +_Must_inspect_result_ +NTSYSCALLAPI +ULONG +NTAPI +NtUserRemoteConnectState( + VOID + ); + +// private // NtUserCallNoParam(SFI_UPDATEPERUSERIMMENABLING) before WIN11 +_Success_(return != 0) +NTSYSCALLAPI +LOGICAL +NTAPI +NtUserUpdatePerUserImmEnabling( + VOID + ); + +// private // NtUserCallNoParam(SFI_USERPOWERCALLOUTWORKER) before WIN11 +_Success_(return != 0) +NTSYSCALLAPI +LOGICAL +NTAPI +NtUserUserPowerCalloutWorker( + VOID + ); + +// private // NtUserCallNoParam(SFI_WAKERITFORSHUTDOWN) before WIN11 +NTSYSCALLAPI +NTSTATUS +NTAPI +NtUserWakeRITForShutdown( + VOID + ); + +// private // NtUserCallNoParam(SFI_DOINITMESSAGEPUMPHOOK) before WIN11 +_Success_(return != 0) +NTSYSCALLAPI +LOGICAL +NTAPI +NtUserDoInitMessagePumpHook( + VOID + ); + +// private // NtUserCallNoParam(SFI_DOUNINITMESSAGEPUMPHOOK) before WIN11 +_Success_(return != 0) +NTSYSCALLAPI +LOGICAL +NTAPI +NtUserDoUninitMessagePumpHook( + VOID + ); + +// rev // NtUserCallNoParam(SFI_ENABLEMOUSEINPOINTERFORTHREAD) before WIN11 +_Success_(return != 0) +NTSYSCALLAPI +LOGICAL +NTAPI +NtUserEnableMouseInPointerForThread( + VOID + ); + +// private // NtUserCallNoParam(SFI_DEFERREDDESKTOPROTATION) before WIN11 +NTSYSCALLAPI +ULONG_PTR +NTAPI +NtUserDeferredDesktopRotation( + VOID + ); + +// private // NtUserCallNoParam(SFI_ENABLEPERMONITORMENUSCALING) before WIN11 +_Success_(return != 0) +NTSYSCALLAPI +LOGICAL +NTAPI +NtUserEnablePerMonitorMenuScaling( + VOID + ); + +// private // NtUserCallOneParam(SFI_BEGINDEFERWINDOWPOS) before WIN11 +_Success_(return != NULL) +_Must_inspect_result_ +NTSYSCALLAPI +HDWP +NTAPI +NtUserBeginDeferWindowPos( + _In_ ULONG NumWindowsHint + ); + +// private // NtUserCallOneParam(SFI_GETSENDMESSAGERECEIVER) before WIN11 +_Success_(return != NULL) +_Must_inspect_result_ +NTSYSCALLAPI +HWND +NTAPI +NtUserGetSendMessageReceiver( + _In_ ULONG ThreadIdSender + ); + +// private // NtUserCallOneParam(SFI_ALLOWSETFOREGROUNDWINDOW) before WIN11 +_Success_(return != 0) +NTSYSCALLAPI +LOGICAL +NTAPI +NtUserAllowSetForegroundWindow( + _In_ ULONG ProcessId + ); + +// private // NtUserCallOneParam(SFI_CSDDEUNINITIALIZE) before WIN11 +_Success_(return != 0) +NTSYSCALLAPI +LOGICAL +NTAPI +NtUserCsDdeUninitialize( + _In_ HANDLE hInst + ); + +// private // NtUserCallOneParam(SFI_ENUMCLIPBOARDFORMATS) before WIN11 +_Success_(return != 0) +_Must_inspect_result_ +NTSYSCALLAPI +ULONG +NTAPI +NtUserEnumClipboardFormats( + _In_ ULONG Format + ); + +// private // NtUserCallOneParam(SFI_GETINPUTEVENT) before WIN11 +_Success_(return != NULL) +_Must_inspect_result_ +NTSYSCALLAPI +HANDLE +NTAPI +NtUserGetInputEvent( + _In_ ULONG WakeMask // QS_* WinUser.h + ); + +// rev (MSDN) +#define KEYBOARD_TYPE 0 +#define KEYBOARD_SUBTYPE 1 +#define KEYBOARD_FUNCTION_KEY 2 + +// private // NtUserCallOneParam(SFI_GETKEYBOARDTYPE) before WIN11 +_Must_inspect_result_ +NTSYSCALLAPI +ULONG +NTAPI +NtUserGetKeyboardType( + _In_ ULONG TypeFlag // KEYBOARD_* + ); + +// private // NtUserCallOneParam(SFI_GETPROCESSDEFAULTLAYOUT) before WIN11 +_Success_(return != 0) +NTSYSCALLAPI +LOGICAL +NTAPI +NtUserGetProcessDefaultLayout( + _Out_ PULONG DefaultLayout + ); + +// private +#define WPROTOCOLNAME_LENGTH 10 +#define WAUDIONAME_LENGTH 10 + +// private +typedef struct tagWSINFO +{ + WCHAR ProtocolName[WPROTOCOLNAME_LENGTH]; + WCHAR AudioDriverName[WAUDIONAME_LENGTH]; +} WSINFO, *PWSINFO; + +// private // NtUserCallOneParam(SFI_GETWINSTATIONINFO) before WIN11 +_Success_(return != 0) +NTSYSCALLAPI +LOGICAL +NTAPI +NtUserGetWinStationInfo( + _Out_ PWSINFO WsInfo + ); + +// private // NtUserCallOneParam(SFI_LOCKSETFOREGROUNDWINDOW) before WIN11 +_Success_(return != 0) +NTSYSCALLAPI +LOGICAL +NTAPI +NtUserLockSetForegroundWindow( + _In_ ULONG LockCode // LSFW_* WinUser.h + ); + +// private // NtUserCallOneParam(SFI_LW_LOADFONTS) before WIN11 +_Success_(return != 0) +NTSYSCALLAPI +LOGICAL +NTAPI +NtUserLW_LoadFonts( + _In_ LOGICAL Remote + ); + +// private // NtUserCallOneParam(SFI_MAPDESKTOPOBJECT) before WIN11 +_Success_(return != NULL) +_Must_inspect_result_ +_Ret_maybenull_ +NTSYSCALLAPI +PVOID +NTAPI +NtUserMapDesktopObject( + _In_ HANDLE h + ); + +// private // NtUserCallOneParam(SFI_MESSAGEBEEP) before WIN11 +_Success_(return != 0) +NTSYSCALLAPI +LOGICAL +NTAPI +NtUserMessageBeep( + _In_ ULONG Type // MB_* (MB_ICONMASK) WinUser.h + ); + +// private +#define USER_SOUND_DEFAULT 0 +#define USER_SOUND_SYSTEMHAND 1 +#define USER_SOUND_SYSTEMQUESTION 2 +#define USER_SOUND_SYSTEMEXCLAMATION 3 +#define USER_SOUND_SYSTEMASTERISK 4 +#define USER_SOUND_MENUPOPUP 5 +#define USER_SOUND_MENUCOMMAND 6 +#define USER_SOUND_OPEN 7 +#define USER_SOUND_CLOSE 8 +#define USER_SOUND_RESTOREUP 9 +#define USER_SOUND_RESTOREDOWN 10 +#define USER_SOUND_MINIMIZE 11 +#define USER_SOUND_MAXIMIZE 12 +#define USER_SOUND_SNAPSHOT 13 + +// private // NtUserCallOneParam(SFI_PLAYEVENTSOUND) before WIN11 +_Success_(return != 0) +NTSYSCALLAPI +LOGICAL +NTAPI +NtUserPlayEventSound( + _In_ ULONG idSound // USER_SOUND_* + ); + +// private // NtUserCallOneParam(SFI_POSTQUITMESSAGE) before WIN11 +_Success_(return != 0) +NTSYSCALLAPI +LOGICAL +NTAPI +NtUserPostQuitMessage( + _In_ LONG ExitCode + ); + +// private // NtUserCallOneParam(SFI_REALIZEPALETTE) before WIN11 +NTSYSCALLAPI +ULONG +NTAPI +NtUserRealizePalette( + _In_ HDC hdc + ); + +// private +#define LPK_TABBED_TEXT_OUT 0 +#define LPK_PSM_TEXT_OUT 1 +#define LPK_DRAW_TEXT_EX 2 +#define LPK_EDIT_CONTROL 3 + +// rev +#define LPK_FLAG_TABBED_TEXT_OUT (1 << LPK_TABBED_TEXT_OUT) +#define LPK_FLAG_PSM_TEXT_OUT (1 << LPK_PSM_TEXT_OUT) +#define LPK_FLAG_DRAW_TEXT_EX (1 << LPK_DRAW_TEXT_EX) +#define LPK_FLAG_EDIT_CONTROL (1 << LPK_EDIT_CONTROL) + +// private // NtUserCallOneParam(SFI_REGISTERLPK) before WIN11 +_Success_(return != 0) +NTSYSCALLAPI +LOGICAL +NTAPI +NtUserRegisterLPK( + _In_ ULONG LpkEntryPoints // LPK_FLAG_* + ); + +// private +#define RST_DONTATTACHQUEUE 0x00000001 +#define RST_DONTJOURNALATTACH 0x00000002 + +// private // NtUserCallOneParam(SFI_REGISTERSYSTEMTHREAD) before WIN11 +_Success_(return != 0) +NTSYSCALLAPI +LOGICAL +NTAPI +NtUserRegisterSystemThread( + _In_ ULONG Flags // RST_* + ); + +// private // NtUserCallOneParam(SFI_REMOTERECONNECT) before WIN11 +NTSYSCALLAPI +NTSTATUS +NTAPI +NtUserRemoteReconnect( + _In_ struct _DOCONNECTDATA* DoConnectData + ); + +// private // NtUserCallOneParam(SFI_REMOTETHINWIRESTATS) before WIN11 +NTSYSCALLAPI +NTSTATUS +NTAPI +NtUserRemoteThinwireStats( + _Out_ struct CACHE_STATISTICS* Stats + ); + +// private // NtUserCallOneParam(SFI_REMOTENOTIFY) before WIN11 +NTSYSCALLAPI +NTSTATUS +NTAPI +NtUserRemoteNotify( + _In_ struct _DONOTIFYDATA* DoNotifyData + ); + +// private // NtUserCallOneParam(SFI_REPLYMESSAGE) before WIN11 +_Success_(return != 0) +NTSYSCALLAPI +LOGICAL +NTAPI +NtUserReplyMessage( + _In_ LRESULT Result + ); + +// private // NtUserCallOneParam(SFI_SETCARETBLINKTIME) before WIN11 +_Success_(return != 0) +NTSYSCALLAPI +LOGICAL +NTAPI +NtUserSetCaretBlinkTime( + _In_ ULONG Milliseconds + ); + +// private // NtUserCallOneParam(SFI_SETDOUBLECLICKTIME) before WIN11 +_Success_(return != 0) +NTSYSCALLAPI +LOGICAL +NTAPI +NtUserSetDoubleClickTime( + _In_ ULONG Milliseconds + ); + +// private // NtUserCallOneParam(SFI_SETMESSAGEEXTRAINFO) before WIN11 +NTSYSCALLAPI +LPARAM +NTAPI +NtUserSetMessageExtraInfo( + _In_ LPARAM Param + ); + +// private // NtUserCallOneParam(SFI_SETPROCESSDEFAULTLAYOUT) before WIN11 +_Success_(return != 0) +NTSYSCALLAPI +LOGICAL +NTAPI +NtUserSetProcessDefaultLayout( + _In_ ULONG DefaultLayout // LAYOUT_* wingdi.h + ); + +// private // NtUserCallOneParam(SFI_SETWATERMARKSTRINGS) before WIN11 +_Success_(return != 0) +NTSYSCALLAPI +LOGICAL +NTAPI +NtUserSetWatermarkStrings( + _In_ PCUNICODE_STRING StringTable + ); + +// private // NtUserCallOneParam(SFI_SHOWSTARTGLASS) before WIN11 +_Success_(return != 0) +NTSYSCALLAPI +LOGICAL +NTAPI +NtUserShowStartGlass( + _In_ ULONG Timeout + ); + +// private // NtUserCallOneParam(SFI_SWAPMOUSEBUTTON) before WIN11 +NTSYSCALLAPI +LOGICAL +NTAPI +NtUserSwapMouseButton( + _In_ LOGICAL SwapButtons + ); + +// private // NtUserCallOneParam(SFI_WOWMODULEUNLOAD) before WIN11 +_Success_(return != 0) +NTSYSCALLAPI +LOGICAL +NTAPI +NtUserWOWModuleUnload( + _In_ HANDLE Module + ); + +// private // NtUserCallOneParam(SFI_DWMLOCKSCREENUPDATES) before WIN11 +NTSYSCALLAPI +ULONG_PTR +NTAPI +NtUserDwmLockScreenUpdates( + _In_ LOGICAL LockUpdates + ); + +// private // NtUserCallOneParam(SFI_ENABLESESSIONFORMMCSS) before WIN11 +_Success_(return != 0) +NTSYSCALLAPI +ULONG_PTR +NTAPI +NtUserEnableSessionForMMCSS( + _In_ LOGICAL Enable + ); + +// private // NtUserCallOneParam(SFI_SETWAITFORQUEUEATTACH) before WIN11 +NTSYSCALLAPI +LOGICAL +NTAPI +NtUserSetWaitForQueueAttach( + _In_ LOGICAL Waiting + ); + +// private // NtUserCallOneParam(SFI_THREADMESSAGEQUEUEATTACHED) before WIN11 +_Must_inspect_result_ +NTSYSCALLAPI +LOGICAL +NTAPI +NtUserThreadMessageQueueAttached( + _In_opt_ ULONG ThreadId + ); + +// private // NtUserCallOneParam(SFI_ENSUREDPIDEPSYSMETCACHEFORPLATEAU) before WIN11 +_Success_(return != 0) +NTSYSCALLAPI +LOGICAL +NTAPI +NtUserEnsureDpiDepSysMetCacheForPlateau( + _In_ ULONG Dpi + ); + +// private // NtUserCallOneParam(SFI_FORCEENABLENUMPADTRANSLATION) before WIN11 +NTSYSCALLAPI +UINT_PTR +NTAPI +NtUserForceEnableNumpadTranslation( + _In_ LOGICAL ForceNumlockTranslation + ); + +// rev // NtUserCallOneParam(SFI_SETTSFEVENTSTATE) before WIN11 +_Success_(return != 0) +NTSYSCALLAPI +LOGICAL +NTAPI +NtUserSetTSFEventState( + _In_ ULONG StateFlags + ); + +// rev // NtUserCallOneParam(SFI_SETSHELLCHANGENOTIFYHWND) before WIN11 +_Success_(return != 0) +NTSYSCALLAPI +LOGICAL +NTAPI +NtUserSetShellChangeNotifyHWND( + _In_ HWND hwnd + ); + +// private // NtUserCallHwnd(SFI_DEREGISTERSHELLHOOKWINDOW) before WIN11 +_Success_(return != 0) +NTSYSCALLAPI +LOGICAL +NTAPI +NtUserDeregisterShellHookWindow( + _In_ HWND hwnd + ); + +// rev // NtUserCallHwnd(SFI_DWP_GETENABLEDPOPUPOFFSET) before WIN11 +_Must_inspect_result_ +NTSYSCALLAPI +ULONG_PTR +NTAPI +NtUserDWP_GetEnabledPopupOffset( + _In_ HWND hwnd + ); + +// private // NtUserCallHwnd(SFI_GETMODERNAPPWINDOW) before WIN11 +_Success_(return != NULL) +_Must_inspect_result_ +NTSYSCALLAPI +HWND +NTAPI +NtUserGetModernAppWindow( + _In_ HWND ShellFrame + ); + +// private // NtUserCallHwnd(SFI_GETWINDOWCONTEXTHELPID) before WIN11 +_Must_inspect_result_ +NTSYSCALLAPI +ULONG +NTAPI +NtUserGetWindowContextHelpId( + _In_ HWND hwnd + ); + +// private // NtUserCallHwnd(SFI_REGISTERSHELLHOOKWINDOW) before WIN11 +_Success_(return != 0) +NTSYSCALLAPI +LOGICAL +NTAPI +NtUserRegisterShellHookWindow( + _In_ HWND hwnd + ); + +// private // NtUserCallHwnd(SFI_SETMSGBOX) before WIN11 +_Success_(return != 0) +NTSYSCALLAPI +LOGICAL +NTAPI +NtUserSetMsgBox( + _In_ HWND hwnd + ); + +// rev // NtUserCallHwnd[Safe](SFI_INITTHREADCOREMESSAGINGIOCP) before WIN11 +NTSYSCALLAPI +ULONG_PTR +NTAPI +NtUserInitThreadCoreMessagingIocp( + _In_ HWND hwnd + ); + +// private // NtUserCallHwnd[Safe](SFI_SCHEDULEDISPATCHNOTIFICATION) before WIN11 +_Success_(return != 0) +NTSYSCALLAPI +LOGICAL +NTAPI +NtUserScheduleDispatchNotification( + _In_ HWND hwnd + ); + +// private // NtUserCallHwndOpt(SFI_SETPROGMANWINDOW) before WIN11 +_Success_(return != 0) +NTSYSCALLAPI +LOGICAL +NTAPI +NtUserSetProgmanWindow( + _In_opt_ HWND hwnd + ); + +// private // NtUserCallHwndOpt(SFI_SETTASKMANWINDOW) before WIN11 +_Success_(return != 0) +NTSYSCALLAPI +LOGICAL +NTAPI +NtUserSetTaskmanWindow( + _In_opt_ HWND hwnd + ); + +// private // NtUserCallHwndParam(SFI_GETCLASSICOCUR) before WIN11 +_Success_(return != NULL) +_Must_inspect_result_ +NTSYSCALLAPI +HCURSOR +NTAPI +NtUserGetClassIcoCur( + _In_ HWND hwnd, + _In_ ULONG Index + ); + +// private +#define WFWIN40COMPAT 0x0502 +#define WFNOANIMATE 0x0710 +#define WEFWINDOWEDGE 0x0901 +#define WEFCLIENTEDGE 0x0902 +#define WEFSTATICEDGE 0x0A02 +#define BFRIGHTBUTTON 0x0C20 +#define BFRIGHT 0x0D02 +#define BFBOTTOM 0x0D08 +#define DFLOCALEDIT 0x0C20 +#define CBFOWNERDRAWVAR 0x0C20 +#define CBFHASSTRINGS 0x0D02 +#define CBFDISABLENOSCROLL 0x0D08 +#define EFPASSWORD 0x0C20 +#define EFCOMBOBOX 0x0D02 +#define EFREADONLY 0x0D08 +#define SFWIDELINESPACING 0x0C20 +#define SFCENTERIMAGE 0x0D02 +#define SFREALSIZEIMAGE 0x0D08 +#define WFMAXBOX 0x0E01 +#define WFTABSTOP 0x0E01 +#define WFSYSMENU 0x0E08 +#define WFHSCROLL 0x0E10 +#define WFVSCROLL 0x0E20 +#define WFBORDER 0x0E80 +#define WFCLIPCHILDREN 0x0F02 + +// private // NtUserCallHwndParam(SFI_CLEARWINDOWSTATE) before WIN11 +_Success_(return != 0) +NTSYSCALLAPI +LOGICAL +NTAPI +NtUserClearWindowState( + _In_ HWND hwnd, + _In_ ULONG Flag // WF*, WEF*, BF*, DF*, CBF*, EF*, SF* + ); + +// private // NtUserCallHwndParam(SFI_SETWINDOWSTATE) before WIN11 +_Success_(return != 0) +NTSYSCALLAPI +LOGICAL +NTAPI +NtUserSetWindowState( + _In_ HWND hwnd, + _In_ ULONG Flag // WF*, WEF*, BF*, DF*, CBF*, EF*, SF* + ); + +// private // NtUserCallHwndParam(SFI_KILLSYSTEMTIMER) before WIN11 +_Success_(return != 0) +NTSYSCALLAPI +LOGICAL +NTAPI +NtUserKillSystemTimer( + _In_ HWND hwnd, + _In_ UINT_PTR IDEvent + ); + +// private // NtUserCallHwndParam(SFI_NOTIFYOVERLAYWINDOW) before WIN11 +_Success_(return != 0) +NTSYSCALLAPI +LOGICAL +NTAPI +NtUserNotifyOverlayWindow( + _In_ HWND hwnd, + _In_ LOGICAL Enable + ); + +// private // NtUserCallHwndParam(SFI_SETDIALOGPOINTER) before WIN11 +_Success_(return != 0) +NTSYSCALLAPI +LOGICAL +NTAPI +NtUserSetDialogPointer( + _In_ HWND hwnd, + _In_ ULONG_PTR Ptr + ); + +// private +#define SV_UNSET 0x0000 +#define SV_SET 0x0001 +#define SV_CLRFTRUEVIS 0x0002 +#define SV_SKIPCOMPOSE 0x0004 // rev +#define SV_CLRFULLSCREEN 0x0008 // rev +#define SV_CLRGHOSTVIS 0x0010 // rev + +// private // NtUserCallHwndParam(SFI_SETVISIBLE) before WIN11 +_Success_(return != 0) +NTSYSCALLAPI +LOGICAL +NTAPI +NtUserSetVisible( + _In_ HWND hwnd, + _In_ ULONG Flags // SV_* + ); + +// private // NtUserCallHwndParam(SFI_SETWINDOWCONTEXTHELPID) before WIN11 +_Success_(return != 0) +NTSYSCALLAPI +LOGICAL +NTAPI +NtUserSetWindowContextHelpId( + _In_ HWND hwnd, + _In_ ULONG ContextId + ); + +// private // NtUserCallHwndParam(SFI_REGISTERWINDOWARRANGEMENTCALLOUT) before WIN11 +_Success_(return != 0) +NTSYSCALLAPI +LOGICAL +NTAPI +NtUserRegisterWindowArrangementCallout( + _In_ HWND hwnd, + _In_ LOGICAL Register + ); + +// private // NtUserCallHwndParam(SFI_ENABLEMODERNAPPWINDOWKEYBOARDINTERCEPT) before WIN11 +_Success_(return != 0) +NTSYSCALLAPI +LOGICAL +NTAPI +NtUserEnableModernAppWindowKeyboardIntercept( + _In_ HWND hwnd, + _In_ LOGICAL Enable + ); + +// private // NtUserCallHwndLock(SFI_ARRANGEICONICWINDOWS) before WIN11 +_Success_(return != 0) +NTSYSCALLAPI +ULONG +NTAPI +NtUserArrangeIconicWindows( + _In_ HWND hwnd + ); + +// private // NtUserCallHwndLock(SFI_DRAWMENUBAR) before WIN11 +_Success_(return != 0) +NTSYSCALLAPI +LOGICAL +NTAPI +NtUserDrawMenuBar( + _In_ HWND hwnd + ); + +// private // NtUserCallHwndLock[Safe](SFI_CHECKIMESHOWSTATUSINTHREAD) before WIN11 +_Success_(return != 0) +NTSYSCALLAPI +LOGICAL +NTAPI +NtUserCheckImeShowStatusInThread( + _In_ HWND Ime + ); + +// rev // NtUserCallHwndLock(SFI_GETSYSMENUOFFSET) before WIN11 +_Success_(return != 0) +_Must_inspect_result_ +NTSYSCALLAPI +ULONG_PTR +NTAPI +NtUserGetSysMenuOffset( + _In_ HWND hwnd + ); + +// private // NtUserCallHwndLock(SFI_REDRAWFRAME) before WIN11 +_Success_(return != 0) +NTSYSCALLAPI +LOGICAL +NTAPI +NtUserRedrawFrame( + _In_ HWND hwnd + ); + +// private // NtUserCallHwndLock(SFI_REDRAWFRAMEANDHOOK) before WIN11 +_Success_(return != 0) +NTSYSCALLAPI +LOGICAL +NTAPI +NtUserRedrawFrameAndHook( + _In_ HWND hwnd + ); + +// private // NtUserCallHwndLock(SFI_SETDIALOGSYSTEMMENU) before WIN11 +_Success_(return != 0) +NTSYSCALLAPI +LOGICAL +NTAPI +NtUserSetDialogSystemMenu( + _In_ HWND hwnd + ); + +// private // NtUserCallHwndLock(SFI_SETFOREGROUNDWINDOW) before WIN11 +_Success_(return != 0) +NTSYSCALLAPI +LOGICAL +NTAPI +NtUserSetForegroundWindow( + _In_ HWND hwnd + ); + +// private // NtUserCallHwndLock(SFI_SETSYSMENU) before WIN11 +_Success_(return != 0) +NTSYSCALLAPI +LOGICAL +NTAPI +NtUserSetSysMenu( + _In_ HWND hwnd + ); + +// private // NtUserCallHwndLock(SFI_UPDATECLIENTRECT) before WIN11 +_Success_(return != 0) +NTSYSCALLAPI +LOGICAL +NTAPI +NtUserUpdateClientRect( + _In_ HWND hwnd + ); + +// private // NtUserCallHwndLock(SFI_UPDATEWINDOW) before WIN11 +_Success_(return != 0) +NTSYSCALLAPI +LOGICAL +NTAPI +NtUserUpdateWindow( + _In_ HWND hwnd + ); + +// private // NtUserCallHwndLock(SFI_SETCANCELROTATIONDELAYHINTWINDOW) before WIN11 +_Success_(return != 0) +NTSYSCALLAPI +LOGICAL +NTAPI +NtUserSetCancelRotationDelayHintWindow( + _In_ HWND hwnd + ); + +// private // NtUserCallHwndLock(SFI_GETWINDOWTRACKINFOASYNC) before WIN11 +_Success_(return != 0) +NTSYSCALLAPI +ULONG_PTR +NTAPI +NtUserGetWindowTrackInfoAsync( + _In_ HWND hwnd + ); + +// private // NtUserCallHwndParamLock(SFI_BROADCASTIMESHOWSTATUSCHANGE) before WIN11 +_Success_(return != 0) +NTSYSCALLAPI +LOGICAL +NTAPI +NtUserBroadcastImeShowStatusChange( + _In_ HWND Ime, + _In_ LOGICAL Show + ); + +// private // NtUserCallHwndParamLock(SFI_SETMODERNAPPWINDOW) before WIN11 +_Success_(return != 0) +NTSYSCALLAPI +LOGICAL +NTAPI +NtUserSetModernAppWindow( + _In_ HWND ShellFrame, + _In_ HWND App + ); + +// private +// #define DC_ACTIVE 0x0001 // WinUser.h +// #define DC_SMALLCAP 0x0002 // WinUser.h +// #define DC_ICON 0x0004 // WinUser.h +// #define DC_TEXT 0x0008 // WinUser.h +// #define DC_INBUTTON 0x0010 // WinUser.h +// #define DC_GRADIENT 0x0020 // WinUser.h +#define DC_LAMEBUTTON 0x0400 +#define DC_NOVISIBLE 0x0800 +// #define DC_BUTTONS 0x1000 // WinUser.h +#define DC_NOSENDMSG 0x2000 +#define DC_CENTER 0x4000 +#define DC_FRAME 0x8000 + +// private // NtUserCallHwndParamLock(SFI_REDRAWTITLE) before WIN11 +_Success_(return != 0) +NTSYSCALLAPI +LOGICAL +NTAPI +NtUserRedrawTitle( + _In_ HWND hwnd, + _In_ ULONG Flags // DC_* + ); + +// private // NtUserCallHwndParamLock(SFI_SHOWOWNEDPOPUPS) before WIN11 +_Success_(return != 0) +NTSYSCALLAPI +LOGICAL +NTAPI +NtUserShowOwnedPopups( + _In_ HWND Owner, + _In_ LOGICAL Show + ); + +// private // NtUserCallHwndParamLock(SFI_SWITCHTOTHISWINDOW) before WIN11 +_Success_(return != 0) +NTSYSCALLAPI +LOGICAL +NTAPI +NtUserSwitchToThisWindow( + _In_ HWND hwnd, + _In_ LOGICAL AltTab + ); + +// private // NtUserCallHwndParamLock(SFI_UPDATEWINDOWS) before WIN11 +_Success_(return != 0) +NTSYSCALLAPI +LOGICAL +NTAPI +NtUserUpdateWindows( + _In_ HWND hwnd, + _In_ HRGN hrgn + ); + +// private // NtUserCallHwndParamLock(SFI_VALIDATERGN) before WIN11 +_Success_(return != 0) +NTSYSCALLAPI +LOGICAL +NTAPI +NtUserValidateRgn( + _In_ HWND hwnd, + _In_ HRGN hrgn + ); + +// private // NtUserCallHwndParamLock[Safe](SFI_ENABLEWINDOW) before WIN11 +_Success_(return != 0) +NTSYSCALLAPI +LOGICAL +NTAPI +NtUserEnableWindow( + _In_ HWND hwnd, + _In_ LOGICAL Enable + ); + +// private // NtUserCallTwoParam(SFI_CHANGEWINDOWMESSAGEFILTER) before WIN11 +_Success_(return != 0) +NTSYSCALLAPI +LOGICAL +NTAPI +NtUserChangeWindowMessageFilter( + _In_ ULONG Message, + _In_ ULONG Flag // MSGFLT_* WinUser.h + ); + +// rev +#define CURSOR_POS_TYPE_LOGICAL 1 +#define CURSOR_POS_TYPE_SAVED 2 + +// private // NtUserCallTwoParam(SFI_GETCURSORPOS) before WIN11 +_Success_(return != 0) +NTSYSCALLAPI +LOGICAL +NTAPI +NtUserGetCursorPos( + _Out_ PPOINT Point, + _In_ ULONG CursorPosType // CURSOR_POS_TYPE_* + ); + +// private // NtUserCallTwoParam(SFI_INITANSIOEM) before WIN11 +_Success_(return != 0) +NTSYSCALLAPI +LOGICAL +NTAPI +NtUserInitAnsiOem( + _In_reads_(256) PCHAR OemToAnsi, + _In_reads_(256) PCHAR AnsiToOem + ); + +// private // NtUserCallTwoParam(SFI_NLSKBDSENDIMENOTIFICATION) before WIN11 +_Success_(return != 0) +NTSYSCALLAPI +LOGICAL +NTAPI +NtUserNlsKbdSendIMENotification( + _In_ ULONG ImeOpen, + _In_ ULONG ImeConversion + ); + +// private // NtUserCallTwoParam(SFI_REGISTERGHOSTWINDOW) before WIN11 +_Success_(return != 0) +NTSYSCALLAPI +LOGICAL +NTAPI +NtUserRegisterGhostWindow( + _In_ HWND Ghost, + _In_ HWND Hung + ); + +// private // NtUserCallTwoParam(SFI_REGISTERLOGONPROCESS) before WIN11 +_Success_(return != 0) +NTSYSCALLAPI +LOGICAL +NTAPI +NtUserRegisterLogonProcess( + _In_ ULONG ProcessId, + _In_ PLUID LuidConnect + ); + +// private // NtUserCallTwoParam(SFI_REGISTERSIBLINGFROSTWINDOW) before WIN11 +_Success_(return != 0) +NTSYSCALLAPI +LOGICAL +NTAPI +NtUserRegisterSiblingFrostWindow( + _In_ HWND hwndFrost, + _In_ HWND hwnd + ); + +// rev +typedef _Function_class_(FNW32ET) +VOID APIENTRY FNW32ET(VOID); +typedef FNW32ET* PFNW32ET; + +// private // NtUserCallTwoParam(SFI_REGISTERUSERHUNGAPPHANDLERS) before WIN11 +_Success_(return != 0) +NTSYSCALLAPI +LOGICAL +NTAPI +NtUserRegisterUserHungAppHandlers( + _In_ PFNW32ET W32EndTask, + _In_ HANDLE EventWowExec + ); + +// private // NtUserCallTwoParam(SFI_REMOTESHADOWCLEANUP) before WIN11 +NTSYSCALLAPI +NTSTATUS +NTAPI +NtUserRemoteShadowCleanup( + _In_reads_bytes_(ThinwireDataLength) PVOID ThinwireData, + _In_ ULONG ThinwireDataLength + ); + +// private // NtUserCallTwoParam(SFI_REMOTESHADOWSTART) before WIN11 +NTSYSCALLAPI +NTSTATUS +NTAPI +NtUserRemoteShadowStart( + _In_reads_bytes_(ThinwireDataLength) PVOID ThinwireData, + _In_ ULONG ThinwireDataLength + ); + +// private // NtUserCallTwoParam(SFI_SETCARETPOS) before WIN11 +_Success_(return != 0) +NTSYSCALLAPI +LOGICAL +NTAPI +NtUserSetCaretPos( + _In_ LONG x, + _In_ LONG y + ); + +// private // NtUserCallTwoParam(SFI_SETTHREADQUEUEMERGESETTING) before WIN11 +_Success_(return != 0) +NTSYSCALLAPI +LOGICAL +NTAPI +NtUserSetThreadQueueMergeSetting( + _In_ ULONG ThreadId, + _In_ ULONG Flags + ); + +// private // NtUserCallTwoParam(SFI_UNHOOKWINDOWSHOOK) before WIN11 +_Success_(return != 0) +NTSYSCALLAPI +LOGICAL +NTAPI +NtUserUnhookWindowsHook( + _In_ LONG FilterType, + _In_ HOOKPROC FilterProc + ); + +// private // NtUserCallTwoParam(SFI_ENABLESHELLWINDOWMANAGEMENTBEHAVIOR) before WIN11 +_Success_(return != 0) +NTSYSCALLAPI +LOGICAL +NTAPI +NtUserEnableShellWindowManagementBehavior( + _In_ ULONG_PTR Param1, + _In_ ULONG_PTR Param2 + ); + +// private // NtUserCallTwoParam(SFI_CITSETINFO) before WIN11 +NTSYSCALLAPI +NTSTATUS +NTAPI +NtUserCitSetInfo( + _In_ ULONG_PTR InfoFlags, + _In_ ULONG_PTR Info + ); + +// private // NtUserCallTwoParam(SFI_SCALESYSTEMMETRICFORDPIWITHOUTCACHE) before WIN11 +_Must_inspect_result_ +NTSYSCALLAPI +ULONG_PTR +NTAPI +NtUserScaleSystemMetricForDPIWithoutCache( + _In_ ULONG Metric, + _In_ ULONG ToDpi + ); + +#endif // PHNT_VERSION >= PHNT_WINDOWS_11 + +typedef _Function_class_(FN_DISPATCH) +NTSTATUS NTAPI FN_DISPATCH( + _In_opt_ PVOID Context + ); +typedef FN_DISPATCH* PFN_DISPATCH; + // Peb!KernelCallbackTable = user32.dll!apfnDispatch typedef struct _KERNEL_CALLBACK_TABLE { - PVOID __fnCOPYDATA; - PVOID __fnCOPYGLOBALDATA; - PVOID __fnEMPTY1; - PVOID __fnNCDESTROY; - PVOID __fnDWORDOPTINLPMSG; - PVOID __fnINOUTDRAG; - PVOID __fnGETTEXTLENGTHS1; - PVOID __fnINCNTOUTSTRING; - PVOID __fnINCNTOUTSTRINGNULL; - PVOID __fnINLPCOMPAREITEMSTRUCT; - PVOID __fnINLPCREATESTRUCT; - PVOID __fnINLPDELETEITEMSTRUCT; - PVOID __fnINLPDRAWITEMSTRUCT; - PVOID __fnPOPTINLPUINT1; - PVOID __fnPOPTINLPUINT2; - PVOID __fnINLPMDICREATESTRUCT; - PVOID __fnINOUTLPMEASUREITEMSTRUCT; - PVOID __fnINLPWINDOWPOS; - PVOID __fnINOUTLPPOINT51; - PVOID __fnINOUTLPSCROLLINFO; - PVOID __fnINOUTLPRECT; - PVOID __fnINOUTNCCALCSIZE; - PVOID __fnINOUTLPPOINT52; - PVOID __fnINPAINTCLIPBRD; - PVOID __fnINSIZECLIPBRD; - PVOID __fnINDESTROYCLIPBRD; - PVOID __fnINSTRINGNULL1; - PVOID __fnINSTRINGNULL2; - PVOID __fnINDEVICECHANGE; - PVOID __fnPOWERBROADCAST; - PVOID __fnINLPUAHDRAWMENU1; - PVOID __fnOPTOUTLPDWORDOPTOUTLPDWORD1; - PVOID __fnOPTOUTLPDWORDOPTOUTLPDWORD2; - PVOID __fnOUTDWORDINDWORD; - PVOID __fnOUTLPRECT; - PVOID __fnOUTSTRING; - PVOID __fnPOPTINLPUINT3; - PVOID __fnPOUTLPINT; - PVOID __fnSENTDDEMSG; - PVOID __fnINOUTSTYLECHANGE1; - PVOID __fnHkINDWORD; - PVOID __fnHkINLPCBTACTIVATESTRUCT; - PVOID __fnHkINLPCBTCREATESTRUCT; - PVOID __fnHkINLPDEBUGHOOKSTRUCT; - PVOID __fnHkINLPMOUSEHOOKSTRUCTEX1; - PVOID __fnHkINLPKBDLLHOOKSTRUCT; - PVOID __fnHkINLPMSLLHOOKSTRUCT; - PVOID __fnHkINLPMSG; - PVOID __fnHkINLPRECT; - PVOID __fnHkOPTINLPEVENTMSG; - PVOID __xxxClientCallDelegateThread; - PVOID __ClientCallDummyCallback1; - PVOID __ClientCallDummyCallback2; - PVOID __fnSHELLWINDOWMANAGEMENTCALLOUT; - PVOID __fnSHELLWINDOWMANAGEMENTNOTIFY; - PVOID __ClientCallDummyCallback3; - PVOID __xxxClientCallDitThread; - PVOID __xxxClientEnableMMCSS; - PVOID __xxxClientUpdateDpi; - PVOID __xxxClientExpandStringW; - PVOID __ClientCopyDDEIn1; - PVOID __ClientCopyDDEIn2; - PVOID __ClientCopyDDEOut1; - PVOID __ClientCopyDDEOut2; - PVOID __ClientCopyImage; - PVOID __ClientEventCallback; - PVOID __ClientFindMnemChar; - PVOID __ClientFreeDDEHandle; - PVOID __ClientFreeLibrary; - PVOID __ClientGetCharsetInfo; - PVOID __ClientGetDDEFlags; - PVOID __ClientGetDDEHookData; - PVOID __ClientGetListboxString; - PVOID __ClientGetMessageMPH; - PVOID __ClientLoadImage; - PVOID __ClientLoadLibrary; - PVOID __ClientLoadMenu; - PVOID __ClientLoadLocalT1Fonts; - PVOID __ClientPSMTextOut; - PVOID __ClientLpkDrawTextEx; - PVOID __ClientExtTextOutW; - PVOID __ClientGetTextExtentPointW; - PVOID __ClientCharToWchar; - PVOID __ClientAddFontResourceW; - PVOID __ClientThreadSetup; - PVOID __ClientDeliverUserApc; - PVOID __ClientNoMemoryPopup; - PVOID __ClientMonitorEnumProc; - PVOID __ClientCallWinEventProc; - PVOID __ClientWaitMessageExMPH; - PVOID __ClientCallDummyCallback4; - PVOID __ClientCallDummyCallback5; - PVOID __ClientImmLoadLayout; - PVOID __ClientImmProcessKey; - PVOID __fnIMECONTROL; - PVOID __fnINWPARAMDBCSCHAR; - PVOID __fnGETTEXTLENGTHS2; - PVOID __ClientCallDummyCallback6; - PVOID __ClientLoadStringW; - PVOID __ClientLoadOLE; - PVOID __ClientRegisterDragDrop; - PVOID __ClientRevokeDragDrop; - PVOID __fnINOUTMENUGETOBJECT; - PVOID __ClientPrinterThunk; - PVOID __fnOUTLPCOMBOBOXINFO; - PVOID __fnOUTLPSCROLLBARINFO; - PVOID __fnINLPUAHDRAWMENU2; - PVOID __fnINLPUAHDRAWMENUITEM; - PVOID __fnINLPUAHDRAWMENU3; - PVOID __fnINOUTLPUAHMEASUREMENUITEM; - PVOID __fnINLPUAHDRAWMENU4; - PVOID __fnOUTLPTITLEBARINFOEX; - PVOID __fnTOUCH; - PVOID __fnGESTURE; - PVOID __fnPOPTINLPUINT4; - PVOID __fnPOPTINLPUINT5; - PVOID __xxxClientCallDefaultInputHandler; - PVOID __fnEMPTY2; - PVOID __ClientRimDevCallback; - PVOID __xxxClientCallMinTouchHitTestingCallback; - PVOID __ClientCallLocalMouseHooks; - PVOID __xxxClientBroadcastThemeChange; - PVOID __xxxClientCallDevCallbackSimple; - PVOID __xxxClientAllocWindowClassExtraBytes; - PVOID __xxxClientFreeWindowClassExtraBytes; - PVOID __fnGETWINDOWDATA; - PVOID __fnINOUTSTYLECHANGE2; - PVOID __fnHkINLPMOUSEHOOKSTRUCTEX2; - PVOID __xxxClientCallDefWindowProc; - PVOID __fnSHELLSYNCDISPLAYCHANGED; - PVOID __fnHkINLPCHARHOOKSTRUCT; - PVOID __fnINTERCEPTEDWINDOWACTION; - PVOID __xxxTooltipCallback; - PVOID __xxxClientInitPSBInfo; - PVOID __xxxClientDoScrollMenu; - PVOID __xxxClientEndScroll; - PVOID __xxxClientDrawSize; - PVOID __xxxClientDrawScrollBar; - PVOID __xxxClientHitTestScrollBar; - PVOID __xxxClientTrackInit; + PFN_DISPATCH __fnCOPYDATA; + PFN_DISPATCH __fnCOPYGLOBALDATA; + PFN_DISPATCH __fnEMPTY1; + PFN_DISPATCH __fnNCDESTROY; + PFN_DISPATCH __fnDWORDOPTINLPMSG; + PFN_DISPATCH __fnINOUTDRAG; + PFN_DISPATCH __fnGETTEXTLENGTHS1; + PFN_DISPATCH __fnINCNTOUTSTRING; + PFN_DISPATCH __fnINCNTOUTSTRINGNULL; + PFN_DISPATCH __fnINLPCOMPAREITEMSTRUCT; + PFN_DISPATCH __fnINLPCREATESTRUCT; + PFN_DISPATCH __fnINLPDELETEITEMSTRUCT; + PFN_DISPATCH __fnINLPDRAWITEMSTRUCT; + PFN_DISPATCH __fnPOPTINLPUINT1; + PFN_DISPATCH __fnPOPTINLPUINT2; + PFN_DISPATCH __fnINLPMDICREATESTRUCT; + PFN_DISPATCH __fnINOUTLPMEASUREITEMSTRUCT; + PFN_DISPATCH __fnINLPWINDOWPOS; + PFN_DISPATCH __fnINOUTLPPOINT51; + PFN_DISPATCH __fnINOUTLPSCROLLINFO; + PFN_DISPATCH __fnINOUTLPRECT; + PFN_DISPATCH __fnINOUTNCCALCSIZE; + PFN_DISPATCH __fnINOUTLPPOINT52; + PFN_DISPATCH __fnINPAINTCLIPBRD; + PFN_DISPATCH __fnINSIZECLIPBRD; + PFN_DISPATCH __fnINDESTROYCLIPBRD; + PFN_DISPATCH __fnINSTRINGNULL1; + PFN_DISPATCH __fnINSTRINGNULL2; + PFN_DISPATCH __fnINDEVICECHANGE; + PFN_DISPATCH __fnPOWERBROADCAST; + PFN_DISPATCH __fnINLPUAHDRAWMENU1; + PFN_DISPATCH __fnOPTOUTLPDWORDOPTOUTLPDWORD1; + PFN_DISPATCH __fnOPTOUTLPDWORDOPTOUTLPDWORD2; + PFN_DISPATCH __fnOUTDWORDINDWORD; + PFN_DISPATCH __fnOUTLPRECT; + PFN_DISPATCH __fnOUTSTRING; + PFN_DISPATCH __fnPOPTINLPUINT3; + PFN_DISPATCH __fnPOUTLPINT; + PFN_DISPATCH __fnSENTDDEMSG; + PFN_DISPATCH __fnINOUTSTYLECHANGE1; + PFN_DISPATCH __fnHkINDWORD; + PFN_DISPATCH __fnHkINLPCBTACTIVATESTRUCT; + PFN_DISPATCH __fnHkINLPCBTCREATESTRUCT; + PFN_DISPATCH __fnHkINLPDEBUGHOOKSTRUCT; + PFN_DISPATCH __fnHkINLPMOUSEHOOKSTRUCTEX1; + PFN_DISPATCH __fnHkINLPKBDLLHOOKSTRUCT; + PFN_DISPATCH __fnHkINLPMSLLHOOKSTRUCT; + PFN_DISPATCH __fnHkINLPMSG; + PFN_DISPATCH __fnHkINLPRECT; + PFN_DISPATCH __fnHkOPTINLPEVENTMSG; + PFN_DISPATCH __xxxClientCallDelegateThread; + PFN_DISPATCH __ClientCallDummyCallback1; + PFN_DISPATCH __ClientCallDummyCallback2; + PFN_DISPATCH __fnSHELLWINDOWMANAGEMENTCALLOUT; + PFN_DISPATCH __fnSHELLWINDOWMANAGEMENTNOTIFY; + PFN_DISPATCH __ClientCallDummyCallback3; + PFN_DISPATCH __xxxClientCallDitThread; + PFN_DISPATCH __xxxClientEnableMMCSS; + PFN_DISPATCH __xxxClientUpdateDpi; + PFN_DISPATCH __xxxClientExpandStringW; + PFN_DISPATCH __ClientCopyDDEIn1; + PFN_DISPATCH __ClientCopyDDEIn2; + PFN_DISPATCH __ClientCopyDDEOut1; + PFN_DISPATCH __ClientCopyDDEOut2; + PFN_DISPATCH __ClientCopyImage; + PFN_DISPATCH __ClientEventCallback; + PFN_DISPATCH __ClientFindMnemChar; + PFN_DISPATCH __ClientFreeDDEHandle; + PFN_DISPATCH __ClientFreeLibrary; + PFN_DISPATCH __ClientGetCharsetInfo; + PFN_DISPATCH __ClientGetDDEFlags; + PFN_DISPATCH __ClientGetDDEHookData; + PFN_DISPATCH __ClientGetListboxString; + PFN_DISPATCH __ClientGetMessageMPH; + PFN_DISPATCH __ClientLoadImage; + PFN_DISPATCH __ClientLoadLibrary; + PFN_DISPATCH __ClientLoadMenu; + PFN_DISPATCH __ClientLoadLocalT1Fonts; + PFN_DISPATCH __ClientPSMTextOut; + PFN_DISPATCH __ClientLpkDrawTextEx; + PFN_DISPATCH __ClientExtTextOutW; + PFN_DISPATCH __ClientGetTextExtentPointW; + PFN_DISPATCH __ClientCharToWchar; + PFN_DISPATCH __ClientAddFontResourceW; + PFN_DISPATCH __ClientThreadSetup; + PFN_DISPATCH __ClientDeliverUserApc; + PFN_DISPATCH __ClientNoMemoryPopup; + PFN_DISPATCH __ClientMonitorEnumProc; + PFN_DISPATCH __ClientCallWinEventProc; + PFN_DISPATCH __ClientWaitMessageExMPH; + PFN_DISPATCH __ClientCallDummyCallback4; + PFN_DISPATCH __ClientCallDummyCallback5; + PFN_DISPATCH __ClientImmLoadLayout; + PFN_DISPATCH __ClientImmProcessKey; + PFN_DISPATCH __fnIMECONTROL; + PFN_DISPATCH __fnINWPARAMDBCSCHAR; + PFN_DISPATCH __fnGETTEXTLENGTHS2; + PFN_DISPATCH __ClientCallDummyCallback6; + PFN_DISPATCH __ClientLoadStringW; + PFN_DISPATCH __ClientLoadOLE; + PFN_DISPATCH __ClientRegisterDragDrop; + PFN_DISPATCH __ClientRevokeDragDrop; + PFN_DISPATCH __fnINOUTMENUGETOBJECT; + PFN_DISPATCH __ClientPrinterThunk; + PFN_DISPATCH __fnOUTLPCOMBOBOXINFO; + PFN_DISPATCH __fnOUTLPSCROLLBARINFO; + PFN_DISPATCH __fnINLPUAHDRAWMENU2; + PFN_DISPATCH __fnINLPUAHDRAWMENUITEM; + PFN_DISPATCH __fnINLPUAHDRAWMENU3; + PFN_DISPATCH __fnINOUTLPUAHMEASUREMENUITEM; + PFN_DISPATCH __fnINLPUAHDRAWMENU4; + PFN_DISPATCH __fnOUTLPTITLEBARINFOEX; + PFN_DISPATCH __fnTOUCH; + PFN_DISPATCH __fnGESTURE; + PFN_DISPATCH __fnPOPTINLPUINT4; + PFN_DISPATCH __fnPOPTINLPUINT5; + PFN_DISPATCH __xxxClientCallDefaultInputHandler; + PFN_DISPATCH __fnEMPTY2; + PFN_DISPATCH __ClientRimDevCallback; + PFN_DISPATCH __xxxClientCallMinTouchHitTestingCallback; + PFN_DISPATCH __ClientCallLocalMouseHooks; + PFN_DISPATCH __xxxClientBroadcastThemeChange; + PFN_DISPATCH __xxxClientCallDevCallbackSimple; + PFN_DISPATCH __xxxClientAllocWindowClassExtraBytes; + PFN_DISPATCH __xxxClientFreeWindowClassExtraBytes; + PFN_DISPATCH __fnGETWINDOWDATA; + PFN_DISPATCH __fnINOUTSTYLECHANGE2; + PFN_DISPATCH __fnHkINLPMOUSEHOOKSTRUCTEX2; + PFN_DISPATCH __xxxClientCallDefWindowProc; + PFN_DISPATCH __fnSHELLSYNCDISPLAYCHANGED; + PFN_DISPATCH __fnHkINLPCHARHOOKSTRUCT; + PFN_DISPATCH __fnINTERCEPTEDWINDOWACTION; + PFN_DISPATCH __xxxTooltipCallback; + PFN_DISPATCH __xxxClientInitPSBInfo; + PFN_DISPATCH __xxxClientDoScrollMenu; + PFN_DISPATCH __xxxClientEndScroll; + PFN_DISPATCH __xxxClientDrawSize; + PFN_DISPATCH __xxxClientDrawScrollBar; + PFN_DISPATCH __xxxClientHitTestScrollBar; + PFN_DISPATCH __xxxClientTrackInit; } KERNEL_CALLBACK_TABLE, *PKERNEL_CALLBACK_TABLE; -#endif +#endif // _NTUSER_H diff --git a/ntwmi.h b/ntwmi.h index bb08ab8..694ff71 100644 --- a/ntwmi.h +++ b/ntwmi.h @@ -7,8 +7,6 @@ #ifndef _NTWMI_H #define _NTWMI_H -EXTERN_C_START - #ifndef _TRACEHANDLE_DEFINED #define _TRACEHANDLE_DEFINED // Obsolete - prefer PROCESSTRACE_HANDLE or CONTROLTRACE_ID. @@ -472,6 +470,23 @@ typedef enum _ETW_RT_EVENT_LOSS EtwRtEventLossMax } ETW_RT_EVENT_LOSS, *PETW_RT_EVENT_LOSS; +// +// Processor and logger ID context embedded in every ETW buffer. +// +//typedef struct _ETW_BUFFER_CONTEXT +//{ +// union +// { +// struct +// { +// UCHAR ProcessorNumber; +// UCHAR Alignment; +// }; +// USHORT ProcessorIndex; +// }; +// USHORT LoggerId; +//} ETW_BUFFER_CONTEXT, *PETW_BUFFER_CONTEXT; + typedef struct _WMI_BUFFER_HEADER *PWMI_BUFFER_HEADER; typedef struct _WMI_BUFFER_HEADER @@ -514,16 +529,16 @@ typedef struct _WMI_BUFFER_HEADER } WMI_BUFFER_HEADER, *PWMI_BUFFER_HEADER; static_assert(sizeof(WMI_BUFFER_HEADER) == 0x48, "WMI_BUFFER_HEADER must equal 0x48"); -C_ASSERT(FIELD_OFFSET(WMI_BUFFER_HEADER, BufferSize) == 0x0); -C_ASSERT(FIELD_OFFSET(WMI_BUFFER_HEADER, SavedOffset) == 0x4); -C_ASSERT(FIELD_OFFSET(WMI_BUFFER_HEADER, CurrentOffset) == 0x8); -C_ASSERT(FIELD_OFFSET(WMI_BUFFER_HEADER, TimeStamp) == 0x10); -C_ASSERT(FIELD_OFFSET(WMI_BUFFER_HEADER, SlistEntry) == 0x20); -C_ASSERT(FIELD_OFFSET(WMI_BUFFER_HEADER, ClientContext) == 0x28); -C_ASSERT(FIELD_OFFSET(WMI_BUFFER_HEADER, State) == 0x2c); // Compression -C_ASSERT(FIELD_OFFSET(WMI_BUFFER_HEADER, Offset) == 0x30); -C_ASSERT(FIELD_OFFSET(WMI_BUFFER_HEADER, BufferFlag) == 0x34); -C_ASSERT(FIELD_OFFSET(WMI_BUFFER_HEADER, BufferType) == 0x36); +static_assert(FIELD_OFFSET(WMI_BUFFER_HEADER, BufferSize) == 0x0); +static_assert(FIELD_OFFSET(WMI_BUFFER_HEADER, SavedOffset) == 0x4); +static_assert(FIELD_OFFSET(WMI_BUFFER_HEADER, CurrentOffset) == 0x8); +static_assert(FIELD_OFFSET(WMI_BUFFER_HEADER, TimeStamp) == 0x10); +static_assert(FIELD_OFFSET(WMI_BUFFER_HEADER, SlistEntry) == 0x20); +static_assert(FIELD_OFFSET(WMI_BUFFER_HEADER, ClientContext) == 0x28); +static_assert(FIELD_OFFSET(WMI_BUFFER_HEADER, State) == 0x2c); // Compression +static_assert(FIELD_OFFSET(WMI_BUFFER_HEADER, Offset) == 0x30); +static_assert(FIELD_OFFSET(WMI_BUFFER_HEADER, BufferFlag) == 0x34); +static_assert(FIELD_OFFSET(WMI_BUFFER_HEADER, BufferType) == 0x36); typedef struct _TRACE_ENABLE_FLAG_EXTENSION { @@ -569,6 +584,26 @@ typedef struct _ETW_STACK_CACHING_CONFIG ULONG BucketCount; } ETW_STACK_CACHING_CONFIG, *PETW_STACK_CACHING_CONFIG; +// +// Compact record of the last enable notification sent to a provider. +// +typedef struct _ETW_LAST_ENABLE_INFO +{ + ULONGLONG EnableFlags; // MatchAnyKeyword (combined enable keyword mask) + USHORT LoggerId; + UCHAR Level; + union + { + struct + { + UCHAR Enabled : 1; + UCHAR InternalFlag : 7; + }; + UCHAR AllFlags; + }; + ULONG Reserved; +} ETW_LAST_ENABLE_INFO, *PETW_LAST_ENABLE_INFO; + #endif // ifndef ETW_WOW6432 #define PERFINFO_APPLY_OFFSET_GIVING_TYPE(_Base, _Offset, _Type) ((_Type) (((PPERF_BYTE) (_Base)) + (_Offset))) @@ -594,6 +629,15 @@ typedef struct _PERFINFO_GROUPMASK #define PERF_GET_MASK_INDEX(GM) (((GM) & PERF_MASK_INDEX) >> 29) #define PERF_GET_MASK_GROUP(GM) ((GM) & PERF_MASK_GROUP) +// Event id packing in kernel system events is Group (bits 8..12) + Type (bits 0..7). +// Disassembly evidence: EtwpLogKernelEvent indexes per-event state with (EventId & 0x1FFF). +#define PERF_EVENT_TYPE_MASK 0x00FF +#define PERF_EVENT_GROUP_MASK 0x1F00 +#define PERF_EVENT_ID_MASK 0x1FFF + +#define PERF_GET_EVENT_TYPE(x) ((x) & PERF_EVENT_TYPE_MASK) +#define PERF_GET_EVENT_GROUP(x) ((x) & PERF_EVENT_GROUP_MASK) + #define PERFINFO_CLEAR_GROUPMASK(GroupMask) RtlZeroMemory((GroupMask), sizeof(PERFINFO_GROUPMASK)) #define PERFINFO_OR_GROUP_WITH_GROUPMASK(Group, GroupMask) (GroupMask)->Masks[PERF_GET_MASK_INDEX(Group)] |= PERF_GET_MASK_GROUP(Group) #define PERFINFO_CLEAR_GROUP_IN_GROUPMASK(Group, GroupMask) (GroupMask)->Masks[PERF_GET_MASK_INDEX(Group)] &= (~PERF_GET_MASK_GROUP(Group)) @@ -2669,13 +2713,16 @@ typedef struct _ETW_OBJECT_TYPE_EVENT WCHAR Name[ANYSIZE_ARRAY]; } ETW_OBJECT_TYPE_EVENT, *PETW_OBJECT_TYPE_EVENT; +#include typedef struct _ETW_OBJECT_HANDLE_EVENT { PVOID Object; ULONG ProcessId; ULONG Handle; USHORT ObjectType; + WCHAR ObjectName[ANYSIZE_ARRAY]; } ETW_OBJECT_HANDLE_EVENT, *PETW_OBJECT_HANDLE_EVENT; +#include typedef struct _ETW_REFDEREF_OBJECT_EVENT { @@ -2711,9 +2758,7 @@ typedef struct _ETW_HEAP_EVENT_COMMON SYSTEM_TRACE_HEADER Header; // Header PVOID Handle; // Handle of Heap } ETW_HEAP_EVENT_COMMON, *PETW_HEAP_EVENT_COMMON; -#include -#include typedef struct _ETW_HEAP_EVENT_ALLOC { SYSTEM_TRACE_HEADER Header; // Header @@ -2723,9 +2768,7 @@ typedef struct _ETW_HEAP_EVENT_ALLOC ULONG Source; // Type ie Lookaside, Lowfrag or main path } ETW_HEAP_EVENT_ALLOC, *PETW_HEAP_EVENT_ALLOC; -#include -#include typedef struct _ETW_HEAP_EVENT_FREE { SYSTEM_TRACE_HEADER Header; // Header @@ -2734,9 +2777,7 @@ typedef struct _ETW_HEAP_EVENT_FREE ULONG Source; // Type ie Lookaside, Lowfrag or main path } ETW_HEAP_EVENT_FREE, *PETW_HEAP_EVENT_FREE; -#include -#include typedef struct _ETW_HEAP_EVENT_REALLOC { SYSTEM_TRACE_HEADER Header; // Header @@ -2747,9 +2788,7 @@ typedef struct _ETW_HEAP_EVENT_REALLOC SIZE_T OldSize; // Old Size in bytes ULONG Source; // Type ie Lookaside, Lowfrag or main path } ETW_HEAP_EVENT_REALLOC, *PETW_HEAP_EVENT_REALLOC; -#include -#include typedef struct _ETW_HEAP_EVENT_EXPANSION { SYSTEM_TRACE_HEADER Header; // Header @@ -2762,9 +2801,7 @@ typedef struct _ETW_HEAP_EVENT_EXPANSION ULONG NoOfUCRs; // Number of uncommitted ranges SIZE_T AllocatedSpace; // Memory allocated } ETW_HEAP_EVENT_EXPANSION, *PETW_HEAP_EVENT_EXPANSION; -#include -#include typedef struct _ETW_HEAP_EVENT_CONTRACTION { SYSTEM_TRACE_HEADER Header; // Header @@ -2778,9 +2815,7 @@ typedef struct _ETW_HEAP_EVENT_CONTRACTION SIZE_T AllocatedSpace; // Memory allocated } ETW_HEAP_EVENT_CONTRACTION, *PETW_HEAP_EVENT_CONTRACTION; -#include -#include typedef struct _ETW_HEAP_EVENT_CREATE { SYSTEM_TRACE_HEADER Header; // Header @@ -2850,18 +2885,14 @@ typedef struct _HEAP_SUBSEGMENT_INIT SIZE_T BlockCount; ULONG AffinityIndex; } HEAP_SUBSEGMENT_INIT, *PHEAP_SUBSEGMENT_INIT; -#include -#include typedef struct _HEAP_AFFINITY_MANAGER_ENABLE { SYSTEM_TRACE_HEADER Header; PVOID HeapHandle; ULONG BucketIndex; } HEAP_AFFINITY_MANAGER_ENABLE, *PHEAP_AFFINITY_MANAGER_ENABLE; -#include -#include typedef struct _HEAP_AFFINITY_SLOT_ASSIGN { SYSTEM_TRACE_HEADER Header; @@ -2869,9 +2900,7 @@ typedef struct _HEAP_AFFINITY_SLOT_ASSIGN PVOID SubSegment; ULONG SlotIndex; } HEAP_AFFINITY_SLOT_ASSIGN, *PHEAP_AFFINITY_SLOT_ASSIGN; -#include -#include typedef struct _HEAP_REUSE_THRESHOLD_ACTIVATED { SYSTEM_TRACE_HEADER Header; @@ -2879,18 +2908,14 @@ typedef struct _HEAP_REUSE_THRESHOLD_ACTIVATED PVOID SubSegment; ULONG BucketIndex; } HEAP_REUSE_THRESHOLD_ACTIVATED, *PHEAP_REUSE_THRESHOLD_ACTIVATED; -#include -#include typedef struct _HEAP_SUBSEGMENT_ACTIVATED { SYSTEM_TRACE_HEADER Header; PVOID HeapHandle; PVOID SubSegment; } HEAP_SUBSEGMENT_ACTIVATED, *PHEAP_SUBSEGMENT_ACTIVATED; -#include -#include typedef struct _ETW_HEAP_EVENT_SNAPSHOT { SYSTEM_TRACE_HEADER Header; // Header @@ -2905,17 +2930,13 @@ typedef struct _ETW_HEAP_EVENT_SNAPSHOT ULONG UCRLength; SIZE_T AllocatedSpace; // Total allocated space in heap, in bytes } ETW_HEAP_EVENT_SNAPSHOT, *PETW_HEAP_EVENT_SNAPSHOT; -#include -#include typedef struct _ETW_HEAP_EVENT_RUNDOWN_RANGE { PVOID Address; SIZE_T Size; } ETW_HEAP_EVENT_RUNDOWN_RANGE, *PETW_HEAP_EVENT_RUNDOWN_RANGE; -#include -#include typedef struct _ETW_HEAP_EVENT_RUNDOWN { SYSTEM_TRACE_HEADER Header; // Header @@ -3733,6 +3754,10 @@ DEFINE_GUID( /* e46eead8-0c54-4489-9898-8fa79d059e0e */ // 0xae, 0xfc, 0xdc, 0x0f, 0x1d, 0x2f, 0xd2, 0x35 // ); +/** + * The ETW class GUID for file I/O events. + * \sa https://learn.microsoft.com/en-us/windows/win32/etw/fileio + */ DEFINE_GUID( /* 90cbdc39-4a3e-11d1-84f4-0000f80464e3 */ FileIoGuid, 0x90cbdc39, @@ -3741,6 +3766,10 @@ DEFINE_GUID( /* 90cbdc39-4a3e-11d1-84f4-0000f80464e3 */ 0x84, 0xf4, 0x00, 0x00, 0xf8, 0x04, 0x64, 0xe3 ); +/** + * The ETW class GUID for image load events. + * \sa https://learn.microsoft.com/en-us/windows/win32/etw/image + */ DEFINE_GUID( /* 2cb15d1d-5fc1-11d2-abe1-00a0c911f518 */ ImageLoadGuid, 0x2cb15d1d, @@ -3749,6 +3778,10 @@ DEFINE_GUID( /* 2cb15d1d-5fc1-11d2-abe1-00a0c911f518 */ 0xab, 0xe1, 0x00, 0xa0, 0xc9, 0x11, 0xf5, 0x18 ); +/** + * The ETW class GUID for page fault events. + * \sa https://learn.microsoft.com/en-us/windows/win32/etw/pagefault-v2 + */ DEFINE_GUID( /* 3d6fa8d3-fe05-11d0-9dda-00c04fd7ba7c */ PageFaultGuid, 0x3d6fa8d3, @@ -3757,6 +3790,10 @@ DEFINE_GUID( /* 3d6fa8d3-fe05-11d0-9dda-00c04fd7ba7c */ 0x9d, 0xda, 0x00, 0xc0, 0x4f, 0xd7, 0xba, 0x7c ); +/** + * The ETW class GUID for registry events. + * \sa https://learn.microsoft.com/en-us/windows/win32/etw/registry + */ DEFINE_GUID( /* AE53722E-C863-11d2-8659-00C04FA321A1 */ RegistryGuid, 0xae53722e, @@ -3765,6 +3802,10 @@ DEFINE_GUID( /* AE53722E-C863-11d2-8659-00C04FA321A1 */ 0x86, 0x59, 0x0, 0xc0, 0x4f, 0xa3, 0x21, 0xa1 ); +/** + * The ETW class GUID for TCP/IP events. + * \sa https://learn.microsoft.com/en-us/windows/win32/etw/tcpip + */ DEFINE_GUID( /* 9a280ac0-c8e0-11d1-84e2-00c04fb998a2 */ TcpIpGuid, 0x9a280ac0, @@ -3773,6 +3814,10 @@ DEFINE_GUID( /* 9a280ac0-c8e0-11d1-84e2-00c04fb998a2 */ 0x84, 0xe2, 0x00, 0xc0, 0x4f, 0xb9, 0x98, 0xa2 ); +/** + * The ETW class GUID for thread events. + * \sa https://learn.microsoft.com/en-us/windows/win32/etw/thread + */ DEFINE_GUID( /* 3d6fa8d1-fe05-11d0-9dda-00c04fd7ba7c */ ThreadGuid, 0x3d6fa8d1, @@ -3781,6 +3826,10 @@ DEFINE_GUID( /* 3d6fa8d1-fe05-11d0-9dda-00c04fd7ba7c */ 0x9d, 0xda, 0x00, 0xc0, 0x4f, 0xd7, 0xba, 0x7c ); +/** + * The ETW class GUID for UDP/IP events. + * \sa https://learn.microsoft.com/en-us/windows/win32/etw/udpip + */ DEFINE_GUID( /* bf3a50c5-a9c9-4988-a005-2df0b7c80f80 */ UdpIpGuid, 0xbf3a50c5, @@ -3789,6 +3838,17 @@ DEFINE_GUID( /* bf3a50c5-a9c9-4988-a005-2df0b7c80f80 */ 0xa0, 0x05, 0x2d, 0xf0, 0xb7, 0xc8, 0x0f, 0x80 ); +/** + * The ETW class GUID for Intel Processor Trace (IPT) events. + */ +DEFINE_GUID( /* ff1fd2fd-6008-42bb-9e75-00a20051f3be */ + IptGuid, + 0xff1fd2fd, + 0x6008, + 0x42bb, + 0x9e, 0x75, 0x00, 0xa2, 0x00, 0x51, 0xf3, 0xbe + ); + // // ThreadPool Events // If you change these structures, may need to update some users of these @@ -4030,17 +4090,13 @@ typedef struct _PERFINFO_DRIVER_MAJORFUNCTION PVOID Irp; ULONG UniqMatchId; } PERFINFO_DRIVER_MAJORFUNCTION, *PPERFINFO_DRIVER_MAJORFUNCTION; -#include -#include typedef struct _PERFINFO_DRIVER_MAJORFUNCTION_RET { PVOID Irp; ULONG UniqMatchId; } PERFINFO_DRIVER_MAJORFUNCTION_RET, *PPERFINFO_DRIVER_MAJORFUNCTION_RET; -#include -#include typedef struct _PERFINFO_DRIVER_COMPLETE_REQUEST { // @@ -4060,9 +4116,7 @@ typedef struct _PERFINFO_DRIVER_COMPLETE_REQUEST ULONG UniqMatchId; } PERFINFO_DRIVER_COMPLETE_REQUEST, *PPERFINFO_DRIVER_COMPLETE_REQUEST; -#include -#include typedef struct _PERFINFO_DRIVER_COMPLETE_REQUEST_RET { // @@ -4072,9 +4126,7 @@ typedef struct _PERFINFO_DRIVER_COMPLETE_REQUEST_RET PVOID Irp; ULONG UniqMatchId; } PERFINFO_DRIVER_COMPLETE_REQUEST_RET, *PPERFINFO_DRIVER_COMPLETE_REQUEST_RET; -#include -#include typedef struct _PERFINFO_DRIVER_COMPLETIONROUTINE { PVOID Routine; @@ -4381,16 +4433,17 @@ typedef struct _PERFINFO_PPM_IDLE_EXIT_LATENCY typedef struct _PERFINFO_PPM_PERF_STATE_CHANGE { - ULONG Type; - ULONG NewState; - ULONG OldState; - NTSTATUS Result; - ULONG64 Processors; + ULONG Type; + ULONG NewState; + ULONG OldState; + NTSTATUS Result; + ULONG64 Processors; } PERFINFO_PPM_PERF_STATE_CHANGE, *PPERFINFO_PPM_PERF_STATE_CHANGE; -typedef struct _PERFINFO_PPM_THERMAL_CONSTRAINT{ - ULONG Constraint; - ULONG64 Processors; +typedef struct _PERFINFO_PPM_THERMAL_CONSTRAINT +{ + ULONG Constraint; + ULONG64 Processors; } PERFINFO_PPM_THERMAL_CONSTRAINT, *PPERFINFO_PPM_THERMAL_CONSTRAINT; // @@ -4585,7 +4638,7 @@ typedef enum _PERFINFO_KERNELMEMORY_USAGE_TYPE PerfInfoMemUsageMax } PERFINFO_KERNELMEMORY_USAGE_TYPE, *PPERFINFO_KERNELMEMORY_USAGE_TYPE; -C_ASSERT(PerfInfoMemUsageMax <= (1 << PERFINFO_MM_KERNELMEMORY_USAGE_TYPE_BITS)); +static_assert(PerfInfoMemUsageMax <= (1 << PERFINFO_MM_KERNELMEMORY_USAGE_TYPE_BITS)); typedef struct _PERFINFO_KERNELMEMORY_RANGE_USAGE { @@ -4605,7 +4658,7 @@ typedef enum _PERFINFO_MM_STAT PerfInfoMMStatMax } PERFINFO_MM_STAT, *PPERFINFO_MM_STAT; -C_ASSERT(PerfInfoMMStatMax <= (1 << PERFINFO_MM_STAT_TYPE_BITS)); +static_assert(PerfInfoMMStatMax <= (1 << PERFINFO_MM_STAT_TYPE_BITS)); // // This is logged as part of the end rundown. @@ -5122,17 +5175,17 @@ typedef struct _PERFINFO_DEBUG_EVENT // #define PERFINFO_CCSWAP_BIT_FULL_TS 30 -C_ASSERT (PERFINFO_CCSWAP_BIT_FULL_TS == (32 - PERFINFO_CCSWAP_BIT_TYPE)); +static_assert (PERFINFO_CCSWAP_BIT_FULL_TS == (32 - PERFINFO_CCSWAP_BIT_TYPE)); #define PERFINFO_CCSWAP_BIT_SHORT_TS 14 -C_ASSERT(PERFINFO_CCSWAP_BIT_SHORT_TS == (16 - PERFINFO_CCSWAP_BIT_TYPE)); +static_assert(PERFINFO_CCSWAP_BIT_SHORT_TS == (16 - PERFINFO_CCSWAP_BIT_TYPE)); #define PERFINFO_CCSWAP_BIT_SMALL_TS 17 -C_ASSERT (PERFINFO_CCSWAP_BIT_SMALL_TS == +static_assert(PERFINFO_CCSWAP_BIT_SMALL_TS == (32 - PERFINFO_CCSWAP_BIT_TYPE - PERFINFO_CCSWAP_BIT_TID - PERFINFO_CCSWAP_BIT_PRI_INC - PERFINFO_CCSWAP_BIT_STATE_WR)); #define PERFINFO_CCSWAP_BIT_WAIT_TIME 17 -C_ASSERT (PERFINFO_CCSWAP_BIT_WAIT_TIME == +static_assert(PERFINFO_CCSWAP_BIT_WAIT_TIME == (32 - PERFINFO_CCSWAP_BIT_TID - PERFINFO_CCSWAP_BIT_STATE_WR - PERFINFO_CCSWAP_BIT_PRIORITY)); // @@ -5342,7 +5395,7 @@ typedef struct _PERFINFO_IO_TIMER #define TLG_KERNEL_PSPROV_KEYWORD_UTC 0x00000002 // -// Logger configuration and running statistics. This structure is used +// Logger configuration and statistics. // typedef struct _WMI_LOGGER_INFORMATION @@ -5355,68 +5408,158 @@ typedef struct _WMI_LOGGER_INFORMATION ULONG LogFileMode; // sequential, circular ULONG FlushTimer; // buffer flush timer, in seconds ULONG EnableFlags; // trace enable flags + union { - LONG AgeLimit; // aging decay time, in minutes + LONG AgeLimit; // aging decay time, in minutes LONG FlushThreshold; // Number of buffers to fill before flushing } DUMMYUNIONNAME; - ULONG Wow; // TRUE if the logger started under WOW64 + union { - HANDLE LogFileHandle; // handle to logfile - ULONG64 LogFileHandle64; + struct + { + ULONG Wow : 1; // TRUE if the logger started under WOW64 + ULONG QpcDeltaTracking : 1; + ULONG LargeMdlPages : 1; + ULONG ExcludeKernelStack : 1; + }; + ULONG64 V2Options; } DUMMYUNIONNAME2; + + union + { + HANDLE LogFileHandle; // Handle to logfile + ULONG64 LogFileHandle64; + } DUMMYUNIONNAME3; + union { ULONG NumberOfBuffers; // no of buffers in use ULONG InstanceCount; // Number of Provider Instances - } DUMMYUNIONNAME3; + } DUMMYUNIONNAME4; + union { ULONG FreeBuffers; // no of buffers free ULONG InstanceId; // Current Provider's Id for UmLogger - } DUMMYUNIONNAME4; + } DUMMYUNIONNAME5; + union { ULONG EventsLost; // event records lost ULONG NumberOfProcessors; // Passed on to UmLogger - } DUMMYUNIONNAME5; + } DUMMYUNIONNAME6; + ULONG BuffersWritten; // no of buffers written to file + union { ULONG LogBuffersLost; // no of logfile write failures ULONG Flags; // internal flags - } DUMMYUNIONNAME6; + } DUMMYUNIONNAME7; ULONG RealTimeBuffersLost; // no of rt delivery failures + union { HANDLE LoggerThreadId; // thread id of Logger ULONG64 LoggerThreadId64; // thread is of Logger - } DUMMYUNIONNAME7; + } DUMMYUNIONNAME8; + union { UNICODE_STRING LogFileName; // used only in WIN64 UNICODE_STRING64 LogFileName64; // Logfile name: only in WIN32 - } DUMMYUNIONNAME8; + } DUMMYUNIONNAME9; - // mandatory data provided by caller union { UNICODE_STRING LoggerName; // Logger instance name in WIN64 UNICODE_STRING64 LoggerName64; // Logger Instance name in WIN32 - } DUMMYUNIONNAME9; + }; ULONG RealTimeConsumerCount; // Number of rt consumers - ULONG SpareUlong; + + ULONG SequenceNumber; union { PVOID LoggerExtension; ULONG64 LoggerExtension64; - } DUMMYUNIONNAME10; + }; } WMI_LOGGER_INFORMATION, *PWMI_LOGGER_INFORMATION; +// +// ETW time structure (kernel-internal variant of SYSTEMTIME). +// +typedef struct _ETW_SYSTEMTIME +{ + USHORT Year; + USHORT Month; + USHORT DayOfWeek; + USHORT Day; + USHORT Hour; + USHORT Minute; + USHORT Second; + USHORT Milliseconds; +} ETW_SYSTEMTIME, *PETW_SYSTEMTIME; + +// +// ETW system logger slot (one entry per kernel session slot). +// +typedef struct _ETW_SYSTEM_LOGGER +{ + UCHAR LoggerId; + UCHAR ClockType; +} ETW_SYSTEM_LOGGER, *PETW_SYSTEM_LOGGER; + +// +// ETW system-wide logger settings (silo-aware). Size = 372 bytes. +// +typedef struct _ETW_SYSTEM_LOGGER_SETTINGS +{ + ETW_SYSTEM_LOGGER EtwpSystemLogger[8]; // +0x000 (16 bytes) + volatile ULONG EtwpActiveSystemLoggers; // +0x010 + PERFINFO_GROUPMASK SiloGlobalGroupMask; // +0x014 (32 bytes) + PERFINFO_GROUPMASK EtwpGroupMasks[10]; // +0x034 (320 bytes) +} ETW_SYSTEM_LOGGER_SETTINGS, *PETW_SYSTEM_LOGGER_SETTINGS; + +// +// ETW boot logger configuration. +// +typedef struct _ETW_BOOT_CONFIG +{ + ULONG MaxLoggers; + ULONG Reserved; + LIST_ENTRY BootLoggersList; +} ETW_BOOT_CONFIG, *PETW_BOOT_CONFIG; + +// +// ETW global performance counters. +// +typedef struct _ETW_PERF_COUNTERS +{ + LONG TotalActiveSessions; + LONG TotalBufferMemoryNonPagedPool; + LONG TotalBufferMemoryPagedPool; + LONG TotalGuidsEnabled; + LONG TotalGuidsNotEnabled; + LONG TotalGuidsPreEnabled; +} ETW_PERF_COUNTERS, *PETW_PERF_COUNTERS; + +// +// ETW per-session performance counters. +// +typedef struct _ETW_SESSION_PERF_COUNTERS +{ + LONG BufferMemoryPagedPool; + LONG BufferMemoryNonPagedPool; + ULONGLONG EventsLoggedCount; + LONG EventsLost; + LONG NumConsumers; +} ETW_SESSION_PERF_COUNTERS, *PETW_SESSION_PERF_COUNTERS; + #define ETW_SYSTEM_EVENT_VERSION_MASK 0x000000FF #define ETW_GET_SYSTEM_EVENT_VERSION(X) ((X) & ETW_SYSTEM_EVENT_VERSION_MASK) @@ -5444,6 +5587,12 @@ typedef struct _WMI_LOGGER_INFORMATION #define ETW_NT_FLAGS_USE_NATIVE_HEADER 0x40000000 // Use native header for WOW64 #define ETW_NT_FLAGS_WOW64_CALL 0x80000000 // For use by WOW (Internal) +#define ETW_NT_FLAGS_TRACE_SYSTEM_V1 (ETW_NT_FLAGS_TRACE_SYSTEM | ETW_SYSTEM_EVENT_V1) +#define ETW_NT_FLAGS_TRACE_SYSTEM_V2 (ETW_NT_FLAGS_TRACE_SYSTEM | ETW_SYSTEM_EVENT_V2) +#define ETW_NT_FLAGS_TRACE_SYSTEM_V3 (ETW_NT_FLAGS_TRACE_SYSTEM | ETW_SYSTEM_EVENT_V3) +#define ETW_NT_FLAGS_TRACE_SYSTEM_V4 (ETW_NT_FLAGS_TRACE_SYSTEM | ETW_SYSTEM_EVENT_V4) +#define ETW_NT_FLAGS_TRACE_SYSTEM_V5 (ETW_NT_FLAGS_TRACE_SYSTEM | ETW_SYSTEM_EVENT_V5) + #define ETW_NT_FLAGS_TRACE_RUNDOWN_V2 (ETW_NT_FLAGS_TRACE_SYSTEM_V2 | ETW_NT_FLAGS_USE_NATIVE_HEADER) // Rundown and SysConfig events #define ETW_NT_FLAGS_TRACE_RUNDOWN_V3 (ETW_NT_FLAGS_TRACE_SYSTEM_V3 | ETW_NT_FLAGS_USE_NATIVE_HEADER) // Rundown and SysConfig events #define ETW_NT_FLAGS_TRACE_RUNDOWN_V4 (ETW_NT_FLAGS_TRACE_SYSTEM_V4 | ETW_NT_FLAGS_USE_NATIVE_HEADER) // Rundown and SysConfig events @@ -5461,12 +5610,6 @@ typedef struct _WMI_LOGGER_INFORMATION #define ETW_SKIP_USER_FRAMES(X) ((X) << ETW_USER_FRAMES_TO_SKIP_SHIFT) #define ETW_USER_EVENT_WITH_STACKWALK(X) (ETW_NT_FLAGS_TRACE_SYSTEM_V2| ETW_SKIP_USER_FRAMES(X)) -#define ETW_NT_FLAGS_TRACE_SYSTEM_V1 (ETW_NT_FLAGS_TRACE_SYSTEM | ETW_SYSTEM_EVENT_V1) -#define ETW_NT_FLAGS_TRACE_SYSTEM_V2 (ETW_NT_FLAGS_TRACE_SYSTEM | ETW_SYSTEM_EVENT_V2) -#define ETW_NT_FLAGS_TRACE_SYSTEM_V3 (ETW_NT_FLAGS_TRACE_SYSTEM | ETW_SYSTEM_EVENT_V3) -#define ETW_NT_FLAGS_TRACE_SYSTEM_V4 (ETW_NT_FLAGS_TRACE_SYSTEM | ETW_SYSTEM_EVENT_V4) -#define ETW_NT_FLAGS_TRACE_SYSTEM_V5 (ETW_NT_FLAGS_TRACE_SYSTEM | ETW_SYSTEM_EVENT_V5) - // Constants for UMGL (User Mode Global Logging). // // N.B. There is enough space reserved in UserSharedData @@ -5634,10 +5777,12 @@ typedef struct _ETW_NOTIFICATION_HEADER GUID SourceGuid; // Source GUID } ETW_NOTIFICATION_HEADER, *PETW_NOTIFICATION_HEADER; -typedef ULONG (NTAPI *PETW_NOTIFICATION_CALLBACK)( +typedef _Function_class_(ETW_NOTIFICATION_CALLBACK) +ULONG NTAPI ETW_NOTIFICATION_CALLBACK( _In_ PETW_NOTIFICATION_HEADER NotificationHeader, _In_ PVOID Context ); +typedef ETW_NOTIFICATION_CALLBACK *PETW_NOTIFICATION_CALLBACK; typedef enum _ETW_SESSION_NOTIFICATION_TYPE { @@ -5919,56 +6064,181 @@ typedef struct _ETW_TRACE_GUID_INFO //ETW_TRACE_PROVIDER_INSTANCE_INFO Instances[1]; } ETW_TRACE_GUID_INFO, *PETW_TRACE_GUID_INFO; +// rev +typedef struct _ETW_UPDATE_DISALLOW_LIST_INFORMATION +{ + ULONG LoggerId; + ULONG GuidCount; + GUID GuidList[ANYSIZE_ARRAY]; +} ETW_UPDATE_DISALLOW_LIST_INFORMATION, *PETW_UPDATE_DISALLOW_LIST_INFORMATION; + +// rev +typedef struct _ETW_GET_DISALLOW_LIST_INFORMATION +{ + ULONG LoggerId; + ULONG Reserved; +} ETW_GET_DISALLOW_LIST_INFORMATION, *PETW_GET_DISALLOW_LIST_INFORMATION; + +// rev +typedef struct _ETW_SET_COMPRESSION_SETTINGS_INFORMATION +{ + ULONG LoggerId; + ULONG Field4; + ULONG Field8; + ULONG FieldC; +} ETW_SET_COMPRESSION_SETTINGS_INFORMATION, *PETW_SET_COMPRESSION_SETTINGS_INFORMATION; + +// rev +typedef struct _ETW_GET_COMPRESSION_SETTINGS_INFORMATION +{ + USHORT LoggerId; + USHORT Reserved0; + ULONG Reserved4; +} ETW_GET_COMPRESSION_SETTINGS_INFORMATION, *PETW_GET_COMPRESSION_SETTINGS_INFORMATION; + +// rev +typedef struct _ETW_COMPRESSION_SETTINGS_DATA +{ + ULONG LoggerId; + ULONG Field4; + ULONG Field8; + ULONG FieldC; +} ETW_COMPRESSION_SETTINGS_DATA, *PETW_COMPRESSION_SETTINGS_DATA; + +// rev +typedef struct _ETW_UPDATE_PERIODIC_CAPTURE_STATE_INFORMATION +{ + ULONG LoggerId; + ULONG CaptureInterval; + USHORT GuidCount; + USHORT Reserved; + GUID GuidList[ANYSIZE_ARRAY]; +} ETW_UPDATE_PERIODIC_CAPTURE_STATE_INFORMATION, *PETW_UPDATE_PERIODIC_CAPTURE_STATE_INFORMATION; + +// rev +typedef struct _ETW_PRIVATE_SESSION_TRACE_REQUEST +{ + ULONG ProcessId; + union + { + ULONG Value; + struct + { + USHORT PrivateSessionId; + USHORT PrivateSessionVersion; + } DUMMYSTRUCTNAME; + } DUMMYUNIONNAME; +} ETW_PRIVATE_SESSION_TRACE_REQUEST, *PETW_PRIVATE_SESSION_TRACE_REQUEST; + +// rev +typedef struct _ETW_GET_PRIVATE_SESSION_TRACE_HANDLE_INFORMATION +{ + ETW_PRIVATE_SESSION_TRACE_REQUEST Requests[ANYSIZE_ARRAY]; +} ETW_GET_PRIVATE_SESSION_TRACE_HANDLE_INFORMATION, *PETW_GET_PRIVATE_SESSION_TRACE_HANDLE_INFORMATION; + +// rev +typedef struct _ETW_REGISTER_PRIVATE_SESSION_INFORMATION +{ + union + { + struct + { + USHORT PrivateSessionId; + USHORT Reserved0; + } DUMMYSTRUCTNAME; + ULONG SessionDemuxHandle; + } DUMMYUNIONNAME; + USHORT PrivateSessionHandle; + USHORT Reserved4; +} ETW_REGISTER_PRIVATE_SESSION_INFORMATION, *PETW_REGISTER_PRIVATE_SESSION_INFORMATION; + +// rev +typedef struct _ETW_QUERY_SESSION_DEMUX_OBJECT_INFORMATION +{ + union + { + HANDLE SessionDemuxHandle; + USHORT PrivateSessionHandle; + } DUMMYUNIONNAME; +} ETW_QUERY_SESSION_DEMUX_OBJECT_INFORMATION, *PETW_QUERY_SESSION_DEMUX_OBJECT_INFORMATION; + +// rev +typedef struct _ETW_SET_PROVIDER_BINARY_TRACKING_INFORMATION +{ + ULONG LoggerId; + BOOLEAN Enable; + UCHAR Reserved1[3]; +} ETW_SET_PROVIDER_BINARY_TRACKING_INFORMATION, *PETW_SET_PROVIDER_BINARY_TRACKING_INFORMATION; + +// rev +typedef struct _ETW_QUERY_USED_PROCESSOR_COUNT_INFORMATION +{ + USHORT LoggerId; + USHORT Reserved; + ULONG Reserved2; +} ETW_QUERY_USED_PROCESSOR_COUNT_INFORMATION, *PETW_QUERY_USED_PROCESSOR_COUNT_INFORMATION; + +static_assert(sizeof(ETW_GET_DISALLOW_LIST_INFORMATION) == 8, "ETW_GET_DISALLOW_LIST_INFORMATION"); +static_assert(sizeof(ETW_SET_COMPRESSION_SETTINGS_INFORMATION) == 16, "ETW_SET_COMPRESSION_SETTINGS_INFORMATION"); +static_assert(sizeof(ETW_GET_COMPRESSION_SETTINGS_INFORMATION) == 8, "ETW_GET_COMPRESSION_SETTINGS_INFORMATION"); +static_assert(sizeof(ETW_COMPRESSION_SETTINGS_DATA) == 16, "ETW_COMPRESSION_SETTINGS_DATA"); +static_assert(sizeof(ETW_PRIVATE_SESSION_TRACE_REQUEST) == 8, "ETW_PRIVATE_SESSION_TRACE_REQUEST"); +static_assert(sizeof(ETW_GET_PRIVATE_SESSION_TRACE_HANDLE_INFORMATION) == 8, "ETW_GET_PRIVATE_SESSION_TRACE_HANDLE_INFORMATION"); +static_assert(sizeof(ETW_REGISTER_PRIVATE_SESSION_INFORMATION) == 8, "ETW_REGISTER_PRIVATE_SESSION_INFORMATION"); +static_assert(sizeof(ETW_QUERY_SESSION_DEMUX_OBJECT_INFORMATION) == sizeof(HANDLE), "ETW_QUERY_SESSION_DEMUX_OBJECT_INFORMATION"); +static_assert(sizeof(ETW_SET_PROVIDER_BINARY_TRACKING_INFORMATION) == 8, "ETW_SET_PROVIDER_BINARY_TRACKING_INFORMATION"); +static_assert(sizeof(ETW_QUERY_USED_PROCESSOR_COUNT_INFORMATION) == 8, "ETW_QUERY_USED_PROCESSOR_COUNT_INFORMATION"); + // 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 + EtwStartLoggerCode = 1, // inout WMI_LOGGER_INFORMATION (>= 0xB0) + EtwStopLoggerCode = 2, // inout WMI_LOGGER_INFORMATION (>= 0xB0) + EtwQueryLoggerCode = 3, // inout WMI_LOGGER_INFORMATION (>= 0xB0) + EtwUpdateLoggerCode = 4, // inout WMI_LOGGER_INFORMATION (>= 0xB0) + EtwFlushLoggerCode = 5, // inout WMI_LOGGER_INFORMATION (>= 0xB0) + EtwIncrementLoggerFile = 6, // inout WMI_LOGGER_INFORMATION (>= 0xB0) + EtwRealtimeTransition = 7, // inout WMI_LOGGER_INFORMATION (>= 0xB0) // reserved - EtwRealtimeConnectCode = 11, - EtwActivityIdCreate = 12, - EtwWdiScenarioCode = 13, - EtwRealtimeDisconnectCode = 14, // in HANDLE - EtwRegisterGuidsCode = 15, - EtwReceiveNotification = 16, - EtwSendDataBlock = 17, // ETW_ENABLE_NOTIFICATION_PACKET // ETW_SESSION_NOTIFICATION_PACKET - EtwSendReplyDataBlock = 18, - EtwReceiveReplyDataBlock = 19, - EtwWdiSemUpdate = 20, - EtwEnumTraceGuidList = 21, // out GUID[] - EtwGetTraceGuidInfo = 22, // in GUID, out ETW_TRACE_GUID_INFO - EtwEnumerateTraceGuids = 23, // out TRACE_GUID_PROPERTIES[] - 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, + EtwRealtimeConnectCode = 11, // inout 0x60-byte realtime connect buffer + EtwActivityIdCreate = 12, // out GUID + EtwWdiScenarioCode = 13, // in 0x30-byte WDI control buffer + EtwRealtimeDisconnectCode = 14, // in HANDLE + EtwRegisterGuidsCode = 15, // in 0xA0-byte registration header, out provider reply buffer (>= 0xA0) + EtwReceiveNotification = 16, // out ETW_NOTIFICATION_HEADER + payload (72..65536 bytes) + EtwSendDataBlock = 17, // in ETW_ENABLE_NOTIFICATION_PACKET, out ETW_SESSION_NOTIFICATION_PACKET (0x48) + EtwSendReplyDataBlock = 18, // in ETW_NOTIFICATION_HEADER + payload + EtwReceiveReplyDataBlock = 19, // in HANDLE, out reply data block + EtwWdiSemUpdate = 20, // no input/output buffers + EtwEnumTraceGuidList = 21, // out GUID[] + EtwGetTraceGuidInfo = 22, // in GUID, out ETW_TRACE_GUID_INFO + instances + EtwEnumerateTraceGuids = 23, // out TRACE_GUID_PROPERTIES[] + EtwRegisterSecurityProv = 24, // no input/output buffers + EtwReferenceTimeCode = 25, // in ULONG LoggerId, out ETW_REF_CLOCK + EtwTrackBinaryCode = 26, // in HANDLE + EtwAddNotificationEvent = 27, // in HANDLE + EtwUpdateDisallowList = 28, // in ETW_UPDATE_DISALLOW_LIST_INFORMATION + EtwSetEnableAllKeywordsCode = 29, // reserved/unsupported in current NtTraceControl switch + EtwSetProviderTraitsCode = 30, // in provider traits header (0x18), out traits reply buffer (>= 0x78) + EtwUseDescriptorTypeCode = 31, // in 0x10-byte descriptor-type control + EtwEnumTraceGroupList = 32, // out GUID[] + EtwGetTraceGroupInfo = 33, // in GUID, out group info buffer + EtwGetDisallowList = 34, // in ETW_GET_DISALLOW_LIST_INFORMATION, out variable-size disallow list + EtwSetCompressionSettings = 35, // in ETW_SET_COMPRESSION_SETTINGS_INFORMATION + EtwGetCompressionSettings = 36, // in ETW_GET_COMPRESSION_SETTINGS_INFORMATION, out ETW_COMPRESSION_SETTINGS_DATA + EtwUpdatePeriodicCaptureState = 37, // in ETW_UPDATE_PERIODIC_CAPTURE_STATE_INFORMATION + EtwGetPrivateSessionTraceHandle = 38, // in ETW_GET_PRIVATE_SESSION_TRACE_HANDLE_INFORMATION, out USHORT PrivateSessionHandle + EtwRegisterPrivateSession = 39, // inout ETW_REGISTER_PRIVATE_SESSION_INFORMATION + EtwQuerySessionDemuxObject = 40, // inout ETW_QUERY_SESSION_DEMUX_OBJECT_INFORMATION + EtwSetProviderBinaryTracking = 41, // in ETW_SET_PROVIDER_BINARY_TRACKING_INFORMATION + EtwMaxLoggers = 42, // out ULONG + EtwMaxPmcCounter = 43, // out ULONG + EtwQueryUsedProcessorCount = 44, // in ETW_QUERY_USED_PROCESSOR_COUNT_INFORMATION (LoggerId), out ULONG // since WIN11 + EtwGetPmcOwnership = 45, // out variable-size PMC ownership buffer + EtwGetPmcSessions = 46, // out variable-size PMC session buffer + EtwTraceControlMax = 47, } ETWTRACECONTROLCODE; -#if (PHNT_VERSION >= PHNT_WINDOWS_VISTA) NTSYSCALLAPI NTSTATUS NTAPI @@ -5980,9 +6250,7 @@ NtTraceControl( _In_ ULONG OutputBufferLength, _Out_ PULONG ReturnLength ); -#endif -#if (PHNT_VERSION >= PHNT_WINDOWS_XP) NTSYSCALLAPI NTSTATUS NTAPI @@ -5992,12 +6260,11 @@ NtTraceEvent( _In_ ULONG FieldSize, _In_ PVOID Fields ); -#endif // private typedef struct _TELEMETRY_COVERAGE_POINT { - PWSTR Name; + PSTR Name; ULONG Hash; ULONG LastCoveredRound; ULONG Flags; @@ -6199,8 +6466,8 @@ WmiExecuteMethodW( #define NOTIFICATION_LIGHTWEIGHT_FLAG 0x00000020 // Event notification callback function prototype -_Function_class_(NOTIFICATIONCALLBACK) -typedef void (WINAPI NOTIFICATIONCALLBACK)( +typedef _Function_class_(NOTIFICATIONCALLBACK) +VOID NTAPI NOTIFICATIONCALLBACK( _In_ PWNODE_HEADER Wnode, _In_ ULONG_PTR NotificationContext ); @@ -6396,6 +6663,4 @@ WmiFreeBuffer( _In_ PVOID Buffer ); -EXTERN_C_END - -#endif +#endif // _NTWMI_H diff --git a/ntwow64.h b/ntwow64.h index 6ddc35a..456b412 100644 --- a/ntwow64.h +++ b/ntwow64.h @@ -8,8 +8,12 @@ #define _NTWOW64_H #if (PHNT_MODE != PHNT_MODE_KERNEL) +#ifdef __has_include +#if __has_include () #include -#endif +#endif // __has_include +#endif // __has_include +#endif // (PHNT_MODE != PHNT_MODE_KERNEL) #define WOW64_SYSTEM_DIRECTORY "SysWOW64" #define WOW64_SYSTEM_DIRECTORY_U L"SysWOW64" @@ -33,7 +37,9 @@ typedef enum _WOW64_SHARED_INFORMATION Wow64SharedPageEntriesCount } WOW64_SHARED_INFORMATION; +// // 32-bit definitions +// #define WOW64_POINTER(Type) ULONG @@ -186,6 +192,23 @@ typedef struct _LDR_DATA_TABLE_ENTRY32 LDR_HOT_PATCH_STATE HotPatchState; } LDR_DATA_TABLE_ENTRY32, *PLDR_DATA_TABLE_ENTRY32; +typedef const LDR_DATA_TABLE_ENTRY32* PCLDR_DATA_TABLE_ENTRY32; + +static_assert(UFIELD_OFFSET(LDR_DATA_TABLE_ENTRY32, InMemoryOrderLinks) == 0x8, "LDR_DATA_TABLE_ENTRY32.InMemoryOrderLinks offset incorrect"); +static_assert(UFIELD_OFFSET(LDR_DATA_TABLE_ENTRY32, InInitializationOrderLinks) == 0x10, "LDR_DATA_TABLE_ENTRY32.InInitializationOrderLinks offset incorrect"); +static_assert(UFIELD_OFFSET(LDR_DATA_TABLE_ENTRY32, DllBase) == 0x18, "LDR_DATA_TABLE_ENTRY32.DllBase offset incorrect"); +static_assert(UFIELD_OFFSET(LDR_DATA_TABLE_ENTRY32, EntryPoint) == 0x1c, "LDR_DATA_TABLE_ENTRY32.EntryPoint offset incorrect"); +static_assert(UFIELD_OFFSET(LDR_DATA_TABLE_ENTRY32, SizeOfImage) == 0x20, "LDR_DATA_TABLE_ENTRY32.SizeOfImage offset incorrect"); +static_assert(UFIELD_OFFSET(LDR_DATA_TABLE_ENTRY32, ObsoleteLoadCount) == 0x38, "LDR_DATA_TABLE_ENTRY32.ObsoleteLoadCount offset incorrect"); +static_assert(UFIELD_OFFSET(LDR_DATA_TABLE_ENTRY32, TimeDateStamp) == 0x44, "LDR_DATA_TABLE_ENTRY32.TimeDateStamp offset incorrect"); +static_assert(UFIELD_OFFSET(LDR_DATA_TABLE_ENTRY32, DdagNode) == 0x50, "LDR_DATA_TABLE_ENTRY32.DdagNode offset incorrect"); +static_assert(UFIELD_OFFSET(LDR_DATA_TABLE_ENTRY32, ParentDllBase) == 0x60, "LDR_DATA_TABLE_ENTRY32.ParentDllBase offset incorrect"); +static_assert(UFIELD_OFFSET(LDR_DATA_TABLE_ENTRY32, OriginalBase) == 0x80, "LDR_DATA_TABLE_ENTRY32.OriginalBase offset incorrect"); +static_assert(UFIELD_OFFSET(LDR_DATA_TABLE_ENTRY32, BaseNameHashValue) == 0x90, "LDR_DATA_TABLE_ENTRY32.BaseNameHashValue offset incorrect"); +static_assert(UFIELD_OFFSET(LDR_DATA_TABLE_ENTRY32, LoadReason) == 0x94, "LDR_DATA_TABLE_ENTRY32.LoadReason offset incorrect"); +static_assert(UFIELD_OFFSET(LDR_DATA_TABLE_ENTRY32, CheckSum) == 0xA8, "LDR_DATA_TABLE_ENTRY32.CheckSum offset incorrect"); +static_assert(sizeof(LDR_DATA_TABLE_ENTRY32) == 0xB8, "LDR_DATA_TABLE_ENTRY32 incorrect size"); + typedef struct _CURDIR32 { UNICODE_STRING32 DosPath; @@ -291,7 +314,10 @@ typedef struct _PEB32 ULONG ProcessUsingVEH : 1; ULONG ProcessUsingVCH : 1; ULONG ProcessUsingFTH : 1; - ULONG ReservedBits0 : 27; + ULONG ProcessPreviouslyThrottled : 1; // The process was previously throttled. + ULONG ProcessCurrentlyThrottled : 1; // The process is currently throttled. + ULONG ProcessImagesHotPatched : 1; // The process images are hot patched. // RS5 + ULONG ReservedBits0 : 24; }; }; union @@ -419,8 +445,6 @@ typedef struct _PEB32 ULONGLONG ExtendedFeatureDisableMask; // since WIN11 } PEB32, *PPEB32; -//static_assert(sizeof(PEB32) == 0x460, "sizeof(PEB32) is incorrect"); // REDSTONE3 -//static_assert(sizeof(PEB32) == 0x470, "sizeof(PEB32) is incorrect"); // REDSTONE5 static_assert(sizeof(PEB32) == 0x488, "sizeof(PEB32) is incorrect"); // WIN11 // Note: Use PhGetProcessPeb32 instead. (dmex) @@ -436,6 +460,28 @@ typedef struct _GDI_TEB_BATCH32 ULONG Buffer[GDI_BATCH_BUFFER_SIZE]; } GDI_TEB_BATCH32, *PGDI_TEB_BATCH32; +typedef struct tagSOleTlsData32 +{ + WOW64_POINTER(PVOID) ThreadBase; + WOW64_POINTER(PVOID) SmAllocator; + ULONG ApartmentID; + ULONG Flags; // OLETLSFLAGS + LONG TlsMapIndex; + WOW64_POINTER(PVOID *) TlsSlot; + ULONG ComInits; + ULONG OleInits; + ULONG Calls; + WOW64_POINTER(PVOID) ServerCall; // was CallInfo before TH1 + WOW64_POINTER(PVOID) CallObjectCache; // was FreeAsyncCall before TH1 + WOW64_POINTER(PVOID) ContextStack; // was FreeClientCall before TH1 + WOW64_POINTER(PVOID) ObjServer; + ULONG TIDCaller; + // ... (other fields are version-dependant) +} SOleTlsData32, *PSOleTlsData32; + +// rev +#define RPC_THREAD_POINTER_KEY32 0xABABABAB + typedef struct _TEB32 { NT_TIB32 NtTib; @@ -521,7 +567,7 @@ typedef struct _TEB32 ULONG GuaranteedStackBytes; WOW64_POINTER(PVOID) ReservedForPerf; - WOW64_POINTER(PVOID) ReservedForOle; + WOW64_POINTER(PSOleTlsData32) ReservedForOle; ULONG WaitingOnLoaderLock; WOW64_POINTER(PVOID) SavedPriorityState; WOW64_POINTER(ULONG_PTR) ReservedForCodeCoverage; @@ -592,11 +638,13 @@ static_assert(FIELD_OFFSET(TEB32, MuiImpersonation) == 0xfc4, "FIELD_OFFSET(TEB3 static_assert(FIELD_OFFSET(TEB32, EffectiveContainerId) == 0xff0, "FIELD_OFFSET(TEB32, EffectiveContainerId) is incorrect"); static_assert(sizeof(TEB32) == 0x1000, "sizeof(TEB32) is incorrect"); +// // Conversion +// FORCEINLINE VOID UStr32ToUStr( _Out_ PUNICODE_STRING Destination, - _In_ PUNICODE_STRING32 Source + _In_ PCUNICODE_STRING32 Source ) { Destination->Length = Source->Length; @@ -606,7 +654,7 @@ FORCEINLINE VOID UStr32ToUStr( FORCEINLINE VOID UStrToUStr32( _Out_ PUNICODE_STRING32 Destination, - _In_ PUNICODE_STRING Source + _In_ PCUNICODE_STRING Source ) { Destination->Length = Source->Length; @@ -786,4 +834,4 @@ Wow64CurrentNativeTeb( #endif // _M_X64 #endif // (PHNT_MODE != PHNT_MODE_KERNEL) -#endif +#endif // _NTWOW64_H diff --git a/ntxcapi.h b/ntxcapi.h index 9236ef5..c45116d 100644 --- a/ntxcapi.h +++ b/ntxcapi.h @@ -24,6 +24,13 @@ RtlRaiseStatus( _In_ NTSTATUS Status ); +/** + * Raises an exception in the calling thread. + * + * \param ExceptionRecord A pointer to an EXCEPTION_RECORD structure that contains the exception information. You must specify the ExceptionAddress and ExceptionCode members. + * \return This function does not return a value. + * \see https://learn.microsoft.com/en-us/windows/win32/api/errhandlingapi/nf-errhandlingapi-raiseexception + */ NTSYSAPI VOID NTAPI @@ -117,16 +124,7 @@ RtlAssert( _In_ PVOID VoidFailedAssertion, _In_ PVOID VoidFileName, _In_ ULONG LineNumber, - _In_opt_ PSTR MutableMessage + _In_opt_ PCSTR 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 +#endif // _NTXCAPI_H diff --git a/ntzwapi.h b/ntzwapi.h index 27d49a1..c9f1954 100644 --- a/ntzwapi.h +++ b/ntzwapi.h @@ -33,10 +33,10 @@ NTSYSCALLAPI NTSTATUS NTAPI ZwAccessCheckAndAuditAlarm( - _In_ PUNICODE_STRING SubsystemName, + _In_ PCUNICODE_STRING SubsystemName, _In_opt_ PVOID HandleId, - _In_ PUNICODE_STRING ObjectTypeName, - _In_ PUNICODE_STRING ObjectName, + _In_ PCUNICODE_STRING ObjectTypeName, + _In_ PCUNICODE_STRING ObjectName, _In_ PSECURITY_DESCRIPTOR SecurityDescriptor, _In_ ACCESS_MASK DesiredAccess, _In_ PGENERIC_MAPPING GenericMapping, @@ -67,10 +67,10 @@ NTSYSCALLAPI NTSTATUS NTAPI ZwAccessCheckByTypeAndAuditAlarm( - _In_ PUNICODE_STRING SubsystemName, + _In_ PCUNICODE_STRING SubsystemName, _In_opt_ PVOID HandleId, - _In_ PUNICODE_STRING ObjectTypeName, - _In_ PUNICODE_STRING ObjectName, + _In_ PCUNICODE_STRING ObjectTypeName, + _In_ PCUNICODE_STRING ObjectName, _In_ PSECURITY_DESCRIPTOR SecurityDescriptor, _In_opt_ PSID PrincipalSelfSid, _In_ ACCESS_MASK DesiredAccess, @@ -106,10 +106,10 @@ NTSYSCALLAPI NTSTATUS NTAPI ZwAccessCheckByTypeResultListAndAuditAlarm( - _In_ PUNICODE_STRING SubsystemName, + _In_ PCUNICODE_STRING SubsystemName, _In_opt_ PVOID HandleId, - _In_ PUNICODE_STRING ObjectTypeName, - _In_ PUNICODE_STRING ObjectName, + _In_ PCUNICODE_STRING ObjectTypeName, + _In_ PCUNICODE_STRING ObjectName, _In_ PSECURITY_DESCRIPTOR SecurityDescriptor, _In_opt_ PSID PrincipalSelfSid, _In_ ACCESS_MASK DesiredAccess, @@ -128,11 +128,11 @@ NTSYSCALLAPI NTSTATUS NTAPI ZwAccessCheckByTypeResultListAndAuditAlarmByHandle( - _In_ PUNICODE_STRING SubsystemName, + _In_ PCUNICODE_STRING SubsystemName, _In_opt_ PVOID HandleId, _In_ HANDLE ClientToken, - _In_ PUNICODE_STRING ObjectTypeName, - _In_ PUNICODE_STRING ObjectName, + _In_ PCUNICODE_STRING ObjectTypeName, + _In_ PCUNICODE_STRING ObjectName, _In_ PSECURITY_DESCRIPTOR SecurityDescriptor, _In_opt_ PSID PrincipalSelfSid, _In_ ACCESS_MASK DesiredAccess, @@ -170,7 +170,7 @@ NTAPI ZwAcquireProcessActivityReference( _Out_ PHANDLE ActivityReferenceHandle, _In_ HANDLE ParentProcessHandle, - _Reserved_ PROCESS_ACTIVITY_TYPE Reserved + _In_ ULONG ProcessActivityType // PROCESS_ACTIVITY_TYPE ); NTSYSCALLAPI @@ -260,8 +260,8 @@ NTAPI ZwAlertMultipleThreadByThreadId( _In_ PHANDLE MultipleThreadId, _In_ ULONG Count, - _In_ PVOID Boost, - _In_ ULONG BoostCount + _Inout_updates_opt_(ExtendedParameterCount) PPS_ALERT_THREAD_EXTENDED_PARAMETER ExtendedParameters, + _In_ ULONG ExtendedParameterCount ); NTSYSCALLAPI @@ -394,7 +394,7 @@ NTSTATUS NTAPI ZwAlpcConnectPort( _Out_ PHANDLE PortHandle, - _In_ PUNICODE_STRING PortName, + _In_ PCUNICODE_STRING PortName, _In_opt_ POBJECT_ATTRIBUTES ObjectAttributes, _In_opt_ PALPC_PORT_ATTRIBUTES PortAttributes, _In_ ULONG Flags, @@ -451,7 +451,7 @@ ZwAlpcCreateResourceReserve( _In_ HANDLE PortHandle, _Reserved_ ULONG Flags, _In_ SIZE_T MessageSize, - _Out_ PALPC_HANDLE ResourceId + _Out_ PULONG ResourceId ); NTSYSCALLAPI @@ -487,7 +487,7 @@ NTAPI ZwAlpcDeleteResourceReserve( _In_ HANDLE PortHandle, _Reserved_ ULONG Flags, - _In_ ALPC_HANDLE ResourceId + _In_ ULONG ResourceId ); NTSYSCALLAPI @@ -614,6 +614,14 @@ ZwAlpcSetInformation( _In_ ULONG Length ); +NTSYSCALLAPI +NTSTATUS +NTAPI +ZwApphelpCacheControl( + _In_ AHC_SERVICE_CLASS ServiceClass, + _Inout_opt_ PVOID ServiceContext // AHC_SERVICE_DATA + ); + NTSYSCALLAPI NTSTATUS NTAPI @@ -658,7 +666,7 @@ NTSTATUS NTAPI ZwCallEnclave( _In_ PENCLAVE_ROUTINE Routine, - _In_ PVOID Reserved, // reserved for dispatch (RtlEnclaveCallDispatch) + _In_ PVOID Reserved, // SelectVsmEnclaveByNumber > 0 // reserved for dispatch (RtlEnclaveCallDispatch) _In_ ULONG Flags, // ENCLAVE_CALL_FLAG_* _Inout_ PVOID* RoutineParamReturn // input routine parameter, output routine return value ); @@ -722,7 +730,7 @@ ZwChangeProcessState( _In_ PROCESS_STATE_CHANGE_TYPE StateChangeType, _In_opt_ _Reserved_ PVOID ExtendedInformation, _In_opt_ _Reserved_ SIZE_T ExtendedInformationLength, - _In_opt_ _Reserved_ ULONG64 Reserved + _In_opt_ _Reserved_ ULONG Reserved ); NTSYSCALLAPI @@ -734,7 +742,7 @@ ZwChangeThreadState( _In_ THREAD_STATE_CHANGE_TYPE StateChangeType, _In_opt_ PVOID ExtendedInformation, _In_opt_ SIZE_T ExtendedInformationLength, - _In_opt_ ULONG64 Reserved + _In_opt_ ULONG Reserved ); NTSYSCALLAPI @@ -755,7 +763,7 @@ NTSYSCALLAPI NTSTATUS NTAPI ZwCloseObjectAuditAlarm( - _In_ PUNICODE_STRING SubsystemName, + _In_ PCUNICODE_STRING SubsystemName, _In_opt_ PVOID HandleId, _In_ BOOLEAN GenerateOnClose ); @@ -776,6 +784,14 @@ ZwCommitEnlistment( _In_opt_ PLARGE_INTEGER TmVirtualClock ); +NTSYSCALLAPI +NTSTATUS +NTAPI +ZwCommitRegistryTransaction( + _In_ HANDLE RegistryTransactionHandle, + _Reserved_ ULONG Flags + ); + NTSYSCALLAPI NTSTATUS NTAPI @@ -836,7 +852,7 @@ NTSTATUS NTAPI ZwConnectPort( _Out_ PHANDLE PortHandle, - _In_ PUNICODE_STRING PortName, + _In_ PCUNICODE_STRING PortName, _In_ PSECURITY_QUALITY_OF_SERVICE SecurityQos, _Inout_opt_ PPORT_VIEW ClientView, _Inout_opt_ PREMOTE_PORT_VIEW ServerView, @@ -1005,7 +1021,7 @@ NTAPI ZwCreateFile( _Out_ PHANDLE FileHandle, _In_ ACCESS_MASK DesiredAccess, - _In_ POBJECT_ATTRIBUTES ObjectAttributes, + _In_ PCOBJECT_ATTRIBUTES ObjectAttributes, _Out_ PIO_STATUS_BLOCK IoStatusBlock, _In_opt_ PLARGE_INTEGER AllocationSize, _In_ ULONG FileAttributes, @@ -1022,7 +1038,7 @@ NTAPI ZwCreateIoCompletion( _Out_ PHANDLE IoCompletionHandle, _In_ ACCESS_MASK DesiredAccess, - _In_opt_ POBJECT_ATTRIBUTES ObjectAttributes, + _In_opt_ PCOBJECT_ATTRIBUTES ObjectAttributes, _In_opt_ ULONG NumberOfConcurrentThreads ); @@ -1042,7 +1058,7 @@ NTSTATUS NTAPI ZwCreateIRTimer( _Out_ PHANDLE TimerHandle, - _In_ PVOID Reserved, + _In_ PULONG TimerId, _In_ ACCESS_MASK DesiredAccess ); @@ -1072,7 +1088,7 @@ ZwCreateKey( _In_ ACCESS_MASK DesiredAccess, _In_ POBJECT_ATTRIBUTES ObjectAttributes, _Reserved_ ULONG TitleIndex, - _In_opt_ PUNICODE_STRING Class, + _In_opt_ PCUNICODE_STRING Class, _In_ ULONG CreateOptions, _Out_opt_ PULONG Disposition ); @@ -1095,7 +1111,7 @@ ZwCreateKeyTransacted( _In_ ACCESS_MASK DesiredAccess, _In_ POBJECT_ATTRIBUTES ObjectAttributes, _Reserved_ ULONG TitleIndex, - _In_opt_ PUNICODE_STRING Class, + _In_opt_ PCUNICODE_STRING Class, _In_ ULONG CreateOptions, _In_ HANDLE TransactionHandle, _Out_opt_ PULONG Disposition @@ -1122,7 +1138,7 @@ NTAPI ZwCreateMailslotFile( _Out_ PHANDLE FileHandle, _In_ ACCESS_MASK DesiredAccess, - _In_ POBJECT_ATTRIBUTES ObjectAttributes, + _In_ PCOBJECT_ATTRIBUTES ObjectAttributes, _Out_ PIO_STATUS_BLOCK IoStatusBlock, _In_ ULONG CreateOptions, _In_ ULONG MailslotQuota, @@ -1146,7 +1162,7 @@ NTAPI ZwCreateNamedPipeFile( _Out_ PHANDLE FileHandle, _In_ ACCESS_MASK DesiredAccess, - _In_ POBJECT_ATTRIBUTES ObjectAttributes, + _In_ PCOBJECT_ATTRIBUTES ObjectAttributes, _Out_ PIO_STATUS_BLOCK IoStatusBlock, _In_ ULONG ShareAccess, _In_ ULONG CreateDisposition, @@ -1164,7 +1180,7 @@ NTSYSCALLAPI NTSTATUS NTAPI ZwCreatePagingFile( - _In_ PUNICODE_STRING PageFileName, + _In_ PCUNICODE_STRING PageFileName, _In_ PLARGE_INTEGER MinimumSize, _In_ PLARGE_INTEGER MaximumSize, _In_ ULONG Priority @@ -1177,8 +1193,7 @@ ZwCreatePartition( _In_opt_ HANDLE ParentPartitionHandle, _Out_ PHANDLE PartitionHandle, _In_ ACCESS_MASK DesiredAccess, - _In_opt_ PCOBJECT_ATTRIBUTES ObjectAttributes, - _In_ ULONG PreferredNode + _In_opt_ PCOBJECT_ATTRIBUTES ObjectAttributes ); NTSYSCALLAPI @@ -1239,7 +1254,7 @@ ZwCreateProcessStateChange( _In_ ACCESS_MASK DesiredAccess, _In_opt_ PCOBJECT_ATTRIBUTES ObjectAttributes, _In_ HANDLE ProcessHandle, - _In_opt_ _Reserved_ ULONG64 Reserved + _In_opt_ _Reserved_ ULONG Reserved ); NTSYSCALLAPI @@ -1273,6 +1288,16 @@ ZwCreateProfileEx( _In_reads_(GroupCount) PGROUP_AFFINITY GroupAffinity ); +NTSYSCALLAPI +NTSTATUS +NTAPI +ZwCreateRegistryTransaction( + _Out_ HANDLE *RegistryTransactionHandle, + _In_ ACCESS_MASK DesiredAccess, + _In_opt_ POBJECT_ATTRIBUTES ObjAttributes, + _Reserved_ ULONG CreateOptions + ); + NTSYSCALLAPI NTSTATUS NTAPI @@ -1283,7 +1308,7 @@ ZwCreateResourceManager( _In_ LPGUID RmGuid, _In_opt_ POBJECT_ATTRIBUTES ObjectAttributes, _In_opt_ ULONG CreateOptions, - _In_opt_ PUNICODE_STRING Description + _In_opt_ PCUNICODE_STRING Description ); NTSYSCALLAPI @@ -1332,7 +1357,7 @@ ZwCreateSymbolicLinkObject( _Out_ PHANDLE LinkHandle, _In_ ACCESS_MASK DesiredAccess, _In_ POBJECT_ATTRIBUTES ObjectAttributes, - _In_ PUNICODE_STRING LinkTarget + _In_ PCUNICODE_STRING LinkTarget ); NTSYSCALLAPI @@ -1374,7 +1399,7 @@ ZwCreateThreadStateChange( _In_ ACCESS_MASK DesiredAccess, _In_opt_ PCOBJECT_ATTRIBUTES ObjectAttributes, _In_ HANDLE ThreadHandle, - _In_opt_ ULONG64 Reserved + _In_opt_ _Reserved_ ULONG Reserved ); NTSYSCALLAPI @@ -1392,9 +1417,9 @@ NTSTATUS NTAPI ZwCreateTimer2( _Out_ PHANDLE TimerHandle, - _In_opt_ PVOID Reserved1, + _In_opt_ PULONG TimerId, _In_opt_ PCOBJECT_ATTRIBUTES ObjectAttributes, - _In_ ULONG Attributes, // TIMER_TYPE + _In_ ULONG Attributes, _In_ ACCESS_MASK DesiredAccess ); @@ -1453,7 +1478,7 @@ ZwCreateTransaction( _In_opt_ ULONG IsolationLevel, _In_opt_ ULONG IsolationFlags, _In_opt_ PLARGE_INTEGER Timeout, - _In_opt_ PUNICODE_STRING Description + _In_opt_ PCUNICODE_STRING Description ); NTSYSCALLAPI @@ -1463,7 +1488,7 @@ ZwCreateTransactionManager( _Out_ PHANDLE TmHandle, _In_ ACCESS_MASK DesiredAccess, _In_opt_ POBJECT_ATTRIBUTES ObjectAttributes, - _In_opt_ PUNICODE_STRING LogFileName, + _In_opt_ PCUNICODE_STRING LogFileName, _In_opt_ ULONG CreateOptions, _In_opt_ ULONG CommitStrength ); @@ -1502,7 +1527,7 @@ NTAPI ZwCreateWaitCompletionPacket( _Out_ PHANDLE WaitCompletionPacketHandle, _In_ ACCESS_MASK DesiredAccess, - _In_opt_ POBJECT_ATTRIBUTES ObjectAttributes + _In_opt_ PCOBJECT_ATTRIBUTES ObjectAttributes ); NTSYSCALLAPI @@ -1584,7 +1609,7 @@ NTSYSCALLAPI NTSTATUS NTAPI ZwDeleteFile( - _In_ POBJECT_ATTRIBUTES ObjectAttributes + _In_ PCOBJECT_ATTRIBUTES ObjectAttributes ); NTSYSCALLAPI @@ -1598,7 +1623,7 @@ NTSYSCALLAPI NTSTATUS NTAPI ZwDeleteObjectAuditAlarm( - _In_ PUNICODE_STRING SubsystemName, + _In_ PCUNICODE_STRING SubsystemName, _In_opt_ PVOID HandleId, _In_ BOOLEAN GenerateOnClose ); @@ -1615,7 +1640,7 @@ NTSTATUS NTAPI ZwDeleteValueKey( _In_ HANDLE KeyHandle, - _In_ PUNICODE_STRING ValueName + _In_ PCUNICODE_STRING ValueName ); NTSYSCALLAPI @@ -1623,7 +1648,7 @@ NTSTATUS NTAPI ZwDeleteWnfStateData( _In_ PCWNF_STATE_NAME StateName, - _In_opt_ const VOID* ExplicitScope + _In_opt_ PCSID ExplicitScope ); NTSYSCALLAPI @@ -1671,14 +1696,14 @@ NTSYSCALLAPI NTSTATUS NTAPI ZwDisplayString( - _In_ PUNICODE_STRING String + _In_ PCUNICODE_STRING String ); NTSYSCALLAPI NTSTATUS NTAPI ZwDrawText( - _In_ PUNICODE_STRING Text + _In_ PCUNICODE_STRING Text ); NTSYSCALLAPI @@ -1814,9 +1839,9 @@ ZwFilterTokenEx( _In_opt_ PTOKEN_PRIVILEGES PrivilegesToDelete, _In_opt_ PTOKEN_GROUPS RestrictedSids, _In_ ULONG DisableUserClaimsCount, - _In_opt_ PUNICODE_STRING UserClaimsToDisable, + _In_opt_ PCUNICODE_STRING UserClaimsToDisable, _In_ ULONG DisableDeviceClaimsCount, - _In_opt_ PUNICODE_STRING DeviceClaimsToDisable, + _In_opt_ PCUNICODE_STRING DeviceClaimsToDisable, _In_opt_ PTOKEN_GROUPS DeviceGroupsToDisable, _In_opt_ PTOKEN_SECURITY_ATTRIBUTES_INFORMATION RestrictedUserAttributes, _In_opt_ PTOKEN_SECURITY_ATTRIBUTES_INFORMATION RestrictedDeviceAttributes, @@ -1866,7 +1891,7 @@ NTAPI ZwFlushInstructionCache( _In_ HANDLE ProcessHandle, _In_opt_ PVOID BaseAddress, - _In_ SIZE_T Length + _In_ SIZE_T RegionSize ); NTSYSCALLAPI @@ -1914,7 +1939,7 @@ NTSTATUS NTAPI ZwFreeVirtualMemory( _In_ HANDLE ProcessHandle, - _Inout_ PVOID *BaseAddress, + _Inout_ __drv_freesMem(Mem) PVOID *BaseAddress, _Inout_ PSIZE_T RegionSize, _In_ ULONG FreeType ); @@ -2032,7 +2057,7 @@ ZwGetNextThread( _In_opt_ HANDLE ThreadHandle, _In_ ACCESS_MASK DesiredAccess, _In_ ULONG HandleAttributes, - _In_ ULONG Flags, + _In_opt_ _Reserved_ ULONG Flags, _Out_ PHANDLE NewThreadHandle ); @@ -2179,7 +2204,7 @@ NTSYSCALLAPI NTSTATUS NTAPI ZwLoadDriver( - _In_ PUNICODE_STRING DriverServiceName + _In_ PCUNICODE_STRING DriverServiceName ); NTSYSCALLAPI @@ -2525,7 +2550,7 @@ NTAPI ZwOpenFile( _Out_ PHANDLE FileHandle, _In_ ACCESS_MASK DesiredAccess, - _In_ POBJECT_ATTRIBUTES ObjectAttributes, + _In_ PCOBJECT_ATTRIBUTES ObjectAttributes, _Out_ PIO_STATUS_BLOCK IoStatusBlock, _In_ ULONG ShareAccess, _In_ ULONG OpenOptions @@ -2537,7 +2562,7 @@ NTAPI ZwOpenIoCompletion( _Out_ PHANDLE IoCompletionHandle, _In_ ACCESS_MASK DesiredAccess, - _In_ POBJECT_ATTRIBUTES ObjectAttributes + _In_ PCOBJECT_ATTRIBUTES ObjectAttributes ); NTSYSCALLAPI @@ -2611,10 +2636,10 @@ NTSYSCALLAPI NTSTATUS NTAPI ZwOpenObjectAuditAlarm( - _In_ PUNICODE_STRING SubsystemName, + _In_ PCUNICODE_STRING SubsystemName, _In_opt_ PVOID HandleId, - _In_ PUNICODE_STRING ObjectTypeName, - _In_ PUNICODE_STRING ObjectName, + _In_ PCUNICODE_STRING ObjectTypeName, + _In_ PCUNICODE_STRING ObjectName, _In_opt_ PSECURITY_DESCRIPTOR SecurityDescriptor, _In_ HANDLE ClientToken, _In_ ACCESS_MASK DesiredAccess, @@ -2673,6 +2698,15 @@ ZwOpenProcessTokenEx( _Out_ PHANDLE TokenHandle ); +NTSYSCALLAPI +NTSTATUS +NTAPI +ZwOpenRegistryTransaction( + _Out_ HANDLE *RegistryTransactionHandle, + _In_ ACCESS_MASK DesiredAccess, + _In_ POBJECT_ATTRIBUTES ObjAttributes + ); + NTSYSCALLAPI NTSTATUS NTAPI @@ -2778,7 +2812,7 @@ ZwOpenTransactionManager( _Out_ PHANDLE TmHandle, _In_ ACCESS_MASK DesiredAccess, _In_opt_ POBJECT_ATTRIBUTES ObjectAttributes, - _In_opt_ PUNICODE_STRING LogFileName, + _In_opt_ PCUNICODE_STRING LogFileName, _In_opt_ LPGUID TmIdentity, _In_opt_ ULONG OpenOptions ); @@ -2848,8 +2882,8 @@ NTSYSCALLAPI NTSTATUS NTAPI ZwPrivilegedServiceAuditAlarm( - _In_ PUNICODE_STRING SubsystemName, - _In_ PUNICODE_STRING ServiceName, + _In_ PCUNICODE_STRING SubsystemName, + _In_ PCUNICODE_STRING ServiceName, _In_ HANDLE ClientToken, _In_ PPRIVILEGE_SET Privileges, _In_ BOOLEAN AccessGranted @@ -2859,7 +2893,7 @@ NTSYSCALLAPI NTSTATUS NTAPI ZwPrivilegeObjectAuditAlarm( - _In_ PUNICODE_STRING SubsystemName, + _In_ PCUNICODE_STRING SubsystemName, _In_opt_ PVOID HandleId, _In_ HANDLE ClientToken, _In_ ACCESS_MASK DesiredAccess, @@ -2920,7 +2954,7 @@ NTSYSCALLAPI NTSTATUS NTAPI ZwQueryAttributesFile( - _In_ POBJECT_ATTRIBUTES ObjectAttributes, + _In_ PCOBJECT_ATTRIBUTES ObjectAttributes, _Out_ PFILE_BASIC_INFORMATION FileInformation ); @@ -2983,7 +3017,7 @@ ZwQueryDirectoryFile( _In_ ULONG Length, _In_ FILE_INFORMATION_CLASS FileInformationClass, _In_ BOOLEAN ReturnSingleEntry, - _In_opt_ PUNICODE_STRING FileName, + _In_opt_ PCUNICODE_STRING FileName, _In_ BOOLEAN RestartScan ); @@ -3000,7 +3034,7 @@ ZwQueryDirectoryFileEx( _In_ ULONG Length, _In_ FILE_INFORMATION_CLASS FileInformationClass, _In_ ULONG QueryFlags, - _In_opt_ PUNICODE_STRING FileName + _In_opt_ PCUNICODE_STRING FileName ); NTSYSCALLAPI @@ -3054,7 +3088,7 @@ NTSYSCALLAPI NTSTATUS NTAPI ZwQueryFullAttributesFile( - _In_ POBJECT_ATTRIBUTES ObjectAttributes, + _In_ PCOBJECT_ATTRIBUTES ObjectAttributes, _Out_ PFILE_NETWORK_OPEN_INFORMATION FileInformation ); @@ -3073,13 +3107,24 @@ NTSYSCALLAPI NTSTATUS NTAPI ZwQueryInformationByName( - _In_ POBJECT_ATTRIBUTES ObjectAttributes, + _In_ PCOBJECT_ATTRIBUTES ObjectAttributes, _Out_ PIO_STATUS_BLOCK IoStatusBlock, _Out_writes_bytes_(Length) PVOID FileInformation, _In_ ULONG Length, _In_ FILE_INFORMATION_CLASS FileInformationClass ); +NTSYSCALLAPI +NTSTATUS +NTAPI +ZwQueryInformationCpuPartition( + _In_ HANDLE CpuPartitionHandle, + _In_ ULONG CpuPartitionInformationClass, + _Out_writes_bytes_opt_(CpuPartitionInformationLength) PVOID CpuPartitionInformation, + _In_ ULONG CpuPartitionInformationLength, + _Out_opt_ PULONG ReturnLength + ); + NTSYSCALLAPI NTSTATUS NTAPI @@ -3250,7 +3295,7 @@ NTSYSCALLAPI NTSTATUS NTAPI ZwQueryLicenseValue( - _In_ PUNICODE_STRING ValueName, + _In_ PCUNICODE_STRING ValueName, _Out_opt_ PULONG Type, _Out_writes_bytes_to_opt_(DataSize, *ResultDataSize) PVOID Data, _In_ ULONG DataSize, @@ -3355,7 +3400,7 @@ NTSTATUS NTAPI ZwQuerySecurityAttributesToken( _In_ HANDLE TokenHandle, - _In_reads_opt_(NumberOfAttributes) PUNICODE_STRING Attributes, + _In_reads_opt_(NumberOfAttributes) PCUNICODE_STRING Attributes, _In_ ULONG NumberOfAttributes, _Out_writes_bytes_(Length) PVOID Buffer, // PTOKEN_SECURITY_ATTRIBUTES_INFORMATION _In_ ULONG Length, @@ -3409,7 +3454,7 @@ NTSYSCALLAPI NTSTATUS NTAPI ZwQuerySystemEnvironmentValue( - _In_ PUNICODE_STRING VariableName, + _In_ PCUNICODE_STRING VariableName, _Out_writes_bytes_(ValueLength) PWSTR VariableValue, _In_ USHORT ValueLength, _Out_opt_ PUSHORT ReturnLength @@ -3480,7 +3525,7 @@ NTSTATUS NTAPI ZwQueryValueKey( _In_ HANDLE KeyHandle, - _In_ PUNICODE_STRING ValueName, + _In_ PCUNICODE_STRING ValueName, _In_ KEY_VALUE_INFORMATION_CLASS KeyValueInformationClass, _Out_writes_bytes_to_opt_(Length, *ResultLength) PVOID KeyValueInformation, _In_ ULONG Length, @@ -3516,10 +3561,10 @@ NTAPI ZwQueryWnfStateData( _In_ PCWNF_STATE_NAME StateName, _In_opt_ PCWNF_TYPE_ID TypeId, - _In_opt_ const VOID* ExplicitScope, + _In_opt_ PCSID ExplicitScope, _Out_ PWNF_CHANGE_STAMP ChangeStamp, - _Out_writes_bytes_opt_(*BufferSize) PVOID Buffer, - _Inout_ PULONG BufferSize + _Out_writes_bytes_opt_(*BufferLength) PVOID Buffer, + _Inout_ PULONG BufferLength ); NTSYSCALLAPI @@ -3528,9 +3573,9 @@ 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 + _In_opt_ PCSID ExplicitScope, + _Out_writes_bytes_(BufferLength) PVOID Buffer, + _In_ ULONG BufferLength ); NTSYSCALLAPI @@ -3780,14 +3825,14 @@ NTSTATUS NTAPI ZwRenameKey( _In_ HANDLE KeyHandle, - _In_ PUNICODE_STRING NewName + _In_ PCUNICODE_STRING NewName ); NTSYSCALLAPI NTSTATUS NTAPI ZwRenameTransactionManager( - _In_ PUNICODE_STRING LogFileName, + _In_ PCUNICODE_STRING LogFileName, _In_ LPGUID ExistingTransactionManagerGuid ); @@ -3804,8 +3849,8 @@ NTSYSCALLAPI NTSTATUS NTAPI ZwReplacePartitionUnit( - _In_ PUNICODE_STRING TargetInstancePath, - _In_ PUNICODE_STRING SpareInstancePath, + _In_ PCUNICODE_STRING TargetInstancePath, + _In_ PCUNICODE_STRING SpareInstancePath, _In_ ULONG Flags ); @@ -3934,6 +3979,14 @@ ZwRollbackEnlistment( _In_opt_ PLARGE_INTEGER TmVirtualClock ); +NTSYSCALLAPI +NTSTATUS +NTAPI +ZwRollbackRegistryTransaction( + _In_ HANDLE RegistryTransactionHandle, + _Reserved_ ULONG Flags + ); + NTSYSCALLAPI NTSTATUS NTAPI @@ -3981,7 +4034,7 @@ NTSTATUS NTAPI ZwSecureConnectPort( _Out_ PHANDLE PortHandle, - _In_ PUNICODE_STRING PortName, + _In_ PCUNICODE_STRING PortName, _In_ PSECURITY_QUALITY_OF_SERVICE SecurityQos, _Inout_opt_ PPORT_VIEW ClientView, _In_opt_ PSID RequiredServerSid, @@ -4465,7 +4518,7 @@ ZwSetTimer2( _In_ HANDLE TimerHandle, _In_ PLARGE_INTEGER DueTime, _In_opt_ PLARGE_INTEGER Period, - _In_ PT2_SET_PARAMETERS Parameters + _In_opt_ PT2_SET_PARAMETERS Parameters ); NTSYSCALLAPI @@ -4499,7 +4552,7 @@ NTSTATUS NTAPI ZwSetValueKey( _In_ HANDLE KeyHandle, - _In_ PUNICODE_STRING ValueName, + _In_ PCUNICODE_STRING ValueName, _In_opt_ ULONG TitleIndex, _In_ ULONG Type, _In_reads_bytes_opt_(DataSize) PVOID Data, @@ -4714,7 +4767,7 @@ NTSYSCALLAPI NTSTATUS NTAPI ZwUnloadDriver( - _In_ PUNICODE_STRING DriverServiceName + _In_ PCUNICODE_STRING DriverServiceName ); NTSYSCALLAPI @@ -4793,7 +4846,7 @@ ZwUpdateWnfStateData( _In_reads_bytes_opt_(Length) const VOID* Buffer, _In_opt_ ULONG Length, _In_opt_ PCWNF_TYPE_ID TypeId, - _In_opt_ const VOID* ExplicitScope, + _In_opt_ PCSID ExplicitScope, _In_ WNF_CHANGE_STAMP MatchingChangeStamp, _In_ LOGICAL CheckStamp ); @@ -4870,10 +4923,7 @@ 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 + _Out_ PFILE_IO_COMPLETION_INFORMATION MiniPacket ); NTSYSCALLAPI @@ -4897,51 +4947,6 @@ ZwWorkerFactoryWorkerReady( _In_ HANDLE WorkerFactoryHandle ); -NTSYSCALLAPI -NTSTATUS -NTAPI -ZwWow64QueryInformationProcess64( - _In_ HANDLE ProcessHandle, - _In_ PROCESSINFOCLASS ProcessInformationClass, - _Out_writes_bytes_(ProcessInformationLength) PVOID ProcessInformation, - _In_ ULONG ProcessInformationLength, - _Out_opt_ PULONG ReturnLength - ); - -NTSYSCALLAPI -NTSTATUS -NTAPI -ZwWow64QueryVirtualMemory64( - _In_ HANDLE ProcessHandle, - _In_opt_ ULONGLONG BaseAddress, - _In_ MEMORY_INFORMATION_CLASS MemoryInformationClass, - _Out_writes_bytes_(MemoryInformationLength) PVOID MemoryInformation, - _In_ ULONGLONG MemoryInformationLength, - _Out_opt_ PULONGLONG ReturnLength - ); - -NTSYSCALLAPI -NTSTATUS -NTAPI -ZwWow64ReadVirtualMemory64( - _In_ HANDLE ProcessHandle, - _In_opt_ ULONGLONG BaseAddress, - _Out_writes_bytes_to_(NumberOfBytesToRead, *NumberOfBytesRead) PVOID Buffer, - _In_ ULONGLONG NumberOfBytesToRead, - _Out_opt_ PULONGLONG NumberOfBytesRead - ); - -NTSYSCALLAPI -NTSTATUS -NTAPI -ZwWow64WriteVirtualMemory64( - _In_ HANDLE ProcessHandle, - _In_opt_ ULONGLONG BaseAddress, - _In_reads_bytes_(NumberOfBytesToWrite) PVOID Buffer, - _In_ ULONGLONG NumberOfBytesToWrite, - _Out_opt_ PULONGLONG NumberOfBytesWritten - ); - NTSYSCALLAPI NTSTATUS NTAPI diff --git a/phnt.h b/phnt.h index db0a3d2..501a54e 100644 --- a/phnt.h +++ b/phnt.h @@ -55,10 +55,16 @@ #define PHNT_WINDOWS_11_22H2 115 // September, 2022 // Build 22621 #define PHNT_WINDOWS_11_23H2 116 // October, 2023 // Build 22631 #define PHNT_WINDOWS_11_24H2 117 // October, 2024 // Build 26100 +#define PHNT_WINDOWS_11_25H2 117 // October, 2025 // Build 26200 #define PHNT_WINDOWS_NEW ULONG_MAX #ifndef PHNT_MODE -#define PHNT_MODE PHNT_MODE_USER +// Auto-detect kernel mode when building with WDK or kernel headers. +#if defined(_NTDDK_) || defined(_NTIFS_) || defined(_NTDRIVER_) + #define PHNT_MODE PHNT_MODE_KERNEL +#else + #define PHNT_MODE PHNT_MODE_USER +#endif #endif #ifndef PHNT_VERSION @@ -78,23 +84,29 @@ #endif // !PHNT_INLINE_TYPEDEFS #endif // (PHNT_MODE != PHNT_MODE_KERNEL) +// +// Headers +// + EXTERN_C_START #if (PHNT_MODE != PHNT_MODE_KERNEL) #include #include +#include +#include #endif // (PHNT_MODE != PHNT_MODE_KERNEL) #include #include #include -#include #include #include #include #if (PHNT_MODE != PHNT_MODE_KERNEL) +#include #include #include #include @@ -114,7 +126,6 @@ EXTERN_C_START #include #include #include -#include #endif // (PHNT_MODE != PHNT_MODE_KERNEL) EXTERN_C_END @@ -122,4 +133,4 @@ EXTERN_C_END static_assert(__alignof(LARGE_INTEGER) == 8, "Windows headers require the default packing option. Changing the packing can lead to memory corruption."); static_assert(__alignof(PROCESS_CYCLE_TIME_INFORMATION) == 8, "PHNT headers require the default packing option. Changing the packing can lead to memory corruption."); -#endif +#endif // _PHNT_H diff --git a/phnt_ntdef.h b/phnt_ntdef.h index 941baa6..b931511 100644 --- a/phnt_ntdef.h +++ b/phnt_ntdef.h @@ -21,6 +21,13 @@ // Basic types // +/** + * The QUAD structure is a union used for 64-bit values or double precision. + * + * This structure is used to represent a 64-bit integer or a double value. + * The field `UseThisFieldToCopy` is intended for copying the structure, + * while `DoNotUseThisField` should not be used directly. + */ typedef struct _QUAD { union @@ -30,16 +37,28 @@ typedef struct _QUAD }; } QUAD, *PQUAD; -// This isn't in NT, but it's useful. +/** + * The QUAD_PTR structure is a utility structure for pointer-sized fields. + * + * This structure is not part of NT, but is useful. + */ typedef struct DECLSPEC_ALIGN(MEMORY_ALLOCATION_ALIGNMENT) _QUAD_PTR { ULONG_PTR DoNotUseThisField1; ULONG_PTR DoNotUseThisField2; } QUAD_PTR, *PQUAD_PTR; +/** + * The LOGICAL type is an unsigned long used by the NT API for boolean logic. + */ typedef ULONG LOGICAL; typedef ULONG *PLOGICAL; +/** + * The NTSTATUS type is a signed long used for NT API status codes. + * + * Functions returning NTSTATUS indicate success or error conditions. + */ typedef _Return_type_success_(return >= 0) LONG NTSTATUS; typedef NTSTATUS *PNTSTATUS; @@ -55,26 +74,56 @@ typedef CCHAR *PCCHAR; typedef CSHORT *PCSHORT; typedef CLONG *PCLONG; +/** + * The PCSZ type is a pointer to a constant string. + */ typedef PCSTR PCSZ; +/** + * The PPVOID type is a pointer to a pointer to void. + */ typedef PVOID* PPVOID; + +/** + * The PCVOID type is a pointer to a constant void. + */ typedef CONST VOID *PCVOID; // // Specific // +/** + * The KIRQL type is an unsigned char used by the NT API for kernel IRQL (Interrupt Request Level). + */ typedef UCHAR KIRQL, *PKIRQL; + +/** + * The KPRIORITY type is a signed long used by the NT API for kernel priority values. + */ typedef LONG KPRIORITY, *PKPRIORITY; + +/** + * The RTL_ATOM type is an unsigned short used by the NT API for Atom values. + */ typedef USHORT RTL_ATOM, *PRTL_ATOM; +/** + * The PHYSICAL_ADDRESS type is a LARGE_INTEGER representing a physical address. + */ typedef LARGE_INTEGER PHYSICAL_ADDRESS, *PPHYSICAL_ADDRESS; +/** + * The LARGE_INTEGER_128 structure represents a 128-bit signed integer. + */ typedef struct _LARGE_INTEGER_128 { LONGLONG QuadPart[2]; } LARGE_INTEGER_128, *PLARGE_INTEGER_128; +/** + * The ULARGE_INTEGER_128 structure represents a 128-bit unsigned integer. + */ typedef struct _ULARGE_INTEGER_128 { ULONGLONG QuadPart[2]; @@ -157,18 +206,27 @@ typedef struct _ULARGE_INTEGER_128 // Synchronization enumerations // +/** + * Event types used with kernel synchronization objects. + */ typedef enum _EVENT_TYPE { NotificationEvent, SynchronizationEvent } EVENT_TYPE; +/** + * Timer types used by kernel timer objects. + */ typedef enum _TIMER_TYPE { NotificationTimer, SynchronizationTimer } TIMER_TYPE; +/** + * Wait operation types for kernel wait routines. + */ typedef enum _WAIT_TYPE { WaitAll, @@ -182,6 +240,11 @@ typedef enum _WAIT_TYPE // Strings // +/** + * The ANSI_STRING structure defines a counted string used for ANSI strings. + * + * \sa https://learn.microsoft.com/en-us/windows/win32/api/ntdef/ns-ntdef-string + */ typedef struct _STRING { USHORT Length; @@ -195,7 +258,13 @@ typedef PSTRING PUTF8_STRING; typedef const STRING *PCSTRING; typedef const ANSI_STRING *PCANSI_STRING; typedef const OEM_STRING *PCOEM_STRING; +typedef const STRING *PCUTF8_STRING; +/** + * The UNICODE_STRING structure defines a counted string used for Unicode strings. + * + * \sa https://learn.microsoft.com/en-us/windows/win32/api/ntdef/ns-ntdef-_unicode_string + */ typedef struct _UNICODE_STRING { USHORT Length; @@ -205,7 +274,28 @@ typedef struct _UNICODE_STRING typedef const UNICODE_STRING *PCUNICODE_STRING; -#define RTL_CONSTANT_STRING(s) { sizeof((s)) - sizeof((s)[0]), sizeof((s)), (PWCH)(s) } +#ifdef __cplusplus +extern "C++" +{ +template char _RTL_CONSTANT_STRING_type_check(const char (&s)[N]); +template char _RTL_CONSTANT_STRING_type_check(const WCHAR (&s)[N]); +// __typeof would be desirable here instead of sizeof. +template class _RTL_CONSTANT_STRING_remove_const_template_class; +template <> class _RTL_CONSTANT_STRING_remove_const_template_class {public: typedef char T; }; +template <> class _RTL_CONSTANT_STRING_remove_const_template_class {public: typedef WCHAR T; }; +#define _RTL_CONSTANT_STRING_remove_const_macro(s) \ + (const_cast<_RTL_CONSTANT_STRING_remove_const_template_class::T*>(s)) +} +#else +char _RTL_CONSTANT_STRING_type_check(const void *s); +#define _RTL_CONSTANT_STRING_remove_const_macro(s) (s) +#endif +#define RTL_CONSTANT_STRING(s) \ +{ \ + sizeof( s ) - sizeof( (s)[0] ), \ + sizeof( s ) / (sizeof(_RTL_CONSTANT_STRING_type_check(s))), \ + _RTL_CONSTANT_STRING_remove_const_macro(s) \ +} #define DECLARE_CONST_UNICODE_STRING(_var, _str) \ const WCHAR _var ## _buffer[] = _str; \ @@ -259,6 +349,11 @@ typedef struct _SINGLE_LIST_ENTRY32 ULONG Next; } SINGLE_LIST_ENTRY32, *PSINGLE_LIST_ENTRY32; +/** + * The STRING32 structure is a 32-bit thunked representation of the `STRING` structure. + * + * \remarks Used for marshaling between 32-bit and 64-bit contexts. + */ typedef struct _STRING32 { USHORT Length; @@ -269,6 +364,14 @@ typedef struct _STRING32 typedef STRING32 UNICODE_STRING32, *PUNICODE_STRING32; typedef STRING32 ANSI_STRING32, *PANSI_STRING32; +typedef const STRING32 *PCUNICODE_STRING32; +typedef const STRING32 *PCANSI_STRING32; + +/** + * The STRING64 structure is a 64-bit thunked representation of the `STRING` structure. + * + * \remarks Used for marshaling between 64-bit and 32-bit contexts. + */ typedef struct _STRING64 { USHORT Length; @@ -279,37 +382,115 @@ typedef struct _STRING64 typedef STRING64 UNICODE_STRING64, *PUNICODE_STRING64; typedef STRING64 ANSI_STRING64, *PANSI_STRING64; +typedef const STRING64 *PCUNICODE_STRING64; +typedef const STRING64 *PCANSI_STRING64; + // // Object attributes // +/** + * Protects the object from being closed by certain APIs (platform specific). + */ #define OBJ_PROTECT_CLOSE 0x00000001L +/** + * This handle can be inherited by child processes of the current process. + */ #define OBJ_INHERIT 0x00000002L +/** + * Request auditing when the object is closed. + */ #define OBJ_AUDIT_OBJECT_CLOSE 0x00000004L +/** + * Prevents automatic rights upgrade on the object. + */ #define OBJ_NO_RIGHTS_UPGRADE 0x00000008L +/** + * This flag only applies to objects that are named within the object manager. + * By default such objects are deleted when all open handles to them are closed. + * If this flag is specified, the object is not deleted when all open handles are closed. + * The NtMakeTemporaryObject function can be used to delete permanent objects. + */ #define OBJ_PERMANENT 0x00000010L +/** + * OBJ_EXCLUSIVE 0x00000020L + * + * Only a single handle can be open for this object. + */ #define OBJ_EXCLUSIVE 0x00000020L +/** + * If this flag is specified, a case-insensitive comparison is used when matching the name + * pointed to by the ObjectName member against the names of existing objects. + * Otherwise, object names are compared using the default system settings. + */ #define OBJ_CASE_INSENSITIVE 0x00000040L +/** + * If this flag is specified, by using the object handle, to a routine that creates objects + * and if that object already exists, the routine should open that object. + * Otherwise, the routine creating the object returns an NTSTATUS code of STATUS_OBJECT_NAME_COLLISION. + */ #define OBJ_OPENIF 0x00000080L +/** + * If an object handle, with this flag set, is passed to a routine that opens objects + * and if the object is a symbolic link object, the routine should open the symbolic link + * object itself, rather than the object that the symbolic link refers to (which is the default behavior). + */ #define OBJ_OPENLINK 0x00000100L +/** + * The handle is created in system process context and can only be accessed from kernel mode. + */ #define OBJ_KERNEL_HANDLE 0x00000200L +/** + * The routine opening the handle should enforce all access checks for the object, + * even if the handle is being opened in kernel mode. + */ #define OBJ_FORCE_ACCESS_CHECK 0x00000400L +/** + * Separate device maps exists for each user in the system, and each user can manage + * their own device maps. If this flag is set, the process user's device map is used + * during impersonation instead of the impersonated user's device map. + */ #define OBJ_IGNORE_IMPERSONATED_DEVICEMAP 0x00000800L +/** + * If this flag is set, no reparse points will be followed when parsing the name of the associated object. + * If any reparses are encountered the attempt will fail and return an STATUS_REPARSE_POINT_ENCOUNTERED result. + * This can be used to determine if there are any reparse points in the object's path, in security scenarios. + */ #define OBJ_DONT_REPARSE 0x00001000L +/** + * Mask of valid object attribute flags. + */ #define OBJ_VALID_ATTRIBUTES 0x00001FF2L +/** + * The OBJECT_ATTRIBUTES structure specifies attributes that can be applied + * to objects or object handles by routines that create objects and/or return handles to objects. + * + * \sa https://learn.microsoft.com/en-us/windows/win32/api/ntdef/ns-ntdef-_object_attributes + */ typedef struct _OBJECT_ATTRIBUTES { ULONG Length; HANDLE RootDirectory; PCUNICODE_STRING ObjectName; ULONG Attributes; - PVOID SecurityDescriptor; // PSECURITY_DESCRIPTOR; - PVOID SecurityQualityOfService; // PSECURITY_QUALITY_OF_SERVICE + PSECURITY_DESCRIPTOR SecurityDescriptor; + PSECURITY_QUALITY_OF_SERVICE SecurityQualityOfService; } OBJECT_ATTRIBUTES, *POBJECT_ATTRIBUTES; typedef const OBJECT_ATTRIBUTES *PCOBJECT_ATTRIBUTES; +/** + * The InitializeObjectAttributes macro initializes the opaque OBJECT_ATTRIBUTES structure, + * which specifies the properties of an object handle to routines that open handles. + * + * \param p A pointer to the OBJECT_ATTRIBUTES structure to initialize. + * \param n A pointer to a Unicode string that contains a fully qualified object name, or a relative path name for which a handle is to be opened. + * \param a Specifies one or more of the OBJ_* attributes flags. + * \param r A handle to the root object directory for the path name specified in the ObjectName parameter + * \param s A pointer to a security descriptor to apply to an object when it is created or NULL to accept the default security for the object. + * \sa https://learn.microsoft.com/en-us/windows/win32/api/ntdef/ns-ntdef-_object_attributes + */ #define InitializeObjectAttributes(p, n, a, r, s) { \ (p)->Length = sizeof(OBJECT_ATTRIBUTES); \ (p)->RootDirectory = r; \ @@ -338,6 +519,10 @@ typedef const OBJECT_ATTRIBUTES *PCOBJECT_ATTRIBUTES; // Portability // +/** + * The OBJECT_ATTRIBUTES64 structure is a 64-bit thunked representation of OBJECT_ATTRIBUTES. + * \remarks Used for marshaling between 64-bit and 32-bit contexts. + */ typedef struct _OBJECT_ATTRIBUTES64 { ULONG Length; @@ -350,6 +535,10 @@ typedef struct _OBJECT_ATTRIBUTES64 typedef const OBJECT_ATTRIBUTES64 *PCOBJECT_ATTRIBUTES64; +/** + * The OBJECT_ATTRIBUTES32 structure is a 32-bit thunked representation of OBJECT_ATTRIBUTES. + * \remarks Used for marshaling between 32-bit and 64-bit contexts. + */ typedef struct _OBJECT_ATTRIBUTES32 { ULONG Length; @@ -366,6 +555,9 @@ typedef const OBJECT_ATTRIBUTES32 *PCOBJECT_ATTRIBUTES32; // Product types // +/** + * The NT_PRODUCT_TYPE enum identifies the Windows product family for the operating system. + */ typedef enum _NT_PRODUCT_TYPE { NtProductWinNt = 1, @@ -373,6 +565,9 @@ typedef enum _NT_PRODUCT_TYPE NtProductServer } NT_PRODUCT_TYPE, *PNT_PRODUCT_TYPE; +/** + * The SUITE_TYPE enum represents the installed Windows product suite or feature set. + */ typedef enum _SUITE_TYPE { SmallBusiness, @@ -399,26 +594,40 @@ typedef enum _SUITE_TYPE // Specific // +/** + * The CLIENT_ID structure contains identifiers of a process and a thread. + * + * \sa https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-tsts/a11e7129-685b-4535-8d37-21d4596ac057 + */ typedef struct _CLIENT_ID { HANDLE UniqueProcess; HANDLE UniqueThread; } CLIENT_ID, *PCLIENT_ID; +/** + * The CLIENT_ID32 structure is a 32-bit version of CLIENT_ID. + * \remarks Used for marshaling between 32-bit and 64-bit contexts. + */ typedef struct _CLIENT_ID32 { ULONG UniqueProcess; ULONG UniqueThread; } CLIENT_ID32, *PCLIENT_ID32; +/** + * The CLIENT_ID64 structure is a 64-bit version of CLIENT_ID. + * \remarks Used for marshaling between 64-bit and 32-bit contexts. + */ typedef struct _CLIENT_ID64 { ULONGLONG UniqueProcess; ULONGLONG UniqueThread; } CLIENT_ID64, *PCLIENT_ID64; -#include - +/** + * The KSYSTEM_TIME structure represents interrupt time, system time, and time zone bias. + */ typedef struct _KSYSTEM_TIME { ULONG LowPart; @@ -426,7 +635,272 @@ typedef struct _KSYSTEM_TIME LONG High2Time; } KSYSTEM_TIME, *PKSYSTEM_TIME; -#include +#if defined(__INTELLISENSE__) || defined(DOXYGEN) + +#ifndef AFFINITY_MASK +/** + * The AFFINITY_MASK macro creates a single-bit affinity mask from an index. + * + * \param n Zero-based bit index. + * \return A `KAFFINITY` mask with only bit @p n set. + * \remarks Shifting by a value >= bit-width of `KAFFINITY` is undefined behavior. + */ +#define AFFINITY_MASK(n) ((KAFFINITY)1 << (n)) +#endif + +#ifndef FlagOn +/** + * The FlagOn macro tests whether any bits in a subset are set in a flag value. + * + * \param _F The flag value to test. + * \param _SF The subset of flags to test for. + * \return Non-zero if any bits in @p _SF are set in @p _F; otherwise zero. + * \remarks This returns the raw AND result (not normalized to BOOLEAN). + */ +#define FlagOn(_F, _SF) ((_F) & (_SF)) +#endif + +#ifndef BooleanFlagOn +/** + * The BooleanFlagOn macro tests whether any bits in a subset are set and returns a BOOLEAN. + * + * \param F The flag value to test. + * \param SF The subset of flags to test for. + * \return `TRUE` if any bits in @p SF are set in @p F; otherwise `FALSE`. + * \remarks The result is explicitly converted to `BOOLEAN`. + */ +#define BooleanFlagOn(F, SF) ((BOOLEAN)(((F) & (SF)) != 0)) +#endif + +#ifndef SetFlag +/** + * The SetFlag macro sets bits in a flag value (in-place). + * + * \param _F The flag lvalue to modify. + * \param _SF The bits to set in @p _F. + * \remarks This macro modifies @p _F by OR-ing it with @p _SF. + */ +#define SetFlag(_F, _SF) ((_F) |= (_SF)) +#endif + +#ifndef ClearFlag +/** + * The ClearFlag macro clears bits in a flag value (in-place). + * + * \param _F The flag lvalue to modify. + * \param _SF The bits to clear from @p _F. + * \remarks This macro modifies @p _F by AND-ing it with the complement of @p _SF. + */ +#define ClearFlag(_F, _SF) ((_F) &= ~(_SF)) +#endif + +#ifndef Add2Ptr +/** + * The Add2Ptr macro adds a byte offset to a pointer. + * + * \param P The base pointer. + * \param I The byte offset to add. + * \return A pointer equal to @p P advanced by @p I bytes. + * \remarks The addition is performed using `PUCHAR` arithmetic and cast to `PVOID`. + */ +#define Add2Ptr(P,I) ((PVOID)((PUCHAR)(P) + (I))) +#endif + +#ifndef PtrOffset +/** + * The PtrOffset macro computes the byte offset between two pointers. + * + * \param B The base pointer. + * \param O The other pointer. + * \return The byte offset from @p B to @p O, cast to `ULONG`. + * \remarks If the true offset does not fit in `ULONG`, truncation may occur. + */ +#define PtrOffset(B,O) ((ULONG)((ULONG_PTR)(O) - (ULONG_PTR)(B))) +#endif + +#ifndef ALIGN_DOWN_BY +/** + * The ALIGN_DOWN_BY macro aligns a value down to a specified alignment boundary. + * + * \param Length The value to align. + * \param Alignment The alignment boundary in bytes (typically a power of two). + * \return @p Length rounded down to the nearest multiple of @p Alignment. + * \remarks Non power-of-two alignments may produce unexpected results. + */ +#define ALIGN_DOWN_BY(Length, Alignment) ((ULONG_PTR)(Length) & ~((ULONG_PTR)(Alignment) - 1)) +#endif + +#ifndef ALIGN_UP_BY +/** + * The ALIGN_UP_BY macro aligns a value up to a specified alignment boundary. + * + * \param Length The value to align. + * \param Alignment The alignment boundary in bytes (typically a power of two). + * \return @p Length rounded up to the nearest multiple of @p Alignment. + * \remarks This uses ALIGN_DOWN_BY after adding (@p Alignment - 1). + */ +#define ALIGN_UP_BY(Length, Alignment) (ALIGN_DOWN_BY(((ULONG_PTR)(Length) + (Alignment) - 1), Alignment)) +#endif + +#ifndef ALIGN_DOWN_POINTER_BY +/** + * The ALIGN_DOWN_POINTER_BY macro aligns a pointer down to a specified alignment boundary. + * + * \param Address The pointer to align. + * \param Alignment The alignment boundary in bytes (typically a power of two). + * \return A pointer at or below @p Address aligned down to @p Alignment. + * \remarks The pointer is treated as an integer (`ULONG_PTR`) for masking. + */ +#define ALIGN_DOWN_POINTER_BY(Address, Alignment) ((PVOID)ALIGN_DOWN_BY(Address, Alignment)) +#endif + +#ifndef ALIGN_UP_POINTER_BY +/** + * The ALIGN_UP_POINTER_BY macro aligns a pointer up to a specified alignment boundary. + * + * \param Address The pointer to align. + * \param Alignment The alignment boundary in bytes (typically a power of two). + * \return A pointer at or above @p Address aligned up to @p Alignment. + * \remarks This is a pointer wrapper over ALIGN_UP_BY. + */ +#define ALIGN_UP_POINTER_BY(Address, Alignment) ((PVOID)ALIGN_UP_BY(Address, Alignment)) +#endif + +#ifndef ALIGN_DOWN +/** + * The ALIGN_DOWN macro aligns a value down using sizeof(Type) as the boundary. + * + * \param Length The value to align. + * \param Type The type whose size is used as the alignment boundary. + * \return @p Length rounded down to the nearest multiple of sizeof(@p Type). + * \remarks This is a convenience wrapper over ALIGN_DOWN_BY. + */ +#define ALIGN_DOWN(Length, Type) ALIGN_DOWN_BY(Length, sizeof(Type)) +#endif + +#ifndef ALIGN_UP +/** + * The ALIGN_UP macro aligns a value up using sizeof(Type) as the boundary. + * + * \param Length The value to align. + * \param Type The type whose size is used as the alignment boundary. + * \return @p Length rounded up to the nearest multiple of sizeof(@p Type). + * \remarks This is a convenience wrapper over ALIGN_UP_BY. + */ +#define ALIGN_UP(Length, Type) ALIGN_UP_BY(Length, sizeof(Type)) +#endif + +#ifndef ALIGN_DOWN_POINTER +/** + * The ALIGN_DOWN_POINTER macro aligns a pointer down using sizeof(Type) as the boundary. + * + * \param Address The pointer to align. + * \param Type The type whose size is used as the alignment boundary. + * \return A pointer at or below @p Address aligned down to sizeof(@p Type). + * \remarks This is a convenience wrapper over ALIGN_DOWN_POINTER_BY. + */ +#define ALIGN_DOWN_POINTER(Address, Type) ALIGN_DOWN_POINTER_BY(Address, sizeof(Type)) +#endif + +#ifndef ALIGN_UP_POINTER +/** + * The ALIGN_UP_POINTER macro aligns a pointer up using sizeof(Type) as the boundary. + * + * \param Address The pointer to align. + * \param Type The type whose size is used as the alignment boundary. + * \return A pointer at or above @p Address aligned up to sizeof(@p Type). + * \remarks This is a convenience wrapper over ALIGN_UP_POINTER_BY. + */ +#define ALIGN_UP_POINTER(Address, Type) ALIGN_UP_POINTER_BY(Address, sizeof(Type)) +#endif + +#ifndef IS_ALIGNED +/** + * The IS_ALIGNED macro tests whether an address is aligned to a given boundary. + * + * \param Address The address/pointer value to test. + * \param Alignment The alignment boundary in bytes (typically a power of two). + * \return Non-zero if @p Address is aligned to @p Alignment; otherwise zero. + * \remarks The test checks that the low bits masked by (@p Alignment - 1) are zero. + */ +#define IS_ALIGNED(Address, Alignment) ((((ULONG_PTR)(Address)) & ((Alignment) - 1)) == 0) +#endif + +#ifndef PAGE_SIZE +/** + * The PAGE_SIZE macro defines the assumed system page size in bytes. + * + * \return The page size in bytes (default 0x1000). + * \remarks This assumes 4 KiB pages. + */ +#define PAGE_SIZE 0x1000 +#endif + +#ifndef PAGE_MASK +/** + * The PAGE_MASK macro defines the mask for offsets within a page. + * + * \return The page offset mask (default 0xFFF). + * \remarks This is typically PAGE_SIZE - 1 for power-of-two page sizes. + */ +#define PAGE_MASK 0xFFF +#endif + +#ifndef PAGE_SHIFT +/** + * The PAGE_SHIFT macro defines the bit shift corresponding to PAGE_SIZE. + * + * \return The shift value (default 0xC, i.e., 12). + * \remarks For 4 KiB pages, PAGE_SHIFT is 12 because 2^12 = 4096. + */ +#define PAGE_SHIFT 0xC +#endif + +#ifndef BYTE_OFFSET +/** + * The BYTE_OFFSET macro returns the byte offset of an address within its page. + * + * \param Address The address/pointer value. + * \return The offset in bytes within the containing page. + * \remarks This masks the address with PAGE_MASK. + */ +#define BYTE_OFFSET(Address) ((SIZE_T)((ULONG_PTR)(Address) & PAGE_MASK)) +#endif + +#ifndef PAGE_ALIGN +/** + * The PAGE_ALIGN macro aligns an address down to the base of its page. + * + * \param Address The address/pointer value. + * \return The page-aligned base address containing @p Address. + * \remarks This clears the low bits specified by PAGE_MASK. + */ +#define PAGE_ALIGN(Address) ((PVOID)((ULONG_PTR)(Address) & ~PAGE_MASK)) +#endif + +#ifndef PAGE_OFFSET +/** + * The PAGE_OFFSET macro returns the offset of a pointer within its page. + * + * \param p The pointer value. + * \return The offset in bytes within the page (0..PAGE_MASK). + * \remarks This is equivalent to (PAGE_MASK & (ULONG_PTR)p). + */ +#define PAGE_OFFSET(p) ((PAGE_MASK) & (ULONG_PTR)(p)) +#endif + +#ifndef PAGE_TAILSIZE +/** + * The PAGE_TAILSIZE macro returns the number of bytes from a pointer to the end of its page. + * + * \param p The pointer value. + * \return The remaining bytes in the page starting at @p p. + * \remarks This is computed as PAGE_SIZE - PAGE_OFFSET(p). + */ +#define PAGE_TAILSIZE(p) (PAGE_SIZE - PAGE_OFFSET(p)) +#endif + +#else #ifndef AFFINITY_MASK #define AFFINITY_MASK(n) ((KAFFINITY)1 << (n)) @@ -452,32 +926,32 @@ typedef struct _KSYSTEM_TIME #define PtrOffset(B,O) ((ULONG)((ULONG_PTR)(O) - (ULONG_PTR)(B))) #endif -#ifndef ALIGN_UP_BY -#define ALIGN_UP_BY(Address, Align) (((ULONG_PTR)(Address) + (Align) - 1) & ~((Align) - 1)) -#endif -#ifndef ALIGN_UP_POINTER_BY -#define ALIGN_UP_POINTER_BY(Pointer, Align) ((PVOID)ALIGN_UP_BY(Pointer, Align)) -#endif -#ifndef ALIGN_UP -#define ALIGN_UP(Address, Type) ALIGN_UP_BY(Address, sizeof(Type)) -#endif -#ifndef ALIGN_UP_POINTER -#define ALIGN_UP_POINTER(Pointer, Type) ((PVOID)ALIGN_UP(Pointer, Type)) -#endif #ifndef ALIGN_DOWN_BY -#define ALIGN_DOWN_BY(Address, Align) ((ULONG_PTR)(Address) & ~((ULONG_PTR)(Align) - 1)) +#define ALIGN_DOWN_BY(Length, Alignment) ((ULONG_PTR)(Length) & ~((ULONG_PTR)(Alignment) - 1)) +#endif +#ifndef ALIGN_UP_BY +#define ALIGN_UP_BY(Length, Alignment) (ALIGN_DOWN_BY(((ULONG_PTR)(Length) + (Alignment) - 1), Alignment)) #endif #ifndef ALIGN_DOWN_POINTER_BY -#define ALIGN_DOWN_POINTER_BY(Pointer, Align) ((PVOID)ALIGN_DOWN_BY(Pointer, Align)) +#define ALIGN_DOWN_POINTER_BY(Address, Alignment) ((PVOID)ALIGN_DOWN_BY(Address, Alignment)) +#endif +#ifndef ALIGN_UP_POINTER_BY +#define ALIGN_UP_POINTER_BY(Address, Alignment) ((PVOID)ALIGN_UP_BY(Address, Alignment)) #endif #ifndef ALIGN_DOWN -#define ALIGN_DOWN(Address, Type) ALIGN_DOWN_BY(Address, sizeof(Type)) +#define ALIGN_DOWN(Length, Type) ALIGN_DOWN_BY(Length, sizeof(Type)) +#endif +#ifndef ALIGN_UP +#define ALIGN_UP(Length, Type) ALIGN_UP_BY(Length, sizeof(Type)) #endif #ifndef ALIGN_DOWN_POINTER -#define ALIGN_DOWN_POINTER(Pointer, Type) ((PVOID)ALIGN_DOWN(Pointer, Type)) +#define ALIGN_DOWN_POINTER(Address, Type) ALIGN_DOWN_POINTER_BY(Address, sizeof(Type)) +#endif +#ifndef ALIGN_UP_POINTER +#define ALIGN_UP_POINTER(Address, Type) ALIGN_UP_POINTER_BY(Address, sizeof(Type)) #endif #ifndef IS_ALIGNED -#define IS_ALIGNED(Pointer, Alignment) ((((ULONG_PTR)(Pointer)) & ((Alignment) - 1)) == 0) +#define IS_ALIGNED(Address, Alignment) ((((ULONG_PTR)(Address)) & ((Alignment) - 1)) == 0) #endif #ifndef PAGE_SIZE @@ -493,18 +967,22 @@ typedef struct _KSYSTEM_TIME #ifndef BYTE_OFFSET #define BYTE_OFFSET(Address) ((SIZE_T)((ULONG_PTR)(Address) & PAGE_MASK)) #endif + #ifndef PAGE_ALIGN #define PAGE_ALIGN(Address) ((PVOID)((ULONG_PTR)(Address) & ~PAGE_MASK)) #endif #ifndef PAGE_OFFSET #define PAGE_OFFSET(p) ((PAGE_MASK) & (ULONG_PTR)(p)) #endif +#ifndef PAGE_TAILSIZE +#define PAGE_TAILSIZE(p) (PAGE_SIZE - PAGE_OFFSET(p)) +#endif #ifndef ADDRESS_AND_SIZE_TO_SPAN_PAGES #define ADDRESS_AND_SIZE_TO_SPAN_PAGES(Address, Size) ((BYTE_OFFSET(Address) + ((SIZE_T)(Size)) + PAGE_MASK) >> PAGE_SHIFT) #endif #ifndef ROUND_TO_SIZE -#define ROUND_TO_SIZE(Size, Alignment) ((((ULONG_PTR)(Size))+((Alignment)-1)) & ~(ULONG_PTR)((Alignment)-1)) +#define ROUND_TO_SIZE(Size, Alignment) ((((ULONG_PTR)(Size)) + ((Alignment) - 1)) & ~(ULONG_PTR)((Alignment) - 1)) #endif #ifndef ROUND_TO_PAGES #define ROUND_TO_PAGES(Size) (((ULONG_PTR)(Size) + PAGE_MASK) & ~PAGE_MASK) @@ -513,6 +991,233 @@ typedef struct _KSYSTEM_TIME #define BYTES_TO_PAGES(Size) (((Size) >> PAGE_SHIFT) + (((Size) & PAGE_MASK) != 0)) #endif +#endif // defined(__INTELLISENSE__) || defined(DOXYGEN) + +#ifdef _DEBUG + +#ifndef ASSERT +#define ASSERT( exp ) \ + ((!(exp)) ? \ + (RtlAssert( (PVOID)#exp, (PVOID)__FILE__, __LINE__, NULL ),FALSE) : \ + TRUE) +#endif + +#ifndef ASSERTMSG +#define ASSERTMSG( msg, exp ) \ + ((!(exp)) ? \ + (RtlAssert( (PVOID)#exp, (PVOID)__FILE__, __LINE__, (PSTR)msg ),FALSE) : \ + TRUE) +#endif + +#ifndef RTL_SOFT_ASSERT +#define RTL_SOFT_ASSERT(_exp) \ + ((!(_exp)) ? \ + (DbgPrint("%s(%d): Soft assertion failed\n Expression: %s\n", __FILE__, __LINE__, #_exp),FALSE) : \ + TRUE) +#endif + +#ifndef RTL_SOFT_ASSERTMSG +#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 + +#ifndef RTL_VERIFY +#define RTL_VERIFY ASSERT +#endif +#ifndef RTL_VERIFYMSG +#define RTL_VERIFYMSG ASSERTMSG +#endif + +#ifndef RTL_SOFT_VERIFY +#define RTL_SOFT_VERIFY RTL_SOFT_ASSERT +#endif +#ifndef RTL_SOFT_VERIFYMSG +#define RTL_SOFT_VERIFYMSG RTL_SOFT_ASSERTMSG +#endif + +#else // _DEBUG + +#ifndef ASSERT +#define ASSERT( exp ) ((void) 0) +#endif +#ifndef ASSERTMSG +#define ASSERTMSG( msg, exp ) ((void) 0) +#endif + +#ifndef RTL_SOFT_ASSERT +#define RTL_SOFT_ASSERT(_exp) ((void) 0) +#endif +#ifndef RTL_SOFT_ASSERTMSG +#define RTL_SOFT_ASSERTMSG(_msg, _exp) ((void) 0) +#endif + +#ifndef RTL_VERIFY +#define RTL_VERIFY( exp ) ((exp) ? TRUE : FALSE) +#endif +#ifndef RTL_VERIFYMSG +#define RTL_VERIFYMSG( msg, exp ) ((exp) ? TRUE : FALSE) +#endif + +#ifndef RTL_SOFT_VERIFY +#define RTL_SOFT_VERIFY(_exp) ((_exp) ? TRUE : FALSE) +#endif +#ifndef RTL_SOFT_VERIFYMSG +#define RTL_SOFT_VERIFYMSG(msg, _exp) ((_exp) ? TRUE : FALSE) +#endif + +#endif // _DEBUG + +#ifndef RTL_ASSERT +#define RTL_ASSERT ASSERT +#endif + +#ifndef RTL_ASSERTMSG +#define RTL_ASSERTMSG ASSERTMSG +#endif + +#ifndef NT_ANALYSIS_ASSUME +#if defined(_PREFAST_) +#define NT_ANALYSIS_ASSUME(_exp) _Analysis_assume_(_exp) +#else // _PREFAST_ +#ifdef _DEBUG +#define NT_ANALYSIS_ASSUME(_exp) ((void) 0) +#else // _DEBUG +#define NT_ANALYSIS_ASSUME(_exp) __noop(_exp) +#endif // _DEBUG +#endif // _PREFAST_ +#endif // NT_ANALYSIS_ASSUME + +#ifndef NT_ASSERT_ACTION +#define NT_ASSERT_ACTION(_exp) \ + ((!(_exp)) ? \ + (__annotation(L"Debug", L"AssertFail", L## #_exp), \ + DbgRaiseAssertionFailure(), FALSE) : \ + TRUE) +#endif + +#ifndef NT_ASSERTMSG_ACTION +#define NT_ASSERTMSG_ACTION(_msg, _exp) \ + ((!(_exp)) ? \ + (__annotation(L"Debug", L"AssertFail", L##_msg), \ + DbgRaiseAssertionFailure(), FALSE) : \ + TRUE) +#endif + +#ifndef NT_ASSERTMSGW_ACTION +#define NT_ASSERTMSGW_ACTION(_msg, _exp) \ + ((!(_exp)) ? \ + (__annotation(L"Debug", L"AssertFail", _msg), \ + DbgRaiseAssertionFailure(), FALSE) : \ + TRUE) +#endif + +#ifdef _DEBUG + +#ifndef NT_ASSERT_ASSUME +#define NT_ASSERT_ASSUME(_exp) \ + (NT_ANALYSIS_ASSUME(_exp), NT_ASSERT_ACTION(_exp)) +#endif +#ifndef NT_ASSERTMSG_ASSUME +#define NT_ASSERTMSG_ASSUME(_msg, _exp) \ + (NT_ANALYSIS_ASSUME(_exp), NT_ASSERTMSG_ACTION(_msg, _exp)) +#endif +#ifdef NT_ASSERTMSGW_ASSUME +#define NT_ASSERTMSGW_ASSUME(_msg, _exp) \ + (NT_ANALYSIS_ASSUME(_exp), NT_ASSERTMSGW_ACTION(_msg, _exp)) +#endif + +#ifndef NT_ASSERT_NOASSUME +#define NT_ASSERT_NOASSUME NT_ASSERT_ASSUME +#endif +#ifndef NT_ASSERTMSG_NOASSUME +#define NT_ASSERTMSG_NOASSUME NT_ASSERTMSG_ASSUME +#endif +#ifndef NT_ASSERTMSGW_NOASSUME +#define NT_ASSERTMSGW_NOASSUME NT_ASSERTMSGW_ASSUME +#endif + +#ifndef NT_VERIFY +#define NT_VERIFY NT_ASSERT +#endif +#ifndef NT_VERIFYMSG +#define NT_VERIFYMSG NT_ASSERTMSG +#endif +#ifndef NT_VERIFYMSGW +#define NT_VERIFYMSGW NT_ASSERTMSGW +#endif + +#else // _DEBUG + +#ifndef NT_ASSERT_ASSUME +#define NT_ASSERT_ASSUME(_exp) (NT_ANALYSIS_ASSUME(_exp), 0) +#endif +#ifndef NT_ASSERTMSG_ASSUME +#define NT_ASSERTMSG_ASSUME(_msg, _exp) (NT_ANALYSIS_ASSUME(_exp), 0) +#endif +#ifndef NT_ASSERTMSGW_ASSUME +#define NT_ASSERTMSGW_ASSUME(_msg, _exp) (NT_ANALYSIS_ASSUME(_exp), 0) +#endif + +#ifndef NT_ASSERT_NOASSUME +#define NT_ASSERT_NOASSUME(_exp) ((void) 0) +#endif +#ifndef NT_ASSERTMSG_NOASSUME +#define NT_ASSERTMSG_NOASSUME(_msg, _exp) ((void) 0) +#endif +#ifndef NT_ASSERTMSGW_NOASSUME +#define NT_ASSERTMSGW_NOASSUME(_msg, _exp) ((void) 0) +#endif + +#ifndef NT_VERIFY +#define NT_VERIFY(_exp) (NT_ANALYSIS_ASSUME(_exp), ((_exp) ? TRUE : FALSE)) +#endif +#ifndef NT_VERIFYMSG +#define NT_VERIFYMSG(_msg, _exp ) (NT_ANALYSIS_ASSUME(_exp), ((_exp) ? TRUE : FALSE)) +#endif +#ifndef NT_VERIFYMSGW +#define NT_VERIFYMSGW(_msg, _exp) (NT_ANALYSIS_ASSUME(_exp), ((_exp) ? TRUE : FALSE)) +#endif + +#endif // _DEBUG + +#ifndef NT_FRE_ASSERT +#define NT_FRE_ASSERT(_exp) (NT_ANALYSIS_ASSUME(_exp), NT_ASSERT_ACTION(_exp)) +#endif +#ifndef NT_FRE_ASSERTMSG +#define NT_FRE_ASSERTMSG(_msg, _exp) (NT_ANALYSIS_ASSUME(_exp), NT_ASSERTMSG_ACTION(_msg, _exp)) +#endif +#ifndef NT_FRE_ASSERTMSGW +#define NT_FRE_ASSERTMSGW(_msg, _exp) (NT_ANALYSIS_ASSUME(_exp), NT_ASSERTMSGW_ACTION(_msg, _exp)) +#endif + +#ifdef NT_ASSERT_ALWAYS_ASSUMES + +#ifndef NT_ASSERT +#define NT_ASSERT NT_ASSERT_ASSUME +#endif +#ifndef NT_ASSERTMSG +#define NT_ASSERTMSG NT_ASSERTMSG_ASSUME +#endif +#ifndef NT_ASSERTMSGW +#define NT_ASSERTMSGW NT_ASSERTMSGW_ASSUME +#endif + +#else // NT_ASSERT_ALWAYS_ASSUMES + +#ifndef NT_ASSERT +#define NT_ASSERT NT_ASSERT_NOASSUME +#endif +#ifndef NT_ASSERTMSG +#define NT_ASSERTMSG NT_ASSERTMSG_NOASSUME +#endif +#ifndef NT_ASSERTMSGW +#define NT_ASSERTMSGW NT_ASSERTMSGW_NOASSUME +#endif + +#endif // NT_ASSERT_ALWAYS_ASSUMES + #endif // _NTDEF_ -#endif +#endif // _PHNT_NTDEF_H diff --git a/phnt_windows.h b/phnt_windows.h index 307e72f..1ca19c0 100644 --- a/phnt_windows.h +++ b/phnt_windows.h @@ -108,8 +108,8 @@ #include #endif +typedef double DOUBLE; typedef DOUBLE *PDOUBLE; -typedef GUID *PGUID; // Desktop access rights #define DESKTOP_ALL_ACCESS \ @@ -159,6 +159,12 @@ typedef GUID *PGUID; #define CONTAINING_RECORD(address, type, field) \ ((type *)((ULONG_PTR)(address) - UFIELD_OFFSET(type, field))) + +#ifndef __PGUID_DEFINED__ +#define __PGUID_DEFINED__ +typedef GUID* PGUID; +#endif + #ifndef __PCGUID_DEFINED__ #define __PCGUID_DEFINED__ typedef const GUID* PCGUID; @@ -168,4 +174,9 @@ typedef const GUID* PCGUID; DEFINE_GUID(GUID_NULL, 0x00000000L, 0x0000, 0x0000, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00); #endif +#ifndef __PCSID_DEFINED__ +#define __PCSID_DEFINED__ +typedef const SID* PCSID; +#endif + #endif diff --git a/smbios.h b/smbios.h index 1518d25..3b83e7d 100644 --- a/smbios.h +++ b/smbios.h @@ -744,7 +744,7 @@ C_ASSERT(sizeof(SMBIOS_PROCESSOR_INFORMATION) == 0x33); #define SMBIOS_PROCESSOR_FAMILY_INTEL_CORE_ULTRA_7 774 #define SMBIOS_PROCESSOR_FAMILY_INTEL_CORE_ULTRA_9 775 // 1024-65533 - Available for assignment -// 65534–65535 - RESERVED +// 65534-65535 - RESERVED #define SMBIOS_PROCESSOR_STATUS_UNKNOWN 0 #define SMBIOS_PROCESSOR_STATUS_ENABLED 1 diff --git a/usermgr.h b/usermgr.h index e69fcdf..fd70be7 100644 --- a/usermgr.h +++ b/usermgr.h @@ -26,14 +26,16 @@ typedef struct _CRED_PROV_CREDENTIAL #define USERMGRAPI DECLSPEC_IMPORT +// // Contexts +// #if (PHNT_VERSION >= PHNT_WINDOWS_10) // rev USERMGRAPI VOID -WINAPI +NTAPI UMgrFreeSessionUsers( _In_ _Post_invalid_ PSESSION_USER_CONTEXT SessionUsers ); @@ -41,7 +43,7 @@ UMgrFreeSessionUsers( // rev USERMGRAPI HRESULT -WINAPI +NTAPI UMgrEnumerateSessionUsers( _Out_ PULONG Count, _Outptr_ PSESSION_USER_CONTEXT *SessionUsers @@ -50,7 +52,7 @@ UMgrEnumerateSessionUsers( // rev USERMGRAPI HRESULT -WINAPI +NTAPI UMgrQueryUserContext( _In_ HANDLE TokenHandle, _Out_ PULONGLONG ContextToken @@ -59,7 +61,7 @@ UMgrQueryUserContext( // rev USERMGRAPI HRESULT -WINAPI +NTAPI UMgrQueryUserContextFromSid( _In_ PCWSTR SidString, _Out_ PULONGLONG ContextToken @@ -68,7 +70,7 @@ UMgrQueryUserContextFromSid( // rev USERMGRAPI HRESULT -WINAPI +NTAPI UMgrQueryUserContextFromName( _In_ PCWSTR UserName, _Out_ PULONGLONG ContextToken @@ -76,14 +78,16 @@ UMgrQueryUserContextFromName( #endif +// // Tokens +// #if (PHNT_VERSION >= PHNT_WINDOWS_10) // rev USERMGRAPI HRESULT -WINAPI +NTAPI UMgrQueryDefaultAccountToken( _Out_ PHANDLE TokenHandle ); @@ -91,7 +95,7 @@ UMgrQueryDefaultAccountToken( // rev USERMGRAPI HRESULT -WINAPI +NTAPI UMgrQuerySessionUserToken( _In_ ULONG SessionId, _Out_ PHANDLE TokenHandle @@ -100,7 +104,7 @@ UMgrQuerySessionUserToken( // rev USERMGRAPI HRESULT -WINAPI +NTAPI UMgrQueryUserToken( _In_ ULONGLONG Context, _Out_ PHANDLE TokenHandle @@ -109,7 +113,7 @@ UMgrQueryUserToken( // rev USERMGRAPI HRESULT -WINAPI +NTAPI UMgrQueryUserTokenFromSid( _In_ PCWSTR SidString, _Out_ PHANDLE TokenHandle @@ -118,7 +122,7 @@ UMgrQueryUserTokenFromSid( // rev USERMGRAPI HRESULT -WINAPI +NTAPI UMgrQueryUserTokenFromName( _In_ PCWSTR UserName, _Out_ PHANDLE TokenHandle @@ -127,7 +131,7 @@ UMgrQueryUserTokenFromName( // rev USERMGRAPI HRESULT -WINAPI +NTAPI UMgrGetConstrainedUserToken( _In_opt_ HANDLE InputTokenHandle, _In_ ULONGLONG Context, @@ -142,7 +146,7 @@ UMgrGetConstrainedUserToken( // rev USERMGRAPI HRESULT -WINAPI +NTAPI UMgrChangeSessionUserToken( _In_ HANDLE TokenHandle ); @@ -150,7 +154,7 @@ UMgrChangeSessionUserToken( // rev USERMGRAPI HRESULT -WINAPI +NTAPI UMgrGetImpersonationTokenForContext( _In_ HANDLE InputTokenHandle, _In_ ULONGLONG Context, @@ -164,7 +168,7 @@ UMgrGetImpersonationTokenForContext( // rev USERMGRAPI HRESULT -WINAPI +NTAPI UMgrGetSessionActiveShellUserToken( _In_ ULONG SessionId, _Out_ PHANDLE TokenHandle @@ -172,14 +176,16 @@ UMgrGetSessionActiveShellUserToken( #endif +// // Single-session SKU +// #if (PHNT_VERSION >= PHNT_WINDOWS_10) // rev USERMGRAPI HRESULT -WINAPI +NTAPI UMgrOpenProcessTokenForQuery( _In_ ULONG ProcessId, _Out_ PHANDLE TokenHandle @@ -188,7 +194,7 @@ UMgrOpenProcessTokenForQuery( // rev USERMGRAPI HRESULT -WINAPI +NTAPI UMgrOpenProcessHandleForAccess( _In_ ACCESS_MASK DesiredAccess, _In_ ULONG ProcessId, @@ -197,14 +203,16 @@ UMgrOpenProcessHandleForAccess( #endif +// // Credentials +// #if (PHNT_VERSION >= PHNT_WINDOWS_10) // rev USERMGRAPI HRESULT -WINAPI +NTAPI UMgrFreeUserCredentials( _In_ PCRED_PROV_CREDENTIAL Credentials ); @@ -212,7 +220,7 @@ UMgrFreeUserCredentials( // rev USERMGRAPI HRESULT -WINAPI +NTAPI UMgrGetCachedCredentials( _In_ PSID Sid, _Outptr_ PCRED_PROV_CREDENTIAL *Credentials diff --git a/winsta.h b/winsta.h index e7361ff..f071ff7 100644 --- a/winsta.h +++ b/winsta.h @@ -7,18 +7,26 @@ #ifndef _WINSTA_H #define _WINSTA_H +// +// Sessions +// + // Specifies the current server. #define WINSTATION_CURRENT_SERVER ((HANDLE)NULL) #define WINSTATION_CURRENT_SERVER_HANDLE ((HANDLE)NULL) #define WINSTATION_CURRENT_SERVER_NAME (NULL) +#define SERVERNAME_CURRENT ((PWSTR)NULL) // Specifies the current session (SessionId) #define WINSTATION_CURRENT_SESSION ((ULONG)-1) +#define LOGONID_CURRENT (-1) // Specifies any-session (SessionId) #define WINSTATION_ANY_SESSION ((ULONG)-2) +// // Access rights +// #define WINSTATION_QUERY 0x00000001 // WinStationQueryInformation #define WINSTATION_SET 0x00000002 // WinStationSetInformation @@ -122,51 +130,59 @@ typedef struct _SESSIONIDW WINSTATIONSTATECLASS State; } SESSIONIDW, *PSESSIONIDW; -// private +/** + * The WINSTATIONINFOCLASS enumeration indicates the class of data for which to either query or set on the server. + * + * \sa https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-tsts/f333c223-de8a-46e1-a83e-79cbdab92371 + * \sa https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-tsts/1bba9ff2-71d3-49a3-bb26-2e5f6fcab3ee + * \sa https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-tsts/2a5ee131-a1dd-44c7-9880-98df708061ea + */ typedef enum _WINSTATIONINFOCLASS { - WinStationCreateData, // q: WINSTATIONCREATE - WinStationConfiguration, // qs: WINSTACONFIGWIRE + USERCONFIG - WinStationPdParams, // qs: PDPARAMS - WinStationWd, // q: WDCONFIG - WinStationPd, // q: PDCONFIG2 + PDPARAMS - WinStationPrinter, // qs: Not supported. - WinStationClient, // q: WINSTATIONCLIENT - WinStationModules, // q: - WinStationInformation, // q: WINSTATIONINFORMATION - WinStationTrace, // qs: - WinStationBeep, // s: // 10 - WinStationEncryptionOff, // s: - WinStationEncryptionPerm, - WinStationNtSecurity, // s: (open secure desktop ctrl+alt+del) - WinStationUserToken, // q: WINSTATIONUSERTOKEN - WinStationUnused1, - WinStationVideoData, // q: WINSTATIONVIDEODATA - WinStationInitialProgram, // s: (set current process as initial program) - WinStationCd, // q: CDCONFIG - WinStationSystemTrace, // qs: - WinStationVirtualData, // q: // 20 - WinStationClientData, // WINSTATIONCLIENTDATA - WinStationSecureDesktopEnter, // qs: - WinStationSecureDesktopExit, // qs: - WinStationLoadBalanceSessionTarget, // q: ULONG - WinStationLoadIndicator, // q: WINSTATIONLOADINDICATORDATA - WinStationShadowInfo, // qs: WINSTATIONSHADOW - WinStationDigProductId, // WINSTATIONPRODID - WinStationLockedState, // BOOL - WinStationRemoteAddress, // WINSTATIONREMOTEADDRESS - WinStationIdleTime, // ULONG // 30 - WinStationLastReconnectType, // ULONG - WinStationDisallowAutoReconnect, // qs: BOOLEAN - WinStationMprNotifyInfo, - WinStationExecSrvSystemPipe, // WCHAR[48] - WinStationSmartCardAutoLogon, // BOOLEAN - WinStationIsAdminLoggedOn, // BOOLEAN - WinStationReconnectedFromId, // ULONG - WinStationEffectsPolicy, // ULONG - WinStationType, // ULONG - WinStationInformationEx, // WINSTATIONINFORMATIONEX // 40 - WinStationValidationInfo + WinStationCreateData, // q: WINSTATIONCREATE + WinStationConfiguration, // qs: WINSTACONFIGWIRE + USERCONFIG + WinStationPdParams, // qs: PDPARAMSWIRE + PDPARAMS + WinStationWd, // q: WDCONFIG + WinStationPd, // q: PDCONFIG2 + PDPARAMS + WinStationPrinter, // qs: Not supported. + WinStationClient, // q: VARDATA_WIRE + WINSTATIONCLIENT + WinStationModules, // q: + WinStationInformation, // q: WINSTATIONINFORMATION + WinStationTrace, // s: TS_TRACE + WinStationBeep, // s: BEEPINPUT // 10 + WinStationEncryptionOff, // s: + WinStationEncryptionPerm, // s: + WinStationNtSecurity, // s: (open secure desktop ctrl+alt+del) + WinStationUserToken, // q: WINSTATIONUSERTOKEN + WinStationUnused1, // qs: Not supported. + WinStationVideoData, // q: WINSTATIONVIDEODATA + WinStationInitialProgram, // s: (set current process as initial program) + WinStationCd, // q: CDCONFIG + WinStationSystemTrace, // s: TS_TRACE + WinStationVirtualData, // q: PVOID // 20 + WinStationClientData, // s: VARDATA_WIRE + WINSTATIONCLIENTDATA + WinStationSecureDesktopEnter, // qs: + WinStationSecureDesktopExit, // qs: + WinStationLoadBalanceSessionTarget, // q: ULONG + WinStationLoadIndicator, // q: WINSTATIONLOADINDICATORDATA + WinStationShadowInfo, // qs: WINSTATIONSHADOW + WinStationDigProductId, // q: WINSTATIONPRODID + WinStationLockedState, // qs: BOOL + WinStationRemoteAddress, // q: WINSTATIONREMOTEADDRESS + WinStationIdleTime, // q: ULONG // 30 + WinStationLastReconnectType, // q: ULONG + WinStationDisallowAutoReconnect, // qs: BOOLEAN + WinStationMprNotifyInfo, // q: + WinStationExecSrvSystemPipe, // q: WCHAR[48] + WinStationSmartCardAutoLogon, // q: BOOLEAN + WinStationIsAdminLoggedOn, // q: BOOLEAN + WinStationReconnectedFromId, // q: ULONG + WinStationEffectsPolicy, // q: ULONG + WinStationType, // q: ULONG + WinStationInformationEx, // q: VARDATA_WIRE + WINSTATIONINFORMATIONEX // 40 + WinStationValidationInfo, // q: + WinStationActivityId, // q: GUID + MaxWinStationInfoClass } WINSTATIONINFOCLASS; /** @@ -181,7 +197,7 @@ typedef struct _WINSTATIONCREATE typedef struct _WINSTACONFIGWIRE { WCHAR Comment[61]; // The WinStation descriptive comment. - CHAR OEMId[4]; // Value identifying the OEM implementor of the TermService Listener to which this session (WinStation) belongs. This can be any value defined by the implementer (OEM) of the listener. + CHAR OEMId[4]; // Value identifying the OEM implementer of the TermService Listener to which this session (WinStation) belongs. This can be any value defined by the implementer (OEM) of the listener. VARDATA_WIRE UserConfig; // VARDATA_WIRE structure defining the size and offset of the variable-length user configuration data succeeding it. VARDATA_WIRE NewFields; // VARDATA_WIRE structure defining the size and offset of the variable-length new data succeeding it. This field is not used and is a placeholder for any new data, if and when added. } WINSTACONFIGWIRE, *PWINSTACONFIGWIRE; @@ -193,7 +209,9 @@ typedef enum _CALLBACKCLASS Callback_Fixed } CALLBACKCLASS; -// The SHADOWCLASS enumeration is used to indicate the shadow-related settings for a session running on a terminal server. +/** + * The SHADOWCLASS enumeration is used to indicate the shadow-related settings for a session running on a terminal server. + */ typedef enum _SHADOWCLASS { Shadow_Disable, // Shadowing is disabled. @@ -203,8 +221,11 @@ typedef enum _SHADOWCLASS Shadow_EnableNoInputNoNotify // Permission is not asked first from the session being shadowed. The shadower is not permitted keyboard and mouse input and MUST observe the shadowed session. } SHADOWCLASS; -// For a specific terminal server session, the USERCONFIG structure indicates the user and session configuration. -// https://msdn.microsoft.com/en-us/library/cc248610.aspx +/** + * The USERCONFIG structure indicates the user and session configuration for a specific terminal server session. + * + * \sa https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-tsts/dba750b8-cb35-4e88-9811-e2a1f8a10701 + */ typedef struct _USERCONFIG { ULONG fInheritAutoLogon : 1; @@ -379,7 +400,11 @@ typedef struct _OEMTDCONFIG ULONG Flags; } OEMTDCONFIG, *POEMTDCONFIG; -// Retrieves transport protocol driver parameters. +/** + * The PDPARAMS structure represents the transport protocol driver parameters. + * + * \sa https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-tsts/ff0e2998-fb8b-4dff-ab64-8427fad556eb + */ typedef struct _PDPARAMS { SDCLASS SdClass; // Stack driver class. Indicates which one of the union's structures is valid. @@ -392,7 +417,11 @@ typedef struct _PDPARAMS }; } PDPARAMS, *PPDPARAMS; -// The WinStation (session) driver configuration. +/** + * The WDCONFIG structure represents the WinStation (session) driver configuration. + * + * \sa https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-tsts/d1bf099b-eb54-4ed9-a723-0b1062dbc128 + */ typedef struct _WDCONFIG { WDNAME WdName; // The descriptive name of the WinStation driver. @@ -404,7 +433,11 @@ typedef struct _WDCONFIG WDPREFIX WdPrefix; // Used as the prefix of the WinStation name generated for the connected sessions with this WinStation driver. } WDCONFIG, *PWDCONFIG; -// The protocol driver's software configuration. +/** + * The PDCONFIG2 structure represents the protocol driver's software configuration. + * + * \sa https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-tsts/74204022-eb7c-4454-b3d0-24f642c892a4 + */ typedef struct _PDCONFIG2 { PDNAME PdName; @@ -419,7 +452,11 @@ typedef struct _PDCONFIG2 ULONG KeepAliveTimeout; } PDCONFIG2, *PPDCONFIG2; -// WinStationClient +/** + * The WINSTATIONCLIENT structure defines the client-requested configuration when connecting to a session. + * + * \sa https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-tsts/673d8ac0-f557-48cb-98a6-49925160d729 + */ typedef struct _WINSTATIONCLIENT { ULONG fTextOnly : 1; @@ -518,57 +555,109 @@ typedef struct _TSHARE_CACHE ULONG Reserved; } TSHARE_CACHE, *PTSHARE_CACHE; +/** + * The CACHE_STATISTICS structure represents the cache statistics on the protocol. + * + * \sa https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-tsts/81203ca2-e58b-4681-affa-924e59671b5c + */ typedef struct CACHE_STATISTICS { - USHORT ProtocolType; - USHORT Length; + USHORT ProtocolType; // Protocol type. + USHORT Length; // Length of data in the protocol-specific area. Can be up to 20 * sizeof(ULONG) in size. union { - RESERVED_CACHE ReservedCacheStats; - TSHARE_CACHE TShareCacheStats; - ULONG Reserved[20]; + RESERVED_CACHE ReservedCacheStats; // Not used. + TSHARE_CACHE TShareCacheStats; // Protocol cache statistics. + ULONG Reserved[20]; // Reserved for future use. } Specific; } CACHE_STATISTICS, *PCACHE_STATISTICS; +/** + * The PROTOCOLSTATUS structure represents the status of the protocol used by the session. + * + * \sa https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-tsts/c9066753-acbd-4678-9a72-8fb1b080bd09 + */ typedef struct _PROTOCOLSTATUS { - PROTOCOLCOUNTERS Output; - PROTOCOLCOUNTERS Input; - CACHE_STATISTICS Cache; - ULONG AsyncSignal; - ULONG AsyncSignalMask; + PROTOCOLCOUNTERS Output; // A PROTOCOLCOUNTERS structure containing the output protocol counters. + PROTOCOLCOUNTERS Input; // A PROTOCOLCOUNTERS structure containing the input protocol counters. + CACHE_STATISTICS Cache; // A CACHE_STATISTICS structure containing statistics for the cache. + ULONG AsyncSignal; // Indicator of async signal, such as MS_CTS_ON, for async protocols. + ULONG AsyncSignalMask; // Mask of async signal events, such as EV_CTS, for async protocols. } PROTOCOLSTATUS, *PPROTOCOLSTATUS; -// Retrieves information on the session. +/** + * The WINSTATIONINFORMATION structure retrieves the state, connect time, last input time, and so on, for a session. + * + * \sa https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-tsts/c2566d8b-7016-440b-b7e0-0d07c3b2418f + */ typedef struct _WINSTATIONINFORMATION { - WINSTATIONSTATECLASS ConnectState; - WINSTATIONNAME WinStationName; - ULONG LogonId; - LARGE_INTEGER ConnectTime; - LARGE_INTEGER DisconnectTime; - LARGE_INTEGER LastInputTime; - LARGE_INTEGER LogonTime; - PROTOCOLSTATUS Status; - WCHAR Domain[DOMAIN_LENGTH + 1]; - WCHAR UserName[USERNAME_LENGTH + 1]; - LARGE_INTEGER CurrentTime; + WINSTATIONSTATECLASS ConnectState; // The current connect state of the session. + WINSTATIONNAME WinStationName; // The name of the session. + ULONG LogonId; // The session identifier of the session. + LARGE_INTEGER ConnectTime; // The time of the most recent connection to the session. + LARGE_INTEGER DisconnectTime; // The time of the most recent disconnection from the session. + LARGE_INTEGER LastInputTime; // The time the session last received input. + LARGE_INTEGER LogonTime; // The time of the logon to the session. + PROTOCOLSTATUS Status; // The status of the protocol. + WCHAR Domain[DOMAIN_LENGTH + 1]; // The user's domain name. + WCHAR UserName[USERNAME_LENGTH + 1]; // The user's user name. + LARGE_INTEGER CurrentTime; // The current time in the session. } WINSTATIONINFORMATION, *PWINSTATIONINFORMATION; -// Retrieves the user's token in the session. Caller requires WINSTATION_ALL_ACCESS permission. +/** + * The TS_TRACE structure specifies fields used for configuring tracing operations in TS binaries if they are checked. + * + * \sa https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-tsts/ad349575-5369-4830-a174-1920a7af8d5f + */ +typedef struct _TS_TRACE +{ + WCHAR TraceFile[256]; // Specifies the file name, if any, to which to write debug information. + BOOLEAN Debugger; // Specifies whether debugger is attached. + BOOLEAN Timestamp; // Specifies whether to append time stamp to the traces logged. + ULONG TraceClass; // Classes of tracing to log. They enable tracing for the various terminal server binaries/functionalities. + ULONG TraceEnable; // Type of tracing calls log. + WCHAR TraceOption[64]; // Trace option string. This can be an empty string meaning collect trace for all files and lines in those files. +} TS_TRACE, *PTS_TRACE; + +/** + * The BEEPINPUT structure performs a beep in the session. + * + * \sa https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-tsts/2faf4c5b-3a79-491a-9d1a-145f46a797d1 + */ +typedef struct _BEEPINPUT +{ + /** + * If the session ID is 0, this can be any of the values that can be passed to the standard MessageBeep function. + * If the session ID is not 0, a frequency and duration is chosen by the server to send as a beep to the session. + */ + ULONG Type; +} BEEPINPUT, *PBEEPINPUT; + +/** + * The WINSTATIONUSERTOKEN structure retrieves the user's token for the session. + * + * \remarks Caller requires WINSTATION_ALL_ACCESS permission. + * \sa https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-tsts/07f9831c-6331-43e5-ba27-d3d58772eb4c + */ typedef struct _WINSTATIONUSERTOKEN { - HANDLE ProcessId; - HANDLE ThreadId; - HANDLE UserToken; + HANDLE ProcessId; // Specifies the Process ID. + HANDLE ThreadId; // Specifies the calling thread. + HANDLE UserToken; // Returns the user token that is currently logged on to the session. } WINSTATIONUSERTOKEN, *PWINSTATIONUSERTOKEN; -// Retrieves resolution and color depth of the session. +/** + * The WINSTATIONVIDEODATA structure defines the resolution and color depth of a session. + * + * \sa https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-tsts/5f95f657-89d2-472d-b4ab-b0595618dbd1 + */ typedef struct _WINSTATIONVIDEODATA { - USHORT HResolution; - USHORT VResolution; - USHORT fColorDepth; + USHORT HResolution; // Specifies the horizontal resolution, in pixels. + USHORT VResolution; // Specifies the vertical resolution, in pixels. + USHORT ColorDepth; // Specifies the color depth. } WINSTATIONVIDEODATA, *PWINSTATIONVIDEODATA; typedef enum _CDCLASS @@ -578,7 +667,11 @@ typedef enum _CDCLASS CdClass_Maximum, } CDCLASS; -// Connection driver configuration. It is used for connecting via modem to a server. +/** + * The CDCONFIG structure defines the configuration used for connecting via modem to a server. + * + * \sa https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-tsts/f88900e1-c159-4f02-b3ae-84f05eec212f + */ typedef struct _CDCONFIG { CDCLASS CdClass; // Connection driver type. @@ -594,7 +687,7 @@ typedef CHAR* PCLIENTDATANAME; typedef struct _WINSTATIONCLIENTDATA { - CLIENTDATANAME DataName; // Identifies the type of data sent in this WINSTATIONCLIENTDATA structure. The definition is dependent on the caller and on the client receiving it. This MUST be a data name following a format similar to that of the CLIENTDATANAME data type. + CLIENTDATANAME DataName; // Identifies the type of data sent in this WINSTATIONCLIENTDATA structure. BOOLEAN fUnicodeData; // TRUE indicates data is in Unicode format; FALSE otherwise. } WINSTATIONCLIENTDATA, *PWINSTATIONCLIENTDATA; @@ -608,19 +701,28 @@ typedef enum _LOADFACTORTYPE CPUConstraint // CPU usage is the constraint. } LOADFACTORTYPE; -// The WINSTATIONLOADINDICATORDATA structure defines data used for the load balancing of a server. +/** + * The WINSTATIONLOADINDICATORDATA structure defines data used for the load balancing of a server. + * + * \sa https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-tsts/91459fa1-77e8-4987-a6f0-fe7dd3e62bfc + */ typedef struct _WINSTATIONLOADINDICATORDATA { - ULONG RemainingSessionCapacity; // The estimated number of additional sessions that can be supported given the CPU constraint. - LOADFACTORTYPE LoadFactor; // Indicates the most constrained current resource. - ULONG TotalSessions; // The total number of sessions. - ULONG DisconnectedSessions; // The number of disconnected sessions. - LARGE_INTEGER IdleCPU; // This is always set to 0. - LARGE_INTEGER TotalCPU; // This is always set to 0. - ULONG RawSessionCapacity; // The raw number of sessions capacity. - ULONG reserved[9]; // Reserved. + ULONG RemainingSessionCapacity; // The estimated number of additional sessions that can be supported given the CPU constraint. + LOADFACTORTYPE LoadFactor; // Indicates the most constrained current resource. + ULONG TotalSessions; // The total number of sessions. + ULONG DisconnectedSessions; // The number of disconnected sessions. + LARGE_INTEGER IdleCPU; // This is always set to 0. + LARGE_INTEGER TotalCPU; // This is always set to 0. + ULONG RawSessionCapacity; // The raw number of sessions capacity. + ULONG reserved[9]; // Reserved. } WINSTATIONLOADINDICATORDATA, *PWINSTATIONLOADINDICATORDATA; +/** + * The SHADOWSTATECLASS enumeration specifies WinStation shadow states. + * + * \sa https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-tsts/c55fbd8f-d7e3-4efe-9ca6-d0985dab9602 + */ typedef enum _SHADOWSTATECLASS { State_NoShadow, // No shadow operations are currently being performed on this session. @@ -674,7 +776,9 @@ typedef struct _WINSTATIONREMOTEADDRESS }; } WINSTATIONREMOTEADDRESS, *PWINSTATIONREMOTEADDRESS; +// // WinStationInformationEx +// // private typedef struct _WINSTATIONINFORMATIONEX_LEVEL1 @@ -739,6 +843,7 @@ typedef struct _TS_PROCESS_INFORMATION_NT4 #define SIZEOF_TS4_SYSTEM_THREAD_INFORMATION 64 #define SIZEOF_TS4_SYSTEM_PROCESS_INFORMATION 136 +_Struct_size_bytes_(NextEntryOffset) typedef struct _TS_SYS_PROCESS_INFORMATION { ULONG NextEntryOffset; @@ -772,21 +877,21 @@ typedef struct _TS_SYS_PROCESS_INFORMATION typedef struct _TS_ALL_PROCESSES_INFO { - PTS_SYS_PROCESS_INFORMATION pTsProcessInfo; + PTS_SYS_PROCESS_INFORMATION TsProcessInfo; ULONG SizeOfSid; - PSID pSid; + PSID Sid; } TS_ALL_PROCESSES_INFO, *PTS_ALL_PROCESSES_INFO; typedef struct _TS_COUNTER_HEADER { - DWORD dwCounterID; - BOOLEAN bResult; + ULONG CounterID; + BOOLEAN Result; } TS_COUNTER_HEADER, *PTS_COUNTER_HEADER; typedef struct _TS_COUNTER { TS_COUNTER_HEADER CounterHead; - DWORD dwValue; + ULONG Value; LARGE_INTEGER StartTime; } TS_COUNTER, *PTS_COUNTER; @@ -817,6 +922,18 @@ typedef struct _TS_COUNTER // begin_rev // Flags for WinStationRegisterConsoleNotification +/** + * WNOTIFY_THIS_SESSION + * + * Specifies that only session notifications involving the session attached + * to by the window identified by the WindowHandle are to be received. + */ +#define WNOTIFY_THIS_SESSION 0x0 +/** + * WNOTIFY_ALL_SESSIONS + * + * Specifies that all session notifications are to be received. + */ #define WNOTIFY_ALL_SESSIONS 0x1 // end_rev @@ -824,10 +941,13 @@ typedef struct _TS_COUNTER // server handles to indicate the local server. -1 can be specified for session IDs to indicate the // current session ID. -#define LOGONID_CURRENT (-1) -#define SERVERNAME_CURRENT ((PWSTR)NULL) - // rev +/** + * The WinStationFreeMemory routine frees memory allocated by a Remote Desktop Services function. + * + * \param Buffer Pointer to the memory to free. + * \sa https://learn.microsoft.com/en-us/windows/win32/api/wtsapi32/nf-wtsapi32-wtsfreememory + */ NTSYSAPI BOOLEAN NTAPI @@ -836,6 +956,13 @@ WinStationFreeMemory( ); // rev +/** + * The WinStationOpenServerW routine opens a handle to the specified Remote Desktop Session Host (RD Session Host) server. + * + * \param ServerName Pointer to a null-terminated string specifying the NetBIOS name of the RD Session Host server. + * \return HANDLE If the function succeeds, the return value is a handle to the specified server. + * \sa https://learn.microsoft.com/en-us/windows/win32/api/wtsapi32/nf-wtsapi32-wtsopenserverw + */ NTSYSAPI HANDLE NTAPI @@ -844,6 +971,29 @@ WinStationOpenServerW( ); // rev +/** + * The WinStationOpenServerExW routine opens a handle to the specified Remote Desktop Session Host (RD Session Host) server + * or Remote Desktop Virtualization Host (RD Virtualization Host) server. + * + * \param ServerName Pointer to a null-terminated string specifying the NetBIOS name of the RD Session Host server. + * \return HANDLE If the function succeeds, the return value is a handle to the specified server. + * \sa https://learn.microsoft.com/en-us/windows/win32/api/wtsapi32/nf-wtsapi32-wtsopenserverexw + */ +NTSYSAPI +HANDLE +NTAPI +WinStationOpenServerExW( + _In_opt_ PCWSTR ServerName + ); + +// rev +/** + * The WinStationCloseServer routine closes an open handle to a Remote Desktop Session Host (RD Session Host) server. + * + * \param ServerHandle A handle to an RD Session Host server opened by a call to the WinStationOpenServerW function. + * \return BOOLEAN Nonzero if the function succeeds, or zero otherwise. To get extended error information, call GetLastError. + * \sa https://learn.microsoft.com/en-us/windows/win32/api/wtsapi32/nf-wtsapi32-wtscloseserver + */ NTSYSAPI BOOLEAN NTAPI @@ -869,6 +1019,16 @@ WinStationGetTermSrvCountersValue( _Inout_ PTS_COUNTER Counters // set counter IDs before calling ); +// rev +/** + * The WinStationShutdownSystem routine shuts down (and optionally restarts) the specified Remote Desktop Session Host (RD Session Host) server. + * + * \param ServerHandle Handle to an RD Session Host server, or specify WINSTATION_CURRENT_SERVER to indicate the server on which your application is running. + * \param ShutdownFlags Indicates the type of shutdown. This parameter can be one of the WSD_* values. + * \return BOOLEAN Nonzero if the function succeeds, or zero otherwise. To get extended error information, call GetLastError. + * \remarks To shut down or restart the system, the calling process must have the SE_SHUTDOWN_NAME privilege enabled. + * \sa https://learn.microsoft.com/en-us/windows/win32/api/wtsapi32/nf-wtsapi32-wtsshutdownsystem + */ NTSYSAPI BOOLEAN NTAPI @@ -888,6 +1048,16 @@ WinStationWaitSystemEvent( ); // rev +/** + * The WinStationRegisterConsoleNotification routine shuts down (and optionally restarts) the specified Remote Desktop Session Host (RD Session Host) server. + * + * \param ServerHandle Handle to an RD Session Host server, or WINSTATION_CURRENT_SERVER . + * \param WindowHandle Handle of the window to receive session change notifications. + * \param Flags Specifies whether to receive notifications for all sessions (WNOTIFY_ALL_SESSIONS) or only for the console session. + * \return BOOLEAN Nonzero if the function succeeds, or zero otherwise. To get extended error information, call GetLastError. + * \remarks To shut down or restart the system, the calling process must have the SE_SHUTDOWN_NAME privilege enabled. + * \sa https://learn.microsoft.com/en-us/windows/win32/api/wtsapi32/nf-wtsapi32-wtsregistersessionnotificationex + */ NTSYSAPI BOOLEAN NTAPI @@ -906,8 +1076,6 @@ WinStationUnRegisterConsoleNotification( _In_ HWND WindowHandle ); -// Sessions - // rev NTSYSAPI BOOLEAN @@ -918,6 +1086,21 @@ WinStationEnumerateW( _Out_ PULONG Count ); +/** + * The WinStationQueryInformationW routine retrieves information about a window station. + * + * \param ServerHandle A handle to an RD Session Host server. Specify a handle opened by the WinStationOpenServerW function, or specify WINSTATION_CURRENT_SERVER to indicate the server on which your application is running. + * \param SessionId A Remote Desktop Services session identifier. + * To indicate the session in which the calling application is running (or the current session) specify WINSTATION_CURRENT_SESSION. + * Only specify WINSTATION_CURRENT_SESSION when obtaining session information on the local server. + * If WINSTATION_CURRENT_SESSION is specified when querying session information on a remote server, the returned session information will be inconsistent. Do not use the returned data. + * \param WinStationInformationClass A value from the TOKEN_INFORMATION_CLASS enumerated type identifying the type of information to be retrieved. + * \param WinStationInformation Pointer to a caller-allocated buffer that receives the requested information about the token. + * \param WinStationInformationLength Length, in bytes, of the caller-allocated TokenInformation buffer. + * \param ReturnLength Pointer to a caller-allocated variable that receives the actual length, in bytes, of the information returned in the TokenInformation buffer. + * \return BOOLEAN Nonzero if the function succeeds, or zero otherwise. To get extended error information, call GetLastError. + * \sa https://learn.microsoft.com/en-us/previous-versions/aa383827(v=vs.85) + */ NTSYSAPI BOOLEAN NTAPI @@ -925,9 +1108,9 @@ WinStationQueryInformationW( _In_opt_ HANDLE ServerHandle, _In_ ULONG SessionId, _In_ WINSTATIONINFOCLASS WinStationInformationClass, - _Out_writes_bytes_(WinStationInformationLength) PVOID pWinStationInformation, + _Out_writes_bytes_(WinStationInformationLength) PVOID WinStationInformation, _In_ ULONG WinStationInformationLength, - _Out_ PULONG pReturnLength + _Out_ PULONG ReturnLength ); // rev @@ -938,7 +1121,7 @@ WinStationSetInformationW( _In_opt_ HANDLE ServerHandle, _In_ ULONG SessionId, _In_ WINSTATIONINFOCLASS WinStationInformationClass, - _In_reads_bytes_(WinStationInformationLength) PVOID pWinStationInformation, + _In_reads_bytes_(WinStationInformationLength) PVOID WinStationInformation, _In_ ULONG WinStationInformationLength ); @@ -948,7 +1131,7 @@ BOOLEAN NTAPI WinStationQueryCurrentSessionInformation( _In_ WINSTATIONINFOCLASS WinStationInformationClass, - _In_reads_bytes_(WinStationInformationLength) PVOID pWinStationInformation, + _In_reads_bytes_(WinStationInformationLength) PVOID WinStationInformation, _In_ ULONG WinStationInformationLength ); @@ -958,7 +1141,7 @@ NTAPI WinStationNameFromLogonIdW( _In_opt_ HANDLE ServerHandle, _In_ ULONG SessionId, - _Out_writes_(WINSTATIONNAME_LENGTH + 1) PWSTR pWinStationName + _Out_writes_(WINSTATIONNAME_LENGTH + 1) PWSTR WinStationName ); // rev @@ -967,7 +1150,7 @@ BOOLEAN NTAPI LogonIdFromWinStationNameW( _In_opt_ HANDLE ServerHandle, - _In_ PCWSTR pWinStationName, + _In_ PCWSTR WinStationName, _Out_ PULONG SessionId ); @@ -995,7 +1178,7 @@ WinStationConnectW( _In_opt_ HANDLE ServerHandle, _In_ ULONG SessionId, _In_ ULONG TargetSessionId, - _In_opt_ PCWSTR pPassword, + _In_opt_ PCWSTR Password, _In_ BOOLEAN bWait ); @@ -1091,13 +1274,13 @@ WinStationGetProcessSid( _In_opt_ HANDLE ServerHandle, _In_ ULONG ProcessId, _In_ FILETIME ProcessStartTime, - _Out_ PVOID pProcessUserSid, + _Out_ PVOID ProcessUserSid, _Inout_ PULONG dwSidSize ); +// // Services isolation - -#if (PHNT_VERSION >= PHNT_WINDOWS_VISTA) +// // rev NTSYSAPI @@ -1115,8 +1298,6 @@ WinStationRevertFromServicesSession( VOID ); -#endif - // Misc. NTSYSAPI BOOLEAN @@ -1200,6 +1381,61 @@ WinStationSetAutologonPassword( _In_ PCSTR Password ); +// private +typedef struct _EXECENVDATAEX_LEVEL1 +{ + LONG ExecEnvId; + LONG State; + LONG AbsSessionId; + PWSTR SessionName; + PWSTR HostName; + PWSTR UserName; + PWSTR DomainName; + PWSTR FarmName; +} EXECENVDATAEX_LEVEL1, *PEXECENVDATAEX_LEVEL1; + +typedef union _EXECENVDATAEX_PAYLOAD +{ + UCHAR Data[1]; + EXECENVDATAEX_LEVEL1 Level1; + // define level 2/3/4 here +} EXECENVDATAEX_PAYLOAD; + +typedef struct _EXECENVDATAEX +{ + ULONG Level; + EXECENVDATAEX_PAYLOAD Payload; +} EXECENVDATAEX, *PEXECENVDATAEX; + +// typedef struct _EXECENVDATAEX +// { +// ULONG Level; +// union +// { +// EXECENVDATAEX_LEVEL1 ExecEnvEnum_Level1; +// }; +// } EXECENVDATAEX, *PEXECENVDATAEX; + +// rev +NTSYSAPI +BOOLEAN +NTAPI +WinStationGetAllSessionsEx( + _In_opt_ HANDLE ServerHandle, + _In_ ULONG Level, // Must be 1 + _Out_ PEXECENVDATAEX *SessionData, + _Out_ PULONG Count + ); + +// rev +NTSYSAPI +VOID +WINAPI +WinStationFreeEXECENVDATAEX( + _In_opt_ PEXECENVDATAEX SessionData, + _In_ ULONG Count + ); + typedef enum _SessionType { SESSIONTYPE_UNKNOWN = 0, @@ -1272,4 +1508,46 @@ WinStationGetLoggedOnCount( _Out_ PULONG LoggedOnDeviceCount ); +// rev +/** + * The WinStationSetRenderHint routine is used by an application that is displaying content that + * can be optimized for displaying in a remote session to identify the region of a window that is the actual content. + * In the remote session, this content will be encoded, sent to the client, then decoded and displayed. + * + * \param[out] RenderHintID The address of a value that identifies the rendering hint affected by this call. + * If a new hint is being created, this value must contain zero. + * This function will return a unique rendering hint identifier which is used for subsequent calls, such as clearing the hint. + * \param[in] WindowHandle The handle of window linked to lifetime of the rendering hint. This window is used in situations where a hint target is removed without the hint being explicitly cleared. + * \param[in] RenderHintType Specifies the type of hint represented by this call. + * \param[in] HintDataLength The size in bytes, of the HintData buffer. + * \param[in] HintData Additional data for the hint. The format of this data is dependent upon the value passed in the renderHintType parameter. + * \return BOOLEAN Nonzero if the function succeeds, or zero otherwise. + * \sa https://learn.microsoft.com/en-us/windows/win32/api/wtshintapi/nf-wtshintapi-wtssetrenderhint + */ +NTSYSAPI +BOOLEAN +NTAPI +WinStationSetRenderHint( + _In_opt_ PULONG64 RenderHintID, + _In_ HWND WindowHandle, + _In_ ULONG RenderHintType, + _In_ ULONG HintDataLength, + _In_ PBYTE HintData + ); + +// rev +/** + * The WinStationActiveSessionExists routine returns active sessions on the system without enumerating through the list of sessions. + * It also does not obtain any extra information from Local Session Manager. + * + * \return BOOLEAN Nonzero if an active session exists. + * \sa https://learn.microsoft.com/en-us/windows/win32/api/wtsapi32/nf-wtsapi32-wtsactivesessionexists + */ +NTSYSAPI +BOOLEAN +NTAPI +WinStationActiveSessionExists( + VOID + ); + #endif