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

HyperDbg general functions for reading and converting and etc. More...

#include "pch.h"

Functions

string SeparateTo64BitValue (UINT64 Value)
 add ` between 64 bit values and convert them to string
 
VOID PrintBits (const UINT32 Size, const void *Ptr)
 print bits and bytes for d* commands
 
BOOL Replace (std::string &str, const std::string &from, const std::string &to)
 general replace all function
 
VOID ReplaceAll (string &str, const string &from, const string &to)
 general replace all function
 
const vector< string > Split (const string &s, const char &c)
 general split command
 
BOOLEAN IsNumber (const string &str)
 check if given string is a numeric string or not
 
BOOLEAN IsHexNotation (const string &s)
 check whether the string is hex or not
 
BOOLEAN IsDecimalNotation (const string &s)
 check whether the string is decimal or not
 
vector< char > HexToBytes (const string &hex)
 converts hex to bytes
 
BOOLEAN ConvertStringToUInt64 (string TextToConvert, PUINT64 Result)
 check and convert string to a 64 bit unsigned integer and also check for special notations like 0x, 0n, etc.
 
BOOLEAN ConvertStringToUInt32 (string TextToConvert, PUINT32 Result)
 check and convert string to a 32 bit unsigned it and also check for special notations like 0x etc.
 
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.
 
BOOLEAN VmxSupportDetection ()
 Detect whether the VMX is supported or not.
 
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_t *FileName)
 check if a file exist or not (wide-char)
 
BOOLEAN IsEmptyString (char *Text)
 Is empty character.
 
VOID GetConfigFilePath (PWCHAR ConfigPath)
 Get config path.
 
std::vector< std::string > ListDirectory (const std::string &Directory, const std::string &Extension)
 Create a list of special files in a directory.
 
VOID StringToWString (std::wstring &ws, const std::string &s)
 convert std::string to std::wstring
 
VOID SplitPathAndArgs (std::vector< std::string > &Qargs, const std::string &Command)
 Split path and arguments and handle strings between quotes.
 
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)
 
char * ConvertStringVectorToCharPointerArray (const std::string &s)
 Convert vector<string> to char*.
 
VOID CommonCpuidInstruction (UINT32 Func, UINT32 SubFunc, int *CpuInfo)
 Get cpuid results.
 
UINT32 Getx86VirtualAddressWidth ()
 Get virtual address width for x86 processors.
 
BOOLEAN CheckCpuSupportRtm ()
 Check whether the processor supports RTM or not.
 
BOOLEAN CheckAddressCanonicality (UINT64 VAddr, PBOOLEAN IsKernelAddress)
 Checks if the address is canonical based on x86 processor's virtual address width or not.
 
BOOLEAN CheckAddressValidityUsingTsx (UINT64 Address)
 This function checks whether the address is valid or not using Intel TSX.
 
BOOLEAN CheckAccessValidityAndSafety (UINT64 TargetAddress, UINT32 Size)
 Check the safety to access the memory.
 
UINT32 Log2Ceil (UINT32 n)
 Function to compute log2Ceil.
 

Variables

BOOLEAN g_RtmSupport
 check for RTM support
 
UINT32 g_VirtualAddressWidth
 Virtual address width for x86 processors.
 

Detailed Description

HyperDbg 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

Function Documentation

◆ CheckAccessValidityAndSafety()

BOOLEAN CheckAccessValidityAndSafety ( UINT64 TargetAddress,
UINT32 Size )

Check the safety to access the memory.

Parameters
TargetAddress
Size
Returns
BOOLEAN
1039{
1040 BOOLEAN IsKernelAddress;
1041 BOOLEAN Result = FALSE;
1042
1043 //
1044 // First, we check if the address is canonical based
1045 // on Intel processor's virtual address width
1046 //
1047 if (!CheckAddressCanonicality(TargetAddress, &IsKernelAddress))
1048 {
1049 //
1050 // No need for further check, address is invalid
1051 //
1052 return FALSE;
1053 }
1054
1055 //
1056 // We cannot check a kernel-mode address here in user-mode
1057 //
1058 if (IsKernelAddress)
1059 {
1060 return FALSE;
1061 }
1062
1063 //
1064 // We'll check address with TSX if it supports TSX RTM
1065 //
1066 if (g_RtmSupport)
1067 {
1068 //
1069 // *** The guest supports Intel TSX ***
1070 //
1071
1072 UINT64 AddressToCheck =
1073 (CHAR *)TargetAddress + Size - ((CHAR *)PAGE_ALIGN(TargetAddress));
1074
1075 if (AddressToCheck > PAGE_SIZE)
1076 {
1077 //
1078 // Address should be accessed in more than one page
1079 //
1080 UINT32 ReadSize = 0;
1081
1082 while (Size != 0)
1083 {
1084 ReadSize = (UINT32)((UINT64)PAGE_ALIGN(TargetAddress + PAGE_SIZE) - TargetAddress);
1085
1086 if (ReadSize == PAGE_SIZE && Size < PAGE_SIZE)
1087 {
1088 ReadSize = Size;
1089 }
1090
1091 if (!CheckAddressValidityUsingTsx(TargetAddress))
1092 {
1093 //
1094 // Address is not valid
1095 //
1096 return FALSE;
1097 }
1098
1099 /*
1100 ShowMessages("Addr From : %llx to Addr To : %llx | ReadSize : %llx\n",
1101 TargetAddress,
1102 TargetAddress + ReadSize,
1103 ReadSize);
1104 */
1105
1106 //
1107 // Apply the changes to the next addresses (if any)
1108 //
1109 Size = Size - ReadSize;
1110 TargetAddress = TargetAddress + ReadSize;
1111 }
1112 }
1113 else
1114 {
1115 if (!CheckAddressValidityUsingTsx(TargetAddress))
1116 {
1117 //
1118 // Address is not valid
1119 //
1120 return FALSE;
1121 }
1122 }
1123 }
1124 else
1125 {
1126 //
1127 // *** processor doesn't support RTM ***
1128 //
1129
1130 //
1131 // There is no way to perform this check! The below implementation doesn't satisfy
1132 // our needs for address checks, but we're not trying to ask kernel about it as
1133 // HyperDbg's script engine is not designed to be ran these functions in user-mode
1134 // so we left it unimplemented to avoid crashes in the main program
1135 //
1136 return FALSE;
1137
1138 //
1139 // Check if memory is safe and present
1140 //
1141
1142 UINT64 AddressToCheck =
1143 (CHAR *)TargetAddress + Size - ((CHAR *)PAGE_ALIGN(TargetAddress));
1144
1145 if (AddressToCheck > PAGE_SIZE)
1146 {
1147 //
1148 // Address should be accessed in more than one page
1149 //
1150 UINT32 ReadSize = 0;
1151
1152 while (Size != 0)
1153 {
1154 ReadSize = (UINT32)((UINT64)PAGE_ALIGN(TargetAddress + PAGE_SIZE) - TargetAddress);
1155
1156 if (ReadSize == PAGE_SIZE && Size < PAGE_SIZE)
1157 {
1158 ReadSize = Size;
1159 }
1160
1161 try
1162 {
1163 UINT64 ReadingTest = *((UINT64 *)TargetAddress);
1164 }
1165 catch (...)
1166 {
1167 //
1168 // Address is not valid
1169 //
1170 return FALSE;
1171 }
1172
1173 /*
1174 ShowMessages("Addr From : %llx to Addr To : %llx | ReadSize : %llx\n",
1175 TargetAddress,
1176 TargetAddress + ReadSize,
1177 ReadSize);
1178 */
1179
1180 //
1181 // Apply the changes to the next addresses (if any)
1182 //
1183 Size = Size - ReadSize;
1184 TargetAddress = TargetAddress + ReadSize;
1185 }
1186 }
1187 else
1188 {
1189 try
1190 {
1191 UINT64 ReadingTest = *((UINT64 *)TargetAddress);
1192 }
1193 catch (...)
1194 {
1195 //
1196 // Address is not valid
1197 //
1198 return FALSE;
1199 }
1200 }
1201 }
1202
1203 //
1204 // If we've reached here, the address was valid
1205 //
1206 return TRUE;
1207}
UCHAR BOOLEAN
Definition BasicTypes.h:39
#define TRUE
Definition BasicTypes.h:55
#define FALSE
Definition BasicTypes.h:54
unsigned __int64 UINT64
Definition BasicTypes.h:21
unsigned int UINT32
Definition BasicTypes.h:48
char CHAR
Definition BasicTypes.h:31
BOOLEAN CheckAddressCanonicality(UINT64 VAddr, PBOOLEAN IsKernelAddress)
Checks if the address is canonical based on x86 processor's virtual address width or not.
Definition common.cpp:944
BOOLEAN CheckAddressValidityUsingTsx(UINT64 Address)
This function checks whether the address is valid or not using Intel TSX.
Definition common.cpp:1000
BOOLEAN g_RtmSupport
check for RTM support
Definition globals.h:22
#define PAGE_SIZE
Size of each page (4096 bytes)
Definition common.h:69
#define PAGE_ALIGN(Va)
Aligning a page.
Definition common.h:75

◆ CheckAddressCanonicality()

BOOLEAN CheckAddressCanonicality ( UINT64 VAddr,
PBOOLEAN IsKernelAddress )

Checks if the address is canonical based on x86 processor's virtual address width or not.

Parameters
VAddrvirtual address to check
IsKernelAddressFilled to show whether the address is a kernel address or user-address

IsKernelAddress wouldn't check for page attributes, it just checks the address convention in Windows

Returns
BOOLEAN
945{
946 UINT64 Addr = (UINT64)VAddr;
947 UINT64 MaxVirtualAddrLowHalf, MinVirtualAddressHighHalf;
948
949 //
950 // Get processor's address width for VA
951 //
952 UINT32 AddrWidth = g_VirtualAddressWidth;
953
954 //
955 // get max address in lower-half canonical addr space
956 // e.g. if width is 48, then 0x00007FFF_FFFFFFFF
957 //
958 MaxVirtualAddrLowHalf = ((UINT64)1ull << (AddrWidth - 1)) - 1;
959
960 //
961 // get min address in higher-half canonical addr space
962 // e.g., if width is 48, then 0xFFFF8000_00000000
963 //
964 MinVirtualAddressHighHalf = ~MaxVirtualAddrLowHalf;
965
966 //
967 // Check to see if the address in a canonical address
968 //
969 if ((Addr > MaxVirtualAddrLowHalf) && (Addr < MinVirtualAddressHighHalf))
970 {
971 *IsKernelAddress = FALSE;
972 return FALSE;
973 }
974
975 //
976 // Set whether it's a kernel address or not
977 //
978 if (MinVirtualAddressHighHalf < Addr)
979 {
980 *IsKernelAddress = TRUE;
981 }
982 else
983 {
984 *IsKernelAddress = FALSE;
985 }
986
987 return TRUE;
988}
UINT32 g_VirtualAddressWidth
Virtual address width for x86 processors.
Definition globals.h:28

◆ CheckAddressValidityUsingTsx()

BOOLEAN CheckAddressValidityUsingTsx ( UINT64 Address)

This function checks whether the address is valid or not using Intel TSX.

Parameters
AddressAddress to check
UINT32ProcId
Returns
BOOLEAN Returns true if the address is valid; otherwise, false
1001{
1002 UINT32 Status = 0;
1003 BOOLEAN Result = FALSE;
1004 CHAR TempContent;
1005
1006 if ((Status = _xbegin()) == _XBEGIN_STARTED)
1007 {
1008 //
1009 // Try to read the memory
1010 //
1011 TempContent = *(CHAR *)Address;
1012 _xend();
1013
1014 //
1015 // No error, address is valid
1016 //
1017 Result = TRUE;
1018 }
1019 else
1020 {
1021 //
1022 // Address is not valid, it aborts the tsx rtm
1023 //
1024 Result = FALSE;
1025 }
1026
1027 return Result;
1028}
UINT64 Address
Definition HyperDbgScriptImports.h:67
#define _XBEGIN_STARTED
Intel TSX Constants.
Definition Common.h:213

◆ CheckCpuSupportRtm()

BOOLEAN CheckCpuSupportRtm ( )

Check whether the processor supports RTM or not.

Returns
BOOLEAN
904{
905 int Regs1[4];
906 int Regs2[4];
907 BOOLEAN Result;
908
909 //
910 // TSX is controlled via MSR_IA32_TSX_CTRL. However, support for this
911 // MSR is enumerated by ARCH_CAP_TSX_MSR bit in MSR_IA32_ARCH_CAPABILITIES.
912 //
913 // TSX control (aka MSR_IA32_TSX_CTRL) is only available after a
914 // microcode update on CPUs that have their MSR_IA32_ARCH_CAPABILITIES
915 // bit MDS_NO=1. CPUs with MDS_NO=0 are not planned to get
916 // MSR_IA32_TSX_CTRL support even after a microcode update. Thus,
917 // tsx= cmdline requests will do nothing on CPUs without
918 // MSR_IA32_TSX_CTRL support.
919 //
920
921 CommonCpuidInstruction(0, 0, Regs1);
922 CommonCpuidInstruction(7, 0, Regs2);
923
924 //
925 // Check RTM and MPX extensions in order to filter out TSX on Haswell CPUs
926 //
927 Result = Regs1[0] >= 0x7 && (Regs2[1] & 0x4800) == 0x4800;
928
929 return Result;
930}
VOID CommonCpuidInstruction(UINT32 Func, UINT32 SubFunc, int *CpuInfo)
Get cpuid results.
Definition common.cpp:874

◆ CommonCpuidInstruction()

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

Get cpuid results.

Parameters
UINT32Func
UINT32SubFunc
int* CpuInfo
Returns
VOID
875{
876 __cpuidex(CpuInfo, Func, SubFunc);
877}

◆ ConvertStringToUInt32()

BOOLEAN ConvertStringToUInt32 ( string TextToConvert,
PUINT32 Result )

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
348{
349 BOOLEAN IsDecimal = FALSE; // By default everything is hex
350
351 if (TextToConvert.rfind("0x", 0) == 0 || TextToConvert.rfind("0X", 0) == 0 ||
352 TextToConvert.rfind("\\x", 0) == 0 ||
353 TextToConvert.rfind("\\X", 0) == 0)
354 {
355 TextToConvert = TextToConvert.erase(0, 2);
356 }
357 else if (TextToConvert.rfind('x', 0) == 0 ||
358 TextToConvert.rfind('X', 0) == 0)
359 {
360 TextToConvert = TextToConvert.erase(0, 1);
361 }
362 else if (TextToConvert.rfind("0n", 0) == 0 || TextToConvert.rfind("0N", 0) == 0 ||
363 TextToConvert.rfind("\\n", 0) == 0 ||
364 TextToConvert.rfind("\\N", 0) == 0)
365 {
366 TextToConvert = TextToConvert.erase(0, 2);
367 IsDecimal = TRUE;
368 }
369 else if (TextToConvert.rfind('n', 0) == 0 ||
370 TextToConvert.rfind('N', 0) == 0)
371 {
372 TextToConvert = TextToConvert.erase(0, 1);
373 IsDecimal = TRUE;
374 }
375
376 TextToConvert.erase(remove(TextToConvert.begin(), TextToConvert.end(), '`'),
377 TextToConvert.end());
378
379 if (IsDecimal)
380 {
381 if (!IsDecimalNotation(TextToConvert))
382 {
383 return FALSE;
384 }
385 else
386 {
387 try
388 {
389 int i = std::stoi(TextToConvert);
390 *Result = i;
391 return TRUE;
392 }
393 catch (std::invalid_argument const &)
394 {
395 //
396 // Bad input: std::invalid_argument thrown
397 //
398 return FALSE;
399 }
400 catch (std::out_of_range const &)
401 {
402 //
403 // Integer overflow: std::out_of_range thrown
404 //
405 return FALSE;
406 }
407
408 return FALSE;
409 }
410 }
411 else
412 {
413 //
414 // It's not decimal
415 //
416 if (!IsHexNotation(TextToConvert))
417 {
418 return FALSE;
419 }
420 else
421 {
422 //
423 // It's hex number
424 //
425 UINT32 TempResult;
426 TempResult = stoi(TextToConvert, nullptr, 16);
427
428 //
429 // Apply the results
430 //
431 *Result = TempResult;
432
433 return TRUE;
434 }
435 }
436}
BOOLEAN IsHexNotation(const string &s)
check whether the string is hex or not
Definition common.cpp:162
BOOLEAN IsDecimalNotation(const string &s)
check whether the string is decimal or not
Definition common.cpp:189
char IsDecimal(char c)
Checks whether input char belongs to decimal digit-set or not.
Definition common.c:540

◆ ConvertStringToUInt64()

BOOLEAN ConvertStringToUInt64 ( string TextToConvert,
PUINT64 Result )

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
241{
242 BOOLEAN IsDecimal = FALSE; // By default everything is hex
243
244 if (TextToConvert.rfind("0x", 0) == 0 || TextToConvert.rfind("0X", 0) == 0 ||
245 TextToConvert.rfind("\\x", 0) == 0 ||
246 TextToConvert.rfind("\\X", 0) == 0)
247 {
248 TextToConvert = TextToConvert.erase(0, 2);
249 }
250 else if (TextToConvert.rfind('x', 0) == 0 ||
251 TextToConvert.rfind('X', 0) == 0)
252 {
253 TextToConvert = TextToConvert.erase(0, 1);
254 }
255 else if (TextToConvert.rfind("0n", 0) == 0 || TextToConvert.rfind("0N", 0) == 0 ||
256 TextToConvert.rfind("\\n", 0) == 0 ||
257 TextToConvert.rfind("\\N", 0) == 0)
258 {
259 TextToConvert = TextToConvert.erase(0, 2);
260 IsDecimal = TRUE;
261 }
262 else if (TextToConvert.rfind('n', 0) == 0 ||
263 TextToConvert.rfind('N', 0) == 0)
264 {
265 TextToConvert = TextToConvert.erase(0, 1);
266 IsDecimal = TRUE;
267 }
268
269 //
270 // Remove '`' (if any)
271 //
272 TextToConvert.erase(remove(TextToConvert.begin(), TextToConvert.end(), '`'),
273 TextToConvert.end());
274
275 if (IsDecimal)
276 {
277 if (!IsDecimalNotation(TextToConvert))
278 {
279 //
280 // Not decimal
281 //
282 return FALSE;
283 }
284 else
285 {
286 errno = 0;
287 char * unparsed = NULL;
288 const char * s = TextToConvert.c_str();
289 const unsigned long long int n = strtoull(s, &unparsed, 10);
290
291 if (errno || (!n && s == unparsed))
292 {
293 // fflush(stdout);
294 // perror(s);
295 return FALSE;
296 }
297
298 *Result = n;
299 return TRUE;
300 }
301 }
302 else
303 {
304 //
305 // It's not decimal
306 //
307 if (!IsHexNotation(TextToConvert))
308 {
309 //
310 // Not decimal and not hex!
311 //
312 return FALSE;
313 }
314 else
315 {
316 //
317 // It's a hex number
318 //
319 const char * Text = TextToConvert.c_str();
320 errno = 0;
321 unsigned long long result = strtoull(Text, NULL, 16);
322
323 *Result = result;
324
325 if (errno == EINVAL)
326 {
327 return FALSE;
328 }
329 else if (errno == ERANGE)
330 {
331 return TRUE;
332 }
333
334 return TRUE;
335 }
336 }
337}
result
Definition modelsim.py:117
NULL()
Definition test-case-generator.py:530

◆ 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
Input
ToSearch
Pos
Returns
size_t
859{
860 char * pc = new char[s.size() + 1];
861 std::strcpy(pc, s.c_str());
862 return pc;
863}

◆ 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
818{
819 // Convert complete given String to lower case
820 std::transform(Input.begin(), Input.end(), Input.begin(), ::tolower);
821 // Convert complete given Sub String to lower case
822 std::transform(ToSearch.begin(), ToSearch.end(), ToSearch.begin(), ::tolower);
823 // Find sub string in given string
824 return Input.find(ToSearch, Pos);
825}

◆ 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
837{
838 // Convert complete given String to lower case
839 std::transform(Input.begin(), Input.end(), Input.begin(), ::tolower);
840 // Convert complete given Sub String to lower case
841 std::transform(ToSearch.begin(), ToSearch.end(), ToSearch.begin(), ::tolower);
842 // Find sub string in given string
843 return Input.find(ToSearch, Pos);
844}

◆ GetConfigFilePath()

VOID GetConfigFilePath ( PWCHAR ConfigPath)

Get config path.

Parameters
ConfigPath
672{
673 WCHAR CurrentPath[MAX_PATH] = {0};
674
675 //
676 // Get path file of current exe
677 //
678 GetModuleFileNameW(NULL, CurrentPath, MAX_PATH);
679
680 //
681 // Remove exe file name
682 //
683 PathRemoveFileSpecW(CurrentPath);
684
685 //
686 // Combine current exe path with config file name
687 //
688 PathCombineW(ConfigPath, CurrentPath, CONFIG_FILE_NAME);
689}
wchar_t WCHAR
Definition BasicTypes.h:32
#define CONFIG_FILE_NAME
Config file name for HyperDbg.
Definition Definition.h:24

◆ Getx86VirtualAddressWidth()

UINT32 Getx86VirtualAddressWidth ( )

Get virtual address width for x86 processors.

Returns
UINT32
886{
887 int Regs[4];
888
890
891 //
892 // Extracting bit 15:8 from eax register
893 //
894 return ((Regs[0] >> 8) & 0x0ff);
895}
#define CPUID_ADDR_WIDTH
Cpuid to get virtual address width.
Definition Common.h:151

◆ 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
449{
450 if (fullString.length() >= ending.length())
451 {
452 return (0 == fullString.compare(fullString.length() - ending.length(),
453 ending.length(),
454 ending));
455 }
456 else
457 {
458 return FALSE;
459 }
460}

◆ HexToBytes()

vector< char > HexToBytes ( const string & hex)

converts hex to bytes

Parameters
hex
Returns
vector<char>
217{
218 vector<char> Bytes;
219
220 for (unsigned int i = 0; i < hex.length(); i += 2)
221 {
222 std::string byteString = hex.substr(i, 2);
223 char byte = (char)strtol(byteString.c_str(), NULL, 16);
224 Bytes.push_back(byte);
225 }
226
227 return Bytes;
228}

◆ IsDecimalNotation()

BOOLEAN IsDecimalNotation ( const string & s)

check whether the string is decimal or not

Parameters
s
Returns
BOOLEAN
190{
191 BOOLEAN IsAnyThing = FALSE;
192
193 for (auto & CptrChar : s)
194 {
195 IsAnyThing = TRUE;
196
197 if (!isdigit(CptrChar))
198 {
199 return FALSE;
200 }
201 }
202 if (IsAnyThing)
203 {
204 return TRUE;
205 }
206 return FALSE;
207}

◆ IsEmptyString()

BOOLEAN IsEmptyString ( char * Text)

Is empty character.

Parameters
Text
645{
646 size_t Len;
647
648 if (Text == NULL || Text[0] == '\0')
649 {
650 return TRUE;
651 }
652
653 Len = strlen(Text);
654 for (size_t i = 0; i < Len; i++)
655 {
656 if (Text[i] != ' ' && Text[i] != '\t' && Text[i] != '\n')
657 {
658 return FALSE;
659 }
660 }
661
662 return TRUE;
663}

◆ 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
620{
621 struct stat buffer;
622 return (stat(FileName, &buffer) == 0);
623}

◆ IsFileExistW()

BOOLEAN IsFileExistW ( const wchar_t * FileName)

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

Parameters
FileNamepath of file
Returns
BOOLEAN shows whether the file exist or not
633{
634 struct _stat64i32 buffer;
635 return (_wstat(FileName, &buffer) == 0);
636}

◆ IsHexNotation()

BOOLEAN IsHexNotation ( const string & s)

check whether the string is hex or not

Parameters
s
Returns
BOOLEAN
163{
164 BOOLEAN IsAnyThing = FALSE;
165
166 for (auto & CptrChar : s)
167 {
168 IsAnyThing = TRUE;
169
170 if (!isxdigit(CptrChar))
171 {
172 return FALSE;
173 }
174 }
175 if (IsAnyThing)
176 {
177 return TRUE;
178 }
179 return FALSE;
180}

◆ IsNumber()

BOOLEAN IsNumber ( const string & str)

check if given string is a numeric string or not

Parameters
str
Returns
BOOLEAN
146{
147 //
148 // std::find_first_not_of searches the string for the first character
149 // that does not match any of the characters specified in its arguments
150 //
151 return !str.empty() &&
152 (str.find_first_not_of("[0123456789]") == std::string::npos);
153}

◆ 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>
700{
701 WIN32_FIND_DATAA FindData;
702 HANDLE Find = INVALID_HANDLE_VALUE;
703 std::string FullPath = Directory + "\\" + Extension;
704 std::vector<std::string> DirList;
705
706 Find = FindFirstFileA(FullPath.c_str(), &FindData);
707
708 if (Find == INVALID_HANDLE_VALUE)
709 throw std::runtime_error("invalid handle value! please check your path...");
710
711 while (FindNextFileA(Find, &FindData) != 0)
712 {
713 DirList.push_back(Directory + "\\" + std::string(FindData.cFileName));
714 }
715
716 FindClose(Find);
717
718 return DirList;
719}

◆ Log2Ceil()

UINT32 Log2Ceil ( UINT32 n)

Function to compute log2Ceil.

Parameters
n
Returns
UINT32
1217{
1218 if (n == 0)
1219 return 0; // log2Ceil(0) is undefined, returning 0 for safety.
1220
1221 n--; // Decrease by 1 to check if it is a power of 2
1222 UINT32 log2Floor = 0;
1223 while (n >>= 1)
1224 {
1225 log2Floor++;
1226 }
1227 return log2Floor + 1;
1228}

◆ PrintBits()

VOID PrintBits ( const UINT32 Size,
const void * Ptr )

print bits and bytes for d* commands

Parameters
Size
Ptr
Returns
VOID
48{
49 unsigned char * Buf = (unsigned char *)Ptr;
50 unsigned char Byte;
51 int i, j;
52
53 for (i = Size - 1; i >= 0; i--)
54 {
55 for (j = 7; j >= 0; j--)
56 {
57 Byte = (Buf[i] >> j) & 1;
58 ShowMessages("%u", Byte);
59 }
60 ShowMessages(" ", Byte);
61 }
62}
VOID ShowMessages(const char *Fmt,...)
Show messages.
Definition libhyperdbg.cpp:96

◆ RemoveSpaces()

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

Remove all the spaces in a string.

Parameters
str
607{
608 str.erase(remove(str.begin(), str.end(), ' '), str.end());
609 return str;
610}

◆ Replace()

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

general replace all function

Parameters
str
from
to
Returns
VOID
74{
75 size_t start_pos = str.find(from);
76 if (start_pos == std::string::npos)
77 return FALSE;
78 str.replace(start_pos, from.size(), to);
79 return TRUE;
80}

◆ ReplaceAll()

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

general replace all function

Parameters
str
from
to
Returns
VOID
92{
93 size_t SartPos = 0;
94
95 if (from.empty())
96 return;
97
98 while ((SartPos = str.find(from, SartPos)) != std::string::npos)
99 {
100 str.replace(SartPos, from.length(), to);
101 //
102 // In case 'to' contains 'from', like replacing
103 // 'x' with 'yx'
104 //
105 SartPos += to.length();
106 }
107}

◆ SeparateTo64BitValue()

string SeparateTo64BitValue ( UINT64 Value)

add ` between 64 bit values and convert them to string

Parameters
Value
Returns
string
28{
29 ostringstream OstringStream;
30 string Temp;
31
32 OstringStream << setw(16) << setfill('0') << hex << Value;
33 Temp = OstringStream.str();
34
35 Temp.insert(8, 1, '`');
36 return Temp;
37}
RequestedActionOfThePacket Value(0x1) 00000000

◆ SetPrivilege()

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

SetPrivilege enables/disables process token privilege.

Parameters
Token
Privilege
EnablePrivilege
Returns
BOOL
526{
527 TOKEN_PRIVILEGES Tp;
528 LUID Luid;
529
530 if (!LookupPrivilegeValue(NULL, // lookup privilege on local system
531 Privilege, // privilege to lookup
532 &Luid)) // receives LUID of privilege
533 {
534 ShowMessages("err, in LookupPrivilegeValue (%x)\n", GetLastError());
535 return FALSE;
536 }
537
538 Tp.PrivilegeCount = 1;
539 Tp.Privileges[0].Luid = Luid;
540 if (EnablePrivilege)
541 Tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
542 else
543 Tp.Privileges[0].Attributes = 0;
544
545 //
546 // Enable the privilege or disable all privileges.
547 //
548 if (!AdjustTokenPrivileges(Token, FALSE, &Tp, sizeof(TOKEN_PRIVILEGES), (PTOKEN_PRIVILEGES)NULL, (PDWORD)NULL))
549 {
550 ShowMessages("err, in AdjustTokenPrivileges (%x)\n", GetLastError());
551 return FALSE;
552 }
553
554 if (GetLastError() == ERROR_NOT_ALL_ASSIGNED)
555 {
556 ShowMessages("err, the token does not have the specified privilege (ACCESS DENIED!)\n");
557 ShowMessages("make sure to run it with administrator privileges\n");
558 return FALSE;
559 }
560
561 return TRUE;
562}

◆ Split()

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

general split command

Parameters
starget string
csplitter (delimiter)
Returns
const vector<string>
118{
119 string buff {""};
120 vector<string> v;
121
122 for (auto n : s)
123 {
124 if (n != c)
125 buff += n;
126 else if (n == c && !buff.empty())
127 {
128 v.push_back(buff);
129 buff.clear();
130 }
131 }
132 if (!buff.empty())
133 v.push_back(buff);
134
135 return v;
136}

◆ SplitPathAndArgs()

VOID SplitPathAndArgs ( std::vector< std::string > & Qargs,
const std::string & Command )

Split path and arguments and handle strings between quotes.

Parameters
Qargs
Command
Returns
VOID
745{
746 int Len = (int)Command.length();
747 bool Qot = false, Sqot = false;
748 int ArgLen;
749
750 for (int i = 0; i < Len; i++)
751 {
752 int start = i;
753 if (Command[i] == '\"')
754 {
755 Qot = true;
756 }
757 else if (Command[i] == '\'')
758 Sqot = true;
759
760 if (Qot)
761 {
762 i++;
763 start++;
764 while (i < Len && Command[i] != '\"')
765 i++;
766 if (i < Len)
767 Qot = false;
768 ArgLen = i - start;
769 i++;
770 }
771 else if (Sqot)
772 {
773 i++;
774 while (i < Len && Command[i] != '\'')
775 i++;
776 if (i < Len)
777 Sqot = false;
778 ArgLen = i - start;
779 i++;
780 }
781 else
782 {
783 while (i < Len && Command[i] != ' ')
784 i++;
785 ArgLen = i - start;
786 }
787
788 string Temp = Command.substr(start, ArgLen);
789 if (!Temp.empty() && Temp != " ")
790 {
791 Qargs.push_back(Temp);
792 }
793 }
794
795 /*
796 for (int i = 0; i < Qargs.size(); i++)
797 {
798 std::cout << Qargs[i] << std::endl;
799 }
800
801 std::cout << Qargs.size();
802
803 if (Qot || Sqot)
804 std::cout << "One of the quotes is open\n";
805 */
806}

◆ StringToWString()

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

convert std::string to std::wstring

Parameters
ws
s
Returns
VOID
730{
731 std::wstring WsTmp(s.begin(), s.end());
732
733 ws = WsTmp;
734}

◆ Trim()

void Trim ( std::string & s)

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

Parameters
s
595{
596 ltrim(s);
597 rtrim(s);
598}

◆ ValidateIP()

BOOLEAN ValidateIP ( const string & ip)

Function to validate an IP address.

Parameters
ip
Returns
BOOLEAN
470{
471 //
472 // split the string into tokens
473 //
474 vector<string> list = Split(ip, '.');
475
476 //
477 // if token size is not equal to four
478 //
479 if (list.size() != 4)
480 return FALSE;
481
482 //
483 // validate each token
484 //
485 for (string str : list)
486 {
487 //
488 // verify that string is number or not and the numbers
489 // are in the valid range
490 //
491 if (!IsNumber(str) || stoi(str) > 255 || stoi(str) < 0)
492 return FALSE;
493 }
494
495 return TRUE;
496}
BOOLEAN IsNumber(const string &str)
check if given string is a numeric string or not
Definition common.cpp:145
const vector< string > Split(const string &s, const char &c)
general split command
Definition common.cpp:117

◆ VmxSupportDetection()

BOOLEAN VmxSupportDetection ( )

Detect whether the VMX is supported or not.

Returns
true if vmx is supported
false if vmx is not supported
506{
507 //
508 // Call assembly function
509 //
510 return AsmVmxSupportDetection();
511}
bool AsmVmxSupportDetection()

Variable Documentation

◆ g_RtmSupport

BOOLEAN g_RtmSupport
extern

check for RTM support

◆ g_VirtualAddressWidth

UINT32 g_VirtualAddressWidth
extern

Virtual address width for x86 processors.