diff --git a/.github/workflows/msbuild.yml b/.github/workflows/msbuild.yml new file mode 100644 index 0000000..faecc1d --- /dev/null +++ b/.github/workflows/msbuild.yml @@ -0,0 +1,36 @@ +name: MSBuild + +on: + push: + branches: [ "main" ] + pull_request: + branches: [ "main" ] + +env: + SOLUTION_FILE_PATH: .\Source\KNSoft.NDK.sln + +permissions: + contents: read + +jobs: + build: + strategy: + matrix: + platform: [x64, x86, ARM64] + config: [Debug, Release] + fail-fast: false + runs-on: windows-latest + steps: + - name: Source checkout + uses: actions/checkout@main + with: + submodules: recursive + - name: Prepare MSBuild + uses: microsoft/setup-msbuild@main + - name: Build + working-directory: ${{env.GITHUB_WORKSPACE}} + run: msbuild ${{env.SOLUTION_FILE_PATH}} /restore /m /p:Configuration=${{matrix.config}} /p:Platform=${{matrix.platform}} /p:RestorePackagesConfig=true + - name: Run Unit Test (x64, x86) + if: ${{ matrix.platform == 'x64' || matrix.platform == 'x86' }} + working-directory: ${{env.GITHUB_WORKSPACE}} + run: .\Source\OutDir\${{matrix.platform}}\${{matrix.config}}\Test.exe -Run diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..ee0152f --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ + MIT License + + Copyright (c) KNSoft.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in all + copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE diff --git a/README.md b/README.md new file mode 100644 index 0000000..9f393d5 --- /dev/null +++ b/README.md @@ -0,0 +1,91 @@ +# KNSoft.NDK + +[![NuGet Downloads](https://img.shields.io/nuget/dt/KNSoft.NDK)](https://www.nuget.org/packages/KNSoft.NDK) [![GitHub Actions Workflow Status](https://img.shields.io/github/actions/workflow/status/KNSoft/KNSoft.NDK/msbuild.yml)](https://github.com/KNSoft/KNSoft.NDK/actions/workflows/msbuild.yml) ![PR Welcome](https://img.shields.io/badge/PR-welcome-0688CB.svg) [![GitHub License](https://img.shields.io/github/license/KNSoft/KNSoft.NDK)](./LICENSE) + +KNSoft.NDK provides native C/C++ definitions and import libraries for Windows NT and some specifications development. + +## Feature + +- Windows NT + - Undocumented type definitions, e.g. `PEB`, `TEB`, `LDR_*`, ... + - Undocumented API declarations, e.g. `Nt/Zw*`, `Ldr*`, ... + - Definitions in public sources but not in Windows SDK, e.g. `winsta.h`, `KUSER_SHARED_DATA`, ... + - Import library for Windows DLL exports, e.g. `KERNEL32.dll!CreateProcessInternalW`, `ntdll.dll!LdrRegisterDllNotification`, ... + - Addendum to Windows SDK + - Extension macros and definitions, e.g. `NtCurrentPeb()`, `PEB(64/32)`, `TEB(64/32)`, ... +- Specifications + - SMBIOS + - CPUID + - MSVC +- Kits + - Unit Test Framework + - StrSafe.h (different from `strsafe.h` in Windows SDK) + +## Usage + +[![NuGet Downloads](https://img.shields.io/nuget/dt/KNSoft.NDK)](https://www.nuget.org/packages/KNSoft.NDK) + +### TL;DR + +Include [NDK.h](./Source/Include/KNSoft/NDK/NDK.h) instead of (or **BEFORE**) `Windows.h` will do. +```C +#include +``` + +NuGet package [KNSoft.NDK](https://www.nuget.org/packages/KNSoft.NDK) includes all the headers and compiled libraries. + +### Details + +The following features are not enabled by default, reference corresponding headers and libraries on demand: + +- Specifications + - CPUID: [CPUID.h](./Source/Include/KNSoft/NDK/Extension/CPUID.h) + - SMBIOS: [SMBIOS.h](./Source/Include/KNSoft/NDK/Extension/SMBIOS.h) +- Ntdll Hash API (`(A_SHA/MD4/MD5)(Init/Update/Final)`) + - [Ntdll.Hash.h](./Source/Include/KNSoft/NDK/WinDef/API/Ntdll.Hash.h) + - KNSoft.NDK.Ntdll.Hash.lib (Generated from [KNSoft.NDK.Ntdll.Hash.xml](./Source/KNSoft.NDK/WinAPI/KNSoft.NDK.Ntdll.Hash.xml)) +- Windows API import library addendum + - KNSoft.NDK.WinAPI.lib (Generated from [KNSoft.NDK.WinAPI.xml](./Source/KNSoft.NDK/WinAPI/KNSoft.NDK.WinAPI.xml)) +- Unit Test Framework + - [UnitTest.h](./Source/Include/KNSoft/NDK/UnitTest/UnitTest.h) + - [UnitTest.inl](./Source/Include/KNSoft/NDK/UnitTest/UnitTest.inl) +- Safe string functions (different from `strsafe.h` in Windows SDK) + - [StrSafe.h](./Source/Include/KNSoft/NDK/Extension/StrSafe.h) + +The following features are enabled by default, can be excluded by defining corresponding macro: + +| Macro | Exclude feature | +| ---- | ---- | +| _KNSOFT_NDK_NO_EXTENSION | Addendum or extension macros and definitions | +| _KNSOFT_NDK_NO_EXTENSION_MSTOOLCHAIN | Microsoft Tool Chain Specification | +| _KNSOFT_NDK_NO_INLINE | Use inline implementation instead of function call | + +## Compatibility + +![PR Welcome](https://img.shields.io/badge/PR-welcome-0688CB.svg) [![GitHub Actions Workflow Status](https://img.shields.io/github/actions/workflow/status/KNSoft/KNSoft.NDK/msbuild.yml)](https://github.com/KNSoft/KNSoft.NDK/actions/workflows/msbuild.yml) + +KNSoft.NDK always keep up with trends, keep up the latest Windows NT and specifications, targets to x86, x64 and ARM64 platforms. + +For project building, only support for the latest MSVC generation tools and SDKs is considered, but it is generally more widely backward compatible. + +For using, it is compatible with VS2015 and above with corresponding SDK. + +> [!CAUTION] +> In beta stage, should be used with caution. + +## License + +[![GitHub License](https://img.shields.io/github/license/KNSoft/KNSoft.NDK)](./LICENSE) + +KNSoft.NDK is licensed under the [MIT](./LICENSE) license. + +The content from the following public sources were used: +- Microsoft WDK/DDK/SDK +- Microsoft Public Symbolic Data +- Microsoft Learning +- Microsoft Windows Protocols + +And public projects: +- [winsiderss/phnt](https://github.com/winsiderss/phnt) - MIT + +KNSoft.NDK also uses [KNSoft/Precomp4C](https://github.com/KNSoft/Precomp4C) to generate DLL import libraries. diff --git a/Source/.editorconfig b/Source/.editorconfig new file mode 100644 index 0000000..aff578a --- /dev/null +++ b/Source/.editorconfig @@ -0,0 +1,77 @@ +# Visual Studio generated .editorconfig file with C++ settings. +root = true + +[*.{c,c++,cc,cpp,cppm,cxx,h,h++,hh,hpp,hxx,inl,ipp,ixx,tlh,tli}] + +charset = utf-8-bom +indent_style = space +indent_size = 4 +end_of_line = crlf +insert_final_newline = true +max_line_length = 120 + +# Visual C++ Code Style settings + +cpp_generate_documentation_comments = xml + +# Visual C++ Formatting settings + +cpp_indent_braces = false +cpp_indent_multi_line_relative_to = innermost_parenthesis +cpp_indent_within_parentheses = align_to_parenthesis +cpp_indent_preserve_within_parentheses = true +cpp_indent_case_contents = true +cpp_indent_case_labels = true +cpp_indent_case_contents_when_block = false +cpp_indent_lambda_braces_when_parameter = false +cpp_indent_goto_labels = leftmost_column +cpp_indent_preprocessor = leftmost_column +cpp_indent_access_specifiers = false +cpp_indent_namespace_contents = true +cpp_indent_preserve_comments = true +cpp_new_line_before_open_brace_namespace = new_line +cpp_new_line_before_open_brace_type = new_line +cpp_new_line_before_open_brace_function = new_line +cpp_new_line_before_open_brace_block = new_line +cpp_new_line_before_open_brace_lambda = new_line +cpp_new_line_scope_braces_on_separate_lines = true +cpp_new_line_close_brace_same_line_empty_type = true +cpp_new_line_close_brace_same_line_empty_function = true +cpp_new_line_before_catch = false +cpp_new_line_before_else = false +cpp_new_line_before_while_in_do_while = false +cpp_space_before_function_open_parenthesis = remove +cpp_space_within_parameter_list_parentheses = false +cpp_space_between_empty_parameter_list_parentheses = false +cpp_space_after_keywords_in_control_flow_statements = true +cpp_space_within_control_flow_statement_parentheses = false +cpp_space_before_lambda_open_parenthesis = false +cpp_space_within_cast_parentheses = false +cpp_space_after_cast_close_parenthesis = false +cpp_space_within_expression_parentheses = false +cpp_space_before_block_open_brace = true +cpp_space_between_empty_braces = false +cpp_space_before_initializer_list_open_brace = false +cpp_space_within_initializer_list_braces = true +cpp_space_preserve_in_initializer_list = true +cpp_space_before_open_square_bracket = false +cpp_space_within_square_brackets = false +cpp_space_before_empty_square_brackets = false +cpp_space_between_empty_square_brackets = false +cpp_space_group_square_brackets = true +cpp_space_within_lambda_brackets = false +cpp_space_between_empty_lambda_brackets = false +cpp_space_before_comma = false +cpp_space_after_comma = true +cpp_space_remove_around_member_operators = true +cpp_space_before_inheritance_colon = true +cpp_space_before_constructor_colon = true +cpp_space_remove_before_semicolon = true +cpp_space_after_semicolon = true +cpp_space_remove_around_unary_operator = true +cpp_space_around_binary_operator = insert +cpp_space_around_assignment_operator = insert +cpp_space_pointer_reference_alignment = ignore +cpp_space_around_ternary_operator = insert +cpp_use_unreal_engine_macro_formatting = true +cpp_wrap_preserve_blocks = all_one_line_scopes \ No newline at end of file diff --git a/Source/.gitignore b/Source/.gitignore new file mode 100644 index 0000000..d59bd3f --- /dev/null +++ b/Source/.gitignore @@ -0,0 +1,9 @@ +.vs +*.user + +/Compatibility +/packages +/OutDir +IntDir + +/*.nupkg \ No newline at end of file diff --git a/Source/Directory.Build.AfterCppDefault.props b/Source/Directory.Build.AfterCppDefault.props new file mode 100644 index 0000000..d56c04b --- /dev/null +++ b/Source/Directory.Build.AfterCppDefault.props @@ -0,0 +1,10 @@ + + + $(DefaultPlatformToolset) + $(SolutionDir)OutDir\$(PlatformTarget)\$(Configuration)\ + IntDir\$(PlatformTarget)\$(Configuration)\ + + + Unicode + + \ No newline at end of file diff --git a/Source/Directory.Build.props b/Source/Directory.Build.props new file mode 100644 index 0000000..4f030c7 --- /dev/null +++ b/Source/Directory.Build.props @@ -0,0 +1,61 @@ + + + + $(MsbuildThisFileDirectory)\Directory.Build.AfterCppDefault.props + + + + + Level3 + stdcpplatest + stdc17 + pch.h + + + + + + + MSB_CONFIGURATIONTYPE_EXE;%(PreprocessorDefinitions) + + + + + MSB_CONFIGURATIONTYPE_DLL;%(PreprocessorDefinitions) + + + + + MSB_CONFIGURATIONTYPE_LIB;%(PreprocessorDefinitions) + + + + + MSB_CONFIGURATIONTYPE_UTILITY;%(PreprocessorDefinitions) + + + + + + + MultiThreaded + + + + + MultiThreadedDebug + + + + + + $(MSBuildProjectDirectory)\$(ProjectName).Build.props + + + + + + $([MSBuild]::GetPathOfFileAbove('Directory.Build.props', '$(MSBuildThisFileDirectory)../')) + + + \ No newline at end of file diff --git a/Source/Include/KNSoft/NDK/Extension/CPUID.h b/Source/Include/KNSoft/NDK/Extension/CPUID.h new file mode 100644 index 0000000..d46fd36 --- /dev/null +++ b/Source/Include/KNSoft/NDK/Extension/CPUID.h @@ -0,0 +1,301 @@ +#pragma once + +#define CPUID_INTEL_VERSION_INFO_MASK 0xFFF3FF0 // Extended Family ID | Extended Model ID | Processor Type | Family ID | Model +#define CPUID_MAKE_INTEL_VERSION_INFO(ExtendedFamilyId, ExtendedModelId, ProcessorType, FamilyId, Model, SteppingId)\ + (((ExtendedFamilyId & 0b11111111) << 20) |\ + ((ExtendedModelId & 0b1111) << 16) |\ + ((ProcessorType & 0b11) << 12) |\ + ((FamilyId & 0b1111) << 8) |\ + ((Model & 0b1111) << 4) |\ + (SteppingId & 0b1111)) + +typedef union _CPUID_INFO +{ + int Registers[4]; + struct + { + int Eax; + int Ebx; + int Ecx; + int Edx; + }; + + /* F_Leaf_SubLeaf, aka F_EAX_ECX */ + + /* 00-03: Basic CPUID Information */ + struct + { + /* Eax */ + unsigned int MaxInputValue; + /* Ebx, Ecx, Edx */ + unsigned int VendorIdString[3]; + } F00_00; + + struct + { +/* + * Eax: Intel CPU version information + * + * 31 28 27 20 19 16 15 14 13 12 11 8 7 4 3 0 + * +-----+--------------------+-------------------+-----+----------------+-----------+-------+-------------+ + * | | Extended Family ID | Extended Model ID | | Processor Type | Family ID | Model | Stepping ID | + * +-----+--------------------+-------------------+-----+----------------+-----------+-------+-------------+ + * + */ + struct + { + unsigned int SteppingId : 4; + unsigned int Model : 4; + unsigned int FamilyId : 4; + unsigned int ProcessorType : 2; + unsigned int ReservedBits0 : 2; + unsigned int ExtendedModelId : 4; + unsigned int ExtendedFamilyId : 8; + unsigned int ReservedBits1 : 4; + } VersionInfo; + /* Ebx: Additional information */ + struct + { + unsigned int BrandIndex : 8; + unsigned int CLFlushLineSize : 8; + unsigned int MaxNumberOfAddressableId : 8; + unsigned int InitialAPICId : 8; + } AdditionalInfo; + /* Ecx, Edx: Feature information */ + struct + { + /* Ecx */ + struct + { + unsigned int SSE3 : 1; /* 00 SSE3 */ + unsigned int PCLMULQDQ : 1; /* 01 PCLMULQDQ */ + unsigned int DTES64 : 1; /* 02 64-bit DS Area */ + unsigned int MONITOR : 1; /* 03 MONITOR/MWAIT */ + unsigned int DS_CPL : 1; /* 04 CPL Qualified Debug Store */ + unsigned int VMX : 1; /* 05 Virtual Machine Extensions */ + unsigned int SMX : 1; /* 06 Safer Mode Extensions */ + unsigned int EIST : 1; /* 07 Enhanced Intel SpeedStep® technology */ + unsigned int TM2 : 1; /* 08 Thermal Monitor 2 */ + unsigned int SSSE3 : 1; /* 09 SSSE3 */ + unsigned int CNXT_ID : 1; /* 10 L1 Context ID*/ + unsigned int SDBG : 1; /* 11 IA32_DEBUG_INTERFACE MSR */ + unsigned int FMA : 1; /* 12 FMA */ + unsigned int CMPXCHG16B : 1; /* 13 CMPXCHG16B Available */ + unsigned int xTPRUpdateControl : 1; /* 14 xTPR Update Control */ + unsigned int PDCM : 1; /* 15 Perfmon and Debug Capability */ + unsigned int ReservedBits0 : 1; /* 16 Reserved */ + unsigned int PCID : 1; /* 17 Process-context identifiers */ + unsigned int DCA : 1; /* 18 Direct Cache Access */ + unsigned int SSE4_1 : 1; /* 19 SSE4.1*/ + unsigned int SSE4_2 : 1; /* 20 SSE4.2*/ + unsigned int x2APIC : 1; /* 21 x2APIC */ + unsigned int MOVBE : 1; /* 22 MOVBE */ + unsigned int POPCNT : 1; /* 23 POPCNT */ + unsigned int TSC_Deadline : 1; /* 24 TSC deadline */ + unsigned int AESNI : 1; /* 25 AESNI */ + unsigned int XSAVE : 1; /* 26 XSAVE */ + unsigned int OSXSAVE : 1; /* 27 CR4.OSXSAVE */ + unsigned int AVX : 1; /* 28 AVX */ + unsigned int F16C : 1; /* 29 16-bit floating-point conversion */ + unsigned int RDRAND : 1; /* 30 RDRAND */ + unsigned int NotUsedBits0 : 1; /* 31 Always 0 */ + }; + /* Edx */ + struct + { + unsigned int FPU : 1; /* 00 x87 FPU */ + unsigned int VME : 1; /* 01 Virtual 8086 mode enhancements */ + unsigned int DE : 1; /* 02 Debugging Extensions */ + unsigned int PSE : 1; /* 03 Page Size Extension */ + unsigned int TSC : 1; /* 04 Time Stamp Counter */ + unsigned int MSR : 1; /* 05 Model Specific Registers RDMSR and WRMSR Instructions */ + unsigned int PAE : 1; /* 06 Physical Address Extension */ + unsigned int MCE : 1; /* 07 Machine Check Exception */ + unsigned int CX8 : 1; /* 08 CMPXCHG8B Instruction */ + unsigned int APIC : 1; /* 09 APIC On-Chip */ + unsigned int ReservedBits1 : 1; /* 10 Reserved */ + unsigned int SEP : 1; /* 11 SYSENTER and SYSEXIT Instructions */ + unsigned int MTRR : 1; /* 12 Memory Type Range Registers */ + unsigned int PGE : 1; /* 13 Page Global Bit */ + unsigned int MCA : 1; /* 14 Machine Check Architecture */ + unsigned int CMOV : 1; /* 15 Conditional Move Instructions */ + unsigned int PAT : 1; /* 16 Page Attribute Table */ + unsigned int PSE_36 : 1; /* 17 36-Bit Page Size Extension */ + unsigned int PSN : 1; /* 18 Processor Serial Number */ + unsigned int CLFSH : 1; /* 19 CLFLUSH Instruction */ + unsigned int ReservedBits2 : 1; /* 20 Reserved */ + unsigned int DS : 1; /* 21 Debug Store */ + unsigned int ACPI : 1; /* 22 Thermal Monitor and Software Controlled Clock Facilities */ + unsigned int MMX : 1; /* 23 Intel MMX Technology */ + unsigned int FXSR : 1; /* 24 FXSAVE and FXRSTOR Instructions */ + unsigned int SSE : 1; /* 25 SSE */ + unsigned int SSE2 : 1; /* 26 SSE2 */ + unsigned int SS : 1; /* 27 Self Snoop */ + unsigned int HTT : 1; /* 28 Max APIC IDs reserved field is Valid */ + unsigned int TM : 1; /* 29 Thermal Monitor */ + unsigned int ReservedBits3 : 1; /* 30 Reserved */ + unsigned int PBE : 1; /* 31 Pending Break Enable */ + }; + } FeatureInfo; + } F01_00; + + /* 07 Structured Extended Feature Flags Enumeration Leaf */ + struct + { + /* Eax */ + unsigned int MaxInputValue; + /* Ebx, Ecx, Edx: Feature Flags */ + struct + { + /* Ebx */ + struct + { + unsigned int FSGSBASE : 1; /* 00 FSGSBASE */ + unsigned int IA32_TSC_ADJUST : 1; /* 01 IA32_TSC_ADJUST MSR */ + unsigned int SGX : 1; /* 02 Intel® Software Guard Extensions */ + unsigned int BMI1 : 1; /* 03 BMI1 */ + unsigned int HLE : 1; /* 04 HLE */ + unsigned int AVX2 : 1; /* 05 AVX2 */ + unsigned int FDP_EXCPTN_ONLY : 1; /* 06 FDP_EXCPTN_ONLY */ + unsigned int SMEP : 1; /* 07 SMEP */ + unsigned int BMI2 : 1; /* 08 BMI2 */ + unsigned int ERMS : 1; /* 09 Enhanced Fast Strings REP MOVB/STOB */ + unsigned int INVPCID : 1; /* 10 INVPCID */ + unsigned int RTM : 1; /* 11 RTM */ + unsigned int RDT_M : 1; /* 12 Intel® Resource Director Technology (Intel® RDT) Monitoring */ + unsigned int DeprecatesFPUCSDS : 1; /* 13 Deprecates FPU CS and FPU DS */ + unsigned int MPX : 1; /* 14 Intel® Memory Protection Extensions */ + unsigned int RDT_A : 1; /* 15 Intel® Resource Director Technology (Intel® RDT) Allocation */ + unsigned int AVX512F : 1; /* 16 AVX512F */ + unsigned int AVX512DQ : 1; /* 17 AVX512DQ */ + unsigned int RDSEED : 1; /* 18 RDSEED */ + unsigned int ADX : 1; /* 19 ADX */ + unsigned int SMAP : 1; /* 20 Supervisor-Mode Access Prevention */ + unsigned int AVX512_IFMA : 1; /* 21 AVX512_IFMA */ + unsigned int ReservedBits0 : 1; /* 22 Reserved */ + unsigned int CLFLUSHOPT : 1; /* 23 CLFLUSHOPT */ + unsigned int CLWB : 1; /* 24 CLWB */ + unsigned int PT : 1; /* 25 Intel Processor Trace */ + unsigned int AVX512PF : 1; /* 26 AVX512PF */ + unsigned int AVX512ER : 1; /* 27 AVX512ER */ + unsigned int AVX512CD : 1; /* 28 AVX512CD */ + unsigned int SHA : 1; /* 29 SHA */ + unsigned int AVX512BW : 1; /* 30 AVX512BW */ + unsigned int AVX512VL : 1; /* 31 AVX512VL */ + }; + /* Ecx */ + struct + { + unsigned int PREFETCHWT1 : 1; /* 00 PREFETCHWT1 */ + unsigned int AVX512_VBMI : 1; /* 01 AVX512_VBMI */ + unsigned int UMIP : 1; /* 02 User-mode instruction prevention */ + unsigned int PKU : 1; /* 03 Protection keys for user-mode pages */ + unsigned int OSPKE : 1; /* 04 CR4.PKE */ + unsigned int WAITPKG : 1; /* 05 WAITPKG */ + unsigned int AVX512_VBMI2 : 1; /* 06 AVX512_VBMI2 */ + unsigned int CET_SS : 1; /* 07 CET shadow stack */ + unsigned int GFNI : 1; /* 08 GFNI */ + unsigned int VAES : 1; /* 09 VAES */ + unsigned int VPCLMULQDQ : 1; /* 10 VPCLMULQDQ */ + unsigned int AVX512_VNNI : 1; /* 11 AVX512_VNNI */ + unsigned int AVX512_BITALG : 1; /* 12 AVX512_BITALG */ + unsigned int TME_EN : 1; /* 13 TME_EN */ + unsigned int AVX512_VPOPCNTDQ : 1; /* 14 AVX512_VPOPCNTDQ */ + unsigned int ReservedBits1 : 1; /* 15 Reserved */ + unsigned int LA57 : 1; /* 16 57-bit linear addresses and five-level paging */ + unsigned int MAWAU : 5; /* 17-21 57-bit linear addresses and five-level paging */ + unsigned int RDPID : 1; /* 22 RDPID and IA32_TSC_AUX */ + unsigned int KL : 1; /* 23 Key Locker */ + unsigned int ReservedBits2 : 1; /* 24 Reserved */ + unsigned int CLDEMOTE : 1; /* 25 Cache line demote */ + unsigned int ReservedBits3 : 1; /* 26 Reserved */ + unsigned int MOVDIRI : 1; /* 27 MOVDIRI */ + unsigned int MOVDIR64B : 1; /* 28 MOVDIR64B */ + unsigned int ENQCMD : 1; /* 29 Enqueue Stores */ + unsigned int SGX_LC : 1; /* 30 SGX Launch Configuration */ + unsigned int PKS : 1; /* 31 Protection keys for supervisor-mode pages */ + }; + /* Edx */ + struct + { + unsigned int ReservedBits4 : 1; /* 00 Reserved */ + unsigned int SGX_KEYS : 1; /* 01 Attestation Services for Intel® SGX */ + unsigned int AVX512_4VNNIW : 1; /* 02 AVX512_4VNNIW */ + unsigned int AVX512_4FMAPS : 1; /* 03 AVX512_4FMAPS */ + unsigned int FSRM : 1; /* 04 Fast Short REP MOV */ + unsigned int UINTR : 1; /* 05 User interrupts */ + unsigned int ReservedBits5 : 2; /* 06-07 Reserved */ + unsigned int AVX512_VP2INTERSECT : 1; /* 08 AVX512_VP2INTERSECT */ + unsigned int SRBDS_CTRL : 1; /* 09 SRBDS_CTRL */ + unsigned int MD_CLEAR : 1; /* 10 MD_CLEAR */ + unsigned int RTM_ALWAYS_ABORT : 1; /* 11 RTM_ALWAYS_ABORT */ + unsigned int ReservedBits6 : 1; /* 12 Reserved */ + unsigned int RTM_FORCE_ABORT : 1; /* 13 RTM_FORCE_ABORT */ + unsigned int SERIALIZE : 1; /* 14 SERIALIZE */ + unsigned int Hybrid : 1; /* 15 Hybrid */ + unsigned int TSXLDTRK : 1; /* 16 Intel TSX suspend/resume of load address tracking */ + unsigned int ReservedBits7 : 1; /* 17 Reserved */ + unsigned int PCONFIG : 1; /* 18 PCONFIG */ + unsigned int ArchitecturalLBRs : 1; /* 19 Architectural LBRs */ + unsigned int CET_IBT : 1; /* 20 CET indirect branch tracking */ + unsigned int ReservedBits8 : 1; /* 21 Reserved */ + unsigned int AMX_BF16 : 1; /* 22 Tile computational operations on bfloat16 numbers */ + unsigned int AVX512_FP16 : 1; /* 23 AVX512_FP16 */ + unsigned int AMX_TILE : 1; /* 24 Tile architecture */ + unsigned int AMX_INT8 : 1; /* 25 Tile computational operations on 8-bit integers */ + unsigned int Enum_IBRS_IBPB : 1; /* 26 Enumerates for IBRS and IBPB */ + unsigned int Enum_STIBP : 1; /* 27 Enumerates for STIBP */ + unsigned int Enum_L1D_FLUSH : 1; /* 28 Enumerates for L1D_FLUSH */ + unsigned int Enum_ARCH_CAPABILITIES : 1; /* 29 Enumerates for the IA32_ARCH_CAPABILITIES MSR */ + unsigned int Enum_CORE_CAPABILITIES : 1; /* 30 Enumerates for the IA32_CORE_CAPABILITIES MSR */ + unsigned int Enum_SSBD : 1; /* 31 Enumerates for SSBD */ + }; + } FeatureFlags; + } F07_00; + + union + { + /* 0 if the sub-leaf index, 1, is invalid */ + struct + { + unsigned int EaxValidity; + unsigned int EbxValidity; + unsigned int EcxValidity; + unsigned int EdxValidity; + }; + /* Eax, Ebx, Ecx, Edx: Feature Flags */ + struct + { + /* Eax */ + struct + { + unsigned int ReservedBits0 : 4; /* 00-03 Reserved */ + unsigned int AVX_VNNI : 1; /* 04 AVX-VNNI */ + unsigned int AVX512_BF16 : 1; /* 05 AVX512_BF16 */ + unsigned int ReservedBits1 : 4; /* 06-09 Reserved */ + unsigned int FZRM : 1; /* 10 Fast zero-length REP MOVSB */ + unsigned int FSRS : 1; /* 11 Fast short REP STOSB */ + unsigned int FSRCS : 1; /* 12 Fast short REP CMPSB/SCASB */ + unsigned int ReservedBits2 : 9; /* 13-21 Reserved */ + unsigned int HRESET : 1; /* 22 HRESET */ + unsigned int ReservedBits3 : 9; /* 23-31 Reserved */ + }; + /* Ebx */ + struct + { + unsigned int Enum_PPIN : 1; /* 00 Enumerates the presence of the IA32_PPIN and IA32_PPIN_CTL MSRs */ + unsigned int ReservedBits4 : 31; /* 01-31 Reserved */ + }; + /* Ecx */ + unsigned int ReservedBits5; + /* Edx */ + struct + { + unsigned int ReservedBits6 : 18; /* 00-17 Reserved */ + unsigned int CET_SSS : 1; /* 18 CET_SSS */ + unsigned int ReservedBits7 : 13; /* 19-31 Reserved */ + }; + }; + } F07_01; + +} CPUID_INFO, *PCPUID_INFO; diff --git a/Source/Include/KNSoft/NDK/Extension/Extension.h b/Source/Include/KNSoft/NDK/Extension/Extension.h new file mode 100644 index 0000000..599a562 --- /dev/null +++ b/Source/Include/KNSoft/NDK/Extension/Extension.h @@ -0,0 +1,78 @@ +#pragma once + +#ifdef _KNSOFT_NDK_NO_EXTENSION +#pragma message("KNSoft.NDK: Extension.h is included but _KNSOFT_NDK_NO_EXTENSION is defined.") +#endif + +#include "../NT/MinDef.h" + +// Gets equality of two value after masked +#define IS_EQUAL_MASKED(val1, val2, mask) (!(((val1) ^ (val2)) & (mask))) +// Sets or removes a flag from a combination value +#define COMBINE_FLAGS(val, uflag, bEnable) ((bEnable) ? ((val) | (uflag)) : ((val) & ~(uflag))) +// Test combined flags +#define TEST_FLAGS(val, flags) (((val) & (flags)) == (flags)) + +// Gets is the value is within the valid range of an atom +#define IS_ATOM(val) (((ULONG_PTR)(val) & 0xFFFF) > 0 && ((ULONG_PTR)(val) & 0xFFFF) < MAXINTATOM) + +#define CPU_CACHE_LINE_SIZE 64 + +#pragma region Size in bytes + +#define BYTE_BIT 8UL +#define KB_TO_BYTES(x) ((x) * 1024UL) +#define MB_TO_KB(x) ((x) * 1024UL) +#define MB_TO_BYTES(x) (KB_TO_BYTES(MB_TO_KB(x))) +#define GB_TO_MB(x) ((x) * 1024UL) +#define GB_TO_BYTES(x) (MB_TO_BYTES(GB_TO_MB(x))) +#define TB_TO_GB(x) ((x) * 1024UL) +#define TB_TO_BYTES(x) (GB_TO_BYTES(TB_TO_GB(x))) + +#if defined(_WIN64) +#define SIZE_OF_POINTER 8 +#else +#define SIZE_OF_POINTER 4 +#endif + +#pragma endregion + +#pragma region Limitations + +#define MAX_CLASSNAME_CCH 256 +#define MAX_CIDENTIFIERNAME_CCH 247 +#define MAX_ATOM_CCH 255 +#define MAX_REG_KEYNAME_CCH 255 +#define MAX_REG_VALUENAME_CCH 16383 +#define POINTER_CCH (sizeof(PVOID) * 2 + 1) +#define HEX_RGB_CCH 8 // #RRGGBB + +#pragma endregion + +#pragma region Alignments + +#define CODE_ALIGNMENT 0x10 +#define STRING_ALIGNMENT 0x4 + +#pragma endregion + +#pragma region String + +#define _STR_CCH_LEN(quote) (ARRAYSIZE(quote) - 1) + +#define ASCII_CASE_MASK 0b100000 +#define UNICODE_EOL ((DWORD)0x000A000D) +#define ANSI_EOL ((WORD)0x0A0D) + +#pragma endregion + +#pragma region Any-size array + +#define ANYSIZE_STRUCT_SIZE(structure, field, size) UFIELD_OFFSET(structure, field[size]) + +#define DEFINE_ANYSIZE_STRUCT(varName, baseType, arrayType, arraySize) struct {\ + baseType BaseType;\ + arrayType Array[(arraySize) - 1];\ +} varName + +#pragma endregion diff --git a/Source/Include/KNSoft/NDK/Extension/MSToolChain.h b/Source/Include/KNSoft/NDK/Extension/MSToolChain.h new file mode 100644 index 0000000..99ab6b1 --- /dev/null +++ b/Source/Include/KNSoft/NDK/Extension/MSToolChain.h @@ -0,0 +1,109 @@ +#pragma once + +#ifdef _KNSOFT_NDK_NO_EXTENSION_MSTOOLCHAIN +#pragma message("KNSoft.NDK: MSToolChain.h is included but _KNSOFT_NDK_NO_EXTENSION_MSTOOLCHAIN is defined.") +#endif + +#include "../NT/MinDef.h" + +#pragma region Disable Microsoft extension warnings + +// Nonstandard extension used: zero-sized array in struct/union +#pragma warning(disable: 4200) + +#pragma endregion + +#pragma region MSVC and WinSDK + +EXTERN_C_START + +extern IMAGE_DOS_HEADER __ImageBase; + +EXTERN_C_END + +#if _WIN64 +#define IS_WIN64 TRUE +#else +#define IS_WIN64 FALSE +#endif + +/* Patch _STATIC_ASSERT to avoid confusion amount static_assert, _Static_assert and C_ASSERT */ + +#undef _STATIC_ASSERT +#define _STATIC_ASSERT(expr) static_assert((expr), #expr) + +#define __A2U8(quote) u8##quote +#define _A2U8(quote) __A2U8(quote) + +#define __A2W(quote) L##quote +#define _A2W(quote) __A2W(quote) + +#define DECLSPEC_EXPORT __declspec(dllexport) +typedef unsigned __int64 QWORD, near* PQWORD, far* LPQWORD; + +// Makes a DWORD value by LOWORD and HIWORD +#define MAKEDWORD(l, h) ((DWORD)(((WORD)(((DWORD_PTR)(l)) & 0xffff)) | ((DWORD)((WORD)(((DWORD_PTR)(h)) & 0xffff))) << 16)) +#define MAKEQWORD(l, h) ((QWORD)(((DWORD)(((DWORD_PTR)(l)) & 0xffffffff)) | ((QWORD)((DWORD)(((DWORD_PTR)(h)) & 0xffffffff))) << 32)) + +#if defined(_DEBUG) && !defined(DBG) +#define DBG 1 +#endif + +#if _WIN64 +#define MSVC_VARDNAME(x) x +#define MSVC_INCLUDE_VAR(x) __pragma(comment(linker, "/include:"#x)) +#else +#define MSVC_VARDNAME(x) _##x +#define MSVC_INCLUDE_VAR(x) __pragma(comment(linker, "/include:_"#x)) +#endif + + +/* + * Initializer support + * See also: + * https://devblogs.microsoft.com/cppblog/new-compiler-warnings-for-dynamic-initialization/ + * https://learn.microsoft.com/en-us/cpp/c-runtime-library/crt-initialization + * + * ** FIXME: Not support C++ yet ** + */ + +#ifndef __cplusplus + +// Section 'section-name' is reserved for C++ dynamic initialization. +#pragma warning(error: 5247 5248) + +typedef int(__cdecl* _PIFV)(void); + +#pragma section(".CRT$XINDK", long, read) + +#define MSVC_INITIALIZER(x)\ +int __cdecl x(void);\ +__declspec(allocate(".CRT$XINDK")) _PIFV _KNSoft_NDK_Initializer_User_##x = &x;\ +MSVC_INCLUDE_VAR(_KNSoft_NDK_Initializer_User_##x)\ +int __cdecl x(void) + +#endif + +#pragma endregion + +#pragma region MSBuild + +#if defined(_M_IX86) +#define MSB_PLATFORMTARGET "x86" +#elif defined(_M_X64) +#define MSB_PLATFORMTARGET "x64" +#elif defined(_M_ARM64) +#define MSB_PLATFORMTARGET "ARM64" +#endif + +#if defined(_DEBUG) +#define MSB_CONFIGURATION "Debug" +#else +#define MSB_CONFIGURATION "Release" +#endif + +#define MSB_LIB_PATH(LibName) (MSB_PLATFORMTARGET"/"MSB_CONFIGURATION"/"##LibName) + +/* MSB_CONFIGURATIONTYPE_[EXE/DLL/LIB/UTILITY] is defined in Directory.Build.props */ + +#pragma endregion diff --git a/Source/Include/KNSoft/NDK/Extension/SMBIOS.h b/Source/Include/KNSoft/NDK/Extension/SMBIOS.h new file mode 100644 index 0000000..ef60465 --- /dev/null +++ b/Source/Include/KNSoft/NDK/Extension/SMBIOS.h @@ -0,0 +1,1526 @@ +/* + * SMBIOS Specification (https://www.dmtf.org/standards/smbios) + * + * V3.7.0 https://www.dmtf.org/sites/default/files/standards/documents/DSP0134_3.7.0.pdf + */ + +#pragma once + +#include "../NT/MinDef.h" + +typedef unsigned __int64 QWORD, near* PQWORD, far* LPQWORD; + +// nonstandard extension used: zero-sized array in struct/union +#pragma warning(disable: 4200) + +#pragma pack(push, 1) + +#pragma region Type 0: BIOS Information + +#define SMBIOS_BIOS_EXTENDEDROMSIZE_UNIT_MB 00b +#define SMBIOS_BIOS_EXTENDEDROMSIZE_UNIT_GB 01b + +#pragma endregion + +#pragma region Type 1: System Information + +#define SMBIOS_SYSTEM_WAKEUPTYPE_RESERVED ((BYTE)00h) +#define SMBIOS_SYSTEM_WAKEUPTYPE_OTHER ((BYTE)01h) +#define SMBIOS_SYSTEM_WAKEUPTYPE_UNKNOW ((BYTE)02h) +#define SMBIOS_SYSTEM_WAKEUPTYPE_APM_TIMER ((BYTE)03h) +#define SMBIOS_SYSTEM_WAKEUPTYPE_MODEM_RING ((BYTE)04h) +#define SMBIOS_SYSTEM_WAKEUPTYPE_LAN_REMOTE ((BYTE)05h) +#define SMBIOS_SYSTEM_WAKEUPTYPE_POWER_SWITCH ((BYTE)06h) +#define SMBIOS_SYSTEM_WAKEUPTYPE_PCI_PME ((BYTE)07h) +#define SMBIOS_SYSTEM_WAKEUPTYPE_AC_POWER_RESTORED ((BYTE)08h) + +#pragma endregion + +#pragma region Type 2: Baseboard Information + +#define SMBIOS_BASEBOARD_TYPE_UNKNOWN ((BYTE)01h) +#define SMBIOS_BASEBOARD_TYPE_OTHER ((BYTE)02h) +#define SMBIOS_BASEBOARD_TYPE_SERVER_BLADE ((BYTE)03h) +#define SMBIOS_BASEBOARD_TYPE_CONNECTIVITY_SWITCH ((BYTE)04h) +#define SMBIOS_BASEBOARD_TYPE_SYSTEM_MANAGEMENT_MODULE ((BYTE)05h) +#define SMBIOS_BASEBOARD_TYPE_PROCESSOR_MODULE ((BYTE)06h) +#define SMBIOS_BASEBOARD_TYPE_IO_MODULE ((BYTE)07h) +#define SMBIOS_BASEBOARD_TYPE_MEMORY_MODULE ((BYTE)08h) +#define SMBIOS_BASEBOARD_TYPE_DAUGHTER_BOARD ((BYTE)09h) +#define SMBIOS_BASEBOARD_TYPE_MOTHERBOARD ((BYTE)0Ah) +#define SMBIOS_BASEBOARD_TYPE_PROCESSOR_MEMORY_MODULE ((BYTE)0Bh) +#define SMBIOS_BASEBOARD_TYPE_PROCESSOR_IO_MODULE ((BYTE)0Ch) +#define SMBIOS_BASEBOARD_TYPE_INTERCONNECT_BOARD ((BYTE)0Dh) + +#pragma endregion + +#pragma region Type 3: System Enclosure or Chassis + +#define SMBIOS_SYSTEM_ENCLOSURE_OR_CHASSIS_TYPE_OTHER ((BYTE)01h) +#define SMBIOS_SYSTEM_ENCLOSURE_OR_CHASSIS_TYPE_UNKNOWN ((BYTE)02h) +#define SMBIOS_SYSTEM_ENCLOSURE_OR_CHASSIS_TYPE_DESKTOP ((BYTE)03h) +#define SMBIOS_SYSTEM_ENCLOSURE_OR_CHASSIS_TYPE_LOW_PROFILE_DESKTOP ((BYTE)04h) +#define SMBIOS_SYSTEM_ENCLOSURE_OR_CHASSIS_TYPE_PIZZA_BOX ((BYTE)05h) +#define SMBIOS_SYSTEM_ENCLOSURE_OR_CHASSIS_TYPE_MINI_TOWER ((BYTE)06h) +#define SMBIOS_SYSTEM_ENCLOSURE_OR_CHASSIS_TYPE_TOWER ((BYTE)07h) +#define SMBIOS_SYSTEM_ENCLOSURE_OR_CHASSIS_TYPE_PORTABLE ((BYTE)08h) +#define SMBIOS_SYSTEM_ENCLOSURE_OR_CHASSIS_TYPE_LAPTOP ((BYTE)09h) +#define SMBIOS_SYSTEM_ENCLOSURE_OR_CHASSIS_TYPE_NOTEBOOK ((BYTE)0Ah) +#define SMBIOS_SYSTEM_ENCLOSURE_OR_CHASSIS_TYPE_HAND_HELD ((BYTE)0Bh) +#define SMBIOS_SYSTEM_ENCLOSURE_OR_CHASSIS_TYPE_DOCKING_STATION ((BYTE)0Ch) +#define SMBIOS_SYSTEM_ENCLOSURE_OR_CHASSIS_TYPE_ALL_IN_ONE ((BYTE)0Dh) +#define SMBIOS_SYSTEM_ENCLOSURE_OR_CHASSIS_TYPE_SUB_NOTEBOOK ((BYTE)0Eh) +#define SMBIOS_SYSTEM_ENCLOSURE_OR_CHASSIS_TYPE_SPACE_SAVING ((BYTE)0Fh) +#define SMBIOS_SYSTEM_ENCLOSURE_OR_CHASSIS_TYPE_LUNCH_BOX ((BYTE)10h) +#define SMBIOS_SYSTEM_ENCLOSURE_OR_CHASSIS_TYPE_MAIN_SERVER_CHASSIS ((BYTE)11h) +#define SMBIOS_SYSTEM_ENCLOSURE_OR_CHASSIS_TYPE_EXPANSION_CHASSIS ((BYTE)12h) +#define SMBIOS_SYSTEM_ENCLOSURE_OR_CHASSIS_TYPE_SUB_CHASSIS ((BYTE)13h) +#define SMBIOS_SYSTEM_ENCLOSURE_OR_CHASSIS_TYPE_BUS_EXPANSION_CHASSIS ((BYTE)14h) +#define SMBIOS_SYSTEM_ENCLOSURE_OR_CHASSIS_TYPE_PERIPHERAL_CHASSIS ((BYTE)15h) +#define SMBIOS_SYSTEM_ENCLOSURE_OR_CHASSIS_TYPE_RAID_CHASSIS ((BYTE)16h) +#define SMBIOS_SYSTEM_ENCLOSURE_OR_CHASSIS_TYPE_RACK_MOUNT_CHASSIS ((BYTE)17h) +#define SMBIOS_SYSTEM_ENCLOSURE_OR_CHASSIS_TYPE_SEALED_CASE_PC ((BYTE)18h) +#define SMBIOS_SYSTEM_ENCLOSURE_OR_CHASSIS_TYPE_MULTI_SYSTEM_CHASSIS ((BYTE)19h) +#define SMBIOS_SYSTEM_ENCLOSURE_OR_CHASSIS_TYPE_COMPACT_PCI ((BYTE)1Ah) +#define SMBIOS_SYSTEM_ENCLOSURE_OR_CHASSIS_TYPE_ADVANCED_TCA ((BYTE)1Bh) +#define SMBIOS_SYSTEM_ENCLOSURE_OR_CHASSIS_TYPE_BLADE ((BYTE)1Ch) +#define SMBIOS_SYSTEM_ENCLOSURE_OR_CHASSIS_TYPE_BLADE_ENCLOSURE ((BYTE)1Dh) +#define SMBIOS_SYSTEM_ENCLOSURE_OR_CHASSIS_TYPE_TABLET ((BYTE)1Eh) +#define SMBIOS_SYSTEM_ENCLOSURE_OR_CHASSIS_TYPE_CONVERTIBLE ((BYTE)1Fh) +#define SMBIOS_SYSTEM_ENCLOSURE_OR_CHASSIS_TYPE_DETACHABLE ((BYTE)20h) +#define SMBIOS_SYSTEM_ENCLOSURE_OR_CHASSIS_TYPE_IOT_GATEWAY ((BYTE)21h) +#define SMBIOS_SYSTEM_ENCLOSURE_OR_CHASSIS_TYPE_EMBEDDED_PC ((BYTE)22h) +#define SMBIOS_SYSTEM_ENCLOSURE_OR_CHASSIS_TYPE_MINI_PC ((BYTE)23h) +#define SMBIOS_SYSTEM_ENCLOSURE_OR_CHASSIS_TYPE_STICK_PC ((BYTE)24h) + +#define SMBIOS_SYSTEM_ENCLOSURE_OR_CHASSIS_STATE_OTHER ((BYTE)01h) +#define SMBIOS_SYSTEM_ENCLOSURE_OR_CHASSIS_STATE_UNKNOWN ((BYTE)02h) +#define SMBIOS_SYSTEM_ENCLOSURE_OR_CHASSIS_STATE_SAFE ((BYTE)03h) +#define SMBIOS_SYSTEM_ENCLOSURE_OR_CHASSIS_STATE_WARNING ((BYTE)04h) +#define SMBIOS_SYSTEM_ENCLOSURE_OR_CHASSIS_STATE_CRITICAL ((BYTE)05h) +#define SMBIOS_SYSTEM_ENCLOSURE_OR_CHASSIS_STATE_NON_RECOVERABLE ((BYTE)06h) + +#define SMBIOS_SYSTEM_ENCLOSURE_OR_CHASSIS_SECURITY_STATE_OTHER ((BYTE)01h) +#define SMBIOS_SYSTEM_ENCLOSURE_OR_CHASSIS_SECURITY_STATE_UNKNOWN ((BYTE)02h) +#define SMBIOS_SYSTEM_ENCLOSURE_OR_CHASSIS_SECURITY_STATE_NONE ((BYTE)03h) +#define SMBIOS_SYSTEM_ENCLOSURE_OR_CHASSIS_SECURITY_STATE_EXTERNAL_INTERFACE_LOCKED_OUT ((BYTE)04h) +#define SMBIOS_SYSTEM_ENCLOSURE_OR_CHASSIS_SECURITY_STATE_EXTERNAL_INTERFACE_ENABLED ((BYTE)05h) + +#pragma endregion + +#pragma region Type 4: Processor Information + +#define SMBIOS_PROCESSOR_TYPE_OTHER ((BYTE)01h) +#define SMBIOS_PROCESSOR_TYPE_UNKNOWN ((BYTE)02h) +#define SMBIOS_PROCESSOR_TYPE_CENTRAL_PROCESSOR ((BYTE)03h) +#define SMBIOS_PROCESSOR_TYPE_MATH_PROCESSOR ((BYTE)04h) +#define SMBIOS_PROCESSOR_TYPE_DSP_PROCESSOR ((BYTE)05h) +#define SMBIOS_PROCESSOR_TYPE_VIDEO_PROCESSOR ((BYTE)06h) + +#define SMBIOS_PROCESSOR_UPGRADE_OTHER ((BYTE)01h) +#define SMBIOS_PROCESSOR_UPGRADE_UNKNOWN ((BYTE)02h) +#define SMBIOS_PROCESSOR_UPGRADE_DAUGHTER_BOARD ((BYTE)03h) +#define SMBIOS_PROCESSOR_UPGRADE_ZIF_SOCKET ((BYTE)04h) +#define SMBIOS_PROCESSOR_UPGRADE_REPLACEABLE_PIGGY_BACK ((BYTE)05h) +#define SMBIOS_PROCESSOR_UPGRADE_NONE ((BYTE)06h) +#define SMBIOS_PROCESSOR_UPGRADE_LIF_SOCKET ((BYTE)07h) +#define SMBIOS_PROCESSOR_UPGRADE_SLOT_1 ((BYTE)08h) +#define SMBIOS_PROCESSOR_UPGRADE_SLOT_2 ((BYTE)09h) +#define SMBIOS_PROCESSOR_UPGRADE_370_PIN_SOCKET ((BYTE)0Ah) +#define SMBIOS_PROCESSOR_UPGRADE_SLOT_A ((BYTE)0Bh) +#define SMBIOS_PROCESSOR_UPGRADE_SLOT_M ((BYTE)0Ch) +#define SMBIOS_PROCESSOR_UPGRADE_SOCKET_423 ((BYTE)0Dh) +#define SMBIOS_PROCESSOR_UPGRADE_SOCKET_A ((BYTE)0Eh) +#define SMBIOS_PROCESSOR_UPGRADE_SOCKET_478 ((BYTE)0Fh) +#define SMBIOS_PROCESSOR_UPGRADE_SOCKET_754 ((BYTE)10h) +#define SMBIOS_PROCESSOR_UPGRADE_SOCKET_940 ((BYTE)11h) +#define SMBIOS_PROCESSOR_UPGRADE_SOCKET_939 ((BYTE)12h) +#define SMBIOS_PROCESSOR_UPGRADE_SOCKET_mPGA604 ((BYTE)13h) +#define SMBIOS_PROCESSOR_UPGRADE_SOCKET_LGA771 ((BYTE)14h) +#define SMBIOS_PROCESSOR_UPGRADE_SOCKET_LGA775 ((BYTE)15h) +#define SMBIOS_PROCESSOR_UPGRADE_SOCKET_S1 ((BYTE)16h) +#define SMBIOS_PROCESSOR_UPGRADE_SOCKET_AM2 ((BYTE)17h) +#define SMBIOS_PROCESSOR_UPGRADE_SOCKET_F ((BYTE)18h) +#define SMBIOS_PROCESSOR_UPGRADE_SOCKET_LGA1366 ((BYTE)19h) +#define SMBIOS_PROCESSOR_UPGRADE_SOCKET_G34 ((BYTE)1Ah) +#define SMBIOS_PROCESSOR_UPGRADE_SOCKET_AM3 ((BYTE)1Bh) +#define SMBIOS_PROCESSOR_UPGRADE_SOCKET_C32 ((BYTE)1Ch) +#define SMBIOS_PROCESSOR_UPGRADE_SOCKET_LGA1156 ((BYTE)1Dh) +#define SMBIOS_PROCESSOR_UPGRADE_SOCKET_LGA1567 ((BYTE)1Eh) +#define SMBIOS_PROCESSOR_UPGRADE_SOCKET_PGA988A ((BYTE)1Fh) +#define SMBIOS_PROCESSOR_UPGRADE_SOCKET_BGA1288 ((BYTE)20h) +#define SMBIOS_PROCESSOR_UPGRADE_SOCKET_rPGA988B ((BYTE)21h) +#define SMBIOS_PROCESSOR_UPGRADE_SOCKET_BGA1023 ((BYTE)22h) +#define SMBIOS_PROCESSOR_UPGRADE_SOCKET_BGA1224 ((BYTE)23h) +#define SMBIOS_PROCESSOR_UPGRADE_SOCKET_LGA1155 ((BYTE)24h) +#define SMBIOS_PROCESSOR_UPGRADE_SOCKET_LGA1356 ((BYTE)25h) +#define SMBIOS_PROCESSOR_UPGRADE_SOCKET_LGA2011 ((BYTE)26h) +#define SMBIOS_PROCESSOR_UPGRADE_SOCKET_FS1 ((BYTE)27h) +#define SMBIOS_PROCESSOR_UPGRADE_SOCKET_FS2 ((BYTE)28h) +#define SMBIOS_PROCESSOR_UPGRADE_SOCKET_FM1 ((BYTE)29h) +#define SMBIOS_PROCESSOR_UPGRADE_SOCKET_FM2 ((BYTE)2Ah) +#define SMBIOS_PROCESSOR_UPGRADE_SOCKET_LGA2011_3 ((BYTE)2Bh) +#define SMBIOS_PROCESSOR_UPGRADE_SOCKET_LGA1356_3 ((BYTE)2Ch) +#define SMBIOS_PROCESSOR_UPGRADE_SOCKET_LGA1150 ((BYTE)2Dh) +#define SMBIOS_PROCESSOR_UPGRADE_SOCKET_BGA1168 ((BYTE)2Eh) +#define SMBIOS_PROCESSOR_UPGRADE_SOCKET_BGA1234 ((BYTE)2Fh) +#define SMBIOS_PROCESSOR_UPGRADE_SOCKET_BGA1364 ((BYTE)30h) +#define SMBIOS_PROCESSOR_UPGRADE_SOCKET_AM4 ((BYTE)31h) +#define SMBIOS_PROCESSOR_UPGRADE_SOCKET_LGA1151 ((BYTE)32h) +#define SMBIOS_PROCESSOR_UPGRADE_SOCKET_BGA1356 ((BYTE)33h) +#define SMBIOS_PROCESSOR_UPGRADE_SOCKET_BGA1440 ((BYTE)34h) +#define SMBIOS_PROCESSOR_UPGRADE_SOCKET_BGA1515 ((BYTE)35h) +#define SMBIOS_PROCESSOR_UPGRADE_SOCKET_LGA3647_1 ((BYTE)36h) +#define SMBIOS_PROCESSOR_UPGRADE_SOCKET_SP3 ((BYTE)37h) +#define SMBIOS_PROCESSOR_UPGRADE_SOCKET_SP3r2 ((BYTE)38h) +#define SMBIOS_PROCESSOR_UPGRADE_SOCKET_LGA2066 ((BYTE)39h) +#define SMBIOS_PROCESSOR_UPGRADE_SOCKET_BGA1392 ((BYTE)3Ah) +#define SMBIOS_PROCESSOR_UPGRADE_SOCKET_BGA1510 ((BYTE)3Bh) +#define SMBIOS_PROCESSOR_UPGRADE_SOCKET_BGA1528 ((BYTE)3Ch) +#define SMBIOS_PROCESSOR_UPGRADE_SOCKET_LGA4189 ((BYTE)3Dh) +#define SMBIOS_PROCESSOR_UPGRADE_SOCKET_LGA1200 ((BYTE)3Eh) +#define SMBIOS_PROCESSOR_UPGRADE_SOCKET_LGA4677 ((BYTE)3Fh) +#define SMBIOS_PROCESSOR_UPGRADE_SOCKET_LGA1700 ((BYTE)40h) +#define SMBIOS_PROCESSOR_UPGRADE_SOCKET_BGA1744 ((BYTE)41h) +#define SMBIOS_PROCESSOR_UPGRADE_SOCKET_BGA1781 ((BYTE)42h) +#define SMBIOS_PROCESSOR_UPGRADE_SOCKET_BGA1211 ((BYTE)43h) +#define SMBIOS_PROCESSOR_UPGRADE_SOCKET_BGA2422 ((BYTE)44h) +#define SMBIOS_PROCESSOR_UPGRADE_SOCKET_LGA1211 ((BYTE)45h) +#define SMBIOS_PROCESSOR_UPGRADE_SOCKET_LGA2422 ((BYTE)46h) +#define SMBIOS_PROCESSOR_UPGRADE_SOCKET_LGA5773 ((BYTE)47h) +#define SMBIOS_PROCESSOR_UPGRADE_SOCKET_BGA5773 ((BYTE)48h) +#define SMBIOS_PROCESSOR_UPGRADE_SOCKET_AM5 ((BYTE)49h) +#define SMBIOS_PROCESSOR_UPGRADE_SOCKET_SP5 ((BYTE)4Ah) +#define SMBIOS_PROCESSOR_UPGRADE_SOCKET_SP6 ((BYTE)4Bh) +#define SMBIOS_PROCESSOR_UPGRADE_SOCKET_BGA883 ((BYTE)4Ch) +#define SMBIOS_PROCESSOR_UPGRADE_SOCKET_BGA1190 ((BYTE)4Dh) +#define SMBIOS_PROCESSOR_UPGRADE_SOCKET_BGA4129 ((BYTE)4Eh) +#define SMBIOS_PROCESSOR_UPGRADE_SOCKET_LGA4710 ((BYTE)4Fh) +#define SMBIOS_PROCESSOR_UPGRADE_SOCKET_LGA7529 ((BYTE)50h) + +#define SMBIOS_PROCESSOR_CPU_STATUS_UNKNOWN 0h +#define SMBIOS_PROCESSOR_CPU_STATUS_ENABLED 1h +#define SMBIOS_PROCESSOR_CPU_STATUS_DISABLED_BY_USER 2h +#define SMBIOS_PROCESSOR_CPU_STATUS_DISABLED_BY_BIOS 3h +#define SMBIOS_PROCESSOR_CPU_STATUS_IDLE 4h +#define SMBIOS_PROCESSOR_CPU_STATUS_OTHER 7h + +#pragma endregion + +#pragma region Type 7: Cache Information + +#define SMBIOS_CACHE_LOCATION_INTERNAL 00b +#define SMBIOS_CACHE_LOCATION_EXTERNAL 01b +#define SMBIOS_CACHE_LOCATION_RESERVED 10b +#define SMBIOS_CACHE_LOCATION_UNKNOWN 11b + +#define SMBIOS_CACHE_OPERATIONAL_MODE_WRITE_THROUGH 00b +#define SMBIOS_CACHE_OPERATIONAL_MODE_WRITE_BACK 01b +#define SMBIOS_CACHE_OPERATIONAL_MODE_VARIES_WITH_MEMORY_ADDRESS 10b +#define SMBIOS_CACHE_OPERATIONAL_MODE_UNKNOWN 11b + +typedef struct _SMBIOS_CACHE_SRAM_TYPE +{ + WORD Other : 1; + WORD Unknown : 1; + WORD NonBurst : 1; + WORD Burst : 1; + WORD PipelineBurst : 1; + WORD Synchronous : 1; + WORD Asynchronous : 1; + WORD Reserved : 9; +} SMBIOS_CACHE_SRAM_TYPE, *PSMBIOS_CACHE_SRAM_TYPE; + +_STATIC_ASSERT(sizeof(SMBIOS_CACHE_SRAM_TYPE) == sizeof(WORD)); + +#define SMBIOS_CACHE_ERROR_CORRECTION_TYPE_OTHER ((BYTE)01h) +#define SMBIOS_CACHE_ERROR_CORRECTION_TYPE_UNKNOWN ((BYTE)02h) +#define SMBIOS_CACHE_ERROR_CORRECTION_TYPE_NONE ((BYTE)03h) +#define SMBIOS_CACHE_ERROR_CORRECTION_TYPE_PARITY ((BYTE)04h) +#define SMBIOS_CACHE_ERROR_CORRECTION_TYPE_SINGLE_BIT_ECC ((BYTE)05h) +#define SMBIOS_CACHE_ERROR_CORRECTION_TYPE_MULTI_BIT_ECC ((BYTE)06h) + +#define SMBIOS_CACHE_SYSTEM_CACHE_TYPE_OTHER ((BYTE)01h) +#define SMBIOS_CACHE_SYSTEM_CACHE_TYPE_UNKNOWN ((BYTE)02h) +#define SMBIOS_CACHE_SYSTEM_CACHE_TYPE_INSTRUCTION ((BYTE)03h) +#define SMBIOS_CACHE_SYSTEM_CACHE_TYPE_DATA ((BYTE)04h) +#define SMBIOS_CACHE_SYSTEM_CACHE_TYPE_UNIFIED ((BYTE)05h) + +#define SMBIOS_CACHE_ASSOCIATIVITY_OTHER ((BYTE)01h) +#define SMBIOS_CACHE_ASSOCIATIVITY_UNKNOWN ((BYTE)02h) +#define SMBIOS_CACHE_ASSOCIATIVITY_DIRECT_MAPPED ((BYTE)03h) +#define SMBIOS_CACHE_ASSOCIATIVITY_2_WAY_SET_ASSOCIATIVE ((BYTE)04h) +#define SMBIOS_CACHE_ASSOCIATIVITY_4_WAY_SET_ASSOCIATIVE ((BYTE)05h) +#define SMBIOS_CACHE_ASSOCIATIVITY_FULL_ASSOCIATIVE ((BYTE)06h) +#define SMBIOS_CACHE_ASSOCIATIVITY_8_WAY_SET_ASSOCIATIVE ((BYTE)07h) +#define SMBIOS_CACHE_ASSOCIATIVITY_16_WAY_SET_ASSOCIATIVE ((BYTE)08h) +#define SMBIOS_CACHE_ASSOCIATIVITY_12_WAY_SET_ASSOCIATIVE ((BYTE)09h) +#define SMBIOS_CACHE_ASSOCIATIVITY_24_WAY_SET_ASSOCIATIVE ((BYTE)0Ah) +#define SMBIOS_CACHE_ASSOCIATIVITY_32_WAY_SET_ASSOCIATIVE ((BYTE)0Bh) +#define SMBIOS_CACHE_ASSOCIATIVITY_48_WAY_SET_ASSOCIATIVE ((BYTE)0Ch) +#define SMBIOS_CACHE_ASSOCIATIVITY_64_WAY_SET_ASSOCIATIVE ((BYTE)0Dh) +#define SMBIOS_CACHE_ASSOCIATIVITY_20_WAY_SET_ASSOCIATIVE ((BYTE)0Eh) + +#pragma endregion + +#pragma region Type 8: Port Connector Information + +#define SMBIOS_PORT_CONNECTOR_TYPE_NONE ((BYTE)00h) +#define SMBIOS_PORT_CONNECTOR_TYPE_CENTRONICS ((BYTE)01h) +#define SMBIOS_PORT_CONNECTOR_TYPE_MINI_CENTRONICS ((BYTE)02h) +#define SMBIOS_PORT_CONNECTOR_TYPE_MINI_PROPRIETARY ((BYTE)03h) +#define SMBIOS_PORT_CONNECTOR_TYPE_DB_25_PIN_MALE ((BYTE)04h) +#define SMBIOS_PORT_CONNECTOR_TYPE_DB_25_PIN_FEMALE ((BYTE)05h) +#define SMBIOS_PORT_CONNECTOR_TYPE_DB_15_PIN_MALE ((BYTE)06h) +#define SMBIOS_PORT_CONNECTOR_TYPE_DB_15_PIN_FEMALE ((BYTE)07h) +#define SMBIOS_PORT_CONNECTOR_TYPE_DB_9_PIN_MALE ((BYTE)08h) +#define SMBIOS_PORT_CONNECTOR_TYPE_DB_9_PIN_FEMALE ((BYTE)09h) +#define SMBIOS_PORT_CONNECTOR_TYPE_RJ_11 ((BYTE)0Ah) +#define SMBIOS_PORT_CONNECTOR_TYPE_RJ_45 ((BYTE)0Bh) +#define SMBIOS_PORT_CONNECTOR_TYPE_50_PIN_MINISCSI ((BYTE)0Ch) +#define SMBIOS_PORT_CONNECTOR_TYPE_MINI_DIN ((BYTE)0Dh) +#define SMBIOS_PORT_CONNECTOR_TYPE_MICRO_DIN ((BYTE)0Eh) +#define SMBIOS_PORT_CONNECTOR_TYPE_PS_2 ((BYTE)0Fh) +#define SMBIOS_PORT_CONNECTOR_TYPE_INFRARED ((BYTE)10h) +#define SMBIOS_PORT_CONNECTOR_TYPE_HP_HIL ((BYTE)11h) +#define SMBIOS_PORT_CONNECTOR_TYPE_ACCESS_BUS ((BYTE)12h) +#define SMBIOS_PORT_CONNECTOR_TYPE_SSA_SCSI ((BYTE)13h) +#define SMBIOS_PORT_CONNECTOR_TYPE_CIRCULAR_DIN_8_MALE ((BYTE)14h) +#define SMBIOS_PORT_CONNECTOR_TYPE_CIRCULAR_DIN_8_FEMALE ((BYTE)15h) +#define SMBIOS_PORT_CONNECTOR_TYPE_ON_BOARD_IDE ((BYTE)16h) +#define SMBIOS_PORT_CONNECTOR_TYPE_ON_BOARD_FLOPPY ((BYTE)17h) +#define SMBIOS_PORT_CONNECTOR_TYPE_9_PIN_DUAL_INLINE ((BYTE)18h) +#define SMBIOS_PORT_CONNECTOR_TYPE_25_PIN_DUAL_INLINE ((BYTE)19h) +#define SMBIOS_PORT_CONNECTOR_TYPE_50_PIN_DUAL_INLINE ((BYTE)1Ah) +#define SMBIOS_PORT_CONNECTOR_TYPE_68_PIN_DUAL_INLINE ((BYTE)1Bh) +#define SMBIOS_PORT_CONNECTOR_TYPE_ON_BOARD_SOUND_INPUT_FROM_CD_ROM ((BYTE)1Ch) +#define SMBIOS_PORT_CONNECTOR_TYPE_MINI_CENTRONICS_TYPE_14 ((BYTE)1Dh) +#define SMBIOS_PORT_CONNECTOR_TYPE_MINI_CENTRONICS_TYPE_26 ((BYTE)1Eh) +#define SMBIOS_PORT_CONNECTOR_TYPE_MINI_JACK ((BYTE)1Fh) +#define SMBIOS_PORT_CONNECTOR_TYPE_BNC ((BYTE)20h) +#define SMBIOS_PORT_CONNECTOR_TYPE_1394 ((BYTE)21h) +#define SMBIOS_PORT_CONNECTOR_TYPE_SAS_SATA_PLUG_RECEPTACLE ((BYTE)22h) +#define SMBIOS_PORT_CONNECTOR_TYPE_USB_TYPE_C_RECEPTACLE ((BYTE)23h) +#define SMBIOS_PORT_CONNECTOR_TYPE_PC_98 ((BYTE)A0h) +#define SMBIOS_PORT_CONNECTOR_TYPE_PC_98HIRESO ((BYTE)A1h) +#define SMBIOS_PORT_CONNECTOR_TYPE_PC_H98 ((BYTE)A2h) +#define SMBIOS_PORT_CONNECTOR_TYPE_PC_98NOTE ((BYTE)A3h) +#define SMBIOS_PORT_CONNECTOR_TYPE_PC_98FULL ((BYTE)A4h) + +#pragma endregion + +#pragma region Type 9: System Slots + +#define SMBIOS_SYSTEM_SLOTS_TYPE_OTHER ((BYTE)01h) +#define SMBIOS_SYSTEM_SLOTS_TYPE_UNKNOWN ((BYTE)02h) +#define SMBIOS_SYSTEM_SLOTS_TYPE_ISA ((BYTE)03h) +#define SMBIOS_SYSTEM_SLOTS_TYPE_MCA ((BYTE)04h) +#define SMBIOS_SYSTEM_SLOTS_TYPE_EISA ((BYTE)05h) +#define SMBIOS_SYSTEM_SLOTS_TYPE_PCI ((BYTE)06h) +#define SMBIOS_SYSTEM_SLOTS_TYPE_PC_CARD ((BYTE)07h) +#define SMBIOS_SYSTEM_SLOTS_TYPE_VL_VESA ((BYTE)08h) +#define SMBIOS_SYSTEM_SLOTS_TYPE_PROPRIETARY ((BYTE)09h) +#define SMBIOS_SYSTEM_SLOTS_TYPE_PROCESSOR_CARD_SLOT ((BYTE)0Ah) +#define SMBIOS_SYSTEM_SLOTS_TYPE_PROPRIETARY_MEMORY_CARD_SLOT ((BYTE)0Bh) +#define SMBIOS_SYSTEM_SLOTS_TYPE_IO_RISER_CARD_SLOT ((BYTE)0Ch) +#define SMBIOS_SYSTEM_SLOTS_TYPE_NUBUS ((BYTE)0Dh) +#define SMBIOS_SYSTEM_SLOTS_TYPE_PCI_66MHZ_CAPABLE ((BYTE)0Eh) +#define SMBIOS_SYSTEM_SLOTS_TYPE_AGP ((BYTE)0Fh) +#define SMBIOS_SYSTEM_SLOTS_TYPE_AGP_2X ((BYTE)10h) +#define SMBIOS_SYSTEM_SLOTS_TYPE_AGP_4X ((BYTE)11h) +#define SMBIOS_SYSTEM_SLOTS_TYPE_PCI_X ((BYTE)12h) +#define SMBIOS_SYSTEM_SLOTS_TYPE_AGP_8X ((BYTE)13h) +#define SMBIOS_SYSTEM_SLOTS_TYPE_M2_SOCKET_1_DP ((BYTE)14h) +#define SMBIOS_SYSTEM_SLOTS_TYPE_M2_SOCKET_1_SD ((BYTE)15h) +#define SMBIOS_SYSTEM_SLOTS_TYPE_M2_SOCKET_2 ((BYTE)16h) +#define SMBIOS_SYSTEM_SLOTS_TYPE_M2_SOCKET_3 ((BYTE)17h) +#define SMBIOS_SYSTEM_SLOTS_TYPE_M2_SOCKET_MXM_TYPE_I ((BYTE)18h) +#define SMBIOS_SYSTEM_SLOTS_TYPE_M2_SOCKET_MXM_TYPE_II ((BYTE)19h) +#define SMBIOS_SYSTEM_SLOTS_TYPE_M2_SOCKET_MXM_TYPE_III_STANDARD ((BYTE)1Ah) +#define SMBIOS_SYSTEM_SLOTS_TYPE_M2_SOCKET_MXM_TYPE_III_HE ((BYTE)1Bh) +#define SMBIOS_SYSTEM_SLOTS_TYPE_M2_SOCKET_MXM_TYPE_IV ((BYTE)1Ch) +#define SMBIOS_SYSTEM_SLOTS_TYPE_M2_SOCKET_MXM_3_TYPE_A ((BYTE)1Dh) +#define SMBIOS_SYSTEM_SLOTS_TYPE_M2_SOCKET_MXM_3_TYPE_B ((BYTE)1Eh) +#define SMBIOS_SYSTEM_SLOTS_TYPE_PCI_EXPRESS_GEN_2_SFF_8639 ((BYTE)1Fh) +#define SMBIOS_SYSTEM_SLOTS_TYPE_PCI_EXPRESS_GEN_3_SFF_8639 ((BYTE)20h) +#define SMBIOS_SYSTEM_SLOTS_TYPE_PCI_EXPRESS_MINI_52_PIN_WITH_BOTTOM_SIDE_KEEP_OUTS ((BYTE)21h) +#define SMBIOS_SYSTEM_SLOTS_TYPE_PCI_EXPRESS_MINI_52_PIN_WITHOUT_BOTTOM_SIDE_KEEP_OUTS ((BYTE)22h) +#define SMBIOS_SYSTEM_SLOTS_TYPE_PCI_EXPRESS_MINI_76_PIN ((BYTE)23h) +#define SMBIOS_SYSTEM_SLOTS_TYPE_PCI_EXPRESS_GEN_4_SFF_8639 ((BYTE)24h) +#define SMBIOS_SYSTEM_SLOTS_TYPE_PCI_EXPRESS_GEN_5_SFF_8639 ((BYTE)25h) +#define SMBIOS_SYSTEM_SLOTS_TYPE_OCP_NIC_3_SFF ((BYTE)26h) +#define SMBIOS_SYSTEM_SLOTS_TYPE_OCP_NIC_3_LFF ((BYTE)27h) +#define SMBIOS_SYSTEM_SLOTS_TYPE_OCP_NIC_PRIOR_TO_3 ((BYTE)28h) +#define SMBIOS_SYSTEM_SLOTS_TYPE_CXL_FLEXBUS_1 ((BYTE)30h) +#define SMBIOS_SYSTEM_SLOTS_TYPE_PC_98_C20 ((BYTE)A0h) +#define SMBIOS_SYSTEM_SLOTS_TYPE_PC_98_C24 ((BYTE)A1h) +#define SMBIOS_SYSTEM_SLOTS_TYPE_PC_98_E ((BYTE)A2h) +#define SMBIOS_SYSTEM_SLOTS_TYPE_PC_98_LOCAL_BUS ((BYTE)A3h) +#define SMBIOS_SYSTEM_SLOTS_TYPE_PC_98_CARD ((BYTE)A4h) +#define SMBIOS_SYSTEM_SLOTS_TYPE_PCI_EXPRESS ((BYTE)A5h) +#define SMBIOS_SYSTEM_SLOTS_TYPE_PCI_EXPRESS_X1 ((BYTE)A6h) +#define SMBIOS_SYSTEM_SLOTS_TYPE_PCI_EXPRESS_X2 ((BYTE)A7h) +#define SMBIOS_SYSTEM_SLOTS_TYPE_PCI_EXPRESS_X4 ((BYTE)A8h) +#define SMBIOS_SYSTEM_SLOTS_TYPE_PCI_EXPRESS_X8 ((BYTE)A9h) +#define SMBIOS_SYSTEM_SLOTS_TYPE_PCI_EXPRESS_X16 ((BYTE)AAh) +#define SMBIOS_SYSTEM_SLOTS_TYPE_PCI_EXPRESS_GEN_2 ((BYTE)ABh) +#define SMBIOS_SYSTEM_SLOTS_TYPE_PCI_EXPRESS_GEN_2_X1 ((BYTE)ACh) +#define SMBIOS_SYSTEM_SLOTS_TYPE_PCI_EXPRESS_GEN_2_X2 ((BYTE)ADh) +#define SMBIOS_SYSTEM_SLOTS_TYPE_PCI_EXPRESS_GEN_2_X4 ((BYTE)AEh) +#define SMBIOS_SYSTEM_SLOTS_TYPE_PCI_EXPRESS_GEN_2_X8 ((BYTE)AFh) +#define SMBIOS_SYSTEM_SLOTS_TYPE_PCI_EXPRESS_GEN_2_X16 ((BYTE)B0h) +#define SMBIOS_SYSTEM_SLOTS_TYPE_PCI_EXPRESS_GEN_3 ((BYTE)B1h) +#define SMBIOS_SYSTEM_SLOTS_TYPE_PCI_EXPRESS_GEN_3_X1 ((BYTE)B2h) +#define SMBIOS_SYSTEM_SLOTS_TYPE_PCI_EXPRESS_GEN_3_X2 ((BYTE)B3h) +#define SMBIOS_SYSTEM_SLOTS_TYPE_PCI_EXPRESS_GEN_3_X4 ((BYTE)B4h) +#define SMBIOS_SYSTEM_SLOTS_TYPE_PCI_EXPRESS_GEN_3_X8 ((BYTE)B5h) +#define SMBIOS_SYSTEM_SLOTS_TYPE_PCI_EXPRESS_GEN_3_X16 ((BYTE)B6h) +#define SMBIOS_SYSTEM_SLOTS_TYPE_PCI_EXPRESS_GEN_4 ((BYTE)B8h) +#define SMBIOS_SYSTEM_SLOTS_TYPE_PCI_EXPRESS_GEN_4_X1 ((BYTE)B9h) +#define SMBIOS_SYSTEM_SLOTS_TYPE_PCI_EXPRESS_GEN_4_X2 ((BYTE)BAh) +#define SMBIOS_SYSTEM_SLOTS_TYPE_PCI_EXPRESS_GEN_4_X4 ((BYTE)BBh) +#define SMBIOS_SYSTEM_SLOTS_TYPE_PCI_EXPRESS_GEN_4_X8 ((BYTE)BCh) +#define SMBIOS_SYSTEM_SLOTS_TYPE_PCI_EXPRESS_GEN_4_X16 ((BYTE)BDh) +#define SMBIOS_SYSTEM_SLOTS_TYPE_PCI_EXPRESS_GEN_5 ((BYTE)BEh) +#define SMBIOS_SYSTEM_SLOTS_TYPE_PCI_EXPRESS_GEN_5_X1 ((BYTE)BFh) +#define SMBIOS_SYSTEM_SLOTS_TYPE_PCI_EXPRESS_GEN_5_X2 ((BYTE)C0h) +#define SMBIOS_SYSTEM_SLOTS_TYPE_PCI_EXPRESS_GEN_5_X4 ((BYTE)C1h) +#define SMBIOS_SYSTEM_SLOTS_TYPE_PCI_EXPRESS_GEN_5_X8 ((BYTE)C2h) +#define SMBIOS_SYSTEM_SLOTS_TYPE_PCI_EXPRESS_GEN_5_X16 ((BYTE)C3h) +#define SMBIOS_SYSTEM_SLOTS_TYPE_PCI_EXPRESS_GEN_6_AND_BEYOND ((BYTE)C4h) +#define SMBIOS_SYSTEM_SLOTS_TYPE_EDSFF_E1S_E1L ((BYTE)C5h) +#define SMBIOS_SYSTEM_SLOTS_TYPE_EDSFF_E3S_E3L ((BYTE)C6h) + +#define SMBIOS_SYSTEM_SLOTS_DATA_BUS_WIDTH_OTHER ((BYTE)01h) +#define SMBIOS_SYSTEM_SLOTS_DATA_BUS_WIDTH_UNKNOWN ((BYTE)02h) +#define SMBIOS_SYSTEM_SLOTS_DATA_BUS_WIDTH_8_BIT ((BYTE)03h) +#define SMBIOS_SYSTEM_SLOTS_DATA_BUS_WIDTH_16_BIT ((BYTE)04h) +#define SMBIOS_SYSTEM_SLOTS_DATA_BUS_WIDTH_32_BIT ((BYTE)05h) +#define SMBIOS_SYSTEM_SLOTS_DATA_BUS_WIDTH_64_BIT ((BYTE)06h) +#define SMBIOS_SYSTEM_SLOTS_DATA_BUS_WIDTH_128_BIT ((BYTE)07h) +#define SMBIOS_SYSTEM_SLOTS_DATA_BUS_WIDTH_1X ((BYTE)08h) +#define SMBIOS_SYSTEM_SLOTS_DATA_BUS_WIDTH_2X ((BYTE)09h) +#define SMBIOS_SYSTEM_SLOTS_DATA_BUS_WIDTH_4X ((BYTE)0Ah) +#define SMBIOS_SYSTEM_SLOTS_DATA_BUS_WIDTH_8X ((BYTE)0Bh) +#define SMBIOS_SYSTEM_SLOTS_DATA_BUS_WIDTH_12X ((BYTE)0Ch) +#define SMBIOS_SYSTEM_SLOTS_DATA_BUS_WIDTH_16X ((BYTE)0Dh) +#define SMBIOS_SYSTEM_SLOTS_DATA_BUS_WIDTH_32X ((BYTE)0Eh) + +#define SMBIOS_SYSTEM_SLOTS_CURRENT_USAGE_OTHER ((BYTE)01h) +#define SMBIOS_SYSTEM_SLOTS_CURRENT_USAGE_UNKNOWN ((BYTE)02h) +#define SMBIOS_SYSTEM_SLOTS_CURRENT_USAGE_AVAILABLE ((BYTE)03h) +#define SMBIOS_SYSTEM_SLOTS_CURRENT_USAGE_IN_USE ((BYTE)04h) +#define SMBIOS_SYSTEM_SLOTS_CURRENT_USAGE_UNAVAILABLE ((BYTE)05h) + +#define SMBIOS_SYSTEM_SLOTS_LENGTH_OTHER ((BYTE)01h) +#define SMBIOS_SYSTEM_SLOTS_LENGTH_UNKNOWN ((BYTE)02h) +#define SMBIOS_SYSTEM_SLOTS_LENGTH_SHORT ((BYTE)03h) +#define SMBIOS_SYSTEM_SLOTS_LENGTH_LONG ((BYTE)04h) +#define SMBIOS_SYSTEM_SLOTS_LENGTH_2DOT5_INCH_DRIVE_FORM_FACTOR ((BYTE)05h) +#define SMBIOS_SYSTEM_SLOTS_LENGTH_3DOT5_INCH_DRIVE_FORM_FACTOR ((BYTE)06h) + +#pragma endregion + +#pragma region Type 10: On Board Devices Information (Obsolete) + +#define SMBIOS_ONBOARD_DEVICES_TYPE_OTHER ((BYTE)01h) +#define SMBIOS_ONBOARD_DEVICES_TYPE_UNKNOWN ((BYTE)02h) +#define SMBIOS_ONBOARD_DEVICES_TYPE_VIDEO ((BYTE)03h) +#define SMBIOS_ONBOARD_DEVICES_TYPE_SCSI_CONTROLLER ((BYTE)04h) +#define SMBIOS_ONBOARD_DEVICES_TYPE_ETHERNET ((BYTE)05h) +#define SMBIOS_ONBOARD_DEVICES_TYPE_TOKEN_RING ((BYTE)06h) +#define SMBIOS_ONBOARD_DEVICES_TYPE_SOUND ((BYTE)07h) +#define SMBIOS_ONBOARD_DEVICES_TYPE_PATA_CONTROLLER ((BYTE)08h) +#define SMBIOS_ONBOARD_DEVICES_TYPE_SATA_CONTROLLER ((BYTE)09h) +#define SMBIOS_ONBOARD_DEVICES_TYPE_SAS_CONTROLLER ((BYTE)0Ah) + +#pragma endregion + +#pragma region Type 16: Physical Memory Array + +#define SMBIOS_PHYSICAL_MEMORY_ARRAY_LOCATION_OTHER ((BYTE)01h) +#define SMBIOS_PHYSICAL_MEMORY_ARRAY_LOCATION_UNKNOWN ((BYTE)02h) +#define SMBIOS_PHYSICAL_MEMORY_ARRAY_LOCATION_SYSTEM_BOARD_OR_MOTHERBOARD ((BYTE)03h) +#define SMBIOS_PHYSICAL_MEMORY_ARRAY_LOCATION_ISA_ADD_ON_CARD ((BYTE)04h) +#define SMBIOS_PHYSICAL_MEMORY_ARRAY_LOCATION_EISA_ADD_ON_CARD ((BYTE)05h) +#define SMBIOS_PHYSICAL_MEMORY_ARRAY_LOCATION_PCI_ADD_ON_CARD ((BYTE)06h) +#define SMBIOS_PHYSICAL_MEMORY_ARRAY_LOCATION_MCA_ADD_ON_CARD ((BYTE)07h) +#define SMBIOS_PHYSICAL_MEMORY_ARRAY_LOCATION_PCMCIA_ADD_ON_CARD ((BYTE)08h) +#define SMBIOS_PHYSICAL_MEMORY_ARRAY_LOCATION_PROPRIETARY_ADD_ON_CARD ((BYTE)09h) +#define SMBIOS_PHYSICAL_MEMORY_ARRAY_LOCATION_NUBUS ((BYTE)0Ah) +#define SMBIOS_PHYSICAL_MEMORY_ARRAY_LOCATION_PC_98_C20_ADD_ON_CARD ((BYTE)A0h) +#define SMBIOS_PHYSICAL_MEMORY_ARRAY_LOCATION_PC_98_C24_ADD_ON_CARD ((BYTE)A1h) +#define SMBIOS_PHYSICAL_MEMORY_ARRAY_LOCATION_PC_98_E_ADD_ON_CARD ((BYTE)A2h) +#define SMBIOS_PHYSICAL_MEMORY_ARRAY_LOCATION_PC_98_LOCAL_BUS_ADD_ON_CARD ((BYTE)A3h) +#define SMBIOS_PHYSICAL_MEMORY_ARRAY_LOCATION_CXL_ADD_ON_CARD ((BYTE)A4h) + +#define SMBIOS_PHYSICAL_MEMORY_ARRAY_USE_OTHER ((BYTE)01h) +#define SMBIOS_PHYSICAL_MEMORY_ARRAY_USE_UNKNOWN ((BYTE)02h) +#define SMBIOS_PHYSICAL_MEMORY_ARRAY_USE_SYSTEM_MEMORY ((BYTE)03h) +#define SMBIOS_PHYSICAL_MEMORY_ARRAY_USE_VIDEO_MEMORY ((BYTE)04h) +#define SMBIOS_PHYSICAL_MEMORY_ARRAY_USE_FLASH_MEMORY ((BYTE)05h) +#define SMBIOS_PHYSICAL_MEMORY_ARRAY_USE_NON_VOLATILE_RAM ((BYTE)06h) +#define SMBIOS_PHYSICAL_MEMORY_ARRAY_USE_CACHE_MEMORY ((BYTE)07h) + +#define SMBIOS_PHYSICAL_MEMORY_ARRAY_ERROR_CORRECTION_TYPE_OTHER ((BYTE)01h) +#define SMBIOS_PHYSICAL_MEMORY_ARRAY_ERROR_CORRECTION_TYPE_UNKNOWN ((BYTE)02h) +#define SMBIOS_PHYSICAL_MEMORY_ARRAY_ERROR_CORRECTION_TYPE_NONE ((BYTE)03h) +#define SMBIOS_PHYSICAL_MEMORY_ARRAY_ERROR_CORRECTION_TYPE_PARITY ((BYTE)04h) +#define SMBIOS_PHYSICAL_MEMORY_ARRAY_ERROR_CORRECTION_TYPE_SINGLE_BIT_ECC ((BYTE)05h) +#define SMBIOS_PHYSICAL_MEMORY_ARRAY_ERROR_CORRECTION_TYPE_MULTI_BIT_ECC ((BYTE)06h) +#define SMBIOS_PHYSICAL_MEMORY_ARRAY_ERROR_CORRECTION_TYPE_CRC ((BYTE)07h) + +#pragma endregion + +#pragma region Type 17: Memory Device + +#define SMBIOS_MEMORY_DEVICE_FORM_FACTOR_OTHER ((BYTE)01h) +#define SMBIOS_MEMORY_DEVICE_FORM_FACTOR_UNKNOWN ((BYTE)02h) +#define SMBIOS_MEMORY_DEVICE_FORM_FACTOR_SIMM ((BYTE)03h) +#define SMBIOS_MEMORY_DEVICE_FORM_FACTOR_SIP ((BYTE)04h) +#define SMBIOS_MEMORY_DEVICE_FORM_FACTOR_CHIP ((BYTE)05h) +#define SMBIOS_MEMORY_DEVICE_FORM_FACTOR_DIP ((BYTE)06h) +#define SMBIOS_MEMORY_DEVICE_FORM_FACTOR_ZIP ((BYTE)07h) +#define SMBIOS_MEMORY_DEVICE_FORM_FACTOR_PROPRIETARY_CARD ((BYTE)08h) +#define SMBIOS_MEMORY_DEVICE_FORM_FACTOR_DIMM ((BYTE)09h) +#define SMBIOS_MEMORY_DEVICE_FORM_FACTOR_TSOP ((BYTE)0Ah) +#define SMBIOS_MEMORY_DEVICE_FORM_FACTOR_ROW_OF_CHIPS ((BYTE)0Bh) +#define SMBIOS_MEMORY_DEVICE_FORM_FACTOR_RIMM ((BYTE)0Ch) +#define SMBIOS_MEMORY_DEVICE_FORM_FACTOR_SODIMM ((BYTE)0Dh) +#define SMBIOS_MEMORY_DEVICE_FORM_FACTOR_SRIMM ((BYTE)0Eh) +#define SMBIOS_MEMORY_DEVICE_FORM_FACTOR_FB_DIMM ((BYTE)0Fh) +#define SMBIOS_MEMORY_DEVICE_FORM_FACTOR_DIE ((BYTE)10h) + +#define SMBIOS_MEMORY_DEVICE_TYPE_OTHER ((BYTE)01h) +#define SMBIOS_MEMORY_DEVICE_TYPE_UNKNOWN ((BYTE)02h) +#define SMBIOS_MEMORY_DEVICE_TYPE_DRAM ((BYTE)03h) +#define SMBIOS_MEMORY_DEVICE_TYPE_EDRAM ((BYTE)04h) +#define SMBIOS_MEMORY_DEVICE_TYPE_VRAM ((BYTE)05h) +#define SMBIOS_MEMORY_DEVICE_TYPE_SRAM ((BYTE)06h) +#define SMBIOS_MEMORY_DEVICE_TYPE_RAM ((BYTE)07h) +#define SMBIOS_MEMORY_DEVICE_TYPE_ROM ((BYTE)08h) +#define SMBIOS_MEMORY_DEVICE_TYPE_FLASH ((BYTE)09h) +#define SMBIOS_MEMORY_DEVICE_TYPE_EEPROM ((BYTE)0Ah) +#define SMBIOS_MEMORY_DEVICE_TYPE_FEPROM ((BYTE)0Bh) +#define SMBIOS_MEMORY_DEVICE_TYPE_EPROM ((BYTE)0Ch) +#define SMBIOS_MEMORY_DEVICE_TYPE_CDRAM ((BYTE)0Dh) +#define SMBIOS_MEMORY_DEVICE_TYPE_3DRAM ((BYTE)0Eh) +#define SMBIOS_MEMORY_DEVICE_TYPE_SDRAM ((BYTE)0Fh) +#define SMBIOS_MEMORY_DEVICE_TYPE_SGRAM ((BYTE)10h) +#define SMBIOS_MEMORY_DEVICE_TYPE_RDRAM ((BYTE)11h) +#define SMBIOS_MEMORY_DEVICE_TYPE_DDR ((BYTE)12h) +#define SMBIOS_MEMORY_DEVICE_TYPE_DDR2 ((BYTE)13h) +#define SMBIOS_MEMORY_DEVICE_TYPE_DDR2_FB_DIMM ((BYTE)14h) +#define SMBIOS_MEMORY_DEVICE_TYPE_DDR3 ((BYTE)18h) +#define SMBIOS_MEMORY_DEVICE_TYPE_FBD2 ((BYTE)19h) +#define SMBIOS_MEMORY_DEVICE_TYPE_DDR4 ((BYTE)1Ah) +#define SMBIOS_MEMORY_DEVICE_TYPE_LPDDR ((BYTE)1Bh) +#define SMBIOS_MEMORY_DEVICE_TYPE_LPDDR2 ((BYTE)1Ch) +#define SMBIOS_MEMORY_DEVICE_TYPE_LPDDR3 ((BYTE)1Dh) +#define SMBIOS_MEMORY_DEVICE_TYPE_LPDDR4 ((BYTE)1Eh) +#define SMBIOS_MEMORY_DEVICE_TYPE_LOGICAL_NON_VOLATILE_DEVICE ((BYTE)1Fh) +#define SMBIOS_MEMORY_DEVICE_TYPE_HBM ((BYTE)20h) +#define SMBIOS_MEMORY_DEVICE_TYPE_HBM2 ((BYTE)21h) +#define SMBIOS_MEMORY_DEVICE_TYPE_DDR5 ((BYTE)22h) +#define SMBIOS_MEMORY_DEVICE_TYPE_LPDDR5 ((BYTE)23h) +#define SMBIOS_MEMORY_DEVICE_TYPE_HBM3 ((BYTE)24h) + +#define SMBIOS_MEMORY_DEVICE_TECHNOLOGY_OTHER ((BYTE)01h) +#define SMBIOS_MEMORY_DEVICE_TECHNOLOGY_UNKNOWN ((BYTE)02h) +#define SMBIOS_MEMORY_DEVICE_TECHNOLOGY_DRAM ((BYTE)03h) +#define SMBIOS_MEMORY_DEVICE_TECHNOLOGY_NVDIMM_N ((BYTE)04h) +#define SMBIOS_MEMORY_DEVICE_TECHNOLOGY_NVDIMM_F ((BYTE)05h) +#define SMBIOS_MEMORY_DEVICE_TECHNOLOGY_NVDIMM_P ((BYTE)06h) +#define SMBIOS_MEMORY_DEVICE_TECHNOLOGY_INTEL_OPTANE_PERSISTENT_MEMORY ((BYTE)07h) + +#pragma endregion + +#pragma region Type 23: System Reset + +#define SMBIOS_SYSTEM_RESET_BOOT_OPTION_RESERVED 00b +#define SMBIOS_SYSTEM_RESET_BOOT_OPTION_OPERATING_SYSTEM 01b +#define SMBIOS_SYSTEM_RESET_BOOT_OPTION_SYSTEM_UTILITIES 10b +#define SMBIOS_SYSTEM_RESET_BOOT_OPTION_DO_NOT_REBOOT 11b + +#pragma endregion + +#pragma region Type 24: Hardware Security + +#define SMBIOS_HARDWARE_SECURITY_SETTINGS_STATUS_DISABLED 00b +#define SMBIOS_HARDWARE_SECURITY_SETTINGS_STATUS_ENABLED 01b +#define SMBIOS_HARDWARE_SECURITY_SETTINGS_STATUS_NOT_IMPLEMENTED 10b +#define SMBIOS_HARDWARE_SECURITY_SETTINGS_STATUS_UNKNOWN 11b + +#pragma endregion + +#pragma region Type 26: Voltage Probe + +#define SMBIOS_VOLTAGE_PROBE_LOCATION_OTHER 00001b +#define SMBIOS_VOLTAGE_PROBE_LOCATION_UNKNOWN 00010b +#define SMBIOS_VOLTAGE_PROBE_LOCATION_PROCESSOR 00011b +#define SMBIOS_VOLTAGE_PROBE_LOCATION_DISK 00100b +#define SMBIOS_VOLTAGE_PROBE_LOCATION_PERIPHERAL_BAY 00101b +#define SMBIOS_VOLTAGE_PROBE_LOCATION_SYSTEM_MANAGEMENT_MODULE 00110b +#define SMBIOS_VOLTAGE_PROBE_LOCATION_MOTHERBOARD 00111b +#define SMBIOS_VOLTAGE_PROBE_LOCATION_MEMORY_MODULE 01000b +#define SMBIOS_VOLTAGE_PROBE_LOCATION_PROCESSOR_MODULE 01001b +#define SMBIOS_VOLTAGE_PROBE_LOCATION_POWER_UNIT 01010b +#define SMBIOS_VOLTAGE_PROBE_LOCATION_ADD_IN_CARD 01011b + +#define SMBIOS_VOLTAGE_PROBE_STATUS_OTHER 001b +#define SMBIOS_VOLTAGE_PROBE_STATUS_UNKNOWN 010b +#define SMBIOS_VOLTAGE_PROBE_STATUS_OK 011b +#define SMBIOS_VOLTAGE_PROBE_STATUS_NON_CRITICAL 100b +#define SMBIOS_VOLTAGE_PROBE_STATUS_CRITICAL 101b +#define SMBIOS_VOLTAGE_PROBE_STATUS_NON_RECOVERABLE 110b + +#pragma endregion + +#pragma region Type 27: Cooling Device + +#define SMBIOS_COOLING_DEVICE_TYPE_FAN 00011b +#define SMBIOS_COOLING_DEVICE_TYPE_CENTRIFUGAL_BLOWER 00100b +#define SMBIOS_COOLING_DEVICE_TYPE_CHIP_FAN 00101b +#define SMBIOS_COOLING_DEVICE_TYPE_CABINET_FAN 00110b +#define SMBIOS_COOLING_DEVICE_TYPE_POWER_SUPPLY_FAN 00111b +#define SMBIOS_COOLING_DEVICE_TYPE_HEAT_PIPE 01000b +#define SMBIOS_COOLING_DEVICE_TYPE_INTEGRATED_REFRIGERATION 01001b +#define SMBIOS_COOLING_DEVICE_TYPE_ACTIVE_COOLING 10000b +#define SMBIOS_COOLING_DEVICE_TYPE_PASSIVE_COOLING 10001b + +#define SMBIOS_COOLING_DEVICE_STATUS_OTHER 001b +#define SMBIOS_COOLING_DEVICE_STATUS_UNKNOWN 010b +#define SMBIOS_COOLING_DEVICE_STATUS_OK 011b +#define SMBIOS_COOLING_DEVICE_STATUS_NON_CRITICAL 100b +#define SMBIOS_COOLING_DEVICE_STATUS_CRITICAL 101b +#define SMBIOS_COOLING_DEVICE_STATUS_NON_RECOVERABLE 110b + +#pragma endregion + +#pragma region Type 28: Temperature Probe + +#define SMBIOS_TEMPERATURE_PROBE_LOCATION_OTHER 00001b +#define SMBIOS_TEMPERATURE_PROBE_LOCATION_UNKNOWN 00010b +#define SMBIOS_TEMPERATURE_PROBE_LOCATION_PROCESSOR 00011b +#define SMBIOS_TEMPERATURE_PROBE_LOCATION_DISK 00100b +#define SMBIOS_TEMPERATURE_PROBE_LOCATION_PERIPHERAL_BAY 00101b +#define SMBIOS_TEMPERATURE_PROBE_LOCATION_SYSTEM_MANAGEMENT_MODULE 00110b +#define SMBIOS_TEMPERATURE_PROBE_LOCATION_MOTHERBOARD 00111b +#define SMBIOS_TEMPERATURE_PROBE_LOCATION_MEMORY_MODULE 01000b +#define SMBIOS_TEMPERATURE_PROBE_LOCATION_PROCESSOR_MODULE 01001b +#define SMBIOS_TEMPERATURE_PROBE_LOCATION_POWER_UNIT 01010b +#define SMBIOS_TEMPERATURE_PROBE_LOCATION_ADD_IN_CARD 01011b +#define SMBIOS_TEMPERATURE_PROBE_LOCATION_FRONT_PANEL_BOARD 01100b +#define SMBIOS_TEMPERATURE_PROBE_LOCATION_BACK_PANEL_BOARD 01101b +#define SMBIOS_TEMPERATURE_PROBE_LOCATION_POWER_SYSTEM_BOARD 01110b +#define SMBIOS_TEMPERATURE_PROBE_LOCATION_DRIVE_BACK_PLANE 01111b + +#define SMBIOS_TEMPERATURE_PROBE_STATUS_OTHER 001b +#define SMBIOS_TEMPERATURE_PROBE_STATUS_UNKNOWN 010b +#define SMBIOS_TEMPERATURE_PROBE_STATUS_OK 011b +#define SMBIOS_TEMPERATURE_PROBE_STATUS_NON_CRITICAL 100b +#define SMBIOS_TEMPERATURE_PROBE_STATUS_CRITICAL 101b +#define SMBIOS_TEMPERATURE_PROBE_STATUS_NON_RECOVERABLE 110b + +#pragma endregion + +#pragma region Type 29: Electrical Current Probe + +#define SMBIOS_ELECTRICAL_CURRENT_PROBE_LOCATION_OTHER 00001b +#define SMBIOS_ELECTRICAL_CURRENT_PROBE_LOCATION_UNKNOWN 00010b +#define SMBIOS_ELECTRICAL_CURRENT_PROBE_LOCATION_PROCESSOR 00011b +#define SMBIOS_ELECTRICAL_CURRENT_PROBE_LOCATION_DISK 00100b +#define SMBIOS_ELECTRICAL_CURRENT_PROBE_LOCATION_PERIPHERAL_BAY 00101b +#define SMBIOS_ELECTRICAL_CURRENT_PROBE_LOCATION_SYSTEM_MANAGEMENT_MODULE 00110b +#define SMBIOS_ELECTRICAL_CURRENT_PROBE_LOCATION_MOTHERBOARD 00111b +#define SMBIOS_ELECTRICAL_CURRENT_PROBE_LOCATION_MEMORY_MODULE 01000b +#define SMBIOS_ELECTRICAL_CURRENT_PROBE_LOCATION_PROCESSOR_MODULE 01001b +#define SMBIOS_ELECTRICAL_CURRENT_PROBE_LOCATION_POWER_UNIT 01010b +#define SMBIOS_ELECTRICAL_CURRENT_PROBE_LOCATION_ADD_IN_CARD 01011b + +#define SMBIOS_ELECTRICAL_CURRENT_PROBE_STATUS_OTHER 001b +#define SMBIOS_ELECTRICAL_CURRENT_PROBE_STATUS_UNKNOWN 010b +#define SMBIOS_ELECTRICAL_CURRENT_PROBE_STATUS_OK 011b +#define SMBIOS_ELECTRICAL_CURRENT_PROBE_STATUS_NON_CRITICAL 100b +#define SMBIOS_ELECTRICAL_CURRENT_PROBE_STATUS_CRITICAL 101b +#define SMBIOS_ELECTRICAL_CURRENT_PROBE_STATUS_NON_RECOVERABLE 110b + +#pragma endregion + +#pragma region Type 34: Management Device + +#define SMBIOS_MANAGEMENT_DEVICE_TYPE_OTHER ((BYTE)01h) +#define SMBIOS_MANAGEMENT_DEVICE_TYPE_UNKNOWN ((BYTE)02h) +#define SMBIOS_MANAGEMENT_DEVICE_TYPE_NATIONAL_SEMICONDUCTOR_LM75 ((BYTE)03h) +#define SMBIOS_MANAGEMENT_DEVICE_TYPE_NATIONAL_SEMICONDUCTOR_LM78 ((BYTE)04h) +#define SMBIOS_MANAGEMENT_DEVICE_TYPE_NATIONAL_SEMICONDUCTOR_LM79 ((BYTE)05h) +#define SMBIOS_MANAGEMENT_DEVICE_TYPE_NATIONAL_SEMICONDUCTOR_LM80 ((BYTE)06h) +#define SMBIOS_MANAGEMENT_DEVICE_TYPE_NATIONAL_SEMICONDUCTOR_LM81 ((BYTE)07h) +#define SMBIOS_MANAGEMENT_DEVICE_TYPE_ANALOG_DEVICES_ADM9240 ((BYTE)08h) +#define SMBIOS_MANAGEMENT_DEVICE_TYPE_DALLAS_SEMICONDUCTOR_DS1780 ((BYTE)09h) +#define SMBIOS_MANAGEMENT_DEVICE_TYPE_MAXIM_1617 ((BYTE)0Ah) +#define SMBIOS_MANAGEMENT_DEVICE_TYPE_GENESYS_GL518SM ((BYTE)0Bh) +#define SMBIOS_MANAGEMENT_DEVICE_TYPE_WINBOND_W83781D ((BYTE)0Ch) +#define SMBIOS_MANAGEMENT_DEVICE_TYPE_HOLTEK_HT82H791 ((BYTE)0Dh) + +#define SMBIOS_MANAGEMENT_DEVICE_ADDRESS_TYPE_OTHER ((BYTE)01h) +#define SMBIOS_MANAGEMENT_DEVICE_ADDRESS_TYPE_UNKNOWN ((BYTE)02h) +#define SMBIOS_MANAGEMENT_DEVICE_ADDRESS_TYPE_IO_PORT ((BYTE)03h) +#define SMBIOS_MANAGEMENT_DEVICE_ADDRESS_TYPE_MEMORY ((BYTE)04h) +#define SMBIOS_MANAGEMENT_DEVICE_ADDRESS_TYPE_SMBUS ((BYTE)05h) + +#pragma endregion + +#pragma region Type 39: System Power Supply + +#define SMBIOS_SYSTEM_POWER_SUPPLY_INPUT_VOLTAGE_RANGE_SWITCHING_OTHER 0001b +#define SMBIOS_SYSTEM_POWER_SUPPLY_INPUT_VOLTAGE_RANGE_SWITCHING_UNKNOWN 0010b +#define SMBIOS_SYSTEM_POWER_SUPPLY_INPUT_VOLTAGE_RANGE_SWITCHING_MANUAL 0011b +#define SMBIOS_SYSTEM_POWER_SUPPLY_INPUT_VOLTAGE_RANGE_SWITCHING_AUTO_SWITCH 0100b +#define SMBIOS_SYSTEM_POWER_SUPPLY_INPUT_VOLTAGE_RANGE_SWITCHING_WIDE_RANGE 0101b +#define SMBIOS_SYSTEM_POWER_SUPPLY_INPUT_VOLTAGE_RANGE_SWITCHING_NOT_APPLICABLE 0110b + +#define SMBIOS_SYSTEM_POWER_SUPPLY_STATUS_OTHER 001b +#define SMBIOS_SYSTEM_POWER_SUPPLY_STATUS_UNKNOWN 010b +#define SMBIOS_SYSTEM_POWER_SUPPLY_STATUS_OK 011b +#define SMBIOS_SYSTEM_POWER_SUPPLY_STATUS_NON_CRITICAL 100b +#define SMBIOS_SYSTEM_POWER_SUPPLY_STATUS_CRITICAL 101b + +#define SMBIOS_SYSTEM_POWER_SUPPLY_TYPE_OTHER 0001b +#define SMBIOS_SYSTEM_POWER_SUPPLY_TYPE_UNKNOWN 0010b +#define SMBIOS_SYSTEM_POWER_SUPPLY_TYPE_LINEAR 0011b +#define SMBIOS_SYSTEM_POWER_SUPPLY_TYPE_SWITCHING 0100b +#define SMBIOS_SYSTEM_POWER_SUPPLY_TYPE_BATTERY 0101b +#define SMBIOS_SYSTEM_POWER_SUPPLY_TYPE_UPS 0110b +#define SMBIOS_SYSTEM_POWER_SUPPLY_TYPE_CONVERTER 0111b +#define SMBIOS_SYSTEM_POWER_SUPPLY_TYPE_REGULATOR 1000b + +#pragma endregion + +#pragma region Type 41: Onboard Devices Extended Information + +#define SMBIOS_ONBOARD_DEVICES_EXTENDED_TYPE_OTHER ((BYTE)01h) +#define SMBIOS_ONBOARD_DEVICES_EXTENDED_TYPE_UNKNOWN ((BYTE)02h) +#define SMBIOS_ONBOARD_DEVICES_EXTENDED_TYPE_VIDEO ((BYTE)03h) +#define SMBIOS_ONBOARD_DEVICES_EXTENDED_TYPE_SCSI_CONTROLLER ((BYTE)04h) +#define SMBIOS_ONBOARD_DEVICES_EXTENDED_TYPE_ETHERNET ((BYTE)05h) +#define SMBIOS_ONBOARD_DEVICES_EXTENDED_TYPE_TOKEN_RING ((BYTE)06h) +#define SMBIOS_ONBOARD_DEVICES_EXTENDED_TYPE_SOUND ((BYTE)07h) +#define SMBIOS_ONBOARD_DEVICES_EXTENDED_TYPE_PATA_CONTROLLER ((BYTE)08h) +#define SMBIOS_ONBOARD_DEVICES_EXTENDED_TYPE_SATA_CONTROLLER ((BYTE)09h) +#define SMBIOS_ONBOARD_DEVICES_EXTENDED_TYPE_SAS_CONTROLLER ((BYTE)0Ah) +#define SMBIOS_ONBOARD_DEVICES_EXTENDED_TYPE_WIRELESS_LAN ((BYTE)0Bh) +#define SMBIOS_ONBOARD_DEVICES_EXTENDED_TYPE_BLUETOOTH ((BYTE)0Ch) +#define SMBIOS_ONBOARD_DEVICES_EXTENDED_TYPE_WWAN ((BYTE)0Dh) +#define SMBIOS_ONBOARD_DEVICES_EXTENDED_TYPE_EMMC ((BYTE)0Eh) +#define SMBIOS_ONBOARD_DEVICES_EXTENDED_TYPE_NVME_CONTROLLER ((BYTE)0Fh) +#define SMBIOS_ONBOARD_DEVICES_EXTENDED_TYPE_UFS_CONTROLLER ((BYTE)10h) + +#pragma endregion + +#pragma region Type 45: Firmware Inventory Information + +#define SMBIOS_FIRMWARE_INVENTORY_VERSION_FORMAT_FREE_FORM ((BYTE)00h) +#define SMBIOS_FIRMWARE_INVENTORY_VERSION_FORMAT_MAJOR_MINOR ((BYTE)01h) +#define SMBIOS_FIRMWARE_INVENTORY_VERSION_FORMAT_HEX_STRING_32 ((BYTE)02h) +#define SMBIOS_FIRMWARE_INVENTORY_VERSION_FORMAT_HEX_STRING_64 ((BYTE)03h) + +#define SMBIOS_FIRMWARE_INVENTORY_ID_FORMAT_FREE_FORM ((BYTE)00h) +#define SMBIOS_FIRMWARE_INVENTORY_ID_FORMAT_UEFI_GUID ((BYTE)01h) + +#define SMBIOS_FIRMWARE_INVENTORY_STATE_OTHER ((BYTE)01h) +#define SMBIOS_FIRMWARE_INVENTORY_STATE_UNKNOWN ((BYTE)02h) +#define SMBIOS_FIRMWARE_INVENTORY_STATE_DISABLED ((BYTE)03h) +#define SMBIOS_FIRMWARE_INVENTORY_STATE_ENABLED ((BYTE)04h) +#define SMBIOS_FIRMWARE_INVENTORY_STATE_ABSENT ((BYTE)05h) +#define SMBIOS_FIRMWARE_INVENTORY_STATE_STANDBY_OFFLINE ((BYTE)06h) +#define SMBIOS_FIRMWARE_INVENTORY_STATE_STANDBY_SPARE ((BYTE)07h) +#define SMBIOS_FIRMWARE_INVENTORY_STATE_UNAVAILABLE_OFFLINE ((BYTE)08h) + +#pragma endregion + +/* aka RawSMBIOSData */ +typedef struct _SMBIOS_RAWDATA +{ + BYTE Used20CallingMethod; + BYTE SMBIOSMajorVersion; + BYTE SMBIOSMinorVersion; + BYTE DmiRevision; + DWORD Length; + _Field_size_bytes_(Length) BYTE SMBIOSTableData[]; // PSMBIOS_TABLE_HEADER +} SMBIOS_RAWDATA, *PSMBIOS_RAWDATA; + +typedef struct _SMBIOS_TABLE_HEADER +{ + BYTE Type; + BYTE Length; + WORD Handle; +} SMBIOS_TABLE_HEADER, *PSMBIOS_TABLE_HEADER; + +_STATIC_ASSERT(sizeof(SMBIOS_TABLE_HEADER) == 4); + +typedef struct _SMBIOS_TABLE +{ + SMBIOS_TABLE_HEADER Header; + union + { + struct + { + BYTE Vendor; + BYTE Version; + WORD StartingAddressSegment; + BYTE ReleaseDate; + BYTE ROMSize; + union + { + QWORD Characteristics; + struct + { + QWORD Reserved0 : 1; /* 00 Reserved */ + QWORD Reserved1 : 1; /* 01 Reserved */ + QWORD Unknown0 : 1; /* 02 Unknown */ + QWORD CharacteristicsNotSupported : 1; /* 03 BIOS Characteristics are not supported */ + QWORD ISA : 1; /* 04 ISA is supported */ + QWORD MCA : 1; /* 05 MCA is supported */ + QWORD EISA : 1; /* 06 EISA is supported */ + QWORD PCI : 1; /* 07 PCI is supported */ + QWORD PCCard : 1; /* 08 PC card (PCMCIA) is supported */ + QWORD PNP : 1; /* 09 Plug and Play is supported */ + QWORD APM : 1; /* 10 APM is supported */ + QWORD Upgradeable : 1; /* 11 BIOS is upgradeable (Flash) */ + QWORD ShadowingIsAllowed : 1; /* 12 BIOS shadowing is allowed */ + QWORD VL_VESA : 1; /* 13 VL-VESA is supported */ + QWORD ESCD : 1; /* 14 ESCD support is available */ + QWORD BootFromCD : 1; /* 15 Boot from CD is supported */ + QWORD SelectableBoot : 1; /* 16 Selectable boot is supported */ + QWORD ROMIsSocketed : 1; /* 17 BIOS ROM is socketed (e.g., PLCC or SOP socket) */ + QWORD BootFromPCCard : 1; /* 18 Boot from PC card (PCMCIA) is supported */ + QWORD EDDSpec : 1; /* 19 EDD specification is supported */ + QWORD FloppyForNEC9800_1Dot2MB : 1; /* 20 Int 13h — Japanese floppy for NEC 9800 1.2 MB (3.5”, 1K bytes/sector, 360 RPM) is supported */ + QWORD FloppyForToshiba_1Dot2MB : 1; /* 21 Int 13h — Japanese floppy for Toshiba 1.2 MB (3.5”, 360 RPM) is supported */ + QWORD Floppy_5Dot25Inch_360KB : 1; /* 22 Int 13h — 5.25” / 360 KB floppy services are supported */ + QWORD Floppy_5Dot25Inch_1Dot2MB : 1; /* 23 Int 13h — 5.25” / 1.2 MB floppy services are supported */ + QWORD Floppy_3Dot5Inch_720KB : 1; /* 24 Int 13h — 3.5” / 720 KB floppy services are supported */ + QWORD Floppy_3Dot5Inch_2Dot88MB : 1; /* 25 Int 13h — 3.5” / 2.88 MB floppy services are supported */ + QWORD PrintScreenService : 1; /* 26 Int 5h, print screen service is supported */ + QWORD _8042KeyboardServices : 1; /* 27 Int 9h, 8042 keyboard services are supported */ + QWORD SerialServices : 1; /* 28 Int 14h, serial services are supported */ + QWORD PrinterServices : 1; /* 29 Int 17h, printer services are supported */ + QWORD CGA_Mono_VideoServices : 1; /* 30 Int 10h, CGA/Mono Video Services are supported */ + QWORD NEC_PC98 : 1; /* 31 NEC PC-98 */ + QWORD ReservedForBIOSVendor : 16; /* 32:47 Reserved for BIOS vendor */ + QWORD ReservedForSystemVendor : 16; /* 48:63 Reserved for system vendor */ + }; + }; + union + { + BYTE CharacteristicsExtensionBytes[2]; + struct + { + struct + { + BYTE ACPI : 1; /* 00 ACPI is supported */ + BYTE USBLegacy : 1; /* 01 USB Legacy is supported */ + BYTE AGP : 1; /* 02 AGP is supported */ + BYTE I2OBoot : 1; /* 03 I2O boot is supported */ + BYTE LS120_SuperDiskBoot : 1; /* 04 LS-120 SuperDisk boot is supported */ + BYTE ATAPI_ZIP_DriveBoot : 1; /* 05 ATAPI ZIP drive boot is supported */ + BYTE _1394Boot : 1; /* 06 1394 boot is supported */ + BYTE SmartBattery : 1; /* 07 Smart battery is supported */ + }; + struct + { + BYTE BIOSBootSpec : 1; /* 00 BIOS Boot Specification is supported */ + BYTE FunctionKeyInitiatedNetworkServiceBoot : 1; /* 01 Function key-initiated network service boot is supported */ + BYTE EnableTargetedContentDistribution : 1; /* 02 Enable targeted content distribution */ + BYTE UEFISpec : 1; /* 03 UEFI Specification is supported */ + BYTE VirtualMachine : 1; /* 04 SMBIOS table describes a virtual machine */ + BYTE ManufacturingMode : 1; /* 05 Manufacturing mode is supported */ + BYTE ManufacturingModeEnabled : 1; /* 06 Manufacturing mode is enabled */ + BYTE Reserved : 1; /* 07 Reserved */ + }; + }; + }; + BYTE MajorRelease; + BYTE MinorRelease; + BYTE ECFirmwareMajorRelease; + BYTE ECFirmwareMinorRelease; + union + { + WORD ExtendedROMSize; + struct + { + WORD Size : 14; /* 00:13 Size */ + WORD Unit : 2; /* 14:15 Unit, SMBIOS_BIOS_EXTENDEDROMSIZE_UNIT_* */ + }; + }; + } TYPE_0_BIOS_INFO; + struct + { + BYTE Manufacturer; + BYTE ProductName; + BYTE Version; + BYTE SerialNumber; + BYTE UUID[16]; + BYTE WakeUpType; /* SMBIOS_SYSTEM_WAKEUPTYPE_* */ + BYTE SKUNumber; + BYTE Famliy; + } TYPE_1_SYSTEM_INFO; + struct + { + BYTE Manufacturer; + BYTE Product; + BYTE Version; + BYTE SerialNumber; + BYTE AssetTag; + union + { + BYTE FeatureFlags; + struct + { + BYTE HostingBoard : 1; /* 00 The board is a hosting board (for example, a motherboard) */ + BYTE RequiresAuxiliary : 1; /* 01 The board requires at least one daughter board or auxiliary card to function properly */ + BYTE Removable : 1; /* 02 The board is removable */ + BYTE Replaceable : 1; /* 03 The board is replaceable */ + BYTE HotSwappable : 1; /* 04 The board is s hot swappable */ + BYTE Reserved : 3; /* 05:07 Reserved for future definition by this specification */ + }; + }; + BYTE LocationInChassis; + WORD ChassisHandle; + BYTE BoardType; /* SMBIOS_BASEBOARD_TYPE_*/ + BYTE NumberOfContainedObjectHandles; + _Field_size_(NumberOfContainedObjectHandles) WORD ContainedObjectHandles[]; + } TYPE_2_BASEBOARD_INFO; + struct + { + BYTE Manufacturer; + union + { + BYTE Type; + struct + { + BYTE Value : 7; /* SMBIOS_SYSTEM_ENCLOSURE_OR_CHASSIS_TYPE_* */ + BYTE ChassisLock : 1; /* Chassis lock is present */ + }; + }; + BYTE Version; + BYTE SerialNumber; + BYTE AssetTagNumber; + BYTE BootUpState; /* SMBIOS_SYSTEM_ENCLOSURE_OR_CHASSIS_STATE_* */ + BYTE PowerSupplyState; /* SMBIOS_SYSTEM_ENCLOSURE_OR_CHASSIS_STATE_* */ + BYTE ThermalState; /* SMBIOS_SYSTEM_ENCLOSURE_OR_CHASSIS_STATE_* */ + BYTE SecurityStatus; /* SMBIOS_SYSTEM_ENCLOSURE_OR_CHASSIS_SECURITY_STATE_* */ + DWORD OEMDefined; + BYTE Height; + BYTE NumberOfPowerCords; + BYTE ContainedElementCount; + BYTE ContainedElementRecordLength; + _Field_size_bytes_(ContainedElementCount * ContainedElementRecordLength) BYTE ContainedElements[]; + /* BYTE SKUNumber; */ + } TYPE_3_SYSTEM_ENCLOSURE_OR_CHASSIS; + struct + { + BYTE SocketDesignation; + BYTE Type; /* SMBIOS_PROCESSOR_TYPE_* */ + BYTE Family; + BYTE Manufacturer; + QWORD ID; + BYTE Version; + union + { + BYTE Voltage; + struct + { + BYTE Voltage5V : 1; + BYTE Voltage3Dot3V : 1; + BYTE Voltage2Dot9V : 1; + BYTE Reserved0 : 1; + BYTE Reserved1 : 3; + BYTE LegacyMode : 1; /* Should be 0 */ + }; + struct + { + BYTE VoltageTimes10 : 7; + BYTE NotLegacyModeVoltage : 1; /* Should be 1 */ + }; + }; + WORD ExternalClock; + WORD MaxSpeed; + WORD CurrentSpeed; + union + { + BYTE Status; + struct + { + BYTE CPUStatus : 3; /* SMBIOS_PROCESSOR_CPU_STATUS_* */ + BYTE Reserved2 : 3; + BYTE CPUSocketPopulated : 1; + BYTE Reserved3 : 1; + }; + }; + BYTE Upgrade; + WORD L1CacheHandle; + WORD L2CacheHandle; + WORD L3CacheHandle; + BYTE SerialNumber; + BYTE AssetTag; + BYTE PartNumber; + BYTE CoreCount; + BYTE CoreEnabled; + BYTE ThreadCount; + union + { + WORD Characteristics; + struct + { + WORD Reserved4 : 1; + WORD Unknown : 1; + WORD _64BitCapable : 1; + WORD MultiCore : 1; + WORD HardwareThread : 1; + WORD ExecuteProtection : 1; + WORD EnhancedVirtualization : 1; + WORD PowerPerformanceControl : 1; + WORD _128BitCapable : 1; + WORD Arm64SoCID : 1; + WORD Reserved5 : 6; + }; + }; + WORD Famliy2; + WORD CoreCount2; + WORD CoreEnabled2; + WORD ThreadCount2; + WORD ThreadEnabled; + } TYPE_4_PROCESSOR_INFO; + struct + { + BYTE SocketDesignation; + union + { + WORD CacheConfiguration; + struct + { + WORD CacheLevel : 3; + WORD CacheSocketed : 1; + WORD Reserved0 : 1; + WORD Location : 2; /* SMBIOS_CACHE_LOCATION_* */ + WORD Enabled : 1; + WORD OperationalMode : 2; /* SMBIOS_CACHE_OPERATIONAL_MODE_* */ + WORD Reserved1 : 6; + }; + }; + union + { + WORD MaximumCacheSize; + struct + { + WORD MaxSizeInGranularity : 15; + WORD MaxSizeGranularity : 1; + }; + }; + union + { + WORD InstalledSize; + struct + { + WORD InstalledSizeInGranularity : 15; + WORD InstalledSizeGranularity : 1; + }; + }; + SMBIOS_CACHE_SRAM_TYPE SupportedSRAMType; + SMBIOS_CACHE_SRAM_TYPE CurrentSRAMType; + BYTE CacheSpeed; + BYTE ErrorCorrectionType; /* SMBIOS_CACHE_ERROR_CORRECTION_TYPE_* */ + BYTE SystemCacheType; /* SMBIOS_CACHE_SYSTEM_CACHE_TYPE_* */ + BYTE Associativity; /* SMBIOS_CACHE_ASSOCIATIVITY_* */ + union + { + DWORD MaximumCacheSize2; + struct + { + DWORD MaxSizeInGranularity2 : 31; + DWORD MaxSizeGranularity2 : 1; + }; + }; + union + { + DWORD InstalledCacheSize2; + struct + { + DWORD InstalledCacheSizeInGranularity2 : 31; + DWORD InstalledCacheSizeGranularity2 : 1; + }; + }; + } TYPE_7_CACHE_INFO; + struct + { + BYTE InternalReferenceDesignator; + BYTE InternalConnectorType; /* SMBIOS_PORT_CONNECTOR_TYPE_* */ + BYTE ExternalReferenceDesignator; + BYTE ExternalConnectorType; /* SMBIOS_PORT_CONNECTOR_TYPE_* */ + BYTE PortType; + } TYPE_8_PORT_CONNECTOR_INFO; + struct + { + BYTE Designation; + BYTE Type; /* SMBIOS_SYSTEM_SLOTS_TYPE_* */ + BYTE SlotDataBusWidth; /* SMBIOS_SYSTEM_SLOTS_DATA_BUS_WIDTH_* */ + BYTE CurrentUsage; /* SMBIOS_SYSTEM_SLOTS_CURRENT_USAGE_* */ + BYTE Length; /* SMBIOS_SYSTEM_SLOTS_LENGTH_* */ + WORD ID; + union + { + BYTE Characteristics1; + struct + { + BYTE CharacteristicsUnknown : 1; + BYTE Provides5Dot0Volts : 1; + BYTE Provides3Dot3Volts : 1; + BYTE OpeningSharedWithAnother : 1; + BYTE PCCardSupportsPCCard16 : 1; + BYTE PCCardSupportsCardBus : 1; + BYTE PCCardSupportsZoomVideo : 1; + BYTE PCCardSupportsModemRingResume : 1; + }; + }; + union + { + BYTE Characteristics2; + struct + { + BYTE PCISupportsPMESignal : 1; + BYTE SupportsHotPlugDevices : 1; + BYTE PCISupportsSMBusSignal : 1; + BYTE PCIeSupportsBifurcation : 1; + BYTE SupportsAsyncOrSurpriseRemoval : 1; + BYTE FlexbusCXL1Capable : 1; + BYTE FlexbusCXL2Capable : 1; + BYTE FlexbusCXL3Capable : 1; + }; + }; + WORD SegmentGroupNumber; + BYTE BusNumber; + union + { + BYTE DeviceFunctionNumber; + struct + { + BYTE FunctionNumber : 3; + BYTE DeviceNumber : 5; + }; + }; + BYTE DataBusWidth; + BYTE PeerGroupingCount; + _Field_size_bytes_(5 * PeerGroupingCount) BYTE PeerGroups[]; + /* BYTE Information; */ + /* BYTE PhysicalWidth; */ + /* WORD Pitch; */ + /* BYTE Height; */ + } TYPE_9_SYSTEM_SLOTS; + struct + { + _Field_size_((Header.Length - sizeof(Header)) / 2) BYTE Type[]; /* SMBIOS_ONBOARD_DEVICES_TYPE_* */ + /* _Field_size_((Header.Length - sizeof(Header)) / 2) BYTE DescriptionString[]; */ + } TYPE_10_OBSOLETE_ON_BOARD_DEVICES_INFO; + struct + { + BYTE Count; + } TYPE_11_OEM_STRINGS; + struct + { + BYTE Count; + } TYPE_12_SYSTEM_CONFIGURATION_OPTIONS; + struct + { + BYTE InstallableLanguages; + union + { + BYTE Flags; + struct + { + BYTE AbbreviatedFormat : 1; + BYTE Reserved0 : 7; + }; + }; + BYTE Reserved1[15]; + BYTE CurrentLanguage; + } TYPE_13_BIOS_LANGUAGE_INFO; + struct + { + BYTE GroupName; + BYTE ItemType1; + WORD ItemHandle1; + /* ItemType2, ItemHandle2, ..., ItemTypeN, ItemHandleN */ + } TYPE_14_GROUP_ASSOCIATIONS; + struct + { + BYTE Location; /* SMBIOS_PHYSICAL_MEMORY_ARRAY_LOCATION_* */ + BYTE Use; /* SMBIOS_PHYSICAL_MEMORY_ARRAY_USE_* */ + BYTE ErrorCorrection; /* SMBIOS_PHYSICAL_MEMORY_ARRAY_ERROR_CORRECTION_TYPE_* */ + DWORD MaximumCapacity; + WORD ErrorInformationHandle; + WORD NumberOfMemoryDevices; + QWORD ExtendedMaximumCapacity; + } TYPE_16_PHYSICAL_MEMORY_ARRAY; + struct + { + WORD PhysicalMemoryArrayHandle; + WORD ErrorInformationHandle; + WORD TotalWidth; + WORD DataWidth; + WORD Size; + BYTE FormFactor; /* SMBIOS_MEMORY_DEVICE_FORM_FACTOR_* */ + BYTE DeviceSet; + BYTE DeviceLocator; + BYTE BankLocator; + BYTE Type; /* SMBIOS_MEMORY_DEVICE_TYPE_* */ + union + { + WORD TypeDetail; + struct + { + WORD Reserved0 : 1; + WORD TypeOther : 1; + WORD TypeUnknow : 1; + WORD FastPaged : 1; + WORD StaticColumn : 1; + WORD PseudoStatic : 1; + WORD RAMBUS : 1; + WORD Synchronous : 1; + WORD CMOS : 1; + WORD EDO : 1; + WORD WindowDRAM : 1; + WORD CacheDRAM : 1; + WORD NonVolatile : 1; + WORD Registered : 1; + WORD Unbuffered : 1; + WORD LRDIMM : 1; + }; + }; + WORD Speed; + BYTE Manufacturer; + BYTE SerialNumber; + BYTE AssetTag; + BYTE PartNumber; + union + { + BYTE Attributes; + struct + { + BYTE Rank : 4; + BYTE Reserved1 : 4; + }; + }; + DWORD ExtendedSize; + WORD ConfiguredMemorySpeed; + WORD MinimumVoltage; + WORD MaximumVoltage; + WORD ConfiguredVoltage; + BYTE Technology; /* SMBIOS_MEMORY_DEVICE_TECHNOLOGY_* */ + union + { + WORD OperatingModeCapability; + struct + { + WORD Reserved2 : 1; + WORD OperatingModeCapabilityOther : 1; + WORD OperatingModeCapabilityUnknown : 1; + WORD VolatileMemory : 1; + WORD ByteAccessiblePersistentMemory : 1; + WORD BlockAccessiblePersistentMemory : 1; + WORD Reserved3 : 10; + }; + }; + BYTE FirmwareVersion; + WORD ModuleManufacturerID; + WORD ModuleProductID; + WORD SubsystemControllerManufacturerID; + QWORD NonVolatileSize; + QWORD VolatileSize; + QWORD CacheSize; + QWORD LogicalSize; + DWORD ExtendedSpeed; + DWORD ExtendedConfiguredSpeed; + WORD PMIC0ManufacturerID; + WORD PMIC0RevisionNumber; + WORD RCDManufacturerID; + WORD RCDRevisionNumber; + } TYPE_17_MEMORY_DEVICE; + struct + { + DWORD StartingAddress; + DWORD EndingAddress; + WORD Handle; + BYTE PartitionWidth; + QWORD ExtendedStartingAddress; + QWORD ExtendedEndingAddress; + } TYPE_19_MEMORY_ARRAY_MAPPED_ADDRESS; + struct + { + DWORD StartingAddress; + DWORD EndingAddress; + WORD Handle; + WORD MemoryArrayMappedAddressHandle; + BYTE PartitionRowPosition; + BYTE InterleavePosition; + BYTE InterleavedDataDepth; + QWORD ExtendedStartingAddress; + QWORD ExtendedEndingAddress; + } TYPE_20_MEMORY_DEVICE_MAPPED_ADDRESS; + struct + { + union + { + BYTE Capabilities; + struct + { + BYTE Status : 1; + BYTE BootOption : 2; /* SMBIOS_SYSTEM_RESET_BOOT_OPTION_* */ + BYTE BootOptionOnLimit : 2; /* SMBIOS_SYSTEM_RESET_BOOT_OPTION_* */ + BYTE SystemContainsAWatchdogTimer : 1; + BYTE Reserved : 2; + }; + }; + WORD ResetCount; + WORD ResetLimit; + WORD TimerInterval; + WORD Timeout; + } TYPE_23_SYSTEM_RESET; + struct + { + union + { + BYTE Settings; + /* SMBIOS_HARDWARE_SECURITY_SETTINGS_STATUS_* */ + struct + { + BYTE FrontPanelResetStatus : 2; + BYTE AdministratorPasswordStatus : 2; + BYTE KeyboardPasswordStatus : 2; + BYTE PowerOnPasswordStatus : 2; + }; + }; + } TYPE_24_HARDWARE_SECURITY; + struct + { + BYTE NextScheduledPowerOnMonth; + BYTE NextScheduledPowerOnDayOfMonth; + BYTE NextScheduledPowerOnHour; + BYTE NextScheduledPowerOnMinute; + BYTE NextScheduledPowerOnSecond; + } TYPE_25_SYSTEM_POWER_CONTROLS; + struct + { + BYTE Description; + union + { + BYTE LocationAndStatus; + struct + { + BYTE Location : 5; /* SMBIOS_VOLTAGE_PROBE_LOCATION_* */ + BYTE Status : 3; /* SMBIOS_VOLTAGE_PROBE_STATUS_* */ + }; + }; + } TYPE_26_VOLTAGE_PROBE; + struct + { + WORD TemperatureProbeHandle; + union + { + BYTE DeviceTypeAndStatus; + struct + { + BYTE Type : 5; /* SMBIOS_COOLING_DEVICE_TYPE_* */ + BYTE Status : 3; /* SMBIOS_COOLING_DEVICE_STATUS_* */ + }; + }; + BYTE CoolingUnitGroup; + DWORD OEMDefined; + WORD NominalSpeed; + BYTE Description; + } TYPE_27_COOLING_DEVICE; + struct + { + BYTE Description; + union + { + BYTE LocationAndStatus; + struct + { + BYTE Location : 5; /* SMBIOS_TEMPERATURE_PROBE_LOCATION_* */ + BYTE Status : 3; /* SMBIOS_TEMPERATURE_PROBE_STATUS_* */ + }; + }; + WORD MaximumValue; + WORD MinimumValue; + WORD Resolution; + WORD Tolerance; + WORD Accuracy; + DWORD OEMDefined; + WORD NominalValue; + } TYPE_28_TEMPERATURE_PROBE; + struct + { + BYTE Description; + union + { + BYTE LocationAndStatus; + struct + { + BYTE Location : 5; /* SMBIOS_ELECTRICAL_CURRENT_PROBE_LOCATION_* */ + BYTE Status : 3; /* SMBIOS_ELECTRICAL_CURRENT_PROBE_STATUS_* */ + }; + }; + WORD MaximumValue; + WORD MinimumValue; + WORD Resolution; + WORD Tolerance; + WORD Accuracy; + DWORD OEMDefined; + WORD NominalValue; + } TYPE_29_ELECTRICAL_CURRENT_PROBE; + struct + { + BYTE ManufacturerName; + union + { + BYTE Connections; + struct + { + BYTE InboundConnectionEnabled : 1; + BYTE OutboundConnectionEnabled : 1; + BYTE Reserved : 6; + }; + }; + } TYPE_30_OUT_OF_BAND_REMOTE_ACCESS; + struct + { + BYTE Reserved[6]; + BYTE BootStatus[10]; + } TYPE_32_SYSTEM_BOOT_INFORMATION; + struct + { + BYTE Description; + BYTE Type; /* SMBIOS_MANAGEMENT_DEVICE_TYPE_* */ + DWORD Address; + BYTE AddressType; /* SMBIOS_MANAGEMENT_DEVICE_ADDRESS_TYPE_* */ + } TYPE_34_MANAGEMENT_DEVICE; + struct + { + BYTE Description; + WORD ManagementDeviceHandle; + WORD ComponentHandle; + WORD ThresholdHandle; + } TYPE_35_MANAGEMENT_DEVICE_COMPONENT; + struct + { + BYTE PowerUnitGroup; + BYTE Location; + BYTE DeviceName; + BYTE Manufacturer; + BYTE SerialNumber; + BYTE AssetTagNumber; + BYTE ModelPartNumber; + BYTE RevisionLevel; + WORD MaxPowerCapacity; + union + { + WORD Characteristics; + struct + { + WORD HotReplaceable : 1; + WORD Present : 1; + WORD UnpluggedFromTheWall : 1; + WORD DMTFInputVoltageRangeSwitching : 4; /* SMBIOS_SYSTEM_POWER_SUPPLY_INPUT_VOLTAGE_RANGE_SWITCHING_* */ + WORD Status : 3; /* SMBIOS_SYSTEM_POWER_SUPPLY_STATUS_* */ + WORD DMTFPowerSupplyType : 4; /* SMBIOS_SYSTEM_POWER_SUPPLY_TYPE_* */ + WORD Reserved : 2; + }; + }; + } TYPE_39_SYSTEM_POWER_SUPPLY; + struct + { + BYTE ReferenceDesignation; + union + { + BYTE Type; + struct + { + BYTE TypeOfDevice : 7; /* SMBIOS_ONBOARD_DEVICES_EXTENDED_TYPE_* */ + BYTE Status : 1; + }; + }; + BYTE TypeInstance; + WORD SegmentGroupNumber; + BYTE BusNumber; + union + { + BYTE DeviceFunctionNumber; + struct + { + BYTE FunctionNumber : 3; + BYTE DeviceNumber : 5; + }; + }; + } TYPE_41_ONBOARD_DEVICES_EXTENDED_INFORMATION; + struct + { + BYTE VendorID[4]; + BYTE MajorSpecVersion; + BYTE MinorSpecVersion; + DWORD FirmwareVersion1; + DWORD FirmwareVersion2; + BYTE Description; + union + { + QWORD Characteristics; + struct + { + QWORD Reserved0 : 1; + QWORD Reserved1 : 1; + QWORD NotSupported : 1; + QWORD FamilyConfigurableViaFirmwareUpdate : 1; + QWORD FamilyConfigurableViaPlatformSoftwareSupport : 1; + QWORD FamilyConfigurableViaOEMProprietaryMechanism : 1; + QWORD Reserved2 : 58; + }; + }; + DWORD OEMDefined; + } TYPE_43_TPM_DEVICE; + struct + { + WORD ReferencedHandle; + BYTE ProcessorSpecificBlock[]; + } TYPE_44_PROCESSOR_ADDITIONAL_INFO; + struct + { + BYTE ComponentName; + BYTE Version; + BYTE VersionFormat; /* SMBIOS_FIRMWARE_INVENTORY_VERSION_FORMAT_* */ + BYTE ID; + BYTE IDFormat; /* SMBIOS_FIRMWARE_INVENTORY_ID_FORMAT_* */ + BYTE ReleaseDate; + BYTE Manufacturer; + BYTE LowestSupportedFirmwareVersion; /* SMBIOS_FIRMWARE_INVENTORY_VERSION_FORMAT_* */ + QWORD ImageSize; + union + { + WORD Characteristics; + struct + { + WORD Updatable : 1; + WORD WriteProtect : 1; + WORD Reserved : 14; + }; + }; + BYTE State; /* SMBIOS_FIRMWARE_INVENTORY_STATE_* */ + BYTE NumberOfAssociatedComponents; + _Field_size_(NumberOfAssociatedComponents) WORD AssociatedComponentHandles[]; + } TYPE_45_FIRMWARE_INVENTORY_INFO; + }; +} SMBIOS_TABLE, *PSMBIOS_TABLE; + +#pragma pack(pop) + +#pragma warning(default: 4200) diff --git a/Source/Include/KNSoft/NDK/Extension/StrSafe.h b/Source/Include/KNSoft/NDK/Extension/StrSafe.h new file mode 100644 index 0000000..576d3ab --- /dev/null +++ b/Source/Include/KNSoft/NDK/Extension/StrSafe.h @@ -0,0 +1,126 @@ +#pragma once + +#include +#include + +#pragma region String PrintF + +/* + * StrSafe_Cch[V]Printf(A/W) + * + * Return == 0: Error or no data + * Return < BufferCount: Success + * Return >= BufferCount: Truncated, returns required size in character, not including null-terminator + */ + +_Success_( + return > 0 && return < BufferCount +) +__inline unsigned long __cdecl StrSafe_CchVPrintfA( + _Out_writes_opt_(BufferCount) _Always_(_Post_z_) char* const Buffer, + _In_ size_t const BufferCount, + _In_z_ _Printf_format_string_ const char* Format, + va_list ArgList) +{ + int i; + +#pragma warning(disable: 4996) + i = _vsnprintf(Buffer, BufferCount, Format, ArgList); +#pragma warning(default: 4996) + if (i > 0) + { + if (Buffer != NULL && i == BufferCount) + { + Buffer[i - 1] = '\0'; + } + return i; + } else if (i == 0) + { + return 0; + } + +#pragma warning(disable: 4996) + i = _vsnprintf(NULL, 0, Format, ArgList); +#pragma warning(default: 4996) + if (i > 0) + { + if (Buffer != NULL && (size_t)i > BufferCount && BufferCount > 0) + { + Buffer[BufferCount - 1] = '\0'; + } + return i; + } + + return 0; +} + +_Success_( + return > 0 && return < BufferCount +) +__inline unsigned long __cdecl StrSafe_CchVPrintfW( + _Out_writes_opt_(BufferCount) _Always_(_Post_z_) wchar_t* const Buffer, + _In_ size_t const BufferCount, + _In_z_ _Printf_format_string_ const wchar_t* Format, + va_list ArgList) +{ + int i; + +#pragma warning(disable: 4996) + i = _vsnwprintf(Buffer, BufferCount, Format, ArgList); +#pragma warning(default: 4996) + if (i > 0) + { + if (Buffer != NULL && i == BufferCount) + { + Buffer[i - 1] = L'\0'; + } + return i; + } else if (i == 0) + { + return 0; + } + +#pragma warning(disable: 4996) + i = _vsnwprintf(NULL, 0, Format, ArgList); +#pragma warning(default: 4996) + if (i > 0) + { + if (Buffer != NULL && (size_t)i > BufferCount && BufferCount > 0) + { + Buffer[BufferCount - 1] = L'\0'; + } + return i; + } + + return 0; +} + +_Success_( + return > 0 && return < BufferCount +) +__inline unsigned long __cdecl StrSafe_CchPrintfA( + _Out_writes_opt_(BufferCount) _Always_(_Post_z_) char* const Buffer, + _In_ size_t const BufferCount, + _In_z_ _Printf_format_string_ const char* Format, ...) +{ + va_list ArgList; + + va_start(ArgList, Format); + return StrSafe_CchVPrintfA(Buffer, BufferCount, Format, ArgList); +} + +_Success_( + return > 0 && return < BufferCount +) +__inline unsigned long __cdecl StrSafe_CchPrintfW( + _Out_writes_opt_(BufferCount) _Always_(_Post_z_) wchar_t* const Buffer, + _In_ size_t const BufferCount, + _In_z_ _Printf_format_string_ const wchar_t* Format, ...) +{ + va_list ArgList; + + va_start(ArgList, Format); + return StrSafe_CchVPrintfW(Buffer, BufferCount, Format, ArgList); +} + +#pragma endregion diff --git a/Source/Include/KNSoft/NDK/NDK.h b/Source/Include/KNSoft/NDK/NDK.h new file mode 100644 index 0000000..07ca729 --- /dev/null +++ b/Source/Include/KNSoft/NDK/NDK.h @@ -0,0 +1,41 @@ +/* + * KNSoft.NDK (https://github.com/KNSoft/KNSoft.NDK) + * Copyright (c) KNSoft.org (https://github.com/KNSoft). All rights reserved. + * Licensed under the MIT license. + */ + +#pragma once + +#include "NT/NT.h" + +/* Windows.h */ + +#include +#include "Win32/Def/WinUser.h" +#include "Win32/Def/winsta.h" + +/* APIs */ + +#include "Win32/API/Ntdll.h" +#include "Win32/API/Kernel32.h" +#include "Win32/API/User32.h" +#include "Win32/API/WinSta.h" + +/* Additional headers */ + +#include +#include + +/* Enable extensions */ + +#ifndef _KNSOFT_NDK_NO_EXTENSION +#include "Extension/Extension.h" +#endif + +#ifndef _KNSOFT_NDK_NO_EXTENSION_MSTOOLCHAIN +#include "Extension/MSToolChain.h" +#endif + +#ifndef _KNSOFT_NDK_NO_INLINE +#define _KNSOFT_NDK_NT_INLINE +#endif diff --git a/Source/Include/KNSoft/NDK/NT/API/API.h b/Source/Include/KNSoft/NDK/NT/API/API.h new file mode 100644 index 0000000..0612bf0 --- /dev/null +++ b/Source/Include/KNSoft/NDK/NT/API/API.h @@ -0,0 +1,13 @@ +#pragma once + +#include "Mm.h" +#include "Ob.h" +#include "Ps.h" +#include "Fs.h" +#include "Se.h" +#include "Cm.h" +#include "Ex.h" +#include "Sys.h" +#include "Wow.h" + +#include "Rtl/Rtl.h" diff --git a/Source/Include/KNSoft/NDK/NT/API/Cm.h b/Source/Include/KNSoft/NDK/NT/API/Cm.h new file mode 100644 index 0000000..427608f --- /dev/null +++ b/Source/Include/KNSoft/NDK/NT/API/Cm.h @@ -0,0 +1,66 @@ +#pragma once + +#include "../../NT/MinDef.h" +#include "../../NT/Types/Cm.h" + +EXTERN_C_START + +NTSYSAPI +NTSTATUS +NTAPI +NtOpenKey( + _Out_ PHANDLE KeyHandle, + _In_ ACCESS_MASK DesiredAccess, + _In_ POBJECT_ATTRIBUTES ObjectAttributes); + +NTSYSAPI +NTSTATUS +NTAPI +NtCreateKey( + _Out_ PHANDLE KeyHandle, + _In_ ACCESS_MASK DesiredAccess, + _In_ POBJECT_ATTRIBUTES ObjectAttributes, + _Reserved_ ULONG TitleIndex, + _In_opt_ PUNICODE_STRING Class, + _In_ ULONG CreateOptions, + _Out_opt_ PULONG Disposition); + +_When_(Length == 0, + _Post_satisfies_(return < 0) +) +_When_(Length > 0, + _Post_satisfies_(return <= 0) +) +_Success_(return == STATUS_SUCCESS) +_On_failure_(_When_(return == STATUS_BUFFER_OVERFLOW || return == STATUS_BUFFER_TOO_SMALL, + _Post_satisfies_(*ResultLength > Length)) +) +NTSYSAPI +NTSTATUS +NTAPI +NtQueryValueKey( + _In_ HANDLE KeyHandle, + _In_ PUNICODE_STRING ValueName, + _In_ KEY_VALUE_INFORMATION_CLASS KeyValueInformationClass, + _Out_writes_bytes_to_(Length, *ResultLength) PVOID KeyValueInformation, + _In_ ULONG Length, + _Out_ PULONG ResultLength); + +NTSYSAPI +NTSTATUS +NTAPI +NtSetValueKey( + _In_ HANDLE KeyHandle, + _In_ PUNICODE_STRING ValueName, + _In_opt_ ULONG TitleIndex, + _In_ ULONG Type, + _In_reads_bytes_(DataSize) PVOID Data, + _In_ ULONG DataSize); + +NTSYSAPI +NTSTATUS +NTAPI +NtDeleteKey( + _In_ HANDLE KeyHandle); + +EXTERN_C_END diff --git a/Source/Include/KNSoft/NDK/NT/API/Ex.h b/Source/Include/KNSoft/NDK/NT/API/Ex.h new file mode 100644 index 0000000..ee2127d --- /dev/null +++ b/Source/Include/KNSoft/NDK/NT/API/Ex.h @@ -0,0 +1,63 @@ +#pragma once + +#include "../../NT/MinDef.h" +#include "../../NT/Types/Ex.h" + +EXTERN_C_START + +#pragma region Event + +NTSYSAPI +NTSTATUS +NTAPI +NtCreateEvent( + _Out_ PHANDLE EventHandle, + _In_ ACCESS_MASK DesiredAccess, + _In_opt_ POBJECT_ATTRIBUTES ObjectAttributes, + _In_ EVENT_TYPE EventType, + _In_ BOOLEAN InitialState); + +NTSYSAPI +NTSTATUS +NTAPI +NtSetEvent( + _In_ HANDLE EventHandle, + _Out_opt_ PLONG PreviousState); + +NTSYSAPI +NTSTATUS +NTAPI +NtResetEvent( + _In_ HANDLE EventHandle, + _Out_opt_ PLONG NumberOfWaitingThreads); + +NTSYSAPI +NTSTATUS +NTAPI +NtPulseEvent( + _In_ HANDLE EventHandle, + _In_opt_ PLONG PulseCount); + +NTSYSAPI +NTSTATUS +NTAPI +NtQueryEvent( + _In_ HANDLE EventHandle, + _In_ EVENT_INFORMATION_CLASS EventInformationClass, + _Out_writes_bytes_to_(EventInformationLength, *ReturnLength) PVOID EventInformation, + _In_ ULONG EventInformationLength, + _Out_opt_ PULONG ReturnLength); + +#pragma endregion + +NTSYSAPI +NTSTATUS +NTAPI +NtQueryInformationAtom( + _In_ RTL_ATOM Atom, + _In_ ATOM_INFORMATION_CLASS AtomInformationClass, + _Out_writes_bytes_to_(AtomInformationLength, *ReturnLength) PVOID AtomInformation, + _In_ ULONG AtomInformationLength, + _Out_opt_ PULONG ReturnLength); + +EXTERN_C_END diff --git a/Source/Include/KNSoft/NDK/NT/API/Fs.h b/Source/Include/KNSoft/NDK/NT/API/Fs.h new file mode 100644 index 0000000..4b3e67b --- /dev/null +++ b/Source/Include/KNSoft/NDK/NT/API/Fs.h @@ -0,0 +1,144 @@ +#pragma once + +#include "../../NT/MinDef.h" +#include "../../NT/Types/Io.h" +#include "../../NT/Types/Fs.h" + +EXTERN_C_START + +NTSYSCALLAPI +NTSTATUS +NTAPI +NtCreateFile( + _Out_ PHANDLE FileHandle, + _In_ ACCESS_MASK DesiredAccess, + _In_ POBJECT_ATTRIBUTES ObjectAttributes, + _Out_ PIO_STATUS_BLOCK IoStatusBlock, + _In_opt_ PLARGE_INTEGER AllocationSize, + _In_ ULONG FileAttributes, + _In_ ULONG ShareAccess, + _In_ ULONG CreateDisposition, + _In_ ULONG CreateOptions, + _In_reads_bytes_opt_(EaLength) PVOID EaBuffer, + _In_ ULONG EaLength); + +NTSYSCALLAPI +NTSTATUS +NTAPI +NtReadFile( + _In_ HANDLE FileHandle, + _In_opt_ HANDLE Event, + _In_opt_ PIO_APC_ROUTINE ApcRoutine, + _In_opt_ PVOID ApcContext, + _Out_ PIO_STATUS_BLOCK IoStatusBlock, + _Out_writes_bytes_(Length) PVOID Buffer, + _In_ ULONG Length, + _In_opt_ PLARGE_INTEGER ByteOffset, + _In_opt_ PULONG Key); + +NTSYSCALLAPI +NTSTATUS +NTAPI +NtWriteFile( + _In_ HANDLE FileHandle, + _In_opt_ HANDLE Event, + _In_opt_ PIO_APC_ROUTINE ApcRoutine, + _In_opt_ PVOID ApcContext, + _Out_ PIO_STATUS_BLOCK IoStatusBlock, + _In_reads_bytes_(Length) PVOID Buffer, + _In_ ULONG Length, + _In_opt_ PLARGE_INTEGER ByteOffset, + _In_opt_ PULONG Key); + +NTSYSCALLAPI +NTSTATUS +NTAPI +NtQueryInformationFile( + _In_ HANDLE FileHandle, + _Out_ PIO_STATUS_BLOCK IoStatusBlock, + _Out_writes_bytes_(Length) PVOID FileInformation, + _In_ ULONG Length, + _In_ FILE_INFORMATION_CLASS FileInformationClass); + +NTSYSCALLAPI +NTSTATUS +NTAPI +NtSetInformationFile( + _In_ HANDLE FileHandle, + _Out_ PIO_STATUS_BLOCK IoStatusBlock, + _In_reads_bytes_(Length) PVOID FileInformation, + _In_ ULONG Length, + _In_ FILE_INFORMATION_CLASS FileInformationClass); + +NTSYSCALLAPI +NTSTATUS +NTAPI +NtDeviceIoControlFile( + _In_ HANDLE FileHandle, + _In_opt_ HANDLE Event, + _In_opt_ PIO_APC_ROUTINE ApcRoutine, + _In_opt_ PVOID ApcContext, + _Out_ PIO_STATUS_BLOCK IoStatusBlock, + _In_ ULONG IoControlCode, + _In_reads_bytes_opt_(InputBufferLength) PVOID InputBuffer, + _In_ ULONG InputBufferLength, + _Out_writes_bytes_opt_(OutputBufferLength) PVOID OutputBuffer, + _In_ ULONG OutputBufferLength); + +NTSYSCALLAPI +NTSTATUS +NTAPI +NtFsControlFile( + _In_ HANDLE FileHandle, + _In_opt_ HANDLE Event, + _In_opt_ PIO_APC_ROUTINE ApcRoutine, + _In_opt_ PVOID ApcContext, + _Out_ PIO_STATUS_BLOCK IoStatusBlock, + _In_ ULONG FsControlCode, + _In_reads_bytes_opt_(InputBufferLength) PVOID InputBuffer, + _In_ ULONG InputBufferLength, + _Out_writes_bytes_opt_(OutputBufferLength) PVOID OutputBuffer, + _In_ ULONG OutputBufferLength); + +NTSYSCALLAPI +NTSTATUS +NTAPI +NtOpenFile( + _Out_ PHANDLE FileHandle, + _In_ ACCESS_MASK DesiredAccess, + _In_ POBJECT_ATTRIBUTES ObjectAttributes, + _Out_ PIO_STATUS_BLOCK IoStatusBlock, + _In_ ULONG ShareAccess, + _In_ ULONG OpenOptions); + +NTSYSCALLAPI +NTSTATUS +NTAPI +NtQueryDirectoryFile( + _In_ HANDLE FileHandle, + _In_opt_ HANDLE Event, + _In_opt_ PIO_APC_ROUTINE ApcRoutine, + _In_opt_ PVOID ApcContext, + _Out_ PIO_STATUS_BLOCK IoStatusBlock, + _Out_writes_bytes_(Length) PVOID FileInformation, + _In_ ULONG Length, + _In_ FILE_INFORMATION_CLASS FileInformationClass, + _In_ BOOLEAN ReturnSingleEntry, + _In_opt_ PUNICODE_STRING FileName, + _In_ BOOLEAN RestartScan); + +NTSYSAPI +NTSTATUS +NTAPI +NtQueryAttributesFile( + _In_ POBJECT_ATTRIBUTES ObjectAttributes, + _Out_ PFILE_BASIC_INFORMATION FileInformation); + +NTSYSAPI +NTSTATUS +NTAPI +NtQueryFullAttributesFile( + _In_ POBJECT_ATTRIBUTES ObjectAttributes, + _Out_ PFILE_NETWORK_OPEN_INFORMATION FileInformation); + +EXTERN_C_END diff --git a/Source/Include/KNSoft/NDK/NT/API/Mm.h b/Source/Include/KNSoft/NDK/NT/API/Mm.h new file mode 100644 index 0000000..e35ccf2 --- /dev/null +++ b/Source/Include/KNSoft/NDK/NT/API/Mm.h @@ -0,0 +1,134 @@ +#pragma once + +#include "../../NT/MinDef.h" +#include "../../NT/Types/Mm.h" + +EXTERN_C_START + +#pragma region Virtual Memory + +NTSYSAPI +NTSTATUS +NTAPI +NtProtectVirtualMemory( + _In_ HANDLE ProcessHandle, + _Inout_ _At_(*BaseAddress, + _Readable_bytes_(*RegionSize) + _Writable_bytes_(*RegionSize) + _Post_readable_byte_size_(*RegionSize)) PVOID* BaseAddress, + _Inout_ PSIZE_T RegionSize, + _In_ ULONG Protect, + _Out_ PULONG OldProtect); + +NTSYSAPI +NTSTATUS +NTAPI +NtReadVirtualMemory( + _In_ HANDLE ProcessHandle, + _In_ PVOID BaseAddress, + _Out_ PVOID Buffer, + _In_ SIZE_T NumberOfBytesToRead, + _Out_opt_ PSIZE_T NumberOfBytesRead); + +NTSYSAPI +NTSTATUS +NTAPI +NtWriteVirtualMemory( + _In_ HANDLE ProcessHandle, + _In_ PVOID BaseAddress, + _In_ PVOID Buffer, + _In_ SIZE_T NumberOfBytesToWrite, + _Out_opt_ PSIZE_T NumberOfBytesWritten); + +_Must_inspect_result_ +__drv_allocatesMem(Mem) +NTSYSCALLAPI +NTSTATUS +NTAPI +NtAllocateVirtualMemory( + _In_ HANDLE ProcessHandle, + _Inout_ _At_(*BaseAddress, + _Readable_bytes_(*RegionSize) + _Writable_bytes_(*RegionSize) + _Post_readable_byte_size_(*RegionSize)) PVOID* BaseAddress, + _In_ ULONG_PTR ZeroBits, + _Inout_ PSIZE_T RegionSize, + _In_ ULONG AllocationType, + _In_ ULONG Protect); + +NTSYSCALLAPI +NTSTATUS +NTAPI +NtFreeVirtualMemory( + _In_ HANDLE ProcessHandle, + _Inout_ __drv_freesMem(Mem) PVOID* BaseAddress, + _Inout_ PSIZE_T RegionSize, + _In_ ULONG FreeType); + +_Must_inspect_result_ +NTSYSCALLAPI +NTSTATUS +NTAPI +NtQueryVirtualMemory( + _In_ HANDLE ProcessHandle, + _In_opt_ PVOID BaseAddress, + _In_ MEMORY_INFORMATION_CLASS MemoryInformationClass, + _Out_writes_bytes_(MemoryInformationLength) PVOID MemoryInformation, + _In_ SIZE_T MemoryInformationLength, + _Out_opt_ PSIZE_T ReturnLength); + +#pragma endregion + +#pragma region Section + +_Must_inspect_result_ +NTSYSCALLAPI +NTSTATUS +NTAPI +NtCreateSection( + _Out_ PHANDLE SectionHandle, + _In_ ACCESS_MASK DesiredAccess, + _In_opt_ POBJECT_ATTRIBUTES ObjectAttributes, + _In_opt_ PLARGE_INTEGER MaximumSize, + _In_ ULONG SectionPageProtection, + _In_ ULONG AllocationAttributes, + _In_opt_ HANDLE FileHandle); + +_Must_inspect_result_ +_Post_satisfies_(*ViewSize >= _Old_(*ViewSize)) +_IRQL_requires_max_(PASSIVE_LEVEL) +NTSYSAPI +NTSTATUS +NTAPI +NtMapViewOfSection( + _In_ HANDLE SectionHandle, + _In_ HANDLE ProcessHandle, + _Outptr_result_bytebuffer_(*ViewSize) PVOID* BaseAddress, + _In_ ULONG_PTR ZeroBits, + _In_ SIZE_T CommitSize, + _Inout_opt_ PLARGE_INTEGER SectionOffset, + _Inout_ PSIZE_T ViewSize, + _In_ SECTION_INHERIT InheritDisposition, + _In_ ULONG AllocationType, + _In_ ULONG Win32Protect); + +NTSYSAPI +NTSTATUS +NTAPI +NtUnmapViewOfSection( + _In_ HANDLE ProcessHandle, + _In_opt_ PVOID BaseAddress); + +NTSYSAPI +NTSTATUS +NTAPI +NtQuerySection( + _In_ HANDLE SectionHandle, + _In_ SECTION_INFORMATION_CLASS SectionInformationClass, + _Out_writes_bytes_(SectionInformationLength) PVOID SectionInformation, + _In_ SIZE_T SectionInformationLength, + _Out_opt_ PSIZE_T ReturnLength); + +#pragma endregion + +EXTERN_C_END diff --git a/Source/Include/KNSoft/NDK/NT/API/Ob.h b/Source/Include/KNSoft/NDK/NT/API/Ob.h new file mode 100644 index 0000000..b5a4596 --- /dev/null +++ b/Source/Include/KNSoft/NDK/NT/API/Ob.h @@ -0,0 +1,26 @@ +#pragma once + +#include "../../NT/MinDef.h" +#include "../../NT/Types/Ob.h" + +EXTERN_C_START + +_IRQL_requires_max_(PASSIVE_LEVEL) +NTSYSCALLAPI +NTSTATUS +NTAPI +NtQueryObject( + _In_opt_ HANDLE Handle, + _In_ OBJECT_INFORMATION_CLASS ObjectInformationClass, + _Out_writes_bytes_opt_(ObjectInformationLength) PVOID ObjectInformation, + _In_ ULONG ObjectInformationLength, + _Out_opt_ PULONG ReturnLength); + +_IRQL_requires_max_(PASSIVE_LEVEL) +NTSYSCALLAPI +NTSTATUS +NTAPI +NtClose( + _In_ _Post_ptr_invalid_ HANDLE Handle); + +EXTERN_C_END diff --git a/Source/Include/KNSoft/NDK/NT/API/Ps.h b/Source/Include/KNSoft/NDK/NT/API/Ps.h new file mode 100644 index 0000000..1870acf --- /dev/null +++ b/Source/Include/KNSoft/NDK/NT/API/Ps.h @@ -0,0 +1,118 @@ +#pragma once + +#include "../../NT/MinDef.h" +#include "../../NT/Types/Basic.h" +#include "../../NT/Types/Ps.h" + +EXTERN_C_START + +NTSYSAPI +NTSTATUS +NTAPI +NtOpenThread( + _Out_ PHANDLE ThreadHandle, + _In_ ACCESS_MASK DesiredAccess, + _In_ POBJECT_ATTRIBUTES ObjectAttributes, + _In_ PCLIENT_ID ClientId); + +NTSYSCALLAPI +NTSTATUS +NTAPI +NtOpenProcess( + _Out_ PHANDLE ProcessHandle, + _In_ ACCESS_MASK DesiredAccess, + _In_ POBJECT_ATTRIBUTES ObjectAttributes, + _In_opt_ PCLIENT_ID ClientId); + +NTSYSAPI +NTSTATUS +NTAPI +NtSuspendThread( + _In_ HANDLE ThreadHandle, + _Out_opt_ PULONG SuspendCount); + +NTSYSAPI +NTSTATUS +NTAPI +NtResumeThread( + _In_ HANDLE ThreadHandle, + _Out_opt_ PULONG SuspendCount); + +NTSYSAPI +NTSTATUS +NTAPI +NtQueryInformationThread( + _In_ HANDLE ThreadHandle, + _In_ THREADINFOCLASS ThreadInformationClass, + _Out_writes_bytes_to_(ThreadInformationLength, *ReturnLength) PVOID ThreadInformation, + _In_ ULONG ThreadInformationLength, + _Out_opt_ PULONG ReturnLength); + +NTSYSCALLAPI +NTSTATUS +NTAPI +NtSetInformationThread( + _In_ HANDLE ThreadHandle, + _In_ THREADINFOCLASS ThreadInformationClass, + _When_((ThreadInformationClass != ThreadManageWritesToExecutableMemory), + _In_reads_bytes_(ThreadInformationLength)) + _When_((ThreadInformationClass == ThreadManageWritesToExecutableMemory), + _Inout_updates_(ThreadInformationLength)) + PVOID ThreadInformation, + _In_ ULONG ThreadInformationLength); + +NTSYSAPI +NTSTATUS +NTAPI +NtQueryInformationProcess( + _In_ HANDLE ProcessHandle, + _In_ PROCESSINFOCLASS ProcessInformationClass, + _Out_writes_bytes_to_(ProcessInformationLength, *ReturnLength) PVOID ProcessInformation, + _In_ ULONG ProcessInformationLength, + _Out_opt_ PULONG ReturnLength); + +NTSYSAPI +NTSTATUS +NTAPI +NtFlushInstructionCache( + _In_ HANDLE ProcessHandle, + _In_opt_ PVOID BaseAddress, + _In_ SIZE_T FlushSize); + +NTSYSAPI +NTSTATUS +NTAPI +NtGetContextThread( + _In_ HANDLE ThreadHandle, + _Inout_ PCONTEXT ThreadContext); + +NTSYSAPI +NTSTATUS +NTAPI +NtSetContextThread( + _In_ HANDLE ThreadHandle, + _In_ PCONTEXT ThreadContext); + +NTSYSAPI +NTSTATUS +NTAPI +NtTerminateProcess( + _In_opt_ HANDLE ProcessHandle, + _In_ NTSTATUS ExitStatus); + +NTSYSAPI +NTSTATUS +NTAPI +NtDelayExecution( + _In_ BOOLEAN Alertable, + _In_ PLARGE_INTEGER DelayInterval); + +NTSYSAPI +NTSTATUS +NTAPI +NtWaitForSingleObject( + _In_ HANDLE Handle, + _In_ BOOLEAN Alertable, + _In_opt_ PLARGE_INTEGER Timeout); + +EXTERN_C_END diff --git a/Source/Include/KNSoft/NDK/NT/API/Rtl/Rtl.Bitmap.h b/Source/Include/KNSoft/NDK/NT/API/Rtl/Rtl.Bitmap.h new file mode 100644 index 0000000..7b5d7aa --- /dev/null +++ b/Source/Include/KNSoft/NDK/NT/API/Rtl/Rtl.Bitmap.h @@ -0,0 +1,110 @@ +#pragma once + +#include "../../../NT/MinDef.h" +#include "../../../NT/Types/Rtl.h" + +EXTERN_C_START + +#ifndef _KNSOFT_NDK_NT_INLINE +NTSYSAPI +VOID +NTAPI +RtlInitializeBitMap( + _Out_ PRTL_BITMAP BitMapHeader, + _In_opt_ __drv_aliasesMem PULONG BitMapBuffer, + _In_opt_ ULONG SizeOfBitMap); +#endif + +NTSYSAPI +VOID +NTAPI +RtlClearBit( + _In_ PRTL_BITMAP BitMapHeader, + _In_range_(<, BitMapHeader->SizeOfBitMap) ULONG BitNumber); + +NTSYSAPI +VOID +NTAPI +RtlSetBit( + _In_ PRTL_BITMAP BitMapHeader, + _In_range_(<, BitMapHeader->SizeOfBitMap) ULONG BitNumber); + +_Must_inspect_result_ +NTSYSAPI +BOOLEAN +NTAPI +RtlTestBit( + _In_ PRTL_BITMAP BitMapHeader, + _In_range_(<, BitMapHeader->SizeOfBitMap) ULONG BitNumber); + +NTSYSAPI +VOID +NTAPI +RtlClearAllBits( + _In_ PRTL_BITMAP BitMapHeader); + +NTSYSAPI +VOID +NTAPI +RtlSetAllBits( + _In_ PRTL_BITMAP BitMapHeader); + +_Success_(return != -1) +_Ret_range_(<=, BitMapHeader->SizeOfBitMap - NumberToFind) +_Must_inspect_result_ +NTSYSAPI +ULONG +NTAPI +RtlFindClearBits( + _In_ PRTL_BITMAP BitMapHeader, + _In_ ULONG NumberToFind, + _In_ ULONG HintIndex); + +_Success_(return != -1) +_Ret_range_(<=, BitMapHeader->SizeOfBitMap - NumberToFind) +_Must_inspect_result_ +NTSYSAPI +ULONG +NTAPI +RtlFindSetBits( + _In_ PRTL_BITMAP BitMapHeader, + _In_ ULONG NumberToFind, + _In_ ULONG HintIndex); + +_Success_(return != -1) +_Ret_range_(<=, BitMapHeader->SizeOfBitMap - NumberToFind) +NTSYSAPI +ULONG +NTAPI +RtlFindClearBitsAndSet( + _In_ PRTL_BITMAP BitMapHeader, + _In_ ULONG NumberToFind, + _In_ ULONG HintIndex); + +_Success_(return != -1) +_Ret_range_(<=, BitMapHeader->SizeOfBitMap - NumberToFind) +NTSYSAPI +ULONG +NTAPI +RtlFindSetBitsAndClear( + _In_ PRTL_BITMAP BitMapHeader, + _In_ ULONG NumberToFind, + _In_ ULONG HintIndex); + +NTSYSAPI +VOID +NTAPI +RtlClearBits( + _In_ PRTL_BITMAP BitMapHeader, + _In_range_(0, BitMapHeader->SizeOfBitMap - NumberToClear) ULONG StartingIndex, + _In_range_(0, BitMapHeader->SizeOfBitMap - StartingIndex) ULONG NumberToClear); + +NTSYSAPI +VOID +NTAPI +RtlSetBits( + _In_ PRTL_BITMAP BitMapHeader, + _In_range_(0, BitMapHeader->SizeOfBitMap - NumberToSet) ULONG StartingIndex, + _In_range_(0, BitMapHeader->SizeOfBitMap - StartingIndex) ULONG NumberToSet); + +EXTERN_C_END diff --git a/Source/Include/KNSoft/NDK/NT/API/Rtl/Rtl.Bitmap.inl b/Source/Include/KNSoft/NDK/NT/API/Rtl/Rtl.Bitmap.inl new file mode 100644 index 0000000..b062d08 --- /dev/null +++ b/Source/Include/KNSoft/NDK/NT/API/Rtl/Rtl.Bitmap.inl @@ -0,0 +1,16 @@ +#pragma once + +#include "../../../NT/MinDef.h" +#include "../../../NT/Types/Rtl.h" + +VOID +FORCEINLINE +NTAPI_INLINE +RtlInitializeBitMap( + _Out_ PRTL_BITMAP BitMapHeader, + _In_opt_ __drv_aliasesMem PULONG BitMapBuffer, + _In_opt_ ULONG SizeOfBitMap) +{ + BitMapHeader->SizeOfBitMap = SizeOfBitMap; + BitMapHeader->Buffer = BitMapBuffer; +} diff --git a/Source/Include/KNSoft/NDK/NT/API/Rtl/Rtl.Heap.h b/Source/Include/KNSoft/NDK/NT/API/Rtl/Rtl.Heap.h new file mode 100644 index 0000000..a38ba3b --- /dev/null +++ b/Source/Include/KNSoft/NDK/NT/API/Rtl/Rtl.Heap.h @@ -0,0 +1,111 @@ +#pragma once + +#include "../../../NT/MinDef.h" +#include "../../../NT/Types/Rtl.h" + +EXTERN_C_START + +_Must_inspect_result_ +NTSYSAPI +PVOID +NTAPI +RtlCreateHeap( + _In_ ULONG Flags, + _In_opt_ PVOID HeapBase, + _In_opt_ SIZE_T ReserveSize, + _In_opt_ SIZE_T CommitSize, + _In_opt_ PVOID Lock, + _When_((Flags & 0x100) != 0, + _In_reads_bytes_opt_(sizeof(RTL_SEGMENT_HEAP_PARAMETERS))) + _When_((Flags & 0x100) == 0, + _In_reads_bytes_opt_(sizeof(RTL_HEAP_PARAMETERS))) + PRTL_HEAP_PARAMETERS Parameters); + +NTSYSAPI +ULONG +NTAPI +RtlCreateTagHeap( + _In_ HANDLE HeapHandle, + _In_ ULONG Flags, + _In_opt_ PWSTR TagName, + _In_ PWSTR TagSubName); + +NTSYSAPI +PWSTR +NTAPI +RtlQueryTagHeap( + _In_ HANDLE HeapHandle, + _In_ ULONG Flags, + _In_ USHORT TagIndex, + _In_ BOOLEAN ResetCounters, + _Out_ PRTL_HEAP_TAG_INFO TagInfo); + +_Success_(return != 0) +NTSYSAPI +BOOLEAN +NTAPI +RtlFreeHeap( + _In_ PVOID HeapHandle, + _In_opt_ ULONG Flags, + _Frees_ptr_opt_ PVOID BaseAddress); + +NTSYSAPI +PVOID +NTAPI +RtlDestroyHeap( + _In_ _Post_invalid_ PVOID HeapHandle); + +NTSYSAPI +_Must_inspect_result_ +_Ret_maybenull_ +_Post_writable_byte_size_(Size) +PVOID +NTAPI +RtlAllocateHeap( + _In_ PVOID HeapHandle, + _In_opt_ ULONG Flags, + _In_ SIZE_T Size); + +NTSYSAPI +_Must_inspect_result_ +_Ret_maybenull_ +_Post_writable_byte_size_(Size) +PVOID +NTAPI +RtlReAllocateHeap( + _In_ PVOID HeapHandle, + _In_opt_ ULONG Flags, + _Frees_ptr_opt_ PVOID BaseAddress, + _In_ SIZE_T Size); + +NTSYSAPI +SIZE_T +NTAPI +RtlSizeHeap( + _In_ PVOID HeapHandle, + _In_opt_ ULONG Flags, + _In_ PVOID BaseAddress); + +NTSYSAPI +SIZE_T +NTAPI +RtlCompactHeap( + _In_ PVOID HeapHandle, + _In_ ULONG Flags); + +NTSYSAPI +BOOLEAN +NTAPI +RtlValidateHeap( + _In_ PVOID HeapHandle, + _In_ ULONG Flags, + _In_ PVOID BaseAddress); + +NTSYSAPI +NTSTATUS +NTAPI +RtlWalkHeap( + _In_ PVOID HeapHandle, + _Inout_ PRTL_HEAP_WALK_ENTRY Entry); + +EXTERN_C_END diff --git a/Source/Include/KNSoft/NDK/NT/API/Rtl/Rtl.List.h b/Source/Include/KNSoft/NDK/NT/API/Rtl/Rtl.List.h new file mode 100644 index 0000000..c4dcf65 --- /dev/null +++ b/Source/Include/KNSoft/NDK/NT/API/Rtl/Rtl.List.h @@ -0,0 +1,312 @@ +#pragma once + +#include "../../../NT/MinDef.h" +#include "Rtl.Process.h" + +#define RTL_STATIC_LIST_HEAD(x) LIST_ENTRY x = { &x, &x } + +FORCEINLINE +VOID +InitializeListHead( + _Out_ PLIST_ENTRY ListHead) +{ + ListHead->Flink = ListHead->Blink = ListHead; + return; +} + +_Must_inspect_result_ +BOOLEAN +CFORCEINLINE +IsListEmpty( + _In_ const LIST_ENTRY* ListHead) +{ + return (BOOLEAN)(ListHead->Flink == ListHead); +} + +FORCEINLINE +BOOLEAN +RemoveEntryListUnsafe( + _In_ PLIST_ENTRY Entry) +{ + PLIST_ENTRY Blink; + PLIST_ENTRY Flink; + + Flink = Entry->Flink; + Blink = Entry->Blink; + Blink->Flink = Flink; + Flink->Blink = Blink; + return (BOOLEAN)(Flink == Blink); +} + +#if defined(NO_KERNEL_LIST_ENTRY_CHECKS) + +FORCEINLINE +BOOLEAN +RemoveEntryList( + _In_ PLIST_ENTRY Entry) +{ + PLIST_ENTRY Blink; + PLIST_ENTRY Flink; + + Flink = Entry->Flink; + Blink = Entry->Blink; + Blink->Flink = Flink; + Flink->Blink = Blink; + return (BOOLEAN)(Flink == Blink); +} + +FORCEINLINE +PLIST_ENTRY +RemoveHeadList( + _Inout_ PLIST_ENTRY ListHead) +{ + PLIST_ENTRY Flink; + PLIST_ENTRY Entry; + + Entry = ListHead->Flink; + Flink = Entry->Flink; + ListHead->Flink = Flink; + Flink->Blink = ListHead; + return Entry; +} + +FORCEINLINE +PLIST_ENTRY +RemoveTailList( + _Inout_ PLIST_ENTRY ListHead) +{ + PLIST_ENTRY Blink; + PLIST_ENTRY Entry; + + Entry = ListHead->Blink; + Blink = Entry->Blink; + ListHead->Blink = Blink; + Blink->Flink = ListHead; + return Entry; +} + +FORCEINLINE +VOID +InsertTailList( + _Inout_ PLIST_ENTRY ListHead, + _Inout_ __drv_aliasesMem PLIST_ENTRY Entry) +{ + PLIST_ENTRY Blink; + + Blink = ListHead->Blink; + Entry->Flink = ListHead; + Entry->Blink = Blink; + Blink->Flink = Entry; + ListHead->Blink = Entry; + return; +} + +FORCEINLINE +VOID +InsertHeadList( + _Inout_ PLIST_ENTRY ListHead, + _Inout_ __drv_aliasesMem PLIST_ENTRY Entry) +{ + PLIST_ENTRY Flink; + + Flink = ListHead->Flink; + Entry->Flink = Flink; + Entry->Blink = ListHead; + Flink->Blink = Entry; + ListHead->Flink = Entry; + return; +} + +FORCEINLINE +VOID +AppendTailList( + _Inout_ PLIST_ENTRY ListHead, + _Inout_ PLIST_ENTRY ListToAppend) +{ + PLIST_ENTRY ListEnd = ListHead->Blink; + + ListHead->Blink->Flink = ListToAppend; + ListHead->Blink = ListToAppend->Blink; + ListToAppend->Blink->Flink = ListHead; + ListToAppend->Blink = ListEnd; + return; +} + +#else // NO_KERNEL_LIST_ENTRY_CHECKS + +FORCEINLINE +VOID +FatalListEntryError( + _In_ PVOID p1, + _In_ PVOID p2, + _In_ PVOID p3) +{ + UNREFERENCED_PARAMETER(p1); + UNREFERENCED_PARAMETER(p2); + UNREFERENCED_PARAMETER(p3); + + RtlFailFast(FAST_FAIL_CORRUPT_LIST_ENTRY); +} + +FORCEINLINE +VOID +RtlpCheckListEntry( + _In_ PLIST_ENTRY Entry) +{ + if ((((Entry->Flink)->Blink) != Entry) || (((Entry->Blink)->Flink) != Entry)) + { + FatalListEntryError((PVOID)(Entry), + (PVOID)((Entry->Flink)->Blink), + (PVOID)((Entry->Blink)->Flink)); + } +} + +FORCEINLINE +BOOLEAN +RemoveEntryList( + _In_ PLIST_ENTRY Entry) +{ + PLIST_ENTRY PrevEntry; + PLIST_ENTRY NextEntry; + + NextEntry = Entry->Flink; + PrevEntry = Entry->Blink; + if ((NextEntry->Blink != Entry) || (PrevEntry->Flink != Entry)) + { + FatalListEntryError((PVOID)PrevEntry, + (PVOID)Entry, + (PVOID)NextEntry); + } + + PrevEntry->Flink = NextEntry; + NextEntry->Blink = PrevEntry; + return (BOOLEAN)(PrevEntry == NextEntry); +} + +FORCEINLINE +PLIST_ENTRY +RemoveHeadList( + _Inout_ PLIST_ENTRY ListHead) +{ + PLIST_ENTRY Entry; + PLIST_ENTRY NextEntry; + + Entry = ListHead->Flink; + +#if defined(DBG) || defined(_DEBUG) + RtlpCheckListEntry(ListHead); +#endif + + NextEntry = Entry->Flink; + if ((Entry->Blink != ListHead) || (NextEntry->Blink != Entry)) + { + FatalListEntryError((PVOID)ListHead, + (PVOID)Entry, + (PVOID)NextEntry); + } + + ListHead->Flink = NextEntry; + NextEntry->Blink = ListHead; + + return Entry; +} + +FORCEINLINE +PLIST_ENTRY +RemoveTailList( + _Inout_ PLIST_ENTRY ListHead) +{ + PLIST_ENTRY Entry; + PLIST_ENTRY PrevEntry; + + Entry = ListHead->Blink; + +#if defined(DBG) || defined(_DEBUG) + RtlpCheckListEntry(ListHead); +#endif + + PrevEntry = Entry->Blink; + if ((Entry->Flink != ListHead) || (PrevEntry->Flink != Entry)) + { + FatalListEntryError((PVOID)PrevEntry, + (PVOID)Entry, + (PVOID)ListHead); + } + + ListHead->Blink = PrevEntry; + PrevEntry->Flink = ListHead; + return Entry; +} + +FORCEINLINE +VOID +InsertTailList( + _Inout_ PLIST_ENTRY ListHead, + _Out_ __drv_aliasesMem PLIST_ENTRY Entry) +{ + PLIST_ENTRY PrevEntry; + +#if defined(DBG) || defined(_DEBUG) + RtlpCheckListEntry(ListHead); +#endif + + PrevEntry = ListHead->Blink; + if (PrevEntry->Flink != ListHead) + { + FatalListEntryError((PVOID)PrevEntry, + (PVOID)ListHead, + (PVOID)PrevEntry->Flink); + } + + Entry->Flink = ListHead; + Entry->Blink = PrevEntry; + PrevEntry->Flink = Entry; + ListHead->Blink = Entry; + return; +} + +FORCEINLINE +VOID +InsertHeadList( + _Inout_ PLIST_ENTRY ListHead, + _Out_ __drv_aliasesMem PLIST_ENTRY Entry) +{ + PLIST_ENTRY NextEntry; + +#if defined(DBG) || defined(_DEBUG) + RtlpCheckListEntry(ListHead); +#endif + + NextEntry = ListHead->Flink; + if (NextEntry->Blink != ListHead) + { + FatalListEntryError((PVOID)ListHead, + (PVOID)NextEntry, + (PVOID)NextEntry->Blink); + } + + Entry->Flink = NextEntry; + Entry->Blink = ListHead; + NextEntry->Blink = Entry; + ListHead->Flink = Entry; + return; +} + +FORCEINLINE +VOID +AppendTailList( + _Inout_ PLIST_ENTRY ListHead, + _Inout_ PLIST_ENTRY ListToAppend) +{ + PLIST_ENTRY ListEnd = ListHead->Blink; + + RtlpCheckListEntry(ListHead); + RtlpCheckListEntry(ListToAppend); + ListHead->Blink->Flink = ListToAppend; + ListHead->Blink = ListToAppend->Blink; + ListToAppend->Blink->Flink = ListHead; + ListToAppend->Blink = ListEnd; + return; +} + +#endif // NO_KERNEL_LIST_ENTRY_CHECKS diff --git a/Source/Include/KNSoft/NDK/NT/API/Rtl/Rtl.Path.h b/Source/Include/KNSoft/NDK/NT/API/Rtl/Rtl.Path.h new file mode 100644 index 0000000..32231fd --- /dev/null +++ b/Source/Include/KNSoft/NDK/NT/API/Rtl/Rtl.Path.h @@ -0,0 +1,32 @@ +#pragma once + +#include "../../../NT/MinDef.h" +#include "../../../NT/Types/Rtl.h" + +EXTERN_C_START + +NTSYSAPI +BOOLEAN +NTAPI +RtlDosPathNameToNtPathName_U( + _In_opt_z_ LPCWSTR DosName, + _Out_ PUNICODE_STRING NtName, + _Out_opt_ LPCWSTR* PartName, + _Out_opt_ PRTL_RELATIVE_NAME_U RelativeName); + +NTSYSAPI +NTSTATUS +NTAPI +RtlDosPathNameToNtPathName_U_WithStatus( + _In_opt_z_ LPCWSTR DosName, + _Out_ PUNICODE_STRING NtName, + _Out_opt_ LPCWSTR* PartName, + _Out_opt_ PRTL_RELATIVE_NAME_U RelativeName); + +NTSYSAPI +VOID +NTAPI +RtlReleaseRelativeName( + _In_ PRTL_RELATIVE_NAME_U RelativeName); + +EXTERN_C_END diff --git a/Source/Include/KNSoft/NDK/NT/API/Rtl/Rtl.Process.h b/Source/Include/KNSoft/NDK/NT/API/Rtl/Rtl.Process.h new file mode 100644 index 0000000..b13a9d5 --- /dev/null +++ b/Source/Include/KNSoft/NDK/NT/API/Rtl/Rtl.Process.h @@ -0,0 +1,145 @@ +#pragma once + +#include "../../../NT/MinDef.h" +#include "../../../NT/Types/Basic.h" + +#include + +EXTERN_C_START + +NTSYSAPI +NTSTATUS +NTAPI +RtlCreateUserThread( + _In_ HANDLE hProcess, + _In_opt_ PSECURITY_DESCRIPTOR ThreadSecurityDescriptor, + _In_ BOOLEAN CreateSuspended, + _In_opt_ ULONG ZeroBits, + _In_opt_ SIZE_T MaximumStackSize, + _In_opt_ SIZE_T CommittedStackSize, + _In_ LPTHREAD_START_ROUTINE StartAddress, + _In_opt_ PVOID Parameter, + _Out_opt_ PHANDLE hThread, + _Out_opt_ PCLIENT_ID ClientId); + +NTSYSAPI +VOID +NTAPI +RtlExitUserThread( + _In_ NTSTATUS ExitStatus); + +typedef ULONG +(NTAPI* RTLP_UNHANDLED_EXCEPTION_FILTER)( + _In_ PEXCEPTION_POINTERS ExceptionInfo); +typedef RTLP_UNHANDLED_EXCEPTION_FILTER* PRTLP_UNHANDLED_EXCEPTION_FILTER; + +NTSYSAPI +VOID +NTAPI +RtlSetUnhandledExceptionFilter( + _In_opt_ PRTLP_UNHANDLED_EXCEPTION_FILTER TopLevelExceptionFilter); + +NTSYSAPI +VOID +DECLSPEC_NORETURN +NTAPI +RtlExitUserProcess( + _In_ NTSTATUS ExitStatus); + +NTSYSAPI +NTSTATUS +NTAPI +RtlSetCurrentDirectory_U( + _In_ PUNICODE_STRING name); + +NTSYSAPI +NTSTATUS +NTAPI +RtlSetEnvironmentVariable( + _In_z_ PWSTR* Environment, + _In_ PUNICODE_STRING Name, + _In_ PUNICODE_STRING Value); + +NTSYSAPI +NTSTATUS +NTAPI +RtlGetLastNtStatus(); + +NTSYSAPI +ULONG +NTAPI +RtlGetLastWin32Error(); + +NTSYSAPI +ULONG +NTAPI +RtlSetLastWin32Error( + _In_ ULONG LastError); + +_IRQL_requires_max_(APC_LEVEL) +_When_(Status < 0, _Out_range_(>, 0)) +_When_(Status >= 0, _Out_range_(==, 0)) +NTSYSAPI +ULONG +NTAPI +RtlNtStatusToDosError( + _In_ NTSTATUS Status); + +_When_(Status < 0, _Out_range_(>, 0)) +_When_(Status >= 0, _Out_range_(==, 0)) +NTSYSAPI +ULONG +NTAPI +RtlNtStatusToDosErrorNoTeb( + _In_ NTSTATUS Status); + +NTSYSAPI +VOID +NTAPI +RtlRaiseStatus( + _In_ NTSTATUS Status); + +DECLSPEC_NORETURN +FORCEINLINE +VOID +RtlFailFast( + _In_ ULONG Code) +{ + __fastfail(Code); +} + +NTSYSAPI +VOID +NTAPI +RtlGetCallersAddress( + _Out_ PVOID* CallersAddress, + _Out_ PVOID* CallersCaller); + +NTSYSAPI +NTSTATUS +NTAPI +RtlWow64EnableFsRedirectionEx( + _In_ PVOID Wow64FsEnableRedirection, + _Out_ PVOID* OldFsRedirectionLevel); + +NTSYSAPI +NTSTATUS +NTAPI +RtlGetUserPreferredUILanguages( + _In_ ULONG Flags, + _In_opt_ PCWSTR LocaleName, + _Out_ PULONG NumLanguages, + _Out_writes_opt_z_(*LanguagesCchSize) PWSTR LanguagesBuffer, + _Inout_ PULONG LanguagesCchSize); + +NTSYSAPI +NTSTATUS +NTAPI +RtlFindMessage( + _In_ PVOID BaseAddress, + _In_ ULONG Type, + _In_ ULONG Language, + _In_ ULONG MessageId, + _Out_ PMESSAGE_RESOURCE_ENTRY* MessageResourceEntry); + +EXTERN_C_END diff --git a/Source/Include/KNSoft/NDK/NT/API/Rtl/Rtl.Random.h b/Source/Include/KNSoft/NDK/NT/API/Rtl/Rtl.Random.h new file mode 100644 index 0000000..ae8a709 --- /dev/null +++ b/Source/Include/KNSoft/NDK/NT/API/Rtl/Rtl.Random.h @@ -0,0 +1,23 @@ +#pragma once + +#include "../../../NT/MinDef.h" + +EXTERN_C_START + +_IRQL_requires_max_(APC_LEVEL) +_Ret_range_(<=, MAXLONG) +NTSYSAPI +ULONG +NTAPI +RtlRandom( + _Inout_ PULONG Seed); + +_IRQL_requires_max_(APC_LEVEL) +_Ret_range_(<=, MAXLONG) +NTSYSAPI +ULONG +NTAPI +RtlRandomEx( + _Inout_ PULONG Seed); + +EXTERN_C_END diff --git a/Source/Include/KNSoft/NDK/NT/API/Rtl/Rtl.Security.h b/Source/Include/KNSoft/NDK/NT/API/Rtl/Rtl.Security.h new file mode 100644 index 0000000..03243d3 --- /dev/null +++ b/Source/Include/KNSoft/NDK/NT/API/Rtl/Rtl.Security.h @@ -0,0 +1,109 @@ +#pragma once + +#include "../../../NT/MinDef.h" + +EXTERN_C_START + +// +// BOOLEAN +// RtlEqualLuid( +// PLUID L1, +// PLUID L2 +// ); + +#define RtlEqualLuid(L1, L2) (((L1)->LowPart == (L2)->LowPart) && \ + ((L1)->HighPart == (L2)->HighPart)) + +// +// BOOLEAN +// RtlIsZeroLuid( +// PLUID L1 +// ); +// +#define RtlIsZeroLuid(L1) ((BOOLEAN) (((L1)->LowPart | (L1)->HighPart) == 0)) + +FORCEINLINE +LUID +NTAPI_INLINE +RtlConvertLongToLuid(_In_ LONG Long) +{ + LUID TempLuid; + LARGE_INTEGER TempLi; + + TempLi.QuadPart = Long; + TempLuid.LowPart = TempLi.u.LowPart; + TempLuid.HighPart = TempLi.u.HighPart; + return(TempLuid); +} + +FORCEINLINE +LUID +NTAPI_INLINE +RtlConvertUlongToLuid(_In_ ULONG Ulong) +{ + LUID TempLuid; + + TempLuid.LowPart = Ulong; + TempLuid.HighPart = 0; + return(TempLuid); +} + +#ifndef _KNSOFT_NDK_NT_INLINE +_Post_satisfies_(return >= 8 && return <= SECURITY_MAX_SID_SIZE) +ULONG +NTSYSAPI +NTAPI +RtlLengthSid( + _In_ PSID Sid); +#endif + +NTSYSAPI +NTSTATUS +NTAPI +RtlCreateSecurityDescriptor( + _Out_ PSECURITY_DESCRIPTOR SecurityDescriptor, + _In_ ULONG Revision); + +NTSYSAPI +NTSTATUS +NTAPI +RtlSetOwnerSecurityDescriptor( + _Inout_ PSECURITY_DESCRIPTOR SecurityDescriptor, + _In_opt_ PSID Owner, + _In_ BOOLEAN OwnerDefaulted); + +NTSYSAPI +NTSTATUS +NTAPI +RtlSetGroupSecurityDescriptor( + _Inout_ PSECURITY_DESCRIPTOR SecurityDescriptor, + _In_opt_ PSID Group, + _In_ BOOLEAN GroupDefaulted); + +NTSYSAPI +NTSTATUS +NTAPI +RtlCreateAcl( + _Out_writes_bytes_(AclLength) PACL Acl, + _In_ ULONG AclLength, + _In_ ULONG AclRevision); + +NTSYSAPI +NTSTATUS +NTAPI +RtlAddAccessAllowedAce( + _Inout_ PACL Acl, + _In_ ULONG AceRevision, + _In_ ACCESS_MASK AccessMask, + _In_ PSID Sid); + +NTSYSAPI +NTSTATUS +NTAPI +RtlSetDaclSecurityDescriptor( + _Inout_ PSECURITY_DESCRIPTOR SecurityDescriptor, + _In_ BOOLEAN DaclPresent, + _In_opt_ PACL Dacl, + _In_ BOOLEAN DaclDefaulted); + +EXTERN_C_END diff --git a/Source/Include/KNSoft/NDK/NT/API/Rtl/Rtl.Security.inl b/Source/Include/KNSoft/NDK/NT/API/Rtl/Rtl.Security.inl new file mode 100644 index 0000000..a816fe2 --- /dev/null +++ b/Source/Include/KNSoft/NDK/NT/API/Rtl/Rtl.Security.inl @@ -0,0 +1,13 @@ +#pragma once + +#include "../../../NT/MinDef.h" + +_Post_satisfies_(return >= 8 && return <= SECURITY_MAX_SID_SIZE) +ULONG +FORCEINLINE +NTAPI_INLINE +RtlLengthSid( + _In_ PSID Sid) +{ + return UFIELD_OFFSET(SID, SubAuthority[Sid->SubAuthorityCount]); +} diff --git a/Source/Include/KNSoft/NDK/NT/API/Rtl/Rtl.String.h b/Source/Include/KNSoft/NDK/NT/API/Rtl/Rtl.String.h new file mode 100644 index 0000000..db4b3ae --- /dev/null +++ b/Source/Include/KNSoft/NDK/NT/API/Rtl/Rtl.String.h @@ -0,0 +1,181 @@ +#pragma once + +#include "../../../NT/MinDef.h" + +EXTERN_C_START + +_IRQL_requires_max_(PASSIVE_LEVEL) +_Must_inspect_result_ +NTSYSAPI +LONG +NTAPI +RtlCompareString( + _In_ const STRING* String1, + _In_ const STRING* String2, + _In_ BOOLEAN CaseInSensitive); + +_IRQL_requires_max_(PASSIVE_LEVEL) +_Must_inspect_result_ +NTSYSAPI +BOOLEAN +NTAPI +RtlEqualString( + _In_ const STRING* String1, + _In_ const STRING* String2, + _In_ BOOLEAN CaseInSensitive); + +_IRQL_requires_max_(PASSIVE_LEVEL) +NTSYSAPI +NTSTATUS +NTAPI +RtlUnicodeStringToInteger( + _In_ PCUNICODE_STRING String, + _In_opt_ ULONG Base, + _Out_ PULONG Value); + +_IRQL_requires_max_(PASSIVE_LEVEL) +_At_(String->MaximumLength, _Const_) +NTSYSAPI +NTSTATUS +NTAPI +RtlIntegerToUnicodeString( + _In_ ULONG Value, + _In_opt_ ULONG Base, + _Inout_ PUNICODE_STRING String); + +_IRQL_requires_max_(DISPATCH_LEVEL) +NTSYSAPI +VOID +NTAPI +RtlInitAnsiString( + _Out_ PANSI_STRING DestinationString, + _In_opt_z_ __drv_aliasesMem PCSZ SourceString); + +_IRQL_requires_max_(DISPATCH_LEVEL) +_At_(DestinationString->Buffer, _Post_equal_to_(SourceString)) +_At_(DestinationString->Length, _Post_equal_to_(_String_length_(SourceString) * sizeof(WCHAR))) +_At_(DestinationString->MaximumLength, _Post_equal_to_((_String_length_(SourceString) + 1) * sizeof(WCHAR))) +NTSYSAPI +VOID +NTAPI +RtlInitUnicodeString( + _Out_ PUNICODE_STRING DestinationString, + _In_opt_z_ __drv_aliasesMem PCWSTR SourceString); + +_IRQL_requires_max_(PASSIVE_LEVEL) +_Must_inspect_result_ +NTSYSAPI +NTSTATUS +NTAPI +RtlAnsiStringToUnicodeString( + _When_(AllocateDestinationString, _Out_ _At_(DestinationString->Buffer, __drv_allocatesMem(Mem))) + _When_(!AllocateDestinationString, _Inout_) + PUNICODE_STRING DestinationString, + _In_ PCANSI_STRING SourceString, + _In_ BOOLEAN AllocateDestinationString); + +_When_(AllocateDestinationString, + _At_(DestinationString->MaximumLength, + _Out_range_(<=, (SourceString->MaximumLength / sizeof(WCHAR)))) +) +_When_(!AllocateDestinationString, + _At_(DestinationString->Buffer, _Const_) + _At_(DestinationString->MaximumLength, _Const_) +) +_IRQL_requires_max_(PASSIVE_LEVEL) +_When_(AllocateDestinationString, _Must_inspect_result_) +NTSYSAPI +NTSTATUS +NTAPI +RtlUnicodeStringToAnsiString( + _When_(AllocateDestinationString, _Out_ _At_(DestinationString->Buffer, __drv_allocatesMem(Mem))) + _When_(!AllocateDestinationString, _Inout_) + PANSI_STRING DestinationString, + _In_ PCUNICODE_STRING SourceString, + _In_ BOOLEAN AllocateDestinationString); + +_IRQL_requires_max_(PASSIVE_LEVEL) +_Must_inspect_result_ +NTSYSAPI +LONG +NTAPI +RtlCompareUnicodeStrings( + _In_reads_(String1Length) PCWCH String1, + _In_ SIZE_T String1Length, + _In_reads_(String2Length) PCWCH String2, + _In_ SIZE_T String2Length, + _In_ BOOLEAN CaseInSensitive); + +_IRQL_requires_max_(PASSIVE_LEVEL) +_Must_inspect_result_ +NTSYSAPI +LONG +NTAPI +RtlCompareUnicodeString( + _In_ PCUNICODE_STRING String1, + _In_ PCUNICODE_STRING String2, + _In_ BOOLEAN CaseInSensitive); + +_IRQL_requires_max_(PASSIVE_LEVEL) +_Must_inspect_result_ +NTSYSAPI +BOOLEAN +NTAPI +RtlEqualUnicodeString( + _In_ PCUNICODE_STRING String1, + _In_ PCUNICODE_STRING String2, + _In_ BOOLEAN CaseInSensitive); + +_IRQL_requires_max_(DISPATCH_LEVEL) +NTSYSAPI +NTSTATUS +NTAPI +RtlInitUnicodeStringEx( + _Out_ PUNICODE_STRING DestinationString, + _In_opt_z_ __drv_aliasesMem PCWSTR SourceString); + +_IRQL_requires_max_(DISPATCH_LEVEL) +NTSYSAPI +NTSTATUS +NTAPI +RtlInitAnsiStringEx( + _Out_ PANSI_STRING DestinationString, + _In_opt_z_ __drv_aliasesMem PCSZ SourceString); + +_IRQL_requires_max_(PASSIVE_LEVEL) +NTSYSAPI +NTSTATUS +NTAPI +RtlMultiByteToUnicodeN( + _Out_writes_bytes_to_(MaxBytesInUnicodeString, *BytesInUnicodeString) PWCH UnicodeString, + _In_ ULONG MaxBytesInUnicodeString, + _Out_opt_ PULONG BytesInUnicodeString, + _In_reads_bytes_(BytesInMultiByteString) const CHAR* MultiByteString, + _In_ ULONG BytesInMultiByteString); + +_IRQL_requires_max_(PASSIVE_LEVEL) +NTSYSAPI +NTSTATUS +NTAPI +RtlUnicodeToMultiByteN( + _Out_writes_bytes_to_(MaxBytesInMultiByteString, *BytesInMultiByteString) PCHAR MultiByteString, + _In_ ULONG MaxBytesInMultiByteString, + _Out_opt_ PULONG BytesInMultiByteString, + _In_reads_bytes_(BytesInUnicodeString) PCWCH UnicodeString, + _In_ ULONG BytesInUnicodeString); + +_IRQL_requires_max_(PASSIVE_LEVEL) +NTSYSAPI +VOID +NTAPI +RtlFreeUnicodeString( + _Inout_ _At_(UnicodeString->Buffer, _Frees_ptr_opt_) PUNICODE_STRING UnicodeString); + +_IRQL_requires_max_(PASSIVE_LEVEL) +NTSYSAPI +VOID +NTAPI +RtlFreeAnsiString( + _Inout_ _At_(AnsiString->Buffer, _Frees_ptr_opt_) PANSI_STRING AnsiString); + +EXTERN_C_END diff --git a/Source/Include/KNSoft/NDK/NT/API/Rtl/Rtl.Synchronization.h b/Source/Include/KNSoft/NDK/NT/API/Rtl/Rtl.Synchronization.h new file mode 100644 index 0000000..23a434a --- /dev/null +++ b/Source/Include/KNSoft/NDK/NT/API/Rtl/Rtl.Synchronization.h @@ -0,0 +1,123 @@ +#pragma once + +#include "../../../NT/MinDef.h" +#include "../../../NT/Types/Rtl.h" + +EXTERN_C_START + +#pragma region Critical Section + +NTSYSAPI +VOID +NTAPI +RtlInitializeCriticalSection( + _Out_ PRTL_CRITICAL_SECTION lpCriticalSection); + +NTSYSAPI +VOID +NTAPI +RtlEnterCriticalSection( + _Inout_ PRTL_CRITICAL_SECTION lpCriticalSection); + +NTSYSAPI +VOID +NTAPI +RtlLeaveCriticalSection( + _Inout_ PRTL_CRITICAL_SECTION lpCriticalSection); + +NTSYSAPI +VOID +NTAPI +RtlDeleteCriticalSection( + _Inout_ PRTL_CRITICAL_SECTION lpCriticalSection); + +#pragma endregion + +#pragma region One-Time initialization + +#ifndef _KNSOFT_NDK_NT_INLINE +NTSYSAPI +VOID +NTAPI +RtlRunOnceInitialize( + _Out_ PRTL_RUN_ONCE RunOnce); +#endif + +_Maybe_raises_SEH_exception_ +NTSYSAPI +NTSTATUS +NTAPI +RtlRunOnceExecuteOnce( + _Inout_ PRTL_RUN_ONCE RunOnce, + _In_ __callback PRTL_RUN_ONCE_INIT_FN InitFn, + _Inout_opt_ PVOID Parameter, + _Outptr_opt_result_maybenull_ PVOID* Context); + +_Must_inspect_result_ +NTSYSAPI +NTSTATUS +NTAPI +RtlRunOnceBeginInitialize( + _Inout_ PRTL_RUN_ONCE RunOnce, + _In_ ULONG Flags, + _Outptr_opt_result_maybenull_ PVOID* Context); + +NTSYSAPI +NTSTATUS +NTAPI +RtlRunOnceComplete( + _Inout_ PRTL_RUN_ONCE RunOnce, + _In_ ULONG Flags, + _In_opt_ PVOID Context); + +#pragma endregion + +#pragma region SRW Lock + +#ifndef _KNSOFT_NDK_NT_INLINE +NTSYSAPI +VOID +NTAPI +RtlInitializeSRWLock( + _Out_ PRTL_SRWLOCK SRWLock); +#endif + +NTSYSAPI +VOID +NTAPI +RtlAcquireSRWLockExclusive( + _Inout_ PRTL_SRWLOCK SRWLock); + +NTSYSAPI +VOID +NTAPI +RtlAcquireSRWLockShared( + _Inout_ PRTL_SRWLOCK SRWLock); + +NTSYSAPI +VOID +NTAPI +RtlReleaseSRWLockExclusive( + _Inout_ PRTL_SRWLOCK SRWLock); + +NTSYSAPI +VOID +NTAPI +RtlReleaseSRWLockShared( + _Inout_ PRTL_SRWLOCK SRWLock); + +NTSYSAPI +BOOLEAN +NTAPI +RtlTryAcquireSRWLockExclusive( + _Inout_ PRTL_SRWLOCK SRWLock); + +NTSYSAPI +BOOLEAN +NTAPI +RtlTryAcquireSRWLockShared( + _Inout_ PRTL_SRWLOCK SRWLock); + +#pragma endregion + +EXTERN_C_END diff --git a/Source/Include/KNSoft/NDK/NT/API/Rtl/Rtl.Synchronization.inl b/Source/Include/KNSoft/NDK/NT/API/Rtl/Rtl.Synchronization.inl new file mode 100644 index 0000000..4fc3389 --- /dev/null +++ b/Source/Include/KNSoft/NDK/NT/API/Rtl/Rtl.Synchronization.inl @@ -0,0 +1,21 @@ +#pragma once + +#include "../../../NT/MinDef.h" + +VOID +FORCEINLINE +NTAPI_INLINE +RtlRunOnceInitialize( + _Out_ PRTL_RUN_ONCE RunOnce) +{ + *RunOnce = RTL_RUN_ONCE_INIT; +} + +VOID +FORCEINLINE +NTAPI_INLINE +RtlInitializeSRWLock( + _Out_ PRTL_SRWLOCK SRWLock) +{ + *SRWLock = RTL_SRWLOCK_INIT; +} diff --git a/Source/Include/KNSoft/NDK/NT/API/Rtl/Rtl.h b/Source/Include/KNSoft/NDK/NT/API/Rtl/Rtl.h new file mode 100644 index 0000000..7bc7b7e --- /dev/null +++ b/Source/Include/KNSoft/NDK/NT/API/Rtl/Rtl.h @@ -0,0 +1,16 @@ +#pragma once + +#include "Rtl.Bitmap.h" +#include "Rtl.String.h" +#include "Rtl.Path.h" +#include "Rtl.Heap.h" +#include "Rtl.Process.h" +#include "Rtl.List.h" +#include "Rtl.Security.h" +#include "Rtl.Synchronization.h" + +#ifdef _KNSOFT_NDK_NT_INLINE +#include "Rtl.Bitmap.inl" +#include "Rtl.Security.inl" +#include "Rtl.Synchronization.inl" +#endif diff --git a/Source/Include/KNSoft/NDK/NT/API/Se.h b/Source/Include/KNSoft/NDK/NT/API/Se.h new file mode 100644 index 0000000..24c6c87 --- /dev/null +++ b/Source/Include/KNSoft/NDK/NT/API/Se.h @@ -0,0 +1,105 @@ +#pragma once + +#include "../../NT/MinDef.h" + +EXTERN_C_START + +NTSYSAPI +NTSTATUS +NTAPI +NtCreateToken( + _Out_ PHANDLE TokenHandle, + _In_ ACCESS_MASK DesiredAccess, + _In_opt_ POBJECT_ATTRIBUTES ObjectAttributes, + _In_ TOKEN_TYPE TokenType, + _In_ PLUID AuthenticationId, + _In_ PLARGE_INTEGER ExpirationTime, + _In_ PTOKEN_USER TokenUser, + _In_ PTOKEN_GROUPS TokenGroups, + _In_ PTOKEN_PRIVILEGES TokenPrivileges, + _In_opt_ PTOKEN_OWNER TokenOwner, + _In_ PTOKEN_PRIMARY_GROUP TokenPrimaryGroup, + _In_opt_ PTOKEN_DEFAULT_DACL TokenDefaultDacl, + _In_ PTOKEN_SOURCE TokenSource); + +_Must_inspect_result_ +NTSYSCALLAPI +NTSTATUS +NTAPI +NtOpenProcessToken( + _In_ HANDLE ProcessHandle, + _In_ ACCESS_MASK DesiredAccess, + _Out_ PHANDLE TokenHandle); + +_Must_inspect_result_ +NTSYSCALLAPI +NTSTATUS +NTAPI +NtOpenThreadToken( + _In_ HANDLE ThreadHandle, + _In_ ACCESS_MASK DesiredAccess, + _In_ BOOLEAN OpenAsSelf, + _Out_ PHANDLE TokenHandle); + +_When_(TokenInformationClass == TokenAccessInformation, + _At_(TokenInformationLength, _In_range_(>=, sizeof(TOKEN_ACCESS_INFORMATION))) +) +_Must_inspect_result_ +NTSYSCALLAPI +NTSTATUS +NTAPI +NtQueryInformationToken( + _In_ HANDLE TokenHandle, + _In_ TOKEN_INFORMATION_CLASS TokenInformationClass, + _Out_writes_bytes_to_opt_(TokenInformationLength, *ReturnLength) PVOID TokenInformation, + _In_ ULONG TokenInformationLength, + _Out_ PULONG ReturnLength); + +_Must_inspect_result_ +NTSYSCALLAPI +NTSTATUS +NTAPI +NtSetInformationToken( + _In_ HANDLE TokenHandle, + _In_ TOKEN_INFORMATION_CLASS TokenInformationClass, + _In_reads_bytes_(TokenInformationLength) PVOID TokenInformation, + _In_ ULONG TokenInformationLength); + +_Must_inspect_result_ +NTSYSCALLAPI +NTSTATUS +NTAPI +NtAdjustPrivilegesToken( + _In_ HANDLE TokenHandle, + _In_ BOOLEAN DisableAllPrivileges, + _In_opt_ PTOKEN_PRIVILEGES NewState, + _In_ ULONG BufferLength, + _Out_writes_bytes_to_opt_(BufferLength, *ReturnLength) PTOKEN_PRIVILEGES PreviousState, + _Out_ _When_(PreviousState == NULL, _Out_opt_) PULONG ReturnLength); + +_Must_inspect_result_ +NTSYSCALLAPI +NTSTATUS +NTAPI +NtDuplicateToken( + _In_ HANDLE ExistingTokenHandle, + _In_ ACCESS_MASK DesiredAccess, + _In_opt_ POBJECT_ATTRIBUTES ObjectAttributes, + _In_ BOOLEAN EffectiveOnly, + _In_ TOKEN_TYPE TokenType, + _Out_ PHANDLE NewTokenHandle); + +NTSYSCALLAPI +NTSTATUS +NTAPI +NtAccessCheck( + _In_ PSECURITY_DESCRIPTOR SecurityDescriptor, + _In_ HANDLE ClientToken, + _In_ ACCESS_MASK DesiredAccess, + _In_ PGENERIC_MAPPING GenericMapping, + _Out_writes_bytes_(*PrivilegeSetLength) PPRIVILEGE_SET PrivilegeSet, + _Inout_ PULONG PrivilegeSetLength, + _Out_ PACCESS_MASK GrantedAccess, + _Out_ PNTSTATUS AccessStatus); + +EXTERN_C_END diff --git a/Source/Include/KNSoft/NDK/NT/API/Sys.h b/Source/Include/KNSoft/NDK/NT/API/Sys.h new file mode 100644 index 0000000..cfce4ee --- /dev/null +++ b/Source/Include/KNSoft/NDK/NT/API/Sys.h @@ -0,0 +1,42 @@ +#pragma once + +#include "../../NT/MinDef.h" +#include "../../NT/Types/Sys.h" + +EXTERN_C_START + +NTSYSAPI +NTSTATUS +NTAPI +NtLoadDriver( + _In_ PUNICODE_STRING DriverServiceName); + +NTSYSAPI +NTSTATUS +NTAPI +NtUnloadDriver( + _In_ PUNICODE_STRING DriverServiceName); + +NTSYSAPI +NTSTATUS +NTAPI +NtQuerySystemInformation( + _In_ SYSTEM_INFORMATION_CLASS SystemInformationClass, + _Out_writes_bytes_to_(SystemInformationLength, *ReturnLength) PVOID SystemInformation, + _In_ ULONG SystemInformationLength, + _Out_opt_ PULONG ReturnLength); + +NTSYSAPI +NTSTATUS +NTAPI +NtQueryPerformanceCounter( + _Out_ PLARGE_INTEGER PerformanceCounter, + _Out_opt_ PLARGE_INTEGER PerformanceFrequency); + +NTSYSAPI +NTSTATUS +NTAPI +NtQuerySystemTime( + _Out_ PLARGE_INTEGER SystemTime); + +EXTERN_C_END diff --git a/Source/Include/KNSoft/NDK/NT/API/Wow.h b/Source/Include/KNSoft/NDK/NT/API/Wow.h new file mode 100644 index 0000000..3d466c1 --- /dev/null +++ b/Source/Include/KNSoft/NDK/NT/API/Wow.h @@ -0,0 +1,60 @@ +#pragma once + +#include "../../NT/MinDef.h" +#include "../../NT/Types/Ps.h" + +EXTERN_C_START + +#pragma region Wow64 + +/* Caution: Exported from Wow Ntdll.dll only!!! */ + +_Must_inspect_result_ +__drv_allocatesMem(Mem) +NTSYSCALLAPI +NTSTATUS +NTAPI +NtWow64AllocateVirtualMemory64( + _In_ HANDLE ProcessHandle, + _Inout_ _At_(*BaseAddress, + _Readable_bytes_(*RegionSize) + _Writable_bytes_(*RegionSize) + _Post_readable_byte_size_(*RegionSize)) PULONGLONG BaseAddress, + _In_ ULONGLONG ZeroBits, + _Inout_ PULONGLONG RegionSize, + _In_ ULONG AllocationType, + _In_ ULONG Protect); + +NTSYSAPI +NTSTATUS +NTAPI +NtWow64QueryInformationProcess64( + _In_ HANDLE ProcessHandle, + _In_ PROCESSINFOCLASS ProcessInformationClass, + _Out_writes_bytes_to_(ProcessInformationLength, *ReturnLength) PVOID ProcessInformation, + _In_ ULONG ProcessInformationLength, + _Out_opt_ PULONG ReturnLength); + +NTSYSAPI +NTSTATUS +NTAPI +NtWow64ReadVirtualMemory64( + _In_ HANDLE ProcessHandle, + _In_ ULONGLONG BaseAddress, + _Out_ PVOID Buffer, + _In_ ULONGLONG NumberOfBytesToRead, + _Out_opt_ PULONGLONG NumberOfBytesRead); + +NTSYSAPI +NTSTATUS +NTAPI +NtWow64WriteVirtualMemory64( + _In_ HANDLE ProcessHandle, + _In_ ULONGLONG BaseAddress, + _In_ PVOID Buffer, + _In_ ULONGLONG NumberOfBytesToWrite, + _Out_opt_ ULONGLONG NumberOfBytesWritten); + +#pragma endregion + +EXTERN_C_END diff --git a/Source/Include/KNSoft/NDK/NT/Extension.h b/Source/Include/KNSoft/NDK/NT/Extension.h new file mode 100644 index 0000000..d91ac19 --- /dev/null +++ b/Source/Include/KNSoft/NDK/NT/Extension.h @@ -0,0 +1,96 @@ +#pragma once + +#include "MinDef.h" + +#include "Types/Types.h" + +#pragma region TEB/PEB fast access + +#if defined(_M_X64) + +#define ReadTeb(m) (\ + RTL_FIELD_SIZE(TEB, m) == sizeof(ULONGLONG) ? __readgsqword(UFIELD_OFFSET(TEB, m)) : (\ + RTL_FIELD_SIZE(TEB, m) == sizeof(ULONG) ? __readgsdword(UFIELD_OFFSET(TEB, m)) : (\ + RTL_FIELD_SIZE(TEB, m) == sizeof(USHORT) ? __readgsword(UFIELD_OFFSET(TEB, m)) :\ + __readgsbyte(UFIELD_OFFSET(TEB, m))\ + )\ + )\ +) + +#define WriteTeb(m, val) (\ + RTL_FIELD_SIZE(TEB, m) == sizeof(ULONGLONG) ? __writegsqword(UFIELD_OFFSET(TEB, m), (ULONGLONG)(val)) : (\ + RTL_FIELD_SIZE(TEB, m) == sizeof(ULONG) ? __writegsdword(UFIELD_OFFSET(TEB, m), (ULONG)(val)) : (\ + RTL_FIELD_SIZE(TEB, m) == sizeof(USHORT) ? __writegsword(UFIELD_OFFSET(TEB, m), (USHORT)(val)) :\ + __writegsbyte(UFIELD_OFFSET(TEB, m), (UCHAR)(val))\ + )\ + )\ +) + +#elif defined(_M_IX86) + +#define ReadTeb(m) (\ + RTL_FIELD_SIZE(TEB, m) == sizeof(ULONG) ? __readfsdword(UFIELD_OFFSET(TEB, m)) : (\ + RTL_FIELD_SIZE(TEB, m) == sizeof(USHORT) ? __readfsword(UFIELD_OFFSET(TEB, m)) :\ + __readfsbyte(UFIELD_OFFSET(TEB, m))\ + )\ +) + +#define WriteTeb(m, val) (\ + RTL_FIELD_SIZE(TEB, m) == sizeof(ULONG) ? __writefsdword(UFIELD_OFFSET(TEB, m), (ULONG)(val)) : (\ + RTL_FIELD_SIZE(TEB, m) == sizeof(USHORT) ? __writefsword(UFIELD_OFFSET(TEB, m), (USHORT)(val)) :\ + __writefsbyte(UFIELD_OFFSET(TEB, m), (UCHAR)(val))\ + )\ +) + +#else + +#define ReadTeb(m) (NtCurrentTeb()->m) +#define WriteTeb(m, val) (NtCurrentTeb()->m = (val)) + +#endif + +#define NtCurrentPeb() ((PPEB)ReadTeb(ProcessEnvironmentBlock)) + +#pragma endregion + +#pragma region Error codes + +/* Gets or sets the last error */ + +#define NtGetLastError() ((ULONG)ReadTeb(LastErrorValue)) +#define NtSetLastError(Error) WriteTeb(LastErrorValue, Error) + +/* Gets or sets the last status */ + +#define NtGetLastStatus() ((NTSTATUS)(ReadTeb(LastStatusValue))) +#define NtSetLastStatus(Status) WriteTeb(LastStatusValue, Status) + +/* + * Error code conversion (NOT translation) Win32 Error/NTSTATUS/HRESULT + * HRESULT_FROM_WIN32 / NTSTATUS_FROM_WIN32 / HRESULT_FROM_NT + */ + +#pragma endregion + +#pragma region Current runtime information + +#define NtGetCurrentProcessId() ((HANDLE)ReadTeb(ClientId.UniqueProcess)) +#define NtGetCurrentThreadId() ((HANDLE)ReadTeb(ClientId.UniqueThread)) +#define NtGetCurrentDirectory() ((PCURDIR)&NtCurrentPeb()->ProcessParameters->CurrentDirectory) +#define NtGetCurrentImageBase() (NtCurrentPeb()->ImageBaseAddress) +#define NtGetNtdllBase() (CONTAINING_RECORD(NtCurrentPeb()->Ldr->InInitializationOrderModuleList.Flink, LDR_DATA_TABLE_ENTRY, InInitializationOrderModuleList)->DllBase) +#define NtGetProcessHeap() (NtCurrentPeb()->ProcessHeap) + +#pragma endregion + +#pragma region Context + +#if defined(_M_IX86) +#define CONTEXT_PC Eip +#elif defined(_M_X64) +#define CONTEXT_PC Rip +#elif defined(_M_ARM64) +#define CONTEXT_PC Pc +#endif + +#pragma endregion diff --git a/Source/Include/KNSoft/NDK/NT/Macro.h b/Source/Include/KNSoft/NDK/NT/Macro.h new file mode 100644 index 0000000..4aabc79 --- /dev/null +++ b/Source/Include/KNSoft/NDK/NT/Macro.h @@ -0,0 +1,63 @@ +#pragma once + +#include "MinDef.h" + +#pragma region Pointer and Size + +#define RtlOffsetToPointer(B,O) ((PCHAR)(((PCHAR)(B)) + ((ULONG_PTR)(O)))) +#define RtlPointerToOffset(B,P) ((ULONG)(((PCHAR)(P)) - ((PCHAR)(B)))) + +#define Add2Ptr(P,I) ((PVOID)((PUCHAR)(P) + (I))) +#define PtrOffset(B,O) ((ULONG)((ULONG_PTR)(O) - (ULONG_PTR)(B))) + +#define ROUND_TO_SIZE(_length, _alignment) \ + ((((ULONG_PTR)(_length)) + ((_alignment)-1)) & ~(ULONG_PTR)((_alignment) - 1)) + +#define IS_ALIGNED(_pointer, _alignment) \ + ((((ULONG_PTR)(_pointer)) & ((_alignment) - 1)) == 0) + +#pragma endregion + +#pragma region Flag + +#ifndef FlagOn +#define FlagOn(_F,_SF) ((_F) & (_SF)) +#endif + +#ifndef BooleanFlagOn +#define BooleanFlagOn(F,SF) ((BOOLEAN)(((F) & (SF)) != 0)) +#endif + +#ifndef SetFlag +#define SetFlag(_F,_SF) ((_F) |= (_SF)) +#endif + +#ifndef ClearFlag +#define ClearFlag(_F,_SF) ((_F) &= ~(_SF)) +#endif + +#pragma endregion + +#pragma region Pseudo Handles + +#define NtCurrentProcess() ((HANDLE)(LONG_PTR)-1) +#define ZwCurrentProcess() NtCurrentProcess() +#define NtCurrentThread() ((HANDLE)(LONG_PTR)-2) +#define ZwCurrentThread() NtCurrentThread() +#define NtCurrentSession() ((HANDLE)(LONG_PTR)-3) +#define ZwCurrentSession() NtCurrentSession() + +#if defined(_KNSOFT_NDK_NT_EXTENSION) + +#define NtCurrentProcessToken() ((HANDLE)(LONG_PTR)-4) +#define ZwCurrentProcessToken() NtCurrentProcessToken() +#define NtCurrentThreadToken() ((HANDLE)(LONG_PTR)-5) +#define ZwCurrentThreadToken() NtCurrentThreadToken() +#define NtCurrentThreadEffectiveToken() ((HANDLE)(LONG_PTR)-6) +#define ZwCurrentThreadEffectiveToken() NtCurrentThreadEffectiveToken() + +#endif /* defined(_KNSOFT_NDK_NT_EXTENSION) */ + +#define SERVERNAME_CURRENT ((HANDLE)NULL) + +#pragma endregion diff --git a/Source/Include/KNSoft/NDK/NT/MinDef.h b/Source/Include/KNSoft/NDK/NT/MinDef.h new file mode 100644 index 0000000..893a4fd --- /dev/null +++ b/Source/Include/KNSoft/NDK/NT/MinDef.h @@ -0,0 +1,19 @@ +/* Supersede minwindef.h and include ntstatus.h */ + +#pragma once + +#include "./PolyFill/SdkDdkVer.h" + +#include "Private/TargetArch.h" + +#include "Private/Winnt_Around.h" +#include +#include "Private/Winnt_Around.h" + +#include "Private/Ntdef_Around.h" +#include +#include "Private/Ntdef_Around.h" + +#include + +#include "./PolyFill/MinDef.h" diff --git a/Source/Include/KNSoft/NDK/NT/NT.h b/Source/Include/KNSoft/NDK/NT/NT.h new file mode 100644 index 0000000..6475520 --- /dev/null +++ b/Source/Include/KNSoft/NDK/NT/NT.h @@ -0,0 +1,11 @@ +#pragma once + +#ifndef _KNSOFT_NDK_NO_EXTENSION +#define _KNSOFT_NDK_NT_EXTENSION +#include "Extension.h" +#endif + +#include "MinDef.h" +#include "Types/Types.h" +#include "API/API.h" +#include "Macro.h" diff --git a/Source/Include/KNSoft/NDK/NT/PolyFill/MinDef.h b/Source/Include/KNSoft/NDK/NT/PolyFill/MinDef.h new file mode 100644 index 0000000..3bfaf2c --- /dev/null +++ b/Source/Include/KNSoft/NDK/NT/PolyFill/MinDef.h @@ -0,0 +1,24 @@ +/* PolyFills about winnt.h, ntdef.h for Win8.1 SDK (VS2015) and above */ + +#pragma once + +#if !defined(EXTERN_C_START) || !defined(EXTERN_C_END) +#ifdef __cplusplus +#define EXTERN_C_START extern "C" { +#define EXTERN_C_END } +#else +#define EXTERN_C_START +#define EXTERN_C_END +#endif +#endif + +#ifndef UFIELD_OFFSET +#ifdef __has_builtin +#if __has_builtin(__builtin_offsetof) +#define UFIELD_OFFSET(type, field) ((ULONG)__builtin_offsetof(type, field)) +#endif +#endif +#ifndef UFIELD_OFFSET +#define UFIELD_OFFSET(type, field) ((ULONG)(LONG_PTR)&(((type *)0)->field)) +#endif +#endif diff --git a/Source/Include/KNSoft/NDK/NT/PolyFill/SdkDdkVer.h b/Source/Include/KNSoft/NDK/NT/PolyFill/SdkDdkVer.h new file mode 100644 index 0000000..214cef0 --- /dev/null +++ b/Source/Include/KNSoft/NDK/NT/PolyFill/SdkDdkVer.h @@ -0,0 +1,26 @@ +/* Versions constants in sdkddkver.h after Win8.1 SDK (VS2015) */ + +#pragma once + +#define _WIN32_WINNT_WINTHRESHOLD 0x0A00 +#define _WIN32_WINNT_WIN10 0x0A00 + +#define _WIN32_IE_IE110 0x0A00 + +#define _WIN32_IE_WINTHRESHOLD _WIN32_IE_IE110 +#define _WIN32_IE_WIN10 _WIN32_IE_IE110 + +#define NTDDI_WINTHRESHOLD 0x0A000000 +#define NTDDI_WIN10 0x0A000000 +#define NTDDI_WIN10_TH2 0x0A000001 +#define NTDDI_WIN10_RS1 0x0A000002 +#define NTDDI_WIN10_RS2 0x0A000003 +#define NTDDI_WIN10_RS3 0x0A000004 +#define NTDDI_WIN10_RS4 0x0A000005 +#define NTDDI_WIN10_RS5 0x0A000006 +#define NTDDI_WIN10_19H1 0x0A000007 +#define NTDDI_WIN10_VB 0x0A000008 +#define NTDDI_WIN10_MN 0x0A000009 +#define NTDDI_WIN10_FE 0x0A00000A +#define NTDDI_WIN10_CO 0x0A00000B +#define NTDDI_WIN10_NI 0x0A00000C diff --git a/Source/Include/KNSoft/NDK/NT/Private/Ntdef_Around.h b/Source/Include/KNSoft/NDK/NT/Private/Ntdef_Around.h new file mode 100644 index 0000000..d185a0d --- /dev/null +++ b/Source/Include/KNSoft/NDK/NT/Private/Ntdef_Around.h @@ -0,0 +1,97 @@ +/* Include this file before and after ntdef.h if winnt.h is already included */ + +#ifndef _NTDEF_ + +#undef LANGIDFROMLCID +#undef MAKELANGID +#undef MAKELCID +#undef MAKESORTLCID +#undef MAX_NATURAL_ALIGNMENT +#undef PRIMARYLANGID +#undef SUBLANGID +#undef PROBE_ALIGNMENT +#undef PROBE_ALIGNMENT32 +#undef SORTIDFROMLCID +#undef SORTVERSIONFROMLCID +#undef UNICODE_STRING_MAX_BYTES + +#define _LIST_ENTRY _MS_LIST_ENTRY +#define LIST_ENTRY MS_LIST_ENTRY +#define PLIST_ENTRY PMS_LIST_ENTRY +#define PRLIST_ENTRY PRMS_LIST_ENTRY +#define LIST_ENTRY32 MS_LIST_ENTRY32 +#define PLIST_ENTRY32 PMS_LIST_ENTRY32 +#define LIST_ENTRY64 MS_LIST_ENTRY64 +#define PLIST_ENTRY64 PMS_LIST_ENTRY64 +#define _SINGLE_LIST_ENTRY _MS_SINGLE_LIST_ENTRY +#define SINGLE_LIST_ENTRY MS_SINGLE_LIST_ENTRY +#define PSINGLE_LIST_ENTRY PMS_SINGLE_LIST_ENTRY +#define _LARGE_INTEGER _MS_LARGE_INTEGER +#define LARGE_INTEGER MS_LARGE_INTEGER +#define PLARGE_INTEGER PMS_LARGE_INTEGER +#define _ULARGE_INTEGER _MS_ULARGE_INTEGER +#define ULARGE_INTEGER MS_ULARGE_INTEGER +#define PULARGE_INTEGER PMS_ULARGE_INTEGER +#define _LUID _MS_LUID +#define LUID MS_LUID +#define PLUID PMS_LUID +#define _FLOAT128 _MS_FLOAT128 +#define FLOAT128 MS_FLOAT128 +#define PFLOAT128 PMS_FLOAT128 +#define _PROCESSOR_NUMBER _MS_PROCESSOR_NUMBER +#define PROCESSOR_NUMBER MS_PROCESSOR_NUMBER +#define PPROCESSOR_NUMBER PMS_PROCESSOR_NUMBER +#define _GROUP_AFFINITY _MS_GROUP_AFFINITY +#define GROUP_AFFINITY MS_GROUP_AFFINITY +#define PGROUP_AFFINITY PMS_GROUP_AFFINITY + +#if defined(_M_IX86) +#define Int64ShllMod32 MS_Int64ShllMod32 +#define Int64ShraMod32 MS_Int64ShraMod32 +#define Int64ShrlMod32 MS_Int64ShrlMod32 +#endif + +#define _ENUM_FLAG_SIZED_INTEGER _MS_ENUM_FLAG_SIZED_INTEGER +#define _ENUM_FLAG_INTEGER_FOR_SIZE _MS_ENUM_FLAG_INTEGER_FOR_SIZE + +#else + +#undef _ENUM_FLAG_SIZED_INTEGER +#undef _ENUM_FLAG_INTEGER_FOR_SIZE + +#undef Int64ShllMod32 +#undef Int64ShraMod32 +#undef Int64ShrlMod32 + +#undef _LIST_ENTRY +#undef LIST_ENTRY +#undef PLIST_ENTRY +#undef PRLIST_ENTRY +#undef LIST_ENTRY32 +#undef PLIST_ENTRY32 +#undef LIST_ENTRY64 +#undef PLIST_ENTRY64 +#undef _SINGLE_LIST_ENTRY +#undef SINGLE_LIST_ENTRY +#undef PSINGLE_LIST_ENTRY + +#undef _LARGE_INTEGER +#undef LARGE_INTEGER +#undef PLARGE_INTEGER +#undef _ULARGE_INTEGER +#undef ULARGE_INTEGER +#undef PULARGE_INTEGER +#undef _LUID +#undef LUID +#undef PLUID +#undef _FLOAT128 +#undef FLOAT128 +#undef PFLOAT128 +#undef _PROCESSOR_NUMBER +#undef PROCESSOR_NUMBER +#undef PPROCESSOR_NUMBER +#undef _GROUP_AFFINITY +#undef GROUP_AFFINITY +#undef PGROUP_AFFINITY + +#endif diff --git a/Source/Include/KNSoft/NDK/NT/Private/TargetArch.h b/Source/Include/KNSoft/NDK/NT/Private/TargetArch.h new file mode 100644 index 0000000..0356364 --- /dev/null +++ b/Source/Include/KNSoft/NDK/NT/Private/TargetArch.h @@ -0,0 +1,46 @@ +/* Patches #error "No Target Architecture" in ntdef.h and winnt.h */ + +#pragma once + +#if !defined(_68K_) && !defined(_MPPC_) && !defined(_X86_) && !defined(_IA64_) && !defined(_AMD64_) && !defined(_ARM_) && !defined(_ARM64_) && !defined(_ARM64EC_) && defined(_M_IX86) +#define _X86_ +#if !defined(_CHPE_X86_ARM64_) && defined(_M_HYBRID) +#define _CHPE_X86_ARM64_ +#endif +#endif + +#if !defined(_68K_) && !defined(_MPPC_) && !defined(_X86_) && !defined(_IA64_) && !defined(_AMD64_) && !defined(_ARM_) && !defined(_ARM64_) && (defined(_M_AMD64) || defined(_M_ARM64EC)) +#define _AMD64_ +#endif + +#if !defined(_68K_) && !defined(_MPPC_) && !defined(_X86_) && !defined(_IA64_) && !defined(_AMD64_) && !defined(_ARM_) && !defined(_ARM64_) && !defined(_ARM64EC_) && defined(_M_ARM) +#define _ARM_ +#endif + +#if !defined(_68K_) && !defined(_MPPC_) && !defined(_X86_) && !defined(_IA64_) && !defined(_AMD64_) && !defined(_ARM_) && !defined(_ARM64_) && !defined(_ARM64EC_) && defined(_M_ARM64) +#define _ARM64_ +#endif + +#if !defined(_68K_) && !defined(_MPPC_) && !defined(_X86_) && !defined(_IA64_) && !defined(_ARM_) && !defined(_ARM64_) && !defined(_ARM64EC_) && defined(_M_ARM64EC) +#define _ARM64EC_ +#endif + +#if !defined(_68K_) && !defined(_MPPC_) && !defined(_X86_) && !defined(_IA64_) && !defined(_AMD64_) && !defined(_ARM_) && !defined(_ARM64_) && !defined(_ARM64EC_) && defined(_M_M68K) +#define _68K_ +#endif + +#if !defined(_68K_) && !defined(_MPPC_) && !defined(_X86_) && !defined(_IA64_) && !defined(_AMD64_) && !defined(_ARM_) && !defined(_ARM64_) && !defined(_ARM64EC_) && defined(_M_MPPC) +#define _MPPC_ +#endif + +#if !defined(_68K_) && !defined(_MPPC_) && !defined(_X86_) && !defined(_M_IX86) && !defined(_AMD64_) && !defined(_ARM_) && !defined(_ARM64_) && !defined(_ARM64EC_) && defined(_M_IA64) +#if !defined(_IA64_) +#define _IA64_ +#endif /* !_IA64_ */ +#endif + +#ifndef _MAC +#if defined(_68K_) || defined(_MPPC_) +#define _MAC +#endif +#endif diff --git a/Source/Include/KNSoft/NDK/NT/Private/Winnt_Around.h b/Source/Include/KNSoft/NDK/NT/Private/Winnt_Around.h new file mode 100644 index 0000000..752fcaf --- /dev/null +++ b/Source/Include/KNSoft/NDK/NT/Private/Winnt_Around.h @@ -0,0 +1,16 @@ +/* Include this file before and after winnt.h */ + +#ifndef _WINNT_ + +#define WIN32_NO_STATUS + +#define PSID MS_PSID + +#else + +#undef WIN32_NO_STATUS + +#undef PSID +typedef SID* PSID; + +#endif diff --git a/Source/Include/KNSoft/NDK/NT/Types/Advance.h b/Source/Include/KNSoft/NDK/NT/Types/Advance.h new file mode 100644 index 0000000..0ef25c0 --- /dev/null +++ b/Source/Include/KNSoft/NDK/NT/Types/Advance.h @@ -0,0 +1,1093 @@ +#pragma once + +#include "../MinDef.h" + +#include "Rtl.h" + +#pragma region PEB_LDR_DATA[64/32] + +typedef struct _PEB_LDR_DATA +{ + ULONG Length; + BOOL Initialized; + PVOID SsHandle; + LIST_ENTRY InLoadOrderModuleList; + LIST_ENTRY InMemoryOrderModuleList; + LIST_ENTRY InInitializationOrderModuleList; + PVOID EntryInProgress; + PVOID ShutdownInProgress; + PVOID ShutdownThreadId; +} PEB_LDR_DATA, *PPEB_LDR_DATA; + +#if defined(_KNSOFT_NDK_NT_EXTENSION) + +typedef struct _PEB_LDR_DATA64 +{ + ULONG Length; + BOOL Initialized; + VOID* POINTER_64 SsHandle; + LIST_ENTRY64 InLoadOrderModuleList; + LIST_ENTRY64 InMemoryOrderModuleList; + LIST_ENTRY64 InInitializationOrderModuleList; + VOID* POINTER_64 EntryInProgress; + VOID* POINTER_64 ShutdownInProgress; + VOID* POINTER_64 ShutdownThreadId; +} PEB_LDR_DATA64, *PPEB_LDR_DATA64; + +typedef struct _PEB_LDR_DATA32 +{ + ULONG Length; + BOOL Initialized; + VOID* POINTER_32 SsHandle; + LIST_ENTRY32 InLoadOrderModuleList; + LIST_ENTRY32 InMemoryOrderModuleList; + LIST_ENTRY32 InInitializationOrderModuleList; + VOID* POINTER_32 EntryInProgress; + VOID* POINTER_32 ShutdownInProgress; + VOID* POINTER_32 ShutdownThreadId; +} PEB_LDR_DATA32, *PPEB_LDR_DATA32; + +#endif /* defined(_KNSOFT_NDK_NT_EXTENSION) */ + +#pragma endregion + +#pragma region PEB[64/32] + +typedef struct _PEB +{ + UCHAR InheritedAddressSpace; + UCHAR ReadImageFileExecOptions; + UCHAR BeingDebugged; + union + { + UCHAR BitField; + struct + { + UCHAR ImageUsesLargePages : 1; + UCHAR IsProtectedProcess : 1; + UCHAR IsImageDynamicallyRelocated : 1; + UCHAR SkipPatchingUser32Forwarders : 1; + UCHAR IsPackagedProcess : 1; + UCHAR IsAppContainer : 1; + UCHAR IsProtectedProcessLight : 1; + UCHAR IsLongPathAwareProcess : 1; + }; + }; +#if _WIN64 + UCHAR Padding0[4]; +#endif + HANDLE Mutant; + PVOID ImageBaseAddress; + PPEB_LDR_DATA Ldr; + PRTL_USER_PROCESS_PARAMETERS ProcessParameters; + PVOID SubSystemData; + HANDLE ProcessHeap; + PRTL_CRITICAL_SECTION FastPebLock; + PSLIST_HEADER AtlThunkSListPtr; + PVOID IFEOKey; + union + { + ULONG CrossProcessFlags; + struct + { + ULONG ProcessInJob : 1; + ULONG ProcessInitializing : 1; + ULONG ProcessUsingVEH : 1; + ULONG ProcessUsingVCH : 1; + ULONG ProcessUsingFTH : 1; + ULONG ProcessPreviouslyThrottled : 1; + ULONG ProcessCurrentlyThrottled : 1; + ULONG ProcessImagesHotPatched : 1; + ULONG ReservedBits0 : 24; + }; + }; +#if _WIN64 + UCHAR Padding1[4]; +#endif + union + { + PVOID KernelCallbackTable; + PVOID UserSharedInfoPtr; + }; + ULONG SystemReserved; + ULONG AtlThunkSListPtr32; + PVOID ApiSetMap; + ULONG TlsExpansionCounter; +#if _WIN64 + UCHAR Padding2[4]; +#endif + PRTL_BITMAP TlsBitmap; + ULONG TlsBitmapBits[2]; + PVOID ReadOnlySharedMemoryBase; + PVOID SharedData; + PVOID* ReadOnlyStaticServerData; + PVOID AnsiCodePageData; + PVOID OemCodePageData; + PVOID UnicodeCaseTableData; + ULONG NumberOfProcessors; + ULONG NtGlobalFlag; + LARGE_INTEGER CriticalSectionTimeout; + ULONG_PTR HeapSegmentReserve; + ULONG_PTR HeapSegmentCommit; + ULONG_PTR HeapDeCommitTotalFreeThreshold; + ULONG_PTR HeapDeCommitFreeBlockThreshold; + ULONG NumberOfHeaps; + ULONG MaximumNumberOfHeaps; + PVOID ProcessHeaps; + PVOID GdiSharedHandleTable; + PVOID ProcessStarterHelper; + ULONG GdiDCAttributeList; +#if _WIN64 + UCHAR Padding3[4]; +#endif + PRTL_CRITICAL_SECTION LoaderLock; + ULONG OSMajorVersion; + ULONG OSMinorVersion; + USHORT OSBuildNumber; + USHORT OSCSDVersion; + ULONG OSPlatformId; + ULONG ImageSubsystem; + ULONG ImageSubsystemMajorVersion; + ULONG ImageSubsystemMinorVersion; +#if _WIN64 + UCHAR Padding4[4]; +#endif + ULONG_PTR ActiveProcessAffinityMask; +#if _WIN64 + ULONG GdiHandleBuffer[60]; +#else + ULONG GdiHandleBuffer[34]; +#endif + PVOID PostProcessInitRoutine; + PRTL_BITMAP TlsExpansionBitmap; + ULONG TlsExpansionBitmapBits[32]; + ULONG SessionId; +#ifdef _WIN64 + UCHAR Padding5[4]; +#endif + ULARGE_INTEGER AppCompatFlags; + ULARGE_INTEGER AppCompatFlagsUser; + PVOID pShimData; + PVOID AppCompatInfo; + UNICODE_STRING CSDVersion; + PACTIVATION_CONTEXT_DATA ActivationContextData; + PASSEMBLY_STORAGE_MAP ProcessAssemblyStorageMap; + PACTIVATION_CONTEXT_DATA SystemDefaultActivationContextData; + PASSEMBLY_STORAGE_MAP SystemAssemblyStorageMap; + ULONG_PTR MinimumStackCommit; + PVOID SparePointers[2]; + PVOID PatchLoaderData; + struct CHPEV2_PROCESS_INFO* ChpeV2ProcessInfo; + ULONG AppModelFeatureState; + ULONG SpareUlongs[2]; + USHORT ActiveCodePage; + USHORT OemCodePage; + USHORT UseCaseMapping; + USHORT UnusedNlsField; + PVOID WerRegistrationData; + PVOID WerShipAssertPtr; +#ifdef _WIN64 + PVOID EcCodeBitMap; +#else + PVOID Spare; +#endif + PVOID pImageHeaderHash; + union + { + ULONG TracingFlags; + struct + { + ULONG HeapTracingEnabled : 1; + ULONG CritSecTracingEnabled : 1; + ULONG LibLoaderTracingEnabled : 1; + ULONG SpareTracingBits : 29; + }; + }; +#ifdef _WIN64 + UCHAR Padding6[4]; +#endif + ULONGLONG CsrServerReadOnlySharedMemoryBase; + ULONG_PTR TppWorkerpListLock; + LIST_ENTRY TppWorkerpList; + PVOID WaitOnAddressHashTable[128]; + PVOID TelemetryCoverageHeader; + ULONG CloudFileFlags; + ULONG CloudFileDiagFlags; + CHAR PlaceholderCompatibilityMode; + CHAR PlaceholderCompatibilityModeReserved[7]; + PLEAP_SECOND_DATA LeapSecondData; + union + { + ULONG LeapSecondFlags; + struct + { + ULONG SixtySecondEnabled : 1; + ULONG Reserved : 31; + }; + }; + ULONG NtGlobalFlag2; + ULONGLONG ExtendedFeatureDisableMask; +} PEB, *PPEB; + +#if defined(_KNSOFT_NDK_NT_EXTENSION) + +typedef struct _PEB64 +{ + UCHAR InheritedAddressSpace; + UCHAR ReadImageFileExecOptions; + UCHAR BeingDebugged; + union + { + UCHAR BitField; + struct + { + UCHAR ImageUsesLargePages : 1; + UCHAR IsProtectedProcess : 1; + UCHAR IsImageDynamicallyRelocated : 1; + UCHAR SkipPatchingUser32Forwarders : 1; + UCHAR IsPackagedProcess : 1; + UCHAR IsAppContainer : 1; + UCHAR IsProtectedProcessLight : 1; + UCHAR IsLongPathAwareProcess : 1; + }; + }; +#if _WIN64 + UCHAR Padding0[4]; +#endif + VOID* POINTER_64 Mutant; + VOID* POINTER_64 ImageBaseAddress; + PEB_LDR_DATA64* POINTER_64 Ldr; + PRTL_USER_PROCESS_PARAMETERS64 ProcessParameters; + VOID* POINTER_64 SubSystemData; + VOID* POINTER_64 ProcessHeap; + RTL_CRITICAL_SECTION64* POINTER_64 FastPebLock; + struct SLIST_HEADER* POINTER_64 AtlThunkSListPtr; // FIXME: SLIST_HEADER is depends on platform + VOID* POINTER_64 IFEOKey; + union + { + ULONG CrossProcessFlags; + struct + { + ULONG ProcessInJob : 1; + ULONG ProcessInitializing : 1; + ULONG ProcessUsingVEH : 1; + ULONG ProcessUsingVCH : 1; + ULONG ProcessUsingFTH : 1; + ULONG ProcessPreviouslyThrottled : 1; + ULONG ProcessCurrentlyThrottled : 1; + ULONG ProcessImagesHotPatched : 1; + ULONG ReservedBits0 : 24; + }; + }; + UCHAR Padding1[4]; + union + { + VOID* POINTER_64 KernelCallbackTable; + VOID* POINTER_64 UserSharedInfoPtr; + }; + ULONG SystemReserved; + ULONG AtlThunkSListPtr32; + VOID* POINTER_64 ApiSetMap; + ULONG TlsExpansionCounter; + UCHAR Padding2[4]; + RTL_BITMAP64* POINTER_64 TlsBitmap; + ULONG TlsBitmapBits[2]; + VOID* POINTER_64 ReadOnlySharedMemoryBase; + VOID* POINTER_64 SharedData; + VOID* POINTER_64* POINTER_64 ReadOnlyStaticServerData; + VOID* POINTER_64 AnsiCodePageData; + VOID* POINTER_64 OemCodePageData; + VOID* POINTER_64 UnicodeCaseTableData; + ULONG NumberOfProcessors; + ULONG NtGlobalFlag; + LARGE_INTEGER CriticalSectionTimeout; + ULONGLONG HeapSegmentReserve; + ULONGLONG HeapSegmentCommit; + ULONGLONG HeapDeCommitTotalFreeThreshold; + ULONGLONG HeapDeCommitFreeBlockThreshold; + ULONG NumberOfHeaps; + ULONG MaximumNumberOfHeaps; + VOID* POINTER_64 ProcessHeaps; + VOID* POINTER_64 GdiSharedHandleTable; + VOID* POINTER_64 ProcessStarterHelper; + ULONG GdiDCAttributeList; + UCHAR Padding3[4]; + RTL_CRITICAL_SECTION64* POINTER_64 LoaderLock; + ULONG OSMajorVersion; + ULONG OSMinorVersion; + USHORT OSBuildNumber; + USHORT OSCSDVersion; + ULONG OSPlatformId; + ULONG ImageSubsystem; + ULONG ImageSubsystemMajorVersion; + ULONG ImageSubsystemMinorVersion; + UCHAR Padding4[4]; + ULONGLONG ActiveProcessAffinityMask; + ULONG GdiHandleBuffer[60]; + VOID* POINTER_64 PostProcessInitRoutine; + RTL_BITMAP64* POINTER_64 TlsExpansionBitmap; + ULONG TlsExpansionBitmapBits[32]; + ULONG SessionId; + UCHAR Padding5[4]; + ULARGE_INTEGER AppCompatFlags; + ULARGE_INTEGER AppCompatFlagsUser; + VOID* POINTER_64 pShimData; + VOID* POINTER_64 AppCompatInfo; + UNICODE_STRING64 CSDVersion; + ACTIVATION_CONTEXT_DATA* POINTER_64 ActivationContextData; + ASSEMBLY_STORAGE_MAP* POINTER_64 ProcessAssemblyStorageMap; + ACTIVATION_CONTEXT_DATA* POINTER_64 SystemDefaultActivationContextData; + ASSEMBLY_STORAGE_MAP* POINTER_64 SystemAssemblyStorageMap; + ULONGLONG MinimumStackCommit; + VOID* POINTER_64 SparePointers[2]; + VOID* POINTER_64 PatchLoaderData; + struct CHPEV2_PROCESS_INFO* POINTER_64 ChpeV2ProcessInfo; + ULONG AppModelFeatureState; + ULONG SpareUlongs[2]; + USHORT ActiveCodePage; + USHORT OemCodePage; + USHORT UseCaseMapping; + USHORT UnusedNlsField; + VOID* POINTER_64 WerRegistrationData; + VOID* POINTER_64 WerShipAssertPtr; + VOID* POINTER_64 EcCodeBitMap; + VOID* POINTER_64 pImageHeaderHash; + union + { + ULONG TracingFlags; + struct + { + ULONG HeapTracingEnabled : 1; + ULONG CritSecTracingEnabled : 1; + ULONG LibLoaderTracingEnabled : 1; + ULONG SpareTracingBits : 29; + }; + }; + UCHAR Padding6[4]; + ULONGLONG CsrServerReadOnlySharedMemoryBase; + ULONGLONG TppWorkerpListLock; + LIST_ENTRY64 TppWorkerpList; + VOID* POINTER_64 WaitOnAddressHashTable[128]; + VOID* POINTER_64 TelemetryCoverageHeader; + ULONG CloudFileFlags; + ULONG CloudFileDiagFlags; + CHAR PlaceholderCompatibilityMode; + CHAR PlaceholderCompatibilityModeReserved[7]; + LEAP_SECOND_DATA* POINTER_64 LeapSecondData; + union + { + ULONG LeapSecondFlags; + struct + { + ULONG SixtySecondEnabled : 1; + ULONG Reserved : 31; + }; + }; + ULONG NtGlobalFlag2; + ULONGLONG ExtendedFeatureDisableMask; +} PEB64, *PPEB64; + +typedef struct _PEB32 +{ + UCHAR InheritedAddressSpace; + UCHAR ReadImageFileExecOptions; + UCHAR BeingDebugged; + union + { + UCHAR BitField; + struct + { + UCHAR ImageUsesLargePages : 1; + UCHAR IsProtectedProcess : 1; + UCHAR IsImageDynamicallyRelocated : 1; + UCHAR SkipPatchingUser32Forwarders : 1; + UCHAR IsPackagedProcess : 1; + UCHAR IsAppContainer : 1; + UCHAR IsProtectedProcessLight : 1; + UCHAR IsLongPathAwareProcess : 1; + }; + }; + VOID* POINTER_32 Mutant; + VOID* POINTER_32 ImageBaseAddress; + PEB_LDR_DATA32* POINTER_32 Ldr; + RTL_USER_PROCESS_PARAMETERS32* POINTER_32 ProcessParameters; + VOID* POINTER_32 SubSystemData; + VOID* POINTER_32 ProcessHeap; + RTL_CRITICAL_SECTION32* POINTER_32 FastPebLock; + struct SLIST_HEADER* POINTER_32 AtlThunkSListPtr; // FIXME: SLIST_HEADER is depends on platform + VOID* POINTER_32 IFEOKey; + union + { + ULONG CrossProcessFlags; + struct + { + ULONG ProcessInJob : 1; + ULONG ProcessInitializing : 1; + ULONG ProcessUsingVEH : 1; + ULONG ProcessUsingVCH : 1; + ULONG ProcessUsingFTH : 1; + ULONG ProcessPreviouslyThrottled : 1; + ULONG ProcessCurrentlyThrottled : 1; + ULONG ProcessImagesHotPatched : 1; + ULONG ReservedBits0 : 24; + }; + }; + union + { + VOID* POINTER_32 KernelCallbackTable; + VOID* POINTER_32 UserSharedInfoPtr; + }; + ULONG SystemReserved; + ULONG AtlThunkSListPtr32; + VOID* POINTER_32 ApiSetMap; + ULONG TlsExpansionCounter; + RTL_BITMAP32* POINTER_32 TlsBitmap; + ULONG TlsBitmapBits[2]; + VOID* POINTER_32 ReadOnlySharedMemoryBase; + VOID* POINTER_32 SharedData; + VOID* POINTER_32* POINTER_32 ReadOnlyStaticServerData; + VOID* POINTER_32 AnsiCodePageData; + VOID* POINTER_32 OemCodePageData; + VOID* POINTER_32 UnicodeCaseTableData; + ULONG NumberOfProcessors; + ULONG NtGlobalFlag; + LARGE_INTEGER CriticalSectionTimeout; + ULONG HeapSegmentReserve; + ULONG HeapSegmentCommit; + ULONG HeapDeCommitTotalFreeThreshold; + ULONG HeapDeCommitFreeBlockThreshold; + ULONG NumberOfHeaps; + ULONG MaximumNumberOfHeaps; + VOID* POINTER_32 ProcessHeaps; + VOID* POINTER_32 GdiSharedHandleTable; + VOID* POINTER_32 ProcessStarterHelper; + ULONG GdiDCAttributeList; + RTL_CRITICAL_SECTION32* POINTER_32 LoaderLock; + ULONG OSMajorVersion; + ULONG OSMinorVersion; + USHORT OSBuildNumber; + USHORT OSCSDVersion; + ULONG OSPlatformId; + ULONG ImageSubsystem; + ULONG ImageSubsystemMajorVersion; + ULONG ImageSubsystemMinorVersion; + ULONG ActiveProcessAffinityMask; + ULONG GdiHandleBuffer[34]; + VOID* POINTER_32 PostProcessInitRoutine; + RTL_BITMAP32* POINTER_32 TlsExpansionBitmap; + ULONG TlsExpansionBitmapBits[32]; + ULONG SessionId; + ULARGE_INTEGER AppCompatFlags; + ULARGE_INTEGER AppCompatFlagsUser; + VOID* POINTER_32 pShimData; + VOID* POINTER_32 AppCompatInfo; + UNICODE_STRING32 CSDVersion; + ACTIVATION_CONTEXT_DATA* POINTER_32 ActivationContextData; + ASSEMBLY_STORAGE_MAP32* POINTER_32 ProcessAssemblyStorageMap; + ACTIVATION_CONTEXT_DATA* POINTER_32 SystemDefaultActivationContextData; + ASSEMBLY_STORAGE_MAP32* POINTER_32 SystemAssemblyStorageMap; + ULONG MinimumStackCommit; + VOID* POINTER_32 SparePointers[2]; + VOID* POINTER_32 PatchLoaderData; + struct CHPEV2_PROCESS_INFO* POINTER_32 ChpeV2ProcessInfo; + ULONG AppModelFeatureState; + ULONG SpareUlongs[2]; + USHORT ActiveCodePage; + USHORT OemCodePage; + USHORT UseCaseMapping; + USHORT UnusedNlsField; + VOID* POINTER_32 WerRegistrationData; + VOID* POINTER_32 WerShipAssertPtr; + VOID* POINTER_32 Spare; + VOID* POINTER_32 pImageHeaderHash; + union + { + ULONG TracingFlags; + struct + { + ULONG HeapTracingEnabled : 1; + ULONG CritSecTracingEnabled : 1; + ULONG LibLoaderTracingEnabled : 1; + ULONG SpareTracingBits : 29; + }; + }; + ULONGLONG CsrServerReadOnlySharedMemoryBase; + ULONG TppWorkerpListLock; + LIST_ENTRY32 TppWorkerpList; + VOID* POINTER_32 WaitOnAddressHashTable[128]; + VOID* POINTER_32 TelemetryCoverageHeader; + ULONG CloudFileFlags; + ULONG CloudFileDiagFlags; + CHAR PlaceholderCompatibilityMode; + CHAR PlaceholderCompatibilityModeReserved[7]; + LEAP_SECOND_DATA* POINTER_32 LeapSecondData; + union + { + ULONG LeapSecondFlags; + struct + { + ULONG SixtySecondEnabled : 1; + ULONG Reserved : 31; + }; + }; + ULONG NtGlobalFlag2; + ULONGLONG ExtendedFeatureDisableMask; +} PEB32, *PPEB32; + +#endif /* defined(_KNSOFT_NDK_NT_EXTENSION) */ + +#pragma endregion + +#pragma region TEB_ACTIVE_FRAME[_CONTEXT][64/32] + +typedef struct _TEB_ACTIVE_FRAME_CONTEXT +{ + ULONG Flags; + UCHAR Padding[4]; + PCHAR FrameName; +} TEB_ACTIVE_FRAME_CONTEXT, *PTEB_ACTIVE_FRAME_CONTEXT; + +typedef struct _TEB_ACTIVE_FRAME TEB_ACTIVE_FRAME, *PTEB_ACTIVE_FRAME; + +struct _TEB_ACTIVE_FRAME +{ + DWORD Flags; +#if _WIN64 + UCHAR Padding[4]; +#endif + struct TEB_ACTIVE_FRAME* Previous; + PTEB_ACTIVE_FRAME_CONTEXT Context; +}; + +#if defined(_KNSOFT_NDK_NT_EXTENSION) + +typedef struct _TEB_ACTIVE_FRAME_CONTEXT64 +{ + ULONG Flags; + UCHAR Padding[4]; + CHAR* POINTER_64 FrameName; +} TEB_ACTIVE_FRAME_CONTEXT64, *PTEB_ACTIVE_FRAME_CONTEXT64; + +typedef struct _TEB_ACTIVE_FRAME_CONTEXT32 +{ + ULONG Flags; + UCHAR Padding[4]; + CHAR* POINTER_32 FrameName; +} TEB_ACTIVE_FRAME_CONTEXT32, *PTEB_ACTIVE_FRAME_CONTEXT32; + +typedef struct _TEB_ACTIVE_FRAME64 TEB_ACTIVE_FRAME64, *PTEB_ACTIVE_FRAME64; +typedef struct _TEB_ACTIVE_FRAME32 TEB_ACTIVE_FRAME32, *PTEB_ACTIVE_FRAME32; + +struct _TEB_ACTIVE_FRAME64 +{ + DWORD Flags; + UCHAR Padding[4]; + struct TEB_ACTIVE_FRAME64* Previous; + TEB_ACTIVE_FRAME_CONTEXT64* POINTER_64 Context; +}; + +struct _TEB_ACTIVE_FRAME32 +{ + DWORD Flags; + struct TEB_ACTIVE_FRAME32* Previous; + TEB_ACTIVE_FRAME_CONTEXT32* POINTER_32 Context; +}; + +#endif /* defined(_KNSOFT_NDK_NT_EXTENSION) */ + +#pragma endregion + +#pragma region TEB[64/32] + +typedef struct _TEB +{ + NT_TIB NtTib; + LPWSTR EnvironmentPointer; + CLIENT_ID ClientId; + PVOID ActiveRpcHandle; + PVOID ThreadLocalStoragePointer; + PPEB ProcessEnvironmentBlock; + ULONG LastErrorValue; + ULONG CountOfOwnedCriticalSections; + PVOID CsrClientThread; + PVOID Win32ThreadInfo; + ULONG User32Reserved[26]; + ULONG UserReserved[5]; + PVOID WOW32Reserved; + ULONG CurrentLocale; + ULONG FpSoftwareStatusRegister; + PVOID ReservedForDebuggerInstrumentation[16]; +#ifdef _WIN64 + PVOID SystemReserved1[30]; +#else + PVOID SystemReserved1[26]; +#endif + CHAR PlaceholderCompatibilityMode; + UCHAR PlaceholderHydrationAlwaysExplicit; + CHAR PlaceholderReserved[10]; + ULONG ProxiedProcessId; + ACTIVATION_CONTEXT_STACK _ActivationStack; + UCHAR WorkingOnBehalfTicket[8]; + LONG ExceptionCode; +#ifdef _WIN64 + UCHAR Padding0[4]; +#endif + PACTIVATION_CONTEXT_STACK ActivationContextStackPointer; + PVOID InstrumentationCallbackSp; + PVOID InstrumentationCallbackPreviousPc; + PVOID InstrumentationCallbackPreviousSp; +#ifdef _WIN64 + ULONG TxFsContext; + BOOLEAN InstrumentationCallbackDisabled; + UCHAR UnalignedLoadStoreExceptions; + UCHAR Padding1[2]; +#else + UCHAR InstrumentationCallbackDisabled; + UCHAR SpareBytes[23]; + DWORD TxFsContext; +#endif + GDI_TEB_BATCH GdiTebBatch; + CLIENT_ID RealClientId; + PVOID GdiCachedProcessHandle; + ULONG GdiClientPID; + ULONG GdiClientTID; + PVOID GdiThreadLocalInfo; + ULONG_PTR Win32ClientInfo[62]; + PVOID glDispatchTable[233]; + ULONG_PTR glReserved1[29]; + PVOID glReserved2; + PVOID glSectionInfo; + PVOID glSection; + PVOID glTable; + PVOID glCurrentRC; + PVOID glContext; + ULONG LastStatusValue; +#ifdef _WIN64 + UCHAR Padding2[4]; +#endif + UNICODE_STRING StaticUnicodeString; + WCHAR StaticUnicodeBuffer[261]; +#ifdef _WIN64 + UCHAR Padding3[6]; +#endif + PVOID DeallocationStack; + PVOID TlsSlots[64]; + LIST_ENTRY TlsLinks; + PVOID Vdm; + PVOID ReservedForNtRpc; + PVOID DbgSsReserved[2]; + ULONG HardErrorMode; +#ifdef _WIN64 + UCHAR Padding4[4]; + PVOID Instrumentation[11]; +#else + PVOID Instrumentation[9]; +#endif + GUID ActivityId; + PVOID SubProcessTag; + PVOID PerflibData; + PVOID EtwTraceData; + PVOID WinSockData; + ULONG GdiBatchCount; + union + { + PROCESSOR_NUMBER CurrentIdealProcessor; + union + { + DWORD IdealProcessorValue; + struct + { + UCHAR ReservedPad0; + UCHAR ReservedPad1; + UCHAR ReservedPad2; + UCHAR IdealProcessor; + }; + }; + }; + ULONG GuaranteedStackBytes; +#ifdef _WIN64 + UCHAR Padding5[4]; +#endif + PVOID ReservedForPerf; + PVOID ReservedForOle; + ULONG WaitingOnLoaderLock; +#ifdef _WIN64 + UCHAR Padding6[4]; +#endif + PVOID SavedPriorityState; + ULONG_PTR ReservedForCodeCoverage; + PVOID ThreadPoolData; + PVOID TlsExpansionSlots; +#ifdef _WIN64 + struct CHPEV2_CPUAREA_INFO* POINTER_64 ChpeV2CpuAreaInfo; + PVOID Unused; +#endif + ULONG MuiGeneration; + ULONG IsImpersonating; + PVOID NlsCache; + PVOID pShimData; + ULONG HeapData; +#ifdef _WIN64 + UCHAR Padding7[4]; +#endif + PVOID CurrentTransactionHandle; + PTEB_ACTIVE_FRAME ActiveFrame; + PVOID FlsData; + PVOID PreferredLanguages; + PVOID UserPrefLanguages; + PVOID MergedPrefLanguages; + ULONG MuiImpersonation; + union + { + USHORT CrossTebFlags; + struct + { + USHORT SpareCrossTebBits : 16; + }; + }; + union + { + USHORT SameTebFlags; + struct + { + USHORT SafeThunkCall : 1; + USHORT InDebugPrint : 1; + USHORT HasFiberData : 1; + USHORT SkipThreadAttach : 1; + USHORT WerInShipAssertCode : 1; + USHORT RanProcessInit : 1; + USHORT ClonedThread : 1; + USHORT SuppressDebugMsg : 1; + USHORT DisableUserStackWalk : 1; + USHORT RtlExceptionAttached : 1; + USHORT InitialThread : 1; + USHORT SessionAware : 1; + USHORT LoadOwner : 1; + USHORT LoaderWorker : 1; + USHORT SkipLoaderInit : 1; + USHORT SkipFileAPIBrokering : 1; + }; + }; + PVOID TxnScopeEnterCallback; + PVOID TxnScopeExitCallback; + PVOID TxnScopeContext; + ULONG LockCount; + LONG WowTebOffset; + PVOID ResourceRetValue; + PVOID ReservedForWdf; + ULONGLONG ReservedForCrt; + GUID EffectiveContainerId; + ULONGLONG LastSleepCounter; + ULONG SpinCallCount; +#ifdef _WIN64 + UCHAR Padding8[4]; +#endif + ULONGLONG ExtendedFeatureDisableMask; +} TEB, *PTEB; + +#if defined(_KNSOFT_NDK_NT_EXTENSION) + +typedef struct _TEB64 +{ + NT_TIB64 NtTib; + WCHAR* POINTER_64 EnvironmentPointer; + CLIENT_ID64 ClientId; + VOID* POINTER_64 ActiveRpcHandle; + VOID* POINTER_64 ThreadLocalStoragePointer; + PEB64* POINTER_64 ProcessEnvironmentBlock; + ULONG LastErrorValue; + ULONG CountOfOwnedCriticalSections; + VOID* POINTER_64 CsrClientThread; + VOID* POINTER_64 Win32ThreadInfo; + ULONG User32Reserved[26]; + ULONG UserReserved[5]; + VOID* POINTER_64 WOW32Reserved; + ULONG CurrentLocale; + ULONG FpSoftwareStatusRegister; + VOID* POINTER_64 ReservedForDebuggerInstrumentation[16]; + VOID* POINTER_64 SystemReserved1[30]; + CHAR PlaceholderCompatibilityMode; + UCHAR PlaceholderHydrationAlwaysExplicit; + CHAR PlaceholderReserved[10]; + ULONG ProxiedProcessId; + ACTIVATION_CONTEXT_STACK64 _ActivationStack; + UCHAR WorkingOnBehalfTicket[8]; + LONG ExceptionCode; + UCHAR Padding0[4]; + ACTIVATION_CONTEXT_STACK64* POINTER_64 ActivationContextStackPointer; + VOID* POINTER_64 InstrumentationCallbackSp; + VOID* POINTER_64 InstrumentationCallbackPreviousPc; + VOID* POINTER_64 InstrumentationCallbackPreviousSp; + ULONG TxFsContext; + BOOLEAN InstrumentationCallbackDisabled; + UCHAR UnalignedLoadStoreExceptions; + UCHAR Padding1[2]; + GDI_TEB_BATCH64 GdiTebBatch; + CLIENT_ID64 RealClientId; + VOID* POINTER_64 GdiCachedProcessHandle; + ULONG GdiClientPID; + ULONG GdiClientTID; + VOID* POINTER_64 GdiThreadLocalInfo; + ULONGLONG Win32ClientInfo[62]; + VOID* POINTER_64 glDispatchTable[233]; + ULONGLONG glReserved1[29]; + VOID* POINTER_64 glReserved2; + VOID* POINTER_64 glSectionInfo; + VOID* POINTER_64 glSection; + VOID* POINTER_64 glTable; + VOID* POINTER_64 glCurrentRC; + VOID* POINTER_64 glContext; + ULONG LastStatusValue; + UCHAR Padding2[4]; + UNICODE_STRING64 StaticUnicodeString; + WCHAR StaticUnicodeBuffer[261]; + UCHAR Padding3[6]; + VOID* POINTER_64 DeallocationStack; + VOID* POINTER_64 TlsSlots[64]; + LIST_ENTRY64 TlsLinks; + VOID* POINTER_64 Vdm; + VOID* POINTER_64 ReservedForNtRpc; + VOID* POINTER_64 DbgSsReserved[2]; + ULONG HardErrorMode; + UCHAR Padding4[4]; + VOID* POINTER_64 Instrumentation[11]; + GUID ActivityId; + VOID* POINTER_64 SubProcessTag; + VOID* POINTER_64 PerflibData; + VOID* POINTER_64 EtwTraceData; + VOID* POINTER_64 WinSockData; + ULONG GdiBatchCount; + union + { + PROCESSOR_NUMBER CurrentIdealProcessor; + union + { + DWORD IdealProcessorValue; + struct + { + UCHAR ReservedPad0; + UCHAR ReservedPad1; + UCHAR ReservedPad2; + UCHAR IdealProcessor; + }; + }; + }; + ULONG GuaranteedStackBytes; + UCHAR Padding5[4]; + VOID* POINTER_64 ReservedForPerf; + VOID* POINTER_64 ReservedForOle; + ULONG WaitingOnLoaderLock; + UCHAR Padding6[4]; + VOID* POINTER_64 SavedPriorityState; + ULONGLONG ReservedForCodeCoverage; + VOID* POINTER_64 ThreadPoolData; + VOID* POINTER_64 TlsExpansionSlots; + struct CHPEV2_CPUAREA_INFO* POINTER_64 ChpeV2CpuAreaInfo; + VOID* POINTER_64 Unused; + ULONG MuiGeneration; + ULONG IsImpersonating; + VOID* POINTER_64 NlsCache; + VOID* POINTER_64 pShimData; + ULONG HeapData; + UCHAR Padding7[4]; + VOID* POINTER_64 CurrentTransactionHandle; + TEB_ACTIVE_FRAME64* POINTER_64 ActiveFrame; + VOID* POINTER_64 FlsData; + VOID* POINTER_64 PreferredLanguages; + VOID* POINTER_64 UserPrefLanguages; + VOID* POINTER_64 MergedPrefLanguages; + ULONG MuiImpersonation; + union + { + USHORT CrossTebFlags; + struct + { + USHORT SpareCrossTebBits : 16; + }; + }; + union + { + USHORT SameTebFlags; + struct + { + USHORT SafeThunkCall : 1; + USHORT InDebugPrint : 1; + USHORT HasFiberData : 1; + USHORT SkipThreadAttach : 1; + USHORT WerInShipAssertCode : 1; + USHORT RanProcessInit : 1; + USHORT ClonedThread : 1; + USHORT SuppressDebugMsg : 1; + USHORT DisableUserStackWalk : 1; + USHORT RtlExceptionAttached : 1; + USHORT InitialThread : 1; + USHORT SessionAware : 1; + USHORT LoadOwner : 1; + USHORT LoaderWorker : 1; + USHORT SkipLoaderInit : 1; + USHORT SkipFileAPIBrokering : 1; + }; + }; + VOID* POINTER_64 TxnScopeEnterCallback; + VOID* POINTER_64 TxnScopeExitCallback; + VOID* POINTER_64 TxnScopeContext; + ULONG LockCount; + LONG WowTebOffset; + VOID* POINTER_64 ResourceRetValue; + VOID* POINTER_64 ReservedForWdf; + ULONGLONG ReservedForCrt; + GUID EffectiveContainerId; + ULONGLONG LastSleepCounter; + ULONG SpinCallCount; + UCHAR Padding8[4]; + ULONGLONG ExtendedFeatureDisableMask; +} TEB64, *PTEB64; + +typedef struct _TEB32 +{ + NT_TIB32 NtTib; + WCHAR* POINTER_32 EnvironmentPointer; + CLIENT_ID32 ClientId; + VOID* POINTER_32 ActiveRpcHandle; + VOID* POINTER_32 ThreadLocalStoragePointer; + PEB32* POINTER_32 ProcessEnvironmentBlock; + ULONG LastErrorValue; + ULONG CountOfOwnedCriticalSections; + VOID* POINTER_32 CsrClientThread; + VOID* POINTER_32 Win32ThreadInfo; + ULONG User32Reserved[26]; + ULONG UserReserved[5]; + VOID* POINTER_32 WOW32Reserved; + ULONG CurrentLocale; + ULONG FpSoftwareStatusRegister; + VOID* POINTER_32 ReservedForDebuggerInstrumentation[16]; + VOID* POINTER_32 SystemReserved1[26]; + CHAR PlaceholderCompatibilityMode; + UCHAR PlaceholderHydrationAlwaysExplicit; + CHAR PlaceholderReserved[10]; + ULONG ProxiedProcessId; + ACTIVATION_CONTEXT_STACK32 _ActivationStack; + UCHAR WorkingOnBehalfTicket[8]; + LONG ExceptionCode; + ACTIVATION_CONTEXT_STACK32* POINTER_32 ActivationContextStackPointer; + VOID* POINTER_32 InstrumentationCallbackSp; + VOID* POINTER_32 InstrumentationCallbackPreviousPc; + VOID* POINTER_32 InstrumentationCallbackPreviousSp; + UCHAR InstrumentationCallbackDisabled; + UCHAR SpareBytes[23]; + ULONG TxFsContext; + GDI_TEB_BATCH32 GdiTebBatch; + CLIENT_ID32 RealClientId; + VOID* POINTER_32 GdiCachedProcessHandle; + ULONG GdiClientPID; + ULONG GdiClientTID; + VOID* POINTER_32 GdiThreadLocalInfo; + ULONG Win32ClientInfo[62]; + VOID* POINTER_32 glDispatchTable[233]; + ULONG glReserved1[29]; + VOID* POINTER_32 glReserved2; + VOID* POINTER_32 glSectionInfo; + VOID* POINTER_32 glSection; + VOID* POINTER_32 glTable; + VOID* POINTER_32 glCurrentRC; + VOID* POINTER_32 glContext; + ULONG LastStatusValue; + UNICODE_STRING32 StaticUnicodeString; + WCHAR StaticUnicodeBuffer[261]; + VOID* POINTER_32 DeallocationStack; + VOID* POINTER_32 TlsSlots[64]; + LIST_ENTRY32 TlsLinks; + VOID* POINTER_32 Vdm; + VOID* POINTER_32 ReservedForNtRpc; + VOID* POINTER_32 DbgSsReserved[2]; + ULONG HardErrorMode; + VOID* POINTER_32 Instrumentation[9]; + GUID ActivityId; + VOID* POINTER_32 SubProcessTag; + VOID* POINTER_32 PerflibData; + VOID* POINTER_32 EtwTraceData; + VOID* POINTER_32 WinSockData; + ULONG GdiBatchCount; + union + { + PROCESSOR_NUMBER CurrentIdealProcessor; + union + { + DWORD IdealProcessorValue; + struct + { + UCHAR ReservedPad0; + UCHAR ReservedPad1; + UCHAR ReservedPad2; + UCHAR IdealProcessor; + }; + }; + }; + ULONG GuaranteedStackBytes; + VOID* POINTER_32 ReservedForPerf; + VOID* POINTER_32 ReservedForOle; + ULONG WaitingOnLoaderLock; + VOID* POINTER_32 SavedPriorityState; + ULONG ReservedForCodeCoverage; + VOID* POINTER_32 ThreadPoolData; + VOID* POINTER_32 TlsExpansionSlots; + ULONG MuiGeneration; + ULONG IsImpersonating; + VOID* POINTER_32 NlsCache; + VOID* POINTER_32 pShimData; + ULONG HeapData; + VOID* POINTER_32 CurrentTransactionHandle; + TEB_ACTIVE_FRAME32* POINTER_32 ActiveFrame; + VOID* POINTER_32 FlsData; + VOID* POINTER_32 PreferredLanguages; + VOID* POINTER_32 UserPrefLanguages; + VOID* POINTER_32 MergedPrefLanguages; + ULONG MuiImpersonation; + union + { + USHORT CrossTebFlags; + struct + { + USHORT SpareCrossTebBits : 16; + }; + }; + union + { + USHORT SameTebFlags; + struct + { + USHORT SafeThunkCall : 1; + USHORT InDebugPrint : 1; + USHORT HasFiberData : 1; + USHORT SkipThreadAttach : 1; + USHORT WerInShipAssertCode : 1; + USHORT RanProcessInit : 1; + USHORT ClonedThread : 1; + USHORT SuppressDebugMsg : 1; + USHORT DisableUserStackWalk : 1; + USHORT RtlExceptionAttached : 1; + USHORT InitialThread : 1; + USHORT SessionAware : 1; + USHORT LoadOwner : 1; + USHORT LoaderWorker : 1; + USHORT SkipLoaderInit : 1; + USHORT SkipFileAPIBrokering : 1; + }; + }; + VOID* POINTER_32 TxnScopeEnterCallback; + VOID* POINTER_32 TxnScopeExitCallback; + VOID* POINTER_32 TxnScopeContext; + ULONG LockCount; + LONG WowTebOffset; + VOID* POINTER_32 ResourceRetValue; + VOID* POINTER_32 ReservedForWdf; + ULONGLONG ReservedForCrt; + GUID EffectiveContainerId; + ULONGLONG LastSleepCounter; + ULONG SpinCallCount; + ULONGLONG ExtendedFeatureDisableMask; +} TEB32, *PTEB32; + +#endif /* defined(_KNSOFT_NDK_NT_EXTENSION) */ + +#pragma endregion diff --git a/Source/Include/KNSoft/NDK/NT/Types/Basic.h b/Source/Include/KNSoft/NDK/NT/Types/Basic.h new file mode 100644 index 0000000..589c05b --- /dev/null +++ b/Source/Include/KNSoft/NDK/NT/Types/Basic.h @@ -0,0 +1,237 @@ +#pragma once + +#include "../MinDef.h" + +typedef enum _ALTERNATIVE_ARCHITECTURE_TYPE +{ + StandardDesign, // None == 0 == standard design + NEC98x86, // NEC PC98xx series on X86 + EndAlternatives // past end of known alternatives +} ALTERNATIVE_ARCHITECTURE_TYPE; + +typedef struct _LEAP_SECOND_DATA +{ + UCHAR Enabled; + UCHAR Padding[3]; + ULONG Count; + _Field_size_(Count) LARGE_INTEGER Data[ANYSIZE_ARRAY]; +} LEAP_SECOND_DATA, *PLEAP_SECOND_DATA; + +typedef struct _ACTIVATION_CONTEXT_DATA +{ + ULONG Magic; + ULONG HeaderSize; + ULONG FormatVersion; + ULONG TotalSize; + ULONG DefaultTocOffset; + ULONG ExtendedTocOffset; + ULONG AssemblyRosterOffset; + ULONG Flags; +} ACTIVATION_CONTEXT_DATA, *PACTIVATION_CONTEXT_DATA; + +#pragma region CLIENT_ID[64/32] + +typedef struct _CLIENT_ID +{ + HANDLE UniqueProcess; + HANDLE UniqueThread; +} CLIENT_ID, *PCLIENT_ID; + +#if defined(_KNSOFT_NDK_NT_EXTENSION) + +typedef struct _CLIENT_ID64 +{ + VOID* POINTER_64 UniqueProcess; + VOID* POINTER_64 UniqueThread; +} CLIENT_ID64, *PCLIENT_ID64; + +typedef struct _CLIENT_ID32 +{ + VOID* POINTER_32 UniqueProcess; + VOID* POINTER_32 UniqueThread; +} CLIENT_ID32, *PCLIENT_ID32; + +#endif /* defined(_KNSOFT_NDK_NT_EXTENSION) */ + +#pragma endregion + +#pragma region CURDIR[64/32] + +typedef struct _CURDIR +{ + UNICODE_STRING DosPath; + HANDLE Handle; +} CURDIR, *PCURDIR; + +#if defined(_KNSOFT_NDK_NT_EXTENSION) + +typedef struct _CURDIR64 +{ + UNICODE_STRING64 DosPath; + VOID* POINTER_64 Handle; +} CURDIR64, *PCURDIR64; + +typedef struct _CURDIR32 +{ + UNICODE_STRING32 DosPath; + VOID* POINTER_32 Handle; +} CURDIR32, *PCURDIR32; + +#endif /* defined(_KNSOFT_NDK_NT_EXTENSION) */ + +#pragma endregion + +#pragma region ASSEMBLY_STORAGE_MAP_ENTRY[64/32] + +typedef struct _ASSEMBLY_STORAGE_MAP_ENTRY +{ + ULONG Flags; + UNICODE_STRING DosPath; + HANDLE Handle; +} ASSEMBLY_STORAGE_MAP_ENTRY, *PASSEMBLY_STORAGE_MAP_ENTRY; + +#if defined(_KNSOFT_NDK_NT_EXTENSION) + +typedef struct _ASSEMBLY_STORAGE_MAP_ENTRY64 +{ + ULONG Flags; + UNICODE_STRING64 DosPath; + VOID* POINTER_64 Handle; +} ASSEMBLY_STORAGE_MAP_ENTRY64, *PASSEMBLY_STORAGE_MAP_ENTRY64; + +typedef struct _ASSEMBLY_STORAGE_MAP_ENTRY32 +{ + ULONG Flags; + UNICODE_STRING32 DosPath; + VOID* POINTER_32 Handle; +} ASSEMBLY_STORAGE_MAP_ENTRY32, *PASSEMBLY_STORAGE_MAP_ENTRY32; + +#endif /* defined(_KNSOFT_NDK_NT_EXTENSION) */ + +#pragma endregion + +#pragma region ASSEMBLY_STORAGE_MAP[64/32] + +typedef struct _ASSEMBLY_STORAGE_MAP +{ + ULONG Flags; + ULONG AssemblyCount; + PASSEMBLY_STORAGE_MAP_ENTRY* AssemblyArray; +} ASSEMBLY_STORAGE_MAP, *PASSEMBLY_STORAGE_MAP; + +#if defined(_KNSOFT_NDK_NT_EXTENSION) + +typedef struct _ASSEMBLY_STORAGE_MAP64 +{ + ULONG Flags; + ULONG AssemblyCount; + ASSEMBLY_STORAGE_MAP_ENTRY64* POINTER_64* AssemblyArray; +} ASSEMBLY_STORAGE_MAP64, *PASSEMBLY_STORAGE_MAP64; + +typedef struct _ASSEMBLY_STORAGE_MAP32 +{ + ULONG Flags; + ULONG AssemblyCount; + ASSEMBLY_STORAGE_MAP_ENTRY32* POINTER_32* AssemblyArray; +} ASSEMBLY_STORAGE_MAP32, *PASSEMBLY_STORAGE_MAP32; + +#endif /* defined(_KNSOFT_NDK_NT_EXTENSION) */ + +#pragma endregion + +#pragma region [RTL_]ACTIVATION_CONTEXT_STACK[_FRAME][64/32] + +typedef struct _RTL_ACTIVATION_CONTEXT_STACK_FRAME RTL_ACTIVATION_CONTEXT_STACK_FRAME, *PRTL_ACTIVATION_CONTEXT_STACK_FRAME; +typedef struct _RTL_ACTIVATION_CONTEXT_STACK_FRAME64 RTL_ACTIVATION_CONTEXT_STACK_FRAME64, *PRTL_ACTIVATION_CONTEXT_STACK_FRAME64; +typedef struct _RTL_ACTIVATION_CONTEXT_STACK_FRAME32 RTL_ACTIVATION_CONTEXT_STACK_FRAME32, *PRTL_ACTIVATION_CONTEXT_STACK_FRAME32; + +struct _RTL_ACTIVATION_CONTEXT_STACK_FRAME +{ + struct RTL_ACTIVATION_CONTEXT_STACK_FRAME* Previous; + struct ACTIVATION_CONTEXT* ActivationContext; + DWORD Flags; +}; + +struct _RTL_ACTIVATION_CONTEXT_STACK_FRAME64 +{ + struct RTL_ACTIVATION_CONTEXT_STACK_FRAME* POINTER_64 Previous; + struct ACTIVATION_CONTEXT* POINTER_64 ActivationContext; + ULONG Flags; +}; + +struct _RTL_ACTIVATION_CONTEXT_STACK_FRAME32 +{ + struct RTL_ACTIVATION_CONTEXT_STACK_FRAME* POINTER_32 Previous; + struct ACTIVATION_CONTEXT* POINTER_32 ActivationContext; + ULONG Flags; +}; + +typedef struct _ACTIVATION_CONTEXT_STACK +{ + PRTL_ACTIVATION_CONTEXT_STACK_FRAME ActiveFrame; + LIST_ENTRY FrameListCache; + ULONG Flags; + ULONG NextCookieSequenceNumber; + ULONG StackId; +} ACTIVATION_CONTEXT_STACK, *PACTIVATION_CONTEXT_STACK; + +typedef struct _ACTIVATION_CONTEXT_STACK64 +{ + RTL_ACTIVATION_CONTEXT_STACK_FRAME64* POINTER_64 ActiveFrame; + LIST_ENTRY64 FrameListCache; + ULONG Flags; + ULONG NextCookieSequenceNumber; + ULONG StackId; +} ACTIVATION_CONTEXT_STACK64, *PACTIVATION_CONTEXT_STACK64; + +typedef struct _ACTIVATION_CONTEXT_STACK32 +{ + RTL_ACTIVATION_CONTEXT_STACK_FRAME32* POINTER_32 ActiveFrame; + LIST_ENTRY32 FrameListCache; + ULONG Flags; + ULONG NextCookieSequenceNumber; + ULONG StackId; +} ACTIVATION_CONTEXT_STACK32, *PACTIVATION_CONTEXT_STACK32; + +#pragma endregion + +#pragma region GDI_TEB_BATCH[64/32] + +typedef struct _GDI_TEB_BATCH +{ + struct + { + ULONG Offset : 31; + BOOL HasRenderingCommand : 1; + }; + ULONG_PTR HDC; + ULONG Buffer[310]; +} GDI_TEB_BATCH, *PGDI_TEB_BATCH; + +#if defined(_KNSOFT_NDK_NT_EXTENSION) + +typedef struct _GDI_TEB_BATCH64 +{ + struct + { + ULONG Offset : 31; + BOOL HasRenderingCommand : 1; + }; + ULONGLONG HDC; + ULONG Buffer[310]; +} GDI_TEB_BATCH64, *PGDI_TEB_BATCH64; + +typedef struct _GDI_TEB_BATCH32 +{ + struct + { + ULONG Offset : 31; + BOOL HasRenderingCommand : 1; + }; + ULONG HDC; + ULONG Buffer[310]; +} GDI_TEB_BATCH32, *PGDI_TEB_BATCH32; + +#endif /* defined(_KNSOFT_NDK_NT_EXTENSION) */ + +#pragma endregion diff --git a/Source/Include/KNSoft/NDK/NT/Types/Cm.h b/Source/Include/KNSoft/NDK/NT/Types/Cm.h new file mode 100644 index 0000000..92321bc --- /dev/null +++ b/Source/Include/KNSoft/NDK/NT/Types/Cm.h @@ -0,0 +1,22 @@ +#pragma once + +#include "../MinDef.h" + +typedef enum _KEY_VALUE_INFORMATION_CLASS +{ + KeyValueBasicInformation, + KeyValueFullInformation, + KeyValuePartialInformation, + KeyValueFullInformationAlign64, + KeyValuePartialInformationAlign64, + KeyValueLayerInformation, + MaxKeyValueInfoClass // MaxKeyValueInfoClass should always be the last enum +} KEY_VALUE_INFORMATION_CLASS; + +typedef struct _KEY_VALUE_PARTIAL_INFORMATION +{ + ULONG TitleIndex; + ULONG Type; + ULONG DataLength; + _Field_size_bytes_(DataLength) UCHAR Data[ANYSIZE_ARRAY]; // Variable size +} KEY_VALUE_PARTIAL_INFORMATION, *PKEY_VALUE_PARTIAL_INFORMATION; diff --git a/Source/Include/KNSoft/NDK/NT/Types/Ex.h b/Source/Include/KNSoft/NDK/NT/Types/Ex.h new file mode 100644 index 0000000..171d394 --- /dev/null +++ b/Source/Include/KNSoft/NDK/NT/Types/Ex.h @@ -0,0 +1,56 @@ +#pragma once + +#include "../MinDef.h" + +#pragma region Atom + +typedef enum _ATOM_INFORMATION_CLASS +{ + AtomBasicInformation, + AtomTableInformation, +} ATOM_INFORMATION_CLASS, *PATOM_INFORMATION_CLASS; + +typedef struct _ATOM_BASIC_INFORMATION +{ + USHORT UsageCount; + USHORT Flags; + USHORT NameLength; + _Field_size_(NameLength) WCHAR Name[ANYSIZE_ARRAY]; +} ATOM_BASIC_INFORMATION, *PATOM_BASIC_INFORMATION; + +typedef struct _ATOM_TABLE_INFORMATION +{ + ULONG NumberOfAtoms; + _Field_size_(NumberOfAtoms) USHORT Atoms[ANYSIZE_ARRAY]; +} ATOM_TABLE_INFORMATION, *PATOM_TABLE_INFORMATION; + +typedef USHORT RTL_ATOM, *PRTL_ATOM; + +#pragma endregion + +#pragma region Event + +typedef enum _EVENT_INFORMATION_CLASS +{ + EventBasicInformation +} EVENT_INFORMATION_CLASS; + +typedef struct _EVENT_BASIC_INFORMATION +{ + EVENT_TYPE EventType; + LONG EventState; +} EVENT_BASIC_INFORMATION, *PEVENT_BASIC_INFORMATION; + +#pragma endregion + +#pragma region Firmware variable attributes + +#define VARIABLE_ATTRIBUTE_NON_VOLATILE 0x00000001 +#define VARIABLE_ATTRIBUTE_BOOTSERVICE_ACCESS 0x00000002 +#define VARIABLE_ATTRIBUTE_RUNTIME_ACCESS 0x00000004 +#define VARIABLE_ATTRIBUTE_HARDWARE_ERROR_RECORD 0x00000008 +#define VARIABLE_ATTRIBUTE_AUTHENTICATED_WRITE_ACCESS 0x00000010 +#define VARIABLE_ATTRIBUTE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS 0x00000020 +#define VARIABLE_ATTRIBUTE_APPEND_WRITE 0x00000040 + +#pragma endregion diff --git a/Source/Include/KNSoft/NDK/NT/Types/Fs.h b/Source/Include/KNSoft/NDK/NT/Types/Fs.h new file mode 100644 index 0000000..38b094a --- /dev/null +++ b/Source/Include/KNSoft/NDK/NT/Types/Fs.h @@ -0,0 +1,215 @@ +#pragma once + +#include "../MinDef.h" + +// +// Define the create disposition values +// + +#define FILE_SUPERSEDE 0x00000000 +#define FILE_OPEN 0x00000001 +#define FILE_CREATE 0x00000002 +#define FILE_OPEN_IF 0x00000003 +#define FILE_OVERWRITE 0x00000004 +#define FILE_OVERWRITE_IF 0x00000005 +#define FILE_MAXIMUM_DISPOSITION 0x00000005 + +// +// Define the create/open option flags +// + +#define FILE_DIRECTORY_FILE 0x00000001 +#define FILE_WRITE_THROUGH 0x00000002 +#define FILE_SEQUENTIAL_ONLY 0x00000004 +#define FILE_NO_INTERMEDIATE_BUFFERING 0x00000008 + +#define FILE_SYNCHRONOUS_IO_ALERT 0x00000010 +#define FILE_SYNCHRONOUS_IO_NONALERT 0x00000020 +#define FILE_NON_DIRECTORY_FILE 0x00000040 +#define FILE_CREATE_TREE_CONNECTION 0x00000080 + +#define FILE_COMPLETE_IF_OPLOCKED 0x00000100 +#define FILE_NO_EA_KNOWLEDGE 0x00000200 +#define FILE_OPEN_REMOTE_INSTANCE 0x00000400 +#define FILE_RANDOM_ACCESS 0x00000800 + +#define FILE_DELETE_ON_CLOSE 0x00001000 +#define FILE_OPEN_BY_FILE_ID 0x00002000 +#define FILE_OPEN_FOR_BACKUP_INTENT 0x00004000 +#define FILE_NO_COMPRESSION 0x00008000 + +#if (NTDDI_VERSION >= NTDDI_WIN7) +#define FILE_OPEN_REQUIRING_OPLOCK 0x00010000 +#define FILE_DISALLOW_EXCLUSIVE 0x00020000 +#endif /* NTDDI_VERSION >= NTDDI_WIN7 */ +#if (NTDDI_VERSION >= NTDDI_WIN8) +#define FILE_SESSION_AWARE 0x00040000 +#endif /* NTDDI_VERSION >= NTDDI_WIN8 */ + +// +// CreateOptions flag to pass in call to CreateFile to allow the write through xro.sys +// + +#define FILE_RESERVE_OPFILTER 0x00100000 +#define FILE_OPEN_REPARSE_POINT 0x00200000 +#define FILE_OPEN_NO_RECALL 0x00400000 +#define FILE_OPEN_FOR_FREE_SPACE_QUERY 0x00800000 + +typedef enum _FILE_INFORMATION_CLASS +{ + FileDirectoryInformation = 1, + FileFullDirectoryInformation, // 2 + FileBothDirectoryInformation, // 3 + FileBasicInformation, // 4 + FileStandardInformation, // 5 + FileInternalInformation, // 6 + FileEaInformation, // 7 + FileAccessInformation, // 8 + FileNameInformation, // 9 + FileRenameInformation, // 10 + FileLinkInformation, // 11 + FileNamesInformation, // 12 + FileDispositionInformation, // 13 + FilePositionInformation, // 14 + FileFullEaInformation, // 15 + FileModeInformation, // 16 + FileAlignmentInformation, // 17 + FileAllInformation, // 18 + FileAllocationInformation, // 19 + FileEndOfFileInformation, // 20 + FileAlternateNameInformation, // 21 + FileStreamInformation, // 22 + FilePipeInformation, // 23 + FilePipeLocalInformation, // 24 + FilePipeRemoteInformation, // 25 + FileMailslotQueryInformation, // 26 + FileMailslotSetInformation, // 27 + FileCompressionInformation, // 28 + FileObjectIdInformation, // 29 + FileCompletionInformation, // 30 + FileMoveClusterInformation, // 31 + FileQuotaInformation, // 32 + FileReparsePointInformation, // 33 + FileNetworkOpenInformation, // 34 + FileAttributeTagInformation, // 35 + FileTrackingInformation, // 36 + FileIdBothDirectoryInformation, // 37 + FileIdFullDirectoryInformation, // 38 + FileValidDataLengthInformation, // 39 + FileShortNameInformation, // 40 + FileIoCompletionNotificationInformation, // 41 + FileIoStatusBlockRangeInformation, // 42 + FileIoPriorityHintInformation, // 43 + FileSfioReserveInformation, // 44 + FileSfioVolumeInformation, // 45 + FileHardLinkInformation, // 46 + FileProcessIdsUsingFileInformation, // 47 + FileNormalizedNameInformation, // 48 + FileNetworkPhysicalNameInformation, // 49 + FileIdGlobalTxDirectoryInformation, // 50 + FileIsRemoteDeviceInformation, // 51 + FileUnusedInformation, // 52 + FileNumaNodeInformation, // 53 + FileStandardLinkInformation, // 54 + FileRemoteProtocolInformation, // 55 + + // + // These are special versions of these operations (defined earlier) + // which can be used by kernel mode drivers only to bypass security + // access checks for Rename and HardLink operations. These operations + // are only recognized by the IOManager, a file system should never + // receive these. + // + + FileRenameInformationBypassAccessCheck, // 56 + FileLinkInformationBypassAccessCheck, // 57 + + // + // End of special information classes reserved for IOManager. + // + + FileVolumeNameInformation, // 58 + FileIdInformation, // 59 + FileIdExtdDirectoryInformation, // 60 + FileReplaceCompletionInformation, // 61 + FileHardLinkFullIdInformation, // 62 + FileIdExtdBothDirectoryInformation, // 63 + FileDispositionInformationEx, // 64 + FileRenameInformationEx, // 65 + FileRenameInformationExBypassAccessCheck, // 66 + FileDesiredStorageClassInformation, // 67 + FileStatInformation, // 68 + FileMemoryPartitionInformation, // 69 + FileStatLxInformation, // 70 + FileCaseSensitiveInformation, // 71 + FileLinkInformationEx, // 72 + FileLinkInformationExBypassAccessCheck, // 73 + FileStorageReserveIdInformation, // 74 + FileCaseSensitiveInformationForceAccessCheck, // 75 + FileKnownFolderInformation, // 76 + + FileMaximumInformation +} FILE_INFORMATION_CLASS, *PFILE_INFORMATION_CLASS; + +typedef struct _FILE_BASIC_INFORMATION +{ + LARGE_INTEGER CreationTime; + LARGE_INTEGER LastAccessTime; + LARGE_INTEGER LastWriteTime; + LARGE_INTEGER ChangeTime; + ULONG FileAttributes; +} FILE_BASIC_INFORMATION, *PFILE_BASIC_INFORMATION; + +typedef struct _FILE_STANDARD_INFORMATION +{ + LARGE_INTEGER AllocationSize; + LARGE_INTEGER EndOfFile; + ULONG NumberOfLinks; + BOOLEAN DeletePending; + BOOLEAN Directory; +} FILE_STANDARD_INFORMATION, *PFILE_STANDARD_INFORMATION; + +typedef struct _FILE_NETWORK_OPEN_INFORMATION +{ + LARGE_INTEGER CreationTime; + LARGE_INTEGER LastAccessTime; + LARGE_INTEGER LastWriteTime; + LARGE_INTEGER ChangeTime; + LARGE_INTEGER AllocationSize; + LARGE_INTEGER EndOfFile; + ULONG FileAttributes; +} FILE_NETWORK_OPEN_INFORMATION, *PFILE_NETWORK_OPEN_INFORMATION; + +#pragma push_macro("DeleteFile") +#undef DeleteFile +typedef struct _FILE_DISPOSITION_INFORMATION +{ + BOOLEAN DeleteFile; +} FILE_DISPOSITION_INFORMATION, *PFILE_DISPOSITION_INFORMATION; +#pragma pop_macro("DeleteFile") + +typedef struct _FILE_DISPOSITION_INFORMATION_EX +{ + ULONG Flags; +} FILE_DISPOSITION_INFORMATION_EX, *PFILE_DISPOSITION_INFORMATION_EX; + +typedef struct _FILE_END_OF_FILE_INFORMATION +{ + LARGE_INTEGER EndOfFile; +} FILE_END_OF_FILE_INFORMATION, *PFILE_END_OF_FILE_INFORMATION; + +typedef struct _FILE_FULL_DIR_INFORMATION +{ + ULONG NextEntryOffset; + ULONG FileIndex; + LARGE_INTEGER CreationTime; + LARGE_INTEGER LastAccessTime; + LARGE_INTEGER LastWriteTime; + LARGE_INTEGER ChangeTime; + LARGE_INTEGER EndOfFile; + LARGE_INTEGER AllocationSize; + ULONG FileAttributes; + ULONG FileNameLength; + ULONG EaSize; + _Field_size_bytes_(FileNameLength) WCHAR FileName[ANYSIZE_ARRAY]; +} FILE_FULL_DIR_INFORMATION, *PFILE_FULL_DIR_INFORMATION; diff --git a/Source/Include/KNSoft/NDK/NT/Types/Io.h b/Source/Include/KNSoft/NDK/NT/Types/Io.h new file mode 100644 index 0000000..a138c98 --- /dev/null +++ b/Source/Include/KNSoft/NDK/NT/Types/Io.h @@ -0,0 +1,21 @@ +#pragma once + +#include "../MinDef.h" + +typedef struct _IO_STATUS_BLOCK +{ + union + { + NTSTATUS Status; + PVOID Pointer; + }; + + ULONG_PTR Information; +} IO_STATUS_BLOCK, *PIO_STATUS_BLOCK; + +typedef +VOID +(NTAPI *PIO_APC_ROUTINE) ( + _In_ PVOID ApcContext, + _In_ PIO_STATUS_BLOCK IoStatusBlock, + _In_ ULONG Reserved); diff --git a/Source/Include/KNSoft/NDK/NT/Types/Ke.h b/Source/Include/KNSoft/NDK/NT/Types/Ke.h new file mode 100644 index 0000000..612ddb4 --- /dev/null +++ b/Source/Include/KNSoft/NDK/NT/Types/Ke.h @@ -0,0 +1,613 @@ +#pragma once + +#include "../MinDef.h" +#include "../Private/TargetArch.h" + +#include "Basic.h" + +#define PROCESSOR_FEATURE_MAX 64 + +typedef struct _KSYSTEM_TIME +{ + ULONG LowPart; + LONG High1Time; + LONG High2Time; +} KSYSTEM_TIME, *PKSYSTEM_TIME; + +typedef LONG KPRIORITY; + +typedef enum _KTHREAD_STATE +{ + Initialized, + Ready, + Running, + Standby, + Terminated, + Waiting, + Transition, + DeferredReady, + GateWait +} KTHREAD_STATE, *PKTHREAD_STATE; + +typedef enum _KWAIT_REASON +{ + Executive, + FreePage, + PageIn, + PoolAllocation, + DelayExecution, + Suspended, + UserRequest, + WrExecutive, + WrFreePage, + WrPageIn, + WrPoolAllocation, + WrDelayExecution, + WrSuspended, + WrUserRequest, + WrSpare0, + WrQueue, + WrLpcReceive, + WrLpcReply, + WrVirtualMemory, + WrPageOut, + WrRendezvous, + WrKeyedEvent, + WrTerminated, + WrProcessInSwap, + WrCpuRateControl, + WrCalloutStack, + WrKernel, + WrResource, + WrPushLock, + WrMutex, + WrQuantumEnd, + WrDispatchInt, + WrPreempted, + WrYieldExecution, + WrFastMutex, + WrGuardedMutex, + WrRundown, + WrAlertByThreadId, + WrDeferredPreempt, + WrPhysicalFault, + WrIoRing, + MaximumWaitReason +} KWAIT_REASON; + +typedef struct _KUSER_SHARED_DATA +{ + + // + // Current low 32-bit of tick count and tick count multiplier. + // + // N.B. The tick count is updated each time the clock ticks. + // + + ULONG TickCountLowDeprecated; + ULONG TickCountMultiplier; + + // + // Current 64-bit interrupt time in 100ns units. + // + + volatile KSYSTEM_TIME InterruptTime; + + // + // Current 64-bit system time in 100ns units. + // + + volatile KSYSTEM_TIME SystemTime; + + // + // Current 64-bit time zone bias. + // + + volatile KSYSTEM_TIME TimeZoneBias; + + // + // Support image magic number range for the host system. + // + // N.B. This is an inclusive range. + // + + USHORT ImageNumberLow; + USHORT ImageNumberHigh; + + // + // Copy of system root in unicode. + // + // N.B. This field must be accessed via the RtlGetNtSystemRoot API for + // an accurate result. + // + + WCHAR NtSystemRoot[260]; + + // + // Maximum stack trace depth if tracing enabled. + // + + ULONG MaxStackTraceDepth; + + // + // Crypto exponent value. + // + + ULONG CryptoExponent; + + // + // Time zone ID. + // + + ULONG TimeZoneId; + ULONG LargePageMinimum; + + // + // This value controls the AIT Sampling rate. + // + + ULONG AitSamplingValue; + + // + // This value controls switchback processing. + // + + ULONG AppCompatFlag; + + // + // Current Kernel Root RNG state seed version + // + + ULONGLONG RNGSeedVersion; + + // + // This value controls assertion failure handling. + // + + ULONG GlobalValidationRunlevel; + + volatile LONG TimeZoneBiasStamp; + + // + // The shared collective build number undecorated with C or F. + // GetVersionEx hides the real number + // + + ULONG NtBuildNumber; + + // + // Product type. + // + // N.B. This field must be accessed via the RtlGetNtProductType API for + // an accurate result. + // + + NT_PRODUCT_TYPE NtProductType; + BOOLEAN ProductTypeIsValid; + BOOLEAN Reserved0[1]; + USHORT NativeProcessorArchitecture; + + // + // The NT Version. + // + // N. B. Note that each process sees a version from its PEB, but if the + // process is running with an altered view of the system version, + // the following two fields are used to correctly identify the + // version + // + + ULONG NtMajorVersion; + ULONG NtMinorVersion; + + // + // Processor features. + // + + BOOLEAN ProcessorFeatures[PROCESSOR_FEATURE_MAX]; + + // + // Reserved fields - do not use. + // + + ULONG Reserved1; + ULONG Reserved3; + + // + // Time slippage while in debugger. + // + + volatile ULONG TimeSlip; + + // + // Alternative system architecture, e.g., NEC PC98xx on x86. + // + + ALTERNATIVE_ARCHITECTURE_TYPE AlternativeArchitecture; + + // + // Boot sequence, incremented for each boot attempt by the OS loader. + // + + ULONG BootId; + + // + // If the system is an evaluation unit, the following field contains the + // date and time that the evaluation unit expires. A value of 0 indicates + // that there is no expiration. A non-zero value is the UTC absolute time + // that the system expires. + // + + LARGE_INTEGER SystemExpirationDate; + + // + // Suite support. + // + // N.B. This field must be accessed via the RtlGetSuiteMask API for + // an accurate result. + // + + ULONG SuiteMask; + + // + // TRUE if a kernel debugger is connected/enabled. + // + + BOOLEAN KdDebuggerEnabled; + + // + // Mitigation policies. + // + + union + { + UCHAR MitigationPolicies; + struct + { + UCHAR NXSupportPolicy : 2; + UCHAR SEHValidationPolicy : 2; + UCHAR CurDirDevicesSkippedForDlls : 2; + UCHAR Reserved : 2; + }; + }; + + // + // Measured duration of a single processor yield, in cycles. This is used by + // lock packages to determine how many times to spin waiting for a state + // change before blocking. + // + + USHORT CyclesPerYield; + + // + // Current console session Id. Always zero on non-TS systems. + // + // N.B. This field must be accessed via the RtlGetActiveConsoleId API for an + // accurate result. + // + + volatile ULONG ActiveConsoleId; + + // + // Force-dismounts cause handles to become invalid. Rather than always + // probe handles, a serial number of dismounts is maintained that clients + // can use to see if they need to probe handles. + // + + volatile ULONG DismountCount; + + // + // This field indicates the status of the 64-bit COM+ package on the + // system. It indicates whether the Itermediate Language (IL) COM+ + // images need to use the 64-bit COM+ runtime or the 32-bit COM+ runtime. + // + + ULONG ComPlusPackage; + + // + // Time in tick count for system-wide last user input across all terminal + // sessions. For MP performance, it is not updated all the time (e.g. once + // a minute per session). It is used for idle detection. + // + + ULONG LastSystemRITEventTickCount; + + // + // Number of physical pages in the system. This can dynamically change as + // physical memory can be added or removed from a running system. + // + + ULONG NumberOfPhysicalPages; + + // + // True if the system was booted in safe boot mode. + // + + BOOLEAN SafeBootMode; + + // + // Virtualization flags + // + + union + { + UCHAR VirtualizationFlags; + +#if defined(_ARM64_) + // + // Keep in sync with arc.w + // + struct + { + UCHAR ArchStartedInEl2 : 1; + UCHAR QcSlIsSupported : 1; + UCHAR : 6; + }; +#endif // _ARM64_ + }; + + // + // Reserved (available for reuse). + // + + UCHAR Reserved12[2]; + + // + // This is a packed bitfield that contains various flags concerning + // the system state. They must be manipulated using interlocked + // operations. + // + // N.B. DbgMultiSessionSku must be accessed via the RtlIsMultiSessionSku + // API for an accurate result + // + + union + { + ULONG SharedDataFlags; + struct + { + + // + // The following bit fields are for the debugger only. Do not use. + // Use the bit definitions instead. + // + + ULONG DbgErrorPortPresent : 1; + ULONG DbgElevationEnabled : 1; + ULONG DbgVirtEnabled : 1; + ULONG DbgInstallerDetectEnabled : 1; + ULONG DbgLkgEnabled : 1; + ULONG DbgDynProcessorEnabled : 1; + ULONG DbgConsoleBrokerEnabled : 1; + ULONG DbgSecureBootEnabled : 1; + ULONG DbgMultiSessionSku : 1; + ULONG DbgMultiUsersInSessionSku : 1; + ULONG DbgStateSeparationEnabled : 1; + ULONG SpareBits : 21; + } DUMMYSTRUCTNAME2; + } DUMMYUNIONNAME2; + + ULONG DataFlagsPad[1]; + + // + // Depending on the processor, the code for fast system call will differ, + // Stub code is provided pointers below to access the appropriate code. + // + // N.B. The following field is only used on 32-bit systems. + // + + ULONGLONG TestRetInstruction; + LONGLONG QpcFrequency; + + // + // On AMD64, this value is initialized to a nonzero value if the system + // operates with an altered view of the system service call mechanism. + // + + ULONG SystemCall; + + // + // Reserved field - do not use. Used to be UserCetAvailableEnvironments. + // + + ULONG Reserved2; + + // + // Reserved, available for reuse. + // + + ULONGLONG SystemCallPad[2]; + + // + // The 64-bit tick count. + // + + union + { + volatile KSYSTEM_TIME TickCount; + volatile ULONG64 TickCountQuad; + struct + { + ULONG ReservedTickCountOverlay[3]; + ULONG TickCountPad[1]; + } DUMMYSTRUCTNAME; + } DUMMYUNIONNAME3; + + // + // Cookie for encoding pointers system wide. + // + + ULONG Cookie; + ULONG CookiePad[1]; + + // + // Client id of the process having the focus in the current + // active console session id. + // + // N.B. This field must be accessed via the + // RtlGetConsoleSessionForegroundProcessId API for an accurate result. + // + + LONGLONG ConsoleSessionForegroundProcessId; + + // + // N.B. The following data is used to implement the precise time + // services. It is aligned on a 64-byte cache-line boundary and + // arranged in the order of typical accesses. + // + // Placeholder for the (internal) time update lock. + // + + ULONGLONG TimeUpdateLock; + + // + // The performance counter value used to establish the current system time. + // + + ULONGLONG BaselineSystemTimeQpc; + + // + // The performance counter value used to compute the last interrupt time. + // + + ULONGLONG BaselineInterruptTimeQpc; + + // + // The scaled number of system time seconds represented by a single + // performance count (this value may vary to achieve time synchronization). + // + + ULONGLONG QpcSystemTimeIncrement; + + // + // The scaled number of interrupt time seconds represented by a single + // performance count (this value is constant after the system is booted). + // + + ULONGLONG QpcInterruptTimeIncrement; + + // + // The scaling shift count applied to the performance counter system time + // increment. + // + + UCHAR QpcSystemTimeIncrementShift; + + // + // The scaling shift count applied to the performance counter interrupt time + // increment. + // + + UCHAR QpcInterruptTimeIncrementShift; + + // + // The count of unparked processors. + // + + USHORT UnparkedProcessorCount; + + // + // A bitmask of enclave features supported on this system. + // + // N.B. This field must be accessed via the RtlIsEnclareFeaturePresent API for an + // accurate result. + // + + ULONG EnclaveFeatureMask[4]; + + // + // Current coverage round for telemetry based coverage. + // + + ULONG TelemetryCoverageRound; + + // + // The following field is used for ETW user mode global logging + // (UMGL). + // + + USHORT UserModeGlobalLogger[16]; + + // + // Settings that can enable the use of Image File Execution Options + // from HKCU in addition to the original HKLM. + // + + ULONG ImageFileExecutionOptions; + + // + // Generation of the kernel structure holding system language information + // + + ULONG LangGenerationCount; + + // + // Reserved (available for reuse). + // + + ULONGLONG Reserved4; + + // + // Current 64-bit interrupt time bias in 100ns units. + // + + volatile ULONGLONG InterruptTimeBias; + + // + // Current 64-bit performance counter bias, in performance counter units + // before the shift is applied. + // + + volatile ULONGLONG QpcBias; + + // + // Number of active processors and groups. + // + + ULONG ActiveProcessorCount; + volatile UCHAR ActiveGroupCount; + + // + // Reserved (available for re-use). + // + + UCHAR Reserved9; + + union + { + USHORT QpcData; + struct + { + + // + // A boolean indicating whether performance counter queries + // can read the counter directly (bypassing the system call). + // + + volatile UCHAR QpcBypassEnabled; + + // + // Shift applied to the raw counter value to derive the + // QPC count. + // + + UCHAR QpcShift; + }; + }; + + LARGE_INTEGER TimeZoneBiasEffectiveStart; + LARGE_INTEGER TimeZoneBiasEffectiveEnd; + + // + // Extended processor state configuration + // + + XSTATE_CONFIGURATION XState; + + KSYSTEM_TIME FeatureConfigurationChangeStamp; + ULONG Spare; + ULONG64 UserPointerAuthMask; + +} KUSER_SHARED_DATA, *PKUSER_SHARED_DATA; +typedef const struct _KUSER_SHARED_DATA* PCKUSER_SHARED_DATA; + +#define SharedUserData ((PCKUSER_SHARED_DATA)MM_SHARED_USER_DATA_VA) diff --git a/Source/Include/KNSoft/NDK/NT/Types/Ldr.h b/Source/Include/KNSoft/NDK/NT/Types/Ldr.h new file mode 100644 index 0000000..b2d447c --- /dev/null +++ b/Source/Include/KNSoft/NDK/NT/Types/Ldr.h @@ -0,0 +1,340 @@ +#pragma once + +#include "../MinDef.h" + +#include "Rtl.h" + +typedef struct _LDR_SERVICE_TAG_RECORD LDR_SERVICE_TAG_RECORD, *PLDR_SERVICE_TAG_RECORD; + +struct _LDR_SERVICE_TAG_RECORD +{ + PLDR_SERVICE_TAG_RECORD Next; + UINT ServiceTag; +}; + +typedef enum _LDR_DDAG_STATE +{ + LdrModulesMerged = -5, + LdrModulesInitError = -4, + LdrModulesSnapError = -3, + LdrModulesUnloaded = -2, + LdrModulesUnloading = -1, + LdrModulesPlaceHolder = 0, + LdrModulesMapping = 1, + LdrModulesMapped = 2, + LdrModulesWaitingForDependencies = 3, + LdrModulesSnapping = 4, + LdrModulesSnapped = 5, + LdrModulesCondensed = 6, + LdrModulesReadyToInit = 7, + LdrModulesInitializing = 8, + LdrModulesReadyToRun = 9, +} LDR_DDAG_STATE, *PLDR_DDAG_STATE; + +typedef struct _LDRP_CSLIST +{ + SINGLE_LIST_ENTRY Tail; +} LDRP_CSLIST, *PLDRP_CSLIST; + +typedef struct _LDR_DDAG_NODE +{ + LIST_ENTRY Modules; + PLDR_SERVICE_TAG_RECORD ServiceTagList; + UINT LoadCount; + UINT LoadWhileUnloadingCount; + PVOID LowestLink; + LDRP_CSLIST Dependencies; + LDRP_CSLIST IncomingDependencies; + LDR_DDAG_STATE State; + SINGLE_LIST_ENTRY CondenseLink; + UINT PreorderNumber; +} LDR_DDAG_NODE, *PLDR_DDAG_NODE; + +typedef enum _LDR_HOT_PATCH_STATE +{ + LdrHotPatchBaseImage = 0, + LdrHotPatchNotApplied = 1, + LdrHotPatchAppliedReverse = 2, + LdrHotPatchAppliedForward = 3, + LdrHotPatchFailedToPatch = 4, + LdrHotPatchStateMax = 5 +}LDR_HOT_PATCH_STATE, *PLDR_HOT_PATCH_STATE; + +typedef enum _LDR_DLL_LOAD_REASON +{ + LoadReasonStaticDependency = 0, + LoadReasonStaticForwarderDependency = 1, + LoadReasonDynamicForwarderDependency = 2, + LoadReasonDelayloadDependency = 3, + LoadReasonDynamicLoad = 4, + LoadReasonAsImageLoad = 5, + LoadReasonAsDataLoad = 6, + LoadReasonEnclavePrimary = 7, + LoadReasonEnclaveDependency = 8, + LoadReasonPatchImage = 9, + LoadReasonUnknown = -1 +} LDR_DLL_LOAD_REASON, *PLDR_DLL_LOAD_REASON; + +#define LDR_DLL_NOTIFICATION_REASON_LOADED 1 +#define LDR_DLL_NOTIFICATION_REASON_UNLOADED 2 + +typedef struct _LDR_DLL_LOADED_NOTIFICATION_DATA +{ + ULONG Flags; + PCUNICODE_STRING FullDllName; + PCUNICODE_STRING BaseDllName; + PVOID DllBase; + ULONG SizeOfImage; +} LDR_DLL_LOADED_NOTIFICATION_DATA, *PLDR_DLL_LOADED_NOTIFICATION_DATA; + +typedef struct _LDR_DLL_UNLOADED_NOTIFICATION_DATA +{ + ULONG Flags; + PCUNICODE_STRING FullDllName; + PCUNICODE_STRING BaseDllName; + PVOID DllBase; + ULONG SizeOfImage; +} LDR_DLL_UNLOADED_NOTIFICATION_DATA, *PLDR_DLL_UNLOADED_NOTIFICATION_DATA; + +typedef union _LDR_DLL_NOTIFICATION_DATA +{ + LDR_DLL_LOADED_NOTIFICATION_DATA Loaded; + LDR_DLL_UNLOADED_NOTIFICATION_DATA Unloaded; +} LDR_DLL_NOTIFICATION_DATA, *PLDR_DLL_NOTIFICATION_DATA, * const PCLDR_DLL_NOTIFICATION_DATA; + +typedef +VOID +(CALLBACK *PLDR_DLL_NOTIFICATION_FUNCTION)( + _In_ ULONG NotificationReason, + _In_ PCLDR_DLL_NOTIFICATION_DATA NotificationData, + _In_opt_ PVOID Context); + +#pragma region LDR_DATA_TABLE_ENTRY[64/32] + +typedef struct _LDR_DATA_TABLE_ENTRY +{ + LIST_ENTRY InLoadOrderModuleList; + LIST_ENTRY InMemoryOrderModuleList; + LIST_ENTRY InInitializationOrderModuleList; + PVOID DllBase; + PVOID EntryPoint; + ULONG SizeOfImage; + UNICODE_STRING FullDllName; + UNICODE_STRING BaseDllName; + union + { + UCHAR FlagGroup[4]; + ULONG Flags; + struct + { + ULONG PackagedBinary : 1; + ULONG MarkedForRemoval : 1; + ULONG ImageDll : 1; + ULONG LoadNotificationsSent : 1; + ULONG TelemetryEntryProcessed : 1; + ULONG ProcessStaticImport : 1; + ULONG InLegacyLists : 1; + ULONG InIndexes : 1; + ULONG ShimDll : 1; + ULONG InExceptionTable : 1; + ULONG ReservedFlags1 : 2; + ULONG LoadInProgress : 1; + ULONG LoadConfigProcessed : 1; + ULONG EntryProcessed : 1; + ULONG ProtectDelayLoad : 1; + ULONG ReservedFlags3 : 2; + ULONG DontCallForThreads : 1; + ULONG ProcessAttachCalled : 1; + ULONG ProcessAttachFailed : 1; + ULONG CorDeferredValidate : 1; + ULONG CorImage : 1; + ULONG DontRelocate : 1; + ULONG CorILOnly : 1; + ULONG ChpeImage : 1; + ULONG ChpeEmulatorImage : 1; + ULONG ReservedFlags5 : 1; + ULONG Redirected : 1; + ULONG ReservedFlags6 : 2; + ULONG CompatDatabaseProcessed : 1; + }; + }; + USHORT ObsoleteLoadCount; + USHORT TlsIndex; + LIST_ENTRY HashLinks; + ULONG TimeDateStamp; + struct ACTIVATION_CONTEXT* EntryPointActivationContext; + PVOID Lock; + PLDR_DDAG_NODE DdagNode; + LIST_ENTRY NodeModuleLink; + struct LDRP_LOAD_CONTEXT* LoadContext; + PVOID ParentDllBase; + PVOID SwitchBackContext; + RTL_BALANCED_NODE BaseAddressIndexNode; + RTL_BALANCED_NODE MappingInfoIndexNode; + ULONG_PTR OriginalBase; + LARGE_INTEGER LoadTime; + ULONG BaseNameHashValue; + LDR_DLL_LOAD_REASON LoadReason; + ULONG ImplicitPathOptions; + ULONG ReferenceCount; + ULONG DependentLoadFlags; + UCHAR SigningLevel; + ULONG CheckSum; + PVOID ActivePatchImageBase; + LDR_HOT_PATCH_STATE HotPatchState; +} LDR_DATA_TABLE_ENTRY, *PLDR_DATA_TABLE_ENTRY; + +#if defined(_KNSOFT_NDK_NT_EXTENSION) + +typedef struct _LDR_DATA_TABLE_ENTRY64 +{ + LIST_ENTRY64 InLoadOrderModuleList; + LIST_ENTRY64 InMemoryOrderModuleList; + LIST_ENTRY64 InInitializationOrderModuleList; + VOID* POINTER_64 DllBase; + VOID* POINTER_64 EntryPoint; + ULONG SizeOfImage; + UNICODE_STRING64 FullDllName; + UNICODE_STRING64 BaseDllName; + union + { + UCHAR FlagGroup[4]; + ULONG Flags; + struct + { + ULONG PackagedBinary : 1; + ULONG MarkedForRemoval : 1; + ULONG ImageDll : 1; + ULONG LoadNotificationsSent : 1; + ULONG TelemetryEntryProcessed : 1; + ULONG ProcessStaticImport : 1; + ULONG InLegacyLists : 1; + ULONG InIndexes : 1; + ULONG ShimDll : 1; + ULONG InExceptionTable : 1; + ULONG ReservedFlags1 : 2; + ULONG LoadInProgress : 1; + ULONG LoadConfigProcessed : 1; + ULONG EntryProcessed : 1; + ULONG ProtectDelayLoad : 1; + ULONG ReservedFlags3 : 2; + ULONG DontCallForThreads : 1; + ULONG ProcessAttachCalled : 1; + ULONG ProcessAttachFailed : 1; + ULONG CorDeferredValidate : 1; + ULONG CorImage : 1; + ULONG DontRelocate : 1; + ULONG CorILOnly : 1; + ULONG ChpeImage : 1; + ULONG ChpeEmulatorImage : 1; + ULONG ReservedFlags5 : 1; + ULONG Redirected : 1; + ULONG ReservedFlags6 : 2; + ULONG CompatDatabaseProcessed : 1; + }; + }; + USHORT ObsoleteLoadCount; + USHORT TlsIndex; + LIST_ENTRY64 HashLinks; + ULONG TimeDateStamp; + struct ACTIVATION_CONTEXT* POINTER_64 EntryPointActivationContext; + VOID* POINTER_64 Lock; + LDR_DDAG_NODE* POINTER_64 DdagNode; // FIXME: Too complex + LIST_ENTRY64 NodeModuleLink; + struct LDRP_LOAD_CONTEXT* POINTER_64 LoadContext; + VOID* POINTER_64 ParentDllBase; + VOID* POINTER_64 SwitchBackContext; + RTL_BALANCED_NODE64 BaseAddressIndexNode; + RTL_BALANCED_NODE64 MappingInfoIndexNode; + ULONGLONG OriginalBase; + LARGE_INTEGER LoadTime; + ULONG BaseNameHashValue; + LDR_DLL_LOAD_REASON LoadReason; + ULONG ImplicitPathOptions; + ULONG ReferenceCount; + ULONG DependentLoadFlags; + UCHAR SigningLevel; + ULONG CheckSum; + VOID* POINTER_64 ActivePatchImageBase; + LDR_HOT_PATCH_STATE HotPatchState; +} LDR_DATA_TABLE_ENTRY64, *PLDR_DATA_TABLE_ENTRY64; + +typedef struct _LDR_DATA_TABLE_ENTRY32 +{ + LIST_ENTRY32 InLoadOrderModuleList; + LIST_ENTRY32 InMemoryOrderModuleList; + LIST_ENTRY32 InInitializationOrderModuleList; + VOID* POINTER_32 DllBase; + VOID* POINTER_32 EntryPoint; + ULONG SizeOfImage; + UNICODE_STRING32 FullDllName; + UNICODE_STRING32 BaseDllName; + union + { + UCHAR FlagGroup[4]; + ULONG Flags; + struct + { + ULONG PackagedBinary : 1; + ULONG MarkedForRemoval : 1; + ULONG ImageDll : 1; + ULONG LoadNotificationsSent : 1; + ULONG TelemetryEntryProcessed : 1; + ULONG ProcessStaticImport : 1; + ULONG InLegacyLists : 1; + ULONG InIndexes : 1; + ULONG ShimDll : 1; + ULONG InExceptionTable : 1; + ULONG ReservedFlags1 : 2; + ULONG LoadInProgress : 1; + ULONG LoadConfigProcessed : 1; + ULONG EntryProcessed : 1; + ULONG ProtectDelayLoad : 1; + ULONG ReservedFlags3 : 2; + ULONG DontCallForThreads : 1; + ULONG ProcessAttachCalled : 1; + ULONG ProcessAttachFailed : 1; + ULONG CorDeferredValidate : 1; + ULONG CorImage : 1; + ULONG DontRelocate : 1; + ULONG CorILOnly : 1; + ULONG ChpeImage : 1; + ULONG ChpeEmulatorImage : 1; + ULONG ReservedFlags5 : 1; + ULONG Redirected : 1; + ULONG ReservedFlags6 : 2; + ULONG CompatDatabaseProcessed : 1; + }; + }; + USHORT ObsoleteLoadCount; + USHORT TlsIndex; + LIST_ENTRY32 HashLinks; + ULONG TimeDateStamp; + struct ACTIVATION_CONTEXT* POINTER_32 EntryPointActivationContext; + VOID* POINTER_32 Lock; + LDR_DDAG_NODE* POINTER_32 DdagNode; // FIXME: Too complex + LIST_ENTRY32 NodeModuleLink; + struct LDRP_LOAD_CONTEXT* POINTER_32 LoadContext; + VOID* POINTER_32 ParentDllBase; + VOID* POINTER_32 SwitchBackContext; + RTL_BALANCED_NODE32 BaseAddressIndexNode; + RTL_BALANCED_NODE32 MappingInfoIndexNode; + ULONG OriginalBase; + LARGE_INTEGER LoadTime; + ULONG BaseNameHashValue; + LDR_DLL_LOAD_REASON LoadReason; + ULONG ImplicitPathOptions; + ULONG ReferenceCount; + ULONG DependentLoadFlags; + UCHAR SigningLevel; + ULONG CheckSum; + VOID* POINTER_32 ActivePatchImageBase; + LDR_HOT_PATCH_STATE HotPatchState; +} LDR_DATA_TABLE_ENTRY32, *PLDR_DATA_TABLE_ENTRY32; + +#endif /* defined(_KNSOFT_NDK_NT_EXTENSION) */ + +#pragma endregion + +typedef VOID(NTAPI LDR_ENUM_CALLBACK)(_In_ PLDR_DATA_TABLE_ENTRY ModuleInformation, _In_opt_ PVOID Context, _Out_ BOOLEAN* Stop); +typedef LDR_ENUM_CALLBACK *PLDR_ENUM_CALLBACK; diff --git a/Source/Include/KNSoft/NDK/NT/Types/Mm.h b/Source/Include/KNSoft/NDK/NT/Types/Mm.h new file mode 100644 index 0000000..00eb027 --- /dev/null +++ b/Source/Include/KNSoft/NDK/NT/Types/Mm.h @@ -0,0 +1,120 @@ +#pragma once + +#include "../MinDef.h" + +#define PAGE_SIZE 0x1000 +#define MM_ALLOCATION_GRANULARITY 0x10000 +#define MM_SHARED_USER_DATA_VA 0x7FFE0000 + +#if defined(_WIN64) +#define MM_HIGHEST_USER_ADDRESS ((PVOID)0x000007FFFFFEFFFFULL) +#else +#define MM_HIGHEST_USER_ADDRESS ((PVOID)0x7FFEFFFFUL) +#endif +#define MM_LOWEST_USER_ADDRESS ((PVOID)0x10000) + +#if defined(_KNSOFT_NDK_NT_EXTENSION) + +/* + * ASLR initialization constants, see: + * "Image randomization." Microsoft Windows Internals + * ntoskrnl.exe!MiInitializeRelocations + */ + +#if defined(_WIN64) + +/* [0x00007FF7FFFF0000 ... 0x00007FFFFFFF0000], 32G */ + +#define MI_ASLR_BITMAP_SIZE 0x10000 +#define MI_ASLR_HIGHEST_SYSTEM_RANGE_ADDRESS ((PVOID)0x00007FFFFFFF0000ULL) + +#else + +/* [0x50000000 ... 0x78000000], 640M */ + +#define MI_ASLR_BITMAP_SIZE 0x500 +#define MI_ASLR_HIGHEST_SYSTEM_RANGE_ADDRESS ((PVOID)0x78000000UL) + +#endif + +#endif /* defined(_KNSOFT_NDK_NT_EXTENSION) */ + +typedef enum _SECTION_INHERIT +{ + ViewShare = 1, + ViewUnmap = 2 +} SECTION_INHERIT; + +typedef struct _MEMORY_RANGE_ENTRY +{ + PVOID VirtualAddress; + SIZE_T NumberOfBytes; +} MEMORY_RANGE_ENTRY, *PMEMORY_RANGE_ENTRY; + +typedef enum _MEMORY_INFORMATION_CLASS +{ + MemoryBasicInformation, + MemoryWorkingSetList, + MemorySectionName, + MemoryBasicVlmInformation, + MemoryWorkingSetExList +} MEMORY_INFORMATION_CLASS, *PMEMORY_INFORMATION_CLASS; + +typedef enum _SECTION_INFORMATION_CLASS +{ + SectionBasicInformation, + SectionImageInformation +} SECTION_INFORMATION_CLASS, *PSECTION_INFORMATION_CLASS; + +typedef struct _SECTION_BASIC_INFORMATION +{ + PVOID BaseAddress; + ULONG AllocationAttributes; + LARGE_INTEGER MaximumSize; +} SECTION_BASIC_INFORMATION, *PSECTION_BASIC_INFORMATION; + +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; + }; + ULONG GpValue; + USHORT ImageCharacteristics; + USHORT DllCharacteristics; + USHORT Machine; + BOOLEAN ImageContainsCode; +#if (NTDDI_VERSION >= NTDDI_WIN6) + union + { + struct + { + UCHAR ComPlusNativeReady : 1; + UCHAR ComPlusILOnly : 1; + UCHAR ImageDynamicallyRelocated : 1; + UCHAR ImageMappedFlat : 1; + UCHAR Reserved : 4; + }; + UCHAR ImageFlags; + }; +#else + BOOLEAN Spare1; +#endif + ULONG LoaderFlags; + ULONG ImageFileSize; +#if (NTDDI_VERSION >= NTDDI_WIN6) + ULONG CheckSum; +#else + ULONG Reserved[1]; +#endif +} SECTION_IMAGE_INFORMATION, *PSECTION_IMAGE_INFORMATION; diff --git a/Source/Include/KNSoft/NDK/NT/Types/Ob.h b/Source/Include/KNSoft/NDK/NT/Types/Ob.h new file mode 100644 index 0000000..e81e4da --- /dev/null +++ b/Source/Include/KNSoft/NDK/NT/Types/Ob.h @@ -0,0 +1,71 @@ +#pragma once + +#include "../MinDef.h" + +typedef enum _OBJECT_INFORMATION_CLASS +{ + ObjectBasicInformation, + ObjectNameInformation, + ObjectTypeInformation, + ObjectAllTypesInformation, + ObjectHandleInformation +} OBJECT_INFORMATION_CLASS, *POBJECT_INFORMATION_CLASS; + +typedef struct _OBJECT_BASIC_INFORMATION +{ + ULONG Attributes; + ACCESS_MASK GrantedAccess; + ULONG HandleCount; + ULONG PointerCount; + ULONG PagedPoolUsage; + ULONG NonPagedPoolUsage; + ULONG Reserved[3]; + ULONG NameInformationLength; + ULONG TypeInformationLength; + ULONG SecurityDescriptorLength; + LARGE_INTEGER CreateTime; +} OBJECT_BASIC_INFORMATION, *POBJECT_BASIC_INFORMATION; + +typedef struct _OBJECT_NAME_INFORMATION +{ + UNICODE_STRING Name; +} OBJECT_NAME_INFORMATION, *POBJECT_NAME_INFORMATION; + +typedef struct _OBJECT_TYPE_INFORMATION +{ + UNICODE_STRING TypeName; + ULONG TotalNumberOfObjects; + ULONG TotalNumberOfHandles; + ULONG TotalPagedPoolUsage; + ULONG TotalNonPagedPoolUsage; + ULONG TotalNamePoolUsage; + ULONG TotalHandleTableUsage; + ULONG HighWaterNumberOfObjects; + ULONG HighWaterNumberOfHandles; + ULONG HighWaterPagedPoolUsage; + ULONG HighWaterNonPagedPoolUsage; + ULONG HighWaterNamePoolUsage; + ULONG HighWaterHandleTableUsage; + ULONG InvalidAttributes; + GENERIC_MAPPING GenericMapping; + ULONG ValidAccessMask; + BOOLEAN SecurityRequired; + BOOLEAN MaintainHandleCount; + UCHAR TypeIndex; + CHAR Reserved; + ULONG PoolType; + ULONG DefaultPagedPoolCharge; + ULONG DefaultNonPagedPoolCharge; +} OBJECT_TYPE_INFORMATION, *POBJECT_TYPE_INFORMATION; + +typedef struct _OBJECT_TYPES_INFORMATION +{ + ULONG NumberOfTypes; + _Field_size_(NumberOfTypes) OBJECT_TYPE_INFORMATION TypeInformation[ANYSIZE_ARRAY]; +} OBJECT_TYPES_INFORMATION, *POBJECT_TYPES_INFORMATION; + +typedef struct _OBJECT_HANDLE_INFORMATION +{ + ULONG HandleAttributes; + ULONG GrantedAccess; +} OBJECT_HANDLE_INFORMATION, *POBJECT_HANDLE_INFORMATION; diff --git a/Source/Include/KNSoft/NDK/NT/Types/Ps.h b/Source/Include/KNSoft/NDK/NT/Types/Ps.h new file mode 100644 index 0000000..c3f932a --- /dev/null +++ b/Source/Include/KNSoft/NDK/NT/Types/Ps.h @@ -0,0 +1,184 @@ +#pragma once + +#include "../MinDef.h" +#include "Basic.h" +#include "Ke.h" + +typedef enum _PROCESSINFOCLASS +{ + ProcessBasicInformation = 0, + ProcessQuotaLimits = 1, + ProcessIoCounters = 2, + ProcessVmCounters = 3, + ProcessTimes = 4, + ProcessBasePriority = 5, + ProcessRaisePriority = 6, + ProcessDebugPort = 7, + ProcessExceptionPort = 8, + ProcessAccessToken = 9, + ProcessLdtInformation = 10, + ProcessLdtSize = 11, + ProcessDefaultHardErrorMode = 12, + ProcessIoPortHandlers = 13, // Note: this is kernel mode only + ProcessPooledUsageAndLimits = 14, + ProcessWorkingSetWatch = 15, + ProcessUserModeIOPL = 16, + ProcessEnableAlignmentFaultFixup = 17, + ProcessPriorityClass = 18, + ProcessWx86Information = 19, + ProcessHandleCount = 20, + ProcessAffinityMask = 21, + ProcessPriorityBoost = 22, + ProcessDeviceMap = 23, + ProcessSessionInformation = 24, + ProcessForegroundInformation = 25, + ProcessWow64Information = 26, + ProcessImageFileName = 27, + ProcessLUIDDeviceMapsEnabled = 28, + ProcessBreakOnTermination = 29, + ProcessDebugObjectHandle = 30, + ProcessDebugFlags = 31, + ProcessHandleTracing = 32, + ProcessIoPriority = 33, + ProcessExecuteFlags = 34, + ProcessTlsInformation = 35, + ProcessCookie = 36, + ProcessImageInformation = 37, + ProcessCycleTime = 38, + ProcessPagePriority = 39, + ProcessInstrumentationCallback = 40, + ProcessThreadStackAllocation = 41, + ProcessWorkingSetWatchEx = 42, + ProcessImageFileNameWin32 = 43, + ProcessImageFileMapping = 44, + ProcessAffinityUpdateMode = 45, + ProcessMemoryAllocationMode = 46, + ProcessGroupInformation = 47, + ProcessTokenVirtualizationEnabled = 48, + ProcessOwnerInformation = 49, + ProcessWindowInformation = 50, + ProcessHandleInformation = 51, + ProcessMitigationPolicy = 52, + ProcessDynamicFunctionTableInformation = 53, + ProcessHandleCheckingMode = 54, + ProcessKeepAliveCount = 55, + ProcessRevokeFileHandles = 56, + ProcessWorkingSetControl = 57, + ProcessHandleTable = 58, + ProcessCheckStackExtentsMode = 59, + ProcessCommandLineInformation = 60, + ProcessProtectionInformation = 61, + ProcessMemoryExhaustion = 62, + ProcessFaultInformation = 63, + ProcessTelemetryIdInformation = 64, + ProcessCommitReleaseInformation = 65, +#if 1 /* From kernel mode ntddk.h */ + ProcessReserved1Information = 66, + ProcessReserved2Information = 67, + ProcessSubsystemProcess = 68, + ProcessInPrivate = 70, + ProcessRaiseUMExceptionOnInvalidHandleClose = 71, + ProcessSubsystemInformation = 75, + ProcessWin32kSyscallFilterInformation = 79, + ProcessEnergyTrackingState = 82, +#else /* From user mode PDB */ + ProcessDefaultCpuSetsInformation = 66, + ProcessAllowedCpuSetsInformation = 67, + ProcessReserved1Information = 68, + ProcessReserved2Information = 69, + ProcessSubsystemProcess = 70, + ProcessJobMemoryInformation = 71, +#endif + MaxProcessInfoClass // MaxProcessInfoClass should always be the last enum +} PROCESSINFOCLASS, *PPROCESSINFOCLASS; + +typedef enum _THREADINFOCLASS +{ + ThreadBasicInformation = 0, + ThreadTimes = 1, + ThreadPriority = 2, + ThreadBasePriority = 3, + ThreadAffinityMask = 4, + ThreadImpersonationToken = 5, + ThreadDescriptorTableEntry = 6, + ThreadEnableAlignmentFaultFixup = 7, + ThreadEventPair_Reusable = 8, + ThreadQuerySetWin32StartAddress = 9, + ThreadZeroTlsCell = 10, + ThreadPerformanceCount = 11, + ThreadAmILastThread = 12, + ThreadIdealProcessor = 13, + ThreadPriorityBoost = 14, + ThreadSetTlsArrayAddress = 15, // Obsolete + ThreadIsIoPending = 16, + ThreadHideFromDebugger = 17, + ThreadBreakOnTermination = 18, + ThreadSwitchLegacyState = 19, + ThreadIsTerminated = 20, + ThreadLastSystemCall = 21, + ThreadIoPriority = 22, + ThreadCycleTime = 23, + ThreadPagePriority = 24, + ThreadActualBasePriority = 25, + ThreadTebInformation = 26, + ThreadCSwitchMon = 27, // Obsolete + ThreadCSwitchPmu = 28, + ThreadWow64Context = 29, + ThreadGroupInformation = 30, + ThreadUmsInformation = 31, // Obsolete + ThreadCounterProfiling = 32, + ThreadIdealProcessorEx = 33, + ThreadCpuAccountingInformation = 34, + ThreadSuspendCount = 35, + ThreadNameInformation = 38, + ThreadActualGroupAffinity = 41, + ThreadDynamicCodePolicyInfo = 42, + ThreadSubsystemInformation = 45, + + MaxThreadInfoClass = 56, +} THREADINFOCLASS, *PTHREADINFOCLASS; + +/* ProcessPagePriority and ThreadPagePriority */ + +#define MEMORY_PRIORITY_LOWEST 0 +#define MEMORY_PRIORITY_VERY_LOW 1 +#define MEMORY_PRIORITY_LOW 2 +#define MEMORY_PRIORITY_MEDIUM 3 +#define MEMORY_PRIORITY_BELOW_NORMAL 4 +#define MEMORY_PRIORITY_NORMAL 5 + +typedef struct _PAGE_PRIORITY_INFORMATION +{ + ULONG PagePriority; +} PAGE_PRIORITY_INFORMATION, *PPAGE_PRIORITY_INFORMATION; + +/* ProcessBasicInformation */ + +typedef struct _PROCESS_BASIC_INFORMATION +{ + NTSTATUS ExitStatus; + PVOID PebBaseAddress; // PPEB + ULONG_PTR AffinityMask; + KPRIORITY BasePriority; + ULONG_PTR UniqueProcessId; + ULONG_PTR InheritedFromUniqueProcessId; +} PROCESS_BASIC_INFORMATION, *PPROCESS_BASIC_INFORMATION; + +/* ProcessSessionInformation */ + +typedef struct _PROCESS_SESSION_INFORMATION +{ + ULONG SessionId; +} PROCESS_SESSION_INFORMATION, *PPROCESS_SESSION_INFORMATION; + +/* ThreadBasicInformation */ + +typedef struct _THREAD_BASIC_INFORMATION +{ + NTSTATUS ExitStatus; + PVOID TebBaseAddress; //PTEB + CLIENT_ID ClientId; + KAFFINITY AffinityMask; + KPRIORITY Priority; + KPRIORITY BasePriority; +} THREAD_BASIC_INFORMATION, *PTHREAD_BASIC_INFORMATION; diff --git a/Source/Include/KNSoft/NDK/NT/Types/Rtl.h b/Source/Include/KNSoft/NDK/NT/Types/Rtl.h new file mode 100644 index 0000000..f12d521 --- /dev/null +++ b/Source/Include/KNSoft/NDK/NT/Types/Rtl.h @@ -0,0 +1,487 @@ +#pragma once + +#include "../MinDef.h" + +#include "Basic.h" + +typedef struct _RTLP_CURDIR_REF +{ + LONG RefCount; + HANDLE Handle; +} RTLP_CURDIR_REF, *PRTLP_CURDIR_REF; + +typedef struct _RTL_RELATIVE_NAME_U +{ + UNICODE_STRING RelativeName; + HANDLE ContainingDirectory; + PRTLP_CURDIR_REF CurDirRef; +} RTL_RELATIVE_NAME_U, *PRTL_RELATIVE_NAME_U; + +typedef +_Function_class_(RTL_RUN_ONCE_INIT_FN) +_IRQL_requires_same_ +ULONG /* LOGICAL */ +NTAPI +RTL_RUN_ONCE_INIT_FN( + _Inout_ PRTL_RUN_ONCE RunOnce, + _Inout_opt_ PVOID Parameter, + _Inout_opt_ PVOID *Context +); +typedef RTL_RUN_ONCE_INIT_FN *PRTL_RUN_ONCE_INIT_FN; + +typedef +_Function_class_(RTL_HEAP_COMMIT_ROUTINE) +_IRQL_requires_same_ +NTSTATUS +NTAPI +RTL_HEAP_COMMIT_ROUTINE( + _In_ PVOID Base, + _Inout_ PVOID *CommitAddress, + _Inout_ PSIZE_T CommitSize +); +typedef RTL_HEAP_COMMIT_ROUTINE *PRTL_HEAP_COMMIT_ROUTINE; + +typedef struct _RTL_HEAP_PARAMETERS +{ + ULONG Length; + SIZE_T SegmentReserve; + SIZE_T SegmentCommit; + SIZE_T DeCommitFreeBlockThreshold; + SIZE_T DeCommitTotalFreeThreshold; + SIZE_T MaximumAllocationSize; + SIZE_T VirtualMemoryThreshold; + SIZE_T InitialCommit; + SIZE_T InitialReserve; + PRTL_HEAP_COMMIT_ROUTINE CommitRoutine; + SIZE_T Reserved[2]; +} RTL_HEAP_PARAMETERS, *PRTL_HEAP_PARAMETERS; + +typedef struct _RTL_HEAP_WALK_ENTRY +{ + PVOID DataAddress; + SIZE_T DataSize; + UCHAR OverheadBytes; + UCHAR SegmentIndex; + USHORT Flags; + union + { + struct + { + SIZE_T Settable; + USHORT TagIndex; + USHORT AllocatorBackTraceIndex; + ULONG Reserved[2]; + } Block; + struct + { + ULONG_PTR CommittedSize; + ULONG_PTR UnCommittedSize; + PVOID FirstEntry; + PVOID LastEntry; + } Segment; + }; +} RTL_HEAP_WALK_ENTRY, * PRTL_HEAP_WALK_ENTRY; + +typedef enum _RTL_MEMORY_TYPE +{ + MemoryTypePaged, + MemoryTypeNonPaged, + MemoryType64KPage, + MemoryTypeLargePage, + MemoryTypeHugePage, + MemoryTypeCustom, + MemoryTypeMax +} RTL_MEMORY_TYPE, *PRTL_MEMORY_TYPE; + +typedef enum _HEAP_MEMORY_INFO_CLASS +{ + HeapMemoryBasicInformation +} HEAP_MEMORY_INFO_CLASS; + +#if (NTDDI_VERSION >= NTDDI_WIN10) + +typedef NTSTATUS +ALLOCATE_VIRTUAL_MEMORY_EX_CALLBACK( + _Inout_ HANDLE CallbackContext, + _In_ HANDLE ProcessHandle, + _Inout_ _At_(*BaseAddress, _Readable_bytes_(*RegionSize) _Writable_bytes_(*RegionSize) _Post_readable_byte_size_(*RegionSize)) PVOID* BaseAddress, + _Inout_ PSIZE_T RegionSize, + _In_ ULONG AllocationType, + _In_ ULONG PageProtection, + _Inout_updates_opt_(ExtendedParameterCount) PMEM_EXTENDED_PARAMETER ExtendedParameters, + _In_ ULONG ExtendedParameterCount +); + +typedef ALLOCATE_VIRTUAL_MEMORY_EX_CALLBACK *PALLOCATE_VIRTUAL_MEMORY_EX_CALLBACK; + +typedef NTSTATUS +FREE_VIRTUAL_MEMORY_EX_CALLBACK( + _Inout_ HANDLE CallbackContext, + _In_ HANDLE ProcessHandle, + _Inout_ __drv_freesMem(Mem) PVOID *BaseAddress, + _Inout_ PSIZE_T RegionSize, + _In_ ULONG FreeType +); + +typedef FREE_VIRTUAL_MEMORY_EX_CALLBACK *PFREE_VIRTUAL_MEMORY_EX_CALLBACK; + +typedef NTSTATUS +QUERY_VIRTUAL_MEMORY_CALLBACK( + _Inout_ HANDLE CallbackContext, + _In_ HANDLE ProcessHandle, + _In_opt_ PVOID BaseAddress, + _In_ HEAP_MEMORY_INFO_CLASS MemoryInformationClass, + _Out_writes_bytes_(MemoryInformationLength) PVOID MemoryInformation, + _In_ SIZE_T MemoryInformationLength, + _Out_opt_ PSIZE_T ReturnLength +); + +typedef QUERY_VIRTUAL_MEMORY_CALLBACK *PQUERY_VIRTUAL_MEMORY_CALLBACK; + +typedef struct _RTL_SEGMENT_HEAP_VA_CALLBACKS +{ + HANDLE CallbackContext; + PALLOCATE_VIRTUAL_MEMORY_EX_CALLBACK AllocateVirtualMemory; + PFREE_VIRTUAL_MEMORY_EX_CALLBACK FreeVirtualMemory; + PQUERY_VIRTUAL_MEMORY_CALLBACK QueryVirtualMemory; +} RTL_SEGMENT_HEAP_VA_CALLBACKS, *PRTL_SEGMENT_HEAP_VA_CALLBACKS; + +#define RTL_SEGHEAP_MEM_SOURCE_ANY_NODE ((ULONG)-1) + +typedef struct _RTL_SEGMENT_HEAP_MEMORY_SOURCE +{ + ULONG Flags; + ULONG MemoryTypeMask; // Mask of RTL_MEMORY_TYPE members. + ULONG NumaNode; + union + { + HANDLE PartitionHandle; + RTL_SEGMENT_HEAP_VA_CALLBACKS *Callbacks; + }; + + SIZE_T Reserved[2]; +} RTL_SEGMENT_HEAP_MEMORY_SOURCE, *PRTL_SEGMENT_HEAP_MEMORY_SOURCE; + +#define SEGMENT_HEAP_PARAMETERS_VERSION 3 +#define SEGMENT_HEAP_FLG_USE_PAGE_HEAP 0x1 +#define SEGMENT_HEAP_PARAMS_VALID_FLAGS SEGMENT_HEAP_FLG_USE_PAGE_HEAP + +typedef struct _RTL_SEGMENT_HEAP_PARAMETERS +{ + USHORT Version; + USHORT Size; + ULONG Flags; + + RTL_SEGMENT_HEAP_MEMORY_SOURCE MemorySource; + + SIZE_T Reserved[4]; +} RTL_SEGMENT_HEAP_PARAMETERS, *PRTL_SEGMENT_HEAP_PARAMETERS; + +#endif /* (NTDDI_VERSION >= NTDDI_WIN10) */ + +typedef struct _RTL_HEAP_TAG_INFO +{ + ULONG NumberOfAllocations; + ULONG NumberOfFrees; + SIZE_T BytesAllocated; +} RTL_HEAP_TAG_INFO, *PRTL_HEAP_TAG_INFO; + +#pragma region RTL_DRIVE_LETTER_CURDIR[64/32] + +typedef struct _RTL_DRIVE_LETTER_CURDIR +{ + USHORT Flags; + USHORT Length; + UINT TimeStamp; + STRING DosPath; +} RTL_DRIVE_LETTER_CURDIR, *PRTL_DRIVE_LETTER_CURDIR; + +#if defined(_KNSOFT_NDK_NT_EXTENSION) + +typedef struct _RTL_DRIVE_LETTER_CURDIR64 +{ + USHORT Flags; + USHORT Length; + UINT TimeStamp; + STRING64 DosPath; +} RTL_DRIVE_LETTER_CURDIR64, *PRTL_DRIVE_LETTER_CURDIR64; + +typedef struct _RTL_DRIVE_LETTER_CURDIR32 +{ + USHORT Flags; + USHORT Length; + UINT TimeStamp; + STRING32 DosPath; +} RTL_DRIVE_LETTER_CURDIR32, *PRTL_DRIVE_LETTER_CURDIR32; + +#endif /* defined(_KNSOFT_NDK_NT_EXTENSION) */ + +#pragma endregion + +#pragma region RTL_BITMAP[64/32] + +typedef struct _RTL_BITMAP +{ + ULONG SizeOfBitMap; // Number of bits in bit map + PULONG Buffer; // Pointer to the bit map itself +} RTL_BITMAP, *PRTL_BITMAP; + +#if defined(_KNSOFT_NDK_NT_EXTENSION) + +typedef struct _RTL_BITMAP64 +{ + ULONG SizeOfBitMap; + ULONG* POINTER_64 Buffer; +} RTL_BITMAP64, *PRTL_BITMAP64; + +typedef struct _RTL_BITMAP32 +{ + ULONG SizeOfBitMap; + ULONG* POINTER_32 Buffer; +} RTL_BITMAP32, *PRTL_BITMAP32; + +#endif /* defined(_KNSOFT_NDK_NT_EXTENSION) */ + +#pragma endregion + +#pragma region RTL_USER_PROCESS_PARAMETERS[64/32] + +typedef struct _RTL_USER_PROCESS_PARAMETERS +{ + ULONG MaximumLength; + ULONG Length; + ULONG Flags; + ULONG DebugFlags; + HANDLE ConsoleHandle; + ULONG ConsoleFlags; + HANDLE StandardInput; + HANDLE StandardOutput; + HANDLE StandardError; + CURDIR CurrentDirectory; + UNICODE_STRING DllPath; + UNICODE_STRING ImagePathName; + UNICODE_STRING CommandLine; + LPWSTR Environment; + ULONG StartingX; + ULONG StartingY; + ULONG CountX; + ULONG CountY; + ULONG CountCharsX; + ULONG CountCharsY; + ULONG FillAttribute; + ULONG WindowFlags; + ULONG ShowWindowFlags; + UNICODE_STRING WindowTitle; + UNICODE_STRING DesktopInfo; + UNICODE_STRING ShellInfo; + UNICODE_STRING RuntimeData; + RTL_DRIVE_LETTER_CURDIR CurrentDirectores[32]; + ULONG_PTR EnvironmentSize; + ULONG_PTR EnvironmentVersion; + PVOID PackageDependencyData; + ULONG ProcessGroupId; + ULONG LoaderThreads; + UNICODE_STRING RedirectionDllName; + UNICODE_STRING HeapPartitionName; + PULONGLONG DefaultThreadpoolCpuSetMasks; + ULONG DefaultThreadpoolCpuSetMaskCount; + ULONG DefaultThreadpoolThreadMaximum; + ULONG HeapMemoryTypeMask; +} RTL_USER_PROCESS_PARAMETERS, *PRTL_USER_PROCESS_PARAMETERS; + +#if defined(_KNSOFT_NDK_NT_EXTENSION) + +typedef struct _RTL_USER_PROCESS_PARAMETERS64 +{ + ULONG MaximumLength; + ULONG Length; + ULONG Flags; + ULONG DebugFlags; + VOID* POINTER_64 ConsoleHandle; + ULONG ConsoleFlags; + VOID* POINTER_64 StandardInput; + VOID* POINTER_64 StandardOutput; + VOID* POINTER_64 StandardError; + CURDIR64 CurrentDirectory; + UNICODE_STRING64 DllPath; + UNICODE_STRING64 ImagePathName; + UNICODE_STRING64 CommandLine; + WCHAR* POINTER_64 Environment; + ULONG StartingX; + ULONG StartingY; + ULONG CountX; + ULONG CountY; + ULONG CountCharsX; + ULONG CountCharsY; + ULONG FillAttribute; + ULONG WindowFlags; + ULONG ShowWindowFlags; + UNICODE_STRING64 WindowTitle; + UNICODE_STRING64 DesktopInfo; + UNICODE_STRING64 ShellInfo; + UNICODE_STRING64 RuntimeData; + RTL_DRIVE_LETTER_CURDIR64 CurrentDirectores[32]; + ULONGLONG EnvironmentSize; + ULONGLONG EnvironmentVersion; + VOID* POINTER_64 PackageDependencyData; + ULONG ProcessGroupId; + ULONG LoaderThreads; + UNICODE_STRING64 RedirectionDllName; + UNICODE_STRING64 HeapPartitionName; + ULONGLONG* POINTER_64 DefaultThreadpoolCpuSetMasks; + ULONG DefaultThreadpoolCpuSetMaskCount; + ULONG DefaultThreadpoolThreadMaximum; + ULONG HeapMemoryTypeMask; +} RTL_USER_PROCESS_PARAMETERS64, *PRTL_USER_PROCESS_PARAMETERS64; + +typedef struct _RTL_USER_PROCESS_PARAMETERS32 +{ + ULONG MaximumLength; + ULONG Length; + ULONG Flags; + ULONG DebugFlags; + VOID* POINTER_32 ConsoleHandle; + ULONG ConsoleFlags; + VOID* POINTER_32 StandardInput; + VOID* POINTER_32 StandardOutput; + VOID* POINTER_32 StandardError; + CURDIR32 CurrentDirectory; + UNICODE_STRING32 DllPath; + UNICODE_STRING32 ImagePathName; + UNICODE_STRING32 CommandLine; + WCHAR* POINTER_32 Environment; + ULONG StartingX; + ULONG StartingY; + ULONG CountX; + ULONG CountY; + ULONG CountCharsX; + ULONG CountCharsY; + ULONG FillAttribute; + ULONG WindowFlags; + ULONG ShowWindowFlags; + UNICODE_STRING32 WindowTitle; + UNICODE_STRING32 DesktopInfo; + UNICODE_STRING32 ShellInfo; + UNICODE_STRING32 RuntimeData; + RTL_DRIVE_LETTER_CURDIR32 CurrentDirectores[32]; + ULONG EnvironmentSize; + ULONG EnvironmentVersion; + VOID* POINTER_32 PackageDependencyData; + ULONG ProcessGroupId; + ULONG LoaderThreads; + UNICODE_STRING32 RedirectionDllName; + UNICODE_STRING32 HeapPartitionName; + ULONGLONG* POINTER_32 DefaultThreadpoolCpuSetMasks; + ULONG DefaultThreadpoolCpuSetMaskCount; + ULONG DefaultThreadpoolThreadMaximum; + ULONG HeapMemoryTypeMask; +} RTL_USER_PROCESS_PARAMETERS32, *PRTL_USER_PROCESS_PARAMETERS32; + +#endif /* defined(_KNSOFT_NDK_NT_EXTENSION) */ + +#pragma endregion + +#if defined(_KNSOFT_NDK_NT_EXTENSION) + +#pragma region RTL_BALANCED_NODE(64/32) + +typedef struct _RTL_BALANCED_NODE64 +{ + union + { + struct _RTL_BALANCED_NODE64* POINTER_64 Children[2]; + struct + { + struct _RTL_BALANCED_NODE64* POINTER_64 Left; + struct _RTL_BALANCED_NODE64* POINTER_64 Right; + } DUMMYSTRUCTNAME; + } DUMMYUNIONNAME; + +#define RTL_BALANCED_NODE_RESERVED_PARENT_MASK 3 + + union + { + UCHAR Red : 1; + UCHAR Balance : 2; + ULONGLONG ParentValue; + } DUMMYUNIONNAME2; +} RTL_BALANCED_NODE64, *PRTL_BALANCED_NODE64; + +typedef struct _RTL_BALANCED_NODE32 +{ + union + { + struct _RTL_BALANCED_NODE32* POINTER_32 Children[2]; + struct + { + struct _RTL_BALANCED_NODE32* POINTER_32 Left; + struct _RTL_BALANCED_NODE32* POINTER_32 Right; + } DUMMYSTRUCTNAME; + } DUMMYUNIONNAME; + +#define RTL_BALANCED_NODE_RESERVED_PARENT_MASK 3 + + union + { + UCHAR Red : 1; + UCHAR Balance : 2; + ULONG ParentValue; + } DUMMYUNIONNAME2; +} RTL_BALANCED_NODE32, *PRTL_BALANCED_NODE32; + +#pragma endregion + +#pragma region RTL_CRITICAL_SECTION[_DEBUG](64/32) + +typedef struct _RTL_CRITICAL_SECTION64 RTL_CRITICAL_SECTION64, *PRTL_CRITICAL_SECTION64; +typedef struct _RTL_CRITICAL_SECTION32 RTL_CRITICAL_SECTION32, *PRTL_CRITICAL_SECTION32; + +typedef struct _RTL_CRITICAL_SECTION_DEBUG64 +{ + WORD Type; + WORD CreatorBackTraceIndex; + RTL_CRITICAL_SECTION64* POINTER_64 CriticalSection; + LIST_ENTRY64 ProcessLocksList; + DWORD EntryCount; + DWORD ContentionCount; + DWORD Flags; + WORD CreatorBackTraceIndexHigh; + WORD Identifier; +} RTL_CRITICAL_SECTION_DEBUG64, *PRTL_CRITICAL_SECTION_DEBUG64, RTL_RESOURCE_DEBUG64, *PRTL_RESOURCE_DEBUG64; + +typedef struct _RTL_CRITICAL_SECTION_DEBUG32 +{ + WORD Type; + WORD CreatorBackTraceIndex; + RTL_CRITICAL_SECTION32* POINTER_32 CriticalSection; + LIST_ENTRY32 ProcessLocksList; + DWORD EntryCount; + DWORD ContentionCount; + DWORD Flags; + WORD CreatorBackTraceIndexHigh; + WORD Identifier; +} RTL_CRITICAL_SECTION_DEBUG32, *PRTL_CRITICAL_SECTION_DEBUG32, RTL_RESOURCE_DEBUG32, *PRTL_RESOURCE_DEBUG32; + +struct _RTL_CRITICAL_SECTION64 +{ + RTL_CRITICAL_SECTION_DEBUG64* POINTER_64 DebugInfo; + LONG LockCount; + LONG RecursionCount; + VOID* POINTER_64 OwningThread; + VOID* POINTER_64 LockSemaphore; + ULONGLONG SpinCount; +}; + +struct _RTL_CRITICAL_SECTION32 +{ + RTL_CRITICAL_SECTION_DEBUG32* POINTER_32 DebugInfo; + LONG LockCount; + LONG RecursionCount; + VOID* POINTER_32 OwningThread; + VOID* POINTER_32 LockSemaphore; + ULONG SpinCount; +}; + +#pragma endregion + +#endif /* defined(_KNSOFT_NDK_NT_EXTENSION) */ diff --git a/Source/Include/KNSoft/NDK/NT/Types/Se.h b/Source/Include/KNSoft/NDK/NT/Types/Se.h new file mode 100644 index 0000000..9d63ad5 --- /dev/null +++ b/Source/Include/KNSoft/NDK/NT/Types/Se.h @@ -0,0 +1,95 @@ +#pragma once + +#pragma region SE_XXX_PRIVILEGE + +// +// These must be converted to LUIDs before use. +// + +#define SE_MIN_WELL_KNOWN_PRIVILEGE (2L) +#define SE_CREATE_TOKEN_PRIVILEGE (2L) +#define SE_ASSIGNPRIMARYTOKEN_PRIVILEGE (3L) +#define SE_LOCK_MEMORY_PRIVILEGE (4L) +#define SE_INCREASE_QUOTA_PRIVILEGE (5L) + + +#define SE_MACHINE_ACCOUNT_PRIVILEGE (6L) +#define SE_TCB_PRIVILEGE (7L) +#define SE_SECURITY_PRIVILEGE (8L) +#define SE_TAKE_OWNERSHIP_PRIVILEGE (9L) +#define SE_LOAD_DRIVER_PRIVILEGE (10L) +#define SE_SYSTEM_PROFILE_PRIVILEGE (11L) +#define SE_SYSTEMTIME_PRIVILEGE (12L) +#define SE_PROF_SINGLE_PROCESS_PRIVILEGE (13L) +#define SE_INC_BASE_PRIORITY_PRIVILEGE (14L) +#define SE_CREATE_PAGEFILE_PRIVILEGE (15L) +#define SE_CREATE_PERMANENT_PRIVILEGE (16L) +#define SE_BACKUP_PRIVILEGE (17L) +#define SE_RESTORE_PRIVILEGE (18L) +#define SE_SHUTDOWN_PRIVILEGE (19L) +#define SE_DEBUG_PRIVILEGE (20L) +#define SE_AUDIT_PRIVILEGE (21L) +#define SE_SYSTEM_ENVIRONMENT_PRIVILEGE (22L) +#define SE_CHANGE_NOTIFY_PRIVILEGE (23L) +#define SE_REMOTE_SHUTDOWN_PRIVILEGE (24L) +#define SE_UNDOCK_PRIVILEGE (25L) +#define SE_SYNC_AGENT_PRIVILEGE (26L) +#define SE_ENABLE_DELEGATION_PRIVILEGE (27L) +#define SE_MANAGE_VOLUME_PRIVILEGE (28L) +#define SE_IMPERSONATE_PRIVILEGE (29L) +#define SE_CREATE_GLOBAL_PRIVILEGE (30L) +#define SE_TRUSTED_CREDMAN_ACCESS_PRIVILEGE (31L) +#define SE_RELABEL_PRIVILEGE (32L) +#define SE_INC_WORKING_SET_PRIVILEGE (33L) +#define SE_TIME_ZONE_PRIVILEGE (34L) +#define SE_CREATE_SYMBOLIC_LINK_PRIVILEGE (35L) +#define SE_DELEGATE_SESSION_USER_IMPERSONATE_PRIVILEGE (36L) +#define SE_MAX_WELL_KNOWN_PRIVILEGE (SE_DELEGATE_SESSION_USER_IMPERSONATE_PRIVILEGE) + +#pragma endregion + +#if defined(_KNSOFT_NDK_NT_EXTENSION) + +/* Well-known SIDs */ + +#ifndef DEFINE_ANYSIZE_STRUCT +#define DEFINE_ANYSIZE_STRUCT(varName, baseType, arrayType, arraySize) struct {\ + baseType BaseType;\ + arrayType Array[(arraySize) - 1];\ +} varName +#endif + +typedef DEFINE_ANYSIZE_STRUCT(SID_2, SID, DWORD, 2); +typedef DEFINE_ANYSIZE_STRUCT(SID_3, SID, DWORD, 3); +typedef DEFINE_ANYSIZE_STRUCT(SID_4, SID, DWORD, 4); +typedef DEFINE_ANYSIZE_STRUCT(SID_5, SID, DWORD, 5); +typedef DEFINE_ANYSIZE_STRUCT(SID_6, SID, DWORD, 6); +typedef DEFINE_ANYSIZE_STRUCT(SID_7, SID, DWORD, 7); + +/* SeExport used */ +#define SID_EVERYONE { SID_REVISION, 1, SECURITY_WORLD_SID_AUTHORITY, { SECURITY_WORLD_RID } } +#define SID_SYSTEM { SID_REVISION, 1, SECURITY_NT_AUTHORITY, { SECURITY_LOCAL_SYSTEM_RID } } +#define SID_ADMINS { { SID_REVISION, 2, SECURITY_NT_AUTHORITY, { SECURITY_BUILTIN_DOMAIN_RID } }, DOMAIN_ALIAS_RID_ADMINS } +#define SID_USERS { { SID_REVISION, 2, SECURITY_NT_AUTHORITY, { SECURITY_BUILTIN_DOMAIN_RID } }, DOMAIN_ALIAS_RID_USERS } +#define SID_AUTHENTICATED_USERS { SID_REVISION, 1, SECURITY_NT_AUTHORITY, { SECURITY_AUTHENTICATED_USER_RID } } +#define SID_LOCAL_SERVICE { SID_REVISION, 1, SECURITY_NT_AUTHORITY, { SECURITY_LOCAL_SERVICE_RID } } +#define SID_NETWORK_SERVICE { SID_REVISION, 1, SECURITY_NT_AUTHORITY, { SECURITY_NETWORK_SERVICE_RID } } +#define SID_TRUSTED_INSTALLER { SID_REVISION, SECURITY_SERVICE_ID_RID_COUNT, SECURITY_NT_AUTHORITY, { SECURITY_SERVICE_ID_BASE_RID }, SECURITY_TRUSTED_INSTALLER_RID1, SECURITY_TRUSTED_INSTALLER_RID2, SECURITY_TRUSTED_INSTALLER_RID3, SECURITY_TRUSTED_INSTALLER_RID4, SECURITY_TRUSTED_INSTALLER_RID5 } +#define SID_LOCAL { SID_REVISION, 1, SECURITY_LOCAL_SID_AUTHORITY, { SECURITY_LOCAL_RID } } +#define SID_INTERACTIVE { SID_REVISION, 1, SECURITY_NT_AUTHORITY, { SECURITY_INTERACTIVE_RID } } +#define SID_MANDATORY_UNTRUSTED { SID_REVISION, 1, SECURITY_MANDATORY_LABEL_AUTHORITY, { SECURITY_MANDATORY_UNTRUSTED_RID } } +#define SID_MANDATORY_LOW { SID_REVISION, 1, SECURITY_MANDATORY_LABEL_AUTHORITY, { SECURITY_MANDATORY_LOW_RID } } +#define SID_MANDATORY_MEDIUM { SID_REVISION, 1, SECURITY_MANDATORY_LABEL_AUTHORITY, { SECURITY_MANDATORY_MEDIUM_RID } } +#define SID_MANDATORY_HIGH { SID_REVISION, 1, SECURITY_MANDATORY_LABEL_AUTHORITY, { SECURITY_MANDATORY_HIGH_RID } } +#define SID_MANDATORY_SYSTEM { SID_REVISION, 1, SECURITY_MANDATORY_LABEL_AUTHORITY, { SECURITY_MANDATORY_SYSTEM_RID } } + +/* Addendum */ +#define SID_LOCAL_ACCOUNT { SID_REVISION, 1, SECURITY_NT_AUTHORITY, { SECURITY_LOCAL_ACCOUNT_RID } } +#define SID_LOCAL_ACCOUNT_AND_ADMIN { SID_REVISION, 1, SECURITY_NT_AUTHORITY, { SECURITY_LOCAL_ACCOUNT_AND_ADMIN_RID } } +#define SID_LOCAL_LOGON { SID_REVISION, 1, SECURITY_LOCAL_SID_AUTHORITY, { SECURITY_LOCAL_LOGON_RID } } +#define SID_NTLM { {SID_REVISION, SECURITY_PACKAGE_RID_COUNT, SECURITY_NT_AUTHORITY, { SECURITY_PACKAGE_BASE_RID }}, SECURITY_PACKAGE_NTLM_RID } +#define SID_THIS_ORGANIZATION { SID_REVISION, 1, SECURITY_NT_AUTHORITY, { SECURITY_THIS_ORGANIZATION_RID } } +#define SID_MANDATORY_MEDIUM_PLUS { SID_REVISION, 1, SECURITY_MANDATORY_LABEL_AUTHORITY, { SECURITY_MANDATORY_MEDIUM_PLUS_RID } } +#define SID_MANDATORY_PROTECTED_PROCESS { SID_REVISION, 1, SECURITY_MANDATORY_LABEL_AUTHORITY, { SECURITY_MANDATORY_PROTECTED_PROCESS_RID } } + +#endif /* defined(_KNSOFT_NDK_NT_EXTENSION) */ diff --git a/Source/Include/KNSoft/NDK/NT/Types/Sys.h b/Source/Include/KNSoft/NDK/NT/Types/Sys.h new file mode 100644 index 0000000..2fe2578 --- /dev/null +++ b/Source/Include/KNSoft/NDK/NT/Types/Sys.h @@ -0,0 +1,379 @@ +#pragma once + +#include "../MinDef.h" + +#include "Basic.h" +#include "Ke.h" + +typedef enum _SYSTEM_INFORMATION_CLASS +{ + SystemBasicInformation = 0, + SystemProcessorInformation = 1, + SystemPerformanceInformation = 2, + SystemTimeOfDayInformation = 3, + SystemPathInformation = 4, + SystemProcessInformation = 5, + SystemCallCountInformation = 6, + SystemDeviceInformation = 7, + SystemProcessorPerformanceInformation = 8, + SystemFlagsInformation = 9, + SystemCallTimeInformation = 10, + SystemModuleInformation = 11, + SystemLocksInformation = 12, + SystemStackTraceInformation = 13, + SystemPagedPoolInformation = 14, + SystemNonPagedPoolInformation = 15, + SystemHandleInformation = 16, + SystemObjectInformation = 17, + SystemPageFileInformation = 18, + SystemVdmInstemulInformation = 19, + SystemVdmBopInformation = 20, + SystemFileCacheInformation = 21, + SystemPoolTagInformation = 22, + SystemInterruptInformation = 23, + SystemDpcBehaviorInformation = 24, + SystemFullMemoryInformation = 25, + SystemLoadGdiDriverInformation = 26, + SystemUnloadGdiDriverInformation = 27, + SystemTimeAdjustmentInformation = 28, + SystemSummaryMemoryInformation = 29, + SystemMirrorMemoryInformation = 30, + SystemPerformanceTraceInformation = 31, + SystemObsolete0 = 32, + SystemExceptionInformation = 33, + SystemCrashDumpStateInformation = 34, + SystemKernelDebuggerInformation = 35, + SystemContextSwitchInformation = 36, + SystemRegistryQuotaInformation = 37, + SystemExtendServiceTableInformation = 38, + SystemPrioritySeperation = 39, + SystemVerifierAddDriverInformation = 40, + SystemVerifierRemoveDriverInformation = 41, + SystemProcessorIdleInformation = 42, + SystemLegacyDriverInformation = 43, + SystemCurrentTimeZoneInformation = 44, + SystemLookasideInformation = 45, + SystemTimeSlipNotification = 46, + SystemSessionCreate = 47, + SystemSessionDetach = 48, + SystemSessionInformation = 49, + SystemRangeStartInformation = 50, + SystemVerifierInformation = 51, + SystemVerifierThunkExtend = 52, + SystemSessionProcessInformation = 53, + SystemLoadGdiDriverInSystemSpace = 54, + SystemNumaProcessorMap = 55, + SystemPrefetcherInformation = 56, + SystemExtendedProcessInformation = 57, + SystemRecommendedSharedDataAlignment = 58, + SystemComPlusPackage = 59, + SystemNumaAvailableMemory = 60, + SystemProcessorPowerInformation = 61, + SystemEmulationBasicInformation = 62, + SystemEmulationProcessorInformation = 63, + SystemExtendedHandleInformation = 64, + SystemLostDelayedWriteInformation = 65, + SystemBigPoolInformation = 66, + SystemSessionPoolTagInformation = 67, + SystemSessionMappedViewInformation = 68, + SystemHotpatchInformation = 69, + SystemObjectSecurityMode = 70, + SystemWatchdogTimerHandler = 71, + SystemWatchdogTimerInformation = 72, + SystemLogicalProcessorInformation = 73, + SystemWow64SharedInformationObsolete = 74, + SystemRegisterFirmwareTableInformationHandler = 75, + SystemFirmwareTableInformation = 76, + SystemModuleInformationEx = 77, + SystemVerifierTriageInformation = 78, + SystemSuperfetchInformation = 79, + SystemMemoryListInformation = 80, + SystemFileCacheInformationEx = 81, + SystemThreadPriorityClientIdInformation = 82, + SystemProcessorIdleCycleTimeInformation = 83, + SystemVerifierCancellationInformation = 84, + SystemProcessorPowerInformationEx = 85, + SystemRefTraceInformation = 86, + SystemSpecialPoolInformation = 87, + SystemProcessIdInformation = 88, + SystemErrorPortInformation = 89, + SystemBootEnvironmentInformation = 90, + SystemHypervisorInformation = 91, + SystemVerifierInformationEx = 92, + SystemTimeZoneInformation = 93, + SystemImageFileExecutionOptionsInformation = 94, + SystemCoverageInformation = 95, + SystemPrefetchPatchInformation = 96, + SystemVerifierFaultsInformation = 97, + SystemSystemPartitionInformation = 98, + SystemSystemDiskInformation = 99, + SystemProcessorPerformanceDistribution = 100, + SystemNumaProximityNodeInformation = 101, + SystemDynamicTimeZoneInformation = 102, + SystemCodeIntegrityInformation = 103, + SystemProcessorMicrocodeUpdateInformation = 104, + SystemProcessorBrandString = 105, + SystemVirtualAddressInformation = 106, + SystemLogicalProcessorAndGroupInformation = 107, + SystemProcessorCycleTimeInformation = 108, + SystemStoreInformation = 109, + SystemRegistryAppendString = 110, + SystemAitSamplingValue = 111, + SystemVhdBootInformation = 112, + SystemCpuQuotaInformation = 113, + SystemNativeBasicInformation = 114, + SystemErrorPortTimeouts = 115, + SystemLowPriorityIoInformation = 116, + SystemBootEntropyInformation = 117, + SystemVerifierCountersInformation = 118, + SystemPagedPoolInformationEx = 119, + SystemSystemPtesInformationEx = 120, + SystemNodeDistanceInformation = 121, + SystemAcpiAuditInformation = 122, + SystemBasicPerformanceInformation = 123, + SystemQueryPerformanceCounterInformation = 124, + SystemSessionBigPoolInformation = 125, + SystemBootGraphicsInformation = 126, + SystemScrubPhysicalMemoryInformation = 127, + SystemBadPageInformation = 128, + SystemProcessorProfileControlArea = 129, + SystemCombinePhysicalMemoryInformation = 130, + SystemEntropyInterruptTimingInformation = 131, + SystemConsoleInformation = 132, + SystemPlatformBinaryInformation = 133, + SystemPolicyInformation = 134, + SystemHypervisorProcessorCountInformation = 135, + SystemDeviceDataInformation = 136, + SystemDeviceDataEnumerationInformation = 137, + SystemMemoryTopologyInformation = 138, + SystemMemoryChannelInformation = 139, + SystemBootLogoInformation = 140, + SystemProcessorPerformanceInformationEx = 141, + SystemCriticalProcessErrorLogInformation = 142, + SystemSecureBootPolicyInformation = 143, + SystemPageFileInformationEx = 144, + SystemSecureBootInformation = 145, + SystemEntropyInterruptTimingRawInformation = 146, + SystemPortableWorkspaceEfiLauncherInformation = 147, + SystemFullProcessInformation = 148, + SystemKernelDebuggerInformationEx = 149, + SystemBootMetadataInformation = 150, + SystemSoftRebootInformation = 151, + SystemElamCertificateInformation = 152, + SystemOfflineDumpConfigInformation = 153, + SystemProcessorFeaturesInformation = 154, + SystemRegistryReconciliationInformation = 155, + SystemEdidInformation = 156, + SystemManufacturingInformation = 157, + SystemEnergyEstimationConfigInformation = 158, + SystemHypervisorDetailInformation = 159, + SystemProcessorCycleStatsInformation = 160, + SystemVmGenerationCountInformation = 161, + SystemTrustedPlatformModuleInformation = 162, + SystemKernelDebuggerFlags = 163, + SystemCodeIntegrityPolicyInformation = 164, + SystemIsolatedUserModeInformation = 165, + SystemHardwareSecurityTestInterfaceResultsInformation = 166, + SystemSingleModuleInformation = 167, + SystemAllowedCpuSetsInformation = 168, + SystemVsmProtectionInformation = 169, + SystemInterruptCpuSetsInformation = 170, + SystemSecureBootPolicyFullInformation = 171, + SystemCodeIntegrityPolicyFullInformation = 172, + SystemAffinitizedInterruptProcessorInformation = 173, + SystemRootSiloInformation = 174, + SystemCpuSetInformation = 175, + SystemCpuSetTagInformation = 176, + SystemWin32WerStartCallout = 177, + SystemSecureKernelProfileInformation = 178, + SystemCodeIntegrityPlatformManifestInformation = 179, + SystemInterruptSteeringInformation = 180, + SystemSupportedProcessorArchitectures = 181, + SystemMemoryUsageInformation = 182, + SystemCodeIntegrityCertificateInformation = 183, + SystemPhysicalMemoryInformation = 184, + SystemControlFlowTransition = 185, + SystemKernelDebuggingAllowed = 186, + SystemActivityModerationExeState = 187, + SystemActivityModerationUserSettings = 188, + SystemCodeIntegrityPoliciesFullInformation = 189, + SystemCodeIntegrityUnlockInformation = 190, + SystemIntegrityQuotaInformation = 191, + SystemFlushInformation = 192, + SystemProcessorIdleMaskInformation = 193, + SystemSecureDumpEncryptionInformation = 194, + SystemWriteConstraintInformation = 195, + SystemKernelVaShadowInformation = 196, + SystemHypervisorSharedPageInformation = 197, + SystemFirmwareBootPerformanceInformation = 198, + SystemCodeIntegrityVerificationInformation = 199, + SystemFirmwarePartitionInformation = 200, + SystemSpeculationControlInformation = 201, + SystemDmaGuardPolicyInformation = 202, + SystemEnclaveLaunchControlInformation = 203, + SystemWorkloadAllowedCpuSetsInformation = 204, + SystemCodeIntegrityUnlockModeInformation = 205, + SystemLeapSecondInformation = 206, + SystemFlags2Information = 207, + SystemSecurityModelInformation = 208, + SystemCodeIntegritySyntheticCacheInformation = 209, + SystemFeatureConfigurationInformation = 210, + SystemFeatureConfigurationSectionInformation = 211, + SystemFeatureUsageSubscriptionInformation = 212, + SystemSecureSpeculationControlInformation = 213, + SystemSpacesBootInformation = 214, + SystemFwRamdiskInformation = 215, + SystemWheaIpmiHardwareInformation = 216, + SystemDifSetRuleClassInformation = 217, + SystemDifClearRuleClassInformation = 218, + SystemDifApplyPluginVerificationOnDriver = 219, + SystemDifRemovePluginVerificationOnDriver = 220, + SystemShadowStackInformation = 221, + SystemBuildVersionInformation = 222, + SystemPoolLimitInformation = 223, + SystemCodeIntegrityAddDynamicStore = 224, + SystemCodeIntegrityClearDynamicStores = 225, + SystemPoolZeroingInformation = 227, + MaxSystemInfoClass = 228 +} SYSTEM_INFORMATION_CLASS, *PSYSTEM_INFORMATION_CLASS; + +/* SystemBasicInformation = 0 */ +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; + ULONG_PTR ActiveProcessorsAffinityMask; + CHAR NumberOfProcessors; +} SYSTEM_BASIC_INFORMATION, *PSYSTEM_BASIC_INFORMATION; + +/* SystemProcessorInformation = 1 */ +typedef struct _SYSTEM_PROCESSOR_INFORMATION +{ + USHORT ProcessorArchitecture; + USHORT ProcessorLevel; + USHORT ProcessorRevision; + USHORT MaximumProcessors; // >= NT6.2 + ULONG ProcessorFeatureBits; +} SYSTEM_PROCESSOR_INFORMATION, *PSYSTEM_PROCESSOR_INFORMATION; + +/* SystemProcessInformation = 5 */ + +typedef struct _SYSTEM_PROCESS_INFORMATION +{ + ULONG NextEntryOffset; + ULONG NumberOfThreads; + LARGE_INTEGER WorkingSetPrivateSize; + ULONG HardFaultCount; + ULONG NumberOfThreadsHighWatermark; + ULONGLONG CycleTime; + LARGE_INTEGER CreateTime; + LARGE_INTEGER UserTime; + LARGE_INTEGER KernelTime; + UNICODE_STRING ImageName; + KPRIORITY BasePriority; + HANDLE UniqueProcessId; + HANDLE InheritedFromUniqueProcessId; + ULONG HandleCount; + ULONG SessionId; + ULONG_PTR PageDirectoryBase; + SIZE_T PeakVirtualSize; + SIZE_T VirtualSize; + ULONG PageFaultCount; + SIZE_T PeakWorkingSetSize; + SIZE_T WorkingSetSize; + SIZE_T QuotaPeakPagedPoolUsage; + SIZE_T QuotaPagedPoolUsage; + SIZE_T QuotaPeakNonPagedPoolUsage; + SIZE_T QuotaNonPagedPoolUsage; + SIZE_T PagefileUsage; + SIZE_T PeakPagefileUsage; + SIZE_T PrivatePageCount; + LARGE_INTEGER ReadOperationCount; + LARGE_INTEGER WriteOperationCount; + LARGE_INTEGER OtherOperationCount; + LARGE_INTEGER ReadTransferCount; + LARGE_INTEGER WriteTransferCount; + LARGE_INTEGER OtherTransferCount; +} SYSTEM_PROCESS_INFORMATION, *PSYSTEM_PROCESS_INFORMATION; + +typedef struct _SYSTEM_THREAD_INFORMATION +{ + LARGE_INTEGER KernelTime; + LARGE_INTEGER UserTime; + LARGE_INTEGER CreateTime; + ULONG WaitTime; + PVOID StartAddress; + CLIENT_ID ClientId; + KPRIORITY Priority; + LONG BasePriority; + ULONG ContextSwitches; + KTHREAD_STATE ThreadState; + KWAIT_REASON WaitReason; + ULONG PadPadAlignment; +} SYSTEM_THREAD_INFORMATION, *PSYSTEM_THREAD_INFORMATION; + +/* SystemModuleInformation = 11 */ + +typedef struct _SYSTEM_MODULE_ENTRY +{ + ULONG_PTR Unused; + ULONG_PTR Always0; + PVOID ModuleBaseAddress; + ULONG ModuleSize; + ULONG Unknown; + ULONG ModuleEntryIndex; + USHORT ModuleNameLength; + USHORT ModuleNameOffset; + CHAR ModuleName[256]; +} SYSTEM_MODULE_ENTRY, *PSYSTEM_MODULE_ENTRY; + +typedef struct _SYSTEM_MODULE_INFORMATION +{ + ULONG Count; + _Field_size_(Count) SYSTEM_MODULE_ENTRY Module[ANYSIZE_ARRAY]; +} SYSTEM_MODULE_INFORMATION, *PSYSTEM_MODULE_INFORMATION; + +/* SystemExtendedHandleInformation = 64 */ + +typedef struct _SYSTEM_HANDLE_TABLE_ENTRY_INFO_EX +{ + PVOID Object; + ULONG_PTR UniqueProcessId; + ULONG_PTR HandleValue; + ULONG GrantedAccess; + USHORT CreatorBackTraceIndex; + USHORT ObjectTypeIndex; + ULONG HandleAttributes; + ULONG Reserved; +} SYSTEM_HANDLE_TABLE_ENTRY_INFO_EX, *PSYSTEM_HANDLE_TABLE_ENTRY_INFO_EX; + +typedef struct _SYSTEM_HANDLE_INFORMATION_EX +{ + ULONG_PTR NumberOfHandles; + ULONG_PTR Reserved; + _Field_size_(NumberOfHandles) SYSTEM_HANDLE_TABLE_ENTRY_INFO_EX Handles[ANYSIZE_ARRAY]; +} SYSTEM_HANDLE_INFORMATION_EX, *PSYSTEM_HANDLE_INFORMATION_EX; + +/* SystemFirmwareTableInformation = 76 */ + +typedef enum _SYSTEM_FIRMWARE_TABLE_ACTION +{ + SystemFirmwareTable_Enumerate, + SystemFirmwareTable_Get +} SYSTEM_FIRMWARE_TABLE_ACTION; + +typedef struct _SYSTEM_FIRMWARE_TABLE_INFORMATION +{ + ULONG ProviderSignature; + SYSTEM_FIRMWARE_TABLE_ACTION Action; + ULONG TableID; + ULONG TableBufferLength; + _Field_size_(TableBufferLength) UCHAR TableBuffer[ANYSIZE_ARRAY]; +} SYSTEM_FIRMWARE_TABLE_INFORMATION, *PSYSTEM_FIRMWARE_TABLE_INFORMATION; diff --git a/Source/Include/KNSoft/NDK/NT/Types/Types.h b/Source/Include/KNSoft/NDK/NT/Types/Types.h new file mode 100644 index 0000000..a1ce28e --- /dev/null +++ b/Source/Include/KNSoft/NDK/NT/Types/Types.h @@ -0,0 +1,19 @@ +#pragma once + +#include "Basic.h" + +#include "Ke.h" +#include "Se.h" +#include "Mm.h" +#include "Ob.h" +#include "Io.h" +#include "Fs.h" +#include "Ps.h" +#include "Rtl.h" +#include "Ldr.h" +#include "Cm.h" +#include "Ex.h" + +#include "Sys.h" + +#include "Advance.h" diff --git a/Source/Include/KNSoft/NDK/UnitTest/UnitTest.h b/Source/Include/KNSoft/NDK/UnitTest/UnitTest.h new file mode 100644 index 0000000..3981de7 --- /dev/null +++ b/Source/Include/KNSoft/NDK/UnitTest/UnitTest.h @@ -0,0 +1,137 @@ +/* + * KNSoft.NDK.UnitTest + * + * Lite weight unit test framework + * + * Basic usage: + * + * // Define a test entry + * TEST_DECL(Xxx) + * { + * TEST_OK(1 == 1); + * TEST_SKIP("Skip reason"); + * } + * + * // Use UnitTest_Main to use default unit test program template + * int wmain( + * _In_ int argc, + * _In_reads_(argc) _Pre_z_ wchar_t** argv) + * { + * return UnitTest_Main(argc, argv); + * } + * + * ** FIXME: Not support C++ yet ** + */ + +#pragma once + +#ifdef __cplusplus +#error FIXME: Not support C++ yet +#endif + +#include "../NT/MinDef.h" + +EXTERN_C_START + +typedef struct _UNITTEST_RESULT +{ + ULONG Pass; + ULONG Fail; + ULONG Skip; + ULONGLONG Elapsed; // in μs (us, microsecond) +} UNITTEST_RESULT, *PUNITTEST_RESULT; + +typedef VOID NTAPI FN_UNITTEST_PROC( + UNITTEST_RESULT* Result, + _In_ INT ArgC, + _In_reads_(ArgC) _Pre_z_ PCWSTR* ArgV); + +typedef struct _UNITTEST_ENTRY +{ + FN_UNITTEST_PROC* Proc; + UNICODE_STRING Name; +} UNITTEST_ENTRY, *PUNITTEST_ENTRY; +typedef const UNITTEST_ENTRY *PCUNITTEST_ENTRY; + +typedef BOOL CALLBACK FN_UNITTEST_ENUM_PROC(_In_ PCUNITTEST_ENTRY Entry, _In_opt_ PVOID Context); + +BOOL NTAPI UnitTest_EnumEntries( + _In_ __callback FN_UNITTEST_ENUM_PROC* Callback, + _In_opt_ PVOID Context); + +_Ret_maybenull_ +_Must_inspect_result_ +PCUNITTEST_ENTRY NTAPI UnitTest_FindEntry( + _In_z_ PCWSTR Name); + +VOID NTAPI UnitTest_RunEntry( + _In_ PCUNITTEST_ENTRY Entry, + _Out_ PUNITTEST_RESULT Result, + _In_ INT ArgC, + _In_reads_(ArgC) _Pre_z_ PCWSTR* ArgV); + +ULONG NTAPI UnitTest_RunAll( + _Out_ PUNITTEST_RESULT Result); + +_Success_(return != FALSE) +BOOL NTAPI UnitTest_Run( + _In_z_ PCWSTR Name, + _Out_ PUNITTEST_RESULT Result, + _In_ INT ArgC, + _In_reads_(ArgC) _Pre_z_ PCWSTR* ArgV); + +_Success_(return == 0) +INT NTAPI UnitTest_Main( + _In_ int argc, + _In_reads_(argc) _Pre_z_ wchar_t** argv); + +/* Print string to stdout */ +VOID NTAPI UnitTest_PrintEx( + _In_reads_bytes_(TextSize) PCCH Text, + _In_ ULONG TextSize); + +#define UnitTest_Print(Text) UnitTest_PrintEx(Text, sizeof(Text)) + +/* Format string and print to stdout */ +VOID __cdecl UnitTest_PrintF( + _In_z_ _Printf_format_string_ PCSTR Format, + ...); + +/* Format string and output to both of stdout and debugger */ +VOID __cdecl UnitTest_FormatMessage( + _In_z_ _Printf_format_string_ PCSTR Format, + ...); + +#pragma section(".NDK$UTB", long, read) + +#define TEST_PARAMETER_RESULT _KNSoft_NDK_UnitTest_Result +#define TEST_PARAMETER_ARGC _KNSoft_NDK_UnitTest_ArgC +#define TEST_PARAMETER_ARGV _KNSoft_NDK_UnitTest_ArgV + +#if _WIN64 +#define TEST_INCLUDE_VAR(x) __pragma(comment(linker, "/include:"#x)) +#else +#define TEST_INCLUDE_VAR(x) __pragma(comment(linker, "/include:_"#x)) +#endif + +/* Define a test entry (function) */ +#define TEST_DECL(Name)\ +VOID NTAPI Name(UNITTEST_RESULT* TEST_PARAMETER_RESULT, _In_ INT TEST_PARAMETER_ARGC, _In_reads_(TEST_PARAMETER_ARGC) _Pre_z_ PCWSTR* TEST_PARAMETER_ARGV);\ +static UNITTEST_ENTRY const _KNSoft_NDK_UnitTest_Entry_##Name = { Name, RTL_CONSTANT_STRING(L###Name) };\ +__declspec(allocate(".NDK$UTB")) PCUNITTEST_ENTRY _KNSoft_NDK_UnitTest_Entry_Ptr_##Name = &_KNSoft_NDK_UnitTest_Entry_##Name;\ +TEST_INCLUDE_VAR(_KNSoft_NDK_UnitTest_Entry_Ptr_##Name)\ +VOID NTAPI Name(UNITTEST_RESULT* TEST_PARAMETER_RESULT, _In_ INT TEST_PARAMETER_ARGC, _In_reads_(TEST_PARAMETER_ARGC) _Pre_z_ PCWSTR* TEST_PARAMETER_ARGV) + +/* Increase count of test result, parameter can be Pass/Fail/Skip */ +#define TEST_RESULT(r) (TEST_PARAMETER_RESULT->r++) + +/* Pass if Expr is True, or fail and print assertion otherwise */ +#define TEST_OK(Expr) (Expr ? TEST_RESULT(Pass) : (TEST_RESULT(Fail), UnitTest_FormatMessage("%hs (Line %d) Assertion failed: %hs\n", __FILE__, __LINE__, #Expr))) + +/* Skip and print message */ +#define TEST_SKIP(Format, ...) (TEST_RESULT(Skip), UnitTest_FormatMessage("%hs (Line %d) Skipped: "Format"\n", __FILE__, __LINE__, ##__VA_ARGS__)) + +/* Fail and print message */ +#define TEST_FAIL(Format, ...) (TEST_RESULT(Fail), UnitTest_FormatMessage("%hs (Line %d) Failed: "Format"\n", __FILE__, __LINE__, ##__VA_ARGS__)) + +EXTERN_C_END diff --git a/Source/Include/KNSoft/NDK/UnitTest/UnitTest.inl b/Source/Include/KNSoft/NDK/UnitTest/UnitTest.inl new file mode 100644 index 0000000..8a57f55 --- /dev/null +++ b/Source/Include/KNSoft/NDK/UnitTest/UnitTest.inl @@ -0,0 +1,339 @@ +#include "../Include/KNSoft/NDK/UnitTest/UnitTest.h" + +#include "../Include/KNSoft/NDK/Extension/StrSafe.h" +#include "../Include/KNSoft/NDK/Win32/API/Ntdll.h" +#include "../Include/KNSoft/NDK/NT/Extension.h" + +#pragma region Entries + +#pragma section(".NDK$UTA", long, read) // First +#pragma section(".NDK$UTZ", long, read) // Last + +static __declspec(allocate(".NDK$UTA")) PUNITTEST_ENTRY g_EntryList_First = NULL; +static __declspec(allocate(".NDK$UTZ")) PUNITTEST_ENTRY g_EntryList_Last = NULL; +static PUNITTEST_ENTRY* const g_pEntryBegin = (&g_EntryList_First) + 1; +static PUNITTEST_ENTRY* const g_pEntryEnd = (&g_EntryList_Last); + +#pragma comment(linker, "/merge:.NDK=.rdata") + +#pragma endregion + +#pragma region Prints + +static VOID UnitTest_PrintTitle() +{ + UnitTest_Print("====================================================================================================\n" + "KNSoft.NDK.UnitTest\n\n" + " Lite-weight Unit Test Framework from KNSoft.NDK (https://github.com/KNSoft/KNSoft.NDK)\n" + "====================================================================================================\n\n"); +} + +static VOID UnitTest_PrintUsage() +{ + UnitTest_Print("Usage: Test_Program [-Run | -List] [TestName] [Parameters]\n\n" + "e.g.,\n\n" + " Test_Program -List\n" + " List all tests.\n\n" + " Test_Program -Run\n" + " Run all tests.\n\n" + " Test_Program -Run TestName -Switch1 -Switch2\n" + " Run the test that named TestName with two input parameters.\n\n" + "Exit with the count of failed tests, or 0 if no test failed.\n\n"); +} + +static VOID UnitTest_PrintList() +{ + PUNITTEST_ENTRY* Entry; + BOOL HasEntry = FALSE; + + UnitTest_Print("Test list:\n"); + + for (Entry = g_pEntryBegin; Entry != g_pEntryEnd; Entry++) + { + if (*Entry != NULL) + { + UnitTest_PrintF(" %wZ\n", &(*Entry)->Name); + HasEntry = TRUE; + } + } + if (!HasEntry) + { + UnitTest_Print(" (Empty)\n"); + } + + UnitTest_Print("\n"); +} + +#pragma endregion + +#pragma region Entry API + +BOOL NTAPI UnitTest_EnumEntries( + _In_ __callback FN_UNITTEST_ENUM_PROC* Callback, + _In_opt_ PVOID Context) +{ + PUNITTEST_ENTRY* Entry; + BOOL Ret; + + for (Entry = g_pEntryBegin; Entry != g_pEntryEnd; Entry++) + { + if (*Entry != NULL) + { + Ret = Callback(*Entry, Context); + if (!Ret) + { + return Ret; + } + } + } + + return TRUE; +} + +_Ret_maybenull_ +_Must_inspect_result_ +PCUNITTEST_ENTRY NTAPI UnitTest_FindEntry( + _In_z_ PCWSTR Name) +{ + PUNITTEST_ENTRY* Entry; + UNICODE_STRING NameString; + + RtlInitUnicodeString(&NameString, Name); + + for (Entry = g_pEntryBegin; Entry != g_pEntryEnd; Entry++) + { + if (*Entry != NULL && RtlEqualUnicodeString(&(*Entry)->Name, &NameString, FALSE)) + { + return *Entry; + } + } + + return NULL; +} + +#pragma endregion + +#pragma region Execute API + +VOID NTAPI UnitTest_RunEntry( + _In_ PCUNITTEST_ENTRY Entry, + _Out_ PUNITTEST_RESULT Result, + _In_ INT ArgC, + _In_reads_(ArgC) _Pre_z_ PCWSTR* ArgV) +{ + LARGE_INTEGER PrefCounter1, PrefCounter2, PrefFreq; + ULONGLONG ElapsedMicroseconds; + + UnitTest_FormatMessage(">>>> Running unit test: %wZ\n", &Entry->Name); + RtlZeroMemory(Result, sizeof(*Result)); + + /* NtQueryPerformanceCounter writes frequency after counter */ + NtQueryPerformanceCounter(&PrefCounter1, NULL); + Entry->Proc(Result, ArgC, ArgV); + NtQueryPerformanceCounter(&PrefCounter2, &PrefFreq); + + /* Convert to microseconds before dividing for avoiding loss-of-precision */ + ElapsedMicroseconds = (ULONGLONG)PrefCounter2.QuadPart - (ULONGLONG)PrefCounter1.QuadPart; + ElapsedMicroseconds *= 1000000; + ElapsedMicroseconds = (ULONGLONG)((ElapsedMicroseconds / (DOUBLE)PrefFreq.QuadPart) + (DOUBLE)0.5); + Result->Elapsed = ElapsedMicroseconds; + UnitTest_FormatMessage("<<<< Result: %lu tests executed (%lu passed, %lu failed, %lu skipped) in %llu ms (%llu μs)\n\n", + Result->Pass + Result->Fail + Result->Skip, + Result->Pass, + Result->Fail, + Result->Skip, + (ULONGLONG)((ElapsedMicroseconds / 1000.0F) + 0.5F), + Result->Elapsed); +} + +ULONG NTAPI UnitTest_RunAll( + _Out_ PUNITTEST_RESULT Result) +{ + ULONG Ret = 0; + PCUNITTEST_ENTRY* Entry; + UNITTEST_RESULT EntryResult; + + RtlZeroMemory(Result, sizeof(*Result)); + + for (Entry = g_pEntryBegin; Entry != g_pEntryEnd; Entry++) + { + if (*Entry != NULL) + { + UnitTest_RunEntry(*Entry, &EntryResult, 0, NULL); + Result->Pass += EntryResult.Pass; + Result->Fail += EntryResult.Fail; + Result->Skip += EntryResult.Skip; + Result->Elapsed += EntryResult.Elapsed; + Ret++; + } + } + + if (Ret > 0) + { + UnitTest_FormatMessage("Totally %lu test entries ran, %lu tests executed (%lu passed, %lu failed, %lu skipped) in %llu ms\n", + Ret, + Result->Pass + Result->Fail + Result->Skip, + Result->Pass, + Result->Fail, + Result->Skip, + (ULONGLONG)((Result->Elapsed / 1000.0F) + 0.5F)); + } + return Ret; +} + +_Success_(return != FALSE) +BOOL NTAPI UnitTest_Run( + _In_z_ PCWSTR Name, + _Out_ PUNITTEST_RESULT Result, + _In_ INT ArgC, + _In_reads_(ArgC) _Pre_z_ PCWSTR* ArgV) +{ + PCUNITTEST_ENTRY Entry = UnitTest_FindEntry(Name); + + if (Entry == NULL) + { + return FALSE; + } + + UnitTest_RunEntry(Entry, Result, ArgC, ArgV); + return TRUE; +} + +_Success_(return == 0) +INT NTAPI UnitTest_Main( + _In_ int argc, + _In_reads_(argc) _Pre_z_ wchar_t** argv) +{ + UNITTEST_RESULT Result; + PCUNITTEST_ENTRY Entry; + + UnitTest_PrintTitle(); + if (argc > 1) + { + if (_wcsicmp(argv[1], L"-List") == 0) + { + UnitTest_PrintList(); + return 0; + } else if (_wcsicmp(argv[1], L"-Run") == 0) + { + if (argc == 2) + { + if (UnitTest_RunAll(&Result) == 0) + { + UnitTest_Print("No test entry found\n\n"); + return (INT)STATUS_NOT_FOUND; + } + return Result.Fail; + } else if (argc >= 3) + { + Entry = UnitTest_FindEntry(argv[2]); + if (Entry == NULL) + { + UnitTest_PrintF("Test \"%ls\" not found\n\n", argv[2]); + UnitTest_PrintList(); + return (INT)STATUS_NOT_FOUND; + } + UnitTest_RunEntry(Entry, &Result, argc - 3, argv + 3); + return Result.Fail; + } + } + } + + UnitTest_Print("Invalid parameter\n\n"); + UnitTest_PrintUsage(); + return (INT)STATUS_INVALID_PARAMETER; +} + +#pragma endregion + +#pragma region Utils + +static VOID __cdecl UnitTest_PrintFV( + _In_z_ _Printf_format_string_ PCSTR Format, + _In_ va_list ArgList) +{ + CHAR sz[512 + 1]; // Same limitation as DbgPrint + ULONG u, uNew; + HANDLE hStdOut; + PSTR psz; + IO_STATUS_BLOCK IoStatusBlock; + + /* Write standard output if exists */ + hStdOut = NtCurrentPeb()->ProcessParameters->StandardOutput; + if (hStdOut == NULL) + { + return; + } + + /* Format string */ + u = StrSafe_CchVPrintfA(sz, ARRAYSIZE(sz), Format, ArgList); + if (u == 0) + { + return; + } + + /* Allocate buffer if sz too small */ + if (u >= ARRAYSIZE(sz)) + { + psz = RtlAllocateHeap(NtGetProcessHeap(), 0, (SIZE_T)u + 1); + if (psz != NULL) + { + uNew = StrSafe_CchVPrintfA(psz, (SIZE_T)u + 1, Format, ArgList); + if (uNew > 0 && uNew < u) + { + u = uNew; + goto _Print_Stdout; + } + RtlFreeHeap(NtGetProcessHeap(), 0, psz); + } + + /* New allocated buffer unavailable, fallback to sz (truncated) */ + u = ARRAYSIZE(sz) - 1; + } + + psz = sz; + +_Print_Stdout: + NtWriteFile(hStdOut, NULL, NULL, NULL, &IoStatusBlock, psz, u, NULL, NULL); + if (psz != sz) + { + RtlFreeHeap(NtGetProcessHeap(), 0, psz); + } +} + +VOID NTAPI UnitTest_PrintEx( + _In_reads_bytes_(TextSize) PCCH Text, + _In_ ULONG TextSize) +{ + HANDLE StdOutHandle; + IO_STATUS_BLOCK IoStatusBlock; + + StdOutHandle = NtCurrentPeb()->ProcessParameters->StandardOutput; + if (StdOutHandle != NULL) + { + NtWriteFile(StdOutHandle, NULL, NULL, NULL, &IoStatusBlock, (PVOID)Text, TextSize, NULL, NULL); + } +} + +VOID __cdecl UnitTest_PrintF( + _In_z_ _Printf_format_string_ PCSTR Format, + ...) +{ + va_list ArgList; + + va_start(ArgList, Format); + UnitTest_PrintFV(Format, ArgList); +} + +VOID __cdecl UnitTest_FormatMessage( + _In_z_ _Printf_format_string_ PCSTR Format, + ...) +{ + va_list ArgList; + + va_start(ArgList, Format); + vDbgPrintEx(MAXULONG, DPFLTR_ERROR_LEVEL, Format, ArgList); + UnitTest_PrintFV(Format, ArgList); +} + +#pragma endregion diff --git a/Source/Include/KNSoft/NDK/Win32/API/Kernel32.h b/Source/Include/KNSoft/NDK/Win32/API/Kernel32.h new file mode 100644 index 0000000..9cd13da --- /dev/null +++ b/Source/Include/KNSoft/NDK/Win32/API/Kernel32.h @@ -0,0 +1,26 @@ +#pragma once + +#include "../../NT/MinDef.h" + +#include + +EXTERN_C_START + +WINBASEAPI +BOOL +WINAPI +CreateProcessInternalW( + _In_opt_ HANDLE hToken, + _In_opt_ LPCWSTR lpApplicationName, + _Inout_opt_ LPWSTR lpCommandLine, + _In_opt_ LPSECURITY_ATTRIBUTES lpProcessAttributes, + _In_opt_ LPSECURITY_ATTRIBUTES lpThreadAttributes, + _In_ BOOL bInheritHandles, + _In_ DWORD dwCreationFlags, + _In_opt_ LPVOID lpEnvironment, + _In_opt_ LPCWSTR lpCurrentDirectory, + _In_ LPSTARTUPINFOW lpStartupInfo, + _Out_ LPPROCESS_INFORMATION lpProcessInformation, + _Out_opt_ PHANDLE hNewToken); + +EXTERN_C_END diff --git a/Source/Include/KNSoft/NDK/Win32/API/Ntdll.Csr.h b/Source/Include/KNSoft/NDK/Win32/API/Ntdll.Csr.h new file mode 100644 index 0000000..0d6e708 --- /dev/null +++ b/Source/Include/KNSoft/NDK/Win32/API/Ntdll.Csr.h @@ -0,0 +1,12 @@ +#pragma once + +#include "../../NT/MinDef.h" + +EXTERN_C_START + +NTSYSAPI +HANDLE +NTAPI +CsrGetProcessId(); + +EXTERN_C_END diff --git a/Source/Include/KNSoft/NDK/Win32/API/Ntdll.Dbg.h b/Source/Include/KNSoft/NDK/Win32/API/Ntdll.Dbg.h new file mode 100644 index 0000000..0d9d5bb --- /dev/null +++ b/Source/Include/KNSoft/NDK/Win32/API/Ntdll.Dbg.h @@ -0,0 +1,66 @@ +#pragma once + +#include "../../NT/MinDef.h" + +#include + +EXTERN_C_START + +NTSYSAPI +ULONG +__cdecl +DbgPrint( + _In_z_ _Printf_format_string_ PCSTR Format, + ...); + +NTSYSAPI +ULONG +__cdecl +DbgPrintEx( + _In_ ULONG ComponentId, + _In_ ULONG Level, + _In_z_ _Printf_format_string_ PCSTR Format, + ...); + +NTSYSAPI +ULONG +NTAPI +vDbgPrintEx( + _In_ ULONG ComponentId, + _In_ ULONG Level, + _In_z_ PCCH Format, + _In_ va_list arglist); + +NTSYSAPI +ULONG +NTAPI +vDbgPrintExWithPrefix( + _In_z_ PCCH Prefix, + _In_ ULONG ComponentId, + _In_ ULONG Level, + _In_z_ PCCH Format, + _In_ va_list arglist); + +NTSYSAPI +ULONG +__cdecl +DbgPrintReturnControlC( + _In_z_ _Printf_format_string_ PCCH Format, + ...); + +NTSYSAPI +NTSTATUS +NTAPI +DbgQueryDebugFilterState( + _In_ ULONG ComponentId, + _In_ ULONG Level); + +NTSYSAPI +NTSTATUS +NTAPI +DbgSetDebugFilterState( + _In_ ULONG ComponentId, + _In_ ULONG Level, + _In_ BOOLEAN State); + +EXTERN_C_END diff --git a/Source/Include/KNSoft/NDK/Win32/API/Ntdll.Hash.h b/Source/Include/KNSoft/NDK/Win32/API/Ntdll.Hash.h new file mode 100644 index 0000000..5ead23c --- /dev/null +++ b/Source/Include/KNSoft/NDK/Win32/API/Ntdll.Hash.h @@ -0,0 +1,101 @@ +#pragma once + +#include "../../NT/MinDef.h" + +EXTERN_C_START + +typedef struct _A_SHA_CTX +{ + UCHAR Buffer[64]; + ULONG State[5]; + ULONG Count[2]; +} A_SHA_CTX, *PA_SHA_CTX; + +#define A_SHA_DIGEST_LEN 20 + +typedef struct _MD5_CTX +{ + ULONG Count[2]; + ULONG State[4]; + UCHAR Buffer[64]; + UCHAR Hash[16]; +} MD5_CTX, *PMD5_CTX; + +#define MD5_DIGEST_LEN 16 + +typedef struct _MD4_CTX +{ + ULONG State[4]; + ULONG Count[2]; + UCHAR Buffer[64]; + UCHAR Hash[16]; +} MD4_CTX, *PMD4_CTX; + +#define MD4_DIGEST_LEN 16 + +#ifndef RSA32API +#define RSA32API __stdcall +#endif + +NTSYSAPI +VOID +RSA32API +A_SHAInit( + _Out_ PA_SHA_CTX Context); + +NTSYSAPI +VOID +RSA32API +A_SHAUpdate( + _Inout_ PA_SHA_CTX Context, + _In_reads_(BufferSize) PUCHAR Buffer, + _In_ ULONG BufferSize); + +NTSYSAPI +VOID +RSA32API +A_SHAFinal( + _Inout_ PA_SHA_CTX Context, + _Out_ PUCHAR Result); + +NTSYSAPI +VOID +RSA32API +MD5Init( + _Out_ PMD5_CTX Context); + +NTSYSAPI +VOID +RSA32API +MD5Update( + _Inout_ PMD5_CTX Context, + _In_reads_(BufferSize) PUCHAR Buffer, + _In_ ULONG BufferSize); + +NTSYSAPI +VOID +RSA32API +MD5Final( + _Inout_ PMD5_CTX Context); + +NTSYSAPI +VOID +RSA32API +MD4Init( + _Out_ PMD4_CTX Context); + +NTSYSAPI +VOID +RSA32API +MD4Update( + _Inout_ PMD4_CTX Context, + _In_reads_(BufferSize) PUCHAR Buffer, + _In_ ULONG BufferSize); + +NTSYSAPI +VOID +RSA32API +MD4Final( + _Inout_ PMD4_CTX Context); + +EXTERN_C_END diff --git a/Source/Include/KNSoft/NDK/Win32/API/Ntdll.Ldr.h b/Source/Include/KNSoft/NDK/Win32/API/Ntdll.Ldr.h new file mode 100644 index 0000000..bbf94f5 --- /dev/null +++ b/Source/Include/KNSoft/NDK/Win32/API/Ntdll.Ldr.h @@ -0,0 +1,86 @@ +#pragma once + +#include "../../NT/MinDef.h" +#include "../../NT/Types/Ldr.h" + +EXTERN_C_START + +NTSTATUS +NTAPI +LdrLockLoaderLock( + _In_ ULONG Flags, + _Out_opt_ PULONG Disposition, + _Out_opt_ PULONG_PTR Cookie); + +NTSTATUS +NTAPI +LdrUnlockLoaderLock( + _In_ ULONG Flags, + _In_opt_ ULONG Cookie); + +NTSTATUS +NTAPI +LdrDisableThreadCalloutsForDll( + _In_ PVOID BaseAddress); + +NTSTATUS +NTAPI +LdrFindEntryForAddress( + _In_ PVOID Address, + _Out_ PLDR_DATA_TABLE_ENTRY* Module); + +NTSTATUS +NTAPI +LdrEnumerateLoadedModules( + _Reserved_ ULONG ReservedFlag, + _In_ PLDR_ENUM_CALLBACK EnumProc, + _In_opt_ PVOID Context); + +NTSTATUS +NTAPI +LdrGetDllHandle( + _In_opt_ PWSTR DllPath, + _In_opt_ PULONG DllCharacteristics, + _In_ PUNICODE_STRING DllName, + _Out_ PVOID* DllHandle); + +NTSYSAPI +NTSTATUS +NTAPI +LdrLoadDll( + _In_opt_ PWSTR DllSearchPath, + _In_opt_ PULONG DllCharacteristics, + _In_ PUNICODE_STRING DllName, + _Out_ PVOID* BaseAddress); + +NTSYSAPI +NTSTATUS +NTAPI +LdrUnloadDll( + _In_ PVOID BaseAddress); + +NTSYSAPI +NTSTATUS +NTAPI +LdrGetProcedureAddress( + _In_ PVOID BaseAddress, + _In_opt_ _When_(Ordinal == 0, _Notnull_) PANSI_STRING Name, + _In_opt_ _When_(Name == NULL, _In_range_(>, 0)) ULONG Ordinal, + _Out_ PVOID* ProcedureAddress); + +NTSYSAPI +NTSTATUS +NTAPI +LdrRegisterDllNotification( + _In_ ULONG Flags, + _In_ PLDR_DLL_NOTIFICATION_FUNCTION NotificationFunction, + _In_opt_ PVOID Context, + _Out_ PVOID* Cookie); + +NTSYSAPI +NTSTATUS +NTAPI +LdrUnregisterDllNotification( + _In_ PVOID Cookie); + +EXTERN_C_END diff --git a/Source/Include/KNSoft/NDK/Win32/API/Ntdll.h b/Source/Include/KNSoft/NDK/Win32/API/Ntdll.h new file mode 100644 index 0000000..378676b --- /dev/null +++ b/Source/Include/KNSoft/NDK/Win32/API/Ntdll.h @@ -0,0 +1,7 @@ +#pragma once + +#include "Ntdll.Csr.h" +#include "Ntdll.Ldr.h" +#include "Ntdll.Dbg.h" + +#include "../../NT/API/API.h" diff --git a/Source/Include/KNSoft/NDK/Win32/API/User32.h b/Source/Include/KNSoft/NDK/Win32/API/User32.h new file mode 100644 index 0000000..139868f --- /dev/null +++ b/Source/Include/KNSoft/NDK/Win32/API/User32.h @@ -0,0 +1,39 @@ +#pragma once + +#include "../../NT/MinDef.h" + +#include + +EXTERN_C_START + +WINUSERAPI +INT +WINAPI +MessageBoxTimeoutA( + _In_opt_ HWND hWnd, + _In_opt_ LPCSTR lpText, + _In_opt_ LPCSTR lpCaption, + _In_ UINT uType, + _In_ WORD wLanguageId, + _In_ DWORD dwMilliseconds); + +WINUSERAPI +INT +WINAPI +MessageBoxTimeoutW( + _In_opt_ HWND hWnd, + _In_opt_ LPCWSTR lpText, + _In_opt_ LPCWSTR lpCaption, + _In_ UINT uType, + _In_ WORD wLanguageId, + _In_ DWORD dwMilliseconds); + +WINUSERAPI +BOOL +WINAPI +EndTask( + HWND hWnd, + BOOL fShutDown, + BOOL fForce); + +EXTERN_C_END diff --git a/Source/Include/KNSoft/NDK/Win32/API/WinSta.h b/Source/Include/KNSoft/NDK/Win32/API/WinSta.h new file mode 100644 index 0000000..b432925 --- /dev/null +++ b/Source/Include/KNSoft/NDK/Win32/API/WinSta.h @@ -0,0 +1,32 @@ +#pragma once + +#include "../Def/winsta.h" + +EXTERN_C_START + +NTSYSAPI +BOOL +NTAPI +WinStationEnumerateW( + _In_opt_ HANDLE ServerHandle, + _Out_ PSESSIONID *SessionIds, + _Out_ PULONG Count); + +NTSYSAPI +BOOL +NTAPI +WinStationFreeMemory( + _Frees_ptr_ PVOID Buffer); + +NTSYSAPI +BOOLEAN +NTAPI +WinStationQueryInformationW( + _In_opt_ HANDLE ServerHandle, + _In_ ULONG LogonId, + _In_ WINSTATIONINFOCLASS WinStationInformationClass, + _Out_ PVOID WinStationInformation, + _In_ ULONG WinStationInformationLength, + _Out_ PULONG ReturnLength); + +EXTERN_C_END diff --git a/Source/Include/KNSoft/NDK/Win32/Def/CommCtrl.h b/Source/Include/KNSoft/NDK/Win32/Def/CommCtrl.h new file mode 100644 index 0000000..613be3c --- /dev/null +++ b/Source/Include/KNSoft/NDK/Win32/Def/CommCtrl.h @@ -0,0 +1,21 @@ +#pragma once + +#include + +#pragma comment(linker, "\"/manifestdependency:type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='*' publicKeyToken='6595b64144ccf1df' language='*'\"") + +#pragma region Patches C26454 warning + +#undef NM_FIRST +#define NM_FIRST 0x100000000 + +#undef TCN_FIRST +#define TCN_FIRST 0xFFFFFDDA + +#undef TVN_FIRST +#define TVN_FIRST 0xFFFFFE70 + +#undef LVN_FIRST +#define LVN_FIRST 0xFFFFFF9C + +#pragma endregion diff --git a/Source/Include/KNSoft/NDK/Win32/Def/WinUser.h b/Source/Include/KNSoft/NDK/Win32/Def/WinUser.h new file mode 100644 index 0000000..af4f699 --- /dev/null +++ b/Source/Include/KNSoft/NDK/Win32/Def/WinUser.h @@ -0,0 +1,5 @@ +#pragma once + +#ifndef WM_COPYGLOBALDATA +#define WM_COPYGLOBALDATA 0x49 +#endif diff --git a/Source/Include/KNSoft/NDK/Win32/Def/winsta.h b/Source/Include/KNSoft/NDK/Win32/Def/winsta.h new file mode 100644 index 0000000..321eac3 --- /dev/null +++ b/Source/Include/KNSoft/NDK/Win32/Def/winsta.h @@ -0,0 +1,1070 @@ +#pragma once + +#include "../../NT/MinDef.h" + +/* + * winsta.h from + * https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-tsts/ce70794f-2138-43e8-bf6c-2c147887d6a2 + */ + +#define WDPREFIX_LENGTH 12 +#define STACK_ADDRESS_LENGTH 128 +#define MAX_BR_NAME 65 +#define DIRECTORY_LENGTH 256 +#define INITIALPROGRAM_LENGTH 256 +#define USERNAME_LENGTH 20 +#define DOMAIN_LENGTH 17 +#define PASSWORD_LENGTH 14 +#define NASISPECIFICNAME_LENGTH 14 +#define NASIUSERNAME_LENGTH 47 +#define NASIPASSWORD_LENGTH 24 +#define NASISESSIONNAME_LENGTH 16 +#define NASIFILESERVER_LENGTH 47 + +#define CLIENTDATANAME_LENGTH 7 +#define CLIENTNAME_LENGTH 20 +#define CLIENTADDRESS_LENGTH 30 +#define IMEFILENAME_LENGTH 32 +#define DIRECTORY_LENGTH 256 +#define CLIENTLICENSE_LENGTH 32 +#define CLIENTMODEM_LENGTH 40 +#define CLIENT_PRODUCT_ID_LENGTH 32 +#define MAX_COUNTER_EXTENSIONS 2 +#define WINSTATIONNAME_LENGTH 32 + + +typedef enum _SDCLASS { + SdNone = 0, + SdConsole, + SdNetwork, + SdAsync, + SdOemTransport +} SDCLASS; + +typedef enum _FLOWCONTROLCLASS { + FlowControl_None, + FlowControl_Hardware, + FlowControl_Software +} FLOWCONTROLCLASS; + +typedef enum _WINSTATIONSTATECLASS { + State_Active = 0, + State_Connected = 1, + State_ConnectQuery = 2, + State_Shadow = 3, + State_Disconnected = 4, + State_Idle = 5, + State_Listen = 6, + State_Reset = 7, + State_Down = 8, + State_Init = 9 +} WINSTATIONSTATECLASS; + +typedef WCHAR NASISPECIFICNAME[NASISPECIFICNAME_LENGTH + 1]; + +typedef WCHAR NASIUSERNAME[NASIUSERNAME_LENGTH + 1]; + +typedef WCHAR NASIPASSWORD[NASIPASSWORD_LENGTH + 1]; + +typedef WCHAR NASISESIONNAME[NASISESSIONNAME_LENGTH + 1]; + +typedef WCHAR NASIFILESERVER[NASIFILESERVER_LENGTH + 1]; + +typedef CHAR CLIENTDATANAME[CLIENTDATANAME_LENGTH + 1]; +typedef CHAR * PCLIENTDATANAME; + +typedef WCHAR WINSTATIONNAME[WINSTATIONNAME_LENGTH + 1]; + +typedef struct _TS_SYSTEMTIME { + USHORT wYear; + USHORT wMonth; + USHORT wDayOfWeek; + USHORT wDay; + USHORT wHour; + USHORT wMinute; + USHORT wSecond; + USHORT wMilliseconds; +} TS_SYSTEMTIME; + +typedef struct _TS_TIME_ZONE_INFORMATION { + LONG Bias; + WCHAR StandardName[32]; + TS_SYSTEMTIME StandardDate; + LONG StandardBias; + WCHAR DaylightName[32]; + TS_SYSTEMTIME DaylightDate; + LONG DaylightBias; +} TS_TIME_ZONE_INFORMATION; + + +#ifdef _WIN64 +typedef unsigned __int64 ULONG_PTR; +#else +typedef ULONG ULONG_PTR; +#endif + +typedef ULONG PTR_SIZE_T; + +typedef enum { + SF_SERVICES_SESSION_POPUP +} SESSION_FILTER; + +#define PROTOCOL_CONSOLE 0 +#define PROTOCOL_ICA 1 +#define PROTOCOL_TSHARE 2 +#define PROTOCOL_RDP 2 +#define PDNAME_LENGTH 32 +#define WDNAME_LENGTH 32 +#define CDNAME_LENGTH 32 +#define DEVICENAME_LENGTH 128 +#define MODEMNAME_LENGTH DEVICENAME_LENGTH +#define CALLBACK_LENGTH 50 +#define DLLNAME_LENGTH 32 +#define WINSTATIONCOMMENT_LENGTH 60 +#define MAX_LICENSE_SERVER_LENGTH 1024 +#define LOGONID_CURRENT ((ULONG)-1) +#define MAX_PDCONFIG 10 + +#define TERMSRV_TOTAL_SESSIONS 1 +#define TERMSRV_DISC_SESSIONS 2 +#define TERMSRV_RECON_SESSIONS 3 +#define TERMSRV_CURRENT_ACTIVE_SESSIONS 4 +#define TERMSRV_CURRENT_DISC_SESSIONS 5 +#define TERMSRV_PENDING_SESSIONS 6 +#define TERMSRV_SUCC_TOTAL_LOGONS 7 +#define TERMSRV_SUCC_LOCAL_LOGONS 8 +#define TERMSRV_SUCC_REMOTE_LOGONS 9 +#define TERMSRV_SUCC_SESSION0_LOGONS 10 +#define TERMSRV_CURRENT_TERMINATING_SESSIONS 11 +#define TERMSRV_CURRENT_LOGGEDON_SESSIONS 12 + +#define NO_FALLBACK_DRIVERS 0x0 +#define FALLBACK_BESTGUESS 0x1 +#define FALLBACK_PCL 0x2 +#define FALLBACK_PS 0x3 +#define FALLBACK_PCLANDPS 0x4 + +/********************************* +* WinStationOpen access values +*********************************/ + +#define WINSTATION_QUERY 0x00000001 /* WinStationQueryInformation() */ +#define WINSTATION_SET 0x00000002 /* WinStationSetInformation() */ +#define WINSTATION_RESET 0x00000004 /* WinStationReset() */ +#define WINSTATION_VIRTUAL 0x00000008 /* read/write direct data */ +#define WINSTATION_SHADOW 0x00000010 /* WinStationShadow() */ +#define WINSTATION_LOGON 0x00000020 /* logon to WinStation */ +#define WINSTATION_LOGOFF 0x00000040 /* WinStationLogoff() */ +#define WINSTATION_MSG 0x00000080 /* WinStationMsg() */ +#define WINSTATION_CONNECT 0x00000100 /* WinStationConnect() */ +#define WINSTATION_DISCONNECT 0x00000200 /* WinStationDisconnect() */ +#define WINSTATION_GUEST_ACCESS (WINSTATION_LOGON) +#define WINSTATION_CURRENT_GUEST_ACCESS (WINSTATION_VIRTUAL | \ + WINSTATION_LOGOFF) +#define WINSTATION_USER_ACCESS (WINSTATION_GUEST_ACCESS | \ + WINSTATION_QUERY | \ + WINSTATION_CONNECT ) +#define WINSTATION_CURRENT_USER_ACCESS (WINSTATION_SET | \ + WINSTATION_RESET | \ + WINSTATION_VIRTUAL | \ + WINSTATION_LOGOFF | \ + WINSTATION_DISCONNECT) +#define WINSTATION_ALL_ACCESS ( STANDARD_RIGHTS_REQUIRED | \ + WINSTATION_QUERY | \ + WINSTATION_SET | \ + WINSTATION_RESET | \ + WINSTATION_VIRTUAL | \ + WINSTATION_SHADOW | \ + WINSTATION_LOGON | \ + WINSTATION_MSG | \ + WINSTATION_CONNECT | \ + WINSTATION_DISCONNECT) + +typedef WCHAR PDNAME[PDNAME_LENGTH + 1]; +typedef WCHAR * PPDNAME; + +/*------------------------------------------------*/ + +typedef WCHAR WDNAME[WDNAME_LENGTH + 1]; +typedef WCHAR * PWDNAME; + +/*------------------------------------------------*/ + +typedef WCHAR CDNAME[CDNAME_LENGTH + 1]; +typedef WCHAR * PCDNAME; + +/*------------------------------------------------*/ + +typedef WCHAR DEVICENAME[DEVICENAME_LENGTH + 1]; +typedef WCHAR * PDEVICENAME; + +/*------------------------------------------------*/ + +typedef WCHAR MODEMNAME[MODEMNAME_LENGTH + 1]; +typedef WCHAR * PMODEMNAME; + +/*------------------------------------------------*/ + +typedef WCHAR DLLNAME[DLLNAME_LENGTH + 1]; +typedef WCHAR * PDLLNAME; +typedef CHAR DLLNAMEA[DLLNAME_LENGTH + 1]; + +/*------------------------------------------------*/ + +typedef WCHAR WDPREFIX[WDPREFIX_LENGTH + 1]; +typedef WCHAR * PWDPREFIX; + +/* +* Stack address structure +*/ + +typedef struct _CLIENT_STACK_ADDRESS { + BYTE Address[STACK_ADDRESS_LENGTH]; // bytes 0,1 family, 2-n address +} CLIENT_STACK_ADDRESS, *PCLIENT_STACK_ADDRESS; + +typedef struct _TS_TRACE { + WCHAR TraceFile[256]; + BOOLEAN fDebugger; + BOOLEAN fTimestamp; + ULONG TraceClass; + ULONG TraceEnable; + WCHAR TraceOption[64]; +} TS_TRACE, * PTS_TRACE; + +#define EXTENDED_USERNAME_LEN 255 +#define EXTENDED_PASSWORD_LEN 255 +#define EXTENDED_DOMAIN_LEN 255 + +typedef struct _ExtendedClientCredentials { + WCHAR UserName[EXTENDED_USERNAME_LEN + 1]; + WCHAR Password[EXTENDED_PASSWORD_LEN + 1]; + WCHAR Domain[EXTENDED_DOMAIN_LEN + 1]; +}ExtendedClientCredentials, *pExtendedClientCredentials; + +/********************************* +* User Configuration structures +*********************************/ + +typedef WCHAR APPLICATIONNAME[MAX_BR_NAME]; +typedef WCHAR *PAPPLICATIONNAME; + +/* +* Shadow options +*/ + +typedef enum _SHADOWCLASS { + Shadow_Disable, + Shadow_EnableInputNotify, + Shadow_EnableInputNoNotify, + Shadow_EnableNoInputNotify, + Shadow_EnableNoInputNoNotify, +} SHADOWCLASS; + +/* +* Callback options +*/ + +typedef enum _CALLBACKCLASS { + Callback_Disable, + Callback_Roving, + Callback_Fixed, +} CALLBACKCLASS; + +typedef struct _POLICY_TS_MACHINE { + ULONG fPolicyDisableClip : 1; + ULONG fPolicyDisableCam : 1; + ULONG fPolicyDisableCcm : 1; + ULONG fPolicyDisableLPT : 1; + ULONG fPolicyDisableCpm : 1; + ULONG fPolicyPromptForPassword : 1; + ULONG fPolicyMaxInstanceCount : 1; + ULONG fPolicyMinEncryptionLevel : 1; + ULONG fPolicyFipsEnabled : 1; + ULONG fPolicyDisableAutoReconnect : 1; + ULONG fPolicyWFProfilePath : 1; + ULONG fPolicyWFHomeDir : 1; + ULONG fPolicyWFHomeDirDrive : 1; + ULONG fPolicyDenyTSConnections : 1; + ULONG fPolicyTempFoldersPerSession : 1; + ULONG fPolicyDeleteTempFoldersOnExit : 1; + ULONG fPolicyColorDepth : 1; + ULONG fPolicySessionDirectoryActive : 1; + ULONG fPolicySessionDirectoryLocation : 1; + ULONG fPolicySessionDirectoryClusterName : 1; + ULONG fPolicySessionDirectoryAdditionalParams : 1; + ULONG fPolicySessionDirectoryExposeServerIP : 1; + ULONG fPolicyPreventLicenseUpgrade : 1; + ULONG fPolicySecureLicensing : 1; + ULONG fPolicyWritableTSCCPermissionsTAB : 1; + ULONG fPolicyDisableCdm : 1; + ULONG fPolicyForceClientLptDef : 1; + ULONG fPolicyShadow : 1; + ULONG fPolicyResetBroken : 1; + ULONG fPolicyReconnectSame : 1; + ULONG fPolicyMaxSessionTime : 1; + ULONG fPolicyMaxDisconnectionTime : 1; + ULONG fPolicyMaxIdleTime : 1; + ULONG fPolicyInitialProgram : 1; + ULONG fPolicySingleSessionPerUser : 1; + ULONG fPolicyDisableWallpaper : 1; + ULONG fPolicyKeepAlive : 1; + ULONG fPolicyEnableTimeZoneRedirection : 1; + ULONG fPolicyDisableForcibleLogoff : 1; + ULONG fPolicyLicensingMode : 1; + ULONG fPolicyExplicitLSDiscovery : 1; + ULONG fPolicyDisableTerminalServerTooltip : 1; + ULONG fDisableClip : 1; + ULONG fDisableCam : 1; + ULONG fDisableCcm : 1; + ULONG fDisableLPT : 1; + ULONG fDisableCpm : 1; + ULONG fPromptForPassword : 1; + ULONG ColorDepth : 3; + ULONG fDenyTSConnections : 1; + ULONG fTempFoldersPerSession : 1; + ULONG fDeleteTempFoldersOnExit : 1; + ULONG fWritableTSCCPermissionsTAB : 1; + ULONG fDisableCdm : 1; + ULONG fForceClientLptDef : 1; + ULONG fResetBroken : 1; + ULONG fReconnectSame : 1; + ULONG fSingleSessionPerUser : 1; + ULONG fDisableWallpaper : 1; + ULONG fKeepAliveEnable : 1; + ULONG fPreventLicenseUpgrade : 1; + ULONG fSecureLicensing : 1; + ULONG fEnableTimeZoneRedirection : 1; + ULONG fDisableAutoReconnect : 1; + ULONG fDisableForcibleLogoff : 1; + ULONG fPolicyEncryptRPCTraffic : 1; + ULONG fEncryptRPCTraffic : 1; + ULONG fErrorInvalidProfile : 1; + ULONG fPolicyFallbackPrintDriver : 1; + ULONG FallbackPrintDriverType : 3; + ULONG fDisableTerminalServerTooltip : 1; + BYTE bSecurityLayer; + ULONG fPolicySecurityLayer : 1; + BYTE bUserAuthentication; + ULONG fPolicyUserAuthentication : 1; + ULONG fPolicyTurnOffSingleAppMode : 1; + ULONG fTurnOffSingleAppMode : 1; + ULONG fDisablePNPPolicyIsEnfored : 1; + ULONG fDisablePNPPolicyValue : 1; + ULONG MaxInstanceCount; + ULONG LicensingMode; + BYTE MinEncryptionLevel; + WCHAR WFProfilePath[DIRECTORY_LENGTH + 1]; + WCHAR WFHomeDir[DIRECTORY_LENGTH + 1]; + WCHAR WFHomeDirDrive[4]; + ULONG SessionDirectoryActive; + WCHAR SessionDirectoryLocation[DIRECTORY_LENGTH + 1]; + WCHAR SessionDirectoryClusterName[DIRECTORY_LENGTH + 1]; + WCHAR SessionDirectoryAdditionalParams[DIRECTORY_LENGTH + 1]; + ULONG SessionDirectoryExposeServerIP; + ULONG KeepAliveInterval; + SHADOWCLASS Shadow; + ULONG MaxConnectionTime; + ULONG MaxDisconnectionTime; + ULONG MaxIdleTime; + WCHAR WorkDirectory[DIRECTORY_LENGTH + 1]; + WCHAR InitialProgram[INITIALPROGRAM_LENGTH + 1]; + WCHAR LicenseServers[MAX_LICENSE_SERVER_LENGTH + 1]; +} POLICY_TS_MACHINE, *PPOLICY_TS_MACHINE; + +/* +* User Configuration data +*/ + +typedef struct _USERCONFIG { + /* if flag is set inherit parameter from user or client configuration */ + ULONG fInheritAutoLogon : 1; + ULONG fInheritResetBroken : 1; + ULONG fInheritReconnectSame : 1; + ULONG fInheritInitialProgram : 1; + ULONG fInheritCallback : 1; + ULONG fInheritCallbackNumber : 1; + ULONG fInheritShadow : 1; + ULONG fInheritMaxSessionTime : 1; + ULONG fInheritMaxDisconnectionTime : 1; + ULONG fInheritMaxIdleTime : 1; + ULONG fInheritAutoClient : 1; + ULONG fInheritSecurity : 1; + ULONG fPromptForPassword : 1; + ULONG fResetBroken : 1; + ULONG fReconnectSame : 1; + ULONG fLogonDisabled : 1; + ULONG fWallPaperDisabled : 1; + ULONG fAutoClientDrives : 1; + ULONG fAutoClientLpts : 1; + ULONG fForceClientLptDef : 1; + ULONG fRequireEncryption : 1; + ULONG fDisableEncryption : 1; + ULONG fUnused1 : 1; + ULONG fHomeDirectoryMapRoot : 1; + ULONG fUseDefaultGina : 1; + ULONG fCursorBlinkDisabled : 1; + ULONG fPublishedApp : 1; + ULONG fHideTitleBar : 1; + ULONG fMaximize : 1; + ULONG fDisableCpm : 1; + ULONG fDisableCdm : 1; + ULONG fDisableCcm : 1; + ULONG fDisableLPT : 1; + ULONG fDisableClip : 1; + ULONG fDisableExe : 1; + ULONG fDisableCam : 1; + ULONG fDisableAutoReconnect : 1; + ULONG ColorDepth : 3; + ULONG fInheritColorDepth : 1; + ULONG fErrorInvalidProfile : 1; + ULONG fPasswordIsScPin : 1; + ULONG fDisablePNPRedir : 1; + WCHAR UserName[USERNAME_LENGTH + 1]; + WCHAR Domain[DOMAIN_LENGTH + 1]; + WCHAR Password[PASSWORD_LENGTH + 1]; + WCHAR WorkDirectory[DIRECTORY_LENGTH + 1]; + WCHAR InitialProgram[INITIALPROGRAM_LENGTH + 1]; + WCHAR CallbackNumber[CALLBACK_LENGTH + 1]; + CALLBACKCLASS Callback; + SHADOWCLASS Shadow; + ULONG MaxConnectionTime; + ULONG MaxDisconnectionTime; + ULONG MaxIdleTime; + ULONG KeyboardLayout; + BYTE MinEncryptionLevel; + WCHAR NWLogonServer[NASIFILESERVER_LENGTH + 1]; + APPLICATIONNAME PublishedName; + WCHAR WFProfilePath[DIRECTORY_LENGTH + 1]; + WCHAR WFHomeDir[DIRECTORY_LENGTH + 1]; + WCHAR WFHomeDirDrive[4]; +} USERCONFIG, * PUSERCONFIG; + +/****************** +* PD structures +******************/ + +typedef struct _PDCONFIG2 { + PDNAME PdName; + SDCLASS SdClass; + DLLNAME PdDLL; + ULONG PdFlag; + ULONG OutBufLength; + ULONG OutBufCount; + ULONG OutBufDelay; + ULONG InteractiveDelay; + ULONG PortNumber; + ULONG KeepAliveTimeout; +} PDCONFIG2, * PPDCONFIG2; + +/* +* PdFlag defines +*/ + +#define PD_UNUSED 0x00000001 +#define PD_RELIABLE 0x00000002 +#define PD_FRAME 0x00000004 +#define PD_CONNECTION 0x00000008 +#define PD_CONSOLE 0x00000010 +#define PD_LANA 0x00000020 +#define PD_TRANSPORT 0x00000040 +#define PD_SINGLE_INST 0x00000080 +#define PD_NOLOW_WATERMARK 0x00000100 + +/*------------------------------------------------*/ +typedef enum _RECEIVEFLOWCONTROLCLASS { + ReceiveFlowControl_None, + ReceiveFlowControl_RTS, + ReceiveFlowControl_DTR, +} RECEIVEFLOWCONTROLCLASS; + +typedef enum _TRANSMITFLOWCONTROLCLASS { + TransmitFlowControl_None, + TransmitFlowControl_CTS, + TransmitFlowControl_DSR, +} TRANSMITFLOWCONTROLCLASS; + +typedef struct _FLOWCONTROLCONFIG { + ULONG fEnableSoftwareTx : 1; + ULONG fEnableSoftwareRx : 1; + ULONG fEnableDTR : 1; + ULONG fEnableRTS : 1; + CHAR XonChar; + CHAR XoffChar; + FLOWCONTROLCLASS Type; + RECEIVEFLOWCONTROLCLASS HardwareReceive; + TRANSMITFLOWCONTROLCLASS HardwareTransmit; +} FLOWCONTROLCONFIG, * PFLOWCONTROLCONFIG; + +typedef enum _ASYNCCONNECTCLASS { + Connect_CTS, + Connect_DSR, + Connect_RI, + Connect_DCD, + Connect_FirstChar, + Connect_Perm, +} ASYNCCONNECTCLASS; + +typedef struct _CONNECTCONFIG { + ASYNCCONNECTCLASS Type; + ULONG fEnableBreakDisconnect : 1; +} CONNECTCONFIG, * PCONNECTCONFIG; +/*------------------------------------------------*/ + +typedef struct _ASYNCCONFIG { + DEVICENAME DeviceName; + MODEMNAME ModemName; + ULONG BaudRate; + ULONG Parity; + ULONG StopBits; + ULONG ByteSize; + ULONG fEnableDsrSensitivity : 1; + ULONG fConnectionDriver : 1; + FLOWCONTROLCONFIG FlowControl; + CONNECTCONFIG Connect; +} ASYNCCONFIG, * PASYNCCONFIG; + +/*------------------------------------------------*/ + +typedef struct _NETWORKCONFIG { + LONG LanAdapter; + DEVICENAME NetworkName; + ULONG Flags; +} NETWORKCONFIG, * PNETWORKCONFIG; + +/*------------------------------------------------*/ + +typedef struct _NASICONFIG { + NASISPECIFICNAME SpecificName; + NASIUSERNAME UserName; + NASIPASSWORD PassWord; + NASISESIONNAME SessionName; + NASIFILESERVER FileServer; + BOOLEAN GlobalSession; +} NASICONFIG, * PNASICONFIG; + +/*------------------------------------------------*/ + +typedef struct _OEMTDCONFIG { + LONG Adapter; + DEVICENAME DeviceName; + ULONG Flags; +} OEMTDCONFIG, * POEMTDCONFIG; + +/*------------------------------------------------*/ + +typedef struct _PDPARAMS { + SDCLASS SdClass; + union { + NETWORKCONFIG Network; + ASYNCCONFIG Async; + NASICONFIG Nasi; + OEMTDCONFIG OemTd; + }; +} PDPARAMS, * PPDPARAMS; + +/*------------------------------------------------*/ + +typedef struct _PDCONFIG { + PDCONFIG2 Create; + PDPARAMS Params; +} PDCONFIG, * PPDCONFIG; + +/*********************** +* Wd structures +***********************/ + +typedef struct _WDCONFIG { + WDNAME WdName; + DLLNAME WdDLL; + DLLNAME WsxDLL; + ULONG WdFlag; + ULONG WdInputBufferLength; + DLLNAME CfgDLL; + WDPREFIX WdPrefix; +} WDCONFIG, * PWDCONFIG; + +/* +* WdFlag defines +*/ + +#define WDF_UNUSED 0x00000001 +#define WDF_SHADOW_SOURCE 0x00000002 +#define WDF_SHADOW_TARGET 0x00000004 +#define WDF_OTHER 0x00000008 +#define WDF_TSHARE 0x00000010 +#define WDF_DYNAMIC_RECONNECT 0x00000020 +#define WDF_USER_VCIOCTL 0x00000040 +#define WDF_SUBDESKTOP 0x00008000 + +/************************************** +* Connection Driver structures (CD) +**************************************/ + +/* +* connection driver classes +*/ + +typedef enum _CDCLASS { + CdNone, + CdModem, + CdClass_Maximum, +} CDCLASS; + +/*------------------------------------------------*/ + +typedef struct _CDCONFIG { + CDCLASS CdClass; + CDNAME CdName; + DLLNAME CdDLL; + ULONG CdFlag; +} CDCONFIG, * PCDCONFIG; + +/***************************** +* Window Station structures +*****************************/ + +typedef struct _WINSTATIONCREATE { + ULONG fEnableWinStation : 1; + ULONG MaxInstanceCount; +} WINSTATIONCREATE, * PWINSTATIONCREATE; + +/*------------------------------------------------*/ + +typedef struct _WINSTATIONCONFIG { + WCHAR Comment[WINSTATIONCOMMENT_LENGTH + 1]; + USERCONFIG User; + char OEMId[4]; +} WINSTATIONCONFIG, * PWINSTATIONCONFIG; + +/*------------------------------------------------*/ + +typedef enum _SessionType { + SESSIONTYPE_UNKNOWN = 0, + SESSIONTYPE_SERVICES, + SESSIONTYPE_LISTENER, + SESSIONTYPE_REGULARDESKTOP, + SESSIONTYPE_ALTERNATESHELL, + SESSIONTYPE_REMOTEAPP, + SESSIONTYPE_MEDIACENTEREXT +} SESSIONTYPE; + +/*------------------------------------------------*/ + +#define EXECSRVPIPENAMELEN 48 + +typedef enum _WINSTATIONINFOCLASS { + WinStationCreateData, + WinStationConfiguration, + WinStationPdParams, + WinStationWd, + WinStationPd, + WinStationPrinter, + WinStationClient, + WinStationModules, + WinStationInformation, + WinStationTrace, + WinStationBeep, + WinStationEncryptionOff, + WinStationEncryptionPerm, + WinStationNtSecurity, + WinStationUserToken, + WinStationUnused1, + WinStationVideoData, + WinStationInitialProgram, + WinStationCd, + WinStationSystemTrace, + WinStationVirtualData, + WinStationClientData, + WinStationSecureDesktopEnter, + WinStationSecureDesktopExit, + WinStationLoadBalanceSessionTarget, + WinStationLoadIndicator, + WinStationShadowInfo, + WinStationDigProductId, + WinStationLockedState, + WinStationRemoteAddress, + WinStationIdleTime, + WinStationLastReconnectType, + WinStationDisallowAutoReconnect, + WinStationUnused2, + WinStationUnused3, + WinStationUnused4, + WinStationUnused5, + WinStationReconnectedFromId, + WinStationEffectsPolicy, + WinStationType, + WinStationInformationEx +} WINSTATIONINFOCLASS; + +/*------------------------------------------------*/ + +typedef struct _WINSTATIONCLIENTDATA { + CLIENTDATANAME DataName; + BOOLEAN fUnicodeData; + /* BYTE Data[1]; Variable length data follows */ +} WINSTATIONCLIENTDATA, * PWINSTATIONCLIENTDATA; + +/*------------------------------------------------*/ + +typedef struct _WINSTATIONUSERTOKEN { + HANDLE ProcessId; + HANDLE ThreadId; + HANDLE UserToken; +} WINSTATIONUSERTOKEN, * PWINSTATIONUSERTOKEN; + +/*------------------------------------------------*/ + +typedef struct _WINSTATIONVIDEODATA { + USHORT HResolution; + USHORT VResolution; + USHORT fColorDepth; +} WINSTATIONVIDEODATA, *PWINSTATIONVIDEODATA; + +/*----------------------------------------------*/ + +typedef struct _WINSTATIONCONFIG2 { + WINSTATIONCREATE Create; + PDCONFIG Pd[MAX_PDCONFIG]; + WDCONFIG Wd; + CDCONFIG Cd; + WINSTATIONCONFIG Config; +} WINSTATIONCONFIG2, * PWINSTATIONCONFIG2; + +/* +* WinStation client data structure +*/ + +typedef struct _WINSTATIONCLIENT { + ULONG fTextOnly : 1; + ULONG fDisableCtrlAltDel : 1; + ULONG fMouse : 1; + ULONG fDoubleClickDetect : 1; + ULONG fINetClient : 1; + ULONG fPromptForPassword : 1; + ULONG fMaximizeShell : 1; + ULONG fEnableWindowsKey : 1; + ULONG fRemoteConsoleAudio : 1; + ULONG fPasswordIsScPin : 1; + ULONG fNoAudioPlayback : 1; + ULONG fUsingSavedCreds : 1; + ULONG fRestrictedLogon : 1; + WCHAR ClientName[CLIENTNAME_LENGTH + 1]; + WCHAR Domain[DOMAIN_LENGTH + 1]; + WCHAR UserName[USERNAME_LENGTH + 1]; + WCHAR Password[PASSWORD_LENGTH + 1]; + WCHAR WorkDirectory[DIRECTORY_LENGTH + 1]; + WCHAR InitialProgram[INITIALPROGRAM_LENGTH + 1]; + ULONG SerialNumber; + BYTE EncryptionLevel; + ULONG ClientAddressFamily; + WCHAR ClientAddress[CLIENTADDRESS_LENGTH + 1]; + USHORT HRes; + USHORT VRes; + USHORT ColorDepth; + USHORT ProtocolType; + ULONG KeyboardLayout; + ULONG KeyboardType; + ULONG KeyboardSubType; + ULONG KeyboardFunctionKey; + WCHAR imeFileName[IMEFILENAME_LENGTH + 1]; + WCHAR ClientDirectory[DIRECTORY_LENGTH + 1]; + WCHAR ClientLicense[CLIENTLICENSE_LENGTH + 1]; + WCHAR ClientModem[CLIENTMODEM_LENGTH + 1]; + ULONG ClientBuildNumber; + ULONG ClientHardwareId; + USHORT ClientProductId; + USHORT OutBufCountHost; + USHORT OutBufCountClient; + USHORT OutBufLength; + WCHAR AudioDriverName[9]; + TS_TIME_ZONE_INFORMATION ClientTimeZone; + ULONG ClientSessionId; + WCHAR clientDigProductId[CLIENT_PRODUCT_ID_LENGTH]; + ULONG PerformanceFlags; + ULONG ActiveInputLocale; +} WINSTATIONCLIENT, * PWINSTATIONCLIENT; + +/* +* T.Share specific protocol performance counters +*/ + +typedef struct _TSHARE_COUNTERS { + ULONG Reserved; +} TSHARE_COUNTERS, * PTSHARE_COUNTERS; + +/* +* WinStation protocol performance counters +*/ + +typedef struct _PROTOCOLCOUNTERS { + ULONG WdBytes; + ULONG WdFrames; + ULONG WaitForOutBuf; + ULONG Frames; + ULONG Bytes; + ULONG CompressedBytes; + ULONG CompressFlushes; + ULONG Errors; + ULONG Timeouts; + ULONG AsyncFramingError; + ULONG AsyncOverrunError; + ULONG AsyncOverflowError; + ULONG AsyncParityError; + ULONG TdErrors; + USHORT ProtocolType; + USHORT Length; + union { + TSHARE_COUNTERS TShareCounters; + ULONG Reserved[100]; + } Specific; +} PROTOCOLCOUNTERS, * PPROTOCOLCOUNTERS; + +/* +* ThinWire cache statistics +*/ + +typedef struct _THINWIRECACHE { + ULONG CacheReads; + ULONG CacheHits; +} THINWIRECACHE, * PTHINWIRECACHE; +#define MAX_THINWIRECACHE 4 + + +typedef struct _RESERVED_CACHE { + THINWIRECACHE ThinWireCache[MAX_THINWIRECACHE]; +} RESERVED_CACHE, * PRESERVED_CACHE; + +/* +* T.Share specific cache statistics +*/ + +typedef struct _TSHARE_CACHE { + ULONG Reserved; +} TSHARE_CACHE, * PTSHARE_CACHE; + +/* +* WinStation cache statistics +*/ + +typedef struct CACHE_STATISTICS { + USHORT ProtocolType; + USHORT Length; + union { + RESERVED_CACHE ReservedCacheStats; + TSHARE_CACHE TShareCacheStats; + ULONG Reserved[20]; + } Specific; +} CACHE_STATISTICS, * PCACHE_STATISTICS; + +/* +* WinStation protocol status +*/ + +typedef struct _PROTOCOLSTATUS { + PROTOCOLCOUNTERS Output; + PROTOCOLCOUNTERS Input; + CACHE_STATISTICS Cache; + ULONG AsyncSignal; + ULONG AsyncSignalMask; +} PROTOCOLSTATUS, * PPROTOCOLSTATUS; + +#ifdef __cplusplus +typedef struct _PROTOCOLSTATUSEX : PROTOCOLSTATUS { +#else +typedef struct _PROTOCOLSTATUSEX { + PROTOCOLSTATUS; +#endif + LARGE_INTEGER Counters[MAX_COUNTER_EXTENSIONS]; +} PROTOCOLSTATUSEX, *PPROTOCOLSTATUSEX; + +/* +* WinStation query information +*/ + +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; +} WINSTATIONINFORMATION, * PWINSTATIONINFORMATION; + +/* +* Load balancing data types +*/ + +typedef enum _LOADFACTORTYPE { + ErrorConstraint, + PagedPoolConstraint, + NonPagedPoolConstraint, + AvailablePagesConstraint, + SystemPtesConstraint, + CPUConstraint +} LOADFACTORTYPE; + +typedef struct _WINSTATIONLOADINDICATORDATA { + ULONG RemainingSessionCapacity; + LOADFACTORTYPE LoadFactor; + ULONG TotalSessions; + ULONG DisconnectedSessions; + LARGE_INTEGER IdleCPU; + LARGE_INTEGER TotalCPU; + ULONG RawSessionCapacity; + ULONG reserved[9]; +} WINSTATIONLOADINDICATORDATA, * PWINSTATIONLOADINDICATORDATA; + +/* +* WinStation shadow states +*/ + +typedef enum _SHADOWSTATECLASS { + State_NoShadow, + State_Shadowing, + State_Shadowed, +} SHADOWSTATECLASS; + +/* +* Shadow query/set information +*/ + +typedef struct _WINSTATIONSHADOW { + SHADOWSTATECLASS ShadowState; + SHADOWCLASS ShadowClass; + ULONG SessionId; + ULONG ProtocolType; +} WINSTATIONSHADOW, * PWINSTATIONSHADOW; + +typedef struct _WINSTATIONPRODID { + WCHAR DigProductId[CLIENT_PRODUCT_ID_LENGTH]; + WCHAR ClientDigProductId[CLIENT_PRODUCT_ID_LENGTH]; + WCHAR OuterMostDigProductId[CLIENT_PRODUCT_ID_LENGTH]; + ULONG curentSessionId; + ULONG ClientSessionId; + ULONG OuterMostSessionId; +}WINSTATIONPRODID, *PWINSTATIONPRODID; + +typedef struct { + unsigned short sin_family; + union { + struct { + USHORT sin_port; + ULONG in_addr; + UCHAR sin_zero[8]; + } ipv4; + struct { + USHORT sin6_port; + ULONG sin6_flowinfo; + USHORT sin6_addr[8]; + ULONG sin6_scope_id; + } ipv6; + }; +} WINSTATIONREMOTEADDRESS, *PWINSTATIONREMOTEADDRESS; + +#define DEFAULT_POLICY_ID 1 +#define PERSEAT_POLICY_ID 2 +#define INTCONN_POLICY_ID 3 +#define PERUSER_POLICY_ID 4 +#define POLICY_NOT_CONFIGURED 5 +#define MAXIMUM_POLICY_ID 6 + +/*------------------------------------------------*/ + +typedef struct _BEEPINPUT { + ULONG uType; +} BEEPINPUT, * PBEEPINPUT; + +/********************** +* NWLogon Structure +**********************/ + +#define IDTIMEOUT 32000 +#define IDASYNC 32001 +#define WSD_LOGOFF 0x00000001 +#define WSD_SHUTDOWN 0x00000002 +#define WSD_REBOOT 0x00000004 +#define WSD_POWEROFF 0x00000008 +#define WSD_FASTREBOOT 0x00000010 + +#define WTS_CONSOLE_CONNECT 0x1 +#define WTS_CONSOLE_DISCONNECT 0x2 +#define WTS_REMOTE_CONNECT 0x3 +#define WTS_REMOTE_DISCONNECT 0x4 +#define WTS_SESSION_LOGON 0x5 +#define WTS_SESSION_LOGOFF 0x6 +#define WTS_SESSION_LOCK 0x7 +#define WTS_SESSION_UNLOCK 0x8 +#define WTS_SESSION_REMOTE_CONTROL 0x9 + +#define CREATE_MASK(__bit) (1 << (__bit -1) ) +#define WTS_CONSOLE_CONNECT_MASK CREATE_MASK( WTS_CONSOLE_CONNECT ) +#define WTS_CONSOLE_DISCONNECT_MASK CREATE_MASK( WTS_CONSOLE_DISCONNECT ) +#define WTS_REMOTE_CONNECT_MASK CREATE_MASK( WTS_REMOTE_CONNECT ) +#define WTS_REMOTE_DISCONNECT_MASK CREATE_MASK( WTS_REMOTE_DISCONNECT ) +#define WTS_SESSION_LOGON_MASK CREATE_MASK( WTS_SESSION_LOGON ) +#define WTS_SESSION_LOGOFF_MASK CREATE_MASK( WTS_SESSION_LOGOFF ) +#define WTS_SESSION_LOCK_MASK CREATE_MASK( WTS_SESSION_LOCK ) +#define WTS_SESSION_UNLOCK_MASK CREATE_MASK( WTS_SESSION_UNLOCK ) +#define WTS_SESSION_REMOTE_CONTROL_MASK CREATE_MASK( WTS_SESSION_REMOTE_CONTROL ) +#define WTS_ALL_NOTIFICATION_MASK 0xFFFFFFFF + + +typedef struct _SESSIONID { + union { + ULONG SessionId; + ULONG LogonId; + } _SessionId_LogonId_union; + WINSTATIONNAME WinStationName; + WINSTATIONSTATECLASS State; +} SESSIONID, *PSESSIONID; + + +#define LOGINID SESSIONID +#define PLOGINID PSESSIONID + + +#define TS_USER_AUTHENTICATION_NONE 0 +#define TS_USER_AUTHENTICATION_VIA_HYBRID 1 +#define TS_USER_AUTHENTICATION_VIA_SSL 2 +#define TS_USER_AUTHENTICATION_DEFAULT TS_USER_AUTHENTICATION_NONE + +typedef struct _VARDATA_WIRE { + USHORT Size; + USHORT Offset; +} VARDATA_WIRE, *PVARDATA_WIRE; + +typedef struct _PDPARAMSWIRE { + SDCLASS SdClass; + VARDATA_WIRE SdClassSpecific; +} PDPARAMSWIRE, *PPDPARAMSWIRE; + +typedef struct _WINSTACONFIGWIRE { + WCHAR Comment[61]; + char OEMId[4]; + VARDATA_WIRE UserConfig; + VARDATA_WIRE NewFields; +} WINSTACONFIGWIRE, *PWINSTACONFIGWIRE; + +#define PRODUCTINFO_COMPANYNAME_LENGTH 256 +#define PRODUCTINFO_PRODUCTID_LENGTH 4 + +typedef struct _WINSTATIONPRODUCTINFO { + WCHAR CompanyName[PRODUCTINFO_COMPANYNAME_LENGTH]; + WCHAR ProductID[PRODUCTINFO_PRODUCTID_LENGTH]; +} WINSTATIONPRODUCTINFO, *PWINSTATIONPRODUCTINFO; + +#define VALIDATIONINFORMATION_LICENSE_LENGTH 16384 +#define VALIDATIONINFORMATION_HARDWAREID_LENGTH 20 + +typedef struct _WINSTATIONVALIDATIONINFORMATION { + WINSTATIONPRODUCTINFO ProductInfo; + BYTE License[VALIDATIONINFORMATION_LICENSE_LENGTH]; + ULONG LicenseLength; + BYTE HardwareID[VALIDATIONINFORMATION_HARDWAREID_LENGTH]; + ULONG HardwareIDLength; +} WINSTATIONVALIDATIONINFORMATION, *PWINSTATIONVALIDATIONINFORMATION; diff --git a/Source/KNSoft.NDK.nuspec b/Source/KNSoft.NDK.nuspec new file mode 100644 index 0000000..3190882 --- /dev/null +++ b/Source/KNSoft.NDK.nuspec @@ -0,0 +1,26 @@ + + + + KNSoft.NDK + 1.0.7-beta + KNSoft.NDK + KNSoft + https://github.com/KNSoft/KNSoft.NDK + true + MIT + https://licenses.nuget.org/MIT + README.md + KNSoft.NDK provides native C/C++ definitions and import libraries for Windows NT and some specifications. + windows utility native + + + + + + + + + + + + \ No newline at end of file diff --git a/Source/KNSoft.NDK.sln b/Source/KNSoft.NDK.sln new file mode 100644 index 0000000..b2bab29 --- /dev/null +++ b/Source/KNSoft.NDK.sln @@ -0,0 +1,54 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 17 +VisualStudioVersion = 17.9.34714.143 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "KNSoft.NDK", "KNSoft.NDK\KNSoft.NDK.vcxproj", "{1A6001A4-2E81-4CFB-86F3-E1FE1B4A5991}" +EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Test", "Test\Test.vcxproj", "{E4BBF3A5-9277-48A9-94E6-3F15F740655D}" + ProjectSection(ProjectDependencies) = postProject + {1A6001A4-2E81-4CFB-86F3-E1FE1B4A5991} = {1A6001A4-2E81-4CFB-86F3-E1FE1B4A5991} + EndProjectSection +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|ARM64 = Debug|ARM64 + Debug|x64 = Debug|x64 + Debug|x86 = Debug|x86 + Release|ARM64 = Release|ARM64 + Release|x64 = Release|x64 + Release|x86 = Release|x86 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {1A6001A4-2E81-4CFB-86F3-E1FE1B4A5991}.Debug|ARM64.ActiveCfg = Release|ARM64 + {1A6001A4-2E81-4CFB-86F3-E1FE1B4A5991}.Debug|ARM64.Build.0 = Release|ARM64 + {1A6001A4-2E81-4CFB-86F3-E1FE1B4A5991}.Debug|x64.ActiveCfg = Release|x64 + {1A6001A4-2E81-4CFB-86F3-E1FE1B4A5991}.Debug|x64.Build.0 = Release|x64 + {1A6001A4-2E81-4CFB-86F3-E1FE1B4A5991}.Debug|x86.ActiveCfg = Release|Win32 + {1A6001A4-2E81-4CFB-86F3-E1FE1B4A5991}.Debug|x86.Build.0 = Release|Win32 + {1A6001A4-2E81-4CFB-86F3-E1FE1B4A5991}.Release|ARM64.ActiveCfg = Release|ARM64 + {1A6001A4-2E81-4CFB-86F3-E1FE1B4A5991}.Release|ARM64.Build.0 = Release|ARM64 + {1A6001A4-2E81-4CFB-86F3-E1FE1B4A5991}.Release|x64.ActiveCfg = Release|x64 + {1A6001A4-2E81-4CFB-86F3-E1FE1B4A5991}.Release|x64.Build.0 = Release|x64 + {1A6001A4-2E81-4CFB-86F3-E1FE1B4A5991}.Release|x86.ActiveCfg = Release|Win32 + {1A6001A4-2E81-4CFB-86F3-E1FE1B4A5991}.Release|x86.Build.0 = Release|Win32 + {E4BBF3A5-9277-48A9-94E6-3F15F740655D}.Debug|ARM64.ActiveCfg = Debug|ARM64 + {E4BBF3A5-9277-48A9-94E6-3F15F740655D}.Debug|ARM64.Build.0 = Debug|ARM64 + {E4BBF3A5-9277-48A9-94E6-3F15F740655D}.Debug|x64.ActiveCfg = Debug|x64 + {E4BBF3A5-9277-48A9-94E6-3F15F740655D}.Debug|x64.Build.0 = Debug|x64 + {E4BBF3A5-9277-48A9-94E6-3F15F740655D}.Debug|x86.ActiveCfg = Debug|Win32 + {E4BBF3A5-9277-48A9-94E6-3F15F740655D}.Debug|x86.Build.0 = Debug|Win32 + {E4BBF3A5-9277-48A9-94E6-3F15F740655D}.Release|ARM64.ActiveCfg = Release|ARM64 + {E4BBF3A5-9277-48A9-94E6-3F15F740655D}.Release|ARM64.Build.0 = Release|ARM64 + {E4BBF3A5-9277-48A9-94E6-3F15F740655D}.Release|x64.ActiveCfg = Release|x64 + {E4BBF3A5-9277-48A9-94E6-3F15F740655D}.Release|x64.Build.0 = Release|x64 + {E4BBF3A5-9277-48A9-94E6-3F15F740655D}.Release|x86.ActiveCfg = Release|Win32 + {E4BBF3A5-9277-48A9-94E6-3F15F740655D}.Release|x86.Build.0 = Release|Win32 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {3236945A-A827-4F1D-9A11-C008E11D0DD3} + EndGlobalSection +EndGlobal diff --git a/Source/KNSoft.NDK.targets b/Source/KNSoft.NDK.targets new file mode 100644 index 0000000..0a30777 --- /dev/null +++ b/Source/KNSoft.NDK.targets @@ -0,0 +1,12 @@ + + + + $(MSBuildThisFileDirectory)Include;$(IncludePath) + $(MSBuildThisFileDirectory)Lib\$(PlatformTarget);$(LibraryPath) + + + + ntdll.lib;%(AdditionalDependencies) + + + diff --git a/Source/KNSoft.NDK/KNSoft.NDK.vcxproj b/Source/KNSoft.NDK/KNSoft.NDK.vcxproj new file mode 100644 index 0000000..39eaef1 --- /dev/null +++ b/Source/KNSoft.NDK/KNSoft.NDK.vcxproj @@ -0,0 +1,203 @@ + + + + + + Release + ARM64 + + + Release + Win32 + + + Release + x64 + + + + 17.0 + Win32Proj + {1a6001a4-2e81-4cfb-86f3-e1fe1b4a5991} + KNSoft.NDK + 10.0 + KNSoft.NDK + + + + false + true + Utility + + + false + true + Utility + + + false + true + Utility + + + + + + + + + + + + + + + + + + $(SolutionDir)OutDir\$(PlatformTarget)\ + IntDir\$(PlatformTarget)\ + + + $(SolutionDir)OutDir\$(PlatformTarget)\ + IntDir\$(PlatformTarget)\ + + + $(SolutionDir)OutDir\$(PlatformTarget)\ + IntDir\$(PlatformTarget)\ + + + + Level3 + true + true + true + WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) + true + + + Console + true + true + true + + + + + Level3 + true + true + true + NDEBUG;_CONSOLE;%(PreprocessorDefinitions) + true + + + Console + true + true + true + + + + + Level3 + true + true + true + NDEBUG;_CONSOLE;%(PreprocessorDefinitions) + true + + + Console + true + true + true + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}. + + + + + \ No newline at end of file diff --git a/Source/KNSoft.NDK/KNSoft.NDK.vcxproj.filters b/Source/KNSoft.NDK/KNSoft.NDK.vcxproj.filters new file mode 100644 index 0000000..cf7954a --- /dev/null +++ b/Source/KNSoft.NDK/KNSoft.NDK.vcxproj.filters @@ -0,0 +1,247 @@ + + + + + {0824e6bd-fba8-4ba1-a245-1c0743fc1404} + + + {3769bb18-ab05-4c44-8684-2ff9124963ae} + + + {41be1bc2-0092-4e39-af06-05d24bcb1fcc} + + + {2e85c850-9b91-4075-b52c-19c59f8872c0} + + + {347e9f2f-faac-4fa8-b572-16ecdf28ed59} + + + {9f7bef88-765d-47ea-93a4-dbd29859e6e3} + + + {b8cf96b3-56aa-4366-920a-77b5f9d68ee9} + + + {c2d448d8-eace-41a6-a2cb-f83cd2106c72} + + + {a8b5d84e-895c-4b3c-843e-85298108c298} + + + {d3ca3df9-7369-4c3e-b850-ec66419160ca} + + + {9e058235-10a5-4f93-a060-463791f77273} + + + + + + NT + + + NT + + + NT + + + NT + + + NT\Types + + + NT\Types + + + NT\Types + + + NT\Types + + + NT\Types + + + NT\Types + + + NT\Types + + + NT\Types + + + NT\Types + + + NT\Types + + + NT\Types + + + NT\Types + + + NT\Types + + + NT\Types + + + NT\Types + + + NT\Private + + + NT\Private + + + NT\Private + + + Extension + + + Extension + + + Extension + + + Extension + + + Extension + + + Win32\Def + + + Win32\Def + + + Win32\Def + + + Win32\API + + + Win32\API + + + Win32\API + + + Win32\API + + + Win32\API + + + NT\API + + + Win32\API + + + Win32\API + + + Win32\API + + + NT\API + + + NT\API + + + NT\API + + + NT\API + + + NT\API + + + NT\API + + + NT\API + + + NT\API + + + NT\API + + + UnitTest + + + NT\API\Rtl + + + NT\API\Rtl + + + NT\API\Rtl + + + NT\API\Rtl + + + NT\API\Rtl + + + NT\API\Rtl + + + NT\API\Rtl + + + NT\API\Rtl + + + NT\API\Rtl + + + NT\API\Rtl + + + NT\PolyFill + + + NT\PolyFill + + + + + + UnitTest + + + NT\API\Rtl + + + NT\API\Rtl + + + NT\API\Rtl + + + + + Win32\API + + + Win32\API + + + \ No newline at end of file diff --git a/Source/KNSoft.NDK/WinAPI/KNSoft.NDK.Ntdll.Hash.xml b/Source/KNSoft.NDK/WinAPI/KNSoft.NDK.Ntdll.Hash.xml new file mode 100644 index 0000000..da624ad --- /dev/null +++ b/Source/KNSoft.NDK/WinAPI/KNSoft.NDK.Ntdll.Hash.xml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/Source/KNSoft.NDK/WinAPI/KNSoft.NDK.WinAPI.xml b/Source/KNSoft.NDK/WinAPI/KNSoft.NDK.WinAPI.xml new file mode 100644 index 0000000..33adc51 --- /dev/null +++ b/Source/KNSoft.NDK/WinAPI/KNSoft.NDK.WinAPI.xml @@ -0,0 +1,61 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Source/KNSoft.NDK/packages.config b/Source/KNSoft.NDK/packages.config new file mode 100644 index 0000000..196bfb0 --- /dev/null +++ b/Source/KNSoft.NDK/packages.config @@ -0,0 +1,4 @@ + + + + \ No newline at end of file diff --git a/Source/Test/Extension/MSToolChain.c b/Source/Test/Extension/MSToolChain.c new file mode 100644 index 0000000..704aa49 --- /dev/null +++ b/Source/Test/Extension/MSToolChain.c @@ -0,0 +1,26 @@ +/* + * Test for the MSToolChain.h + */ + +#include "../Test.h" + +static volatile LONG g_lInit = 0; + +static MSVC_INITIALIZER(Init1) +{ + InterlockedAdd(&g_lInit, 234); + return 0; +} + +static MSVC_INITIALIZER(Init2) +{ + InterlockedAdd(&g_lInit, 432); + return 0; +} + +static TEST_DECL(MSToolChain) +{ + TEST_OK(g_lInit == 666); +} + +_STATIC_ASSERT(TRUE); diff --git a/Source/Test/Main.c b/Source/Test/Main.c new file mode 100644 index 0000000..f68fa44 --- /dev/null +++ b/Source/Test/Main.c @@ -0,0 +1,10 @@ +#include + +#include "Test.h" + +int _cdecl wmain( + _In_ int argc, + _In_reads_(argc) _Pre_z_ wchar_t** argv) +{ + return UnitTest_Main(argc, argv); +} diff --git a/Source/Test/NT/PebLdr.c b/Source/Test/NT/PebLdr.c new file mode 100644 index 0000000..c7f645b --- /dev/null +++ b/Source/Test/NT/PebLdr.c @@ -0,0 +1,35 @@ +/* + * Test for the PEB_LDR_DATA structure definitions + */ + +#include "../Test.h" + +static TEST_DECL(PebLdrStruct) +{ + PPEB_LDR_DATA Ldr = NtCurrentPeb()->Ldr; + PLDR_DATA_TABLE_ENTRY NtdllLdrEntry; + PIMAGE_NT_HEADERS NtdllHeader; + BOOL NtdllBaseValid; + + TEST_OK(CONTAINING_RECORD(Ldr->InLoadOrderModuleList.Flink, + LDR_DATA_TABLE_ENTRY, + InLoadOrderModuleList)->DllBase == GetModuleHandleW(NULL)); + + NtdllLdrEntry = CONTAINING_RECORD(Ldr->InInitializationOrderModuleList.Flink, + LDR_DATA_TABLE_ENTRY, + InInitializationOrderModuleList); + TEST_OK(NtdllLdrEntry->EntryPoint == NULL); + + NtdllBaseValid = NtdllLdrEntry->DllBase != NULL && NtdllLdrEntry->DllBase == GetModuleHandleW(L"ntdll.dll"); + TEST_OK(NtdllBaseValid); + if (NtdllBaseValid) + { + NtdllHeader = Add2Ptr(NtdllLdrEntry->DllBase, ((PIMAGE_DOS_HEADER)(NtdllLdrEntry->DllBase))->e_lfanew); + TEST_OK(NtdllLdrEntry->SizeOfImage == NtdllHeader->OptionalHeader.SizeOfImage); + TEST_OK(NtdllLdrEntry->CheckSum == NtdllHeader->OptionalHeader.CheckSum); + TEST_OK(NtdllLdrEntry->TimeDateStamp == NtdllHeader->FileHeader.TimeDateStamp); + } else + { + TEST_SKIP("NtdllBaseValid is FALSE, skip some field tests about PE image\n"); + } +} diff --git a/Source/Test/NT/PebTebKUSD.c b/Source/Test/NT/PebTebKUSD.c new file mode 100644 index 0000000..659ec29 --- /dev/null +++ b/Source/Test/NT/PebTebKUSD.c @@ -0,0 +1,90 @@ +/* + * Test for the KNSoft.NDK PEB/TEB/KUSER_SHARED_DATA structure definitions + */ + +#include "../Test.h" + +static TEST_DECL(PebStruct) +{ + NTSTATUS Status; + PPEB Peb = NtCurrentPeb(); + + PROCESS_BASIC_INFORMATION PBI; + Status = NtQueryInformationProcess(NtCurrentProcess(), + ProcessBasicInformation, + &PBI, + sizeof(PBI), + NULL); + if (NT_SUCCESS(Status)) + { + TEST_OK(Peb == PBI.PebBaseAddress); + } else + { + TEST_SKIP("NtQueryInformationProcess failed with 0x%08lX, skip test for Peb\n", Status); + } + + TEST_OK(Peb->ImageBaseAddress == &__ImageBase); + TEST_OK(Peb->ProcessHeap == GetProcessHeap()); + + PIMAGE_NT_HEADERS pNtHeader = Add2Ptr(&__ImageBase, __ImageBase.e_lfanew); + TEST_OK(Peb->ImageSubsystemMajorVersion == (ULONG)pNtHeader->OptionalHeader.MajorSubsystemVersion); + TEST_OK(Peb->ImageSubsystemMinorVersion == (ULONG)pNtHeader->OptionalHeader.MinorSubsystemVersion); + + PROCESS_SESSION_INFORMATION PSI; + Status = NtQueryInformationProcess(NtCurrentProcess(), + ProcessSessionInformation, + &PSI, + sizeof(PSI), + NULL); + if (NT_SUCCESS(Status)) + { + TEST_OK(Peb->SessionId == PSI.SessionId); + } else + { + TEST_SKIP("NtQueryInformationProcess failed with 0x%08lX, skip test for Peb->SessionId\n", Status); + } +} + +static TEST_DECL(TebStruct) +{ + PTEB Teb = NtCurrentTeb(); + + TEST_OK(Teb->ProcessEnvironmentBlock == NtCurrentPeb()); + TEST_OK((ULONG_PTR)Teb->ClientId.UniqueProcess == (ULONG_PTR)GetCurrentProcessId()); + TEST_OK((ULONG_PTR)Teb->ClientId.UniqueThread == (ULONG_PTR)GetCurrentThreadId()); + + Teb->LastErrorValue = ERROR_BAD_FILE_TYPE; + TEST_OK(GetLastError() == ERROR_BAD_FILE_TYPE); + SetLastError(ERROR_INVALID_EA_NAME); + TEST_OK(Teb->LastErrorValue == ERROR_INVALID_EA_NAME); + + Teb->LastStatusValue = STATUS_NOT_IMPLEMENTED; + TEST_OK(RtlGetLastNtStatus() == STATUS_NOT_IMPLEMENTED); + RtlNtStatusToDosError(STATUS_DYNAMIC_CODE_BLOCKED); + TEST_OK(Teb->LastStatusValue == STATUS_DYNAMIC_CODE_BLOCKED); + + TEST_OK(Teb->CurrentLocale == GetThreadLocale()); + TEST_OK(Teb->HardErrorMode == GetThreadErrorMode()); +} + +static TEST_DECL(KUSDStruct) +{ + PCKUSER_SHARED_DATA KUSD = SharedUserData; + TIME_ZONE_INFORMATION TimeZoneInfo; + WCHAR NtSystemRoot[MAX_PATH]; + SYSTEM_INFO SystemInfo; + + DWORD TimeZoneId = GetTimeZoneInformation(&TimeZoneInfo); + TEST_OK(KUSD->TimeZoneId == TimeZoneId); + + if (GetWindowsDirectoryW(NtSystemRoot, ARRAYSIZE(NtSystemRoot)) > 0) + { + TEST_OK(_wcsicmp(KUSD->NtSystemRoot, NtSystemRoot) == 0); + } else + { + TEST_SKIP("GetWindowsDirectoryW failed with 0x%08lX, skip test for KUSD->NtSystemRoot\n", GetLastError()); + } + + GetNativeSystemInfo(&SystemInfo); + TEST_OK(KUSD->NativeProcessorArchitecture == SystemInfo.wProcessorArchitecture); +} diff --git a/Source/Test/StrSafe.c b/Source/Test/StrSafe.c new file mode 100644 index 0000000..9b0d7eb --- /dev/null +++ b/Source/Test/StrSafe.c @@ -0,0 +1,36 @@ +/* + * Test for the StrSafe.h + */ + +#include "Test.h" + +#include + +#define DEFINE_TEST_STRING(Name, String)\ +static const char Name##_A[] = String;\ +static const wchar_t Name##_W[] = _A2W(String); + +DEFINE_TEST_STRING(TEST_STRING1, "KNSoft.NDK StrSafe.h Test String"); +DEFINE_TEST_STRING(TEST_STRING1_PART1, "KNSoft.NDK StrSafe.h Test"); + +static TEST_DECL(StrSafeFunc) +{ + char szTempA[_countof(TEST_STRING1_A)]; + wchar_t szTempW[_countof(TEST_STRING1_W)]; + + TEST_OK(StrSafe_CchPrintfA(NULL, 0, "%hs", TEST_STRING1_A) == _STR_CCH_LEN(TEST_STRING1_A)); + TEST_OK(StrSafe_CchPrintfA(szTempA, ARRAYSIZE(szTempA), "%hs", TEST_STRING1_A) == _STR_CCH_LEN(TEST_STRING1_A)); + TEST_OK(strcmp(szTempA, TEST_STRING1_A) == 0); + TEST_OK(StrSafe_CchPrintfW(NULL, 0, L"%ls", TEST_STRING1_W) == _STR_CCH_LEN(TEST_STRING1_W)); + TEST_OK(StrSafe_CchPrintfW(szTempW, ARRAYSIZE(szTempW), L"%ls", TEST_STRING1_W) == _STR_CCH_LEN(TEST_STRING1_W)); + TEST_OK(wcscmp(szTempW, TEST_STRING1_W) == 0); + + TEST_OK(StrSafe_CchPrintfA(szTempA, ARRAYSIZE(szTempA), "%hs", TEST_STRING1_PART1_A) == _STR_CCH_LEN(TEST_STRING1_PART1_A)); + TEST_OK(strcmp(szTempA, TEST_STRING1_PART1_A) == 0); + TEST_OK(StrSafe_CchPrintfA(szTempA, ARRAYSIZE(szTempA), "%hs$", TEST_STRING1_A) == _STR_CCH_LEN(TEST_STRING1_A) + 1); + TEST_OK(strcmp(szTempA, TEST_STRING1_A) == 0); + TEST_OK(StrSafe_CchPrintfW(szTempW, ARRAYSIZE(szTempW), L"%ls", TEST_STRING1_PART1_W) == _STR_CCH_LEN(TEST_STRING1_PART1_W)); + TEST_OK(wcscmp(szTempW, TEST_STRING1_PART1_W) == 0); + TEST_OK(StrSafe_CchPrintfW(szTempW, ARRAYSIZE(szTempW), L"%ls$", TEST_STRING1_W) == _STR_CCH_LEN(TEST_STRING1_W) + 1); + TEST_OK(wcscmp(szTempW, TEST_STRING1_W) == 0); +} diff --git a/Source/Test/Test.h b/Source/Test/Test.h new file mode 100644 index 0000000..a4aefaa --- /dev/null +++ b/Source/Test/Test.h @@ -0,0 +1,8 @@ +#pragma once + +#include +#include +#include + +#pragma comment(lib, "KNSoft.NDK.Ntdll.Hash.lib") +#pragma comment(lib, "KNSoft.NDK.WinAPI.lib") diff --git a/Source/Test/Test.vcxproj b/Source/Test/Test.vcxproj new file mode 100644 index 0000000..aeb0321 --- /dev/null +++ b/Source/Test/Test.vcxproj @@ -0,0 +1,198 @@ + + + + + Debug + ARM64 + + + Debug + Win32 + + + Release + ARM64 + + + Release + Win32 + + + Debug + x64 + + + Release + x64 + + + + 17.0 + Win32Proj + {e4bbf3a5-9277-48a9-94e6-3f15f740655d} + Test + 10.0 + + + + Application + true + + + Application + false + true + + + Application + true + + + Application + true + + + Application + false + true + + + Application + false + true + + + + + + + + + + + + + + + + + + + + + + + + + + + $(SolutionDir)Include;$(IncludePath) + $(OutDir)../;$(LibraryPath) + + + $(SolutionDir)Include;$(IncludePath) + $(OutDir)../;$(LibraryPath) + + + $(SolutionDir)Include;$(IncludePath) + $(OutDir)../;$(LibraryPath) + + + $(SolutionDir)Include;$(IncludePath) + $(OutDir)../;$(LibraryPath) + + + $(SolutionDir)Include;$(IncludePath) + $(OutDir)../;$(LibraryPath) + + + $(SolutionDir)Include;$(IncludePath) + $(OutDir)../;$(LibraryPath) + + + + WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) + + + Console + true + ntdll.lib;%(AdditionalDependencies) + + + + + true + true + WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) + + + Console + true + true + true + ntdll.lib;%(AdditionalDependencies) + + + + + _DEBUG;_CONSOLE;%(PreprocessorDefinitions) + + + Console + true + ntdll.lib;%(AdditionalDependencies) + + + + + _DEBUG;_CONSOLE;%(PreprocessorDefinitions) + + + Console + true + ntdll.lib;%(AdditionalDependencies) + + + + + true + true + NDEBUG;_CONSOLE;%(PreprocessorDefinitions) + + + Console + true + true + true + ntdll.lib;%(AdditionalDependencies) + + + + + true + true + NDEBUG;_CONSOLE;%(PreprocessorDefinitions) + + + Console + true + true + true + ntdll.lib;%(AdditionalDependencies) + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Source/Test/Test.vcxproj.filters b/Source/Test/Test.vcxproj.filters new file mode 100644 index 0000000..14e97b8 --- /dev/null +++ b/Source/Test/Test.vcxproj.filters @@ -0,0 +1,28 @@ + + + + + + + NT + + + + NT + + + Extension + + + + + + + + {62d5419b-ca75-423e-b61b-b51ebb1a1c18} + + + {465796cb-eade-41ce-a5d4-197bee582c40} + + + \ No newline at end of file diff --git a/Source/Test/UnitTestFramework.c b/Source/Test/UnitTestFramework.c new file mode 100644 index 0000000..d5b33ca --- /dev/null +++ b/Source/Test/UnitTestFramework.c @@ -0,0 +1,39 @@ +/* + * Test for the KNSoft.NDK.UnitTest unit test framework itself + */ + +#include "Test.h" + +static TEST_DECL(UnitTestFramework) +{ + UNITTEST_RESULT Result; + + UnitTest_Print("The following tests verify the unit test framework itself, so fail and skip outputs are expected\n"); + + /* Totally 5 pass, 6 fail, 3 skip */ + TEST_OK(TRUE); + TEST_OK(1 == 1); + TEST_OK(1 != 2); + TEST_RESULT(Pass); + TEST_RESULT(Pass); + + TEST_OK(FALSE); + TEST_OK(1 != 1); + TEST_OK(1 == 2); + TEST_RESULT(Fail); + TEST_FAIL("Fail"); + TEST_FAIL(); + + TEST_SKIP("Skip"); + TEST_SKIP(); + TEST_RESULT(Skip); + + /* Move the result to local and verify */ + _STATIC_ASSERT(sizeof(Result) == sizeof(*TEST_PARAMETER_RESULT)); + RtlCopyMemory(&Result, TEST_PARAMETER_RESULT, sizeof(Result)); + RtlZeroMemory(TEST_PARAMETER_RESULT, sizeof(*TEST_PARAMETER_RESULT)); + + TEST_OK(Result.Pass == 5); + TEST_OK(Result.Fail == 6); + TEST_OK(Result.Skip == 3); +}