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 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_BUILD_SIGNATURE_DOESNT_MATCH
 
#define ASSERT_MESSAGE_CANNOT_SPECIFY_PID
 
#define AssertReturnStmt(expr, stmt, rc)
 
#define AssertShowMessageReturnStmt(expr, message, rc)
 
#define PAGE_SIZE   0x1000
 Size of each page (4096 bytes)
 
#define PAGE_ALIGN(Va)   ((PVOID)((ULONG_PTR)(Va) & ~(PAGE_SIZE - 1)))
 Aligning a page.
 
#define CPUID_ADDR_WIDTH   0x80000008
 Cpuid to get virtual address width.
 

Functions

bool 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, unsigned 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)
 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
 
UINT32 Log2Ceil (UINT32 n)
 Function to compute log2Ceil.
 
vector< string > SplitIp (const string &str, char delim)
 
BOOLEAN IsHexNotation (const string &s)
 check whether the string is hex 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.
 
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)
 
VOID GetConfigFilePath (PWCHAR ConfigPath)
 Get config path.
 
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*.
 
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"
27#define ASSERT_MESSAGE_BUILD_SIGNATURE_DOESNT_MATCH "the handshaking process was successful; however, there is a mismatch between " \
28 "the version/build of the debuggee and the debugger. please use the same " \
29 "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"
31#define ASSERT_MESSAGE_CANNOT_SPECIFY_PID "err, since HyperDbg won't context-switch to keep the system in a halted state, " \
32 "you cannot specify 'pid' for this command in the debugger mode. You can switch to the target process " \
33 "memory layout using the '.process' or the '.thread' command. After that, you can use " \
34 "this command without specifying the process ID. Alternatively, you can modify the current " \
35 "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"

◆ 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)
37#define AssertReturnStmt(expr, stmt, rc) \
38 do \
39 { \
40 if (expr) \
41 { \
42 /* likely */ \
43 } \
44 else \
45 { \
46 stmt; \
47 rc; \
48 } \
49 } while (0)

◆ AssertShowMessageReturnStmt

#define AssertShowMessageReturnStmt ( expr,
message,
rc )
Value:
do \
{ \
if (expr) \
{ \
/* likely */ \
} \
else \
{ \
ShowMessages(message); \
rc; \
} \
} while (0)
51#define AssertShowMessageReturnStmt(expr, message, rc) \
52 do \
53 { \
54 if (expr) \
55 { \
56 /* likely */ \
57 } \
58 else \
59 { \
60 ShowMessages(message); \
61 rc; \
62 } \
63 } while (0)

◆ CPUID_ADDR_WIDTH

#define CPUID_ADDR_WIDTH   0x80000008

Cpuid to get virtual address width.

◆ PAGE_ALIGN

#define PAGE_ALIGN ( Va)    ((PVOID)((ULONG_PTR)(Va) & ~(PAGE_SIZE - 1)))

Aligning a page.

◆ PAGE_SIZE

#define PAGE_SIZE   0x1000

Size of each page (4096 bytes)

Function Documentation

◆ AsmVmxSupportDetection()

bool AsmVmxSupportDetection ( )
extern

◆ CheckAccessValidityAndSafety()

BOOLEAN CheckAccessValidityAndSafety ( UINT64 TargetAddress,
UINT32 Size )

Check the safety to access the memory.

Parameters
TargetAddress
Size
Returns
BOOLEAN
157{
158 CR3_TYPE GuestCr3;
159 UINT64 OriginalCr3;
160 BOOLEAN IsKernelAddress;
161 BOOLEAN Result = FALSE;
162
163 //
164 // First, we check if the address is canonical based
165 // on Intel processor's virtual address width
166 //
167 if (!CheckAddressCanonicality(TargetAddress, &IsKernelAddress))
168 {
169 //
170 // No need for further check, address is invalid
171 //
172 Result = FALSE;
173 goto Return;
174 }
175
176 //
177 // Find the current process cr3
178 //
180
181 //
182 // Move to new cr3
183 //
184 OriginalCr3 = __readcr3();
185 __writecr3(GuestCr3.Flags);
186
187 //
188 // We'll only check address with TSX if the address is a kernel-mode
189 // address because an exception is thrown if we access user-mode code
190 // from vmx-root mode, thus, TSX will fail the transaction and the
191 // result is not true, so we check each pages' page-table for user-mode
192 // codes in both user-mode and kernel-mode
193 //
194 // if (g_RtmSupport && IsKernelAddress)
195 // {
196 // //
197 // // The guest supports Intel TSX
198 // //
199 // UINT64 AlignedPage = (UINT64)PAGE_ALIGN(TargetAddress);
200 // UINT64 PageCount = ((TargetAddress - AlignedPage) + Size) / PAGE_SIZE;
201 //
202 // for (size_t i = 0; i <= PageCount; i++)
203 // {
204 // UINT64 CheckAddr = AlignedPage + (PAGE_SIZE * i);
205 // if (!CheckAddressValidityUsingTsx(CheckAddr))
206 // {
207 // //
208 // // Address is not valid
209 // //
210 // Result = FALSE;
211 //
212 // goto RestoreCr3;
213 // }
214 // }
215 // }
216
217 //
218 // We've realized that using TSX for address checking is not faster
219 // than the legacy memory checking (traversing the page-tables),
220 // based on our resultsm it's ~50 TSC clock cycles for a valid address
221 // and ~180 TSC clock cycles for an invalid address slower to use TSX
222 // for memory checking, that's why it is deprecated now
223 //
224
225 //
226 // Check if memory is safe and present
227 //
228 UINT64 AddressToCheck = (CHAR *)TargetAddress + Size - ((CHAR *)PAGE_ALIGN(TargetAddress));
229
230 if (AddressToCheck > PAGE_SIZE)
231 {
232 //
233 // Address should be accessed in more than one page
234 //
235 UINT64 ReadSize = AddressToCheck;
236
237 while (Size != 0)
238 {
239 ReadSize = (UINT64)PAGE_ALIGN(TargetAddress + PAGE_SIZE) - TargetAddress;
240
241 if (ReadSize == PAGE_SIZE && Size < PAGE_SIZE)
242 {
243 ReadSize = Size;
244 }
245
246 if (!MemoryMapperCheckIfPageIsPresentByCr3((PVOID)TargetAddress, GuestCr3))
247 {
248 //
249 // Address is not valid
250 //
251 Result = FALSE;
252
253 goto RestoreCr3;
254 }
255
256 /*
257 LogInfo("Addr From : %llx to Addr To : %llx | ReadSize : %llx\n",
258 TargetAddress,
259 TargetAddress + ReadSize,
260 ReadSize);
261 */
262
263 //
264 // Apply the changes to the next addresses (if any)
265 //
266 Size = (UINT32)(Size - ReadSize);
267 TargetAddress = TargetAddress + ReadSize;
268 }
269 }
270 else
271 {
272 if (!MemoryMapperCheckIfPageIsPresentByCr3((PVOID)TargetAddress, GuestCr3))
273 {
274 //
275 // Address is not valid
276 //
277 Result = FALSE;
278
279 goto RestoreCr3;
280 }
281 }
282
283 //
284 // If we've reached here, the address was valid
285 //
286 Result = TRUE;
287
288RestoreCr3:
289
290 //
291 // Move back to original cr3
292 //
293 __writecr3(OriginalCr3);
294
295Return:
296 return Result;
297}
BOOLEAN CheckAddressCanonicality(UINT64 VAddr, PBOOLEAN IsKernelAddress)
Checks if the address is canonical based on x86 processor's virtual address width or not.
Definition AddressCheck.c:66
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
CR3_TYPE LayoutGetCurrentProcessCr3()
Get cr3 of the target running process.
Definition Layout.c:55
_Use_decl_annotations_ BOOLEAN MemoryMapperCheckIfPageIsPresentByCr3(PVOID Va, CR3_TYPE TargetCr3)
This function checks if the page is mapped or not.
Definition MemoryMapper.c:418
#define PAGE_SIZE
Size of each page (4096 bytes)
Definition common.h:69
#define PAGE_ALIGN(Va)
Aligning a page.
Definition common.h:75
CR3 Structure.
Definition BasicTypes.h:130
UINT64 Flags
Definition BasicTypes.h:133

◆ 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
86{
87 __cpuidex(CpuInfo, Func, SubFunc);
88}

◆ 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}

◆ 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}

◆ 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}

◆ SpinlockLock()

void SpinlockLock ( volatile LONG * Lock)

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

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

◆ SpinlockLockWithCustomWait()

void SpinlockLockWithCustomWait ( volatile LONG * Lock,
unsigned MaximumWait )

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

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

◆ SpinlockUnlock()

void SpinlockUnlock ( volatile LONG * Lock)

Release the lock.

Parameters
LONGLock variable
159{
160 *Lock = 0;
161}

◆ 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}

◆ SplitIp()

vector< string > SplitIp ( const string & str,
char delim )

◆ 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()