language
stringlengths 0
24
| filename
stringlengths 9
214
| code
stringlengths 99
9.93M
|
---|---|---|
Assembly Language | x64dbg-development/src/dbg/test/pferrie/x32/pferrie.asm | global _start
section .data
@real:
mov byte [l1],0b0h
l1: mov al,1
ret
section .text
_start:
jmp @real |
C/C++ | x64dbg-development/src/dbg/TitanEngine/TitanEngine.h | #ifndef TITANENGINE
#define TITANENGINE
#define TITCALL
#if _MSC_VER > 1000
#pragma once
#endif
#include <windows.h>
#include <stdint.h>
#pragma pack(push, 1)
// Global.Constant.Structure.Declaration:
// Engine.External:
#define UE_STRUCT_PE32STRUCT 1
#define UE_STRUCT_PE64STRUCT 2
#define UE_STRUCT_PESTRUCT 3
#define UE_STRUCT_IMPORTENUMDATA 4
#define UE_STRUCT_THREAD_ITEM_DATA 5
#define UE_STRUCT_LIBRARY_ITEM_DATA 6
#define UE_STRUCT_LIBRARY_ITEM_DATAW 7
#define UE_STRUCT_PROCESS_ITEM_DATA 8
#define UE_STRUCT_HANDLERARRAY 9
#define UE_STRUCT_PLUGININFORMATION 10
#define UE_STRUCT_HOOK_ENTRY 11
#define UE_STRUCT_FILE_STATUS_INFO 12
#define UE_STRUCT_FILE_FIX_INFO 13
#define UE_STRUCT_X87FPUREGISTER 14
#define UE_STRUCT_X87FPU 15
#define UE_STRUCT_TITAN_ENGINE_CONTEXT 16
#define UE_ACCESS_READ 0
#define UE_ACCESS_WRITE 1
#define UE_ACCESS_ALL 2
#define UE_HIDE_PEBONLY 0
#define UE_HIDE_BASIC 1
#define UE_PLUGIN_CALL_REASON_PREDEBUG 1
#define UE_PLUGIN_CALL_REASON_EXCEPTION 2
#define UE_PLUGIN_CALL_REASON_POSTDEBUG 3
#define UE_PLUGIN_CALL_REASON_UNHANDLEDEXCEPTION 4
#define TEE_HOOK_NRM_JUMP 1
#define TEE_HOOK_NRM_CALL 3
#define TEE_HOOK_IAT 5
#define UE_ENGINE_ALOW_MODULE_LOADING 1
#define UE_ENGINE_AUTOFIX_FORWARDERS 2
#define UE_ENGINE_PASS_ALL_EXCEPTIONS 3
#define UE_ENGINE_NO_CONSOLE_WINDOW 4
#define UE_ENGINE_BACKUP_FOR_CRITICAL_FUNCTIONS 5
#define UE_ENGINE_CALL_PLUGIN_CALLBACK 6
#define UE_ENGINE_RESET_CUSTOM_HANDLER 7
#define UE_ENGINE_CALL_PLUGIN_DEBUG_CALLBACK 8
#define UE_ENGINE_SET_DEBUG_PRIVILEGE 9
#define UE_ENGINE_SAFE_ATTACH 10
#define UE_ENGINE_MEMBP_ALT 11
#define UE_ENGINE_DISABLE_ASLR 12
#define UE_ENGINE_SAFE_STEP 13
#define UE_OPTION_REMOVEALL 1
#define UE_OPTION_DISABLEALL 2
#define UE_OPTION_REMOVEALLDISABLED 3
#define UE_OPTION_REMOVEALLENABLED 4
#define UE_STATIC_DECRYPTOR_XOR 1
#define UE_STATIC_DECRYPTOR_SUB 2
#define UE_STATIC_DECRYPTOR_ADD 3
#define UE_STATIC_DECRYPTOR_FOREWARD 1
#define UE_STATIC_DECRYPTOR_BACKWARD 2
#define UE_STATIC_KEY_SIZE_1 1
#define UE_STATIC_KEY_SIZE_2 2
#define UE_STATIC_KEY_SIZE_4 4
#define UE_STATIC_KEY_SIZE_8 8
#define UE_STATIC_APLIB 1
#define UE_STATIC_APLIB_DEPACK 2
#define UE_STATIC_LZMA 3
#define UE_STATIC_HASH_MD5 1
#define UE_STATIC_HASH_SHA1 2
#define UE_STATIC_HASH_CRC32 3
#define UE_RESOURCE_LANGUAGE_ANY -1
#define UE_PE_OFFSET 0
#define UE_IMAGEBASE 1
#define UE_OEP 2
#define UE_SIZEOFIMAGE 3
#define UE_SIZEOFHEADERS 4
#define UE_SIZEOFOPTIONALHEADER 5
#define UE_SECTIONALIGNMENT 6
#define UE_IMPORTTABLEADDRESS 7
#define UE_IMPORTTABLESIZE 8
#define UE_RESOURCETABLEADDRESS 9
#define UE_RESOURCETABLESIZE 10
#define UE_EXPORTTABLEADDRESS 11
#define UE_EXPORTTABLESIZE 12
#define UE_TLSTABLEADDRESS 13
#define UE_TLSTABLESIZE 14
#define UE_RELOCATIONTABLEADDRESS 15
#define UE_RELOCATIONTABLESIZE 16
#define UE_TIMEDATESTAMP 17
#define UE_SECTIONNUMBER 18
#define UE_CHECKSUM 19
#define UE_SUBSYSTEM 20
#define UE_CHARACTERISTICS 21
#define UE_NUMBEROFRVAANDSIZES 22
#define UE_BASEOFCODE 23
#define UE_BASEOFDATA 24
#define UE_DLLCHARACTERISTICS 25
//leaving some enum space here for future additions
#define UE_SECTIONNAME 40
#define UE_SECTIONVIRTUALOFFSET 41
#define UE_SECTIONVIRTUALSIZE 42
#define UE_SECTIONRAWOFFSET 43
#define UE_SECTIONRAWSIZE 44
#define UE_SECTIONFLAGS 45
#define UE_VANOTFOUND = -2;
#define UE_CH_BREAKPOINT 1
#define UE_CH_SINGLESTEP 2
#define UE_CH_ACCESSVIOLATION 3
#define UE_CH_ILLEGALINSTRUCTION 4
#define UE_CH_NONCONTINUABLEEXCEPTION 5
#define UE_CH_ARRAYBOUNDSEXCEPTION 6
#define UE_CH_FLOATDENORMALOPERAND 7
#define UE_CH_FLOATDEVIDEBYZERO 8
#define UE_CH_INTEGERDEVIDEBYZERO 9
#define UE_CH_INTEGEROVERFLOW 10
#define UE_CH_PRIVILEGEDINSTRUCTION 11
#define UE_CH_PAGEGUARD 12
#define UE_CH_EVERYTHINGELSE 13
#define UE_CH_CREATETHREAD 14
#define UE_CH_EXITTHREAD 15
#define UE_CH_CREATEPROCESS 16
#define UE_CH_EXITPROCESS 17
#define UE_CH_LOADDLL 18
#define UE_CH_UNLOADDLL 19
#define UE_CH_OUTPUTDEBUGSTRING 20
#define UE_CH_AFTEREXCEPTIONPROCESSING 21
#define UE_CH_SYSTEMBREAKPOINT 23
#define UE_CH_UNHANDLEDEXCEPTION 24
#define UE_CH_RIPEVENT 25
#define UE_CH_DEBUGEVENT 26
#define UE_OPTION_HANDLER_RETURN_HANDLECOUNT 1
#define UE_OPTION_HANDLER_RETURN_ACCESS 2
#define UE_OPTION_HANDLER_RETURN_FLAGS 3
#define UE_OPTION_HANDLER_RETURN_TYPENAME 4
#define UE_BREAKPOINT_INT3 1
#define UE_BREAKPOINT_LONG_INT3 2
#define UE_BREAKPOINT_UD2 3
#define UE_BPXREMOVED 0
#define UE_BPXACTIVE 1
#define UE_BPXINACTIVE 2
#define UE_BREAKPOINT 0
#define UE_SINGLESHOOT 1
#define UE_HARDWARE 2
#define UE_MEMORY 3
#define UE_MEMORY_READ 4
#define UE_MEMORY_WRITE 5
#define UE_MEMORY_EXECUTE 6
#define UE_BREAKPOINT_TYPE_INT3 0x10000000
#define UE_BREAKPOINT_TYPE_LONG_INT3 0x20000000
#define UE_BREAKPOINT_TYPE_UD2 0x30000000
#define UE_HARDWARE_EXECUTE 4
#define UE_HARDWARE_WRITE 5
#define UE_HARDWARE_READWRITE 6
#define UE_HARDWARE_SIZE_1 7
#define UE_HARDWARE_SIZE_2 8
#define UE_HARDWARE_SIZE_4 9
#define UE_HARDWARE_SIZE_8 10
#define UE_ON_LIB_LOAD 1
#define UE_ON_LIB_UNLOAD 2
#define UE_ON_LIB_ALL 3
#define UE_APISTART 0
#define UE_APIEND 1
#define UE_PLATFORM_x86 1
#define UE_PLATFORM_x64 2
#define UE_PLATFORM_ALL 3
#define UE_FUNCTION_STDCALL 1
#define UE_FUNCTION_CCALL 2
#define UE_FUNCTION_FASTCALL 3
#define UE_FUNCTION_STDCALL_RET 4
#define UE_FUNCTION_CCALL_RET 5
#define UE_FUNCTION_FASTCALL_RET 6
#define UE_FUNCTION_STDCALL_CALL 7
#define UE_FUNCTION_CCALL_CALL 8
#define UE_FUNCTION_FASTCALL_CALL 9
#define UE_PARAMETER_BYTE 0
#define UE_PARAMETER_WORD 1
#define UE_PARAMETER_DWORD 2
#define UE_PARAMETER_QWORD 3
#define UE_PARAMETER_PTR_BYTE 4
#define UE_PARAMETER_PTR_WORD 5
#define UE_PARAMETER_PTR_DWORD 6
#define UE_PARAMETER_PTR_QWORD 7
#define UE_PARAMETER_STRING 8
#define UE_PARAMETER_UNICODE 9
#define UE_EAX 1
#define UE_EBX 2
#define UE_ECX 3
#define UE_EDX 4
#define UE_EDI 5
#define UE_ESI 6
#define UE_EBP 7
#define UE_ESP 8
#define UE_EIP 9
#define UE_EFLAGS 10
#define UE_DR0 11
#define UE_DR1 12
#define UE_DR2 13
#define UE_DR3 14
#define UE_DR6 15
#define UE_DR7 16
#define UE_RAX 17
#define UE_RBX 18
#define UE_RCX 19
#define UE_RDX 20
#define UE_RDI 21
#define UE_RSI 22
#define UE_RBP 23
#define UE_RSP 24
#define UE_RIP 25
#define UE_RFLAGS 26
#define UE_R8 27
#define UE_R9 28
#define UE_R10 29
#define UE_R11 30
#define UE_R12 31
#define UE_R13 32
#define UE_R14 33
#define UE_R15 34
#define UE_CIP 35
#define UE_CSP 36
#ifdef _WIN64
#define UE_CFLAGS UE_RFLAGS
#else
#define UE_CFLAGS UE_EFLAGS
#endif
#define UE_SEG_GS 37
#define UE_SEG_FS 38
#define UE_SEG_ES 39
#define UE_SEG_DS 40
#define UE_SEG_CS 41
#define UE_SEG_SS 42
#define UE_x87_r0 43
#define UE_x87_r1 44
#define UE_x87_r2 45
#define UE_x87_r3 46
#define UE_x87_r4 47
#define UE_x87_r5 48
#define UE_x87_r6 49
#define UE_x87_r7 50
#define UE_X87_STATUSWORD 51
#define UE_X87_CONTROLWORD 52
#define UE_X87_TAGWORD 53
#define UE_MXCSR 54
#define UE_MMX0 55
#define UE_MMX1 56
#define UE_MMX2 57
#define UE_MMX3 58
#define UE_MMX4 59
#define UE_MMX5 60
#define UE_MMX6 61
#define UE_MMX7 62
#define UE_XMM0 63
#define UE_XMM1 64
#define UE_XMM2 65
#define UE_XMM3 66
#define UE_XMM4 67
#define UE_XMM5 68
#define UE_XMM6 69
#define UE_XMM7 70
#define UE_XMM8 71
#define UE_XMM9 72
#define UE_XMM10 73
#define UE_XMM11 74
#define UE_XMM12 75
#define UE_XMM13 76
#define UE_XMM14 77
#define UE_XMM15 78
#define UE_x87_ST0 79
#define UE_x87_ST1 80
#define UE_x87_ST2 81
#define UE_x87_ST3 82
#define UE_x87_ST4 83
#define UE_x87_ST5 84
#define UE_x87_ST6 85
#define UE_x87_ST7 86
#define UE_YMM0 87
#define UE_YMM1 88
#define UE_YMM2 89
#define UE_YMM3 90
#define UE_YMM4 91
#define UE_YMM5 92
#define UE_YMM6 93
#define UE_YMM7 94
#define UE_YMM8 95
#define UE_YMM9 96
#define UE_YMM10 97
#define UE_YMM11 98
#define UE_YMM12 99
#define UE_YMM13 100
#define UE_YMM14 101
#define UE_YMM15 102
#ifndef CONTEXT_EXTENDED_REGISTERS
#define CONTEXT_EXTENDED_REGISTERS 0
#endif
typedef void(*TITANCALLBACKARG)(const void*);
typedef void(*TITANCALLBACK)();
typedef TITANCALLBACK TITANCBCH;
typedef TITANCALLBACK TITANCBSTEP;
typedef TITANCALLBACK TITANCBSOFTBP;
typedef TITANCALLBACKARG TITANCBHWBP;
typedef TITANCALLBACKARG TITANCBMEMBP;
typedef struct
{
DWORD PE32Offset;
DWORD ImageBase;
DWORD OriginalEntryPoint;
DWORD BaseOfCode;
DWORD BaseOfData;
DWORD NtSizeOfImage;
DWORD NtSizeOfHeaders;
WORD SizeOfOptionalHeaders;
DWORD FileAlignment;
DWORD SectionAligment;
DWORD ImportTableAddress;
DWORD ImportTableSize;
DWORD ResourceTableAddress;
DWORD ResourceTableSize;
DWORD ExportTableAddress;
DWORD ExportTableSize;
DWORD TLSTableAddress;
DWORD TLSTableSize;
DWORD RelocationTableAddress;
DWORD RelocationTableSize;
DWORD TimeDateStamp;
WORD SectionNumber;
DWORD CheckSum;
WORD SubSystem;
WORD Characteristics;
DWORD NumberOfRvaAndSizes;
} PE32Struct, *PPE32Struct;
typedef struct
{
DWORD PE64Offset;
DWORD64 ImageBase;
DWORD OriginalEntryPoint;
DWORD BaseOfCode;
DWORD BaseOfData;
DWORD NtSizeOfImage;
DWORD NtSizeOfHeaders;
WORD SizeOfOptionalHeaders;
DWORD FileAlignment;
DWORD SectionAligment;
DWORD ImportTableAddress;
DWORD ImportTableSize;
DWORD ResourceTableAddress;
DWORD ResourceTableSize;
DWORD ExportTableAddress;
DWORD ExportTableSize;
DWORD TLSTableAddress;
DWORD TLSTableSize;
DWORD RelocationTableAddress;
DWORD RelocationTableSize;
DWORD TimeDateStamp;
WORD SectionNumber;
DWORD CheckSum;
WORD SubSystem;
WORD Characteristics;
DWORD NumberOfRvaAndSizes;
} PE64Struct, *PPE64Struct;
#if defined(_WIN64)
typedef PE64Struct PEStruct;
#else
typedef PE32Struct PEStruct;
#endif
typedef struct
{
bool NewDll;
int NumberOfImports;
ULONG_PTR ImageBase;
ULONG_PTR BaseImportThunk;
ULONG_PTR ImportThunk;
char* APIName;
char* DLLName;
} ImportEnumData, *PImportEnumData;
typedef struct
{
HANDLE hThread;
DWORD dwThreadId;
void* ThreadStartAddress;
void* ThreadLocalBase;
void* TebAddress;
ULONG WaitTime;
LONG Priority;
LONG BasePriority;
ULONG ContextSwitches;
ULONG ThreadState;
ULONG WaitReason;
} THREAD_ITEM_DATA, *PTHREAD_ITEM_DATA;
typedef struct
{
HANDLE hFile;
void* BaseOfDll;
HANDLE hFileMapping;
void* hFileMappingView;
char szLibraryPath[MAX_PATH];
char szLibraryName[MAX_PATH];
} LIBRARY_ITEM_DATA, *PLIBRARY_ITEM_DATA;
typedef struct
{
HANDLE hFile;
void* BaseOfDll;
HANDLE hFileMapping;
void* hFileMappingView;
wchar_t szLibraryPath[MAX_PATH];
wchar_t szLibraryName[MAX_PATH];
} LIBRARY_ITEM_DATAW, *PLIBRARY_ITEM_DATAW;
typedef struct
{
HANDLE hProcess;
DWORD dwProcessId;
HANDLE hThread;
DWORD dwThreadId;
HANDLE hFile;
void* BaseOfImage;
void* ThreadStartAddress;
void* ThreadLocalBase;
} PROCESS_ITEM_DATA, *PPROCESS_ITEM_DATA;
typedef struct
{
ULONG ProcessId;
HANDLE hHandle;
} HandlerArray, *PHandlerArray;
typedef struct
{
char PluginName[64];
DWORD PluginMajorVersion;
DWORD PluginMinorVersion;
HMODULE PluginBaseAddress;
void* TitanDebuggingCallBack;
void* TitanRegisterPlugin;
void* TitanReleasePlugin;
void* TitanResetPlugin;
bool PluginDisabled;
} PluginInformation, *PPluginInformation;
#define TEE_MAXIMUM_HOOK_SIZE 14
#define TEE_MAXIMUM_HOOK_RELOCS 7
#if defined(_WIN64)
#define TEE_MAXIMUM_HOOK_INSERT_SIZE 14
#else
#define TEE_MAXIMUM_HOOK_INSERT_SIZE 5
#endif
typedef struct HOOK_ENTRY
{
bool IATHook;
BYTE HookType;
DWORD HookSize;
void* HookAddress;
void* RedirectionAddress;
BYTE HookBytes[TEE_MAXIMUM_HOOK_SIZE];
BYTE OriginalBytes[TEE_MAXIMUM_HOOK_SIZE];
void* IATHookModuleBase;
DWORD IATHookNameHash;
bool HookIsEnabled;
bool HookIsRemote;
void* PatchedEntry;
DWORD RelocationInfo[TEE_MAXIMUM_HOOK_RELOCS];
int RelocationCount;
} HOOK_ENTRY, *PHOOK_ENTRY;
#define UE_DEPTH_SURFACE 0
#define UE_DEPTH_DEEP 1
#define UE_UNPACKER_CONDITION_SEARCH_FROM_EP 1
#define UE_UNPACKER_CONDITION_LOADLIBRARY 1
#define UE_UNPACKER_CONDITION_GETPROCADDRESS 2
#define UE_UNPACKER_CONDITION_ENTRYPOINTBREAK 3
#define UE_UNPACKER_CONDITION_RELOCSNAPSHOT1 4
#define UE_UNPACKER_CONDITION_RELOCSNAPSHOT2 5
#define UE_FIELD_OK 0
#define UE_FIELD_BROKEN_NON_FIXABLE 1
#define UE_FIELD_BROKEN_NON_CRITICAL 2
#define UE_FIELD_BROKEN_FIXABLE_FOR_STATIC_USE 3
#define UE_FIELD_BROKEN_BUT_CAN_BE_EMULATED 4
#define UE_FIELD_FIXABLE_NON_CRITICAL 5
#define UE_FIELD_FIXABLE_CRITICAL 6
#define UE_FIELD_NOT_PRESET 7
#define UE_FIELD_NOT_PRESET_WARNING 8
#define UE_RESULT_FILE_OK 10
#define UE_RESULT_FILE_INVALID_BUT_FIXABLE 11
#define UE_RESULT_FILE_INVALID_AND_NON_FIXABLE 12
#define UE_RESULT_FILE_INVALID_FORMAT 13
typedef struct
{
BYTE OveralEvaluation;
bool EvaluationTerminatedByException;
bool FileIs64Bit;
bool FileIsDLL;
bool FileIsConsole;
bool MissingDependencies;
bool MissingDeclaredAPIs;
BYTE SignatureMZ;
BYTE SignaturePE;
BYTE EntryPoint;
BYTE ImageBase;
BYTE SizeOfImage;
BYTE FileAlignment;
BYTE SectionAlignment;
BYTE ExportTable;
BYTE RelocationTable;
BYTE ImportTable;
BYTE ImportTableSection;
BYTE ImportTableData;
BYTE IATTable;
BYTE TLSTable;
BYTE LoadConfigTable;
BYTE BoundImportTable;
BYTE COMHeaderTable;
BYTE ResourceTable;
BYTE ResourceData;
BYTE SectionTable;
} FILE_STATUS_INFO, *PFILE_STATUS_INFO;
typedef struct
{
BYTE OveralEvaluation;
bool FixingTerminatedByException;
bool FileFixPerformed;
bool StrippedRelocation;
bool DontFixRelocations;
DWORD OriginalRelocationTableAddress;
DWORD OriginalRelocationTableSize;
bool StrippedExports;
bool DontFixExports;
DWORD OriginalExportTableAddress;
DWORD OriginalExportTableSize;
bool StrippedResources;
bool DontFixResources;
DWORD OriginalResourceTableAddress;
DWORD OriginalResourceTableSize;
bool StrippedTLS;
bool DontFixTLS;
DWORD OriginalTLSTableAddress;
DWORD OriginalTLSTableSize;
bool StrippedLoadConfig;
bool DontFixLoadConfig;
DWORD OriginalLoadConfigTableAddress;
DWORD OriginalLoadConfigTableSize;
bool StrippedBoundImports;
bool DontFixBoundImports;
DWORD OriginalBoundImportTableAddress;
DWORD OriginalBoundImportTableSize;
bool StrippedIAT;
bool DontFixIAT;
DWORD OriginalImportAddressTableAddress;
DWORD OriginalImportAddressTableSize;
bool StrippedCOM;
bool DontFixCOM;
DWORD OriginalCOMTableAddress;
DWORD OriginalCOMTableSize;
} FILE_FIX_INFO, *PFILE_FIX_INFO;
typedef struct DECLSPEC_ALIGN(16) _XmmRegister_t
{
ULONGLONG Low;
LONGLONG High;
} XmmRegister_t;
typedef struct
{
XmmRegister_t Low; //XMM/SSE part
XmmRegister_t High; //AVX part
} YmmRegister_t;
typedef struct
{
BYTE data[10];
int st_value;
int tag;
} x87FPURegister_t;
typedef struct
{
WORD ControlWord;
WORD StatusWord;
WORD TagWord;
DWORD ErrorOffset;
DWORD ErrorSelector;
DWORD DataOffset;
DWORD DataSelector;
DWORD Cr0NpxState;
} x87FPU_t;
typedef struct
{
ULONG_PTR cax;
ULONG_PTR ccx;
ULONG_PTR cdx;
ULONG_PTR cbx;
ULONG_PTR csp;
ULONG_PTR cbp;
ULONG_PTR csi;
ULONG_PTR cdi;
#ifdef _WIN64
ULONG_PTR r8;
ULONG_PTR r9;
ULONG_PTR r10;
ULONG_PTR r11;
ULONG_PTR r12;
ULONG_PTR r13;
ULONG_PTR r14;
ULONG_PTR r15;
#endif //_WIN64
ULONG_PTR cip;
ULONG_PTR eflags;
unsigned short gs;
unsigned short fs;
unsigned short es;
unsigned short ds;
unsigned short cs;
unsigned short ss;
ULONG_PTR dr0;
ULONG_PTR dr1;
ULONG_PTR dr2;
ULONG_PTR dr3;
ULONG_PTR dr6;
ULONG_PTR dr7;
BYTE RegisterArea[80];
x87FPU_t x87fpu;
DWORD MxCsr;
#ifdef _WIN64
XmmRegister_t XmmRegisters[16];
YmmRegister_t YmmRegisters[16];
#else // x86
XmmRegister_t XmmRegisters[8];
YmmRegister_t YmmRegisters[8];
#endif
} TITAN_ENGINE_CONTEXT_t;
#ifdef __cplusplus
extern "C"
{
#endif
// Global.Function.Declaration:
// TitanEngine.Dumper.functions:
__declspec(dllexport) bool TITCALL DumpProcess(HANDLE hProcess, LPVOID ImageBase, const char* szDumpFileName, ULONG_PTR EntryPoint);
__declspec(dllexport) bool TITCALL DumpProcessW(HANDLE hProcess, LPVOID ImageBase, const wchar_t* szDumpFileName, ULONG_PTR EntryPoint);
__declspec(dllexport) bool TITCALL DumpProcessEx(DWORD ProcessId, LPVOID ImageBase, const char* szDumpFileName, ULONG_PTR EntryPoint);
__declspec(dllexport) bool TITCALL DumpProcessExW(DWORD ProcessId, LPVOID ImageBase, const wchar_t* szDumpFileName, ULONG_PTR EntryPoint);
__declspec(dllexport) bool TITCALL DumpMemory(HANDLE hProcess, LPVOID MemoryStart, ULONG_PTR MemorySize, const char* szDumpFileName);
__declspec(dllexport) bool TITCALL DumpMemoryW(HANDLE hProcess, LPVOID MemoryStart, ULONG_PTR MemorySize, const wchar_t* szDumpFileName);
__declspec(dllexport) bool TITCALL DumpMemoryEx(DWORD ProcessId, LPVOID MemoryStart, ULONG_PTR MemorySize, const char* szDumpFileName);
__declspec(dllexport) bool TITCALL DumpMemoryExW(DWORD ProcessId, LPVOID MemoryStart, ULONG_PTR MemorySize, const wchar_t* szDumpFileName);
__declspec(dllexport) bool TITCALL DumpRegions(HANDLE hProcess, const char* szDumpFolder, bool DumpAboveImageBaseOnly);
__declspec(dllexport) bool TITCALL DumpRegionsW(HANDLE hProcess, const wchar_t* szDumpFolder, bool DumpAboveImageBaseOnly);
__declspec(dllexport) bool TITCALL DumpRegionsEx(DWORD ProcessId, const char* szDumpFolder, bool DumpAboveImageBaseOnly);
__declspec(dllexport) bool TITCALL DumpRegionsExW(DWORD ProcessId, const wchar_t* szDumpFolder, bool DumpAboveImageBaseOnly);
__declspec(dllexport) bool TITCALL DumpModule(HANDLE hProcess, LPVOID ModuleBase, const char* szDumpFileName);
__declspec(dllexport) bool TITCALL DumpModuleW(HANDLE hProcess, LPVOID ModuleBase, const wchar_t* szDumpFileName);
__declspec(dllexport) bool TITCALL DumpModuleEx(DWORD ProcessId, LPVOID ModuleBase, const char* szDumpFileName);
__declspec(dllexport) bool TITCALL DumpModuleExW(DWORD ProcessId, LPVOID ModuleBase, const wchar_t* szDumpFileName);
__declspec(dllexport) bool TITCALL PastePEHeader(HANDLE hProcess, LPVOID ImageBase, const char* szDebuggedFileName);
__declspec(dllexport) bool TITCALL PastePEHeaderW(HANDLE hProcess, LPVOID ImageBase, const wchar_t* szDebuggedFileName);
__declspec(dllexport) bool TITCALL ExtractSection(const char* szFileName, const char* szDumpFileName, DWORD SectionNumber);
__declspec(dllexport) bool TITCALL ExtractSectionW(const wchar_t* szFileName, const wchar_t* szDumpFileName, DWORD SectionNumber);
__declspec(dllexport) bool TITCALL ResortFileSections(const char* szFileName);
__declspec(dllexport) bool TITCALL ResortFileSectionsW(const wchar_t* szFileName);
__declspec(dllexport) bool TITCALL FindOverlay(const char* szFileName, LPDWORD OverlayStart, LPDWORD OverlaySize);
__declspec(dllexport) bool TITCALL FindOverlayW(const wchar_t* szFileName, LPDWORD OverlayStart, LPDWORD OverlaySize);
__declspec(dllexport) bool TITCALL ExtractOverlay(const char* szFileName, const char* szExtactedFileName);
__declspec(dllexport) bool TITCALL ExtractOverlayW(const wchar_t* szFileName, const wchar_t* szExtactedFileName);
__declspec(dllexport) bool TITCALL AddOverlay(const char* szFileName, const char* szOverlayFileName);
__declspec(dllexport) bool TITCALL AddOverlayW(const wchar_t* szFileName, const wchar_t* szOverlayFileName);
__declspec(dllexport) bool TITCALL CopyOverlay(const char* szInFileName, const char* szOutFileName);
__declspec(dllexport) bool TITCALL CopyOverlayW(const wchar_t* szInFileName, const wchar_t* szOutFileName);
__declspec(dllexport) bool TITCALL RemoveOverlay(const char* szFileName);
__declspec(dllexport) bool TITCALL RemoveOverlayW(const wchar_t* szFileName);
__declspec(dllexport) bool TITCALL MakeAllSectionsRWE(const char* szFileName);
__declspec(dllexport) bool TITCALL MakeAllSectionsRWEW(const wchar_t* szFileName);
__declspec(dllexport) long TITCALL AddNewSectionEx(const char* szFileName, const char* szSectionName, DWORD SectionSize, DWORD SectionAttributes, LPVOID SectionContent, DWORD ContentSize);
__declspec(dllexport) long TITCALL AddNewSectionExW(const wchar_t* szFileName, const char* szSectionName, DWORD SectionSize, DWORD SectionAttributes, LPVOID SectionContent, DWORD ContentSize);
__declspec(dllexport) long TITCALL AddNewSection(const char* szFileName, const char* szSectionName, DWORD SectionSize);
__declspec(dllexport) long TITCALL AddNewSectionW(const wchar_t* szFileName, const char* szSectionName, DWORD SectionSize);
__declspec(dllexport) bool TITCALL ResizeLastSection(const char* szFileName, DWORD NumberOfExpandBytes, bool AlignResizeData);
__declspec(dllexport) bool TITCALL ResizeLastSectionW(const wchar_t* szFileName, DWORD NumberOfExpandBytes, bool AlignResizeData);
__declspec(dllexport) void TITCALL SetSharedOverlay(const char* szFileName);
__declspec(dllexport) void TITCALL SetSharedOverlayW(const wchar_t* szFileName);
__declspec(dllexport) char* TITCALL GetSharedOverlay();
__declspec(dllexport) wchar_t* TITCALL GetSharedOverlayW();
__declspec(dllexport) bool TITCALL DeleteLastSection(const char* szFileName);
__declspec(dllexport) bool TITCALL DeleteLastSectionW(const wchar_t* szFileName);
__declspec(dllexport) bool TITCALL DeleteLastSectionEx(const char* szFileName, DWORD NumberOfSections);
__declspec(dllexport) bool TITCALL DeleteLastSectionExW(const wchar_t* szFileName, DWORD NumberOfSections);
__declspec(dllexport) ULONG_PTR TITCALL GetPE32DataFromMappedFile(ULONG_PTR FileMapVA, DWORD WhichSection, DWORD WhichData);
__declspec(dllexport) ULONG_PTR TITCALL GetPE32Data(const char* szFileName, DWORD WhichSection, DWORD WhichData);
__declspec(dllexport) ULONG_PTR TITCALL GetPE32DataW(const wchar_t* szFileName, DWORD WhichSection, DWORD WhichData);
__declspec(dllexport) bool TITCALL GetPE32DataFromMappedFileEx(ULONG_PTR FileMapVA, LPVOID DataStorage);
__declspec(dllexport) bool TITCALL GetPE32DataEx(const char* szFileName, LPVOID DataStorage);
__declspec(dllexport) bool TITCALL GetPE32DataExW(const wchar_t* szFileName, LPVOID DataStorage);
__declspec(dllexport) bool TITCALL SetPE32DataForMappedFile(ULONG_PTR FileMapVA, DWORD WhichSection, DWORD WhichData, ULONG_PTR NewDataValue);
__declspec(dllexport) bool TITCALL SetPE32Data(const char* szFileName, DWORD WhichSection, DWORD WhichData, ULONG_PTR NewDataValue);
__declspec(dllexport) bool TITCALL SetPE32DataW(const wchar_t* szFileName, DWORD WhichSection, DWORD WhichData, ULONG_PTR NewDataValue);
__declspec(dllexport) bool TITCALL SetPE32DataForMappedFileEx(ULONG_PTR FileMapVA, LPVOID DataStorage);
__declspec(dllexport) bool TITCALL SetPE32DataEx(const char* szFileName, LPVOID DataStorage);
__declspec(dllexport) bool TITCALL SetPE32DataExW(const wchar_t* szFileName, LPVOID DataStorage);
__declspec(dllexport) long TITCALL GetPE32SectionNumberFromVA(ULONG_PTR FileMapVA, ULONG_PTR AddressToConvert);
__declspec(dllexport) ULONG_PTR TITCALL ConvertVAtoFileOffset(ULONG_PTR FileMapVA, ULONG_PTR AddressToConvert, bool ReturnType);
__declspec(dllexport) ULONG_PTR TITCALL ConvertVAtoFileOffsetEx(ULONG_PTR FileMapVA, DWORD FileSize, ULONG_PTR ImageBase, ULONG_PTR AddressToConvert, bool AddressIsRVA, bool ReturnType);
__declspec(dllexport) ULONG_PTR TITCALL ConvertFileOffsetToVA(ULONG_PTR FileMapVA, ULONG_PTR AddressToConvert, bool ReturnType);
__declspec(dllexport) ULONG_PTR TITCALL ConvertFileOffsetToVAEx(ULONG_PTR FileMapVA, DWORD FileSize, ULONG_PTR ImageBase, ULONG_PTR AddressToConvert, bool ReturnType);
__declspec(dllexport) bool TITCALL MemoryReadSafe(HANDLE hProcess, LPVOID lpBaseAddress, LPVOID lpBuffer, SIZE_T nSize, SIZE_T* lpNumberOfBytesRead);
__declspec(dllexport) bool TITCALL MemoryWriteSafe(HANDLE hProcess, LPVOID lpBaseAddress, LPCVOID lpBuffer, SIZE_T nSize, SIZE_T* lpNumberOfBytesWritten);
// TitanEngine.Realigner.functions:
__declspec(dllexport) bool TITCALL FixHeaderCheckSum(const char* szFileName);
__declspec(dllexport) bool TITCALL FixHeaderCheckSumW(const wchar_t* szFileName);
__declspec(dllexport) long TITCALL RealignPE(ULONG_PTR FileMapVA, DWORD FileSize, DWORD RealingMode);
__declspec(dllexport) long TITCALL RealignPEEx(const char* szFileName, DWORD RealingFileSize, DWORD ForcedFileAlignment);
__declspec(dllexport) long TITCALL RealignPEExW(const wchar_t* szFileName, DWORD RealingFileSize, DWORD ForcedFileAlignment);
__declspec(dllexport) bool TITCALL WipeSection(const char* szFileName, int WipeSectionNumber, bool RemovePhysically);
__declspec(dllexport) bool TITCALL WipeSectionW(const wchar_t* szFileName, int WipeSectionNumber, bool RemovePhysically);
__declspec(dllexport) bool TITCALL IsPE32FileValidEx(const char* szFileName, DWORD CheckDepth, LPVOID FileStatusInfo);
__declspec(dllexport) bool TITCALL IsPE32FileValidExW(const wchar_t* szFileName, DWORD CheckDepth, LPVOID FileStatusInfo);
__declspec(dllexport) bool TITCALL FixBrokenPE32FileEx(const char* szFileName, LPVOID FileStatusInfo, LPVOID FileFixInfo);
__declspec(dllexport) bool TITCALL FixBrokenPE32FileExW(const wchar_t* szFileName, LPVOID FileStatusInfo, LPVOID FileFixInfo);
__declspec(dllexport) bool TITCALL IsFileDLL(const char* szFileName, ULONG_PTR FileMapVA);
__declspec(dllexport) bool TITCALL IsFileDLLW(const wchar_t* szFileName, ULONG_PTR FileMapVA);
// TitanEngine.Hider.functions:
__declspec(dllexport) void* TITCALL GetPEBLocation(HANDLE hProcess);
__declspec(dllexport) void* TITCALL GetPEBLocation64(HANDLE hProcess);
__declspec(dllexport) void* TITCALL GetTEBLocation(HANDLE hThread);
__declspec(dllexport) void* TITCALL GetTEBLocation64(HANDLE hThread);
__declspec(dllexport) bool TITCALL HideDebugger(HANDLE hProcess, DWORD PatchAPILevel);
__declspec(dllexport) bool TITCALL UnHideDebugger(HANDLE hProcess, DWORD PatchAPILevel);
// TitanEngine.Relocater.functions:
__declspec(dllexport) void TITCALL RelocaterCleanup();
__declspec(dllexport) void TITCALL RelocaterInit(DWORD MemorySize, ULONG_PTR OldImageBase, ULONG_PTR NewImageBase);
__declspec(dllexport) void TITCALL RelocaterAddNewRelocation(HANDLE hProcess, ULONG_PTR RelocateAddress, DWORD RelocateState);
__declspec(dllexport) long TITCALL RelocaterEstimatedSize();
__declspec(dllexport) bool TITCALL RelocaterExportRelocation(ULONG_PTR StorePlace, DWORD StorePlaceRVA, ULONG_PTR FileMapVA);
__declspec(dllexport) bool TITCALL RelocaterExportRelocationEx(const char* szFileName, const char* szSectionName);
__declspec(dllexport) bool TITCALL RelocaterExportRelocationExW(const wchar_t* szFileName, const char* szSectionName);
__declspec(dllexport) bool TITCALL RelocaterGrabRelocationTable(HANDLE hProcess, ULONG_PTR MemoryStart, DWORD MemorySize);
__declspec(dllexport) bool TITCALL RelocaterGrabRelocationTableEx(HANDLE hProcess, ULONG_PTR MemoryStart, ULONG_PTR MemorySize, DWORD NtSizeOfImage);
__declspec(dllexport) bool TITCALL RelocaterMakeSnapshot(HANDLE hProcess, const char* szSaveFileName, LPVOID MemoryStart, ULONG_PTR MemorySize);
__declspec(dllexport) bool TITCALL RelocaterMakeSnapshotW(HANDLE hProcess, const wchar_t* szSaveFileName, LPVOID MemoryStart, ULONG_PTR MemorySize);
__declspec(dllexport) bool TITCALL RelocaterCompareTwoSnapshots(HANDLE hProcess, ULONG_PTR LoadedImageBase, ULONG_PTR NtSizeOfImage, const char* szDumpFile1, const char* szDumpFile2, ULONG_PTR MemStart);
__declspec(dllexport) bool TITCALL RelocaterCompareTwoSnapshotsW(HANDLE hProcess, ULONG_PTR LoadedImageBase, ULONG_PTR NtSizeOfImage, const wchar_t* szDumpFile1, const wchar_t* szDumpFile2, ULONG_PTR MemStart);
__declspec(dllexport) bool TITCALL RelocaterChangeFileBase(const char* szFileName, ULONG_PTR NewImageBase);
__declspec(dllexport) bool TITCALL RelocaterChangeFileBaseW(const wchar_t* szFileName, ULONG_PTR NewImageBase);
__declspec(dllexport) bool TITCALL RelocaterRelocateMemoryBlock(ULONG_PTR FileMapVA, ULONG_PTR MemoryLocation, void* RelocateMemory, DWORD RelocateMemorySize, ULONG_PTR CurrentLoadedBase, ULONG_PTR RelocateBase);
__declspec(dllexport) bool TITCALL RelocaterWipeRelocationTable(const char* szFileName);
__declspec(dllexport) bool TITCALL RelocaterWipeRelocationTableW(const wchar_t* szFileName);
// TitanEngine.Resourcer.functions:
__declspec(dllexport) ULONG_PTR TITCALL ResourcerLoadFileForResourceUse(const char* szFileName);
__declspec(dllexport) ULONG_PTR TITCALL ResourcerLoadFileForResourceUseW(const wchar_t* szFileName);
__declspec(dllexport) bool TITCALL ResourcerFreeLoadedFile(LPVOID LoadedFileBase);
__declspec(dllexport) bool TITCALL ResourcerExtractResourceFromFileEx(HMODULE hFile, const char* szResourceType, const char* szResourceName, const char* szExtractedFileName);
__declspec(dllexport) bool TITCALL ResourcerExtractResourceFromFile(const char* szFileName, const char* szResourceType, const char* szResourceName, const char* szExtractedFileName);
__declspec(dllexport) bool TITCALL ResourcerExtractResourceFromFileW(const wchar_t* szFileName, char* szResourceType, const char* szResourceName, const char* szExtractedFileName);
__declspec(dllexport) bool TITCALL ResourcerFindResource(const char* szFileName, const char* szResourceType, DWORD ResourceType, const char* szResourceName, DWORD ResourceName, DWORD ResourceLanguage, PULONG_PTR pResourceData, LPDWORD pResourceSize);
__declspec(dllexport) bool TITCALL ResourcerFindResourceW(const wchar_t* szFileName, const wchar_t* szResourceType, DWORD ResourceType, const wchar_t* szResourceName, DWORD ResourceName, DWORD ResourceLanguage, PULONG_PTR pResourceData, LPDWORD pResourceSize);
__declspec(dllexport) bool TITCALL ResourcerFindResourceEx(ULONG_PTR FileMapVA, DWORD FileSize, const wchar_t* szResourceType, DWORD ResourceType, const wchar_t* szResourceName, DWORD ResourceName, DWORD ResourceLanguage, PULONG_PTR pResourceData, LPDWORD pResourceSize);
__declspec(dllexport) void TITCALL ResourcerEnumerateResource(const char* szFileName, void* CallBack);
__declspec(dllexport) void TITCALL ResourcerEnumerateResourceW(const wchar_t* szFileName, void* CallBack);
__declspec(dllexport) void TITCALL ResourcerEnumerateResourceEx(ULONG_PTR FileMapVA, DWORD FileSize, void* CallBack);
// TitanEngine.Threader.functions:
__declspec(dllexport) bool TITCALL ThreaderImportRunningThreadData(DWORD ProcessId);
__declspec(dllexport) void* TITCALL ThreaderGetThreadInfo(HANDLE hThread, DWORD ThreadId);
__declspec(dllexport) void TITCALL ThreaderEnumThreadInfo(void* EnumCallBack);
__declspec(dllexport) bool TITCALL ThreaderPauseThread(HANDLE hThread);
__declspec(dllexport) bool TITCALL ThreaderResumeThread(HANDLE hThread);
__declspec(dllexport) bool TITCALL ThreaderTerminateThread(HANDLE hThread, DWORD ThreadExitCode);
__declspec(dllexport) bool TITCALL ThreaderPauseAllThreads(bool LeaveMainRunning);
__declspec(dllexport) bool TITCALL ThreaderResumeAllThreads(bool LeaveMainPaused);
__declspec(dllexport) bool TITCALL ThreaderPauseProcess();
__declspec(dllexport) bool TITCALL ThreaderResumeProcess();
__declspec(dllexport) ULONG_PTR TITCALL ThreaderCreateRemoteThread(ULONG_PTR ThreadStartAddress, bool AutoCloseTheHandle, LPVOID ThreadPassParameter, LPDWORD ThreadId);
__declspec(dllexport) bool TITCALL ThreaderInjectAndExecuteCode(LPVOID InjectCode, DWORD StartDelta, DWORD InjectSize);
__declspec(dllexport) ULONG_PTR TITCALL ThreaderCreateRemoteThreadEx(HANDLE hProcess, ULONG_PTR ThreadStartAddress, bool AutoCloseTheHandle, LPVOID ThreadPassParameter, LPDWORD ThreadId);
__declspec(dllexport) bool TITCALL ThreaderInjectAndExecuteCodeEx(HANDLE hProcess, LPVOID InjectCode, DWORD StartDelta, DWORD InjectSize);
__declspec(dllexport) void TITCALL ThreaderSetCallBackForNextExitThreadEvent(LPVOID exitThreadCallBack);
__declspec(dllexport) bool TITCALL ThreaderIsThreadStillRunning(HANDLE hThread);
__declspec(dllexport) bool TITCALL ThreaderIsThreadActive(HANDLE hThread);
__declspec(dllexport) bool TITCALL ThreaderIsAnyThreadActive();
__declspec(dllexport) bool TITCALL ThreaderExecuteOnlyInjectedThreads();
__declspec(dllexport) ULONG_PTR TITCALL ThreaderGetOpenHandleForThread(DWORD ThreadId);
__declspec(dllexport) bool TITCALL ThreaderIsExceptionInMainThread();
// TitanEngine.Debugger.functions:
__declspec(dllexport) void* TITCALL StaticDisassembleEx(ULONG_PTR DisassmStart, LPVOID DisassmAddress);
__declspec(dllexport) void* TITCALL StaticDisassemble(LPVOID DisassmAddress);
__declspec(dllexport) void* TITCALL DisassembleEx(HANDLE hProcess, LPVOID DisassmAddress, bool ReturnInstructionType);
__declspec(dllexport) void* TITCALL Disassemble(LPVOID DisassmAddress);
__declspec(dllexport) long TITCALL StaticLengthDisassemble(LPVOID DisassmAddress);
__declspec(dllexport) long TITCALL LengthDisassembleEx(HANDLE hProcess, LPVOID DisassmAddress);
__declspec(dllexport) long TITCALL LengthDisassemble(LPVOID DisassmAddress);
__declspec(dllexport) void* TITCALL InitDebug(char* szFileName, char* szCommandLine, char* szCurrentFolder);
__declspec(dllexport) void* TITCALL InitDebugW(const wchar_t* szFileName, const wchar_t* szCommandLine, const wchar_t* szCurrentFolder);
__declspec(dllexport) void* TITCALL InitNativeDebug(char* szFileName, char* szCommandLine, char* szCurrentFolder);
__declspec(dllexport) void* TITCALL InitNativeDebugW(const wchar_t* szFileName, const wchar_t* szCommandLine, const wchar_t* szCurrentFolder);
__declspec(dllexport) void* TITCALL InitDebugEx(const char* szFileName, const char* szCommandLine, const char* szCurrentFolder, LPVOID EntryCallBack);
__declspec(dllexport) void* TITCALL InitDebugExW(const wchar_t* szFileName, const wchar_t* szCommandLine, const wchar_t* szCurrentFolder, LPVOID EntryCallBack);
__declspec(dllexport) void* TITCALL InitDLLDebug(const char* szFileName, bool ReserveModuleBase, const char* szCommandLine, const char* szCurrentFolder, LPVOID EntryCallBack);
__declspec(dllexport) void* TITCALL InitDLLDebugW(const wchar_t* szFileName, bool ReserveModuleBase, const wchar_t* szCommandLine, const wchar_t* szCurrentFolder, LPVOID EntryCallBack);
__declspec(dllexport) bool TITCALL StopDebug();
__declspec(dllexport) void TITCALL SetBPXOptions(long DefaultBreakPointType);
__declspec(dllexport) bool TITCALL IsBPXEnabled(ULONG_PTR bpxAddress);
__declspec(dllexport) bool TITCALL EnableBPX(ULONG_PTR bpxAddress);
__declspec(dllexport) bool TITCALL DisableBPX(ULONG_PTR bpxAddress);
__declspec(dllexport) bool TITCALL SetBPX(ULONG_PTR bpxAddress, DWORD bpxType, TITANCBSOFTBP bpxCallBack);
__declspec(dllexport) bool TITCALL DeleteBPX(ULONG_PTR bpxAddress);
__declspec(dllexport) bool TITCALL SafeDeleteBPX(ULONG_PTR bpxAddress);
__declspec(dllexport) bool TITCALL SetAPIBreakPoint(const char* szDLLName, const char* szAPIName, DWORD bpxType, DWORD bpxPlace, LPVOID bpxCallBack);
__declspec(dllexport) bool TITCALL DeleteAPIBreakPoint(const char* szDLLName, const char* szAPIName, DWORD bpxPlace);
__declspec(dllexport) bool TITCALL SafeDeleteAPIBreakPoint(const char* szDLLName, const char* szAPIName, DWORD bpxPlace);
__declspec(dllexport) bool TITCALL SetMemoryBPX(ULONG_PTR MemoryStart, SIZE_T SizeOfMemory, LPVOID bpxCallBack);
__declspec(dllexport) bool TITCALL SetMemoryBPXEx(ULONG_PTR MemoryStart, SIZE_T SizeOfMemory, DWORD BreakPointType, bool RestoreOnHit, TITANCBMEMBP bpxCallBack);
__declspec(dllexport) bool TITCALL RemoveMemoryBPX(ULONG_PTR MemoryStart, SIZE_T SizeOfMemory);
__declspec(dllexport) bool TITCALL GetContextFPUDataEx(HANDLE hActiveThread, void* FPUSaveArea);
__declspec(dllexport) void TITCALL Getx87FPURegisters(x87FPURegister_t x87FPURegisters[8], TITAN_ENGINE_CONTEXT_t* titcontext);
__declspec(dllexport) void TITCALL GetMMXRegisters(uint64_t mmx[8], TITAN_ENGINE_CONTEXT_t* titcontext);
__declspec(dllexport) bool TITCALL GetFullContextDataEx(HANDLE hActiveThread, TITAN_ENGINE_CONTEXT_t* titcontext);
__declspec(dllexport) bool TITCALL SetFullContextDataEx(HANDLE hActiveThread, TITAN_ENGINE_CONTEXT_t* titcontext);
__declspec(dllexport) ULONG_PTR TITCALL GetContextDataEx(HANDLE hActiveThread, DWORD IndexOfRegister);
__declspec(dllexport) ULONG_PTR TITCALL GetContextData(DWORD IndexOfRegister);
__declspec(dllexport) bool TITCALL SetContextFPUDataEx(HANDLE hActiveThread, void* FPUSaveArea);
__declspec(dllexport) bool TITCALL SetContextDataEx(HANDLE hActiveThread, DWORD IndexOfRegister, ULONG_PTR NewRegisterValue);
__declspec(dllexport) bool TITCALL SetContextData(DWORD IndexOfRegister, ULONG_PTR NewRegisterValue);
__declspec(dllexport) bool TITCALL GetAVXContext(HANDLE hActiveThread, TITAN_ENGINE_CONTEXT_t* titcontext);
__declspec(dllexport) bool TITCALL SetAVXContext(HANDLE hActiveThread, TITAN_ENGINE_CONTEXT_t* titcontext);
__declspec(dllexport) void TITCALL ClearExceptionNumber();
__declspec(dllexport) long TITCALL CurrentExceptionNumber();
__declspec(dllexport) bool TITCALL MatchPatternEx(HANDLE hProcess, void* MemoryToCheck, int SizeOfMemoryToCheck, void* PatternToMatch, int SizeOfPatternToMatch, PBYTE WildCard);
__declspec(dllexport) bool TITCALL MatchPattern(void* MemoryToCheck, int SizeOfMemoryToCheck, void* PatternToMatch, int SizeOfPatternToMatch, PBYTE WildCard);
__declspec(dllexport) ULONG_PTR TITCALL FindEx(HANDLE hProcess, LPVOID MemoryStart, DWORD MemorySize, LPVOID SearchPattern, DWORD PatternSize, LPBYTE WildCard);
extern "C" __declspec(dllexport) ULONG_PTR TITCALL Find(LPVOID MemoryStart, DWORD MemorySize, LPVOID SearchPattern, DWORD PatternSize, LPBYTE WildCard);
__declspec(dllexport) bool TITCALL FillEx(HANDLE hProcess, LPVOID MemoryStart, DWORD MemorySize, PBYTE FillByte);
__declspec(dllexport) bool TITCALL Fill(LPVOID MemoryStart, DWORD MemorySize, PBYTE FillByte);
__declspec(dllexport) bool TITCALL PatchEx(HANDLE hProcess, LPVOID MemoryStart, DWORD MemorySize, LPVOID ReplacePattern, DWORD ReplaceSize, bool AppendNOP, bool PrependNOP);
__declspec(dllexport) bool TITCALL Patch(LPVOID MemoryStart, DWORD MemorySize, LPVOID ReplacePattern, DWORD ReplaceSize, bool AppendNOP, bool PrependNOP);
__declspec(dllexport) bool TITCALL ReplaceEx(HANDLE hProcess, LPVOID MemoryStart, DWORD MemorySize, LPVOID SearchPattern, DWORD PatternSize, DWORD NumberOfRepetitions, LPVOID ReplacePattern, DWORD ReplaceSize, PBYTE WildCard);
__declspec(dllexport) bool TITCALL Replace(LPVOID MemoryStart, DWORD MemorySize, LPVOID SearchPattern, DWORD PatternSize, DWORD NumberOfRepetitions, LPVOID ReplacePattern, DWORD ReplaceSize, PBYTE WildCard);
__declspec(dllexport) void* TITCALL GetDebugData();
__declspec(dllexport) void* TITCALL GetTerminationData();
__declspec(dllexport) long TITCALL GetExitCode();
__declspec(dllexport) ULONG_PTR TITCALL GetDebuggedDLLBaseAddress();
__declspec(dllexport) ULONG_PTR TITCALL GetDebuggedFileBaseAddress();
__declspec(dllexport) bool TITCALL GetRemoteString(HANDLE hProcess, LPVOID StringAddress, LPVOID StringStorage, int MaximumStringSize);
__declspec(dllexport) ULONG_PTR TITCALL GetFunctionParameter(HANDLE hProcess, DWORD FunctionType, DWORD ParameterNumber, DWORD ParameterType);
__declspec(dllexport) ULONG_PTR TITCALL GetJumpDestinationEx(HANDLE hProcess, ULONG_PTR InstructionAddress, bool JustJumps);
__declspec(dllexport) ULONG_PTR TITCALL GetJumpDestination(HANDLE hProcess, ULONG_PTR InstructionAddress);
__declspec(dllexport) bool TITCALL IsJumpGoingToExecuteEx(HANDLE hProcess, HANDLE hThread, ULONG_PTR InstructionAddress, ULONG_PTR RegFlags);
__declspec(dllexport) bool TITCALL IsJumpGoingToExecute();
__declspec(dllexport) void TITCALL SetCustomHandler(DWORD ExceptionId, TITANCBCH CallBack);
__declspec(dllexport) void TITCALL ForceClose();
__declspec(dllexport) void TITCALL StepInto(TITANCBSTEP traceCallBack);
__declspec(dllexport) void TITCALL StepOver(TITANCBSTEP traceCallBack);
__declspec(dllexport) void TITCALL StepOut(TITANCBSTEP StepOut, bool StepFinal);
__declspec(dllexport) void TITCALL SingleStep(DWORD StepCount, TITANCBSTEP StepCallBack);
__declspec(dllexport) bool TITCALL GetUnusedHardwareBreakPointRegister(LPDWORD RegisterIndex);
__declspec(dllexport) bool TITCALL SetHardwareBreakPointEx(HANDLE hActiveThread, ULONG_PTR bpxAddress, DWORD IndexOfRegister, DWORD bpxType, DWORD bpxSize, TITANCBHWBP bpxCallBack, LPDWORD IndexOfSelectedRegister);
__declspec(dllexport) bool TITCALL SetHardwareBreakPoint(ULONG_PTR bpxAddress, DWORD IndexOfRegister, DWORD bpxType, DWORD bpxSize, TITANCBHWBP bpxCallBack);
__declspec(dllexport) bool TITCALL DeleteHardwareBreakPoint(DWORD IndexOfRegister);
__declspec(dllexport) bool TITCALL RemoveAllBreakPoints(DWORD RemoveOption);
__declspec(dllexport) PROCESS_INFORMATION* TITCALL TitanGetProcessInformation();
__declspec(dllexport) STARTUPINFOW* TITCALL TitanGetStartupInformation();
__declspec(dllexport) void TITCALL DebugLoop();
__declspec(dllexport) void TITCALL SetDebugLoopTimeOut(DWORD TimeOut);
__declspec(dllexport) void TITCALL SetNextDbgContinueStatus(DWORD SetDbgCode);
__declspec(dllexport) bool TITCALL AttachDebugger(DWORD ProcessId, bool KillOnExit, LPVOID DebugInfo, TITANCALLBACK CallBack);
__declspec(dllexport) bool TITCALL DetachDebugger(DWORD ProcessId);
__declspec(dllexport) bool TITCALL DetachDebuggerEx(DWORD ProcessId);
__declspec(dllexport) void TITCALL DebugLoopEx(DWORD TimeOut);
__declspec(dllexport) void TITCALL AutoDebugEx(const char* szFileName, bool ReserveModuleBase, const char* szCommandLine, const char* szCurrentFolder, DWORD TimeOut, TITANCBSOFTBP EntryCallBack);
__declspec(dllexport) void TITCALL AutoDebugExW(const wchar_t* szFileName, bool ReserveModuleBase, const wchar_t* szCommandLine, const wchar_t* szCurrentFolder, DWORD TimeOut, TITANCBSOFTBP EntryCallBack);
__declspec(dllexport) bool TITCALL IsFileBeingDebugged();
__declspec(dllexport) void TITCALL SetErrorModel(bool DisplayErrorMessages);
// TitanEngine.FindOEP.functions:
__declspec(dllexport) void TITCALL FindOEPInit();
__declspec(dllexport) bool TITCALL FindOEPGenerically(const char* szFileName, LPVOID TraceInitCallBack, LPVOID CallBack);
__declspec(dllexport) bool TITCALL FindOEPGenericallyW(const wchar_t* szFileName, LPVOID TraceInitCallBack, LPVOID CallBack);
// TitanEngine.Importer.functions:
__declspec(dllexport) void TITCALL ImporterAddNewDll(const char* szDLLName, ULONG_PTR FirstThunk);
__declspec(dllexport) void TITCALL ImporterAddNewAPI(const char* szAPIName, ULONG_PTR ThunkValue);
__declspec(dllexport) void TITCALL ImporterAddNewOrdinalAPI(ULONG_PTR OrdinalNumber, ULONG_PTR ThunkValue);
__declspec(dllexport) long TITCALL ImporterGetAddedDllCount();
__declspec(dllexport) long TITCALL ImporterGetAddedAPICount();
__declspec(dllexport) bool TITCALL ImporterExportIAT(ULONG_PTR StorePlace, ULONG_PTR FileMapVA, HANDLE hFileMap);
__declspec(dllexport) long TITCALL ImporterEstimatedSize();
__declspec(dllexport) bool TITCALL ImporterExportIATEx(const char* szDumpFileName, const char* szExportFileName, const char* szSectionName);
__declspec(dllexport) bool TITCALL ImporterExportIATExW(const wchar_t* szDumpFileName, const wchar_t* szExportFileName, const wchar_t* szSectionName = L".RL!TEv2");
__declspec(dllexport) ULONG_PTR TITCALL ImporterFindAPIWriteLocation(const char* szAPIName);
__declspec(dllexport) ULONG_PTR TITCALL ImporterFindOrdinalAPIWriteLocation(ULONG_PTR OrdinalNumber);
__declspec(dllexport) ULONG_PTR TITCALL ImporterFindAPIByWriteLocation(ULONG_PTR APIWriteLocation);
__declspec(dllexport) ULONG_PTR TITCALL ImporterFindDLLByWriteLocation(ULONG_PTR APIWriteLocation);
__declspec(dllexport) void* TITCALL ImporterGetDLLName(ULONG_PTR APIAddress);
__declspec(dllexport) void* TITCALL ImporterGetDLLNameW(ULONG_PTR APIAddress);
__declspec(dllexport) void* TITCALL ImporterGetAPIName(ULONG_PTR APIAddress);
__declspec(dllexport) ULONG_PTR TITCALL ImporterGetAPIOrdinalNumber(ULONG_PTR APIAddress);
__declspec(dllexport) void* TITCALL ImporterGetAPINameEx(ULONG_PTR APIAddress, ULONG_PTR DLLBasesList);
__declspec(dllexport) ULONG_PTR TITCALL ImporterGetRemoteAPIAddress(HANDLE hProcess, ULONG_PTR APIAddress);
__declspec(dllexport) ULONG_PTR TITCALL ImporterGetRemoteAPIAddressEx(const char* szDLLName, const char* szAPIName);
__declspec(dllexport) ULONG_PTR TITCALL ImporterGetLocalAPIAddress(HANDLE hProcess, ULONG_PTR APIAddress);
__declspec(dllexport) void* TITCALL ImporterGetDLLNameFromDebugee(HANDLE hProcess, ULONG_PTR APIAddress);
__declspec(dllexport) void* TITCALL ImporterGetDLLNameFromDebugeeW(HANDLE hProcess, ULONG_PTR APIAddress);
__declspec(dllexport) void* TITCALL ImporterGetAPINameFromDebugee(HANDLE hProcess, ULONG_PTR APIAddress);
__declspec(dllexport) ULONG_PTR TITCALL ImporterGetAPIOrdinalNumberFromDebugee(HANDLE hProcess, ULONG_PTR APIAddress);
__declspec(dllexport) long TITCALL ImporterGetDLLIndexEx(ULONG_PTR APIAddress, ULONG_PTR DLLBasesList);
__declspec(dllexport) long TITCALL ImporterGetDLLIndex(HANDLE hProcess, ULONG_PTR APIAddress, ULONG_PTR DLLBasesList);
__declspec(dllexport) ULONG_PTR TITCALL ImporterGetRemoteDLLBase(HANDLE hProcess, HMODULE LocalModuleBase);
__declspec(dllexport) ULONG_PTR TITCALL ImporterGetRemoteDLLBaseEx(HANDLE hProcess, const char* szModuleName);
__declspec(dllexport) void* TITCALL ImporterGetRemoteDLLBaseExW(HANDLE hProcess, const wchar_t* szModuleName);
__declspec(dllexport) bool TITCALL ImporterIsForwardedAPI(HANDLE hProcess, ULONG_PTR APIAddress);
__declspec(dllexport) void* TITCALL ImporterGetForwardedAPIName(HANDLE hProcess, ULONG_PTR APIAddress);
__declspec(dllexport) void* TITCALL ImporterGetForwardedDLLName(HANDLE hProcess, ULONG_PTR APIAddress);
__declspec(dllexport) long TITCALL ImporterGetForwardedDLLIndex(HANDLE hProcess, ULONG_PTR APIAddress, ULONG_PTR DLLBasesList);
__declspec(dllexport) ULONG_PTR TITCALL ImporterGetForwardedAPIOrdinalNumber(HANDLE hProcess, ULONG_PTR APIAddress);
__declspec(dllexport) ULONG_PTR TITCALL ImporterGetNearestAPIAddress(HANDLE hProcess, ULONG_PTR APIAddress);
__declspec(dllexport) void* TITCALL ImporterGetNearestAPIName(HANDLE hProcess, ULONG_PTR APIAddress);
__declspec(dllexport) bool TITCALL ImporterCopyOriginalIAT(const char* szOriginalFile, const char* szDumpFile);
__declspec(dllexport) bool TITCALL ImporterCopyOriginalIATW(const wchar_t* szOriginalFile, const wchar_t* szDumpFile);
__declspec(dllexport) bool TITCALL ImporterLoadImportTable(const char* szFileName);
__declspec(dllexport) bool TITCALL ImporterLoadImportTableW(const wchar_t* szFileName);
__declspec(dllexport) bool TITCALL ImporterMoveOriginalIAT(const char* szOriginalFile, const char* szDumpFile, const char* szSectionName);
__declspec(dllexport) bool TITCALL ImporterMoveOriginalIATW(const wchar_t* szOriginalFile, const wchar_t* szDumpFile, const char* szSectionName);
__declspec(dllexport) void TITCALL ImporterAutoSearchIAT(DWORD ProcessId, const char* szFileName, ULONG_PTR SearchStart, LPVOID pIATStart, LPVOID pIATSize);
__declspec(dllexport) void TITCALL ImporterAutoSearchIATW(DWORD ProcessIds, const wchar_t* szFileName, ULONG_PTR SearchStart, LPVOID pIATStart, LPVOID pIATSize);
__declspec(dllexport) void TITCALL ImporterAutoSearchIATEx(DWORD ProcessId, ULONG_PTR ImageBase, ULONG_PTR SearchStart, LPVOID pIATStart, LPVOID pIATSize);
__declspec(dllexport) void TITCALL ImporterEnumAddedData(LPVOID EnumCallBack);
__declspec(dllexport) long TITCALL ImporterAutoFixIATEx(DWORD ProcessId, const char* szDumpedFile, const char* szSectionName, bool DumpRunningProcess, bool RealignFile, ULONG_PTR EntryPointAddress, ULONG_PTR ImageBase, ULONG_PTR SearchStart, bool TryAutoFix, bool FixEliminations, LPVOID UnknownPointerFixCallback);
__declspec(dllexport) long TITCALL ImporterAutoFixIATExW(DWORD ProcessId, const wchar_t* szDumpedFile, const wchar_t* szSectionName, bool DumpRunningProcess, bool RealignFile, ULONG_PTR EntryPointAddress, ULONG_PTR ImageBase, ULONG_PTR SearchStart, bool TryAutoFix, bool FixEliminations, LPVOID UnknownPointerFixCallback);
__declspec(dllexport) long TITCALL ImporterAutoFixIAT(DWORD ProcessId, const char* szDumpedFile, ULONG_PTR SearchStart);
__declspec(dllexport) long TITCALL ImporterAutoFixIATW(DWORD ProcessId, const wchar_t* szDumpedFile, ULONG_PTR SearchStart);
__declspec(dllexport) bool TITCALL ImporterDeleteAPI(DWORD_PTR apiAddr);
// Global.Engine.Hook.functions:
__declspec(dllexport) bool TITCALL HooksSafeTransitionEx(LPVOID HookAddressArray, int NumberOfHooks, bool TransitionStart);
__declspec(dllexport) bool TITCALL HooksSafeTransition(LPVOID HookAddress, bool TransitionStart);
__declspec(dllexport) bool TITCALL HooksIsAddressRedirected(LPVOID HookAddress);
__declspec(dllexport) void* TITCALL HooksGetTrampolineAddress(LPVOID HookAddress);
__declspec(dllexport) void* TITCALL HooksGetHookEntryDetails(LPVOID HookAddress);
__declspec(dllexport) bool TITCALL HooksInsertNewRedirection(LPVOID HookAddress, LPVOID RedirectTo, int HookType);
__declspec(dllexport) bool TITCALL HooksInsertNewIATRedirectionEx(ULONG_PTR FileMapVA, ULONG_PTR LoadedModuleBase, const char* szHookFunction, LPVOID RedirectTo);
__declspec(dllexport) bool TITCALL HooksInsertNewIATRedirection(const char* szModuleName, const char* szHookFunction, LPVOID RedirectTo);
__declspec(dllexport) bool TITCALL HooksRemoveRedirection(LPVOID HookAddress, bool RemoveAll);
__declspec(dllexport) bool TITCALL HooksRemoveRedirectionsForModule(HMODULE ModuleBase);
__declspec(dllexport) bool TITCALL HooksRemoveIATRedirection(const char* szModuleName, const char* szHookFunction, bool RemoveAll);
__declspec(dllexport) bool TITCALL HooksDisableRedirection(LPVOID HookAddress, bool DisableAll);
__declspec(dllexport) bool TITCALL HooksDisableRedirectionsForModule(HMODULE ModuleBase);
__declspec(dllexport) bool TITCALL HooksDisableIATRedirection(const char* szModuleName, const char* szHookFunction, bool DisableAll);
__declspec(dllexport) bool TITCALL HooksEnableRedirection(LPVOID HookAddress, bool EnableAll);
__declspec(dllexport) bool TITCALL HooksEnableRedirectionsForModule(HMODULE ModuleBase);
__declspec(dllexport) bool TITCALL HooksEnableIATRedirection(const char* szModuleName, const char* szHookFunction, bool EnableAll);
__declspec(dllexport) void TITCALL HooksScanModuleMemory(HMODULE ModuleBase, LPVOID CallBack);
__declspec(dllexport) void TITCALL HooksScanEntireProcessMemory(LPVOID CallBack);
__declspec(dllexport) void TITCALL HooksScanEntireProcessMemoryEx();
// TitanEngine.Tracer.functions:
__declspec(dllexport) void TITCALL TracerInit();
__declspec(dllexport) ULONG_PTR TITCALL TracerLevel1(HANDLE hProcess, ULONG_PTR AddressToTrace);
__declspec(dllexport) ULONG_PTR TITCALL HashTracerLevel1(HANDLE hProcess, ULONG_PTR AddressToTrace, DWORD InputNumberOfInstructions);
__declspec(dllexport) long TITCALL TracerDetectRedirection(HANDLE hProcess, ULONG_PTR AddressToTrace);
__declspec(dllexport) ULONG_PTR TITCALL TracerFixKnownRedirection(HANDLE hProcess, ULONG_PTR AddressToTrace, DWORD RedirectionId);
__declspec(dllexport) ULONG_PTR TITCALL TracerFixRedirectionViaModule(HMODULE hModuleHandle, HANDLE hProcess, ULONG_PTR AddressToTrace, DWORD IdParameter);
__declspec(dllexport) long TITCALL TracerFixRedirectionViaImpRecPlugin(HANDLE hProcess, const char* szPluginName, ULONG_PTR AddressToTrace);
// TitanEngine.Exporter.functions:
__declspec(dllexport) void TITCALL ExporterCleanup();
__declspec(dllexport) void TITCALL ExporterSetImageBase(ULONG_PTR ImageBase);
__declspec(dllexport) void TITCALL ExporterInit(DWORD MemorySize, ULONG_PTR ImageBase, DWORD ExportOrdinalBase, const char* szExportModuleName);
__declspec(dllexport) bool TITCALL ExporterAddNewExport(const char* szExportName, DWORD ExportRelativeAddress);
__declspec(dllexport) bool TITCALL ExporterAddNewOrdinalExport(DWORD OrdinalNumber, DWORD ExportRelativeAddress);
__declspec(dllexport) long TITCALL ExporterGetAddedExportCount();
__declspec(dllexport) long TITCALL ExporterEstimatedSize();
__declspec(dllexport) bool TITCALL ExporterBuildExportTable(ULONG_PTR StorePlace, ULONG_PTR FileMapVA);
__declspec(dllexport) bool TITCALL ExporterBuildExportTableEx(const char* szExportFileName, const char* szSectionName);
__declspec(dllexport) bool TITCALL ExporterBuildExportTableExW(const wchar_t* szExportFileName, const char* szSectionName);
__declspec(dllexport) bool TITCALL ExporterLoadExportTable(const char* szFileName);
__declspec(dllexport) bool TITCALL ExporterLoadExportTableW(const wchar_t* szFileName);
// TitanEngine.Librarian.functions:
__declspec(dllexport) bool TITCALL LibrarianSetBreakPoint(const char* szLibraryName, DWORD bpxType, bool SingleShoot, LPVOID bpxCallBack);
__declspec(dllexport) bool TITCALL LibrarianRemoveBreakPoint(const char* szLibraryName, DWORD bpxType);
__declspec(dllexport) void* TITCALL LibrarianGetLibraryInfo(const char* szLibraryName);
__declspec(dllexport) void* TITCALL LibrarianGetLibraryInfoW(const wchar_t* szLibraryName);
__declspec(dllexport) void* TITCALL LibrarianGetLibraryInfoEx(void* BaseOfDll);
__declspec(dllexport) void* TITCALL LibrarianGetLibraryInfoExW(void* BaseOfDll);
__declspec(dllexport) void TITCALL LibrarianEnumLibraryInfo(void* EnumCallBack);
__declspec(dllexport) void TITCALL LibrarianEnumLibraryInfoW(void* EnumCallBack);
// TitanEngine.Process.functions:
__declspec(dllexport) long TITCALL GetActiveProcessId(const char* szImageName);
__declspec(dllexport) long TITCALL GetActiveProcessIdW(const wchar_t* szImageName);
__declspec(dllexport) void TITCALL EnumProcessesWithLibrary(const char* szLibraryName, void* EnumFunction);
__declspec(dllexport) HANDLE TITCALL TitanOpenProcess(DWORD dwDesiredAccess, bool bInheritHandle, DWORD dwProcessId);
__declspec(dllexport) HANDLE TITCALL TitanOpenThread(DWORD dwDesiredAccess, bool bInheritHandle, DWORD dwThreadId);
// TitanEngine.TLSFixer.functions:
__declspec(dllexport) bool TITCALL TLSBreakOnCallBack(LPVOID ArrayOfCallBacks, DWORD NumberOfCallBacks, LPVOID bpxCallBack);
__declspec(dllexport) bool TITCALL TLSGrabCallBackData(const char* szFileName, LPVOID ArrayOfCallBacks, LPDWORD NumberOfCallBacks);
__declspec(dllexport) bool TITCALL TLSGrabCallBackDataW(const wchar_t* szFileName, LPVOID ArrayOfCallBacks, LPDWORD NumberOfCallBacks);
__declspec(dllexport) bool TITCALL TLSBreakOnCallBackEx(const char* szFileName, LPVOID bpxCallBack);
__declspec(dllexport) bool TITCALL TLSBreakOnCallBackExW(const wchar_t* szFileName, LPVOID bpxCallBack);
__declspec(dllexport) bool TITCALL TLSRemoveCallback(const char* szFileName);
__declspec(dllexport) bool TITCALL TLSRemoveCallbackW(const wchar_t* szFileName);
__declspec(dllexport) bool TITCALL TLSRemoveTable(const char* szFileName);
__declspec(dllexport) bool TITCALL TLSRemoveTableW(const wchar_t* szFileName);
__declspec(dllexport) bool TITCALL TLSBackupData(const char* szFileName);
__declspec(dllexport) bool TITCALL TLSBackupDataW(const wchar_t* szFileName);
__declspec(dllexport) bool TITCALL TLSRestoreData();
__declspec(dllexport) bool TITCALL TLSBuildNewTable(ULONG_PTR FileMapVA, ULONG_PTR StorePlace, ULONG_PTR StorePlaceRVA, LPVOID ArrayOfCallBacks, DWORD NumberOfCallBacks);
__declspec(dllexport) bool TITCALL TLSBuildNewTableEx(const char* szFileName, const char* szSectionName, LPVOID ArrayOfCallBacks, DWORD NumberOfCallBacks);
__declspec(dllexport) bool TITCALL TLSBuildNewTableExW(const wchar_t* szFileName, const char* szSectionName, LPVOID ArrayOfCallBacks, DWORD NumberOfCallBacks);
// TitanEngine.TranslateName.functions:
__declspec(dllexport) void* TITCALL TranslateNativeName(const char* szNativeName);
__declspec(dllexport) void* TITCALL TranslateNativeNameW(const wchar_t* szNativeName);
// TitanEngine.Handler.functions:
__declspec(dllexport) long TITCALL HandlerGetActiveHandleCount(DWORD ProcessId);
__declspec(dllexport) bool TITCALL HandlerIsHandleOpen(DWORD ProcessId, HANDLE hHandle);
__declspec(dllexport) void* TITCALL HandlerGetHandleName(HANDLE hProcess, DWORD ProcessId, HANDLE hHandle, bool TranslateName);
__declspec(dllexport) void* TITCALL HandlerGetHandleNameW(HANDLE hProcess, DWORD ProcessId, HANDLE hHandle, bool TranslateName);
__declspec(dllexport) long TITCALL HandlerEnumerateOpenHandles(DWORD ProcessId, LPVOID HandleBuffer, DWORD MaxHandleCount);
__declspec(dllexport) ULONG_PTR TITCALL HandlerGetHandleDetails(HANDLE hProcess, DWORD ProcessId, HANDLE hHandle, DWORD InformationReturn);
__declspec(dllexport) bool TITCALL HandlerCloseRemoteHandle(HANDLE hProcess, HANDLE hHandle);
__declspec(dllexport) long TITCALL HandlerEnumerateLockHandles(char* szFileOrFolderName, bool NameIsFolder, bool NameIsTranslated, LPVOID HandleDataBuffer, DWORD MaxHandleCount);
__declspec(dllexport) long TITCALL HandlerEnumerateLockHandlesW(const wchar_t* szFileOrFolderName, bool NameIsFolder, bool NameIsTranslated, LPVOID HandleDataBuffer, DWORD MaxHandleCount);
__declspec(dllexport) bool TITCALL HandlerCloseAllLockHandles(const char* szFileOrFolderName, bool NameIsFolder, bool NameIsTranslated);
__declspec(dllexport) bool TITCALL HandlerCloseAllLockHandlesW(const wchar_t* szFileOrFolderName, bool NameIsFolder, bool NameIsTranslated);
__declspec(dllexport) bool TITCALL HandlerIsFileLocked(const char* szFileOrFolderName, bool NameIsFolder, bool NameIsTranslated);
__declspec(dllexport) bool TITCALL HandlerIsFileLockedW(const wchar_t* szFileOrFolderName, bool NameIsFolder, bool NameIsTranslated);
// TitanEngine.Handler[Mutex].functions:
__declspec(dllexport) long TITCALL HandlerEnumerateOpenMutexes(HANDLE hProcess, DWORD ProcessId, LPVOID HandleBuffer, DWORD MaxHandleCount);
__declspec(dllexport) ULONG_PTR TITCALL HandlerGetOpenMutexHandle(HANDLE hProcess, DWORD ProcessId, const char* szMutexString);
__declspec(dllexport) ULONG_PTR TITCALL HandlerGetOpenMutexHandleW(HANDLE hProcess, DWORD ProcessId, const wchar_t* szMutexString);
__declspec(dllexport) long TITCALL HandlerGetProcessIdWhichCreatedMutex(const char* szMutexString);
__declspec(dllexport) long TITCALL HandlerGetProcessIdWhichCreatedMutexW(const wchar_t* szMutexString);
// TitanEngine.Injector.functions:
__declspec(dllexport) bool TITCALL RemoteLoadLibrary(HANDLE hProcess, const char* szLibraryFile, bool WaitForThreadExit);
__declspec(dllexport) bool TITCALL RemoteLoadLibraryW(HANDLE hProcess, const wchar_t* szLibraryFile, bool WaitForThreadExit);
__declspec(dllexport) bool TITCALL RemoteFreeLibrary(HANDLE hProcess, HMODULE hModule, const char* szLibraryFile, bool WaitForThreadExit);
__declspec(dllexport) bool TITCALL RemoteFreeLibraryW(HANDLE hProcess, HMODULE hModule, const wchar_t* szLibraryFile, bool WaitForThreadExit);
__declspec(dllexport) bool TITCALL RemoteExitProcess(HANDLE hProcess, DWORD ExitCode);
// TitanEngine.StaticUnpacker.functions:
__declspec(dllexport) bool TITCALL StaticFileLoad(const char* szFileName, DWORD DesiredAccess, bool SimulateLoad, LPHANDLE FileHandle, LPDWORD LoadedSize, LPHANDLE FileMap, PULONG_PTR FileMapVA);
__declspec(dllexport) bool TITCALL StaticFileLoadW(const wchar_t* szFileName, DWORD DesiredAccess, bool SimulateLoad, LPHANDLE FileHandle, LPDWORD LoadedSize, LPHANDLE FileMap, PULONG_PTR FileMapVA);
__declspec(dllexport) bool TITCALL StaticFileUnload(const char* szFileName, bool CommitChanges, HANDLE FileHandle, DWORD LoadedSize, HANDLE FileMap, ULONG_PTR FileMapVA);
__declspec(dllexport) bool TITCALL StaticFileUnloadW(const wchar_t* szFileName, bool CommitChanges, HANDLE FileHandle, DWORD LoadedSize, HANDLE FileMap, ULONG_PTR FileMapVA);
__declspec(dllexport) bool TITCALL StaticFileOpen(const char* szFileName, DWORD DesiredAccess, LPHANDLE FileHandle, LPDWORD FileSizeLow, LPDWORD FileSizeHigh);
__declspec(dllexport) bool TITCALL StaticFileOpenW(const wchar_t* szFileName, DWORD DesiredAccess, LPHANDLE FileHandle, LPDWORD FileSizeLow, LPDWORD FileSizeHigh);
__declspec(dllexport) bool TITCALL StaticFileGetContent(HANDLE FileHandle, DWORD FilePositionLow, LPDWORD FilePositionHigh, void* Buffer, DWORD Size);
__declspec(dllexport) void TITCALL StaticFileClose(HANDLE FileHandle);
__declspec(dllexport) void TITCALL StaticMemoryDecrypt(LPVOID MemoryStart, DWORD MemorySize, DWORD DecryptionType, DWORD DecryptionKeySize, ULONG_PTR DecryptionKey);
__declspec(dllexport) void TITCALL StaticMemoryDecryptEx(LPVOID MemoryStart, DWORD MemorySize, DWORD DecryptionKeySize, void* DecryptionCallBack);
__declspec(dllexport) void TITCALL StaticMemoryDecryptSpecial(LPVOID MemoryStart, DWORD MemorySize, DWORD DecryptionKeySize, DWORD SpecDecryptionType, void* DecryptionCallBack);
__declspec(dllexport) void TITCALL StaticSectionDecrypt(ULONG_PTR FileMapVA, DWORD SectionNumber, bool SimulateLoad, DWORD DecryptionType, DWORD DecryptionKeySize, ULONG_PTR DecryptionKey);
__declspec(dllexport) bool TITCALL StaticMemoryDecompress(void* Source, DWORD SourceSize, void* Destination, DWORD DestinationSize, int Algorithm);
__declspec(dllexport) bool TITCALL StaticRawMemoryCopy(HANDLE hFile, ULONG_PTR FileMapVA, ULONG_PTR VitualAddressToCopy, DWORD Size, bool AddressIsRVA, const char* szDumpFileName);
__declspec(dllexport) bool TITCALL StaticRawMemoryCopyW(HANDLE hFile, ULONG_PTR FileMapVA, ULONG_PTR VitualAddressToCopy, DWORD Size, bool AddressIsRVA, const wchar_t* szDumpFileName);
__declspec(dllexport) bool TITCALL StaticRawMemoryCopyEx(HANDLE hFile, DWORD RawAddressToCopy, DWORD Size, const char* szDumpFileName);
__declspec(dllexport) bool TITCALL StaticRawMemoryCopyExW(HANDLE hFile, DWORD RawAddressToCopy, DWORD Size, const wchar_t* szDumpFileName);
__declspec(dllexport) bool TITCALL StaticRawMemoryCopyEx64(HANDLE hFile, DWORD64 RawAddressToCopy, DWORD64 Size, const char* szDumpFileName);
__declspec(dllexport) bool TITCALL StaticRawMemoryCopyEx64W(HANDLE hFile, DWORD64 RawAddressToCopy, DWORD64 Size, const wchar_t* szDumpFileName);
__declspec(dllexport) bool TITCALL StaticHashMemory(void* MemoryToHash, DWORD SizeOfMemory, void* HashDigest, bool OutputString, int Algorithm);
__declspec(dllexport) bool TITCALL StaticHashFileW(const wchar_t* szFileName, char* HashDigest, bool OutputString, int Algorithm);
__declspec(dllexport) bool TITCALL StaticHashFile(const char* szFileName, char* HashDigest, bool OutputString, int Algorithm);
// TitanEngine.Engine.functions:
__declspec(dllexport) void TITCALL EngineUnpackerInitialize(const char* szFileName, const char* szUnpackedFileName, bool DoLogData, bool DoRealignFile, bool DoMoveOverlay, void* EntryCallBack);
__declspec(dllexport) void TITCALL EngineUnpackerInitializeW(const wchar_t* szFileName, const wchar_t* szUnpackedFileName, bool DoLogData, bool DoRealignFile, bool DoMoveOverlay, void* EntryCallBack);
__declspec(dllexport) bool TITCALL EngineUnpackerSetBreakCondition(void* SearchStart, DWORD SearchSize, void* SearchPattern, DWORD PatternSize, DWORD PatternDelta, ULONG_PTR BreakType, bool SingleBreak, DWORD Parameter1, DWORD Parameter2);
__declspec(dllexport) void TITCALL EngineUnpackerSetEntryPointAddress(ULONG_PTR UnpackedEntryPointAddress);
__declspec(dllexport) void TITCALL EngineUnpackerFinalizeUnpacking();
// TitanEngine.Engine.functions:
__declspec(dllexport) void TITCALL SetEngineVariable(DWORD VariableId, bool VariableSet);
__declspec(dllexport) bool TITCALL EngineCreateMissingDependencies(const char* szFileName, const char* szOutputFolder, bool LogCreatedFiles);
__declspec(dllexport) bool TITCALL EngineCreateMissingDependenciesW(const wchar_t* szFileName, const wchar_t* szOutputFolder, bool LogCreatedFiles);
__declspec(dllexport) bool TITCALL EngineFakeMissingDependencies(HANDLE hProcess);
__declspec(dllexport) bool TITCALL EngineDeleteCreatedDependencies();
__declspec(dllexport) bool TITCALL EngineCreateUnpackerWindow(const char* WindowUnpackerTitle, const char* WindowUnpackerLongTitle, const char* WindowUnpackerName, const char* WindowUnpackerAuthor, void* StartUnpackingCallBack);
__declspec(dllexport) void TITCALL EngineAddUnpackerWindowLogMessage(const char* szLogMessage);
__declspec(dllexport) bool TITCALL EngineCheckStructAlignment(DWORD StructureType, ULONG_PTR StructureSize);
// Global.Engine.Extension.Functions:
__declspec(dllexport) bool TITCALL ExtensionManagerIsPluginLoaded(const char* szPluginName);
__declspec(dllexport) bool TITCALL ExtensionManagerIsPluginEnabled(const char* szPluginName);
__declspec(dllexport) bool TITCALL ExtensionManagerDisableAllPlugins();
__declspec(dllexport) bool TITCALL ExtensionManagerDisablePlugin(const char* szPluginName);
__declspec(dllexport) bool TITCALL ExtensionManagerEnableAllPlugins();
__declspec(dllexport) bool TITCALL ExtensionManagerEnablePlugin(const char* szPluginName);
__declspec(dllexport) bool TITCALL ExtensionManagerUnloadAllPlugins();
__declspec(dllexport) bool TITCALL ExtensionManagerUnloadPlugin(const char* szPluginName);
__declspec(dllexport) void* TITCALL ExtensionManagerGetPluginInfo(const char* szPluginName);
#ifdef __cplusplus
}
#endif
#pragma pack(pop)
#endif /*TITANENGINE*/ |
Text | x64dbg-development/src/dbg/TitanEngine/TitanEngine.txt | TitanEngine
SDK References
Contents
Introduction to TitanEngine 12
Introduction to static unpackers . 13
Introduction to dynamic unpackers 14
Introduction to generic unpackers 15
Dynamic unpacker layout . 16
TitanEngine SDK References . 18
Unicode support . 19
Python support . 19
LUA support 19
Debugger module . 20
Debugger module constants . 21
StaticDisassembleEx function . 24
StaticDisassemble function . 25
*DisassembleEx function 26
*Disassemble function 27
StaticLengthDisassemble function 28
*LengthDisassembleEx function . 29
*LengthDisassemble function . 30
*InitDebug function 31
*InitDebugEx function . 32
*InitDLLDebug function 33
*AutoDebugEx function 34
SetErrorModel function 35
*IsFileBeingDebugged function 36
*AttachDebugger function 37
*DetachDebugger function . 38
*DetachDebuggerEx function . 39
*GetProcessInformation function . 40
*GetStartupInformation function . 41
*GetDebuggedDLLBaseAddress function . 42
*GetDebuggedFileBaseAddress function 43
*GetExitCode function 44
*DebugLoop function 45
*DebugLoopEx function 46
SetDebugLoopTimeOut function 47
SetNextDbgContinueStatus function 48
*StopDebug function 49
*ForceClose function 50
*SetBPXOptions function 51
*SetBPX function . 52
*SetBPXEx function . 53
*EnableBPX function . 55
*DisableBPX function 56
*IsBPXEnabled function 57
*DeleteBPX function . 58
*SafeDeleteBPX function 59
*SetAPIBreakPoint function 60
*DeleteAPIBreakPoint function 61
*SafeDeleteAPIBreakPoint function . 62
*SetMemoryBPX function . 63
*SetMemoryBPXEx function . 64
*RemoveMemoryBPX function . 65
*SetHardwareBreakPoint function . 66
*SetHardwareBreakPointEx function 67
*DeleteHardwareBreakPoint function 68
*GetUnusedHardwareBreakPointRegister function . 69
*RemoveAllBreakPoints function . 70
*CurrentExceptionNumber function 71
*ClearExceptionNumber function . 72
*GetDebugData function 73
*GetTerminationData function . 74
*GetContextDataEx function 75
*GetContextData function 76
*SetContextDataEx function . 77
*SetContextData function . 78
*GetContextFPUDataEx function 79
*SetContextFPUDataEx function. 80
*StepInto function 81
*StepOver function . 82
*SingleStep function . 83
*FindEx function . 84
*Find function . 85
*MatchPatternEx function 86
*MatchPattern function 87
*FillEx function 88
*Fill function 89
*PatchEx function . 90
*Patch function . 91
*ReplaceEx function 92
*Replace function . 94
*GetRemoteString function 96
*GetFunctionParameter function . 97
*GetJumpDestinationEx function . 99
*GetJumpDestination function . 100
*IsJumpGoingToExecuteEx function . 101
*IsJumpGoingToExecute function . 102
*SetCustomHandler function 103
SetCustomHandler CallBack details 104
*HideDebugger function . 106
*UnHideDebugger function 107
*GetPEBLocation function 108
**SetEngineVariable function . 109
Threader module 110
Threader module structures . 111
**ThreaderGetThreadInfo function 112
**ThreaderGetThreadData function 113
**ThreaderEnumThreadInfo function 114
**ThreaderPauseThread function 115
**ThreaderResumeThread function . 116
**ThreaderTerminateThread function . 117
**ThreaderPauseAllThreads function . 118
**ThreaderResumeAllThreads function . 119
**ThreaderPauseProcess function . 120
**ThreaderResumeProcess function 121
**ThreaderIsThreadStillRunning function 122
**ThreaderIsThreadActive function . 123
**ThreaderIsAnyThreadActive function . 124
**ThreaderIsExceptionInMainThread function 125
**ThreaderGetOpenHandleForThread function 126
**ThreaderSetCallBackForNextExitThreadEvent function . 127
**ThreaderCreateRemoteThreadEx function . 128
**ThreaderCreateRemoteThread function 129
**ThreaderInjectAndExecuteCodeEx function . 130
**ThreaderInjectAndExecuteCode function . 131
**ThreaderExecuteOnlyInjectedThreads function . 132
**ThreaderImportRunningThreadData function 133
TLS module 134
TLSBreakOnCallBack function . 135
TLSBreakOnCallBackEx function 136
TLSGrabCallBackData function 137
TLSRemoveCallback function 138
TLSRemoveTable function . 139
TLSBackupData function . 140
TLSRestoreData function. 141
TLSBuildNewTable function 142
TLSBuildNewTableEx function. 143
Librarian module . 144
Librarian module constants 145
Librarian module structures 145
*LibrarianSetBreakPoint function . 146
*LibrarianRemoveBreakPoint function . 147
*LibrarianGetLibraryInfo function 148
*LibrarianGetLibraryInfoEx function . 149
**LibrarianEnumLibraryInfo function . 150
Hooks module . 151
Hooks module constants. 152
Hooks module structures 152
HooksSafeTransition function . 153
HooksSafeTransitionEx function . 154
HooksDisableRedirection function 155
HooksDisableRedirectionsForModule function 156
HooksDisableIATRedirection function 157
HooksEnableRedirection function 158
HooksEnableRedirectionsForModule function . 159
HooksEnableIATRedirection function . 160
HooksRemoveRedirection function 161
HooksRemoveRedirectionsForModule function . 162
HooksRemoveIATRedirection function . 163
HooksInsertNewRedirection function . 164
HooksInsertNewIATRedirectionEx function 165
HooksInsertNewIATRedirection function . 166
HooksGetTrampolineAddress function . 167
HooksGetHookEntryDetails function 168
HooksScanModuleMemory function 169
HooksScanEntireProcessMemory function . 170
HooksScanEntireProcessMemoryEx function . 171
OEP Finder module . 172
FindOEPInit function . 173
FindOEPGenerically function 174
Process module . 175
*GetActiveProcessId function . 176
*EnumProcessesWithLibrary function 177
*RemoteLoadLibrary function 178
*RemoteFreeLibrary function . 179
*RemoteExitProcess function . 180
*TranslateNativeName function . 181
Dumper module 182
Dumper module constants . 183
Dumper module structures . 184
*DumpProcess function 186
*DumpProcessEx function 187
*DumpMemory function 188
*DumpMemoryEx function . 189
*DumpRegions function 190
*DumpRegionsEx function 191
*DumpModule function 192
*DumpModuleEx function 193
*PastePEHeader function . 194
ExtractSection function . 195
ResortFileSections function 196
FindOverlay function . 197
ExtractOverlay function 198
AddOverlay function . 199
CopyOverlay function 200
RemoveOverlay function 201
MakeAllSectionsRWE function 202
AddNewSectionEx function . 203
AddNewSection function 204
ResizeLastSection function . 205
SetSharedOverlay function . 206
GetSharedOverlay function. 207
DeleteLastSection function . 208
DeleteLastSectionEx function . 209
*GetPE32DataFromMappedFile function . 210
*GetPE32DataFromMappedFileEx function . 211
*GetPE32Data function . 212
*GetPE32DataEx function . 213
*SetPE32DataForMappedFile function . 214
*SetPE32DataForMappedFileEx function . 215
*SetPE32Data function . 216
*SetPE32DataEx function 217
*GetPE32SectionNumberFromVA function 218
*ConvertVAtoFileOffset function 219
*ConvertVAtoFileOffsetEx function 220
*ConvertFileOffsetToVA function . 221
*ConvertFileOffsetToVAEx function . 222
Importer module . 223
Importer module structures . 224
ImporterInit function 225
ImporterSetImageBase function . 226
ImporterAddNewDll function . 227
ImporterAddNewAPI function 228
ImporterAddNewOrdinalAPI function 229
ImporterGetLastAddedDLLName function . 230
ImporterGetAddedDllCount function . 231
ImporterGetAddedAPICount function 232
ImporterEnumAddedData function 233
ImporterEstimatedSize function . 234
ImporterCleanup function 235
ImporterExportIATEx function 236
ImporterExportIAT function 237
ImporterGetDLLName function 238
ImporterGetAPIName function . 239
ImporterGetAPINameEx function . 240
ImporterGetAPIOrdinalNumber function . 241
*ImporterGetRemoteAPIAddress function . 242
*ImporterGetRemoteAPIAddressEx function . 243
ImporterGetLocalAPIAddress function . 244
*ImporterGetDLLNameFromDebugee function . 245
*ImporterGetAPINameFromDebugee function 246
*ImporterGetAPIOrdinalNumberFromDebugee function 247
ImporterGetDLLIndexEx function . 248
ImporterGetDLLIndex function . 249
*ImporterGetRemoteDLLBase function 250
*ImporterGetRemoteDLLBaseEx function 251
ImporterIsForwardedAPI function 252
ImporterGetForwardedAPIName function . 253
ImporterGetForwardedAPIOrdinalNumber function . 254
ImporterGetForwardedDLLName function . 255
ImporterGetForwardedDLLIndex function . 256
ImporterFindAPIWriteLocation function 257
ImporterFindOrdinalAPIWriteLocation function 258
ImporterFindAPIByWriteLocation function 259
ImporterFindDLLByWriteLocation function 260
ImporterGetNearestAPIAddress function . 261
ImporterGetNearestAPIName function 262
ImporterMoveIAT function . 263
ImporterRelocateWriteLocation function . 264
ImporterSetUnknownDelta function 265
ImporterGetCurrentDelta function . 266
ImporterLoadImportTable function 267
ImporterCopyOriginalIAT function 268
ImporterMoveOriginalIAT function 269
ImporterAutoSearchIAT function 270
ImporterAutoSearchIATEx function 271
ImporterAutoFixIATEx function 272
ImporterAutoFixIAT function 274
Tracer module . 275
**TracerInit function 276
**TracerLevel1 function . 277
**HashTracerLevel1 function . 278
**TracerDetectRedirection function 279
**TracerFixKnownRedirection function . 280
**TracerFixRedirectionViaImpRecPlugin function 281
Realigner module 282
Realigner module structures and constants . 283
RealignPE function 285
RealignPEEx function . 286
FixHeaderCheckSum function . 287
WipeSection function 288
*IsFileDLL function 289
*IsPE32FileValidEx function 290
FixBrokenPE32FileEx function . 291
Relocater module 292
RelocaterInit function . 293
RelocaterCleanup function . 294
RelocaterAddNewRelocation function 295
RelocaterEstimatedSize function 296
RelocaterExportRelocationEx function . 297
RelocaterExportRelocation function . 298
RelocaterGrabRelocationTableEx function . 299
RelocaterGrabRelocationTable function . 300
RelocaterMakeSnapshot function 301
RelocaterCompareTwoSnapshots function 302
RelocaterWipeRelocationTable function 303
RelocaterRelocateMemoryBlock function 304
Exporter module . 305
ExporterInit function . 306
ExporterSetImageBase function . 307
ExporterCleanup function . 308
ExporterAddNewExport function 309
ExporterAddNewOrdinalExport function 310
ExporterGetAddedExportCount function . 311
ExporterEstimatedSize function 312
ExporterBuildExportTableEx function . 313
ExporterBuildExportTable function. 314
*ExporterLoadExportTable function . 315
Resourcer module . 316
ResourcerLoadFileForResourceUse function 317
ResourcerFreeLoadedFile function . 318
ResourcerExtractResourceFromFileEx function 319
ResourcerExtractResourceFromFile function . 320
ResourcerFindResource function 321
ResourcerFindResourceEx function 323
ResourcerEnumerateResource function . 325
ResourcerEnumerateResourceEx function . 326
Static module 327
Static module constants 328
StaticFileOpen function . 329
StaticFileGetContent function. 330
StaticFileClose function . 331
StaticFileLoad function 332
StaticFileUnload function 333
StaticMemoryDecrypt function 334
StaticMemoryDecryptEx function . 335
StaticSectionDecrypt function 336
StaticMemoryDecryptSpecial function . 337
StaticMemoryDecompress function . 338
StaticRawMemoryCopy function 339
StaticRawMemoryCopyEx function 340
StaticRawMemoryCopyEx64 function 341
StaticHashMemory function . 342
StaticHashFile function . 343
Handler module 344
Handler module constants 345
Handler module structures . 345
**HandlerGetActiveHandleCount function 346
**HandlerIsHandleOpen function 347
**HandlerGetHandleName function 348
**HandlerGetHandleDetails function . 349
**HandlerEnumerateOpenHandles function . 350
**HandlerIsFileLocked function 351
**HandlerCloseAllLockHandles function 352
**HandlerEnumerateLockHandles function . 353
**HandlerCloseRemoteHandle function 354
**HandlerEnumerateOpenMutexes function 355
**HandlerGetOpenMutexHandle function . 356
**HandlerGetProcessIdWhichCreatedMutex function 357
Extension module . 358
Guide to writing extensions for TitanEngine 359
Extension structure and function definitions . 359
**ExtensionManagerIsPluginLoaded function . 360
**ExtensionManagerIsPluginEnabled function 361
**ExtensionManagerDisablePlugin function 362
**ExtensionManagerDisableAllPlugins function 363
**ExtensionManagerEnablePlugin function . 364
**ExtensionManagerEnableAllPlugins function . 365
**ExtensionManagerUnloadPlugin function 366
**ExtensionManagerUnloadAllPlugins function 367
**ExtensionManagerGetPluginInfo function 368
Engine module 369
EngineCreateMissingDependencies function . 370
EngineFakeMissingDependencies function 371
EngineDeleteCreatedDependencies function . 372
EngineCreateUnpackerWindow function . 373
EngineAddUnpackerWindowLogMessage function 374
Engine unpacker simplification module 375
Engine simplification module constants . 376
EngineUnpackerInitialize function 377
EngineUnpackerSetBreakCondition function . 378
EngineUnpackerSetEntryPointAddress function 381
EngineUnpackerFinalizeUnpacking function 382
TitanEngine 2.0.1 - history 383
TitanEngine 2.0.2 - history 384
TitanEngine 2.0.3 - history 385
License . 386
Introduction to TitanEngine
One of the greatest challenges of modern reverse engineering is taking apart and analyzing
software protections. During the last decade a vast number of such shell modifiers have appeared.
Software Protection as an industry has come a long way from simple encryption that protects
executable and data parts to current highly sophisticated protections that are packed with tricks aiming
at slow down in the reversing process. Number of such techniques increases every year. Hence we need
to ask ourselves, can we keep up with the tools that we have?
Protections have evolved over the last few years, but so have the reverser’s tools. Some of those
tools are still in use today since they were written to solve a specific problem, or at least a part of it. Yet
when it comes to writing unpackers this process hasn’t evolved much. We are limited to writing our own
code for every scenario in the field.
We have designed TitanEngine in such fashion that writing unpackers would mimic analyst’s
manual unpacking process. Basic set of libraries, which will later become the framework, had the
functionality of the four most common tools used in the unpacking process: debugger, dumper,
importer and realigner. With the guided execution and a set of callbacks these separate modules
complement themselves in a manner compatible with the way any reverse engineer would use his tools
of choice to unpack the file. This creates an execution timeline which parries the protection execution
and gathers information from it while guided to the point from where the protection passes control to
the original software code. When that point is reached file gets dumped to disk and fixed so it resembles
the original to as great of a degree as possible. In this fashion problems of making static unpackers have
been solved. Yet static unpacking is still important due to the fact that it will always be the most secure,
and in some cases, fastest available method. That is why we will discuss both static and dynamic
unpackers. We will also see into methods of making generic code to support large number of formats
without knowing the format specifics.
TitanEngine can be described as Swiss army knife for reversers. With its 400 functions, every
reverser tool created to this date has been covered through its fabric. Best yet, TitanEngine can be
automated. It is suitable for more than just file unpacking. TitanEngine can be used to make new tools
that work with PE files. Support for both x86 and x64 systems make this framework the only framework
supporting work with PE32+ files. As such, it can be used to create all known types of unpackers. Engine
is open source making it open to modifications that will only ease its integration into existing solutions
and would enable creation of new ones suiting different project needs.
TitanEngine SDK contains:
. Integrated x86/x64 debugger
. Integrated x86/x64 disassembler
. Integrated memory dumper
. Integrated import tracer & fixer
. Integrated relocation fixer
. Integrated file realigner
. Functions to work with TLS, Resources, Exports,…
Introduction to static unpackers
Most of basic unpackers are of the static variety. We take this observation very loosely as this
depends on the complexity of the format being unpacked. In most cases writing such unpackers is easy
because the format being unpacked is a simple one or more commonly referred to as a crypter.
This kind of PE file protectors (because packing is a very basic form of protection) have a simple
layout that only encrypts the code and resources, and in some cases even takes the role of the import
loader. Even if we encounter the most advanced representative of this shell protection type it won’t
differ much from its most basic protection model. Which is, no modification to the PE section layout
other than adding a new section for the crypter code and encryption of the entire code and resource
sections with possible import loader role for the crypter stub. Since these modifications don’t impact the
file in such way that major file reconstruction should be done writing static unpackers also has its
general model. This is, get the needed data for decryption of the encrypter parts and reconstruction of
the import table followed by removing the crypter section.
With the slight variations of the guidelines described above this could be considered as the basic
crypter model. These variations could be variations in the position of the crypter code, way it handles
imports and some protection shell specifics such as: protected entry point, import redirections or
eliminations, code splices, code markers, etc.
However static unpackers can be used for a more difficult use cases which require the full file
reconstruction in order to complete the unpacking process. In such cases static unpacking can be used
and it’s recommended only if the security is of the vital importance. These cases most commonly require
the identification of the compression algorithm used and its adaptation to our own code. This code
ripping must be done very carefully and it requires the full understanding of the algorithm which
decompresses the code. There are a few standard compression algorithms in use by most PE shells so
we can use this to create our own database of corresponding decompression algorithms to ease the
unpacker writing process. No matter which path we choose we must always check whether or not the
algorithm has changed since this is one way to tamper with the unpackers. Dynamic unpackers are
resilient to such changes.
Original Entry Point
jump
Import
resolving
Section
decryption
Internal data
decryption
Overlay
STUB
Sections
(encrypted)
PE
DOS
Figure (1) Crypter file & execution layout
Introduction to dynamic unpackers
Most common unpacker type is dynamic. This model is widely used because it is easy to
implement and resilient to minor changes in packing shell decryption and decompression algorithms.
But due to the fact that files do execute during unpacking process this method must be conducted with
great care about system security. There is a risk of files being executed outside the unpacking process or
even stuck in infinite loops. This can and must be avoided by the unpacker implementation. Most logical
choice is creation of internal sandbox for the unpacking process itself.
Dynamic unpacking is used on specific shell modifier types. These types have a more complex
layout and file content is commonly not only encrypted but compressed too. To avoid heavy coding to
allow what is basically recompiling of the file we execute it to the original entry point which is the first
instruction of the code before the file was protected. Even though all shells can be dynamically
unpacked this kind of unpacking is only used on packers, protectors, bundlers and hybrids.
Basic layout of such shell modifiers includes compression of the file sections and vital data and
optionally their protection by encryption. Stub is usually located in the last section and section layout
before packing is either preserved or all sections are merged into one. First case usually implies that
each section still contains its original data only compressed while the second one implies a physically
empty section which only serves as virtual memory space reserve. In this second case compressed data
is usually stored inside stub section and upon its decompression returned to original location.
When creating dynamic unpackers it is important to always keep control over executing sample.
At no point this control must be left in a gray area in which we are uncertain what will occur.
Furthermore unpacking must be conducted inside safe environment so software sandbox must be
designed. This along with multiple checks before and during the unpacking process ensures that we
retain maximum control during this risky process. This kind of unpackers has a standard model which
will be described in Dynamic unpacker layout. That kind of unpacker is a basic unpacker type that can be
created with TitanEngine whose largest number of functions is dedicated to writing.
Original Entry Point
jump
Import Resolving &
TLS callback execution
Relocation
to new base
Section
decompression
Overlay
STUB
Sections
(compressed)
PE
DOS
Figure (2) Packer file & execution layout
Introduction to generic unpackers
Most complex way of creating unpackers is creating generic unpackers. Totally opposite from
the other two cases when creating generic unpackers you don’t need to worry about extracting a good
enough patter on code segment to create a good signature for your unpacker. Quite simply because
these unpackers don’t care about the shell specifics, they only care about their overall behavior which is
common for shell modifiers of the same group. This means that there can never be a general generic
unpacker but several wide range generic unpackers targeting specific behavior groups.
Here we will focus only on generic unpacking of packed executables and present a wide generic
algorithm targeting these shell modifiers. Major challenge here is retaining as much control as possible
without slowing down the unpacking process drastically. Slowdown occurs because we use memory
breakpoints to monitor packed shell access to executable sections. If we reset the memory breakpoint
each time the packer accesses the section we will have a major speed impact and if we don’t we reset
we risk not to catch the original entry point jump event and even let file execute. There are a few ways
to do this but one is most common.
Figure (3) Generic unpacker algorithm layout
Code sections
SetMemoryBPX
SetMemoryBPX
SetMemoryBPX
GetPEData
Hash
test
Your code
1. EIP inside sections
2. Already written to
3. Hash has changed
4. Not a simple redirection
Generic unpackers commonly use WaitForDebugEvent timeouts to reset the breakpoints once
one such breakpoint has been hit. Memory breakpoints can be hit for three reasons: when memory is
read from, written to or executing. Since we only place memory breakpoints on places where we expect
entry point to be we are only interested in execution case. To check whether or not that memory is
executing we just check the EIP register to see if it matches our region. If it does that memory is
executing. However we can set a breakpoint on the section which contains packer code. That is why we
will track if the section has been written to prior its execution. If it has been written to it is highly
possible that the entry point resides there and that we are at the right spot. We can track writing with
memory breakpoints but one can also check that section hash just to make sure that the data has
actually changed. Last check that should be performed before determining that we are sitting on a
possible entry point is a check for known simple redirections that packers such as ASPack use to fool
generic algorithms. Once we verify this last thing we can be fairly certain that we have found our entry
point. To finish the unpacking we must dump and process imports which can be done with TitanEngine.
StopDebug();
Finalize unpacking
Dynamic unpacker layout
In order to use the TitanEngine SDK you must know the order in which APIs must be called. The
order is fairly strict, and the layout of your unpacker will always be pretty much the same. Every
unpacker starts with debugging and setting a breakpoint on your target's entry point. After this you
must debug the program by running it until you get to the IAT filling code. This code uses LoadLibrary or
GetModuleHandle API to load the dependent .dll files and GetProcAddress to find the locations of the
necessary APIs. When this is done you need to break on the Original Entry Point (OEP), dump the file and
paste imports to it.
To start debugging you must first find the OEP address. To do this you can call GetPE32Data API and
load the ImageBase and OriginalEntryPoint data. The sum of these two values is the address of the entry
point. When this is done, initialize debugging by calling the InitDebug API. This API creates the debugged
process but it does not start the actual debugging. In this suspended state call SetBpx to set the main
breakpoint at OEP. This breakpoint's callback will be called as soon as the debugged process finishes
loading. To get the debugging process to this point you must call the DebugLoop API. After it is called,
the debugger takes over the debugging process. The only way to control the debugging process from
this point is by callback procedures. Callbacks are set with all types of breakpoints. So if you set the
breakpoint at OEP call the DebugLoop API first callback which will be called is the callback for original
entry point breakpoint. Use that callback to set all the other breakpoints.
The best way to find where to set the breakpoint is by using the Find API. It will tell you the location
at which your search pattern is found. If the packer for which you are writing an unpacker is single
layered, you can set all the breakpoints in the first or before the first callback, the one at the original
entry point. To get all the data needed to fix the IAT you need to set two or three breakpoints. First at
LoadLibrary or GetModuleHandle API call, second at GetProcAddress call (use two if the packer calls
GetProcAddress at two places for string API locating and ordinal API locating). But before you can
actually call any of the importer functions in order to collect the IAT data you must first call the
ImporterInit API to initialize the importer.
After you do this and set the breakpoints you must code the breakpoint callbacks to get the IAT data.
In the LoadLibrary/GetModuleHandle callbacks, you call ImporterAddNewDll API. One of its parameters
is the string which holds the name of the .dll file which is loaded. This data location if located in a
register or in a specific memory address. To get this data call the GetContextData API. If the data is in a
location on which the string is located, and not an ordinal number, you must call the
ReadProcessMemory API to read the .dll name from the debugged processes. Then you can add the new
.dll to importer engine. Note that once you add the .dll by calling the ImporterAddNewDll API all calls to
ImporterAddNewAPI add APIs to last added .dll file. APIs are added by calling the ImporterAddNewAPI
the same way you add a new .dll to the importer engine. But unlike ImporterAddNewDll API, you must
specify the location on which the API pointer will be stored. This is a memory location to which the
pointer loaded with GetProcAddress API is written. After you collect all the data needed to fill in the IAT,
the unpacking is pretty much done.
Now you need to load the unpacked file's OEP (this depends on the packer code) and dump the
debugged process with DumpProcess. After this you can use the AddNewSection API to make space for
the IAT, which needs to be pasted to the dump file. To know just how much space you need, use the
ImporterEstimatedSize API. Finally the IAT is exported to a new section by calling the ImporterExportIAT
API. Optionally you can realign the file and then stop the debugging process by calling the StopDebug
API (if you don't stop the debugging target will keep running). This terminates the debugged process and
your program's execution resumes after the call to DebugLoop.
StopDebug();
Entry point
RealignPE
ExportRelocation
ImporterExportIAT
PastePEHeader
DumpProcess
CompareTwoSnapshots
RelocaterMakeSnaphot
ImporterAddNewAPI
ImporterAddNewDLL
RelocaterMakeSnaphot
Code just after
Packer segment
Relocation code
Code just before
Relocation fix
GetProcAddress
LoadLibrary
Gather import data
Import fix
DebugLoop();
SetBPX
InitDebug
Unpacking init
GetPEData
SetBPX
maintitan.png
TitanEngine SDK References
Unicode support
Unicode support has been added to TitanEngine with version 2.0.2. However Unicode functions
are not documented in this document because changes between function versions that use ASCII or
UNICODE strings as input/output parameters are minor. Unicode functions are defined in the SDK and
can be used normally. Such functions can be easily recognized by the appendix “W” which they have. For
specific function definitions please refer to the SDK header files.
Python support
Python support has been added to TitanEngine with version 2.0.3. To use the python SDK
include teSDK.py with your project. SDK wrapper around the engine uses the default python libraries
which ship with Python 2.6.5.
LUA support
LUA support has been added to TitanEngine with version 2.0.3. To use the LUA SDK include
SDK.lua with your project. SDK wrapper around the engine uses Alien LUA module version 0.51. To be
able to use the LUA SDK alien module that comes with LUA 5.1.4 must be updated. We suggest that you
use LuaRocks for a simple alien update procedure.
Debugger module
Debugger module's functions are used for process debugging, disassembling, accessing context and
manipulating memory.
Debugger module constants
Constants used by: SetBPXEx function, SetHardwareBreakPoint function, SetHardwareBreakPointEx
function, DeleteHardwareBreakPoint function, GetContextDataEx function,
GetContextData function, SetContextDataEx function and SetContextData function
#define UE_EAX 1
#define UE_EBX 2
#define UE_ECX 3
#define UE_EDX 4
#define UE_EDI 5
#define UE_ESI 6
#define UE_EBP 7
#define UE_ESP 8
#define UE_EIP 9
#define UE_EFLAGS 10
#define UE_DR0 11
#define UE_DR1 12
#define UE_DR2 13
#define UE_DR3 14
#define UE_DR6 15
#define UE_DR7 16
#define UE_RAX 17
#define UE_RBX 18
#define UE_RCX 19
#define UE_RDX 20
#define UE_RDI 21
#define UE_RSI 22
#define UE_RBP 23
#define UE_RSP 24
#define UE_RIP 25
#define UE_RFLAGS 26
#define UE_R8 27
#define UE_R9 28
#define UE_R10 29
#define UE_R11 30
#define UE_R12 31
#define UE_R13 32
#define UE_R14 33
#define UE_R15 34
#define UE_CIP 35 // Generic, on x86 = EIP and on x64 = RIP
#define UE_CSP 36 // Generic, on x86 = ESP and on x64 = RSP
Constants used by: SetBPXEx function
#define UE_CMP_NOCONDITION 0
#define UE_CMP_EQUAL 1
#define UE_CMP_NOTEQUAL 2
#define UE_CMP_GREATER 3
#define UE_CMP_GREATEROREQUAL 4
#define UE_CMP_LOWER 5
#define UE_CMP_LOWEROREQUAL 6
#define UE_CMP_REG_EQUAL 7
#define UE_CMP_REG_NOTEQUAL 8
#define UE_CMP_REG_GREATER 9
#define UE_CMP_REG_GREATEROREQUAL 10
#define UE_CMP_REG_LOWER 11
#define UE_CMP_REG_LOWEROREQUAL 12
#define UE_CMP_ALWAYSFALSE 13
Constants used by: SetBPX function, SetBPXEx function, SetMemoryBPX function, SetMemoryBPXEx
function and SetHardwareBreakPoint function
#define UE_BREAKPOINT 0
#define UE_SINGLESHOOT 1
#define UE_HARDWARE 2
#define UE_MEMORY 3
#define UE_MEMORY_READ 4
#define UE_MEMORY_WRITE 5
#define UE_BREAKPOINT_TYPE_INT3 0x10000000
#define UE_BREAKPOINT_TYPE_LONG_INT3 0x20000000
#define UE_BREAKPOINT_TYPE_UD2 0x30000000
#define UE_HARDWARE_EXECUTE 4
#define UE_HARDWARE_WRITE 5
#define UE_HARDWARE_READWRITE 6
#define UE_HARDWARE_SIZE_1 7
#define UE_HARDWARE_SIZE_2 8
#define UE_HARDWARE_SIZE_4 9
#define UE_APISTART 0
#define UE_APIEND 1
Constants used by: SetCustomHandler function
#define UE_CH_BREAKPOINT 1
#define UE_CH_SINGLESTEP 2
#define UE_CH_ACCESSVIOLATION 3
#define UE_CH_ILLEGALINSTRUCTION 4
#define UE_CH_NONCONTINUABLEEXCEPTION 5
#define UE_CH_ARRAYBOUNDSEXCEPTION 6
#define UE_CH_FLOATDENORMALOPERAND 7
#define UE_CH_FLOATDEVIDEBYZERO 8
#define UE_CH_INTEGERDEVIDEBYZERO 9
#define UE_CH_INTEGEROVERFLOW 10
#define UE_CH_PRIVILEGEDINSTRUCTION 11
#define UE_CH_PAGEGUARD 12
#define UE_CH_EVERYTHINGELSE 13
#define UE_CH_CREATETHREAD 14
#define UE_CH_EXITTHREAD 15
#define UE_CH_CREATEPROCESS 16
#define UE_CH_EXITPROCESS 17
#define UE_CH_LOADDLL 18
#define UE_CH_UNLOADDLL 19
#define UE_CH_OUTPUTDEBUGSTRING 20
Constants used by: RemoveAllBreakPoints function
#define UE_OPTION_REMOVEALL 1
#define UE_OPTION_DISABLEALL 2
#define UE_OPTION_REMOVEALLDISABLED 3
#define UE_OPTION_REMOVEALLENABLED 4
Constants used by: SetEngineVariable function
#define UE_ENGINE_ALOW_MODULE_LOADING 1
#define UE_ENGINE_AUTOFIX_FORWARDERS 2
#define UE_ENGINE_PASS_ALL_EXCEPTIONS 3
#define UE_ENGINE_NO_CONSOLE_WINDOW 4
#define UE_ENGINE_BACKUP_FOR_CRITICAL_FUNCTIONS 5
#define UE_ENGINE_RESET_CUSTOM_HANDLER 7
#define UE_ENGINE_CALL_PLUGIN_DEBUG_CALLBACK 8
Constants used by: HideDebugger function
#define UE_HIDE_BASIC 1
Constants used by: SetBPXOptions function
#define UE_BREAKPOINT_INT3 1
#define UE_BREAKPOINT_LONG_INT3 2
#define UE_BREAKPOINT_UD2 3
StaticDisassembleEx function
The StaticDisassembleEx function is used to disassemble data from the context of the process using the
SDK. This is only used to disassemble instructions locally, meaning code inside your executable and its
memory context.
Syntax
void* __stdcall StaticDisassembleEx(
ULONG_PTR DisassmStart,
LPVOID DisassmAddress
);
Parameters
DisassmStart
[in] Used only to help with disassembling relative instructions such as jumps. This
variable should be set to the address you are disassembling. If data was copied from
a remote process, make sure you use that address. Size of this variable varies: on
x86 its 4 bytes and on x64 its 8 bytes. Therefore it can also be declared as void*
DisassmAddress
[in] Pointer to the address where the instruction to be disassembled is located. Only the
first instruction in that block will be disassembled.
Return value
If disassembly succeeds, StaticDisassembleEx returns a pointer to the disassembled instruction
string, otherwise, it returns NULL.
Remarks
diStorm64 is used for instruction disassembling.
Example
None.
StaticDisassemble function
The StaticDisassemble function is used to disassemble data from the context of the process using the
SDK. This is only used to disassemble instructions locally, meaning code inside your executable and its
memory context.
Syntax
void* __stdcall StaticDisassemble(
LPVOID DisassmAddress
);
Parameters
DisassmAddress
[in] Pointer to the address where the instruction to be disassembled is located. Only the
first instruction in that block will be disassembled. If you use StaticDisassemble to
disassemble relative instructions, such as jumps, it will assume that instructions
resides at DiassmAddress and will disassemble them as such. If you need to
disassemble instructions that have been moved, use StaticDisassembleEx.
Return value
If disassembly succeeds, StaticDisassemble returns a pointer to the disassembled instruction
string, otherwise, it returns NULL.
Remarks
diStorm64 is used for instruction disassembling.
Example
None.
DisassembleEx function
The function DisassembleEx disassembles data from the context of any running process, as long as you
have access to the process.
Syntax
void* __stdcall DisassembleEx(
HANDLE hProcess,
LPVOID DisassmAddress,
bool ReturnInstructionType
);
Parameters
hProcess
[in] Handle of the process whose memory will be disassembled.
DisassmAddress
[in] Pointer to address of the remote process containing the instruction to disassemble.
Only the first instruction in that block will be disassembled.
ReturnInstructionType
[in] Boolean switch specifying whether to return the disassembled string or the
instruction type of that string. For example is the disassembled instruction is: MOV
EAX,EBX and this switch is set to TRUE DisassembleEx returns only the string MOV. If
this switch is set to FALSE, DisassembleEx returns the entire disassembled string.
Return value
If DisassembleEx succeeds, it returns a pointer to either the disassembled instruction string or
the string's instruction type. If it fails, it returns NULL.
Remarks
diStorm64 is used for instruction disassembling.
Example
None.
Disassemble function
The function Disassemble disassembles data from the context of currently debugged process. This
function will fail if no process is being debugged or the specified address doesn’t exist inside debugged
process.
Syntax
void* __stdcall Disassemble(
LPVOID DisassmAddress,
);
Parameters
DisassmAddress
[in] Pointer to address of the remote process containing the instruction to disassemble.
Only the first instruction in that block will be disassembled.
Return value
If it succeeds, Disassemble returns a pointer to disassembled instruction string, otherwise it
returns NULL.
Remarks
diStorm64 is used for instruction disassembling.
Example
None.
StaticLengthDisassemble function
The function StaticLengthDisassemble gets the length, in bytes, of a disassembled instruction from the
context of a process, using the SDK. This is only used to disassemble instructions locally, meaning code
inside your executable and its memory context.
Syntax
void* __stdcall StaticLengthDisassemble(
LPVOID DisassmAddress
);
Parameters
DisassmAddress
[in] Pointer to memory which holds instruction whose size in bytes will be determined.
Only the first instruction in that block will be disassembled.
Return value
StaticLengthDisassemble returns the size of disassembled instruction string or NULL if
disassemble fails.
Remarks
diStorm64 is used for instruction disassembling.
Example
None.
LengthDisassembleEx function
The function LengthDisassembleEx gets the length, in bytes, of a disassembled instruction from the
context of any running process, as long as you have the access to the process.
Syntax
long __stdcall LengthDisassembleEx(
HANDLE hProcess,
LPVOID DisassmAddress
);
Parameters
hProcess
[in] Handle of the process whose memory will be disassembled.
DisassmAddress
[in] Pointer to the address of the instruction whose size you want to know. Only the first
instruction in that block will be disassembled.
Return value
If it succeeds, LengthDisassembleEx returns the size of disassembled instruction string. If it fails,
it returns either NULL or minus one.
Remarks
diStorm64 is used for instruction disassembling.
Example
None.
LengthDisassemble function
The function LengthDisassemble gets the length, in bytes, of the disassembled instruction from the
context of the process currently being debugged. This function fails if no process is being debugged or if
the specified address doesn’t exist inside the debugged process.
Syntax
long __stdcall LengthDisassembleEx(
LPVOID DisassmAddress
);
Parameters
DisassmAddress
[in] Pointer to the address of the instruction whose size you want to know. Only the first
instruction in that block will be disassembled.
Return value
If it succeeds, LengthDisassemble returns the size of the disassembled instruction string. If it
fails, it returns either NULL or minus one.
Remarks
diStorm64 is used for instruction disassembling.
Example
None.
InitDebug function
The InitDebug function is used to initialize the debugging process. This function is always used first and
it is creating a process which will be debugged.
Syntax
void* __stdcall InitDebug(
char* szFileName,
char* szCommandLine,
char* szCurrentFolder
);
Parameters
szFileName
[in] Pointer to the full path of the file to debug.
szCommandLine
[in] Pointer to a command line parameter string that is passed to the created process.
szCurrentFolder
[in] Pointer to string which will be passed to CreateProcess API during the process
creation.
Return value
InitDebug returns the pointer to PROCESS_INFORMATION structure or NULL if it fails.
Remarks
None.
Example
None.
InitDebugEx function
The InitDebugEx function is used to initialize the debugging process. This function is always used first. It
creates a process which will be debugged.
Syntax
void* __stdcall InitDebug(
char* szFileName,
char* szCommandLine,
char* szCurrentFolder,
LPVOID EntryCallBack
);
Parameters
szFileName
[in] Pointer to the full path of the file to debug.
szCommandLine
[in] Pointer to a command line parameter string that is passed to the created process.
szCurrentFolder
[in] Pointer to string which will be passed to CreateProcess API during the process
creation.
EntryCallBack
[in] Pointer to the callback function to call when the application reaches the file entry
point. This is equal to setting breakpoint at the file entry point.
Return value
If it succeeds, InitDebugEx returns a pointer to a PROCESS_INFORMATION structure, otherwise
it returns NULL.
Remarks
None.
Example
None.
InitDLLDebug function
The InitDLLDebug function is used to initialize the DLL debugging process. This function is always used
first and it is creating a process which will be debugged and it is specialized only for debugging DLL files.
This function automatically loads any DLL loaders required to make DLL debugging work.
Syntax
void* __stdcall InitDLLDebug(
char* szFileName,
bool ReserveModuleBase,
char* szCommandLine,
char* szCurrentFolder,
LPVOID EntryCallBack
);
Parameters
szFileName
[in] Pointer to the full path of the file to debug.
ReserveModuleBase
[in] Boolean variable that specifies whether or not to load a debugged DLL on a non-
default image base.
szCommandLine
[in] Pointer to string which will be passed to the created process as a command line
parameter.
szCurrentFolder
[in] Pointer to string which will be passed to CreateProcess API during the process
creation.
EntryCallBack
[in] Pointer to a callback function to call when the application reaches the file entry
point. This is equal to setting a breakpoint at the file entry point.
Return value
If it succeeds, InitDLLDebug returns a pointer to the PROCESS_INFORMATION structure,
otherwise it returns NULL.
AutoDebugEx function
AutoDebugEx initializes the debugging process for both executables and DLLs. This function is always
used first. It creates a process which will be debugged
Syntax
void __stdcall AutoDebugEx(
char* szFileName,
bool ReserveModuleBase,
char* szCommandLine,
char* szCurrentFolder,
DWORD TimeOut,
LPVOID EntryCallBack
);
Parameters
szFileName
[in] Pointer to the full path of the file to debug.
ReserveModuleBase
[in] Boolean variable specifying whether or not to load debugged DLL on non default
image base.
szCommandLine
[in] Pointer to string which will be passed to created process as a command line
parameter.
szCurrentFolder
[in] Pointer to string which will be passed to CreateProcess API during the process
creation.
TimeOut
[in] Value which will be passed to Windows WaitForDebugEvent API.
EntryCallBack
[in] [in] Pointer to a callback function to call when the application reaches the file entry
point. This is equal to setting a breakpoint at the file entry point.
Remarks
Since debugging is performed in second thread, any calls to the SendMessage Windows API will
cause the program to freeze. Keep this in mind while using this function.
SetErrorModel function
The SetErrorModel function is used to change the way that Windows loader behaves errors found while
loading PE files. If you chose not to display error messages no warnings about broken or invalid files you
try to debug will be shown to the user.
Syntax
void __stdcall SetErrorModel(
bool DisplayErrorMessages
);
Parameters
DisplayErrorMessages
[in] Boolean switch which tells the TitanEngine should Windows loader errors be
displayed or not.
Return value
None.
Remarks
None.
IsFileBeingDebugged function
The IsFileBeingDebugged function is used to determine if a file is currently being debugged or not.
Syntax
bool __stdcall IsFileBeingDebugged();
Parameters
None.
Return value
Boolean switch indicating whether or not a file is being debugged.
Remarks
None.
AttachDebugger function
The AttachDebugger function is used to initialize the debugging process by attaching to already running
process. Your program will not return from the call to AttachDebugger before the debugging is finished
and debugged application has been terminated.
Syntax
void __stdcall AttachDebugger(
DWORD ProcessId,
bool KillOnExit,
LPVOID DebugInfo,
LPVOID CallBack
);
Parameters
ProcessId
[in] Process ID of the running process which can be acquired with Windows API.
KillOnExit
[in] Boolean variable specifying whether or not to terminate the process to which the
debugger was attached when debugging is complete.
DebugInfo
[out] Pointer to the PROCESS_INFORMATION structure to fill when the process is
attached.
CallBack
[in] Pointer to the callback function to call when the first system breakpoint is reached.
Return value
None.
Remarks
None.
DetachDebugger function
Please use DetachDebuggerEx instead. The DetachDebugger function detaches the debugger from a
debugged process. DetachDebugger detaches the debugger from a running process, allowing the
process to continue running. All exceptions must be processed before detaching. Since exception
processing can’t be done from any TitanEngine callback, this function should NOT be used.
Syntax
bool __stdcall DetachDebugger(
DWORD ProcessId
);
Parameters
ProcessId
[in] Process ID of the process from which you want to detach. The ID can be acquired
from the Windows API or internal structures.
Return value
Returns TRUE when detachment is complete, and FALSE if there is an error.
Remarks
This function only works on Window 2003/XP and later.
Example
None.
DetachDebuggerEx function
The DetachDebuggerEx function detaches the debugger from a debugged process, leaving the process
running. DetachDebuggerEx ensures that all exceptions are processed before detaching.
Syntax
bool __stdcall DetachDebuggerEx(
DWORD ProcessId
);
Parameters
ProcessId
[in] Process ID of the process from which you want to detach. The ID can be acquired
from the Windows API or internal structures.
Return value
Returns TRUE when detachment is complete, and FALSE if there is an error.
Remarks
This function only works on Window 2003/XP and later.
Example
None.
GetProcessInformation function
The GetProcessInformation function retrieves a pointer to the PROCESS_INFORMATION structure that
contains the initialization data for the debugged process.
Syntax
void* __stdcall GetProcessInformation();
Parameters
None.
Return value
Returns a pointer to the PROCESS_INFORMATION structure, and therefore can be declared as
LPPROCESS_INFORMATION.
Remarks
This data can only be retrieved from an active process.
Example
None.
GetStartupInformation function
The GetStartupInformation function is used to retrieve the pointer to initialization data for the
debugged process.
Syntax
void* __stdcall GetStartupInformation();
Parameters
None.
Return value
Returns pointer to a STARTUPINFOA structure, and can also be declared as LPSTARTUPINFOA.
Remarks
This data can only be retrieved from an active process.
Example
None.
GetDebuggedDLLBaseAddress function
GetDebuggedDLLBaseAddress retrieves the base address on which the debugged DLL file was loaded.
This function is needed for DLL debugging, because a DLL may not be loaded on its default image base,
for example, if the default base address is reserved for some other module or ASLR file.
Syntax
long long __stdcall GetDebuggedDLLBaseAddress();
Parameters
None.
Return value
This function returns a pointer to the base address on which debugged DLL file was loaded. It
can also be declared as void*.
Remarks
This data can only be retrieved from an active process whose DLL is being debugged.
Example
None.
GetDebuggedFileBaseAddress function
GetDebuggedFileBaseAddress retrieves the base address on which the debugged file is loaded. It
retrieves the base address on which the debugged file was loaded. This function is needed for file
debugging, because a file may not be loaded on its default image base, for example, if the default base
address is reserved for some other module or ASLR file. Note, this function retrieves the base address of
the main module, so if you are debugging a DLL file, it will return the base address of the DLL loader.
Syntax
long long __stdcall GetDebuggedFileBaseAddress();
Parameters
None.
Return value
This function returns a pointer the base address at which debugged file resides. It can also be
declared as void*.
Remarks
Process must be active to retrieve this data.
Example
None.
GetExitCode function
GetExitCode retrieves a process exit code.
Syntax
long __stdcall GetExitCode();
Parameters
None.
Return value
This function returns the exit code provided by the debugged file upon its termination.
Remarks
The process must be terminated to retrieve this data.
Example
None.
DebugLoop function
DebugLoop starts the debugging process. Always call this function or DebugLoopEx after initializing the
debugger with one of the initialization functions. Set at least one breakpoint before running the
debugged or the application whose process is being debugged will run. DebugLoop will not return until
the debugger is finished and the debugged application has been terminated.
Syntax
void __stdcall DebugLoop();
Parameters
None.
Return value
None.
Remarks
None.
Example
None.
DebugLoopEx function
The DebugLoopEx function is used to start the debugging process. This function is always used after
debugger initialization. Before running the debugged process makes sure you have at least one
breakpoint set otherwise the application will run. Your program will not return from the call to
DebugLoopEx before the debugging is finished and debugged application has been terminated.
Syntax
void __stdcall DebugLoopEx(
DWORD TimeOut
);
Parameters
TimeOut
[in] Value which to pass to the Windows WaitForDebugEvent API.
Return value
None.
Remarks
None.
Example
None.
SetDebugLoopTimeOut function
SetDebugLoopTimeOut sets a debug timeout at runtime. This value is passed to the WaitForDebugEvent
Windows API.
Syntax
void __stdcall SetDebugLoopTimeOut(
DWORD TimeOut
);
Parameters
TimeOut
[in] Value which will be passed to Windows WaitForDebugEvent API.
Return value
None.
Remarks
None.
Example
None.
SetNextDbgContinueStatus function
SetNextDbgContinueStatus sets the parameter passed to the ContinueDebugEvent Windows API.
Syntax
void __stdcall SetNextDbgContinueStatus(
DWORD SetDbgCode
);
Parameters
SetDbgCode
[in] Specify one of two values: DBG_CONTINUE or DBG_EXCEPTION_NOT_HANDLED.
Return value
None.
Remarks
USE WITH CAUTION: This function can break the debugging process. It may cause the debugged
target to exit the debugging loop, and terminate the application, or it may show an error
message on Windows Vista and later.
Example
None.
StopDebug function
StopDebug stops the debugging process. The Debugged process is terminated just after the call to this
function, and program control is passed to the first command following the DebugLoop function that
started the debugging process.
Syntax
void __stdcall StopDebug();
Parameters
None.
Return value
None.
Remarks
None.
Example
None.
ForceClose function
ForceClose stops the debugging process. The debugged process is terminated just after the call to this
function and program control is passed to the first command following the DebugLoop function that
started the debugging process. If your code has crashed with an exception, ForceClose is a safer way to
terminate debugging than StopDebug.
Syntax
void __stdcall ForceClose();
Parameters
None.
Return value
None.
Remarks
None.
Example
None.
SetBPXOptions function
SetBPXOptions sets the global breakpoint type. Set type is global making all breakpoints set after calling
this function to be set as the selected type.
Syntax
void __stdcall SetBPXOptions(
long DefaultBreakPointType
);
Parameters
DefaultBreakPointType
[in] Can be one of the following:
. UE_BREAKPOINT_INT3 (0xCC)
. UE_BREAKPOINT_LONG_INT3 (0xCD03)
. UE_BREAKPOINT_UD2 (0x0F0B)
Return value
None.
Remarks
UE_BREAKPOINT_UD2 refers to two byte INT3 defined as 0xCD03.
Example
None.
SetBPX function
SetBPX sets INT 3 breakpoints. Specify the type of INT3 breakpoint with the SetBPXOptions function.
Syntax
bool __stdcall SetBPX(
ULONG_PTR bpxAddress,
DWORD bpxType,
LPVOID bpxCallBack
);
Parameters
bpxAddress
[in] Address on which to set the breakpoint.
bpxType
[in] Type of breakpoint to set, either UE_BREAKPOINT or UE_SINGLESHOOT. By adding
one of the following values you can select the breakpoint type:
. UE_BREAKPOINT_TYPE_INT3 (0xCC)
. UE_BREAKPOINT_TYPE_LONG_INT3 (0xCD03)
. UE_BREAKPOINT_TYPE_UD2 (0x0F0B)
bpxCallBack
[in] Address of a callback to call when the breakpoint is hit.
CallBack definition
typedef void(__stdcall *cbBreakPoint)(void);
Return value
Boolean switch indicating whether or not the breakpoint was set.
Remarks
None.
Example
None.
SetBPXEx function
SetBPXEx sets INT3 breakpoints. Set the type of INT3 breakpoint with the SetBPXOptions function.
Syntax
bool __stdcall SetBPXEx(
ULONG_PTR bpxAddress,
DWORD bpxType,
DWORD NumberOfExecution,
DWORD CmpRegister,
DWORD CmpCondition,
ULONG_PTR CmpValue,
LPVOID bpxCallBack,
LPVOID bpxCompareCallBack,
LPVOID bpxRemoveCallBack
);
Parameters
bpxAddress
[in] Address at which a breakpoint will be set.
bpxType
[in] Type of the breakpoint to set. Either UE_BREAKPOINT or UE_SINGLESHOOT. By
adding one of the following values you can select the breakpoint type:
. UE_BREAKPOINT_TYPE_INT3 (0xCC)
. UE_BREAKPOINT_TYPE_LONG_INT3 (0xCD03)
. UE_BREAKPOINT_TYPE_UD2 (0x0F0B)
NumberOfExecutions
[in] Set maximum number of breakpoint executions. Specify NULL for no execution
limit.
CmpRegister
[in] Register to check to determine whether the breakpoint execution condition is met.
CmpCondition
[in] Type of comparison to run with the register. See Debugger module constants for
details.
CmpValue
[in] Value to use in the comparison. If condition has been met, the breakpoint callback
will be executed. See Debugger module constants for details.
bpxCallBack
[in] Address of a callback to call once breakpoint has been hit.
bpxCompareCallBack
[in] Reserved, always set to NULL.
bpxRemoveCallBack
[in] The callback to call when the breakpoint is removed.
CallBack definition
typedef void(__stdcall *cbBreakPoint)(void);
Return value
Boolean switch indicating whether or not the breakpoint was set.
Remarks
All callbacks have the same declaration.
Example
None.
EnableBPX function
EnableBPX enables a currently-disabled INT 3 breakpoint. This function can’t be used to enable memory
or hardware breakpoints, and should only be used after DisableBPX.
Syntax
bool __stdcall EnableBPX(
ULONG_PTR bpxAddress
);
Parameters
bpxAddress
[in] Address of an existing breakpoint which you would like to re-enable after it has
been disabled with DisableBPX.
Return value
Boolean switch indicating whether or not the breakpoint was enabled.
Remarks
None.
Example
None.
DisableBPX function
DisableBPX disables a currently enabled or active INT 3 breakpoint. This function can’t be used to
disable memory or hardware breakpoints.
Syntax
bool __stdcall DisableBPX(
ULONG_PTR bpxAddress
);
Parameters
bpxAddress
[in] Address of the existing INT 3 breakpoint to disable.
Return value
Boolean switch indicating whether or not the breakpoint was disabled.
Remarks
None.
Example
None.
IsBPXEnabled function
IsBPXEnabled determines whether or not the specified INT3 breakpoint is enabled. This function can’t
be used to check the state of memory or hardware breakpoints.
Syntax
bool __stdcall DisableBPX(
ULONG_PTR bpxAddress
);
Parameters
bpxAddress
[in] Address of the existing INT3 breakpoint whose state you want to know.
Return value
Boolean switch indicating whether or not the breakpoint is enabled.
Remarks
None.
Example
None.
DeleteBPX function
The DeleteBPX function is used to remove set INT3 breakpoints. This function can’t be used to remove
memory or hardware breakpoints.
Syntax
bool __stdcall DeleteBPX(
ULONG_PTR bpxAddress
);
Parameters
bpxAddress
[in] Address of the INT3 breakpoint to remove.
Return value
Boolean switch indicating whether or not the breakpoint was removed.
Remarks
If the breakpoint was set with SetBPXEx, and a remove callback was specified via SetBPXEx, the
callback will be called once this function is called.
Example
None.
SafeDeleteBPX function
This function has been deprecated. It has been preserved only for compatibility with earlier versions of
TitanEngine SDK. SafeDeleteBPX is used to remove an existing INT3 breakpoint. This function can’t be
used to remove memory or hardware breakpoints.
Syntax
bool __stdcall SafeDeleteBPX(
ULONG_PTR bpxAddress
);
Parameters
bpxAddress
[in] Address of the existing INT3 breakpoint to remove.
Return value
Boolean switch indicating whether or not the breakpoint has been removed.
Remarks
If the breakpoint was set with SetBPXEx, and a remove callback was specified via SetBPXEx, the
callback will be called once this function is called.
Example
None.
SetAPIBreakPoint function
The SetAPIBreakPoint sets an INT 3 breakpoint at an exported function in any loaded DLL file, not just
the system ones.
Syntax
bool __stdcall SetAPIBreakPoint(
char* szDLLName,
char* szAPIName,
DWORD bpxType,
DWORD bpxPlace,
LPVOID bpxCallBack
);
Parameters
szDLLName
[in] Pointer to string. Specify the name of the DLL containing the function on which to
set the breakpoint, for example kernel32.dll.
szAPIName
[in] Pointer to string. Specify the name of the API on which to set the breakpoint, for
example VirtualAlloc.
bpxType
[in] Type of breakpoint to set. Either UE_BREAKPOINT or UE_SINGLESHOOT.
bpxPlace
[in] Where to set the breakpoint. Use UE_APISTART to specify the first
instruction of the API or UE_APIEND to specify the last instruction, which is
always RET or one of its variations.
bpxCallBack
[in] Address of a callback to call once the breakpoint is hit.
CallBack definition
typedef void(__stdcall *cbBreakPoint)(void);
Return value
Boolean switch indicating whether or not the breakpoint was set.
Remarks
None.
DeleteAPIBreakPoint function
DeleteAPIBreakPoint removes an existing INT3 breakpoint from a function inside a DLL file.
Syntax
bool __stdcall DeleteAPIBreakPoint(
char* szDLLName,
char* szAPIName,
DWORD bpxPlace
);
Parameters
szDLLName
[in] Pointer to string. Specify the name of the DLL containing the function on which to
set the breakpoint, for example kernel32.dll.
szAPIName
[in] Pointer to string. Specify the name of the API on which the breakpoint was set, for
example VirtualAlloc.
bpxPlace
[in] Where on the API the breakpoint was set. Valid values: UE_APISTART if the
breakpoint was set on the first instruction in the API, or UE_APIEND if the
breakpoint was set on the last instruction in the API, which is always RET or a
variation.
Return value
Boolean switch indicating whether or not the breakpoint has been removed.
Remarks
None.
Example
None.
SafeDeleteAPIBreakPoint function
The SafeDeleteAPIBreakPoint function removes INT3 breakpoints from functions inside DLL files. This
function has been preserved only for backward compatibility with earlier versions of TitanEngine SDK.
Syntax
bool __stdcall SafeDeleteAPIBreakPoint(
char* szDLLName,
char* szAPIName,
DWORD bpxPlace
);
Parameters
szDLLName
[in] Pointer to string specifying the name of the DLL containing the function on which
the breakpoint was set, for example kernel32.dll.
szAPIName
[in] Pointer to string specitying the name of the API on which the breakpoint was set,
for example VirtualAlloc.
bpxPlace
[in] Location in the API at which the breakpoint was set. Use UE_APISTART if the
breakpoint was set at the first instruction in the API or UE_APIEND if the
breakpoint was set at the last instructionin the API, which is always RET or a
variation.
Return value
Boolean switch indicating whether or not the breakpoint has been removed.
Remarks
This function has been replaced by DeleteAPIBreakpoint.
Example
None.
SetMemoryBPX function
SetMemoryBPX sets memory breakpoints. These breakpoints are set by PAGE_GUARD to a targeted
memory region. If your breakpoint size is smaller than one page, the whole page will be affected by the
PAGE_GUARD and therefore it is possible that the page will be hit, but your breakpoint will not be
handled. Keep this in mind when setting this kind of breakpoint, and always set your breakpoint to a
whole page.
Syntax
bool __stdcall SetMemoryBPX(
ULONG_PTR MemoryStart,
DWORD SizeOfMemory,
LPVOID bpxCallBack
);
Parameters
MemoryStart
[in] Address on which breakpoint will be set. Ideally this is equal to page start.
SizeOfMemory
[in] Size of the memory to be affected by PAGE_GUARD.
bpxCallBack
[in] Address of the callback to call once breakpoint is hit.
CallBack definition
typedef void(__stdcall *cbBreakPoint)(void);
Return value
Boolean switch indicating whether or not the breakpoint was set.
Remarks
None.
Example
None.
SetMemoryBPXEx function
Like SetMemoryBPX, the function SetMemoryBPXEx sets memory breakpoints, but SetMemoryBPXEx
allows you to specify which type of memory access will trigger the break, and whether or not to restore
the breakpoint once it has been hit.
These breakpoints are set by PAGE_GUARD to targeted memory region. If your breakpoint size is
smaller than one page, the whole page will be affected by the PAGE_GUARD and therefore it is possible
that the page will be hit, but your breakpoint will not be handled. Keep this in mind when setting this
kind of breakpoint, and always set your breakpoint to a whole page.
Syntax
bool __stdcall SetMemoryBPXEx(
ULONG_PTR MemoryStart,
DWORD SizeOfMemory,
DWORD BreakPointType,
bool RestoreOnHit,
LPVOID bpxCallBack
);
Parameters
MemoryStart
[in] Address on which to set the breakpoint. Ideally this is the start of a page.
SizeOfMemory
[in] Size of the memory to be affected by PAGE_GUARD.
BreakPointType
[in] Defines type of memory breakpoint. Depending on the usage this can be either
UE_MEMORY, UE_MEMORY_READ, or UE_MEMORY_WRITE. Where UE_MEMORY
breaks on any type of access, UE_MEMORY_READ breaks only on read access, and
UE_MEMORY_WRITE breaks only on write access.
RestoreOnHit
[in] Indicates whether or not to restore the breakpoint once it is executed. By default, a
memory breakpoint is triggered only once, unless you use this option to restore it.
bpxCallBack
[in] Address of a callback to call when the breakpoint is hit.
CallBack definition
typedef void(__stdcall *cbBreakPoint)(void);
Return value
Boolean switch indicating whether or not the breakpoint was set.
RemoveMemoryBPX function
RemoveMemoryBPX removes previously-set memory breakpoints by removing PAGE_GUARD from
page protection flags.
Syntax
bool __stdcall RemoveMemoryBPX(
ULONG_PTR MemoryStart,
DWORD SizeOfMemory
);
Parameters
MemoryStart
[in] Address on which breakpoint was set.
SizeOfMemory
[in] Size of the memory that was specified when the breakpoint was set.
Return value
Boolean switch indicating whether or not the breakpoint is removed.
Remarks
None.
Example
None.
SetHardwareBreakPoint function
The SetHardwareBreakPoint function is used to set hardware breakpoints. These breakpoints can only
be set on CPUs that support them.
Syntax
bool __stdcall SetHardwareBreakPoint(
ULONG_PTR bpxAddress,
DWORD IndexOfRegister,
DWORD bpxType,
DWORD bpxSize,
LPVOID bpxCallBack
);
Parameters
bpxAddress
[in] Address on which to set the breakpoint.
IndexOfRegister
[in] Register that holds the bpxAddress. Specify a register in the range DR0 to DR3. If no
register is specified, the first available free register will be used.
bpxType
[in] Type of the breakpoint to set. UE_HARDWARE_EXECUTE, UE_HARDWARE_WRITE or
UE_HARDWARE_READWRITE. First type sets breakpoint on that memory execution
while other two set breakpoint on memory access.
bpxSize
[in] Size of the breakpoint to set. UE_HARDWARE_SIZE_1, UE_HARDWARE_SIZE_2 or
UE_HARDWARE_SIZE_4 indicating the size in bytes affected by the breakpoint.
bpxCallBack
[in] Address of a callback which to call when the breakpoint is hit.
CallBack definition
typedef void(__stdcall *cbBreakPoint)(void);
Return value
Boolean switch indicating whether or not the breakpoint was set.
Remarks
None.
SetHardwareBreakPointEx function
The SetHardwareBreakPointEx function is used to set hardware breakpoints. These breakpoints can
only be set on CPUs that support them. Function has the same callback definition as non expert version.
Syntax
bool __stdcall SetHardwareBreakPoint(
HANDLE hActiveThread,
ULONG_PTR bpxAddress,
DWORD IndexOfRegister,
DWORD bpxType,
DWORD bpxSize,
LPVOID bpxCallBack,
LPDWORD IndexOfSelectedRegister
);
Parameters
hActiveThread
[in] Handle of the open thread from which context will be set.
bpxAddress
[in] Address on which to set the breakpoint.
IndexOfRegister
[in] Register that holds the bpxAddress. Specify a register in the range DR0 to DR3. If no
register is specified, the first available free register will be used.
bpxType
[in] Type of the breakpoint to set. UE_HARDWARE_EXECUTE, UE_HARDWARE_WRITE or
UE_HARDWARE_READWRITE. First type sets breakpoint on that memory execution
while other two set breakpoint on memory access.
bpxSize
[in] Size of the breakpoint to set. UE_HARDWARE_SIZE_1, UE_HARDWARE_SIZE_2 or
UE_HARDWARE_SIZE_4 indicating the size in bytes affected by the breakpoint.
bpxCallBack
[in] Address of a callback which will be called once breakpoint has been hit.
IndexOfSelectedRegister
[out] Pointer to DWORD variable which will receive the index of the register used to set
the hardware breakpoint.
Return value
Boolean switch indicating whether or not the breakpoint was set.
DeleteHardwareBreakPoint function
DeleteHardwareBreakPoint removes a previously-set hardware breakpoint.
Syntax
bool __stdcall DeleteHardwareBreakPoint(
DWORD IndexOfRegister
);
Parameters
IndexOfRegister
[in] The register containing the breakpoint's address pointer (DR0 to DR3).
Return value
Boolean switch indicating whether or not the breakpoint has been removed.
Remarks
None.
Example
None.
GetUnusedHardwareBreakPointRegister function
GetUnusedHardwareBreakPointRegister get the currently free DRx register.
Syntax
bool __stdcall GetUnusedHardwareBreakPointRegister(
LPDWORD RegisterIndex
);
Parameters
IndexOfRegister
[out] Pointer to the variable which will receive the free DRx register (DR0 to DR3).
Return value
Boolean switch indicating whether or not the any of the registers is free.
Remarks
None.
Example
None.
RemoveAllBreakPoints function
RemoveAllBreakPoints removes/disables all breakpoints of the specified type(s).
Syntax
bool __stdcall RemoveAllBreakPoints(
DWORD RemoveOption
);
Parameters
RemoveOption
[in] One of the following:
. UE_OPTION_REMOVEALL, removes all breakpoints.
. UE_OPTION_DISABLEALL, disables all breakpoints excluding hardware ones.
. UE_OPTION_REMOVEALLDISABLED, removes all disabled INT3 breakpoints.
. UE_OPTION_REMOVEALLENABLED, removes all active INT3 breakpoints.
Return value
Boolean switch indicating whether or not the breakpoints were removed.
Remarks
None.
Example
None.
CurrentExceptionNumber function
CurrentExceptionNumber retrieves the number of exceptions that were registered and processed prior
to this function being called.
Syntax
long __stdcall CurrentExceptionNumber();
Parameters
None.
Return value
Function returns the number of registered exceptions.
Remarks
None.
Example
None.
ClearExceptionNumber function
ClearExceptionNumber resets to zero the number of exceptions that were registered and processed
prior to this function being called.
Syntax
long __stdcall ClearExceptionNumber();
Parameters
None.
Return value
None.
Remarks
None.
Example
None.
GetDebugData function
GetDebugData retrieves a pointer to an internal DEBUG_EVENT structure.
Syntax
void* __stdcall GetDebugData();
Parameters
None.
Return value
Pointer to DEBUG_EVENT structure. Can be declared as LPDEBUG_EVENT instead of void*.
Remarks
Process must be active for this function to work.
Example
None.
GetTerminationData function
GetTerminationData retrieves a pointer to an internal DEBUG_EVENT structure. GetTerminationData is
similar to GetDebugData but is used only when the process has terminated its execution.
Syntax
void* __stdcall GetTerminationData();
Parameters
None.
Return value
Pointer to a DEBUG_EVENT structure. Can be declared as LPDEBUG_EVENT instead of void*.
Remarks
Function can only be used for terminated processes.
Example
None.
GetContextDataEx function
GetContextDataEx retrieves data from the context of any debugged process thread. You can use engine
thread handling functions to get the handles of all active threads.
Syntax
long long __stdcall GetContextDataEx(
HANDLE hActiveThread,
DWORD IndexOfRegister
);
Parameters
hActiveThread
[in] Handle of the open thread from which to read the context.
IndexOfRegister
[in] Indicator on which register will be read from the context of the selected thread. See
Debugger module constants for details.
Return value
This function returns the requested data.
Remarks
None.
Example
None.
GetContextData function
GetContextData retrieves context data from the thread that generated the last exception or timeout in
the active process that the debugger is currently processing. Use GetContextDataEx if you want to get
the context for a specific thread.
Syntax
long long __stdcall GetContextData(
DWORD IndexOfRegister
);
Parameters
IndexOfRegister
[in] Indicator on which register will be read from the context of the selected thread. See
Debugger module constants for details.
Return value
This function returns the requested data.
Remarks
None.
Example
None.
SetContextDataEx function
SetContextDataEx sets the context data for the process thread that is being debugged.
Syntax
bool __stdcall SetContextDataEx(
HANDLE hActiveThread,
DWORD IndexOfRegister,
ULONG_PTR NewRegisterValue
);
Parameters
hActiveThread
[in] Handle of the open thread whose context will be set.
IndexOfRegister
[in] Specifies the context register to modify. See Debugger module constants for details.
NewRegisterValue
[in] The new context value to place in the register.
Return value
Boolean switch indicating whether or not the value in the register was updated.
Remarks
CAUTION: This function modifies context of the thread, so be careful using it, since corrupting
certain registers can cause the application to crash.
Example
None.
SetContextData function
SetContextData sets the context data for the active process thread that generated the most recent
exception or debug timeout.
Syntax
bool __stdcall SetContextData(
DWORD IndexOfRegister,
ULONG_PTR NewRegisterValue
);
Parameters
IndexOfRegister
[in] Specifies the context register to modify. See Debugger module constants for details.
NewRegisterValue
[in] The new context value to use.
Return value
Boolean switch indicating whether or not the function was successful.
Remarks
CAUTION: This function modifies context of the thread, so be careful using it, since corrupting
certain registers can cause the application to crash.
Example
None.
GetContextFPUDataEx function
GetContextFPUDataEx retrieves FPU data from the context of any debugged process thread. You can
use engine thread handling functions to get the handles of all active threads.
Syntax
bool __stdcall GetContextFPUDataEx(
HANDLE hActiveThread,
void* FPUSaveArea
);
Parameters
hActiveThread
[in] Handle of the open thread from which to read the context.
FPUSaveArea
[out] Pointer to FLOATING_SAVE_AREA structure defined in WinNT.h for 32 bit systems
or to XMM_SAVE_AREA32 for 64 bit systems.
Return value
This function returns TRUE on successful data retrieval or FALSE if data isn’t available.
Remarks
None.
Example
None.
SetContextFPUDataEx function
SetContextFPUDataEx sets FPU data in the context of any debugged process thread. You can use engine
thread handling functions to get the handles of all active threads.
Syntax
bool __stdcall SetContextFPUDataEx(
HANDLE hActiveThread,
void* FPUSaveArea
);
Parameters
hActiveThread
[in] Handle of the open thread from which to read the context.
FPUSaveArea
[in] Pointer to FLOATING_SAVE_AREA structure defined in WinNT.h for 32 bit systems
or to XMM_SAVE_AREA32 for 64 bit systems.
Return value
This function returns TRUE on successful data update or FALSE if update failed.
Remarks
None.
Example
None.
StepInto function
StepInto traces code by single-stepping into calls. This tracing function sets a trap flag and calls your
callback once that trap flag has been activated. This allows you to execute one instruction at a time,
making it possible to trace through the execution of each instruction.
Syntax
void __stdcall StepInto(
LPVOID StepCallBack
);
Parameters
StepCallBack
[in] Address of the callback to call when trap flag has been hit.
CallBack definition
typedef void(__stdcall *cbBreakPoint)(void);
Return value
None.
Remarks
None.
Example
None.
StepOver function
The StepOver traces code by single-stepping over calls. This tracing function sets an INT3 breakpoint
after the call, which is used to call your callback. There is no guarantee that code execution will return
from that call, and thus no guarantee that your callback will ever be called. The breakpoint is run only
once, and is removed once your callback has finished.
Syntax
void __stdcall StepOver(
LPVOID StepCallBack
);
Parameters
StepCallBack
[in] Address of the callback to call when the breakpoint has been hit.
CallBack definition
typedef void(__stdcall *cbBreakPoint)(void);
Return value
None.
Remarks
None.
Example
None.
SingleStep function
The SingleStep traces code by single-stepping through a series of instructions. This tracing function sets
a trap flag and calls your callback once that trap flag has been activated. This allows you to execute one
instruction at a time, making it possible to trace through the execution of each instruction.
Syntax
void __stdcall SingleStep(
DWORD StepCount,
LPVOID StepCallBack
);
Parameters
StepCount
[in] Number of instructions to trace. Your callback will be called each time an
instruction executes, up to the number of instructions specified.
StepCallBack
[in] Address of the callback to call when each instruction executes.
CallBack definition
typedef void(__stdcall *cbBreakPoint)(void);
Return value
None.
Remarks
None.
Example
None.
FindEx function
FindEx searches the process memory for binary patterns.
Syntax
long long __stdcall FindEx(
HANDLE hProcess,
LPVOID MemoryStart,
DWORD MemorySize,
LPVOID SearchPattern,
DWORD PatternSize,
LPBYTE WildCard
);
Parameters
hProcess
[in] Handle of the process whose memory will be searched.
MemoryStart
[in] Pointer to the memory location to use as the start point for the search.
MemorySize
[in] Size of the memory region to search for the byte pattern.
SearchPattern
[in] Pointer to the sequence of bytes to find.
PatternSize
[in] Size of the search pattern, in bytes.
WildCard
[in] Pointer to a wild card byte which will be ignored during search. This wild card is
equal to search asterisk “?” and those bytes inside the search pattern will always be
considered as found. Usually this byte is NULL.
Return value
Function returns pointer to the first byte of the found pattern inside the remote process. It can
also be declared as void*, or NULL if byte pattern is not found.
Remarks
None.
Find function
Find searches the process memory for binary patterns. This function always searches the memory of the
currently debugger process.
Syntax
long long __stdcall Find(
LPVOID MemoryStart,
DWORD MemorySize,
LPVOID SearchPattern,
DWORD PatternSize,
LPBYTE WildCard
);
Parameters
MemoryStart
[in] Pointer to memory in remote process which is used as a start point for the search.
MemorySize
[in] Size of the memory which will be searched for byte pattern.
SearchPattern
[in] Pointer to sequence of bytes which represent the search pattern.
PatternSize
[in] Size of the search pattern in bytes.
WildCard
[in] Pointer to a wild card byte which will be ignored during search. This wild card is
equal to search asterisk “?” and those bytes inside the search pattern will always be
considered as found. Usually this byte is NULL.
Return value
Function returns pointer to first byte of the found pattern inside the remote process. Therefore
it can also be declared as void*, or NULL if byte pattern is not found.
Remarks
None.
MatchPatternEx function
MatchPatternEx tries to match the selected pattern to specified memory address.
Syntax
bool __stdcall MatchPatternEx(
HANDLE hProcess,
void* MemoryToCheck,
int SizeOfMemoryToCheck,
void* PatternToMatch,
int SizeOfPatternToMatch,
PBYTE WildCard
);
Parameters
hProcess
[in] Handle of the process whose memory will be searched.
MemoryToCheck
[in] Pointer to the memory location to use as the start point for the pattern match.
SizeOfMemoryToCheck
[in] Size of the memory region to check the pattern match.
PattternToMatch
[in] Pointer to the sequence of bytes to match.
SizeOfPatternToMatch
[in] Size of the match pattern, in bytes.
WildCard
[in] Pointer to a wild card byte which will be ignored during search. This wild card is
equal to search asterisk “?” and those bytes inside the search pattern will always be
considered as found. Usually this byte is NULL.
Return value
Function returns TRUE if the provided pattern matches the memory content or FALSE if it
doesn’t.
Remarks
None.
MatchPattern function
MatchPattern tries to match the selected pattern to specified memory address.
Syntax
bool __stdcall MatchPattern(
void* MemoryToCheck,
int SizeOfMemoryToCheck,
void* PatternToMatch,
int SizeOfPatternToMatch,
PBYTE WildCard
);
Parameters
MemoryToCheck
[in] Pointer to the memory location to use as the start point for the pattern match.
SizeOfMemoryToCheck
[in] Size of the memory region to check the pattern match.
PattternToMatch
[in] Pointer to the sequence of bytes to match.
SizeOfPatternToMatch
[in] Size of the match pattern, in bytes.
WildCard
[in] Pointer to a wild card byte which will be ignored during search. This wild card is
equal to search asterisk “?” and those bytes inside the search pattern will always be
considered as found. Usually this byte is NULL.
Return value
Function returns TRUE if the provided pattern matches the memory content or FALSE if it
doesn’t.
Remarks
None.
FillEx function
FillEx fills the specified process memory location with the specified byte. If the location size is larger
than a byte, the byte is repeated until the location is full. Most commonly this is done to NOP parts of
the code, or to zero out a memory region.
Syntax
bool __stdcall FillEx(
HANDLE hProcess,
LPVOID MemoryStart,
DWORD MemorySize,
PBYTE FillByte
);
Parameters
hProcess
[in] Handle of the process whose memory will be patched.
MemoryStart
[in] Pointer to memory in remote process which is used as a start point for the filling.
MemorySize
[in] Size of the memory which will be filled with selected byte.
FillByte
[in] Pointer to byte which will be used for memory filling.
Return value
Boolean switch indicating whether or not the function was successful.
Remarks
None.
Example
None.
Fill function
Fill fills the currently debugged process memory location with the specified byte. If the location size is
larger than a byte, the byte is repeated until the location is full. Most commonly this is done to NOP
parts of the code, or to zero out a memory region.
Syntax
bool __stdcall Fill(
LPVOID MemoryStart,
DWORD MemorySize,
PBYTE FillByte
);
Parameters
MemoryStart
[in] Pointer to memory in remote process which is used as a start point for the filling.
MemorySize
[in] Size of the memory which will be filled with selected byte.
FillByte
[in] Pointer to byte which will be used for memory filling.
Return value
Boolean switch indicating whether or not the function was successful.
Remarks
None.
Example
None.
PatchEx function
PatchEx fills a process memory location with the specified multi-byte pattern. If the region being filled is
larger than the pattern, the remaining bytes may optionally be NOPed or left unmodified.
Syntax
bool __stdcall PatchEx(
HANDLE hProcess,
LPVOID MemoryStart,
DWORD MemorySize,
LPVOID ReplacePattern,
DWORD ReplaceSize,
bool AppendNOP,
bool PrependNOP
);
Parameters
hProcess
[in] Handle of the process whose memory will be patched.
MemoryStart
[in] Pointer to memory in remote process which is used as a start point for the patch.
MemorySize
[in] Size of the memory which will be patched with selected byte pattern.
ReplacePattern
[in] Pointer to sequence of bytes which will be written to targeted memory.
ReplaceSize
[in] Size of the replace pattern.
AppendNOP
[in] If the patch size is lesser then targeted memory size patching NOPs can be
appended to patch bytes to make that memory execution safe.
PrependNOP
[in] If the patch size is lesser then targeted memory size patching NOPs can be prepend
to patch bytes to make that memory execution safe.
Return value
Boolean switch indicating whether or not the function was successful.
Patch function
Patch fills a memory location with the specified multi-byte pattern. If the region being filled is larger
than the pattern, the remaining bytes may optionally be NOPed or left unmodified. This function always
patches the process currently being debugged.
Syntax
bool __stdcall Patch(
LPVOID MemoryStart,
DWORD MemorySize,
LPVOID ReplacePattern,
DWORD ReplaceSize,
bool AppendNOP,
bool PrependNOP
);
Parameters
MemoryStart
[in] Pointer to memory in remote process which is used as a start point for the patch.
MemorySize
[in] Size of the memory which will be patched with selected byte pattern.
ReplacePattern
[in] Pointer to sequence of bytes which will be written to targeted memory.
ReplaceSize
[in] Size of the replace pattern.
AppendNOP
[in] If the patch size is lesser then targeted memory size patching NOPs can be
appended to patch bytes to make that memory execution safe.
PrependNOP
[in] If the patch size is lesser then targeted memory size patching NOPs can be prepend
to patch bytes to make that memory execution safe.
Return value
Boolean switch indicating whether or not the function was successful.
ReplaceEx function
ReplaceEx does a search and replace on a specific byte pattern in a process memory location. When the
byte pattern is found, it is replaced with the byte pattern you specify. Number of matches which will be
replaced can be specified. Any remaining bytes may optionally be NOPed or left unmodified.
Syntax
bool __stdcall ReplaceEx(
HANDLE hProcess,
LPVOID MemoryStart,
DWORD MemorySize,
LPVOID SearchPattern,
DWORD PatternSize,
DWORD NumberOfRepetitions,
LPVOID ReplacePattern,
DWORD ReplaceSize,
PBYTE WildCard
);
Parameters
hProcess
[in] Handle of the process whose memory will be patched.
MemoryStart
[in] Pointer to memory in remote process which is used as a start point for the search.
MemorySize
[in] Size of the memory which will be searched for the byte pattern.
SearchPattern
[in] Pointer to sequence of bytes which represent the search pattern.
NumberOfRepetitions
[in] Maximum number of patterns which will be replaced.
PatternSize
[in] Size of the search pattern in bytes.
ReplacePattern
[in] Pointer to sequence of bytes which will be written to targeted memory.
ReplaceSize
[in] Size of the replace pattern.
WildCard
[in] Pointer to a wild card byte which will be ignored during search and replace. This
wild card is equal to search asterisk “?” and those bytes inside the search pattern
will always be considered as found. Usually this byte is NULL.
Return value
Boolean switch indicating whether or not the function was successful.
Remarks
Both search and replace patterns can have wild card bytes to ignore during search and replace.
Example
None.
Replace function
Replace does a search and replace on a specific byte pattern in a memory location. When the byte
pattern is found, it is replaced with the byte pattern you specify. This function always replaces the byte
pattern in the process currently being debugged.
Syntax
bool __stdcall Replace(
LPVOID MemoryStart,
DWORD MemorySize,
LPVOID SearchPattern,
DWORD PatternSize,
DWORD NumberOfRepetitions,
LPVOID ReplacePattern,
DWORD ReplaceSize,
PBYTE WildCard
);
Parameters
MemoryStart
[in] Pointer to memory in remote process which is used as a start point for the search.
MemorySize
[in] Size of the memory which will be searched for the byte pattern.
SearchPattern
[in] Pointer to sequence of bytes which represent the search pattern.
NumberOfRepetitions
[in] Maximum number of patterns which will be replaced.
PatternSize
[in] Size of the search pattern in bytes.
ReplacePattern
[in] Pointer to sequence of bytes which will be written to targeted memory.
ReplaceSize
[in] Size of the replace pattern.
WildCard
[in] Pointer to a wild card byte which will be ignored during search and replace. This
wild card is equal to search asterisk “?” and those bytes inside the search pattern
will always be considered as found. Usually this byte is NULL.
Return value
Boolean switch indicating whether or not the function was successful.
Remarks
Both search and replace patterns can have wild card bytes which will be ignored during search
and replace.
Example
None.
GetRemoteString function
GetRemoteString retrieves a string from a remote process. This function can read both ASCII and
UNICODE strings.
Syntax
bool __stdcall GetRemoteString(
HANDLE hProcess,
LPVOID StringAddress,
LPVOID StringStorage,
int MaximumStringSize
);
Parameters
hProcess
[in] Handle of the process from which the string will be read.
StringAddress
[in] Pointer to string in remote process which will be copied to selected memory.
StringStorage
[out] Pointer to memory location inside your code which will receive the remote string
content.
MaximumStringSize
[in] Size of the local memory buffer reserved for reading the remote string.
Return value
Boolean switch indicating whether or not the function was successful.
Remarks
Always copies the maximum available bytes but keeping in mind the bounds imposed by the
maximum size of the string.
Example
None.
GetFunctionParameter function
GetFunctionParameter retrieves the value of an input parameter from a standard function types.
GetFunctionParameter can only work if the function's execution has been paused at either the first
instruction of the call or the last instruction inside the call.
Syntax
long long __stdcall GetFunctionParameter(
HANDLE hProcess,
DWORD FunctionType,
DWORD ParameterNumber,
DWORD ParameterType
);
Parameters
hProcess
[in] Handle of the process from which the function parameter will be read. Debugged
process handle should always be used.
FunctionType
[in] Can be one of the following:
. UE_FUNCTION_STDCALL, EIP/RIP at first instruction inside the call.
. UE_FUNCTION_CCALL, EIP/RIP at first instruction inside the call.
. UE_FUNCTION_FASTCALL, EIP/RIP at first instruction inside the call.
. UE_FUNCTION_STDCALL_RET, EIP/RIP at last instruction of the call (RET).
. UE_FUNCTION_CCALL_RET, EIP/RIP at last instruction of the call (RET).
. UE_FUNCTION_FASTCALL_RET, EIP/RIP at last instruction of the call (RET).
. UE_FUNCTION_STDCALL_CALL, reserved for future use.
. UE_FUNCTION_FASTCALL_CALL, reserved for future use.
ParameterNumber
[in] Number if the input parameter whose value will be returned.
ParameterType
[in] Can be one of the following: UE_PARAMETER_BYTE, UE_PARAMETER_WORD,
UE_PARAMETER_DWORD, UE_PARAMETER_QWORD, UE_PARAMETER_PTR_BYTE,
UE_PARAMETER_PTR_WORD, UE_PARAMETER_PTR_DWORD, UE_PARAMETER_PTR_QWORD,
UE_PARAMETER_STRING or UE_PARAMETER_UNICODE.
Return value
Returns either the requested value or a pointer to string, depending on the parameter type. If
the parameter type is PTR then this function will return the data to which the pointer points. So
if you use PARAMETER_PTR_DWORD it will return the DWORD to which that parameter points.
Remarks
Maximum length of the read string is 512 characters.
The Stack is acquired for the currently paused thread inside the debugged process.
Example:
/*7630B86F*/ MOV EDI,EDI ;<- EIP at VirtualAlloc
/*7630B871*/ PUSH EBP
/*7630B872*/ MOV EBP,ESP
/*7630B874*/ PUSH DWORD PTR SS:[EBP+14]
/*7630B877*/ PUSH DWORD PTR SS:[EBP+10]
/*7630B87A*/ PUSH DWORD PTR SS:[EBP+C]
/*7630B87D*/ PUSH DWORD PTR SS:[EBP+8]
/*7630B880*/ PUSH -1
/*7630B882*/ CALL kernel32.VirtualAllocEx
/*7630B887*/ POP EBP
/*7630B888*/ RET 10
Stack:
0012FA6C 004015A0 /CALL to VirtualAlloc from 0040159B
0012FA70 00000000 |Address = NULL
0012FA74 00100000 |Size = 100000 (1048576.)
0012FA78 00002000 |AllocationType = MEM_RESERVE
0012FA7C 00000001 \Protect = PAGE_NOACCESS
Calling GetFunctionParameter to return the second input parameter of the VirtualAlloc function we will
need to call it like this:
GetFunctionParameter(hProcess, UE_FUNCTION_STDCALL , 2, UE_PARAMETER_DWORD);
Which returns 0x00100000. If the EIP was at the RET instruction this function would be called like this:
GetFunctionParameter(hProcess, UE_FUNCTION_STDCALL_RET , 2, UE_PARAMETER_DWORD);
Which would return the same value.
GetJumpDestinationEx function
GetJumpDestinationEx determines where the specified jump or call instruction will land.
Syntax
long long __stdcall GetJumpDestinationEx(
HANDLE hProcess,
ULONG_PTR InstructionAddress,
bool JustJumps
);
Parameters
hProcess
[in] Handle of the process in which the jump or call resides.
InstructionAddress
[in] Address of the jump or call whose destination you want to find.
JustJumps
[in] Boolean switch that indicates whether or to get destinations for calls or only jumps.
Return value
Returns the address targeted by jump/call or NULL if the instruction at the specified address
isn’t a jump or call.
Remarks
None.
Example
None.
GetJumpDestination function
GetJumpDestination determines where the specified jump or call instruction will land.
Syntax
long long __stdcall GetJumpDestination(
HANDLE hProcess,
ULONG_PTR InstructionAddress
);
Parameters
hProcess
[in] Handle of the process in which the jump or call resides.
InstructionAddress
[in] Address on which the jump or call is located.
Return value
Returns the address targeted by jump/call or NULL if the instruction on selected address isn’t
jump or call.
Remarks
Function calls GetJumpDestinationEx with JustJumps parameter set to FALSE.
Example
None.
IsJumpGoingToExecuteEx function
IsJumpGoingToExecuteEx determines whether or not the targeted jump is going to execute.
IsJumpGoingToExecuteEx allows you to specify which process and which thread to check.
Syntax
bool __stdcall IsJumpGoingToExecuteEx(
HANDLE hProcess,
HANDLE hThread,
ULONG_PTR InstructionAddress,
ULONG_PTR RegFlags
);
Parameters
hProcess
[in] Handle of the process in which the jump resides.
hThread
[in] Handle of the thread from which EFLAGS/RFLAGS will be read.
InstructionAddress
[in] Address on which the jump is located. Optional parameter, if it is not specified
instruction at EIP/RIP will be targeted.
RegFlags
[in] Used to override current EFLAGS/RFLAGS. Used only if EIP/RIP isn’t at targeted
instruction. Optional parameter, if not specified EFLAGS/RFLAGS will be read from
the specified thread.
Return value
Returns TRUE if jump would execute if execution continues or FALSE if not.
Remarks
None.
Example
None.
IsJumpGoingToExecute function
IsJumpGoingToExecute check if the targeted jump is going to execute or not for the currently active
thread in the process currently being debugged.
Syntax
bool __stdcall IsJumpGoingToExecute();
Parameters
None.
Return value
Returns TRUE if jump would execute if execution continues or FALSE if not.
Remarks
Function assumes currently debugged process and currently active thread executing jump at
current EIP/RIP.
Example
None.
SetCustomHandler function
SetCustomHandler allows you to specify a custom exception handler for the specified exception. You
can handle the most commonly generated errors via the built-in definitions, or you can handle all
exceptions and filter only the ones of interest to you.
Syntax
void __stdcall SetCustomHandler(
DWORD ExceptionId,
LPVOID CallBack
);
Parameters
ExceptionId
[in] Exception identifier, exact code and alias can be found at Debugger module
constants.
CallBack
[in] Pointer to callback function which will be called when application encounters that
specific exception.
CallBack definition
typedef void(__stdcall *cbCustomHandler)(void* ExceptionData);
Return value
None.
Remarks
See below for ExceptionData callback details.
Example
None.
SetCustomHandler CallBack details
UE_CH_BREAKPOINT
ExceptionData points to: &DBGEvent.u.Exception.ExceptionRecord
UE_CH_SINGLESTEP
ExceptionData points to: &DBGEvent.u.Exception.ExceptionRecord
UE_CH_ACCESSVIOLATION
ExceptionData points to: &DBGEvent.u.Exception.ExceptionRecord
UE_CH_ILLEGALINSTRUCTION
ExceptionData points to: &DBGEvent.u.Exception.ExceptionRecord
UE_CH_NONCONTINUABLEEXCEPTION
ExceptionData points to: &DBGEvent.u.Exception.ExceptionRecord
UE_CH_ARRAYBOUNDSEXCEPTION
ExceptionData points to: &DBGEvent.u.Exception.ExceptionRecord
UE_CH_FLOATDENORMALOPERAND
ExceptionData points to: &DBGEvent.u.Exception.ExceptionRecord
UE_CH_FLOATDEVIDEBYZERO
ExceptionData points to: &DBGEvent.u.Exception.ExceptionRecord
UE_CH_INTEGERDEVIDEBYZERO
ExceptionData points to: &DBGEvent.u.Exception.ExceptionRecord
UE_CH_INTEGEROVERFLOW
ExceptionData points to: &DBGEvent.u.Exception.ExceptionRecord
UE_CH_PRIVILEGEDINSTRUCTION
ExceptionData points to: &DBGEvent.u.Exception.ExceptionRecord
UE_CH_PAGEGUARD
ExceptionData points to: &DBGEvent.u.Exception.ExceptionRecord
UE_CH_EVERYTHINGELSE
ExceptionData points to: &DBGEvent.u.Exception.ExceptionRecord
UE_CH_CREATETHREAD
ExceptionData points to: &DBGEvent.u.CreateThread
UE_CH_EXITTHREAD
ExceptionData points to: &DBGEvent.u.ExitThread
UE_CH_CREATEPROCESS
ExceptionData points to: &DBGEvent.u.CreateProcessInfo
UE_CH_EXITPROCESS
ExceptionData points to: &DBGEvent.u.ExitProcess
UE_CH_LOADDLL
ExceptionData points to: &DBGEvent.u.LoadDll
UE_CH_UNLOADDLL
ExceptionData points to: &DBGEvent.u.UnloadDll
UE_CH_OUTPUTDEBUGSTRING
ExceptionData points to: &DBGEvent.u.DebugString
HideDebugger function
HideDebugger hides the debugger from a variety of detection tricks, reducing the chances that it will be
detected.
Syntax
bool __stdcall HideDebugger(
HANDLE hProcess,
DWORD PatchAPILevel
);
Parameters
hProcess
[in] Handle of the debugged process.
PatchAPILevel
[in] Patches following APIs when set to UE_HIDE_BASIC:
. CheckRemoteDebuggerPresent
. GetTickCount
Return value
Returns TRUE if the debugger is now hidden or FALSE if there were errors.
Remarks
None.
Example
None.
UnHideDebugger function
UnHideDebugger reverts hiding the debugger from a variety of detection tricks.
Syntax
bool __stdcall UnHideDebugger(
HANDLE hProcess,
DWORD PatchAPILevel
);
Parameters
hProcess
[in] Handle of the debugged process.
PatchAPILevel
[in] Patches following APIs when set to UE_HIDE_BASIC:
. CheckRemoteDebuggerPresent
. GetTickCount
Return value
Returns TRUE if the debugger is now visible or FALSE if there were errors.
Remarks
None.
Example
None.
GetPEBLocation function
GetPEBLocation gets the PEB location inside the remote process.
Syntax
void* __stdcall GetPEBLocation(
HANDLE hProcess
);
Parameters
hProcess
[in] Handle for process whose PEB location you are interested in.
Return value
Returns a pointer to PEB inside remote process.
Remarks
None.
Example
None.
SetEngineVariable function
The SetEngineVariable sets various global settings for the TitanEngine SDK.
Syntax
void __stdcall SetEngineVariable(
DWORD VariableId,
bool VariableSet
);
Parameters
VariableId
[in] Can be one of the following:
. UE_ENGINE_ALOW_MODULE_LOADING
. UE_ENGINE_AUTOFIX_FORWARDERS
. UE_ENGINE_PASS_ALL_EXCEPTIONS
. UE_ENGINE_NO_CONSOLE_WINDOW
. UE_ENGINE_BACKUP_FOR_CRITICAL_FUNCTIONS
. UE_ENGINE_RESET_CUSTOM_HANDLER
. UE_ENGINE_CALL_PLUGIN_DEBUG_CALLBACK
VariableSet
[in] Boolean value which will be set to the selected option.
Return value
None.
Remarks
None.
Example
None.
Threader module
Functions in the threader module are designed for working with threads. Threader module functions
cover thread identification; thread manipulation and remote thread injection.
Threader module structures
Structures used by the: ThreaderGetThreadInfo function and ThreaderEnumThreadInfo function
typedef struct{
HANDLE hThread;
DWORD dwThreadId;
void* ThreadStartAddress;
void* ThreadLocalBase;
}THREAD_ITEM_DATA, *PTHREAD_ITEM_DATA;
ThreaderGetThreadInfo function
ThreaderGetThreadInfo retrieves information about the threads inside the debugged process. Data is
collected each time a new thread is created, or any of the existing ones terminates. You may specify
either the thread handle or thread ID, but do not need to specify both.
Syntax
void* __stdcall ThreaderGetThreadInfo(
HANDLE hThread,
DWORD ThreadId
);
Parameters
hThread
[in] Handle of the thread whose info will be returned.
ThreadIs
[in] ID of thread whose info will be returned.
Return value
This function returns pointer to a THREAD_ITEM_DATA structure or NULL if the thread is no
longer active or not found.
Remarks
Only one of the two input parameters is needed.
Example
None.
ThreaderGetThreadData function
ThreaderGetThreadData retrieves a pointer to an array of THREAD_ITEM_DATA entries containing
information about the existing threads. The hThread item in the last structure in the array is set to NULL.
The number of items in the array is the number of existing threads inside the debugged process. The size
of this array isn’t stored anywhere and must be determined on the fly.
Syntax
void* __stdcall ThreaderGetThreadData();
Parameters
None.
Return value
This function returns pointer to THREAD_ITEM_DATA structure array.
Remarks
None.
Example
None.
ThreaderEnumThreadInfo function
ThreaderEnumThreadInfo enumerates data about existing threads inside the debugged process. Data is
collected each time a new thread is created, or any of the existing ones terminates.
Syntax
void __stdcall ThreaderEnumThreadInfo(
void* EnumCallBack
);
Parameters
EnumCallBack
[in] Pointer to the callback function that will process the thread item data for each
thread.
CallBack definition
typedef void(__stdcall *fEnumCallBack)(LPVOID fThreadDetail);
// fThreadDetail is a pointer to THREAD_ITEM_DATA structure
Return value
None.
Remarks
None.
Example
None.
ThreaderPauseThread function
ThreaderPauseThread changes the state of any active thread from active to suspend.
Syntax
bool __stdcall ThreaderPauseThread(
HANDLE hThread
);
Parameters
hThread
[in] Handle of the thread to pause.
Return value
This function returns TRUE if thread is paused or FALSE if its execution can’t be paused at this
time.
Remarks
None.
Example
None.
ThreaderResumeThread function
ThreaderResumeThread resumes execution of any currently paused thread inside the debugged
process.
Syntax
bool __stdcall ThreaderResumeThread(
HANDLE hThread
);
Parameters
hThread
[in] Handle of the thread whose execution will be resumed.
Return value
This function returns TRUE if thread resumes or FALSE if its execution can’t resume at this time.
Remarks
None.
Example
None.
ThreaderTerminateThread function
ThreaderTerminateThread tries to terminate an existing thread inside the debugged process.
Syntax
bool __stdcall ThreaderTerminateThread(
HANDLE hThread,
DWORD ThreadExitCode
);
Parameters
hThread
[in] Handle of the thread to terminate.
ThreadExitCode
[in] Exit code to pass to the TerminateThread Windows API that terminates the thread.
Return value
This function returns TRUE if the thread is terminated or FALSE if thread cannot be terminated.
Remarks
None.
Example
None.
ThreaderPauseAllThreads function
ThreaderPauseAllThreads pauses all running threads inside the debugged process, optionally leaving
the main thread running.
Syntax
bool __stdcall ThreaderPauseAllThreads(
bool LeaveMainRunning
);
Parameters
LeaveMainRunning
[in] Boolean switch indicating whether or not to leave the main thread running.
Return value
This function returns TRUE if the specified threads are paused or FALSE if not.
Remarks
None.
Example
None.
ThreaderResumeAllThreads function
ThreaderResumeAllThreads resumes execution of all paused threads in the debugged process;
optionally leaving the main thread paused.
Syntax
bool __stdcall ThreaderResumeAllThreads(
bool LeaveMainPaused
);
Parameters
LeaveMainPaused
[in] Boolean switch indicating whether or not to leave the main thread paused.
Return value
This function returns TRUE if all the existing threads are resumed or FALSE if not.
Remarks
None.
Example
None.
ThreaderPauseProcess function
ThreaderPauseProcess pauses all active threads inside the debugged process, suspending that process.
Syntax
bool __stdcall ThreaderPauseProcess();
Parameters
None.
Return value
This function returns TRUE if all threads are paused successfully or FALSE otherwise.
Remarks
None.
Example
None.
ThreaderResumeProcess function
The ThreaderResumeProcess function is used to resume all paused threads inside the debugged
process.
Syntax
bool __stdcall ThreaderResumeProcess();
Parameters
None.
Return value
This function returns TRUE if all threads get resumed or FALSE if there are no threads inside the
debugged process.
Remarks
None.
Example
None.
ThreaderIsThreadStillRunning function
ThreaderIsThreadStillRunning checks whether the selected thread still exists, regardless of its state, in
the debugged process.
Syntax
bool __stdcall ThreaderIsThreadStillRunning(
HANDLE hThread
);
Parameters
hThread
[in] Handle of the thread whose existence will be checked.
Return value
This function returns TRUE if the thread exists and FALSE if it has terminated.
Remarks
None.
Example
None.
ThreaderIsThreadActive function
ThreaderIsThreadActive checks whether the selected thread is active and running inside the debugged
process.
Syntax
bool __stdcall ThreaderIsThreadActive(
HANDLE hThread
);
Parameters
hThread
[in] Handle of the thread whose execution state will be queried.
Return value
This function returns TRUE if the thread is running and FALSE if it has terminated or it is
suspended.
Remarks
None.
Example
None.
ThreaderIsAnyThreadActive function
ThreaderIsAnyThreadActive checks whether any thread in the debugged process is active and running.
Syntax
bool __stdcall ThreaderIsAnyThreadActive();
Parameters
None.
Return value
This function returns TRUE if any of the threads is running and FALSE if all threads are
suspended.
Remarks
None.
Example
None.
ThreaderIsExceptionInMainThread function
ThreaderIsExceptionInMainThread determines whether the last exception occurred inside the main
debugged process thread.
Syntax
bool __stdcall ThreaderIsExceptionInMainThread();
Parameters
None.
Return value
This function returns TRUE if the last exception occurred inside the main thread, FALSE if it
occurred in another running thread.
Remarks
None.
Example
None.
ThreaderGetOpenHandleForThread function
ThreaderGetOpenHandleForThread is used resolve the existing open handle for thread with the
specified ID.
Syntax
long long __stdcall ThreaderGetOpenHandleForThread(
DWORD ThreadId
);
Parameters
ThreadId
[in] ID of the active thread, returned from thread data enumeration or Windows API.
Return value
This function returns the handle of the specified thread or NULL if the thread doesn’t exist
anymore.
Remarks
None.
Example
None.
ThreaderSetCallBackForNextExitThreadEvent function
ThreaderSetCallBackForNextExitThreadEvent specifies a custom callback to call the next time an active
thread terminates.
Syntax
void __stdcall ThreaderSetCallBackForNextExitThreadEvent(
LPVOID exitThreadCallBack
);
Parameters
exitThreadCallBack
[in] Pointer to callback function to call when the next active thread terminates.
CallBack definition
typedef void(__stdcall *fCustomHandler)(void* SpecialDBG);
// Here SpecialDBG is defined as a pointer to &DBGEvent.u.ExitThread
Return value
None.
Remarks
None.
Example
None.
ThreaderCreateRemoteThreadEx function
ThreaderCreateRemoteThreadEx creates a new thread inside the targeted process.
Syntax
long long __stdcall ThreaderCreateRemoteThreadEx(
HANDLE hProcess,
ULONG_PTR ThreadStartAddress,
bool AutoCloseTheHandle,
LPVOID ThreadPassParameter,
LPDWORD ThreadId
);
Parameters
hProcess
[in] Handle of the process in which to create the thread.
ThreadStartAddress
[in] Start address at which to create the thread in the remote process.
AutoCloseTheHandle
[in] Boolean switch indicating whether or not to close the handle to this new remote
thread automatically.
ThreadPassParameter
[in] Parameter which to pass to newly created thread.
ThreadId
[in] Pointer to DWORD to hold the ID for the newly created thread.
Return value
This function returns handle for the new thread or NULL if the thread wasn’t created or
AutoCloseTheHandle was set to TRUE.
Remarks
None.
Example
None.
ThreaderCreateRemoteThread function
ThreaderCreateRemoteThread creates a new thread inside the process currently being debugged.
Syntax
long long __stdcall ThreaderCreateRemoteThreadEx(
ULONG_PTR ThreadStartAddress,
bool AutoCloseTheHandle,
LPVOID ThreadPassParameter,
LPDWORD ThreadId
);
Parameters
ThreadStartAddress
[in] Start address for the new thread located in the remote process.
AutoCloseTheHandle
[in] Boolean switch indicating whether or not to close the handle to to this new remote
thread automatically.
ThreadPassParameter
[in] Parameter which to pass to newly created thread.
ThreadId
[in] Pointer to DWORD to hold the ID for the newly created thread.
Return value
This function returns handle for the new thread or NULL if the thread wasn’t created or
AutoCloseTheHandle was set to TRUE.
Remarks
None.
Example
None.
ThreaderInjectAndExecuteCodeEx function
ThreaderInjectAndExecuteCodeEx creates a new thread inside the targeted process and auto-executes
the injected code.
Syntax
bool __stdcall ThreaderInjectAndExecuteCodeEx(
HANDLE hProcess,
LPVOID InjectCode,
DWORD StartDelta,
DWORD InjectSize
);
Parameters
hProcess
[in] Handle of the process in which the new thread will be created.
InjectedCode
[in] Pointer to the data to inject in the remote process.
StartDelta
[in] Used when you need to to execute the code from any other point other then the
first byte of the InjectedCode memory, the start address of the new thread will be
increased by this value.
InjectedSize
[in] Size of the memory the new thread will occupy in the remote process.
Return value
This function returns TRUE if the thread has been created and FALSE if there were problems.
Remarks
Before creating new thread data is allocated in targeted process and written there.
Example
None.
ThreaderInjectAndExecuteCode function
ThreaderInjectAndExecuteCode creates a new thread inside the currently debugged process and auto-
executes the injected code.
Syntax
bool __stdcall ThreaderInjectAndExecuteCode(
LPVOID InjectCode,
DWORD StartDelta,
DWORD InjectSize
);
Parameters
InjectedCode
[in] Pointer to the data to inject into the remote process.
StartDelta
[in] Start address of the new thread will be increased by this value. Use this option if
you need to execute the code from any other point other then the first byte of the
InjectedCode memory.
InjectedSize
[in] Size of the memory which will be injected inside the remote process.
Return value
This function returns TRUE if the thread has been created and FALSE if there were problems.
Remarks
Before creating new thread data is allocated in targeted process and written there.
Example
None.
ThreaderExecuteOnlyInjectedThreads function
The ThreaderExecuteOnlyInjectedThreads pause all active non injected threads inside the debugged
process making that process suspended. All threads that get injected after using this function will be
executed normally. Once all injected threads finish their execution process execution must be resumed
with ThreaderResumeProcess.
Syntax
bool __stdcall ThreaderExecuteOnlyInjectedThreads();
Parameters
None.
Return value
This function returns TRUE if all non injected threads get paused or FALSE if there are some
threads still running.
Remarks
None.
Example
None.
ThreaderImportRunningThreadData function
ThreaderImportRunningThreadData collects data about running threads for the specified process. This
function can be used to get data about remote process threads and manipulate them. However this
function overwrites internal data and should only be used if no program is being currently debugged.
Syntax
bool __stdcall ThreaderImportRunningThreadData(
DWORD ProcessId
);
Parameters
ProcessId
[in] Process ID of the running process which can be acquired with Windows API.
Return value
This function returns TRUE if the threads have been imported and FALSE if there were problems.
Remarks
This action removes ALL data about the threads and should only be used if no program is
debugged.
Example
None.
TLS module
TLS module has functions designed for working with thread local storage both on disk and in memory.
TLSBreakOnCallBack function
The TLSBreakOnCallBack sets a breakpoint on all TLS callbacks inside the PE header.
Syntax
bool __stdcall TLSBreakOnCallBack(
LPVOID ArrayOfCallBacks,
DWORD NumberOfCallBacks,
LPVOID bpxCallBack
);
Parameters
ArrayOfCallBacks
[in] Pointer to array of callbacks on which the breakpoints will be set.
NumberOfCallBacks
[in] Number of callbacks in the provided array.
bpxCallBack
[in] Address of the callback to call when each TLS breakpoint has been hit.
Return value
This function returns TRUE if the breakpoint has been set and FALSE if breakpoint cannot be set.
Remarks
None.
Example
None.
TLSBreakOnCallBackEx function
The TLSBreakOnCallBackEx sets a breakpoint on all TLS callbacks inside the PE header.
Syntax
bool __stdcall TLSBreakOnCallBackEx(
char* szFileName,
LPVOID bpxCallBack
);
Parameters
szFileName
[in] Pointer to the full path of the file to debug.
bpxCallBack
[in] Address of the callback to call when each TLS breakpoint has been hit.
Return value
This function returns TRUE if the breakpoint has been set and FALSE if breakpoint cannot be set.
Remarks
None.
Example
None.
TLSGrabCallBackData function
The TLSGrabCallBackData function is used to retrieve the TLS callbacks from the PE header.
Syntax
bool __stdcall TLSGrabCallBackData(
char* szFileName,
LPVOID ArrayOfCallBacks,
LPDWORD NumberOfCallBacks
);
Parameters
szFileName
[in] Pointer to a null terminated string which is the full path to the file whose TLS
callback data will be read and copied to the specified array.
ArrayOfCallBacks
[out] Pointer to array which will receive the callback addresses.
NumberOfCallBacks
[out] Number of callbacks in the TLS callback array.
Return value
This function returns TRUE if the breakpoint has been set and FALSE if breakpoint cannot be set.
Remarks
None.
Example
None.
TLSRemoveCallback function
The TLSRemoveCallback remove TLS callbacks from the PE header of the selected file.
Syntax
bool __stdcall TLSRemoveCallback(
char* szFileName
);
Parameters
szFileName
[in] Pointer to the full path of the file whose TLS callback table will be removed.
Return value
Boolean switch indicating whether or not the function was successful.
Remarks
None.
Example
None.
TLSRemoveTable function
The TLSRemoveTable removes TLS table from the PE header of the selected file.
Syntax
bool __stdcall TLSRemoveTable(
char* szFileName
);
Parameters
szFileName
[in] Pointer to the full path of the file whose TLS table will be removed.
Return value
Boolean switch indicating whether or not the function was successful.
Remarks
None.
Example
None.
TLSBackupData function
The TLSBackupData make an internal backup of the TLS table so that it can be restored at runtime if it
gets corrupted.
Syntax
bool __stdcall TLSBackupData(
char* szFileName
);
Parameters
szFileName
[in] Pointer to the full path of the file whose TLS table will be backed up.
Return value
Boolean switch indicating whether or not the function was successful.
Remarks
None.
Example
None.
TLSRestoreData function
The TLSRestoreData restore data from internal backup of the TLS table directly to running process
memory. In case of TLS table corruption this function can be used to restore the previously backed up
data.
Syntax
bool __stdcall TLSRestoreData();
Parameters
None.
Return value
Boolean switch indicating whether or not the function was successful.
Remarks
None.
Example
None.
TLSBuildNewTable function
The TLSBuildNewTable build and store completely new TLS table inside the selected PE file. This option
can be used to create a new TLS table in case of dealing with protections that use TLS elimination
protection technique.
Syntax
bool __stdcall TLSBuildNewTable(
ULONG_PTR FileMapVA,
ULONG_PTR StorePlace,
ULONG_PTR StorePlaceRVA,
LPVOID ArrayOfCallBacks,
DWORD NumberOfCallBacks
);
Parameters
FileMapVA
[in] Pointer to the mapped file content which must be mapped in read/write mode. This
pointer is set by using either StaticFileLoad function or Windows API for file
mapping.
StorePlace
[in] Physical address inside PE file on which the new TLS table will be written. Usually
this is a new section but can also be the part of the file which is unused but still in
read/write mode.
StorePlaceRVA
[in] Relative virtual address inside PE file on which the new TLS table will be written.
This input is just conversion from physical to relative virtual offset.
ArrayOfCallBacks
[in] Pointer to array of custom TLS callback.
NumberOfCallBacks
[in] Number of callbacks in the provided array.
Return value
Boolean switch indicating whether or not the function was successful.
Example
None.
TLSBuildNewTableEx function
The TLSBuildNewTableEx build and store completely new TLS table inside the selected PE file. This
option can be used to create a new TLS table in case of dealing with protections that use TLS elimination
protection technique.
Syntax
bool __stdcall TLSBuildNewTableEx(
char* szFileName,
char* szSectionName,
LPVOID ArrayOfCallBacks,
DWORD NumberOfCallBacks
);
Parameters
szFileName
[in] Pointer to string specifying the full path to the file in which to write the new TLS
table.
szSectionName
[in] The new TLS table will be written to a new PE section in the file specified by
szFileName. This variable specifies the name to use for the new section. The section
name may be up to 8 characters long.
ArrayOfCallBacks
[in] Pointer to array of custom TLS callback functions.
NumberOfCallBacks
[in] Number of callbacks in the specified array.
Return value
Boolean switch indicating whether or not the function was successful.
Remarks
None.
Example
None.
Librarian module
The Librarian module contains functions designed to manipulate loaded libraries, setting breakpoints for
specific library loading events, and retrieving information about loaded libraries.
Librarian module constants
Constants used by: LibrarianSetBreakPoint function and LibrarianRemoveBreakPoint function
#define UE_ON_LIB_LOAD 1
#define UE_ON_LIB_UNLOAD 2
#define UE_ON_LIB_ALL 3
Librarian module structures
Structure used by: LibrarianGetLibraryInfo function, LibrarianGetLibraryInfoEx function and
LibrarianEnumLibraryInfo function
typedef struct{
HANDLE hFile;
void* BaseOfDll;
HANDLE hFileMapping;
void* hFileMappingView;
char szLibraryPath[MAX_PATH];
char szLibraryName[MAX_PATH];
}LIBRARY_ITEM_DATA, *PLIBRARY_ITEM_DATA;
LibrarianSetBreakPoint function
LibrarianSetBreakPoint sets a breakpoint on a specific type of library event, such as library loading or
unloading.
Syntax
bool __stdcall LibrarianSetBreakPoint(
char* szLibraryName,
DWORD bpxType,
bool SingleShoot,
LPVOID bpxCallBack
);
Parameters
szLibraryName
[in] Name of the library to watch for specified events. For example kernel32.dll
bpxType
[in] Specifies the type of event on which the breakpoint will be triggered. Can be one of
the following: UE_ON_LIB_LOAD, UE_ON_LIB_UNLOAD or UE_ON_LIB_ALL.
SingleShoot
[in] Specifies whether the breakpoint will be executed only once, or each time the
specified event occurs.
bpxCallBack
[in] Address of the callback to call when the breakpoint is triggered.
CallBack definition
typedef void(__stdcall *fCustomBreakPoint)(void* SpecialDBG);
// SpecialDBG is a pointer to &DBGEvent.u.LoadDll
Return value
This function returns TRUE if the breakpoint is set and FALSE if breakpoint cannot be set.
Remarks
Maximum number of breakpoints is defined with MAX_LIBRARY_BPX.
LibrarianRemoveBreakPoint function
The LibrarianRemoveBreakPoint function is used to remove a breakpoint set on specific library events
such as library loading or unloading.
Syntax
bool __stdcall LibrarianRemoveBreakPoint(
char* szLibraryName,
DWORD bpxType
);
Parameters
szLibraryName
[in] Name of the library which was used as a breakpoint trigger. For example
kernel32.dll
bpxType
[in] Specifies the event on which the breakpoint was set. Can be one of the following:
UE_ON_LIB_LOAD, UE_ON_LIB_UNLOAD or UE_ON_LIB_ALL.
Return value
This function returns TRUE if the breakpoint has been removed and FALSE if breakpoint cannot
be removed which should never happen.
Remarks
Maximum number of breakpoints is defined with MAX_LIBRARY_BPX.
Example
None.
LibrarianGetLibraryInfo function
LibrarianGetLibraryInfo retrieves library item data for the modules loaded by the debugged process.
Syntax
void* __stdcall LibrarianGetLibraryInfo(
char* szLibraryName
);
Parameters
szLibraryName
[in] Name of the library loaded inside the debugged process. For example kernel32.dll
Return value
This function returns a pointer to a LIBRARY_ITEM_DATA structure or NULL if selected DLL
cannot be found.
Example
None.
LibrarianGetLibraryInfoEx function
LibrarianGetLibraryInfoEx retrieves additional library item data for the modules loaded by the debugged
process.
Syntax
void* __stdcall LibrarianGetLibraryInfoEx(
void* BaseOfDll
);
Parameters
BaseOfDll
[in] Base address at which the selected module is loaded in remote process.
Return value
This function returns the pointer to LIBRARY_ITEM_DATA structure or NULL if selected DLL
cannot be found.
Example
None.
LibrarianEnumLibraryInfo function
LibrarianEnumLibraryInfo enumerates data for all DLL files loaded by the debugged process. This list
contains data about only currently loaded modules. Unloaded modules are automatically removed from
the list.
Syntax
void __stdcall LibrarianEnumLibraryInfo(
void* EnumCallBack
);
Parameters
EnumCallBack
[in] Address of the callback function to use for processing loaded library data.
CallBack definition
typedef void(__stdcall *fEnumCallBack)(LPVOID fLibraryDetail);
// Here fLibraryDetail is a pointer to LIBRARY_ITEM_DATA structure
Return value
None.
Remarks
None.
Example
None.
Hooks module
The Hooks module has functions designed for in process function hooking. For hooking to be possible
entire engine or just TitaniumHooks must be loaded in the context of the process in which the hooks are
being applied.
Hooks module constants
Constants used by: HooksInsertNewRedirection function
#define TEE_HOOK_NRM_JUMP 1
#define TEE_HOOK_NRM_CALL 3
#define TEE_HOOK_IAT 5
#define TEE_MAXIMUM_HOOK_RELOCS 7
Hooks module structures
Structure used by: HooksGetHookEntryDetails function
typedef struct HOOK_ENTRY{
bool IATHook;
BYTE HookType;
DWORD HookSize;
void* HookAddress;
void* RedirectionAddress;
BYTE HookBytes[TEE_MAXIMUM_HOOK_SIZE];
BYTE OriginalBytes[TEE_MAXIMUM_HOOK_SIZE];
void* IATHookModuleBase;
DWORD IATHookNameHash;
bool HookIsEnabled;
bool HookIsRemote;
void* PatchedEntry;
DWORD RelocationInfo[TEE_MAXIMUM_HOOK_RELOCS];
int RelocationCount;
}HOOK_ENTRY, *PHOOK_ENTRY;
HooksSafeTransition function
HooksSafeTransition puts the running process in suspended state leaving only the thread that inserts
new hooks running. Once all the hooks are inserted paused process can be resumed by calling the same
function again. WARNING: Using this function to resume paused threads will cause all threads to be
resumed not only the ones paused by the previous use of the same function.
Syntax
bool __stdcall HooksSafeTransition(
LPVOID HookAddress,
bool TransitionStart
);
Parameters
HookAddress
[in] Single address which will be hooked inside this safe transition block. If there is more
than one hook to insert use the expert version of HookSafeTransition function.
TransitionStart
[in] Since the same function can be used to both pause and resume the process
execution this boolean switch indicates which of the two needs to be performed.
Return value
Boolean switch indicating whether or not the function was successful.
Remarks
None.
Example
None.
HooksSafeTransitionEx function
HooksSafeTransitionEx puts the running process in suspended state leaving only the thread that inserts
new hooks running. Once all the hooks are inserted paused process can be resumed by calling the same
function again. WARNING: Using this function to resume paused threads will cause all threads to be
resumed not only the ones paused by the previous use of the same function.
Syntax
bool __stdcall HooksSafeTransitionEx(
LPVOID HookAddressArray,
int NumberOfHooks,
bool TransitionStart
);
Parameters
HookAddressArray
[in] Array of addresses which will be hooked inside this safe transition block.
NumberOfHooks
[in] Number of items in the provided array.
TransitionStart
[in] Since the same function can be used to both pause and resume the process
execution this boolean switch indicates which of the two needs to be performed.
Return value
Boolean switch indicating whether or not the function was successful.
Remarks
None.
Example
None.
HooksDisableRedirection function
HooksDisableRedirection disables the selected hook. Original bytes are restored in the process and
therefore using this function in multithreaded environment is recommended only after transitioning to
safe patching mode.
Syntax
bool __stdcall HooksDisableRedirection(
LPVOID HookAddress,
bool DisableAll
);
Parameters
HookAddress
[in] Hooked address whose hook will be disabled.
DisableAll
[in] Boolean switch indicating whether or not to disable all installed hooks.
Return value
Boolean switch indicating whether or not the function was successful.
Remarks
None.
Example
None.
HooksDisableRedirectionsForModule function
HooksDisableRedirectionsForModule disables all installed hooks inside the selected module. Original
bytes are restored in the process and therefore using this function in multithreaded environment is
recommended only after transitioning to safe patching mode.
Syntax
bool __stdcall HooksDisableRedirectionsForModule(
HMODULE ModuleBase
);
Parameters
ModuleBase
[in] Base address of the loaded library whose hooks need disabling.
Return value
Boolean switch indicating whether or not the function was successful.
Remarks
Here module refers to loaded library which is hooked.
Example
None.
HooksDisableIATRedirection function
HooksDisableIATRedirection disables all installed hooks inside the selected module’s import address
table. Original bytes are restored in the process and therefore using this function in multithreaded
environment is recommended only after transitioning to safe patching mode.
Syntax
bool __stdcall HooksDisableIATRedirection(
char* szModuleName,
char* szHookFunction,
bool DisableAll
);
Parameters
szModuleName
[in] Name of the loaded module, for example: kernel32.dll
szHookFunction
[in] Name of the hooked function, for example: VirtualProtect
DisableAll
[in] Boolean switch indicating whether or not to disable all installed import address
hooks for the selected module.
Return value
Boolean switch indicating whether or not the function was successful.
Remarks
None.
Example
None.
HooksEnableRedirection function
HooksEnableRedirection enables the selected hook. Original bytes are restored in the process and
therefore using this function in multithreaded environment is recommended only after transitioning to
safe patching mode.
Syntax
bool __stdcall HooksEnableRedirection(
LPVOID HookAddress,
bool EnableAll
);
Parameters
HookAddress
[in] Hooked address whose hook will be disabled.
EnableAll
[in] Boolean switch indicating whether or not to enable all disabled hooks.
Return value
Boolean switch indicating whether or not the function was successful.
Remarks
None.
Example
None.
HooksEnableRedirectionsForModule function
HooksEnableRedirectionsForModule enables all disabled hooks inside the selected module. Original
bytes are restored in the process and therefore using this function in multithreaded environment is
recommended only after transitioning to safe patching mode.
Syntax
bool __stdcall HooksEnableRedirectionsForModule(
HMODULE ModuleBase
);
Parameters
ModuleBase
[in] Base address of the loaded library whose hooks need enabling.
Return value
Boolean switch indicating whether or not the function was successful.
Remarks
Here module refers to loaded library which is hooked.
Example
None.
HooksEnableIATRedirection function
HooksEnableIATRedirection enables all disabled hooks inside the selected module’s import address
table. Original bytes are restored in the process and therefore using this function in multithreaded
environment is recommended only after transitioning to safe patching mode.
Syntax
bool __stdcall HooksEnableIATRedirection(
char* szModuleName,
char* szHookFunction,
bool EnableAll
);
Parameters
szModuleName
[in] Name of the loaded module, for example: kernel32.dll
szHookFunction
[in] Name of the hooked function, for example: VirtualProtect
EnableAll
[in] Boolean switch indicating whether or not to enable all disabled import address
hooks for the selected module.
Return value
Boolean switch indicating whether or not the function was successful.
Remarks
None.
Example
None.
HooksRemoveRedirection function
HooksRemoveRedirection removes the selected hook. Original bytes are restored in the process and
therefore using this function in multithreaded environment is recommended only after transitioning to
safe patching mode.
Syntax
bool __stdcall HooksRemoveRedirection(
LPVOID HookAddress,
bool RemoveAll
);
Parameters
HookAddress
[in] Hooked address whose hook will be disabled.
RemoveAll
[in] Boolean switch indicating whether or not to remove all installed hooks.
Return value
Boolean switch indicating whether or not the function was successful.
Remarks
None.
Example
None.
HooksRemoveRedirectionsForModule function
HooksRemoveRedirectionsForModule removes all installed hooks inside the selected module. Original
bytes are restored in the process and therefore using this function in multithreaded environment is
recommended only after transitioning to safe patching mode.
Syntax
bool __stdcall HooksRemoveRedirectionsForModule(
HMODULE ModuleBase
);
Parameters
ModuleBase
[in] Base address of the loaded library whose hooks will be removed.
Return value
Boolean switch indicating whether or not the function was successful.
Remarks
Here module refers to loaded library which is hooked.
Example
None.
HooksRemoveIATRedirection function
HooksEnableIATRedirection removes all installed hooks inside the selected module’s import address
table. Original bytes are restored in the process and therefore using this function in multithreaded
environment is recommended only after transitioning to safe patching mode.
Syntax
bool __stdcall HooksRemoveIATRedirection(
char* szModuleName,
char* szHookFunction,
bool RemoveAll
);
Parameters
szModuleName
[in] Name of the loaded module, for example: kernel32.dll
szHookFunction
[in] Name of the hooked function, for example: VirtualProtect
RemoveAll
[in] Boolean switch indicating whether or not to remove all import address hooks for
the selected module.
Return value
Boolean switch indicating whether or not the function was successful.
Remarks
None.
Example
None.
HooksInsertNewRedirection function
HooksInsertNewRedirection installs a new hook on the selected address. Memory is changed in the
process of installing hooks and therefore using this function in multithreaded environment is
recommended only after transitioning to safe patching mode. You can only have one hook on the
selected address and therefore trying to hook the same address twice will result into this function
returning false indicating that the hook wasn’t installed.
Syntax
bool __stdcall HooksInsertNewRedirection(
LPVOID HookAddress,
LPVOID RedirectTo,
int HookType
;
Parameters
HookAddress
[in] Address which will be redirected by a hook.
RedirectTo
[in] Installed hook will redirect code execution to this address.
HookType
[in] Indicates which type of hook to use. Can be one of the following:
TEE_HOOK_NRM_JUMP or TEE_HOOK_NRM_CALL.
Return value
Boolean switch indicating whether or not the function was successful.
Remarks
None.
Example
None.
HooksInsertNewIATRedirectionEx function
HooksInsertNewIATRedirectionEx installs a new import address hook. Memory is changed in the
process of installing hooks and therefore using this function in multithreaded environment is
recommended only after transitioning to safe patching mode. You can only have one hook on the
selected address and therefore trying to hook the same address twice will result into this function
returning false indicating that the hook wasn’t installed.
Syntax
bool __stdcall HooksInsertNewIATRedirectionEx(
ULONG_PTR FileMapVA,
ULONG_PTR LoadedModuleBase,
char* szHookFunction,
LPVOID RedirectTo
);
Parameters
FileMapVA
[in] Pointer to the mapped file content which must be mapped in read/write mode. This
pointer is set by using either StaticFileLoad function or Windows API for file
mapping.
LoadedModuleBase
[in] Base address on which the module whose IAT is being patched is loaded on.
szHookFunction
[in] Name of the hooked function, for example: VirtualProtect
RedirectTo
[in] Installed hook will redirect code execution to this address.
Return value
Boolean switch indicating whether or not the function was successful.
Remarks
None.
Example
None.
HooksInsertNewIATRedirection function
HooksInsertNewIATRedirection installs a new import address hook. Memory is changed in the process
of installing hooks and therefore using this function in multithreaded environment is recommended only
after transitioning to safe patching mode. You can only have one hook on the selected address and
therefore trying to hook the same address twice will result into this function returning false indicating
that the hook wasn’t installed.
Syntax
bool __stdcall HooksInsertNewIATRedirection(
char* szModuleName,
char* szHookFunction,
LPVOID RedirectTo
);
Parameters
szModuleName
[in] Name of the loaded module, for example: kernel32.dll
szHookFunction
[in] Name of the hooked function, for example: VirtualProtect
RedirectTo
[in] Installed hook will redirect code execution to this address.
Return value
Boolean switch indicating whether or not the function was successful.
Remarks
None.
Example
None.
HooksGetTrampolineAddress function
HooksGetTrampolineAddress retrieves the trampoline address which can be called if the hooked
function needs to execute the original function and not just replace its functionality. This function is
used for both API and IAT hooks.
Syntax
void* __stdcall HooksGetTrampolineAddress(
LPVOID HookAddress
);
Parameters
HookAddress
[in] Address which was hooked for which the function will return the appropriate
trampoline.
Return value
Function returns trampoline address or NULL is there is no hook at the selected address.
Remarks
None.
Example
None.
HooksGetHookEntryDetails function
HooksGetHookEntryDetails retrieves the information about installed hooks. This function is used for all
hooks. Data returned can be manipulated to affect the hook state.
Syntax
void* __stdcall HooksGetHookEntryDetails(
LPVOID HookAddress
);
Parameters
HookAddress
[in] Address which was hooked for which the function will return the hook info.
Return value
Function returns the hook info or NULL is there is no hook at the selected address.
Remarks
None.
Example
None.
HooksScanModuleMemory function
HooksScanModuleMemory function scans the selected module memory for installed hooks which are
registered to internal hooking system. All found hooks are registered regardless of which component of
the program installed them. Therefore this can be used to uninstall existing hooks not inserted by the
Hooks module.
Syntax
void __stdcall HooksScanModuleMemory(
HMODULE ModuleBase,
LPVOID CallBack
);
Parameters
ModuleBase
[in] Base address of the loaded library whose memory will be scanned for hooks.
CallBack
[in] Pointer to the callback function to call for each found hook.
CallBack definition
typedef bool(__stdcall *fEnumCallBack)(PHOOK_ENTRY HookDetails, \
void* ptrOriginalInstructions, PLIBRARY_ITEM_DATA ModuleInformation, \
DWORD SizeOfImage);
Return value
None.
Remarks
None.
Example
None.
HooksScanEntireProcessMemory function
HooksScanEntireProcessMemory function scans the entire process memory for installed hooks which
are registered to internal hooking system. All found hooks are registered regardless of which component
of the program installed them. Therefore this can be used to uninstall existing hooks not inserted by the
Hooks module.
Syntax
void __stdcall HooksScanEntireProcessMemory(
LPVOID CallBack
);
Parameters
CallBack
[in] Pointer to the callback function to call for each found hook.
CallBack definition
typedef bool(__stdcall *fEnumCallBack)(PHOOK_ENTRY HookDetails, \
void* ptrOriginalInstructions, PLIBRARY_ITEM_DATA ModuleInformation, \
DWORD SizeOfImage);
Return value
None.
Remarks
None.
Example
None.
HooksScanEntireProcessMemoryEx function
HooksScanEntireProcessMemoryEx function scans the entire process memory for installed hooks which
are registered to internal hooking system. All found hooks are registered regardless of which component
of the program installed them. Therefore this can be used to uninstall existing hooks not inserted by the
Hooks module.
Syntax
void __stdcall HooksScanEntireProcessMemoryEx();
Parameters
None.
Return value
None.
Remarks
Found hooks are registered without any notification.
Example
None.
OEP Finder module
The OEP Finder module has functions designed for generic entry point finding.
FindOEPInit function
FindOEPInit initializes the OEP tracing process. It is not necessary to call it directly, since it will be
automatically called by the engine itself.
Syntax
void __stdcall FindOEPInit();
Parameters
None.
Return value
None.
Remarks
None.
Example
None.
FindOEPGenerically function
FindOEPGenerically finds the packed file's original entry point. There are some limitations to what
formats are supported. This function only supports packers which use LoadLibrary in order to load more
than just kernel32.dll. WARNING: It is possible for the file to execute when this function is called, so use
this function with caution!
Syntax
void __stdcall FindOEPGenerically(
char* szFileName,
LPVOID TraceInitCallBack,
LPVOID CallBack
);
Parameters
szFileName
[in] Pointer to the full path of the file whose entry point you want to find.
TraceInitCallBack
[in] Callback to call once the packed file hits its packed entry point.
CallBack
[in] Callback to call once the packed file hits its original entry point.
Return value
None.
Remarks
All callbacks used here are normal breakpoint callbacks. See SetBPX function for details.
Example
See RL!dePacke2 source code.
Process module
The Process module includes functions that enumerate processes and execute basic operations inside
the context of a remote process.
GetActiveProcessId function
GetActiveProcessId finds an active process using its image name.
Syntax
long __stdcall GetActiveProcessId(
char* szImageName
);
Parameters
szImageName
[in] The image name of the running process. For example explorer.exe
Return value
This function returns process ID if the process is running and found, or NULL if the image with
the specified name isn’t currently running.
Remarks
In case of multiple process images with the same name, this function always returns the ID of
the first one found.
Example
None.
EnumProcessesWithLibrary function
EnumProcessesWithLibrary enumerates all processes that have loaded the specified DLL image.
Syntax
void __stdcall EnumProcessesWithLibrary(
char* szLibraryName,
void* EnumFunction
);
Parameters
szLibraryName
[in] Name of the library in which you are interested. For example kernel32.dll
EnumFunction
[in] Address of a callback function that will process the data.
CallBack definition
typedef void(__stdcall *fEnumFunction)(DWORD ProcessId,
HMODULE ModuleBaseAddress);
Return value
None.
Remarks
None.
Example
None.
RemoteLoadLibrary function
RemoteLoadLibrary makes a remote process load the selected DLL file. This function injects a remote
thread in the selected process which calls LoadLibraryA in order to load the DLL file from disk.
Syntax
bool __stdcall RemoteLoadLibrary(
HANDLE hProcess,
char* szLibraryFile,
bool WaitForThreadExit
);
Parameters
hProcess
[in] Handle of the process in which the new thread that loads the DLL will be created.
szLibraryName
[in] Name of the library to load inside remote process. For example advapi32.dll
WaitForThreadExit
[in] Boolean switch indicating whether or not to wait for the remote thread to
terminate before returning from this function call.
Return value
Boolean switch indicating whether or not the function was successful.
Remarks
None.
Example
None.
RemoteFreeLibrary function
RemoteFreeLibrary make a remote process unload the selected DLL file. This function injects a remote
thread in the selected process. The thread calls FreeLibrary to unload the specified DLL file.
Syntax
bool __stdcall RemoteFreeLibrary(
HANDLE hProcess,
HMODULE hModule,
char* szLibraryFile,
bool WaitForThreadExit
);
Parameters
hProcess
[in] Handle of the process in which to create the new thread that will unload the DLL.
hModule
[in] Base address at which the DLL file is loaded in remote process.
szLibraryName
[in] Name of the library to unload from the remote process. For example advapi32.dll
WaitForThreadExit
[in] Boolean switch indicating whether or not to wait for the remote thread to
terminate before returning from this function call.
Return value
Boolean switch indicating whether or not the function was successful.
Remarks
You only need to specify the name or the base address of the module, not both.
Example
None.
RemoteExitProcess function
RemoteExitProcess injects a remote thread in the selected process to terminate the process by calling
ExitProcess.
Syntax
bool __stdcall RemoteExitProcess(
HANDLE hProcess,
DWORD ExitCode
);
Parameters
hProcess
[in] Handle of the process to terminate.
ExitCode
[in] Exit code that will be passed to the ExitProcess API. Can be NULL.
Return value
Boolean switch indicating whether or not the function was successful.
Remarks
None.
Example
None.
TranslateNativeName function
TranslateNativeName resolves the full path to a file using its native name. TranslateNativeName is used
to resolve paths that contain physical devices in their file references.
Syntax
void* __stdcall TranslateNativeName(
char* szNativeName
);
Parameters
szNativeName
[in] The native name of the file whose path you want to resolve.
Return value
Function returns a pointer to the decoded file name, or NULL if the supplied string can’t be
decoded.
Remarks
CAUTION: A string with the translated native name is stored inside the engine which makes this
function multi thread unsafe.
Example
None.
Dumper module
Dumper module has functions designed for the dumping process, region and module memory dumping.
This module also contains functions to aid in work with PE header specifics and file overlay.
Dumper module constants
Constants used by: GetPE32DataFromMappedFile function, GetPE32Data function,
SetPE32DataForMappedFile function, and SetPE32Data function.
#define UE_PE_OFFSET 0
#define UE_IMAGEBASE 1
#define UE_OEP 2
#define UE_SIZEOFIMAGE 3
#define UE_SIZEOFHEADERS 4
#define UE_SIZEOFOPTIONALHEADER 5
#define UE_SECTIONALIGNMENT 6
#define UE_IMPORTTABLEADDRESS 7
#define UE_IMPORTTABLESIZE 8
#define UE_RESOURCETABLEADDRESS 9
#define UE_RESOURCETABLESIZE 10
#define UE_EXPORTTABLEADDRESS 11
#define UE_EXPORTTABLESIZE 12
#define UE_TLSTABLEADDRESS 13
#define UE_TLSTABLESIZE 14
#define UE_RELOCATIONTABLEADDRESS 15
#define UE_RELOCATIONTABLESIZE 16
#define UE_TIMEDATESTAMP 17
#define UE_SECTIONNUMBER 18
#define UE_CHECKSUM 19
#define UE_SUBSYSTEM 20
#define UE_CHARACTERISTICS 21
#define UE_NUMBEROFRVAANDSIZES 22
#define UE_SECTIONNAME 23
#define UE_SECTIONVIRTUALOFFSET 24
#define UE_SECTIONVIRTUALSIZE 25
#define UE_SECTIONRAWOFFSET 26
#define UE_SECTIONRAWSIZE 27
#define UE_SECTIONFLAGS 28
Constants used by: GetPE32SectionNumberFromVA function
#define UE_VANOTFOUND -2
Dumper module structures
Structures used by: GetPE32DataFromMappedFileEx function, GetPE32DataEx function,
SetPE32DataForMappedFileEx function and SetPE32DataEx function.
typedef struct{
DWORD PE32Offset;
DWORD ImageBase;
DWORD OriginalEntryPoint;
DWORD NtSizeOfImage;
DWORD NtSizeOfHeaders;
WORD SizeOfOptionalHeaders;
DWORD FileAlignment;
DWORD SectionAligment;
DWORD ImportTableAddress;
DWORD ImportTableSize;
DWORD ResourceTableAddress;
DWORD ResourceTableSize;
DWORD ExportTableAddress;
DWORD ExportTableSize;
DWORD TLSTableAddress;
DWORD TLSTableSize;
DWORD RelocationTableAddress;
DWORD RelocationTableSize;
DWORD TimeDateStamp;
WORD SectionNumber;
DWORD CheckSum;
WORD SubSystem;
WORD Characteristics;
DWORD NumberOfRvaAndSizes;
}PE32Struct, *PPE32Struct;
Structures used by: GetPE32DataFromMappedFileEx function, GetPE32DataEx function,
SetPE32DataForMappedFileEx function and SetPE32DataEx function.
typedef struct{
DWORD PE64Offset;
DWORD64 ImageBase;
DWORD OriginalEntryPoint;
DWORD NtSizeOfImage;
DWORD NtSizeOfHeaders;
WORD SizeOfOptionalHeaders;
DWORD FileAlignment;
DWORD SectionAligment;
DWORD ImportTableAddress;
DWORD ImportTableSize;
DWORD ResourceTableAddress;
DWORD ResourceTableSize;
DWORD ExportTableAddress;
DWORD ExportTableSize;
DWORD TLSTableAddress;
DWORD TLSTableSize;
DWORD RelocationTableAddress;
DWORD RelocationTableSize;
DWORD TimeDateStamp;
WORD SectionNumber;
DWORD CheckSum;
WORD SubSystem;
WORD Characteristics;
DWORD NumberOfRvaAndSizes;
}PE64Struct, *PPE64Struct;
DumpProcess function
DumpProcess creates, for the currently running process, a memory dump in a file on disk. This image is
not a valid PE file, but a state of memory at the time the function is called.
Syntax
bool __stdcall DumpProcess(
HANDLE hProcess,
LPVOID ImageBase,
char* szDumpFileName,
ULONG_PTR EntryPoint
);
Parameters
hProcess
[in] Handle of the process whose memory will be dumped to disk.
ImageBase
[in] Default image base of the active file image from which to dump the memory. This
value should be read from the file on disk.
szDumpFileName
[in] Pointer to the full path of the file in which to write the memory content.
EntryPoint
[in] Virtual address which will be set to the new file's entry point. The size of this
variable varies, on x86 its 4 bytes and on x64 its 8 bytes. Therefore it can also be
declared as void*.
Return value
This function returns TRUE on successful dump and FALSE if the memory dump fails.
Remarks
None.
Example
None.
DumpProcessEx function
DumpProcessEx, for the specified running process, a memory dump in a file on disk. This image is not a
valid PE file, but a state of memory at the time the function is called.
Syntax
bool __stdcall DumpProcessEx(
DWORD ProcessId,
LPVOID ImageBase,
char* szDumpFileName,
ULONG_PTR EntryPoint
);
Parameters
ProcessId
[in] Process ID of the process, which can be acquired with the Windows API.
ImageBase
[in] Default image base of the active file image from which to dump the memory. This
value should be read from the file on disk.
szDumpFileName
[in] Pointer to the full path of the file in which to write the memory content.
EntryPoint
[in] Virtual address which will be set to the new file's entry point. The size of this
variable varies, on x86 its 4 bytes and on x64 its 8 bytes. Therefore it can also be
declared as void*.
Return value
This function returns TRUE on successful dump and FALSE if the memory dump fails.
Remarks
None.
Example
None.
DumpMemory function
DumpMemory creates memory dump to a file on disk which for a specified part of memory from the
running process.
Syntax
bool __stdcall DumpMemory(
HANDLE hProcess,
LPVOID MemoryStart,
ULONG_PTR MemorySize,
char* szDumpFileName
);
Parameters
hProcess
[in] Handle of the process whose memory will be dumped to disk.
MemoryStart
[in] Start of the memory range to dump. This does not need to be the start of a page.
MemorySize
[in] The size of memory to copy to disk. Size of this variable varies, on x86 its 4 bytes
and on x64 its 8 bytes. Therefore it can also be declared as SIZE_T.
szDumpFileName
[in] Pointer to the full path of the file in which to write the memory content.
Return value
This function returns TRUE on successful dump and FALSE if the memory dump fails.
Remarks
None.
Example
None.
DumpMemoryEx function
DumpMemoryEx dumps to a file on disk the specified part of memory from the specified running
process.
Syntax
bool __stdcall DumpMemoryEx(
DWORD ProcessId,
LPVOID MemoryStart,
ULONG_PTR MemorySize,
char* szDumpFileName
);
Parameters
ProcessId
[in] Process ID of the process whose memory you want to dump, which can be acquired
with the Windows API.
MemoryStart
[in] Start of the memory range dump to disk. This start does not have to be the start of a
page.
MemorySize
[in] Specifies the size of the memory to copy to disk. The size of this variable varies, on
x86 its 4 bytes and on x64 its 8 bytes. Therefore it can also be declared as SIZE_T.
szDumpFileName
[in] Pointer to the full path of the file in which to write the memory content.
Return value
This function returns TRUE on successful dump and FALSE if the memory dump fails.
Remarks
None.
Example
None.
DumpRegions function
DumpRegions creates a memory dump for all used memory regions in the specified running process.
The dump is written to a series of files in the specified folder on disk. Optionally this function can dump
only those regions located above the image base of the folder.
Syntax
bool __stdcall DumpRegions(
HANDLE hProcess,
char* szDumpFolder,
bool DumpAboveImageBaseOnly
);
Parameters
hProcess
[in] Handle of the process whose memory will be dumped to disk.
szDumpFolder
[in] Pointer to the full path of the folder in which to write the memory content. Each
region will be dumped into a separate file within this folder.
DumpAboveImageBaseOnly
[in] This variable is a switch which tells the engine which regions to dump. If its value is
FALSE it will dump all regions and if it is TRUE it will dump only regions above image
base of the targeted PE file.
Return value
This function returns TRUE on successful dump and FALSE if the memory dump fails.
Remarks
None.
Example
None.
DumpRegionsEx function
DumpRegionsEx creates a memory dump for all used memory regions in the specified running process.
The dump is written to a series of files in the specified folder on disk. Optionally this function can dump
only those regions located above the image base of the folder.
Syntax
bool __stdcall DumpRegionsEx(
DWORD ProcessId,
char* szDumpFolder,
bool DumpAboveImageBaseOnly
);
Parameters
ProcessId
[in] Process ID of the running process which can be acquired with Windows API.
szDumpFolder
[in] Pointer to the full path of the folder in which to write the memory content. Each
region will be dumped into a separate file within this folder.
DumpAboveImageBaseOnly
[in] This variable is a switch which tells the engine which regions to dump. If its value is
FALSE it will dump all regions and if it is TRUE it will dump only regions above image
base of the targeted PE file.
Return value
This function returns TRUE on successful dump and FALSE if the memory dump fails.
Remarks
None.
Example
None.
DumpModule function
DumpModule dumps to a file on disk the memory of one module within the specified running process.
This image is not a valid PE file, but the state of memory at the time this function is called.
Syntax
bool __stdcall DumpModule(
HANDLE hProcess,
LPVOID ModuleBase,
char* szDumpFileName
);
Parameters
hProcess
[in] Handle of the running process in which the module is running.
ModuleBase
[in] The base address of the loaded module in the specified process.
szDumpFileName
[in] Pointer to the full path of the file in which to write the module's memory content.
Return value
This function returns TRUE on a successful dump and FALSE if the memory dump fails.
Remarks
None.
Example
None.
DumpModuleEx function
DumpModuleEx dumps to a file on disk the memory of one module within the specified running
process. This image is not a valid PE file, but the state of memory at the time this function is called.
Syntax
bool __stdcall DumpModuleEx(
DWORD ProcessId,
LPVOID ModuleBase,
char* szDumpFileName
);
Parameters
ProcessId
[in] Process ID of the running process in which the module is loaded - can be acquired
with the Windows API.
ModuleBase
[in] The base address of the loaded module in the specified process.
szDumpFileName
[in] Pointer to the full path of the file in which to write the module's memory content.
Return value
This function returns TRUE on a successful dump and FALSE if the memory dump fails.
Remarks
None.
Example
None.
PastePEHeader function
PastePEHeader loads the PE header from a file on disk and writes it to running process memory. This
can be used to fix damage to PE header during process runtime. Such damage only occurs as a result of
memory protection algorithms used by some protection solutions.
Syntax
bool __stdcall PastePEHeader(
HANDLE hProcess,
LPVOID ImageBase,
char* szDebuggedFileName
);
Parameters
hProcess
[in] Handle of the process whose memory will be repaired.
ImageBase
[in] Default image base of the targeted PE file. This value should be read from the file on
disk.
szDebuggedFileName
[in] Pointer to the full path of the file from which the PE header will be read.
Return value
This function returns TRUE if the PE header is fixed and FALSE otherwise.
Remarks
None.
Example
None.
ExtractSection function
ExtractSection copies the physical content of the specified section in a file to a new file on disk.
Syntax
bool __stdcall ExtractSection(
char* szFileName,
char* szDumpFileName,
DWORD SectionNumber
);
Parameters
szFileName
[in] Pointer to the full path of the file from which the section will be extracted.
szDumpFileName
[in] Pointer to the full path of the file to which the section will be written.
SectionNumber
[in] Number of the section to extract. Section numbers range from zero to section count
minus one.
Return value
This function returns TRUE if the extraction succeeds, and FALSE if the extraction fails.
Remarks
None.
Example
None.
ResortFileSections function
ResortFileSections sorts a file's physical sections, putting them in the order of ascending physical offset.
This can be useful if there you need to add data to, or expand; the last logical section of the file, but it
isn’t physically located in the last physical section of the file.
Syntax
bool __stdcall ResortFileSections(
char* szFileName,
);
Parameters
szFileName
[in] Pointer to the full path of the file to re-sort.
Return value
This function returns TRUE on successful resort and FALSE if the sorting fails.
Remarks
The file's size doesn’t change, but its hash does, because sections will be physically moved to
new positions.
Example
None.
FindOverlay function
FindOverlay finds overlay data (extra data appended to the end of a PE file). This data can be the file
certificate or other important data that is useful for further file analysis.
Syntax
bool __stdcall FindOverlay(
char* szFileName,
LPDWORD OverlayStart,
LPDWORD OverlaySize
);
Parameters
szFileName
[in] Pointer to the full path of the file from which to extract any overlay data.
OverlayStart
[out] Pointer to a DWORD which will hold a file pointer that points to the overlay data.
This file pointer can be used with the Windows API to access the overlay.
OverlaySize
[out] Pointer to a DWORD to hold the size of the overlay.
Return value
This function returns TRUE if an overlay is found, FALSE if the overlay is not found.
Remarks
None.
Example
None.
ExtractOverlay function
ExtractOverlay finds overlay data (extra data appended to the end of a PE file) and copies it to new file.
This data can be the file certificate or other important data that is useful for further file analysis.
Syntax
bool __stdcall ExtractOverlay(
char* szFileName,
char* szExtactedFileName
);
Parameters
szFileName
[in] Pointer to a null terminated string which is a full path to file which will be queried
for overlay presence and whose overlay will be extracted.
szExtractedFileName
[in] Pointer to the full path of the file to hold the overlay content extracted from the
input file.
Return value
This function returns TRUE when overlay data is found and extracted and FALSE if the overlay is
not found or overlay export fails.
Remarks
The output file is always overwritten.
Example
None.
AddOverlay function
AddOverlay appends extracted overlay data to the end of PE files. This data can be the file certificate or
other important data that is useful for further file analysis.
Syntax
bool __stdcall AddOverlay(
char* szFileName,
char* szOverlayFileName
);
Parameters
szFileName
[in] Pointer to a null terminated string which is a full path to file which will be queried
for overlay presence and whose overlay will be extracted.
szOverlayFileName
[in] Pointer to the full path of the PE file to which the overlay content will be appended
(null terminated string).
Return value
This function returns TRUE if data is successfully appended and FALSE if one of the files is not
found.
Remarks
This function can also be used to merge two non PE files.
Example
None.
CopyOverlay function
CopyOverlay copies overlay data from one PE file to another. If target file already has overlay data, the
new data will be appended just after the existing data.
Syntax
bool __stdcall CopyOverlay(
char* szInFileName,
char* szOutFileName
);
Parameters
szInFileName
[in] Pointer to a null terminated string which is a full path to file which will be queried
for overlay presence and whose overlay will be copied.
szOutFileName
[in] Pointer to a null terminated string which is a full path to file to which new overlay
data will be appended.
Return value
This function returns TRUE if the data is successfully appended and FALSE if one of the files is
not found or not a PE file.
Remarks
None.
Example
None.
RemoveOverlay function
RemoveOverlay removes overlay data from PE files.
Syntax
bool __stdcall RemoveOverlay(
char* szFileName
);
Parameters
szFileName
[in] Pointer to the full path of the file which will be stripped of its overlay data.
Return value
This function returns TRUE if the overlay is removed and FALSE if overlay or file isn’t found.
Remarks
None.
Example
None.
MakeAllSectionsRWE function
MakeAllSectionsRWE sets the characteristics of all sections in a PE file to read/write/executable.
Syntax
bool __stdcall MakeAllSectionsRWE(
char* szFileName
);
Parameters
szFileName
[in] Pointer to the full path of the file whose PE sections will be set to
read/write/executable.
Return value
This function returns TRUE on success and FALSE if the file doesn’t exist or the PE header is
broken.
Remarks
None.
Example
None.
AddNewSectionEx function
AddNewSectionEx adds a new PE section to a file. The newly created section is physical and its content
is filled with zeroes if no content is specified. This reserved space can be used to store data later.
Syntax
long __stdcall AddNewSectionEx(
char* szFileName,
char* szSectionName,
DWORD SectionSize,
DWORD SectionAttributes,
LPVOID SectionContent,
DWORD ContentSize
);
Parameters
szFileName
[in] Pointer to a null terminated string which is a full path to file to which new section
will be added.
szSectionName
[in] Pointer to a null terminated string which will be the new section name. This string
can be up to 8 characters long.
SectionSize
[in] Size of the new section, both virtual and physical. Virtual size will be rounded up to
next modus of SectionAlignment, and physical size will be rounded up to next
modus of FileAlignment.
SectionAttributes
[in] Section attributes as defined by PECOFF 8. If this value is NULL, attributes will be set
to default read/write/execute 0xE0000020 value.
SectionContent
[in] Pointer to memory whose content will be copied to the newly created section. If
null, the new section will be filled with zeroes.
ContentSize
[in] Size of the memory whose content which will be copied to the new section.
Return value
This function returns the relative virtual offset of the newly created section, or NULL if adding
the new section fails.
AddNewSection function
AddNewSection adds a new physical PE section, filled with zeroes, to a file, creating space in the file
that can be used to store data later.
Syntax
long __stdcall AddNewSection(
char* szFileName,
char* szSectionName,
DWORD SectionSize
);
Parameters
szFileName
[in] Pointer to a null terminated string which is a full path to file to which new section
will be added.
szSectionName
[in] Pointer to a null terminated string to use as the new section name. This string can
be up to 8 characters long.
SectionSize
[in] Size of the new section, both virtual and physical. Virtual size will be rounded up to
next modus of SectionAlignment, and physical size will be rounded up to next
modus of FileAlignment.
Return value
This function returns relative virtual offset of the newly created section, or NULL if adding the
new section fails.
Remarks
None.
Example
None.
ResizeLastSection function
ResizeLastSection increases the size of the last PE file section in a file. The section is increased both
physically and virtually. Optionally, the new section's size can be aligned to FileAlignment.
Syntax
bool __stdcall ResizeLastSection(
char* szFileName,
DWORD NumberOfExpandBytes,
bool AlignResizeData
);
Parameters
szFileName
[in] Pointer to a null terminated string which is a full path to file whose last PE section
will be resized.
NumberOfExpandBytes
[in] Last section will be increased by this variable value.
AlignResizeData
[in] Set to TRUE to align the last section's size to FileAlignment.
Return value
This function returns TRUE on success and FALSE if the file doesn’t exist or the PE header is
broken.
Remarks
The file is backed up before modification, and restored if the file cannot be resized.
Example
None.
SetSharedOverlay function
SetSharedOverlay is used only to store string pointer provided to it. This function is from the old SDK
and is retained only for backward compatibility.
Syntax
void __stdcall SetSharedOverlay(
char* szFileName
);
Parameters
szFileName
[in] Pointer to the full path of a file. This string pointer will be stored in case other
modules need to retrieve it but have no direct access to the variable. The string
itself won’t be moved or modified so it must remain at that location for all time it is
needed.
Return value
This function has no return value.
Remarks
None.
Example
None.
GetSharedOverlay function
GetSharedOverlay is retrieves a store string pointer provided by SetSharedOverlay function. This
function is from the old SDK and is retained only for backward compatibility
Syntax
char* __stdcall GetSharedOverlay();
Parameters
None.
Return value
This function returns the previously stored pointer.
Remarks
None.
Example
None.
DeleteLastSection function
DeleteLastSection physically deletes the last PE section from the specified file.
Syntax
bool __stdcall DeleteLastSection(
char* szFileName
);
Parameters
szFileName
[in] Pointer to a null terminated string which is a full path to file whose last PE section
will be deleted.
Return value
This function returns TRUE on success and FALSE if the file doesn’t exist or the PE header is
broken.
Remarks
The file is backed up before modification and restored if the file cannot be resized.
Example
None.
DeleteLastSectionEx function
DeleteLastSectionEx physically deletes the selected number PE sections from the end of the specified
file.
Syntax
bool __stdcall DeleteLastSectionEx(
char* szFileName,
DWORD NumberOfSections
);
Parameters
szFileName
[in] Pointer to a null terminated string which is a full path to file whose last PE section(s)
will be deleted.
NumberOfSections
[in] Number of sections to remove from the end of the PE file.
Return value
This function returns TRUE on success and FALSE if the file doesn’t exist or the PE header is
broken.
Remarks
The file is backed up before modification and restored if the file cannot be resized.
Example
None.
GetPE32DataFromMappedFile function
GetPE32DataFromMappedFile retrieves data from the PE header for both x86 and x64 files.
Syntax
long long __stdcall GetPE32DataFromMappedFile(
ULONG_PTR FileMapVA,
DWORD WhichSection,
DWORD WhichData
);
Parameters
FileMapVA
[in] Pointer to the mapped file content. This pointer is set by using either StaticFileLoad
function or Windows API for file mapping. It is a ULONG_PTR which defines its size
on the x86 and x64 operating systems. On x86 systems this variable is 4 bytes long
and equal to DWORD, and on x64 platform this variable is 8 bytes long and equal to
DWORD64, but since this is a pointer, void* can also be used.
WhichSection
[in] Number of the first PE section from which to read the data. The first PE section is
section zero, so the section numbers range from zero to section count minus one.
WhichData
[in] Specifies which PE header info this function will return. The list of constants used by
this function is located at the beginning of this section under Dumper module
constants.
Return value
This function returns the requested PE data. The return variable should be defined as
ULONG_PTR which defines its size on x86 and x64 operating system.
Remarks
The file must be mapped before using this function.
GetPE32DataFromMappedFileEx function
The GetPE32DataFromMappedFileEx function is used to retrieve data from the PE header for both x86
and x64 files.
Syntax
bool __stdcall GetPE32DataFromMappedFileEx(
ULONG_PTR FileMapVA,
LPVOID DataStorage
);
Parameters
FileMapVA
[in] Pointer to the mapped file content. This pointer is set by using either StaticFileLoad
function or Windows API for file mapping. It is a ULONG_PTR which defines its size
on the x86 and x64 operating systems. On x86 systems this variable is 4 bytes long
and equal to DWORD, and on x64 platform this variable is 8 bytes long and equal to
DWORD64. But since this is a pointer, void* can also be used.
DataStorage
[in] Pointer to a structure to hold all PE header data. This structure is different for x86
and x64 systems. Its definition is located at the beginning of this section under
Dumper module structures.
Return value
This function returns TRUE on success and FALSE if the file doesn’t exist or the PE header is
broken.
Remarks
The file must be mapped before using this function.
Example
None.
GetPE32Data function
GetPE32Data retrieves data from the PE header for both x86 and x64 files.
Syntax
long long __stdcall GetPE32Data(
char* szFileName,
DWORD WhichSection,
DWORD WhichData
);
Parameters
szFileName
[in] Pointer to a null terminated string which is a full path to file from which PE header
data will be read.
WhichSection
[in] Number of the PE section from which data will be read. The first PE section is
section zero, so the section numbers range from zero to section count minus one.
WhichData
[in] Specifies which PE header info this function will return. The list of constants used by
this function is located at the beginning of this section under Dumper module
constants.
Return value
This function returns the PE header data. The return variable should be defined as ULONG_PTR
which defines its size on x86 and x64 operating system.
Remarks
None.
Example
None.
GetPE32DataEx function
The GetPE32DataEx function is used to retrieve data from the PE header for both x86 and x64 files.
Syntax
bool __stdcall GetPE32DataEx(
char* szFileName,
LPVOID DataStorage
);
Parameters
szFileName
[in] Pointer to a null terminated string which is a full path to file from which PE header
data will be read.
DataStorage
[in] Pointer to a structure to hold the PE header data. This structure is different for x86
and x64. Its definition is located at the beginning of this section under Dumper
module structures.
Return value
This function returns TRUE on success and FALSE if the file doesn’t exist or the PE header is
broken.
Remarks
None.
Example
None.
SetPE32DataForMappedFile function
The SetPE32DataFromMappedFile function is used to set data to PE header for both x86 and x64 files.
Syntax
bool __stdcall SetPE32DataForMappedFile(
ULONG_PTR FileMapVA,
DWORD WhichSection,
DWORD WhichData,
ULONG_PTR NewDataValue
);
Parameters
FileMapVA
[in] Pointer to the mapped file content. This pointer is set by using either StaticFileLoad
function or Windows API for file mapping. It is a ULONG_PTR which defines its size
on the x86 and x64 operating systems. On x86 systems this variable is 4 bytes long
and equal to DWORD, and on x64 platform this variable is 8 bytes long and equal to
DWORD64, but since this is a pointer void* can also be used.
WhichSection
[in] Number of the PE section from which data will be read. The first PE section is
section zero, so the section numbers range from zero to section count minus one.
WhichData
[in] Indicator on which PE header info this function will return. The list of constants
used by this function is located at the beginning of this section under Dumper
module constants.
NewDataValue
[in] Value which will be set for the selected PE header field.
Return value
This function returns TRUE on success and FALSE if the file doesn’t exist or the PE header is
broken.
Remarks
The file must be mapped before using this function.
SetPE32DataForMappedFileEx function
SetPE32DataForMappedFileEx stores the data from a PE header into a data structure, for both x86 and
x64 files.
Syntax
bool __stdcall SetPE32DataForMappedFileEx(
ULONG_PTR FileMapVA,
LPVOID DataStorage
);
Parameters
FileMapVA
[in] Pointer to the mapped file content you want to store. This pointer is set by using
either StaticFileLoad function or Windows API for file mapping. It is a ULONG_PTR
which defines its size on the x86 and x64 operating systems. On x86 systems this
variable is 4 bytes long and equal to DWORD, and on x64 platform this variable is 8
bytes long and equal to DWORD64. But since this is a pointer, void* can also be
used.
DataStorage
[in] Pointer to a structure that will hold the PE header data. Ideally this structure is first
filled by using GetPE32DataFromMappedFileEx. This structure is different for x86
and x64, its definition is located at the beginning of this section under Dumper
module structures.
Return value
This function returns TRUE on success and FALSE if the file doesn’t exist or the PE header is
broken.
Remarks
The file must be mapped before using this function.
Example
None.
SetPE32Data function
SetPE32Data sets data to the PE header for both x86 and x64 files.
Syntax
bool __stdcall SetPE32Data(
char* szFileName,
DWORD WhichSection,
DWORD WhichData
);
Parameters
szFileName
[in] Pointer to a null terminated string which is a full path to file whose PE header data
will be modified.
WhichSection
[in] Number of the PE section from which data will be read. The first PE section is
section zero, so the section numbers range from zero to section count minus one.
WhichData
[in] Indicator on which PE header info this function will return. Specifies which PE
header info this function will return. The list of constants used by this function is
located at the beginning of this section Dumper module constants.
Return value
This function returns TRUE on success and FALSE if the file doesn’t exist or the PE header is
broken.
Remarks
None.
Example
None.
SetPE32DataEx function
SetPE32DataEx sets data to the PE header for both x86 and x64 files.
Syntax
bool __stdcall SetPE32DataEx(
char* szFileName,
LPVOID DataStorage
);
Parameters
szFileName
[in] Pointer to a null terminated string which is a full path to file whose PE header data
will be modified.
DataStorage
[in] Pointer to a structure from which the PE header data is reset. Ideally this structure
is first filled by using GetPE32DataFromMappedFileEx function. This structure is
different for x86 and x64 and its definition is located at the beginning of this section
under Dumper module structures.
Return value
This function returns TRUE on success and FALSE if the file doesn’t exist or the PE header is
broken.
Remarks
None.
Example
None.
GetPE32SectionNumberFromVA function
GetPE32SectionNumberFromVA determines in which PE section the selected virtual address resides.
Syntax
long __stdcall GetPE32SectionNumberFromVA(
ULONG_PTR FileMapVA,
ULONG_PTR AddressToConvert
);
Parameters
FileMapVA
[in] Pointer to the mapped file content. This pointer is set by using either StaticFileLoad
function or Windows API for file mapping. It is a ULONG_PTR which defines its size
on the x86 and x64 operating systems. On x86 systems this variable is 4 bytes long
and equal to DWORD, and on x64 platform this variable is 8 bytes long and equal to
DWORD64. But since this is a pointer void* can also be used.
AddressToConvert
[in] Virtual address which will be located inside mapped file sections.
Return value
This function returns number of section in which virtual address resides or UE_VANOTFOUND.
The first PE section is section zero, so the section numbers range from zero to section count
minus one.
Remarks
The file must be mapped before using this function.
Example
None.
ConvertVAtoFileOffset function
ConvertVAtoFileOffset converts virtual addresses to its physical counterpart.
Syntax
long long __stdcall ConvertVAtoFileOffset(
ULONG_PTR FileMapVA,
ULONG_PTR AddressToConvert,
bool ReturnType
);
Parameters
FileMapVA
[in] Pointer to the mapped file content. This pointer is set by using either StaticFileLoad
function or Windows API for file mapping. It is a ULONG_PTR which defines its size
on the x86 and x64 operating systems.
AddressToConvert
[in] Virtual address to convert to a physical address.
ReturnType
[in] Boolean variable which indicates whether or not to add the FileMapVA to the
function's return value.
Return value
This function returns the converted physical address. Return variable should be defined as
ULONG_PTR which defines its size on x86 and x64 operating system. If ReturnType is FALSE this
value will never be larger than DWORD. If this function returns NULL conversion has failed.
Remarks
The file must be mapped before using this function.
Example
None.
ConvertVAtoFileOffsetEx function
ConvertVAtoFileOffsetEx converts virtual or relative virtual addresses to its physical counterpart. Using
this function is considered safer then ConvertVAtoFileOffset because it uses safety checks to ensure that
the PE file is valid and memory is there and accessible.
Syntax
long long __stdcall ConvertVAtoFileOffsetEx(
ULONG_PTR FileMapVA,
DWORD FileSize,
ULONG_PTR ImageBase,
ULONG_PTR AddressToConvert,
bool AddressIsRVA,
bool ReturnType
);
Parameters
FileMapVA
[in] Pointer to the mapped file content. This pointer is set by using either StaticFileLoad
function or Windows API for file mapping. It is a ULONG_PTR which defines its size
on the x86 and x64 operating systems.
FileSize
[in] Size of the mapped file.
ImageBase
[in] ImageBase of the mapped file, read directly from its PE header.
AddressToConvert
[in] Virtual address which to converted to its physical address.
AddressIsRVA
[in] Boolean variable which indicates whether the input address is relative or virtual.
Virtual is the default expected input.
ReturnType
[in] Boolean variable which indicates whether or not to add FileMapVA to function
return.
Return value
This function returns the converted physical address. Return variable should be defined as
ULONG_PTR which defines its size on x86 and x64 operating system. If ReturnType is FALSE this
value will never be larger than DWORD. If this function returns NULL conversion has failed.
ConvertFileOffsetToVA function
ConvertFileOffsetToVA converts a physical address to its virtual counterpart.
Syntax
long long __stdcall ConvertFileOffsetToVA(
ULONG_PTR FileMapVA,
ULONG_PTR AddressToConvert,
bool ReturnType
);
Parameters
FileMapVA
[in] Pointer to the mapped file content. This pointer is set by using either StaticFileLoad
function or Windows API for file mapping. It is a ULONG_PTR which defines its size
on the x86 and x64 operating systems.
AddressToConvert
[in] The physical address to convert to a virtual address. It must reside in address space
allocated with FileMapVA.
ReturnType
[in] Boolean variable which indicates whether or not to add ImageBase to the function's
return.
Return value
This function returns the converted virtual address. Return variable should be defined as
ULONG_PTR which defines its size on x86 and x64 operating system. If ReturnType is FALSE this
value will never be larger than DWORD. If this function returns NULL conversion has failed.
Remarks
The file must be mapped before using this function.
Example
None.
ConvertFileOffsetToVAEx function
ConvertFileOffsetToVAEx converts physical addresses to its virtual counterpart. Using this function is
considered safer then ConvertFileOffsetToVA because it does safety checks to ensure that the PE file is
valid and memory is there and accessible.
Syntax
long long __stdcall ConvertFileOffsetToVAEx(
ULONG_PTR FileMapVA,
DWORD FileSize,
ULONG_PTR ImageBase,
ULONG_PTR AddressToConvert,
bool ReturnType
);
Parameters
FileMapVA
[in] Pointer to the mapped file content. This pointer is set by using either StaticFileLoad
function or Windows API for file mapping. It is a ULONG_PTR which defines its size
on the x86 and x64 operating systems.
FileSize
[in] Size of the mapped file.
ImageBase
[in] ImageBase of the mapped file read directly from its PE header.
AddressToConvert
[in] Physical address which will be converted to virtual address. It must reside in address
space allocated with FileMapVA.
ReturnType
[in] Boolean variable which indicates whether or not to add ImageBase to function
return.
Return value
This function returns the converted virtual address. Return variable should be defined as
ULONG_PTR which defines its size on x86 and x64 operating system. If the ReturnType is FALSE
this value will never be larger than DWORD. If this function returns NULL conversion has failed.
Remarks
The file must be mapped before using this function.
Importer module
The Importer module has functions designed for import manipulation, forward handling, and automatic
import locating and fixing.
Importer module structures
Structure used by: ImporterEnumAddedData function
typedef struct{
bool NewDll;
int NumberOfImports;
ULONG_PTR ImageBase;
ULONG_PTR BaseImportThunk;
ULONG_PTR ImportThunk;
char* APIName;
char* DLLName;
}ImportEnumData, *PImportEnumData;
ImporterInit function
ImporterInit initializes the importer module. It must be used before using any of the functions that do
manual import fixing.
Syntax
void __stdcall ImporterInit(
DWORD MemorySize,
ULONG_PTR ImageBase
);
Parameters
MemorySize
[in] Default memory size allocated for each of the new DLLs files you add. This size must
be large enough to hold all data needed by the engine. Usually there is no need to
reserve more than 40kb of memory.
ImageBase
[in] Default image base of the targeted PE file. This value should be read from the file on
disk.
Return value
None.
Remarks
None.
Example
None.
ImporterSetImageBase function
ImporterSetImageBase updates information passed to the engine when the importer is initialized.
Syntax
void __stdcall ImporterSetImageBase(
ULONG_PTR ImageBase
);
Parameters
ImageBase
[in] Default image base of the targeted PE file. This value should be read from the file on
disk.
Return value
None.
Remarks
None.
Example
None.
ImporterAddNewDll function
ImporterAddNewDll adds new DLLs to the new import tree. This function creates a new DLL entry
making all subsequent ImporterAddNewAPI function calls add APIs to the current DLL. If you want to add
APIs that don’t belong to the current DLL, add a new DLL entry first. PECOFF specifications imply that
trunks are in a plus four (or eight on x64) sequence. The importer takes care of this automatically and
adds a new DLL entry equal to the last entered DLL if this sequence is broken.
Syntax
void __stdcall ImporterAddNewDll(
char* szDLLName,
ULONG_PTR FirstThunk
);
Parameters
szDLLName
[in] Pointer to string which is the name of the DLL to add to the new import tree. For
example: kernel32.dll or SomeFolder\mydll.dll in case of relative path loading.
FirstThunk
[in] Optional: address inside the PE file's memory that holds the pointer to an API
belonging to that DLL. This is the first pointer in the sequence. If set to NULL the
next call to ImporterAddNewAPI will set the first trunk to the data provided to it. If
the trunk is outside the PE file's memory you must use a special approach described
in examples.
Return value
None.
Remarks
None.
Example
None.
ImporterAddNewAPI function
ImporterAddNewAPI adds a new API to the current import tree. This function creates a new API entry
under currently selected DLL added by ImporterAddNewDLL. If the APIs don’t belong to the current DLL,
add a new DLL entry first. PECOFF specifications imply that trunks are in a plus four (or eight on x64)
sequence. The importer takes care of this automatically, and adds a new DLL entry equal to the last
entered DLL if this sequence is broken.
Syntax
void __stdcall ImporterAddNewAPI(
char* szAPIName,
ULONG_PTR ThunkValue
);
Parameters
szAPIName
[in] Pointer to string which is the name of the API to be added to the new import tree,
but belonging to current DLL. For example: VirtualProtect or VirtualAlloc, which are
added to the current DLL, which is in this case kernel32.dll
ThunkValue
[in] Mandatory parameter, specifying the address inside the PE file's memory that holds
the pointer to the API belonging to that DLL. In case the trunk is outside the PE file's
memory you must use a special approach described in examples.
Return value
None.
Remarks
None.
Example
None.
ImporterAddNewOrdinalAPI function
ImporterAddNewOrdinalAPI adds a new ordinal API to the current import tree. This function creates a
new API entry under currently selected DLL added by ImporterAddNewOrdinalAPI. If the APIs don’t
belong to the current DLL, add a new DLL entry first. PECOFF specifications imply that trunks are in a
plus four (or eight on x64) sequence. The importer takes care of this automatically, and adds a new DLL
entry equal to the last entered DLL if this sequence is broken.
Syntax
void __stdcall ImporterAddNewOrdinalAPI(
ULONG_PTR OrdinalNumber,
ULONG_PTR ThunkValue
);
Parameters
OrdinalNumber
[in] API ordinal number to be added. Can have a IMAGE_ORDINAL_FLAG mask.
ThunkValue
[in] Mandatory parameter, specifying the address inside the PE file's memory that holds
the pointer to the API belonging to that DLL. In case the trunk is outside the PE file's
memory you must use a special approach described in examples.
Return value
None.
Remarks
None.
Example
None.
ImporterGetLastAddedDLLName function
ImporterGetLastAddedDLLName retrieves the name of the last added DLL in the current importer tree.
Syntax
void* __stdcall ImporterGetLastAddedDLLName();
Parameters
None.
Return value
Pointer to string holding the last added DLL name.
Remarks
CAUTION: A string with the DLL name is stored inside the engine which makes this function
multi thread unsafe.
Example
None.
ImporterGetAddedDllCount function
ImporterGetAddedDllCount gets the current number of added DLLs inside the import tree.
Syntax
long __stdcall ImporterGetAddedDllCount();
Parameters
None.
Return value
Returns the number of added DLLs inside the import tree.
Remarks
None.
Example
None.
ImporterGetAddedAPICount function
ImporterGetAddedAPICount gets the current number of added APIs inside the import tree.
Syntax
long __stdcall ImporterGetAddedAPICount();
Parameters
None.
Return value
Returns the number of added APIs inside the import tree.
Remarks
None.
Example
None.
ImporterEnumAddedData function
ImporterEnumAddedData enumerates all added import tree data and calls the designated callback for
each one, with the details about it.
Syntax
void __stdcall ImporterEnumAddedData(
LPVOID EnumCallBack
);
Parameters
EnumCallBack
[in] Address of a callback function that will process the added import data.
CallBack definition
typedef void(__stdcall *fEnumCallBack)(LPVOID ptrImportEnumData);
typedef struct{
bool NewDll; // Indicator on if the dll has changed
int NumberOfImports;
ULONG_PTR ImageBase;
ULONG_PTR BaseImportThunk; // Original first trunk
ULONG_PTR ImportThunk; // Current import trunk
char* APIName;
char* DLLName;
}ImportEnumData, *PImportEnumData;
Return value
None.
Remarks
Strings with the API and the DLL name is stored inside the engine which makes this function
multi thread unsafe.
ImporterEstimatedSize function
ImporterEstimatedSize estimates the size of memory needed to write the import data. This value can be
used to determine the size of the new section in which the import data will be written.
Syntax
long __stdcall ImporterEstimatedSize();
Parameters
None.
Return value
Returns the size needed to write the import data.
Remarks
None.
Example
None.
ImporterCleanup function
ImporterCleanup clears all added DLLs and APIs from the import tree. This resets the inputted data to its
original state. Before using the functions to add the data to import tree, you must initialize the importer
again.
Syntax
void __stdcall ImporterCleanup();
Parameters
None.
Return value
None.
Remarks
None.
Example
None.
ImporterExportIATEx function
ImporterExportIATEx exports the added import data to existing PE file creating the valid import table for
the selected PE file. After this function has executed, the import data will be cleared by using the
ImporterCleanup function.
Syntax
bool __stdcall ImporterExportIATEx(
char* szExportFileName,
char* szSectionName
);
Parameters
szExportFileName
[in] Pointer to string which is a full path to the file to which new import table will be
written. This file is usually created by using DumpProcess.
szSectionName
[in] Name of the PE section in which the new import table content will be written. This
section will be added to the file. Length of this string is capped at 8 characters.
Return value
Boolean switch indicating whether or not the function was successful.
Remarks
None.
Example
None.
ImporterExportIAT function
ImporterExportIAT exports the added import data to the existing PE file creating the valid import table
for the selected PE file. After this function has executed, the import data will be cleared by using
ImporterCleanup function.
Syntax
bool __stdcall ImporterExportIAT(
ULONG_PTR StorePlace,
ULONG_PTR FileMapVA
);
Parameters
StorePlace
[in] Physical address inside PE file on which the new import table will be written.
Usually this is a new section, but it can also be an unused part of the file that is still
in read/write mode.
FileMapVA
[in] Pointer to the mapped file content, which must be mapped, in read/write mode.
This pointer is set by using either StaticFileLoad function or Windows API for file
mapping. It is a ULONG_PTR which defines its size on the x86 and x64 operating
systems. On x86 systems this variable is 4 bytes long and equal to DWORD, and on
x64 platform this variable is 8 bytes long and equal to DWORD64, but since this is a
pointer void* can also be used.
Return value
Boolean switch indicating whether or not the function was successful.
Remarks
None.
Example
None.
ImporterGetDLLName function
ImporterGetDLLName returns the name of the DLL in which address supplied to the function resides in.
This address is usually the pointer to API located inside the import table of the file whose IAT you are
fixing.
Syntax
void* __stdcall ImporterGetDLLName(
ULONG_PTR APIAddress
);
Parameters
APIAddress
[in] Address on which possible API is located. This address is equal to the address
returned by the GetProcAddress Windows API for DLL and the function of interest.
Return value
Pointer to string, which is the name of the DLL which holds the API located at specified address
or NULL if no DLL is found.
Remarks
String with the DLL name is stored inside the engine which makes this function multi thread
unsafe. Process which is searched for the DLL is always the currently debugged process.
Example
ImporterGetDLLName(GetProcAddress(GetModuleHandleA(“kernel32.dll”), “VirtualAlloc”));
This will return a pointer to “kernel32.dll” string, without the quotes. Example can fail in ASLR
environment since API address must reside inside the debugged process, therefore if used like
this local API address inside debugger must be relocated to remote one inside the debugge.
ImporterGetAPIName function
ImporterGetAPIName returns the name of the API whose address is supplied to the function. This
address is usually the pointer to API located inside the import table of the file whose IAT you are fixing.
Syntax
void* __stdcall ImporterGetAPIName(
ULONG_PTR APIAddress
);
Parameters
APIAddress
[in] Address on which possible API is located. This address is equal to the address
returned by the GetProcAddress Windows API for DLL and the function of interest.
Return value
Pointer to string, which is the name of the API located at specified address or NULL if no API is
found.
Remarks
String with the API name is stored inside the engine which makes this function multi thread
unsafe. Process which is searched for the API is always the currently debugged process.
Example
ImporterGetAPIName(GetProcAddress(GetModuleHandleA(“kernel32.dll”), “VirtualAlloc”));
This will return a pointer to “VirtualAlloc” string, without the quotes. Example can fail in ASLR
environment since API address must reside inside the debugged process, therefore if used like
this local API address inside debugger must be relocated to remote one inside the debugge.
ImporterGetAPINameEx function
ImporterGetAPINameEx returns the name of the API whose address is supplied to the function. This
address is usually the pointer to API located inside the import table of the file whose IAT you are fixing.
Expert version of this function only searches for API in the provided module list. This list is compiled of
DLL module base addresses from the debugged process.
Syntax
void* __stdcall ImporterGetAPINameEx(
ULONG_PTR APIAddress,
ULONG_PTR DLLBasesList
);
Parameters
APIAddress
[in] Address on which possible API is located. This address is equal to address returned
by GetProcAddress Windows API for DLL and function of interest.
DLLBasesList
[in] Pointer to array of module base addresses inside the remote process. This list is
either manually compiled or generated with EnumProcessModules Windows API.
Return value
Pointer to string which is the name of the API located at supplied address or NULL if no API is
found.
Remarks
String with the API name is stored inside the engine which makes this function multi thread
unsafe. Process which is searched for the API is always the currently debugged process.
Example
None.
ImporterGetAPIOrdinalNumber function
ImporterGetAPIOrdinalNumber returns the ordinal number of the API whose address is supplied to the
function. This address is usually the pointer to API located inside the import table of the file whose IAT
you are fixing.
Syntax
long long __stdcall ImporterGetAPIOrdinalNumber(
ULONG_PTR APIAddress
);
Parameters
APIAddress
[in] Address on which possible API is located. This address is equal to address returned
by GetProcAddress Windows API for DLL and function of interest.
Return value
Ordinal number of the API located at supplied address or minus one if no API is found.
Remarks
None.
Example
None.
ImporterGetRemoteAPIAddress function
ImporterGetRemoteAPIAddress realigns the local API address to remote one inside the debugged
process. This function is usefully in cases when local and remote DLL are not loaded on the same base
address or in case of ASLR. Keep in mind that your process might not have loaded all the remote DLL
files so that this function cannot be used in case that module in which the API resides isn’t loaded.
Syntax
long long __stdcall ImporterGetRemoteAPIAddress(
HANDLE hProcess,
ULONG_PTR APIAddress
);
Parameters
hProcess
[in] Handle of the process whose modules will be searched for the supplied API.
APIAddress
[in] Address on which API is located. This address is equal to address returned by
GetProcAddress Windows API for DLL and function of interest.
Return value
Realigned API address matching the API address inside the debugged process.
Remarks
None.
Example
None.
ImporterGetRemoteAPIAddressEx function
ImporterGetRemoteAPIAddressEx retrieves the remote API address from any module that debugged
process has loaded. There is no need to have the remote DLL loaded locally in order to use this function.
Syntax
long long __stdcall ImporterGetRemoteAPIAddressEx(
char* szDLLName,
char* szAPIName
);
Parameters
szDLLName
[in] Name of the remote DLL file which contains the needed API.
szAPIName
[in] Name of the API inside the remote DLL whose address inside the remote process
will be returned.
Return value
Remote API address matching the API address inside the debugged process.
Remarks
None.
Example
None.
ImporterGetLocalAPIAddress function
ImporterGetLocalAPIAddress is used relocate the remote API address to local one. This is used when
the remote module is loaded inside the debugger and you need to know the local address of that
remote API, which is usefully in cases when local and remote DLL are not loaded on the same base
address or in case of ASLR.
Syntax
long long __stdcall ImporterGetLocalAPIAddress(
HANDLE hProcess,
ULONG_PTR APIAddress
);
Parameters
hProcess
[in] Handle of the process whose modules will be searched for the supplied API.
APIAddress
[in] Address on which API is located in the remote process. This address is equal to
address returned by GetProcAddress Windows API for DLL and function of interest if
called in debugged process.
Return value
Local API address for the remotely found API or NULL if that API can’t be found in your process.
Remarks
None.
Example
None.
ImporterGetDLLNameFromDebugee function
ImporterGetDLLNameFromDebugee gets the name of the remote DLL which has the selected API.
Address of the API is the remote one so this function can be used to query if the remote address is an
API pointer.
Syntax
void* __stdcall ImporterGetDLLNameFromDebugee(
HANDLE hProcess,
ULONG_PTR APIAddress
);
Parameters
hProcess
[in] Handle of the process whose modules will be searched for the supplied API.
APIAddress
[in] Address on which API is located in the remote process. This address is equal to
address returned by GetProcAddress Windows API for DLL and function of interest if
called in debugged process.
Return value
Pointer to string which is the name of the DLL that holds API located at supplied address or NULL
if no API is found.
Remarks
String with the DLL name is stored inside the engine which makes this function multi thread
unsafe.
Example
None.
ImporterGetAPINameFromDebugee function
ImporterGetAPINameFromDebugee resolves the API name for the remote process API pointer. Address
of the API is the remote one so this function can be used to query if the remote address is an API
pointer.
Syntax
void* __stdcall ImporterGetAPINameFromDebugee(
HANDLE hProcess,
ULONG_PTR APIAddress
);
Parameters
hProcess
[in] Handle of the process whose modules will be searched for the supplied API.
APIAddress
[in] Address on which API is located in the remote process. This address is equal to
address returned by GetProcAddress Windows API for DLL and function of interest if
called in debugged process.
Return value
Pointer to string which is the name of the API that is located at supplied address or NULL if no
API is found.
Remarks
String with the API name is stored inside the engine which makes this function multi thread
unsafe.
Example
None.
ImporterGetAPIOrdinalNumberFromDebugee function
ImporterGetAPIOrdinalNumberFromDebugee resolves the API ordinal number for the remote process
API pointer. Address of the API is the remote one so this function can be used to query if the remote
address is an API pointer.
Syntax
void* __stdcall ImporterGetAPIOrdinalNumberFromDebugee(
HANDLE hProcess,
ULONG_PTR APIAddress
);
Parameters
hProcess
[in] Handle of the process whose modules will be searched for the supplied API.
APIAddress
[in] Address on which API is located in the remote process. This address is equal to
address returned by GetProcAddress Windows API for DLL and function of interest if
called in debugged process.
Return value
Ordinal number of the API that is located at supplied address or minus one if no API is found.
Remarks
None.
Example
None.
ImporterGetDLLIndexEx function
ImporterGetDLLIndexEx identify in which DLL of the module list selected API is located. Process which is
searched for the API is always the currently debugged process.
Syntax
long __stdcall ImporterGetDLLIndexEx(
ULONG_PTR APIAddress,
ULONG_PTR DLLBasesList
);
Parameters
APIAddress
[in] Address on which API is located in the remote process. This address is equal to
address returned by GetProcAddress Windows API for DLL and function of interest if
called in debugged process.
DLLBasesList
[in] Pointer to array of module base addresses inside the remote process. This list is
either manually compiled or generated with EnumProcessModules Windows API.
Return value
Function returns the index of the DLL in the list to which selected API belongs to or NULL if API
isn’t valid or found in the provided DLL list.
Remarks
List contains items with indexes going from zero to list count but first (zero) item is ignored
because it is usually the base address of the debugged executable module. If API is found in the
provided list return can only be greater or equal to one.
Example
HMODULE mList[3] = {0x00400000, 0x7E000000, 0x7F000000};
ImporterGetDLLIndexEx(0x7E555105, & mList);
Function call would return one because the API on 0x7E555105 belongs to second module.
ImporterGetDLLIndex function
ImporterGetDLLIndex identify in which DLL of the module list selected API is located.
Syntax
long __stdcall ImporterGetDLLIndex(
HANDLE hProcess,
ULONG_PTR APIAddress,
ULONG_PTR DLLBasesList
);
Parameters
hProcess
[in] Handle of the process whose modules will be searched for the supplied API.
APIAddress
[in] Address on which API is located in the remote process. This address is equal to
address returned by GetProcAddress Windows API for DLL and function of interest if
called in debugged process.
DLLBasesList
[in] Pointer to array of module base addresses inside the remote process. This list is
either manually compiled or generated with EnumProcessModules Windows API.
Return value
Function returns the index of the DLL in the list to which selected API belongs to or NULL if API
isn’t valid or found in the provided DLL list.
Remarks
List contains items with indexes going from zero to list count but first (zero) item is ignored
because it is usually the base address of the debugged executable module. If API is found in the
provided list return can only be greater or equal to one.
Example
None.
ImporterGetRemoteDLLBase function
ImporterGetRemoteDLLBase gets the remote DLL base for a locally loaded DLL file. In this case
debugger and the debugged process load the same module but due to Windows nature those two can
be loaded on two different base addresses so we use this function to resolve the module base for the
remote process. It is commonly used to get remote module bases for system DLL files in ASLR
environment.
Syntax
long long __stdcall ImporterGetRemoteDLLBase(
HANDLE hProcess,
HMODULE LocalModuleBase
);
Parameters
hProcess
[in] Handle of the process which will be queried for local module presence.
LocalModuleBase
[in] Handle of the local DLL file which will be searched for in the remote process.
Return value
Function returns the remote DLL base for the locally loaded module or NULL if module isn’t
found.
Remarks
None.
Example
None.
ImporterGetRemoteDLLBaseEx function
ImporterGetRemoteDLLBaseEx gets the remote DLL base for a specified file. This function does not
require that the remote module is loaded locally.
Syntax
long long __stdcall ImporterGetRemoteDLLBaseEx(
HANDLE hProcess,
char* szModuleName
);
Parameters
hProcess
[in] Handle of the process which will be queried for local module presence.
szModuleName
[in] Name of the module inside the remote process whose loaded base address will be
returned.
Return value
Function returns the remote DLL base for the specified module or NULL if module isn’t found.
Remarks
None.
Example
None.
ImporterIsForwardedAPI function
ImporterIsForwardedAPI checks if the supplied API address is forwarded from another top level
dynamic link library to lower system one. Usually forwarders can be found in kernel32.dll which are
forwarded to ntdll.dll. These APIs are automatically resolved to correct APIs by the engine itself.
Syntax
bool __stdcall ImporterIsForwardedAPI(
HANDLE hProcess,
ULONG_PTR APIAddress
);
Parameters
hProcess
[in] Handle of the process which will be inspected for API forwarding.
APIAddress
[in] Address on which API is located in the remote process. This address is equal to
address returned by GetProcAddress Windows API for DLL and function of interest if
called in debugged process.
Return value
Function returns TRUE if API is forwarded and FALSE if it isn’t.
Remarks
None.
Example
hModule = GetModuleHandleA(“ntdll.dll”);
ImporterIsForwardedAPI(hProcess, GetProcAddress(hModule, “RtlAllocateHeap”));
Function would return TRUE because this API is a forward for kernel32.HeapAlloc
ImporterGetForwardedAPIName function
ImporterGetForwardedAPIName retrieves the name of the forwarded API.
Syntax
void* __stdcall ImporterGetForwardedAPIName(
HANDLE hProcess,
ULONG_PTR APIAddress
);
Parameters
hProcess
[in] Handle of the process which will be inspected for API forwarding.
APIAddress
[in] Address on which API is located in the remote process. This address is equal to
address returned by GetProcAddress Windows API for DLL and function of interest if
called in debugged process.
Return value
Pointer to string which is the name of the API forwarded for supplied address or NULL if no API
is found.
Remarks
None.
Example
hModule = GetModuleHandleA(“ntdll.dll”);
ImporterGetForwardedAPIName(hProcess, GetProcAddress(hModule, “RtlAllocateHeap”));
Function would return HeapAlloc because this API is a forward for kernel32.HeapAlloc
ImporterGetForwardedAPIOrdinalNumber function
ImporterGetForwardedAPIOrdinalNumber retrieves the ordinal number of the forwarded API.
Syntax
long long __stdcall ImporterGetForwardedAPIOrdinalNumber(
HANDLE hProcess,
ULONG_PTR APIAddress
);
Parameters
hProcess
[in] Handle of the process which will be inspected for API forwarding.
APIAddress
[in] Address on which API is located in the remote process. This address is equal to
address returned by GetProcAddress Windows API for DLL and function of interest if
called in debugged process.
Return value
Ordinal number name of the API forwarded for supplied address or minus one if no API is found.
Remarks
None.
Example
None.
ImporterGetForwardedDLLName function
ImporterGetForwardedDLLName retrieves the name of DLL which holds the forwarded API.
Syntax
void* __stdcall ImporterGetForwardedDLLName(
HANDLE hProcess,
ULONG_PTR APIAddress
);
Parameters
hProcess
[in] Handle of the process which will be inspected for API forwarding.
APIAddress
[in] Address on which API is located in the remote process. This address is equal to
address returned by GetProcAddress Windows API for DLL and function of interest if
called in debugged process.
Return value
Pointer to string which is the name of the DLL which holds that API forwarded for supplied
address or NULL if no DLL is found.
Remarks
None.
Example
hModule = GetModuleHandleA(“ntdll.dll”);
ImporterGetForwardedDLLName(hProcess, GetProcAddress(hModule, “RtlAllocateHeap”));
Return would be kernel32.dll because this API is in that DLL as a forward for kernel32.HeapAlloc
ImporterGetForwardedDLLIndex function
ImporterGetForwardedDLLIndex retrieves the index of the DLL in the module list which holds the
forwarded API.
Syntax
long __stdcall ImporterGetForwardedDLLIndex(
HANDLE hProcess,
ULONG_PTR APIAddress,
ULONG_PTR DLLBasesList
);
Parameters
hProcess
[in] Handle of the process which will be inspected for API forwarding.
APIAddress
[in] Address on which API is located in the remote process. This address is equal to
address returned by GetProcAddress Windows API for DLL and function of interest if
called in debugged process.
DLLBasesList
[in] Pointer to array of module base addresses inside the remote process. This list is
either manually compiled or generated with EnumProcessModules Windows API.
Return value
Function returns the index of the DLL in the list to which resolved API forwarder belongs to or
NULL if API isn’t valid or found in the provided DLL list.
Remarks
List contains items with indexes going from zero to list count but first (zero) item is ignored
because it is usually the base address of the debugged executable module. If API is found in the
provided list return can only be greater or equal to one.
Example
None.
ImporterFindAPIWriteLocation function
ImporterFindAPIWriteLocation searches through the list of added APIs by ImporterAddNewAPI in order
to locate the trunk location for already added API.
Syntax
long long __stdcall ImporterFindAPIWriteLocation(
char* szAPIName
);
Parameters
szAPIName
[in] Pointer to string which is the name of the API on which has been added to import
tree, for example VirtualAlloc.
Return value
Function returns the address on which the import trunk for selected API is written or NULL is
that API wasn’t added to import tree.
Remarks
None.
Example
None.
ImporterFindOrdinalAPIWriteLocation function
ImporterFindOrdinalAPIWriteLocation searches through the list of added APIs by ImporterAddNewAPI
in order to locate the name of the added API by using its trunk location.
Syntax
long long __stdcall ImporterFindOrdinalAPIWriteLocation(
ULONG_PTR OrdinalNumber
);
Parameters
OrdinalNumber
[in] Ordinal number for which the write address will be located. This was the ordinal
number passed to ImporterAddNewAPI or ImporterAddNewDLL at the time of
adding that API.
Return value
Function returns the address on which the selected ordinal API is written or NULL is that ordinal
number wasn’t added to import tree.
Remarks
Function assumes that ordinal numbers are unique.
Example
None.
ImporterFindAPIByWriteLocation function
ImporterFindAPIByWriteLocation searches through the list of added APIs by ImporterAddNewAPI in
order to locate the name of the added API by using its trunk location.
Syntax
long long __stdcall ImporterFindAPIByWriteLocation(
ULONG_PTR APIWriteLocation
);
Parameters
APIWriteLocation
[in] Trunk location on which pointer to selected API will be written. This was the trunk
value passed to ImporterAddNewAPI or ImporterAddNewDLL at the time of adding
that API.
Return value
Function returns pointer to string which is the name of the API for supplied trunk address or
NULL if API isn’t found.
Remarks
None.
Example
None.
ImporterFindDLLByWriteLocation function
ImporterFindDLLByWriteLocation searches through the list of added APIs by ImporterAddNewAPI in
order to locate the name of the DLL to which the added API belongs to.
Syntax
long long __stdcall ImporterFindDLLByWriteLocation(
ULONG_PTR APIWriteLocation
);
Parameters
APIWriteLocation
[in] Trunk location on which pointer to selected API will be written. This was the trunk
value passed to ImporterAddNewAPI or ImporterAddNewDLL at the time of adding
that API.
Return value
Function returns pointer to string which is the name of the DLL which holds the API for supplied
trunk address or NULL if API isn’t found.
Remarks
None.
Example
None.
ImporterGetNearestAPIAddress function
ImporterGetNearestAPIAddress estimates the correct API by closeness to provided API. This is useful if
by tracing you get to the address which is inside the API itself but it is unknown how many instructions
the API has before the one you are on.
Syntax
long long __stdcall ImporterGetNearestAPIAddress(
HANDLE hProcess,
ULONG_PTR APIAddress
);
Parameters
hProcess
[in] Handle of the process which will be inspected for correct API estimation.
APIAddress
[in] Address near the possible API start in the remote process.
Return value
Function returns the address of the nearest possible API or NULL if no close API can be found.
Remarks
None.
Example
None.
ImporterGetNearestAPIName function
ImporterGetNearestAPIName gets the name of the API closest to the specified API. This is useful if, by
tracing, you get to the address of the target API from is inside the current API, but you don't know how
many instructions the target API executes prior to the start of the one you are in.
Syntax
void* __stdcall ImporterGetNearestAPIName(
HANDLE hProcess,
ULONG_PTR APIAddress
);
Parameters
hProcess
[in] Handle of the process in which the target API is located.
APIAddress
[in] Address near the possible start of the target API the specified process.
Return value
Pointer to string which is the name of the nearest API to the specified address or NULL if no API
is found.
Remarks
CAUTION: The string containing the API name is stored inside the engine, which makes this
function multi thread unsafe.
Example
None.
ImporterMoveIAT function
ImporterMoveIAT turns on a switch to make the importer export the import table in a way that ensures
strings are written after the import tree, which is important when fixing import eliminations if we don’t
know where APIs will be written. If that is the case, all APIs need to be added to the tree with relative
addresses, starting from NULL and incrementing by four (or eight for x64) or double that value if we
need to write a pointer for new DLL. This data will later be relocated to match the new section in which
it will be written. Since default strings are written to the section first, ImporterMoveIAT must be called
to move those strings behind the pointers, which will be written at the beginning of that section. This
functionality has been added to the automatic import fixing functions, so examples using this kind of
model can be seen in the TitanEngine source code.
Syntax
void __stdcall ImporterMoveIAT();
Parameters
None.
Return value
None.
Remarks
None.
Example
None.
ImporterRelocateWriteLocation function
ImporterRelocateWriteLocation relocates all import data by the same value. It is used only in the
situation describes for the ImporterMoveIAT function. This value can be the offset of the newly added
section, or a code cave inside the file.
Syntax
bool __stdcall ImporterRelocateWriteLocation(
ULONG_PTR AddValue
);
Parameters
AddValue
[in] Offset to add to every import tree entry added with engine functions
ImporterAddNewAPI and/or ImporterAddNewDLL.
Return value
Function returns TRUE on success or FALSE if function fails to relocate added data.
Remarks
None.
Example
None.
ImporterSetUnknownDelta function
The ImporterSetUnknownDelta function is used only in specific situation describe with function
ImporterMoveIAT to relocate all import data by the same value. This value can be the offset of the newly
added section or a code cave inside the file.
Syntax
void __stdcall ImporterSetUnknownDelta(
ULONG_PTR DeltaAddress
);
Parameters
DeltaAddress
[in] Value to use as a temporary import tree entry offset, when using the engine
functions ImporterAddNewAPI and/or ImporterAddNewDLL.
Return value
None.
Remarks
None.
Example
None.
ImporterGetCurrentDelta function
The ImporterGetCurrentDelta function is used only in specific situation describe with function
ImporterMoveIAT to relocate all import data by the same value.
Syntax
long long __stdcall ImporterGetCurrentDelta();
Parameters
None.
Return value
This function returns the current delta which will be used for writing new virtual trunk.
Remarks
None.
Example
None.
ImporterLoadImportTable function
ImporterLoadImportTable loads an import table from any PE file. The loaded table will be converted to
an internal engine import tree, making it available for further modifications before it's exported to the
same or any other PE file.
Syntax
bool __stdcall ImporterLoadImportTable(
char* szFileName
);
Parameters
szFileName
[in] Pointer to a null terminated string which is a full path to file whose import table will
be loaded by the engine.
Return value
Function returns TRUE on success or FALSE if function fails to load data.
Remarks
None.
Example
None.
ImporterCopyOriginalIAT function
ImporterCopyOriginalIAT copies IAT from one file to another. This function assumes that the IAT will be
in the same virtual location in both files, so it is only used in cases when you dynamically unpack
crypters and where the format doesn’t handle imports by itself. Instead it leaves the import table
handling to Windows loader, as if the file wasn’t packed.
Syntax
bool __stdcall ImporterCopyOriginalIAT(
char* szOriginalFile,
char* szDumpFile
);
Parameters
szOriginalFile
[in] Pointer to a null terminated string which is a full path to file from which import
table will be copied.
szDumpFile
[in] Pointer to a null terminated string which is a full path to file to which import table
will be copied to.
Return value
Function returns TRUE on success or FALSE if function fails to copy the import table.
Remarks
None.
Example
None.
ImporterMoveOriginalIAT function
ImporterMoveOriginalIAT moves IAT from one file to another. This function doesn’t actually modify the
original file, but loads the import table and exports it to selected dump file.
Syntax
bool __stdcall ImporterMoveOriginalIAT(
char* szOriginalFile,
char* szDumpFile,
char* szSectionName
);
Parameters
szOriginalFile
[in] Pointer to a null terminated string which is a full path to file from which import
table will be copied.
szDumpFile
[in] Pointer to a null terminated string which is a full path to file to which import table
will be copied to.
szSectionName
[in] Pointer to a null terminated string which will be the new section name which will
hold the import table. This string can only be 8 characters long.
Return value
Function returns TRUE on success or FALSE if function fails to move the import table.
Remarks
None.
Example
None.
ImporterAutoSearchIAT function
ImporterAutoSearchIAT automatically locates a possible import table location inside the packed file
memory. Returns from this function can be used to automatically fix the import table for the selected
file.
Syntax
void __stdcall ImporterAutoSearchIAT(
HANDLE hProcess,
char* szFileName,
ULONG_PTR ImageBase,
ULONG_PTR SearchStart,
DWORD SearchSize,
LPVOID pIATStart,
LPVOID pIATSize
);
Parameters
hProcess
[in] Handle of the process whose memory will be searched for import table.
szFileName
[in] Pointer to a null terminated string which is a full path to file whose content will be
searched for import table. This file is a memory dump from the running process
whose handle you have provided.
ImageBase
[in] Default image base of the targeted PE file dump on the disk.
SearchStart
[in] Virtual address inside the file which is used as a start marker for the search. It is safe
to use virtual offset of the first section as a start position as only the code should be
searched.
SearchSize
[in] Size of the memory to be searched for import pointers. It is safe to use
NtSizeOfImage to search the whole file memory.
pIATStart
[out] Pointer to ULONG_PTR variable which will receive the virtual address on which the
import table has been found.
pIATSize
[out] Pointer to ULONG_PTR variable which will receive the size of the found import
table.
ImporterAutoSearchIATEx function
ImporterAutoSearchIATEx automatically locates the possible import table location inside the packed file
memory. This function will automatically dump the targeted process before searching for the import
table. Returns from this function can be used to automatically fix the import table for the selected file.
Syntax
void __stdcall ImporterAutoSearchIATEx(
HANDLE hProcess,
ULONG_PTR ImageBase,
ULONG_PTR SearchStart,
DWORD SearchSize,
LPVOID pIATStart,
LPVOID pIATSize
);
Parameters
hProcess
[in] Handle of the process whose memory will be searched for import table.
ImageBase
[in] Default image base of the targeted PE file dump on the disk.
SearchStart
[in] Virtual address inside the file which is used as a start marker for the search. It is safe
to use virtual offset of the first section as a start position as only the code should be
searched.
SearchSize
[in] Size of the memory to be searched for import pointers. It is safe to use
NtSizeOfImage to search the whole file memory.
pIATStart
[out] Pointer to ULONG_PTR variable which will receive the virtual address on which the
import table has been found.
pIATSize
[out] Pointer to ULONG_PTR variable which will receive the size of the found import
table.
ImporterAutoFixIATEx function
ImporterAutoFixIATEx automatically fixes the import table for the running process. This function can fix
all known redirections and import eliminations with the optional callback to manually fix unknown
import pointers.
Syntax
long __stdcall ImporterAutoFixIATEx(
HANDLE hProcess,
char* szDumpedFile,
char* szSectionName,
bool DumpRunningProcess,
bool RealignFile,
ULONG_PTR EntryPointAddress,
ULONG_PTR ImageBase,
ULONG_PTR SearchStart,
DWORD SearchSize,
DWORD SearchStep,
bool TryAutoFix,
bool FixEliminations,
LPVOID UnknownPointerFixCallback
);
Parameters
hProcess
[in] Handle of the process whose memory will be searched for import table.
szDumpedFile
[in] Pointer to a null terminated string which is a full path to file which will contain the
memory content if DumpRunningProcess is TRUE or already contains the dump
memory content if DumpRunningProcess is FALSE.
DumpRunningProcess
[in] Boolean switch that indicates whether the file was dumped or not.
RealignFile
[in] Boolean switch that indicates whether or not the file needs realigning after fixing
imports.
EntryPointAddress
[in] [in] Virtual address which will be set to the new file. Size of this variable varies, on
x86 its 4 bytes and on x64 is 8 bytes. Therefore it can also be declared as void*.
ImageBase
[in] Default image base of the targeted PE file. This value should be read from the file on
disk.
SearchStart
[in] Virtual address inside the file - used as a start marker for the search. This is the
return value of ImporterAutoSearchIAT function.
SearchSize
[in] Size of the memory to be searched for import pointers. This is the return value of
ImporterAutoSearchIAT.
SearchStep
[in] Search step is a value which will be used to iterate the search position. Default value
is four (or eight on x64) and it will be used is you don’t specify the search step and
use NULL.
TryAutoFix
[in] Boolean switch that indicates whether or not to trace possible import pointers, in
order to fix the import table. This can be always set to TRUE, but can be disabled in
case you are sure that the target doesn’t use import redirection.
FixEliminations
[in] Boolean switch that indicates whether or not to fix possible import eliminations, in
order to fix the import table. This can be always set to TRUE, but can be disabled in
case you are sure that the target doesn’t use import elimination.
UnknownPointerFixCallback
[in] Pointer to the callback to call for every possible but unknown import redirection or
elimination. Use this callback to correct import table fixing when a particular import
protection is not yet recognized by TitanEngine.
CallBack definition
typedef void*(__stdcall *fFixerCallback)(LPVOID fIATPointer);
// Returns API address in remote process or NULL
Return value
One of the following:
. NULL - Critical error! *just to be safe, but it should never happen
. 0x400 - Success
. 0x401 - Error, process terminated
. 0x404 - Error, memory could not be read
. 0x405 - Error, no API found
. 0x406 - Success, but realign failed
ImporterAutoFixIAT function
ImporterAutoFixIAT automatically fixes the import table for the running process. This function can fix all
known redirections and import eliminations, using an optional callback to manually fix unknown import
pointers.
Syntax
long __stdcall ImporterAutoFixIAT(
HANDLE hProcess,
char* szDumpedFile,
ULONG_PTR ImageBase,
ULONG_PTR SearchStart,
DWORD SearchSize,
DWORD SearchStep
);
Parameters
hProcess
[in] Handle of the process whose memory will be searched for import table.
szDumpedFile
[in] Pointer to a null terminated string which is a full path to file which already contains
the dump memory content.
ImageBase
[in] Default image base of the targeted PE file. This value should be read from the file on
disk.
SearchStart
[in] Virtual address inside the file. It will be used as a start marker for the search. This is
the return value of ImporterAutoSearchIAT function.
SearchSize
[in] Size of the memory to be searched for import pointers. This is the return value of
ImporterAutoSearchIAT function.
SearchStep
[in] Search step is used to iterate the search position. If you specify NULL, the default is
used: four on x86, or eight on x64.
Return value
See ImporterAutoFixIATEx function for return details.
Tracer module
The Tracer module has functions designed for detecting and fixing import redirections. It has integrated
import tracers and can also use ImpRec modules to fix known redirections.
TracerInit function
TracerInit is not used in TitanEngine and is retained only for backward compatibility issued with version
1.5.
Syntax
void __stdcall TracerInit();
Parameters
None.
Return value
None.
Remarks
None.
Example
None.
TracerLevel1 function
TracerLevel1 traces the provided address via code disassembling, in order to try to find the API hiding
behind an import redirection. This function uses common code tracing to try to identify the API that is
being redirected.
Syntax
long long __stdcall TracerLevel1(
HANDLE hProcess,
ULONG_PTR AddressToTrace
);
Parameters
hProcess
[in] Handle of the process whose memory will be traced.
AddressToTrace
[in] Pointer to the memory that holds the redirection code. This memory is commonly
outside the PE file memory and is allocated by the packer/protector code.
Return value
If the return value is NULL the trace has failed, and if the return value is greater than 0x1000
then the return is an API address inside the remote process. For cases where return is greater
than NULL and lower then 0x1000, the return is the number of valid instructions detected while
tracing, which can then be used by the HashTracerLevel1 API.
Remarks
None.
Example
None.
HashTracerLevel1 function
HashTracerLevel1 traces the provided address via code hashing in order to try to find the correct API
hiding behind selected import redirection. This function uses advanced code tracing in order to try to
identify the API that is being redirected.
Syntax
long long __stdcall HashTracerLevel1(
HANDLE hProcess,
ULONG_PTR AddressToTrace,
DWORD InputNumberOfInstructions
);
Parameters
hProcess
[in] Handle of the process whose memory will be traced.
AddressToTrace
[in] Pointer to the memory that holds the redirection code. This memory is commonly
outside the PE file memory and is allocated by the packer/protector code.
InputNumberOfInstructions
[in] Number of valid instructions detected while tracing with TraceLevel1.
Return value
If the return value is NULL or minus one, the trace has failed; if the return value is greater than
NULL then the return is an API address inside the remote process.
Remarks
None.
Example
None.
TracerDetectRedirection function
TracerDetectRedirection checks whether the memory at the selected address is equal to one of the
known import redirection patterns.
Syntax
long __stdcall TracerDetectRedirection(
HANDLE hProcess,
ULONG_PTR AddressToTrace
);
Parameters
hProcess
[in] Handle of the process whose memory will be checked for known import
redirections.
AddressToTrace
[in] Pointer to the memory that holds the redirection code. This memory is commonly
outside the PE file memory and is allocated by the packer/protector code.
Return value
If the return value is NULL then no known redirection was detected, and if return value is
greater than NULL then the return is an ID of the known redirection inside the internal
TitanEngine import redirection database.
Remarks
None.
Example
None.
TracerFixKnownRedirection function
TracerFixKnownRedirection fixes known import redirection based on the known import redirection ID
inside the TitanEngine database.
Syntax
long long __stdcall TracerFixKnownRedirection(
HANDLE hProcess,
ULONG_PTR AddressToTrace,
DWORD RedirectionId
);
Parameters
hProcess
[in] Handle of the process whose memory will be checked for known import
redirections.
AddressToTrace
[in] Pointer to the memory that holds the redirection code. This memory is commonly
outside the PE file memory and is allocated by the packer/protector code.
RedirectionId
[in] ID of the detected import redirection inside the TitanEngine database.
Return value
If the return value is NULL, the trace has failed; if the return value is greater than NULL then the
return is an API address inside the remote process.
Remarks
None.
Example
None.
TracerFixRedirectionViaImpRecPlugin function
TracerFixRedirectionViaImpRecPlugin fixes import redirections with ImpRec modules. To use this option
you must install all needed ImpRec plugins by placing them in the .\import\ImpRec\ folder.
Syntax
long __stdcall TracerFixRedirectionViaImpRecPlugin(
HANDLE hProcess,
char* szPluginName,
ULONG_PTR AddressToTrace
);
Parameters
hProcess
[in] Handle of the process whose import redirection will be fixed.
szPluginName
[in] Name of the ImpRec module inside the .\import\ImpRec\ folder. For example
aspr1.dll
AddressToTrace
[in] Pointer to the memory that holds the redirection code. This memory is commonly
outside the PE file memory and is allocated by the packer/protector code.
Return value
If the return value is NULL the trace has failed and if the return value is greater than NULL then
the return is an API address inside the remote process.
Remarks
This function only works on x86 systems since ImpRec and its plugins are designed that way.
Example
None.
Realigner module
Realigner module has functions designed for PE file validation, fixing and realigning.
Realigner module structures and constants
Constants used by: IsPE32FileValidEx function
#define UE_DEPTH_SURFACE 0
#define UE_DEPTH_DEEP 1
Structures used by: IsPE32FileValidEx function
typedef struct{
BYTE OveralEvaluation;
bool EvaluationTerminatedByException;
bool FileIs64Bit;
bool FileIsDLL;
bool FileIsConsole;
bool MissingDependencies;
bool MissingDeclaredAPIs;
BYTE SignatureMZ;
BYTE SignaturePE;
BYTE EntryPoint;
BYTE ImageBase;
BYTE SizeOfImage;
BYTE FileAlignment;
BYTE SectionAlignment;
BYTE ExportTable;
BYTE RelocationTable;
BYTE ImportTable;
BYTE ImportTableSection;
BYTE ImportTableData;
BYTE IATTable;
BYTE TLSTable;
BYTE LoadConfigTable;
BYTE BoundImportTable;
BYTE COMHeaderTable;
BYTE ResourceTable;
BYTE ResourceData;
BYTE SectionTable;
}FILE_STATUS_INFO, *PFILE_STATUS_INFO;
Constants used by: IsPE32FileValidEx function and FixBrokenPE32FileEx function
#define UE_FIELD_OK 0
#define UE_FIELD_BROKEN_NON_FIXABLE 1
#define UE_FIELD_BROKEN_NON_CRITICAL 2
#define UE_FIELD_BROKEN_FIXABLE_FOR_STATIC_USE 3
#define UE_FIELD_BROKEN_BUT_CAN_BE_EMULATED 4
#define UE_FILED_FIXABLE_NON_CRITICAL 5
#define UE_FILED_FIXABLE_CRITICAL 6
#define UE_FIELD_NOT_PRESET 7
#define UE_FIELD_NOT_PRESET_WARNING 8
#define UE_RESULT_FILE_OK 10
#define UE_RESULT_FILE_INVALID_BUT_FIXABLE 11
#define UE_RESULT_FILE_INVALID_AND_NON_FIXABLE 12
#define UE_RESULT_FILE_INVALID_FORMAT 13
Structures used by: FixBrokenPE32FileEx function
typedef struct{
BYTE OveralEvaluation;
bool FixingTerminatedByException;
bool FileFixPerformed;
bool StrippedRelocation;
bool DontFixRelocations;
DWORD OriginalRelocationTableAddress;
DWORD OriginalRelocationTableSize;
bool StrippedExports;
bool DontFixExports;
DWORD OriginalExportTableAddress;
DWORD OriginalExportTableSize;
bool StrippedResources;
bool DontFixResources;
DWORD OriginalResourceTableAddress;
DWORD OriginalResourceTableSize;
bool StrippedTLS;
bool DontFixTLS;
DWORD OriginalTLSTableAddress;
DWORD OriginalTLSTableSize;
bool StrippedLoadConfig;
bool DontFixLoadConfig;
DWORD OriginalLoadConfigTableAddress;
DWORD OriginalLoadConfigTableSize;
bool StrippedBoundImports;
bool DontFixBoundImports;
DWORD OriginalBoundImportTableAddress;
DWORD OriginalBoundImportTableSize;
bool StrippedIAT;
bool DontFixIAT;
DWORD OriginalImportAddressTableAddress;
DWORD OriginalImportAddressTableSize;
bool StrippedCOM;
bool DontFixCOM;
DWORD OriginalCOMTableAddress;
DWORD OriginalCOMTableSize;
}FILE_FIX_INFO, *PFILE_FIX_INFO;
RealignPE function
RealignPE realigns the PE file sections so that virtual and physical data are aligned to PECOFF
specifications and extra data removed in order to minimize the file size. After file unpacking it is
recommended to use this function to make the file a valid PE image.
Syntax
long __stdcall RealignPE(
ULONG_PTR FileMapVA,
DWORD FileSize,
DWORD RealingMode
);
Parameters
FileMapVA
[in] Pointer to the mapped file content. This pointer is set by using either StaticFileLoad
function or Windows API for file mapping. It is a ULONG_PTR which defines its size
on the x86 and x64 operating systems. On x86 systems this variable is 4 bytes long
and equal to DWORD, and on x64 platform this variable is 8 bytes long and equal to
DWORD64, but since this is a pointer void* can also be used.
FileSize
[in] Size of the mapped file.
RealignMode
[in] Reserved for future use, set to NULL always.
Return value
This function returns the new realigned file size which can be used to trim the file during the
unmapping process, or NULL if it fails.
Remarks
None.
Example
None.
RealignPEEx function
RealignPEEx realigns the PE file sections so that virtual and physical data are aligned to PECOFF
specifications and extra data removed in order to minimize the file size. After file unpacking it is
recommended to use this function to make the file a valid PE image.
Syntax
long __stdcall RealignPEEx(
char* szFileName,
DWORD RealingFileSize,
DWORD ForcedFileAlignment
);
Parameters
szFileName
[in] Pointer to a null terminated string which is a full path to file which will be realigned.
RealignedFileSize
[in] Force the engine to make the file the specified size. This option should only be used
to increase the file size.
ForcedFileAlignment
[in] Specify FileAlignment manually. If no value is specified, the default of 0x200 will be
used.
Return value
This function returns the new realigned file size or NULL if it fails.
Remarks
None.
Example
None.
FixHeaderCheckSum function
FixHeaderCheckSum recalculates the PE header field checksum which refers to checksum of the whole
header. After new value is calculated selected file will be updated.
Syntax
bool __stdcall FixHeaderCheckSum(
char* szFileName
);
Parameters
szFileName
[in] Pointer to a null terminated string which is a full path to file whose checksum will
be updated.
Return value
This function returns TRUE on successful checksum update and FALSE if the function fails.
Remarks
None.
Example
None.
WipeSection function
WipeSection removes the section from the file but preserves that virtual space by expanding nearby
section.
Syntax
bool __stdcall WipeSection(
char* szFileName,
int WipeSectionNumber,
bool RemovePhysically
);
Parameters
szFileName
[in] Pointer to a null terminated string which is a full path to file whose section will be
removed.
WipeSectionNumber
[in] Removes the selected PE section. Section numbers go from NULL to SectionNumber
minus one.
RemovePhysically
[in] If set to TRUE file size will decrease because the section content will be removed
from the file and in case this switch is set to FALSE content will remain in the file and
only the PE header content will be changed.
Return value
This function returns TRUE on successful section wipe and FALSE if the function fails.
Remarks
None.
Example
None.
IsFileDLL function
IsFileDLL determines if the selected file is a DLL by inspecting its PE header flags.
Syntax
bool __stdcall IsFileDLL(
char* szFileName,
ULONG_PTR FileMapVA
);
Parameters
szFileName
[in] Pointer to a null terminated string which is a full path to file whose PE header will
be checked to see if it is a DLL file.
FileMapVA
[in] Pointer to the mapped file content. This pointer is set by using either StaticFileLoad
function or Windows API for file mapping. It is a ULONG_PTR which defines its size
on the x86 and x64 operating systems. On x86 systems this variable is 4 bytes long
and equal to DWORD, and on x64 platform this variable is 8 bytes long and equal to
DWORD64, but since this is a pointer void* can also be used.
Return value
This function returns TRUE if the selected file is a DLL and FALSE if it isn’t.
Remarks
You can specify both input parameters but only one is required.
Example
None.
IsPE32FileValidEx function
IsPE32FileValidEx determines if the selected file is a valid PE file and provide as much additional
information about the file and detected errors.
Syntax
bool __stdcall IsPE32FileValidEx(
char* szFileName,
DWORD CheckDepth,
LPVOID FileStatusInfo
);
Parameters
szFileName
[in] Pointer to a null terminated string which is a full path to file whose PE header will
be validated.
CheckDepth
[in] Indicates how detail the checks will be. Can be either UE_DEPTH_SURFACE or
UE_DEPTH_DEEP.
FileStatusInfo
[out] Pointer to a FILE_STATUS_INFO structure which will be filled by this function.
Return value
This function returns TRUE if the function completes without critical errors in verification
process which can occur in broken files and FALSE if there are errors during validation.
Remarks
OveralEvaluation member of the structure tells the state of the file. Can be one of the following:
UE_RESULT_FILE_INVALID_FORMAT, UE_RESULT_FILE_INVALID_BUT_FIXABLE,
UE_RESULT_FILE_INVALID_AND_NON_FIXABLE or UE_RESULT_FILE_OK.
Example
None.
FixBrokenPE32FileEx function
FixBrokenPE32FileEx tries to fix PE file errors and provide as much additional information about the file,
both detected errors and fixed errors data.
Syntax
bool __stdcall FixBrokenPE32FileEx(
char* szFileName,
LPVOID FileStatusInfo,
LPVOID FileFixInfo
);
Parameters
szFileName
[in] Pointer to a null terminated string which is a full path to file whose PE header will
be validated.
FileStatusInfo
[in] Pointer to a FILE_STATUS_INFO structure that was filled by the IsPE32FileValidEx
function, or NULL, which would make the engine call a file validation function before
fixing the file automatically.
FileFixInfo
[in & out] Pointer to a FILE_FIX_INFO structure to fill during file fixing. Also serves as
an input parameter which tells the engine which tables not to fix or strip.
Return value
This function returns TRUE if the function completes without critical errors in the file repair
process which can occur in broken files. It returns FALSE if there are errors during fixing.
Remarks
The OveralEvaluation member of the structure tells the state of the file after fixing.
Example
None.
Relocater module
The relocater module has functions designed for relocation manipulation, making file memory
snapshots, and removing relocation tables. This module is used to fix a relocation table when unpacking
DLL files.
RelocaterInit function
RelocaterInit initializes the relocater module. It must be used before using any of the relocator functions
to do manual relocation fixing.
Syntax
void __stdcall RelocaterInit(
DWORD MemorySize,
ULONG_PTR OldImageBase,
ULONG_PTR NewImageBase
);
Parameters
MemorySize
[in] Default memory size allocated for all relocations you add. This size must be large
enough to hold all data needed by the engine. Usually there is no need to reserve
more than 100kb of memory.
OldImageBase
[in] Default image base of the targeted PE file. This value should be read from the file on
disk.
NewImageBase
[in] Base address at which the targeted DLL file, whose relocation table you are fixing, is
loaded.
Return value
None.
Remarks
None.
Example
None.
RelocaterCleanup function
RelocaterCleanup frees memory allocated by the engine during relocation fixing.
Syntax
void __stdcall RelocaterCleanup();
Parameters
None.
Return value
None.
Remarks
None.
Example
None.
RelocaterAddNewRelocation function
RelocaterAddNewRelocation adds an address from the remote process to the list of addresses tnat
need relocating, if the file is allocated at a base address other then default one. Just like when adding
import via the importer, you must add relocations one page at a time. The engine itself will take care of
page switching but once the page is switched you can’t go back to adding data to any of the previous
pages.
Syntax
void __stdcall RelocaterAddNewRelocation(
HANDLE hProcess,
ULONG_PTR RelocateAddress,
DWORD RelocateState
);
Parameters
hProcess
[in] Handle of the process that has loaded the targeted DLL, whose relocation table you
are fixing.
RelocateAddress
[in] Address inside the remote process, belonging to targeted DLL, which needs
relocation if the file is being loaded at a base address other than default.
RelocateState
[in] Reserved for future usage, for now always set to NULL.
Return value
None.
Remarks
None.
Example
None.
RelocaterEstimatedSize function
RelocaterEstimatedSize estimates the space needed to write the relocation table to the file. This value
can be used to determine the size of the new section in which the relocation data will be written.
Syntax
long __stdcall RelocaterEstimatedSize();
Parameters
None.
Return value
Returns the size needed to write the relocation data.
Remarks
None.
Example
None.
RelocaterExportRelocationEx function
RelocaterExportRelocationEx exports the added relocation data to an existing PE file, creating a valid
relocation table for the selected PE file. After this function has executed, relocation data will be cleared
by using the RelocaterCleanup function.
Syntax
bool __stdcall RelocaterExportRelocationEx(
char* szFileName,
char* szSectionName
);
Parameters
szFileName
[in] Pointer to string which is the full path to the file in which the new relocation table
will be written. This file is usually created by the DumpProcess function.
szSectionName
[in] Name (up to 8 characters long) of the PE section in which the new relocation table
content will be written. This section will be added to the file.
Return value
Boolean switch indicating whether or not the function was successful.
Remarks
None.
Example
None.
RelocaterExportRelocation function
RelocaterExportRelocation exports the added relocation data to an existing PE file, creating a valid
relocation table for the selected PE file. After this function has executed relocation data will be cleared
by using RelocaterCleanup function.
Syntax
bool __stdcall RelocaterExportRelocation(
ULONG_PTR StorePlace,
DWORD StorePlaceRVA,
ULONG_PTR FileMapVA
);
Parameters
StorePlace
[in] Physical address inside PE file at which the new relocation table will be written.
Usually this is a new section but, it can also be part of the file which is unused, but
still in read/write mode.
StorePlaceRVA
[in] Relative virtual address inside the PE file at which the new relocation table will be
written. This input is just a conversion from physical to relative virtual offset.
FileMapVA
[in] Pointer to the mapped file content, which must be mapped in read/write mode.
This pointer is set by either the StaticFileLoad function or Windows API for file
mapping. It is a ULONG_PTR which defines its size on the x86 and x64 operating
systems. On x86 systems this variable is 4 bytes long and equal to DWORD, and on
x64 platform this variable is 8 bytes long and equal to DWORD64, but since this is a
pointer void* can also be used.
Return value
Boolean switch indicating whether or not the function was successful.
Remarks
None.
Example
None.
RelocaterGrabRelocationTableEx function
RelocaterGrabRelocationTableEx copies a PECOFF valid relocation table from the targeted process to
engine relocation data storage. This function can automatically determine the size of the relocation
table, but the size parameter must be close to or higher than the actual relocation table size so that the
targeted memory slice contains the end of the relocation table. If this function succeeds, the relocation
table is ready to be exported.
Syntax
bool __stdcall RelocaterGrabRelocationTableEx(
HANDLE hProcess,
ULONG_PTR MemoryStart,
ULONG_PTR MemorySize,
DWORD NtSizeOfImage
);
Parameters
hProcess
[in] Handle of the process from which the relocation table will be copied.
MemoryStart
[in] Pointer to memory in the remote process: the start of a valid relocation table.
MemorySize
[in] Size of the memory inside which the relocation table resides.
NtSizeOfImage
[in] PE header variable read from the file on the disk.
Return value
Boolean switch indicating whether or not the function was successful.
Remarks
None.
Example
None.
RelocaterGrabRelocationTable function
RelocaterGrabRelocationTable copies a PECOFF valid relocation table from the targeted process to
engine relocation data storage. If this function succeeds the relocation table is ready to be exported.
Syntax
bool __stdcall RelocaterGrabRelocationTable(
HANDLE hProcess,
ULONG_PTR MemoryStart,
ULONG_PTR MemorySize
);
Parameters
hProcess
[in] Handle of the process from which the relocation table will be copied.
MemoryStart
[in] Pointer to memory in the remote process: the start of a valid relocation table.
MemorySize
[in] Exact size of the relocation table inside the remote process.
Return value
Boolean switch indicating whether or not the function was successful.
Remarks
None.
Example
None.
RelocaterMakeSnapshot function
RelocaterMakeSnapshot copies the selected memory segment to a file on the disk. This memory
segment should contain all data that can and will be relocated by the packer itself. Most commonly, it
covers all the executable code inside the PE files memory. By creating two snapshots, one just before
the code that relocates the file inside the packer, and one right after its execution, you create two
memory state images, which can be used to create a valid relocation table by comparing the two.
Syntax
bool __stdcall RelocaterMakeSnapshot(
HANDLE hProcess,
char* szSaveFileName,
LPVOID MemoryStart,
ULONG_PTR MemorySize
);
Parameters
hProcess
[in] Handle of the process whose memory will be snapshotted.
szFileName
[in] Pointer to the full path of the file to create and fill with the snapshot.
MemoryStart
[in] Pointer to memory in the remote process: the start of the snapshot image. The
start of the snapshot must be the same for both snapshots.
MemorySize
[in] Size of the snapshot, which must be the same for both snapshots.
Return value
Boolean switch indicating whether or not the function was successful.
Remarks
None.
Example
None.
RelocaterCompareTwoSnapshots function
RelocaterCompareTwoSnapshots creates a valid relocation table by comparing two memory snapshots:
one taken just before the relocation code inside the packer was executed and another taken right
afterward. If this function succeeds, the relocation table is ready to be exported.
Syntax
bool __stdcall RelocaterCompareTwoSnapshots(
HANDLE hProcess,
ULONG_PTR LoadedImageBase,
ULONG_PTR NtSizeOfImage,
char* szDumpFile1,
char* szDumpFile2,
ULONG_PTR MemStart
);
Parameters
hProcess
[in] Handle of the process whose memory will be snapshot.
LoadedImageBase
[in] Base address at which the targeted file is loaded.
NtSizeOfImage
[in] PE header variable, read from the file on the disk for the targeted file.
MemoryStart
[in] Pointer to memory in remote process: used as the start for a snapshot image.
szDumpFile1
[in] Pointer to the full path of the file which was created for the first memory snapshot.
szDumpFile2
[in] Pointer to the full path of the file which for the second memory snapshot.
Return value
Boolean switch indicating whether or not the function was successful.
RelocaterWipeRelocationTable function
RelocaterWipeRelocationTable removes the relocation table from any PE file. However it is only
recommended that you remove the relocation table from executable files if you need to reduce their
size.
Syntax
bool __stdcall RelocaterWipeRelocationTable(
char* szFileName
);
Parameters
szFileName
[in] Pointer to a null terminated string which is a full path to file whose relocation table
will be removed.
Return value
Boolean switch indicating whether or not the function was successful.
Remarks
None.
Example
None.
RelocaterRelocateMemoryBlock function
RelocaterRelocateMemoryBlock uses mapped file relocation table to relocate selected memory
segment to new loaded base. Data about which parts of the memory need relocating is read directly
from the relocation table and therefore presence of such table is a necessity.
Syntax
bool __stdcall RelocaterRelocateMemoryBlock(
ULONG_PTR FileMapVA,
ULONG_PTR MemoryLocation,
void* RelocateMemory,
DWORD RelocateMemorySize,
ULONG_PTR CurrentLoadedBase,
ULONG_PTR RelocateBase
);
Parameters
FileMapVA
[in] Pointer to the mapped file content which must be mapped in read/write mode. This
pointer is set by using either StaticFileLoad function or Windows API for file
mapping.
MemoryLocation
[in] Virtual address of the memory segment to be relocated.
RelocateMemory
[in] Pointer to memory segment which will be relocated.
RelocateMemorySize
[in] Size of the memory segment to relocate.
CurrentLoadedBase
[in] Current base on which the memory segment to be relocated is loaded.
RelocateBase
[in] New base to which the memory segment will be relocated.
Return value
Boolean switch indicating whether or not the function was successful.
Remarks
None.
Exporter module
The exporter module has functions designed for export manipulation and building new export tables.
ExporterInit function
The ExporterInit function initializes the importer module and it must be used before using any of the
functions used in the process of manual import fixing.
Syntax
void __stdcall ExporterInit(
DWORD MemorySize,
ULONG_PTR ImageBase,
DWORD ExportOrdinalBase,
char* szExportModuleName
);
Parameters
MemorySize
[in] Default memory size allocated for the entire export table data. This size must be
large enough to hold all data needed by the engine. Usually there is no need to
reserve more than 20kb of memory.
ImageBase
[in] Default image base of the targeted PE file. This value should be read from the file on
disk.
ExportOrdinalBase
[in] Sets the default ordinal base for the new export table. Default value is NULL.
szExportModuleName
[in] String which to use as a default library name in the export table. For example:
mylib.dll
Return value
None.
Remarks
None.
Example
None.
ExporterSetImageBase function
ExporterSetImageBase updates information passed to the engine when exporter is initialized.
Syntax
void __stdcall ExporterSetImageBase(
ULONG_PTR ImageBase
);
Parameters
ImageBase
[in] Default image base of the targeted PE file. This value should be read from the file on
disk.
Return value
None.
Remarks
None.
Example
None.
ExporterCleanup function
ExporterCleanup clears all added exports. This resets the inputted data to its original state. Before using
the functions to add the export data, you must initialize the exporter again.
Syntax
void __stdcall ExporterCleanup();
Parameters
None.
Return value
None.
Remarks
None.
Example
None.
ExporterAddNewExport function
ExporterAddNewExport adds new function to the export table.
Syntax
void __stdcall ExporterAddNewExport(
char* szExportName,
DWORD ExportRelativeAddress
);
Parameters
szExportName
[in] Name of the function that will be used to locate this function with APIs such as
GetProcAddress.
ExportRelativeAddress
[in] Relative virtual address for the exported function. Location in the PE file at which
the function you want to export is located.
Return value
None.
Remarks
None.
Example
None.
ExporterAddNewOrdinalExport function
ExporterAddNewOrdinalExport adds a new function to the export table.
Syntax
void __stdcall ExporterAddNewOrdinalExport(
DWORD OrdinalNumber,
DWORD ExportRelativeAddress
);
Parameters
OrdinalNumber
[in] Function will be exported as an ordinal with the specified ordinal number.
ExportRelativeAddress
[in] Relative virtual address for the exported function. The location in the PE file at
which the function you want to export is located.
Return value
None.
Remarks
None.
Example
None.
ExporterGetAddedExportCount function
ExporterGetAddedExportCount gets the current number of added functions in the export table.
Syntax
long __stdcall ExporterGetAddedExportCount();
Parameters
None.
Return value
Returns the number of added items in the export table.
Remarks
None.
Example
None.
ExporterEstimatedSize function
ExporterEstimatedSize estimates the size of memory needed to write the export data. This value can be
used to determine the size of the new section to which the export table will be written.
Syntax
long __stdcall ExporterEstimatedSize();
Parameters
None.
Return value
Returns the size needed to write the export data.
Remarks
None.
Example
None.
ExporterBuildExportTableEx function
ExporterBuildExportTableEx exports the added export data to an existing PE file, creating a valid export
table for the selected PE file. After this function executes, export data will be cleared by using
ExporterCleanup function.
Syntax
bool __stdcall ExporterBuildExportTableEx(
char* szExportFileName,
char* szSectionName
);
Parameters
szExportFileName
[in] Pointer to string which is a full path to the file in which new export table will be
written.
szSectionName
[in] Name (up to 8 characters long) of the PE section in which the new import table
content will be written. This section will be added to the file.
Return value
Boolean switch indicating whether or not the function was successful.
Remarks
None.
Example
None.
ExporterBuildExportTable function
ExporterBuildExportTable exports the added export data to existing PE file, creating a valid export table
for the selected PE file. After this function executes, the export data will be cleared by using
ExporterCleanup function.
Syntax
bool __stdcall ExporterBuildExportTable(
ULONG_PTR StorePlace,
ULONG_PTR FileMapVA
);
Parameters
StorePlace
[in] Physical address inside PE file to which the new export table will be written. Usually
this is a new section, but it can also be a part of the file which is unused but still in
read/write mode.
FileMapVA
[in] Pointer to the mapped file content which must be mapped in read/write mode. This
pointer is set by using either StaticFileLoad function or Windows API for file
mapping. It is a ULONG_PTR which defines its size on the x86 and x64 operating
systems. On x86 systems this variable is 4 bytes long and equal to DWORD, and on
x64 platform this variable is 8 bytes long and equal to DWORD64, but since this is a
pointer void* can also be used.
Return value
Boolean switch indicating whether or not the function was successful.
Remarks
None.
Example
None.
ExporterLoadExportTable function
ExporterLoadExportTable loads an export table from any PE file. The loaded table will be converted to
an internal engine export tree, making it available for further modifications before it's exported to the
same or any other PE file.
Syntax
bool __stdcall ExporterLoadExportTable(
char* szFileName
);
Parameters
szFileName
[in] Pointer to a null terminated string which is a full path to file whose export table will
be loaded by the engine.
Return value
Function returns TRUE on success or FALSE if function fails to load data.
Remarks
None.
Example
None.
Resourcer module
The resourcer module has functions designed to load and access PE files in order to work with them and
functions to extract those resources out.
ResourcerLoadFileForResourceUse function
ResourcerLoadFileForResourceUse simulates PE file loading, in order to make all the virtual addresses
equal to physical ones in the newly loaded file. This is different than file mapping, because it simulates
only Windows PE loader behavior concerning PE file loading and storing sections in memory. No other
function of the Windows PE loader other than that is emulated.
Syntax
long long __stdcall ResourcerLoadFileForResourceUse(
char* szFileName
);
Parameters
szFileName
[in] Pointer to a null terminated string which is a full path to file whose loading will be a
simulated PE loading so that all the virtual addresses match the newly loaded
physical ones. This is a done by simulating the Windows PE loader.
Return value
Return is the base address of the newly loaded file, or NULL if the file isn’t a PE file or it couldn’t
be loaded.
Remarks
None.
Example
None.
ResourcerFreeLoadedFile function
ResourcerFreeLoadedFile unloads a file previously loaded by the ResourcerLoadFileForResourceUse
function. Due to the nature of the TitanEngine PE file loader simulator, using this function is equal to
using VirtualFree on the selected memory range.
Syntax
bool __stdcall ResourcerFreeLoadedFile(
LPVOID LoadedFileBase
);
Parameters
LoadedFileBase
[in] Base address at which the file is loaded. This is usually a return value from the
ResourcerLoadFileForResourceUse function.
Return value
Boolean switch indicating whether or not the function was successful.
Remarks
None.
Example
None.
ResourcerExtractResourceFromFileEx function
ResourcerExtractResourceFromFileEx goes through the resource tree of the loaded file and extracts the
specified resource to disk.
Syntax
bool __stdcall ResourcerExtractResourceFromFileEx(
ULONG_PTR FileMapVA,
char* szResourceType,
char* szResourceName,
char* szExtractedFileName
);
Parameters
FileMapVA
[in] Pointer to the mapped file content. This pointer is set by using either StaticFileLoad
function or Windows API for file mapping. It is a ULONG_PTR which defines its size
on the x86 and x64 operating systems. On x86 systems this variable is 4 bytes long
and equal to DWORD, and on x64 platform this variable is 8 bytes long and equal to
DWORD64, but since this is a pointer void* can also be used.
ResourceType
[in] Pointer to string, which is a resource type identifier. If the resource type is an
integer you must convert it to string. For this conversion you can use the
MAKEINTRESOURCEA macro available in WinUser.h
ResourceName
[in] Pointer to string which is a resource name identifier. If the resource type is an
integer you must convert it to string. For this conversion you can use
MAKEINTRESOURCEA macro available in WinUser.h
szExtractFileName
[in] Pointer to the full path of the file to create and fill with the specified resource
memory content.
Return value
Boolean switch indicating whether or not the function was successful.
ResourcerExtractResourceFromFile function
ResourcerExtractResourceFromFile goes through the resource tree of the loaded file and extracts the
specified resource to disk.
Syntax
bool __stdcall ResourcerExtractResourceFromFile(
char* szFileName,
char* szResourceType,
char* szResourceName,
char* szExtractedFileName
);
Parameters
szFileName
[in] Pointer to a null terminated string which is a full path to file whose resource will be
extracted.
ResourceType
[in] Pointer to string which is a resource type identifier. If the resource type is an
integer you must convert it to string. For this conversion you can use
MAKEINTRESOURCEA macro available in WinUser.h
ResourceName
[in] Pointer to string which is a resource name identifier. If the resource type is an
integer you must convert it to string. For this conversion you can use
MAKEINTRESOURCEA macro available in WinUser.h
szExtractFileName
[in] Pointer to a null terminated string which is a full path to file which will be created
and filled with selected resource memory content.
Return value
Boolean switch indicating whether or not the function was successful.
Remarks
None.
Example
None.
ResourcerFindResource function
ResourcerFindResource goes through the resource tree of the selected file and finds the specified
resource.
Syntax
bool __stdcall ResourcerFindResource(
char* szFileName,
char* szResourceType,
DWORD ResourceType,
char* szResourceName,
DWORD ResourceName,
DWORD ResourceLanguage,
PULONG_PTR pResourceData,
LPDWORD pResourceSize
);
Parameters
szFileName
[in] Pointer to a null terminated string which is a full path to file.
szResourceType
[in] Pointer to string which is a resource type identifier. If the resource type is an
integer use the integer input variable to locate such resource.
ResourceType
[in] Pointer to string which is a resource type identifier. If the resource type is an
integer use this variable to pass the value and set its string version to NULL.
szResourceName
[in] Pointer to string which is a resource name identifier. If the resource type is an
integer use the integer input variable to locate such resource.
ResourceName
[in] Pointer to string which is a resource name identifier. If the resource type is an
integer use this variable to pass the value and set its string version to NULL.
ResourceLanguage
[in] Integer value that indicates the language of the resource to use.
pResourceData
[out] Pointer to a ULONG_PTR variable which will receive the offset on which the
resource is located on.
pResourceSize
[in] Pointer to a DWORD variable which will receive the size of located resource.
Return value
Boolean switch indicating whether or not the function was successful.
Remarks
None.
Example
None.
ResourcerFindResourceEx function
ResourcerFindResourceEx goes through the resource tree of the selected file and finds the specified
resource.
Syntax
bool __stdcall ResourcerFindResourceEx(
ULONG_PTR FileMapVA,
DWORD FileSize,
char* szResourceType,
DWORD ResourceType,
char* szResourceName,
DWORD ResourceName,
DWORD ResourceLanguage,
PULONG_PTR pResourceData,
LPDWORD pResourceSize
);
Parameters
FileMapVA
[in] Pointer to the mapped file content which must be mapped in read/write mode. This
pointer is set by using either StaticFileLoad function or Windows API for file
mapping.
FileSize
[in] Size of the mapped file.
szResourceType
[in] Pointer to string which is a resource type identifier. If the resource type is an
integer use the integer input variable to locate such resource.
ResourceType
[in] Pointer to string which is a resource type identifier. If the resource type is an
integer use this variable to pass the value and set its string version to NULL.
szResourceName
[in] Pointer to string which is a resource name identifier. If the resource type is an
integer use the integer input variable to locate such resource.
ResourceName
[in] Pointer to string which is a resource name identifier. If the resource type is an
integer use this variable to pass the value and set its string version to NULL.
ResourceLanguage
[in] Integer value that indicates the language of the resource to use.
pResourceData
[out] Pointer to a ULONG_PTR variable which will receive the offset on which the
resource is located on.
pResourceSize
[in] Pointer to a DWORD variable which will receive the size of located resource.
Return value
Boolean switch indicating whether or not the function was successful.
Remarks
None.
Example
None.
ResourcerEnumerateResource function
ResourcerEnumerateResource goes through the resource tree of the loaded file and enumerates all
found resources.
Syntax
void __stdcall ResourcerEnumerateResource(
char* szFileName,
void* CallBack
);
Parameters
szFileName
[in] Pointer to a null terminated string which is a full path to file whose resource will be
enumerated.
CallBack
[in] Address of a callback to call for each found resource.
CallBack definition
typedef bool(__stdcall *fResourceEnumerator)(wchar_t* szResourceType, \
DWORD ResourceType, wchar_t* szResourceName, DWORD ResourceName, \
DWORD ResourceLanguage, DWORD ResourceData, DWORD ResourceSize);
Return value
None.
Remarks
None.
Example
None.
ResourcerEnumerateResourceEx function
ResourcerEnumerateResourceEx goes through the resource tree of the loaded file and enumerates all
found resources.
Syntax
void __stdcall ResourcerEnumerateResourceEx(
ULONG_PTR FileMapVA,
DWORD FileSize,
void* CallBack
);
Parameters
szFileName
[in] Pointer to a null terminated string which is a full path to file whose resource will be
enumerated.
CallBack
[in] Address of a callback to call for each found resource.
CallBack definition
typedef bool(__stdcall *fResourceEnumerator)(wchar_t* szResourceType, \
DWORD ResourceType, wchar_t* szResourceName, DWORD ResourceName, \
DWORD ResourceLanguage, DWORD ResourceData, DWORD ResourceSize);
Return value
None.
Remarks
None.
Example
None.
Static module
The static module has functions designed to load and access PE files in order to work with them or use
predefined decryption behaviors in order to decrypt common crypters.
Static module constants
Constants used by: StaticFileLoad function
#define UE_ACCESS_READ 0
#define UE_ACCESS_WRITE 1
#define UE_ACCESS_ALL 2
Constants used by: StaticMemoryDecrypt function, StaticMemoryDecryptEx function,
StaticSectionDecrypt function and StaticMemoryDecryptSpecial function
#define UE_STATIC_DECRYPTOR_XOR 1
#define UE_STATIC_DECRYPTOR_SUB 2
#define UE_STATIC_DECRYPTOR_ADD 3
#define UE_STATIC_KEY_SIZE_1 1
#define UE_STATIC_KEY_SIZE_2 2
#define UE_STATIC_KEY_SIZE_4 4
#define UE_STATIC_KEY_SIZE_8 8
#define UE_STATIC_DECRYPTOR_FOREWARD 1
#define UE_STATIC_DECRYPTOR_BACKWARD 2
Constants used by: StaticMemoryDecompress function
#define UE_STATIC_APLIB 1
#define UE_STATIC_APLIB_DEPACK 2
#define UE_STATIC_LZMA 3
Constants used by: StaticHashMemory function and StaticHashFile function
#define UE_STATIC_HASH_MD5 1
#define UE_STATIC_HASH_SHA1 2
#define UE_STATIC_HASH_CRC32 3
StaticFileOpen function
StaticFileOpen opens a handle to a selected file. Using this function produces a normal Windows file
handle which can be used for other operations.
Syntax
bool __stdcall StaticFileOpen(
char* szFileName,
DWORD DesiredAccess,
LPHANDLE FileHandle,
LPDWORD FileSizeLow,
LPDWORD FileSizeHigh
);
Parameters
szFileName
[in] Pointer to a null terminated string which is a full path to file which will be opened.
DesiredAccess
[in] Determines the type of file access you will have. These values are defined in
Windows as GENERIC_READ and GENERIC_WRITE.
FileHandle
[out] Pointer to HANDLE variable which will receive the open file handle.
FileSizeLow
[out] Pointer to DWORD variable which will receive the file size.
FileSizeHigh
[out] Pointer to DWORD variable which will receive the high file size. This parameter can
be NULL if you don’t intend to open files larger than 4 Gb.
Return value
Boolean switch indicating whether or not the function was successful.
Example
None.
StaticFileGetContent function
StaticFileGetContent retrieves data from opened file at the specified location from the start of the file.
Syntax
bool __stdcall StaticFileGetContent(
HANDLE FileHandle,
DWORD FilePositionLow,
LPDWORD FilePositionHigh,
void* Buffer,
DWORD Size
);
Parameters
FileHandle
[in] Opened file HANDLE. File must be opened with read access.
FilePositionLow
[in] Low offset from which data retrieval will start. For files fewer than 4 Gb in size this is
the only positioning parameter you need.
FilePositionHigh
[in] High offset from which data retrieval will start. For file greater than 4 Gb in size this
parameter is needed only if the data needs to be read from addresses greater than
0xFFFFFFFF.
Buffer
[out] Pointer to buffer which will receive the retrieved data. Buffer must be large
enough to hold all requested data.
Size
[in] Size of the data to retrieve from the opened file.
Return value
Boolean switch indicating whether or not the function was successful.
Example
None.
StaticFileClose function
StaticFileClose closes an open file handle.
Syntax
void __stdcall StaticFileClose(
HANDLE FileHandle
);
Parameters
FileHandle
[in] Opened file HANDLE which will be closed by the function.
Return value
None.
Example
None.
StaticFileLoad function
StaticFileLoad either maps the selected file, or simulates its loading. Depending on the type of static
unpacker being developed, you need to specify the type of file memory access. File content can be
changed with either type, without affecting the loading type you are using.
Syntax
bool __stdcall StaticFileLoad(
char* szFileName,
DWORD DesiredAccess,
bool SimulateLoad,
LPHANDLE FileHandle,
LPDWORD LoadedSize,
LPHANDLE FileMap,
PULONG_PTR FileMapVA
);
Parameters
szFileName
[in] Pointer to a null terminated string which is a full path to file which will be mapped
or loaded.
DesiredAccess
[in] Determines the type of memory access you will have if you are mapping the file. It
can be one of the following: UE_ACCESS_READ, UE_ACCESS_WRITE and
UE_ACCESS_ALL.
SimulateLoad
[in] Boolean switch indicating whether or not to simulate the Windows PE loader.
FileHandle
[out] Pointer to HANDLE variable which will receive the open file handle.
LoadedSize
[out] Pointer to DWORD variable which will receive the size of the mapped file.
FileMap
[out] Pointer to HANDLE variable which will receive the file mapping handle.
FileMapVA
[out] Pointer to ULONG_PTR variable which will receive the mapped file base address.
Return value
Boolean switch indicating whether or not the function was successful.
StaticFileUnload function
StaticFileUnload either maps the selected file or simulates its loading. Depending on the type of static
unpacker being developed, you need to specify the type of file memory access. File content can be
changed with either type, without affecting the loading type you are using.
Syntax
bool __stdcall StaticFileUnload(
char* szFileName,
bool CommitChanges,
HANDLE FileHandle,
DWORD LoadedSize,
HANDLE FileMap,
ULONG_PTR FileMapVA
);
Parameters
szFileName
[in] Pointer to a null terminated string which is a full path to file which will receive the
changed file content. In case of simulated load this parameter is mandatory if you
need to save the changes to the file.
CommitChanges
[in] Boolean switch indicating whether or not to commit done changes to files loaded by
Windows PE loader simulation.
FileHandle
[in] Handle of the mapped file returned by StaticFileLoad.
LoadedSize
[in] Size of the mapped file returned by StaticFileLoad. You can change the file size and
by doing that either trim or increase its size.
FileMap
[in] File mapping handle returned by StaticFileLoad.
FileMapVA
[in] Base address at which the file is loaded returned by StaticFileLoad.
Return value
Boolean switch indicating whether or not the function was successful.
StaticMemoryDecrypt function
StaticMemoryDecrypt decrypts the selected memory range, using the specified decryption key and
decryption method.
Syntax
void __stdcall StaticMemoryDecrypt(
LPVOID MemoryStart,
DWORD MemorySize,
DWORD DecryptionType,
DWORD DecryptionKeySize,
ULONG_PTR DecryptionKey
);
Parameters
MemoryStart
[in] Pointer to the beginning of the memory block you want to decrypt in the remote
process.
MemorySize
[in] Size of the memory to decrypt.
DecryptionType
[in] Specifies which decryption engine to use. Decryption algorithm options:
UE_STATIC_DECRYPTOR_XOR, UE_STATIC_DECRYPTOR_SUB or
UE_STATIC_DECRYPTOR_ADD.
DecryptionKeySize
[in] Specifies the size of the decryption key that will be used. Can only be one of the
following key sizes: UE_STATIC_KEY_SIZE_1, UE_STATIC_KEY_SIZE_2,
UE_STATIC_KEY_SIZE_4 or UE_STATIC_KEY_SIZE_8.
DecryptionKey
[in] Specifies the decryption key to use.
Return value
None.
Example
StaticMemoryDecrypt(0x00401000, 0x1000, UE_STATIC_DECRYPTOR_XOR, UE_STATIC_KEY_SIZE_1, 0x90);
StaticMemoryDecryptEx function
StaticMemoryDecryptEx decrypts the selected memory range with a custom decryption algorithm. The
specified callback will be called for each member of the encrypted block.
Syntax
void __stdcall StaticMemoryDecryptEx(
LPVOID MemoryStart,
DWORD MemorySize,
DWORD DecryptionKeySize,
void* DecryptionCallBack
);
Parameters
MemoryStart
[in] Pointer to the beginning of the memory block you want to decrypt in the remote
process.
MemorySize
[in] Size of the memory to decrypt.
DecryptionKeySize
[in] Specifies the size of the decryption key that will be used. Can be custom or one of
the following key sizes: UE_STATIC_KEY_SIZE_1, UE_STATIC_KEY_SIZE_2,
UE_STATIC_KEY_SIZE_4 or UE_STATIC_KEY_SIZE_8. If you use a custom
size, make sure the MemorySize % DecryptionKeySize is NULL. If modus isn’t NULL,
the last few bytes of the memory content will not be decrypted.
DecryptionCallBack
[in] Callback that will decrypt the targeted memory slice. It is called for each member of
the encrypted block, with the block pointer increasing by the size of the decryption
key.
CallBack definition
typedef bool(__stdcall *fStaticCallBack)(void* sMemoryStart, int sKeySize);
Return value
None.
StaticSectionDecrypt function
StaticSectionDecrypt decrypts the selected memory range with a custom decryption algorithm. The
specified callback will be called for each member of the encrypted block.
Syntax
void __stdcall StaticSectionDecrypt(
ULONG_PTR FileMapVA,
DWORD SectionNumber,
bool SimulateLoad,
DWORD DecryptionType,
DWORD DecryptionKeySize,
ULONG_PTR DecryptionKey
);
Parameters
FileMapVA
[in] Pointer to the mapped file content. This pointer is set by either the StaticFileLoad
function or Windows API for file mapping.
SectionNumber
[in] Number of the section to decrypte. Section numbers range from zero to section
count minus one.
SimulatedLoad
[in] Boolean switch indicating whether or not the file was loaded by simulating
Windows PE loader. If FALSE the engine assumes that the file was mapped.
DecryptionType
[in] Specifies which decryption engine to use. Decryption algorithm options:
UE_STATIC_DECRYPTOR_XOR, UE_STATIC_DECRYPTOR_SUB or
UE_STATIC_DECRYPTOR_ADD.
DecryptionKeySize
[in] Determines the size of the decryption key that will be used. Can only be one of the
following key sizes: UE_STATIC_KEY_SIZE_1, UE_STATIC_KEY_SIZE_2,
UE_STATIC_KEY_SIZE_4 or UE_STATIC_KEY_SIZE_8.
DecryptionKey
[in] The decryption key to use.
Return value
None.
StaticMemoryDecryptSpecial function
StaticMemoryDecryptSpecial decrypts the selected memory range with a custom decryption algorithm.
The specified callback will be called for each member of the encrypted block.
Syntax
void __stdcall StaticMemoryDecryptSpecial(
LPVOID MemoryStart,
DWORD MemorySize,
DWORD DecryptionKeySize,
DWORD SpecDecryptionType,
void* DecryptionCallBack
);
Parameters
MemoryStart
[in] Pointer to the beginning of the memory block you want to decrypt in the remote
process.
MemorySize
[in] Size of the memory to decrypt.
DecryptionKeySize
[in] Specifies the size of the decryption key that will be used. Can be custom or one of
the following key sizes: UE_STATIC_KEY_SIZE_1, UE_STATIC_KEY_SIZE_2,
UE_STATIC_KEY_SIZE_4 or UE_STATIC_KEY_SIZE_8. If you use a custom
size, make sure the MemorySize % DecryptionKeySize is NULL. If modus isn’t NULL,
the last few bytes of the memory content will not be decrypted.
SpecDecryptionType
[in] Type of decryption to perform, can be: UE_STATIC_DECRYPTOR_FOREWARD or
UE_STATIC_DECRYPTOR_BACKWARD. This sets decryption direction.
DecryptionCallBack
[in] Callback that will decrypt the targeted memory slice. It is called for each member of
the encrypted block, with the block pointer increasing by the size of the decryption
key.
CallBack definition
typedef bool(__stdcall *fStaticCallBack)(void* sMemoryStart, int sKeySize);
Return value
None.
StaticMemoryDecompress function
StaticMemoryDecompress decompresses the selected memory block to designated destination. Source
memory block can be compressed with the following methods: aplib and lzma.
Syntax
void __stdcall StaticMemoryDecompress(
void* Source,
DWORD SourceSize,
void* Destination,
DWORD DestinationSize,
int Algorithm
);
Parameters
Source
[in] Pointer to the beginning of the memory block you want to decompress.
SourceSize
[in] Size of the memory to decompress.
Destination
[in] Pointer to memory buffer to hold decompressed content.
DestinationSize
[in] Size of the destination buffer.
Algorithm
[in] Specifies algorithm to use for decompression, can be one of the following:
UE_STATIC_APLIB, UE_STATIC_APLIB_DEPACK or UE_STATIC_LZMA.
Return value
Boolean switch indicating whether or not the function was successful.
Example
None.
StaticRawMemoryCopy function
StaticRawMemoryCopy copies data from mapped file directly to file on the disk. This function is used as
a workaround the memory usage problem when reading data from mapped files.
Syntax
bool __stdcall StaticRawMemoryCopy(
HANDLE hFile,
ULONG_PTR FileMapVA,
ULONG_PTR VitualAddressToCopy,
DWORD Size,
bool AddressIsRVA,
char* szDumpFileName
);
Parameters
hFile
[in] Handle of the opened file.
FileMapVA
[in] Pointer to the mapped file content. This pointer is set by either the StaticFileLoad
function or Windows API for file mapping.
VitualAddressToCopy
[in] Virtual address of data inside the mapped file which will be copied to new file.
Size
[in] Number of bytes to copy.
AddressIsRVA
[in] Boolean switch indicating whether or not the VirtualAddressToCopy is a relative
address.
szDumpFileName
[in] Pointer to the full path of the file in which to write the memory content.
Return value
Boolean switch indicating whether or not the function was successful.
Example
None.
StaticRawMemoryCopyEx function
StaticRawMemoryCopyEx copies data from opened file directly to another file on the disk.
Syntax
bool __stdcall StaticRawMemoryCopyEx(
HANDLE hFile,
DWORD RawAddressToCopy,
DWORD Size,
char* szDumpFileName
);
Parameters
hFile
[in] Handle of the opened file.
RawAddressToCopy
[in] Offset from which the file copy will be performed.
Size
[in] Number of bytes to copy.
szDumpFileName
[in] Pointer to the full path of the file in which to write the memory content.
Return value
Boolean switch indicating whether or not the function was successful.
Example
None.
StaticRawMemoryCopyEx64 function
StaticRawMemoryCopyEx64 copies data from opened file directly to another file on the disk. This
function is used for file greater than 4 Gb in size.
Syntax
bool __stdcall StaticRawMemoryCopyEx64(
HANDLE hFile,
DWORD64 RawAddressToCopy,
DWORD64 Size,
char* szDumpFileName
);
Parameters
hFile
[in] Handle of the opened file.
RawAddressToCopy
[in] Offset from which the file copy will be performed.
Size
[in] Number of bytes to copy.
szDumpFileName
[in] Pointer to the full path of the file in which to write the memory content.
Return value
Boolean switch indicating whether or not the function was successful.
Example
None.
StaticHashMemory function
StaticHashMemory hashes the selected memory part with a selected hashing algorithm.
Syntax
bool __stdcall StaticHashMemory(
void* MemoryToHash,
DWORD SizeOfMemory,
void* HashDigest,
bool OutputString,
int Algorithm
);
Parameters
MemoryToHash
[in] Pointer to memory to be hashed.
SizeOfMemory
[in] Size of the memory to be hashed.
HashDigest
[out] Pointer to a buffer which will receive the hash. If OutputString is set to TRUE
output will be a string otherwise it will be an array containing the hash value.
OutputString
[in] This input variable determines the output type. If it is set to TRUE the output will be
a string otherwise it will be an array containing the hash value.
Algorithm
[in] Determines which algorithm to use for hashing, can be one of the following:
UE_STATIC_HASH_MD5, UE_STATIC_HASH_SHA1 or UE_STATIC_HASH_CRC32.
Return value
Boolean switch indicating whether or not the function was successful.
Example
None.
StaticHashFile function
StaticHashFile hashes the selected file with a selected hashing algorithm.
Syntax
bool __stdcall StaticHashFile(
char* szFileName,
char* HashDigest,
bool OutputString,
int Algorithm
);
Parameters
szFileName
[in] Path to file which will be hashed.
HashDigest
[out] Pointer to a buffer which will receive the hash. If OutputString is set to TRUE
output will be a string otherwise it will be an array containing the hash value.
OutputString
[in] This input variable determines the output type. If it is set to TRUE the output will be
a string otherwise it will be an array containing the hash value.
Algorithm
[in] Determines which algorithm to use for hashing, can be one of the following:
UE_STATIC_HASH_MD5, UE_STATIC_HASH_SHA1 or UE_STATIC_HASH_CRC32.
Return value
Boolean switch indicating whether or not the function was successful.
Example
None.
Handler module
The handler module has functions designed to work with open handles and mutexes. Additionally, it can
find processes which use the designated mutex, or close all lock handles to selected files.
Handler module constants
Constants used by: HandlerGetHandleDetails function
#define UE_OPTION_HANDLER_RETURN_HANDLECOUNT 1
#define UE_OPTION_HANDLER_RETURN_ACCESS 2
#define UE_OPTION_HANDLER_RETURN_FLAGS 3
#define UE_OPTION_HANDLER_RETURN_TYPENAME 4
#define UE_OPTION_HANDLER_RETURN_TYPENAME_UNICODE 5
Handler module structures
Structures used by: HandlerEnumerateOpenHandles function and HandlerEnumerateLockHandles
function
typedef struct{
ULONG ProcessId;
HANDLE hHandle;
}HandlerArray, *PHandlerArray;
HandlerGetActiveHandleCount function
HandlerGetActiveHandleCount gets the number of open handles inside the selected process.
Syntax
long __stdcall HandlerGetActiveHandleCount(
DWORD ProcessId
);
Parameters
ProcessId
[in] Process ID of the running process, which can be acquired with the Windows API.
Return value
Boolean switch indicating whether or not the function was successful.
Remarks
None.
Example
None.
HandlerIsHandleOpen function
HandlerIsHandleOpen checks whether the remote handle is still open.
Syntax
bool __stdcall HandlerIsHandleOpen(
DWORD ProcessId,
HANDLE hHandle
);
Parameters
ProcessId
[in] Process ID of the running process, which can be acquired with the Windows API.
hHandle
[in] Handle inside the remote process whose state will be queried.
Return value
Boolean switch indicating whether or not the handle is still open.
Remarks
None.
Example
None.
HandlerGetHandleName function
HandlerGetHandleName retrieves the name of an open handle in a remote process.
Syntax
void* __stdcall HandlerGetHandleName(
HANDLE hProcess,
DWORD ProcessId,
HANDLE hHandle,
bool TranslateName
);
Parameters
hProcess
[in] Handle of the process whose handle info is needed.
ProcessId
[in] Process ID of the running process, which can be acquired with the Windows API.
hHandle
[in] Handle inside the remote process whose name you want to find.
TranslateName
[in] Boolean switch indicating whether or not to translate the name of the handle to
non native name. Names or paths which contain physical devices in their file
references are resolved with this function.
Return value
Function returns a pointer to the handle name, or NULL if the supplied string can’t be retrieved.
Remarks
CAUTION: The string with the translated native name is stored inside the engine, which makes
this function multi thread unsafe.
Example
None.
HandlerGetHandleDetails function
HandlerGetHandleDetails retrieves additional information about an open handle in a remote process.
Syntax
long long __stdcall HandlerGetHandleDetails(
HANDLE hProcess,
DWORD ProcessId,
HANDLE hHandle,
DWORD InformationReturn
);
Parameters
hProcess
[in] Handle of the process whose handle info is needed.
ProcessId
[in] Process ID of the running process, which can be acquired with the Windows API.
hHandle
[in] Handle inside the remote process whose name you want.
InformationReturn
[in] Defines the type of the information to return about the specified remote handle. It
can be one of the following:
. UE_OPTION_HANDLER_RETURN_HANDLECOUNT
. UE_OPTION_HANDLER_RETURN_ACCESS
. UE_OPTION_HANDLER_RETURN_FLAGS
. UE_OPTION_HANDLER_RETURN_TYPENAME
. UE_OPTION_HANDLER_RETURN_TYPENAME_UNICODE
Return value
Function can return a DWORD value of the selected handle property or a pointer to handle
name, depending on the InformationReturn value.
Remarks
CAUTION: The string with the translated native name is stored inside the engine, which makes
this function multi thread unsafe.
HandlerEnumerateOpenHandles function
HandlerEnumerateOpenHandles gets the information about all open handles for the selected process
inside one array.
Syntax
long __stdcall HandlerEnumerateOpenHandles(
DWORD ProcessId,
LPVOID HandleBuffer,
DWORD MaxHandleCount
);
Parameters
ProcessId
[in] Process ID of the running process, which can be acquired with the Windows API.
HandleDataBuffer
[out] Pointer to the array which will receive the lock handle information. The array is
defined as stated in the
Handler module .
MaxHandleCount
[in] Specifies the maximum possible entries in the array.
Return value
Returns the number of open handles found.
Remarks
None.
Example
None.
HandlerIsFileLocked function
HandlerIsFileLocked checks whether the selected file or folder is locked by open handles from any of
the running processes.
Syntax
bool __stdcall HandlerIsFileLocked(
char* szFileOrFolderName,
bool NameIsFolder,
bool NameIsTranslated
);
Parameters
szFileOrFolderName
[in] Pointer to a null terminated string which is a full path to file or folder which will be
checked for locking handles.
NameIsFolder
[in] Boolean switch indicating whether the provided string is a folder.
NameIsTranslated
[in] Boolean switch indicating whether the string has already been translated.
Return value
Boolean switch indicating whether or not the file or folder is locked.
Remarks
None.
Example
None.
HandlerCloseAllLockHandles function
HandlerCloseAllLockHandles checks whether the selected file or folder is locked by open handles from
any of the running processes, and if so, whether it should to try to close all of them, regardless of the
process locking the file or folder. Use this function with caution because it can cause any applications
relying on those handles to crash.
Syntax
bool __stdcall HandlerCloseAllLockHandles(
char* szFileOrFolderName,
bool NameIsFolder,
bool NameIsTranslated
);
Parameters
szFileOrFolderName
[in] Pointer to a null terminated string which is a full path to file or folder which will be
checked for locking handles and whose lock handles will be closed.
NameIsFolder
[in] Boolean switch indicating whether the provided string is a folder.
NameIsTranslated
[in] Boolean switch indicating whether the string has already been translated.
Return value
Boolean switch indicating whether or not the file or folder is still locked.
Remarks
None.
Example
None.
HandlerEnumerateLockHandles function
HandlerEnumerateLockHandles puts the information about all file or folder locking handles into one
array.
Syntax
long __stdcall HandlerEnumerateLockHandles(
char* szFileOrFolderName,
bool NameIsFolder,
bool NameIsTranslated,
LPVOID HandleDataBuffer,
DWORD MaxHandleCount
);
Parameters
NameIsFolder
[in] Boolean switch indicating whether the provided string is a folder.
NameIsTranslated
[in] Boolean switch indicating whether the string has already been translated.
HandleDataBuffer
[out] Pointer to the array that will receive the lock handle information. The array is
defined as stated in the
Handler module .
MaxHandleCount
[in] Defines the maximum possible entries in the array.
Return value
Returns the number of lock handles found.
Remarks
None.
Example
None.
HandlerCloseRemoteHandle function
HandlerCloseRemoteHandle closes handles in a remote process. Use this function with caution because
it can cause any applications relying on those handles to crash.
Syntax
bool __stdcall HandlerCloseRemoteHandle(
HANDLE hProcess,
HANDLE hHandle
);
Parameters
hProcess
[in] Handle of the process whose handle will be closed.
hHandle
[in] Handle to close inside the remote process.
Return value
Boolean switch indicating whether or not the handle has closed.
Remarks
None.
Example
None.
HandlerEnumerateOpenMutexes function
HandlerEnumerateOpenMutexes puts the information about all open mutex handles for the specified
process into an array.
Syntax
long __stdcall HandlerEnumerateOpenMutexes(
HANDLE hProcess,
DWORD ProcessId,
LPVOID HandleBuffer,
DWORD MaxHandleCount
);
Parameters
hProcess
[in] Handle of the process whose mutexes will be enumerated.
ProcessId
[in] Process ID of the running process which can be acquired with the Windows API.
HandleDataBuffer
[out] Pointer to the array that will receive the open mutex handle information.
MaxHandleCount
[in] Defines the maximum possible entries in the array.
Return value
Returns the number of open mutex handles found.
Remarks
Array is defined as an array of HANDLEs.
Example
None.
HandlerGetOpenMutexHandle function
HandlerGetOpenMutexHandle gets the handle for the remotely opened mutex.
Syntax
long long __stdcall HandlerGetOpenMutexHandle(
HANDLE hProcess,
DWORD ProcessId,
char* szMutexString
);
Parameters
hProcess
[in] Handle of the process whose mutexes will be enumerated.
ProcessId
[in] Process ID of the running process which can be acquired with the Windows API.
szMutexString
[in] Pointer to string which is the mutex whose handle will be returned.
Return value
Returns the handle inside the remote process for the selected mutex or NULL if mutex isn’t
found.
Remarks
None.
Example
None.
HandlerGetProcessIdWhichCreatedMutex function
HandlerGetProcessIdWhichCreatedMutex gets the process ID which has opened the selected mutex.
Syntax
long __stdcall HandlerGetProcessIdWhichCreatedMutex(
char* szMutexString
);
Parameters
szMutexString
[in] Pointer to string which is the mutex whose presence will be queried in all of the
running processes.
Return value
Returns the ID of the process which has opened the selected mutex.
Remarks
None.
Example
None.
Extension module
The extension module has functions designed to work with plugins created for the TitanEngine.
Functions inside this module provide interface to manipulating loaded plugins.
Guide to writing extensions for TitanEngine
TitanEngine extensions are created as normal dynamic link libraries placed in the selected folder (either
.\plugins\x86 or .\plugins\x64) for the engine to load. Following export functions are used by the engine:
. TitanResetPlugin – Function which is called every time the debugging starts within the
DebuLoop function.
. TitanReleasePlugin – Function which is called when the plugin gets unloaded or the engine
shuts down.
. TitanRegisterPlugin – Function which is called when the plugin gets loaded by the engine. Plugin
should register itself by using a unique name (up to 64 characters long) and optionally fill the
version information.
. TitanDebuggingCallBack – Function which is called for every debug even registered by the
engine. This function has a CallReason parameter which can be one of the following:
UE_PLUGIN_CALL_REASON_PREDEBUG, UE_PLUGIN_CALL_REASON_EXCEPTION or
UE_PLUGIN_CALL_REASON_POSTDEBUG.
Extension structure and function definitions
typedef struct{
char PluginName[64];
DWORD PluginMajorVersion;
DWORD PluginMinorVersion;
HMODULE PluginBaseAddress;
void* TitanDebuggingCallBack;
void* TitanRegisterPlugin;
void* TitanReleasePlugin;
void* TitanResetPlugin;
bool PluginDisabled;
}PluginInformation, *PPluginInformation;
__declspec(dllexport) void __stdcall TitanResetPlugin();
__declspec(dllexport) void __stdcall TitanReleasePlugin();
__declspec(dllexport) bool __stdcall TitanRegisterPlugin(char* szPluginName,
LPDWORD titanPluginMajorVersion, LPDWORD titanPluginMinorVersion);
__declspec(dllexport) void __stdcall TitanDebuggingCallBack(LPDEBUG_EVENT
debugEvent, int CallReason);
ExtensionManagerIsPluginLoaded function
ExtensionManagerIsPluginLoaded checks if the selected plugin is loaded.
Syntax
bool __stdcall ExtensionManagerIsPluginLoaded(
char* szPluginName
);
Parameters
szPluginName
[in] Unique identifier plugin uses to register itself.
Return value
Boolean switch indicating whether or not the plugin is still loaded.
Remarks
None.
Example
None.
ExtensionManagerIsPluginEnabled function
ExtensionManagerIsPluginEnabled checks if the selected plugin is enabled.
Syntax
bool __stdcall ExtensionManagerIsPluginEnabled(
char* szPluginName
);
Parameters
szPluginName
[in] Unique identifier plugin uses to register itself.
Return value
Boolean switch indicating whether or not the plugin is enabled.
Remarks
None.
Example
None.
ExtensionManagerDisablePlugin function
ExtensionManagerDisablePlugin temporarily disables the use of the selected plugin.
Syntax
bool __stdcall ExtensionManagerDisablePlugin(
char* szPluginName
);
Parameters
szPluginName
[in] Unique identifier plugin uses to register itself.
Return value
Boolean switch indicating whether or not the plugin was disabled.
Remarks
None.
Example
None.
ExtensionManagerDisableAllPlugins function
ExtensionManagerDisableAllPlugins temporarily disables the use of all loaded plugins.
Syntax
bool __stdcall ExtensionManagerDisableAllPlugins();
Parameters
None.
Return value
Boolean switch indicating whether or not the plugins were disabled.
Remarks
None.
Example
None.
ExtensionManagerEnablePlugin function
ExtensionManagerEnablePlugin enables the use of the selected previously disabled plugin.
Syntax
bool __stdcall ExtensionManagerEnablePlugin(
char* szPluginName
);
Parameters
szPluginName
[in] Unique identifier plugin uses to register itself.
Return value
Boolean switch indicating whether or not the plugin was enabled.
Remarks
None.
Example
None.
ExtensionManagerEnableAllPlugins function
ExtensionManagerEnableAllPlugins enables the use of all previously disabled plugins.
Syntax
bool __stdcall ExtensionManagerEnableAllPlugins();
Parameters
None.
Return value
Boolean switch indicating whether or not the plugins were enabled.
Remarks
None.
Example
None.
ExtensionManagerUnloadPlugin function
ExtensionManagerUnloadPlugin unloads the selected plugin from the current session. It will still be
loaded the next time the engine starts. Only way to actually remove the plugin completely is to delete it
from the plugins folder.
Syntax
bool __stdcall ExtensionManagerUnloadPlugin(
char* szPluginName
);
Parameters
szPluginName
[in] Unique identifier plugin uses to register itself.
Return value
Boolean switch indicating whether or not the plugin was unloaded.
Remarks
None.
Example
None.
ExtensionManagerUnloadAllPlugins function
ExtensionManagerUnloadAllPlugins unloads the selected plugin from the current session. All plugins
will still be loaded the next time the engine starts. Only way to actually remove any of the plugins
completely is to delete them from the plugins folder.
Syntax
bool __stdcall ExtensionManagerUnloadAllPlugins();
Parameters
None.
Return value
Boolean switch indicating whether or not the plugins were unloaded.
Remarks
None.
Example
None.
ExtensionManagerGetPluginInfo function
ExtensionManagerGetPluginInfo retrieves the information about the selected plugin. Data returned can
be modified in order to manipulate the plugin behavior.
Syntax
void* __stdcall ExtensionManagerGetPluginInfo(
char* szPluginName
);
Parameters
szPluginName
[in] Unique identifier plugin uses to register itself.
Return value
Pointer to PluginInformation structure or NULL if the selected plugin isn’t currently loaded.
Remarks
None.
Example
None.
Engine module
The engine module isn’t a separate module or a functional part; instead it is a top level engine
functionality which utilizes multiple engine functions to perform a certain task.
EngineCreateMissingDependencies function
EngineCreateMissingDependencies goes thought the import table of the selected file and creates all
dynamic link libraries needed by the file which are not present on the system.
Syntax
bool __stdcall EngineCreateMissingDependencies(
char* szFileName,
char* szOutputFolder,
bool LogCreatedFiles
);
Parameters
szFileName
[in] Pointer to the full path of the file to inspect for missing dependencies.
szOutputFolder
[in] Pointer to the full path of the folder in which the files will be created. Most
commonly this is the folder in which the file which will be unpacked is.
LogCreatedFile
[in] Indicates whether or not to internally log all created files. Using this option later
enables simple deletion of created files.
Return value
Boolean switch indicating whether or not the function was successful.
Remarks
None.
Example
None.
EngineFakeMissingDependencies function
EngineFakeMissingDependencies performs low level API hooking in user mode to ensure that
dynamically loaded libraries are always virtually present. This ensures that all libraries which are loaded
by Windows API are seemingly present. This function should be called once the debugee execution hit
the packed entry point in cases when packing shell dynamically loads libraries.
Syntax
bool __stdcall EngineCreateMissingDependencies(
HANDLE hProcess
);
Parameters
hProcess
[in] Handle of the process whose dynamically loaded modules will be simulated.
Return value
Boolean switch indicating whether or not the function was successful.
Remarks
None.
Example
None.
EngineDeleteCreatedDependencies function
EngineDeleteCreatedDependencies deletes logged created missing dependencies. This function
performs disk cleanup at the end of unpacking process. If files can’t be deleted at that particular time
they will be moved to system’s temporary folder for user deletion.
Syntax
bool __stdcall EngineDeleteCreatedDependencies();
Parameters
None.
Return value
Boolean switch indicating whether or not the function was successful.
Remarks
None.
Example
None.
EngineCreateUnpackerWindow function
EngineCreateUnpackerWindow creates a default and easily customizable graphical user interface for
your unpacker project. Program doesn’t return from this call until the window has been closed.
Syntax
bool __stdcall EngineCreateUnpackerWindow(
char* WindowUnpackerTitle,
char* WindowUnpackerLongTitle,
char* WindowUnpackerName,
char* WindowUnpackerAuthor,
void* StartUnpackingCallBack
);
Parameters
WindowUnpackerTitle
[in] Custom graphical user interface window title string.
WindowUnpackerLongTitle
[in] Custom graphical user interface long unpacker name string.
WindowUnpackerName
[in] Custom graphical user interface unpacker name string.
WindowUnpackerAuthor
[in] Custom graphical user interface unpacker author name string.
StartUnpackingCallBack
[in] Callback which will be called once the user presses unpack button.
CallBack definition
typedef void(__stdcall *fStartUnpacking)(
char* szInputFile, bool RealignFile, bool CopyOverlay);
Return value
Boolean switch indicating whether or not the function was successful.
Example
EngineCreateUnpackerWindow("UPX 1.x - 3.x", "Unpacker for UPX packed files", "RL!deUPX 1.x - 3.x",
"ReversingLabs Corporation", &InitializeUnpacking);
EngineAddUnpackerWindowLogMessage function
EngineAddUnpackerWindowLogMessage can be used to show unpacking log messages while the
unpacker uses built-in graphical user interface.
Syntax
void __stdcall EngineAddUnpackerWindowLogMessage(
char* szLogMessage
);
Parameters
szLogMessage
[in] Message which will be shown inside the unpacker log window.
Return value
None.
Remarks
None.
Example
None.
Engine unpacker simplification module
The engine module isn’t a separate module or a functional part; instead it is a top level engine
functionality which utilizes multiple engine functions to perform a certain task. Engine unpacker
simplification functions enable easy unpacker coding for most common portable executable packers.
Engine simplification module constants
Constants used by: EngineUnpackerSetBreakCondition function
#define UE_UNPACKER_CONDITION_SEARCH_FROM_EP 1
#define UE_UNPACKER_CONDITION_LOADLIBRARY 1
#define UE_UNPACKER_CONDITION_GETPROCADDRESS 2
#define UE_UNPACKER_CONDITION_ENTRYPOINTBREAK 3
#define UE_UNPACKER_CONDITION_RELOCSNAPSHOT1 4
#define UE_UNPACKER_CONDITION_RELOCSNAPSHOT2 5
EngineUnpackerInitialize function
EngineUnpackerInitialize initializes simplified unpacking routines. Initialization creates an unpacking
process for any provided input portable executable be it EXE or DLL.
Syntax
void __stdcall EngineUnpackerInitialize(
char* szFileName,
char* szUnpackedFileName,
bool DoLogData,
bool DoRealignFile,
bool DoMoveOverlay,
void* EntryCallBack
);
Parameters
szFileName
[in] Pointer to the full path of the file to debug.
szUnpackedFileName
[in] Pointer to the full path of the file which will be created as the end result of the
unpacking process.
DoLogData
[in] Enables or disable automatic data logging.
DoRealignFile
[in] Enables or disables file realigning at the end of the unpacking process.
DoMoveOverlay
[in] Enables or disables overlay moving from original to the unpacked file at the end of
the unpacking process.
EntryCallBack
[in] Callback which will be called once the file reaches its packed entry point.
Return value
Boolean switch indicating whether or not the function was successful.
Example
None.
EngineUnpackerSetBreakCondition function
EngineUnpackerSetBreakCondition function searches the debugee memory and sets breakpoints for
selected patterns.
Syntax
bool __stdcall EngineUnpackerSetBreakCondition(
void* SearchStart,
DWORD SearchSize,
void* SearchPattern,
DWORD PatternSize,
DWORD PatternDelta,
ULONG_PTR BreakType,
bool SingleBreak,
DWORD Parameter1,
DWORD Parameter2
);
Parameters
SearchStart
[in] Indicates the point in memory from which search will be performed.
SearchSize
[in] Size of the memory to search.
SearchPattern
[in] Pointer to pattern to be searched.
PatternDelta
[in] On successfully found pattern its offset is affected by delta value. This helps to set
the breakpoint on any byte relative to the found pattern. This variable is a signed
integer which means that delta can be negative value as well.
BreakType
[in] Callback address which will be called once the breakpoint has been hit. This is a
default breakpoint callback type. Additionally following values are considered valid:
. UE_UNPACKER_CONDITION_LOADLIBRARY
. UE_UNPACKER_CONDITION_GETPROCADDRESS
. UE_UNPACKER_CONDITION_ENTRYPOINTBREAK
. UE_UNPACKER_CONDITION_RELOCSNAPSHOT1
. UE_UNPACKER_CONDITION_RELOCSNAPSHOT2
SingleBreak
[in] Boolean switch indicating whether or not the breakpoint will be used only once.
Parametar1
[in] If you use predefined values as your BreakType Parameter1 indicates the following
data will be used by the TitanEngine when breakpoints are processed:
. LoadLibrary
o Parameter1 is the register (UE_EAX . UE_EDI) which points to the
remote DLL name string.
. GetProcAddress
o Parameter1 is the register (UE_EAX . UE_EDI) which points to the
remote API name string or contains API ordinal number. Difference
between the two is automatically detected.
. EntryPointBreak
o Parameter1 is unused.
. RelocateSnapshot1
o Relative virtual address from which the memory snapshot will start.
. RelocateSnapshot2
o Relative virtual address from which the memory snapshot will start.
Parametar2
[in] If you use predefined values as your BreakType Parameter2 indicates the following
data will be used by the TitanEngine when breakpoints are processed:
. LoadLibrary
o Parameter2 is the register (UE_EAX . UE_EDI) which holds the first
import trunk address. This is optional and can be set to NULL.
. GetProcAddress
o Parameter2 is the register (UE_EAX . UE_EDI) which holds the API write
location.
. EntryPointBreak
o Parameter2 is unused.
. RelocateSnapshot1
o Size of the memory to snapshot.
. RelocateSnapshot2
o Size of the memory to snapshot.
Return value
Boolean switch indicating whether or not the function was successful in finding the selected
pattern and placing the breakpoint there.
Remarks
For simplification to work correctly you must define LoadLibrary, GetProcAddress and entry
point breakpoints as a minimum of functionality.
If relocation snapshot two isn’t defined second snapshot is automatically performed once the
entry point breakpoint is hit.
If you don’t set the original entry point and use the default entry point callback EIP/RIP address
will be used to set that data.
Example
None.
EngineUnpackerSetEntryPointAddress function
EngineUnpackerSetEntryPointAddress sets the original entry point address. This function is used if
breaking at the original entry point isn’t possible and the address of the original entry point must be
read by the program.
Syntax
void __stdcall EngineUnpackerSetEntryPointAddress(
ULONG_PTR UnpackedEntryPointAddress
);
Parameters
UnpackedEntryPointAddress
[in] Sets the original entry point before the unpacking finalization.
Return value
None.
Example
None.
EngineUnpackerFinalizeUnpacking function
EngineUnpackerFinalizeUnpacking finalizes the unpacking process performing the memory dumping
and image fixing procedures. This function should only be called if EngineUnpackerSetEntryPointAddress
calling was necessary.
Syntax
void __stdcall EngineUnpackerFinalizeUnpacking();
Parameters
None.
Return value
None.
Example
None.
TitanEngine 2.0.1 - history
. SDK
o Extended SDK headers to support Delphi
o Changes to SDK.h to support non MSVC compilers
o Changed the file/folder layout and fixed relative paths in RC file
o Removed type-o mistakes and bad function definitions
. Bug fixes
o Fixed some mistakes in SDK.h
o Added missing entries in TitanEngine.def
o FindEx searched only 0x1000 bytes
o Fixed a minor bug inside injectTerminator
o EngineExtractForwarderData crash on invalid input
o RelocaterGrabRelocationTableEx doesn't grab whole table
o RelocaterCompareTwoSnapshots crash when first DWORD of the snapshot is relocated
o RelocaterCompareTwoSnapshots doesn't correctly compare two snapshots for some packers
o ImporterAutoFixIATEx very rare crash handled by handler but it makes import table invalid
o ImporterAutoFixIATEx incorrect import fixing if import is only exported by ordinal
o ImporterAutoFixIATEx incorrect stepping if step is greater than one
o Fixed StaticLoadFile & StaticUnloadFile to be compatible with x64
o Fixed a problem with imports and WinSxS folder
o Fixed a crash with Librarian on Windows XP x64
o Fixed problem with NtdllDefWindowProc on Vista x64
o Fixed problem with deleting temp files: DLLLoader.exe & *.module base reserve file
o Fixed problem with DumpProcess on x64 systems
o Fixed problem with DumpProcess and empty last PE sections
o Fixed problem with DumpProcess and files with non default SectionAlignment
o Fixed problem with DumpProcess and dumping PAGE_GUARD protected memory
o Fixed UPX unpacker sample not working on files packed with --lzma option
o Fixed problem with Exporter module and building new export table under x64 systems
o Fixed problem with Importer module and Windows 7 kernelbase.dll MiniWin
o Fixed problem with RealignPE/RealignPEEx and files with non default SectionAlignment
. Additions
o Fill & FillEx now have a default fill byte value of 0x90 if no fill byte is supplied
o SetHardwareBreakPointEx function for setting breakpoints in custom threads
o Global variable UE_ENGINE_RESET_CUSTOM_HANDLER set to TRUE resetting custom handler on debug init
o Improved speed of API & DLL data resolving
o Added function: ImporterAddNewOrdinalAPI
o Added function: ImporterGetAPIOrdinalNumber
o Added function: ImporterGetAPIOrdinalNumberFromDebugee
o Added function: ImporterGetForwardedAPIOrdinalNumber
o Added function: ImporterGetLastAddedDLLName
o Added function: ImporterGetDLLName
o Added function: GetUnusedHardwareBreakPointRegister
o Changed function: HideDebugger, less parameters and x64 compliant
o Added function: UnHideDebugger
o Added function: GetPEBLocation
. Samples
o Unpacking ASPack 2.12, features usage of: RelocaterGrabRelocationTableEx and GetRemoteString
o Unpacking FSG 2.0, features usage of: overlay detection
o Unpacking PeCompact 2.0 - 3.x, features usage of: ImporterAutoFixIATEx with custom callback for fixing redirection
o Unpacking DEF 1.0, features usage of: static unpacker functions
o Unpacking LameCrypt 1.0, features usage of: static unpacker functions
TitanEngine 2.0.2 - history
. SDK/PDK
o Added functions to support UNICODE
o Extended SDK headers to support MASM32
o Changes to SDK.h to support non MSVC compilers, Set default structure align to: 1 byte
o Removed type-o mistakes and bad function definitions
. Bug fixes
o Fixed some mistakes in SDK.h
o Fixed a bug in SetPE32DataForMappedFile
o Fixed a bug with import processing and Windows7 x64
o Fixed a bug in PastePEHeader which made it not work on x64
o Fixed a bug in PastePEHeader which prevented header paste when header doesn't have write attribute
o Fixed a rare disassemble crash which happened due to distorm not having enough space
o Fixed problem with GetPE32DataFromMappedFileEx and x64
o Fixed a rare problem with FindEx and some memory ranges
o Fixed a bug inside LibrarianGetLibraryInfoEx
. Additions
o Added functions
. RelocaterRelocateMemoryBlock, ThreaderImportRunningThreadData, EngineFakeMissingDependencies
. EngineDeleteCreatedDependencies, EngineCreateMissingDependencies, EngineCreateMissingDependenciesW
. ExtensionManagerIsPluginLoaded, ExtensionManagerIsPluginEnabled, ExtensionManagerDisablePlugin
. ExtensionManagerDisableAllPlugins, ExtensionManagerEnablePlugin, ExtensionManagerEnableAllPlugins
. ExtensionManagerUnloadPlugin, ExtensionManagerUnloadAllPlugins, ExtensionManagerGetPluginInfo
. HooksSafeTransition, HooksSafeTransitionEx, HooksIsAddressRedirected, HooksGetTrampolineAddress
. HooksGetHookEntryDetails, HooksInsertNewRedirection, HooksInsertNewIATRedirection
. HooksInsertNewIATRedirectionEx, HooksRemoveRedirection, HooksRemoveRedirectionsForModule
. HooksRemoveIATRedirection, HooksDisableRedirection, HooksDisableRedirectionsForModule
. HooksDisableIATRedirection, HooksEnableRedirection, HooksEnableRedirectionsForModule
. HooksEnableIATRedirection, HooksScanModuleMemory, HooksScanEntireProcessMemory
. HooksScanEntireProcessMemoryEx, StaticRawMemoryCopy, StaticMemoryDecompress,
. StaticMemoryDecryptSpecial, ResourcerFindResource, ResourcerEnumerateResource,
. StaticHashMemory, StaticHashFile, IsFileBeingDebugged
o Added TitaniumHooks as a module and a separate project
. Samples
o Samples of using Hooks module: HooksDemo and LoaderSpy
o Plugin samples
. TitanEngine: ASMExtractor, DataExtractor, lynxImpRec & Nexus
. OllyDBG: TitaniumHandles & ImportStudio
. PeID: TitaniumOverlay
o Tool samples
. LameCrypter
o Unpacker samples
. C
. MarioPack, CryptoCrackPE, ExeFog, MEW, PackMan, nPack, yC
. Delphi
. MEW 5, PeX
. MASM
. UPX
TitanEngine 2.0.3 - history
. SDK/PDK
o Extended SDK headers to support Python, LUA and C++
o Removed type-o mistakes and bad function definitions
o Documented missing functions
. Bug fixes
o Fixed a bug inside Find/Ex
o Fixed a bug fix inside EngineSimulateNtLoaderW
o Enabled code execution inside mapped images loaded with all access
o Fixed a bug in SetPE32Data/W which prevented data update due to incorrect file access
o Fixed a bug inside ConvertVAtoFileOffset/Ex which incorrectly converted addresses in some cases
o Multiple changes inside IsPE32FileValidEx/W making it compatible with Microsoft compilers
o Multiple changes inside FixBrokenPE32FileEx/W making it compatible with Microsoft compilers
o Fixed a bug inside debugging logic that causes the debugger to handle hardware breakpoints set by the debugee
o Fixed a bug inside StepOver making it unsafe to execute with self modifying code with multi byte breakpoints turned on
o Fixed a bug inside StepInto making it execute one time more than specified by the program
o Added an option to select the type of breakpoint set with SetBPX and SetBPXEx
o Implemented UD2 breakpoints correctly inside debugging logic
o Fixed a bug inside ImporterAddNewAPI with ordinal logic
o Improved the accuracy of ImporterEstimatedSize function
o Improved ImporterFindAPIWriteLocation to take ordinals into the account
o Fixed a bug inside ImporterRelocateWriteLocation and cases of single imported DLL file
o Fixed a bug inside ImporterLoadImportTableW with certain compilers
o Improved ImporterEnumAdded data to take ordinals into the account
o Fixed a bug in HooksInsertNewIATRedirectionEx with certain compilers
o Fixed a bug inside RemoteLoadLibraryW making it fail with DEP turned on
o Fixed a bug inside RemoteFreeLibrary making it fail with DEP turned on
o Fixed a bug inside RemoteExitProcess making it fail with DEP turned on
o Fixed a bug inside StaticRawMemoryCopyW preventing it from copying all data
o Fixed a bug inside DetachDebuggerEx that crashed the debugee upon detaching
. Additions
o Added functionality
. Added GUI interface for unpackers
. Added unpacker simplification functions
o Added functions
. GetContextFPUDataEx, SetContextFPUDataEx, MatchPatternEx, MatchPattern
. SetErrorModel, ImporterFindOrdinalAPIWriteLocation, ImporterIsForwardedAPI
. StaticFileOpen, StaticFileGetContent, StaticRawMemoryCopyEx64, StaticFileClose
. EngineCreateUnpackerWindow, EngineAddUnpackerWindowLogMessage
. Samples
o Tool samples
. LameCrypt, PEValidate
o Unpacker samples
. C
. tELock, AHPack, AlexProtector, UPX (simplified) and FSG (simplified), DEB
. Python
. FSG, UPX, LameCrypt
. LUA
. UPX
C:\masm32\UnpackEngine\bit9\ENGINE-Cpp\UE 1.5\SDK\Manual\lgpl.gif
License
GNU LESSER GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
This version of the GNU Lesser General Public License incorporates
the terms and conditions of version 3 of the GNU General Public
License, supplemented by the additional permissions listed below.
0. Additional Definitions.
As used herein, "this License" refers to version 3 of the GNU Lesser
General Public License, and the "GNU GPL" refers to version 3 of the GNU
General Public License.
"The Library" refers to a covered work governed by this License,
other than an Application or a Combined Work as defined below.
An "Application" is any work that makes use of an interface provided
by the Library, but which is not otherwise based on the Library.
Defining a subclass of a class defined by the Library is deemed a mode
of using an interface provided by the Library.
A "Combined Work" is a work produced by combining or linking an
Application with the Library. The particular version of the Library
with which the Combined Work was made is also called the "Linked
Version".
The "Minimal Corresponding Source" for a Combined Work means the
Corresponding Source for the Combined Work, excluding any source code
for portions of the Combined Work that, considered in isolation, are
based on the Application, and not on the Linked Version.
The "Corresponding Application Code" for a Combined Work means the
object code and/or source code for the Application, including any data
and utility programs needed for reproducing the Combined Work from the
Application, but excluding the System Libraries of the Combined Work.
1. Exception to Section 3 of the GNU GPL.
You may convey a covered work under sections 3 and 4 of this License
without being bound by section 3 of the GNU GPL.
2. Conveying Modified Versions.
If you modify a copy of the Library, and, in your modifications, a
facility refers to a function or data to be supplied by an Application
that uses the facility (other than as an argument passed when the
facility is invoked), then you may convey a copy of the modified
version:
a) under this License, provided that you make a good faith effort to
ensure that, in the event an Application does not supply the
function or data, the facility still operates, and performs
whatever part of its purpose remains meaningful, or
b) under the GNU GPL, with none of the additional permissions of
this License applicable to that copy.
3. Object Code Incorporating Material from Library Header Files.
The object code form of an Application may incorporate material from
a header file that is part of the Library. You may convey such object
code under terms of your choice, provided that, if the incorporated
material is not limited to numerical parameters, data structure
layouts and accessors, or small macros, inline functions and templates
(ten or fewer lines in length), you do both of the following:
a) Give prominent notice with each copy of the object code that the
Library is used in it and that the Library and its use are
covered by this License.
b) Accompany the object code with a copy of the GNU GPL and this license
document.
4. Combined Works.
You may convey a Combined Work under terms of your choice that,
taken together, effectively do not restrict modification of the
portions of the Library contained in the Combined Work and reverse
engineering for debugging such modifications, if you also do each of
the following:
a) Give prominent notice with each copy of the Combined Work that
the Library is used in it and that the Library and its use are
covered by this License.
b) Accompany the Combined Work with a copy of the GNU GPL and this license
document.
c) For a Combined Work that displays copyright notices during
execution, include the copyright notice for the Library among
these notices, as well as a reference directing the user to the
copies of the GNU GPL and this license document.
d) Do one of the following:
0) Convey the Minimal Corresponding Source under the terms of this
License, and the Corresponding Application Code in a form
suitable for, and under terms that permit, the user to
recombine or relink the Application with a modified version of
the Linked Version to produce a modified Combined Work, in the
manner specified by section 6 of the GNU GPL for conveying
Corresponding Source.
1) Use a suitable shared library mechanism for linking with the
Library. A suitable mechanism is one that (a) uses at run time
a copy of the Library already present on the user's computer
system, and (b) will operate properly with a modified version
of the Library that is interface-compatible with the Linked
Version.
e) Provide Installation Information, but only if you would otherwise
be required to provide such information under section 6 of the
GNU GPL, and only to the extent that such information is
necessary to install and execute a modified version of the
Combined Work produced by recombining or relinking the
Application with a modified version of the Linked Version. (If
you use option 4d0, the Installation Information must accompany
the Minimal Corresponding Source and Corresponding Application
Code. If you use option 4d1, you must provide the Installation
Information in the manner specified by section 6 of the GNU GPL
for conveying Corresponding Source.)
5. Combined Libraries.
You may place library facilities that are a work based on the
Library side by side in a single library together with other library
facilities that are not Applications and are not covered by this
License, and convey such a combined library under terms of your
choice, if you do both of the following:
a) Accompany the combined library with a copy of the same work based
on the Library, uncombined with any other library facilities,
conveyed under the terms of this License.
b) Give prominent notice with the combined library that part of it
is a work based on the Library, and explaining where to find the
accompanying uncombined form of the same work.
6. Revised Versions of the GNU Lesser General Public License.
The Free Software Foundation may publish revised and/or new versions
of the GNU Lesser General Public License from time to time. Such new
versions will be similar in spirit to the present version, but may
differ in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the
Library as you received it specifies that a certain numbered version
of the GNU Lesser General Public License "or any later version"
applies to it, you have the option of following the terms and
conditions either of that published version or of any later version
published by the Free Software Foundation. If the Library as you
received it does not specify a version number of the GNU Lesser
General Public License, you may choose any version of the GNU Lesser
General Public License ever published by the Free Software Foundation.
If the Library as you received it specifies that a proxy can decide
whether future versions of the GNU Lesser General Public License shall
apply, that proxy's public statement of acceptance of any version is
permanent authorization for you to choose that version for the
Library. |
C++ | x64dbg-development/src/dbg/WinInet-Downloader/downslib.cpp | /* Created by John Ã…kerblom 10/26/2014 */
#include "downslib.h"
#include <windows.h>
#include <stdio.h>
#include <Wininet.h>
#include <functional>
#pragma comment(lib, "Wininet.lib")
class Cleanup
{
std::function<void()> fn;
public:
explicit Cleanup(std::function<void()> fn) : fn(std::move(fn)) { }
~Cleanup() { fn(); }
};
downslib_error downslib_download(const char* url,
const wchar_t* filename,
const char* useragent,
unsigned int timeout,
downslib_cb cb,
void* userdata)
{
HINTERNET hInternet = nullptr;
HINTERNET hUrl = nullptr;
HANDLE hFile = nullptr;
DWORD dwBufferSize = 0;
const char* headers = nullptr;
DWORD dwHeaderslen = 0;
const DWORD chunk_size = 8192;
Cleanup cleanup([&]()
{
DWORD dwLastError = GetLastError();
if(hFile != INVALID_HANDLE_VALUE)
{
bool doDelete = false;
LARGE_INTEGER fileSize;
if(dwLastError != ERROR_SUCCESS || (GetFileSizeEx(hFile, &fileSize) && fileSize.QuadPart == 0))
{
// an error occurred and now there is an empty or incomplete file that didn't exist before we came in
doDelete = true;
}
CloseHandle(hFile);
if(doDelete)
DeleteFileW(filename);
}
if(hUrl != NULL)
InternetCloseHandle(hUrl);
if(hInternet != NULL)
InternetCloseHandle(hInternet);
SetLastError(dwLastError);
});
// Create the PDB file that will be written to
hFile = CreateFileW(filename, GENERIC_WRITE | FILE_READ_ATTRIBUTES, 0, NULL, CREATE_ALWAYS, 0, NULL);
if(hFile == INVALID_HANDLE_VALUE)
return downslib_error::createfile;
hInternet = InternetOpenA(useragent,
INTERNET_OPEN_TYPE_PRECONFIG,
NULL,
NULL,
0);
if(!hInternet)
return downslib_error::inetopen;
// Set a time-out value in milliseconds
InternetSetOptionA(hInternet,
INTERNET_OPTION_RECEIVE_TIMEOUT,
&timeout,
sizeof(timeout));
// Attempt to enable content decoding if the option is supported
DWORD gzipDecoding = true;
if(InternetSetOptionA(hInternet,
INTERNET_OPTION_HTTP_DECODING,
&gzipDecoding,
sizeof(gzipDecoding)))
{
// Add the required request headers
headers = "Accept-Encoding: gzip\r\n";
dwHeaderslen = static_cast<DWORD>(strlen(headers));
}
DWORD dwFlags = INTERNET_FLAG_RELOAD;
if(strncmp(url, "https://", 8) == 0)
dwFlags |= INTERNET_FLAG_SECURE;
// Make the HTTP request
hUrl = InternetOpenUrlA(hInternet, url, headers, dwHeaderslen, dwFlags, 0);
if(!hUrl)
return downslib_error::openurl;
// Get HTTP status code
DWORD dwStatusCode;
dwBufferSize = sizeof(dwStatusCode);
if(HttpQueryInfoA(hUrl, HTTP_QUERY_STATUS_CODE | HTTP_QUERY_FLAG_NUMBER, &dwStatusCode, &dwBufferSize, 0))
{
if(dwStatusCode != 200)
{
SetLastError(dwStatusCode);
return downslib_error::statuscode;
}
}
// Get HTTP content length
unsigned long long contentLength = 0;
dwBufferSize = sizeof(contentLength);
HttpQueryInfoA(hUrl, HTTP_QUERY_CONTENT_LENGTH | HTTP_QUERY_FLAG_NUMBER, &contentLength, &dwBufferSize, 0);
// Receive the data from the HINTERNET handle
char buffer[chunk_size];
DWORD dwRead = 0;
DWORD dwWritten = 0;
unsigned long long readBytes = 0;
unsigned long long totalBytes = contentLength;
while(InternetReadFile(hUrl, buffer, sizeof(buffer), &dwRead))
{
readBytes += dwRead;
// We are done if nothing more to read, so now we can report total size in our final cb call
if(dwRead == 0)
totalBytes = readBytes;
// Call the callback to report progress and cancellation
if(cb && !cb(userdata, readBytes, totalBytes))
{
SetLastError(ERROR_OPERATION_ABORTED);
return downslib_error::cancel;
}
// Exit if nothing more to read
if(dwRead == 0)
break;
// Write buffer to PDB file
WriteFile(hFile, buffer, dwRead, &dwWritten, nullptr);
// Check WriteFile successfully wrote the entire buffer
if(dwWritten != dwRead)
{
SetLastError(ERROR_IO_INCOMPLETE);
return downslib_error::incomplete;
}
}
if(totalBytes > 0 && readBytes != totalBytes)
{
SetLastError(ERROR_IO_INCOMPLETE);
return downslib_error::incomplete;
}
SetLastError(ERROR_SUCCESS);
return downslib_error::ok;
} |
C/C++ | x64dbg-development/src/dbg/WinInet-Downloader/downslib.h | /* Created by John Ã…kerblom 10/26/2014 */
#pragma once
#include <wchar.h>
#include <stdbool.h>
enum class downslib_error
{
ok,
createfile,
inetopen,
openurl,
statuscode,
cancel,
incomplete
};
typedef bool (*downslib_cb)(void* userdata, unsigned long long read_bytes, unsigned long long total_bytes);
downslib_error downslib_download(const char* url,
const wchar_t* filename,
const char* useragent = "downslib",
unsigned int timeout = 3000,
downslib_cb cb = nullptr,
void* userdata = nullptr); |
C/C++ | x64dbg-development/src/dbg/XEDParse/XEDParse.h | #ifndef _XEDPARSE_H
#define _XEDPARSE_H
#include <windows.h>
//XEDParse defines
#ifdef XEDPARSE_BUILD
#define XEDPARSE_EXPORT __declspec(dllexport)
#else
#define XEDPARSE_EXPORT __declspec(dllimport)
#endif //XEDPARSE_BUILD
#define XEDPARSE_CALL //calling convention
#define XEDPARSE_MAXBUFSIZE 256
#define XEDPARSE_MAXASMSIZE 16
//typedefs
typedef bool (XEDPARSE_CALL* CBXEDPARSE_UNKNOWN)(const char* text, ULONGLONG* value);
//XEDParse enums
enum XEDPARSE_STATUS
{
XEDPARSE_ERROR = 0,
XEDPARSE_OK = 1
};
//XEDParse structs
#pragma pack(push,8)
struct XEDPARSE
{
bool x64; // use 64-bit instructions
ULONGLONG cip; //instruction pointer (for relative addressing)
unsigned int dest_size; //destination size (returned by XEDParse)
CBXEDPARSE_UNKNOWN cbUnknown; //unknown operand callback
unsigned char dest[XEDPARSE_MAXASMSIZE]; //destination buffer
char instr[XEDPARSE_MAXBUFSIZE]; //instruction text
char error[XEDPARSE_MAXBUFSIZE]; //error text (in case of an error)
};
#pragma pack(pop)
#ifdef __cplusplus
extern "C"
{
#endif
XEDPARSE_EXPORT XEDPARSE_STATUS XEDPARSE_CALL XEDParseAssemble(XEDPARSE* XEDParse);
#ifdef __cplusplus
}
#endif
#endif // _XEDPARSE_H |
C++ | x64dbg-development/src/exe/crashdump.cpp | #include <windows.h>
#pragma warning(push)
#pragma warning(disable:4091)
#include <dbghelp.h>
#pragma warning(pop)
#include <stdio.h>
#include <exception>
#include <signal.h>
#include "crashdump.h"
#include "signaturecheck.h"
#define PROCESS_CALLBACK_FILTER_ENABLED 0x1
BOOL
(WINAPI*
MiniDumpWriteDumpPtr)(
_In_ HANDLE hProcess,
_In_ DWORD ProcessId,
_In_ HANDLE hFile,
_In_ MINIDUMP_TYPE DumpType,
_In_opt_ PMINIDUMP_EXCEPTION_INFORMATION ExceptionParam,
_In_opt_ PMINIDUMP_USER_STREAM_INFORMATION UserStreamParam,
_In_opt_ PMINIDUMP_CALLBACK_INFORMATION CallbackParam
);
BOOL
(WINAPI*
SetProcessUserModeExceptionPolicyPtr)(
_In_ DWORD PolicyFlags
);
BOOL
(WINAPI*
GetProcessUserModeExceptionPolicyPtr)(
_Out_ LPDWORD PolicyFlags
);
void CrashDumpInitialize()
{
// Get handles to kernel32 and dbghelp
HMODULE hDbghelp = LoadLibraryCheckedW(L"dbghelp.dll", false);
if(hDbghelp)
*(FARPROC*)&MiniDumpWriteDumpPtr = GetProcAddress(hDbghelp, "MiniDumpWriteDump");
HMODULE hKernel32 = GetModuleHandleA("kernel32.dll");
*(FARPROC*)&SetProcessUserModeExceptionPolicyPtr = GetProcAddress(hKernel32, "SetProcessUserModeExceptionPolicy");
*(FARPROC*)&GetProcessUserModeExceptionPolicyPtr = GetProcAddress(hKernel32, "GetProcessUserModeExceptionPolicy");
if(MiniDumpWriteDumpPtr)
SetUnhandledExceptionFilter(CrashDumpExceptionHandler);
// Ensure that exceptions are not swallowed when dispatching certain Windows
// messages.
//
// http://blog.paulbetts.org/index.php/2010/07/20/the-case-of-the-disappearing-onload-exception-user-mode-callback-exceptions-in-x64/
// https://support.microsoft.com/en-gb/kb/976038
if(SetProcessUserModeExceptionPolicyPtr && GetProcessUserModeExceptionPolicyPtr)
{
DWORD flags = 0;
if(GetProcessUserModeExceptionPolicyPtr(&flags))
SetProcessUserModeExceptionPolicyPtr(flags & ~PROCESS_CALLBACK_FILTER_ENABLED);
}
// If not running under a debugger, redirect purecall, terminate, abort, and
// invalid parameter callbacks to force generate a dump.
if(!IsDebuggerPresent())
{
_set_purecall_handler(TerminateHandler); // https://msdn.microsoft.com/en-us/library/t296ys27.aspx
_set_invalid_parameter_handler(InvalidParameterHandler);// https://msdn.microsoft.com/en-us/library/a9yf33zb.aspx
set_terminate(TerminateHandler); // http://en.cppreference.com/w/cpp/error/set_terminate
signal(SIGABRT, AbortHandler); // https://msdn.microsoft.com/en-us/library/xdkz3x12.aspx
}
}
void CrashDumpFatal(const char* Format, ...)
{
char buffer[1024];
va_list va;
va_start(va, Format);
vsnprintf_s(buffer, _TRUNCATE, Format, va);
va_end(va);
MessageBoxA(nullptr, buffer, "Error", MB_ICONERROR);
}
void CrashDumpCreate(EXCEPTION_POINTERS* ExceptionPointers)
{
// Generate a crash dump file in the minidump directory
wchar_t dumpFile[MAX_PATH];
wchar_t dumpDir[MAX_PATH];
if(!GetCurrentDirectoryW(ARRAYSIZE(dumpDir), dumpDir))
{
CrashDumpFatal("Unable to obtain current directory during crash dump");
return;
}
wcscat_s(dumpDir, L"\\minidump");
CreateDirectoryW(dumpDir, nullptr);
// Append the name with generated timestamp
SYSTEMTIME st;
GetLocalTime(&st);
swprintf_s(dumpFile, L"%ws\\dump-%02d%02d%04d_%02d%02d%02d%04d.dmp", dumpDir,
st.wDay,
st.wMonth,
st.wYear,
st.wHour,
st.wMinute,
st.wSecond,
st.wMilliseconds);
// Open the file
HANDLE fileHandle = CreateFileW(dumpFile, GENERIC_READ | GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr);
if(fileHandle == INVALID_HANDLE_VALUE)
{
CrashDumpFatal("Failed to open file path '%ws' while generating crash dump", dumpFile);
return;
}
// Create the minidump with DbgHelp
MINIDUMP_EXCEPTION_INFORMATION info;
memset(&info, 0, sizeof(MINIDUMP_EXCEPTION_INFORMATION));
info.ThreadId = GetCurrentThreadId();
info.ExceptionPointers = ExceptionPointers;
info.ClientPointers = TRUE;
if(!MiniDumpWriteDumpPtr(GetCurrentProcess(), GetCurrentProcessId(), fileHandle, MiniDumpNormal, &info, nullptr, nullptr))
CrashDumpFatal("MiniDumpWriteDump failed. Error: %u", GetLastError());
// Close the file & done
CloseHandle(fileHandle);
}
LONG CALLBACK CrashDumpExceptionHandler(EXCEPTION_POINTERS* ExceptionInfo)
{
// Any "exception" under 0x1000 is usually a failed remote procedure call (RPC)
if(ExceptionInfo && ExceptionInfo->ExceptionRecord->ExceptionCode > 0x1000)
{
switch(ExceptionInfo->ExceptionRecord->ExceptionCode)
{
case DBG_PRINTEXCEPTION_C: // OutputDebugStringA
case 0x4001000A: // OutputDebugStringW
case STATUS_INVALID_HANDLE: // Invalid TitanEngine handle
case 0x406D1388: // SetThreadName
return EXCEPTION_CONTINUE_SEARCH;
}
CrashDumpCreate(ExceptionInfo);
}
return EXCEPTION_CONTINUE_SEARCH;
}
void InvalidParameterHandler(const wchar_t* Expression, const wchar_t* Function, const wchar_t* File, unsigned int Line, uintptr_t Reserved)
{
CrashDumpFatal("Invalid parameter passed to CRT function! Program will now generate an exception.\n\nFile: %ws\nFunction: %ws\nExpression: %ws",
Function ? Function : L"???",
File ? File : L"???",
Expression ? Expression : L"???");
// RaiseException: avoid the use of throw/C++ exceptions and possible __fastfail calls
RaiseException(0x78646267, EXCEPTION_NONCONTINUABLE, 0, nullptr);
}
void TerminateHandler()
{
CrashDumpFatal("Process termination was requested in an unusual way. Program will now generate an exception.");
// See InvalidParameterHandler()
RaiseException(0x78646267, EXCEPTION_NONCONTINUABLE, 0, nullptr);
}
void AbortHandler(int Signal)
{
TerminateHandler();
} |
C/C++ | x64dbg-development/src/exe/crashdump.h | #pragma once
void CrashDumpInitialize();
LONG CALLBACK CrashDumpExceptionHandler(EXCEPTION_POINTERS* ExceptionInfo);
void InvalidParameterHandler(const wchar_t* Expression, const wchar_t* Function, const wchar_t* File, unsigned int Line, uintptr_t Reserved);
void TerminateHandler();
void AbortHandler(int Signal); |
C/C++ | x64dbg-development/src/exe/icon.h | //{{NO_DEPENDENCIES}}
// Microsoft Visual C++ generated include file.
// Used by icon64.rc
//
#define IDI_ICON1 100
// Next default values for new objects
//
#ifdef APSTUDIO_INVOKED
#ifndef APSTUDIO_READONLY_SYMBOLS
#define _APS_NO_MFC 1
#define _APS_NEXT_RESOURCE_VALUE 102
#define _APS_NEXT_COMMAND_VALUE 40001
#define _APS_NEXT_CONTROL_VALUE 1001
#define _APS_NEXT_SYMED_VALUE 101
#endif
#endif |
x64dbg-development/src/exe/icon.rc | // Microsoft Visual C++ generated resource script.
//
#include "icon.h"
#define APSTUDIO_READONLY_SYMBOLS
/////////////////////////////////////////////////////////////////////////////
//
// Generated from the TEXTINCLUDE 2 resource.
//
#include "winres.h"
/////////////////////////////////////////////////////////////////////////////
#undef APSTUDIO_READONLY_SYMBOLS
/////////////////////////////////////////////////////////////////////////////
// English (United States) resources
#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU)
LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US
/////////////////////////////////////////////////////////////////////////////
//
// Icon
//
// Icon with lowest ID value placed first to ensure application icon
// remains consistent on all systems.
IDI_ICON1 ICON "..\\bug.ico"
#endif // English (United States) resources
/////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////
// English (United States) resources
#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_NLD)
LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US
#ifdef APSTUDIO_INVOKED
/////////////////////////////////////////////////////////////////////////////
//
// TEXTINCLUDE
//
1 TEXTINCLUDE
BEGIN
"icon.h\0"
END
2 TEXTINCLUDE
BEGIN
"#include ""winres.h""\r\n"
"\0"
END
3 TEXTINCLUDE
BEGIN
"\r\n"
"\0"
END
#endif // APSTUDIO_INVOKED
#endif // English (United States) resources
/////////////////////////////////////////////////////////////////////////////
#ifndef APSTUDIO_INVOKED
/////////////////////////////////////////////////////////////////////////////
//
// Generated from the TEXTINCLUDE 3 resource.
//
/////////////////////////////////////////////////////////////////////////////
#endif // not APSTUDIO_INVOKED |
|
x64dbg-development/src/exe/icon32.rc | // Microsoft Visual C++ generated resource script.
//
#include "icon.h"
#define APSTUDIO_READONLY_SYMBOLS
/////////////////////////////////////////////////////////////////////////////
//
// Generated from the TEXTINCLUDE 2 resource.
//
#include "winres.h"
/////////////////////////////////////////////////////////////////////////////
#undef APSTUDIO_READONLY_SYMBOLS
/////////////////////////////////////////////////////////////////////////////
// English (United States) resources
#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU)
LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US
/////////////////////////////////////////////////////////////////////////////
//
// Icon
//
// Icon with lowest ID value placed first to ensure application icon
// remains consistent on all systems.
IDI_ICON1 ICON "..\\bug32.ico"
#endif // English (United States) resources
/////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////
// English (United States) resources
#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_NLD)
LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US
#ifdef APSTUDIO_INVOKED
/////////////////////////////////////////////////////////////////////////////
//
// TEXTINCLUDE
//
1 TEXTINCLUDE
BEGIN
"icon.h\0"
END
2 TEXTINCLUDE
BEGIN
"#include ""winres.h""\r\n"
"\0"
END
3 TEXTINCLUDE
BEGIN
"\r\n"
"\0"
END
#endif // APSTUDIO_INVOKED
#endif // English (United States) resources
/////////////////////////////////////////////////////////////////////////////
#ifndef APSTUDIO_INVOKED
/////////////////////////////////////////////////////////////////////////////
//
// Generated from the TEXTINCLUDE 3 resource.
//
/////////////////////////////////////////////////////////////////////////////
#endif // not APSTUDIO_INVOKED |
|
x64dbg-development/src/exe/icon64.rc | // Microsoft Visual C++ generated resource script.
//
#include "icon.h"
#define APSTUDIO_READONLY_SYMBOLS
/////////////////////////////////////////////////////////////////////////////
//
// Generated from the TEXTINCLUDE 2 resource.
//
#include "winres.h"
/////////////////////////////////////////////////////////////////////////////
#undef APSTUDIO_READONLY_SYMBOLS
/////////////////////////////////////////////////////////////////////////////
// English (United States) resources
#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU)
LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US
/////////////////////////////////////////////////////////////////////////////
//
// Icon
//
// Icon with lowest ID value placed first to ensure application icon
// remains consistent on all systems.
IDI_ICON1 ICON "..\\bug64.ico"
#endif // English (United States) resources
/////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////
// English (United States) resources
#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_NLD)
LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US
#ifdef APSTUDIO_INVOKED
/////////////////////////////////////////////////////////////////////////////
//
// TEXTINCLUDE
//
1 TEXTINCLUDE
BEGIN
"icon.h\0"
END
2 TEXTINCLUDE
BEGIN
"#include ""winres.h""\r\n"
"\0"
END
3 TEXTINCLUDE
BEGIN
"\r\n"
"\0"
END
#endif // APSTUDIO_INVOKED
#endif // English (United States) resources
/////////////////////////////////////////////////////////////////////////////
#ifndef APSTUDIO_INVOKED
/////////////////////////////////////////////////////////////////////////////
//
// Generated from the TEXTINCLUDE 3 resource.
//
/////////////////////////////////////////////////////////////////////////////
#endif // not APSTUDIO_INVOKED |
|
C/C++ | x64dbg-development/src/exe/LoadResourceString.h | #include <string>
#include "strings.h" // String resources
inline std::wstring _LoadResString(UINT uID)
{
wchar_t* p = nullptr;
int len = ::LoadStringW(NULL, uID, reinterpret_cast<LPWSTR>(&p), 0);
if(len > 0)
{
return std::wstring(p, len);
}
else
{
return std::wstring();
}
}
#define LoadResString(uID) _LoadResString(uID).c_str() |
C/C++ | x64dbg-development/src/exe/resource.h | //{{NO_DEPENDENCIES}}
// Microsoft Visual C++ generated include file.
// Used by resource.rc
//
#define IDD_DIALOGLAUNCHER 105
#define IDC_BUTTON32 1001
#define IDC_BUTTON64 1002
#define IDC_BUTTON3 1003
#define IDC_BUTTONINSTALL 1003
// Next default values for new objects
//
#ifdef APSTUDIO_INVOKED
#ifndef APSTUDIO_READONLY_SYMBOLS
#define _APS_NEXT_RESOURCE_VALUE 107
#define _APS_NEXT_COMMAND_VALUE 40001
#define _APS_NEXT_CONTROL_VALUE 1002
#define _APS_NEXT_SYMED_VALUE 101
#endif
#endif |
x64dbg-development/src/exe/resource.rc | // Microsoft Visual C++ generated resource script.
//
#pragma code_page(65001)
#include "resource.h"
#define APSTUDIO_READONLY_SYMBOLS
/////////////////////////////////////////////////////////////////////////////
//
// Generated from the TEXTINCLUDE 2 resource.
//
#include "winres.h"
/////////////////////////////////////////////////////////////////////////////
#undef APSTUDIO_READONLY_SYMBOLS
/////////////////////////////////////////////////////////////////////////////
// Neutral resources
#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_NEU)
LANGUAGE LANG_NEUTRAL, SUBLANG_NEUTRAL
#ifdef APSTUDIO_INVOKED
/////////////////////////////////////////////////////////////////////////////
//
// TEXTINCLUDE
//
1 TEXTINCLUDE
BEGIN
"resource.h\0"
END
2 TEXTINCLUDE
BEGIN
"#include ""winres.h""\r\n"
"\0"
END
3 TEXTINCLUDE
BEGIN
"\r\n"
"\0"
END
#endif // APSTUDIO_INVOKED
/////////////////////////////////////////////////////////////////////////////
//
// RT_MANIFEST
//
1 RT_MANIFEST ".\\manifest.xml"
/////////////////////////////////////////////////////////////////////////////
//
// Version
//
VS_VERSION_INFO VERSIONINFO
FILEVERSION 0,0,2,5
PRODUCTVERSION 0,0,2,5
FILEFLAGSMASK 0x3fL
#ifdef _DEBUG
FILEFLAGS 0x1L
#else
FILEFLAGS 0x0L
#endif
FILEOS 0x40004L
FILETYPE 0x0L
FILESUBTYPE 0x0L
BEGIN
BLOCK "StringFileInfo"
BEGIN
BLOCK "040904b0"
BEGIN
VALUE "FileDescription", "x64dbg"
VALUE "FileVersion", "0.0.2.5"
VALUE "LegalCopyright", "x64dbg.com"
VALUE "ProductName", "x64dbg"
VALUE "ProductVersion", "0.0.2.5"
END
END
BLOCK "VarFileInfo"
BEGIN
VALUE "Translation", 0x409, 1200
END
END
/////////////////////////////////////////////////////////////////////////////
//
// Dialog
//
IDD_DIALOGLAUNCHER DIALOGEX 0, 0, 177, 28
STYLE DS_SETFONT | DS_FIXEDSYS | DS_CENTER | WS_POPUP | WS_CAPTION | WS_SYSMENU
CAPTION "Launcher"
FONT 8, "MS Shell Dlg", 400, 0, 0x1
BEGIN
PUSHBUTTON "x32dbg",IDC_BUTTON32,7,7,50,14
PUSHBUTTON "x64dbg",IDC_BUTTON64,63,7,50,14
PUSHBUTTON "Setup",IDC_BUTTONINSTALL,120,7,50,14
END
/////////////////////////////////////////////////////////////////////////////
//
// DESIGNINFO
//
#ifdef APSTUDIO_INVOKED
GUIDELINES DESIGNINFO
BEGIN
IDD_DIALOGLAUNCHER, DIALOG
BEGIN
LEFTMARGIN, 7
RIGHTMARGIN, 170
TOPMARGIN, 7
BOTTOMMARGIN, 21
END
END
#endif // APSTUDIO_INVOKED
/////////////////////////////////////////////////////////////////////////////
//
// AFX_DIALOG_LAYOUT
//
IDD_DIALOGLAUNCHER AFX_DIALOG_LAYOUT
BEGIN
0
END
#endif // Neutral resources
/////////////////////////////////////////////////////////////////////////////
#ifndef APSTUDIO_INVOKED
/////////////////////////////////////////////////////////////////////////////
//
// Generated from the TEXTINCLUDE 3 resource.
//
/////////////////////////////////////////////////////////////////////////////
#endif // not APSTUDIO_INVOKED |
|
C++ | x64dbg-development/src/exe/signaturecheck.cpp | #include "signaturecheck.h"
#include <delayimp.h>
#include <Softpub.h>
#include <wincrypt.h>
#include <wintrust.h>
#include <string>
#include <vector>
static wchar_t szApplicationDir[MAX_PATH];
static bool bPerformSignatureChecks = false;
//#define DEBUG_SIGNATURE_CHECKS
#ifdef DEBUG_SIGNATURE_CHECKS
static const wchar_t* gCheckedList[4096];
static size_t gCheckedListSize = 0;
static void debugMessage(const wchar_t* szMessage)
{
wchar_t finalMessage[512] = L"[signaturecheck] ";
wcsncat_s(finalMessage, szMessage, _TRUNCATE);
OutputDebugStringW(finalMessage);
}
#endif // DEBUG_SIGNATURE_CHECKS
#pragma comment(lib, "wintrust")
// Source: https://learn.microsoft.com/en-us/windows/win32/seccrypto/example-c-program--verifying-the-signature-of-a-pe-file
static bool VerifyEmbeddedSignature(LPCWSTR pwszSourceFile, bool checkRevocation)
{
// Initialize the WINTRUST_FILE_INFO structure.
WINTRUST_FILE_INFO FileData;
memset(&FileData, 0, sizeof(FileData));
FileData.cbStruct = sizeof(WINTRUST_FILE_INFO);
FileData.pcwszFilePath = pwszSourceFile;
FileData.hFile = NULL;
FileData.pgKnownSubject = NULL;
/*
WVTPolicyGUID specifies the policy to apply on the file
WINTRUST_ACTION_GENERIC_VERIFY_V2 policy checks:
1) The certificate used to sign the file chains up to a root
certificate located in the trusted root certificate store. This
implies that the identity of the publisher has been verified by
a certification authority.
2) In cases where user interface is displayed (which this example
does not do), WinVerifyTrust will check for whether the
end entity certificate is stored in the trusted publisher store,
implying that the user trusts content from this publisher.
3) The end entity certificate has sufficient permission to sign
code, as indicated by the presence of a code signing EKU or no
EKU.
*/
GUID WVTPolicyGUID = WINTRUST_ACTION_GENERIC_VERIFY_V2;
WINTRUST_DATA WinTrustData;
// Initialize the WinVerifyTrust input data structure.
// Default all fields to 0.
memset(&WinTrustData, 0, sizeof(WinTrustData));
WinTrustData.cbStruct = sizeof(WinTrustData);
// Use default code signing EKU.
WinTrustData.pPolicyCallbackData = NULL;
// No data to pass to SIP.
WinTrustData.pSIPClientData = NULL;
// Disable WVT UI.
WinTrustData.dwUIChoice = WTD_UI_NONE;
// Check certificate revocations
WinTrustData.fdwRevocationChecks = checkRevocation ? WTD_REVOKE_WHOLECHAIN : WTD_REVOKE_NONE;
// Verify an embedded signature on a file.
WinTrustData.dwUnionChoice = WTD_CHOICE_FILE;
// Verify action.
WinTrustData.dwStateAction = WTD_STATEACTION_VERIFY;
// Verification sets this value.
WinTrustData.hWVTStateData = NULL;
// Not used.
WinTrustData.pwszURLReference = NULL;
// This is not applicable if there is no UI because it changes
// the UI to accommodate running applications instead of
// installing applications.
WinTrustData.dwUIContext = 0;
// Set pFile.
WinTrustData.pFile = &FileData;
// WinVerifyTrust verifies signatures as specified by the GUID
// and Wintrust_Data.
auto lStatus = WinVerifyTrust(
NULL,
&WVTPolicyGUID,
&WinTrustData);
bool validSignature = lStatus == ERROR_SUCCESS;
// Any hWVTStateData must be released by a call with close.
WinTrustData.dwStateAction = WTD_STATEACTION_CLOSE;
auto lStatusClean = WinVerifyTrust(
NULL,
&WVTPolicyGUID,
&WinTrustData);
SetLastError(lStatus);
return validSignature;
}
static std::wstring Utf8ToUtf16(const char* str)
{
std::wstring convertedString;
if(!str || !*str)
return convertedString;
int requiredSize = MultiByteToWideChar(CP_UTF8, 0, str, -1, nullptr, 0);
if(requiredSize > 0)
{
convertedString.resize(requiredSize - 1);
if(!MultiByteToWideChar(CP_UTF8, 0, str, -1, (wchar_t*)convertedString.c_str(), requiredSize))
convertedString.clear();
}
return convertedString;
}
static bool FileExists(const wchar_t* szFullPath)
{
DWORD attrib = GetFileAttributesW(szFullPath);
return (attrib != INVALID_FILE_ATTRIBUTES && !(attrib & FILE_ATTRIBUTE_DIRECTORY));
}
HMODULE WINAPI LoadLibraryCheckedW(const wchar_t* szDll, bool allowFailure)
{
std::wstring fullDllPath = szApplicationDir;
fullDllPath += szDll;
#ifdef DEBUG_SIGNATURE_CHECKS
debugMessage(L"LoadLibraryCheckedW");
debugMessage(fullDllPath.c_str());
auto checkedPath = (wchar_t*)malloc(sizeof(wchar_t) * (fullDllPath.size() + 1));
wcscpy_s(checkedPath, fullDllPath.size() + 1, fullDllPath.c_str());
gCheckedList[gCheckedListSize++] = checkedPath;
#endif // DEBUG_SIGNATURE_CHECKS
if(allowFailure && !FileExists(fullDllPath.c_str()))
{
#ifdef DEBUG_SIGNATURE_CHECKS
debugMessage(L"^^^ DLL NOT FOUND ^^^");
#endif // DEBUG_SIGNATURE_CHECKS
SetLastError(ERROR_MOD_NOT_FOUND);
return 0;
}
if(bPerformSignatureChecks)
{
auto validSignature = VerifyEmbeddedSignature(fullDllPath.c_str(), false);
if(!validSignature)
{
#ifdef DEBUG_SIGNATURE_CHECKS
wchar_t msg[128] = L"";
wsprintfW(msg, L"^^^ INVALID SIGNATURE ^^^ -> %08X", GetLastError());
debugMessage(msg);
#else
MessageBoxW(nullptr, fullDllPath.c_str(), L"DLL does not have a valid signature", MB_ICONERROR | MB_SYSTEMMODAL);
ExitProcess(TRUST_E_NOSIGNATURE);
#endif // DEBUG_SIGNATURE_CHECKS
}
}
auto hModule = LoadLibraryW(fullDllPath.c_str());
auto lastError = GetLastError();
if(!allowFailure && !hModule)
{
MessageBoxW(nullptr, fullDllPath.c_str(), L"DLL not found!", MB_ICONERROR | MB_SYSTEMMODAL);
ExitProcess(lastError);
}
return hModule;
}
HMODULE WINAPI LoadLibraryCheckedA(const char* szDll, bool allowFailure)
{
return LoadLibraryCheckedW(Utf8ToUtf16(szDll).c_str(), allowFailure);
}
// https://devblogs.microsoft.com/oldnewthing/20170126-00/?p=95265
static FARPROC WINAPI delayHook(unsigned dliNotify, PDelayLoadInfo pdli)
{
// TODO: pre-parse the imports required and make sure there isn't a fake signed DLL being loaded
if(dliNotify == dliNotePreLoadLibrary)
{
if(_stricmp(pdli->szDll, "wintrust.dll") == 0 || _stricmp(pdli->szDll, "user32.dll") == 0)
{
return 0;
}
return (FARPROC)LoadLibraryCheckedA(pdli->szDll, false);
}
return 0;
}
// Visual Studio 2015 Update 3 made this const per default
// https://dev.to/yumetodo/list-of-mscver-and-mscfullver-8nd
#if _MSC_FULL_VER >= 190024210
const
#endif // _MSC_FULL_VER
PfnDliHook __pfnDliNotifyHook2 = delayHook;
#ifdef DEBUG_SIGNATURE_CHECKS
typedef struct _UNICODE_STRING
{
USHORT Length;
USHORT MaximumLength;
PWSTR Buffer;
} UNICODE_STRING, * PUNICODE_STRING;
typedef struct _LDR_DLL_UNLOADED_NOTIFICATION_DATA
{
ULONG Flags; //Reserved.
PUNICODE_STRING FullDllName; //The full path name of the DLL module.
PUNICODE_STRING BaseDllName; //The base file name of the DLL module.
PVOID DllBase; //A pointer to the base address for the DLL in memory.
ULONG SizeOfImage; //The size of the DLL image, in bytes.
} LDR_DLL_UNLOADED_NOTIFICATION_DATA, * PLDR_DLL_UNLOADED_NOTIFICATION_DATA;
typedef struct _LDR_DLL_LOADED_NOTIFICATION_DATA
{
ULONG Flags; //Reserved.
PUNICODE_STRING FullDllName; //The full path name of the DLL module.
PUNICODE_STRING BaseDllName; //The base file name of the DLL module.
PVOID DllBase; //A pointer to the base address for the DLL in memory.
ULONG SizeOfImage; //The size of the DLL image, in bytes.
} LDR_DLL_LOADED_NOTIFICATION_DATA, * PLDR_DLL_LOADED_NOTIFICATION_DATA;
typedef union _LDR_DLL_NOTIFICATION_DATA
{
LDR_DLL_LOADED_NOTIFICATION_DATA Loaded;
LDR_DLL_UNLOADED_NOTIFICATION_DATA Unloaded;
} LDR_DLL_NOTIFICATION_DATA, * PLDR_DLL_NOTIFICATION_DATA, * const PCLDR_DLL_NOTIFICATION_DATA;
#define LDR_DLL_NOTIFICATION_REASON_LOADED 1
#define LDR_DLL_NOTIFICATION_REASON_UNLOADED 2
VOID CALLBACK LdrDllNotification(
_In_ ULONG NotificationReason,
_In_ PCLDR_DLL_NOTIFICATION_DATA NotificationData,
_In_opt_ PVOID Context
);
using PLDR_DLL_NOTIFICATION_FUNCTION = decltype(&LdrDllNotification);
NTSTATUS NTAPI LdrRegisterDllNotification(
_In_ ULONG Flags,
_In_ PLDR_DLL_NOTIFICATION_FUNCTION NotificationFunction,
_In_opt_ PVOID Context,
_Out_ PVOID* Cookie
);
using PLDR_REGISTER_DLL_NOTIFICATION_FUNCTION = decltype(&LdrRegisterDllNotification);
PLDR_REGISTER_DLL_NOTIFICATION_FUNCTION pLdrRegisterDllNotification;
static VOID CALLBACK MyLdrDllNotification(
_In_ ULONG NotificationReason,
_In_ PCLDR_DLL_NOTIFICATION_DATA NotificationData,
_In_opt_ PVOID Context
)
{
if(NotificationReason == LDR_DLL_NOTIFICATION_REASON_LOADED)
{
auto buffer = NotificationData->Loaded.FullDllName->Buffer;
auto length = NotificationData->Loaded.FullDllName->Length;
if(memcmp(buffer, szApplicationDir, wcslen(szApplicationDir)) == 0)
{
auto alreadyChecked = false;
for(size_t i = 0; i < gCheckedListSize; i++)
{
auto checkedPath = gCheckedList[i];
auto checkedLen = wcslen(checkedPath);
if(length / 2 == checkedLen && memcmp(checkedPath, buffer, length) == 0)
{
alreadyChecked = true;
break;
}
}
if(alreadyChecked)
{
debugMessage(L"DllLoadNotification (checked)");
}
else
{
if(wcsstr(buffer, L"\\plugins\\"))
debugMessage(L"DllLoadNotification(plugin)");
else
debugMessage(L"=== UNCHECKED === DllLoadNotification");
}
debugMessage(buffer);
}
}
}
#endif // DEBUG_SIGNATURE_CHECKS
#define LOAD_LIBRARY_SEARCH_APPLICATION_DIR 0x00000200
#define LOAD_LIBRARY_SEARCH_USER_DIRS 0x00000400
#define LOAD_LIBRARY_SEARCH_SYSTEM32 0x00000800
#define LOAD_LIBRARY_SEARCH_DEFAULT_DIRS 0x00001000
typedef BOOL(WINAPI* pfnSetDefaultDllDirectories)(DWORD DirectoryFlags);
typedef BOOL(WINAPI* pfnSetDllDirectoryW)(LPCWSTR lpPathName);
typedef BOOL(WINAPI* pfnAddDllDirectory)(LPCWSTR lpPathName);
static pfnSetDefaultDllDirectories pSetDefaultDllDirectories;
static pfnSetDllDirectoryW pSetDllDirectoryW;
static pfnAddDllDirectory pAddDllDirectory;
bool InitializeSignatureCheck()
{
if(!GetModuleFileNameW(GetModuleHandleW(nullptr), szApplicationDir, _countof(szApplicationDir)))
return false;
std::wstring executablePath = szApplicationDir;
auto ptr = wcsrchr(szApplicationDir, L'\\');
if(ptr == nullptr)
return false;
ptr[1] = L'\0';
// Get system directory
wchar_t szSystemDir[MAX_PATH] = L"";
GetSystemDirectoryW(szSystemDir, _countof(szSystemDir));
// This is generically fixing DLL hijacking by using the following search order
// - System directory
// - Application directory
// References:
// - https://learn.microsoft.com/en-us/windows/win32/api/libloaderapi/nf-libloaderapi-setdefaultdlldirectories
// - https://learn.microsoft.com/en-us/windows/win32/api/libloaderapi/nf-libloaderapi-adddlldirectory
// - https://medium.com/@1ndahous3/safe-code-pitfalls-dll-side-loading-winapi-and-c-73baaf48bdf5
// - https://www.bleepingcomputer.com/news/security/microsoft-code-sign-check-bypassed-to-drop-zloader-malware/
// - https://www.trustedsec.com/blog/object-overloading/
HMODULE hKernel32 = GetModuleHandleW(L"kernel32.dll");
pSetDefaultDllDirectories = (pfnSetDefaultDllDirectories)GetProcAddress(hKernel32, "SetDefaultDllDirectories");
pSetDllDirectoryW = (pfnSetDllDirectoryW)GetProcAddress(hKernel32, "SetDllDirectoryW");
pAddDllDirectory = (pfnAddDllDirectory)GetProcAddress(hKernel32, "AddDllDirectory");
if(pSetDefaultDllDirectories && pSetDllDirectoryW && pAddDllDirectory)
{
if(!pSetDllDirectoryW(L""))
return false;
// Thanks to daax for finding this order
// > If more than one directory has been added, the order in which those directories are searched is unspecified.
// Reversing ntdll shows that it is using a singly-linked list, so the order is the opposite in which you add it
// Wine: https://github.com/wine-mirror/wine/blob/e796002ee61bf5dfb2718e8f4fb8fa928ccdc236/dlls/ntdll/loader.c#L4423-L4462
if(!pAddDllDirectory(szApplicationDir))
return false;
if(!pAddDllDirectory(szSystemDir))
return false;
if(!pSetDefaultDllDirectories(LOAD_LIBRARY_SEARCH_SYSTEM32 | LOAD_LIBRARY_SEARCH_USER_DIRS))
return false;
}
else
{
auto loadSystemDll = [&szSystemDir](const wchar_t* szName)
{
std::wstring fullDllPath;
fullDllPath = szSystemDir;
fullDllPath += L'\\';
fullDllPath += szName;
LoadLibraryW(fullDllPath.c_str());
};
// At least prevent DLL hijacking for wintrust.dll on XP/Old 7
loadSystemDll(L"msasn1.dll");
loadSystemDll(L"cryptsp.dll");
loadSystemDll(L"cryptbase.dll");
loadSystemDll(L"wintrust.dll");
loadSystemDll(L"rsaenh.dll");
loadSystemDll(L"psapi.dll");
}
bPerformSignatureChecks = VerifyEmbeddedSignature(executablePath.c_str(), false);
#ifdef DEBUG_SIGNATURE_CHECKS
bPerformSignatureChecks = true;
pLdrRegisterDllNotification = (PLDR_REGISTER_DLL_NOTIFICATION_FUNCTION)GetProcAddress(GetModuleHandleW(L"ntdll.dll"), "LdrRegisterDllNotification");
if(pLdrRegisterDllNotification == nullptr)
return true;
PVOID Cookie;
auto status = pLdrRegisterDllNotification(0, MyLdrDllNotification, nullptr, &Cookie);
if(status != 0)
return false;
#endif // DEBUG_SIGNATURE_CHECKS
if(bPerformSignatureChecks)
{
// Safely load the MSVC runtime DLLs (since they cannot be delay loaded)
auto loadRuntimeDll = [](const wchar_t* szDll)
{
std::wstring fullDllPath = szApplicationDir;
fullDllPath += L'\\';
fullDllPath += szDll;
if(FileExists(fullDllPath.c_str()))
LoadLibraryCheckedW(szDll, true);
else
LoadLibraryW(szDll);
};
loadRuntimeDll(L"msvcr120.dll");
loadRuntimeDll(L"msvcp120.dll");
}
return true;
} |
C/C++ | x64dbg-development/src/exe/signaturecheck.h | #pragma once
#include <Windows.h>
bool InitializeSignatureCheck();
HMODULE WINAPI LoadLibraryCheckedW(const wchar_t* szDll, bool allowFailure);
HMODULE WINAPI LoadLibraryCheckedA(const char* szDll, bool allowFailure); |
C/C++ | x64dbg-development/src/exe/strings.h | //{{NO_DEPENDENCIES}}
// Microsoft Visual C++ generated include file.
// Used by Strings.rc
//
#define IDS_SETUP 101
#define IDS_ERROR 105
#define IDS_ERRORGETTINGMODULEPATH 106
#define IDS_QUESTION 107
#define IDS_ASKSHELLEXT 108
#define IDS_ASKDESKTOPSHORTCUT 109
#define IDS_DONE 110
#define IDS_NEWCFGWRITTEN 111
#define IDS_INVDPATH32 112
#define IDS_INVDPATH64 113
#define IDS_INVDPE 114
#define IDS_FILEERR 115
#define IDS_SHORTCUTDESC 116
#define IDS_ASKADMIN 117
#define IDS_REGCREATEKEYFAIL 118
#define IDS_REGSETVALUEEXFAIL 119
#define IDS_REGOPENKEYFAIL 120
#define IDS_BRIDGEINITERR 121
#define IDS_SHELLEXTDBG 122
#define IDS_ASKICON 123
#define IDS_BRIDGESTARTERR 126
// Next default values for new objects
//
#ifdef APSTUDIO_INVOKED
#ifndef APSTUDIO_READONLY_SYMBOLS
#define _APS_NEXT_RESOURCE_VALUE 102
#define _APS_NEXT_COMMAND_VALUE 40001
#define _APS_NEXT_CONTROL_VALUE 1001
#define _APS_NEXT_SYMED_VALUE 101
#endif
#endif |
x64dbg-development/src/exe/strings.rc | // Microsoft Visual C++ generated resource script.
//
#include "strings.h"
#define APSTUDIO_READONLY_SYMBOLS
/////////////////////////////////////////////////////////////////////////////
//
// Generated from the TEXTINCLUDE 2 resource.
//
#include "winres.h"
/////////////////////////////////////////////////////////////////////////////
#undef APSTUDIO_READONLY_SYMBOLS
/////////////////////////////////////////////////////////////////////////////
// Chinese (Simplified, PRC) resources
#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_CHS)
LANGUAGE LANG_CHINESE, SUBLANG_CHINESE_SIMPLIFIED
#ifdef APSTUDIO_INVOKED
/////////////////////////////////////////////////////////////////////////////
//
// TEXTINCLUDE
//
1 TEXTINCLUDE
BEGIN
"strings.h\0"
END
2 TEXTINCLUDE
BEGIN
"#include ""winres.h""\r\n"
"\0"
END
3 TEXTINCLUDE
BEGIN
"\r\n"
"\0"
END
#endif // APSTUDIO_INVOKED
/////////////////////////////////////////////////////////////////////////////
//
// String Table
//
STRINGTABLE
BEGIN
IDS_SETUP "安装"
IDS_ERROR "错误"
IDS_ERRORGETTINGMODULEPATH "获取模块路径时出错!"
IDS_QUESTION "温馨提示"
IDS_ASKSHELLEXT "您想要为调试器注册右键菜单吗?"
IDS_ASKDESKTOPSHORTCUT "您想要创建桌面快捷方式吗?"
IDS_DONE "完成!"
IDS_NEWCFGWRITTEN "新的配置已经写入!"
END
STRINGTABLE
BEGIN
IDS_INVDPATH32 "启动器的配置文件中没有指定x32dbg的路径..."
IDS_INVDPATH64 "启动器的配置文件中没有指定x64dbg的路径..."
IDS_INVDPE "无效的PE文件!"
IDS_FILEERR "文件没找到,或者已被占用!"
IDS_SHORTCUTDESC "一个面向未来的调试器!"
IDS_ASKADMIN "您确定以管理员权限运行本程序了吗?"
IDS_REGCREATEKEYFAIL "RegCreateKey 失败!"
IDS_REGSETVALUEEXFAIL "RegSetValueEx 失败!"
IDS_REGOPENKEYFAIL "RegOpenKeyEx 失败!"
IDS_BRIDGEINITERR "BridgeInit 发生错误"
IDS_SHELLEXTDBG "用x64dbg调试"
IDS_ASKICON "您想为调试数据库设置图标吗?"
IDS_BRIDGESTARTERR "BridgeStart 发生错误"
END
#endif // Chinese (Simplified, PRC) resources
/////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////
// English (United States) resources
#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU)
LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US
/////////////////////////////////////////////////////////////////////////////
//
// String Table
//
STRINGTABLE
BEGIN
IDS_SETUP "Install"
IDS_ERROR "Error"
IDS_ERRORGETTINGMODULEPATH "Error getting module path!"
IDS_QUESTION "Question"
IDS_ASKSHELLEXT "Do you want to register a shell extension?"
IDS_ASKDESKTOPSHORTCUT "Do you want to create Desktop Shortcuts?"
IDS_DONE "Done!"
IDS_NEWCFGWRITTEN "New configuration written! Restart to use x64dbg."
END
STRINGTABLE
BEGIN
IDS_INVDPATH32 "Path to x32dbg not specified in launcher configuration..."
IDS_INVDPATH64 "Path to x64dbg not specified in launcher configuration..."
IDS_INVDPE "Invalid PE File!"
IDS_FILEERR "File not found or in use!"
IDS_SHORTCUTDESC "A Debugger for the future!"
IDS_ASKADMIN "Running as Admin?"
IDS_REGCREATEKEYFAIL "RegCreateKey failed!"
IDS_REGSETVALUEEXFAIL "RegSetValueEx failed!"
IDS_REGOPENKEYFAIL "RegOpenKeyEx Failed!"
IDS_BRIDGEINITERR "BridgeInit Error"
IDS_SHELLEXTDBG "Debug with x64dbg"
IDS_ASKICON "Do you want to register the database icon?"
IDS_BRIDGESTARTERR "BridgeStart Error"
END
#endif // English (United States) resources
/////////////////////////////////////////////////////////////////////////////
#ifndef APSTUDIO_INVOKED
/////////////////////////////////////////////////////////////////////////////
//
// Generated from the TEXTINCLUDE 3 resource.
//
/////////////////////////////////////////////////////////////////////////////
#endif // not APSTUDIO_INVOKED |
|
C++ | x64dbg-development/src/exe/x64dbg_exe.cpp | /**
@file x64dbg_exe.cpp
@brief Implements the 64 debug executable class.
*/
#include <stdio.h>
#include <windows.h>
#include "crashdump.h"
#include "../bridge/bridgemain.h"
#include "LoadResourceString.h"
#include "signaturecheck.h"
/**
@fn int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nShowCmd)
@brief Window main.
@param hInstance The instance.
@param hPrevInstance The previous instance.
@param lpCmdLine The command line.
@param nShowCmd The show command.
@return An APIENTRY.
*/
int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nShowCmd)
{
// Reference: https://www.trendmicro.com/pl_pl/research/23/b/investigating-the-plugx-trojan-disguised-as-a-legitimate-windows.html
if(!InitializeSignatureCheck())
MessageBoxA(nullptr, "Failed to initialize signature check.", "Error", MB_SYSTEMMODAL | MB_ICONERROR);
CrashDumpInitialize();
const wchar_t* errormsg = BridgeInit();
if(errormsg)
{
MessageBoxW(0, errormsg, LoadResString(IDS_BRIDGEINITERR), MB_ICONERROR | MB_SYSTEMMODAL);
return 1;
}
errormsg = BridgeStart();
if(errormsg)
{
MessageBoxW(0, errormsg, LoadResString(IDS_BRIDGESTARTERR), MB_ICONERROR | MB_SYSTEMMODAL);
return 1;
}
return 0;
} |
Visual C++ Project | x64dbg-development/src/exe/x64dbg_exe.vcxproj | <?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Debug|Win32">
<Configuration>Debug</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Debug|x64">
<Configuration>Debug</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|Win32">
<Configuration>Release</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|x64">
<Configuration>Release</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
</ItemGroup>
<ItemGroup>
<ClCompile Include="crashdump.cpp" />
<ClCompile Include="signaturecheck.cpp" />
<ClCompile Include="x64dbg_exe.cpp" />
</ItemGroup>
<ItemGroup>
<ClInclude Include="crashdump.h" />
<ClInclude Include="icon.h" />
<ClInclude Include="LoadResourceString.h" />
<ClInclude Include="resource.h" />
<ClInclude Include="signaturecheck.h" />
<ClInclude Include="strings.h" />
</ItemGroup>
<ItemGroup>
<ResourceCompile Include="icon32.rc">
<ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">true</ExcludedFromBuild>
<ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release|x64'">true</ExcludedFromBuild>
</ResourceCompile>
<ResourceCompile Include="icon64.rc">
<ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</ExcludedFromBuild>
<ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">true</ExcludedFromBuild>
</ResourceCompile>
<ResourceCompile Include="resource.rc" />
<ResourceCompile Include="Strings.rc" />
</ItemGroup>
<ItemGroup>
<None Include="..\bug.ico" />
<None Include="manifest.xml" />
</ItemGroup>
<ItemGroup>
<Image Include="..\bug32.ico" />
<Image Include="..\bug64.ico" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\bridge\x64dbg_bridge.vcxproj">
<Project>{944d9923-cb1a-6f6c-bcbc-9e00a71954c1}</Project>
</ProjectReference>
</ItemGroup>
<PropertyGroup Label="Globals">
<ProjectGuid>{3A22175E-6B72-FDCC-1603-C4A2163C7900}</ProjectGuid>
<Keyword>Win32Proj</Keyword>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v120_xp</PlatformToolset>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v120_xp</PlatformToolset>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v120_xp</PlatformToolset>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v120_xp</PlatformToolset>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings">
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="PropertySheets">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="PropertySheets">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="PropertySheets">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<PropertyGroup Label="UserMacros" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<LinkIncremental>false</LinkIncremental>
<OutDir>$(ProjectDir)..\..\bin\x32\</OutDir>
<IntDir>$(Platform)\$(Configuration)\</IntDir>
<TargetName>x32dbg</TargetName>
<GenerateManifest>false</GenerateManifest>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<LinkIncremental>false</LinkIncremental>
<OutDir>$(ProjectDir)..\..\bin\x32d\</OutDir>
<IntDir>$(Platform)\$(Configuration)\</IntDir>
<TargetName>x32dbg</TargetName>
<GenerateManifest>false</GenerateManifest>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<LinkIncremental>false</LinkIncremental>
<OutDir>$(ProjectDir)..\..\bin\x64\</OutDir>
<TargetName>x64dbg</TargetName>
<GenerateManifest>false</GenerateManifest>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<LinkIncremental>false</LinkIncremental>
<OutDir>$(ProjectDir)..\..\bin\x64d\</OutDir>
<TargetName>x64dbg</TargetName>
<GenerateManifest>false</GenerateManifest>
</PropertyGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<ClCompile>
<PreprocessorDefinitions>WIN32;NDEBUG;_WINDOWS;_USRDLL;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<RuntimeLibrary>MultiThreaded</RuntimeLibrary>
<WarningLevel>Level3</WarningLevel>
<DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
</ClCompile>
<Link>
<TargetMachine>MachineX86</TargetMachine>
<GenerateDebugInformation>true</GenerateDebugInformation>
<SubSystem>Windows</SubSystem>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
<ProgramDatabaseFile>$(TargetDir)$(TargetName)_exe.pdb</ProgramDatabaseFile>
<AdditionalManifestDependencies>
</AdditionalManifestDependencies>
<LargeAddressAware>true</LargeAddressAware>
<DelayLoadDLLs>user32.dll;wintrust.dll;x32bridge.dll</DelayLoadDLLs>
<ModuleDefinitionFile>signaturecheck.def</ModuleDefinitionFile>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<ClCompile>
<PreprocessorDefinitions>WIN32;NDEBUG;_WINDOWS;_USRDLL;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<RuntimeLibrary>MultiThreadedDebugDLL</RuntimeLibrary>
<WarningLevel>Level3</WarningLevel>
<DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
</ClCompile>
<Link>
<TargetMachine>MachineX86</TargetMachine>
<GenerateDebugInformation>true</GenerateDebugInformation>
<SubSystem>Windows</SubSystem>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
<ProgramDatabaseFile>$(TargetDir)$(TargetName)_exe.pdb</ProgramDatabaseFile>
<AdditionalManifestDependencies>
</AdditionalManifestDependencies>
<ModuleDefinitionFile>signaturecheck.def</ModuleDefinitionFile>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<ClCompile>
<PreprocessorDefinitions>WIN32;NDEBUG;_WINDOWS;_USRDLL;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<RuntimeLibrary>MultiThreaded</RuntimeLibrary>
<WarningLevel>Level3</WarningLevel>
<DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
</ClCompile>
<Link>
<GenerateDebugInformation>true</GenerateDebugInformation>
<SubSystem>Windows</SubSystem>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
<ProgramDatabaseFile>$(TargetDir)$(TargetName)_exe.pdb</ProgramDatabaseFile>
<AdditionalManifestDependencies>
</AdditionalManifestDependencies>
<DelayLoadDLLs>user32.dll;wintrust.dll;x64bridge.dll</DelayLoadDLLs>
<ModuleDefinitionFile>signaturecheck.def</ModuleDefinitionFile>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<ClCompile>
<PreprocessorDefinitions>WIN32;NDEBUG;_WINDOWS;_USRDLL;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<RuntimeLibrary>MultiThreadedDebugDLL</RuntimeLibrary>
<WarningLevel>Level3</WarningLevel>
<DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
</ClCompile>
<Link>
<GenerateDebugInformation>true</GenerateDebugInformation>
<SubSystem>Windows</SubSystem>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
<ProgramDatabaseFile>$(TargetDir)$(TargetName)_exe.pdb</ProgramDatabaseFile>
<AdditionalManifestDependencies>
</AdditionalManifestDependencies>
<ModuleDefinitionFile>signaturecheck.def</ModuleDefinitionFile>
</Link>
</ItemDefinitionGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
</ImportGroup>
</Project> |
x64dbg-development/src/exe/x64dbg_exe.vcxproj.filters | <?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup>
<Filter Include="Source Files">
<UniqueIdentifier>{4FC737F1-C7A5-4376-A066-2A32D752A2FF}</UniqueIdentifier>
<Extensions>cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx</Extensions>
</Filter>
<Filter Include="Header Files">
<UniqueIdentifier>{93995380-89BD-4b04-88EB-625FBE52EBFB}</UniqueIdentifier>
<Extensions>h;hpp;hxx;hm;inl;inc;xsd</Extensions>
</Filter>
<Filter Include="Resource Files">
<UniqueIdentifier>{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}</UniqueIdentifier>
<Extensions>rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav</Extensions>
</Filter>
</ItemGroup>
<ItemGroup>
<ClCompile Include="crashdump.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="x64dbg_exe.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="signaturecheck.cpp">
<Filter>Source Files</Filter>
</ClCompile>
</ItemGroup>
<ItemGroup>
<ClInclude Include="resource.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="crashdump.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="icon.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="strings.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="LoadResourceString.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="signaturecheck.h">
<Filter>Header Files</Filter>
</ClInclude>
</ItemGroup>
<ItemGroup>
<ResourceCompile Include="resource.rc">
<Filter>Resource Files</Filter>
</ResourceCompile>
<ResourceCompile Include="icon32.rc">
<Filter>Resource Files</Filter>
</ResourceCompile>
<ResourceCompile Include="icon64.rc">
<Filter>Resource Files</Filter>
</ResourceCompile>
<ResourceCompile Include="Strings.rc">
<Filter>Resource Files</Filter>
</ResourceCompile>
</ItemGroup>
<ItemGroup>
<None Include="..\bug.ico">
<Filter>Resource Files</Filter>
</None>
<None Include="manifest.xml" />
</ItemGroup>
<ItemGroup>
<Image Include="..\bug32.ico">
<Filter>Resource Files</Filter>
</Image>
<Image Include="..\bug64.ico">
<Filter>Resource Files</Filter>
</Image>
</ItemGroup>
</Project> |
|
x64dbg-development/src/gui/default.css | /* QStatusBar == DebugStatusLabel, LogStatusLabel, TimeWastedCounter */
QStatusBar QLabel {
background-color: #c0c0c0;
}
QStatusBar QFrame {
qproperty-frameShape: Panel;
qproperty-frameShadow: Sunken;
}
QStatusBar::item {
border: none;
}
QStatusBar {
background-color: #c0c0c0;
}
DebugStatusLabel[state="initialized"] {
color: #00dd00;
background-color: #c0c0c0;
}
DebugStatusLabel[state="paused"] {
color: #ff0000;
background-color: #ffff00;
}
DebugStatusLabel[state="running"] {
color: #000000;
background-color: #c0c0c0;
}
DebugStatusLabel[state="stopped"] {
color: #ff0000;
background-color: #c0c0c0;
}
QPushButton#AbstractTableViewHeader {
background-color: rgb(192, 192, 192);
border-style: outset;
border-width: 2px;
border-color: rgb(128, 128, 128);
}
QPushButton#AbstractTableViewHeader QPushButton:pressed {
background-color: rgb(192, 192, 192);
border-style: inset;
}
ShortcutEdit {
color: #222222;
}
ShortcutEdit[error="true"] {
color: #dd0000;
}
QTabWidget::pane {
border: 0px;
}
QTabBar::tear {
width: 0px;
border: none;
}
/* Attempt at fixing an ugly bug: https://stackoverflow.com/a/55097717/1806760 */
QTabBar QToolButton {
border-width: 1px;
border-color: grey;
border-style: solid;
border-radius: 2px;
background: #f0f0f0;
padding: 0px;
margin: 0px;
margin-top: 2px;
margin-bottom: 2px;
}
QTabBar QToolButton::hover {
background: #f0f0f0;
border: 1px solid black;
}
QTabBar::scroller {
width: 15px;
}
/* JIT debugger in SettingsDialog */
QLineEdit:read-only {
background-color: #f0f0f0;
} |
|
x64dbg-development/src/gui/index.theme | [Icon Theme]
Name=Default
Comment=Default icon theme
Directories=icons
[icons]
Size=16
Type=Scalable |
|
x64dbg-development/src/gui/resource.qrc | <RCC>
<qresource prefix="/Default">
<file>icons/folder-horizontal-open.png</file>
<file>icons/arrow-step-into.png</file>
<file>icons/arrow-step-over.png</file>
<file>icons/control-pause.png</file>
<file>icons/arrow-run.png</file>
<file>icons/geolocation-goto.png</file>
<file>icons/arrow-restart.png</file>
<file>icons/arrow-step-rtr.png</file>
<file>icons/control-exit.png</file>
<file>icons/control-stop.png</file>
<file>icons/terminal-command.png</file>
<file>icons/memory-map.png</file>
<file>icons/ui-combo-box-edit.png</file>
<file>icons/scylla.png</file>
<file>icons/compile-error.png</file>
<file>icons/compile-warning.png</file>
<file>icons/compile.png</file>
<file>icons/script-code.png</file>
<file>icons/script-error.png</file>
<file>icons/information.png</file>
<file>icons/question.png</file>
<file>icons/arrow-run-cursor.png</file>
<file>icons/log.png</file>
<file>icons/breakpoint.png</file>
<file>icons/pdb.png</file>
<file>icons/search.png</file>
<file>icons/arrow-threads.png</file>
<file>icons/settings.png</file>
<file>icons/strings.png</file>
<file>icons/color-swatches.png</file>
<file>icons/call.png</file>
<file>icons/document-binary.png</file>
<file>icons/patch.png</file>
<file>icons/bookmarks.png</file>
<file>icons/functions.png</file>
<file>icons/labels.png</file>
<file>icons/comments.png</file>
<file>icons/update.png</file>
<file>icons/callstack.png</file>
<file>icons/shortcut.png</file>
<file>icons/donate.png</file>
<file>icons/calculator.png</file>
<file>icons/attach.png</file>
<file>icons/detach.png</file>
<file>icons/trace.png</file>
<file>icons/changeargs.png</file>
<file>icons/arrow-skip.png</file>
<file>icons/topmost.png</file>
<file>icons/close-all-tabs.png</file>
<file>icons/bug-report.png</file>
<file>icons/yara.png</file>
<file>icons/data-copy.png</file>
<file>icons/source.png</file>
<file>icons/bookmark.png</file>
<file>icons/comment.png</file>
<file>icons/binary.png</file>
<file>icons/copy.png</file>
<file>icons/search-for.png</file>
<file>icons/highlight.png</file>
<file>icons/label.png</file>
<file>icons/notes.png</file>
<file>icons/win-help.png</file>
<file>icons/faq.png</file>
<file>icons/help.png</file>
<file>icons/goto.png</file>
<file>icons/neworigin.png</file>
<file>icons/find.png</file>
<file>icons/recentfiles.png</file>
<file>icons/eraser.png</file>
<file>icons/processor32.png</file>
<file>icons/processor64.png</file>
<file>icons/processor-cpu.png</file>
<file>icons/seh-chain.png</file>
<file>icons/css.png</file>
<file>icons/hide-debugger.png</file>
<file>icons/sync.png</file>
<file>icons/stack.png</file>
<file>icons/address.png</file>
<file>icons/float.png</file>
<file>icons/hex.png</file>
<file>icons/integer.png</file>
<file>icons/plugin.png</file>
<file>icons/modify.png</file>
<file>icons/freeze.png</file>
<file>icons/cbp.png</file>
<file>icons/next.png</file>
<file>icons/previous.png</file>
<file>icons/bottom.png</file>
<file>icons/top.png</file>
<file>icons/fileoffset.png</file>
<file>icons/helpbrief.png</file>
<file>icons/helpmnemonic.png</file>
<file>icons/handles.png</file>
<file>icons/dump.png</file>
<file>icons/xrefs.png</file>
<file>icons/codepage.png</file>
<file>icons/traceinto.png</file>
<file>icons/traceover.png</file>
<file>icons/analysis_single_function.png</file>
<file>icons/remove_analysis_from_module.png</file>
<file>icons/remove_analysis_from_selection.png</file>
<file>icons/treat_selection_as_ascii.png</file>
<file>icons/treat_selection_as_byte.png</file>
<file>icons/treat_selection_as_cmd.png</file>
<file>icons/treat_selection_as_dword.png</file>
<file>icons/treat_selection_as_float.png</file>
<file>icons/treat_selection_as_fword.png</file>
<file>icons/treat_selection_as_mmword.png</file>
<file>icons/treat_selection_as_oword.png</file>
<file>icons/treat_selection_as_qword.png</file>
<file>icons/treat_selection_as_tbyte.png</file>
<file>icons/treat_selection_as_unicode.png</file>
<file>icons/treat_selection_as_word.png</file>
<file>icons/treat_selection_as_xmm.png</file>
<file>icons/treat_selection_as_ymm.png</file>
<file>icons/analysis.png</file>
<file>icons/arguments.png</file>
<file>icons/bit.png</file>
<file>icons/byte.png</file>
<file>icons/dword.png</file>
<file>icons/functionend.png</file>
<file>icons/functionstart.png</file>
<file>icons/qword.png</file>
<file>icons/word.png</file>
<file>icons/xmm.png</file>
<file>icons/ymm.png</file>
<file>icons/zmm.png</file>
<file>icons/treat_selection_as_double.png</file>
<file>icons/treat_selection_as_longdouble.png</file>
<file>icons/treat_from_selection_as.png</file>
<file>icons/treat_selection_head_as.png</file>
<file>icons/register_dec.png</file>
<file>icons/register_edit.png</file>
<file>icons/register_inc.png</file>
<file>icons/register_one.png</file>
<file>icons/register_toggle.png</file>
<file>icons/register_zero.png</file>
<file>icons/arrow-small-down.png</file>
<file>icons/arrow-small-up.png</file>
<file>icons/copy-alt.png</file>
<file>icons/change-view.png</file>
<file>icons/ascii.png</file>
<file>icons/ascii-extended.png</file>
<file>icons/binary_copy.png</file>
<file>icons/binary_edit.png</file>
<file>icons/binary_fill.png</file>
<file>icons/binary_fill_nop.png</file>
<file>icons/binary_paste.png</file>
<file>icons/binary_paste_ignoresize.png</file>
<file>icons/bookmark_toggle.png</file>
<file>icons/breakpoint_access.png</file>
<file>icons/breakpoint_add.png</file>
<file>icons/breakpoint_byte.png</file>
<file>icons/breakpoint_dword.png</file>
<file>icons/breakpoint_edit.png</file>
<file>icons/breakpoint_edit_alt.png</file>
<file>icons/breakpoint_execute.png</file>
<file>icons/breakpoint_execute_slot1.png</file>
<file>icons/breakpoint_execute_slot2.png</file>
<file>icons/breakpoint_execute_slot3.png</file>
<file>icons/breakpoint_execute_slot4.png</file>
<file>icons/breakpoint_memory_access.png</file>
<file>icons/breakpoint_memory_execute.png</file>
<file>icons/breakpoint_memory_restore_on_hit.png</file>
<file>icons/breakpoint_memory_singleshoot.png</file>
<file>icons/breakpoint_memory_write.png</file>
<file>icons/breakpoint_qword.png</file>
<file>icons/breakpoint_remove.png</file>
<file>icons/breakpoint_settings.png</file>
<file>icons/breakpoint_toggle.png</file>
<file>icons/breakpoint_word.png</file>
<file>icons/breakpoint_write.png</file>
<file>icons/copy_address.png</file>
<file>icons/copy_cropped_table.png</file>
<file>icons/copy_disassembly.png</file>
<file>icons/copy_full_table.png</file>
<file>icons/copy_selection.png</file>
<file>icons/copy_selection_no_bytes.png</file>
<file>icons/copy_table_line.png</file>
<file>icons/copyfilepath.png</file>
<file>icons/download_symbols.png</file>
<file>icons/entrypoint.png</file>
<file>icons/follow_entrypoint.png</file>
<file>icons/follow_in_cpu.png</file>
<file>icons/follow_in_dump.png</file>
<file>icons/follow_in_dump1.png</file>
<file>icons/follow_in_dump2.png</file>
<file>icons/follow_in_dump3.png</file>
<file>icons/follow_in_dump4.png</file>
<file>icons/follow_in_dump5.png</file>
<file>icons/pdb_alt.png</file>
<file>icons/search_all_modules.png</file>
<file>icons/search_current_module.png</file>
<file>icons/search_current_region.png</file>
<file>icons/search_for_command.png</file>
<file>icons/search_for_constant.png</file>
<file>icons/search_for_pattern.png</file>
<file>icons/search_for_string.png</file>
<file>icons/thread-entry.png</file>
<file>icons/thread-kill.png</file>
<file>icons/thread-pause.png</file>
<file>icons/thread-priority-above-normal.png</file>
<file>icons/thread-priority-below-normal.png</file>
<file>icons/thread-priority-highest.png</file>
<file>icons/thread-priority-idle.png</file>
<file>icons/thread-priority-lowest.png</file>
<file>icons/thread-priority-normal.png</file>
<file>icons/thread-priority-timecritical.png</file>
<file>icons/thread-resume.png</file>
<file>icons/thread-setpriority.png</file>
<file>icons/thread-setpriority_alt.png</file>
<file>icons/thread-switch.png</file>
<file>icons/unicode.png</file>
<file>icons/fatal-error.png</file>
<file>icons/star.png</file>
<file>icons/16bit.png</file>
<file>icons/16bit-short.png</file>
<file>icons/32bit.png</file>
<file>icons/32bit-float.png</file>
<file>icons/32bit-long.png</file>
<file>icons/64bit.png</file>
<file>icons/64bit-float.png</file>
<file>icons/64bit-long.png</file>
<file>icons/80bit.png</file>
<file>icons/80bit-float.png</file>
<file>icons/breakpoint_disable.png</file>
<file>icons/breakpoint_disable_all.png</file>
<file>icons/breakpoint_editcaret.png</file>
<file>icons/breakpoint_enable.png</file>
<file>icons/breakpoint_enable_all.png</file>
<file>icons/breakpoint_remove_all.png</file>
<file>icons/breakpoint_remove_all_commands.png</file>
<file>icons/breakpoint_reset_hitcount.png</file>
<file>icons/breakpoint_seton_all_commands.png</file>
<file>icons/memmap_alloc_memory.png</file>
<file>icons/memmap_dump_memory_to_file.png</file>
<file>icons/memmap_find_address_page.png</file>
<file>icons/memmap_free_memory.png</file>
<file>icons/memmap_memory_breakpoint.png</file>
<file>icons/memmap_set_page_memory_rights.png</file>
<file>icons/runtouser.png</file>
<file>icons/undo.png</file>
<file>icons/binary_save.png</file>
<file>icons/animal-dog.png</file>
<file>icons/graph.png</file>
<file>icons/enable.png</file>
<file>icons/disable.png</file>
<file>icons/database-export.png</file>
<file>icons/database-import.png</file>
<file>icons/lock.png</file>
<file>icons/createthread.png</file>
<file>icons/animatecommand.png</file>
<file>icons/animateinto.png</file>
<file>icons/animateover.png</file>
<file>icons/browseinexplorer.png</file>
<file>icons/markasparty.png</file>
<file>icons/markasuser.png</file>
<file>icons/markassystem.png</file>
<file>icons/guid.png</file>
<file>icons/analyzemodule.png</file>
<file>icons/branchpreview.png</file>
<file>icons/simdmode.png</file>
<file>icons/breakpoint_exception_add.png</file>
<file>icons/breakpoint_module_add.png</file>
<file>icons/importsettings.png</file>
<file>icons/themes.png</file>
<file>icons/initscript.png</file>
<file>icons/struct.png</file>
<file>icons/removestruct.png</file>
<file>icons/visitstruct.png</file>
<file>icons/structaddr.png</file>
<file>icons/virtual.png</file>
<file>icons/uac.png</file>
<file>icons/hidetab.png</file>
<file>icons/variables.png</file>
<file>icons/lib_load.png</file>
<file>icons/lib_free.png</file>
<file>icons/christmas1.png</file>
<file>icons/christmas2.png</file>
<file>icons/christmas3.png</file>
<file>icons/christmas4.png</file>
<file>icons/christmas5.png</file>
<file>icons/christmas6.png</file>
<file>icons/christmas7.png</file>
<file>icons/christmas8.png</file>
<file>icons/image.png</file>
<file>icons/medium.png</file>
<file>icons/narrow.png</file>
<file>icons/wide.png</file>
<file>icons/layout.png</file>
<file>icons/summary.png</file>
<file>icons/edit-script.png</file>
<file>icons/load-script.png</file>
<file>icons/import.png</file>
<file>icons/easter1.png</file>
<file>icons/easter2.png</file>
<file>icons/easter3.png</file>
<file>icons/easter4.png</file>
<file>icons/easter5.png</file>
<file>icons/easter6.png</file>
<file>icons/easter7.png</file>
<file>icons/easter8.png</file>
<file>icons/egg.wav</file>
<file>icons/localvars.png</file>
<file>icons/nextref.png</file>
<file>icons/prevref.png</file>
<file>icons/bug.png</file>
<file>icons/donation_qr.png</file>
<file>icons/breakpoint_memory_read.png</file>
<file>icons/lib.png</file>
<file>icons/names.png</file>
<file>icons/fit.png</file>
<file>icons/zoom.png</file>
<file>icons/crash_dump.png</file>
<file>icons/exclamation.png</file>
<file>index.theme</file>
<file>icons/control-record.png</file>
<file>icons/delete.png</file>
<file>icons/close.png</file>
</qresource>
<qresource prefix="/css">
<file>default.css</file>
</qresource>
</RCC> |
|
x64dbg-development/src/gui/x64dbg.pro | #-------------------------------------------------
#
# Project created by QtCreator 2013-05-20T13:22:23
#
#-------------------------------------------------
##
## Pre-defined global variables
##
CONFIG(debug, debug|release) {
DIR_SUFFIX = d
} else {
DIR_SUFFIX =
}
!contains(QMAKE_HOST.arch, x86_64) {
X64_BIN_DIR = ../../bin/x32$${DIR_SUFFIX} # Relative BIN path, 32-bit
X64_GEN_DIR = ../gui_build/out32$${DIR_SUFFIX} # QMake temporary generated files, placed inside the build folder. (OBJ, UI, MOC)
TARGET = x32gui # Build x32gui
} else {
X64_BIN_DIR = ../../bin/x64$${DIR_SUFFIX} # Relative BIN path, 64-bit
X64_GEN_DIR = ../gui_build/out64$${DIR_SUFFIX} # QMake temporary generated files, placed inside the build folder. (OBJ, UI, MOC)
TARGET = x64gui # Build x64gui
}
##
## QMake output directories
##
DESTDIR = $${X64_BIN_DIR}
OBJECTS_DIR = $${X64_GEN_DIR}
MOC_DIR = $${X64_GEN_DIR}
RCC_DIR = $${X64_GEN_DIR}
UI_DIR = $${X64_GEN_DIR}
##
## QT libraries
##
QT += core gui network winextras
# QT5 requires widgets
greaterThan(QT_MAJOR_VERSION, 4): QT += widgets
##
## Build flags
##
# Generate debug symbols in release mode
QMAKE_CXXFLAGS_RELEASE += -Zi # Compiler
QMAKE_LFLAGS_RELEASE += /DEBUG # Linker
# Build as a library
DEFINES += BUILD_LIB NOMINMAX
TEMPLATE = lib
##
## Includes
##
INCLUDEPATH += \
../ \
Src \
Src/Gui \
Src/BasicView \
Src/Disassembler \
Src/Memory \
Src/Bridge \
Src/Global \
Src/Utils \
Src/ThirdPartyLibs/ldconvert \
../zydis_wrapper \
../zydis_wrapper/zydis/include
# Resources, sources, headers, and forms
RESOURCES += \
resource.qrc
SOURCES += \
Src/BasicView/StdIconSearchListView.cpp \
Src/BasicView/StdIconTable.cpp \
Src/Gui/CPURegistersView.cpp \
Src/Gui/RichTextItemDelegate.cpp \
Src/Gui/SystemBreakpointScriptDialog.cpp \
Src/Imports.cpp \
Src/Tracer/TraceInfoBox.cpp \
Src/Tracer/TraceRegisters.cpp \
Src/Tracer/TraceWidget.cpp \
Src/Utils/CommonActions.cpp \
Src/main.cpp \
Src/Gui/MainWindow.cpp \
Src/Gui/CPUWidget.cpp \
Src/Gui/CommandLineEdit.cpp \
Src/BasicView/Disassembly.cpp \
Src/BasicView/HexDump.cpp \
Src/BasicView/AbstractTableView.cpp \
Src/Disassembler/QBeaEngine.cpp \
Src/Disassembler/ZydisTokenizer.cpp \
Src/Memory/MemoryPage.cpp \
Src/Bridge/Bridge.cpp \
Src/BasicView/StdTable.cpp \
Src/Gui/MemoryMapView.cpp \
Src/Gui/LogView.cpp \
Src/Gui/GotoDialog.cpp \
Src/Gui/WordEditDialog.cpp \
Src/Gui/CPUDisassembly.cpp \
Src/Gui/LineEditDialog.cpp \
Src/Gui/BreakpointsView.cpp \
Src/Utils/Breakpoints.cpp \
Src/Gui/CPUInfoBox.cpp \
Src/Gui/CPUDump.cpp \
Src/Gui/ScriptView.cpp \
Src/Gui/CPUStack.cpp \
Src/Gui/SymbolView.cpp \
Src/Gui/RegistersView.cpp \
Src/BasicView/SearchListView.cpp \
Src/BasicView/ReferenceView.cpp \
Src/Gui/ThreadView.cpp \
Src/Gui/SettingsDialog.cpp \
Src/Gui/ExceptionRangeDialog.cpp \
Src/Utils/RichTextPainter.cpp \
Src/Gui/TabBar.cpp \
Src/Gui/TabWidget.cpp \
Src/BasicView/HistoryLineEdit.cpp \
Src/Utils/Configuration.cpp \
Src/Gui/CPUSideBar.cpp \
Src/Gui/AppearanceDialog.cpp \
Src/Gui/CloseDialog.cpp \
Src/Gui/HexEditDialog.cpp \
Src/Gui/HexLineEdit.cpp \
Src/QHexEdit/ArrayCommand.cpp \
Src/QHexEdit/QHexEdit.cpp \
Src/QHexEdit/QHexEditPrivate.cpp \
Src/QHexEdit/XByteArray.cpp \
Src/Gui/PatchDialog.cpp \
Src/Gui/PatchDialogGroupSelector.cpp \
Src/Utils/UpdateChecker.cpp \
Src/Gui/CallStackView.cpp \
Src/Gui/ShortcutsDialog.cpp \
Src/BasicView/ShortcutEdit.cpp \
Src/Gui/CalculatorDialog.cpp \
Src/Gui/AttachDialog.cpp \
Src/Gui/PageMemoryRights.cpp \
Src/Gui/SelectFields.cpp \
Src/Gui/ReferenceManager.cpp \
Src/Bridge/BridgeResult.cpp \
Src/Gui/SourceViewerManager.cpp \
Src/Gui/SourceView.cpp \
Src/Utils/ValidateExpressionThread.cpp \
Src/Utils/MainWindowCloseThread.cpp \
Src/Gui/TimeWastedCounter.cpp \
Src/Utils/FlickerThread.cpp \
Src/Gui/NotesManager.cpp \
Src/Gui/NotepadView.cpp \
Src/Gui/CPUMultiDump.cpp \
Src/Gui/AssembleDialog.cpp \
Src/Utils/StringUtil.cpp \
Src/Gui/SEHChainView.cpp \
Src/Gui/EditBreakpointDialog.cpp \
Src/Gui/CPUArgumentWidget.cpp \
Src/Gui/HandlesView.cpp \
Src/Gui/EditFloatRegister.cpp \
Src/Utils/HexValidator.cpp \
Src/Utils/LongLongValidator.cpp \
Src/Utils/MiscUtil.cpp \
Src/Gui/XrefBrowseDialog.cpp \
Src/Gui/CodepageSelectionDialog.cpp \
Src/Gui/ColumnReorderDialog.cpp \
Src/Utils/EncodeMap.cpp \
Src/Utils/CodeFolding.cpp \
Src/Gui/WatchView.cpp \
Src/Gui/FavouriteTools.cpp \
Src/Gui/BrowseDialog.cpp \
Src/Gui/DisassemblerGraphView.cpp \
Src/Gui/DisassemblyPopup.cpp \
Src/Gui/VirtualModDialog.cpp \
Src/BasicView/LabeledSplitter.cpp \
Src/BasicView/LabeledSplitterDetachedWindow.cpp \
Src/Gui/LogStatusLabel.cpp \
Src/Gui/DebugStatusLabel.cpp \
Src/Utils/MenuBuilder.cpp \
Src/Gui/StructWidget.cpp \
Src/Gui/CustomizeMenuDialog.cpp \
Src/Gui/SimpleTraceDialog.cpp \
Src/Utils/MRUList.cpp \
Src/Gui/LocalVarsView.cpp \
Src/Gui/MessagesBreakpoints.cpp \
Src/Gui/AboutDialog.cpp \
Src/Gui/ComboBoxDialog.cpp \
Src/Utils/SymbolAutoCompleteModel.cpp \
Src/Tracer/TraceBrowser.cpp \
Src/Tracer/TraceFileReader.cpp \
Src/Tracer/TraceFileSearch.cpp \
Src/Gui/MultiItemsSelectWindow.cpp \
Src/BasicView/AbstractStdTable.cpp \
Src/Gui/ZehSymbolTable.cpp \
Src/BasicView/StdSearchListView.cpp \
Src/BasicView/StdTableSearchList.cpp \
Src/Utils/BackgroundFlickerThread.cpp
HEADERS += \
Src/BasicView/StdIconSearchListView.h \
Src/BasicView/StdIconTable.h \
Src/Gui/CPURegistersView.h \
Src/Gui/RichTextItemDelegate.h \
Src/Gui/SystemBreakpointScriptDialog.h \
Src/Tracer/TraceInfoBox.h \
Src/Tracer/TraceRegisters.h \
Src/Tracer/TraceWidget.h \
Src/Utils/CommonActions.h \
Src/main.h \
Src/Gui/MainWindow.h \
Src/Gui/CPUWidget.h \
Src/Gui/CommandLineEdit.h \
Src/BasicView/Disassembly.h \
Src/BasicView/HexDump.h \
Src/BasicView/AbstractTableView.h \
Src/Disassembler/QBeaEngine.h \
Src/Disassembler/ZydisTokenizer.h \
Src/Memory/MemoryPage.h \
Src/Bridge/Bridge.h \
Src/Exports.h \
Src/Imports.h \
Src/BasicView/StdTable.h \
Src/Gui/MemoryMapView.h \
Src/Gui/LogView.h \
Src/Gui/GotoDialog.h \
Src/Gui/RegistersView.h \
Src/Gui/WordEditDialog.h \
Src/Gui/CPUDisassembly.h \
Src/Gui/LineEditDialog.h \
Src/Gui/BreakpointsView.h \
Src/Utils/Breakpoints.h \
Src/Gui/CPUInfoBox.h \
Src/Gui/CPUDump.h \
Src/Gui/ScriptView.h \
Src/Gui/CPUStack.h \
Src/Gui/SymbolView.h \
Src/BasicView/SearchListView.h \
Src/BasicView/ReferenceView.h \
Src/Gui/ThreadView.h \
Src/Gui/SettingsDialog.h \
Src/Gui/ExceptionRangeDialog.h \
Src/Utils/RichTextPainter.h \
Src/Gui/TabBar.h \
Src/Gui/TabWidget.h \
Src/BasicView/HistoryLineEdit.h \
Src/Utils/Configuration.h \
Src/Gui/CPUSideBar.h \
Src/Gui/AppearanceDialog.h \
Src/Gui/CloseDialog.h \
Src/Gui/HexEditDialog.h \
Src/Gui/HexLineEdit.h \
Src/QHexEdit/ArrayCommand.h \
Src/QHexEdit/QHexEdit.h \
Src/QHexEdit/QHexEditPrivate.h \
Src/QHexEdit/XByteArray.h \
Src/Gui/PatchDialog.h \
Src/Gui/PatchDialogGroupSelector.h \
Src/Utils/UpdateChecker.h \
Src/Gui/CallStackView.h \
Src/Gui/ShortcutsDialog.h \
Src/BasicView/ShortcutEdit.h \
Src/Gui/CalculatorDialog.h \
Src/Gui/AttachDialog.h \
Src/Gui/PageMemoryRights.h \
Src/Gui/SelectFields.h \
Src/Gui/ReferenceManager.h \
Src/Bridge/BridgeResult.h \
Src/Gui/SourceViewerManager.h \
Src/Gui/SourceView.h \
Src/Utils/StringUtil.h \
Src/Utils/ValidateExpressionThread.h \
Src/Utils/MainWindowCloseThread.h \
Src/Gui/TimeWastedCounter.h \
Src/Utils/FlickerThread.h \
Src/Gui/NotesManager.h \
Src/Gui/NotepadView.h \
Src/Utils/MenuBuilder.h \
Src/Gui/CPUMultiDump.h \
Src/Gui/AssembleDialog.h \
Src/Gui/SEHChainView.h \
Src/Gui/EditBreakpointDialog.h \
Src/Gui/CPUArgumentWidget.h \
Src/Gui/HandlesView.h \
Src/Gui/EditFloatRegister.h \
Src/Utils/HexValidator.h \
Src/Utils/LongLongValidator.h \
Src/Utils/MiscUtil.h \
Src/Gui/XrefBrowseDialog.h \
Src/Gui/CodepageSelectionDialog.h \
Src/Utils/CachedFontMetrics.h \
Src/Gui/ColumnReorderDialog.h \
Src/Utils/EncodeMap.h \
Src/Utils/CodeFolding.h \
Src/Gui/WatchView.h \
Src/Gui/FavouriteTools.h \
Src/Gui/BrowseDialog.h \
Src/Gui/DisassemblerGraphView.h \
Src/Utils/ActionHelpers.h \
Src/Gui/DisassemblyPopup.h \
Src/Gui/VirtualModDialog.h \
Src/BasicView/LabeledSplitter.h \
Src/BasicView/LabeledSplitterDetachedWindow.h \
Src/Gui/LogStatusLabel.h \
Src/Gui/DebugStatusLabel.h \
Src/Gui/CustomizeMenuDialog.h \
Src/Gui/StructWidget.h \
Src/Gui/SimpleTraceDialog.h \
Src/Utils/MRUList.h \
Src/Gui/LocalVarsView.h \
Src/Gui/MessagesBreakpoints.h \
Src/Gui/AboutDialog.h \
Src/Gui/ComboBoxDialog.h \
Src/Utils/VaHistory.h \
Src/Utils/SymbolAutoCompleteModel.h \
Src/Tracer/TraceBrowser.h \
Src/Tracer/TraceFileReader.h \
Src/Tracer/TraceFileReaderInternal.h \
Src/Tracer/TraceFileSearch.h \
Src/Gui/MultiItemsSelectWindow.h \
Src/BasicView/AbstractStdTable.h \
Src/Gui/ZehSymbolTable.h \
Src/BasicView/AbstractSearchList.h \
Src/BasicView/StdSearchListView.h \
Src/Gui/FileLines.h \
Src/BasicView/StdTableSearchList.h \
Src/Utils/MethodInvoker.h \
Src/Utils/BackgroundFlickerThread.h
FORMS += \
Src/Gui/SystemBreakpointScriptDialog.ui \
Src/Gui/MainWindow.ui \
Src/Gui/CPUWidget.ui \
Src/Gui/GotoDialog.ui \
Src/Gui/WordEditDialog.ui \
Src/Gui/LineEditDialog.ui \
Src/Gui/SymbolView.ui \
Src/Gui/SettingsDialog.ui \
Src/Gui/ExceptionRangeDialog.ui \
Src/Gui/AppearanceDialog.ui \
Src/Gui/CloseDialog.ui \
Src/Gui/HexEditDialog.ui \
Src/Gui/HexLineEdit.ui \
Src/Gui/PatchDialog.ui \
Src/Gui/PatchDialogGroupSelector.ui \
Src/Gui/ShortcutsDialog.ui \
Src/Gui/CalculatorDialog.ui \
Src/Gui/AttachDialog.ui \
Src/Gui/PageMemoryRights.ui \
Src/Gui/SelectFields.ui \
Src/Gui/AssembleDialog.ui \
Src/Gui/EditBreakpointDialog.ui \
Src/Gui/CPUArgumentWidget.ui \
Src/Gui/EditFloatRegister.ui \
Src/Gui/XrefBrowseDialog.ui \
Src/Gui/CodepageSelectionDialog.ui \
Src/Gui/ColumnReorderDialog.ui \
Src/Gui/FavouriteTools.ui \
Src/Gui/BrowseDialog.ui \
Src/Gui/VirtualModDialog.ui \
Src/Gui/CustomizeMenuDialog.ui \
Src/Gui/StructWidget.ui \
Src/Gui/SimpleTraceDialog.ui \
Src/Gui/MessagesBreakpoints.ui \
Src/Gui/AboutDialog.ui \
Src/Gui/ComboBoxDialog.ui \
Src/Tracer/TraceWidget.ui
##
## Libraries
##
LIBS += -luser32 -ladvapi32 -lwinmm -lshell32
!contains(QMAKE_HOST.arch, x86_64) {
# Windows x86 (32bit) specific build
LIBS += -L"$$PWD/../zydis_wrapper/bin/x32$${DIR_SUFFIX}" -lzydis_wrapper
LIBS += -L"$$PWD/Src/ThirdPartyLibs/ldconvert" -lldconvert_x86
LIBS += -L"$${X64_BIN_DIR}" -lx32bridge
} else {
# Windows x64 (64bit) specific build
LIBS += -L"$$PWD/../zydis_wrapper/bin/x64$${DIR_SUFFIX}" -lzydis_wrapper
LIBS += -L"$$PWD/Src/ThirdPartyLibs/ldconvert" -lldconvert_x64
LIBS += -L"$${X64_BIN_DIR}" -lx64bridge
} |
|
C/C++ | x64dbg-development/src/gui/Src/Exports.h | #pragma once
#include "Imports.h"
/************************************************************************************
Exported Function Prototypes
************************************************************************************/
#ifdef BUILD_LIB
extern "C" __declspec(dllexport) int _gui_guiinit(int argc, char* argv[]);
extern "C" __declspec(dllexport) void* _gui_sendmessage(GUIMSG type, void* param1, void* param2);
extern "C" __declspec(dllexport) const char* _gui_translate_text(const char* source);
#endif |
C++ | x64dbg-development/src/gui/Src/Imports.cpp | #include "Imports.h"
#include <QString>
bool DbgCmdExec(const QString & cmd)
{
return DbgCmdExec(cmd.toUtf8().constData());
}
bool DbgCmdExecDirect(const QString & cmd)
{
return DbgCmdExecDirect(cmd.toUtf8().constData());
} |
C/C++ | x64dbg-development/src/gui/Src/Imports.h | #pragma once
#ifndef _BRIDGEMAIN_H_
#include "bridge/bridgemain.h"
#endif
#ifndef _DBGFUNCTIONS_H
#include "dbg/_dbgfunctions.h"
#endif
#ifndef _DBG_TYPES_H_
#include "dbg_types.h"
#endif
// Convenience overloads
class QString;
bool DbgCmdExec(const QString & cmd);
bool DbgCmdExecDirect(const QString & cmd); |
C++ | x64dbg-development/src/gui/Src/main.cpp | #include "main.h"
#include "zydis_wrapper.h"
#include "MainWindow.h"
#include "Configuration.h"
#include <QTextCodec>
#include <QFile>
#include <QTranslator>
#include <QTextStream>
#include <QLibraryInfo>
#include <QDebug>
#include <QDir>
#include "MiscUtil.h"
MyApplication::MyApplication(int & argc, char** argv)
: QApplication(argc, argv)
{
}
#if QT_VERSION < QT_VERSION_CHECK(5,0,0)
bool MyApplication::winEventFilter(MSG* message, long* result)
{
return DbgWinEvent(message, result);
}
bool MyApplication::globalEventFilter(void* message)
{
return DbgWinEventGlobal((MSG*)message);
}
#endif
bool MyApplication::notify(QObject* receiver, QEvent* event)
{
bool done = true;
try
{
if(event->type() == QEvent::WindowActivate && receiver->isWidgetType())
{
auto widget = (QWidget*)receiver;
if((widget->windowFlags() & Qt::Window) == Qt::Window)
{
MainWindow::updateDarkTitleBar(widget);
}
}
done = QApplication::notify(receiver, event);
}
catch(const std::exception & ex)
{
QString message = QString().sprintf("Fatal GUI Exception: %s!\n", ex.what());
GuiAddLogMessage(message.toUtf8().constData());
puts(message.toUtf8().constData());
OutputDebugStringA(message.toUtf8().constData());
}
catch(...)
{
const char* message = "Fatal GUI Exception: (...)!\n";
GuiAddLogMessage(message);
puts(message);
OutputDebugStringA(message);
}
return done;
}
static Configuration* mConfiguration;
char currentLocale[MAX_SETTING_SIZE] = "";
// Boom... VS does not support "thread_local"... and cannot use "__declspec(thread)" in a DLL... https://blogs.msdn.microsoft.com/oldnewthing/20101122-00/?p=12233
// Simulating Thread Local Storage with a map...
std::map<DWORD, TranslatedStringStorage>* TLS_TranslatedStringMap; //key = Thread Id, value = Translate Buffer
static bool isValidLocale(const QString & locale)
{
auto allLocales = QLocale::matchingLocales(QLocale::AnyLanguage, QLocale::AnyScript, QLocale::AnyCountry);
for(auto & l : allLocales)
if(l.name() == locale || l.name().replace(QRegExp("_.+"), "") == locale)
return true;
return false;
}
// This function doesn't appear to have any effect when Qt DPI scaling is enabled.
// When scaling is disabled it drastically improves the results though.
static void setDpiUnaware()
{
// https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-setprocessdpiawarenesscontext
typedef unsigned int(WINAPI * pfnSetProcessDpiAwarenessContext)(size_t value);
static pfnSetProcessDpiAwarenessContext pSetProcessDpiAwarenessContext =
(pfnSetProcessDpiAwarenessContext)GetProcAddress(GetModuleHandleW(L"user32.dll"), "SetProcessDpiAwarenessContext");
if(pSetProcessDpiAwarenessContext)
{
// It's unclear if there is any benefit to the GDI scaling, but it should work the best in theory.
pSetProcessDpiAwarenessContext(/* DPI_AWARENESS_CONTEXT_UNAWARE_GDISCALED */ -5);
if(GetLastError() == ERROR_INVALID_PARAMETER)
{
// Fall back to unaware if the option doesn't exist.
pSetProcessDpiAwarenessContext(/* DPI_AWARENESS_CONTEXT_UNAWARE */ -1);
}
}
}
/*
Some resources:
- https://www.programmersought.com/article/89186999411/
- https://github.com/COVESA/dlt-viewer/issues/205
- https://vicrucann.github.io/tutorials/osg-qt-high-dpi/
- https://forum.freecadweb.org/viewtopic.php?t=52307
- https://wiki.freecadweb.org/HiDPI_support
- https://doc.qt.io/qt-5/highdpi.html#high-dpi-support-in-qt
*/
static void handleHighDpiScaling()
{
// If the user messes with the Qt environment variables, do not set anything
if(qEnvironmentVariableIsSet("QT_DEVICE_PIXEL_RATIO") // legacy in 5.6, but still functional
|| qEnvironmentVariableIsSet("QT_AUTO_SCREEN_SCALE_FACTOR")
|| qEnvironmentVariableIsSet("QT_SCALE_FACTOR")
|| qEnvironmentVariableIsSet("QT_SCREEN_SCALE_FACTORS")
|| qEnvironmentVariableIsSet("QT_ENABLE_HIGHDPI_SCALING")
|| qEnvironmentVariableIsSet("QT_SCALE_FACTOR_ROUNDING_POLICY"))
{
qDebug() << "Detected environment variables related to Qt scaling, skipping High DPI handling";
return;
}
duint enableQtHighDpiScaling = true;
BridgeSettingGetUint("Gui", "EnableQtHighDpiScaling", &enableQtHighDpiScaling);
if(enableQtHighDpiScaling)
{
QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
}
else
{
// This enables Windows scaling the application automatically
setDpiUnaware();
// These options don't seem to do anything, but the Qt documentation recommends it
putenv("QT_AUTO_SCREEN_SCALE_FACTOR=1");
QCoreApplication::setAttribute(Qt::AA_DisableHighDpiScaling);
}
}
int main(int argc, char* argv[])
{
handleHighDpiScaling();
MyApplication application(argc, argv);
#if QT_VERSION < QT_VERSION_CHECK(5,0,0)
QAbstractEventDispatcher::instance(application.thread())->setEventFilter(MyApplication::globalEventFilter);
#else
auto eventFilter = new MyEventFilter();
application.installNativeEventFilter(eventFilter);
#endif
// Get the language setting
if(!BridgeSettingGet("Engine", "Language", currentLocale) || !isValidLocale(currentLocale))
{
QStringList uiLanguages = QLocale::system().uiLanguages();
QString sysLocale = uiLanguages.size() ? QLocale(uiLanguages[0]).name() : QLocale::system().name();
strcpy_s(currentLocale, sysLocale.toUtf8().constData());
BridgeSettingSet("Engine", "Language", currentLocale);
}
// Load translations for Qt
QTranslator qtTranslator;
if(qtTranslator.load(QString("qt_%1").arg(currentLocale), QLibraryInfo::location(QLibraryInfo::TranslationsPath)))
application.installTranslator(&qtTranslator);
//x64dbg and x32dbg can share the same translation
QTranslator x64dbgTranslator;
auto path = QString("%1/../translations").arg(QCoreApplication::applicationDirPath());
if(x64dbgTranslator.load(QString("x64dbg_%1").arg(currentLocale), path))
application.installTranslator(&x64dbgTranslator);
TLS_TranslatedStringMap = new std::map<DWORD, TranslatedStringStorage>();
// initialize Zydis
Zydis::GlobalInitialize();
// load config file + set config font
mConfiguration = new Configuration;
application.setFont(ConfigFont("Application"));
// Set configured link color
QPalette appPalette = application.palette();
appPalette.setColor(QPalette::Link, ConfigColor("LinkColor"));
application.setPalette(appPalette);
// Register a path prefix for the program main directory
QDir::addSearchPath("approot", QApplication::applicationDirPath() + "/..");
// Load the selected theme
MainWindow::loadSelectedTheme(true);
// Register custom data types
qRegisterMetaType<dsint>("dsint");
qRegisterMetaType<duint>("duint");
qRegisterMetaType<byte_t>("byte_t");
qRegisterMetaType<DBGSTATE>("DBGSTATE");
// Set QString codec to UTF-8
QTextCodec::setCodecForLocale(QTextCodec::codecForName("UTF-8"));
#if QT_VERSION < QT_VERSION_CHECK(5,0,0)
QTextCodec::setCodecForCStrings(QTextCodec::codecForName("UTF-8"));
QTextCodec::setCodecForTr(QTextCodec::codecForName("UTF-8"));
#endif
// Init communication with debugger
Bridge::initBridge();
// Start GUI
MainWindow* mainWindow;
mainWindow = new MainWindow();
mainWindow->show();
// Set some data
Bridge::getBridge()->winId = (void*)mainWindow->winId();
// Init debugger
const char* errormsg = DbgInit();
if(errormsg)
{
QMessageBox msg(QMessageBox::Critical, QObject::tr("DbgInit Error!"), QString(errormsg));
msg.setWindowIcon(DIcon("compile-error"));
msg.setWindowFlags(msg.windowFlags() & (~Qt::WindowContextHelpButtonHint));
msg.exec();
exit(1);
}
//execute the application
int result = application.exec();
#if QT_VERSION >= QT_VERSION_CHECK(5,0,0)
application.removeNativeEventFilter(eventFilter);
#else
QAbstractEventDispatcher::instance(application.thread())->setEventFilter(nullptr);
#endif
delete mainWindow;
mConfiguration->save(); //save config on exit
{
//delete tls
auto temp = TLS_TranslatedStringMap;
TLS_TranslatedStringMap = nullptr;
delete temp;
}
//TODO free Zydis/config/bridge and prevent use after free.
return result;
} |
C/C++ | x64dbg-development/src/gui/Src/main.h | #pragma once
#include <QApplication>
#include <QAbstractEventDispatcher>
#include <QMessageBox>
#include "Bridge.h"
#if QT_VERSION >= QT_VERSION_CHECK(5,0,0)
#include <QAbstractNativeEventFilter>
#endif
class MyApplication : public QApplication
{
Q_OBJECT
public:
MyApplication(int & argc, char** argv);
bool notify(QObject* receiver, QEvent* event) Q_DECL_OVERRIDE;
#if QT_VERSION < QT_VERSION_CHECK(5,0,0)
bool winEventFilter(MSG* message, long* result) Q_DECL_OVERRIDE;
static bool globalEventFilter(void* message);
#endif
};
int main(int argc, char* argv[]);
extern char currentLocale[MAX_SETTING_SIZE];
struct TranslatedStringStorage
{
char Data[4096];
};
extern std::map<DWORD, TranslatedStringStorage>* TLS_TranslatedStringMap;
#if QT_VERSION >= QT_VERSION_CHECK(5,0,0)
class MyEventFilter : public QAbstractNativeEventFilter
{
public:
virtual bool nativeEventFilter(const QByteArray & eventType, void* message, long* result) Q_DECL_OVERRIDE
{
if(eventType == "windows_dispatcher_MSG")
return DbgWinEventGlobal((MSG*)message);
else if(eventType == "windows_generic_MSG")
return DbgWinEvent((MSG*)message, result);
return false;
}
};
#endif // QT_VERSION |
C/C++ | x64dbg-development/src/gui/Src/BasicView/AbstractSearchList.h | #pragma once
#include "AbstractStdTable.h"
class AbstractSearchList
{
public:
enum FilterType
{
FilterStartsWithTextCaseSensitive, //unused
FilterStartsWithTextCaseInsensitive, //unused
FilterContainsTextCaseSensitive, //unused
FilterContainsTextCaseInsensitive,
FilterRegexCaseSensitive,
FilterRegexCaseInsensitive
};
virtual void lock() = 0;
virtual void unlock() = 0;
virtual AbstractStdTable* list() const = 0;
virtual AbstractStdTable* searchList() const = 0;
virtual void filter(const QString & filter, FilterType type, int startColumn) = 0;
bool rowMatchesFilter(const QString & filter, FilterType type, int row, int startColumn) const
{
int count = list()->getColumnCount();
if(startColumn + 1 > count)
return false;
auto cs = Qt::CaseInsensitive;
switch(type)
{
case FilterStartsWithTextCaseSensitive:
cs = Qt::CaseSensitive;
case FilterStartsWithTextCaseInsensitive:
for(int i = startColumn; i < count; i++)
if(list()->getCellContent(row, i).startsWith(filter, cs))
return true;
break;
case FilterContainsTextCaseSensitive:
cs = Qt::CaseSensitive;
case FilterContainsTextCaseInsensitive:
for(int i = startColumn; i < count; i++)
if(list()->getCellContent(row, i).contains(filter, cs))
return true;
break;
case FilterRegexCaseSensitive:
cs = Qt::CaseSensitive;
case FilterRegexCaseInsensitive:
for(int i = startColumn; i < count; i++)
if(list()->getCellContent(row, i).contains(QRegExp(filter, cs)))
return true;
break;
default:
__debugbreak();
}
return false;
}
}; |
C++ | x64dbg-development/src/gui/Src/BasicView/AbstractStdTable.cpp | #include "AbstractStdTable.h"
#include "Bridge.h"
#include "RichTextPainter.h"
AbstractStdTable::AbstractStdTable(QWidget* parent) : AbstractTableView(parent)
{
setContextMenuPolicy(Qt::CustomContextMenu);
connect(Bridge::getBridge(), SIGNAL(repaintTableView()), this, SLOT(reloadData()));
connect(this, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(contextMenuRequestedSlot(QPoint)));
connect(this, SIGNAL(headerButtonPressed(int)), this, SLOT(headerButtonPressedSlot(int)));
Initialize();
// Set up copy menu
mCopyLine = makeShortcutAction(DIcon("copy_table_line"), tr("&Line"), SLOT(copyLineSlot()), "ActionCopy");
mCopyTable = makeShortcutAction(DIcon("copy_cropped_table"), tr("Cropped &Table"), SLOT(copyTableSlot()), "ActionCopyCroppedTable");
mCopyTableResize = makeShortcutAction(DIcon("copy_full_table"), tr("&Full Table"), SLOT(copyTableResizeSlot()), "ActionCopyTable");
mCopyLineToLog = makeShortcutAction(DIcon("copy_table_line"), tr("Line, To Log"), SLOT(copyLineToLogSlot()), "ActionCopyLineToLog");
mCopyTableToLog = makeShortcutAction(DIcon("copy_cropped_table"), tr("Cropped Table, To Log"), SLOT(copyTableToLogSlot()), "ActionCopyCroppedTableToLog");
mCopyTableResizeToLog = makeShortcutAction(DIcon("copy_full_table"), tr("Full Table, To Log"), SLOT(copyTableResizeToLogSlot()), "ActionCopyTableToLog");
mExportTableCSV = makeShortcutAction(DIcon("database-export"), tr("&Export Table"), SLOT(exportTableSlot()), "ActionExport");
}
QString AbstractStdTable::paintContent(QPainter* painter, dsint rowBase, int rowOffset, int col, int x, int y, int w, int h)
{
bool isaddr = DbgIsDebugging() && getRowCount() > 0 && col == mAddressColumn;
bool wIsSelected = isSelected(rowBase, rowOffset);
QString text = getCellContent(rowBase + rowOffset, col);
duint wVA = isaddr ? duint(text.toULongLong(&isaddr, 16)) : 0;
auto wIsTraced = isaddr && DbgFunctions()->GetTraceRecordHitCount(wVA) != 0;
QColor lineBackgroundColor;
bool isBackgroundColorSet;
if(wIsSelected && wIsTraced)
{
lineBackgroundColor = mTracedSelectedAddressBackgroundColor;
isBackgroundColorSet = true;
}
else if(wIsSelected)
{
lineBackgroundColor = mSelectionColor;
isBackgroundColorSet = true;
}
else if(wIsTraced)
{
lineBackgroundColor = mTracedBackgroundColor;
isBackgroundColorSet = true;
}
else
{
isBackgroundColorSet = false;
}
if(isBackgroundColorSet)
painter->fillRect(QRect(x, y, w, h), QBrush(lineBackgroundColor));
if(col == mAddressColumn && isaddr)
{
char label[MAX_LABEL_SIZE] = "";
if(bAddressLabel && DbgGetLabelAt(wVA, SEG_DEFAULT, label)) //has label
{
char module[MAX_MODULE_SIZE] = "";
if(DbgGetModuleAt(wVA, module) && !QString(label).startsWith("JMP.&"))
text += " <" + QString(module) + "." + QString(label) + ">";
else
text += " <" + QString(label) + ">";
}
BPXTYPE bpxtype = DbgGetBpxTypeAt(wVA);
bool isbookmark = DbgGetBookmarkAt(wVA);
duint cip = Bridge::getBridge()->mLastCip;
if(bCipBase)
{
duint base = DbgFunctions()->ModBaseFromAddr(cip);
if(base)
cip = base;
}
if(DbgIsDebugging() && wVA == cip) //debugging + cip
{
painter->fillRect(QRect(x, y, w, h), QBrush(mCipBackgroundColor));
if(!isbookmark) //no bookmark
{
if(bpxtype & bp_normal) //normal breakpoint
{
QColor & bpColor = mBreakpointBackgroundColor;
if(!bpColor.alpha()) //we don't want transparent text
bpColor = mBreakpointColor;
if(bpColor == mCipBackgroundColor)
bpColor = mCipColor;
painter->setPen(bpColor);
}
else if(bpxtype & bp_hardware) //hardware breakpoint only
{
QColor hwbpColor = mHardwareBreakpointBackgroundColor;
if(!hwbpColor.alpha()) //we don't want transparent text
hwbpColor = mHardwareBreakpointColor;
if(hwbpColor == mCipBackgroundColor)
hwbpColor = mCipColor;
painter->setPen(hwbpColor);
}
else //no breakpoint
{
painter->setPen(mCipColor);
}
}
else //bookmark
{
QColor bookmarkColor = mBookmarkBackgroundColor;
if(!bookmarkColor.alpha()) //we don't want transparent text
bookmarkColor = mBookmarkColor;
if(bookmarkColor == mCipBackgroundColor)
bookmarkColor = mCipColor;
painter->setPen(bookmarkColor);
}
}
else //non-cip address
{
if(!isbookmark) //no bookmark
{
if(*label) //label
{
if(bpxtype == bp_none) //label only : fill label background
{
painter->setPen(mLabelColor); //red -> address + label text
painter->fillRect(QRect(x, y, w, h), QBrush(mLabelBackgroundColor)); //fill label background
}
else //label + breakpoint
{
if(bpxtype & bp_normal) //label + normal breakpoint
{
painter->setPen(mBreakpointColor);
painter->fillRect(QRect(x, y, w, h), QBrush(mBreakpointBackgroundColor)); //fill red
}
else if(bpxtype & bp_hardware) //label + hardware breakpoint only
{
painter->setPen(mHardwareBreakpointColor);
painter->fillRect(QRect(x, y, w, h), QBrush(mHardwareBreakpointBackgroundColor)); //fill ?
}
else //other cases -> do as normal
{
painter->setPen(mLabelColor); //red -> address + label text
painter->fillRect(QRect(x, y, w, h), QBrush(mLabelBackgroundColor)); //fill label background
}
}
}
else //no label
{
if(bpxtype == bp_none) //no label, no breakpoint
{
QColor background;
if(wIsSelected)
{
background = mSelectedAddressBackgroundColor;
painter->setPen(mSelectedAddressColor); //black address (DisassemblySelectedAddressColor)
}
else
{
background = mAddressBackgroundColor;
painter->setPen(mAddressColor); //DisassemblyAddressColor
}
if(background.alpha())
painter->fillRect(QRect(x, y, w, h), QBrush(background)); //fill background
}
else //breakpoint only
{
if(bpxtype & bp_normal) //normal breakpoint
{
painter->setPen(mBreakpointColor);
painter->fillRect(QRect(x, y, w, h), QBrush(mBreakpointBackgroundColor)); //fill red
}
else if(bpxtype & bp_hardware) //hardware breakpoint only
{
painter->setPen(mHardwareBreakpointColor);
painter->fillRect(QRect(x, y, w, h), QBrush(mHardwareBreakpointBackgroundColor)); //fill red
}
else //other cases (memory breakpoint in disassembly) -> do as normal
{
QColor background;
if(wIsSelected)
{
background = mSelectedAddressBackgroundColor;
painter->setPen(mSelectedAddressColor); //black address (DisassemblySelectedAddressColor)
}
else
{
background = mAddressBackgroundColor;
painter->setPen(mAddressColor);
}
if(background.alpha())
painter->fillRect(QRect(x, y, w, h), QBrush(background)); //fill background
}
}
}
}
else //bookmark
{
if(*label) //label + bookmark
{
if(bpxtype == bp_none) //label + bookmark
{
painter->setPen(mLabelColor); //red -> address + label text
painter->fillRect(QRect(x, y, w, h), QBrush(mBookmarkBackgroundColor)); //fill label background
}
else //label + breakpoint + bookmark
{
QColor color = mBookmarkBackgroundColor;
if(!color.alpha()) //we don't want transparent text
color = mAddressColor;
painter->setPen(color);
if(bpxtype & bp_normal) //label + bookmark + normal breakpoint
{
painter->fillRect(QRect(x, y, w, h), QBrush(mBreakpointBackgroundColor)); //fill red
}
else if(bpxtype & bp_hardware) //label + bookmark + hardware breakpoint only
{
painter->fillRect(QRect(x, y, w, h), QBrush(mHardwareBreakpointBackgroundColor)); //fill ?
}
}
}
else //bookmark, no label
{
if(bpxtype == bp_none) //bookmark only
{
painter->setPen(mBookmarkColor); //black address
painter->fillRect(QRect(x, y, w, h), QBrush(mBookmarkBackgroundColor)); //fill bookmark color
}
else //bookmark + breakpoint
{
QColor color = mBookmarkBackgroundColor;
if(!color.alpha()) //we don't want transparent text
color = mAddressColor;
painter->setPen(color);
if(bpxtype & bp_normal) //bookmark + normal breakpoint
{
painter->fillRect(QRect(x, y, w, h), QBrush(mBreakpointBackgroundColor)); //fill red
}
else if(bpxtype & bp_hardware) //bookmark + hardware breakpoint only
{
painter->fillRect(QRect(x, y, w, h), QBrush(mHardwareBreakpointBackgroundColor)); //fill red
}
else //other cases (bookmark + memory breakpoint in disassembly) -> do as normal
{
painter->setPen(mBookmarkColor); //black address
painter->fillRect(QRect(x, y, w, h), QBrush(mBookmarkBackgroundColor)); //fill bookmark color
}
}
}
}
}
painter->drawText(QRect(x + 4, y, w - 4, h), Qt::AlignVCenter | Qt::AlignLeft, text);
text.clear();
}
else if(mHighlightText.length() && col >= mMinimumHighlightColumn && text.contains(mHighlightText, Qt::CaseInsensitive)) // TODO: case sensitive + regex highlighting
{
//super smart way of splitting while keeping the delimiters (thanks to cypher for guidance)
int index = -2;
do
{
index = text.indexOf(mHighlightText, index + 2, Qt::CaseInsensitive);
if(index != -1)
{
text = text.insert(index + mHighlightText.length(), QChar('\1'));
text = text.insert(index, QChar('\1'));
}
}
while(index != -1);
QStringList split = text.split(QChar('\1'), QString::SkipEmptyParts, Qt::CaseInsensitive);
//create rich text list
RichTextPainter::CustomRichText_t curRichText;
curRichText.flags = RichTextPainter::FlagColor;
QColor textColor = getCellColor(rowBase + rowOffset, col);
QColor textBackgroundColor = Qt::transparent;
QColor highlightColor = ConfigColor("SearchListViewHighlightColor");
QColor highlightBackgroundColor = ConfigColor("SearchListViewHighlightBackgroundColor");
curRichText.textColor = textColor;
curRichText.underline = false;
RichTextPainter::List richText;
foreach(QString str, split)
{
curRichText.text = str;
if(!str.compare(mHighlightText, Qt::CaseInsensitive))
{
curRichText.textColor = highlightColor;
curRichText.textBackground = highlightBackgroundColor;
}
else
{
curRichText.textColor = textColor;
curRichText.textBackground = textBackgroundColor;
}
richText.push_back(curRichText);
}
//paint the rich text
RichTextPainter::paintRichText(painter, x + 1, y, w, h, 4, richText, mFontMetrics);
text.clear();
}
return text;
}
void AbstractStdTable::updateColors()
{
AbstractTableView::updateColors();
mCipBackgroundColor = ConfigColor("DisassemblyCipBackgroundColor");
mCipColor = ConfigColor("DisassemblyCipColor");
mBreakpointBackgroundColor = ConfigColor("DisassemblyBreakpointBackgroundColor");
mBreakpointColor = ConfigColor("DisassemblyBreakpointColor");
mHardwareBreakpointBackgroundColor = ConfigColor("DisassemblyHardwareBreakpointBackgroundColor");
mHardwareBreakpointColor = ConfigColor("DisassemblyHardwareBreakpointColor");
mBookmarkBackgroundColor = ConfigColor("DisassemblyBookmarkBackgroundColor");
mBookmarkColor = ConfigColor("DisassemblyBookmarkColor");
mLabelColor = ConfigColor("DisassemblyLabelColor");
mLabelBackgroundColor = ConfigColor("DisassemblyLabelBackgroundColor");
mSelectedAddressBackgroundColor = ConfigColor("DisassemblySelectedAddressBackgroundColor");
mSelectedAddressColor = ConfigColor("DisassemblySelectedAddressColor");
mAddressBackgroundColor = ConfigColor("DisassemblyAddressBackgroundColor");
mAddressColor = ConfigColor("DisassemblyAddressColor");
mTracedBackgroundColor = ConfigColor("DisassemblyTracedBackgroundColor");
auto a = mSelectionColor, b = mTracedBackgroundColor;
mTracedSelectedAddressBackgroundColor = QColor((a.red() + b.red()) / 2, (a.green() + b.green()) / 2, (a.blue() + b.blue()) / 2);
}
void AbstractStdTable::mouseMoveEvent(QMouseEvent* event)
{
bool wAccept = true;
int y = transY(event->y());
if(mGuiState == AbstractStdTable::MultiRowsSelectionState)
{
//qDebug() << "State = MultiRowsSelectionState";
if(y >= 0 && y <= this->getTableHeight())
{
int wRowIndex = getTableOffset() + getIndexOffsetFromY(y);
if(wRowIndex < getRowCount())
{
if(mIsMultiSelectionAllowed)
expandSelectionUpTo(wRowIndex);
else
setSingleSelection(wRowIndex);
updateViewport();
wAccept = false;
}
}
else if(y < 0)
{
verticalScrollBar()->triggerAction(QAbstractSlider::SliderSingleStepSub);
}
else if(y > getTableHeight())
{
verticalScrollBar()->triggerAction(QAbstractSlider::SliderSingleStepAdd);
}
}
if(wAccept)
AbstractTableView::mouseMoveEvent(event);
}
void AbstractStdTable::mousePressEvent(QMouseEvent* event)
{
bool wAccept = false;
if(((event->buttons() & Qt::LeftButton) != 0) && ((event->buttons() & Qt::RightButton) == 0))
{
if(getGuiState() == AbstractTableView::NoState)
{
if(event->y() > getHeaderHeight())
{
int wRowIndex = getTableOffset() + getIndexOffsetFromY(transY(event->y()));
if(wRowIndex < getRowCount())
{
if(mIsMultiSelectionAllowed && (event->modifiers() & Qt::ShiftModifier))
expandSelectionUpTo(wRowIndex);
else
setSingleSelection(wRowIndex);
mGuiState = AbstractStdTable::MultiRowsSelectionState;
updateViewport();
wAccept = true;
}
}
}
}
if(!wAccept)
AbstractTableView::mousePressEvent(event);
}
void AbstractStdTable::mouseDoubleClickEvent(QMouseEvent* event)
{
if(event->y() > getHeaderHeight() && event->button() == Qt::LeftButton)
emit doubleClickedSignal();
AbstractTableView::mouseDoubleClickEvent(event);
}
void AbstractStdTable::mouseReleaseEvent(QMouseEvent* event)
{
bool wAccept = true;
if((event->buttons() & Qt::LeftButton) == 0)
{
if(mGuiState == AbstractStdTable::MultiRowsSelectionState)
{
mGuiState = AbstractStdTable::NoState;
updateViewport();
wAccept = false;
}
}
if(wAccept)
AbstractTableView::mouseReleaseEvent(event);
}
void AbstractStdTable::keyPressEvent(QKeyEvent* event)
{
emit keyPressedSignal(event);
int key = event->key();
Qt::KeyboardModifiers modifiers = event->modifiers();
if(key == Qt::Key_Up ||
key == Qt::Key_Down ||
key == Qt::Key_Home ||
key == Qt::Key_End ||
key == Qt::Key_A)
{
dsint wBotIndex = getTableOffset();
dsint wTopIndex = wBotIndex + getNbrOfLineToPrint() - 1;
switch(key)
{
case Qt::Key_Up:
if(mIsMultiSelectionAllowed && modifiers == Qt::ShiftModifier) //Shift+Up -> expand selection upwards
{
expandUp();
}
else //Up -> select previous
{
selectPrevious();
}
break;
case Qt::Key_Down:
if(mIsMultiSelectionAllowed && modifiers == Qt::ShiftModifier) //Shift+Down -> expand selection downwards
{
expandDown();
}
else //Down -> select next
{
selectNext();
}
break;
case Qt::Key_Home:
if(mIsMultiSelectionAllowed && modifiers == Qt::ShiftModifier) //Shift+Home -> expand selection to top
{
expandTop();
}
else if(modifiers == Qt::NoModifier) //Home -> select first line
{
selectStart();
}
break;
case Qt::Key_End:
if(mIsMultiSelectionAllowed && modifiers == Qt::ShiftModifier) //Shift+End -> expand selection to bottom
{
expandBottom();
}
else if(modifiers == Qt::NoModifier) //End -> select last line
{
selectEnd();
}
break;
case Qt::Key_A:
if(mIsMultiSelectionAllowed && modifiers == Qt::ControlModifier) //Ctrl+A -> select all
{
selectAll();
}
break;
}
if(getInitialSelection() < wBotIndex)
{
setTableOffset(getInitialSelection());
}
else if(getInitialSelection() >= wTopIndex)
{
setTableOffset(getInitialSelection() - getNbrOfLineToPrint() + 2);
}
updateViewport();
}
else
{
AbstractTableView::keyPressEvent(event);
}
}
void AbstractStdTable::enableMultiSelection(bool enabled)
{
mIsMultiSelectionAllowed = enabled;
}
void AbstractStdTable::enableColumnSorting(bool enabled)
{
mIsColumnSortingAllowed = enabled;
}
/************************************************************************************
Selection Management
************************************************************************************/
void AbstractStdTable::expandSelectionUpTo(int to)
{
if(to < mSelection.firstSelectedIndex)
{
mSelection.fromIndex = to;
mSelection.toIndex = mSelection.firstSelectedIndex;
emit selectionChangedSignal(to);
}
else if(to > mSelection.firstSelectedIndex)
{
mSelection.fromIndex = mSelection.firstSelectedIndex;
mSelection.toIndex = to;
emit selectionChangedSignal(to);
}
else if(to == mSelection.firstSelectedIndex)
{
setSingleSelection(to);
}
}
void AbstractStdTable::expandUp()
{
int wRowIndex = mSelection.firstSelectedIndex - 1;
if(wRowIndex >= 0)
{
if(wRowIndex < mSelection.fromIndex)
{
mSelection.fromIndex = wRowIndex;
mSelection.firstSelectedIndex = wRowIndex;
}
else
{
mSelection.firstSelectedIndex = wRowIndex;
mSelection.toIndex = wRowIndex;
}
emit selectionChangedSignal(wRowIndex);
}
}
void AbstractStdTable::expandDown()
{
int wRowIndex = mSelection.firstSelectedIndex + 1;
int endIndex = getRowCount() - 1;
if(wRowIndex <= endIndex)
{
if(wRowIndex > mSelection.toIndex)
{
mSelection.firstSelectedIndex = wRowIndex;
mSelection.toIndex = wRowIndex;
}
else
{
mSelection.fromIndex = wRowIndex;
mSelection.firstSelectedIndex = wRowIndex;
}
emit selectionChangedSignal(wRowIndex);
}
}
void AbstractStdTable::expandTop()
{
if(getRowCount() > 0)
{
expandSelectionUpTo(0);
}
}
void AbstractStdTable::expandBottom()
{
int endIndex = getRowCount() - 1;
if(endIndex >= 0)
{
expandSelectionUpTo(endIndex);
}
}
void AbstractStdTable::setSingleSelection(int index)
{
mSelection.firstSelectedIndex = index;
mSelection.fromIndex = index;
mSelection.toIndex = index;
emit selectionChangedSignal(index);
}
int AbstractStdTable::getInitialSelection() const
{
return mSelection.firstSelectedIndex;
}
QList<int> AbstractStdTable::getSelection() const
{
QList<int> selection;
selection.reserve(mSelection.toIndex - mSelection.fromIndex);
for(int i = mSelection.fromIndex; i <= mSelection.toIndex; i++)
{
selection.append(i);
}
return selection;
}
void AbstractStdTable::selectStart()
{
if(getRowCount() > 0)
{
setSingleSelection(0);
}
}
void AbstractStdTable::selectEnd()
{
int endIndex = getRowCount() - 1;
if(endIndex >= 0)
{
setSingleSelection(endIndex);
}
}
void AbstractStdTable::selectNext()
{
int wNext = getInitialSelection() + 1;
// Bounding
wNext = wNext > getRowCount() - 1 ? getRowCount() - 1 : wNext;
wNext = wNext < 0 ? 0 : wNext;
setSingleSelection(wNext);
}
void AbstractStdTable::selectPrevious()
{
int wNext = getInitialSelection() - 1;
// Bounding
wNext = wNext > getRowCount() - 1 ? getRowCount() - 1 : wNext;
wNext = wNext < 0 ? 0 : wNext;
setSingleSelection(wNext);
}
void AbstractStdTable::selectAll()
{
int index = 0;
int indexEnd = getRowCount() - 1;
mSelection.firstSelectedIndex = index;
mSelection.fromIndex = index;
mSelection.toIndex = indexEnd;
emit selectionChangedSignal(index);
}
bool AbstractStdTable::isSelected(int base, int offset) const
{
int wIndex = base + offset;
if(wIndex >= mSelection.fromIndex && wIndex <= mSelection.toIndex)
return true;
else
return false;
}
bool AbstractStdTable::scrollSelect(int offset)
{
if(!isValidIndex(offset, 0))
return false;
int rangefrom = getTableOffset();
int rangeto = rangefrom + getViewableRowsCount() - 1;
if(offset < rangefrom) //offset lays before the current view
setTableOffset(offset);
else if(offset > (rangeto - 1)) //offset lays after the current view
setTableOffset(offset - getViewableRowsCount() + 2);
setSingleSelection(offset);
return true;
}
/************************************************************************************
Data Management
************************************************************************************/
void AbstractStdTable::addColumnAt(int width, QString title, bool isClickable, QString copyTitle)
{
AbstractTableView::addColumnAt(width, title, isClickable);
//Append copy title
if(!copyTitle.length())
mCopyTitles.push_back(title);
else
mCopyTitles.push_back(copyTitle);
}
void AbstractStdTable::deleteAllColumns()
{
setRowCount(0);
AbstractTableView::deleteAllColumns();
mCopyTitles.clear();
}
void AbstractStdTable::copyLineSlot()
{
int colCount = getColumnCount();
QString finalText = "";
if(colCount == 1)
finalText = getCellContent(getInitialSelection(), 0);
else
{
for(int selected : getSelection())
{
for(int i = 0; i < colCount; i++)
{
QString cellContent = getCellContent(selected, i);
if(!cellContent.length()) //skip empty cells
continue;
QString title = mCopyTitles.at(i);
if(title.length())
finalText += title + "=";
finalText += cellContent.trimmed();;
finalText += "\r\n";
}
}
}
Bridge::CopyToClipboard(finalText);
}
void AbstractStdTable::copyLineToLogSlot()
{
int colCount = getColumnCount();
int selected = getInitialSelection();
QString finalText = "";
if(colCount == 1)
finalText = getCellContent(selected, 0);
else
{
for(int i = 0; i < colCount; i++)
{
QString cellContent = getCellContent(selected, i);
if(!cellContent.length()) //skip empty cells
continue;
QString title = mCopyTitles.at(i);
if(title.length())
finalText += title + "=";
finalText += cellContent.trimmed();;
finalText += "\r\n";
}
}
emit Bridge::getBridge()->addMsgToLog(finalText.toUtf8());
}
QString AbstractStdTable::copyTable(const std::vector<int> & colWidths)
{
int colCount = getColumnCount();
int rowCount = getRowCount();
QString finalText = "";
if(colCount == 1)
{
for(int i = 0; i < rowCount; i++)
{
QString cellContent = getCellContent(i, 0);
if(!cellContent.length()) //skip empty cells
continue;
finalText += cellContent + "\r\n";
}
}
else
{
//std::vector<int> colWidths;
//for(int i = 0; i < colCount; i++)
// colWidths.push_back(getMaxColumnLength(i));
for(int i = 0; i < colCount; i++)
{
if(i)
finalText += " ";
int colWidth = colWidths[i];
if(colWidth)
finalText += getColTitle(i).leftJustified(colWidth, QChar(' '), true);
else
finalText += getColTitle(i);
}
finalText += "\r\n";
for(int i = 0; i < rowCount; i++)
{
QString finalRowText = "";
for(int j = 0; j < colCount; j++)
{
if(j)
finalRowText += " ";
QString cellContent = getCellContent(i, j);
int colWidth = colWidths[j];
if(colWidth && j != colCount - 1)
finalRowText += cellContent.leftJustified(colWidth, QChar(' '), true);
else
finalRowText += cellContent;
}
finalText += finalRowText + "\r\n";
}
}
return finalText;
}
void AbstractStdTable::copyTableSlot()
{
std::vector<int> colWidths;
int colCount = getColumnCount();
for(int i = 0; i < colCount; i++)
colWidths.push_back(getColumnWidth(i) / getCharWidth());
Bridge::CopyToClipboard(copyTable(colWidths));
}
void AbstractStdTable::copyTableToLogSlot()
{
std::vector<int> colWidths;
int colCount = getColumnCount();
for(int i = 0; i < colCount; i++)
colWidths.push_back(getColumnWidth(i) / getCharWidth());
emit Bridge::getBridge()->addMsgToLog(copyTable(colWidths).toUtf8());
}
void AbstractStdTable::copyTableResizeSlot()
{
std::vector<int> colWidths;
int rowCount = getRowCount();
int colCount = getColumnCount();
for(int i = 0; i < colCount; i++)
{
int max = getCellContent(0, i).length();
for(int j = 1; j < rowCount; j++)
max = std::max(getCellContent(j, i).length(), max);
colWidths.push_back(max);
}
Bridge::CopyToClipboard(copyTable(colWidths));
}
void AbstractStdTable::copyTableResizeToLogSlot()
{
std::vector<int> colWidths;
int rowCount = getRowCount();
int colCount = getColumnCount();
for(int i = 0; i < colCount; i++)
{
int max = getCellContent(0, i).length();
for(int j = 1; j < rowCount; j++)
max = std::max(getCellContent(j, i).length(), max);
colWidths.push_back(max);
}
emit Bridge::getBridge()->addMsgToLog(copyTable(colWidths).toUtf8());
}
void AbstractStdTable::copyEntrySlot()
{
QAction* action = qobject_cast<QAction*>(sender());
if(!action)
return;
int col = action->objectName().toInt();
QString finalText = getCellContent(getInitialSelection(), col);
while(finalText.endsWith(" ")) finalText.chop(1);
Bridge::CopyToClipboard(finalText);
}
void AbstractStdTable::exportTableSlot()
{
std::vector<QString> headers;
headers.reserve(getColumnCount());
for(int i = 0; i < getColumnCount(); i++)
headers.push_back(getColTitle(i));
ExportCSV(getRowCount(), getColumnCount(), headers, [this](duint row, duint column)
{
return getCellContent(row, column);
});
}
void AbstractStdTable::setupCopyMenu(QMenu* copyMenu)
{
if(!getColumnCount())
return;
copyMenu->setIcon(DIcon("copy"));
//Copy->Whole Line
copyMenu->addAction(mCopyLine);
//Copy->Cropped Table
copyMenu->addAction(mCopyTable);
//Copy->Full Table
copyMenu->addAction(mCopyTableResize);
//Copy->Separator
copyMenu->addSeparator();
//Copy->Whole Line To Log
copyMenu->addAction(mCopyLineToLog);
//Copy->Cropped Table To Log
copyMenu->addAction(mCopyTableToLog);
//Copy->Full Table To Log
copyMenu->addAction(mCopyTableResizeToLog);
//Copy->Export Table
copyMenu->addAction(mExportTableCSV);
//Copy->Separator
copyMenu->addSeparator();
//Copy->ColName
setupCopyColumnMenu(copyMenu);
}
void AbstractStdTable::setupCopyColumnMenu(QMenu* copyMenu)
{
for(int i = 0; i < getColumnCount(); i++)
{
if(!getCellContent(getInitialSelection(), i).length()) //skip empty cells
continue;
QString title = mCopyTitles.at(i);
if(!title.length()) //skip empty copy titles
continue;
QAction* mCopyAction = new QAction(DIcon("copy_item"), title, copyMenu);
mCopyAction->setObjectName(QString::number(i));
connect(mCopyAction, SIGNAL(triggered()), this, SLOT(copyEntrySlot()));
copyMenu->addAction(mCopyAction);
}
}
void AbstractStdTable::setupCopyMenu(MenuBuilder* copyMenu)
{
if(!getColumnCount())
return;
//Copy->Whole Line
copyMenu->addAction(mCopyLine);
//Copy->Cropped Table
copyMenu->addAction(mCopyTable);
//Copy->Full Table
copyMenu->addAction(mCopyTableResize);
//Copy->Separator
copyMenu->addSeparator();
//Copy->Whole Line To Log
copyMenu->addAction(mCopyLineToLog);
//Copy->Cropped Table
copyMenu->addAction(mCopyTableToLog);
//Copy->Full Table
copyMenu->addAction(mCopyTableResizeToLog);
//Copy->Export Table
copyMenu->addAction(mExportTableCSV);
//Copy->Separator
copyMenu->addSeparator();
//Copy->ColName
setupCopyColumnMenu(copyMenu);
}
void AbstractStdTable::setupCopyColumnMenu(MenuBuilder* copyMenu)
{
copyMenu->addBuilder(new MenuBuilder(this, [this](QMenu * menu)
{
for(int i = 0; i < getColumnCount(); i++)
{
if(!getCellContent(getInitialSelection(), i).length()) //skip empty cells
continue;
QString title = mCopyTitles.at(i);
if(!title.length()) //skip empty copy titles
continue;
QAction* action = new QAction(DIcon("copy_item"), title, menu);
action->setObjectName(QString::number(i));
connect(action, SIGNAL(triggered()), this, SLOT(copyEntrySlot()));
menu->addAction(action);
}
return true;
}));
}
void AbstractStdTable::setCopyMenuOnly(bool bSet, bool bDebugOnly)
{
mCopyMenuOnly = bSet;
mCopyMenuDebugOnly = bDebugOnly;
}
void AbstractStdTable::contextMenuRequestedSlot(const QPoint & pos)
{
if(!mCopyMenuOnly)
{
emit contextMenuSignal(pos);
return;
}
if(mCopyMenuDebugOnly && !DbgIsDebugging())
return;
QMenu wMenu(this);
QMenu wCopyMenu(tr("&Copy"), this);
setupCopyMenu(&wCopyMenu);
if(wCopyMenu.actions().length())
{
wMenu.addSeparator();
wMenu.addMenu(&wCopyMenu);
wMenu.exec(mapToGlobal(pos));
}
}
void AbstractStdTable::headerButtonPressedSlot(int col)
{
if(!mIsColumnSortingAllowed)
return;
if(mSort.column != col)
{
mSort.column = col;
mSort.ascending = true;
}
else
mSort.ascending = !mSort.ascending;
reloadData();
}
void AbstractStdTable::reloadData()
{
//TODO: do this on request, not every time reloadData is called...
if(mSort.column != -1) //re-sort if the user wants to sort
{
sortRows(mSort.column, mSort.ascending);
}
AbstractTableView::reloadData();
}
duint AbstractStdTable::getDisassemblyPopupAddress(int mousex, int mousey)
{
if(!bDisassemblyPopupEnabled) //No disassembly popup is meaningful for this table
return 0;
int c = getColumnIndexFromX(mousex);
int r = getTableOffset() + getIndexOffsetFromY(transY(mousey));
if(r < getRowCount())
{
QString cell = getCellContent(r, c);
duint addr;
bool ok = false;
#ifdef _WIN64
addr = cell.toULongLong(&ok, 16);
#else //x86
addr = cell.toULong(&ok, 16);
#endif //_WIN64
if(!ok)
return 0;
else
return addr;
}
else
return 0;
} |
C/C++ | x64dbg-development/src/gui/Src/BasicView/AbstractStdTable.h | #pragma once
#include "AbstractTableView.h"
class AbstractStdTable : public AbstractTableView
{
Q_OBJECT
public:
explicit AbstractStdTable(QWidget* parent = 0);
QString paintContent(QPainter* painter, dsint rowBase, int rowOffset, int col, int x, int y, int w, int h) override;
void updateColors() override;
void reloadData() override;
void mouseMoveEvent(QMouseEvent* event) override;
void mousePressEvent(QMouseEvent* event) override;
void mouseDoubleClickEvent(QMouseEvent* event) override;
void mouseReleaseEvent(QMouseEvent* event) override;
void keyPressEvent(QKeyEvent* event) override;
void enableMultiSelection(bool enabled);
void enableColumnSorting(bool enabled);
// Selection Management
void expandSelectionUpTo(int to);
void expandUp();
void expandDown();
void expandTop();
void expandBottom();
void setSingleSelection(int index);
int getInitialSelection() const;
QList<int> getSelection() const;
void selectStart();
void selectEnd();
void selectNext();
void selectPrevious();
void selectAll();
bool isSelected(int base, int offset) const;
bool scrollSelect(int offset);
// Data Management
void addColumnAt(int width, QString title, bool isClickable, QString copyTitle = "");
void deleteAllColumns() override;
virtual QString getCellContent(int r, int c) = 0;
virtual bool isValidIndex(int r, int c) = 0;
virtual void sortRows(int column, bool ascending) = 0;
duint getDisassemblyPopupAddress(int mousex, int mousey) override;
//context menu helpers
void setupCopyMenu(QMenu* copyMenu);
void setupCopyColumnMenu(QMenu* copyMenu);
void setupCopyMenu(MenuBuilder* copyMenu);
void setupCopyColumnMenu(MenuBuilder* copyMenu);
void setCopyMenuOnly(bool bSet, bool bDebugOnly = true);
//draw helpers
void setHighlightText(QString highlightText, int minCol = 0)
{
mHighlightText = highlightText;
mMinimumHighlightColumn = minCol;
}
void setAddressColumn(int col, bool cipBase = false)
{
mAddressColumn = col;
bCipBase = cipBase;
}
void setAddressLabel(bool addressLabel)
{
bAddressLabel = addressLabel;
}
bool setDisassemblyPopupEnabled(bool enabled)
{
return bDisassemblyPopupEnabled = enabled;
}
signals:
void selectionChangedSignal(int index);
void keyPressedSignal(QKeyEvent* event);
void doubleClickedSignal();
void contextMenuSignal(const QPoint & pos);
public slots:
void copyLineSlot();
void copyTableSlot();
void copyTableResizeSlot();
void copyLineToLogSlot();
void copyTableToLogSlot();
void copyTableResizeToLogSlot();
void copyEntrySlot();
void exportTableSlot();
void contextMenuRequestedSlot(const QPoint & pos);
void headerButtonPressedSlot(int col);
protected:
QString copyTable(const std::vector<int> & colWidths);
struct SelectionData
{
int firstSelectedIndex = 0;
int fromIndex = 0;
int toIndex = 0;
};
SelectionData mSelection;
enum
{
NoState,
MultiRowsSelectionState
} mGuiState = NoState;
bool mIsMultiSelectionAllowed = false;
bool mCopyMenuOnly = false;
bool mCopyMenuDebugOnly = true;
bool mIsColumnSortingAllowed = true;
std::vector<QString> mCopyTitles;
struct SortData
{
int column = -1;
bool ascending = true;
} mSort;
QColor mCipBackgroundColor;
QColor mCipColor;
QColor mBreakpointBackgroundColor;
QColor mBreakpointColor;
QColor mHardwareBreakpointBackgroundColor;
QColor mHardwareBreakpointColor;
QColor mBookmarkBackgroundColor;
QColor mBookmarkColor;
QColor mLabelColor;
QColor mLabelBackgroundColor;
QColor mSelectedAddressBackgroundColor;
QColor mSelectedAddressColor;
QColor mAddressBackgroundColor;
QColor mAddressColor;
QColor mTracedBackgroundColor;
QColor mTracedSelectedAddressBackgroundColor;
bool bCipBase = false;
QString mHighlightText;
int mMinimumHighlightColumn = 0;
int mAddressColumn = -1;
bool bAddressLabel = true;
bool bDisassemblyPopupEnabled = true;
QAction* mCopyLine;
QAction* mCopyTable;
QAction* mCopyTableResize;
QAction* mCopyLineToLog;
QAction* mCopyTableToLog;
QAction* mCopyTableResizeToLog;
QAction* mExportTableCSV;
}; |
C++ | x64dbg-development/src/gui/Src/BasicView/AbstractTableView.cpp | #include "AbstractTableView.h"
#include <QStyleOptionButton>
#include "Configuration.h"
#include "ColumnReorderDialog.h"
#include "CachedFontMetrics.h"
#include "Bridge.h"
#include "DisassemblyPopup.h"
#include "MethodInvoker.h"
int AbstractTableView::mMouseWheelScrollDelta = 0;
AbstractTableScrollBar::AbstractTableScrollBar(QScrollBar* scrollbar)
{
setOrientation(scrollbar->orientation());
setParent(scrollbar->parentWidget());
}
void AbstractTableScrollBar::enterEvent(QEvent* event)
{
Q_UNUSED(event);
QApplication::setOverrideCursor(Qt::ArrowCursor);
}
void AbstractTableScrollBar::leaveEvent(QEvent* event)
{
Q_UNUSED(event);
QApplication::restoreOverrideCursor();
}
AbstractTableView::AbstractTableView(QWidget* parent)
: QAbstractScrollArea(parent),
mFontMetrics(nullptr),
mDisassemblyPopup(nullptr)
{
// Class variable initialization
mTableOffset = 0;
mPrevTableOffset = mTableOffset + 1;
Header data;
data.isVisible = true;
data.height = 20;
data.activeButtonIndex = -1;
mHeader = data;
// Paint cell content only when debugger is running
setDrawDebugOnly(true);
mRowCount = 0;
mHeaderButtonSytle.setObjectName("AbstractTableViewHeader");
mNbrOfLineToPrint = 0;
memset(&mColResizeData, 0, sizeof(mColResizeData));
mGuiState = AbstractTableView::NoState;
mShouldReload = true;
mAllowPainting = true;
mDrawDebugOnly = false;
mPopupEnabled = true;
mPopupTimer = 0;
// ScrollBar Init
setVerticalScrollBar(new AbstractTableScrollBar(verticalScrollBar()));
setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
memset(&mScrollBarAttributes, 0, sizeof(mScrollBarAttributes));
horizontalScrollBar()->setRange(0, 0);
horizontalScrollBar()->setPageStep(650);
if(mMouseWheelScrollDelta == 0)
mMouseWheelScrollDelta = QApplication::wheelScrollLines();
setMouseTracking(true);
// Slots
connect(verticalScrollBar(), SIGNAL(actionTriggered(int)), this, SLOT(vertSliderActionSlot(int)));
connect(Config(), SIGNAL(colorsUpdated()), this, SLOT(updateColorsSlot()));
connect(Config(), SIGNAL(fontsUpdated()), this, SLOT(updateFontsSlot()));
connect(Config(), SIGNAL(shortcutsUpdated()), this, SLOT(updateShortcutsSlot()));
connect(Bridge::getBridge(), SIGNAL(shutdown()), this, SLOT(shutdownSlot()));
// todo: try Qt::QueuedConnection to init
Initialize();
}
void AbstractTableView::shutdownSlot()
{
if(ConfigBool("Gui", "SaveColumnOrder"))
saveColumnToConfig();
setAllowPainting(false);
}
/************************************************************************************
Configuration
************************************************************************************/
void AbstractTableView::Initialize()
{
// Required to be called by each constructor because
// of VTable changes
//
// Init all other updates once
updateColors();
updateFonts();
updateShortcuts();
}
void AbstractTableView::updateColors()
{
mBackgroundColor = ConfigColor("AbstractTableViewBackgroundColor");
mTextColor = ConfigColor("AbstractTableViewTextColor");
mSeparatorColor = ConfigColor("AbstractTableViewSeparatorColor");
mHeaderTextColor = ConfigColor("AbstractTableViewHeaderTextColor");
mSelectionColor = ConfigColor("AbstractTableViewSelectionColor");
}
void AbstractTableView::updateFonts()
{
setFont(ConfigFont("AbstractTableView"));
invalidateCachedFont();
mHeader.height = mFontMetrics->height() + 4;
}
QColor AbstractTableView::getCellColor(int r, int c)
{
Q_UNUSED(r);
Q_UNUSED(c);
return mTextColor;
}
void AbstractTableView::invalidateCachedFont()
{
delete mFontMetrics;
mFontMetrics = new CachedFontMetrics(this, font());
}
void AbstractTableView::updateColorsSlot()
{
updateColors();
}
void AbstractTableView::updateFontsSlot()
{
auto oldCharWidth = getCharWidth();
updateFonts();
auto newCharWidth = getCharWidth();
// Scale the column widths to the new font
for(int col = 0; col < getColumnCount(); col++)
{
auto width = getColumnWidth(col);
auto charCount = width / oldCharWidth;
auto padding = width % oldCharWidth;
setColumnWidth(col, charCount * newCharWidth + padding);
}
}
void AbstractTableView::updateShortcutsSlot()
{
updateShortcuts();
}
void AbstractTableView::loadColumnFromConfig(const QString & viewName)
{
int columnCount = getColumnCount();
for(int i = 0; i < columnCount; i++)
{
duint width = ConfigUint("Gui", QString("%1ColumnWidth%2").arg(viewName).arg(i).toUtf8().constData());
duint hidden = ConfigUint("Gui", QString("%1ColumnHidden%2").arg(viewName).arg(i).toUtf8().constData());
duint order = ConfigUint("Gui", QString("%1ColumnOrder%2").arg(viewName).arg(i).toUtf8().constData());
if(width != 0)
setColumnWidth(i, width);
if(hidden != 2)
setColumnHidden(i, !!hidden);
if(order != 0)
mColumnOrder[i] = order - 1;
}
mViewName = viewName;
}
void AbstractTableView::saveColumnToConfig()
{
if(mViewName.length() == 0)
return;
int columnCount = getColumnCount();
auto cfg = Config();
for(int i = 0; i < columnCount; i++)
{
cfg->setUint("Gui", QString("%1ColumnWidth%2").arg(mViewName).arg(i).toUtf8().constData(), getColumnWidth(i));
cfg->setUint("Gui", QString("%1ColumnHidden%2").arg(mViewName).arg(i).toUtf8().constData(), getColumnHidden(i) ? 1 : 0);
cfg->setUint("Gui", QString("%1ColumnOrder%2").arg(mViewName).arg(i).toUtf8().constData(), mColumnOrder[i] + 1);
}
}
void AbstractTableView::setupColumnConfigDefaultValue(QMap<QString, duint> & map, const QString & viewName, int columnCount)
{
for(int i = 0; i < columnCount; i++)
{
map.insert(QString("%1ColumnWidth%2").arg(viewName).arg(i), 0);
map.insert(QString("%1ColumnHidden%2").arg(viewName).arg(i), 2);
map.insert(QString("%1ColumnOrder%2").arg(viewName).arg(i), 0);
}
}
void AbstractTableView::editColumnDialog()
{
ColumnReorderDialog reorderDialog(this);
reorderDialog.setWindowTitle(tr("Edit columns"));
reorderDialog.exec();
}
/************************************************************************************
Painting Stuff
************************************************************************************/
/**
* @brief This method has been reimplemented. It paints the whole table.
*
* @param[in] event Paint event
*
* @return Nothing.
*/
void AbstractTableView::paintEvent(QPaintEvent* event)
{
Q_UNUSED(event);
QPainter wPainter(this->viewport());
wPainter.setFont(font());
// Paint background
if(mBackgroundColor.alpha() == 255) // The secret code to allow the user to set a background image in style.css
wPainter.fillRect(wPainter.viewport(), QBrush(mBackgroundColor));
if(!mAllowPainting)
return;
if(getColumnCount()) //make sure the last column is never smaller than the window
{
int totalWidth = 0;
int lastWidth = totalWidth;
int last = 0;
for(int i = 0; i < getColumnCount(); i++)
{
if(getColumnHidden(mColumnOrder[i]))
continue;
last = mColumnOrder[i];
lastWidth = getColumnWidth(last);
totalWidth += lastWidth;
}
lastWidth = totalWidth - lastWidth;
int width = this->viewport()->width();
lastWidth = width > lastWidth ? width - lastWidth : 0;
if(totalWidth < width)
setColumnWidth(last, lastWidth);
else
setColumnWidth(last, getColumnWidth(last));
}
int wViewableRowsCount = getViewableRowsCount();
int scrollValue = -horizontalScrollBar()->value();
int x = scrollValue;
int y = 0;
// Reload data if needed
if(mPrevTableOffset != mTableOffset || mShouldReload == true)
{
updateScrollBarRange(getRowCount());
prepareData();
mPrevTableOffset = mTableOffset;
mShouldReload = false;
}
// Paint header
if(mHeader.isVisible == true)
{
for(int j = 0; j < getColumnCount(); j++)
{
int i = mColumnOrder[j];
if(getColumnHidden(i))
continue;
int width = getColumnWidth(i);
QStyleOptionButton wOpt;
if((mColumnList[i].header.isPressed == true) && (mColumnList[i].header.isMouseOver == true)
|| (mGuiState == AbstractTableView::HeaderButtonReordering && mColumnOrder[mHoveredColumnDisplayIndex] == i))
wOpt.state = QStyle::State_Sunken;
else
wOpt.state = QStyle::State_Enabled;
wOpt.rect = QRect(x, y, width, getHeaderHeight());
mHeaderButtonSytle.style()->drawControl(QStyle::CE_PushButton, &wOpt, &wPainter, &mHeaderButtonSytle);
wPainter.setPen(mHeaderTextColor);
wPainter.drawText(QRect(x + 4, y, width - 8, getHeaderHeight()), Qt::AlignVCenter | Qt::AlignLeft, mColumnList[i].title);
x += width;
}
}
x = scrollValue;
y = getHeaderHeight();
// Iterate over all columns and cells
QString wStr;
for(int k = 0; k < getColumnCount(); k++)
{
int j = mColumnOrder[k];
if(getColumnHidden(j))
continue;
for(int i = 0; i < wViewableRowsCount; i++)
{
// Paints cell contents
if(i < mNbrOfLineToPrint)
{
// Don't draw cells if the flag is set, and no process is running
if(!mDrawDebugOnly || DbgIsDebugging())
{
wStr = paintContent(&wPainter, mTableOffset, i, j, x, y, getColumnWidth(j), getRowHeight());
if(wStr.length())
{
wPainter.setPen(getCellColor(mTableOffset + i, j));
wPainter.drawText(QRect(x + 4, y, getColumnWidth(j) - 5, getRowHeight()), Qt::AlignVCenter | Qt::AlignLeft, wStr);
}
}
}
if(getColumnCount() > 1)
{
// Paints cell right borders
wPainter.setPen(mSeparatorColor);
wPainter.drawLine(x + getColumnWidth(j) - 1, y, x + getColumnWidth(j) - 1, y + getRowHeight() - 1);
}
// Update y for the next iteration
y += getRowHeight();
}
y = getHeaderHeight();
x += getColumnWidth(j);
}
}
/************************************************************************************
Mouse Management
************************************************************************************/
/**
* @brief This method has been reimplemented. It manages the following actions:
* - Column resizing
* - Header button
*
* @param[in] event Mouse event
*
* @return Nothing.
*/
void AbstractTableView::mouseMoveEvent(QMouseEvent* event)
{
if(getColumnCount() <= 1)
return;
int wColIndex = getColumnIndexFromX(event->x());
int wDisplayIndex = getColumnDisplayIndexFromX(event->x());
int wStartPos = getColumnPosition(wDisplayIndex); // Position X of the start of column
int wEndPos = wStartPos + getColumnWidth(wColIndex); // Position X of the end of column
bool wHandle = ((wColIndex != 0) && (event->x() >= wStartPos) && (event->x() <= (wStartPos + 2))) || ((event->x() <= wEndPos) && (event->x() >= (wEndPos - 2)));
if(wColIndex == getColumnCount() - 1 && event->x() > viewport()->width()) //last column
wHandle = false;
switch(mGuiState)
{
case AbstractTableView::NoState:
{
if(event->buttons() == Qt::NoButton)
{
bool wHasCursor = cursor().shape() == Qt::SplitHCursor ? true : false;
if((wHandle == true) && (wHasCursor == false))
{
setCursor(Qt::SplitHCursor);
mColResizeData.splitHandle = true;
mGuiState = AbstractTableView::ReadyToResize;
}
else if((wHandle == false) && (wHasCursor == true))
{
unsetCursor();
mColResizeData.splitHandle = false;
mGuiState = AbstractTableView::NoState;
}
else if(wHandle == false && wHasCursor == false)
{
if(event->y() > getHeaderHeight() && DbgIsDebugging())
ShowDisassemblyPopup(getDisassemblyPopupAddress(event->x(), event->y()), event->x(), event->y());
}
}
else
{
QAbstractScrollArea::mouseMoveEvent(event);
}
}
break;
case AbstractTableView::ReadyToResize:
{
if(event->buttons() == Qt::NoButton)
{
if((wHandle == false) && (mGuiState == AbstractTableView::ReadyToResize))
{
unsetCursor();
mColResizeData.splitHandle = false;
mGuiState = AbstractTableView::NoState;
}
}
}
break;
case AbstractTableView::ResizeColumnState:
{
int delta = event->x() - mColResizeData.lastPosX;
bool bCanResize = (getColumnWidth(mColumnOrder[mColResizeData.index]) + delta) >= 20;
if(bCanResize)
{
int wNewSize = getColumnWidth(mColumnOrder[mColResizeData.index]) + delta;
setColumnWidth(mColumnOrder[mColResizeData.index], wNewSize);
mColResizeData.lastPosX = event->x();
updateViewport();
}
}
break;
case AbstractTableView::HeaderButtonPressed:
{
int wColIndex = getColumnIndexFromX(event->x());
if(wColIndex == mHeader.activeButtonIndex)
{
mColumnList[mHeader.activeButtonIndex].header.isMouseOver = (event->y() <= getHeaderHeight()) && (event->y() >= 0);
break;
}
else
{
mGuiState = AbstractTableView::HeaderButtonReordering;
}
}
// no break
case AbstractTableView::HeaderButtonReordering:
{
mHoveredColumnDisplayIndex = getColumnDisplayIndexFromX(event->x());
updateViewport();
}
break;
default:
break;
}
}
/**
* @brief This method has been reimplemented. It manages the following actions:
* - Column resizing
* - Header button
*
* @param[in] event Mouse event
*
* @return Nothing.
*/
void AbstractTableView::mousePressEvent(QMouseEvent* event)
{
if(((event->buttons() & Qt::LeftButton) != 0) && ((event->buttons() & Qt::RightButton) == 0))
{
if(mColResizeData.splitHandle == true)
{
int wColIndex = getColumnDisplayIndexFromX(event->x());
int wDisplayIndex = getColumnDisplayIndexFromX(event->x());
int wStartPos = getColumnPosition(wDisplayIndex); // Position X of the start of column
mGuiState = AbstractTableView::ResizeColumnState;
if(event->x() <= (wStartPos + 2))
{
mColResizeData.index = wColIndex - 1;
}
else
{
mColResizeData.index = wColIndex;
}
mColResizeData.lastPosX = event->x();
}
else if(mHeader.isVisible && getColumnCount() && (event->y() <= getHeaderHeight()) && (event->y() >= 0))
{
mReorderStartX = event->x();
int wColIndex = getColumnIndexFromX(event->x());
if(mColumnList[wColIndex].header.isClickable)
{
//qDebug() << "Button " << wColIndex << "has been pressed.";
emit headerButtonPressed(wColIndex);
mColumnList[wColIndex].header.isPressed = true;
mColumnList[wColIndex].header.isMouseOver = true;
mHeader.activeButtonIndex = wColIndex;
mGuiState = AbstractTableView::HeaderButtonPressed;
updateViewport();
}
}
}
else //right/middle click
{
if(event->y() < getHeaderHeight())
{
editColumnDialog();
event->accept();
}
}
//QWidget::mousePressEvent(event);
}
/**
* @brief This method has been reimplemented. It manages the following actions:
* - Column resizing
* - Header button
*
* @param[in] event Mouse event
*
* @return Nothing.
*/
void AbstractTableView::mouseReleaseEvent(QMouseEvent* event)
{
if((event->buttons() & Qt::LeftButton) == 0)
{
if(mGuiState == AbstractTableView::ResizeColumnState)
{
mGuiState = AbstractTableView::NoState;
}
else if(mGuiState == AbstractTableView::HeaderButtonPressed)
{
if(mColumnList[mHeader.activeButtonIndex].header.isMouseOver == true)
{
//qDebug() << "Button " << mHeader.activeButtonIndex << "has been released.";
emit headerButtonReleased(mHeader.activeButtonIndex);
}
mGuiState = AbstractTableView::NoState;
}
else if(mGuiState == AbstractTableView::HeaderButtonReordering)
{
int temp;
int wReorderFrom = getColumnDisplayIndexFromX(mReorderStartX);
int wReorderTo = getColumnDisplayIndexFromX(event->x());
temp = mColumnOrder[wReorderFrom];
mColumnOrder[wReorderFrom] = mColumnOrder[wReorderTo];
mColumnOrder[wReorderTo] = temp;
mGuiState = AbstractTableView::NoState;
}
else
{
QWidget::mouseReleaseEvent(event);
}
// Release all buttons
for(int i = 0; i < getColumnCount(); i++)
{
mColumnList[i].header.isPressed = false;
}
updateViewport();
}
}
void AbstractTableView::mouseDoubleClickEvent(QMouseEvent* event)
{
if(event->y() < getHeaderHeight())
{
editColumnDialog();
event->accept();
}
}
/**
* @brief This method has been reimplemented. It manages the following actions:
* - Mouse wheel
*
* @param[in] event Wheel event
*
* @return Nothing.
*/
void AbstractTableView::wheelEvent(QWheelEvent* event)
{
QPoint numDegrees = event->angleDelta() / 8;
QPoint numSteps = numDegrees / 15;
if(event->modifiers() == Qt::NoModifier)
{
if(numSteps.y() > 0)
{
if(mMouseWheelScrollDelta > 0)
for(int i = 0; i < mMouseWheelScrollDelta * numSteps.y(); i++)
verticalScrollBar()->triggerAction(QAbstractSlider::SliderSingleStepSub);
else // -1 : one screen at a time
verticalScrollBar()->triggerAction(QAbstractSlider::SliderPageStepSub);
}
else if(numSteps.y() < 0)
{
if(mMouseWheelScrollDelta > 0)
for(int i = 0; i < mMouseWheelScrollDelta * numSteps.y() * -1; i++)
verticalScrollBar()->triggerAction(QAbstractSlider::SliderSingleStepAdd);
else // -1 : one screen at a time
verticalScrollBar()->triggerAction(QAbstractSlider::SliderPageStepAdd);
}
else if(numSteps.x() > 0)
{
for(int i = 0; i < 20 * numSteps.x(); i++)
horizontalScrollBar()->triggerAction(QAbstractSlider::SliderSingleStepSub);
}
else if(numSteps.x() < 0)
{
for(int i = 0; i < 20 * numSteps.x() * -1; i++)
horizontalScrollBar()->triggerAction(QAbstractSlider::SliderSingleStepAdd);
}
}
else if(event->modifiers() == Qt::ControlModifier) // Zoom
Config()->zoomFont("AbstractTableView", event);
}
/**
* @brief This method has been reimplemented. It repaints the table when the height changes.
*
* @param[in] event Resize event
*
* @return Nothing.
*/
void AbstractTableView::resizeEvent(QResizeEvent* event)
{
if(event->size().height() != event->oldSize().height())
{
updateScrollBarRange(getRowCount());
emit viewableRowsChanged(getViewableRowsCount());
mShouldReload = true;
}
QAbstractScrollArea::resizeEvent(event);
}
void AbstractTableView::leaveEvent(QEvent* event)
{
ShowDisassemblyPopup(0, 0, 0);
QAbstractScrollArea::leaveEvent(event);
}
/************************************************************************************
Keyboard Management
************************************************************************************/
/**
* @brief This method has been reimplemented. It manages the following actions:
* - Pressed keys
*
* @param[in] event Key event
*
* @return Nothing.
*/
void AbstractTableView::keyPressEvent(QKeyEvent* event)
{
int wKey = event->key();
if(event->modifiers() != Qt::NoModifier && event->modifiers() != Qt::KeypadModifier)
return;
if(wKey == Qt::Key_Up)
{
verticalScrollBar()->triggerAction(QAbstractSlider::SliderSingleStepSub);
}
else if(wKey == Qt::Key_Down)
{
verticalScrollBar()->triggerAction(QAbstractSlider::SliderSingleStepAdd);
}
else if(wKey == Qt::Key_PageUp)
{
verticalScrollBar()->triggerAction(QAbstractSlider::SliderPageStepSub);
}
else if(wKey == Qt::Key_PageDown)
{
verticalScrollBar()->triggerAction(QAbstractSlider::SliderPageStepAdd);
}
else if(wKey == Qt::Key_Return || wKey == Qt::Key_Enter) //user pressed enter
emit enterPressedSignal();
}
/************************************************************************************
ScrollBar Management
***********************************************************************************/
/**
* @brief This method is the slot connected to the actionTriggered signal of the vertical scrollbar.
*
* @param[in] action Slider action type
*
* @return Nothing.
*/
void AbstractTableView::vertSliderActionSlot(int action)
{
dsint wDelta = 0;
int wSliderPos = verticalScrollBar()->sliderPosition();
int wNewScrollBarValue;
// Bounding
wSliderPos = wSliderPos > verticalScrollBar()->maximum() ? verticalScrollBar()->maximum() : wSliderPos;
wSliderPos = wSliderPos < 0 ? 0 : wSliderPos;
// Determine the delta
switch(action)
{
case QAbstractSlider::SliderNoAction:
break;
case QAbstractSlider::SliderSingleStepAdd:
wDelta = 1;
break;
case QAbstractSlider::SliderSingleStepSub:
wDelta = -1;
break;
case QAbstractSlider::SliderPageStepAdd:
wDelta = 30;
break;
case QAbstractSlider::SliderPageStepSub:
wDelta = -30;
break;
case QAbstractSlider::SliderToMinimum:
case QAbstractSlider::SliderToMaximum:
case QAbstractSlider::SliderMove:
#ifdef _WIN64
wDelta = scaleFromScrollBarRangeToUint64(wSliderPos) - mTableOffset;
#else
wDelta = wSliderPos - mTableOffset;
#endif
break;
default:
break;
}
// Call the hook (Usefull for disassembly)
mTableOffset = sliderMovedHook(action, mTableOffset, wDelta);
//this emit causes massive lag in the GUI
//emit tableOffsetChanged(mTableOffset);
// Scale the new table offset to the 32bits scrollbar range
#ifdef _WIN64
wNewScrollBarValue = scaleFromUint64ToScrollBarRange(mTableOffset);
#else
wNewScrollBarValue = mTableOffset;
#endif
//this emit causes massive lag in the GUI
//emit repainted();
// Update scrollbar attributes
verticalScrollBar()->setValue(wNewScrollBarValue);
verticalScrollBar()->setSliderPosition(wNewScrollBarValue);
}
/**
* @brief This virtual method is called at the end of the vertSliderActionSlot(...) method.
* It allows changing the table offset according to the action type, the old table offset
* and delta between the old and the new table offset.
*
* @param[in] type Type of action (Refer to the QAbstractSlider::SliderAction enum)
* @param[in] value Old table offset
* @param[in] delta Scrollbar value delta compared to the previous state
*
* @return Return the value of the new table offset.
*/
dsint AbstractTableView::sliderMovedHook(int type, dsint value, dsint delta)
{
Q_UNUSED(type);
dsint wValue = value + delta;
dsint wMax = getRowCount() - getViewableRowsCount() + 1;
// Bounding
wValue = wValue > wMax ? wMax : wValue;
wValue = wValue < 0 ? 0 : wValue;
return wValue;
}
/**
* @brief This method scale the given 64bits integer to the scrollbar range (32bits).
*
* @param[in] value 64bits integer to rescale
*
* @return 32bits integer.
*/
#ifdef _WIN64
int AbstractTableView::scaleFromUint64ToScrollBarRange(dsint value)
{
if(mScrollBarAttributes.is64 == true)
{
dsint wValue = ((dsint)value) >> mScrollBarAttributes.rightShiftCount;
dsint wValueMax = ((dsint)getRowCount() - 1) >> mScrollBarAttributes.rightShiftCount;
if(value == ((dsint)getRowCount() - 1))
return (int)(verticalScrollBar()->maximum());
else
return (int)((dsint)((dsint)verticalScrollBar()->maximum() * (dsint)wValue) / (dsint)wValueMax);
}
else
{
return (int)value;
}
}
#endif
/**
* @brief This method scale the given 32bits integer to the table range (64bits).
*
* @param[in] value 32bits integer to rescale
*
* @return 64bits integer.
*/
#ifdef _WIN64
dsint AbstractTableView::scaleFromScrollBarRangeToUint64(int value)
{
if(mScrollBarAttributes.is64 == true)
{
dsint wValueMax = ((dsint)getRowCount() - 1) >> mScrollBarAttributes.rightShiftCount;
if(value == (int)0x7FFFFFFF)
return (dsint)(getRowCount() - 1);
else
return (dsint)(((dsint)((dsint)wValueMax * (dsint)value) / (dsint)0x7FFFFFFF) << mScrollBarAttributes.rightShiftCount);
}
else
{
return (dsint)value;
}
}
#endif
/**
* @brief This method updates the vertical scrollbar range and pre-computes some attributes for the 32<->64bits conversion methods.
*
* @param[in] range New table range (size)
*
* @return none.
*/
void AbstractTableView::updateScrollBarRange(dsint range)
{
dsint wMax = range - getViewableRowsCount() + 1;
int rangeMin = 0, rangeMax = wMax;
if(wMax > 0)
{
#ifdef _WIN64
if((duint)wMax < (duint)0x0000000080000000)
{
mScrollBarAttributes.is64 = false;
mScrollBarAttributes.rightShiftCount = 0;
rangeMin = 0;
rangeMax = wMax;
}
else
{
duint wMask = 0x8000000000000000;
int wLeadingZeroCount;
// Count leading zeros
for(wLeadingZeroCount = 0; wLeadingZeroCount < 64; wLeadingZeroCount++)
{
if((duint)wMax < wMask)
{
wMask = wMask >> 1;
}
else
{
break;
}
}
mScrollBarAttributes.is64 = true;
mScrollBarAttributes.rightShiftCount = 32 - wLeadingZeroCount;
rangeMin = 0;
rangeMax = 0x7FFFFFFF;
}
#else
rangeMin = 0;
rangeMax = wMax;
#endif
}
else
{
rangeMin = 0;
rangeMax = 0;
}
verticalScrollBar()->setRange(rangeMin, rangeMax);
verticalScrollBar()->setSingleStep(getRowHeight());
verticalScrollBar()->setPageStep(getViewableRowsCount() * getRowHeight());
}
/************************************************************************************
Coordinates Utils
************************************************************************************/
/**
* @brief Returns the index offset (relative to the table offset) corresponding to the given y coordinate.
*
* @param[in] y Pixel offset starting from the top of the table (without the header)
*
* @return row index offset.
*/
int AbstractTableView::getIndexOffsetFromY(int y) const
{
return (y / getRowHeight());
}
/**
* @brief Returns the index of the column corresponding to the given x coordinate.
*
* @param[in] x Pixel offset starting from the left of the table
*
* @return Column index.
*/
int AbstractTableView::getColumnIndexFromX(int x) const
{
int wX = -horizontalScrollBar()->value();
int wColIndex = 0;
while(wColIndex < getColumnCount())
{
int col = mColumnOrder[wColIndex];
if(getColumnHidden(col))
{
wColIndex++;
continue;
}
wX += getColumnWidth(col);
if(x <= wX)
{
return mColumnOrder[wColIndex];
}
else if(wColIndex < getColumnCount())
{
wColIndex++;
}
}
return getColumnCount() > 0 ? mColumnOrder[getColumnCount() - 1] : -1;
}
/**
* @brief Returns the displayed index of the column corresponding to the given x coordinate.
*
* @param[in] x Pixel offset starting from the left of the table
*
* @return Displayed index.
*/
int AbstractTableView::getColumnDisplayIndexFromX(int x)
{
int wX = -horizontalScrollBar()->value();
int wColIndex = 0;
while(wColIndex < getColumnCount())
{
int col = mColumnOrder[wColIndex];
if(getColumnHidden(col))
{
wColIndex++;
continue;
}
wX += getColumnWidth(col);
if(x <= wX)
{
return wColIndex;
}
else if(wColIndex < getColumnCount())
{
wColIndex++;
}
}
return getColumnCount() - 1;
}
/**
* @brief Returns the x coordinate of the beginning of the column at index index.
*
* @param[in] index Column index.
*
* @return X coordinate of the column index.
*/
int AbstractTableView::getColumnPosition(int index) const
{
int posX = -horizontalScrollBar()->value();
if((index >= 0) && (index < getColumnCount()))
{
for(int i = 0; i < index; i++)
if(!getColumnHidden(mColumnOrder[i]))
posX += getColumnWidth(mColumnOrder[i]);
return posX;
}
else
{
return -1;
}
}
/**
* @brief Substracts the header height from the given y.
*
* @param[in] y y coordinate
*
* @return y - getHeaderHeight().
*/
int AbstractTableView::transY(int y) const
{
return y - getHeaderHeight();
}
/**
* @brief Returns the number of viewable rows in the current window (Partially viewable rows are aslo counted).
*
* @return Number of viewable rows.
*/
int AbstractTableView::getViewableRowsCount() const
{
int wTableHeight = this->viewport()->height() - getHeaderHeight();
int wCount = wTableHeight / getRowHeight();
wCount += (wTableHeight % getRowHeight()) > 0 ? 1 : 0;
return wCount;
}
/**
* @brief This virtual method returns the number of remaining lines to print.
*
* @return Number of remaining lines to print.
*/
int AbstractTableView::getLineToPrintcount() const
{
int wViewableRowsCount = getViewableRowsCount();
dsint wRemainingRowsCount = getRowCount() - mTableOffset;
int wCount = (dsint)wRemainingRowsCount > (dsint)wViewableRowsCount ? (int)wViewableRowsCount : (int)wRemainingRowsCount;
return wCount;
}
/************************************************************************************
New Columns/New Size
************************************************************************************/
/**
* @brief This mehtod adds a new column to the table.
*
* @param[in] width Width of the column in pixel
* @param[in] isClickable Boolean that tells whether the header is clickable or not
* @return Nothing.
*/
void AbstractTableView::addColumnAt(int width, const QString & title, bool isClickable)
{
HeaderButton wHeaderButton;
Column wColumn;
int wCurrentCount;
// Fix invisible columns near the edge of the screen
if(width < 20)
width = 20;
wHeaderButton.isPressed = false;
wHeaderButton.isClickable = isClickable;
wHeaderButton.isMouseOver = false;
wColumn.header = wHeaderButton;
wColumn.width = width;
wColumn.hidden = false;
wColumn.title = title;
wCurrentCount = mColumnList.length();
mColumnList.append(wColumn);
mColumnOrder.append(wCurrentCount);
}
void AbstractTableView::setRowCount(dsint count)
{
if(mRowCount != count)
mShouldReload = true;
mRowCount = count;
}
void AbstractTableView::deleteAllColumns()
{
mColumnList.clear();
mColumnOrder.clear();
}
void AbstractTableView::setColTitle(int index, const QString & title)
{
if(mColumnList.size() > 0 && index >= 0 && index < mColumnList.size())
{
Column wColumn = mColumnList.takeAt(index);
wColumn.title = title;
mColumnList.insert(index - 1, wColumn);
}
}
QString AbstractTableView::getColTitle(int index) const
{
if(mColumnList.size() > 0 && index >= 0 && index < mColumnList.size())
return mColumnList[index].title;
return QString();
}
/************************************************************************************
Getter & Setter
************************************************************************************/
dsint AbstractTableView::getRowCount() const
{
return mRowCount;
}
int AbstractTableView::getColumnCount() const
{
return mColumnList.size();
}
int AbstractTableView::getRowHeight() const
{
return mFontMetrics->height() | 1;
}
int AbstractTableView::getColumnWidth(int index) const
{
if(index < 0)
return -1;
else if(index < getColumnCount())
return mColumnList[index].width;
return 0;
}
bool AbstractTableView::getColumnHidden(int col) const
{
if(col < 0)
return true;
else if(col < getColumnCount())
return mColumnList[col].hidden;
else
return true;
}
void AbstractTableView::setColumnHidden(int col, bool hidden)
{
if(col < getColumnCount() && col >= 0)
mColumnList[col].hidden = hidden;
}
void AbstractTableView::setColumnWidth(int index, int width)
{
mColumnList[index].width = width;
MethodInvoker::invokeMethod([this]()
{
int totalWidth = 0;
for(int i = 0; i < getColumnCount(); i++)
if(!getColumnHidden(i))
totalWidth += getColumnWidth(i);
if(totalWidth > viewport()->width())
horizontalScrollBar()->setRange(0, totalWidth - viewport()->width());
else
horizontalScrollBar()->setRange(0, 0);
});
}
void AbstractTableView::setColumnOrder(int pos, int index)
{
if(index != 0)
mColumnOrder[pos] = index - 1;
}
int AbstractTableView::getColumnOrder(int index) const
{
return mColumnOrder[index] + 1;
}
int AbstractTableView::getHeaderHeight() const
{
if(mHeader.isVisible == true)
return mHeader.height;
else
return 0;
}
int AbstractTableView::getTableHeight() const
{
return this->viewport()->height() - getHeaderHeight();
}
int AbstractTableView::getGuiState() const
{
return mGuiState;
}
int AbstractTableView::getNbrOfLineToPrint() const
{
return mNbrOfLineToPrint;
}
void AbstractTableView::setNbrOfLineToPrint(int parNbrOfLineToPrint)
{
mNbrOfLineToPrint = parNbrOfLineToPrint;
}
void AbstractTableView::setShowHeader(bool show)
{
mHeader.isVisible = show;
}
int AbstractTableView::getCharWidth() const
{
return QFontMetrics(this->font()).width(QChar(' '));
}
/************************************************************************************
Content drawing control
************************************************************************************/
bool AbstractTableView::getDrawDebugOnly() const
{
return mDrawDebugOnly;
}
void AbstractTableView::setDrawDebugOnly(bool value)
{
mDrawDebugOnly = value;
}
void AbstractTableView::setAllowPainting(bool allow)
{
mAllowPainting = allow;
}
bool AbstractTableView::getAllowPainting() const
{
return mAllowPainting;
}
/************************************************************************************
Table offset management
************************************************************************************/
dsint AbstractTableView::getTableOffset() const
{
return mTableOffset;
}
void AbstractTableView::setTableOffset(dsint val)
{
dsint wMaxOffset = getRowCount() - getViewableRowsCount() + 1;
wMaxOffset = wMaxOffset > 0 ? getRowCount() : 0;
if(val > wMaxOffset)
return;
// If val is within the last ViewableRows, then set RVA to rowCount - ViewableRows + 1
if(wMaxOffset && val >= (getRowCount() - getViewableRowsCount() + 1))
mTableOffset = (getRowCount() - getViewableRowsCount()) + 1;
else
mTableOffset = val;
emit tableOffsetChanged(val);
MethodInvoker::invokeMethod([this]()
{
#ifdef _WIN64
int wNewValue = scaleFromUint64ToScrollBarRange(mTableOffset);
verticalScrollBar()->setValue(wNewValue);
verticalScrollBar()->setSliderPosition(wNewValue);
#else
verticalScrollBar()->setValue(mTableOffset);
verticalScrollBar()->setSliderPosition(mTableOffset);
#endif
});
}
/************************************************************************************
Update/Reload/Refresh/Repaint
************************************************************************************/
void AbstractTableView::reloadData()
{
mShouldReload = true;
emit tableOffsetChanged(mTableOffset);
updateViewport();
}
void AbstractTableView::updateViewport()
{
MethodInvoker::invokeMethod([this]()
{
viewport()->update();
});
}
/**
* @brief This method is called when data have to be reloaded (e.g. When table offset changes).
*
* @return Nothing.
*/
void AbstractTableView::prepareData()
{
int wViewableRowsCount = getViewableRowsCount();
dsint wRemainingRowsCount = getRowCount() - mTableOffset;
mNbrOfLineToPrint = (dsint)wRemainingRowsCount > (dsint)wViewableRowsCount ? (int)wViewableRowsCount : (int)wRemainingRowsCount;
}
/************************************************************************************
DisassemblyPopup
************************************************************************************/
void AbstractTableView::setDisassemblyPopupEnabled(bool enable)
{
mPopupEnabled = enable;
}
duint AbstractTableView::getDisassemblyPopupAddress(int mousex, int mousey)
{
Q_UNUSED(mousex)
Q_UNUSED(mousey)
return 0; //Default is no disassembly popup
}
void AbstractTableView::ShowDisassemblyPopup(duint addr, int x, int y)
{
if(!mPopupEnabled || !addr)
{
killTimer(mPopupTimer);
mPopupTimer = 0;
if(mDisassemblyPopup)
mDisassemblyPopup->hide();
return;
}
if(!mDisassemblyPopup)
mDisassemblyPopup = new DisassemblyPopup(this);
if(mDisassemblyPopup->getAddress() == addr)
return;
if(DbgFunctions()->MemIsCodePage(addr, false))
{
mDisassemblyPopup->move(mapToGlobal(QPoint(x + 20, y + fontMetrics().height() * 2)));
mDisassemblyPopup->setAddress(addr);
//mDisassemblyPopup->show();
if(mPopupTimer == 0)
mPopupTimer = startTimer(QApplication::startDragTime());
}
else
{
mDisassemblyPopup->hide();
killTimer(mPopupTimer);
mPopupTimer = 0;
}
}
void AbstractTableView::timerEvent(QTimerEvent* event)
{
if(event->timerId() == mPopupTimer)
{
mDisassemblyPopup->show();
killTimer(mPopupTimer);
mPopupTimer = 0;
}
QAbstractScrollArea::timerEvent(event);
}
void AbstractTableView::hideEvent(QHideEvent* event)
{
ShowDisassemblyPopup(0, 0, 0);
QAbstractScrollArea::hideEvent(event);
} |
C/C++ | x64dbg-development/src/gui/Src/BasicView/AbstractTableView.h | #pragma once
#include <QScrollBar>
#include <QAbstractScrollArea>
#include <QPushButton>
#include <QApplication>
#include <QMouseEvent>
#include <QPainter>
#include <QMenu>
#include "StringUtil.h"
#include "Configuration.h"
#include "MenuBuilder.h"
#include "MiscUtil.h"
#include "ActionHelpers.h"
class CachedFontMetrics;
class DisassemblyPopup;
//Hacky class that fixes a really annoying cursor problem
class AbstractTableScrollBar : public QScrollBar
{
Q_OBJECT
public:
explicit AbstractTableScrollBar(QScrollBar* scrollbar);
void enterEvent(QEvent* event) override;
void leaveEvent(QEvent* event) override;
};
class AbstractTableView;
class AbstractTableView : public QAbstractScrollArea, public ActionHelper<AbstractTableView>
{
Q_OBJECT
public:
enum GuiState
{
NoState,
ReadyToResize,
ResizeColumnState,
HeaderButtonPressed,
HeaderButtonReordering
};
// Constructor
explicit AbstractTableView(QWidget* parent = 0);
virtual ~AbstractTableView() = default;
// Configuration
virtual void Initialize();
virtual void updateColors();
virtual void updateFonts();
// Pure Virtual Methods
virtual QString paintContent(QPainter* painter, dsint rowBase, int rowOffset, int col, int x, int y, int w, int h) = 0;
virtual QColor getCellColor(int r, int c);
// Painting Stuff
void paintEvent(QPaintEvent* event) override;
// Mouse Management
void mouseMoveEvent(QMouseEvent* event) override;
void mousePressEvent(QMouseEvent* event) override;
void mouseReleaseEvent(QMouseEvent* event) override;
void mouseDoubleClickEvent(QMouseEvent* event) override;
void wheelEvent(QWheelEvent* event) override;
void resizeEvent(QResizeEvent* event) override;
void keyPressEvent(QKeyEvent* event) override;
void leaveEvent(QEvent* event) override;
void hideEvent(QHideEvent* event) override;
// ScrollBar Management
virtual dsint sliderMovedHook(int type, dsint value, dsint delta); // can be made protected
int scaleFromUint64ToScrollBarRange(dsint value); // can be made private
dsint scaleFromScrollBarRangeToUint64(int value); // can be made private
void updateScrollBarRange(dsint range); // setRowCount+resizeEvent needs this, can be made private
// Coordinates Utils
int getIndexOffsetFromY(int y) const; // can be made protected
int getColumnIndexFromX(int x) const; // can be made protected
int getColumnPosition(int index) const; // can be made protected
int transY(int y) const; // can be made protected
int getViewableRowsCount() const; // can be made protected
virtual int getLineToPrintcount() const;
// New Columns/New Size
virtual void addColumnAt(int width, const QString & title, bool isClickable);
virtual void setRowCount(dsint count);
virtual void deleteAllColumns(); // can be made protected, although it makes sense as a public API
void setColTitle(int index, const QString & title); // can be deleted, although it makes sense as a public API
QString getColTitle(int index) const; // can be deleted, although it makes sense as a public API
// Getter & Setter
dsint getRowCount() const;
int getColumnCount() const;
int getRowHeight() const;
int getColumnWidth(int index) const;
void setColumnWidth(int index, int width);
void setColumnOrder(int pos, int index);
int getColumnOrder(int index) const;
int getHeaderHeight() const; // can be made protected
int getTableHeight() const; // can be made protected
int getGuiState() const; // can be made protected
int getNbrOfLineToPrint() const;
void setNbrOfLineToPrint(int parNbrOfLineToPrint);
void setShowHeader(bool show);
int getCharWidth() const;
bool getColumnHidden(int col) const;
void setColumnHidden(int col, bool hidden);
bool getDrawDebugOnly() const;
void setDrawDebugOnly(bool value);
bool getAllowPainting() const;
void setAllowPainting(bool allow);
void setDisassemblyPopupEnabled(bool enable);
// UI customization
void loadColumnFromConfig(const QString & viewName);
void saveColumnToConfig();
static void setupColumnConfigDefaultValue(QMap<QString, duint> & map, const QString & viewName, int columnCount);
// Table offset management
dsint getTableOffset() const;
void setTableOffset(dsint val);
// Update/Reload/Refresh/Repaint
virtual void prepareData();
virtual duint getDisassemblyPopupAddress(int mousex, int mousey);
signals:
void enterPressedSignal();
void headerButtonPressed(int col);
void headerButtonReleased(int col);
void tableOffsetChanged(dsint i);
void viewableRowsChanged(int rows);
void repainted();
public slots:
// Update/Reload/Refresh/Repaint
virtual void reloadData();
void updateViewport();
// ScrollBar Management
void vertSliderActionSlot(int action);
void editColumnDialog();
protected slots:
void ShowDisassemblyPopup(duint addr, int x, int y); // this should probably be a slot, but doesn't need emit fixes (it's already used correctly)
void timerEvent(QTimerEvent* event);
private slots:
// Configuration
void updateColorsSlot();
void updateFontsSlot();
void updateShortcutsSlot();
void shutdownSlot();
private:
struct ColumnResizingData
{
bool splitHandle;
int index;
int lastPosX;
};
struct HeaderButton
{
bool isClickable;
bool isPressed;
bool isMouseOver;
};
struct Column
{
int width;
bool hidden;
HeaderButton header;
QString title;
};
struct Header
{
bool isVisible;
int height;
int activeButtonIndex;
};
struct ScrollBar64
{
bool is64;
int rightShiftCount;
};
GuiState mGuiState;
Header mHeader;
QPushButton mHeaderButtonSytle;
QList<Column> mColumnList;
ColumnResizingData mColResizeData;
QList<int> mColumnOrder;
int mReorderStartX;
int mHoveredColumnDisplayIndex;
dsint mRowCount;
dsint mTableOffset;
dsint mPrevTableOffset;
int mNbrOfLineToPrint;
bool mShouldReload;
bool mDrawDebugOnly;
bool mPopupEnabled;
int mPopupTimer;
static int mMouseWheelScrollDelta;
ScrollBar64 mScrollBarAttributes;
int getColumnDisplayIndexFromX(int x);
friend class ColumnReorderDialog;
protected:
// Configuration
QColor mBackgroundColor;
QColor mTextColor;
QColor mSeparatorColor;
QColor mHeaderTextColor;
QColor mSelectionColor;
QString mViewName;
bool mAllowPainting;
// Font metrics
CachedFontMetrics* mFontMetrics;
void invalidateCachedFont();
// Disassembly Popup
DisassemblyPopup* mDisassemblyPopup;
}; |
C++ | x64dbg-development/src/gui/Src/BasicView/Disassembly.cpp | #include "Disassembly.h"
#include "Configuration.h"
#include "CodeFolding.h"
#include "EncodeMap.h"
#include "Bridge.h"
#include "CachedFontMetrics.h"
#include "QBeaEngine.h"
#include "MemoryPage.h"
Disassembly::Disassembly(QWidget* parent, bool isMain)
: AbstractTableView(parent),
mIsMain(isMain)
{
mMemPage = new MemoryPage(0, 0);
mInstBuffer.clear();
setDrawDebugOnly(true);
historyClear();
memset(&mSelection, 0, sizeof(SelectionData));
mHighlightToken.text = "";
mHighlightingMode = false;
mShowMnemonicBrief = false;
int maxModuleSize = (int)ConfigUint("Disassembler", "MaxModuleSize");
Config()->writeUints();
mDisasm = new QBeaEngine(maxModuleSize);
tokenizerConfigUpdatedSlot();
updateConfigSlot();
mCodeFoldingManager = nullptr;
mIsLastInstDisplayed = false;
mGuiState = Disassembly::NoState;
// Update fonts immediately because they are used in calculations
updateFonts();
setRowCount(mMemPage->getSize());
addColumnAt(getCharWidth() * 2 * sizeof(dsint) + 8, tr("Address"), false); //address
addColumnAt(getCharWidth() * 2 * 12 + 8, tr("Bytes"), false); //bytes
addColumnAt(getCharWidth() * 40, tr("Disassembly"), false); //disassembly
addColumnAt(getCharWidth() * 40, tr("Mnemonic brief"), false);
addColumnAt(1000, tr("Comments"), false); //comments
setColumnHidden(ColMnemonicBrief, true);
setShowHeader(false); //hide header
mBackgroundColor = ConfigColor("DisassemblyBackgroundColor");
mXrefInfo.refcount = 0;
// Slots
connect(Bridge::getBridge(), SIGNAL(updateDisassembly()), this, SLOT(reloadData()));
connect(Bridge::getBridge(), SIGNAL(dbgStateChanged(DBGSTATE)), this, SLOT(debugStateChangedSlot(DBGSTATE)));
connect(this, SIGNAL(selectionChanged(dsint)), this, SLOT(selectionChangedSlot(dsint)));
connect(Config(), SIGNAL(tokenizerConfigUpdated()), this, SLOT(tokenizerConfigUpdatedSlot()));
connect(Config(), SIGNAL(guiOptionsUpdated()), this, SLOT(updateConfigSlot()));
Initialize();
}
Disassembly::~Disassembly()
{
delete mMemPage;
delete mDisasm;
if(mXrefInfo.refcount != 0)
BridgeFree(mXrefInfo.references);
}
void Disassembly::updateColors()
{
AbstractTableView::updateColors();
mBackgroundColor = ConfigColor("DisassemblyBackgroundColor");
mInstructionHighlightColor = ConfigColor("InstructionHighlightColor");
mDisassemblyRelocationUnderlineColor = ConfigColor("DisassemblyRelocationUnderlineColor");
mSelectionColor = ConfigColor("DisassemblySelectionColor");
mCipBackgroundColor = ConfigColor("DisassemblyCipBackgroundColor");
mCipColor = ConfigColor("DisassemblyCipColor");
mBreakpointBackgroundColor = ConfigColor("DisassemblyBreakpointBackgroundColor");
mBreakpointColor = ConfigColor("DisassemblyBreakpointColor");
mHardwareBreakpointBackgroundColor = ConfigColor("DisassemblyHardwareBreakpointBackgroundColor");
mHardwareBreakpointColor = ConfigColor("DisassemblyHardwareBreakpointColor");
mBookmarkBackgroundColor = ConfigColor("DisassemblyBookmarkBackgroundColor");
mBookmarkColor = ConfigColor("DisassemblyBookmarkColor");
mLabelColor = ConfigColor("DisassemblyLabelColor");
mLabelBackgroundColor = ConfigColor("DisassemblyLabelBackgroundColor");
mSelectedAddressBackgroundColor = ConfigColor("DisassemblySelectedAddressBackgroundColor");
mTracedAddressBackgroundColor = ConfigColor("DisassemblyTracedBackgroundColor");
mSelectedAddressColor = ConfigColor("DisassemblySelectedAddressColor");
mAddressBackgroundColor = ConfigColor("DisassemblyAddressBackgroundColor");
mAddressColor = ConfigColor("DisassemblyAddressColor");
mBytesColor = ConfigColor("DisassemblyBytesColor");
mBytesBackgroundColor = ConfigColor("DisassemblyBytesBackgroundColor");
mModifiedBytesColor = ConfigColor("DisassemblyModifiedBytesColor");
mModifiedBytesBackgroundColor = ConfigColor("DisassemblyModifiedBytesBackgroundColor");
mRestoredBytesColor = ConfigColor("DisassemblyRestoredBytesColor");
mRestoredBytesBackgroundColor = ConfigColor("DisassemblyRestoredBytesBackgroundColor");
mAutoCommentColor = ConfigColor("DisassemblyAutoCommentColor");
mAutoCommentBackgroundColor = ConfigColor("DisassemblyAutoCommentBackgroundColor");
mMnemonicBriefColor = ConfigColor("DisassemblyMnemonicBriefColor");
mMnemonicBriefBackgroundColor = ConfigColor("DisassemblyMnemonicBriefBackgroundColor");
mCommentColor = ConfigColor("DisassemblyCommentColor");
mCommentBackgroundColor = ConfigColor("DisassemblyCommentBackgroundColor");
mUnconditionalJumpLineColor = ConfigColor("DisassemblyUnconditionalJumpLineColor");
mConditionalJumpLineTrueColor = ConfigColor("DisassemblyConditionalJumpLineTrueColor");
mConditionalJumpLineFalseColor = ConfigColor("DisassemblyConditionalJumpLineFalseColor");
mLoopColor = ConfigColor("DisassemblyLoopColor");
mFunctionColor = ConfigColor("DisassemblyFunctionColor");
auto a = mSelectionColor, b = mTracedAddressBackgroundColor;
mTracedSelectedAddressBackgroundColor = QColor((a.red() + b.red()) / 2, (a.green() + b.green()) / 2, (a.blue() + b.blue()) / 2);
mLoopPen = QPen(mLoopColor, 2);
mFunctionPen = QPen(mFunctionColor, 2);
mUnconditionalPen = QPen(mUnconditionalJumpLineColor);
mConditionalTruePen = QPen(mConditionalJumpLineTrueColor);
mConditionalFalsePen = QPen(mConditionalJumpLineFalseColor);
ZydisTokenizer::UpdateColors();
mDisasm->UpdateConfig();
}
void Disassembly::updateFonts()
{
setFont(ConfigFont("Disassembly"));
invalidateCachedFont();
mTextLayout.setFont(font());
mTextLayout.setCacheEnabled(true);
}
void Disassembly::updateConfigSlot()
{
setDisassemblyPopupEnabled(!Config()->getBool("Disassembler", "NoBranchDisasmPreview"));
}
void Disassembly::tokenizerConfigUpdatedSlot()
{
mDisasm->UpdateConfig();
mPermanentHighlightingMode = ConfigBool("Disassembler", "PermanentHighlightingMode");
mNoCurrentModuleText = ConfigBool("Disassembler", "NoCurrentModuleText");
}
static void mnemonicBriefRichText(RichTextPainter::List & richText, const Instruction_t & instr, QColor mMnemonicBriefColor, QColor mMnemonicBriefBackgroundColor)
{
RichTextPainter::CustomRichText_t richBrief;
richBrief.underline = false;
richBrief.textColor = mMnemonicBriefColor;
richBrief.textBackground = mMnemonicBriefBackgroundColor;
richBrief.flags = RichTextPainter::FlagAll;
char brief[MAX_STRING_SIZE] = "";
QString mnem;
for(const ZydisTokenizer::SingleToken & token : instr.tokens.tokens)
{
if(token.type != ZydisTokenizer::TokenType::Space && token.type != ZydisTokenizer::TokenType::Prefix)
{
mnem = token.text;
break;
}
}
if(mnem.isEmpty())
mnem = instr.instStr;
int index = mnem.indexOf(' ');
if(index != -1)
mnem.truncate(index);
DbgFunctions()->GetMnemonicBrief(mnem.toUtf8().constData(), MAX_STRING_SIZE, brief);
QString mnemBrief = brief;
if(mnemBrief.length())
{
RichTextPainter::CustomRichText_t space;
space.underline = false;
space.flags = RichTextPainter::FlagNone;
space.text = " ";
if(richText.size())
richText.emplace_back(std::move(space));
richBrief.text = std::move(mnemBrief);
richText.emplace_back(std::move(richBrief));
}
}
#define HANDLE_RANGE_TYPE(prefix, first, last) \
if(first == prefix ## _BEGIN && last == prefix ## _END) \
first = prefix ## _SINGLE; \
if(last == prefix ## _END && first != prefix ## _SINGLE) \
first = last
/************************************************************************************
Reimplemented Functions
************************************************************************************/
/**
* @brief This method has been reimplemented. It returns the string to paint or paints it
* by its own.
*
* @param[in] painter Pointer to the painter that allows painting by its own
* @param[in] rowBase Index of the top item (Table offset)
* @param[in] rowOffset Index offset starting from rowBase
* @param[in] col Column index
* @param[in] x Rectangle x
* @param[in] y Rectangle y
* @param[in] w Rectangle width
* @param[in] h Rectangle heigth
*
* @return String to paint.
*/
QString Disassembly::paintContent(QPainter* painter, dsint rowBase, int rowOffset, int col, int x, int y, int w, int h)
{
Q_UNUSED(rowBase);
if(mHighlightingMode)
{
QPen pen(Qt::red);
pen.setWidth(2);
painter->setPen(pen);
QRect rect = viewport()->rect();
rect.adjust(1, 1, -1, -1);
painter->drawRect(rect);
}
dsint wRVA = mInstBuffer.at(rowOffset).rva;
bool wIsSelected = isSelected(&mInstBuffer, rowOffset);
dsint cur_addr = rvaToVa(mInstBuffer.at(rowOffset).rva);
auto traceCount = DbgFunctions()->GetTraceRecordHitCount(cur_addr);
// Highlight if selected
if(wIsSelected && traceCount)
painter->fillRect(QRect(x, y, w, h), QBrush(mTracedSelectedAddressBackgroundColor));
else if(wIsSelected)
painter->fillRect(QRect(x, y, w, h), QBrush(mSelectionColor));
else if(traceCount)
{
// Color depending on how often a sequence of code is executed
int exponent = 1;
while(traceCount >>= 1) //log2(traceCount)
exponent++;
int colorDiff = (exponent * exponent) / 2;
// If the user has a light trace background color, substract
if(mTracedAddressBackgroundColor.blue() > 160)
colorDiff *= -1;
painter->fillRect(QRect(x, y, w, h),
QBrush(QColor(mTracedAddressBackgroundColor.red(),
mTracedAddressBackgroundColor.green(),
std::max(0, std::min(256, mTracedAddressBackgroundColor.blue() + colorDiff)))));
}
switch(col)
{
case ColAddress: // Draw address (+ label)
{
RichTextPainter::CustomRichText_t richText;
richText.underline = false;
richText.textColor = mTextColor;
richText.flags = RichTextPainter::FlagColor;
char label[MAX_LABEL_SIZE] = "";
QString addrText = getAddrText(cur_addr, label);
richText.text = addrText;
BPXTYPE bpxtype = DbgGetBpxTypeAt(cur_addr);
bool isbookmark = DbgGetBookmarkAt(cur_addr);
if(rvaToVa(mInstBuffer.at(rowOffset).rva) == mCipVa && !Bridge::getBridge()->mIsRunning && DbgMemFindBaseAddr(DbgValFromString("cip"), nullptr)) //cip + not running + valid cip
{
richText.textBackground = mCipBackgroundColor;
if(!isbookmark) //no bookmark
{
if(bpxtype & bp_normal) //normal breakpoint
{
QColor bpColor = mBreakpointBackgroundColor;
if(!bpColor.alpha()) //we don't want transparent text
bpColor = mBreakpointColor;
if(bpColor == mCipBackgroundColor)
bpColor = mCipColor;
richText.textColor = bpColor;
}
else if(bpxtype & bp_hardware) //hardware breakpoint only
{
QColor hwbpColor = mHardwareBreakpointBackgroundColor;
if(!hwbpColor.alpha()) //we don't want transparent text
hwbpColor = mHardwareBreakpointColor;
if(hwbpColor == mCipBackgroundColor)
hwbpColor = mCipColor;
richText.textColor = hwbpColor;
}
else //no breakpoint
{
richText.textColor = mCipColor;
}
}
else //bookmark
{
QColor bookmarkColor = mBookmarkBackgroundColor;
if(!bookmarkColor.alpha()) //we don't want transparent text
bookmarkColor = mBookmarkColor;
if(bookmarkColor == mCipBackgroundColor)
bookmarkColor = mCipColor;
richText.textColor = bookmarkColor;
}
}
else //non-cip address
{
if(!isbookmark) //no bookmark
{
if(*label) //label
{
if(bpxtype == bp_none) //label only : fill label background
{
richText.textColor = mLabelColor;
richText.textBackground = mLabelBackgroundColor;
}
else //label + breakpoint
{
if(bpxtype & bp_normal) //label + normal breakpoint
{
richText.textColor = mBreakpointColor;
richText.textBackground = mBreakpointBackgroundColor;
}
else if(bpxtype & bp_hardware) //label + hardware breakpoint only
{
richText.textColor = mHardwareBreakpointColor;
richText.textBackground = mHardwareBreakpointBackgroundColor;
}
else //other cases -> do as normal
{
richText.textColor = mLabelColor;
richText.textBackground = mLabelBackgroundColor;
}
}
}
else //no label
{
if(bpxtype == bp_none) //no label, no breakpoint
{
if(wIsSelected)
{
richText.textColor = mSelectedAddressColor;
richText.textBackground = mSelectedAddressBackgroundColor;
}
else
{
richText.textColor = mAddressColor;
richText.textBackground = mAddressBackgroundColor;
}
}
else //breakpoint only
{
if(bpxtype & bp_normal) //normal breakpoint
{
richText.textColor = mBreakpointColor;
richText.textBackground = mBreakpointBackgroundColor;
}
else if(bpxtype & bp_hardware) //hardware breakpoint only
{
richText.textColor = mHardwareBreakpointColor;
richText.textBackground = mHardwareBreakpointBackgroundColor;
}
else //other cases (memory breakpoint in disassembly) -> do as normal
{
if(wIsSelected)
{
richText.textColor = mSelectedAddressColor;
richText.textBackground = mSelectedAddressBackgroundColor;
}
else
{
richText.textColor = mAddressColor;
richText.textBackground = mAddressBackgroundColor;
}
}
}
}
}
else //bookmark
{
if(*label) //label + bookmark
{
if(bpxtype == bp_none) //label + bookmark
{
richText.textColor = mLabelColor;
richText.textBackground = mBookmarkBackgroundColor;
}
else //label + breakpoint + bookmark
{
QColor color = mBookmarkBackgroundColor;
if(!color.alpha()) //we don't want transparent text
color = mAddressColor;
richText.textColor = color;
if(bpxtype & bp_normal) //label + bookmark + normal breakpoint
{
richText.textBackground = mBreakpointBackgroundColor;
}
else if(bpxtype & bp_hardware) //label + bookmark + hardware breakpoint only
{
richText.textBackground = mHardwareBreakpointBackgroundColor;
}
}
}
else //bookmark, no label
{
if(bpxtype == bp_none) //bookmark only
{
richText.textColor = mBookmarkColor;
richText.textBackground = mBookmarkBackgroundColor;
}
else //bookmark + breakpoint
{
QColor color = mBookmarkBackgroundColor;
if(!color.alpha()) //we don't want transparent text
color = mAddressColor;
richText.textColor = color;
if(bpxtype & bp_normal) //bookmark + normal breakpoint
{
richText.textBackground = mBreakpointBackgroundColor;
}
else if(bpxtype & bp_hardware) //bookmark + hardware breakpoint only
{
richText.textBackground = mHardwareBreakpointBackgroundColor;
}
else //other cases (bookmark + memory breakpoint in disassembly) -> do as normal
{
richText.textColor = mBookmarkColor;
richText.textBackground = mBookmarkBackgroundColor;
}
}
}
}
}
if(richText.textBackground.alpha())
{
painter->fillRect(QRect(x, y, w, h), richText.textBackground);
}
RichTextPainter::List list;
list.emplace_back(std::move(richText));
paintRichText(x, y, w, h, 2, std::move(list), rowOffset, col);
}
break;
case ColBytes: //draw bytes
{
const Instruction_t & instr = mInstBuffer.at(rowOffset);
//draw functions
Function_t funcType;
FUNCTYPE funcFirst = DbgGetFunctionTypeAt(cur_addr);
FUNCTYPE funcLast = DbgGetFunctionTypeAt(cur_addr + instr.length - 1);
HANDLE_RANGE_TYPE(FUNC, funcFirst, funcLast);
switch(funcFirst)
{
case FUNC_SINGLE:
funcType = Function_single;
break;
case FUNC_NONE:
funcType = Function_none;
break;
case FUNC_BEGIN:
funcType = Function_start;
break;
case FUNC_MIDDLE:
funcType = Function_middle;
break;
case FUNC_END:
funcType = Function_end;
break;
}
int funcsize = paintFunctionGraphic(painter, x, y, funcType, false);
painter->setPen(mFunctionPen);
XREFTYPE refType = DbgGetXrefTypeAt(cur_addr);
char indicator;
if(refType == XREF_JMP)
{
indicator = '>';
}
else if(refType == XREF_CALL)
{
indicator = '$';
}
else if(funcType != Function_none)
{
indicator = '.';
}
else
{
indicator = ' ';
}
int charwidth = getCharWidth();
painter->drawText(QRect(x + funcsize, y, charwidth, h), Qt::AlignVCenter | Qt::AlignLeft, QString(indicator));
funcsize += charwidth;
//draw jump arrows
Instruction_t::BranchType branchType = mInstBuffer.at(rowOffset).branchType;
int jumpsize = paintJumpsGraphic(painter, x + funcsize, y - 1, wRVA, branchType != Instruction_t::None && branchType != Instruction_t::Call); //jump line
//draw bytes
auto richBytes = getRichBytes(instr, wIsSelected);
paintRichText(x, y, getColumnWidth(col), getRowHeight(), jumpsize + funcsize, std::move(richBytes), rowOffset, col);
}
break;
case ColDisassembly: //draw disassembly (with colours needed)
{
int loopsize = 0;
int depth = 0;
while(1) //paint all loop depths
{
LOOPTYPE loopFirst = DbgGetLoopTypeAt(cur_addr, depth);
LOOPTYPE loopLast = DbgGetLoopTypeAt(cur_addr + mInstBuffer.at(rowOffset).length - 1, depth);
HANDLE_RANGE_TYPE(LOOP, loopFirst, loopLast);
if(loopFirst == LOOP_NONE)
break;
Function_t funcType;
switch(loopFirst)
{
case LOOP_SINGLE:
funcType = Function_single;
break;
case LOOP_BEGIN:
funcType = Function_start;
break;
case LOOP_ENTRY:
funcType = Function_loop_entry;
break;
case LOOP_MIDDLE:
funcType = Function_middle;
break;
case LOOP_END:
funcType = Function_end;
break;
default:
break;
}
loopsize += paintFunctionGraphic(painter, x + loopsize, y, funcType, loopFirst != LOOP_SINGLE);
depth++;
}
RichTextPainter::List richText;
auto & token = mInstBuffer[rowOffset].tokens;
if(mHighlightToken.text.length())
ZydisTokenizer::TokenToRichText(token, richText, &mHighlightToken);
else
ZydisTokenizer::TokenToRichText(token, richText, 0);
int xinc = 4 + loopsize;
paintRichText(x, y, getColumnWidth(col), getRowHeight(), xinc, std::move(richText), rowOffset, col);
token.x = x + loopsize + xinc;
}
break;
case ColMnemonicBrief: //mnemonic brief
{
RichTextPainter::List richText;
if(mShowMnemonicBrief)
{
mnemonicBriefRichText(richText, mInstBuffer.at(rowOffset), mMnemonicBriefColor, mMnemonicBriefBackgroundColor);
}
paintRichText(x, y, w, h, 3, std::move(richText), rowOffset, col);
}
break;
case ColComment: //draw comments
{
//draw arguments
Function_t funcType;
ARGTYPE argFirst = DbgGetArgTypeAt(cur_addr);
ARGTYPE argLast = DbgGetArgTypeAt(cur_addr + mInstBuffer.at(rowOffset).length - 1);
HANDLE_RANGE_TYPE(ARG, argFirst, argLast);
switch(argFirst)
{
case ARG_SINGLE:
funcType = Function_single;
break;
case ARG_NONE:
funcType = Function_none;
break;
case ARG_BEGIN:
funcType = Function_start;
break;
case ARG_MIDDLE:
funcType = Function_middle;
break;
case ARG_END:
funcType = Function_end;
break;
}
RichTextPainter::List richText;
int argsize = funcType == Function_none ? 3 : paintFunctionGraphic(painter, x, y, funcType, false);
RichTextPainter::CustomRichText_t richComment;
richComment.underline = false;
richComment.textColor = mTextColor;
richComment.textBackground = mBackgroundColor;
richComment.flags = RichTextPainter::FlagAll;
QString comment;
bool autoComment = false;
char label[MAX_LABEL_SIZE] = "";
if(GetCommentFormat(cur_addr, comment, &autoComment))
{
if(autoComment)
{
richComment.textColor = mAutoCommentColor;
richComment.textBackground = mAutoCommentBackgroundColor;
}
else //user comment
{
richComment.textColor = mCommentColor;
richComment.textBackground = mCommentBackgroundColor;
}
richComment.text = std::move(comment);
richText.emplace_back(std::move(richComment));
}
else if(DbgGetLabelAt(cur_addr, SEG_DEFAULT, label)) // label but no comment
{
richComment.textColor = mLabelColor;
richComment.textBackground = mLabelBackgroundColor;
richComment.text = label;
richText.emplace_back(std::move(richComment));
}
if(mShowMnemonicBrief && getColumnHidden(ColMnemonicBrief))
{
mnemonicBriefRichText(richText, mInstBuffer.at(rowOffset), mMnemonicBriefColor, mMnemonicBriefBackgroundColor);
}
paintRichText(x, y, w, h, argsize, std::move(richText), rowOffset, col);
}
break;
}
return QString();
}
/************************************************************************************
Mouse Management
************************************************************************************/
/**
* @brief This method has been reimplemented. It manages the following actions:
* - Multi-rows selection
*
* @param[in] event Mouse event
*
* @return Nothing.
*/
void Disassembly::mouseMoveEvent(QMouseEvent* event)
{
//qDebug() << "Disassembly::mouseMoveEvent";
bool wAccept = true;
int y = event->y();
if(mGuiState == Disassembly::MultiRowsSelectionState)
{
//qDebug() << "State = MultiRowsSelectionState";
if((transY(y) >= 0) && (transY(y) <= this->getTableHeight()))
{
int wI = getIndexOffsetFromY(transY(y));
if(mMemPage->getSize() > 0)
{
// Bound
wI = wI >= mInstBuffer.size() ? mInstBuffer.size() - 1 : wI;
wI = wI < 0 ? 0 : wI;
if(wI >= mInstBuffer.size())
return;
dsint wRowIndex = mInstBuffer.at(wI).rva;
dsint wInstrSize = getInstructionRVA(wRowIndex, 1) - wRowIndex - 1;
if(wRowIndex < getRowCount())
{
setSingleSelection(getInitialSelection());
expandSelectionUpTo(getInstructionRVA(getInitialSelection(), 1) - 1);
if(wRowIndex > getInitialSelection()) //select down
expandSelectionUpTo(wRowIndex + wInstrSize);
else
expandSelectionUpTo(wRowIndex);
emit selectionExpanded();
updateViewport();
wAccept = false;
}
}
}
else if(y > this->height())
{
verticalScrollBar()->triggerAction(QAbstractSlider::SliderSingleStepAdd);
}
else if(transY(y) < 0)
{
verticalScrollBar()->triggerAction(QAbstractSlider::SliderSingleStepSub);
}
}
if(wAccept == true)
AbstractTableView::mouseMoveEvent(event);
}
duint Disassembly::getDisassemblyPopupAddress(int mousex, int mousey)
{
if(mHighlightingMode)
return 0; //Don't show this in highlight mode
if(getColumnIndexFromX(mousex) != 2)
return 0; //Disassembly popup for other column is undefined
int rowOffset = getIndexOffsetFromY(transY(mousey));
if(rowOffset < mInstBuffer.size())
{
ZydisTokenizer::SingleToken token;
auto & instruction = mInstBuffer.at(rowOffset);
if(ZydisTokenizer::TokenFromX(instruction.tokens, token, mousex, mFontMetrics))
{
duint addr = token.value.value;
bool isCodePage = DbgFunctions()->MemIsCodePage(addr, false);
if(!isCodePage && instruction.branchDestination)
{
addr = instruction.branchDestination;
isCodePage = DbgFunctions()->MemIsCodePage(addr, false);
}
if(isCodePage && (addr - mMemPage->getBase() < mInstBuffer.front().rva || addr - mMemPage->getBase() > mInstBuffer.back().rva))
{
return addr;
}
}
}
return 0;
}
/**
* @brief This method has been reimplemented. It manages the following actions:
* - Multi-rows selection
*
* @param[in] event Mouse event
*
* @return Nothing.
*/
void Disassembly::mousePressEvent(QMouseEvent* event)
{
bool wAccept = false;
if(mHighlightingMode || mPermanentHighlightingMode)
{
if(getColumnIndexFromX(event->x()) == 2) //click in instruction column
{
int rowOffset = getIndexOffsetFromY(transY(event->y()));
if(rowOffset < mInstBuffer.size())
{
ZydisTokenizer::SingleToken token;
if(ZydisTokenizer::TokenFromX(mInstBuffer.at(rowOffset).tokens, token, event->x(), mFontMetrics))
{
if(ZydisTokenizer::IsHighlightableToken(token))
{
if(!ZydisTokenizer::TokenEquals(&token, &mHighlightToken) || event->button() == Qt::RightButton)
mHighlightToken = token;
else
mHighlightToken = ZydisTokenizer::SingleToken();
}
else if(!mPermanentHighlightingMode)
{
mHighlightToken = ZydisTokenizer::SingleToken();
}
}
else if(!mPermanentHighlightingMode)
{
mHighlightToken = ZydisTokenizer::SingleToken();
}
}
}
else if(!mPermanentHighlightingMode)
{
mHighlightToken = ZydisTokenizer::SingleToken();
}
if(!mPermanentHighlightingMode)
return;
}
if(DbgIsDebugging() && ((event->buttons() & Qt::LeftButton) != 0) && ((event->buttons() & Qt::RightButton) == 0))
{
if(getGuiState() == AbstractTableView::NoState)
{
if(event->y() > getHeaderHeight())
{
dsint wIndex = getIndexOffsetFromY(transY(event->y()));
if(mInstBuffer.size() > wIndex && wIndex >= 0)
{
dsint wRowIndex = mInstBuffer.at(wIndex).rva;
dsint wInstrSize = mInstBuffer.at(wIndex).length - 1;
if(!(event->modifiers() & Qt::ShiftModifier)) //SHIFT pressed
setSingleSelection(wRowIndex);
if(getSelectionStart() > wRowIndex) //select up
{
setSingleSelection(getInitialSelection());
expandSelectionUpTo(getInstructionRVA(getInitialSelection(), 1) - 1);
expandSelectionUpTo(wRowIndex);
}
else //select down
{
setSingleSelection(getInitialSelection());
expandSelectionUpTo(wRowIndex + wInstrSize);
}
mGuiState = Disassembly::MultiRowsSelectionState;
updateViewport();
wAccept = true;
}
}
}
}
if(wAccept == false)
AbstractTableView::mousePressEvent(event);
}
/**
* @brief This method has been reimplemented. It manages the following actions:
* - Multi-rows selection
*
* @param[in] event Mouse event
*
* @return Nothing.
*/
void Disassembly::mouseReleaseEvent(QMouseEvent* event)
{
bool wAccept = true;
if((event->buttons() & Qt::LeftButton) == 0)
{
if(mGuiState == Disassembly::MultiRowsSelectionState)
{
mGuiState = Disassembly::NoState;
updateViewport();
wAccept = false;
}
}
if((event->button() & Qt::BackButton) != 0)
{
wAccept = true;
historyPrevious();
}
else if((event->button() & Qt::ForwardButton) != 0)
{
wAccept = true;
historyNext();
}
if(wAccept == true)
AbstractTableView::mouseReleaseEvent(event);
}
void Disassembly::wheelEvent(QWheelEvent* event)
{
if(event->modifiers() == Qt::NoModifier)
AbstractTableView::wheelEvent(event);
else if(event->modifiers() == Qt::ControlModifier) // Zoom
Config()->zoomFont("Disassembly", event);
}
/************************************************************************************
Keyboard Management
************************************************************************************/
/**
* @brief This method has been reimplemented. It processes the Up/Down key events.
*
* @param[in] event Key event
*
* @return Nothing.
*/
void Disassembly::keyPressEvent(QKeyEvent* event)
{
int key = event->key();
if(event->modifiers() == (Qt::ControlModifier | Qt::AltModifier))
{
ShowDisassemblyPopup(0, 0, 0);
if(key == Qt::Key_Left)
{
setTableOffset(getTableOffset() - 1);
}
else if(key == Qt::Key_Right)
{
setTableOffset(getTableOffset() + 1);
}
updateViewport();
}
else if(key == Qt::Key_Up || key == Qt::Key_Down)
{
ShowDisassemblyPopup(0, 0, 0);
dsint botRVA = getTableOffset();
dsint topRVA = getInstructionRVA(getTableOffset(), getNbrOfLineToPrint() - 1);
bool expand = false;
if(event->modifiers() & Qt::ShiftModifier) //SHIFT pressed
expand = true;
dsint initialStart = getSelectionStart();
if(key == Qt::Key_Up)
selectPrevious(expand); //TODO: fix this shit to actually go to whatever the previous instruction shows
else
selectNext(expand);
bool expandedUp = initialStart != getSelectionStart();
dsint modifiedSelection = expandedUp ? getSelectionStart() : getSelectionEnd();
if(modifiedSelection < botRVA)
{
setTableOffset(modifiedSelection);
}
else if(modifiedSelection >= topRVA)
{
setTableOffset(getInstructionRVA(modifiedSelection, -getNbrOfLineToPrint() + 2));
}
updateViewport();
}
else if(key == Qt::Key_Return || key == Qt::Key_Enter)
{
ShowDisassemblyPopup(0, 0, 0);
// Follow branch instruction
duint dest = DbgGetBranchDestination(rvaToVa(getInitialSelection()));
if(DbgMemIsValidReadPtr(dest))
{
gotoAddress(dest);
return;
}
// Follow memory operand in dump
DISASM_INSTR instr;
DbgDisasmAt(rvaToVa(getInitialSelection()), &instr);
for(int op = instr.argcount - 1; op >= 0; op--)
{
if(instr.arg[op].type == arg_memory)
{
dest = instr.arg[op].value;
if(DbgMemIsValidReadPtr(dest))
{
if(instr.arg[op].segment == SEG_SS)
DbgCmdExec(QString("sdump %1").arg(ToPtrString(dest)));
else
DbgCmdExec(QString("dump %1").arg(ToPtrString(dest)));
return;
}
}
}
// Follow constant in dump
for(int op = instr.argcount - 1; op >= 0; op--)
{
if(instr.arg[op].type == arg_normal)
{
dest = instr.arg[op].value;
if(DbgMemIsValidReadPtr(dest))
{
DbgCmdExec(QString("dump %1").arg(ToPtrString(dest)));
return;
}
}
}
}
else
AbstractTableView::keyPressEvent(event);
}
/************************************************************************************
ScrollBar Management
***********************************************************************************/
/**
* @brief This method has been reimplemented. It realigns the slider on real instructions except
* when the type is QAbstractSlider::SliderNoAction. This type (QAbstractSlider::SliderNoAction)
* is used to force the disassembling at a specific RVA.
*
* @param[in] type Type of action
* @param[in] value Old table offset
* @param[in] delta Scrollbar value delta compared to the previous state
*
* @return Return the value of the new table offset.
*/
dsint Disassembly::sliderMovedHook(int type, dsint value, dsint delta)
{
ShowDisassemblyPopup(0, 0, 0);
// QAbstractSlider::SliderNoAction is used to disassembe at a specific address
if(type == QAbstractSlider::SliderNoAction)
return value + delta;
// If it's a slider action, disassemble one instruction back and one instruction next in order to be aligned on a real instruction
if(type == QAbstractSlider::SliderMove)
{
dsint wNewValue = 0;
if(value + delta > 0)
{
wNewValue = getInstructionRVA(value + delta, -1);
wNewValue = getInstructionRVA(wNewValue, 1);
}
return wNewValue;
}
// For other actions, disassemble according to the delta
return getInstructionRVA(value, delta);
}
/************************************************************************************
Jumps Graphic
************************************************************************************/
/**
* @brief This method paints the graphic for jumps.
*
* @param[in] painter Pointer to the painter that allows painting by its own
* @param[in] x Rectangle x
* @param[in] y Rectangle y
* @param[in] addr RVA of address to process
*
* @return Nothing.
*/
int Disassembly::paintJumpsGraphic(QPainter* painter, int x, int y, dsint addr, bool isjmp)
{
dsint selHeadRVA = mSelection.fromIndex;
dsint rva = addr;
duint curVa = rvaToVa(addr);
duint selVa = rvaToVa(mSelection.firstSelectedIndex);
Instruction_t instruction = DisassembleAt(selHeadRVA);
auto branchType = instruction.branchType;
bool showXref = false;
GraphicDump wPict = GD_Nothing;
if(branchType != Instruction_t::None && branchType != Instruction_t::Call)
{
dsint base = mMemPage->getBase();
dsint destVA = DbgGetBranchDestination(rvaToVa(selHeadRVA));
if(destVA >= base && destVA < base + (dsint)mMemPage->getSize())
{
destVA -= base;
if(destVA < selHeadRVA)
{
if(rva == destVA)
wPict = GD_HeadFromBottom;
else if(rva > destVA && rva < selHeadRVA)
wPict = GD_Vert;
else if(rva == selHeadRVA)
wPict = GD_FootToTop;
}
else if(destVA > selHeadRVA)
{
if(rva == selHeadRVA)
wPict = GD_FootToBottom;
else if(rva > selHeadRVA && rva < destVA)
wPict = GD_Vert;
else if(rva == destVA)
wPict = GD_HeadFromTop;
}
}
}
else if(mXrefInfo.refcount > 0)
{
// TODO: bad performance for sure, this code is also doing things in a super weird order...
duint max = selVa, min = selVa;
showXref = true;
int jmpcount = 0;
for(duint i = 0; i < mXrefInfo.refcount; i++)
{
if(mXrefInfo.references[i].type != XREF_JMP)
continue;
jmpcount++;
if(curVa == mXrefInfo.references[i].addr)
wPict = GD_VertHori;
if(mXrefInfo.references[i].addr > max)
max = mXrefInfo.references[i].addr;
if(mXrefInfo.references[i].addr < min)
min = mXrefInfo.references[i].addr;
}
if(jmpcount)
{
if(curVa == selVa)
{
if(max == selVa)
{
wPict = GD_HeadFromTop;
}
else if(min == selVa)
{
wPict = GD_HeadFromBottom;
}
else if(max > selVa && min < selVa)
{
wPict = GD_HeadFromBoth;
}
}
else if(curVa < selVa && curVa == min)
{
wPict = GD_FootToBottom;
}
else if(curVa > selVa && curVa == max)
{
wPict = GD_FootToTop;
}
if(wPict == GD_Nothing && curVa > min && curVa < max)
wPict = GD_Vert;
}
}
GraphicJumpDirection curInstDir = GJD_Nothing;
if(isjmp)
{
duint curInstDestination = DbgGetBranchDestination(curVa);
if(curInstDestination == 0 || curVa == curInstDestination)
{
curInstDir = GJD_Nothing;
}
else if(curInstDestination < curVa)
{
curInstDir = GJD_Up;
}
else
{
curInstDir = GJD_Down;
}
}
int halfRow = getRowHeight() / 2 + 1;
painter->setPen(mConditionalTruePen);
if(curInstDir == GJD_Up)
{
QPoint wPoints[] =
{
QPoint(x, y + halfRow + 1),
QPoint(x + 2, y + halfRow - 1),
QPoint(x + 4, y + halfRow + 1),
};
painter->drawPolyline(wPoints, 3);
}
else if(curInstDir == GJD_Down)
{
QPoint wPoints[] =
{
QPoint(x, y + halfRow - 1),
QPoint(x + 2, y + halfRow + 1),
QPoint(x + 4, y + halfRow - 1),
};
painter->drawPolyline(wPoints, 3);
}
x += 8;
if(showXref)
{
painter->setPen(mUnconditionalPen);
}
else
{
bool bIsExecute = DbgIsJumpGoingToExecute(rvaToVa(instruction.rva));
if(branchType == Instruction_t::Unconditional) //unconditional
{
painter->setPen(mUnconditionalPen);
}
else
{
if(bIsExecute)
painter->setPen(mConditionalTruePen);
else
painter->setPen(mConditionalFalsePen);
}
}
if(wPict == GD_Vert)
{
painter->drawLine(x, y, x, y + getRowHeight());
}
else if(wPict == GD_FootToBottom)
{
painter->drawLine(x, y + halfRow, x + 5, y + halfRow);
painter->drawLine(x, y + halfRow, x, y + getRowHeight());
}
else if(wPict == GD_FootToTop)
{
painter->drawLine(x, y + halfRow, x + 5, y + halfRow);
painter->drawLine(x, y, x, y + halfRow);
}
else if(wPict == GD_HeadFromBottom)
{
QPoint wPoints[] =
{
QPoint(x + 3, y + halfRow - 2),
QPoint(x + 5, y + halfRow),
QPoint(x + 3, y + halfRow + 2),
};
painter->drawLine(x, y + halfRow, x + 5, y + halfRow);
painter->drawLine(x, y + halfRow, x, y + getRowHeight());
painter->drawPolyline(wPoints, 3);
}
else if(wPict == GD_HeadFromTop)
{
QPoint wPoints[] =
{
QPoint(x + 3, y + halfRow - 2),
QPoint(x + 5, y + halfRow),
QPoint(x + 3, y + halfRow + 2),
};
painter->drawLine(x, y + halfRow, x + 5, y + halfRow);
painter->drawLine(x, y, x, y + halfRow);
painter->drawPolyline(wPoints, 3);
}
else if(wPict == GD_HeadFromBoth)
{
QPoint wPoints[] =
{
QPoint(x + 3, y + halfRow - 2),
QPoint(x + 5, y + halfRow),
QPoint(x + 3, y + halfRow + 2),
};
painter->drawLine(x, y + halfRow, x + 5, y + halfRow);
painter->drawLine(x, y, x, y + getRowHeight());
painter->drawPolyline(wPoints, 3);
}
else if(wPict == GD_VertHori)
{
painter->drawLine(x, y + halfRow, x + 5, y + halfRow);
painter->drawLine(x, y, x, y + getRowHeight());
}
return 15;
}
/************************************************************************************
Function Graphic
************************************************************************************/
/**
* @brief This method paints the graphic for functions/loops.
*
* @param[in] painter Pointer to the painter that allows painting by its own
* @param[in] x Rectangle x
* @param[in] y Rectangle y
* @param[in] funcType Type of drawing to make
*
* @return Width of the painted data.
*/
int Disassembly::paintFunctionGraphic(QPainter* painter, int x, int y, Function_t funcType, bool loop)
{
if(loop && funcType == Function_none)
return 0;
if(loop)
painter->setPen(mLoopPen); //thick black line
else
painter->setPen(mFunctionPen); //thick black line
int height = getRowHeight();
int x_add = 5;
int y_add = 4;
int end_add = 2;
int line_width = 3;
if(loop)
{
end_add = -1;
x_add = 4;
}
switch(funcType)
{
case Function_single:
{
if(loop)
y_add = height / 2 + 1;
painter->drawLine(x + x_add + line_width, y + y_add, x + x_add, y + y_add);
painter->drawLine(x + x_add, y + y_add, x + x_add, y + height - y_add - 1);
if(loop)
y_add = height / 2 - 1;
painter->drawLine(x + x_add, y + height - y_add, x + x_add + line_width, y + height - y_add);
}
break;
case Function_start:
{
if(loop)
y_add = height / 2 + 1;
painter->drawLine(x + x_add + line_width, y + y_add, x + x_add, y + y_add);
painter->drawLine(x + x_add, y + y_add, x + x_add, y + height);
}
break;
case Function_middle:
{
painter->drawLine(x + x_add, y, x + x_add, y + height);
}
break;
case Function_loop_entry:
{
int trisize = 2;
int y_start = (height - trisize * 2) / 2 + y;
painter->drawLine(x + x_add, y_start, x + trisize + x_add, y_start + trisize);
painter->drawLine(x + trisize + x_add, y_start + trisize, x + x_add, y_start + trisize * 2);
painter->drawLine(x + x_add, y, x + x_add, y_start - 1);
painter->drawLine(x + x_add, y_start + trisize * 2 + 2, x + x_add, y + height);
}
break;
case Function_end:
{
if(loop)
y_add = height / 2 - 1;
painter->drawLine(x + x_add, y, x + x_add, y + height - y_add);
painter->drawLine(x + x_add, y + height - y_add, x + x_add + line_width, y + height - y_add);
}
break;
case Function_none:
{
}
break;
}
return x_add + line_width + end_add;
}
void Disassembly::paintRichText(int x, int y, int w, int h, int xinc, const RichTextPainter::List & richText, int rowOffset, int column)
{
RichTextInfo & info = mRichText[column][rowOffset];
info.x = x;
info.y = y;
info.w = w;
info.h = h;
info.xinc = xinc;
info.richText = richText;
info.alive = true;
}
void Disassembly::paintRichText(int x, int y, int w, int h, int xinc, RichTextPainter::List && richText, int rowOffset, int column)
{
RichTextInfo & info = mRichText[column][rowOffset];
info.x = x;
info.y = y;
info.w = w;
info.h = h;
info.xinc = xinc;
info.richText = std::move(richText);
info.alive = true;
}
/************************************************************************************
Instructions Management
***********************************************************************************/
/**
* @brief Returns the RVA of count-th instructions before the given instruction RVA.
*
* @param[in] rva Instruction RVA
* @param[in] count Instruction count
*
* @return RVA of count-th instructions before the given instruction RVA.
*/
dsint Disassembly::getPreviousInstructionRVA(dsint rva, duint count)
{
QByteArray wBuffer;
dsint wBottomByteRealRVA;
dsint wVirtualRVA;
dsint wMaxByteCountToRead;
wBottomByteRealRVA = (dsint)rva - 16 * (count + 3);
if(mCodeFoldingManager)
{
if(mCodeFoldingManager->isFolded(rvaToVa(wBottomByteRealRVA)))
{
wBottomByteRealRVA = mCodeFoldingManager->getFoldBegin(wBottomByteRealRVA) - mMemPage->getBase() - 16 * (count + 3);
}
}
wBottomByteRealRVA = wBottomByteRealRVA < 0 ? 0 : wBottomByteRealRVA;
wVirtualRVA = (dsint)rva - wBottomByteRealRVA;
wMaxByteCountToRead = wVirtualRVA + 1 + 16;
wBuffer.resize(wMaxByteCountToRead);
mMemPage->read(wBuffer.data(), wBottomByteRealRVA, wBuffer.size());
dsint addr = mDisasm->DisassembleBack((byte_t*)wBuffer.data(), rvaToVa(wBottomByteRealRVA), wBuffer.size(), wVirtualRVA, count);
addr += rva - wVirtualRVA;
return addr;
}
/**
* @brief Returns the RVA of count-th instructions after the given instruction RVA.
*
* @param[in] rva Instruction RVA
* @param[in] count Instruction count
* @param[in] isGlobal Whether it rejects rva beyond current page
*
* @return RVA of count-th instructions after the given instruction RVA.
*/
dsint Disassembly::getNextInstructionRVA(dsint rva, duint count, bool isGlobal)
{
QByteArray wBuffer;
dsint wRemainingBytes;
dsint wMaxByteCountToRead;
dsint wNewRVA;
if(!isGlobal)
{
if(mMemPage->getSize() < (duint)rva)
return rva;
wRemainingBytes = mMemPage->getSize() - rva;
wMaxByteCountToRead = 16 * (count + 1);
if(mCodeFoldingManager)
wMaxByteCountToRead += mCodeFoldingManager->getFoldedSize(rvaToVa(rva), rvaToVa(rva + wMaxByteCountToRead));
wMaxByteCountToRead = wRemainingBytes > wMaxByteCountToRead ? wMaxByteCountToRead : wRemainingBytes;
}
else
{
wMaxByteCountToRead = 16 * (count + 1);
if(mCodeFoldingManager)
wMaxByteCountToRead += mCodeFoldingManager->getFoldedSize(rvaToVa(rva), rvaToVa(rva + wMaxByteCountToRead));
}
wBuffer.resize(wMaxByteCountToRead);
mMemPage->read(wBuffer.data(), rva, wBuffer.size());
wNewRVA = mDisasm->DisassembleNext((byte_t*)wBuffer.data(), rvaToVa(rva), wBuffer.size(), 0, count);
wNewRVA += rva;
return wNewRVA;
}
/**
* @brief Returns the RVA of count-th instructions before/after (depending on the sign) the given instruction RVA.
*
* @param[in] rva Instruction RVA
* @param[in] count Instruction count
*
* @return RVA of count-th instructions before/after the given instruction RVA.
*/
dsint Disassembly::getInstructionRVA(dsint index, dsint count)
{
dsint wAddr = 0;
if(count == 0)
wAddr = index;
if(count < 0)
wAddr = getPreviousInstructionRVA(index, qAbs(count));
else if(count > 0)
wAddr = getNextInstructionRVA(index, qAbs(count));
if(wAddr < 0)
wAddr = 0;
else if(wAddr > getRowCount() - 1)
wAddr = getRowCount() - 1;
return wAddr;
}
/**
* @brief Disassembles the instruction at the given RVA.
*
* @param[in] rva RVA of instruction to disassemble
*
* @return Return the disassembled instruction.
*/
Instruction_t Disassembly::DisassembleAt(dsint rva)
{
if(mMemPage->getSize() < (duint)rva)
return Instruction_t();
QByteArray wBuffer;
duint base = mMemPage->getBase();
duint wMaxByteCountToRead = 16 * 2;
// Bounding
auto size = getSize();
if(!size)
size = rva + wMaxByteCountToRead * 2;
if(mCodeFoldingManager)
wMaxByteCountToRead += mCodeFoldingManager->getFoldedSize(rvaToVa(rva), rvaToVa(rva + wMaxByteCountToRead));
wMaxByteCountToRead = wMaxByteCountToRead > (size - rva) ? (size - rva) : wMaxByteCountToRead;
if(!wMaxByteCountToRead)
return Instruction_t();
wBuffer.resize(wMaxByteCountToRead);
if(!mMemPage->read(wBuffer.data(), rva, wBuffer.size()))
return Instruction_t();
return mDisasm->DisassembleAt((byte_t*)wBuffer.data(), wBuffer.size(), base, rva);
}
/**
* @brief Disassembles the instruction count instruction afterc the instruction at the given RVA.
* Count can be positive or negative.
*
* @param[in] rva RVA of reference instruction
* @param[in] count Number of instruction
*
* @return Return the disassembled instruction.
*/
Instruction_t Disassembly::DisassembleAt(dsint rva, dsint count)
{
rva = getNextInstructionRVA(rva, count);
return DisassembleAt(rva);
}
/************************************************************************************
Selection Management
************************************************************************************/
void Disassembly::expandSelectionUpTo(dsint to)
{
if(to < mSelection.firstSelectedIndex)
{
mSelection.fromIndex = to;
}
else if(to > mSelection.firstSelectedIndex)
{
mSelection.toIndex = to;
}
else if(to == mSelection.firstSelectedIndex)
{
setSingleSelection(to);
}
}
void Disassembly::setSingleSelection(dsint index)
{
mSelection.firstSelectedIndex = index;
mSelection.fromIndex = index;
mSelection.toIndex = getInstructionRVA(mSelection.fromIndex, 1) - 1;
emit selectionChanged(rvaToVa(index));
}
dsint Disassembly::getInitialSelection() const
{
return mSelection.firstSelectedIndex;
}
dsint Disassembly::getSelectionSize() const
{
return mSelection.toIndex - mSelection.fromIndex + 1;
}
dsint Disassembly::getSelectionStart() const
{
return mSelection.fromIndex;
}
dsint Disassembly::getSelectionEnd() const
{
return mSelection.toIndex;
}
void Disassembly::selectionChangedSlot(dsint Va)
{
if(mXrefInfo.refcount != 0)
{
BridgeFree(mXrefInfo.references);
mXrefInfo.refcount = 0;
}
if(DbgIsDebugging())
DbgXrefGet(Va, &mXrefInfo);
}
void Disassembly::selectNext(bool expand)
{
dsint wAddr;
dsint wStart = getInstructionRVA(getSelectionStart(), 1) - 1;
dsint wInstrSize;
if(expand)
{
if(getSelectionEnd() == getInitialSelection() && wStart != getSelectionEnd()) //decrease down
{
wAddr = getInstructionRVA(getSelectionStart(), 1);
expandSelectionUpTo(wAddr);
}
else //expand down
{
wAddr = getSelectionEnd() + 1;
wInstrSize = getInstructionRVA(wAddr, 1) - 1;
expandSelectionUpTo(wInstrSize);
}
}
else //select next instruction
{
wAddr = getSelectionEnd() + 1;
setSingleSelection(wAddr);
wInstrSize = getInstructionRVA(wAddr, 1) - 1;
expandSelectionUpTo(wInstrSize);
}
}
void Disassembly::selectPrevious(bool expand)
{
dsint wAddr;
dsint wStart;
dsint wInstrSize;
wStart = getInstructionRVA(getSelectionStart(), 1) - 1;
if(expand)
{
if(getSelectionStart() == getInitialSelection() && wStart != getSelectionEnd()) //decrease up
{
wAddr = getInstructionRVA(getSelectionEnd() + 1, -2);
wInstrSize = getInstructionRVA(wAddr, 1) - 1;
expandSelectionUpTo(wInstrSize);
}
else //expand up
{
wAddr = getInstructionRVA(wStart + 1, -2);
expandSelectionUpTo(wAddr);
}
}
else
{
wAddr = getInstructionRVA(getSelectionStart(), -1);
setSingleSelection(wAddr);
wInstrSize = getInstructionRVA(wAddr, 1) - 1;
expandSelectionUpTo(wInstrSize);
}
}
bool Disassembly::isSelected(dsint base, dsint offset)
{
dsint wAddr = base;
if(offset < 0)
wAddr = getPreviousInstructionRVA(getTableOffset(), offset);
else if(offset > 0)
wAddr = getNextInstructionRVA(getTableOffset(), offset);
if(wAddr >= mSelection.fromIndex && wAddr <= mSelection.toIndex)
return true;
else
return false;
}
bool Disassembly::isSelected(QList<Instruction_t>* buffer, int index) const
{
if(buffer->size() > 0 && index >= 0 && index < buffer->size())
{
if((dsint)buffer->at(index).rva >= mSelection.fromIndex && (dsint)buffer->at(index).rva <= mSelection.toIndex)
return true;
else
return false;
}
else
{
return false;
}
}
duint Disassembly::getSelectedVa() const
{
// Wrapper around commonly used code:
// Converts the selected index to a valid virtual address
return rvaToVa(getInitialSelection());
}
/************************************************************************************
Update/Reload/Refresh/Repaint
************************************************************************************/
void Disassembly::prepareDataCount(const QList<dsint> & wRVAs, QList<Instruction_t>* instBuffer)
{
instBuffer->clear();
Instruction_t wInst;
for(int wI = 0; wI < wRVAs.count(); wI++)
{
wInst = DisassembleAt(wRVAs.at(wI));
instBuffer->append(wInst);
}
}
void Disassembly::prepareDataRange(dsint startRva, dsint endRva, const std::function<bool(int, const Instruction_t &)> & disassembled)
{
dsint wAddrPrev = startRva;
dsint wAddr = wAddrPrev;
int i = 0;
while(true)
{
if(wAddr > endRva)
break;
wAddrPrev = wAddr;
auto wInst = DisassembleAt(wAddr);
wAddr = getNextInstructionRVA(wAddr, 1);
if(wAddr == wAddrPrev)
break;
if(!disassembled(i++, wInst))
break;
}
}
RichTextPainter::List Disassembly::getRichBytes(const Instruction_t & instr, bool isSelected) const
{
RichTextPainter::List richBytes;
std::vector<std::pair<size_t, bool>> realBytes;
formatOpcodeString(instr, richBytes, realBytes);
dsint cur_addr = rvaToVa(instr.rva);
if(!richBytes.empty() && richBytes.back().text.endsWith(' '))
richBytes.back().text.chop(1); //remove trailing space if exists
auto selectionFromVa = rvaToVa(mSelection.fromIndex);
auto selectionToVa = rvaToVa(mSelection.toIndex);
for(size_t i = 0; i < richBytes.size(); i++)
{
auto byteIdx = realBytes[i].first;
auto byteAddr = cur_addr + byteIdx;
auto isReal = realBytes[i].second;
RichTextPainter::CustomRichText_t & curByte = richBytes.at(i);
DBGRELOCATIONINFO relocInfo;
curByte.underlineColor = mDisassemblyRelocationUnderlineColor;
if(DbgFunctions()->ModRelocationAtAddr(byteAddr, &relocInfo))
{
bool prevInSameReloc = relocInfo.rva < byteAddr - DbgFunctions()->ModBaseFromAddr(byteAddr);
curByte.underline = isReal;
curByte.underlineConnectPrev = i > 0 && prevInSameReloc;
}
else
{
curByte.underline = false;
curByte.underlineConnectPrev = false;
}
DBGPATCHINFO patchInfo;
if(isReal && DbgFunctions()->PatchGetEx(byteAddr, &patchInfo))
{
if((unsigned char)(instr.dump.at((int)byteIdx)) == patchInfo.newbyte)
{
curByte.textColor = mModifiedBytesColor;
curByte.textBackground = mModifiedBytesBackgroundColor;
}
else
{
curByte.textColor = mRestoredBytesColor;
curByte.textBackground = mRestoredBytesBackgroundColor;
}
}
else
{
curByte.textColor = mBytesColor;
curByte.textBackground = mBytesBackgroundColor;
}
if(curByte.textBackground.alpha() == 0)
{
auto byteSelected = byteAddr >= selectionFromVa && byteAddr <= selectionToVa;
if(isSelected && !byteSelected)
curByte.textBackground = mBackgroundColor;
else if(!isSelected && byteSelected)
curByte.textBackground = mSelectionColor;
}
}
if(mCodeFoldingManager && mCodeFoldingManager->isFolded(cur_addr))
{
RichTextPainter::CustomRichText_t curByte;
curByte.textColor = mBytesColor;
curByte.textBackground = mBytesBackgroundColor;
curByte.underlineColor = mDisassemblyRelocationUnderlineColor;
curByte.underlineWidth = 1;
curByte.flags = RichTextPainter::FlagAll;
curByte.underline = false;
curByte.textColor = mBytesColor;
curByte.textBackground = mBytesBackgroundColor;
curByte.text = "...";
richBytes.push_back(curByte);
}
return richBytes;
}
void Disassembly::prepareData()
{
dsint wViewableRowsCount = getViewableRowsCount();
mInstBuffer.clear();
mInstBuffer.reserve(wViewableRowsCount);
dsint wAddrPrev = getTableOffset();
dsint wAddr = wAddrPrev;
Instruction_t wInst;
int wCount = 0;
for(int wI = 0; wI < wViewableRowsCount && getRowCount() > 0; wI++)
{
wAddrPrev = wAddr;
wInst = DisassembleAt(wAddr);
wAddr = getNextInstructionRVA(wAddr, 1);
if(wAddr == wAddrPrev)
break;
mInstBuffer.append(wInst);
wCount++;
}
setNbrOfLineToPrint(wCount);
mRichText.resize(getColumnCount());
for(size_t i = 0; i < mRichText.size(); i++)
{
mRichText[i].resize(wViewableRowsCount);
for(size_t j = 0; j < mRichText[i].size(); j++)
{
mRichText[i][j].alive = false;
}
}
}
void Disassembly::reloadData()
{
emit selectionChanged(rvaToVa(mSelection.firstSelectedIndex));
AbstractTableView::reloadData();
}
void Disassembly::paintEvent(QPaintEvent* event)
{
AbstractTableView::paintEvent(event);
if(!mAllowPainting)
return;
// Delay paint the rich text
QPainter painter(this->viewport());
painter.setFont(font());
int x = -horizontalScrollBar()->value();
for(int column = 0; column < (int)mRichText.size(); column++)
{
int w = getColumnWidth(column);
int h = getViewableRowsCount() * getRowHeight();
const bool optimizationEnabled = false;
if(optimizationEnabled)
{
QString columnText;
columnText.reserve(getColumnWidth(column) * getViewableRowsCount() / getCharWidth());
QVector<QTextLayout::FormatRange> selections;
for(int rowOffset = 0; rowOffset < (int)mRichText[column].size(); rowOffset++)
{
if(rowOffset > 0)
columnText += QChar::LineSeparator;
const RichTextInfo & info = mRichText[column][rowOffset];
if(!info.alive)
continue;
for(const RichTextPainter::CustomRichText_t & curRichText : info.richText)
{
if(curRichText.text.isEmpty())
continue;
if(mFormatCache.empty())
{
mFormatCache.emplace_back();
}
QTextLayout::FormatRange range = std::move(mFormatCache.back());
mFormatCache.pop_back();
range.start = columnText.length();
range.length = curRichText.text.length();
columnText += curRichText.text;
QTextCharFormat & format = range.format;
switch(curRichText.flags)
{
case RichTextPainter::FlagNone: //defaults
{
format.clearForeground();
format.clearBackground();
}
break;
case RichTextPainter::FlagColor: //color only
{
format.setForeground(curRichText.textColor);
format.clearBackground();
}
break;
case RichTextPainter::FlagBackground: //background only
{
if(curRichText.textBackground.alpha())
{
format.setBackground(curRichText.textBackground);
}
else
{
format.clearBackground();
}
format.clearForeground();
}
break;
case RichTextPainter::FlagAll: //color+background
{
if(curRichText.textBackground.alpha())
{
format.setBackground(curRichText.textBackground);
}
else
{
format.clearBackground();
}
format.setForeground(curRichText.textColor);
}
break;
}
if(curRichText.underline)
{
range.format.setFontUnderline(true);
range.format.setUnderlineColor(curRichText.underlineColor);
}
else
{
range.format.setFontUnderline(false);
}
selections.push_back(std::move(range));
}
}
QTextOption textOption;
textOption.setWrapMode(QTextOption::NoWrap);
mTextLayout.setTextOption(textOption);
mTextLayout.setFormats(selections);
while(!selections.empty())
{
mFormatCache.push_back(std::move(selections.back()));
selections.pop_back();
}
mTextLayout.setText(columnText);
mTextLayout.beginLayout();
int rowHeight = getRowHeight();
for(int i = 0, y = 0; ; i++, y += rowHeight)
{
QTextLine line = mTextLayout.createLine();
if(!line.isValid())
break;
const RichTextInfo & info = mRichText[column][i];
line.setPosition(QPointF(info.xinc, y));
}
mTextLayout.endLayout();
QPixmap pixmap(w - 2, h);
pixmap.fill(Qt::transparent);
QPainter clippedPainter;
clippedPainter.begin(&pixmap);
mTextLayout.draw(&clippedPainter, QPointF(0, 0));
clippedPainter.end();
painter.drawPixmap(x, 0, pixmap);
}
else
{
for(int rowOffset = 0; rowOffset < (int)mRichText[column].size(); rowOffset++)
{
const RichTextInfo & info = mRichText[column][rowOffset];
if(info.alive)
RichTextPainter::paintRichText(&painter, info.x, info.y, info.w, info.h, info.xinc, info.richText, mFontMetrics);
}
}
x += w;
}
}
/************************************************************************************
Public Methods
************************************************************************************/
duint Disassembly::rvaToVa(dsint rva) const
{
return mMemPage->va(rva);
}
void Disassembly::gotoAddress(duint addr)
{
disassembleAt(addr, true, -1);
if(mIsMain)
{
// Update window title
DbgCmdExecDirect(QString("guiupdatetitle %1").arg(ToPtrString(addr)));
}
GuiUpdateAllViews();
}
void Disassembly::disassembleAt(dsint parVA, bool history, dsint newTableOffset)
{
duint wSize;
auto wBase = DbgMemFindBaseAddr(parVA, &wSize);
unsigned char test;
if(!wBase || !wSize || !DbgMemRead(parVA, &test, sizeof(test)))
return;
dsint wRVA = parVA - wBase;
HistoryData newHistory;
//VA history
if(history)
{
//truncate everything right from the current VA
if(mVaHistory.size() && mCurrentVa < mVaHistory.size() - 1) //mCurrentVa is not the last
mVaHistory.erase(mVaHistory.begin() + mCurrentVa + 1, mVaHistory.end());
//NOTE: mCurrentVa always points to the last entry of the list
//add the currently selected address to the history
dsint selectionVA = rvaToVa(getInitialSelection()); //currently selected VA
dsint selectionTableOffset = getTableOffset();
if(selectionVA && mVaHistory.size() && mVaHistory.last().va != selectionVA) //do not have 2x the same va in a row
{
mCurrentVa++;
newHistory.va = selectionVA;
newHistory.tableOffset = selectionTableOffset;
mVaHistory.push_back(newHistory);
}
}
// Set base and size (Useful when memory page changed)
mMemPage->setAttributes(wBase, wSize);
mDisasm->getEncodeMap()->setMemoryRegion(wBase);
if(mRvaDisplayEnabled && mMemPage->getBase() != mRvaDisplayPageBase)
mRvaDisplayEnabled = false;
setRowCount(wSize);
setSingleSelection(wRVA); // Selects disassembled instruction
dsint wInstrSize = getInstructionRVA(wRVA, 1) - wRVA - 1;
expandSelectionUpTo(wRVA + wInstrSize);
if(newTableOffset == -1) //nothing specified
{
// Update table offset depending on the location of the instruction to disassemble
if(mInstBuffer.size() > 0 && wRVA >= (dsint)mInstBuffer.first().rva && wRVA < (dsint)mInstBuffer.last().rva)
{
int wI;
bool wIsAligned = false;
// Check if the new RVA is aligned on an instruction from the cache (buffer)
for(wI = 0; wI < mInstBuffer.size(); wI++)
{
if(mInstBuffer.at(wI).rva == wRVA)
{
wIsAligned = true;
break;
}
}
if(wIsAligned == true)
{
updateViewport();
}
else
{
setTableOffset(wRVA);
}
}
else if(mInstBuffer.size() > 0 && wRVA == (dsint)mInstBuffer.last().rva)
{
setTableOffset(mInstBuffer.first().rva + mInstBuffer.first().length);
}
else
{
setTableOffset(wRVA);
}
if(history)
{
//new disassembled address
newHistory.va = parVA;
newHistory.tableOffset = getTableOffset();
if(mVaHistory.size())
{
if(mVaHistory.last().va != parVA) //not 2x the same va in history
{
if(mVaHistory.size() >= 1024) //max 1024 in the history
{
mCurrentVa--;
mVaHistory.erase(mVaHistory.begin()); //remove the oldest element
}
mCurrentVa++;
mVaHistory.push_back(newHistory); //add a va to the history
}
}
else //the list is empty
mVaHistory.push_back(newHistory);
}
}
else //specified new table offset
setTableOffset(newTableOffset);
/*
//print history
if(history)
{
QString strList = "";
for(int i=0; i<mVaHistory.size(); i++)
strList += QString().sprintf("[%d]:%p,%p\n", i, mVaHistory.at(i).va, mVaHistory.at(i).tableOffset);
MessageBoxA(GuiGetWindowHandle(), strList.toUtf8().constData(), QString().sprintf("mCurrentVa=%d", mCurrentVa).toUtf8().constData(), MB_ICONINFORMATION);
}
*/
}
QList<Instruction_t>* Disassembly::instructionsBuffer()
{
return &mInstBuffer;
}
void Disassembly::disassembleAtSlot(dsint parVA, dsint parCIP)
{
if(parCIP == 0)
parCIP = mCipVa;
if(mCodeFoldingManager)
{
mCodeFoldingManager->expandFoldSegment(parVA);
mCodeFoldingManager->expandFoldSegment(parCIP);
}
mCipVa = parCIP;
if(mIsMain || !mMemPage->getBase())
disassembleAt(parVA, true, -1);
}
void Disassembly::disassembleClear()
{
mHighlightingMode = false;
mHighlightToken = ZydisTokenizer::SingleToken();
historyClear();
mMemPage->setAttributes(0, 0);
mDisasm->getEncodeMap()->setMemoryRegion(0);
setRowCount(0);
setTableOffset(0);
mInstBuffer.clear();
reloadData();
}
void Disassembly::debugStateChangedSlot(DBGSTATE state)
{
switch(state)
{
case stopped:
disassembleClear();
break;
default:
break;
}
}
const duint Disassembly::getBase() const
{
return mMemPage->getBase();
}
duint Disassembly::getSize() const
{
return mMemPage->getSize();
}
duint Disassembly::getTableOffsetRva() const
{
return mInstBuffer.size() ? mInstBuffer.at(0).rva : 0;
}
void Disassembly::historyClear()
{
mVaHistory.clear(); //clear history for new targets
mCurrentVa = 0;
}
void Disassembly::historyPrevious()
{
if(!historyHasPrevious())
return;
mCurrentVa--;
dsint va = mVaHistory.at(mCurrentVa).va;
if(mCodeFoldingManager && mCodeFoldingManager->isFolded(va))
mCodeFoldingManager->expandFoldSegment(va);
disassembleAt(va, false, mVaHistory.at(mCurrentVa).tableOffset);
if(mIsMain)
{
// Update window title
DbgCmdExecDirect(QString("guiupdatetitle %1").arg(ToPtrString(va)));
GuiUpdateAllViews();
}
}
void Disassembly::historyNext()
{
if(!historyHasNext())
return;
mCurrentVa++;
dsint va = mVaHistory.at(mCurrentVa).va;
if(mCodeFoldingManager && mCodeFoldingManager->isFolded(va))
mCodeFoldingManager->expandFoldSegment(va);
disassembleAt(va, false, mVaHistory.at(mCurrentVa).tableOffset);
if(mIsMain)
{
// Update window title
DbgCmdExecDirect(QString("guiupdatetitle %1").arg(ToPtrString(va)));
GuiUpdateAllViews();
}
}
bool Disassembly::historyHasPrevious() const
{
if(!mCurrentVa || !mVaHistory.size()) //we are at the earliest history entry
return false;
return true;
}
bool Disassembly::historyHasNext() const
{
int size = mVaHistory.size();
if(!size || mCurrentVa >= mVaHistory.size() - 1) //we are at the newest history entry
return false;
return true;
}
QString Disassembly::getAddrText(dsint cur_addr, char label[MAX_LABEL_SIZE], bool getLabel)
{
QString addrText = "";
if(mRvaDisplayEnabled) //RVA display
{
dsint rva = cur_addr - mRvaDisplayBase;
if(rva == 0)
{
#ifdef _WIN64
addrText = "$ ==> ";
#else
addrText = "$ ==> ";
#endif //_WIN64
}
else if(rva > 0)
{
#ifdef _WIN64
addrText = "$+" + QString("%1").arg(rva, -15, 16, QChar(' ')).toUpper();
#else
addrText = "$+" + QString("%1").arg(rva, -7, 16, QChar(' ')).toUpper();
#endif //_WIN64
}
else if(rva < 0)
{
#ifdef _WIN64
addrText = "$-" + QString("%1").arg(-rva, -15, 16, QChar(' ')).toUpper();
#else
addrText = "$-" + QString("%1").arg(-rva, -7, 16, QChar(' ')).toUpper();
#endif //_WIN64
}
}
addrText += ToPtrString(cur_addr);
char label_[MAX_LABEL_SIZE] = "";
if(getLabel && DbgGetLabelAt(cur_addr, SEG_DEFAULT, label_)) //has label
{
char module[MAX_MODULE_SIZE] = "";
if(DbgGetModuleAt(cur_addr, module) && !QString(label_).startsWith("JMP.&") && !mNoCurrentModuleText)
addrText += " <" + QString(module) + "." + QString(label_) + ">";
else
addrText += " <" + QString(label_) + ">";
}
else
*label_ = 0;
if(label)
strcpy_s(label, MAX_LABEL_SIZE, label_);
return addrText;
}
/**
* @brief Set the code folding manager for the disassembly view
* @param CodeFoldingManager The pointer to the code folding manager.
*/
void Disassembly::setCodeFoldingManager(CodeFoldingHelper* CodeFoldingManager)
{
mCodeFoldingManager = CodeFoldingManager;
mDisasm->setCodeFoldingManager(CodeFoldingManager);
}
/**
* @brief Unfolds specified rva.
* @param rva the address.
*/
void Disassembly::unfold(dsint rva)
{
if(mCodeFoldingManager)
{
mCodeFoldingManager->expandFoldSegment(rvaToVa(rva));
viewport()->update();
}
}
bool Disassembly::hightlightToken(const ZydisTokenizer::SingleToken & token)
{
mHighlightToken = token;
mHighlightingMode = false;
return true;
}
bool Disassembly::isHighlightMode() const
{
return mHighlightingMode;
} |
C/C++ | x64dbg-development/src/gui/Src/BasicView/Disassembly.h | #pragma once
#include "AbstractTableView.h"
#include "QBeaEngine.h"
#include <QTextLayout>
class CodeFoldingHelper;
class MemoryPage;
class Disassembly : public AbstractTableView
{
Q_OBJECT
public:
Disassembly(QWidget* parent, bool isMain);
~Disassembly() override;
// Configuration
void updateColors() override;
void updateFonts() override;
// Reimplemented Functions
QString paintContent(QPainter* painter, dsint rowBase, int rowOffset, int col, int x, int y, int w, int h) override;
// Mouse Management
void mouseMoveEvent(QMouseEvent* event) override;
void mousePressEvent(QMouseEvent* event) override;
void mouseReleaseEvent(QMouseEvent* event) override;
void wheelEvent(QWheelEvent* event) override;
// Keyboard Management
void keyPressEvent(QKeyEvent* event) override;
// ScrollBar Management
dsint sliderMovedHook(int type, dsint value, dsint delta) override;
// Instructions Management
dsint getPreviousInstructionRVA(dsint rva, duint count);
dsint getNextInstructionRVA(dsint rva, duint count, bool isGlobal = false);
dsint getInstructionRVA(dsint index, dsint count);
Instruction_t DisassembleAt(dsint rva);
Instruction_t DisassembleAt(dsint rva, dsint count);
// Selection Management
void expandSelectionUpTo(dsint to);
void setSingleSelection(dsint index);
dsint getInitialSelection() const;
dsint getSelectionSize() const;
dsint getSelectionStart() const;
dsint getSelectionEnd() const;
void selectNext(bool expand);
void selectPrevious(bool expand);
bool isSelected(dsint base, dsint offset);
bool isSelected(QList<Instruction_t>* buffer, int index) const;
duint getSelectedVa() const;
// Update/Reload/Refresh/Repaint
void prepareData() override;
void reloadData() override;
void paintEvent(QPaintEvent* event) override;
// Public Methods
duint rvaToVa(dsint rva) const;
void disassembleClear();
const duint getBase() const;
duint getSize() const;
duint getTableOffsetRva() const;
// history management
void historyClear();
void historyPrevious();
void historyNext();
bool historyHasPrevious() const;
bool historyHasNext() const;
//disassemble
void gotoAddress(duint addr);
void disassembleAt(dsint parVA, bool history, dsint newTableOffset);
QList<Instruction_t>* instructionsBuffer(); // ugly
const dsint baseAddress() const;
QString getAddrText(dsint cur_addr, char label[MAX_LABEL_SIZE], bool getLabel = true);
void prepareDataCount(const QList<dsint> & wRVAs, QList<Instruction_t>* instBuffer);
void prepareDataRange(dsint startRva, dsint endRva, const std::function<bool(int, const Instruction_t &)> & disassembled);
RichTextPainter::List getRichBytes(const Instruction_t & instr, bool isSelected) const;
//misc
void setCodeFoldingManager(CodeFoldingHelper* CodeFoldingManager);
duint getDisassemblyPopupAddress(int mousex, int mousey) override;
void unfold(dsint rva);
bool hightlightToken(const ZydisTokenizer::SingleToken & token);
bool isHighlightMode() const;
signals:
void selectionChanged(dsint parVA);
void selectionExpanded();
void updateWindowTitle(QString title);
public slots:
void disassembleAtSlot(dsint parVA, dsint parCIP);
void debugStateChangedSlot(DBGSTATE state);
void selectionChangedSlot(dsint parVA);
void tokenizerConfigUpdatedSlot();
void updateConfigSlot();
private:
enum GuiState
{
NoState,
MultiRowsSelectionState
};
enum GraphicDump
{
GD_Nothing,
GD_FootToTop, //GD_FootToTop = '-
GD_FootToBottom, //GD_FootToBottom = ,-
GD_HeadFromTop, //GD_HeadFromTop = '->
GD_HeadFromBottom, //GD_HeadFromBottom = ,->
GD_HeadFromBoth, //GD_HeadFromBoth = |->
GD_Vert, //GD_Vert = |
GD_VertHori //GD_VertHori = |-
};
enum GraphicJumpDirection
{
GJD_Nothing,
GJD_Up,
GJD_Down
};
struct SelectionData
{
dsint firstSelectedIndex;
dsint fromIndex;
dsint toIndex;
};
SelectionData mSelection;
bool mIsLastInstDisplayed;
GuiState mGuiState;
duint mCipVa = 0;
QList<Instruction_t> mInstBuffer;
struct HistoryData
{
dsint va;
dsint tableOffset;
};
QList<HistoryData> mVaHistory;
int mCurrentVa;
enum
{
ColAddress,
ColBytes,
ColDisassembly,
ColMnemonicBrief,
ColComment,
};
protected:
// Jumps Graphic
int paintJumpsGraphic(QPainter* painter, int x, int y, dsint addr, bool isjmp);
// Function Graphic
enum Function_t
{
Function_none,
Function_single,
Function_start,
Function_middle,
Function_loop_entry,
Function_end
};
int paintFunctionGraphic(QPainter* painter, int x, int y, Function_t funcType, bool loop);
// Configuration
QColor mInstructionHighlightColor;
QColor mDisassemblyRelocationUnderlineColor;
QColor mCipBackgroundColor;
QColor mCipColor;
QColor mBreakpointBackgroundColor;
QColor mBreakpointColor;
QColor mHardwareBreakpointBackgroundColor;
QColor mHardwareBreakpointColor;
QColor mBookmarkBackgroundColor;
QColor mBookmarkColor;
QColor mLabelColor;
QColor mLabelBackgroundColor;
QColor mSelectedAddressBackgroundColor;
QColor mTracedAddressBackgroundColor;
QColor mSelectedAddressColor;
QColor mAddressBackgroundColor;
QColor mAddressColor;
QColor mTracedSelectedAddressBackgroundColor;
QColor mBytesColor;
QColor mBytesBackgroundColor;
QColor mModifiedBytesColor;
QColor mModifiedBytesBackgroundColor;
QColor mRestoredBytesColor;
QColor mRestoredBytesBackgroundColor;
QColor mAutoCommentColor;
QColor mAutoCommentBackgroundColor;
QColor mMnemonicBriefColor;
QColor mMnemonicBriefBackgroundColor;
QColor mCommentColor;
QColor mCommentBackgroundColor;
QColor mUnconditionalJumpLineColor;
QColor mConditionalJumpLineTrueColor;
QColor mConditionalJumpLineFalseColor;
QColor mLoopColor;
QColor mFunctionColor;
QPen mLoopPen;
QPen mFunctionPen;
QPen mUnconditionalPen;
QPen mConditionalTruePen;
QPen mConditionalFalsePen;
// Misc
bool mRvaDisplayEnabled;
duint mRvaDisplayBase;
dsint mRvaDisplayPageBase;
bool mHighlightingMode;
MemoryPage* mMemPage;
QBeaEngine* mDisasm;
bool mShowMnemonicBrief;
XREF_INFO mXrefInfo;
CodeFoldingHelper* mCodeFoldingManager;
ZydisTokenizer::SingleToken mHighlightToken;
bool mPermanentHighlightingMode;
bool mNoCurrentModuleText;
bool mIsMain = false;
struct RichTextInfo
{
bool alive = true;
int x = 0;
int y = 0;
int w = 0;
int h = 0;
int xinc = 0;
RichTextPainter::List richText;
};
QTextLayout mTextLayout;
std::vector<QTextLayout::FormatRange> mFormatCache;
std::vector<std::vector<RichTextInfo>> mRichText;
void paintRichText(int x, int y, int w, int h, int xinc, const RichTextPainter::List & richText, int rowOffset, int column);
void paintRichText(int x, int y, int w, int h, int xinc, RichTextPainter::List && richText, int rowOffset, int column);
}; |
C/C++ | x64dbg-development/src/gui/Src/BasicView/HeaderButton.h | #pragma once
#include <QWidget>
class HeaderButton : public QWidget
{
Q_OBJECT
public:
explicit HeaderButton(QWidget* parent = 0);
void setGeometry(int x, int y, int w, int h);
signals:
public slots:
}; |
C++ | x64dbg-development/src/gui/Src/BasicView/HexDump.cpp | #include "HexDump.h"
#include "Configuration.h"
#include "Bridge.h"
#include "StringUtil.h"
#include <QMessageBox>
static int getStringMaxLength(HexDump::DataDescriptor desc);
static int byteStringMaxLength(HexDump::ByteViewMode mode);
static int wordStringMaxLength(HexDump::WordViewMode mode);
static int dwordStringMaxLength(HexDump::DwordViewMode mode);
static int qwordStringMaxLength(HexDump::QwordViewMode mode);
static int twordStringMaxLength(HexDump::TwordViewMode mode);
HexDump::HexDump(QWidget* parent)
: AbstractTableView(parent)
{
memset(&mSelection, 0, sizeof(SelectionData));
setDrawDebugOnly(true);
mGuiState = HexDump::NoState;
setRowCount(0);
mMemPage = new MemoryPage(0, 0);
mForceColumn = -1;
clearDescriptors();
mBackgroundColor = ConfigColor("HexDumpBackgroundColor");
mTextColor = ConfigColor("HexDumpTextColor");
mSelectionColor = ConfigColor("HexDumpSelectionColor");
mRvaDisplayEnabled = false;
mSyncAddrExpression = "";
mNonprintReplace = QChar('.'); //QChar(0x25CA);
mNullReplace = QChar('.'); //QChar(0x2022);
const auto updateCacheDataSize = 0x1000;
mUpdateCacheData.resize(updateCacheDataSize);
mUpdateCacheTemp.resize(updateCacheDataSize);
// Slots
connect(Bridge::getBridge(), SIGNAL(updateDump()), this, SLOT(updateDumpSlot()));
connect(Bridge::getBridge(), SIGNAL(dbgStateChanged(DBGSTATE)), this, SLOT(debugStateChanged(DBGSTATE)));
setupCopyMenu();
Initialize();
}
HexDump::~HexDump()
{
delete mMemPage;
}
void HexDump::updateColors()
{
AbstractTableView::updateColors();
mBackgroundColor = ConfigColor("HexDumpBackgroundColor");
mTextColor = ConfigColor("HexDumpTextColor");
mSelectionColor = ConfigColor("HexDumpSelectionColor");
mModifiedBytesColor = ConfigColor("HexDumpModifiedBytesColor");
mModifiedBytesBackgroundColor = ConfigColor("HexDumpModifiedBytesBackgroundColor");
mRestoredBytesColor = ConfigColor("HexDumpRestoredBytesColor");
mRestoredBytesBackgroundColor = ConfigColor("HexDumpRestoredBytesBackgroundColor");
mByte00Color = ConfigColor("HexDumpByte00Color");
mByte00BackgroundColor = ConfigColor("HexDumpByte00BackgroundColor");
mByte7FColor = ConfigColor("HexDumpByte7FColor");
mByte7FBackgroundColor = ConfigColor("HexDumpByte7FBackgroundColor");
mByteFFColor = ConfigColor("HexDumpByteFFColor");
mByteFFBackgroundColor = ConfigColor("HexDumpByteFFBackgroundColor");
mByteIsPrintColor = ConfigColor("HexDumpByteIsPrintColor");
mByteIsPrintBackgroundColor = ConfigColor("HexDumpByteIsPrintBackgroundColor");
mUserModuleCodePointerHighlightColor = ConfigColor("HexDumpUserModuleCodePointerHighlightColor");
mUserModuleDataPointerHighlightColor = ConfigColor("HexDumpUserModuleDataPointerHighlightColor");
mSystemModuleCodePointerHighlightColor = ConfigColor("HexDumpSystemModuleCodePointerHighlightColor");
mSystemModuleDataPointerHighlightColor = ConfigColor("HexDumpSystemModuleDataPointerHighlightColor");
mUnknownCodePointerHighlightColor = ConfigColor("HexDumpUnknownCodePointerHighlightColor");
mUnknownDataPointerHighlightColor = ConfigColor("HexDumpUnknownDataPointerHighlightColor");
reloadData();
}
void HexDump::updateFonts()
{
duint setting;
if(BridgeSettingGetUint("Gui", "NonprintReplaceCharacter", &setting))
mNonprintReplace = QChar(uint(setting));
if(BridgeSettingGetUint("Gui", "NullReplaceCharacter", &setting))
mNullReplace = QChar(uint(setting));
setFont(ConfigFont("HexDump"));
invalidateCachedFont();
}
void HexDump::updateShortcuts()
{
AbstractTableView::updateShortcuts();
mCopyAddress->setShortcut(ConfigShortcut("ActionCopyAddress"));
mCopyRva->setShortcut(ConfigShortcut("ActionCopyRva"));
mCopySelection->setShortcut(ConfigShortcut("ActionCopy"));
}
void HexDump::updateDumpSlot()
{
if(mSyncAddrExpression.length() && DbgFunctions()->ValFromString)
{
duint syncAddr;
if(DbgFunctions()->ValFromString(mSyncAddrExpression.toUtf8().constData(), &syncAddr)
&& DbgMemIsValidReadPtr(syncAddr))
{
printDumpAt(syncAddr, false, false, true);
}
}
UpdateCache cur;
cur.memBase = mMemPage->getBase();
cur.memSize = mMemPage->getSize();
if(cur.memBase)
{
cur.rva = getTableOffsetRva();
cur.size = getBytePerRowCount() * getViewableRowsCount();
if(cur.size < mUpdateCacheData.size())
{
if(mMemPage->read(mUpdateCacheTemp.data(), cur.rva, cur.size))
{
if(mUpdateCache == cur && memcmp(mUpdateCacheData.data(), mUpdateCacheTemp.data(), cur.size) == 0)
{
// same view and same data, do not reload
return;
}
else
{
mUpdateCache = cur;
mUpdateCacheData.swap(mUpdateCacheTemp);
#ifdef DEBUG
OutputDebugStringA(QString("[x64dbg] %1[%2] %3[%4]").arg(ToPtrString(mUpdateCache.memBase)).arg(ToHexString(mUpdateCache.memSize)).arg(ToPtrString(mUpdateCache.rva)).arg(ToHexString(mUpdateCache.size)).toUtf8().constData());
#endif // DEBUG
}
}
}
}
reloadData();
}
void HexDump::copySelectionSlot()
{
Bridge::CopyToClipboard(makeCopyText());
}
void HexDump::printDumpAt(dsint parVA, bool select, bool repaint, bool updateTableOffset)
{
duint wSize;
auto wBase = DbgMemFindBaseAddr(parVA, &wSize); //get memory base
if(!wBase || !wSize)
return;
dsint wRVA = parVA - wBase; //calculate rva
int wBytePerRowCount = getBytePerRowCount(); //get the number of bytes per row
dsint wRowCount;
// Byte offset used to be aligned on the given RVA
mByteOffset = (int)((dsint)wRVA % (dsint)wBytePerRowCount);
mByteOffset = mByteOffset > 0 ? wBytePerRowCount - mByteOffset : 0;
// Compute row count
wRowCount = wSize / wBytePerRowCount;
wRowCount += mByteOffset > 0 ? 1 : 0;
if(mRvaDisplayEnabled && mMemPage->getBase() != mRvaDisplayPageBase)
mRvaDisplayEnabled = false;
setRowCount(wRowCount); //set the number of rows
mMemPage->setAttributes(wBase, wSize); // Set base and size (Useful when memory page changed)
if(updateTableOffset)
{
setTableOffset(-1); //make sure the requested address is always first
setTableOffset((wRVA + mByteOffset) / wBytePerRowCount); //change the displayed offset
}
if(select)
{
setSingleSelection(wRVA);
dsint wEndingAddress = wRVA + getSizeOf(mDescriptor.at(0).data.itemSize) - 1;
expandSelectionUpTo(wEndingAddress);
}
if(repaint)
reloadData();
}
void HexDump::printDumpAt(dsint parVA)
{
printDumpAt(parVA, true);
}
void HexDump::gotoPreviousSlot()
{
printDumpAt(mHistory.historyPrev());
}
void HexDump::gotoNextSlot()
{
printDumpAt(mHistory.historyNext());
}
duint HexDump::rvaToVa(dsint rva) const
{
return mMemPage->va(rva);
}
duint HexDump::getTableOffsetRva() const
{
return getTableOffset() * getBytePerRowCount() - mByteOffset;
}
QString HexDump::makeAddrText(duint va) const
{
char label[MAX_LABEL_SIZE] = "";
QString addrText = "";
dsint cur_addr = va;
if(mRvaDisplayEnabled) //RVA display
{
dsint rva = cur_addr - mRvaDisplayBase;
if(rva == 0)
{
#ifdef _WIN64
addrText = "$ ==> ";
#else
addrText = "$ ==> ";
#endif //_WIN64
}
else if(rva > 0)
{
#ifdef _WIN64
addrText = "$+" + QString("%1").arg(rva, -15, 16, QChar(' ')).toUpper();
#else
addrText = "$+" + QString("%1").arg(rva, -7, 16, QChar(' ')).toUpper();
#endif //_WIN64
}
else if(rva < 0)
{
#ifdef _WIN64
addrText = "$-" + QString("%1").arg(-rva, -15, 16, QChar(' ')).toUpper();
#else
addrText = "$-" + QString("%1").arg(-rva, -7, 16, QChar(' ')).toUpper();
#endif //_WIN64
}
}
addrText += ToPtrString(cur_addr);
if(DbgGetLabelAt(cur_addr, SEG_DEFAULT, label)) //has label
{
char module[MAX_MODULE_SIZE] = "";
if(DbgGetModuleAt(cur_addr, module) && !QString(label).startsWith("JMP.&"))
addrText += " <" + QString(module) + "." + QString(label) + ">";
else
addrText += " <" + QString(label) + ">";
}
else
*label = 0;
return std::move(addrText);
}
QString HexDump::makeCopyText()
{
dsint deltaRowBase = getSelectionStart() % getBytePerRowCount() + mByteOffset;
if(deltaRowBase >= getBytePerRowCount())
deltaRowBase -= getBytePerRowCount();
auto curRow = getSelectionStart() - deltaRowBase;
QString result;
while(curRow <= getSelectionEnd())
{
for(int col = 0; col < getColumnCount(); col++)
{
if(col)
result += " ";
RichTextPainter::List richText;
getColumnRichText(col, curRow, richText);
QString colText;
for(auto & r : richText)
colText += r.text;
if(col + 1 == getColumnCount())
result += colText;
else
result += colText.leftJustified(getColumnWidth(col) / getCharWidth(), QChar(' '), true);
}
curRow += getBytePerRowCount();
result += "\n";
}
return std::move(result);
}
void HexDump::setupCopyMenu()
{
// Copy -> Data
mCopySelection = new QAction(DIcon("copy_selection"), tr("&Selected lines"), this);
connect(mCopySelection, SIGNAL(triggered(bool)), this, SLOT(copySelectionSlot()));
mCopySelection->setShortcutContext(Qt::WidgetShortcut);
addAction(mCopySelection);
// Copy -> Address
mCopyAddress = new QAction(DIcon("copy_address"), tr("&Address"), this);
connect(mCopyAddress, SIGNAL(triggered()), this, SLOT(copyAddressSlot()));
mCopyAddress->setShortcutContext(Qt::WidgetShortcut);
addAction(mCopyAddress);
// Copy -> RVA
mCopyRva = new QAction(DIcon("copy_address"), "&RVA", this);
connect(mCopyRva, SIGNAL(triggered()), this, SLOT(copyRvaSlot()));
mCopyRva->setShortcutContext(Qt::WidgetShortcut);
addAction(mCopyRva);
}
void HexDump::copyAddressSlot()
{
QString addrText = ToPtrString(rvaToVa(getInitialSelection()));
Bridge::CopyToClipboard(addrText);
}
void HexDump::copyRvaSlot()
{
duint addr = rvaToVa(getInitialSelection());
duint base = DbgFunctions()->ModBaseFromAddr(addr);
if(base)
{
QString addrText = ToHexString(addr - base);
Bridge::CopyToClipboard(addrText);
}
else
QMessageBox::warning(this, tr("Error!"), tr("Selection not in a module..."));
}
void HexDump::mouseMoveEvent(QMouseEvent* event)
{
bool wAccept = true;
int x = event->x();
int y = event->y();
if(mGuiState == HexDump::MultiRowsSelectionState)
{
//qDebug() << "State = MultiRowsSelectionState";
if((transY(y) >= 0) && y <= this->height())
{
int wColIndex = getColumnIndexFromX(x);
if(mForceColumn != -1)
{
wColIndex = mForceColumn;
x = getColumnPosition(mForceColumn) + 1;
}
if(wColIndex > 0) // No selection for first column (addresses)
{
dsint wStartingAddress = getItemStartingAddress(x, y);
dsint dataSize = getSizeOf(mDescriptor.at(wColIndex - 1).data.itemSize) - 1;
dsint wEndingAddress = wStartingAddress + dataSize;
if(wEndingAddress < (dsint)mMemPage->getSize())
{
if(wStartingAddress < getInitialSelection())
{
expandSelectionUpTo(wStartingAddress);
mSelection.toIndex += dataSize;
emit selectionUpdated();
}
else
expandSelectionUpTo(wEndingAddress);
mGuiState = HexDump::MultiRowsSelectionState;
updateViewport();
}
}
else
{
dsint wStartingAddress = getItemStartingAddress(getColumnPosition(1) + 1, y);
dsint dataSize = getSizeOf(mDescriptor.at(0).data.itemSize) * mDescriptor.at(0).itemCount - 1;
dsint wEndingAddress = wStartingAddress + dataSize;
if(wEndingAddress < (dsint)mMemPage->getSize())
{
if(wStartingAddress < getInitialSelection())
{
expandSelectionUpTo(wStartingAddress);
mSelection.toIndex += dataSize;
emit selectionUpdated();
}
else
expandSelectionUpTo(wEndingAddress);
mGuiState = HexDump::MultiRowsSelectionState;
updateViewport();
}
}
wAccept = true;
}
else if(y > this->height() && mGuiState == HexDump::MultiRowsSelectionState)
{
verticalScrollBar()->triggerAction(QAbstractSlider::SliderSingleStepAdd);
}
else if(transY(y) < 0 && mGuiState == HexDump::MultiRowsSelectionState)
{
verticalScrollBar()->triggerAction(QAbstractSlider::SliderSingleStepSub);
}
}
if(wAccept == true)
AbstractTableView::mouseMoveEvent(event);
}
void HexDump::mousePressEvent(QMouseEvent* event)
{
if(event->buttons() == Qt::MiddleButton) //copy address to clipboard
{
if(!DbgIsDebugging())
return;
MessageBeep(MB_OK);
QString addrText = ToPtrString(rvaToVa(getInitialSelection()));
Bridge::CopyToClipboard(addrText);
return;
}
//qDebug() << "HexDump::mousePressEvent";
int x = event->x();
int y = event->y();
bool wAccept = false;
if(((event->buttons() & Qt::LeftButton) != 0) && ((event->buttons() & Qt::RightButton) == 0))
{
if(getGuiState() == AbstractTableView::NoState)
{
if(y > getHeaderHeight() && y <= this->height())
{
int wColIndex = getColumnIndexFromX(x);
if(mForceColumn != -1)
{
wColIndex = mForceColumn;
x = getColumnPosition(mForceColumn) + 1;
}
if(wColIndex > 0 && mDescriptor.at(wColIndex - 1).isData == true) // No selection for first column (addresses) and no data columns
{
dsint wStartingAddress = getItemStartingAddress(x, y);
dsint dataSize = getSizeOf(mDescriptor.at(wColIndex - 1).data.itemSize) - 1;
dsint wEndingAddress = wStartingAddress + dataSize;
if(wEndingAddress < (dsint)mMemPage->getSize())
{
bool bUpdateTo = false;
if(!(event->modifiers() & Qt::ShiftModifier))
setSingleSelection(wStartingAddress);
else if(getInitialSelection() > wEndingAddress)
{
wEndingAddress -= dataSize;
bUpdateTo = true;
}
expandSelectionUpTo(wEndingAddress);
if(bUpdateTo)
{
mSelection.toIndex += dataSize;
emit selectionUpdated();
}
mGuiState = HexDump::MultiRowsSelectionState;
updateViewport();
}
}
else if(wColIndex == 0)
{
dsint wStartingAddress = getItemStartingAddress(getColumnPosition(1) + 1, y);
dsint dataSize = getSizeOf(mDescriptor.at(0).data.itemSize) * mDescriptor.at(0).itemCount - 1;
dsint wEndingAddress = wStartingAddress + dataSize;
if(wEndingAddress < (dsint)mMemPage->getSize())
{
bool bUpdateTo = false;
if(!(event->modifiers() & Qt::ShiftModifier))
setSingleSelection(wStartingAddress);
else if(getInitialSelection() > wEndingAddress)
{
wEndingAddress -= dataSize;
bUpdateTo = true;
}
expandSelectionUpTo(wEndingAddress);
if(bUpdateTo)
{
mSelection.toIndex += dataSize;
emit selectionUpdated();
}
mGuiState = HexDump::MultiRowsSelectionState;
updateViewport();
}
}
wAccept = true;
}
}
}
if(wAccept == false)
AbstractTableView::mousePressEvent(event);
}
void HexDump::mouseReleaseEvent(QMouseEvent* event)
{
bool wAccept = true;
if((event->buttons() & Qt::LeftButton) == 0)
{
if(mGuiState == HexDump::MultiRowsSelectionState)
{
mGuiState = HexDump::NoState;
updateViewport();
wAccept = false;
}
}
if((event->button() & Qt::BackButton) != 0) //Go to previous/next history
{
wAccept = true;
printDumpAt(mHistory.historyPrev());
}
else if((event->button() & Qt::ForwardButton) != 0)
{
wAccept = true;
printDumpAt(mHistory.historyNext());
}
if(wAccept == true)
AbstractTableView::mouseReleaseEvent(event);
}
void HexDump::wheelEvent(QWheelEvent* event)
{
if(event->modifiers() == Qt::NoModifier)
AbstractTableView::wheelEvent(event);
else if(event->modifiers() == Qt::ControlModifier) // Zoom
Config()->zoomFont("HexDump", event);
}
void HexDump::keyPressEvent(QKeyEvent* event)
{
int key = event->key();
auto selStart = getInitialSelection();
char granularity = 1; //Size of a data word.
char action = 0; //Where to scroll the scrollbar
Qt::KeyboardModifiers modifiers = event->modifiers();
for(int i = 0; i < mDescriptor.size(); i++) //Find the first data column
{
if(mDescriptor.at(i).isData)
{
granularity = getSizeOf(mDescriptor.at(i).data.itemSize);
break;
}
}
if(modifiers == Qt::NoModifier)
{
//selStart -= selStart % granularity; //Align the selection to word boundary. TODO: Unaligned data?
switch(key)
{
case Qt::Key_Left:
{
selStart -= granularity;
if(0 <= selStart)
action = -1;
}
break;
case Qt::Key_Right:
{
selStart += granularity;
if(mMemPage->getSize() > selStart)
action = 1;
}
break;
case Qt::Key_Up:
{
selStart -= getBytePerRowCount();
if(0 <= selStart)
action = -1;
}
break;
case Qt::Key_Down:
{
selStart += getBytePerRowCount();
if(mMemPage->getSize() > selStart)
action = 1;
}
break;
default:
AbstractTableView::keyPressEvent(event);
}
if(action != 0)
{
//Check if selection is out of viewport. Step the scrollbar if necessary. (TODO)
if(action == 1 && selStart >= getViewableRowsCount() * getBytePerRowCount() + getTableOffsetRva())
verticalScrollBar()->triggerAction(QAbstractSlider::SliderSingleStepAdd);
else if(action == -1 && selStart < getTableOffsetRva())
verticalScrollBar()->triggerAction(QAbstractSlider::SliderSingleStepSub);
setSingleSelection(selStart);
if(granularity > 1)
expandSelectionUpTo(selStart + granularity - 1);
reloadData();
}
}
else if(modifiers == Qt::ControlModifier || modifiers == (Qt::ControlModifier | Qt::AltModifier))
{
duint offsetVa = rvaToVa(getTableOffsetRva());
switch(key)
{
case Qt::Key_Left:
action = (modifiers & Qt::AltModifier) ? -1 : -granularity;
break;
case Qt::Key_Right:
action = (modifiers & Qt::AltModifier) ? 1 : granularity;
break;
case Qt::Key_Up:
action = 0;
verticalScrollBar()->triggerAction(QAbstractSlider::SliderSingleStepSub);
break;
case Qt::Key_Down:
action = 0;
verticalScrollBar()->triggerAction(QAbstractSlider::SliderSingleStepAdd);
break;
default:
AbstractTableView::keyPressEvent(event);
}
if(action != 0)
{
offsetVa += action;
if(mMemPage->inRange(offsetVa))
printDumpAt(offsetVa, false);
}
}
else if(modifiers == Qt::ShiftModifier)
{
//TODO
}
else
{
AbstractTableView::keyPressEvent(event);
}
/*
Let's keep the old code for a while until nobody remembers previous behaviour.
if(key == Qt::Key_Left || (key == Qt::Key_Up && control)) //TODO: see if Ctrl+Up is redundant
{
duint offsetVa = rvaToVa(getTableOffsetRva()) - 1;
if(mMemPage->inRange(offsetVa))
printDumpAt(offsetVa, false);
}
else if(key == Qt::Key_Right || (key == Qt::Key_Down && control)) //TODO: see if Ctrl+Down is redundant
{
duint offsetVa = rvaToVa(getTableOffsetRva()) + 1;
if(mMemPage->inRange(offsetVa))
printDumpAt(offsetVa, false);
}
else
AbstractTableView::keyPressEvent(event);
*/
}
QString HexDump::paintContent(QPainter* painter, dsint rowBase, int rowOffset, int col, int x, int y, int w, int h)
{
// Reset byte offset when base address is reached
if(rowBase == 0 && mByteOffset != 0)
printDumpAt(mMemPage->getBase(), false, false);
// Compute RVA
int wBytePerRowCount = getBytePerRowCount();
dsint wRva = (rowBase + rowOffset) * wBytePerRowCount - mByteOffset;
if(col && mDescriptor.at(col - 1).isData)
printSelected(painter, rowBase, rowOffset, col, x, y, w, h);
RichTextPainter::List richText;
getColumnRichText(col, wRva, richText);
RichTextPainter::paintRichText(painter, x, y, w, h, 4, richText, mFontMetrics);
return QString();
}
void HexDump::printSelected(QPainter* painter, dsint rowBase, int rowOffset, int col, int x, int y, int w, int h)
{
if((col > 0) && ((col - 1) < mDescriptor.size()))
{
ColumnDescriptor curDescriptor = mDescriptor.at(col - 1);
int wBytePerRowCount = getBytePerRowCount();
dsint wRva = (rowBase + rowOffset) * wBytePerRowCount - mByteOffset;
int wItemPixWidth = getItemPixelWidth(curDescriptor);
int wCharWidth = getCharWidth();
if(wItemPixWidth == wCharWidth)
x += 4;
for(int i = 0; i < curDescriptor.itemCount; i++)
{
int wSelectionX = x + i * wItemPixWidth;
if(isSelected(wRva + i * getSizeOf(curDescriptor.data.itemSize)) == true)
{
int wSelectionWidth = wItemPixWidth > w - (wSelectionX - x) ? w - (wSelectionX - x) : wItemPixWidth;
wSelectionWidth = wSelectionWidth < 0 ? 0 : wSelectionWidth;
painter->setPen(mTextColor);
painter->fillRect(QRect(wSelectionX, y, wSelectionWidth, h), QBrush(mSelectionColor));
}
int separator = curDescriptor.separator;
if(i && separator && !(i % separator))
{
painter->setPen(mSeparatorColor);
painter->drawLine(wSelectionX, y, wSelectionX, y + h);
}
}
}
}
/************************************************************************************
Selection Management
************************************************************************************/
void HexDump::expandSelectionUpTo(dsint rva)
{
if(rva < mSelection.firstSelectedIndex)
{
mSelection.fromIndex = rva;
mSelection.toIndex = mSelection.firstSelectedIndex;
emit selectionUpdated();
}
else if(rva > mSelection.firstSelectedIndex)
{
mSelection.fromIndex = mSelection.firstSelectedIndex;
mSelection.toIndex = rva;
emit selectionUpdated();
}
else if(rva == mSelection.firstSelectedIndex)
{
setSingleSelection(rva);
}
}
void HexDump::setSingleSelection(dsint rva)
{
mSelection.firstSelectedIndex = rva;
mSelection.fromIndex = rva;
mSelection.toIndex = rva;
emit selectionUpdated();
}
dsint HexDump::getInitialSelection() const
{
return mSelection.firstSelectedIndex;
}
dsint HexDump::getSelectionStart() const
{
return mSelection.fromIndex;
}
dsint HexDump::getSelectionEnd() const
{
return mSelection.toIndex;
}
bool HexDump::isSelected(dsint rva) const
{
return rva >= mSelection.fromIndex && rva <= mSelection.toIndex;
}
void HexDump::getColumnRichText(int col, dsint rva, RichTextPainter::List & richText)
{
RichTextPainter::CustomRichText_t curData;
curData.underline = false;
curData.flags = RichTextPainter::FlagAll;
curData.textColor = mTextColor;
curData.textBackground = Qt::transparent;
curData.underlineColor = Qt::transparent;
RichTextPainter::CustomRichText_t spaceData;
spaceData.underline = false;
spaceData.flags = RichTextPainter::FlagNone;
spaceData.underlineColor = Qt::transparent;
if(!col) //address
{
curData.text = makeAddrText(rvaToVa(rva));
richText.push_back(curData);
}
else if(mDescriptor.at(col - 1).isData == true)
{
const ColumnDescriptor & desc = mDescriptor.at(col - 1);
int wI;
int wByteCount = getSizeOf(desc.data.itemSize);
int wBufferByteCount = desc.itemCount * wByteCount;
wBufferByteCount = wBufferByteCount > (dsint)(mMemPage->getSize() - rva) ? mMemPage->getSize() - rva : wBufferByteCount;
byte_t* wData = new byte_t[wBufferByteCount];
mMemPage->read(wData, rva, wBufferByteCount);
if(desc.textCodec) //convert the row bytes to unicode
{
//This might produce invalid characters in variables-width encodings. This is currently ignored.
curData.text = desc.textCodec->toUnicode(QByteArray((const char*)wData, wBufferByteCount));
curData.text.replace('\t', "\\t");
curData.text.replace('\f', "\\f");
curData.text.replace('\v', "\\v");
curData.text.replace('\n', "\\n");
curData.text.replace('\r', "\\r");
richText.push_back(curData);
}
else
{
for(wI = 0; wI < desc.itemCount && (rva + wI) < (dsint)mMemPage->getSize(); wI++)
{
curData.text.clear();
curData.textColor = mTextColor;
curData.textBackground = Qt::transparent;
curData.flags = RichTextPainter::FlagAll;
int maxLen = getStringMaxLength(desc.data);
if((rva + wI + wByteCount - 1) < (dsint)mMemPage->getSize())
{
toString(desc.data, rva + wI * wByteCount, wData + wI * wByteCount, curData);
if(curData.text.length() < maxLen)
{
spaceData.text = QString(' ').repeated(maxLen - curData.text.length());
richText.push_back(spaceData);
}
if(wI % sizeof(duint) == 0 && wByteCount == 1 && desc.data.byteMode == HexByte) //pointer underlining
{
auto ptr = *(duint*)(wData + wI * wByteCount);
if(spaceData.underline = curData.underline = DbgMemIsValidReadPtr(ptr))
{
auto codePage = DbgFunctions()->MemIsCodePage(ptr, false);
auto modbase = DbgFunctions()->ModBaseFromAddr(ptr);
if(modbase)
{
if(DbgFunctions()->ModGetParty(modbase) == 1) //system
spaceData.underlineColor = curData.underlineColor = codePage ? mSystemModuleCodePointerHighlightColor : mSystemModuleDataPointerHighlightColor;
else //user
spaceData.underlineColor = curData.underlineColor = codePage ? mUserModuleCodePointerHighlightColor : mUserModuleDataPointerHighlightColor;
}
else
spaceData.underlineColor = curData.underlineColor = codePage ? mUnknownCodePointerHighlightColor : mUnknownDataPointerHighlightColor;
}
}
richText.push_back(curData);
if(maxLen)
{
spaceData.text = QString(' ');
if(wI % sizeof(duint) == sizeof(duint) - 1)
spaceData.underline = false;
richText.push_back(spaceData);
}
}
else
{
curData.text = QString("?").rightJustified(maxLen, ' ');
if(maxLen)
curData.text.append(' ');
richText.push_back(curData);
}
}
}
auto dataStartAddr = rvaToVa(rva);
auto dataEndAddr = dataStartAddr + wBufferByteCount - 1;
if(mUnderlineRangeStartVa && mUnderlineRangeEndVa)
{
// Check if the highlight ranges overlap
if(mUnderlineRangeStartVa <= dataEndAddr && dataStartAddr <= mUnderlineRangeEndVa)
{
for(RichTextPainter::CustomRichText_t & token : richText)
{
token.underline = true;
token.underlineColor = token.textColor;
}
while(richText.back().text == QStringLiteral(" "))
richText.pop_back();
}
}
delete[] wData;
}
}
void HexDump::toString(DataDescriptor desc, duint rva, byte_t* data, RichTextPainter::CustomRichText_t & richText) //convert data to string
{
switch(desc.itemSize)
{
case Byte:
{
byteToString(rva, *((byte_t*)data), desc.byteMode, richText);
}
break;
case Word:
{
wordToString(rva, *((uint16*)data), desc.wordMode, richText);
}
break;
case Dword:
{
dwordToString(rva, *((uint32*)data), desc.dwordMode, richText);
}
break;
case Qword:
{
qwordToString(rva, *((uint64*)data), desc.qwordMode, richText);
}
break;
case Tword:
{
twordToString(rva, data, desc.twordMode, richText);
}
break;
default:
{
}
break;
}
if(desc.itemSize == Byte) //byte patches are handled in byteToString
return;
dsint start = rvaToVa(rva);
dsint end = start + getSizeOf(desc.itemSize) - 1;
if(DbgFunctions()->PatchInRange(start, end))
richText.textColor = ConfigColor("HexDumpModifiedBytesColor");
}
void HexDump::byteToString(duint rva, byte_t byte, ByteViewMode mode, RichTextPainter::CustomRichText_t & richText)
{
QString wStr = "";
switch(mode)
{
case HexByte:
{
wStr = ToByteString((unsigned char)byte);
}
break;
case AsciiByte:
{
QChar wChar = QChar::fromLatin1((char)byte);
if(wChar.isPrint())
wStr = QString(wChar);
else if(!wChar.unicode())
wStr = mNullReplace;
else
wStr = mNonprintReplace;
}
break;
case SignedDecByte:
{
wStr = QString::number((int)((char)byte));
}
break;
case UnsignedDecByte:
{
wStr = QString::number((unsigned int)byte);
}
break;
default:
{
}
break;
}
richText.text = wStr;
DBGPATCHINFO patchInfo;
if(DbgFunctions()->PatchGetEx(rvaToVa(rva), &patchInfo))
{
if(byte == patchInfo.newbyte)
{
richText.textColor = mModifiedBytesColor;
richText.textBackground = mModifiedBytesBackgroundColor;
}
else
{
richText.textColor = mRestoredBytesColor;
richText.textBackground = mRestoredBytesBackgroundColor;
}
}
else
{
switch(byte)
{
case 0x00:
richText.textColor = mByte00Color;
richText.textBackground = mByte00BackgroundColor;
break;
case 0x7F:
richText.textColor = mByte7FColor;
richText.textBackground = mByte7FBackgroundColor;
break;
case 0xFF:
richText.textColor = mByteFFColor;
richText.textBackground = mByteFFBackgroundColor;
break;
default:
if(isprint(byte) || isspace(byte))
{
richText.textColor = mByteIsPrintColor;
richText.textBackground = mByteIsPrintBackgroundColor;
}
break;
}
}
}
void HexDump::wordToString(duint rva, uint16 word, WordViewMode mode, RichTextPainter::CustomRichText_t & richText)
{
Q_UNUSED(rva);
QString wStr;
switch(mode)
{
case HexWord:
{
wStr = ToWordString((unsigned short)word);
}
break;
case UnicodeWord:
{
QChar wChar = QChar::fromLatin1((char)word & 0xFF);
if(wChar.isPrint() && (word >> 8) == 0)
wStr = QString(wChar);
else if(!wChar.unicode())
wStr = mNullReplace;
else
wStr = mNonprintReplace;
}
break;
case SignedDecWord:
{
wStr = QString::number((int)((short)word));
}
break;
case UnsignedDecWord:
{
wStr = QString::number((unsigned int)word);
}
break;
default:
{
}
break;
}
richText.text = wStr;
}
void HexDump::dwordToString(duint rva, uint32 dword, DwordViewMode mode, RichTextPainter::CustomRichText_t & richText)
{
Q_UNUSED(rva);
QString wStr;
switch(mode)
{
case HexDword:
{
wStr = QString("%1").arg((unsigned int)dword, 8, 16, QChar('0')).toUpper();
}
break;
case SignedDecDword:
{
wStr = QString::number((int)dword);
}
break;
case UnsignedDecDword:
{
wStr = QString::number((unsigned int)dword);
}
break;
case FloatDword:
{
wStr = ToFloatString(&dword);
}
break;
default:
{
}
break;
}
richText.text = wStr;
}
void HexDump::qwordToString(duint rva, uint64 qword, QwordViewMode mode, RichTextPainter::CustomRichText_t & richText)
{
Q_UNUSED(rva);
QString wStr;
switch(mode)
{
case HexQword:
{
wStr = QString("%1").arg((unsigned long long)qword, 16, 16, QChar('0')).toUpper();
}
break;
case SignedDecQword:
{
wStr = QString::number((long long)qword);
}
break;
case UnsignedDecQword:
{
wStr = QString::number((unsigned long long)qword);
}
break;
case DoubleQword:
{
wStr = ToDoubleString(&qword);
}
break;
default:
{
}
break;
}
richText.text = wStr;
}
void HexDump::twordToString(duint rva, void* tword, TwordViewMode mode, RichTextPainter::CustomRichText_t & richText)
{
Q_UNUSED(rva);
QString wStr;
switch(mode)
{
case FloatTword:
{
wStr = ToLongDoubleString(tword);
}
break;
default:
{
}
break;
}
richText.text = wStr;
}
size_t HexDump::getSizeOf(DataSize size)
{
return size_t(size);
}
static int getStringMaxLength(HexDump::DataDescriptor desc)
{
int wLength = 0;
switch(desc.itemSize)
{
case HexDump::Byte:
{
wLength = byteStringMaxLength(desc.byteMode);
}
break;
case HexDump::Word:
{
wLength = wordStringMaxLength(desc.wordMode);
}
break;
case HexDump::Dword:
{
wLength = dwordStringMaxLength(desc.dwordMode);
}
break;
case HexDump::Qword:
{
wLength = qwordStringMaxLength(desc.qwordMode);
}
break;
case HexDump::Tword:
{
wLength = twordStringMaxLength(desc.twordMode);
}
break;
default:
{
}
break;
}
return wLength;
}
static int byteStringMaxLength(HexDump::ByteViewMode mode)
{
int wLength = 0;
switch(mode)
{
case HexDump::HexByte:
{
wLength = 2;
}
break;
case HexDump::AsciiByte:
{
wLength = 0;
}
break;
case HexDump::SignedDecByte:
{
wLength = 4;
}
break;
case HexDump::UnsignedDecByte:
{
wLength = 3;
}
break;
default:
{
}
break;
}
return wLength;
}
static int wordStringMaxLength(HexDump::WordViewMode mode)
{
int wLength = 0;
switch(mode)
{
case HexDump::HexWord:
{
wLength = 4;
}
break;
case HexDump::UnicodeWord:
{
wLength = 0;
}
break;
case HexDump::SignedDecWord:
{
wLength = 6;
}
break;
case HexDump::UnsignedDecWord:
{
wLength = 5;
}
break;
default:
{
}
break;
}
return wLength;
}
static int dwordStringMaxLength(HexDump::DwordViewMode mode)
{
int wLength = 0;
switch(mode)
{
case HexDump::HexDword:
{
wLength = 8;
}
break;
case HexDump::SignedDecDword:
{
wLength = 11;
}
break;
case HexDump::UnsignedDecDword:
{
wLength = 10;
}
break;
case HexDump::FloatDword:
{
wLength = 13;
}
break;
default:
{
}
break;
}
return wLength;
}
static int qwordStringMaxLength(HexDump::QwordViewMode mode)
{
int wLength = 0;
switch(mode)
{
case HexDump::HexQword:
{
wLength = 16;
}
break;
case HexDump::SignedDecQword:
{
wLength = 20;
}
break;
case HexDump::UnsignedDecQword:
{
wLength = 20;
}
break;
case HexDump::DoubleQword:
{
wLength = 23;
}
break;
default:
{
}
break;
}
return wLength;
}
static int twordStringMaxLength(HexDump::TwordViewMode mode)
{
int wLength = 0;
switch(mode)
{
case HexDump::FloatTword:
{
wLength = 29;
}
break;
default:
{
}
break;
}
return wLength;
}
int HexDump::getItemIndexFromX(int x) const
{
int wColIndex = getColumnIndexFromX(x);
if(wColIndex > 0)
{
int wColStartingPos = getColumnPosition(wColIndex);
int wRelativeX = x - wColStartingPos;
int wItemPixWidth = getItemPixelWidth(mDescriptor.at(wColIndex - 1));
int wCharWidth = getCharWidth();
if(wItemPixWidth == wCharWidth)
wRelativeX -= 4;
int wItemIndex = wRelativeX / wItemPixWidth;
wItemIndex = wItemIndex < 0 ? 0 : wItemIndex;
wItemIndex = wItemIndex > (mDescriptor.at(wColIndex - 1).itemCount - 1) ? (mDescriptor.at(wColIndex - 1).itemCount - 1) : wItemIndex;
return wItemIndex;
}
else
{
return 0;
}
}
dsint HexDump::getItemStartingAddress(int x, int y)
{
int wRowOffset = getIndexOffsetFromY(transY(y));
int wItemIndex = getItemIndexFromX(x);
int wColIndex = getColumnIndexFromX(x);
dsint wStartingAddress = 0;
if(wColIndex > 0)
{
wColIndex -= 1;
wStartingAddress = (getTableOffset() + wRowOffset) * (mDescriptor.at(wColIndex).itemCount * getSizeOf(mDescriptor.at(wColIndex).data.itemSize)) + wItemIndex * getSizeOf(mDescriptor.at(wColIndex).data.itemSize) - mByteOffset;
}
return wStartingAddress;
}
int HexDump::getBytePerRowCount() const
{
return mDescriptor.at(0).itemCount * getSizeOf(mDescriptor.at(0).data.itemSize);
}
int HexDump::getItemPixelWidth(ColumnDescriptor desc) const
{
int wCharWidth = getCharWidth();
int wItemPixWidth = getStringMaxLength(desc.data) * wCharWidth + wCharWidth;
return wItemPixWidth;
}
void HexDump::appendDescriptor(int width, QString title, bool clickable, ColumnDescriptor descriptor)
{
addColumnAt(width, title, clickable);
mDescriptor.append(descriptor);
}
//Clears the descriptors, append a new descriptor and fix the tableOffset (use this instead of clearDescriptors()
void HexDump::appendResetDescriptor(int width, QString title, bool clickable, ColumnDescriptor descriptor)
{
setAllowPainting(false);
if(mDescriptor.size())
{
dsint wRVA = getTableOffset() * getBytePerRowCount() - mByteOffset;
clearDescriptors();
appendDescriptor(width, title, clickable, descriptor);
printDumpAt(rvaToVa(wRVA), true, false);
}
else
appendDescriptor(width, title, clickable, descriptor);
setAllowPainting(true);
}
void HexDump::clearDescriptors()
{
deleteAllColumns();
mDescriptor.clear();
int charwidth = getCharWidth();
addColumnAt(8 + charwidth * 2 * sizeof(duint), tr("Address"), false); //address
}
void HexDump::debugStateChanged(DBGSTATE state)
{
if(state == stopped)
{
mMemPage->setAttributes(0, 0);
setRowCount(0);
reloadData();
}
} |
C/C++ | x64dbg-development/src/gui/Src/BasicView/HexDump.h | #pragma once
#include "AbstractTableView.h"
#include "RichTextPainter.h"
#include "MemoryPage.h"
#include "VaHistory.h"
#include <QTextCodec>
class HexDump : public AbstractTableView
{
Q_OBJECT
public:
enum DataSize
{
Byte = 1,
Word = 2,
Dword = 4,
Qword = 8,
Tword = 10
};
enum ByteViewMode
{
HexByte,
AsciiByte,
SignedDecByte,
UnsignedDecByte
};
enum WordViewMode
{
HexWord,
UnicodeWord,
SignedDecWord,
UnsignedDecWord
};
enum DwordViewMode
{
HexDword,
SignedDecDword,
UnsignedDecDword,
FloatDword //sizeof(float)=4
};
enum QwordViewMode
{
HexQword,
SignedDecQword,
UnsignedDecQword,
DoubleQword //sizeof(double)=8
};
enum TwordViewMode
{
FloatTword
};
struct DataDescriptor
{
DataSize itemSize; // Items size
union // View mode
{
ByteViewMode byteMode;
WordViewMode wordMode;
DwordViewMode dwordMode;
QwordViewMode qwordMode;
TwordViewMode twordMode;
};
};
struct ColumnDescriptor
{
bool isData = true;
int itemCount = 16;
int separator = 0;
QTextCodec* textCodec = nullptr; //name of the text codec (leave empty if you want to keep your sanity)
DataDescriptor data;
std::function<void()> columnSwitch;
};
explicit HexDump(QWidget* parent = 0);
~HexDump() override;
// Configuration
void updateColors() override;
void updateFonts() override;
void updateShortcuts() override;
//QString getStringToPrint(int rowBase, int rowOffset, int col);
void mouseMoveEvent(QMouseEvent* event) override;
void mousePressEvent(QMouseEvent* event) override;
void mouseReleaseEvent(QMouseEvent* event) override;
void wheelEvent(QWheelEvent* event) override;
void keyPressEvent(QKeyEvent* event) override;
QString paintContent(QPainter* painter, dsint rowBase, int rowOffset, int col, int x, int y, int w, int h) override;
void paintGraphicDump(QPainter* painter, int x, int y, int addr);
void printSelected(QPainter* painter, dsint rowBase, int rowOffset, int col, int x, int y, int w, int h);
// Selection Management
void expandSelectionUpTo(dsint rva);
void setSingleSelection(dsint rva);
dsint getInitialSelection() const;
dsint getSelectionStart() const;
dsint getSelectionEnd() const;
bool isSelected(dsint rva) const;
virtual void getColumnRichText(int col, dsint rva, RichTextPainter::List & richText);
static size_t getSizeOf(DataSize size);
void toString(DataDescriptor desc, duint rva, byte_t* data, RichTextPainter::CustomRichText_t & richText);
void byteToString(duint rva, byte_t byte, ByteViewMode mode, RichTextPainter::CustomRichText_t & richText);
void wordToString(duint rva, uint16 word, WordViewMode mode, RichTextPainter::CustomRichText_t & richText);
static void dwordToString(duint rva, uint32 dword, DwordViewMode mode, RichTextPainter::CustomRichText_t & richText);
static void qwordToString(duint rva, uint64 qword, QwordViewMode mode, RichTextPainter::CustomRichText_t & richText);
static void twordToString(duint rva, void* tword, TwordViewMode mode, RichTextPainter::CustomRichText_t & richText);
int getItemIndexFromX(int x) const;
dsint getItemStartingAddress(int x, int y);
int getBytePerRowCount() const;
int getItemPixelWidth(ColumnDescriptor desc) const;
//descriptor management
void appendDescriptor(int width, QString title, bool clickable, ColumnDescriptor descriptor);
void appendResetDescriptor(int width, QString title, bool clickable, ColumnDescriptor descriptor);
void clearDescriptors();
void printDumpAt(dsint parVA, bool select, bool repaint = true, bool updateTableOffset = true);
duint rvaToVa(dsint rva) const;
duint getTableOffsetRva() const;
QString makeAddrText(duint va) const;
QString makeCopyText();
void setupCopyMenu();
VaHistory mHistory;
signals:
void selectionUpdated();
public slots:
void printDumpAt(dsint parVA);
void debugStateChanged(DBGSTATE state);
void updateDumpSlot();
void copySelectionSlot();
void copyAddressSlot();
void copyRvaSlot();
void gotoPreviousSlot();
void gotoNextSlot();
private:
enum GuiState
{
NoState,
MultiRowsSelectionState
};
struct SelectionData
{
dsint firstSelectedIndex;
dsint fromIndex;
dsint toIndex;
};
SelectionData mSelection;
GuiState mGuiState;
QChar mNonprintReplace;
QChar mNullReplace;
QColor mModifiedBytesColor;
QColor mModifiedBytesBackgroundColor;
QColor mRestoredBytesColor;
QColor mRestoredBytesBackgroundColor;
QColor mByte00Color;
QColor mByte00BackgroundColor;
QColor mByte7FColor;
QColor mByte7FBackgroundColor;
QColor mByteFFColor;
QColor mByteFFBackgroundColor;
QColor mByteIsPrintColor;
QColor mByteIsPrintBackgroundColor;
QColor mUserModuleCodePointerHighlightColor;
QColor mUserModuleDataPointerHighlightColor;
QColor mSystemModuleCodePointerHighlightColor;
QColor mSystemModuleDataPointerHighlightColor;
QColor mUnknownCodePointerHighlightColor;
QColor mUnknownDataPointerHighlightColor;
struct UpdateCache
{
duint memBase = 0;
duint memSize = 0;
duint rva = 0;
duint size = 0;
bool operator==(const UpdateCache & o) const
{
return std::tie(memBase, memSize, rva, size) == std::tie(o.memBase, o.memSize, o.rva, o.size);
}
} mUpdateCache;
std::vector<uint8_t> mUpdateCacheData;
std::vector<uint8_t> mUpdateCacheTemp;
protected:
MemoryPage* mMemPage;
int mByteOffset;
QList<ColumnDescriptor> mDescriptor;
int mForceColumn;
bool mRvaDisplayEnabled;
duint mRvaDisplayBase;
dsint mRvaDisplayPageBase;
QString mSyncAddrExpression;
QAction* mCopyAddress;
QAction* mCopyRva;
QAction* mCopySelection;
duint mUnderlineRangeStartVa = 0;
duint mUnderlineRangeEndVa = 0;
}; |
C++ | x64dbg-development/src/gui/Src/BasicView/HistoryLineEdit.cpp | #include "HistoryLineEdit.h"
#include "Bridge.h"
HistoryLineEdit::HistoryLineEdit(QWidget* parent) : QLineEdit(parent)
{
mCmdIndex = -1;
bSixPressed = false;
}
void HistoryLineEdit::loadSettings(QString sectionPrefix)
{
char buffer[MAX_SETTING_SIZE];
for(int i = 1; BridgeSettingGet(sectionPrefix.toUtf8().constData(),
QString("Line%1").arg(i).toUtf8().constData(),
buffer) && buffer[0] && i < mCmdHistoryMaxSize; i++)
{
QString entry = QString(buffer);
mCmdHistory.append(entry);
}
}
void HistoryLineEdit::saveSettings(QString sectionPrefix)
{
int i = 1;
for(i = 1; i <= mCmdHistory.size(); i++)
{
BridgeSettingSet(sectionPrefix.toUtf8().constData(),
QString("Line%1").arg(i).toUtf8().constData(),
mCmdHistory.at(i - 1).toUtf8().constData());
}
// Sentinel in case we saved less than is in the store currently
BridgeSettingSet(sectionPrefix.toUtf8().constData(),
QString("Line%1").arg(i).toUtf8().constData(),
"");
}
void HistoryLineEdit::addLineToHistory(QString parLine)
{
if(mCmdHistory.size() > mCmdHistoryMaxSize)
mCmdHistory.removeLast();
if(mCmdHistory.empty() || mCmdHistory.first() != parLine)
mCmdHistory.prepend(parLine);
mCmdIndex = -1;
}
QString HistoryLineEdit::getLineFromHistory()
{
if(mCmdHistory.empty())
return "";
else
return mCmdHistory.first();
}
QString HistoryLineEdit::addHistoryClear()
{
auto str = text();
if(str.length())
{
addLineToHistory(str);
clear();
}
return str;
}
void HistoryLineEdit::keyPressEvent(QKeyEvent* event)
{
int wKey = event->key();
//This fixes a very annoying bug on some systems
if(bSixPressed)
{
bSixPressed = false;
if(event->text() == "^")
{
event->ignore();
return;
}
}
if(wKey == Qt::Key_6)
bSixPressed = true;
if(wKey == Qt::Key_Up || wKey == Qt::Key_Down)
{
if(wKey == Qt::Key_Up)
mCmdIndex++;
else if(wKey == Qt::Key_Down)
mCmdIndex--;
mCmdIndex = mCmdIndex < -1 ? -1 : mCmdIndex;
mCmdIndex = mCmdIndex > mCmdHistory.size() - 1 ? mCmdHistory.size() - 1 : mCmdIndex;
// Set the new text if an existing command was available
QString newText("");
if(mCmdIndex != -1)
newText = mCmdHistory.at(mCmdIndex);
// NOTE: "Unlike textChanged(), this signal [textEdited()] is not emitted when
// the text is changed programmatically, for example, by calling setText()."
setText(newText);
emit textEdited(newText);
}
QLineEdit::keyPressEvent(event);
}
void HistoryLineEdit::setFocus()
{
mCmdIndex = -1;
QLineEdit::setFocus();
} |
C/C++ | x64dbg-development/src/gui/Src/BasicView/HistoryLineEdit.h | #pragma once
#include <QLineEdit>
#include <QKeyEvent>
class HistoryLineEdit : public QLineEdit
{
Q_OBJECT
public:
explicit HistoryLineEdit(QWidget* parent = 0);
void keyPressEvent(QKeyEvent* event);
void addLineToHistory(QString parLine);
QString getLineFromHistory();
QString addHistoryClear();
void setFocus();
void loadSettings(QString sectionPrefix);
void saveSettings(QString sectionPrefix);
signals:
void keyPressed(int parKey);
private:
int mCmdHistoryMaxSize = 1000;
QList<QString> mCmdHistory;
int mCmdIndex;
bool bSixPressed;
}; |
C++ | x64dbg-development/src/gui/Src/BasicView/LabeledSplitter.cpp | #include "LabeledSplitter.h"
#include "LabeledSplitterDetachedWindow.h"
#include <QPainter>
#include <QpaintEvent>
#include <QMenu>
#include <QDesktopWidget>
#include <QApplication>
#include "Bridge.h"
#include "Configuration.h"
//LabeledSplitterHandle class
LabeledSplitterHandle::LabeledSplitterHandle(Qt::Orientation o, LabeledSplitter* parent) : QSplitterHandle(o, parent)
{
charHeight = QFontMetrics(font()).height();
setMouseTracking(true);
originalSize = 0;
}
QSize LabeledSplitterHandle::sizeHint() const
{
QSize size;
size.setHeight(charHeight + 2);
return std::move(size);
}
QSize LabeledSplitterHandle::minimumSizeHint() const
{
return sizeHint();
}
LabeledSplitter* LabeledSplitterHandle::getParent() const
{
return qobject_cast<LabeledSplitter*>(parent());
}
int LabeledSplitterHandle::getIndex()
{
return getParent()->indexOf(this);
}
void LabeledSplitter::setupContextMenu()
{
mMenu = new QMenu(this);
mExpandCollapseAction = new QAction(this);
connect(mExpandCollapseAction, SIGNAL(triggered()), this, SLOT(collapseSlot()));
mMenu->addAction(mExpandCollapseAction);
QAction* mDetach = new QAction(tr("&Detach"), this);
connect(mDetach, SIGNAL(triggered()), this, SLOT(detachSlot()));
mMenu->addAction(mDetach);
}
void LabeledSplitterHandle::contextMenuEvent(QContextMenuEvent* event)
{
getParent()->currentIndex = getIndex();
QSplitterHandle::contextMenuEvent(event);
return;
}
void LabeledSplitter::collapseSlot()
{
auto sizes = this->sizes();
int index2;
int* originalSize = &(qobject_cast<LabeledSplitterHandle*>(handle(currentIndex))->originalSize);
for(index2 = currentIndex - 1; sizes.at(index2) == 0 && index2 != 0; index2--);
if(sizes.at(currentIndex) == 0)
{
if(*originalSize == 0)
*originalSize = 100;
if(sizes[index2] > *originalSize)
sizes[index2] -= *originalSize;
sizes[currentIndex] = *originalSize;
}
else
{
*originalSize = sizes[currentIndex];
sizes[currentIndex] = 0;
sizes[index2] += *originalSize;
}
setSizes(sizes);
}
// Convert a tab to an external window
void LabeledSplitter::detachSlot()
{
// Create the window
LabeledSplitterDetachedWindow* detachedWidget = new LabeledSplitterDetachedWindow(this, this);
detachedWidget->setWindowModality(Qt::NonModal);
// Find Widget and connect
connect(detachedWidget, SIGNAL(OnClose(LabeledSplitterDetachedWindow*)), this, SLOT(attachSlot(LabeledSplitterDetachedWindow*)));
detachedWidget->setWindowTitle(mNames.at(currentIndex));
detachedWidget->index = currentIndex;
// Remove from splitter
QWidget* tearOffWidget = widget(currentIndex);
tearOffWidget->setParent(detachedWidget);
// Add it to the windows list
mWindows.append(tearOffWidget);
// Create and show
detachedWidget->setCentralWidget(tearOffWidget);
// Needs to be done explicitly
tearOffWidget->showNormal();
QRect screenGeometry = QApplication::desktop()->screenGeometry();
int w = 640;
int h = 480;
int x = (screenGeometry.width() - w) / 2;
int y = (screenGeometry.height() - h) / 2;
detachedWidget->showNormal();
detachedWidget->setGeometry(x, y, w, h);
detachedWidget->showNormal();
mNames.removeAt(currentIndex);
}
void LabeledSplitter::attachSlot(LabeledSplitterDetachedWindow* widget)
{
// Retrieve widget
QWidget* tearOffWidget = widget->centralWidget();
// Remove it from the windows list
for(int i = 0; i < mWindows.size(); i++)
{
if(mWindows.at(i) == tearOffWidget)
{
mWindows.removeAt(i);
}
}
// Make Active
insertWidget(widget->index, tearOffWidget, widget->windowTitle());
// Cleanup Window
disconnect(widget, SIGNAL(OnClose(QWidget*)), this, SLOT(attachSlot(LabeledSplitterDetachedWindow*)));
widget->hide();
widget->close();
}
void LabeledSplitterHandle::paintEvent(QPaintEvent* event)
{
QPainter painter(this);
const QRect & rect = event->rect();
painter.fillRect(rect, Qt::gray);
painter.setPen(Qt::black);
LabeledSplitter* parent = getParent();
int index = parent->indexOf(this);
if(parent->sizes().at(index) != 0)
{
//hidden
QPoint points[3] = {QPoint(charHeight / 5, charHeight / 3), QPoint(charHeight * 4 / 5, charHeight / 3), QPoint(charHeight / 2, charHeight * 2 / 3)};
painter.setPen(Qt::black);
painter.setBrush(Qt::green);
painter.drawConvexPolygon(points, 3);
}
else
{
QPoint points[3] = {QPoint(charHeight / 5, charHeight * 2 / 3), QPoint(charHeight * 4 / 5, charHeight * 2 / 3), QPoint(charHeight / 2, charHeight / 3)};
painter.setPen(Qt::black);
painter.setBrush(Qt::green);
painter.drawConvexPolygon(points, 3);
painter.drawLine(rect.left(), rect.height() - 1, rect.right(), rect.height() - 1);
}
QRect textRect(rect.left() + charHeight, rect.top(), rect.width() - charHeight, rect.height());
painter.drawText(textRect, 0, parent->mNames.at(index));
}
void LabeledSplitterHandle::mouseMoveEvent(QMouseEvent* event)
{
if(event->x() <= charHeight)
{
this->setCursor(QCursor(Qt::ArrowCursor));
event->accept();
}
else
{
this->setCursor(QCursor(Qt::SplitVCursor));
QSplitterHandle::mouseMoveEvent(event);
}
}
void LabeledSplitterHandle::mousePressEvent(QMouseEvent* event)
{
if(event->x() <= charHeight && event->button() & Qt::LeftButton)
{
LabeledSplitter* parent = getParent();
auto sizes = parent->sizes();
int index = parent->indexOf(this);
int index2;
for(index2 = index - 1; sizes.at(index2) == 0 && index2 != 0; index2--);
if(sizes.at(index) == 0)
{
if(originalSize == 0)
originalSize = 100;
if(sizes[index2] > originalSize)
sizes[index2] -= originalSize;
sizes[index] = originalSize;
}
else
{
originalSize = sizes[index];
sizes[index] = 0;
sizes[index2] += originalSize;
}
parent->setSizes(sizes);
event->accept();
}
else
QSplitterHandle::mousePressEvent(event);
}
// LabeledSplitter class
LabeledSplitter::LabeledSplitter(QWidget* parent) : QSplitter(Qt::Vertical, parent)
{
setupContextMenu();
}
QSplitterHandle* LabeledSplitter::createHandle()
{
return new LabeledSplitterHandle(orientation(), this);
}
void LabeledSplitter::addWidget(QWidget* widget, const QString & name)
{
mNames.push_back(name);
addWidget(widget);
}
void LabeledSplitter::addWidget(QWidget* widget)
{
QSplitter::addWidget(widget);
}
void LabeledSplitter::collapseLowerTabs()
{
if(count() > 3)
{
auto size = sizes();
size[0] = 1;
size[1] = 1;
size[2] = 1;
for(int i = 3; i < size.count(); i++)
size[i] = 0;
setSizes(size);
}
}
void LabeledSplitter::insertWidget(int index, QWidget* widget, const QString & name)
{
mNames.insert(index, name);
insertWidget(index, widget);
}
void LabeledSplitter::insertWidget(int index, QWidget* widget)
{
QSplitter::insertWidget(index, widget);
}
void LabeledSplitter::contextMenuEvent(QContextMenuEvent* event)
{
event->accept();
if(sizes().at(currentIndex) != 0)
mExpandCollapseAction->setText(tr("&Collapse"));
else
mExpandCollapseAction->setText(tr("&Expand"));
mMenu->exec(mapToGlobal(event->pos()));
}
void LabeledSplitter::loadFromConfig(const QString & configName)
{
if(!configName.isEmpty())
{
mConfigName = configName;
char state[MAX_SETTING_SIZE];
memset(state, 0, sizeof(state));
BridgeSettingGet("Gui", mConfigName.toUtf8().constData(), state);
size_t sizeofState = strlen(state);
if(sizeofState > 0)
this->restoreState(QByteArray::fromBase64(QByteArray(state, int(sizeofState))));
connect(Bridge::getBridge(), SIGNAL(shutdown()), this, SLOT(shutdownSlot()));
}
}
void LabeledSplitter::shutdownSlot()
{
if(Config()->getBool("Gui", "SaveColumnOrder"))
BridgeSettingSet("Gui", mConfigName.toUtf8().constData(), this->saveState().toBase64().data());
} |
C/C++ | x64dbg-development/src/gui/Src/BasicView/LabeledSplitter.h | #pragma once
#include <QSplitter>
class LabeledSplitter;
class QMenu;
class QAction;
class LabeledSplitterDetachedWindow;
class LabeledSplitter : public QSplitter
{
Q_OBJECT
public:
LabeledSplitter(QWidget* parent);
void addWidget(QWidget* widget, const QString & name);
void insertWidget(int index, QWidget* widget, const QString & name);
void collapseLowerTabs();
void loadFromConfig(const QString & configName);
public slots:
void attachSlot(LabeledSplitterDetachedWindow* widget);
void contextMenuEvent(QContextMenuEvent* event);
protected slots:
void detachSlot();
void collapseSlot();
void shutdownSlot();
protected:
QMenu* mMenu;
QAction* mExpandCollapseAction;
QString mConfigName;
int currentIndex;
void setOrientation(Qt::Orientation o); // LabeledSplitter is always vertical
void addWidget(QWidget* widget);
void insertWidget(int index, QWidget* widget);
QSplitterHandle* createHandle() override;
void setupContextMenu();
friend class LabeledSplitterHandle;
private:
QList<QString> mNames;
QList<QWidget*> mWindows;
}; |
C++ | x64dbg-development/src/gui/Src/BasicView/LabeledSplitterDetachedWindow.cpp | #include "LabeledSplitterDetachedWindow.h"
LabeledSplitterDetachedWindow::LabeledSplitterDetachedWindow(QWidget* parent, LabeledSplitter* splitterwidget)
: QMainWindow(parent),
index(0)
{
mSplitterWidget = splitterwidget;
}
LabeledSplitterDetachedWindow::~LabeledSplitterDetachedWindow()
{
}
void LabeledSplitterDetachedWindow::closeEvent(QCloseEvent* event)
{
Q_UNUSED(event);
emit OnClose(this);
} |
C/C++ | x64dbg-development/src/gui/Src/BasicView/LabeledSplitterDetachedWindow.h | #pragma once
#include <QMainWindow>
#include <QSplitterHandle>
class LabeledSplitter;
class LabeledSplitterHandle : public QSplitterHandle
{
Q_OBJECT
public:
LabeledSplitterHandle(Qt::Orientation o, LabeledSplitter* parent);
int originalSize;
protected slots:
QSize sizeHint() const override;
QSize minimumSizeHint() const override;
void mouseMoveEvent(QMouseEvent* event) override;
void mousePressEvent(QMouseEvent* event) override;
void paintEvent(QPaintEvent* event) override;
void contextMenuEvent(QContextMenuEvent* event) override;
protected:
int getIndex();
LabeledSplitter* getParent() const;
int charHeight;
};
class LabeledSplitterDetachedWindow : public QMainWindow
{
Q_OBJECT
public:
LabeledSplitterDetachedWindow(QWidget* parent = 0, LabeledSplitter* splitterwidget = 0);
~LabeledSplitterDetachedWindow();
int index;
signals:
void OnClose(LabeledSplitterDetachedWindow* widget);
protected:
void closeEvent(QCloseEvent* event);
LabeledSplitter* mSplitterWidget;
}; |
C++ | x64dbg-development/src/gui/Src/BasicView/ReferenceView.cpp | #include <QHBoxLayout>
#include <QMessageBox>
#include <QLabel>
#include <QTabWidget>
#include "ReferenceView.h"
#include "Configuration.h"
#include "Bridge.h"
#include "MiscUtil.h"
ReferenceView::ReferenceView(bool sourceView, QWidget* parent) : StdSearchListView(parent, true, false), mParent(dynamic_cast<QTabWidget*>(parent))
{
// Setup SearchListView settings
mSearchStartCol = 1;
enableMultiSelection(true);
// Widget container for progress
QWidget* progressWidget = new QWidget(this);
// Create the layout for the progress bars
QHBoxLayout* layoutProgress = new QHBoxLayout();
progressWidget->setLayout(layoutProgress);
layoutProgress->setContentsMargins(2, 0, 0, 0);
layoutProgress->setSpacing(4);
// Create current task search progress bar
mSearchCurrentTaskProgress = new QProgressBar();
mSearchCurrentTaskProgress->setRange(0, 100);
mSearchCurrentTaskProgress->setTextVisible(true);
mSearchCurrentTaskProgress->setMaximumHeight(15);
layoutProgress->addWidget(mSearchCurrentTaskProgress);
// Create total search progress bar
mSearchTotalProgress = new QProgressBar();
mSearchTotalProgress->setRange(0, 100);
mSearchTotalProgress->setTextVisible(true);
mSearchTotalProgress->setMaximumHeight(15);
layoutProgress->addWidget(mSearchTotalProgress);
// Label for the number of references
mCountTotalLabel = new QLabel("");
mCountTotalLabel->setAlignment(Qt::AlignCenter);
mCountTotalLabel->setMaximumHeight(16);
mCountTotalLabel->setMinimumWidth(40);
mCountTotalLabel->setContentsMargins(2, 0, 5, 0);
layoutProgress->addWidget(mCountTotalLabel);
if(!sourceView)
{
// Add the progress bar and label to the main layout
layout()->addWidget(progressWidget);
}
connect(this, SIGNAL(listContextMenuSignal(QMenu*)), this, SLOT(referenceContextMenu(QMenu*)));
connect(this, SIGNAL(enterPressedSignal()), this, SLOT(followGenericAddress()));
setupContextMenu();
}
void ReferenceView::setupContextMenu()
{
QIcon disassembler = DIcon(ArchValue("processor32", "processor64"));
mFollowAddress = new QAction(disassembler, tr("&Follow in Disassembler"), this);
connect(mFollowAddress, SIGNAL(triggered()), this, SLOT(followAddress()));
mFollowDumpAddress = new QAction(DIcon("dump"), tr("Follow in &Dump"), this);
connect(mFollowDumpAddress, SIGNAL(triggered()), this, SLOT(followDumpAddress()));
mFollowApiAddress = new QAction(tr("Follow &API Address"), this);
connect(mFollowApiAddress, SIGNAL(triggered()), this, SLOT(followApiAddress()));
mToggleBreakpoint = new QAction(DIcon("breakpoint_toggle"), tr("Toggle Breakpoint"), this);
mToggleBreakpoint->setShortcutContext(Qt::WidgetWithChildrenShortcut);
addAction(mToggleBreakpoint);
StdSearchListView::addAction(mToggleBreakpoint);
connect(mToggleBreakpoint, SIGNAL(triggered()), this, SLOT(toggleBreakpoint()));
mToggleBookmark = new QAction(DIcon("bookmark_toggle"), tr("Toggle Bookmark"), this);
mToggleBookmark->setShortcutContext(Qt::WidgetWithChildrenShortcut);
addAction(mToggleBookmark);
StdSearchListView::addAction(mToggleBookmark);
connect(mToggleBookmark, SIGNAL(triggered()), this, SLOT(toggleBookmark()));
mSetBreakpointOnAllCommands = new QAction(DIcon("breakpoint_seton_all_commands"), tr("Set breakpoint on all commands"), this);
connect(mSetBreakpointOnAllCommands, SIGNAL(triggered()), this, SLOT(setBreakpointOnAllCommands()));
mRemoveBreakpointOnAllCommands = new QAction(DIcon("breakpoint_remove_all_commands"), tr("Remove breakpoint on all commands"), this);
connect(mRemoveBreakpointOnAllCommands, SIGNAL(triggered()), this, SLOT(removeBreakpointOnAllCommands()));
mSetBreakpointOnAllApiCalls = new QAction(tr("Set breakpoint on all api calls"), this);
connect(mSetBreakpointOnAllApiCalls, SIGNAL(triggered()), this, SLOT(setBreakpointOnAllApiCalls()));
mRemoveBreakpointOnAllApiCalls = new QAction(tr("Remove breakpoint on all api calls"), this);
connect(mRemoveBreakpointOnAllApiCalls, SIGNAL(triggered()), this, SLOT(removeBreakpointOnAllApiCalls()));
refreshShortcutsSlot();
connect(Config(), SIGNAL(shortcutsUpdated()), this, SLOT(refreshShortcutsSlot()));
}
void ReferenceView::connectBridge()
{
connect(Bridge::getBridge(), SIGNAL(referenceReloadData()), this, SLOT(reloadDataSlot()));
connect(Bridge::getBridge(), SIGNAL(referenceSetSingleSelection(int, bool)), this, SLOT(setSingleSelection(int, bool)));
connect(Bridge::getBridge(), SIGNAL(referenceSetProgress(int)), this, SLOT(referenceSetProgressSlot(int)));
connect(Bridge::getBridge(), SIGNAL(referenceSetCurrentTaskProgress(int, QString)), this, SLOT(referenceSetCurrentTaskProgressSlot(int, QString)));
connect(Bridge::getBridge(), SIGNAL(referenceAddCommand(QString, QString)), this, SLOT(addCommand(QString, QString)));
connect(stdSearchList(), SIGNAL(selectionChangedSignal(int)), this, SLOT(searchSelectionChanged(int)));
connect(stdList(), SIGNAL(selectionChangedSignal(int)), this, SLOT(searchSelectionChanged(int)));
}
void ReferenceView::disconnectBridge()
{
disconnect(Bridge::getBridge(), SIGNAL(referenceReloadData()), this, SLOT(reloadDataSlot()));
disconnect(Bridge::getBridge(), SIGNAL(referenceSetSingleSelection(int, bool)), this, SLOT(setSingleSelection(int, bool)));
disconnect(Bridge::getBridge(), SIGNAL(referenceSetProgress(int)), this, SLOT(referenceSetProgressSlot(int)));
disconnect(Bridge::getBridge(), SIGNAL(referenceSetCurrentTaskProgress(int, QString)), this, SLOT(referenceSetCurrentTaskProgressSlot(int, QString)));
disconnect(Bridge::getBridge(), SIGNAL(referenceAddCommand(QString, QString)), this, SLOT(addCommand(QString, QString)));
disconnect(stdSearchList(), SIGNAL(selectionChangedSignal(int)), this, SLOT(searchSelectionChanged(int)));
disconnect(stdList(), SIGNAL(selectionChangedSignal(int)), this, SLOT(searchSelectionChanged(int)));
}
int ReferenceView::progress() const
{
return mSearchTotalProgress->value();
}
int ReferenceView::currentTaskProgress() const
{
return mSearchCurrentTaskProgress->value();
}
void ReferenceView::refreshShortcutsSlot()
{
mToggleBreakpoint->setShortcut(ConfigShortcut("ActionToggleBreakpoint"));
mToggleBookmark->setShortcut(ConfigShortcut("ActionToggleBookmark"));
}
void ReferenceView::referenceSetProgressSlot(int progress)
{
mSearchTotalProgress->setValue(progress);
mSearchTotalProgress->setAlignment(Qt::AlignCenter);
mSearchTotalProgress->setFormat(tr("Total Progress %1%").arg(QString::number(progress)));
mCountTotalLabel->setText(QString("%1").arg(stdList()->getRowCount()));
}
void ReferenceView::referenceSetCurrentTaskProgressSlot(int progress, QString taskTitle)
{
mSearchCurrentTaskProgress->setValue(progress);
mSearchCurrentTaskProgress->setAlignment(Qt::AlignCenter);
mSearchCurrentTaskProgress->setFormat(taskTitle + " " + QString::number(progress) + "%");
}
void ReferenceView::searchSelectionChanged(int index)
{
DbgValToString("$__disasm_refindex", index);
DbgValToString("$__dump_refindex", index);
}
void ReferenceView::reloadDataSlot()
{
if(mUpdateCountLabel)
{
mUpdateCountLabel = true;
mCountTotalLabel->setText(QString("%1").arg(stdList()->getRowCount()));
}
reloadData();
}
void ReferenceView::addColumnAtRef(int width, QString title)
{
int charwidth = getCharWidth();
if(width)
width = charwidth * width + 8;
else
width = 0;
clearFilter();
if(title.toLower() == "&data&")
title = "Data";
StdSearchListView::addColumnAt(width, title, true);
}
void ReferenceView::setRowCount(dsint count)
{
if(!stdList()->getRowCount() && count) //from zero to N rows
searchSelectionChanged(0);
mUpdateCountLabel = true;
StdSearchListView::setRowCount(count);
}
void ReferenceView::setSingleSelection(int index, bool scroll)
{
clearFilter();
stdList()->setSingleSelection(index);
if(scroll) //TODO: better scrolling
stdList()->setTableOffset(index);
}
void ReferenceView::addCommand(QString title, QString command)
{
mCommandTitles.append(title);
mCommands.append(command);
}
void ReferenceView::referenceContextMenu(QMenu* wMenu)
{
if(!mCurList->getRowCount())
return;
QString text = mCurList->getCellContent(mCurList->getInitialSelection(), 0);
duint addr;
if(!DbgFunctions()->ValFromString(text.toUtf8().constData(), &addr))
return;
if(DbgMemIsValidReadPtr(addr))
{
wMenu->addAction(mFollowAddress);
wMenu->addAction(mFollowDumpAddress);
dsint apiaddr = apiAddressFromString(mCurList->getCellContent(mCurList->getInitialSelection(), 1));
if(apiaddr)
wMenu->addAction(mFollowApiAddress);
wMenu->addSeparator();
wMenu->addAction(mToggleBreakpoint);
wMenu->addAction(mSetBreakpointOnAllCommands);
wMenu->addAction(mRemoveBreakpointOnAllCommands);
if(apiaddr)
{
char label[MAX_LABEL_SIZE] = "";
if(DbgGetLabelAt(apiaddr, SEG_DEFAULT, label))
{
wMenu->addSeparator();
mSetBreakpointOnAllApiCalls->setText(tr("Set breakpoint on all calls to %1").arg(label));
wMenu->addAction(mSetBreakpointOnAllApiCalls);
mRemoveBreakpointOnAllApiCalls->setText(tr("Remove breakpoint on all calls to %1").arg(label));
wMenu->addAction(mRemoveBreakpointOnAllApiCalls);
}
}
wMenu->addSeparator();
wMenu->addAction(mToggleBookmark);
}
if(this->mCommands.size() > 0)
{
wMenu->addSeparator();
for(auto i = 0; i < this->mCommandTitles.size(); i++)
{
QAction* newCommandAction = new QAction(this->mCommandTitles.at(i), wMenu);
newCommandAction->setData(QVariant(mCommands.at(i)));
connect(newCommandAction, SIGNAL(triggered()), this, SLOT(referenceExecCommand()));
wMenu->addAction(newCommandAction);
}
}
}
void ReferenceView::followAddress()
{
int index = mCurList->getInitialSelection();
searchSelectionChanged(index);
DbgCmdExecDirect(QString("disasm " + mCurList->getCellContent(index, 0)));
}
void ReferenceView::followDumpAddress()
{
int index = mCurList->getInitialSelection();
searchSelectionChanged(index);
DbgCmdExecDirect(QString("dump " + mCurList->getCellContent(index, 0)));
}
void ReferenceView::followApiAddress()
{
dsint apiValue = apiAddressFromString(mCurList->getCellContent(mCurList->getInitialSelection(), 1));
DbgCmdExecDirect(QString("disasm " + ToPtrString(apiValue)));
}
void ReferenceView::followGenericAddress()
{
auto addr = DbgValFromString(mCurList->getCellContent(mCurList->getInitialSelection(), 0).toUtf8().constData());
if(!addr)
return;
if(DbgFunctions()->MemIsCodePage(addr, false))
followAddress();
else
{
followDumpAddress();
emit Bridge::getBridge()->getDumpAttention();
}
}
void ReferenceView::setBreakpointAt(int row, BPSetAction action)
{
if(!DbgIsDebugging())
return;
if(!mCurList->getRowCount())
return;
QString addrText = mCurList->getCellContent(row, 0).toUtf8().constData();
duint wVA;
if(!DbgFunctions()->ValFromString(addrText.toUtf8().constData(), &wVA))
return;
if(!DbgMemIsValidReadPtr(wVA))
return;
BPXTYPE wBpType = DbgGetBpxTypeAt(wVA);
QString wCmd;
if((wBpType & bp_normal) == bp_normal)
{
if(action == Toggle || action == Remove)
wCmd = "bc " + ToPtrString(wVA);
else if(action == Disable)
wCmd = "bpd " + ToPtrString(wVA);
else if(action == Enable)
wCmd = "bpe " + ToPtrString(wVA);
}
else if(wBpType == bp_none && (action == Toggle || action == Enable))
{
wCmd = "bp " + ToPtrString(wVA);
}
DbgCmdExecDirect(wCmd);
}
void ReferenceView::toggleBreakpoint()
{
if(!DbgIsDebugging())
return;
if(!mCurList->getRowCount())
return;
GuiDisableUpdateScope s;
foreach(int i, mCurList->getSelection())
setBreakpointAt(i, Toggle);
}
void ReferenceView::setBreakpointOnAllCommands()
{
GuiDisableUpdateScope s;
for(int i = 0; i < mCurList->getRowCount(); i++)
setBreakpointAt(i, Enable);
}
void ReferenceView::removeBreakpointOnAllCommands()
{
GuiDisableUpdateScope s;
for(int i = 0; i < mCurList->getRowCount(); i++)
setBreakpointAt(i, Remove);
}
void ReferenceView::setBreakpointOnAllApiCalls()
{
if(!mCurList->getRowCount())
return;
dsint apiaddr = apiAddressFromString(mCurList->getCellContent(mCurList->getInitialSelection(), 1));
if(!apiaddr)
return;
QString apiText = mCurList->getCellContent(mCurList->getInitialSelection(), 1);
GuiDisableUpdateScope s;
for(int i = 0; i < mCurList->getRowCount(); i++)
if(mCurList->getCellContent(i, 1) == apiText)
setBreakpointAt(i, Enable);
}
void ReferenceView::removeBreakpointOnAllApiCalls()
{
if(!mCurList->getRowCount())
return;
dsint apiaddr = apiAddressFromString(mCurList->getCellContent(mCurList->getInitialSelection(), 1));
if(!apiaddr)
return;
QString apiText = mCurList->getCellContent(mCurList->getInitialSelection(), 1);
GuiDisableUpdateScope s;
for(int i = 0; i < mCurList->getRowCount(); i++)
if(mCurList->getCellContent(i, 1) == apiText)
setBreakpointAt(i, Remove);
}
void ReferenceView::toggleBookmark()
{
if(!DbgIsDebugging())
return;
if(!mCurList->getRowCount())
return;
QString addrText = mCurList->getCellContent(mCurList->getInitialSelection(), 0);
duint wVA;
if(!DbgFunctions()->ValFromString(addrText.toUtf8().constData(), &wVA))
return;
if(!DbgMemIsValidReadPtr(wVA))
return;
bool result;
if(DbgGetBookmarkAt(wVA))
result = DbgSetBookmarkAt(wVA, false);
else
result = DbgSetBookmarkAt(wVA, true);
if(!result)
SimpleErrorBox(this, tr("Error!"), tr("DbgSetBookmarkAt failed!"));
GuiUpdateAllViews();
}
dsint ReferenceView::apiAddressFromString(const QString & s)
{
QRegExp regEx("call.+<(.+)>");
regEx.indexIn(s);
QStringList list = regEx.capturedTexts();
if(list.length() < 2)
return 0;
QString match = list[1];
if(match[0] == QChar('&'))
match.remove(0, 1);
duint value;
return DbgFunctions()->ValFromString(match.toUtf8().constData(), &value) && DbgMemIsValidReadPtr(value) ? value : 0;
}
void ReferenceView::referenceExecCommand()
{
QAction* act = qobject_cast<QAction*>(sender());
if(act != nullptr)
{
QString command = act->data().toString();
for(int selected : mCurList->getSelection()) //to do: enable multi-selection
{
QString specializedCommand = command;
for(int i = 0; i < mCurList->getColumnCount(); i++)
{
QString token = "$" + QString::number(i);
if(specializedCommand.contains(token))
specializedCommand.replace(token, mCurList->getCellContent(selected, i));
}
DbgCmdExec(specializedCommand);
}
}
}
void ReferenceView::mouseReleaseEvent(QMouseEvent* event)
{
if(mParent)
{
if(event->button() == Qt::ForwardButton)
mParent->setCurrentIndex(std::min(mParent->currentIndex() + 1, mParent->count()));
else if(event->button() == Qt::BackButton)
mParent->setCurrentIndex(std::max(mParent->currentIndex() - 1, 0));
}
} |
C/C++ | x64dbg-development/src/gui/Src/BasicView/ReferenceView.h | #pragma once
#include <QProgressBar>
#include <QLabel>
#include "StdSearchListView.h"
class DisassemblyPopup;
class QTabWidget;
class ReferenceView : public StdSearchListView
{
Q_OBJECT
public:
ReferenceView(bool sourceView = false, QWidget* parent = nullptr);
void setupContextMenu();
void connectBridge();
void disconnectBridge();
int progress() const;
int currentTaskProgress() const;
public slots:
void addColumnAtRef(int width, QString title);
void setRowCount(dsint count) override;
void setSingleSelection(int index, bool scroll);
void addCommand(QString title, QString command);
void referenceContextMenu(QMenu* wMenu);
void followAddress();
void followDumpAddress();
void followApiAddress();
void followGenericAddress();
void toggleBreakpoint();
void setBreakpointOnAllCommands();
void removeBreakpointOnAllCommands();
void setBreakpointOnAllApiCalls();
void removeBreakpointOnAllApiCalls();
void toggleBookmark();
void refreshShortcutsSlot();
void referenceSetProgressSlot(int progress);
void referenceSetCurrentTaskProgressSlot(int progress, QString taskTitle);
void searchSelectionChanged(int index);
void reloadDataSlot();
signals:
void showCpu();
private slots:
void referenceExecCommand();
private:
QProgressBar* mSearchTotalProgress;
QProgressBar* mSearchCurrentTaskProgress;
QAction* mFollowAddress;
QAction* mFollowDumpAddress;
QAction* mFollowApiAddress;
QAction* mToggleBreakpoint;
QAction* mToggleBookmark;
QAction* mSetBreakpointOnAllCommands;
QAction* mRemoveBreakpointOnAllCommands;
QAction* mSetBreakpointOnAllApiCalls;
QAction* mRemoveBreakpointOnAllApiCalls;
bool mUpdateCountLabel = false;
QLabel* mCountTotalLabel;
QVector<QString> mCommandTitles;
QVector<QString> mCommands;
QTabWidget* mParent;
enum BPSetAction
{
Enable,
Disable,
Toggle,
Remove
};
void setBreakpointAt(int row, BPSetAction action);
dsint apiAddressFromString(const QString & s);
void mouseReleaseEvent(QMouseEvent* event);
}; |
C++ | x64dbg-development/src/gui/Src/BasicView/SearchListView.cpp | #include <QVBoxLayout>
#include <QHBoxLayout>
#include <QSplitter>
#include <QLabel>
#include <QTimer>
#include "SearchListView.h"
#include "FlickerThread.h"
#include "MethodInvoker.h"
SearchListView::SearchListView(QWidget* parent, AbstractSearchList* abstractSearchList, bool enableRegex, bool enableLock)
: QWidget(parent), mAbstractSearchList(abstractSearchList)
{
setContextMenuPolicy(Qt::CustomContextMenu);
// Create the main button/bar view with QSplitter
//
// |- Splitter --------------------------------------------|
// | LISTVIEW |
// | SEARCH: | SEARCH BOX | LOCK CHECKBOX | REGEX CHECKBOX |
// |-------------------------------------------------------|
QSplitter* barSplitter = new QSplitter(Qt::Vertical);
{
// Create list layout (contains both ListViews)
{
// Initially hide the search list
abstractSearchList->searchList()->hide();
// Vertical layout
QVBoxLayout* listLayout = new QVBoxLayout();
listLayout->setContentsMargins(0, 0, 0, 0);
listLayout->setSpacing(0);
listLayout->addWidget(abstractSearchList->list());
listLayout->addWidget(abstractSearchList->searchList());
// Add list placeholder
QWidget* listPlaceholder = new QWidget(this);
listPlaceholder->setLayout(listLayout);
barSplitter->addWidget(listPlaceholder);
}
// Filtering elements
{
// Input box
mSearchBox = new QLineEdit();
mSearchBox->setPlaceholderText(tr("Type here to filter results..."));
// Regex parsing checkbox
mRegexCheckbox = new QCheckBox(tr("Regex"));
mRegexCheckbox->setTristate(true);
// Lock checkbox
mLockCheckbox = new QCheckBox(tr("Lock"));
if(!enableRegex)
mRegexCheckbox->hide();
if(!enableLock)
mLockCheckbox->hide();
// Horizontal layout
QHBoxLayout* horzLayout = new QHBoxLayout();
horzLayout->setContentsMargins(4, 0, (enableRegex || enableLock) ? 0 : 4, 0);
horzLayout->setSpacing(2);
QLabel* label = new QLabel(tr("Search: "), this);
label->setBuddy(mSearchBox);
horzLayout->addWidget(label);
horzLayout->addWidget(mSearchBox);
horzLayout->addWidget(mLockCheckbox);
horzLayout->addWidget(mRegexCheckbox);
// Add searchbar placeholder
QWidget* horzPlaceholder = new QWidget(this);
horzPlaceholder->setLayout(horzLayout);
barSplitter->addWidget(horzPlaceholder);
}
// Minimum size for the search box
barSplitter->setStretchFactor(0, 1000);
barSplitter->setStretchFactor(0, 1);
// Disable main splitter
for(int i = 0; i < barSplitter->count(); i++)
barSplitter->handle(i)->setEnabled(false);
}
// Set the main layout which holds the splitter
QVBoxLayout* mainLayout = new QVBoxLayout();
mainLayout->setContentsMargins(0, 0, 0, 0);
mainLayout->addWidget(barSplitter);
setLayout(mainLayout);
// Set global variables
mCurList = abstractSearchList->list();
mSearchStartCol = 0;
// Install input event filter
mSearchBox->installEventFilter(this);
if(parent)
mSearchBox->setWindowTitle(parent->metaObject()->className());
// Setup search menu action
mSearchAction = new QAction(DIcon("find"), tr("Search..."), this);
connect(mSearchAction, SIGNAL(triggered()), this, SLOT(searchSlot()));
// https://wiki.qt.io/Delay_action_to_wait_for_user_interaction
mTypingTimer = new QTimer(this);
mTypingTimer->setSingleShot(true);
connect(mTypingTimer, SIGNAL(timeout()), this, SLOT(filterEntries()));
// Slots
connect(abstractSearchList->list(), SIGNAL(contextMenuSignal(QPoint)), this, SLOT(listContextMenu(QPoint)));
connect(abstractSearchList->list(), SIGNAL(doubleClickedSignal()), this, SLOT(doubleClickedSlot()));
connect(abstractSearchList->searchList(), SIGNAL(contextMenuSignal(QPoint)), this, SLOT(listContextMenu(QPoint)));
connect(abstractSearchList->searchList(), SIGNAL(doubleClickedSignal()), this, SLOT(doubleClickedSlot()));
connect(mSearchBox, SIGNAL(textEdited(QString)), this, SLOT(searchTextEdited(QString)));
connect(mRegexCheckbox, SIGNAL(stateChanged(int)), this, SLOT(on_checkBoxRegex_stateChanged(int)));
connect(mLockCheckbox, SIGNAL(toggled(bool)), mSearchBox, SLOT(setDisabled(bool)));
// List input should always be forwarded to the filter edit
abstractSearchList->searchList()->setFocusProxy(mSearchBox);
abstractSearchList->list()->setFocusProxy(mSearchBox);
}
bool SearchListView::findTextInList(AbstractStdTable* list, QString text, int row, int startcol, bool startswith)
{
int count = list->getColumnCount();
if(startcol + 1 > count)
return false;
if(startswith)
{
for(int i = startcol; i < count; i++)
if(list->getCellContent(row, i).startsWith(text, Qt::CaseInsensitive))
return true;
}
else
{
for(int i = startcol; i < count; i++)
{
auto state = mRegexCheckbox->checkState();
if(state != Qt::Unchecked)
{
if(list->getCellContent(row, i).contains(QRegExp(text, state == Qt::PartiallyChecked ? Qt::CaseInsensitive : Qt::CaseSensitive)))
return true;
}
else
{
if(list->getCellContent(row, i).contains(text, Qt::CaseInsensitive))
return true;
}
}
}
return false;
}
void SearchListView::filterEntries()
{
mAbstractSearchList->lock();
// store the first selection value
QString mLastFirstColValue;
auto selList = mCurList->getSelection();
if(!selList.empty() && mCurList->isValidIndex(selList[0], 0))
mLastFirstColValue = mCurList->getCellContent(selList[0], 0);
// get the correct previous list instance
auto mPrevList = mAbstractSearchList->list()->isVisible() ? mAbstractSearchList->list() : mAbstractSearchList->searchList();
if(mFilterText.length())
{
MethodInvoker::invokeMethod([this]()
{
mAbstractSearchList->list()->hide();
mAbstractSearchList->searchList()->show();
});
mCurList = mAbstractSearchList->searchList();
// filter the list
auto filterType = AbstractSearchList::FilterContainsTextCaseInsensitive;
switch(mRegexCheckbox->checkState())
{
case Qt::PartiallyChecked:
filterType = AbstractSearchList::FilterRegexCaseInsensitive;
break;
case Qt::Checked:
filterType = AbstractSearchList::FilterRegexCaseSensitive;
break;
}
mAbstractSearchList->filter(mFilterText, filterType, mSearchStartCol);
}
else
{
MethodInvoker::invokeMethod([this]()
{
mAbstractSearchList->searchList()->hide();
mAbstractSearchList->list()->show();
});
mCurList = mAbstractSearchList->list();
}
// attempt to restore previous selection
bool hasSetSingleSelection = false;
if(!mLastFirstColValue.isEmpty())
{
int rows = mCurList->getRowCount();
mCurList->setTableOffset(0);
for(int i = 0; i < rows; i++)
{
if(mCurList->getCellContent(i, 0) == mLastFirstColValue)
{
if(rows > mCurList->getViewableRowsCount())
{
int cur = i - mCurList->getViewableRowsCount() / 2;
if(!mCurList->isValidIndex(cur, 0))
cur = i;
mCurList->setTableOffset(cur);
}
mCurList->setSingleSelection(i);
hasSetSingleSelection = true;
break;
}
}
}
if(!hasSetSingleSelection)
mCurList->setSingleSelection(0);
if(!mCurList->getRowCount())
emit emptySearchResult();
// Do not highlight with regex
// TODO: fully respect highlighting mode
if(mRegexCheckbox->checkState() == Qt::Unchecked)
mAbstractSearchList->searchList()->setHighlightText(mFilterText, mSearchStartCol);
else
mAbstractSearchList->searchList()->setHighlightText(QString());
// Reload the search list data
mAbstractSearchList->searchList()->reloadData();
// setup the same layout of the previous list control
if(mPrevList != mCurList)
{
int cols = mPrevList->getColumnCount();
for(int i = 0; i < cols; i++)
{
mCurList->setColumnOrder(i, mPrevList->getColumnOrder(i));
mCurList->setColumnHidden(i, mPrevList->getColumnHidden(i));
mCurList->setColumnWidth(i, mPrevList->getColumnWidth(i));
}
}
mAbstractSearchList->unlock();
}
void SearchListView::searchTextEdited(const QString & text)
{
mFilterText = text;
mAbstractSearchList->lock();
mTypingTimer->setInterval([](dsint rowCount)
{
// These numbers are kind of arbitrarily chosen, but seem to work
if(rowCount <= 10000)
return 0;
else if(rowCount <= 600000)
return 100;
else
return 350;
}(mAbstractSearchList->list()->getRowCount()));
mAbstractSearchList->unlock();
mTypingTimer->start(); // This will fire filterEntries after interval ms.
// If the user types something before it fires, the timer restarts counting
}
void SearchListView::refreshSearchList()
{
filterEntries();
}
void SearchListView::clearFilter()
{
bool isFilterAlreadyEmpty = mFilterText.isEmpty();
mFilterText.clear();
if(!isFilterAlreadyEmpty)
{
MethodInvoker::invokeMethod([this]()
{
mSearchBox->clear();
});
filterEntries();
}
}
void SearchListView::listContextMenu(const QPoint & pos)
{
QMenu wMenu(this);
emit listContextMenuSignal(&wMenu);
wMenu.addSeparator();
wMenu.addAction(mSearchAction);
QMenu wCopyMenu(tr("&Copy"), this);
wCopyMenu.setIcon(DIcon("copy"));
mCurList->setupCopyMenu(&wCopyMenu);
if(wCopyMenu.actions().length())
wMenu.addMenu(&wCopyMenu);
wMenu.exec(mCurList->mapToGlobal(pos));
}
void SearchListView::doubleClickedSlot()
{
emit enterPressedSignal();
}
void SearchListView::on_checkBoxRegex_stateChanged(int state)
{
QString tooltip;
switch(state)
{
default:
case Qt::Unchecked:
//No tooltip
break;
case Qt::Checked:
tooltip = tr("Use case sensitive regular expression");
break;
case Qt::PartiallyChecked:
tooltip = tr("Use case insensitive regular expression");
break;
}
mRegexCheckbox->setToolTip(tooltip);
refreshSearchList();
}
bool SearchListView::isSearchBoxLocked()
{
return mLockCheckbox->isChecked();
}
bool SearchListView::eventFilter(QObject* obj, QEvent* event)
{
// Keyboard button press being sent to the QLineEdit
if(obj == mSearchBox && event->type() == QEvent::KeyPress)
{
QKeyEvent* keyEvent = static_cast<QKeyEvent*>(event);
switch(keyEvent->key())
{
// The user pressed enter/return
case Qt::Key_Return:
case Qt::Key_Enter:
if(mCurList->getCellContent(mCurList->getInitialSelection(), 0).length())
emit enterPressedSignal();
return true;
// Search box misc controls
case Qt::Key_Escape:
mSearchBox->clear();
case Qt::Key_Left:
case Qt::Key_Right:
case Qt::Key_Backspace:
case Qt::Key_Delete:
case Qt::Key_Home:
case Qt::Key_End:
case Qt::Key_Insert:
return QWidget::eventFilter(obj, event);
// Search box shortcuts
case Qt::Key_V: //Ctrl+V
case Qt::Key_X: //Ctrl+X
case Qt::Key_Z: //Ctrl+Z
case Qt::Key_A: //Ctrl+A
case Qt::Key_Y: //Ctrl+Y
if(keyEvent->modifiers() == Qt::CTRL)
return QWidget::eventFilter(obj, event);
}
// Printable characters go to the search box
QString keyText = keyEvent->text();
if(!keyText.isEmpty() && QChar(keyText.toUtf8().at(0)).isPrint())
return QWidget::eventFilter(obj, event);
// By default, all other keys are forwarded to the search view
return QApplication::sendEvent(mCurList, event);
}
return QWidget::eventFilter(obj, event);
}
void SearchListView::searchSlot()
{
FlickerThread* thread = new FlickerThread(mSearchBox, this);
connect(thread, SIGNAL(setStyleSheet(QString)), mSearchBox, SLOT(setStyleSheet(QString)));
connect(thread, SIGNAL(finished()), thread, SLOT(deleteLater()));
thread->start();
} |
C/C++ | x64dbg-development/src/gui/Src/BasicView/SearchListView.h | #pragma once
#include <QWidget>
#include <QLineEdit>
#include <QCheckBox>
#include "MenuBuilder.h"
#include "ActionHelpers.h"
#include "AbstractSearchList.h"
class SearchListView : public QWidget, public ActionHelper<SearchListView>
{
Q_OBJECT
public:
explicit SearchListView(QWidget* parent, AbstractSearchList* abstractSearchList, bool enableRegex, bool enableLock);
AbstractStdTable* mCurList;
int mSearchStartCol;
bool findTextInList(AbstractStdTable* list, QString text, int row, int startcol, bool startswith);
void refreshSearchList();
void clearFilter();
bool isSearchBoxLocked();
private slots:
void filterEntries();
void searchTextEdited(const QString & text);
void listContextMenu(const QPoint & pos);
void doubleClickedSlot();
void searchSlot();
void on_checkBoxRegex_stateChanged(int state);
signals:
void enterPressedSignal();
void listContextMenuSignal(QMenu* wMenu);
void emptySearchResult();
protected:
bool eventFilter(QObject* obj, QEvent* event);
private:
QLineEdit* mSearchBox;
QCheckBox* mRegexCheckbox;
QCheckBox* mLockCheckbox;
QAction* mSearchAction;
QTimer* mTypingTimer;
QString mFilterText;
AbstractSearchList* mAbstractSearchList;
}; |
C++ | x64dbg-development/src/gui/Src/BasicView/ShortcutEdit.cpp | #include "ShortcutEdit.h"
#include <QStyle>
ShortcutEdit::ShortcutEdit(QWidget* parent) : QLineEdit(parent)
{
keyInt = -1;
mError = true;
}
const QKeySequence ShortcutEdit::getKeysequence() const
{
if(keyInt == -1) //return empty on -1
return QKeySequence();
// returns current keystroke combination
return QKeySequence(keyInt);
}
bool ShortcutEdit::error() const
{
return mError;
}
void ShortcutEdit::setErrorState(bool error)
{
this->mError = error;
this->style()->unpolish(this);
this->style()->polish(this);
}
void ShortcutEdit::keyPressEvent(QKeyEvent* event)
{
keyInt = event->key();
// find key-id
const Qt::Key key = static_cast<Qt::Key>(keyInt);
// we do not know how to handle this case
if(key == Qt::Key_unknown)
{
keyInt = -1;
emit askForSave();
return;
}
// Workaround for Shift+Tab
if(keyInt == Qt::Key_Backtab)
keyInt = Qt::Key_Tab;
// any combination of "Ctrl, Alt, Shift" ?
Qt::KeyboardModifiers modifiers = event->modifiers();
QString text = event->text();
// The shift modifier only counts when it is not used to type a symbol
// that is only reachable using the shift key anyway
// Fix from: https://bbs.pediy.com/thread-270394.htm
if(modifiers.testFlag(Qt::ShiftModifier) && (text.isEmpty() ||
!text.at(0).isPrint() ||
text.at(0).isLetterOrNumber() ||
text.at(0).isSpace()) &&
(!((keyInt >= Qt::Key_Exclam) && (keyInt <= Qt::Key_Slash)) ||
((keyInt >= Qt::Key_Colon) && (keyInt <= Qt::Key_At)) ||
((keyInt >= Qt::Key_BracketLeft) && (keyInt <= Qt::Key_QuoteLeft))))
keyInt += Qt::SHIFT;
if(modifiers.testFlag(Qt::ControlModifier))
keyInt += Qt::CTRL;
if(modifiers.testFlag(Qt::AltModifier))
keyInt += Qt::ALT;
// some strange cases (only Ctrl)
QString KeyText = QKeySequence(keyInt).toString(QKeySequence::NativeText);
for(int i = 0; i < KeyText.length(); i++)
{
if(KeyText[i].toLatin1() == 0)
{
setText("");
keyInt = -1;
emit askForSave();
return;
}
}
// display key combination
setText(QKeySequence(keyInt).toString(QKeySequence::NativeText));
// do not forward keypress-event
event->setAccepted(true);
// everything is fine , so ask for saving
emit askForSave();
} |
C/C++ | x64dbg-development/src/gui/Src/BasicView/ShortcutEdit.h | #pragma once
#include <QLineEdit>
#include <QKeySequence>
#include <QKeyEvent>
class ShortcutEdit : public QLineEdit
{
Q_OBJECT
Q_PROPERTY(bool error MEMBER mError READ error)
int keyInt;
bool mError;
public:
explicit ShortcutEdit(QWidget* parent = 0);
const QKeySequence getKeysequence() const;
bool error() const;
public slots:
void setErrorState(bool error);
signals:
void askForSave();
protected:
void keyPressEvent(QKeyEvent* event);
}; |
C++ | x64dbg-development/src/gui/Src/BasicView/StdIconSearchListView.cpp | #include "StdIconSearchListView.h"
StdIconSearchListView::StdIconSearchListView(QWidget* parent, bool enableRegex, bool enableLock)
: StdIconSearchListView(parent, enableRegex, enableLock, new StdTableSearchList(new StdIconTable(), new StdIconTable()))
{
}
StdIconSearchListView::StdIconSearchListView(QWidget* parent, bool enableRegex, bool enableLock, StdTableSearchList* tableSearchList)
: StdSearchListView(parent, enableRegex, enableLock, tableSearchList)
{
}
void StdIconSearchListView::setIconColumn(int c)
{
qobject_cast<StdIconTable*>(stdList())->setIconColumn(c);
qobject_cast<StdIconTable*>(stdSearchList())->setIconColumn(c);
}
void StdIconSearchListView::setRowIcon(int r, const QIcon & icon)
{
//clearFilter();
qobject_cast<StdIconTable*>(stdList())->setRowIcon(r, icon);
} |
C/C++ | x64dbg-development/src/gui/Src/BasicView/StdIconSearchListView.h | #pragma once
#include "StdSearchListView.h"
#include "StdIconTable.h"
class StdIconSearchListView : public StdSearchListView
{
Q_OBJECT
public:
StdIconSearchListView(QWidget* parent, bool enableRegex, bool enableLock);
StdIconSearchListView(QWidget* parent, bool enableRegex, bool enableLock, StdTableSearchList* tableSearchList);
public slots:
void setIconColumn(int c);
void setRowIcon(int r, const QIcon & icon);
private:
StdTableSearchList* mSearchListData;
protected:
friend class SymbolView;
friend class Bridge;
}; |
C++ | x64dbg-development/src/gui/Src/BasicView/StdIconTable.cpp | #include "StdIconTable.h"
/************************************************************************************
Data Management
************************************************************************************/
void StdIconTable::setRowIcon(int r, const QIcon & icon)
{
mIcon.at(r) = icon;
}
QIcon StdIconTable::getRowIcon(int r) const
{
return mIcon.at(r);
}
void StdIconTable::setIconColumn(int c)
{
mIconColumn = c;
}
int StdIconTable::getIconColumn() const
{
return mIconColumn;
}
void StdIconTable::setRowCount(dsint count)
{
int wRowToAddOrRemove = count - int(mIcon.size());
for(int i = 0; i < qAbs(wRowToAddOrRemove); i++)
{
if(wRowToAddOrRemove > 0)
mIcon.push_back(QIcon());
else
mIcon.pop_back();
}
StdTable::setRowCount(count);
}
void StdIconTable::sortRows(int column, bool ascending)
{
auto sortFn = mColumnSortFunctions.at(column);
std::vector<size_t> index;
index.resize(mData.size());
size_t i;
for(i = 0; i < mData.size(); i++)
{
index[i] = i;
}
std::stable_sort(index.begin(), index.end(), [column, ascending, this, &sortFn](const size_t & a, const size_t & b)
{
auto less = sortFn(mData.at(a).at(column).text, mData.at(b).at(column).text);
return ascending ? less : !less;
});
auto copy1 = mData;
auto copy2 = mIcon;
for(i = 0; i < mData.size(); i++)
{
mData[i] = std::move(copy1[index[i]]);
mIcon[i] = std::move(copy2[index[i]]);
}
}
QString StdIconTable::paintContent(QPainter* painter, dsint rowBase, int rowOffset, int col, int x, int y, int w, int h)
{
if(col == mIconColumn)
{
// Draw the selection first, so that transparent icons are drawn properly
if(isSelected(rowBase, rowOffset))
painter->fillRect(QRect(x, y, w, h), QBrush(mSelectionColor));
mIcon.at(rowBase + rowOffset).paint(painter, x, y, h, h);
QString wStr = StdTable::paintContent(painter, rowBase, rowOffset, col, x + h, y, w - h, h);
if(wStr.length())
{
painter->setPen(getCellColor(rowBase + rowOffset, col));
painter->drawText(QRect(x + 4 + h, y, w - 4 - h, h), Qt::AlignVCenter | Qt::AlignLeft, wStr);
}
return QString();
}
else
return StdTable::paintContent(painter, rowBase, rowOffset, col, x, y, w, h);
} |
C/C++ | x64dbg-development/src/gui/Src/BasicView/StdIconTable.h | #pragma once
#include "StdTable.h"
// StdIconTable extends StdTable by adding icons to one of the columns
class StdIconTable : public StdTable
{
Q_OBJECT
public:
explicit StdIconTable(QWidget* parent = 0) : StdTable(parent), mIconColumn(0) {}
// Data Management
void setRowIcon(int r, const QIcon & icon); // set the icon for a row
QIcon getRowIcon(int r) const;
void setIconColumn(int c); // set in which column the icons appear
int getIconColumn() const;
void setRowCount(dsint count) override;
void sortRows(int column, bool ascending) override;
QString paintContent(QPainter* painter, dsint rowBase, int rowOffset, int col, int x, int y, int w, int h) override;
protected:
std::vector<QIcon> mIcon; //listof(row) where row = (listof(col) where col = CellData)
int mIconColumn;
}; |
C++ | x64dbg-development/src/gui/Src/BasicView/StdSearchListView.cpp | #include "StdSearchListView.h"
#include "MethodInvoker.h"
StdSearchListView::StdSearchListView(QWidget* parent, bool enableRegex, bool enableLock)
: StdSearchListView(parent, enableRegex, enableLock, new StdTableSearchList())
{
}
StdSearchListView::StdSearchListView(QWidget* parent, bool enableRegex, bool enableLock, StdTableSearchList* tableSearchList)
: SearchListView(parent, mSearchListData = tableSearchList, enableRegex, enableLock)
{
setAddressColumn(0);
}
StdSearchListView::~StdSearchListView()
{
delete mSearchListData;
}
void StdSearchListView::setInternalTitle(const QString & title)
{
stdList()->setWindowTitle(title);
}
int StdSearchListView::getCharWidth()
{
return stdList()->getCharWidth();
}
void StdSearchListView::addColumnAt(int width, QString title, bool isClickable, QString copyTitle, StdTable::SortBy::t sortFn)
{
stdList()->addColumnAt(width, title, isClickable, copyTitle, sortFn);
stdSearchList()->addColumnAt(width, title, isClickable, copyTitle, sortFn);
}
void StdSearchListView::setDrawDebugOnly(bool value)
{
stdList()->setDrawDebugOnly(value);
stdSearchList()->setDrawDebugOnly(value);
}
void StdSearchListView::enableMultiSelection(bool enabled)
{
stdList()->enableMultiSelection(enabled);
stdSearchList()->enableMultiSelection(enabled);
}
void StdSearchListView::setAddressColumn(int col, bool cipBase)
{
stdList()->setAddressColumn(col, cipBase);
stdSearchList()->setAddressColumn(col, cipBase);
}
void StdSearchListView::loadColumnFromConfig(const QString & viewName)
{
stdList()->loadColumnFromConfig(viewName);
stdSearchList()->loadColumnFromConfig(viewName);
}
void StdSearchListView::setRowCount(dsint count)
{
//clearFilter();
stdList()->setRowCount(count);
}
void StdSearchListView::setCellContent(int r, int c, QString s)
{
//clearFilter();
stdList()->setCellContent(r, c, s);
}
void StdSearchListView::reloadData()
{
//clearFilter();
stdList()->reloadData();
MethodInvoker::invokeMethod([this]()
{
stdList()->setFocus();
});
}
void StdSearchListView::setSearchStartCol(int col)
{
if(col < stdList()->getColumnCount())
mSearchStartCol = col;
}
bool StdSearchListView::setDisassemblyPopupEnabled(bool enabled)
{
stdList()->setDisassemblyPopupEnabled(enabled);
return stdSearchList()->setDisassemblyPopupEnabled(enabled);
}
StdTable* StdSearchListView::stdList()
{
return mSearchListData->mList;
}
StdTable* StdSearchListView::stdSearchList()
{
return mSearchListData->mSearchList;
} |
C/C++ | x64dbg-development/src/gui/Src/BasicView/StdSearchListView.h | #pragma once
#include "SearchListView.h"
#include "StdTableSearchList.h"
class StdSearchListView : public SearchListView
{
Q_OBJECT
public:
StdSearchListView(QWidget* parent, bool enableRegex, bool enableLock);
StdSearchListView(QWidget* parent, bool enableRegex, bool enableLock, StdTableSearchList* tableSearchList);
~StdSearchListView() override;
void setInternalTitle(const QString & title);
int getCharWidth();
void addColumnAt(int width, QString title, bool isClickable, QString copyTitle = "", StdTable::SortBy::t sortFn = StdTable::SortBy::AsText);
void setDrawDebugOnly(bool value);
void enableMultiSelection(bool enabled);
void setAddressColumn(int col, bool cipBase = false);
void loadColumnFromConfig(const QString & viewName);
bool setDisassemblyPopupEnabled(bool enabled);
public slots:
virtual void setRowCount(dsint count);
void setCellContent(int r, int c, QString s);
void reloadData();
void setSearchStartCol(int col);
private:
StdTableSearchList* mSearchListData;
protected:
friend class SymbolView;
friend class Bridge;
StdTable* stdList();
StdTable* stdSearchList();
}; |
C++ | x64dbg-development/src/gui/Src/BasicView/StdTable.cpp | #include "StdTable.h"
#include "Bridge.h"
StdTable::StdTable(QWidget* parent) : AbstractStdTable(parent)
{
}
/************************************************************************************
Sorting
************************************************************************************/
bool StdTable::SortBy::AsText(const QString & a, const QString & b)
{
auto i = QString::compare(a, b);
return i < 0;
}
bool StdTable::SortBy::AsInt(const QString & a, const QString & b)
{
return a.toLongLong() < b.toLongLong();
}
bool StdTable::SortBy::AsHex(const QString & a, const QString & b)
{
return a.toLongLong(0, 16) < b.toLongLong(0, 16);
}
/************************************************************************************
Data Management
************************************************************************************/
void StdTable::addColumnAt(int width, QString title, bool isClickable, QString copyTitle, SortBy::t sortFn)
{
AbstractTableView::addColumnAt(width, title, isClickable);
//append empty column to list of rows
for(size_t i = 0; i < mData.size(); i++)
mData[i].push_back(CellData());
//Append copy title
if(!copyTitle.length())
mCopyTitles.push_back(title);
else
mCopyTitles.push_back(copyTitle);
//append column sort function
mColumnSortFunctions.push_back(sortFn);
}
void StdTable::deleteAllColumns()
{
setRowCount(0);
AbstractTableView::deleteAllColumns();
mCopyTitles.clear();
mColumnSortFunctions.clear();
}
void StdTable::setRowCount(dsint count)
{
int wRowToAddOrRemove = count - int(mData.size());
for(int i = 0; i < qAbs(wRowToAddOrRemove); i++)
{
if(wRowToAddOrRemove > 0)
{
mData.push_back(std::vector<CellData>());
for(int j = 0; j < getColumnCount(); j++)
mData[mData.size() - 1].push_back(CellData());
}
else
mData.pop_back();
}
AbstractTableView::setRowCount(count);
}
void StdTable::setCellContent(int r, int c, QString s)
{
if(isValidIndex(r, c))
mData[r][c].text = std::move(s);
}
QString StdTable::getCellContent(int r, int c)
{
if(isValidIndex(r, c))
return mData[r][c].text;
else
return QString("");
}
void StdTable::setCellUserdata(int r, int c, duint userdata)
{
if(isValidIndex(r, c))
mData[r][c].userdata = userdata;
}
duint StdTable::getCellUserdata(int r, int c)
{
return isValidIndex(r, c) ? mData[r][c].userdata : 0;
}
bool StdTable::isValidIndex(int r, int c)
{
if(r < 0 || c < 0 || r >= int(mData.size()))
return false;
return c < int(mData.at(r).size());
}
void StdTable::sortRows(int column, bool ascending)
{
auto sortFn = mColumnSortFunctions.at(column);
std::stable_sort(mData.begin(), mData.end(), [column, ascending, &sortFn](const std::vector<CellData> & a, const std::vector<CellData> & b)
{
auto less = sortFn(a.at(column).text, b.at(column).text);
return ascending ? less : !less;
});
} |
C/C++ | x64dbg-development/src/gui/Src/BasicView/StdTable.h | #pragma once
#include "AbstractStdTable.h"
class StdTable : public AbstractStdTable
{
Q_OBJECT
public:
explicit StdTable(QWidget* parent = 0);
// Sorting
struct SortBy
{
typedef std::function<bool(const QString &, const QString &)> t;
static bool AsText(const QString & a, const QString & b);
static bool AsInt(const QString & a, const QString & b);
static bool AsHex(const QString & a, const QString & b);
};
// Data Management
void addColumnAt(int width, QString title, bool isClickable, QString copyTitle = "", SortBy::t sortFn = SortBy::AsText);
void deleteAllColumns() override;
void setRowCount(dsint count) override;
void setCellContent(int r, int c, QString s);
QString getCellContent(int r, int c) override;
void setCellUserdata(int r, int c, duint userdata);
duint getCellUserdata(int r, int c);
bool isValidIndex(int r, int c) override;
void sortRows(int column, bool ascending) override;
protected:
struct CellData
{
QString text;
duint userdata = 0;
};
std::vector<std::vector<CellData>> mData; //listof(row) where row = (listof(col) where col = CellData)
std::vector<SortBy::t> mColumnSortFunctions;
}; |
C++ | x64dbg-development/src/gui/Src/BasicView/StdTableSearchList.cpp | #include "StdTableSearchList.h"
#include "StdIconTable.h"
void StdTableSearchList::filter(const QString & filter, FilterType type, int startColumn)
{
StdIconTable* mSearchIconList = qobject_cast<StdIconTable*>(mSearchList);
StdIconTable* mIconList = qobject_cast<StdIconTable*>(mList);
mSearchList->setRowCount(0);
int rows = mList->getRowCount();
int columns = mList->getColumnCount();
for(int i = 0, j = 0; i < rows; i++)
{
if(rowMatchesFilter(filter, type, i, startColumn))
{
mSearchList->setRowCount(j + 1);
for(int k = 0; k < columns; k++)
{
mSearchList->setCellContent(j, k, mList->getCellContent(i, k));
mSearchList->setCellUserdata(j, k, mList->getCellUserdata(i, k));
}
if(mSearchIconList && mIconList)
mSearchIconList->setRowIcon(j, mIconList->getRowIcon(i));
j++;
}
}
} |
C/C++ | x64dbg-development/src/gui/Src/BasicView/StdTableSearchList.h | #pragma once
#include "AbstractSearchList.h"
#include "StdTable.h"
class StdTableSearchList : public AbstractSearchList
{
public:
friend class StdSearchListView;
StdTableSearchList() : StdTableSearchList(new StdTable(), new StdTable()) { }
StdTableSearchList(StdTable* list, StdTable* searchList) : mList(list), mSearchList(searchList) { }
~StdTableSearchList() { delete mList; delete mSearchList; }
void lock() override { }
void unlock() override { }
AbstractStdTable* list() const override { return mList; }
AbstractStdTable* searchList() const override { return mSearchList; }
void filter(const QString & filter, FilterType type, int startColumn) override;
private:
StdTable* mList;
StdTable* mSearchList;
}; |
C++ | x64dbg-development/src/gui/Src/Bridge/Bridge.cpp | #include "Bridge.h"
#include <QClipboard>
#include "QBeaEngine.h"
#include "main.h"
#include "Exports.h"
#include "ReferenceManager.h"
#include "SymbolView.h"
/************************************************************************************
Global Variables
************************************************************************************/
static Bridge* mBridge;
/************************************************************************************
Class Members
************************************************************************************/
Bridge::Bridge(QObject* parent) : QObject(parent)
{
InitializeCriticalSection(&csBridge);
for(size_t i = 0; i < BridgeResult::Last; i++)
resultEvents[i] = CreateEventW(nullptr, true, true, nullptr);
dwMainThreadId = GetCurrentThreadId();
}
Bridge::~Bridge()
{
EnterCriticalSection(&csBridge);
for(size_t i = 0; i < BridgeResult::Last; i++)
CloseHandle(resultEvents[i]);
DeleteCriticalSection(&csBridge);
}
void Bridge::CopyToClipboard(const QString & text)
{
if(!text.length())
return;
QClipboard* clipboard = QApplication::clipboard();
clipboard->setText(text);
GuiAddStatusBarMessage(tr("The data has been copied to clipboard.\n").toUtf8().constData());
}
void Bridge::CopyToClipboard(const QString & text, const QString & htmlText)
{
QMimeData* mimeData = new QMimeData();
mimeData->setData("text/html", htmlText.toUtf8()); // Set text/html data
mimeData->setData("text/plain", text.toUtf8()); //Set text/plain data
//Reason not using setText() or setHtml():Don't support storing multiple data in one QMimeData
QApplication::clipboard()->setMimeData(mimeData); //Copy the QMimeData with text and html data
GuiAddStatusBarMessage(tr("The data has been copied to clipboard.\n").toUtf8().constData());
}
void Bridge::setResult(BridgeResult::Type type, dsint result)
{
#ifdef DEBUG
OutputDebugStringA(QString().sprintf("[x64dbg] [%u] Bridge::setResult(%d, %p)\n", GetCurrentThreadId(), type, result).toUtf8().constData());
#endif //DEBUG
bridgeResults[type] = result;
SetEvent(resultEvents[type]);
}
/************************************************************************************
Static Functions
************************************************************************************/
Bridge* Bridge::getBridge()
{
return mBridge;
}
void Bridge::initBridge()
{
mBridge = new Bridge();
}
/************************************************************************************
Helper Functions
************************************************************************************/
void Bridge::emitMenuAddToList(QWidget* parent, QMenu* menu, GUIMENUTYPE hMenu, int hParentMenu)
{
BridgeResult result(BridgeResult::MenuAddToList);
emit menuAddMenuToList(parent, menu, hMenu, hParentMenu);
result.Wait();
}
void Bridge::setDbgStopped()
{
dbgStopped = true;
}
/************************************************************************************
Message processing
************************************************************************************/
void* Bridge::processMessage(GUIMSG type, void* param1, void* param2)
{
if(dbgStopped) //there can be no more messages if the debugger stopped = IGNORE
return nullptr;
switch(type)
{
case GUI_DISASSEMBLE_AT:
mLastCip = (duint)param2;
emit disassembleAt((dsint)param1, (dsint)param2);
break;
case GUI_SET_DEBUG_STATE:
mIsRunning = DBGSTATE(duint(param1)) == running;
if(!param2)
emit dbgStateChanged((DBGSTATE)(dsint)param1);
break;
case GUI_ADD_MSG_TO_LOG:
{
auto msg = (const char*)param1;
emit addMsgToLog(QByteArray(msg, int(strlen(msg)) + 1)); //Speed up performance: don't convert to UCS-2 QString
}
break;
case GUI_ADD_MSG_TO_LOG_HTML:
{
auto msg = (const char*)param1;
emit addMsgToLogHtml(QByteArray(msg, int(strlen(msg)) + 1)); //Speed up performance: don't convert to UCS-2 QString
}
break;
case GUI_CLEAR_LOG:
emit clearLog();
break;
case GUI_SAVE_LOG:
if(!param1)
emit saveLog();
else
emit saveLogToFile(QString((const char*)param1));
break;
case GUI_REDIRECT_LOG:
emit redirectLogToFile(QString((const char*)param1));
break;
case GUI_STOP_REDIRECT_LOG:
emit redirectLogStop();
break;
case GUI_UPDATE_REGISTER_VIEW:
emit updateRegisters();
break;
case GUI_UPDATE_DISASSEMBLY_VIEW:
emit updateDisassembly();
break;
case GUI_UPDATE_BREAKPOINTS_VIEW:
emit updateBreakpoints();
break;
case GUI_UPDATE_WINDOW_TITLE:
emit updateWindowTitle(QString((const char*)param1));
break;
case GUI_GET_WINDOW_HANDLE:
return winId;
case GUI_DUMP_AT:
emit dumpAt((dsint)param1);
break;
case GUI_SCRIPT_ADD:
{
BridgeResult result(BridgeResult::ScriptAdd);
emit scriptAdd((int)param1, (const char**)param2);
result.Wait();
}
break;
case GUI_SCRIPT_CLEAR:
emit scriptClear();
break;
case GUI_SCRIPT_SETIP:
emit scriptSetIp((int)param1);
break;
case GUI_SCRIPT_ERROR:
{
BridgeResult result(BridgeResult::ScriptMessage);
emit scriptError((int)param1, QString((const char*)param2));
result.Wait();
}
break;
case GUI_SCRIPT_SETTITLE:
emit scriptSetTitle(QString((const char*)param1));
break;
case GUI_SCRIPT_SETINFOLINE:
emit scriptSetInfoLine((int)param1, QString((const char*)param2));
break;
case GUI_SCRIPT_MESSAGE:
{
BridgeResult result(BridgeResult::ScriptMessage);
emit scriptMessage(QString((const char*)param1));
result.Wait();
}
break;
case GUI_SCRIPT_MSGYN:
{
BridgeResult result(BridgeResult::ScriptMessage);
emit scriptQuestion(QString((const char*)param1));
return (void*)result.Wait();
}
break;
case GUI_SCRIPT_ENABLEHIGHLIGHTING:
emit scriptEnableHighlighting((bool)param1);
break;
case GUI_SYMBOL_UPDATE_MODULE_LIST:
emit updateSymbolList((int)param1, (SYMBOLMODULEINFO*)param2);
break;
case GUI_SYMBOL_LOG_ADD:
emit addMsgToSymbolLog(QString((const char*)param1));
break;
case GUI_SYMBOL_LOG_CLEAR:
emit clearSymbolLog();
break;
case GUI_SYMBOL_SET_PROGRESS:
emit setSymbolProgress((int)param1);
break;
case GUI_REF_ADDCOLUMN:
if(referenceManager->currentReferenceView())
referenceManager->currentReferenceView()->addColumnAtRef((int)param1, QString((const char*)param2));
break;
case GUI_REF_SETROWCOUNT:
{
if(referenceManager->currentReferenceView())
referenceManager->currentReferenceView()->setRowCount((dsint)param1);
}
break;
case GUI_REF_GETROWCOUNT:
if(referenceManager->currentReferenceView())
return (void*)referenceManager->currentReferenceView()->stdList()->getRowCount();
return 0;
case GUI_REF_SEARCH_GETROWCOUNT:
if(referenceManager->currentReferenceView())
return (void*)referenceManager->currentReferenceView()->mCurList->getRowCount();
return 0;
case GUI_REF_DELETEALLCOLUMNS:
GuiReferenceInitialize(tr("References").toUtf8().constData());
break;
case GUI_REF_SETCELLCONTENT:
{
CELLINFO* info = (CELLINFO*)param1;
if(referenceManager->currentReferenceView())
referenceManager->currentReferenceView()->setCellContent(info->row, info->col, QString(info->str));
}
break;
case GUI_REF_GETCELLCONTENT:
{
QString content;
if(referenceManager->currentReferenceView())
content = referenceManager->currentReferenceView()->stdList()->getCellContent((int)param1, (int)param2);
auto bytes = content.toUtf8();
auto data = BridgeAlloc(bytes.size() + 1);
memcpy(data, bytes.constData(), bytes.size());
return data;
}
case GUI_REF_SEARCH_GETCELLCONTENT:
{
QString content;
if(referenceManager->currentReferenceView())
content = referenceManager->currentReferenceView()->mCurList->getCellContent((int)param1, (int)param2);
auto bytes = content.toUtf8();
auto data = BridgeAlloc(bytes.size() + 1);
memcpy(data, bytes.constData(), bytes.size());
return data;
}
case GUI_REF_RELOADDATA:
emit referenceReloadData();
break;
case GUI_REF_SETSINGLESELECTION:
emit referenceSetSingleSelection((int)param1, (bool)param2);
break;
case GUI_REF_SETPROGRESS:
if(referenceManager->currentReferenceView())
{
auto newProgress = (int)param1;
if(referenceManager->currentReferenceView()->progress() != newProgress)
emit referenceSetProgress(newProgress);
}
break;
case GUI_REF_SETCURRENTTASKPROGRESS:
if(referenceManager->currentReferenceView())
{
auto newProgress = (int)param1;
if(referenceManager->currentReferenceView()->currentTaskProgress() != newProgress)
emit referenceSetCurrentTaskProgress((int)param1, QString((const char*)param2));
}
break;
case GUI_REF_SETSEARCHSTARTCOL:
if(referenceManager->currentReferenceView())
referenceManager->currentReferenceView()->setSearchStartCol((int)param1);
break;
case GUI_REF_INITIALIZE:
{
BridgeResult result(BridgeResult::RefInitialize);
emit referenceInitialize(QString((const char*)param1));
result.Wait();
}
break;
case GUI_STACK_DUMP_AT:
emit stackDumpAt((duint)param1, (duint)param2);
break;
case GUI_UPDATE_DUMP_VIEW:
emit updateDump();
break;
case GUI_UPDATE_THREAD_VIEW:
emit updateThreads();
break;
case GUI_UPDATE_MEMORY_VIEW:
emit updateMemory();
break;
case GUI_ADD_RECENT_FILE:
emit addRecentFile(QString((const char*)param1));
break;
case GUI_SET_LAST_EXCEPTION:
emit setLastException((unsigned int)param1);
break;
case GUI_GET_DISASSEMBLY:
{
duint parVA = (duint)param1;
char* text = (char*)param2;
if(!text || !parVA || !DbgIsDebugging())
return 0;
byte_t wBuffer[16];
if(!DbgMemRead(parVA, wBuffer, 16))
return 0;
QBeaEngine disasm(int(ConfigUint("Disassembler", "MaxModuleSize")));
Instruction_t instr = disasm.DisassembleAt(wBuffer, 16, 0, parVA);
QString finalInstruction;
for(const auto & curToken : instr.tokens.tokens)
finalInstruction += curToken.text;
strncpy_s(text, GUI_MAX_DISASSEMBLY_SIZE, finalInstruction.toUtf8().constData(), _TRUNCATE);
return (void*)1;
}
break;
case GUI_MENU_ADD:
{
BridgeResult result(BridgeResult::MenuAdd);
emit menuAddMenu((int)param1, QString((const char*)param2));
return (void*)result.Wait();
}
break;
case GUI_MENU_ADD_ENTRY:
{
BridgeResult result(BridgeResult::MenuAddEntry);
emit menuAddMenuEntry((int)param1, QString((const char*)param2));
return (void*)result.Wait();
}
break;
case GUI_MENU_ADD_SEPARATOR:
{
BridgeResult result(BridgeResult::MenuAddSeparator);
emit menuAddSeparator((int)param1);
result.Wait();
}
break;
case GUI_MENU_CLEAR:
{
BridgeResult result(BridgeResult::MenuClear);
emit menuClearMenu((int)param1, false);
result.Wait();
}
break;
case GUI_MENU_REMOVE:
{
BridgeResult result(BridgeResult::MenuRemove);
emit menuRemoveMenuEntry((int)param1);
result.Wait();
}
break;
case GUI_MENU_SET_ICON:
{
int hMenu = (int)param1;
const ICONDATA* icon = (const ICONDATA*)param2;
BridgeResult result(BridgeResult::MenuSetIcon);
if(!icon)
emit setIconMenu(hMenu, QIcon());
else
{
QImage img;
img.loadFromData((uchar*)icon->data, icon->size);
QIcon qIcon(QPixmap::fromImage(img));
emit setIconMenu(hMenu, qIcon);
}
result.Wait();
}
break;
case GUI_MENU_SET_ENTRY_ICON:
{
int hEntry = (int)param1;
const ICONDATA* icon = (const ICONDATA*)param2;
BridgeResult result(BridgeResult::MenuSetEntryIcon);
if(!icon)
emit setIconMenuEntry(hEntry, QIcon());
else
{
QImage img;
img.loadFromData((uchar*)icon->data, icon->size);
QIcon qIcon(QPixmap::fromImage(img));
emit setIconMenuEntry(hEntry, qIcon);
}
result.Wait();
}
break;
case GUI_MENU_SET_ENTRY_CHECKED:
{
BridgeResult result(BridgeResult::MenuSetEntryChecked);
emit setCheckedMenuEntry(int(param1), bool(param2));
result.Wait();
}
break;
case GUI_MENU_SET_VISIBLE:
{
BridgeResult result(BridgeResult::MenuSetVisible);
emit setVisibleMenu(int(param1), bool(param2));
result.Wait();
}
break;
case GUI_MENU_SET_ENTRY_VISIBLE:
{
BridgeResult result(BridgeResult::MenuSetEntryVisible);
emit setVisibleMenuEntry(int(param1), bool(param2));
result.Wait();
}
break;
case GUI_MENU_SET_NAME:
{
BridgeResult result(BridgeResult::MenuSetName);
emit setNameMenu(int(param1), QString((const char*)param2));
result.Wait();
}
break;
case GUI_MENU_SET_ENTRY_NAME:
{
BridgeResult result(BridgeResult::MenuSetEntryName);
emit setNameMenuEntry(int(param1), QString((const char*)param2));
result.Wait();
}
break;
case GUI_MENU_SET_ENTRY_HOTKEY:
{
BridgeResult result(BridgeResult::MenuSetEntryHotkey);
auto params = QString((const char*)param2).split('\1');
if(params.length() == 2)
{
emit setHotkeyMenuEntry(int(param1), params[0], params[1]);
result.Wait();
}
}
break;
case GUI_SELECTION_GET:
{
GUISELECTIONTYPE hWindow = GUISELECTIONTYPE(duint(param1));
SELECTIONDATA* selection = (SELECTIONDATA*)param2;
if(!DbgIsDebugging())
return (void*)false;
BridgeResult result(BridgeResult::SelectionGet);
switch(hWindow)
{
case GUI_DISASSEMBLY:
emit selectionDisasmGet(selection);
break;
case GUI_DUMP:
emit selectionDumpGet(selection);
break;
case GUI_STACK:
emit selectionStackGet(selection);
break;
case GUI_GRAPH:
emit selectionGraphGet(selection);
break;
case GUI_MEMMAP:
emit selectionMemmapGet(selection);
break;
case GUI_SYMMOD:
emit selectionSymmodGet(selection);
break;
default:
return (void*)false;
}
result.Wait();
if(selection->start > selection->end) //swap start and end
{
dsint temp = selection->end;
selection->end = selection->start;
selection->start = temp;
}
return (void*)true;
}
break;
case GUI_SELECTION_SET:
{
GUISELECTIONTYPE hWindow = GUISELECTIONTYPE(duint(param1));
const SELECTIONDATA* selection = (const SELECTIONDATA*)param2;
if(!DbgIsDebugging())
return (void*)false;
BridgeResult result(BridgeResult::SelectionSet);
switch(hWindow)
{
case GUI_DISASSEMBLY:
emit selectionDisasmSet(selection);
break;
case GUI_DUMP:
emit selectionDumpSet(selection);
break;
case GUI_STACK:
emit selectionStackSet(selection);
break;
default:
return (void*)false;
}
return (void*)result.Wait();
}
break;
case GUI_GETLINE_WINDOW:
{
QString text = "";
BridgeResult result(BridgeResult::GetlineWindow);
emit getStrWindow(QString((const char*)param1), &text);
if(result.Wait())
{
strcpy_s((char*)param2, GUI_MAX_LINE_SIZE, text.toUtf8().constData());
return (void*)true;
}
return (void*)false; //cancel/escape
}
break;
case GUI_AUTOCOMPLETE_ADDCMD:
emit autoCompleteAddCmd(QString((const char*)param1));
break;
case GUI_AUTOCOMPLETE_DELCMD:
emit autoCompleteDelCmd(QString((const char*)param1));
break;
case GUI_AUTOCOMPLETE_CLEARALL:
emit autoCompleteClearAll();
break;
case GUI_ADD_MSG_TO_STATUSBAR:
emit addMsgToStatusBar(QString((const char*)param1));
break;
case GUI_UPDATE_SIDEBAR:
emit updateSideBar();
break;
case GUI_REPAINT_TABLE_VIEW:
emit repaintTableView();
break;
case GUI_UPDATE_PATCHES:
emit updatePatches();
break;
case GUI_UPDATE_CALLSTACK:
emit updateCallStack();
break;
case GUI_UPDATE_SEHCHAIN:
emit updateSEHChain();
break;
case GUI_SYMBOL_REFRESH_CURRENT:
emit symbolRefreshCurrent();
break;
case GUI_LOAD_SOURCE_FILE:
emit loadSourceFile(QString((const char*)param1), (duint)param2);
break;
case GUI_SHOW_CPU:
emit showCpu();
break;
case GUI_ADD_QWIDGET_TAB:
emit addQWidgetTab((QWidget*)param1);
break;
case GUI_SHOW_QWIDGET_TAB:
emit showQWidgetTab((QWidget*)param1);
break;
case GUI_CLOSE_QWIDGET_TAB:
emit closeQWidgetTab((QWidget*)param1);
break;
case GUI_EXECUTE_ON_GUI_THREAD:
{
if(GetCurrentThreadId() == dwMainThreadId)
((GUICALLBACKEX)param1)(param2);
else
emit executeOnGuiThread(param1, param2);
}
break;
case GUI_UPDATE_TIME_WASTED_COUNTER:
emit updateTimeWastedCounter();
break;
case GUI_SET_GLOBAL_NOTES:
{
QString text = QString((const char*)param1);
emit setGlobalNotes(text);
}
break;
case GUI_GET_GLOBAL_NOTES:
{
BridgeResult result(BridgeResult::GetGlobalNotes);
emit getGlobalNotes(param1);
result.Wait();
}
break;
case GUI_SET_DEBUGGEE_NOTES:
{
QString text = QString((const char*)param1);
emit setDebuggeeNotes(text);
}
break;
case GUI_GET_DEBUGGEE_NOTES:
{
BridgeResult result(BridgeResult::GetDebuggeeNotes);
emit getDebuggeeNotes(param1);
result.Wait();
}
break;
case GUI_DUMP_AT_N:
emit dumpAtN((duint)param1, (int)param2);
break;
case GUI_DISPLAY_WARNING:
{
QString title = QString((const char*)param1);
QString text = QString((const char*)param2);
emit displayWarning(title, text);
}
break;
case GUI_REGISTER_SCRIPT_LANG:
{
BridgeResult result(BridgeResult::RegisterScriptLang);
emit registerScriptLang((SCRIPTTYPEINFO*)param1);
result.Wait();
}
break;
case GUI_UNREGISTER_SCRIPT_LANG:
emit unregisterScriptLang((int)param1);
break;
case GUI_UPDATE_ARGUMENT_VIEW:
emit updateArgumentView();
break;
case GUI_FOCUS_VIEW:
{
int hWindow = int(param1);
switch(hWindow)
{
case GUI_DISASSEMBLY:
emit focusDisasm();
break;
case GUI_DUMP:
emit focusDump();
break;
case GUI_STACK:
emit focusStack();
break;
case GUI_GRAPH:
emit focusGraph();
break;
case GUI_MEMMAP:
emit focusMemmap();
break;
default:
break;
}
}
break;
case GUI_UPDATE_WATCH_VIEW:
emit updateWatch();
break;
case GUI_LOAD_GRAPH:
{
BridgeResult result(BridgeResult::LoadGraph);
emit loadGraph((BridgeCFGraphList*)param1, duint(param2));
return (void*)result.Wait();
}
break;
case GUI_GRAPH_AT:
{
BridgeResult result(BridgeResult::GraphAt);
emit graphAt(duint(param1));
return (void*)result.Wait();
}
break;
case GUI_UPDATE_GRAPH_VIEW:
emit updateGraph();
break;
case GUI_SET_LOG_ENABLED:
loggingEnabled = param1 != 0;
emit setLogEnabled(loggingEnabled);
break;
case GUI_IS_LOG_ENABLED:
return (void*)loggingEnabled;
case GUI_ADD_FAVOURITE_TOOL:
{
QString name;
QString description;
if(param1 == nullptr)
return nullptr;
name = QString((const char*)param1);
if(param2 != nullptr)
description = QString((const char*)param2);
emit addFavouriteItem(0, name, description);
}
break;
case GUI_ADD_FAVOURITE_COMMAND:
{
QString name;
QString shortcut;
if(param1 == nullptr)
return nullptr;
name = QString((const char*)param1);
if(param2 != nullptr)
shortcut = QString((const char*)param2);
emit addFavouriteItem(2, name, shortcut);
}
break;
case GUI_SET_FAVOURITE_TOOL_SHORTCUT:
{
QString name;
QString shortcut;
if(param1 == nullptr)
return nullptr;
name = QString((const char*)param1);
if(param2 != nullptr)
shortcut = QString((const char*)param2);
emit setFavouriteItemShortcut(0, name, shortcut);
}
break;
case GUI_FOLD_DISASSEMBLY:
emit foldDisassembly(duint(param1), duint(param2));
break;
case GUI_SELECT_IN_MEMORY_MAP:
emit selectInMemoryMap(duint(param1));
break;
case GUI_GET_ACTIVE_VIEW:
{
if(param1)
{
BridgeResult result(BridgeResult::GetActiveView);
emit getActiveView((ACTIVEVIEW*)param1);
result.Wait();
}
}
break;
case GUI_ADD_INFO_LINE:
{
if(param1)
{
emit addInfoLine(QString((const char*)param1));
}
}
break;
case GUI_PROCESS_EVENTS:
QCoreApplication::processEvents();
break;
case GUI_TYPE_ADDNODE:
{
BridgeResult result(BridgeResult::TypeAddNode);
emit typeAddNode(param1, (const TYPEDESCRIPTOR*)param2);
return (void*)result.Wait();
}
break;
case GUI_TYPE_CLEAR:
{
BridgeResult result(BridgeResult::TypeClear);
emit typeClear();
result.Wait();
}
break;
case GUI_UPDATE_TYPE_WIDGET:
emit typeUpdateWidget();
break;
case GUI_CLOSE_APPLICATION:
emit closeApplication();
break;
case GUI_FLUSH_LOG:
emit flushLog();
break;
case GUI_REF_ADDCOMMAND:
{
if(param1 == nullptr && param2 == nullptr)
return nullptr;
else if(param1 == nullptr)
emit referenceAddCommand(QString::fromUtf8((const char*)param2), QString::fromUtf8((const char*)param2));
else
emit referenceAddCommand(QString::fromUtf8((const char*)param1), QString::fromUtf8((const char*)param2));
}
break;
case GUI_OPEN_TRACE_FILE:
{
if(param1 == nullptr)
return nullptr;
emit openTraceFile(QString::fromUtf8((const char*)param1));
}
break;
case GUI_UPDATE_TRACE_BROWSER:
emit updateTraceBrowser();
break;
case GUI_INVALIDATE_SYMBOL_SOURCE:
symbolView->invalidateSymbolSource(duint(param1));
break;
case GUI_GET_CURRENT_GRAPH:
{
BridgeResult result(BridgeResult::GraphCurrent);
emit getCurrentGraph((BridgeCFGraphList*)param1);
result.Wait();
}
break;
case GUI_SHOW_REF:
emit showReferences();
break;
case GUI_SELECT_IN_SYMBOLS_TAB:
emit symbolSelectModule(duint(param1));
break;
case GUI_GOTO_TRACE:
emit gotoTraceIndex(duint(param1));
break;
case GUI_SHOW_TRACE:
emit showTraceBrowser();
break;
case GUI_GET_MAIN_THREAD_ID:
return (void*)dwMainThreadId;
}
return nullptr;
}
/************************************************************************************
Exported Functions
************************************************************************************/
__declspec(dllexport) int _gui_guiinit(int argc, char* argv[])
{
return main(argc, argv);
}
__declspec(dllexport) void* _gui_sendmessage(GUIMSG type, void* param1, void* param2)
{
return Bridge::getBridge()->processMessage(type, param1, param2);
}
__declspec(dllexport) const char* _gui_translate_text(const char* source)
{
if(TLS_TranslatedStringMap)
{
QByteArray translatedUtf8 = QCoreApplication::translate("DBG", source).toUtf8();
// Boom... VS does not support "thread_local"... and cannot use "__declspec(thread)" in a DLL... https://blogs.msdn.microsoft.com/oldnewthing/20101122-00/?p=12233
// Simulating Thread Local Storage with a map...
DWORD ThreadId = GetCurrentThreadId();
TranslatedStringStorage & TranslatedString = (*TLS_TranslatedStringMap)[ThreadId];
TranslatedString.Data[translatedUtf8.size()] = 0; // Set the string terminator first.
memcpy(TranslatedString.Data, translatedUtf8.constData(), std::min((size_t)translatedUtf8.size(), sizeof(TranslatedString.Data) - 1)); // Then copy the string safely.
return TranslatedString.Data; // Don't need to free this memory. But this pointer should be used immediately to reduce race condition.
}
else // Translators are not initialized yet.
return source;
} |
C/C++ | x64dbg-development/src/gui/Src/Bridge/Bridge.h | #pragma once
#include <agents.h>
#include <QObject>
#include <QWidget>
#include <QMutex>
#include <QMenu>
#include "Imports.h"
#include "BridgeResult.h"
class ReferenceManager;
class SymbolView;
class Bridge : public QObject
{
Q_OBJECT
friend class BridgeResult;
public:
explicit Bridge(QObject* parent = 0);
~Bridge();
static Bridge* getBridge();
static void initBridge();
// Message processing function
void* processMessage(GUIMSG type, void* param1, void* param2);
// Misc functions
static void CopyToClipboard(const QString & text);
static void CopyToClipboard(const QString & text, const QString & htmlText);
//result function
void setResult(BridgeResult::Type type, dsint result = 0);
//helper functions
void emitMenuAddToList(QWidget* parent, QMenu* menu, GUIMENUTYPE hMenu, int hParentMenu = -1);
void setDbgStopped();
//Public variables
void* winId = nullptr;
ReferenceManager* referenceManager = nullptr;
bool mIsRunning = false;
duint mLastCip = 0;
SymbolView* symbolView = nullptr;
bool loggingEnabled = true;
signals:
void disassembleAt(dsint va, dsint eip);
void updateDisassembly();
void dbgStateChanged(DBGSTATE state);
void addMsgToLog(QByteArray msg);
void addMsgToLogHtml(QByteArray msg);
void clearLog();
void saveLog();
void saveLogToFile(QString file);
void redirectLogStop();
void redirectLogToFile(QString filename);
void shutdown();
void updateRegisters();
void updateBreakpoints();
void updateWindowTitle(QString filename);
void dumpAt(dsint va);
void scriptAdd(int count, const char** lines);
void scriptClear();
void scriptSetIp(int line);
void scriptError(int line, QString message);
void scriptSetTitle(QString title);
void scriptSetInfoLine(int line, QString info);
void scriptMessage(QString message);
void scriptQuestion(QString message);
void scriptEnableHighlighting(bool enable);
void updateSymbolList(int module_count, SYMBOLMODULEINFO* modules);
void addMsgToSymbolLog(QString msg);
void clearSymbolLog();
void setSymbolProgress(int progress);
void referenceAddColumnAt(int width, QString title);
void referenceSetRowCount(dsint count);
void referenceSetCellContent(int r, int c, QString s);
void referenceAddCommand(QString title, QString command);
void referenceReloadData();
void referenceSetSingleSelection(int index, bool scroll);
void referenceSetProgress(int progress);
void referenceSetCurrentTaskProgress(int progress, QString taskTitle);
void referenceSetSearchStartCol(int col);
void referenceInitialize(QString name);
void stackDumpAt(duint va, duint csp);
void updateDump();
void updateThreads();
void updateMemory();
void addRecentFile(QString file);
void setLastException(unsigned int exceptionCode);
void menuAddMenuToList(QWidget* parent, QMenu* menu, GUIMENUTYPE hMenu, int hParentMenu);
void menuAddMenu(int hMenu, QString title);
void menuAddMenuEntry(int hMenu, QString title);
void menuAddSeparator(int hMenu);
void menuClearMenu(int hMenu, bool erase);
void menuRemoveMenuEntry(int hEntryMenu);
void setIconMenuEntry(int hEntry, QIcon icon);
void setIconMenu(int hMenu, QIcon icon);
void setCheckedMenuEntry(int hEntry, bool checked);
void setVisibleMenuEntry(int hEntry, bool visible);
void setVisibleMenu(int hMenu, bool visible);
void setNameMenuEntry(int hEntry, QString name);
void setNameMenu(int hMenu, QString name);
void setHotkeyMenuEntry(int hEntry, QString hotkey, QString id);
void selectionDisasmGet(SELECTIONDATA* selection);
void selectionDisasmSet(const SELECTIONDATA* selection);
void selectionDumpGet(SELECTIONDATA* selection);
void selectionDumpSet(const SELECTIONDATA* selection);
void selectionStackGet(SELECTIONDATA* selection);
void selectionStackSet(const SELECTIONDATA* selection);
void selectionGraphGet(SELECTIONDATA* selection);
void selectionMemmapGet(SELECTIONDATA* selection);
void selectionSymmodGet(SELECTIONDATA* selection);
void getStrWindow(const QString title, QString* text);
void autoCompleteAddCmd(const QString cmd);
void autoCompleteDelCmd(const QString cmd);
void autoCompleteClearAll();
void addMsgToStatusBar(QString msg);
void updateSideBar();
void repaintTableView();
void updatePatches();
void updateCallStack();
void updateSEHChain();
void updateArgumentView();
void symbolRefreshCurrent();
void loadSourceFile(const QString path, duint addr);
void showCpu();
void addQWidgetTab(QWidget* qWidget);
void showQWidgetTab(QWidget* qWidget);
void closeQWidgetTab(QWidget* qWidget);
void executeOnGuiThread(void* cbGuiThread, void* userdata);
void updateTimeWastedCounter();
void setGlobalNotes(const QString text);
void getGlobalNotes(void* text);
void setDebuggeeNotes(const QString text);
void getDebuggeeNotes(void* text);
void dumpAtN(duint va, int index);
void displayWarning(QString title, QString text);
void registerScriptLang(SCRIPTTYPEINFO* info);
void unregisterScriptLang(int id);
void focusDisasm();
void focusDump();
void focusStack();
void focusGraph();
void focusMemmap();
void updateWatch();
void loadGraph(BridgeCFGraphList* graph, duint addr);
void graphAt(duint addr);
void updateGraph();
void setLogEnabled(bool enabled);
void addFavouriteItem(int type, const QString & name, const QString & description);
void setFavouriteItemShortcut(int type, const QString & name, const QString & shortcut);
void foldDisassembly(duint startAddr, duint length);
void selectInMemoryMap(duint addr);
void getActiveView(ACTIVEVIEW* activeView);
void addInfoLine(const QString & text);
void typeAddNode(void* parent, const TYPEDESCRIPTOR* type);
void typeClear();
void typeUpdateWidget();
void closeApplication();
void flushLog();
void getDumpAttention();
void openTraceFile(const QString & fileName);
void updateTraceBrowser();
void symbolSelectModule(duint base);
void getCurrentGraph(BridgeCFGraphList* graphList);
void showReferences();
void gotoTraceIndex(duint index);
void showTraceBrowser();
private:
CRITICAL_SECTION csBridge;
HANDLE resultEvents[BridgeResult::Last];
duint bridgeResults[BridgeResult::Last];
DWORD dwMainThreadId = 0;
volatile bool dbgStopped = false;
}; |
C++ | x64dbg-development/src/gui/Src/Bridge/BridgeResult.cpp | #include "BridgeResult.h"
#include "Bridge.h"
#include <QCoreApplication>
BridgeResult::BridgeResult(Type type)
: mType(type)
{
Bridge* bridge = Bridge::getBridge();
EnterCriticalSection(&bridge->csBridge);
#ifdef DEBUG
OutputDebugStringA(QString().sprintf("[x64dbg] [%u] BridgeResult(%d)\n", GetCurrentThreadId(), type).toUtf8().constData());
#endif //DEBUG
ResetEvent(bridge->resultEvents[type]);
}
BridgeResult::~BridgeResult()
{
#ifdef DEBUG
OutputDebugStringA(QString().sprintf("[x64dbg] [%u] ~BridgeResult(%d)\n", GetCurrentThreadId(), mType).toUtf8().constData());
#endif //DEBUG
LeaveCriticalSection(&Bridge::getBridge()->csBridge);
}
dsint BridgeResult::Wait()
{
#ifdef DEBUG
OutputDebugStringA(QString().sprintf("[x64dbg] [%u] BridgeResult::Wait(%d)\n", GetCurrentThreadId(), mType).toUtf8().constData());
#endif //DEBUG
Bridge* bridge = Bridge::getBridge();
HANDLE hResultEvent = bridge->resultEvents[mType];
//Don't freeze when waiting on the main thread (https://github.com/x64dbg/x64dbg/issues/1716)
if(GetCurrentThreadId() == bridge->dwMainThreadId)
while(WaitForSingleObject(hResultEvent, 10) == WAIT_TIMEOUT)
QCoreApplication::processEvents();
else
WaitForSingleObject(hResultEvent, INFINITE);
#ifdef DEBUG
OutputDebugStringA(QString().sprintf("[x64dbg] [%u] BridgeResult::~Wait(%d)\n", GetCurrentThreadId(), mType).toUtf8().constData());
#endif //DEBUG
return bridge->bridgeResults[mType];
} |
C/C++ | x64dbg-development/src/gui/Src/Bridge/BridgeResult.h | #pragma once
#include "Imports.h"
class BridgeResult
{
public:
enum Type
{
ScriptAdd,
ScriptMessage,
RefInitialize,
MenuAddToList,
MenuAdd,
MenuAddEntry,
MenuAddSeparator,
MenuClear,
MenuRemove,
SelectionGet,
SelectionSet,
GetlineWindow,
MenuSetIcon,
MenuSetEntryIcon,
MenuSetEntryChecked,
MenuSetVisible,
MenuSetEntryVisible,
MenuSetName,
MenuSetEntryName,
GetGlobalNotes,
GetDebuggeeNotes,
RegisterScriptLang,
LoadGraph,
GraphAt,
GetActiveView,
TypeAddNode,
TypeClear,
MenuSetEntryHotkey,
GraphCurrent,
Last,
};
explicit BridgeResult(Type type);
~BridgeResult();
dsint Wait();
private:
Type mType;
}; |
C++ | x64dbg-development/src/gui/Src/Disassembler/QBeaEngine.cpp | #include "QBeaEngine.h"
#include "StringUtil.h"
#include "EncodeMap.h"
#include "CodeFolding.h"
QBeaEngine::QBeaEngine(int maxModuleSize)
: _tokenizer(maxModuleSize), mCodeFoldingManager(nullptr), _bLongDataInst(false)
{
ZydisTokenizer::UpdateColors();
UpdateDataInstructionMap();
this->mEncodeMap = new EncodeMap();
}
QBeaEngine::~QBeaEngine()
{
delete this->mEncodeMap;
}
/**
* @brief Return the address of the nth instruction before the instruction pointed by ip. @n
* This function has been grabbed from OllyDbg ("Disassembleback" in asmserv.c)
*
* @param[in] data Address of the data to disassemble
* @param[in] base Original base address of the memory page (Required to disassemble destination addresses)
* @param[in] size Size of the data block pointed by data
* @param[in] ip RVA of the current instruction (Relative to data pointer)
* @param[in] n Number of instruction back
*
* @return Return the RVA (Relative to the data pointer) of the nth instruction before the instruction pointed by ip
*/
ulong QBeaEngine::DisassembleBack(const byte_t* data, duint base, duint size, duint ip, int n)
{
int i;
uint abuf[128], addr, back, cmdsize;
const unsigned char* pdata;
// Reset Disasm Structure
Zydis cp;
// Check if the pointer is not null
if(data == NULL)
return 0;
// Round the number of back instructions to 127
if(n < 0)
n = 0;
else if(n > 127)
n = 127;
// Check if the instruction pointer ip is not outside the memory range
if(ip >= size)
ip = size - 1;
// Obvious answer
if(n == 0)
return ip;
if(ip < (uint)n)
return ip;
//TODO: buffer overflow due to unchecked "back" value
back = MAX_DISASM_BUFFER * (n + 3); // Instruction length limited to 16
if(ip < back)
back = ip;
addr = ip - back;
if(mCodeFoldingManager && mCodeFoldingManager->isFolded(addr + base))
{
duint newback = mCodeFoldingManager->getFoldBegin(addr + base);
if(newback >= base && newback < size + base)
addr = newback - base;
}
pdata = data + addr;
for(i = 0; addr < ip; i++)
{
abuf[i % 128] = addr;
if(mCodeFoldingManager && mCodeFoldingManager->isFolded(addr + base))
{
duint newaddr = mCodeFoldingManager->getFoldBegin(addr + base);
if(newaddr >= base)
{
addr = newaddr - base;
}
cmdsize = mCodeFoldingManager->getFoldEnd(addr + base) - (addr + base) + 1;
}
else
{
if(!cp.DisassembleSafe(addr + base, pdata, (int)size))
cmdsize = 2; //heuristic for better output (FF FE or FE FF are usually part of an instruction)
else
cmdsize = cp.Size();
cmdsize = mEncodeMap->getDataSize(base + addr, cmdsize);
}
pdata += cmdsize;
addr += cmdsize;
back -= cmdsize;
size -= cmdsize;
}
if(i < n)
return abuf[0];
else
return abuf[(i - n + 128) % 128];
}
/**
* @brief Return the address of the nth instruction after the instruction pointed by ip. @n
* This function has been grabbed from OllyDbg ("Disassembleforward" in asmserv.c)
*
* @param[in] data Address of the data to disassemble
* @param[in] base Original base address of the memory page (Required to disassemble destination addresses)
* @param[in] size Size of the data block pointed by data
* @param[in] ip RVA of the current instruction (Relative to data pointer)
* @param[in] n Number of instruction next
*
* @return Return the RVA (Relative to the data pointer) of the nth instruction after the instruction pointed by ip
*/
ulong QBeaEngine::DisassembleNext(const byte_t* data, duint base, duint size, duint ip, int n)
{
int i;
uint cmdsize;
const unsigned char* pdata;
// Reset Disasm Structure
Zydis cp;
if(data == NULL)
return 0;
if(ip >= size)
ip = size - 1;
if(n <= 0)
return ip;
pdata = data + ip;
size -= ip;
for(i = 0; i < n && size > 0; i++)
{
if(mCodeFoldingManager && mCodeFoldingManager->isFolded(ip + base))
{
cmdsize = mCodeFoldingManager->getFoldEnd(ip + base) - (ip + base) + 1;
}
else
{
if(!cp.DisassembleSafe(ip + base, pdata, (int)size))
cmdsize = 1;
else
cmdsize = cp.Size();
cmdsize = mEncodeMap->getDataSize(base + ip, cmdsize);
}
pdata += cmdsize;
ip += cmdsize;
size -= cmdsize;
}
return ip;
}
/**
* @brief Disassemble the instruction at the given ip RVA.
*
* @param[in] data Pointer to memory data (Can be either a buffer or the original data memory)
* @param[in] size Size of the memory pointed by data (Can be the memory page size if data points to the original memory page base address)
* @param[in] origBase Original base address of the memory page (Required to disassemble destination addresses)
* @param[in] origInstRVA Original Instruction RVA of the instruction to disassemble
*
* @return Return the disassembled instruction
*/
Instruction_t QBeaEngine::DisassembleAt(const byte_t* data, duint size, duint origBase, duint origInstRVA, bool datainstr)
{
if(datainstr)
{
ENCODETYPE type = mEncodeMap->getDataType(origBase + origInstRVA);
if(!mEncodeMap->isCode(type))
return DecodeDataAt(data, size, origBase, origInstRVA, type);
}
//tokenize
ZydisTokenizer::InstructionToken cap;
_tokenizer.Tokenize(origBase + origInstRVA, data, size, cap);
int len = _tokenizer.Size();
const auto & cp = _tokenizer.GetZydis();
bool success = cp.Success();
auto branchType = Instruction_t::None;
Instruction_t wInst;
if(success && cp.IsBranchType(Zydis::BTJmp | Zydis::BTCall | Zydis::BTRet | Zydis::BTLoop | Zydis::BTXbegin))
{
wInst.branchDestination = DbgGetBranchDestination(origBase + origInstRVA);
if(cp.IsBranchType(Zydis::BTUncondJmp))
branchType = Instruction_t::Unconditional;
else if(cp.IsBranchType(Zydis::BTCall))
branchType = Instruction_t::Call;
else if(cp.IsBranchType(Zydis::BTCondJmp) || cp.IsBranchType(Zydis::BTLoop))
branchType = Instruction_t::Conditional;
}
else
wInst.branchDestination = 0;
wInst.instStr = QString(cp.InstructionText().c_str());
wInst.dump = QByteArray((const char*)data, len);
wInst.rva = origInstRVA;
if(mCodeFoldingManager && mCodeFoldingManager->isFolded(origInstRVA))
wInst.length = mCodeFoldingManager->getFoldEnd(origInstRVA + origBase) - (origInstRVA + origBase) + 1;
else
wInst.length = len;
wInst.branchType = branchType;
wInst.tokens = cap;
cp.BytesGroup(&wInst.prefixSize, &wInst.opcodeSize, &wInst.group1Size, &wInst.group2Size, &wInst.group3Size);
for(uint8_t i = 0; i < _countof(wInst.vectorElementType); ++i)
wInst.vectorElementType[i] = cp.getVectorElementType(i);
if(!success)
return wInst;
auto instr = cp.GetInstr();
cp.RegInfo(reginfo);
for(size_t i = 0; i < _countof(instr->accessedFlags); ++i)
{
auto flagAction = instr->accessedFlags[i].action;
if(flagAction == ZYDIS_CPUFLAG_ACTION_NONE)
continue;
Zydis::RegAccessInfo rai;
switch(flagAction)
{
case ZYDIS_CPUFLAG_ACTION_MODIFIED:
case ZYDIS_CPUFLAG_ACTION_SET_0:
case ZYDIS_CPUFLAG_ACTION_SET_1:
rai = Zydis::RAIWrite;
break;
case ZYDIS_CPUFLAG_ACTION_TESTED:
rai = Zydis::RAIRead;
break;
default:
rai = Zydis::RAINone;
break;
}
reginfo[ZYDIS_REGISTER_RFLAGS] = Zydis::RAINone;
reginfo[ZYDIS_REGISTER_EFLAGS] = Zydis::RAINone;
reginfo[ZYDIS_REGISTER_FLAGS] = Zydis::RAINone;
wInst.regsReferenced.emplace_back(cp.FlagName(ZydisCPUFlag(i)), rai);
}
wInst.regsReferenced.reserve(ZYDIS_REGISTER_MAX_VALUE);
reginfo[ArchValue(ZYDIS_REGISTER_EIP, ZYDIS_REGISTER_RIP)] = Zydis::RAINone;
for(int i = ZYDIS_REGISTER_NONE; i <= ZYDIS_REGISTER_MAX_VALUE; ++i)
if(reginfo[i])
wInst.regsReferenced.emplace_back(cp.RegName(ZydisRegister(i)), reginfo[i]);
// Info about volatile and nonvolatile registers
if(cp.IsBranchType(Zydis::BranchType::BTCall))
{
enum : uint8_t
{
Volatile = Zydis::RAIImplicit | Zydis::RAIWrite,
Parameter = Volatile | Zydis::RAIRead,
};
#define info(reg, type) wInst.regsReferenced.emplace_back(#reg, type)
#ifdef _WIN64
// https://docs.microsoft.com/en-us/cpp/build/x64-software-conventions
info(rax, Volatile);
info(rcx, Parameter);
info(rdx, Parameter);
info(r8, Parameter);
info(r9, Parameter);
info(r10, Volatile);
info(r11, Volatile);
info(xmm0, Parameter);
info(ymm0, Parameter);
info(xmm1, Parameter);
info(ymm1, Parameter);
info(xmm2, Parameter);
info(ymm2, Parameter);
info(xmm3, Parameter);
info(ymm3, Parameter);
info(xmm4, Parameter);
info(ymm4, Parameter);
info(xmm5, Parameter);
info(ymm5, Parameter);
#else
// https://en.wikipedia.org/wiki/X86_calling_conventions#Caller-saved_(volatile)_registers
info(eax, Volatile);
info(edx, Volatile);
info(ecx, Volatile);
#endif // _WIN64
#undef info
}
return wInst;
}
Instruction_t QBeaEngine::DecodeDataAt(const byte_t* data, duint size, duint origBase, duint origInstRVA, ENCODETYPE type)
{
//tokenize
ZydisTokenizer::InstructionToken cap;
auto infoIter = dataInstMap.find(type);
if(infoIter == dataInstMap.end())
infoIter = dataInstMap.find(enc_byte);
int len = mEncodeMap->getDataSize(origBase + origInstRVA, 1);
QString mnemonic = _bLongDataInst ? infoIter.value().longName : infoIter.value().shortName;
len = std::min(len, (int)size);
QString datastr = GetDataTypeString(data, len, type);
_tokenizer.TokenizeData(mnemonic, datastr, cap);
Instruction_t wInst;
wInst.instStr = mnemonic + " " + datastr;
wInst.dump = QByteArray((const char*)data, len);
wInst.rva = origInstRVA;
wInst.length = len;
wInst.branchType = Instruction_t::None;
wInst.branchDestination = 0;
wInst.tokens = cap;
wInst.prefixSize = 0;
wInst.opcodeSize = len;
wInst.group1Size = 0;
wInst.group2Size = 0;
wInst.group3Size = 0;
wInst.vectorElementType[0] = Zydis::VETDefault;
wInst.vectorElementType[1] = Zydis::VETDefault;
wInst.vectorElementType[2] = Zydis::VETDefault;
wInst.vectorElementType[3] = Zydis::VETDefault;
return wInst;
}
void QBeaEngine::UpdateDataInstructionMap()
{
dataInstMap.clear();
dataInstMap.insert(enc_byte, {"db", "byte", "int8"});
dataInstMap.insert(enc_word, {"dw", "word", "short"});
dataInstMap.insert(enc_dword, {"dd", "dword", "int"});
dataInstMap.insert(enc_fword, {"df", "fword", "fword"});
dataInstMap.insert(enc_qword, {"dq", "qword", "long"});
dataInstMap.insert(enc_tbyte, {"tbyte", "tbyte", "tbyte"});
dataInstMap.insert(enc_oword, {"oword", "oword", "oword"});
dataInstMap.insert(enc_mmword, {"mmword", "mmword", "long long"});
dataInstMap.insert(enc_xmmword, {"xmmword", "xmmword", "_m128"});
dataInstMap.insert(enc_ymmword, {"ymmword", "ymmword", "_m256"});
dataInstMap.insert(enc_real4, {"real4", "real4", "float"});
dataInstMap.insert(enc_real8, {"real8", "real8", "double"});
dataInstMap.insert(enc_real10, {"real10", "real10", "long double"});
dataInstMap.insert(enc_ascii, {"ascii", "ascii", "string"});
dataInstMap.insert(enc_unicode, {"unicode", "unicode", "wstring"});
}
void QBeaEngine::setCodeFoldingManager(CodeFoldingHelper* CodeFoldingManager)
{
mCodeFoldingManager = CodeFoldingManager;
}
void QBeaEngine::UpdateConfig()
{
_bLongDataInst = ConfigBool("Disassembler", "LongDataInstruction");
_tokenizer.UpdateConfig();
}
void formatOpcodeString(const Instruction_t & inst, RichTextPainter::List & list, std::vector<std::pair<size_t, bool>> & realBytes)
{
RichTextPainter::CustomRichText_t curByte;
auto size = inst.dump.size();
assert(list.empty()); //List must be empty before use
curByte.underlineWidth = 1;
curByte.flags = RichTextPainter::FlagAll;
curByte.underline = false;
list.reserve(size + 5);
realBytes.reserve(size + 5);
for(int i = 0; i < size; i++)
{
curByte.text = ToByteString(inst.dump.at(i));
list.push_back(curByte);
realBytes.push_back({i, true});
auto addCh = [&](char ch)
{
curByte.text = QString(ch);
list.push_back(curByte);
realBytes.push_back({i, false});
};
if(inst.prefixSize && i + 1 == inst.prefixSize)
addCh(':');
else if(inst.opcodeSize && i + 1 == inst.prefixSize + inst.opcodeSize)
addCh(' ');
else if(inst.group1Size && i + 1 == inst.prefixSize + inst.opcodeSize + inst.group1Size)
addCh(' ');
else if(inst.group2Size && i + 1 == inst.prefixSize + inst.opcodeSize + inst.group1Size + inst.group2Size)
addCh(' ');
else if(inst.group3Size && i + 1 == inst.prefixSize + inst.opcodeSize + inst.group1Size + inst.group2Size + inst.group3Size)
addCh(' ');
}
} |
C/C++ | x64dbg-development/src/gui/Src/Disassembler/QBeaEngine.h | #pragma once
#include <QString>
#include <vector>
#include "ZydisTokenizer.h"
class EncodeMap;
class CodeFoldingHelper;
struct Instruction_t
{
enum BranchType
{
None,
Conditional,
Unconditional,
Call
};
Instruction_t()
: rva(0),
length(0),
branchDestination(0),
branchType(None)
{
}
QString instStr;
QByteArray dump;
uint8_t prefixSize, opcodeSize, group1Size, group2Size, group3Size;
duint rva;
int length;
duint branchDestination;
BranchType branchType;
ZydisTokenizer::InstructionToken tokens;
std::vector<std::pair<const char*, uint8_t>> regsReferenced;
uint8_t vectorElementType[4];
};
class QBeaEngine
{
public:
explicit QBeaEngine(int maxModuleSize);
~QBeaEngine();
ulong DisassembleBack(const byte_t* data, duint base, duint size, duint ip, int n);
ulong DisassembleNext(const byte_t* data, duint base, duint size, duint ip, int n);
Instruction_t DisassembleAt(const byte_t* data, duint size, duint origBase, duint origInstRVA, bool datainstr = true);
Instruction_t DecodeDataAt(const byte_t* data, duint size, duint origBase, duint origInstRVA, ENCODETYPE type);
void setCodeFoldingManager(CodeFoldingHelper* CodeFoldingManager);
void UpdateConfig();
EncodeMap* getEncodeMap()
{
return mEncodeMap;
}
private:
struct DataInstructionInfo
{
QString shortName;
QString longName;
QString cName;
};
void UpdateDataInstructionMap();
ZydisTokenizer _tokenizer;
QHash<ENCODETYPE, DataInstructionInfo> dataInstMap;
bool _bLongDataInst;
EncodeMap* mEncodeMap;
CodeFoldingHelper* mCodeFoldingManager;
uint8_t reginfo[ZYDIS_REGISTER_MAX_VALUE + 1];
uint8_t flaginfo[ZYDIS_CPUFLAG_MAX_VALUE + 1];
};
void formatOpcodeString(const Instruction_t & inst, RichTextPainter::List & list, std::vector<std::pair<size_t, bool>> & realBytes); |
C++ | x64dbg-development/src/gui/Src/Disassembler/ZydisTokenizer.cpp | #include "ZydisTokenizer.h"
#include "Configuration.h"
#include "StringUtil.h"
#include "CachedFontMetrics.h"
ZydisTokenizer::ZydisTokenizer(int maxModuleLength)
: _maxModuleLength(maxModuleLength),
_success(false),
isNop(false),
_mnemonicType(TokenType::Uncategorized)
{
SetConfig(false, false, false, false, false, false, false, false, false);
}
static ZydisTokenizer::TokenColor colorNamesMap[size_t(ZydisTokenizer::TokenType::Last)];
QHash<QString, int> ZydisTokenizer::stringPoolMap;
int ZydisTokenizer::poolId = 0;
void ZydisTokenizer::addColorName(TokenType type, QString color, QString backgroundColor)
{
colorNamesMap[int(type)] = TokenColor(color, backgroundColor);
}
ZydisTokenizer::TokenColor ZydisTokenizer::getTokenColor(TokenType type)
{
return colorNamesMap[(size_t)type];
}
void ZydisTokenizer::addStringsToPool(const QString & strings)
{
QStringList stringList = strings.split(' ', QString::SkipEmptyParts);
for(const QString & string : stringList)
stringPoolMap.insert(string, poolId);
poolId++;
}
void ZydisTokenizer::UpdateColors()
{
//filling
addColorName(TokenType::Comma, "InstructionCommaColor", "InstructionCommaBackgroundColor");
addColorName(TokenType::Space, "", "");
addColorName(TokenType::ArgumentSpace, "", "");
addColorName(TokenType::MemoryOperatorSpace, "", "");
//general instruction parts
addColorName(TokenType::Prefix, "InstructionPrefixColor", "InstructionPrefixBackgroundColor");
addColorName(TokenType::Uncategorized, "InstructionUncategorizedColor", "InstructionUncategorizedBackgroundColor");
addColorName(TokenType::Address, "InstructionAddressColor", "InstructionAddressBackgroundColor"); //jump/call destinations
addColorName(TokenType::Value, "InstructionValueColor", "InstructionValueBackgroundColor");
//mnemonics
addColorName(TokenType::MnemonicNormal, "InstructionMnemonicColor", "InstructionMnemonicBackgroundColor");
addColorName(TokenType::MnemonicPushPop, "InstructionPushPopColor", "InstructionPushPopBackgroundColor");
addColorName(TokenType::MnemonicCall, "InstructionCallColor", "InstructionCallBackgroundColor");
addColorName(TokenType::MnemonicRet, "InstructionRetColor", "InstructionRetBackgroundColor");
addColorName(TokenType::MnemonicCondJump, "InstructionConditionalJumpColor", "InstructionConditionalJumpBackgroundColor");
addColorName(TokenType::MnemonicUncondJump, "InstructionUnconditionalJumpColor", "InstructionUnconditionalJumpBackgroundColor");
addColorName(TokenType::MnemonicNop, "InstructionNopColor", "InstructionNopBackgroundColor");
addColorName(TokenType::MnemonicFar, "InstructionFarColor", "InstructionFarBackgroundColor");
addColorName(TokenType::MnemonicInt3, "InstructionInt3Color", "InstructionInt3BackgroundColor");
addColorName(TokenType::MnemonicUnusual, "InstructionUnusualColor", "InstructionUnusualBackgroundColor");
//memory
addColorName(TokenType::MemorySize, "InstructionMemorySizeColor", "InstructionMemorySizeBackgroundColor");
addColorName(TokenType::MemorySegment, "InstructionMemorySegmentColor", "InstructionMemorySegmentBackgroundColor");
addColorName(TokenType::MemoryBrackets, "InstructionMemoryBracketsColor", "InstructionMemoryBracketsBackgroundColor");
addColorName(TokenType::MemoryStackBrackets, "InstructionMemoryStackBracketsColor", "InstructionMemoryStackBracketsBackgroundColor");
addColorName(TokenType::MemoryBaseRegister, "InstructionMemoryBaseRegisterColor", "InstructionMemoryBaseRegisterBackgroundColor");
addColorName(TokenType::MemoryIndexRegister, "InstructionMemoryIndexRegisterColor", "InstructionMemoryIndexRegisterBackgroundColor");
addColorName(TokenType::MemoryScale, "InstructionMemoryScaleColor", "InstructionMemoryScaleBackgroundColor");
addColorName(TokenType::MemoryOperator, "InstructionMemoryOperatorColor", "InstructionMemoryOperatorBackgroundColor");
//registers
addColorName(TokenType::GeneralRegister, "InstructionGeneralRegisterColor", "InstructionGeneralRegisterBackgroundColor");
addColorName(TokenType::FpuRegister, "InstructionFpuRegisterColor", "InstructionFpuRegisterBackgroundColor");
addColorName(TokenType::MmxRegister, "InstructionMmxRegisterColor", "InstructionMmxRegisterBackgroundColor");
addColorName(TokenType::XmmRegister, "InstructionXmmRegisterColor", "InstructionXmmRegisterBackgroundColor");
addColorName(TokenType::YmmRegister, "InstructionYmmRegisterColor", "InstructionYmmRegisterBackgroundColor");
addColorName(TokenType::ZmmRegister, "InstructionZmmRegisterColor", "InstructionZmmRegisterBackgroundColor");
}
void ZydisTokenizer::UpdateStringPool()
{
poolId = 0;
stringPoolMap.clear();
// These registers must be in lower case.
addStringsToPool("rax eax ax al ah");
addStringsToPool("rbx ebx bx bl bh");
addStringsToPool("rcx ecx cx cl ch");
addStringsToPool("rdx edx dx dl dh");
addStringsToPool("rsi esi si sil");
addStringsToPool("rdi edi di dil");
addStringsToPool("rbp ebp bp bpl");
addStringsToPool("rsp esp sp spl");
addStringsToPool("r8 r8d r8w r8b");
addStringsToPool("r9 r9d r9w r9b");
addStringsToPool("r10 r10d r10w r10b");
addStringsToPool("r11 r11d r11w r11b");
addStringsToPool("r12 r12d r12w r12b");
addStringsToPool("r13 r13d r13w r13b");
addStringsToPool("r14 r14d r14w r14b");
addStringsToPool("r15 r15d r15w r15b");
addStringsToPool("xmm0 ymm0 zmm0");
addStringsToPool("xmm1 ymm1 zmm1");
addStringsToPool("xmm2 ymm2 zmm2");
addStringsToPool("xmm3 ymm3 zmm3");
addStringsToPool("xmm4 ymm4 zmm4");
addStringsToPool("xmm5 ymm5 zmm5");
addStringsToPool("xmm6 ymm6 zmm6");
addStringsToPool("xmm7 ymm7 zmm7");
addStringsToPool("xmm8 ymm8 zmm8");
addStringsToPool("xmm9 ymm9 zmm9");
addStringsToPool("xmm10 ymm10 zmm10");
addStringsToPool("xmm11 ymm11 zmm11");
addStringsToPool("xmm12 ymm12 zmm12");
addStringsToPool("xmm13 ymm13 zmm13");
addStringsToPool("xmm14 ymm14 zmm14");
addStringsToPool("xmm15 ymm15 zmm15");
}
bool ZydisTokenizer::Tokenize(duint addr, const unsigned char* data, int datasize, InstructionToken & instruction)
{
_inst = InstructionToken();
_success = _cp.DisassembleSafe(addr, data, datasize);
if(_success)
{
if(!tokenizePrefix())
return false;
isNop = _cp.IsNop();
if(!tokenizeMnemonic())
return false;
for(int i = 0; i < _cp.OpCount(); i++)
{
if(i == 1 && _cp[0].size >= 128 && _cp[1].type == ZYDIS_OPERAND_TYPE_REGISTER
&& ZydisRegisterGetClass(_cp[1].reg.value) == ZYDIS_REGCLASS_MASK)
{
if(_bArgumentSpaces)
addToken(TokenType::ArgumentSpace, " ");
addToken(TokenType::Comma, "{");
if(!tokenizeOperand(_cp[i]))
return false;
addToken(TokenType::Comma, "}");
}
else if(i)
{
addToken(TokenType::Comma, ",");
if(_bArgumentSpaces)
addToken(TokenType::ArgumentSpace, " ");
if(!tokenizeOperand(_cp[i]))
return false;
}
else
{
if(!tokenizeOperand(_cp[i]))
return false;
}
}
}
else
{
isNop = false;
addToken(TokenType::MnemonicUnusual, "???");
}
if(_bNoHighlightOperands)
{
while(_inst.tokens.size() && _inst.tokens[_inst.tokens.size() - 1].type == TokenType::Space)
_inst.tokens.pop_back();
for(SingleToken & token : _inst.tokens)
token.type = _mnemonicType;
}
instruction = _inst;
return true;
}
bool ZydisTokenizer::TokenizeData(const QString & datatype, const QString & data, InstructionToken & instruction)
{
_inst = InstructionToken();
isNop = false;
if(!tokenizeMnemonic(TokenType::MnemonicNormal, datatype))
return false;
addToken(TokenType::Value, data);
instruction = _inst;
return true;
}
void ZydisTokenizer::TokenizeTraceRegister(const char* reg, duint oldValue, duint newValue, std::vector<SingleToken> & tokens)
{
if(tokens.size() > 0)
{
tokens.push_back(SingleToken(TokenType::ArgumentSpace, " ", TokenValue()));
}
QString regName(reg);
tokens.push_back(SingleToken(TokenType::GeneralRegister, ConfigBool("Disassembler", "Uppercase") ? regName.toUpper() : regName, TokenValue()));
tokens.push_back(SingleToken(TokenType::ArgumentSpace, ": ", TokenValue()));
tokens.push_back(SingleToken(TokenType::Value, ToHexString(oldValue), TokenValue(8, oldValue)));
tokens.push_back(SingleToken(TokenType::ArgumentSpace, "-> ", TokenValue()));
tokens.push_back(SingleToken(TokenType::Value, ToHexString(newValue), TokenValue(8, newValue)));
}
void ZydisTokenizer::TokenizeTraceMemory(duint address, duint oldValue, duint newValue, std::vector<SingleToken> & tokens)
{
if(tokens.size() > 0)
{
tokens.push_back(SingleToken(TokenType::ArgumentSpace, " ", TokenValue()));
}
tokens.push_back(SingleToken(TokenType::Address, ToPtrString(address), TokenValue(8, address)));
tokens.push_back(SingleToken(TokenType::ArgumentSpace, ": ", TokenValue()));
tokens.push_back(SingleToken(TokenType::Value, ToHexString(oldValue), TokenValue(8, oldValue)));
tokens.push_back(SingleToken(TokenType::ArgumentSpace, "-> ", TokenValue()));
tokens.push_back(SingleToken(TokenType::Value, ToHexString(newValue), TokenValue(8, newValue)));
}
void ZydisTokenizer::UpdateConfig()
{
SetConfig(ConfigBool("Disassembler", "Uppercase"),
ConfigBool("Disassembler", "TabbedMnemonic"),
ConfigBool("Disassembler", "ArgumentSpaces"),
ConfigBool("Disassembler", "HidePointerSizes"),
ConfigBool("Disassembler", "HideNormalSegments"),
ConfigBool("Disassembler", "MemorySpaces"),
ConfigBool("Disassembler", "NoHighlightOperands"),
ConfigBool("Disassembler", "NoCurrentModuleText"),
ConfigBool("Disassembler", "0xPrefixValues"));
_maxModuleLength = (int)ConfigUint("Disassembler", "MaxModuleSize");
UpdateStringPool();
}
void ZydisTokenizer::SetConfig(bool bUppercase, bool bTabbedMnemonic, bool bArgumentSpaces, bool bHidePointerSizes, bool bHideNormalSegments, bool bMemorySpaces, bool bNoHighlightOperands, bool bNoCurrentModuleText, bool b0xPrefixValues)
{
_bUppercase = bUppercase;
_bTabbedMnemonic = bTabbedMnemonic;
_bArgumentSpaces = bArgumentSpaces;
_bHidePointerSizes = bHidePointerSizes;
_bHideNormalSegments = bHideNormalSegments;
_bMemorySpaces = bMemorySpaces;
_bNoHighlightOperands = bNoHighlightOperands;
_bNoCurrentModuleText = bNoCurrentModuleText;
_b0xPrefixValues = b0xPrefixValues;
}
int ZydisTokenizer::Size() const
{
return _success ? _cp.Size() : 1;
}
const Zydis & ZydisTokenizer::GetZydis() const
{
return _cp;
}
void ZydisTokenizer::TokenToRichText(const InstructionToken & instr, RichTextPainter::List & richTextList, const SingleToken* highlightToken)
{
QColor highlightColor = ConfigColor("InstructionHighlightColor");
QColor highlightBackgroundColor = ConfigColor("InstructionHighlightBackgroundColor");
for(const auto & token : instr.tokens)
{
RichTextPainter::CustomRichText_t richText;
richText.flags = RichTextPainter::FlagNone;
richText.text = token.text;
richText.underline = false;
if(token.type < TokenType::Last)
{
const auto & tokenColor = colorNamesMap[int(token.type)];
richText.flags = tokenColor.flags;
if(TokenEquals(&token, highlightToken))
{
richText.textColor = highlightColor;
richText.textBackground = highlightBackgroundColor;
}
else
{
richText.textColor = tokenColor.color;
richText.textBackground = tokenColor.backgroundColor;
}
}
richTextList.push_back(richText);
}
}
bool ZydisTokenizer::TokenFromX(const InstructionToken & instr, SingleToken & token, int x, CachedFontMetrics* fontMetrics)
{
if(x < instr.x) //before the first token
return false;
int len = int(instr.tokens.size());
for(int i = 0, xStart = instr.x; i < len; i++)
{
const auto & curToken = instr.tokens.at(i);
int curWidth = fontMetrics->width(curToken.text);
int xEnd = xStart + curWidth;
if(x >= xStart && x < xEnd)
{
token = curToken;
return true;
}
xStart = xEnd;
}
return false; //not found
}
bool ZydisTokenizer::IsHighlightableToken(const SingleToken & token)
{
switch(token.type)
{
case TokenType::Comma:
case TokenType::Space:
case TokenType::ArgumentSpace:
case TokenType::Uncategorized:
case TokenType::MemoryOperatorSpace:
case TokenType::MemoryBrackets:
case TokenType::MemoryStackBrackets:
case TokenType::MemoryOperator:
return false;
break;
}
return true;
}
bool ZydisTokenizer::tokenTextPoolEquals(const QString & a, const QString & b)
{
if(a.compare(b, Qt::CaseInsensitive) == 0)
return true;
auto found1 = stringPoolMap.find(a.toLower());
auto found2 = stringPoolMap.find(b.toLower());
if(found1 == stringPoolMap.end() || found2 == stringPoolMap.end())
return false;
return found1.value() == found2.value();
}
bool ZydisTokenizer::TokenEquals(const SingleToken* a, const SingleToken* b, bool ignoreSize)
{
if(!a || !b)
return false;
if(a->value.size != 0 && b->value.size != 0) //we have a value
{
if(!ignoreSize && a->value.size != b->value.size)
return false;
else if(a->value.value != b->value.value)
return false;
}
return tokenTextPoolEquals(a->text, b->text);
}
void ZydisTokenizer::addToken(TokenType type, QString text, const TokenValue & value)
{
switch(type)
{
case TokenType::Space:
case TokenType::ArgumentSpace:
case TokenType::MemoryOperatorSpace:
break;
default:
text = text.trimmed();
break;
}
if(_bUppercase && !value.size)
text = text.toUpper();
_inst.tokens.push_back(SingleToken(isNop ? TokenType::MnemonicNop : type, text, value));
}
void ZydisTokenizer::addToken(TokenType type, const QString & text)
{
addToken(type, text, TokenValue());
}
void ZydisTokenizer::addMemoryOperator(char operatorText)
{
if(_bMemorySpaces)
addToken(TokenType::MemoryOperatorSpace, " ");
QString text;
text += operatorText;
addToken(TokenType::MemoryOperator, text);
if(_bMemorySpaces)
addToken(TokenType::MemoryOperatorSpace, " ");
}
QString ZydisTokenizer::printValue(const TokenValue & value, bool expandModule, int maxModuleLength) const
{
QString labelText;
char label_[MAX_LABEL_SIZE] = "";
char module_[MAX_MODULE_SIZE] = "";
QString moduleText;
duint addr = value.value;
bool bHasLabel = DbgGetLabelAt(addr, SEG_DEFAULT, label_);
labelText = QString(label_);
bool bHasModule;
if(_bNoCurrentModuleText)
{
duint size, base;
base = DbgMemFindBaseAddr(this->GetZydis().Address(), &size);
if(addr >= base && addr < base + size)
bHasModule = false;
else
bHasModule = (expandModule && DbgGetModuleAt(addr, module_) && !QString(labelText).startsWith("JMP.&"));
}
else
bHasModule = (expandModule && DbgGetModuleAt(addr, module_) && !QString(labelText).startsWith("JMP.&"));
moduleText = QString(module_);
if(maxModuleLength != -1)
moduleText.truncate(maxModuleLength);
if(moduleText.length())
moduleText += ".";
QString addrText = ToHexString(addr);
QString finalText;
if(bHasLabel && bHasModule) //<module.label>
finalText = QString("<%1%2>").arg(moduleText).arg(labelText);
else if(bHasModule) //module.addr
finalText = QString("%1%2").arg(moduleText).arg(addrText);
else if(bHasLabel) //<label>
finalText = QString("<%1>").arg(labelText);
else if(_b0xPrefixValues)
finalText = QString("0x") + addrText;
else
finalText = addrText;
return finalText;
}
bool ZydisTokenizer::tokenizePrefix()
{
//TODO: what happens with multiple prefixes?
bool hasPrefix = true;
QStringList prefixText;
auto attr = _cp.GetInstr()->attributes;
if(attr & ZYDIS_ATTRIB_HAS_LOCK)
prefixText += "lock";
else if(attr & ZYDIS_ATTRIB_HAS_REP)
prefixText += "rep";
else if(attr & ZYDIS_ATTRIB_HAS_REPE)
prefixText += "repe";
else if(attr & ZYDIS_ATTRIB_HAS_REPNE)
prefixText += "repne";
else if(attr & ZYDIS_ATTRIB_HAS_BOUND)
prefixText += "bnd";
else if(attr & ZYDIS_ATTRIB_HAS_XACQUIRE)
prefixText += "xacquire";
else if(attr & ZYDIS_ATTRIB_HAS_XRELEASE)
prefixText += "xrelease";
else
hasPrefix = false;
if(hasPrefix)
{
addToken(TokenType::Prefix, prefixText.join(' '));
addToken(TokenType::Space, " ");
}
return true;
}
bool ZydisTokenizer::tokenizeMnemonic()
{
QString mnemonic = QString(_cp.Mnemonic().c_str());
_mnemonicType = TokenType::MnemonicNormal;
if(_cp.IsBranchType(Zydis::BTFar))
mnemonic += " far";
if(isNop)
_mnemonicType = TokenType::MnemonicNop;
else if(_cp.IsInt3())
_mnemonicType = TokenType::MnemonicInt3;
else if(_cp.IsUnusual())
_mnemonicType = TokenType::MnemonicUnusual;
else if(_cp.IsBranchType(Zydis::BTCallSem))
_mnemonicType = TokenType::MnemonicCall;
else if(_cp.IsBranchType(Zydis::BTCondJmpSem))
_mnemonicType = TokenType::MnemonicCondJump;
else if(_cp.IsBranchType(Zydis::BTUncondJmpSem))
_mnemonicType = TokenType::MnemonicUncondJump;
else if(_cp.IsBranchType(Zydis::BTRetSem))
_mnemonicType = TokenType::MnemonicRet;
else if(_cp.IsPushPop())
_mnemonicType = TokenType::MnemonicPushPop;
return tokenizeMnemonic(_mnemonicType, mnemonic);
}
bool ZydisTokenizer::tokenizeMnemonic(TokenType type, const QString & mnemonic)
{
addToken(type, mnemonic);
if(_bTabbedMnemonic)
{
int spaceCount = 7 - mnemonic.length();
if(spaceCount > 0)
{
for(int i = 0; i < spaceCount; i++)
addToken(TokenType::Space, " ");
}
}
addToken(TokenType::Space, " ");
return true;
}
bool ZydisTokenizer::tokenizeOperand(const ZydisDecodedOperand & op)
{
switch(op.type)
{
case ZYDIS_OPERAND_TYPE_REGISTER:
return tokenizeRegOperand(op);
case ZYDIS_OPERAND_TYPE_IMMEDIATE:
return tokenizeImmOperand(op);
case ZYDIS_OPERAND_TYPE_MEMORY:
return tokenizeMemOperand(op);
case ZYDIS_OPERAND_TYPE_POINTER:
return tokenizePtrOperand(op);
default:
return tokenizeInvalidOperand(op);
}
}
bool ZydisTokenizer::tokenizeRegOperand(const ZydisDecodedOperand & op)
{
auto registerType = TokenType::GeneralRegister;
auto reg = op.reg;
auto regClass = ZydisRegisterGetClass(reg.value);
switch(regClass)
{
case ZYDIS_REGCLASS_X87:
registerType = TokenType::FpuRegister;
break;
case ZYDIS_REGCLASS_MMX:
registerType = TokenType::MmxRegister;
break;
case ZYDIS_REGCLASS_XMM:
registerType = TokenType::XmmRegister;
break;
case ZYDIS_REGCLASS_YMM:
registerType = TokenType::YmmRegister;
break;
case ZYDIS_REGCLASS_ZMM:
case ZYDIS_REGCLASS_MASK:
registerType = TokenType::ZmmRegister;
break;
}
if(reg.value == ArchValue(ZYDIS_REGISTER_FS, ZYDIS_REGISTER_GS))
registerType = TokenType::MnemonicUnusual;
addToken(registerType, _cp.RegName(reg.value));
return true;
}
bool ZydisTokenizer::tokenizeImmOperand(const ZydisDecodedOperand & op)
{
duint value;
TokenType valueType;
if(_cp.IsBranchType(Zydis::BTJmp | Zydis::BTCall | Zydis::BTLoop | Zydis::BTXbegin))
{
valueType = TokenType::Address;
value = op.imm.value.u;
}
else
{
auto opsize = _cp.GetInstr()->operandWidth;
valueType = TokenType::Value;
value = duint(op.imm.value.u) & (duint(-1) >> (sizeof(duint) * 8 - opsize));
}
auto tokenValue = TokenValue(op.size / 8, value);
addToken(valueType, printValue(tokenValue, true, _maxModuleLength), tokenValue);
return true;
}
bool ZydisTokenizer::tokenizeMemOperand(const ZydisDecodedOperand & op)
{
auto opsize = op.size / 8;
//memory size
if(!_bHidePointerSizes)
{
const char* sizeText = _cp.MemSizeName(opsize);
if(sizeText)
{
addToken(TokenType::MemorySize, QString(sizeText) + " ptr");
addToken(TokenType::Space, " ");
}
}
const auto & mem = op.mem;
//memory segment
bool bUnusualSegment = (mem.segment == ZYDIS_REGISTER_FS || mem.segment == ZYDIS_REGISTER_GS);
if(!_bHideNormalSegments || bUnusualSegment)
{
auto segmentType = mem.segment == ArchValue(ZYDIS_REGISTER_FS, ZYDIS_REGISTER_GS)
? TokenType::MnemonicUnusual : TokenType::MemorySegment;
addToken(segmentType, _cp.RegName(mem.segment));
addToken(TokenType::Uncategorized, ":");
}
//memory opening bracket
auto bracketsType = TokenType::MemoryBrackets;
switch(mem.base)
{
case ZYDIS_REGISTER_ESP:
case ZYDIS_REGISTER_RSP:
case ZYDIS_REGISTER_EBP:
case ZYDIS_REGISTER_RBP:
bracketsType = TokenType::MemoryStackBrackets;
default:
break;
}
addToken(bracketsType, "[");
//stuff inside the brackets
if(mem.base == ZYDIS_REGISTER_RIP) //rip-relative (#replacement)
{
duint addr = _cp.Address() + duint(mem.disp.value) + _cp.Size();
TokenValue value = TokenValue(opsize, addr);
auto displacementType = DbgMemIsValidReadPtr(addr) ? TokenType::Address : TokenType::Value;
addToken(displacementType, printValue(value, false, _maxModuleLength), value);
}
else //#base + #index * #scale + #displacement
{
bool prependPlus = false;
if(mem.base != ZYDIS_REGISTER_NONE) //base register
{
addToken(TokenType::MemoryBaseRegister, _cp.RegName(mem.base));
prependPlus = true;
}
if(mem.index != ZYDIS_REGISTER_NONE) //index register
{
if(prependPlus)
addMemoryOperator('+');
addToken(TokenType::MemoryIndexRegister, _cp.RegName(mem.index));
if(mem.scale > 1)
{
addMemoryOperator('*');
addToken(TokenType::MemoryScale, QString().sprintf("%d", mem.scale));
}
prependPlus = true;
}
if(mem.disp.value)
{
char operatorText = '+';
TokenValue value(opsize, duint(mem.disp.value));
auto displacementType = DbgMemIsValidReadPtr(duint(mem.disp.value)) ? TokenType::Address : TokenType::Value;
QString valueText;
if(mem.disp.value < 0 && prependPlus)
{
operatorText = '-';
valueText = printValue(TokenValue(opsize, duint(mem.disp.value * -1)), false, _maxModuleLength);
}
else
valueText = printValue(value, false, _maxModuleLength);
if(prependPlus)
addMemoryOperator(operatorText);
addToken(displacementType, valueText, value);
}
else if(!prependPlus)
addToken(TokenType::Value, "0");
}
//closing bracket
addToken(bracketsType, "]");
return true;
}
bool ZydisTokenizer::tokenizePtrOperand(const ZydisDecodedOperand & op)
{
auto segValue = TokenValue(2, op.ptr.segment);
addToken(TokenType::MemorySegment, printValue(segValue, true, _maxModuleLength), segValue);
addToken(TokenType::Uncategorized, ":");
auto offsetValue = TokenValue(_cp.GetInstr()->operandWidth / 8, op.ptr.offset);
addToken(TokenType::Address, printValue(offsetValue, true, _maxModuleLength), offsetValue);
return true;
}
bool ZydisTokenizer::tokenizeInvalidOperand(const ZydisDecodedOperand & op)
{
Q_UNUSED(op);
addToken(TokenType::MnemonicUnusual, "???");
return true;
} |
C/C++ | x64dbg-development/src/gui/Src/Disassembler/ZydisTokenizer.h | #pragma once
#include <zydis_wrapper.h>
#include "RichTextPainter.h"
#include "Configuration.h"
#include <map>
#include <QHash>
#include <QtCore>
class ZydisTokenizer
{
public:
enum class TokenType
{
//filling
Comma = 0,
Space,
ArgumentSpace,
MemoryOperatorSpace,
//general instruction parts
Prefix,
Uncategorized,
//mnemonics
MnemonicNormal,
MnemonicPushPop,
MnemonicCall,
MnemonicRet,
MnemonicCondJump,
MnemonicUncondJump,
MnemonicNop,
MnemonicFar,
MnemonicInt3,
MnemonicUnusual,
//values
Address, //jump/call destinations or displacements inside memory
Value,
//memory
MemorySize,
MemorySegment,
MemoryBrackets,
MemoryStackBrackets,
MemoryBaseRegister,
MemoryIndexRegister,
MemoryScale,
MemoryOperator, //'+', '-' and '*'
//registers
GeneralRegister,
FpuRegister,
MmxRegister,
XmmRegister,
YmmRegister,
ZmmRegister,
//last
Last
};
struct TokenValue
{
int size; //value size (in bytes), zero means no value
duint value; //actual value
TokenValue(int size, duint value) :
size(size),
value(value)
{
}
TokenValue() :
size(0),
value(0)
{
}
bool operator == (const TokenValue & rhs) const
{
return /*size == rhs.size &&*/ value == rhs.value;
}
};
struct SingleToken
{
TokenType type; //token type
QString text; //token text
TokenValue value; //token value (if applicable)
SingleToken() :
type(TokenType::Uncategorized)
{
}
SingleToken(TokenType type, const QString & text, const TokenValue & value) :
type(type),
text(text),
value(value)
{
}
SingleToken(TokenType type, const QString & text) :
SingleToken(type, text, TokenValue())
{
}
bool operator == (const SingleToken & rhs) const
{
return type == rhs.type && text == rhs.text && value == rhs.value;
}
};
struct InstructionToken
{
std::vector<SingleToken> tokens; //list of tokens that form the instruction
int x; //x of the first character
InstructionToken()
{
tokens.clear();
x = 0;
}
};
struct TokenColor
{
RichTextPainter::CustomRichTextFlags flags;
QColor color;
QColor backgroundColor;
TokenColor(QString color, QString backgroundColor)
{
if(color.length() && backgroundColor.length())
{
this->flags = RichTextPainter::FlagAll;
this->color = ConfigColor(color);
this->backgroundColor = ConfigColor(backgroundColor);
}
else if(color.length())
{
this->flags = RichTextPainter::FlagColor;
this->color = ConfigColor(color);
}
else if(backgroundColor.length())
{
this->flags = RichTextPainter::FlagBackground;
this->backgroundColor = ConfigColor(backgroundColor);
}
else
this->flags = RichTextPainter::FlagNone;
}
TokenColor()
: TokenColor("", "")
{
}
};
ZydisTokenizer(int maxModuleLength);
bool Tokenize(duint addr, const unsigned char* data, int datasize, InstructionToken & instruction);
bool TokenizeData(const QString & datatype, const QString & data, InstructionToken & instruction);
void UpdateConfig();
void SetConfig(bool bUppercase, bool bTabbedMnemonic, bool bArgumentSpaces, bool bHidePointerSizes, bool bHideNormalSegments, bool bMemorySpaces, bool bNoHighlightOperands, bool bNoCurrentModuleText, bool b0xPrefixValues);
int Size() const;
const Zydis & GetZydis() const;
static void UpdateColors();
static void UpdateStringPool();
static void TokenToRichText(const InstructionToken & instr, RichTextPainter::List & richTextList, const SingleToken* highlightToken);
static bool TokenFromX(const InstructionToken & instr, SingleToken & token, int x, CachedFontMetrics* fontMetrics);
static bool IsHighlightableToken(const SingleToken & token);
static bool TokenEquals(const SingleToken* a, const SingleToken* b, bool ignoreSize = true);
static void addColorName(TokenType type, QString color, QString backgroundColor);
static void addStringsToPool(const QString & regs);
static bool tokenTextPoolEquals(const QString & a, const QString & b);
static TokenColor getTokenColor(TokenType type);
static void TokenizeTraceRegister(const char* reg, duint oldValue, duint newValue, std::vector<SingleToken> & tokens);
static void TokenizeTraceMemory(duint address, duint oldValue, duint newValue, std::vector<SingleToken> & tokens);
private:
Zydis _cp;
bool isNop;
InstructionToken _inst;
bool _success;
int _maxModuleLength;
bool _bUppercase;
bool _bTabbedMnemonic;
bool _bArgumentSpaces;
bool _bHidePointerSizes;
bool _bHideNormalSegments;
bool _bMemorySpaces;
bool _bNoHighlightOperands;
bool _bNoCurrentModuleText;
bool _b0xPrefixValues;
TokenType _mnemonicType;
void addToken(TokenType type, QString text, const TokenValue & value);
void addToken(TokenType type, const QString & text);
void addMemoryOperator(char operatorText);
QString printValue(const TokenValue & value, bool expandModule, int maxModuleLength) const;
static QHash<QString, int> stringPoolMap;
static int poolId;
bool tokenizePrefix();
bool tokenizeMnemonic();
bool tokenizeMnemonic(TokenType type, const QString & mnemonic);
bool tokenizeOperand(const ZydisDecodedOperand & op);
bool tokenizeRegOperand(const ZydisDecodedOperand & op);
bool tokenizeImmOperand(const ZydisDecodedOperand & op);
bool tokenizeMemOperand(const ZydisDecodedOperand & op);
bool tokenizePtrOperand(const ZydisDecodedOperand & op);
bool tokenizeInvalidOperand(const ZydisDecodedOperand & op);
}; |
C++ | x64dbg-development/src/gui/Src/Gui/AboutDialog.cpp | #include "AboutDialog.h"
#include "UpdateChecker.h"
#include "ui_AboutDialog.h"
#include <StringUtil.h>
#include <QDesktopServices>
#include <QUrl>
AboutDialog::AboutDialog(UpdateChecker* updateChecker, QWidget* parent) :
mUpdateChecker(updateChecker),
QDialog(parent),
ui(new Ui::AboutDialog)
{
ui->setupUi(this);
//set window flags
setModal(true);
setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint | Qt::MSWindowsFixedSizeDialogHint);
ui->lblVersion->setText(ToDateString(GetCompileDate()) + ", " __TIME__);
ui->lblQrImage->installEventFilter(this);
}
AboutDialog::~AboutDialog()
{
delete ui;
}
bool AboutDialog::eventFilter(QObject* obj, QEvent* event)
{
if(obj == ui->lblQrImage && event->type() == QEvent::MouseButtonPress)
QDesktopServices::openUrl(QUrl("https://blockchain.info/address/1GuXgtCrLk4aYgivAT7xAi8zVHWk5CkEoY"));
return false;
}
void AboutDialog::on_btnCheckUpdates_clicked()
{
mUpdateChecker->checkForUpdates();
} |
C/C++ | x64dbg-development/src/gui/Src/Gui/AboutDialog.h | #pragma once
#include <QDialog>
class UpdateChecker;
namespace Ui
{
class AboutDialog;
}
class AboutDialog : public QDialog
{
Q_OBJECT
public:
explicit AboutDialog(UpdateChecker* updateChecker, QWidget* parent = 0);
~AboutDialog();
protected:
bool eventFilter(QObject* obj, QEvent* event) override;
private slots:
void on_btnCheckUpdates_clicked();
private:
Ui::AboutDialog* ui;
UpdateChecker* mUpdateChecker;
}; |
User Interface | x64dbg-development/src/gui/Src/Gui/AboutDialog.ui | <?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>AboutDialog</class>
<widget class="QDialog" name="AboutDialog">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>321</width>
<height>321</height>
</rect>
</property>
<property name="windowTitle">
<string>About x64dbg</string>
</property>
<property name="windowIcon">
<iconset theme="information" resource="../../resource.qrc">
<normaloff>:/Default/icons/information.png</normaloff>:/Default/icons/information.png</iconset>
</property>
<layout class="QVBoxLayout" name="verticalLayout_7">
<item>
<layout class="QHBoxLayout" name="horizontalLayout">
<item>
<spacer name="horizontalSpacer_3">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>40</width>
<height>20</height>
</size>
</property>
</spacer>
</item>
<item>
<widget class="QLabel" name="lblLogoImage">
<property name="minimumSize">
<size>
<width>128</width>
<height>128</height>
</size>
</property>
<property name="maximumSize">
<size>
<width>128</width>
<height>128</height>
</size>
</property>
<property name="text">
<string/>
</property>
<property name="pixmap">
<pixmap resource="../../resource.qrc">:/Default/icons/bug.png</pixmap>
</property>
<property name="scaledContents">
<bool>true</bool>
</property>
<property name="alignment">
<set>Qt::AlignCenter</set>
</property>
</widget>
</item>
<item>
<layout class="QVBoxLayout" name="verticalLayout_4">
<property name="spacing">
<number>0</number>
</property>
<property name="topMargin">
<number>0</number>
</property>
<item>
<layout class="QVBoxLayout" name="verticalLayout">
<property name="spacing">
<number>0</number>
</property>
<property name="sizeConstraint">
<enum>QLayout::SetDefaultConstraint</enum>
</property>
<item>
<widget class="QLabel" name="lblWebsiteTitle">
<property name="sizePolicy">
<sizepolicy hsizetype="Preferred" vsizetype="Maximum">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="styleSheet">
<string notr="true"/>
</property>
<property name="inputMethodHints">
<set>Qt::ImhUrlCharactersOnly</set>
</property>
<property name="text">
<string>Website:</string>
</property>
<property name="openExternalLinks">
<bool>true</bool>
</property>
</widget>
</item>
<item>
<widget class="QLabel" name="lblWebsite">
<property name="sizePolicy">
<sizepolicy hsizetype="Preferred" vsizetype="Maximum">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="cursor">
<cursorShape>PointingHandCursor</cursorShape>
</property>
<property name="styleSheet">
<string notr="true"/>
</property>
<property name="inputMethodHints">
<set>Qt::ImhUrlCharactersOnly</set>
</property>
<property name="text">
<string><a href="https://x64dbg.com">https://x64dbg.com</a></string>
</property>
<property name="textFormat">
<enum>Qt::RichText</enum>
</property>
<property name="openExternalLinks">
<bool>true</bool>
</property>
<property name="textInteractionFlags">
<set>Qt::LinksAccessibleByMouse</set>
</property>
</widget>
</item>
</layout>
</item>
<item>
<layout class="QVBoxLayout" name="verticalLayout_2">
<property name="spacing">
<number>0</number>
</property>
<item>
<widget class="QLabel" name="lblVersionTitle">
<property name="sizePolicy">
<sizepolicy hsizetype="Preferred" vsizetype="Maximum">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="styleSheet">
<string notr="true"/>
</property>
<property name="inputMethodHints">
<set>Qt::ImhUrlCharactersOnly</set>
</property>
<property name="text">
<string>Version:</string>
</property>
<property name="openExternalLinks">
<bool>true</bool>
</property>
</widget>
</item>
<item>
<widget class="QLabel" name="lblVersion">
<property name="sizePolicy">
<sizepolicy hsizetype="Preferred" vsizetype="Maximum">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="styleSheet">
<string notr="true"/>
</property>
<property name="inputMethodHints">
<set>Qt::ImhUrlCharactersOnly</set>
</property>
<property name="text">
<string/>
</property>
<property name="openExternalLinks">
<bool>true</bool>
</property>
<property name="textInteractionFlags">
<set>Qt::NoTextInteraction</set>
</property>
</widget>
</item>
</layout>
</item>
<item>
<layout class="QVBoxLayout" name="verticalLayout_3">
<property name="spacing">
<number>0</number>
</property>
<item>
<widget class="QLabel" name="lblIconsTitle">
<property name="sizePolicy">
<sizepolicy hsizetype="Preferred" vsizetype="Maximum">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="styleSheet">
<string notr="true"/>
</property>
<property name="inputMethodHints">
<set>Qt::ImhUrlCharactersOnly</set>
</property>
<property name="text">
<string>Icons:</string>
</property>
<property name="openExternalLinks">
<bool>true</bool>
</property>
</widget>
</item>
<item>
<widget class="QLabel" name="lblIcons">
<property name="sizePolicy">
<sizepolicy hsizetype="Preferred" vsizetype="Maximum">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="cursor">
<cursorShape>PointingHandCursor</cursorShape>
</property>
<property name="styleSheet">
<string notr="true"/>
</property>
<property name="inputMethodHints">
<set>Qt::ImhUrlCharactersOnly</set>
</property>
<property name="text">
<string><html><head/><body><p><a href="https://p.yusukekamiyamane.com"><span style=" text-decoration: underline;">Yusuke Kamiyamane</span></a><br/><a href="https://github.com/mrfearless"><span style=" text-decoration: underline;">mrfearless</span></a></p></body></html></string>
</property>
<property name="textFormat">
<enum>Qt::RichText</enum>
</property>
<property name="alignment">
<set>Qt::AlignLeading|Qt::AlignLeft|Qt::AlignTop</set>
</property>
<property name="openExternalLinks">
<bool>true</bool>
</property>
<property name="textInteractionFlags">
<set>Qt::LinksAccessibleByMouse</set>
</property>
</widget>
</item>
</layout>
</item>
</layout>
</item>
<item>
<spacer name="horizontalSpacer_4">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>40</width>
<height>20</height>
</size>
</property>
</spacer>
</item>
</layout>
</item>
<item>
<layout class="QVBoxLayout" name="verticalLayout_5">
<property name="spacing">
<number>10</number>
</property>
<item>
<spacer name="verticalSpacer">
<property name="orientation">
<enum>Qt::Vertical</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>20</width>
<height>40</height>
</size>
</property>
</spacer>
</item>
<item>
<widget class="QLabel" name="lblAbout">
<property name="sizePolicy">
<sizepolicy hsizetype="Preferred" vsizetype="Preferred">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="styleSheet">
<string notr="true"/>
</property>
<property name="inputMethodHints">
<set>Qt::ImhUrlCharactersOnly</set>
</property>
<property name="text">
<string>An open-source x64/x32 debugger for windows.</string>
</property>
<property name="alignment">
<set>Qt::AlignCenter</set>
</property>
<property name="openExternalLinks">
<bool>true</bool>
</property>
</widget>
</item>
<item>
<layout class="QHBoxLayout" name="horizontalLayout_2">
<item>
<spacer name="horizontalSpacer">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>40</width>
<height>20</height>
</size>
</property>
</spacer>
</item>
<item>
<widget class="QPushButton" name="btnCheckUpdates">
<property name="sizePolicy">
<sizepolicy hsizetype="Expanding" vsizetype="Preferred">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="minimumSize">
<size>
<width>121</width>
<height>28</height>
</size>
</property>
<property name="text">
<string>Check for Updates</string>
</property>
</widget>
</item>
<item>
<spacer name="horizontalSpacer_2">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>40</width>
<height>20</height>
</size>
</property>
</spacer>
</item>
</layout>
</item>
<item>
<spacer name="verticalSpacer_2">
<property name="orientation">
<enum>Qt::Vertical</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>20</width>
<height>40</height>
</size>
</property>
</spacer>
</item>
</layout>
</item>
<item>
<layout class="QHBoxLayout" name="horizontalLayout_3">
<property name="spacing">
<number>0</number>
</property>
<item>
<layout class="QVBoxLayout" name="verticalLayout_6">
<property name="spacing">
<number>0</number>
</property>
<property name="sizeConstraint">
<enum>QLayout::SetMaximumSize</enum>
</property>
<property name="topMargin">
<number>7</number>
</property>
<property name="bottomMargin">
<number>7</number>
</property>
<item>
<widget class="QLabel" name="lblDonationTitle">
<property name="sizePolicy">
<sizepolicy hsizetype="Preferred" vsizetype="Maximum">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="styleSheet">
<string notr="true"/>
</property>
<property name="inputMethodHints">
<set>Qt::ImhUrlCharactersOnly</set>
</property>
<property name="text">
<string><h3>Donations</h3></string>
</property>
<property name="openExternalLinks">
<bool>true</bool>
</property>
</widget>
</item>
<item>
<widget class="QLabel" name="lblDonation">
<property name="sizePolicy">
<sizepolicy hsizetype="Preferred" vsizetype="Maximum">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="styleSheet">
<string notr="true"/>
</property>
<property name="inputMethodHints">
<set>Qt::ImhUrlCharactersOnly</set>
</property>
<property name="text">
<string>Please consider donating using the Bitcoin address on the right or by going to <a href="https://donate.x64dbg.com">donate.x64dbg.com</a>.</string>
</property>
<property name="alignment">
<set>Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter</set>
</property>
<property name="wordWrap">
<bool>true</bool>
</property>
<property name="openExternalLinks">
<bool>true</bool>
</property>
<property name="textInteractionFlags">
<set>Qt::LinksAccessibleByMouse</set>
</property>
</widget>
</item>
</layout>
</item>
<item>
<widget class="QLabel" name="lblQrImage">
<property name="sizePolicy">
<sizepolicy hsizetype="Preferred" vsizetype="Preferred">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="minimumSize">
<size>
<width>81</width>
<height>81</height>
</size>
</property>
<property name="maximumSize">
<size>
<width>81</width>
<height>81</height>
</size>
</property>
<property name="cursor">
<cursorShape>PointingHandCursor</cursorShape>
</property>
<property name="text">
<string/>
</property>
<property name="textFormat">
<enum>Qt::RichText</enum>
</property>
<property name="pixmap">
<pixmap resource="../../resource.qrc">:/Default/icons/donation_qr.png</pixmap>
</property>
<property name="scaledContents">
<bool>true</bool>
</property>
<property name="wordWrap">
<bool>false</bool>
</property>
</widget>
</item>
</layout>
</item>
<item>
<spacer name="verticalSpacer_3">
<property name="orientation">
<enum>Qt::Vertical</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>20</width>
<height>40</height>
</size>
</property>
</spacer>
</item>
</layout>
</widget>
<resources>
<include location="../../resource.qrc"/>
</resources>
<connections/>
</ui> |
C++ | x64dbg-development/src/gui/Src/Gui/AppearanceDialog.cpp | #include "AppearanceDialog.h"
#include "ui_AppearanceDialog.h"
#include <QColorDialog>
#include <QFontDialog>
#include <QMessageBox>
#include <memory>
#include "Configuration.h"
#include "StringUtil.h"
#include "MiscUtil.h"
AppearanceDialog::AppearanceDialog(QWidget* parent) : QDialog(parent), ui(new Ui::AppearanceDialog)
{
ui->setupUi(this);
//set window flags
setModal(true);
setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint | Qt::MSWindowsFixedSizeDialogHint);
//Colors
colorMap = &Config()->Colors;
colorBackupMap = *colorMap;
ui->groupColor->setEnabled(false);
ui->groupBackgroundColor->setEnabled(false);
colorInfoListInit();
//Fonts
fontMap = &Config()->Fonts;
fontBackupMap = *fontMap;
fontInit();
ui->exampleText->setFont(ConfigFont("AbstractTableView"));
connect(this, SIGNAL(rejected()), this, SLOT(rejectedSlot()));
}
AppearanceDialog::~AppearanceDialog()
{
delete ui;
}
//Colors
void AppearanceDialog::on_button000000_clicked()
{
ui->editColor->setText("#000000");
}
void AppearanceDialog::on_button000080_clicked()
{
ui->editColor->setText("#000080");
}
void AppearanceDialog::on_button008000_clicked()
{
ui->editColor->setText("#008000");
}
void AppearanceDialog::on_button008080_clicked()
{
ui->editColor->setText("#008080");
}
void AppearanceDialog::on_button800000_clicked()
{
ui->editColor->setText("#800000");
}
void AppearanceDialog::on_button800080_clicked()
{
ui->editColor->setText("#800080");
}
void AppearanceDialog::on_button808000_clicked()
{
ui->editColor->setText("#808000");
}
void AppearanceDialog::on_buttonC0C0C0_clicked()
{
ui->editColor->setText("#C0C0C0");
}
void AppearanceDialog::on_button808080_clicked()
{
ui->editColor->setText("#808080");
}
void AppearanceDialog::on_button0000FF_clicked()
{
ui->editColor->setText("#0000FF");
}
void AppearanceDialog::on_button00FF00_clicked()
{
ui->editColor->setText("#00FF00");
}
void AppearanceDialog::on_button00FFFF_clicked()
{
ui->editColor->setText("#00FFFF");
}
void AppearanceDialog::on_buttonFF0000_clicked()
{
ui->editColor->setText("#FF0000");
}
void AppearanceDialog::on_buttonFF00FF_clicked()
{
ui->editColor->setText("#FF00FF");
}
void AppearanceDialog::on_buttonFFFF00_clicked()
{
ui->editColor->setText("#FFFF00");
}
void AppearanceDialog::on_buttonFFFFFF_clicked()
{
ui->editColor->setText("#FFFBF0");
}
void AppearanceDialog::on_buttonBackground000000_clicked()
{
ui->editBackgroundColor->setText("#000000");
}
void AppearanceDialog::on_buttonBackgroundC0C0C0_clicked()
{
ui->editBackgroundColor->setText("#C0C0C0");
}
void AppearanceDialog::on_buttonBackgroundFFFFFF_clicked()
{
ui->editBackgroundColor->setText("#FFFBF0");
}
void AppearanceDialog::on_buttonBackground00FFFF_clicked()
{
ui->editBackgroundColor->setText("#00FFFF");
}
void AppearanceDialog::on_buttonBackground00FF00_clicked()
{
ui->editBackgroundColor->setText("#00FF00");
}
void AppearanceDialog::on_buttonBackgroundFF0000_clicked()
{
ui->editBackgroundColor->setText("#FF0000");
}
void AppearanceDialog::on_buttonBackgroundFFFF00_clicked()
{
ui->editBackgroundColor->setText("#FFFF00");
}
void AppearanceDialog::on_buttonBackgroundNone_clicked()
{
ui->editBackgroundColor->setText("#XXXXXX");
}
void AppearanceDialog::on_editBackgroundColor_textChanged(const QString & arg1)
{
QString text = arg1;
if(!arg1.length())
{
ui->editBackgroundColor->setText("#");
text = ui->editBackgroundColor->text();
return;
}
if(arg1.at(0) != '#')
{
ui->editBackgroundColor->setText("#" + arg1);
text = ui->editBackgroundColor->text();
}
QString styleSheet;
QString id = colorInfoList.at(colorInfoIndex).backgroundColorName;
if(text == "#XXXXXX")
{
styleSheet = "border: 2px solid black; background-color: #C0C0C0";
ui->buttonBackgroundColor->setText("X");
if(colorMap->contains(id))
{
(*colorMap)[id] = Qt::transparent;
ui->buttonSave->setEnabled(true);
emit Config()->colorsUpdated();
GuiUpdateAllViews();
}
if(QColor(ui->editColor->text()).isValid())
text = ui->editColor->text();
else
text = "black";
if(ConfigColor(colorInfoList.at(colorInfoIndex).defaultBackgroundColorName).alpha())
ui->exampleText->setStyleSheet(QString("color: %1; background-color: %2").arg(text).arg(ConfigColor(colorInfoList.at(colorInfoIndex).defaultBackgroundColorName).name()));
else
ui->exampleText->setStyleSheet(QString("color: %1").arg(text));
}
else
{
ui->buttonBackgroundColor->setText("");
if(QColor(text).isValid())
{
styleSheet = "border: 2px solid black; background-color: " + text;
if(colorMap->contains(id))
{
(*colorMap)[id] = QColor(text);
ui->buttonSave->setEnabled(true);
emit Config()->colorsUpdated();
GuiUpdateAllViews();
}
}
else
{
styleSheet = "border: 2px solid red; background-color: #FFFFFF";
if(colorMap->contains(id))
ui->buttonSave->setEnabled(false); //we cannot save with an invalid color
}
// Update the styles of example text
if(ui->editBackgroundColor->isEnabled())
{
if(QColor(ui->editColor->text()).isValid())
ui->exampleText->setStyleSheet(QString("color: %1; background-color: %2").arg(ui->editColor->text()).arg(arg1));
else
ui->exampleText->setStyleSheet(QString("color: black; background-color: %1").arg(arg1));
}
else
{
if(QColor(ui->editColor->text()).isValid())
ui->exampleText->setStyleSheet(QString("color: %1").arg(ui->editColor->text()));
else
ui->exampleText->setStyleSheet(QString("color: black"));
}
ui->exampleText->setFont(ConfigFont(colorInfoList.at(colorInfoIndex).defaultFontName));
}
ui->buttonBackgroundColor->setStyleSheet(styleSheet);
}
void AppearanceDialog::on_editColor_textChanged(const QString & arg1)
{
QString text = arg1;
if(!arg1.length())
{
ui->editColor->setText("#");
text = ui->editColor->text();
return;
}
if(arg1.at(0) != '#')
{
ui->editColor->setText("#" + arg1);
text = ui->editColor->text();
}
QString id = colorInfoList.at(colorInfoIndex).colorName;
QString styleSheet;
if(QColor(text).isValid())
{
styleSheet = "border: 2px solid black; background-color: " + text;
if(colorMap->contains(id))
{
(*colorMap)[id] = QColor(text);
ui->buttonSave->setEnabled(true);
emit Config()->colorsUpdated();
GuiUpdateAllViews();
}
// Update the styles of example text
if(QColor(ui->editBackgroundColor->text()).isValid() && ui->editBackgroundColor->isEnabled())
ui->exampleText->setStyleSheet(QString("color: %1; background-color: %2").arg(arg1).arg(ui->editBackgroundColor->text()));
else if((!ui->editBackgroundColor->isEnabled() || ui->editBackgroundColor->text() == "#XXXXXX") && ConfigColor(colorInfoList.at(colorInfoIndex).defaultBackgroundColorName).alpha())
{
//GuiAddLogMessage(colorInfoList.at(colorInfoIndex).defaultBackgroundColorName.toUtf8().constData());
//GuiAddLogMessage(ConfigColor(colorInfoList.at(colorInfoIndex).defaultBackgroundColorName).name().toUtf8().constData());
ui->exampleText->setStyleSheet(QString("color: %1; background-color: %2").arg(ui->editColor->text()).arg(ConfigColor(colorInfoList.at(colorInfoIndex).defaultBackgroundColorName).name()));
}
else
ui->exampleText->setStyleSheet(QString("color: %1").arg(arg1));
ui->exampleText->setFont(ConfigFont(colorInfoList.at(colorInfoIndex).defaultFontName));
}
else
{
styleSheet = "border: 2px solid red; background-color: #FFFFFF";
if(colorMap->contains(id))
ui->buttonSave->setEnabled(false); //we cannot save with an invalid color
}
ui->buttonColor->setStyleSheet(styleSheet);
}
void AppearanceDialog::on_buttonColor_clicked()
{
selectColor(ui->editColor);
}
void AppearanceDialog::on_buttonBackgroundColor_clicked()
{
selectColor(ui->editBackgroundColor);
}
void AppearanceDialog::on_listColorNames_itemSelectionChanged()
{
colorInfoIndex = ui->listColorNames->currentItem()->data(0, Qt::UserRole).toInt();
ColorInfo info = colorInfoList.at(colorInfoIndex);
defaultValueAction->setEnabled(false);
currentSettingAction->setEnabled(false);
ui->buttonSave->setEnabled(false);
ui->groupColor->setEnabled(false);
ui->groupBackgroundColor->setEnabled(false);
if(info.colorName.length())
{
QString id = info.colorName;
if(colorMap->contains(id))
{
ui->groupColor->setEnabled(true);
ui->buttonSave->setEnabled(true);
defaultValueAction->setEnabled(true);
currentSettingAction->setEnabled(true);
ui->editColor->setText(colorToString((*colorMap)[id]));
}
else
ui->editColor->setText("#FFFFFF");
}
else
ui->editColor->setText("#FFFFFF");
if(info.backgroundColorName.length())
{
QString id = info.backgroundColorName;
if(colorMap->contains(id))
{
ui->groupBackgroundColor->setEnabled(true);
ui->buttonSave->setEnabled(true);
defaultValueAction->setEnabled(true);
currentSettingAction->setEnabled(true);
ui->editBackgroundColor->setText(colorToString((*colorMap)[id]));
}
else
ui->editBackgroundColor->setText("#FFFFFF");
}
else
ui->editBackgroundColor->setText("#FFFFFF");
}
void AppearanceDialog::on_buttonSave_clicked()
{
Config()->writeColors();
Config()->writeFonts();
GuiUpdateAllViews();
BridgeSettingFlush();
GuiAddStatusBarMessage(tr("Settings saved!\n").toUtf8().constData());
}
void AppearanceDialog::defaultValueSlot()
{
ColorInfo info = colorInfoList.at(colorInfoIndex);
if(info.colorName.length())
{
QString id = info.colorName;
if(Config()->defaultColors.contains(id))
{
ui->editColor->setText(colorToString(Config()->defaultColors[id]));
}
}
if(info.backgroundColorName.length())
{
QString id = info.backgroundColorName;
if(Config()->defaultColors.contains(id))
{
ui->editBackgroundColor->setText(colorToString(Config()->defaultColors[id]));
}
}
}
void AppearanceDialog::currentSettingSlot()
{
ColorInfo info = colorInfoList.at(colorInfoIndex);
if(info.colorName.length())
{
QString id = info.colorName;
if(colorBackupMap.contains(id))
{
ui->editColor->setText(colorToString(colorBackupMap[id]));
}
}
if(info.backgroundColorName.length())
{
QString id = info.backgroundColorName;
if(colorBackupMap.contains(id))
{
ui->editBackgroundColor->setText(colorToString(colorBackupMap[id]));
}
}
}
void AppearanceDialog::colorInfoListCategory(QString categoryName, const QString & currentBackgroundColorName, const QString & currentFontName)
{
// Remove the (now) redundant colon
while(categoryName[categoryName.length() - 1] == ':')
categoryName.resize(categoryName.length() - 1);
currentCategory = new QTreeWidgetItem(QList<QString>({ categoryName }));
this->currentBackgroundColorName = currentBackgroundColorName;
this->currentFontName = currentFontName;
ui->listColorNames->addTopLevelItem(currentCategory);
}
void AppearanceDialog::colorInfoListAppend(QString propertyName, QString colorName, QString backgroundColorName)
{
ColorInfo info;
info.propertyName = propertyName;
info.colorName = colorName;
info.backgroundColorName = backgroundColorName;
info.defaultBackgroundColorName = currentBackgroundColorName;
info.defaultFontName = currentFontName;
colorInfoList.append(info);
auto item = new QTreeWidgetItem(currentCategory, QList<QString>({ propertyName }));
item->setData(0, Qt::UserRole, QVariant(colorInfoIndex));
currentCategory->addChild(item);
colorInfoIndex++;
}
void AppearanceDialog::colorInfoListInit()
{
//clear list
colorInfoIndex = 1;
colorInfoList.clear();
colorInfoList.append(ColorInfo({"", "", "", "AbstractTableViewBackgroundColor", "AbstractTableView"})); // default, not editable
//list entries
// Guide lines for entry order:
// 1. Most visual and common first
// So mostly that'll be "Background" (most visual)
// followed by "Selection" and "Text" (most common)
// 2. others are sorted by read direction (Top to down / left to right)
// Example: "Header Text", "Addresses", "Text",...
//
colorInfoListCategory(tr("General Tables:"), "AbstractTableViewBackgroundColor", "AbstractTableView");
colorInfoListAppend(tr("Background"), "AbstractTableViewBackgroundColor", "");
colorInfoListAppend(tr("Selection"), "AbstractTableViewSelectionColor", "");
colorInfoListAppend(tr("Header Text"), "AbstractTableViewHeaderTextColor", "");
colorInfoListAppend(tr("Text"), "AbstractTableViewTextColor", "");
colorInfoListAppend(tr("Separators"), "AbstractTableViewSeparatorColor", "");
colorInfoListCategory(tr("Disassembly:"), "DisassemblyBackgroundColor", "Disassembly");
colorInfoListAppend(tr("Background"), "DisassemblyBackgroundColor", "");
colorInfoListAppend(tr("Selection"), "DisassemblySelectionColor", "");
colorInfoListAppend(ArchValue(tr("EIP"), tr("RIP")), "DisassemblyCipColor", "DisassemblyCipBackgroundColor");
colorInfoListAppend(tr("Addresses"), "DisassemblyAddressColor", "DisassemblyAddressBackgroundColor");
colorInfoListAppend(tr("Selected Addresses"), "DisassemblySelectedAddressColor", "DisassemblySelectedAddressBackgroundColor");
colorInfoListAppend(tr("Breakpoints"), "DisassemblyBreakpointColor", "DisassemblyBreakpointBackgroundColor");
colorInfoListAppend(tr("Hardware Breakpoints"), "DisassemblyHardwareBreakpointColor", "DisassemblyHardwareBreakpointBackgroundColor");
colorInfoListAppend(tr("Labels"), "DisassemblyLabelColor", "DisassemblyLabelBackgroundColor");
colorInfoListAppend(tr("Bytes"), "DisassemblyBytesColor", "DisassemblyBytesBackgroundColor");
colorInfoListAppend(tr("Modified Bytes"), "DisassemblyModifiedBytesColor", "DisassemblyModifiedBytesBackgroundColor");
colorInfoListAppend(tr("Restored Bytes"), "DisassemblyRestoredBytesColor", "DisassemblyRestoredBytesBackgroundColor");
colorInfoListAppend(tr("Bookmarks"), "DisassemblyBookmarkColor", "DisassemblyBookmarkBackgroundColor");
colorInfoListAppend(tr("Comments"), "DisassemblyCommentColor", "DisassemblyCommentBackgroundColor");
colorInfoListAppend(tr("Automatic Comments"), "DisassemblyAutoCommentColor", "DisassemblyAutoCommentBackgroundColor");
colorInfoListAppend(tr("Mnemonic Brief Comments"), "DisassemblyMnemonicBriefColor", "DisassemblyMnemonicBriefBackgroundColor");
colorInfoListAppend(tr("Relocation underline"), "DisassemblyRelocationUnderlineColor", "");
colorInfoListAppend(tr("Conditional Jump Lines (jump)"), "DisassemblyConditionalJumpLineTrueColor", "");
colorInfoListAppend(tr("Conditional Jump Lines (no jump)"), "DisassemblyConditionalJumpLineFalseColor", "");
colorInfoListAppend(tr("Unconditional Jump Lines"), "DisassemblyUnconditionalJumpLineColor", "");
colorInfoListAppend(tr("Traced line"), "DisassemblyTracedBackgroundColor", "");
colorInfoListAppend(tr("Function Lines"), "DisassemblyFunctionColor", "");
colorInfoListAppend(tr("Loop Lines"), "DisassemblyLoopColor", "");
colorInfoListCategory(tr("SideBar:"), "SideBarBackgroundColor", "Disassembly");
colorInfoListAppend(tr("Background"), "SideBarBackgroundColor", "");
colorInfoListAppend(tr("Register Labels"), "SideBarCipLabelColor", "SideBarCipLabelBackgroundColor");
colorInfoListAppend(tr("Conditional Jump Lines (jump)"), "SideBarConditionalJumpLineTrueColor", "");
colorInfoListAppend(tr("Conditional Jump Backwards Lines (jump)"), "SideBarConditionalJumpLineTrueBackwardsColor", "");
colorInfoListAppend(tr("Conditional Jump Lines (no jump)"), "SideBarConditionalJumpLineFalseColor", "");
colorInfoListAppend(tr("Conditional Jump Backwards Lines (no jump)"), "SideBarConditionalJumpLineFalseBackwardsColor", "");
colorInfoListAppend(tr("Unconditional Jump Lines (jump)"), "SideBarUnconditionalJumpLineTrueColor", "");
colorInfoListAppend(tr("Unconditional Jump Backwards Lines (jump)"), "SideBarUnconditionalJumpLineTrueBackwardsColor", "");
colorInfoListAppend(tr("Unconditional Jump Lines (no jump)"), "SideBarUnconditionalJumpLineFalseColor", "");
colorInfoListAppend(tr("Unconditional Jump Backwards Lines (no jump)"), "SideBarUnconditionalJumpLineFalseBackwardsColor", "");
colorInfoListAppend(tr("Code Folding Checkbox Color"), "SideBarCheckBoxForeColor", "SideBarCheckBoxBackColor");
colorInfoListAppend(tr("Bullets"), "SideBarBulletColor", "");
colorInfoListAppend(tr("Breakpoint bullets"), "SideBarBulletBreakpointColor", "");
colorInfoListAppend(tr("Disabled Breakpoint bullets"), "SideBarBulletDisabledBreakpointColor", "");
colorInfoListAppend(tr("Bookmark bullets"), "SideBarBulletBookmarkColor", "");
colorInfoListCategory(tr("Registers:"), "RegistersBackgroundColor", "Registers");
colorInfoListAppend(tr("Background"), "RegistersBackgroundColor", "");
colorInfoListAppend(tr("Selection"), "RegistersSelectionColor", "");
colorInfoListAppend(tr("Register Names"), "RegistersLabelColor", "");
colorInfoListAppend(tr("Argument Register Names"), "RegistersArgumentLabelColor", "");
colorInfoListAppend(tr("Text"), "RegistersColor", "");
colorInfoListAppend(tr("Modified Registers"), "RegistersModifiedColor", "");
colorInfoListAppend(tr("Highlight Read"), "RegistersHighlightReadColor", "");
colorInfoListAppend(tr("Highlight Write"), "RegistersHighlightWriteColor", "");
colorInfoListAppend(tr("Highlight Read+Write"), "RegistersHighlightReadWriteColor", "");
colorInfoListAppend(tr("Extra Information"), "RegistersExtraInfoColor", "");
colorInfoListCategory(tr("Instructions:"), "DisassemblyBackgroundColor", "Disassembly");
colorInfoListAppend(tr("Mnemonics"), "InstructionMnemonicColor", "InstructionMnemonicBackgroundColor");
colorInfoListAppend(tr("Push/Pops"), "InstructionPushPopColor", "InstructionPushPopBackgroundColor");
colorInfoListAppend(tr("Calls"), "InstructionCallColor", "InstructionCallBackgroundColor");
colorInfoListAppend(tr("Returns"), "InstructionRetColor", "InstructionRetBackgroundColor");
colorInfoListAppend(tr("Conditional Jumps"), "InstructionConditionalJumpColor", "InstructionConditionalJumpBackgroundColor");
colorInfoListAppend(tr("Unconditional Jumps"), "InstructionUnconditionalJumpColor", "InstructionUnconditionalJumpBackgroundColor");
colorInfoListAppend(tr("NOPs"), "InstructionNopColor", "InstructionNopBackgroundColor");
colorInfoListAppend(tr("FAR"), "InstructionFarColor", "InstructionFarBackgroundColor");
colorInfoListAppend(tr("INT3s"), "InstructionInt3Color", "InstructionInt3BackgroundColor");
colorInfoListAppend(tr("Unusual Instructions"), "InstructionUnusualColor", "InstructionUnusualBackgroundColor");
colorInfoListAppend(tr("Prefixes"), "InstructionPrefixColor", "InstructionPrefixBackgroundColor");
colorInfoListAppend(tr("Addresses"), "InstructionAddressColor", "InstructionAddressBackgroundColor");
colorInfoListAppend(tr("Values"), "InstructionValueColor", "InstructionValueBackgroundColor");
colorInfoListAppend(tr("Commas"), "InstructionCommaColor", "InstructionCommaBackgroundColor");
colorInfoListAppend(tr("General Registers"), "InstructionGeneralRegisterColor", "InstructionGeneralRegisterBackgroundColor");
colorInfoListAppend(tr("FPU Registers"), "InstructionFpuRegisterColor", "InstructionFpuRegisterBackgroundColor");
colorInfoListAppend(tr("MMX Registers"), "InstructionMmxRegisterColor", "InstructionMmxRegisterBackgroundColor");
colorInfoListAppend(tr("XMM Registers"), "InstructionXmmRegisterColor", "InstructionXmmRegisterBackgroundColor");
colorInfoListAppend(tr("YMM Registers"), "InstructionYmmRegisterColor", "InstructionYmmRegisterBackgroundColor");
colorInfoListAppend(tr("ZMM Registers"), "InstructionZmmRegisterColor", "InstructionZmmRegisterBackgroundColor");
colorInfoListAppend(tr("Memory Sizes"), "InstructionMemorySizeColor", "InstructionMemorySizeBackgroundColor");
colorInfoListAppend(tr("Memory Segments"), "InstructionMemorySegmentColor", "InstructionMemorySegmentBackgroundColor");
colorInfoListAppend(tr("Text"), "InstructionUncategorizedColor", "InstructionUncategorizedBackgroundColor");
colorInfoListAppend(tr("Memory Brackets"), "InstructionMemoryBracketsColor", "InstructionMemoryBracketsBackgroundColor");
colorInfoListAppend(tr("Memory Stack Brackets"), "InstructionMemoryStackBracketsColor", "InstructionMemoryStackBracketsBackgroundColor");
colorInfoListAppend(tr("Memory Base Registers"), "InstructionMemoryBaseRegisterColor", "InstructionMemoryBaseRegisterBackgroundColor");
colorInfoListAppend(tr("Memory Index Registers"), "InstructionMemoryIndexRegisterColor", "InstructionMemoryIndexRegisterBackgroundColor");
colorInfoListAppend(tr("Memory Scales"), "InstructionMemoryScaleColor", "InstructionMemoryScaleBackgroundColor");
colorInfoListAppend(tr("Memory Operators (+/-/*)"), "InstructionMemoryOperatorColor", "InstructionMemoryOperatorBackgroundColor");
colorInfoListAppend(tr("Highlighting"), "InstructionHighlightColor", "InstructionHighlightBackgroundColor");
colorInfoListCategory(tr("HexDump:"), "HexDumpBackgroundColor", "HexDump");
colorInfoListAppend(tr("Background"), "HexDumpBackgroundColor", "");
colorInfoListAppend(tr("Selection"), "HexDumpSelectionColor", "");
colorInfoListAppend(tr("Addresses"), "HexDumpAddressColor", "HexDumpAddressBackgroundColor");
colorInfoListAppend(tr("Labels"), "HexDumpLabelColor", "HexDumpLabelBackgroundColor");
colorInfoListAppend(tr("Text"), "HexDumpTextColor", "");
colorInfoListAppend(tr("Modified Bytes"), "HexDumpModifiedBytesColor", "HexDumpModifiedBytesBackgroundColor");
colorInfoListAppend(tr("Restored Bytes"), "HexDumpRestoredBytesColor", "HexDumpRestoredBytesBackgroundColor");
colorInfoListAppend(tr("0x00 Bytes"), "HexDumpByte00Color", "HexDumpByte00BackgroundColor");
colorInfoListAppend(tr("0x7F Bytes"), "HexDumpByte7FColor", "HexDumpByte7FBackgroundColor");
colorInfoListAppend(tr("0xFF Bytes"), "HexDumpByteFFColor", "HexDumpByteFFBackgroundColor");
colorInfoListAppend(tr("IsPrint Bytes"), "HexDumpByteIsPrintColor", "HexDumpByteIsPrintBackgroundColor");
colorInfoListAppend(tr("User Code Pointer Highlight Color"), "HexDumpUserModuleCodePointerHighlightColor", "");
colorInfoListAppend(tr("User Data Pointer Highlight Color"), "HexDumpUserModuleDataPointerHighlightColor", "");
colorInfoListAppend(tr("System Code Pointer Highlight Color"), "HexDumpSystemModuleCodePointerHighlightColor", "");
colorInfoListAppend(tr("System Data Pointer Highlight Color"), "HexDumpSystemModuleDataPointerHighlightColor", "");
colorInfoListAppend(tr("Unknown Code Pointer Highlight Color"), "HexDumpUnknownCodePointerHighlightColor", "");
colorInfoListAppend(tr("Unknown Data Pointer Highlight Color"), "HexDumpUnknownDataPointerHighlightColor", "");
colorInfoListCategory(tr("Stack:"), "StackBackgroundColor", "Stack");
colorInfoListAppend(tr("Background"), "StackBackgroundColor", "");
colorInfoListAppend(ArchValue(tr("ESP"), tr("RSP")), "StackCspColor", "StackCspBackgroundColor");
colorInfoListAppend(tr("Addresses"), "StackAddressColor", "StackAddressBackgroundColor");
colorInfoListAppend(tr("Selected Addresses"), "StackSelectedAddressColor", "StackSelectedAddressBackgroundColor");
colorInfoListAppend(tr("Labels"), "StackLabelColor", "StackLabelBackgroundColor");
colorInfoListAppend(tr("User Stack Frame Line"), "StackFrameColor", "");
colorInfoListAppend(tr("System Stack Frame Line"), "StackFrameSystemColor", "");
colorInfoListAppend(tr("Text"), "StackTextColor", "");
colorInfoListAppend(tr("Inactive Text"), "StackInactiveTextColor", "");
colorInfoListAppend(tr("Selection"), "StackSelectionColor", "");
colorInfoListAppend(tr("Return To Comment"), "StackReturnToColor", "");
colorInfoListAppend(tr("SEH Chain Comment"), "StackSEHChainColor", "");
colorInfoListCategory(tr("HexEdit:"), "HexEditBackgroundColor", "HexEdit");
colorInfoListAppend(tr("Background"), "HexEditBackgroundColor", "");
colorInfoListAppend(tr("Selection"), "HexEditSelectionColor", "");
colorInfoListAppend(tr("Text"), "HexEditTextColor", "");
colorInfoListAppend(tr("Wildcards"), "HexEditWildcardColor", "");
colorInfoListCategory(tr("Graph:"), "GraphBackgroundColor", "Disassembly");
colorInfoListAppend(tr("Background"), "GraphBackgroundColor", "");
colorInfoListAppend(ArchValue(tr("EIP"), tr("RIP")), "GraphCipColor", "");
colorInfoListAppend(tr("Breakpoint"), "GraphBreakpointColor", "");
colorInfoListAppend(tr("Disabled Breakpoint"), "GraphDisabledBreakpointColor", "");
colorInfoListAppend(tr("Node"), "GraphNodeColor", "GraphNodeBackgroundColor");
colorInfoListAppend(tr("Current node shadow"), "GraphCurrentShadowColor", "");
colorInfoListAppend(tr("Terminal node shadow"), "GraphRetShadowColor", "");
colorInfoListAppend(tr("Indirect call shadow"), "GraphIndirectcallShadowColor", "");
colorInfoListAppend(tr("Unconditional branch line"), "GraphJmpColor", "");
colorInfoListAppend(tr("True branch line"), "GraphBrtrueColor", "");
colorInfoListAppend(tr("False branch line"), "GraphBrfalseColor", "");
colorInfoListCategory(tr("Log:"), "LogBackgroundColor", "Log");
colorInfoListAppend(tr("Log"), "LogColor", "LogBackgroundColor");
colorInfoListAppend(tr("Log Link Color") + "*", "LogLinkColor", "LogLinkBackgroundColor");
colorInfoListCategory(tr("Other:"), "AbstractTableViewBackgroundColor", "AbstractTableView");
colorInfoListAppend(tr("Background Flicker Color"), "BackgroundFlickerColor", "");
colorInfoListAppend(tr("Search Highlight Color"), "SearchListViewHighlightColor", "SearchListViewHighlightBackgroundColor");
colorInfoListAppend(tr("Patch located in relocation region"), "PatchRelocatedByteHighlightColor", "");
colorInfoListAppend(tr("Current Thread"), "ThreadCurrentColor", "ThreadCurrentBackgroundColor");
colorInfoListAppend(tr("Watch (When Watchdog is Triggered)"), "WatchTriggeredColor", "WatchTriggeredBackgroundColor");
colorInfoListAppend(tr("Memory Map Breakpoint"), "MemoryMapBreakpointColor", "MemoryMapBreakpointBackgroundColor");
colorInfoListAppend(tr("Memory Map %1").arg(ArchValue(tr("EIP"), tr("RIP"))), "MemoryMapCipColor", "MemoryMapCipBackgroundColor");
colorInfoListAppend(tr("Memory Map Section Text"), "MemoryMapSectionTextColor", "");
colorInfoListAppend(tr("Struct text"), "StructTextColor", "");
colorInfoListAppend(tr("Struct primary background"), "StructBackgroundColor", "");
colorInfoListAppend(tr("Struct secondary background"), "StructAlternateBackgroundColor", "");
colorInfoListAppend(tr("Breakpoint Summary Parentheses"), "BreakpointSummaryParenColor", "");
colorInfoListAppend(tr("Breakpoint Summary Keywords"), "BreakpointSummaryKeywordColor", "");
colorInfoListAppend(tr("Breakpoint Summary Strings"), "BreakpointSummaryStringColor", "");
colorInfoListAppend(tr("Symbol User Module Text"), "SymbolUserTextColor", "");
colorInfoListAppend(tr("Symbol System Module Text"), "SymbolSystemTextColor", "");
colorInfoListAppend(tr("Symbol Unloaded Text"), "SymbolUnloadedTextColor", "");
colorInfoListAppend(tr("Symbol Loading Text"), "SymbolLoadingTextColor", "");
colorInfoListAppend(tr("Symbol Loaded Text"), "SymbolLoadedTextColor", "");
colorInfoListAppend(tr("Link color"), "LinkColor", "");
colorInfoIndex = 0;
//dev helper
const QMap<QString, QColor>* Colors = &Config()->defaultColors;
QString notFound;
for(int i = 0; i < Colors->size(); i++)
{
QString id = Colors->keys().at(i);
bool bFound = false;
for(int j = 0; j < colorInfoList.size(); j++)
{
if(colorInfoList.at(j).colorName == id || colorInfoList.at(j).backgroundColorName == id)
{
bFound = true;
break;
}
}
if(!bFound) //color not found in info list
notFound += id + "\n";
}
if(notFound.length())
SimpleWarningBox(this, tr("NOT FOUND IN CONFIG!"), notFound);
//setup context menu
ui->listColorNames->setContextMenuPolicy(Qt::ActionsContextMenu);
defaultValueAction = new QAction(tr("&Default Value"), this);
defaultValueAction->setEnabled(false);
connect(defaultValueAction, SIGNAL(triggered()), this, SLOT(defaultValueSlot()));
currentSettingAction = new QAction(tr("&Current Setting"), this);
currentSettingAction->setEnabled(false);
connect(currentSettingAction, SIGNAL(triggered()), this, SLOT(currentSettingSlot()));
ui->listColorNames->addAction(defaultValueAction);
ui->listColorNames->addAction(currentSettingAction);
}
static void fontInitHelper(const QFont & font, QFontComboBox & fontSelector, QComboBox & style, QComboBox & sizes)
{
fontSelector.setCurrentFont(QFont(font.family()));
if(font.bold() && font.italic())
style.setCurrentIndex(3);
else if(font.italic())
style.setCurrentIndex(2);
else if(font.bold())
style.setCurrentIndex(1);
else
style.setCurrentIndex(0);
int index = sizes.findText(QString("%1").arg(font.pointSize()));
if(index != -1)
sizes.setCurrentIndex(index);
}
void AppearanceDialog::fontInit()
{
isInit = true;
//AbstractTableView
fontInitHelper(fontMap->find("AbstractTableView").value(), *ui->fontAbstractTables, *ui->fontAbstractTablesStyle, *ui->fontAbstractTablesSize);
//Disassembly
fontInitHelper(fontMap->find("Disassembly").value(), *ui->fontDisassembly, *ui->fontDisassemblyStyle, *ui->fontDisassemblySize);
//HexDump
fontInitHelper(fontMap->find("HexDump").value(), *ui->fontHexDump, *ui->fontHexDumpStyle, *ui->fontHexDumpSize);
//Stack
fontInitHelper(fontMap->find("Stack").value(), *ui->fontStack, *ui->fontStackStyle, *ui->fontStackSize);
//Registers
fontInitHelper(fontMap->find("Registers").value(), *ui->fontRegisters, *ui->fontRegistersStyle, *ui->fontRegistersSize);
//HexEdit
fontInitHelper(fontMap->find("HexEdit").value(), *ui->fontHexEdit, *ui->fontHexEditStyle, *ui->fontHexEditSize);
//Log
fontInitHelper(fontMap->find("Log").value(), *ui->fontLog, *ui->fontLogStyle, *ui->fontLogSize);
//Application
ui->labelApplicationFont->setText(fontMap->find("Application").value().family());
isInit = false;
}
void AppearanceDialog::selectColor(QLineEdit* lineEdit, QColorDialog::ColorDialogOptions options)
{
colorLineEdit = lineEdit;
auto oldText = lineEdit->text();
QColor initialColor;
if(oldText.toUpper() == "#XXXXXX")
initialColor = Qt::black; //transparent will set the alpha channel, which users will forget
else
initialColor = QColor(oldText);
QColorDialog dialog(initialColor, this);
dialog.setWindowTitle(tr("Select Color"));
dialog.setOptions(options);
connect(&dialog, &QColorDialog::currentColorChanged, this, &AppearanceDialog::colorSelectionChangedSlot);
duint customColorCount = 0;
BridgeSettingGetUint("Colors", "CustomColorCount", &customColorCount);
if(customColorCount > 0)
{
for(duint i = 0; i < customColorCount; i++)
{
char customColorText[MAX_SETTING_SIZE] = "";
if(BridgeSettingGet("Colors", QString("CustomColor%1").arg(i).toUtf8().constData(), customColorText))
{
QColor customColor;
if(strcmp(customColorText, "#XXXXXX") == 0)
customColor = Qt::transparent;
else
customColor = QColor(customColorText);
dialog.setCustomColor(i, customColor);
}
}
}
auto result = dialog.exec();
for(int i = 0; i < dialog.customCount(); i++)
{
QColor customColor = dialog.customColor(i);
QString colorName = customColor.name().toUpper();
if(!customColor.alpha())
colorName = "#XXXXXX";
BridgeSettingSet("Colors", QString("CustomColor%1").arg(i).toUtf8().constData(), colorName.toUtf8().constData());
}
BridgeSettingSetUint("Colors", "CustomColorCount", dialog.customCount());
colorLineEdit = nullptr;
if(result == QDialog::Accepted)
{
lineEdit->setText(colorToString(dialog.selectedColor()));
}
else
{
lineEdit->setText(oldText);
}
}
QString AppearanceDialog::colorToString(const QColor & color)
{
if(!color.alpha())
return "#XXXXXX";
return color.name().toUpper();
}
void AppearanceDialog::on_fontAbstractTables_currentFontChanged(const QFont & f)
{
QString id = "AbstractTableView";
QFont font = fontMap->find(id).value();
font.setFamily(f.family());
(*fontMap)[id] = font;
if(isInit)
return;
emit Config()->fontsUpdated();
GuiUpdateAllViews();
}
void AppearanceDialog::on_fontAbstractTablesStyle_currentIndexChanged(int index)
{
QString id = "AbstractTableView";
QFont font = fontMap->find(id).value();
font.setBold(false);
font.setItalic(false);
font.setKerning(false);
if(index == 1 || index == 3)
font.setBold(true);
if(index == 2 || index == 3)
font.setItalic(true);
(*fontMap)[id] = font;
if(isInit)
return;
emit Config()->fontsUpdated();
GuiUpdateAllViews();
}
void AppearanceDialog::on_fontAbstractTablesSize_currentIndexChanged(const QString & arg1)
{
QString id = "AbstractTableView";
QFont font = fontMap->find(id).value();
font.setPointSize(arg1.toInt());
font.setKerning(false);
(*fontMap)[id] = font;
if(isInit)
return;
emit Config()->fontsUpdated();
GuiUpdateAllViews();
}
void AppearanceDialog::on_fontDisassembly_currentFontChanged(const QFont & f)
{
QString id = "Disassembly";
QFont font = fontMap->find(id).value();
font.setFamily(f.family());
font.setKerning(false);
(*fontMap)[id] = font;
if(isInit)
return;
emit Config()->fontsUpdated();
GuiUpdateAllViews();
}
void AppearanceDialog::on_fontDisassemblyStyle_currentIndexChanged(int index)
{
QString id = "Disassembly";
QFont font = fontMap->find(id).value();
font.setBold(false);
font.setItalic(false);
font.setKerning(false);
if(index == 1 || index == 3)
font.setBold(true);
if(index == 2 || index == 3)
font.setItalic(true);
(*fontMap)[id] = font;
if(isInit)
return;
emit Config()->fontsUpdated();
GuiUpdateAllViews();
}
void AppearanceDialog::on_fontDisassemblySize_currentIndexChanged(const QString & arg1)
{
QString id = "Disassembly";
QFont font = fontMap->find(id).value();
font.setPointSize(arg1.toInt());
font.setKerning(false);
(*fontMap)[id] = font;
if(isInit)
return;
emit Config()->fontsUpdated();
GuiUpdateAllViews();
}
void AppearanceDialog::on_fontHexDump_currentFontChanged(const QFont & f)
{
QString id = "HexDump";
QFont font = fontMap->find(id).value();
font.setFamily(f.family());
font.setKerning(false);
(*fontMap)[id] = font;
if(isInit)
return;
emit Config()->fontsUpdated();
GuiUpdateAllViews();
}
void AppearanceDialog::on_fontHexDumpStyle_currentIndexChanged(int index)
{
QString id = "HexDump";
QFont font = fontMap->find(id).value();
font.setBold(false);
font.setItalic(false);
font.setKerning(false);
if(index == 1 || index == 3)
font.setBold(true);
if(index == 2 || index == 3)
font.setItalic(true);
(*fontMap)[id] = font;
if(isInit)
return;
emit Config()->fontsUpdated();
GuiUpdateAllViews();
}
void AppearanceDialog::on_fontHexDumpSize_currentIndexChanged(const QString & arg1)
{
QString id = "HexDump";
QFont font = fontMap->find(id).value();
font.setPointSize(arg1.toInt());
font.setKerning(false);
(*fontMap)[id] = font;
if(isInit)
return;
emit Config()->fontsUpdated();
GuiUpdateAllViews();
}
void AppearanceDialog::on_fontStack_currentFontChanged(const QFont & f)
{
QString id = "Stack";
QFont font = fontMap->find(id).value();
font.setFamily(f.family());
font.setKerning(false);
(*fontMap)[id] = font;
if(isInit)
return;
emit Config()->fontsUpdated();
GuiUpdateAllViews();
}
void AppearanceDialog::on_fontStackStyle_currentIndexChanged(int index)
{
QString id = "Stack";
QFont font = fontMap->find(id).value();
font.setBold(false);
font.setItalic(false);
font.setKerning(false);
if(index == 1 || index == 3)
font.setBold(true);
if(index == 2 || index == 3)
font.setItalic(true);
(*fontMap)[id] = font;
if(isInit)
return;
emit Config()->fontsUpdated();
GuiUpdateAllViews();
}
void AppearanceDialog::on_fontStackSize_currentIndexChanged(const QString & arg1)
{
QString id = "Stack";
QFont font = fontMap->find(id).value();
font.setPointSize(arg1.toInt());
font.setKerning(false);
(*fontMap)[id] = font;
if(isInit)
return;
emit Config()->fontsUpdated();
GuiUpdateAllViews();
}
void AppearanceDialog::on_fontRegisters_currentFontChanged(const QFont & f)
{
QString id = "Registers";
QFont font = fontMap->find(id).value();
font.setFamily(f.family());
font.setKerning(false);
(*fontMap)[id] = font;
if(isInit)
return;
emit Config()->fontsUpdated();
GuiUpdateAllViews();
}
void AppearanceDialog::on_fontRegistersStyle_currentIndexChanged(int index)
{
QString id = "Registers";
QFont font = fontMap->find(id).value();
font.setBold(false);
font.setItalic(false);
font.setKerning(false);
if(index == 1 || index == 3)
font.setBold(true);
if(index == 2 || index == 3)
font.setItalic(true);
(*fontMap)[id] = font;
if(isInit)
return;
emit Config()->fontsUpdated();
GuiUpdateAllViews();
}
void AppearanceDialog::on_fontRegistersSize_currentIndexChanged(const QString & arg1)
{
QString id = "Registers";
QFont font = fontMap->find(id).value();
font.setPointSize(arg1.toInt());
font.setKerning(false);
(*fontMap)[id] = font;
if(isInit)
return;
emit Config()->fontsUpdated();
GuiUpdateAllViews();
}
void AppearanceDialog::on_fontHexEdit_currentFontChanged(const QFont & f)
{
QString id = "HexEdit";
QFont font = fontMap->find(id).value();
font.setFamily(f.family());
font.setKerning(false);
(*fontMap)[id] = font;
if(isInit)
return;
emit Config()->fontsUpdated();
GuiUpdateAllViews();
}
void AppearanceDialog::on_fontHexEditStyle_currentIndexChanged(int index)
{
QString id = "HexEdit";
QFont font = fontMap->find(id).value();
font.setBold(false);
font.setItalic(false);
font.setKerning(false);
if(index == 1 || index == 3)
font.setBold(true);
if(index == 2 || index == 3)
font.setItalic(true);
(*fontMap)[id] = font;
if(isInit)
return;
emit Config()->fontsUpdated();
GuiUpdateAllViews();
}
void AppearanceDialog::on_fontHexEditSize_currentIndexChanged(const QString & arg1)
{
QString id = "HexEdit";
QFont font = fontMap->find(id).value();
font.setPointSize(arg1.toInt());
font.setKerning(false);
(*fontMap)[id] = font;
if(isInit)
return;
emit Config()->fontsUpdated();
GuiUpdateAllViews();
}
void AppearanceDialog::on_fontLog_currentFontChanged(const QFont & f)
{
QString id = "Log";
QFont font = fontMap->find(id).value();
font.setFamily(f.family());
font.setKerning(false);
(*fontMap)[id] = font;
if(isInit)
return;
emit Config()->fontsUpdated();
GuiUpdateAllViews();
}
void AppearanceDialog::on_fontLogStyle_currentIndexChanged(int index)
{
QString id = "Log";
QFont font = fontMap->find(id).value();
font.setBold(false);
font.setItalic(false);
font.setKerning(false);
if(index == 1 || index == 3)
font.setBold(true);
if(index == 2 || index == 3)
font.setItalic(true);
(*fontMap)[id] = font;
if(isInit)
return;
emit Config()->fontsUpdated();
GuiUpdateAllViews();
}
void AppearanceDialog::on_fontLogSize_currentIndexChanged(const QString & arg1)
{
QString id = "Log";
QFont font = fontMap->find(id).value();
font.setPointSize(arg1.toInt());
font.setKerning(false);
(*fontMap)[id] = font;
if(isInit)
return;
emit Config()->fontsUpdated();
GuiUpdateAllViews();
}
void AppearanceDialog::on_buttonApplicationFont_clicked()
{
QString id = "Application";
QFontDialog fontDialog(this);
fontDialog.setCurrentFont(fontMap->find(id).value());
if(fontDialog.exec() != QDialog::Accepted)
return;
(*fontMap)[id] = fontDialog.currentFont();
ui->labelApplicationFont->setText(fontDialog.currentFont().family());
if(isInit)
return;
emit Config()->fontsUpdated();
GuiUpdateAllViews();
}
void AppearanceDialog::on_buttonFontDefaults_clicked()
{
(*fontMap) = Config()->defaultFonts;
isInit = true;
fontInit();
isInit = false;
emit Config()->fontsUpdated();
GuiUpdateAllViews();
}
void AppearanceDialog::rejectedSlot()
{
Config()->Colors = colorBackupMap;
emit Config()->colorsUpdated();
Config()->Fonts = fontBackupMap;
emit Config()->fontsUpdated();
GuiUpdateAllViews();
}
void AppearanceDialog::colorSelectionChangedSlot(QColor color)
{
if(colorLineEdit)
colorLineEdit->setText(colorToString(color));
} |
C/C++ | x64dbg-development/src/gui/Src/Gui/AppearanceDialog.h | #pragma once
#include <QAction>
#include <QDialog>
#include <QMap>
#include <QColorDialog>
#include <QLineEdit>
namespace Ui
{
class AppearanceDialog;
}
class QTreeWidgetItem;
class AppearanceDialog : public QDialog
{
Q_OBJECT
public:
explicit AppearanceDialog(QWidget* parent = 0);
~AppearanceDialog();
private slots:
void on_button000000_clicked();
void on_button000080_clicked();
void on_button008000_clicked();
void on_button008080_clicked();
void on_button800000_clicked();
void on_button800080_clicked();
void on_button808000_clicked();
void on_buttonC0C0C0_clicked();
void on_button808080_clicked();
void on_button0000FF_clicked();
void on_button00FF00_clicked();
void on_button00FFFF_clicked();
void on_buttonFF0000_clicked();
void on_buttonFF00FF_clicked();
void on_buttonFFFF00_clicked();
void on_buttonFFFFFF_clicked();
void on_buttonBackground000000_clicked();
void on_buttonBackgroundC0C0C0_clicked();
void on_buttonBackgroundFFFFFF_clicked();
void on_buttonBackground00FFFF_clicked();
void on_buttonBackground00FF00_clicked();
void on_buttonBackgroundFF0000_clicked();
void on_buttonBackgroundFFFF00_clicked();
void on_buttonBackgroundNone_clicked();
void on_editBackgroundColor_textChanged(const QString & arg1);
void on_editColor_textChanged(const QString & arg1);
void on_buttonColor_clicked();
void on_buttonBackgroundColor_clicked();
void on_buttonSave_clicked();
void on_listColorNames_itemSelectionChanged();
void defaultValueSlot();
void currentSettingSlot();
void on_fontAbstractTables_currentFontChanged(const QFont & f);
void on_fontAbstractTablesStyle_currentIndexChanged(int index);
void on_fontAbstractTablesSize_currentIndexChanged(const QString & arg1);
void on_fontDisassembly_currentFontChanged(const QFont & f);
void on_fontDisassemblyStyle_currentIndexChanged(int index);
void on_fontDisassemblySize_currentIndexChanged(const QString & arg1);
void on_fontHexDump_currentFontChanged(const QFont & f);
void on_fontHexDumpStyle_currentIndexChanged(int index);
void on_fontHexDumpSize_currentIndexChanged(const QString & arg1);
void on_fontStack_currentFontChanged(const QFont & f);
void on_fontStackStyle_currentIndexChanged(int index);
void on_fontStackSize_currentIndexChanged(const QString & arg1);
void on_fontRegisters_currentFontChanged(const QFont & f);
void on_fontRegistersStyle_currentIndexChanged(int index);
void on_fontRegistersSize_currentIndexChanged(const QString & arg1);
void on_fontHexEdit_currentFontChanged(const QFont & f);
void on_fontHexEditStyle_currentIndexChanged(int index);
void on_fontHexEditSize_currentIndexChanged(const QString & arg1);
void on_fontLog_currentFontChanged(const QFont & f);
void on_fontLogStyle_currentIndexChanged(int index);
void on_fontLogSize_currentIndexChanged(const QString & arg1);
void on_buttonApplicationFont_clicked();
void on_buttonFontDefaults_clicked();
void rejectedSlot();
void colorSelectionChangedSlot(QColor color);
private:
Ui::AppearanceDialog* ui;
QLineEdit* colorLineEdit = nullptr;
struct ColorInfo
{
QString propertyName;
QString colorName;
QString backgroundColorName;
QString defaultBackgroundColorName;
QString defaultFontName;
};
QList<ColorInfo> colorInfoList;
int colorInfoIndex;
QMap<QString, QColor>* colorMap;
QMap<QString, QColor> colorBackupMap;
QMap<QString, QFont>* fontMap;
QMap<QString, QFont> fontBackupMap;
QAction* defaultValueAction;
QAction* currentSettingAction;
QTreeWidgetItem* currentCategory;
QString currentBackgroundColorName;
QString currentFontName;
bool isInit;
void colorInfoListCategory(QString categoryName, const QString & currentBackgroundColorName, const QString & currentFontName);
void colorInfoListAppend(QString propertyName, QString colorName, QString backgroundColorName);
void colorInfoListInit();
void fontInit();
void selectColor(QLineEdit* lineEdit, QColorDialog::ColorDialogOptions options = QColorDialog::ColorDialogOptions());
static QString colorToString(const QColor & color);
}; |
User Interface | x64dbg-development/src/gui/Src/Gui/AppearanceDialog.ui | <?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>AppearanceDialog</class>
<widget class="QDialog" name="AppearanceDialog">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>522</width>
<height>429</height>
</rect>
</property>
<property name="windowTitle">
<string>Appearance</string>
</property>
<property name="windowIcon">
<iconset theme="color-swatches" resource="../../resource.qrc">
<normaloff>:/Default/icons/color-swatches.png</normaloff>:/Default/icons/color-swatches.png</iconset>
</property>
<property name="styleSheet">
<string notr="true"/>
</property>
<layout class="QVBoxLayout" name="verticalLayout_3">
<item>
<widget class="QTabWidget" name="tabWidget">
<property name="currentIndex">
<number>0</number>
</property>
<widget class="QWidget" name="tabColors">
<attribute name="title">
<string>Colors</string>
</attribute>
<layout class="QGridLayout" name="gridLayout_3">
<item row="0" column="0" rowspan="3">
<widget class="QGroupBox" name="groupProperties">
<property name="title">
<string>Properties</string>
</property>
<property name="checkable">
<bool>false</bool>
</property>
<layout class="QVBoxLayout" name="verticalLayout_2">
<item>
<widget class="QTreeWidget" name="listColorNames">
<attribute name="headerVisible">
<bool>false</bool>
</attribute>
<column>
<property name="text">
<string notr="true">1</string>
</property>
</column>
</widget>
</item>
</layout>
</widget>
</item>
<item row="0" column="1">
<widget class="QGroupBox" name="groupColor">
<property name="title">
<string>Color</string>
</property>
<property name="checkable">
<bool>false</bool>
</property>
<layout class="QGridLayout" name="gridLayout_2">
<item row="0" column="0" colspan="2">
<layout class="QGridLayout" name="gridForegroundColors">
<property name="spacing">
<number>0</number>
</property>
<item row="0" column="0">
<widget class="QPushButton" name="button000000">
<property name="sizePolicy">
<sizepolicy hsizetype="MinimumExpanding" vsizetype="MinimumExpanding">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="styleSheet">
<string notr="true">background-color: #000000;
border: solid black;
border-width: 2px 1px 2px 2px;</string>
</property>
<property name="text">
<string/>
</property>
</widget>
</item>
<item row="0" column="1">
<widget class="QPushButton" name="button000080">
<property name="sizePolicy">
<sizepolicy hsizetype="MinimumExpanding" vsizetype="MinimumExpanding">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="styleSheet">
<string notr="true">background-color: #000080;
border: solid black;
border-width: 2px 1px 2px 1px;</string>
</property>
<property name="text">
<string/>
</property>
</widget>
</item>
<item row="0" column="2">
<widget class="QPushButton" name="button008000">
<property name="sizePolicy">
<sizepolicy hsizetype="MinimumExpanding" vsizetype="MinimumExpanding">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="styleSheet">
<string notr="true">background-color: #008000;
border: solid black;
border-width: 2px 1px 2px 1px;</string>
</property>
<property name="text">
<string/>
</property>
</widget>
</item>
<item row="0" column="3">
<widget class="QPushButton" name="button008080">
<property name="sizePolicy">
<sizepolicy hsizetype="MinimumExpanding" vsizetype="MinimumExpanding">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="styleSheet">
<string notr="true">background-color: #008080;
border: solid black;
border-width: 2px 2px 2px 1px;</string>
</property>
<property name="text">
<string/>
</property>
</widget>
</item>
<item row="1" column="0">
<widget class="QPushButton" name="button800000">
<property name="sizePolicy">
<sizepolicy hsizetype="MinimumExpanding" vsizetype="MinimumExpanding">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="styleSheet">
<string notr="true">background-color: #800000;
border: solid black;
border-width: 1px 1px 2px 2px;</string>
</property>
<property name="text">
<string/>
</property>
</widget>
</item>
<item row="1" column="1">
<widget class="QPushButton" name="button800080">
<property name="sizePolicy">
<sizepolicy hsizetype="MinimumExpanding" vsizetype="MinimumExpanding">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="styleSheet">
<string notr="true">background-color: #800080;
border: solid black;
border-width: 1px 1px 2px 1px;</string>
</property>
<property name="text">
<string/>
</property>
</widget>
</item>
<item row="1" column="2">
<widget class="QPushButton" name="button808000">
<property name="sizePolicy">
<sizepolicy hsizetype="MinimumExpanding" vsizetype="MinimumExpanding">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="styleSheet">
<string notr="true">background-color: #808000;
border: solid black;
border-width: 1px 1px 2px 1px;</string>
</property>
<property name="text">
<string/>
</property>
</widget>
</item>
<item row="1" column="3">
<widget class="QPushButton" name="buttonC0C0C0">
<property name="sizePolicy">
<sizepolicy hsizetype="MinimumExpanding" vsizetype="MinimumExpanding">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="styleSheet">
<string notr="true">background-color: #C0C0C0;
border: solid black;
border-width: 1px 2px 2px 1px;</string>
</property>
<property name="text">
<string/>
</property>
</widget>
</item>
<item row="2" column="0">
<widget class="QPushButton" name="button808080">
<property name="sizePolicy">
<sizepolicy hsizetype="MinimumExpanding" vsizetype="MinimumExpanding">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="styleSheet">
<string notr="true">background-color: #808080;
border: solid black;
border-width: 1px 1px 2px 2px;</string>
</property>
<property name="text">
<string/>
</property>
</widget>
</item>
<item row="2" column="1">
<widget class="QPushButton" name="button0000FF">
<property name="sizePolicy">
<sizepolicy hsizetype="MinimumExpanding" vsizetype="MinimumExpanding">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="styleSheet">
<string notr="true">background-color: #0000FF;
border: solid black;
border-width: 1px 1px 2px 1px;</string>
</property>
<property name="text">
<string/>
</property>
</widget>
</item>
<item row="2" column="2">
<widget class="QPushButton" name="button00FF00">
<property name="sizePolicy">
<sizepolicy hsizetype="MinimumExpanding" vsizetype="MinimumExpanding">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="styleSheet">
<string notr="true">background-color: #00FF00;
border: solid black;
border-width: 1px 1px 2px 1px;</string>
</property>
<property name="text">
<string/>
</property>
</widget>
</item>
<item row="2" column="3">
<widget class="QPushButton" name="button00FFFF">
<property name="sizePolicy">
<sizepolicy hsizetype="MinimumExpanding" vsizetype="MinimumExpanding">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="styleSheet">
<string notr="true">background-color: #00FFFF;
border: solid black;
border-width: 1px 2px 2px 1px;</string>
</property>
<property name="text">
<string/>
</property>
</widget>
</item>
<item row="3" column="0">
<widget class="QPushButton" name="buttonFF0000">
<property name="sizePolicy">
<sizepolicy hsizetype="MinimumExpanding" vsizetype="MinimumExpanding">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="styleSheet">
<string notr="true">background-color : #FF0000;
border: solid black;
border-width: 1px 1px 2px 2px;</string>
</property>
<property name="text">
<string/>
</property>
</widget>
</item>
<item row="3" column="1">
<widget class="QPushButton" name="buttonFF00FF">
<property name="sizePolicy">
<sizepolicy hsizetype="MinimumExpanding" vsizetype="MinimumExpanding">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="styleSheet">
<string notr="true">background-color: #FF00FF;
border: solid black;
border-width: 1px 1px 2px 1px;</string>
</property>
<property name="text">
<string/>
</property>
</widget>
</item>
<item row="3" column="2">
<widget class="QPushButton" name="buttonFFFF00">
<property name="sizePolicy">
<sizepolicy hsizetype="MinimumExpanding" vsizetype="MinimumExpanding">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="styleSheet">
<string notr="true">background-color: #FFFF00;
border: solid black;
border-width: 1px 1px 2px 1px;</string>
</property>
<property name="text">
<string/>
</property>
</widget>
</item>
<item row="3" column="3">
<widget class="QPushButton" name="buttonFFFFFF">
<property name="sizePolicy">
<sizepolicy hsizetype="MinimumExpanding" vsizetype="MinimumExpanding">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="styleSheet">
<string notr="true">background-color: #FFFBF0;
border: solid black;
border-width: 1px 2px 2px 1px;</string>
</property>
<property name="text">
<string/>
</property>
</widget>
</item>
</layout>
</item>
<item row="1" column="0">
<widget class="QLineEdit" name="editColor">
<property name="sizePolicy">
<sizepolicy hsizetype="Fixed" vsizetype="Fixed">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="styleSheet">
<string notr="true">QLineEdit {border-style: outset; border-width: 1px; border-color: black}</string>
</property>
<property name="text">
<string>#FFFFFF</string>
</property>
<property name="frame">
<bool>false</bool>
</property>
</widget>
</item>
<item row="1" column="1">
<widget class="QPushButton" name="buttonColor">
<property name="sizePolicy">
<sizepolicy hsizetype="Fixed" vsizetype="Fixed">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="minimumSize">
<size>
<width>30</width>
<height>18</height>
</size>
</property>
<property name="toolTip">
<string>Open color selector</string>
</property>
<property name="styleSheet">
<string notr="true">background-color: #FFFFFF; border : 2px solid black</string>
</property>
<property name="text">
<string/>
</property>
</widget>
</item>
</layout>
</widget>
</item>
<item row="1" column="1">
<widget class="QGroupBox" name="groupBackgroundColor">
<property name="title">
<string>Background Color</string>
</property>
<layout class="QGridLayout" name="gridLayout">
<item row="0" column="0" colspan="2">
<layout class="QGridLayout" name="gridBackgroundColors">
<property name="spacing">
<number>0</number>
</property>
<item row="0" column="0">
<widget class="QPushButton" name="buttonBackgroundNone">
<property name="sizePolicy">
<sizepolicy hsizetype="MinimumExpanding" vsizetype="MinimumExpanding">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="toolTip">
<string>Transparent</string>
</property>
<property name="styleSheet">
<string notr="true">background-color: #C0C0C0;
border: solid black;
border-width: 2px 1px 2px 2px;</string>
</property>
<property name="text">
<string>X</string>
</property>
</widget>
</item>
<item row="0" column="1">
<widget class="QPushButton" name="buttonBackground000000">
<property name="sizePolicy">
<sizepolicy hsizetype="MinimumExpanding" vsizetype="MinimumExpanding">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="styleSheet">
<string notr="true">background-color: #000000;
border: solid black;
border-width: 2px 1px 2px 1px;</string>
</property>
<property name="text">
<string/>
</property>
</widget>
</item>
<item row="0" column="2">
<widget class="QPushButton" name="buttonBackgroundC0C0C0">
<property name="sizePolicy">
<sizepolicy hsizetype="MinimumExpanding" vsizetype="MinimumExpanding">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="styleSheet">
<string notr="true">background-color: #C0C0C0;
border: solid black;
border-width: 2px 1px 2px 1px;</string>
</property>
<property name="text">
<string/>
</property>
</widget>
</item>
<item row="0" column="3">
<widget class="QPushButton" name="buttonBackgroundFFFFFF">
<property name="sizePolicy">
<sizepolicy hsizetype="MinimumExpanding" vsizetype="MinimumExpanding">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="styleSheet">
<string notr="true">background-color: #FFFBF0;
border: solid black;
border-width: 2px 2px 2px 1px;</string>
</property>
<property name="text">
<string/>
</property>
</widget>
</item>
<item row="1" column="0">
<widget class="QPushButton" name="buttonBackground00FFFF">
<property name="sizePolicy">
<sizepolicy hsizetype="MinimumExpanding" vsizetype="MinimumExpanding">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="styleSheet">
<string notr="true">background-color : #00FFFF;
border: solid black;
border-width: 1px 1px 2px 2px;</string>
</property>
<property name="text">
<string/>
</property>
</widget>
</item>
<item row="1" column="1">
<widget class="QPushButton" name="buttonBackground00FF00">
<property name="sizePolicy">
<sizepolicy hsizetype="MinimumExpanding" vsizetype="MinimumExpanding">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="styleSheet">
<string notr="true">background-color: #00FF00;
border: solid black;
border-width: 1px 1px 2px 1px;</string>
</property>
<property name="text">
<string/>
</property>
</widget>
</item>
<item row="1" column="2">
<widget class="QPushButton" name="buttonBackgroundFF0000">
<property name="sizePolicy">
<sizepolicy hsizetype="MinimumExpanding" vsizetype="MinimumExpanding">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="styleSheet">
<string notr="true">background-color: #FF0000;
border: solid black;
border-width: 1px 1px 2px 1px;</string>
</property>
<property name="text">
<string/>
</property>
</widget>
</item>
<item row="1" column="3">
<widget class="QPushButton" name="buttonBackgroundFFFF00">
<property name="sizePolicy">
<sizepolicy hsizetype="MinimumExpanding" vsizetype="MinimumExpanding">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="styleSheet">
<string notr="true">background-color: #FFFF00;
border: solid black;
border-width: 1px 2px 2px 1px;</string>
</property>
<property name="text">
<string/>
</property>
</widget>
</item>
</layout>
</item>
<item row="1" column="0">
<widget class="QLineEdit" name="editBackgroundColor">
<property name="sizePolicy">
<sizepolicy hsizetype="Fixed" vsizetype="Fixed">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="styleSheet">
<string notr="true">QLineEdit {border-style: outset; border-width: 1px; border-color: black}</string>
</property>
<property name="text">
<string>#FFFFFF</string>
</property>
<property name="frame">
<bool>false</bool>
</property>
</widget>
</item>
<item row="1" column="1">
<widget class="QPushButton" name="buttonBackgroundColor">
<property name="sizePolicy">
<sizepolicy hsizetype="Fixed" vsizetype="Fixed">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="minimumSize">
<size>
<width>30</width>
<height>18</height>
</size>
</property>
<property name="toolTip">
<string>Open color selector</string>
</property>
<property name="styleSheet">
<string notr="true">background-color: #FFFFFF; border : 2px solid black</string>
</property>
<property name="text">
<string/>
</property>
</widget>
</item>
</layout>
</widget>
</item>
<item row="2" column="1">
<widget class="QLabel" name="exampleText">
<property name="text">
<string>Example Text</string>
</property>
<property name="alignment">
<set>Qt::AlignCenter</set>
</property>
</widget>
</item>
</layout>
<zorder>groupBackgroundColor</zorder>
<zorder>groupColor</zorder>
<zorder>groupProperties</zorder>
<zorder>exampleText</zorder>
</widget>
<widget class="QWidget" name="tabFont">
<attribute name="title">
<string>Font</string>
</attribute>
<layout class="QVBoxLayout" name="verticalLayout">
<item>
<layout class="QHBoxLayout" name="fontAbstractTablesLayout">
<item>
<widget class="QLabel" name="labelFontAbstractTables">
<property name="sizePolicy">
<sizepolicy hsizetype="Preferred" vsizetype="Preferred">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="text">
<string>General Tables:</string>
</property>
</widget>
</item>
<item>
<widget class="QFontComboBox" name="fontAbstractTables">
<property name="sizePolicy">
<sizepolicy hsizetype="Preferred" vsizetype="Preferred">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="editable">
<bool>false</bool>
</property>
<property name="fontFilters">
<set>QFontComboBox::MonospacedFonts</set>
</property>
</widget>
</item>
<item>
<widget class="QComboBox" name="fontAbstractTablesStyle">
<property name="sizePolicy">
<sizepolicy hsizetype="Maximum" vsizetype="Preferred">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<item>
<property name="text">
<string>Normal</string>
</property>
</item>
<item>
<property name="text">
<string>Bold</string>
</property>
</item>
<item>
<property name="text">
<string>Italic</string>
</property>
</item>
<item>
<property name="text">
<string>Bold + Italic</string>
</property>
</item>
</widget>
</item>
<item>
<widget class="QComboBox" name="fontAbstractTablesSize">
<property name="sizePolicy">
<sizepolicy hsizetype="Maximum" vsizetype="Preferred">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="maxVisibleItems">
<number>12</number>
</property>
<property name="sizeAdjustPolicy">
<enum>QComboBox::AdjustToContentsOnFirstShow</enum>
</property>
<item>
<property name="text">
<string>6</string>
</property>
</item>
<item>
<property name="text">
<string>7</string>
</property>
</item>
<item>
<property name="text">
<string>8</string>
</property>
</item>
<item>
<property name="text">
<string>9</string>
</property>
</item>
<item>
<property name="text">
<string>10</string>
</property>
</item>
<item>
<property name="text">
<string>11</string>
</property>
</item>
<item>
<property name="text">
<string>12</string>
</property>
</item>
<item>
<property name="text">
<string>14</string>
</property>
</item>
<item>
<property name="text">
<string>16</string>
</property>
</item>
<item>
<property name="text">
<string>18</string>
</property>
</item>
<item>
<property name="text">
<string>20</string>
</property>
</item>
<item>
<property name="text">
<string>22</string>
</property>
</item>
</widget>
</item>
</layout>
</item>
<item>
<layout class="QHBoxLayout" name="fontDisassemblyLayout">
<item>
<widget class="QLabel" name="labelFontDisassembly">
<property name="sizePolicy">
<sizepolicy hsizetype="Preferred" vsizetype="Preferred">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="text">
<string>Disassembly:</string>
</property>
</widget>
</item>
<item>
<widget class="QFontComboBox" name="fontDisassembly">
<property name="sizePolicy">
<sizepolicy hsizetype="Preferred" vsizetype="Preferred">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="editable">
<bool>false</bool>
</property>
<property name="fontFilters">
<set>QFontComboBox::MonospacedFonts</set>
</property>
</widget>
</item>
<item>
<widget class="QComboBox" name="fontDisassemblyStyle">
<property name="sizePolicy">
<sizepolicy hsizetype="Maximum" vsizetype="Preferred">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<item>
<property name="text">
<string>Normal</string>
</property>
</item>
<item>
<property name="text">
<string>Bold</string>
</property>
</item>
<item>
<property name="text">
<string>Italic</string>
</property>
</item>
<item>
<property name="text">
<string>Bold + Italic</string>
</property>
</item>
</widget>
</item>
<item>
<widget class="QComboBox" name="fontDisassemblySize">
<property name="sizePolicy">
<sizepolicy hsizetype="Maximum" vsizetype="Preferred">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="maxVisibleItems">
<number>12</number>
</property>
<property name="sizeAdjustPolicy">
<enum>QComboBox::AdjustToContentsOnFirstShow</enum>
</property>
<item>
<property name="text">
<string>6</string>
</property>
</item>
<item>
<property name="text">
<string>7</string>
</property>
</item>
<item>
<property name="text">
<string>8</string>
</property>
</item>
<item>
<property name="text">
<string>9</string>
</property>
</item>
<item>
<property name="text">
<string>10</string>
</property>
</item>
<item>
<property name="text">
<string>11</string>
</property>
</item>
<item>
<property name="text">
<string>12</string>
</property>
</item>
<item>
<property name="text">
<string>14</string>
</property>
</item>
<item>
<property name="text">
<string>16</string>
</property>
</item>
<item>
<property name="text">
<string>18</string>
</property>
</item>
<item>
<property name="text">
<string>20</string>
</property>
</item>
<item>
<property name="text">
<string>22</string>
</property>
</item>
</widget>
</item>
</layout>
</item>
<item>
<layout class="QHBoxLayout" name="fontHexDumpLayout">
<item>
<widget class="QLabel" name="labelFontHexDump">
<property name="sizePolicy">
<sizepolicy hsizetype="Preferred" vsizetype="Preferred">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="text">
<string>HexDump:</string>
</property>
</widget>
</item>
<item>
<widget class="QFontComboBox" name="fontHexDump">
<property name="sizePolicy">
<sizepolicy hsizetype="Preferred" vsizetype="Preferred">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="editable">
<bool>false</bool>
</property>
<property name="fontFilters">
<set>QFontComboBox::MonospacedFonts</set>
</property>
</widget>
</item>
<item>
<widget class="QComboBox" name="fontHexDumpStyle">
<property name="sizePolicy">
<sizepolicy hsizetype="Maximum" vsizetype="Preferred">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<item>
<property name="text">
<string>Normal</string>
</property>
</item>
<item>
<property name="text">
<string>Bold</string>
</property>
</item>
<item>
<property name="text">
<string>Italic</string>
</property>
</item>
<item>
<property name="text">
<string>Bold + Italic</string>
</property>
</item>
</widget>
</item>
<item>
<widget class="QComboBox" name="fontHexDumpSize">
<property name="sizePolicy">
<sizepolicy hsizetype="Maximum" vsizetype="Preferred">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="maxVisibleItems">
<number>12</number>
</property>
<property name="sizeAdjustPolicy">
<enum>QComboBox::AdjustToContentsOnFirstShow</enum>
</property>
<item>
<property name="text">
<string>6</string>
</property>
</item>
<item>
<property name="text">
<string>7</string>
</property>
</item>
<item>
<property name="text">
<string>8</string>
</property>
</item>
<item>
<property name="text">
<string>9</string>
</property>
</item>
<item>
<property name="text">
<string>10</string>
</property>
</item>
<item>
<property name="text">
<string>11</string>
</property>
</item>
<item>
<property name="text">
<string>12</string>
</property>
</item>
<item>
<property name="text">
<string>14</string>
</property>
</item>
<item>
<property name="text">
<string>16</string>
</property>
</item>
<item>
<property name="text">
<string>18</string>
</property>
</item>
<item>
<property name="text">
<string>20</string>
</property>
</item>
<item>
<property name="text">
<string>22</string>
</property>
</item>
</widget>
</item>
</layout>
</item>
<item>
<layout class="QHBoxLayout" name="fontStackLayout">
<item>
<widget class="QLabel" name="labelFontStack">
<property name="sizePolicy">
<sizepolicy hsizetype="Preferred" vsizetype="Preferred">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="text">
<string>Stack:</string>
</property>
</widget>
</item>
<item>
<widget class="QFontComboBox" name="fontStack">
<property name="sizePolicy">
<sizepolicy hsizetype="Preferred" vsizetype="Preferred">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="editable">
<bool>false</bool>
</property>
<property name="fontFilters">
<set>QFontComboBox::MonospacedFonts</set>
</property>
</widget>
</item>
<item>
<widget class="QComboBox" name="fontStackStyle">
<property name="sizePolicy">
<sizepolicy hsizetype="Maximum" vsizetype="Preferred">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<item>
<property name="text">
<string>Normal</string>
</property>
</item>
<item>
<property name="text">
<string>Bold</string>
</property>
</item>
<item>
<property name="text">
<string>Italic</string>
</property>
</item>
<item>
<property name="text">
<string>Bold + Italic</string>
</property>
</item>
</widget>
</item>
<item>
<widget class="QComboBox" name="fontStackSize">
<property name="sizePolicy">
<sizepolicy hsizetype="Maximum" vsizetype="Preferred">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="maxVisibleItems">
<number>12</number>
</property>
<property name="sizeAdjustPolicy">
<enum>QComboBox::AdjustToContentsOnFirstShow</enum>
</property>
<item>
<property name="text">
<string>6</string>
</property>
</item>
<item>
<property name="text">
<string>7</string>
</property>
</item>
<item>
<property name="text">
<string>8</string>
</property>
</item>
<item>
<property name="text">
<string>9</string>
</property>
</item>
<item>
<property name="text">
<string>10</string>
</property>
</item>
<item>
<property name="text">
<string>11</string>
</property>
</item>
<item>
<property name="text">
<string>12</string>
</property>
</item>
<item>
<property name="text">
<string>14</string>
</property>
</item>
<item>
<property name="text">
<string>16</string>
</property>
</item>
<item>
<property name="text">
<string>18</string>
</property>
</item>
<item>
<property name="text">
<string>20</string>
</property>
</item>
<item>
<property name="text">
<string>22</string>
</property>
</item>
</widget>
</item>
</layout>
</item>
<item>
<layout class="QHBoxLayout" name="fontRegistersLayout">
<item>
<widget class="QLabel" name="labelFontRegisters">
<property name="sizePolicy">
<sizepolicy hsizetype="Preferred" vsizetype="Preferred">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="text">
<string>Registers:</string>
</property>
</widget>
</item>
<item>
<widget class="QFontComboBox" name="fontRegisters">
<property name="sizePolicy">
<sizepolicy hsizetype="Preferred" vsizetype="Preferred">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="editable">
<bool>false</bool>
</property>
<property name="fontFilters">
<set>QFontComboBox::MonospacedFonts</set>
</property>
</widget>
</item>
<item>
<widget class="QComboBox" name="fontRegistersStyle">
<property name="sizePolicy">
<sizepolicy hsizetype="Maximum" vsizetype="Preferred">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<item>
<property name="text">
<string>Normal</string>
</property>
</item>
<item>
<property name="text">
<string>Bold</string>
</property>
</item>
<item>
<property name="text">
<string>Italic</string>
</property>
</item>
<item>
<property name="text">
<string>Bold + Italic</string>
</property>
</item>
</widget>
</item>
<item>
<widget class="QComboBox" name="fontRegistersSize">
<property name="sizePolicy">
<sizepolicy hsizetype="Maximum" vsizetype="Preferred">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="maxVisibleItems">
<number>12</number>
</property>
<property name="sizeAdjustPolicy">
<enum>QComboBox::AdjustToContentsOnFirstShow</enum>
</property>
<item>
<property name="text">
<string>6</string>
</property>
</item>
<item>
<property name="text">
<string>7</string>
</property>
</item>
<item>
<property name="text">
<string>8</string>
</property>
</item>
<item>
<property name="text">
<string>9</string>
</property>
</item>
<item>
<property name="text">
<string>10</string>
</property>
</item>
<item>
<property name="text">
<string>11</string>
</property>
</item>
<item>
<property name="text">
<string>12</string>
</property>
</item>
<item>
<property name="text">
<string>14</string>
</property>
</item>
<item>
<property name="text">
<string>16</string>
</property>
</item>
<item>
<property name="text">
<string>18</string>
</property>
</item>
<item>
<property name="text">
<string>20</string>
</property>
</item>
<item>
<property name="text">
<string>22</string>
</property>
</item>
</widget>
</item>
</layout>
</item>
<item>
<layout class="QHBoxLayout" name="fontHexEditLayout">
<item>
<widget class="QLabel" name="labelFontHexEdit">
<property name="sizePolicy">
<sizepolicy hsizetype="Preferred" vsizetype="Preferred">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="text">
<string>HexEdit:</string>
</property>
</widget>
</item>
<item>
<widget class="QFontComboBox" name="fontHexEdit">
<property name="sizePolicy">
<sizepolicy hsizetype="Preferred" vsizetype="Preferred">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="editable">
<bool>false</bool>
</property>
<property name="fontFilters">
<set>QFontComboBox::MonospacedFonts</set>
</property>
</widget>
</item>
<item>
<widget class="QComboBox" name="fontHexEditStyle">
<property name="sizePolicy">
<sizepolicy hsizetype="Maximum" vsizetype="Preferred">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<item>
<property name="text">
<string>Normal</string>
</property>
</item>
<item>
<property name="text">
<string>Bold</string>
</property>
</item>
<item>
<property name="text">
<string>Italic</string>
</property>
</item>
<item>
<property name="text">
<string>Bold + Italic</string>
</property>
</item>
</widget>
</item>
<item>
<widget class="QComboBox" name="fontHexEditSize">
<property name="sizePolicy">
<sizepolicy hsizetype="Maximum" vsizetype="Preferred">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="maxVisibleItems">
<number>12</number>
</property>
<property name="sizeAdjustPolicy">
<enum>QComboBox::AdjustToContentsOnFirstShow</enum>
</property>
<item>
<property name="text">
<string>6</string>
</property>
</item>
<item>
<property name="text">
<string>7</string>
</property>
</item>
<item>
<property name="text">
<string>8</string>
</property>
</item>
<item>
<property name="text">
<string>9</string>
</property>
</item>
<item>
<property name="text">
<string>10</string>
</property>
</item>
<item>
<property name="text">
<string>11</string>
</property>
</item>
<item>
<property name="text">
<string>12</string>
</property>
</item>
<item>
<property name="text">
<string>14</string>
</property>
</item>
<item>
<property name="text">
<string>16</string>
</property>
</item>
<item>
<property name="text">
<string>18</string>
</property>
</item>
<item>
<property name="text">
<string>20</string>
</property>
</item>
<item>
<property name="text">
<string>22</string>
</property>
</item>
</widget>
</item>
</layout>
</item>
<item>
<layout class="QHBoxLayout" name="fontLogLayout">
<item>
<widget class="QLabel" name="labelFontLog">
<property name="sizePolicy">
<sizepolicy hsizetype="Preferred" vsizetype="Preferred">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="text">
<string>Log:</string>
</property>
</widget>
</item>
<item>
<widget class="QFontComboBox" name="fontLog">
<property name="sizePolicy">
<sizepolicy hsizetype="Preferred" vsizetype="Preferred">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="editable">
<bool>false</bool>
</property>
<property name="fontFilters">
<set>QFontComboBox::MonospacedFonts</set>
</property>
</widget>
</item>
<item>
<widget class="QComboBox" name="fontLogStyle">
<property name="sizePolicy">
<sizepolicy hsizetype="Maximum" vsizetype="Preferred">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<item>
<property name="text">
<string>Normal</string>
</property>
</item>
<item>
<property name="text">
<string>Bold</string>
</property>
</item>
<item>
<property name="text">
<string>Italic</string>
</property>
</item>
<item>
<property name="text">
<string>Bold + Italic</string>
</property>
</item>
</widget>
</item>
<item>
<widget class="QComboBox" name="fontLogSize">
<property name="sizePolicy">
<sizepolicy hsizetype="Maximum" vsizetype="Preferred">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="maxVisibleItems">
<number>12</number>
</property>
<property name="sizeAdjustPolicy">
<enum>QComboBox::AdjustToContentsOnFirstShow</enum>
</property>
<item>
<property name="text">
<string>6</string>
</property>
</item>
<item>
<property name="text">
<string>7</string>
</property>
</item>
<item>
<property name="text">
<string>8</string>
</property>
</item>
<item>
<property name="text">
<string>9</string>
</property>
</item>
<item>
<property name="text">
<string>10</string>
</property>
</item>
<item>
<property name="text">
<string>11</string>
</property>
</item>
<item>
<property name="text">
<string>12</string>
</property>
</item>
<item>
<property name="text">
<string>14</string>
</property>
</item>
<item>
<property name="text">
<string>16</string>
</property>
</item>
<item>
<property name="text">
<string>18</string>
</property>
</item>
<item>
<property name="text">
<string>20</string>
</property>
</item>
<item>
<property name="text">
<string>22</string>
</property>
</item>
</widget>
</item>
</layout>
</item>
<item>
<layout class="QHBoxLayout" name="fontApplicationLayout">
<item>
<widget class="QPushButton" name="buttonApplicationFont">
<property name="sizePolicy">
<sizepolicy hsizetype="Minimum" vsizetype="Preferred">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="text">
<string>&Application Font*</string>
</property>
</widget>
</item>
<item>
<widget class="QLabel" name="labelApplicationFont">
<property name="sizePolicy">
<sizepolicy hsizetype="Maximum" vsizetype="Preferred">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="text">
<string>Courier New</string>
</property>
</widget>
</item>
<item>
<widget class="QPushButton" name="buttonFontDefaults">
<property name="sizePolicy">
<sizepolicy hsizetype="Maximum" vsizetype="Preferred">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="text">
<string>&Defaults</string>
</property>
</widget>
</item>
</layout>
</item>
<item>
<spacer name="verticalSpacer">
<property name="orientation">
<enum>Qt::Vertical</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>20</width>
<height>40</height>
</size>
</property>
</spacer>
</item>
<item>
<layout class="QVBoxLayout" name="fontRestartRequiredLayout">
<property name="sizeConstraint">
<enum>QLayout::SetMinimumSize</enum>
</property>
<item>
<widget class="QLabel" name="labelFontRestartRequired">
<property name="sizePolicy">
<sizepolicy hsizetype="Preferred" vsizetype="Minimum">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="text">
<string>*Setting requires restarting the application to take effect.</string>
</property>
<property name="wordWrap">
<bool>true</bool>
</property>
</widget>
</item>
</layout>
</item>
</layout>
</widget>
</widget>
</item>
<item>
<layout class="QHBoxLayout" name="horizontalLayout">
<item>
<spacer name="horizontalSpacer">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>40</width>
<height>20</height>
</size>
</property>
</spacer>
</item>
<item>
<widget class="QPushButton" name="buttonSave">
<property name="text">
<string>&Save</string>
</property>
<property name="default">
<bool>true</bool>
</property>
</widget>
</item>
<item>
<widget class="QPushButton" name="buttonCancel">
<property name="text">
<string>&Cancel</string>
</property>
</widget>
</item>
</layout>
</item>
</layout>
</widget>
<layoutdefault spacing="6" margin="11"/>
<tabstops>
<tabstop>tabWidget</tabstop>
<tabstop>listColorNames</tabstop>
<tabstop>button000000</tabstop>
<tabstop>button000080</tabstop>
<tabstop>button008000</tabstop>
<tabstop>button008080</tabstop>
<tabstop>button800000</tabstop>
<tabstop>button800080</tabstop>
<tabstop>button808000</tabstop>
<tabstop>buttonC0C0C0</tabstop>
<tabstop>button808080</tabstop>
<tabstop>button0000FF</tabstop>
<tabstop>button00FF00</tabstop>
<tabstop>button00FFFF</tabstop>
<tabstop>buttonFF0000</tabstop>
<tabstop>buttonFF00FF</tabstop>
<tabstop>buttonFFFF00</tabstop>
<tabstop>buttonFFFFFF</tabstop>
<tabstop>editColor</tabstop>
<tabstop>buttonColor</tabstop>
<tabstop>buttonBackgroundNone</tabstop>
<tabstop>buttonBackground000000</tabstop>
<tabstop>buttonBackgroundC0C0C0</tabstop>
<tabstop>buttonBackgroundFFFFFF</tabstop>
<tabstop>buttonBackground00FFFF</tabstop>
<tabstop>buttonBackground00FF00</tabstop>
<tabstop>buttonBackgroundFF0000</tabstop>
<tabstop>buttonBackgroundFFFF00</tabstop>
<tabstop>editBackgroundColor</tabstop>
<tabstop>buttonBackgroundColor</tabstop>
<tabstop>fontAbstractTables</tabstop>
<tabstop>fontAbstractTablesStyle</tabstop>
<tabstop>fontAbstractTablesSize</tabstop>
<tabstop>fontDisassembly</tabstop>
<tabstop>fontDisassemblyStyle</tabstop>
<tabstop>fontDisassemblySize</tabstop>
<tabstop>fontHexDump</tabstop>
<tabstop>fontHexDumpStyle</tabstop>
<tabstop>fontHexDumpSize</tabstop>
<tabstop>fontStack</tabstop>
<tabstop>fontStackStyle</tabstop>
<tabstop>fontStackSize</tabstop>
<tabstop>fontRegisters</tabstop>
<tabstop>fontRegistersStyle</tabstop>
<tabstop>fontRegistersSize</tabstop>
<tabstop>fontHexEdit</tabstop>
<tabstop>fontHexEditStyle</tabstop>
<tabstop>fontHexEditSize</tabstop>
<tabstop>fontLog</tabstop>
<tabstop>fontLogStyle</tabstop>
<tabstop>fontLogSize</tabstop>
<tabstop>buttonApplicationFont</tabstop>
<tabstop>buttonFontDefaults</tabstop>
</tabstops>
<resources>
<include location="../../resource.qrc"/>
</resources>
<connections>
<connection>
<sender>buttonCancel</sender>
<signal>clicked()</signal>
<receiver>AppearanceDialog</receiver>
<slot>close()</slot>
<hints>
<hint type="sourcelabel">
<x>481</x>
<y>381</y>
</hint>
<hint type="destinationlabel">
<x>476</x>
<y>386</y>
</hint>
</hints>
</connection>
<connection>
<sender>buttonSave</sender>
<signal>clicked(bool)</signal>
<receiver>AppearanceDialog</receiver>
<slot>accept()</slot>
<hints>
<hint type="sourcelabel">
<x>393</x>
<y>382</y>
</hint>
<hint type="destinationlabel">
<x>398</x>
<y>376</y>
</hint>
</hints>
</connection>
</connections>
</ui> |
C++ | x64dbg-development/src/gui/Src/Gui/AssembleDialog.cpp | #include "AssembleDialog.h"
#include "ui_AssembleDialog.h"
#include "ValidateExpressionThread.h"
#include <QMessageBox>
#include "Configuration.h"
bool AssembleDialog::bWarningShowedOnce = false;
#define ASSEMBLE_ERROR (-1337)
AssembleDialog::AssembleDialog(QWidget* parent) :
QDialog(parent),
ui(new Ui::AssembleDialog)
{
ui->setupUi(this);
setModal(true);
setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint | Qt::MSWindowsFixedSizeDialogHint);
mSelectedInstrVa = 0;
bKeepSizeChecked = false;
bFillWithNopsChecked = false;
setKeepSizeLabel("");
mValidateThread = new ValidateExpressionThread(this);
mValidateThread->setOnExpressionChangedCallback(std::bind(&AssembleDialog::validateInstruction, this, std::placeholders::_1));
connect(ui->lineEdit, SIGNAL(textChanged(QString)), this, SLOT(textChangedSlot(QString)));
connect(mValidateThread, SIGNAL(instructionChanged(dsint, QString)), this, SLOT(instructionChangedSlot(dsint, QString)));
mValidateThread->start();
duint setting;
if(BridgeSettingGetUint("Engine", "Assembler", &setting))
{
if(setting == 1 || setting == 2)
ui->radioAsmjit->setChecked(true);
}
Config()->loadWindowGeometry(this);
}
AssembleDialog::~AssembleDialog()
{
mValidateThread->stop();
mValidateThread->wait();
Config()->saveWindowGeometry(this);
delete ui;
}
void AssembleDialog::setTextEditValue(const QString & text)
{
ui->lineEdit->setText(text);
ui->lineEdit->selectAll();
}
void AssembleDialog::setKeepSizeChecked(bool checked)
{
ui->checkBoxKeepSize->setChecked(checked);
bKeepSizeChecked = checked;
}
void AssembleDialog::setKeepSizeLabel(const QString & text)
{
ui->labelKeepSize->setText(text);
}
void AssembleDialog::setFillWithNopsChecked(bool checked)
{
ui->checkBoxFillWithNops->setChecked(checked);
bFillWithNopsChecked = checked;
}
void AssembleDialog::setSelectedInstrVa(const duint va)
{
mSelectedInstrVa = va;
}
void AssembleDialog::setOkButtonEnabled(bool enabled)
{
ui->pushButtonOk->setEnabled(enabled);
}
void AssembleDialog::validateInstruction(QString expression)
{
//sanitize the expression (just simplifying it by removing excess whitespaces)
expression = expression.simplified();
if(!expression.length())
{
emit mValidateThread->emitInstructionChanged(ASSEMBLE_ERROR, tr("empty instruction"));
return;
}
//void instructionChanged(bool validInstruction, dsint sizeDifference, QString error)
dsint sizeDifference = 0;
int typedInstructionSize = 0;
int selectedInstructionSize = 0;
bool validInstruction = false;
QByteArray error(MAX_ERROR_SIZE, 0);
QByteArray opcode(16, 0);
BASIC_INSTRUCTION_INFO basicInstrInfo;
// Get selected instruction info (size here)
DbgDisasmFastAt(mSelectedInstrVa, &basicInstrInfo);
selectedInstructionSize = basicInstrInfo.size;
// Get typed in instruction size
if(!DbgFunctions()->Assemble(mSelectedInstrVa, (unsigned char*)opcode.data(), &typedInstructionSize, expression.toUtf8().constData(), error.data()) || selectedInstructionSize == 0)
{
emit mValidateThread->emitInstructionChanged(ASSEMBLE_ERROR, QString(error));
return;
}
// Valid instruction
validInstruction = true;
sizeDifference = typedInstructionSize - selectedInstructionSize;
opcode.resize(typedInstructionSize);
emit mValidateThread->emitInstructionChanged(sizeDifference, opcode.toHex().toUpper());
}
void AssembleDialog::textChangedSlot(QString text)
{
mValidateThread->textChanged(text);
}
void AssembleDialog::instructionChangedSlot(dsint sizeDifference, QString data)
{
// If there was an error
if(sizeDifference == ASSEMBLE_ERROR)
{
setKeepSizeLabel(tr("<font color='orange'><b>Instruction encoding error: %1</b></font>").arg(data));
setOkButtonEnabled(false);
}
else if(ui->checkBoxKeepSize->isChecked())
{
// SizeDifference > 0 <=> Typed instruction is bigger
if(sizeDifference > 0)
{
QString message = tr("<font color='red'><b>Instruction bigger by %1 %2...</b></font>")
.arg(sizeDifference)
.arg(sizeDifference == 1 ? tr("byte") : tr("bytes")).append(tr("<br>Bytes: %1").arg(data));
setKeepSizeLabel(message);
setOkButtonEnabled(false);
}
// SizeDifference < 0 <=> Typed instruction is smaller
else if(sizeDifference < 0)
{
QString message = tr("<font color='#00cc00'><b>Instruction smaller by %1 %2...</b></font>")
.arg(-sizeDifference)
.arg(sizeDifference == -1 ? tr("byte") : tr("bytes")).append(tr("<br>Bytes: %1").arg(data));
setKeepSizeLabel(message);
setOkButtonEnabled(true);
}
// SizeDifference == 0 <=> Both instruction have same size
else
{
QString message = tr("<font color='#00cc00'><b>Instruction is same size!</b></font>").append(tr("<br>Bytes: %1").arg(data));
setKeepSizeLabel(message);
setOkButtonEnabled(true);
}
}
else
{
QString message = tr("<font color='#00cc00'><b>Instruction encoded successfully!</b></font>").append(tr("<br>Bytes: %1").arg(data));
setKeepSizeLabel(message);
setOkButtonEnabled(true);
}
}
void AssembleDialog::on_lineEdit_textChanged(const QString & arg1)
{
editText = arg1;
}
void AssembleDialog::on_checkBoxKeepSize_clicked(bool checked)
{
bKeepSizeChecked = checked;
mValidateThread->additionalStateChanged();
}
void AssembleDialog::on_checkBoxFillWithNops_clicked(bool checked)
{
bFillWithNopsChecked = checked;
}
void AssembleDialog::on_radioXEDParse_clicked()
{
BridgeSettingSetUint("Engine", "Assembler", 0);
DbgSettingsUpdated();
validateInstruction(ui->lineEdit->text());
}
void AssembleDialog::on_radioAsmjit_clicked()
{
BridgeSettingSetUint("Engine", "Assembler", 2);
DbgSettingsUpdated();
validateInstruction(ui->lineEdit->text());
} |
C/C++ | x64dbg-development/src/gui/Src/Gui/AssembleDialog.h | #pragma once
#include <QDialog>
#include <functional>
#include "Bridge.h"
class ValidateExpressionThread;
namespace Ui
{
class AssembleDialog;
}
class AssembleDialog : public QDialog
{
Q_OBJECT
public:
explicit AssembleDialog(QWidget* parent = 0);
~AssembleDialog();
QString editText;
static bool bWarningShowedOnce;
void setTextEditValue(const QString & text);
bool bKeepSizeChecked;
void setKeepSizeChecked(bool checked);
void setKeepSizeLabel(const QString & text);
bool bFillWithNopsChecked;
void setFillWithNopsChecked(bool checked);
void setSelectedInstrVa(const duint va);
void setOkButtonEnabled(bool enabled);
void validateInstruction(QString expression);
private slots:
void textChangedSlot(QString text);
void instructionChangedSlot(dsint sizeDifference, QString data);
void on_lineEdit_textChanged(const QString & arg1);
void on_checkBoxKeepSize_clicked(bool checked);
void on_checkBoxFillWithNops_clicked(bool checked);
void on_radioXEDParse_clicked();
void on_radioAsmjit_clicked();
private:
Ui::AssembleDialog* ui;
duint mSelectedInstrVa;
ValidateExpressionThread* mValidateThread;
}; |
User Interface | x64dbg-development/src/gui/Src/Gui/AssembleDialog.ui | <?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>AssembleDialog</class>
<widget class="QDialog" name="AssembleDialog">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>526</width>
<height>96</height>
</rect>
</property>
<property name="windowTitle">
<string>0</string>
</property>
<property name="windowIcon">
<iconset theme="ui-combo-box-edit" resource="../../resource.qrc">
<normaloff>:/Default/icons/ui-combo-box-edit.png</normaloff>:/Default/icons/ui-combo-box-edit.png</iconset>
</property>
<layout class="QVBoxLayout" name="verticalLayout">
<property name="bottomMargin">
<number>0</number>
</property>
<item>
<widget class="QLineEdit" name="lineEdit">
<property name="sizePolicy">
<sizepolicy hsizetype="Minimum" vsizetype="Preferred">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
</widget>
</item>
<item>
<layout class="QHBoxLayout" name="horizontalLayout">
<property name="sizeConstraint">
<enum>QLayout::SetDefaultConstraint</enum>
</property>
<item>
<widget class="QCheckBox" name="checkBoxKeepSize">
<property name="sizePolicy">
<sizepolicy hsizetype="Fixed" vsizetype="Maximum">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="text">
<string>Keep &Size</string>
</property>
</widget>
</item>
<item>
<widget class="QCheckBox" name="checkBoxFillWithNops">
<property name="text">
<string>&Fill with NOP's</string>
</property>
</widget>
</item>
<item>
<widget class="QRadioButton" name="radioXEDParse">
<property name="text">
<string>&XEDParse</string>
</property>
<property name="checked">
<bool>true</bool>
</property>
</widget>
</item>
<item>
<widget class="QRadioButton" name="radioAsmjit">
<property name="text">
<string>&asmjit</string>
</property>
</widget>
</item>
<item>
<spacer name="horizontalSpacer">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>40</width>
<height>20</height>
</size>
</property>
</spacer>
</item>
<item>
<widget class="QPushButton" name="pushButtonOk">
<property name="minimumSize">
<size>
<width>0</width>
<height>0</height>
</size>
</property>
<property name="text">
<string>OK</string>
</property>
</widget>
</item>
<item>
<widget class="QPushButton" name="pushButtonCancel">
<property name="text">
<string>Cancel</string>
</property>
</widget>
</item>
</layout>
</item>
<item>
<widget class="QLabel" name="labelKeepSize">
<property name="sizePolicy">
<sizepolicy hsizetype="Preferred" vsizetype="Fixed">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="minimumSize">
<size>
<width>0</width>
<height>0</height>
</size>
</property>
<property name="text">
<string><font color='orange'><b>Instruction decoding error</b></font></string>
</property>
<property name="alignment">
<set>Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter</set>
</property>
</widget>
</item>
<item>
<spacer name="verticalSpacer">
<property name="orientation">
<enum>Qt::Vertical</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>20</width>
<height>40</height>
</size>
</property>
</spacer>
</item>
</layout>
</widget>
<resources>
<include location="../../resource.qrc"/>
</resources>
<connections>
<connection>
<sender>pushButtonOk</sender>
<signal>clicked()</signal>
<receiver>AssembleDialog</receiver>
<slot>accept()</slot>
<hints>
<hint type="sourcelabel">
<x>265</x>
<y>77</y>
</hint>
<hint type="destinationlabel">
<x>217</x>
<y>49</y>
</hint>
</hints>
</connection>
<connection>
<sender>pushButtonCancel</sender>
<signal>clicked()</signal>
<receiver>AssembleDialog</receiver>
<slot>close()</slot>
<hints>
<hint type="sourcelabel">
<x>373</x>
<y>77</y>
</hint>
<hint type="destinationlabel">
<x>217</x>
<y>49</y>
</hint>
</hints>
</connection>
</connections>
</ui> |
C++ | x64dbg-development/src/gui/Src/Gui/AttachDialog.cpp | #include "AttachDialog.h"
#include "ui_AttachDialog.h"
#include "StdIconSearchListView.h"
#include "StdTable.h"
#include <QMenu>
#include <QMessageBox>
#include <QFileInfo>
AttachDialog::AttachDialog(QWidget* parent) : QDialog(parent), ui(new Ui::AttachDialog)
{
ui->setupUi(this);
setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint);
// Setup actions/shortcuts
//
// Enter key as shortcut for "Attach"
mAttachAction = new QAction(DIcon("attach"), tr("Attach"), this);
mAttachAction->setShortcut(QKeySequence("enter"));
connect(mAttachAction, SIGNAL(triggered()), this, SLOT(on_btnAttach_clicked()));
// F5 as shortcut to refresh view
mRefreshAction = new QAction(DIcon("arrow-restart"), tr("Refresh"), this);
mRefreshAction->setShortcut(ConfigShortcut("ActionRefresh"));
ui->btnRefresh->setText(tr("Refresh") + QString(" (%1)").arg(mRefreshAction->shortcut().toString()));
connect(mRefreshAction, SIGNAL(triggered()), this, SLOT(refresh()));
this->addAction(mRefreshAction);
connect(ui->btnRefresh, SIGNAL(clicked()), this, SLOT(refresh()));
// Create search view (regex disabled)
mSearchListView = new StdIconSearchListView(this, false, false);
mSearchListView->mSearchStartCol = 0;
ui->verticalLayout->insertWidget(0, mSearchListView);
//setup process list
int charwidth = mSearchListView->getCharWidth();
mSearchListView->addColumnAt(charwidth * sizeof(int) * 2 + 8, tr("PID"), true, QString(), ConfigBool("Gui", "PidTidInHex") ? StdTable::SortBy::AsHex : StdTable::SortBy::AsInt);
mSearchListView->addColumnAt(150, tr("Name"), true);
mSearchListView->addColumnAt(300, tr("Title"), true);
mSearchListView->addColumnAt(500, tr("Path"), true);
mSearchListView->addColumnAt(800, tr("Command Line Arguments"), true);
mSearchListView->setIconColumn(1); // Name
mSearchListView->setDrawDebugOnly(false);
connect(mSearchListView, SIGNAL(enterPressedSignal()), this, SLOT(on_btnAttach_clicked()));
connect(mSearchListView, SIGNAL(listContextMenuSignal(QMenu*)), this, SLOT(processListContextMenu(QMenu*)));
// Highlight the search box
mSearchListView->mCurList->setFocus();
Config()->loadWindowGeometry(this);
// Populate the process list atleast once
refresh();
}
AttachDialog::~AttachDialog()
{
Config()->saveWindowGeometry(this);
delete ui;
}
void AttachDialog::refresh()
{
mSearchListView->setRowCount(0);
DBGPROCESSINFO* entries;
int count;
if(!DbgFunctions()->GetProcessList(&entries, &count))
return;
mSearchListView->setRowCount(count);
for(int i = 0; i < count; i++)
{
QFileInfo fi(entries[i].szExeFile);
mSearchListView->setCellContent(i, ColPid, QString().sprintf(ConfigBool("Gui", "PidTidInHex") ? "%.8X" : "%u", entries[i].dwProcessId));
mSearchListView->setCellContent(i, ColName, fi.baseName());
mSearchListView->setCellContent(i, ColTitle, QString(entries[i].szExeMainWindowTitle));
mSearchListView->setCellContent(i, ColPath, QString(entries[i].szExeFile));
mSearchListView->setCellContent(i, ColCommandLine, QString(entries[i].szExeArgs));
mSearchListView->setRowIcon(i, getFileIcon(QString(entries[i].szExeFile)));
}
mSearchListView->reloadData();
mSearchListView->refreshSearchList();
}
void AttachDialog::on_btnAttach_clicked()
{
QString pid = mSearchListView->mCurList->getCellContent(mSearchListView->mCurList->getInitialSelection(), ColPid);
DbgCmdExec(QString("attach %1%2").arg(ConfigBool("Gui", "PidTidInHex") ? "" : ".").arg(pid));
accept();
}
void AttachDialog::on_btnFindWindow_clicked()
{
QString windowText;
retryFindWindow:
if(!SimpleInputBox(this, tr("Find Window"), windowText, windowText, tr("Enter window title or class name here.")))
return;
HWND hWndFound = FindWindowW(NULL, reinterpret_cast<LPCWSTR>(windowText.utf16())); //Window Title first
if(hWndFound == NULL)
hWndFound = FindWindowW(reinterpret_cast<LPCWSTR>(windowText.utf16()), NULL); //Then try window class name
if(hWndFound == NULL)
{
QMessageBox retryDialog(QMessageBox::Critical, tr("Find Window"), tr("Cannot find window \"%1\". Retry?").arg(windowText), QMessageBox::Cancel | QMessageBox::Retry, this);
retryDialog.setWindowIcon(DIcon("compile-error"));
if(retryDialog.exec() == QMessageBox::Retry)
goto retryFindWindow;
}
else
{
DWORD pid, tid;
if(tid = GetWindowThreadProcessId(hWndFound, &pid))
{
refresh();
QString pidText = QString().sprintf(ConfigBool("Gui", "PidTidInHex") ? "%.8X" : "%u", pid);
bool found = false;
for(int i = 0; i < mSearchListView->mCurList->getRowCount(); i++)
{
if(mSearchListView->mCurList->getCellContent(i, ColPid) == pidText)
{
mSearchListView->mCurList->setSingleSelection(i);
found = true;
break;
}
}
if(!found)
{
QMessageBox hiddenProcessDialog(QMessageBox::Question, tr("Find Window"),
tr("The PID of the window \"%1\" is %2, but it's hidden in the process list. Do you want to attach to it immediately?").arg(windowText).arg(pidText),
QMessageBox::Yes | QMessageBox::No, this);
if(hiddenProcessDialog.exec() == QMessageBox::Yes)
{
DbgCmdExec(QString("attach %1").arg(pid, 0, 16));
accept();
}
}
}
else
SimpleErrorBox(this, tr("Find Window"), tr("GetWindowThreadProcessId() failed. Cannot get the PID of the window."));
}
}
void AttachDialog::processListContextMenu(QMenu* wMenu)
{
// Don't show menu options if nothing is listed
if(!mSearchListView->mCurList->getRowCount())
return;
wMenu->addAction(mAttachAction);
wMenu->addAction(mRefreshAction);
} |
C/C++ | x64dbg-development/src/gui/Src/Gui/AttachDialog.h | #pragma once
#include <QDialog>
class StdIconSearchListView;
class QMenu;
class QAction;
namespace Ui
{
class AttachDialog;
}
class AttachDialog : public QDialog
{
Q_OBJECT
public:
explicit AttachDialog(QWidget* parent = 0);
~AttachDialog();
private slots:
void on_btnAttach_clicked();
void on_btnFindWindow_clicked();
void refresh();
void processListContextMenu(QMenu* wMenu);
private:
Ui::AttachDialog* ui;
StdIconSearchListView* mSearchListView;
QAction* mAttachAction;
QAction* mRefreshAction;
enum
{
ColPid,
ColName,
ColTitle,
ColPath,
ColCommandLine,
};
}; |
User Interface | x64dbg-development/src/gui/Src/Gui/AttachDialog.ui | <?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>AttachDialog</class>
<widget class="QDialog" name="AttachDialog">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>800</width>
<height>400</height>
</rect>
</property>
<property name="windowTitle">
<string>Attach</string>
</property>
<property name="windowIcon">
<iconset theme="attach" resource="../../resource.qrc">
<normaloff>:/Default/icons/attach.png</normaloff>:/Default/icons/attach.png</iconset>
</property>
<layout class="QGridLayout" name="gridLayout">
<property name="leftMargin">
<number>0</number>
</property>
<property name="topMargin">
<number>0</number>
</property>
<property name="rightMargin">
<number>0</number>
</property>
<property name="bottomMargin">
<number>6</number>
</property>
<item row="0" column="0">
<layout class="QVBoxLayout" name="verticalLayout">
<property name="spacing">
<number>6</number>
</property>
<property name="sizeConstraint">
<enum>QLayout::SetDefaultConstraint</enum>
</property>
<item>
<layout class="QHBoxLayout" name="horizontalLayout">
<property name="spacing">
<number>6</number>
</property>
<property name="sizeConstraint">
<enum>QLayout::SetDefaultConstraint</enum>
</property>
<property name="leftMargin">
<number>6</number>
</property>
<property name="topMargin">
<number>0</number>
</property>
<property name="rightMargin">
<number>6</number>
</property>
<property name="bottomMargin">
<number>0</number>
</property>
<item>
<spacer name="horizontalSpacer">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>40</width>
<height>20</height>
</size>
</property>
</spacer>
</item>
<item>
<widget class="QLabel" name="label">
<property name="text">
<string><a href="http://faq.x64dbg.com">Why is process X not shown?</a></string>
</property>
<property name="openExternalLinks">
<bool>true</bool>
</property>
</widget>
</item>
<item>
<widget class="QPushButton" name="btnRefresh">
<property name="sizePolicy">
<sizepolicy hsizetype="Preferred" vsizetype="Fixed">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="text">
<string>Refresh</string>
</property>
<property name="autoDefault">
<bool>false</bool>
</property>
</widget>
</item>
<item>
<widget class="QPushButton" name="btnFindWindow">
<property name="text">
<string>Find Window...</string>
</property>
</widget>
</item>
<item>
<widget class="QPushButton" name="btnAttach">
<property name="sizePolicy">
<sizepolicy hsizetype="Preferred" vsizetype="Fixed">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="text">
<string>&Attach</string>
</property>
<property name="autoDefault">
<bool>true</bool>
</property>
<property name="default">
<bool>true</bool>
</property>
</widget>
</item>
<item>
<widget class="QPushButton" name="btnCancel">
<property name="sizePolicy">
<sizepolicy hsizetype="Preferred" vsizetype="Fixed">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="text">
<string>&Cancel</string>
</property>
<property name="autoDefault">
<bool>false</bool>
</property>
</widget>
</item>
</layout>
</item>
</layout>
</item>
</layout>
</widget>
<resources>
<include location="../../resource.qrc"/>
</resources>
<connections>
<connection>
<sender>btnCancel</sender>
<signal>clicked()</signal>
<receiver>AttachDialog</receiver>
<slot>reject()</slot>
<hints>
<hint type="sourcelabel">
<x>561</x>
<y>272</y>
</hint>
<hint type="destinationlabel">
<x>551</x>
<y>255</y>
</hint>
</hints>
</connection>
</connections>
</ui> |
C++ | x64dbg-development/src/gui/Src/Gui/BreakpointsView.cpp | #include <QClipboard>
#include <QRegularExpression>
#include "BreakpointsView.h"
#include "EditBreakpointDialog.h"
#include "Bridge.h"
#include "MenuBuilder.h"
#include "Breakpoints.h"
BreakpointsView::BreakpointsView(QWidget* parent)
: StdTable(parent), mExceptionMaxLength(0)
{
auto charWidth = [this](int count)
{
return getCharWidth() * count + 8;
};
addColumnAt(charWidth(9), tr("Type"), false);
addColumnAt(charWidth(sizeof(duint) * 2), tr("Address"), true, "", StdTable::SortBy::AsHex);
addColumnAt(charWidth(35), tr("Module/Label/Exception"), true);
addColumnAt(charWidth(8), tr("State"), true);
addColumnAt(charWidth(50), tr("Disassembly"), true);
addColumnAt(charWidth(4), tr("Hits"), true, "", StdTable::SortBy::AsInt);
addColumnAt(0, tr("Summary"), true);
loadColumnFromConfig("BreakpointsView");
mDisasm = new QBeaEngine(ConfigUint("Disassembler", "MaxModuleSize"));
mDisasm->UpdateConfig();
enableMultiSelection(true);
setupContextMenu();
connect(Bridge::getBridge(), SIGNAL(updateBreakpoints()), this, SLOT(updateBreakpointsSlot()));
connect(Bridge::getBridge(), SIGNAL(disassembleAt(dsint, dsint)), this, SLOT(disassembleAtSlot(dsint, dsint)));
connect(Config(), SIGNAL(tokenizerConfigUpdated()), this, SLOT(tokenizerConfigUpdatedSlot()));
connect(this, SIGNAL(contextMenuSignal(QPoint)), this, SLOT(contextMenuSlot(QPoint)));
connect(this, SIGNAL(doubleClickedSignal()), this, SLOT(followBreakpointSlot()));
connect(this, SIGNAL(enterPressedSignal()), this, SLOT(followBreakpointSlot()));
Initialize();
}
void BreakpointsView::setupContextMenu()
{
mMenuBuilder = new MenuBuilder(this, [](QMenu*)
{
return DbgIsDebugging();
});
auto validBp = [this](QMenu*)
{
return isValidBp();
};
mMenuBuilder->addAction(makeAction(DIcon(ArchValue("processor32", "processor64")), tr("Follow breakpoint"), SLOT(followBreakpointSlot())), [this](QMenu*)
{
if(!isValidBp())
return false;
if(selectedBp().type == bp_exception)
return false;
return true;
});
mMenuBuilder->addAction(makeShortcutAction(DIcon("breakpoint_remove"), tr("&Remove"), SLOT(removeBreakpointSlot()), "ActionDeleteBreakpoint"), validBp);
QAction* enableDisableBreakpoint = makeShortcutAction(DIcon("breakpoint_disable"), tr("Disable"), SLOT(toggleBreakpointSlot()), "ActionEnableDisableBreakpoint");
mMenuBuilder->addAction(enableDisableBreakpoint, [this, enableDisableBreakpoint](QMenu*)
{
if(!isValidBp() || !selectedBp().active)
return false;
if(selectedBp().enabled)
{
enableDisableBreakpoint->setIcon(DIcon("breakpoint_disable"));
enableDisableBreakpoint->setText(tr("Disable"));
}
else
{
enableDisableBreakpoint->setIcon(DIcon("breakpoint_enable"));
enableDisableBreakpoint->setText(tr("Enable"));
}
return true;
});
mMenuBuilder->addAction(makeShortcutAction(DIcon("breakpoint_edit_alt"), tr("&Edit"), SLOT(editBreakpointSlot()), "ActionEditBreakpoint"), validBp);
mMenuBuilder->addAction(makeShortcutAction(DIcon("breakpoint_reset_hitcount"), tr("Reset hit count"), SLOT(resetHitCountBreakpointSlot()), "ActionResetHitCountBreakpoint"), [this](QMenu*)
{
if(!isValidBp())
return false;
return selectedBp().hitCount > 0;
});
mMenuBuilder->addSeparator();
QAction* enableAll = makeShortcutAction(DIcon("breakpoint_enable_all"), QString(), SLOT(enableAllBreakpointsSlot()), "ActionEnableAllBreakpoints");
mMenuBuilder->addAction(enableAll, [this, enableAll](QMenu*)
{
if(!isValidBp())
return false;
enableAll->setText(tr("Enable all (%1)").arg(bpTypeName(selectedBp().type)));
return true;
});
QAction* disableAll = makeShortcutAction(DIcon("breakpoint_disable_all"), QString(), SLOT(disableAllBreakpointsSlot()), "ActionDisableAllBreakpoints");
mMenuBuilder->addAction(disableAll, [this, disableAll](QMenu*)
{
if(!isValidBp())
return false;
disableAll->setText(tr("Disable all (%1)").arg(bpTypeName(selectedBp().type)));
return true;
});
QAction* removeAll = makeShortcutAction(DIcon("breakpoint_remove_all"), QString(), SLOT(removeAllBreakpointsSlot()), "ActionRemoveAllBreakpoints");
mMenuBuilder->addAction(removeAll, [this, removeAll](QMenu*)
{
if(!isValidBp())
return false;
removeAll->setText(tr("Remove all (%1)").arg(bpTypeName(selectedBp().type)));
return true;
});
mMenuBuilder->addSeparator();
mMenuBuilder->addAction(makeAction(DIcon("breakpoint_module_add"), tr("Add DLL breakpoint"), SLOT(addDllBreakpointSlot())));
mMenuBuilder->addAction(makeAction(DIcon("breakpoint_exception_add"), tr("Add exception breakpoint"), SLOT(addExceptionBreakpointSlot())));
mMenuBuilder->addSeparator();
mMenuBuilder->addAction(makeAction(tr("Copy breakpoint conditions"), SLOT(copyConditionalBreakpointSlot())));
mMenuBuilder->addAction(makeAction(tr("Paste breakpoint conditions"), SLOT(pasteConditionalBreakpointSlot())), [](QMenu*)
{
return QApplication::clipboard()->text().size() > 10;
});
MenuBuilder* copyMenu = new MenuBuilder(this);
setupCopyMenu(copyMenu);
mMenuBuilder->addMenu(makeMenu(DIcon("copy"), tr("&Copy")), copyMenu);
}
void BreakpointsView::updateColors()
{
StdTable::updateColors();
mDisasmBackgroundColor = ConfigColor("DisassemblyBackgroundColor");
mDisasmSelectionColor = ConfigColor("DisassemblySelectionColor");
mCipBackgroundColor = ConfigColor("ThreadCurrentBackgroundColor");
mCipColor = ConfigColor("ThreadCurrentColor");
mSummaryParenColor = ConfigColor("BreakpointSummaryParenColor");
mSummaryKeywordColor = ConfigColor("BreakpointSummaryKeywordColor");
mSummaryStringColor = ConfigColor("BreakpointSummaryStringColor");
mDisasm->UpdateConfig();
updateBreakpointsSlot();
}
void BreakpointsView::sortRows(int column, bool ascending)
{
std::stable_sort(mData.begin(), mData.end(), [this, column, ascending](const std::vector<CellData> & a, const std::vector<CellData> & b)
{
//this function sorts on header type first and then on column content
auto aBp = &mBps.at(a.at(ColAddr).userdata), bBp = &mBps.at(b.at(ColAddr).userdata);
auto aType = aBp->type, bType = bBp->type;
auto aHeader = aBp->addr || aBp->active, bHeader = bBp->addr || bBp->active;
struct Hax
{
const bool & greater;
const QString & s;
Hax(const bool & greater, const QString & s) : greater(greater), s(s) { }
bool operator<(const Hax & b)
{
return greater ? s > b.s : s < b.s;
}
} aHax(!ascending, a.at(column).text), bHax(!ascending, b.at(column).text);
return std::tie(aType, aHeader, aHax) < std::tie(bType, bHeader, bHax);
});
}
QString BreakpointsView::paintContent(QPainter* painter, dsint rowBase, int rowOffset, int col, int x, int y, int w, int h)
{
if(isSelected(rowBase, rowOffset))
painter->fillRect(QRect(x, y, w, h), QBrush(col == ColDisasm ? mDisasmSelectionColor : mSelectionColor));
else if(col == ColDisasm)
painter->fillRect(QRect(x, y, w, h), QBrush(mDisasmBackgroundColor));
auto index = bpIndex(rowBase + rowOffset);
auto & bp = mBps.at(index);
auto cellContent = getCellContent(rowBase + rowOffset, col);
if(col > ColType && !bp.addr && !bp.active)
{
auto mid = h / 2.0;
painter->drawLine(QPointF(x, y + mid), QPointF(x + w, y + mid));
}
else if(col == ColAddr)
{
if(bp.type == bp_dll || bp.type == bp_exception)
return cellContent;
else if(bp.addr && bp.addr == mCip)
{
painter->fillRect(QRect(x, y, w, h), QBrush(mCipBackgroundColor));
painter->setPen(QPen(mCipColor));
painter->drawText(QRect(x + 4, y, w - 4, h), Qt::AlignVCenter | Qt::AlignLeft, cellContent);
return QString();
}
}
else if(col == ColDisasm)
{
RichTextPainter::paintRichText(painter, x + 4, y, w - 4, h, 0, mRich.at(index).first, mFontMetrics);
return QString();
}
else if(col == ColSummary)
{
RichTextPainter::paintRichText(painter, x + 4, y, w - 4, h, 0, mRich.at(index).second, mFontMetrics);
return QString();
}
return cellContent;
}
void BreakpointsView::updateBreakpointsSlot()
{
if(mExceptionMap.empty() && DbgFunctions()->EnumExceptions)
{
BridgeList<CONSTANTINFO> exceptions;
DbgFunctions()->EnumExceptions(&exceptions);
for(int i = 0; i < exceptions.Count(); i++)
{
mExceptionMap.insert({exceptions[i].value, exceptions[i].name});
mExceptionList.append(QString(exceptions[i].name));
mExceptionMaxLength = std::max(mExceptionMaxLength, int(strlen(exceptions[i].name)));
}
mExceptionList.sort();
}
BPMAP bpmap;
DbgGetBpList(bp_none, &bpmap);
setRowCount(bpmap.count);
mBps.clear();
mBps.reserve(bpmap.count + 5);
mRich.clear();
mRich.reserve(bpmap.count + 5);
BPXTYPE lasttype = bp_none;
for(int i = 0, row = 0; i < bpmap.count; i++, row++)
{
BRIDGEBP & bp = bpmap.bp[i];
if(lasttype != bp.type)
{
lasttype = bp.type;
setRowCount(getRowCount() + 1);
setCellContent(row, ColType, bpTypeName(bp.type));
setCellUserdata(row, ColType, bp.type);
setCellContent(row, ColHits, QString());
setCellContent(row, ColAddr, QString());
setCellUserdata(row, ColAddr, row);
setCellContent(row, ColModLabel, QString());
setCellContent(row, ColState, QString());
setCellContent(row, ColDisasm, QString());
setCellContent(row, ColSummary, QString());
row++;
BRIDGEBP fakebp;
memset(&fakebp, 0, sizeof(fakebp));
fakebp.type = lasttype;
mBps.push_back(fakebp);
mRich.push_back(std::make_pair(RichTextPainter::List(), RichTextPainter::List()));
}
mBps.push_back(bp);
RichTextPainter::List richSummary, richDisasm;
auto addrText = [&]()
{
if(bp.type == bp_dll)
{
auto base = DbgModBaseFromName(bp.mod);
if(!base)
base = -1;
return ToPtrString(base);
}
else
return ToPtrString(bp.addr);
};
auto modLabelText = [&]() -> QString
{
char label[MAX_LABEL_SIZE] = "";
if(bp.type == bp_exception)
{
auto found = mExceptionMap.find(bp.addr);
return found == mExceptionMap.end() ? "" : found->second;
}
else if(bp.type != bp_dll && DbgGetLabelAt(bp.addr, SEG_DEFAULT, label))
return QString("<%1.%2>").arg(bp.mod, label);
else
return bp.mod;
};
auto stateName = [&]()
{
if(!bp.active)
return tr("Inactive");
if(bp.enabled)
return bp.singleshoot ? tr("One-time") : tr("Enabled");
else
return tr("Disabled");
};
auto disasmText = [&]() -> QString
{
QString result;
if(!bp.active || bp.type == bp_dll || bp.type == bp_exception)
return result;
byte_t data[MAX_DISASM_BUFFER];
if(DbgMemRead(bp.addr, data, sizeof(data)))
{
auto instr = mDisasm->DisassembleAt(data, sizeof(data), 0, bp.addr);
ZydisTokenizer::TokenToRichText(instr.tokens, richDisasm, 0);
for(auto & token : richDisasm)
result += token.text;
}
else
{
RichTextPainter::CustomRichText_t err;
err.text = "Failed to read: " + ToPtrString(bp.addr);
richDisasm.push_back(err);
return err.text;
}
return result;
};
//memory/hardware/dll/exception type, name, address comment, condition, log(text+condition), command(text+condition)
auto summaryText = [&]()
{
auto colored = [&richSummary](QString text, QColor color)
{
RichTextPainter::CustomRichText_t token;
token.underline = false;
token.flags = RichTextPainter::FlagColor;
token.textColor = color;
token.text = text;
richSummary.push_back(token);
};
auto text = [this, &richSummary](QString text)
{
RichTextPainter::CustomRichText_t token;
token.underline = false;
token.flags = RichTextPainter::FlagColor;
token.textColor = this->mTextColor;
token.text = text;
richSummary.push_back(token);
};
auto next = [&richSummary, &text]()
{
if(!richSummary.empty())
text(", ");
};
char comment[MAX_COMMENT_SIZE];
if(bp.type != bp_dll && bp.type != bp_exception && DbgGetCommentAt(bp.addr, comment) && *comment != '\1')
{
next();
colored(comment, mSummaryStringColor);
}
else if(*bp.name)
{
next();
colored(bp.name, mSummaryStringColor);
}
switch(bp.type)
{
case bp_normal:
break;
case bp_hardware:
{
auto size = [](BPHWSIZE size)
{
switch(size)
{
case hw_byte:
return tr("byte");
case hw_word:
return tr("word");
case hw_dword:
return tr("dword");
case hw_qword:
return tr("qword");
default:
return QString();
}
}(BPHWSIZE(bp.hwSize));
switch(bp.typeEx)
{
case hw_access:
next();
colored(tr("access"), mSummaryKeywordColor);
colored("(", mSummaryParenColor);
text(size);
colored(")", mSummaryParenColor);
break;
case hw_write:
next();
colored(tr("write"), mSummaryKeywordColor);
colored("(", mSummaryParenColor);
text(size);
colored(")", mSummaryParenColor);
break;
case hw_execute:
next();
colored(tr("execute"), mSummaryKeywordColor);
colored("()", mSummaryParenColor);
break;
}
}
break;
case bp_memory:
{
auto op = [](BPMEMTYPE type)
{
switch(type)
{
case mem_access:
return tr("access");
case mem_read:
return tr("read");
case mem_write:
return tr("write");
case mem_execute:
return tr("execute");
default:
return QString();
}
}(BPMEMTYPE(bp.typeEx));
next();
colored(op, mSummaryKeywordColor);
colored("(", mSummaryParenColor);
text(ToHexString(DbgFunctions()->MemBpSize(bp.addr)));
colored(")", mSummaryParenColor);
}
break;
case bp_dll:
switch(bp.typeEx)
{
case dll_load:
next();
colored(tr("load"), mSummaryKeywordColor);
colored("()", mSummaryParenColor);
break;
case dll_unload:
next();
colored(tr("unload"), mSummaryKeywordColor);
colored("()", mSummaryParenColor);
break;
case dll_all:
next();
colored(tr("all"), mSummaryKeywordColor);
colored("()", mSummaryParenColor);
break;
}
break;
case bp_exception:
switch(bp.typeEx)
{
case ex_firstchance:
next();
colored(tr("firstchance"), mSummaryKeywordColor);
colored("()", mSummaryParenColor);
break;
case ex_secondchance:
next();
colored(tr("secondchance"), mSummaryKeywordColor);
colored("()", mSummaryParenColor);
break;
case ex_all:
next();
colored(tr("anychance"), mSummaryKeywordColor);
colored("()", mSummaryParenColor);
break;
}
break;
default:
return QString();
}
if(*bp.breakCondition)
{
next();
colored(tr("breakif"), mSummaryKeywordColor);
colored("(", mSummaryParenColor);
text(bp.breakCondition);
colored(")", mSummaryParenColor);
}
if(bp.fastResume)
{
next();
colored(tr("fastresume"), mSummaryKeywordColor);
colored("()", mSummaryParenColor);
}
else //fast resume skips all other steps
{
if(*bp.logText)
{
next();
if(*bp.logCondition)
{
colored(tr("logif"), mSummaryKeywordColor);
colored("(", mSummaryParenColor);
text(bp.logCondition);
colored(",", mSummaryParenColor);
text(" ");
}
else
{
colored(tr("log"), mSummaryKeywordColor);
colored("(", mSummaryParenColor);
}
colored(QString("\"%1\"").arg(bp.logText), mSummaryStringColor);
colored(")", mSummaryParenColor);
}
if(*bp.commandText)
{
next();
if(*bp.commandCondition)
{
colored(tr("cmdif"), mSummaryKeywordColor);
colored("(", mSummaryParenColor);
text(bp.commandCondition);
colored(",", mSummaryParenColor);
text(" ");
}
else
{
colored(tr("cmd"), mSummaryKeywordColor);
colored("(", mSummaryParenColor);
}
colored(QString("\"%1\"").arg(bp.commandText), mSummaryStringColor);
colored(")", mSummaryParenColor);
}
}
QString result;
for(auto & token : richSummary)
result += token.text;
return result;
};
setCellContent(row, ColType, QString());
setCellUserdata(row, ColType, bp.type);
setCellContent(row, ColAddr, addrText());
setCellUserdata(row, ColAddr, row);
setCellContent(row, ColModLabel, modLabelText());
setCellContent(row, ColState, stateName());
setCellContent(row, ColDisasm, disasmText());
setCellContent(row, ColHits, QString("%1").arg(bp.hitCount));
setCellContent(row, ColSummary, summaryText());
mRich.push_back(std::make_pair(std::move(richDisasm), std::move(richSummary)));
}
if(bpmap.count)
{
BridgeFree(bpmap.bp);
auto sel = getInitialSelection();
auto rows = getRowCount();
if(sel >= rows)
setSingleSelection(rows - 1);
}
reloadData();
}
void BreakpointsView::disassembleAtSlot(dsint addr, dsint cip)
{
Q_UNUSED(addr);
mCip = cip;
}
void BreakpointsView::tokenizerConfigUpdatedSlot()
{
mDisasm->UpdateConfig();
updateBreakpointsSlot();
}
void BreakpointsView::contextMenuSlot(const QPoint & pos)
{
QMenu wMenu(this);
mMenuBuilder->build(&wMenu);
if(!wMenu.actions().isEmpty())
wMenu.exec(mapToGlobal(pos));
}
void BreakpointsView::followBreakpointSlot()
{
if(!isValidBp())
return;
auto & bp = selectedBp();
if(bp.type == bp_exception || !bp.active)
{
GuiAddStatusBarMessage(tr("Cannot follow this breakpoint.\n").toUtf8().constData());
return;
}
duint addr = bp.type == bp_dll ? DbgModBaseFromName(bp.mod) : bp.addr;
if(!DbgMemIsValidReadPtr(addr))
{
GuiAddStatusBarMessage(tr("Cannot follow this breakpoint.\n").toUtf8().constData());
return;
}
if(DbgFunctions()->MemIsCodePage(addr, false))
DbgCmdExecDirect(QString("disasm %1").arg(ToPtrString(addr)));
else
{
DbgCmdExecDirect(QString("dump %1").arg(ToPtrString(addr)));
emit Bridge::getBridge()->getDumpAttention();
}
}
void BreakpointsView::removeBreakpointSlot()
{
GuiDisableUpdateScope s;
for(int i : getSelection())
{
if(isValidBp(i))
{
const BRIDGEBP & bp = selectedBp(i);
Breakpoints::removeBP(bp);
}
}
}
void BreakpointsView::toggleBreakpointSlot()
{
GuiDisableUpdateScope s;
for(int i : getSelection())
if(isValidBp(i) && selectedBp(i).active)
Breakpoints::toggleBPByDisabling(selectedBp(i));
}
void BreakpointsView::editBreakpointSlot()
{
if(!isValidBp())
return;
const BRIDGEBP & bp = selectedBp();
if(bp.type == bp_dll)
{
Breakpoints::editBP(bp_dll, bp.mod, this);
}
else if(bp.active || bp.type == bp_exception)
{
Breakpoints::editBP(bp.type, ToPtrString(bp.addr), this);
}
else
{
QString addrText = QString().sprintf("\"%s\":$%X", bp.mod, bp.addr);
EditBreakpointDialog dialog(this, bp);
if(dialog.exec() != QDialog::Accepted)
return;
auto exec = [](const QString & command)
{
DbgCmdExecDirect(command);
};
const BRIDGEBP & newBp = dialog.getBp();
switch(bp.type)
{
case bp_normal:
exec(QString("SetBreakpointName %1, \"%2\"").arg(addrText).arg(newBp.name));
exec(QString("SetBreakpointCondition %1, \"%2\"").arg(addrText).arg(newBp.breakCondition));
exec(QString("SetBreakpointLog %1, \"%2\"").arg(addrText).arg(newBp.logText));
exec(QString("SetBreakpointLogCondition %1, \"%2\"").arg(addrText).arg(newBp.logCondition));
exec(QString("SetBreakpointCommand %1, \"%2\"").arg(addrText).arg(newBp.commandText));
exec(QString("SetBreakpointCommandCondition %1, \"%2\"").arg(addrText).arg(newBp.commandCondition));
exec(QString("ResetBreakpointHitCount %1, %2").arg(addrText).arg(ToPtrString(newBp.hitCount)));
exec(QString("SetBreakpointFastResume %1, %2").arg(addrText).arg(newBp.fastResume));
exec(QString("SetBreakpointSilent %1, %2").arg(addrText).arg(newBp.silent));
exec(QString("SetBreakpointSingleshoot %1, %2").arg(addrText).arg(newBp.singleshoot));
break;
case bp_hardware:
exec(QString("SetHardwareBreakpointName %1, \"%2\"").arg(addrText).arg(newBp.name));
exec(QString("SetHardwareBreakpointCondition %1, \"%2\"").arg(addrText).arg(newBp.breakCondition));
exec(QString("SetHardwareBreakpointLog %1, \"%2\"").arg(addrText).arg(newBp.logText));
exec(QString("SetHardwareBreakpointLogCondition %1, \"%2\"").arg(addrText).arg(newBp.logCondition));
exec(QString("SetHardwareBreakpointCommand %1, \"%2\"").arg(addrText).arg(newBp.commandText));
exec(QString("SetHardwareBreakpointCommandCondition %1, \"%2\"").arg(addrText).arg(newBp.commandCondition));
exec(QString("ResetHardwareBreakpointHitCount %1, %2").arg(addrText).arg(ToPtrString(newBp.hitCount)));
exec(QString("SetHardwareBreakpointFastResume %1, %2").arg(addrText).arg(newBp.fastResume));
exec(QString("SetHardwareBreakpointSilent %1, %2").arg(addrText).arg(newBp.silent));
exec(QString("SetHardwareBreakpointSingleshoot %1, %2").arg(addrText).arg(newBp.singleshoot));
break;
case bp_memory:
exec(QString("SetMemoryBreakpointName %1, \"\"%2\"\"").arg(addrText).arg(newBp.name));
exec(QString("SetMemoryBreakpointCondition %1, \"%2\"").arg(addrText).arg(newBp.breakCondition));
exec(QString("SetMemoryBreakpointLog %1, \"%2\"").arg(addrText).arg(newBp.logText));
exec(QString("SetMemoryBreakpointLogCondition %1, \"%2\"").arg(addrText).arg(newBp.logCondition));
exec(QString("SetMemoryBreakpointCommand %1, \"%2\"").arg(addrText).arg(newBp.commandText));
exec(QString("SetMemoryBreakpointCommandCondition %1, \"%2\"").arg(addrText).arg(newBp.commandCondition));
exec(QString("ResetMemoryBreakpointHitCount %1, %2").arg(addrText).arg(ToPtrString(newBp.hitCount)));
exec(QString("SetMemoryBreakpointFastResume %1, %2").arg(addrText).arg(newBp.fastResume));
exec(QString("SetMemoryBreakpointSilent %1, %2").arg(addrText).arg(newBp.silent));
exec(QString("SetMemoryBreakpointSingleshoot %1, %2").arg(addrText).arg(newBp.singleshoot));
break;
default:
break;
}
}
}
void BreakpointsView::resetHitCountBreakpointSlot()
{
GuiDisableUpdateScope s;
for(int i : getSelection())
{
if(!isValidBp(i))
continue;
auto & bp = selectedBp(i);
DbgCmdExec([&bp]()
{
switch(bp.type)
{
case bp_normal:
return QString("ResetBreakpointHitCount %1").arg(ToPtrString(bp.addr));
case bp_hardware:
return QString("ResetHardwareBreakpointHitCount %1").arg(ToPtrString(bp.addr));
case bp_memory:
return QString("ResetMemoryBreakpointHitCount %1").arg(ToPtrString(bp.addr));
case bp_dll:
return QString("ResetLibrarianBreakpointHitCount \"%1\"").arg(bp.mod);
case bp_exception:
return QString("ResetExceptionBreakpointHitCount %1").arg(ToHexString(bp.addr));
default:
return QString("invalid");
}
}());
QString cmd;
DbgCmdExecDirect(cmd);
}
}
void BreakpointsView::enableAllBreakpointsSlot()
{
if(mBps.empty())
return;
DbgCmdExec([this]()
{
switch(selectedBp().type)
{
case bp_normal:
return "bpe";
case bp_hardware:
return "bphwe";
case bp_memory:
return "bpme";
case bp_dll:
return "bpdll";
case bp_exception:
return "EnableExceptionBPX";
default:
return "invalid";
}
}());
}
void BreakpointsView::disableAllBreakpointsSlot()
{
if(mBps.empty())
return;
DbgCmdExec([this]()
{
switch(selectedBp().type)
{
case bp_normal:
return "bpd";
case bp_hardware:
return "bphwd";
case bp_memory:
return "bpmd";
case bp_dll:
return "bpddll";
case bp_exception:
return "DisableExceptionBPX";
default:
return "invalid";
}
}());
}
void BreakpointsView::removeAllBreakpointsSlot()
{
if(mBps.empty())
return;
DbgCmdExec([this]()
{
switch(selectedBp().type)
{
case bp_normal:
return "bc";
case bp_hardware:
return "bphwc";
case bp_memory:
return "bpmc";
case bp_dll:
return "bcdll";
case bp_exception:
return "DeleteExceptionBPX";
default:
return "invalid";
}
}());
}
void BreakpointsView::addDllBreakpointSlot()
{
QString fileName;
if(SimpleInputBox(this, tr("Enter the module name"), "", fileName, tr("Example: mydll.dll"), &DIcon("breakpoint")) && !fileName.isEmpty())
DbgCmdExec(QString("bpdll \"%1\"").arg(fileName));
}
void BreakpointsView::addExceptionBreakpointSlot()
{
QString exception;
if(SimpleChoiceBox(this, tr("Enter the exception code"), "", mExceptionList, exception, true, tr("Example: EXCEPTION_ACCESS_VIOLATION"), &DIcon("breakpoint"), mExceptionMaxLength) && !exception.isEmpty())
DbgCmdExec((QString("SetExceptionBPX ") + exception));
}
static QString escape(QString data)
{
//data = data.replace("\\", "\\\\");
data = data.replace("\"", "\\\"");
return data;
}
void BreakpointsView::copyConditionalBreakpointSlot()
{
BRIDGEBP bp = selectedBp();
const char* bpcnd;
const char* bplog;
const char* bpcmd;
const char* bplogcnd;
const char* bpcmdcnd;
const char* bpfastresume;
const char* bpsilent;
const char* bpsingleshoot;
switch(bp.type)
{
case bp_normal:
bpcnd = "bpcnd %1, \"%2\"";
bplog = "bpl %1, \"%2\"";
bpcmd = "SetBreakpointCommand %1, \"%2\"";
bplogcnd = "bplogcondition %1, \"%2\"";
bpcmdcnd = "SetBreakpointCommandCondition %1, \"%2\"";
bpfastresume = "SetBreakpointFastResume ";
bpsilent = "SetBreakpointSilent ";
bpsingleshoot = "SetBreakpointSingleshoot ";
break;
case bp_hardware:
bpcnd = "bphwcond %1, \"%2\"";
bplog = "bphwlog %1, \"%2\"";
bpcmd = "SetHardwareBreakpointCommand %1, \"%2\"";
bplogcnd = "bphwlogcondition %1, \"%2\"";
bpcmdcnd = "SetHardwareBreakpointCommandCondition %1, \"%2\"";
bpfastresume = "SetHardwareBreakpointFastResume ";
bpsilent = "SetHardwareBreakpointSilent ";
bpsingleshoot = "SetHardwareBreakpointSingleshoot ";
break;
case bp_memory:
bpcnd = "bpmcond %1, \"%2\"";
bplog = "bpml %1, \"%2\"";
bpcmd = "SetMemoryBreakpointCommand %1, \"%2\"";
bplogcnd = "bpmlogcondition %1, \"%2\"";
bpcmdcnd = "SetMemoryBreakpointCommandCondition %1, \"%2\"";
bpfastresume = "SetMemoryBreakpointFastResume ";
bpsilent = "SetMemoryBreakpointSilent ";
bpsingleshoot = "SetMemoryBreakpointSingleshoot ";
break;
case bp_dll:
bpcnd = "SetLibrarianBreakpointCondition %1, \"%2\"";
bplog = "SetLibrarianBreakpointLog %1, \"%2\"";
bpcmd = "SetLibrarianBreakpointCommand %1, \"%2\"";
bplogcnd = "SetLibrarianBreakpointLogCondition %1, \"%2\"";
bpcmdcnd = "SetLibrarianBreakpointCommandCondition %1, \"%2\"";
bpfastresume = "SetLibrarianBreakpointFastResume ";
bpsilent = "SetLibrarianBreakpointSilent ";
bpsingleshoot = "SetLibrarianBreakpointSingleshoot ";
break;
case bp_exception:
bpcnd = "SetExceptionBreakpointCondition %1, \"%2\"";
bplog = "SetExceptionBreakpointLog %1, \"%2\"";
bpcmd = "SetExceptionBreakpointCommand %1, \"%2\"";
bplogcnd = "SetExceptionBreakpointLogCondition %1, \"%2\"";
bpcmdcnd = "SetExceptionBreakpointCommandCondition %1, \"%2\"";
bpfastresume = "SetExceptionBreakpointFastResume ";
bpsilent = "SetExceptionBreakpointSilent ";
bpsingleshoot = "SetExceptionBreakpointSingleshoot ";
break;
default:
return;
}
QString text;
QString addr;
if(bp.type != bp_dll)
addr = ToPtrString(bp.addr);
else
addr = '"' + escape(bp.mod) + '"';
QTextStream s(&text, QIODevice::WriteOnly);
s << QString(bpcnd).arg(addr).arg(escape(bp.breakCondition)) << "\r\n";
s << QString(bplog).arg(addr).arg(escape(bp.logText)) << "\r\n";
s << QString(bplogcnd).arg(addr).arg(escape(bp.logCondition)) << "\r\n";
s << QString(bpcmd).arg(addr).arg(escape(bp.commandText)) << "\r\n";
s << QString(bpcmdcnd).arg(addr).arg(escape(bp.commandCondition)) << "\r\n";
addr += ", ";
s << bpfastresume << addr << (bp.fastResume ? '1' : '0') << "\r\n";
s << bpsilent << addr << (bp.silent ? '1' : '0') << "\r\n";
s << bpsingleshoot << addr << (bp.singleshoot ? '1' : '0') << "\r\n";
Bridge::CopyToClipboard(text);
}
void BreakpointsView::pasteConditionalBreakpointSlot()
{
//TO DO perform a validation
QClipboard* clipboard = QApplication::clipboard();
QString text = clipboard->text();
QRegExp regexp(ArchValue("(\\w+) ([\\dA-F]{8}),", "(\\w+) ([\\dA-F]{16}),"), Qt::CaseInsensitive);
GuiDisableUpdateScope s;
for(int i : getSelection())
{
if(!isValidBp(i))
continue;
auto & bp = selectedBp(i);
QString text1 = text.replace(regexp, "\\1 " + ToPtrString(bp.addr) + ",");
QList<QString> cmds;
cmds = text1.split("\r\n");
for(const auto & j : cmds)
DbgCmdExecDirect(j.toUtf8().constData());
}
} |
C/C++ | x64dbg-development/src/gui/Src/Gui/BreakpointsView.h | #pragma once
#include <QWidget>
#include "Bridge.h"
#include "StdTable.h"
#include "QBeaEngine.h"
class MenuBuilder;
class BreakpointsView : public StdTable
{
Q_OBJECT
public:
explicit BreakpointsView(QWidget* parent = 0);
protected:
void setupContextMenu();
void updateColors() override;
void sortRows(int column, bool ascending) override;
QString paintContent(QPainter* painter, dsint rowBase, int rowOffset, int col, int x, int y, int w, int h) override;
private slots:
void updateBreakpointsSlot();
void disassembleAtSlot(dsint addr, dsint cip);
void tokenizerConfigUpdatedSlot();
void contextMenuSlot(const QPoint & pos);
void followBreakpointSlot();
void removeBreakpointSlot();
void toggleBreakpointSlot();
void editBreakpointSlot();
void resetHitCountBreakpointSlot();
void enableAllBreakpointsSlot();
void disableAllBreakpointsSlot();
void removeAllBreakpointsSlot();
void addDllBreakpointSlot();
void addExceptionBreakpointSlot();
void copyConditionalBreakpointSlot();
void pasteConditionalBreakpointSlot();
private:
enum
{
ColType,
ColAddr,
ColModLabel,
ColState,
ColDisasm,
ColHits,
ColSummary
};
std::unordered_map<duint, const char*> mExceptionMap;
QStringList mExceptionList;
int mExceptionMaxLength;
std::vector<BRIDGEBP> mBps;
std::vector<std::pair<RichTextPainter::List, RichTextPainter::List>> mRich;
QColor mDisasmBackgroundColor;
QColor mDisasmSelectionColor;
QColor mCipBackgroundColor;
QColor mCipColor;
QColor mSummaryParenColor;
QColor mSummaryKeywordColor;
QColor mSummaryStringColor;
duint mCip = 0;
MenuBuilder* mMenuBuilder;
QAction* mEnableDisableAction;
QBeaEngine* mDisasm;
const int bpIndex(int i) const
{
return mData.at(i).at(ColAddr).userdata;
}
const BRIDGEBP & selectedBp(int index = -1) const
{
if(index == -1)
index = getInitialSelection();
return mBps.at(bpIndex(index));
}
bool isValidBp(int sel = -1)
{
if(sel == -1)
sel = getInitialSelection();
if(!DbgIsDebugging() || mBps.empty() || !isValidIndex(sel, ColType))
return false;
auto & bp = mBps.at(bpIndex(sel));
return bp.addr != 0 || bp.active;
}
QString bpTypeName(BPXTYPE type) const
{
switch(type)
{
case bp_normal:
return tr("Software");
case bp_hardware:
return tr("Hardware");
case bp_memory:
return tr("Memory");
case bp_dll:
return tr("DLL");
case bp_exception:
return tr("Exception");
default:
return QString();
}
}
}; |
C++ | x64dbg-development/src/gui/Src/Gui/BrowseDialog.cpp | #include "BrowseDialog.h"
#include "ui_BrowseDialog.h"
#include "MiscUtil.h"
#include <QDirModel>
#include <QCompleter>
#include <QFileDialog>
#include <Configuration.h>
BrowseDialog::BrowseDialog(QWidget* parent, const QString & title, const QString & text, const QString & filter, const QString & defaultPath, bool save) :
QDialog(parent),
ui(new Ui::BrowseDialog), mFilter(filter), mSave(save)
{
ui->setupUi(this);
setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint | Qt::MSWindowsFixedSizeDialogHint);
setWindowTitle(title);
ui->label->setText(text);
auto nativePath = QDir::toNativeSeparators(defaultPath);
ui->lineEdit->setText(nativePath);
// Select the filename when saving
auto lastSlashIdx = nativePath.lastIndexOf(QDir::separator());
if(save && !QFileInfo(nativePath).isDir() && lastSlashIdx != -1)
{
auto periodIdx = nativePath.lastIndexOf('.');
if(periodIdx == -1)
periodIdx = nativePath.length();
ui->lineEdit->setSelection(lastSlashIdx + 1, periodIdx - lastSlashIdx - 1);
}
QCompleter* completer = new QCompleter(ui->lineEdit);
completer->setModel(new QDirModel(completer));
ui->lineEdit->setCompleter(completer);
Config()->loadWindowGeometry(this);
}
BrowseDialog::~BrowseDialog()
{
Config()->saveWindowGeometry(this);
delete ui;
}
void BrowseDialog::on_browse_clicked()
{
QString file;
if(mSave)
file = QFileDialog::getSaveFileName(this, ui->label->text(), ui->lineEdit->text(), mFilter);
else
file = QFileDialog::getOpenFileName(this, ui->label->text(), ui->lineEdit->text(), mFilter);
if(file.size() != 0)
ui->lineEdit->setText(QDir::toNativeSeparators(file));
}
void BrowseDialog::on_ok_clicked()
{
path = ui->lineEdit->text();
accept();
} |
C/C++ | x64dbg-development/src/gui/Src/Gui/BrowseDialog.h | #pragma once
#include <QDialog>
namespace Ui
{
class BrowseDialog;
}
class BrowseDialog : public QDialog
{
Q_OBJECT
public:
BrowseDialog(QWidget* parent, const QString & title, const QString & text, const QString & filter, const QString & defaultPath, bool save);
~BrowseDialog();
QString path;
public slots:
void on_browse_clicked();
void on_ok_clicked();
private:
Ui::BrowseDialog* ui;
QString mFilter;
bool mSave;
}; |
User Interface | x64dbg-development/src/gui/Src/Gui/BrowseDialog.ui | <?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>BrowseDialog</class>
<widget class="QDialog" name="BrowseDialog">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>487</width>
<height>97</height>
</rect>
</property>
<property name="windowTitle">
<string>Dialog</string>
</property>
<layout class="QVBoxLayout" name="verticalLayout">
<item>
<widget class="QLabel" name="label">
<property name="text">
<string>Please input the file path.</string>
</property>
</widget>
</item>
<item>
<layout class="QHBoxLayout" name="horizontalLayout">
<item>
<widget class="QLabel" name="label_2">
<property name="text">
<string>Path:</string>
</property>
<property name="buddy">
<cstring>lineEdit</cstring>
</property>
</widget>
</item>
<item>
<widget class="QLineEdit" name="lineEdit"/>
</item>
<item>
<widget class="QPushButton" name="browse">
<property name="text">
<string>&Browse...</string>
</property>
</widget>
</item>
</layout>
</item>
<item>
<layout class="QHBoxLayout" name="horizontalLayout_2">
<item>
<spacer name="horizontalSpacer">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>40</width>
<height>20</height>
</size>
</property>
</spacer>
</item>
<item>
<widget class="QPushButton" name="ok">
<property name="text">
<string>&OK</string>
</property>
<property name="default">
<bool>true</bool>
</property>
</widget>
</item>
<item>
<widget class="QPushButton" name="cancel">
<property name="text">
<string>&Cancel</string>
</property>
</widget>
</item>
</layout>
</item>
</layout>
</widget>
<resources/>
<connections>
<connection>
<sender>cancel</sender>
<signal>clicked()</signal>
<receiver>BrowseDialog</receiver>
<slot>reject()</slot>
<hints>
<hint type="sourcelabel">
<x>439</x>
<y>75</y>
</hint>
<hint type="destinationlabel">
<x>243</x>
<y>48</y>
</hint>
</hints>
</connection>
</connections>
</ui> |
C++ | x64dbg-development/src/gui/Src/Gui/CalculatorDialog.cpp | #include "CalculatorDialog.h"
#include "ui_CalculatorDialog.h"
#include "ValidateExpressionThread.h"
static duint bswap(duint value)
{
duint result = 0;
for(size_t i = 0; i < sizeof(value); i++)
((unsigned char*)&result)[sizeof(value) - i - 1] = ((unsigned char*)&value)[i];
return result;
}
QString CalculatorDialog::inFormat(const duint val, CalculatorDialog::Format format) const
{
switch(format)
{
default:
case Format::Hex:
return QString("%1").arg(val, 1, 16, QChar('0')).toUpper();
case Format::SignedDec:
return QString("%1").arg((dsint)val);
case Format::UnsignedDec:
return QString("%1").arg(val);
case Format::Binary:
{
QString binary = QString("%1").arg(val, 8 * sizeof(duint), 2, QChar('0')).toUpper();
QString ans = "";
for(int i = 0; i < sizeof(duint) * 8; i++)
{
if((i % 4 == 0) && (i != 0))
ans += " ";
ans += binary[i];
}
return ans;
}
case Format::Octal:
return QString("%1").arg(val, 1, 8, QChar('0')).toUpper();
case Format::Bytes:
return QString("%1").arg(bswap(val), 2 * sizeof(duint), 16, QChar('0')).toUpper();
}
}
CalculatorDialog::CalculatorDialog(QWidget* parent) : QDialog(parent), ui(new Ui::CalculatorDialog)
{
ui->setupUi(this);
setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint | Qt::MSWindowsFixedSizeDialogHint);
connect(this, SIGNAL(validAddress(bool)), ui->btnGoto, SLOT(setEnabled(bool)));
connect(this, SIGNAL(validAddress(bool)), ui->btnGotoDump, SLOT(setEnabled(bool)));
connect(this, SIGNAL(validAddress(bool)), ui->btnGotoMemoryMap, SLOT(setEnabled(bool)));
emit validAddress(false);
ui->txtBytes->setInputMask(QString("HH").repeated(sizeof(duint)));
ui->txtBin->setInputMask(QString("bbbb ").repeated(sizeof(duint) * 2).trimmed());
ui->txtExpression->setText("0");
ui->txtExpression->selectAll();
ui->txtExpression->setFocus();
mValidateThread = new ValidateExpressionThread(this);
mValidateThread->setOnExpressionChangedCallback(std::bind(&CalculatorDialog::validateExpression, this, std::placeholders::_1));
connect(mValidateThread, SIGNAL(expressionChanged(bool, bool, dsint)), this, SLOT(expressionChanged(bool, bool, dsint)));
connect(ui->txtExpression, SIGNAL(textChanged(QString)), mValidateThread, SLOT(textChanged(QString)));
}
CalculatorDialog::~CalculatorDialog()
{
mValidateThread->stop();
mValidateThread->wait();
delete ui;
}
void CalculatorDialog::validateExpression(QString expression)
{
duint value;
bool validExpression = DbgFunctions()->ValFromString(expression.toUtf8().constData(), &value);
bool validPointer = validExpression && DbgMemIsValidReadPtr(value);
this->mValidateThread->emitExpressionChanged(validExpression, validPointer, value);
}
void CalculatorDialog::setExpressionFocus()
{
ui->txtExpression->selectAll();
ui->txtExpression->setFocus();
}
void CalculatorDialog::showEvent(QShowEvent* event)
{
Q_UNUSED(event);
mValidateThread->start();
}
void CalculatorDialog::hideEvent(QHideEvent* event)
{
Q_UNUSED(event);
mValidateThread->stop();
mValidateThread->wait();
}
void CalculatorDialog::expressionChanged(bool validExpression, bool validPointer, dsint value)
{
if(!validExpression)
{
ui->txtHex->setText("");
ui->txtSignedDec->setText("");
ui->txtUnsignedDec->setText("");
ui->txtOct->setText("");
ui->txtBytes->setText("");
ui->txtBin->setText("");
ui->txtAscii->setText("");
ui->txtUnicode->setText("");
ui->txtExpression->setStyleSheet("border: 2px solid red");
emit validAddress(false);
}
else
{
ui->txtExpression->setStyleSheet("");
ui->txtHex->setText(inFormat(value, Format::Hex));
ui->txtSignedDec->setText(inFormat(value, Format::SignedDec));
ui->txtUnsignedDec->setText(inFormat(value, Format::UnsignedDec));
ui->txtOct->setText(inFormat(value, Format::Octal));
{
int cursorpos = ui->txtBytes->cursorPosition();
ui->txtBytes->setText(inFormat(value, Format::Bytes));
ui->txtBytes->setCursorPosition(cursorpos);
}
{
int cursorpos = ui->txtBin->cursorPosition();
ui->txtBin->setText(inFormat(value, Format::Binary));
ui->txtBin->setCursorPosition(cursorpos);
}
if(value == (value & 0xFF))
{
QChar c((ushort)value);
if(c.isPrint())
ui->txtAscii->setText(QString(c));
else
ui->txtAscii->setText("???");
}
else
ui->txtAscii->setText("???");
ui->txtAscii->setCursorPosition(0);
ui->txtAscii->selectAll();
if((value == (value & 0xFFFF))) //UNICODE?
{
QChar c = QChar((ushort)value);
if(c.isPrint())
ui->txtUnicode->setText(QString(c));
else
ui->txtUnicode->setText("????");
}
else
{
ui->txtUnicode->setText("????");
}
ui->txtUnicode->setCursorPosition(0);
ui->txtUnicode->selectAll();
emit validAddress(validPointer);
}
}
void CalculatorDialog::on_txtExpression_textChanged(const QString & arg1)
{
Q_UNUSED(arg1);
ui->txtHex->setStyleSheet("");
ui->txtSignedDec->setStyleSheet("");
ui->txtUnsignedDec->setStyleSheet("");
ui->txtOct->setStyleSheet("");
ui->txtBytes->setStyleSheet("");
ui->txtBin->setStyleSheet("");
ui->txtAscii->setStyleSheet("");
ui->txtUnicode->setStyleSheet("");
emit validAddress(false);
}
void CalculatorDialog::on_txtHex_textEdited(const QString & arg1)
{
bool ok = false;
ULONGLONG val = arg1.toULongLong(&ok, 16);
if(!ok)
{
ui->txtHex->setStyleSheet("border: 2px solid red");
return;
}
ui->txtHex->setStyleSheet("");
ui->txtExpression->setText(QString("%1").arg(val, 1, 16, QChar('0')).toUpper());
}
void CalculatorDialog::on_txtSignedDec_textEdited(const QString & arg1)
{
bool ok = false;
LONGLONG val = arg1.toLongLong(&ok, 10);
if(!ok)
{
ui->txtUnsignedDec->setStyleSheet("border: 2px solid red");
return;
}
ui->txtUnsignedDec->setStyleSheet("");
ui->txtExpression->setText(QString("%1").arg(val, 1, 16, QChar('0')).toUpper());
}
void CalculatorDialog::on_txtUnsignedDec_textEdited(const QString & arg1)
{
bool ok = false;
LONGLONG val = arg1.toULongLong(&ok, 10);
if(!ok)
{
ui->txtUnsignedDec->setStyleSheet("border: 2px solid red");
return;
}
ui->txtUnsignedDec->setStyleSheet("");
ui->txtExpression->setText(QString("%1").arg(val, 1, 16, QChar('0')).toUpper());
}
void CalculatorDialog::on_txtOct_textEdited(const QString & arg1)
{
bool ok = false;
ULONGLONG val = arg1.toULongLong(&ok, 8);
if(!ok)
{
ui->txtOct->setStyleSheet("border: 2px solid red");
return;
}
ui->txtOct->setStyleSheet("");
ui->txtExpression->setText(QString("%1").arg(val, 1, 16, QChar('0')).toUpper());
}
void CalculatorDialog::on_txtBytes_textEdited(const QString & arg1)
{
bool ok = false;
QString text = arg1;
text = text.leftJustified(sizeof(duint) * 2, '0', true);
ULONGLONG val = text.toULongLong(&ok, 16);
if(!ok)
{
ui->txtBytes->setStyleSheet("border: 2px solid red");
return;
}
ui->txtBytes->setStyleSheet("");
ui->txtExpression->setText(QString("%1").arg(bswap(val), 1, 16, QChar('0')).toUpper());
}
void CalculatorDialog::on_txtBin_textEdited(const QString & arg1)
{
bool ok = false;
QString text = arg1;
text = text.replace(" ", "").leftJustified(sizeof(duint) * 8, '0', true);
ULONGLONG val = text.toULongLong(&ok, 2);
if(!ok)
{
ui->txtBin->setStyleSheet("border: 2px solid red");
return;
}
ui->txtBin->setStyleSheet("");
ui->txtExpression->setText(QString("%1").arg(val, 1, 16, QChar('0')).toUpper());
}
void CalculatorDialog::on_txtAscii_textEdited(const QString & arg1)
{
QString text = arg1;
ui->txtAscii->setStyleSheet("");
ui->txtExpression->setText(QString().sprintf("%X", text[0].unicode()));
ui->txtAscii->setCursorPosition(0);
ui->txtAscii->selectAll();
}
void CalculatorDialog::on_txtUnicode_textEdited(const QString & arg1)
{
QString text = arg1;
ui->txtUnicode->setStyleSheet("");
ui->txtExpression->setText(QString().sprintf("%X", text[0].unicode()));
ui->txtUnicode->setCursorPosition(0);
ui->txtUnicode->selectAll();
}
void CalculatorDialog::on_btnGoto_clicked()
{
DbgCmdExecDirect(QString("disasm " + ui->txtHex->text()));
}
void CalculatorDialog::on_btnGotoDump_clicked()
{
DbgCmdExecDirect(QString("dump " + ui->txtHex->text()));
}
void CalculatorDialog::on_btnGotoMemoryMap_clicked()
{
DbgCmdExecDirect(QString("memmapdump " + ui->txtHex->text()));
} |
C/C++ | x64dbg-development/src/gui/Src/Gui/CalculatorDialog.h | #pragma once
#include <QDialog>
#include "Imports.h"
class ValidateExpressionThread;
namespace Ui
{
class CalculatorDialog;
}
class CalculatorDialog : public QDialog
{
Q_OBJECT
enum class Format
{
Unknown = 0,
Hex,
SignedDec,
UnsignedDec,
Octal,
Bytes,
Binary,
};
QString inFormat(const duint val, CalculatorDialog::Format format) const;
public:
explicit CalculatorDialog(QWidget* parent = 0);
~CalculatorDialog();
void validateExpression(QString expression);
void setExpressionFocus();
void showEvent(QShowEvent* event);
void hideEvent(QHideEvent* event);
signals:
bool validAddress(bool valid);
private slots:
void expressionChanged(bool validExpression, bool validPointer, dsint value);
void on_txtExpression_textChanged(const QString & arg1);
void on_txtHex_textEdited(const QString & arg1);
void on_txtSignedDec_textEdited(const QString & arg1);
void on_txtUnsignedDec_textEdited(const QString & arg1);
void on_txtOct_textEdited(const QString & arg1);
void on_txtBytes_textEdited(const QString & arg1);
void on_txtBin_textEdited(const QString & arg1);
void on_txtAscii_textEdited(const QString & arg1);
void on_txtUnicode_textEdited(const QString & arg1);
void on_btnGoto_clicked();
void on_btnGotoDump_clicked();
void on_btnGotoMemoryMap_clicked();
private:
ValidateExpressionThread* mValidateThread;
Ui::CalculatorDialog* ui;
}; |
User Interface | x64dbg-development/src/gui/Src/Gui/CalculatorDialog.ui | <?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>CalculatorDialog</class>
<widget class="QDialog" name="CalculatorDialog">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>502</width>
<height>279</height>
</rect>
</property>
<property name="sizePolicy">
<sizepolicy hsizetype="Fixed" vsizetype="Fixed">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="windowTitle">
<string>Calculator</string>
</property>
<property name="windowIcon">
<iconset theme="calculator" resource="../../resource.qrc">
<normaloff>:/Default/icons/calculator.png</normaloff>:/Default/icons/calculator.png</iconset>
</property>
<layout class="QVBoxLayout" name="verticalLayout">
<item>
<layout class="QGridLayout" name="gridLayout">
<item row="2" column="0">
<widget class="QLabel" name="label_8">
<property name="text">
<string>Signed:</string>
</property>
<property name="buddy">
<cstring>txtSignedDec</cstring>
</property>
</widget>
</item>
<item row="3" column="0">
<widget class="QLabel" name="label_3">
<property name="text">
<string>Unsigned:</string>
</property>
<property name="buddy">
<cstring>txtUnsignedDec</cstring>
</property>
</widget>
</item>
<item row="10" column="0">
<widget class="QLabel" name="label_7">
<property name="text">
<string>Unicode:</string>
</property>
<property name="buddy">
<cstring>txtUnicode</cstring>
</property>
</widget>
</item>
<item row="5" column="0">
<widget class="QLabel" name="label_4">
<property name="text">
<string>Octal:</string>
</property>
<property name="buddy">
<cstring>txtOct</cstring>
</property>
</widget>
</item>
<item row="0" column="0">
<widget class="QLabel" name="label">
<property name="text">
<string>Expression:</string>
</property>
<property name="buddy">
<cstring>txtExpression</cstring>
</property>
</widget>
</item>
<item row="2" column="1">
<widget class="QLineEdit" name="txtSignedDec">
<property name="sizePolicy">
<sizepolicy hsizetype="Expanding" vsizetype="Preferred">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="font">
<font>
<family>Courier New</family>
</font>
</property>
<property name="readOnly">
<bool>false</bool>
</property>
</widget>
</item>
<item row="3" column="1">
<widget class="QLineEdit" name="txtUnsignedDec">
<property name="sizePolicy">
<sizepolicy hsizetype="Expanding" vsizetype="Preferred">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="font">
<font>
<family>Courier New</family>
</font>
</property>
<property name="readOnly">
<bool>false</bool>
</property>
</widget>
</item>
<item row="7" column="0">
<widget class="QLabel" name="label_5">
<property name="text">
<string>Binary:</string>
</property>
<property name="buddy">
<cstring>txtBin</cstring>
</property>
</widget>
</item>
<item row="9" column="0">
<widget class="QLabel" name="label_6">
<property name="text">
<string>ASCII:</string>
</property>
<property name="buddy">
<cstring>txtAscii</cstring>
</property>
</widget>
</item>
<item row="1" column="1">
<widget class="QLineEdit" name="txtHex">
<property name="sizePolicy">
<sizepolicy hsizetype="Expanding" vsizetype="Preferred">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="font">
<font>
<family>Courier New</family>
</font>
</property>
<property name="readOnly">
<bool>false</bool>
</property>
</widget>
</item>
<item row="7" column="1">
<widget class="QLineEdit" name="txtBin">
<property name="sizePolicy">
<sizepolicy hsizetype="Expanding" vsizetype="Preferred">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="font">
<font>
<family>Lucida Console</family>
<pointsize>7</pointsize>
</font>
</property>
<property name="text">
<string>0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000</string>
</property>
<property name="readOnly">
<bool>false</bool>
</property>
</widget>
</item>
<item row="5" column="1">
<widget class="QLineEdit" name="txtOct">
<property name="sizePolicy">
<sizepolicy hsizetype="Expanding" vsizetype="Preferred">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="font">
<font>
<family>Courier New</family>
</font>
</property>
<property name="readOnly">
<bool>false</bool>
</property>
</widget>
</item>
<item row="10" column="1">
<widget class="QLineEdit" name="txtUnicode">
<property name="sizePolicy">
<sizepolicy hsizetype="Expanding" vsizetype="Preferred">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="font">
<font>
<family>Courier New</family>
</font>
</property>
<property name="inputMask">
<string/>
</property>
<property name="maxLength">
<number>1</number>
</property>
<property name="readOnly">
<bool>false</bool>
</property>
</widget>
</item>
<item row="9" column="1">
<widget class="QLineEdit" name="txtAscii">
<property name="sizePolicy">
<sizepolicy hsizetype="Expanding" vsizetype="Preferred">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="font">
<font>
<family>Courier New</family>
</font>
</property>
<property name="inputMask">
<string/>
</property>
<property name="maxLength">
<number>1</number>
</property>
<property name="readOnly">
<bool>false</bool>
</property>
</widget>
</item>
<item row="1" column="0">
<widget class="QLabel" name="label_2">
<property name="text">
<string>Hexadecimal:</string>
</property>
<property name="buddy">
<cstring>txtHex</cstring>
</property>
</widget>
</item>
<item row="0" column="1">
<widget class="QLineEdit" name="txtExpression">
<property name="sizePolicy">
<sizepolicy hsizetype="Expanding" vsizetype="Preferred">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="font">
<font>
<family>Courier New</family>
</font>
</property>
</widget>
</item>
<item row="6" column="1">
<widget class="QLineEdit" name="txtBytes">
<property name="font">
<font>
<family>Courier New</family>
<pointsize>8</pointsize>
</font>
</property>
<property name="text">
<string>0000000000000000</string>
</property>
<property name="cursorPosition">
<number>0</number>
</property>
</widget>
</item>
<item row="6" column="0">
<widget class="QLabel" name="label_9">
<property name="text">
<string>Bytes:</string>
</property>
<property name="buddy">
<cstring>txtBytes</cstring>
</property>
</widget>
</item>
</layout>
</item>
<item>
<layout class="QHBoxLayout" name="horizontalLayout">
<item>
<widget class="QPushButton" name="btnGoto">
<property name="text">
<string>&Follow in Disassembler</string>
</property>
</widget>
</item>
<item>
<widget class="QPushButton" name="btnGotoDump">
<property name="text">
<string>Follow in &Dump</string>
</property>
</widget>
</item>
<item>
<widget class="QPushButton" name="btnGotoMemoryMap">
<property name="text">
<string>Follow in Memory Map</string>
</property>
</widget>
</item>
<item>
<spacer name="horizontalSpacer">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>40</width>
<height>20</height>
</size>
</property>
</spacer>
</item>
<item>
<widget class="QPushButton" name="btnClose">
<property name="text">
<string>&Close</string>
</property>
</widget>
</item>
</layout>
</item>
</layout>
</widget>
<tabstops>
<tabstop>txtExpression</tabstop>
<tabstop>txtHex</tabstop>
<tabstop>txtSignedDec</tabstop>
<tabstop>txtUnsignedDec</tabstop>
<tabstop>txtOct</tabstop>
<tabstop>txtBytes</tabstop>
<tabstop>txtBin</tabstop>
<tabstop>txtAscii</tabstop>
<tabstop>txtUnicode</tabstop>
<tabstop>btnGoto</tabstop>
<tabstop>btnGotoDump</tabstop>
<tabstop>btnGotoMemoryMap</tabstop>
<tabstop>btnClose</tabstop>
</tabstops>
<resources>
<include location="../../resource.qrc"/>
</resources>
<connections>
<connection>
<sender>btnClose</sender>
<signal>clicked()</signal>
<receiver>CalculatorDialog</receiver>
<slot>accept()</slot>
<hints>
<hint type="sourcelabel">
<x>491</x>
<y>268</y>
</hint>
<hint type="destinationlabel">
<x>284</x>
<y>215</y>
</hint>
</hints>
</connection>
</connections>
</ui> |
C++ | x64dbg-development/src/gui/Src/Gui/CallStackView.cpp | #include "CallStackView.h"
#include "CommonActions.h"
#include "Bridge.h"
CallStackView::CallStackView(StdTable* parent) : StdIconTable(parent)
{
int charwidth = getCharWidth();
addColumnAt(8 * charwidth, tr("Thread ID"), false);
addColumnAt(8 + charwidth * sizeof(dsint) * 2, tr("Address"), false); //address in the stack
addColumnAt(8 + charwidth * sizeof(dsint) * 2, tr("To"), false); //return to
addColumnAt(8 + charwidth * sizeof(dsint) * 2, tr("From"), false); //return from
addColumnAt(8 + charwidth * sizeof(dsint) * 2, tr("Size"), false); //size
addColumnAt(9 * charwidth, tr("Party"), false); //party
addColumnAt(50 * charwidth, tr("Comment"), false);
setIconColumn(ColParty);
loadColumnFromConfig("CallStack");
connect(Bridge::getBridge(), SIGNAL(updateCallStack()), this, SLOT(updateCallStack()));
connect(this, SIGNAL(contextMenuSignal(QPoint)), this, SLOT(contextMenuSlot(QPoint)));
connect(this, SIGNAL(doubleClickedSignal()), this, SLOT(followFrom()));
setupContextMenu();
}
void CallStackView::setupContextMenu()
{
mMenuBuilder = new MenuBuilder(this, [](QMenu*)
{
return DbgIsDebugging();
});
mCommonActions = new CommonActions(this, getActionHelperFuncs(), [this]()
{
return getSelectionVa();
});
QIcon icon = DIcon(ArchValue("processor32", "processor64"));
mMenuBuilder->addAction(makeAction(icon, tr("Follow &Address"), SLOT(followAddress())), [this](QMenu*)
{
return isSelectionValid();
});
mMenuBuilder->addAction(makeAction(icon, tr("Follow &To"), SLOT(followTo())), [this](QMenu*)
{
return isSelectionValid();
});
QAction* mFollowFrom = mMenuBuilder->addAction(makeAction(icon, tr("Follow &From"), SLOT(followFrom())), [this](QMenu*)
{
return !getCellContent(getInitialSelection(), ColFrom).isEmpty() && isSelectionValid();
});
mFollowFrom->setShortcutContext(Qt::WidgetShortcut);
mFollowFrom->setShortcut(QKeySequence("enter"));
connect(this, SIGNAL(enterPressedSignal()), this, SLOT(followFrom()));
// Breakpoint menu
// TODO: Is Label/Comment/Bookmark useful?
mCommonActions->build(mMenuBuilder, CommonActions::ActionBreakpoint);
mMenuBuilder->addSeparator();
QAction* wShowSuspectedCallStack = makeAction(tr("Show Suspected Call Stack Frame"), SLOT(showSuspectedCallStack()));
mMenuBuilder->addAction(wShowSuspectedCallStack, [wShowSuspectedCallStack](QMenu*)
{
duint i;
if(!BridgeSettingGetUint("Engine", "ShowSuspectedCallStack", &i))
i = 0;
if(i != 0)
wShowSuspectedCallStack->setText(tr("Show Active Call Stack Frame"));
else
wShowSuspectedCallStack->setText(tr("Show Suspected Call Stack Frame"));
return true;
});
MenuBuilder* mCopyMenu = new MenuBuilder(this);
setupCopyMenu(mCopyMenu);
// Column count cannot be zero
mMenuBuilder->addSeparator();
mMenuBuilder->addMenu(makeMenu(DIcon("copy"), tr("&Copy")), mCopyMenu);
mMenuBuilder->loadFromConfig();
}
QString CallStackView::paintContent(QPainter* painter, dsint rowBase, int rowOffset, int col, int x, int y, int w, int h)
{
if(isSelected(rowBase, rowOffset))
painter->fillRect(QRect(x, y, w, h), QBrush(mSelectionColor));
bool isSpaceRow = !getCellContent(rowBase + rowOffset, ColThread).isEmpty();
if(col == ColThread && !(rowBase + rowOffset))
{
QString ret = getCellContent(rowBase + rowOffset, col);
if(!ret.isEmpty())
{
painter->fillRect(QRect(x, y, w, h), QBrush(ConfigColor("ThreadCurrentBackgroundColor")));
painter->setPen(QPen(ConfigColor("ThreadCurrentColor")));
painter->drawText(QRect(x + 4, y, w - 4, h), Qt::AlignVCenter | Qt::AlignLeft, ret);
}
return "";
}
else if(col > ColThread && isSpaceRow)
{
auto mid = h / 2.0;
painter->drawLine(QPointF(x, y + mid), QPointF(x + w, y + mid));
}
else if(col == ColFrom || col == ColTo || col == ColAddress)
{
QString ret = getCellContent(rowBase + rowOffset, col);
BPXTYPE bpxtype = DbgGetBpxTypeAt(getCellUserdata(rowBase + rowOffset, col));
if(bpxtype & bp_normal)
{
painter->fillRect(QRect(x, y, w, h), QBrush(ConfigColor("DisassemblyBreakpointBackgroundColor")));
painter->setPen(QPen(ConfigColor("DisassemblyBreakpointColor")));
painter->drawText(QRect(x + 4, y, w - 4, h), Qt::AlignVCenter | Qt::AlignLeft, ret);
return "";
}
else if(bpxtype & bp_hardware)
{
painter->fillRect(QRect(x, y, w, h), QBrush(ConfigColor("DisassemblyHardwareBreakpointBackgroundColor")));
painter->setPen(QPen(ConfigColor("DisassemblyHardwareBreakpointColor")));
painter->drawText(QRect(x + 4, y, w - 4, h), Qt::AlignVCenter | Qt::AlignLeft, ret);
return "";
}
}
return StdIconTable::paintContent(painter, rowBase, rowOffset, col, x, y, w, h);
}
void CallStackView::updateCallStack()
{
if(!DbgFunctions()->GetCallStackByThread)
return;
THREADLIST threadList;
memset(&threadList, 0, sizeof(THREADLIST));
DbgGetThreadList(&threadList);
int currentRow = 0;
int currentIndexToDraw = 0;
setRowCount(0);
for(int j = 0; j < threadList.count; j++)
{
if(!j)
currentIndexToDraw = threadList.CurrentThread; // Draw the current thread first
else if(j == threadList.CurrentThread)
currentIndexToDraw = 0; // Draw the previously skipped thread
else
currentIndexToDraw = j;
DBGCALLSTACK callstack;
memset(&callstack, 0, sizeof(DBGCALLSTACK));
DbgFunctions()->GetCallStackByThread(threadList.list[currentIndexToDraw].BasicInfo.Handle, &callstack);
setRowCount(currentRow + callstack.total + 1);
setCellContent(currentRow, ColThread, ToDecString(threadList.list[currentIndexToDraw].BasicInfo.ThreadId));
currentRow++;
for(int i = 0; i < callstack.total; i++, currentRow++)
{
QString addrText = ToPtrString(callstack.entries[i].addr);
setCellContent(currentRow, ColAddress, addrText);
addrText = ToPtrString(callstack.entries[i].to);
setCellContent(currentRow, ColTo, addrText);
if(callstack.entries[i].from)
{
addrText = ToPtrString(callstack.entries[i].from);
setCellContent(currentRow, ColFrom, addrText);
}
setCellUserdata(currentRow, ColFrom, callstack.entries[i].from);
setCellUserdata(currentRow, ColTo, callstack.entries[i].to);
setCellUserdata(currentRow, ColAddress, callstack.entries[i].addr);
if(i != callstack.total - 1)
setCellContent(currentRow, ColSize, ToHexString(callstack.entries[i + 1].addr - callstack.entries[i].addr));
else
setCellContent(currentRow, ColSize, "");
setCellContent(currentRow, ColComment, callstack.entries[i].comment);
int party = DbgFunctions()->ModGetParty(callstack.entries[i].to);
switch(party)
{
case mod_user:
setCellContent(currentRow, ColParty, tr("User"));
setRowIcon(currentRow, DIcon("markasuser"));
break;
case mod_system:
setCellContent(currentRow, ColParty, tr("System"));
setRowIcon(currentRow, DIcon("markassystem"));
break;
default:
setCellContent(currentRow, ColParty, QString::number(party));
setRowIcon(currentRow, DIcon("markasparty"));
break;
}
}
if(callstack.total)
BridgeFree(callstack.entries);
}
if(threadList.count)
BridgeFree(threadList.list);
reloadData();
}
void CallStackView::contextMenuSlot(const QPoint pos)
{
QMenu wMenu(this); //create context menu
mMenuBuilder->build(&wMenu);
if(!wMenu.isEmpty())
wMenu.exec(mapToGlobal(pos)); //execute context menu
}
void CallStackView::followAddress()
{
QString addrText = getCellContent(getInitialSelection(), ColAddress);
DbgCmdExecDirect(QString("sdump " + addrText));
}
void CallStackView::followTo()
{
QString addrText = getCellContent(getInitialSelection(), ColTo);
DbgCmdExecDirect(QString("disasm " + addrText));
}
void CallStackView::followFrom()
{
QString addrText = getCellContent(getInitialSelection(), ColFrom);
DbgCmdExecDirect(QString("disasm " + addrText));
}
void CallStackView::showSuspectedCallStack()
{
duint i;
if(!BridgeSettingGetUint("Engine", "ShowSuspectedCallStack", &i))
i = 0;
i = (i == 0) ? 1 : 0;
BridgeSettingSetUint("Engine", "ShowSuspectedCallStack", i);
DbgSettingsUpdated();
updateCallStack();
emit Bridge::getBridge()->updateDump();
}
bool CallStackView::isSelectionValid()
{
return getCellContent(getInitialSelection(), ColThread).isEmpty();
}
// For breakpoint/run to selection
duint CallStackView::getSelectionVa()
{
if(isSelectionValid())
return getCellUserdata(getInitialSelection(), ColFrom);
else
return 0;
} |
C/C++ | x64dbg-development/src/gui/Src/Gui/CallStackView.h | #pragma once
#include "StdIconTable.h"
class CommonActions;
class CallStackView : public StdIconTable
{
Q_OBJECT
public:
explicit CallStackView(StdTable* parent = 0);
void setupContextMenu();
duint getSelectionVa();
protected:
QString paintContent(QPainter* painter, dsint rowBase, int rowOffset, int col, int x, int y, int w, int h) override;
protected slots:
void updateCallStack();
void contextMenuSlot(const QPoint pos);
void followAddress();
void followTo();
void followFrom();
void showSuspectedCallStack();
private:
enum
{
ColThread = 0,
ColAddress,
ColTo,
ColFrom,
ColSize,
ColParty,
ColComment
};
MenuBuilder* mMenuBuilder;
CommonActions* mCommonActions;
bool isSelectionValid();
}; |
C++ | x64dbg-development/src/gui/Src/Gui/CloseDialog.cpp | #include "CloseDialog.h"
#include "ui_CloseDialog.h"
#include "MiscUtil.h"
#include <QCloseEvent>
CloseDialog::CloseDialog(QWidget* parent) : QDialog(parent), ui(new Ui::CloseDialog)
{
ui->setupUi(this);
setModal(true);
setWindowFlags(windowFlags() & ~(Qt::WindowContextHelpButtonHint | Qt::WindowCloseButtonHint) | Qt::MSWindowsFixedSizeDialogHint);
SetApplicationIcon(QDialog::winId());
bCanClose = false;
// Resize window
int requiredWidth = ui->label->fontMetrics().boundingRect(ui->label->text()).width();
if(width() < requiredWidth)
resize(requiredWidth, height());
}
CloseDialog::~CloseDialog()
{
delete ui;
}
void CloseDialog::allowClose()
{
bCanClose = true;
}
void CloseDialog::closeEvent(QCloseEvent* event)
{
if(bCanClose)
event->accept();
else
event->ignore();
} |
C/C++ | x64dbg-development/src/gui/Src/Gui/CloseDialog.h | #pragma once
#include <QDialog>
class QCloseEvent;
namespace Ui
{
class CloseDialog;
}
class CloseDialog : public QDialog
{
Q_OBJECT
public:
explicit CloseDialog(QWidget* parent = 0);
~CloseDialog();
void closeEvent(QCloseEvent* event);
void allowClose();
private:
Ui::CloseDialog* ui;
bool bCanClose;
}; |
User Interface | x64dbg-development/src/gui/Src/Gui/CloseDialog.ui | <?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>CloseDialog</class>
<widget class="QDialog" name="CloseDialog">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>220</width>
<height>80</height>
</rect>
</property>
<property name="windowTitle">
<string/>
</property>
<layout class="QHBoxLayout" name="horizontalLayout">
<item>
<widget class="QLabel" name="label">
<property name="text">
<string>Closing Debugger...</string>
</property>
<property name="alignment">
<set>Qt::AlignCenter</set>
</property>
</widget>
</item>
</layout>
</widget>
<resources/>
<connections/>
</ui> |
C++ | x64dbg-development/src/gui/Src/Gui/CodepageSelectionDialog.cpp | #include "CodepageSelectionDialog.h"
#include "ui_CodepageSelectionDialog.h"
#include "Bridge.h"
#include <QTextCodec>
#include "MiscUtil.h"
CodepageSelectionDialog::CodepageSelectionDialog(QWidget* parent) :
QDialog(parent),
ui(new Ui::CodepageSelectionDialog)
{
ui->setupUi(this);
setModal(true);
setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint | Qt::MSWindowsFixedSizeDialogHint);
setWindowIcon(DIcon("codepage"));
for(auto & name : QTextCodec::availableCodecs())
{
auto codec = QTextCodec::codecForName(name);
if(!codec)
continue;
ui->listCodepages->addItem(name);
mCodepages.append(codec->name());
}
duint setting;
if(BridgeSettingGetUint("Misc", "LastCodepage", &setting) && setting < duint(ui->listCodepages->count()))
ui->listCodepages->setCurrentRow(setting);
else
ui->listCodepages->setCurrentRow(0);
}
CodepageSelectionDialog::~CodepageSelectionDialog()
{
BridgeSettingSetUint("Misc", "LastCodepage", ui->listCodepages->currentRow());
delete ui;
}
QByteArray CodepageSelectionDialog::getSelectedCodepage()
{
return mCodepages[ui->listCodepages->currentRow()];
} |
C/C++ | x64dbg-development/src/gui/Src/Gui/CodepageSelectionDialog.h | #pragma once
#include <QDialog>
namespace Ui
{
class CodepageSelectionDialog;
}
class CodepageSelectionDialog : public QDialog
{
Q_OBJECT
public:
explicit CodepageSelectionDialog(QWidget* parent = 0);
~CodepageSelectionDialog();
QByteArray getSelectedCodepage();
private:
Ui::CodepageSelectionDialog* ui;
QList<QByteArray> mCodepages;
}; |
User Interface | x64dbg-development/src/gui/Src/Gui/CodepageSelectionDialog.ui | <?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>CodepageSelectionDialog</class>
<widget class="QDialog" name="CodepageSelectionDialog">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>396</width>
<height>300</height>
</rect>
</property>
<property name="windowTitle">
<string>Select Codepage...</string>
</property>
<layout class="QVBoxLayout" name="verticalLayout">
<item>
<widget class="QListWidget" name="listCodepages"/>
</item>
<item>
<layout class="QHBoxLayout" name="horizontalLayout">
<item>
<spacer name="horizontalSpacer">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>40</width>
<height>20</height>
</size>
</property>
</spacer>
</item>
<item>
<widget class="QPushButton" name="buttonOk">
<property name="text">
<string>&OK</string>
</property>
<property name="default">
<bool>true</bool>
</property>
</widget>
</item>
<item>
<widget class="QPushButton" name="buttonCancel">
<property name="text">
<string>&Cancel</string>
</property>
</widget>
</item>
</layout>
</item>
</layout>
</widget>
<resources/>
<connections>
<connection>
<sender>buttonOk</sender>
<signal>clicked()</signal>
<receiver>CodepageSelectionDialog</receiver>
<slot>accept()</slot>
<hints>
<hint type="sourcelabel">
<x>257</x>
<y>280</y>
</hint>
<hint type="destinationlabel">
<x>204</x>
<y>273</y>
</hint>
</hints>
</connection>
<connection>
<sender>buttonCancel</sender>
<signal>clicked()</signal>
<receiver>CodepageSelectionDialog</receiver>
<slot>reject()</slot>
<hints>
<hint type="sourcelabel">
<x>340</x>
<y>283</y>
</hint>
<hint type="destinationlabel">
<x>93</x>
<y>279</y>
</hint>
</hints>
</connection>
</connections>
</ui> |
C++ | x64dbg-development/src/gui/Src/Gui/ColumnReorderDialog.cpp | #include "ColumnReorderDialog.h"
#include "ui_ColumnReorderDialog.h"
#include "AbstractTableView.h"
#include <QMessageBox>
ColumnReorderDialog::ColumnReorderDialog(AbstractTableView* parent) :
QDialog(parent),
mParent(parent),
ui(new Ui::ColumnReorderDialog)
{
ui->setupUi(this);
setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint | Qt::MSWindowsFixedSizeDialogHint);
for(int j = 0; j < parent->getColumnCount(); j++)
{
int i = parent->mColumnOrder[j];
if(parent->getColumnHidden(i))
{
ui->listAvailable->addItem(parent->getColTitle(i));
ui->listAvailable->item(ui->listAvailable->count() - 1)->setData(Qt::UserRole, QVariant(i));
}
else
{
ui->listDisplayed->addItem(parent->getColTitle(i));
ui->listDisplayed->item(ui->listDisplayed->count() - 1)->setData(Qt::UserRole, QVariant(i));
}
}
if(ui->listAvailable->count() == 0)
{
ui->addAllButton->setEnabled(false);
ui->addButton->setEnabled(false);
}
else
ui->listAvailable->setCurrentRow(0);
if(ui->listDisplayed->count())
ui->listDisplayed->setCurrentRow(0);
}
ColumnReorderDialog::~ColumnReorderDialog()
{
delete ui;
}
void ColumnReorderDialog::on_okButton_clicked()
{
int i = 0;
if(ui->listDisplayed->count() == 0)
{
QMessageBox msg(QMessageBox::Warning, tr("Error"), tr("There isn't anything to display yet!"));
msg.setWindowIcon(DIcon("compile-error"));
msg.exec();
return;
}
for(i = 0; i < ui->listDisplayed->count(); i++)
{
int col = ui->listDisplayed->item(i)->data(Qt::UserRole).toInt();
mParent->mColumnOrder[i] = col;
mParent->setColumnHidden(col, false);
}
for(int j = 0; j < ui->listAvailable->count(); j++, i++)
{
int col = ui->listAvailable->item(j)->data(Qt::UserRole).toInt();
mParent->mColumnOrder[i] = col;
mParent->setColumnHidden(col, true);
}
this->done(QDialog::Accepted);
}
void ColumnReorderDialog::on_addButton_clicked()
{
if(ui->listAvailable->selectedItems().empty())
return;
auto selected = ui->listAvailable->selectedItems();
for(auto i : selected)
{
ui->listDisplayed->addItem(i->text());
ui->listDisplayed->item(ui->listDisplayed->count() - 1)->setData(Qt::UserRole, i->data(Qt::UserRole));
delete i;
}
if(ui->listAvailable->count() == 0)
{
ui->addAllButton->setEnabled(false);
ui->addButton->setEnabled(false);
}
}
void ColumnReorderDialog::on_addAllButton_clicked()
{
for(int i = 0; i < ui->listAvailable->count(); i++)
{
ui->listDisplayed->addItem(ui->listAvailable->item(i)->text());
ui->listDisplayed->item(ui->listDisplayed->count() - 1)->setData(Qt::UserRole, ui->listAvailable->item(i)->data(Qt::UserRole));
}
ui->listAvailable->clear();
ui->addAllButton->setEnabled(false);
ui->addButton->setEnabled(false);
}
void ColumnReorderDialog::on_upButton_clicked()
{
if(ui->listDisplayed->selectedItems().empty())
return;
auto i = ui->listDisplayed->currentIndex().row();
if(i != 0)
{
auto prevItem = ui->listDisplayed->item(i - 1);
auto currentItem = ui->listDisplayed->item(i);
QString text = prevItem->text();
auto data = prevItem->data(Qt::UserRole);
prevItem->setText(currentItem->text());
prevItem->setData(Qt::UserRole, currentItem->data(Qt::UserRole));
currentItem->setText(text);
currentItem->setData(Qt::UserRole, data);
ui->listDisplayed->setCurrentRow(i - 1);
}
}
void ColumnReorderDialog::on_downButton_clicked()
{
if(ui->listDisplayed->selectedItems().empty())
return;
auto i = ui->listDisplayed->currentIndex().row();
if(i != ui->listDisplayed->count() - 1)
{
auto nextItem = ui->listDisplayed->item(i + 1);
auto currentItem = ui->listDisplayed->item(i);
QString text = nextItem->text();
auto data = nextItem->data(Qt::UserRole);
nextItem->setText(currentItem->text());
nextItem->setData(Qt::UserRole, currentItem->data(Qt::UserRole));
currentItem->setText(text);
currentItem->setData(Qt::UserRole, data);
ui->listDisplayed->setCurrentRow(i + 1);
}
}
void ColumnReorderDialog::on_hideButton_clicked()
{
if(ui->listDisplayed->selectedItems().empty())
return;
auto currentItem = ui->listDisplayed->currentItem();
ui->listAvailable->addItem(currentItem->text());
ui->listAvailable->item(ui->listAvailable->count() - 1)->setData(Qt::UserRole, currentItem->data(Qt::UserRole));
delete currentItem;
ui->addAllButton->setEnabled(true);
ui->addButton->setEnabled(true);
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.