From 14660715f3d49a6b2943fb630fe1ad4b23fffe17 Mon Sep 17 00:00:00 2001 From: NotCapengeR Date: Sat, 30 Nov 2024 14:37:02 +0500 Subject: [PATCH 1/7] Added CMakeSettings.json files from Visual Studio to .gitignore --- .gitignore | 1 + 1 file changed, 1 insertion(+) diff --git a/.gitignore b/.gitignore index ec94d6a6f..5ac67f685 100644 --- a/.gitignore +++ b/.gitignore @@ -3,3 +3,4 @@ docs .vs out *.aps +/CMakeSettings.json \ No newline at end of file From 6918a8edd938b07e9377c061de981c08c56046b4 Mon Sep 17 00:00:00 2001 From: NotCapengeR Date: Sat, 30 Nov 2024 14:39:30 +0500 Subject: [PATCH 2/7] Changed the method of setting exceptions to manually adding a new entry to the LdrpInvertedFunctionTable from Ntdll: improved support for C++ and SEH exceptions; support for 32-bits images --- libpeconv/include/peconv/exceptions_parser.h | 7 +- libpeconv/src/exceptions_parser.cpp | 624 +- libpeconv/src/ntddk.h | 7792 +++++++++--------- tests/test_exceptions.cpp | 4 +- 4 files changed, 4603 insertions(+), 3824 deletions(-) diff --git a/libpeconv/include/peconv/exceptions_parser.h b/libpeconv/include/peconv/exceptions_parser.h index 4f4e2d0e5..547ef7523 100644 --- a/libpeconv/include/peconv/exceptions_parser.h +++ b/libpeconv/include/peconv/exceptions_parser.h @@ -9,12 +9,13 @@ namespace peconv { -#ifdef _WIN64 /** - Allows to activate the Exception table from the manually loaded module. Works only for 64-bit PEs. + Allows to activate the Exception table from the manually loaded module. + For 32-bits the loaded image should enable /SAFESEH linker option, + otherwise the exception handler cannot pass the RtlIsValidHandler() check + when an exception occurs */ bool setup_exceptions(IN BYTE* modulePtr, IN size_t moduleSize); -#endif }; diff --git a/libpeconv/src/exceptions_parser.cpp b/libpeconv/src/exceptions_parser.cpp index 97cf1df8f..e537e91df 100644 --- a/libpeconv/src/exceptions_parser.cpp +++ b/libpeconv/src/exceptions_parser.cpp @@ -1,60 +1,614 @@ #include "peconv/exceptions_parser.h" #include "peconv/pe_hdrs_helper.h" +#include "ntddk.h" #ifdef _DEBUG #include #endif +namespace details { +#define RTL_VERIFY_FLAGS_MAJOR_VERSION 0 +#define RTL_VERIFY_FLAGS_MINOR_VERSION 1 +#define RTL_VERIFY_FLAGS_BUILD_NUMBERS 2 +#define RTL_VERIFY_FLAGS_DEFAULT RTL_VERIFY_FLAGS_MAJOR_VERSION|RTL_VERIFY_FLAGS_MINOR_VERSION|RTL_VERIFY_FLAGS_BUILD_NUMBERS + typedef struct _SEARCH_CONTEXT { + + IN LPBYTE SearchPattern; + IN SIZE_T PatternSize; + + OUT LPBYTE Result; + SIZE_T MemoryBlockSize; + + } SEARCH_CONTEXT, * PSEARCH_CONTEXT; + typedef struct _NtVersion { + ULONG MajorVersion; + ULONG MinorVersion; + ULONG BuildNumber; + } NtVersion, * PNtVersion; + + typedef struct _RTL_INVERTED_FUNCTION_TABLE_ENTRY_64 { + PIMAGE_RUNTIME_FUNCTION_ENTRY ExceptionDirectory; + PVOID ImageBase; + ULONG ImageSize; + ULONG ExceptionDirectorySize; + } RTL_INVERTED_FUNCTION_TABLE_ENTRY_64, * PRTL_INVERTED_FUNCTION_TABLE_ENTRY_64; + typedef struct _RTL_INVERTED_FUNCTION_TABLE_64 { + ULONG Count; + ULONG MaxCount; + ULONG Epoch; + ULONG Overflow; + RTL_INVERTED_FUNCTION_TABLE_ENTRY_64 Entries[0x200]; + } RTL_INVERTED_FUNCTION_TABLE_64, * PRTL_INVERTED_FUNCTION_TABLE_64; + + // The correct data structure should be this. + // + typedef struct _RTL_INVERTED_FUNCTION_TABLE_ENTRY_WIN7_32 { + PVOID EntrySEHandlerTableEncoded; + PVOID ImageBase; + ULONG ImageSize; + ULONG SEHandlerCount; + } RTL_INVERTED_FUNCTION_TABLE_ENTRY_WIN7_32, * PRTL_INVERTED_FUNCTION_TABLE_ENTRY_WIN7_32; + typedef struct _RTL_INVERTED_FUNCTION_TABLE_WIN7_32 { + ULONG Count; + ULONG MaxCount; + ULONG Overflow; + ULONG NextEntrySEHandlerTableEncoded; + RTL_INVERTED_FUNCTION_TABLE_ENTRY_WIN7_32 Entries[0x200]; + } RTL_INVERTED_FUNCTION_TABLE_WIN7_32, * PRTL_INVERTED_FUNCTION_TABLE_WIN7_32; + #ifdef _WIN64 -bool peconv::setup_exceptions(IN BYTE* modulePtr, IN size_t moduleSize) -{ - if (moduleSize == 0) { - const DWORD img_size = peconv::get_image_size((BYTE*)modulePtr); - if (!img_size) { - return false; // invalid image + typedef _RTL_INVERTED_FUNCTION_TABLE_ENTRY_64 _RTL_INVERTED_FUNCTION_TABLE_ENTRY, RTL_INVERTED_FUNCTION_TABLE_ENTRY, * PRTL_INVERTED_FUNCTION_TABLE_ENTRY; + typedef RTL_INVERTED_FUNCTION_TABLE_64 _RTL_INVERTED_FUNCTION_TABLE, RTL_INVERTED_FUNCTION_TABLE, * PRTL_INVERTED_FUNCTION_TABLE; +#else + typedef RTL_INVERTED_FUNCTION_TABLE_WIN7_32 _RTL_INVERTED_FUNCTION_TABLE, RTL_INVERTED_FUNCTION_TABLE, * PRTL_INVERTED_FUNCTION_TABLE; + typedef _RTL_INVERTED_FUNCTION_TABLE_ENTRY_WIN7_32 _RTL_INVERTED_FUNCTION_TABLE_ENTRY, RTL_INVERTED_FUNCTION_TABLE_ENTRY, * PRTL_INVERTED_FUNCTION_TABLE_ENTRY; +#endif + + typedef struct _LDR_DDAG_NODE_WIN8 { + LIST_ENTRY Modules; //0x0 + PLDR_SERVICE_TAG_RECORD ServiceTagList; //0x10 + ULONG LoadCount; //0x18 + ULONG ReferenceCount; //0x1c + ULONG DependencyCount; //0x20 + PLDRP_CSLIST_DEPENDENT Dependencies; //0x28 + PLDRP_CSLIST_INCOMMING IncomingDependencies; //0x30 + LDR_DDAG_STATE State; //0x38 + SINGLE_LIST_ENTRY CondenseLink; //0x40 + ULONG PreorderNumber; //0x48 + ULONG LowestLink; //0x4c + } LDR_DDAG_NODE_WIN8, * PLDR_DDAG_NODE_WIN8; + + //6.2.9200 Windows 8 | 2012 RTM + typedef struct _LDR_DATA_TABLE_ENTRY_WIN8 { + LIST_ENTRY InLoadOrderLinks; //0x0 + LIST_ENTRY InMemoryOrderLinks; //0x10 + union { + LIST_ENTRY InInitializationOrderLinks; //0x20 + LIST_ENTRY InProgressLinks; //0x20 + }; + PVOID DllBase; //0x30 + PVOID EntryPoint; //0x38 + ULONG SizeOfImage; //0x40 + UNICODE_STRING FullDllName; //0x48 + UNICODE_STRING BaseDllName; //0x58 + union { + UCHAR FlagGroup[4]; //0x68 + ULONG Flags; //0x68 + struct { + ULONG PackagedBinary : 1; //0x68 + ULONG MarkedForRemoval : 1; //0x68 + ULONG ImageDll : 1; //0x68 + ULONG LoadNotificationsSent : 1; //0x68 + ULONG TelemetryEntryProcessed : 1; //0x68 + ULONG ProcessStaticImport : 1; //0x68 + ULONG InLegacyLists : 1; //0x68 + ULONG InIndexes : 1; //0x68 + ULONG ShimDll : 1; //0x68 + ULONG InExceptionTable : 1; //0x68 + ULONG ReservedFlags1 : 2; //0x68 + ULONG LoadInProgress : 1; //0x68 + ULONG ReservedFlags2 : 1; //0x68 + ULONG EntryProcessed : 1; //0x68 + ULONG ReservedFlags3 : 3; //0x68 + ULONG DontCallForThreads : 1; //0x68 + ULONG ProcessAttachCalled : 1; //0x68 + ULONG ProcessAttachFailed : 1; //0x68 + ULONG CorDeferredValidate : 1; //0x68 + ULONG CorImage : 1; //0x68 + ULONG DontRelocate : 1; //0x68 + ULONG CorILOnly : 1; //0x68 + ULONG ReservedFlags5 : 3; //0x68 + ULONG Redirected : 1; //0x68 + ULONG ReservedFlags6 : 2; //0x68 + ULONG CompatDatabaseProcessed : 1; //0x68 + }; + }; + USHORT ObsoleteLoadCount; //0x6c + USHORT TlsIndex; //0x6e + LIST_ENTRY HashLinks; //0x70 + ULONG TimeDateStamp; //0x80 + PACTIVATION_CONTEXT EntryPointActivationContext; //0x88 + PVOID PatchInformation; //0x90 + PLDR_DDAG_NODE_WIN8 DdagNode; //0x98 + LIST_ENTRY NodeModuleLink; //0xa0 + PVOID SnapContext; //0xb0 + PVOID ParentDllBase; //0xb8 + PVOID SwitchBackContext; //0xc0 + RTL_BALANCED_NODE BaseAddressIndexNode; //0xc8 + RTL_BALANCED_NODE MappingInfoIndexNode; //0xe0 + ULONGLONG OriginalBase; //0xf8 + LARGE_INTEGER LoadTime; //0x100 + ULONG BaseNameHashValue; //0x108 + LDR_DLL_LOAD_REASON LoadReason; //0x10c + } LDR_DATA_TABLE_ENTRY_WIN8, * PLDR_DATA_TABLE_ENTRY_WIN8; + + static void NTAPI RtlCurrentVersion(_Out_ PNtVersion pVersion) { + RtlGetNtVersionNumbers( + &pVersion->MajorVersion, + &pVersion->MinorVersion, + &pVersion->BuildNumber + ); + } + + static BOOL NTAPI RtlIsWindowsVersionOrGreater( + _In_ ULONG MajorVersion, + _In_ ULONG MinorVersion, + _In_ ULONG BuildNumber + ) { + NtVersion version{}; + RtlSecureZeroMemory(&version, sizeof NtVersion); + RtlCurrentVersion(&version); + if (version.MajorVersion == MajorVersion) { + if (version.MinorVersion == MinorVersion) return version.BuildNumber >= BuildNumber; + else return (version.MinorVersion > MinorVersion); } - moduleSize = img_size; + else return version.MajorVersion > MajorVersion; } - IMAGE_DATA_DIRECTORY* my_dir = peconv::get_directory_entry((const BYTE*)modulePtr, IMAGE_DIRECTORY_ENTRY_EXCEPTION); - if (!my_dir || !my_dir->VirtualAddress || !my_dir->Size) { - return false; + + static BOOL NTAPI RtlVerifyVersion( + _In_ ULONG MajorVersion, + _In_ ULONG MinorVersion, + _In_ ULONG BuildNumber, + _In_ BYTE Flags + ) { + NtVersion version{}; + RtlSecureZeroMemory(&version, sizeof NtVersion); + RtlCurrentVersion(&version); + if (version.MajorVersion == MajorVersion && + ((Flags & RTL_VERIFY_FLAGS_MINOR_VERSION) ? version.MinorVersion == MinorVersion : true) && + ((Flags & RTL_VERIFY_FLAGS_BUILD_NUMBERS) ? version.BuildNumber == BuildNumber : true))return TRUE; + return FALSE; + } +#ifndef _WIN64 + static int NTAPI RtlCaptureImageExceptionValues(PVOID BaseAddress, PDWORD SEHandlerTable, PDWORD SEHandlerCount) { + PIMAGE_LOAD_CONFIG_DIRECTORY pLoadConfigDirectory = nullptr; + PIMAGE_COR20_HEADER pCor20 = nullptr; + ULONG Size = 0; + + auto hdrs = reinterpret_cast(RtlImageNtHeader(BaseAddress)); + //check if no seh + if (hdrs->OptionalHeader.DllCharacteristics & IMAGE_DLLCHARACTERISTICS_NO_SEH) { + *SEHandlerTable = *SEHandlerCount = -1; + return 0; + } + + //get seh table and count + pLoadConfigDirectory = (decltype(pLoadConfigDirectory))RtlImageDirectoryEntryToData(BaseAddress, TRUE, IMAGE_DIRECTORY_ENTRY_LOAD_CONFIG, &Size); + if (pLoadConfigDirectory) { + if (Size == 0x40 && pLoadConfigDirectory->Size >= 0x48u) { + if (pLoadConfigDirectory->SEHandlerTable && pLoadConfigDirectory->SEHandlerCount) { + *SEHandlerTable = pLoadConfigDirectory->SEHandlerTable; + return *SEHandlerCount = pLoadConfigDirectory->SEHandlerCount; + } + } + } + + //is .net core ? + pCor20 = (decltype(pCor20))RtlImageDirectoryEntryToData(BaseAddress, TRUE, IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR, &Size); + *SEHandlerTable = *SEHandlerCount = ((pCor20 && pCor20->Flags & 1) ? -1 : 0); + return 0; } - RUNTIME_FUNCTION* exceptions_list = (RUNTIME_FUNCTION*)(my_dir->VirtualAddress + (ULONG_PTR)modulePtr); - if (!validate_ptr(modulePtr, moduleSize, exceptions_list, my_dir->Size)) { - return false; +#endif + + static __forceinline bool IsModuleUnloaded(PLDR_DATA_TABLE_ENTRY entry) { + if (RtlIsWindowsVersionOrGreater(6, 2, 0)) { // Windows 8+ + return PLDR_DATA_TABLE_ENTRY_WIN8(entry)->DdagNode->State == LdrModulesUnloaded; + } + else { + return entry->DllBase == nullptr; + } } - //validate exceptions table: - const size_t except_max_count = my_dir->Size / sizeof(RUNTIME_FUNCTION); + + static NTSTATUS NTAPI RtlFindMemoryBlockFromModuleSection( + _In_ HMODULE ModuleHandle, + _In_ LPCSTR SectionName, + _Inout_ PSEARCH_CONTEXT SearchContext) { + + NTSTATUS status = STATUS_SUCCESS; + #ifdef _DEBUG - std::cout << "[+] Found exception table of: " << std::dec << except_max_count << " entries\n"; + std::cout << "Searching in section " << SectionName << " in module " << ModuleHandle << std::endl; +#endif + + __try { + + // + // checks if no search pattern and length are provided + // + + if (!SearchContext->SearchPattern || !SearchContext->PatternSize) { + SearchContext->Result = nullptr; + SearchContext->MemoryBlockSize = 0; + status = STATUS_INVALID_PARAMETER; + __leave; + } + + if (SearchContext->Result) { + ++SearchContext->Result; + --SearchContext->MemoryBlockSize; + } + else { + + // + // if it is the first search, find the length and start address of the specified section + // + + auto headers = reinterpret_cast(RtlImageNtHeader(ModuleHandle)); + PIMAGE_SECTION_HEADER section = nullptr; + + if (headers) { + section = IMAGE_FIRST_SECTION(headers); + for (WORD i = 0; i < headers->FileHeader.NumberOfSections; ++i) { + if (!_strnicmp(SectionName, reinterpret_cast(section->Name), 8)) { + SearchContext->Result = reinterpret_cast(ModuleHandle) + section->VirtualAddress; + SearchContext->MemoryBlockSize = section->Misc.VirtualSize; + break; + } + + ++section; + } + + if (!SearchContext->Result || !SearchContext->MemoryBlockSize || SearchContext->MemoryBlockSize < SearchContext->PatternSize) { + SearchContext->Result = nullptr; + SearchContext->MemoryBlockSize = 0; + status = STATUS_NOT_FOUND; + __leave; + } + } + else { + status = STATUS_INVALID_PARAMETER_1; + __leave; + } + } + + // + // perform a linear search on the pattern + // + + LPBYTE end = SearchContext->Result + SearchContext->MemoryBlockSize - SearchContext->PatternSize; + while (SearchContext->Result <= end) { + if (RtlCompareMemory(SearchContext->SearchPattern, SearchContext->Result, SearchContext->PatternSize) == SearchContext->PatternSize) { + __leave; + } + + ++SearchContext->Result; + --SearchContext->MemoryBlockSize; + } + + // + // if the search fails, clear the output parameters + // + + SearchContext->Result = nullptr; + SearchContext->MemoryBlockSize = 0; + status = STATUS_NOT_FOUND; + } + __except (EXCEPTION_EXECUTE_HANDLER) { + status = GetExceptionCode(); + } + + return status; + } + + static NTSTATUS RtlProtectMrdata(_In_ ULONG Protect, PRTL_INVERTED_FUNCTION_TABLE mrdata) { + static PVOID MrdataBase = nullptr; + static SIZE_T size = 0; + NTSTATUS status; + PVOID tmp; + SIZE_T tmp_len; + ULONG old; + + if (!MrdataBase) { + MEMORY_BASIC_INFORMATION mbi{}; + status = NtQueryVirtualMemory(NtCurrentProcess(), mrdata, MemoryBasicInformation, &mbi, sizeof(mbi), nullptr); + if (!NT_SUCCESS(status))return status; + MrdataBase = mbi.BaseAddress; + size = mbi.RegionSize; + } + + tmp = MrdataBase; + tmp_len = size; + return NtProtectVirtualMemory(NtCurrentProcess(), &tmp, &tmp_len, Protect, &old); + } + + static PVOID RtlFindInvertedFunctionTable() { +#ifdef _WIN64 + // _RTL_INVERTED_FUNCTION_TABLE x64 +// Count +0x0 ???????? +// MaxCount +0x4 0x00000200 +// Epoch +0x8 ???????? +// OverFlow +0xc 0x00000000 +// _RTL_INVERTED_FUNCTION_TABLE_ENTRY[0] +0x10 ntdll.dll(win10) or The smallest base module +// ExceptionDirectory +0x10 ++++++++ +// ImageBase +0x18 ++++++++ +// ImageSize +0x20 ++++++++ +// ExceptionDirectorySize +0x24 ++++++++ +// _RTL_INVERTED_FUNCTION_TABLE_ENTRY[1] ... ... +// ...... + HMODULE hModule = nullptr, hNtdll = GetModuleHandleW(L"ntdll.dll"); + LPCSTR lpSectionName = ".data"; + if (!hNtdll) return nullptr; + auto NtdllHeaders = reinterpret_cast(RtlImageNtHeader(hNtdll)); + PIMAGE_NT_HEADERS ModuleHeaders = nullptr; + _RTL_INVERTED_FUNCTION_TABLE_ENTRY_64 entry{}; + PIMAGE_DATA_DIRECTORY dir = nullptr; + SEARCH_CONTEXT SearchContext{}; + SearchContext.SearchPattern = reinterpret_cast(&entry); + SearchContext.PatternSize = sizeof(entry); + RtlSecureZeroMemory(&entry, sizeof entry); + + // Windows 8 + if (RtlVerifyVersion(6, 2, 0, RTL_VERIFY_FLAGS_MAJOR_VERSION | RTL_VERIFY_FLAGS_MINOR_VERSION)) { + hModule = hNtdll; + ModuleHeaders = NtdllHeaders; + //lpSectionName = ".data"; + } + //Windows 8.1 ~ Windows 10 (11) + else if (RtlIsWindowsVersionOrGreater(6, 3, 0)) { + hModule = hNtdll; + ModuleHeaders = NtdllHeaders; + lpSectionName = ".mrdata"; + } + else { //Windows 7 and below + PLIST_ENTRY ListHead = &NtCurrentPeb()->Ldr->InLoadOrderModuleList, + ListEntry = ListHead->Flink; + PLDR_DATA_TABLE_ENTRY CurEntry = nullptr; + while (ListEntry != ListHead) { + CurEntry = CONTAINING_RECORD(ListEntry, LDR_DATA_TABLE_ENTRY, InLoadOrderLinks); + ListEntry = ListEntry->Flink; + hModule = reinterpret_cast( + hModule ? reinterpret_cast(min( + reinterpret_cast(hModule), + reinterpret_cast(CurEntry->DllBase) + )) : CurEntry->DllBase + ); + } + if (hModule) ModuleHeaders = reinterpret_cast(RtlImageNtHeader(hModule)); + } + if (!hModule || !ModuleHeaders || !hNtdll || !NtdllHeaders) return nullptr; + dir = &ModuleHeaders->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXCEPTION]; + + entry.ExceptionDirectory = dir->Size ? + reinterpret_cast( + reinterpret_cast(hModule) + dir->VirtualAddress + ) : nullptr; + entry.ImageBase = reinterpret_cast(hModule); + entry.ImageSize = ModuleHeaders->OptionalHeader.SizeOfImage; + entry.ExceptionDirectorySize = dir->Size; + + while (NT_SUCCESS(RtlFindMemoryBlockFromModuleSection(hNtdll, lpSectionName, &SearchContext))) { + auto tab = reinterpret_cast(SearchContext.Result - 0x10); + if (RtlIsWindowsVersionOrGreater(6, 2, 0) && tab->MaxCount == 0x200 && !tab->Overflow) return tab; + else if (tab->MaxCount == 0x200 && !tab->Epoch) return tab; + } + + return nullptr; +#else + // _RTL_INVERTED_FUNCTION_TABLE x86 +// Count +0x0 ???????? +// MaxCount +0x4 0x00000200 +// Overflow +0x8 0x00000000(Win7) ????????(Win10) +// NextEntrySEHandlerTableEncoded +0xc 0x00000000(Win10) ++++++++(Win7) +// _RTL_INVERTED_FUNCTION_TABLE_ENTRY[0] +0x10 ntdll.dll(win10) or The smallest base module +// ImageBase +0x10 ++++++++ +// ImageSize +0x14 ++++++++ +// SEHandlerCount +0x18 ++++++++ +// NextEntrySEHandlerTableEncoded +0x1c ++++++++(Win10) ????????(Win7) +// _RTL_INVERTED_FUNCTION_TABLE_ENTRY[1] ... ... +// ...... + HMODULE hModule = nullptr, hNtdll = GetModuleHandleW(L"ntdll.dll"); + auto NtdllHeaders = reinterpret_cast(RtlImageNtHeader(hNtdll)); + PIMAGE_NT_HEADERS ModuleHeaders = nullptr; + _RTL_INVERTED_FUNCTION_TABLE_ENTRY_WIN7_32 entry{}; + RtlSecureZeroMemory(&entry, sizeof entry); + LPCSTR lpSectionName = ".data"; + SEARCH_CONTEXT SearchContext{ + }; + SearchContext.SearchPattern = reinterpret_cast(&entry); + SearchContext.PatternSize = sizeof(entry); + PLIST_ENTRY ListHead = &NtCurrentPeb()->Ldr->InMemoryOrderModuleList, + ListEntry = ListHead->Flink; + PLDR_DATA_TABLE_ENTRY CurEntry = nullptr; + DWORD SEHTable, SEHCount; + BYTE Offset = 0x20; //sizeof(_RTL_INVERTED_FUNCTION_TABLE_ENTRY)*2 + + if (RtlIsWindowsVersionOrGreater(6, 3, 0)) lpSectionName = ".mrdata"; + else if (!RtlIsWindowsVersionOrGreater(6, 2, 0)) Offset = 0xC; + + while (ListEntry != ListHead) { + CurEntry = CONTAINING_RECORD(ListEntry, LDR_DATA_TABLE_ENTRY, InMemoryOrderLinks); + ListEntry = ListEntry->Flink; + if (IsModuleUnloaded(CurEntry)) + continue; //skip unloaded module + if (CurEntry->DllBase == hNtdll && Offset == 0x20) + continue; //Win10 skip first entry, if the base of ntdll is smallest. + + hModule = reinterpret_cast( + hModule ? reinterpret_cast(min( + reinterpret_cast(hModule), + reinterpret_cast(CurEntry->DllBase) + )) : CurEntry->DllBase + ); + } + ModuleHeaders = reinterpret_cast(RtlImageNtHeader(hModule)); + if (!hModule || !ModuleHeaders || !hNtdll || !NtdllHeaders)return nullptr; + + RtlCaptureImageExceptionValues(hModule, &SEHTable, &SEHCount); + + entry.EntrySEHandlerTableEncoded = RtlEncodeSystemPointer(reinterpret_cast(SEHTable)); + entry.ImageBase = reinterpret_cast(hModule); + entry.ImageSize = ModuleHeaders->OptionalHeader.SizeOfImage; + entry.SEHandlerCount = SEHCount; + + while (NT_SUCCESS(RtlFindMemoryBlockFromModuleSection(hNtdll, lpSectionName, &SearchContext))) { + PRTL_INVERTED_FUNCTION_TABLE_WIN7_32 tab = decltype(tab)(SearchContext.Result - Offset); + + //Note: Same memory layout for RTL_INVERTED_FUNCTION_TABLE_ENTRY in Windows 10 x86 and x64. + if (RtlIsWindowsVersionOrGreater(6, 2, 0) && tab->MaxCount == 0x200 && !tab->NextEntrySEHandlerTableEncoded) return tab; + else if (tab->MaxCount == 0x200 && !tab->Overflow) return tab; + } + return nullptr; #endif - size_t i = 0; - for (i = 0; i < except_max_count; i++) { - RUNTIME_FUNCTION next_func = exceptions_list[i]; - BYTE* start_ptr = next_func.BeginAddress + modulePtr; -#if defined(_M_AMD64) - size_t func_size = next_func.EndAddress - next_func.BeginAddress; -#elif defined(_M_ARM64) - size_t func_size = next_func.FunctionLength; + } + + static VOID RtlpInsertInvertedFunctionTable( + _In_ PRTL_INVERTED_FUNCTION_TABLE InvertedTable, + _In_ PVOID ImageBase, + _In_ ULONG SizeOfImage) { +#ifdef _WIN64 + ULONG CurrentSize = InvertedTable->Count; + PIMAGE_RUNTIME_FUNCTION_ENTRY FunctionTable = nullptr; + ULONG SizeOfTable = 0; + bool IsWin8OrGreater = RtlIsWindowsVersionOrGreater(6, 2, 0); + ULONG Index = static_cast(IsWin8OrGreater); + + if (CurrentSize != InvertedTable->MaxCount) { + if (CurrentSize != 0) { + while (Index < CurrentSize) { + if (ImageBase < InvertedTable->Entries[Index].ImageBase) break; + ++Index; + } + + + if (Index != CurrentSize) { + RtlMoveMemory(&InvertedTable->Entries[Index + 1], + &InvertedTable->Entries[Index], + (CurrentSize - Index) * sizeof(RTL_INVERTED_FUNCTION_TABLE_ENTRY)); + } + } + + FunctionTable = reinterpret_cast(RtlImageDirectoryEntryToData(ImageBase, TRUE, IMAGE_DIRECTORY_ENTRY_EXCEPTION, &SizeOfTable)); + InvertedTable->Entries[Index].ExceptionDirectory = FunctionTable; + InvertedTable->Entries[Index].ImageBase = ImageBase; + InvertedTable->Entries[Index].ImageSize = SizeOfImage; + InvertedTable->Entries[Index].ExceptionDirectorySize = SizeOfTable; + InvertedTable->Count++; +#ifdef _DEBUG + std::cout << "Exception table was set! " << std::endl; #endif - if (!validate_ptr(modulePtr, moduleSize, start_ptr, func_size)) { - break; } + else { + IsWin8OrGreater ? (InvertedTable->Overflow = TRUE) : (InvertedTable->Epoch = TRUE); + } + +#else + DWORD ptr = 0, count = 0; + bool IsWin8OrGreater = RtlIsWindowsVersionOrGreater(6, 2, 0); + ULONG Index = IsWin8OrGreater ? 1 : 0; + + if (InvertedTable->Count == InvertedTable->MaxCount) { + if (IsWin8OrGreater)InvertedTable->NextEntrySEHandlerTableEncoded = TRUE; + else InvertedTable->Overflow = TRUE; + return; + } + while (Index < InvertedTable->Count) { + if (ImageBase < (IsWin8OrGreater ? + (reinterpret_cast(&InvertedTable->Entries[Index]))->ImageBase : + InvertedTable->Entries[Index].ImageBase)) + break; + Index++; + } + if (Index != InvertedTable->Count) { + if (IsWin8OrGreater) { + RtlMoveMemory(&InvertedTable->Entries[Index + 1], &InvertedTable->Entries[Index], + (InvertedTable->Count - Index) * sizeof(RTL_INVERTED_FUNCTION_TABLE_ENTRY)); + } + else { + RtlMoveMemory(&InvertedTable->Entries[Index].EntrySEHandlerTableEncoded, + Index ? &InvertedTable->Entries[Index - 1].EntrySEHandlerTableEncoded : (PVOID)&InvertedTable->NextEntrySEHandlerTableEncoded, + (InvertedTable->Count - Index) * sizeof(RTL_INVERTED_FUNCTION_TABLE_ENTRY)); + } + } + + RtlCaptureImageExceptionValues(ImageBase, &ptr, &count); + if (IsWin8OrGreater) { + //memory layout is same as x64 + auto entry = reinterpret_cast(&InvertedTable->Entries[Index]); + entry->ExceptionDirectory = reinterpret_cast(RtlEncodeSystemPointer(reinterpret_cast(ptr))); + entry->ExceptionDirectorySize = count; + entry->ImageBase = ImageBase; + entry->ImageSize = SizeOfImage; + } + else { + if (Index) InvertedTable->Entries[Index - 1].EntrySEHandlerTableEncoded = RtlEncodeSystemPointer(reinterpret_cast(ptr)); + else InvertedTable->NextEntrySEHandlerTableEncoded = reinterpret_cast(RtlEncodeSystemPointer(reinterpret_cast(ptr))); + InvertedTable->Entries[Index].ImageBase = ImageBase; + InvertedTable->Entries[Index].ImageSize = SizeOfImage; + InvertedTable->Entries[Index].SEHandlerCount = count; + } +#ifdef _DEBUG + std::cout << "Exception table was set! " << std::endl; +#endif + ++InvertedTable->Count; +#endif + return; } + + static NTSTATUS NTAPI RtlInsertInvertedFunctionTable( + _In_ PVOID BaseAddress, + _In_ ULONG ImageSize + ) { + auto table = reinterpret_cast(RtlFindInvertedFunctionTable()); + if (!table) { +#ifdef _DEBUG + std::cout << "Exception table not found! " << std::endl; +#endif + return STATUS_NOT_SUPPORTED; + } #ifdef _DEBUG - std::cout << "[+] Valid exception entries: " << std::dec << i << " entries\n"; + std::cout << "Found exception table: " << std::hex << table << std::endl; #endif - if (i == 0) { + bool need_virtual_protect = RtlIsWindowsVersionOrGreater(6, 3, 0); + // Windows 8.1 and above require to set PAGE_READWRITE protection #ifdef _DEBUG - std::cerr << "[-] None of the exceptions was valid\n"; + std::cout << "Need virtual protect: " << std::boolalpha << need_virtual_protect << std::endl; #endif - // none of the exceptions was valid - return false; + NTSTATUS status; + + if (need_virtual_protect) { + status = RtlProtectMrdata(PAGE_READWRITE, table); + if (!NT_SUCCESS(status))return status; + } + RtlpInsertInvertedFunctionTable(table, BaseAddress, ImageSize); + if (need_virtual_protect) { + status = RtlProtectMrdata(PAGE_READONLY, table); + if (!NT_SUCCESS(status))return status; + } + // Windows 8+ versons have different structure than Windows 7 and below + return (RtlIsWindowsVersionOrGreater(6, 2, 0) ? PRTL_INVERTED_FUNCTION_TABLE_64(table)->Overflow : PRTL_INVERTED_FUNCTION_TABLE_WIN7_32(table)->Overflow) ? + STATUS_NO_MEMORY : STATUS_SUCCESS; } - if (RtlAddFunctionTable(exceptions_list, (DWORD)i, (ULONG_PTR)modulePtr)) { - return true; +} + +bool peconv::setup_exceptions(IN BYTE* modulePtr, IN size_t moduleSize) +{ + if (moduleSize == 0) { + const DWORD img_size = get_image_size(reinterpret_cast(modulePtr)); + if (!img_size) { + return false; // invalid image + } + moduleSize = img_size; } - return false; + return NT_SUCCESS(details::RtlInsertInvertedFunctionTable(modulePtr, moduleSize)); } -#endif diff --git a/libpeconv/src/ntddk.h b/libpeconv/src/ntddk.h index d24154eb4..965859454 100644 --- a/libpeconv/src/ntddk.h +++ b/libpeconv/src/ntddk.h @@ -22,10 +22,10 @@ extern "C" { #include #pragma warning(pop) -//------------------------------------------------------------------------------ -// Defines for NTSTATUS + //------------------------------------------------------------------------------ + // Defines for NTSTATUS -typedef long NTSTATUS; + typedef long NTSTATUS; #ifndef NT_SUCCESS #define NT_SUCCESS(Status) ((NTSTATUS)(Status) >= 0) @@ -47,58 +47,58 @@ typedef long NTSTATUS; #endif #endif -//------------------------------------------------------------------------------ -// Structures + //------------------------------------------------------------------------------ + // Structures -typedef enum _EVENT_TYPE -{ - NotificationEvent, - SynchronizationEvent + typedef enum _EVENT_TYPE + { + NotificationEvent, + SynchronizationEvent -} EVENT_TYPE; + } EVENT_TYPE; -// -// ANSI strings are counted 8-bit character strings. If they are -// NULL terminated, Length does not include trailing NULL. -// + // + // ANSI strings are counted 8-bit character strings. If they are + // NULL terminated, Length does not include trailing NULL. + // #ifndef _NTSECAPI_ -typedef struct _STRING -{ - USHORT Length; - USHORT MaximumLength; - PCHAR Buffer; + typedef struct _STRING + { + USHORT Length; + USHORT MaximumLength; + PCHAR Buffer; -} STRING, *PSTRING; + } STRING, * PSTRING; -// -// Unicode strings are counted 16-bit character strings. If they are -// NULL terminated, Length does not include trailing NULL. -// + // + // Unicode strings are counted 16-bit character strings. If they are + // NULL terminated, Length does not include trailing NULL. + // -typedef struct _UNICODE_STRING -{ - USHORT Length; - USHORT MaximumLength; - PWSTR Buffer; + typedef struct _UNICODE_STRING + { + USHORT Length; + USHORT MaximumLength; + PWSTR Buffer; -} UNICODE_STRING, *PUNICODE_STRING; + } UNICODE_STRING, * PUNICODE_STRING; #endif // _NTSECAPI_ -typedef STRING ANSI_STRING; -typedef PSTRING PANSI_STRING; + typedef STRING ANSI_STRING; + typedef PSTRING PANSI_STRING; -typedef STRING OEM_STRING; -typedef PSTRING POEM_STRING; -typedef CONST STRING* PCOEM_STRING; + typedef STRING OEM_STRING; + typedef PSTRING POEM_STRING; + typedef CONST STRING* PCOEM_STRING; -typedef const UNICODE_STRING *PCUNICODE_STRING; + typedef const UNICODE_STRING* PCUNICODE_STRING; #define UNICODE_NULL ((WCHAR)0) // winnt -// -// Valid values for the Attributes field -// + // + // Valid values for the Attributes field + // #ifndef OBJ_CASE_INSENSITIVE #define OBJ_INHERIT 0x00000002L @@ -115,62 +115,62 @@ typedef const UNICODE_STRING *PCUNICODE_STRING; // Object Attributes structure // -typedef struct _OBJECT_ATTRIBUTES -{ - ULONG Length; - HANDLE RootDirectory; - PUNICODE_STRING ObjectName; - ULONG Attributes; - PVOID SecurityDescriptor; // Points to type SECURITY_DESCRIPTOR - PVOID SecurityQualityOfService; // Points to type SECURITY_QUALITY_OF_SERVICE - -} OBJECT_ATTRIBUTES, *POBJECT_ATTRIBUTES; + typedef struct _OBJECT_ATTRIBUTES + { + ULONG Length; + HANDLE RootDirectory; + PUNICODE_STRING ObjectName; + ULONG Attributes; + PVOID SecurityDescriptor; // Points to type SECURITY_DESCRIPTOR + PVOID SecurityQualityOfService; // Points to type SECURITY_QUALITY_OF_SERVICE + + } OBJECT_ATTRIBUTES, * POBJECT_ATTRIBUTES; #endif // OBJ_CASE_INSENSITIVE -// -// IO_STATUS_BLOCK -// + // + // IO_STATUS_BLOCK + // -typedef struct _IO_STATUS_BLOCK -{ - union + typedef struct _IO_STATUS_BLOCK { - NTSTATUS Status; - PVOID Pointer; - }; + union + { + NTSTATUS Status; + PVOID Pointer; + }; - ULONG_PTR Information; + ULONG_PTR Information; -} IO_STATUS_BLOCK, *PIO_STATUS_BLOCK; + } IO_STATUS_BLOCK, * PIO_STATUS_BLOCK; -// -// ClientId -// + // + // ClientId + // -typedef struct _CLIENT_ID -{ - HANDLE UniqueProcess; - HANDLE UniqueThread; + typedef struct _CLIENT_ID + { + HANDLE UniqueProcess; + HANDLE UniqueThread; -} CLIENT_ID, *PCLIENT_ID; + } CLIENT_ID, * PCLIENT_ID; -// -// CURDIR structure -// + // + // CURDIR structure + // -typedef struct _CURDIR -{ - UNICODE_STRING DosPath; - HANDLE Handle; + typedef struct _CURDIR + { + UNICODE_STRING DosPath; + HANDLE Handle; -} CURDIR, *PCURDIR; + } CURDIR, * PCURDIR; -//------------------------------------------------------------------------------ -// Macros + //------------------------------------------------------------------------------ + // Macros -// INIT_UNICODE_STRING is a replacement of RtlInitUnicodeString + // INIT_UNICODE_STRING is a replacement of RtlInitUnicodeString #ifndef INIT_UNICODE_STRING #define INIT_UNICODE_STRING(us, wch) \ us.MaximumLength = (USHORT)sizeof(wch); \ @@ -203,311 +203,320 @@ typedef struct _CURDIR //----------------------------------------------------------------------------- // Image functions -NTSYSAPI -PVOID -NTAPI -RtlImageNtHeader ( - IN PVOID BaseAddress - ); - -NTSYSAPI -PVOID -NTAPI -RtlImageDirectoryEntryToData ( - IN PVOID Base, - IN BOOLEAN MappedAsImage, - IN USHORT DirectoryEntry, - OUT PULONG Size - ); - -//----------------------------------------------------------------------------- -// Unicode string functions - -NTSYSAPI -NTSTATUS -NTAPI -RtlStringFromGUID( - IN REFGUID Guid, - OUT PUNICODE_STRING GuidString - ); - - -NTSYSAPI -VOID -NTAPI -RtlInitUnicodeString( - PUNICODE_STRING DestinationString, - PCWSTR SourceString - ); - - -NTSYSAPI -BOOLEAN -NTAPI -RtlCreateUnicodeString( - OUT PUNICODE_STRING DestinationString, - IN PCWSTR SourceString - ); - - -NTSYSAPI -BOOLEAN -NTAPI -RtlCreateUnicodeStringFromAsciiz( - OUT PUNICODE_STRING Destination, - IN PCSTR Source - ); - - -NTSYSAPI -BOOLEAN -NTAPI -RtlPrefixUnicodeString ( - IN PUNICODE_STRING String1, - IN PUNICODE_STRING String2, - IN BOOLEAN CaseInSensitive - ); - - -NTSYSAPI -NTSTATUS -NTAPI -RtlDuplicateUnicodeString( - IN BOOLEAN AllocateNew, - IN PUNICODE_STRING SourceString, - OUT PUNICODE_STRING TargetString - ); - - -NTSYSAPI -NTSTATUS -NTAPI -RtlAppendUnicodeToString ( - PUNICODE_STRING Destination, - PCWSTR Source - ); - - -NTSYSAPI -NTSTATUS -NTAPI -RtlAppendUnicodeStringToString( - IN OUT PUNICODE_STRING Destination, - IN PUNICODE_STRING Source - ); - - -NTSYSAPI -NTSTATUS -NTAPI -RtlUnicodeStringToInteger ( - IN PUNICODE_STRING String, - IN ULONG Base OPTIONAL, - OUT PULONG Value - ); - - -NTSYSAPI -NTSTATUS -NTAPI -RtlIntegerToUnicodeString ( - IN ULONG Value, - IN ULONG Base OPTIONAL, - IN OUT PUNICODE_STRING String - ); - - -NTSYSAPI -NTSTATUS -NTAPI -RtlGUIDFromString( - IN PUNICODE_STRING GuidString, - OUT GUID *Guid - ); - - -NTSYSAPI -LONG -NTAPI -RtlCompareUnicodeString ( - IN PUNICODE_STRING String1, - IN PUNICODE_STRING String2, - IN BOOLEAN CaseInSensitive - ); - - -NTSYSAPI -VOID -NTAPI -RtlCopyUnicodeString( - OUT PUNICODE_STRING DestinationString, - IN PUNICODE_STRING SourceString - ); - - -NTSYSAPI -NTSTATUS -NTAPI -RtlUpcaseUnicodeString ( - OUT PUNICODE_STRING DestinationString, - IN PUNICODE_STRING SourceString, - IN BOOLEAN AllocateDestinationString - ); - - -NTSYSAPI -NTSTATUS -NTAPI -RtlDowncaseUnicodeString ( - OUT PUNICODE_STRING DestinationString, - IN PUNICODE_STRING SourceString, - IN BOOLEAN AllocateDestinationString - ); - - -NTSYSAPI -BOOLEAN -NTAPI -RtlEqualUnicodeString ( - IN PUNICODE_STRING String1, - IN PUNICODE_STRING String2, - IN BOOLEAN CaseInSensitive - ); - - -NTSYSAPI -VOID -NTAPI -RtlFreeUnicodeString( - IN PUNICODE_STRING UnicodeString - ); - - -NTSYSAPI -NTSTATUS -NTAPI -RtlAnsiStringToUnicodeString ( - OUT PUNICODE_STRING DestinationString, - IN PANSI_STRING SourceString, - IN BOOLEAN AllocateDestinationString - ); - - -NTSYSAPI -NTSTATUS -NTAPI -RtlUnicodeStringToAnsiString ( - OUT PANSI_STRING DestinationString, - IN PUNICODE_STRING SourceString, - IN BOOLEAN AllocateDestinationString - ); - - -NTSYSAPI -VOID -NTAPI -RtlInitAnsiString ( - OUT PANSI_STRING DestinationString, - IN PCHAR SourceString - ); - - -NTSYSAPI -VOID -NTAPI -RtlFreeAnsiString ( - IN PANSI_STRING AnsiString - ); - - -NTSYSAPI -NTSTATUS -NTAPI -RtlFormatCurrentUserKeyPath( - OUT PUNICODE_STRING CurrentUserKeyPath - ); - - -NTSYSAPI -VOID -NTAPI -RtlRaiseStatus ( - IN NTSTATUS Status - ); - - -NTSYSAPI -VOID -NTAPI -DbgBreakPoint( - VOID - ); - - -NTSYSAPI -ULONG -_cdecl -DbgPrint ( - PCH Format, - ... - ); - - -NTSYSAPI -ULONG -NTAPI -RtlRandom( - IN OUT PULONG Seed - ); - -//----------------------------------------------------------------------------- -// Critical section functions - -NTSYSAPI -NTSTATUS -NTAPI -RtlInitializeCriticalSection( - IN PRTL_CRITICAL_SECTION CriticalSection - ); - - -NTSYSAPI -BOOL -NTAPI -RtlTryEnterCriticalSection( - IN PRTL_CRITICAL_SECTION CriticalSection - ); - - -NTSYSAPI -NTSTATUS -NTAPI -RtlEnterCriticalSection( - IN PRTL_CRITICAL_SECTION CriticalSection - ); - - -NTSYSAPI -NTSTATUS -NTAPI -RtlLeaveCriticalSection( - IN PRTL_CRITICAL_SECTION CriticalSection - ); - - -NTSYSAPI -NTSTATUS -NTAPI -RtlDeleteCriticalSection( - IN PRTL_CRITICAL_SECTION CriticalSection - ); + NTSYSAPI + PVOID + NTAPI + RtlImageNtHeader( + IN PVOID BaseAddress + ); + + NTSYSAPI + PVOID + NTAPI + RtlImageDirectoryEntryToData( + IN PVOID Base, + IN BOOLEAN MappedAsImage, + IN USHORT DirectoryEntry, + OUT PULONG Size + ); + + //----------------------------------------------------------------------------- + // Unicode string functions + + NTSYSAPI + NTSTATUS + NTAPI + RtlStringFromGUID( + IN REFGUID Guid, + OUT PUNICODE_STRING GuidString + ); + + + NTSYSAPI + VOID + NTAPI + RtlInitUnicodeString( + PUNICODE_STRING DestinationString, + PCWSTR SourceString + ); + + + NTSYSAPI + BOOLEAN + NTAPI + RtlCreateUnicodeString( + OUT PUNICODE_STRING DestinationString, + IN PCWSTR SourceString + ); + + + NTSYSAPI + BOOLEAN + NTAPI + RtlCreateUnicodeStringFromAsciiz( + OUT PUNICODE_STRING Destination, + IN PCSTR Source + ); + + + NTSYSAPI + BOOLEAN + NTAPI + RtlPrefixUnicodeString( + IN PUNICODE_STRING String1, + IN PUNICODE_STRING String2, + IN BOOLEAN CaseInSensitive + ); + + + NTSYSAPI + NTSTATUS + NTAPI + RtlDuplicateUnicodeString( + IN BOOLEAN AllocateNew, + IN PUNICODE_STRING SourceString, + OUT PUNICODE_STRING TargetString + ); + + + NTSYSAPI + NTSTATUS + NTAPI + RtlAppendUnicodeToString( + PUNICODE_STRING Destination, + PCWSTR Source + ); + + + NTSYSAPI + NTSTATUS + NTAPI + RtlAppendUnicodeStringToString( + IN OUT PUNICODE_STRING Destination, + IN PUNICODE_STRING Source + ); + + + NTSYSAPI + NTSTATUS + NTAPI + RtlUnicodeStringToInteger( + IN PUNICODE_STRING String, + IN ULONG Base OPTIONAL, + OUT PULONG Value + ); + + + NTSYSAPI + NTSTATUS + NTAPI + RtlIntegerToUnicodeString( + IN ULONG Value, + IN ULONG Base OPTIONAL, + IN OUT PUNICODE_STRING String + ); + + + NTSYSAPI + NTSTATUS + NTAPI + RtlGUIDFromString( + IN PUNICODE_STRING GuidString, + OUT GUID* Guid + ); + + + NTSYSAPI + LONG + NTAPI + RtlCompareUnicodeString( + IN PUNICODE_STRING String1, + IN PUNICODE_STRING String2, + IN BOOLEAN CaseInSensitive + ); + + + NTSYSAPI + VOID + NTAPI + RtlCopyUnicodeString( + OUT PUNICODE_STRING DestinationString, + IN PUNICODE_STRING SourceString + ); + + + NTSYSAPI + NTSTATUS + NTAPI + RtlUpcaseUnicodeString( + OUT PUNICODE_STRING DestinationString, + IN PUNICODE_STRING SourceString, + IN BOOLEAN AllocateDestinationString + ); + + + NTSYSAPI + NTSTATUS + NTAPI + RtlDowncaseUnicodeString( + OUT PUNICODE_STRING DestinationString, + IN PUNICODE_STRING SourceString, + IN BOOLEAN AllocateDestinationString + ); + + + NTSYSAPI + BOOLEAN + NTAPI + RtlEqualUnicodeString( + IN PUNICODE_STRING String1, + IN PUNICODE_STRING String2, + IN BOOLEAN CaseInSensitive + ); + + + NTSYSAPI + VOID + NTAPI + RtlFreeUnicodeString( + IN PUNICODE_STRING UnicodeString + ); + + + NTSYSAPI + NTSTATUS + NTAPI + RtlAnsiStringToUnicodeString( + OUT PUNICODE_STRING DestinationString, + IN PANSI_STRING SourceString, + IN BOOLEAN AllocateDestinationString + ); + + + NTSYSAPI + NTSTATUS + NTAPI + RtlUnicodeStringToAnsiString( + OUT PANSI_STRING DestinationString, + IN PUNICODE_STRING SourceString, + IN BOOLEAN AllocateDestinationString + ); + + + NTSYSAPI + VOID + NTAPI + RtlInitAnsiString( + OUT PANSI_STRING DestinationString, + IN PCHAR SourceString + ); + + + NTSYSAPI + VOID + NTAPI + RtlFreeAnsiString( + IN PANSI_STRING AnsiString + ); + + + NTSYSAPI + NTSTATUS + NTAPI + RtlFormatCurrentUserKeyPath( + OUT PUNICODE_STRING CurrentUserKeyPath + ); + + + NTSYSAPI + VOID + NTAPI + RtlRaiseStatus( + IN NTSTATUS Status + ); + + NTSYSAPI + VOID + NTAPI + RtlGetNtVersionNumbers( + _Out_opt_ PULONG NtMajorVersion, + _Out_opt_ PULONG NtMinorVersion, + _Out_opt_ PULONG NtBuildNumber + ); + + + NTSYSAPI + VOID + NTAPI + DbgBreakPoint( + VOID + ); + + + NTSYSAPI + ULONG + _cdecl + DbgPrint( + PCH Format, + ... + ); + + + NTSYSAPI + ULONG + NTAPI + RtlRandom( + IN OUT PULONG Seed + ); + + //----------------------------------------------------------------------------- + // Critical section functions + + NTSYSAPI + NTSTATUS + NTAPI + RtlInitializeCriticalSection( + IN PRTL_CRITICAL_SECTION CriticalSection + ); + + + NTSYSAPI + BOOL + NTAPI + RtlTryEnterCriticalSection( + IN PRTL_CRITICAL_SECTION CriticalSection + ); + + + NTSYSAPI + NTSTATUS + NTAPI + RtlEnterCriticalSection( + IN PRTL_CRITICAL_SECTION CriticalSection + ); + + + NTSYSAPI + NTSTATUS + NTAPI + RtlLeaveCriticalSection( + IN PRTL_CRITICAL_SECTION CriticalSection + ); + + + NTSYSAPI + NTSTATUS + NTAPI + RtlDeleteCriticalSection( + IN PRTL_CRITICAL_SECTION CriticalSection + ); + + //----------------------------------------------------------------------------- + // Object functions -//----------------------------------------------------------------------------- -// Object functions - -// -// Object Manager Directory Specific Access Rights. -// + // + // Object Manager Directory Specific Access Rights. + // #ifndef DIRECTORY_QUERY #define DIRECTORY_QUERY (0x0001) @@ -517,642 +526,642 @@ RtlDeleteCriticalSection( #define DIRECTORY_ALL_ACCESS (STANDARD_RIGHTS_REQUIRED | 0xF) #endif -typedef enum _POOL_TYPE { - NonPagedPool, - PagedPool, - NonPagedPoolMustSucceed, - DontUseThisType, - NonPagedPoolCacheAligned, - PagedPoolCacheAligned, - NonPagedPoolCacheAlignedMustS, - MaxPoolType -} POOL_TYPE; - + typedef enum _POOL_TYPE { + NonPagedPool, + PagedPool, + NonPagedPoolMustSucceed, + DontUseThisType, + NonPagedPoolCacheAligned, + PagedPoolCacheAligned, + NonPagedPoolCacheAlignedMustS, + MaxPoolType + } POOL_TYPE; -// -// For NtQueryObject -// -typedef enum _OBJECT_INFORMATION_CLASS { - ObjectBasicInformation, // = 0 - ObjectNameInformation, // = 1 - ObjectTypeInformation, // = 2 - ObjectTypesInformation, // = 3 //object handle is ignored - ObjectHandleFlagInformation // = 4 -} OBJECT_INFORMATION_CLASS; - -// -// NtQueryObject uses ObjectBasicInformation -// + // + // For NtQueryObject + // -typedef struct _OBJECT_BASIC_INFORMATION { - ULONG Attributes; - ACCESS_MASK GrantedAccess; - ULONG HandleCount; - ULONG PointerCount; - ULONG PagedPoolCharge; - ULONG NonPagedPoolCharge; - ULONG Reserved[3]; - ULONG NameInfoSize; - ULONG TypeInfoSize; - ULONG SecurityDescriptorSize; - LARGE_INTEGER CreationTime; -} OBJECT_BASIC_INFORMATION, *POBJECT_BASIC_INFORMATION; + typedef enum _OBJECT_INFORMATION_CLASS { + ObjectBasicInformation, // = 0 + ObjectNameInformation, // = 1 + ObjectTypeInformation, // = 2 + ObjectTypesInformation, // = 3 //object handle is ignored + ObjectHandleFlagInformation // = 4 + } OBJECT_INFORMATION_CLASS; -// -// NtQueryObject uses ObjectNameInformation -// + // + // NtQueryObject uses ObjectBasicInformation + // -typedef struct _OBJECT_NAME_INFORMATION { - UNICODE_STRING Name; -} OBJECT_NAME_INFORMATION, *POBJECT_NAME_INFORMATION; + typedef struct _OBJECT_BASIC_INFORMATION { + ULONG Attributes; + ACCESS_MASK GrantedAccess; + ULONG HandleCount; + ULONG PointerCount; + ULONG PagedPoolCharge; + ULONG NonPagedPoolCharge; + ULONG Reserved[3]; + ULONG NameInfoSize; + ULONG TypeInfoSize; + ULONG SecurityDescriptorSize; + LARGE_INTEGER CreationTime; + } OBJECT_BASIC_INFORMATION, * POBJECT_BASIC_INFORMATION; -// -// NtQueryObject uses ObjectTypeInformation -// + // + // NtQueryObject uses ObjectNameInformation + // -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; - POOL_TYPE PoolType; - ULONG DefaultPagedPoolCharge; - ULONG DefaultNonPagedPoolCharge; -} OBJECT_TYPE_INFORMATION, *POBJECT_TYPE_INFORMATION; + typedef struct _OBJECT_NAME_INFORMATION { + UNICODE_STRING Name; + } OBJECT_NAME_INFORMATION, * POBJECT_NAME_INFORMATION; -// -// NtQueryObject uses ObjectHandleFlagInformation -// NtSetInformationObject uses ObjectHandleFlagInformation -// + // + // NtQueryObject uses ObjectTypeInformation + // -typedef struct _OBJECT_HANDLE_FLAG_INFORMATION { - BOOLEAN Inherit; - BOOLEAN ProtectFromClose; -} OBJECT_HANDLE_FLAG_INFORMATION, *POBJECT_HANDLE_FLAG_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; + POOL_TYPE PoolType; + ULONG DefaultPagedPoolCharge; + ULONG DefaultNonPagedPoolCharge; + } OBJECT_TYPE_INFORMATION, * POBJECT_TYPE_INFORMATION; -// -// NtQueryDirectoryObject uses this type -// + // + // NtQueryObject uses ObjectHandleFlagInformation + // NtSetInformationObject uses ObjectHandleFlagInformation + // -typedef struct _OBJECT_DIRECTORY_INFORMATION { - UNICODE_STRING Name; - UNICODE_STRING TypeName; -} OBJECT_DIRECTORY_INFORMATION, *POBJECT_DIRECTORY_INFORMATION; - - -NTSYSAPI -NTSTATUS -NTAPI -NtOpenDirectoryObject( - OUT PHANDLE DirectoryHandle, - IN ACCESS_MASK DesiredAccess, - IN POBJECT_ATTRIBUTES ObjectAttributes - ); - - -NTSYSAPI -NTSTATUS -NTAPI -NtQueryDirectoryObject( - IN HANDLE DirectoryHandle, - OUT PVOID Buffer, - IN ULONG Length, - IN BOOLEAN ReturnSingleEntry, - IN BOOLEAN RestartScan, - IN OUT PULONG Context, - OUT PULONG ReturnLength OPTIONAL - ); - - -NTSYSAPI -NTSTATUS -NTAPI -NtQueryObject ( - IN HANDLE ObjectHandle, - IN OBJECT_INFORMATION_CLASS ObjectInformationClass, - OUT PVOID ObjectInformation, - IN ULONG Length, - OUT PULONG ResultLength OPTIONAL - ); - - -NTSYSAPI -NTSTATUS -NTAPI -NtSetInformationObject ( - IN HANDLE ObjectHandle, - IN OBJECT_INFORMATION_CLASS ObjectInformationClass, - IN PVOID ObjectInformation, - IN ULONG Length - ); - - -NTSYSAPI -NTSTATUS -NTAPI -NtDuplicateObject ( - IN HANDLE SourceProcessHandle, - IN HANDLE SourceHandle, - IN HANDLE TargetProcessHandle OPTIONAL, - OUT PHANDLE TargetHandle OPTIONAL, - IN ACCESS_MASK DesiredAccess, - IN ULONG HandleAttributes, - IN ULONG Options - ); - - -NTSYSAPI -NTSTATUS -NTAPI -NtQuerySecurityObject ( - IN HANDLE ObjectHandle, - IN SECURITY_INFORMATION SecurityInformation, - OUT PSECURITY_DESCRIPTOR SecurityDescriptor, - IN ULONG DescriptorLength, - OUT PULONG ReturnLength - ); - - -NTSYSAPI -NTSTATUS -NTAPI -NtSetSecurityObject ( - IN HANDLE ObjectHandle, - IN SECURITY_INFORMATION SecurityInformation, - IN PSECURITY_DESCRIPTOR SecurityDescriptor - ); + typedef struct _OBJECT_HANDLE_FLAG_INFORMATION { + BOOLEAN Inherit; + BOOLEAN ProtectFromClose; + } OBJECT_HANDLE_FLAG_INFORMATION, * POBJECT_HANDLE_FLAG_INFORMATION; + // + // NtQueryDirectoryObject uses this type + // -//----------------------------------------------------------------------------- -// Handle table RTL functions + typedef struct _OBJECT_DIRECTORY_INFORMATION { + UNICODE_STRING Name; + UNICODE_STRING TypeName; + } OBJECT_DIRECTORY_INFORMATION, * POBJECT_DIRECTORY_INFORMATION; + + + NTSYSAPI + NTSTATUS + NTAPI + NtOpenDirectoryObject( + OUT PHANDLE DirectoryHandle, + IN ACCESS_MASK DesiredAccess, + IN POBJECT_ATTRIBUTES ObjectAttributes + ); + + + NTSYSAPI + NTSTATUS + NTAPI + NtQueryDirectoryObject( + IN HANDLE DirectoryHandle, + OUT PVOID Buffer, + IN ULONG Length, + IN BOOLEAN ReturnSingleEntry, + IN BOOLEAN RestartScan, + IN OUT PULONG Context, + OUT PULONG ReturnLength OPTIONAL + ); + + + NTSYSAPI + NTSTATUS + NTAPI + NtQueryObject( + IN HANDLE ObjectHandle, + IN OBJECT_INFORMATION_CLASS ObjectInformationClass, + OUT PVOID ObjectInformation, + IN ULONG Length, + OUT PULONG ResultLength OPTIONAL + ); + + + NTSYSAPI + NTSTATUS + NTAPI + NtSetInformationObject( + IN HANDLE ObjectHandle, + IN OBJECT_INFORMATION_CLASS ObjectInformationClass, + IN PVOID ObjectInformation, + IN ULONG Length + ); + + + NTSYSAPI + NTSTATUS + NTAPI + NtDuplicateObject( + IN HANDLE SourceProcessHandle, + IN HANDLE SourceHandle, + IN HANDLE TargetProcessHandle OPTIONAL, + OUT PHANDLE TargetHandle OPTIONAL, + IN ACCESS_MASK DesiredAccess, + IN ULONG HandleAttributes, + IN ULONG Options + ); + + + NTSYSAPI + NTSTATUS + NTAPI + NtQuerySecurityObject( + IN HANDLE ObjectHandle, + IN SECURITY_INFORMATION SecurityInformation, + OUT PSECURITY_DESCRIPTOR SecurityDescriptor, + IN ULONG DescriptorLength, + OUT PULONG ReturnLength + ); + + + NTSYSAPI + NTSTATUS + NTAPI + NtSetSecurityObject( + IN HANDLE ObjectHandle, + IN SECURITY_INFORMATION SecurityInformation, + IN PSECURITY_DESCRIPTOR SecurityDescriptor + ); + + + //----------------------------------------------------------------------------- + // Handle table RTL functions #define LEVEL_HANDLE_ID 0x74000000 #define LEVEL_HANDLE_ID_MASK 0xFF000000 #define LEVEL_HANDLE_INDEX_MASK 0x00FFFFFF -typedef enum _RTL_GENERIC_COMPARE_RESULTS { - GenericLessThan, - GenericGreaterThan, - GenericEqual -} RTL_GENERIC_COMPARE_RESULTS; - - -typedef struct _RTL_SPLAY_LINKS -{ - struct _RTL_SPLAY_LINKS *Parent; - struct _RTL_SPLAY_LINKS *LeftChild; - struct _RTL_SPLAY_LINKS *RightChild; -} RTL_SPLAY_LINKS, *PRTL_SPLAY_LINKS; - - -struct _RTL_GENERIC_TABLE; - -typedef -RTL_GENERIC_COMPARE_RESULTS -(NTAPI * PRTL_GENERIC_COMPARE_ROUTINE) ( - struct _RTL_GENERIC_TABLE *Table, - PVOID FirstStruct, - PVOID SecondStruct - ); - -typedef -PVOID -(NTAPI *PRTL_GENERIC_ALLOCATE_ROUTINE) ( - struct _RTL_GENERIC_TABLE *Table, - ULONG ByteSize - ); - -typedef -VOID -(NTAPI *PRTL_GENERIC_FREE_ROUTINE) ( - struct _RTL_GENERIC_TABLE *Table, - PVOID Buffer - ); - - -typedef struct _RTL_GENERIC_TABLE { - PRTL_SPLAY_LINKS TableRoot; - LIST_ENTRY InsertOrderList; - PLIST_ENTRY OrderedPointer; - ULONG WhichOrderedElement; - ULONG NumberGenericTableElements; - PRTL_GENERIC_COMPARE_ROUTINE CompareRoutine; - PRTL_GENERIC_ALLOCATE_ROUTINE AllocateRoutine; - PRTL_GENERIC_FREE_ROUTINE FreeRoutine; - PVOID TableContext; -} RTL_GENERIC_TABLE, *PRTL_GENERIC_TABLE; - - -typedef struct _RTL_HANDLE_TABLE_ENTRY -{ - struct _RTL_HANDLE_TABLE_ENTRY *Next; /* pointer to next free handle */ - PVOID Object; - -} RTL_HANDLE_TABLE_ENTRY, *PRTL_HANDLE_TABLE_ENTRY; - - -typedef struct _RTL_HANDLE_TABLE -{ - ULONG MaximumNumberOfHandles; - ULONG SizeOfHandleTableEntry; - ULONG Unknown01; - ULONG Unknown02; - PRTL_HANDLE_TABLE_ENTRY FreeHandles; - PRTL_HANDLE_TABLE_ENTRY CommittedHandles; - PRTL_HANDLE_TABLE_ENTRY UnCommittedHandles; - PRTL_HANDLE_TABLE_ENTRY MaxReservedHandles; -} RTL_HANDLE_TABLE, *PRTL_HANDLE_TABLE; - - -NTSYSAPI -VOID -NTAPI -RtlInitializeGenericTable ( - IN PRTL_GENERIC_TABLE Table, - IN PRTL_GENERIC_COMPARE_ROUTINE CompareRoutine, - IN PRTL_GENERIC_ALLOCATE_ROUTINE AllocateRoutine, - IN PRTL_GENERIC_FREE_ROUTINE FreeRoutine, - IN PVOID TableContext - ); - - -NTSYSAPI -VOID -NTAPI -RtlInitializeHandleTable( - IN ULONG MaximumNumberOfHandles, - IN ULONG SizeOfHandleTableEntry, - OUT PRTL_HANDLE_TABLE HandleTable - ); - - -NTSYSAPI -PRTL_HANDLE_TABLE_ENTRY -NTAPI -RtlAllocateHandle( - IN PRTL_HANDLE_TABLE HandleTable, - OUT PULONG HandleIndex OPTIONAL - ); - - -NTSYSAPI -BOOLEAN -NTAPI -RtlFreeHandle( - IN PRTL_HANDLE_TABLE HandleTable, - IN PRTL_HANDLE_TABLE_ENTRY Handle - ); - - -NTSYSAPI -BOOLEAN -NTAPI -RtlIsValidIndexHandle( - IN PRTL_HANDLE_TABLE HandleTable, - IN ULONG HandleIndex, - OUT PRTL_HANDLE_TABLE_ENTRY *Handle - ); - - -NTSYSAPI -PVOID -NTAPI -RtlInsertElementGenericTable ( - IN PRTL_GENERIC_TABLE Table, - IN PVOID Buffer, - IN LONG BufferSize, - OUT PBOOLEAN NewElement OPTIONAL - ); - - -NTSYSAPI -BOOLEAN -NTAPI -RtlIsGenericTableEmpty ( - IN PRTL_GENERIC_TABLE Table - ); - - -NTSYSAPI -BOOLEAN -NTAPI -RtlIsGenericTableEmpty ( - IN PRTL_GENERIC_TABLE Table - ); - - -NTSYSAPI -PVOID -NTAPI -RtlLookupElementGenericTable ( - IN PRTL_GENERIC_TABLE Table, - IN PVOID Buffer - ); - - -NTSYSAPI -PVOID -NTAPI -RtlEnumerateGenericTableWithoutSplaying( - IN PRTL_GENERIC_TABLE Table, - IN PVOID *RestartKey - ); - - -NTSYSAPI -NTSTATUS -NTAPI -NtClose( - IN HANDLE Handle - ); - - -NTSYSAPI -NTSTATUS -NTAPI -ZwClose( - IN HANDLE Handle - ); + typedef enum _RTL_GENERIC_COMPARE_RESULTS { + GenericLessThan, + GenericGreaterThan, + GenericEqual + } RTL_GENERIC_COMPARE_RESULTS; -//----------------------------------------------------------------------------- -// Environment functions - -NTSYSAPI -NTSTATUS -NTAPI -RtlOpenCurrentUser( - IN ULONG DesiredAccess, - OUT PHANDLE CurrentUserKey - ); - - -NTSYSAPI -NTSTATUS -NTAPI -RtlCreateEnvironment( - BOOLEAN CloneCurrentEnvironment, - PVOID *Environment - ); - - -NTSYSAPI -NTSTATUS -NTAPI -RtlQueryEnvironmentVariable_U ( - PVOID Environment, - PUNICODE_STRING Name, - PUNICODE_STRING Value - ); - - -NTSYSAPI -NTSTATUS -NTAPI -RtlSetEnvironmentVariable( - PVOID *Environment, - PUNICODE_STRING Name, - PUNICODE_STRING Value - ); - - -NTSYSAPI -NTSTATUS -NTAPI -RtlDestroyEnvironment( - PVOID Environment - ); -//----------------------------------------------------------------------------- -// Registry functions + typedef struct _RTL_SPLAY_LINKS + { + struct _RTL_SPLAY_LINKS* Parent; + struct _RTL_SPLAY_LINKS* LeftChild; + struct _RTL_SPLAY_LINKS* RightChild; + } RTL_SPLAY_LINKS, * PRTL_SPLAY_LINKS; + + + struct _RTL_GENERIC_TABLE; + + typedef + RTL_GENERIC_COMPARE_RESULTS + (NTAPI* PRTL_GENERIC_COMPARE_ROUTINE) ( + struct _RTL_GENERIC_TABLE* Table, + PVOID FirstStruct, + PVOID SecondStruct + ); + + typedef + PVOID + (NTAPI* PRTL_GENERIC_ALLOCATE_ROUTINE) ( + struct _RTL_GENERIC_TABLE* Table, + ULONG ByteSize + ); + + typedef + VOID + (NTAPI* PRTL_GENERIC_FREE_ROUTINE) ( + struct _RTL_GENERIC_TABLE* Table, + PVOID Buffer + ); + + + typedef struct _RTL_GENERIC_TABLE { + PRTL_SPLAY_LINKS TableRoot; + LIST_ENTRY InsertOrderList; + PLIST_ENTRY OrderedPointer; + ULONG WhichOrderedElement; + ULONG NumberGenericTableElements; + PRTL_GENERIC_COMPARE_ROUTINE CompareRoutine; + PRTL_GENERIC_ALLOCATE_ROUTINE AllocateRoutine; + PRTL_GENERIC_FREE_ROUTINE FreeRoutine; + PVOID TableContext; + } RTL_GENERIC_TABLE, * PRTL_GENERIC_TABLE; + + + typedef struct _RTL_HANDLE_TABLE_ENTRY + { + struct _RTL_HANDLE_TABLE_ENTRY* Next; /* pointer to next free handle */ + PVOID Object; + } RTL_HANDLE_TABLE_ENTRY, * PRTL_HANDLE_TABLE_ENTRY; -typedef enum _KEY_INFORMATION_CLASS -{ - KeyBasicInformation, - KeyNodeInformation, - KeyFullInformation, - KeyNameInformation, - KeyCachedInformation, - KeyFlagsInformation, - MaxKeyInfoClass // MaxKeyInfoClass should always be the last enum -} KEY_INFORMATION_CLASS; + typedef struct _RTL_HANDLE_TABLE + { + ULONG MaximumNumberOfHandles; + ULONG SizeOfHandleTableEntry; + ULONG Unknown01; + ULONG Unknown02; + PRTL_HANDLE_TABLE_ENTRY FreeHandles; + PRTL_HANDLE_TABLE_ENTRY CommittedHandles; + PRTL_HANDLE_TABLE_ENTRY UnCommittedHandles; + PRTL_HANDLE_TABLE_ENTRY MaxReservedHandles; + } RTL_HANDLE_TABLE, * PRTL_HANDLE_TABLE; + + + NTSYSAPI + VOID + NTAPI + RtlInitializeGenericTable( + IN PRTL_GENERIC_TABLE Table, + IN PRTL_GENERIC_COMPARE_ROUTINE CompareRoutine, + IN PRTL_GENERIC_ALLOCATE_ROUTINE AllocateRoutine, + IN PRTL_GENERIC_FREE_ROUTINE FreeRoutine, + IN PVOID TableContext + ); + + + NTSYSAPI + VOID + NTAPI + RtlInitializeHandleTable( + IN ULONG MaximumNumberOfHandles, + IN ULONG SizeOfHandleTableEntry, + OUT PRTL_HANDLE_TABLE HandleTable + ); + + + NTSYSAPI + PRTL_HANDLE_TABLE_ENTRY + NTAPI + RtlAllocateHandle( + IN PRTL_HANDLE_TABLE HandleTable, + OUT PULONG HandleIndex OPTIONAL + ); + + + NTSYSAPI + BOOLEAN + NTAPI + RtlFreeHandle( + IN PRTL_HANDLE_TABLE HandleTable, + IN PRTL_HANDLE_TABLE_ENTRY Handle + ); + + + NTSYSAPI + BOOLEAN + NTAPI + RtlIsValidIndexHandle( + IN PRTL_HANDLE_TABLE HandleTable, + IN ULONG HandleIndex, + OUT PRTL_HANDLE_TABLE_ENTRY* Handle + ); + + + NTSYSAPI + PVOID + NTAPI + RtlInsertElementGenericTable( + IN PRTL_GENERIC_TABLE Table, + IN PVOID Buffer, + IN LONG BufferSize, + OUT PBOOLEAN NewElement OPTIONAL + ); + + + NTSYSAPI + BOOLEAN + NTAPI + RtlIsGenericTableEmpty( + IN PRTL_GENERIC_TABLE Table + ); + + + NTSYSAPI + BOOLEAN + NTAPI + RtlIsGenericTableEmpty( + IN PRTL_GENERIC_TABLE Table + ); + + + NTSYSAPI + PVOID + NTAPI + RtlLookupElementGenericTable( + IN PRTL_GENERIC_TABLE Table, + IN PVOID Buffer + ); + + + NTSYSAPI + PVOID + NTAPI + RtlEnumerateGenericTableWithoutSplaying( + IN PRTL_GENERIC_TABLE Table, + IN PVOID* RestartKey + ); + + + NTSYSAPI + NTSTATUS + NTAPI + NtClose( + IN HANDLE Handle + ); + + + NTSYSAPI + NTSTATUS + NTAPI + ZwClose( + IN HANDLE Handle + ); + + //----------------------------------------------------------------------------- + // Environment functions + + NTSYSAPI + NTSTATUS + NTAPI + RtlOpenCurrentUser( + IN ULONG DesiredAccess, + OUT PHANDLE CurrentUserKey + ); + + + NTSYSAPI + NTSTATUS + NTAPI + RtlCreateEnvironment( + BOOLEAN CloneCurrentEnvironment, + PVOID* Environment + ); + + + NTSYSAPI + NTSTATUS + NTAPI + RtlQueryEnvironmentVariable_U( + PVOID Environment, + PUNICODE_STRING Name, + PUNICODE_STRING Value + ); + + + NTSYSAPI + NTSTATUS + NTAPI + RtlSetEnvironmentVariable( + PVOID* Environment, + PUNICODE_STRING Name, + PUNICODE_STRING Value + ); + + + NTSYSAPI + NTSTATUS + NTAPI + RtlDestroyEnvironment( + PVOID Environment + ); + + //----------------------------------------------------------------------------- + // Registry functions + + + typedef enum _KEY_INFORMATION_CLASS + { + KeyBasicInformation, + KeyNodeInformation, + KeyFullInformation, + KeyNameInformation, + KeyCachedInformation, + KeyFlagsInformation, + MaxKeyInfoClass // MaxKeyInfoClass should always be the last enum -// -// Key query structures -// + } KEY_INFORMATION_CLASS; -typedef struct _KEY_BASIC_INFORMATION -{ - LARGE_INTEGER LastWriteTime; - ULONG TitleIndex; - ULONG NameLength; - WCHAR Name[1]; // Variable length string - -} KEY_BASIC_INFORMATION, *PKEY_BASIC_INFORMATION; - - -typedef struct _KEY_NODE_INFORMATION -{ - LARGE_INTEGER LastWriteTime; - ULONG TitleIndex; - ULONG ClassOffset; - ULONG ClassLength; - ULONG NameLength; - WCHAR Name[1]; // Variable length string -// Class[1]; // Variable length string not declared -} KEY_NODE_INFORMATION, *PKEY_NODE_INFORMATION; - - -typedef struct _KEY_FULL_INFORMATION -{ - LARGE_INTEGER LastWriteTime; - ULONG TitleIndex; - ULONG ClassOffset; - ULONG ClassLength; - ULONG SubKeys; - ULONG MaxNameLen; - ULONG MaxClassLen; - ULONG Values; - ULONG MaxValueNameLen; - ULONG MaxValueDataLen; - WCHAR Class[1]; // Variable length - -} KEY_FULL_INFORMATION, *PKEY_FULL_INFORMATION; - - -// end_wdm -typedef struct _KEY_NAME_INFORMATION -{ - ULONG NameLength; - WCHAR Name[1]; // Variable length string - -} KEY_NAME_INFORMATION, *PKEY_NAME_INFORMATION; - -typedef struct _KEY_CACHED_INFORMATION -{ - LARGE_INTEGER LastWriteTime; - ULONG TitleIndex; - ULONG SubKeys; - ULONG MaxNameLen; - ULONG Values; - ULONG MaxValueNameLen; - ULONG MaxValueDataLen; - ULONG NameLength; - WCHAR Name[1]; // Variable length string - -} KEY_CACHED_INFORMATION, *PKEY_CACHED_INFORMATION; - - -typedef struct _KEY_FLAGS_INFORMATION -{ - ULONG UserFlags; - -} KEY_FLAGS_INFORMATION, *PKEY_FLAGS_INFORMATION; - - - -typedef enum _KEY_VALUE_INFORMATION_CLASS { - KeyValueBasicInformation, - KeyValueFullInformation, - KeyValuePartialInformation, - KeyValueFullInformationAlign64, - KeyValuePartialInformationAlign64, - MaxKeyValueInfoClass // MaxKeyValueInfoClass should always be the last enum -} KEY_VALUE_INFORMATION_CLASS; - - -typedef struct _KEY_VALUE_FULL_INFORMATION { - ULONG TitleIndex; - ULONG Type; - ULONG DataOffset; - ULONG DataLength; - ULONG NameLength; - WCHAR Name[1]; // Variable size -// Data[1]; // Variable size data not declared -} KEY_VALUE_FULL_INFORMATION, *PKEY_VALUE_FULL_INFORMATION; - - -typedef struct _KEY_VALUE_PARTIAL_INFORMATION { - ULONG TitleIndex; - ULONG Type; - ULONG DataLength; - UCHAR Data[1]; // Variable size -} KEY_VALUE_PARTIAL_INFORMATION, *PKEY_VALUE_PARTIAL_INFORMATION; - - - -NTSYSAPI -NTSTATUS -NTAPI -NtCreateKey( - OUT PHANDLE KeyHandle, - IN ACCESS_MASK DesiredAccess, - IN POBJECT_ATTRIBUTES ObjectAttributes, - IN ULONG TitleIndex, - IN PUNICODE_STRING Class OPTIONAL, - IN ULONG CreateOptions, - OUT PULONG Disposition OPTIONAL - ); - - -NTSYSAPI -NTSTATUS -NTAPI -NtOpenKey( - OUT PHANDLE KeyHandle, - IN ACCESS_MASK DesiredAccess, - IN POBJECT_ATTRIBUTES ObjectAttributes - ); - -NTSYSAPI -NTSTATUS -NTAPI -NtQueryKey( - IN HANDLE KeyHandle, - IN KEY_INFORMATION_CLASS KeyInformationClass, - OUT PVOID KeyInformation, - IN ULONG Length, - OUT PULONG ResultLength - ); - -NTSYSAPI -NTSTATUS -NTAPI -NtEnumerateKey( - IN HANDLE KeyHandle, - IN ULONG Index, - IN KEY_INFORMATION_CLASS KeyInformationClass, - IN PVOID KeyInformation, - IN ULONG Length, - IN PULONG ResultLength - ); - - -NTSYSAPI -NTSTATUS -NTAPI -NtDeleteKey( - IN HANDLE KeyHandle - ); - - -NTSYSAPI -NTSTATUS -NTAPI -NtQueryValueKey( - IN HANDLE KeyHandle, - IN PUNICODE_STRING ValueName, - IN KEY_VALUE_INFORMATION_CLASS KeyValueInformationClass, - OUT PVOID KeyValueInformation, - IN ULONG Length, - OUT PULONG ResultLength - ); - - -NTSYSAPI -NTSTATUS -NTAPI -NtSetValueKey( - IN HANDLE KeyHandle, - IN PUNICODE_STRING ValueName, - IN ULONG TitleIndex OPTIONAL, - IN ULONG Type, - IN PVOID Data, - IN ULONG DataSize - ); - - -NTSYSAPI -NTSTATUS -NTAPI -NtDeleteValueKey( - IN HANDLE KeyHandle, - IN PUNICODE_STRING ValueName - ); + // + // Key query structures + // -//----------------------------------------------------------------------------- -// RtlQueryRegistryValues + typedef struct _KEY_BASIC_INFORMATION + { + LARGE_INTEGER LastWriteTime; + ULONG TitleIndex; + ULONG NameLength; + WCHAR Name[1]; // Variable length string -// -// The following flags specify how the Name field of a RTL_QUERY_REGISTRY_TABLE -// entry is interpreted. A NULL name indicates the end of the table. -// + } KEY_BASIC_INFORMATION, * PKEY_BASIC_INFORMATION; + + + typedef struct _KEY_NODE_INFORMATION + { + LARGE_INTEGER LastWriteTime; + ULONG TitleIndex; + ULONG ClassOffset; + ULONG ClassLength; + ULONG NameLength; + WCHAR Name[1]; // Variable length string + // Class[1]; // Variable length string not declared + } KEY_NODE_INFORMATION, * PKEY_NODE_INFORMATION; + + + typedef struct _KEY_FULL_INFORMATION + { + LARGE_INTEGER LastWriteTime; + ULONG TitleIndex; + ULONG ClassOffset; + ULONG ClassLength; + ULONG SubKeys; + ULONG MaxNameLen; + ULONG MaxClassLen; + ULONG Values; + ULONG MaxValueNameLen; + ULONG MaxValueDataLen; + WCHAR Class[1]; // Variable length + + } KEY_FULL_INFORMATION, * PKEY_FULL_INFORMATION; + + + // end_wdm + typedef struct _KEY_NAME_INFORMATION + { + ULONG NameLength; + WCHAR Name[1]; // Variable length string + + } KEY_NAME_INFORMATION, * PKEY_NAME_INFORMATION; + + typedef struct _KEY_CACHED_INFORMATION + { + LARGE_INTEGER LastWriteTime; + ULONG TitleIndex; + ULONG SubKeys; + ULONG MaxNameLen; + ULONG Values; + ULONG MaxValueNameLen; + ULONG MaxValueDataLen; + ULONG NameLength; + WCHAR Name[1]; // Variable length string + + } KEY_CACHED_INFORMATION, * PKEY_CACHED_INFORMATION; + + + typedef struct _KEY_FLAGS_INFORMATION + { + ULONG UserFlags; + + } KEY_FLAGS_INFORMATION, * PKEY_FLAGS_INFORMATION; + + + + typedef enum _KEY_VALUE_INFORMATION_CLASS { + KeyValueBasicInformation, + KeyValueFullInformation, + KeyValuePartialInformation, + KeyValueFullInformationAlign64, + KeyValuePartialInformationAlign64, + MaxKeyValueInfoClass // MaxKeyValueInfoClass should always be the last enum + } KEY_VALUE_INFORMATION_CLASS; + + + typedef struct _KEY_VALUE_FULL_INFORMATION { + ULONG TitleIndex; + ULONG Type; + ULONG DataOffset; + ULONG DataLength; + ULONG NameLength; + WCHAR Name[1]; // Variable size + // Data[1]; // Variable size data not declared + } KEY_VALUE_FULL_INFORMATION, * PKEY_VALUE_FULL_INFORMATION; + + + typedef struct _KEY_VALUE_PARTIAL_INFORMATION { + ULONG TitleIndex; + ULONG Type; + ULONG DataLength; + UCHAR Data[1]; // Variable size + } KEY_VALUE_PARTIAL_INFORMATION, * PKEY_VALUE_PARTIAL_INFORMATION; + + + + NTSYSAPI + NTSTATUS + NTAPI + NtCreateKey( + OUT PHANDLE KeyHandle, + IN ACCESS_MASK DesiredAccess, + IN POBJECT_ATTRIBUTES ObjectAttributes, + IN ULONG TitleIndex, + IN PUNICODE_STRING Class OPTIONAL, + IN ULONG CreateOptions, + OUT PULONG Disposition OPTIONAL + ); + + + NTSYSAPI + NTSTATUS + NTAPI + NtOpenKey( + OUT PHANDLE KeyHandle, + IN ACCESS_MASK DesiredAccess, + IN POBJECT_ATTRIBUTES ObjectAttributes + ); + + NTSYSAPI + NTSTATUS + NTAPI + NtQueryKey( + IN HANDLE KeyHandle, + IN KEY_INFORMATION_CLASS KeyInformationClass, + OUT PVOID KeyInformation, + IN ULONG Length, + OUT PULONG ResultLength + ); + + NTSYSAPI + NTSTATUS + NTAPI + NtEnumerateKey( + IN HANDLE KeyHandle, + IN ULONG Index, + IN KEY_INFORMATION_CLASS KeyInformationClass, + IN PVOID KeyInformation, + IN ULONG Length, + IN PULONG ResultLength + ); + + + NTSYSAPI + NTSTATUS + NTAPI + NtDeleteKey( + IN HANDLE KeyHandle + ); + + + NTSYSAPI + NTSTATUS + NTAPI + NtQueryValueKey( + IN HANDLE KeyHandle, + IN PUNICODE_STRING ValueName, + IN KEY_VALUE_INFORMATION_CLASS KeyValueInformationClass, + OUT PVOID KeyValueInformation, + IN ULONG Length, + OUT PULONG ResultLength + ); + + + NTSYSAPI + NTSTATUS + NTAPI + NtSetValueKey( + IN HANDLE KeyHandle, + IN PUNICODE_STRING ValueName, + IN ULONG TitleIndex OPTIONAL, + IN ULONG Type, + IN PVOID Data, + IN ULONG DataSize + ); + + + NTSYSAPI + NTSTATUS + NTAPI + NtDeleteValueKey( + IN HANDLE KeyHandle, + IN PUNICODE_STRING ValueName + ); + + //----------------------------------------------------------------------------- + // RtlQueryRegistryValues + + // + // The following flags specify how the Name field of a RTL_QUERY_REGISTRY_TABLE + // entry is interpreted. A NULL name indicates the end of the table. + // #define RTL_QUERY_REGISTRY_SUBKEY 0x00000001 // Name is a subkey and remainder of // table or until next subkey are value @@ -1202,469 +1211,469 @@ NtDeleteValueKey( #define RTL_REGISTRY_OPTIONAL 0x80000000 // Indicates the key node is optional -typedef NTSTATUS (NTAPI * PRTL_QUERY_REGISTRY_ROUTINE)( - IN PWSTR ValueName, - IN ULONG ValueType, - IN PVOID ValueData, - IN ULONG ValueLength, - IN PVOID Context, - IN PVOID EntryContext - ); - -typedef struct _RTL_QUERY_REGISTRY_TABLE -{ - PRTL_QUERY_REGISTRY_ROUTINE QueryRoutine; - ULONG Flags; - PWSTR Name; - PVOID EntryContext; - ULONG DefaultType; - PVOID DefaultData; - ULONG DefaultLength; - -} RTL_QUERY_REGISTRY_TABLE, *PRTL_QUERY_REGISTRY_TABLE; - - -NTSYSAPI -NTSTATUS -NTAPI -RtlQueryRegistryValues( - IN ULONG RelativeTo, - IN PCWSTR Path, - IN PRTL_QUERY_REGISTRY_TABLE QueryTable, - IN PVOID Context, - IN PVOID Environment OPTIONAL - ); + typedef NTSTATUS(NTAPI* PRTL_QUERY_REGISTRY_ROUTINE)( + IN PWSTR ValueName, + IN ULONG ValueType, + IN PVOID ValueData, + IN ULONG ValueLength, + IN PVOID Context, + IN PVOID EntryContext + ); + typedef struct _RTL_QUERY_REGISTRY_TABLE + { + PRTL_QUERY_REGISTRY_ROUTINE QueryRoutine; + ULONG Flags; + PWSTR Name; + PVOID EntryContext; + ULONG DefaultType; + PVOID DefaultData; + ULONG DefaultLength; -//----------------------------------------------------------------------------- -// Query system information - -typedef enum _SYSTEM_INFORMATION_CLASS -{ - SystemBasicInformation, // 0x00 SYSTEM_BASIC_INFORMATION - SystemProcessorInformation, // 0x01 SYSTEM_PROCESSOR_INFORMATION - SystemPerformanceInformation, // 0x02 - SystemTimeOfDayInformation, // 0x03 - SystemPathInformation, // 0x04 - SystemProcessInformation, // 0x05 - SystemCallCountInformation, // 0x06 - SystemDeviceInformation, // 0x07 - SystemProcessorPerformanceInformation, // 0x08 - SystemFlagsInformation, // 0x09 - SystemCallTimeInformation, // 0x0A - SystemModuleInformation, // 0x0B SYSTEM_MODULE_INFORMATION - SystemLocksInformation, // 0x0C - SystemStackTraceInformation, // 0x0D - SystemPagedPoolInformation, // 0x0E - SystemNonPagedPoolInformation, // 0x0F - SystemHandleInformation, // 0x10 - SystemObjectInformation, // 0x11 - SystemPageFileInformation, // 0x12 - SystemVdmInstemulInformation, // 0x13 - SystemVdmBopInformation, // 0x14 - SystemFileCacheInformation, // 0x15 - SystemPoolTagInformation, // 0x16 - SystemInterruptInformation, // 0x17 - SystemDpcBehaviorInformation, // 0x18 - SystemFullMemoryInformation, // 0x19 - SystemLoadGdiDriverInformation, // 0x1A - SystemUnloadGdiDriverInformation, // 0x1B - SystemTimeAdjustmentInformation, // 0x1C - SystemSummaryMemoryInformation, // 0x1D - SystemNextEventIdInformation, // 0x1E - SystemEventIdsInformation, // 0x1F - SystemCrashDumpInformation, // 0x20 - SystemExceptionInformation, // 0x21 - SystemCrashDumpStateInformation, // 0x22 - SystemKernelDebuggerInformation, // 0x23 - SystemContextSwitchInformation, // 0x24 - SystemRegistryQuotaInformation, // 0x25 - SystemExtendServiceTableInformation, // 0x26 - SystemPrioritySeperation, // 0x27 - SystemPlugPlayBusInformation, // 0x28 - SystemDockInformation, // 0x29 - //SystemPowerInformation, // 0x2A - //SystemProcessorSpeedInformation, // 0x2B - //SystemCurrentTimeZoneInformation, // 0x2C - //SystemLookasideInformation // 0x2D - -} SYSTEM_INFORMATION_CLASS, *PSYSTEM_INFORMATION_CLASS; + } RTL_QUERY_REGISTRY_TABLE, * PRTL_QUERY_REGISTRY_TABLE; -// -// Thread priority -// -typedef LONG KPRIORITY; + NTSYSAPI + NTSTATUS + NTAPI + RtlQueryRegistryValues( + IN ULONG RelativeTo, + IN PCWSTR Path, + IN PRTL_QUERY_REGISTRY_TABLE QueryTable, + IN PVOID Context, + IN PVOID Environment OPTIONAL + ); -// -// Basic System information -// NtQuerySystemInformation with SystemBasicInformation -// -typedef struct _SYSTEM_BASIC_INFORMATION { - ULONG Reserved; - ULONG TimerResolution; - ULONG PageSize; - ULONG NumberOfPhysicalPages; - ULONG LowestPhysicalPageNumber; - ULONG HighestPhysicalPageNumber; - ULONG AllocationGranularity; - ULONG MinimumUserModeAddress; - ULONG MaximumUserModeAddress; - KAFFINITY ActiveProcessorsAffinityMask; - CCHAR NumberOfProcessors; -} SYSTEM_BASIC_INFORMATION, *PSYSTEM_BASIC_INFORMATION; + //----------------------------------------------------------------------------- + // Query system information -// -// Processor information -// NtQuerySystemInformation with SystemProcessorInformation -// + typedef enum _SYSTEM_INFORMATION_CLASS + { + SystemBasicInformation, // 0x00 SYSTEM_BASIC_INFORMATION + SystemProcessorInformation, // 0x01 SYSTEM_PROCESSOR_INFORMATION + SystemPerformanceInformation, // 0x02 + SystemTimeOfDayInformation, // 0x03 + SystemPathInformation, // 0x04 + SystemProcessInformation, // 0x05 + SystemCallCountInformation, // 0x06 + SystemDeviceInformation, // 0x07 + SystemProcessorPerformanceInformation, // 0x08 + SystemFlagsInformation, // 0x09 + SystemCallTimeInformation, // 0x0A + SystemModuleInformation, // 0x0B SYSTEM_MODULE_INFORMATION + SystemLocksInformation, // 0x0C + SystemStackTraceInformation, // 0x0D + SystemPagedPoolInformation, // 0x0E + SystemNonPagedPoolInformation, // 0x0F + SystemHandleInformation, // 0x10 + SystemObjectInformation, // 0x11 + SystemPageFileInformation, // 0x12 + SystemVdmInstemulInformation, // 0x13 + SystemVdmBopInformation, // 0x14 + SystemFileCacheInformation, // 0x15 + SystemPoolTagInformation, // 0x16 + SystemInterruptInformation, // 0x17 + SystemDpcBehaviorInformation, // 0x18 + SystemFullMemoryInformation, // 0x19 + SystemLoadGdiDriverInformation, // 0x1A + SystemUnloadGdiDriverInformation, // 0x1B + SystemTimeAdjustmentInformation, // 0x1C + SystemSummaryMemoryInformation, // 0x1D + SystemNextEventIdInformation, // 0x1E + SystemEventIdsInformation, // 0x1F + SystemCrashDumpInformation, // 0x20 + SystemExceptionInformation, // 0x21 + SystemCrashDumpStateInformation, // 0x22 + SystemKernelDebuggerInformation, // 0x23 + SystemContextSwitchInformation, // 0x24 + SystemRegistryQuotaInformation, // 0x25 + SystemExtendServiceTableInformation, // 0x26 + SystemPrioritySeperation, // 0x27 + SystemPlugPlayBusInformation, // 0x28 + SystemDockInformation, // 0x29 + //SystemPowerInformation, // 0x2A + //SystemProcessorSpeedInformation, // 0x2B + //SystemCurrentTimeZoneInformation, // 0x2C + //SystemLookasideInformation // 0x2D + + } SYSTEM_INFORMATION_CLASS, * PSYSTEM_INFORMATION_CLASS; -typedef struct _SYSTEM_PROCESSOR_INFORMATION { - USHORT ProcessorArchitecture; - USHORT ProcessorLevel; - USHORT ProcessorRevision; - USHORT Reserved; - ULONG ProcessorFeatureBits; -} SYSTEM_PROCESSOR_INFORMATION, *PSYSTEM_PROCESSOR_INFORMATION; + // + // Thread priority + // -// -// Performance information -// NtQuerySystemInformation with SystemPerformanceInformation -// + typedef LONG KPRIORITY; -typedef struct _SYSTEM_PERFORMANCE_INFORMATION { - LARGE_INTEGER IdleProcessTime; - LARGE_INTEGER IoReadTransferCount; - LARGE_INTEGER IoWriteTransferCount; - LARGE_INTEGER IoOtherTransferCount; - ULONG IoReadOperationCount; - ULONG IoWriteOperationCount; - ULONG IoOtherOperationCount; - ULONG AvailablePages; - ULONG CommittedPages; - ULONG CommitLimit; - ULONG PeakCommitment; - ULONG PageFaultCount; - ULONG CopyOnWriteCount; - ULONG TransitionCount; - ULONG CacheTransitionCount; - ULONG DemandZeroCount; - ULONG PageReadCount; - ULONG PageReadIoCount; - ULONG CacheReadCount; - ULONG CacheIoCount; - ULONG DirtyPagesWriteCount; - ULONG DirtyWriteIoCount; - ULONG MappedPagesWriteCount; - ULONG MappedWriteIoCount; - ULONG PagedPoolPages; - ULONG NonPagedPoolPages; - ULONG PagedPoolAllocs; - ULONG PagedPoolFrees; - ULONG NonPagedPoolAllocs; - ULONG NonPagedPoolFrees; - ULONG FreeSystemPtes; - ULONG ResidentSystemCodePage; - ULONG TotalSystemDriverPages; - ULONG TotalSystemCodePages; - ULONG NonPagedPoolLookasideHits; - ULONG PagedPoolLookasideHits; - ULONG Spare3Count; - ULONG ResidentSystemCachePage; - ULONG ResidentPagedPoolPage; - ULONG ResidentSystemDriverPage; - ULONG CcFastReadNoWait; - ULONG CcFastReadWait; - ULONG CcFastReadResourceMiss; - ULONG CcFastReadNotPossible; - ULONG CcFastMdlReadNoWait; - ULONG CcFastMdlReadWait; - ULONG CcFastMdlReadResourceMiss; - ULONG CcFastMdlReadNotPossible; - ULONG CcMapDataNoWait; - ULONG CcMapDataWait; - ULONG CcMapDataNoWaitMiss; - ULONG CcMapDataWaitMiss; - ULONG CcPinMappedDataCount; - ULONG CcPinReadNoWait; - ULONG CcPinReadWait; - ULONG CcPinReadNoWaitMiss; - ULONG CcPinReadWaitMiss; - ULONG CcCopyReadNoWait; - ULONG CcCopyReadWait; - ULONG CcCopyReadNoWaitMiss; - ULONG CcCopyReadWaitMiss; - ULONG CcMdlReadNoWait; - ULONG CcMdlReadWait; - ULONG CcMdlReadNoWaitMiss; - ULONG CcMdlReadWaitMiss; - ULONG CcReadAheadIos; - ULONG CcLazyWriteIos; - ULONG CcLazyWritePages; - ULONG CcDataFlushes; - ULONG CcDataPages; - ULONG ContextSwitches; - ULONG FirstLevelTbFills; - ULONG SecondLevelTbFills; - ULONG SystemCalls; -} SYSTEM_PERFORMANCE_INFORMATION, *PSYSTEM_PERFORMANCE_INFORMATION; + // + // Basic System information + // NtQuerySystemInformation with SystemBasicInformation + // -// -// Time of Day information -// NtQuerySystemInformation with SystemTimeOfDayInformation -// + typedef struct _SYSTEM_BASIC_INFORMATION { + ULONG Reserved; + ULONG TimerResolution; + ULONG PageSize; + ULONG NumberOfPhysicalPages; + ULONG LowestPhysicalPageNumber; + ULONG HighestPhysicalPageNumber; + ULONG AllocationGranularity; + ULONG MinimumUserModeAddress; + ULONG MaximumUserModeAddress; + KAFFINITY ActiveProcessorsAffinityMask; + CCHAR NumberOfProcessors; + } SYSTEM_BASIC_INFORMATION, * PSYSTEM_BASIC_INFORMATION; -typedef struct _SYSTEM_TIMEOFDAY_INFORMATION { - LARGE_INTEGER BootTime; - LARGE_INTEGER CurrentTime; - LARGE_INTEGER TimeZoneBias; - ULONG TimeZoneId; - ULONG Reserved; -} SYSTEM_TIMEOFDAY_INFORMATION, *PSYSTEM_TIMEOFDAY_INFORMATION; + // + // Processor information + // NtQuerySystemInformation with SystemProcessorInformation + // -// -// Process information -// NtQuerySystemInformation with SystemProcessInformation -// + typedef struct _SYSTEM_PROCESSOR_INFORMATION { + USHORT ProcessorArchitecture; + USHORT ProcessorLevel; + USHORT ProcessorRevision; + USHORT Reserved; + ULONG ProcessorFeatureBits; + } SYSTEM_PROCESSOR_INFORMATION, * PSYSTEM_PROCESSOR_INFORMATION; -typedef struct _SYSTEM_PROCESS_INFORMATION { - ULONG NextEntryOffset; - ULONG NumberOfThreads; - LARGE_INTEGER SpareLi1; - LARGE_INTEGER SpareLi2; - LARGE_INTEGER SpareLi3; - LARGE_INTEGER CreateTime; - LARGE_INTEGER UserTime; - LARGE_INTEGER KernelTime; - UNICODE_STRING ImageName; - KPRIORITY BasePriority; - ULONG_PTR UniqueProcessId; - ULONG_PTR InheritedFromUniqueProcessId; - ULONG HandleCount; - // Next part is platform dependent - -} SYSTEM_PROCESS_INFORMATION, *PSYSTEM_PROCESS_INFORMATION; + // + // Performance information + // NtQuerySystemInformation with SystemPerformanceInformation + // -// -// Device information -// NtQuerySystemInformation with SystemDeviceInformation -// + typedef struct _SYSTEM_PERFORMANCE_INFORMATION { + LARGE_INTEGER IdleProcessTime; + LARGE_INTEGER IoReadTransferCount; + LARGE_INTEGER IoWriteTransferCount; + LARGE_INTEGER IoOtherTransferCount; + ULONG IoReadOperationCount; + ULONG IoWriteOperationCount; + ULONG IoOtherOperationCount; + ULONG AvailablePages; + ULONG CommittedPages; + ULONG CommitLimit; + ULONG PeakCommitment; + ULONG PageFaultCount; + ULONG CopyOnWriteCount; + ULONG TransitionCount; + ULONG CacheTransitionCount; + ULONG DemandZeroCount; + ULONG PageReadCount; + ULONG PageReadIoCount; + ULONG CacheReadCount; + ULONG CacheIoCount; + ULONG DirtyPagesWriteCount; + ULONG DirtyWriteIoCount; + ULONG MappedPagesWriteCount; + ULONG MappedWriteIoCount; + ULONG PagedPoolPages; + ULONG NonPagedPoolPages; + ULONG PagedPoolAllocs; + ULONG PagedPoolFrees; + ULONG NonPagedPoolAllocs; + ULONG NonPagedPoolFrees; + ULONG FreeSystemPtes; + ULONG ResidentSystemCodePage; + ULONG TotalSystemDriverPages; + ULONG TotalSystemCodePages; + ULONG NonPagedPoolLookasideHits; + ULONG PagedPoolLookasideHits; + ULONG Spare3Count; + ULONG ResidentSystemCachePage; + ULONG ResidentPagedPoolPage; + ULONG ResidentSystemDriverPage; + ULONG CcFastReadNoWait; + ULONG CcFastReadWait; + ULONG CcFastReadResourceMiss; + ULONG CcFastReadNotPossible; + ULONG CcFastMdlReadNoWait; + ULONG CcFastMdlReadWait; + ULONG CcFastMdlReadResourceMiss; + ULONG CcFastMdlReadNotPossible; + ULONG CcMapDataNoWait; + ULONG CcMapDataWait; + ULONG CcMapDataNoWaitMiss; + ULONG CcMapDataWaitMiss; + ULONG CcPinMappedDataCount; + ULONG CcPinReadNoWait; + ULONG CcPinReadWait; + ULONG CcPinReadNoWaitMiss; + ULONG CcPinReadWaitMiss; + ULONG CcCopyReadNoWait; + ULONG CcCopyReadWait; + ULONG CcCopyReadNoWaitMiss; + ULONG CcCopyReadWaitMiss; + ULONG CcMdlReadNoWait; + ULONG CcMdlReadWait; + ULONG CcMdlReadNoWaitMiss; + ULONG CcMdlReadWaitMiss; + ULONG CcReadAheadIos; + ULONG CcLazyWriteIos; + ULONG CcLazyWritePages; + ULONG CcDataFlushes; + ULONG CcDataPages; + ULONG ContextSwitches; + ULONG FirstLevelTbFills; + ULONG SecondLevelTbFills; + ULONG SystemCalls; + } SYSTEM_PERFORMANCE_INFORMATION, * PSYSTEM_PERFORMANCE_INFORMATION; -typedef struct _SYSTEM_DEVICE_INFORMATION { - ULONG NumberOfDisks; - ULONG NumberOfFloppies; - ULONG NumberOfCdRoms; - ULONG NumberOfTapes; - ULONG NumberOfSerialPorts; - ULONG NumberOfParallelPorts; -} SYSTEM_DEVICE_INFORMATION, *PSYSTEM_DEVICE_INFORMATION; + // + // Time of Day information + // NtQuerySystemInformation with SystemTimeOfDayInformation + // -// -// Processor performance information -// NtQuerySystemInformation with SystemProcessorPerformanceInformation -// + typedef struct _SYSTEM_TIMEOFDAY_INFORMATION { + LARGE_INTEGER BootTime; + LARGE_INTEGER CurrentTime; + LARGE_INTEGER TimeZoneBias; + ULONG TimeZoneId; + ULONG Reserved; + } SYSTEM_TIMEOFDAY_INFORMATION, * PSYSTEM_TIMEOFDAY_INFORMATION; -typedef struct _SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION { - LARGE_INTEGER IdleTime; - LARGE_INTEGER KernelTime; - LARGE_INTEGER UserTime; - LARGE_INTEGER DpcTime; // DEVL only - LARGE_INTEGER InterruptTime; // DEVL only - ULONG InterruptCount; -} SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION, *PSYSTEM_PROCESSOR_PERFORMANCE_INFORMATION; + // + // Process information + // NtQuerySystemInformation with SystemProcessInformation + // -// -// NT Global Flag information -// NtQuerySystemInformation with SystemFlagsInformation -// + typedef struct _SYSTEM_PROCESS_INFORMATION { + ULONG NextEntryOffset; + ULONG NumberOfThreads; + LARGE_INTEGER SpareLi1; + LARGE_INTEGER SpareLi2; + LARGE_INTEGER SpareLi3; + LARGE_INTEGER CreateTime; + LARGE_INTEGER UserTime; + LARGE_INTEGER KernelTime; + UNICODE_STRING ImageName; + KPRIORITY BasePriority; + ULONG_PTR UniqueProcessId; + ULONG_PTR InheritedFromUniqueProcessId; + ULONG HandleCount; + // Next part is platform dependent + + } SYSTEM_PROCESS_INFORMATION, * PSYSTEM_PROCESS_INFORMATION; -typedef struct _SYSTEM_FLAGS_INFORMATION -{ - ULONG GlobalFlag; + // + // Device information + // NtQuerySystemInformation with SystemDeviceInformation + // -} SYSTEM_FLAGS_INFORMATION, *PSYSTEM_FLAGS_INFORMATION; + typedef struct _SYSTEM_DEVICE_INFORMATION { + ULONG NumberOfDisks; + ULONG NumberOfFloppies; + ULONG NumberOfCdRoms; + ULONG NumberOfTapes; + ULONG NumberOfSerialPorts; + ULONG NumberOfParallelPorts; + } SYSTEM_DEVICE_INFORMATION, * PSYSTEM_DEVICE_INFORMATION; -// -// System Module information -// NtQuerySystemInformation with SystemModuleInformation -// + // + // Processor performance information + // NtQuerySystemInformation with SystemProcessorPerformanceInformation + // -typedef struct _SYSTEM_MODULE -{ - ULONG Reserved1; // Should be 0xBAADF00D - ULONG Reserved2; // Should be zero - PVOID Base; - ULONG Size; - ULONG Flags; - USHORT Index; - USHORT Unknown; - USHORT LoadCount; - USHORT ModuleNameOffset; - CHAR ImageName[256]; - -} SYSTEM_MODULE, *PSYSTEM_MODULE; - - -typedef struct _SYSTEM_MODULE_INFORMATION -{ - ULONG ModulesCount; - SYSTEM_MODULE Modules[1]; - -} SYSTEM_MODULE_INFORMATION, *PSYSTEM_MODULE_INFORMATION; - -/* -typedef struct _SYSTEM_VDM_INSTEMUL_INFO { - ULONG SegmentNotPresent ; - ULONG VdmOpcode0F ; - ULONG OpcodeESPrefix ; - ULONG OpcodeCSPrefix ; - ULONG OpcodeSSPrefix ; - ULONG OpcodeDSPrefix ; - ULONG OpcodeFSPrefix ; - ULONG OpcodeGSPrefix ; - ULONG OpcodeOPER32Prefix; - ULONG OpcodeADDR32Prefix; - ULONG OpcodeINSB ; - ULONG OpcodeINSW ; - ULONG OpcodeOUTSB ; - ULONG OpcodeOUTSW ; - ULONG OpcodePUSHF ; - ULONG OpcodePOPF ; - ULONG OpcodeINTnn ; - ULONG OpcodeINTO ; - ULONG OpcodeIRET ; - ULONG OpcodeINBimm ; - ULONG OpcodeINWimm ; - ULONG OpcodeOUTBimm ; - ULONG OpcodeOUTWimm ; - ULONG OpcodeINB ; - ULONG OpcodeINW ; - ULONG OpcodeOUTB ; - ULONG OpcodeOUTW ; - ULONG OpcodeLOCKPrefix ; - ULONG OpcodeREPNEPrefix ; - ULONG OpcodeREPPrefix ; - ULONG OpcodeHLT ; - ULONG OpcodeCLI ; - ULONG OpcodeSTI ; - ULONG BopCount ; -} SYSTEM_VDM_INSTEMUL_INFO, *PSYSTEM_VDM_INSTEMUL_INFO; - - -typedef struct _SYSTEM_QUERY_TIME_ADJUST_INFORMATION { - ULONG TimeAdjustment; - ULONG TimeIncrement; - BOOLEAN Enable; -} SYSTEM_QUERY_TIME_ADJUST_INFORMATION, *PSYSTEM_QUERY_TIME_ADJUST_INFORMATION; - -typedef struct _SYSTEM_SET_TIME_ADJUST_INFORMATION { - ULONG TimeAdjustment; - BOOLEAN Enable; -} SYSTEM_SET_TIME_ADJUST_INFORMATION, *PSYSTEM_SET_TIME_ADJUST_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; - ULONG ThreadState; - ULONG WaitReason; -} SYSTEM_THREAD_INFORMATION, *PSYSTEM_THREAD_INFORMATION; - -typedef struct _SYSTEM_MEMORY_INFO { - PUCHAR StringOffset; - USHORT ValidCount; - USHORT TransitionCount; - USHORT ModifiedCount; - USHORT PageTableCount; -} SYSTEM_MEMORY_INFO, *PSYSTEM_MEMORY_INFO; - -typedef struct _SYSTEM_MEMORY_INFORMATION { - ULONG InfoSize; - ULONG StringStart; - SYSTEM_MEMORY_INFO Memory[1]; -} SYSTEM_MEMORY_INFORMATION, *PSYSTEM_MEMORY_INFORMATION; - -typedef struct _SYSTEM_CALL_COUNT_INFORMATION { - ULONG Length; - ULONG NumberOfTables; - //ULONG NumberOfEntries[NumberOfTables]; - //ULONG CallCounts[NumberOfTables][NumberOfEntries]; -} SYSTEM_CALL_COUNT_INFORMATION, *PSYSTEM_CALL_COUNT_INFORMATION; - -typedef struct _SYSTEM_CRASH_DUMP_INFORMATION { - HANDLE CrashDumpSection; -} SYSTEM_CRASH_DUMP_INFORMATION, *PSYSTEM_CRASH_DUMP_INFORMATION; - -typedef struct _SYSTEM_EXCEPTION_INFORMATION { - ULONG AlignmentFixupCount; - ULONG ExceptionDispatchCount; - ULONG FloatingEmulationCount; - ULONG ByteWordEmulationCount; -} SYSTEM_EXCEPTION_INFORMATION, *PSYSTEM_EXCEPTION_INFORMATION; - -typedef struct _SYSTEM_CRASH_STATE_INFORMATION { - ULONG ValidCrashDump; -} SYSTEM_CRASH_STATE_INFORMATION, *PSYSTEM_CRASH_STATE_INFORMATION; - -typedef struct _SYSTEM_KERNEL_DEBUGGER_INFORMATION { - BOOLEAN KernelDebuggerEnabled; - BOOLEAN KernelDebuggerNotPresent; -} SYSTEM_KERNEL_DEBUGGER_INFORMATION, *PSYSTEM_KERNEL_DEBUGGER_INFORMATION; - -typedef struct _SYSTEM_REGISTRY_QUOTA_INFORMATION { - ULONG RegistryQuotaAllowed; - ULONG RegistryQuotaUsed; - ULONG PagedPoolSize; -} SYSTEM_REGISTRY_QUOTA_INFORMATION, *PSYSTEM_REGISTRY_QUOTA_INFORMATION; - -typedef struct _SYSTEM_GDI_DRIVER_INFORMATION { - UNICODE_STRING DriverName; - PVOID ImageAddress; - PVOID SectionPointer; - PVOID EntryPoint; - PIMAGE_EXPORT_DIRECTORY ExportSectionPointer; -} SYSTEM_GDI_DRIVER_INFORMATION, *PSYSTEM_GDI_DRIVER_INFORMATION; -*/ - -NTSYSAPI -NTSTATUS -NTAPI -NtQuerySystemInformation( - IN SYSTEM_INFORMATION_CLASS SystemInformationClass, - OUT PVOID SystemInformation, - IN ULONG SystemInformationLength, - OUT PULONG ReturnLength - ); - -//------------------------------------------------------------------------------ -// Shutdown system - -typedef enum _SHUTDOWN_ACTION -{ - ShutdownNoReboot, - ShutdownReboot, - ShutdownPowerOff - -} SHUTDOWN_ACTION, *PSHUTDOWN_ACTION; - - -NTSYSAPI -NTSTATUS -NTAPI -NtShutdownSystem( - IN SHUTDOWN_ACTION Action - ); + typedef struct _SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION { + LARGE_INTEGER IdleTime; + LARGE_INTEGER KernelTime; + LARGE_INTEGER UserTime; + LARGE_INTEGER DpcTime; // DEVL only + LARGE_INTEGER InterruptTime; // DEVL only + ULONG InterruptCount; + } SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION, * PSYSTEM_PROCESSOR_PERFORMANCE_INFORMATION; -//----------------------------------------------------------------------------- -// File functions + // + // NT Global Flag information + // NtQuerySystemInformation with SystemFlagsInformation + // + + typedef struct _SYSTEM_FLAGS_INFORMATION + { + ULONG GlobalFlag; + + } SYSTEM_FLAGS_INFORMATION, * PSYSTEM_FLAGS_INFORMATION; + + // + // System Module information + // NtQuerySystemInformation with SystemModuleInformation + // + + typedef struct _SYSTEM_MODULE + { + ULONG Reserved1; // Should be 0xBAADF00D + ULONG Reserved2; // Should be zero + PVOID Base; + ULONG Size; + ULONG Flags; + USHORT Index; + USHORT Unknown; + USHORT LoadCount; + USHORT ModuleNameOffset; + CHAR ImageName[256]; + + } SYSTEM_MODULE, * PSYSTEM_MODULE; + + + typedef struct _SYSTEM_MODULE_INFORMATION + { + ULONG ModulesCount; + SYSTEM_MODULE Modules[1]; + + } SYSTEM_MODULE_INFORMATION, * PSYSTEM_MODULE_INFORMATION; + + /* + typedef struct _SYSTEM_VDM_INSTEMUL_INFO { + ULONG SegmentNotPresent ; + ULONG VdmOpcode0F ; + ULONG OpcodeESPrefix ; + ULONG OpcodeCSPrefix ; + ULONG OpcodeSSPrefix ; + ULONG OpcodeDSPrefix ; + ULONG OpcodeFSPrefix ; + ULONG OpcodeGSPrefix ; + ULONG OpcodeOPER32Prefix; + ULONG OpcodeADDR32Prefix; + ULONG OpcodeINSB ; + ULONG OpcodeINSW ; + ULONG OpcodeOUTSB ; + ULONG OpcodeOUTSW ; + ULONG OpcodePUSHF ; + ULONG OpcodePOPF ; + ULONG OpcodeINTnn ; + ULONG OpcodeINTO ; + ULONG OpcodeIRET ; + ULONG OpcodeINBimm ; + ULONG OpcodeINWimm ; + ULONG OpcodeOUTBimm ; + ULONG OpcodeOUTWimm ; + ULONG OpcodeINB ; + ULONG OpcodeINW ; + ULONG OpcodeOUTB ; + ULONG OpcodeOUTW ; + ULONG OpcodeLOCKPrefix ; + ULONG OpcodeREPNEPrefix ; + ULONG OpcodeREPPrefix ; + ULONG OpcodeHLT ; + ULONG OpcodeCLI ; + ULONG OpcodeSTI ; + ULONG BopCount ; + } SYSTEM_VDM_INSTEMUL_INFO, *PSYSTEM_VDM_INSTEMUL_INFO; + + + typedef struct _SYSTEM_QUERY_TIME_ADJUST_INFORMATION { + ULONG TimeAdjustment; + ULONG TimeIncrement; + BOOLEAN Enable; + } SYSTEM_QUERY_TIME_ADJUST_INFORMATION, *PSYSTEM_QUERY_TIME_ADJUST_INFORMATION; + + typedef struct _SYSTEM_SET_TIME_ADJUST_INFORMATION { + ULONG TimeAdjustment; + BOOLEAN Enable; + } SYSTEM_SET_TIME_ADJUST_INFORMATION, *PSYSTEM_SET_TIME_ADJUST_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; + ULONG ThreadState; + ULONG WaitReason; + } SYSTEM_THREAD_INFORMATION, *PSYSTEM_THREAD_INFORMATION; + + typedef struct _SYSTEM_MEMORY_INFO { + PUCHAR StringOffset; + USHORT ValidCount; + USHORT TransitionCount; + USHORT ModifiedCount; + USHORT PageTableCount; + } SYSTEM_MEMORY_INFO, *PSYSTEM_MEMORY_INFO; + + typedef struct _SYSTEM_MEMORY_INFORMATION { + ULONG InfoSize; + ULONG StringStart; + SYSTEM_MEMORY_INFO Memory[1]; + } SYSTEM_MEMORY_INFORMATION, *PSYSTEM_MEMORY_INFORMATION; + + typedef struct _SYSTEM_CALL_COUNT_INFORMATION { + ULONG Length; + ULONG NumberOfTables; + //ULONG NumberOfEntries[NumberOfTables]; + //ULONG CallCounts[NumberOfTables][NumberOfEntries]; + } SYSTEM_CALL_COUNT_INFORMATION, *PSYSTEM_CALL_COUNT_INFORMATION; + + typedef struct _SYSTEM_CRASH_DUMP_INFORMATION { + HANDLE CrashDumpSection; + } SYSTEM_CRASH_DUMP_INFORMATION, *PSYSTEM_CRASH_DUMP_INFORMATION; + + typedef struct _SYSTEM_EXCEPTION_INFORMATION { + ULONG AlignmentFixupCount; + ULONG ExceptionDispatchCount; + ULONG FloatingEmulationCount; + ULONG ByteWordEmulationCount; + } SYSTEM_EXCEPTION_INFORMATION, *PSYSTEM_EXCEPTION_INFORMATION; + + typedef struct _SYSTEM_CRASH_STATE_INFORMATION { + ULONG ValidCrashDump; + } SYSTEM_CRASH_STATE_INFORMATION, *PSYSTEM_CRASH_STATE_INFORMATION; + + typedef struct _SYSTEM_KERNEL_DEBUGGER_INFORMATION { + BOOLEAN KernelDebuggerEnabled; + BOOLEAN KernelDebuggerNotPresent; + } SYSTEM_KERNEL_DEBUGGER_INFORMATION, *PSYSTEM_KERNEL_DEBUGGER_INFORMATION; + + typedef struct _SYSTEM_REGISTRY_QUOTA_INFORMATION { + ULONG RegistryQuotaAllowed; + ULONG RegistryQuotaUsed; + ULONG PagedPoolSize; + } SYSTEM_REGISTRY_QUOTA_INFORMATION, *PSYSTEM_REGISTRY_QUOTA_INFORMATION; + + typedef struct _SYSTEM_GDI_DRIVER_INFORMATION { + UNICODE_STRING DriverName; + PVOID ImageAddress; + PVOID SectionPointer; + PVOID EntryPoint; + PIMAGE_EXPORT_DIRECTORY ExportSectionPointer; + } SYSTEM_GDI_DRIVER_INFORMATION, *PSYSTEM_GDI_DRIVER_INFORMATION; + */ + + NTSYSAPI + NTSTATUS + NTAPI + NtQuerySystemInformation( + IN SYSTEM_INFORMATION_CLASS SystemInformationClass, + OUT PVOID SystemInformation, + IN ULONG SystemInformationLength, + OUT PULONG ReturnLength + ); + + //------------------------------------------------------------------------------ + // Shutdown system + + typedef enum _SHUTDOWN_ACTION + { + ShutdownNoReboot, + ShutdownReboot, + ShutdownPowerOff + + } SHUTDOWN_ACTION, * PSHUTDOWN_ACTION; + + + NTSYSAPI + NTSTATUS + NTAPI + NtShutdownSystem( + IN SHUTDOWN_ACTION Action + ); + + //----------------------------------------------------------------------------- + // File functions #ifndef OLD_DOS_VOLID #define OLD_DOS_VOLID 0x00000008 @@ -1721,1601 +1730,1603 @@ NtShutdownSystem( #ifndef PIO_APC_ROUTINE_DEFINED -typedef -VOID -(NTAPI *PIO_APC_ROUTINE) ( - IN PVOID ApcContext, - IN PIO_STATUS_BLOCK IoStatusBlock, - IN ULONG Reserved - ); + typedef + VOID + (NTAPI* PIO_APC_ROUTINE) ( + IN PVOID ApcContext, + IN PIO_STATUS_BLOCK IoStatusBlock, + IN ULONG Reserved + ); #define PIO_APC_ROUTINE_DEFINED #endif // PIO_APC_ROUTINE_DEFINED -typedef enum _FILE_INFORMATION_CLASS -{ - FileDirectoryInformation = 1, - FileFullDirectoryInformation, // 2 - FileBothDirectoryInformation, // 3 - FileBasicInformation, // 4 wdm - FileStandardInformation, // 5 wdm - FileInternalInformation, // 6 - FileEaInformation, // 7 - FileAccessInformation, // 8 - FileNameInformation, // 9 - FileRenameInformation, // 10 - FileLinkInformation, // 11 - FileNamesInformation, // 12 - FileDispositionInformation, // 13 - FilePositionInformation, // 14 wdm - FileFullEaInformation, // 15 - FileModeInformation, // 16 - FileAlignmentInformation, // 17 - FileAllInformation, // 18 - FileAllocationInformation, // 19 - FileEndOfFileInformation, // 20 wdm - 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 - FileMaximumInformation // 48 -} FILE_INFORMATION_CLASS, *PFILE_INFORMATION_CLASS; - - -typedef struct _FILE_DIRECTORY_INFORMATION { - ULONG NextEntryOffset; - ULONG FileIndex; - LARGE_INTEGER CreationTime; - LARGE_INTEGER LastAccessTime; - LARGE_INTEGER LastWriteTime; - LARGE_INTEGER ChangeTime; - LARGE_INTEGER EndOfFile; - LARGE_INTEGER AllocationSize; - ULONG FileAttributes; - ULONG FileNameLength; - WCHAR FileName[1]; -} FILE_DIRECTORY_INFORMATION, *PFILE_DIRECTORY_INFORMATION; - - -typedef struct _FILE_FULL_DIR_INFORMATION { - ULONG NextEntryOffset; - ULONG FileIndex; - LARGE_INTEGER CreationTime; - LARGE_INTEGER LastAccessTime; - LARGE_INTEGER LastWriteTime; - LARGE_INTEGER ChangeTime; - LARGE_INTEGER EndOfFile; - LARGE_INTEGER AllocationSize; - ULONG FileAttributes; - ULONG FileNameLength; - ULONG EaSize; - WCHAR FileName[1]; -} FILE_FULL_DIR_INFORMATION, *PFILE_FULL_DIR_INFORMATION; - - -typedef struct _FILE_BOTH_DIR_INFORMATION { - ULONG NextEntryOffset; - ULONG FileIndex; - LARGE_INTEGER CreationTime; - LARGE_INTEGER LastAccessTime; - LARGE_INTEGER LastWriteTime; - LARGE_INTEGER ChangeTime; - LARGE_INTEGER EndOfFile; - LARGE_INTEGER AllocationSize; - ULONG FileAttributes; - ULONG FileNameLength; - ULONG EaSize; - CCHAR ShortNameLength; - WCHAR ShortName[12]; - WCHAR FileName[1]; -} FILE_BOTH_DIR_INFORMATION, *PFILE_BOTH_DIR_INFORMATION; - - -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_INTERNAL_INFORMATION { - LARGE_INTEGER IndexNumber; -} FILE_INTERNAL_INFORMATION, *PFILE_INTERNAL_INFORMATION; - - -typedef struct _FILE_EA_INFORMATION { - ULONG EaSize; -} FILE_EA_INFORMATION, *PFILE_EA_INFORMATION; - - -typedef struct _FILE_ACCESS_INFORMATION { - ACCESS_MASK AccessFlags; -} FILE_ACCESS_INFORMATION, *PFILE_ACCESS_INFORMATION; - - -typedef struct _FILE_NAME_INFORMATION { - ULONG FileNameLength; - WCHAR FileName[1]; -} FILE_NAME_INFORMATION, *PFILE_NAME_INFORMATION; - - -typedef struct _FILE_RENAME_INFORMATION { - BOOLEAN ReplaceIfExists; - HANDLE RootDirectory; - ULONG FileNameLength; - WCHAR FileName[1]; -} FILE_RENAME_INFORMATION, *PFILE_RENAME_INFORMATION; - - -typedef struct _FILE_NAMES_INFORMATION { - ULONG NextEntryOffset; - ULONG FileIndex; - ULONG FileNameLength; - WCHAR FileName[1]; -} FILE_NAMES_INFORMATION, *PFILE_NAMES_INFORMATION; - - -typedef struct _FILE_DISPOSITION_INFORMATION { - BOOLEAN DeleteFile; -} FILE_DISPOSITION_INFORMATION, *PFILE_DISPOSITION_INFORMATION; - - -typedef struct _FILE_POSITION_INFORMATION { - LARGE_INTEGER CurrentByteOffset; -} FILE_POSITION_INFORMATION, *PFILE_POSITION_INFORMATION; + typedef enum _FILE_INFORMATION_CLASS + { + FileDirectoryInformation = 1, + FileFullDirectoryInformation, // 2 + FileBothDirectoryInformation, // 3 + FileBasicInformation, // 4 wdm + FileStandardInformation, // 5 wdm + FileInternalInformation, // 6 + FileEaInformation, // 7 + FileAccessInformation, // 8 + FileNameInformation, // 9 + FileRenameInformation, // 10 + FileLinkInformation, // 11 + FileNamesInformation, // 12 + FileDispositionInformation, // 13 + FilePositionInformation, // 14 wdm + FileFullEaInformation, // 15 + FileModeInformation, // 16 + FileAlignmentInformation, // 17 + FileAllInformation, // 18 + FileAllocationInformation, // 19 + FileEndOfFileInformation, // 20 wdm + 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 + FileMaximumInformation // 48 + } FILE_INFORMATION_CLASS, * PFILE_INFORMATION_CLASS; + + + typedef struct _FILE_DIRECTORY_INFORMATION { + ULONG NextEntryOffset; + ULONG FileIndex; + LARGE_INTEGER CreationTime; + LARGE_INTEGER LastAccessTime; + LARGE_INTEGER LastWriteTime; + LARGE_INTEGER ChangeTime; + LARGE_INTEGER EndOfFile; + LARGE_INTEGER AllocationSize; + ULONG FileAttributes; + ULONG FileNameLength; + WCHAR FileName[1]; + } FILE_DIRECTORY_INFORMATION, * PFILE_DIRECTORY_INFORMATION; + + + typedef struct _FILE_FULL_DIR_INFORMATION { + ULONG NextEntryOffset; + ULONG FileIndex; + LARGE_INTEGER CreationTime; + LARGE_INTEGER LastAccessTime; + LARGE_INTEGER LastWriteTime; + LARGE_INTEGER ChangeTime; + LARGE_INTEGER EndOfFile; + LARGE_INTEGER AllocationSize; + ULONG FileAttributes; + ULONG FileNameLength; + ULONG EaSize; + WCHAR FileName[1]; + } FILE_FULL_DIR_INFORMATION, * PFILE_FULL_DIR_INFORMATION; + + + typedef struct _FILE_BOTH_DIR_INFORMATION { + ULONG NextEntryOffset; + ULONG FileIndex; + LARGE_INTEGER CreationTime; + LARGE_INTEGER LastAccessTime; + LARGE_INTEGER LastWriteTime; + LARGE_INTEGER ChangeTime; + LARGE_INTEGER EndOfFile; + LARGE_INTEGER AllocationSize; + ULONG FileAttributes; + ULONG FileNameLength; + ULONG EaSize; + CCHAR ShortNameLength; + WCHAR ShortName[12]; + WCHAR FileName[1]; + } FILE_BOTH_DIR_INFORMATION, * PFILE_BOTH_DIR_INFORMATION; + + + 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_INTERNAL_INFORMATION { + LARGE_INTEGER IndexNumber; + } FILE_INTERNAL_INFORMATION, * PFILE_INTERNAL_INFORMATION; + + + typedef struct _FILE_EA_INFORMATION { + ULONG EaSize; + } FILE_EA_INFORMATION, * PFILE_EA_INFORMATION; + + + typedef struct _FILE_ACCESS_INFORMATION { + ACCESS_MASK AccessFlags; + } FILE_ACCESS_INFORMATION, * PFILE_ACCESS_INFORMATION; + + + typedef struct _FILE_NAME_INFORMATION { + ULONG FileNameLength; + WCHAR FileName[1]; + } FILE_NAME_INFORMATION, * PFILE_NAME_INFORMATION; + + + typedef struct _FILE_RENAME_INFORMATION { + BOOLEAN ReplaceIfExists; + HANDLE RootDirectory; + ULONG FileNameLength; + WCHAR FileName[1]; + } FILE_RENAME_INFORMATION, * PFILE_RENAME_INFORMATION; + + + typedef struct _FILE_NAMES_INFORMATION { + ULONG NextEntryOffset; + ULONG FileIndex; + ULONG FileNameLength; + WCHAR FileName[1]; + } FILE_NAMES_INFORMATION, * PFILE_NAMES_INFORMATION; + + + typedef struct _FILE_DISPOSITION_INFORMATION { + BOOLEAN DeleteFile; + } FILE_DISPOSITION_INFORMATION, * PFILE_DISPOSITION_INFORMATION; + + + typedef struct _FILE_POSITION_INFORMATION { + LARGE_INTEGER CurrentByteOffset; + } FILE_POSITION_INFORMATION, * PFILE_POSITION_INFORMATION; -typedef struct _FILE_FULL_EA_INFORMATION { - ULONG NextEntryOffset; - UCHAR Flags; - UCHAR EaNameLength; - USHORT EaValueLength; - CHAR EaName[1]; -} FILE_FULL_EA_INFORMATION, *PFILE_FULL_EA_INFORMATION; + typedef struct _FILE_FULL_EA_INFORMATION { + ULONG NextEntryOffset; + UCHAR Flags; + UCHAR EaNameLength; + USHORT EaValueLength; + CHAR EaName[1]; + } FILE_FULL_EA_INFORMATION, * PFILE_FULL_EA_INFORMATION; -typedef struct _FILE_MODE_INFORMATION { - ULONG Mode; -} FILE_MODE_INFORMATION, *PFILE_MODE_INFORMATION; + typedef struct _FILE_MODE_INFORMATION { + ULONG Mode; + } FILE_MODE_INFORMATION, * PFILE_MODE_INFORMATION; -typedef struct _FILE_ALIGNMENT_INFORMATION { - ULONG AlignmentRequirement; -} FILE_ALIGNMENT_INFORMATION, *PFILE_ALIGNMENT_INFORMATION; - - -typedef struct _FILE_ALL_INFORMATION { - FILE_BASIC_INFORMATION BasicInformation; - FILE_STANDARD_INFORMATION StandardInformation; - FILE_INTERNAL_INFORMATION InternalInformation; - FILE_EA_INFORMATION EaInformation; - FILE_ACCESS_INFORMATION AccessInformation; - FILE_POSITION_INFORMATION PositionInformation; - FILE_MODE_INFORMATION ModeInformation; - FILE_ALIGNMENT_INFORMATION AlignmentInformation; - FILE_NAME_INFORMATION NameInformation; -} FILE_ALL_INFORMATION, *PFILE_ALL_INFORMATION; + typedef struct _FILE_ALIGNMENT_INFORMATION { + ULONG AlignmentRequirement; + } FILE_ALIGNMENT_INFORMATION, * PFILE_ALIGNMENT_INFORMATION; -typedef struct _FILE_ALLOCATION_INFORMATION { - LARGE_INTEGER AllocationSize; -} FILE_ALLOCATION_INFORMATION, *PFILE_ALLOCATION_INFORMATION; + typedef struct _FILE_ALL_INFORMATION { + FILE_BASIC_INFORMATION BasicInformation; + FILE_STANDARD_INFORMATION StandardInformation; + FILE_INTERNAL_INFORMATION InternalInformation; + FILE_EA_INFORMATION EaInformation; + FILE_ACCESS_INFORMATION AccessInformation; + FILE_POSITION_INFORMATION PositionInformation; + FILE_MODE_INFORMATION ModeInformation; + FILE_ALIGNMENT_INFORMATION AlignmentInformation; + FILE_NAME_INFORMATION NameInformation; + } FILE_ALL_INFORMATION, * PFILE_ALL_INFORMATION; -typedef struct _FILE_END_OF_FILE_INFORMATION { - LARGE_INTEGER EndOfFile; -} FILE_END_OF_FILE_INFORMATION, *PFILE_END_OF_FILE_INFORMATION; + typedef struct _FILE_ALLOCATION_INFORMATION { + LARGE_INTEGER AllocationSize; + } FILE_ALLOCATION_INFORMATION, * PFILE_ALLOCATION_INFORMATION; -typedef struct _FILE_STREAM_INFORMATION { - ULONG NextEntryOffset; - ULONG StreamNameLength; - LARGE_INTEGER StreamSize; - LARGE_INTEGER StreamAllocationSize; - WCHAR StreamName[1]; -} FILE_STREAM_INFORMATION, *PFILE_STREAM_INFORMATION; + typedef struct _FILE_END_OF_FILE_INFORMATION { + LARGE_INTEGER EndOfFile; + } FILE_END_OF_FILE_INFORMATION, * PFILE_END_OF_FILE_INFORMATION; -typedef struct _FILE_PIPE_INFORMATION { - ULONG ReadMode; - ULONG CompletionMode; -} FILE_PIPE_INFORMATION, *PFILE_PIPE_INFORMATION; + typedef struct _FILE_STREAM_INFORMATION { + ULONG NextEntryOffset; + ULONG StreamNameLength; + LARGE_INTEGER StreamSize; + LARGE_INTEGER StreamAllocationSize; + WCHAR StreamName[1]; + } FILE_STREAM_INFORMATION, * PFILE_STREAM_INFORMATION; -typedef struct _FILE_PIPE_LOCAL_INFORMATION { - ULONG NamedPipeType; - ULONG NamedPipeConfiguration; - ULONG MaximumInstances; - ULONG CurrentInstances; - ULONG InboundQuota; - ULONG ReadDataAvailable; - ULONG OutboundQuota; - ULONG WriteQuotaAvailable; - ULONG NamedPipeState; - ULONG NamedPipeEnd; -} FILE_PIPE_LOCAL_INFORMATION, *PFILE_PIPE_LOCAL_INFORMATION; + typedef struct _FILE_PIPE_INFORMATION { + ULONG ReadMode; + ULONG CompletionMode; + } FILE_PIPE_INFORMATION, * PFILE_PIPE_INFORMATION; -typedef struct _FILE_PIPE_REMOTE_INFORMATION { - LARGE_INTEGER CollectDataTime; - ULONG MaximumCollectionCount; -} FILE_PIPE_REMOTE_INFORMATION, *PFILE_PIPE_REMOTE_INFORMATION; - - -typedef struct _FILE_MAILSLOT_QUERY_INFORMATION { - ULONG MaximumMessageSize; - ULONG MailslotQuota; - ULONG NextMessageSize; - ULONG MessagesAvailable; - LARGE_INTEGER ReadTimeout; -} FILE_MAILSLOT_QUERY_INFORMATION, *PFILE_MAILSLOT_QUERY_INFORMATION; - - -typedef struct _FILE_MAILSLOT_SET_INFORMATION { - PLARGE_INTEGER ReadTimeout; -} FILE_MAILSLOT_SET_INFORMATION, *PFILE_MAILSLOT_SET_INFORMATION; - - -typedef struct _FILE_COMPRESSION_INFORMATION { - LARGE_INTEGER CompressedFileSize; - USHORT CompressionFormat; - UCHAR CompressionUnitShift; - UCHAR ChunkShift; - UCHAR ClusterShift; - UCHAR Reserved[3]; -} FILE_COMPRESSION_INFORMATION, *PFILE_COMPRESSION_INFORMATION; - - -typedef struct _FILE_LINK_INFORMATION { - BOOLEAN ReplaceIfExists; - HANDLE RootDirectory; - ULONG FileNameLength; - WCHAR FileName[1]; -} FILE_LINK_INFORMATION, *PFILE_LINK_INFORMATION; - - -typedef struct _FILE_OBJECTID_INFORMATION -{ - LONGLONG FileReference; - UCHAR ObjectId[16]; - union { - struct { - UCHAR BirthVolumeId[16]; - UCHAR BirthObjectId[16]; - UCHAR DomainId[16]; - } ; - UCHAR ExtendedInfo[48]; - }; -} FILE_OBJECTID_INFORMATION, *PFILE_OBJECTID_INFORMATION; - - -typedef struct _FILE_COMPLETION_INFORMATION { - HANDLE Port; - PVOID Key; -} FILE_COMPLETION_INFORMATION, *PFILE_COMPLETION_INFORMATION; - - -typedef struct _FILE_MOVE_CLUSTER_INFORMATION { - ULONG ClusterCount; - HANDLE RootDirectory; - ULONG FileNameLength; - WCHAR FileName[1]; -} FILE_MOVE_CLUSTER_INFORMATION, *PFILE_MOVE_CLUSTER_INFORMATION; - - -typedef struct _FILE_NETWORK_OPEN_INFORMATION { - LARGE_INTEGER CreationTime; - LARGE_INTEGER LastAccessTime; - LARGE_INTEGER LastWriteTime; - LARGE_INTEGER ChangeTime; - LARGE_INTEGER AllocationSize; - LARGE_INTEGER EndOfFile; - ULONG FileAttributes; -} FILE_NETWORK_OPEN_INFORMATION, *PFILE_NETWORK_OPEN_INFORMATION; - - -typedef struct _FILE_ATTRIBUTE_TAG_INFORMATION { - ULONG FileAttributes; - ULONG ReparseTag; -} FILE_ATTRIBUTE_TAG_INFORMATION, *PFILE_ATTRIBUTE_TAG_INFORMATION; - - -typedef struct _FILE_TRACKING_INFORMATION { - HANDLE DestinationFile; - ULONG ObjectInformationLength; - CHAR ObjectInformation[1]; -} FILE_TRACKING_INFORMATION, *PFILE_TRACKING_INFORMATION; - - -typedef struct _FILE_REPARSE_POINT_INFORMATION { - LONGLONG FileReference; - ULONG Tag; -} FILE_REPARSE_POINT_INFORMATION, *PFILE_REPARSE_POINT_INFORMATION; - - -typedef struct _FILE_QUOTA_INFORMATION { - ULONG NextEntryOffset; - ULONG SidLength; - LARGE_INTEGER ChangeTime; - LARGE_INTEGER QuotaUsed; - LARGE_INTEGER QuotaThreshold; - LARGE_INTEGER QuotaLimit; - SID Sid; -} FILE_QUOTA_INFORMATION, *PFILE_QUOTA_INFORMATION; - - -typedef struct _FILE_ID_BOTH_DIR_INFORMATION { - ULONG NextEntryOffset; - ULONG FileIndex; - LARGE_INTEGER CreationTime; - LARGE_INTEGER LastAccessTime; - LARGE_INTEGER LastWriteTime; - LARGE_INTEGER ChangeTime; - LARGE_INTEGER EndOfFile; - LARGE_INTEGER AllocationSize; - ULONG FileAttributes; - ULONG FileNameLength; - ULONG EaSize; - CCHAR ShortNameLength; - WCHAR ShortName[12]; - LARGE_INTEGER FileId; - WCHAR FileName[1]; -} FILE_ID_BOTH_DIR_INFORMATION, *PFILE_ID_BOTH_DIR_INFORMATION; - - -typedef struct _FILE_ID_FULL_DIR_INFORMATION { - ULONG NextEntryOffset; - ULONG FileIndex; - LARGE_INTEGER CreationTime; - LARGE_INTEGER LastAccessTime; - LARGE_INTEGER LastWriteTime; - LARGE_INTEGER ChangeTime; - LARGE_INTEGER EndOfFile; - LARGE_INTEGER AllocationSize; - ULONG FileAttributes; - ULONG FileNameLength; - ULONG EaSize; - LARGE_INTEGER FileId; - WCHAR FileName[1]; -} FILE_ID_FULL_DIR_INFORMATION, *PFILE_ID_FULL_DIR_INFORMATION; - - -typedef struct _FILE_VALID_DATA_LENGTH_INFORMATION { - LARGE_INTEGER ValidDataLength; -} FILE_VALID_DATA_LENGTH_INFORMATION, *PFILE_VALID_DATA_LENGTH_INFORMATION; - -typedef struct _FILE_LINK_ENTRY_INFORMATION { - ULONG NextEntryOffset; - LONGLONG ParentFileId; - ULONG FileNameLength; - WCHAR FileName[1]; -} FILE_LINK_ENTRY_INFORMATION, *PFILE_LINK_ENTRY_INFORMATION; - -typedef struct _FILE_LINKS_INFORMATION { - ULONG BytesNeeded; - ULONG EntriesReturned; - FILE_LINK_ENTRY_INFORMATION Entry; -} FILE_LINKS_INFORMATION, *PFILE_LINKS_INFORMATION; - - - -typedef enum _FSINFOCLASS { - FileFsVolumeInformation = 1, - FileFsLabelInformation, // 2 - FileFsSizeInformation, // 3 - FileFsDeviceInformation, // 4 - FileFsAttributeInformation, // 5 - FileFsControlInformation, // 6 - FileFsFullSizeInformation, // 7 - FileFsObjectIdInformation, // 8 - FileFsDriverPathInformation, // 9 - FileFsMaximumInformation -} FS_INFORMATION_CLASS, *PFS_INFORMATION_CLASS; - - -NTSYSAPI -NTSTATUS -NTAPI -NtCreateFile( - OUT PHANDLE FileHandle, - IN ACCESS_MASK DesiredAccess, - IN POBJECT_ATTRIBUTES ObjectAttributes, - OUT PIO_STATUS_BLOCK IoStatusBlock, - IN PLARGE_INTEGER AllocationSize, - IN ULONG FileAttributes, - IN ULONG ShareAccess, - IN ULONG CreateDisposition, - IN ULONG CreateOptions, - IN PVOID EaBuffer, - IN ULONG EaLength); - - -NTSYSAPI -NTSTATUS -NTAPI -ZwCreateFile( - OUT PHANDLE FileHandle, - IN ACCESS_MASK DesiredAccess, - IN POBJECT_ATTRIBUTES ObjectAttributes, - OUT PIO_STATUS_BLOCK IoStatusBlock, - IN PLARGE_INTEGER AllocationSize, - IN ULONG FileAttributes, - IN ULONG ShareAccess, - IN ULONG CreateDisposition, - IN ULONG CreateOptions, - IN PVOID EaBuffer, - IN ULONG EaLength); - - -NTSYSAPI -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 - ); - - -NTSYSAPI -NTSTATUS -NTAPI -ZwOpenFile( - OUT PHANDLE FileHandle, - IN ACCESS_MASK DesiredAccess, - IN POBJECT_ATTRIBUTES ObjectAttributes, - OUT PIO_STATUS_BLOCK IoStatusBlock, - IN ULONG ShareAccess, - IN ULONG OpenOptions - ); - - -NTSYSAPI -NTSTATUS -NTAPI -NtQueryInformationFile( - IN HANDLE FileHandle, - OUT PIO_STATUS_BLOCK IoStatusBlock, - OUT PVOID FileInformation, - IN ULONG Length, - IN FILE_INFORMATION_CLASS FileInformationClass - ); - - -NTSYSAPI -NTSTATUS -NTAPI -ZwQueryInformationFile( - IN HANDLE FileHandle, - OUT PIO_STATUS_BLOCK IoStatusBlock, - OUT PVOID FileInformation, - IN ULONG Length, - IN FILE_INFORMATION_CLASS FileInformationClass - ); - - -NTSYSAPI -NTSTATUS -NTAPI -NtQueryDirectoryFile( - IN HANDLE FileHandle, - IN HANDLE Event OPTIONAL, - IN PIO_APC_ROUTINE ApcRoutine OPTIONAL, - IN PVOID ApcContext OPTIONAL, - OUT PIO_STATUS_BLOCK IoStatusBlock, - OUT PVOID FileInformation, - IN ULONG Length, - IN FILE_INFORMATION_CLASS FileInformationClass, - IN BOOLEAN ReturnSingleEntry, - IN PUNICODE_STRING FileName OPTIONAL, - IN BOOLEAN RestartScan - ); - - -NTSYSAPI -NTSTATUS -NTAPI -ZwQueryDirectoryFile( - IN HANDLE FileHandle, - IN HANDLE Event OPTIONAL, - IN PIO_APC_ROUTINE ApcRoutine OPTIONAL, - IN PVOID ApcContext OPTIONAL, - OUT PIO_STATUS_BLOCK IoStatusBlock, - OUT PVOID FileInformation, - IN ULONG Length, - IN FILE_INFORMATION_CLASS FileInformationClass, - IN BOOLEAN ReturnSingleEntry, - IN PUNICODE_STRING FileName OPTIONAL, - IN BOOLEAN RestartScan - ); - - -NTSYSAPI -NTSTATUS -NTAPI -NtQueryVolumeInformationFile( - IN HANDLE FileHandle, - OUT PIO_STATUS_BLOCK IoStatusBlock, - OUT PVOID FsInformation, - IN ULONG Length, - IN FS_INFORMATION_CLASS FsInformationClass - ); - - -NTSYSAPI -NTSTATUS -NTAPI -ZwQueryVolumeInformationFile( - IN HANDLE FileHandle, - OUT PIO_STATUS_BLOCK IoStatusBlock, - OUT PVOID FsInformation, - IN ULONG Length, - IN FS_INFORMATION_CLASS FsInformationClass - ); - - -NTSYSAPI -NTSTATUS -NTAPI -NtSetInformationFile( - IN HANDLE FileHandle, - OUT PIO_STATUS_BLOCK IoStatusBlock, - IN PVOID FileInformation, - IN ULONG Length, - IN FILE_INFORMATION_CLASS FileInformationClass - ); - - -NTSYSAPI -NTSTATUS -NTAPI -ZwSetInformationFile( - IN HANDLE FileHandle, - OUT PIO_STATUS_BLOCK IoStatusBlock, - IN PVOID FileInformation, - IN ULONG Length, - IN FILE_INFORMATION_CLASS FileInformationClass - ); - - -NTSYSAPI -NTSTATUS -NTAPI -NtQueryEaFile( - IN HANDLE FileHandle, - OUT PIO_STATUS_BLOCK IoStatusBlock, - OUT PVOID Buffer, - IN ULONG Length, - IN BOOLEAN ReturnSingleEntry, - IN PVOID EaList OPTIONAL, - IN ULONG EaListLength, - IN PULONG EaIndex OPTIONAL, - IN BOOLEAN RestartScan); - - -NTSYSAPI -NTSTATUS -NTAPI -ZwQueryEaFile( - IN HANDLE FileHandle, - OUT PIO_STATUS_BLOCK IoStatusBlock, - OUT PVOID Buffer, - IN ULONG Length, - IN BOOLEAN ReturnSingleEntry, - IN PVOID EaList OPTIONAL, - IN ULONG EaListLength, - IN PULONG EaIndex OPTIONAL, - IN BOOLEAN RestartScan); - - -NTSYSAPI -NTSTATUS -NTAPI -NtSetEaFile( - IN HANDLE FileHandle, - OUT PIO_STATUS_BLOCK IoStatusBlock, - IN PVOID Buffer, - IN ULONG Length); - - -NTSYSAPI -NTSTATUS -NTAPI -ZwSetEaFile( - IN HANDLE FileHandle, - OUT PIO_STATUS_BLOCK IoStatusBlock, - IN PVOID Buffer, - IN ULONG Length); - - -NTSYSAPI -NTSTATUS -NTAPI -NtReadFile( - IN HANDLE FileHandle, - IN HANDLE Event OPTIONAL, - IN PIO_APC_ROUTINE ApcRoutine OPTIONAL, - IN PVOID ApcContext OPTIONAL, - OUT PIO_STATUS_BLOCK IoStatusBlock, - OUT PVOID Buffer, - IN ULONG Length, - IN PLARGE_INTEGER ByteOffset OPTIONAL, - IN PULONG Key OPTIONAL - ); - - -NTSYSAPI -NTSTATUS -NTAPI -ZwReadFile( - IN HANDLE FileHandle, - IN HANDLE Event OPTIONAL, - IN PIO_APC_ROUTINE ApcRoutine OPTIONAL, - IN PVOID ApcContext OPTIONAL, - OUT PIO_STATUS_BLOCK IoStatusBlock, - OUT PVOID Buffer, - IN ULONG Length, - IN PLARGE_INTEGER ByteOffset OPTIONAL, - IN PULONG Key OPTIONAL - ); - - -NTSYSAPI -NTSTATUS -NTAPI -NtWriteFile( - IN HANDLE FileHandle, - IN HANDLE Event OPTIONAL, - IN PIO_APC_ROUTINE ApcRoutine OPTIONAL, - IN PVOID ApcContext OPTIONAL, - OUT PIO_STATUS_BLOCK IoStatusBlock, - IN PVOID Buffer, - IN ULONG Length, - IN PLARGE_INTEGER ByteOffset OPTIONAL, - IN PULONG Key OPTIONAL - ); - - -NTSYSAPI -NTSTATUS -NTAPI -ZwWriteFile( - IN HANDLE FileHandle, - IN HANDLE Event OPTIONAL, - IN PIO_APC_ROUTINE ApcRoutine OPTIONAL, - IN PVOID ApcContext OPTIONAL, - OUT PIO_STATUS_BLOCK IoStatusBlock, - IN PVOID Buffer, - IN ULONG Length, - IN PLARGE_INTEGER ByteOffset OPTIONAL, - IN PULONG Key OPTIONAL - ); - - -NTSYSAPI -NTSTATUS -NTAPI -NtDeleteFile( - IN POBJECT_ATTRIBUTES ObjectAttributes - ); - - -NTSYSAPI -NTSTATUS -NTAPI -ZwDeleteFile( - IN POBJECT_ATTRIBUTES ObjectAttributes - ); - - -NTSYSAPI -NTSTATUS -NTAPI -NtFlushBuffersFile( - IN HANDLE FileHandle, - OUT PIO_STATUS_BLOCK IoStatusBlock - ); - - -NTSYSAPI -NTSTATUS -NTAPI -ZwFlushBuffersFile( - IN HANDLE FileHandle, - OUT PIO_STATUS_BLOCK IoStatusBlock - ); - - -NTSYSAPI -NTSTATUS -NTAPI -NtDeviceIoControlFile( - IN HANDLE FileHandle, - IN HANDLE Event, - IN PIO_APC_ROUTINE ApcRoutine, - IN PVOID ApcContext, - OUT PIO_STATUS_BLOCK IoStatusBlock, - IN ULONG IoControlCode, - IN PVOID InputBuffer, - IN ULONG InputBufferLength, - IN PVOID OutputBuffer, - IN ULONG OutputBufferLength - ); - - -NTSYSAPI -NTSTATUS -NTAPI -ZwDeviceIoControlFile( - IN HANDLE FileHandle, - IN HANDLE Event, - IN PIO_APC_ROUTINE ApcRoutine, - IN PVOID ApcContext, - OUT PIO_STATUS_BLOCK IoStatusBlock, - IN ULONG IoControlCode, - IN PVOID InputBuffer, - IN ULONG InputBufferLength, - IN PVOID OutputBuffer, - IN ULONG OutputBufferLength - ); - - -NTSYSAPI -NTSTATUS -NTAPI -NtCancelIoFile( - IN HANDLE Filehandle, - OUT PIO_STATUS_BLOCK IoStatusBlock - ); - - -NTSYSAPI -NTSTATUS -NTAPI -ZwCancelIoFile( - IN HANDLE Filehandle, - OUT PIO_STATUS_BLOCK IoStatusBlock - ); - - -NTSYSAPI -BOOLEAN -NTAPI -RtlDosPathNameToNtPathName_U ( - IN PWSTR DosPathName, - OUT PUNICODE_STRING NtPathName, - OUT PWSTR * NtFileNamePart OPTIONAL, - OUT PCURDIR DirectoryInfo OPTIONAL - ); + typedef struct _FILE_PIPE_LOCAL_INFORMATION { + ULONG NamedPipeType; + ULONG NamedPipeConfiguration; + ULONG MaximumInstances; + ULONG CurrentInstances; + ULONG InboundQuota; + ULONG ReadDataAvailable; + ULONG OutboundQuota; + ULONG WriteQuotaAvailable; + ULONG NamedPipeState; + ULONG NamedPipeEnd; + } FILE_PIPE_LOCAL_INFORMATION, * PFILE_PIPE_LOCAL_INFORMATION; -//----------------------------------------------------------------------------- -// Process functions + typedef struct _FILE_PIPE_REMOTE_INFORMATION { + LARGE_INTEGER CollectDataTime; + ULONG MaximumCollectionCount; + } FILE_PIPE_REMOTE_INFORMATION, * PFILE_PIPE_REMOTE_INFORMATION; -#define GDI_HANDLE_BUFFER_SIZE 34 -// -// Process Information Classes -// + typedef struct _FILE_MAILSLOT_QUERY_INFORMATION { + ULONG MaximumMessageSize; + ULONG MailslotQuota; + ULONG NextMessageSize; + ULONG MessagesAvailable; + LARGE_INTEGER ReadTimeout; + } FILE_MAILSLOT_QUERY_INFORMATION, * PFILE_MAILSLOT_QUERY_INFORMATION; -typedef enum _PROCESSINFOCLASS { - ProcessBasicInformation, - ProcessQuotaLimits, - ProcessIoCounters, - ProcessVmCounters, - ProcessTimes, - ProcessBasePriority, - ProcessRaisePriority, - ProcessDebugPort, - ProcessExceptionPort, - ProcessAccessToken, - ProcessLdtInformation, - ProcessLdtSize, - ProcessDefaultHardErrorMode, - ProcessIoPortHandlers, // Note: this is kernel mode only - ProcessPooledUsageAndLimits, - ProcessWorkingSetWatch, - ProcessUserModeIOPL, - ProcessEnableAlignmentFaultFixup, - ProcessPriorityClass, - ProcessWx86Information, - ProcessHandleCount, - ProcessAffinityMask, - ProcessPriorityBoost, - ProcessDeviceMap, - ProcessSessionInformation, - ProcessForegroundInformation, - ProcessWow64Information, - ProcessImageFileName, - ProcessLUIDDeviceMapsEnabled, - ProcessBreakOnTermination, - ProcessDebugObjectHandle, - ProcessDebugFlags, - ProcessHandleTracing, - MaxProcessInfoClass // MaxProcessInfoClass should always be the last enum -} PROCESSINFOCLASS; -// -// Thread Information Classes -// + typedef struct _FILE_MAILSLOT_SET_INFORMATION { + PLARGE_INTEGER ReadTimeout; + } FILE_MAILSLOT_SET_INFORMATION, * PFILE_MAILSLOT_SET_INFORMATION; -typedef enum _THREADINFOCLASS { - ThreadBasicInformation, // ?? - ThreadTimes, - ThreadPriority, // ?? - ThreadBasePriority, // ?? - ThreadAffinityMask, // ?? - ThreadImpersonationToken, // HANDLE - ThreadDescriptorTableEntry, // ULONG Selector + LDT_ENTRY - ThreadEnableAlignmentFaultFixup, // ?? - ThreadEventPair, // ?? - ThreadQuerySetWin32StartAddress, // ?? - ThreadZeroTlsCell, // ?? - ThreadPerformanceCount, // ?? - ThreadAmILastThread, // ?? - ThreadIdealProcessor, // ?? - ThreadPriorityBoost, // ?? - ThreadSetTlsArrayAddress, // ?? - MaxThreadInfoClass -} THREADINFOCLASS; - - -typedef struct _RTL_DRIVE_LETTER_CURDIR -{ - USHORT Flags; - USHORT Length; - ULONG TimeStamp; - STRING DosPath; - -} RTL_DRIVE_LETTER_CURDIR, *PRTL_DRIVE_LETTER_CURDIR; - - -typedef struct _RTL_USER_PROCESS_PARAMETERS -{ - ULONG MaximumLength; // Should be set before call RtlCreateProcessParameters - ULONG Length; // Length of valid structure - ULONG Flags; // Currently only PPF_NORMALIZED (1) is known: - // - Means that structure is normalized by call RtlNormalizeProcessParameters - ULONG DebugFlags; - - PVOID ConsoleHandle; // HWND to console window associated with process (if any). - ULONG ConsoleFlags; - HANDLE StandardInput; - HANDLE StandardOutput; - HANDLE StandardError; - - CURDIR CurrentDirectory; // Specified in DOS-like symbolic link path, ex: "C:/WinNT/SYSTEM32" - UNICODE_STRING DllPath; // DOS-like paths separated by ';' where system should search for DLL files. - UNICODE_STRING ImagePathName; // Full path in DOS-like format to process'es file image. - UNICODE_STRING CommandLine; // Command line - PVOID Environment; // Pointer to environment block (see RtlCreateEnvironment) - ULONG StartingX; - ULONG StartingY; - ULONG CountX; - ULONG CountY; - ULONG CountCharsX; - ULONG CountCharsY; - ULONG FillAttribute; // Fill attribute for console window - ULONG WindowFlags; - ULONG ShowWindowFlags; - UNICODE_STRING WindowTitle; - UNICODE_STRING DesktopInfo; // Name of WindowStation and Desktop objects, where process is assigned - UNICODE_STRING ShellInfo; - UNICODE_STRING RuntimeData; - RTL_DRIVE_LETTER_CURDIR CurrentDirectores[0x20]; - -} RTL_USER_PROCESS_PARAMETERS, *PRTL_USER_PROCESS_PARAMETERS; -// -// Process Environment Block -// + typedef struct _FILE_COMPRESSION_INFORMATION { + LARGE_INTEGER CompressedFileSize; + USHORT CompressionFormat; + UCHAR CompressionUnitShift; + UCHAR ChunkShift; + UCHAR ClusterShift; + UCHAR Reserved[3]; + } FILE_COMPRESSION_INFORMATION, * PFILE_COMPRESSION_INFORMATION; -typedef struct _PEB_FREE_BLOCK -{ - struct _PEB_FREE_BLOCK *Next; - ULONG Size; - -} PEB_FREE_BLOCK, *PPEB_FREE_BLOCK; - - -typedef struct _PEB_LDR_DATA -{ - ULONG Length; - BOOLEAN Initialized; - HANDLE SsHandle; - LIST_ENTRY InLoadOrderModuleList; // Points to the loaded modules (main EXE usually) - LIST_ENTRY InMemoryOrderModuleList; // Points to all modules (EXE and all DLLs) - LIST_ENTRY InInitializationOrderModuleList; - PVOID EntryInProgress; - -} PEB_LDR_DATA, *PPEB_LDR_DATA; - - -typedef struct _LDR_DATA_TABLE_ENTRY -{ - LIST_ENTRY InLoadOrderLinks; - LIST_ENTRY InMemoryOrderLinks; - LIST_ENTRY InInitializationOrderLinks; - PVOID DllBase; // Base address of the module - PVOID EntryPoint; - ULONG SizeOfImage; - UNICODE_STRING FullDllName; - UNICODE_STRING BaseDllName; - ULONG Flags; - USHORT LoadCount; - USHORT TlsIndex; - LIST_ENTRY HashLinks; - PVOID SectionPointer; - ULONG CheckSum; - ULONG TimeDateStamp; - PVOID LoadedImports; - PVOID EntryPointActivationContext; - PVOID PatchInformation; - PVOID Unknown1; - PVOID Unknown2; - PVOID Unknown3; - -} LDR_DATA_TABLE_ENTRY, *PLDR_DATA_TABLE_ENTRY; - - -typedef struct _PEB -{ - BOOLEAN InheritedAddressSpace; // These four fields cannot change unless the - BOOLEAN ReadImageFileExecOptions; // - BOOLEAN BeingDebugged; // - BOOLEAN BitField; // reserved for bitfields with system-specific flags - - HANDLE Mutant; // INITIAL_PEB structure is also updated. - - PVOID ImageBaseAddress; - PPEB_LDR_DATA Ldr; - PRTL_USER_PROCESS_PARAMETERS ProcessParameters; - PVOID SubSystemData; - PVOID ProcessHeap; - PRTL_CRITICAL_SECTION FastPebLock; - - PSLIST_HEADER AtlThunkSListPtr; - PVOID IFEOKey; - ULONG CrossProcessFlags; - union { - PVOID KernelCallbackTable; - PVOID UserSharedInfoPtr; - }; - - DWORD SystemReserved; - DWORD AtlThunkSListPtr32; - PVOID ApiSetMap; - - PVOID TlsExpansionCounter; - PVOID TlsBitmap; - DWORD TlsBitmapBits[2]; // relates to TLS_MINIMUM_AVAILABLE - - PVOID ReadOnlySharedMemoryBase; - PVOID SharedData; - PVOID *ReadOnlyStaticServerData; - PVOID AnsiCodePageData; - PVOID OemCodePageData; - PVOID UnicodeCaseTableData; - // - // Useful information for LdrpInitialize + typedef struct _FILE_LINK_INFORMATION { + BOOLEAN ReplaceIfExists; + HANDLE RootDirectory; + ULONG FileNameLength; + WCHAR FileName[1]; + } FILE_LINK_INFORMATION, * PFILE_LINK_INFORMATION; - ULONG NumberOfProcessors; - ULONG NtGlobalFlag; - // - // Passed up from MmCreatePeb from Session Manager registry key - // + typedef struct _FILE_OBJECTID_INFORMATION + { + LONGLONG FileReference; + UCHAR ObjectId[16]; + union { + struct { + UCHAR BirthVolumeId[16]; + UCHAR BirthObjectId[16]; + UCHAR DomainId[16]; + }; + UCHAR ExtendedInfo[48]; + }; + } FILE_OBJECTID_INFORMATION, * PFILE_OBJECTID_INFORMATION; + + + typedef struct _FILE_COMPLETION_INFORMATION { + HANDLE Port; + PVOID Key; + } FILE_COMPLETION_INFORMATION, * PFILE_COMPLETION_INFORMATION; + + + typedef struct _FILE_MOVE_CLUSTER_INFORMATION { + ULONG ClusterCount; + HANDLE RootDirectory; + ULONG FileNameLength; + WCHAR FileName[1]; + } FILE_MOVE_CLUSTER_INFORMATION, * PFILE_MOVE_CLUSTER_INFORMATION; + + + typedef struct _FILE_NETWORK_OPEN_INFORMATION { + LARGE_INTEGER CreationTime; + LARGE_INTEGER LastAccessTime; + LARGE_INTEGER LastWriteTime; + LARGE_INTEGER ChangeTime; + LARGE_INTEGER AllocationSize; + LARGE_INTEGER EndOfFile; + ULONG FileAttributes; + } FILE_NETWORK_OPEN_INFORMATION, * PFILE_NETWORK_OPEN_INFORMATION; + + + typedef struct _FILE_ATTRIBUTE_TAG_INFORMATION { + ULONG FileAttributes; + ULONG ReparseTag; + } FILE_ATTRIBUTE_TAG_INFORMATION, * PFILE_ATTRIBUTE_TAG_INFORMATION; + + + typedef struct _FILE_TRACKING_INFORMATION { + HANDLE DestinationFile; + ULONG ObjectInformationLength; + CHAR ObjectInformation[1]; + } FILE_TRACKING_INFORMATION, * PFILE_TRACKING_INFORMATION; + + + typedef struct _FILE_REPARSE_POINT_INFORMATION { + LONGLONG FileReference; + ULONG Tag; + } FILE_REPARSE_POINT_INFORMATION, * PFILE_REPARSE_POINT_INFORMATION; + + + typedef struct _FILE_QUOTA_INFORMATION { + ULONG NextEntryOffset; + ULONG SidLength; + LARGE_INTEGER ChangeTime; + LARGE_INTEGER QuotaUsed; + LARGE_INTEGER QuotaThreshold; + LARGE_INTEGER QuotaLimit; + SID Sid; + } FILE_QUOTA_INFORMATION, * PFILE_QUOTA_INFORMATION; + + + typedef struct _FILE_ID_BOTH_DIR_INFORMATION { + ULONG NextEntryOffset; + ULONG FileIndex; + LARGE_INTEGER CreationTime; + LARGE_INTEGER LastAccessTime; + LARGE_INTEGER LastWriteTime; + LARGE_INTEGER ChangeTime; + LARGE_INTEGER EndOfFile; + LARGE_INTEGER AllocationSize; + ULONG FileAttributes; + ULONG FileNameLength; + ULONG EaSize; + CCHAR ShortNameLength; + WCHAR ShortName[12]; + LARGE_INTEGER FileId; + WCHAR FileName[1]; + } FILE_ID_BOTH_DIR_INFORMATION, * PFILE_ID_BOTH_DIR_INFORMATION; + + + typedef struct _FILE_ID_FULL_DIR_INFORMATION { + ULONG NextEntryOffset; + ULONG FileIndex; + LARGE_INTEGER CreationTime; + LARGE_INTEGER LastAccessTime; + LARGE_INTEGER LastWriteTime; + LARGE_INTEGER ChangeTime; + LARGE_INTEGER EndOfFile; + LARGE_INTEGER AllocationSize; + ULONG FileAttributes; + ULONG FileNameLength; + ULONG EaSize; + LARGE_INTEGER FileId; + WCHAR FileName[1]; + } FILE_ID_FULL_DIR_INFORMATION, * PFILE_ID_FULL_DIR_INFORMATION; + + + typedef struct _FILE_VALID_DATA_LENGTH_INFORMATION { + LARGE_INTEGER ValidDataLength; + } FILE_VALID_DATA_LENGTH_INFORMATION, * PFILE_VALID_DATA_LENGTH_INFORMATION; + + typedef struct _FILE_LINK_ENTRY_INFORMATION { + ULONG NextEntryOffset; + LONGLONG ParentFileId; + ULONG FileNameLength; + WCHAR FileName[1]; + } FILE_LINK_ENTRY_INFORMATION, * PFILE_LINK_ENTRY_INFORMATION; + + typedef struct _FILE_LINKS_INFORMATION { + ULONG BytesNeeded; + ULONG EntriesReturned; + FILE_LINK_ENTRY_INFORMATION Entry; + } FILE_LINKS_INFORMATION, * PFILE_LINKS_INFORMATION; + + + + typedef enum _FSINFOCLASS { + FileFsVolumeInformation = 1, + FileFsLabelInformation, // 2 + FileFsSizeInformation, // 3 + FileFsDeviceInformation, // 4 + FileFsAttributeInformation, // 5 + FileFsControlInformation, // 6 + FileFsFullSizeInformation, // 7 + FileFsObjectIdInformation, // 8 + FileFsDriverPathInformation, // 9 + FileFsMaximumInformation + } FS_INFORMATION_CLASS, * PFS_INFORMATION_CLASS; + + + NTSYSAPI + NTSTATUS + NTAPI + NtCreateFile( + OUT PHANDLE FileHandle, + IN ACCESS_MASK DesiredAccess, + IN POBJECT_ATTRIBUTES ObjectAttributes, + OUT PIO_STATUS_BLOCK IoStatusBlock, + IN PLARGE_INTEGER AllocationSize, + IN ULONG FileAttributes, + IN ULONG ShareAccess, + IN ULONG CreateDisposition, + IN ULONG CreateOptions, + IN PVOID EaBuffer, + IN ULONG EaLength); + + + NTSYSAPI + NTSTATUS + NTAPI + ZwCreateFile( + OUT PHANDLE FileHandle, + IN ACCESS_MASK DesiredAccess, + IN POBJECT_ATTRIBUTES ObjectAttributes, + OUT PIO_STATUS_BLOCK IoStatusBlock, + IN PLARGE_INTEGER AllocationSize, + IN ULONG FileAttributes, + IN ULONG ShareAccess, + IN ULONG CreateDisposition, + IN ULONG CreateOptions, + IN PVOID EaBuffer, + IN ULONG EaLength); + + + NTSYSAPI + 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 + ); + + + NTSYSAPI + NTSTATUS + NTAPI + ZwOpenFile( + OUT PHANDLE FileHandle, + IN ACCESS_MASK DesiredAccess, + IN POBJECT_ATTRIBUTES ObjectAttributes, + OUT PIO_STATUS_BLOCK IoStatusBlock, + IN ULONG ShareAccess, + IN ULONG OpenOptions + ); + + + NTSYSAPI + NTSTATUS + NTAPI + NtQueryInformationFile( + IN HANDLE FileHandle, + OUT PIO_STATUS_BLOCK IoStatusBlock, + OUT PVOID FileInformation, + IN ULONG Length, + IN FILE_INFORMATION_CLASS FileInformationClass + ); + + + NTSYSAPI + NTSTATUS + NTAPI + ZwQueryInformationFile( + IN HANDLE FileHandle, + OUT PIO_STATUS_BLOCK IoStatusBlock, + OUT PVOID FileInformation, + IN ULONG Length, + IN FILE_INFORMATION_CLASS FileInformationClass + ); + + + NTSYSAPI + NTSTATUS + NTAPI + NtQueryDirectoryFile( + IN HANDLE FileHandle, + IN HANDLE Event OPTIONAL, + IN PIO_APC_ROUTINE ApcRoutine OPTIONAL, + IN PVOID ApcContext OPTIONAL, + OUT PIO_STATUS_BLOCK IoStatusBlock, + OUT PVOID FileInformation, + IN ULONG Length, + IN FILE_INFORMATION_CLASS FileInformationClass, + IN BOOLEAN ReturnSingleEntry, + IN PUNICODE_STRING FileName OPTIONAL, + IN BOOLEAN RestartScan + ); + + + NTSYSAPI + NTSTATUS + NTAPI + ZwQueryDirectoryFile( + IN HANDLE FileHandle, + IN HANDLE Event OPTIONAL, + IN PIO_APC_ROUTINE ApcRoutine OPTIONAL, + IN PVOID ApcContext OPTIONAL, + OUT PIO_STATUS_BLOCK IoStatusBlock, + OUT PVOID FileInformation, + IN ULONG Length, + IN FILE_INFORMATION_CLASS FileInformationClass, + IN BOOLEAN ReturnSingleEntry, + IN PUNICODE_STRING FileName OPTIONAL, + IN BOOLEAN RestartScan + ); + + + NTSYSAPI + NTSTATUS + NTAPI + NtQueryVolumeInformationFile( + IN HANDLE FileHandle, + OUT PIO_STATUS_BLOCK IoStatusBlock, + OUT PVOID FsInformation, + IN ULONG Length, + IN FS_INFORMATION_CLASS FsInformationClass + ); + + + NTSYSAPI + NTSTATUS + NTAPI + ZwQueryVolumeInformationFile( + IN HANDLE FileHandle, + OUT PIO_STATUS_BLOCK IoStatusBlock, + OUT PVOID FsInformation, + IN ULONG Length, + IN FS_INFORMATION_CLASS FsInformationClass + ); + + + NTSYSAPI + NTSTATUS + NTAPI + NtSetInformationFile( + IN HANDLE FileHandle, + OUT PIO_STATUS_BLOCK IoStatusBlock, + IN PVOID FileInformation, + IN ULONG Length, + IN FILE_INFORMATION_CLASS FileInformationClass + ); + + + NTSYSAPI + NTSTATUS + NTAPI + ZwSetInformationFile( + IN HANDLE FileHandle, + OUT PIO_STATUS_BLOCK IoStatusBlock, + IN PVOID FileInformation, + IN ULONG Length, + IN FILE_INFORMATION_CLASS FileInformationClass + ); + + + NTSYSAPI + NTSTATUS + NTAPI + NtQueryEaFile( + IN HANDLE FileHandle, + OUT PIO_STATUS_BLOCK IoStatusBlock, + OUT PVOID Buffer, + IN ULONG Length, + IN BOOLEAN ReturnSingleEntry, + IN PVOID EaList OPTIONAL, + IN ULONG EaListLength, + IN PULONG EaIndex OPTIONAL, + IN BOOLEAN RestartScan); + + + NTSYSAPI + NTSTATUS + NTAPI + ZwQueryEaFile( + IN HANDLE FileHandle, + OUT PIO_STATUS_BLOCK IoStatusBlock, + OUT PVOID Buffer, + IN ULONG Length, + IN BOOLEAN ReturnSingleEntry, + IN PVOID EaList OPTIONAL, + IN ULONG EaListLength, + IN PULONG EaIndex OPTIONAL, + IN BOOLEAN RestartScan); + + + NTSYSAPI + NTSTATUS + NTAPI + NtSetEaFile( + IN HANDLE FileHandle, + OUT PIO_STATUS_BLOCK IoStatusBlock, + IN PVOID Buffer, + IN ULONG Length); + + + NTSYSAPI + NTSTATUS + NTAPI + ZwSetEaFile( + IN HANDLE FileHandle, + OUT PIO_STATUS_BLOCK IoStatusBlock, + IN PVOID Buffer, + IN ULONG Length); + + + NTSYSAPI + NTSTATUS + NTAPI + NtReadFile( + IN HANDLE FileHandle, + IN HANDLE Event OPTIONAL, + IN PIO_APC_ROUTINE ApcRoutine OPTIONAL, + IN PVOID ApcContext OPTIONAL, + OUT PIO_STATUS_BLOCK IoStatusBlock, + OUT PVOID Buffer, + IN ULONG Length, + IN PLARGE_INTEGER ByteOffset OPTIONAL, + IN PULONG Key OPTIONAL + ); + + + NTSYSAPI + NTSTATUS + NTAPI + ZwReadFile( + IN HANDLE FileHandle, + IN HANDLE Event OPTIONAL, + IN PIO_APC_ROUTINE ApcRoutine OPTIONAL, + IN PVOID ApcContext OPTIONAL, + OUT PIO_STATUS_BLOCK IoStatusBlock, + OUT PVOID Buffer, + IN ULONG Length, + IN PLARGE_INTEGER ByteOffset OPTIONAL, + IN PULONG Key OPTIONAL + ); + + + NTSYSAPI + NTSTATUS + NTAPI + NtWriteFile( + IN HANDLE FileHandle, + IN HANDLE Event OPTIONAL, + IN PIO_APC_ROUTINE ApcRoutine OPTIONAL, + IN PVOID ApcContext OPTIONAL, + OUT PIO_STATUS_BLOCK IoStatusBlock, + IN PVOID Buffer, + IN ULONG Length, + IN PLARGE_INTEGER ByteOffset OPTIONAL, + IN PULONG Key OPTIONAL + ); + + + NTSYSAPI + NTSTATUS + NTAPI + ZwWriteFile( + IN HANDLE FileHandle, + IN HANDLE Event OPTIONAL, + IN PIO_APC_ROUTINE ApcRoutine OPTIONAL, + IN PVOID ApcContext OPTIONAL, + OUT PIO_STATUS_BLOCK IoStatusBlock, + IN PVOID Buffer, + IN ULONG Length, + IN PLARGE_INTEGER ByteOffset OPTIONAL, + IN PULONG Key OPTIONAL + ); + + + NTSYSAPI + NTSTATUS + NTAPI + NtDeleteFile( + IN POBJECT_ATTRIBUTES ObjectAttributes + ); + + + NTSYSAPI + NTSTATUS + NTAPI + ZwDeleteFile( + IN POBJECT_ATTRIBUTES ObjectAttributes + ); + + + NTSYSAPI + NTSTATUS + NTAPI + NtFlushBuffersFile( + IN HANDLE FileHandle, + OUT PIO_STATUS_BLOCK IoStatusBlock + ); + + + NTSYSAPI + NTSTATUS + NTAPI + ZwFlushBuffersFile( + IN HANDLE FileHandle, + OUT PIO_STATUS_BLOCK IoStatusBlock + ); + + + NTSYSAPI + NTSTATUS + NTAPI + NtDeviceIoControlFile( + IN HANDLE FileHandle, + IN HANDLE Event, + IN PIO_APC_ROUTINE ApcRoutine, + IN PVOID ApcContext, + OUT PIO_STATUS_BLOCK IoStatusBlock, + IN ULONG IoControlCode, + IN PVOID InputBuffer, + IN ULONG InputBufferLength, + IN PVOID OutputBuffer, + IN ULONG OutputBufferLength + ); + + + NTSYSAPI + NTSTATUS + NTAPI + ZwDeviceIoControlFile( + IN HANDLE FileHandle, + IN HANDLE Event, + IN PIO_APC_ROUTINE ApcRoutine, + IN PVOID ApcContext, + OUT PIO_STATUS_BLOCK IoStatusBlock, + IN ULONG IoControlCode, + IN PVOID InputBuffer, + IN ULONG InputBufferLength, + IN PVOID OutputBuffer, + IN ULONG OutputBufferLength + ); + + + NTSYSAPI + NTSTATUS + NTAPI + NtCancelIoFile( + IN HANDLE Filehandle, + OUT PIO_STATUS_BLOCK IoStatusBlock + ); + + + NTSYSAPI + NTSTATUS + NTAPI + ZwCancelIoFile( + IN HANDLE Filehandle, + OUT PIO_STATUS_BLOCK IoStatusBlock + ); + + + NTSYSAPI + BOOLEAN + NTAPI + RtlDosPathNameToNtPathName_U( + IN PWSTR DosPathName, + OUT PUNICODE_STRING NtPathName, + OUT PWSTR* NtFileNamePart OPTIONAL, + OUT PCURDIR DirectoryInfo OPTIONAL + ); + + + //----------------------------------------------------------------------------- + // Process functions - LARGE_INTEGER CriticalSectionTimeout; - PVOID HeapSegmentReserve; - PVOID HeapSegmentCommit; - PVOID HeapDeCommitTotalFreeThreshold; - PVOID HeapDeCommitFreeBlockThreshold; +#define GDI_HANDLE_BUFFER_SIZE 34 - // - // Where heap manager keeps track of all heaps created for a process - // Fields initialized by MmCreatePeb. ProcessHeaps is initialized - // to point to the first free byte after the PEB and MaximumNumberOfHeaps - // is computed from the page size used to hold the PEB, less the fixed - // size of this data structure. - // +// +// Process Information Classes +// - DWORD NumberOfHeaps; - DWORD MaximumNumberOfHeaps; - PVOID *ProcessHeaps; + typedef enum _PROCESSINFOCLASS { + ProcessBasicInformation, + ProcessQuotaLimits, + ProcessIoCounters, + ProcessVmCounters, + ProcessTimes, + ProcessBasePriority, + ProcessRaisePriority, + ProcessDebugPort, + ProcessExceptionPort, + ProcessAccessToken, + ProcessLdtInformation, + ProcessLdtSize, + ProcessDefaultHardErrorMode, + ProcessIoPortHandlers, // Note: this is kernel mode only + ProcessPooledUsageAndLimits, + ProcessWorkingSetWatch, + ProcessUserModeIOPL, + ProcessEnableAlignmentFaultFixup, + ProcessPriorityClass, + ProcessWx86Information, + ProcessHandleCount, + ProcessAffinityMask, + ProcessPriorityBoost, + ProcessDeviceMap, + ProcessSessionInformation, + ProcessForegroundInformation, + ProcessWow64Information, + ProcessImageFileName, + ProcessLUIDDeviceMapsEnabled, + ProcessBreakOnTermination, + ProcessDebugObjectHandle, + ProcessDebugFlags, + ProcessHandleTracing, + MaxProcessInfoClass // MaxProcessInfoClass should always be the last enum + } PROCESSINFOCLASS; // + // Thread Information Classes // - PVOID GdiSharedHandleTable; - PVOID ProcessStarterHelper; - PVOID GdiDCAttributeList; - PRTL_CRITICAL_SECTION LoaderLock; + + typedef enum _THREADINFOCLASS { + ThreadBasicInformation, // ?? + ThreadTimes, + ThreadPriority, // ?? + ThreadBasePriority, // ?? + ThreadAffinityMask, // ?? + ThreadImpersonationToken, // HANDLE + ThreadDescriptorTableEntry, // ULONG Selector + LDT_ENTRY + ThreadEnableAlignmentFaultFixup, // ?? + ThreadEventPair, // ?? + ThreadQuerySetWin32StartAddress, // ?? + ThreadZeroTlsCell, // ?? + ThreadPerformanceCount, // ?? + ThreadAmILastThread, // ?? + ThreadIdealProcessor, // ?? + ThreadPriorityBoost, // ?? + ThreadSetTlsArrayAddress, // ?? + MaxThreadInfoClass + } THREADINFOCLASS; + + + typedef struct _RTL_DRIVE_LETTER_CURDIR + { + USHORT Flags; + USHORT Length; + ULONG TimeStamp; + STRING DosPath; + + } RTL_DRIVE_LETTER_CURDIR, * PRTL_DRIVE_LETTER_CURDIR; + + + typedef struct _RTL_USER_PROCESS_PARAMETERS + { + ULONG MaximumLength; // Should be set before call RtlCreateProcessParameters + ULONG Length; // Length of valid structure + ULONG Flags; // Currently only PPF_NORMALIZED (1) is known: + // - Means that structure is normalized by call RtlNormalizeProcessParameters + ULONG DebugFlags; + + PVOID ConsoleHandle; // HWND to console window associated with process (if any). + ULONG ConsoleFlags; + HANDLE StandardInput; + HANDLE StandardOutput; + HANDLE StandardError; + + CURDIR CurrentDirectory; // Specified in DOS-like symbolic link path, ex: "C:/WinNT/SYSTEM32" + UNICODE_STRING DllPath; // DOS-like paths separated by ';' where system should search for DLL files. + UNICODE_STRING ImagePathName; // Full path in DOS-like format to process'es file image. + UNICODE_STRING CommandLine; // Command line + PVOID Environment; // Pointer to environment block (see RtlCreateEnvironment) + ULONG StartingX; + ULONG StartingY; + ULONG CountX; + ULONG CountY; + ULONG CountCharsX; + ULONG CountCharsY; + ULONG FillAttribute; // Fill attribute for console window + ULONG WindowFlags; + ULONG ShowWindowFlags; + UNICODE_STRING WindowTitle; + UNICODE_STRING DesktopInfo; // Name of WindowStation and Desktop objects, where process is assigned + UNICODE_STRING ShellInfo; + UNICODE_STRING RuntimeData; + RTL_DRIVE_LETTER_CURDIR CurrentDirectores[0x20]; + + } RTL_USER_PROCESS_PARAMETERS, * PRTL_USER_PROCESS_PARAMETERS; // - // Following fields filled in by MmCreatePeb from system values and/or - // image header. These fields have changed since Windows NT 4.0, - // so use with caution + // Process Environment Block // - DWORD OSMajorVersion; - DWORD OSMinorVersion; - USHORT OSBuildNumber; - USHORT OSCSDVersion; - DWORD OSPlatformId; - DWORD ImageSubsystem; - DWORD ImageSubsystemMajorVersion; + typedef struct _PEB_FREE_BLOCK + { + struct _PEB_FREE_BLOCK* Next; + ULONG Size; - PVOID ImageSubsystemMinorVersion; - PVOID ImageProcessAffinityMask; - PVOID GdiHandleBuffer[GDI_HANDLE_BUFFER_SIZE]; + } PEB_FREE_BLOCK, * PPEB_FREE_BLOCK; - // [...] - more fields are there: this is just a fragment of the PEB structure -} PEB, *PPEB; + typedef struct _PEB_LDR_DATA + { + ULONG Length; + BOOLEAN Initialized; + HANDLE SsHandle; + LIST_ENTRY InLoadOrderModuleList; // Points to the loaded modules (main EXE usually) + LIST_ENTRY InMemoryOrderModuleList; // Points to all modules (EXE and all DLLs) + LIST_ENTRY InInitializationOrderModuleList; + PVOID EntryInProgress; -// -// Thread environment block -// + } PEB_LDR_DATA, * PPEB_LDR_DATA; -typedef struct _TEB -{ - NT_TIB NtTib; - PVOID EnvironmentPointer; - CLIENT_ID ClientId; - PVOID ActiveRpcHandle; - PVOID ThreadLocalStoragePointer; - PPEB ProcessEnvironmentBlock; - ULONG LastErrorValue; - ULONG CountOfOwnedCriticalSections; - PVOID CsrClientThread; - PVOID Win32ThreadInfo; - // Incomplete -} TEB, *PTEB; + typedef struct _LDR_DATA_TABLE_ENTRY + { + LIST_ENTRY InLoadOrderLinks; + LIST_ENTRY InMemoryOrderLinks; + LIST_ENTRY InInitializationOrderLinks; + PVOID DllBase; // Base address of the module + PVOID EntryPoint; + ULONG SizeOfImage; + UNICODE_STRING FullDllName; + UNICODE_STRING BaseDllName; + ULONG Flags; + USHORT LoadCount; + USHORT TlsIndex; + LIST_ENTRY HashLinks; + PVOID SectionPointer; + ULONG CheckSum; + ULONG TimeDateStamp; + PVOID LoadedImports; + PVOID EntryPointActivationContext; + PVOID PatchInformation; + PVOID Unknown1; + PVOID Unknown2; + PVOID Unknown3; + + } LDR_DATA_TABLE_ENTRY, * PLDR_DATA_TABLE_ENTRY; + + + typedef struct _PEB + { + BOOLEAN InheritedAddressSpace; // These four fields cannot change unless the + BOOLEAN ReadImageFileExecOptions; // + BOOLEAN BeingDebugged; // + BOOLEAN BitField; // reserved for bitfields with system-specific flags + + HANDLE Mutant; // INITIAL_PEB structure is also updated. + + PVOID ImageBaseAddress; + PPEB_LDR_DATA Ldr; + PRTL_USER_PROCESS_PARAMETERS ProcessParameters; + PVOID SubSystemData; + PVOID ProcessHeap; + PRTL_CRITICAL_SECTION FastPebLock; + + PSLIST_HEADER AtlThunkSListPtr; + PVOID IFEOKey; + ULONG CrossProcessFlags; + union { + PVOID KernelCallbackTable; + PVOID UserSharedInfoPtr; + }; + + DWORD SystemReserved; + DWORD AtlThunkSListPtr32; + PVOID ApiSetMap; + + PVOID TlsExpansionCounter; + PVOID TlsBitmap; + DWORD TlsBitmapBits[2]; // relates to TLS_MINIMUM_AVAILABLE + + PVOID ReadOnlySharedMemoryBase; + PVOID SharedData; + PVOID* ReadOnlyStaticServerData; + PVOID AnsiCodePageData; + PVOID OemCodePageData; + PVOID UnicodeCaseTableData; + + // + // Useful information for LdrpInitialize + + ULONG NumberOfProcessors; + ULONG NtGlobalFlag; + + // + // Passed up from MmCreatePeb from Session Manager registry key + // + + LARGE_INTEGER CriticalSectionTimeout; + PVOID HeapSegmentReserve; + PVOID HeapSegmentCommit; + PVOID HeapDeCommitTotalFreeThreshold; + PVOID HeapDeCommitFreeBlockThreshold; + + // + // Where heap manager keeps track of all heaps created for a process + // Fields initialized by MmCreatePeb. ProcessHeaps is initialized + // to point to the first free byte after the PEB and MaximumNumberOfHeaps + // is computed from the page size used to hold the PEB, less the fixed + // size of this data structure. + // + + DWORD NumberOfHeaps; + DWORD MaximumNumberOfHeaps; + PVOID* ProcessHeaps; + + // + // + PVOID GdiSharedHandleTable; + PVOID ProcessStarterHelper; + PVOID GdiDCAttributeList; + PRTL_CRITICAL_SECTION LoaderLock; + + // + // Following fields filled in by MmCreatePeb from system values and/or + // image header. These fields have changed since Windows NT 4.0, + // so use with caution + // + + DWORD OSMajorVersion; + DWORD OSMinorVersion; + USHORT OSBuildNumber; + USHORT OSCSDVersion; + DWORD OSPlatformId; + DWORD ImageSubsystem; + DWORD ImageSubsystemMajorVersion; + + PVOID ImageSubsystemMinorVersion; + PVOID ImageProcessAffinityMask; + PVOID GdiHandleBuffer[GDI_HANDLE_BUFFER_SIZE]; + + // [...] - more fields are there: this is just a fragment of the PEB structure + } PEB, * PPEB; -typedef struct _PROCESS_BASIC_INFORMATION -{ - NTSTATUS ExitStatus; - PPEB PebBaseAddress; - ULONG_PTR AffinityMask; - KPRIORITY BasePriority; - ULONG_PTR UniqueProcessId; - ULONG_PTR InheritedFromUniqueProcessId; + // + // Thread environment block + // -} PROCESS_BASIC_INFORMATION,*PPROCESS_BASIC_INFORMATION; + typedef struct _TEB + { + NT_TIB NtTib; + PVOID EnvironmentPointer; + CLIENT_ID ClientId; + PVOID ActiveRpcHandle; + PVOID ThreadLocalStoragePointer; + PPEB ProcessEnvironmentBlock; + ULONG LastErrorValue; + ULONG CountOfOwnedCriticalSections; + PVOID CsrClientThread; + PVOID Win32ThreadInfo; + // Incomplete + + } TEB, * PTEB; + + + typedef struct _PROCESS_BASIC_INFORMATION + { + NTSTATUS ExitStatus; + PPEB PebBaseAddress; + ULONG_PTR AffinityMask; + KPRIORITY BasePriority; + ULONG_PTR UniqueProcessId; + ULONG_PTR InheritedFromUniqueProcessId; + + } PROCESS_BASIC_INFORMATION, * PPROCESS_BASIC_INFORMATION; #define NtCurrentProcess() ((HANDLE) -1) #define NtCurrentThread() ((HANDLE) -2) -NTSYSAPI -NTSTATUS -NTAPI -NtOpenProcess ( - OUT PHANDLE ProcessHandle, - IN ACCESS_MASK DesiredAccess, - IN POBJECT_ATTRIBUTES ObjectAttributes, - IN PCLIENT_ID ClientId OPTIONAL - ); - -NTSYSCALLAPI - NTSTATUS - NTAPI - NtSuspendProcess( - IN HANDLE ProcessHandle - ); - -NTSYSCALLAPI - NTSTATUS - NTAPI - NtResumeProcess( - IN HANDLE ProcessHandle - ); - -NTSYSAPI -NTSTATUS -NTAPI -NtOpenThread ( - OUT PHANDLE ThreadHandle, - IN ACCESS_MASK DesiredAccess, - IN POBJECT_ATTRIBUTES ObjectAttributes, - IN PCLIENT_ID ClientId OPTIONAL - ); - -NTSYSAPI - NTSTATUS - NTAPI - NtQueryInformationThread( - IN HANDLE ThreadHandle, - IN THREADINFOCLASS ThreadInformationClass, - OUT PVOID ThreadInformation, - IN ULONG ThreadInformationLength, - OUT PULONG ReturnLength OPTIONAL - ); - -NTSYSAPI -NTSTATUS -NTAPI -NtQueryInformationProcess( - IN HANDLE ProcessHandle, - IN PROCESSINFOCLASS ProcessInformationClass, - OUT PVOID ProcessInformation, - IN ULONG ProcessInformationLength, - OUT PULONG ReturnLength OPTIONAL - ); - - -NTSYSAPI -NTSTATUS -NTAPI -NtSetInformationProcess ( - IN HANDLE ProcessHandle, - IN PROCESSINFOCLASS ProcessInformationClass, - IN PVOID ProcessInformation, - IN ULONG ProcessInformationLength - ); - -//------------------------------------------------------------------------------ -// LPC Functions +#define NtCurrentPeb() (NtCurrentTeb()->ProcessEnvironmentBlock) + + NTSYSAPI + NTSTATUS + NTAPI + NtOpenProcess( + OUT PHANDLE ProcessHandle, + IN ACCESS_MASK DesiredAccess, + IN POBJECT_ATTRIBUTES ObjectAttributes, + IN PCLIENT_ID ClientId OPTIONAL + ); + + NTSYSCALLAPI + NTSTATUS + NTAPI + NtSuspendProcess( + IN HANDLE ProcessHandle + ); + + NTSYSCALLAPI + NTSTATUS + NTAPI + NtResumeProcess( + IN HANDLE ProcessHandle + ); + + NTSYSAPI + NTSTATUS + NTAPI + NtOpenThread( + OUT PHANDLE ThreadHandle, + IN ACCESS_MASK DesiredAccess, + IN POBJECT_ATTRIBUTES ObjectAttributes, + IN PCLIENT_ID ClientId OPTIONAL + ); + + NTSYSAPI + NTSTATUS + NTAPI + NtQueryInformationThread( + IN HANDLE ThreadHandle, + IN THREADINFOCLASS ThreadInformationClass, + OUT PVOID ThreadInformation, + IN ULONG ThreadInformationLength, + OUT PULONG ReturnLength OPTIONAL + ); + + NTSYSAPI + NTSTATUS + NTAPI + NtQueryInformationProcess( + IN HANDLE ProcessHandle, + IN PROCESSINFOCLASS ProcessInformationClass, + OUT PVOID ProcessInformation, + IN ULONG ProcessInformationLength, + OUT PULONG ReturnLength OPTIONAL + ); + + + NTSYSAPI + NTSTATUS + NTAPI + NtSetInformationProcess( + IN HANDLE ProcessHandle, + IN PROCESSINFOCLASS ProcessInformationClass, + IN PVOID ProcessInformation, + IN ULONG ProcessInformationLength + ); + + //------------------------------------------------------------------------------ + // LPC Functions #define MAX_LPC_DATA 0x130 // Maximum number of bytes that can be copied through LPC // LPC connection types -typedef enum _LPC_TYPE -{ - LPC_NEW_MESSAGE, // (0) A new message - LPC_REQUEST, // (1) A request message - LPC_REPLY, // (2) A reply to a request message - LPC_DATAGRAM, // (3) - LPC_LOST_REPLY, // (4) - LPC_PORT_CLOSED, // (5) Send when port is deleted - LPC_CLIENT_DIED, // (6) Messages to thread termination ports - LPC_EXCEPTION, // (7) Messages to thread exception ports - LPC_DEBUG_EVENT, // (8) Messages to thread debug port - LPC_ERROR_EVENT, // (9) Used by NtRaiseHardError - LPC_CONNECTION_REQUEST // (A) Used by NtConnectPort - -} LPC_TYPE, *PLPC_TYPE; + typedef enum _LPC_TYPE + { + LPC_NEW_MESSAGE, // (0) A new message + LPC_REQUEST, // (1) A request message + LPC_REPLY, // (2) A reply to a request message + LPC_DATAGRAM, // (3) + LPC_LOST_REPLY, // (4) + LPC_PORT_CLOSED, // (5) Send when port is deleted + LPC_CLIENT_DIED, // (6) Messages to thread termination ports + LPC_EXCEPTION, // (7) Messages to thread exception ports + LPC_DEBUG_EVENT, // (8) Messages to thread debug port + LPC_ERROR_EVENT, // (9) Used by NtRaiseHardError + LPC_CONNECTION_REQUEST // (A) Used by NtConnectPort + + } LPC_TYPE, * PLPC_TYPE; -// -// Define header for Port Message -// + // + // Define header for Port Message + // -typedef struct _PORT_MESSAGE -{ - USHORT DataLength; // Length of data following the header (bytes) - USHORT TotalLength; // Length of data + sizeof(PORT_MESSAGE) - USHORT Type; // Type of the message (See LPC_TYPE enum) - USHORT VirtualRangesOffset; // Offset of array of virtual address ranges - CLIENT_ID ClientId; // Client identifier of the message sender - ULONG MessageId; // Identifier of the particular message instance - union + typedef struct _PORT_MESSAGE { - ULONG CallbackId; // - ULONG ClientViewSize; // Size, in bytes, of section created by the sender - }; - -} PORT_MESSAGE, *PPORT_MESSAGE; + USHORT DataLength; // Length of data following the header (bytes) + USHORT TotalLength; // Length of data + sizeof(PORT_MESSAGE) + USHORT Type; // Type of the message (See LPC_TYPE enum) + USHORT VirtualRangesOffset; // Offset of array of virtual address ranges + CLIENT_ID ClientId; // Client identifier of the message sender + ULONG MessageId; // Identifier of the particular message instance + union + { + ULONG CallbackId; // + ULONG ClientViewSize; // Size, in bytes, of section created by the sender + }; + + } PORT_MESSAGE, * PPORT_MESSAGE; -// -// Define structure for initializing shared memory on the caller's side of the port -// + // + // Define structure for initializing shared memory on the caller's side of the port + // -typedef struct _PORT_VIEW { - - ULONG Length; // Size of this structure - HANDLE SectionHandle; // Handle to section object with - // SECTION_MAP_WRITE and SECTION_MAP_READ - ULONG SectionOffset; // The offset in the section to map a view for - // the port data area. The offset must be aligned - // with the allocation granularity of the system. - ULONG ViewSize; // The size of the view (in bytes) - PVOID ViewBase; // The base address of the view in the creator - // - PVOID ViewRemoteBase; // The base address of the view in the process - // connected to the port. -} PORT_VIEW, *PPORT_VIEW; + typedef struct _PORT_VIEW { + + ULONG Length; // Size of this structure + HANDLE SectionHandle; // Handle to section object with + // SECTION_MAP_WRITE and SECTION_MAP_READ + ULONG SectionOffset; // The offset in the section to map a view for + // the port data area. The offset must be aligned + // with the allocation granularity of the system. + ULONG ViewSize; // The size of the view (in bytes) + PVOID ViewBase; // The base address of the view in the creator + // + PVOID ViewRemoteBase; // The base address of the view in the process + // connected to the port. + } PORT_VIEW, * PPORT_VIEW; -// -// Define structure for shared memory coming from remote side of the port -// + // + // Define structure for shared memory coming from remote side of the port + // -typedef struct _REMOTE_PORT_VIEW { + typedef struct _REMOTE_PORT_VIEW { - ULONG Length; // Size of this structure - ULONG ViewSize; // The size of the view (bytes) - PVOID ViewBase; // Base address of the view + ULONG Length; // Size of this structure + ULONG ViewSize; // The size of the view (bytes) + PVOID ViewBase; // Base address of the view -} REMOTE_PORT_VIEW, *PREMOTE_PORT_VIEW; + } REMOTE_PORT_VIEW, * PREMOTE_PORT_VIEW; -/*++ + /*++ - NtCreatePort - ============ + NtCreatePort + ============ - Creates a LPC port object. The creator of the LPC port becomes a server - of LPC communication + Creates a LPC port object. The creator of the LPC port becomes a server + of LPC communication - PortHandle - Points to a variable that will receive the - port object handle if the call is successful. + PortHandle - Points to a variable that will receive the + port object handle if the call is successful. - ObjectAttributes - Points to a structure that specifies the object s - attributes. OBJ_KERNEL_HANDLE, OBJ_OPENLINK, OBJ_OPENIF, OBJ_EXCLUSIVE, - OBJ_PERMANENT, and OBJ_INHERIT are not valid attributes for a port object. + ObjectAttributes - Points to a structure that specifies the object s + attributes. OBJ_KERNEL_HANDLE, OBJ_OPENLINK, OBJ_OPENIF, OBJ_EXCLUSIVE, + OBJ_PERMANENT, and OBJ_INHERIT are not valid attributes for a port object. - MaxConnectionInfoLength - The maximum size, in bytes, of data that can - be sent through the port. + MaxConnectionInfoLength - The maximum size, in bytes, of data that can + be sent through the port. - MaxMessageLength - The maximum size, in bytes, of a message - that can be sent through the port. + MaxMessageLength - The maximum size, in bytes, of a message + that can be sent through the port. - MaxPoolUsage - Specifies the maximum amount of NonPaged pool that can be used for - message storage. Zero means default value. + MaxPoolUsage - Specifies the maximum amount of NonPaged pool that can be used for + message storage. Zero means default value. - ZwCreatePort verifies that (MaxDataSize <= 0x104) and (MaxMessageSize <= 0x148). + ZwCreatePort verifies that (MaxDataSize <= 0x104) and (MaxMessageSize <= 0x148). ---*/ + --*/ -NTSYSAPI -NTSTATUS -NTAPI -NtCreatePort( - OUT PHANDLE PortHandle, - IN POBJECT_ATTRIBUTES ObjectAttributes, - IN ULONG MaxConnectionInfoLength, - IN ULONG MaxMessageLength, - IN ULONG MaxPoolUsage - ); + NTSYSAPI + NTSTATUS + NTAPI + NtCreatePort( + OUT PHANDLE PortHandle, + IN POBJECT_ATTRIBUTES ObjectAttributes, + IN ULONG MaxConnectionInfoLength, + IN ULONG MaxMessageLength, + IN ULONG MaxPoolUsage + ); -/*++ + /*++ - NtConnectPort - ============= + NtConnectPort + ============= - Creates a port connected to a named port (cliend side). + Creates a port connected to a named port (cliend side). - PortHandle - A pointer to a variable that will receive the client - communication port object handle value. + PortHandle - A pointer to a variable that will receive the client + communication port object handle value. - PortName - Points to a structure that specifies the name - of the port to connect to. + PortName - Points to a structure that specifies the name + of the port to connect to. - SecurityQos - Points to a structure that specifies the level - of impersonation available to the port listener. + SecurityQos - Points to a structure that specifies the level + of impersonation available to the port listener. - ClientView - Optionally points to a structure describing - the shared memory region used to send large amounts of data - to the listener; if the call is successful, this will be updated. + ClientView - Optionally points to a structure describing + the shared memory region used to send large amounts of data + to the listener; if the call is successful, this will be updated. - ServerView - Optionally points to a caller-allocated buffer - or variable that receives information on the shared memory region - used by the listener to send large amounts of data to the - caller. + ServerView - Optionally points to a caller-allocated buffer + or variable that receives information on the shared memory region + used by the listener to send large amounts of data to the + caller. - MaxMessageLength - Optionally points to a variable that receives the size, - in bytes, of the largest message that can be sent through the port. + MaxMessageLength - Optionally points to a variable that receives the size, + in bytes, of the largest message that can be sent through the port. - ConnectionInformation - Optionally points to a caller-allocated - buffer or variable that specifies connect data to send to the listener, - and receives connect data sent by the listener. + ConnectionInformation - Optionally points to a caller-allocated + buffer or variable that specifies connect data to send to the listener, + and receives connect data sent by the listener. - ConnectionInformationLength - Optionally points to a variable that - specifies the size, in bytes, of the connect data to send - to the listener, and receives the size of the connect data - sent by the listener. + ConnectionInformationLength - Optionally points to a variable that + specifies the size, in bytes, of the connect data to send + to the listener, and receives the size of the connect data + sent by the listener. ---*/ + --*/ -NTSYSAPI -NTSTATUS -NTAPI -NtConnectPort( - OUT PHANDLE PortHandle, - IN PUNICODE_STRING PortName, - IN PSECURITY_QUALITY_OF_SERVICE SecurityQos, - IN OUT PPORT_VIEW ClientView OPTIONAL, - OUT PREMOTE_PORT_VIEW ServerView OPTIONAL, - OUT PULONG MaxMessageLength OPTIONAL, - IN OUT PVOID ConnectionInformation OPTIONAL, - IN OUT PULONG ConnectionInformationLength OPTIONAL - ); + NTSYSAPI + NTSTATUS + NTAPI + NtConnectPort( + OUT PHANDLE PortHandle, + IN PUNICODE_STRING PortName, + IN PSECURITY_QUALITY_OF_SERVICE SecurityQos, + IN OUT PPORT_VIEW ClientView OPTIONAL, + OUT PREMOTE_PORT_VIEW ServerView OPTIONAL, + OUT PULONG MaxMessageLength OPTIONAL, + IN OUT PVOID ConnectionInformation OPTIONAL, + IN OUT PULONG ConnectionInformationLength OPTIONAL + ); -NTSYSAPI -NTSTATUS -NTAPI -ZwConnectPort( - OUT PHANDLE PortHandle, - IN PUNICODE_STRING PortName, - IN PSECURITY_QUALITY_OF_SERVICE SecurityQos, - IN OUT PPORT_VIEW ClientView OPTIONAL, - OUT PREMOTE_PORT_VIEW ServerView OPTIONAL, - OUT PULONG MaxMessageLength OPTIONAL, - IN OUT PVOID ConnectionInformation OPTIONAL, - IN OUT PULONG ConnectionInformationLength OPTIONAL - ); + NTSYSAPI + NTSTATUS + NTAPI + ZwConnectPort( + OUT PHANDLE PortHandle, + IN PUNICODE_STRING PortName, + IN PSECURITY_QUALITY_OF_SERVICE SecurityQos, + IN OUT PPORT_VIEW ClientView OPTIONAL, + OUT PREMOTE_PORT_VIEW ServerView OPTIONAL, + OUT PULONG MaxMessageLength OPTIONAL, + IN OUT PVOID ConnectionInformation OPTIONAL, + IN OUT PULONG ConnectionInformationLength OPTIONAL + ); -/*++ + /*++ - NtListenPort - ============ + NtListenPort + ============ - Listens on a port for a connection request message on the server side. + Listens on a port for a connection request message on the server side. - PortHandle - A handle to a port object. The handle doesn't need - to grant any specific access. + PortHandle - A handle to a port object. The handle doesn't need + to grant any specific access. - ConnectionRequest - Points to a caller-allocated buffer - or variable that receives the connect message sent to - the port. + ConnectionRequest - Points to a caller-allocated buffer + or variable that receives the connect message sent to + the port. ---*/ + --*/ -NTSYSAPI -NTSTATUS -NTAPI -NtListenPort( - IN HANDLE PortHandle, - OUT PPORT_MESSAGE RequestMessage - ); + NTSYSAPI + NTSTATUS + NTAPI + NtListenPort( + IN HANDLE PortHandle, + OUT PPORT_MESSAGE RequestMessage + ); -/*++ + /*++ - NtAcceptConnectPort - =================== + NtAcceptConnectPort + =================== - Accepts or rejects a connection request on the server side. + Accepts or rejects a connection request on the server side. - PortHandle - Points to a variable that will receive the port object - handle if the call is successful. + PortHandle - Points to a variable that will receive the port object + handle if the call is successful. - PortContext - A numeric identifier to be associated with the port. + PortContext - A numeric identifier to be associated with the port. - ConnectionRequest - Points to a caller-allocated buffer or variable - that identifies the connection request and contains any connect - data that should be returned to requestor of the connection + ConnectionRequest - Points to a caller-allocated buffer or variable + that identifies the connection request and contains any connect + data that should be returned to requestor of the connection - AcceptConnection - Specifies whether the connection should - be accepted or not + AcceptConnection - Specifies whether the connection should + be accepted or not - ServerView - Optionally points to a structure describing - the shared memory region used to send large amounts of data to the - requestor; if the call is successful, this will be updated + ServerView - Optionally points to a structure describing + the shared memory region used to send large amounts of data to the + requestor; if the call is successful, this will be updated - ClientView - Optionally points to a caller-allocated buffer - or variable that receives information on the shared memory - region used by the requestor to send large amounts of data to the - caller + ClientView - Optionally points to a caller-allocated buffer + or variable that receives information on the shared memory + region used by the requestor to send large amounts of data to the + caller ---*/ + --*/ -NTSYSAPI -NTSTATUS -NTAPI -NtAcceptConnectPort( - OUT PHANDLE PortHandle, - IN PVOID PortContext OPTIONAL, - IN PPORT_MESSAGE ConnectionRequest, - IN BOOLEAN AcceptConnection, - IN OUT PPORT_VIEW ServerView OPTIONAL, - OUT PREMOTE_PORT_VIEW ClientView OPTIONAL - ); + NTSYSAPI + NTSTATUS + NTAPI + NtAcceptConnectPort( + OUT PHANDLE PortHandle, + IN PVOID PortContext OPTIONAL, + IN PPORT_MESSAGE ConnectionRequest, + IN BOOLEAN AcceptConnection, + IN OUT PPORT_VIEW ServerView OPTIONAL, + OUT PREMOTE_PORT_VIEW ClientView OPTIONAL + ); -/*++ + /*++ - NtCompleteConnectPort - ===================== + NtCompleteConnectPort + ===================== - Completes the port connection process on the server side. + Completes the port connection process on the server side. - PortHandle - A handle to a port object. The handle doesn't need - to grant any specific access. + PortHandle - A handle to a port object. The handle doesn't need + to grant any specific access. ---*/ + --*/ -NTSYSAPI -NTSTATUS -NTAPI -NtCompleteConnectPort( - IN HANDLE PortHandle - ); + NTSYSAPI + NTSTATUS + NTAPI + NtCompleteConnectPort( + IN HANDLE PortHandle + ); -NTSYSAPI -NTSTATUS -NTAPI -ZwCompleteConnectPort( - IN HANDLE PortHandle - ); + NTSYSAPI + NTSTATUS + NTAPI + ZwCompleteConnectPort( + IN HANDLE PortHandle + ); -/*++ + /*++ - NtRequestPort - ============= + NtRequestPort + ============= - Sends a request message to a port (client side) + Sends a request message to a port (client side) - PortHandle - A handle to a port object. The handle doesn't need - to grant any specific access. + PortHandle - A handle to a port object. The handle doesn't need + to grant any specific access. - RequestMessage - Points to a caller-allocated buffer or variable - that specifies the request message to send to the port. + RequestMessage - Points to a caller-allocated buffer or variable + that specifies the request message to send to the port. ---*/ + --*/ -NTSYSAPI -NTSTATUS -NTAPI -NtRequestPort ( - IN HANDLE PortHandle, - IN PPORT_MESSAGE RequestMessage - ); + NTSYSAPI + NTSTATUS + NTAPI + NtRequestPort( + IN HANDLE PortHandle, + IN PPORT_MESSAGE RequestMessage + ); -/*++ + /*++ - NtRequestWaitReplyPort - ====================== + NtRequestWaitReplyPort + ====================== - Sends a request message to a port and waits for a reply (client side) + Sends a request message to a port and waits for a reply (client side) - PortHandle - A handle to a port object. The handle doesn't need - to grant any specific access. + PortHandle - A handle to a port object. The handle doesn't need + to grant any specific access. - RequestMessage - Points to a caller-allocated buffer or variable - that specifies the request message to send to the port. + RequestMessage - Points to a caller-allocated buffer or variable + that specifies the request message to send to the port. - ReplyMessage - Points to a caller-allocated buffer or variable - that receives the reply message sent to the port. + ReplyMessage - Points to a caller-allocated buffer or variable + that receives the reply message sent to the port. ---*/ + --*/ -NTSYSAPI -NTSTATUS -NTAPI -NtRequestWaitReplyPort( - IN HANDLE PortHandle, - IN PPORT_MESSAGE RequestMessage, - OUT PPORT_MESSAGE ReplyMessage - ); + NTSYSAPI + NTSTATUS + NTAPI + NtRequestWaitReplyPort( + IN HANDLE PortHandle, + IN PPORT_MESSAGE RequestMessage, + OUT PPORT_MESSAGE ReplyMessage + ); -NTSYSAPI -NTSTATUS -NTAPI -ZwRequestWaitReplyPort( - IN HANDLE PortHandle, - IN PPORT_MESSAGE RequestMessage, - OUT PPORT_MESSAGE ReplyMessage - ); + NTSYSAPI + NTSTATUS + NTAPI + ZwRequestWaitReplyPort( + IN HANDLE PortHandle, + IN PPORT_MESSAGE RequestMessage, + OUT PPORT_MESSAGE ReplyMessage + ); -/*++ + /*++ - NtReplyPort - =========== + NtReplyPort + =========== - Sends a reply message to a port (Server side) + Sends a reply message to a port (Server side) - PortHandle - A handle to a port object. The handle doesn't need - to grant any specific access. + PortHandle - A handle to a port object. The handle doesn't need + to grant any specific access. - ReplyMessage - Points to a caller-allocated buffer or variable - that specifies the reply message to send to the port. + ReplyMessage - Points to a caller-allocated buffer or variable + that specifies the reply message to send to the port. ---*/ + --*/ -NTSYSAPI -NTSTATUS -NTAPI -NtReplyPort( - IN HANDLE PortHandle, - IN PPORT_MESSAGE ReplyMessage - ); + NTSYSAPI + NTSTATUS + NTAPI + NtReplyPort( + IN HANDLE PortHandle, + IN PPORT_MESSAGE ReplyMessage + ); -/*++ + /*++ - NtReplyWaitReplyPort - ==================== + NtReplyWaitReplyPort + ==================== - Sends a reply message to a port and waits for a reply message + Sends a reply message to a port and waits for a reply message - PortHandle - A handle to a port object. The handle doesn't need - to grant any specific access. + PortHandle - A handle to a port object. The handle doesn't need + to grant any specific access. - ReplyMessage - Points to a caller-allocated buffer or variable - that specifies the reply message to send to the port. + ReplyMessage - Points to a caller-allocated buffer or variable + that specifies the reply message to send to the port. ---*/ + --*/ -NTSYSAPI -NTSTATUS -NTAPI -NtReplyWaitReplyPort( - IN HANDLE PortHandle, - IN OUT PPORT_MESSAGE ReplyMessage - ); + NTSYSAPI + NTSTATUS + NTAPI + NtReplyWaitReplyPort( + IN HANDLE PortHandle, + IN OUT PPORT_MESSAGE ReplyMessage + ); -/*++ + /*++ - NtReplyWaitReceivePort - ====================== + NtReplyWaitReceivePort + ====================== - Optionally sends a reply message to a port and waits for a - message + Optionally sends a reply message to a port and waits for a + message - PortHandle - A handle to a port object. The handle doesn't need - to grant any specific access. + PortHandle - A handle to a port object. The handle doesn't need + to grant any specific access. - PortContext - Optionally points to a variable that receives - a numeric identifier associated with the port. + PortContext - Optionally points to a variable that receives + a numeric identifier associated with the port. - ReplyMessage - Optionally points to a caller-allocated buffer - or variable that specifies the reply message to send to the port. + ReplyMessage - Optionally points to a caller-allocated buffer + or variable that specifies the reply message to send to the port. - ReceiveMessage - Points to a caller-allocated buffer or variable - that receives the message sent to the port. + ReceiveMessage - Points to a caller-allocated buffer or variable + that receives the message sent to the port. ---*/ + --*/ -NTSYSAPI -NTSTATUS -NTAPI -NtReplyWaitReceivePort( - IN HANDLE PortHandle, - OUT PVOID *PortContext OPTIONAL, - IN PPORT_MESSAGE ReplyMessage OPTIONAL, - OUT PPORT_MESSAGE ReceiveMessage - ); + NTSYSAPI + NTSTATUS + NTAPI + NtReplyWaitReceivePort( + IN HANDLE PortHandle, + OUT PVOID* PortContext OPTIONAL, + IN PPORT_MESSAGE ReplyMessage OPTIONAL, + OUT PPORT_MESSAGE ReceiveMessage + ); -//----------------------------------------------------------------------------- -// Heap functions + //----------------------------------------------------------------------------- + // Heap functions #define HEAP_NO_SERIALIZE 0x00000001 #define HEAP_GROWABLE 0x00000002 @@ -3336,961 +3347,1176 @@ NtReplyWaitReceivePort( // result in default behavior // -typedef struct RTL_HEAP_PARAMETERS { - ULONG Length; //sizeof(RTL_HEAP_PARAMETERS) - ULONG SegmentReserve; - ULONG SegmentCommit; - ULONG DeCommitFreeBlockThreshold; - ULONG DeCommitTotalFreeThreshold; - ULONG MaximumAllocationSize; - ULONG VirtualMemoryThreshold; - ULONG InitialCommit; - ULONG InitialReserve; - PVOID CommitRoutine; - ULONG Reserved; -} RTL_HEAP_PARAMETERS, *PRTL_HEAP_PARAMETERS; + typedef struct RTL_HEAP_PARAMETERS { + ULONG Length; //sizeof(RTL_HEAP_PARAMETERS) + ULONG SegmentReserve; + ULONG SegmentCommit; + ULONG DeCommitFreeBlockThreshold; + ULONG DeCommitTotalFreeThreshold; + ULONG MaximumAllocationSize; + ULONG VirtualMemoryThreshold; + ULONG InitialCommit; + ULONG InitialReserve; + PVOID CommitRoutine; + ULONG Reserved; + } RTL_HEAP_PARAMETERS, * PRTL_HEAP_PARAMETERS; #define RtlProcessHeap() (HANDLE)(NtCurrentTeb()->ProcessEnvironmentBlock->ProcessHeap) -NTSYSAPI -HANDLE -NTAPI -RtlCreateHeap ( - IN ULONG Flags, - IN PVOID BaseAddress OPTIONAL, - IN ULONG SizeToReserve, - IN ULONG SizeToCommit, - IN BOOLEAN Lock OPTIONAL, - IN PRTL_HEAP_PARAMETERS Definition OPTIONAL - ); - - -NTSYSAPI -ULONG -NTAPI -RtlDestroyHeap ( - IN HANDLE HeapHandle - ); - - -NTSYSAPI -PVOID -NTAPI -RtlAllocateHeap ( - IN HANDLE HeapHandle, - IN ULONG Flags, - IN ULONG Size - ); - - -NTSYSAPI -BOOLEAN -NTAPI -RtlFreeHeap ( - IN HANDLE HeapHandle, - IN ULONG Flags, - IN PVOID Address - ); - - -NTSYSAPI -ULONG -NTAPI -RtlCompactHeap ( - IN HANDLE HeapHandle, - IN ULONG Flags - ); - - -NTSYSAPI -BOOLEAN -NTAPI -RtlLockHeap ( - IN HANDLE HeapHandle - ); - - -NTSYSAPI -BOOLEAN -NTAPI -RtlUnlockHeap ( - IN HANDLE HeapHandle - ); - - -NTSYSAPI -PVOID -NTAPI -RtlReAllocateHeap ( - IN HANDLE HeapHandle, - IN ULONG Flags, - IN PVOID Address, - IN ULONG Size - ); - - -NTSYSAPI -ULONG -NTAPI -RtlSizeHeap ( - IN HANDLE HeapHandle, - IN ULONG Flags, - IN PVOID Address - ); - - -NTSYSAPI -BOOLEAN -NTAPI -RtlValidateHeap ( - IN HANDLE HeapHandle, - IN ULONG Flags, - IN PVOID Address OPTIONAL - ); - - -//----------------------------------------------------------------------------- -// Virtual memory functions - -NTSYSAPI -NTSTATUS -NTAPI -NtAllocateVirtualMemory ( - IN HANDLE ProcessHandle, - IN OUT PVOID *BaseAddress, - IN ULONG ZeroBits, - IN OUT PULONG RegionSize, - IN ULONG AllocationType, - IN ULONG Protect - ); - - -NTSYSAPI -NTSTATUS -NTAPI -ZwAllocateVirtualMemory ( - IN HANDLE ProcessHandle, - IN OUT PVOID *BaseAddress, - IN ULONG ZeroBits, - IN OUT PULONG RegionSize, - IN ULONG AllocationType, - IN ULONG Protect - ); - - -NTSYSAPI -NTSTATUS -NTAPI -NtFreeVirtualMemory ( - IN HANDLE ProcessHandle, - IN OUT PVOID *BaseAddress, - IN OUT PULONG RegionSize, - IN ULONG FreeType - ); - - -NTSYSAPI -NTSTATUS -NTAPI -ZwFreeVirtualMemory ( - IN HANDLE ProcessHandle, - IN OUT PVOID *BaseAddress, - IN OUT PULONG RegionSize, - IN ULONG FreeType - ); - - -NTSYSAPI -NTSTATUS -NTAPI -NtReadVirtualMemory( - IN HANDLE ProcessHandle, - IN PVOID BaseAddress, - OUT PVOID Buffer, - IN ULONG NumberOfBytesToRead, - OUT PULONG NumberOfBytesRead OPTIONAL - ); - - -NTSYSAPI -NTSTATUS -NTAPI -NtWriteVirtualMemory( - IN HANDLE ProcessHandle, - IN PVOID BaseAddress, - IN PVOID Buffer, - IN ULONG NumberOfBytesToWrite, - OUT PULONG NumberOfBytesWritten OPTIONAL - ); - + NTSYSAPI + HANDLE + NTAPI + RtlCreateHeap( + IN ULONG Flags, + IN PVOID BaseAddress OPTIONAL, + IN ULONG SizeToReserve, + IN ULONG SizeToCommit, + IN BOOLEAN Lock OPTIONAL, + IN PRTL_HEAP_PARAMETERS Definition OPTIONAL + ); + + + NTSYSAPI + ULONG + NTAPI + RtlDestroyHeap( + IN HANDLE HeapHandle + ); + + + NTSYSAPI + PVOID + NTAPI + RtlAllocateHeap( + IN HANDLE HeapHandle, + IN ULONG Flags, + IN ULONG Size + ); + + + NTSYSAPI + BOOLEAN + NTAPI + RtlFreeHeap( + IN HANDLE HeapHandle, + IN ULONG Flags, + IN PVOID Address + ); + + + NTSYSAPI + ULONG + NTAPI + RtlCompactHeap( + IN HANDLE HeapHandle, + IN ULONG Flags + ); + + + NTSYSAPI + BOOLEAN + NTAPI + RtlLockHeap( + IN HANDLE HeapHandle + ); + + + NTSYSAPI + BOOLEAN + NTAPI + RtlUnlockHeap( + IN HANDLE HeapHandle + ); + + + NTSYSAPI + PVOID + NTAPI + RtlReAllocateHeap( + IN HANDLE HeapHandle, + IN ULONG Flags, + IN PVOID Address, + IN ULONG Size + ); + + + NTSYSAPI + ULONG + NTAPI + RtlSizeHeap( + IN HANDLE HeapHandle, + IN ULONG Flags, + IN PVOID Address + ); + + + NTSYSAPI + BOOLEAN + NTAPI + RtlValidateHeap( + IN HANDLE HeapHandle, + IN ULONG Flags, + IN PVOID Address OPTIONAL + ); + + + //----------------------------------------------------------------------------- + // Virtual memory functions + + NTSYSAPI + NTSTATUS + NTAPI + NtAllocateVirtualMemory( + IN HANDLE ProcessHandle, + IN OUT PVOID* BaseAddress, + IN ULONG ZeroBits, + IN OUT PULONG RegionSize, + IN ULONG AllocationType, + IN ULONG Protect + ); + + + NTSYSAPI + NTSTATUS + NTAPI + ZwAllocateVirtualMemory( + IN HANDLE ProcessHandle, + IN OUT PVOID* BaseAddress, + IN ULONG ZeroBits, + IN OUT PULONG RegionSize, + IN ULONG AllocationType, + IN ULONG Protect + ); + + + NTSYSAPI + NTSTATUS + NTAPI + NtFreeVirtualMemory( + IN HANDLE ProcessHandle, + IN OUT PVOID* BaseAddress, + IN OUT PULONG RegionSize, + IN ULONG FreeType + ); + + + NTSYSAPI + NTSTATUS + NTAPI + ZwFreeVirtualMemory( + IN HANDLE ProcessHandle, + IN OUT PVOID* BaseAddress, + IN OUT PULONG RegionSize, + IN ULONG FreeType + ); + + + NTSYSAPI + NTSTATUS + NTAPI + NtReadVirtualMemory( + IN HANDLE ProcessHandle, + IN PVOID BaseAddress, + OUT PVOID Buffer, + IN ULONG NumberOfBytesToRead, + OUT PULONG NumberOfBytesRead OPTIONAL + ); + + + NTSYSAPI + NTSTATUS + NTAPI + NtWriteVirtualMemory( + IN HANDLE ProcessHandle, + IN PVOID BaseAddress, + IN PVOID Buffer, + IN ULONG NumberOfBytesToWrite, + OUT PULONG NumberOfBytesWritten OPTIONAL + ); + + NTSYSCALLAPI + NTSTATUS + NTAPI + NtProtectVirtualMemory( + _In_ HANDLE ProcessHandle, + _Inout_ PVOID* BaseAddress, + _Inout_ PSIZE_T RegionSize, + _In_ ULONG NewProtect, + _Out_ PULONG OldProtect + ); + + NTSYSCALLAPI + NTSTATUS + NTAPI + ZwProtectVirtualMemory( + _In_ HANDLE ProcessHandle, + _Inout_ PVOID* BaseAddress, + _Inout_ PSIZE_T RegionSize, + _In_ ULONG NewProtect, + _Out_ PULONG OldProtect + ); + + typedef enum _MEMORY_INFORMATION_CLASS + { + MemoryBasicInformation, // q: MEMORY_BASIC_INFORMATION + MemoryWorkingSetInformation, // q: MEMORY_WORKING_SET_INFORMATION + MemoryMappedFilenameInformation, // q: UNICODE_STRING + MemoryRegionInformation, // q: MEMORY_REGION_INFORMATION + MemoryWorkingSetExInformation, // q: MEMORY_WORKING_SET_EX_INFORMATION // since VISTA + MemorySharedCommitInformation, // q: MEMORY_SHARED_COMMIT_INFORMATION // since WIN8 + MemoryImageInformation, // q: MEMORY_IMAGE_INFORMATION + MemoryRegionInformationEx, // MEMORY_REGION_INFORMATION + MemoryPrivilegedBasicInformation, // MEMORY_BASIC_INFORMATION + MemoryEnclaveImageInformation, // MEMORY_ENCLAVE_IMAGE_INFORMATION // since REDSTONE3 + MemoryBasicInformationCapped, // 10 + MemoryPhysicalContiguityInformation, // MEMORY_PHYSICAL_CONTIGUITY_INFORMATION // since 20H1 + MemoryBadInformation, // since WIN11 + MemoryBadInformationAllProcesses, // since 22H1 + MemoryImageExtensionInformation, // MEMORY_IMAGE_EXTENSION_INFORMATION // since 24H2 + MaxMemoryInfoClass + } MEMORY_INFORMATION_CLASS; + + 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 + ); + + NTSYSCALLAPI + NTSTATUS + NTAPI + ZwQueryVirtualMemory( + _In_ HANDLE ProcessHandle, + _In_opt_ PVOID BaseAddress, + _In_ MEMORY_INFORMATION_CLASS MemoryInformationClass, + _Out_writes_bytes_(MemoryInformationLength) PVOID MemoryInformation, + _In_ SIZE_T MemoryInformationLength, + _Out_opt_ PSIZE_T ReturnLength + ); + + + //----------------------------------------------------------------------------- + // Section functions + + typedef enum _SECTION_INHERIT + { + ViewShare = 1, + ViewUnmap = 2 -//----------------------------------------------------------------------------- -// Section functions - -typedef enum _SECTION_INHERIT -{ - ViewShare = 1, - ViewUnmap = 2 - -} SECTION_INHERIT; - - -typedef enum _SECTION_INFORMATION_CLASS -{ - SectionBasicInformation, - SectionImageInformation - -} SECTION_INFORMATION_CLASS, *PSECTION_INFORMATION_CLASS; - - -/*++ - - NtCreateSection - =============== - - Creates a section object. - - SectionHandle - Points to a variable that will receive the section - object handle if the call is successful. - - DesiredAccess - Specifies the type of access that the caller requires - to the section object. This parameter can be zero, or any combination - of the following flags: - - SECTION_QUERY - Query access - SECTION_MAP_WRITE - Can be written when mapped - SECTION_MAP_READ - Can be read when mapped - SECTION_MAP_EXECUTE - Can be executed when mapped - SECTION_EXTEND_SIZE - Extend access - SECTION_ALL_ACCESS - All of the preceding + - STANDARD_RIGHTS_REQUIRED - - ObjectAttributes - Points to a structure that specifies the object s attributes. - OBJ_OPENLINK is not a valid attribute for a section object. - - MaximumSize - Optionally points to a variable that specifies the size, - in bytes, of the section. If FileHandle is zero, the size must be - specified; otherwise, it can be defaulted from the size of the file - referred to by FileHandle. - - SectionPageProtection - The protection desired for the pages - of the section when the section is mapped. This parameter can take - one of the following values: - - PAGE_READONLY - PAGE_READWRITE - PAGE_WRITECOPY - PAGE_EXECUTE - PAGE_EXECUTE_READ - PAGE_EXECUTE_READWRITE - PAGE_EXECUTE_WRITECOPY - - AllocationAttributes - The attributes for the section. This parameter must - be a combination of the following values: - - SEC_BASED 0x00200000 // Map section at same address in each process - SEC_NO_CHANGE 0x00400000 // Disable changes to protection of pages - SEC_IMAGE 0x01000000 // Map section as an image - SEC_VLM 0x02000000 // Map section in VLM region - SEC_RESERVE 0x04000000 // Reserve without allocating pagefile storage - SEC_COMMIT 0x08000000 // Commit pages; the default behavior - SEC_NOCACHE 0x10000000 // Mark pages as non-cacheable - - FileHandle - Identifies the file from which to create the section object. - The file must be opened with an access mode compatible with the protection - flags specified by the Protect parameter. If FileHandle is zero, - the function creates a section object of the specified size backed - by the paging file rather than by a named file in the file system. - ---*/ - - -NTSYSAPI -NTSTATUS -NTAPI -NtCreateSection( - OUT PHANDLE SectionHandle, - IN ACCESS_MASK DesiredAccess, - IN POBJECT_ATTRIBUTES ObjectAttributes OPTIONAL, - IN PLARGE_INTEGER MaximumSize OPTIONAL, - IN ULONG SectionPageProtection, - IN ULONG AllocationAttributes, - IN HANDLE FileHandle OPTIONAL - ); - - -NTSYSAPI -NTSTATUS -NTAPI -ZwCreateSection( - OUT PHANDLE SectionHandle, - IN ACCESS_MASK DesiredAccess, - IN POBJECT_ATTRIBUTES ObjectAttributes OPTIONAL, - IN PLARGE_INTEGER MaximumSize OPTIONAL, - IN ULONG SectionPageProtection, - IN ULONG AllocationAttributes, - IN HANDLE FileHandle OPTIONAL - ); - - -NTSYSAPI -NTSTATUS -NTAPI -NtOpenSection ( - OUT PHANDLE SectionHandle, - IN ACCESS_MASK DesiredAccess, - IN POBJECT_ATTRIBUTES ObjectAttributes - ); - - -NTSYSAPI -NTSTATUS -NTAPI -ZwOpenSection ( - OUT PHANDLE SectionHandle, - IN ACCESS_MASK DesiredAccess, - IN POBJECT_ATTRIBUTES ObjectAttributes - ); - -NTSYSAPI -NTSTATUS -NTAPI -NtMapViewOfSection( - IN HANDLE SectionHandle, - IN HANDLE ProcessHandle, - IN OUT PVOID *BaseAddress, - IN ULONG_PTR ZeroBits, - IN SIZE_T CommitSize, - IN OUT PLARGE_INTEGER SectionOffset OPTIONAL, - IN OUT PSIZE_T ViewSize, - IN SECTION_INHERIT InheritDisposition, - IN ULONG AllocationType, - IN ULONG Protect -); - - -NTSYSAPI -NTSTATUS -NTAPI -ZwMapViewOfSection ( - IN HANDLE SectionHandle, - IN HANDLE ProcessHandle, - IN OUT PVOID *BaseAddress, - IN ULONG_PTR ZeroBits, - IN SIZE_T CommitSize, - IN OUT PLARGE_INTEGER SectionOffset OPTIONAL, - IN OUT PSIZE_T ViewSize, - IN SECTION_INHERIT InheritDisposition, - IN ULONG AllocationType, - IN ULONG Protect -); - -NTSYSAPI -NTSTATUS -NTAPI -NtUnmapViewOfSection ( - IN HANDLE ProcessHandle, - IN PVOID BaseAddress - ); - - -NTSYSAPI -NTSTATUS -NTAPI -ZwUnmapViewOfSection ( - IN HANDLE ProcessHandle, - IN PVOID BaseAddress - ); - - -NTSYSAPI -NTSTATUS -NTAPI -NtExtendSection ( - IN HANDLE SectionHandle, - IN OUT PLARGE_INTEGER SectionSize - ); - - -NTSYSAPI -NTSTATUS -NTAPI -ZwExtendSection ( - IN HANDLE SectionHandle, - IN OUT PLARGE_INTEGER SectionSize - ); - - -NTSYSAPI -NTSTATUS -NTAPI -NtQuerySection ( - IN HANDLE SectionHandle, - IN SECTION_INFORMATION_CLASS SectionInformationClass, - OUT PVOID SectionInformation, - IN ULONG Length, - OUT PULONG ResultLength OPTIONAL - ); - - -NTSYSAPI -NTSTATUS -NTAPI -ZwQuerySection ( - IN HANDLE SectionHandle, - IN SECTION_INFORMATION_CLASS SectionInformationClass, - OUT PVOID SectionInformation, - IN ULONG Length, - OUT PULONG ResultLength OPTIONAL - ); + } SECTION_INHERIT; -//----------------------------------------------------------------------------- -// Synchronization + typedef enum _SECTION_INFORMATION_CLASS + { + SectionBasicInformation, + SectionImageInformation + + } SECTION_INFORMATION_CLASS, * PSECTION_INFORMATION_CLASS; + + + /*++ + + NtCreateSection + =============== + + Creates a section object. + + SectionHandle - Points to a variable that will receive the section + object handle if the call is successful. + + DesiredAccess - Specifies the type of access that the caller requires + to the section object. This parameter can be zero, or any combination + of the following flags: + + SECTION_QUERY - Query access + SECTION_MAP_WRITE - Can be written when mapped + SECTION_MAP_READ - Can be read when mapped + SECTION_MAP_EXECUTE - Can be executed when mapped + SECTION_EXTEND_SIZE - Extend access + SECTION_ALL_ACCESS - All of the preceding + + STANDARD_RIGHTS_REQUIRED + + ObjectAttributes - Points to a structure that specifies the object s attributes. + OBJ_OPENLINK is not a valid attribute for a section object. + + MaximumSize - Optionally points to a variable that specifies the size, + in bytes, of the section. If FileHandle is zero, the size must be + specified; otherwise, it can be defaulted from the size of the file + referred to by FileHandle. + + SectionPageProtection - The protection desired for the pages + of the section when the section is mapped. This parameter can take + one of the following values: + + PAGE_READONLY + PAGE_READWRITE + PAGE_WRITECOPY + PAGE_EXECUTE + PAGE_EXECUTE_READ + PAGE_EXECUTE_READWRITE + PAGE_EXECUTE_WRITECOPY + + AllocationAttributes - The attributes for the section. This parameter must + be a combination of the following values: + + SEC_BASED 0x00200000 // Map section at same address in each process + SEC_NO_CHANGE 0x00400000 // Disable changes to protection of pages + SEC_IMAGE 0x01000000 // Map section as an image + SEC_VLM 0x02000000 // Map section in VLM region + SEC_RESERVE 0x04000000 // Reserve without allocating pagefile storage + SEC_COMMIT 0x08000000 // Commit pages; the default behavior + SEC_NOCACHE 0x10000000 // Mark pages as non-cacheable + + FileHandle - Identifies the file from which to create the section object. + The file must be opened with an access mode compatible with the protection + flags specified by the Protect parameter. If FileHandle is zero, + the function creates a section object of the specified size backed + by the paging file rather than by a named file in the file system. + + --*/ + + + NTSYSAPI + NTSTATUS + NTAPI + NtCreateSection( + OUT PHANDLE SectionHandle, + IN ACCESS_MASK DesiredAccess, + IN POBJECT_ATTRIBUTES ObjectAttributes OPTIONAL, + IN PLARGE_INTEGER MaximumSize OPTIONAL, + IN ULONG SectionPageProtection, + IN ULONG AllocationAttributes, + IN HANDLE FileHandle OPTIONAL + ); + + + NTSYSAPI + NTSTATUS + NTAPI + ZwCreateSection( + OUT PHANDLE SectionHandle, + IN ACCESS_MASK DesiredAccess, + IN POBJECT_ATTRIBUTES ObjectAttributes OPTIONAL, + IN PLARGE_INTEGER MaximumSize OPTIONAL, + IN ULONG SectionPageProtection, + IN ULONG AllocationAttributes, + IN HANDLE FileHandle OPTIONAL + ); + + + NTSYSAPI + NTSTATUS + NTAPI + NtOpenSection( + OUT PHANDLE SectionHandle, + IN ACCESS_MASK DesiredAccess, + IN POBJECT_ATTRIBUTES ObjectAttributes + ); + + + NTSYSAPI + NTSTATUS + NTAPI + ZwOpenSection( + OUT PHANDLE SectionHandle, + IN ACCESS_MASK DesiredAccess, + IN POBJECT_ATTRIBUTES ObjectAttributes + ); + + NTSYSAPI + NTSTATUS + NTAPI + NtMapViewOfSection( + IN HANDLE SectionHandle, + IN HANDLE ProcessHandle, + IN OUT PVOID* BaseAddress, + IN ULONG_PTR ZeroBits, + IN SIZE_T CommitSize, + IN OUT PLARGE_INTEGER SectionOffset OPTIONAL, + IN OUT PSIZE_T ViewSize, + IN SECTION_INHERIT InheritDisposition, + IN ULONG AllocationType, + IN ULONG Protect + ); + + + NTSYSAPI + NTSTATUS + NTAPI + ZwMapViewOfSection( + IN HANDLE SectionHandle, + IN HANDLE ProcessHandle, + IN OUT PVOID* BaseAddress, + IN ULONG_PTR ZeroBits, + IN SIZE_T CommitSize, + IN OUT PLARGE_INTEGER SectionOffset OPTIONAL, + IN OUT PSIZE_T ViewSize, + IN SECTION_INHERIT InheritDisposition, + IN ULONG AllocationType, + IN ULONG Protect + ); + + NTSYSAPI + NTSTATUS + NTAPI + NtUnmapViewOfSection( + IN HANDLE ProcessHandle, + IN PVOID BaseAddress + ); + + + NTSYSAPI + NTSTATUS + NTAPI + ZwUnmapViewOfSection( + IN HANDLE ProcessHandle, + IN PVOID BaseAddress + ); + + + NTSYSAPI + NTSTATUS + NTAPI + NtExtendSection( + IN HANDLE SectionHandle, + IN OUT PLARGE_INTEGER SectionSize + ); + + + NTSYSAPI + NTSTATUS + NTAPI + ZwExtendSection( + IN HANDLE SectionHandle, + IN OUT PLARGE_INTEGER SectionSize + ); + + + NTSYSAPI + NTSTATUS + NTAPI + NtQuerySection( + IN HANDLE SectionHandle, + IN SECTION_INFORMATION_CLASS SectionInformationClass, + OUT PVOID SectionInformation, + IN ULONG Length, + OUT PULONG ResultLength OPTIONAL + ); + + + NTSYSAPI + NTSTATUS + NTAPI + ZwQuerySection( + IN HANDLE SectionHandle, + IN SECTION_INFORMATION_CLASS SectionInformationClass, + OUT PVOID SectionInformation, + IN ULONG Length, + OUT PULONG ResultLength OPTIONAL + ); + + + //----------------------------------------------------------------------------- + // Synchronization -// -// Wait type -// + // + // Wait type + // -typedef enum _WAIT_TYPE { - WaitAll, - WaitAny + typedef enum _WAIT_TYPE { + WaitAll, + WaitAny } WAIT_TYPE; -NTSYSAPI -NTSTATUS -NTAPI -NtWaitForSingleObject ( - IN HANDLE Handle, - IN BOOLEAN Alertable, - IN PLARGE_INTEGER Timeout OPTIONAL - ); - - -NTSYSAPI -NTSTATUS -NTAPI -ZwWaitForSingleObject ( - IN HANDLE Handle, - IN BOOLEAN Alertable, - IN PLARGE_INTEGER Timeout OPTIONAL - ); - - -NTSYSAPI -NTSTATUS -NTAPI -NtWaitForMultipleObjects ( - IN ULONG Count, - IN HANDLE Handle[], - IN WAIT_TYPE WaitType, - IN BOOLEAN Alertable, - IN PLARGE_INTEGER Timeout OPTIONAL - ); - - -NTSYSAPI -NTSTATUS -NTAPI -ZwWaitForMultipleObjects ( - IN ULONG Count, - IN HANDLE Handle[], - IN WAIT_TYPE WaitType, - IN BOOLEAN Alertable, - IN PLARGE_INTEGER Timeout OPTIONAL - ); - - -//----------------------------------------------------------------------------- -// Event support - -typedef enum _EVENT_INFORMATION_CLASS { - EventBasicInformation // = 0 -} EVENT_INFORMATION_CLASS; - -typedef struct _EVENT_BASIC_INFORMATION { - EVENT_TYPE EventType; - LONG EventState; -} EVENT_BASIC_INFORMATION, *PEVENT_BASIC_INFORMATION; - -// -// Event handling routines -// - - -NTSYSAPI -NTSTATUS -NTAPI -NtCreateEvent ( - OUT PHANDLE EventHandle, - IN ACCESS_MASK DesiredAccess, - IN POBJECT_ATTRIBUTES ObjectAttributes OPTIONAL, - IN EVENT_TYPE EventType, - IN BOOLEAN InitialState - ); - - -NTSYSAPI -NTSTATUS -NTAPI -ZwCreateEvent ( - OUT PHANDLE EventHandle, - IN ACCESS_MASK DesiredAccess, - IN POBJECT_ATTRIBUTES ObjectAttributes OPTIONAL, - IN EVENT_TYPE EventType, - IN BOOLEAN InitialState - ); - - -NTSYSAPI -NTSTATUS -NTAPI -NtClearEvent ( - IN HANDLE Handle - ); - - -NTSYSAPI -NTSTATUS -NTAPI -ZwClearEvent ( - IN HANDLE Handle - ); - - -NTSYSAPI -NTSTATUS -NTAPI -NtPulseEvent ( - IN HANDLE Handle, - OUT PLONG PreviousState OPTIONAL - ); - - -NTSYSAPI -NTSTATUS -NTAPI -ZwPulseEvent ( - IN HANDLE Handle, - OUT PLONG PreviousState OPTIONAL - ); - - -NTSYSAPI -NTSTATUS -NTAPI -NtResetEvent ( - IN HANDLE Handle, - OUT PLONG PreviousState OPTIONAL - ); - - -NTSYSAPI -NTSTATUS -NTAPI -ZwResetEvent ( - IN HANDLE Handle, - OUT PLONG PreviousState OPTIONAL - ); - - -NTSYSAPI -NTSTATUS -NTAPI -NtSetEvent ( - IN HANDLE Handle, - OUT PLONG PreviousState OPTIONAL - ); - - -NTSYSAPI -NTSTATUS -NTAPI -ZwSetEvent ( - IN HANDLE Handle, - OUT PLONG PreviousState OPTIONAL - ); - - -NTSYSAPI -NTSTATUS -NTAPI -NtOpenEvent ( - OUT PHANDLE EventHandle, - IN ACCESS_MASK DesiredAccess, - IN POBJECT_ATTRIBUTES ObjectAttributes - ); - - -NTSYSAPI -NTSTATUS -NTAPI -ZwOpenEvent ( - OUT PHANDLE EventHandle, - IN ACCESS_MASK DesiredAccess, - IN POBJECT_ATTRIBUTES ObjectAttributes - ); - - -NTSYSAPI -NTSTATUS -NTAPI -NtQueryEvent ( - IN HANDLE EventHandle, - IN EVENT_INFORMATION_CLASS EventInfoClass, - OUT PVOID EventInfo, - IN ULONG Length, - OUT PULONG ResultLength OPTIONAL - ); - - -NTSYSAPI -NTSTATUS -NTAPI -ZwQueryEvent ( - IN HANDLE EventHandle, - IN EVENT_INFORMATION_CLASS EventInfoClass, - OUT PVOID EventInfo, - IN ULONG Length, - OUT PULONG ResultLength OPTIONAL - ); - - -//----------------------------------------------------------------------------- -// Security descriptor functions - -NTSYSAPI -NTSTATUS -NTAPI -RtlCreateSecurityDescriptor ( - IN PSECURITY_DESCRIPTOR SecurityDescriptor, - IN ULONG Revision - ); - - -NTSYSAPI -NTSTATUS -NTAPI -RtlSetDaclSecurityDescriptor( - IN PSECURITY_DESCRIPTOR SecurityDescriptor, - IN BOOLEAN DaclPresent, - IN PACL Dacl OPTIONAL, - IN BOOLEAN DaclDefaulted OPTIONAL - ); - - -NTSYSAPI -NTSTATUS -NTAPI -RtlSetOwnerSecurityDescriptor ( - IN PSECURITY_DESCRIPTOR SecurityDescriptor, - IN PSID Owner OPTIONAL, - IN BOOLEAN OwnerDefaulted OPTIONAL - ); - - -NTSYSAPI -NTSTATUS -NTAPI -RtlAllocateAndInitializeSid( - IN PSID_IDENTIFIER_AUTHORITY IdentifierAuthority, - IN UCHAR SubAuthorityCount, - IN ULONG SubAuthority0, - IN ULONG SubAuthority1, - IN ULONG SubAuthority2, - IN ULONG SubAuthority3, - IN ULONG SubAuthority4, - IN ULONG SubAuthority5, - IN ULONG SubAuthority6, - IN ULONG SubAuthority7, - OUT PSID *Sid - ); - - -NTSYSAPI -ULONG -NTAPI -RtlLengthSid ( - IN PSID Sid - ); - - -NTSYSAPI -BOOLEAN -NTAPI -RtlEqualSid ( - IN PSID Sid1, - IN PSID Sid2 - ); - - -NTSYSAPI -PVOID -NTAPI -RtlFreeSid( - IN PSID Sid - ); - - -NTSYSAPI -NTSTATUS -NTAPI -RtlCreateAcl( - IN PACL Acl, - IN ULONG AclLength, - IN ULONG AclRevision - ); - - -NTSYSAPI -NTSTATUS -NTAPI -RtlAddAccessAllowedAce( - IN OUT PACL Acl, - IN ULONG AceRevision, - IN ACCESS_MASK AccessMask, - IN PSID Sid - ); - - -NTSYSAPI -NTSTATUS -NTAPI -RtlAddAccessAllowedAceEx( - IN OUT PACL Acl, - IN ULONG AceRevision, - IN ULONG AceFlags, - IN ULONG AccessMask, - IN PSID Sid - ); + NTSYSAPI + NTSTATUS + NTAPI + NtWaitForSingleObject( + IN HANDLE Handle, + IN BOOLEAN Alertable, + IN PLARGE_INTEGER Timeout OPTIONAL + ); + + + NTSYSAPI + NTSTATUS + NTAPI + ZwWaitForSingleObject( + IN HANDLE Handle, + IN BOOLEAN Alertable, + IN PLARGE_INTEGER Timeout OPTIONAL + ); + + + NTSYSAPI + NTSTATUS + NTAPI + NtWaitForMultipleObjects( + IN ULONG Count, + IN HANDLE Handle[], + IN WAIT_TYPE WaitType, + IN BOOLEAN Alertable, + IN PLARGE_INTEGER Timeout OPTIONAL + ); + + + NTSYSAPI + NTSTATUS + NTAPI + ZwWaitForMultipleObjects( + IN ULONG Count, + IN HANDLE Handle[], + IN WAIT_TYPE WaitType, + IN BOOLEAN Alertable, + IN PLARGE_INTEGER Timeout OPTIONAL + ); + + + //----------------------------------------------------------------------------- + // Event support + + typedef enum _EVENT_INFORMATION_CLASS { + EventBasicInformation // = 0 + } EVENT_INFORMATION_CLASS; + + typedef struct _EVENT_BASIC_INFORMATION { + EVENT_TYPE EventType; + LONG EventState; + } EVENT_BASIC_INFORMATION, * PEVENT_BASIC_INFORMATION; -//----------------------------------------------------------------------------- -// Token functions - -NTSYSAPI -NTSTATUS -NTAPI -NtOpenProcessToken( - IN HANDLE ProcessHandle, - IN ACCESS_MASK DesiredAccess, - OUT PHANDLE TokenHandle - ); - - -NTSYSAPI -NTSTATUS -NTAPI -NtOpenThreadToken( - IN HANDLE ThreadHandle, - IN ACCESS_MASK DesiredAccess, - IN BOOLEAN OpenAsSelf, - OUT PHANDLE TokenHandle - ); - - -NTSYSAPI -NTSTATUS -NTAPI -NtQueryInformationToken( - IN HANDLE TokenHandle, - IN TOKEN_INFORMATION_CLASS TokenInformationClass, - OUT PVOID TokenInformation, - IN ULONG TokenInformationLength, - OUT PULONG ReturnLength - ); - - -NTSYSAPI -NTSTATUS -NTAPI -NtSetInformationToken( - IN HANDLE TokenHandle, - IN TOKEN_INFORMATION_CLASS TokenInformationClass, - IN PVOID TokenInformation, - IN ULONG TokenInformationLength - ); - - -NTSYSAPI -NTSTATUS -NTAPI -NtAdjustPrivilegesToken( - IN HANDLE TokenHandle, - IN BOOLEAN DisableAllPrivileges, - IN PTOKEN_PRIVILEGES NewState OPTIONAL, - IN ULONG BufferLength OPTIONAL, - IN PTOKEN_PRIVILEGES PreviousState OPTIONAL, - OUT PULONG ReturnLength - ); - - -NTSYSAPI -NTSTATUS -NTAPI -NtDuplicateToken( - IN HANDLE ExistingTokenHandle, - IN ACCESS_MASK DesiredAccess, - IN POBJECT_ATTRIBUTES ObjectAttributes, - IN BOOLEAN EffectiveOnly, - IN TOKEN_TYPE TokenType, - OUT PHANDLE NewTokenHandle - ); - - -NTSYSAPI -NTSTATUS -NTAPI -NtCompareTokens( - IN HANDLE FirstTokenHandle, - IN HANDLE SecondTokenHandle, - OUT PBOOLEAN IdenticalTokens - ); + // + // Event handling routines + // -//----------------------------------------------------------------------------- -// Symbolic links + NTSYSAPI + NTSTATUS + NTAPI + NtCreateEvent( + OUT PHANDLE EventHandle, + IN ACCESS_MASK DesiredAccess, + IN POBJECT_ATTRIBUTES ObjectAttributes OPTIONAL, + IN EVENT_TYPE EventType, + IN BOOLEAN InitialState + ); + + + NTSYSAPI + NTSTATUS + NTAPI + ZwCreateEvent( + OUT PHANDLE EventHandle, + IN ACCESS_MASK DesiredAccess, + IN POBJECT_ATTRIBUTES ObjectAttributes OPTIONAL, + IN EVENT_TYPE EventType, + IN BOOLEAN InitialState + ); + + + NTSYSAPI + NTSTATUS + NTAPI + NtClearEvent( + IN HANDLE Handle + ); + + + NTSYSAPI + NTSTATUS + NTAPI + ZwClearEvent( + IN HANDLE Handle + ); + + + NTSYSAPI + NTSTATUS + NTAPI + NtPulseEvent( + IN HANDLE Handle, + OUT PLONG PreviousState OPTIONAL + ); + + + NTSYSAPI + NTSTATUS + NTAPI + ZwPulseEvent( + IN HANDLE Handle, + OUT PLONG PreviousState OPTIONAL + ); + + + NTSYSAPI + NTSTATUS + NTAPI + NtResetEvent( + IN HANDLE Handle, + OUT PLONG PreviousState OPTIONAL + ); + + + NTSYSAPI + NTSTATUS + NTAPI + ZwResetEvent( + IN HANDLE Handle, + OUT PLONG PreviousState OPTIONAL + ); + + + NTSYSAPI + NTSTATUS + NTAPI + NtSetEvent( + IN HANDLE Handle, + OUT PLONG PreviousState OPTIONAL + ); + + + NTSYSAPI + NTSTATUS + NTAPI + ZwSetEvent( + IN HANDLE Handle, + OUT PLONG PreviousState OPTIONAL + ); + + + NTSYSAPI + NTSTATUS + NTAPI + NtOpenEvent( + OUT PHANDLE EventHandle, + IN ACCESS_MASK DesiredAccess, + IN POBJECT_ATTRIBUTES ObjectAttributes + ); + + + NTSYSAPI + NTSTATUS + NTAPI + ZwOpenEvent( + OUT PHANDLE EventHandle, + IN ACCESS_MASK DesiredAccess, + IN POBJECT_ATTRIBUTES ObjectAttributes + ); + + + NTSYSAPI + NTSTATUS + NTAPI + NtQueryEvent( + IN HANDLE EventHandle, + IN EVENT_INFORMATION_CLASS EventInfoClass, + OUT PVOID EventInfo, + IN ULONG Length, + OUT PULONG ResultLength OPTIONAL + ); + + + NTSYSAPI + NTSTATUS + NTAPI + ZwQueryEvent( + IN HANDLE EventHandle, + IN EVENT_INFORMATION_CLASS EventInfoClass, + OUT PVOID EventInfo, + IN ULONG Length, + OUT PULONG ResultLength OPTIONAL + ); + + + //----------------------------------------------------------------------------- + // Security descriptor functions + + NTSYSAPI + NTSTATUS + NTAPI + RtlCreateSecurityDescriptor( + IN PSECURITY_DESCRIPTOR SecurityDescriptor, + IN ULONG Revision + ); + + + NTSYSAPI + NTSTATUS + NTAPI + RtlSetDaclSecurityDescriptor( + IN PSECURITY_DESCRIPTOR SecurityDescriptor, + IN BOOLEAN DaclPresent, + IN PACL Dacl OPTIONAL, + IN BOOLEAN DaclDefaulted OPTIONAL + ); + + + NTSYSAPI + NTSTATUS + NTAPI + RtlSetOwnerSecurityDescriptor( + IN PSECURITY_DESCRIPTOR SecurityDescriptor, + IN PSID Owner OPTIONAL, + IN BOOLEAN OwnerDefaulted OPTIONAL + ); + + + NTSYSAPI + NTSTATUS + NTAPI + RtlAllocateAndInitializeSid( + IN PSID_IDENTIFIER_AUTHORITY IdentifierAuthority, + IN UCHAR SubAuthorityCount, + IN ULONG SubAuthority0, + IN ULONG SubAuthority1, + IN ULONG SubAuthority2, + IN ULONG SubAuthority3, + IN ULONG SubAuthority4, + IN ULONG SubAuthority5, + IN ULONG SubAuthority6, + IN ULONG SubAuthority7, + OUT PSID* Sid + ); + + + NTSYSAPI + ULONG + NTAPI + RtlLengthSid( + IN PSID Sid + ); + + + NTSYSAPI + BOOLEAN + NTAPI + RtlEqualSid( + IN PSID Sid1, + IN PSID Sid2 + ); + + + NTSYSAPI + PVOID + NTAPI + RtlFreeSid( + IN PSID Sid + ); + + + NTSYSAPI + NTSTATUS + NTAPI + RtlCreateAcl( + IN PACL Acl, + IN ULONG AclLength, + IN ULONG AclRevision + ); + + + NTSYSAPI + NTSTATUS + NTAPI + RtlAddAccessAllowedAce( + IN OUT PACL Acl, + IN ULONG AceRevision, + IN ACCESS_MASK AccessMask, + IN PSID Sid + ); + + + NTSYSAPI + NTSTATUS + NTAPI + RtlAddAccessAllowedAceEx( + IN OUT PACL Acl, + IN ULONG AceRevision, + IN ULONG AceFlags, + IN ULONG AccessMask, + IN PSID Sid + ); + + //----------------------------------------------------------------------------- + // Token functions + + NTSYSAPI + NTSTATUS + NTAPI + NtOpenProcessToken( + IN HANDLE ProcessHandle, + IN ACCESS_MASK DesiredAccess, + OUT PHANDLE TokenHandle + ); + + + NTSYSAPI + NTSTATUS + NTAPI + NtOpenThreadToken( + IN HANDLE ThreadHandle, + IN ACCESS_MASK DesiredAccess, + IN BOOLEAN OpenAsSelf, + OUT PHANDLE TokenHandle + ); + + + NTSYSAPI + NTSTATUS + NTAPI + NtQueryInformationToken( + IN HANDLE TokenHandle, + IN TOKEN_INFORMATION_CLASS TokenInformationClass, + OUT PVOID TokenInformation, + IN ULONG TokenInformationLength, + OUT PULONG ReturnLength + ); + + + NTSYSAPI + NTSTATUS + NTAPI + NtSetInformationToken( + IN HANDLE TokenHandle, + IN TOKEN_INFORMATION_CLASS TokenInformationClass, + IN PVOID TokenInformation, + IN ULONG TokenInformationLength + ); + + + NTSYSAPI + NTSTATUS + NTAPI + NtAdjustPrivilegesToken( + IN HANDLE TokenHandle, + IN BOOLEAN DisableAllPrivileges, + IN PTOKEN_PRIVILEGES NewState OPTIONAL, + IN ULONG BufferLength OPTIONAL, + IN PTOKEN_PRIVILEGES PreviousState OPTIONAL, + OUT PULONG ReturnLength + ); + + + NTSYSAPI + NTSTATUS + NTAPI + NtDuplicateToken( + IN HANDLE ExistingTokenHandle, + IN ACCESS_MASK DesiredAccess, + IN POBJECT_ATTRIBUTES ObjectAttributes, + IN BOOLEAN EffectiveOnly, + IN TOKEN_TYPE TokenType, + OUT PHANDLE NewTokenHandle + ); + + + NTSYSAPI + NTSTATUS + NTAPI + NtCompareTokens( + IN HANDLE FirstTokenHandle, + IN HANDLE SecondTokenHandle, + OUT PBOOLEAN IdenticalTokens + ); + + + //----------------------------------------------------------------------------- + // Symbolic links -// -// Object Manager Symbolic Link Specific Access Rights. -// + // + // Object Manager Symbolic Link Specific Access Rights. + // #ifndef SYMBOLIC_LINK_QUERY #define SYMBOLIC_LINK_QUERY (0x0001) #define SYMBOLIC_LINK_ALL_ACCESS (STANDARD_RIGHTS_REQUIRED | 0x1) #endif -NTSYSAPI -NTSTATUS -NTAPI -NtOpenSymbolicLinkObject ( - OUT PHANDLE SymbolicLinkHandle, - IN ACCESS_MASK DesiredAccess, - IN POBJECT_ATTRIBUTES ObjectAttributes - ); - - -NTSYSAPI -NTSTATUS -NTAPI -NtQuerySymbolicLinkObject ( - IN HANDLE SymbolicLinkHandle, - OUT PUNICODE_STRING NameString, - OUT PULONG ResultLength OPTIONAL - ); - -//----------------------------------------------------------------------------- -// Loader functions - -NTSYSAPI -NTSTATUS -NTAPI -LdrGetDllHandle( - IN PWSTR DllPath OPTIONAL, - IN PULONG DllCharacteristics OPTIONAL, - IN PUNICODE_STRING DllName, - OUT PVOID * DllHandle - ); - - -NTSYSAPI -NTSTATUS -NTAPI -LdrGetProcedureAddress( - IN PVOID DllHandle, - IN PANSI_STRING ProcedureName OPTIONAL, - IN ULONG ProcedureNumber OPTIONAL, - OUT PVOID *ProcedureAddress - ); - - -NTSYSAPI -NTSTATUS -NTAPI -LdrLoadDll( - IN PWSTR DllPath OPTIONAL, - IN PULONG DllCharacteristics OPTIONAL, - IN PUNICODE_STRING DllName, - OUT PVOID *DllHandle - ); - -NTSYSAPI -NTSTATUS -NTAPI -LdrFindEntryForAddress( - IN PVOID Address, - OUT PLDR_DATA_TABLE_ENTRY *Module - ); - -NTSYSAPI -VOID -NTAPI - RtlGetCallersAddress( - OUT PVOID *CallersAddress, - OUT PVOID *CallersCaller - ); - -//----------------------------------------------------------------------------- -// Functions dealing with NTSTATUS and Win32 error - -NTSYSAPI -ULONG -NTAPI -RtlNtStatusToDosError( - NTSTATUS Status - ); - - -NTSYSAPI -ULONG -NTAPI -RtlNtStatusToDosErrorNoTeb( - NTSTATUS Status - ); - - -NTSYSAPI -NTSTATUS -NTAPI -RtlGetLastNtStatus( - ); - - -NTSYSAPI -ULONG -NTAPI -RtlGetLastWin32Error( - ); - - -NTSYSAPI -VOID -NTAPI -RtlSetLastWin32Error( - ULONG WinError - ); - - -NTSYSAPI -VOID -NTAPI -RtlSetLastWin32ErrorAndNtStatusFromNtStatus( - NTSTATUS Status - ); - - -//----------------------------------------------------------------------------- -// I/O functions + NTSYSAPI + NTSTATUS + NTAPI + NtOpenSymbolicLinkObject( + OUT PHANDLE SymbolicLinkHandle, + IN ACCESS_MASK DesiredAccess, + IN POBJECT_ATTRIBUTES ObjectAttributes + ); + + + NTSYSAPI + NTSTATUS + NTAPI + NtQuerySymbolicLinkObject( + IN HANDLE SymbolicLinkHandle, + OUT PUNICODE_STRING NameString, + OUT PULONG ResultLength OPTIONAL + ); + + //----------------------------------------------------------------------------- + // Loader functions + + NTSYSAPI + NTSTATUS + NTAPI + LdrGetDllHandle( + IN PWSTR DllPath OPTIONAL, + IN PULONG DllCharacteristics OPTIONAL, + IN PUNICODE_STRING DllName, + OUT PVOID* DllHandle + ); + + + NTSYSAPI + NTSTATUS + NTAPI + LdrGetProcedureAddress( + IN PVOID DllHandle, + IN PANSI_STRING ProcedureName OPTIONAL, + IN ULONG ProcedureNumber OPTIONAL, + OUT PVOID* ProcedureAddress + ); + + + NTSYSAPI + NTSTATUS + NTAPI + LdrLoadDll( + IN PWSTR DllPath OPTIONAL, + IN PULONG DllCharacteristics OPTIONAL, + IN PUNICODE_STRING DllName, + OUT PVOID* DllHandle + ); + + NTSYSAPI + NTSTATUS + NTAPI + LdrFindEntryForAddress( + IN PVOID Address, + OUT PLDR_DATA_TABLE_ENTRY* Module + ); + + NTSYSAPI + VOID + NTAPI + RtlGetCallersAddress( + OUT PVOID* CallersAddress, + OUT PVOID* CallersCaller + ); + + //----------------------------------------------------------------------------- + // Functions dealing with NTSTATUS and Win32 error + + NTSYSAPI + ULONG + NTAPI + RtlNtStatusToDosError( + NTSTATUS Status + ); + + + NTSYSAPI + ULONG + NTAPI + RtlNtStatusToDosErrorNoTeb( + NTSTATUS Status + ); + + + NTSYSAPI + NTSTATUS + NTAPI + RtlGetLastNtStatus( + ); + + + NTSYSAPI + ULONG + NTAPI + RtlGetLastWin32Error( + ); + + + NTSYSAPI + VOID + NTAPI + RtlSetLastWin32Error( + ULONG WinError + ); + + + NTSYSAPI + VOID + NTAPI + RtlSetLastWin32ErrorAndNtStatusFromNtStatus( + NTSTATUS Status + ); + + + //----------------------------------------------------------------------------- + // I/O functions + + + NTSYSAPI + NTSTATUS + NTAPI + NtDisplayString( + IN PUNICODE_STRING String + ); + + NTSYSAPI + PVOID + NTAPI + RtlEncodeSystemPointer( + _In_ PVOID Ptr + ); + + typedef struct _LDR_SERVICE_TAG_RECORD { + struct _LDR_SERVICE_TAG_RECORD* Next; + ULONG ServiceTag; + } LDR_SERVICE_TAG_RECORD, * PLDR_SERVICE_TAG_RECORD; + + typedef struct _LDRP_CSLIST + { + PSINGLE_LIST_ENTRY Tail; + } LDRP_CSLIST, * PLDRP_CSLIST; + 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; + + typedef enum _LDR_DLL_LOAD_REASON + { + LoadReasonStaticDependency, + LoadReasonStaticForwarderDependency, + LoadReasonDynamicForwarderDependency, + LoadReasonDelayloadDependency, + LoadReasonDynamicLoad, + LoadReasonAsImageLoad, + LoadReasonAsDataLoad, + LoadReasonEnclavePrimary, // since REDSTONE3 + LoadReasonEnclaveDependency, + LoadReasonPatchImage, // since WIN11 + LoadReasonUnknown = -1 + } LDR_DLL_LOAD_REASON, * PLDR_DLL_LOAD_REASON; + + typedef struct _LDR_DDAG_NODE + { + LIST_ENTRY Modules; + PLDR_SERVICE_TAG_RECORD ServiceTagList; + ULONG LoadCount; + ULONG LoadWhileUnloadingCount; + ULONG LowestLink; + union + { + LDRP_CSLIST Dependencies; + SINGLE_LIST_ENTRY RemovalLink; + }; + LDRP_CSLIST IncomingDependencies; + LDR_DDAG_STATE State; + SINGLE_LIST_ENTRY CondenseLink; + ULONG PreorderNumber; + } LDR_DDAG_NODE, * PLDR_DDAG_NODE; + + typedef struct _RTL_BALANCED_NODE + { + union + { + struct _RTL_BALANCED_NODE* Children[2]; + struct + { + struct _RTL_BALANCED_NODE* Left; + struct _RTL_BALANCED_NODE* Right; + }; + }; + union + { + UCHAR Red : 1; + UCHAR Balance : 2; + ULONG_PTR ParentValue; + }; + } RTL_BALANCED_NODE, * PRTL_BALANCED_NODE; + +#include + + typedef struct _ACTIVATION_CONTEXT_DATA + { + ULONG Magic; + ULONG HeaderSize; + ULONG FormatVersion; + ULONG TotalSize; + ULONG DefaultTocOffset; // to ACTIVATION_CONTEXT_DATA_TOC_HEADER + ULONG ExtendedTocOffset; // to ACTIVATION_CONTEXT_DATA_EXTENDED_TOC_HEADER + ULONG AssemblyRosterOffset; // to ACTIVATION_CONTEXT_DATA_ASSEMBLY_ROSTER_HEADER + ULONG Flags; // ACTIVATION_CONTEXT_FLAG_* + } ACTIVATION_CONTEXT_DATA, * PACTIVATION_CONTEXT_DATA; + +#include + + typedef struct _ASSEMBLY_STORAGE_MAP_ENTRY + { + ULONG Flags; + UNICODE_STRING DosPath; + HANDLE Handle; + } ASSEMBLY_STORAGE_MAP_ENTRY, * PASSEMBLY_STORAGE_MAP_ENTRY; -NTSYSAPI -NTSTATUS -NTAPI -NtDisplayString( - IN PUNICODE_STRING String - ); + typedef struct _ASSEMBLY_STORAGE_MAP + { + ULONG Flags; + ULONG AssemblyCount; + PASSEMBLY_STORAGE_MAP_ENTRY* AssemblyArray; + } ASSEMBLY_STORAGE_MAP, * PASSEMBLY_STORAGE_MAP; + + typedef VOID(NTAPI* PACTIVATION_CONTEXT_NOTIFY_ROUTINE)( + _In_ ULONG NotificationType, // ACTIVATION_CONTEXT_NOTIFICATION_* + _In_ struct _ACTIVATION_CONTEXT* ActivationContext, + _In_ PACTIVATION_CONTEXT_DATA ActivationContextData, + _In_opt_ PVOID NotificationContext, + _In_opt_ PVOID NotificationData, + _Inout_ PBOOLEAN DisableThisNotification + ); + + typedef struct _ACTIVATION_CONTEXT + { + LONG RefCount; + ULONG Flags; + PACTIVATION_CONTEXT_DATA ActivationContextData; + PACTIVATION_CONTEXT_NOTIFY_ROUTINE NotificationRoutine; + PVOID NotificationContext; + ULONG SentNotifications[8]; + ULONG DisabledNotifications[8]; + ASSEMBLY_STORAGE_MAP StorageMap; + PASSEMBLY_STORAGE_MAP_ENTRY InlineStorageMapEntries[32]; + } ACTIVATION_CONTEXT, * PACTIVATION_CONTEXT; + + typedef struct _LDRP_CSLIST_DEPENDENT { + PSINGLE_LIST_ENTRY NextDependentEntry; //0x0 + PLDR_DDAG_NODE DependentDdagNode; + } LDRP_CSLIST_DEPENDENT, * PLDRP_CSLIST_DEPENDENT; + typedef struct _LDRP_CSLIST_INCOMMING { + PSINGLE_LIST_ENTRY NextIncommingEntry; + PLDR_DDAG_NODE IncommingDdagNode; + } LDRP_CSLIST_INCOMMING, * PLDRP_CSLIST_INCOMMING; #ifdef __cplusplus diff --git a/tests/test_exceptions.cpp b/tests/test_exceptions.cpp index c053403d1..d5274324d 100644 --- a/tests/test_exceptions.cpp +++ b/tests/test_exceptions.cpp @@ -9,7 +9,6 @@ using namespace peconv; int tests::test_load_with_exception_table(LPCTSTR path) { -#ifdef _WIN64 if (path == NULL) { std::cerr << "Supply the path to the app" << std::endl; return -1; @@ -35,7 +34,7 @@ int tests::test_load_with_exception_table(LPCTSTR path) peconv::run_tls_callbacks(loaded_pe, v_size); ULONGLONG ep_exp_offset = (ULONGLONG)loaded_pe + peconv::get_entry_point_rva(loaded_pe); - void(_cdecl *ep_func)() = (void(_cdecl *)()) (ep_exp_offset); + void(_cdecl * ep_func)() = (void(_cdecl*)()) (ep_exp_offset); std::wcout << "Calling entry point:" << std::endl; ep_func(); } @@ -43,6 +42,5 @@ int tests::test_load_with_exception_table(LPCTSTR path) std::wcout << "Exception captured by the caller" << std::endl; } peconv::free_pe_buffer(loaded_pe, v_size); -#endif return 0; } From 10ad75ce162c913592b437f52c9ab81c52bbab7f Mon Sep 17 00:00:00 2001 From: NotCapengeR Date: Sat, 30 Nov 2024 14:43:58 +0500 Subject: [PATCH 3/7] Space fix --- tests/test_exceptions.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/test_exceptions.cpp b/tests/test_exceptions.cpp index d5274324d..bd5caef7c 100644 --- a/tests/test_exceptions.cpp +++ b/tests/test_exceptions.cpp @@ -34,7 +34,7 @@ int tests::test_load_with_exception_table(LPCTSTR path) peconv::run_tls_callbacks(loaded_pe, v_size); ULONGLONG ep_exp_offset = (ULONGLONG)loaded_pe + peconv::get_entry_point_rva(loaded_pe); - void(_cdecl * ep_func)() = (void(_cdecl*)()) (ep_exp_offset); + void(_cdecl *ep_func)() = (void(_cdecl *)()) (ep_exp_offset); std::wcout << "Calling entry point:" << std::endl; ep_func(); } From 80a10156aefc563dfff35a84e27d1c48d69250e2 Mon Sep 17 00:00:00 2001 From: NotCapengeR Date: Wed, 4 Dec 2024 14:31:17 +0500 Subject: [PATCH 4/7] CLang & MinGW support in exception_parser --- libpeconv/include/peconv/util.h | 16 +++- libpeconv/src/exceptions_parser.cpp | 124 +++++++++++++++------------- 2 files changed, 80 insertions(+), 60 deletions(-) diff --git a/libpeconv/include/peconv/util.h b/libpeconv/include/peconv/util.h index 822601a7f..9ee7d87da 100644 --- a/libpeconv/include/peconv/util.h +++ b/libpeconv/include/peconv/util.h @@ -8,6 +8,17 @@ #include "file_util.h" #include "resource_util.h" +#ifdef _MSC_VER +#define PECONV_FORCEINLINE __forceinline +#define PECONV_TRY_EXCEPT_BLOCK_START __try { +#define PECONV_TRY_EXCEPT_BLOCK_END __except (EXCEPTION_EXECUTE_HANDLER) { +#else +#define PECONV_FORCEINLINE __attribute__((always_inline)) inline +#define PECONV_TRY_EXCEPT_BLOCK_START try { +#define PECONV_TRY_EXCEPT_BLOCK_END catch (...) { +#endif + + namespace peconv { /** Checks if the given buffer is fully filled with the specified character. @@ -15,7 +26,7 @@ namespace peconv { \param cave_size : size of the buffer to be checked \param padding_char : the required character */ - bool is_padding(const BYTE *cave_ptr, size_t cave_size, const BYTE padding_char); + bool is_padding(const BYTE* cave_ptr, size_t cave_size, const BYTE padding_char); /** Wrapper for GetProcessId - for a backward compatibility with old versions of Windows @@ -37,5 +48,4 @@ namespace peconv { \param areaSize : The size of the memory block, in bytes. If this parameter is zero, the return value is true (bad pointer). */ bool is_bad_read_ptr(LPCVOID areaStart, SIZE_T areaSize); -}; - +}; \ No newline at end of file diff --git a/libpeconv/src/exceptions_parser.cpp b/libpeconv/src/exceptions_parser.cpp index e537e91df..f2c42de8b 100644 --- a/libpeconv/src/exceptions_parser.cpp +++ b/libpeconv/src/exceptions_parser.cpp @@ -1,4 +1,5 @@ #include "peconv/exceptions_parser.h" +#include "peconv/util.h" #include "peconv/pe_hdrs_helper.h" #include "ntddk.h" @@ -7,6 +8,10 @@ #include #endif +#ifndef min +#define min(a,b) (((a) < (b)) ? (a) : (b)) +#endif + namespace details { #define RTL_VERIFY_FLAGS_MAJOR_VERSION 0 #define RTL_VERIFY_FLAGS_MINOR_VERSION 1 @@ -157,7 +162,7 @@ namespace details { _In_ ULONG BuildNumber ) { NtVersion version{}; - RtlSecureZeroMemory(&version, sizeof NtVersion); + RtlSecureZeroMemory(&version, sizeof(NtVersion)); RtlCurrentVersion(&version); if (version.MajorVersion == MajorVersion) { if (version.MinorVersion == MinorVersion) return version.BuildNumber >= BuildNumber; @@ -173,7 +178,7 @@ namespace details { _In_ BYTE Flags ) { NtVersion version{}; - RtlSecureZeroMemory(&version, sizeof NtVersion); + RtlSecureZeroMemory(&version, sizeof(NtVersion)); RtlCurrentVersion(&version); if (version.MajorVersion == MajorVersion && ((Flags & RTL_VERIFY_FLAGS_MINOR_VERSION) ? version.MinorVersion == MinorVersion : true) && @@ -211,7 +216,7 @@ namespace details { } #endif - static __forceinline bool IsModuleUnloaded(PLDR_DATA_TABLE_ENTRY entry) { + static PECONV_FORCEINLINE bool IsModuleUnloaded(PLDR_DATA_TABLE_ENTRY entry) { if (RtlIsWindowsVersionOrGreater(6, 2, 0)) { // Windows 8+ return PLDR_DATA_TABLE_ENTRY_WIN8(entry)->DdagNode->State == LdrModulesUnloaded; } @@ -226,12 +231,17 @@ namespace details { _Inout_ PSEARCH_CONTEXT SearchContext) { NTSTATUS status = STATUS_SUCCESS; +#ifdef _MSC_VER +#define RtlFindMemoryBlockFromModuleSection__leave __leave +#else +#define RtlFindMemoryBlockFromModuleSection__leave return status +#endif #ifdef _DEBUG std::cout << "Searching in section " << SectionName << " in module " << ModuleHandle << std::endl; #endif - __try { + PECONV_TRY_EXCEPT_BLOCK_START // // checks if no search pattern and length are provided @@ -241,74 +251,74 @@ namespace details { SearchContext->Result = nullptr; SearchContext->MemoryBlockSize = 0; status = STATUS_INVALID_PARAMETER; - __leave; + RtlFindMemoryBlockFromModuleSection__leave; } - if (SearchContext->Result) { - ++SearchContext->Result; - --SearchContext->MemoryBlockSize; - } - else { - - // - // if it is the first search, find the length and start address of the specified section - // + if (SearchContext->Result) { + ++SearchContext->Result; + --SearchContext->MemoryBlockSize; + } + else { - auto headers = reinterpret_cast(RtlImageNtHeader(ModuleHandle)); - PIMAGE_SECTION_HEADER section = nullptr; + // + // if it is the first search, find the length and start address of the specified section + // - if (headers) { - section = IMAGE_FIRST_SECTION(headers); - for (WORD i = 0; i < headers->FileHeader.NumberOfSections; ++i) { - if (!_strnicmp(SectionName, reinterpret_cast(section->Name), 8)) { - SearchContext->Result = reinterpret_cast(ModuleHandle) + section->VirtualAddress; - SearchContext->MemoryBlockSize = section->Misc.VirtualSize; - break; - } + auto headers = reinterpret_cast(RtlImageNtHeader(ModuleHandle)); + PIMAGE_SECTION_HEADER section = nullptr; - ++section; + if (headers) { + section = IMAGE_FIRST_SECTION(headers); + for (WORD i = 0; i < headers->FileHeader.NumberOfSections; ++i) { + if (!_strnicmp(SectionName, reinterpret_cast(section->Name), 8)) { + SearchContext->Result = reinterpret_cast(ModuleHandle) + section->VirtualAddress; + SearchContext->MemoryBlockSize = section->Misc.VirtualSize; + break; } - if (!SearchContext->Result || !SearchContext->MemoryBlockSize || SearchContext->MemoryBlockSize < SearchContext->PatternSize) { - SearchContext->Result = nullptr; - SearchContext->MemoryBlockSize = 0; - status = STATUS_NOT_FOUND; - __leave; - } + ++section; } - else { - status = STATUS_INVALID_PARAMETER_1; - __leave; + + if (!SearchContext->Result || !SearchContext->MemoryBlockSize || SearchContext->MemoryBlockSize < SearchContext->PatternSize) { + SearchContext->Result = nullptr; + SearchContext->MemoryBlockSize = 0; + status = STATUS_NOT_FOUND; + RtlFindMemoryBlockFromModuleSection__leave; } } + else { + status = STATUS_INVALID_PARAMETER_1; + RtlFindMemoryBlockFromModuleSection__leave; + } + } - // - // perform a linear search on the pattern - // - - LPBYTE end = SearchContext->Result + SearchContext->MemoryBlockSize - SearchContext->PatternSize; - while (SearchContext->Result <= end) { - if (RtlCompareMemory(SearchContext->SearchPattern, SearchContext->Result, SearchContext->PatternSize) == SearchContext->PatternSize) { - __leave; - } + // + // perform a linear search on the pattern + // - ++SearchContext->Result; - --SearchContext->MemoryBlockSize; + LPBYTE end = SearchContext->Result + SearchContext->MemoryBlockSize - SearchContext->PatternSize; + while (SearchContext->Result <= end) { + if (RtlCompareMemory(SearchContext->SearchPattern, SearchContext->Result, SearchContext->PatternSize) == SearchContext->PatternSize) { + RtlFindMemoryBlockFromModuleSection__leave; } - // - // if the search fails, clear the output parameters - // - - SearchContext->Result = nullptr; - SearchContext->MemoryBlockSize = 0; - status = STATUS_NOT_FOUND; - } - __except (EXCEPTION_EXECUTE_HANDLER) { - status = GetExceptionCode(); + ++SearchContext->Result; + --SearchContext->MemoryBlockSize; } - return status; + // + // if the search fails, clear the output parameters + // + + SearchContext->Result = nullptr; + SearchContext->MemoryBlockSize = 0; + status = STATUS_NOT_FOUND; + } + PECONV_TRY_EXCEPT_BLOCK_END + status = GetExceptionCode(); +} + +return status; } static NTSTATUS RtlProtectMrdata(_In_ ULONG Protect, PRTL_INVERTED_FUNCTION_TABLE mrdata) { @@ -611,4 +621,4 @@ bool peconv::setup_exceptions(IN BYTE* modulePtr, IN size_t moduleSize) moduleSize = img_size; } return NT_SUCCESS(details::RtlInsertInvertedFunctionTable(modulePtr, moduleSize)); -} +} \ No newline at end of file From 489ae34ef597cf5e5641c36572e1ddff07a53334 Mon Sep 17 00:00:00 2001 From: NotCapengeR Date: Wed, 4 Dec 2024 14:46:17 +0500 Subject: [PATCH 5/7] MinGW & CLang support in exception_parser --- libpeconv/src/exceptions_parser.cpp | 124 +++++++++++++++------------- 1 file changed, 67 insertions(+), 57 deletions(-) diff --git a/libpeconv/src/exceptions_parser.cpp b/libpeconv/src/exceptions_parser.cpp index e537e91df..f2c42de8b 100644 --- a/libpeconv/src/exceptions_parser.cpp +++ b/libpeconv/src/exceptions_parser.cpp @@ -1,4 +1,5 @@ #include "peconv/exceptions_parser.h" +#include "peconv/util.h" #include "peconv/pe_hdrs_helper.h" #include "ntddk.h" @@ -7,6 +8,10 @@ #include #endif +#ifndef min +#define min(a,b) (((a) < (b)) ? (a) : (b)) +#endif + namespace details { #define RTL_VERIFY_FLAGS_MAJOR_VERSION 0 #define RTL_VERIFY_FLAGS_MINOR_VERSION 1 @@ -157,7 +162,7 @@ namespace details { _In_ ULONG BuildNumber ) { NtVersion version{}; - RtlSecureZeroMemory(&version, sizeof NtVersion); + RtlSecureZeroMemory(&version, sizeof(NtVersion)); RtlCurrentVersion(&version); if (version.MajorVersion == MajorVersion) { if (version.MinorVersion == MinorVersion) return version.BuildNumber >= BuildNumber; @@ -173,7 +178,7 @@ namespace details { _In_ BYTE Flags ) { NtVersion version{}; - RtlSecureZeroMemory(&version, sizeof NtVersion); + RtlSecureZeroMemory(&version, sizeof(NtVersion)); RtlCurrentVersion(&version); if (version.MajorVersion == MajorVersion && ((Flags & RTL_VERIFY_FLAGS_MINOR_VERSION) ? version.MinorVersion == MinorVersion : true) && @@ -211,7 +216,7 @@ namespace details { } #endif - static __forceinline bool IsModuleUnloaded(PLDR_DATA_TABLE_ENTRY entry) { + static PECONV_FORCEINLINE bool IsModuleUnloaded(PLDR_DATA_TABLE_ENTRY entry) { if (RtlIsWindowsVersionOrGreater(6, 2, 0)) { // Windows 8+ return PLDR_DATA_TABLE_ENTRY_WIN8(entry)->DdagNode->State == LdrModulesUnloaded; } @@ -226,12 +231,17 @@ namespace details { _Inout_ PSEARCH_CONTEXT SearchContext) { NTSTATUS status = STATUS_SUCCESS; +#ifdef _MSC_VER +#define RtlFindMemoryBlockFromModuleSection__leave __leave +#else +#define RtlFindMemoryBlockFromModuleSection__leave return status +#endif #ifdef _DEBUG std::cout << "Searching in section " << SectionName << " in module " << ModuleHandle << std::endl; #endif - __try { + PECONV_TRY_EXCEPT_BLOCK_START // // checks if no search pattern and length are provided @@ -241,74 +251,74 @@ namespace details { SearchContext->Result = nullptr; SearchContext->MemoryBlockSize = 0; status = STATUS_INVALID_PARAMETER; - __leave; + RtlFindMemoryBlockFromModuleSection__leave; } - if (SearchContext->Result) { - ++SearchContext->Result; - --SearchContext->MemoryBlockSize; - } - else { - - // - // if it is the first search, find the length and start address of the specified section - // + if (SearchContext->Result) { + ++SearchContext->Result; + --SearchContext->MemoryBlockSize; + } + else { - auto headers = reinterpret_cast(RtlImageNtHeader(ModuleHandle)); - PIMAGE_SECTION_HEADER section = nullptr; + // + // if it is the first search, find the length and start address of the specified section + // - if (headers) { - section = IMAGE_FIRST_SECTION(headers); - for (WORD i = 0; i < headers->FileHeader.NumberOfSections; ++i) { - if (!_strnicmp(SectionName, reinterpret_cast(section->Name), 8)) { - SearchContext->Result = reinterpret_cast(ModuleHandle) + section->VirtualAddress; - SearchContext->MemoryBlockSize = section->Misc.VirtualSize; - break; - } + auto headers = reinterpret_cast(RtlImageNtHeader(ModuleHandle)); + PIMAGE_SECTION_HEADER section = nullptr; - ++section; + if (headers) { + section = IMAGE_FIRST_SECTION(headers); + for (WORD i = 0; i < headers->FileHeader.NumberOfSections; ++i) { + if (!_strnicmp(SectionName, reinterpret_cast(section->Name), 8)) { + SearchContext->Result = reinterpret_cast(ModuleHandle) + section->VirtualAddress; + SearchContext->MemoryBlockSize = section->Misc.VirtualSize; + break; } - if (!SearchContext->Result || !SearchContext->MemoryBlockSize || SearchContext->MemoryBlockSize < SearchContext->PatternSize) { - SearchContext->Result = nullptr; - SearchContext->MemoryBlockSize = 0; - status = STATUS_NOT_FOUND; - __leave; - } + ++section; } - else { - status = STATUS_INVALID_PARAMETER_1; - __leave; + + if (!SearchContext->Result || !SearchContext->MemoryBlockSize || SearchContext->MemoryBlockSize < SearchContext->PatternSize) { + SearchContext->Result = nullptr; + SearchContext->MemoryBlockSize = 0; + status = STATUS_NOT_FOUND; + RtlFindMemoryBlockFromModuleSection__leave; } } + else { + status = STATUS_INVALID_PARAMETER_1; + RtlFindMemoryBlockFromModuleSection__leave; + } + } - // - // perform a linear search on the pattern - // - - LPBYTE end = SearchContext->Result + SearchContext->MemoryBlockSize - SearchContext->PatternSize; - while (SearchContext->Result <= end) { - if (RtlCompareMemory(SearchContext->SearchPattern, SearchContext->Result, SearchContext->PatternSize) == SearchContext->PatternSize) { - __leave; - } + // + // perform a linear search on the pattern + // - ++SearchContext->Result; - --SearchContext->MemoryBlockSize; + LPBYTE end = SearchContext->Result + SearchContext->MemoryBlockSize - SearchContext->PatternSize; + while (SearchContext->Result <= end) { + if (RtlCompareMemory(SearchContext->SearchPattern, SearchContext->Result, SearchContext->PatternSize) == SearchContext->PatternSize) { + RtlFindMemoryBlockFromModuleSection__leave; } - // - // if the search fails, clear the output parameters - // - - SearchContext->Result = nullptr; - SearchContext->MemoryBlockSize = 0; - status = STATUS_NOT_FOUND; - } - __except (EXCEPTION_EXECUTE_HANDLER) { - status = GetExceptionCode(); + ++SearchContext->Result; + --SearchContext->MemoryBlockSize; } - return status; + // + // if the search fails, clear the output parameters + // + + SearchContext->Result = nullptr; + SearchContext->MemoryBlockSize = 0; + status = STATUS_NOT_FOUND; + } + PECONV_TRY_EXCEPT_BLOCK_END + status = GetExceptionCode(); +} + +return status; } static NTSTATUS RtlProtectMrdata(_In_ ULONG Protect, PRTL_INVERTED_FUNCTION_TABLE mrdata) { @@ -611,4 +621,4 @@ bool peconv::setup_exceptions(IN BYTE* modulePtr, IN size_t moduleSize) moduleSize = img_size; } return NT_SUCCESS(details::RtlInsertInvertedFunctionTable(modulePtr, moduleSize)); -} +} \ No newline at end of file From b1fd0c07ebcd4f233c50345523a97e941f2cdb30 Mon Sep 17 00:00:00 2001 From: NotCapengeR Date: Wed, 4 Dec 2024 14:56:43 +0500 Subject: [PATCH 6/7] Space fixes --- libpeconv/src/exceptions_parser.cpp | 111 ++++++++++++++-------------- 1 file changed, 54 insertions(+), 57 deletions(-) diff --git a/libpeconv/src/exceptions_parser.cpp b/libpeconv/src/exceptions_parser.cpp index f2c42de8b..ecb5b7225 100644 --- a/libpeconv/src/exceptions_parser.cpp +++ b/libpeconv/src/exceptions_parser.cpp @@ -1,17 +1,13 @@ #include "peconv/exceptions_parser.h" -#include "peconv/util.h" #include "peconv/pe_hdrs_helper.h" +#include "peconv/util.h" #include "ntddk.h" #ifdef _DEBUG #include #endif -#ifndef min -#define min(a,b) (((a) < (b)) ? (a) : (b)) -#endif - namespace details { #define RTL_VERIFY_FLAGS_MAJOR_VERSION 0 #define RTL_VERIFY_FLAGS_MINOR_VERSION 1 @@ -231,6 +227,7 @@ namespace details { _Inout_ PSEARCH_CONTEXT SearchContext) { NTSTATUS status = STATUS_SUCCESS; + #ifdef _MSC_VER #define RtlFindMemoryBlockFromModuleSection__leave __leave #else @@ -254,71 +251,71 @@ namespace details { RtlFindMemoryBlockFromModuleSection__leave; } - if (SearchContext->Result) { - ++SearchContext->Result; - --SearchContext->MemoryBlockSize; - } - else { + if (SearchContext->Result) { + ++SearchContext->Result; + --SearchContext->MemoryBlockSize; + } + else { - // - // if it is the first search, find the length and start address of the specified section - // + // + // if it is the first search, find the length and start address of the specified section + // + + auto headers = reinterpret_cast(RtlImageNtHeader(ModuleHandle)); + PIMAGE_SECTION_HEADER section = nullptr; - auto headers = reinterpret_cast(RtlImageNtHeader(ModuleHandle)); - PIMAGE_SECTION_HEADER section = nullptr; + if (headers) { + section = IMAGE_FIRST_SECTION(headers); + for (WORD i = 0; i < headers->FileHeader.NumberOfSections; ++i) { + if (!_strnicmp(SectionName, reinterpret_cast(section->Name), 8)) { + SearchContext->Result = reinterpret_cast(ModuleHandle) + section->VirtualAddress; + SearchContext->MemoryBlockSize = section->Misc.VirtualSize; + break; + } - if (headers) { - section = IMAGE_FIRST_SECTION(headers); - for (WORD i = 0; i < headers->FileHeader.NumberOfSections; ++i) { - if (!_strnicmp(SectionName, reinterpret_cast(section->Name), 8)) { - SearchContext->Result = reinterpret_cast(ModuleHandle) + section->VirtualAddress; - SearchContext->MemoryBlockSize = section->Misc.VirtualSize; - break; + ++section; } - ++section; + if (!SearchContext->Result || !SearchContext->MemoryBlockSize || SearchContext->MemoryBlockSize < SearchContext->PatternSize) { + SearchContext->Result = nullptr; + SearchContext->MemoryBlockSize = 0; + status = STATUS_NOT_FOUND; + RtlFindMemoryBlockFromModuleSection__leave; + } } - - if (!SearchContext->Result || !SearchContext->MemoryBlockSize || SearchContext->MemoryBlockSize < SearchContext->PatternSize) { - SearchContext->Result = nullptr; - SearchContext->MemoryBlockSize = 0; - status = STATUS_NOT_FOUND; + else { + status = STATUS_INVALID_PARAMETER_1; RtlFindMemoryBlockFromModuleSection__leave; } } - else { - status = STATUS_INVALID_PARAMETER_1; - RtlFindMemoryBlockFromModuleSection__leave; - } - } - // - // perform a linear search on the pattern - // + // + // perform a linear search on the pattern + // - LPBYTE end = SearchContext->Result + SearchContext->MemoryBlockSize - SearchContext->PatternSize; - while (SearchContext->Result <= end) { - if (RtlCompareMemory(SearchContext->SearchPattern, SearchContext->Result, SearchContext->PatternSize) == SearchContext->PatternSize) { - RtlFindMemoryBlockFromModuleSection__leave; - } + LPBYTE end = SearchContext->Result + SearchContext->MemoryBlockSize - SearchContext->PatternSize; + while (SearchContext->Result <= end) { + if (RtlCompareMemory(SearchContext->SearchPattern, SearchContext->Result, SearchContext->PatternSize) == SearchContext->PatternSize) { + RtlFindMemoryBlockFromModuleSection__leave; + } - ++SearchContext->Result; - --SearchContext->MemoryBlockSize; - } + ++SearchContext->Result; + --SearchContext->MemoryBlockSize; + } - // - // if the search fails, clear the output parameters - // + // + // if the search fails, clear the output parameters + // - SearchContext->Result = nullptr; - SearchContext->MemoryBlockSize = 0; - status = STATUS_NOT_FOUND; - } - PECONV_TRY_EXCEPT_BLOCK_END - status = GetExceptionCode(); -} + SearchContext->Result = nullptr; + SearchContext->MemoryBlockSize = 0; + status = STATUS_NOT_FOUND; + } + PECONV_TRY_EXCEPT_BLOCK_END + status = GetExceptionCode(); + } -return status; + return status; } static NTSTATUS RtlProtectMrdata(_In_ ULONG Protect, PRTL_INVERTED_FUNCTION_TABLE mrdata) { @@ -366,7 +363,7 @@ return status; SEARCH_CONTEXT SearchContext{}; SearchContext.SearchPattern = reinterpret_cast(&entry); SearchContext.PatternSize = sizeof(entry); - RtlSecureZeroMemory(&entry, sizeof entry); + RtlSecureZeroMemory(&entry, sizeof(entry)); // Windows 8 if (RtlVerifyVersion(6, 2, 0, RTL_VERIFY_FLAGS_MAJOR_VERSION | RTL_VERIFY_FLAGS_MINOR_VERSION)) { @@ -431,7 +428,7 @@ return status; auto NtdllHeaders = reinterpret_cast(RtlImageNtHeader(hNtdll)); PIMAGE_NT_HEADERS ModuleHeaders = nullptr; _RTL_INVERTED_FUNCTION_TABLE_ENTRY_WIN7_32 entry{}; - RtlSecureZeroMemory(&entry, sizeof entry); + RtlSecureZeroMemory(&entry, sizeof(entry)); LPCSTR lpSectionName = ".data"; SEARCH_CONTEXT SearchContext{ }; From 3e4d7aa8b49c68cdda5ba8d3936b503ba071f9da Mon Sep 17 00:00:00 2001 From: NotCapengeR Date: Wed, 4 Dec 2024 14:58:02 +0500 Subject: [PATCH 7/7] Space fix --- libpeconv/src/exceptions_parser.cpp | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/libpeconv/src/exceptions_parser.cpp b/libpeconv/src/exceptions_parser.cpp index ecb5b7225..29f44a0d3 100644 --- a/libpeconv/src/exceptions_parser.cpp +++ b/libpeconv/src/exceptions_parser.cpp @@ -8,6 +8,10 @@ #include #endif +#ifndef min +#define min(a,b) (((a) < (b)) ? (a) : (b)) +#endif + namespace details { #define RTL_VERIFY_FLAGS_MAJOR_VERSION 0 #define RTL_VERIFY_FLAGS_MINOR_VERSION 1