/* * Copyright (c) 2022 Winsider Seminars & Solutions, Inc. All rights reserved. * * This file is part of System Informer. * * Authors: * * wj32 2010-2015 * dmex 2017-2026 * */ #ifndef _PH_PHSUP_H #define _PH_PHSUP_H // This header file provides some useful definitions specific to phlib. // // Workaround for macro redefinition conflicts between Clang and MSVC. // Save and restore these definitions. // // See: https://github.com/llvm/llvm-project/issues/36748 // // C:\Program Files\LLVM\lib\clang\20\include\xmmintrin.h(2195,9): error: '_MM_HINT_T0' macro redefined [-Werror,-Wmacro-redefined] // 2195 | #define _MM_HINT_T0 3 // | ^ // C:\Program Files (x86)\Windows Kits\10\\include\10.0.26100.0\\um\winnt.h(3649,9): note: previous definition is here // 3649 | #define _MM_HINT_T0 1 // | // // Workaround for unused function warnings. // Narrowly suppress -Wunused-function warnings. // // C:\Program Files\LLVM\lib\clang\20\include\amxcomplexintrin.h(139,13): error: unused function '__tile_cmmimfp16ps' [-Werror,-Wunused-function] // 139 | static void __tile_cmmimfp16ps(__tile1024i *dst, __tile1024i src0, // | ^~~~~~~~~~~~~~~~~~ // C:\Program Files\LLVM\lib\clang\20\include\amxcomplexintrin.h(162,13): error: unused function '__tile_cmmrlfp16ps' [-Werror,-Wunused-function] // 162 | static void __tile_cmmrlfp16ps(__tile1024i *dst, __tile1024i src0, // | ^~~~~~~~~~~~~~~~~~ // #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wunused-function" #ifdef _MM_HINT_T0 #pragma push_macro("_MM_HINT_T0") #pragma push_macro("_MM_HINT_T1") #pragma push_macro("_MM_HINT_T2") #undef _MM_HINT_T0 #undef _MM_HINT_T1 #undef _MM_HINT_T2 #define PH_SAVED_MM_HINT_MACROS #endif // _MM_HINT_T0 #endif // __clang__ #include #ifdef __clang__ #pragma clang diagnostic pop #ifdef PH_SAVED_MM_HINT_MACROS #pragma pop_macro("_MM_HINT_T2") #pragma pop_macro("_MM_HINT_T1") #pragma pop_macro("_MM_HINT_T0") #undef PH_SAVED_MM_HINT_MACROS #endif // PH_SAVED_MM_HINT_MACROS #endif // __clang__ #include #include #include #include #include #include #include #include #include #include #include #include #include #include // // Memory // #if defined(_cplusplus) template FORCEINLINE T* PTR_ADD_OFFSET( _In_ const T* Pointer, _In_ const T* Offset ) { return reinterpret_cast( static_cast(Pointer) + static_cast(Offset) ); } template FORCEINLINE T* PTR_SUB_OFFSET( _In_ const T* Pointer, _In_ const T* Offset ) { return reinterpret_cast( static_cast(Pointer) - static_cast(Offset) ); } #else #define PTR_ADD_OFFSET(Pointer, Offset) ((PVOID)((PUCHAR)(Pointer) + (ULONG_PTR)(Offset))) #define PTR_SUB_OFFSET(Pointer, Offset) ((PVOID)((PUCHAR)(Pointer) - (ULONG_PTR)(Offset))) #endif #define PH_LARGE_BUFFER_SIZE (256 * 1024 * 1024) #define XMM_SIZE sizeof(__m128i) #define XMM_OFFSET(Payload) ((XMM_SIZE - 1) & (ULONG_PTR)(Payload)) #define XMM_CHARS (XMM_SIZE / sizeof(wchar_t)) #define XMM_CHAR_ALIGNED(Payload) (0 == (((ULONG_PTR)(Payload) + sizeof(wchar_t) - 1) & (0-sizeof(wchar_t)) & (XMM_SIZE-1))) #define XMM_PAGE_SAFE(Payload) (PAGE_OFFSET(Payload) <= (PAGE_SIZE - XMM_SIZE)) // // Exceptions // #define PhRaiseStatus(Status) RtlRaiseStatus(Status) #define SIMPLE_EXCEPTION_FILTER(Condition) \ ((Condition) ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH) // // Compiler // #ifdef DEBUG #define ASSUME_ASSERT(Expression) assert(Expression) #define ASSUME_NO_DEFAULT assert(FALSE) #else #define ASSUME_ASSERT(Expression) __assume(Expression) #define ASSUME_NO_DEFAULT __assume(FALSE) #endif #if defined(__clang__) || defined(__GNUC__) #define PH_RESTRICT __restrict__ #elif defined(_MSC_VER) #define PH_RESTRICT __restrict #else #define PH_RESTRICT #endif // // Math // #if defined(_M_IX86) #define UInt32Add32To64(a, b) ((unsigned __int64)(((unsigned __int64)((unsigned int)(a))) + ((unsigned int)(b)))) // Avoids warning C26451 (dmex) #define UInt32Sub32To64(a, b) ((unsigned __int64)(((unsigned __int64)((unsigned int)(a))) - ((unsigned int)(b)))) #define UInt32Div32To64(a, b) ((unsigned __int64)(((unsigned __int64)((unsigned int)(a))) / ((unsigned int)(b)))) #define UInt32Mul32To64(a, b) ((unsigned __int64)(((unsigned __int64)((unsigned int)(a))) * ((unsigned int)(b)))) #else #define UInt32Add32To64(a, b) (((unsigned __int64)((unsigned int)(a))) + ((unsigned __int64)((unsigned int)(b)))) // from UInt32x32To64 (dmex) #define UInt32Sub32To64(a, b) (((unsigned __int64)((unsigned int)(a))) - ((unsigned __int64)((unsigned int)(b)))) #define UInt32Div32To64(a, b) (((unsigned __int64)((unsigned int)(a))) / ((unsigned __int64)((unsigned int)(b)))) #define UInt32Mul32To64(a, b) (((unsigned __int64)((unsigned int)(a))) * ((unsigned __int64)((unsigned int)(b)))) #endif // // Time // #define PH_TICKS_PER_US (LONG64_C(1) * LONG64_C(10)) // 10 ticks (1 tick = 100 ns = 0.1 us) #define PH_TICKS_PER_MS (PH_TICKS_PER_US * LONG64_C(1000)) // 10 * 1,000 = 10,000 ticks/ms #define PH_TICKS_PER_SEC (PH_TICKS_PER_MS * LONG64_C(1000)) // 10,000 * 1,000 = 10,000,000 ticks/s #define PH_TICKS_PER_MIN (PH_TICKS_PER_SEC * LONG64_C(60)) // 10,000,000 * 60 #define PH_TICKS_PER_HOUR (PH_TICKS_PER_MIN * LONG64_C(60)) // previous * 60 #define PH_TICKS_PER_DAY (PH_TICKS_PER_HOUR * LONG64_C(24)) // previous * 24 #define PH_TICKS_PARTIAL_US(Ticks) ((((ULONG64)(Ticks)) / ((ULONG64)PH_TICKS_PER_US)) % ULONG64_C(1000)) #define PH_TICKS_PARTIAL_MS(Ticks) ((((ULONG64)(Ticks)) / ((ULONG64)PH_TICKS_PER_MS)) % ULONG64_C(1000)) #define PH_TICKS_PARTIAL_SEC(Ticks) ((((ULONG64)(Ticks)) / ((ULONG64)PH_TICKS_PER_SEC)) % ULONG64_C(60)) #define PH_TICKS_PARTIAL_MIN(Ticks) ((((ULONG64)(Ticks)) / ((ULONG64)PH_TICKS_PER_MIN)) % ULONG64_C(60)) #define PH_TICKS_PARTIAL_HOURS(Ticks) ((((ULONG64)(Ticks)) / ((ULONG64)PH_TICKS_PER_HOUR)) % ULONG64_C(24)) #define PH_TICKS_PARTIAL_DAYS(Ticks) (((ULONG64)(Ticks)) / ((ULONG64)PH_TICKS_PER_DAY)) #define PH_TICKS_TO_US(Ticks) (((ULONG64)(Ticks)) / (ULONG64)PH_TICKS_PER_US) #define PH_TICKS_TO_MS(Ticks) (((ULONG64)(Ticks)) / (ULONG64)PH_TICKS_PER_MS) #define PH_TICKS_TO_SEC(Ticks) (((ULONG64)(Ticks)) / (ULONG64)PH_TICKS_PER_SEC) #define PH_TICKS_TO_MIN(Ticks) (((ULONG64)(Ticks)) / (ULONG64)PH_TICKS_PER_MIN) #define PH_TICKS_TO_HOURS(Ticks) (((ULONG64)(Ticks)) / (ULONG64)PH_TICKS_PER_HOUR) #define PH_TICKS_TO_DAYS(Ticks) (((ULONG64)(Ticks)) / (ULONG64)PH_TICKS_PER_DAY) // Generate negative LONGLONG values for relative NT waits #define PH_TIMEOUT_US(Us) ((LONGLONG)(Us) * -((LONGLONG)PH_TICKS_PER_US)) //#define PH_TIMEOUT_MS(Ms) ((LONGLONG)(Ms) * -((LONGLONG)PH_TICKS_PER_MS)) //#define PH_TIMEOUT_SEC(Sec) ((LONGLONG)(Sec) * -((LONGLONG)PH_TICKS_PER_SEC)) #define PH_TIMEOUT_MIN(Min) ((LONGLONG)(Min) * -((LONGLONG)PH_TICKS_PER_MIN)) #define PH_TIMEOUT_MS PH_TICKS_PER_MS #define PH_TIMEOUT_SEC PH_TICKS_PER_SEC // 116444736000000000 ticks between 1601-01-01 and 1970-01-01 #define PH_TICKS_TO_UNIX_EPOCH (LONG64_C(11644473600) * PH_TICKS_PER_SEC) // Convert Windows NT Ticks to UNIX Epoch (Milliseconds) #define PH_TICKS_TO_UNIX_MS(Ticks) ((((ULONG64)(Ticks)) - PH_TICKS_TO_UNIX_EPOCH) / (ULONG64)PH_TICKS_PER_MS) // Convert UNIX Epoch (Milliseconds) to Windows NT Ticks #define PH_UNIX_MS_TO_TICKS(UnixMs) ((((ULONG64)(UnixMs)) * (ULONG64)PH_TICKS_PER_MS) + PH_TICKS_TO_UNIX_EPOCH) // // Annotations // /** * Indicates that a function assumes the specified number of references are available for the * object. * * \remarks Usually functions reference objects if they store them for later usage; this annotation * specifies that the caller must supply these extra references itself. In effect these references * are "transferred" to the function and must not be used. E.g. if you create an object and * immediately call a function with _Assume_refs_(1), you may no longer use the object since that * one reference you held is no longer yours. */ #define _Assume_refs_(count) #define _Callback_ /** * Indicates that a function may raise a software exception. * * \remarks Do not use this annotation for temporary usages of exceptions, e.g. unimplemented * functions. */ #define _May_raise_ // // Casts // // Zero extension and sign extension macros #define C_1uTo2(x) ((unsigned short)(unsigned char)(x)) #define C_1sTo2(x) ((unsigned short)(signed char)(x)) #define C_1uTo4(x) ((unsigned int)(unsigned char)(x)) #define C_1sTo4(x) ((unsigned int)(signed char)(x)) #define C_2uTo4(x) ((unsigned int)(unsigned short)(x)) #define C_2sTo4(x) ((unsigned int)(signed short)(x)) #define C_4uTo8(x) ((unsigned __int64)(unsigned int)(x)) #define C_4sTo8(x) ((unsigned __int64)(signed int)(x)) // // Sorting // typedef enum _PH_SORT_ORDER { NoSortOrder = 0, AscendingSortOrder, DescendingSortOrder } PH_SORT_ORDER, *PPH_SORT_ORDER; /** * Adjusts a comparison result to match the requested sort order. * * \param Result The original comparison result. * \param Order The sort order to apply. * \return The adjusted comparison result. */ FORCEINLINE LONG PhModifySort( _In_ LONG Result, _In_ PH_SORT_ORDER Order ) { switch (Order) { case AscendingSortOrder: return Result; case DescendingSortOrder: return -Result; default: return Result; } } #define PH_BUILTIN_COMPARE(value1, value2) \ if ((value1) > (value2)) \ return 1; \ else if ((value1) < (value2)) \ return -1; \ \ return 0 /** * Compares two signed 8-bit values. * * \param value1 The first value. * \param value2 The second value. * \return A negative, zero, or positive value depending on the comparison result. */ FORCEINLINE int charcmp( _In_ signed char value1, _In_ signed char value2 ) { return C_1sTo4(value1 - value2); } /** * Compares two unsigned 8-bit values. * * \param value1 The first value. * \param value2 The second value. * \return A negative, zero, or positive value depending on the comparison result. */ FORCEINLINE int ucharcmp( _In_ unsigned char value1, _In_ unsigned char value2 ) { PH_BUILTIN_COMPARE(value1, value2); } /** * Compares two signed 16-bit values. * * \param value1 The first value. * \param value2 The second value. * \return A negative, zero, or positive value depending on the comparison result. */ FORCEINLINE int shortcmp( _In_ signed short value1, _In_ signed short value2 ) { return C_2sTo4(value1 - value2); } /** * Compares two unsigned 16-bit values. * * \param value1 The first value. * \param value2 The second value. * \return A negative, zero, or positive value depending on the comparison result. */ FORCEINLINE int ushortcmp( _In_ unsigned short value1, _In_ unsigned short value2 ) { PH_BUILTIN_COMPARE(value1, value2); } /** * Compares two signed 32-bit values. * * \param value1 The first value. * \param value2 The second value. * \return A negative, zero, or positive value depending on the comparison result. */ FORCEINLINE int intcmp( _In_ int value1, _In_ int value2 ) { return value1 - value2; } /** * Compares two unsigned 32-bit values. * * \param value1 The first value. * \param value2 The second value. * \return A negative, zero, or positive value depending on the comparison result. */ FORCEINLINE int uintcmp( _In_ unsigned int value1, _In_ unsigned int value2 ) { PH_BUILTIN_COMPARE(value1, value2); } /** * Compares two signed 64-bit values. * * \param value1 The first value. * \param value2 The second value. * \return A negative, zero, or positive value depending on the comparison result. */ FORCEINLINE int int64cmp( _In_ __int64 value1, _In_ __int64 value2 ) { PH_BUILTIN_COMPARE(value1, value2); } /** * Compares two unsigned 64-bit values. * * \param value1 The first value. * \param value2 The second value. * \return A negative, zero, or positive value depending on the comparison result. */ FORCEINLINE int uint64cmp( _In_ unsigned __int64 value1, _In_ unsigned __int64 value2 ) { PH_BUILTIN_COMPARE(value1, value2); } /** * Compares two signed pointer-sized values. * * \param value1 The first value. * \param value2 The second value. * \return A negative, zero, or positive value depending on the comparison result. */ FORCEINLINE int intptrcmp( _In_ LONG_PTR value1, _In_ LONG_PTR value2 ) { PH_BUILTIN_COMPARE(value1, value2); } /** * Compares two unsigned pointer-sized values. * * \param value1 The first value. * \param value2 The second value. * \return A negative, zero, or positive value depending on the comparison result. */ FORCEINLINE int uintptrcmp( _In_ ULONG_PTR value1, _In_ ULONG_PTR value2 ) { PH_BUILTIN_COMPARE(value1, value2); } /** * Compares two single-precision floating-point values. * * \param value1 The first value. * \param value2 The second value. * \return A negative, zero, or positive value depending on the comparison result. */ FORCEINLINE int singlecmp( _In_ float value1, _In_ float value2 ) { PH_BUILTIN_COMPARE(value1, value2); } /** * Compares two double-precision floating-point values. * * \param value1 The first value. * \param value2 The second value. * \return A negative, zero, or positive value depending on the comparison result. */ FORCEINLINE int doublecmp( _In_ double value1, _In_ double value2 ) { PH_BUILTIN_COMPARE(value1, value2); } /** * Compares two optional Unicode strings without regard to case. * * \param Value1 The first string, or NULL. * \param Value2 The second string, or NULL. * \return A negative, zero, or positive value depending on the comparison result. */ FORCEINLINE int wcsicmp2( _In_opt_ PCWSTR Value1, _In_opt_ PCWSTR Value2 ) { if (Value1 && Value2) return _wcsicmp(Value1, Value2); else if (!Value1) return !Value2 ? 0 : -1; else return 1; } typedef int (__cdecl *PC_COMPARE_FUNCTION)(void *, const void *, const void *); // // Synchronization // /** * Atomically adds a pointer-sized value and returns the previous value. * * \param Addend The target value to update. * \param Value The value to add. * \return The original value before the addition. */ FORCEINLINE LONG_PTR __InterlockedExchangeAddPointer( _Inout_ _Interlocked_operand_ LONG_PTR volatile *Addend, _In_ LONG_PTR Value ) { #ifdef _WIN64 return (LONG_PTR)_InterlockedExchangeAdd64((volatile LONG64*)Addend, (LONG64)Value); #else return (LONG_PTR)_InterlockedExchangeAdd((volatile LONG*)Addend, (LONG)Value); #endif } #define _InterlockedExchangeAddPointer __InterlockedExchangeAddPointer /** * Atomically increments a pointer-sized value. * * \param Addend The target value to update. * \return The incremented value. */ FORCEINLINE LONG_PTR _InterlockedIncrementPointer( _Inout_ _Interlocked_operand_ LONG_PTR volatile *Addend ) { #ifdef _WIN64 return (LONG_PTR)_InterlockedIncrement64((volatile LONG64*)Addend); #else return (LONG_PTR)_InterlockedIncrement((volatile LONG*)Addend); #endif } /** * Atomically decrements a pointer-sized value. * * \param Addend The target value to update. * \return The decremented value. */ FORCEINLINE LONG_PTR __InterlockedDecrementPointer( _Inout_ _Interlocked_operand_ LONG_PTR volatile *Addend ) { #ifdef _WIN64 return (LONG_PTR)_InterlockedDecrement64((volatile LONG64*)Addend); #else return (LONG_PTR)_InterlockedDecrement((volatile LONG*)Addend); #endif } #define _InterlockedDecrementPointer __InterlockedDecrementPointer /** * Atomically clears the specified bit in a pointer-sized value. * * \param Base The target value to update. * \param Bit The zero-based bit index to clear. * \return TRUE if the bit was previously set; otherwise, FALSE. */ FORCEINLINE BOOLEAN _InterlockedBitTestAndResetPointer( _Inout_ _Interlocked_operand_ LONG_PTR volatile *Base, _In_ LONG_PTR Bit ) { #ifdef _WIN64 return _interlockedbittestandreset64((volatile LONG64*)Base, (LONG64)Bit); #else return _interlockedbittestandreset((volatile LONG*)Base, (LONG)Bit); #endif } /** * Atomically sets the specified bit in a pointer-sized value. * * \param Base The target value to update. * \param Bit The zero-based bit index to set. * \return TRUE if the bit was previously set; otherwise, FALSE. */ FORCEINLINE BOOLEAN _InterlockedBitTestAndSetPointer( _Inout_ _Interlocked_operand_ LONG_PTR volatile *Base, _In_ LONG_PTR Bit ) { #ifdef _WIN64 return _interlockedbittestandset64((volatile LONG64*)Base, (LONG64)Bit); #else return _interlockedbittestandset((volatile LONG*)Base, (LONG)Bit); #endif } /** * Atomically increments a value unless it is zero. * * \param Addend The target value to update. * \return TRUE if the increment succeeded; otherwise, FALSE. */ FORCEINLINE BOOLEAN _InterlockedIncrementNoZero( _Inout_ _Interlocked_operand_ LONG volatile *Addend ) { LONG value; LONG newValue; value = *Addend; while (TRUE) { if (value == 0) return FALSE; if ((newValue = _InterlockedCompareExchange( Addend, value + 1, value )) == value) { return TRUE; } value = newValue; } } /** * Atomically increments a value only while it remains positive. * * \param Addend The target value to update. * \return TRUE if the increment succeeded; otherwise, FALSE. */ FORCEINLINE BOOLEAN _InterlockedIncrementPositive( _Inout_ _Interlocked_operand_ LONG volatile *Addend ) { LONG value; LONG newValue; value = *Addend; while (TRUE) { if (value <= 0) return FALSE; if ((newValue = _InterlockedCompareExchange( Addend, value + 1, value )) == value) { return TRUE; } value = newValue; } } /** * Atomically reads a pointer value. * * \param Base The pointer to read. * \return The current pointer value. */ FORCEINLINE PVOID _InterlockedReadPointer( _Inout_ _Interlocked_operand_ volatile PVOID *Base ) { return _InterlockedCompareExchangePointer(Base, NULL, NULL); } /** * Atomically writes a pointer value. * * \param Base The pointer to update. * \param Value The new value to store. * \return The previous pointer value. */ FORCEINLINE PVOID _InterlockedWritePointer( _Inout_ _Interlocked_operand_ volatile PVOID* Base, _In_ PVOID Value ) { return _InterlockedExchangePointer(Base, Value); } #ifndef InterlockedReadPointer #define InterlockedReadPointer _InterlockedReadPointer #endif #ifndef InterlockedWritePointer #define InterlockedWritePointer _InterlockedWritePointer #endif // // Strings // #define PH_INT32_STR_LEN 12 #define PH_INT32_STR_LEN_1 (PH_INT32_STR_LEN + 1) #define PH_INT64_STR_LEN 50 #define PH_INT64_STR_LEN_1 (PH_INT64_STR_LEN + 1) #define PH_PTR_STR_LEN 24 #define PH_PTR_STR_LEN_1 (PH_PTR_STR_LEN + 1) #define PH_HEX_CHARS L"0123456789abcdef" #pragma warning(push) #pragma warning(disable:4996) /** * Formats a signed 32-bit integer as a decimal string. * * \param Destination The destination buffer. * \param Int32 The value to format. */ FORCEINLINE VOID PhPrintInt32( _Out_writes_(PH_INT32_STR_LEN_1) CONST PWSTR Destination, _In_ CONST LONG Int32 ) { _ltow(Int32, Destination, 10); } /** * Formats an unsigned 32-bit integer as a decimal string. * * \param Destination The destination buffer. * \param UInt32 The value to format. */ FORCEINLINE VOID PhPrintUInt32( _Out_writes_(PH_INT32_STR_LEN_1) CONST PWSTR Destination, _In_ CONST ULONG UInt32 ) { _ultow(UInt32, Destination, 10); } /** * Formats an unsigned 32-bit integer as a hexadecimal string. * * \param Destination The destination buffer. * \param UInt32 The value to format. */ FORCEINLINE VOID PhPrintUInt32IX( _Out_writes_(PH_PTR_STR_LEN_1) CONST PWSTR Destination, _In_ CONST ULONG UInt32 ) { _ultow(UInt32, Destination, 16); } /** * Formats a signed 64-bit integer as a decimal string. * * \param Destination The destination buffer. * \param Int64 The value to format. */ FORCEINLINE VOID PhPrintInt64( _Out_writes_(PH_INT64_STR_LEN_1) CONST PWSTR Destination, _In_ CONST LONG64 Int64 ) { _i64tow(Int64, Destination, 10); } /** * Formats an unsigned 64-bit integer as a decimal string. * * \param Destination The destination buffer. * \param UInt64 The value to format. */ FORCEINLINE VOID PhPrintUInt64( _Out_writes_(PH_INT64_STR_LEN_1) CONST PWSTR Destination, _In_ CONST ULONG64 UInt64 ) { _ui64tow(UInt64, Destination, 10); } /** * Formats a pointer with a hexadecimal prefix. * * \param Destination The destination buffer. * \param Pointer The pointer to format. */ FORCEINLINE VOID PhPrintPointer( _Out_writes_(PH_PTR_STR_LEN_1) PWSTR Destination, _In_opt_ PVOID Pointer ) { Destination[0] = L'0'; Destination[1] = L'x'; #ifdef _WIN64 _ui64tow((ULONG64)Pointer, &Destination[2], 16); #else _ultow((ULONG)Pointer, &Destination[2], 16); #endif } #pragma warning(pop) /** * Formats a pointer with a hexadecimal prefix and zero-padded digits. * * \param Destination The destination buffer. * \param Pointer The pointer to format. */ FORCEINLINE VOID PhPrintPointerPadZeros( _Out_writes_(PH_PTR_STR_LEN_1) PWSTR Destination, _In_ PVOID Pointer ) { ULONG_PTR ptr = (ULONG_PTR)Pointer; PWSTR dest = Destination; *dest++ = L'0'; *dest++ = L'x'; #ifdef _WIN64 *dest++ = PH_HEX_CHARS[ptr >> 60]; *dest++ = PH_HEX_CHARS[(ptr & 0x0f00000000000000) >> 56]; *dest++ = PH_HEX_CHARS[(ptr & 0x00f0000000000000) >> 52]; *dest++ = PH_HEX_CHARS[(ptr & 0x000f000000000000) >> 48]; *dest++ = PH_HEX_CHARS[(ptr & 0x0000f00000000000) >> 44]; *dest++ = PH_HEX_CHARS[(ptr & 0x00000f0000000000) >> 40]; *dest++ = PH_HEX_CHARS[(ptr & 0x000000f000000000) >> 36]; *dest++ = PH_HEX_CHARS[(ptr & 0x0000000f00000000) >> 32]; *dest++ = PH_HEX_CHARS[(ptr & 0x00000000f0000000) >> 28]; *dest++ = PH_HEX_CHARS[(ptr & 0x000000000f000000) >> 24]; *dest++ = PH_HEX_CHARS[(ptr & 0x0000000000f00000) >> 20]; *dest++ = PH_HEX_CHARS[(ptr & 0x00000000000f0000) >> 16]; *dest++ = PH_HEX_CHARS[(ptr & 0x000000000000f000) >> 12]; *dest++ = PH_HEX_CHARS[(ptr & 0x0000000000000f00) >> 8]; *dest++ = PH_HEX_CHARS[(ptr & 0x00000000000000f0) >> 4]; *dest++ = PH_HEX_CHARS[ptr & 0x000000000000000f]; #else *dest++ = PH_HEX_CHARS[ptr >> 28]; *dest++ = PH_HEX_CHARS[(ptr & 0x0f000000) >> 24]; *dest++ = PH_HEX_CHARS[(ptr & 0x00f00000) >> 20]; *dest++ = PH_HEX_CHARS[(ptr & 0x000f0000) >> 16]; *dest++ = PH_HEX_CHARS[(ptr & 0x0000f000) >> 12]; *dest++ = PH_HEX_CHARS[(ptr & 0x00000f00) >> 8]; *dest++ = PH_HEX_CHARS[(ptr & 0x000000f0) >> 4]; *dest++ = PH_HEX_CHARS[ptr & 0x0000000f]; #endif *dest = UNICODE_NULL; } // // Misc. // /** * Rounds the given value to the nearest multiple of the specified granularity. * * \param Value The value to round. * \param Granularity The granularity to which the value should be rounded. * \return The value rounded to the nearest multiple of granularity. */ FORCEINLINE ULONG64 PhRoundNumber( _In_ CONST ULONG64 Value, _In_ CONST ULONG64 Granularity ) { return (Value + Granularity / 2) / Granularity * Granularity; } /** * Multiplies a number by a numerator and divides by a denominator, with rounding. * * This function performs the operation: ((Number * Numerator) + (Denominator / 2)) / Denominator * using 32-bit unsigned integers, avoiding overflow and providing rounding. * * \param Number The base number to multiply. * \param Numerator The numerator for multiplication. * \param Denominator The denominator for division. * \return The result of the multiply-divide operation, rounded to the nearest integer. */ FORCEINLINE ULONG PhMultiplyDivide( _In_ CONST ULONG Number, _In_ CONST ULONG Numerator, _In_ CONST ULONG Denominator ) { //return (((ULONG64)Number * (ULONG64)Numerator + (ULONG64)Denominator / 2) / (ULONG64)Denominator); return UInt32Div32To64(UInt32Add32To64(UInt32Mul32To64(Number, Numerator), UInt32Div32To64(Denominator, 2)), Denominator); } /** * Multiplies a signed number by a numerator and divides by a denominator, with rounding. * * This function performs the operation: ((Number * Numerator) + (Denominator / 2)) / Denominator * for signed numbers, preserving the sign and providing rounding. * * \param Number The signed base number to multiply. * \param Numerator The numerator for multiplication. * \param Denominator The denominator for division. * \return The result of the signed multiply-divide operation, rounded to the nearest integer. */ FORCEINLINE LONG PhMultiplyDivideSigned( _In_ CONST LONG Number, _In_ CONST ULONG Numerator, _In_ CONST ULONG Denominator ) { if (Number >= 0) return (LONG)PhMultiplyDivide(Number, Numerator, Denominator); else return -(LONG)PhMultiplyDivide(-Number, Numerator, Denominator); } FORCEINLINE ULONG64 PhMultiply128( _In_ CONST ULONG64 Multiplicand, _In_ CONST ULONG64 Multiplier, _Out_ PULONG64 ProductHigh ) { #if !defined(WIDEMATHAPI) ULONG64 productHigh; ULONG64 productLow; #if defined(_M_X64) && !defined(_M_ARM64EC) productLow = UnsignedMultiply128(Multiplicand, Multiplier, &productHigh); #elif defined(_M_ARM64) || defined(_M_ARM64EC) || defined(_M_HYBRID_X86_ARM64) productLow = Multiplicand * Multiplier; productHigh = UnsignedMultiplyHigh(Multiplicand, Multiplier); #else { ULONG64 multiplicandLow = (ULONG)Multiplicand; ULONG64 multiplicandHigh = Multiplicand >> 32; ULONG64 multiplierLow = (ULONG)Multiplier; ULONG64 multiplierHigh = Multiplier >> 32; ULONG64 productLowLow = multiplicandLow * multiplierLow; ULONG64 productLowHigh = multiplicandLow * multiplierHigh; ULONG64 productHighLow = multiplicandHigh * multiplierLow; ULONG64 productHighHigh = multiplicandHigh * multiplierHigh; ULONG64 previousLow; productLow = productLowLow; productHigh = productHighHigh + (productLowHigh >> 32) + (productHighLow >> 32); previousLow = productLow; productLow += productLowHigh << 32; productHigh += productLow < previousLow; previousLow = productLow; productLow += productHighLow << 32; productHigh += productLow < previousLow; } #endif *ProductHigh = productHigh; return productLow; #else return UMUL128(Multiplicand, Multiplier, ProductHigh); #endif } FORCEINLINE ULONG64 PhDivide128( _In_ CONST ULONG64 DividendHigh, _In_ CONST ULONG64 DividendLow, _In_ CONST ULONG64 Divisor, _Out_ PULONG64 Remainder ) { #if !defined(WIDEMATHAPI) ULONG64 remainder; ULONG64 quotient; LONG shift; remainder = DividendHigh; quotient = 0; for (shift = 63; shift >= 0; shift--) { BOOLEAN carry = !!(remainder & (1ULL << 63)); remainder = (remainder << 1) | ((DividendLow >> shift) & 1); if (carry || remainder >= Divisor) { remainder -= Divisor; quotient |= 1ULL << shift; } } *Remainder = remainder; return quotient; #else return UDIV128(DividendHigh, DividendLow, Divisor, Remainder); #endif } _Success_(return) FORCEINLINE BOOLEAN PhMultiplyDivide128( _In_ CONST ULONG64 Number, _In_ CONST ULONG64 Numerator, _In_ CONST ULONG64 Denominator, _In_ CONST ULONG64 Addend, _Out_ PULONG64 Result ) { ULONG64 productHigh; ULONG64 productLow; ULONG64 remainder; if (Denominator == 0) return FALSE; productLow = PhMultiply128(Number, Numerator, &productHigh); if (Addend != 0) { ULONG64 previousLow = productLow; productLow += Addend; productHigh += productLow < previousLow; } if (productHigh >= Denominator) return FALSE; *Result = PhDivide128(productHigh, productLow, Denominator, &remainder); return TRUE; } /** * Multiplies two 64-bit numbers and divides the full 128-bit product. * * This function computes (Number * Numerator) / Denominator without losing * the high half of the multiplication. The quotient is truncated. * * \param Number The base number to multiply. * \param Numerator The numerator for multiplication. * \param Denominator The denominator for division. * \param Result Receives the quotient. The value is not modified on failure. * \return TRUE if the operation succeeded; FALSE if the denominator is zero * or the quotient does not fit in 64 bits. */ FORCEINLINE BOOLEAN PhMultiplyDivide64( _In_ CONST ULONG64 Number, _In_ CONST ULONG64 Numerator, _In_ CONST ULONG64 Denominator, _Out_ PULONG64 Result ) { return PhMultiplyDivide128(Number, Numerator, Denominator, 0, Result); } /** * Probes a user-supplied address for validity and alignment within a specified buffer. * * This function checks that the given `UserAddress` is properly aligned to the specified `Alignment`, * and that the memory region defined by `UserAddress` and `UserLength` is fully contained within * the buffer defined by `BufferAddress` and `BufferLength`. If any of these checks fail, a software * exception is raised. * * \param UserAddress The starting address of the user-supplied memory region to probe. * \param UserLength The length, in bytes, of the memory region to probe. * \param BufferAddress The base address of the buffer within which the user region must reside. * \param BufferLength The length, in bytes, of the buffer. * \param Alignment The required alignment, in bytes, for the user address. * \remarks * This function does not actually access the memory at `UserAddress`; it only performs pointer arithmetic * and alignment checks. Use this function before reading from or writing to user-supplied memory to ensure * safety and prevent access violations. */ FORCEINLINE VOID PhProbeAddress( _In_ CONST PVOID UserAddress, _In_ CONST SIZE_T UserLength, _In_ CONST PVOID BufferAddress, _In_ CONST SIZE_T BufferLength, _In_ CONST ULONG Alignment ) { if (UserLength != 0) { if (!IS_ALIGNED(UserAddress, Alignment)) { PhRaiseStatus(STATUS_DATATYPE_MISALIGNMENT); } ULONG_PTR userStartAddress = (ULONG_PTR)UserAddress; ULONG_PTR userEndAddress = userStartAddress + UserLength; ULONG_PTR bufferStartAddress = (ULONG_PTR)BufferAddress; ULONG_PTR bufferEndAddress = bufferStartAddress + BufferLength; if ( (userEndAddress < userStartAddress) || (bufferEndAddress < bufferStartAddress) || (userStartAddress < bufferStartAddress) || (userEndAddress > bufferEndAddress) ) { PhRaiseStatus(STATUS_ACCESS_VIOLATION); } } } /** * Probes an unaligned user address and checks if the specified span is within the bounds of the buffer. * * \param UserAddress The address to probe. * \param UserLength The length of the memory to probe. * \param BufferAddress The base address of the buffer. * \param BufferLength The length of the buffer. * \param Alignment The required alignment of the address. */ FORCEINLINE VOID PhProbeAddressUnaligned( _In_ VOID UNALIGNED* CONST UserAddress, _In_ CONST SIZE_T UserLength, _In_ CONST PVOID BufferAddress, _In_ CONST SIZE_T BufferLength, _In_ CONST ULONG Alignment ) { // Note: __unaligned only changes codegen where the pointer is dereferenced. // Neither helper ever reads *Address (only (ULONG_PTR) arithmetic + IS_ALIGNED), // so the new functions are inert on every target purely a type-level // accommodation for improved diagnostics. PhProbeAddress((PVOID)UserAddress, UserLength, BufferAddress, BufferLength, Alignment); } /** * Probes a user address for read access and checks if the specified user address is readable * and within the bounds of the buffer. * * \param UserAddress The address to probe. * \param UserLength The length of the memory to probe. * \param BufferAddress The base address of the buffer. * \param BufferLength The length of the buffer. * \param Alignment The required alignment of the address. */ FORCEINLINE VOID PhProbeForRead( _In_ CONST PVOID UserAddress, _In_ CONST SIZE_T UserLength, _In_ CONST PVOID BufferAddress, _In_ CONST SIZE_T BufferLength, _In_ CONST ULONG Alignment ) { ULONG_PTR startAddress; ULONG_PTR endAddress; ULONG_PTR p; if (UserLength != 0) { // Validate the requested span before touching the memory. PhProbeAddress(UserAddress, UserLength, BufferAddress, BufferLength, Alignment); startAddress = (ULONG_PTR)UserAddress; endAddress = startAddress + UserLength; p = startAddress; // Probe the first byte in the range to verify the initial page is readable. *((volatile UCHAR*)p); // Stop if rounding up by one page would wrap the address space. if (p > (ULONG_PTR_MAX - PAGE_SIZE)) return; // Round up to the first byte of the next page. p = (ULONG_PTR)PAGE_ALIGN(p) + PAGE_SIZE; // Probe the first byte of each remaining page that intersects the range. while (p < endAddress) { // Verify the current page is readable. *(volatile UCHAR*)p; // Stop before adding another page would wrap the address space. if (p > (ULONG_PTR_MAX - PAGE_SIZE)) break; // Advance to the first byte of the next page. p += PAGE_SIZE; } } } /** * Probes a user address for write access and checks if the specified user address is writable * and within the bounds of the buffer. * * \param UserAddress The address to probe. * \param UserLength The length of the memory to probe. * \param BufferAddress The base address of the buffer. * \param BufferLength The length of the buffer. * \param Alignment The required alignment of the address. */ FORCEINLINE VOID PhProbeForWrite( _In_ CONST PVOID UserAddress, _In_ CONST SIZE_T UserLength, _In_ CONST PVOID BufferAddress, _In_ CONST SIZE_T BufferLength, _In_ CONST ULONG Alignment ) { ULONG_PTR startAddress; ULONG_PTR endAddress; ULONG_PTR p; if (UserLength != 0) { // Validate the address span, alignment, boundaries, and overflow before touching the address. PhProbeAddress(UserAddress, UserLength, BufferAddress, BufferLength, Alignment); startAddress = (ULONG_PTR)UserAddress; endAddress = startAddress + UserLength; p = startAddress; // Probe the first byte in the range with a self-assignment to verify writability. *(volatile UCHAR*)p = *(volatile UCHAR*)p; // Stop if rounding up by one page would wrap the address space. if (p > (ULONG_PTR_MAX - PAGE_SIZE)) return; // Round up to the first byte of the next page. p = (ULONG_PTR)PAGE_ALIGN(p) + PAGE_SIZE; // p = (p + PAGE_SIZE) & ~((ULONG_PTR)PAGE_MASK); // Probe the first byte of each remaining page that intersects the range. while (p < endAddress) { // Verify the page is writable by performing a volatile read‑modify‑write. *(volatile UCHAR*)p = *(volatile UCHAR*)p; // Prevent wraparound before adding PAGE_SIZE. if (p > (ULONG_PTR_MAX - PAGE_SIZE)) break; // Advance to the first byte of the next page. p += PAGE_SIZE; } } } /** * Converts a millisecond timeout to a relative or infinite NT timeout value. * * \param Timeout Receives the converted timeout. * \param Milliseconds The timeout, in milliseconds, or `INFINITE`. * \return The `Timeout` pointer. */ FORCEINLINE PLARGE_INTEGER PhTimeoutFromMilliseconds( _Out_ CONST PLARGE_INTEGER Timeout, _In_ CONST ULONG Milliseconds ) { if (Milliseconds == INFINITE) Timeout->QuadPart = MINLONGLONG; else Timeout->QuadPart = -(LONGLONG)UInt32x32To64(Milliseconds, PH_TIMEOUT_MS); return Timeout; } /** * Clamps a single-precision floating-point value to the specified range. * * \param Value The value to clamp. * \param Min The lower bound. * \param Max The upper bound. * \return The clamped value. */ FORCEINLINE FLOAT PhClampSingle( _In_ FLOAT Value, _In_ FLOAT Min, _In_ FLOAT Max ) { return fminf(fmaxf(Value, Min), Max); } /** * Clamps a double-precision floating-point value to the specified range. * * \param Value The value to clamp. * \param Min The lower bound. * \param Max The upper bound. * \return The clamped value. */ FORCEINLINE DOUBLE PhClampDouble( _In_ DOUBLE Value, _In_ DOUBLE Min, _In_ DOUBLE Max ) { return fmin(fmax(Value, Min), Max); } #endif