master ohmu/fastfetch-openbsd / src / common / windows / nt.h
ohmu  ·  2026-10-15
   1#pragma once
   2
   3#include <ntdef.h>
   4#include <winternl.h>
   5#include <winnt.h>
   6#include <stdint.h>
   7#include <assert.h>
   8
   9enum {
  10    SystemModuleInformation = 11,
  11    SystemFirmwareTableInformation = 76,
  12    SystemBootEnvironmentInformation = 90,
  13    SystemLogicalProcessorAndGroupInformation = 107,
  14    SystemBasicPerformanceInformation = 123,
  15    SystemSecureBootInformation = 146,
  16    SystemBasicProcessInformation = 252,
  17    SystemHandleCountInformation = 253,
  18};
  19
  20typedef struct _PROCESSOR_POWER_INFORMATION {
  21    ULONG Number;
  22    ULONG MaxMhz;
  23    ULONG CurrentMhz;
  24    ULONG MhzLimit;
  25    ULONG MaxIdleState;
  26    ULONG CurrentIdleState;
  27} PROCESSOR_POWER_INFORMATION, *PPROCESSOR_POWER_INFORMATION;
  28
  29NTSYSAPI NTSTATUS NTAPI NtPowerInformation(
  30    IN POWER_INFORMATION_LEVEL InformationLevel,
  31    IN PVOID InputBuffer OPTIONAL,
  32    IN ULONG InputBufferLength,
  33    OUT PVOID OutputBuffer OPTIONAL,
  34    IN ULONG OutputBufferLength);
  35
  36NTSYSAPI NTSTATUS NTAPI RtlGetVersion(
  37    _Inout_ PRTL_OSVERSIONINFOW lpVersionInformation);
  38
  39NTSYSAPI NTSTATUS NTAPI NtQueryDirectoryFile(
  40    IN HANDLE FileHandle,
  41    IN HANDLE Event OPTIONAL,
  42    IN PIO_APC_ROUTINE ApcRoutine OPTIONAL,
  43    IN PVOID ApcContext OPTIONAL,
  44    OUT PIO_STATUS_BLOCK IoStatusBlock,
  45    OUT PVOID FileInformation,
  46    IN ULONG Length,
  47    IN FILE_INFORMATION_CLASS FileInformationClass,
  48    IN BOOLEAN ReturnSingleEntry,
  49    IN PUNICODE_STRING FileName OPTIONAL,
  50    IN BOOLEAN RestartScan);
  51
  52// https://ntdoc.m417z.com/process_devicemap_information_ex
  53typedef struct _PROCESS_DEVICEMAP_INFORMATION_EX {
  54    union {
  55        struct
  56        {
  57            HANDLE DirectoryHandle; // A handle to a directory object that can be set as the new device map for the process. This handle must have DIRECTORY_TRAVERSE access.
  58        } Set;
  59        struct
  60        {
  61            ULONG DriveMap;      // A bitmask that indicates which drive letters are currently in use in the process's device map.
  62            UCHAR DriveType[32]; // A value that indicates the type of each drive (e.g., local disk, network drive, etc.). // DRIVE_* WinBase.h
  63        } Query;
  64    };
  65    ULONG Flags; // PROCESS_LUID_DOSDEVICES_ONLY
  66} PROCESS_DEVICEMAP_INFORMATION_EX, *PPROCESS_DEVICEMAP_INFORMATION_EX;
  67
  68#ifndef NtCurrentProcess
  69    #define NtCurrentProcess() ((HANDLE) (LONG_PTR) - 1)
  70#endif
  71
  72typedef struct _CURDIR {
  73    UNICODE_STRING DosPath;
  74    HANDLE Handle;
  75} CURDIR, *PCURDIR;
  76
  77NTSYSAPI PIMAGE_NT_HEADERS NTAPI RtlImageNtHeader(IN PVOID BaseOfImage);
  78
  79/**
  80 * The SECTION_IMAGE_INFORMATION structure contains detailed information about an image section.
  81 */
  82typedef struct _SECTION_IMAGE_INFORMATION {
  83    PVOID TransferAddress;     // The address of the image entry point function.
  84    ULONG ZeroBits;            // The number of high-order address bits that must be zero in the image base address.
  85    SIZE_T MaximumStackSize;   // The maximum stack size of threads from the PE file header.
  86    SIZE_T CommittedStackSize; // The initial stack size of threads from the PE file header.
  87    ULONG SubSystemType;       // The image subsystem from the PE file header (e.g., Windows GUI, Windows CUI, POSIX).
  88    union {
  89        struct
  90        {
  91            USHORT SubSystemMinorVersion;
  92            USHORT SubSystemMajorVersion;
  93        };
  94        ULONG SubSystemVersion;
  95    };
  96    union {
  97        struct
  98        {
  99            USHORT MajorOperatingSystemVersion;
 100            USHORT MinorOperatingSystemVersion;
 101        };
 102        ULONG OperatingSystemVersion;
 103    };
 104    USHORT ImageCharacteristics; // The image characteristics from the PE file header.
 105    USHORT DllCharacteristics;   // The DLL characteristics flags (e.g., ASLR, NX compatibility).
 106    USHORT Machine;              // The image architecture (e.g., x86, x64, ARM).
 107    BOOLEAN ImageContainsCode;   // The image contains native executable code.
 108    union {
 109        UCHAR ImageFlags;
 110        struct
 111        {
 112            UCHAR ComPlusNativeReady : 1;        // The image contains precompiled .NET assembly generated by NGEN (Native Image Generator).
 113            UCHAR ComPlusILOnly : 1;             // the image contains only Microsoft Intermediate Language (IL) assembly.
 114            UCHAR ImageDynamicallyRelocated : 1; // The image was mapped using a random base address rather than the preferred base address.
 115            UCHAR ImageMappedFlat : 1;           // The image was mapped using a single contiguous region, rather than separate regions for each section.
 116            UCHAR BaseBelow4gb : 1;              // The image was mapped using a base address below the 4 GB boundary.
 117            UCHAR ComPlusPrefer32bit : 1;        // The image prefers to run as a 32-bit process, even on a 64-bit system.
 118            UCHAR Reserved : 2;
 119        };
 120    };
 121    ULONG LoaderFlags;   // Reserved by ntdll.dll for the Windows loader.
 122    ULONG ImageFileSize; // The size of the image, in bytes, including all headers.
 123    ULONG CheckSum;      // The image file checksum, from the PE optional header.
 124} SECTION_IMAGE_INFORMATION, *PSECTION_IMAGE_INFORMATION;
 125
 126typedef struct _SYSTEM_BOOT_ENVIRONMENT_INFORMATION {
 127    GUID BootIdentifier;
 128    FIRMWARE_TYPE FirmwareType;
 129    union {
 130        ULONGLONG BootFlags;
 131        struct
 132        {
 133            ULONGLONG DbgMenuOsSelection : 1; // REDSTONE4
 134            ULONGLONG DbgHiberBoot : 1;
 135            ULONGLONG DbgSoftBoot : 1;
 136            ULONGLONG DbgMeasuredLaunch : 1;
 137            ULONGLONG DbgMeasuredLaunchCapable : 1; // 19H1
 138            ULONGLONG DbgSystemHiveReplace : 1;
 139            ULONGLONG DbgMeasuredLaunchSmmProtections : 1;
 140            ULONGLONG DbgMeasuredLaunchSmmLevel : 7; // 20H1
 141            ULONGLONG DbgBugCheckRecovery : 1;       // 24H2
 142            ULONGLONG DbgFASR : 1;
 143            ULONGLONG DbgUseCachedBcd : 1;
 144        };
 145    };
 146} SYSTEM_BOOT_ENVIRONMENT_INFORMATION;
 147
 148typedef struct _RTL_PROCESS_MODULE_INFORMATION {
 149    PVOID Section;
 150    PVOID MappedBase;
 151    PVOID ImageBase;
 152    ULONG ImageSize;
 153    ULONG Flags;
 154    USHORT LoadOrderIndex;
 155    USHORT InitOrderIndex;
 156    USHORT LoadCount;
 157    USHORT OffsetToFileName;
 158    UCHAR FullPathName[256];
 159} RTL_PROCESS_MODULE_INFORMATION, *PRTL_PROCESS_MODULE_INFORMATION;
 160
 161typedef struct _RTL_PROCESS_MODULES {
 162    ULONG NumberOfModules;
 163    _Field_size_(NumberOfModules) RTL_PROCESS_MODULE_INFORMATION Modules[1];
 164} RTL_PROCESS_MODULES, *PRTL_PROCESS_MODULES;
 165
 166NTSTATUS NTAPI NtQuerySystemEnvironmentValueEx(
 167    _In_ PCUNICODE_STRING VariableName,
 168    _In_ const GUID* VendorGuid,
 169    _Out_writes_bytes_opt_(*BufferLength) PVOID Buffer,
 170    _Inout_ PULONG BufferLength,
 171    _Out_opt_ PULONG Attributes // EFI_VARIABLE_*
 172);
 173
 174typedef struct _SYSTEM_SECUREBOOT_INFORMATION {
 175    BOOLEAN SecureBootEnabled;
 176    BOOLEAN SecureBootCapable;
 177} SYSTEM_SECUREBOOT_INFORMATION, *PSYSTEM_SECUREBOOT_INFORMATION;
 178
 179NTSTATUS NTAPI NtQuerySystemInformationEx(
 180    _In_ SYSTEM_INFORMATION_CLASS SystemInformationClass,
 181    _In_reads_bytes_(InputBufferLength) PVOID InputBuffer,
 182    _In_ ULONG InputBufferLength,
 183    _Out_writes_bytes_opt_(SystemInformationLength) PVOID SystemInformation,
 184    _In_ ULONG SystemInformationLength,
 185    _Out_opt_ PULONG ReturnLength);
 186
 187typedef enum _SYSTEM_FIRMWARE_TABLE_ACTION {
 188    SystemFirmwareTableEnumerate,
 189    SystemFirmwareTableGet,
 190    SystemFirmwareTableMax
 191} SYSTEM_FIRMWARE_TABLE_ACTION;
 192
 193typedef struct _SYSTEM_FIRMWARE_TABLE_INFORMATION {
 194    ULONG ProviderSignature; // (same as the GetSystemFirmwareTable function)
 195    SYSTEM_FIRMWARE_TABLE_ACTION Action;
 196    ULONG TableID;
 197    ULONG TableBufferLength;
 198    _Field_size_bytes_(TableBufferLength) UCHAR TableBuffer[];
 199} SYSTEM_FIRMWARE_TABLE_INFORMATION, *PSYSTEM_FIRMWARE_TABLE_INFORMATION;
 200
 201typedef struct _SYSTEM_BASIC_PERFORMANCE_INFORMATION {
 202    SIZE_T AvailablePages;
 203    SIZE_T CommittedPages;
 204    SIZE_T CommitLimit;
 205    SIZE_T PeakCommitment;
 206} SYSTEM_BASIC_PERFORMANCE_INFORMATION, *PSYSTEM_BASIC_PERFORMANCE_INFORMATION;
 207
 208typedef struct _SYSTEM_BASICPROCESS_INFORMATION {
 209    ULONG NextEntryOffset;
 210    HANDLE UniqueProcessId;
 211    HANDLE InheritedFromUniqueProcessId;
 212    ULONG64 SequenceNumber;
 213    UNICODE_STRING ImageName;
 214} SYSTEM_BASICPROCESS_INFORMATION, *PSYSTEM_BASICPROCESS_INFORMATION;
 215
 216typedef struct _SYSTEM_HANDLECOUNT_INFORMATION {
 217    ULONG ProcessCount;
 218    ULONG ThreadCount;
 219    ULONG HandleCount;
 220} SYSTEM_HANDLECOUNT_INFORMATION, *PSYSTEM_HANDLECOUNT_INFORMATION;
 221
 222NTSYSAPI NTSTATUS NTAPI NtDelayExecution(_In_ BOOLEAN Alertable, _In_ PLARGE_INTEGER DelayInterval);
 223
 224/**
 225 * The KSYSTEM_TIME structure represents interrupt time, system time, and time zone bias.
 226 */
 227typedef struct _KSYSTEM_TIME {
 228    ULONG LowPart;
 229    LONG High1Time;
 230    LONG High2Time;
 231} KSYSTEM_TIME, *PKSYSTEM_TIME;
 232
 233/**
 234 * PROCESSOR_FEATURE_MAX defines the maximum number of processor feature flags
 235 * that may be reported by the system.
 236 */
 237#define PROCESSOR_FEATURE_MAX 64
 238
 239/**
 240 * The ALTERNATIVE_ARCHITECTURE_TYPE enumeration specifies the hardware
 241 * architecture variant used by the system.
 242 *
 243 * \remarks NEC98x86 represents the NEC PC-98 architecture,
 244 * supported only on very early Windows releases.
 245 */
 246typedef enum _ALTERNATIVE_ARCHITECTURE_TYPE {
 247    StandardDesign,
 248    NEC98x86,
 249    EndAlternatives
 250} ALTERNATIVE_ARCHITECTURE_TYPE;
 251
 252/**
 253 * The KUSER_SHARED_DATA structure contains information shared with user-mode.
 254 *
 255 * \sa https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/ntddk/ns-ntddk-kuser_shared_data
 256 */
 257typedef struct _KUSER_SHARED_DATA {
 258    //
 259    // Current low 32-bit of tick count and tick count multiplier.
 260    //
 261    // N.B. The tick count is updated each time the clock ticks.
 262    //
 263
 264    ULONG TickCountLowDeprecated;
 265    ULONG TickCountMultiplier;
 266
 267    //
 268    // Current 64-bit interrupt time in 100ns units.
 269    //
 270
 271    volatile KSYSTEM_TIME InterruptTime;
 272
 273    //
 274    // Current 64-bit system time in 100ns units.
 275    //
 276
 277    volatile KSYSTEM_TIME SystemTime;
 278
 279    //
 280    // Current 64-bit time zone bias.
 281    //
 282
 283    volatile KSYSTEM_TIME TimeZoneBias;
 284
 285    //
 286    // Support image magic number range for the host system.
 287    //
 288    // N.B. This is an inclusive range.
 289    //
 290
 291    USHORT ImageNumberLow;
 292    USHORT ImageNumberHigh;
 293
 294    //
 295    // Copy of system root in unicode.
 296    //
 297    // N.B. This field must be accessed via the RtlGetNtSystemRoot API for
 298    //      an accurate result.
 299    //
 300
 301    WCHAR NtSystemRoot[260];
 302
 303    //
 304    // Maximum stack trace depth if tracing enabled.
 305    //
 306
 307    ULONG MaxStackTraceDepth;
 308
 309    //
 310    // Crypto exponent value.
 311    //
 312
 313    ULONG CryptoExponent;
 314
 315    //
 316    // Time zone ID.
 317    //
 318
 319    ULONG TimeZoneId;
 320
 321    //
 322    // Minimum size of a large page on the system, in bytes.
 323    //
 324    // N.B. Returned by GetLargePageMinimum() function.
 325    //
 326
 327    ULONG LargePageMinimum;
 328
 329    //
 330    // This value controls the Application Impact Telemetry (AIT) Sampling rate.
 331    //
 332    // This value determines how frequently the system records AIT events,
 333    // which are used by the Application Experience and compatibility
 334    // subsystems to evaluate application behavior, performance, and
 335    // potential compatibility issues.
 336    //
 337    // Lower values increase sampling frequency, while higher values reduce it.
 338    // The kernel updates this field as part of its internal telemetry and
 339    // heuristics logic.
 340    //
 341
 342    ULONG AitSamplingValue;
 343
 344    //
 345    // This value controls Application Compatibility (AppCompat) switchback processing.
 346    //
 347
 348    union {
 349        ULONG AppCompatFlag;
 350        struct
 351        {
 352            ULONG SwitchbackEnabled : 1;  // Basic switchback processing
 353            ULONG ExtendedHeuristics : 1; // Extended switchback heuristics
 354            ULONG TelemetryFallback : 1;  // Telemetry-driven fallback
 355            ULONG Reserved : 29;
 356        } AppCompatFlags;
 357    };
 358
 359    //
 360    // Current Kernel Root RNG state seed version
 361    //
 362
 363    ULONGLONG RNGSeedVersion;
 364
 365    //
 366    // This value controls assertion failure handling.
 367    //
 368    // Historically (prior to Windows 10), this value was also used by
 369    // Code Integrity (CI), AppLocker, and related security components to
 370    // determine the minimum validation requirements for executable images,
 371    // drivers, and privileged operations.
 372    //
 373    // In modern Windows versions, this field is used primarily by the kernel's
 374    // diagnostic and validation infrastructure to decide how assertion failures
 375    // should be handled (e.g., logging, debugger break-in, or bugcheck).
 376
 377    ULONG GlobalValidationRunlevel;
 378
 379    //
 380    // Monotonic stamp incremented by the kernel whenever the system's
 381    // time zone bias value changes.
 382    //
 383    // N.B. This field must be accessed via the RtlGetSystemTimeAndBias API for
 384    //      an accurate result.
 385    // This value is read before and after accessing the bias fields to determine
 386    // whether the time zone data changed during the read. If the stamp differs,
 387    // the caller must re-read the bias values to ensure consistency.
 388    //
 389
 390    volatile LONG TimeZoneBiasStamp;
 391
 392    //
 393    // The shared collective build number undecorated with C or F.
 394    // GetVersionEx hides the real number
 395    //
 396
 397    ULONG NtBuildNumber;
 398
 399    //
 400    // Product type.
 401    //
 402    // N.B. This field must be accessed via the RtlGetNtProductType API for
 403    //      an accurate result.
 404    //
 405
 406    NT_PRODUCT_TYPE NtProductType;
 407    BOOLEAN ProductTypeIsValid;
 408    BOOLEAN Reserved0[1];
 409
 410    //
 411    // Native hardware processor architecture of the running system.
 412    //
 413    // N.B. User-mode components read this field to determine the true system
 414    // architecture, especially in WOW64 scenarios where the process architecture
 415    // differs from the native one.
 416    //
 417
 418    USHORT NativeProcessorArchitecture;
 419
 420    //
 421    // The NT Version.
 422    //
 423    // N. B. Note that each process sees a version from its PEB, but if the
 424    //       process is running with an altered view of the system version,
 425    //       the following two fields are used to correctly identify the
 426    //       version
 427    //
 428
 429    ULONG NtMajorVersion;
 430    ULONG NtMinorVersion;
 431
 432    //
 433    // Processor features.
 434    //
 435
 436    BOOLEAN ProcessorFeatures[PROCESSOR_FEATURE_MAX];
 437
 438    //
 439    // Reserved fields - do not use.
 440    //
 441
 442    ULONG MaximumUserModeAddressDeprecated; // Deprecated, use SystemBasicInformation instead.
 443    ULONG SystemRangeStartDeprecated;       // Deprecated, use SystemRangeStartInformation instead.
 444
 445    //
 446    // Time slippage while in debugger.
 447    //
 448
 449    volatile ULONG TimeSlip;
 450
 451    //
 452    // Alternative system architecture, e.g., NEC PC98xx on x86.
 453    //
 454
 455    ALTERNATIVE_ARCHITECTURE_TYPE AlternativeArchitecture;
 456
 457    //
 458    // Boot sequence, incremented for each boot attempt by the OS loader.
 459    //
 460
 461    ULONG BootId;
 462
 463    //
 464    // If the system is an evaluation unit, the following field contains the
 465    // date and time that the evaluation unit expires. A value of 0 indicates
 466    // that there is no expiration. A non-zero value is the UTC absolute time
 467    // that the system expires.
 468    //
 469
 470    LARGE_INTEGER SystemExpirationDate;
 471
 472    //
 473    // Suite support.
 474    //
 475    // N.B. This field must be accessed via the RtlGetSuiteMask API for
 476    //      an accurate result.
 477    //
 478
 479    ULONG SuiteMask;
 480
 481    //
 482    // TRUE if a kernel debugger is connected/enabled.
 483    //
 484
 485    BOOLEAN KdDebuggerEnabled;
 486
 487    //
 488    // Mitigation policies.
 489    //
 490
 491    union {
 492        UCHAR MitigationPolicies;
 493        struct
 494        {
 495            UCHAR NXSupportPolicy : 2;
 496            UCHAR SEHValidationPolicy : 2;
 497            UCHAR CurDirDevicesSkippedForDlls : 2;
 498            UCHAR Reserved : 2;
 499        };
 500    };
 501
 502    //
 503    // Measured duration of a single processor yield, in cycles. This is used by
 504    // lock packages to determine how many times to spin waiting for a state
 505    // change before blocking.
 506    //
 507
 508    USHORT CyclesPerYield;
 509
 510    //
 511    // Current console session Id. Always zero on non-TS systems.
 512    //
 513    // N.B. This field must be accessed via the RtlGetActiveConsoleId API for an
 514    //      accurate result.
 515    //
 516
 517    volatile ULONG ActiveConsoleId;
 518
 519    //
 520    // Force-dismounts cause handles to become invalid. Rather than always
 521    // probe handles, a serial number of dismounts is maintained that clients
 522    // can use to see if they need to probe handles.
 523    //
 524
 525    volatile ULONG DismountCount;
 526
 527    //
 528    // This field indicates the status of the 64-bit COM+ package on the
 529    // system. It indicates whether the Intermediate Language (IL) COM+
 530    // images need to use the 64-bit COM+ runtime or the 32-bit COM+ runtime.
 531    //
 532
 533    ULONG ComPlusPackage;
 534
 535    //
 536    // Time in tick count for system-wide last user input across all terminal
 537    // sessions. For MP performance, it is not updated all the time (e.g. once
 538    // a minute per session). It is used for idle detection.
 539    //
 540
 541    ULONG LastSystemRITEventTickCount;
 542
 543    //
 544    // Number of physical pages in the system. This can dynamically change as
 545    // physical memory can be added or removed from a running system.  This
 546    // cell is too small to hold the non-truncated value on very large memory
 547    // machines so code that needs the full value should access
 548    // FullNumberOfPhysicalPages instead.
 549    //
 550
 551    ULONG NumberOfPhysicalPages;
 552
 553    //
 554    // True if the system was booted in safe boot mode.
 555    //
 556
 557    BOOLEAN SafeBootMode;
 558
 559    //
 560    // Virtualization flags.
 561    //
 562
 563    union {
 564        UCHAR VirtualizationFlags;
 565
 566#if defined(_ARM64_)
 567
 568        //
 569        // N.B. Keep this bitfield in sync with the one in arc.w.
 570        //
 571
 572        struct
 573        {
 574            UCHAR ArchStartedInEl2 : 1;
 575            UCHAR QcSlIsSupported : 1;
 576            UCHAR : 6;
 577        };
 578
 579#endif
 580    };
 581
 582    //
 583    // Reserved (available for reuse).
 584    //
 585
 586    UCHAR Reserved12[2];
 587
 588    //
 589    // This is a packed bitfield that contains various flags concerning
 590    // the system state. They must be manipulated using interlocked
 591    // operations.
 592    //
 593    // N.B. DbgMultiSessionSku must be accessed via the RtlIsMultiSessionSku
 594    //      API for an accurate result
 595    //
 596
 597    union {
 598        ULONG SharedDataFlags;
 599        struct
 600        {
 601            //
 602            // The following bit fields are for the debugger only. Do not use.
 603            // Use the bit definitions instead.
 604            //
 605
 606            ULONG DbgErrorPortPresent : 1;
 607            ULONG DbgElevationEnabled : 1;
 608            ULONG DbgVirtEnabled : 1;
 609            ULONG DbgInstallerDetectEnabled : 1;
 610            ULONG DbgLkgEnabled : 1;
 611            ULONG DbgDynProcessorEnabled : 1;
 612            ULONG DbgConsoleBrokerEnabled : 1;
 613            ULONG DbgSecureBootEnabled : 1;
 614            ULONG DbgMultiSessionSku : 1;
 615            ULONG DbgMultiUsersInSessionSku : 1;
 616            ULONG DbgStateSeparationEnabled : 1;
 617            ULONG DbgSplitTokenEnabled : 1;
 618            ULONG DbgShadowAdminEnabled : 1;
 619            ULONG SpareBits : 19;
 620        };
 621    };
 622
 623    //
 624    // Reserved padding field to preserve structure alignment and compatibility.
 625    //
 626
 627    ULONG DataFlagsPad[1];
 628
 629    //
 630    // Depending on the processor, the code for fast system call will differ,
 631    // Stub code is provided pointers below to access the appropriate code.
 632    //
 633    // N.B. The following field is only used on 32-bit systems.
 634    //
 635
 636    ULONGLONG TestRetInstruction;
 637
 638    //
 639    // Query-performance counter (QPC) frequency, in counts per second.
 640    //
 641    // N.B. This value represents the fixed frequency of the system's high-resolution
 642    // performance counter. It is used by user-mode time routines to convert QPC
 643    // ticks into elapsed time without requiring a system call. The frequency is
 644    // constant for the lifetime of the system and reflects the hardware or
 645    // virtualized timer source selected by the kernel.
 646    //
 647
 648    LONGLONG QpcFrequency;
 649
 650    //
 651    // On AMD64, this value is initialized to a nonzero value if the system
 652    // operates with an altered view of the system service call mechanism.
 653    //
 654
 655    ULONG SystemCall;
 656
 657    //
 658    // Reserved field - do not use. Used to be UserCetAvailableEnvironments.
 659    //
 660
 661    ULONG Reserved2;
 662
 663    //
 664    // Full 64 bit version of the number of physical pages in the system.
 665    // This can dynamically change as physical memory can be added or removed
 666    // from a running system.
 667    //
 668
 669    ULONGLONG FullNumberOfPhysicalPages;
 670
 671    // ... more fields follow, but we don't need them
 672} KUSER_SHARED_DATA, *PKUSER_SHARED_DATA;
 673
 674#ifdef __aarch64__
 675    #define SharedUserData ({                                                                        \
 676        auto shared_user_data = (const volatile KUSER_SHARED_DATA*) (uintptr_t) 0x7FFE0000UL; \
 677        __asm__("" : "+r"(shared_user_data)); /* https://github.com/lhmouse/mcfgthread/issues/330 */ \
 678        shared_user_data;                                                                            \
 679    })
 680#else
 681    #define SharedUserData ((const volatile KUSER_SHARED_DATA*) (uintptr_t) 0x7FFE0000UL)
 682#endif
 683
 684static inline uint64_t ffKSystemTimeToUInt64(const volatile KSYSTEM_TIME* pTime) {
 685#if _WIN64
 686
 687    // This is safe even if pTime is not 8-byte aligned
 688    // See https://learn.microsoft.com/en-us/windows/win32/winprog64/fault-alignments
 689    return *(const volatile uint64_t*) pTime;
 690
 691#else
 692
 693    uint32_t low, high1, high2;
 694
 695    do {
 696        high1 = (uint32_t) pTime->High1Time;
 697        low = (uint32_t) pTime->LowPart;
 698        high2 = (uint32_t) pTime->High2Time;
 699    } while (high1 != high2);
 700
 701    return ((uint64_t) high1 << 32) | low;
 702#endif
 703}
 704
 705static inline bool ffIsWindows10OrGreater() {
 706#if FF_WIN81_COMPAT
 707    return SharedUserData->NtBuildNumber >= 10240;
 708#else
 709    return true;
 710#endif
 711}
 712
 713static inline bool ffIsWindows11OrGreater() {
 714    return SharedUserData->NtBuildNumber >= 22000;
 715}
 716
 717static inline bool ffIsSystemBasicProcessInfoAvailable() { // Includes HandleCountInformation, which was added together
 718    // https://learn.microsoft.com/en-us/windows/win32/api/winternl/nf-winternl-ntquerysysteminformation#systembasicprocessinformation
 719    return SharedUserData->NtBuildNumber >= 26200; // MSDN says it was added in 26100.4770; ntdoc says 25H2
 720}
 721
 722static inline bool ffIsFileFsFullSizeInformationExAvailable() {
 723    return SharedUserData->NtBuildNumber >= 17763; // Windows 10 October 2018 Update (1809, REDSTONE5)
 724}
 725
 726NTSYSAPI NTSTATUS NTAPI NtOpenProcessToken(
 727    _In_ HANDLE ProcessHandle,
 728    _In_ ACCESS_MASK DesiredAccess,
 729    _Out_ PHANDLE TokenHandle);
 730NTSYSAPI NTSTATUS NTAPI NtAdjustPrivilegesToken(
 731    _In_ HANDLE TokenHandle,
 732    _In_ BOOLEAN DisableAllPrivileges,
 733    _In_opt_ PTOKEN_PRIVILEGES NewState,
 734    _In_ ULONG BufferLength,
 735    _Out_writes_bytes_to_opt_(BufferLength, *ReturnLength) PTOKEN_PRIVILEGES PreviousState,
 736    _Out_opt_ PULONG ReturnLength);
 737NTSYSAPI NTSTATUS NTAPI NtQueryInformationToken(
 738    _In_ HANDLE TokenHandle,
 739    _In_ TOKEN_INFORMATION_CLASS TokenInformationClass,
 740    _Out_writes_bytes_to_opt_(TokenInformationLength, *ReturnLength) PVOID TokenInformation,
 741    _In_ ULONG TokenInformationLength,
 742    _Out_ PULONG ReturnLength);
 743#define NtCurrentProcessToken() ((HANDLE) (LONG_PTR) - 4) // for NtQueryInformationToken only; Windows 8+
 744
 745NTSYSAPI NTSTATUS NTAPI NtReadFile(
 746    _In_ HANDLE FileHandle,
 747    _In_opt_ HANDLE Event,
 748    _In_opt_ PIO_APC_ROUTINE ApcRoutine,
 749    _In_opt_ PVOID ApcContext,
 750    _Out_ PIO_STATUS_BLOCK IoStatusBlock,
 751    _Out_writes_bytes_(Length) PVOID Buffer,
 752    _In_ ULONG Length,
 753    _In_opt_ PLARGE_INTEGER ByteOffset,
 754    _In_opt_ PULONG Key);
 755
 756NTSYSAPI NTSTATUS NTAPI NtCreateEvent(
 757    _Out_ PHANDLE EventHandle,
 758    _In_ ACCESS_MASK DesiredAccess,
 759    _In_opt_ POBJECT_ATTRIBUTES ObjectAttributes,
 760    _In_ EVENT_TYPE EventType,
 761    _In_ BOOLEAN InitialState);
 762
 763NTSYSAPI NTSTATUS NTAPI NtQueryAttributesFile(
 764    _In_ PCOBJECT_ATTRIBUTES ObjectAttributes,
 765    _Out_ PFILE_BASIC_INFORMATION FileInformation);
 766
 767NTSYSAPI NTSTATUS NTAPI RtlUnicodeToUTF8N(
 768    _Out_writes_bytes_to_(UTF8StringMaxByteCount, *UTF8StringActualByteCount) PCHAR UTF8StringDestination,
 769    _In_ ULONG UTF8StringMaxByteCount,
 770    _Out_opt_ PULONG UTF8StringActualByteCount,
 771    _In_reads_bytes_(UnicodeStringByteCount) PCWCH UnicodeStringSource,
 772    _In_ ULONG UnicodeStringByteCount);
 773
 774NTSYSAPI NTSTATUS NTAPI RtlUTF8ToUnicodeN(
 775    _Out_writes_bytes_to_(UnicodeStringMaxByteCount, *UnicodeStringActualByteCount) PWSTR UnicodeStringDestination,
 776    _In_ ULONG UnicodeStringMaxByteCount,
 777    _Out_opt_ PULONG UnicodeStringActualByteCount,
 778    _In_reads_bytes_(UTF8StringByteCount) PCCH UTF8StringSource,
 779    _In_ ULONG UTF8StringByteCount);
 780
 781#define RTL_MAX_DRIVE_LETTERS 32
 782typedef struct _RTL_DRIVE_LETTER_CURDIR {
 783    USHORT Flags;
 784    USHORT Length;
 785    ULONG TimeStamp;
 786    STRING DosPath;
 787} RTL_DRIVE_LETTER_CURDIR, *PRTL_DRIVE_LETTER_CURDIR;
 788
 789typedef struct _RTL_USER_PROCESS_PARAMETERS_FULL {
 790    ULONG MaximumLength;
 791    ULONG Length;
 792
 793    ULONG Flags;
 794    ULONG DebugFlags;
 795
 796    HANDLE ConsoleHandle;
 797    ULONG ConsoleFlags;
 798    HANDLE StandardInput;
 799    HANDLE StandardOutput;
 800    HANDLE StandardError;
 801
 802    CURDIR CurrentDirectory;
 803    UNICODE_STRING DllPath;
 804    UNICODE_STRING ImagePathName;
 805    UNICODE_STRING CommandLine;
 806    PVOID Environment;
 807
 808    ULONG StartingX;
 809    ULONG StartingY;
 810    ULONG CountX;
 811    ULONG CountY;
 812    ULONG CountCharsX;
 813    ULONG CountCharsY;
 814    ULONG FillAttribute;
 815
 816    ULONG WindowFlags;
 817    ULONG ShowWindowFlags;
 818    UNICODE_STRING WindowTitle;
 819    UNICODE_STRING DesktopInfo;
 820    UNICODE_STRING ShellInfo;
 821    UNICODE_STRING RuntimeData;
 822    RTL_DRIVE_LETTER_CURDIR CurrentDirectories[RTL_MAX_DRIVE_LETTERS];
 823
 824    // Windows Vista
 825    ULONG_PTR EnvironmentSize;
 826    // Windows 7
 827    ULONG_PTR EnvironmentVersion;
 828
 829    // Windows 8
 830    PVOID PackageDependencyData;
 831    ULONG ProcessGroupId;
 832
 833    // ...
 834} RTL_USER_PROCESS_PARAMETERS_FULL, *PRTL_USER_PROCESS_PARAMETERS_FULL;
 835
 836typedef struct KERNEL_CALLBACK_TABLE* PKERNEL_CALLBACK_TABLE;
 837typedef struct API_SET_NAMESPACE* PAPI_SET_NAMESPACE;
 838typedef struct RTL_BITMAP* PRTL_BITMAP;
 839typedef struct SILO_USER_SHARED_DATA* PSILO_USER_SHARED_DATA;
 840typedef struct CPTABLEINFO* PCPTABLEINFO;
 841typedef struct NLSTABLEINFO* PNLSTABLEINFO;
 842typedef struct GDI_HANDLE_ENTRY* PGDI_HANDLE_ENTRY;
 843
 844typedef struct _PEB_FULL {
 845    //
 846    // The process was cloned with an inherited address space.
 847    //
 848    BOOLEAN InheritedAddressSpace;
 849
 850    //
 851    // The process has image file execution options (IFEO).
 852    //
 853    BOOLEAN ReadImageFileExecOptions;
 854
 855    //
 856    // The process has a debugger attached.
 857    //
 858    BOOLEAN BeingDebugged;
 859
 860    union {
 861        BOOLEAN BitField;
 862        struct
 863        {
 864            BOOLEAN ImageUsesLargePages : 1;          // The process uses large image regions (4 MB).
 865            BOOLEAN IsProtectedProcess : 1;           // The process is a protected process.
 866            BOOLEAN IsImageDynamicallyRelocated : 1;  // The process image base address was relocated.
 867            BOOLEAN SkipPatchingUser32Forwarders : 1; // The process skipped forwarders for User32.dll functions. 1 for 64-bit, 0 for 32-bit.
 868            BOOLEAN IsPackagedProcess : 1;            // The process is a packaged store process (APPX/MSIX).
 869            BOOLEAN IsAppContainerProcess : 1;        // The process has an AppContainer token.
 870            BOOLEAN IsProtectedProcessLight : 1;      // The process is a protected process (light).
 871            BOOLEAN IsLongPathAwareProcess : 1;       // The process is long path aware.
 872        };
 873    };
 874
 875    //
 876    // Handle to a mutex for synchronization.
 877    //
 878    HANDLE Mutant;
 879
 880    //
 881    // Pointer to the base address of the process image.
 882    //
 883    PVOID ImageBaseAddress;
 884
 885    //
 886    // Pointer to the process loader data.
 887    //
 888    PPEB_LDR_DATA Ldr;
 889
 890    //
 891    // Pointer to the process parameters.
 892    //
 893    PRTL_USER_PROCESS_PARAMETERS_FULL ProcessParameters;
 894
 895    //
 896    // Reserved.
 897    //
 898    PVOID SubSystemData;
 899
 900    //
 901    // Pointer to the process default heap.
 902    //
 903    PVOID ProcessHeap;
 904
 905    //
 906    // Pointer to a critical section used to synchronize access to the PEB.
 907    //
 908    PRTL_CRITICAL_SECTION FastPebLock;
 909
 910    //
 911    // Pointer to a singly linked list used by ATL.
 912    //
 913    PSLIST_HEADER AtlThunkSListPtr;
 914
 915    //
 916    // Handle to the Image File Execution Options key.
 917    //
 918    HANDLE IFEOKey;
 919
 920    //
 921    // Cross process flags.
 922    //
 923    union {
 924        ULONG CrossProcessFlags;
 925        struct
 926        {
 927            ULONG ProcessInJob : 1;               // The process is part of a job.
 928            ULONG ProcessInitializing : 1;        // The process is initializing.
 929            ULONG ProcessUsingVEH : 1;            // The process is using VEH.
 930            ULONG ProcessUsingVCH : 1;            // The process is using VCH.
 931            ULONG ProcessUsingFTH : 1;            // The process is using FTH.
 932            ULONG ProcessPreviouslyThrottled : 1; // The process was previously throttled.
 933            ULONG ProcessCurrentlyThrottled : 1;  // The process is currently throttled.
 934            ULONG ProcessImagesHotPatched : 1;    // The process images are hot patched. // RS5
 935            ULONG ReservedBits0 : 24;
 936        };
 937    };
 938
 939    //
 940    // User32 KERNEL_CALLBACK_TABLE (ntuser.h)
 941    //
 942    union {
 943        PKERNEL_CALLBACK_TABLE KernelCallbackTable;
 944        PVOID UserSharedInfoPtr;
 945    };
 946
 947    //
 948    // Reserved.
 949    //
 950    ULONG SystemReserved;
 951
 952    //
 953    // Pointer to the Active Template Library (ATL) singly linked list (32-bit)
 954    //
 955    ULONG AtlThunkSListPtr32;
 956
 957    //
 958    // Pointer to the API Set Schema.
 959    //
 960    PAPI_SET_NAMESPACE ApiSetMap;
 961
 962    //
 963    // Counter for TLS expansion.
 964    //
 965    ULONG TlsExpansionCounter;
 966
 967    //
 968    // Pointer to the TLS bitmap.
 969    //
 970    PRTL_BITMAP TlsBitmap;
 971
 972    //
 973    // Bits for the TLS bitmap.
 974    //
 975    ULONG TlsBitmapBits[2];
 976
 977    //
 978    // Reserved for CSRSS.
 979    //
 980    PVOID ReadOnlySharedMemoryBase;
 981
 982    //
 983    // Pointer to the USER_SHARED_DATA for the current SILO.
 984    //
 985    PSILO_USER_SHARED_DATA SharedData;
 986
 987    //
 988    // Reserved for CSRSS.
 989    //
 990    PVOID* ReadOnlyStaticServerData;
 991
 992    //
 993    // Pointer to the ANSI code page data.
 994    //
 995    PCPTABLEINFO AnsiCodePageData;
 996
 997    //
 998    // Pointer to the OEM code page data.
 999    //
1000    PCPTABLEINFO OemCodePageData;
1001
1002    //
1003    // Pointer to the Unicode case table data.
1004    //
1005    PNLSTABLEINFO UnicodeCaseTableData;
1006
1007    //
1008    // The total number of system processors.
1009    //
1010    ULONG NumberOfProcessors;
1011
1012    //
1013    // Global flags for the system.
1014    //
1015    union {
1016        ULONG NtGlobalFlag;
1017        struct
1018        {
1019            ULONG StopOnException : 1;          // FLG_STOP_ON_EXCEPTION
1020            ULONG ShowLoaderSnaps : 1;          // FLG_SHOW_LDR_SNAPS
1021            ULONG DebugInitialCommand : 1;      // FLG_DEBUG_INITIAL_COMMAND
1022            ULONG StopOnHungGUI : 1;            // FLG_STOP_ON_HUNG_GUI
1023            ULONG HeapEnableTailCheck : 1;      // FLG_HEAP_ENABLE_TAIL_CHECK
1024            ULONG HeapEnableFreeCheck : 1;      // FLG_HEAP_ENABLE_FREE_CHECK
1025            ULONG HeapValidateParameters : 1;   // FLG_HEAP_VALIDATE_PARAMETERS
1026            ULONG HeapValidateAll : 1;          // FLG_HEAP_VALIDATE_ALL
1027            ULONG ApplicationVerifier : 1;      // FLG_APPLICATION_VERIFIER
1028            ULONG MonitorSilentProcessExit : 1; // FLG_MONITOR_SILENT_PROCESS_EXIT
1029            ULONG PoolEnableTagging : 1;        // FLG_POOL_ENABLE_TAGGING
1030            ULONG HeapEnableTagging : 1;        // FLG_HEAP_ENABLE_TAGGING
1031            ULONG UserStackTraceDb : 1;         // FLG_USER_STACK_TRACE_DB
1032            ULONG KernelStackTraceDb : 1;       // FLG_KERNEL_STACK_TRACE_DB
1033            ULONG MaintainObjectTypeList : 1;   // FLG_MAINTAIN_OBJECT_TYPELIST
1034            ULONG HeapEnableTagByDll : 1;       // FLG_HEAP_ENABLE_TAG_BY_DLL
1035            ULONG DisableStackExtension : 1;    // FLG_DISABLE_STACK_EXTENSION
1036            ULONG EnableCsrDebug : 1;           // FLG_ENABLE_CSRDEBUG
1037            ULONG EnableKDebugSymbolLoad : 1;   // FLG_ENABLE_KDEBUG_SYMBOL_LOAD
1038            ULONG DisablePageKernelStacks : 1;  // FLG_DISABLE_PAGE_KERNEL_STACKS
1039            ULONG EnableSystemCritBreaks : 1;   // FLG_ENABLE_SYSTEM_CRIT_BREAKS
1040            ULONG HeapDisableCoalescing : 1;    // FLG_HEAP_DISABLE_COALESCING
1041            ULONG EnableCloseExceptions : 1;    // FLG_ENABLE_CLOSE_EXCEPTIONS
1042            ULONG EnableExceptionLogging : 1;   // FLG_ENABLE_EXCEPTION_LOGGING
1043            ULONG EnableHandleTypeTagging : 1;  // FLG_ENABLE_HANDLE_TYPE_TAGGING
1044            ULONG HeapPageAllocs : 1;           // FLG_HEAP_PAGE_ALLOCS
1045            ULONG DebugInitialCommandEx : 1;    // FLG_DEBUG_INITIAL_COMMAND_EX
1046            ULONG DisableDbgPrint : 1;          // FLG_DISABLE_DBGPRINT
1047            ULONG CritSecEventCreation : 1;     // FLG_CRITSEC_EVENT_CREATION
1048            ULONG LdrTopDown : 1;               // FLG_LDR_TOP_DOWN
1049            ULONG EnableHandleExceptions : 1;   // FLG_ENABLE_HANDLE_EXCEPTIONS
1050            ULONG DisableProtDlls : 1;          // FLG_DISABLE_PROTDLLS
1051        } NtGlobalFlags;
1052    };
1053
1054    //
1055    // Timeout for critical sections.
1056    //
1057    LARGE_INTEGER CriticalSectionTimeout;
1058
1059    //
1060    // Reserved size for heap segments.
1061    //
1062    SIZE_T HeapSegmentReserve;
1063
1064    //
1065    // Committed size for heap segments.
1066    //
1067    SIZE_T HeapSegmentCommit;
1068
1069    //
1070    // Threshold for decommitting total free heap.
1071    //
1072    SIZE_T HeapDeCommitTotalFreeThreshold;
1073
1074    //
1075    // Threshold for decommitting free heap blocks.
1076    //
1077    SIZE_T HeapDeCommitFreeBlockThreshold;
1078
1079    //
1080    // Number of process heaps.
1081    //
1082    ULONG NumberOfHeaps;
1083
1084    //
1085    // Maximum number of process heaps.
1086    //
1087    ULONG MaximumNumberOfHeaps;
1088
1089    //
1090    // Pointer to an array of process heaps. ProcessHeaps is initialized
1091    // to point to the first free byte after the PEB and MaximumNumberOfHeaps
1092    // is computed from the page size used to hold the PEB, less the fixed
1093    // size of this data structure.
1094    //
1095    PVOID* ProcessHeaps;
1096
1097    //
1098    // Pointer to the system GDI shared handle table.
1099    //
1100    PGDI_HANDLE_ENTRY GdiSharedHandleTable;
1101
1102    //
1103    // Pointer to the process starter helper.
1104    //
1105    PVOID ProcessStarterHelper;
1106
1107    //
1108    // The maximum number of GDI function calls during batch operations (GdiSetBatchLimit)
1109    //
1110    ULONG GdiDCAttributeList;
1111
1112    //
1113    // Pointer to the loader lock critical section.
1114    //
1115    PRTL_CRITICAL_SECTION LoaderLock;
1116
1117    //
1118    // Major version of the operating system.
1119    //
1120    ULONG OSMajorVersion;
1121
1122    //
1123    // Minor version of the operating system.
1124    //
1125    ULONG OSMinorVersion;
1126
1127    //
1128    // Build number of the operating system.
1129    //
1130    USHORT OSBuildNumber;
1131
1132    //
1133    // CSD version of the operating system.
1134    //
1135    USHORT OSCSDVersion;
1136
1137    //
1138    // Platform ID of the operating system.
1139    //
1140    ULONG OSPlatformId;
1141
1142    //
1143    // Subsystem version of the current process image (PE Headers).
1144    //
1145    ULONG ImageSubsystem;
1146
1147    //
1148    // Major version of the current process image subsystem (PE Headers).
1149    //
1150    ULONG ImageSubsystemMajorVersion;
1151
1152    //
1153    // Minor version of the current process image subsystem (PE Headers).
1154    //
1155    ULONG ImageSubsystemMinorVersion;
1156
1157    // ...
1158} PEB_FULL, *PPEB_FULL;
1159
1160typedef struct _TEB_FULL {
1161    //
1162    // Thread Information Block (TIB) contains the thread's stack, base and limit addresses, the current stack pointer, and the exception list.
1163    //
1164    NT_TIB NtTib;
1165
1166    //
1167    // Reserved.
1168    //
1169    PVOID EnvironmentPointer;
1170
1171    //
1172    // Client ID for this thread.
1173    //
1174    CLIENT_ID ClientId;
1175
1176    //
1177    // A handle to an active Remote Procedure Call (RPC) if the thread is currently involved in an RPC operation.
1178    //
1179    PVOID ActiveRpcHandle;
1180
1181    //
1182    // A pointer to the __declspec(thread) local storage array.
1183    //
1184    PVOID ThreadLocalStoragePointer;
1185
1186    //
1187    // A pointer to the Process Environment Block (PEB), which contains information about the process.
1188    //
1189    PPEB_FULL ProcessEnvironmentBlock;
1190
1191    //
1192    // The previous Win32 error value for this thread.
1193    //
1194    ULONG LastErrorValue;
1195
1196    //
1197    // The number of critical sections currently owned by this thread.
1198    //
1199    ULONG CountOfOwnedCriticalSections;
1200
1201    //
1202    // Reserved.
1203    //
1204    PVOID CsrClientThread;
1205
1206    //
1207    // Reserved for win32k.sys
1208    //
1209    PVOID Win32ThreadInfo;
1210
1211    //
1212    // Reserved for user32.dll
1213    //
1214    ULONG User32Reserved[26];
1215
1216    //
1217    // Reserved for winsrv.dll
1218    //
1219    ULONG UserReserved[5];
1220
1221    //
1222    // Reserved.
1223    //
1224    PVOID WOW32Reserved;
1225
1226    //
1227    // The LCID of the current thread. (Kernel32!GetThreadLocale)
1228    //
1229    LCID CurrentLocale;
1230} TEB_FULL, *PTEB_FULL;
1231
1232static inline PTEB_FULL ffGetTeb() {
1233    return (PTEB_FULL) NtCurrentTeb();
1234}
1235
1236static inline PPEB_FULL ffGetPeb() {
1237    return ffGetTeb()->ProcessEnvironmentBlock;
1238}
1239
1240NTSYSAPI NTSTATUS NTAPI RtlExpandEnvironmentStrings(
1241    _In_opt_ PVOID Environment,
1242    _In_reads_(SourceLength) PCWSTR Source,
1243    _In_ SIZE_T SourceLength,
1244    _Out_writes_(DestinationLength) PWSTR Destination,
1245    _In_ SIZE_T DestinationLength,
1246    _Out_opt_ PSIZE_T ReturnLength);
1247
1248NTSYSAPI NTSTATUS NTAPI NtOpenKey(
1249    _Out_ PHANDLE KeyHandle,
1250    _In_ ACCESS_MASK DesiredAccess,
1251    _In_ POBJECT_ATTRIBUTES ObjectAttributes);
1252
1253typedef enum _KEY_VALUE_INFORMATION_CLASS {
1254    KeyValueBasicInformation,          // KEY_VALUE_BASIC_INFORMATION
1255    KeyValueFullInformation,           // KEY_VALUE_FULL_INFORMATION
1256    KeyValuePartialInformation,        // KEY_VALUE_PARTIAL_INFORMATION
1257    KeyValueFullInformationAlign64,    // KEY_VALUE_FULL_INFORMATION_ALIGN64
1258    KeyValuePartialInformationAlign64, // KEY_VALUE_PARTIAL_INFORMATION_ALIGN64
1259    KeyValueLayerInformation,          // KEY_VALUE_LAYER_INFORMATION
1260    MaxKeyValueInfoClass
1261} KEY_VALUE_INFORMATION_CLASS;
1262
1263NTSYSAPI NTSTATUS NTAPI NtQueryValueKey(
1264    _In_ HANDLE KeyHandle,
1265    _In_ PCUNICODE_STRING ValueName,
1266    _In_ KEY_VALUE_INFORMATION_CLASS KeyValueInformationClass,
1267    _Out_writes_bytes_to_opt_(Length, *ResultLength) PVOID KeyValueInformation,
1268    _In_ ULONG Length,
1269    _Out_ PULONG ResultLength);
1270
1271NTSYSAPI NTSTATUS NTAPI RtlOpenCurrentUser(
1272    _In_ ACCESS_MASK DesiredAccess,
1273    _Out_ PHANDLE CurrentUserKey);
1274
1275typedef struct _KEY_VALUE_PARTIAL_INFORMATION {
1276    ULONG TitleIndex;
1277    ULONG Type;
1278    ULONG DataLength;
1279    _Field_size_bytes_(DataLength) UCHAR Data[];
1280} KEY_VALUE_PARTIAL_INFORMATION, *PKEY_VALUE_PARTIAL_INFORMATION;
1281
1282typedef enum _KEY_INFORMATION_CLASS {
1283    KeyBasicInformation,          // KEY_BASIC_INFORMATION
1284    KeyNodeInformation,           // KEY_NODE_INFORMATION
1285    KeyFullInformation,           // KEY_FULL_INFORMATION
1286    KeyNameInformation,           // KEY_NAME_INFORMATION
1287    KeyCachedInformation,         // KEY_CACHED_INFORMATION
1288    KeyFlagsInformation,          // KEY_FLAGS_INFORMATION
1289    KeyVirtualizationInformation, // KEY_VIRTUALIZATION_INFORMATION
1290    KeyHandleTagsInformation,     // KEY_HANDLE_TAGS_INFORMATION
1291    KeyTrustInformation,          // KEY_TRUST_INFORMATION
1292    KeyLayerInformation,          // KEY_LAYER_INFORMATION
1293    MaxKeyInfoClass
1294} KEY_INFORMATION_CLASS;
1295
1296NTSYSAPI NTSTATUS NTAPI NtEnumerateKey(
1297    _In_ HANDLE KeyHandle,
1298    _In_ ULONG Index,
1299    _In_ KEY_INFORMATION_CLASS KeyInformationClass,
1300    _Out_writes_bytes_to_opt_(Length, *ResultLength) PVOID KeyInformation,
1301    _In_ ULONG Length,
1302    _Out_ PULONG ResultLength);
1303
1304typedef struct _KEY_BASIC_INFORMATION {
1305    LARGE_INTEGER LastWriteTime;                 // Number of 100-nanosecond intervals since this key or any of its values changed.
1306    ULONG TitleIndex;                            // Reserved // A legacy field originally intended for use with localization such as an index of a resource table.
1307    ULONG NameLength;                            // The size, in bytes, of the key name string in the Name array.
1308    _Field_size_bytes_(NameLength) WCHAR Name[]; // The name of the registry key. This string is not null-terminated.
1309} KEY_BASIC_INFORMATION, *PKEY_BASIC_INFORMATION;
1310
1311typedef struct _KEY_CACHED_INFORMATION {
1312    LARGE_INTEGER LastWriteTime; // Number of 100-nanosecond intervals since this key or any of its values changed.
1313    ULONG TitleIndex;            // Reserved // A legacy field originally intended for use with localization such as an index of a resource table.
1314    ULONG SubKeys;               // The number of subkeys for a key.
1315    ULONG MaxNameLen;            // The maximum length, in bytes, of a subkey name.
1316    ULONG Values;                // The number of value entries.
1317    ULONG MaxValueNameLen;       // The maximum length, in bytes, of a value entry name.
1318    ULONG MaxValueDataLen;       // The maximum length, in bytes, of a value entry data field.
1319    ULONG NameLength;            // Size, in bytes, of the key's own (leaf) name, without the terminator. The name itself is not stored.
1320} KEY_CACHED_INFORMATION, *PKEY_CACHED_INFORMATION;
1321// 36 bytes of members, but LARGE_INTEGER makes the struct 8-byte aligned, and that is exactly what
1322// the kernel demands: a 36-byte buffer is rejected with STATUS_BUFFER_TOO_SMALL (measured).
1323// The kernel writes all 40 bytes -- the 4 padding bytes included, zeroed -- and reports
1324// ResultLength = 40 whatever size you pass, so a larger buffer buys nothing (measured 40..4096).
1325// This is the only information class that never appends a string: NameLength is the length of the
1326// key's own (leaf) name in bytes without the terminator, and the name itself is not returned.
1327static_assert(sizeof(KEY_CACHED_INFORMATION) == 40, "KEY_CACHED_INFORMATION should be 40 bytes");
1328
1329NTSYSAPI NTSTATUS NTAPI NtQueryKey(
1330    _In_ HANDLE KeyHandle,
1331    _In_ KEY_INFORMATION_CLASS KeyInformationClass,
1332    _Out_writes_bytes_to_opt_(Length, *ResultLength) PVOID KeyInformation,
1333    _In_ ULONG Length,
1334    _Out_ PULONG ResultLength);
1335
1336NTSYSAPI NTSTATUS NTAPI NtOpenProcess(
1337    _Out_ PHANDLE ProcessHandle,
1338    _In_ ACCESS_MASK DesiredAccess,
1339    _In_ PCOBJECT_ATTRIBUTES ObjectAttributes,
1340    _In_opt_ PCLIENT_ID ClientId);
1341
1342NTSYSAPI NTSTATUS NTAPI LdrLoadDll(
1343    _In_opt_ PCWSTR DllPath,
1344    _In_opt_ PULONG DllCharacteristics,
1345    _In_ PCUNICODE_STRING DllName,
1346    _Out_ PVOID* DllHandle);
1347
1348NTSYSAPI NTSTATUS NTAPI LdrUnloadDll(
1349    _In_ PVOID DllHandle);
1350
1351NTSYSAPI NTSTATUS NTAPI LdrGetDllHandle(
1352    _In_opt_ PCWSTR DllPath,
1353    _In_opt_ PULONG DllCharacteristics,
1354    _In_ PCUNICODE_STRING DllName,
1355    _Out_ PVOID* DllHandle);
1356
1357NTSYSAPI NTSTATUS NTAPI LdrGetProcedureAddress(
1358    _In_ PVOID DllHandle,
1359    _In_opt_ PCANSI_STRING ProcedureName,
1360    _In_opt_ ULONG ProcedureNumber,
1361    _Out_ PVOID* ProcedureAddress);
1362
1363typedef _Function_class_(LDR_LOADED_MODULE_ENUMERATION_CALLBACK_FUNCTION)
1364VOID NTAPI LDR_LOADED_MODULE_ENUMERATION_CALLBACK_FUNCTION(
1365    _In_ PLDR_DATA_TABLE_ENTRY DataTableEntry,
1366    _In_opt_ PVOID Context,
1367    _Inout_ BOOLEAN* StopEnumeration
1368);
1369
1370NTSYSAPI
1371NTSTATUS
1372NTAPI
1373LdrEnumerateLoadedModules(
1374    _In_ BOOLEAN ReservedFlag,
1375    _In_ LDR_LOADED_MODULE_ENUMERATION_CALLBACK_FUNCTION* EnumProc,
1376    _In_opt_ PVOID Context
1377);
1378
1379typedef enum _SECTION_INHERIT {
1380    ViewShare = 1,
1381    ViewUnmap = 2
1382} SECTION_INHERIT;
1383
1384NTSYSAPI NTSTATUS NTAPI NtCreateSection(
1385    _Out_ PHANDLE SectionHandle,
1386    _In_ ACCESS_MASK DesiredAccess,
1387    _In_opt_ POBJECT_ATTRIBUTES ObjectAttributes,
1388    _In_opt_ PLARGE_INTEGER MaximumSize,
1389    _In_ ULONG SectionPageProtection,
1390    _In_ ULONG AllocationAttributes,
1391    _In_opt_ HANDLE FileHandle);
1392
1393NTSYSAPI NTSTATUS NTAPI NtMapViewOfSection(
1394    _In_ HANDLE SectionHandle,
1395    _In_ HANDLE ProcessHandle,
1396    _Inout_ _At_(*BaseAddress, _Readable_bytes_(*ViewSize) _Writable_bytes_(*ViewSize) _Post_readable_byte_size_(*ViewSize)) PVOID* BaseAddress,
1397    _In_ ULONG_PTR ZeroBits,
1398    _In_ SIZE_T CommitSize,
1399    _Inout_opt_ PLARGE_INTEGER SectionOffset,
1400    _Inout_ PSIZE_T ViewSize,
1401    _In_ SECTION_INHERIT InheritDisposition,
1402    _In_ ULONG AllocationType,
1403    _In_ ULONG PageProtection);
1404
1405NTSYSAPI NTSTATUS NTAPI NtUnmapViewOfSection(
1406    _In_ HANDLE ProcessHandle,
1407    _In_opt_ PVOID BaseAddress);
1408
1409NTSYSAPI LOGICAL NTAPI RtlQueryPerformanceCounter(
1410    _Out_ PLARGE_INTEGER PerformanceCounter);
1411
1412NTSYSAPI LOGICAL NTAPI RtlQueryPerformanceFrequency(
1413    _Out_ PLARGE_INTEGER PerformanceFrequency);
1414
1415NTSYSAPI NTSTATUS NTAPI NtCancelIoFileEx(
1416    _In_ HANDLE FileHandle,
1417    _In_opt_ PIO_STATUS_BLOCK IoRequestToCancel,
1418    _Out_ PIO_STATUS_BLOCK IoStatusBlock);
1419
1420NTSYSAPI NTSTATUS NTAPI NtTerminateProcess(
1421    _In_opt_ HANDLE ProcessHandle,
1422    _In_ NTSTATUS ExitStatus);
1423
1424NTSYSAPI NTSTATUS NTAPI RtlAcquirePebLock(VOID);
1425NTSYSAPI NTSTATUS NTAPI RtlReleasePebLock(VOID);
1426
1427typedef struct _FILE_FS_FULL_SIZE_INFORMATION_EX {
1428    ULONGLONG ActualTotalAllocationUnits;
1429    ULONGLONG ActualAvailableAllocationUnits;
1430    ULONGLONG ActualPoolUnavailableAllocationUnits;
1431    ULONGLONG CallerTotalAllocationUnits;
1432    ULONGLONG CallerAvailableAllocationUnits;
1433    ULONGLONG CallerPoolUnavailableAllocationUnits;
1434    ULONGLONG UsedAllocationUnits;
1435    ULONGLONG TotalReservedAllocationUnits;
1436    ULONGLONG VolumeStorageReserveAllocationUnits;
1437    ULONGLONG AvailableCommittedAllocationUnits;
1438    ULONGLONG PoolAvailableAllocationUnits;
1439    ULONG     SectorsPerAllocationUnit;
1440    ULONG     BytesPerSector;
1441} FILE_FS_FULL_SIZE_INFORMATION_EX, *PFILE_FS_FULL_SIZE_INFORMATION_EX;
1442
1443enum {
1444    FileFsFullSizeInformationEx = 14
1445};