HyperDbg Debugger
Loading...
Searching...
No Matches
common.h File Reference

header for HyperDbg's general functions for reading and converting and etc More...

Go to the source code of this file.

Macros

#define AssertReturn   return;
#define AssertReturnFalse   return FALSE;
#define AssertReturnOne   return 1;
#define PAUSE_MESSAGE_IN_USER_DEBUGGER   "\nTo pause the target process, run the 'pause' command"
#define ASSERT_MESSAGE_DRIVER_NOT_LOADED   "handle of the driver not found, probably the driver is not loaded. Did you use 'load' command?\n"
#define ASSERT_MESSAGE_KD_NOT_LOADED   "the kd (kernel debugger) module is not loaded. Did you use 'load kd' command?\n"
#define ASSERT_MESSAGE_VMM_NOT_LOADED   "the vmm (virtualization) module is not loaded. Did you use 'load vmm' command?\n"
#define ASSERT_MESSAGE_HYPERTRACE_NOT_LOADED   "the trace (hypertrace) module is not loaded. Did you use 'load trace' command?\n"
#define ASSERT_MESSAGE_BUILD_SIGNATURE_DOESNT_MATCH
#define ASSERT_MESSAGE_CANNOT_SPECIFY_PID
#define AssertReturnStmt(expr, stmt, rc)
#define AssertShowMessageReturnStmt(expr1, expr2, message1, message2, rc)
#define PAGE_SIZE   0x1000
 Size of each page (4096 bytes).
#define PAGE_ALIGN(Va)
 Aligning a page.
#define CPUID_ADDR_WIDTH   0x80000008
 Cpuid to get virtual address width.
#define DbgWaitForKernelResponse(KernelSyncObjectId)
#define DbgWaitForUserResponse(UserSyncObjectId)
#define DbgWaitSetKernelRequestData(KernelSyncObjectId, ReqData, ReqSize)
#define DbgWaitSetUserRequestData(UserSyncObjectId, ReqData, ReqSize)
#define DbgWaitGetKernelRequestData(KernelSyncObjectId, ReqData, ReqSize)
#define DbgWaitGetUserRequestData(UserSyncObjectId, ReqData, ReqSize)
#define DbgReceivedKernelResponse(KernelSyncObjectId)
#define DbgReceivedUserResponse(UserSyncObjectId)

Functions

BOOLEAN AsmVmxSupportDetection ()
VOID SpinlockLock (volatile LONG *Lock)
 Tries to get the lock and won't return until successfully get the lock.
VOID SpinlockLockWithCustomWait (volatile LONG *Lock, UINT32 MaximumWait)
 Tries to get the lock and won't return until successfully get the lock.
VOID SpinlockUnlock (volatile LONG *Lock)
 Release the lock.
VOID PrintBits (const UINT32 size, const VOID *ptr)
BOOL Replace (std::string &str, const std::string &from, const std::string &to)
VOID ReplaceAll (string &str, const string &from, const string &to)
const vector< string > Split (const string &s, const CHAR &c)
BOOLEAN IsNumber (const string &str)
UINT32 Log2Ceil (UINT32 n)
 Function to compute log2Ceil.
BOOLEAN IsHexNotation (const string &s)
vector< CHARHexToBytes (const string &hex)
BOOLEAN ConvertStringToUInt64 (string TextToConvert, PUINT64 Result)
BOOLEAN ConvertStringToUInt32 (string TextToConvert, PUINT32 Result)
BOOLEAN ConvertTokenToUInt64 (CommandToken TargetToken, PUINT64 Result)
 add ` between 64 bit values and convert them to string
BOOLEAN ConvertTokenToUInt32 (CommandToken TargetToken, PUINT32 Result)
 check and convert command token to a 32 bit unsigned integer
std::string GetCaseSensitiveStringFromCommandToken (CommandToken TargetToken)
 Get case sensitive string from command token.
std::string GetLowerStringFromCommandToken (CommandToken TargetToken)
 Get lower case string from command token.
BOOLEAN CompareLowerCaseStrings (CommandToken TargetToken, const CHAR *StringToCompare)
 Compare lower case strings.
BOOLEAN IsTokenBracketString (CommandToken TargetToken)
 Is token bracket string.
BOOLEAN HasEnding (string const &fullString, string const &ending)
 checks whether the string ends with a special string or not
BOOLEAN ValidateIP (const string &ip)
 Function to validate an IP address.
BOOL SetPrivilege (HANDLE Token, LPCTSTR Privilege, BOOL EnablePrivilege)
 SetPrivilege enables/disables process token privilege.
VOID Trim (std::string &s)
 trim from both ends and start of a string (in place)
std::string RemoveSpaces (std::string str)
 Remove all the spaces in a string.
BOOLEAN IsFileExistA (const CHAR *FileName)
 check if a file exist or not (ASCII)
BOOLEAN IsFileExistW (const WCHAR *FileName)
 check if a file exist or not (wide-char)
VOID GetConfigFilePath (PWCHAR ConfigPath)
 Get config path.
VOID StringToWString (std::wstring &ws, const std::string &s)
 convert std::string to std::wstring
SIZE_T FindCaseInsensitive (std::string Input, std::string ToSearch, SIZE_T Pos)
 Find case insensitive sub string in a given substring.
SIZE_T FindCaseInsensitiveW (std::wstring Input, std::wstring ToSearch, SIZE_T Pos)
 Find case insensitive sub string in a given substring (unicode).
CHARConvertStringVectorToCharPointerArray (const std::string &s)
 Convert vector<string> to char*.
std::vector< std::string > ListDirectory (const std::string &Directory, const std::string &Extension)
 Create a list of special files in a directory.
BOOLEAN IsEmptyString (CHAR *Text)
 Is empty character.
VOID CommonCpuidInstruction (UINT32 Func, UINT32 SubFunc, INT *CpuInfo)
 Get cpuid results.
BOOLEAN CheckCpuSupportRtm ()
 Check whether the processor supports RTM or not.
UINT32 Getx86VirtualAddressWidth ()
 Get virtual address width for x86 processors.
BOOLEAN CheckAccessValidityAndSafety (UINT64 TargetAddress, UINT32 Size)
 Check the safety to access the memory.
BOOLEAN VmxSupportDetection ()
 Detect whether the VMX is supported or not.

Detailed Description

header for HyperDbg's general functions for reading and converting and etc

Author
Sina Karvandi (sina@.nosp@m.hype.nosp@m.rdbg..nosp@m.org)
Version
0.1
Date
2020-05-27

Macro Definition Documentation

◆ ASSERT_MESSAGE_BUILD_SIGNATURE_DOESNT_MATCH

#define ASSERT_MESSAGE_BUILD_SIGNATURE_DOESNT_MATCH
Value:
"the handshaking process was successful; however, there is a mismatch between " \
"the version/build of the debuggee and the debugger. please use the same " \
"version/build for both the debuggee and debugger\n"
35#define ASSERT_MESSAGE_BUILD_SIGNATURE_DOESNT_MATCH "the handshaking process was successful; however, there is a mismatch between " \
36 "the version/build of the debuggee and the debugger. please use the same " \
37 "version/build for both the debuggee and debugger\n"

◆ ASSERT_MESSAGE_CANNOT_SPECIFY_PID

#define ASSERT_MESSAGE_CANNOT_SPECIFY_PID
Value:
"err, since HyperDbg won't context-switch to keep the system in a halted state, " \
"you cannot specify 'pid' for this command in the debugger mode. You can switch to the target process " \
"memory layout using the '.process' or the '.thread' command. After that, you can use " \
"this command without specifying the process ID. Alternatively, you can modify the current " \
"CR3 register to achieve the same functionality\n"
39#define ASSERT_MESSAGE_CANNOT_SPECIFY_PID "err, since HyperDbg won't context-switch to keep the system in a halted state, " \
40 "you cannot specify 'pid' for this command in the debugger mode. You can switch to the target process " \
41 "memory layout using the '.process' or the '.thread' command. After that, you can use " \
42 "this command without specifying the process ID. Alternatively, you can modify the current " \
43 "CR3 register to achieve the same functionality\n"

◆ ASSERT_MESSAGE_DRIVER_NOT_LOADED

#define ASSERT_MESSAGE_DRIVER_NOT_LOADED   "handle of the driver not found, probably the driver is not loaded. Did you use 'load' command?\n"

◆ ASSERT_MESSAGE_HYPERTRACE_NOT_LOADED

#define ASSERT_MESSAGE_HYPERTRACE_NOT_LOADED   "the trace (hypertrace) module is not loaded. Did you use 'load trace' command?\n"

◆ ASSERT_MESSAGE_KD_NOT_LOADED

#define ASSERT_MESSAGE_KD_NOT_LOADED   "the kd (kernel debugger) module is not loaded. Did you use 'load kd' command?\n"

◆ ASSERT_MESSAGE_VMM_NOT_LOADED

#define ASSERT_MESSAGE_VMM_NOT_LOADED   "the vmm (virtualization) module is not loaded. Did you use 'load vmm' command?\n"

◆ AssertReturn

#define AssertReturn   return;

◆ AssertReturnFalse

#define AssertReturnFalse   return FALSE;

◆ AssertReturnOne

#define AssertReturnOne   return 1;

◆ AssertReturnStmt

#define AssertReturnStmt ( expr,
stmt,
rc )
Value:
do \
{ \
if (expr) \
{ \
/* likely */ \
} \
else \
{ \
stmt; \
rc; \
} \
} while (0)
45#define AssertReturnStmt(expr, stmt, rc) \
46 do \
47 { \
48 if (expr) \
49 { \
50 /* likely */ \
51 } \
52 else \
53 { \
54 stmt; \
55 rc; \
56 } \
57 } while (0)

◆ AssertShowMessageReturnStmt

#define AssertShowMessageReturnStmt ( expr1,
expr2,
message1,
message2,
rc )
Value:
do \
{ \
if (expr1 && expr2) \
{ \
/* likely */ \
} \
else \
{ \
if (!expr1) \
ShowMessages(message1); \
else if (!expr2) \
ShowMessages(message2); \
rc; \
} \
} while (0)
59#define AssertShowMessageReturnStmt(expr1, expr2, message1, message2, rc) \
60 do \
61 { \
62 if (expr1 && expr2) \
63 { \
64 /* likely */ \
65 } \
66 else \
67 { \
68 if (!expr1) \
69 ShowMessages(message1); \
70 else if (!expr2) \
71 ShowMessages(message2); \
72 rc; \
73 } \
74 } while (0)

◆ CPUID_ADDR_WIDTH

#define CPUID_ADDR_WIDTH   0x80000008

Cpuid to get virtual address width.

◆ DbgReceivedKernelResponse

#define DbgReceivedKernelResponse ( KernelSyncObjectId)
Value:
do \
{ \
DEBUGGER_SYNCRONIZATION_EVENTS_STATE * SyncronizationObject = \
\
SyncronizationObject->IsOnWaitingState = FALSE; \
SetEvent(SyncronizationObject->EventHandle); \
} while (FALSE);
#define FALSE
Definition BasicTypes.h:113
DEBUGGER_SYNCRONIZATION_EVENTS_STATE g_KernelSyncronizationObjectsHandleTable[DEBUGGER_MAXIMUM_SYNCRONIZATION_KERNEL_DEBUGGER_OBJECTS]
In debugger (not debuggee), we save the handle of the user-mode listening thread for pauses here for ...
Definition globals.h:220
struct _DEBUGGER_SYNCRONIZATION_EVENTS_STATE DEBUGGER_SYNCRONIZATION_EVENTS_STATE
In debugger holds the state of events.
HANDLE EventHandle
Definition debugger.h:119
BOOLEAN IsOnWaitingState
Definition debugger.h:120
168#define DbgReceivedKernelResponse(KernelSyncObjectId) \
169 do \
170 { \
171 DEBUGGER_SYNCRONIZATION_EVENTS_STATE * SyncronizationObject = \
172 &g_KernelSyncronizationObjectsHandleTable[KernelSyncObjectId]; \
173 \
174 SyncronizationObject->IsOnWaitingState = FALSE; \
175 SetEvent(SyncronizationObject->EventHandle); \
176 } while (FALSE);

◆ DbgReceivedUserResponse

#define DbgReceivedUserResponse ( UserSyncObjectId)
Value:
do \
{ \
DEBUGGER_SYNCRONIZATION_EVENTS_STATE * SyncronizationObject = \
\
SyncronizationObject->IsOnWaitingState = FALSE; \
SetEvent(SyncronizationObject->EventHandle); \
} while (FALSE);
DEBUGGER_SYNCRONIZATION_EVENTS_STATE g_UserSyncronizationObjectsHandleTable[DEBUGGER_MAXIMUM_SYNCRONIZATION_USER_DEBUGGER_OBJECTS]
In debugger (not debuggee), we save the handle of the user-mode listening thread for pauses here for ...
Definition globals.h:198
178#define DbgReceivedUserResponse(UserSyncObjectId) \
179 do \
180 { \
181 DEBUGGER_SYNCRONIZATION_EVENTS_STATE * SyncronizationObject = \
182 &g_UserSyncronizationObjectsHandleTable[UserSyncObjectId]; \
183 \
184 SyncronizationObject->IsOnWaitingState = FALSE; \
185 SetEvent(SyncronizationObject->EventHandle); \
186 } while (FALSE);

◆ DbgWaitForKernelResponse

#define DbgWaitForKernelResponse ( KernelSyncObjectId)
Value:
do \
{ \
DEBUGGER_SYNCRONIZATION_EVENTS_STATE * SyncronizationObject = \
\
SyncronizationObject->IsOnWaitingState = TRUE; \
PlatformWaitForSingleObject(SyncronizationObject->EventHandle, INFINITE); \
\
} while (FALSE);
#define TRUE
Definition BasicTypes.h:114
98#define DbgWaitForKernelResponse(KernelSyncObjectId) \
99 do \
100 { \
101 DEBUGGER_SYNCRONIZATION_EVENTS_STATE * SyncronizationObject = \
102 &g_KernelSyncronizationObjectsHandleTable[KernelSyncObjectId]; \
103 \
104 SyncronizationObject->IsOnWaitingState = TRUE; \
105 PlatformWaitForSingleObject(SyncronizationObject->EventHandle, INFINITE); \
106 \
107 } while (FALSE);

◆ DbgWaitForUserResponse

#define DbgWaitForUserResponse ( UserSyncObjectId)
Value:
do \
{ \
DEBUGGER_SYNCRONIZATION_EVENTS_STATE * SyncronizationObject = \
\
SyncronizationObject->IsOnWaitingState = TRUE; \
PlatformWaitForSingleObject(SyncronizationObject->EventHandle, INFINITE); \
\
} while (FALSE);
109#define DbgWaitForUserResponse(UserSyncObjectId) \
110 do \
111 { \
112 DEBUGGER_SYNCRONIZATION_EVENTS_STATE * SyncronizationObject = \
113 &g_UserSyncronizationObjectsHandleTable[UserSyncObjectId]; \
114 \
115 SyncronizationObject->IsOnWaitingState = TRUE; \
116 PlatformWaitForSingleObject(SyncronizationObject->EventHandle, INFINITE); \
117 \
118 } while (FALSE);

◆ DbgWaitGetKernelRequestData

#define DbgWaitGetKernelRequestData ( KernelSyncObjectId,
ReqData,
ReqSize )
Value:
do \
{ \
DEBUGGER_SYNCRONIZATION_EVENTS_STATE * SyncronizationObject = \
\
*ReqData = SyncronizationObject->RequestData; \
*ReqSize = SyncronizationObject->RequestSize; \
SyncronizationObject->RequestData = NULL; \
SyncronizationObject->RequestSize = NULL_ZERO; \
\
} while (FALSE);
#define NULL_ZERO
Definition BasicTypes.h:110
UINT32 RequestSize
Definition debugger.h:122
PVOID RequestData
Definition debugger.h:121
142#define DbgWaitGetKernelRequestData(KernelSyncObjectId, ReqData, ReqSize) \
143 do \
144 { \
145 DEBUGGER_SYNCRONIZATION_EVENTS_STATE * SyncronizationObject = \
146 &g_KernelSyncronizationObjectsHandleTable[KernelSyncObjectId]; \
147 \
148 *ReqData = SyncronizationObject->RequestData; \
149 *ReqSize = SyncronizationObject->RequestSize; \
150 SyncronizationObject->RequestData = NULL; \
151 SyncronizationObject->RequestSize = NULL_ZERO; \
152 \
153 } while (FALSE);

◆ DbgWaitGetUserRequestData

#define DbgWaitGetUserRequestData ( UserSyncObjectId,
ReqData,
ReqSize )
Value:
do \
{ \
DEBUGGER_SYNCRONIZATION_EVENTS_STATE * SyncronizationObject = \
\
*ReqData = SyncronizationObject->RequestData; \
*ReqSize = SyncronizationObject->RequestSize; \
SyncronizationObject->RequestData = NULL; \
SyncronizationObject->RequestSize = NULL_ZERO; \
\
} while (FALSE);
155#define DbgWaitGetUserRequestData(UserSyncObjectId, ReqData, ReqSize) \
156 do \
157 { \
158 DEBUGGER_SYNCRONIZATION_EVENTS_STATE * SyncronizationObject = \
159 &g_UserSyncronizationObjectsHandleTable[UserSyncObjectId]; \
160 \
161 *ReqData = SyncronizationObject->RequestData; \
162 *ReqSize = SyncronizationObject->RequestSize; \
163 SyncronizationObject->RequestData = NULL; \
164 SyncronizationObject->RequestSize = NULL_ZERO; \
165 \
166 } while (FALSE);

◆ DbgWaitSetKernelRequestData

#define DbgWaitSetKernelRequestData ( KernelSyncObjectId,
ReqData,
ReqSize )
Value:
do \
{ \
DEBUGGER_SYNCRONIZATION_EVENTS_STATE * SyncronizationObject = \
\
SyncronizationObject->RequestData = (PVOID)ReqData; \
SyncronizationObject->RequestSize = (UINT32)ReqSize; \
\
} while (FALSE);
void * PVOID
Definition BasicTypes.h:56
unsigned int UINT32
Definition BasicTypes.h:54
120#define DbgWaitSetKernelRequestData(KernelSyncObjectId, ReqData, ReqSize) \
121 do \
122 { \
123 DEBUGGER_SYNCRONIZATION_EVENTS_STATE * SyncronizationObject = \
124 &g_KernelSyncronizationObjectsHandleTable[KernelSyncObjectId]; \
125 \
126 SyncronizationObject->RequestData = (PVOID)ReqData; \
127 SyncronizationObject->RequestSize = (UINT32)ReqSize; \
128 \
129 } while (FALSE);

◆ DbgWaitSetUserRequestData

#define DbgWaitSetUserRequestData ( UserSyncObjectId,
ReqData,
ReqSize )
Value:
do \
{ \
DEBUGGER_SYNCRONIZATION_EVENTS_STATE * SyncronizationObject = \
\
SyncronizationObject->RequestData = (PVOID)ReqData; \
SyncronizationObject->RequestSize = (UINT32)ReqSize; \
\
} while (FALSE);
131#define DbgWaitSetUserRequestData(UserSyncObjectId, ReqData, ReqSize) \
132 do \
133 { \
134 DEBUGGER_SYNCRONIZATION_EVENTS_STATE * SyncronizationObject = \
135 &g_UserSyncronizationObjectsHandleTable[UserSyncObjectId]; \
136 \
137 SyncronizationObject->RequestData = (PVOID)ReqData; \
138 SyncronizationObject->RequestSize = (UINT32)ReqSize; \
139 \
140 } while (FALSE);

◆ PAGE_ALIGN

#define PAGE_ALIGN ( Va)
Value:
((PVOID)((ULONG_PTR)(Va) & ~(PAGE_SIZE - 1)))
#define PAGE_SIZE
Size of each page (4096 bytes).
Definition common.h:80

Aligning a page.

◆ PAGE_SIZE

#define PAGE_SIZE   0x1000

Size of each page (4096 bytes).

◆ PAUSE_MESSAGE_IN_USER_DEBUGGER

#define PAUSE_MESSAGE_IN_USER_DEBUGGER   "\nTo pause the target process, run the 'pause' command"

Function Documentation

◆ AsmVmxSupportDetection()

BOOLEAN AsmVmxSupportDetection ( )
extern

◆ CheckAccessValidityAndSafety()

BOOLEAN CheckAccessValidityAndSafety ( UINT64 TargetAddress,
UINT32 Size )

Check the safety to access the memory.

Parameters
TargetAddress
Size
Returns
BOOLEAN
319{
320 return CheckAccessValidityAndSafetyWrapper(TargetAddress, Size, NULL_ZERO);
321}
BOOLEAN CheckAccessValidityAndSafetyWrapper(UINT64 TargetAddress, UINT32 Size, UINT32 ProcessId)
Check the safety to access the memory wrapper.
Definition AddressCheck.c:157

◆ CheckCpuSupportRtm()

BOOLEAN CheckCpuSupportRtm ( )

Check whether the processor supports RTM or not.

Returns
BOOLEAN
951{
952 INT Regs1[4];
953 INT Regs2[4];
954 BOOLEAN Result;
955
956 //
957 // TSX is controlled via MSR_IA32_TSX_CTRL. However, support for this
958 // MSR is enumerated by ARCH_CAP_TSX_MSR bit in MSR_IA32_ARCH_CAPABILITIES.
959 //
960 // TSX control (aka MSR_IA32_TSX_CTRL) is only available after a
961 // microcode update on CPUs that have their MSR_IA32_ARCH_CAPABILITIES
962 // bit MDS_NO=1. CPUs with MDS_NO=0 are not planned to get
963 // MSR_IA32_TSX_CTRL support even after a microcode update. Thus,
964 // tsx= cmdline requests will do nothing on CPUs without
965 // MSR_IA32_TSX_CTRL support.
966 //
967
968 CommonCpuidInstruction(0, 0, Regs1);
969 CommonCpuidInstruction(7, 0, Regs2);
970
971 //
972 // Check RTM and MPX extensions in order to filter out TSX on Haswell CPUs
973 //
974 Result = Regs1[0] >= 0x7 && (Regs2[1] & 0x4800) == 0x4800;
975
976 return Result;
977}
UCHAR BOOLEAN
Definition BasicTypes.h:35
int INT
Definition BasicTypes.h:43
VOID CommonCpuidInstruction(UINT32 Func, UINT32 SubFunc, INT *CpuInfo)
Get cpuid results.
Definition common.cpp:921

◆ CommonCpuidInstruction()

VOID CommonCpuidInstruction ( UINT32 Func,
UINT32 SubFunc,
INT * CpuInfo )

Get cpuid results.

Parameters
Func
SubFunc
CpuInfo
Returns
VOID
86{
87 CpuCpuIdEx(CpuInfo, Func, SubFunc);
88}
VOID CpuCpuIdEx(INT32 *CpuInfo, INT32 FunctionId, INT32 SubFunctionId)
Execute CPUID with sub-leaf.
Definition PlatformIntrinsics.c:274

◆ CompareLowerCaseStrings()

BOOLEAN CompareLowerCaseStrings ( CommandToken TargetToken,
const CHAR * StringToCompare )

Compare lower case strings.

Parameters
TargetTokenthe target command token
StringToComparethe string to compare
Returns
BOOLEAN shows whether text is equal or not
504{
505 //
506 // Extract the token type and value from the tuple
507 //
508 std::string TargetTokenValue = std::get<2>(TargetToken); // the second index is lower case
509
510 //
511 // Convert the token value to 64 bit unsigned integer
512 //
513 return _stricmp(TargetTokenValue.c_str(), StringToCompare) == 0;
514}

◆ ConvertStringToUInt32()

BOOLEAN ConvertStringToUInt32 ( string TextToConvert,
PUINT32 Result )

◆ ConvertStringToUInt64()

BOOLEAN ConvertStringToUInt64 ( string TextToConvert,
PUINT64 Result )

◆ ConvertStringVectorToCharPointerArray()

CHAR * ConvertStringVectorToCharPointerArray ( const std::string & s)

Convert vector<string> to char*.

use it like : std::transform(vs.begin(), vs.end(), std::back_inserter(vc), ConvertStringVectorToCharPointerArray); from: https://stackoverflow.com/questions/7048888/stdvectorstdstring-to-char-array

Parameters
s
Returns
CHAR*
906{
907 CHAR * Pc = new CHAR[s.size() + 1];
908 std::strcpy(Pc, s.c_str());
909 return Pc;
910}
char CHAR
Definition BasicTypes.h:33

◆ ConvertTokenToUInt32()

BOOLEAN ConvertTokenToUInt32 ( CommandToken TargetToken,
PUINT32 Result )

check and convert command token to a 32 bit unsigned integer

Parameters
TargetTokenthe target command token
Resultresult will be save to the pointer
Returns
BOOLEAN shows whether the conversion was successful or not
547{
548 //
549 // Extract the token type and value from the tuple
550 //
551 std::string TargetTokenValue = std::get<1>(TargetToken);
552
553 //
554 // Convert the token value to 32 bit unsigned integer
555 //
556 return ConvertStringToUInt32(TargetTokenValue, Result);
557}
BOOLEAN ConvertStringToUInt32(string TextToConvert, PUINT32 Result)

◆ ConvertTokenToUInt64()

BOOLEAN ConvertTokenToUInt64 ( CommandToken TargetToken,
PUINT64 Result )

add ` between 64 bit values and convert them to string

Parameters
Value
Returns
string */ string SeparateTo64BitValue(UINT64 Value) { ostringstream OstringStream; string Temp;

OstringStream << setw(16) << setfill('0') << hex << Value; Temp = OstringStream.str();

Temp.insert(8, 1, '`'); return Temp; }

/**

print bits and bytes for d* commands

Parameters
Size
Ptr
Returns
VOID */ VOID PrintBits(const UINT32 Size, const VOID * Ptr) { UCHAR * Buf = (UCHAR *)Ptr; UCHAR Byte; INT i, j;

for (i = Size - 1; i >= 0; i–) { for (j = 7; j >= 0; j–) { Byte = (Buf[i] >> j) & 1; ShowMessages("%u", Byte); } ShowMessages(" ", Byte); } }

/**

general replace all function

Parameters
str
from
to
Returns
VOID */ BOOL Replace(std::string & str, const std::string & from, const std::string & to) { SIZE_T StartPos = str.find(from); if (StartPos == std::string::npos) return FALSE; str.replace(StartPos, from.size(), to); return TRUE; }

/**

general replace all function

Parameters
str
from
to
Returns
VOID */ VOID ReplaceAll(string & str, const string & from, const string & to) { SIZE_T SartPos = 0;

if (from.empty()) return;

while ((SartPos = str.find(from, SartPos)) != std::string::npos) { str.replace(SartPos, from.length(), to); // // In case 'to' contains 'from', like replacing // 'x' with 'yx' // SartPos += to.length(); } }

/**

general split command

Parameters
starget string
csplitter (delimiter)
Returns
const vector<string> */ const vector<string> Split(const string & s, const CHAR & c) { string buff {""}; vector<string> v;

for (auto n : s) { if (n != c) buff += n; else if (n == c && !buff.empty()) { v.push_back(buff); buff.clear(); } } if (!buff.empty()) v.push_back(buff);

return v; }

/**

check if given string is a numeric string or not

Parameters
str
Returns
BOOLEAN */ BOOLEAN IsNumber(const string & str) { // // std::find_first_not_of searches the string for the first character // that does not match any of the characters specified in its arguments // return !str.empty() && (str.find_first_not_of("[0123456789]") == std::string::npos); }

/**

check whether the string is hex or not

Parameters
s
Returns
BOOLEAN */ BOOLEAN IsHexNotation(const string & s) { BOOLEAN IsAnyThing = FALSE;

for (auto & CptrChar : s) { IsAnyThing = TRUE;

if (!isxdigit(CptrChar)) { return FALSE; } } if (IsAnyThing) { return TRUE; } return FALSE; }

/**

check whether the string is decimal or not

Parameters
s
Returns
BOOLEAN */ BOOLEAN IsDecimalNotation(const string & s) { BOOLEAN IsAnyThing = FALSE;

for (auto & CptrChar : s) { IsAnyThing = TRUE;

if (!isdigit(CptrChar)) { return FALSE; } } if (IsAnyThing) { return TRUE; } return FALSE; }

/**

converts hex to bytes

Parameters
hex
Returns
vector<CHAR> */ vector<CHAR> HexToBytes(const string & hex) { vector<CHAR> Bytes;

for (UINT32 i = 0; i < hex.length(); i += 2) { std::string byteString = hex.substr(i, 2); CHAR Byte = (CHAR)strtol(byteString.c_str(), NULL, 16); Bytes.push_back(Byte); }

return Bytes; }

/**

check and convert string to a 64 bit unsigned integer and also check for special notations like 0x, 0n, etc.

Parameters
TextToConvertthe target string
Resultresult will be save to the pointer
Returns
BOOLEAN shows whether the conversion was successful or not */ BOOLEAN ConvertStringToUInt64(string TextToConvert, PUINT64 Result) { BOOLEAN IsDecimal = FALSE; // By default everything is hex

if (TextToConvert.rfind("0x", 0) == 0 || TextToConvert.rfind("0X", 0) == 0 || TextToConvert.rfind("\\x", 0) == 0 || TextToConvert.rfind("\\X", 0) == 0) { TextToConvert = TextToConvert.erase(0, 2); } else if (TextToConvert.rfind('x', 0) == 0 || TextToConvert.rfind('X', 0) == 0) { TextToConvert = TextToConvert.erase(0, 1); } else if (TextToConvert.rfind("0n", 0) == 0 || TextToConvert.rfind("0N", 0) == 0 || TextToConvert.rfind("\\n", 0) == 0 || TextToConvert.rfind("\\N", 0) == 0) { TextToConvert = TextToConvert.erase(0, 2); IsDecimal = TRUE; } else if (TextToConvert.rfind('n', 0) == 0 || TextToConvert.rfind('N', 0) == 0) { TextToConvert = TextToConvert.erase(0, 1); IsDecimal = TRUE; }

// // Remove '`' (if any)

TextToConvert.erase(remove(TextToConvert.begin(), TextToConvert.end(), '`'), TextToConvert.end());

if (IsDecimal) { if (!IsDecimalNotation(TextToConvert)) { // // Not decimal // return FALSE; } else { errno = 0; CHAR * Unparsed = NULL; const CHAR * S = TextToConvert.c_str(); const UINT64 N = strtoull(S, &Unparsed, 10);

if (errno || (!N && S == Unparsed)) { // fflush(stdout); // perror(s); return FALSE; }

*Result = N; return TRUE; } } else { // // It's not decimal // if (!IsHexNotation(TextToConvert)) { // // Not decimal and not hex! // return FALSE; } else { // // It's a hex number // const CHAR * Text = TextToConvert.c_str(); errno = 0; UINT64 ResultValue = strtoull(Text, NULL, 16);

*Result = ResultValue;

if (errno == EINVAL) { return FALSE; } else if (errno == ERANGE) { return TRUE; }

return TRUE; } } }

/**

check and convert string to a 32 bit unsigned it and also check for special notations like 0x etc.

Parameters
TextToConvertthe target string
Resultresult will be save to the pointer
Returns
BOOLEAN shows whether the conversion was successful or not */ BOOLEAN ConvertStringToUInt32(string TextToConvert, PUINT32 Result) { BOOLEAN IsDecimal = FALSE; // By default everything is hex

if (TextToConvert.rfind("0x", 0) == 0 || TextToConvert.rfind("0X", 0) == 0 || TextToConvert.rfind("\\x", 0) == 0 || TextToConvert.rfind("\\X", 0) == 0) { TextToConvert = TextToConvert.erase(0, 2); } else if (TextToConvert.rfind('x', 0) == 0 || TextToConvert.rfind('X', 0) == 0) { TextToConvert = TextToConvert.erase(0, 1); } else if (TextToConvert.rfind("0n", 0) == 0 || TextToConvert.rfind("0N", 0) == 0 || TextToConvert.rfind("\\n", 0) == 0 || TextToConvert.rfind("\\N", 0) == 0) { TextToConvert = TextToConvert.erase(0, 2); IsDecimal = TRUE; } else if (TextToConvert.rfind('n', 0) == 0 || TextToConvert.rfind('N', 0) == 0) { TextToConvert = TextToConvert.erase(0, 1); IsDecimal = TRUE; }

TextToConvert.erase(remove(TextToConvert.begin(), TextToConvert.end(), '`'), TextToConvert.end());

if (IsDecimal) { if (!IsDecimalNotation(TextToConvert)) { return FALSE; } else { try { INT I = std::stoi(TextToConvert); Result = I; return TRUE; } catch (std::invalid_argument const &) {

Bad input: std::invalid_argument thrown

            return FALSE;
        }
        catch (std::out_of_range const &)
        {

Integer overflow: std::out_of_range thrown

            return FALSE;
        }

        return FALSE;
    }
}
else
{

It's not decimal

    if (!IsHexNotation(TextToConvert))
    {
        return FALSE;
    }
    else
    {

It's hex number

        UINT32 TempResult;
        TempResult = stoi(TextToConvert, nullptr, 16);

Apply the results

         Result = TempResult;

        return TRUE;
    }
}

}

/**

check and convert command token to a 64 bit unsigned integer

Parameters
TargetTokenthe target command token
Resultresult will be save to the pointer
Returns
BOOLEAN shows whether the conversion was successful or not
448{
449 //
450 // Extract the token type and value from the tuple
451 //
452 std::string TargetTokenValue = std::get<1>(TargetToken);
453
454 //
455 // Convert the token value to 64 bit unsigned integer
456 //
457 return ConvertStringToUInt64(TargetTokenValue, Result);
458}
BOOLEAN ConvertStringToUInt64(string TextToConvert, PUINT64 Result)

◆ FindCaseInsensitive()

SIZE_T FindCaseInsensitive ( std::string Input,
std::string ToSearch,
SIZE_T Pos )

Find case insensitive sub string in a given substring.

Parameters
Input
ToSearch
Pos
Returns
SIZE_T
867{
868 // Convert complete given String to lower case
869 std::transform(Input.begin(), Input.end(), Input.begin(), ::tolower);
870 // Convert complete given Sub String to lower case
871 std::transform(ToSearch.begin(), ToSearch.end(), ToSearch.begin(), ::tolower);
872 // Find sub string in given string
873 return Input.find(ToSearch, Pos);
874}

◆ FindCaseInsensitiveW()

SIZE_T FindCaseInsensitiveW ( std::wstring Input,
std::wstring ToSearch,
SIZE_T Pos )

Find case insensitive sub string in a given substring (unicode).

Parameters
Input
ToSearch
Pos
Returns
SIZE_T
886{
887 // Convert complete given String to lower case
888 std::transform(Input.begin(), Input.end(), Input.begin(), ::tolower);
889 // Convert complete given Sub String to lower case
890 std::transform(ToSearch.begin(), ToSearch.end(), ToSearch.begin(), ::tolower);
891 // Find sub string in given string
892 return Input.find(ToSearch, Pos);
893}

◆ GetCaseSensitiveStringFromCommandToken()

std::string GetCaseSensitiveStringFromCommandToken ( CommandToken TargetToken)

Get case sensitive string from command token.

Parameters
TargetTokenthe target command token
Returns
string the string value of the token
468{
469 //
470 // Extract the token type and value from the tuple
471 //
472 std::string TargetTokenValue = std::get<1>(TargetToken); // the first index is case sensitive
473
474 return TargetTokenValue;
475}

◆ GetConfigFilePath()

VOID GetConfigFilePath ( PWCHAR ConfigPath)

Get config path.

Parameters
ConfigPath
793{
794 WCHAR CurrentPath[MAX_PATH] = {0};
795
796 //
797 // Get path file of current exe
798 //
799 GetModuleFileNameW(NULL, CurrentPath, MAX_PATH);
800
801 //
802 // Remove exe file name
803 //
804 PathRemoveFileSpecW(CurrentPath);
805
806 //
807 // Combine current exe path with config file name
808 //
809 PathCombineW(ConfigPath, CurrentPath, CONFIG_FILE_NAME);
810}
#define CONFIG_FILE_NAME
Config file name for HyperDbg.
Definition Definition.h:24

◆ GetLowerStringFromCommandToken()

std::string GetLowerStringFromCommandToken ( CommandToken TargetToken)

Get lower case string from command token.

Parameters
TargetTokenthe target command token
Returns
string the string value of the token
485{
486 //
487 // Extract the token type and value from the tuple
488 //
489 std::string TargetTokenValue = std::get<2>(TargetToken); // the second index is lower case
490
491 return TargetTokenValue;
492}

◆ Getx86VirtualAddressWidth()

UINT32 Getx86VirtualAddressWidth ( )

Get virtual address width for x86 processors.

Returns
UINT32
933{
934 INT Regs[4];
935
937
938 //
939 // Extracting bit 15:8 from eax register
940 //
941 return ((Regs[0] >> 8) & 0x0ff);
942}
#define CPUID_ADDR_WIDTH
Cpuid to get virtual address width.
Definition Constants.h:695

◆ HasEnding()

BOOLEAN HasEnding ( string const & fullString,
string const & ending )

checks whether the string ends with a special string or not

Parameters
fullString
ending
Returns
BOOLEAN if true then it shows that string ends with another string and if false then it shows that this string is not ended with the target string
570{
571 if (fullString.length() >= ending.length())
572 {
573 return (0 == fullString.compare(fullString.length() - ending.length(),
574 ending.length(),
575 ending));
576 }
577 else
578 {
579 return FALSE;
580 }
581}

◆ HexToBytes()

vector< CHAR > HexToBytes ( const string & hex)

◆ IsEmptyString()

BOOLEAN IsEmptyString ( CHAR * Text)

Is empty character.

Parameters
Text
766{
767 SIZE_T Len;
768
769 if (Text == NULL || Text[0] == '\0')
770 {
771 return TRUE;
772 }
773
774 Len = strlen(Text);
775 for (SIZE_T i = 0; i < Len; i++)
776 {
777 if (Text[i] != ' ' && Text[i] != '\t' && Text[i] != '\n')
778 {
779 return FALSE;
780 }
781 }
782
783 return TRUE;
784}

◆ IsFileExistA()

BOOLEAN IsFileExistA ( const CHAR * FileName)

check if a file exist or not (ASCII)

Parameters
FileNamepath of file
Returns
BOOLEAN shows whether the file exist or not
741{
742 struct stat buffer;
743 return (stat(FileName, &buffer) == 0);
744}

◆ IsFileExistW()

BOOLEAN IsFileExistW ( const WCHAR * FileName)

check if a file exist or not (wide-char)

Parameters
FileNamepath of file
Returns
BOOLEAN shows whether the file exist or not
754{
755 struct _stat64i32 buffer;
756 return (_wstat(FileName, &buffer) == 0);
757}

◆ IsHexNotation()

BOOLEAN IsHexNotation ( const string & s)

◆ IsNumber()

BOOLEAN IsNumber ( const string & str)

◆ IsTokenBracketString()

BOOLEAN IsTokenBracketString ( CommandToken TargetToken)

Is token bracket string.

Parameters
TargetTokenthe target command token
Returns
BOOLEAN shows whether the token is bracket string or not
525{
526 //
527 // Extract the token type and value from the tuple
528 //
529 CommandParsingTokenType TargetTokenValue = std::get<0>(TargetToken);
530
531 //
532 // Check if the token is a bracket string
533 //
534 return TargetTokenValue == CommandParsingTokenType::BracketString;
535}
CommandParsingTokenType
Command's parsing type (enum).
Definition commands.h:166
@ BracketString
Definition commands.h:170

◆ ListDirectory()

std::vector< std::string > ListDirectory ( const std::string & Directory,
const std::string & Extension )

Create a list of special files in a directory.

Parameters
Directory
Extension
Returns
std::vector<std::string>
821{
822 WIN32_FIND_DATAA FindData;
823 HANDLE Find = INVALID_HANDLE_VALUE;
824 std::string FullPath = Directory + "\\" + Extension;
825 std::vector<std::string> DirList;
826
827 Find = FindFirstFileA(FullPath.c_str(), &FindData);
828
829 if (Find == INVALID_HANDLE_VALUE)
830 throw std::runtime_error("invalid handle value! please check your path...");
831
832 while (FindNextFileA(Find, &FindData) != 0)
833 {
834 DirList.push_back(Directory + "\\" + std::string(FindData.cFileName));
835 }
836
837 FindClose(Find);
838
839 return DirList;
840}

◆ Log2Ceil()

UINT32 Log2Ceil ( UINT32 n)

Function to compute log2Ceil.

Parameters
n
Returns
UINT32
1264{
1265 if (n == 0)
1266 return 0; // log2Ceil(0) is undefined, returning 0 for safety.
1267
1268 n--; // Decrease by 1 to check if it is a power of 2
1269 UINT32 log2Floor = 0;
1270 while (n >>= 1)
1271 {
1272 log2Floor++;
1273 }
1274 return log2Floor + 1;
1275}

◆ PrintBits()

VOID PrintBits ( const UINT32 size,
const VOID * ptr )

◆ RemoveSpaces()

std::string RemoveSpaces ( std::string str)

Remove all the spaces in a string.

Parameters
str
728{
729 str.erase(remove(str.begin(), str.end(), ' '), str.end());
730 return str;
731}

◆ Replace()

BOOL Replace ( std::string & str,
const std::string & from,
const std::string & to )

◆ ReplaceAll()

VOID ReplaceAll ( string & str,
const string & from,
const string & to )

◆ SetPrivilege()

BOOL SetPrivilege ( HANDLE Token,
LPCTSTR Privilege,
BOOL EnablePrivilege )

SetPrivilege enables/disables process token privilege.

Parameters
Token
Privilege
EnablePrivilege
Returns
BOOL
647{
648 TOKEN_PRIVILEGES Tp;
649 LUID Luid;
650
651 if (!LookupPrivilegeValue(NULL, // lookup privilege on local system
652 Privilege, // privilege to lookup
653 &Luid)) // receives LUID of privilege
654 {
655 ShowMessages("err, in LookupPrivilegeValue (%x)\n", GetLastError());
656 return FALSE;
657 }
658
659 Tp.PrivilegeCount = 1;
660 Tp.Privileges[0].Luid = Luid;
661 if (EnablePrivilege)
662 Tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
663 else
664 Tp.Privileges[0].Attributes = 0;
665
666 //
667 // Enable the privilege or disable all privileges.
668 //
669 if (!AdjustTokenPrivileges(Token, FALSE, &Tp, sizeof(TOKEN_PRIVILEGES), (PTOKEN_PRIVILEGES)NULL, (PDWORD)NULL))
670 {
671 ShowMessages("err, in AdjustTokenPrivileges (%x)\n", GetLastError());
672 return FALSE;
673 }
674
675 if (GetLastError() == ERROR_NOT_ALL_ASSIGNED)
676 {
677 ShowMessages("err, the token does not have the specified (debug) privilege (ACCESS DENIED!)\n");
678 ShowMessages("make sure to run it with administrator privileges\n");
679 return FALSE;
680 }
681
682 return TRUE;
683}

◆ SpinlockLock()

VOID SpinlockLock ( volatile LONG * Lock)

Tries to get the lock and won't return until successfully get the lock.

Parameters
LockLock variable
Returns
VOID
54{
55 UINT32 Wait = 1;
56
57 while (!SpinlockTryLock(Lock))
58 {
59 for (UINT32 i = 0; i < Wait; ++i)
60 {
61 _mm_pause();
62 }
63
64 //
65 // Don't call "pause" too many times. If the Wait becomes too big,
66 // clamp it to the MaxWait.
67 //
68
69 if (Wait * 2 > g_MaxWait)
70 {
71 Wait = g_MaxWait;
72 }
73 else
74 {
75 Wait = Wait * 2;
76 }
77 }
78}
BOOLEAN SpinlockTryLock(volatile LONG *Lock)
Tries to get the lock otherwise returns.
Definition Spinlock.c:41

◆ SpinlockLockWithCustomWait()

VOID SpinlockLockWithCustomWait ( volatile LONG * Lock,
UINT32 MaximumWait )

Tries to get the lock and won't return until successfully get the lock.

Parameters
LockLock variable
MaximumWaitMaximum wait (pause) count
Returns
VOID
129{
130 UINT32 Wait = 1;
131
132 while (!SpinlockTryLock(Lock))
133 {
134 for (UINT32 i = 0; i < Wait; ++i)
135 {
136 _mm_pause();
137 }
138
139 //
140 // Don't call "pause" too many times. If the Wait becomes too big,
141 // clamp it to the MaxWait.
142 //
143
144 if (Wait * 2 > MaximumWait)
145 {
146 Wait = MaximumWait;
147 }
148 else
149 {
150 Wait = Wait * 2;
151 }
152 }
153}

◆ SpinlockUnlock()

VOID SpinlockUnlock ( volatile LONG * Lock)

Release the lock.

Parameters
LockLock variable
Returns
VOID
163{
164 *Lock = 0;
165}

◆ Split()

const vector< string > Split ( const string & s,
const CHAR & c )

◆ StringToWString()

VOID StringToWString ( std::wstring & ws,
const std::string & s )

convert std::string to std::wstring

Parameters
ws
s
Returns
VOID
851{
852 std::wstring WsTmp(s.begin(), s.end());
853
854 ws = WsTmp;
855}

◆ Trim()

VOID Trim ( std::string & s)

trim from both ends and start of a string (in place)

Parameters
s
716{
717 ltrim(s);
718 rtrim(s);
719}

◆ ValidateIP()

BOOLEAN ValidateIP ( const string & ip)

Function to validate an IP address.

Parameters
ip
Returns
BOOLEAN
591{
592 //
593 // split the string into tokens
594 //
595 vector<string> list = Split(ip, '.');
596
597 //
598 // if token size is not equal to four
599 //
600 if (list.size() != 4)
601 return FALSE;
602
603 //
604 // validate each token
605 //
606 for (string str : list)
607 {
608 //
609 // verify that string is number or not and the numbers
610 // are in the valid range
611 //
612 if (!IsNumber(str) || stoi(str) > 255 || stoi(str) < 0)
613 return FALSE;
614 }
615
616 return TRUE;
617}
BOOLEAN IsNumber(const string &str)
const vector< string > Split(const string &s, const CHAR &c)

◆ VmxSupportDetection()

BOOLEAN VmxSupportDetection ( )

Detect whether the VMX is supported or not.

Returns
true if vmx is supported
false if vmx is not supported
627{
628 //
629 // Call assembly function
630 //
631 return AsmVmxSupportDetection();
632}
BOOLEAN AsmVmxSupportDetection()